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