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