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