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