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