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