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