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