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