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