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