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