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