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