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