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