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