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