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