CameraActivity.java revision e4002f3a703a1835dce30d74ccfc22e00956e13f
1/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.camera;
18
19import android.animation.Animator;
20import android.annotation.TargetApi;
21import android.app.ActionBar;
22import android.app.Activity;
23import android.app.AlertDialog;
24import android.content.ActivityNotFoundException;
25import android.content.BroadcastReceiver;
26import android.content.ContentResolver;
27import android.content.Context;
28import android.content.Intent;
29import android.content.IntentFilter;
30import android.content.SharedPreferences;
31import android.content.pm.ActivityInfo;
32import android.content.res.Configuration;
33import android.graphics.Bitmap;
34import android.graphics.Color;
35import android.graphics.SurfaceTexture;
36import android.graphics.drawable.ColorDrawable;
37import android.net.Uri;
38import android.nfc.NfcAdapter;
39import android.nfc.NfcAdapter.CreateBeamUrisCallback;
40import android.nfc.NfcEvent;
41import android.os.Build;
42import android.os.Bundle;
43import android.os.Handler;
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.Gravity;
51import android.view.KeyEvent;
52import android.view.LayoutInflater;
53import android.view.MenuItem;
54import android.view.MotionEvent;
55import android.view.View;
56import android.view.ViewGroup;
57import android.view.Window;
58import android.view.WindowManager;
59import android.widget.FrameLayout;
60import android.widget.FrameLayout.LayoutParams;
61import android.widget.ImageView;
62import android.widget.PopupWindow;
63import android.widget.ProgressBar;
64import android.widget.ShareActionProvider;
65import android.widget.TextView;
66
67import com.android.camera.app.AppController;
68import com.android.camera.app.CameraAppUI;
69import com.android.camera.app.CameraController;
70import com.android.camera.app.CameraManager;
71import com.android.camera.app.CameraManagerFactory;
72import com.android.camera.app.CameraProvider;
73import com.android.camera.app.CameraServices;
74import com.android.camera.app.ModuleManagerImpl;
75import com.android.camera.app.OrientationManager;
76import com.android.camera.app.OrientationManagerImpl;
77import com.android.camera.data.CameraDataAdapter;
78import com.android.camera.data.FixedLastDataAdapter;
79import com.android.camera.data.InProgressDataWrapper;
80import com.android.camera.data.LocalData;
81import com.android.camera.data.LocalDataAdapter;
82import com.android.camera.data.LocalMediaObserver;
83import com.android.camera.data.SimpleViewData;
84import com.android.camera.filmstrip.FilmstripContentPanel;
85import com.android.camera.filmstrip.FilmstripController;
86import com.android.camera.module.ModulesInfo;
87import com.android.camera.session.CaptureSessionManager;
88import com.android.camera.session.CaptureSessionManager.SessionListener;
89import com.android.camera.session.PlaceholderManager;
90import com.android.camera.settings.SettingsManager;
91import com.android.camera.settings.SettingsManager.SettingsCapabilities;
92import com.android.camera.tinyplanet.TinyPlanetFragment;
93import com.android.camera.ui.MainActivityLayout;
94import com.android.camera.ui.ModeListView;
95import com.android.camera.ui.PreviewStatusListener;
96import com.android.camera.ui.SettingsView;
97import com.android.camera.util.ApiHelper;
98import com.android.camera.util.CameraUtil;
99import com.android.camera.util.FeedbackHelper;
100import com.android.camera.util.GcamHelper;
101import com.android.camera.util.IntentHelper;
102import com.android.camera.util.PhotoSphereHelper.PanoramaViewHelper;
103import com.android.camera.util.UsageStatistics;
104import com.android.camera.widget.FilmstripView;
105import com.android.camera2.R;
106
107import java.io.File;
108
109public class CameraActivity extends Activity
110        implements AppController, CameraManager.CameraOpenCallback,
111        ActionBar.OnMenuVisibilityListener, ShareActionProvider.OnShareTargetSelectedListener,
112        OrientationManager.OnOrientationChangeListener {
113
114    private static final String TAG = "CAM_Activity";
115
116    private static final String INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE =
117            "android.media.action.STILL_IMAGE_CAMERA_SECURE";
118    public static final String ACTION_IMAGE_CAPTURE_SECURE =
119            "android.media.action.IMAGE_CAPTURE_SECURE";
120
121    // The intent extra for camera from secure lock screen. True if the gallery
122    // should only show newly captured pictures. sSecureAlbumId does not
123    // increment. This is used when switching between camera, camcorder, and
124    // panorama. If the extra is not set, it is in the normal camera mode.
125    public static final String SECURE_CAMERA_EXTRA = "secure_camera";
126
127    /**
128     * Request code from an activity we started that indicated that we do not want
129     * to reset the view to the preview in onResume.
130     */
131    public static final int REQ_CODE_DONT_SWITCH_TO_PREVIEW = 142;
132
133    public static final int REQ_CODE_GCAM_DEBUG_POSTCAPTURE = 999;
134
135    private static final int MSG_HIDE_ACTION_BAR = 1;
136    private static final int MSG_CLEAR_SCREEN_ON_FLAG = 2;
137    private static final long SCREEN_DELAY_MS = 2 * 60 * 1000;  // 2 mins.
138
139    /**
140     * Whether onResume should reset the view to the preview.
141     */
142    private boolean mResetToPreviewOnResume = true;
143
144    /**
145     * This data adapter is used by FilmStripView.
146     */
147    private LocalDataAdapter mDataAdapter;
148
149    /**
150     * TODO: This should be moved to the app level.
151     */
152    private SettingsManager mSettingsManager;
153
154    /**
155     * TODO: This should be moved to the app level.
156     */
157    private SettingsController mSettingsController;
158    private ModeListView mModeListView;
159    private int mCurrentModeIndex;
160    private CameraModule mCurrentModule;
161    private ModuleManagerImpl mModuleManager;
162    private FrameLayout mAboveFilmstripControlLayout;
163    private FilmstripController mFilmstripController;
164    private boolean mFilmstripVisible;
165    private TextView mBottomProgressText;
166    private ProgressBar mBottomProgressBar;
167    private View mSessionProgressPanel;
168    private int mResultCodeForTesting;
169    private Intent mResultDataForTesting;
170    private OnScreenHint mStorageHint;
171    private long mStorageSpaceBytes = Storage.LOW_STORAGE_THRESHOLD_BYTES;
172    private boolean mAutoRotateScreen;
173    private boolean mSecureCamera;
174    private int mLastRawOrientation;
175    private OrientationManagerImpl mOrientationManager;
176    private LocationManager mLocationManager;
177    private ButtonManager mButtonManager;
178    private Handler mMainHandler;
179    private PanoramaViewHelper mPanoramaViewHelper;
180    private ActionBar mActionBar;
181    private ViewGroup mUndoDeletionBar;
182    private boolean mIsUndoingDeletion = false;
183
184    private final Uri[] mNfcPushUris = new Uri[1];
185
186    private LocalMediaObserver mLocalImagesObserver;
187    private LocalMediaObserver mLocalVideosObserver;
188
189    private boolean mPendingDeletion = false;
190
191    private CameraController mCameraController;
192    private boolean mPaused;
193    private CameraAppUI mCameraAppUI;
194
195    private FeedbackHelper mFeedbackHelper;
196
197    @Override
198    public CameraAppUI getCameraAppUI() {
199        return mCameraAppUI;
200    }
201
202    // close activity when screen turns off
203    private final BroadcastReceiver mScreenOffReceiver = new BroadcastReceiver() {
204        @Override
205        public void onReceive(Context context, Intent intent) {
206            finish();
207        }
208    };
209
210    /**
211     * Whether the screen is kept turned on.
212     */
213    private boolean mKeepScreenOn;
214    private int mLastLayoutOrientation;
215    private final CameraAppUI.BottomControls.Listener mMyFilmstripBottomControlListener =
216            new CameraAppUI.BottomControls.Listener() {
217
218                /**
219                 * If the current photo is a photo sphere, this will launch the Photo Sphere
220                 * panorama viewer.
221                 */
222                @Override
223                public void onView() {
224                    LocalData data = getCurrentLocalData();
225                    if (data != null) {
226                        data.view(mPanoramaViewHelper);
227                    }
228                }
229
230                @Override
231                public void onEdit() {
232                    LocalData data = getCurrentLocalData();
233                    if (data == null) {
234                        return;
235                    }
236                    launchEditor(data);
237                }
238
239                @Override
240                public void onTinyPlanet() {
241                    LocalData data = getCurrentLocalData();
242                    if (data == null) {
243                        return;
244                    }
245                    final int currentDataId = getCurrentDataId();
246                    UsageStatistics.onEvent(UsageStatistics.COMPONENT_CAMERA,
247                            UsageStatistics.ACTION_EDIT, null, 0,
248                            UsageStatistics.hashFileName(fileNameFromDataID(currentDataId)));
249                    launchTinyPlanetEditor(data);
250                }
251
252                @Override
253                public void onDelete() {
254                    final int currentDataId = getCurrentDataId();
255                    UsageStatistics.onEvent(UsageStatistics.COMPONENT_CAMERA,
256                            UsageStatistics.ACTION_DELETE, null, 0,
257                            UsageStatistics.hashFileName(fileNameFromDataID(currentDataId)));
258                    removeData(currentDataId);
259                }
260
261                @Override
262                public void onShare() {
263                    final LocalData data = getCurrentLocalData();
264                    Intent shareIntent = getShareIntentByData(data);
265                    if (shareIntent != null) {
266                        try {
267                            startActivityForResult(shareIntent, REQ_CODE_DONT_SWITCH_TO_PREVIEW);
268                            mCameraAppUI.getFilmstripBottomControls().setShareEnabled(false);
269                        } catch (ActivityNotFoundException ex) {
270                            // Nothing.
271                        }
272                    }
273                }
274
275                @Override
276                public void onGallery() {
277                    startGallery();
278                }
279
280                private int getCurrentDataId() {
281                    return mFilmstripController.getCurrentId();
282                }
283
284                private LocalData getCurrentLocalData() {
285                    return mDataAdapter.getLocalData(getCurrentDataId());
286                }
287
288                /**
289                 * Sets up the share intent and NFC properly according to the data.
290                 *
291                 * @param data The data to be shared.
292                 */
293                private Intent getShareIntentByData(final LocalData data) {
294                    Intent intent = null;
295                    final Uri contentUri = data.getContentUri();
296                    if (data.getLocalDataType() == LocalData.LOCAL_360_PHOTO_SPHERE &&
297                            data.getContentUri() != Uri.EMPTY) {
298                        intent = new Intent(Intent.ACTION_SEND);
299                        intent.setType("application/vnd.google.panorama360+jpg");
300                        intent.putExtra(Intent.EXTRA_STREAM, contentUri);
301                    } else if (data.isDataActionSupported(LocalData.DATA_ACTION_SHARE)) {
302                        final String mimeType = data.getMimeType();
303                        intent = getShareIntentFromType(mimeType);
304                        if (intent != null) {
305                            intent.putExtra(Intent.EXTRA_STREAM, contentUri);
306                            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
307                        }
308                    }
309                    return intent;
310                }
311
312                /**
313                 * Get the share intent according to the mimeType
314                 *
315                 * @param mimeType The mimeType of current data.
316                 * @return the video/image's ShareIntent or null if mimeType is invalid.
317                 */
318                private Intent getShareIntentFromType(String mimeType) {
319                    // Lazily create the intent object.
320                    Intent intent = new Intent(Intent.ACTION_SEND);
321                    if (mimeType.startsWith("video/")) {
322                        intent.setType("video/*");
323                    } else {
324                        if (mimeType.startsWith("image/")) {
325                            intent.setType("image/*");
326                        } else {
327                            Log.w(TAG, "unsupported mimeType " + mimeType);
328                        }
329                    }
330                    return intent;
331                }
332            };
333
334    @Override
335    public void onCameraOpened(CameraManager.CameraProxy camera) {
336        if (!mModuleManager.getModuleAgent(mCurrentModeIndex).requestAppForCamera()) {
337            // We shouldn't be here. Just close the camera and leave.
338            camera.release(false);
339            throw new IllegalStateException("Camera opened but the module shouldn't be " +
340                    "requesting");
341        }
342        if (mCurrentModule != null) {
343            SettingsCapabilities capabilities =
344                SettingsController.getSettingsCapabilities(camera);
345            mSettingsManager.changeCamera(camera.getCameraId(), capabilities);
346            mCurrentModule.onCameraAvailable(camera);
347        }
348    }
349
350    @Override
351    public void onCameraDisabled(int cameraId) {
352        UsageStatistics.onEvent(UsageStatistics.COMPONENT_CAMERA, UsageStatistics.ACTION_OPEN_FAIL,
353                "security");
354
355        CameraUtil.showErrorAndFinish(this, R.string.camera_disabled);
356    }
357
358    @Override
359    public void onDeviceOpenFailure(int cameraId) {
360        UsageStatistics.onEvent(UsageStatistics.COMPONENT_CAMERA,
361                UsageStatistics.ACTION_OPEN_FAIL, "open");
362
363        CameraUtil.showErrorAndFinish(this, R.string.cannot_connect_camera);
364    }
365
366    @Override
367    public void onReconnectionFailure(CameraManager mgr) {
368        UsageStatistics.onEvent(UsageStatistics.COMPONENT_CAMERA,
369                UsageStatistics.ACTION_OPEN_FAIL, "reconnect");
370
371        CameraUtil.showErrorAndFinish(this, R.string.cannot_connect_camera);
372    }
373
374    private class MainHandler extends Handler {
375        public MainHandler(Looper looper) {
376            super(looper);
377        }
378
379        @Override
380        public void handleMessage(Message msg) {
381            switch (msg.what) {
382                case MSG_HIDE_ACTION_BAR: {
383                    removeMessages(MSG_HIDE_ACTION_BAR);
384                    CameraActivity.this.setFilmstripUiVisibility(false);
385                    break;
386                }
387
388                case MSG_CLEAR_SCREEN_ON_FLAG:  {
389                    if (!mPaused) {
390                        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
391                    }
392                    break;
393                }
394
395                default:
396            }
397        }
398    }
399
400    private String fileNameFromDataID(int dataID) {
401        final LocalData localData = mDataAdapter.getLocalData(dataID);
402
403        File localFile = new File(localData.getPath());
404        return localFile.getName();
405    }
406
407    private final FilmstripContentPanel.Listener mFilmstripListener =
408            new FilmstripContentPanel.Listener() {
409
410                @Override
411                public void onFilmstripHidden() {
412                    mFilmstripVisible = false;
413                    CameraActivity.this.setFilmstripUiVisibility(false);
414                    // When the user hide the filmstrip (either swipe out or
415                    // tap on back key) we move to the first item so next time
416                    // when the user swipe in the filmstrip, the most recent
417                    // one is shown.
418                    mFilmstripController.goToFirstItem();
419                    if (mCurrentModule != null) {
420                        mCurrentModule.onPreviewVisibilityChanged(true);
421                    }
422                }
423
424                @Override
425                public void onFilmstripShown() {
426                    mFilmstripVisible = true;
427                    updateUiByData(mFilmstripController.getCurrentId());
428                    if (mCurrentModule != null) {
429                        mCurrentModule.onPreviewVisibilityChanged(false);
430                    }
431                }
432
433                @Override
434                public void onDataPromoted(int dataID) {
435                    UsageStatistics.onEvent(UsageStatistics.COMPONENT_CAMERA,
436                            UsageStatistics.ACTION_DELETE, "promoted", 0,
437                            UsageStatistics.hashFileName(fileNameFromDataID(dataID)));
438
439                    removeData(dataID);
440                }
441
442                @Override
443                public void onDataDemoted(int dataID) {
444                    UsageStatistics.onEvent(UsageStatistics.COMPONENT_CAMERA,
445                            UsageStatistics.ACTION_DELETE, "demoted", 0,
446                            UsageStatistics.hashFileName(fileNameFromDataID(dataID)));
447
448                    removeData(dataID);
449                }
450
451                @Override
452                public void onEnterFullScreen(int dataId) {
453                    if (mFilmstripVisible) {
454                        CameraActivity.this.setFilmstripUiVisibility(false);
455                    }
456                }
457
458                @Override
459                public void onLeaveFullScreen(int dataId) {
460                    // Do nothing.
461                }
462
463                @Override
464                public void onEnterFilmstrip(int dataId) {
465                    if (mFilmstripVisible) {
466                        CameraActivity.this.setFilmstripUiVisibility(true);
467                    }
468                }
469
470                @Override
471                public void onLeaveFilmstrip(int dataId) {
472                    // Do nothing.
473                }
474
475                @Override
476                public void onDataReloaded() {
477                    if (!mFilmstripVisible) {
478                        return;
479                    }
480                    updateUiByData(mFilmstripController.getCurrentId());
481                }
482
483                @Override
484                public void onEnterZoomView(int dataID) {
485                    if (mFilmstripVisible) {
486                        CameraActivity.this.setFilmstripUiVisibility(false);
487                    }
488                }
489
490                @Override
491                public void onDataFocusChanged(final int prevDataId, final int newDataId) {
492                    if (!mFilmstripVisible) {
493                        return;
494                    }
495                    // TODO: This callback is UI event callback, should always
496                    // happen on UI thread. Find the reason for this
497                    // runOnUiThread() and fix it.
498                    runOnUiThread(new Runnable() {
499                        @Override
500                        public void run() {
501                            updateUiByData(newDataId);
502                        }
503                    });
504                }
505            };
506
507    public void gotoGallery() {
508        UsageStatistics.onEvent(UsageStatistics.COMPONENT_CAMERA, UsageStatistics.ACTION_FILMSTRIP,
509                "thumbnailTap");
510
511        mFilmstripController.goToNextItem();
512    }
513
514    /**
515     * If {@param visible} is false, this hides the action bar and switches the
516     * filmstrip UI to lights-out mode.
517     */
518    // TODO: This should not be called outside of the activity.
519    public void setFilmstripUiVisibility(boolean visible) {
520        mMainHandler.removeMessages(MSG_HIDE_ACTION_BAR);
521
522        int currentSystemUIVisibility = mAboveFilmstripControlLayout.getSystemUiVisibility();
523        int newSystemUIVisibility = (visible ? View.SYSTEM_UI_FLAG_VISIBLE :
524                        View.SYSTEM_UI_FLAG_LOW_PROFILE | View.SYSTEM_UI_FLAG_FULLSCREEN);
525        if (newSystemUIVisibility != currentSystemUIVisibility) {
526            mAboveFilmstripControlLayout.setSystemUiVisibility(newSystemUIVisibility);
527        }
528
529        boolean currentActionBarVisibility = mActionBar.isShowing();
530        mCameraAppUI.getFilmstripBottomControls().setVisible(visible);
531        if (visible != currentActionBarVisibility) {
532            if (visible) {
533                mActionBar.show();
534            } else {
535                mActionBar.hide();
536            }
537        }
538    }
539
540    private void hideSessionProgress() {
541        mSessionProgressPanel.setVisibility(View.GONE);
542    }
543
544    private void showSessionProgress(CharSequence message) {
545        mBottomProgressText.setText(message);
546        mSessionProgressPanel.setVisibility(View.VISIBLE);
547    }
548
549    private void updateSessionProgress(int progress) {
550        mBottomProgressBar.setProgress(progress);
551    }
552
553    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
554    private void setupNfcBeamPush() {
555        NfcAdapter adapter = NfcAdapter.getDefaultAdapter(CameraActivity.this);
556        if (adapter == null) {
557            return;
558        }
559
560        if (!ApiHelper.HAS_SET_BEAM_PUSH_URIS) {
561            // Disable beaming
562            adapter.setNdefPushMessage(null, CameraActivity.this);
563            return;
564        }
565
566        adapter.setBeamPushUris(null, CameraActivity.this);
567        adapter.setBeamPushUrisCallback(new CreateBeamUrisCallback() {
568            @Override
569            public Uri[] createBeamUris(NfcEvent event) {
570                return mNfcPushUris;
571            }
572        }, CameraActivity.this);
573    }
574
575    @Override
576    public void onMenuVisibilityChanged(boolean isVisible) {
577        // TODO: Remove this or bring back the original implementation: cancel
578        // auto-hide actionbar.
579    }
580
581    @Override
582    public boolean onShareTargetSelected(ShareActionProvider shareActionProvider, Intent intent) {
583        int currentDataId = mFilmstripController.getCurrentId();
584        if (currentDataId < 0) {
585            return false;
586        }
587        UsageStatistics.onEvent(UsageStatistics.COMPONENT_CAMERA, UsageStatistics.ACTION_SHARE,
588                intent.getComponent().getPackageName(), 0,
589                UsageStatistics.hashFileName(fileNameFromDataID(currentDataId)));
590        return true;
591    }
592
593    // Note: All callbacks come back on the main thread.
594    private final SessionListener mSessionListener =
595            new SessionListener() {
596                @Override
597                public void onSessionQueued(final Uri uri) {
598                    notifyNewMedia(uri);
599                    int dataID = mDataAdapter.findDataByContentUri(uri);
600                    if (dataID != -1) {
601                        // Don't allow special UI actions (swipe to
602                        // delete, for example) on in-progress data.
603                        LocalData d = mDataAdapter.getLocalData(dataID);
604                        InProgressDataWrapper newData = new InProgressDataWrapper(d);
605                        mDataAdapter.updateData(dataID, newData);
606                    }
607                }
608
609                @Override
610                public void onSessionDone(final Uri uri) {
611                    Log.v(TAG, "onSessionDone:" + uri);
612                    int doneID = mDataAdapter.findDataByContentUri(uri);
613                    int currentDataId = mFilmstripController.getCurrentId();
614
615                    if (currentDataId == doneID) {
616                        hideSessionProgress();
617                        updateSessionProgress(0);
618                    }
619                    mDataAdapter.refresh(getContentResolver(), uri, /* isInProgress */ false);
620                }
621
622                @Override
623                public void onSessionProgress(final Uri uri, final int progress) {
624                    if (progress < 0) {
625                        // Do nothing, there is no task for this URI.
626                        return;
627                    }
628                    int currentDataId = mFilmstripController.getCurrentId();
629                    if (currentDataId == -1) {
630                        return;
631                    }
632                    if (uri.equals(
633                            mDataAdapter.getLocalData(currentDataId).getContentUri())) {
634                        updateSessionProgress(progress);
635                    }
636                }
637
638                @Override
639                public void onSessionUpdated(Uri uri) {
640                    mDataAdapter.refresh(getContentResolver(), uri, /* isInProgress */ true);
641                }
642            };
643
644    @Override
645    public Context getAndroidContext() {
646        return this;
647    }
648
649    @Override
650    public int getCurrentModuleIndex() {
651        return mCurrentModeIndex;
652    }
653
654    @Override
655    public SurfaceTexture getPreviewBuffer() {
656        // TODO: implement this
657        return null;
658    }
659
660    @Override
661    public void onPreviewStarted() {
662        mCameraAppUI.onPreviewStarted();
663    }
664
665    @Override
666    public void setPreviewStatusListener(PreviewStatusListener previewStatusListener) {
667        mCameraAppUI.setPreviewStatusListener(previewStatusListener);
668    }
669
670    @Override
671    public FrameLayout getModuleLayoutRoot() {
672        return mCameraAppUI.getModuleRootView();
673    }
674
675    @Override
676    public void setShutterEventsListener(ShutterEventsListener listener) {
677        // TODO: implement this
678    }
679
680    @Override
681    public void setShutterEnabled(boolean enabled) {
682        // TODO: implement this
683    }
684
685    @Override
686    public boolean isShutterEnabled() {
687        // TODO: implement this
688        return false;
689    }
690
691    @Override
692    public void startPreCaptureAnimation() {
693        mCameraAppUI.startPreCaptureAnimation();
694    }
695
696    @Override
697    public void cancelPreCaptureAnimation() {
698        // TODO: implement this
699    }
700
701    @Override
702    public void startPostCaptureAnimation() {
703        // TODO: implement this
704    }
705
706    @Override
707    public void startPostCaptureAnimation(Bitmap thumbnail) {
708        // TODO: implement this
709    }
710
711    @Override
712    public void cancelPostCaptureAnimation() {
713        // TODO: implement this
714    }
715
716    @Override
717    public OrientationManager getOrientationManager() {
718        return mOrientationManager;
719    }
720
721    @Override
722    public LocationManager getLocationManager() {
723        return mLocationManager;
724    }
725
726    @Override
727    public void lockOrientation() {
728        mOrientationManager.lockOrientation();
729    }
730
731    @Override
732    public void unlockOrientation() {
733        mOrientationManager.unlockOrientation();
734    }
735
736    @Override
737    public void notifyNewMedia(Uri uri) {
738        ContentResolver cr = getContentResolver();
739        String mimeType = cr.getType(uri);
740        if (mimeType.startsWith("video/")) {
741            sendBroadcast(new Intent(CameraUtil.ACTION_NEW_VIDEO, uri));
742            mDataAdapter.addNewVideo(cr, uri);
743        } else if (mimeType.startsWith("image/")) {
744            CameraUtil.broadcastNewPicture(this, uri);
745            mDataAdapter.addNewPhoto(cr, uri);
746        } else if (mimeType.startsWith(PlaceholderManager.PLACEHOLDER_MIME_TYPE)) {
747            mDataAdapter.addNewPhoto(cr, uri);
748        } else {
749            android.util.Log.w(TAG, "Unknown new media with MIME type:"
750                    + mimeType + ", uri:" + uri);
751        }
752    }
753
754    @Override
755    public void enableKeepScreenOn(boolean enabled) {
756        if (mPaused) {
757            return;
758        }
759
760        mKeepScreenOn = enabled;
761        if (mKeepScreenOn) {
762            mMainHandler.removeMessages(MSG_CLEAR_SCREEN_ON_FLAG);
763            getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
764        } else {
765            keepScreenOnForAWhile();
766        }
767    }
768
769    @Override
770    public CameraProvider getCameraProvider() {
771        return mCameraController;
772    }
773
774    private void removeData(int dataID) {
775        mDataAdapter.removeData(CameraActivity.this, dataID);
776        if (mDataAdapter.getTotalNumber() > 1) {
777            showUndoDeletionBar();
778        } else {
779            // If camera preview is the only view left in filmstrip,
780            // no need to show undo bar.
781            mPendingDeletion = true;
782            performDeletion();
783        }
784    }
785
786    @Override
787    public boolean onOptionsItemSelected(MenuItem item) {
788        // Handle presses on the action bar items
789        switch (item.getItemId()) {
790            case android.R.id.home:
791                onBackPressed();
792                return true;
793            default:
794                return super.onOptionsItemSelected(item);
795        }
796    }
797
798    private boolean isCaptureIntent() {
799        if (MediaStore.ACTION_VIDEO_CAPTURE.equals(getIntent().getAction())
800                || MediaStore.ACTION_IMAGE_CAPTURE.equals(getIntent().getAction())
801                || MediaStore.ACTION_IMAGE_CAPTURE_SECURE.equals(getIntent().getAction())) {
802            return true;
803        } else {
804            return false;
805        }
806    }
807
808    @Override
809    public void onCreate(Bundle state) {
810        super.onCreate(state);
811        GcamHelper.init(getContentResolver());
812
813        getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
814        setContentView(R.layout.activity_main);
815        mActionBar = getActionBar();
816        mActionBar.addOnMenuVisibilityListener(this);
817        mMainHandler = new MainHandler(getMainLooper());
818        mCameraController =
819                new CameraController(this, this, mMainHandler,
820                        CameraManagerFactory.getAndroidCameraManager());
821        ComboPreferences prefs = new ComboPreferences(getAndroidContext());
822
823        mSettingsManager = new SettingsManager(this, null, mCameraController.getNumberOfCameras());
824        // Remove this after we get rid of ComboPreferences.
825        int cameraId = Integer.parseInt(mSettingsManager.get(SettingsManager.SETTING_CAMERA_ID));
826        prefs.setLocalId(this, cameraId);
827        CameraSettings.upgradeGlobalPreferences(prefs, mCameraController.getNumberOfCameras());
828        // TODO: Try to move all the resources allocation to happen as soon as
829        // possible so we can call module.init() at the earliest time.
830        mModuleManager = new ModuleManagerImpl();
831        ModulesInfo.setupModules(this, mModuleManager);
832
833        mModeListView = (ModeListView) findViewById(R.id.mode_list_layout);
834        mModeListView.init(mModuleManager.getSupportedModeIndexList());
835        if (ApiHelper.HAS_ROTATION_ANIMATION) {
836            setRotationAnimation();
837        }
838
839        // Check if this is in the secure camera mode.
840        Intent intent = getIntent();
841        String action = intent.getAction();
842        if (INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE.equals(action)
843                || ACTION_IMAGE_CAPTURE_SECURE.equals(action)) {
844            mSecureCamera = true;
845        } else {
846            mSecureCamera = intent.getBooleanExtra(SECURE_CAMERA_EXTRA, false);
847        }
848
849        if (mSecureCamera) {
850            // Change the window flags so that secure camera can show when locked
851            Window win = getWindow();
852            WindowManager.LayoutParams params = win.getAttributes();
853            params.flags |= WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
854            win.setAttributes(params);
855
856            // Filter for screen off so that we can finish secure camera activity
857            // when screen is off.
858            IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
859            registerReceiver(mScreenOffReceiver, filter);
860        }
861        mCameraAppUI = new CameraAppUI(this,
862                (MainActivityLayout) findViewById(R.id.activity_root_view),
863                isSecureCamera(), isCaptureIntent());
864
865        mCameraAppUI.setFilmstripBottomControlsListener(mMyFilmstripBottomControlListener);
866
867        mAboveFilmstripControlLayout =
868                (FrameLayout) findViewById(R.id.camera_filmstrip_content_layout);
869
870        // Add the session listener so we can track the session progress updates.
871        getServices().getCaptureSessionManager().addSessionListener(mSessionListener);
872        mSessionProgressPanel = findViewById(R.id.pano_session_progress_panel);
873        mBottomProgressBar = (ProgressBar) findViewById(R.id.pano_session_progress_bar);
874        mBottomProgressText = (TextView) findViewById(R.id.pano_session_progress_text);
875        mFilmstripController = ((FilmstripView) findViewById(R.id.filmstrip_view)).getController();
876        mFilmstripController.setImageGap(
877                getResources().getDimensionPixelSize(R.dimen.camera_film_strip_gap));
878        mPanoramaViewHelper = new PanoramaViewHelper(this);
879        mPanoramaViewHelper.onCreate();
880        // Set up the camera preview first so the preview shows up ASAP.
881        mDataAdapter = new CameraDataAdapter(
882                new ColorDrawable(getResources().getColor(R.color.photo_placeholder)));
883
884        mCameraAppUI.getFilmstripContentPanel().setFilmstripListener(mFilmstripListener);
885
886        mLocationManager = new LocationManager(this,
887            new LocationManager.Listener() {
888                @Override
889                public void showGpsOnScreenIndicator(boolean hasSignal) {
890                }
891
892                @Override
893                public void hideGpsOnScreenIndicator() {
894                }
895            });
896
897        mSettingsController = new SettingsController(this, mSettingsManager, mLocationManager);
898
899        int modeIndex = -1;
900        if (MediaStore.INTENT_ACTION_VIDEO_CAMERA.equals(getIntent().getAction())
901                || MediaStore.ACTION_VIDEO_CAPTURE.equals(getIntent().getAction())) {
902            modeIndex = ModeListView.MODE_VIDEO;
903        } else if (MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA.equals(getIntent().getAction())
904                || MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE.equals(getIntent()
905                        .getAction())) {
906            modeIndex = ModeListView.MODE_PHOTO;
907            if (mSettingsManager.getInt(SettingsManager.SETTING_STARTUP_MODULE_INDEX)
908                        == ModeListView.MODE_GCAM && GcamHelper.hasGcamCapture()) {
909                modeIndex = ModeListView.MODE_GCAM;
910            }
911        } else if (MediaStore.ACTION_IMAGE_CAPTURE.equals(getIntent().getAction())
912                || MediaStore.ACTION_IMAGE_CAPTURE_SECURE.equals(getIntent().getAction())) {
913            modeIndex = ModeListView.MODE_PHOTO;
914        } else {
915            // If the activity has not been started using an explicit intent,
916            // read the module index from the last time the user changed modes
917            modeIndex = mSettingsManager.getInt(SettingsManager.SETTING_STARTUP_MODULE_INDEX);
918            if ((modeIndex == ModeListView.MODE_GCAM &&
919                    !GcamHelper.hasGcamCapture()) || modeIndex < 0) {
920                modeIndex = ModeListView.MODE_PHOTO;
921            }
922        }
923
924        mOrientationManager = new OrientationManagerImpl(this);
925        mOrientationManager.addOnOrientationChangeListener(mMainHandler, this);
926
927        setModuleFromModeIndex(modeIndex);
928
929        // TODO: Remove this when refactor is done.
930        if (modeIndex == ModulesInfo.MODULE_PHOTO
931                || modeIndex == ModulesInfo.MODULE_VIDEO
932                || modeIndex == ModulesInfo.MODULE_GCAM) {
933            mCameraAppUI.prepareModuleUI();
934        }
935        mCurrentModule.init(this, isSecureCamera(), isCaptureIntent());
936
937        if (!mSecureCamera) {
938            mFilmstripController.setDataAdapter(mDataAdapter);
939            if (!isCaptureIntent()) {
940                mDataAdapter.requestLoad(getContentResolver());
941            }
942        } else {
943            // Put a lock placeholder as the last image by setting its date to
944            // 0.
945            ImageView v = (ImageView) getLayoutInflater().inflate(
946                    R.layout.secure_album_placeholder, null);
947            v.setOnClickListener(new View.OnClickListener() {
948                @Override
949                public void onClick(View view) {
950                    startGallery();
951                    finish();
952                }
953            });
954            mDataAdapter = new FixedLastDataAdapter(
955                    mDataAdapter,
956                    new SimpleViewData(
957                            v,
958                            v.getDrawable().getIntrinsicWidth(),
959                            v.getDrawable().getIntrinsicHeight(),
960                            0, 0));
961            // Flush out all the original data.
962            mDataAdapter.flush();
963            mFilmstripController.setDataAdapter(mDataAdapter);
964        }
965
966        setupNfcBeamPush();
967
968        mLocalImagesObserver = new LocalMediaObserver();
969        mLocalVideosObserver = new LocalMediaObserver();
970
971        getContentResolver().registerContentObserver(
972                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, true,
973                mLocalImagesObserver);
974        getContentResolver().registerContentObserver(
975                MediaStore.Video.Media.EXTERNAL_CONTENT_URI, true,
976                mLocalVideosObserver);
977        if (FeedbackHelper.feedbackAvailable()) {
978            mFeedbackHelper = new FeedbackHelper(this);
979        }
980    }
981
982    private void setRotationAnimation() {
983        int rotationAnimation = WindowManager.LayoutParams.ROTATION_ANIMATION_ROTATE;
984        rotationAnimation = WindowManager.LayoutParams.ROTATION_ANIMATION_CROSSFADE;
985        Window win = getWindow();
986        WindowManager.LayoutParams winParams = win.getAttributes();
987        winParams.rotationAnimation = rotationAnimation;
988        win.setAttributes(winParams);
989    }
990
991    @Override
992    public void onUserInteraction() {
993        super.onUserInteraction();
994        if (!isFinishing()) {
995            keepScreenOnForAWhile();
996        }
997    }
998
999    @Override
1000    public boolean dispatchTouchEvent(MotionEvent ev) {
1001        boolean result = super.dispatchTouchEvent(ev);
1002        if (ev.getActionMasked() == MotionEvent.ACTION_DOWN) {
1003            // Real deletion is postponed until the next user interaction after
1004            // the gesture that triggers deletion. Until real deletion is performed,
1005            // users can click the undo button to bring back the image that they
1006            // chose to delete.
1007            if (mPendingDeletion && !mIsUndoingDeletion) {
1008                performDeletion();
1009            }
1010        }
1011        return result;
1012    }
1013
1014    @Override
1015    public void onPause() {
1016        mPaused = true;
1017
1018        // Delete photos that are pending deletion
1019        performDeletion();
1020        mCurrentModule.pause();
1021        mOrientationManager.pause();
1022        // Close the camera and wait for the operation done.
1023        mCameraController.closeCamera();
1024
1025        mLocalImagesObserver.setActivityPaused(true);
1026        mLocalVideosObserver.setActivityPaused(true);
1027        resetScreenOn();
1028        super.onPause();
1029    }
1030
1031    @Override
1032    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
1033        if (requestCode == REQ_CODE_DONT_SWITCH_TO_PREVIEW) {
1034            mResetToPreviewOnResume = false;
1035        } else {
1036            super.onActivityResult(requestCode, resultCode, data);
1037        }
1038    }
1039
1040    @Override
1041    public void onResume() {
1042        mPaused = false;
1043
1044        mLastLayoutOrientation = getResources().getConfiguration().orientation;
1045
1046        // TODO: Handle this in OrientationManager.
1047        // Auto-rotate off
1048        if (Settings.System.getInt(getContentResolver(),
1049                Settings.System.ACCELEROMETER_ROTATION, 0) == 0) {
1050            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
1051            mAutoRotateScreen = false;
1052        } else {
1053            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
1054            mAutoRotateScreen = true;
1055        }
1056
1057        UsageStatistics.onEvent(UsageStatistics.COMPONENT_CAMERA,
1058                UsageStatistics.ACTION_FOREGROUNDED, this.getClass().getSimpleName());
1059
1060        mOrientationManager.resume();
1061        super.onResume();
1062        mCurrentModule.resume();
1063        setSwipingEnabled(true);
1064
1065        if (mResetToPreviewOnResume) {
1066            mCameraAppUI.resume();
1067        }
1068        // The share button might be disabled to avoid double tapping.
1069        mCameraAppUI.getFilmstripBottomControls().setShareEnabled(true);
1070        // Default is showing the preview, unless disabled by explicitly
1071        // starting an activity we want to return from to the filmstrip rather
1072        // than the preview.
1073        mResetToPreviewOnResume = true;
1074
1075        if (mLocalVideosObserver.isMediaDataChangedDuringPause()
1076                || mLocalImagesObserver.isMediaDataChangedDuringPause()) {
1077            if (!mSecureCamera) {
1078                // If it's secure camera, requestLoad() should not be called
1079                // as it will load all the data.
1080                if (!mFilmstripVisible) {
1081                    mDataAdapter.requestLoad(getContentResolver());
1082                }
1083            }
1084        }
1085        mLocalImagesObserver.setActivityPaused(false);
1086        mLocalVideosObserver.setActivityPaused(false);
1087
1088        keepScreenOnForAWhile();
1089    }
1090
1091    @Override
1092    public void onStart() {
1093        super.onStart();
1094        mPanoramaViewHelper.onStart();
1095    }
1096
1097    @Override
1098    protected void onStop() {
1099        mPanoramaViewHelper.onStop();
1100        if (mFeedbackHelper != null) {
1101            mFeedbackHelper.stopFeedback();
1102        }
1103
1104        CameraManagerFactory.recycle();
1105        super.onStop();
1106    }
1107
1108    @Override
1109    public void onDestroy() {
1110        if (mSecureCamera) {
1111            unregisterReceiver(mScreenOffReceiver);
1112        }
1113        getContentResolver().unregisterContentObserver(mLocalImagesObserver);
1114        getContentResolver().unregisterContentObserver(mLocalVideosObserver);
1115        super.onDestroy();
1116    }
1117
1118    @Override
1119    public void onConfigurationChanged(Configuration config) {
1120        super.onConfigurationChanged(config);
1121        Log.v(TAG, "onConfigurationChanged");
1122        if (config.orientation == Configuration.ORIENTATION_UNDEFINED) {
1123            return;
1124        }
1125
1126        if (mLastLayoutOrientation != config.orientation) {
1127            mLastLayoutOrientation = config.orientation;
1128            mCurrentModule.onLayoutOrientationChanged(
1129                    mLastLayoutOrientation == Configuration.ORIENTATION_LANDSCAPE);
1130        }
1131    }
1132
1133    @Override
1134    public boolean onKeyDown(int keyCode, KeyEvent event) {
1135        if (mFilmstripController.inCameraFullscreen()) {
1136            if (mCurrentModule.onKeyDown(keyCode, event)) {
1137                return true;
1138            }
1139            // Prevent software keyboard or voice search from showing up.
1140            if (keyCode == KeyEvent.KEYCODE_SEARCH
1141                    || keyCode == KeyEvent.KEYCODE_MENU) {
1142                if (event.isLongPress()) {
1143                    return true;
1144                }
1145            }
1146        }
1147
1148        return super.onKeyDown(keyCode, event);
1149    }
1150
1151    @Override
1152    public boolean onKeyUp(int keyCode, KeyEvent event) {
1153        if (mFilmstripController.inCameraFullscreen() && mCurrentModule.onKeyUp(keyCode, event)) {
1154            return true;
1155        }
1156        return super.onKeyUp(keyCode, event);
1157    }
1158
1159    @Override
1160    public void onBackPressed() {
1161        if (!mCameraAppUI.onBackPressed()) {
1162            if (!mCurrentModule.onBackPressed()) {
1163                super.onBackPressed();
1164            }
1165        }
1166    }
1167
1168    public boolean isAutoRotateScreen() {
1169        return mAutoRotateScreen;
1170    }
1171
1172    protected void updateStorageSpace() {
1173        mStorageSpaceBytes = Storage.getAvailableSpace();
1174    }
1175
1176    protected long getStorageSpaceBytes() {
1177        return mStorageSpaceBytes;
1178    }
1179
1180    protected void updateStorageSpaceAndHint() {
1181        updateStorageSpace();
1182        updateStorageHint(mStorageSpaceBytes);
1183    }
1184
1185    protected void updateStorageHint(long storageSpace) {
1186        String message = null;
1187        if (storageSpace == Storage.UNAVAILABLE) {
1188            message = getString(R.string.no_storage);
1189        } else if (storageSpace == Storage.PREPARING) {
1190            message = getString(R.string.preparing_sd);
1191        } else if (storageSpace == Storage.UNKNOWN_SIZE) {
1192            message = getString(R.string.access_sd_fail);
1193        } else if (storageSpace <= Storage.LOW_STORAGE_THRESHOLD_BYTES) {
1194            message = getString(R.string.spaceIsLow_content);
1195        }
1196
1197        if (message != null) {
1198            if (mStorageHint == null) {
1199                mStorageHint = OnScreenHint.makeText(this, message);
1200            } else {
1201                mStorageHint.setText(message);
1202            }
1203            mStorageHint.show();
1204        } else if (mStorageHint != null) {
1205            mStorageHint.cancel();
1206            mStorageHint = null;
1207        }
1208    }
1209
1210    protected void setResultEx(int resultCode) {
1211        mResultCodeForTesting = resultCode;
1212        setResult(resultCode);
1213    }
1214
1215    protected void setResultEx(int resultCode, Intent data) {
1216        mResultCodeForTesting = resultCode;
1217        mResultDataForTesting = data;
1218        setResult(resultCode, data);
1219    }
1220
1221    public int getResultCode() {
1222        return mResultCodeForTesting;
1223    }
1224
1225    public Intent getResultData() {
1226        return mResultDataForTesting;
1227    }
1228
1229    public boolean isSecureCamera() {
1230        return mSecureCamera;
1231    }
1232
1233    @Override
1234    public boolean isPaused() {
1235        return mPaused;
1236    }
1237
1238    @Override
1239    public void onModeSelected(int modeIndex) {
1240        if (mCurrentModeIndex == modeIndex) {
1241            return;
1242        }
1243
1244        if (modeIndex == ModeListView.MODE_SETTING) {
1245            onSettingsSelected();
1246            return;
1247        }
1248
1249        CameraHolder.instance().keep();
1250        closeModule(mCurrentModule);
1251        int oldModuleIndex = mCurrentModeIndex;
1252        setModuleFromModeIndex(modeIndex);
1253
1254        // TODO: The following check is temporary for modules attached to the
1255        // generic_module layout. When the refactor is done, similar logic will
1256        // be applied to all modules.
1257        if (mCurrentModeIndex == ModulesInfo.MODULE_PHOTO
1258                || mCurrentModeIndex == ModulesInfo.MODULE_VIDEO
1259                || mCurrentModeIndex == ModulesInfo.MODULE_GCAM) {
1260            if (oldModuleIndex != ModulesInfo.MODULE_PHOTO
1261                    && oldModuleIndex != ModulesInfo.MODULE_VIDEO
1262                    && oldModuleIndex != ModulesInfo.MODULE_GCAM) {
1263                mCameraAppUI.prepareModuleUI();
1264            } else {
1265                mCameraAppUI.clearModuleUI();
1266            }
1267        } else {
1268            // This is the old way of removing all views in CameraRootView. Will
1269            // be deprecated soon. It is here to make sure modules that haven't
1270            // been refactored can still function.
1271            mCameraAppUI.clearCameraUI();
1272        }
1273
1274        openModule(mCurrentModule);
1275        mCurrentModule.onOrientationChanged(mLastRawOrientation);
1276        // Store the module index so we can use it the next time the Camera
1277        // starts up.
1278        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
1279        prefs.edit().putInt(CameraSettings.KEY_STARTUP_MODULE_INDEX, modeIndex).apply();
1280    }
1281
1282    public void onSettingsSelected() {
1283        // Temporary until we finalize the touch flow.
1284        LayoutInflater inflater = getLayoutInflater();
1285        SettingsView settingsView = (SettingsView) inflater.inflate(R.layout.settings_list_layout,
1286            null, false);
1287        settingsView.setSettingsListener(mSettingsController);
1288        if (mFeedbackHelper != null) {
1289            settingsView.setFeedbackHelper(mFeedbackHelper);
1290        }
1291        PopupWindow popup = new PopupWindow(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
1292        popup.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
1293        popup.setOutsideTouchable(true);
1294        popup.setFocusable(true);
1295        popup.setContentView(settingsView);
1296        popup.showAtLocation(mModeListView.getRootView(), Gravity.CENTER, 0, 0);
1297    }
1298
1299    /**
1300     * Sets the mCurrentModuleIndex, creates a new module instance for the given
1301     * index an sets it as mCurrentModule.
1302     */
1303    private void setModuleFromModeIndex(int modeIndex) {
1304        ModuleManagerImpl.ModuleAgent agent = mModuleManager.getModuleAgent(modeIndex);
1305        if (agent == null) {
1306            return;
1307        }
1308        if (!agent.requestAppForCamera()) {
1309            mCameraController.closeCamera();
1310        }
1311        mCurrentModeIndex = agent.getModuleId();
1312        mCurrentModule = (CameraModule)  agent.createModule(this);
1313    }
1314
1315    @Override
1316    public SettingsManager getSettingsManager() {
1317        return mSettingsManager;
1318    }
1319
1320    @Override
1321    public CameraServices getServices() {
1322        return (CameraServices) getApplication();
1323    }
1324
1325    @Override
1326    public SettingsController getSettingsController() {
1327        return mSettingsController;
1328    }
1329
1330    public ButtonManager getButtonManager() {
1331        if (mButtonManager == null) {
1332            mButtonManager = new ButtonManager(this);
1333        }
1334        return mButtonManager;
1335    }
1336
1337    /**
1338     * Creates an AlertDialog appropriate for choosing whether to enable location
1339     * on the first run of the app.
1340     */
1341    public AlertDialog getFirstTimeLocationAlert() {
1342        AlertDialog.Builder builder = new AlertDialog.Builder(this);
1343        builder = SettingsView.getFirstTimeLocationAlertBuilder(builder, mSettingsController);
1344        if (builder != null) {
1345            return builder.create();
1346        } else {
1347            return null;
1348        }
1349    }
1350
1351    /**
1352     * Launches an ACTION_EDIT intent for the given local data item.
1353     */
1354    public void launchEditor(LocalData data) {
1355        Intent intent = new Intent(Intent.ACTION_EDIT)
1356                .setDataAndType(data.getContentUri(), data.getMimeType())
1357                .setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
1358        try {
1359            startActivityForResult(intent, REQ_CODE_DONT_SWITCH_TO_PREVIEW);
1360        } catch (ActivityNotFoundException e) {
1361            startActivityForResult(Intent.createChooser(intent, null),
1362                    REQ_CODE_DONT_SWITCH_TO_PREVIEW);
1363        }
1364    }
1365
1366    /**
1367     * Launch the tiny planet editor.
1368     *
1369     * @param data The data must be a 360 degree stereographically mapped
1370     *             panoramic image. It will not be modified, instead a new item
1371     *             with the result will be added to the filmstrip.
1372     */
1373    public void launchTinyPlanetEditor(LocalData data) {
1374        TinyPlanetFragment fragment = new TinyPlanetFragment();
1375        Bundle bundle = new Bundle();
1376        bundle.putString(TinyPlanetFragment.ARGUMENT_URI, data.getContentUri().toString());
1377        bundle.putString(TinyPlanetFragment.ARGUMENT_TITLE, data.getTitle());
1378        fragment.setArguments(bundle);
1379        fragment.show(getFragmentManager(), "tiny_planet");
1380    }
1381
1382    private void openModule(CameraModule module) {
1383        module.init(this, isSecureCamera(), isCaptureIntent());
1384        module.resume();
1385        module.onPreviewVisibilityChanged(!mFilmstripVisible);
1386    }
1387
1388    private void closeModule(CameraModule module) {
1389        module.pause();
1390    }
1391
1392    private void performDeletion() {
1393        if (!mPendingDeletion) {
1394            return;
1395        }
1396        hideUndoDeletionBar(false);
1397        mDataAdapter.executeDeletion(CameraActivity.this);
1398    }
1399
1400    public void showUndoDeletionBar() {
1401        if (mPendingDeletion) {
1402            performDeletion();
1403        }
1404        Log.v(TAG, "showing undo bar");
1405        mPendingDeletion = true;
1406        if (mUndoDeletionBar == null) {
1407            ViewGroup v = (ViewGroup) getLayoutInflater().inflate(R.layout.undo_bar,
1408                    mAboveFilmstripControlLayout, true);
1409            mUndoDeletionBar = (ViewGroup) v.findViewById(R.id.camera_undo_deletion_bar);
1410            View button = mUndoDeletionBar.findViewById(R.id.camera_undo_deletion_button);
1411            button.setOnClickListener(new View.OnClickListener() {
1412                @Override
1413                public void onClick(View view) {
1414                    mDataAdapter.undoDataRemoval();
1415                    hideUndoDeletionBar(true);
1416                }
1417            });
1418            // Setting undo bar clickable to avoid touch events going through
1419            // the bar to the buttons (eg. edit button, etc) underneath the bar.
1420            mUndoDeletionBar.setClickable(true);
1421            // When there is user interaction going on with the undo button, we
1422            // do not want to hide the undo bar.
1423            button.setOnTouchListener(new View.OnTouchListener() {
1424                @Override
1425                public boolean onTouch(View v, MotionEvent event) {
1426                    if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
1427                        mIsUndoingDeletion = true;
1428                    } else if (event.getActionMasked() == MotionEvent.ACTION_UP) {
1429                        mIsUndoingDeletion = false;
1430                    }
1431                    return false;
1432                }
1433            });
1434        }
1435        mUndoDeletionBar.setAlpha(0f);
1436        mUndoDeletionBar.setVisibility(View.VISIBLE);
1437        mUndoDeletionBar.animate().setDuration(200).alpha(1f).setListener(null).start();
1438    }
1439
1440    private void hideUndoDeletionBar(boolean withAnimation) {
1441        Log.v(TAG, "Hiding undo deletion bar");
1442        mPendingDeletion = false;
1443        if (mUndoDeletionBar != null) {
1444            if (withAnimation) {
1445                mUndoDeletionBar.animate().setDuration(200).alpha(0f)
1446                        .setListener(new Animator.AnimatorListener() {
1447                            @Override
1448                            public void onAnimationStart(Animator animation) {
1449                                // Do nothing.
1450                            }
1451
1452                            @Override
1453                            public void onAnimationEnd(Animator animation) {
1454                                mUndoDeletionBar.setVisibility(View.GONE);
1455                            }
1456
1457                            @Override
1458                            public void onAnimationCancel(Animator animation) {
1459                                // Do nothing.
1460                            }
1461
1462                            @Override
1463                            public void onAnimationRepeat(Animator animation) {
1464                                // Do nothing.
1465                            }
1466                        }).start();
1467            } else {
1468                mUndoDeletionBar.setVisibility(View.GONE);
1469            }
1470        }
1471    }
1472
1473    @Override
1474    public void onOrientationChanged(int orientation) {
1475        // We keep the last known orientation. So if the user first orient
1476        // the camera then point the camera to floor or sky, we still have
1477        // the correct orientation.
1478        if (orientation == OrientationManager.ORIENTATION_UNKNOWN) {
1479            return;
1480        }
1481        mLastRawOrientation = orientation;
1482        if (mCurrentModule != null) {
1483            mCurrentModule.onOrientationChanged(orientation);
1484        }
1485    }
1486
1487    /**
1488     * Enable/disable swipe-to-filmstrip. Will always disable swipe if in
1489     * capture intent.
1490     *
1491     * @param enable {@code true} to enable swipe.
1492     */
1493    public void setSwipingEnabled(boolean enable) {
1494        // TODO: Bring back the functionality.
1495        if (isCaptureIntent()) {
1496            //lockPreview(true);
1497        } else {
1498            //lockPreview(!enable);
1499        }
1500    }
1501
1502    // Accessor methods for getting latency times used in performance testing
1503    public long getAutoFocusTime() {
1504        return (mCurrentModule instanceof PhotoModule) ?
1505                ((PhotoModule) mCurrentModule).mAutoFocusTime : -1;
1506    }
1507
1508    public long getShutterLag() {
1509        return (mCurrentModule instanceof PhotoModule) ?
1510                ((PhotoModule) mCurrentModule).mShutterLag : -1;
1511    }
1512
1513    public long getShutterToPictureDisplayedTime() {
1514        return (mCurrentModule instanceof PhotoModule) ?
1515                ((PhotoModule) mCurrentModule).mShutterToPictureDisplayedTime : -1;
1516    }
1517
1518    public long getPictureDisplayedToJpegCallbackTime() {
1519        return (mCurrentModule instanceof PhotoModule) ?
1520                ((PhotoModule) mCurrentModule).mPictureDisplayedToJpegCallbackTime : -1;
1521    }
1522
1523    public long getJpegCallbackFinishTime() {
1524        return (mCurrentModule instanceof PhotoModule) ?
1525                ((PhotoModule) mCurrentModule).mJpegCallbackFinishTime : -1;
1526    }
1527
1528    public long getCaptureStartTime() {
1529        return (mCurrentModule instanceof PhotoModule) ?
1530                ((PhotoModule) mCurrentModule).mCaptureStartTime : -1;
1531    }
1532
1533    public boolean isRecording() {
1534        return (mCurrentModule instanceof VideoModule) ?
1535                ((VideoModule) mCurrentModule).isRecording() : false;
1536    }
1537
1538    public CameraManager.CameraOpenCallback getCameraOpenErrorCallback() {
1539        return mCameraController;
1540    }
1541
1542    // For debugging purposes only.
1543    public CameraModule getCurrentModule() {
1544        return mCurrentModule;
1545    }
1546
1547    private void keepScreenOnForAWhile() {
1548        if (mKeepScreenOn) {
1549            return;
1550        }
1551        mMainHandler.removeMessages(MSG_CLEAR_SCREEN_ON_FLAG);
1552        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1553        mMainHandler.sendEmptyMessageDelayed(MSG_CLEAR_SCREEN_ON_FLAG, SCREEN_DELAY_MS);
1554    }
1555
1556    private void resetScreenOn() {
1557        mKeepScreenOn = false;
1558        mMainHandler.removeMessages(MSG_CLEAR_SCREEN_ON_FLAG);
1559        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1560    }
1561
1562    private void startGallery() {
1563        try {
1564            UsageStatistics.onEvent(UsageStatistics.COMPONENT_CAMERA,
1565                    UsageStatistics.ACTION_GALLERY, null);
1566            startActivityForResult(IntentHelper.getGalleryIntent(CameraActivity.this),
1567                    REQ_CODE_DONT_SWITCH_TO_PREVIEW);
1568        } catch (ActivityNotFoundException e) {
1569            Log.w(TAG, "Failed to launch gallery activity, closing");
1570        }
1571    }
1572
1573    private void setNfcBeamPushUriFromData(LocalData data) {
1574        final Uri uri = data.getContentUri();
1575        if (uri != Uri.EMPTY) {
1576            mNfcPushUris[0] = uri;
1577        } else {
1578            mNfcPushUris[0] = null;
1579        }
1580    }
1581
1582    /**
1583     * Updates the visibility of the filmstrip bottom controls.
1584     */
1585    private void updateUiByData(final int dataId) {
1586        if (isSecureCamera()) {
1587            // We cannot show buttons in secure camera since go to other
1588            // activities might create a security hole.
1589            return;
1590        }
1591
1592        final LocalData currentData = mDataAdapter.getLocalData(dataId);
1593        if (currentData == null) {
1594            Log.w(TAG, "Current data ID not found.");
1595            hideSessionProgress();
1596            return;
1597        }
1598
1599        setNfcBeamPushUriFromData(currentData);
1600
1601        /* Bottom controls. */
1602
1603        final CameraAppUI.BottomControls filmstripBottomControls =
1604                mCameraAppUI.getFilmstripBottomControls();
1605        filmstripBottomControls.setEditButtonVisibility(
1606                currentData.isDataActionSupported(LocalData.DATA_ACTION_EDIT));
1607        filmstripBottomControls.setShareButtonVisibility(
1608                currentData.isDataActionSupported(LocalData.DATA_ACTION_SHARE));
1609        filmstripBottomControls.setDeleteButtonVisibility(
1610                currentData.isDataActionSupported(LocalData.DATA_ACTION_DELETE));
1611
1612        /* Progress bar */
1613
1614        Uri contentUri = currentData.getContentUri();
1615        CaptureSessionManager sessionManager = getServices()
1616                .getCaptureSessionManager();
1617        int sessionProgress = sessionManager.getSessionProgress(contentUri);
1618
1619        if (sessionProgress < 0) {
1620            hideSessionProgress();
1621        } else {
1622            CharSequence progressMessage = sessionManager
1623                    .getSessionProgressMessage(contentUri);
1624            showSessionProgress(progressMessage);
1625            updateSessionProgress(sessionProgress);
1626        }
1627
1628        /* View button */
1629
1630        // We need to add this to a separate DB.
1631        // TODO: Redesign this.
1632        currentData.requestAuxInfo(this, new LocalData.AuxInfoSupportCallback() {
1633            @Override
1634            public void auxInfoAvailable(final boolean isPanorama,
1635                    final boolean isPanorama360, boolean isRgbz) {
1636                // Make sure the returned data is for the current image.
1637                if (dataId != mFilmstripController.getCurrentId()) {
1638                    return;
1639                }
1640
1641                // If this is a photo sphere, show the button to view it. If it's a full
1642                // 360 photo sphere, show the tiny planet button.
1643                final int viewButtonVisibility;
1644                if (isPanorama) {
1645                    viewButtonVisibility = CameraAppUI.BottomControls.VIEW_PHOTO_SPHERE;
1646                } else if (isRgbz) {
1647                    viewButtonVisibility = CameraAppUI.BottomControls.VIEW_RGBZ;
1648                } else {
1649                    viewButtonVisibility = CameraAppUI.BottomControls.VIEW_NONE;
1650                }
1651
1652                runOnUiThread(new Runnable() {
1653
1654                    @Override
1655                    public void run() {
1656                        if (mFilmstripController.getCurrentId() == dataId) {
1657                            filmstripBottomControls.setTinyPlanetButtonVisibility(isPanorama360);
1658                            filmstripBottomControls.setViewButtonVisibility(viewButtonVisibility);
1659                        }
1660                    }
1661                });
1662            }
1663        });
1664    }
1665}
1666