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