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