CameraActivity.java revision 571a8c389798bd3f01429f6be34cd3e606ab34df
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                            !settingsManager.getBoolean(SettingsManager.SETTING_RECORD_LOCATION)) {
1138                        settingsManager.remove(SettingsManager.SETTING_RECORD_LOCATION);
1139                    }
1140                }
1141            };
1142
1143    private final CameraManager.CameraExceptionCallback mCameraDefaultExceptionCallback
1144        = new CameraManager.CameraExceptionCallback() {
1145                @Override
1146                public void onCameraException(RuntimeException e) {
1147                    Log.d(TAG, "Camera Exception", e);
1148                    CameraUtil.showErrorAndFinish(CameraActivity.this,
1149                            R.string.cannot_connect_camera);
1150                }
1151            };
1152
1153    @Override
1154    public void onCreate(Bundle state) {
1155        super.onCreate(state);
1156        CameraPerformanceTracker.onEvent(CameraPerformanceTracker.ACTIVITY_START);
1157        mOnCreateTime = System.currentTimeMillis();
1158        mAppContext = getApplicationContext();
1159        GcamHelper.init(getContentResolver());
1160
1161        getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
1162        setContentView(R.layout.activity_main);
1163        mActionBar = getActionBar();
1164        mActionBar.addOnMenuVisibilityListener(this);
1165        mMainHandler = new MainHandler(this, getMainLooper());
1166        mCameraController =
1167                new CameraController(mAppContext, this, mMainHandler,
1168                        CameraManagerFactory.getAndroidCameraManager());
1169        mCameraController.setCameraDefaultExceptionCallback(mCameraDefaultExceptionCallback,
1170                mMainHandler);
1171
1172        mPreferences = new ComboPreferences(mAppContext);
1173
1174        mSettingsManager = new SettingsManager(mAppContext, this,
1175                mCameraController.getNumberOfCameras(), mStrictUpgradeCallback);
1176
1177        // Remove this after we get rid of ComboPreferences.
1178        int cameraId = Integer.parseInt(mSettingsManager.get(SettingsManager.SETTING_CAMERA_ID));
1179        mPreferences.setLocalId(mAppContext, cameraId);
1180        CameraSettings.upgradeGlobalPreferences(mPreferences,
1181                mCameraController.getNumberOfCameras());
1182        // TODO: Try to move all the resources allocation to happen as soon as
1183        // possible so we can call module.init() at the earliest time.
1184        mModuleManager = new ModuleManagerImpl();
1185        ModulesInfo.setupModules(mAppContext, mModuleManager);
1186
1187        mModeListView = (ModeListView) findViewById(R.id.mode_list_layout);
1188        mModeListView.init(mModuleManager.getSupportedModeIndexList());
1189        if (ApiHelper.HAS_ROTATION_ANIMATION) {
1190            setRotationAnimation();
1191        }
1192        mModeListView.setVisibilityChangedListener(new ModeListVisibilityChangedListener() {
1193            @Override
1194            public void onVisibilityChanged(boolean visible) {
1195                mModeListVisible = visible;
1196                updatePreviewVisibility();
1197            }
1198        });
1199
1200        // Check if this is in the secure camera mode.
1201        Intent intent = getIntent();
1202        String action = intent.getAction();
1203        if (INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE.equals(action)
1204                || ACTION_IMAGE_CAPTURE_SECURE.equals(action)) {
1205            mSecureCamera = true;
1206        } else {
1207            mSecureCamera = intent.getBooleanExtra(SECURE_CAMERA_EXTRA, false);
1208        }
1209
1210        if (mSecureCamera) {
1211            // Foreground event caused by lock screen startup.
1212            // It is necessary to log this in onCreate, to avoid the
1213            // onResume->onPause->onResume sequence.
1214            UsageStatistics.foregrounded(
1215                    eventprotos.ForegroundEvent.ForegroundSource.LOCK_SCREEN);
1216
1217            // Change the window flags so that secure camera can show when
1218            // locked
1219            Window win = getWindow();
1220            WindowManager.LayoutParams params = win.getAttributes();
1221            params.flags |= WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
1222            win.setAttributes(params);
1223
1224            // Filter for screen off so that we can finish secure camera
1225            // activity
1226            // when screen is off.
1227            IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
1228            registerReceiver(mScreenOffReceiver, filter);
1229        }
1230        mCameraAppUI = new CameraAppUI(this,
1231                (MainActivityLayout) findViewById(R.id.activity_root_view), isCaptureIntent());
1232
1233        mCameraAppUI.setFilmstripBottomControlsListener(mMyFilmstripBottomControlListener);
1234
1235        mAboveFilmstripControlLayout =
1236                (FrameLayout) findViewById(R.id.camera_filmstrip_content_layout);
1237
1238        // Add the session listener so we can track the session progress
1239        // updates.
1240        getServices().getCaptureSessionManager().addSessionListener(mSessionListener);
1241        mFilmstripController = ((FilmstripView) findViewById(R.id.filmstrip_view)).getController();
1242        mFilmstripController.setImageGap(
1243                getResources().getDimensionPixelSize(R.dimen.camera_film_strip_gap));
1244        mPanoramaViewHelper = new PanoramaViewHelper(this);
1245        mPanoramaViewHelper.onCreate();
1246        // Set up the camera preview first so the preview shows up ASAP.
1247        mDataAdapter = new CameraDataAdapter(mAppContext,
1248                new ColorDrawable(getResources().getColor(R.color.photo_placeholder)));
1249        mDataAdapter.setLocalDataListener(mLocalDataListener);
1250
1251        mCameraAppUI.getFilmstripContentPanel().setFilmstripListener(mFilmstripListener);
1252
1253        mLocationManager = new LocationManager(mAppContext);
1254
1255        int modeIndex = -1;
1256        int photoIndex = getResources().getInteger(R.integer.camera_mode_photo);
1257        int videoIndex = getResources().getInteger(R.integer.camera_mode_video);
1258        int gcamIndex = getResources().getInteger(R.integer.camera_mode_gcam);
1259        if (MediaStore.INTENT_ACTION_VIDEO_CAMERA.equals(getIntent().getAction())
1260                || MediaStore.ACTION_VIDEO_CAPTURE.equals(getIntent().getAction())) {
1261            modeIndex = videoIndex;
1262        } else if (MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA.equals(getIntent().getAction())
1263                || MediaStore.ACTION_IMAGE_CAPTURE.equals(getIntent().getAction())) {
1264            // TODO: synchronize mode options with photo module without losing
1265            // HDR+ preferences.
1266            modeIndex = photoIndex;
1267        } else if (MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE.equals(getIntent()
1268                        .getAction())
1269                || MediaStore.ACTION_IMAGE_CAPTURE_SECURE.equals(getIntent().getAction())) {
1270            modeIndex = mSettingsManager.getInt(
1271                SettingsManager.SETTING_KEY_CAMERA_MODULE_LAST_USED_INDEX);
1272        } else {
1273            // If the activity has not been started using an explicit intent,
1274            // read the module index from the last time the user changed modes
1275            modeIndex = mSettingsManager.getInt(SettingsManager.SETTING_STARTUP_MODULE_INDEX);
1276            if ((modeIndex == gcamIndex &&
1277                    !GcamHelper.hasGcamCapture()) || modeIndex < 0) {
1278                modeIndex = photoIndex;
1279            }
1280        }
1281
1282        mOrientationManager = new OrientationManagerImpl(this);
1283        mOrientationManager.addOnOrientationChangeListener(mMainHandler, this);
1284
1285        setModuleFromModeIndex(modeIndex);
1286        mCameraAppUI.prepareModuleUI();
1287        mCurrentModule.init(this, isSecureCamera(), isCaptureIntent());
1288
1289        if (!mSecureCamera) {
1290            mFilmstripController.setDataAdapter(mDataAdapter);
1291            if (!isCaptureIntent()) {
1292                mDataAdapter.requestLoad();
1293            }
1294        } else {
1295            // Put a lock placeholder as the last image by setting its date to
1296            // 0.
1297            ImageView v = (ImageView) getLayoutInflater().inflate(
1298                    R.layout.secure_album_placeholder, null);
1299            v.setOnClickListener(new View.OnClickListener() {
1300                @Override
1301                public void onClick(View view) {
1302                    UsageStatistics.changeScreen(NavigationChange.Mode.GALLERY,
1303                            InteractionCause.BUTTON);
1304                    startGallery();
1305                    finish();
1306                }
1307            });
1308            mDataAdapter = new FixedLastDataAdapter(
1309                    mAppContext,
1310                    mDataAdapter,
1311                    new SimpleViewData(
1312                            v,
1313                            v.getDrawable().getIntrinsicWidth(),
1314                            v.getDrawable().getIntrinsicHeight(),
1315                            0, 0));
1316            // Flush out all the original data.
1317            mDataAdapter.flush();
1318            mFilmstripController.setDataAdapter(mDataAdapter);
1319        }
1320
1321        setupNfcBeamPush();
1322
1323        mLocalImagesObserver = new LocalMediaObserver();
1324        mLocalVideosObserver = new LocalMediaObserver();
1325
1326        getContentResolver().registerContentObserver(
1327                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, true,
1328                mLocalImagesObserver);
1329        getContentResolver().registerContentObserver(
1330                MediaStore.Video.Media.EXTERNAL_CONTENT_URI, true,
1331                mLocalVideosObserver);
1332        if (FeedbackHelper.feedbackAvailable()) {
1333            mFeedbackHelper = new FeedbackHelper(mAppContext);
1334        }
1335    }
1336
1337    /**
1338     * Call this whenever the mode drawer or filmstrip change the visibility
1339     * state.
1340     */
1341    private void updatePreviewVisibility() {
1342        if (mCurrentModule == null) {
1343            return;
1344        }
1345        int visibility;
1346        if (mFilmstripCoversPreview) {
1347            visibility = ModuleController.VISIBILITY_HIDDEN;
1348        } else if (mModeListVisible){
1349            visibility = ModuleController.VISIBILITY_COVERED;
1350        } else {
1351            visibility = ModuleController.VISIBILITY_VISIBLE;
1352        }
1353        mCurrentModule.onPreviewVisibilityChanged(visibility);
1354    }
1355
1356    private void setRotationAnimation() {
1357        int rotationAnimation = WindowManager.LayoutParams.ROTATION_ANIMATION_ROTATE;
1358        rotationAnimation = WindowManager.LayoutParams.ROTATION_ANIMATION_CROSSFADE;
1359        Window win = getWindow();
1360        WindowManager.LayoutParams winParams = win.getAttributes();
1361        winParams.rotationAnimation = rotationAnimation;
1362        win.setAttributes(winParams);
1363    }
1364
1365    @Override
1366    public void onUserInteraction() {
1367        super.onUserInteraction();
1368        if (!isFinishing()) {
1369            keepScreenOnForAWhile();
1370        }
1371    }
1372
1373    @Override
1374    public boolean dispatchTouchEvent(MotionEvent ev) {
1375        boolean result = super.dispatchTouchEvent(ev);
1376        if (ev.getActionMasked() == MotionEvent.ACTION_DOWN) {
1377            // Real deletion is postponed until the next user interaction after
1378            // the gesture that triggers deletion. Until real deletion is
1379            // performed, users can click the undo button to bring back the
1380            // image that they chose to delete.
1381            if (mPendingDeletion && !mIsUndoingDeletion) {
1382                performDeletion();
1383            }
1384        }
1385        return result;
1386    }
1387
1388    @Override
1389    public void onPause() {
1390        mPaused = true;
1391        mPeekAnimationHandler = null;
1392        mPeekAnimationThread.quitSafely();
1393        mPeekAnimationThread = null;
1394        CameraPerformanceTracker.onEvent(CameraPerformanceTracker.ACTIVITY_PAUSE);
1395
1396        // Delete photos that are pending deletion
1397        performDeletion();
1398        mCurrentModule.pause();
1399        mOrientationManager.pause();
1400        // Close the camera and wait for the operation done.
1401        mCameraController.closeCamera();
1402        mPanoramaViewHelper.onPause();
1403
1404        mLocalImagesObserver.setForegroundChangeListener(null);
1405        mLocalImagesObserver.setActivityPaused(true);
1406        mLocalVideosObserver.setActivityPaused(true);
1407        resetScreenOn();
1408        super.onPause();
1409    }
1410
1411    @Override
1412    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
1413        if (requestCode == REQ_CODE_DONT_SWITCH_TO_PREVIEW) {
1414            mResetToPreviewOnResume = false;
1415        } else {
1416            super.onActivityResult(requestCode, resultCode, data);
1417        }
1418    }
1419
1420    @Override
1421    public void onResume() {
1422        mPaused = false;
1423        CameraPerformanceTracker.onEvent(CameraPerformanceTracker.ACTIVITY_RESUME);
1424
1425        mLastLayoutOrientation = getResources().getConfiguration().orientation;
1426
1427        // TODO: Handle this in OrientationManager.
1428        // Auto-rotate off
1429        if (Settings.System.getInt(getContentResolver(),
1430                Settings.System.ACCELEROMETER_ROTATION, 0) == 0) {
1431            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
1432            mAutoRotateScreen = false;
1433        } else {
1434            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
1435            mAutoRotateScreen = true;
1436        }
1437
1438        if (isCaptureIntent()) {
1439            // Foreground event caused by photo or video capure intent.
1440            UsageStatistics.foregrounded(
1441                    eventprotos.ForegroundEvent.ForegroundSource.INTENT_PICKER);
1442        } else if (!mSecureCamera) {
1443            // Foreground event that is not caused by an intent.
1444            UsageStatistics.foregrounded(
1445                    eventprotos.ForegroundEvent.ForegroundSource.ICON_LAUNCHER);
1446        }
1447
1448        Drawable galleryLogo;
1449        if (mSecureCamera) {
1450            mGalleryIntent = null;
1451            galleryLogo = null;
1452        } else {
1453            mGalleryIntent = IntentHelper.getDefaultGalleryIntent(mAppContext);
1454            galleryLogo = IntentHelper.getGalleryIcon(mAppContext, mGalleryIntent);
1455        }
1456        if (galleryLogo == null) {
1457            try {
1458                galleryLogo = getPackageManager().getActivityLogo(getComponentName());
1459            } catch (PackageManager.NameNotFoundException e) {
1460                Log.e(TAG, "Can't get the activity logo");
1461            }
1462        }
1463        if (mGalleryIntent != null) {
1464            mActionBar.setDisplayUseLogoEnabled(true);
1465        }
1466        mActionBar.setLogo(galleryLogo);
1467        mOrientationManager.resume();
1468        super.onResume();
1469        mPeekAnimationThread = new HandlerThread("Peek animation");
1470        mPeekAnimationThread.start();
1471        mPeekAnimationHandler = new PeekAnimationHandler(mPeekAnimationThread.getLooper());
1472        mCurrentModule.resume();
1473        setSwipingEnabled(true);
1474
1475        if (mResetToPreviewOnResume) {
1476            mCameraAppUI.resume();
1477        } else {
1478            LocalData data = mDataAdapter.getLocalData(mFilmstripController.getCurrentId());
1479            if (data != null) {
1480                mDataAdapter.refresh(data.getUri());
1481            }
1482        }
1483        // The share button might be disabled to avoid double tapping.
1484        mCameraAppUI.getFilmstripBottomControls().setShareEnabled(true);
1485        // Default is showing the preview, unless disabled by explicitly
1486        // starting an activity we want to return from to the filmstrip rather
1487        // than the preview.
1488        mResetToPreviewOnResume = true;
1489
1490        if (mLocalVideosObserver.isMediaDataChangedDuringPause()
1491                || mLocalImagesObserver.isMediaDataChangedDuringPause()) {
1492            if (!mSecureCamera) {
1493                // If it's secure camera, requestLoad() should not be called
1494                // as it will load all the data.
1495                if (!mFilmstripVisible) {
1496                    mDataAdapter.requestLoad();
1497                } else {
1498                    mDataAdapter.requestLoadNewPhotos();
1499                }
1500            }
1501        }
1502        mLocalImagesObserver.setActivityPaused(false);
1503        mLocalVideosObserver.setActivityPaused(false);
1504        mLocalImagesObserver.setForegroundChangeListener(new LocalMediaObserver.ChangeListener() {
1505            @Override
1506            public void onChange() {
1507                mDataAdapter.requestLoadNewPhotos();
1508            }
1509        });
1510
1511        keepScreenOnForAWhile();
1512
1513        // Lights-out mode at all times.
1514        findViewById(R.id.activity_root_view)
1515                .setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
1516        mPanoramaViewHelper.onResume();
1517        ReleaseDialogHelper.showReleaseInfoDialogOnStart(this, mSettingsManager);
1518        syncLocationManagerSetting();
1519    }
1520
1521    @Override
1522    public void onStart() {
1523        super.onStart();
1524        mPanoramaViewHelper.onStart();
1525        if (mResetToPreviewOnResume) {
1526            mCameraAppUI.resume();
1527            mResetToPreviewOnResume = false;
1528        }
1529    }
1530
1531    @Override
1532    protected void onStop() {
1533        mPanoramaViewHelper.onStop();
1534        if (mFeedbackHelper != null) {
1535            mFeedbackHelper.stopFeedback();
1536        }
1537
1538        mLocationManager.disconnect();
1539        super.onStop();
1540    }
1541
1542    @Override
1543    public void onDestroy() {
1544        if (mSecureCamera) {
1545            unregisterReceiver(mScreenOffReceiver);
1546        }
1547        mActionBar.removeOnMenuVisibilityListener(this);
1548        mSettingsManager.removeAllListeners();
1549        mCameraController.removeCallbackReceiver();
1550        getContentResolver().unregisterContentObserver(mLocalImagesObserver);
1551        getContentResolver().unregisterContentObserver(mLocalVideosObserver);
1552        getServices().getCaptureSessionManager().removeSessionListener(mSessionListener);
1553        mCameraAppUI.onDestroy();
1554        mCameraController = null;
1555        mSettingsManager = null;
1556        mCameraAppUI = null;
1557        mOrientationManager = null;
1558        mButtonManager = null;
1559        CameraManagerFactory.recycle();
1560        super.onDestroy();
1561    }
1562
1563    @Override
1564    public void onConfigurationChanged(Configuration config) {
1565        super.onConfigurationChanged(config);
1566        Log.v(TAG, "onConfigurationChanged");
1567        if (config.orientation == Configuration.ORIENTATION_UNDEFINED) {
1568            return;
1569        }
1570
1571        if (mLastLayoutOrientation != config.orientation) {
1572            mLastLayoutOrientation = config.orientation;
1573            mCurrentModule.onLayoutOrientationChanged(
1574                    mLastLayoutOrientation == Configuration.ORIENTATION_LANDSCAPE);
1575        }
1576    }
1577
1578    @Override
1579    public boolean onKeyDown(int keyCode, KeyEvent event) {
1580        if (!mFilmstripVisible) {
1581            if (mCurrentModule.onKeyDown(keyCode, event)) {
1582                return true;
1583            }
1584            // Prevent software keyboard or voice search from showing up.
1585            if (keyCode == KeyEvent.KEYCODE_SEARCH
1586                    || keyCode == KeyEvent.KEYCODE_MENU) {
1587                if (event.isLongPress()) {
1588                    return true;
1589                }
1590            }
1591        }
1592
1593        return super.onKeyDown(keyCode, event);
1594    }
1595
1596    @Override
1597    public boolean onKeyUp(int keyCode, KeyEvent event) {
1598        if (!mFilmstripVisible) {
1599            // If a module is in the middle of capture, it should
1600            // consume the key event.
1601            if (mCurrentModule.onKeyUp(keyCode, event)) {
1602                return true;
1603            } else if (keyCode == KeyEvent.KEYCODE_MENU) {
1604                // Let the mode list view consume the event.
1605                mModeListView.onMenuPressed();
1606                return true;
1607            }
1608        }
1609        return super.onKeyUp(keyCode, event);
1610    }
1611
1612    @Override
1613    public void onBackPressed() {
1614        if (!mCameraAppUI.onBackPressed()) {
1615            if (!mCurrentModule.onBackPressed()) {
1616                super.onBackPressed();
1617            }
1618        }
1619    }
1620
1621    @Override
1622    public boolean isAutoRotateScreen() {
1623        // TODO: Move to OrientationManager.
1624        return mAutoRotateScreen;
1625    }
1626
1627    @Override
1628    public boolean onCreateOptionsMenu(Menu menu) {
1629        MenuInflater inflater = getMenuInflater();
1630        inflater.inflate(R.menu.filmstrip_menu, menu);
1631        mActionBarMenu = menu;
1632        return super.onCreateOptionsMenu(menu);
1633    }
1634
1635    protected void updateStorageSpace() {
1636        mStorageSpaceBytes = Storage.getAvailableSpace();
1637    }
1638
1639    protected long getStorageSpaceBytes() {
1640        return mStorageSpaceBytes;
1641    }
1642
1643    protected void updateStorageSpaceAndHint() {
1644        updateStorageSpace();
1645        updateStorageHint(mStorageSpaceBytes);
1646    }
1647
1648    protected void updateStorageHint(long storageSpace) {
1649        String message = null;
1650        if (storageSpace == Storage.UNAVAILABLE) {
1651            message = getString(R.string.no_storage);
1652        } else if (storageSpace == Storage.PREPARING) {
1653            message = getString(R.string.preparing_sd);
1654        } else if (storageSpace == Storage.UNKNOWN_SIZE) {
1655            message = getString(R.string.access_sd_fail);
1656        } else if (storageSpace <= Storage.LOW_STORAGE_THRESHOLD_BYTES) {
1657            message = getString(R.string.spaceIsLow_content);
1658        }
1659
1660        if (message != null) {
1661            if (mStorageHint == null) {
1662                mStorageHint = OnScreenHint.makeText(mAppContext, message);
1663            } else {
1664                mStorageHint.setText(message);
1665            }
1666            mStorageHint.show();
1667        } else if (mStorageHint != null) {
1668            mStorageHint.cancel();
1669            mStorageHint = null;
1670        }
1671    }
1672
1673    protected void setResultEx(int resultCode) {
1674        mResultCodeForTesting = resultCode;
1675        setResult(resultCode);
1676    }
1677
1678    protected void setResultEx(int resultCode, Intent data) {
1679        mResultCodeForTesting = resultCode;
1680        mResultDataForTesting = data;
1681        setResult(resultCode, data);
1682    }
1683
1684    public int getResultCode() {
1685        return mResultCodeForTesting;
1686    }
1687
1688    public Intent getResultData() {
1689        return mResultDataForTesting;
1690    }
1691
1692    public boolean isSecureCamera() {
1693        return mSecureCamera;
1694    }
1695
1696    @Override
1697    public boolean isPaused() {
1698        return mPaused;
1699    }
1700
1701    @Override
1702    public int getPreferredChildModeIndex(int modeIndex) {
1703        if (modeIndex == getResources().getInteger(R.integer.camera_mode_photo)) {
1704            boolean hdrPlusOn = mSettingsManager.isHdrPlusOn();
1705            if (hdrPlusOn && GcamHelper.hasGcamCapture()) {
1706                modeIndex = getResources().getInteger(R.integer.camera_mode_gcam);
1707            }
1708        }
1709        return modeIndex;
1710    }
1711
1712    @Override
1713    public void onModeSelected(int modeIndex) {
1714        if (mCurrentModeIndex == modeIndex) {
1715            return;
1716        }
1717
1718        CameraPerformanceTracker.onEvent(CameraPerformanceTracker.MODE_SWITCH_START);
1719        // Record last used camera mode for quick switching
1720        if (modeIndex == getResources().getInteger(R.integer.camera_mode_photo)
1721                || modeIndex == getResources().getInteger(R.integer.camera_mode_gcam)) {
1722            mSettingsManager.setInt(SettingsManager.SETTING_KEY_CAMERA_MODULE_LAST_USED_INDEX,
1723                    modeIndex);
1724        }
1725
1726        closeModule(mCurrentModule);
1727        int oldModuleIndex = mCurrentModeIndex;
1728
1729        // Select the correct module index from the mode switcher index.
1730        modeIndex = getPreferredChildModeIndex(modeIndex);
1731        setModuleFromModeIndex(modeIndex);
1732
1733        mCameraAppUI.resetBottomControls(mCurrentModule, modeIndex);
1734        mCameraAppUI.addShutterListener(mCurrentModule);
1735        openModule(mCurrentModule);
1736        mCurrentModule.onOrientationChanged(mLastRawOrientation);
1737        // Store the module index so we can use it the next time the Camera
1738        // starts up.
1739        SharedPreferences prefs = PreferenceManager
1740                .getDefaultSharedPreferences(mAppContext);
1741        prefs.edit().putInt(CameraSettings.KEY_STARTUP_MODULE_INDEX, modeIndex).apply();
1742    }
1743
1744    /**
1745     * Shows the settings dialog.
1746     */
1747    @Override
1748    public void onSettingsSelected() {
1749        Intent intent = new Intent(this, CameraSettingsActivity.class);
1750        startActivity(intent);
1751    }
1752
1753    /**
1754     * Sets the mCurrentModuleIndex, creates a new module instance for the given
1755     * index an sets it as mCurrentModule.
1756     */
1757    private void setModuleFromModeIndex(int modeIndex) {
1758        ModuleManagerImpl.ModuleAgent agent = mModuleManager.getModuleAgent(modeIndex);
1759        if (agent == null) {
1760            return;
1761        }
1762        if (!agent.requestAppForCamera()) {
1763            mCameraController.closeCamera();
1764        }
1765        mCurrentModeIndex = agent.getModuleId();
1766        mCurrentModule = (CameraModule) agent.createModule(this);
1767    }
1768
1769    @Override
1770    public SettingsManager getSettingsManager() {
1771        return mSettingsManager;
1772    }
1773
1774    @Override
1775    public CameraServices getServices() {
1776        return (CameraServices) getApplication();
1777    }
1778
1779    public List<String> getSupportedModeNames() {
1780        List<Integer> indices = mModuleManager.getSupportedModeIndexList();
1781        List<String> supported = new ArrayList<String>();
1782
1783        for (Integer modeIndex : indices) {
1784            String name = CameraUtil.getCameraModeText(modeIndex, mAppContext);
1785            if (name != null && !name.equals("")) {
1786                supported.add(name);
1787            }
1788        }
1789        return supported;
1790    }
1791
1792    @Override
1793    public ButtonManager getButtonManager() {
1794        if (mButtonManager == null) {
1795            mButtonManager = new ButtonManager(this);
1796        }
1797        return mButtonManager;
1798    }
1799
1800    /**
1801     * Creates an AlertDialog appropriate for choosing whether to enable
1802     * location on the first run of the app.
1803     */
1804    public AlertDialog getFirstTimeLocationAlert() {
1805        AlertDialog.Builder builder = new AlertDialog.Builder(this);
1806        builder = SettingsUtil.getFirstTimeLocationAlertBuilder(builder, new Callback<Boolean>() {
1807            @Override
1808            public void onCallback(Boolean locationOn) {
1809                mSettingsManager.setLocation(locationOn, mLocationManager);
1810            }
1811        });
1812        if (builder != null) {
1813            return builder.create();
1814        } else {
1815            return null;
1816        }
1817    }
1818
1819    /**
1820     * Launches an ACTION_EDIT intent for the given local data item. If
1821     * 'withTinyPlanet' is set, this will show a disambig dialog first to let
1822     * the user start either the tiny planet editor or another photo edior.
1823     *
1824     * @param data The data item to edit.
1825     */
1826    public void launchEditor(LocalData data) {
1827        Intent intent = new Intent(Intent.ACTION_EDIT)
1828                .setDataAndType(data.getUri(), data.getMimeType())
1829                .setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
1830        try {
1831            launchActivityByIntent(intent);
1832        } catch (ActivityNotFoundException e) {
1833            launchActivityByIntent(Intent.createChooser(intent, null));
1834        }
1835    }
1836
1837    @Override
1838    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
1839        super.onCreateContextMenu(menu, v, menuInfo);
1840
1841        MenuInflater inflater = getMenuInflater();
1842        inflater.inflate(R.menu.filmstrip_context_menu, menu);
1843    }
1844
1845    @Override
1846    public boolean onContextItemSelected(MenuItem item) {
1847        switch (item.getItemId()) {
1848            case R.id.tiny_planet_editor:
1849                mMyFilmstripBottomControlListener.onTinyPlanet();
1850                return true;
1851            case R.id.photo_editor:
1852                mMyFilmstripBottomControlListener.onEdit();
1853                return true;
1854        }
1855        return false;
1856    }
1857
1858    /**
1859     * Launch the tiny planet editor.
1860     *
1861     * @param data The data must be a 360 degree stereographically mapped
1862     *            panoramic image. It will not be modified, instead a new item
1863     *            with the result will be added to the filmstrip.
1864     */
1865    public void launchTinyPlanetEditor(LocalData data) {
1866        TinyPlanetFragment fragment = new TinyPlanetFragment();
1867        Bundle bundle = new Bundle();
1868        bundle.putString(TinyPlanetFragment.ARGUMENT_URI, data.getUri().toString());
1869        bundle.putString(TinyPlanetFragment.ARGUMENT_TITLE, data.getTitle());
1870        fragment.setArguments(bundle);
1871        fragment.show(getFragmentManager(), "tiny_planet");
1872    }
1873
1874    private void openModule(CameraModule module) {
1875        module.init(this, isSecureCamera(), isCaptureIntent());
1876        module.resume();
1877        updatePreviewVisibility();
1878    }
1879
1880    private void closeModule(CameraModule module) {
1881        module.pause();
1882        mCameraAppUI.clearModuleUI();
1883    }
1884
1885    private void performDeletion() {
1886        if (!mPendingDeletion) {
1887            return;
1888        }
1889        hideUndoDeletionBar(false);
1890        mDataAdapter.executeDeletion();
1891    }
1892
1893    public void showUndoDeletionBar() {
1894        if (mPendingDeletion) {
1895            performDeletion();
1896        }
1897        Log.v(TAG, "showing undo bar");
1898        mPendingDeletion = true;
1899        if (mUndoDeletionBar == null) {
1900            ViewGroup v = (ViewGroup) getLayoutInflater().inflate(R.layout.undo_bar,
1901                    mAboveFilmstripControlLayout, true);
1902            mUndoDeletionBar = (ViewGroup) v.findViewById(R.id.camera_undo_deletion_bar);
1903            View button = mUndoDeletionBar.findViewById(R.id.camera_undo_deletion_button);
1904            button.setOnClickListener(new View.OnClickListener() {
1905                @Override
1906                public void onClick(View view) {
1907                    mDataAdapter.undoDataRemoval();
1908                    hideUndoDeletionBar(true);
1909                }
1910            });
1911            // Setting undo bar clickable to avoid touch events going through
1912            // the bar to the buttons (eg. edit button, etc) underneath the bar.
1913            mUndoDeletionBar.setClickable(true);
1914            // When there is user interaction going on with the undo button, we
1915            // do not want to hide the undo bar.
1916            button.setOnTouchListener(new View.OnTouchListener() {
1917                @Override
1918                public boolean onTouch(View v, MotionEvent event) {
1919                    if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
1920                        mIsUndoingDeletion = true;
1921                    } else if (event.getActionMasked() == MotionEvent.ACTION_UP) {
1922                        mIsUndoingDeletion = false;
1923                    }
1924                    return false;
1925                }
1926            });
1927        }
1928        mUndoDeletionBar.setAlpha(0f);
1929        mUndoDeletionBar.setVisibility(View.VISIBLE);
1930        mUndoDeletionBar.animate().setDuration(200).alpha(1f).setListener(null).start();
1931    }
1932
1933    private void hideUndoDeletionBar(boolean withAnimation) {
1934        Log.v(TAG, "Hiding undo deletion bar");
1935        mPendingDeletion = false;
1936        if (mUndoDeletionBar != null) {
1937            if (withAnimation) {
1938                mUndoDeletionBar.animate().setDuration(200).alpha(0f)
1939                        .setListener(new Animator.AnimatorListener() {
1940                            @Override
1941                            public void onAnimationStart(Animator animation) {
1942                                // Do nothing.
1943                            }
1944
1945                            @Override
1946                            public void onAnimationEnd(Animator animation) {
1947                                mUndoDeletionBar.setVisibility(View.GONE);
1948                            }
1949
1950                            @Override
1951                            public void onAnimationCancel(Animator animation) {
1952                                // Do nothing.
1953                            }
1954
1955                            @Override
1956                            public void onAnimationRepeat(Animator animation) {
1957                                // Do nothing.
1958                            }
1959                        }).start();
1960            } else {
1961                mUndoDeletionBar.setVisibility(View.GONE);
1962            }
1963        }
1964    }
1965
1966    @Override
1967    public void onOrientationChanged(int orientation) {
1968        // We keep the last known orientation. So if the user first orient
1969        // the camera then point the camera to floor or sky, we still have
1970        // the correct orientation.
1971        if (orientation == OrientationManager.ORIENTATION_UNKNOWN) {
1972            return;
1973        }
1974        mLastRawOrientation = orientation;
1975        if (mCurrentModule != null) {
1976            mCurrentModule.onOrientationChanged(orientation);
1977        }
1978    }
1979
1980    /**
1981     * Enable/disable swipe-to-filmstrip. Will always disable swipe if in
1982     * capture intent.
1983     *
1984     * @param enable {@code true} to enable swipe.
1985     */
1986    public void setSwipingEnabled(boolean enable) {
1987        // TODO: Bring back the functionality.
1988        if (isCaptureIntent()) {
1989            // lockPreview(true);
1990        } else {
1991            // lockPreview(!enable);
1992        }
1993    }
1994
1995    // Accessor methods for getting latency times used in performance testing
1996    public long getFirstPreviewTime() {
1997        if (mCurrentModule instanceof PhotoModule) {
1998            long coverHiddenTime = getCameraAppUI().getCoverHiddenTime();
1999            if (coverHiddenTime != -1) {
2000                return coverHiddenTime - mOnCreateTime;
2001            }
2002        }
2003        return -1;
2004    }
2005
2006    public long getAutoFocusTime() {
2007        return (mCurrentModule instanceof PhotoModule) ?
2008                ((PhotoModule) mCurrentModule).mAutoFocusTime : -1;
2009    }
2010
2011    public long getShutterLag() {
2012        return (mCurrentModule instanceof PhotoModule) ?
2013                ((PhotoModule) mCurrentModule).mShutterLag : -1;
2014    }
2015
2016    public long getShutterToPictureDisplayedTime() {
2017        return (mCurrentModule instanceof PhotoModule) ?
2018                ((PhotoModule) mCurrentModule).mShutterToPictureDisplayedTime : -1;
2019    }
2020
2021    public long getPictureDisplayedToJpegCallbackTime() {
2022        return (mCurrentModule instanceof PhotoModule) ?
2023                ((PhotoModule) mCurrentModule).mPictureDisplayedToJpegCallbackTime : -1;
2024    }
2025
2026    public long getJpegCallbackFinishTime() {
2027        return (mCurrentModule instanceof PhotoModule) ?
2028                ((PhotoModule) mCurrentModule).mJpegCallbackFinishTime : -1;
2029    }
2030
2031    public long getCaptureStartTime() {
2032        return (mCurrentModule instanceof PhotoModule) ?
2033                ((PhotoModule) mCurrentModule).mCaptureStartTime : -1;
2034    }
2035
2036    public boolean isRecording() {
2037        return (mCurrentModule instanceof VideoModule) ?
2038                ((VideoModule) mCurrentModule).isRecording() : false;
2039    }
2040
2041    public CameraManager.CameraOpenCallback getCameraOpenErrorCallback() {
2042        return mCameraController;
2043    }
2044
2045    // For debugging purposes only.
2046    public CameraModule getCurrentModule() {
2047        return mCurrentModule;
2048    }
2049
2050    @Override
2051    public void showTutorial(AbstractTutorialOverlay tutorial) {
2052        mCameraAppUI.showTutorial(tutorial, getLayoutInflater());
2053    }
2054
2055    /**
2056     * Reads the current location recording settings and passes it on to the
2057     * location manager.
2058     */
2059    public void syncLocationManagerSetting() {
2060        mSettingsManager.syncLocationManager(mLocationManager);
2061    }
2062
2063    private void keepScreenOnForAWhile() {
2064        if (mKeepScreenOn) {
2065            return;
2066        }
2067        mMainHandler.removeMessages(MSG_CLEAR_SCREEN_ON_FLAG);
2068        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
2069        mMainHandler.sendEmptyMessageDelayed(MSG_CLEAR_SCREEN_ON_FLAG, SCREEN_DELAY_MS);
2070    }
2071
2072    private void resetScreenOn() {
2073        mKeepScreenOn = false;
2074        mMainHandler.removeMessages(MSG_CLEAR_SCREEN_ON_FLAG);
2075        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
2076    }
2077
2078    /**
2079     * @return {@code true} if the Gallery is launched successfully.
2080     */
2081    private boolean startGallery() {
2082        if (mGalleryIntent == null) {
2083            return false;
2084        }
2085        try {
2086            UsageStatistics.changeScreen(NavigationChange.Mode.GALLERY, InteractionCause.BUTTON);
2087            Intent startGalleryIntent = new Intent(mGalleryIntent);
2088            int currentDataId = mFilmstripController.getCurrentId();
2089            LocalData currentLocalData = mDataAdapter.getLocalData(currentDataId);
2090            if (currentLocalData != null) {
2091                GalleryHelper.setContentUri(startGalleryIntent, currentLocalData.getUri());
2092            }
2093            launchActivityByIntent(startGalleryIntent);
2094        } catch (ActivityNotFoundException e) {
2095            Log.w(TAG, "Failed to launch gallery activity, closing");
2096        }
2097        return false;
2098    }
2099
2100    private void setNfcBeamPushUriFromData(LocalData data) {
2101        final Uri uri = data.getUri();
2102        if (uri != Uri.EMPTY) {
2103            mNfcPushUris[0] = uri;
2104        } else {
2105            mNfcPushUris[0] = null;
2106        }
2107    }
2108
2109    /**
2110     * Updates the visibility of the filmstrip bottom controls and action bar.
2111     */
2112    private void updateUiByData(final int dataId) {
2113        final LocalData currentData = mDataAdapter.getLocalData(dataId);
2114        if (currentData == null) {
2115            Log.w(TAG, "Current data ID not found.");
2116            hideSessionProgress();
2117            return;
2118        }
2119        updateActionBarMenu(currentData);
2120
2121        /* Bottom controls. */
2122        updateBottomControlsByData(currentData);
2123
2124        if (isSecureCamera()) {
2125            // We cannot show buttons in secure camera since go to other
2126            // activities might create a security hole.
2127            mCameraAppUI.getFilmstripBottomControls().hideControls();
2128            return;
2129        }
2130
2131
2132        setNfcBeamPushUriFromData(currentData);
2133
2134        if (!mDataAdapter.isMetadataUpdated(dataId)) {
2135            mDataAdapter.updateMetadata(dataId);
2136        }
2137    }
2138
2139    /**
2140     * Updates the bottom controls based on the data.
2141     */
2142    private void updateBottomControlsByData(final LocalData currentData) {
2143
2144        final CameraAppUI.BottomPanel filmstripBottomPanel =
2145                mCameraAppUI.getFilmstripBottomControls();
2146        filmstripBottomPanel.showControls();
2147        filmstripBottomPanel.setEditButtonVisibility(
2148                currentData.isDataActionSupported(LocalData.DATA_ACTION_EDIT));
2149        filmstripBottomPanel.setShareButtonVisibility(
2150                currentData.isDataActionSupported(LocalData.DATA_ACTION_SHARE));
2151        filmstripBottomPanel.setDeleteButtonVisibility(
2152                currentData.isDataActionSupported(LocalData.DATA_ACTION_DELETE));
2153
2154        /* Progress bar */
2155
2156        Uri contentUri = currentData.getUri();
2157        CaptureSessionManager sessionManager = getServices()
2158                .getCaptureSessionManager();
2159
2160        if (sessionManager.hasErrorMessage(contentUri)) {
2161            showProcessError(sessionManager.getErrorMesage(contentUri));
2162        } else {
2163            filmstripBottomPanel.hideProgressError();
2164            int sessionProgress = sessionManager.getSessionProgress(contentUri);
2165
2166            if (sessionProgress < 0) {
2167                hideSessionProgress();
2168            } else {
2169                CharSequence progressMessage = sessionManager
2170                        .getSessionProgressMessage(contentUri);
2171                showSessionProgress(progressMessage);
2172                updateSessionProgress(sessionProgress);
2173            }
2174        }
2175
2176        /* View button */
2177
2178        // We need to add this to a separate DB.
2179        final int viewButtonVisibility;
2180        if (PanoramaMetadataLoader.isPanoramaAndUseViewer(currentData)) {
2181            viewButtonVisibility = CameraAppUI.BottomPanel.VIEWER_PHOTO_SPHERE;
2182        } else if (RgbzMetadataLoader.hasRGBZData(currentData)) {
2183            viewButtonVisibility = CameraAppUI.BottomPanel.VIEWER_REFOCUS;
2184        } else {
2185            viewButtonVisibility = CameraAppUI.BottomPanel.VIEWER_NONE;
2186        }
2187
2188        filmstripBottomPanel.setTinyPlanetEnabled(
2189                PanoramaMetadataLoader.isPanorama360(currentData));
2190        filmstripBottomPanel.setViewerButtonVisibility(viewButtonVisibility);
2191    }
2192
2193    private class PeekAnimationHandler extends Handler {
2194        private class DataAndCallback {
2195            LocalData mData;
2196            com.android.camera.util.Callback<Bitmap> mCallback;
2197
2198            public DataAndCallback(LocalData data, com.android.camera.util.Callback<Bitmap>
2199                    callback) {
2200                mData = data;
2201                mCallback = callback;
2202            }
2203        }
2204
2205        public PeekAnimationHandler(Looper looper) {
2206            super(looper);
2207        }
2208
2209        /**
2210         * Starts the animation decoding job and posts a {@code Runnable} back
2211         * when when the decoding is done.
2212         *
2213         * @param data The data item to decode the thumbnail for.
2214         * @param callback {@link com.android.camera.util.Callback} after the
2215         *                 decoding is done.
2216         */
2217        public void startDecodingJob(final LocalData data,
2218                final com.android.camera.util.Callback<Bitmap> callback) {
2219            PeekAnimationHandler.this.obtainMessage(0 /** dummy integer **/,
2220                    new DataAndCallback(data, callback)).sendToTarget();
2221        }
2222
2223        @Override
2224        public void handleMessage(Message msg) {
2225            final LocalData data = ((DataAndCallback) msg.obj).mData;
2226            final com.android.camera.util.Callback<Bitmap> callback =
2227                    ((DataAndCallback) msg.obj).mCallback;
2228            if (data == null || callback == null) {
2229                return;
2230            }
2231
2232            final Bitmap bitmap;
2233            switch (data.getLocalDataType()) {
2234                case LocalData.LOCAL_IN_PROGRESS_DATA:
2235                    byte[] jpegData = Storage.getJpegForSession(data.getUri());
2236                    if (jpegData != null) {
2237                        bitmap = BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length);
2238                    } else {
2239                        bitmap = null;
2240                    }
2241                    break;
2242
2243                case LocalData.LOCAL_IMAGE:
2244                    FileInputStream stream;
2245                    try {
2246                        stream = new FileInputStream(data.getPath());
2247                    } catch (FileNotFoundException e) {
2248                        Log.e(TAG, "File not found:" + data.getPath());
2249                        return;
2250                    }
2251                    Point dim = CameraUtil.resizeToFill(data.getWidth(), data.getHeight(),
2252                            data.getRotation(), mAboveFilmstripControlLayout.getWidth(),
2253                            mAboveFilmstripControlLayout.getMeasuredHeight());
2254                    if (data.getRotation() % 180 != 0) {
2255                        int dummy = dim.x;
2256                        dim.x = dim.y;
2257                        dim.y = dummy;
2258                    }
2259                    bitmap = LocalDataUtil
2260                            .loadImageThumbnailFromStream(stream, data.getWidth(), data.getHeight(),
2261                                    (int) (dim.x * 0.7f), (int) (dim.y * 0.7),
2262                                    data.getRotation(), MAX_PEEK_BITMAP_PIXELS);
2263                    break;
2264
2265                case LocalData.LOCAL_VIDEO:
2266                    bitmap = LocalDataUtil.loadVideoThumbnail(data.getPath());
2267                    break;
2268
2269                default:
2270                    bitmap = null;
2271                    break;
2272            }
2273
2274            if (bitmap == null) {
2275                return;
2276            }
2277
2278            mMainHandler.post(new Runnable() {
2279                @Override
2280                public void run() {
2281                    callback.onCallback(bitmap);
2282                }
2283            });
2284        }
2285    }
2286
2287    private void showDetailsDialog(int dataId) {
2288        final LocalData data = mDataAdapter.getLocalData(dataId);
2289        if (data == null) {
2290            return;
2291        }
2292        MediaDetails details = data.getMediaDetails(getAndroidContext());
2293        if (details == null) {
2294            return;
2295        }
2296        Dialog detailDialog = DetailsDialog.create(CameraActivity.this, details);
2297        detailDialog.show();
2298
2299        UsageStatistics.photoInteraction(
2300                UsageStatistics.hashFileName(fileNameFromDataID(dataId)),
2301                eventprotos.CameraEvent.InteractionType.DETAILS,
2302                InteractionCause.BUTTON);
2303    }
2304
2305    /**
2306     * Show or hide action bar items depending on current data type.
2307     */
2308    private void updateActionBarMenu(LocalData data) {
2309        if (mActionBarMenu == null) {
2310            return;
2311        }
2312
2313        MenuItem detailsMenuItem = mActionBarMenu.findItem(R.id.action_details);
2314        if (detailsMenuItem == null) {
2315            return;
2316        }
2317
2318        int type = data.getLocalDataType();
2319        boolean showDetails = (type == LocalData.LOCAL_IMAGE) || (type == LocalData.LOCAL_VIDEO);
2320        detailsMenuItem.setVisible(showDetails);
2321    }
2322}
2323