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