CameraActivity.java revision ad3003bbb275b91d7564568e413400fc187dbcd4
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.content.BroadcastReceiver;
24import android.content.ComponentName;
25import android.content.ContentResolver;
26import android.content.Context;
27import android.content.Intent;
28import android.content.IntentFilter;
29import android.content.ServiceConnection;
30import android.content.SharedPreferences;
31import android.content.pm.ActivityInfo;
32import android.content.res.Configuration;
33import android.graphics.drawable.ColorDrawable;
34import android.net.Uri;
35import android.nfc.NfcAdapter;
36import android.nfc.NfcAdapter.CreateBeamUrisCallback;
37import android.nfc.NfcEvent;
38import android.os.AsyncTask;
39import android.os.Build;
40import android.os.Bundle;
41import android.os.Handler;
42import android.os.IBinder;
43import android.os.Looper;
44import android.os.Message;
45import android.preference.PreferenceManager;
46import android.provider.MediaStore;
47import android.provider.Settings;
48import android.util.Log;
49import android.view.KeyEvent;
50import android.view.LayoutInflater;
51import android.view.Menu;
52import android.view.MenuInflater;
53import android.view.MenuItem;
54import android.view.MotionEvent;
55import android.view.OrientationEventListener;
56import android.view.View;
57import android.view.ViewGroup;
58import android.view.Window;
59import android.view.WindowManager;
60import android.widget.FrameLayout;
61import android.widget.ImageView;
62import android.widget.ProgressBar;
63import android.widget.ShareActionProvider;
64
65import com.android.camera.app.AppManagerFactory;
66import com.android.camera.app.PanoramaStitchingManager;
67import com.android.camera.crop.CropActivity;
68import com.android.camera.data.CameraDataAdapter;
69import com.android.camera.data.CameraPreviewData;
70import com.android.camera.data.FixedFirstDataAdapter;
71import com.android.camera.data.FixedLastDataAdapter;
72import com.android.camera.data.LocalData;
73import com.android.camera.data.LocalDataAdapter;
74import com.android.camera.data.LocalMediaObserver;
75import com.android.camera.data.MediaDetails;
76import com.android.camera.data.SimpleViewData;
77import com.android.camera.tinyplanet.TinyPlanetFragment;
78import com.android.camera.ui.ModuleSwitcher;
79import com.android.camera.ui.DetailsDialog;
80import com.android.camera.ui.FilmStripView;
81import com.android.camera.util.ApiHelper;
82import com.android.camera.util.CameraUtil;
83import com.android.camera.util.GcamHelper;
84import com.android.camera.util.PhotoSphereHelper;
85import com.android.camera.util.PhotoSphereHelper.PanoramaViewHelper;
86import com.android.camera2.R;
87
88import static com.android.camera.CameraManager.CameraOpenErrorCallback;
89
90public class CameraActivity extends Activity
91        implements ModuleSwitcher.ModuleSwitchListener,
92        ActionBar.OnMenuVisibilityListener {
93
94    private static final String TAG = "CAM_Activity";
95
96    private static final String INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE =
97            "android.media.action.STILL_IMAGE_CAMERA_SECURE";
98    public static final String ACTION_IMAGE_CAPTURE_SECURE =
99            "android.media.action.IMAGE_CAPTURE_SECURE";
100    public static final String ACTION_TRIM_VIDEO =
101            "com.android.camera.action.TRIM";
102    public static final String MEDIA_ITEM_PATH = "media-item-path";
103
104    private static final String PREF_STARTUP_MODULE_INDEX = "camera.startup_module";
105
106    // The intent extra for camera from secure lock screen. True if the gallery
107    // should only show newly captured pictures. sSecureAlbumId does not
108    // increment. This is used when switching between camera, camcorder, and
109    // panorama. If the extra is not set, it is in the normal camera mode.
110    public static final String SECURE_CAMERA_EXTRA = "secure_camera";
111
112    /**
113     * Request code from an activity we started that indicated that we do not
114     * want to reset the view to the preview in onResume.
115     */
116    public static final int REQ_CODE_DONT_SWITCH_TO_PREVIEW = 142;
117
118    private static final int HIDE_ACTION_BAR = 1;
119    private static final long SHOW_ACTION_BAR_TIMEOUT_MS = 3000;
120
121    /** Whether onResume should reset the view to the preview. */
122    private boolean mResetToPreviewOnResume = true;
123
124    // Supported operations at FilmStripView. Different data has different
125    // set of supported operations.
126    private static final int SUPPORT_DELETE = 1 << 0;
127    private static final int SUPPORT_ROTATE = 1 << 1;
128    private static final int SUPPORT_INFO = 1 << 2;
129    private static final int SUPPORT_CROP = 1 << 3;
130    private static final int SUPPORT_SETAS = 1 << 4;
131    private static final int SUPPORT_EDIT = 1 << 5;
132    private static final int SUPPORT_TRIM = 1 << 6;
133    private static final int SUPPORT_SHARE = 1 << 7;
134    private static final int SUPPORT_SHARE_PANORAMA360 = 1 << 8;
135    private static final int SUPPORT_SHOW_ON_MAP = 1 << 9;
136    private static final int SUPPORT_ALL = 0xffffffff;
137
138    /** This data adapter is used by FilmStripView. */
139    private LocalDataAdapter mDataAdapter;
140    /** This data adapter represents the real local camera data. */
141    private LocalDataAdapter mWrappedDataAdapter;
142
143    private PanoramaStitchingManager mPanoramaManager;
144    private int mCurrentModuleIndex;
145    private CameraModule mCurrentModule;
146    private FrameLayout mAboveFilmstripControlLayout;
147    private View mCameraModuleRootView;
148    private FilmStripView mFilmStripView;
149    private ProgressBar mBottomProgress;
150    private View mPanoStitchingPanel;
151    private int mResultCodeForTesting;
152    private Intent mResultDataForTesting;
153    private OnScreenHint mStorageHint;
154    private long mStorageSpaceBytes = Storage.LOW_STORAGE_THRESHOLD_BYTES;
155    private boolean mAutoRotateScreen;
156    private boolean mSecureCamera;
157    // This is a hack to speed up the start of SecureCamera.
158    private static boolean sFirstStartAfterScreenOn = true;
159    private int mLastRawOrientation;
160    private MyOrientationEventListener mOrientationListener;
161    private Handler mMainHandler;
162    private PanoramaViewHelper mPanoramaViewHelper;
163    private CameraPreviewData mCameraPreviewData;
164    private ActionBar mActionBar;
165    private OnActionBarVisibilityListener mOnActionBarVisibilityListener = null;
166    private Menu mActionBarMenu;
167    private ViewGroup mUndoDeletionBar;
168    private boolean mIsUndoingDeletion = false;
169
170    private Uri[] mNfcPushUris = new Uri[1];
171
172    private ShareActionProvider mStandardShareActionProvider;
173    private Intent mStandardShareIntent;
174    private ShareActionProvider mPanoramaShareActionProvider;
175    private Intent mPanoramaShareIntent;
176    private LocalMediaObserver mLocalImagesObserver;
177    private LocalMediaObserver mLocalVideosObserver;
178
179    private final int DEFAULT_SYSTEM_UI_VISIBILITY = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
180            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
181    private boolean mPendingDeletion = false;
182
183    private Intent mVideoShareIntent;
184    private Intent mImageShareIntent;
185
186    private class MyOrientationEventListener
187            extends OrientationEventListener {
188        public MyOrientationEventListener(Context context) {
189            super(context);
190        }
191
192        @Override
193        public void onOrientationChanged(int orientation) {
194            // We keep the last known orientation. So if the user first orient
195            // the camera then point the camera to floor or sky, we still have
196            // the correct orientation.
197            if (orientation == ORIENTATION_UNKNOWN) {
198                return;
199            }
200            mLastRawOrientation = orientation;
201            mCurrentModule.onOrientationChanged(orientation);
202        }
203    }
204
205    private MediaSaveService mMediaSaveService;
206    private ServiceConnection mConnection = new ServiceConnection() {
207        @Override
208        public void onServiceConnected(ComponentName className, IBinder b) {
209            mMediaSaveService = ((MediaSaveService.LocalBinder) b).getService();
210            mCurrentModule.onMediaSaveServiceConnected(mMediaSaveService);
211        }
212
213        @Override
214        public void onServiceDisconnected(ComponentName className) {
215            if (mMediaSaveService != null) {
216                mMediaSaveService.setListener(null);
217                mMediaSaveService = null;
218            }
219        }
220    };
221
222    private CameraOpenErrorCallback mCameraOpenErrorCallback =
223            new CameraOpenErrorCallback() {
224                @Override
225                public void onCameraDisabled(int cameraId) {
226                    CameraUtil.showErrorAndFinish(CameraActivity.this,
227                            R.string.camera_disabled);
228                }
229
230                @Override
231                public void onDeviceOpenFailure(int cameraId) {
232                    CameraUtil.showErrorAndFinish(CameraActivity.this,
233                            R.string.cannot_connect_camera);
234                }
235
236                @Override
237                public void onReconnectionFailure(CameraManager mgr) {
238                    CameraUtil.showErrorAndFinish(CameraActivity.this,
239                            R.string.cannot_connect_camera);
240                }
241            };
242
243    // close activity when screen turns off
244    private BroadcastReceiver mScreenOffReceiver = new BroadcastReceiver() {
245        @Override
246        public void onReceive(Context context, Intent intent) {
247            finish();
248        }
249    };
250
251    private static BroadcastReceiver sScreenOffReceiver;
252
253    private static class ScreenOffReceiver extends BroadcastReceiver {
254        @Override
255        public void onReceive(Context context, Intent intent) {
256            sFirstStartAfterScreenOn = true;
257        }
258    }
259
260    private class MainHandler extends Handler {
261        public MainHandler(Looper looper) {
262            super(looper);
263        }
264
265        @Override
266        public void handleMessage(Message msg) {
267            if (msg.what == HIDE_ACTION_BAR) {
268                removeMessages(HIDE_ACTION_BAR);
269                CameraActivity.this.setSystemBarsVisibility(false);
270            }
271        }
272    }
273
274    public interface OnActionBarVisibilityListener {
275        public void onActionBarVisibilityChanged(boolean isVisible);
276    }
277
278    public void setOnActionBarVisibilityListener(OnActionBarVisibilityListener listener) {
279        mOnActionBarVisibilityListener = listener;
280    }
281
282    public static boolean isFirstStartAfterScreenOn() {
283        return sFirstStartAfterScreenOn;
284    }
285
286    public static void resetFirstStartAfterScreenOn() {
287        sFirstStartAfterScreenOn = false;
288    }
289
290    private FilmStripView.Listener mFilmStripListener =
291            new FilmStripView.Listener() {
292                @Override
293                public void onDataPromoted(int dataID) {
294                    removeData(dataID);
295                }
296
297                @Override
298                public void onDataDemoted(int dataID) {
299                    removeData(dataID);
300                }
301
302                @Override
303                public void onDataFullScreenChange(int dataID, boolean full) {
304                    boolean isCameraID = isCameraPreview(dataID);
305                    if (!isCameraID) {
306                        if (!full) {
307                            // Always show action bar in filmstrip mode
308                            CameraActivity.this.setSystemBarsVisibility(true, false);
309                        } else if (mActionBar.isShowing()) {
310                            // Hide action bar after time out in full screen mode
311                            mMainHandler.sendEmptyMessageDelayed(HIDE_ACTION_BAR,
312                                    SHOW_ACTION_BAR_TIMEOUT_MS);
313                        }
314                    }
315                }
316
317                /**
318                 * Check if the local data corresponding to dataID is the camera
319                 * preview.
320                 *
321                 * @param dataID the ID of the local data
322                 * @return true if the local data is not null and it is the
323                 *         camera preview.
324                 */
325                private boolean isCameraPreview(int dataID) {
326                    LocalData localData = mDataAdapter.getLocalData(dataID);
327                    if (localData == null) {
328                        Log.w(TAG, "Current data ID not found.");
329                        return false;
330                    }
331                    return localData.getLocalDataType() == LocalData.LOCAL_CAMERA_PREVIEW;
332                }
333
334                @Override
335                public void onCurrentDataChanged(final int dataID, final boolean current) {
336                    // Delay hiding action bar if there is any user interaction
337                    if (mMainHandler.hasMessages(HIDE_ACTION_BAR)) {
338                        mMainHandler.removeMessages(HIDE_ACTION_BAR);
339                        mMainHandler.sendEmptyMessageDelayed(HIDE_ACTION_BAR,
340                                SHOW_ACTION_BAR_TIMEOUT_MS);
341                    }
342                    runOnUiThread(new Runnable() {
343                        @Override
344                        public void run() {
345                            LocalData currentData = mDataAdapter.getLocalData(dataID);
346                            if (currentData == null) {
347                                Log.w(TAG, "Current data ID not found.");
348                                hidePanoStitchingProgress();
349                                return;
350                            }
351                            boolean isCameraID = currentData.getLocalDataType() ==
352                                    LocalData.LOCAL_CAMERA_PREVIEW;
353                            if (!current) {
354                                if (isCameraID) {
355                                    mCurrentModule.onPreviewFocusChanged(false);
356                                    CameraActivity.this.setSystemBarsVisibility(true);
357                                }
358                                hidePanoStitchingProgress();
359                            } else {
360                                if (isCameraID) {
361                                    mCurrentModule.onPreviewFocusChanged(true);
362                                    // Don't show the action bar in Camera
363                                    // preview.
364                                    CameraActivity.this.setSystemBarsVisibility(false);
365                                    if (mPendingDeletion) {
366                                        performDeletion();
367                                    }
368                                } else {
369                                    updateActionBarMenu(dataID);
370                                }
371
372                                Uri contentUri = currentData.getContentUri();
373                                if (contentUri == null) {
374                                    hidePanoStitchingProgress();
375                                    return;
376                                }
377                                int panoStitchingProgress = mPanoramaManager.getTaskProgress(
378                                        contentUri);
379                                if (panoStitchingProgress < 0) {
380                                    hidePanoStitchingProgress();
381                                    return;
382                                }
383                                showPanoStitchingProgress();
384                                updateStitchingProgress(panoStitchingProgress);
385                            }
386                        }
387                    });
388                }
389
390                @Override
391                public void onToggleSystemDecorsVisibility(int dataID) {
392                    // If action bar is showing, hide it immediately, otherwise
393                    // show action bar and hide it later
394                    if (mActionBar.isShowing()) {
395                        CameraActivity.this.setSystemBarsVisibility(false);
396                    } else {
397                        // Don't show the action bar if that is the camera preview.
398                        boolean isCameraID = isCameraPreview(dataID);
399                        if (!isCameraID) {
400                            CameraActivity.this.setSystemBarsVisibility(true, true);
401                        }
402                    }
403                }
404
405                @Override
406                public void setSystemDecorsVisibility(boolean visible) {
407                    CameraActivity.this.setSystemBarsVisibility(visible);
408                }
409            };
410
411    public void gotoGallery() {
412        mFilmStripView.getController().goToNextItem();
413    }
414
415    /**
416     * If {@param visible} is false, this hides the action bar and switches the system UI
417     * to lights-out mode.
418     */
419
420    private void setSystemBarsVisibility(boolean visible) {
421        setSystemBarsVisibility(visible, false);
422    }
423
424    /**
425     * If {@param visible} is false, this hides the action bar and switches the
426     * system UI to lights-out mode. If {@param hideLater} is true, a delayed message
427     * will be sent after a timeout to hide the action bar.
428     */
429    private void setSystemBarsVisibility(boolean visible, boolean hideLater) {
430        mMainHandler.removeMessages(HIDE_ACTION_BAR);
431        boolean currentlyVisible = mActionBar.isShowing();
432
433        if (visible != currentlyVisible) {
434            int visibility = DEFAULT_SYSTEM_UI_VISIBILITY | (visible ? View.SYSTEM_UI_FLAG_VISIBLE
435                    : View.SYSTEM_UI_FLAG_LOW_PROFILE | View.SYSTEM_UI_FLAG_FULLSCREEN);
436            mAboveFilmstripControlLayout.setSystemUiVisibility(visibility);
437            if (visible) {
438                mActionBar.show();
439            } else {
440                mActionBar.hide();
441            }
442            if (mOnActionBarVisibilityListener != null) {
443                mOnActionBarVisibilityListener.onActionBarVisibilityChanged(visible);
444            }
445        }
446
447        // Now delay hiding the bars
448        if (visible && hideLater) {
449            mMainHandler.sendEmptyMessageDelayed(HIDE_ACTION_BAR, SHOW_ACTION_BAR_TIMEOUT_MS);
450        }
451    }
452
453    private void hidePanoStitchingProgress() {
454        mPanoStitchingPanel.setVisibility(View.GONE);
455    }
456
457    private void showPanoStitchingProgress() {
458        mPanoStitchingPanel.setVisibility(View.VISIBLE);
459    }
460
461    private void updateStitchingProgress(int progress) {
462        mBottomProgress.setProgress(progress);
463    }
464
465    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
466    private void setupNfcBeamPush() {
467        NfcAdapter adapter = NfcAdapter.getDefaultAdapter(CameraActivity.this);
468        if (adapter == null) {
469            return;
470        }
471
472        if (!ApiHelper.HAS_SET_BEAM_PUSH_URIS) {
473            // Disable beaming
474            adapter.setNdefPushMessage(null, CameraActivity.this);
475            return;
476        }
477
478        adapter.setBeamPushUris(null, CameraActivity.this);
479        adapter.setBeamPushUrisCallback(new CreateBeamUrisCallback() {
480            @Override
481            public Uri[] createBeamUris(NfcEvent event) {
482                return mNfcPushUris;
483            }
484        }, CameraActivity.this);
485    }
486
487    private void setNfcBeamPushUri(Uri uri) {
488        mNfcPushUris[0] = uri;
489    }
490
491    private void setStandardShareIntent(Uri contentUri, String mimeType) {
492        mStandardShareIntent = getShareIntentFromType(mimeType);
493        if (mStandardShareIntent != null) {
494            mStandardShareIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
495            mStandardShareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
496            if (mStandardShareActionProvider != null) {
497                mStandardShareActionProvider.setShareIntent(mStandardShareIntent);
498            }
499        }
500    }
501
502    /**
503     * Get the share intent according to the mimeType
504     *
505     * @param mimeType The mimeType of current data.
506     * @return the video/image's ShareIntent or null if mimeType is invalid.
507     */
508    private Intent getShareIntentFromType(String mimeType) {
509        // Lazily create the intent object.
510        if (mimeType.startsWith("video/")) {
511            if (mVideoShareIntent == null) {
512                mVideoShareIntent = new Intent(Intent.ACTION_SEND);
513                mVideoShareIntent.setType("video/*");
514            }
515            return mVideoShareIntent;
516        } else if (mimeType.startsWith("image/")) {
517            if (mImageShareIntent == null) {
518                mImageShareIntent = new Intent(Intent.ACTION_SEND);
519                mImageShareIntent.setType("image/*");
520            }
521            return mImageShareIntent;
522        }
523        Log.w(TAG, "unsupported mimeType " + mimeType);
524        return null;
525    }
526
527    private void setPanoramaShareIntent(Uri contentUri) {
528        if (mPanoramaShareIntent == null) {
529            mPanoramaShareIntent = new Intent(Intent.ACTION_SEND);
530        }
531        mPanoramaShareIntent.setType("application/vnd.google.panorama360+jpg");
532        mPanoramaShareIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
533        if (mPanoramaShareActionProvider != null) {
534            mPanoramaShareActionProvider.setShareIntent(mPanoramaShareIntent);
535        }
536    }
537
538    @Override
539    public void onMenuVisibilityChanged(boolean isVisible) {
540        // If menu is showing, we need to make sure action bar does not go away.
541        mMainHandler.removeMessages(HIDE_ACTION_BAR);
542        if (!isVisible) {
543            mMainHandler.sendEmptyMessageDelayed(HIDE_ACTION_BAR, SHOW_ACTION_BAR_TIMEOUT_MS);
544        }
545    }
546
547    /**
548     * According to the data type, make the menu items for supported operations
549     * visible.
550     *
551     * @param dataID the data ID of the current item.
552     */
553    private void updateActionBarMenu(int dataID) {
554        LocalData currentData = mDataAdapter.getLocalData(dataID);
555        int type = currentData.getLocalDataType();
556
557        if (mActionBarMenu == null) {
558            return;
559        }
560
561        int supported = 0;
562        switch (type) {
563            case LocalData.LOCAL_IMAGE:
564                supported |= SUPPORT_DELETE | SUPPORT_ROTATE | SUPPORT_INFO
565                        | SUPPORT_CROP | SUPPORT_SETAS | SUPPORT_EDIT
566                        | SUPPORT_SHARE | SUPPORT_SHOW_ON_MAP;
567                break;
568            case LocalData.LOCAL_VIDEO:
569                supported |= SUPPORT_DELETE | SUPPORT_INFO | SUPPORT_TRIM
570                        | SUPPORT_SHARE;
571                break;
572            case LocalData.LOCAL_PHOTO_SPHERE:
573                supported |= SUPPORT_DELETE | SUPPORT_ROTATE | SUPPORT_INFO
574                        | SUPPORT_CROP | SUPPORT_SETAS | SUPPORT_EDIT
575                        | SUPPORT_SHARE | SUPPORT_SHOW_ON_MAP;
576                break;
577            case LocalData.LOCAL_360_PHOTO_SPHERE:
578                supported |= SUPPORT_DELETE | SUPPORT_ROTATE | SUPPORT_INFO
579                        | SUPPORT_CROP | SUPPORT_SETAS | SUPPORT_EDIT
580                        | SUPPORT_SHARE | SUPPORT_SHARE_PANORAMA360
581                        | SUPPORT_SHOW_ON_MAP;
582                break;
583            default:
584                break;
585        }
586
587        setMenuItemVisible(mActionBarMenu, R.id.action_delete,
588                (supported & SUPPORT_DELETE) != 0);
589        setMenuItemVisible(mActionBarMenu, R.id.action_rotate_ccw,
590                (supported & SUPPORT_ROTATE) != 0);
591        setMenuItemVisible(mActionBarMenu, R.id.action_rotate_cw,
592                (supported & SUPPORT_ROTATE) != 0);
593        setMenuItemVisible(mActionBarMenu, R.id.action_details,
594                (supported & SUPPORT_INFO) != 0);
595        setMenuItemVisible(mActionBarMenu, R.id.action_crop,
596                (supported & SUPPORT_CROP) != 0);
597        setMenuItemVisible(mActionBarMenu, R.id.action_setas,
598                (supported & SUPPORT_SETAS) != 0);
599        setMenuItemVisible(mActionBarMenu, R.id.action_edit,
600                (supported & SUPPORT_EDIT) != 0);
601        setMenuItemVisible(mActionBarMenu, R.id.action_trim,
602                (supported & SUPPORT_TRIM) != 0);
603
604        boolean standardShare = (supported & SUPPORT_SHARE) != 0;
605        boolean panoramaShare = (supported & SUPPORT_SHARE_PANORAMA360) != 0;
606        setMenuItemVisible(mActionBarMenu, R.id.action_share, standardShare);
607        setMenuItemVisible(mActionBarMenu, R.id.action_share_panorama, panoramaShare);
608
609        if (panoramaShare) {
610            // For 360 PhotoSphere, relegate standard share to the overflow menu
611            MenuItem item = mActionBarMenu.findItem(R.id.action_share);
612            if (item != null) {
613                item.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
614                item.setTitle(getResources().getString(R.string.share_as_photo));
615            }
616            // And, promote "share as panorama" to action bar
617            item = mActionBarMenu.findItem(R.id.action_share_panorama);
618            if (item != null) {
619                item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
620            }
621            setPanoramaShareIntent(currentData.getContentUri());
622        }
623        if (standardShare) {
624            if (!panoramaShare) {
625                MenuItem item = mActionBarMenu.findItem(R.id.action_share);
626                if (item != null) {
627                    item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
628                    item.setTitle(getResources().getString(R.string.share));
629                }
630            }
631            setStandardShareIntent(currentData.getContentUri(), currentData.getMimeType());
632            setNfcBeamPushUri(currentData.getContentUri());
633        }
634
635        boolean itemHasLocation = currentData.getLatLong() != null;
636        setMenuItemVisible(mActionBarMenu, R.id.action_show_on_map,
637                itemHasLocation && (supported & SUPPORT_SHOW_ON_MAP) != 0);
638    }
639
640    private void setMenuItemVisible(Menu menu, int itemId, boolean visible) {
641        MenuItem item = menu.findItem(itemId);
642        if (item != null)
643            item.setVisible(visible);
644    }
645
646    private ImageTaskManager.TaskListener mStitchingListener =
647            new ImageTaskManager.TaskListener() {
648                @Override
649                public void onTaskQueued(String filePath, final Uri imageUri) {
650                    mMainHandler.post(new Runnable() {
651                        @Override
652                        public void run() {
653                            notifyNewMedia(imageUri);
654                        }
655                    });
656                }
657
658                @Override
659                public void onTaskDone(String filePath, final Uri imageUri) {
660                    Log.v(TAG, "onTaskDone:" + filePath);
661                    mMainHandler.post(new Runnable() {
662                        @Override
663                        public void run() {
664                            int doneID = mDataAdapter.findDataByContentUri(imageUri);
665                            int currentDataId = mFilmStripView.getCurrentId();
666
667                            if (currentDataId == doneID) {
668                                hidePanoStitchingProgress();
669                                updateStitchingProgress(0);
670                            }
671
672                            mDataAdapter.refresh(getContentResolver(), imageUri);
673                        }
674                    });
675                }
676
677                @Override
678                public void onTaskProgress(
679                        String filePath, final Uri imageUri, final int progress) {
680                    mMainHandler.post(new Runnable() {
681                        @Override
682                        public void run() {
683                            int currentDataId = mFilmStripView.getCurrentId();
684                            if (currentDataId == -1) {
685                                return;
686                            }
687                            if (imageUri.equals(
688                                    mDataAdapter.getLocalData(currentDataId).getContentUri())) {
689                                updateStitchingProgress(progress);
690                            }
691                        }
692                    });
693                }
694            };
695
696    public MediaSaveService getMediaSaveService() {
697        return mMediaSaveService;
698    }
699
700    public void notifyNewMedia(Uri uri) {
701        ContentResolver cr = getContentResolver();
702        String mimeType = cr.getType(uri);
703        if (mimeType.startsWith("video/")) {
704            sendBroadcast(new Intent(CameraUtil.ACTION_NEW_VIDEO, uri));
705            mDataAdapter.addNewVideo(cr, uri);
706        } else if (mimeType.startsWith("image/")) {
707            CameraUtil.broadcastNewPicture(this, uri);
708            mDataAdapter.addNewPhoto(cr, uri);
709        } else if (mimeType.startsWith("application/stitching-preview")) {
710            mDataAdapter.addNewPhoto(cr, uri);
711        } else {
712            android.util.Log.w(TAG, "Unknown new media with MIME type:"
713                    + mimeType + ", uri:" + uri);
714        }
715    }
716
717    private void removeData(int dataID) {
718        mDataAdapter.removeData(CameraActivity.this, dataID);
719        updateActionBarMenu(dataID);
720        if (mDataAdapter.getTotalNumber() > 1) {
721            showUndoDeletionBar();
722        } else {
723            // If camera preview is the only view left in filmstrip,
724            // no need to show undo bar.
725            mPendingDeletion = true;
726            performDeletion();
727        }
728    }
729
730    private void bindMediaSaveService() {
731        Intent intent = new Intent(this, MediaSaveService.class);
732        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
733    }
734
735    private void unbindMediaSaveService() {
736        if (mConnection != null) {
737            unbindService(mConnection);
738        }
739    }
740
741    @Override
742    public boolean onCreateOptionsMenu(Menu menu) {
743        // Inflate the menu items for use in the action bar
744        MenuInflater inflater = getMenuInflater();
745        inflater.inflate(R.menu.operations, menu);
746        mActionBarMenu = menu;
747
748        // Configure the standard share action provider
749        MenuItem item = menu.findItem(R.id.action_share);
750        mStandardShareActionProvider = (ShareActionProvider) item.getActionProvider();
751        mStandardShareActionProvider.setShareHistoryFileName("standard_share_history.xml");
752        if (mStandardShareIntent != null) {
753            mStandardShareActionProvider.setShareIntent(mStandardShareIntent);
754        }
755
756        // Configure the panorama share action provider
757        item = menu.findItem(R.id.action_share_panorama);
758        mPanoramaShareActionProvider = (ShareActionProvider) item.getActionProvider();
759        mPanoramaShareActionProvider.setShareHistoryFileName("panorama_share_history.xml");
760        if (mPanoramaShareIntent != null) {
761            mPanoramaShareActionProvider.setShareIntent(mPanoramaShareIntent);
762        }
763
764        return super.onCreateOptionsMenu(menu);
765    }
766
767    @Override
768    public boolean onOptionsItemSelected(MenuItem item) {
769        int currentDataId = mFilmStripView.getCurrentId();
770        if (currentDataId < 0) {
771            return false;
772        }
773        final LocalData localData = mDataAdapter.getLocalData(currentDataId);
774
775        // Handle presses on the action bar items
776        switch (item.getItemId()) {
777            case android.R.id.home:
778                // ActionBar's Up/Home button was clicked
779                if (!CameraUtil.launchGallery(CameraActivity.this)) {
780                    mFilmStripView.getController().goToFirstItem();
781                }
782                return true;
783            case R.id.action_delete:
784                removeData(currentDataId);
785                return true;
786            case R.id.action_edit:
787                launchEditor(localData);
788                return true;
789            case R.id.action_trim: {
790                // This is going to be handled by the Gallery app.
791                Intent intent = new Intent(ACTION_TRIM_VIDEO);
792                LocalData currentData = mDataAdapter.getLocalData(
793                        mFilmStripView.getCurrentId());
794                intent.setData(currentData.getContentUri());
795                // We need the file path to wrap this into a RandomAccessFile.
796                intent.putExtra(MEDIA_ITEM_PATH, currentData.getPath());
797                startActivityForResult(intent, REQ_CODE_DONT_SWITCH_TO_PREVIEW);
798                return true;
799            }
800            case R.id.action_rotate_ccw:
801                localData.rotate90Degrees(this, mDataAdapter, currentDataId, false);
802                return true;
803            case R.id.action_rotate_cw:
804                localData.rotate90Degrees(this, mDataAdapter, currentDataId, true);
805                return true;
806            case R.id.action_crop: {
807                Intent intent = new Intent(CropActivity.CROP_ACTION);
808                intent.setClass(this, CropActivity.class);
809                intent.setDataAndType(localData.getContentUri(), localData.getMimeType())
810                        .setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
811                startActivityForResult(intent, REQ_CODE_DONT_SWITCH_TO_PREVIEW);
812                return true;
813            }
814            case R.id.action_setas: {
815                Intent intent = new Intent(Intent.ACTION_ATTACH_DATA)
816                        .setDataAndType(localData.getContentUri(),
817                                localData.getMimeType())
818                        .setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
819                intent.putExtra("mimeType", intent.getType());
820                startActivityForResult(Intent.createChooser(
821                        intent, getString(R.string.set_as)), REQ_CODE_DONT_SWITCH_TO_PREVIEW);
822                return true;
823            }
824            case R.id.action_details:
825                (new AsyncTask<Void, Void, MediaDetails>() {
826                    @Override
827                    protected MediaDetails doInBackground(Void... params) {
828                        return localData.getMediaDetails(CameraActivity.this);
829                    }
830
831                    @Override
832                    protected void onPostExecute(MediaDetails mediaDetails) {
833                        DetailsDialog.create(CameraActivity.this, mediaDetails).show();
834                    }
835                }).execute();
836                return true;
837            case R.id.action_show_on_map:
838                double[] latLong = localData.getLatLong();
839                if (latLong != null) {
840                    CameraUtil.showOnMap(this, latLong);
841                }
842                return true;
843            default:
844                return super.onOptionsItemSelected(item);
845        }
846    }
847
848    private boolean isCaptureIntent() {
849        if (MediaStore.ACTION_VIDEO_CAPTURE.equals(getIntent().getAction())
850                || MediaStore.ACTION_IMAGE_CAPTURE.equals(getIntent().getAction())
851                || MediaStore.ACTION_IMAGE_CAPTURE_SECURE.equals(getIntent().getAction())) {
852            return true;
853        } else {
854            return false;
855        }
856    }
857
858    @Override
859    public void onCreate(Bundle state) {
860        super.onCreate(state);
861        getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
862        setContentView(R.layout.camera_filmstrip);
863        mActionBar = getActionBar();
864        mActionBar.addOnMenuVisibilityListener(this);
865
866        if (ApiHelper.HAS_ROTATION_ANIMATION) {
867            setRotationAnimation();
868        }
869
870        mMainHandler = new MainHandler(getMainLooper());
871        // Check if this is in the secure camera mode.
872        Intent intent = getIntent();
873        String action = intent.getAction();
874        if (INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE.equals(action)
875                || ACTION_IMAGE_CAPTURE_SECURE.equals(action)) {
876            mSecureCamera = true;
877        } else {
878            mSecureCamera = intent.getBooleanExtra(SECURE_CAMERA_EXTRA, false);
879        }
880
881        if (mSecureCamera) {
882            // Change the window flags so that secure camera can show when locked
883            Window win = getWindow();
884            WindowManager.LayoutParams params = win.getAttributes();
885            params.flags |= WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
886            win.setAttributes(params);
887
888            // Filter for screen off so that we can finish secure camera activity
889            // when screen is off.
890            IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
891            registerReceiver(mScreenOffReceiver, filter);
892            // TODO: This static screen off event receiver is a workaround to the
893            // double onResume() invocation (onResume->onPause->onResume). We should
894            // find a better solution to this.
895            if (sScreenOffReceiver == null) {
896                sScreenOffReceiver = new ScreenOffReceiver();
897                registerReceiver(sScreenOffReceiver, filter);
898            }
899        }
900        mAboveFilmstripControlLayout =
901                (FrameLayout) findViewById(R.id.camera_above_filmstrip_layout);
902        mAboveFilmstripControlLayout.setFitsSystemWindows(true);
903        // Hide action bar first since we are in full screen mode first, and
904        // switch the system UI to lights-out mode.
905        this.setSystemBarsVisibility(false);
906        mPanoramaManager = AppManagerFactory.getInstance(this)
907                .getPanoramaStitchingManager();
908        mPanoramaManager.addTaskListener(mStitchingListener);
909        LayoutInflater inflater = getLayoutInflater();
910        View rootLayout = inflater.inflate(R.layout.camera, null, false);
911        mCameraModuleRootView = rootLayout.findViewById(R.id.camera_app_root);
912        mPanoStitchingPanel = findViewById(R.id.pano_stitching_progress_panel);
913        mBottomProgress = (ProgressBar) findViewById(R.id.pano_stitching_progress_bar);
914        mCameraPreviewData = new CameraPreviewData(rootLayout,
915                FilmStripView.ImageData.SIZE_FULL,
916                FilmStripView.ImageData.SIZE_FULL);
917        // Put a CameraPreviewData at the first position.
918        mWrappedDataAdapter = new FixedFirstDataAdapter(
919                new CameraDataAdapter(new ColorDrawable(
920                        getResources().getColor(R.color.photo_placeholder))),
921                mCameraPreviewData);
922        mFilmStripView = (FilmStripView) findViewById(R.id.filmstrip_view);
923        mFilmStripView.setViewGap(
924                getResources().getDimensionPixelSize(R.dimen.camera_film_strip_gap));
925        mPanoramaViewHelper = new PanoramaViewHelper(this);
926        mPanoramaViewHelper.onCreate();
927        mFilmStripView.setPanoramaViewHelper(mPanoramaViewHelper);
928        // Set up the camera preview first so the preview shows up ASAP.
929        mFilmStripView.setListener(mFilmStripListener);
930
931        int moduleIndex = -1;
932        if (MediaStore.INTENT_ACTION_VIDEO_CAMERA.equals(getIntent().getAction())
933                || MediaStore.ACTION_VIDEO_CAPTURE.equals(getIntent().getAction())) {
934            moduleIndex = ModuleSwitcher.VIDEO_MODULE_INDEX;
935        } else if (MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA.equals(getIntent().getAction())
936                || MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE.equals(getIntent()
937                        .getAction())
938                || MediaStore.ACTION_IMAGE_CAPTURE.equals(getIntent().getAction())
939                || MediaStore.ACTION_IMAGE_CAPTURE_SECURE.equals(getIntent().getAction())) {
940            moduleIndex = ModuleSwitcher.PHOTO_MODULE_INDEX;
941        } else {
942            // If the activity has not been started using an explicit intent,
943            // read the module index from the last time the user changed modes
944            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
945            moduleIndex = prefs.getInt(PREF_STARTUP_MODULE_INDEX, -1);
946            if ((moduleIndex == ModuleSwitcher.GCAM_MODULE_INDEX &&
947                    !GcamHelper.hasGcamCapture()) || moduleIndex < 0) {
948                moduleIndex = ModuleSwitcher.PHOTO_MODULE_INDEX;
949            }
950        }
951
952        mOrientationListener = new MyOrientationEventListener(this);
953        setModuleFromIndex(moduleIndex);
954        mCurrentModule.init(this, mCameraModuleRootView);
955
956        if (!mSecureCamera) {
957            mDataAdapter = mWrappedDataAdapter;
958            mFilmStripView.setDataAdapter(mDataAdapter);
959            if (!isCaptureIntent()) {
960                mDataAdapter.requestLoad(getContentResolver());
961            }
962        } else {
963            // Put a lock placeholder as the last image by setting its date to
964            // 0.
965            ImageView v = (ImageView) getLayoutInflater().inflate(
966                    R.layout.secure_album_placeholder, null);
967            v.setOnClickListener(new View.OnClickListener() {
968                @Override
969                public void onClick(View view) {
970                    CameraUtil.launchGallery(CameraActivity.this);
971                    finish();
972                }
973            });
974            mDataAdapter = new FixedLastDataAdapter(
975                    mWrappedDataAdapter,
976                    new SimpleViewData(
977                            v,
978                            v.getDrawable().getIntrinsicWidth(),
979                            v.getDrawable().getIntrinsicHeight(),
980                            0, 0));
981            // Flush out all the original data.
982            mDataAdapter.flush();
983            mFilmStripView.setDataAdapter(mDataAdapter);
984        }
985
986        setupNfcBeamPush();
987
988        mLocalImagesObserver = new LocalMediaObserver();
989        mLocalVideosObserver = new LocalMediaObserver();
990
991        getContentResolver().registerContentObserver(
992                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, true,
993                mLocalImagesObserver);
994        getContentResolver().registerContentObserver(
995                MediaStore.Video.Media.EXTERNAL_CONTENT_URI, true,
996                mLocalVideosObserver);
997    }
998
999    private void setRotationAnimation() {
1000        int rotationAnimation = WindowManager.LayoutParams.ROTATION_ANIMATION_ROTATE;
1001        rotationAnimation = WindowManager.LayoutParams.ROTATION_ANIMATION_CROSSFADE;
1002        Window win = getWindow();
1003        WindowManager.LayoutParams winParams = win.getAttributes();
1004        winParams.rotationAnimation = rotationAnimation;
1005        win.setAttributes(winParams);
1006    }
1007
1008    @Override
1009    public void onUserInteraction() {
1010        super.onUserInteraction();
1011        mCurrentModule.onUserInteraction();
1012    }
1013
1014    @Override
1015    public boolean dispatchTouchEvent(MotionEvent ev) {
1016        boolean result = super.dispatchTouchEvent(ev);
1017        if (ev.getActionMasked() == MotionEvent.ACTION_DOWN) {
1018            // Real deletion is postponed until the next user interaction after
1019            // the gesture that triggers deletion. Until real deletion is performed,
1020            // users can click the undo button to bring back the image that they
1021            // chose to delete.
1022            if (mPendingDeletion && !mIsUndoingDeletion) {
1023                 performDeletion();
1024            }
1025        }
1026        return result;
1027    }
1028
1029    @Override
1030    public void onPause() {
1031        // Delete photos that are pending deletion
1032        performDeletion();
1033        mOrientationListener.disable();
1034        mCurrentModule.onPauseBeforeSuper();
1035        super.onPause();
1036        mCurrentModule.onPauseAfterSuper();
1037
1038        mLocalImagesObserver.setActivityPaused(true);
1039        mLocalVideosObserver.setActivityPaused(true);
1040    }
1041
1042    @Override
1043    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
1044        if (requestCode == REQ_CODE_DONT_SWITCH_TO_PREVIEW) {
1045            mResetToPreviewOnResume = false;
1046        } else {
1047            super.onActivityResult(requestCode, resultCode, data);
1048        }
1049    }
1050
1051    @Override
1052    public void onResume() {
1053        // TODO: Handle this in OrientationManager.
1054        // Auto-rotate off
1055        if (Settings.System.getInt(getContentResolver(),
1056                Settings.System.ACCELEROMETER_ROTATION, 0) == 0) {
1057            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
1058            mAutoRotateScreen = false;
1059        } else {
1060            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
1061            mAutoRotateScreen = true;
1062        }
1063        mOrientationListener.enable();
1064        mCurrentModule.onResumeBeforeSuper();
1065        super.onResume();
1066        mCurrentModule.onResumeAfterSuper();
1067
1068        setSwipingEnabled(true);
1069
1070        if (mResetToPreviewOnResume) {
1071            // Go to the preview on resume.
1072            mFilmStripView.getController().goToFirstItem();
1073        }
1074        // Default is showing the preview, unless disabled by explicitly
1075        // starting an activity we want to return from to the filmstrip rather
1076        // than the preview.
1077        mResetToPreviewOnResume = true;
1078
1079        if (mLocalVideosObserver.isMediaDataChangedDuringPause()
1080                || mLocalImagesObserver.isMediaDataChangedDuringPause()) {
1081            mDataAdapter.requestLoad(getContentResolver());
1082        }
1083        mLocalImagesObserver.setActivityPaused(false);
1084        mLocalVideosObserver.setActivityPaused(false);
1085    }
1086
1087    @Override
1088    public void onStart() {
1089        super.onStart();
1090        bindMediaSaveService();
1091        mPanoramaViewHelper.onStart();
1092    }
1093
1094    @Override
1095    protected void onStop() {
1096        super.onStop();
1097        mPanoramaViewHelper.onStop();
1098        unbindMediaSaveService();
1099    }
1100
1101    @Override
1102    public void onDestroy() {
1103        if (mSecureCamera) {
1104            unregisterReceiver(mScreenOffReceiver);
1105        }
1106        getContentResolver().unregisterContentObserver(mLocalImagesObserver);
1107        getContentResolver().unregisterContentObserver(mLocalVideosObserver);
1108
1109        super.onDestroy();
1110    }
1111
1112    @Override
1113    public void onConfigurationChanged(Configuration config) {
1114        super.onConfigurationChanged(config);
1115        mCurrentModule.onConfigurationChanged(config);
1116    }
1117
1118    @Override
1119    public boolean onKeyDown(int keyCode, KeyEvent event) {
1120        if (mCurrentModule.onKeyDown(keyCode, event)) {
1121            return true;
1122        }
1123        // Prevent software keyboard or voice search from showing up.
1124        if (keyCode == KeyEvent.KEYCODE_SEARCH
1125                || keyCode == KeyEvent.KEYCODE_MENU) {
1126            if (event.isLongPress()) {
1127                return true;
1128            }
1129        }
1130
1131        return super.onKeyDown(keyCode, event);
1132    }
1133
1134    @Override
1135    public boolean onKeyUp(int keyCode, KeyEvent event) {
1136        if (mCurrentModule.onKeyUp(keyCode, event)) {
1137            return true;
1138        }
1139        return super.onKeyUp(keyCode, event);
1140    }
1141
1142    @Override
1143    public void onBackPressed() {
1144        if (!mFilmStripView.inCameraFullscreen()) {
1145            mFilmStripView.getController().goToFirstItem();
1146        } else if (!mCurrentModule.onBackPressed()) {
1147            super.onBackPressed();
1148        }
1149    }
1150
1151    public boolean isAutoRotateScreen() {
1152        return mAutoRotateScreen;
1153    }
1154
1155    protected void updateStorageSpace() {
1156        mStorageSpaceBytes = Storage.getAvailableSpace();
1157    }
1158
1159    protected long getStorageSpaceBytes() {
1160        return mStorageSpaceBytes;
1161    }
1162
1163    protected void updateStorageSpaceAndHint() {
1164        updateStorageSpace();
1165        updateStorageHint(mStorageSpaceBytes);
1166    }
1167
1168    protected void updateStorageHint(long storageSpace) {
1169        String message = null;
1170        if (storageSpace == Storage.UNAVAILABLE) {
1171            message = getString(R.string.no_storage);
1172        } else if (storageSpace == Storage.PREPARING) {
1173            message = getString(R.string.preparing_sd);
1174        } else if (storageSpace == Storage.UNKNOWN_SIZE) {
1175            message = getString(R.string.access_sd_fail);
1176        } else if (storageSpace <= Storage.LOW_STORAGE_THRESHOLD_BYTES) {
1177            message = getString(R.string.spaceIsLow_content);
1178        }
1179
1180        if (message != null) {
1181            if (mStorageHint == null) {
1182                mStorageHint = OnScreenHint.makeText(this, message);
1183            } else {
1184                mStorageHint.setText(message);
1185            }
1186            mStorageHint.show();
1187        } else if (mStorageHint != null) {
1188            mStorageHint.cancel();
1189            mStorageHint = null;
1190        }
1191    }
1192
1193    protected void setResultEx(int resultCode) {
1194        mResultCodeForTesting = resultCode;
1195        setResult(resultCode);
1196    }
1197
1198    protected void setResultEx(int resultCode, Intent data) {
1199        mResultCodeForTesting = resultCode;
1200        mResultDataForTesting = data;
1201        setResult(resultCode, data);
1202    }
1203
1204    public int getResultCode() {
1205        return mResultCodeForTesting;
1206    }
1207
1208    public Intent getResultData() {
1209        return mResultDataForTesting;
1210    }
1211
1212    public boolean isSecureCamera() {
1213        return mSecureCamera;
1214    }
1215
1216    @Override
1217    public void onModuleSelected(int moduleIndex) {
1218        if (mCurrentModuleIndex == moduleIndex) {
1219            return;
1220        }
1221
1222        CameraHolder.instance().keep();
1223        closeModule(mCurrentModule);
1224        setModuleFromIndex(moduleIndex);
1225
1226        openModule(mCurrentModule);
1227        mCurrentModule.onOrientationChanged(mLastRawOrientation);
1228        if (mMediaSaveService != null) {
1229            mCurrentModule.onMediaSaveServiceConnected(mMediaSaveService);
1230        }
1231
1232        // Store the module index so we can use it the next time the Camera
1233        // starts up.
1234        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
1235        prefs.edit().putInt(PREF_STARTUP_MODULE_INDEX, moduleIndex).apply();
1236    }
1237
1238    /**
1239     * Sets the mCurrentModuleIndex, creates a new module instance for the given
1240     * index an sets it as mCurrentModule.
1241     */
1242    private void setModuleFromIndex(int moduleIndex) {
1243        mCurrentModuleIndex = moduleIndex;
1244        switch (moduleIndex) {
1245            case ModuleSwitcher.VIDEO_MODULE_INDEX:
1246                mCurrentModule = new VideoModule();
1247                break;
1248
1249            case ModuleSwitcher.PHOTO_MODULE_INDEX:
1250                mCurrentModule = new PhotoModule();
1251                break;
1252
1253            case ModuleSwitcher.WIDE_ANGLE_PANO_MODULE_INDEX:
1254                mCurrentModule = new WideAnglePanoramaModule();
1255                break;
1256
1257            case ModuleSwitcher.LIGHTCYCLE_MODULE_INDEX:
1258                mCurrentModule = PhotoSphereHelper.createPanoramaModule();
1259                break;
1260            case ModuleSwitcher.GCAM_MODULE_INDEX:
1261                // Force immediate release of Camera instance
1262                CameraHolder.instance().strongRelease();
1263                mCurrentModule = GcamHelper.createGcamModule();
1264                break;
1265            default:
1266                // Fall back to photo mode.
1267                mCurrentModule = new PhotoModule();
1268                mCurrentModuleIndex = ModuleSwitcher.PHOTO_MODULE_INDEX;
1269                break;
1270        }
1271    }
1272
1273    /**
1274     * Launches an ACTION_EDIT intent for the given local data item.
1275     */
1276    public void launchEditor(LocalData data) {
1277        Intent intent = new Intent(Intent.ACTION_EDIT)
1278                .setDataAndType(data.getContentUri(), data.getMimeType())
1279                .setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
1280        startActivityForResult(Intent.createChooser(intent, null),
1281                REQ_CODE_DONT_SWITCH_TO_PREVIEW);
1282    }
1283
1284    /**
1285     * Launch the tiny planet editor.
1286     *
1287     * @param data the data must be a 360 degree stereographically mapped
1288     *            panoramic image. It will not be modified, instead a new item
1289     *            with the result will be added to the filmstrip.
1290     */
1291    public void launchTinyPlanetEditor(LocalData data) {
1292        TinyPlanetFragment fragment = new TinyPlanetFragment();
1293        Bundle bundle = new Bundle();
1294        bundle.putString(TinyPlanetFragment.ARGUMENT_URI, data.getContentUri().toString());
1295        bundle.putString(TinyPlanetFragment.ARGUMENT_TITLE, data.getTitle());
1296        fragment.setArguments(bundle);
1297        fragment.show(getFragmentManager(), "tiny_planet");
1298    }
1299
1300    private void openModule(CameraModule module) {
1301        module.init(this, mCameraModuleRootView);
1302        module.onResumeBeforeSuper();
1303        module.onResumeAfterSuper();
1304    }
1305
1306    private void closeModule(CameraModule module) {
1307        module.onPauseBeforeSuper();
1308        module.onPauseAfterSuper();
1309        ((ViewGroup) mCameraModuleRootView).removeAllViews();
1310    }
1311
1312    private void performDeletion() {
1313        if (!mPendingDeletion) {
1314            return;
1315        }
1316        hideUndoDeletionBar(false);
1317        mDataAdapter.executeDeletion(CameraActivity.this);
1318    }
1319
1320    public void showUndoDeletionBar() {
1321        if (mPendingDeletion) {
1322            performDeletion();
1323        }
1324        Log.v(TAG, "showing undo bar");
1325        mPendingDeletion = true;
1326        if (mUndoDeletionBar == null) {
1327            ViewGroup v = (ViewGroup) getLayoutInflater().inflate(
1328                    R.layout.undo_bar, mAboveFilmstripControlLayout, true);
1329            mUndoDeletionBar = (ViewGroup) v.findViewById(R.id.camera_undo_deletion_bar);
1330            View button = mUndoDeletionBar.findViewById(R.id.camera_undo_deletion_button);
1331            button.setOnClickListener(new View.OnClickListener() {
1332                @Override
1333                public void onClick(View view) {
1334                    mDataAdapter.undoDataRemoval();
1335                    hideUndoDeletionBar(true);
1336                }
1337            });
1338            // Setting undo bar clickable to avoid touch events going through
1339            // the bar to the buttons (eg. edit button, etc) underneath the bar.
1340            mUndoDeletionBar.setClickable(true);
1341            // When there is user interaction going on with the undo button, we
1342            // do not want to hide the undo bar.
1343            button.setOnTouchListener(new View.OnTouchListener() {
1344                @Override
1345                public boolean onTouch(View v, MotionEvent event) {
1346                    if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
1347                        mIsUndoingDeletion = true;
1348                    } else if (event.getActionMasked() == MotionEvent.ACTION_UP) {
1349                        mIsUndoingDeletion =false;
1350                    }
1351                    return false;
1352                }
1353            });
1354        }
1355        mUndoDeletionBar.setAlpha(0f);
1356        mUndoDeletionBar.setVisibility(View.VISIBLE);
1357        mUndoDeletionBar.animate().setDuration(200).alpha(1f).setListener(null).start();
1358    }
1359
1360    private void hideUndoDeletionBar(boolean withAnimation) {
1361        Log.v(TAG, "Hiding undo deletion bar");
1362        mPendingDeletion = false;
1363        if (mUndoDeletionBar != null) {
1364            if (withAnimation) {
1365                mUndoDeletionBar.animate()
1366                        .setDuration(200)
1367                        .alpha(0f)
1368                        .setListener(new Animator.AnimatorListener() {
1369                            @Override
1370                            public void onAnimationStart(Animator animation) {
1371                                // Do nothing.
1372                            }
1373
1374                            @Override
1375                            public void onAnimationEnd(Animator animation) {
1376                                mUndoDeletionBar.setVisibility(View.GONE);
1377                            }
1378
1379                            @Override
1380                            public void onAnimationCancel(Animator animation) {
1381                                // Do nothing.
1382                            }
1383
1384                            @Override
1385                            public void onAnimationRepeat(Animator animation) {
1386                                // Do nothing.
1387                            }
1388                        })
1389                        .start();
1390            } else {
1391                mUndoDeletionBar.setVisibility(View.GONE);
1392            }
1393        }
1394    }
1395
1396    @Override
1397    public void onShowSwitcherPopup() {
1398    }
1399
1400    /**
1401     * Enable/disable swipe-to-filmstrip. Will always disable swipe if in
1402     * capture intent.
1403     *
1404     * @param enable {@code true} to enable swipe.
1405     */
1406    public void setSwipingEnabled(boolean enable) {
1407        if (isCaptureIntent()) {
1408            mCameraPreviewData.lockPreview(true);
1409        } else {
1410            mCameraPreviewData.lockPreview(!enable);
1411        }
1412    }
1413
1414    // Accessor methods for getting latency times used in performance testing
1415    public long getAutoFocusTime() {
1416        return (mCurrentModule instanceof PhotoModule) ?
1417                ((PhotoModule) mCurrentModule).mAutoFocusTime : -1;
1418    }
1419
1420    public long getShutterLag() {
1421        return (mCurrentModule instanceof PhotoModule) ?
1422                ((PhotoModule) mCurrentModule).mShutterLag : -1;
1423    }
1424
1425    public long getShutterToPictureDisplayedTime() {
1426        return (mCurrentModule instanceof PhotoModule) ?
1427                ((PhotoModule) mCurrentModule).mShutterToPictureDisplayedTime : -1;
1428    }
1429
1430    public long getPictureDisplayedToJpegCallbackTime() {
1431        return (mCurrentModule instanceof PhotoModule) ?
1432                ((PhotoModule) mCurrentModule).mPictureDisplayedToJpegCallbackTime : -1;
1433    }
1434
1435    public long getJpegCallbackFinishTime() {
1436        return (mCurrentModule instanceof PhotoModule) ?
1437                ((PhotoModule) mCurrentModule).mJpegCallbackFinishTime : -1;
1438    }
1439
1440    public long getCaptureStartTime() {
1441        return (mCurrentModule instanceof PhotoModule) ?
1442                ((PhotoModule) mCurrentModule).mCaptureStartTime : -1;
1443    }
1444
1445    public boolean isRecording() {
1446        return (mCurrentModule instanceof VideoModule) ?
1447                ((VideoModule) mCurrentModule).isRecording() : false;
1448    }
1449
1450    public CameraOpenErrorCallback getCameraOpenErrorCallback() {
1451        return mCameraOpenErrorCallback;
1452    }
1453}
1454