Camera.java revision 94ca8baae7e6e3885d895c095890eabf30d922e2
1/*
2 * Copyright (C) 2007 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 com.android.camera.ui.CameraPicker;
20import com.android.camera.ui.FaceView;
21import com.android.camera.ui.IndicatorControlContainer;
22import com.android.camera.ui.Rotatable;
23import com.android.camera.ui.RotateImageView;
24import com.android.camera.ui.RotateLayout;
25import com.android.camera.ui.SharePopup;
26import com.android.camera.ui.ZoomControl;
27
28import android.app.Activity;
29import android.content.BroadcastReceiver;
30import android.content.ContentProviderClient;
31import android.content.ContentResolver;
32import android.content.Context;
33import android.content.Intent;
34import android.content.IntentFilter;
35import android.content.SharedPreferences.Editor;
36import android.graphics.Bitmap;
37import android.hardware.Camera.CameraInfo;
38import android.hardware.Camera.Face;
39import android.hardware.Camera.FaceDetectionListener;
40import android.hardware.Camera.Parameters;
41import android.hardware.Camera.PictureCallback;
42import android.hardware.Camera.Size;
43import android.location.Location;
44import android.media.CameraProfile;
45import android.net.Uri;
46import android.os.Bundle;
47import android.os.Handler;
48import android.os.Looper;
49import android.os.Message;
50import android.os.MessageQueue;
51import android.os.SystemClock;
52import android.provider.MediaStore;
53import android.util.Log;
54import android.view.GestureDetector;
55import android.view.Gravity;
56import android.view.KeyEvent;
57import android.view.Menu;
58import android.view.MenuItem;
59import android.view.MenuItem.OnMenuItemClickListener;
60import android.view.MotionEvent;
61import android.view.OrientationEventListener;
62import android.view.SurfaceHolder;
63import android.view.SurfaceView;
64import android.view.View;
65import android.view.WindowManager;
66import android.view.animation.AnimationUtils;
67import android.widget.TextView;
68import android.widget.Toast;
69
70import java.io.File;
71import java.io.FileNotFoundException;
72import java.io.FileOutputStream;
73import java.io.IOException;
74import java.io.OutputStream;
75import java.util.ArrayList;
76import java.util.Collections;
77import java.util.Formatter;
78import java.util.List;
79import java.util.concurrent.atomic.AtomicReference;
80
81/** The Camera activity which can preview and take pictures. */
82public class Camera extends ActivityBase implements FocusManager.Listener,
83        View.OnTouchListener, ShutterButton.OnShutterButtonListener,
84        SurfaceHolder.Callback, ModePicker.OnModeChangeListener,
85        FaceDetectionListener, CameraPreference.OnPreferenceChangedListener,
86        LocationManager.Listener {
87
88    private static final String TAG = "camera";
89
90    private static final int CROP_MSG = 1;
91    private static final int FIRST_TIME_INIT = 2;
92    private static final int CLEAR_SCREEN_DELAY = 3;
93    private static final int SET_CAMERA_PARAMETERS_WHEN_IDLE = 4;
94    private static final int CHECK_DISPLAY_ROTATION = 5;
95    private static final int SHOW_TAP_TO_FOCUS_TOAST = 6;
96    private static final int DISMISS_TAP_TO_FOCUS_TOAST = 7;
97    private static final int UPDATE_THUMBNAIL = 8;
98
99    // The subset of parameters we need to update in setCameraParameters().
100    private static final int UPDATE_PARAM_INITIALIZE = 1;
101    private static final int UPDATE_PARAM_ZOOM = 2;
102    private static final int UPDATE_PARAM_PREFERENCE = 4;
103    private static final int UPDATE_PARAM_ALL = -1;
104
105    // When setCameraParametersWhenIdle() is called, we accumulate the subsets
106    // needed to be updated in mUpdateSet.
107    private int mUpdateSet;
108
109    private static final int SCREEN_DELAY = 2 * 60 * 1000;
110
111    private static final int ZOOM_STOPPED = 0;
112    private static final int ZOOM_START = 1;
113    private static final int ZOOM_STOPPING = 2;
114
115    private int mZoomState = ZOOM_STOPPED;
116    private boolean mSmoothZoomSupported = false;
117    private int mZoomValue;  // The current zoom value.
118    private int mZoomMax;
119    private int mTargetZoomValue;
120    private ZoomControl mZoomControl;
121
122    private Parameters mParameters;
123    private Parameters mInitialParams;
124    private boolean mFocusAreaSupported;
125    private boolean mMeteringAreaSupported;
126
127    private MyOrientationEventListener mOrientationListener;
128    // The degrees of the device rotated clockwise from its natural orientation.
129    private int mOrientation = OrientationEventListener.ORIENTATION_UNKNOWN;
130    // The orientation compensation for icons and thumbnails. Ex: if the value
131    // is 90, the UI components should be rotated 90 degrees counter-clockwise.
132    private int mOrientationCompensation = 0;
133    private ComboPreferences mPreferences;
134
135    private static final String sTempCropFilename = "crop-temp";
136
137    private android.hardware.Camera mCameraDevice;
138    private ContentProviderClient mMediaProviderClient;
139    private SurfaceHolder mSurfaceHolder = null;
140    private ShutterButton mShutterButton;
141    private GestureDetector mPopupGestureDetector;
142    private boolean mOpenCameraFail = false;
143    private boolean mCameraDisabled = false;
144
145    private View mPreviewPanel;  // The container of PreviewFrameLayout.
146    private PreviewFrameLayout mPreviewFrameLayout;
147    private View mPreviewFrame;  // Preview frame area.
148
149    // A popup window that contains a bigger thumbnail and a list of apps to share.
150    private SharePopup mSharePopup;
151    // The bitmap of the last captured picture thumbnail and the URI of the
152    // original picture.
153    private Thumbnail mThumbnail;
154    // An imageview showing showing the last captured picture thumbnail.
155    private RotateImageView mThumbnailView;
156    private ModePicker mModePicker;
157    private FaceView mFaceView;
158    private RotateLayout mFocusIndicator;
159    private Rotatable mReviewCancelButton;
160    private Rotatable mReviewDoneButton;
161
162    // mCropValue and mSaveUri are used only if isImageCaptureIntent() is true.
163    private String mCropValue;
164    private Uri mSaveUri;
165
166    // On-screen indicator
167    private View mGpsNoSignalIndicator;
168    private View mGpsHasSignalIndicator;
169    private TextView mExposureIndicator;
170
171    // We put the work of saving images and generating thumbnails to the thread
172    // in ImageSaver.
173    private ImageSaver mImageSaver;
174
175    private final StringBuilder mBuilder = new StringBuilder();
176    private final Formatter mFormatter = new Formatter(mBuilder);
177    private final Object[] mFormatterArgs = new Object[1];
178
179    /**
180     * An unpublished intent flag requesting to return as soon as capturing
181     * is completed.
182     *
183     * TODO: consider publishing by moving into MediaStore.
184     */
185    private final static String EXTRA_QUICK_CAPTURE =
186            "android.intent.extra.quickCapture";
187
188    // The display rotation in degrees. This is only valid when mCameraState is
189    // not PREVIEW_STOPPED.
190    private int mDisplayRotation;
191    // The value for android.hardware.Camera.setDisplayOrientation.
192    private int mDisplayOrientation;
193    private boolean mPausing;
194    private boolean mFirstTimeInitialized;
195    private boolean mIsImageCaptureIntent;
196
197    private static final int PREVIEW_STOPPED = 0;
198    private static final int IDLE = 1;  // preview is active
199    // Focus is in progress. The exact focus state is in Focus.java.
200    private static final int FOCUSING = 2;
201    private static final int SNAPSHOT_IN_PROGRESS = 3;
202    private int mCameraState = PREVIEW_STOPPED;
203
204    private ContentResolver mContentResolver;
205    private boolean mDidRegister = false;
206
207    private LocationManager mLocationManager;
208
209    private final ShutterCallback mShutterCallback = new ShutterCallback();
210    private final PostViewPictureCallback mPostViewPictureCallback =
211            new PostViewPictureCallback();
212    private final RawPictureCallback mRawPictureCallback =
213            new RawPictureCallback();
214    private final AutoFocusCallback mAutoFocusCallback =
215            new AutoFocusCallback();
216    private final ZoomListener mZoomListener = new ZoomListener();
217    private final CameraErrorCallback mErrorCallback = new CameraErrorCallback();
218
219    private long mFocusStartTime;
220    private long mCaptureStartTime;
221    private long mShutterCallbackTime;
222    private long mPostViewPictureCallbackTime;
223    private long mRawPictureCallbackTime;
224    private long mJpegPictureCallbackTime;
225    private long mOnResumeTime;
226    private long mPicturesRemaining;
227    private byte[] mJpegImageData;
228
229    // These latency time are for the CameraLatency test.
230    public long mAutoFocusTime;
231    public long mShutterLag;
232    public long mShutterToPictureDisplayedTime;
233    public long mPictureDisplayedToJpegCallbackTime;
234    public long mJpegCallbackFinishTime;
235
236    // This handles everything about focus.
237    private FocusManager mFocusManager;
238    private String mSceneMode;
239    private Toast mNotSelectableToast;
240    private Toast mNoShareToast;
241
242    private final Handler mHandler = new MainHandler();
243    private IndicatorControlContainer mIndicatorControlContainer;
244    private PreferenceGroup mPreferenceGroup;
245
246    // multiple cameras support
247    private int mNumberOfCameras;
248    private int mCameraId;
249    private int mFrontCameraId;
250    private int mBackCameraId;
251
252    private boolean mQuickCapture;
253
254    /**
255     * This Handler is used to post message back onto the main thread of the
256     * application
257     */
258    private class MainHandler extends Handler {
259        @Override
260        public void handleMessage(Message msg) {
261            switch (msg.what) {
262                case CLEAR_SCREEN_DELAY: {
263                    getWindow().clearFlags(
264                            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
265                    break;
266                }
267
268                case FIRST_TIME_INIT: {
269                    initializeFirstTime();
270                    break;
271                }
272
273                case SET_CAMERA_PARAMETERS_WHEN_IDLE: {
274                    setCameraParametersWhenIdle(0);
275                    break;
276                }
277
278                case CHECK_DISPLAY_ROTATION: {
279                    // Restart the preview if display rotation has changed.
280                    // Sometimes this happens when the device is held upside
281                    // down and camera app is opened. Rotation animation will
282                    // take some time and the rotation value we have got may be
283                    // wrong. Framework does not have a callback for this now.
284                    if (Util.getDisplayRotation(Camera.this) != mDisplayRotation
285                            && isCameraIdle()) {
286                        startPreview();
287                    }
288                    if (SystemClock.uptimeMillis() - mOnResumeTime < 5000) {
289                        mHandler.sendEmptyMessageDelayed(CHECK_DISPLAY_ROTATION, 100);
290                    }
291                    break;
292                }
293
294                case SHOW_TAP_TO_FOCUS_TOAST: {
295                    showTapToFocusToast();
296                    break;
297                }
298
299                case DISMISS_TAP_TO_FOCUS_TOAST: {
300                    View v = findViewById(R.id.tap_to_focus_prompt);
301                    v.setVisibility(View.GONE);
302                    v.setAnimation(AnimationUtils.loadAnimation(Camera.this,
303                            R.anim.on_screen_hint_exit));
304                    break;
305                }
306
307                case UPDATE_THUMBNAIL: {
308                    mImageSaver.updateThumbnail();
309                    break;
310                }
311            }
312        }
313    }
314
315    private void resetExposureCompensation() {
316        String value = mPreferences.getString(CameraSettings.KEY_EXPOSURE,
317                CameraSettings.EXPOSURE_DEFAULT_VALUE);
318        if (!CameraSettings.EXPOSURE_DEFAULT_VALUE.equals(value)) {
319            Editor editor = mPreferences.edit();
320            editor.putString(CameraSettings.KEY_EXPOSURE, "0");
321            editor.apply();
322            if (mIndicatorControlContainer != null) {
323                mIndicatorControlContainer.reloadPreferences();
324            }
325        }
326    }
327
328    private void keepMediaProviderInstance() {
329        // We want to keep a reference to MediaProvider in camera's lifecycle.
330        // TODO: Utilize mMediaProviderClient instance to replace
331        // ContentResolver calls.
332        if (mMediaProviderClient == null) {
333            mMediaProviderClient = getContentResolver()
334                    .acquireContentProviderClient(MediaStore.AUTHORITY);
335        }
336    }
337
338    // Snapshots can only be taken after this is called. It should be called
339    // once only. We could have done these things in onCreate() but we want to
340    // make preview screen appear as soon as possible.
341    private void initializeFirstTime() {
342        if (mFirstTimeInitialized) return;
343
344        // Create orientation listenter. This should be done first because it
345        // takes some time to get first orientation.
346        mOrientationListener = new MyOrientationEventListener(Camera.this);
347        mOrientationListener.enable();
348
349        // Initialize location sevice.
350        boolean recordLocation = RecordLocationPreference.get(
351                mPreferences, getContentResolver());
352        initOnScreenIndicator();
353        mLocationManager.recordLocation(recordLocation);
354
355        keepMediaProviderInstance();
356        checkStorage();
357
358        // Initialize last picture button.
359        mContentResolver = getContentResolver();
360        if (!mIsImageCaptureIntent) {  // no thumbnail in image capture intent
361            initThumbnailButton();
362        }
363
364        // Initialize shutter button.
365        mShutterButton = (ShutterButton) findViewById(R.id.shutter_button);
366        mShutterButton.setOnShutterButtonListener(this);
367        mShutterButton.setVisibility(View.VISIBLE);
368
369        // Initialize focus UI.
370        mPreviewFrame = findViewById(R.id.camera_preview);
371        mPreviewFrame.setOnTouchListener(this);
372        mFocusIndicator = (RotateLayout) findViewById(R.id.focus_indicator_rotate_layout);
373        mFocusManager.initialize(mFocusIndicator, mPreviewFrame, mFaceView, this);
374        mFocusManager.initializeSoundPlayer(getResources().openRawResourceFd(R.raw.camera_focus));
375        mImageSaver = new ImageSaver();
376        Util.initializeScreenBrightness(getWindow(), getContentResolver());
377        installIntentFilter();
378        initializeZoom();
379        // Show the tap to focus toast if this is the first start.
380        if (mFocusAreaSupported &&
381                mPreferences.getBoolean(CameraSettings.KEY_TAP_TO_FOCUS_PROMPT_SHOWN, true)) {
382            // Delay the toast for one second to wait for orientation.
383            mHandler.sendEmptyMessageDelayed(SHOW_TAP_TO_FOCUS_TOAST, 1000);
384        }
385
386        mFirstTimeInitialized = true;
387        addIdleHandler();
388    }
389
390    private void addIdleHandler() {
391        MessageQueue queue = Looper.myQueue();
392        queue.addIdleHandler(new MessageQueue.IdleHandler() {
393            public boolean queueIdle() {
394                Storage.ensureOSXCompatible();
395                return false;
396            }
397        });
398    }
399
400    private void initThumbnailButton() {
401        // Load the thumbnail from the disk.
402        mThumbnail = Thumbnail.loadFrom(new File(getFilesDir(), Thumbnail.LAST_THUMB_FILENAME));
403        updateThumbnailButton();
404    }
405
406    private void updateThumbnailButton() {
407        // Update last image if URI is invalid and the storage is ready.
408        if ((mThumbnail == null || !Util.isUriValid(mThumbnail.getUri(), mContentResolver))
409                && mPicturesRemaining >= 0) {
410            mThumbnail = Thumbnail.getLastThumbnail(mContentResolver);
411        }
412        if (mThumbnail != null) {
413            mThumbnailView.setBitmap(mThumbnail.getBitmap());
414        } else {
415            mThumbnailView.setBitmap(null);
416        }
417    }
418
419    // If the activity is paused and resumed, this method will be called in
420    // onResume.
421    private void initializeSecondTime() {
422        // Start orientation listener as soon as possible because it takes
423        // some time to get first orientation.
424        mOrientationListener.enable();
425
426        // Start location update if needed.
427        boolean recordLocation = RecordLocationPreference.get(
428                mPreferences, getContentResolver());
429        mLocationManager.recordLocation(recordLocation);
430
431        installIntentFilter();
432        mFocusManager.initializeSoundPlayer(getResources().openRawResourceFd(R.raw.camera_focus));
433        mImageSaver = new ImageSaver();
434        initializeZoom();
435        keepMediaProviderInstance();
436        checkStorage();
437        hidePostCaptureAlert();
438
439        if (!mIsImageCaptureIntent) {
440            updateThumbnailButton();
441            mModePicker.setCurrentMode(ModePicker.MODE_CAMERA);
442        }
443    }
444
445    private class ZoomChangeListener implements ZoomControl.OnZoomChangedListener {
446        // only for immediate zoom
447        @Override
448        public void onZoomValueChanged(int index) {
449            Camera.this.onZoomValueChanged(index);
450        }
451
452        // only for smooth zoom
453        @Override
454        public void onZoomStateChanged(int state) {
455            if (mPausing) return;
456
457            Log.v(TAG, "zoom picker state=" + state);
458            if (state == ZoomControl.ZOOM_IN) {
459                Camera.this.onZoomValueChanged(mZoomMax);
460            } else if (state == ZoomControl.ZOOM_OUT) {
461                Camera.this.onZoomValueChanged(0);
462            } else {
463                mTargetZoomValue = -1;
464                if (mZoomState == ZOOM_START) {
465                    mZoomState = ZOOM_STOPPING;
466                    mCameraDevice.stopSmoothZoom();
467                }
468            }
469        }
470    }
471
472    private void initializeZoom() {
473        // Get the parameter to make sure we have the up-to-date zoom value.
474        mParameters = mCameraDevice.getParameters();
475        if (!mParameters.isZoomSupported()) return;
476        mZoomMax = mParameters.getMaxZoom();
477        // Currently we use immediate zoom for fast zooming to get better UX and
478        // there is no plan to take advantage of the smooth zoom.
479        mZoomControl.setZoomMax(mZoomMax);
480        mZoomControl.setZoomIndex(mParameters.getZoom());
481        mZoomControl.setSmoothZoomSupported(mSmoothZoomSupported);
482        mZoomControl.setOnZoomChangeListener(new ZoomChangeListener());
483        mCameraDevice.setZoomChangeListener(mZoomListener);
484    }
485
486    private void onZoomValueChanged(int index) {
487        // Not useful to change zoom value when the activity is paused.
488        if (mPausing) return;
489
490        if (mSmoothZoomSupported) {
491            if (mTargetZoomValue != index && mZoomState != ZOOM_STOPPED) {
492                mTargetZoomValue = index;
493                if (mZoomState == ZOOM_START) {
494                    mZoomState = ZOOM_STOPPING;
495                    mCameraDevice.stopSmoothZoom();
496                }
497            } else if (mZoomState == ZOOM_STOPPED && mZoomValue != index) {
498                mTargetZoomValue = index;
499                mCameraDevice.startSmoothZoom(index);
500                mZoomState = ZOOM_START;
501            }
502        } else {
503            mZoomValue = index;
504            setCameraParametersWhenIdle(UPDATE_PARAM_ZOOM);
505        }
506    }
507
508    @Override
509    public void startFaceDetection() {
510        if (mParameters.getMaxNumDetectedFaces() > 0) {
511            mFaceView = (FaceView) findViewById(R.id.face_view);
512            mFaceView.clear();
513            mFaceView.setVisibility(View.VISIBLE);
514            mFaceView.setDisplayOrientation(mDisplayOrientation);
515            CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId];
516            mFaceView.setMirror(info.facing == CameraInfo.CAMERA_FACING_FRONT);
517            mFaceView.resume();
518            mCameraDevice.setFaceDetectionListener(this);
519            mCameraDevice.startFaceDetection();
520        }
521    }
522
523    @Override
524    public void stopFaceDetection() {
525        if (mParameters.getMaxNumDetectedFaces() > 0) {
526            mCameraDevice.setFaceDetectionListener(null);
527            mCameraDevice.stopFaceDetection();
528            if (mFaceView != null) mFaceView.clear();
529        }
530    }
531
532    private class PopupGestureListener
533            extends GestureDetector.SimpleOnGestureListener {
534        @Override
535        public boolean onDown(MotionEvent e) {
536            // Check if the popup window is visible.
537            View popup = mIndicatorControlContainer.getActiveSettingPopup();
538            if (popup == null) return false;
539
540
541            // Let popup window, indicator control or preview frame handle the
542            // event by themselves. Dismiss the popup window if users touch on
543            // other areas.
544            if (!Util.pointInView(e.getX(), e.getY(), popup)
545                    && !Util.pointInView(e.getX(), e.getY(), mIndicatorControlContainer)
546                    && !Util.pointInView(e.getX(), e.getY(), mPreviewFrame)) {
547                mIndicatorControlContainer.dismissSettingPopup();
548                // Let event fall through.
549            }
550            return false;
551        }
552    }
553
554    @Override
555    public boolean dispatchTouchEvent(MotionEvent m) {
556        // Check if the popup window should be dismissed first.
557        if (mPopupGestureDetector != null && mPopupGestureDetector.onTouchEvent(m)) {
558            return true;
559        }
560
561        return super.dispatchTouchEvent(m);
562    }
563
564    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
565        @Override
566        public void onReceive(Context context, Intent intent) {
567            String action = intent.getAction();
568            Log.d(TAG, "Received intent action=" + action);
569            if (action.equals(Intent.ACTION_MEDIA_MOUNTED)
570                    || action.equals(Intent.ACTION_MEDIA_UNMOUNTED)
571                    || action.equals(Intent.ACTION_MEDIA_CHECKING)) {
572                checkStorage();
573            } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)) {
574                checkStorage();
575                if (!mIsImageCaptureIntent) {
576                    updateThumbnailButton();
577                }
578            }
579        }
580    };
581
582    private void initOnScreenIndicator() {
583        mGpsNoSignalIndicator = findViewById(R.id.onscreen_gps_indicator_no_signal);
584        mGpsHasSignalIndicator = findViewById(R.id.onscreen_gps_indicator_on);
585        mExposureIndicator = (TextView) findViewById(R.id.onscreen_exposure_indicator);
586    }
587
588    @Override
589    public void showGpsOnScreenIndicator(boolean hasSignal) {
590        if (hasSignal) {
591            if (mGpsNoSignalIndicator != null) {
592                mGpsNoSignalIndicator.setVisibility(View.GONE);
593            }
594            if (mGpsHasSignalIndicator != null) {
595                mGpsHasSignalIndicator.setVisibility(View.VISIBLE);
596            }
597        } else {
598            if (mGpsNoSignalIndicator != null) {
599                mGpsNoSignalIndicator.setVisibility(View.VISIBLE);
600            }
601            if (mGpsHasSignalIndicator != null) {
602                mGpsHasSignalIndicator.setVisibility(View.GONE);
603            }
604        }
605    }
606
607    @Override
608    public void hideGpsOnScreenIndicator() {
609        if (mGpsNoSignalIndicator != null) mGpsNoSignalIndicator.setVisibility(View.GONE);
610        if (mGpsHasSignalIndicator != null) mGpsHasSignalIndicator.setVisibility(View.GONE);
611    }
612
613    private void updateExposureOnScreenIndicator(int value) {
614        if (mExposureIndicator == null) return;
615
616        if (value == 0) {
617            mExposureIndicator.setText("");
618            mExposureIndicator.setVisibility(View.GONE);
619        } else {
620            float step = mParameters.getExposureCompensationStep();
621            mFormatterArgs[0] = value * step;
622            mBuilder.delete(0, mBuilder.length());
623            mFormatter.format("%+1.1f", mFormatterArgs);
624            String exposure = mFormatter.toString();
625            mExposureIndicator.setText(exposure);
626            mExposureIndicator.setVisibility(View.VISIBLE);
627        }
628    }
629
630    private final class ShutterCallback
631            implements android.hardware.Camera.ShutterCallback {
632        public void onShutter() {
633            mShutterCallbackTime = System.currentTimeMillis();
634            mShutterLag = mShutterCallbackTime - mCaptureStartTime;
635            Log.v(TAG, "mShutterLag = " + mShutterLag + "ms");
636            mFocusManager.onShutter();
637        }
638    }
639
640    private final class PostViewPictureCallback implements PictureCallback {
641        public void onPictureTaken(
642                byte [] data, android.hardware.Camera camera) {
643            mPostViewPictureCallbackTime = System.currentTimeMillis();
644            Log.v(TAG, "mShutterToPostViewCallbackTime = "
645                    + (mPostViewPictureCallbackTime - mShutterCallbackTime)
646                    + "ms");
647        }
648    }
649
650    private final class RawPictureCallback implements PictureCallback {
651        public void onPictureTaken(
652                byte [] rawData, android.hardware.Camera camera) {
653            mRawPictureCallbackTime = System.currentTimeMillis();
654            Log.v(TAG, "mShutterToRawCallbackTime = "
655                    + (mRawPictureCallbackTime - mShutterCallbackTime) + "ms");
656        }
657    }
658
659    private final class JpegPictureCallback implements PictureCallback {
660        Location mLocation;
661
662        public JpegPictureCallback(Location loc) {
663            mLocation = loc;
664        }
665
666        public void onPictureTaken(
667                final byte [] jpegData, final android.hardware.Camera camera) {
668            if (mPausing) {
669                return;
670            }
671
672            mJpegPictureCallbackTime = System.currentTimeMillis();
673            // If postview callback has arrived, the captured image is displayed
674            // in postview callback. If not, the captured image is displayed in
675            // raw picture callback.
676            if (mPostViewPictureCallbackTime != 0) {
677                mShutterToPictureDisplayedTime =
678                        mPostViewPictureCallbackTime - mShutterCallbackTime;
679                mPictureDisplayedToJpegCallbackTime =
680                        mJpegPictureCallbackTime - mPostViewPictureCallbackTime;
681            } else {
682                mShutterToPictureDisplayedTime =
683                        mRawPictureCallbackTime - mShutterCallbackTime;
684                mPictureDisplayedToJpegCallbackTime =
685                        mJpegPictureCallbackTime - mRawPictureCallbackTime;
686            }
687            Log.v(TAG, "mPictureDisplayedToJpegCallbackTime = "
688                    + mPictureDisplayedToJpegCallbackTime + "ms");
689
690            if (!mIsImageCaptureIntent) {
691                enableCameraControls(true);
692
693                startPreview();
694            }
695
696            if (!mIsImageCaptureIntent) {
697                Size s = mParameters.getPictureSize();
698                mImageSaver.addImage(jpegData, mLocation, s.width, s.height);
699            } else {
700                mJpegImageData = jpegData;
701                if (!mQuickCapture) {
702                    showPostCaptureAlert();
703                } else {
704                    doAttach();
705                }
706            }
707
708            // Check this in advance of each shot so we don't add to shutter
709            // latency. It's true that someone else could write to the SD card in
710            // the mean time and fill it, but that could have happened between the
711            // shutter press and saving the JPEG too.
712            checkStorage();
713
714            long now = System.currentTimeMillis();
715            mJpegCallbackFinishTime = now - mJpegPictureCallbackTime;
716            Log.v(TAG, "mJpegCallbackFinishTime = "
717                    + mJpegCallbackFinishTime + "ms");
718            mJpegPictureCallbackTime = 0;
719        }
720    }
721
722    private final class AutoFocusCallback
723            implements android.hardware.Camera.AutoFocusCallback {
724        public void onAutoFocus(
725                boolean focused, android.hardware.Camera camera) {
726            if (mPausing) return;
727
728            mAutoFocusTime = System.currentTimeMillis() - mFocusStartTime;
729            Log.v(TAG, "mAutoFocusTime = " + mAutoFocusTime + "ms");
730            mFocusManager.onAutoFocus(focused);
731            // If focus completes and the snapshot is not started, enable the
732            // controls.
733            if (mFocusManager.isFocusCompleted()) {
734                enableCameraControls(true);
735            }
736        }
737    }
738
739    private final class ZoomListener
740            implements android.hardware.Camera.OnZoomChangeListener {
741        @Override
742        public void onZoomChange(
743                int value, boolean stopped, android.hardware.Camera camera) {
744            Log.v(TAG, "Zoom changed: value=" + value + ". stopped=" + stopped);
745            mZoomValue = value;
746
747            // Update the UI when we get zoom value.
748            mZoomControl.setZoomIndex(value);
749
750            // Keep mParameters up to date. We do not getParameter again in
751            // takePicture. If we do not do this, wrong zoom value will be set.
752            mParameters.setZoom(value);
753
754            if (stopped && mZoomState != ZOOM_STOPPED) {
755                if (mTargetZoomValue != -1 && value != mTargetZoomValue) {
756                    mCameraDevice.startSmoothZoom(mTargetZoomValue);
757                    mZoomState = ZOOM_START;
758                } else {
759                    mZoomState = ZOOM_STOPPED;
760                }
761            }
762        }
763    }
764
765    private static class ImageInfo {
766        byte[] data;
767        Location loc;
768        int width, height;
769        long dateTaken;
770        int previewWidth;
771    }
772
773    private class ImageSaver extends Thread {
774        private ArrayList<ImageInfo> mQueue;
775        private AtomicReference<Thumbnail> mPendingThumbnail;
776        private boolean mStop;
777
778        // Runs in main thread
779        public ImageSaver() {
780            mQueue = new ArrayList<ImageInfo>();
781            mPendingThumbnail = new AtomicReference<Thumbnail>();
782            start();
783        }
784
785        // Runs in main thread
786        public void addImage(final byte[] data, Location loc, int width,
787                int height) {
788            ImageInfo i = new ImageInfo();
789            i.data = data;
790            i.loc = (loc == null) ? null : new Location(loc);  // make a copy
791            i.width = width;
792            i.height = height;
793            i.dateTaken = System.currentTimeMillis();
794            i.previewWidth = mPreviewFrameLayout.getWidth();
795            synchronized (this) {
796                mQueue.add(i);
797                notifyAll();
798            }
799        }
800
801        // Runs in keeper thread
802        @Override
803        public void run() {
804            while (true) {
805                ImageInfo i;
806                synchronized (this) {
807                    if (mQueue.isEmpty()) {
808                        notifyAll();  // for waitDone
809                        // Note that we can stop only after the queue is empty.
810                        if (mStop) break;
811                        try {
812                            wait();
813                        } catch (InterruptedException ex) {
814                            // ignore.
815                        }
816                        continue;
817                    }
818                    i = mQueue.get(0);
819                }
820                keepImage(i.data, i.loc, i.width, i.height, i.dateTaken,
821                        i.previewWidth);
822                synchronized(this) {
823                    mQueue.remove(0);
824                }
825            }
826        }
827
828        // Runs in main thread
829        public void waitDone() {
830            synchronized (this) {
831                while (!mQueue.isEmpty()) {
832                    try {
833                        wait();
834                    } catch (InterruptedException ex) {
835                        // ignore.
836                    }
837                }
838            }
839            updateThumbnail();
840        }
841
842        // Runs in main thread
843        public void finish() {
844            waitDone();
845            synchronized (this) {
846                mStop = true;
847                notifyAll();
848            }
849            try {
850                join();
851            } catch (InterruptedException ex) {
852                // ignore.
853            }
854        }
855
856        // Runs in main thread
857        public void updateThumbnail() {
858            mHandler.removeMessages(UPDATE_THUMBNAIL);
859            Thumbnail t = mPendingThumbnail.getAndSet(null);
860            if (t != null) {
861                mThumbnail = t;
862                mThumbnailView.setBitmap(mThumbnail.getBitmap());
863            }
864            // Share popup may still have the reference to the old thumbnail. Clear it.
865            mSharePopup = null;
866        }
867
868        // Runs in keeper thread
869        private void keepImage(final byte[] data, Location loc, int width,
870                int height, long dateTaken, int previewWidth) {
871            String title = Util.createJpegName(dateTaken);
872            int orientation = Exif.getOrientation(data);
873            Uri uri = Storage.addImage(mContentResolver, title, dateTaken,
874                    loc, orientation, data, width, height);
875            boolean needThumbnail;
876            if (uri != null) {
877                synchronized (this) {
878                    needThumbnail = (mQueue.size() == 1);
879                }
880                if (needThumbnail) {
881                    // Create a thumbnail whose width is equal or bigger than
882                    // that of the preview.
883                    int ratio = (int) Math.ceil((double) width / previewWidth);
884                    int inSampleSize = Integer.highestOneBit(ratio);
885                    mPendingThumbnail.set(Thumbnail.createThumbnail(
886                            data, orientation, inSampleSize, uri));
887                    mHandler.sendEmptyMessage(UPDATE_THUMBNAIL);
888                }
889                Util.broadcastNewPicture(Camera.this, uri);
890            }
891        }
892    }
893
894    @Override
895    public boolean capture() {
896        // If we are already in the middle of taking a snapshot then ignore.
897        if (mCameraState == SNAPSHOT_IN_PROGRESS || mCameraDevice == null) {
898            return false;
899        }
900        mCaptureStartTime = System.currentTimeMillis();
901        mPostViewPictureCallbackTime = 0;
902        enableCameraControls(false);
903        mJpegImageData = null;
904
905        // Set rotation and gps data.
906        Util.setRotationParameter(mParameters, mCameraId, mOrientation);
907        Location loc = mLocationManager.getCurrentLocation();
908        Util.setGpsParameters(mParameters, loc);
909        mCameraDevice.setParameters(mParameters);
910
911        mCameraDevice.takePicture(mShutterCallback, mRawPictureCallback,
912                mPostViewPictureCallback, new JpegPictureCallback(loc));
913        mCameraState = SNAPSHOT_IN_PROGRESS;
914        return true;
915    }
916
917    @Override
918    public void setFocusParameters() {
919        setCameraParameters(UPDATE_PARAM_PREFERENCE);
920    }
921
922    private boolean saveDataToFile(String filePath, byte[] data) {
923        FileOutputStream f = null;
924        try {
925            f = new FileOutputStream(filePath);
926            f.write(data);
927        } catch (IOException e) {
928            return false;
929        } finally {
930            Util.closeSilently(f);
931        }
932        return true;
933    }
934
935    @Override
936    public void onCreate(Bundle icicle) {
937        super.onCreate(icicle);
938
939        mIsImageCaptureIntent = isImageCaptureIntent();
940        setContentView(R.layout.camera);
941        if (mIsImageCaptureIntent) {
942            mReviewDoneButton = (Rotatable) findViewById(R.id.btn_done);
943            mReviewCancelButton = (Rotatable) findViewById(R.id.btn_cancel);
944            findViewById(R.id.btn_cancel).setVisibility(View.VISIBLE);
945        } else {
946            mThumbnailView = (RotateImageView) findViewById(R.id.thumbnail);
947            mThumbnailView.setVisibility(View.VISIBLE);
948        }
949
950        mPreferences = new ComboPreferences(this);
951        CameraSettings.upgradeGlobalPreferences(mPreferences.getGlobal());
952        mFocusManager = new FocusManager(mPreferences,
953                getString(R.string.pref_camera_focusmode_default));
954
955        mCameraId = CameraSettings.readPreferredCameraId(mPreferences);
956
957        // Testing purpose. Launch a specific camera through the intent extras.
958        int intentCameraId = Util.getCameraFacingIntentExtras(this);
959        if (intentCameraId != -1) {
960            mCameraId = intentCameraId;
961        }
962
963        mPreferences.setLocalId(this, mCameraId);
964        CameraSettings.upgradeLocalPreferences(mPreferences.getLocal());
965
966        mNumberOfCameras = CameraHolder.instance().getNumberOfCameras();
967        mQuickCapture = getIntent().getBooleanExtra(EXTRA_QUICK_CAPTURE, false);
968
969        // we need to reset exposure for the preview
970        resetExposureCompensation();
971
972        /*
973         * To reduce startup time, we start the preview in another thread.
974         * We make sure the preview is started at the end of onCreate.
975         */
976        Thread startPreviewThread = new Thread(new Runnable() {
977            public void run() {
978                try {
979                    mCameraDevice = Util.openCamera(Camera.this, mCameraId);
980                    initializeCapabilities();
981                    startPreview();
982                } catch (CameraHardwareException e) {
983                    mOpenCameraFail = true;
984                } catch (CameraDisabledException e) {
985                    mCameraDisabled = true;
986                }
987            }
988        });
989        startPreviewThread.start();
990
991        Util.enterLightsOutMode(getWindow());
992
993        // don't set mSurfaceHolder here. We have it set ONLY within
994        // surfaceChanged / surfaceDestroyed, other parts of the code
995        // assume that when it is set, the surface is also set.
996        SurfaceView preview = (SurfaceView) findViewById(R.id.camera_preview);
997        SurfaceHolder holder = preview.getHolder();
998        holder.addCallback(this);
999        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
1000
1001        if (mIsImageCaptureIntent) {
1002            setupCaptureParams();
1003        } else {
1004            mModePicker = (ModePicker) findViewById(R.id.mode_picker);
1005            mModePicker.setVisibility(View.VISIBLE);
1006            mModePicker.setOnModeChangeListener(this);
1007            mModePicker.setCurrentMode(ModePicker.MODE_CAMERA);
1008        }
1009
1010        mZoomControl = (ZoomControl) findViewById(R.id.zoom_control);
1011        mLocationManager = new LocationManager(this, this);
1012
1013        // Make sure preview is started.
1014        try {
1015            startPreviewThread.join();
1016            if (mOpenCameraFail) {
1017                Util.showErrorAndFinish(this, R.string.cannot_connect_camera);
1018                return;
1019            } else if (mCameraDisabled) {
1020                Util.showErrorAndFinish(this, R.string.camera_disabled);
1021                return;
1022            }
1023        } catch (InterruptedException ex) {
1024            // ignore
1025        }
1026
1027        mBackCameraId = CameraHolder.instance().getBackCameraId();
1028        mFrontCameraId = CameraHolder.instance().getFrontCameraId();
1029
1030        // Do this after starting preview because it depends on camera
1031        // parameters.
1032        initializeIndicatorControl();
1033    }
1034
1035    private void overrideCameraSettings(final String flashMode,
1036            final String whiteBalance, final String focusMode) {
1037        if (mIndicatorControlContainer != null) {
1038            mIndicatorControlContainer.overrideSettings(
1039                    CameraSettings.KEY_FLASH_MODE, flashMode,
1040                    CameraSettings.KEY_WHITE_BALANCE, whiteBalance,
1041                    CameraSettings.KEY_FOCUS_MODE, focusMode);
1042        }
1043    }
1044
1045    private void updateSceneModeUI() {
1046        // If scene mode is set, we cannot set flash mode, white balance, and
1047        // focus mode, instead, we read it from driver
1048        if (!Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) {
1049            overrideCameraSettings(mParameters.getFlashMode(),
1050                    mParameters.getWhiteBalance(), mParameters.getFocusMode());
1051        } else {
1052            overrideCameraSettings(null, null, null);
1053        }
1054    }
1055
1056    private void loadCameraPreferences() {
1057        CameraSettings settings = new CameraSettings(this, mInitialParams,
1058                mCameraId, CameraHolder.instance().getCameraInfo());
1059        mPreferenceGroup = settings.getPreferenceGroup(R.xml.camera_preferences);
1060    }
1061
1062    private void initializeIndicatorControl() {
1063        // setting the indicator buttons.
1064        mIndicatorControlContainer =
1065                (IndicatorControlContainer) findViewById(R.id.indicator_control);
1066        if (mIndicatorControlContainer == null) return;
1067        loadCameraPreferences();
1068        final String[] SETTING_KEYS = {
1069                CameraSettings.KEY_FLASH_MODE,
1070                CameraSettings.KEY_WHITE_BALANCE,
1071                CameraSettings.KEY_EXPOSURE,
1072                CameraSettings.KEY_SCENE_MODE};
1073        final String[] OTHER_SETTING_KEYS = {
1074                CameraSettings.KEY_RECORD_LOCATION,
1075                CameraSettings.KEY_PICTURE_SIZE,
1076                CameraSettings.KEY_FOCUS_MODE};
1077
1078        CameraPicker.setImageResourceId(R.drawable.ic_switch_photo_facing_holo_light);
1079        mIndicatorControlContainer.initialize(this, mPreferenceGroup,
1080                mParameters.isZoomSupported(),
1081                SETTING_KEYS, OTHER_SETTING_KEYS);
1082        updateSceneModeUI();
1083        mIndicatorControlContainer.setListener(this);
1084    }
1085
1086    private boolean collapseCameraControls() {
1087        if ((mIndicatorControlContainer != null)
1088                && mIndicatorControlContainer.dismissSettingPopup()) {
1089            return true;
1090        }
1091        return false;
1092    }
1093
1094    private void enableCameraControls(boolean enable) {
1095        if (mIndicatorControlContainer != null) {
1096            mIndicatorControlContainer.setEnabled(enable);
1097        }
1098        if (mModePicker != null) mModePicker.setEnabled(enable);
1099        if (mZoomControl != null) mZoomControl.setEnabled(enable);
1100    }
1101
1102    public static int roundOrientation(int orientation) {
1103        return ((orientation + 45) / 90 * 90) % 360;
1104    }
1105
1106    private class MyOrientationEventListener
1107            extends OrientationEventListener {
1108        public MyOrientationEventListener(Context context) {
1109            super(context);
1110        }
1111
1112        @Override
1113        public void onOrientationChanged(int orientation) {
1114            // We keep the last known orientation. So if the user first orient
1115            // the camera then point the camera to floor or sky, we still have
1116            // the correct orientation.
1117            if (orientation == ORIENTATION_UNKNOWN) return;
1118            mOrientation = roundOrientation(orientation);
1119            // When the screen is unlocked, display rotation may change. Always
1120            // calculate the up-to-date orientationCompensation.
1121            int orientationCompensation = mOrientation
1122                    + Util.getDisplayRotation(Camera.this);
1123            if (mOrientationCompensation != orientationCompensation) {
1124                mOrientationCompensation = orientationCompensation;
1125                setOrientationIndicator(mOrientationCompensation);
1126            }
1127
1128            // Show the toast after getting the first orientation changed.
1129            if (mHandler.hasMessages(SHOW_TAP_TO_FOCUS_TOAST)) {
1130                mHandler.removeMessages(SHOW_TAP_TO_FOCUS_TOAST);
1131                showTapToFocusToast();
1132            }
1133        }
1134    }
1135
1136    private void setOrientationIndicator(int degree) {
1137        if (mThumbnailView != null) mThumbnailView.setDegree(degree);
1138        if (mModePicker != null) mModePicker.setDegree(degree);
1139        if (mSharePopup != null) mSharePopup.setOrientation(degree);
1140        if (mIndicatorControlContainer != null) mIndicatorControlContainer.setDegree(degree);
1141        if (mZoomControl != null) mZoomControl.setDegree(degree);
1142        if (mFocusIndicator != null) mFocusIndicator.setOrientation(degree);
1143        if (mFaceView != null) mFaceView.setOrientation(degree);
1144        if (mReviewCancelButton != null) mReviewCancelButton.setOrientation(degree);
1145        if (mReviewDoneButton != null) mReviewDoneButton.setOrientation(degree);
1146    }
1147
1148    @Override
1149    public void onStop() {
1150        super.onStop();
1151        if (mMediaProviderClient != null) {
1152            mMediaProviderClient.release();
1153            mMediaProviderClient = null;
1154        }
1155    }
1156
1157    private void checkStorage() {
1158        mPicturesRemaining = Storage.getAvailableSpace();
1159        if (mPicturesRemaining > 0) {
1160            mPicturesRemaining /= 1500000;
1161        }
1162        updateStorageHint();
1163    }
1164
1165    @OnClickAttr
1166    public void onThumbnailClicked(View v) {
1167        if (isCameraIdle() && mThumbnail != null) {
1168            showSharePopup();
1169        }
1170    }
1171
1172    @OnClickAttr
1173    public void onReviewRetakeClicked(View v) {
1174        hidePostCaptureAlert();
1175        startPreview();
1176    }
1177
1178    @OnClickAttr
1179    public void onReviewDoneClicked(View v) {
1180        doAttach();
1181    }
1182
1183    @OnClickAttr
1184    public void onReviewCancelClicked(View v) {
1185        doCancel();
1186    }
1187
1188    private void doAttach() {
1189        if (mPausing) {
1190            return;
1191        }
1192
1193        byte[] data = mJpegImageData;
1194
1195        if (mCropValue == null) {
1196            // First handle the no crop case -- just return the value.  If the
1197            // caller specifies a "save uri" then write the data to it's
1198            // stream. Otherwise, pass back a scaled down version of the bitmap
1199            // directly in the extras.
1200            if (mSaveUri != null) {
1201                OutputStream outputStream = null;
1202                try {
1203                    outputStream = mContentResolver.openOutputStream(mSaveUri);
1204                    outputStream.write(data);
1205                    outputStream.close();
1206
1207                    setResultEx(RESULT_OK);
1208                    finish();
1209                } catch (IOException ex) {
1210                    // ignore exception
1211                } finally {
1212                    Util.closeSilently(outputStream);
1213                }
1214            } else {
1215                int orientation = Exif.getOrientation(data);
1216                Bitmap bitmap = Util.makeBitmap(data, 50 * 1024);
1217                bitmap = Util.rotate(bitmap, orientation);
1218                setResultEx(RESULT_OK,
1219                        new Intent("inline-data").putExtra("data", bitmap));
1220                finish();
1221            }
1222        } else {
1223            // Save the image to a temp file and invoke the cropper
1224            Uri tempUri = null;
1225            FileOutputStream tempStream = null;
1226            try {
1227                File path = getFileStreamPath(sTempCropFilename);
1228                path.delete();
1229                tempStream = openFileOutput(sTempCropFilename, 0);
1230                tempStream.write(data);
1231                tempStream.close();
1232                tempUri = Uri.fromFile(path);
1233            } catch (FileNotFoundException ex) {
1234                setResultEx(Activity.RESULT_CANCELED);
1235                finish();
1236                return;
1237            } catch (IOException ex) {
1238                setResultEx(Activity.RESULT_CANCELED);
1239                finish();
1240                return;
1241            } finally {
1242                Util.closeSilently(tempStream);
1243            }
1244
1245            Bundle newExtras = new Bundle();
1246            if (mCropValue.equals("circle")) {
1247                newExtras.putString("circleCrop", "true");
1248            }
1249            if (mSaveUri != null) {
1250                newExtras.putParcelable(MediaStore.EXTRA_OUTPUT, mSaveUri);
1251            } else {
1252                newExtras.putBoolean("return-data", true);
1253            }
1254
1255            Intent cropIntent = new Intent("com.android.camera.action.CROP");
1256
1257            cropIntent.setData(tempUri);
1258            cropIntent.putExtras(newExtras);
1259
1260            startActivityForResult(cropIntent, CROP_MSG);
1261        }
1262    }
1263
1264    private void doCancel() {
1265        setResultEx(RESULT_CANCELED, new Intent());
1266        finish();
1267    }
1268
1269    public void onShutterButtonFocus(ShutterButton button, boolean pressed) {
1270        switch (button.getId()) {
1271            case R.id.shutter_button:
1272                doFocus(pressed);
1273                break;
1274        }
1275    }
1276
1277    public void onShutterButtonClick(ShutterButton button) {
1278        switch (button.getId()) {
1279            case R.id.shutter_button:
1280                doSnap();
1281                break;
1282        }
1283    }
1284
1285    private OnScreenHint mStorageHint;
1286
1287    private void updateStorageHint() {
1288        String noStorageText = null;
1289
1290        if (mPicturesRemaining == Storage.UNAVAILABLE) {
1291            noStorageText = getString(R.string.no_storage);
1292        } else if (mPicturesRemaining == Storage.PREPARING) {
1293            noStorageText = getString(R.string.preparing_sd);
1294        } else if (mPicturesRemaining == Storage.UNKNOWN_SIZE) {
1295            noStorageText = getString(R.string.access_sd_fail);
1296        } else if (mPicturesRemaining < 1L) {
1297            noStorageText = getString(R.string.not_enough_space);
1298        }
1299
1300        if (noStorageText != null) {
1301            if (mStorageHint == null) {
1302                mStorageHint = OnScreenHint.makeText(this, noStorageText);
1303            } else {
1304                mStorageHint.setText(noStorageText);
1305            }
1306            mStorageHint.show();
1307        } else if (mStorageHint != null) {
1308            mStorageHint.cancel();
1309            mStorageHint = null;
1310        }
1311    }
1312
1313    private void installIntentFilter() {
1314        // install an intent filter to receive SD card related events.
1315        IntentFilter intentFilter =
1316                new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);
1317        intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
1318        intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
1319        intentFilter.addAction(Intent.ACTION_MEDIA_CHECKING);
1320        intentFilter.addDataScheme("file");
1321        registerReceiver(mReceiver, intentFilter);
1322        mDidRegister = true;
1323    }
1324
1325    @Override
1326    protected void onResume() {
1327        super.onResume();
1328        mPausing = false;
1329        if (mOpenCameraFail || mCameraDisabled) return;
1330
1331        mJpegPictureCallbackTime = 0;
1332        mZoomValue = 0;
1333
1334        // Start the preview if it is not started.
1335        if (mCameraState == PREVIEW_STOPPED) {
1336            try {
1337                mCameraDevice = Util.openCamera(this, mCameraId);
1338                initializeCapabilities();
1339                resetExposureCompensation();
1340                startPreview();
1341            } catch (CameraHardwareException e) {
1342                Util.showErrorAndFinish(this, R.string.cannot_connect_camera);
1343                return;
1344            } catch (CameraDisabledException e) {
1345                Util.showErrorAndFinish(this, R.string.camera_disabled);
1346                return;
1347            }
1348        }
1349
1350        if (mSurfaceHolder != null) {
1351            // If first time initialization is not finished, put it in the
1352            // message queue.
1353            if (!mFirstTimeInitialized) {
1354                mHandler.sendEmptyMessage(FIRST_TIME_INIT);
1355            } else {
1356                initializeSecondTime();
1357            }
1358        }
1359        keepScreenOnAwhile();
1360
1361        if (mCameraState == IDLE) {
1362            mOnResumeTime = SystemClock.uptimeMillis();
1363            mHandler.sendEmptyMessageDelayed(CHECK_DISPLAY_ROTATION, 100);
1364        }
1365    }
1366
1367    @Override
1368    protected void onPause() {
1369        mPausing = true;
1370        stopPreview();
1371        // Close the camera now because other activities may need to use it.
1372        closeCamera();
1373        resetScreenOn();
1374
1375        // Clear UI.
1376        collapseCameraControls();
1377        if (mSharePopup != null) mSharePopup.dismiss();
1378        if (mFaceView != null) mFaceView.clear();
1379
1380        if (mFirstTimeInitialized) {
1381            mOrientationListener.disable();
1382            mImageSaver.finish();
1383            mImageSaver = null;
1384            if (!mIsImageCaptureIntent && mThumbnail != null && !mThumbnail.fromFile()) {
1385                mThumbnail.saveTo(new File(getFilesDir(), Thumbnail.LAST_THUMB_FILENAME));
1386            }
1387        }
1388
1389        if (mDidRegister) {
1390            unregisterReceiver(mReceiver);
1391            mDidRegister = false;
1392        }
1393        mLocationManager.recordLocation(false);
1394        updateExposureOnScreenIndicator(0);
1395
1396        mFocusManager.releaseSoundPlayer();
1397
1398        if (mStorageHint != null) {
1399            mStorageHint.cancel();
1400            mStorageHint = null;
1401        }
1402
1403        // If we are in an image capture intent and has taken
1404        // a picture, we just clear it in onPause.
1405        mJpegImageData = null;
1406
1407        // Remove the messages in the event queue.
1408        mHandler.removeMessages(FIRST_TIME_INIT);
1409        mHandler.removeMessages(CHECK_DISPLAY_ROTATION);
1410        mFocusManager.removeMessages();
1411
1412        super.onPause();
1413    }
1414
1415    @Override
1416    protected void onActivityResult(
1417            int requestCode, int resultCode, Intent data) {
1418        switch (requestCode) {
1419            case CROP_MSG: {
1420                Intent intent = new Intent();
1421                if (data != null) {
1422                    Bundle extras = data.getExtras();
1423                    if (extras != null) {
1424                        intent.putExtras(extras);
1425                    }
1426                }
1427                setResultEx(resultCode, intent);
1428                finish();
1429
1430                File path = getFileStreamPath(sTempCropFilename);
1431                path.delete();
1432
1433                break;
1434            }
1435        }
1436    }
1437
1438    private boolean canTakePicture() {
1439        return isCameraIdle() && (mPicturesRemaining > 0);
1440    }
1441
1442    @Override
1443    public void autoFocus() {
1444        mFocusStartTime = System.currentTimeMillis();
1445        mCameraDevice.autoFocus(mAutoFocusCallback);
1446        mCameraState = FOCUSING;
1447        enableCameraControls(false);
1448    }
1449
1450    @Override
1451    public void cancelAutoFocus() {
1452        mCameraDevice.cancelAutoFocus();
1453        mCameraState = IDLE;
1454        enableCameraControls(true);
1455        setCameraParameters(UPDATE_PARAM_PREFERENCE);
1456    }
1457
1458    // Preview area is touched. Handle touch focus.
1459    @Override
1460    public boolean onTouch(View v, MotionEvent e) {
1461        if (mPausing || mCameraDevice == null || !mFirstTimeInitialized
1462                || mCameraState == SNAPSHOT_IN_PROGRESS) {
1463            return false;
1464        }
1465
1466        // Do not trigger touch focus if popup window is opened.
1467        if (collapseCameraControls()) return false;
1468
1469        // Check if metering area or focus area is supported.
1470        if (!mFocusAreaSupported && !mMeteringAreaSupported) return false;
1471
1472        return mFocusManager.onTouch(e);
1473    }
1474
1475    @Override
1476    public void onBackPressed() {
1477        if (!isCameraIdle()) {
1478            // ignore backs while we're taking a picture
1479            return;
1480        } else if (!collapseCameraControls()) {
1481            super.onBackPressed();
1482        }
1483    }
1484
1485    @Override
1486    public boolean onKeyDown(int keyCode, KeyEvent event) {
1487        switch (keyCode) {
1488            case KeyEvent.KEYCODE_FOCUS:
1489                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1490                    doFocus(true);
1491                }
1492                return true;
1493            case KeyEvent.KEYCODE_CAMERA:
1494                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1495                    doSnap();
1496                }
1497                return true;
1498            case KeyEvent.KEYCODE_DPAD_CENTER:
1499                // If we get a dpad center event without any focused view, move
1500                // the focus to the shutter button and press it.
1501                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1502                    // Start auto-focus immediately to reduce shutter lag. After
1503                    // the shutter button gets the focus, doFocus() will be
1504                    // called again but it is fine.
1505                    if (collapseCameraControls()) return true;
1506                    doFocus(true);
1507                    if (mShutterButton.isInTouchMode()) {
1508                        mShutterButton.requestFocusFromTouch();
1509                    } else {
1510                        mShutterButton.requestFocus();
1511                    }
1512                    mShutterButton.setPressed(true);
1513                }
1514                return true;
1515        }
1516
1517        return super.onKeyDown(keyCode, event);
1518    }
1519
1520    @Override
1521    public boolean onKeyUp(int keyCode, KeyEvent event) {
1522        switch (keyCode) {
1523            case KeyEvent.KEYCODE_FOCUS:
1524                if (mFirstTimeInitialized) {
1525                    doFocus(false);
1526                }
1527                return true;
1528        }
1529        return super.onKeyUp(keyCode, event);
1530    }
1531
1532    private void doSnap() {
1533        if (mPausing || collapseCameraControls()) return;
1534
1535        // Do not take the picture if there is not enough storage.
1536        if (mPicturesRemaining <= 0) {
1537            Log.i(TAG, "Not enough space or storage not ready. remaining=" + mPicturesRemaining);
1538            return;
1539        }
1540
1541        Log.v(TAG, "doSnap: mCameraState=" + mCameraState);
1542        mFocusManager.doSnap();
1543    }
1544
1545    private void doFocus(boolean pressed) {
1546        if (mPausing || collapseCameraControls() || mCameraState == SNAPSHOT_IN_PROGRESS) return;
1547
1548        // Do not do focus if there is not enough storage.
1549        if (pressed && !canTakePicture()) return;
1550
1551        mFocusManager.doFocus(pressed);
1552    }
1553
1554    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
1555        // Make sure we have a surface in the holder before proceeding.
1556        if (holder.getSurface() == null) {
1557            Log.d(TAG, "holder.getSurface() == null");
1558            return;
1559        }
1560
1561        Log.v(TAG, "surfaceChanged. w=" + w + ". h=" + h);
1562
1563        // We need to save the holder for later use, even when the mCameraDevice
1564        // is null. This could happen if onResume() is invoked after this
1565        // function.
1566        mSurfaceHolder = holder;
1567
1568        // The mCameraDevice will be null if it fails to connect to the camera
1569        // hardware. In this case we will show a dialog and then finish the
1570        // activity, so it's OK to ignore it.
1571        if (mCameraDevice == null) return;
1572
1573        // Sometimes surfaceChanged is called after onPause or before onResume.
1574        // Ignore it.
1575        if (mPausing || isFinishing()) return;
1576
1577        // Set preview display if the surface is being created. Preview was
1578        // already started. Also restart the preview if display rotation has
1579        // changed. Sometimes this happens when the device is held in portrait
1580        // and camera app is opened. Rotation animation takes some time and
1581        // display rotation in onCreate may not be what we want.
1582        if (mCameraState != PREVIEW_STOPPED
1583                && (Util.getDisplayRotation(this) == mDisplayRotation)
1584                && holder.isCreating()) {
1585            // Set preview display if the surface is being created and preview
1586            // was already started. That means preview display was set to null
1587            // and we need to set it now.
1588            setPreviewDisplay(holder);
1589        } else {
1590            // 1. Restart the preview if the size of surface was changed. The
1591            // framework may not support changing preview display on the fly.
1592            // 2. Start the preview now if surface was destroyed and preview
1593            // stopped.
1594            startPreview();
1595        }
1596
1597        // If first time initialization is not finished, send a message to do
1598        // it later. We want to finish surfaceChanged as soon as possible to let
1599        // user see preview first.
1600        if (!mFirstTimeInitialized) {
1601            mHandler.sendEmptyMessage(FIRST_TIME_INIT);
1602        } else {
1603            initializeSecondTime();
1604        }
1605    }
1606
1607    public void surfaceCreated(SurfaceHolder holder) {
1608    }
1609
1610    public void surfaceDestroyed(SurfaceHolder holder) {
1611        stopPreview();
1612        mSurfaceHolder = null;
1613    }
1614
1615    private void closeCamera() {
1616        if (mCameraDevice != null) {
1617            mCameraDevice.cancelAutoFocus(); // Reset the focus.
1618            CameraHolder.instance().release();
1619            mCameraDevice.setZoomChangeListener(null);
1620            mCameraDevice.setFaceDetectionListener(null);
1621            mCameraDevice.setErrorCallback(null);
1622            mCameraDevice = null;
1623            mCameraState = PREVIEW_STOPPED;
1624            mFocusManager.onCameraReleased();
1625        }
1626    }
1627
1628    private void setPreviewDisplay(SurfaceHolder holder) {
1629        try {
1630            mCameraDevice.setPreviewDisplay(holder);
1631        } catch (Throwable ex) {
1632            closeCamera();
1633            throw new RuntimeException("setPreviewDisplay failed", ex);
1634        }
1635    }
1636
1637    private void startPreview() {
1638        if (mPausing || isFinishing()) return;
1639
1640        mFocusManager.resetTouchFocus();
1641
1642        mCameraDevice.setErrorCallback(mErrorCallback);
1643
1644        // If we're previewing already, stop the preview first (this will blank
1645        // the screen).
1646        if (mCameraState != PREVIEW_STOPPED) stopPreview();
1647
1648        setPreviewDisplay(mSurfaceHolder);
1649        mDisplayRotation = Util.getDisplayRotation(this);
1650        mDisplayOrientation = Util.getDisplayOrientation(mDisplayRotation, mCameraId);
1651        mCameraDevice.setDisplayOrientation(mDisplayOrientation);
1652        if (mFaceView != null) {
1653            mFaceView.setDisplayOrientation(mDisplayOrientation);
1654        }
1655        setCameraParameters(UPDATE_PARAM_ALL);
1656        // If the focus mode is continuous autofocus, call cancelAutoFocus to
1657        // resume it because it may have been paused by autoFocus call.
1658        if (Parameters.FOCUS_MODE_CONTINUOUS_PICTURE.equals(mParameters.getFocusMode())) {
1659            mCameraDevice.cancelAutoFocus();
1660        }
1661
1662        try {
1663            Log.v(TAG, "startPreview");
1664            mCameraDevice.startPreview();
1665        } catch (Throwable ex) {
1666            closeCamera();
1667            throw new RuntimeException("startPreview failed", ex);
1668        }
1669
1670        startFaceDetection();
1671        mZoomState = ZOOM_STOPPED;
1672        mCameraState = IDLE;
1673        mFocusManager.onPreviewStarted();
1674    }
1675
1676    private void stopPreview() {
1677        if (mCameraDevice != null && mCameraState != PREVIEW_STOPPED) {
1678            Log.v(TAG, "stopPreview");
1679            mCameraDevice.stopPreview();
1680        }
1681        mCameraState = PREVIEW_STOPPED;
1682        mFocusManager.onPreviewStopped();
1683    }
1684
1685    private static boolean isSupported(String value, List<String> supported) {
1686        return supported == null ? false : supported.indexOf(value) >= 0;
1687    }
1688
1689    private void updateCameraParametersInitialize() {
1690        // Reset preview frame rate to the maximum because it may be lowered by
1691        // video camera application.
1692        List<Integer> frameRates = mParameters.getSupportedPreviewFrameRates();
1693        if (frameRates != null) {
1694            Integer max = Collections.max(frameRates);
1695            mParameters.setPreviewFrameRate(max);
1696        }
1697
1698        mParameters.setRecordingHint(false);
1699    }
1700
1701    private void updateCameraParametersZoom() {
1702        // Set zoom.
1703        if (mParameters.isZoomSupported()) {
1704            mParameters.setZoom(mZoomValue);
1705        }
1706    }
1707
1708    private void updateCameraParametersPreference() {
1709        if (mFocusAreaSupported) {
1710            mParameters.setFocusAreas(mFocusManager.getFocusAreas());
1711        }
1712
1713        if (mMeteringAreaSupported) {
1714            // Use the same area for focus and metering.
1715            mParameters.setMeteringAreas(mFocusManager.getMeteringAreas());
1716        }
1717
1718        // Set picture size.
1719        String pictureSize = mPreferences.getString(
1720                CameraSettings.KEY_PICTURE_SIZE, null);
1721        if (pictureSize == null) {
1722            CameraSettings.initialCameraPictureSize(this, mParameters);
1723        } else {
1724            List<Size> supported = mParameters.getSupportedPictureSizes();
1725            CameraSettings.setCameraPictureSize(
1726                    pictureSize, supported, mParameters);
1727        }
1728
1729        // Set the preview frame aspect ratio according to the picture size.
1730        Size size = mParameters.getPictureSize();
1731
1732        mPreviewPanel = findViewById(R.id.frame_layout);
1733        mPreviewFrameLayout = (PreviewFrameLayout) findViewById(R.id.frame);
1734        mPreviewFrameLayout.setAspectRatio((double) size.width / size.height);
1735
1736        // Set a preview size that is closest to the viewfinder height and has
1737        // the right aspect ratio.
1738        List<Size> sizes = mParameters.getSupportedPreviewSizes();
1739        Size optimalSize = Util.getOptimalPreviewSize(this,
1740                sizes, (double) size.width / size.height);
1741        Size original = mParameters.getPreviewSize();
1742        if (!original.equals(optimalSize)) {
1743            mParameters.setPreviewSize(optimalSize.width, optimalSize.height);
1744
1745            // Zoom related settings will be changed for different preview
1746            // sizes, so set and read the parameters to get lastest values
1747            mCameraDevice.setParameters(mParameters);
1748            mParameters = mCameraDevice.getParameters();
1749        }
1750        Log.v(TAG, "Preview size is " + optimalSize.width + "x" + optimalSize.height);
1751
1752        // Since change scene mode may change supported values,
1753        // Set scene mode first,
1754        mSceneMode = mPreferences.getString(
1755                CameraSettings.KEY_SCENE_MODE,
1756                getString(R.string.pref_camera_scenemode_default));
1757        if (isSupported(mSceneMode, mParameters.getSupportedSceneModes())) {
1758            if (!mParameters.getSceneMode().equals(mSceneMode)) {
1759                mParameters.setSceneMode(mSceneMode);
1760                mCameraDevice.setParameters(mParameters);
1761
1762                // Setting scene mode will change the settings of flash mode,
1763                // white balance, and focus mode. Here we read back the
1764                // parameters, so we can know those settings.
1765                mParameters = mCameraDevice.getParameters();
1766            }
1767        } else {
1768            mSceneMode = mParameters.getSceneMode();
1769            if (mSceneMode == null) {
1770                mSceneMode = Parameters.SCENE_MODE_AUTO;
1771            }
1772        }
1773
1774        // Set JPEG quality.
1775        int jpegQuality = CameraProfile.getJpegEncodingQualityParameter(mCameraId,
1776                CameraProfile.QUALITY_HIGH);
1777        mParameters.setJpegQuality(jpegQuality);
1778
1779        // For the following settings, we need to check if the settings are
1780        // still supported by latest driver, if not, ignore the settings.
1781
1782        // Set exposure compensation
1783        int value = CameraSettings.readExposure(mPreferences);
1784        int max = mParameters.getMaxExposureCompensation();
1785        int min = mParameters.getMinExposureCompensation();
1786        if (value >= min && value <= max) {
1787            mParameters.setExposureCompensation(value);
1788        } else {
1789            Log.w(TAG, "invalid exposure range: " + value);
1790        }
1791
1792        if (Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) {
1793            // Set flash mode.
1794            String flashMode = mPreferences.getString(
1795                    CameraSettings.KEY_FLASH_MODE,
1796                    getString(R.string.pref_camera_flashmode_default));
1797            List<String> supportedFlash = mParameters.getSupportedFlashModes();
1798            if (isSupported(flashMode, supportedFlash)) {
1799                mParameters.setFlashMode(flashMode);
1800            } else {
1801                flashMode = mParameters.getFlashMode();
1802                if (flashMode == null) {
1803                    flashMode = getString(
1804                            R.string.pref_camera_flashmode_no_flash);
1805                }
1806            }
1807
1808            // Set white balance parameter.
1809            String whiteBalance = mPreferences.getString(
1810                    CameraSettings.KEY_WHITE_BALANCE,
1811                    getString(R.string.pref_camera_whitebalance_default));
1812            if (isSupported(whiteBalance,
1813                    mParameters.getSupportedWhiteBalance())) {
1814                mParameters.setWhiteBalance(whiteBalance);
1815            } else {
1816                whiteBalance = mParameters.getWhiteBalance();
1817                if (whiteBalance == null) {
1818                    whiteBalance = Parameters.WHITE_BALANCE_AUTO;
1819                }
1820            }
1821
1822            // Set focus mode.
1823            mFocusManager.overrideFocusMode(null);
1824            mParameters.setFocusMode(mFocusManager.getFocusMode());
1825        } else {
1826            mFocusManager.overrideFocusMode(mParameters.getFocusMode());
1827        }
1828    }
1829
1830    // We separate the parameters into several subsets, so we can update only
1831    // the subsets actually need updating. The PREFERENCE set needs extra
1832    // locking because the preference can be changed from GLThread as well.
1833    private void setCameraParameters(int updateSet) {
1834        mParameters = mCameraDevice.getParameters();
1835
1836        if ((updateSet & UPDATE_PARAM_INITIALIZE) != 0) {
1837            updateCameraParametersInitialize();
1838        }
1839
1840        if ((updateSet & UPDATE_PARAM_ZOOM) != 0) {
1841            updateCameraParametersZoom();
1842        }
1843
1844        if ((updateSet & UPDATE_PARAM_PREFERENCE) != 0) {
1845            updateCameraParametersPreference();
1846        }
1847
1848        mCameraDevice.setParameters(mParameters);
1849    }
1850
1851    // If the Camera is idle, update the parameters immediately, otherwise
1852    // accumulate them in mUpdateSet and update later.
1853    private void setCameraParametersWhenIdle(int additionalUpdateSet) {
1854        mUpdateSet |= additionalUpdateSet;
1855        if (mCameraDevice == null) {
1856            // We will update all the parameters when we open the device, so
1857            // we don't need to do anything now.
1858            mUpdateSet = 0;
1859            return;
1860        } else if (isCameraIdle()) {
1861            setCameraParameters(mUpdateSet);
1862            updateSceneModeUI();
1863            mUpdateSet = 0;
1864        } else {
1865            if (!mHandler.hasMessages(SET_CAMERA_PARAMETERS_WHEN_IDLE)) {
1866                mHandler.sendEmptyMessageDelayed(
1867                        SET_CAMERA_PARAMETERS_WHEN_IDLE, 1000);
1868            }
1869        }
1870    }
1871
1872    private void gotoGallery() {
1873        MenuHelper.gotoCameraImageGallery(this);
1874    }
1875
1876    private boolean isCameraIdle() {
1877        return (mCameraState == IDLE) || (mFocusManager.isFocusCompleted());
1878    }
1879
1880    private boolean isImageCaptureIntent() {
1881        String action = getIntent().getAction();
1882        return (MediaStore.ACTION_IMAGE_CAPTURE.equals(action));
1883    }
1884
1885    private void setupCaptureParams() {
1886        Bundle myExtras = getIntent().getExtras();
1887        if (myExtras != null) {
1888            mSaveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT);
1889            mCropValue = myExtras.getString("crop");
1890        }
1891    }
1892
1893    private void showPostCaptureAlert() {
1894        if (mIsImageCaptureIntent) {
1895            Util.fadeOut(mIndicatorControlContainer);
1896            Util.fadeOut(mShutterButton);
1897
1898            int[] pickIds = {R.id.btn_retake, R.id.btn_done};
1899            for (int id : pickIds) {
1900                Util.fadeIn(findViewById(id));
1901            }
1902        }
1903    }
1904
1905    private void hidePostCaptureAlert() {
1906        if (mIsImageCaptureIntent) {
1907            enableCameraControls(true);
1908
1909            int[] pickIds = {R.id.btn_retake, R.id.btn_done};
1910            for (int id : pickIds) {
1911                Util.fadeOut(findViewById(id));
1912            }
1913
1914            Util.fadeIn(mShutterButton);
1915            Util.fadeIn(mIndicatorControlContainer);
1916        }
1917    }
1918
1919    @Override
1920    public boolean onPrepareOptionsMenu(Menu menu) {
1921        super.onPrepareOptionsMenu(menu);
1922        // Only show the menu when camera is idle.
1923        for (int i = 0; i < menu.size(); i++) {
1924            menu.getItem(i).setVisible(isCameraIdle());
1925        }
1926
1927        return true;
1928    }
1929
1930    @Override
1931    public boolean onCreateOptionsMenu(Menu menu) {
1932        super.onCreateOptionsMenu(menu);
1933
1934        if (mIsImageCaptureIntent) {
1935            // No options menu for attach mode.
1936            return false;
1937        } else {
1938            addBaseMenuItems(menu);
1939        }
1940        return true;
1941    }
1942
1943    private void addBaseMenuItems(Menu menu) {
1944        MenuHelper.addSwitchModeMenuItem(menu, ModePicker.MODE_VIDEO, new Runnable() {
1945            public void run() {
1946                switchToOtherMode(ModePicker.MODE_VIDEO);
1947            }
1948        });
1949        MenuHelper.addSwitchModeMenuItem(menu, ModePicker.MODE_PANORAMA, new Runnable() {
1950            public void run() {
1951                switchToOtherMode(ModePicker.MODE_PANORAMA);
1952            }
1953        });
1954
1955        if (mNumberOfCameras > 1) {
1956            menu.add(R.string.switch_camera_id)
1957                    .setOnMenuItemClickListener(new OnMenuItemClickListener() {
1958                public boolean onMenuItemClick(MenuItem item) {
1959                    CameraSettings.writePreferredCameraId(mPreferences,
1960                            ((mCameraId == mFrontCameraId)
1961                            ? mBackCameraId : mFrontCameraId));
1962                    onSharedPreferenceChanged();
1963                    return true;
1964                }
1965            }).setIcon(android.R.drawable.ic_menu_camera);
1966        }
1967    }
1968
1969    private boolean switchToOtherMode(int mode) {
1970        if (isFinishing()) return false;
1971        MenuHelper.gotoMode(mode, Camera.this);
1972        mHandler.removeMessages(FIRST_TIME_INIT);
1973        finish();
1974        return true;
1975    }
1976
1977    public boolean onModeChanged(int mode) {
1978        if (mode != ModePicker.MODE_CAMERA) {
1979            return switchToOtherMode(mode);
1980        } else {
1981            return true;
1982        }
1983    }
1984
1985    public void onSharedPreferenceChanged() {
1986        // ignore the events after "onPause()"
1987        if (mPausing) return;
1988
1989        boolean recordLocation = RecordLocationPreference.get(
1990                mPreferences, getContentResolver());
1991        mLocationManager.recordLocation(recordLocation);
1992
1993        int cameraId = CameraSettings.readPreferredCameraId(mPreferences);
1994        if (mCameraId != cameraId) {
1995            // Restart the activity to have a crossfade animation.
1996            // TODO: Use SurfaceTexture to implement a better and faster
1997            // animation.
1998            if (mIsImageCaptureIntent) {
1999                // If the intent is camera capture, stay in camera capture mode.
2000                MenuHelper.gotoCameraMode(this, getIntent());
2001            } else {
2002                MenuHelper.gotoCameraMode(this);
2003            }
2004
2005            finish();
2006        } else {
2007            setCameraParametersWhenIdle(UPDATE_PARAM_PREFERENCE);
2008        }
2009
2010        int exposureValue = CameraSettings.readExposure(mPreferences);
2011        updateExposureOnScreenIndicator(exposureValue);
2012    }
2013
2014    @Override
2015    public void onUserInteraction() {
2016        super.onUserInteraction();
2017        keepScreenOnAwhile();
2018    }
2019
2020    private void resetScreenOn() {
2021        mHandler.removeMessages(CLEAR_SCREEN_DELAY);
2022        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
2023    }
2024
2025    private void keepScreenOnAwhile() {
2026        mHandler.removeMessages(CLEAR_SCREEN_DELAY);
2027        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
2028        mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY);
2029    }
2030
2031    public void onRestorePreferencesClicked() {
2032        if (mPausing) return;
2033        Runnable runnable = new Runnable() {
2034            public void run() {
2035                restorePreferences();
2036            }
2037        };
2038        MenuHelper.confirmAction(this,
2039                getString(R.string.confirm_restore_title),
2040                getString(R.string.confirm_restore_message),
2041                runnable);
2042    }
2043
2044    private void restorePreferences() {
2045        // Reset the zoom. Zoom value is not stored in preference.
2046        if (mParameters.isZoomSupported()) {
2047            mZoomValue = 0;
2048            setCameraParametersWhenIdle(UPDATE_PARAM_ZOOM);
2049            mZoomControl.setZoomIndex(0);
2050        }
2051        if (mIndicatorControlContainer != null) {
2052            mIndicatorControlContainer.dismissSettingPopup();
2053            CameraSettings.restorePreferences(Camera.this, mPreferences,
2054                    mParameters);
2055            mIndicatorControlContainer.reloadPreferences();
2056            onSharedPreferenceChanged();
2057        }
2058    }
2059
2060    public void onOverriddenPreferencesClicked() {
2061        if (mPausing) return;
2062        if (mNotSelectableToast == null) {
2063            String str = getResources().getString(R.string.not_selectable_in_scene_mode);
2064            mNotSelectableToast = Toast.makeText(Camera.this, str, Toast.LENGTH_SHORT);
2065        }
2066        mNotSelectableToast.show();
2067    }
2068
2069    private void showSharePopup() {
2070        mImageSaver.waitDone();
2071        Uri uri = mThumbnail.getUri();
2072        if (mSharePopup == null || !uri.equals(mSharePopup.getUri())) {
2073            // SharePopup window takes the mPreviewPanel as its size reference.
2074            mSharePopup = new SharePopup(this, uri, mThumbnail.getBitmap(),
2075                    mOrientationCompensation, mPreviewPanel);
2076        }
2077        mSharePopup.showAtLocation(mThumbnailView, Gravity.NO_GRAVITY, 0, 0);
2078    }
2079
2080    @Override
2081    public void onFaceDetection(Face[] faces, android.hardware.Camera camera) {
2082        mFaceView.setFaces(faces);
2083    }
2084
2085    private void showTapToFocusToast() {
2086        // Show the toast.
2087        RotateLayout v = (RotateLayout) findViewById(R.id.tap_to_focus_prompt);
2088        v.setOrientation(mOrientationCompensation);
2089        v.startAnimation(AnimationUtils.loadAnimation(this, R.anim.on_screen_hint_enter));
2090        v.setVisibility(View.VISIBLE);
2091        mHandler.sendEmptyMessageDelayed(DISMISS_TAP_TO_FOCUS_TOAST, 5000);
2092        // Clear the preference.
2093        Editor editor = mPreferences.edit();
2094        editor.putBoolean(CameraSettings.KEY_TAP_TO_FOCUS_PROMPT_SHOWN, false);
2095        editor.apply();
2096    }
2097
2098    private void initializeCapabilities() {
2099        mInitialParams = mCameraDevice.getParameters();
2100        mFocusManager.initializeParameters(mInitialParams);
2101        mFocusAreaSupported = (mInitialParams.getMaxNumFocusAreas() > 0
2102                && isSupported(Parameters.FOCUS_MODE_AUTO,
2103                        mInitialParams.getSupportedFocusModes()));
2104        mMeteringAreaSupported = (mInitialParams.getMaxNumMeteringAreas() > 0);
2105    }
2106}
2107