Camera.java revision 46f4430b50ba8ca8b04b698d45d9ca2d4513121d
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                storeImage(jpegData, mLocation);
682            } else {
683                mJpegImageData = jpegData;
684                if (!mQuickCapture) {
685                    showPostCaptureAlert();
686                } else {
687                    doAttach();
688                }
689            }
690
691            // Check this in advance of each shot so we don't add to shutter
692            // latency. It's true that someone else could write to the SD card in
693            // the mean time and fill it, but that could have happened between the
694            // shutter press and saving the JPEG too.
695            checkStorage();
696
697            long now = System.currentTimeMillis();
698            mJpegCallbackFinishTime = now - mJpegPictureCallbackTime;
699            Log.v(TAG, "mJpegCallbackFinishTime = "
700                    + mJpegCallbackFinishTime + "ms");
701            mJpegPictureCallbackTime = 0;
702        }
703    }
704
705    private final class AutoFocusCallback
706            implements android.hardware.Camera.AutoFocusCallback {
707        public void onAutoFocus(
708                boolean focused, android.hardware.Camera camera) {
709            if (mPausing) return;
710
711            mAutoFocusTime = System.currentTimeMillis() - mFocusStartTime;
712            Log.v(TAG, "mAutoFocusTime = " + mAutoFocusTime + "ms");
713            mFocusManager.onAutoFocus(focused);
714            // If focus completes and the snapshot is not started, enable the
715            // controls.
716            if (mFocusManager.isFocusCompleted()) {
717                enableCameraControls(true);
718            }
719        }
720    }
721
722    private final class ZoomListener
723            implements android.hardware.Camera.OnZoomChangeListener {
724        @Override
725        public void onZoomChange(
726                int value, boolean stopped, android.hardware.Camera camera) {
727            Log.v(TAG, "Zoom changed: value=" + value + ". stopped=" + stopped);
728            mZoomValue = value;
729
730            // Update the UI when we get zoom value.
731            mZoomControl.setZoomIndex(value);
732
733            // Keep mParameters up to date. We do not getParameter again in
734            // takePicture. If we do not do this, wrong zoom value will be set.
735            mParameters.setZoom(value);
736
737            if (stopped && mZoomState != ZOOM_STOPPED) {
738                if (mTargetZoomValue != -1 && value != mTargetZoomValue) {
739                    mCameraDevice.startSmoothZoom(mTargetZoomValue);
740                    mZoomState = ZOOM_START;
741                } else {
742                    mZoomState = ZOOM_STOPPED;
743                }
744            }
745        }
746    }
747
748    private void storeImage(final byte[] data, Location loc) {
749        long dateTaken = System.currentTimeMillis();
750        String title = Util.createJpegName(dateTaken);
751        int orientation = Exif.getOrientation(data);
752        Uri uri = Storage.addImage(mContentResolver, title, dateTaken,
753                loc, orientation, data);
754        if (uri != null) {
755            // Create a thumbnail whose width is equal or bigger than that of the preview.
756            int ratio = (int) Math.ceil((double) mParameters.getPictureSize().width
757                    / mPreviewFrameLayout.getWidth());
758            int inSampleSize = Integer.highestOneBit(ratio);
759            mThumbnail = Thumbnail.createThumbnail(data, orientation, inSampleSize, uri);
760            if (mThumbnail != null) {
761                mThumbnailView.setBitmap(mThumbnail.getBitmap());
762            }
763            // Share popup may still have the reference to the old thumbnail. Clear it.
764            mSharePopup = null;
765            Util.broadcastNewPicture(this, uri);
766        }
767    }
768
769    @Override
770    public boolean capture() {
771        // If we are already in the middle of taking a snapshot then ignore.
772        if (mCameraState == SNAPSHOT_IN_PROGRESS || mCameraDevice == null) {
773            return false;
774        }
775        mCaptureStartTime = System.currentTimeMillis();
776        mPostViewPictureCallbackTime = 0;
777        enableCameraControls(false);
778        mJpegImageData = null;
779
780        // Set rotation and gps data.
781        Util.setRotationParameter(mParameters, mCameraId, mOrientation);
782        Location loc = mLocationManager.getCurrentLocation();
783        Util.setGpsParameters(mParameters, loc);
784        mCameraDevice.setParameters(mParameters);
785
786        mCameraDevice.takePicture(mShutterCallback, mRawPictureCallback,
787                mPostViewPictureCallback, new JpegPictureCallback(loc));
788        mCameraState = SNAPSHOT_IN_PROGRESS;
789        return true;
790    }
791
792    @Override
793    public void setFocusParameters() {
794        setCameraParameters(UPDATE_PARAM_PREFERENCE);
795    }
796
797    private boolean saveDataToFile(String filePath, byte[] data) {
798        FileOutputStream f = null;
799        try {
800            f = new FileOutputStream(filePath);
801            f.write(data);
802        } catch (IOException e) {
803            return false;
804        } finally {
805            Util.closeSilently(f);
806        }
807        return true;
808    }
809
810    @Override
811    public void onCreate(Bundle icicle) {
812        super.onCreate(icicle);
813
814        mIsImageCaptureIntent = isImageCaptureIntent();
815        setContentView(R.layout.camera);
816        if (mIsImageCaptureIntent) {
817            findViewById(R.id.btn_cancel).setVisibility(View.VISIBLE);
818        } else {
819            mThumbnailView = (RotateImageView) findViewById(R.id.thumbnail);
820            mThumbnailView.setVisibility(View.VISIBLE);
821        }
822
823        mPreferences = new ComboPreferences(this);
824        CameraSettings.upgradeGlobalPreferences(mPreferences.getGlobal());
825        mFocusManager = new FocusManager(mPreferences,
826                getString(R.string.pref_camera_focusmode_default));
827
828        mCameraId = CameraSettings.readPreferredCameraId(mPreferences);
829
830        // Testing purpose. Launch a specific camera through the intent extras.
831        int intentCameraId = Util.getCameraFacingIntentExtras(this);
832        if (intentCameraId != -1) {
833            mCameraId = intentCameraId;
834        }
835
836        mPreferences.setLocalId(this, mCameraId);
837        CameraSettings.upgradeLocalPreferences(mPreferences.getLocal());
838
839        mNumberOfCameras = CameraHolder.instance().getNumberOfCameras();
840        mQuickCapture = getIntent().getBooleanExtra(EXTRA_QUICK_CAPTURE, false);
841
842        // we need to reset exposure for the preview
843        resetExposureCompensation();
844
845        /*
846         * To reduce startup time, we start the preview in another thread.
847         * We make sure the preview is started at the end of onCreate.
848         */
849        Thread startPreviewThread = new Thread(new Runnable() {
850            public void run() {
851                try {
852                    mCameraDevice = Util.openCamera(Camera.this, mCameraId);
853                    initializeCapabilities();
854                    startPreview();
855                } catch (CameraHardwareException e) {
856                    mOpenCameraFail = true;
857                } catch (CameraDisabledException e) {
858                    mCameraDisabled = true;
859                }
860            }
861        });
862        startPreviewThread.start();
863
864        Util.enterLightsOutMode(getWindow());
865
866        // don't set mSurfaceHolder here. We have it set ONLY within
867        // surfaceChanged / surfaceDestroyed, other parts of the code
868        // assume that when it is set, the surface is also set.
869        SurfaceView preview = (SurfaceView) findViewById(R.id.camera_preview);
870        SurfaceHolder holder = preview.getHolder();
871        holder.addCallback(this);
872        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
873
874        if (mIsImageCaptureIntent) {
875            setupCaptureParams();
876        } else {
877            mModePicker = (ModePicker) findViewById(R.id.mode_picker);
878            mModePicker.setVisibility(View.VISIBLE);
879            mModePicker.setOnModeChangeListener(this);
880            mModePicker.setCurrentMode(ModePicker.MODE_CAMERA);
881        }
882
883        mZoomControl = (ZoomControl) findViewById(R.id.zoom_control);
884        mLocationManager = new LocationManager(this, this);
885
886        // Make sure preview is started.
887        try {
888            startPreviewThread.join();
889            if (mOpenCameraFail) {
890                Util.showErrorAndFinish(this, R.string.cannot_connect_camera);
891                return;
892            } else if (mCameraDisabled) {
893                Util.showErrorAndFinish(this, R.string.camera_disabled);
894                return;
895            }
896        } catch (InterruptedException ex) {
897            // ignore
898        }
899
900        mBackCameraId = CameraHolder.instance().getBackCameraId();
901        mFrontCameraId = CameraHolder.instance().getFrontCameraId();
902
903        // Do this after starting preview because it depends on camera
904        // parameters.
905        initializeIndicatorControl();
906    }
907
908    private void overrideCameraSettings(final String flashMode,
909            final String whiteBalance, final String focusMode) {
910        if (mIndicatorControlContainer != null) {
911            mIndicatorControlContainer.overrideSettings(
912                    CameraSettings.KEY_FLASH_MODE, flashMode,
913                    CameraSettings.KEY_WHITE_BALANCE, whiteBalance,
914                    CameraSettings.KEY_FOCUS_MODE, focusMode);
915        }
916    }
917
918    private void updateSceneModeUI() {
919        // If scene mode is set, we cannot set flash mode, white balance, and
920        // focus mode, instead, we read it from driver
921        if (!Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) {
922            overrideCameraSettings(mParameters.getFlashMode(),
923                    mParameters.getWhiteBalance(), mParameters.getFocusMode());
924        } else {
925            overrideCameraSettings(null, null, null);
926        }
927    }
928
929    private void loadCameraPreferences() {
930        CameraSettings settings = new CameraSettings(this, mInitialParams,
931                mCameraId, CameraHolder.instance().getCameraInfo());
932        mPreferenceGroup = settings.getPreferenceGroup(R.xml.camera_preferences);
933    }
934
935    private void initializeIndicatorControl() {
936        // setting the indicator buttons.
937        mIndicatorControlContainer =
938                (IndicatorControlContainer) findViewById(R.id.indicator_control);
939        if (mIndicatorControlContainer == null) return;
940        loadCameraPreferences();
941        final String[] SETTING_KEYS = {
942                CameraSettings.KEY_FLASH_MODE,
943                CameraSettings.KEY_WHITE_BALANCE,
944                CameraSettings.KEY_SCENE_MODE};
945        final String[] OTHER_SETTING_KEYS = {
946                CameraSettings.KEY_RECORD_LOCATION,
947                CameraSettings.KEY_FOCUS_MODE,
948                CameraSettings.KEY_EXPOSURE,
949                CameraSettings.KEY_PICTURE_SIZE};
950
951        CameraPicker.setImageResourceId(R.drawable.ic_switch_photo_facing_holo_light);
952        mIndicatorControlContainer.initialize(this, mPreferenceGroup,
953                mParameters.isZoomSupported(),
954                SETTING_KEYS, OTHER_SETTING_KEYS);
955        updateSceneModeUI();
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    @Override
1197    protected void onResume() {
1198        super.onResume();
1199        mPausing = false;
1200        if (mOpenCameraFail || mCameraDisabled) return;
1201
1202        mJpegPictureCallbackTime = 0;
1203        mZoomValue = 0;
1204
1205        // Start the preview if it is not started.
1206        if (mCameraState == PREVIEW_STOPPED) {
1207            try {
1208                mCameraDevice = Util.openCamera(this, mCameraId);
1209                initializeCapabilities();
1210                resetExposureCompensation();
1211                startPreview();
1212            } catch (CameraHardwareException e) {
1213                Util.showErrorAndFinish(this, R.string.cannot_connect_camera);
1214                return;
1215            } catch (CameraDisabledException e) {
1216                Util.showErrorAndFinish(this, R.string.camera_disabled);
1217                return;
1218            }
1219        }
1220
1221        if (mSurfaceHolder != null) {
1222            // If first time initialization is not finished, put it in the
1223            // message queue.
1224            if (!mFirstTimeInitialized) {
1225                mHandler.sendEmptyMessage(FIRST_TIME_INIT);
1226            } else {
1227                initializeSecondTime();
1228            }
1229        }
1230        keepScreenOnAwhile();
1231
1232        if (mCameraState == IDLE) {
1233            mOnResumeTime = SystemClock.uptimeMillis();
1234            mHandler.sendEmptyMessageDelayed(CHECK_DISPLAY_ROTATION, 100);
1235        }
1236    }
1237
1238    @Override
1239    protected void onPause() {
1240        mPausing = true;
1241        stopPreview();
1242        // Close the camera now because other activities may need to use it.
1243        closeCamera();
1244        resetScreenOn();
1245
1246        // Clear UI.
1247        collapseCameraControls();
1248        if (mSharePopup != null) mSharePopup.dismiss();
1249        if (mFaceView != null) mFaceView.clear();
1250
1251        if (mFirstTimeInitialized) {
1252            mOrientationListener.disable();
1253            if (!mIsImageCaptureIntent && mThumbnail != null && !mThumbnail.fromFile()) {
1254                mThumbnail.saveTo(new File(getFilesDir(), Thumbnail.LAST_THUMB_FILENAME));
1255            }
1256        }
1257
1258        if (mDidRegister) {
1259            unregisterReceiver(mReceiver);
1260            mDidRegister = false;
1261        }
1262        mLocationManager.recordLocation(false);
1263        updateExposureOnScreenIndicator(0);
1264
1265        mFocusManager.releaseToneGenerator();
1266
1267        if (mStorageHint != null) {
1268            mStorageHint.cancel();
1269            mStorageHint = null;
1270        }
1271
1272        // If we are in an image capture intent and has taken
1273        // a picture, we just clear it in onPause.
1274        mJpegImageData = null;
1275
1276        // Remove the messages in the event queue.
1277        mHandler.removeMessages(FIRST_TIME_INIT);
1278        mHandler.removeMessages(CHECK_DISPLAY_ROTATION);
1279        mFocusManager.removeMessages();
1280
1281        super.onPause();
1282    }
1283
1284    @Override
1285    protected void onActivityResult(
1286            int requestCode, int resultCode, Intent data) {
1287        switch (requestCode) {
1288            case CROP_MSG: {
1289                Intent intent = new Intent();
1290                if (data != null) {
1291                    Bundle extras = data.getExtras();
1292                    if (extras != null) {
1293                        intent.putExtras(extras);
1294                    }
1295                }
1296                setResultEx(resultCode, intent);
1297                finish();
1298
1299                File path = getFileStreamPath(sTempCropFilename);
1300                path.delete();
1301
1302                break;
1303            }
1304        }
1305    }
1306
1307    private boolean canTakePicture() {
1308        return isCameraIdle() && (mPicturesRemaining > 0);
1309    }
1310
1311    @Override
1312    public void autoFocus() {
1313        mFocusStartTime = System.currentTimeMillis();
1314        mCameraDevice.autoFocus(mAutoFocusCallback);
1315        mCameraState = FOCUSING;
1316        enableCameraControls(false);
1317    }
1318
1319    @Override
1320    public void cancelAutoFocus() {
1321        mCameraDevice.cancelAutoFocus();
1322        mCameraState = IDLE;
1323        enableCameraControls(true);
1324        setCameraParameters(UPDATE_PARAM_PREFERENCE);
1325    }
1326
1327    // Preview area is touched. Handle touch focus.
1328    @Override
1329    public boolean onTouch(View v, MotionEvent e) {
1330        if (mPausing || mCameraDevice == null || !mFirstTimeInitialized
1331                || mCameraState == SNAPSHOT_IN_PROGRESS) {
1332            return false;
1333        }
1334
1335        // Do not trigger touch focus if popup window is opened.
1336        if (collapseCameraControls()) return false;
1337
1338        // Check if metering area or focus area is supported.
1339        if (!mFocusAreaSupported && !mMeteringAreaSupported) return false;
1340
1341        return mFocusManager.onTouch(e);
1342    }
1343
1344    @Override
1345    public void onBackPressed() {
1346        if (!isCameraIdle()) {
1347            // ignore backs while we're taking a picture
1348            return;
1349        } else if (!collapseCameraControls()) {
1350            super.onBackPressed();
1351        }
1352    }
1353
1354    @Override
1355    public boolean onKeyDown(int keyCode, KeyEvent event) {
1356        switch (keyCode) {
1357            case KeyEvent.KEYCODE_FOCUS:
1358                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1359                    doFocus(true);
1360                }
1361                return true;
1362            case KeyEvent.KEYCODE_CAMERA:
1363                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1364                    doSnap();
1365                }
1366                return true;
1367            case KeyEvent.KEYCODE_DPAD_CENTER:
1368                // If we get a dpad center event without any focused view, move
1369                // the focus to the shutter button and press it.
1370                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1371                    // Start auto-focus immediately to reduce shutter lag. After
1372                    // the shutter button gets the focus, doFocus() will be
1373                    // called again but it is fine.
1374                    if (collapseCameraControls()) return true;
1375                    doFocus(true);
1376                    if (mShutterButton.isInTouchMode()) {
1377                        mShutterButton.requestFocusFromTouch();
1378                    } else {
1379                        mShutterButton.requestFocus();
1380                    }
1381                    mShutterButton.setPressed(true);
1382                }
1383                return true;
1384        }
1385
1386        return super.onKeyDown(keyCode, event);
1387    }
1388
1389    @Override
1390    public boolean onKeyUp(int keyCode, KeyEvent event) {
1391        switch (keyCode) {
1392            case KeyEvent.KEYCODE_FOCUS:
1393                if (mFirstTimeInitialized) {
1394                    doFocus(false);
1395                }
1396                return true;
1397        }
1398        return super.onKeyUp(keyCode, event);
1399    }
1400
1401    private void doSnap() {
1402        if (mPausing || collapseCameraControls()) return;
1403
1404        // Do not take the picture if there is not enough storage.
1405        if (mPicturesRemaining <= 0) {
1406            Log.i(TAG, "Not enough space or storage not ready. remaining=" + mPicturesRemaining);
1407            return;
1408        }
1409
1410        Log.v(TAG, "doSnap: mCameraState=" + mCameraState);
1411        mFocusManager.doSnap();
1412    }
1413
1414    private void doFocus(boolean pressed) {
1415        if (mPausing || collapseCameraControls() || mCameraState == SNAPSHOT_IN_PROGRESS) return;
1416
1417        // Do not do focus if there is not enough storage.
1418        if (pressed && !canTakePicture()) return;
1419
1420        // Lock AE and AWB so users can half-press shutter and recompose.
1421        mAeAwbLock = pressed;
1422        setCameraParameters(UPDATE_PARAM_PREFERENCE);
1423        mFocusManager.doFocus(pressed);
1424    }
1425
1426    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
1427        // Make sure we have a surface in the holder before proceeding.
1428        if (holder.getSurface() == null) {
1429            Log.d(TAG, "holder.getSurface() == null");
1430            return;
1431        }
1432
1433        Log.v(TAG, "surfaceChanged. w=" + w + ". h=" + h);
1434
1435        // We need to save the holder for later use, even when the mCameraDevice
1436        // is null. This could happen if onResume() is invoked after this
1437        // function.
1438        mSurfaceHolder = holder;
1439
1440        // The mCameraDevice will be null if it fails to connect to the camera
1441        // hardware. In this case we will show a dialog and then finish the
1442        // activity, so it's OK to ignore it.
1443        if (mCameraDevice == null) return;
1444
1445        // Sometimes surfaceChanged is called after onPause or before onResume.
1446        // Ignore it.
1447        if (mPausing || isFinishing()) return;
1448
1449        // Set preview display if the surface is being created. Preview was
1450        // already started. Also restart the preview if display rotation has
1451        // changed. Sometimes this happens when the device is held in portrait
1452        // and camera app is opened. Rotation animation takes some time and
1453        // display rotation in onCreate may not be what we want.
1454        if (mCameraState != PREVIEW_STOPPED
1455                && (Util.getDisplayRotation(this) == mDisplayRotation)
1456                && holder.isCreating()) {
1457            // Set preview display if the surface is being created and preview
1458            // was already started. That means preview display was set to null
1459            // and we need to set it now.
1460            setPreviewDisplay(holder);
1461        } else {
1462            // 1. Restart the preview if the size of surface was changed. The
1463            // framework may not support changing preview display on the fly.
1464            // 2. Start the preview now if surface was destroyed and preview
1465            // stopped.
1466            startPreview();
1467        }
1468
1469        // If first time initialization is not finished, send a message to do
1470        // it later. We want to finish surfaceChanged as soon as possible to let
1471        // user see preview first.
1472        if (!mFirstTimeInitialized) {
1473            mHandler.sendEmptyMessage(FIRST_TIME_INIT);
1474        } else {
1475            initializeSecondTime();
1476        }
1477    }
1478
1479    public void surfaceCreated(SurfaceHolder holder) {
1480    }
1481
1482    public void surfaceDestroyed(SurfaceHolder holder) {
1483        stopPreview();
1484        mSurfaceHolder = null;
1485    }
1486
1487    private void closeCamera() {
1488        if (mCameraDevice != null) {
1489            mCameraDevice.cancelAutoFocus(); // Reset the focus.
1490            CameraHolder.instance().release();
1491            mCameraDevice.setZoomChangeListener(null);
1492            mCameraDevice.setFaceDetectionListener(null);
1493            mCameraDevice.setErrorCallback(null);
1494            mCameraDevice = null;
1495            mCameraState = PREVIEW_STOPPED;
1496            mFocusManager.onCameraReleased();
1497        }
1498    }
1499
1500    private void setPreviewDisplay(SurfaceHolder holder) {
1501        try {
1502            mCameraDevice.setPreviewDisplay(holder);
1503        } catch (Throwable ex) {
1504            closeCamera();
1505            throw new RuntimeException("setPreviewDisplay failed", ex);
1506        }
1507    }
1508
1509    private void startPreview() {
1510        if (mPausing || isFinishing()) return;
1511
1512        mFocusManager.resetTouchFocus();
1513
1514        mCameraDevice.setErrorCallback(mErrorCallback);
1515
1516        // If we're previewing already, stop the preview first (this will blank
1517        // the screen).
1518        if (mCameraState != PREVIEW_STOPPED) stopPreview();
1519
1520        setPreviewDisplay(mSurfaceHolder);
1521        mDisplayRotation = Util.getDisplayRotation(this);
1522        mDisplayOrientation = Util.getDisplayOrientation(mDisplayRotation, mCameraId);
1523        mCameraDevice.setDisplayOrientation(mDisplayOrientation);
1524        if (mFaceView != null) {
1525            mFaceView.setDisplayOrientation(mDisplayOrientation);
1526        }
1527        mAeAwbLock = false; // Always unlock AE and AWB before start.
1528        setCameraParameters(UPDATE_PARAM_ALL);
1529        // If the focus mode is continuous autofocus, call cancelAutoFocus to
1530        // resume it because it may have been paused by autoFocus call.
1531        if (Parameters.FOCUS_MODE_CONTINUOUS_PICTURE.equals(mParameters.getFocusMode())) {
1532            mCameraDevice.cancelAutoFocus();
1533        }
1534
1535        try {
1536            Log.v(TAG, "startPreview");
1537            mCameraDevice.startPreview();
1538        } catch (Throwable ex) {
1539            closeCamera();
1540            throw new RuntimeException("startPreview failed", ex);
1541        }
1542
1543        startFaceDetection();
1544        mZoomState = ZOOM_STOPPED;
1545        mCameraState = IDLE;
1546        mFocusManager.onPreviewStarted();
1547    }
1548
1549    private void stopPreview() {
1550        if (mCameraDevice != null && mCameraState != PREVIEW_STOPPED) {
1551            Log.v(TAG, "stopPreview");
1552            mCameraDevice.stopPreview();
1553        }
1554        mCameraState = PREVIEW_STOPPED;
1555        mFocusManager.onPreviewStopped();
1556    }
1557
1558    private static boolean isSupported(String value, List<String> supported) {
1559        return supported == null ? false : supported.indexOf(value) >= 0;
1560    }
1561
1562    private void updateCameraParametersInitialize() {
1563        // Reset preview frame rate to the maximum because it may be lowered by
1564        // video camera application.
1565        List<Integer> frameRates = mParameters.getSupportedPreviewFrameRates();
1566        if (frameRates != null) {
1567            Integer max = Collections.max(frameRates);
1568            mParameters.setPreviewFrameRate(max);
1569        }
1570
1571        mParameters.setRecordingHint(false);
1572    }
1573
1574    private void updateCameraParametersZoom() {
1575        // Set zoom.
1576        if (mParameters.isZoomSupported()) {
1577            mParameters.setZoom(mZoomValue);
1578        }
1579    }
1580
1581    private void updateCameraParametersPreference() {
1582        if (mAwbLockSupported) {
1583            mParameters.setAutoWhiteBalanceLock(mAeAwbLock);
1584        }
1585
1586        if (mAeLockSupported) {
1587            mParameters.setAutoExposureLock(mAeAwbLock);
1588        }
1589
1590        if (mFocusAreaSupported) {
1591            mParameters.setFocusAreas(mFocusManager.getTapArea());
1592        }
1593
1594        if (mMeteringAreaSupported) {
1595            // Use the same area for focus and metering.
1596            mParameters.setMeteringAreas(mFocusManager.getTapArea());
1597        }
1598
1599        // Set picture size.
1600        String pictureSize = mPreferences.getString(
1601                CameraSettings.KEY_PICTURE_SIZE, null);
1602        if (pictureSize == null) {
1603            CameraSettings.initialCameraPictureSize(this, mParameters);
1604        } else {
1605            List<Size> supported = mParameters.getSupportedPictureSizes();
1606            CameraSettings.setCameraPictureSize(
1607                    pictureSize, supported, mParameters);
1608        }
1609
1610        // Set the preview frame aspect ratio according to the picture size.
1611        Size size = mParameters.getPictureSize();
1612
1613        mPreviewPanel = findViewById(R.id.frame_layout);
1614        mPreviewFrameLayout = (PreviewFrameLayout) findViewById(R.id.frame);
1615        mPreviewFrameLayout.setAspectRatio((double) size.width / size.height);
1616
1617        // Set a preview size that is closest to the viewfinder height and has
1618        // the right aspect ratio.
1619        List<Size> sizes = mParameters.getSupportedPreviewSizes();
1620        Size optimalSize = Util.getOptimalPreviewSize(this,
1621                sizes, (double) size.width / size.height);
1622        Size original = mParameters.getPreviewSize();
1623        if (!original.equals(optimalSize)) {
1624            mParameters.setPreviewSize(optimalSize.width, optimalSize.height);
1625
1626            // Zoom related settings will be changed for different preview
1627            // sizes, so set and read the parameters to get lastest values
1628            mCameraDevice.setParameters(mParameters);
1629            mParameters = mCameraDevice.getParameters();
1630        }
1631        Log.v(TAG, "Preview size is " + optimalSize.width + "x" + optimalSize.height);
1632
1633        // Since change scene mode may change supported values,
1634        // Set scene mode first,
1635        mSceneMode = mPreferences.getString(
1636                CameraSettings.KEY_SCENE_MODE,
1637                getString(R.string.pref_camera_scenemode_default));
1638        if (isSupported(mSceneMode, mParameters.getSupportedSceneModes())) {
1639            if (!mParameters.getSceneMode().equals(mSceneMode)) {
1640                mParameters.setSceneMode(mSceneMode);
1641                mCameraDevice.setParameters(mParameters);
1642
1643                // Setting scene mode will change the settings of flash mode,
1644                // white balance, and focus mode. Here we read back the
1645                // parameters, so we can know those settings.
1646                mParameters = mCameraDevice.getParameters();
1647            }
1648        } else {
1649            mSceneMode = mParameters.getSceneMode();
1650            if (mSceneMode == null) {
1651                mSceneMode = Parameters.SCENE_MODE_AUTO;
1652            }
1653        }
1654
1655        // Set JPEG quality.
1656        int jpegQuality = CameraProfile.getJpegEncodingQualityParameter(mCameraId,
1657                CameraProfile.QUALITY_HIGH);
1658        mParameters.setJpegQuality(jpegQuality);
1659
1660        // For the following settings, we need to check if the settings are
1661        // still supported by latest driver, if not, ignore the settings.
1662
1663        // Set exposure compensation
1664        int value = CameraSettings.readExposure(mPreferences);
1665        int max = mParameters.getMaxExposureCompensation();
1666        int min = mParameters.getMinExposureCompensation();
1667        if (value >= min && value <= max) {
1668            mParameters.setExposureCompensation(value);
1669        } else {
1670            Log.w(TAG, "invalid exposure range: " + value);
1671        }
1672
1673        if (Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) {
1674            // Set flash mode.
1675            String flashMode = mPreferences.getString(
1676                    CameraSettings.KEY_FLASH_MODE,
1677                    getString(R.string.pref_camera_flashmode_default));
1678            List<String> supportedFlash = mParameters.getSupportedFlashModes();
1679            if (isSupported(flashMode, supportedFlash)) {
1680                mParameters.setFlashMode(flashMode);
1681            } else {
1682                flashMode = mParameters.getFlashMode();
1683                if (flashMode == null) {
1684                    flashMode = getString(
1685                            R.string.pref_camera_flashmode_no_flash);
1686                }
1687            }
1688
1689            // Set white balance parameter.
1690            String whiteBalance = mPreferences.getString(
1691                    CameraSettings.KEY_WHITE_BALANCE,
1692                    getString(R.string.pref_camera_whitebalance_default));
1693            if (isSupported(whiteBalance,
1694                    mParameters.getSupportedWhiteBalance())) {
1695                mParameters.setWhiteBalance(whiteBalance);
1696            } else {
1697                whiteBalance = mParameters.getWhiteBalance();
1698                if (whiteBalance == null) {
1699                    whiteBalance = Parameters.WHITE_BALANCE_AUTO;
1700                }
1701            }
1702
1703            // Set focus mode.
1704            mFocusManager.overrideFocusMode(null);
1705            mParameters.setFocusMode(mFocusManager.getFocusMode());
1706        } else {
1707            mFocusManager.overrideFocusMode(mParameters.getFocusMode());
1708        }
1709    }
1710
1711    // We separate the parameters into several subsets, so we can update only
1712    // the subsets actually need updating. The PREFERENCE set needs extra
1713    // locking because the preference can be changed from GLThread as well.
1714    private void setCameraParameters(int updateSet) {
1715        mParameters = mCameraDevice.getParameters();
1716
1717        if ((updateSet & UPDATE_PARAM_INITIALIZE) != 0) {
1718            updateCameraParametersInitialize();
1719        }
1720
1721        if ((updateSet & UPDATE_PARAM_ZOOM) != 0) {
1722            updateCameraParametersZoom();
1723        }
1724
1725        if ((updateSet & UPDATE_PARAM_PREFERENCE) != 0) {
1726            updateCameraParametersPreference();
1727        }
1728
1729        mCameraDevice.setParameters(mParameters);
1730    }
1731
1732    // If the Camera is idle, update the parameters immediately, otherwise
1733    // accumulate them in mUpdateSet and update later.
1734    private void setCameraParametersWhenIdle(int additionalUpdateSet) {
1735        mUpdateSet |= additionalUpdateSet;
1736        if (mCameraDevice == null) {
1737            // We will update all the parameters when we open the device, so
1738            // we don't need to do anything now.
1739            mUpdateSet = 0;
1740            return;
1741        } else if (isCameraIdle()) {
1742            setCameraParameters(mUpdateSet);
1743            updateSceneModeUI();
1744            mUpdateSet = 0;
1745        } else {
1746            if (!mHandler.hasMessages(SET_CAMERA_PARAMETERS_WHEN_IDLE)) {
1747                mHandler.sendEmptyMessageDelayed(
1748                        SET_CAMERA_PARAMETERS_WHEN_IDLE, 1000);
1749            }
1750        }
1751    }
1752
1753    private void gotoGallery() {
1754        MenuHelper.gotoCameraImageGallery(this);
1755    }
1756
1757    private boolean isCameraIdle() {
1758        return (mCameraState == IDLE) || (mFocusManager.isFocusCompleted());
1759    }
1760
1761    private boolean isImageCaptureIntent() {
1762        String action = getIntent().getAction();
1763        return (MediaStore.ACTION_IMAGE_CAPTURE.equals(action));
1764    }
1765
1766    private void setupCaptureParams() {
1767        Bundle myExtras = getIntent().getExtras();
1768        if (myExtras != null) {
1769            mSaveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT);
1770            mCropValue = myExtras.getString("crop");
1771        }
1772    }
1773
1774    private void showPostCaptureAlert() {
1775        if (mIsImageCaptureIntent) {
1776            Util.fadeOut(mIndicatorControlContainer);
1777            Util.fadeOut(mShutterButton);
1778
1779            int[] pickIds = {R.id.btn_retake, R.id.btn_done};
1780            for (int id : pickIds) {
1781                Util.fadeIn(findViewById(id));
1782            }
1783        }
1784    }
1785
1786    private void hidePostCaptureAlert() {
1787        if (mIsImageCaptureIntent) {
1788            enableCameraControls(true);
1789
1790            int[] pickIds = {R.id.btn_retake, R.id.btn_done};
1791            for (int id : pickIds) {
1792                Util.fadeOut(findViewById(id));
1793            }
1794
1795            Util.fadeIn(mShutterButton);
1796            Util.fadeIn(mIndicatorControlContainer);
1797        }
1798    }
1799
1800    @Override
1801    public boolean onPrepareOptionsMenu(Menu menu) {
1802        super.onPrepareOptionsMenu(menu);
1803        // Only show the menu when camera is idle.
1804        for (int i = 0; i < menu.size(); i++) {
1805            menu.getItem(i).setVisible(isCameraIdle());
1806        }
1807
1808        return true;
1809    }
1810
1811    @Override
1812    public boolean onCreateOptionsMenu(Menu menu) {
1813        super.onCreateOptionsMenu(menu);
1814
1815        if (mIsImageCaptureIntent) {
1816            // No options menu for attach mode.
1817            return false;
1818        } else {
1819            addBaseMenuItems(menu);
1820        }
1821        return true;
1822    }
1823
1824    private void addBaseMenuItems(Menu menu) {
1825        MenuHelper.addSwitchModeMenuItem(menu, ModePicker.MODE_VIDEO, new Runnable() {
1826            public void run() {
1827                switchToOtherMode(ModePicker.MODE_VIDEO);
1828            }
1829        });
1830        MenuHelper.addSwitchModeMenuItem(menu, ModePicker.MODE_PANORAMA, new Runnable() {
1831            public void run() {
1832                switchToOtherMode(ModePicker.MODE_PANORAMA);
1833            }
1834        });
1835
1836        if (mNumberOfCameras > 1) {
1837            menu.add(R.string.switch_camera_id)
1838                    .setOnMenuItemClickListener(new OnMenuItemClickListener() {
1839                public boolean onMenuItemClick(MenuItem item) {
1840                    CameraSettings.writePreferredCameraId(mPreferences,
1841                            ((mCameraId == mFrontCameraId)
1842                            ? mBackCameraId : mFrontCameraId));
1843                    onSharedPreferenceChanged();
1844                    return true;
1845                }
1846            }).setIcon(android.R.drawable.ic_menu_camera);
1847        }
1848    }
1849
1850    private boolean switchToOtherMode(int mode) {
1851        if (isFinishing()) return false;
1852        MenuHelper.gotoMode(mode, Camera.this);
1853        mHandler.removeMessages(FIRST_TIME_INIT);
1854        finish();
1855        return true;
1856    }
1857
1858    public boolean onModeChanged(int mode) {
1859        if (mode != ModePicker.MODE_CAMERA) {
1860            return switchToOtherMode(mode);
1861        } else {
1862            return true;
1863        }
1864    }
1865
1866    public void onSharedPreferenceChanged() {
1867        // ignore the events after "onPause()"
1868        if (mPausing) return;
1869
1870        boolean recordLocation = RecordLocationPreference.get(
1871                mPreferences, getContentResolver());
1872        mLocationManager.recordLocation(recordLocation);
1873
1874        int cameraId = CameraSettings.readPreferredCameraId(mPreferences);
1875        if (mCameraId != cameraId) {
1876            // Restart the activity to have a crossfade animation.
1877            // TODO: Use SurfaceTexture to implement a better and faster
1878            // animation.
1879            if (mIsImageCaptureIntent) {
1880                // If the intent is camera capture, stay in camera capture mode.
1881                MenuHelper.gotoCameraMode(this, getIntent());
1882            } else {
1883                MenuHelper.gotoCameraMode(this);
1884            }
1885
1886            finish();
1887        } else {
1888            setCameraParametersWhenIdle(UPDATE_PARAM_PREFERENCE);
1889        }
1890
1891        int exposureValue = CameraSettings.readExposure(mPreferences);
1892        updateExposureOnScreenIndicator(exposureValue);
1893    }
1894
1895    @Override
1896    public void onUserInteraction() {
1897        super.onUserInteraction();
1898        keepScreenOnAwhile();
1899    }
1900
1901    private void resetScreenOn() {
1902        mHandler.removeMessages(CLEAR_SCREEN_DELAY);
1903        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1904    }
1905
1906    private void keepScreenOnAwhile() {
1907        mHandler.removeMessages(CLEAR_SCREEN_DELAY);
1908        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1909        mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY);
1910    }
1911
1912    public void onRestorePreferencesClicked() {
1913        if (mPausing) return;
1914        Runnable runnable = new Runnable() {
1915            public void run() {
1916                restorePreferences();
1917            }
1918        };
1919        MenuHelper.confirmAction(this,
1920                getString(R.string.confirm_restore_title),
1921                getString(R.string.confirm_restore_message),
1922                runnable);
1923    }
1924
1925    private void restorePreferences() {
1926        // Reset the zoom. Zoom value is not stored in preference.
1927        if (mParameters.isZoomSupported()) {
1928            mZoomValue = 0;
1929            setCameraParametersWhenIdle(UPDATE_PARAM_ZOOM);
1930            mZoomControl.setZoomIndex(0);
1931        }
1932        if (mIndicatorControlContainer != null) {
1933            mIndicatorControlContainer.dismissSettingPopup();
1934            CameraSettings.restorePreferences(Camera.this, mPreferences,
1935                    mParameters);
1936            mIndicatorControlContainer.reloadPreferences();
1937            onSharedPreferenceChanged();
1938        }
1939    }
1940
1941    public void onOverriddenPreferencesClicked() {
1942        if (mPausing) return;
1943        if (mNotSelectableToast == null) {
1944            String str = getResources().getString(R.string.not_selectable_in_scene_mode);
1945            mNotSelectableToast = Toast.makeText(Camera.this, str, Toast.LENGTH_SHORT);
1946        }
1947        mNotSelectableToast.show();
1948    }
1949
1950    private void showSharePopup() {
1951        Uri uri = mThumbnail.getUri();
1952        if (mSharePopup == null || !uri.equals(mSharePopup.getUri())) {
1953            // SharePopup window takes the mPreviewPanel as its size reference.
1954            mSharePopup = new SharePopup(this, uri, mThumbnail.getBitmap(),
1955                    mOrientationCompensation, mPreviewPanel);
1956        }
1957        mSharePopup.showAtLocation(mThumbnailView, Gravity.NO_GRAVITY, 0, 0);
1958    }
1959
1960    @Override
1961    public void onFaceDetection(Face[] faces, android.hardware.Camera camera) {
1962        mFaceView.setFaces(faces);
1963    }
1964
1965    private void showTapToFocusToast() {
1966        // Show the toast.
1967        RotateLayout v = (RotateLayout) findViewById(R.id.tap_to_focus_prompt);
1968        v.setOrientation(mOrientationCompensation);
1969        v.startAnimation(AnimationUtils.loadAnimation(this, R.anim.on_screen_hint_enter));
1970        v.setVisibility(View.VISIBLE);
1971        mHandler.sendEmptyMessageDelayed(DISMISS_TAP_TO_FOCUS_TOAST, 5000);
1972        // Clear the preference.
1973        Editor editor = mPreferences.edit();
1974        editor.putBoolean(CameraSettings.KEY_TAP_TO_FOCUS_PROMPT_SHOWN, false);
1975        editor.apply();
1976    }
1977
1978    private void initializeCapabilities() {
1979        mInitialParams = mCameraDevice.getParameters();
1980        mFocusManager.initializeParameters(mInitialParams);
1981        mFocusAreaSupported = (mInitialParams.getMaxNumFocusAreas() > 0
1982                && isSupported(Parameters.FOCUS_MODE_AUTO,
1983                        mInitialParams.getSupportedFocusModes()));
1984        mMeteringAreaSupported = (mInitialParams.getMaxNumMeteringAreas() > 0);
1985        mAwbLockSupported = mInitialParams.isAutoWhiteBalanceLockSupported();
1986        mAeLockSupported = mInitialParams.isAutoExposureLockSupported();
1987    }
1988}
1989