CameraActivity.java revision 2b86d873ca4fb3a921139633ed7be9959ab452df
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);
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        if (mDataAdapter.getTotalNumber() > 1) {
720            showUndoDeletionBar();
721        } else {
722            // If camera preview is the only view left in filmstrip,
723            // no need to show undo bar.
724            mPendingDeletion = true;
725            performDeletion();
726        }
727    }
728
729    private void bindMediaSaveService() {
730        Intent intent = new Intent(this, MediaSaveService.class);
731        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
732    }
733
734    private void unbindMediaSaveService() {
735        if (mConnection != null) {
736            unbindService(mConnection);
737        }
738    }
739
740    @Override
741    public boolean onCreateOptionsMenu(Menu menu) {
742        // Inflate the menu items for use in the action bar
743        MenuInflater inflater = getMenuInflater();
744        inflater.inflate(R.menu.operations, menu);
745        mActionBarMenu = menu;
746
747        // Configure the standard share action provider
748        MenuItem item = menu.findItem(R.id.action_share);
749        mStandardShareActionProvider = (ShareActionProvider) item.getActionProvider();
750        mStandardShareActionProvider.setShareHistoryFileName("standard_share_history.xml");
751        if (mStandardShareIntent != null) {
752            mStandardShareActionProvider.setShareIntent(mStandardShareIntent);
753        }
754
755        // Configure the panorama share action provider
756        item = menu.findItem(R.id.action_share_panorama);
757        mPanoramaShareActionProvider = (ShareActionProvider) item.getActionProvider();
758        mPanoramaShareActionProvider.setShareHistoryFileName("panorama_share_history.xml");
759        if (mPanoramaShareIntent != null) {
760            mPanoramaShareActionProvider.setShareIntent(mPanoramaShareIntent);
761        }
762
763        return super.onCreateOptionsMenu(menu);
764    }
765
766    @Override
767    public boolean onOptionsItemSelected(MenuItem item) {
768        int currentDataId = mFilmStripView.getCurrentId();
769        if (currentDataId < 0) {
770            return false;
771        }
772        final LocalData localData = mDataAdapter.getLocalData(currentDataId);
773
774        // Handle presses on the action bar items
775        switch (item.getItemId()) {
776            case android.R.id.home:
777                // ActionBar's Up/Home button was clicked
778                if (!CameraUtil.launchGallery(CameraActivity.this)) {
779                    mFilmStripView.getController().goToFirstItem();
780                }
781                return true;
782            case R.id.action_delete:
783                removeData(currentDataId);
784                return true;
785            case R.id.action_edit:
786                launchEditor(localData);
787                return true;
788            case R.id.action_trim: {
789                // This is going to be handled by the Gallery app.
790                Intent intent = new Intent(ACTION_TRIM_VIDEO);
791                LocalData currentData = mDataAdapter.getLocalData(
792                        mFilmStripView.getCurrentId());
793                intent.setData(currentData.getContentUri());
794                // We need the file path to wrap this into a RandomAccessFile.
795                intent.putExtra(MEDIA_ITEM_PATH, currentData.getPath());
796                startActivityForResult(intent, REQ_CODE_DONT_SWITCH_TO_PREVIEW);
797                return true;
798            }
799            case R.id.action_rotate_ccw:
800                localData.rotate90Degrees(this, mDataAdapter, currentDataId, false);
801                return true;
802            case R.id.action_rotate_cw:
803                localData.rotate90Degrees(this, mDataAdapter, currentDataId, true);
804                return true;
805            case R.id.action_crop: {
806                Intent intent = new Intent(CropActivity.CROP_ACTION);
807                intent.setClass(this, CropActivity.class);
808                intent.setDataAndType(localData.getContentUri(), localData.getMimeType())
809                        .setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
810                startActivityForResult(intent, REQ_CODE_DONT_SWITCH_TO_PREVIEW);
811                return true;
812            }
813            case R.id.action_setas: {
814                Intent intent = new Intent(Intent.ACTION_ATTACH_DATA)
815                        .setDataAndType(localData.getContentUri(),
816                                localData.getMimeType())
817                        .setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
818                intent.putExtra("mimeType", intent.getType());
819                startActivityForResult(Intent.createChooser(
820                        intent, getString(R.string.set_as)), REQ_CODE_DONT_SWITCH_TO_PREVIEW);
821                return true;
822            }
823            case R.id.action_details:
824                (new AsyncTask<Void, Void, MediaDetails>() {
825                    @Override
826                    protected MediaDetails doInBackground(Void... params) {
827                        return localData.getMediaDetails(CameraActivity.this);
828                    }
829
830                    @Override
831                    protected void onPostExecute(MediaDetails mediaDetails) {
832                        DetailsDialog.create(CameraActivity.this, mediaDetails).show();
833                    }
834                }).execute();
835                return true;
836            case R.id.action_show_on_map:
837                double[] latLong = localData.getLatLong();
838                if (latLong != null) {
839                    CameraUtil.showOnMap(this, latLong);
840                }
841                return true;
842            default:
843                return super.onOptionsItemSelected(item);
844        }
845    }
846
847    private boolean isCaptureIntent() {
848        if (MediaStore.ACTION_VIDEO_CAPTURE.equals(getIntent().getAction())
849                || MediaStore.ACTION_IMAGE_CAPTURE.equals(getIntent().getAction())
850                || MediaStore.ACTION_IMAGE_CAPTURE_SECURE.equals(getIntent().getAction())) {
851            return true;
852        } else {
853            return false;
854        }
855    }
856
857    @Override
858    public void onCreate(Bundle state) {
859        super.onCreate(state);
860        getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
861        setContentView(R.layout.camera_filmstrip);
862        mActionBar = getActionBar();
863        mActionBar.addOnMenuVisibilityListener(this);
864
865        if (ApiHelper.HAS_ROTATION_ANIMATION) {
866            setRotationAnimation();
867        }
868
869        mMainHandler = new MainHandler(getMainLooper());
870        // Check if this is in the secure camera mode.
871        Intent intent = getIntent();
872        String action = intent.getAction();
873        if (INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE.equals(action)
874                || ACTION_IMAGE_CAPTURE_SECURE.equals(action)) {
875            mSecureCamera = true;
876        } else {
877            mSecureCamera = intent.getBooleanExtra(SECURE_CAMERA_EXTRA, false);
878        }
879
880        if (mSecureCamera) {
881            // Change the window flags so that secure camera can show when locked
882            Window win = getWindow();
883            WindowManager.LayoutParams params = win.getAttributes();
884            params.flags |= WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
885            win.setAttributes(params);
886
887            // Filter for screen off so that we can finish secure camera activity
888            // when screen is off.
889            IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
890            registerReceiver(mScreenOffReceiver, filter);
891            // TODO: This static screen off event receiver is a workaround to the
892            // double onResume() invocation (onResume->onPause->onResume). We should
893            // find a better solution to this.
894            if (sScreenOffReceiver == null) {
895                sScreenOffReceiver = new ScreenOffReceiver();
896                registerReceiver(sScreenOffReceiver, filter);
897            }
898        }
899        mAboveFilmstripControlLayout =
900                (FrameLayout) findViewById(R.id.camera_above_filmstrip_layout);
901        mAboveFilmstripControlLayout.setFitsSystemWindows(true);
902        // Hide action bar first since we are in full screen mode first, and
903        // switch the system UI to lights-out mode.
904        this.setSystemBarsVisibility(false);
905        mPanoramaManager = AppManagerFactory.getInstance(this)
906                .getPanoramaStitchingManager();
907        mPanoramaManager.addTaskListener(mStitchingListener);
908        LayoutInflater inflater = getLayoutInflater();
909        View rootLayout = inflater.inflate(R.layout.camera, null, false);
910        mCameraModuleRootView = rootLayout.findViewById(R.id.camera_app_root);
911        mPanoStitchingPanel = findViewById(R.id.pano_stitching_progress_panel);
912        mBottomProgress = (ProgressBar) findViewById(R.id.pano_stitching_progress_bar);
913        mCameraPreviewData = new CameraPreviewData(rootLayout,
914                FilmStripView.ImageData.SIZE_FULL,
915                FilmStripView.ImageData.SIZE_FULL);
916        // Put a CameraPreviewData at the first position.
917        mWrappedDataAdapter = new FixedFirstDataAdapter(
918                new CameraDataAdapter(new ColorDrawable(
919                        getResources().getColor(R.color.photo_placeholder))),
920                mCameraPreviewData);
921        mFilmStripView = (FilmStripView) findViewById(R.id.filmstrip_view);
922        mFilmStripView.setViewGap(
923                getResources().getDimensionPixelSize(R.dimen.camera_film_strip_gap));
924        mPanoramaViewHelper = new PanoramaViewHelper(this);
925        mPanoramaViewHelper.onCreate();
926        mFilmStripView.setPanoramaViewHelper(mPanoramaViewHelper);
927        // Set up the camera preview first so the preview shows up ASAP.
928        mFilmStripView.setListener(mFilmStripListener);
929
930        int moduleIndex = -1;
931        if (MediaStore.INTENT_ACTION_VIDEO_CAMERA.equals(getIntent().getAction())
932                || MediaStore.ACTION_VIDEO_CAPTURE.equals(getIntent().getAction())) {
933            moduleIndex = ModuleSwitcher.VIDEO_MODULE_INDEX;
934        } else if (MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA.equals(getIntent().getAction())
935                || MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE.equals(getIntent()
936                        .getAction())
937                || MediaStore.ACTION_IMAGE_CAPTURE.equals(getIntent().getAction())
938                || MediaStore.ACTION_IMAGE_CAPTURE_SECURE.equals(getIntent().getAction())) {
939            moduleIndex = ModuleSwitcher.PHOTO_MODULE_INDEX;
940        } else {
941            // If the activity has not been started using an explicit intent,
942            // read the module index from the last time the user changed modes
943            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
944            moduleIndex = prefs.getInt(PREF_STARTUP_MODULE_INDEX, -1);
945            if ((moduleIndex == ModuleSwitcher.GCAM_MODULE_INDEX &&
946                    !GcamHelper.hasGcamCapture()) || moduleIndex < 0) {
947                moduleIndex = ModuleSwitcher.PHOTO_MODULE_INDEX;
948            }
949        }
950
951        mOrientationListener = new MyOrientationEventListener(this);
952        setModuleFromIndex(moduleIndex);
953        mCurrentModule.init(this, mCameraModuleRootView);
954
955        if (!mSecureCamera) {
956            mDataAdapter = mWrappedDataAdapter;
957            mFilmStripView.setDataAdapter(mDataAdapter);
958            if (!isCaptureIntent()) {
959                mDataAdapter.requestLoad(getContentResolver());
960            }
961        } else {
962            // Put a lock placeholder as the last image by setting its date to
963            // 0.
964            ImageView v = (ImageView) getLayoutInflater().inflate(
965                    R.layout.secure_album_placeholder, null);
966            v.setOnClickListener(new View.OnClickListener() {
967                @Override
968                public void onClick(View view) {
969                    CameraUtil.launchGallery(CameraActivity.this);
970                    finish();
971                }
972            });
973            mDataAdapter = new FixedLastDataAdapter(
974                    mWrappedDataAdapter,
975                    new SimpleViewData(
976                            v,
977                            v.getDrawable().getIntrinsicWidth(),
978                            v.getDrawable().getIntrinsicHeight(),
979                            0, 0));
980            // Flush out all the original data.
981            mDataAdapter.flush();
982            mFilmStripView.setDataAdapter(mDataAdapter);
983        }
984
985        setupNfcBeamPush();
986
987        mLocalImagesObserver = new LocalMediaObserver();
988        mLocalVideosObserver = new LocalMediaObserver();
989
990        getContentResolver().registerContentObserver(
991                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, true,
992                mLocalImagesObserver);
993        getContentResolver().registerContentObserver(
994                MediaStore.Video.Media.EXTERNAL_CONTENT_URI, true,
995                mLocalVideosObserver);
996    }
997
998    private void setRotationAnimation() {
999        int rotationAnimation = WindowManager.LayoutParams.ROTATION_ANIMATION_ROTATE;
1000        rotationAnimation = WindowManager.LayoutParams.ROTATION_ANIMATION_CROSSFADE;
1001        Window win = getWindow();
1002        WindowManager.LayoutParams winParams = win.getAttributes();
1003        winParams.rotationAnimation = rotationAnimation;
1004        win.setAttributes(winParams);
1005    }
1006
1007    @Override
1008    public void onUserInteraction() {
1009        super.onUserInteraction();
1010        mCurrentModule.onUserInteraction();
1011    }
1012
1013    @Override
1014    public boolean dispatchTouchEvent(MotionEvent ev) {
1015        boolean result = super.dispatchTouchEvent(ev);
1016        if (ev.getActionMasked() == MotionEvent.ACTION_DOWN) {
1017            // Real deletion is postponed until the next user interaction after
1018            // the gesture that triggers deletion. Until real deletion is performed,
1019            // users can click the undo button to bring back the image that they
1020            // chose to delete.
1021            if (mPendingDeletion && !mIsUndoingDeletion) {
1022                 performDeletion();
1023            }
1024        }
1025        return result;
1026    }
1027
1028    @Override
1029    public void onPause() {
1030        // Delete photos that are pending deletion
1031        performDeletion();
1032        mOrientationListener.disable();
1033        mCurrentModule.onPauseBeforeSuper();
1034        super.onPause();
1035        mCurrentModule.onPauseAfterSuper();
1036
1037        mLocalImagesObserver.setActivityPaused(true);
1038        mLocalVideosObserver.setActivityPaused(true);
1039    }
1040
1041    @Override
1042    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
1043        if (requestCode == REQ_CODE_DONT_SWITCH_TO_PREVIEW) {
1044            mResetToPreviewOnResume = false;
1045        } else {
1046            super.onActivityResult(requestCode, resultCode, data);
1047        }
1048    }
1049
1050    @Override
1051    public void onResume() {
1052        // TODO: Handle this in OrientationManager.
1053        // Auto-rotate off
1054        if (Settings.System.getInt(getContentResolver(),
1055                Settings.System.ACCELEROMETER_ROTATION, 0) == 0) {
1056            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
1057            mAutoRotateScreen = false;
1058        } else {
1059            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
1060            mAutoRotateScreen = true;
1061        }
1062        mOrientationListener.enable();
1063        mCurrentModule.onResumeBeforeSuper();
1064        super.onResume();
1065        mCurrentModule.onResumeAfterSuper();
1066
1067        setSwipingEnabled(true);
1068
1069        if (mResetToPreviewOnResume) {
1070            // Go to the preview on resume.
1071            mFilmStripView.getController().goToFirstItem();
1072        }
1073        // Default is showing the preview, unless disabled by explicitly
1074        // starting an activity we want to return from to the filmstrip rather
1075        // than the preview.
1076        mResetToPreviewOnResume = true;
1077
1078        if (mLocalVideosObserver.isMediaDataChangedDuringPause()
1079                || mLocalImagesObserver.isMediaDataChangedDuringPause()) {
1080            mDataAdapter.requestLoad(getContentResolver());
1081        }
1082        mLocalImagesObserver.setActivityPaused(false);
1083        mLocalVideosObserver.setActivityPaused(false);
1084    }
1085
1086    @Override
1087    public void onStart() {
1088        super.onStart();
1089        bindMediaSaveService();
1090        mPanoramaViewHelper.onStart();
1091    }
1092
1093    @Override
1094    protected void onStop() {
1095        super.onStop();
1096        mPanoramaViewHelper.onStop();
1097        unbindMediaSaveService();
1098    }
1099
1100    @Override
1101    public void onDestroy() {
1102        if (mSecureCamera) {
1103            unregisterReceiver(mScreenOffReceiver);
1104        }
1105        getContentResolver().unregisterContentObserver(mLocalImagesObserver);
1106        getContentResolver().unregisterContentObserver(mLocalVideosObserver);
1107
1108        super.onDestroy();
1109    }
1110
1111    @Override
1112    public void onConfigurationChanged(Configuration config) {
1113        super.onConfigurationChanged(config);
1114        mCurrentModule.onConfigurationChanged(config);
1115    }
1116
1117    @Override
1118    public boolean onKeyDown(int keyCode, KeyEvent event) {
1119        if (mCurrentModule.onKeyDown(keyCode, event)) {
1120            return true;
1121        }
1122        // Prevent software keyboard or voice search from showing up.
1123        if (keyCode == KeyEvent.KEYCODE_SEARCH
1124                || keyCode == KeyEvent.KEYCODE_MENU) {
1125            if (event.isLongPress()) {
1126                return true;
1127            }
1128        }
1129
1130        return super.onKeyDown(keyCode, event);
1131    }
1132
1133    @Override
1134    public boolean onKeyUp(int keyCode, KeyEvent event) {
1135        if (mCurrentModule.onKeyUp(keyCode, event)) {
1136            return true;
1137        }
1138        return super.onKeyUp(keyCode, event);
1139    }
1140
1141    @Override
1142    public void onBackPressed() {
1143        if (!mFilmStripView.inCameraFullscreen()) {
1144            mFilmStripView.getController().goToFirstItem();
1145        } else if (!mCurrentModule.onBackPressed()) {
1146            super.onBackPressed();
1147        }
1148    }
1149
1150    public boolean isAutoRotateScreen() {
1151        return mAutoRotateScreen;
1152    }
1153
1154    protected void updateStorageSpace() {
1155        mStorageSpaceBytes = Storage.getAvailableSpace();
1156    }
1157
1158    protected long getStorageSpaceBytes() {
1159        return mStorageSpaceBytes;
1160    }
1161
1162    protected void updateStorageSpaceAndHint() {
1163        updateStorageSpace();
1164        updateStorageHint(mStorageSpaceBytes);
1165    }
1166
1167    protected void updateStorageHint(long storageSpace) {
1168        String message = null;
1169        if (storageSpace == Storage.UNAVAILABLE) {
1170            message = getString(R.string.no_storage);
1171        } else if (storageSpace == Storage.PREPARING) {
1172            message = getString(R.string.preparing_sd);
1173        } else if (storageSpace == Storage.UNKNOWN_SIZE) {
1174            message = getString(R.string.access_sd_fail);
1175        } else if (storageSpace <= Storage.LOW_STORAGE_THRESHOLD_BYTES) {
1176            message = getString(R.string.spaceIsLow_content);
1177        }
1178
1179        if (message != null) {
1180            if (mStorageHint == null) {
1181                mStorageHint = OnScreenHint.makeText(this, message);
1182            } else {
1183                mStorageHint.setText(message);
1184            }
1185            mStorageHint.show();
1186        } else if (mStorageHint != null) {
1187            mStorageHint.cancel();
1188            mStorageHint = null;
1189        }
1190    }
1191
1192    protected void setResultEx(int resultCode) {
1193        mResultCodeForTesting = resultCode;
1194        setResult(resultCode);
1195    }
1196
1197    protected void setResultEx(int resultCode, Intent data) {
1198        mResultCodeForTesting = resultCode;
1199        mResultDataForTesting = data;
1200        setResult(resultCode, data);
1201    }
1202
1203    public int getResultCode() {
1204        return mResultCodeForTesting;
1205    }
1206
1207    public Intent getResultData() {
1208        return mResultDataForTesting;
1209    }
1210
1211    public boolean isSecureCamera() {
1212        return mSecureCamera;
1213    }
1214
1215    @Override
1216    public void onModuleSelected(int moduleIndex) {
1217        if (mCurrentModuleIndex == moduleIndex) {
1218            return;
1219        }
1220
1221        CameraHolder.instance().keep();
1222        closeModule(mCurrentModule);
1223        setModuleFromIndex(moduleIndex);
1224
1225        openModule(mCurrentModule);
1226        mCurrentModule.onOrientationChanged(mLastRawOrientation);
1227        if (mMediaSaveService != null) {
1228            mCurrentModule.onMediaSaveServiceConnected(mMediaSaveService);
1229        }
1230
1231        // Store the module index so we can use it the next time the Camera
1232        // starts up.
1233        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
1234        prefs.edit().putInt(PREF_STARTUP_MODULE_INDEX, moduleIndex).apply();
1235    }
1236
1237    /**
1238     * Sets the mCurrentModuleIndex, creates a new module instance for the given
1239     * index an sets it as mCurrentModule.
1240     */
1241    private void setModuleFromIndex(int moduleIndex) {
1242        mCurrentModuleIndex = moduleIndex;
1243        switch (moduleIndex) {
1244            case ModuleSwitcher.VIDEO_MODULE_INDEX:
1245                mCurrentModule = new VideoModule();
1246                break;
1247
1248            case ModuleSwitcher.PHOTO_MODULE_INDEX:
1249                mCurrentModule = new PhotoModule();
1250                break;
1251
1252            case ModuleSwitcher.WIDE_ANGLE_PANO_MODULE_INDEX:
1253                mCurrentModule = new WideAnglePanoramaModule();
1254                break;
1255
1256            case ModuleSwitcher.LIGHTCYCLE_MODULE_INDEX:
1257                mCurrentModule = PhotoSphereHelper.createPanoramaModule();
1258                break;
1259            case ModuleSwitcher.GCAM_MODULE_INDEX:
1260                // Force immediate release of Camera instance
1261                CameraHolder.instance().strongRelease();
1262                mCurrentModule = GcamHelper.createGcamModule();
1263                break;
1264            default:
1265                // Fall back to photo mode.
1266                mCurrentModule = new PhotoModule();
1267                mCurrentModuleIndex = ModuleSwitcher.PHOTO_MODULE_INDEX;
1268                break;
1269        }
1270    }
1271
1272    /**
1273     * Launches an ACTION_EDIT intent for the given local data item.
1274     */
1275    public void launchEditor(LocalData data) {
1276        Intent intent = new Intent(Intent.ACTION_EDIT)
1277                .setDataAndType(data.getContentUri(), data.getMimeType())
1278                .setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
1279        startActivityForResult(Intent.createChooser(intent, null),
1280                REQ_CODE_DONT_SWITCH_TO_PREVIEW);
1281    }
1282
1283    /**
1284     * Launch the tiny planet editor.
1285     *
1286     * @param data the data must be a 360 degree stereographically mapped
1287     *            panoramic image. It will not be modified, instead a new item
1288     *            with the result will be added to the filmstrip.
1289     */
1290    public void launchTinyPlanetEditor(LocalData data) {
1291        TinyPlanetFragment fragment = new TinyPlanetFragment();
1292        Bundle bundle = new Bundle();
1293        bundle.putString(TinyPlanetFragment.ARGUMENT_URI, data.getContentUri().toString());
1294        bundle.putString(TinyPlanetFragment.ARGUMENT_TITLE, data.getTitle());
1295        fragment.setArguments(bundle);
1296        fragment.show(getFragmentManager(), "tiny_planet");
1297    }
1298
1299    private void openModule(CameraModule module) {
1300        module.init(this, mCameraModuleRootView);
1301        module.onResumeBeforeSuper();
1302        module.onResumeAfterSuper();
1303    }
1304
1305    private void closeModule(CameraModule module) {
1306        module.onPauseBeforeSuper();
1307        module.onPauseAfterSuper();
1308        ((ViewGroup) mCameraModuleRootView).removeAllViews();
1309    }
1310
1311    private void performDeletion() {
1312        if (!mPendingDeletion) {
1313            return;
1314        }
1315        hideUndoDeletionBar(false);
1316        mDataAdapter.executeDeletion(CameraActivity.this);
1317    }
1318
1319    public void showUndoDeletionBar() {
1320        if (mPendingDeletion) {
1321            performDeletion();
1322        }
1323        Log.v(TAG, "showing undo bar");
1324        mPendingDeletion = true;
1325        if (mUndoDeletionBar == null) {
1326            ViewGroup v = (ViewGroup) getLayoutInflater().inflate(
1327                    R.layout.undo_bar, mAboveFilmstripControlLayout, true);
1328            mUndoDeletionBar = (ViewGroup) v.findViewById(R.id.camera_undo_deletion_bar);
1329            View button = mUndoDeletionBar.findViewById(R.id.camera_undo_deletion_button);
1330            button.setOnClickListener(new View.OnClickListener() {
1331                @Override
1332                public void onClick(View view) {
1333                    mDataAdapter.undoDataRemoval();
1334                    hideUndoDeletionBar(true);
1335                }
1336            });
1337            // Setting undo bar clickable to avoid touch events going through
1338            // the bar to the buttons (eg. edit button, etc) underneath the bar.
1339            mUndoDeletionBar.setClickable(true);
1340            // When there is user interaction going on with the undo button, we
1341            // do not want to hide the undo bar.
1342            button.setOnTouchListener(new View.OnTouchListener() {
1343                @Override
1344                public boolean onTouch(View v, MotionEvent event) {
1345                    if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
1346                        mIsUndoingDeletion = true;
1347                    } else if (event.getActionMasked() == MotionEvent.ACTION_UP) {
1348                        mIsUndoingDeletion =false;
1349                    }
1350                    return false;
1351                }
1352            });
1353        }
1354        mUndoDeletionBar.setAlpha(0f);
1355        mUndoDeletionBar.setVisibility(View.VISIBLE);
1356        mUndoDeletionBar.animate().setDuration(200).alpha(1f).setListener(null).start();
1357    }
1358
1359    private void hideUndoDeletionBar(boolean withAnimation) {
1360        Log.v(TAG, "Hiding undo deletion bar");
1361        mPendingDeletion = false;
1362        if (mUndoDeletionBar != null) {
1363            if (withAnimation) {
1364                mUndoDeletionBar.animate()
1365                        .setDuration(200)
1366                        .alpha(0f)
1367                        .setListener(new Animator.AnimatorListener() {
1368                            @Override
1369                            public void onAnimationStart(Animator animation) {
1370                                // Do nothing.
1371                            }
1372
1373                            @Override
1374                            public void onAnimationEnd(Animator animation) {
1375                                mUndoDeletionBar.setVisibility(View.GONE);
1376                            }
1377
1378                            @Override
1379                            public void onAnimationCancel(Animator animation) {
1380                                // Do nothing.
1381                            }
1382
1383                            @Override
1384                            public void onAnimationRepeat(Animator animation) {
1385                                // Do nothing.
1386                            }
1387                        })
1388                        .start();
1389            } else {
1390                mUndoDeletionBar.setVisibility(View.GONE);
1391            }
1392        }
1393    }
1394
1395    @Override
1396    public void onShowSwitcherPopup() {
1397    }
1398
1399    /**
1400     * Enable/disable swipe-to-filmstrip. Will always disable swipe if in
1401     * capture intent.
1402     *
1403     * @param enable {@code true} to enable swipe.
1404     */
1405    public void setSwipingEnabled(boolean enable) {
1406        if (isCaptureIntent()) {
1407            mCameraPreviewData.lockPreview(true);
1408        } else {
1409            mCameraPreviewData.lockPreview(!enable);
1410        }
1411    }
1412
1413    // Accessor methods for getting latency times used in performance testing
1414    public long getAutoFocusTime() {
1415        return (mCurrentModule instanceof PhotoModule) ?
1416                ((PhotoModule) mCurrentModule).mAutoFocusTime : -1;
1417    }
1418
1419    public long getShutterLag() {
1420        return (mCurrentModule instanceof PhotoModule) ?
1421                ((PhotoModule) mCurrentModule).mShutterLag : -1;
1422    }
1423
1424    public long getShutterToPictureDisplayedTime() {
1425        return (mCurrentModule instanceof PhotoModule) ?
1426                ((PhotoModule) mCurrentModule).mShutterToPictureDisplayedTime : -1;
1427    }
1428
1429    public long getPictureDisplayedToJpegCallbackTime() {
1430        return (mCurrentModule instanceof PhotoModule) ?
1431                ((PhotoModule) mCurrentModule).mPictureDisplayedToJpegCallbackTime : -1;
1432    }
1433
1434    public long getJpegCallbackFinishTime() {
1435        return (mCurrentModule instanceof PhotoModule) ?
1436                ((PhotoModule) mCurrentModule).mJpegCallbackFinishTime : -1;
1437    }
1438
1439    public long getCaptureStartTime() {
1440        return (mCurrentModule instanceof PhotoModule) ?
1441                ((PhotoModule) mCurrentModule).mCaptureStartTime : -1;
1442    }
1443
1444    public boolean isRecording() {
1445        return (mCurrentModule instanceof VideoModule) ?
1446                ((VideoModule) mCurrentModule).isRecording() : false;
1447    }
1448
1449    public CameraOpenErrorCallback getCameraOpenErrorCallback() {
1450        return mCameraOpenErrorCallback;
1451    }
1452}
1453