Camera.java revision af40ad5126da5b116440e015fbc3cfb55ff437d4
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                showGpsOnScreenIndicator(true);
648            }
649            if (!mValid) {
650                Log.d(TAG, "Got first location.");
651            }
652            mLastLocation.set(newLocation);
653            mValid = true;
654        }
655
656        public void onProviderEnabled(String provider) {
657        }
658
659        public void onProviderDisabled(String provider) {
660            mValid = false;
661        }
662
663        public void onStatusChanged(
664                String provider, int status, Bundle extras) {
665            switch(status) {
666                case LocationProvider.OUT_OF_SERVICE:
667                case LocationProvider.TEMPORARILY_UNAVAILABLE: {
668                    mValid = false;
669                    if (mRecordLocation &&
670                            LocationManager.GPS_PROVIDER.equals(provider)) {
671                        showGpsOnScreenIndicator(false);
672                    }
673                    break;
674                }
675            }
676        }
677
678        public Location current() {
679            return mValid ? mLastLocation : null;
680        }
681    }
682
683    private final class ShutterCallback
684            implements android.hardware.Camera.ShutterCallback {
685        public void onShutter() {
686            mShutterCallbackTime = System.currentTimeMillis();
687            mShutterLag = mShutterCallbackTime - mCaptureStartTime;
688            Log.v(TAG, "mShutterLag = " + mShutterLag + "ms");
689            updateFocusUI();
690        }
691    }
692
693    private final class PostViewPictureCallback implements PictureCallback {
694        public void onPictureTaken(
695                byte [] data, android.hardware.Camera camera) {
696            mPostViewPictureCallbackTime = System.currentTimeMillis();
697            Log.v(TAG, "mShutterToPostViewCallbackTime = "
698                    + (mPostViewPictureCallbackTime - mShutterCallbackTime)
699                    + "ms");
700        }
701    }
702
703    private final class RawPictureCallback implements PictureCallback {
704        public void onPictureTaken(
705                byte [] rawData, android.hardware.Camera camera) {
706            mRawPictureCallbackTime = System.currentTimeMillis();
707            Log.v(TAG, "mShutterToRawCallbackTime = "
708                    + (mRawPictureCallbackTime - mShutterCallbackTime) + "ms");
709        }
710    }
711
712    private final class JpegPictureCallback implements PictureCallback {
713        Location mLocation;
714
715        public JpegPictureCallback(Location loc) {
716            mLocation = loc;
717        }
718
719        public void onPictureTaken(
720                final byte [] jpegData, final android.hardware.Camera camera) {
721            if (mPausing) {
722                return;
723            }
724
725            mJpegPictureCallbackTime = System.currentTimeMillis();
726            // If postview callback has arrived, the captured image is displayed
727            // in postview callback. If not, the captured image is displayed in
728            // raw picture callback.
729            if (mPostViewPictureCallbackTime != 0) {
730                mShutterToPictureDisplayedTime =
731                        mPostViewPictureCallbackTime - mShutterCallbackTime;
732                mPictureDisplayedToJpegCallbackTime =
733                        mJpegPictureCallbackTime - mPostViewPictureCallbackTime;
734            } else {
735                mShutterToPictureDisplayedTime =
736                        mRawPictureCallbackTime - mShutterCallbackTime;
737                mPictureDisplayedToJpegCallbackTime =
738                        mJpegPictureCallbackTime - mRawPictureCallbackTime;
739            }
740            Log.v(TAG, "mPictureDisplayedToJpegCallbackTime = "
741                    + mPictureDisplayedToJpegCallbackTime + "ms");
742
743            if (!mIsImageCaptureIntent) {
744                enableCameraControls(true);
745
746                // We want to show the taken picture for a while, so we wait
747                // for at least 1.2 second before restarting the preview.
748                long delay = 1200 - mPictureDisplayedToJpegCallbackTime;
749                if (delay < 0) {
750                    restartPreview();
751                } else {
752                    mHandler.sendEmptyMessageDelayed(RESTART_PREVIEW, delay);
753                }
754            }
755            storeImage(jpegData, camera, mLocation);
756
757            // Check this in advance of each shot so we don't add to shutter
758            // latency. It's true that someone else could write to the SD card in
759            // the mean time and fill it, but that could have happened between the
760            // shutter press and saving the JPEG too.
761            checkStorage();
762
763            if (!mHandler.hasMessages(RESTART_PREVIEW)) {
764                long now = System.currentTimeMillis();
765                mJpegCallbackFinishTime = now - mJpegPictureCallbackTime;
766                Log.v(TAG, "mJpegCallbackFinishTime = "
767                        + mJpegCallbackFinishTime + "ms");
768                mJpegPictureCallbackTime = 0;
769            }
770        }
771    }
772
773    private final class AutoFocusCallback
774            implements android.hardware.Camera.AutoFocusCallback {
775        public void onAutoFocus(
776                boolean focused, android.hardware.Camera camera) {
777            mFocusCallbackTime = System.currentTimeMillis();
778            mAutoFocusTime = mFocusCallbackTime - mFocusStartTime;
779            Log.v(TAG, "mAutoFocusTime = " + mAutoFocusTime + "ms");
780            if (mCameraState == FOCUSING_SNAP_ON_FINISH) {
781                // Take the picture no matter focus succeeds or fails. No need
782                // to play the AF sound if we're about to play the shutter
783                // sound.
784                if (focused) {
785                    mCameraState = FOCUS_SUCCESS;
786                } else {
787                    mCameraState = FOCUS_FAIL;
788                }
789                updateFocusUI();
790                capture();
791            } else if (mCameraState == FOCUSING) {
792                // This happens when (1) user is half-pressing the focus key or
793                // (2) touch focus is triggered. Play the focus tone. Do not
794                // take the picture now.
795                if (focused) {
796                    mCameraState = FOCUS_SUCCESS;
797                    if (mFocusToneGenerator != null) {
798                        mFocusToneGenerator.startTone(ToneGenerator.TONE_PROP_BEEP2);
799                    }
800                } else {
801                    mCameraState = FOCUS_FAIL;
802                }
803                updateFocusUI();
804                enableCameraControls(true);
805                // If this is triggered by touch focus, cancel focus after a
806                // while.
807                if (mFocusArea != null) {
808                    mHandler.sendEmptyMessageDelayed(CANCEL_AUTOFOCUS, 3000);
809                }
810            } else if (mCameraState == IDLE) {
811                // User has released the focus key before focus completes.
812                // Do nothing.
813            }
814
815        }
816    }
817
818    private final class ZoomListener
819            implements android.hardware.Camera.OnZoomChangeListener {
820        public void onZoomChange(
821                int value, boolean stopped, android.hardware.Camera camera) {
822            Log.v(TAG, "Zoom changed: value=" + value + ". stopped="+ stopped);
823            mZoomValue = value;
824
825            // Update the UI when we get zoom value.
826            if (mZoomPicker != null) mZoomPicker.setZoomIndex(value);
827
828            // Keep mParameters up to date. We do not getParameter again in
829            // takePicture. If we do not do this, wrong zoom value will be set.
830            mParameters.setZoom(value);
831
832            if (stopped && mZoomState != ZOOM_STOPPED) {
833                if (mTargetZoomValue != -1 && value != mTargetZoomValue) {
834                    mCameraDevice.startSmoothZoom(mTargetZoomValue);
835                    mZoomState = ZOOM_START;
836                } else {
837                    mZoomState = ZOOM_STOPPED;
838                }
839            }
840        }
841    }
842
843    public void storeImage(final byte[] data,
844            android.hardware.Camera camera, Location loc) {
845        if (!mIsImageCaptureIntent) {
846            long dateTaken = System.currentTimeMillis();
847            String title = createName(dateTaken);
848            int orientation = Exif.getOrientation(data);
849            Uri uri = Storage.addImage(mContentResolver, title, dateTaken,
850                    loc, orientation, data);
851            if (uri != null) {
852                // Create a thumbnail whose size is smaller than half of the surface view.
853                int ratio = (int) Math.ceil((double) mParameters.getPictureSize().width
854                        / (mPreviewFrame.getWidth() / 2));
855                int inSampleSize = Util.nextPowerOf2(ratio);
856                mThumbnail = Thumbnail.createThumbnail(data, orientation, inSampleSize, uri);
857                if (mThumbnail != null) {
858                    mThumbnailButton.setBitmap(mThumbnail.getBitmap());
859                }
860                sendBroadcast(new Intent("com.android.camera.NEW_PICTURE", uri));
861            }
862        } else {
863            mJpegImageData = data;
864            if (!mQuickCapture) {
865                showPostCaptureAlert();
866            } else {
867                doAttach();
868            }
869        }
870    }
871
872    private void capture() {
873        // If we are already in the middle of taking a snapshot then ignore.
874        if (mPausing || mCameraState == SNAPSHOT_IN_PROGRESS || mCameraDevice == null) {
875            return;
876        }
877        mCaptureStartTime = System.currentTimeMillis();
878        mPostViewPictureCallbackTime = 0;
879        enableCameraControls(false);
880        mJpegImageData = null;
881
882        // See android.hardware.Camera.Parameters.setRotation for
883        // documentation.
884        int rotation = 0;
885        if (mOrientation != OrientationEventListener.ORIENTATION_UNKNOWN) {
886            CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId];
887            if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
888                rotation = (info.orientation - mOrientation + 360) % 360;
889            } else {  // back-facing camera
890                rotation = (info.orientation + mOrientation) % 360;
891            }
892        }
893        mParameters.setRotation(rotation);
894
895        // Clear previous GPS location from the parameters.
896        mParameters.removeGpsData();
897
898        // We always encode GpsTimeStamp
899        mParameters.setGpsTimestamp(System.currentTimeMillis() / 1000);
900
901        // Set GPS location.
902        Location loc = mRecordLocation ? getCurrentLocation() : null;
903        if (loc != null) {
904            double lat = loc.getLatitude();
905            double lon = loc.getLongitude();
906            boolean hasLatLon = (lat != 0.0d) || (lon != 0.0d);
907
908            if (hasLatLon) {
909                Log.d(TAG, "Set gps location");
910                mParameters.setGpsLatitude(lat);
911                mParameters.setGpsLongitude(lon);
912                mParameters.setGpsProcessingMethod(loc.getProvider().toUpperCase());
913                if (loc.hasAltitude()) {
914                    mParameters.setGpsAltitude(loc.getAltitude());
915                } else {
916                    // for NETWORK_PROVIDER location provider, we may have
917                    // no altitude information, but the driver needs it, so
918                    // we fake one.
919                    mParameters.setGpsAltitude(0);
920                }
921                if (loc.getTime() != 0) {
922                    // Location.getTime() is UTC in milliseconds.
923                    // gps-timestamp is UTC in seconds.
924                    long utcTimeSeconds = loc.getTime() / 1000;
925                    mParameters.setGpsTimestamp(utcTimeSeconds);
926                }
927            } else {
928                loc = null;
929            }
930        }
931
932        mCameraDevice.setParameters(mParameters);
933
934        mCameraDevice.takePicture(mShutterCallback, mRawPictureCallback,
935                mPostViewPictureCallback, new JpegPictureCallback(loc));
936        mCameraState = SNAPSHOT_IN_PROGRESS;
937        mHandler.removeMessages(CANCEL_AUTOFOCUS);
938    }
939
940    private boolean saveDataToFile(String filePath, byte[] data) {
941        FileOutputStream f = null;
942        try {
943            f = new FileOutputStream(filePath);
944            f.write(data);
945        } catch (IOException e) {
946            return false;
947        } finally {
948            Util.closeSilently(f);
949        }
950        return true;
951    }
952
953    private String createName(long dateTaken) {
954        Date date = new Date(dateTaken);
955        SimpleDateFormat dateFormat = new SimpleDateFormat(
956                getString(R.string.image_file_name_format));
957
958        return dateFormat.format(date);
959    }
960
961    @Override
962    public void onCreate(Bundle icicle) {
963        super.onCreate(icicle);
964
965        mIsImageCaptureIntent = isImageCaptureIntent();
966        if (mIsImageCaptureIntent) {
967            setContentView(R.layout.camera_attach);
968        } else {
969            setContentView(R.layout.camera);
970        }
971        mFocusRectangle = (FocusRectangle) findViewById(R.id.focus_rectangle);
972        mThumbnailButton = (RotateImageView) findViewById(R.id.review_thumbnail);
973        mReviewImage = (ImageView) findViewById(R.id.review_image);
974
975        mPreferences = new ComboPreferences(this);
976        CameraSettings.upgradeGlobalPreferences(mPreferences.getGlobal());
977
978        mCameraId = CameraSettings.readPreferredCameraId(mPreferences);
979
980        // Testing purpose. Launch a specific camera through the intent extras.
981        int intentCameraId = Util.getCameraFacingIntentExtras(this);
982        if (intentCameraId != -1) {
983            mCameraId = intentCameraId;
984        }
985
986        mPreferences.setLocalId(this, mCameraId);
987        CameraSettings.upgradeLocalPreferences(mPreferences.getLocal());
988
989        mNumberOfCameras = CameraHolder.instance().getNumberOfCameras();
990        mQuickCapture = getIntent().getBooleanExtra(EXTRA_QUICK_CAPTURE, false);
991
992        // we need to reset exposure for the preview
993        resetExposureCompensation();
994        /*
995         * To reduce startup time, we start the preview in another thread.
996         * We make sure the preview is started at the end of onCreate.
997         */
998        Thread startPreviewThread = new Thread(new Runnable() {
999            public void run() {
1000                try {
1001                    mStartPreviewFail = false;
1002                    startPreview();
1003                } catch (CameraHardwareException e) {
1004                    // In eng build, we throw the exception so that test tool
1005                    // can detect it and report it
1006                    if ("eng".equals(Build.TYPE)) {
1007                        throw new RuntimeException(e);
1008                    }
1009                    mStartPreviewFail = true;
1010                }
1011            }
1012        });
1013        startPreviewThread.start();
1014
1015        // don't set mSurfaceHolder here. We have it set ONLY within
1016        // surfaceChanged / surfaceDestroyed, other parts of the code
1017        // assume that when it is set, the surface is also set.
1018        SurfaceView preview = (SurfaceView) findViewById(R.id.camera_preview);
1019        SurfaceHolder holder = preview.getHolder();
1020        holder.addCallback(this);
1021        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
1022
1023        if (mIsImageCaptureIntent) {
1024            setupCaptureParams();
1025
1026            findViewById(R.id.review_control).setVisibility(View.VISIBLE);
1027            findViewById(R.id.btn_cancel).setOnClickListener(this);
1028            findViewById(R.id.btn_retake).setOnClickListener(this);
1029            findViewById(R.id.btn_done).setOnClickListener(this);
1030        } else {
1031            mSwitcher = (SwitcherSet) findViewById(R.id.camera_switch);
1032            mSwitcher.setVisibility(View.VISIBLE);
1033            mSwitcher.setOnSwitchListener(this);
1034        }
1035
1036        // Make sure preview is started.
1037        try {
1038            startPreviewThread.join();
1039            if (mStartPreviewFail) {
1040                showCameraErrorAndFinish();
1041                return;
1042            }
1043        } catch (InterruptedException ex) {
1044            // ignore
1045        }
1046
1047        mBackCameraId = CameraHolder.instance().getBackCameraId();
1048        mFrontCameraId = CameraHolder.instance().getFrontCameraId();
1049
1050        // Do this after starting preview because it depends on camera
1051        // parameters.
1052        initializeIndicatorWheel();
1053        initializeCameraPicker();
1054
1055        mZoomPicker = (ZoomPicker) findViewById(R.id.zoom_picker);
1056        if (mZoomPicker != null) mZoomPicker.setEnabled(true); // disabled initially in xml
1057    }
1058
1059    private void changeHeadUpDisplayState() {
1060        if (mHeadUpDisplay == null) return;
1061        // If the camera resumes behind the lock screen, the orientation
1062        // will be portrait. That causes OOM when we try to allocation GPU
1063        // memory for the GLSurfaceView again when the orientation changes. So,
1064        // we delayed initialization of HeadUpDisplay until the orientation
1065        // becomes landscape.
1066        Configuration config = getResources().getConfiguration();
1067        if (config.orientation == Configuration.ORIENTATION_LANDSCAPE
1068                && !mPausing && mFirstTimeInitialized) {
1069            if (mGLRootView == null) attachHeadUpDisplay();
1070        } else if (mGLRootView != null) {
1071            detachHeadUpDisplay();
1072        }
1073    }
1074
1075    private void overrideCameraSettings(final String flashMode,
1076            final String whiteBalance, final String focusMode) {
1077        if (mHeadUpDisplay != null) {
1078            mHeadUpDisplay.overrideSettings(
1079                    CameraSettings.KEY_FLASH_MODE, flashMode,
1080                    CameraSettings.KEY_WHITE_BALANCE, whiteBalance,
1081                    CameraSettings.KEY_FOCUS_MODE, focusMode);
1082        }
1083        if (mIndicatorWheel != null) {
1084            mIndicatorWheel.overrideSettings(
1085                    CameraSettings.KEY_FLASH_MODE, flashMode,
1086                    CameraSettings.KEY_WHITE_BALANCE, whiteBalance,
1087                    CameraSettings.KEY_FOCUS_MODE, focusMode);
1088        }
1089    }
1090
1091    private void updateSceneModeUI() {
1092        // If scene mode is set, we cannot set flash mode, white balance, and
1093        // focus mode, instead, we read it from driver
1094        if (!Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) {
1095            overrideCameraSettings(mParameters.getFlashMode(),
1096                    mParameters.getWhiteBalance(), mParameters.getFocusMode());
1097        } else {
1098            overrideCameraSettings(null, null, null);
1099        }
1100    }
1101
1102    private void loadCameraPreferences() {
1103        CameraSettings settings = new CameraSettings(this, mInitialParams,
1104                mCameraId, CameraHolder.instance().getCameraInfo());
1105        mPreferenceGroup = settings.getPreferenceGroup(R.xml.camera_preferences);
1106    }
1107
1108    private void initializeIndicatorWheel() {
1109        mIndicatorWheel = (IndicatorWheel) findViewById(R.id.indicator_wheel);
1110        if (mIndicatorWheel == null) return;
1111        loadCameraPreferences();
1112
1113        final String[] SETTING_KEYS = {
1114                CameraSettings.KEY_FLASH_MODE,
1115                CameraSettings.KEY_WHITE_BALANCE,
1116                CameraSettings.KEY_SCENE_MODE};
1117        final String[] OTHER_SETTING_KEYS = {
1118                CameraSettings.KEY_RECORD_LOCATION,
1119                CameraSettings.KEY_FOCUS_MODE,
1120                CameraSettings.KEY_EXPOSURE,
1121                CameraSettings.KEY_COLOR_EFFECT,
1122                CameraSettings.KEY_PICTURE_SIZE,
1123                CameraSettings.KEY_JPEG_QUALITY};
1124        mIndicatorWheel.initialize(this, mPreferenceGroup, SETTING_KEYS,
1125                OTHER_SETTING_KEYS);
1126        mIndicatorWheel.setListener(new MyIndicatorWheelListener());
1127        mPopupGestureDetector = new GestureDetector(this,
1128                new PopupGestureListener());
1129        updateSceneModeUI();
1130    }
1131
1132    private void initializeHeadUpDisplay() {
1133        if (mHeadUpDisplay == null) return;
1134        loadCameraPreferences();
1135
1136        // If we have zoom picker, do not show zoom control on head-up display.
1137        float[] zoomRatios = null;
1138        if (mZoomPicker == null) zoomRatios = getZoomRatios();
1139        mHeadUpDisplay.initialize(this, mPreferenceGroup,
1140                zoomRatios, mOrientationCompensation);
1141        if (mZoomPicker == null && mParameters.isZoomSupported()) {
1142            mHeadUpDisplay.setZoomListener(new ZoomControllerListener() {
1143                public void onZoomChanged(
1144                        int index, float ratio, boolean isMoving) {
1145                    onZoomValueChanged(index);
1146                }
1147            });
1148        }
1149        updateSceneModeUI();
1150    }
1151
1152    private void attachHeadUpDisplay() {
1153        mHeadUpDisplay.setOrientation(mOrientationCompensation);
1154        if (mParameters.isZoomSupported()) {
1155            mHeadUpDisplay.setZoomIndex(mZoomValue);
1156        }
1157        ViewGroup frame = (ViewGroup) findViewById(R.id.frame);
1158        mGLRootView = new GLRootView(this);
1159        mGLRootView.setContentPane(mHeadUpDisplay);
1160        frame.addView(mGLRootView);
1161    }
1162
1163    private void detachHeadUpDisplay() {
1164        mHeadUpDisplay.collapse();
1165        ((ViewGroup) mGLRootView.getParent()).removeView(mGLRootView);
1166        mGLRootView = null;
1167    }
1168
1169    private boolean collapseCameraControls() {
1170        if (mHeadUpDisplay != null && mHeadUpDisplay.collapse()) {
1171            return true;
1172        }
1173        if (mIndicatorWheel != null && mIndicatorWheel.dismissSettingPopup()) {
1174            return true;
1175        }
1176        return false;
1177    }
1178
1179    private void enableCameraControls(boolean enable) {
1180        if (mHeadUpDisplay != null) mHeadUpDisplay.setEnabled(enable);
1181        if (mIndicatorWheel != null) mIndicatorWheel.setEnabled(enable);
1182        if (mCameraPicker != null) mCameraPicker.setEnabled(enable);
1183        if (mZoomPicker != null) mZoomPicker.setEnabled(enable);
1184        if (mSwitcher != null) mSwitcher.setEnabled(enable);
1185    }
1186
1187    public static int roundOrientation(int orientation) {
1188        return ((orientation + 45) / 90 * 90) % 360;
1189    }
1190
1191    private class MyOrientationEventListener
1192            extends OrientationEventListener {
1193        public MyOrientationEventListener(Context context) {
1194            super(context);
1195        }
1196
1197        @Override
1198        public void onOrientationChanged(int orientation) {
1199            // We keep the last known orientation. So if the user first orient
1200            // the camera then point the camera to floor or sky, we still have
1201            // the correct orientation.
1202            if (orientation == ORIENTATION_UNKNOWN) return;
1203            mOrientation = roundOrientation(orientation);
1204            // When the screen is unlocked, display rotation may change. Always
1205            // calculate the up-to-date orientationCompensation.
1206            int orientationCompensation = mOrientation
1207                    + Util.getDisplayRotation(Camera.this);
1208            if (mOrientationCompensation != orientationCompensation) {
1209                mOrientationCompensation = orientationCompensation;
1210                if (!mIsImageCaptureIntent) {
1211                    setOrientationIndicator(mOrientationCompensation);
1212                }
1213                if (mHeadUpDisplay != null) {
1214                    mHeadUpDisplay.setOrientation(mOrientationCompensation);
1215                }
1216            }
1217        }
1218    }
1219
1220    private void setOrientationIndicator(int degree) {
1221        RotateImageView icon = (RotateImageView) findViewById(
1222                R.id.review_thumbnail);
1223        if (icon != null) icon.setDegree(degree);
1224
1225        icon = (RotateImageView) findViewById(R.id.camera_switch_icon);
1226        if (icon != null) icon.setDegree(degree);
1227        icon = (RotateImageView) findViewById(R.id.video_switch_icon);
1228        if (icon != null) icon.setDegree(degree);
1229    }
1230
1231    @Override
1232    public void onStart() {
1233        super.onStart();
1234        if (!mIsImageCaptureIntent) {
1235            mSwitcher.setSwitch(SWITCH_CAMERA);
1236        }
1237    }
1238
1239    @Override
1240    public void onStop() {
1241        super.onStop();
1242        if (mMediaProviderClient != null) {
1243            mMediaProviderClient.release();
1244            mMediaProviderClient = null;
1245        }
1246    }
1247
1248    private void checkStorage() {
1249        mPicturesRemaining = Storage.getAvailableSpace();
1250        if (mPicturesRemaining > 0) {
1251            mPicturesRemaining /= 1500000;
1252        }
1253        updateStorageHint();
1254    }
1255
1256    public void onClick(View v) {
1257        switch (v.getId()) {
1258            case R.id.btn_retake:
1259                hidePostCaptureAlert();
1260                restartPreview();
1261                break;
1262            case R.id.review_thumbnail:
1263                if (isCameraIdle() && mThumbnail != null) {
1264                    Util.viewUri(mThumbnail.getUri(), this);
1265                }
1266                break;
1267            case R.id.btn_done:
1268                doAttach();
1269                break;
1270            case R.id.btn_cancel:
1271                doCancel();
1272                break;
1273            case R.id.btn_gallery:
1274                gotoGallery();
1275                break;
1276        }
1277    }
1278
1279    private void doAttach() {
1280        if (mPausing) {
1281            return;
1282        }
1283
1284        byte[] data = mJpegImageData;
1285
1286        if (mCropValue == null) {
1287            // First handle the no crop case -- just return the value.  If the
1288            // caller specifies a "save uri" then write the data to it's
1289            // stream. Otherwise, pass back a scaled down version of the bitmap
1290            // directly in the extras.
1291            if (mSaveUri != null) {
1292                OutputStream outputStream = null;
1293                try {
1294                    outputStream = mContentResolver.openOutputStream(mSaveUri);
1295                    outputStream.write(data);
1296                    outputStream.close();
1297
1298                    setResultEx(RESULT_OK);
1299                    finish();
1300                } catch (IOException ex) {
1301                    // ignore exception
1302                } finally {
1303                    Util.closeSilently(outputStream);
1304                }
1305            } else {
1306                int orientation = Exif.getOrientation(data);
1307                Bitmap bitmap = Util.makeBitmap(data, 50 * 1024);
1308                bitmap = Util.rotate(bitmap, orientation);
1309                setResultEx(RESULT_OK,
1310                        new Intent("inline-data").putExtra("data", bitmap));
1311                finish();
1312            }
1313        } else {
1314            // Save the image to a temp file and invoke the cropper
1315            Uri tempUri = null;
1316            FileOutputStream tempStream = null;
1317            try {
1318                File path = getFileStreamPath(sTempCropFilename);
1319                path.delete();
1320                tempStream = openFileOutput(sTempCropFilename, 0);
1321                tempStream.write(data);
1322                tempStream.close();
1323                tempUri = Uri.fromFile(path);
1324            } catch (FileNotFoundException ex) {
1325                setResultEx(Activity.RESULT_CANCELED);
1326                finish();
1327                return;
1328            } catch (IOException ex) {
1329                setResultEx(Activity.RESULT_CANCELED);
1330                finish();
1331                return;
1332            } finally {
1333                Util.closeSilently(tempStream);
1334            }
1335
1336            Bundle newExtras = new Bundle();
1337            if (mCropValue.equals("circle")) {
1338                newExtras.putString("circleCrop", "true");
1339            }
1340            if (mSaveUri != null) {
1341                newExtras.putParcelable(MediaStore.EXTRA_OUTPUT, mSaveUri);
1342            } else {
1343                newExtras.putBoolean("return-data", true);
1344            }
1345
1346            Intent cropIntent = new Intent("com.android.camera.action.CROP");
1347
1348            cropIntent.setData(tempUri);
1349            cropIntent.putExtras(newExtras);
1350
1351            startActivityForResult(cropIntent, CROP_MSG);
1352        }
1353    }
1354
1355    private void doCancel() {
1356        setResultEx(RESULT_CANCELED, new Intent());
1357        finish();
1358    }
1359
1360    public void onShutterButtonFocus(ShutterButton button, boolean pressed) {
1361        if (mPausing) {
1362            return;
1363        }
1364        switch (button.getId()) {
1365            case R.id.shutter_button:
1366                doFocus(pressed);
1367                break;
1368        }
1369    }
1370
1371    public void onShutterButtonClick(ShutterButton button) {
1372        if (mPausing) {
1373            return;
1374        }
1375        switch (button.getId()) {
1376            case R.id.shutter_button:
1377                doSnap();
1378                break;
1379        }
1380    }
1381
1382    private OnScreenHint mStorageHint;
1383
1384    private void updateStorageHint() {
1385        String noStorageText = null;
1386
1387        if (mPicturesRemaining == Storage.UNAVAILABLE) {
1388            noStorageText = getString(R.string.no_storage);
1389        } else if (mPicturesRemaining == Storage.PREPARING) {
1390            noStorageText = getString(R.string.preparing_sd);
1391        } else if (mPicturesRemaining == Storage.UNKNOWN_SIZE) {
1392            noStorageText = getString(R.string.access_sd_fail);
1393        } else if (mPicturesRemaining < 1L) {
1394            noStorageText = getString(R.string.not_enough_space);
1395        }
1396
1397        if (noStorageText != null) {
1398            if (mStorageHint == null) {
1399                mStorageHint = OnScreenHint.makeText(this, noStorageText);
1400            } else {
1401                mStorageHint.setText(noStorageText);
1402            }
1403            mStorageHint.show();
1404        } else if (mStorageHint != null) {
1405            mStorageHint.cancel();
1406            mStorageHint = null;
1407        }
1408    }
1409
1410    private void installIntentFilter() {
1411        // install an intent filter to receive SD card related events.
1412        IntentFilter intentFilter =
1413                new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);
1414        intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
1415        intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
1416        intentFilter.addAction(Intent.ACTION_MEDIA_CHECKING);
1417        intentFilter.addDataScheme("file");
1418        registerReceiver(mReceiver, intentFilter);
1419        mDidRegister = true;
1420    }
1421
1422    private void initializeFocusTone() {
1423        // Initialize focus tone generator.
1424        try {
1425            mFocusToneGenerator = new ToneGenerator(
1426                    AudioManager.STREAM_SYSTEM, FOCUS_BEEP_VOLUME);
1427        } catch (Throwable ex) {
1428            Log.w(TAG, "Exception caught while creating tone generator: ", ex);
1429            mFocusToneGenerator = null;
1430        }
1431    }
1432
1433    private void initializeScreenBrightness() {
1434        Window win = getWindow();
1435        // Overright the brightness settings if it is automatic
1436        int mode = Settings.System.getInt(
1437                getContentResolver(),
1438                Settings.System.SCREEN_BRIGHTNESS_MODE,
1439                Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
1440        if (mode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
1441            WindowManager.LayoutParams winParams = win.getAttributes();
1442            winParams.screenBrightness = DEFAULT_CAMERA_BRIGHTNESS;
1443            win.setAttributes(winParams);
1444        }
1445    }
1446
1447    @Override
1448    protected void onResume() {
1449        super.onResume();
1450
1451        mPausing = false;
1452        mJpegPictureCallbackTime = 0;
1453        mZoomValue = 0;
1454
1455        mReviewImage.setVisibility(View.GONE);
1456
1457        // Start the preview if it is not started.
1458        if (mCameraState == PREVIEW_STOPPED && !mStartPreviewFail) {
1459            resetExposureCompensation();
1460            if (!restartPreview()) return;
1461        }
1462
1463        if (mSurfaceHolder != null) {
1464            // If first time initialization is not finished, put it in the
1465            // message queue.
1466            if (!mFirstTimeInitialized) {
1467                mHandler.sendEmptyMessage(FIRST_TIME_INIT);
1468            } else {
1469                initializeSecondTime();
1470            }
1471        }
1472        keepScreenOnAwhile();
1473
1474        if (mCameraState == IDLE) {
1475            mOnResumeTime = SystemClock.uptimeMillis();
1476            mHandler.sendEmptyMessageDelayed(CHECK_DISPLAY_ROTATION, 100);
1477        }
1478    }
1479
1480    @Override
1481    public void onConfigurationChanged(Configuration config) {
1482        super.onConfigurationChanged(config);
1483        changeHeadUpDisplayState();
1484    }
1485
1486    @Override
1487    protected void onPause() {
1488        mPausing = true;
1489        stopPreview();
1490        // Close the camera now because other activities may need to use it.
1491        closeCamera();
1492        resetScreenOn();
1493        collapseCameraControls();
1494        changeHeadUpDisplayState();
1495
1496        if (mFirstTimeInitialized) {
1497            mOrientationListener.disable();
1498            if (!mIsImageCaptureIntent) {
1499                if (mThumbnail != null) mThumbnail.saveTo(LAST_THUMB_FILENAME);
1500            }
1501            hidePostCaptureAlert();
1502        }
1503
1504        if (mDidRegister) {
1505            unregisterReceiver(mReceiver);
1506            mDidRegister = false;
1507        }
1508        stopReceivingLocationUpdates();
1509
1510        if (mFocusToneGenerator != null) {
1511            mFocusToneGenerator.release();
1512            mFocusToneGenerator = null;
1513        }
1514
1515        if (mStorageHint != null) {
1516            mStorageHint.cancel();
1517            mStorageHint = null;
1518        }
1519
1520        // If we are in an image capture intent and has taken
1521        // a picture, we just clear it in onPause.
1522        mJpegImageData = null;
1523
1524        // Remove the messages in the event queue.
1525        mHandler.removeMessages(RESTART_PREVIEW);
1526        mHandler.removeMessages(FIRST_TIME_INIT);
1527        mHandler.removeMessages(CHECK_DISPLAY_ROTATION);
1528        mHandler.removeMessages(CANCEL_AUTOFOCUS);
1529
1530        super.onPause();
1531    }
1532
1533    @Override
1534    protected void onActivityResult(
1535            int requestCode, int resultCode, Intent data) {
1536        switch (requestCode) {
1537            case CROP_MSG: {
1538                Intent intent = new Intent();
1539                if (data != null) {
1540                    Bundle extras = data.getExtras();
1541                    if (extras != null) {
1542                        intent.putExtras(extras);
1543                    }
1544                }
1545                setResultEx(resultCode, intent);
1546                finish();
1547
1548                File path = getFileStreamPath(sTempCropFilename);
1549                path.delete();
1550
1551                break;
1552            }
1553        }
1554    }
1555
1556    private boolean canTakePicture() {
1557        return isCameraIdle() && (mPicturesRemaining > 0);
1558    }
1559
1560    private void autoFocus() {
1561        Log.v(TAG, "Start autofocus.");
1562        mFocusStartTime = System.currentTimeMillis();
1563        mCameraDevice.autoFocus(mAutoFocusCallback);
1564        mCameraState = FOCUSING;
1565        enableCameraControls(false);
1566        updateFocusUI();
1567        mHandler.removeMessages(CANCEL_AUTOFOCUS);
1568    }
1569
1570    private void cancelAutoFocus() {
1571        Log.v(TAG, "Cancel autofocus.");
1572        mCameraDevice.cancelAutoFocus();
1573        mCameraState = IDLE;
1574        enableCameraControls(true);
1575        resetTouchFocus();
1576        setCameraParameters(UPDATE_PARAM_PREFERENCE);
1577        updateFocusUI();
1578        mHandler.removeMessages(CANCEL_AUTOFOCUS);
1579    }
1580
1581    private void updateFocusUI() {
1582        if (mCameraState == FOCUSING || mCameraState == FOCUSING_SNAP_ON_FINISH) {
1583            mFocusRectangle.showStart();
1584        } else if (mCameraState == FOCUS_SUCCESS) {
1585            mFocusRectangle.showSuccess();
1586        } else if (mCameraState == FOCUS_FAIL) {
1587            mFocusRectangle.showFail();
1588        } else if (mCameraState == IDLE && mFocusArea != null) {
1589            // Users touch on the preview and the rectangle indicates the metering area.
1590            // Either focus area is not supported or autoFocus call is not required.
1591            mFocusRectangle.showStart();
1592        } else {
1593            mFocusRectangle.clear();
1594        }
1595    }
1596
1597    // Preview area is touched. Handle touch focus.
1598    @Override
1599    public boolean onTouch(View v, MotionEvent e) {
1600        if (mPausing || !mFirstTimeInitialized || mCameraState == SNAPSHOT_IN_PROGRESS
1601                || mCameraState == FOCUSING_SNAP_ON_FINISH) {
1602            return false;
1603        }
1604
1605        // Do not trigger touch focus if popup window is opened.
1606        if (collapseCameraControls()) return false;
1607
1608        // Check if metering area or focus area is supported.
1609        boolean focusAreaSupported = (mParameters.getMaxNumFocusAreas() > 0
1610                && (mFocusMode.equals(Parameters.FOCUS_MODE_AUTO) ||
1611                    mFocusMode.equals(Parameters.FOCUS_MODE_MACRO) ||
1612                    mFocusMode.equals(Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)));
1613        boolean meteringAreaSupported = (mParameters.getMaxNumMeteringAreas() > 0);
1614        if (!focusAreaSupported && !meteringAreaSupported) return false;
1615
1616        boolean callAutoFocusRequired = false;
1617        if (focusAreaSupported &&
1618                (mFocusMode.equals(Parameters.FOCUS_MODE_AUTO) ||
1619                 mFocusMode.equals(Parameters.FOCUS_MODE_MACRO))) {
1620            callAutoFocusRequired = true;
1621        }
1622
1623        // Let users be able to cancel previous touch focus.
1624        if (callAutoFocusRequired && mFocusArea != null && e.getAction() == MotionEvent.ACTION_DOWN
1625                && (mCameraState == FOCUSING || mCameraState == FOCUS_SUCCESS ||
1626                    mCameraState == FOCUS_FAIL)) {
1627            cancelAutoFocus();
1628        }
1629
1630        // Initialize variables.
1631        int x = Math.round(e.getX());
1632        int y = Math.round(e.getY());
1633        int focusWidth = mFocusRectangle.getWidth();
1634        int focusHeight = mFocusRectangle.getHeight();
1635        int previewWidth = mPreviewFrame.getWidth();
1636        int previewHeight = mPreviewFrame.getHeight();
1637        if (mFocusArea == null) {
1638            mFocusArea = new ArrayList<Area>();
1639            mFocusArea.add(new Area(new Rect(), 1));
1640        }
1641
1642        // Convert the coordinates to driver format. The actual focus area is two times bigger than
1643        // UI because a huge rectangle looks strange.
1644        int areaWidth = focusWidth * 2;
1645        int areaHeight = focusHeight * 2;
1646        int areaLeft = Util.clamp(x - areaWidth / 2, 0, previewWidth - areaWidth);
1647        int areaTop = Util.clamp(y - areaHeight / 2, 0, previewHeight - areaHeight);
1648        Log.d(TAG, "x=" + x + ". y=" + y);
1649        Log.d(TAG, "Focus area left=" + areaLeft + ". top=" + areaTop);
1650        Log.d(TAG, "Preview width=" + previewWidth + ". height=" + previewHeight);
1651        Log.d(TAG, "focusWidth=" + focusWidth + ". focusHeight=" + focusHeight);
1652        Rect rect = mFocusArea.get(0).rect;
1653        convertToFocusArea(areaLeft, areaTop, areaWidth, areaHeight, previewWidth, previewHeight,
1654                mFocusArea.get(0).rect);
1655
1656        // Use margin to set the focus rectangle to the touched area.
1657        RelativeLayout.LayoutParams p =
1658                (RelativeLayout.LayoutParams) mFocusRectangle.getLayoutParams();
1659        int left = Util.clamp(x - focusWidth / 2, 0, previewWidth - focusWidth);
1660        int top = Util.clamp(y - focusHeight / 2, 0, previewHeight - focusHeight);
1661        p.setMargins(left, top, 0, 0);
1662        // Disable "center" rule because we no longer want to put it in the center.
1663        int[] rules = p.getRules();
1664        rules[RelativeLayout.CENTER_IN_PARENT] = 0;
1665        mFocusRectangle.requestLayout();
1666
1667        // Set the focus area and metering area.
1668        setCameraParameters(UPDATE_PARAM_PREFERENCE);
1669        if (callAutoFocusRequired && e.getAction() == MotionEvent.ACTION_UP) {
1670            autoFocus();
1671        } else {  // Just show the rectangle in all other cases.
1672            updateFocusUI();
1673        }
1674
1675        return true;
1676    }
1677
1678    // Convert the touch point to the focus area in driver format.
1679    public static void convertToFocusArea(int left, int top, int focusWidth, int focusHeight,
1680            int previewWidth, int previewHeight, Rect rect) {
1681        rect.left = Math.round((float) left / previewWidth * 2000 - 1000);
1682        rect.top = Math.round((float) top / previewHeight * 2000 - 1000);
1683        rect.right = Math.round((float) (left + focusWidth) / previewWidth * 2000 - 1000);
1684        rect.bottom = Math.round((float) (top + focusHeight) / previewHeight * 2000 - 1000);
1685    }
1686
1687    void resetTouchFocus() {
1688        // Put focus rectangle to the center.
1689        RelativeLayout.LayoutParams p =
1690                (RelativeLayout.LayoutParams) mFocusRectangle.getLayoutParams();
1691        int[] rules = p.getRules();
1692        rules[RelativeLayout.CENTER_IN_PARENT] = RelativeLayout.TRUE;
1693        p.setMargins(0, 0, 0, 0);
1694
1695        mFocusArea = null;
1696    }
1697
1698    @Override
1699    public void onBackPressed() {
1700        if (!isCameraIdle()) {
1701            // ignore backs while we're taking a picture
1702            return;
1703        } else if (!collapseCameraControls()) {
1704            super.onBackPressed();
1705        }
1706    }
1707
1708    @Override
1709    public boolean onKeyDown(int keyCode, KeyEvent event) {
1710        switch (keyCode) {
1711            case KeyEvent.KEYCODE_FOCUS:
1712                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1713                    doFocus(true);
1714                }
1715                return true;
1716            case KeyEvent.KEYCODE_CAMERA:
1717                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1718                    doSnap();
1719                }
1720                return true;
1721            case KeyEvent.KEYCODE_DPAD_CENTER:
1722                // If we get a dpad center event without any focused view, move
1723                // the focus to the shutter button and press it.
1724                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1725                    // Start auto-focus immediately to reduce shutter lag. After
1726                    // the shutter button gets the focus, doFocus() will be
1727                    // called again but it is fine.
1728                    if (collapseCameraControls()) return true;
1729                    doFocus(true);
1730                    if (mShutterButton.isInTouchMode()) {
1731                        mShutterButton.requestFocusFromTouch();
1732                    } else {
1733                        mShutterButton.requestFocus();
1734                    }
1735                    mShutterButton.setPressed(true);
1736                }
1737                return true;
1738        }
1739
1740        return super.onKeyDown(keyCode, event);
1741    }
1742
1743    @Override
1744    public boolean onKeyUp(int keyCode, KeyEvent event) {
1745        switch (keyCode) {
1746            case KeyEvent.KEYCODE_FOCUS:
1747                if (mFirstTimeInitialized) {
1748                    doFocus(false);
1749                }
1750                return true;
1751        }
1752        return super.onKeyUp(keyCode, event);
1753    }
1754
1755    private void doSnap() {
1756        if (collapseCameraControls()) return;
1757
1758        Log.v(TAG, "doSnap: mCameraState=" + mCameraState);
1759        // If the user has half-pressed the shutter and focus is completed, we
1760        // can take the photo right away. If the focus mode is infinity, we can
1761        // also take the photo.
1762        if (mFocusMode.equals(Parameters.FOCUS_MODE_INFINITY)
1763                || mFocusMode.equals(Parameters.FOCUS_MODE_FIXED)
1764                || mFocusMode.equals(Parameters.FOCUS_MODE_EDOF)
1765                || (mCameraState == FOCUS_SUCCESS
1766                || mCameraState == FOCUS_FAIL)) {
1767            capture();
1768        } else if (mCameraState == FOCUSING) {
1769            // Half pressing the shutter (i.e. the focus button event) will
1770            // already have requested AF for us, so just request capture on
1771            // focus here.
1772            mCameraState = FOCUSING_SNAP_ON_FINISH;
1773        } else if (mCameraState == IDLE) {
1774            // Focus key down event is dropped for some reasons. Just ignore.
1775        }
1776    }
1777
1778    private void doFocus(boolean pressed) {
1779        // Do the focus if the mode is not infinity.
1780        if (collapseCameraControls()) return;
1781        if (!(mFocusMode.equals(Parameters.FOCUS_MODE_INFINITY)
1782                  || mFocusMode.equals(Parameters.FOCUS_MODE_FIXED)
1783                  || mFocusMode.equals(Parameters.FOCUS_MODE_EDOF))) {
1784            if (pressed) {  // Focus key down.
1785                // Do not do focus if there is not enoguh storage. Do not focus
1786                // if touch focus has been triggered, that is, camera state is
1787                // FOCUS_SUCCESS or FOCUS_FAIL.
1788                if (canTakePicture() && mCameraState != FOCUS_SUCCESS
1789                        && mCameraState != FOCUS_FAIL) {
1790                    autoFocus();
1791                }
1792            } else {  // Focus key up.
1793                // User releases half-pressed focus key.
1794                if (mCameraState == FOCUSING || mCameraState == FOCUS_SUCCESS
1795                        || mCameraState == FOCUS_FAIL) {
1796                    cancelAutoFocus();
1797                }
1798            }
1799        }
1800    }
1801
1802    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
1803        // Make sure we have a surface in the holder before proceeding.
1804        if (holder.getSurface() == null) {
1805            Log.d(TAG, "holder.getSurface() == null");
1806            return;
1807        }
1808
1809        Log.v(TAG, "surfaceChanged. w=" + w + ". h=" + h);
1810
1811        // We need to save the holder for later use, even when the mCameraDevice
1812        // is null. This could happen if onResume() is invoked after this
1813        // function.
1814        mSurfaceHolder = holder;
1815
1816        // The mCameraDevice will be null if it fails to connect to the camera
1817        // hardware. In this case we will show a dialog and then finish the
1818        // activity, so it's OK to ignore it.
1819        if (mCameraDevice == null) return;
1820
1821        // Sometimes surfaceChanged is called after onPause or before onResume.
1822        // Ignore it.
1823        if (mPausing || isFinishing()) return;
1824
1825        // Set preview display if the surface is being created. Preview was
1826        // already started. Also restart the preview if display rotation has
1827        // changed. Sometimes this happens when the device is held in portrait
1828        // and camera app is opened. Rotation animation takes some time and
1829        // display rotation in onCreate may not be what we want.
1830        if (mCameraState != PREVIEW_STOPPED
1831                && (Util.getDisplayRotation(this) == mDisplayRotation)
1832                && holder.isCreating()) {
1833            // Set preview display if the surface is being created and preview
1834            // was already started. That means preview display was set to null
1835            // and we need to set it now.
1836            setPreviewDisplay(holder);
1837        } else {
1838            // 1. Restart the preview if the size of surface was changed. The
1839            // framework may not support changing preview display on the fly.
1840            // 2. Start the preview now if surface was destroyed and preview
1841            // stopped.
1842            restartPreview();
1843        }
1844
1845        // If first time initialization is not finished, send a message to do
1846        // it later. We want to finish surfaceChanged as soon as possible to let
1847        // user see preview first.
1848        if (!mFirstTimeInitialized) {
1849            mHandler.sendEmptyMessage(FIRST_TIME_INIT);
1850        } else {
1851            initializeSecondTime();
1852        }
1853    }
1854
1855    public void surfaceCreated(SurfaceHolder holder) {
1856    }
1857
1858    public void surfaceDestroyed(SurfaceHolder holder) {
1859        stopPreview();
1860        mSurfaceHolder = null;
1861    }
1862
1863    private void closeCamera() {
1864        if (mCameraDevice != null) {
1865            CameraHolder.instance().release();
1866            mCameraDevice.setZoomChangeListener(null);
1867            mCameraDevice = null;
1868            mCameraState = PREVIEW_STOPPED;
1869        }
1870    }
1871
1872    private void ensureCameraDevice() throws CameraHardwareException {
1873        if (mCameraDevice == null) {
1874            mCameraDevice = CameraHolder.instance().open(mCameraId);
1875            mInitialParams = mCameraDevice.getParameters();
1876        }
1877    }
1878
1879    private void showCameraErrorAndFinish() {
1880        Resources ress = getResources();
1881        Util.showFatalErrorAndFinish(Camera.this,
1882                ress.getString(R.string.camera_error_title),
1883                ress.getString(R.string.cannot_connect_camera));
1884    }
1885
1886    private boolean restartPreview() {
1887        try {
1888            startPreview();
1889        } catch (CameraHardwareException e) {
1890            showCameraErrorAndFinish();
1891            return false;
1892        }
1893        return true;
1894    }
1895
1896    private void setPreviewDisplay(SurfaceHolder holder) {
1897        try {
1898            mCameraDevice.setPreviewDisplay(holder);
1899        } catch (Throwable ex) {
1900            closeCamera();
1901            throw new RuntimeException("setPreviewDisplay failed", ex);
1902        }
1903    }
1904
1905    private void startPreview() throws CameraHardwareException {
1906        if (mPausing || isFinishing()) return;
1907
1908        resetTouchFocus();
1909
1910        ensureCameraDevice();
1911        mCameraDevice.setErrorCallback(mErrorCallback);
1912
1913        // If we're previewing already, stop the preview first (this will blank
1914        // the screen).
1915        if (mCameraState != PREVIEW_STOPPED) stopPreview();
1916
1917        setPreviewDisplay(mSurfaceHolder);
1918        mDisplayRotation = Util.getDisplayRotation(this);
1919        Util.setCameraDisplayOrientation(mDisplayRotation, mCameraId, mCameraDevice);
1920        setCameraParameters(UPDATE_PARAM_ALL);
1921
1922
1923        try {
1924            Log.v(TAG, "startPreview");
1925            mCameraDevice.startPreview();
1926        } catch (Throwable ex) {
1927            closeCamera();
1928            throw new RuntimeException("startPreview failed", ex);
1929        }
1930        mZoomState = ZOOM_STOPPED;
1931        mCameraState = IDLE;
1932    }
1933
1934    private void stopPreview() {
1935        if (mCameraDevice != null && mCameraState != PREVIEW_STOPPED) {
1936            Log.v(TAG, "stopPreview");
1937            mCameraDevice.stopPreview();
1938        }
1939        mCameraState = PREVIEW_STOPPED;
1940        // If auto focus was in progress, it would have been canceled.
1941        updateFocusUI();
1942    }
1943
1944    private static boolean isSupported(String value, List<String> supported) {
1945        return supported == null ? false : supported.indexOf(value) >= 0;
1946    }
1947
1948    private void updateCameraParametersInitialize() {
1949        // Reset preview frame rate to the maximum because it may be lowered by
1950        // video camera application.
1951        List<Integer> frameRates = mParameters.getSupportedPreviewFrameRates();
1952        if (frameRates != null) {
1953            Integer max = Collections.max(frameRates);
1954            mParameters.setPreviewFrameRate(max);
1955        }
1956
1957    }
1958
1959    private void updateCameraParametersZoom() {
1960        // Set zoom.
1961        if (mParameters.isZoomSupported()) {
1962            mParameters.setZoom(mZoomValue);
1963        }
1964    }
1965
1966    private void updateCameraParametersPreference() {
1967        if (mParameters.getMaxNumFocusAreas() > 0) {
1968            mParameters.setFocusAreas(mFocusArea);
1969            Log.d(TAG, "Parameter focus areas=" + mParameters.get("focus-areas"));
1970        }
1971
1972        if (mParameters.getMaxNumMeteringAreas() > 0) {
1973            // Use the same area for focus and metering.
1974            mParameters.setMeteringAreas(mFocusArea);
1975        }
1976
1977        // Set picture size.
1978        String pictureSize = mPreferences.getString(
1979                CameraSettings.KEY_PICTURE_SIZE, null);
1980        if (pictureSize == null) {
1981            CameraSettings.initialCameraPictureSize(this, mParameters);
1982        } else {
1983            List<Size> supported = mParameters.getSupportedPictureSizes();
1984            CameraSettings.setCameraPictureSize(
1985                    pictureSize, supported, mParameters);
1986        }
1987
1988        // Set the preview frame aspect ratio according to the picture size.
1989        Size size = mParameters.getPictureSize();
1990        PreviewFrameLayout frameLayout =
1991                (PreviewFrameLayout) findViewById(R.id.frame_layout);
1992        frameLayout.setAspectRatio((double) size.width / size.height);
1993
1994        // Set a preview size that is closest to the viewfinder height and has
1995        // the right aspect ratio.
1996        List<Size> sizes = mParameters.getSupportedPreviewSizes();
1997        Size optimalSize = Util.getOptimalPreviewSize(this,
1998                sizes, (double) size.width / size.height);
1999        Size original = mParameters.getPreviewSize();
2000        if (!original.equals(optimalSize)) {
2001            mParameters.setPreviewSize(optimalSize.width, optimalSize.height);
2002
2003            // Zoom related settings will be changed for different preview
2004            // sizes, so set and read the parameters to get lastest values
2005            mCameraDevice.setParameters(mParameters);
2006            mParameters = mCameraDevice.getParameters();
2007        }
2008        Log.v(TAG, "Preview size is " + optimalSize.width + "x" + optimalSize.height);
2009
2010        // Since change scene mode may change supported values,
2011        // Set scene mode first,
2012        mSceneMode = mPreferences.getString(
2013                CameraSettings.KEY_SCENE_MODE,
2014                getString(R.string.pref_camera_scenemode_default));
2015        if (isSupported(mSceneMode, mParameters.getSupportedSceneModes())) {
2016            if (!mParameters.getSceneMode().equals(mSceneMode)) {
2017                mParameters.setSceneMode(mSceneMode);
2018                mCameraDevice.setParameters(mParameters);
2019
2020                // Setting scene mode will change the settings of flash mode,
2021                // white balance, and focus mode. Here we read back the
2022                // parameters, so we can know those settings.
2023                mParameters = mCameraDevice.getParameters();
2024            }
2025        } else {
2026            mSceneMode = mParameters.getSceneMode();
2027            if (mSceneMode == null) {
2028                mSceneMode = Parameters.SCENE_MODE_AUTO;
2029            }
2030        }
2031
2032        // Set JPEG quality.
2033        String jpegQuality = mPreferences.getString(
2034                CameraSettings.KEY_JPEG_QUALITY,
2035                getString(R.string.pref_camera_jpegquality_default));
2036        mParameters.setJpegQuality(JpegEncodingQualityMappings.getQualityNumber(jpegQuality));
2037
2038        // For the following settings, we need to check if the settings are
2039        // still supported by latest driver, if not, ignore the settings.
2040
2041        // Set color effect parameter.
2042        String colorEffect = mPreferences.getString(
2043                CameraSettings.KEY_COLOR_EFFECT,
2044                getString(R.string.pref_camera_coloreffect_default));
2045        if (isSupported(colorEffect, mParameters.getSupportedColorEffects())) {
2046            mParameters.setColorEffect(colorEffect);
2047        }
2048
2049        // Set exposure compensation
2050        String exposure = mPreferences.getString(
2051                CameraSettings.KEY_EXPOSURE,
2052                getString(R.string.pref_exposure_default));
2053        try {
2054            int value = Integer.parseInt(exposure);
2055            int max = mParameters.getMaxExposureCompensation();
2056            int min = mParameters.getMinExposureCompensation();
2057            if (value >= min && value <= max) {
2058                mParameters.setExposureCompensation(value);
2059            } else {
2060                Log.w(TAG, "invalid exposure range: " + exposure);
2061            }
2062        } catch (NumberFormatException e) {
2063            Log.w(TAG, "invalid exposure: " + exposure);
2064        }
2065
2066        if (Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) {
2067            // Set flash mode.
2068            String flashMode = mPreferences.getString(
2069                    CameraSettings.KEY_FLASH_MODE,
2070                    getString(R.string.pref_camera_flashmode_default));
2071            List<String> supportedFlash = mParameters.getSupportedFlashModes();
2072            if (isSupported(flashMode, supportedFlash)) {
2073                mParameters.setFlashMode(flashMode);
2074            } else {
2075                flashMode = mParameters.getFlashMode();
2076                if (flashMode == null) {
2077                    flashMode = getString(
2078                            R.string.pref_camera_flashmode_no_flash);
2079                }
2080            }
2081
2082            // Set white balance parameter.
2083            String whiteBalance = mPreferences.getString(
2084                    CameraSettings.KEY_WHITE_BALANCE,
2085                    getString(R.string.pref_camera_whitebalance_default));
2086            if (isSupported(whiteBalance,
2087                    mParameters.getSupportedWhiteBalance())) {
2088                mParameters.setWhiteBalance(whiteBalance);
2089            } else {
2090                whiteBalance = mParameters.getWhiteBalance();
2091                if (whiteBalance == null) {
2092                    whiteBalance = Parameters.WHITE_BALANCE_AUTO;
2093                }
2094            }
2095
2096            // Set focus mode.
2097            mFocusMode = mPreferences.getString(
2098                    CameraSettings.KEY_FOCUS_MODE,
2099                    getString(R.string.pref_camera_focusmode_default));
2100            if (isSupported(mFocusMode, mParameters.getSupportedFocusModes())) {
2101                mParameters.setFocusMode(mFocusMode);
2102            } else {
2103                mFocusMode = mParameters.getFocusMode();
2104                if (mFocusMode == null) {
2105                    mFocusMode = Parameters.FOCUS_MODE_AUTO;
2106                }
2107            }
2108        } else {
2109            mFocusMode = mParameters.getFocusMode();
2110        }
2111    }
2112
2113    // We separate the parameters into several subsets, so we can update only
2114    // the subsets actually need updating. The PREFERENCE set needs extra
2115    // locking because the preference can be changed from GLThread as well.
2116    private void setCameraParameters(int updateSet) {
2117        mParameters = mCameraDevice.getParameters();
2118
2119        if ((updateSet & UPDATE_PARAM_INITIALIZE) != 0) {
2120            updateCameraParametersInitialize();
2121        }
2122
2123        if ((updateSet & UPDATE_PARAM_ZOOM) != 0) {
2124            updateCameraParametersZoom();
2125        }
2126
2127        if ((updateSet & UPDATE_PARAM_PREFERENCE) != 0) {
2128            updateCameraParametersPreference();
2129        }
2130
2131        mCameraDevice.setParameters(mParameters);
2132    }
2133
2134    // If the Camera is idle, update the parameters immediately, otherwise
2135    // accumulate them in mUpdateSet and update later.
2136    private void setCameraParametersWhenIdle(int additionalUpdateSet) {
2137        mUpdateSet |= additionalUpdateSet;
2138        if (mCameraDevice == null) {
2139            // We will update all the parameters when we open the device, so
2140            // we don't need to do anything now.
2141            mUpdateSet = 0;
2142            return;
2143        } else if (isCameraIdle()) {
2144            setCameraParameters(mUpdateSet);
2145            updateSceneModeUI();
2146            mUpdateSet = 0;
2147        } else {
2148            if (!mHandler.hasMessages(SET_CAMERA_PARAMETERS_WHEN_IDLE)) {
2149                mHandler.sendEmptyMessageDelayed(
2150                        SET_CAMERA_PARAMETERS_WHEN_IDLE, 1000);
2151            }
2152        }
2153    }
2154
2155    private void gotoGallery() {
2156        MenuHelper.gotoCameraImageGallery(this);
2157    }
2158
2159    private void startReceivingLocationUpdates() {
2160        if (mLocationManager != null) {
2161            try {
2162                mLocationManager.requestLocationUpdates(
2163                        LocationManager.NETWORK_PROVIDER,
2164                        1000,
2165                        0F,
2166                        mLocationListeners[1]);
2167            } catch (SecurityException ex) {
2168                Log.i(TAG, "fail to request location update, ignore", ex);
2169            } catch (IllegalArgumentException ex) {
2170                Log.d(TAG, "provider does not exist " + ex.getMessage());
2171            }
2172            try {
2173                mLocationManager.requestLocationUpdates(
2174                        LocationManager.GPS_PROVIDER,
2175                        1000,
2176                        0F,
2177                        mLocationListeners[0]);
2178                showGpsOnScreenIndicator(false);
2179            } catch (SecurityException ex) {
2180                Log.i(TAG, "fail to request location update, ignore", ex);
2181            } catch (IllegalArgumentException ex) {
2182                Log.d(TAG, "provider does not exist " + ex.getMessage());
2183            }
2184            Log.d(TAG, "startReceivingLocationUpdates");
2185        }
2186    }
2187
2188    private void stopReceivingLocationUpdates() {
2189        if (mLocationManager != null) {
2190            for (int i = 0; i < mLocationListeners.length; i++) {
2191                try {
2192                    mLocationManager.removeUpdates(mLocationListeners[i]);
2193                } catch (Exception ex) {
2194                    Log.i(TAG, "fail to remove location listners, ignore", ex);
2195                }
2196            }
2197            Log.d(TAG, "stopReceivingLocationUpdates");
2198        }
2199        hideGpsOnScreenIndicator();
2200    }
2201
2202    private Location getCurrentLocation() {
2203        // go in best to worst order
2204        for (int i = 0; i < mLocationListeners.length; i++) {
2205            Location l = mLocationListeners[i].current();
2206            if (l != null) return l;
2207        }
2208        Log.d(TAG, "No location received yet.");
2209        return null;
2210    }
2211
2212    private boolean isCameraIdle() {
2213        return mCameraState == IDLE || mCameraState == FOCUS_SUCCESS || mCameraState == FOCUS_FAIL;
2214    }
2215
2216    private boolean isImageCaptureIntent() {
2217        String action = getIntent().getAction();
2218        return (MediaStore.ACTION_IMAGE_CAPTURE.equals(action));
2219    }
2220
2221    private void setupCaptureParams() {
2222        Bundle myExtras = getIntent().getExtras();
2223        if (myExtras != null) {
2224            mSaveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT);
2225            mCropValue = myExtras.getString("crop");
2226        }
2227    }
2228
2229    private void showPostCaptureAlert() {
2230        if (mIsImageCaptureIntent) {
2231            if (mIndicatorWheel == null) {
2232                mShutterButton.setVisibility(View.INVISIBLE);
2233            } else {
2234                mShutterButton.setEnabled(false);
2235            }
2236            int[] pickIds = {R.id.btn_retake, R.id.btn_done};
2237            for (int id : pickIds) {
2238                View button = findViewById(id);
2239                ((View) button.getParent()).setVisibility(View.VISIBLE);
2240            }
2241
2242            // Remove the text of the cancel button
2243            View view = findViewById(R.id.btn_cancel);
2244            if (view instanceof Button) ((Button) view).setText("");
2245        }
2246    }
2247
2248    private void hidePostCaptureAlert() {
2249        if (mIsImageCaptureIntent) {
2250            if (mIndicatorWheel == null) {
2251                mShutterButton.setVisibility(View.VISIBLE);
2252            } else {
2253                mShutterButton.setEnabled(true);
2254            }
2255            int[] pickIds = {R.id.btn_retake, R.id.btn_done};
2256            for (int id : pickIds) {
2257                View button = findViewById(id);
2258                ((View) button.getParent()).setVisibility(View.GONE);
2259            }
2260            enableCameraControls(true);
2261
2262            // Restore the text of the cancel button
2263            View view = findViewById(R.id.btn_cancel);
2264            if (view instanceof Button) {
2265                ((Button) view).setText(R.string.review_cancel);
2266            }
2267        }
2268    }
2269
2270    @Override
2271    public boolean onPrepareOptionsMenu(Menu menu) {
2272        super.onPrepareOptionsMenu(menu);
2273        // Only show the menu when camera is idle.
2274        for (int i = 0; i < menu.size(); i++) {
2275            menu.getItem(i).setVisible(isCameraIdle());
2276        }
2277
2278        return true;
2279    }
2280
2281    @Override
2282    public boolean onCreateOptionsMenu(Menu menu) {
2283        super.onCreateOptionsMenu(menu);
2284
2285        if (mIsImageCaptureIntent) {
2286            // No options menu for attach mode.
2287            return false;
2288        } else {
2289            addBaseMenuItems(menu);
2290        }
2291        return true;
2292    }
2293
2294    private void addBaseMenuItems(Menu menu) {
2295        MenuHelper.addSwitchModeMenuItem(menu, true, new Runnable() {
2296            public void run() {
2297                switchToVideoMode();
2298            }
2299        });
2300        MenuItem gallery = menu.add(Menu.NONE, Menu.NONE,
2301                MenuHelper.POSITION_GOTO_GALLERY,
2302                R.string.camera_gallery_photos_text)
2303                .setOnMenuItemClickListener(new OnMenuItemClickListener() {
2304            public boolean onMenuItemClick(MenuItem item) {
2305                gotoGallery();
2306                return true;
2307            }
2308        });
2309        gallery.setIcon(android.R.drawable.ic_menu_gallery);
2310        mGalleryItems.add(gallery);
2311
2312        if (mNumberOfCameras > 1) {
2313            menu.add(Menu.NONE, Menu.NONE,
2314                    MenuHelper.POSITION_SWITCH_CAMERA_ID,
2315                    R.string.switch_camera_id)
2316                    .setOnMenuItemClickListener(new OnMenuItemClickListener() {
2317                public boolean onMenuItemClick(MenuItem item) {
2318                    CameraSettings.writePreferredCameraId(mPreferences,
2319                            ((mCameraId == mFrontCameraId)
2320                            ? mBackCameraId : mFrontCameraId));
2321                    onSharedPreferenceChanged();
2322                    return true;
2323                }
2324            }).setIcon(android.R.drawable.ic_menu_camera);
2325        }
2326    }
2327
2328    private boolean switchToVideoMode() {
2329        if (isFinishing() || !isCameraIdle()) return false;
2330        MenuHelper.gotoVideoMode(Camera.this);
2331        mHandler.removeMessages(FIRST_TIME_INIT);
2332        finish();
2333        return true;
2334    }
2335
2336    public boolean onSwitchChanged(Switcher source, boolean onOff) {
2337        if (onOff == SWITCH_VIDEO) {
2338            return switchToVideoMode();
2339        } else {
2340            return true;
2341        }
2342    }
2343
2344    private void onSharedPreferenceChanged() {
2345        // ignore the events after "onPause()"
2346        if (mPausing) return;
2347
2348        boolean recordLocation;
2349
2350        recordLocation = RecordLocationPreference.get(
2351                mPreferences, getContentResolver());
2352
2353        if (mRecordLocation != recordLocation) {
2354            mRecordLocation = recordLocation;
2355            if (mRecordLocation) {
2356                startReceivingLocationUpdates();
2357            } else {
2358                stopReceivingLocationUpdates();
2359            }
2360        }
2361        int cameraId = CameraSettings.readPreferredCameraId(mPreferences);
2362        if (mCameraId != cameraId) {
2363            // Restart the activity to have a crossfade animation.
2364            // TODO: Use SurfaceTexture to implement a better and faster
2365            // animation.
2366            if (mIsImageCaptureIntent) {
2367                // If the intent is camera capture, stay in camera capture mode.
2368                MenuHelper.gotoCameraMode(this, getIntent());
2369            } else {
2370                MenuHelper.gotoCameraMode(this);
2371            }
2372
2373            finish();
2374        } else {
2375            setCameraParametersWhenIdle(UPDATE_PARAM_PREFERENCE);
2376        }
2377    }
2378
2379    @Override
2380    public void onUserInteraction() {
2381        super.onUserInteraction();
2382        keepScreenOnAwhile();
2383    }
2384
2385    private void resetScreenOn() {
2386        mHandler.removeMessages(CLEAR_SCREEN_DELAY);
2387        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
2388    }
2389
2390    private void keepScreenOnAwhile() {
2391        mHandler.removeMessages(CLEAR_SCREEN_DELAY);
2392        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
2393        mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY);
2394    }
2395
2396    private class MyHeadUpDisplayListener implements HeadUpDisplay.Listener {
2397
2398        public void onSharedPreferenceChanged() {
2399            Camera.this.onSharedPreferenceChanged();
2400        }
2401
2402        public void onRestorePreferencesClicked() {
2403            Camera.this.onRestorePreferencesClicked();
2404        }
2405
2406        public void onPopupWindowVisibilityChanged(int visibility) {
2407        }
2408    }
2409
2410    protected void onRestorePreferencesClicked() {
2411        if (mPausing) return;
2412        Runnable runnable = new Runnable() {
2413            public void run() {
2414                restorePreferences();
2415            }
2416        };
2417        MenuHelper.confirmAction(this,
2418                getString(R.string.confirm_restore_title),
2419                getString(R.string.confirm_restore_message),
2420                runnable);
2421    }
2422
2423    private void restorePreferences() {
2424        // Reset the zoom. Zoom value is not stored in preference.
2425        if (mParameters.isZoomSupported()) {
2426            mZoomValue = 0;
2427            setCameraParametersWhenIdle(UPDATE_PARAM_ZOOM);
2428            if (mZoomPicker != null) mZoomPicker.setZoomIndex(0);
2429        }
2430
2431        if (mHeadUpDisplay != null) {
2432            mHeadUpDisplay.restorePreferences(mParameters);
2433        }
2434
2435        if (mIndicatorWheel != null) {
2436            mIndicatorWheel.dismissSettingPopup();
2437            CameraSettings.restorePreferences(Camera.this, mPreferences,
2438                    mParameters);
2439            initializeIndicatorWheel();
2440            onSharedPreferenceChanged();
2441        }
2442    }
2443
2444    protected void onOverriddenPreferencesClicked() {
2445        if (mPausing) return;
2446        if (mNotSelectableToast == null) {
2447            String str = getResources().getString(R.string.not_selectable_in_scene_mode);
2448            mNotSelectableToast = Toast.makeText(Camera.this, str, Toast.LENGTH_SHORT);
2449        }
2450        mNotSelectableToast.show();
2451    }
2452
2453    private void onShareButtonClicked() {
2454        if (mPausing) return;
2455
2456        // Share the last captured picture.
2457        if (mThumbnail != null) {
2458            mReviewImage.setImageBitmap(mThumbnail.getBitmap());
2459            mReviewImage.setVisibility(View.VISIBLE);
2460
2461            Intent intent = new Intent(Intent.ACTION_SEND);
2462            intent.setType("image/jpeg");
2463            intent.putExtra(Intent.EXTRA_STREAM, mThumbnail.getUri());
2464            startActivity(Intent.createChooser(intent, getString(R.string.share_picture_via)));
2465        } else {  // No last picture
2466            if (mNoShareToast == null) {
2467                mNoShareToast = Toast.makeText(this,
2468                        getResources().getString(R.string.no_picture_to_share), Toast.LENGTH_SHORT);
2469            }
2470            mNoShareToast.show();
2471        }
2472    }
2473
2474    private class MyIndicatorWheelListener implements IndicatorWheel.Listener {
2475        public void onSharedPreferenceChanged() {
2476            Camera.this.onSharedPreferenceChanged();
2477        }
2478
2479        public void onRestorePreferencesClicked() {
2480            Camera.this.onRestorePreferencesClicked();
2481        }
2482
2483        public void onOverriddenPreferencesClicked() {
2484            Camera.this.onOverriddenPreferencesClicked();
2485        }
2486
2487        public void onShareButtonClicked() {
2488            Camera.this.onShareButtonClicked();
2489        }
2490    }
2491
2492    private class MyCameraPickerListener implements CameraPicker.Listener {
2493        public void onSharedPreferenceChanged() {
2494            Camera.this.onSharedPreferenceChanged();
2495        }
2496    }
2497}
2498