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