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