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