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