Camera.java revision 30f0481931beed547656f2c7bc6290ecc9b01ac3
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        }
1272
1273        if (mDidRegister) {
1274            unregisterReceiver(mReceiver);
1275            mDidRegister = false;
1276        }
1277        mLocationManager.recordLocation(false);
1278        updateExposureOnScreenIndicator(0);
1279
1280        mFocusManager.releaseToneGenerator();
1281
1282        if (mStorageHint != null) {
1283            mStorageHint.cancel();
1284            mStorageHint = null;
1285        }
1286
1287        // If we are in an image capture intent and has taken
1288        // a picture, we just clear it in onPause.
1289        mJpegImageData = null;
1290
1291        // Remove the messages in the event queue.
1292        mHandler.removeMessages(FIRST_TIME_INIT);
1293        mHandler.removeMessages(CHECK_DISPLAY_ROTATION);
1294        mFocusManager.removeMessages();
1295
1296        super.onPause();
1297    }
1298
1299    @Override
1300    protected void onActivityResult(
1301            int requestCode, int resultCode, Intent data) {
1302        switch (requestCode) {
1303            case CROP_MSG: {
1304                Intent intent = new Intent();
1305                if (data != null) {
1306                    Bundle extras = data.getExtras();
1307                    if (extras != null) {
1308                        intent.putExtras(extras);
1309                    }
1310                }
1311                setResultEx(resultCode, intent);
1312                finish();
1313
1314                File path = getFileStreamPath(sTempCropFilename);
1315                path.delete();
1316
1317                break;
1318            }
1319        }
1320    }
1321
1322    private boolean canTakePicture() {
1323        return isCameraIdle() && (mPicturesRemaining > 0);
1324    }
1325
1326    @Override
1327    public void autoFocus() {
1328        mFocusStartTime = System.currentTimeMillis();
1329        mCameraDevice.autoFocus(mAutoFocusCallback);
1330        mCameraState = FOCUSING;
1331        enableCameraControls(false);
1332    }
1333
1334    @Override
1335    public void cancelAutoFocus() {
1336        mCameraDevice.cancelAutoFocus();
1337        mCameraState = IDLE;
1338        enableCameraControls(true);
1339        setCameraParameters(UPDATE_PARAM_PREFERENCE);
1340    }
1341
1342    // Preview area is touched. Handle touch focus.
1343    @Override
1344    public boolean onTouch(View v, MotionEvent e) {
1345        if (mPausing || !mFirstTimeInitialized || mCameraState == SNAPSHOT_IN_PROGRESS) {
1346            return false;
1347        }
1348
1349        // Do not trigger touch focus if popup window is opened.
1350        if (collapseCameraControls()) return false;
1351
1352        // Check if metering area or focus area is supported.
1353        if (!mFocusAreaSupported && !mMeteringAreaSupported) return false;
1354
1355        return mFocusManager.onTouch(e);
1356    }
1357
1358    @Override
1359    public void onBackPressed() {
1360        if (!isCameraIdle()) {
1361            // ignore backs while we're taking a picture
1362            return;
1363        } else if (!collapseCameraControls()) {
1364            super.onBackPressed();
1365        }
1366    }
1367
1368    @Override
1369    public boolean onKeyDown(int keyCode, KeyEvent event) {
1370        switch (keyCode) {
1371            case KeyEvent.KEYCODE_FOCUS:
1372                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1373                    doFocus(true);
1374                }
1375                return true;
1376            case KeyEvent.KEYCODE_CAMERA:
1377                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1378                    doSnap();
1379                }
1380                return true;
1381            case KeyEvent.KEYCODE_DPAD_CENTER:
1382                // If we get a dpad center event without any focused view, move
1383                // the focus to the shutter button and press it.
1384                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1385                    // Start auto-focus immediately to reduce shutter lag. After
1386                    // the shutter button gets the focus, doFocus() will be
1387                    // called again but it is fine.
1388                    if (collapseCameraControls()) return true;
1389                    doFocus(true);
1390                    if (mShutterButton.isInTouchMode()) {
1391                        mShutterButton.requestFocusFromTouch();
1392                    } else {
1393                        mShutterButton.requestFocus();
1394                    }
1395                    mShutterButton.setPressed(true);
1396                }
1397                return true;
1398        }
1399
1400        return super.onKeyDown(keyCode, event);
1401    }
1402
1403    @Override
1404    public boolean onKeyUp(int keyCode, KeyEvent event) {
1405        switch (keyCode) {
1406            case KeyEvent.KEYCODE_FOCUS:
1407                if (mFirstTimeInitialized) {
1408                    doFocus(false);
1409                }
1410                return true;
1411        }
1412        return super.onKeyUp(keyCode, event);
1413    }
1414
1415    private void doSnap() {
1416        if (mPausing || collapseCameraControls()) return;
1417
1418        // Do not take the picture if there is not enough storage.
1419        if (mPicturesRemaining <= 0) {
1420            Log.i(TAG, "Not enough space or storage not ready. remaining=" + mPicturesRemaining);
1421            return;
1422        }
1423
1424        Log.v(TAG, "doSnap: mCameraState=" + mCameraState);
1425        mFocusManager.doSnap();
1426    }
1427
1428    private void doFocus(boolean pressed) {
1429        if (mPausing || collapseCameraControls()) return;
1430
1431        // Do not do focus if there is not enough storage.
1432        if (pressed && !canTakePicture()) return;
1433
1434        mFocusManager.doFocus(pressed);
1435    }
1436
1437    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
1438        // Make sure we have a surface in the holder before proceeding.
1439        if (holder.getSurface() == null) {
1440            Log.d(TAG, "holder.getSurface() == null");
1441            return;
1442        }
1443
1444        Log.v(TAG, "surfaceChanged. w=" + w + ". h=" + h);
1445
1446        // We need to save the holder for later use, even when the mCameraDevice
1447        // is null. This could happen if onResume() is invoked after this
1448        // function.
1449        mSurfaceHolder = holder;
1450
1451        // The mCameraDevice will be null if it fails to connect to the camera
1452        // hardware. In this case we will show a dialog and then finish the
1453        // activity, so it's OK to ignore it.
1454        if (mCameraDevice == null) return;
1455
1456        // Sometimes surfaceChanged is called after onPause or before onResume.
1457        // Ignore it.
1458        if (mPausing || isFinishing()) return;
1459
1460        // Set preview display if the surface is being created. Preview was
1461        // already started. Also restart the preview if display rotation has
1462        // changed. Sometimes this happens when the device is held in portrait
1463        // and camera app is opened. Rotation animation takes some time and
1464        // display rotation in onCreate may not be what we want.
1465        if (mCameraState != PREVIEW_STOPPED
1466                && (Util.getDisplayRotation(this) == mDisplayRotation)
1467                && holder.isCreating()) {
1468            // Set preview display if the surface is being created and preview
1469            // was already started. That means preview display was set to null
1470            // and we need to set it now.
1471            setPreviewDisplay(holder);
1472        } else {
1473            // 1. Restart the preview if the size of surface was changed. The
1474            // framework may not support changing preview display on the fly.
1475            // 2. Start the preview now if surface was destroyed and preview
1476            // stopped.
1477            startPreview();
1478        }
1479
1480        // If first time initialization is not finished, send a message to do
1481        // it later. We want to finish surfaceChanged as soon as possible to let
1482        // user see preview first.
1483        if (!mFirstTimeInitialized) {
1484            mHandler.sendEmptyMessage(FIRST_TIME_INIT);
1485        } else {
1486            initializeSecondTime();
1487        }
1488    }
1489
1490    public void surfaceCreated(SurfaceHolder holder) {
1491    }
1492
1493    public void surfaceDestroyed(SurfaceHolder holder) {
1494        stopPreview();
1495        mSurfaceHolder = null;
1496    }
1497
1498    private void closeCamera() {
1499        if (mCameraDevice != null) {
1500            CameraHolder.instance().release();
1501            mCameraDevice.setZoomChangeListener(null);
1502            mCameraDevice.setFaceDetectionListener(null);
1503            mCameraDevice = null;
1504            mCameraState = PREVIEW_STOPPED;
1505            mFocusManager.onCameraReleased();
1506        }
1507    }
1508
1509    private void setPreviewDisplay(SurfaceHolder holder) {
1510        try {
1511            mCameraDevice.setPreviewDisplay(holder);
1512        } catch (Throwable ex) {
1513            closeCamera();
1514            throw new RuntimeException("setPreviewDisplay failed", ex);
1515        }
1516    }
1517
1518    private void startPreview() {
1519        if (mPausing || isFinishing()) return;
1520
1521        mFocusManager.resetTouchFocus();
1522
1523        mCameraDevice.setErrorCallback(mErrorCallback);
1524
1525        // If we're previewing already, stop the preview first (this will blank
1526        // the screen).
1527        if (mCameraState != PREVIEW_STOPPED) stopPreview();
1528
1529        setPreviewDisplay(mSurfaceHolder);
1530        mDisplayRotation = Util.getDisplayRotation(this);
1531        mDisplayOrientation = Util.getDisplayOrientation(mDisplayRotation, mCameraId);
1532        mCameraDevice.setDisplayOrientation(mDisplayOrientation);
1533        if (mFaceView != null) {
1534            mFaceView.setDisplayOrientation(mDisplayOrientation);
1535        }
1536        setCameraParameters(UPDATE_PARAM_ALL);
1537
1538        try {
1539            Log.v(TAG, "startPreview");
1540            mCameraDevice.startPreview();
1541        } catch (Throwable ex) {
1542            closeCamera();
1543            throw new RuntimeException("startPreview failed", ex);
1544        }
1545
1546        startFaceDetection();
1547        mZoomState = ZOOM_STOPPED;
1548        mCameraState = IDLE;
1549        mFocusManager.onPreviewStarted();
1550    }
1551
1552    private void stopPreview() {
1553        if (mCameraDevice != null && mCameraState != PREVIEW_STOPPED) {
1554            Log.v(TAG, "stopPreview");
1555            mCameraDevice.stopPreview();
1556        }
1557        mCameraState = PREVIEW_STOPPED;
1558        mFocusManager.onPreviewStopped();
1559    }
1560
1561    private static boolean isSupported(String value, List<String> supported) {
1562        return supported == null ? false : supported.indexOf(value) >= 0;
1563    }
1564
1565    private void updateCameraParametersInitialize() {
1566        // Reset preview frame rate to the maximum because it may be lowered by
1567        // video camera application.
1568        List<Integer> frameRates = mParameters.getSupportedPreviewFrameRates();
1569        if (frameRates != null) {
1570            Integer max = Collections.max(frameRates);
1571            mParameters.setPreviewFrameRate(max);
1572        }
1573
1574        mParameters.setRecordingHint(false);
1575    }
1576
1577    private void updateCameraParametersZoom() {
1578        // Set zoom.
1579        if (mParameters.isZoomSupported()) {
1580            mParameters.setZoom(mZoomValue);
1581        }
1582    }
1583
1584    private void updateCameraParametersPreference() {
1585        if (mFocusAreaSupported) {
1586            mParameters.setFocusAreas(mFocusManager.getTapArea());
1587        }
1588
1589        if (mMeteringAreaSupported) {
1590            // Use the same area for focus and metering.
1591            mParameters.setMeteringAreas(mFocusManager.getTapArea());
1592        }
1593
1594        // Set picture size.
1595        String pictureSize = mPreferences.getString(
1596                CameraSettings.KEY_PICTURE_SIZE, null);
1597        if (pictureSize == null) {
1598            CameraSettings.initialCameraPictureSize(this, mParameters);
1599        } else {
1600            List<Size> supported = mParameters.getSupportedPictureSizes();
1601            CameraSettings.setCameraPictureSize(
1602                    pictureSize, supported, mParameters);
1603        }
1604
1605        // Set the preview frame aspect ratio according to the picture size.
1606        Size size = mParameters.getPictureSize();
1607
1608        mPreviewFrameLayout = (PreviewFrameLayout) findViewById(R.id.frame_layout);
1609        mPreviewFrameLayout.setAspectRatio((double) size.width / size.height);
1610
1611        // Set a preview size that is closest to the viewfinder height and has
1612        // the right aspect ratio.
1613        List<Size> sizes = mParameters.getSupportedPreviewSizes();
1614        Size optimalSize = Util.getOptimalPreviewSize(this,
1615                sizes, (double) size.width / size.height);
1616        Size original = mParameters.getPreviewSize();
1617        if (!original.equals(optimalSize)) {
1618            mParameters.setPreviewSize(optimalSize.width, optimalSize.height);
1619
1620            // Zoom related settings will be changed for different preview
1621            // sizes, so set and read the parameters to get lastest values
1622            mCameraDevice.setParameters(mParameters);
1623            mParameters = mCameraDevice.getParameters();
1624        }
1625        Log.v(TAG, "Preview size is " + optimalSize.width + "x" + optimalSize.height);
1626
1627        // Since change scene mode may change supported values,
1628        // Set scene mode first,
1629        mSceneMode = mPreferences.getString(
1630                CameraSettings.KEY_SCENE_MODE,
1631                getString(R.string.pref_camera_scenemode_default));
1632        if (isSupported(mSceneMode, mParameters.getSupportedSceneModes())) {
1633            if (!mParameters.getSceneMode().equals(mSceneMode)) {
1634                mParameters.setSceneMode(mSceneMode);
1635                mCameraDevice.setParameters(mParameters);
1636
1637                // Setting scene mode will change the settings of flash mode,
1638                // white balance, and focus mode. Here we read back the
1639                // parameters, so we can know those settings.
1640                mParameters = mCameraDevice.getParameters();
1641            }
1642        } else {
1643            mSceneMode = mParameters.getSceneMode();
1644            if (mSceneMode == null) {
1645                mSceneMode = Parameters.SCENE_MODE_AUTO;
1646            }
1647        }
1648
1649        // Set JPEG quality.
1650        int jpegQuality = CameraProfile.getJpegEncodingQualityParameter(mCameraId,
1651                CameraProfile.QUALITY_HIGH);
1652        mParameters.setJpegQuality(jpegQuality);
1653
1654        // For the following settings, we need to check if the settings are
1655        // still supported by latest driver, if not, ignore the settings.
1656
1657        // Set exposure compensation
1658        int value = CameraSettings.readExposure(mPreferences);
1659        int max = mParameters.getMaxExposureCompensation();
1660        int min = mParameters.getMinExposureCompensation();
1661        if (value >= min && value <= max) {
1662            mParameters.setExposureCompensation(value);
1663        } else {
1664            Log.w(TAG, "invalid exposure range: " + value);
1665        }
1666
1667        if (Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) {
1668            // Set flash mode.
1669            String flashMode = mPreferences.getString(
1670                    CameraSettings.KEY_FLASH_MODE,
1671                    getString(R.string.pref_camera_flashmode_default));
1672            List<String> supportedFlash = mParameters.getSupportedFlashModes();
1673            if (isSupported(flashMode, supportedFlash)) {
1674                mParameters.setFlashMode(flashMode);
1675            } else {
1676                flashMode = mParameters.getFlashMode();
1677                if (flashMode == null) {
1678                    flashMode = getString(
1679                            R.string.pref_camera_flashmode_no_flash);
1680                }
1681            }
1682
1683            // Set white balance parameter.
1684            String whiteBalance = mPreferences.getString(
1685                    CameraSettings.KEY_WHITE_BALANCE,
1686                    getString(R.string.pref_camera_whitebalance_default));
1687            if (isSupported(whiteBalance,
1688                    mParameters.getSupportedWhiteBalance())) {
1689                mParameters.setWhiteBalance(whiteBalance);
1690            } else {
1691                whiteBalance = mParameters.getWhiteBalance();
1692                if (whiteBalance == null) {
1693                    whiteBalance = Parameters.WHITE_BALANCE_AUTO;
1694                }
1695            }
1696
1697            // Set focus mode.
1698            mFocusManager.overrideFocusMode(null);
1699            mParameters.setFocusMode(mFocusManager.getFocusMode());
1700        } else {
1701            mFocusManager.overrideFocusMode(mParameters.getFocusMode());
1702        }
1703    }
1704
1705    // We separate the parameters into several subsets, so we can update only
1706    // the subsets actually need updating. The PREFERENCE set needs extra
1707    // locking because the preference can be changed from GLThread as well.
1708    private void setCameraParameters(int updateSet) {
1709        mParameters = mCameraDevice.getParameters();
1710
1711        if ((updateSet & UPDATE_PARAM_INITIALIZE) != 0) {
1712            updateCameraParametersInitialize();
1713        }
1714
1715        if ((updateSet & UPDATE_PARAM_ZOOM) != 0) {
1716            updateCameraParametersZoom();
1717        }
1718
1719        if ((updateSet & UPDATE_PARAM_PREFERENCE) != 0) {
1720            updateCameraParametersPreference();
1721        }
1722
1723        mCameraDevice.setParameters(mParameters);
1724    }
1725
1726    // If the Camera is idle, update the parameters immediately, otherwise
1727    // accumulate them in mUpdateSet and update later.
1728    private void setCameraParametersWhenIdle(int additionalUpdateSet) {
1729        mUpdateSet |= additionalUpdateSet;
1730        if (mCameraDevice == null) {
1731            // We will update all the parameters when we open the device, so
1732            // we don't need to do anything now.
1733            mUpdateSet = 0;
1734            return;
1735        } else if (isCameraIdle()) {
1736            setCameraParameters(mUpdateSet);
1737            updateSceneModeUI();
1738            mUpdateSet = 0;
1739        } else {
1740            if (!mHandler.hasMessages(SET_CAMERA_PARAMETERS_WHEN_IDLE)) {
1741                mHandler.sendEmptyMessageDelayed(
1742                        SET_CAMERA_PARAMETERS_WHEN_IDLE, 1000);
1743            }
1744        }
1745    }
1746
1747    private void gotoGallery() {
1748        MenuHelper.gotoCameraImageGallery(this);
1749    }
1750
1751    private boolean isCameraIdle() {
1752        return (mCameraState == IDLE) || (mFocusManager.isFocusCompleted());
1753    }
1754
1755    private boolean isImageCaptureIntent() {
1756        String action = getIntent().getAction();
1757        return (MediaStore.ACTION_IMAGE_CAPTURE.equals(action));
1758    }
1759
1760    private void setupCaptureParams() {
1761        Bundle myExtras = getIntent().getExtras();
1762        if (myExtras != null) {
1763            mSaveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT);
1764            mCropValue = myExtras.getString("crop");
1765        }
1766    }
1767
1768    private void showPostCaptureAlert() {
1769        if (mIsImageCaptureIntent) {
1770            Util.fadeOut(mIndicatorControlContainer);
1771            Util.fadeOut(mShutterButton);
1772
1773            int[] pickIds = {R.id.btn_retake, R.id.btn_done};
1774            for (int id : pickIds) {
1775                Util.fadeIn(findViewById(id));
1776            }
1777        }
1778    }
1779
1780    private void hidePostCaptureAlert() {
1781        if (mIsImageCaptureIntent) {
1782            enableCameraControls(true);
1783
1784            int[] pickIds = {R.id.btn_retake, R.id.btn_done};
1785            for (int id : pickIds) {
1786                Util.fadeOut(findViewById(id));
1787            }
1788
1789            Util.fadeIn(mShutterButton);
1790            Util.fadeIn(mIndicatorControlContainer);
1791        }
1792    }
1793
1794    @Override
1795    public boolean onPrepareOptionsMenu(Menu menu) {
1796        super.onPrepareOptionsMenu(menu);
1797        // Only show the menu when camera is idle.
1798        for (int i = 0; i < menu.size(); i++) {
1799            menu.getItem(i).setVisible(isCameraIdle());
1800        }
1801
1802        return true;
1803    }
1804
1805    @Override
1806    public boolean onCreateOptionsMenu(Menu menu) {
1807        super.onCreateOptionsMenu(menu);
1808
1809        if (mIsImageCaptureIntent) {
1810            // No options menu for attach mode.
1811            return false;
1812        } else {
1813            addBaseMenuItems(menu);
1814        }
1815        return true;
1816    }
1817
1818    private void addBaseMenuItems(Menu menu) {
1819        MenuHelper.addSwitchModeMenuItem(menu, ModePicker.MODE_VIDEO, new Runnable() {
1820            public void run() {
1821                switchToOtherMode(ModePicker.MODE_VIDEO);
1822            }
1823        });
1824        MenuHelper.addSwitchModeMenuItem(menu, ModePicker.MODE_PANORAMA, new Runnable() {
1825            public void run() {
1826                switchToOtherMode(ModePicker.MODE_PANORAMA);
1827            }
1828        });
1829        MenuItem gallery = menu.add(R.string.camera_gallery_photos_text)
1830                .setOnMenuItemClickListener(new OnMenuItemClickListener() {
1831            public boolean onMenuItemClick(MenuItem item) {
1832                gotoGallery();
1833                return true;
1834            }
1835        });
1836        gallery.setIcon(android.R.drawable.ic_menu_gallery);
1837        mGalleryItems.add(gallery);
1838
1839        if (mNumberOfCameras > 1) {
1840            menu.add(R.string.switch_camera_id)
1841                    .setOnMenuItemClickListener(new OnMenuItemClickListener() {
1842                public boolean onMenuItemClick(MenuItem item) {
1843                    CameraSettings.writePreferredCameraId(mPreferences,
1844                            ((mCameraId == mFrontCameraId)
1845                            ? mBackCameraId : mFrontCameraId));
1846                    onSharedPreferenceChanged();
1847                    return true;
1848                }
1849            }).setIcon(android.R.drawable.ic_menu_camera);
1850        }
1851    }
1852
1853    private boolean switchToOtherMode(int mode) {
1854        if (isFinishing() || !isCameraIdle()) return false;
1855        MenuHelper.gotoMode(mode, Camera.this);
1856        mHandler.removeMessages(FIRST_TIME_INIT);
1857        finish();
1858        return true;
1859    }
1860
1861    public boolean onModeChanged(int mode) {
1862        if (mode != ModePicker.MODE_CAMERA) {
1863            return switchToOtherMode(mode);
1864        } else {
1865            return true;
1866        }
1867    }
1868
1869    public void onSharedPreferenceChanged() {
1870        // ignore the events after "onPause()"
1871        if (mPausing) return;
1872
1873        boolean recordLocation = RecordLocationPreference.get(
1874                mPreferences, getContentResolver());
1875        mLocationManager.recordLocation(recordLocation);
1876
1877        int cameraId = CameraSettings.readPreferredCameraId(mPreferences);
1878        if (mCameraId != cameraId) {
1879            // Restart the activity to have a crossfade animation.
1880            // TODO: Use SurfaceTexture to implement a better and faster
1881            // animation.
1882            if (mIsImageCaptureIntent) {
1883                // If the intent is camera capture, stay in camera capture mode.
1884                MenuHelper.gotoCameraMode(this, getIntent());
1885            } else {
1886                MenuHelper.gotoCameraMode(this);
1887            }
1888
1889            finish();
1890        } else {
1891            setCameraParametersWhenIdle(UPDATE_PARAM_PREFERENCE);
1892        }
1893
1894        int exposureValue = CameraSettings.readExposure(mPreferences);
1895        updateExposureOnScreenIndicator(exposureValue);
1896    }
1897
1898    @Override
1899    public void onUserInteraction() {
1900        super.onUserInteraction();
1901        keepScreenOnAwhile();
1902    }
1903
1904    private void resetScreenOn() {
1905        mHandler.removeMessages(CLEAR_SCREEN_DELAY);
1906        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1907    }
1908
1909    private void keepScreenOnAwhile() {
1910        mHandler.removeMessages(CLEAR_SCREEN_DELAY);
1911        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1912        mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY);
1913    }
1914
1915    public void onRestorePreferencesClicked() {
1916        if (mPausing) return;
1917        Runnable runnable = new Runnable() {
1918            public void run() {
1919                restorePreferences();
1920            }
1921        };
1922        MenuHelper.confirmAction(this,
1923                getString(R.string.confirm_restore_title),
1924                getString(R.string.confirm_restore_message),
1925                runnable);
1926    }
1927
1928    private void restorePreferences() {
1929        // Reset the zoom. Zoom value is not stored in preference.
1930        if (mParameters.isZoomSupported()) {
1931            mZoomValue = 0;
1932            setCameraParametersWhenIdle(UPDATE_PARAM_ZOOM);
1933            mZoomControl.setZoomIndex(0);
1934        }
1935        if (mIndicatorControlContainer != null) {
1936            mIndicatorControlContainer.dismissSettingPopup();
1937            CameraSettings.restorePreferences(Camera.this, mPreferences,
1938                    mParameters);
1939            mIndicatorControlContainer.reloadPreferences();
1940            onSharedPreferenceChanged();
1941        }
1942    }
1943
1944    public void onOverriddenPreferencesClicked() {
1945        if (mPausing) return;
1946        if (mNotSelectableToast == null) {
1947            String str = getResources().getString(R.string.not_selectable_in_scene_mode);
1948            mNotSelectableToast = Toast.makeText(Camera.this, str, Toast.LENGTH_SHORT);
1949        }
1950        mNotSelectableToast.show();
1951    }
1952
1953    private void showSharePopup() {
1954        Uri uri = mThumbnail.getUri();
1955        if (mSharePopup == null || !uri.equals(mSharePopup.getUri())) {
1956            mSharePopup = new SharePopup(this, uri, mThumbnail.getBitmap(),
1957                    mOrientationCompensation, mPreviewFrameLayout);
1958        }
1959        mSharePopup.showAtLocation(mThumbnailView, Gravity.NO_GRAVITY, 0, 0);
1960    }
1961
1962    @Override
1963    public void onFaceDetection(Face[] faces, android.hardware.Camera camera) {
1964        mFaceView.setFaces(faces);
1965    }
1966
1967    private void showTapToFocusToast() {
1968        // Show the toast.
1969        RotateLayout v = (RotateLayout) findViewById(R.id.tap_to_focus_prompt);
1970        v.setOrientation(mOrientationCompensation);
1971        v.startAnimation(AnimationUtils.loadAnimation(this, R.anim.on_screen_hint_enter));
1972        v.setVisibility(View.VISIBLE);
1973        mHandler.sendEmptyMessageDelayed(DISMISS_TAP_TO_FOCUS_TOAST, 5000);
1974        // Clear the preference.
1975        Editor editor = mPreferences.edit();
1976        editor.putBoolean(CameraSettings.KEY_TAP_TO_FOCUS_PROMPT_SHOWN, false);
1977        editor.apply();
1978    }
1979
1980    private void initializeCapabilities() {
1981        mInitialParams = mCameraDevice.getParameters();
1982        mFocusManager.initializeParameters(mInitialParams);
1983        mFocusAreaSupported = (mInitialParams.getMaxNumFocusAreas() > 0
1984                && isSupported(Parameters.FOCUS_MODE_AUTO,
1985                        mInitialParams.getSupportedFocusModes()));
1986        mMeteringAreaSupported = (mInitialParams.getMaxNumMeteringAreas() > 0);
1987    }
1988}
1989