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