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