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