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