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