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