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