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