2 * Copyright (C) 2012 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 package com.android.camera;
20 import android.animation.Animator;
21 import android.app.ActionBar;
22 import android.app.Activity;
23 import android.app.Dialog;
24 import android.content.ActivityNotFoundException;
25 import android.content.BroadcastReceiver;
26 import android.content.ContentResolver;
27 import android.content.Context;
28 import android.content.Intent;
29 import android.content.IntentFilter;
30 import android.content.pm.ActivityInfo;
31 import android.content.res.Configuration;
32 import android.graphics.Bitmap;
33 import android.graphics.Matrix;
34 import android.graphics.RectF;
35 import android.graphics.SurfaceTexture;
36 import android.graphics.drawable.ColorDrawable;
37 import android.graphics.drawable.Drawable;
38 import android.net.Uri;
39 import android.nfc.NfcAdapter;
40 import android.nfc.NfcAdapter.CreateBeamUrisCallback;
41 import android.nfc.NfcEvent;
42 import android.os.AsyncTask;
43 import android.os.Build;
44 import android.os.Bundle;
45 import android.os.Handler;
46 import android.os.Looper;
47 import android.os.Message;
48 import android.provider.MediaStore;
49 import android.provider.Settings;
50 import android.text.TextUtils;
51 import android.util.CameraPerformanceTracker;
52 import android.view.ContextMenu;
53 import android.view.ContextMenu.ContextMenuInfo;
54 import android.view.KeyEvent;
55 import android.view.Menu;
56 import android.view.MenuInflater;
57 import android.view.MenuItem;
58 import android.view.MotionEvent;
59 import android.view.View;
60 import android.view.View.OnSystemUiVisibilityChangeListener;
61 import android.view.ViewGroup;
62 import android.view.Window;
63 import android.view.WindowManager;
64 import android.widget.FrameLayout;
65 import android.widget.ImageView;
66 import android.widget.ShareActionProvider;
68 import com.android.camera.app.AppController;
69 import com.android.camera.app.CameraAppUI;
70 import com.android.camera.app.CameraController;
71 import com.android.camera.app.CameraProvider;
72 import com.android.camera.app.CameraServices;
73 import com.android.camera.app.CameraServicesImpl;
74 import com.android.camera.app.FirstRunDialog;
75 import com.android.camera.app.LocationManager;
76 import com.android.camera.app.MemoryManager;
77 import com.android.camera.app.MemoryQuery;
78 import com.android.camera.app.ModuleManager;
79 import com.android.camera.app.ModuleManager.ModuleAgent;
80 import com.android.camera.app.ModuleManagerImpl;
81 import com.android.camera.app.MotionManager;
82 import com.android.camera.app.OrientationManager;
83 import com.android.camera.app.OrientationManagerImpl;
84 import com.android.camera.data.CameraFilmstripDataAdapter;
85 import com.android.camera.data.FilmstripContentObserver;
86 import com.android.camera.data.FilmstripItem;
87 import com.android.camera.data.FilmstripItemData;
88 import com.android.camera.data.FilmstripItemType;
89 import com.android.camera.data.FilmstripItemUtils;
90 import com.android.camera.data.FixedLastProxyAdapter;
91 import com.android.camera.data.GlideFilmstripManager;
92 import com.android.camera.data.LocalFilmstripDataAdapter;
93 import com.android.camera.data.LocalFilmstripDataAdapter.FilmstripItemListener;
94 import com.android.camera.data.MediaDetails;
95 import com.android.camera.data.MetadataLoader;
96 import com.android.camera.data.PhotoDataFactory;
97 import com.android.camera.data.PhotoItem;
98 import com.android.camera.data.PhotoItemFactory;
99 import com.android.camera.data.PlaceholderItem;
100 import com.android.camera.data.SessionItem;
101 import com.android.camera.data.VideoDataFactory;
102 import com.android.camera.data.VideoItemFactory;
103 import com.android.camera.debug.Log;
104 import com.android.camera.device.ActiveCameraDeviceTracker;
105 import com.android.camera.filmstrip.FilmstripContentPanel;
106 import com.android.camera.filmstrip.FilmstripController;
107 import com.android.camera.module.ModuleController;
108 import com.android.camera.module.ModulesInfo;
109 import com.android.camera.one.OneCameraException;
110 import com.android.camera.one.OneCameraManager;
111 import com.android.camera.one.OneCameraModule;
112 import com.android.camera.one.OneCameraOpener;
113 import com.android.camera.one.config.OneCameraFeatureConfig;
114 import com.android.camera.one.config.OneCameraFeatureConfigCreator;
115 import com.android.camera.session.CaptureSession;
116 import com.android.camera.session.CaptureSessionManager;
117 import com.android.camera.session.CaptureSessionManager.SessionListener;
118 import com.android.camera.settings.AppUpgrader;
119 import com.android.camera.settings.CameraSettingsActivity;
120 import com.android.camera.settings.Keys;
121 import com.android.camera.settings.ResolutionSetting;
122 import com.android.camera.settings.ResolutionUtil;
123 import com.android.camera.settings.SettingsManager;
124 import com.android.camera.stats.UsageStatistics;
125 import com.android.camera.stats.profiler.Profile;
126 import com.android.camera.stats.profiler.Profiler;
127 import com.android.camera.stats.profiler.Profilers;
128 import com.android.camera.tinyplanet.TinyPlanetFragment;
129 import com.android.camera.ui.AbstractTutorialOverlay;
130 import com.android.camera.ui.DetailsDialog;
131 import com.android.camera.ui.MainActivityLayout;
132 import com.android.camera.ui.ModeListView;
133 import com.android.camera.ui.ModeListView.ModeListVisibilityChangedListener;
134 import com.android.camera.ui.PreviewStatusListener;
135 import com.android.camera.util.ApiHelper;
136 import com.android.camera.util.Callback;
137 import com.android.camera.util.CameraUtil;
138 import com.android.camera.util.GalleryHelper;
139 import com.android.camera.util.GcamHelper;
140 import com.android.camera.util.GoogleHelpHelper;
141 import com.android.camera.util.IntentHelper;
142 import com.android.camera.util.PhotoSphereHelper.PanoramaViewHelper;
143 import com.android.camera.util.QuickActivity;
144 import com.android.camera.util.ReleaseHelper;
145 import com.android.camera.widget.FilmstripView;
146 import com.android.camera.widget.Preloader;
147 import com.android.camera2.R;
148 import com.android.ex.camera2.portability.CameraAgent;
149 import com.android.ex.camera2.portability.CameraAgentFactory;
150 import com.android.ex.camera2.portability.CameraExceptionHandler;
151 import com.android.ex.camera2.portability.CameraSettings;
152 import com.bumptech.glide.Glide;
153 import com.bumptech.glide.GlideBuilder;
154 import com.bumptech.glide.MemoryCategory;
155 import com.bumptech.glide.load.DecodeFormat;
156 import com.bumptech.glide.load.engine.executor.FifoPriorityThreadPoolExecutor;
157 import com.bumptech.glide.load.engine.prefill.PreFillType;
158 import com.google.common.base.Optional;
159 import com.google.common.logging.eventprotos;
160 import com.google.common.logging.eventprotos.ForegroundEvent.ForegroundSource;
161 import com.google.common.logging.eventprotos.MediaInteraction;
162 import com.google.common.logging.eventprotos.NavigationChange;
165 import java.lang.ref.WeakReference;
166 import java.util.ArrayList;
167 import java.util.HashMap;
168 import java.util.List;
170 public class CameraActivity extends QuickActivity
171 implements AppController, CameraAgent.CameraOpenCallback,
172 ShareActionProvider.OnShareTargetSelectedListener {
174 private static final Log.Tag TAG = new Log.Tag("CameraActivity");
176 private static final String INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE =
177 "android.media.action.STILL_IMAGE_CAMERA_SECURE";
178 public static final String ACTION_IMAGE_CAPTURE_SECURE =
179 "android.media.action.IMAGE_CAPTURE_SECURE";
181 // The intent extra for camera from secure lock screen. True if the gallery
182 // should only show newly captured pictures. sSecureAlbumId does not
183 // increment. This is used when switching between camera, camcorder, and
184 // panorama. If the extra is not set, it is in the normal camera mode.
185 public static final String SECURE_CAMERA_EXTRA = "secure_camera";
187 public static final String MODULE_SCOPE_PREFIX = "_preferences_module_";
188 public static final String CAMERA_SCOPE_PREFIX = "_preferences_camera_";
190 private static final int MSG_CLEAR_SCREEN_ON_FLAG = 2;
191 private static final long SCREEN_DELAY_MS = 2 * 60 * 1000; // 2 mins.
192 /** Load metadata for 10 items ahead of our current. */
193 private static final int FILMSTRIP_PRELOAD_AHEAD_ITEMS = 10;
195 /** Should be used wherever a context is needed. */
196 private Context mAppContext;
199 * Camera fatal error handling:
200 * 1) Present error dialog to guide users to exit the app.
201 * 2) If users hit home button, onPause should just call finish() to exit the app.
203 private boolean mCameraFatalError = false;
206 * Whether onResume should reset the view to the preview.
208 private boolean mResetToPreviewOnResume = true;
211 * This data adapter is used by FilmStripView.
213 private VideoItemFactory mVideoItemFactory;
214 private PhotoItemFactory mPhotoItemFactory;
215 private LocalFilmstripDataAdapter mDataAdapter;
217 private OneCameraOpener mOneCameraOpener;
218 private OneCameraManager mOneCameraManager;
219 private SettingsManager mSettingsManager;
220 private ResolutionSetting mResolutionSetting;
221 private ModeListView mModeListView;
222 private boolean mModeListVisible = false;
223 private int mCurrentModeIndex;
224 private CameraModule mCurrentModule;
225 private ModuleManagerImpl mModuleManager;
226 private FrameLayout mAboveFilmstripControlLayout;
227 private FilmstripController mFilmstripController;
228 private boolean mFilmstripVisible;
229 /** Whether the filmstrip fully covers the preview. */
230 private boolean mFilmstripCoversPreview = false;
231 private int mResultCodeForTesting;
232 private Intent mResultDataForTesting;
233 private OnScreenHint mStorageHint;
234 private final Object mStorageSpaceLock = new Object();
235 private long mStorageSpaceBytes = Storage.LOW_STORAGE_THRESHOLD_BYTES;
236 private boolean mAutoRotateScreen;
237 private boolean mSecureCamera;
238 private OrientationManagerImpl mOrientationManager;
239 private LocationManager mLocationManager;
240 private ButtonManager mButtonManager;
241 private Handler mMainHandler;
242 private PanoramaViewHelper mPanoramaViewHelper;
243 private ActionBar mActionBar;
244 private ViewGroup mUndoDeletionBar;
245 private boolean mIsUndoingDeletion = false;
246 private boolean mIsActivityRunning = false;
247 private FatalErrorHandler mFatalErrorHandler;
249 private final Uri[] mNfcPushUris = new Uri[1];
251 private FilmstripContentObserver mLocalImagesObserver;
252 private FilmstripContentObserver mLocalVideosObserver;
254 private boolean mPendingDeletion = false;
256 private CameraController mCameraController;
257 private boolean mPaused;
258 private CameraAppUI mCameraAppUI;
260 private Intent mGalleryIntent;
261 private long mOnCreateTime;
263 private Menu mActionBarMenu;
264 private Preloader<Integer, AsyncTask> mPreloader;
266 /** Can be used to play custom sounds. */
267 private SoundPlayer mSoundPlayer;
269 /** Holds configuration for various OneCamera features. */
270 private OneCameraFeatureConfig mFeatureConfig;
272 private static final int LIGHTS_OUT_DELAY_MS = 4000;
273 private final int BASE_SYS_UI_VISIBILITY =
274 View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
275 | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
276 private final Runnable mLightsOutRunnable = new Runnable() {
279 getWindow().getDecorView().setSystemUiVisibility(
280 BASE_SYS_UI_VISIBILITY | View.SYSTEM_UI_FLAG_LOW_PROFILE);
283 private MemoryManager mMemoryManager;
284 private MotionManager mMotionManager;
285 private final Profiler mProfiler = Profilers.instance().guard();
287 /** First run dialog */
288 private FirstRunDialog mFirstRunDialog;
291 public CameraAppUI getCameraAppUI() {
296 public ModuleManager getModuleManager() {
297 return mModuleManager;
301 * Close activity when secure app passes lock screen or screen turns
304 private final BroadcastReceiver mShutdownReceiver = new BroadcastReceiver() {
306 public void onReceive(Context context, Intent intent) {
312 * Whether the screen is kept turned on.
314 private boolean mKeepScreenOn;
315 private int mLastLayoutOrientation;
316 private final CameraAppUI.BottomPanel.Listener mMyFilmstripBottomControlListener =
317 new CameraAppUI.BottomPanel.Listener() {
320 * If the current photo is a photo sphere, this will launch the
321 * Photo Sphere panorama viewer.
324 public void onExternalViewer() {
325 if (mPanoramaViewHelper == null) {
328 final FilmstripItem data = getCurrentLocalData();
330 Log.w(TAG, "Cannot open null data.");
333 final Uri contentUri = data.getData().getUri();
334 if (contentUri == Uri.EMPTY) {
335 Log.w(TAG, "Cannot open empty URL.");
339 if (data.getMetadata().isUsePanoramaViewer()) {
340 mPanoramaViewHelper.showPanorama(CameraActivity.this, contentUri);
341 } else if (data.getMetadata().isHasRgbzData()) {
342 mPanoramaViewHelper.showRgbz(contentUri);
343 if (mSettingsManager.getBoolean(SettingsManager.SCOPE_GLOBAL,
344 Keys.KEY_SHOULD_SHOW_REFOCUS_VIEWER_CLING)) {
345 mSettingsManager.set(SettingsManager.SCOPE_GLOBAL,
346 Keys.KEY_SHOULD_SHOW_REFOCUS_VIEWER_CLING, false);
347 mCameraAppUI.clearClingForViewer(
348 CameraAppUI.BottomPanel.VIEWER_REFOCUS);
354 public void onEdit() {
355 FilmstripItem data = getCurrentLocalData();
357 Log.w(TAG, "Cannot edit null data.");
360 final int currentDataId = getCurrentDataId();
361 UsageStatistics.instance().mediaInteraction(fileNameFromAdapterAtIndex(
363 MediaInteraction.InteractionType.EDIT,
364 NavigationChange.InteractionCause.BUTTON,
365 fileAgeFromAdapterAtIndex(currentDataId));
370 public void onTinyPlanet() {
371 FilmstripItem data = getCurrentLocalData();
373 Log.w(TAG, "Cannot edit tiny planet on null data.");
376 launchTinyPlanetEditor(data);
380 public void onDelete() {
381 final int currentDataId = getCurrentDataId();
382 UsageStatistics.instance().mediaInteraction(fileNameFromAdapterAtIndex(
384 MediaInteraction.InteractionType.DELETE,
385 NavigationChange.InteractionCause.BUTTON,
386 fileAgeFromAdapterAtIndex(currentDataId));
387 removeItemAt(currentDataId);
391 public void onShare() {
392 final FilmstripItem data = getCurrentLocalData();
394 Log.w(TAG, "Cannot share null data.");
398 final int currentDataId = getCurrentDataId();
399 UsageStatistics.instance().mediaInteraction(fileNameFromAdapterAtIndex(
401 MediaInteraction.InteractionType.SHARE,
402 NavigationChange.InteractionCause.BUTTON,
403 fileAgeFromAdapterAtIndex(currentDataId));
404 // If applicable, show release information before this item
406 if (ReleaseHelper.shouldShowReleaseInfoDialogOnShare(data)) {
407 ReleaseHelper.showReleaseInfoDialog(CameraActivity.this,
408 new Callback<Void>() {
410 public void onCallback(Void result) {
419 private void share(FilmstripItem data) {
420 Intent shareIntent = getShareIntentByData(data);
421 if (shareIntent != null) {
423 launchActivityByIntent(shareIntent);
424 mCameraAppUI.getFilmstripBottomControls().setShareEnabled(false);
425 } catch (ActivityNotFoundException ex) {
431 private int getCurrentDataId() {
432 return mFilmstripController.getCurrentAdapterIndex();
435 private FilmstripItem getCurrentLocalData() {
436 return mDataAdapter.getItemAt(getCurrentDataId());
440 * Sets up the share intent and NFC properly according to the
443 * @param item The data to be shared.
445 private Intent getShareIntentByData(final FilmstripItem item) {
446 Intent intent = null;
447 final Uri contentUri = item.getData().getUri();
448 final String msgShareTo = getResources().getString(R.string.share_to);
450 if (item.getMetadata().isPanorama360() &&
451 item.getData().getUri() != Uri.EMPTY) {
452 intent = new Intent(Intent.ACTION_SEND);
453 intent.setType(FilmstripItemData.MIME_TYPE_PHOTOSPHERE);
454 intent.putExtra(Intent.EXTRA_STREAM, contentUri);
455 } else if (item.getAttributes().canShare()) {
456 final String mimeType = item.getData().getMimeType();
457 intent = getShareIntentFromType(mimeType);
458 if (intent != null) {
459 intent.putExtra(Intent.EXTRA_STREAM, contentUri);
460 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
462 intent = Intent.createChooser(intent, msgShareTo);
468 * Get the share intent according to the mimeType
470 * @param mimeType The mimeType of current data.
471 * @return the video/image's ShareIntent or null if mimeType is
474 private Intent getShareIntentFromType(String mimeType) {
475 // Lazily create the intent object.
476 Intent intent = new Intent(Intent.ACTION_SEND);
477 if (mimeType.startsWith("video/")) {
478 intent.setType("video/*");
480 if (mimeType.startsWith("image/")) {
481 intent.setType("image/*");
483 Log.w(TAG, "unsupported mimeType " + mimeType);
490 public void onProgressErrorClicked() {
491 FilmstripItem data = getCurrentLocalData();
492 getServices().getCaptureSessionManager().removeErrorMessage(
493 data.getData().getUri());
494 updateBottomControlsByData(data);
499 public void onCameraOpened(CameraAgent.CameraProxy camera) {
500 Log.v(TAG, "onCameraOpened");
502 // We've paused, but just asynchronously opened the camera. Close it
503 // because we should be releasing the camera when paused to allow
504 // other apps to access it.
505 Log.v(TAG, "received onCameraOpened but activity is paused, closing Camera");
506 mCameraController.closeCamera(false);
510 if (!mModuleManager.getModuleAgent(mCurrentModeIndex).requestAppForCamera()) {
511 // We shouldn't be here. Just close the camera and leave.
512 mCameraController.closeCamera(false);
513 throw new IllegalStateException("Camera opened but the module shouldn't be " +
516 if (mCurrentModule != null) {
517 resetExposureCompensationToDefault(camera);
518 mCurrentModule.onCameraAvailable(camera);
520 Log.v(TAG, "mCurrentModule null, not invoking onCameraAvailable");
522 Log.v(TAG, "invoking onChangeCamera");
523 mCameraAppUI.onChangeCamera();
526 private void resetExposureCompensationToDefault(CameraAgent.CameraProxy camera) {
527 // Reset the exposure compensation before handing the camera to module.
528 CameraSettings cameraSettings = camera.getSettings();
529 cameraSettings.setExposureCompensationIndex(0);
530 camera.applySettings(cameraSettings);
534 public void onCameraDisabled(int cameraId) {
535 Log.w(TAG, "Camera disabled: " + cameraId);
536 mFatalErrorHandler.onCameraDisabledFailure();
540 public void onDeviceOpenFailure(int cameraId, String info) {
541 Log.w(TAG, "Camera open failure: " + info);
542 mFatalErrorHandler.onCameraOpenFailure();
546 public void onDeviceOpenedAlready(int cameraId, String info) {
547 Log.w(TAG, "Camera open already: " + cameraId + "," + info);
548 mFatalErrorHandler.onGenericCameraAccessFailure();
552 public void onReconnectionFailure(CameraAgent mgr, String info) {
553 Log.w(TAG, "Camera reconnection failure:" + info);
554 mFatalErrorHandler.onCameraReconnectFailure();
557 private static class MainHandler extends Handler {
558 final WeakReference<CameraActivity> mActivity;
560 public MainHandler(CameraActivity activity, Looper looper) {
562 mActivity = new WeakReference<CameraActivity>(activity);
566 public void handleMessage(Message msg) {
567 CameraActivity activity = mActivity.get();
568 if (activity == null) {
573 case MSG_CLEAR_SCREEN_ON_FLAG: {
574 if (!activity.mPaused) {
575 activity.getWindow().clearFlags(
576 WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
584 private String fileNameFromAdapterAtIndex(int index) {
585 final FilmstripItem filmstripItem = mDataAdapter.getItemAt(index);
586 if (filmstripItem == null) {
590 File localFile = new File(filmstripItem.getData().getFilePath());
591 return localFile.getName();
594 private float fileAgeFromAdapterAtIndex(int index) {
595 final FilmstripItem filmstripItem = mDataAdapter.getItemAt(index);
596 if (filmstripItem == null) {
600 File localFile = new File(filmstripItem.getData().getFilePath());
601 return 0.001f * (System.currentTimeMillis() - localFile.lastModified());
604 private final FilmstripContentPanel.Listener mFilmstripListener =
605 new FilmstripContentPanel.Listener() {
608 public void onSwipeOut() {
612 public void onSwipeOutBegin() {
614 mCameraAppUI.hideBottomControls();
615 mFilmstripCoversPreview = false;
616 updatePreviewVisibility();
620 public void onFilmstripHidden() {
621 mFilmstripVisible = false;
622 UsageStatistics.instance().changeScreen(currentUserInterfaceMode(),
623 NavigationChange.InteractionCause.SWIPE_RIGHT);
624 CameraActivity.this.setFilmstripUiVisibility(false);
625 // When the user hide the filmstrip (either swipe out or
626 // tap on back key) we move to the first item so next time
627 // when the user swipe in the filmstrip, the most recent
629 mFilmstripController.goToFirstItem();
633 public void onFilmstripShown() {
634 mFilmstripVisible = true;
635 mCameraAppUI.hideCaptureIndicator();
636 UsageStatistics.instance().changeScreen(currentUserInterfaceMode(),
637 NavigationChange.InteractionCause.SWIPE_LEFT);
638 updateUiByData(mFilmstripController.getCurrentAdapterIndex());
642 public void onFocusedDataLongPressed(int adapterIndex) {
647 public void onFocusedDataPromoted(int adapterIndex) {
648 UsageStatistics.instance().mediaInteraction(fileNameFromAdapterAtIndex(
650 MediaInteraction.InteractionType.DELETE,
651 NavigationChange.InteractionCause.SWIPE_UP, fileAgeFromAdapterAtIndex(
653 removeItemAt(adapterIndex);
657 public void onFocusedDataDemoted(int adapterIndex) {
658 UsageStatistics.instance().mediaInteraction(fileNameFromAdapterAtIndex(
660 MediaInteraction.InteractionType.DELETE,
661 NavigationChange.InteractionCause.SWIPE_DOWN,
662 fileAgeFromAdapterAtIndex(adapterIndex));
663 removeItemAt(adapterIndex);
667 public void onEnterFullScreenUiShown(int adapterIndex) {
668 if (mFilmstripVisible) {
669 CameraActivity.this.setFilmstripUiVisibility(true);
674 public void onLeaveFullScreenUiShown(int adapterIndex) {
679 public void onEnterFullScreenUiHidden(int adapterIndex) {
680 if (mFilmstripVisible) {
681 CameraActivity.this.setFilmstripUiVisibility(false);
686 public void onLeaveFullScreenUiHidden(int adapterIndex) {
691 public void onEnterFilmstrip(int adapterIndex) {
692 if (mFilmstripVisible) {
693 CameraActivity.this.setFilmstripUiVisibility(true);
698 public void onLeaveFilmstrip(int adapterIndex) {
703 public void onDataReloaded() {
704 if (!mFilmstripVisible) {
707 updateUiByData(mFilmstripController.getCurrentAdapterIndex());
711 public void onDataUpdated(int adapterIndex) {
712 if (!mFilmstripVisible) {
715 updateUiByData(mFilmstripController.getCurrentAdapterIndex());
719 public void onEnterZoomView(int adapterIndex) {
720 if (mFilmstripVisible) {
721 CameraActivity.this.setFilmstripUiVisibility(false);
726 public void onZoomAtIndexChanged(int adapterIndex, float zoom) {
727 final FilmstripItem filmstripItem = mDataAdapter.getItemAt(adapterIndex);
728 long ageMillis = System.currentTimeMillis()
729 - filmstripItem.getData().getLastModifiedDate().getTime();
731 // Do not log if items is to old or does not have a path (which is
732 // being used as a key).
733 if (TextUtils.isEmpty(filmstripItem.getData().getFilePath()) ||
734 ageMillis > UsageStatistics.VIEW_TIMEOUT_MILLIS) {
737 File localFile = new File(filmstripItem.getData().getFilePath());
738 UsageStatistics.instance().mediaView(localFile.getName(),
739 filmstripItem.getData().getLastModifiedDate().getTime(), zoom);
743 public void onDataFocusChanged(final int prevIndex, final int newIndex) {
744 if (!mFilmstripVisible) {
747 // TODO: This callback is UI event callback, should always
748 // happen on UI thread. Find the reason for this
749 // runOnUiThread() and fix it.
750 runOnUiThread(new Runnable() {
753 updateUiByData(newIndex);
759 public void onScroll(int firstVisiblePosition, int visibleItemCount, int totalItemCount) {
760 mPreloader.onScroll(null /*absListView*/, firstVisiblePosition, visibleItemCount, totalItemCount);
764 private final FilmstripItemListener mFilmstripItemListener =
765 new FilmstripItemListener() {
767 public void onMetadataUpdated(List<Integer> indexes) {
769 // Callback after the activity is paused.
772 int currentIndex = mFilmstripController.getCurrentAdapterIndex();
773 for (Integer index : indexes) {
774 if (index == currentIndex) {
775 updateBottomControlsByData(mDataAdapter.getItemAt(index));
776 // Currently we have only 1 data can be matched.
777 // No need to look for more, break.
784 public void gotoGallery() {
785 UsageStatistics.instance().changeScreen(NavigationChange.Mode.FILMSTRIP,
786 NavigationChange.InteractionCause.BUTTON);
788 mFilmstripController.goToNextItem();
792 * If 'visible' is false, this hides the action bar. Also maintains
793 * lights-out at all times.
795 * @param visible is false, this hides the action bar and filmstrip bottom
798 private void setFilmstripUiVisibility(boolean visible) {
799 mLightsOutRunnable.run();
800 mCameraAppUI.getFilmstripBottomControls().setVisible(visible);
801 if (visible != mActionBar.isShowing()) {
804 mCameraAppUI.showBottomControls();
807 mCameraAppUI.hideBottomControls();
810 mFilmstripCoversPreview = visible;
811 updatePreviewVisibility();
814 private void hideSessionProgress() {
815 mCameraAppUI.getFilmstripBottomControls().hideProgress();
818 private void showSessionProgress(int messageId) {
819 CameraAppUI.BottomPanel controls = mCameraAppUI.getFilmstripBottomControls();
820 controls.setProgressText(messageId > 0 ? getString(messageId) : "");
821 controls.hideControls();
822 controls.hideProgressError();
823 controls.showProgress();
826 private void showProcessError(int messageId) {
827 mCameraAppUI.getFilmstripBottomControls().showProgressError(
828 messageId > 0 ? getString(messageId) : "");
831 private void updateSessionProgress(int progress) {
832 mCameraAppUI.getFilmstripBottomControls().setProgress(progress);
835 private void updateSessionProgressText(int messageId) {
836 mCameraAppUI.getFilmstripBottomControls().setProgressText(
837 messageId > 0 ? getString(messageId) : "");
840 private void setupNfcBeamPush() {
841 NfcAdapter adapter = NfcAdapter.getDefaultAdapter(mAppContext);
842 if (adapter == null) {
846 if (!ApiHelper.HAS_SET_BEAM_PUSH_URIS) {
848 adapter.setNdefPushMessage(null, CameraActivity.this);
852 adapter.setBeamPushUris(null, CameraActivity.this);
853 adapter.setBeamPushUrisCallback(new CreateBeamUrisCallback() {
855 public Uri[] createBeamUris(NfcEvent event) {
858 }, CameraActivity.this);
862 public boolean onShareTargetSelected(ShareActionProvider shareActionProvider, Intent intent) {
863 int currentIndex = mFilmstripController.getCurrentAdapterIndex();
864 if (currentIndex < 0) {
867 UsageStatistics.instance().mediaInteraction(fileNameFromAdapterAtIndex(currentIndex),
868 MediaInteraction.InteractionType.SHARE,
869 NavigationChange.InteractionCause.BUTTON, fileAgeFromAdapterAtIndex(currentIndex));
870 // TODO add intent.getComponent().getPackageName()
874 // Note: All callbacks come back on the main thread.
875 private final SessionListener mSessionListener =
876 new SessionListener() {
878 public void onSessionQueued(final Uri uri) {
879 Log.v(TAG, "onSessionQueued: " + uri);
880 if (!Storage.isSessionUri(uri)) {
883 SessionItem newData = new SessionItem(getApplicationContext(), uri);
884 mDataAdapter.addOrUpdate(newData);
888 public void onSessionUpdated(Uri uri) {
889 Log.v(TAG, "onSessionUpdated: " + uri);
890 mDataAdapter.refresh(uri);
894 public void onSessionDone(final Uri sessionUri) {
895 Log.v(TAG, "onSessionDone:" + sessionUri);
896 Uri contentUri = Storage.getContentUriForSessionUri(sessionUri);
897 if (contentUri == null) {
898 mDataAdapter.refresh(sessionUri);
901 PhotoItem newData = mPhotoItemFactory.queryContentUri(contentUri);
903 // This can be null if e.g. a session is canceled (e.g.
904 // through discard panorama). It might be worth adding
905 // onSessionCanceled or the like this interface.
906 if (newData == null) {
907 Log.i(TAG, "onSessionDone: Could not find LocalData for URI: " + contentUri);
911 final int pos = mDataAdapter.findByContentUri(sessionUri);
913 // We do not have a placeholder for this image, perhaps
914 // due to the activity crashing or being killed.
915 mDataAdapter.addOrUpdate(newData);
917 // Make the PhotoItem aware of the session placeholder, to
918 // allow it to make a smooth transition to its content if it
919 // the session item is currently visible.
920 FilmstripItem oldSessionData = mDataAdapter.getFilmstripItemAt(pos);
921 if (mCameraAppUI.getFilmstripVisibility() == View.VISIBLE
922 && mFilmstripController.isVisible(oldSessionData)) {
923 Log.v(TAG, "session item visible, setting transition placeholder");
924 newData.setSessionPlaceholderBitmap(
925 Storage.getPlaceholderForSession(sessionUri));
927 mDataAdapter.updateItemAt(pos, newData);
932 public void onSessionProgress(final Uri uri, final int progress) {
934 // Do nothing, there is no task for this URI.
937 int currentIndex = mFilmstripController.getCurrentAdapterIndex();
938 if (currentIndex == -1) {
942 mDataAdapter.getItemAt(currentIndex).getData().getUri())) {
943 updateSessionProgress(progress);
948 public void onSessionProgressText(final Uri uri, final int messageId) {
949 int currentIndex = mFilmstripController.getCurrentAdapterIndex();
950 if (currentIndex == -1) {
954 mDataAdapter.getItemAt(currentIndex).getData().getUri())) {
955 updateSessionProgressText(messageId);
960 public void onSessionCaptureIndicatorUpdate(Bitmap indicator, int rotationDegrees) {
961 // Don't show capture indicator in Photo Sphere.
962 final int photosphereModuleId = getApplicationContext().getResources()
964 R.integer.camera_mode_photosphere);
965 if (mCurrentModeIndex == photosphereModuleId) {
968 indicateCapture(indicator, rotationDegrees);
972 public void onSessionFailed(Uri uri, int failureMessageId,
973 boolean removeFromFilmstrip) {
974 Log.v(TAG, "onSessionFailed:" + uri);
976 int failedIndex = mDataAdapter.findByContentUri(uri);
977 int currentIndex = mFilmstripController.getCurrentAdapterIndex();
979 if (currentIndex == failedIndex) {
980 updateSessionProgress(0);
981 showProcessError(failureMessageId);
982 mDataAdapter.refresh(uri);
984 if (removeFromFilmstrip) {
985 mFatalErrorHandler.onMediaStorageFailure();
986 mDataAdapter.removeAt(failedIndex);
991 public void onSessionThumbnailUpdate(Bitmap bitmap) {
995 public void onSessionPictureDataUpdate(byte[] pictureData, int orientation) {
1000 public Context getAndroidContext() {
1005 public OneCameraFeatureConfig getCameraFeatureConfig() {
1006 return mFeatureConfig;
1010 public Dialog createDialog() {
1011 return new Dialog(this, android.R.style.Theme_Black_NoTitleBar_Fullscreen);
1015 public void launchActivityByIntent(Intent intent) {
1016 // Starting from L, we prefer not to start edit activity within camera's task.
1017 mResetToPreviewOnResume = false;
1018 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
1020 startActivity(intent);
1024 public int getCurrentModuleIndex() {
1025 return mCurrentModeIndex;
1029 public String getModuleScope() {
1030 ModuleAgent agent = mModuleManager.getModuleAgent(mCurrentModeIndex);
1031 return MODULE_SCOPE_PREFIX + agent.getScopeNamespace();
1035 public String getCameraScope() {
1036 // if an unopen camera i.e. negative ID is returned, which we've observed in
1037 // some automated scenarios, just return it as a valid separate scope
1038 // this could cause user issues, so log a stack trace noting the call path
1039 // which resulted in this scenario.
1041 return CAMERA_SCOPE_PREFIX + mCameraController.getCurrentCameraId().getValue();
1045 public ModuleController getCurrentModuleController() {
1046 return mCurrentModule;
1050 public int getQuickSwitchToModuleId(int currentModuleIndex) {
1051 return mModuleManager.getQuickSwitchToModuleId(currentModuleIndex, mSettingsManager,
1056 public SurfaceTexture getPreviewBuffer() {
1057 // TODO: implement this
1062 public void onPreviewReadyToStart() {
1063 mCameraAppUI.onPreviewReadyToStart();
1067 public void onPreviewStarted() {
1068 mCameraAppUI.onPreviewStarted();
1072 public void addPreviewAreaSizeChangedListener(
1073 PreviewStatusListener.PreviewAreaChangedListener listener) {
1074 mCameraAppUI.addPreviewAreaChangedListener(listener);
1078 public void removePreviewAreaSizeChangedListener(
1079 PreviewStatusListener.PreviewAreaChangedListener listener) {
1080 mCameraAppUI.removePreviewAreaChangedListener(listener);
1084 public void setupOneShotPreviewListener() {
1085 mCameraController.setOneShotPreviewCallback(mMainHandler,
1086 new CameraAgent.CameraPreviewDataCallback() {
1088 public void onPreviewFrame(byte[] data, CameraAgent.CameraProxy camera) {
1089 mCurrentModule.onPreviewInitialDataReceived();
1090 mCameraAppUI.onNewPreviewFrame();
1097 public void updatePreviewAspectRatio(float aspectRatio) {
1098 mCameraAppUI.updatePreviewAspectRatio(aspectRatio);
1102 public void updatePreviewTransformFullscreen(Matrix matrix, float aspectRatio) {
1103 mCameraAppUI.updatePreviewTransformFullscreen(matrix, aspectRatio);
1107 public RectF getFullscreenRect() {
1108 return mCameraAppUI.getFullscreenRect();
1112 public void updatePreviewTransform(Matrix matrix) {
1113 mCameraAppUI.updatePreviewTransform(matrix);
1117 public void setPreviewStatusListener(PreviewStatusListener previewStatusListener) {
1118 mCameraAppUI.setPreviewStatusListener(previewStatusListener);
1122 public FrameLayout getModuleLayoutRoot() {
1123 return mCameraAppUI.getModuleRootView();
1127 public void setShutterEventsListener(ShutterEventsListener listener) {
1128 // TODO: implement this
1132 public void setShutterEnabled(boolean enabled) {
1133 mCameraAppUI.setShutterButtonEnabled(enabled);
1137 public boolean isShutterEnabled() {
1138 return mCameraAppUI.isShutterButtonEnabled();
1142 public void startFlashAnimation(boolean shortFlash) {
1143 mCameraAppUI.startFlashAnimation(shortFlash);
1147 public void startPreCaptureAnimation() {
1148 // TODO: implement this
1152 public void cancelPreCaptureAnimation() {
1153 // TODO: implement this
1157 public void startPostCaptureAnimation() {
1158 // TODO: implement this
1162 public void startPostCaptureAnimation(Bitmap thumbnail) {
1163 // TODO: implement this
1167 public void cancelPostCaptureAnimation() {
1168 // TODO: implement this
1172 public OrientationManager getOrientationManager() {
1173 return mOrientationManager;
1177 public LocationManager getLocationManager() {
1178 return mLocationManager;
1182 public void lockOrientation() {
1183 if (mOrientationManager != null) {
1184 mOrientationManager.lockOrientation();
1189 public void unlockOrientation() {
1190 if (mOrientationManager != null) {
1191 mOrientationManager.unlockOrientation();
1196 * If not in filmstrip, this shows the capture indicator.
1198 private void indicateCapture(final Bitmap indicator, final int rotationDegrees) {
1199 if (mFilmstripVisible) {
1203 // Don't show capture indicator in Photo Sphere.
1204 // TODO: Don't reach into resources to figure out the current mode.
1205 final int photosphereModuleId = getApplicationContext().getResources().getInteger(
1206 R.integer.camera_mode_photosphere);
1207 if (mCurrentModeIndex == photosphereModuleId) {
1211 mMainHandler.post(new Runnable() {
1214 mCameraAppUI.startCaptureIndicatorRevealAnimation(mCurrentModule
1215 .getPeekAccessibilityString());
1216 mCameraAppUI.updateCaptureIndicatorThumbnail(indicator, rotationDegrees);
1222 public void notifyNewMedia(Uri uri) {
1223 // TODO: This method is running on the main thread. Also we should get
1224 // rid of that AsyncTask.
1226 updateStorageSpaceAndHint(null);
1227 ContentResolver cr = getContentResolver();
1228 String mimeType = cr.getType(uri);
1229 FilmstripItem newData = null;
1230 if (FilmstripItemUtils.isMimeTypeVideo(mimeType)) {
1231 sendBroadcast(new Intent(CameraUtil.ACTION_NEW_VIDEO, uri));
1232 newData = mVideoItemFactory.queryContentUri(uri);
1233 if (newData == null) {
1234 Log.e(TAG, "Can't find video data in content resolver:" + uri);
1237 } else if (FilmstripItemUtils.isMimeTypeImage(mimeType)) {
1238 CameraUtil.broadcastNewPicture(mAppContext, uri);
1239 newData = mPhotoItemFactory.queryContentUri(uri);
1240 if (newData == null) {
1241 Log.e(TAG, "Can't find photo data in content resolver:" + uri);
1245 Log.w(TAG, "Unknown new media with MIME type:" + mimeType + ", uri:" + uri);
1249 // We are preloading the metadata for new video since we need the
1250 // rotation info for the thumbnail.
1251 new AsyncTask<FilmstripItem, Void, FilmstripItem>() {
1253 protected FilmstripItem doInBackground(FilmstripItem... params) {
1254 FilmstripItem data = params[0];
1255 MetadataLoader.loadMetadata(getAndroidContext(), data);
1260 protected void onPostExecute(final FilmstripItem data) {
1261 // TODO: Figure out why sometimes the data is aleady there.
1262 mDataAdapter.addOrUpdate(data);
1264 // Legacy modules don't use CaptureSession, so we show the capture indicator when
1265 // the item was safed.
1266 if (mCurrentModule instanceof PhotoModule ||
1267 mCurrentModule instanceof VideoModule) {
1268 AsyncTask.THREAD_POOL_EXECUTOR.execute(new Runnable() {
1271 final Optional<Bitmap> bitmap = data.generateThumbnail(
1272 mAboveFilmstripControlLayout.getWidth(),
1273 mAboveFilmstripControlLayout.getMeasuredHeight());
1274 if (bitmap.isPresent()) {
1275 indicateCapture(bitmap.get(), 0);
1281 }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, newData);
1285 public void enableKeepScreenOn(boolean enabled) {
1290 mKeepScreenOn = enabled;
1291 if (mKeepScreenOn) {
1292 mMainHandler.removeMessages(MSG_CLEAR_SCREEN_ON_FLAG);
1293 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1295 keepScreenOnForAWhile();
1300 public CameraProvider getCameraProvider() {
1301 return mCameraController;
1305 public OneCameraOpener getCameraOpener() {
1306 return mOneCameraOpener;
1309 private void removeItemAt(int index) {
1310 mDataAdapter.removeAt(index);
1311 if (mDataAdapter.getTotalNumber() > 1) {
1312 showUndoDeletionBar();
1314 // If camera preview is the only view left in filmstrip,
1315 // no need to show undo bar.
1316 mPendingDeletion = true;
1318 if (mFilmstripVisible) {
1319 mCameraAppUI.getFilmstripContentPanel().animateHide();
1325 public boolean onOptionsItemSelected(MenuItem item) {
1326 // Handle presses on the action bar items
1327 switch (item.getItemId()) {
1328 case android.R.id.home:
1331 case R.id.action_details:
1332 showDetailsDialog(mFilmstripController.getCurrentAdapterIndex());
1334 case R.id.action_help_and_feedback:
1335 mResetToPreviewOnResume = false;
1336 new GoogleHelpHelper(this).launchGoogleHelp();
1339 return super.onOptionsItemSelected(item);
1343 private boolean isCaptureIntent() {
1344 if (MediaStore.ACTION_VIDEO_CAPTURE.equals(getIntent().getAction())
1345 || MediaStore.ACTION_IMAGE_CAPTURE.equals(getIntent().getAction())
1346 || MediaStore.ACTION_IMAGE_CAPTURE_SECURE.equals(getIntent().getAction())) {
1354 * Note: Make sure this callback is unregistered properly when the activity
1355 * is destroyed since we're otherwise leaking the Activity reference.
1357 private final CameraExceptionHandler.CameraExceptionCallback mCameraExceptionCallback
1358 = new CameraExceptionHandler.CameraExceptionCallback() {
1360 public void onCameraError(int errorCode) {
1361 // Not a fatal error. only do Log.e().
1362 Log.e(TAG, "Camera error callback. error=" + errorCode);
1365 public void onCameraException(
1366 RuntimeException ex, String commandHistory, int action, int state) {
1367 Log.e(TAG, "Camera Exception", ex);
1368 UsageStatistics.instance().cameraFailure(
1369 eventprotos.CameraFailure.FailureReason.API_RUNTIME_EXCEPTION,
1370 commandHistory, action, state);
1374 public void onDispatchThreadException(RuntimeException ex) {
1375 Log.e(TAG, "DispatchThread Exception", ex);
1376 UsageStatistics.instance().cameraFailure(
1377 eventprotos.CameraFailure.FailureReason.API_TIMEOUT,
1378 null, UsageStatistics.NONE, UsageStatistics.NONE);
1381 private void onFatalError() {
1382 if (mCameraFatalError) {
1385 mCameraFatalError = true;
1387 // If the activity receives exception during onPause, just exit the app.
1388 if (mPaused && !isFinishing()) {
1389 Log.e(TAG, "Fatal error during onPause, call Activity.finish()");
1392 mFatalErrorHandler.handleFatalError(FatalErrorHandler.Reason.CANNOT_CONNECT_TO_CAMERA);
1398 public void onNewIntentTasks(Intent intent) {
1399 onModeSelected(getModeIndex());
1403 public void onCreateTasks(Bundle state) {
1404 Profile profile = mProfiler.create("CameraActivity.onCreateTasks").start();
1405 CameraPerformanceTracker.onEvent(CameraPerformanceTracker.ACTIVITY_START);
1406 mOnCreateTime = System.currentTimeMillis();
1407 mAppContext = getApplicationContext();
1408 mMainHandler = new MainHandler(this, getMainLooper());
1409 mLocationManager = new LocationManager(mAppContext);
1410 mOrientationManager = new OrientationManagerImpl(this, mMainHandler);
1411 mSettingsManager = getServices().getSettingsManager();
1412 mSoundPlayer = new SoundPlayer(mAppContext);
1413 mFeatureConfig = OneCameraFeatureConfigCreator.createDefault(getContentResolver(),
1414 getServices().getMemoryManager());
1415 mFatalErrorHandler = new FatalErrorHandlerImpl(this);
1418 if (!Glide.isSetup()) {
1419 Context context = getAndroidContext();
1420 Glide.setup(new GlideBuilder(context)
1421 .setDecodeFormat(DecodeFormat.ALWAYS_ARGB_8888)
1422 .setResizeService(new FifoPriorityThreadPoolExecutor(2)));
1424 Glide glide = Glide.get(context);
1426 // As a camera we will use a large amount of memory
1427 // for displaying images.
1428 glide.setMemoryCategory(MemoryCategory.HIGH);
1430 // Prefill glides bitmap pool to prevent excessive jank
1431 // when loading large images.
1432 glide.preFillBitmapPool(
1433 new PreFillType.Builder(GlideFilmstripManager.MAXIMUM_TEXTURE_SIZE)
1435 // It's more important for jank and GC to have
1436 // A larger weight of max texture size images than
1437 // media store sized images.
1438 new PreFillType.Builder(
1439 GlideFilmstripManager.MEDIASTORE_THUMB_WIDTH,
1440 GlideFilmstripManager.MEDIASTORE_THUMB_HEIGHT));
1442 profile.mark("Glide.setup");
1444 mOneCameraOpener = OneCameraModule.provideOneCameraOpener(
1445 mFeatureConfig, mAppContext, ResolutionUtil.getDisplayMetrics(this));
1446 mOneCameraManager = OneCameraModule.provideOneCameraManager();
1447 } catch (OneCameraException e) {
1448 // Log error and continue start process while showing error dialog..
1449 Log.e(TAG, "Creating camera manager failed.", e);
1450 mFatalErrorHandler.onGenericCameraAccessFailure();
1452 profile.mark("OneCameraManager.get");
1454 mCameraController = new CameraController(mAppContext, this, mMainHandler,
1455 CameraAgentFactory.getAndroidCameraAgent(mAppContext,
1456 CameraAgentFactory.CameraApi.API_1),
1457 CameraAgentFactory.getAndroidCameraAgent(mAppContext,
1458 CameraAgentFactory.CameraApi.AUTO),
1459 ActiveCameraDeviceTracker.instance());
1460 mCameraController.setCameraExceptionHandler(
1461 new CameraExceptionHandler(mCameraExceptionCallback, mMainHandler));
1463 // TODO: Try to move all the resources allocation to happen as soon as
1464 // possible so we can call module.init() at the earliest time.
1465 mModuleManager = new ModuleManagerImpl();
1467 ModulesInfo.setupModules(mAppContext, mModuleManager, mFeatureConfig);
1469 AppUpgrader appUpgrader = new AppUpgrader(this);
1470 appUpgrader.upgrade(mSettingsManager);
1471 Keys.setDefaults(mSettingsManager, mAppContext);
1473 mResolutionSetting = new ResolutionSetting(mSettingsManager, mOneCameraManager,
1474 getContentResolver());
1476 getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
1477 // We suppress this flag via theme when drawing the system preview
1478 // background, but once we create activity here, reactivate to the
1479 // default value. The default is important for L, we don't want to
1480 // change app behavior, just starting background drawable layout.
1481 if (ApiHelper.isLOrHigher()) {
1482 getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
1486 setContentView(R.layout.activity_main);
1487 profile.mark("setContentView()");
1488 // A window background is set in styles.xml for the system to show a
1489 // drawable background with gray color and camera icon before the
1490 // activity is created. We set the background to null here to prevent
1491 // overdraw, all views must take care of drawing backgrounds if
1492 // necessary. This call to setBackgroundDrawable must occur after
1493 // setContentView, otherwise a background may be set again from the
1495 getWindow().setBackgroundDrawable(null);
1497 mActionBar = getActionBar();
1498 // set actionbar background to 100% or 50% transparent
1499 if (ApiHelper.isLOrHigher()) {
1500 mActionBar.setBackgroundDrawable(new ColorDrawable(0x00000000));
1502 mActionBar.setBackgroundDrawable(new ColorDrawable(0x80000000));
1505 mModeListView = (ModeListView) findViewById(R.id.mode_list_layout);
1506 mModeListView.init(mModuleManager.getSupportedModeIndexList());
1507 if (ApiHelper.HAS_ROTATION_ANIMATION) {
1508 setRotationAnimation();
1510 mModeListView.setVisibilityChangedListener(new ModeListVisibilityChangedListener() {
1512 public void onVisibilityChanged(boolean visible) {
1513 mModeListVisible = visible;
1514 mCameraAppUI.setShutterButtonImportantToA11y(!visible);
1515 updatePreviewVisibility();
1519 // Check if this is in the secure camera mode.
1520 Intent intent = getIntent();
1521 String action = intent.getAction();
1522 if (INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE.equals(action)
1523 || ACTION_IMAGE_CAPTURE_SECURE.equals(action)) {
1524 mSecureCamera = true;
1526 mSecureCamera = intent.getBooleanExtra(SECURE_CAMERA_EXTRA, false);
1529 if (mSecureCamera) {
1530 // Change the window flags so that secure camera can show when
1532 Window win = getWindow();
1533 WindowManager.LayoutParams params = win.getAttributes();
1534 params.flags |= WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
1535 win.setAttributes(params);
1537 // Filter for screen off so that we can finish secure camera
1538 // activity when screen is off.
1539 IntentFilter filter_screen_off = new IntentFilter(Intent.ACTION_SCREEN_OFF);
1540 registerReceiver(mShutdownReceiver, filter_screen_off);
1542 // Filter for phone unlock so that we can finish secure camera
1543 // via this UI path:
1544 // 1. from secure lock screen, user starts secure camera
1545 // 2. user presses home button
1546 // 3. user unlocks phone
1547 IntentFilter filter_user_unlock = new IntentFilter(Intent.ACTION_USER_PRESENT);
1548 registerReceiver(mShutdownReceiver, filter_user_unlock);
1550 mCameraAppUI = new CameraAppUI(this,
1551 (MainActivityLayout) findViewById(R.id.activity_root_view), isCaptureIntent());
1553 mCameraAppUI.setFilmstripBottomControlsListener(mMyFilmstripBottomControlListener);
1555 mAboveFilmstripControlLayout =
1556 (FrameLayout) findViewById(R.id.camera_filmstrip_content_layout);
1558 // Add the session listener so we can track the session progress
1560 getServices().getCaptureSessionManager().addSessionListener(mSessionListener);
1561 mFilmstripController = ((FilmstripView) findViewById(R.id.filmstrip_view)).getController();
1562 mFilmstripController.setImageGap(
1563 getResources().getDimensionPixelSize(R.dimen.camera_film_strip_gap));
1564 profile.mark("Configure Camera UI");
1566 mPanoramaViewHelper = new PanoramaViewHelper(this);
1567 mPanoramaViewHelper.onCreate();
1569 ContentResolver appContentResolver = mAppContext.getContentResolver();
1570 GlideFilmstripManager glideManager = new GlideFilmstripManager(mAppContext);
1571 mPhotoItemFactory = new PhotoItemFactory(mAppContext, glideManager, appContentResolver,
1572 new PhotoDataFactory());
1573 mVideoItemFactory = new VideoItemFactory(mAppContext, glideManager, appContentResolver,
1574 new VideoDataFactory());
1575 mDataAdapter = new CameraFilmstripDataAdapter(mAppContext,
1576 mPhotoItemFactory, mVideoItemFactory);
1577 mDataAdapter.setLocalDataListener(mFilmstripItemListener);
1579 mPreloader = new Preloader<Integer, AsyncTask>(FILMSTRIP_PRELOAD_AHEAD_ITEMS, mDataAdapter,
1582 mCameraAppUI.getFilmstripContentPanel().setFilmstripListener(mFilmstripListener);
1583 if (mSettingsManager.getBoolean(SettingsManager.SCOPE_GLOBAL,
1584 Keys.KEY_SHOULD_SHOW_REFOCUS_VIEWER_CLING)) {
1585 mCameraAppUI.setupClingForViewer(CameraAppUI.BottomPanel.VIEWER_REFOCUS);
1588 setModuleFromModeIndex(getModeIndex());
1591 mCameraAppUI.prepareModuleUI();
1592 profile.mark("Init Current Module UI");
1593 mCurrentModule.init(this, isSecureCamera(), isCaptureIntent());
1594 profile.mark("Init CurrentModule");
1596 if (!mSecureCamera) {
1597 mFilmstripController.setDataAdapter(mDataAdapter);
1598 if (!isCaptureIntent()) {
1599 mDataAdapter.requestLoad(new Callback<Void>() {
1601 public void onCallback(Void result) {
1602 fillTemporarySessions();
1607 // Put a lock placeholder as the last image by setting its date to
1609 ImageView v = (ImageView) getLayoutInflater().inflate(
1610 R.layout.secure_album_placeholder, null);
1611 v.setTag(R.id.mediadata_tag_viewtype, FilmstripItemType.SECURE_ALBUM_PLACEHOLDER.ordinal());
1612 v.setOnClickListener(new View.OnClickListener() {
1614 public void onClick(View view) {
1615 UsageStatistics.instance().changeScreen(NavigationChange.Mode.GALLERY,
1616 NavigationChange.InteractionCause.BUTTON);
1621 v.setContentDescription(getString(R.string.accessibility_unlock_to_camera));
1622 mDataAdapter = new FixedLastProxyAdapter(
1625 new PlaceholderItem(
1627 FilmstripItemType.SECURE_ALBUM_PLACEHOLDER,
1628 v.getDrawable().getIntrinsicWidth(),
1629 v.getDrawable().getIntrinsicHeight()));
1630 // Flush out all the original data.
1631 mDataAdapter.clear();
1632 mFilmstripController.setDataAdapter(mDataAdapter);
1637 mLocalImagesObserver = new FilmstripContentObserver();
1638 mLocalVideosObserver = new FilmstripContentObserver();
1640 getContentResolver().registerContentObserver(
1641 MediaStore.Images.Media.EXTERNAL_CONTENT_URI, true,
1642 mLocalImagesObserver);
1643 getContentResolver().registerContentObserver(
1644 MediaStore.Video.Media.EXTERNAL_CONTENT_URI, true,
1645 mLocalVideosObserver);
1647 mMemoryManager = getServices().getMemoryManager();
1649 AsyncTask.THREAD_POOL_EXECUTOR.execute(new Runnable() {
1652 HashMap memoryData = mMemoryManager.queryMemory();
1653 UsageStatistics.instance().reportMemoryConsumed(memoryData,
1654 MemoryQuery.REPORT_LABEL_LAUNCH);
1658 mMotionManager = getServices().getMotionManager();
1660 mFirstRunDialog = new FirstRunDialog(this,
1661 getAndroidContext(),
1665 new FirstRunDialog.FirstRunDialogListener() {
1667 public void onFirstRunStateReady() {
1668 // Run normal resume tasks.
1673 public void onFirstRunDialogCancelled() {
1674 // App isn't functional until users finish first run dialog.
1675 // We need to finish here since users hit back button during
1676 // first run dialog (b/19593942).
1681 public void onCameraAccessException() {
1682 mFatalErrorHandler.onGenericCameraAccessFailure();
1689 * Get the current mode index from the Intent or from persistent
1692 private int getModeIndex() {
1694 int photoIndex = getResources().getInteger(R.integer.camera_mode_photo);
1695 int videoIndex = getResources().getInteger(R.integer.camera_mode_video);
1696 int gcamIndex = getResources().getInteger(R.integer.camera_mode_gcam);
1697 int captureIntentIndex =
1698 getResources().getInteger(R.integer.camera_mode_capture_intent);
1699 String intentAction = getIntent().getAction();
1700 if (MediaStore.INTENT_ACTION_VIDEO_CAMERA.equals(intentAction)
1701 || MediaStore.ACTION_VIDEO_CAPTURE.equals(intentAction)) {
1702 modeIndex = videoIndex;
1703 } else if (MediaStore.ACTION_IMAGE_CAPTURE.equals(intentAction)
1704 || MediaStore.ACTION_IMAGE_CAPTURE_SECURE.equals(intentAction)) {
1706 modeIndex = captureIntentIndex;
1707 } else if (MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA.equals(intentAction)
1708 ||MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE.equals(intentAction)
1709 || MediaStore.ACTION_IMAGE_CAPTURE_SECURE.equals(intentAction)) {
1710 modeIndex = mSettingsManager.getInteger(SettingsManager.SCOPE_GLOBAL,
1711 Keys.KEY_CAMERA_MODULE_LAST_USED);
1713 // For upgraders who have not seen the aspect ratio selection screen,
1714 // we need to drop them back in the photo module and have them select
1716 // TODO: Move this to SettingsManager as an upgrade procedure.
1717 if (!mSettingsManager.getBoolean(SettingsManager.SCOPE_GLOBAL,
1718 Keys.KEY_USER_SELECTED_ASPECT_RATIO)) {
1719 modeIndex = photoIndex;
1722 // If the activity has not been started using an explicit intent,
1723 // read the module index from the last time the user changed modes
1724 modeIndex = mSettingsManager.getInteger(SettingsManager.SCOPE_GLOBAL,
1725 Keys.KEY_STARTUP_MODULE_INDEX);
1726 if ((modeIndex == gcamIndex &&
1727 !GcamHelper.hasGcamAsSeparateModule(mFeatureConfig)) || modeIndex < 0) {
1728 modeIndex = photoIndex;
1735 * Call this whenever the mode drawer or filmstrip change the visibility
1738 private void updatePreviewVisibility() {
1739 if (mCurrentModule == null) {
1743 int visibility = getPreviewVisibility();
1744 mCameraAppUI.onPreviewVisiblityChanged(visibility);
1745 updatePreviewRendering(visibility);
1746 mCurrentModule.onPreviewVisibilityChanged(visibility);
1749 private void updatePreviewRendering(int visibility) {
1750 if (visibility == ModuleController.VISIBILITY_HIDDEN) {
1751 mCameraAppUI.pausePreviewRendering();
1753 mCameraAppUI.resumePreviewRendering();
1757 private int getPreviewVisibility() {
1758 if (mFilmstripCoversPreview) {
1759 return ModuleController.VISIBILITY_HIDDEN;
1760 } else if (mModeListVisible){
1761 return ModuleController.VISIBILITY_COVERED;
1763 return ModuleController.VISIBILITY_VISIBLE;
1767 private void setRotationAnimation() {
1768 int rotationAnimation = WindowManager.LayoutParams.ROTATION_ANIMATION_ROTATE;
1769 rotationAnimation = WindowManager.LayoutParams.ROTATION_ANIMATION_CROSSFADE;
1770 Window win = getWindow();
1771 WindowManager.LayoutParams winParams = win.getAttributes();
1772 winParams.rotationAnimation = rotationAnimation;
1773 win.setAttributes(winParams);
1777 public void onUserInteraction() {
1778 super.onUserInteraction();
1779 if (!isFinishing()) {
1780 keepScreenOnForAWhile();
1785 public boolean dispatchTouchEvent(MotionEvent ev) {
1786 boolean result = super.dispatchTouchEvent(ev);
1787 if (ev.getActionMasked() == MotionEvent.ACTION_DOWN) {
1788 // Real deletion is postponed until the next user interaction after
1789 // the gesture that triggers deletion. Until real deletion is
1790 // performed, users can click the undo button to bring back the
1791 // image that they chose to delete.
1792 if (mPendingDeletion && !mIsUndoingDeletion) {
1800 public void onPauseTasks() {
1801 CameraPerformanceTracker.onEvent(CameraPerformanceTracker.ACTIVITY_PAUSE);
1802 Profile profile = mProfiler.create("CameraActivity.onPause").start();
1805 * Save the last module index after all secure camera and icon launches,
1806 * not just on mode switches.
1808 * Right now we exclude capture intents from this logic, because we also
1809 * ignore the cross-Activity recovery logic in onStart for capture intents.
1811 if (!isCaptureIntent()) {
1812 mSettingsManager.set(SettingsManager.SCOPE_GLOBAL,
1813 Keys.KEY_STARTUP_MODULE_INDEX,
1818 mCameraAppUI.hideCaptureIndicator();
1819 mFirstRunDialog.dismiss();
1821 // Delete photos that are pending deletion
1823 mCurrentModule.pause();
1824 mOrientationManager.pause();
1825 mPanoramaViewHelper.onPause();
1827 mLocalImagesObserver.setForegroundChangeListener(null);
1828 mLocalImagesObserver.setActivityPaused(true);
1829 mLocalVideosObserver.setActivityPaused(true);
1830 mPreloader.cancelAllLoads();
1833 mMotionManager.stop();
1835 // Always stop recording location when paused. Resume will start
1836 // location recording again if the location setting is on.
1837 mLocationManager.recordLocation(false);
1839 UsageStatistics.instance().backgrounded();
1841 // Camera is in fatal state. A fatal dialog is presented to users, but users just hit home
1842 // button. Let's just kill the process.
1843 if (mCameraFatalError && !isFinishing()) {
1844 Log.v(TAG, "onPause when camera is in fatal state, call Activity.finish()");
1847 // Close the camera and wait for the operation done.
1848 Log.v(TAG, "onPause closing camera");
1849 mCameraController.closeCamera(true);
1856 public void onResumeTasks() {
1859 // Show the dialog if necessary. The rest resume logic will be invoked
1860 // at the onFirstRunStateReady() callback.
1861 mFirstRunDialog.showIfNecessary();
1864 private void resume() {
1865 Profile profile = mProfiler.create("CameraActivity.resume").start();
1866 CameraPerformanceTracker.onEvent(CameraPerformanceTracker.ACTIVITY_RESUME);
1867 Log.v(TAG, "Build info: " + Build.DISPLAY);
1869 updateStorageSpaceAndHint(null);
1871 mLastLayoutOrientation = getResources().getConfiguration().orientation;
1873 // TODO: Handle this in OrientationManager.
1875 if (Settings.System.getInt(getContentResolver(),
1876 Settings.System.ACCELEROMETER_ROTATION, 0) == 0) {
1877 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
1878 mAutoRotateScreen = false;
1880 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
1881 mAutoRotateScreen = true;
1884 // Foreground event logging. ACTION_STILL_IMAGE_CAMERA and
1885 // INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE are double logged due to
1886 // lockscreen onResume->onPause->onResume sequence.
1888 String action = getIntent().getAction();
1889 if (action == null) {
1890 source = ForegroundSource.UNKNOWN_SOURCE;
1893 case MediaStore.ACTION_IMAGE_CAPTURE:
1894 source = ForegroundSource.ACTION_IMAGE_CAPTURE;
1896 case MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA:
1897 // was UNKNOWN_SOURCE in Fishlake.
1898 source = ForegroundSource.ACTION_STILL_IMAGE_CAMERA;
1900 case MediaStore.INTENT_ACTION_VIDEO_CAMERA:
1901 // was UNKNOWN_SOURCE in Fishlake.
1902 source = ForegroundSource.ACTION_VIDEO_CAMERA;
1904 case MediaStore.ACTION_VIDEO_CAPTURE:
1905 source = ForegroundSource.ACTION_VIDEO_CAPTURE;
1907 case MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE:
1908 // was ACTION_IMAGE_CAPTURE_SECURE in Fishlake.
1909 source = ForegroundSource.ACTION_STILL_IMAGE_CAMERA_SECURE;
1911 case MediaStore.ACTION_IMAGE_CAPTURE_SECURE:
1912 source = ForegroundSource.ACTION_IMAGE_CAPTURE_SECURE;
1914 case Intent.ACTION_MAIN:
1915 source = ForegroundSource.ACTION_MAIN;
1918 source = ForegroundSource.UNKNOWN_SOURCE;
1922 UsageStatistics.instance().foregrounded(source, currentUserInterfaceMode(),
1923 isKeyguardSecure(), isKeyguardLocked(),
1924 mStartupOnCreate, mExecutionStartNanoTime);
1926 mGalleryIntent = IntentHelper.getGalleryIntent(mAppContext);
1927 if (ApiHelper.isLOrHigher()) {
1928 // hide the up affordance for L devices, it's not very Materially
1929 mActionBar.setDisplayShowHomeEnabled(false);
1932 mOrientationManager.resume();
1934 mCurrentModule.hardResetSettings(mSettingsManager);
1937 mCurrentModule.resume();
1938 UsageStatistics.instance().changeScreen(currentUserInterfaceMode(),
1939 NavigationChange.InteractionCause.BUTTON);
1940 setSwipingEnabled(true);
1941 profile.mark("mCurrentModule.resume");
1943 if (!mResetToPreviewOnResume) {
1944 FilmstripItem item = mDataAdapter.getItemAt(
1945 mFilmstripController.getCurrentAdapterIndex());
1947 mDataAdapter.refresh(item.getData().getUri());
1951 // The share button might be disabled to avoid double tapping.
1952 mCameraAppUI.getFilmstripBottomControls().setShareEnabled(true);
1953 // Default is showing the preview, unless disabled by explicitly
1954 // starting an activity we want to return from to the filmstrip rather
1955 // than the preview.
1956 mResetToPreviewOnResume = true;
1958 if (mLocalVideosObserver.isMediaDataChangedDuringPause()
1959 || mLocalImagesObserver.isMediaDataChangedDuringPause()) {
1960 if (!mSecureCamera) {
1961 // If it's secure camera, requestLoad() should not be called
1962 // as it will load all the data.
1963 if (!mFilmstripVisible) {
1964 mDataAdapter.requestLoad(new Callback<Void>() {
1966 public void onCallback(Void result) {
1967 fillTemporarySessions();
1971 mDataAdapter.requestLoadNewPhotos();
1975 mLocalImagesObserver.setActivityPaused(false);
1976 mLocalVideosObserver.setActivityPaused(false);
1977 if (!mSecureCamera) {
1978 mLocalImagesObserver.setForegroundChangeListener(
1979 new FilmstripContentObserver.ChangeListener() {
1981 public void onChange() {
1982 mDataAdapter.requestLoadNewPhotos();
1987 keepScreenOnForAWhile();
1989 // Lights-out mode at all times.
1990 final View rootView = findViewById(R.id.activity_root_view);
1991 mLightsOutRunnable.run();
1992 getWindow().getDecorView().setOnSystemUiVisibilityChangeListener(
1993 new OnSystemUiVisibilityChangeListener() {
1995 public void onSystemUiVisibilityChange(int visibility) {
1996 mMainHandler.removeCallbacks(mLightsOutRunnable);
1997 mMainHandler.postDelayed(mLightsOutRunnable, LIGHTS_OUT_DELAY_MS);
2002 mPanoramaViewHelper.onResume();
2003 profile.mark("mPanoramaViewHelper.onResume()");
2005 ReleaseHelper.showReleaseInfoDialogOnStart(this, mSettingsManager);
2006 // Enable location recording if the setting is on.
2007 final boolean locationRecordingEnabled =
2008 mSettingsManager.getBoolean(SettingsManager.SCOPE_GLOBAL, Keys.KEY_RECORD_LOCATION);
2009 mLocationManager.recordLocation(locationRecordingEnabled);
2011 final int previewVisibility = getPreviewVisibility();
2012 updatePreviewRendering(previewVisibility);
2014 mMotionManager.start();
2018 private void fillTemporarySessions() {
2019 if (mSecureCamera) {
2022 // There might be sessions still in flight (processed by our service).
2023 // Make sure they're added to the filmstrip.
2024 getServices().getCaptureSessionManager().fillTemporarySession(mSessionListener);
2028 public void onStartTasks() {
2029 mIsActivityRunning = true;
2030 mPanoramaViewHelper.onStart();
2033 * If we're starting after launching a different Activity (lockscreen),
2034 * we need to use the last mode used in the other Activity, and
2035 * not the old one from this Activity.
2037 * This needs to happen before CameraAppUI.resume() in order to set the
2038 * mode cover icon to the actual last mode used.
2040 * Right now we exclude capture intents from this logic.
2042 int modeIndex = getModeIndex();
2043 if (!isCaptureIntent() && mCurrentModeIndex != modeIndex) {
2044 onModeSelected(modeIndex);
2047 if (mResetToPreviewOnResume) {
2048 mCameraAppUI.resume();
2049 mResetToPreviewOnResume = false;
2054 protected void onStopTasks() {
2055 mIsActivityRunning = false;
2056 mPanoramaViewHelper.onStop();
2058 mLocationManager.disconnect();
2062 public void onDestroyTasks() {
2063 if (mSecureCamera) {
2064 unregisterReceiver(mShutdownReceiver);
2067 mSettingsManager.removeAllListeners();
2068 mCameraController.removeCallbackReceiver();
2069 mCameraController.setCameraExceptionHandler(null);
2070 getContentResolver().unregisterContentObserver(mLocalImagesObserver);
2071 getContentResolver().unregisterContentObserver(mLocalVideosObserver);
2072 getServices().getCaptureSessionManager().removeSessionListener(mSessionListener);
2073 mCameraAppUI.onDestroy();
2074 mModeListView.setVisibilityChangedListener(null);
2075 mCameraController = null;
2076 mSettingsManager = null;
2077 mOrientationManager = null;
2078 mButtonManager = null;
2079 mSoundPlayer.release();
2080 CameraAgentFactory.recycle(CameraAgentFactory.CameraApi.API_1);
2081 CameraAgentFactory.recycle(CameraAgentFactory.CameraApi.AUTO);
2085 public void onConfigurationChanged(Configuration config) {
2086 super.onConfigurationChanged(config);
2087 Log.v(TAG, "onConfigurationChanged");
2088 if (config.orientation == Configuration.ORIENTATION_UNDEFINED) {
2092 if (mLastLayoutOrientation != config.orientation) {
2093 mLastLayoutOrientation = config.orientation;
2094 mCurrentModule.onLayoutOrientationChanged(
2095 mLastLayoutOrientation == Configuration.ORIENTATION_LANDSCAPE);
2100 public boolean onKeyDown(int keyCode, KeyEvent event) {
2101 if (!mFilmstripVisible) {
2102 if (mCurrentModule.onKeyDown(keyCode, event)) {
2105 // Prevent software keyboard or voice search from showing up.
2106 if (keyCode == KeyEvent.KEYCODE_SEARCH
2107 || keyCode == KeyEvent.KEYCODE_MENU) {
2108 if (event.isLongPress()) {
2114 return super.onKeyDown(keyCode, event);
2118 public boolean onKeyUp(int keyCode, KeyEvent event) {
2119 if (!mFilmstripVisible) {
2120 // If a module is in the middle of capture, it should
2121 // consume the key event.
2122 if (mCurrentModule.onKeyUp(keyCode, event)) {
2124 } else if (keyCode == KeyEvent.KEYCODE_MENU
2125 || keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
2126 // Let the mode list view consume the event.
2127 mCameraAppUI.openModeList();
2129 } else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
2130 mCameraAppUI.showFilmstrip();
2134 if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
2135 mFilmstripController.goToNextItem();
2137 } else if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
2138 boolean wentToPrevious = mFilmstripController.goToPreviousItem();
2139 if (!wentToPrevious) {
2140 // at beginning of filmstrip, hide and go back to preview
2141 mCameraAppUI.hideFilmstrip();
2146 return super.onKeyUp(keyCode, event);
2150 public void onBackPressed() {
2151 if (!mCameraAppUI.onBackPressed()) {
2152 if (!mCurrentModule.onBackPressed()) {
2153 super.onBackPressed();
2159 public boolean isAutoRotateScreen() {
2160 // TODO: Move to OrientationManager.
2161 return mAutoRotateScreen;
2165 public boolean onCreateOptionsMenu(Menu menu) {
2166 MenuInflater inflater = getMenuInflater();
2167 inflater.inflate(R.menu.filmstrip_menu, menu);
2168 mActionBarMenu = menu;
2170 // add a button for launching the gallery
2171 if (mGalleryIntent != null) {
2172 CharSequence appName = IntentHelper.getGalleryAppName(mAppContext, mGalleryIntent);
2173 if (appName != null) {
2174 MenuItem menuItem = menu.add(appName);
2175 menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
2176 menuItem.setIntent(mGalleryIntent);
2178 Drawable galleryLogo = IntentHelper.getGalleryIcon(mAppContext, mGalleryIntent);
2179 if (galleryLogo != null) {
2180 menuItem.setIcon(galleryLogo);
2185 return super.onCreateOptionsMenu(menu);
2189 public boolean onPrepareOptionsMenu(Menu menu) {
2190 if (isSecureCamera() && !ApiHelper.isLOrHigher()) {
2191 // Compatibility pre-L: launching new activities right above
2192 // lockscreen does not reliably work, only show help if not secure
2193 menu.removeItem(R.id.action_help_and_feedback);
2196 return super.onPrepareOptionsMenu(menu);
2199 protected long getStorageSpaceBytes() {
2200 synchronized (mStorageSpaceLock) {
2201 return mStorageSpaceBytes;
2205 protected interface OnStorageUpdateDoneListener {
2206 public void onStorageUpdateDone(long bytes);
2209 protected void updateStorageSpaceAndHint(final OnStorageUpdateDoneListener callback) {
2211 * We execute disk operations on a background thread in order to
2212 * free up the UI thread. Synchronizing on the lock below ensures
2213 * that when getStorageSpaceBytes is called, the main thread waits
2214 * until this method has completed.
2216 * However, .execute() does not ensure this execution block will be
2217 * run right away (.execute() schedules this AsyncTask for sometime
2218 * in the future. executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)
2219 * tries to execute the task in parellel with other AsyncTasks, but
2220 * there's still no guarantee).
2221 * e.g. don't call this then immediately call getStorageSpaceBytes().
2222 * Instead, pass in an OnStorageUpdateDoneListener.
2224 (new AsyncTask<Void, Void, Long>() {
2226 protected Long doInBackground(Void ... arg) {
2227 synchronized (mStorageSpaceLock) {
2228 mStorageSpaceBytes = Storage.getAvailableSpace();
2229 return mStorageSpaceBytes;
2234 protected void onPostExecute(Long bytes) {
2235 updateStorageHint(bytes);
2236 // This callback returns after I/O to check disk, so we could be
2237 // pausing and shutting down. If so, don't bother invoking.
2238 if (callback != null && !mPaused) {
2239 callback.onStorageUpdateDone(bytes);
2241 Log.v(TAG, "ignoring storage callback after activity pause");
2244 }).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
2247 protected void updateStorageHint(long storageSpace) {
2248 if (!mIsActivityRunning) {
2252 String message = null;
2253 if (storageSpace == Storage.UNAVAILABLE) {
2254 message = getString(R.string.no_storage);
2255 } else if (storageSpace == Storage.PREPARING) {
2256 message = getString(R.string.preparing_sd);
2257 } else if (storageSpace == Storage.UNKNOWN_SIZE) {
2258 message = getString(R.string.access_sd_fail);
2259 } else if (storageSpace <= Storage.LOW_STORAGE_THRESHOLD_BYTES) {
2260 message = getString(R.string.spaceIsLow_content);
2263 if (message != null) {
2264 Log.w(TAG, "Storage warning: " + message);
2265 if (mStorageHint == null) {
2266 mStorageHint = OnScreenHint.makeText(message);
2268 mStorageHint.setText(message);
2270 mStorageHint.show();
2271 UsageStatistics.instance().storageWarning(storageSpace);
2273 // Disable all user interactions,
2274 mCameraAppUI.setDisableAllUserInteractions(true);
2275 } else if (mStorageHint != null) {
2276 mStorageHint.cancel();
2277 mStorageHint = null;
2279 // Re-enable all user interactions.
2280 mCameraAppUI.setDisableAllUserInteractions(false);
2284 protected void setResultEx(int resultCode) {
2285 mResultCodeForTesting = resultCode;
2286 setResult(resultCode);
2289 protected void setResultEx(int resultCode, Intent data) {
2290 mResultCodeForTesting = resultCode;
2291 mResultDataForTesting = data;
2292 setResult(resultCode, data);
2295 public int getResultCode() {
2296 return mResultCodeForTesting;
2299 public Intent getResultData() {
2300 return mResultDataForTesting;
2303 public boolean isSecureCamera() {
2304 return mSecureCamera;
2308 public boolean isPaused() {
2313 public int getPreferredChildModeIndex(int modeIndex) {
2314 if (modeIndex == getResources().getInteger(R.integer.camera_mode_photo)) {
2315 boolean hdrPlusOn = Keys.isHdrPlusOn(mSettingsManager);
2316 if (hdrPlusOn && GcamHelper.hasGcamAsSeparateModule(mFeatureConfig)) {
2317 modeIndex = getResources().getInteger(R.integer.camera_mode_gcam);
2324 public void onModeSelected(int modeIndex) {
2325 if (mCurrentModeIndex == modeIndex) {
2329 CameraPerformanceTracker.onEvent(CameraPerformanceTracker.MODE_SWITCH_START);
2330 // Record last used camera mode for quick switching
2331 if (modeIndex == getResources().getInteger(R.integer.camera_mode_photo)
2332 || modeIndex == getResources().getInteger(R.integer.camera_mode_gcam)) {
2333 mSettingsManager.set(SettingsManager.SCOPE_GLOBAL,
2334 Keys.KEY_CAMERA_MODULE_LAST_USED,
2338 closeModule(mCurrentModule);
2340 // Select the correct module index from the mode switcher index.
2341 modeIndex = getPreferredChildModeIndex(modeIndex);
2342 setModuleFromModeIndex(modeIndex);
2344 mCameraAppUI.resetBottomControls(mCurrentModule, modeIndex);
2345 mCameraAppUI.addShutterListener(mCurrentModule);
2346 openModule(mCurrentModule);
2347 // Store the module index so we can use it the next time the Camera
2349 mSettingsManager.set(SettingsManager.SCOPE_GLOBAL,
2350 Keys.KEY_STARTUP_MODULE_INDEX, modeIndex);
2354 * Shows the settings dialog.
2357 public void onSettingsSelected() {
2358 UsageStatistics.instance().controlUsed(
2359 eventprotos.ControlEvent.ControlType.OVERALL_SETTINGS);
2360 Intent intent = new Intent(this, CameraSettingsActivity.class);
2361 startActivity(intent);
2365 public void freezeScreenUntilPreviewReady() {
2366 mCameraAppUI.freezeScreenUntilPreviewReady();
2370 public int getModuleId(int modeIndex) {
2371 ModuleManagerImpl.ModuleAgent agent = mModuleManager.getModuleAgent(modeIndex);
2372 if (agent == null) {
2375 return agent.getModuleId();
2379 * Sets the mCurrentModuleIndex, creates a new module instance for the given
2380 * index an sets it as mCurrentModule.
2382 private void setModuleFromModeIndex(int modeIndex) {
2383 ModuleManagerImpl.ModuleAgent agent = mModuleManager.getModuleAgent(modeIndex);
2384 if (agent == null) {
2387 if (!agent.requestAppForCamera()) {
2388 mCameraController.closeCamera(true);
2390 mCurrentModeIndex = agent.getModuleId();
2391 mCurrentModule = (CameraModule) agent.createModule(this, getIntent());
2395 public SettingsManager getSettingsManager() {
2396 return mSettingsManager;
2400 public ResolutionSetting getResolutionSetting() {
2401 return mResolutionSetting;
2405 public CameraServices getServices() {
2406 return CameraServicesImpl.instance();
2410 public FatalErrorHandler getFatalErrorHandler() {
2411 return mFatalErrorHandler;
2414 public List<String> getSupportedModeNames() {
2415 List<Integer> indices = mModuleManager.getSupportedModeIndexList();
2416 List<String> supported = new ArrayList<String>();
2418 for (Integer modeIndex : indices) {
2419 String name = CameraUtil.getCameraModeText(modeIndex, mAppContext);
2420 if (name != null && !name.equals("")) {
2421 supported.add(name);
2428 public ButtonManager getButtonManager() {
2429 if (mButtonManager == null) {
2430 mButtonManager = new ButtonManager(this);
2432 return mButtonManager;
2436 public SoundPlayer getSoundPlayer() {
2437 return mSoundPlayer;
2441 * Launches an ACTION_EDIT intent for the given local data item. If
2442 * 'withTinyPlanet' is set, this will show a disambig dialog first to let
2443 * the user start either the tiny planet editor or another photo editor.
2445 * @param data The data item to edit.
2447 public void launchEditor(FilmstripItem data) {
2448 Intent intent = new Intent(Intent.ACTION_EDIT)
2449 .setDataAndType(data.getData().getUri(), data.getData().getMimeType())
2450 .setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
2452 launchActivityByIntent(intent);
2453 } catch (ActivityNotFoundException e) {
2454 final String msgEditWith = getResources().getString(R.string.edit_with);
2455 launchActivityByIntent(Intent.createChooser(intent, msgEditWith));
2460 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
2461 super.onCreateContextMenu(menu, v, menuInfo);
2463 MenuInflater inflater = getMenuInflater();
2464 inflater.inflate(R.menu.filmstrip_context_menu, menu);
2468 public boolean onContextItemSelected(MenuItem item) {
2469 switch (item.getItemId()) {
2470 case R.id.tiny_planet_editor:
2471 mMyFilmstripBottomControlListener.onTinyPlanet();
2473 case R.id.photo_editor:
2474 mMyFilmstripBottomControlListener.onEdit();
2481 * Launch the tiny planet editor.
2483 * @param data The data must be a 360 degree stereographically mapped
2484 * panoramic image. It will not be modified, instead a new item
2485 * with the result will be added to the filmstrip.
2487 public void launchTinyPlanetEditor(FilmstripItem data) {
2488 TinyPlanetFragment fragment = new TinyPlanetFragment();
2489 Bundle bundle = new Bundle();
2490 bundle.putString(TinyPlanetFragment.ARGUMENT_URI, data.getData().getUri().toString());
2491 bundle.putString(TinyPlanetFragment.ARGUMENT_TITLE, data.getData().getTitle());
2492 fragment.setArguments(bundle);
2493 fragment.show(getFragmentManager(), "tiny_planet");
2497 * Returns what UI mode (capture mode or filmstrip) we are in.
2498 * Returned number one of {@link com.google.common.logging.eventprotos.NavigationChange.Mode}
2500 private int currentUserInterfaceMode() {
2501 int mode = NavigationChange.Mode.UNKNOWN_MODE;
2502 if (mCurrentModeIndex == getResources().getInteger(R.integer.camera_mode_photo)) {
2503 mode = NavigationChange.Mode.PHOTO_CAPTURE;
2505 if (mCurrentModeIndex == getResources().getInteger(R.integer.camera_mode_video)) {
2506 mode = NavigationChange.Mode.VIDEO_CAPTURE;
2508 if (mCurrentModeIndex == getResources().getInteger(R.integer.camera_mode_refocus)) {
2509 mode = NavigationChange.Mode.LENS_BLUR;
2511 if (mCurrentModeIndex == getResources().getInteger(R.integer.camera_mode_gcam)) {
2512 mode = NavigationChange.Mode.HDR_PLUS;
2514 if (mCurrentModeIndex == getResources().getInteger(R.integer.camera_mode_photosphere)) {
2515 mode = NavigationChange.Mode.PHOTO_SPHERE;
2517 if (mCurrentModeIndex == getResources().getInteger(R.integer.camera_mode_panorama)) {
2518 mode = NavigationChange.Mode.PANORAMA;
2520 if (mFilmstripVisible) {
2521 mode = NavigationChange.Mode.FILMSTRIP;
2526 private void openModule(CameraModule module) {
2527 module.init(this, isSecureCamera(), isCaptureIntent());
2528 module.hardResetSettings(mSettingsManager);
2529 // Hide accessibility zoom UI by default. Modules will enable it themselves if required.
2530 getCameraAppUI().hideAccessibilityZoomUI();
2533 UsageStatistics.instance().changeScreen(currentUserInterfaceMode(),
2534 NavigationChange.InteractionCause.BUTTON);
2535 updatePreviewVisibility();
2539 private void closeModule(CameraModule module) {
2541 mCameraAppUI.clearModuleUI();
2544 private void performDeletion() {
2545 if (!mPendingDeletion) {
2548 hideUndoDeletionBar(false);
2549 mDataAdapter.executeDeletion();
2552 public void showUndoDeletionBar() {
2553 if (mPendingDeletion) {
2556 Log.v(TAG, "showing undo bar");
2557 mPendingDeletion = true;
2558 if (mUndoDeletionBar == null) {
2559 ViewGroup v = (ViewGroup) getLayoutInflater().inflate(R.layout.undo_bar,
2560 mAboveFilmstripControlLayout, true);
2561 mUndoDeletionBar = (ViewGroup) v.findViewById(R.id.camera_undo_deletion_bar);
2562 View button = mUndoDeletionBar.findViewById(R.id.camera_undo_deletion_button);
2563 button.setOnClickListener(new View.OnClickListener() {
2565 public void onClick(View view) {
2566 mDataAdapter.undoDeletion();
2567 hideUndoDeletionBar(true);
2570 // Setting undo bar clickable to avoid touch events going through
2571 // the bar to the buttons (eg. edit button, etc) underneath the bar.
2572 mUndoDeletionBar.setClickable(true);
2573 // When there is user interaction going on with the undo button, we
2574 // do not want to hide the undo bar.
2575 button.setOnTouchListener(new View.OnTouchListener() {
2577 public boolean onTouch(View v, MotionEvent event) {
2578 if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
2579 mIsUndoingDeletion = true;
2580 } else if (event.getActionMasked() == MotionEvent.ACTION_UP) {
2581 mIsUndoingDeletion = false;
2587 mUndoDeletionBar.setAlpha(0f);
2588 mUndoDeletionBar.setVisibility(View.VISIBLE);
2589 mUndoDeletionBar.animate().setDuration(200).alpha(1f).setListener(null).start();
2592 private void hideUndoDeletionBar(boolean withAnimation) {
2593 Log.v(TAG, "Hiding undo deletion bar");
2594 mPendingDeletion = false;
2595 if (mUndoDeletionBar != null) {
2596 if (withAnimation) {
2597 mUndoDeletionBar.animate().setDuration(200).alpha(0f)
2598 .setListener(new Animator.AnimatorListener() {
2600 public void onAnimationStart(Animator animation) {
2605 public void onAnimationEnd(Animator animation) {
2606 mUndoDeletionBar.setVisibility(View.GONE);
2610 public void onAnimationCancel(Animator animation) {
2615 public void onAnimationRepeat(Animator animation) {
2620 mUndoDeletionBar.setVisibility(View.GONE);
2626 * Enable/disable swipe-to-filmstrip. Will always disable swipe if in
2629 * @param enable {@code true} to enable swipe.
2631 public void setSwipingEnabled(boolean enable) {
2632 // TODO: Bring back the functionality.
2633 if (isCaptureIntent()) {
2634 // lockPreview(true);
2636 // lockPreview(!enable);
2640 // Accessor methods for getting latency times used in performance testing
2641 public long getFirstPreviewTime() {
2642 if (mCurrentModule instanceof PhotoModule) {
2643 long coverHiddenTime = getCameraAppUI().getCoverHiddenTime();
2644 if (coverHiddenTime != -1) {
2645 return coverHiddenTime - mOnCreateTime;
2651 public long getAutoFocusTime() {
2652 return (mCurrentModule instanceof PhotoModule) ?
2653 ((PhotoModule) mCurrentModule).mAutoFocusTime : -1;
2656 public long getShutterLag() {
2657 return (mCurrentModule instanceof PhotoModule) ?
2658 ((PhotoModule) mCurrentModule).mShutterLag : -1;
2661 public long getShutterToPictureDisplayedTime() {
2662 return (mCurrentModule instanceof PhotoModule) ?
2663 ((PhotoModule) mCurrentModule).mShutterToPictureDisplayedTime : -1;
2666 public long getPictureDisplayedToJpegCallbackTime() {
2667 return (mCurrentModule instanceof PhotoModule) ?
2668 ((PhotoModule) mCurrentModule).mPictureDisplayedToJpegCallbackTime : -1;
2671 public long getJpegCallbackFinishTime() {
2672 return (mCurrentModule instanceof PhotoModule) ?
2673 ((PhotoModule) mCurrentModule).mJpegCallbackFinishTime : -1;
2676 public long getCaptureStartTime() {
2677 return (mCurrentModule instanceof PhotoModule) ?
2678 ((PhotoModule) mCurrentModule).mCaptureStartTime : -1;
2681 public boolean isRecording() {
2682 return (mCurrentModule instanceof VideoModule) ?
2683 ((VideoModule) mCurrentModule).isRecording() : false;
2686 public CameraAgent.CameraOpenCallback getCameraOpenErrorCallback() {
2687 return mCameraController;
2690 // For debugging purposes only.
2691 public CameraModule getCurrentModule() {
2692 return mCurrentModule;
2696 public void showTutorial(AbstractTutorialOverlay tutorial) {
2697 mCameraAppUI.showTutorial(tutorial, getLayoutInflater());
2701 public void finishActivityWithIntentCompleted(Intent resultIntent) {
2702 finishActivityWithIntentResult(Activity.RESULT_OK, resultIntent);
2706 public void finishActivityWithIntentCanceled() {
2707 finishActivityWithIntentResult(Activity.RESULT_CANCELED, new Intent());
2710 private void finishActivityWithIntentResult(int resultCode, Intent resultIntent) {
2711 mResultCodeForTesting = resultCode;
2712 mResultDataForTesting = resultIntent;
2713 setResult(resultCode, resultIntent);
2717 private void keepScreenOnForAWhile() {
2718 if (mKeepScreenOn) {
2721 mMainHandler.removeMessages(MSG_CLEAR_SCREEN_ON_FLAG);
2722 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
2723 mMainHandler.sendEmptyMessageDelayed(MSG_CLEAR_SCREEN_ON_FLAG, SCREEN_DELAY_MS);
2726 private void resetScreenOn() {
2727 mKeepScreenOn = false;
2728 mMainHandler.removeMessages(MSG_CLEAR_SCREEN_ON_FLAG);
2729 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
2733 * @return {@code true} if the Gallery is launched successfully.
2735 private boolean startGallery() {
2736 if (mGalleryIntent == null) {
2740 UsageStatistics.instance().changeScreen(NavigationChange.Mode.GALLERY,
2741 NavigationChange.InteractionCause.BUTTON);
2742 Intent startGalleryIntent = new Intent(mGalleryIntent);
2743 int currentIndex = mFilmstripController.getCurrentAdapterIndex();
2744 FilmstripItem currentFilmstripItem = mDataAdapter.getItemAt(currentIndex);
2745 if (currentFilmstripItem != null) {
2746 GalleryHelper.setContentUri(startGalleryIntent,
2747 currentFilmstripItem.getData().getUri());
2749 launchActivityByIntent(startGalleryIntent);
2750 } catch (ActivityNotFoundException e) {
2751 Log.w(TAG, "Failed to launch gallery activity, closing");
2756 private void setNfcBeamPushUriFromData(FilmstripItem data) {
2757 final Uri uri = data.getData().getUri();
2758 if (uri != Uri.EMPTY) {
2759 mNfcPushUris[0] = uri;
2761 mNfcPushUris[0] = null;
2766 * Updates the visibility of the filmstrip bottom controls and action bar.
2768 private void updateUiByData(final int index) {
2769 final FilmstripItem currentData = mDataAdapter.getItemAt(index);
2770 if (currentData == null) {
2771 Log.w(TAG, "Current data ID not found.");
2772 hideSessionProgress();
2775 updateActionBarMenu(currentData);
2777 /* Bottom controls. */
2778 updateBottomControlsByData(currentData);
2780 if (isSecureCamera()) {
2781 // We cannot show buttons in secure camera since go to other
2782 // activities might create a security hole.
2783 mCameraAppUI.getFilmstripBottomControls().hideControls();
2787 setNfcBeamPushUriFromData(currentData);
2789 if (!mDataAdapter.isMetadataUpdatedAt(index)) {
2790 mDataAdapter.updateMetadataAt(index);
2795 * Updates the bottom controls based on the data.
2797 private void updateBottomControlsByData(final FilmstripItem currentData) {
2799 final CameraAppUI.BottomPanel filmstripBottomPanel =
2800 mCameraAppUI.getFilmstripBottomControls();
2801 filmstripBottomPanel.showControls();
2802 filmstripBottomPanel.setEditButtonVisibility(
2803 currentData.getAttributes().canEdit());
2804 filmstripBottomPanel.setShareButtonVisibility(
2805 currentData.getAttributes().canShare());
2806 filmstripBottomPanel.setDeleteButtonVisibility(
2807 currentData.getAttributes().canDelete());
2811 Uri contentUri = currentData.getData().getUri();
2812 CaptureSessionManager sessionManager = getServices()
2813 .getCaptureSessionManager();
2815 if (sessionManager.hasErrorMessage(contentUri)) {
2816 showProcessError(sessionManager.getErrorMessageId(contentUri));
2818 filmstripBottomPanel.hideProgressError();
2819 CaptureSession session = sessionManager.getSession(contentUri);
2821 if (session != null) {
2822 int sessionProgress = session.getProgress();
2824 if (sessionProgress < 0) {
2825 hideSessionProgress();
2827 int progressMessageId = session.getProgressMessageId();
2828 showSessionProgress(progressMessageId);
2829 updateSessionProgress(sessionProgress);
2832 hideSessionProgress();
2838 // We need to add this to a separate DB.
2839 final int viewButtonVisibility;
2840 if (currentData.getMetadata().isUsePanoramaViewer()) {
2841 viewButtonVisibility = CameraAppUI.BottomPanel.VIEWER_PHOTO_SPHERE;
2842 } else if (currentData.getMetadata().isHasRgbzData()) {
2843 viewButtonVisibility = CameraAppUI.BottomPanel.VIEWER_REFOCUS;
2845 viewButtonVisibility = CameraAppUI.BottomPanel.VIEWER_NONE;
2848 filmstripBottomPanel.setTinyPlanetEnabled(
2849 currentData.getMetadata().isPanorama360());
2850 filmstripBottomPanel.setViewerButtonVisibility(viewButtonVisibility);
2853 private void showDetailsDialog(int index) {
2854 final FilmstripItem data = mDataAdapter.getItemAt(index);
2858 Optional<MediaDetails> details = data.getMediaDetails();
2859 if (!details.isPresent()) {
2862 Dialog detailDialog = DetailsDialog.create(CameraActivity.this, details.get());
2863 detailDialog.show();
2864 UsageStatistics.instance().mediaInteraction(
2865 fileNameFromAdapterAtIndex(index), MediaInteraction.InteractionType.DETAILS,
2866 NavigationChange.InteractionCause.BUTTON, fileAgeFromAdapterAtIndex(index));
2870 * Show or hide action bar items depending on current data type.
2872 private void updateActionBarMenu(FilmstripItem data) {
2873 if (mActionBarMenu == null) {
2877 MenuItem detailsMenuItem = mActionBarMenu.findItem(R.id.action_details);
2878 if (detailsMenuItem == null) {
2882 boolean showDetails = data.getAttributes().hasDetailedCaptureInfo();
2883 detailsMenuItem.setVisible(showDetails);