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