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