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