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