CameraActivity.java revision cc93255f596b47d1a860461dd0d4be697422964f
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 Log.e(TAG, "Camera error callback. error=" + errorCode); 1325 } 1326 @Override 1327 public void onCameraException(RuntimeException ex) { 1328 Log.e(TAG, "Camera Exception", ex); 1329 onFatalError(); 1330 } 1331 @Override 1332 public void onDispatchThreadException(RuntimeException ex) { 1333 Log.e(TAG, "DispatchThread Exception", ex); 1334 onFatalError(); 1335 } 1336 private void onFatalError() { 1337 mCameraFatalError = true; 1338 // If the activity receives exception during onPause, just exit the app. 1339 if (mPaused && !isFinishing()) { 1340 Log.v(TAG, "Fatal error during onPause, call Activity.finish()"); 1341 finish(); 1342 } 1343 CameraUtil.showErrorAndFinish(CameraActivity.this, 1344 R.string.cannot_connect_camera); 1345 } 1346 }; 1347 1348 @Override 1349 public void onNewIntentTasks(Intent intent) { 1350 onModeSelected(getModeIndex()); 1351 } 1352 1353 @Override 1354 public void onCreateTasks(Bundle state) { 1355 CameraPerformanceTracker.onEvent(CameraPerformanceTracker.ACTIVITY_START); 1356 if (!Glide.isSetup()) { 1357 Glide.setup(new GlideBuilder(this) 1358 .setResizeService(new FifoPriorityThreadPoolExecutor(2))); 1359 Glide.get(this).setMemoryCategory(MemoryCategory.HIGH); 1360 } 1361 1362 mOnCreateTime = System.currentTimeMillis(); 1363 mAppContext = getApplicationContext(); 1364 mSoundPlayer = new SoundPlayer(mAppContext); 1365 1366 try { 1367 mCameraManager = OneCameraManager.get(this); 1368 } catch (OneCameraException e) { 1369 Log.d(TAG, "Creating camera manager failed.", e); 1370 CameraUtil.showErrorAndFinish(this, R.string.cannot_connect_camera); 1371 return; 1372 } 1373 1374 // TODO: Try to move all the resources allocation to happen as soon as 1375 // possible so we can call module.init() at the earliest time. 1376 mModuleManager = new ModuleManagerImpl(); 1377 GcamHelper.init(getContentResolver()); 1378 ModulesInfo.setupModules(mAppContext, mModuleManager); 1379 1380 mSettingsManager = getServices().getSettingsManager(); 1381 AppUpgrader appUpgrader = new AppUpgrader(this); 1382 appUpgrader.upgrade(mSettingsManager); 1383 Keys.setDefaults(mSettingsManager, mAppContext); 1384 1385 getWindow().requestFeature(Window.FEATURE_ACTION_BAR); 1386 setContentView(R.layout.activity_main); 1387 1388 mActionBar = getActionBar(); 1389 // set actionbar background to 100% or 50% transparent 1390 if (ApiHelper.isLOrHigher()) { 1391 mActionBar.setBackgroundDrawable(new ColorDrawable(0x00000000)); 1392 } else { 1393 mActionBar.setBackgroundDrawable(new ColorDrawable(0x80000000)); 1394 } 1395 mActionBar.addOnMenuVisibilityListener(mOnMenuVisibilityListener); 1396 1397 mMainHandler = new MainHandler(this, getMainLooper()); 1398 mCameraController = new CameraController(mAppContext, this, mMainHandler, 1399 CameraAgentFactory.getAndroidCameraAgent(this, CameraAgentFactory.CameraApi.API_1), 1400 CameraAgentFactory.getAndroidCameraAgent(this, CameraAgentFactory.CameraApi.AUTO)); 1401 mCameraController.setCameraExceptionHandler( 1402 new CameraExceptionHandler(mCameraExceptionCallback, mMainHandler)); 1403 1404 mModeListView = (ModeListView) findViewById(R.id.mode_list_layout); 1405 mModeListView.init(mModuleManager.getSupportedModeIndexList()); 1406 if (ApiHelper.HAS_ROTATION_ANIMATION) { 1407 setRotationAnimation(); 1408 } 1409 mModeListView.setVisibilityChangedListener(new ModeListVisibilityChangedListener() { 1410 @Override 1411 public void onVisibilityChanged(boolean visible) { 1412 mModeListVisible = visible; 1413 mCameraAppUI.setShutterButtonImportantToA11y(!visible); 1414 updatePreviewVisibility(); 1415 } 1416 }); 1417 1418 // Check if this is in the secure camera mode. 1419 Intent intent = getIntent(); 1420 String action = intent.getAction(); 1421 if (INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE.equals(action) 1422 || ACTION_IMAGE_CAPTURE_SECURE.equals(action)) { 1423 mSecureCamera = true; 1424 } else { 1425 mSecureCamera = intent.getBooleanExtra(SECURE_CAMERA_EXTRA, false); 1426 } 1427 1428 if (mSecureCamera) { 1429 // Change the window flags so that secure camera can show when 1430 // locked 1431 Window win = getWindow(); 1432 WindowManager.LayoutParams params = win.getAttributes(); 1433 params.flags |= WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED; 1434 win.setAttributes(params); 1435 1436 // Filter for screen off so that we can finish secure camera 1437 // activity 1438 // when screen is off. 1439 IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF); 1440 registerReceiver(mScreenOffReceiver, filter); 1441 } 1442 mCameraAppUI = new CameraAppUI(this, 1443 (MainActivityLayout) findViewById(R.id.activity_root_view), isCaptureIntent()); 1444 1445 mCameraAppUI.setFilmstripBottomControlsListener(mMyFilmstripBottomControlListener); 1446 1447 mAboveFilmstripControlLayout = 1448 (FrameLayout) findViewById(R.id.camera_filmstrip_content_layout); 1449 1450 // Add the session listener so we can track the session progress 1451 // updates. 1452 getServices().getCaptureSessionManager().addSessionListener(mSessionListener); 1453 mFilmstripController = ((FilmstripView) findViewById(R.id.filmstrip_view)).getController(); 1454 mFilmstripController.setImageGap( 1455 getResources().getDimensionPixelSize(R.dimen.camera_film_strip_gap)); 1456 mPanoramaViewHelper = new PanoramaViewHelper(this); 1457 mPanoramaViewHelper.onCreate(); 1458 // Set up the camera preview first so the preview shows up ASAP. 1459 mDataAdapter = new CameraDataAdapter(mAppContext, mMainHandler, R.color.photo_placeholder); 1460 mDataAdapter.setLocalDataListener(mLocalDataListener); 1461 1462 mPreloader = new Preloader<Integer, AsyncTask>(FILMSTRIP_PRELOAD_AHEAD_ITEMS, mDataAdapter, 1463 mDataAdapter); 1464 1465 mCameraAppUI.getFilmstripContentPanel().setFilmstripListener(mFilmstripListener); 1466 if (mSettingsManager.getBoolean(SettingsManager.SCOPE_GLOBAL, 1467 Keys.KEY_SHOULD_SHOW_REFOCUS_VIEWER_CLING)) { 1468 mCameraAppUI.setupClingForViewer(CameraAppUI.BottomPanel.VIEWER_REFOCUS); 1469 } 1470 1471 mLocationManager = new LocationManager(mAppContext); 1472 1473 mOrientationManager = new OrientationManagerImpl(this); 1474 mOrientationManager.addOnOrientationChangeListener(mMainHandler, this); 1475 1476 setModuleFromModeIndex(getModeIndex()); 1477 mCameraAppUI.prepareModuleUI(); 1478 mCurrentModule.init(this, isSecureCamera(), isCaptureIntent()); 1479 1480 if (!mSecureCamera) { 1481 mFilmstripController.setDataAdapter(mDataAdapter); 1482 if (!isCaptureIntent()) { 1483 mDataAdapter.requestLoad(new Callback<Void>() { 1484 @Override 1485 public void onCallback(Void result) { 1486 fillTemporarySessions(); 1487 } 1488 }); 1489 } 1490 } else { 1491 // Put a lock placeholder as the last image by setting its date to 1492 // 0. 1493 ImageView v = (ImageView) getLayoutInflater().inflate( 1494 R.layout.secure_album_placeholder, null); 1495 v.setTag(R.id.mediadata_tag_viewtype, LocalDataViewType.SECURE_ALBUM_PLACEHOLDER.ordinal()); 1496 v.setOnClickListener(new View.OnClickListener() { 1497 @Override 1498 public void onClick(View view) { 1499 UsageStatistics.instance().changeScreen(NavigationChange.Mode.GALLERY, 1500 NavigationChange.InteractionCause.BUTTON); 1501 startGallery(); 1502 finish(); 1503 } 1504 }); 1505 v.setContentDescription(getString(R.string.accessibility_unlock_to_camera)); 1506 mDataAdapter = new FixedLastDataAdapter( 1507 mAppContext, 1508 mDataAdapter, 1509 new SimpleViewData( 1510 v, 1511 LocalDataViewType.SECURE_ALBUM_PLACEHOLDER, 1512 v.getDrawable().getIntrinsicWidth(), 1513 v.getDrawable().getIntrinsicHeight(), 1514 0, 0)); 1515 // Flush out all the original data. 1516 mDataAdapter.flush(); 1517 mFilmstripController.setDataAdapter(mDataAdapter); 1518 } 1519 1520 setupNfcBeamPush(); 1521 1522 mLocalImagesObserver = new LocalMediaObserver(); 1523 mLocalVideosObserver = new LocalMediaObserver(); 1524 1525 getContentResolver().registerContentObserver( 1526 MediaStore.Images.Media.EXTERNAL_CONTENT_URI, true, 1527 mLocalImagesObserver); 1528 getContentResolver().registerContentObserver( 1529 MediaStore.Video.Media.EXTERNAL_CONTENT_URI, true, 1530 mLocalVideosObserver); 1531 mMemoryManager = getServices().getMemoryManager(); 1532 1533 AsyncTask.THREAD_POOL_EXECUTOR.execute(new Runnable() { 1534 @Override 1535 public void run() { 1536 HashMap memoryData = mMemoryManager.queryMemory(); 1537 UsageStatistics.instance().reportMemoryConsumed(memoryData, 1538 MemoryQuery.REPORT_LABEL_LAUNCH); 1539 } 1540 }); 1541 mMotionManager = getServices().getMotionManager(); 1542 } 1543 1544 /** 1545 * Get the current mode index from the Intent or from persistent 1546 * settings. 1547 */ 1548 public int getModeIndex() { 1549 int modeIndex = -1; 1550 int photoIndex = getResources().getInteger(R.integer.camera_mode_photo); 1551 int videoIndex = getResources().getInteger(R.integer.camera_mode_video); 1552 int gcamIndex = getResources().getInteger(R.integer.camera_mode_gcam); 1553 if (MediaStore.INTENT_ACTION_VIDEO_CAMERA.equals(getIntent().getAction()) 1554 || MediaStore.ACTION_VIDEO_CAPTURE.equals(getIntent().getAction())) { 1555 modeIndex = videoIndex; 1556 } else if (MediaStore.ACTION_IMAGE_CAPTURE.equals(getIntent().getAction())) { 1557 // Capture intent. 1558 modeIndex = photoIndex; 1559 } else if (MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA.equals(getIntent().getAction()) 1560 ||MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE.equals(getIntent() 1561 .getAction()) 1562 || MediaStore.ACTION_IMAGE_CAPTURE_SECURE.equals(getIntent().getAction())) { 1563 modeIndex = mSettingsManager.getInteger(SettingsManager.SCOPE_GLOBAL, 1564 Keys.KEY_CAMERA_MODULE_LAST_USED); 1565 1566 // For upgraders who have not seen the aspect ratio selection screen, 1567 // we need to drop them back in the photo module and have them select 1568 // aspect ratio. 1569 // TODO: Move this to SettingsManager as an upgrade procedure. 1570 if (!mSettingsManager.getBoolean(SettingsManager.SCOPE_GLOBAL, 1571 Keys.KEY_USER_SELECTED_ASPECT_RATIO)) { 1572 modeIndex = photoIndex; 1573 } 1574 } else { 1575 // If the activity has not been started using an explicit intent, 1576 // read the module index from the last time the user changed modes 1577 modeIndex = mSettingsManager.getInteger(SettingsManager.SCOPE_GLOBAL, 1578 Keys.KEY_STARTUP_MODULE_INDEX); 1579 if ((modeIndex == gcamIndex && 1580 !GcamHelper.hasGcamAsSeparateModule()) || modeIndex < 0) { 1581 modeIndex = photoIndex; 1582 } 1583 } 1584 return modeIndex; 1585 } 1586 1587 /** 1588 * Call this whenever the mode drawer or filmstrip change the visibility 1589 * state. 1590 */ 1591 private void updatePreviewVisibility() { 1592 if (mCurrentModule == null) { 1593 return; 1594 } 1595 1596 int visibility = getPreviewVisibility(); 1597 mCameraAppUI.onPreviewVisiblityChanged(visibility); 1598 updatePreviewRendering(visibility); 1599 mCurrentModule.onPreviewVisibilityChanged(visibility); 1600 } 1601 1602 private void updatePreviewRendering(int visibility) { 1603 if (visibility == ModuleController.VISIBILITY_HIDDEN) { 1604 mCameraAppUI.pausePreviewRendering(); 1605 } else { 1606 mCameraAppUI.resumePreviewRendering(); 1607 } 1608 } 1609 1610 private int getPreviewVisibility() { 1611 if (mFilmstripCoversPreview) { 1612 return ModuleController.VISIBILITY_HIDDEN; 1613 } else if (mModeListVisible){ 1614 return ModuleController.VISIBILITY_COVERED; 1615 } else { 1616 return ModuleController.VISIBILITY_VISIBLE; 1617 } 1618 } 1619 1620 private void setRotationAnimation() { 1621 int rotationAnimation = WindowManager.LayoutParams.ROTATION_ANIMATION_ROTATE; 1622 rotationAnimation = WindowManager.LayoutParams.ROTATION_ANIMATION_CROSSFADE; 1623 Window win = getWindow(); 1624 WindowManager.LayoutParams winParams = win.getAttributes(); 1625 winParams.rotationAnimation = rotationAnimation; 1626 win.setAttributes(winParams); 1627 } 1628 1629 @Override 1630 public void onUserInteraction() { 1631 super.onUserInteraction(); 1632 if (!isFinishing()) { 1633 keepScreenOnForAWhile(); 1634 } 1635 } 1636 1637 @Override 1638 public boolean dispatchTouchEvent(MotionEvent ev) { 1639 boolean result = super.dispatchTouchEvent(ev); 1640 if (ev.getActionMasked() == MotionEvent.ACTION_DOWN) { 1641 // Real deletion is postponed until the next user interaction after 1642 // the gesture that triggers deletion. Until real deletion is 1643 // performed, users can click the undo button to bring back the 1644 // image that they chose to delete. 1645 if (mPendingDeletion && !mIsUndoingDeletion) { 1646 performDeletion(); 1647 } 1648 } 1649 return result; 1650 } 1651 1652 @Override 1653 public void onPauseTasks() { 1654 CameraPerformanceTracker.onEvent(CameraPerformanceTracker.ACTIVITY_PAUSE); 1655 1656 /* 1657 * Save the last module index after all secure camera and icon launches, 1658 * not just on mode switches. 1659 * 1660 * Right now we exclude capture intents from this logic, because we also 1661 * ignore the cross-Activity recovery logic in onStart for capture intents. 1662 */ 1663 if (!isCaptureIntent()) { 1664 mSettingsManager.set(SettingsManager.SCOPE_GLOBAL, 1665 Keys.KEY_STARTUP_MODULE_INDEX, 1666 mCurrentModeIndex); 1667 } 1668 1669 mPaused = true; 1670 mPeekAnimationHandler = null; 1671 mPeekAnimationThread.quitSafely(); 1672 mPeekAnimationThread = null; 1673 1674 // Delete photos that are pending deletion 1675 performDeletion(); 1676 mCurrentModule.pause(); 1677 mOrientationManager.pause(); 1678 mPanoramaViewHelper.onPause(); 1679 1680 mLocalImagesObserver.setForegroundChangeListener(null); 1681 mLocalImagesObserver.setActivityPaused(true); 1682 mLocalVideosObserver.setActivityPaused(true); 1683 mPreloader.cancelAllLoads(); 1684 resetScreenOn(); 1685 1686 mMotionManager.stop(); 1687 1688 UsageStatistics.instance().backgrounded(); 1689 1690 // Camera is in fatal state. A fatal dialog is presented to users, but users just hit home 1691 // button. Let's just kill the process. 1692 if (mCameraFatalError && !isFinishing()) { 1693 Log.v(TAG, "onPause when camera is in fatal state, call Activity.finish()"); 1694 finish(); 1695 } 1696 // Close the camera and wait for the operation done. 1697 mCameraController.closeCamera(true); 1698 } 1699 1700 @Override 1701 public void onResumeTasks() { 1702 CameraPerformanceTracker.onEvent(CameraPerformanceTracker.ACTIVITY_RESUME); 1703 Log.v(TAG, "Build info: " + Build.DISPLAY); 1704 1705 mPaused = false; 1706 updateStorageSpaceAndHint(null); 1707 1708 mLastLayoutOrientation = getResources().getConfiguration().orientation; 1709 1710 // TODO: Handle this in OrientationManager. 1711 // Auto-rotate off 1712 if (Settings.System.getInt(getContentResolver(), 1713 Settings.System.ACCELEROMETER_ROTATION, 0) == 0) { 1714 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); 1715 mAutoRotateScreen = false; 1716 } else { 1717 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR); 1718 mAutoRotateScreen = true; 1719 } 1720 1721 // Foreground event logging. ACTION_STILL_IMAGE_CAMERA and 1722 // INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE are double logged due to 1723 // lockscreen onResume->onPause->onResume sequence. 1724 int source; 1725 String action = getIntent().getAction(); 1726 if (action == null) { 1727 source = ForegroundSource.UNKNOWN_SOURCE; 1728 } else { 1729 switch (action) { 1730 case MediaStore.ACTION_IMAGE_CAPTURE: 1731 source = ForegroundSource.ACTION_IMAGE_CAPTURE; 1732 break; 1733 case MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA: 1734 // was UNKNOWN_SOURCE in Fishlake. 1735 source = ForegroundSource.ACTION_STILL_IMAGE_CAMERA; 1736 break; 1737 case MediaStore.INTENT_ACTION_VIDEO_CAMERA: 1738 // was UNKNOWN_SOURCE in Fishlake. 1739 source = ForegroundSource.ACTION_VIDEO_CAMERA; 1740 break; 1741 case MediaStore.ACTION_VIDEO_CAPTURE: 1742 source = ForegroundSource.ACTION_VIDEO_CAPTURE; 1743 break; 1744 case MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE: 1745 // was ACTION_IMAGE_CAPTURE_SECURE in Fishlake. 1746 source = ForegroundSource.ACTION_STILL_IMAGE_CAMERA_SECURE; 1747 break; 1748 case MediaStore.ACTION_IMAGE_CAPTURE_SECURE: 1749 source = ForegroundSource.ACTION_IMAGE_CAPTURE_SECURE; 1750 break; 1751 case Intent.ACTION_MAIN: 1752 source = ForegroundSource.ACTION_MAIN; 1753 break; 1754 default: 1755 source = ForegroundSource.UNKNOWN_SOURCE; 1756 break; 1757 } 1758 } 1759 UsageStatistics.instance().foregrounded(source, currentUserInterfaceMode()); 1760 1761 mGalleryIntent = IntentHelper.getGalleryIntent(mAppContext); 1762 if (ApiHelper.isLOrHigher()) { 1763 // hide the up affordance for L devices, it's not very Materially 1764 mActionBar.setDisplayShowHomeEnabled(false); 1765 } 1766 1767 mOrientationManager.resume(); 1768 mPeekAnimationThread = new HandlerThread("Peek animation"); 1769 mPeekAnimationThread.start(); 1770 mPeekAnimationHandler = new PeekAnimationHandler(mPeekAnimationThread.getLooper()); 1771 1772 mCurrentModule.hardResetSettings(mSettingsManager); 1773 mCurrentModule.resume(); 1774 UsageStatistics.instance().changeScreen(currentUserInterfaceMode(), 1775 NavigationChange.InteractionCause.BUTTON); 1776 setSwipingEnabled(true); 1777 1778 if (!mResetToPreviewOnResume) { 1779 LocalData data = mDataAdapter.getLocalData(mFilmstripController.getCurrentId()); 1780 if (data != null) { 1781 mDataAdapter.refresh(data.getUri()); 1782 } 1783 } 1784 // The share button might be disabled to avoid double tapping. 1785 mCameraAppUI.getFilmstripBottomControls().setShareEnabled(true); 1786 // Default is showing the preview, unless disabled by explicitly 1787 // starting an activity we want to return from to the filmstrip rather 1788 // than the preview. 1789 mResetToPreviewOnResume = true; 1790 1791 if (mLocalVideosObserver.isMediaDataChangedDuringPause() 1792 || mLocalImagesObserver.isMediaDataChangedDuringPause()) { 1793 if (!mSecureCamera) { 1794 // If it's secure camera, requestLoad() should not be called 1795 // as it will load all the data. 1796 if (!mFilmstripVisible) { 1797 mDataAdapter.requestLoad(new Callback<Void>() { 1798 @Override 1799 public void onCallback(Void result) { 1800 fillTemporarySessions(); 1801 } 1802 }); 1803 } else { 1804 mDataAdapter.requestLoadNewPhotos(); 1805 } 1806 } 1807 } 1808 mLocalImagesObserver.setActivityPaused(false); 1809 mLocalVideosObserver.setActivityPaused(false); 1810 if (!mSecureCamera) { 1811 mLocalImagesObserver.setForegroundChangeListener( 1812 new LocalMediaObserver.ChangeListener() { 1813 @Override 1814 public void onChange() { 1815 mDataAdapter.requestLoadNewPhotos(); 1816 } 1817 }); 1818 } 1819 1820 keepScreenOnForAWhile(); 1821 1822 // Lights-out mode at all times. 1823 final View rootView = findViewById(R.id.activity_root_view); 1824 mLightsOutRunnable.run(); 1825 getWindow().getDecorView().setOnSystemUiVisibilityChangeListener( 1826 new OnSystemUiVisibilityChangeListener() { 1827 @Override 1828 public void onSystemUiVisibilityChange(int visibility) { 1829 mMainHandler.removeCallbacks(mLightsOutRunnable); 1830 mMainHandler.postDelayed(mLightsOutRunnable, LIGHTS_OUT_DELAY_MS); 1831 } 1832 }); 1833 1834 mPanoramaViewHelper.onResume(); 1835 ReleaseHelper.showReleaseInfoDialogOnStart(this, mSettingsManager); 1836 syncLocationManagerSetting(); 1837 1838 final int previewVisibility = getPreviewVisibility(); 1839 updatePreviewRendering(previewVisibility); 1840 1841 mMotionManager.start(); 1842 } 1843 1844 private void fillTemporarySessions() { 1845 if (mSecureCamera) { 1846 return; 1847 } 1848 // There might be sessions still in flight (processed by our service). 1849 // Make sure they're added to the filmstrip. 1850 getServices().getCaptureSessionManager().fillTemporarySession(mSessionListener); 1851 } 1852 1853 @Override 1854 public void onStartTasks() { 1855 mIsActivityRunning = true; 1856 mPanoramaViewHelper.onStart(); 1857 1858 /* 1859 * If we're starting after launching a different Activity (lockscreen), 1860 * we need to use the last mode used in the other Activity, and 1861 * not the old one from this Activity. 1862 * 1863 * This needs to happen before CameraAppUI.resume() in order to set the 1864 * mode cover icon to the actual last mode used. 1865 * 1866 * Right now we exclude capture intents from this logic. 1867 */ 1868 int modeIndex = getModeIndex(); 1869 if (!isCaptureIntent() && mCurrentModeIndex != modeIndex) { 1870 onModeSelected(modeIndex); 1871 } 1872 1873 if (mResetToPreviewOnResume) { 1874 mCameraAppUI.resume(); 1875 mResetToPreviewOnResume = false; 1876 } 1877 } 1878 1879 @Override 1880 protected void onStopTasks() { 1881 mIsActivityRunning = false; 1882 mPanoramaViewHelper.onStop(); 1883 1884 mLocationManager.disconnect(); 1885 } 1886 1887 @Override 1888 public void onDestroyTasks() { 1889 if (mSecureCamera) { 1890 unregisterReceiver(mScreenOffReceiver); 1891 } 1892 mActionBar.removeOnMenuVisibilityListener(mOnMenuVisibilityListener); 1893 mSettingsManager.removeAllListeners(); 1894 mCameraController.removeCallbackReceiver(); 1895 getContentResolver().unregisterContentObserver(mLocalImagesObserver); 1896 getContentResolver().unregisterContentObserver(mLocalVideosObserver); 1897 getServices().getCaptureSessionManager().removeSessionListener(mSessionListener); 1898 mCameraAppUI.onDestroy(); 1899 mModeListView.setVisibilityChangedListener(null); 1900 mCameraController = null; 1901 mSettingsManager = null; 1902 mOrientationManager = null; 1903 mButtonManager = null; 1904 mSoundPlayer.release(); 1905 CameraAgentFactory.recycle(CameraAgentFactory.CameraApi.API_1); 1906 CameraAgentFactory.recycle(CameraAgentFactory.CameraApi.AUTO); 1907 } 1908 1909 @Override 1910 public void onConfigurationChanged(Configuration config) { 1911 super.onConfigurationChanged(config); 1912 Log.v(TAG, "onConfigurationChanged"); 1913 if (config.orientation == Configuration.ORIENTATION_UNDEFINED) { 1914 return; 1915 } 1916 1917 if (mLastLayoutOrientation != config.orientation) { 1918 mLastLayoutOrientation = config.orientation; 1919 mCurrentModule.onLayoutOrientationChanged( 1920 mLastLayoutOrientation == Configuration.ORIENTATION_LANDSCAPE); 1921 } 1922 } 1923 1924 @Override 1925 public boolean onKeyDown(int keyCode, KeyEvent event) { 1926 if (!mFilmstripVisible) { 1927 if (mCurrentModule.onKeyDown(keyCode, event)) { 1928 return true; 1929 } 1930 // Prevent software keyboard or voice search from showing up. 1931 if (keyCode == KeyEvent.KEYCODE_SEARCH 1932 || keyCode == KeyEvent.KEYCODE_MENU) { 1933 if (event.isLongPress()) { 1934 return true; 1935 } 1936 } 1937 } 1938 1939 return super.onKeyDown(keyCode, event); 1940 } 1941 1942 @Override 1943 public boolean onKeyUp(int keyCode, KeyEvent event) { 1944 if (!mFilmstripVisible) { 1945 // If a module is in the middle of capture, it should 1946 // consume the key event. 1947 if (mCurrentModule.onKeyUp(keyCode, event)) { 1948 return true; 1949 } else if (keyCode == KeyEvent.KEYCODE_MENU 1950 || keyCode == KeyEvent.KEYCODE_DPAD_LEFT) { 1951 // Let the mode list view consume the event. 1952 mCameraAppUI.openModeList(); 1953 return true; 1954 } else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) { 1955 mCameraAppUI.showFilmstrip(); 1956 return true; 1957 } 1958 } else { 1959 if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) { 1960 mFilmstripController.goToNextItem(); 1961 return true; 1962 } else if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) { 1963 boolean wentToPrevious = mFilmstripController.goToPreviousItem(); 1964 if (!wentToPrevious) { 1965 // at beginning of filmstrip, hide and go back to preview 1966 mCameraAppUI.hideFilmstrip(); 1967 } 1968 return true; 1969 } 1970 } 1971 return super.onKeyUp(keyCode, event); 1972 } 1973 1974 @Override 1975 public void onBackPressed() { 1976 if (!mCameraAppUI.onBackPressed()) { 1977 if (!mCurrentModule.onBackPressed()) { 1978 super.onBackPressed(); 1979 } 1980 } 1981 } 1982 1983 @Override 1984 public boolean isAutoRotateScreen() { 1985 // TODO: Move to OrientationManager. 1986 return mAutoRotateScreen; 1987 } 1988 1989 @Override 1990 public boolean onCreateOptionsMenu(Menu menu) { 1991 MenuInflater inflater = getMenuInflater(); 1992 inflater.inflate(R.menu.filmstrip_menu, menu); 1993 mActionBarMenu = menu; 1994 1995 // add a button for launching the gallery 1996 if (mGalleryIntent != null) { 1997 CharSequence appName = IntentHelper.getGalleryAppName(mAppContext, mGalleryIntent); 1998 if (appName != null) { 1999 MenuItem menuItem = menu.add(appName); 2000 menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); 2001 menuItem.setIntent(mGalleryIntent); 2002 2003 Drawable galleryLogo = IntentHelper.getGalleryIcon(mAppContext, mGalleryIntent); 2004 if (galleryLogo != null) { 2005 menuItem.setIcon(galleryLogo); 2006 } 2007 } 2008 } 2009 2010 return super.onCreateOptionsMenu(menu); 2011 } 2012 2013 @Override 2014 public boolean onPrepareOptionsMenu(Menu menu) { 2015 if (isSecureCamera() && !ApiHelper.isLOrHigher()) { 2016 // Compatibility pre-L: launching new activities right above 2017 // lockscreen does not reliably work, only show help if not secure 2018 menu.removeItem(R.id.action_help_and_feedback); 2019 } 2020 2021 return super.onPrepareOptionsMenu(menu); 2022 } 2023 2024 protected long getStorageSpaceBytes() { 2025 synchronized (mStorageSpaceLock) { 2026 return mStorageSpaceBytes; 2027 } 2028 } 2029 2030 protected interface OnStorageUpdateDoneListener { 2031 public void onStorageUpdateDone(long bytes); 2032 } 2033 2034 protected void updateStorageSpaceAndHint(final OnStorageUpdateDoneListener callback) { 2035 /* 2036 * We execute disk operations on a background thread in order to 2037 * free up the UI thread. Synchronizing on the lock below ensures 2038 * that when getStorageSpaceBytes is called, the main thread waits 2039 * until this method has completed. 2040 * 2041 * However, .execute() does not ensure this execution block will be 2042 * run right away (.execute() schedules this AsyncTask for sometime 2043 * in the future. executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) 2044 * tries to execute the task in parellel with other AsyncTasks, but 2045 * there's still no guarantee). 2046 * e.g. don't call this then immediately call getStorageSpaceBytes(). 2047 * Instead, pass in an OnStorageUpdateDoneListener. 2048 */ 2049 (new AsyncTask<Void, Void, Long>() { 2050 @Override 2051 protected Long doInBackground(Void ... arg) { 2052 synchronized (mStorageSpaceLock) { 2053 mStorageSpaceBytes = Storage.getAvailableSpace(); 2054 return mStorageSpaceBytes; 2055 } 2056 } 2057 2058 @Override 2059 protected void onPostExecute(Long bytes) { 2060 updateStorageHint(bytes); 2061 // This callback returns after I/O to check disk, so we could be 2062 // pausing and shutting down. If so, don't bother invoking. 2063 if (callback != null && !mPaused) { 2064 callback.onStorageUpdateDone(bytes); 2065 } else { 2066 Log.v(TAG, "ignoring storage callback after activity pause"); 2067 } 2068 } 2069 }).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); 2070 } 2071 2072 protected void updateStorageHint(long storageSpace) { 2073 if (!mIsActivityRunning) { 2074 return; 2075 } 2076 2077 String message = null; 2078 if (storageSpace == Storage.UNAVAILABLE) { 2079 message = getString(R.string.no_storage); 2080 } else if (storageSpace == Storage.PREPARING) { 2081 message = getString(R.string.preparing_sd); 2082 } else if (storageSpace == Storage.UNKNOWN_SIZE) { 2083 message = getString(R.string.access_sd_fail); 2084 } else if (storageSpace <= Storage.LOW_STORAGE_THRESHOLD_BYTES) { 2085 message = getString(R.string.spaceIsLow_content); 2086 } 2087 2088 if (message != null) { 2089 Log.w(TAG, "Storage warning: " + message); 2090 if (mStorageHint == null) { 2091 mStorageHint = OnScreenHint.makeText(CameraActivity.this, message); 2092 } else { 2093 mStorageHint.setText(message); 2094 } 2095 mStorageHint.show(); 2096 UsageStatistics.instance().storageWarning(storageSpace); 2097 2098 // Disable all user interactions, 2099 mCameraAppUI.setDisableAllUserInteractions(true); 2100 } else if (mStorageHint != null) { 2101 mStorageHint.cancel(); 2102 mStorageHint = null; 2103 2104 // Re-enable all user interactions. 2105 mCameraAppUI.setDisableAllUserInteractions(false); 2106 } 2107 } 2108 2109 protected void setResultEx(int resultCode) { 2110 mResultCodeForTesting = resultCode; 2111 setResult(resultCode); 2112 } 2113 2114 protected void setResultEx(int resultCode, Intent data) { 2115 mResultCodeForTesting = resultCode; 2116 mResultDataForTesting = data; 2117 setResult(resultCode, data); 2118 } 2119 2120 public int getResultCode() { 2121 return mResultCodeForTesting; 2122 } 2123 2124 public Intent getResultData() { 2125 return mResultDataForTesting; 2126 } 2127 2128 public boolean isSecureCamera() { 2129 return mSecureCamera; 2130 } 2131 2132 @Override 2133 public boolean isPaused() { 2134 return mPaused; 2135 } 2136 2137 @Override 2138 public int getPreferredChildModeIndex(int modeIndex) { 2139 if (modeIndex == getResources().getInteger(R.integer.camera_mode_photo)) { 2140 boolean hdrPlusOn = Keys.isHdrPlusOn(mSettingsManager); 2141 if (hdrPlusOn && GcamHelper.hasGcamAsSeparateModule()) { 2142 modeIndex = getResources().getInteger(R.integer.camera_mode_gcam); 2143 } 2144 } 2145 return modeIndex; 2146 } 2147 2148 @Override 2149 public void onModeSelected(int modeIndex) { 2150 if (mCurrentModeIndex == modeIndex) { 2151 return; 2152 } 2153 2154 CameraPerformanceTracker.onEvent(CameraPerformanceTracker.MODE_SWITCH_START); 2155 // Record last used camera mode for quick switching 2156 if (modeIndex == getResources().getInteger(R.integer.camera_mode_photo) 2157 || modeIndex == getResources().getInteger(R.integer.camera_mode_gcam)) { 2158 mSettingsManager.set(SettingsManager.SCOPE_GLOBAL, 2159 Keys.KEY_CAMERA_MODULE_LAST_USED, 2160 modeIndex); 2161 } 2162 2163 closeModule(mCurrentModule); 2164 2165 // Select the correct module index from the mode switcher index. 2166 modeIndex = getPreferredChildModeIndex(modeIndex); 2167 setModuleFromModeIndex(modeIndex); 2168 2169 mCameraAppUI.resetBottomControls(mCurrentModule, modeIndex); 2170 mCameraAppUI.addShutterListener(mCurrentModule); 2171 openModule(mCurrentModule); 2172 mCurrentModule.onOrientationChanged(mLastRawOrientation); 2173 // Store the module index so we can use it the next time the Camera 2174 // starts up. 2175 mSettingsManager.set(SettingsManager.SCOPE_GLOBAL, 2176 Keys.KEY_STARTUP_MODULE_INDEX, modeIndex); 2177 } 2178 2179 /** 2180 * Shows the settings dialog. 2181 */ 2182 @Override 2183 public void onSettingsSelected() { 2184 UsageStatistics.instance().controlUsed( 2185 eventprotos.ControlEvent.ControlType.OVERALL_SETTINGS); 2186 Intent intent = new Intent(this, CameraSettingsActivity.class); 2187 startActivity(intent); 2188 } 2189 2190 @Override 2191 public void freezeScreenUntilPreviewReady() { 2192 mCameraAppUI.freezeScreenUntilPreviewReady(); 2193 } 2194 2195 /** 2196 * Sets the mCurrentModuleIndex, creates a new module instance for the given 2197 * index an sets it as mCurrentModule. 2198 */ 2199 private void setModuleFromModeIndex(int modeIndex) { 2200 ModuleManagerImpl.ModuleAgent agent = mModuleManager.getModuleAgent(modeIndex); 2201 if (agent == null) { 2202 return; 2203 } 2204 if (!agent.requestAppForCamera()) { 2205 mCameraController.closeCamera(true); 2206 } 2207 mCurrentModeIndex = agent.getModuleId(); 2208 mCurrentModule = (CameraModule) agent.createModule(this); 2209 } 2210 2211 @Override 2212 public SettingsManager getSettingsManager() { 2213 return mSettingsManager; 2214 } 2215 2216 @Override 2217 public CameraServices getServices() { 2218 return (CameraServices) getApplication(); 2219 } 2220 2221 public List<String> getSupportedModeNames() { 2222 List<Integer> indices = mModuleManager.getSupportedModeIndexList(); 2223 List<String> supported = new ArrayList<String>(); 2224 2225 for (Integer modeIndex : indices) { 2226 String name = CameraUtil.getCameraModeText(modeIndex, mAppContext); 2227 if (name != null && !name.equals("")) { 2228 supported.add(name); 2229 } 2230 } 2231 return supported; 2232 } 2233 2234 @Override 2235 public ButtonManager getButtonManager() { 2236 if (mButtonManager == null) { 2237 mButtonManager = new ButtonManager(this); 2238 } 2239 return mButtonManager; 2240 } 2241 2242 @Override 2243 public SoundPlayer getSoundPlayer() { 2244 return mSoundPlayer; 2245 } 2246 2247 /** 2248 * Creates an AlertDialog appropriate for choosing whether to enable 2249 * location on the first run of the app. 2250 */ 2251 public AlertDialog getFirstTimeLocationAlert() { 2252 AlertDialog.Builder builder = new AlertDialog.Builder(this); 2253 builder = SettingsUtil.getFirstTimeLocationAlertBuilder(builder, new Callback<Boolean>() { 2254 @Override 2255 public void onCallback(Boolean locationOn) { 2256 Keys.setLocation(mSettingsManager, locationOn, mLocationManager); 2257 } 2258 }); 2259 if (builder != null) { 2260 return builder.create(); 2261 } else { 2262 return null; 2263 } 2264 } 2265 2266 /** 2267 * Launches an ACTION_EDIT intent for the given local data item. If 2268 * 'withTinyPlanet' is set, this will show a disambig dialog first to let 2269 * the user start either the tiny planet editor or another photo edior. 2270 * 2271 * @param data The data item to edit. 2272 */ 2273 public void launchEditor(LocalData data) { 2274 Intent intent = new Intent(Intent.ACTION_EDIT) 2275 .setDataAndType(data.getUri(), data.getMimeType()) 2276 .setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 2277 try { 2278 launchActivityByIntent(intent); 2279 } catch (ActivityNotFoundException e) { 2280 final String msgEditWith = getResources().getString(R.string.edit_with); 2281 launchActivityByIntent(Intent.createChooser(intent, msgEditWith)); 2282 } 2283 } 2284 2285 @Override 2286 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { 2287 super.onCreateContextMenu(menu, v, menuInfo); 2288 2289 MenuInflater inflater = getMenuInflater(); 2290 inflater.inflate(R.menu.filmstrip_context_menu, menu); 2291 } 2292 2293 @Override 2294 public boolean onContextItemSelected(MenuItem item) { 2295 switch (item.getItemId()) { 2296 case R.id.tiny_planet_editor: 2297 mMyFilmstripBottomControlListener.onTinyPlanet(); 2298 return true; 2299 case R.id.photo_editor: 2300 mMyFilmstripBottomControlListener.onEdit(); 2301 return true; 2302 } 2303 return false; 2304 } 2305 2306 /** 2307 * Launch the tiny planet editor. 2308 * 2309 * @param data The data must be a 360 degree stereographically mapped 2310 * panoramic image. It will not be modified, instead a new item 2311 * with the result will be added to the filmstrip. 2312 */ 2313 public void launchTinyPlanetEditor(LocalData data) { 2314 TinyPlanetFragment fragment = new TinyPlanetFragment(); 2315 Bundle bundle = new Bundle(); 2316 bundle.putString(TinyPlanetFragment.ARGUMENT_URI, data.getUri().toString()); 2317 bundle.putString(TinyPlanetFragment.ARGUMENT_TITLE, data.getTitle()); 2318 fragment.setArguments(bundle); 2319 fragment.show(getFragmentManager(), "tiny_planet"); 2320 } 2321 2322 /** 2323 * Returns what UI mode (capture mode or filmstrip) we are in. 2324 * Returned number one of {@link com.google.common.logging.eventprotos.NavigationChange.Mode} 2325 */ 2326 private int currentUserInterfaceMode() { 2327 int mode = NavigationChange.Mode.UNKNOWN_MODE; 2328 if (mCurrentModeIndex == getResources().getInteger(R.integer.camera_mode_photo)) { 2329 mode = NavigationChange.Mode.PHOTO_CAPTURE; 2330 } 2331 if (mCurrentModeIndex == getResources().getInteger(R.integer.camera_mode_video)) { 2332 mode = NavigationChange.Mode.VIDEO_CAPTURE; 2333 } 2334 if (mCurrentModeIndex == getResources().getInteger(R.integer.camera_mode_refocus)) { 2335 mode = NavigationChange.Mode.LENS_BLUR; 2336 } 2337 if (mCurrentModeIndex == getResources().getInteger(R.integer.camera_mode_gcam)) { 2338 mode = NavigationChange.Mode.HDR_PLUS; 2339 } 2340 if (mCurrentModeIndex == getResources().getInteger(R.integer.camera_mode_photosphere)) { 2341 mode = NavigationChange.Mode.PHOTO_SPHERE; 2342 } 2343 if (mCurrentModeIndex == getResources().getInteger(R.integer.camera_mode_panorama)) { 2344 mode = NavigationChange.Mode.PANORAMA; 2345 } 2346 if (mFilmstripVisible) { 2347 mode = NavigationChange.Mode.FILMSTRIP; 2348 } 2349 return mode; 2350 } 2351 2352 private void openModule(CameraModule module) { 2353 module.init(this, isSecureCamera(), isCaptureIntent()); 2354 module.hardResetSettings(mSettingsManager); 2355 if (!mPaused) { 2356 module.resume(); 2357 UsageStatistics.instance().changeScreen(currentUserInterfaceMode(), 2358 NavigationChange.InteractionCause.BUTTON); 2359 updatePreviewVisibility(); 2360 } 2361 } 2362 2363 private void closeModule(CameraModule module) { 2364 module.pause(); 2365 mCameraAppUI.clearModuleUI(); 2366 } 2367 2368 private void performDeletion() { 2369 if (!mPendingDeletion) { 2370 return; 2371 } 2372 hideUndoDeletionBar(false); 2373 mDataAdapter.executeDeletion(); 2374 } 2375 2376 public void showUndoDeletionBar() { 2377 if (mPendingDeletion) { 2378 performDeletion(); 2379 } 2380 Log.v(TAG, "showing undo bar"); 2381 mPendingDeletion = true; 2382 if (mUndoDeletionBar == null) { 2383 ViewGroup v = (ViewGroup) getLayoutInflater().inflate(R.layout.undo_bar, 2384 mAboveFilmstripControlLayout, true); 2385 mUndoDeletionBar = (ViewGroup) v.findViewById(R.id.camera_undo_deletion_bar); 2386 View button = mUndoDeletionBar.findViewById(R.id.camera_undo_deletion_button); 2387 button.setOnClickListener(new View.OnClickListener() { 2388 @Override 2389 public void onClick(View view) { 2390 mDataAdapter.undoDataRemoval(); 2391 hideUndoDeletionBar(true); 2392 } 2393 }); 2394 // Setting undo bar clickable to avoid touch events going through 2395 // the bar to the buttons (eg. edit button, etc) underneath the bar. 2396 mUndoDeletionBar.setClickable(true); 2397 // When there is user interaction going on with the undo button, we 2398 // do not want to hide the undo bar. 2399 button.setOnTouchListener(new View.OnTouchListener() { 2400 @Override 2401 public boolean onTouch(View v, MotionEvent event) { 2402 if (event.getActionMasked() == MotionEvent.ACTION_DOWN) { 2403 mIsUndoingDeletion = true; 2404 } else if (event.getActionMasked() == MotionEvent.ACTION_UP) { 2405 mIsUndoingDeletion = false; 2406 } 2407 return false; 2408 } 2409 }); 2410 } 2411 mUndoDeletionBar.setAlpha(0f); 2412 mUndoDeletionBar.setVisibility(View.VISIBLE); 2413 mUndoDeletionBar.animate().setDuration(200).alpha(1f).setListener(null).start(); 2414 } 2415 2416 private void hideUndoDeletionBar(boolean withAnimation) { 2417 Log.v(TAG, "Hiding undo deletion bar"); 2418 mPendingDeletion = false; 2419 if (mUndoDeletionBar != null) { 2420 if (withAnimation) { 2421 mUndoDeletionBar.animate().setDuration(200).alpha(0f) 2422 .setListener(new Animator.AnimatorListener() { 2423 @Override 2424 public void onAnimationStart(Animator animation) { 2425 // Do nothing. 2426 } 2427 2428 @Override 2429 public void onAnimationEnd(Animator animation) { 2430 mUndoDeletionBar.setVisibility(View.GONE); 2431 } 2432 2433 @Override 2434 public void onAnimationCancel(Animator animation) { 2435 // Do nothing. 2436 } 2437 2438 @Override 2439 public void onAnimationRepeat(Animator animation) { 2440 // Do nothing. 2441 } 2442 }).start(); 2443 } else { 2444 mUndoDeletionBar.setVisibility(View.GONE); 2445 } 2446 } 2447 } 2448 2449 @Override 2450 public void onOrientationChanged(int orientation) { 2451 // We keep the last known orientation. So if the user first orient 2452 // the camera then point the camera to floor or sky, we still have 2453 // the correct orientation. 2454 if (orientation == OrientationManager.ORIENTATION_UNKNOWN) { 2455 return; 2456 } 2457 mLastRawOrientation = orientation; 2458 if (mCurrentModule != null) { 2459 mCurrentModule.onOrientationChanged(orientation); 2460 } 2461 } 2462 2463 /** 2464 * Enable/disable swipe-to-filmstrip. Will always disable swipe if in 2465 * capture intent. 2466 * 2467 * @param enable {@code true} to enable swipe. 2468 */ 2469 public void setSwipingEnabled(boolean enable) { 2470 // TODO: Bring back the functionality. 2471 if (isCaptureIntent()) { 2472 // lockPreview(true); 2473 } else { 2474 // lockPreview(!enable); 2475 } 2476 } 2477 2478 // Accessor methods for getting latency times used in performance testing 2479 public long getFirstPreviewTime() { 2480 if (mCurrentModule instanceof PhotoModule) { 2481 long coverHiddenTime = getCameraAppUI().getCoverHiddenTime(); 2482 if (coverHiddenTime != -1) { 2483 return coverHiddenTime - mOnCreateTime; 2484 } 2485 } 2486 return -1; 2487 } 2488 2489 public long getAutoFocusTime() { 2490 return (mCurrentModule instanceof PhotoModule) ? 2491 ((PhotoModule) mCurrentModule).mAutoFocusTime : -1; 2492 } 2493 2494 public long getShutterLag() { 2495 return (mCurrentModule instanceof PhotoModule) ? 2496 ((PhotoModule) mCurrentModule).mShutterLag : -1; 2497 } 2498 2499 public long getShutterToPictureDisplayedTime() { 2500 return (mCurrentModule instanceof PhotoModule) ? 2501 ((PhotoModule) mCurrentModule).mShutterToPictureDisplayedTime : -1; 2502 } 2503 2504 public long getPictureDisplayedToJpegCallbackTime() { 2505 return (mCurrentModule instanceof PhotoModule) ? 2506 ((PhotoModule) mCurrentModule).mPictureDisplayedToJpegCallbackTime : -1; 2507 } 2508 2509 public long getJpegCallbackFinishTime() { 2510 return (mCurrentModule instanceof PhotoModule) ? 2511 ((PhotoModule) mCurrentModule).mJpegCallbackFinishTime : -1; 2512 } 2513 2514 public long getCaptureStartTime() { 2515 return (mCurrentModule instanceof PhotoModule) ? 2516 ((PhotoModule) mCurrentModule).mCaptureStartTime : -1; 2517 } 2518 2519 public boolean isRecording() { 2520 return (mCurrentModule instanceof VideoModule) ? 2521 ((VideoModule) mCurrentModule).isRecording() : false; 2522 } 2523 2524 public CameraAgent.CameraOpenCallback getCameraOpenErrorCallback() { 2525 return mCameraController; 2526 } 2527 2528 // For debugging purposes only. 2529 public CameraModule getCurrentModule() { 2530 return mCurrentModule; 2531 } 2532 2533 @Override 2534 public void showTutorial(AbstractTutorialOverlay tutorial) { 2535 mCameraAppUI.showTutorial(tutorial, getLayoutInflater()); 2536 } 2537 2538 @Override 2539 public void showErrorAndFinish(int messageId) { 2540 CameraUtil.showErrorAndFinish(this, messageId); 2541 } 2542 2543 /** 2544 * Reads the current location recording settings and passes it on to the 2545 * location manager. 2546 */ 2547 public void syncLocationManagerSetting() { 2548 Keys.syncLocationManager(mSettingsManager, mLocationManager); 2549 } 2550 2551 private void keepScreenOnForAWhile() { 2552 if (mKeepScreenOn) { 2553 return; 2554 } 2555 mMainHandler.removeMessages(MSG_CLEAR_SCREEN_ON_FLAG); 2556 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 2557 mMainHandler.sendEmptyMessageDelayed(MSG_CLEAR_SCREEN_ON_FLAG, SCREEN_DELAY_MS); 2558 } 2559 2560 private void resetScreenOn() { 2561 mKeepScreenOn = false; 2562 mMainHandler.removeMessages(MSG_CLEAR_SCREEN_ON_FLAG); 2563 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 2564 } 2565 2566 /** 2567 * @return {@code true} if the Gallery is launched successfully. 2568 */ 2569 private boolean startGallery() { 2570 if (mGalleryIntent == null) { 2571 return false; 2572 } 2573 try { 2574 UsageStatistics.instance().changeScreen(NavigationChange.Mode.GALLERY, 2575 NavigationChange.InteractionCause.BUTTON); 2576 Intent startGalleryIntent = new Intent(mGalleryIntent); 2577 int currentDataId = mFilmstripController.getCurrentId(); 2578 LocalData currentLocalData = mDataAdapter.getLocalData(currentDataId); 2579 if (currentLocalData != null) { 2580 GalleryHelper.setContentUri(startGalleryIntent, currentLocalData.getUri()); 2581 } 2582 launchActivityByIntent(startGalleryIntent); 2583 } catch (ActivityNotFoundException e) { 2584 Log.w(TAG, "Failed to launch gallery activity, closing"); 2585 } 2586 return false; 2587 } 2588 2589 private void setNfcBeamPushUriFromData(LocalData data) { 2590 final Uri uri = data.getUri(); 2591 if (uri != Uri.EMPTY) { 2592 mNfcPushUris[0] = uri; 2593 } else { 2594 mNfcPushUris[0] = null; 2595 } 2596 } 2597 2598 /** 2599 * Updates the visibility of the filmstrip bottom controls and action bar. 2600 */ 2601 private void updateUiByData(final int dataId) { 2602 final LocalData currentData = mDataAdapter.getLocalData(dataId); 2603 if (currentData == null) { 2604 Log.w(TAG, "Current data ID not found."); 2605 hideSessionProgress(); 2606 return; 2607 } 2608 updateActionBarMenu(currentData); 2609 2610 /* Bottom controls. */ 2611 updateBottomControlsByData(currentData); 2612 2613 if (isSecureCamera()) { 2614 // We cannot show buttons in secure camera since go to other 2615 // activities might create a security hole. 2616 mCameraAppUI.getFilmstripBottomControls().hideControls(); 2617 return; 2618 } 2619 2620 2621 setNfcBeamPushUriFromData(currentData); 2622 2623 if (!mDataAdapter.isMetadataUpdated(dataId)) { 2624 mDataAdapter.updateMetadata(dataId); 2625 } 2626 } 2627 2628 /** 2629 * Updates the bottom controls based on the data. 2630 */ 2631 private void updateBottomControlsByData(final LocalData currentData) { 2632 2633 final CameraAppUI.BottomPanel filmstripBottomPanel = 2634 mCameraAppUI.getFilmstripBottomControls(); 2635 filmstripBottomPanel.showControls(); 2636 filmstripBottomPanel.setEditButtonVisibility( 2637 currentData.isDataActionSupported(LocalData.DATA_ACTION_EDIT)); 2638 filmstripBottomPanel.setShareButtonVisibility( 2639 currentData.isDataActionSupported(LocalData.DATA_ACTION_SHARE)); 2640 filmstripBottomPanel.setDeleteButtonVisibility( 2641 currentData.isDataActionSupported(LocalData.DATA_ACTION_DELETE)); 2642 2643 /* Progress bar */ 2644 2645 Uri contentUri = currentData.getUri(); 2646 CaptureSessionManager sessionManager = getServices() 2647 .getCaptureSessionManager(); 2648 2649 if (sessionManager.hasErrorMessage(contentUri)) { 2650 showProcessError(sessionManager.getErrorMesage(contentUri)); 2651 } else { 2652 filmstripBottomPanel.hideProgressError(); 2653 CaptureSession session = sessionManager.getSession(contentUri); 2654 2655 if (session != null) { 2656 int sessionProgress = session.getProgress(); 2657 2658 if (sessionProgress < 0) { 2659 hideSessionProgress(); 2660 } else { 2661 CharSequence progressMessage = session.getProgressMessage(); 2662 showSessionProgress(progressMessage); 2663 updateSessionProgress(sessionProgress); 2664 } 2665 } else { 2666 hideSessionProgress(); 2667 } 2668 } 2669 2670 /* View button */ 2671 2672 // We need to add this to a separate DB. 2673 final int viewButtonVisibility; 2674 if (PanoramaMetadataLoader.isPanoramaAndUseViewer(currentData)) { 2675 viewButtonVisibility = CameraAppUI.BottomPanel.VIEWER_PHOTO_SPHERE; 2676 } else if (RgbzMetadataLoader.hasRGBZData(currentData)) { 2677 viewButtonVisibility = CameraAppUI.BottomPanel.VIEWER_REFOCUS; 2678 } else { 2679 viewButtonVisibility = CameraAppUI.BottomPanel.VIEWER_NONE; 2680 } 2681 2682 filmstripBottomPanel.setTinyPlanetEnabled( 2683 PanoramaMetadataLoader.isPanorama360(currentData)); 2684 filmstripBottomPanel.setViewerButtonVisibility(viewButtonVisibility); 2685 } 2686 2687 private class PeekAnimationHandler extends Handler { 2688 private class DataAndCallback { 2689 LocalData mData; 2690 com.android.camera.util.Callback<Bitmap> mCallback; 2691 2692 public DataAndCallback(LocalData data, com.android.camera.util.Callback<Bitmap> 2693 callback) { 2694 mData = data; 2695 mCallback = callback; 2696 } 2697 } 2698 2699 public PeekAnimationHandler(Looper looper) { 2700 super(looper); 2701 } 2702 2703 /** 2704 * Starts the animation decoding job and posts a {@code Runnable} back 2705 * when when the decoding is done. 2706 * 2707 * @param data The data item to decode the thumbnail for. 2708 * @param callback {@link com.android.camera.util.Callback} after the 2709 * decoding is done. 2710 */ 2711 public void startDecodingJob(final LocalData data, 2712 final com.android.camera.util.Callback<Bitmap> callback) { 2713 PeekAnimationHandler.this.obtainMessage(0 /** dummy integer **/, 2714 new DataAndCallback(data, callback)).sendToTarget(); 2715 } 2716 2717 @Override 2718 public void handleMessage(Message msg) { 2719 final LocalData data = ((DataAndCallback) msg.obj).mData; 2720 final com.android.camera.util.Callback<Bitmap> callback = 2721 ((DataAndCallback) msg.obj).mCallback; 2722 if (data == null || callback == null) { 2723 return; 2724 } 2725 2726 final Bitmap bitmap; 2727 switch (data.getLocalDataType()) { 2728 case LocalData.LOCAL_IN_PROGRESS_DATA: 2729 byte[] jpegData = Storage.getJpegForSession(data.getUri()); 2730 if (jpegData != null) { 2731 bitmap = BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length); 2732 } else { 2733 bitmap = null; 2734 } 2735 break; 2736 2737 case LocalData.LOCAL_IMAGE: 2738 FileInputStream stream; 2739 try { 2740 stream = new FileInputStream(data.getPath()); 2741 } catch (FileNotFoundException e) { 2742 Log.e(TAG, "File not found:" + data.getPath()); 2743 return; 2744 } 2745 Point dim = CameraUtil.resizeToFill(data.getWidth(), data.getHeight(), 2746 data.getRotation(), mAboveFilmstripControlLayout.getWidth(), 2747 mAboveFilmstripControlLayout.getMeasuredHeight()); 2748 if (data.getRotation() % 180 != 0) { 2749 int dummy = dim.x; 2750 dim.x = dim.y; 2751 dim.y = dummy; 2752 } 2753 bitmap = LocalDataUtil 2754 .loadImageThumbnailFromStream(stream, data.getWidth(), data.getHeight(), 2755 (int) (dim.x * 0.7f), (int) (dim.y * 0.7), 2756 data.getRotation(), MAX_PEEK_BITMAP_PIXELS); 2757 break; 2758 2759 case LocalData.LOCAL_VIDEO: 2760 bitmap = LocalDataUtil.loadVideoThumbnail(data.getPath()); 2761 break; 2762 2763 default: 2764 bitmap = null; 2765 break; 2766 } 2767 2768 if (bitmap == null) { 2769 return; 2770 } 2771 2772 mMainHandler.post(new Runnable() { 2773 @Override 2774 public void run() { 2775 callback.onCallback(bitmap); 2776 } 2777 }); 2778 } 2779 } 2780 2781 private void showDetailsDialog(int dataId) { 2782 final LocalData data = mDataAdapter.getLocalData(dataId); 2783 if (data == null) { 2784 return; 2785 } 2786 MediaDetails details = data.getMediaDetails(getAndroidContext()); 2787 if (details == null) { 2788 return; 2789 } 2790 Dialog detailDialog = DetailsDialog.create(CameraActivity.this, details); 2791 detailDialog.show(); 2792 UsageStatistics.instance().mediaInteraction( 2793 fileNameFromDataID(dataId), MediaInteraction.InteractionType.DETAILS, 2794 NavigationChange.InteractionCause.BUTTON, fileAgeFromDataID(dataId)); 2795 } 2796 2797 /** 2798 * Show or hide action bar items depending on current data type. 2799 */ 2800 private void updateActionBarMenu(LocalData data) { 2801 if (mActionBarMenu == null) { 2802 return; 2803 } 2804 2805 MenuItem detailsMenuItem = mActionBarMenu.findItem(R.id.action_details); 2806 if (detailsMenuItem == null) { 2807 return; 2808 } 2809 2810 int type = data.getLocalDataType(); 2811 boolean showDetails = (type == LocalData.LOCAL_IMAGE) || (type == LocalData.LOCAL_VIDEO); 2812 detailsMenuItem.setVisible(showDetails); 2813 } 2814} 2815