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