Camera.java revision a5edbe951a507a066f7601204e633dbd2dff3224
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 > Storage.LOW_STORAGE_THRESHOLD) {
1213            mPicturesRemaining = (mPicturesRemaining - Storage.LOW_STORAGE_THRESHOLD)
1214                    / Storage.PICTURE_SIZE;
1215        } else if (mPicturesRemaining > 0) {
1216            mPicturesRemaining = 0;
1217        }
1218
1219        updateStorageHint();
1220    }
1221
1222    @OnClickAttr
1223    public void onThumbnailClicked(View v) {
1224        if (isCameraIdle() && mThumbnail != null) {
1225            showSharePopup();
1226        }
1227    }
1228
1229    @OnClickAttr
1230    public void onReviewRetakeClicked(View v) {
1231        hidePostCaptureAlert();
1232        startPreview();
1233    }
1234
1235    @OnClickAttr
1236    public void onReviewDoneClicked(View v) {
1237        doAttach();
1238    }
1239
1240    @OnClickAttr
1241    public void onReviewCancelClicked(View v) {
1242        doCancel();
1243    }
1244
1245    private void doAttach() {
1246        if (mPausing) {
1247            return;
1248        }
1249
1250        byte[] data = mJpegImageData;
1251
1252        if (mCropValue == null) {
1253            // First handle the no crop case -- just return the value.  If the
1254            // caller specifies a "save uri" then write the data to it's
1255            // stream. Otherwise, pass back a scaled down version of the bitmap
1256            // directly in the extras.
1257            if (mSaveUri != null) {
1258                OutputStream outputStream = null;
1259                try {
1260                    outputStream = mContentResolver.openOutputStream(mSaveUri);
1261                    outputStream.write(data);
1262                    outputStream.close();
1263
1264                    setResultEx(RESULT_OK);
1265                    finish();
1266                } catch (IOException ex) {
1267                    // ignore exception
1268                } finally {
1269                    Util.closeSilently(outputStream);
1270                }
1271            } else {
1272                int orientation = Exif.getOrientation(data);
1273                Bitmap bitmap = Util.makeBitmap(data, 50 * 1024);
1274                bitmap = Util.rotate(bitmap, orientation);
1275                setResultEx(RESULT_OK,
1276                        new Intent("inline-data").putExtra("data", bitmap));
1277                finish();
1278            }
1279        } else {
1280            // Save the image to a temp file and invoke the cropper
1281            Uri tempUri = null;
1282            FileOutputStream tempStream = null;
1283            try {
1284                File path = getFileStreamPath(sTempCropFilename);
1285                path.delete();
1286                tempStream = openFileOutput(sTempCropFilename, 0);
1287                tempStream.write(data);
1288                tempStream.close();
1289                tempUri = Uri.fromFile(path);
1290            } catch (FileNotFoundException ex) {
1291                setResultEx(Activity.RESULT_CANCELED);
1292                finish();
1293                return;
1294            } catch (IOException ex) {
1295                setResultEx(Activity.RESULT_CANCELED);
1296                finish();
1297                return;
1298            } finally {
1299                Util.closeSilently(tempStream);
1300            }
1301
1302            Bundle newExtras = new Bundle();
1303            if (mCropValue.equals("circle")) {
1304                newExtras.putString("circleCrop", "true");
1305            }
1306            if (mSaveUri != null) {
1307                newExtras.putParcelable(MediaStore.EXTRA_OUTPUT, mSaveUri);
1308            } else {
1309                newExtras.putBoolean("return-data", true);
1310            }
1311
1312            Intent cropIntent = new Intent("com.android.camera.action.CROP");
1313
1314            cropIntent.setData(tempUri);
1315            cropIntent.putExtras(newExtras);
1316
1317            startActivityForResult(cropIntent, CROP_MSG);
1318        }
1319    }
1320
1321    private void doCancel() {
1322        setResultEx(RESULT_CANCELED, new Intent());
1323        finish();
1324    }
1325
1326    @Override
1327    public void onShutterButtonFocus(boolean pressed) {
1328        if (mPausing || collapseCameraControls() || mCameraState == SNAPSHOT_IN_PROGRESS) return;
1329
1330        // Do not do focus if there is not enough storage.
1331        if (pressed && !canTakePicture()) return;
1332
1333        mFocusManager.doFocus(pressed);
1334    }
1335
1336    @Override
1337    public void onShutterButtonClick() {
1338        if (mPausing || collapseCameraControls()) return;
1339
1340        // Do not take the picture if there is not enough storage.
1341        if (mPicturesRemaining <= 0) {
1342            Log.i(TAG, "Not enough space or storage not ready. remaining=" + mPicturesRemaining);
1343            return;
1344        }
1345
1346        Log.v(TAG, "onShutterButtonClick: mCameraState=" + mCameraState);
1347
1348        // If the user wants to do a snapshot while the previous one is still
1349        // in progress, remember the fact and do it after we finish the previous
1350        // one and re-start the preview.
1351        if (mCameraState == SNAPSHOT_IN_PROGRESS) {
1352            mSnapshotOnIdle = true;
1353            return;
1354        }
1355
1356        mSnapshotOnIdle = false;
1357        mFocusManager.doSnap();
1358    }
1359
1360    @Override
1361    public void onShutterButtonLongPressed() {
1362        if (mPausing || mCameraState == SNAPSHOT_IN_PROGRESS
1363                || mCameraDevice == null || mPicturesRemaining <= 0) return;
1364
1365        Log.v(TAG, "onShutterButtonLongPressed");
1366        mFocusManager.shutterLongPressed();
1367    }
1368
1369    private OnScreenHint mStorageHint;
1370
1371    private void updateStorageHint() {
1372        String noStorageText = null;
1373
1374        if (mPicturesRemaining == Storage.UNAVAILABLE) {
1375            noStorageText = getString(R.string.no_storage);
1376        } else if (mPicturesRemaining == Storage.PREPARING) {
1377            noStorageText = getString(R.string.preparing_sd);
1378        } else if (mPicturesRemaining == Storage.UNKNOWN_SIZE) {
1379            noStorageText = getString(R.string.access_sd_fail);
1380        } else if (mPicturesRemaining < 1L) {
1381            noStorageText = getString(R.string.not_enough_space);
1382        }
1383
1384        if (noStorageText != null) {
1385            if (mStorageHint == null) {
1386                mStorageHint = OnScreenHint.makeText(this, noStorageText);
1387            } else {
1388                mStorageHint.setText(noStorageText);
1389            }
1390            mStorageHint.show();
1391        } else if (mStorageHint != null) {
1392            mStorageHint.cancel();
1393            mStorageHint = null;
1394        }
1395    }
1396
1397    private void installIntentFilter() {
1398        // install an intent filter to receive SD card related events.
1399        IntentFilter intentFilter =
1400                new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);
1401        intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
1402        intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
1403        intentFilter.addAction(Intent.ACTION_MEDIA_CHECKING);
1404        intentFilter.addDataScheme("file");
1405        registerReceiver(mReceiver, intentFilter);
1406        mDidRegister = true;
1407    }
1408
1409    @Override
1410    protected void onResume() {
1411        super.onResume();
1412        mPausing = false;
1413        if (mOpenCameraFail || mCameraDisabled) return;
1414
1415        mJpegPictureCallbackTime = 0;
1416        mZoomValue = 0;
1417
1418        // Start the preview if it is not started.
1419        if (mCameraState == PREVIEW_STOPPED) {
1420            try {
1421                mCameraDevice = Util.openCamera(this, mCameraId);
1422                initializeCapabilities();
1423                resetExposureCompensation();
1424                startPreview();
1425            } catch (CameraHardwareException e) {
1426                Util.showErrorAndFinish(this, R.string.cannot_connect_camera);
1427                return;
1428            } catch (CameraDisabledException e) {
1429                Util.showErrorAndFinish(this, R.string.camera_disabled);
1430                return;
1431            }
1432        }
1433
1434        if (mSurfaceHolder != null) {
1435            // If first time initialization is not finished, put it in the
1436            // message queue.
1437            if (!mFirstTimeInitialized) {
1438                mHandler.sendEmptyMessage(FIRST_TIME_INIT);
1439            } else {
1440                initializeSecondTime();
1441            }
1442        }
1443        keepScreenOnAwhile();
1444
1445        if (mCameraState == IDLE) {
1446            mOnResumeTime = SystemClock.uptimeMillis();
1447            mHandler.sendEmptyMessageDelayed(CHECK_DISPLAY_ROTATION, 100);
1448        }
1449    }
1450
1451    @Override
1452    protected void onPause() {
1453        mPausing = true;
1454        stopPreview();
1455        // Close the camera now because other activities may need to use it.
1456        closeCamera();
1457        resetScreenOn();
1458
1459        // Clear UI.
1460        collapseCameraControls();
1461        if (mSharePopup != null) mSharePopup.dismiss();
1462        if (mFaceView != null) mFaceView.clear();
1463
1464        if (mFirstTimeInitialized) {
1465            mOrientationListener.disable();
1466            mImageSaver.finish();
1467            mImageSaver = null;
1468            if (!mIsImageCaptureIntent && mThumbnail != null && !mThumbnail.fromFile()) {
1469                mThumbnail.saveTo(new File(getFilesDir(), Thumbnail.LAST_THUMB_FILENAME));
1470            }
1471        }
1472
1473        if (mDidRegister) {
1474            unregisterReceiver(mReceiver);
1475            mDidRegister = false;
1476        }
1477        mLocationManager.recordLocation(false);
1478        updateExposureOnScreenIndicator(0);
1479
1480        mFocusManager.releaseSoundPlayer();
1481
1482        if (mStorageHint != null) {
1483            mStorageHint.cancel();
1484            mStorageHint = null;
1485        }
1486
1487        // If we are in an image capture intent and has taken
1488        // a picture, we just clear it in onPause.
1489        mJpegImageData = null;
1490
1491        // Remove the messages in the event queue.
1492        mHandler.removeMessages(FIRST_TIME_INIT);
1493        mHandler.removeMessages(CHECK_DISPLAY_ROTATION);
1494        mFocusManager.removeMessages();
1495
1496        super.onPause();
1497    }
1498
1499    @Override
1500    protected void onActivityResult(
1501            int requestCode, int resultCode, Intent data) {
1502        switch (requestCode) {
1503            case CROP_MSG: {
1504                Intent intent = new Intent();
1505                if (data != null) {
1506                    Bundle extras = data.getExtras();
1507                    if (extras != null) {
1508                        intent.putExtras(extras);
1509                    }
1510                }
1511                setResultEx(resultCode, intent);
1512                finish();
1513
1514                File path = getFileStreamPath(sTempCropFilename);
1515                path.delete();
1516
1517                break;
1518            }
1519        }
1520    }
1521
1522    private boolean canTakePicture() {
1523        return isCameraIdle() && (mPicturesRemaining > 0);
1524    }
1525
1526    @Override
1527    public void autoFocus() {
1528        mFocusStartTime = System.currentTimeMillis();
1529        mCameraDevice.autoFocus(mAutoFocusCallback);
1530        mCameraState = FOCUSING;
1531        enableCameraControls(false);
1532    }
1533
1534    @Override
1535    public void cancelAutoFocus() {
1536        mCameraDevice.cancelAutoFocus();
1537        mCameraState = IDLE;
1538        enableCameraControls(true);
1539        setCameraParameters(UPDATE_PARAM_PREFERENCE);
1540    }
1541
1542    // Preview area is touched. Handle touch focus.
1543    @Override
1544    public boolean onTouch(View v, MotionEvent e) {
1545        if (mPausing || mCameraDevice == null || !mFirstTimeInitialized
1546                || mCameraState == SNAPSHOT_IN_PROGRESS) {
1547            return false;
1548        }
1549
1550        // Do not trigger touch focus if popup window is opened.
1551        if (collapseCameraControls()) return false;
1552
1553        // Check if metering area or focus area is supported.
1554        if (!mFocusAreaSupported && !mMeteringAreaSupported) return false;
1555
1556        return mFocusManager.onTouch(e);
1557    }
1558
1559    @Override
1560    public void onBackPressed() {
1561        if (!isCameraIdle()) {
1562            // ignore backs while we're taking a picture
1563            return;
1564        } else if (!collapseCameraControls()) {
1565            super.onBackPressed();
1566        }
1567    }
1568
1569    @Override
1570    public boolean onKeyDown(int keyCode, KeyEvent event) {
1571        switch (keyCode) {
1572            case KeyEvent.KEYCODE_FOCUS:
1573                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1574                    onShutterButtonFocus(true);
1575                }
1576                return true;
1577            case KeyEvent.KEYCODE_CAMERA:
1578                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1579                    onShutterButtonClick();
1580                }
1581                return true;
1582            case KeyEvent.KEYCODE_DPAD_CENTER:
1583                // If we get a dpad center event without any focused view, move
1584                // the focus to the shutter button and press it.
1585                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1586                    // Start auto-focus immediately to reduce shutter lag. After
1587                    // the shutter button gets the focus, onShutterButtonFocus()
1588                    // will be called again but it is fine.
1589                    if (collapseCameraControls()) return true;
1590                    onShutterButtonFocus(true);
1591                    if (mShutterButton.isInTouchMode()) {
1592                        mShutterButton.requestFocusFromTouch();
1593                    } else {
1594                        mShutterButton.requestFocus();
1595                    }
1596                    mShutterButton.setPressed(true);
1597                }
1598                return true;
1599        }
1600
1601        return super.onKeyDown(keyCode, event);
1602    }
1603
1604    @Override
1605    public boolean onKeyUp(int keyCode, KeyEvent event) {
1606        switch (keyCode) {
1607            case KeyEvent.KEYCODE_FOCUS:
1608                if (mFirstTimeInitialized) {
1609                    onShutterButtonFocus(false);
1610                }
1611                return true;
1612        }
1613        return super.onKeyUp(keyCode, event);
1614    }
1615
1616    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
1617        // Make sure we have a surface in the holder before proceeding.
1618        if (holder.getSurface() == null) {
1619            Log.d(TAG, "holder.getSurface() == null");
1620            return;
1621        }
1622
1623        Log.v(TAG, "surfaceChanged. w=" + w + ". h=" + h);
1624
1625        // We need to save the holder for later use, even when the mCameraDevice
1626        // is null. This could happen if onResume() is invoked after this
1627        // function.
1628        mSurfaceHolder = holder;
1629
1630        // The mCameraDevice will be null if it fails to connect to the camera
1631        // hardware. In this case we will show a dialog and then finish the
1632        // activity, so it's OK to ignore it.
1633        if (mCameraDevice == null) return;
1634
1635        // Sometimes surfaceChanged is called after onPause or before onResume.
1636        // Ignore it.
1637        if (mPausing || isFinishing()) return;
1638
1639        // Set preview display if the surface is being created. Preview was
1640        // already started. Also restart the preview if display rotation has
1641        // changed. Sometimes this happens when the device is held in portrait
1642        // and camera app is opened. Rotation animation takes some time and
1643        // display rotation in onCreate may not be what we want.
1644        if (mCameraState == PREVIEW_STOPPED) {
1645            startPreview();
1646        } else {
1647            if (Util.getDisplayRotation(this) != mDisplayRotation) {
1648                setDisplayOrientation();
1649            }
1650            if (holder.isCreating()) {
1651                // Set preview display if the surface is being created and preview
1652                // was already started. That means preview display was set to null
1653                // and we need to set it now.
1654                setPreviewDisplay(holder);
1655            }
1656        }
1657
1658        // If first time initialization is not finished, send a message to do
1659        // it later. We want to finish surfaceChanged as soon as possible to let
1660        // user see preview first.
1661        if (!mFirstTimeInitialized) {
1662            mHandler.sendEmptyMessage(FIRST_TIME_INIT);
1663        } else {
1664            initializeSecondTime();
1665        }
1666    }
1667
1668    public void surfaceCreated(SurfaceHolder holder) {
1669    }
1670
1671    public void surfaceDestroyed(SurfaceHolder holder) {
1672        stopPreview();
1673        mSurfaceHolder = null;
1674    }
1675
1676    private void closeCamera() {
1677        if (mCameraDevice != null) {
1678            CameraHolder.instance().release();
1679            mCameraDevice.setZoomChangeListener(null);
1680            mCameraDevice.setFaceDetectionListener(null);
1681            mCameraDevice.setErrorCallback(null);
1682            mCameraDevice = null;
1683            mCameraState = PREVIEW_STOPPED;
1684            mFocusManager.onCameraReleased();
1685        }
1686    }
1687
1688    private void setPreviewDisplay(SurfaceHolder holder) {
1689        try {
1690            mCameraDevice.setPreviewDisplay(holder);
1691        } catch (Throwable ex) {
1692            closeCamera();
1693            throw new RuntimeException("setPreviewDisplay failed", ex);
1694        }
1695    }
1696
1697    private void setDisplayOrientation() {
1698        mDisplayRotation = Util.getDisplayRotation(this);
1699        mDisplayOrientation = Util.getDisplayOrientation(mDisplayRotation, mCameraId);
1700        mCameraDevice.setDisplayOrientation(mDisplayOrientation);
1701        if (mFaceView != null) {
1702            mFaceView.setDisplayOrientation(mDisplayOrientation);
1703        }
1704    }
1705
1706    private void startPreview() {
1707        if (mPausing || isFinishing()) return;
1708
1709        mFocusManager.resetTouchFocus();
1710
1711        mCameraDevice.setErrorCallback(mErrorCallback);
1712
1713        // If we're previewing already, stop the preview first (this will blank
1714        // the screen).
1715        if (mCameraState != PREVIEW_STOPPED) stopPreview();
1716
1717        setPreviewDisplay(mSurfaceHolder);
1718        setDisplayOrientation();
1719        setCameraParameters(UPDATE_PARAM_ALL);
1720        // If the focus mode is continuous autofocus, call cancelAutoFocus to
1721        // resume it because it may have been paused by autoFocus call.
1722        if (Parameters.FOCUS_MODE_CONTINUOUS_PICTURE.equals(mParameters.getFocusMode())) {
1723            mCameraDevice.cancelAutoFocus();
1724        }
1725
1726        try {
1727            Log.v(TAG, "startPreview");
1728            mCameraDevice.startPreview();
1729        } catch (Throwable ex) {
1730            closeCamera();
1731            throw new RuntimeException("startPreview failed", ex);
1732        }
1733
1734        startFaceDetection();
1735        mZoomState = ZOOM_STOPPED;
1736        mCameraState = IDLE;
1737        mFocusManager.onPreviewStarted();
1738
1739        if (mSnapshotOnIdle) {
1740            mHandler.post(mDoSnapRunnable);
1741        }
1742    }
1743
1744    private void stopPreview() {
1745        if (mCameraDevice != null && mCameraState != PREVIEW_STOPPED) {
1746            Log.v(TAG, "stopPreview");
1747            mCameraDevice.cancelAutoFocus(); // Reset the focus.
1748            mCameraDevice.stopPreview();
1749        }
1750        mCameraState = PREVIEW_STOPPED;
1751        mFocusManager.onPreviewStopped();
1752    }
1753
1754    private static boolean isSupported(String value, List<String> supported) {
1755        return supported == null ? false : supported.indexOf(value) >= 0;
1756    }
1757
1758    private void updateCameraParametersInitialize() {
1759        // Reset preview frame rate to the maximum because it may be lowered by
1760        // video camera application.
1761        List<Integer> frameRates = mParameters.getSupportedPreviewFrameRates();
1762        if (frameRates != null) {
1763            Integer max = Collections.max(frameRates);
1764            mParameters.setPreviewFrameRate(max);
1765        }
1766
1767        mParameters.setRecordingHint(false);
1768
1769        // Disable video stabilization. Convenience methods not available in API
1770        // level <= 14
1771        String vstabSupported = mParameters.get("video-stabilization-supported");
1772        if ("true".equals(vstabSupported)) {
1773            mParameters.set("video-stabilization", "false");
1774        }
1775    }
1776
1777    private void updateCameraParametersZoom() {
1778        // Set zoom.
1779        if (mParameters.isZoomSupported()) {
1780            mParameters.setZoom(mZoomValue);
1781        }
1782    }
1783
1784    private void updateCameraParametersPreference() {
1785        if (mFocusAreaSupported) {
1786            mParameters.setFocusAreas(mFocusManager.getFocusAreas());
1787        }
1788
1789        if (mMeteringAreaSupported) {
1790            // Use the same area for focus and metering.
1791            mParameters.setMeteringAreas(mFocusManager.getMeteringAreas());
1792        }
1793
1794        // Set picture size.
1795        String pictureSize = mPreferences.getString(
1796                CameraSettings.KEY_PICTURE_SIZE, null);
1797        if (pictureSize == null) {
1798            CameraSettings.initialCameraPictureSize(this, mParameters);
1799        } else {
1800            List<Size> supported = mParameters.getSupportedPictureSizes();
1801            CameraSettings.setCameraPictureSize(
1802                    pictureSize, supported, mParameters);
1803        }
1804
1805        // Set the preview frame aspect ratio according to the picture size.
1806        Size size = mParameters.getPictureSize();
1807
1808        mPreviewPanel = findViewById(R.id.frame_layout);
1809        mPreviewFrameLayout = (PreviewFrameLayout) findViewById(R.id.frame);
1810        mPreviewFrameLayout.setAspectRatio((double) size.width / size.height);
1811
1812        // Set a preview size that is closest to the viewfinder height and has
1813        // the right aspect ratio.
1814        List<Size> sizes = mParameters.getSupportedPreviewSizes();
1815        Size optimalSize = Util.getOptimalPreviewSize(this,
1816                sizes, (double) size.width / size.height);
1817        Size original = mParameters.getPreviewSize();
1818        if (!original.equals(optimalSize)) {
1819            mParameters.setPreviewSize(optimalSize.width, optimalSize.height);
1820
1821            // Zoom related settings will be changed for different preview
1822            // sizes, so set and read the parameters to get lastest values
1823            mCameraDevice.setParameters(mParameters);
1824            mParameters = mCameraDevice.getParameters();
1825        }
1826        Log.v(TAG, "Preview size is " + optimalSize.width + "x" + optimalSize.height);
1827
1828        // Since change scene mode may change supported values,
1829        // Set scene mode first,
1830        mSceneMode = mPreferences.getString(
1831                CameraSettings.KEY_SCENE_MODE,
1832                getString(R.string.pref_camera_scenemode_default));
1833        if (isSupported(mSceneMode, mParameters.getSupportedSceneModes())) {
1834            if (!mParameters.getSceneMode().equals(mSceneMode)) {
1835                mParameters.setSceneMode(mSceneMode);
1836                mCameraDevice.setParameters(mParameters);
1837
1838                // Setting scene mode will change the settings of flash mode,
1839                // white balance, and focus mode. Here we read back the
1840                // parameters, so we can know those settings.
1841                mParameters = mCameraDevice.getParameters();
1842            }
1843        } else {
1844            mSceneMode = mParameters.getSceneMode();
1845            if (mSceneMode == null) {
1846                mSceneMode = Parameters.SCENE_MODE_AUTO;
1847            }
1848        }
1849
1850        // Set JPEG quality.
1851        int jpegQuality = CameraProfile.getJpegEncodingQualityParameter(mCameraId,
1852                CameraProfile.QUALITY_HIGH);
1853        mParameters.setJpegQuality(jpegQuality);
1854
1855        // For the following settings, we need to check if the settings are
1856        // still supported by latest driver, if not, ignore the settings.
1857
1858        // Set exposure compensation
1859        int value = CameraSettings.readExposure(mPreferences);
1860        int max = mParameters.getMaxExposureCompensation();
1861        int min = mParameters.getMinExposureCompensation();
1862        if (value >= min && value <= max) {
1863            mParameters.setExposureCompensation(value);
1864        } else {
1865            Log.w(TAG, "invalid exposure range: " + value);
1866        }
1867
1868        if (Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) {
1869            // Set flash mode.
1870            String flashMode = mPreferences.getString(
1871                    CameraSettings.KEY_FLASH_MODE,
1872                    getString(R.string.pref_camera_flashmode_default));
1873            List<String> supportedFlash = mParameters.getSupportedFlashModes();
1874            if (isSupported(flashMode, supportedFlash)) {
1875                mParameters.setFlashMode(flashMode);
1876            } else {
1877                flashMode = mParameters.getFlashMode();
1878                if (flashMode == null) {
1879                    flashMode = getString(
1880                            R.string.pref_camera_flashmode_no_flash);
1881                }
1882            }
1883
1884            // Set white balance parameter.
1885            String whiteBalance = mPreferences.getString(
1886                    CameraSettings.KEY_WHITE_BALANCE,
1887                    getString(R.string.pref_camera_whitebalance_default));
1888            if (isSupported(whiteBalance,
1889                    mParameters.getSupportedWhiteBalance())) {
1890                mParameters.setWhiteBalance(whiteBalance);
1891            } else {
1892                whiteBalance = mParameters.getWhiteBalance();
1893                if (whiteBalance == null) {
1894                    whiteBalance = Parameters.WHITE_BALANCE_AUTO;
1895                }
1896            }
1897
1898            // Set focus mode.
1899            mFocusManager.overrideFocusMode(null);
1900            mParameters.setFocusMode(mFocusManager.getFocusMode());
1901        } else {
1902            mFocusManager.overrideFocusMode(mParameters.getFocusMode());
1903        }
1904    }
1905
1906    // We separate the parameters into several subsets, so we can update only
1907    // the subsets actually need updating. The PREFERENCE set needs extra
1908    // locking because the preference can be changed from GLThread as well.
1909    private void setCameraParameters(int updateSet) {
1910        mParameters = mCameraDevice.getParameters();
1911
1912        if ((updateSet & UPDATE_PARAM_INITIALIZE) != 0) {
1913            updateCameraParametersInitialize();
1914        }
1915
1916        if ((updateSet & UPDATE_PARAM_ZOOM) != 0) {
1917            updateCameraParametersZoom();
1918        }
1919
1920        if ((updateSet & UPDATE_PARAM_PREFERENCE) != 0) {
1921            updateCameraParametersPreference();
1922        }
1923
1924        mCameraDevice.setParameters(mParameters);
1925    }
1926
1927    // If the Camera is idle, update the parameters immediately, otherwise
1928    // accumulate them in mUpdateSet and update later.
1929    private void setCameraParametersWhenIdle(int additionalUpdateSet) {
1930        mUpdateSet |= additionalUpdateSet;
1931        if (mCameraDevice == null) {
1932            // We will update all the parameters when we open the device, so
1933            // we don't need to do anything now.
1934            mUpdateSet = 0;
1935            return;
1936        } else if (isCameraIdle()) {
1937            setCameraParameters(mUpdateSet);
1938            updateSceneModeUI();
1939            mUpdateSet = 0;
1940        } else {
1941            if (!mHandler.hasMessages(SET_CAMERA_PARAMETERS_WHEN_IDLE)) {
1942                mHandler.sendEmptyMessageDelayed(
1943                        SET_CAMERA_PARAMETERS_WHEN_IDLE, 1000);
1944            }
1945        }
1946    }
1947
1948    private void gotoGallery() {
1949        MenuHelper.gotoCameraImageGallery(this);
1950    }
1951
1952    private boolean isCameraIdle() {
1953        return (mCameraState == IDLE) || (mFocusManager.isFocusCompleted());
1954    }
1955
1956    private boolean isImageCaptureIntent() {
1957        String action = getIntent().getAction();
1958        return (MediaStore.ACTION_IMAGE_CAPTURE.equals(action));
1959    }
1960
1961    private void setupCaptureParams() {
1962        Bundle myExtras = getIntent().getExtras();
1963        if (myExtras != null) {
1964            mSaveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT);
1965            mCropValue = myExtras.getString("crop");
1966        }
1967    }
1968
1969    private void showPostCaptureAlert() {
1970        if (mIsImageCaptureIntent) {
1971            Util.fadeOut(mIndicatorControlContainer);
1972            Util.fadeOut(mShutterButton);
1973
1974            int[] pickIds = {R.id.btn_retake, R.id.btn_done};
1975            for (int id : pickIds) {
1976                Util.fadeIn(findViewById(id));
1977            }
1978        }
1979    }
1980
1981    private void hidePostCaptureAlert() {
1982        if (mIsImageCaptureIntent) {
1983            enableCameraControls(true);
1984
1985            int[] pickIds = {R.id.btn_retake, R.id.btn_done};
1986            for (int id : pickIds) {
1987                Util.fadeOut(findViewById(id));
1988            }
1989
1990            Util.fadeIn(mShutterButton);
1991            Util.fadeIn(mIndicatorControlContainer);
1992        }
1993    }
1994
1995    @Override
1996    public boolean onPrepareOptionsMenu(Menu menu) {
1997        super.onPrepareOptionsMenu(menu);
1998        // Only show the menu when camera is idle.
1999        for (int i = 0; i < menu.size(); i++) {
2000            menu.getItem(i).setVisible(isCameraIdle());
2001        }
2002
2003        return true;
2004    }
2005
2006    @Override
2007    public boolean onCreateOptionsMenu(Menu menu) {
2008        super.onCreateOptionsMenu(menu);
2009
2010        if (mIsImageCaptureIntent) {
2011            // No options menu for attach mode.
2012            return false;
2013        } else {
2014            addBaseMenuItems(menu);
2015        }
2016        return true;
2017    }
2018
2019    private void addBaseMenuItems(Menu menu) {
2020        MenuHelper.addSwitchModeMenuItem(menu, ModePicker.MODE_VIDEO, new Runnable() {
2021            public void run() {
2022                switchToOtherMode(ModePicker.MODE_VIDEO);
2023            }
2024        });
2025        MenuHelper.addSwitchModeMenuItem(menu, ModePicker.MODE_PANORAMA, new Runnable() {
2026            public void run() {
2027                switchToOtherMode(ModePicker.MODE_PANORAMA);
2028            }
2029        });
2030
2031        if (mNumberOfCameras > 1) {
2032            menu.add(R.string.switch_camera_id)
2033                    .setOnMenuItemClickListener(new OnMenuItemClickListener() {
2034                public boolean onMenuItemClick(MenuItem item) {
2035                    CameraSettings.writePreferredCameraId(mPreferences,
2036                            ((mCameraId == mFrontCameraId)
2037                            ? mBackCameraId : mFrontCameraId));
2038                    onSharedPreferenceChanged();
2039                    return true;
2040                }
2041            }).setIcon(android.R.drawable.ic_menu_camera);
2042        }
2043    }
2044
2045    private boolean switchToOtherMode(int mode) {
2046        if (isFinishing()) return false;
2047        mImageSaver.waitDone();
2048        MenuHelper.gotoMode(mode, Camera.this);
2049        mHandler.removeMessages(FIRST_TIME_INIT);
2050        finish();
2051        return true;
2052    }
2053
2054    public boolean onModeChanged(int mode) {
2055        if (mode != ModePicker.MODE_CAMERA) {
2056            return switchToOtherMode(mode);
2057        } else {
2058            return true;
2059        }
2060    }
2061
2062    public void onSharedPreferenceChanged() {
2063        // ignore the events after "onPause()"
2064        if (mPausing) return;
2065
2066        boolean recordLocation = RecordLocationPreference.get(
2067                mPreferences, getContentResolver());
2068        mLocationManager.recordLocation(recordLocation);
2069
2070        int cameraId = CameraSettings.readPreferredCameraId(mPreferences);
2071        if (mCameraId != cameraId) {
2072            // Restart the activity to have a crossfade animation.
2073            // TODO: Use SurfaceTexture to implement a better and faster
2074            // animation.
2075            if (mIsImageCaptureIntent) {
2076                // If the intent is camera capture, stay in camera capture mode.
2077                MenuHelper.gotoCameraMode(this, getIntent());
2078            } else {
2079                MenuHelper.gotoCameraMode(this);
2080            }
2081
2082            finish();
2083        } else {
2084            setCameraParametersWhenIdle(UPDATE_PARAM_PREFERENCE);
2085        }
2086
2087        int exposureValue = CameraSettings.readExposure(mPreferences);
2088        updateExposureOnScreenIndicator(exposureValue);
2089    }
2090
2091    @Override
2092    public void onUserInteraction() {
2093        super.onUserInteraction();
2094        keepScreenOnAwhile();
2095    }
2096
2097    private void resetScreenOn() {
2098        mHandler.removeMessages(CLEAR_SCREEN_DELAY);
2099        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
2100    }
2101
2102    private void keepScreenOnAwhile() {
2103        mHandler.removeMessages(CLEAR_SCREEN_DELAY);
2104        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
2105        mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY);
2106    }
2107
2108    public void onRestorePreferencesClicked() {
2109        if (mPausing) return;
2110        Runnable runnable = new Runnable() {
2111            public void run() {
2112                restorePreferences();
2113            }
2114        };
2115        MenuHelper.confirmAction(this,
2116                getString(R.string.confirm_restore_title),
2117                getString(R.string.confirm_restore_message),
2118                runnable);
2119    }
2120
2121    private void restorePreferences() {
2122        // Reset the zoom. Zoom value is not stored in preference.
2123        if (mParameters.isZoomSupported()) {
2124            mZoomValue = 0;
2125            setCameraParametersWhenIdle(UPDATE_PARAM_ZOOM);
2126            mZoomControl.setZoomIndex(0);
2127        }
2128        if (mIndicatorControlContainer != null) {
2129            mIndicatorControlContainer.dismissSettingPopup();
2130            CameraSettings.restorePreferences(Camera.this, mPreferences,
2131                    mParameters);
2132            mIndicatorControlContainer.reloadPreferences();
2133            onSharedPreferenceChanged();
2134        }
2135    }
2136
2137    public void onOverriddenPreferencesClicked() {
2138        if (mPausing) return;
2139        if (mNotSelectableToast == null) {
2140            String str = getResources().getString(R.string.not_selectable_in_scene_mode);
2141            mNotSelectableToast = Toast.makeText(Camera.this, str, Toast.LENGTH_SHORT);
2142        }
2143        mNotSelectableToast.show();
2144    }
2145
2146    private void showSharePopup() {
2147        mImageSaver.waitDone();
2148        Uri uri = mThumbnail.getUri();
2149        if (mSharePopup == null || !uri.equals(mSharePopup.getUri())) {
2150            // SharePopup window takes the mPreviewPanel as its size reference.
2151            mSharePopup = new SharePopup(this, uri, mThumbnail.getBitmap(),
2152                    mOrientationCompensation, mPreviewPanel);
2153        }
2154        mSharePopup.showAtLocation(mThumbnailView, Gravity.NO_GRAVITY, 0, 0);
2155    }
2156
2157    @Override
2158    public void onFaceDetection(Face[] faces, android.hardware.Camera camera) {
2159        mFaceView.setFaces(faces);
2160    }
2161
2162    private void showTapToFocusToast() {
2163        // Show the toast.
2164        RotateLayout v = (RotateLayout) findViewById(R.id.tap_to_focus_prompt);
2165        v.setOrientation(mOrientationCompensation);
2166        v.startAnimation(AnimationUtils.loadAnimation(this, R.anim.on_screen_hint_enter));
2167        v.setVisibility(View.VISIBLE);
2168        mHandler.sendEmptyMessageDelayed(DISMISS_TAP_TO_FOCUS_TOAST, 5000);
2169        // Clear the preference.
2170        Editor editor = mPreferences.edit();
2171        editor.putBoolean(CameraSettings.KEY_TAP_TO_FOCUS_PROMPT_SHOWN, false);
2172        editor.apply();
2173    }
2174
2175    private void initializeCapabilities() {
2176        mInitialParams = mCameraDevice.getParameters();
2177        mFocusManager.initializeParameters(mInitialParams);
2178        mFocusAreaSupported = (mInitialParams.getMaxNumFocusAreas() > 0
2179                && isSupported(Parameters.FOCUS_MODE_AUTO,
2180                        mInitialParams.getSupportedFocusModes()));
2181        mMeteringAreaSupported = (mInitialParams.getMaxNumMeteringAreas() > 0);
2182    }
2183}
2184