Camera.java revision 1324c7a05149ffa07a2b1339d1bc9bdff862e77e
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        hidePostCaptureAlert();
429
430        if (!mIsImageCaptureIntent) {
431            updateThumbnailButton();
432            mModePicker.setCurrentMode(ModePicker.MODE_CAMERA);
433        }
434    }
435
436    private class ZoomChangeListener implements ZoomControl.OnZoomChangedListener {
437        // only for immediate zoom
438        @Override
439        public void onZoomValueChanged(int index) {
440            Camera.this.onZoomValueChanged(index);
441        }
442
443        // only for smooth zoom
444        @Override
445        public void onZoomStateChanged(int state) {
446            if (mPausing) return;
447
448            Log.v(TAG, "zoom picker state=" + state);
449            if (state == ZoomControl.ZOOM_IN) {
450                Camera.this.onZoomValueChanged(mZoomMax);
451            } else if (state == ZoomControl.ZOOM_OUT) {
452                Camera.this.onZoomValueChanged(0);
453            } else {
454                mTargetZoomValue = -1;
455                if (mZoomState == ZOOM_START) {
456                    mZoomState = ZOOM_STOPPING;
457                    mCameraDevice.stopSmoothZoom();
458                }
459            }
460        }
461    }
462
463    private void initializeZoom() {
464        if (!mParameters.isZoomSupported()) return;
465        mZoomMax = mParameters.getMaxZoom();
466        mSmoothZoomSupported = mParameters.isSmoothZoomSupported();
467        mZoomControl.setZoomMax(mZoomMax);
468        mZoomControl.setZoomIndex(mParameters.getZoom());
469        mZoomControl.setSmoothZoomSupported(mSmoothZoomSupported);
470        mZoomControl.setOnZoomChangeListener(new ZoomChangeListener());
471        mCameraDevice.setZoomChangeListener(mZoomListener);
472    }
473
474    private void onZoomValueChanged(int index) {
475        // Not useful to change zoom value when the activity is paused.
476        if (mPausing) return;
477
478        if (mSmoothZoomSupported) {
479            if (mTargetZoomValue != index && mZoomState != ZOOM_STOPPED) {
480                mTargetZoomValue = index;
481                if (mZoomState == ZOOM_START) {
482                    mZoomState = ZOOM_STOPPING;
483                    mCameraDevice.stopSmoothZoom();
484                }
485            } else if (mZoomState == ZOOM_STOPPED && mZoomValue != index) {
486                mTargetZoomValue = index;
487                mCameraDevice.startSmoothZoom(index);
488                mZoomState = ZOOM_START;
489            }
490        } else {
491            mZoomValue = index;
492            setCameraParametersWhenIdle(UPDATE_PARAM_ZOOM);
493        }
494    }
495
496    @Override
497    public void startFaceDetection() {
498        if (mParameters.getMaxNumDetectedFaces() > 0) {
499            mFaceView = (FaceView) findViewById(R.id.face_view);
500            mFaceView.clear();
501            mFaceView.setVisibility(View.VISIBLE);
502            mFaceView.setDisplayOrientation(mDisplayOrientation);
503            CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId];
504            mFaceView.setMirror(info.facing == CameraInfo.CAMERA_FACING_FRONT);
505            mFaceView.resume();
506            mCameraDevice.setFaceDetectionListener(this);
507            mCameraDevice.startFaceDetection();
508        }
509    }
510
511    @Override
512    public void stopFaceDetection() {
513        if (mParameters.getMaxNumDetectedFaces() > 0) {
514            mCameraDevice.setFaceDetectionListener(null);
515            mCameraDevice.stopFaceDetection();
516            if (mFaceView != null) mFaceView.clear();
517        }
518    }
519
520    private class PopupGestureListener
521            extends GestureDetector.SimpleOnGestureListener {
522        @Override
523        public boolean onDown(MotionEvent e) {
524            // Check if the popup window is visible.
525            View popup = mIndicatorControlContainer.getActiveSettingPopup();
526            if (popup == null) return false;
527
528
529            // Let popup window, indicator control or preview frame handle the
530            // event by themselves. Dismiss the popup window if users touch on
531            // other areas.
532            if (!Util.pointInView(e.getX(), e.getY(), popup)
533                    && !Util.pointInView(e.getX(), e.getY(), mIndicatorControlContainer)
534                    && !Util.pointInView(e.getX(), e.getY(), mPreviewFrame)) {
535                mIndicatorControlContainer.dismissSettingPopup();
536                // Let event fall through.
537            }
538            return false;
539        }
540    }
541
542    @Override
543    public boolean dispatchTouchEvent(MotionEvent m) {
544        // Check if the popup window should be dismissed first.
545        if (mPopupGestureDetector != null && mPopupGestureDetector.onTouchEvent(m)) {
546            return true;
547        }
548
549        return super.dispatchTouchEvent(m);
550    }
551
552    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
553        @Override
554        public void onReceive(Context context, Intent intent) {
555            String action = intent.getAction();
556            Log.d(TAG, "Received intent action=" + action);
557            if (action.equals(Intent.ACTION_MEDIA_MOUNTED)
558                    || action.equals(Intent.ACTION_MEDIA_UNMOUNTED)
559                    || action.equals(Intent.ACTION_MEDIA_CHECKING)) {
560                checkStorage();
561            } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)) {
562                checkStorage();
563                if (!mIsImageCaptureIntent) {
564                    updateThumbnailButton();
565                }
566            }
567        }
568    };
569
570    private void initOnScreenIndicator() {
571        mGpsNoSignalIndicator = findViewById(R.id.onscreen_gps_indicator_no_signal);
572        mGpsHasSignalIndicator = findViewById(R.id.onscreen_gps_indicator_on);
573        mExposureIndicator = (TextView) findViewById(R.id.onscreen_exposure_indicator);
574    }
575
576    @Override
577    public void showGpsOnScreenIndicator(boolean hasSignal) {
578        if (hasSignal) {
579            if (mGpsNoSignalIndicator != null) {
580                mGpsNoSignalIndicator.setVisibility(View.GONE);
581            }
582            if (mGpsHasSignalIndicator != null) {
583                mGpsHasSignalIndicator.setVisibility(View.VISIBLE);
584            }
585        } else {
586            if (mGpsNoSignalIndicator != null) {
587                mGpsNoSignalIndicator.setVisibility(View.VISIBLE);
588            }
589            if (mGpsHasSignalIndicator != null) {
590                mGpsHasSignalIndicator.setVisibility(View.GONE);
591            }
592        }
593    }
594
595    @Override
596    public void hideGpsOnScreenIndicator() {
597        if (mGpsNoSignalIndicator != null) mGpsNoSignalIndicator.setVisibility(View.GONE);
598        if (mGpsHasSignalIndicator != null) mGpsHasSignalIndicator.setVisibility(View.GONE);
599    }
600
601    private void updateExposureOnScreenIndicator(int value) {
602        if (mExposureIndicator == null) return;
603
604        if (value == 0) {
605            mExposureIndicator.setText("");
606            mExposureIndicator.setVisibility(View.GONE);
607        } else {
608            float step = mParameters.getExposureCompensationStep();
609            mFormatterArgs[0] = value * step;
610            mBuilder.delete(0, mBuilder.length());
611            mFormatter.format("%+1.1f", mFormatterArgs);
612            String exposure = mFormatter.toString();
613            mExposureIndicator.setText(exposure);
614            mExposureIndicator.setVisibility(View.VISIBLE);
615        }
616    }
617
618    private final class ShutterCallback
619            implements android.hardware.Camera.ShutterCallback {
620        public void onShutter() {
621            mShutterCallbackTime = System.currentTimeMillis();
622            mShutterLag = mShutterCallbackTime - mCaptureStartTime;
623            Log.v(TAG, "mShutterLag = " + mShutterLag + "ms");
624            mFocusManager.onShutter();
625        }
626    }
627
628    private final class PostViewPictureCallback implements PictureCallback {
629        public void onPictureTaken(
630                byte [] data, android.hardware.Camera camera) {
631            mPostViewPictureCallbackTime = System.currentTimeMillis();
632            Log.v(TAG, "mShutterToPostViewCallbackTime = "
633                    + (mPostViewPictureCallbackTime - mShutterCallbackTime)
634                    + "ms");
635        }
636    }
637
638    private final class RawPictureCallback implements PictureCallback {
639        public void onPictureTaken(
640                byte [] rawData, android.hardware.Camera camera) {
641            mRawPictureCallbackTime = System.currentTimeMillis();
642            Log.v(TAG, "mShutterToRawCallbackTime = "
643                    + (mRawPictureCallbackTime - mShutterCallbackTime) + "ms");
644        }
645    }
646
647    private final class JpegPictureCallback implements PictureCallback {
648        Location mLocation;
649
650        public JpegPictureCallback(Location loc) {
651            mLocation = loc;
652        }
653
654        public void onPictureTaken(
655                final byte [] jpegData, final android.hardware.Camera camera) {
656            if (mPausing) {
657                return;
658            }
659
660            mJpegPictureCallbackTime = System.currentTimeMillis();
661            // If postview callback has arrived, the captured image is displayed
662            // in postview callback. If not, the captured image is displayed in
663            // raw picture callback.
664            if (mPostViewPictureCallbackTime != 0) {
665                mShutterToPictureDisplayedTime =
666                        mPostViewPictureCallbackTime - mShutterCallbackTime;
667                mPictureDisplayedToJpegCallbackTime =
668                        mJpegPictureCallbackTime - mPostViewPictureCallbackTime;
669            } else {
670                mShutterToPictureDisplayedTime =
671                        mRawPictureCallbackTime - mShutterCallbackTime;
672                mPictureDisplayedToJpegCallbackTime =
673                        mJpegPictureCallbackTime - mRawPictureCallbackTime;
674            }
675            Log.v(TAG, "mPictureDisplayedToJpegCallbackTime = "
676                    + mPictureDisplayedToJpegCallbackTime + "ms");
677
678            if (!mIsImageCaptureIntent) {
679                enableCameraControls(true);
680
681                startPreview();
682            }
683
684            if (!mIsImageCaptureIntent) {
685                storeImage(jpegData, mLocation);
686            } else {
687                mJpegImageData = jpegData;
688                if (!mQuickCapture) {
689                    showPostCaptureAlert();
690                } else {
691                    doAttach();
692                }
693            }
694
695            // Check this in advance of each shot so we don't add to shutter
696            // latency. It's true that someone else could write to the SD card in
697            // the mean time and fill it, but that could have happened between the
698            // shutter press and saving the JPEG too.
699            checkStorage();
700
701            long now = System.currentTimeMillis();
702            mJpegCallbackFinishTime = now - mJpegPictureCallbackTime;
703            Log.v(TAG, "mJpegCallbackFinishTime = "
704                    + mJpegCallbackFinishTime + "ms");
705            mJpegPictureCallbackTime = 0;
706        }
707    }
708
709    private final class AutoFocusCallback
710            implements android.hardware.Camera.AutoFocusCallback {
711        public void onAutoFocus(
712                boolean focused, android.hardware.Camera camera) {
713            if (mPausing) return;
714
715            mAutoFocusTime = System.currentTimeMillis() - mFocusStartTime;
716            Log.v(TAG, "mAutoFocusTime = " + mAutoFocusTime + "ms");
717            mFocusManager.onAutoFocus(focused);
718            // If focus completes and the snapshot is not started, enable the
719            // controls.
720            if (mFocusManager.isFocusCompleted()) {
721                enableCameraControls(true);
722            }
723        }
724    }
725
726    private final class ZoomListener
727            implements android.hardware.Camera.OnZoomChangeListener {
728        @Override
729        public void onZoomChange(
730                int value, boolean stopped, android.hardware.Camera camera) {
731            Log.v(TAG, "Zoom changed: value=" + value + ". stopped="+ stopped);
732            mZoomValue = value;
733
734            // Update the UI when we get zoom value.
735            mZoomControl.setZoomIndex(value);
736
737            // Keep mParameters up to date. We do not getParameter again in
738            // takePicture. If we do not do this, wrong zoom value will be set.
739            mParameters.setZoom(value);
740
741            if (stopped && mZoomState != ZOOM_STOPPED) {
742                if (mTargetZoomValue != -1 && value != mTargetZoomValue) {
743                    mCameraDevice.startSmoothZoom(mTargetZoomValue);
744                    mZoomState = ZOOM_START;
745                } else {
746                    mZoomState = ZOOM_STOPPED;
747                }
748            }
749        }
750    }
751
752    private void storeImage(final byte[] data, Location loc) {
753        long dateTaken = System.currentTimeMillis();
754        String title = Util.createJpegName(dateTaken);
755        int orientation = Exif.getOrientation(data);
756        Uri uri = Storage.addImage(mContentResolver, title, dateTaken,
757                loc, orientation, data);
758        if (uri != null) {
759            // Create a thumbnail whose width is equal or bigger than that of the preview.
760            int ratio = (int) Math.ceil((double) mParameters.getPictureSize().width
761                    / mPreviewFrameLayout.getWidth());
762            int inSampleSize = Integer.highestOneBit(ratio);
763            mThumbnail = Thumbnail.createThumbnail(data, orientation, inSampleSize, uri);
764            if (mThumbnail != null) {
765                mThumbnailView.setBitmap(mThumbnail.getBitmap());
766            }
767            Util.broadcastNewPicture(this, uri);
768        }
769    }
770
771    @Override
772    public boolean capture() {
773        // If we are already in the middle of taking a snapshot then ignore.
774        if (mCameraState == SNAPSHOT_IN_PROGRESS || mCameraDevice == null) {
775            return false;
776        }
777        mCaptureStartTime = System.currentTimeMillis();
778        mPostViewPictureCallbackTime = 0;
779        enableCameraControls(false);
780        mJpegImageData = null;
781
782        // Set rotation and gps data.
783        Util.setRotationParameter(mParameters, mCameraId, mOrientation);
784        Location loc = mLocationManager.getCurrentLocation();
785        Util.setGpsParameters(mParameters, loc);
786        mCameraDevice.setParameters(mParameters);
787
788        mCameraDevice.takePicture(mShutterCallback, mRawPictureCallback,
789                mPostViewPictureCallback, new JpegPictureCallback(loc));
790        mCameraState = SNAPSHOT_IN_PROGRESS;
791        return true;
792    }
793
794    @Override
795    public void setFocusParameters() {
796        setCameraParameters(UPDATE_PARAM_PREFERENCE);
797    }
798
799    private boolean saveDataToFile(String filePath, byte[] data) {
800        FileOutputStream f = null;
801        try {
802            f = new FileOutputStream(filePath);
803            f.write(data);
804        } catch (IOException e) {
805            return false;
806        } finally {
807            Util.closeSilently(f);
808        }
809        return true;
810    }
811
812    @Override
813    public void onCreate(Bundle icicle) {
814        super.onCreate(icicle);
815
816        mIsImageCaptureIntent = isImageCaptureIntent();
817        setContentView(R.layout.camera);
818        if (mIsImageCaptureIntent) {
819            findViewById(R.id.btn_cancel).setVisibility(View.VISIBLE);
820        } else {
821            mThumbnailView = (RotateImageView) findViewById(R.id.thumbnail);
822            mThumbnailView.setVisibility(View.VISIBLE);
823        }
824
825        mPreferences = new ComboPreferences(this);
826        CameraSettings.upgradeGlobalPreferences(mPreferences.getGlobal());
827        mFocusManager = new FocusManager(mPreferences,
828                getString(R.string.pref_camera_focusmode_default));
829
830        mCameraId = CameraSettings.readPreferredCameraId(mPreferences);
831
832        // Testing purpose. Launch a specific camera through the intent extras.
833        int intentCameraId = Util.getCameraFacingIntentExtras(this);
834        if (intentCameraId != -1) {
835            mCameraId = intentCameraId;
836        }
837
838        mPreferences.setLocalId(this, mCameraId);
839        CameraSettings.upgradeLocalPreferences(mPreferences.getLocal());
840
841        mNumberOfCameras = CameraHolder.instance().getNumberOfCameras();
842        mQuickCapture = getIntent().getBooleanExtra(EXTRA_QUICK_CAPTURE, false);
843
844        // we need to reset exposure for the preview
845        resetExposureCompensation();
846
847        /*
848         * To reduce startup time, we start the preview in another thread.
849         * We make sure the preview is started at the end of onCreate.
850         */
851        Thread startPreviewThread = new Thread(new Runnable() {
852            public void run() {
853                try {
854                    mCameraDevice = Util.openCamera(Camera.this, mCameraId);
855                    initializeCapabilities();
856                    startPreview();
857                } catch (CameraHardwareException e) {
858                    mOpenCameraFail = true;
859                } catch (CameraDisabledException e) {
860                    mCameraDisabled = true;
861                }
862            }
863        });
864        startPreviewThread.start();
865
866        Util.enterLightsOutMode(getWindow());
867
868        // don't set mSurfaceHolder here. We have it set ONLY within
869        // surfaceChanged / surfaceDestroyed, other parts of the code
870        // assume that when it is set, the surface is also set.
871        SurfaceView preview = (SurfaceView) findViewById(R.id.camera_preview);
872        SurfaceHolder holder = preview.getHolder();
873        holder.addCallback(this);
874        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
875
876        if (mIsImageCaptureIntent) {
877            setupCaptureParams();
878        } else {
879            mModePicker = (ModePicker) findViewById(R.id.mode_picker);
880            mModePicker.setVisibility(View.VISIBLE);
881            mModePicker.setOnModeChangeListener(this);
882            mModePicker.setCurrentMode(ModePicker.MODE_CAMERA);
883        }
884
885        mZoomControl = (ZoomControl) findViewById(R.id.zoom_control);
886        mLocationManager = new LocationManager(this, this);
887
888        // Make sure preview is started.
889        try {
890            startPreviewThread.join();
891            if (mOpenCameraFail) {
892                Util.showErrorAndFinish(this, R.string.cannot_connect_camera);
893                return;
894            } else if (mCameraDisabled) {
895                Util.showErrorAndFinish(this, R.string.camera_disabled);
896                return;
897            }
898        } catch (InterruptedException ex) {
899            // ignore
900        }
901
902        mBackCameraId = CameraHolder.instance().getBackCameraId();
903        mFrontCameraId = CameraHolder.instance().getFrontCameraId();
904
905        // Do this after starting preview because it depends on camera
906        // parameters.
907        initializeIndicatorControl();
908    }
909
910    private void overrideCameraSettings(final String flashMode,
911            final String whiteBalance, final String focusMode) {
912        if (mIndicatorControlContainer != null) {
913            mIndicatorControlContainer.overrideSettings(
914                    CameraSettings.KEY_FLASH_MODE, flashMode,
915                    CameraSettings.KEY_WHITE_BALANCE, whiteBalance,
916                    CameraSettings.KEY_FOCUS_MODE, focusMode);
917        }
918    }
919
920    private void updateSceneModeUI() {
921        // If scene mode is set, we cannot set flash mode, white balance, and
922        // focus mode, instead, we read it from driver
923        if (!Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) {
924            overrideCameraSettings(mParameters.getFlashMode(),
925                    mParameters.getWhiteBalance(), mParameters.getFocusMode());
926        } else {
927            overrideCameraSettings(null, null, null);
928        }
929    }
930
931    private void loadCameraPreferences() {
932        CameraSettings settings = new CameraSettings(this, mInitialParams,
933                mCameraId, CameraHolder.instance().getCameraInfo());
934        mPreferenceGroup = settings.getPreferenceGroup(R.xml.camera_preferences);
935    }
936
937    private void initializeIndicatorControl() {
938        // setting the indicator buttons.
939        mIndicatorControlContainer =
940                (IndicatorControlContainer) findViewById(R.id.indicator_control);
941        if (mIndicatorControlContainer == null) return;
942        loadCameraPreferences();
943        final String[] SETTING_KEYS = {
944                CameraSettings.KEY_WHITE_BALANCE,
945                CameraSettings.KEY_SCENE_MODE};
946        final String[] OTHER_SETTING_KEYS = {
947                CameraSettings.KEY_RECORD_LOCATION,
948                CameraSettings.KEY_FOCUS_MODE,
949                CameraSettings.KEY_EXPOSURE,
950                CameraSettings.KEY_PICTURE_SIZE};
951
952        CameraPicker.setImageResourceId(R.drawable.ic_switch_photo_facing_holo_light);
953        mIndicatorControlContainer.initialize(this, mPreferenceGroup,
954                CameraSettings.KEY_FLASH_MODE, mParameters.isZoomSupported(),
955                SETTING_KEYS, OTHER_SETTING_KEYS);
956        mIndicatorControlContainer.setListener(this);
957    }
958
959    private boolean collapseCameraControls() {
960        if ((mIndicatorControlContainer != null)
961                && mIndicatorControlContainer.dismissSettingPopup()) {
962            return true;
963        }
964        return false;
965    }
966
967    private void enableCameraControls(boolean enable) {
968        if (mIndicatorControlContainer != null) {
969            mIndicatorControlContainer.setEnabled(enable);
970        }
971        if (mModePicker != null) mModePicker.setEnabled(enable);
972        if (mZoomControl != null) mZoomControl.setEnabled(enable);
973    }
974
975    public static int roundOrientation(int orientation) {
976        return ((orientation + 45) / 90 * 90) % 360;
977    }
978
979    private class MyOrientationEventListener
980            extends OrientationEventListener {
981        public MyOrientationEventListener(Context context) {
982            super(context);
983        }
984
985        @Override
986        public void onOrientationChanged(int orientation) {
987            // We keep the last known orientation. So if the user first orient
988            // the camera then point the camera to floor or sky, we still have
989            // the correct orientation.
990            if (orientation == ORIENTATION_UNKNOWN) return;
991            mOrientation = roundOrientation(orientation);
992            // When the screen is unlocked, display rotation may change. Always
993            // calculate the up-to-date orientationCompensation.
994            int orientationCompensation = mOrientation
995                    + Util.getDisplayRotation(Camera.this);
996            if (mOrientationCompensation != orientationCompensation) {
997                mOrientationCompensation = orientationCompensation;
998                setOrientationIndicator(mOrientationCompensation);
999            }
1000
1001            // Show the toast after getting the first orientation changed.
1002            if (mHandler.hasMessages(SHOW_TAP_TO_FOCUS_TOAST)) {
1003                mHandler.removeMessages(SHOW_TAP_TO_FOCUS_TOAST);
1004                showTapToFocusToast();
1005            }
1006        }
1007    }
1008
1009    private void setOrientationIndicator(int degree) {
1010        if (mThumbnailView != null) mThumbnailView.setDegree(degree);
1011        if (mModePicker != null) mModePicker.setDegree(degree);
1012        if (mSharePopup != null) mSharePopup.setOrientation(degree);
1013        if (mIndicatorControlContainer != null) mIndicatorControlContainer.setDegree(degree);
1014        if (mZoomControl != null) mZoomControl.setDegree(degree);
1015        if (mFocusIndicator != null) mFocusIndicator.setOrientation(degree);
1016        if (mFaceView != null) mFaceView.setOrientation(degree);
1017    }
1018
1019    @Override
1020    public void onStop() {
1021        super.onStop();
1022        if (mMediaProviderClient != null) {
1023            mMediaProviderClient.release();
1024            mMediaProviderClient = null;
1025        }
1026    }
1027
1028    private void checkStorage() {
1029        mPicturesRemaining = Storage.getAvailableSpace();
1030        if (mPicturesRemaining > 0) {
1031            mPicturesRemaining /= 1500000;
1032        }
1033        updateStorageHint();
1034    }
1035
1036    @OnClickAttr
1037    public void onThumbnailClicked(View v) {
1038        if (isCameraIdle() && mThumbnail != null) {
1039            showSharePopup();
1040        }
1041    }
1042
1043    @OnClickAttr
1044    public void onRetakeButtonClicked(View v) {
1045        hidePostCaptureAlert();
1046        startPreview();
1047    }
1048
1049    @OnClickAttr
1050    public void onDoneButtonClicked(View v) {
1051        doAttach();
1052    }
1053
1054    @OnClickAttr
1055    public void onCancelButtonClicked(View v) {
1056        doCancel();
1057    }
1058
1059    private void doAttach() {
1060        if (mPausing) {
1061            return;
1062        }
1063
1064        byte[] data = mJpegImageData;
1065
1066        if (mCropValue == null) {
1067            // First handle the no crop case -- just return the value.  If the
1068            // caller specifies a "save uri" then write the data to it's
1069            // stream. Otherwise, pass back a scaled down version of the bitmap
1070            // directly in the extras.
1071            if (mSaveUri != null) {
1072                OutputStream outputStream = null;
1073                try {
1074                    outputStream = mContentResolver.openOutputStream(mSaveUri);
1075                    outputStream.write(data);
1076                    outputStream.close();
1077
1078                    setResultEx(RESULT_OK);
1079                    finish();
1080                } catch (IOException ex) {
1081                    // ignore exception
1082                } finally {
1083                    Util.closeSilently(outputStream);
1084                }
1085            } else {
1086                int orientation = Exif.getOrientation(data);
1087                Bitmap bitmap = Util.makeBitmap(data, 50 * 1024);
1088                bitmap = Util.rotate(bitmap, orientation);
1089                setResultEx(RESULT_OK,
1090                        new Intent("inline-data").putExtra("data", bitmap));
1091                finish();
1092            }
1093        } else {
1094            // Save the image to a temp file and invoke the cropper
1095            Uri tempUri = null;
1096            FileOutputStream tempStream = null;
1097            try {
1098                File path = getFileStreamPath(sTempCropFilename);
1099                path.delete();
1100                tempStream = openFileOutput(sTempCropFilename, 0);
1101                tempStream.write(data);
1102                tempStream.close();
1103                tempUri = Uri.fromFile(path);
1104            } catch (FileNotFoundException ex) {
1105                setResultEx(Activity.RESULT_CANCELED);
1106                finish();
1107                return;
1108            } catch (IOException ex) {
1109                setResultEx(Activity.RESULT_CANCELED);
1110                finish();
1111                return;
1112            } finally {
1113                Util.closeSilently(tempStream);
1114            }
1115
1116            Bundle newExtras = new Bundle();
1117            if (mCropValue.equals("circle")) {
1118                newExtras.putString("circleCrop", "true");
1119            }
1120            if (mSaveUri != null) {
1121                newExtras.putParcelable(MediaStore.EXTRA_OUTPUT, mSaveUri);
1122            } else {
1123                newExtras.putBoolean("return-data", true);
1124            }
1125
1126            Intent cropIntent = new Intent("com.android.camera.action.CROP");
1127
1128            cropIntent.setData(tempUri);
1129            cropIntent.putExtras(newExtras);
1130
1131            startActivityForResult(cropIntent, CROP_MSG);
1132        }
1133    }
1134
1135    private void doCancel() {
1136        setResultEx(RESULT_CANCELED, new Intent());
1137        finish();
1138    }
1139
1140    public void onShutterButtonFocus(ShutterButton button, boolean pressed) {
1141        switch (button.getId()) {
1142            case R.id.shutter_button:
1143                doFocus(pressed);
1144                break;
1145        }
1146    }
1147
1148    public void onShutterButtonClick(ShutterButton button) {
1149        switch (button.getId()) {
1150            case R.id.shutter_button:
1151                doSnap();
1152                break;
1153        }
1154    }
1155
1156    private OnScreenHint mStorageHint;
1157
1158    private void updateStorageHint() {
1159        String noStorageText = null;
1160
1161        if (mPicturesRemaining == Storage.UNAVAILABLE) {
1162            noStorageText = getString(R.string.no_storage);
1163        } else if (mPicturesRemaining == Storage.PREPARING) {
1164            noStorageText = getString(R.string.preparing_sd);
1165        } else if (mPicturesRemaining == Storage.UNKNOWN_SIZE) {
1166            noStorageText = getString(R.string.access_sd_fail);
1167        } else if (mPicturesRemaining < 1L) {
1168            noStorageText = getString(R.string.not_enough_space);
1169        }
1170
1171        if (noStorageText != null) {
1172            if (mStorageHint == null) {
1173                mStorageHint = OnScreenHint.makeText(this, noStorageText);
1174            } else {
1175                mStorageHint.setText(noStorageText);
1176            }
1177            mStorageHint.show();
1178        } else if (mStorageHint != null) {
1179            mStorageHint.cancel();
1180            mStorageHint = null;
1181        }
1182    }
1183
1184    private void installIntentFilter() {
1185        // install an intent filter to receive SD card related events.
1186        IntentFilter intentFilter =
1187                new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);
1188        intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
1189        intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
1190        intentFilter.addAction(Intent.ACTION_MEDIA_CHECKING);
1191        intentFilter.addDataScheme("file");
1192        registerReceiver(mReceiver, intentFilter);
1193        mDidRegister = true;
1194    }
1195
1196    private void initializeScreenBrightness() {
1197        Window win = getWindow();
1198        // Overright the brightness settings if it is automatic
1199        int mode = Settings.System.getInt(
1200                getContentResolver(),
1201                Settings.System.SCREEN_BRIGHTNESS_MODE,
1202                Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
1203        if (mode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
1204            WindowManager.LayoutParams winParams = win.getAttributes();
1205            winParams.screenBrightness = DEFAULT_CAMERA_BRIGHTNESS;
1206            win.setAttributes(winParams);
1207        }
1208    }
1209
1210    @Override
1211    protected void onResume() {
1212        super.onResume();
1213        mPausing = false;
1214        if (mOpenCameraFail || mCameraDisabled) return;
1215
1216        mJpegPictureCallbackTime = 0;
1217        mZoomValue = 0;
1218
1219        // Start the preview if it is not started.
1220        if (mCameraState == PREVIEW_STOPPED) {
1221            try {
1222                mCameraDevice = Util.openCamera(this, mCameraId);
1223                initializeCapabilities();
1224                resetExposureCompensation();
1225                startPreview();
1226            } catch(CameraHardwareException e) {
1227                Util.showErrorAndFinish(this, R.string.cannot_connect_camera);
1228                return;
1229            } catch(CameraDisabledException e) {
1230                Util.showErrorAndFinish(this, R.string.camera_disabled);
1231                return;
1232            }
1233        }
1234
1235        if (mSurfaceHolder != null) {
1236            // If first time initialization is not finished, put it in the
1237            // message queue.
1238            if (!mFirstTimeInitialized) {
1239                mHandler.sendEmptyMessage(FIRST_TIME_INIT);
1240            } else {
1241                initializeSecondTime();
1242            }
1243        }
1244        keepScreenOnAwhile();
1245
1246        if (mCameraState == IDLE) {
1247            mOnResumeTime = SystemClock.uptimeMillis();
1248            mHandler.sendEmptyMessageDelayed(CHECK_DISPLAY_ROTATION, 100);
1249        }
1250    }
1251
1252    @Override
1253    protected void onPause() {
1254        mPausing = true;
1255        stopPreview();
1256        // Close the camera now because other activities may need to use it.
1257        closeCamera();
1258        resetScreenOn();
1259
1260        // Clear UI.
1261        collapseCameraControls();
1262        if (mSharePopup != null) mSharePopup.dismiss();
1263        if (mFaceView != null) mFaceView.clear();
1264
1265        if (mFirstTimeInitialized) {
1266            mOrientationListener.disable();
1267            if (!mIsImageCaptureIntent) {
1268                if (mThumbnail != null) {
1269                    mThumbnail.saveTo(new File(getFilesDir(), Thumbnail.LAST_THUMB_FILENAME));
1270                }
1271            }
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            Util.fadeOut(mIndicatorControlContainer);
1772            Util.fadeOut(mShutterButton);
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                Util.fadeOut(findViewById(id));
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