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