OSDN Git Service

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