Camera.java revision 6374ed8614a151c27d6277272e3e72769e768766
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        // Calculate the position of the focus rectangle.
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 left = Util.clamp(x - focusWidth / 2, 0,
1636                mPreviewFrame.getWidth() - focusWidth);
1637        int top = Util.clamp(y - focusHeight / 2, 0,
1638                mPreviewFrame.getHeight() - focusHeight);
1639        Log.d(TAG, "x=" + x + ". y=" + y);
1640        Log.d(TAG, "Margin left=" + left + ". top=" + top);
1641        Log.d(TAG, "Preview width=" + mPreviewFrame.getWidth() +
1642                ". height=" + mPreviewFrame.getHeight());
1643        Log.d(TAG, "focusWidth=" + focusWidth + ". focusHeight=" + focusHeight);
1644
1645        // Convert the coordinates to driver format. The coordinates range from
1646        // -1000 to 1000.
1647        if (mFocusArea == null) {
1648            mFocusArea = new ArrayList<Area>();
1649            mFocusArea.add(new Area(new Rect(), 1));
1650        }
1651        Rect rect = mFocusArea.get(0).rect;
1652        convertToFocusArea(left, top, focusWidth, focusHeight, mPreviewFrame.getWidth(),
1653                mPreviewFrame.getHeight(), mFocusArea.get(0).rect);
1654
1655        // Use margin to set the focus rectangle to the touched area.
1656        RelativeLayout.LayoutParams p =
1657                (RelativeLayout.LayoutParams) mFocusRectangle.getLayoutParams();
1658        p.setMargins(left, top, 0, 0);
1659        // Disable "center" rule because we no longer want to put it in the center.
1660        int[] rules = p.getRules();
1661        rules[RelativeLayout.CENTER_IN_PARENT] = 0;
1662        mFocusRectangle.requestLayout();
1663
1664        // Set the focus area and metering area.
1665        setCameraParameters(UPDATE_PARAM_PREFERENCE);
1666        if (callAutoFocusRequired && e.getAction() == MotionEvent.ACTION_UP) {
1667            autoFocus();
1668        } else {  // Just show the rectangle in all other cases.
1669            updateFocusUI();
1670        }
1671
1672        return true;
1673    }
1674
1675    // Convert the touch point to the focus area in driver format.
1676    public static void convertToFocusArea(int left, int top, int focusWidth, int focusHeight,
1677            int previewWidth, int previewHeight, Rect rect) {
1678        rect.left = Math.round((float) left / previewWidth * 2000 - 1000);
1679        rect.top = Math.round((float) top / previewHeight * 2000 - 1000);
1680        rect.right = Math.round((float) (left + focusWidth) / previewWidth * 2000 - 1000);
1681        rect.bottom = Math.round((float) (top + focusHeight) / previewHeight * 2000 - 1000);
1682    }
1683
1684    void resetTouchFocus() {
1685        // Put focus rectangle to the center.
1686        RelativeLayout.LayoutParams p =
1687                (RelativeLayout.LayoutParams) mFocusRectangle.getLayoutParams();
1688        int[] rules = p.getRules();
1689        rules[RelativeLayout.CENTER_IN_PARENT] = RelativeLayout.TRUE;
1690        p.setMargins(0, 0, 0, 0);
1691
1692        mFocusArea = null;
1693    }
1694
1695    @Override
1696    public void onBackPressed() {
1697        if (!isCameraIdle()) {
1698            // ignore backs while we're taking a picture
1699            return;
1700        } else if (!collapseCameraControls()) {
1701            super.onBackPressed();
1702        }
1703    }
1704
1705    @Override
1706    public boolean onKeyDown(int keyCode, KeyEvent event) {
1707        switch (keyCode) {
1708            case KeyEvent.KEYCODE_FOCUS:
1709                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1710                    doFocus(true);
1711                }
1712                return true;
1713            case KeyEvent.KEYCODE_CAMERA:
1714                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1715                    doSnap();
1716                }
1717                return true;
1718            case KeyEvent.KEYCODE_DPAD_CENTER:
1719                // If we get a dpad center event without any focused view, move
1720                // the focus to the shutter button and press it.
1721                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1722                    // Start auto-focus immediately to reduce shutter lag. After
1723                    // the shutter button gets the focus, doFocus() will be
1724                    // called again but it is fine.
1725                    if (collapseCameraControls()) return true;
1726                    doFocus(true);
1727                    if (mShutterButton.isInTouchMode()) {
1728                        mShutterButton.requestFocusFromTouch();
1729                    } else {
1730                        mShutterButton.requestFocus();
1731                    }
1732                    mShutterButton.setPressed(true);
1733                }
1734                return true;
1735        }
1736
1737        return super.onKeyDown(keyCode, event);
1738    }
1739
1740    @Override
1741    public boolean onKeyUp(int keyCode, KeyEvent event) {
1742        switch (keyCode) {
1743            case KeyEvent.KEYCODE_FOCUS:
1744                if (mFirstTimeInitialized) {
1745                    doFocus(false);
1746                }
1747                return true;
1748        }
1749        return super.onKeyUp(keyCode, event);
1750    }
1751
1752    private void doSnap() {
1753        if (collapseCameraControls()) return;
1754
1755        Log.v(TAG, "doSnap: mCameraState=" + mCameraState);
1756        // If the user has half-pressed the shutter and focus is completed, we
1757        // can take the photo right away. If the focus mode is infinity, we can
1758        // also take the photo.
1759        if (mFocusMode.equals(Parameters.FOCUS_MODE_INFINITY)
1760                || mFocusMode.equals(Parameters.FOCUS_MODE_FIXED)
1761                || mFocusMode.equals(Parameters.FOCUS_MODE_EDOF)
1762                || (mCameraState == FOCUS_SUCCESS
1763                || mCameraState == FOCUS_FAIL)) {
1764            capture();
1765        } else if (mCameraState == FOCUSING) {
1766            // Half pressing the shutter (i.e. the focus button event) will
1767            // already have requested AF for us, so just request capture on
1768            // focus here.
1769            mCameraState = FOCUSING_SNAP_ON_FINISH;
1770        } else if (mCameraState == IDLE) {
1771            // Focus key down event is dropped for some reasons. Just ignore.
1772        }
1773    }
1774
1775    private void doFocus(boolean pressed) {
1776        // Do the focus if the mode is not infinity.
1777        if (collapseCameraControls()) return;
1778        if (!(mFocusMode.equals(Parameters.FOCUS_MODE_INFINITY)
1779                  || mFocusMode.equals(Parameters.FOCUS_MODE_FIXED)
1780                  || mFocusMode.equals(Parameters.FOCUS_MODE_EDOF))) {
1781            if (pressed) {  // Focus key down.
1782                // Do not do focus if there is not enoguh storage. Do not focus
1783                // if touch focus has been triggered, that is, camera state is
1784                // FOCUS_SUCCESS or FOCUS_FAIL.
1785                if (canTakePicture() && mCameraState != FOCUS_SUCCESS
1786                        && mCameraState != FOCUS_FAIL) {
1787                    autoFocus();
1788                }
1789            } else {  // Focus key up.
1790                // User releases half-pressed focus key.
1791                if (mCameraState == FOCUSING || mCameraState == FOCUS_SUCCESS
1792                        || mCameraState == FOCUS_FAIL) {
1793                    cancelAutoFocus();
1794                }
1795            }
1796        }
1797    }
1798
1799    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
1800        // Make sure we have a surface in the holder before proceeding.
1801        if (holder.getSurface() == null) {
1802            Log.d(TAG, "holder.getSurface() == null");
1803            return;
1804        }
1805
1806        Log.v(TAG, "surfaceChanged. w=" + w + ". h=" + h);
1807
1808        // We need to save the holder for later use, even when the mCameraDevice
1809        // is null. This could happen if onResume() is invoked after this
1810        // function.
1811        mSurfaceHolder = holder;
1812
1813        // The mCameraDevice will be null if it fails to connect to the camera
1814        // hardware. In this case we will show a dialog and then finish the
1815        // activity, so it's OK to ignore it.
1816        if (mCameraDevice == null) return;
1817
1818        // Sometimes surfaceChanged is called after onPause or before onResume.
1819        // Ignore it.
1820        if (mPausing || isFinishing()) return;
1821
1822        // Set preview display if the surface is being created. Preview was
1823        // already started. Also restart the preview if display rotation has
1824        // changed. Sometimes this happens when the device is held in portrait
1825        // and camera app is opened. Rotation animation takes some time and
1826        // display rotation in onCreate may not be what we want.
1827        if (mCameraState != PREVIEW_STOPPED
1828                && (Util.getDisplayRotation(this) == mDisplayRotation)
1829                && holder.isCreating()) {
1830            // Set preview display if the surface is being created and preview
1831            // was already started. That means preview display was set to null
1832            // and we need to set it now.
1833            setPreviewDisplay(holder);
1834        } else {
1835            // 1. Restart the preview if the size of surface was changed. The
1836            // framework may not support changing preview display on the fly.
1837            // 2. Start the preview now if surface was destroyed and preview
1838            // stopped.
1839            restartPreview();
1840        }
1841
1842        // If first time initialization is not finished, send a message to do
1843        // it later. We want to finish surfaceChanged as soon as possible to let
1844        // user see preview first.
1845        if (!mFirstTimeInitialized) {
1846            mHandler.sendEmptyMessage(FIRST_TIME_INIT);
1847        } else {
1848            initializeSecondTime();
1849        }
1850    }
1851
1852    public void surfaceCreated(SurfaceHolder holder) {
1853    }
1854
1855    public void surfaceDestroyed(SurfaceHolder holder) {
1856        stopPreview();
1857        mSurfaceHolder = null;
1858    }
1859
1860    private void closeCamera() {
1861        if (mCameraDevice != null) {
1862            CameraHolder.instance().release();
1863            mCameraDevice.setZoomChangeListener(null);
1864            mCameraDevice = null;
1865            mCameraState = PREVIEW_STOPPED;
1866        }
1867    }
1868
1869    private void ensureCameraDevice() throws CameraHardwareException {
1870        if (mCameraDevice == null) {
1871            mCameraDevice = CameraHolder.instance().open(mCameraId);
1872            mInitialParams = mCameraDevice.getParameters();
1873        }
1874    }
1875
1876    private void showCameraErrorAndFinish() {
1877        Resources ress = getResources();
1878        Util.showFatalErrorAndFinish(Camera.this,
1879                ress.getString(R.string.camera_error_title),
1880                ress.getString(R.string.cannot_connect_camera));
1881    }
1882
1883    private boolean restartPreview() {
1884        try {
1885            startPreview();
1886        } catch (CameraHardwareException e) {
1887            showCameraErrorAndFinish();
1888            return false;
1889        }
1890        return true;
1891    }
1892
1893    private void setPreviewDisplay(SurfaceHolder holder) {
1894        try {
1895            mCameraDevice.setPreviewDisplay(holder);
1896        } catch (Throwable ex) {
1897            closeCamera();
1898            throw new RuntimeException("setPreviewDisplay failed", ex);
1899        }
1900    }
1901
1902    private void startPreview() throws CameraHardwareException {
1903        if (mPausing || isFinishing()) return;
1904
1905        resetTouchFocus();
1906
1907        ensureCameraDevice();
1908        mCameraDevice.setErrorCallback(mErrorCallback);
1909
1910        // If we're previewing already, stop the preview first (this will blank
1911        // the screen).
1912        if (mCameraState != PREVIEW_STOPPED) stopPreview();
1913
1914        setPreviewDisplay(mSurfaceHolder);
1915        mDisplayRotation = Util.getDisplayRotation(this);
1916        Util.setCameraDisplayOrientation(mDisplayRotation, mCameraId, mCameraDevice);
1917        setCameraParameters(UPDATE_PARAM_ALL);
1918
1919
1920        try {
1921            Log.v(TAG, "startPreview");
1922            mCameraDevice.startPreview();
1923        } catch (Throwable ex) {
1924            closeCamera();
1925            throw new RuntimeException("startPreview failed", ex);
1926        }
1927        mZoomState = ZOOM_STOPPED;
1928        mCameraState = IDLE;
1929    }
1930
1931    private void stopPreview() {
1932        if (mCameraDevice != null && mCameraState != PREVIEW_STOPPED) {
1933            Log.v(TAG, "stopPreview");
1934            mCameraDevice.stopPreview();
1935        }
1936        mCameraState = PREVIEW_STOPPED;
1937        // If auto focus was in progress, it would have been canceled.
1938        updateFocusUI();
1939    }
1940
1941    private static boolean isSupported(String value, List<String> supported) {
1942        return supported == null ? false : supported.indexOf(value) >= 0;
1943    }
1944
1945    private void updateCameraParametersInitialize() {
1946        // Reset preview frame rate to the maximum because it may be lowered by
1947        // video camera application.
1948        List<Integer> frameRates = mParameters.getSupportedPreviewFrameRates();
1949        if (frameRates != null) {
1950            Integer max = Collections.max(frameRates);
1951            mParameters.setPreviewFrameRate(max);
1952        }
1953
1954    }
1955
1956    private void updateCameraParametersZoom() {
1957        // Set zoom.
1958        if (mParameters.isZoomSupported()) {
1959            mParameters.setZoom(mZoomValue);
1960        }
1961    }
1962
1963    private void updateCameraParametersPreference() {
1964        if (mParameters.getMaxNumFocusAreas() > 0) {
1965            mParameters.setFocusAreas(mFocusArea);
1966            Log.d(TAG, "Parameter focus areas=" + mParameters.get("focus-areas"));
1967        }
1968
1969        if (mParameters.getMaxNumMeteringAreas() > 0) {
1970            // Use the same area for focus and metering.
1971            mParameters.setMeteringAreas(mFocusArea);
1972        }
1973
1974        // Set picture size.
1975        String pictureSize = mPreferences.getString(
1976                CameraSettings.KEY_PICTURE_SIZE, null);
1977        if (pictureSize == null) {
1978            CameraSettings.initialCameraPictureSize(this, mParameters);
1979        } else {
1980            List<Size> supported = mParameters.getSupportedPictureSizes();
1981            CameraSettings.setCameraPictureSize(
1982                    pictureSize, supported, mParameters);
1983        }
1984
1985        // Set the preview frame aspect ratio according to the picture size.
1986        Size size = mParameters.getPictureSize();
1987        PreviewFrameLayout frameLayout =
1988                (PreviewFrameLayout) findViewById(R.id.frame_layout);
1989        frameLayout.setAspectRatio((double) size.width / size.height);
1990
1991        // Set a preview size that is closest to the viewfinder height and has
1992        // the right aspect ratio.
1993        List<Size> sizes = mParameters.getSupportedPreviewSizes();
1994        Size optimalSize = Util.getOptimalPreviewSize(this,
1995                sizes, (double) size.width / size.height);
1996        Size original = mParameters.getPreviewSize();
1997        if (!original.equals(optimalSize)) {
1998            mParameters.setPreviewSize(optimalSize.width, optimalSize.height);
1999
2000            // Zoom related settings will be changed for different preview
2001            // sizes, so set and read the parameters to get lastest values
2002            mCameraDevice.setParameters(mParameters);
2003            mParameters = mCameraDevice.getParameters();
2004        }
2005        Log.v(TAG, "Preview size is " + optimalSize.width + "x" + optimalSize.height);
2006
2007        // Since change scene mode may change supported values,
2008        // Set scene mode first,
2009        mSceneMode = mPreferences.getString(
2010                CameraSettings.KEY_SCENE_MODE,
2011                getString(R.string.pref_camera_scenemode_default));
2012        if (isSupported(mSceneMode, mParameters.getSupportedSceneModes())) {
2013            if (!mParameters.getSceneMode().equals(mSceneMode)) {
2014                mParameters.setSceneMode(mSceneMode);
2015                mCameraDevice.setParameters(mParameters);
2016
2017                // Setting scene mode will change the settings of flash mode,
2018                // white balance, and focus mode. Here we read back the
2019                // parameters, so we can know those settings.
2020                mParameters = mCameraDevice.getParameters();
2021            }
2022        } else {
2023            mSceneMode = mParameters.getSceneMode();
2024            if (mSceneMode == null) {
2025                mSceneMode = Parameters.SCENE_MODE_AUTO;
2026            }
2027        }
2028
2029        // Set JPEG quality.
2030        String jpegQuality = mPreferences.getString(
2031                CameraSettings.KEY_JPEG_QUALITY,
2032                getString(R.string.pref_camera_jpegquality_default));
2033        mParameters.setJpegQuality(JpegEncodingQualityMappings.getQualityNumber(jpegQuality));
2034
2035        // For the following settings, we need to check if the settings are
2036        // still supported by latest driver, if not, ignore the settings.
2037
2038        // Set color effect parameter.
2039        String colorEffect = mPreferences.getString(
2040                CameraSettings.KEY_COLOR_EFFECT,
2041                getString(R.string.pref_camera_coloreffect_default));
2042        if (isSupported(colorEffect, mParameters.getSupportedColorEffects())) {
2043            mParameters.setColorEffect(colorEffect);
2044        }
2045
2046        // Set exposure compensation
2047        String exposure = mPreferences.getString(
2048                CameraSettings.KEY_EXPOSURE,
2049                getString(R.string.pref_exposure_default));
2050        try {
2051            int value = Integer.parseInt(exposure);
2052            int max = mParameters.getMaxExposureCompensation();
2053            int min = mParameters.getMinExposureCompensation();
2054            if (value >= min && value <= max) {
2055                mParameters.setExposureCompensation(value);
2056            } else {
2057                Log.w(TAG, "invalid exposure range: " + exposure);
2058            }
2059        } catch (NumberFormatException e) {
2060            Log.w(TAG, "invalid exposure: " + exposure);
2061        }
2062
2063        if (Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) {
2064            // Set flash mode.
2065            String flashMode = mPreferences.getString(
2066                    CameraSettings.KEY_FLASH_MODE,
2067                    getString(R.string.pref_camera_flashmode_default));
2068            List<String> supportedFlash = mParameters.getSupportedFlashModes();
2069            if (isSupported(flashMode, supportedFlash)) {
2070                mParameters.setFlashMode(flashMode);
2071            } else {
2072                flashMode = mParameters.getFlashMode();
2073                if (flashMode == null) {
2074                    flashMode = getString(
2075                            R.string.pref_camera_flashmode_no_flash);
2076                }
2077            }
2078
2079            // Set white balance parameter.
2080            String whiteBalance = mPreferences.getString(
2081                    CameraSettings.KEY_WHITE_BALANCE,
2082                    getString(R.string.pref_camera_whitebalance_default));
2083            if (isSupported(whiteBalance,
2084                    mParameters.getSupportedWhiteBalance())) {
2085                mParameters.setWhiteBalance(whiteBalance);
2086            } else {
2087                whiteBalance = mParameters.getWhiteBalance();
2088                if (whiteBalance == null) {
2089                    whiteBalance = Parameters.WHITE_BALANCE_AUTO;
2090                }
2091            }
2092
2093            // Set focus mode.
2094            mFocusMode = mPreferences.getString(
2095                    CameraSettings.KEY_FOCUS_MODE,
2096                    getString(R.string.pref_camera_focusmode_default));
2097            if (isSupported(mFocusMode, mParameters.getSupportedFocusModes())) {
2098                mParameters.setFocusMode(mFocusMode);
2099            } else {
2100                mFocusMode = mParameters.getFocusMode();
2101                if (mFocusMode == null) {
2102                    mFocusMode = Parameters.FOCUS_MODE_AUTO;
2103                }
2104            }
2105        } else {
2106            mFocusMode = mParameters.getFocusMode();
2107        }
2108    }
2109
2110    // We separate the parameters into several subsets, so we can update only
2111    // the subsets actually need updating. The PREFERENCE set needs extra
2112    // locking because the preference can be changed from GLThread as well.
2113    private void setCameraParameters(int updateSet) {
2114        mParameters = mCameraDevice.getParameters();
2115
2116        if ((updateSet & UPDATE_PARAM_INITIALIZE) != 0) {
2117            updateCameraParametersInitialize();
2118        }
2119
2120        if ((updateSet & UPDATE_PARAM_ZOOM) != 0) {
2121            updateCameraParametersZoom();
2122        }
2123
2124        if ((updateSet & UPDATE_PARAM_PREFERENCE) != 0) {
2125            updateCameraParametersPreference();
2126        }
2127
2128        mCameraDevice.setParameters(mParameters);
2129    }
2130
2131    // If the Camera is idle, update the parameters immediately, otherwise
2132    // accumulate them in mUpdateSet and update later.
2133    private void setCameraParametersWhenIdle(int additionalUpdateSet) {
2134        mUpdateSet |= additionalUpdateSet;
2135        if (mCameraDevice == null) {
2136            // We will update all the parameters when we open the device, so
2137            // we don't need to do anything now.
2138            mUpdateSet = 0;
2139            return;
2140        } else if (isCameraIdle()) {
2141            setCameraParameters(mUpdateSet);
2142            updateSceneModeUI();
2143            mUpdateSet = 0;
2144        } else {
2145            if (!mHandler.hasMessages(SET_CAMERA_PARAMETERS_WHEN_IDLE)) {
2146                mHandler.sendEmptyMessageDelayed(
2147                        SET_CAMERA_PARAMETERS_WHEN_IDLE, 1000);
2148            }
2149        }
2150    }
2151
2152    private void gotoGallery() {
2153        MenuHelper.gotoCameraImageGallery(this);
2154    }
2155
2156    private void startReceivingLocationUpdates() {
2157        if (mLocationManager != null) {
2158            try {
2159                mLocationManager.requestLocationUpdates(
2160                        LocationManager.NETWORK_PROVIDER,
2161                        1000,
2162                        0F,
2163                        mLocationListeners[1]);
2164            } catch (SecurityException ex) {
2165                Log.i(TAG, "fail to request location update, ignore", ex);
2166            } catch (IllegalArgumentException ex) {
2167                Log.d(TAG, "provider does not exist " + ex.getMessage());
2168            }
2169            try {
2170                mLocationManager.requestLocationUpdates(
2171                        LocationManager.GPS_PROVIDER,
2172                        1000,
2173                        0F,
2174                        mLocationListeners[0]);
2175                showGpsOnScreenIndicator(false);
2176            } catch (SecurityException ex) {
2177                Log.i(TAG, "fail to request location update, ignore", ex);
2178            } catch (IllegalArgumentException ex) {
2179                Log.d(TAG, "provider does not exist " + ex.getMessage());
2180            }
2181            Log.d(TAG, "startReceivingLocationUpdates");
2182        }
2183    }
2184
2185    private void stopReceivingLocationUpdates() {
2186        if (mLocationManager != null) {
2187            for (int i = 0; i < mLocationListeners.length; i++) {
2188                try {
2189                    mLocationManager.removeUpdates(mLocationListeners[i]);
2190                } catch (Exception ex) {
2191                    Log.i(TAG, "fail to remove location listners, ignore", ex);
2192                }
2193            }
2194            Log.d(TAG, "stopReceivingLocationUpdates");
2195        }
2196        hideGpsOnScreenIndicator();
2197    }
2198
2199    private Location getCurrentLocation() {
2200        // go in best to worst order
2201        for (int i = 0; i < mLocationListeners.length; i++) {
2202            Location l = mLocationListeners[i].current();
2203            if (l != null) return l;
2204        }
2205        Log.d(TAG, "No location received yet.");
2206        return null;
2207    }
2208
2209    private boolean isCameraIdle() {
2210        return mCameraState == IDLE || mCameraState == FOCUS_SUCCESS || mCameraState == FOCUS_FAIL;
2211    }
2212
2213    private boolean isImageCaptureIntent() {
2214        String action = getIntent().getAction();
2215        return (MediaStore.ACTION_IMAGE_CAPTURE.equals(action));
2216    }
2217
2218    private void setupCaptureParams() {
2219        Bundle myExtras = getIntent().getExtras();
2220        if (myExtras != null) {
2221            mSaveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT);
2222            mCropValue = myExtras.getString("crop");
2223        }
2224    }
2225
2226    private void showPostCaptureAlert() {
2227        if (mIsImageCaptureIntent) {
2228            if (mIndicatorWheel == null) {
2229                mShutterButton.setVisibility(View.INVISIBLE);
2230            } else {
2231                mShutterButton.setEnabled(false);
2232            }
2233            int[] pickIds = {R.id.btn_retake, R.id.btn_done};
2234            for (int id : pickIds) {
2235                View button = findViewById(id);
2236                ((View) button.getParent()).setVisibility(View.VISIBLE);
2237            }
2238
2239            // Remove the text of the cancel button
2240            View view = findViewById(R.id.btn_cancel);
2241            if (view instanceof Button) ((Button) view).setText("");
2242        }
2243    }
2244
2245    private void hidePostCaptureAlert() {
2246        if (mIsImageCaptureIntent) {
2247            if (mIndicatorWheel == null) {
2248                mShutterButton.setVisibility(View.VISIBLE);
2249            } else {
2250                mShutterButton.setEnabled(true);
2251            }
2252            int[] pickIds = {R.id.btn_retake, R.id.btn_done};
2253            for (int id : pickIds) {
2254                View button = findViewById(id);
2255                ((View) button.getParent()).setVisibility(View.GONE);
2256            }
2257            enableCameraControls(true);
2258
2259            // Restore the text of the cancel button
2260            View view = findViewById(R.id.btn_cancel);
2261            if (view instanceof Button) {
2262                ((Button) view).setText(R.string.review_cancel);
2263            }
2264        }
2265    }
2266
2267    @Override
2268    public boolean onPrepareOptionsMenu(Menu menu) {
2269        super.onPrepareOptionsMenu(menu);
2270        // Only show the menu when camera is idle.
2271        for (int i = 0; i < menu.size(); i++) {
2272            menu.getItem(i).setVisible(isCameraIdle());
2273        }
2274
2275        return true;
2276    }
2277
2278    @Override
2279    public boolean onCreateOptionsMenu(Menu menu) {
2280        super.onCreateOptionsMenu(menu);
2281
2282        if (mIsImageCaptureIntent) {
2283            // No options menu for attach mode.
2284            return false;
2285        } else {
2286            addBaseMenuItems(menu);
2287        }
2288        return true;
2289    }
2290
2291    private void addBaseMenuItems(Menu menu) {
2292        MenuHelper.addSwitchModeMenuItem(menu, true, new Runnable() {
2293            public void run() {
2294                switchToVideoMode();
2295            }
2296        });
2297        MenuItem gallery = menu.add(Menu.NONE, Menu.NONE,
2298                MenuHelper.POSITION_GOTO_GALLERY,
2299                R.string.camera_gallery_photos_text)
2300                .setOnMenuItemClickListener(new OnMenuItemClickListener() {
2301            public boolean onMenuItemClick(MenuItem item) {
2302                gotoGallery();
2303                return true;
2304            }
2305        });
2306        gallery.setIcon(android.R.drawable.ic_menu_gallery);
2307        mGalleryItems.add(gallery);
2308
2309        if (mNumberOfCameras > 1) {
2310            menu.add(Menu.NONE, Menu.NONE,
2311                    MenuHelper.POSITION_SWITCH_CAMERA_ID,
2312                    R.string.switch_camera_id)
2313                    .setOnMenuItemClickListener(new OnMenuItemClickListener() {
2314                public boolean onMenuItemClick(MenuItem item) {
2315                    CameraSettings.writePreferredCameraId(mPreferences,
2316                            ((mCameraId == mFrontCameraId)
2317                            ? mBackCameraId : mFrontCameraId));
2318                    onSharedPreferenceChanged();
2319                    return true;
2320                }
2321            }).setIcon(android.R.drawable.ic_menu_camera);
2322        }
2323    }
2324
2325    private boolean switchToVideoMode() {
2326        if (isFinishing() || !isCameraIdle()) return false;
2327        MenuHelper.gotoVideoMode(Camera.this);
2328        mHandler.removeMessages(FIRST_TIME_INIT);
2329        finish();
2330        return true;
2331    }
2332
2333    public boolean onSwitchChanged(Switcher source, boolean onOff) {
2334        if (onOff == SWITCH_VIDEO) {
2335            return switchToVideoMode();
2336        } else {
2337            return true;
2338        }
2339    }
2340
2341    private void onSharedPreferenceChanged() {
2342        // ignore the events after "onPause()"
2343        if (mPausing) return;
2344
2345        boolean recordLocation;
2346
2347        recordLocation = RecordLocationPreference.get(
2348                mPreferences, getContentResolver());
2349
2350        if (mRecordLocation != recordLocation) {
2351            mRecordLocation = recordLocation;
2352            if (mRecordLocation) {
2353                startReceivingLocationUpdates();
2354            } else {
2355                stopReceivingLocationUpdates();
2356            }
2357        }
2358        int cameraId = CameraSettings.readPreferredCameraId(mPreferences);
2359        if (mCameraId != cameraId) {
2360            // Restart the activity to have a crossfade animation.
2361            // TODO: Use SurfaceTexture to implement a better and faster
2362            // animation.
2363            if (mIsImageCaptureIntent) {
2364                // If the intent is camera capture, stay in camera capture mode.
2365                MenuHelper.gotoCameraMode(this, getIntent());
2366            } else {
2367                MenuHelper.gotoCameraMode(this);
2368            }
2369
2370            finish();
2371        } else {
2372            setCameraParametersWhenIdle(UPDATE_PARAM_PREFERENCE);
2373        }
2374    }
2375
2376    @Override
2377    public void onUserInteraction() {
2378        super.onUserInteraction();
2379        keepScreenOnAwhile();
2380    }
2381
2382    private void resetScreenOn() {
2383        mHandler.removeMessages(CLEAR_SCREEN_DELAY);
2384        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
2385    }
2386
2387    private void keepScreenOnAwhile() {
2388        mHandler.removeMessages(CLEAR_SCREEN_DELAY);
2389        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
2390        mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY);
2391    }
2392
2393    private class MyHeadUpDisplayListener implements HeadUpDisplay.Listener {
2394
2395        public void onSharedPreferenceChanged() {
2396            Camera.this.onSharedPreferenceChanged();
2397        }
2398
2399        public void onRestorePreferencesClicked() {
2400            Camera.this.onRestorePreferencesClicked();
2401        }
2402
2403        public void onPopupWindowVisibilityChanged(int visibility) {
2404        }
2405
2406        public void onShareButtonClicked() {
2407            Camera.this.onShareButtonClicked();
2408        }
2409    }
2410
2411    protected void onRestorePreferencesClicked() {
2412        if (mPausing) return;
2413        Runnable runnable = new Runnable() {
2414            public void run() {
2415                restorePreferences();
2416            }
2417        };
2418        MenuHelper.confirmAction(this,
2419                getString(R.string.confirm_restore_title),
2420                getString(R.string.confirm_restore_message),
2421                runnable);
2422    }
2423
2424    private void restorePreferences() {
2425        // Reset the zoom. Zoom value is not stored in preference.
2426        if (mParameters.isZoomSupported()) {
2427            mZoomValue = 0;
2428            setCameraParametersWhenIdle(UPDATE_PARAM_ZOOM);
2429            if (mZoomPicker != null) mZoomPicker.setZoomIndex(0);
2430        }
2431
2432        if (mHeadUpDisplay != null) {
2433            mHeadUpDisplay.restorePreferences(mParameters);
2434        }
2435
2436        if (mIndicatorWheel != null) {
2437            mIndicatorWheel.dismissSettingPopup();
2438            CameraSettings.restorePreferences(Camera.this, mPreferences,
2439                    mParameters);
2440            initializeIndicatorWheel();
2441            onSharedPreferenceChanged();
2442        }
2443    }
2444
2445    protected void onOverriddenPreferencesClicked() {
2446        if (mPausing) return;
2447        if (mNotSelectableToast == null) {
2448            String str = getResources().getString(R.string.not_selectable_in_scene_mode);
2449            mNotSelectableToast = Toast.makeText(Camera.this, str, Toast.LENGTH_SHORT);
2450        }
2451        mNotSelectableToast.show();
2452    }
2453
2454    private void onShareButtonClicked() {
2455        if (mPausing) return;
2456
2457        // Share the last captured picture.
2458        if (mThumbnail != null) {
2459            mReviewImage.setImageBitmap(mThumbnail.getBitmap());
2460            mReviewImage.setVisibility(View.VISIBLE);
2461
2462            Intent intent = new Intent(Intent.ACTION_SEND);
2463            intent.setType("image/jpeg");
2464            intent.putExtra(Intent.EXTRA_STREAM, mThumbnail.getUri());
2465            startActivity(Intent.createChooser(intent, getString(R.string.share_picture_via)));
2466        } else {  // No last picture
2467            if (mNoShareToast == null) {
2468                mNoShareToast = Toast.makeText(this,
2469                        getResources().getString(R.string.no_picture_to_share), Toast.LENGTH_SHORT);
2470            }
2471            mNoShareToast.show();
2472        }
2473    }
2474
2475    private class MyIndicatorWheelListener implements IndicatorWheel.Listener {
2476        public void onSharedPreferenceChanged() {
2477            Camera.this.onSharedPreferenceChanged();
2478        }
2479
2480        public void onRestorePreferencesClicked() {
2481            Camera.this.onRestorePreferencesClicked();
2482        }
2483
2484        public void onOverriddenPreferencesClicked() {
2485            Camera.this.onOverriddenPreferencesClicked();
2486        }
2487
2488        public void onShareButtonClicked() {
2489            Camera.this.onShareButtonClicked();
2490        }
2491    }
2492
2493    private class MyCameraPickerListener implements CameraPicker.Listener {
2494        public void onSharedPreferenceChanged() {
2495            Camera.this.onSharedPreferenceChanged();
2496        }
2497    }
2498}
2499