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