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