OSDN Git Service

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