CameraActivity.java revision 54985c973140b896db75f086ac0f904d0228f8aa
1/* 2 * Copyright (C) 2012 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 18package com.android.camera; 19 20import android.animation.Animator; 21import android.annotation.TargetApi; 22import android.app.ActionBar; 23import android.app.AlertDialog; 24import android.app.Dialog; 25import android.content.ActivityNotFoundException; 26import android.content.BroadcastReceiver; 27import android.content.ContentResolver; 28import android.content.Context; 29import android.content.Intent; 30import android.content.IntentFilter; 31import android.content.pm.ActivityInfo; 32import android.content.res.Configuration; 33import android.graphics.Bitmap; 34import android.graphics.BitmapFactory; 35import android.graphics.Matrix; 36import android.graphics.Point; 37import android.graphics.RectF; 38import android.graphics.SurfaceTexture; 39import android.graphics.drawable.ColorDrawable; 40import android.graphics.drawable.Drawable; 41import android.net.Uri; 42import android.nfc.NfcAdapter; 43import android.nfc.NfcAdapter.CreateBeamUrisCallback; 44import android.nfc.NfcEvent; 45import android.os.AsyncTask; 46import android.os.Build; 47import android.os.Bundle; 48import android.os.Handler; 49import android.os.HandlerThread; 50import android.os.Looper; 51import android.os.Message; 52import android.provider.MediaStore; 53import android.provider.Settings; 54import android.text.TextUtils; 55import android.util.CameraPerformanceTracker; 56import android.view.ContextMenu; 57import android.view.ContextMenu.ContextMenuInfo; 58import android.view.KeyEvent; 59import android.view.Menu; 60import android.view.MenuInflater; 61import android.view.MenuItem; 62import android.view.MotionEvent; 63import android.view.View; 64import android.view.View.OnSystemUiVisibilityChangeListener; 65import android.view.ViewGroup; 66import android.view.Window; 67import android.view.WindowManager; 68import android.widget.FrameLayout; 69import android.widget.ImageView; 70import android.widget.ShareActionProvider; 71 72import com.android.camera.app.AppController; 73import com.android.camera.app.CameraAppUI; 74import com.android.camera.app.CameraController; 75import com.android.camera.app.CameraProvider; 76import com.android.camera.app.CameraServices; 77import com.android.camera.app.LocationManager; 78import com.android.camera.app.MemoryManager; 79import com.android.camera.app.MemoryQuery; 80import com.android.camera.app.ModuleManager; 81import com.android.camera.app.ModuleManagerImpl; 82import com.android.camera.app.MotionManager; 83import com.android.camera.app.OrientationManager; 84import com.android.camera.app.OrientationManagerImpl; 85import com.android.camera.data.CameraDataAdapter; 86import com.android.camera.data.FixedLastDataAdapter; 87import com.android.camera.data.LocalData; 88import com.android.camera.data.LocalDataAdapter; 89import com.android.camera.data.LocalDataUtil; 90import com.android.camera.data.LocalDataViewType; 91import com.android.camera.data.LocalMediaData; 92import com.android.camera.data.LocalMediaObserver; 93import com.android.camera.data.LocalSessionData; 94import com.android.camera.data.MediaDetails; 95import com.android.camera.data.MetadataLoader; 96import com.android.camera.data.PanoramaMetadataLoader; 97import com.android.camera.data.RgbzMetadataLoader; 98import com.android.camera.data.SimpleViewData; 99import com.android.camera.debug.Log; 100import com.android.camera.filmstrip.FilmstripContentPanel; 101import com.android.camera.filmstrip.FilmstripController; 102import com.android.camera.hardware.HardwareSpec; 103import com.android.camera.hardware.HardwareSpecImpl; 104import com.android.camera.module.ModuleController; 105import com.android.camera.module.ModulesInfo; 106import com.android.camera.one.OneCameraException; 107import com.android.camera.one.OneCameraManager; 108import com.android.camera.session.CaptureSession; 109import com.android.camera.session.CaptureSessionManager; 110import com.android.camera.session.CaptureSessionManager.SessionListener; 111import com.android.camera.settings.AppUpgrader; 112import com.android.camera.settings.CameraSettingsActivity; 113import com.android.camera.settings.Keys; 114import com.android.camera.settings.SettingsManager; 115import com.android.camera.settings.SettingsUtil; 116import com.android.camera.tinyplanet.TinyPlanetFragment; 117import com.android.camera.ui.AbstractTutorialOverlay; 118import com.android.camera.ui.DetailsDialog; 119import com.android.camera.ui.MainActivityLayout; 120import com.android.camera.ui.ModeListView; 121import com.android.camera.ui.ModeListView.ModeListVisibilityChangedListener; 122import com.android.camera.ui.PreviewStatusListener; 123import com.android.camera.util.ApiHelper; 124import com.android.camera.util.Callback; 125import com.android.camera.util.CameraUtil; 126import com.android.camera.util.GalleryHelper; 127import com.android.camera.util.GcamHelper; 128import com.android.camera.util.GoogleHelpHelper; 129import com.android.camera.util.IntentHelper; 130import com.android.camera.util.PhotoSphereHelper.PanoramaViewHelper; 131import com.android.camera.util.QuickActivity; 132import com.android.camera.util.ReleaseHelper; 133import com.android.camera.util.UsageStatistics; 134import com.android.camera.widget.FilmstripView; 135import com.android.camera.widget.Preloader; 136import com.android.camera2.R; 137import com.android.ex.camera2.portability.CameraAgent; 138import com.android.ex.camera2.portability.CameraAgentFactory; 139import com.android.ex.camera2.portability.CameraExceptionHandler; 140import com.android.ex.camera2.portability.CameraSettings; 141import com.bumptech.glide.Glide; 142import com.bumptech.glide.GlideBuilder; 143import com.bumptech.glide.MemoryCategory; 144import com.bumptech.glide.load.engine.executor.FifoPriorityThreadPoolExecutor; 145import com.google.common.logging.eventprotos; 146import com.google.common.logging.eventprotos.ForegroundEvent.ForegroundSource; 147import com.google.common.logging.eventprotos.MediaInteraction; 148import com.google.common.logging.eventprotos.NavigationChange; 149 150import java.io.File; 151import java.io.FileInputStream; 152import java.io.FileNotFoundException; 153import java.lang.ref.WeakReference; 154import java.util.ArrayList; 155import java.util.HashMap; 156import java.util.List; 157import java.util.concurrent.TimeUnit; 158 159public class CameraActivity extends QuickActivity 160 implements AppController, CameraAgent.CameraOpenCallback, 161 ShareActionProvider.OnShareTargetSelectedListener, 162 OrientationManager.OnOrientationChangeListener { 163 164 private static final Log.Tag TAG = new Log.Tag("CameraActivity"); 165 166 private static final String INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE = 167 "android.media.action.STILL_IMAGE_CAMERA_SECURE"; 168 public static final String ACTION_IMAGE_CAPTURE_SECURE = 169 "android.media.action.IMAGE_CAPTURE_SECURE"; 170 171 // The intent extra for camera from secure lock screen. True if the gallery 172 // should only show newly captured pictures. sSecureAlbumId does not 173 // increment. This is used when switching between camera, camcorder, and 174 // panorama. If the extra is not set, it is in the normal camera mode. 175 public static final String SECURE_CAMERA_EXTRA = "secure_camera"; 176 177 public static final String MODULE_SCOPE_PREFIX = "_preferences_module_"; 178 public static final String CAMERA_SCOPE_PREFIX = "_preferences_camera_"; 179 180 private static final int MSG_CLEAR_SCREEN_ON_FLAG = 2; 181 private static final long SCREEN_DELAY_MS = 2 * 60 * 1000; // 2 mins. 182 private static final int MAX_PEEK_BITMAP_PIXELS = 1600000; // 1.6 * 4 MBs. 183 /** Load metadata for 10 items ahead of our current. */ 184 private static final int FILMSTRIP_PRELOAD_AHEAD_ITEMS = 10; 185 186 /** Should be used wherever a context is needed. */ 187 private Context mAppContext; 188 189 /** 190 * Camera fatal error handling: 191 * 1) Present error dialog to guide users to exit the app. 192 * 2) If users hit home button, onPause should just call finish() to exit the app. 193 */ 194 private boolean mCameraFatalError = false; 195 196 /** 197 * Whether onResume should reset the view to the preview. 198 */ 199 private boolean mResetToPreviewOnResume = true; 200 201 /** 202 * This data adapter is used by FilmStripView. 203 */ 204 private LocalDataAdapter mDataAdapter; 205 206 private OneCameraManager mCameraManager; 207 private SettingsManager mSettingsManager; 208 private ModeListView mModeListView; 209 private boolean mModeListVisible = false; 210 private int mCurrentModeIndex; 211 private CameraModule mCurrentModule; 212 private ModuleManagerImpl mModuleManager; 213 private FrameLayout mAboveFilmstripControlLayout; 214 private FilmstripController mFilmstripController; 215 private boolean mFilmstripVisible; 216 /** Whether the filmstrip fully covers the preview. */ 217 private boolean mFilmstripCoversPreview = false; 218 private int mResultCodeForTesting; 219 private Intent mResultDataForTesting; 220 private OnScreenHint mStorageHint; 221 private final Object mStorageSpaceLock = new Object(); 222 private long mStorageSpaceBytes = Storage.LOW_STORAGE_THRESHOLD_BYTES; 223 private boolean mAutoRotateScreen; 224 private boolean mSecureCamera; 225 private int mLastRawOrientation; 226 private OrientationManagerImpl mOrientationManager; 227 private LocationManager mLocationManager; 228 private ButtonManager mButtonManager; 229 private Handler mMainHandler; 230 private PanoramaViewHelper mPanoramaViewHelper; 231 private ActionBar mActionBar; 232 private ViewGroup mUndoDeletionBar; 233 private boolean mIsUndoingDeletion = false; 234 private boolean mIsActivityRunning = false; 235 236 private final Uri[] mNfcPushUris = new Uri[1]; 237 238 private LocalMediaObserver mLocalImagesObserver; 239 private LocalMediaObserver mLocalVideosObserver; 240 241 private boolean mPendingDeletion = false; 242 243 private CameraController mCameraController; 244 private boolean mPaused; 245 private CameraAppUI mCameraAppUI; 246 247 private PeekAnimationHandler mPeekAnimationHandler; 248 private HandlerThread mPeekAnimationThread; 249 250 private Intent mGalleryIntent; 251 private long mOnCreateTime; 252 253 private Menu mActionBarMenu; 254 private Preloader<Integer, AsyncTask> mPreloader; 255 256 /** Can be used to play custom sounds. */ 257 private SoundPlayer mSoundPlayer; 258 259 private static final int LIGHTS_OUT_DELAY_MS = 4000; 260 private final int BASE_SYS_UI_VISIBILITY = 261 View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN 262 | View.SYSTEM_UI_FLAG_LAYOUT_STABLE; 263 private final Runnable mLightsOutRunnable = new Runnable() { 264 @Override 265 public void run() { 266 getWindow().getDecorView().setSystemUiVisibility( 267 BASE_SYS_UI_VISIBILITY | View.SYSTEM_UI_FLAG_LOW_PROFILE); 268 } 269 }; 270 private MemoryManager mMemoryManager; 271 private MotionManager mMotionManager; 272 273 @Override 274 public CameraAppUI getCameraAppUI() { 275 return mCameraAppUI; 276 } 277 278 @Override 279 public ModuleManager getModuleManager() { 280 return mModuleManager; 281 } 282 283 // close activity when screen turns off 284 private final BroadcastReceiver mScreenOffReceiver = new BroadcastReceiver() { 285 @Override 286 public void onReceive(Context context, Intent intent) { 287 finish(); 288 } 289 }; 290 291 private final ActionBar.OnMenuVisibilityListener mOnMenuVisibilityListener = 292 new ActionBar.OnMenuVisibilityListener() { 293 @Override 294 public void onMenuVisibilityChanged(boolean isVisible) { 295 // TODO: Remove this or bring back the original implementation: cancel 296 // auto-hide actionbar. 297 } 298 }; 299 300 /** 301 * Whether the screen is kept turned on. 302 */ 303 private boolean mKeepScreenOn; 304 private int mLastLayoutOrientation; 305 private final CameraAppUI.BottomPanel.Listener mMyFilmstripBottomControlListener = 306 new CameraAppUI.BottomPanel.Listener() { 307 308 /** 309 * If the current photo is a photo sphere, this will launch the 310 * Photo Sphere panorama viewer. 311 */ 312 @Override 313 public void onExternalViewer() { 314 if (mPanoramaViewHelper == null) { 315 return; 316 } 317 final LocalData data = getCurrentLocalData(); 318 if (data == null) { 319 Log.w(TAG, "Cannot open null data."); 320 return; 321 } 322 final Uri contentUri = data.getUri(); 323 if (contentUri == Uri.EMPTY) { 324 Log.w(TAG, "Cannot open empty URL."); 325 return; 326 } 327 328 if (PanoramaMetadataLoader.isPanoramaAndUseViewer(data)) { 329 mPanoramaViewHelper.showPanorama(CameraActivity.this, contentUri); 330 } else if (RgbzMetadataLoader.hasRGBZData(data)) { 331 mPanoramaViewHelper.showRgbz(contentUri); 332 if (mSettingsManager.getBoolean(SettingsManager.SCOPE_GLOBAL, 333 Keys.KEY_SHOULD_SHOW_REFOCUS_VIEWER_CLING)) { 334 mSettingsManager.set(SettingsManager.SCOPE_GLOBAL, 335 Keys.KEY_SHOULD_SHOW_REFOCUS_VIEWER_CLING, false); 336 mCameraAppUI.clearClingForViewer( 337 CameraAppUI.BottomPanel.VIEWER_REFOCUS); 338 } 339 } 340 } 341 342 @Override 343 public void onEdit() { 344 LocalData data = getCurrentLocalData(); 345 if (data == null) { 346 Log.w(TAG, "Cannot edit null data."); 347 return; 348 } 349 final int currentDataId = getCurrentDataId(); 350 UsageStatistics.instance().mediaInteraction(fileNameFromDataID(currentDataId), 351 MediaInteraction.InteractionType.EDIT, 352 NavigationChange.InteractionCause.BUTTON, 353 fileAgeFromDataID(currentDataId)); 354 launchEditor(data); 355 } 356 357 @Override 358 public void onTinyPlanet() { 359 LocalData data = getCurrentLocalData(); 360 if (data == null) { 361 Log.w(TAG, "Cannot edit tiny planet on null data."); 362 return; 363 } 364 launchTinyPlanetEditor(data); 365 } 366 367 @Override 368 public void onDelete() { 369 final int currentDataId = getCurrentDataId(); 370 UsageStatistics.instance().mediaInteraction(fileNameFromDataID(currentDataId), 371 MediaInteraction.InteractionType.DELETE, 372 NavigationChange.InteractionCause.BUTTON, 373 fileAgeFromDataID(currentDataId)); 374 removeData(currentDataId); 375 } 376 377 @Override 378 public void onShare() { 379 final LocalData data = getCurrentLocalData(); 380 if (data == null) { 381 Log.w(TAG, "Cannot share null data."); 382 return; 383 } 384 385 final int currentDataId = getCurrentDataId(); 386 UsageStatistics.instance().mediaInteraction(fileNameFromDataID(currentDataId), 387 MediaInteraction.InteractionType.SHARE, 388 NavigationChange.InteractionCause.BUTTON, 389 fileAgeFromDataID(currentDataId)); 390 // If applicable, show release information before this item 391 // is shared. 392 if (ReleaseHelper.shouldShowReleaseInfoDialogOnShare(data)) { 393 ReleaseHelper.showReleaseInfoDialog(CameraActivity.this, 394 new Callback<Void>() { 395 @Override 396 public void onCallback(Void result) { 397 share(data); 398 } 399 }); 400 } else { 401 share(data); 402 } 403 } 404 405 private void share(LocalData data) { 406 Intent shareIntent = getShareIntentByData(data); 407 if (shareIntent != null) { 408 try { 409 launchActivityByIntent(shareIntent); 410 mCameraAppUI.getFilmstripBottomControls().setShareEnabled(false); 411 } catch (ActivityNotFoundException ex) { 412 // Nothing. 413 } 414 } 415 } 416 417 private int getCurrentDataId() { 418 return mFilmstripController.getCurrentId(); 419 } 420 421 private LocalData getCurrentLocalData() { 422 return mDataAdapter.getLocalData(getCurrentDataId()); 423 } 424 425 /** 426 * Sets up the share intent and NFC properly according to the 427 * data. 428 * 429 * @param data The data to be shared. 430 */ 431 private Intent getShareIntentByData(final LocalData data) { 432 Intent intent = null; 433 final Uri contentUri = data.getUri(); 434 final String msgShareTo = getResources().getString(R.string.share_to); 435 436 if (PanoramaMetadataLoader.isPanorama360(data) && 437 data.getUri() != Uri.EMPTY) { 438 intent = new Intent(Intent.ACTION_SEND); 439 intent.setType("application/vnd.google.panorama360+jpg"); 440 intent.putExtra(Intent.EXTRA_STREAM, contentUri); 441 } else if (data.isDataActionSupported(LocalData.DATA_ACTION_SHARE)) { 442 final String mimeType = data.getMimeType(); 443 intent = getShareIntentFromType(mimeType); 444 if (intent != null) { 445 intent.putExtra(Intent.EXTRA_STREAM, contentUri); 446 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 447 } 448 intent = Intent.createChooser(intent, msgShareTo); 449 } 450 return intent; 451 } 452 453 /** 454 * Get the share intent according to the mimeType 455 * 456 * @param mimeType The mimeType of current data. 457 * @return the video/image's ShareIntent or null if mimeType is 458 * invalid. 459 */ 460 private Intent getShareIntentFromType(String mimeType) { 461 // Lazily create the intent object. 462 Intent intent = new Intent(Intent.ACTION_SEND); 463 if (mimeType.startsWith("video/")) { 464 intent.setType("video/*"); 465 } else { 466 if (mimeType.startsWith("image/")) { 467 intent.setType("image/*"); 468 } else { 469 Log.w(TAG, "unsupported mimeType " + mimeType); 470 } 471 } 472 return intent; 473 } 474 475 @Override 476 public void onProgressErrorClicked() { 477 LocalData data = getCurrentLocalData(); 478 getServices().getCaptureSessionManager().removeErrorMessage( 479 data.getUri()); 480 updateBottomControlsByData(data); 481 } 482 }; 483 484 @Override 485 public void onCameraOpened(CameraAgent.CameraProxy camera) { 486 Log.v(TAG, "onCameraOpened"); 487 if (mPaused) { 488 // We've paused, but just asynchronously opened the camera. Close it 489 // because we should be releasing the camera when paused to allow 490 // other apps to access it. 491 Log.v(TAG, "received onCameraOpened but activity is paused, closing Camera"); 492 mCameraController.closeCamera(false); 493 return; 494 } 495 /** 496 * The current UI requires that the flash option visibility in front-facing 497 * camera be 498 * * disabled if back facing camera supports flash 499 * * hidden if back facing camera does not support flash 500 * We save whether back facing camera supports flash because we cannot get 501 * this in front facing camera without a camera switch. 502 * 503 * If this preference is cleared, we also need to clear the camera facing 504 * setting so we default to opening the camera in back facing camera, and 505 * can save this flash support value again. 506 */ 507 if (!mSettingsManager.isSet(SettingsManager.SCOPE_GLOBAL, 508 Keys.KEY_FLASH_SUPPORTED_BACK_CAMERA)) { 509 HardwareSpec hardware = 510 new HardwareSpecImpl(getCameraProvider(), camera.getCapabilities()); 511 mSettingsManager.set(SettingsManager.SCOPE_GLOBAL, 512 Keys.KEY_FLASH_SUPPORTED_BACK_CAMERA, 513 hardware.isFlashSupported()); 514 } 515 516 if (!mModuleManager.getModuleAgent(mCurrentModeIndex).requestAppForCamera()) { 517 // We shouldn't be here. Just close the camera and leave. 518 mCameraController.closeCamera(false); 519 throw new IllegalStateException("Camera opened but the module shouldn't be " + 520 "requesting"); 521 } 522 if (mCurrentModule != null) { 523 resetExposureCompensationToDefault(camera); 524 mCurrentModule.onCameraAvailable(camera); 525 } else { 526 Log.v(TAG, "mCurrentModule null, not invoking onCameraAvailable"); 527 } 528 Log.v(TAG, "invoking onChangeCamera"); 529 mCameraAppUI.onChangeCamera(); 530 } 531 532 private void resetExposureCompensationToDefault(CameraAgent.CameraProxy camera) { 533 // Reset the exposure compensation before handing the camera to module. 534 CameraSettings cameraSettings = camera.getSettings(); 535 cameraSettings.setExposureCompensationIndex(0); 536 camera.applySettings(cameraSettings); 537 } 538 539 @Override 540 public void onCameraDisabled(int cameraId) { 541 UsageStatistics.instance().cameraFailure(eventprotos.CameraFailure.FailureReason.SECURITY, 542 null); 543 Log.w(TAG, "Camera disabled: " + cameraId); 544 CameraUtil.showErrorAndFinish(this, R.string.camera_disabled); 545 } 546 547 @Override 548 public void onDeviceOpenFailure(int cameraId, String info) { 549 UsageStatistics.instance().cameraFailure( 550 eventprotos.CameraFailure.FailureReason.OPEN_FAILURE, info); 551 Log.w(TAG, "Camera open failure: " + info); 552 CameraUtil.showErrorAndFinish(this, R.string.cannot_connect_camera); 553 } 554 555 @Override 556 public void onDeviceOpenedAlready(int cameraId, String info) { 557 Log.w(TAG, "Camera open already: " + cameraId + "," + info); 558 CameraUtil.showErrorAndFinish(this, R.string.cannot_connect_camera); 559 } 560 561 @Override 562 public void onReconnectionFailure(CameraAgent mgr, String info) { 563 UsageStatistics.instance().cameraFailure( 564 eventprotos.CameraFailure.FailureReason.RECONNECT_FAILURE, null); 565 Log.w(TAG, "Camera reconnection failure:" + info); 566 CameraUtil.showErrorAndFinish(this, R.string.cannot_connect_camera); 567 } 568 569 private static class MainHandler extends Handler { 570 final WeakReference<CameraActivity> mActivity; 571 572 public MainHandler(CameraActivity activity, Looper looper) { 573 super(looper); 574 mActivity = new WeakReference<CameraActivity>(activity); 575 } 576 577 @Override 578 public void handleMessage(Message msg) { 579 CameraActivity activity = mActivity.get(); 580 if (activity == null) { 581 return; 582 } 583 switch (msg.what) { 584 585 case MSG_CLEAR_SCREEN_ON_FLAG: { 586 if (!activity.mPaused) { 587 activity.getWindow().clearFlags( 588 WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 589 } 590 break; 591 } 592 } 593 } 594 } 595 596 private String fileNameFromDataID(int dataID) { 597 final LocalData localData = mDataAdapter.getLocalData(dataID); 598 if (localData == null) { 599 return ""; 600 } 601 602 File localFile = new File(localData.getPath()); 603 return localFile.getName(); 604 } 605 606 private float fileAgeFromDataID(int dataID) { 607 final LocalData localData = mDataAdapter.getLocalData(dataID); 608 if (localData == null) { 609 return 0; 610 } 611 612 File localFile = new File(localData.getPath()); 613 return 0.001f * (System.currentTimeMillis() - localFile.lastModified()); 614 } 615 616 private final FilmstripContentPanel.Listener mFilmstripListener = 617 new FilmstripContentPanel.Listener() { 618 619 @Override 620 public void onSwipeOut() { 621 } 622 623 @Override 624 public void onSwipeOutBegin() { 625 mActionBar.hide(); 626 mCameraAppUI.hideBottomControls(); 627 mFilmstripCoversPreview = false; 628 updatePreviewVisibility(); 629 } 630 631 @Override 632 public void onFilmstripHidden() { 633 mFilmstripVisible = false; 634 UsageStatistics.instance().changeScreen(currentUserInterfaceMode(), 635 NavigationChange.InteractionCause.SWIPE_RIGHT); 636 CameraActivity.this.setFilmstripUiVisibility(false); 637 // When the user hide the filmstrip (either swipe out or 638 // tap on back key) we move to the first item so next time 639 // when the user swipe in the filmstrip, the most recent 640 // one is shown. 641 mFilmstripController.goToFirstItem(); 642 } 643 644 @Override 645 public void onFilmstripShown() { 646 mFilmstripVisible = true; 647 UsageStatistics.instance().changeScreen(currentUserInterfaceMode(), 648 NavigationChange.InteractionCause.SWIPE_LEFT); 649 updateUiByData(mFilmstripController.getCurrentId()); 650 } 651 652 @Override 653 public void onFocusedDataLongPressed(int dataId) { 654 // Do nothing. 655 } 656 657 @Override 658 public void onFocusedDataPromoted(int dataID) { 659 UsageStatistics.instance().mediaInteraction(fileNameFromDataID(dataID), 660 MediaInteraction.InteractionType.DELETE, 661 NavigationChange.InteractionCause.SWIPE_UP, fileAgeFromDataID(dataID)); 662 removeData(dataID); 663 } 664 665 @Override 666 public void onFocusedDataDemoted(int dataID) { 667 UsageStatistics.instance().mediaInteraction(fileNameFromDataID(dataID), 668 MediaInteraction.InteractionType.DELETE, 669 NavigationChange.InteractionCause.SWIPE_DOWN, 670 fileAgeFromDataID(dataID)); 671 removeData(dataID); 672 } 673 674 @Override 675 public void onEnterFullScreenUiShown(int dataId) { 676 if (mFilmstripVisible) { 677 CameraActivity.this.setFilmstripUiVisibility(true); 678 } 679 } 680 681 @Override 682 public void onLeaveFullScreenUiShown(int dataId) { 683 // Do nothing. 684 } 685 686 @Override 687 public void onEnterFullScreenUiHidden(int dataId) { 688 if (mFilmstripVisible) { 689 CameraActivity.this.setFilmstripUiVisibility(false); 690 } 691 } 692 693 @Override 694 public void onLeaveFullScreenUiHidden(int dataId) { 695 // Do nothing. 696 } 697 698 @Override 699 public void onEnterFilmstrip(int dataId) { 700 if (mFilmstripVisible) { 701 CameraActivity.this.setFilmstripUiVisibility(true); 702 } 703 } 704 705 @Override 706 public void onLeaveFilmstrip(int dataId) { 707 // Do nothing. 708 } 709 710 @Override 711 public void onDataReloaded() { 712 if (!mFilmstripVisible) { 713 return; 714 } 715 updateUiByData(mFilmstripController.getCurrentId()); 716 } 717 718 @Override 719 public void onDataUpdated(int dataId) { 720 if (!mFilmstripVisible) { 721 return; 722 } 723 updateUiByData(mFilmstripController.getCurrentId()); 724 } 725 726 @Override 727 public void onEnterZoomView(int dataID) { 728 if (mFilmstripVisible) { 729 CameraActivity.this.setFilmstripUiVisibility(false); 730 } 731 } 732 733 @Override 734 public void onZoomAtIndexChanged(int dataId, float zoom) { 735 final LocalData localData = mDataAdapter.getLocalData(dataId); 736 long ageMillis = System.currentTimeMillis() - localData.getDateModified() * 1000; 737 738 // Do not log if items is to old or does not have a path (which is 739 // being used as a key). 740 if (TextUtils.isEmpty(localData.getPath()) || 741 ageMillis > UsageStatistics.VIEW_TIMEOUT_MILLIS) { 742 return; 743 } 744 File localFile = new File(localData.getPath()); 745 UsageStatistics.instance().mediaView(localFile.getName(), 746 TimeUnit.SECONDS.toMillis(localData.getDateModified()), zoom); 747 } 748 749 @Override 750 public void onDataFocusChanged(final int prevDataId, final int newDataId) { 751 if (!mFilmstripVisible) { 752 return; 753 } 754 // TODO: This callback is UI event callback, should always 755 // happen on UI thread. Find the reason for this 756 // runOnUiThread() and fix it. 757 runOnUiThread(new Runnable() { 758 @Override 759 public void run() { 760 updateUiByData(newDataId); 761 } 762 }); 763 } 764 765 @Override 766 public void onScroll(int firstVisiblePosition, int visibleItemCount, int totalItemCount) { 767 mPreloader.onScroll(null /*absListView*/, firstVisiblePosition, visibleItemCount, totalItemCount); 768 } 769 }; 770 771 private final LocalDataAdapter.LocalDataListener mLocalDataListener = 772 new LocalDataAdapter.LocalDataListener() { 773 @Override 774 public void onMetadataUpdated(List<Integer> updatedData) { 775 if (mPaused) { 776 // Callback after the activity is paused. 777 return; 778 } 779 int currentDataId = mFilmstripController.getCurrentId(); 780 for (Integer dataId : updatedData) { 781 if (dataId == currentDataId) { 782 updateBottomControlsByData(mDataAdapter.getLocalData(dataId)); 783 // Currently we have only 1 data can be matched. 784 // No need to look for more, break. 785 break; 786 } 787 } 788 } 789 }; 790 791 public void gotoGallery() { 792 UsageStatistics.instance().changeScreen(NavigationChange.Mode.FILMSTRIP, 793 NavigationChange.InteractionCause.BUTTON); 794 795 mFilmstripController.goToNextItem(); 796 } 797 798 /** 799 * If 'visible' is false, this hides the action bar. Also maintains 800 * lights-out at all times. 801 * 802 * @param visible is false, this hides the action bar and filmstrip bottom 803 * controls. 804 */ 805 private void setFilmstripUiVisibility(boolean visible) { 806 mLightsOutRunnable.run(); 807 mCameraAppUI.getFilmstripBottomControls().setVisible(visible); 808 if (visible != mActionBar.isShowing()) { 809 if (visible) { 810 mActionBar.show(); 811 mCameraAppUI.showBottomControls(); 812 } else { 813 mActionBar.hide(); 814 mCameraAppUI.hideBottomControls(); 815 } 816 } 817 mFilmstripCoversPreview = visible; 818 updatePreviewVisibility(); 819 } 820 821 private void hideSessionProgress() { 822 mCameraAppUI.getFilmstripBottomControls().hideProgress(); 823 } 824 825 private void showSessionProgress(CharSequence message) { 826 CameraAppUI.BottomPanel controls = mCameraAppUI.getFilmstripBottomControls(); 827 controls.setProgressText(message); 828 controls.hideControls(); 829 controls.hideProgressError(); 830 controls.showProgress(); 831 } 832 833 private void showProcessError(CharSequence message) { 834 mCameraAppUI.getFilmstripBottomControls().showProgressError(message); 835 } 836 837 private void updateSessionProgress(int progress) { 838 mCameraAppUI.getFilmstripBottomControls().setProgress(progress); 839 } 840 841 private void updateSessionProgressText(CharSequence message) { 842 mCameraAppUI.getFilmstripBottomControls().setProgressText(message); 843 } 844 845 @TargetApi(Build.VERSION_CODES.JELLY_BEAN) 846 private void setupNfcBeamPush() { 847 NfcAdapter adapter = NfcAdapter.getDefaultAdapter(mAppContext); 848 if (adapter == null) { 849 return; 850 } 851 852 if (!ApiHelper.HAS_SET_BEAM_PUSH_URIS) { 853 // Disable beaming 854 adapter.setNdefPushMessage(null, CameraActivity.this); 855 return; 856 } 857 858 adapter.setBeamPushUris(null, CameraActivity.this); 859 adapter.setBeamPushUrisCallback(new CreateBeamUrisCallback() { 860 @Override 861 public Uri[] createBeamUris(NfcEvent event) { 862 return mNfcPushUris; 863 } 864 }, CameraActivity.this); 865 } 866 867 @Override 868 public boolean onShareTargetSelected(ShareActionProvider shareActionProvider, Intent intent) { 869 int currentDataId = mFilmstripController.getCurrentId(); 870 if (currentDataId < 0) { 871 return false; 872 } 873 UsageStatistics.instance().mediaInteraction(fileNameFromDataID(currentDataId), 874 MediaInteraction.InteractionType.SHARE, 875 NavigationChange.InteractionCause.BUTTON, fileAgeFromDataID(currentDataId)); 876 // TODO add intent.getComponent().getPackageName() 877 return true; 878 } 879 880 // Note: All callbacks come back on the main thread. 881 private final SessionListener mSessionListener = 882 new SessionListener() { 883 @Override 884 public void onSessionQueued(final Uri uri) { 885 Log.v(TAG, "onSessionQueued: " + uri); 886 if (!Storage.isSessionUri(uri)) { 887 return; 888 } 889 LocalSessionData newData = new LocalSessionData(uri); 890 mDataAdapter.addData(newData); 891 } 892 893 @Override 894 public void onSessionDone(final Uri sessionUri) { 895 Log.v(TAG, "onSessionDone:" + sessionUri); 896 Uri contentUri = Storage.getContentUriForSessionUri(sessionUri); 897 if (contentUri == null) { 898 mDataAdapter.refresh(sessionUri); 899 return; 900 } 901 LocalData newData = LocalMediaData.PhotoData.fromContentUri( 902 getContentResolver(), contentUri); 903 904 // This can be null if e.g. a session is canceled (e.g. 905 // through discard panorama). It might be worth adding 906 // onSessionCanceled or the like this interface. 907 if (newData == null) { 908 Log.i(TAG, "onSessionDone: Could not find LocalData for URI: " + contentUri); 909 return; 910 } 911 912 final int pos = mDataAdapter.findDataByContentUri(sessionUri); 913 if (pos == -1) { 914 // We do not have a placeholder for this image, perhaps 915 // due to the activity crashing or being killed. 916 mDataAdapter.addData(newData); 917 } else { 918 mDataAdapter.updateData(pos, newData); 919 } 920 } 921 922 @Override 923 public void onSessionProgress(final Uri uri, final int progress) { 924 if (progress < 0) { 925 // Do nothing, there is no task for this URI. 926 return; 927 } 928 int currentDataId = mFilmstripController.getCurrentId(); 929 if (currentDataId == -1) { 930 return; 931 } 932 if (uri.equals( 933 mDataAdapter.getLocalData(currentDataId).getUri())) { 934 updateSessionProgress(progress); 935 } 936 } 937 938 @Override 939 public void onSessionProgressText(final Uri uri, final CharSequence message) { 940 int currentDataId = mFilmstripController.getCurrentId(); 941 if (currentDataId == -1) { 942 return; 943 } 944 if (uri.equals( 945 mDataAdapter.getLocalData(currentDataId).getUri())) { 946 updateSessionProgressText(message); 947 } 948 } 949 950 @Override 951 public void onSessionUpdated(Uri uri) { 952 Log.v(TAG, "onSessionUpdated: " + uri); 953 mDataAdapter.refresh(uri); 954 } 955 956 @Override 957 public void onSessionPreviewAvailable(Uri uri) { 958 Log.v(TAG, "onSessionPreviewAvailable: " + uri); 959 mDataAdapter.refresh(uri); 960 int dataId = mDataAdapter.findDataByContentUri(uri); 961 if (dataId != -1) { 962 startPeekAnimation(mDataAdapter.getLocalData(dataId), 963 mCurrentModule.getPeekAccessibilityString()); 964 } 965 } 966 967 @Override 968 public void onSessionFailed(Uri uri, CharSequence reason) { 969 Log.v(TAG, "onSessionFailed:" + uri); 970 971 int failedDataId = mDataAdapter.findDataByContentUri(uri); 972 int currentDataId = mFilmstripController.getCurrentId(); 973 974 if (currentDataId == failedDataId) { 975 updateSessionProgress(0); 976 showProcessError(reason); 977 } 978 // HERE 979 mDataAdapter.refresh(uri); 980 } 981 }; 982 983 @Override 984 public Context getAndroidContext() { 985 return mAppContext; 986 } 987 988 @Override 989 public void launchActivityByIntent(Intent intent) { 990 // Starting from L, we prefer not to start edit activity within camera's task. 991 mResetToPreviewOnResume = false; 992 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT); 993 994 startActivity(intent); 995 } 996 997 @Override 998 public int getCurrentModuleIndex() { 999 return mCurrentModeIndex; 1000 } 1001 1002 @Override 1003 public int getCurrentCameraId() { 1004 return mCameraController.getCurrentCameraId(); 1005 } 1006 1007 @Override 1008 public String getModuleScope() { 1009 return MODULE_SCOPE_PREFIX + mCurrentModule.getModuleStringIdentifier(); 1010 } 1011 1012 @Override 1013 public String getCameraScope() { 1014 int currentCameraId = getCurrentCameraId(); 1015 if (currentCameraId < 0) { 1016 // if an unopen camera i.e. negative ID is returned, which we've observed in 1017 // some automated scenarios, just return it as a valid separate scope 1018 // this could cause user issues, so log a stack trace noting the call path 1019 // which resulted in this scenario. 1020 Log.w(TAG, "getting camera scope with no open camera, using id: " + currentCameraId); 1021 } 1022 return CAMERA_SCOPE_PREFIX + Integer.toString(currentCameraId); 1023 } 1024 1025 @Override 1026 public ModuleController getCurrentModuleController() { 1027 return mCurrentModule; 1028 } 1029 1030 @Override 1031 public int getQuickSwitchToModuleId(int currentModuleIndex) { 1032 return mModuleManager.getQuickSwitchToModuleId(currentModuleIndex, mSettingsManager, 1033 mAppContext); 1034 } 1035 1036 @Override 1037 public SurfaceTexture getPreviewBuffer() { 1038 // TODO: implement this 1039 return null; 1040 } 1041 1042 @Override 1043 public void onPreviewReadyToStart() { 1044 mCameraAppUI.onPreviewReadyToStart(); 1045 } 1046 1047 @Override 1048 public void onPreviewStarted() { 1049 mCameraAppUI.onPreviewStarted(); 1050 } 1051 1052 @Override 1053 public void addPreviewAreaSizeChangedListener( 1054 PreviewStatusListener.PreviewAreaChangedListener listener) { 1055 mCameraAppUI.addPreviewAreaChangedListener(listener); 1056 } 1057 1058 @Override 1059 public void removePreviewAreaSizeChangedListener( 1060 PreviewStatusListener.PreviewAreaChangedListener listener) { 1061 mCameraAppUI.removePreviewAreaChangedListener(listener); 1062 } 1063 1064 @Override 1065 public void setupOneShotPreviewListener() { 1066 mCameraController.setOneShotPreviewCallback(mMainHandler, 1067 new CameraAgent.CameraPreviewDataCallback() { 1068 @Override 1069 public void onPreviewFrame(byte[] data, CameraAgent.CameraProxy camera) { 1070 mCurrentModule.onPreviewInitialDataReceived(); 1071 mCameraAppUI.onNewPreviewFrame(); 1072 } 1073 } 1074 ); 1075 } 1076 1077 @Override 1078 public void updatePreviewAspectRatio(float aspectRatio) { 1079 mCameraAppUI.updatePreviewAspectRatio(aspectRatio); 1080 } 1081 1082 @Override 1083 public void updatePreviewTransformFullscreen(Matrix matrix, float aspectRatio) { 1084 mCameraAppUI.updatePreviewTransformFullscreen(matrix, aspectRatio); 1085 } 1086 1087 @Override 1088 public RectF getFullscreenRect() { 1089 return mCameraAppUI.getFullscreenRect(); 1090 } 1091 1092 @Override 1093 public void updatePreviewTransform(Matrix matrix) { 1094 mCameraAppUI.updatePreviewTransform(matrix); 1095 } 1096 1097 @Override 1098 public void setPreviewStatusListener(PreviewStatusListener previewStatusListener) { 1099 mCameraAppUI.setPreviewStatusListener(previewStatusListener); 1100 } 1101 1102 @Override 1103 public FrameLayout getModuleLayoutRoot() { 1104 return mCameraAppUI.getModuleRootView(); 1105 } 1106 1107 @Override 1108 public void setShutterEventsListener(ShutterEventsListener listener) { 1109 // TODO: implement this 1110 } 1111 1112 @Override 1113 public void setShutterEnabled(boolean enabled) { 1114 mCameraAppUI.setShutterButtonEnabled(enabled); 1115 } 1116 1117 @Override 1118 public boolean isShutterEnabled() { 1119 return mCameraAppUI.isShutterButtonEnabled(); 1120 } 1121 1122 @Override 1123 public void startPreCaptureAnimation(boolean shortFlash) { 1124 mCameraAppUI.startPreCaptureAnimation(shortFlash); 1125 } 1126 1127 @Override 1128 public void startPreCaptureAnimation() { 1129 mCameraAppUI.startPreCaptureAnimation(false); 1130 } 1131 1132 @Override 1133 public void cancelPreCaptureAnimation() { 1134 // TODO: implement this 1135 } 1136 1137 @Override 1138 public void startPostCaptureAnimation() { 1139 // TODO: implement this 1140 } 1141 1142 @Override 1143 public void startPostCaptureAnimation(Bitmap thumbnail) { 1144 // TODO: implement this 1145 } 1146 1147 @Override 1148 public void cancelPostCaptureAnimation() { 1149 // TODO: implement this 1150 } 1151 1152 @Override 1153 public OrientationManager getOrientationManager() { 1154 return mOrientationManager; 1155 } 1156 1157 @Override 1158 public LocationManager getLocationManager() { 1159 return mLocationManager; 1160 } 1161 1162 @Override 1163 public void lockOrientation() { 1164 if (mOrientationManager != null) { 1165 mOrientationManager.lockOrientation(); 1166 } 1167 } 1168 1169 @Override 1170 public void unlockOrientation() { 1171 if (mOrientationManager != null) { 1172 mOrientationManager.unlockOrientation(); 1173 } 1174 } 1175 1176 /** 1177 * Starts the filmstrip peek animation if the filmstrip is not visible. 1178 * Only {@link LocalData#LOCAL_IMAGE}, {@link 1179 * LocalData#LOCAL_IN_PROGRESS_DATA} and {@link 1180 * LocalData#LOCAL_VIDEO} are supported. 1181 * 1182 * @param data The data to peek. 1183 * @param accessibilityString Accessibility string to announce on peek animation. 1184 */ 1185 private void startPeekAnimation(final LocalData data, final String accessibilityString) { 1186 if (mFilmstripVisible || mPeekAnimationHandler == null) { 1187 return; 1188 } 1189 1190 int dataType = data.getLocalDataType(); 1191 if (dataType != LocalData.LOCAL_IMAGE && dataType != LocalData.LOCAL_IN_PROGRESS_DATA && 1192 dataType != LocalData.LOCAL_VIDEO) { 1193 return; 1194 } 1195 1196 mPeekAnimationHandler.startDecodingJob(data, new Callback<Bitmap>() { 1197 @Override 1198 public void onCallback(Bitmap result) { 1199 mCameraAppUI.startPeekAnimation(result, true, accessibilityString); 1200 } 1201 }); 1202 } 1203 1204 @Override 1205 public void notifyNewMedia(Uri uri) { 1206 // TODO: This method is running on the main thread. Also we should get 1207 // rid of that AsyncTask. 1208 1209 updateStorageSpaceAndHint(null); 1210 ContentResolver cr = getContentResolver(); 1211 String mimeType = cr.getType(uri); 1212 LocalData newData = null; 1213 if (LocalDataUtil.isMimeTypeVideo(mimeType)) { 1214 sendBroadcast(new Intent(CameraUtil.ACTION_NEW_VIDEO, uri)); 1215 newData = LocalMediaData.VideoData.fromContentUri(getContentResolver(), uri); 1216 if (newData == null) { 1217 Log.e(TAG, "Can't find video data in content resolver:" + uri); 1218 return; 1219 } 1220 } else if (LocalDataUtil.isMimeTypeImage(mimeType)) { 1221 CameraUtil.broadcastNewPicture(mAppContext, uri); 1222 newData = LocalMediaData.PhotoData.fromContentUri(getContentResolver(), uri); 1223 if (newData == null) { 1224 Log.e(TAG, "Can't find photo data in content resolver:" + uri); 1225 return; 1226 } 1227 } else { 1228 Log.w(TAG, "Unknown new media with MIME type:" + mimeType + ", uri:" + uri); 1229 return; 1230 } 1231 1232 // We are preloading the metadata for new video since we need the 1233 // rotation info for the thumbnail. 1234 new AsyncTask<LocalData, Void, LocalData>() { 1235 @Override 1236 protected LocalData doInBackground(LocalData... params) { 1237 LocalData data = params[0]; 1238 MetadataLoader.loadMetadata(getAndroidContext(), data); 1239 return data; 1240 } 1241 1242 @Override 1243 protected void onPostExecute(LocalData data) { 1244 // TODO: Figure out why sometimes the data is aleady there. 1245 mDataAdapter.addData(data); 1246 startPeekAnimation(data, mCurrentModule.getPeekAccessibilityString()); 1247 } 1248 }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, newData); 1249 } 1250 1251 @Override 1252 public void enableKeepScreenOn(boolean enabled) { 1253 if (mPaused) { 1254 return; 1255 } 1256 1257 mKeepScreenOn = enabled; 1258 if (mKeepScreenOn) { 1259 mMainHandler.removeMessages(MSG_CLEAR_SCREEN_ON_FLAG); 1260 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 1261 } else { 1262 keepScreenOnForAWhile(); 1263 } 1264 } 1265 1266 @Override 1267 public CameraProvider getCameraProvider() { 1268 return mCameraController; 1269 } 1270 1271 @Override 1272 public OneCameraManager getCameraManager() { 1273 return mCameraManager; 1274 } 1275 1276 private void removeData(int dataID) { 1277 mDataAdapter.removeData(dataID); 1278 if (mDataAdapter.getTotalNumber() > 1) { 1279 showUndoDeletionBar(); 1280 } else { 1281 // If camera preview is the only view left in filmstrip, 1282 // no need to show undo bar. 1283 mPendingDeletion = true; 1284 performDeletion(); 1285 if (mFilmstripVisible) { 1286 mCameraAppUI.getFilmstripContentPanel().animateHide(); 1287 } 1288 } 1289 } 1290 1291 @Override 1292 public boolean onOptionsItemSelected(MenuItem item) { 1293 // Handle presses on the action bar items 1294 switch (item.getItemId()) { 1295 case android.R.id.home: 1296 onBackPressed(); 1297 return true; 1298 case R.id.action_details: 1299 showDetailsDialog(mFilmstripController.getCurrentId()); 1300 return true; 1301 case R.id.action_help_and_feedback: 1302 mResetToPreviewOnResume = false; 1303 GoogleHelpHelper.launchGoogleHelp(this); 1304 return true; 1305 default: 1306 return super.onOptionsItemSelected(item); 1307 } 1308 } 1309 1310 private boolean isCaptureIntent() { 1311 if (MediaStore.ACTION_VIDEO_CAPTURE.equals(getIntent().getAction()) 1312 || MediaStore.ACTION_IMAGE_CAPTURE.equals(getIntent().getAction()) 1313 || MediaStore.ACTION_IMAGE_CAPTURE_SECURE.equals(getIntent().getAction())) { 1314 return true; 1315 } else { 1316 return false; 1317 } 1318 } 1319 1320 private final CameraExceptionHandler.CameraExceptionCallback mCameraExceptionCallback 1321 = new CameraExceptionHandler.CameraExceptionCallback() { 1322 @Override 1323 public void onCameraError(int errorCode) { 1324 // Not a fatal error. only do Log.e(). 1325 Log.e(TAG, "Camera error callback. error=" + errorCode); 1326 } 1327 @Override 1328 public void onCameraException(RuntimeException ex) { 1329 Log.e(TAG, "Camera Exception", ex); 1330 onFatalError(); 1331 } 1332 @Override 1333 public void onDispatchThreadException(RuntimeException ex) { 1334 Log.e(TAG, "DispatchThread Exception", ex); 1335 onFatalError(); 1336 } 1337 private void onFatalError() { 1338 if (mCameraFatalError) { 1339 return; 1340 } 1341 mCameraFatalError = true; 1342 1343 // If the activity receives exception during onPause, just exit the app. 1344 if (mPaused && !isFinishing()) { 1345 Log.e(TAG, "Fatal error during onPause, call Activity.finish()"); 1346 finish(); 1347 } else { 1348 CameraUtil.showErrorAndFinish(CameraActivity.this, 1349 R.string.cannot_connect_camera); 1350 } 1351 } 1352 }; 1353 1354 @Override 1355 public void onNewIntentTasks(Intent intent) { 1356 onModeSelected(getModeIndex()); 1357 } 1358 1359 @Override 1360 public void onCreateTasks(Bundle state) { 1361 CameraPerformanceTracker.onEvent(CameraPerformanceTracker.ACTIVITY_START); 1362 if (!Glide.isSetup()) { 1363 Glide.setup(new GlideBuilder(this) 1364 .setResizeService(new FifoPriorityThreadPoolExecutor(2))); 1365 Glide.get(this).setMemoryCategory(MemoryCategory.HIGH); 1366 } 1367 1368 mOnCreateTime = System.currentTimeMillis(); 1369 mAppContext = getApplicationContext(); 1370 mSoundPlayer = new SoundPlayer(mAppContext); 1371 1372 try { 1373 mCameraManager = OneCameraManager.get(this); 1374 } catch (OneCameraException e) { 1375 Log.d(TAG, "Creating camera manager failed.", e); 1376 CameraUtil.showErrorAndFinish(this, R.string.cannot_connect_camera); 1377 return; 1378 } 1379 1380 // TODO: Try to move all the resources allocation to happen as soon as 1381 // possible so we can call module.init() at the earliest time. 1382 mModuleManager = new ModuleManagerImpl(); 1383 GcamHelper.init(getContentResolver()); 1384 ModulesInfo.setupModules(mAppContext, mModuleManager); 1385 1386 mSettingsManager = getServices().getSettingsManager(); 1387 AppUpgrader appUpgrader = new AppUpgrader(this); 1388 appUpgrader.upgrade(mSettingsManager); 1389 Keys.setDefaults(mSettingsManager, mAppContext); 1390 1391 getWindow().requestFeature(Window.FEATURE_ACTION_BAR); 1392 setContentView(R.layout.activity_main); 1393 1394 mActionBar = getActionBar(); 1395 // set actionbar background to 100% or 50% transparent 1396 if (ApiHelper.isLOrHigher()) { 1397 mActionBar.setBackgroundDrawable(new ColorDrawable(0x00000000)); 1398 } else { 1399 mActionBar.setBackgroundDrawable(new ColorDrawable(0x80000000)); 1400 } 1401 mActionBar.addOnMenuVisibilityListener(mOnMenuVisibilityListener); 1402 1403 mMainHandler = new MainHandler(this, getMainLooper()); 1404 mCameraController = new CameraController(mAppContext, this, mMainHandler, 1405 CameraAgentFactory.getAndroidCameraAgent(this, CameraAgentFactory.CameraApi.API_1), 1406 CameraAgentFactory.getAndroidCameraAgent(this, CameraAgentFactory.CameraApi.AUTO)); 1407 mCameraController.setCameraExceptionHandler( 1408 new CameraExceptionHandler(mCameraExceptionCallback, mMainHandler)); 1409 1410 mModeListView = (ModeListView) findViewById(R.id.mode_list_layout); 1411 mModeListView.init(mModuleManager.getSupportedModeIndexList()); 1412 if (ApiHelper.HAS_ROTATION_ANIMATION) { 1413 setRotationAnimation(); 1414 } 1415 mModeListView.setVisibilityChangedListener(new ModeListVisibilityChangedListener() { 1416 @Override 1417 public void onVisibilityChanged(boolean visible) { 1418 mModeListVisible = visible; 1419 mCameraAppUI.setShutterButtonImportantToA11y(!visible); 1420 updatePreviewVisibility(); 1421 } 1422 }); 1423 1424 // Check if this is in the secure camera mode. 1425 Intent intent = getIntent(); 1426 String action = intent.getAction(); 1427 if (INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE.equals(action) 1428 || ACTION_IMAGE_CAPTURE_SECURE.equals(action)) { 1429 mSecureCamera = true; 1430 } else { 1431 mSecureCamera = intent.getBooleanExtra(SECURE_CAMERA_EXTRA, false); 1432 } 1433 1434 if (mSecureCamera) { 1435 // Change the window flags so that secure camera can show when 1436 // locked 1437 Window win = getWindow(); 1438 WindowManager.LayoutParams params = win.getAttributes(); 1439 params.flags |= WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED; 1440 win.setAttributes(params); 1441 1442 // Filter for screen off so that we can finish secure camera 1443 // activity 1444 // when screen is off. 1445 IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF); 1446 registerReceiver(mScreenOffReceiver, filter); 1447 } 1448 mCameraAppUI = new CameraAppUI(this, 1449 (MainActivityLayout) findViewById(R.id.activity_root_view), isCaptureIntent()); 1450 1451 mCameraAppUI.setFilmstripBottomControlsListener(mMyFilmstripBottomControlListener); 1452 1453 mAboveFilmstripControlLayout = 1454 (FrameLayout) findViewById(R.id.camera_filmstrip_content_layout); 1455 1456 // Add the session listener so we can track the session progress 1457 // updates. 1458 getServices().getCaptureSessionManager().addSessionListener(mSessionListener); 1459 mFilmstripController = ((FilmstripView) findViewById(R.id.filmstrip_view)).getController(); 1460 mFilmstripController.setImageGap( 1461 getResources().getDimensionPixelSize(R.dimen.camera_film_strip_gap)); 1462 mPanoramaViewHelper = new PanoramaViewHelper(this); 1463 mPanoramaViewHelper.onCreate(); 1464 // Set up the camera preview first so the preview shows up ASAP. 1465 mDataAdapter = new CameraDataAdapter(mAppContext, R.color.photo_placeholder); 1466 mDataAdapter.setLocalDataListener(mLocalDataListener); 1467 1468 mPreloader = new Preloader<Integer, AsyncTask>(FILMSTRIP_PRELOAD_AHEAD_ITEMS, mDataAdapter, 1469 mDataAdapter); 1470 1471 mCameraAppUI.getFilmstripContentPanel().setFilmstripListener(mFilmstripListener); 1472 if (mSettingsManager.getBoolean(SettingsManager.SCOPE_GLOBAL, 1473 Keys.KEY_SHOULD_SHOW_REFOCUS_VIEWER_CLING)) { 1474 mCameraAppUI.setupClingForViewer(CameraAppUI.BottomPanel.VIEWER_REFOCUS); 1475 } 1476 1477 mLocationManager = new LocationManager(mAppContext); 1478 1479 mOrientationManager = new OrientationManagerImpl(this); 1480 mOrientationManager.addOnOrientationChangeListener(mMainHandler, this); 1481 1482 setModuleFromModeIndex(getModeIndex()); 1483 mCameraAppUI.prepareModuleUI(); 1484 mCurrentModule.init(this, isSecureCamera(), isCaptureIntent()); 1485 1486 if (!mSecureCamera) { 1487 mFilmstripController.setDataAdapter(mDataAdapter); 1488 if (!isCaptureIntent()) { 1489 mDataAdapter.requestLoad(new Callback<Void>() { 1490 @Override 1491 public void onCallback(Void result) { 1492 fillTemporarySessions(); 1493 } 1494 }); 1495 } 1496 } else { 1497 // Put a lock placeholder as the last image by setting its date to 1498 // 0. 1499 ImageView v = (ImageView) getLayoutInflater().inflate( 1500 R.layout.secure_album_placeholder, null); 1501 v.setTag(R.id.mediadata_tag_viewtype, LocalDataViewType.SECURE_ALBUM_PLACEHOLDER.ordinal()); 1502 v.setOnClickListener(new View.OnClickListener() { 1503 @Override 1504 public void onClick(View view) { 1505 UsageStatistics.instance().changeScreen(NavigationChange.Mode.GALLERY, 1506 NavigationChange.InteractionCause.BUTTON); 1507 startGallery(); 1508 finish(); 1509 } 1510 }); 1511 v.setContentDescription(getString(R.string.accessibility_unlock_to_camera)); 1512 mDataAdapter = new FixedLastDataAdapter( 1513 mAppContext, 1514 mDataAdapter, 1515 new SimpleViewData( 1516 v, 1517 LocalDataViewType.SECURE_ALBUM_PLACEHOLDER, 1518 v.getDrawable().getIntrinsicWidth(), 1519 v.getDrawable().getIntrinsicHeight(), 1520 0, 0)); 1521 // Flush out all the original data. 1522 mDataAdapter.flush(); 1523 mFilmstripController.setDataAdapter(mDataAdapter); 1524 } 1525 1526 setupNfcBeamPush(); 1527 1528 mLocalImagesObserver = new LocalMediaObserver(); 1529 mLocalVideosObserver = new LocalMediaObserver(); 1530 1531 getContentResolver().registerContentObserver( 1532 MediaStore.Images.Media.EXTERNAL_CONTENT_URI, true, 1533 mLocalImagesObserver); 1534 getContentResolver().registerContentObserver( 1535 MediaStore.Video.Media.EXTERNAL_CONTENT_URI, true, 1536 mLocalVideosObserver); 1537 mMemoryManager = getServices().getMemoryManager(); 1538 1539 AsyncTask.THREAD_POOL_EXECUTOR.execute(new Runnable() { 1540 @Override 1541 public void run() { 1542 HashMap memoryData = mMemoryManager.queryMemory(); 1543 UsageStatistics.instance().reportMemoryConsumed(memoryData, 1544 MemoryQuery.REPORT_LABEL_LAUNCH); 1545 } 1546 }); 1547 mMotionManager = getServices().getMotionManager(); 1548 } 1549 1550 /** 1551 * Get the current mode index from the Intent or from persistent 1552 * settings. 1553 */ 1554 public int getModeIndex() { 1555 int modeIndex = -1; 1556 int photoIndex = getResources().getInteger(R.integer.camera_mode_photo); 1557 int videoIndex = getResources().getInteger(R.integer.camera_mode_video); 1558 int gcamIndex = getResources().getInteger(R.integer.camera_mode_gcam); 1559 if (MediaStore.INTENT_ACTION_VIDEO_CAMERA.equals(getIntent().getAction()) 1560 || MediaStore.ACTION_VIDEO_CAPTURE.equals(getIntent().getAction())) { 1561 modeIndex = videoIndex; 1562 } else if (MediaStore.ACTION_IMAGE_CAPTURE.equals(getIntent().getAction())) { 1563 // Capture intent. 1564 modeIndex = photoIndex; 1565 } else if (MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA.equals(getIntent().getAction()) 1566 ||MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE.equals(getIntent() 1567 .getAction()) 1568 || MediaStore.ACTION_IMAGE_CAPTURE_SECURE.equals(getIntent().getAction())) { 1569 modeIndex = mSettingsManager.getInteger(SettingsManager.SCOPE_GLOBAL, 1570 Keys.KEY_CAMERA_MODULE_LAST_USED); 1571 1572 // For upgraders who have not seen the aspect ratio selection screen, 1573 // we need to drop them back in the photo module and have them select 1574 // aspect ratio. 1575 // TODO: Move this to SettingsManager as an upgrade procedure. 1576 if (!mSettingsManager.getBoolean(SettingsManager.SCOPE_GLOBAL, 1577 Keys.KEY_USER_SELECTED_ASPECT_RATIO)) { 1578 modeIndex = photoIndex; 1579 } 1580 } else { 1581 // If the activity has not been started using an explicit intent, 1582 // read the module index from the last time the user changed modes 1583 modeIndex = mSettingsManager.getInteger(SettingsManager.SCOPE_GLOBAL, 1584 Keys.KEY_STARTUP_MODULE_INDEX); 1585 if ((modeIndex == gcamIndex && 1586 !GcamHelper.hasGcamAsSeparateModule()) || modeIndex < 0) { 1587 modeIndex = photoIndex; 1588 } 1589 } 1590 return modeIndex; 1591 } 1592 1593 /** 1594 * Call this whenever the mode drawer or filmstrip change the visibility 1595 * state. 1596 */ 1597 private void updatePreviewVisibility() { 1598 if (mCurrentModule == null) { 1599 return; 1600 } 1601 1602 int visibility = getPreviewVisibility(); 1603 mCameraAppUI.onPreviewVisiblityChanged(visibility); 1604 updatePreviewRendering(visibility); 1605 mCurrentModule.onPreviewVisibilityChanged(visibility); 1606 } 1607 1608 private void updatePreviewRendering(int visibility) { 1609 if (visibility == ModuleController.VISIBILITY_HIDDEN) { 1610 mCameraAppUI.pausePreviewRendering(); 1611 } else { 1612 mCameraAppUI.resumePreviewRendering(); 1613 } 1614 } 1615 1616 private int getPreviewVisibility() { 1617 if (mFilmstripCoversPreview) { 1618 return ModuleController.VISIBILITY_HIDDEN; 1619 } else if (mModeListVisible){ 1620 return ModuleController.VISIBILITY_COVERED; 1621 } else { 1622 return ModuleController.VISIBILITY_VISIBLE; 1623 } 1624 } 1625 1626 private void setRotationAnimation() { 1627 int rotationAnimation = WindowManager.LayoutParams.ROTATION_ANIMATION_ROTATE; 1628 rotationAnimation = WindowManager.LayoutParams.ROTATION_ANIMATION_CROSSFADE; 1629 Window win = getWindow(); 1630 WindowManager.LayoutParams winParams = win.getAttributes(); 1631 winParams.rotationAnimation = rotationAnimation; 1632 win.setAttributes(winParams); 1633 } 1634 1635 @Override 1636 public void onUserInteraction() { 1637 super.onUserInteraction(); 1638 if (!isFinishing()) { 1639 keepScreenOnForAWhile(); 1640 } 1641 } 1642 1643 @Override 1644 public boolean dispatchTouchEvent(MotionEvent ev) { 1645 boolean result = super.dispatchTouchEvent(ev); 1646 if (ev.getActionMasked() == MotionEvent.ACTION_DOWN) { 1647 // Real deletion is postponed until the next user interaction after 1648 // the gesture that triggers deletion. Until real deletion is 1649 // performed, users can click the undo button to bring back the 1650 // image that they chose to delete. 1651 if (mPendingDeletion && !mIsUndoingDeletion) { 1652 performDeletion(); 1653 } 1654 } 1655 return result; 1656 } 1657 1658 @Override 1659 public void onPauseTasks() { 1660 CameraPerformanceTracker.onEvent(CameraPerformanceTracker.ACTIVITY_PAUSE); 1661 1662 /* 1663 * Save the last module index after all secure camera and icon launches, 1664 * not just on mode switches. 1665 * 1666 * Right now we exclude capture intents from this logic, because we also 1667 * ignore the cross-Activity recovery logic in onStart for capture intents. 1668 */ 1669 if (!isCaptureIntent()) { 1670 mSettingsManager.set(SettingsManager.SCOPE_GLOBAL, 1671 Keys.KEY_STARTUP_MODULE_INDEX, 1672 mCurrentModeIndex); 1673 } 1674 1675 mPaused = true; 1676 mPeekAnimationHandler = null; 1677 mPeekAnimationThread.quitSafely(); 1678 mPeekAnimationThread = null; 1679 1680 // Delete photos that are pending deletion 1681 performDeletion(); 1682 mCurrentModule.pause(); 1683 mOrientationManager.pause(); 1684 mPanoramaViewHelper.onPause(); 1685 1686 mLocalImagesObserver.setForegroundChangeListener(null); 1687 mLocalImagesObserver.setActivityPaused(true); 1688 mLocalVideosObserver.setActivityPaused(true); 1689 mPreloader.cancelAllLoads(); 1690 resetScreenOn(); 1691 1692 mMotionManager.stop(); 1693 1694 UsageStatistics.instance().backgrounded(); 1695 1696 // Camera is in fatal state. A fatal dialog is presented to users, but users just hit home 1697 // button. Let's just kill the process. 1698 if (mCameraFatalError && !isFinishing()) { 1699 Log.v(TAG, "onPause when camera is in fatal state, call Activity.finish()"); 1700 finish(); 1701 } else { 1702 // Close the camera and wait for the operation done. 1703 mCameraController.closeCamera(true); 1704 } 1705 } 1706 1707 @Override 1708 public void onResumeTasks() { 1709 CameraPerformanceTracker.onEvent(CameraPerformanceTracker.ACTIVITY_RESUME); 1710 Log.v(TAG, "Build info: " + Build.DISPLAY); 1711 1712 mPaused = false; 1713 updateStorageSpaceAndHint(null); 1714 1715 mLastLayoutOrientation = getResources().getConfiguration().orientation; 1716 1717 // TODO: Handle this in OrientationManager. 1718 // Auto-rotate off 1719 if (Settings.System.getInt(getContentResolver(), 1720 Settings.System.ACCELEROMETER_ROTATION, 0) == 0) { 1721 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); 1722 mAutoRotateScreen = false; 1723 } else { 1724 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR); 1725 mAutoRotateScreen = true; 1726 } 1727 1728 // Foreground event logging. ACTION_STILL_IMAGE_CAMERA and 1729 // INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE are double logged due to 1730 // lockscreen onResume->onPause->onResume sequence. 1731 int source; 1732 String action = getIntent().getAction(); 1733 if (action == null) { 1734 source = ForegroundSource.UNKNOWN_SOURCE; 1735 } else { 1736 switch (action) { 1737 case MediaStore.ACTION_IMAGE_CAPTURE: 1738 source = ForegroundSource.ACTION_IMAGE_CAPTURE; 1739 break; 1740 case MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA: 1741 // was UNKNOWN_SOURCE in Fishlake. 1742 source = ForegroundSource.ACTION_STILL_IMAGE_CAMERA; 1743 break; 1744 case MediaStore.INTENT_ACTION_VIDEO_CAMERA: 1745 // was UNKNOWN_SOURCE in Fishlake. 1746 source = ForegroundSource.ACTION_VIDEO_CAMERA; 1747 break; 1748 case MediaStore.ACTION_VIDEO_CAPTURE: 1749 source = ForegroundSource.ACTION_VIDEO_CAPTURE; 1750 break; 1751 case MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE: 1752 // was ACTION_IMAGE_CAPTURE_SECURE in Fishlake. 1753 source = ForegroundSource.ACTION_STILL_IMAGE_CAMERA_SECURE; 1754 break; 1755 case MediaStore.ACTION_IMAGE_CAPTURE_SECURE: 1756 source = ForegroundSource.ACTION_IMAGE_CAPTURE_SECURE; 1757 break; 1758 case Intent.ACTION_MAIN: 1759 source = ForegroundSource.ACTION_MAIN; 1760 break; 1761 default: 1762 source = ForegroundSource.UNKNOWN_SOURCE; 1763 break; 1764 } 1765 } 1766 UsageStatistics.instance().foregrounded(source, currentUserInterfaceMode()); 1767 1768 mGalleryIntent = IntentHelper.getGalleryIntent(mAppContext); 1769 if (ApiHelper.isLOrHigher()) { 1770 // hide the up affordance for L devices, it's not very Materially 1771 mActionBar.setDisplayShowHomeEnabled(false); 1772 } 1773 1774 mOrientationManager.resume(); 1775 mPeekAnimationThread = new HandlerThread("Peek animation"); 1776 mPeekAnimationThread.start(); 1777 mPeekAnimationHandler = new PeekAnimationHandler(mPeekAnimationThread.getLooper()); 1778 1779 mCurrentModule.hardResetSettings(mSettingsManager); 1780 mCurrentModule.resume(); 1781 UsageStatistics.instance().changeScreen(currentUserInterfaceMode(), 1782 NavigationChange.InteractionCause.BUTTON); 1783 setSwipingEnabled(true); 1784 1785 if (!mResetToPreviewOnResume) { 1786 LocalData data = mDataAdapter.getLocalData(mFilmstripController.getCurrentId()); 1787 if (data != null) { 1788 mDataAdapter.refresh(data.getUri()); 1789 } 1790 } 1791 // The share button might be disabled to avoid double tapping. 1792 mCameraAppUI.getFilmstripBottomControls().setShareEnabled(true); 1793 // Default is showing the preview, unless disabled by explicitly 1794 // starting an activity we want to return from to the filmstrip rather 1795 // than the preview. 1796 mResetToPreviewOnResume = true; 1797 1798 if (mLocalVideosObserver.isMediaDataChangedDuringPause() 1799 || mLocalImagesObserver.isMediaDataChangedDuringPause()) { 1800 if (!mSecureCamera) { 1801 // If it's secure camera, requestLoad() should not be called 1802 // as it will load all the data. 1803 if (!mFilmstripVisible) { 1804 mDataAdapter.requestLoad(new Callback<Void>() { 1805 @Override 1806 public void onCallback(Void result) { 1807 fillTemporarySessions(); 1808 } 1809 }); 1810 } else { 1811 mDataAdapter.requestLoadNewPhotos(); 1812 } 1813 } 1814 } 1815 mLocalImagesObserver.setActivityPaused(false); 1816 mLocalVideosObserver.setActivityPaused(false); 1817 if (!mSecureCamera) { 1818 mLocalImagesObserver.setForegroundChangeListener( 1819 new LocalMediaObserver.ChangeListener() { 1820 @Override 1821 public void onChange() { 1822 mDataAdapter.requestLoadNewPhotos(); 1823 } 1824 }); 1825 } 1826 1827 keepScreenOnForAWhile(); 1828 1829 // Lights-out mode at all times. 1830 final View rootView = findViewById(R.id.activity_root_view); 1831 mLightsOutRunnable.run(); 1832 getWindow().getDecorView().setOnSystemUiVisibilityChangeListener( 1833 new OnSystemUiVisibilityChangeListener() { 1834 @Override 1835 public void onSystemUiVisibilityChange(int visibility) { 1836 mMainHandler.removeCallbacks(mLightsOutRunnable); 1837 mMainHandler.postDelayed(mLightsOutRunnable, LIGHTS_OUT_DELAY_MS); 1838 } 1839 }); 1840 1841 mPanoramaViewHelper.onResume(); 1842 ReleaseHelper.showReleaseInfoDialogOnStart(this, mSettingsManager); 1843 syncLocationManagerSetting(); 1844 1845 final int previewVisibility = getPreviewVisibility(); 1846 updatePreviewRendering(previewVisibility); 1847 1848 mMotionManager.start(); 1849 } 1850 1851 private void fillTemporarySessions() { 1852 if (mSecureCamera) { 1853 return; 1854 } 1855 // There might be sessions still in flight (processed by our service). 1856 // Make sure they're added to the filmstrip. 1857 getServices().getCaptureSessionManager().fillTemporarySession(mSessionListener); 1858 } 1859 1860 @Override 1861 public void onStartTasks() { 1862 mIsActivityRunning = true; 1863 mPanoramaViewHelper.onStart(); 1864 1865 /* 1866 * If we're starting after launching a different Activity (lockscreen), 1867 * we need to use the last mode used in the other Activity, and 1868 * not the old one from this Activity. 1869 * 1870 * This needs to happen before CameraAppUI.resume() in order to set the 1871 * mode cover icon to the actual last mode used. 1872 * 1873 * Right now we exclude capture intents from this logic. 1874 */ 1875 int modeIndex = getModeIndex(); 1876 if (!isCaptureIntent() && mCurrentModeIndex != modeIndex) { 1877 onModeSelected(modeIndex); 1878 } 1879 1880 if (mResetToPreviewOnResume) { 1881 mCameraAppUI.resume(); 1882 mResetToPreviewOnResume = false; 1883 } 1884 } 1885 1886 @Override 1887 protected void onStopTasks() { 1888 mIsActivityRunning = false; 1889 mPanoramaViewHelper.onStop(); 1890 1891 mLocationManager.disconnect(); 1892 } 1893 1894 @Override 1895 public void onDestroyTasks() { 1896 if (mSecureCamera) { 1897 unregisterReceiver(mScreenOffReceiver); 1898 } 1899 mActionBar.removeOnMenuVisibilityListener(mOnMenuVisibilityListener); 1900 mSettingsManager.removeAllListeners(); 1901 mCameraController.removeCallbackReceiver(); 1902 getContentResolver().unregisterContentObserver(mLocalImagesObserver); 1903 getContentResolver().unregisterContentObserver(mLocalVideosObserver); 1904 getServices().getCaptureSessionManager().removeSessionListener(mSessionListener); 1905 mCameraAppUI.onDestroy(); 1906 mModeListView.setVisibilityChangedListener(null); 1907 mCameraController = null; 1908 mSettingsManager = null; 1909 mOrientationManager = null; 1910 mButtonManager = null; 1911 mSoundPlayer.release(); 1912 CameraAgentFactory.recycle(CameraAgentFactory.CameraApi.API_1); 1913 CameraAgentFactory.recycle(CameraAgentFactory.CameraApi.AUTO); 1914 } 1915 1916 @Override 1917 public void onConfigurationChanged(Configuration config) { 1918 super.onConfigurationChanged(config); 1919 Log.v(TAG, "onConfigurationChanged"); 1920 if (config.orientation == Configuration.ORIENTATION_UNDEFINED) { 1921 return; 1922 } 1923 1924 if (mLastLayoutOrientation != config.orientation) { 1925 mLastLayoutOrientation = config.orientation; 1926 mCurrentModule.onLayoutOrientationChanged( 1927 mLastLayoutOrientation == Configuration.ORIENTATION_LANDSCAPE); 1928 } 1929 } 1930 1931 @Override 1932 public boolean onKeyDown(int keyCode, KeyEvent event) { 1933 if (!mFilmstripVisible) { 1934 if (mCurrentModule.onKeyDown(keyCode, event)) { 1935 return true; 1936 } 1937 // Prevent software keyboard or voice search from showing up. 1938 if (keyCode == KeyEvent.KEYCODE_SEARCH 1939 || keyCode == KeyEvent.KEYCODE_MENU) { 1940 if (event.isLongPress()) { 1941 return true; 1942 } 1943 } 1944 } 1945 1946 return super.onKeyDown(keyCode, event); 1947 } 1948 1949 @Override 1950 public boolean onKeyUp(int keyCode, KeyEvent event) { 1951 if (!mFilmstripVisible) { 1952 // If a module is in the middle of capture, it should 1953 // consume the key event. 1954 if (mCurrentModule.onKeyUp(keyCode, event)) { 1955 return true; 1956 } else if (keyCode == KeyEvent.KEYCODE_MENU 1957 || keyCode == KeyEvent.KEYCODE_DPAD_LEFT) { 1958 // Let the mode list view consume the event. 1959 mCameraAppUI.openModeList(); 1960 return true; 1961 } else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) { 1962 mCameraAppUI.showFilmstrip(); 1963 return true; 1964 } 1965 } else { 1966 if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) { 1967 mFilmstripController.goToNextItem(); 1968 return true; 1969 } else if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) { 1970 boolean wentToPrevious = mFilmstripController.goToPreviousItem(); 1971 if (!wentToPrevious) { 1972 // at beginning of filmstrip, hide and go back to preview 1973 mCameraAppUI.hideFilmstrip(); 1974 } 1975 return true; 1976 } 1977 } 1978 return super.onKeyUp(keyCode, event); 1979 } 1980 1981 @Override 1982 public void onBackPressed() { 1983 if (!mCameraAppUI.onBackPressed()) { 1984 if (!mCurrentModule.onBackPressed()) { 1985 super.onBackPressed(); 1986 } 1987 } 1988 } 1989 1990 @Override 1991 public boolean isAutoRotateScreen() { 1992 // TODO: Move to OrientationManager. 1993 return mAutoRotateScreen; 1994 } 1995 1996 @Override 1997 public boolean onCreateOptionsMenu(Menu menu) { 1998 MenuInflater inflater = getMenuInflater(); 1999 inflater.inflate(R.menu.filmstrip_menu, menu); 2000 mActionBarMenu = menu; 2001 2002 // add a button for launching the gallery 2003 if (mGalleryIntent != null) { 2004 CharSequence appName = IntentHelper.getGalleryAppName(mAppContext, mGalleryIntent); 2005 if (appName != null) { 2006 MenuItem menuItem = menu.add(appName); 2007 menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); 2008 menuItem.setIntent(mGalleryIntent); 2009 2010 Drawable galleryLogo = IntentHelper.getGalleryIcon(mAppContext, mGalleryIntent); 2011 if (galleryLogo != null) { 2012 menuItem.setIcon(galleryLogo); 2013 } 2014 } 2015 } 2016 2017 return super.onCreateOptionsMenu(menu); 2018 } 2019 2020 @Override 2021 public boolean onPrepareOptionsMenu(Menu menu) { 2022 if (isSecureCamera() && !ApiHelper.isLOrHigher()) { 2023 // Compatibility pre-L: launching new activities right above 2024 // lockscreen does not reliably work, only show help if not secure 2025 menu.removeItem(R.id.action_help_and_feedback); 2026 } 2027 2028 return super.onPrepareOptionsMenu(menu); 2029 } 2030 2031 protected long getStorageSpaceBytes() { 2032 synchronized (mStorageSpaceLock) { 2033 return mStorageSpaceBytes; 2034 } 2035 } 2036 2037 protected interface OnStorageUpdateDoneListener { 2038 public void onStorageUpdateDone(long bytes); 2039 } 2040 2041 protected void updateStorageSpaceAndHint(final OnStorageUpdateDoneListener callback) { 2042 /* 2043 * We execute disk operations on a background thread in order to 2044 * free up the UI thread. Synchronizing on the lock below ensures 2045 * that when getStorageSpaceBytes is called, the main thread waits 2046 * until this method has completed. 2047 * 2048 * However, .execute() does not ensure this execution block will be 2049 * run right away (.execute() schedules this AsyncTask for sometime 2050 * in the future. executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) 2051 * tries to execute the task in parellel with other AsyncTasks, but 2052 * there's still no guarantee). 2053 * e.g. don't call this then immediately call getStorageSpaceBytes(). 2054 * Instead, pass in an OnStorageUpdateDoneListener. 2055 */ 2056 (new AsyncTask<Void, Void, Long>() { 2057 @Override 2058 protected Long doInBackground(Void ... arg) { 2059 synchronized (mStorageSpaceLock) { 2060 mStorageSpaceBytes = Storage.getAvailableSpace(); 2061 return mStorageSpaceBytes; 2062 } 2063 } 2064 2065 @Override 2066 protected void onPostExecute(Long bytes) { 2067 updateStorageHint(bytes); 2068 // This callback returns after I/O to check disk, so we could be 2069 // pausing and shutting down. If so, don't bother invoking. 2070 if (callback != null && !mPaused) { 2071 callback.onStorageUpdateDone(bytes); 2072 } else { 2073 Log.v(TAG, "ignoring storage callback after activity pause"); 2074 } 2075 } 2076 }).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); 2077 } 2078 2079 protected void updateStorageHint(long storageSpace) { 2080 if (!mIsActivityRunning) { 2081 return; 2082 } 2083 2084 String message = null; 2085 if (storageSpace == Storage.UNAVAILABLE) { 2086 message = getString(R.string.no_storage); 2087 } else if (storageSpace == Storage.PREPARING) { 2088 message = getString(R.string.preparing_sd); 2089 } else if (storageSpace == Storage.UNKNOWN_SIZE) { 2090 message = getString(R.string.access_sd_fail); 2091 } else if (storageSpace <= Storage.LOW_STORAGE_THRESHOLD_BYTES) { 2092 message = getString(R.string.spaceIsLow_content); 2093 } 2094 2095 if (message != null) { 2096 Log.w(TAG, "Storage warning: " + message); 2097 if (mStorageHint == null) { 2098 mStorageHint = OnScreenHint.makeText(CameraActivity.this, message); 2099 } else { 2100 mStorageHint.setText(message); 2101 } 2102 mStorageHint.show(); 2103 UsageStatistics.instance().storageWarning(storageSpace); 2104 2105 // Disable all user interactions, 2106 mCameraAppUI.setDisableAllUserInteractions(true); 2107 } else if (mStorageHint != null) { 2108 mStorageHint.cancel(); 2109 mStorageHint = null; 2110 2111 // Re-enable all user interactions. 2112 mCameraAppUI.setDisableAllUserInteractions(false); 2113 } 2114 } 2115 2116 protected void setResultEx(int resultCode) { 2117 mResultCodeForTesting = resultCode; 2118 setResult(resultCode); 2119 } 2120 2121 protected void setResultEx(int resultCode, Intent data) { 2122 mResultCodeForTesting = resultCode; 2123 mResultDataForTesting = data; 2124 setResult(resultCode, data); 2125 } 2126 2127 public int getResultCode() { 2128 return mResultCodeForTesting; 2129 } 2130 2131 public Intent getResultData() { 2132 return mResultDataForTesting; 2133 } 2134 2135 public boolean isSecureCamera() { 2136 return mSecureCamera; 2137 } 2138 2139 @Override 2140 public boolean isPaused() { 2141 return mPaused; 2142 } 2143 2144 @Override 2145 public int getPreferredChildModeIndex(int modeIndex) { 2146 if (modeIndex == getResources().getInteger(R.integer.camera_mode_photo)) { 2147 boolean hdrPlusOn = Keys.isHdrPlusOn(mSettingsManager); 2148 if (hdrPlusOn && GcamHelper.hasGcamAsSeparateModule()) { 2149 modeIndex = getResources().getInteger(R.integer.camera_mode_gcam); 2150 } 2151 } 2152 return modeIndex; 2153 } 2154 2155 @Override 2156 public void onModeSelected(int modeIndex) { 2157 if (mCurrentModeIndex == modeIndex) { 2158 return; 2159 } 2160 2161 CameraPerformanceTracker.onEvent(CameraPerformanceTracker.MODE_SWITCH_START); 2162 // Record last used camera mode for quick switching 2163 if (modeIndex == getResources().getInteger(R.integer.camera_mode_photo) 2164 || modeIndex == getResources().getInteger(R.integer.camera_mode_gcam)) { 2165 mSettingsManager.set(SettingsManager.SCOPE_GLOBAL, 2166 Keys.KEY_CAMERA_MODULE_LAST_USED, 2167 modeIndex); 2168 } 2169 2170 closeModule(mCurrentModule); 2171 2172 // Select the correct module index from the mode switcher index. 2173 modeIndex = getPreferredChildModeIndex(modeIndex); 2174 setModuleFromModeIndex(modeIndex); 2175 2176 mCameraAppUI.resetBottomControls(mCurrentModule, modeIndex); 2177 mCameraAppUI.addShutterListener(mCurrentModule); 2178 openModule(mCurrentModule); 2179 mCurrentModule.onOrientationChanged(mLastRawOrientation); 2180 // Store the module index so we can use it the next time the Camera 2181 // starts up. 2182 mSettingsManager.set(SettingsManager.SCOPE_GLOBAL, 2183 Keys.KEY_STARTUP_MODULE_INDEX, modeIndex); 2184 } 2185 2186 /** 2187 * Shows the settings dialog. 2188 */ 2189 @Override 2190 public void onSettingsSelected() { 2191 UsageStatistics.instance().controlUsed( 2192 eventprotos.ControlEvent.ControlType.OVERALL_SETTINGS); 2193 Intent intent = new Intent(this, CameraSettingsActivity.class); 2194 startActivity(intent); 2195 } 2196 2197 @Override 2198 public void freezeScreenUntilPreviewReady() { 2199 mCameraAppUI.freezeScreenUntilPreviewReady(); 2200 } 2201 2202 /** 2203 * Sets the mCurrentModuleIndex, creates a new module instance for the given 2204 * index an sets it as mCurrentModule. 2205 */ 2206 private void setModuleFromModeIndex(int modeIndex) { 2207 ModuleManagerImpl.ModuleAgent agent = mModuleManager.getModuleAgent(modeIndex); 2208 if (agent == null) { 2209 return; 2210 } 2211 if (!agent.requestAppForCamera()) { 2212 mCameraController.closeCamera(true); 2213 } 2214 mCurrentModeIndex = agent.getModuleId(); 2215 mCurrentModule = (CameraModule) agent.createModule(this); 2216 } 2217 2218 @Override 2219 public SettingsManager getSettingsManager() { 2220 return mSettingsManager; 2221 } 2222 2223 @Override 2224 public CameraServices getServices() { 2225 return (CameraServices) getApplication(); 2226 } 2227 2228 public List<String> getSupportedModeNames() { 2229 List<Integer> indices = mModuleManager.getSupportedModeIndexList(); 2230 List<String> supported = new ArrayList<String>(); 2231 2232 for (Integer modeIndex : indices) { 2233 String name = CameraUtil.getCameraModeText(modeIndex, mAppContext); 2234 if (name != null && !name.equals("")) { 2235 supported.add(name); 2236 } 2237 } 2238 return supported; 2239 } 2240 2241 @Override 2242 public ButtonManager getButtonManager() { 2243 if (mButtonManager == null) { 2244 mButtonManager = new ButtonManager(this); 2245 } 2246 return mButtonManager; 2247 } 2248 2249 @Override 2250 public SoundPlayer getSoundPlayer() { 2251 return mSoundPlayer; 2252 } 2253 2254 /** 2255 * Creates an AlertDialog appropriate for choosing whether to enable 2256 * location on the first run of the app. 2257 */ 2258 public AlertDialog getFirstTimeLocationAlert() { 2259 AlertDialog.Builder builder = new AlertDialog.Builder(this); 2260 builder = SettingsUtil.getFirstTimeLocationAlertBuilder(builder, new Callback<Boolean>() { 2261 @Override 2262 public void onCallback(Boolean locationOn) { 2263 Keys.setLocation(mSettingsManager, locationOn, mLocationManager); 2264 } 2265 }); 2266 if (builder != null) { 2267 return builder.create(); 2268 } else { 2269 return null; 2270 } 2271 } 2272 2273 /** 2274 * Launches an ACTION_EDIT intent for the given local data item. If 2275 * 'withTinyPlanet' is set, this will show a disambig dialog first to let 2276 * the user start either the tiny planet editor or another photo edior. 2277 * 2278 * @param data The data item to edit. 2279 */ 2280 public void launchEditor(LocalData data) { 2281 Intent intent = new Intent(Intent.ACTION_EDIT) 2282 .setDataAndType(data.getUri(), data.getMimeType()) 2283 .setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 2284 try { 2285 launchActivityByIntent(intent); 2286 } catch (ActivityNotFoundException e) { 2287 final String msgEditWith = getResources().getString(R.string.edit_with); 2288 launchActivityByIntent(Intent.createChooser(intent, msgEditWith)); 2289 } 2290 } 2291 2292 @Override 2293 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { 2294 super.onCreateContextMenu(menu, v, menuInfo); 2295 2296 MenuInflater inflater = getMenuInflater(); 2297 inflater.inflate(R.menu.filmstrip_context_menu, menu); 2298 } 2299 2300 @Override 2301 public boolean onContextItemSelected(MenuItem item) { 2302 switch (item.getItemId()) { 2303 case R.id.tiny_planet_editor: 2304 mMyFilmstripBottomControlListener.onTinyPlanet(); 2305 return true; 2306 case R.id.photo_editor: 2307 mMyFilmstripBottomControlListener.onEdit(); 2308 return true; 2309 } 2310 return false; 2311 } 2312 2313 /** 2314 * Launch the tiny planet editor. 2315 * 2316 * @param data The data must be a 360 degree stereographically mapped 2317 * panoramic image. It will not be modified, instead a new item 2318 * with the result will be added to the filmstrip. 2319 */ 2320 public void launchTinyPlanetEditor(LocalData data) { 2321 TinyPlanetFragment fragment = new TinyPlanetFragment(); 2322 Bundle bundle = new Bundle(); 2323 bundle.putString(TinyPlanetFragment.ARGUMENT_URI, data.getUri().toString()); 2324 bundle.putString(TinyPlanetFragment.ARGUMENT_TITLE, data.getTitle()); 2325 fragment.setArguments(bundle); 2326 fragment.show(getFragmentManager(), "tiny_planet"); 2327 } 2328 2329 /** 2330 * Returns what UI mode (capture mode or filmstrip) we are in. 2331 * Returned number one of {@link com.google.common.logging.eventprotos.NavigationChange.Mode} 2332 */ 2333 private int currentUserInterfaceMode() { 2334 int mode = NavigationChange.Mode.UNKNOWN_MODE; 2335 if (mCurrentModeIndex == getResources().getInteger(R.integer.camera_mode_photo)) { 2336 mode = NavigationChange.Mode.PHOTO_CAPTURE; 2337 } 2338 if (mCurrentModeIndex == getResources().getInteger(R.integer.camera_mode_video)) { 2339 mode = NavigationChange.Mode.VIDEO_CAPTURE; 2340 } 2341 if (mCurrentModeIndex == getResources().getInteger(R.integer.camera_mode_refocus)) { 2342 mode = NavigationChange.Mode.LENS_BLUR; 2343 } 2344 if (mCurrentModeIndex == getResources().getInteger(R.integer.camera_mode_gcam)) { 2345 mode = NavigationChange.Mode.HDR_PLUS; 2346 } 2347 if (mCurrentModeIndex == getResources().getInteger(R.integer.camera_mode_photosphere)) { 2348 mode = NavigationChange.Mode.PHOTO_SPHERE; 2349 } 2350 if (mCurrentModeIndex == getResources().getInteger(R.integer.camera_mode_panorama)) { 2351 mode = NavigationChange.Mode.PANORAMA; 2352 } 2353 if (mFilmstripVisible) { 2354 mode = NavigationChange.Mode.FILMSTRIP; 2355 } 2356 return mode; 2357 } 2358 2359 private void openModule(CameraModule module) { 2360 module.init(this, isSecureCamera(), isCaptureIntent()); 2361 module.hardResetSettings(mSettingsManager); 2362 if (!mPaused) { 2363 module.resume(); 2364 UsageStatistics.instance().changeScreen(currentUserInterfaceMode(), 2365 NavigationChange.InteractionCause.BUTTON); 2366 updatePreviewVisibility(); 2367 } 2368 } 2369 2370 private void closeModule(CameraModule module) { 2371 module.pause(); 2372 mCameraAppUI.clearModuleUI(); 2373 } 2374 2375 private void performDeletion() { 2376 if (!mPendingDeletion) { 2377 return; 2378 } 2379 hideUndoDeletionBar(false); 2380 mDataAdapter.executeDeletion(); 2381 } 2382 2383 public void showUndoDeletionBar() { 2384 if (mPendingDeletion) { 2385 performDeletion(); 2386 } 2387 Log.v(TAG, "showing undo bar"); 2388 mPendingDeletion = true; 2389 if (mUndoDeletionBar == null) { 2390 ViewGroup v = (ViewGroup) getLayoutInflater().inflate(R.layout.undo_bar, 2391 mAboveFilmstripControlLayout, true); 2392 mUndoDeletionBar = (ViewGroup) v.findViewById(R.id.camera_undo_deletion_bar); 2393 View button = mUndoDeletionBar.findViewById(R.id.camera_undo_deletion_button); 2394 button.setOnClickListener(new View.OnClickListener() { 2395 @Override 2396 public void onClick(View view) { 2397 mDataAdapter.undoDataRemoval(); 2398 hideUndoDeletionBar(true); 2399 } 2400 }); 2401 // Setting undo bar clickable to avoid touch events going through 2402 // the bar to the buttons (eg. edit button, etc) underneath the bar. 2403 mUndoDeletionBar.setClickable(true); 2404 // When there is user interaction going on with the undo button, we 2405 // do not want to hide the undo bar. 2406 button.setOnTouchListener(new View.OnTouchListener() { 2407 @Override 2408 public boolean onTouch(View v, MotionEvent event) { 2409 if (event.getActionMasked() == MotionEvent.ACTION_DOWN) { 2410 mIsUndoingDeletion = true; 2411 } else if (event.getActionMasked() == MotionEvent.ACTION_UP) { 2412 mIsUndoingDeletion = false; 2413 } 2414 return false; 2415 } 2416 }); 2417 } 2418 mUndoDeletionBar.setAlpha(0f); 2419 mUndoDeletionBar.setVisibility(View.VISIBLE); 2420 mUndoDeletionBar.animate().setDuration(200).alpha(1f).setListener(null).start(); 2421 } 2422 2423 private void hideUndoDeletionBar(boolean withAnimation) { 2424 Log.v(TAG, "Hiding undo deletion bar"); 2425 mPendingDeletion = false; 2426 if (mUndoDeletionBar != null) { 2427 if (withAnimation) { 2428 mUndoDeletionBar.animate().setDuration(200).alpha(0f) 2429 .setListener(new Animator.AnimatorListener() { 2430 @Override 2431 public void onAnimationStart(Animator animation) { 2432 // Do nothing. 2433 } 2434 2435 @Override 2436 public void onAnimationEnd(Animator animation) { 2437 mUndoDeletionBar.setVisibility(View.GONE); 2438 } 2439 2440 @Override 2441 public void onAnimationCancel(Animator animation) { 2442 // Do nothing. 2443 } 2444 2445 @Override 2446 public void onAnimationRepeat(Animator animation) { 2447 // Do nothing. 2448 } 2449 }).start(); 2450 } else { 2451 mUndoDeletionBar.setVisibility(View.GONE); 2452 } 2453 } 2454 } 2455 2456 @Override 2457 public void onOrientationChanged(int orientation) { 2458 // We keep the last known orientation. So if the user first orient 2459 // the camera then point the camera to floor or sky, we still have 2460 // the correct orientation. 2461 if (orientation == OrientationManager.ORIENTATION_UNKNOWN) { 2462 return; 2463 } 2464 mLastRawOrientation = orientation; 2465 if (mCurrentModule != null) { 2466 mCurrentModule.onOrientationChanged(orientation); 2467 } 2468 } 2469 2470 /** 2471 * Enable/disable swipe-to-filmstrip. Will always disable swipe if in 2472 * capture intent. 2473 * 2474 * @param enable {@code true} to enable swipe. 2475 */ 2476 public void setSwipingEnabled(boolean enable) { 2477 // TODO: Bring back the functionality. 2478 if (isCaptureIntent()) { 2479 // lockPreview(true); 2480 } else { 2481 // lockPreview(!enable); 2482 } 2483 } 2484 2485 // Accessor methods for getting latency times used in performance testing 2486 public long getFirstPreviewTime() { 2487 if (mCurrentModule instanceof PhotoModule) { 2488 long coverHiddenTime = getCameraAppUI().getCoverHiddenTime(); 2489 if (coverHiddenTime != -1) { 2490 return coverHiddenTime - mOnCreateTime; 2491 } 2492 } 2493 return -1; 2494 } 2495 2496 public long getAutoFocusTime() { 2497 return (mCurrentModule instanceof PhotoModule) ? 2498 ((PhotoModule) mCurrentModule).mAutoFocusTime : -1; 2499 } 2500 2501 public long getShutterLag() { 2502 return (mCurrentModule instanceof PhotoModule) ? 2503 ((PhotoModule) mCurrentModule).mShutterLag : -1; 2504 } 2505 2506 public long getShutterToPictureDisplayedTime() { 2507 return (mCurrentModule instanceof PhotoModule) ? 2508 ((PhotoModule) mCurrentModule).mShutterToPictureDisplayedTime : -1; 2509 } 2510 2511 public long getPictureDisplayedToJpegCallbackTime() { 2512 return (mCurrentModule instanceof PhotoModule) ? 2513 ((PhotoModule) mCurrentModule).mPictureDisplayedToJpegCallbackTime : -1; 2514 } 2515 2516 public long getJpegCallbackFinishTime() { 2517 return (mCurrentModule instanceof PhotoModule) ? 2518 ((PhotoModule) mCurrentModule).mJpegCallbackFinishTime : -1; 2519 } 2520 2521 public long getCaptureStartTime() { 2522 return (mCurrentModule instanceof PhotoModule) ? 2523 ((PhotoModule) mCurrentModule).mCaptureStartTime : -1; 2524 } 2525 2526 public boolean isRecording() { 2527 return (mCurrentModule instanceof VideoModule) ? 2528 ((VideoModule) mCurrentModule).isRecording() : false; 2529 } 2530 2531 public CameraAgent.CameraOpenCallback getCameraOpenErrorCallback() { 2532 return mCameraController; 2533 } 2534 2535 // For debugging purposes only. 2536 public CameraModule getCurrentModule() { 2537 return mCurrentModule; 2538 } 2539 2540 @Override 2541 public void showTutorial(AbstractTutorialOverlay tutorial) { 2542 mCameraAppUI.showTutorial(tutorial, getLayoutInflater()); 2543 } 2544 2545 @Override 2546 public void showErrorAndFinish(int messageId) { 2547 CameraUtil.showErrorAndFinish(this, messageId); 2548 } 2549 2550 /** 2551 * Reads the current location recording settings and passes it on to the 2552 * location manager. 2553 */ 2554 public void syncLocationManagerSetting() { 2555 Keys.syncLocationManager(mSettingsManager, mLocationManager); 2556 } 2557 2558 private void keepScreenOnForAWhile() { 2559 if (mKeepScreenOn) { 2560 return; 2561 } 2562 mMainHandler.removeMessages(MSG_CLEAR_SCREEN_ON_FLAG); 2563 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 2564 mMainHandler.sendEmptyMessageDelayed(MSG_CLEAR_SCREEN_ON_FLAG, SCREEN_DELAY_MS); 2565 } 2566 2567 private void resetScreenOn() { 2568 mKeepScreenOn = false; 2569 mMainHandler.removeMessages(MSG_CLEAR_SCREEN_ON_FLAG); 2570 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 2571 } 2572 2573 /** 2574 * @return {@code true} if the Gallery is launched successfully. 2575 */ 2576 private boolean startGallery() { 2577 if (mGalleryIntent == null) { 2578 return false; 2579 } 2580 try { 2581 UsageStatistics.instance().changeScreen(NavigationChange.Mode.GALLERY, 2582 NavigationChange.InteractionCause.BUTTON); 2583 Intent startGalleryIntent = new Intent(mGalleryIntent); 2584 int currentDataId = mFilmstripController.getCurrentId(); 2585 LocalData currentLocalData = mDataAdapter.getLocalData(currentDataId); 2586 if (currentLocalData != null) { 2587 GalleryHelper.setContentUri(startGalleryIntent, currentLocalData.getUri()); 2588 } 2589 launchActivityByIntent(startGalleryIntent); 2590 } catch (ActivityNotFoundException e) { 2591 Log.w(TAG, "Failed to launch gallery activity, closing"); 2592 } 2593 return false; 2594 } 2595 2596 private void setNfcBeamPushUriFromData(LocalData data) { 2597 final Uri uri = data.getUri(); 2598 if (uri != Uri.EMPTY) { 2599 mNfcPushUris[0] = uri; 2600 } else { 2601 mNfcPushUris[0] = null; 2602 } 2603 } 2604 2605 /** 2606 * Updates the visibility of the filmstrip bottom controls and action bar. 2607 */ 2608 private void updateUiByData(final int dataId) { 2609 final LocalData currentData = mDataAdapter.getLocalData(dataId); 2610 if (currentData == null) { 2611 Log.w(TAG, "Current data ID not found."); 2612 hideSessionProgress(); 2613 return; 2614 } 2615 updateActionBarMenu(currentData); 2616 2617 /* Bottom controls. */ 2618 updateBottomControlsByData(currentData); 2619 2620 if (isSecureCamera()) { 2621 // We cannot show buttons in secure camera since go to other 2622 // activities might create a security hole. 2623 mCameraAppUI.getFilmstripBottomControls().hideControls(); 2624 return; 2625 } 2626 2627 2628 setNfcBeamPushUriFromData(currentData); 2629 2630 if (!mDataAdapter.isMetadataUpdated(dataId)) { 2631 mDataAdapter.updateMetadata(dataId); 2632 } 2633 } 2634 2635 /** 2636 * Updates the bottom controls based on the data. 2637 */ 2638 private void updateBottomControlsByData(final LocalData currentData) { 2639 2640 final CameraAppUI.BottomPanel filmstripBottomPanel = 2641 mCameraAppUI.getFilmstripBottomControls(); 2642 filmstripBottomPanel.showControls(); 2643 filmstripBottomPanel.setEditButtonVisibility( 2644 currentData.isDataActionSupported(LocalData.DATA_ACTION_EDIT)); 2645 filmstripBottomPanel.setShareButtonVisibility( 2646 currentData.isDataActionSupported(LocalData.DATA_ACTION_SHARE)); 2647 filmstripBottomPanel.setDeleteButtonVisibility( 2648 currentData.isDataActionSupported(LocalData.DATA_ACTION_DELETE)); 2649 2650 /* Progress bar */ 2651 2652 Uri contentUri = currentData.getUri(); 2653 CaptureSessionManager sessionManager = getServices() 2654 .getCaptureSessionManager(); 2655 2656 if (sessionManager.hasErrorMessage(contentUri)) { 2657 showProcessError(sessionManager.getErrorMesage(contentUri)); 2658 } else { 2659 filmstripBottomPanel.hideProgressError(); 2660 CaptureSession session = sessionManager.getSession(contentUri); 2661 2662 if (session != null) { 2663 int sessionProgress = session.getProgress(); 2664 2665 if (sessionProgress < 0) { 2666 hideSessionProgress(); 2667 } else { 2668 CharSequence progressMessage = session.getProgressMessage(); 2669 showSessionProgress(progressMessage); 2670 updateSessionProgress(sessionProgress); 2671 } 2672 } else { 2673 hideSessionProgress(); 2674 } 2675 } 2676 2677 /* View button */ 2678 2679 // We need to add this to a separate DB. 2680 final int viewButtonVisibility; 2681 if (PanoramaMetadataLoader.isPanoramaAndUseViewer(currentData)) { 2682 viewButtonVisibility = CameraAppUI.BottomPanel.VIEWER_PHOTO_SPHERE; 2683 } else if (RgbzMetadataLoader.hasRGBZData(currentData)) { 2684 viewButtonVisibility = CameraAppUI.BottomPanel.VIEWER_REFOCUS; 2685 } else { 2686 viewButtonVisibility = CameraAppUI.BottomPanel.VIEWER_NONE; 2687 } 2688 2689 filmstripBottomPanel.setTinyPlanetEnabled( 2690 PanoramaMetadataLoader.isPanorama360(currentData)); 2691 filmstripBottomPanel.setViewerButtonVisibility(viewButtonVisibility); 2692 } 2693 2694 private class PeekAnimationHandler extends Handler { 2695 private class DataAndCallback { 2696 LocalData mData; 2697 com.android.camera.util.Callback<Bitmap> mCallback; 2698 2699 public DataAndCallback(LocalData data, com.android.camera.util.Callback<Bitmap> 2700 callback) { 2701 mData = data; 2702 mCallback = callback; 2703 } 2704 } 2705 2706 public PeekAnimationHandler(Looper looper) { 2707 super(looper); 2708 } 2709 2710 /** 2711 * Starts the animation decoding job and posts a {@code Runnable} back 2712 * when when the decoding is done. 2713 * 2714 * @param data The data item to decode the thumbnail for. 2715 * @param callback {@link com.android.camera.util.Callback} after the 2716 * decoding is done. 2717 */ 2718 public void startDecodingJob(final LocalData data, 2719 final com.android.camera.util.Callback<Bitmap> callback) { 2720 PeekAnimationHandler.this.obtainMessage(0 /** dummy integer **/, 2721 new DataAndCallback(data, callback)).sendToTarget(); 2722 } 2723 2724 @Override 2725 public void handleMessage(Message msg) { 2726 final LocalData data = ((DataAndCallback) msg.obj).mData; 2727 final com.android.camera.util.Callback<Bitmap> callback = 2728 ((DataAndCallback) msg.obj).mCallback; 2729 if (data == null || callback == null) { 2730 return; 2731 } 2732 2733 final Bitmap bitmap; 2734 switch (data.getLocalDataType()) { 2735 case LocalData.LOCAL_IN_PROGRESS_DATA: 2736 byte[] jpegData = Storage.getJpegForSession(data.getUri()); 2737 if (jpegData != null) { 2738 bitmap = BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length); 2739 } else { 2740 bitmap = null; 2741 } 2742 break; 2743 2744 case LocalData.LOCAL_IMAGE: 2745 FileInputStream stream; 2746 try { 2747 stream = new FileInputStream(data.getPath()); 2748 } catch (FileNotFoundException e) { 2749 Log.e(TAG, "File not found:" + data.getPath()); 2750 return; 2751 } 2752 Point dim = CameraUtil.resizeToFill(data.getWidth(), data.getHeight(), 2753 data.getRotation(), mAboveFilmstripControlLayout.getWidth(), 2754 mAboveFilmstripControlLayout.getMeasuredHeight()); 2755 if (data.getRotation() % 180 != 0) { 2756 int dummy = dim.x; 2757 dim.x = dim.y; 2758 dim.y = dummy; 2759 } 2760 bitmap = LocalDataUtil 2761 .loadImageThumbnailFromStream(stream, data.getWidth(), data.getHeight(), 2762 (int) (dim.x * 0.7f), (int) (dim.y * 0.7), 2763 data.getRotation(), MAX_PEEK_BITMAP_PIXELS); 2764 break; 2765 2766 case LocalData.LOCAL_VIDEO: 2767 bitmap = LocalDataUtil.loadVideoThumbnail(data.getPath()); 2768 break; 2769 2770 default: 2771 bitmap = null; 2772 break; 2773 } 2774 2775 if (bitmap == null) { 2776 return; 2777 } 2778 2779 mMainHandler.post(new Runnable() { 2780 @Override 2781 public void run() { 2782 callback.onCallback(bitmap); 2783 } 2784 }); 2785 } 2786 } 2787 2788 private void showDetailsDialog(int dataId) { 2789 final LocalData data = mDataAdapter.getLocalData(dataId); 2790 if (data == null) { 2791 return; 2792 } 2793 MediaDetails details = data.getMediaDetails(getAndroidContext()); 2794 if (details == null) { 2795 return; 2796 } 2797 Dialog detailDialog = DetailsDialog.create(CameraActivity.this, details); 2798 detailDialog.show(); 2799 UsageStatistics.instance().mediaInteraction( 2800 fileNameFromDataID(dataId), MediaInteraction.InteractionType.DETAILS, 2801 NavigationChange.InteractionCause.BUTTON, fileAgeFromDataID(dataId)); 2802 } 2803 2804 /** 2805 * Show or hide action bar items depending on current data type. 2806 */ 2807 private void updateActionBarMenu(LocalData data) { 2808 if (mActionBarMenu == null) { 2809 return; 2810 } 2811 2812 MenuItem detailsMenuItem = mActionBarMenu.findItem(R.id.action_details); 2813 if (detailsMenuItem == null) { 2814 return; 2815 } 2816 2817 int type = data.getLocalDataType(); 2818 boolean showDetails = (type == LocalData.LOCAL_IMAGE) || (type == LocalData.LOCAL_VIDEO); 2819 detailsMenuItem.setVisible(showDetails); 2820 } 2821} 2822