Camera.java revision c8e13fecea56e679418f41ba454f867c49f888aa
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 < 1) {
1212            noStorageText = getString(R.string.not_enough_space);
1213        }
1214
1215        if (noStorageText != null) {
1216            if (mStorageHint == null) {
1217                mStorageHint = OnScreenHint.makeText(this, noStorageText);
1218            } else {
1219                mStorageHint.setText(noStorageText);
1220            }
1221            mStorageHint.show();
1222        } else if (mStorageHint != null) {
1223            mStorageHint.cancel();
1224            mStorageHint = null;
1225        }
1226    }
1227
1228    private void installIntentFilter() {
1229        // install an intent filter to receive SD card related events.
1230        IntentFilter intentFilter =
1231                new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);
1232        intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
1233        intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
1234        intentFilter.addAction(Intent.ACTION_MEDIA_CHECKING);
1235        intentFilter.addDataScheme("file");
1236        registerReceiver(mReceiver, intentFilter);
1237        mDidRegister = true;
1238    }
1239
1240    private void initializeFocusTone() {
1241        // Initialize focus tone generator.
1242        try {
1243            mFocusToneGenerator = new ToneGenerator(
1244                    AudioManager.STREAM_SYSTEM, FOCUS_BEEP_VOLUME);
1245        } catch (Throwable ex) {
1246            Log.w(TAG, "Exception caught while creating tone generator: ", ex);
1247            mFocusToneGenerator = null;
1248        }
1249    }
1250
1251    private void initializeScreenBrightness() {
1252        Window win = getWindow();
1253        // Overright the brightness settings if it is automatic
1254        int mode = Settings.System.getInt(
1255                getContentResolver(),
1256                Settings.System.SCREEN_BRIGHTNESS_MODE,
1257                Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
1258        if (mode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
1259            WindowManager.LayoutParams winParams = win.getAttributes();
1260            winParams.screenBrightness = DEFAULT_CAMERA_BRIGHTNESS;
1261            win.setAttributes(winParams);
1262        }
1263    }
1264
1265    @Override
1266    protected void onResume() {
1267        super.onResume();
1268
1269        mPausing = false;
1270        mJpegPictureCallbackTime = 0;
1271        mZoomValue = 0;
1272        mImageCapture = new ImageCapture();
1273
1274        // Start the preview if it is not started.
1275        if (!mPreviewing && !mStartPreviewFail) {
1276            resetExposureCompensation();
1277            try {
1278                startPreview();
1279            } catch (CameraHardwareException e) {
1280                showCameraErrorAndFinish();
1281                return;
1282            }
1283        }
1284
1285        if (mSurfaceHolder != null) {
1286            // If first time initialization is not finished, put it in the
1287            // message queue.
1288            if (!mFirstTimeInitialized) {
1289                mHandler.sendEmptyMessage(FIRST_TIME_INIT);
1290            } else {
1291                initializeSecondTime();
1292            }
1293        }
1294        keepScreenOnAwhile();
1295    }
1296
1297    @Override
1298    public void onConfigurationChanged(Configuration config) {
1299        super.onConfigurationChanged(config);
1300        changeHeadUpDisplayState();
1301    }
1302
1303    private static ImageManager.DataLocation dataLocation() {
1304        return ImageManager.DataLocation.EXTERNAL;
1305    }
1306
1307    @Override
1308    protected void onPause() {
1309        mPausing = true;
1310        stopPreview();
1311        // Close the camera now because other activities may need to use it.
1312        closeCamera();
1313        resetScreenOn();
1314        changeHeadUpDisplayState();
1315
1316        if (mFirstTimeInitialized) {
1317            mOrientationListener.disable();
1318            if (!mIsImageCaptureIntent) {
1319                mThumbController.storeData(
1320                        ImageManager.getLastImageThumbPath());
1321            }
1322            hidePostCaptureAlert();
1323        }
1324
1325        if (mDidRegister) {
1326            unregisterReceiver(mReceiver);
1327            mDidRegister = false;
1328        }
1329        stopReceivingLocationUpdates();
1330
1331        if (mFocusToneGenerator != null) {
1332            mFocusToneGenerator.release();
1333            mFocusToneGenerator = null;
1334        }
1335
1336        if (mStorageHint != null) {
1337            mStorageHint.cancel();
1338            mStorageHint = null;
1339        }
1340
1341        // If we are in an image capture intent and has taken
1342        // a picture, we just clear it in onPause.
1343        mImageCapture.clearLastData();
1344        mImageCapture = null;
1345
1346        // Remove the messages in the event queue.
1347        mHandler.removeMessages(RESTART_PREVIEW);
1348        mHandler.removeMessages(FIRST_TIME_INIT);
1349
1350        super.onPause();
1351    }
1352
1353    @Override
1354    protected void onActivityResult(
1355            int requestCode, int resultCode, Intent data) {
1356        switch (requestCode) {
1357            case CROP_MSG: {
1358                Intent intent = new Intent();
1359                if (data != null) {
1360                    Bundle extras = data.getExtras();
1361                    if (extras != null) {
1362                        intent.putExtras(extras);
1363                    }
1364                }
1365                setResult(resultCode, intent);
1366                finish();
1367
1368                File path = getFileStreamPath(sTempCropFilename);
1369                path.delete();
1370
1371                break;
1372            }
1373        }
1374    }
1375
1376    private boolean canTakePicture() {
1377        return isCameraIdle() && mPreviewing && (mPicturesRemaining > 0);
1378    }
1379
1380    private void autoFocus() {
1381        // Initiate autofocus only when preview is started and snapshot is not
1382        // in progress.
1383        if (canTakePicture()) {
1384            mHeadUpDisplay.setEnabled(false);
1385            Log.v(TAG, "Start autofocus.");
1386            mFocusStartTime = System.currentTimeMillis();
1387            mFocusState = FOCUSING;
1388            updateFocusIndicator();
1389            mCameraDevice.autoFocus(mAutoFocusCallback);
1390        }
1391    }
1392
1393    private void cancelAutoFocus() {
1394        // User releases half-pressed focus key.
1395        if (mFocusState == FOCUSING || mFocusState == FOCUS_SUCCESS
1396                || mFocusState == FOCUS_FAIL) {
1397            Log.v(TAG, "Cancel autofocus.");
1398            mHeadUpDisplay.setEnabled(true);
1399            mCameraDevice.cancelAutoFocus();
1400        }
1401        if (mFocusState != FOCUSING_SNAP_ON_FINISH) {
1402            clearFocusState();
1403        }
1404    }
1405
1406    private void clearFocusState() {
1407        mFocusState = FOCUS_NOT_STARTED;
1408        updateFocusIndicator();
1409    }
1410
1411    private void updateFocusIndicator() {
1412        if (mFocusRectangle == null) return;
1413
1414        if (mFocusState == FOCUSING || mFocusState == FOCUSING_SNAP_ON_FINISH) {
1415            mFocusRectangle.showStart();
1416        } else if (mFocusState == FOCUS_SUCCESS) {
1417            mFocusRectangle.showSuccess();
1418        } else if (mFocusState == FOCUS_FAIL) {
1419            mFocusRectangle.showFail();
1420        } else {
1421            mFocusRectangle.clear();
1422        }
1423    }
1424
1425    @Override
1426    public void onBackPressed() {
1427        if (!isCameraIdle()) {
1428            // ignore backs while we're taking a picture
1429            return;
1430        } else if (mHeadUpDisplay == null || !mHeadUpDisplay.collapse()) {
1431            super.onBackPressed();
1432        }
1433    }
1434
1435    @Override
1436    public boolean onKeyDown(int keyCode, KeyEvent event) {
1437        switch (keyCode) {
1438            case KeyEvent.KEYCODE_FOCUS:
1439                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1440                    doFocus(true);
1441                }
1442                return true;
1443            case KeyEvent.KEYCODE_CAMERA:
1444                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1445                    doSnap();
1446                }
1447                return true;
1448            case KeyEvent.KEYCODE_DPAD_CENTER:
1449                // If we get a dpad center event without any focused view, move
1450                // the focus to the shutter button and press it.
1451                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1452                    // Start auto-focus immediately to reduce shutter lag. After
1453                    // the shutter button gets the focus, doFocus() will be
1454                    // called again but it is fine.
1455                    if (mHeadUpDisplay.collapse()) return true;
1456                    doFocus(true);
1457                    if (mShutterButton.isInTouchMode()) {
1458                        mShutterButton.requestFocusFromTouch();
1459                    } else {
1460                        mShutterButton.requestFocus();
1461                    }
1462                    mShutterButton.setPressed(true);
1463                }
1464                return true;
1465        }
1466
1467        return super.onKeyDown(keyCode, event);
1468    }
1469
1470    @Override
1471    public boolean onKeyUp(int keyCode, KeyEvent event) {
1472        switch (keyCode) {
1473            case KeyEvent.KEYCODE_FOCUS:
1474                if (mFirstTimeInitialized) {
1475                    doFocus(false);
1476                }
1477                return true;
1478        }
1479        return super.onKeyUp(keyCode, event);
1480    }
1481
1482    private void doSnap() {
1483        if (mHeadUpDisplay.collapse()) return;
1484
1485        Log.v(TAG, "doSnap: mFocusState=" + mFocusState);
1486        // If the user has half-pressed the shutter and focus is completed, we
1487        // can take the photo right away. If the focus mode is infinity, we can
1488        // also take the photo.
1489        if (mFocusMode.equals(Parameters.FOCUS_MODE_INFINITY)
1490                || (mFocusState == FOCUS_SUCCESS
1491                || mFocusState == FOCUS_FAIL)) {
1492            mImageCapture.onSnap();
1493        } else if (mFocusState == FOCUSING) {
1494            // Half pressing the shutter (i.e. the focus button event) will
1495            // already have requested AF for us, so just request capture on
1496            // focus here.
1497            mFocusState = FOCUSING_SNAP_ON_FINISH;
1498        } else if (mFocusState == FOCUS_NOT_STARTED) {
1499            // Focus key down event is dropped for some reasons. Just ignore.
1500        }
1501    }
1502
1503    private void doFocus(boolean pressed) {
1504        // Do the focus if the mode is not infinity.
1505        if (mHeadUpDisplay.collapse()) return;
1506        if (!mFocusMode.equals(Parameters.FOCUS_MODE_INFINITY)) {
1507            if (pressed) {  // Focus key down.
1508                autoFocus();
1509            } else {  // Focus key up.
1510                cancelAutoFocus();
1511            }
1512        }
1513    }
1514
1515    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
1516        // Make sure we have a surface in the holder before proceeding.
1517        if (holder.getSurface() == null) {
1518            Log.d(TAG, "holder.getSurface() == null");
1519            return;
1520        }
1521
1522        // We need to save the holder for later use, even when the mCameraDevice
1523        // is null. This could happen if onResume() is invoked after this
1524        // function.
1525        mSurfaceHolder = holder;
1526
1527        // The mCameraDevice will be null if it fails to connect to the camera
1528        // hardware. In this case we will show a dialog and then finish the
1529        // activity, so it's OK to ignore it.
1530        if (mCameraDevice == null) return;
1531
1532        // Sometimes surfaceChanged is called after onPause or before onResume.
1533        // Ignore it.
1534        if (mPausing || isFinishing()) return;
1535
1536        if (mPreviewing && holder.isCreating()) {
1537            // Set preview display if the surface is being created and preview
1538            // was already started. That means preview display was set to null
1539            // and we need to set it now.
1540            setPreviewDisplay(holder);
1541        } else {
1542            // 1. Restart the preview if the size of surface was changed. The
1543            // framework may not support changing preview display on the fly.
1544            // 2. Start the preview now if surface was destroyed and preview
1545            // stopped.
1546            restartPreview();
1547        }
1548
1549        // If first time initialization is not finished, send a message to do
1550        // it later. We want to finish surfaceChanged as soon as possible to let
1551        // user see preview first.
1552        if (!mFirstTimeInitialized) {
1553            mHandler.sendEmptyMessage(FIRST_TIME_INIT);
1554        } else {
1555            initializeSecondTime();
1556        }
1557    }
1558
1559    public void surfaceCreated(SurfaceHolder holder) {
1560    }
1561
1562    public void surfaceDestroyed(SurfaceHolder holder) {
1563        stopPreview();
1564        mSurfaceHolder = null;
1565    }
1566
1567    private void closeCamera() {
1568        if (mCameraDevice != null) {
1569            CameraHolder.instance().release();
1570            mCameraDevice.setZoomChangeListener(null);
1571            mCameraDevice = null;
1572            mPreviewing = false;
1573        }
1574    }
1575
1576    private void ensureCameraDevice() throws CameraHardwareException {
1577        if (mCameraDevice == null) {
1578            mCameraDevice = CameraHolder.instance().open();
1579            mInitialParams = mCameraDevice.getParameters();
1580        }
1581    }
1582
1583    private void updateLastImage() {
1584        IImageList list = ImageManager.makeImageList(
1585            mContentResolver,
1586            dataLocation(),
1587            ImageManager.INCLUDE_IMAGES,
1588            ImageManager.SORT_ASCENDING,
1589            ImageManager.CAMERA_IMAGE_BUCKET_ID);
1590        int count = list.getCount();
1591        if (count > 0) {
1592            IImage image = list.getImageAt(count - 1);
1593            Uri uri = image.fullSizeImageUri();
1594            mThumbController.setData(uri, image.miniThumbBitmap());
1595        } else {
1596            mThumbController.setData(null, null);
1597        }
1598        list.close();
1599    }
1600
1601    private void showCameraErrorAndFinish() {
1602        Resources ress = getResources();
1603        Util.showFatalErrorAndFinish(Camera.this,
1604                ress.getString(R.string.camera_error_title),
1605                ress.getString(R.string.cannot_connect_camera));
1606    }
1607
1608    private void restartPreview() {
1609        try {
1610            startPreview();
1611        } catch (CameraHardwareException e) {
1612            showCameraErrorAndFinish();
1613            return;
1614        }
1615    }
1616
1617    private void setPreviewDisplay(SurfaceHolder holder) {
1618        try {
1619            mCameraDevice.setPreviewDisplay(holder);
1620        } catch (Throwable ex) {
1621            closeCamera();
1622            throw new RuntimeException("setPreviewDisplay failed", ex);
1623        }
1624    }
1625
1626    private void startPreview() throws CameraHardwareException {
1627        if (mPausing || isFinishing()) return;
1628
1629        ensureCameraDevice();
1630
1631        // If we're previewing already, stop the preview first (this will blank
1632        // the screen).
1633        if (mPreviewing) stopPreview();
1634
1635        setPreviewDisplay(mSurfaceHolder);
1636        setCameraParameters(UPDATE_PARAM_ALL);
1637
1638        final long wallTimeStart = SystemClock.elapsedRealtime();
1639        final long threadTimeStart = Debug.threadCpuTimeNanos();
1640
1641        mCameraDevice.setErrorCallback(mErrorCallback);
1642
1643        try {
1644            Log.v(TAG, "startPreview");
1645            mCameraDevice.startPreview();
1646        } catch (Throwable ex) {
1647            closeCamera();
1648            throw new RuntimeException("startPreview failed", ex);
1649        }
1650        mPreviewing = true;
1651        mZoomState = ZOOM_STOPPED;
1652        mStatus = IDLE;
1653    }
1654
1655    private void stopPreview() {
1656        if (mCameraDevice != null && mPreviewing) {
1657            Log.v(TAG, "stopPreview");
1658            mCameraDevice.stopPreview();
1659        }
1660        mPreviewing = false;
1661        // If auto focus was in progress, it would have been canceled.
1662        clearFocusState();
1663    }
1664
1665    private Size getOptimalPreviewSize(List<Size> sizes, double targetRatio) {
1666        final double ASPECT_TOLERANCE = 0.05;
1667        if (sizes == null) return null;
1668
1669        Size optimalSize = null;
1670        double minDiff = Double.MAX_VALUE;
1671
1672        // Because of bugs of overlay and layout, we sometimes will try to
1673        // layout the viewfinder in the portrait orientation and thus get the
1674        // wrong size of mSurfaceView. When we change the preview size, the
1675        // new overlay will be created before the old one closed, which causes
1676        // an exception. For now, just get the screen size
1677
1678        Display display = getWindowManager().getDefaultDisplay();
1679        int targetHeight = Math.min(display.getHeight(), display.getWidth());
1680
1681        if (targetHeight <= 0) {
1682            // We don't know the size of SurefaceView, use screen height
1683            WindowManager windowManager = (WindowManager)
1684                    getSystemService(Context.WINDOW_SERVICE);
1685            targetHeight = windowManager.getDefaultDisplay().getHeight();
1686        }
1687
1688        // Try to find an size match aspect ratio and size
1689        for (Size size : sizes) {
1690            double ratio = (double) size.width / size.height;
1691            if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
1692            if (Math.abs(size.height - targetHeight) < minDiff) {
1693                optimalSize = size;
1694                minDiff = Math.abs(size.height - targetHeight);
1695            }
1696        }
1697
1698        // Cannot find the one match the aspect ratio, ignore the requirement
1699        if (optimalSize == null) {
1700            Log.v(TAG, "No preview size match the aspect ratio");
1701            minDiff = Double.MAX_VALUE;
1702            for (Size size : sizes) {
1703                if (Math.abs(size.height - targetHeight) < minDiff) {
1704                    optimalSize = size;
1705                    minDiff = Math.abs(size.height - targetHeight);
1706                }
1707            }
1708        }
1709        return optimalSize;
1710    }
1711
1712    private static boolean isSupported(String value, List<String> supported) {
1713        return supported == null ? false : supported.indexOf(value) >= 0;
1714    }
1715
1716    private void updateCameraParametersInitialize() {
1717        // Reset preview frame rate to the maximum because it may be lowered by
1718        // video camera application.
1719        List<Integer> frameRates = mParameters.getSupportedPreviewFrameRates();
1720        if (frameRates != null) {
1721            Integer max = Collections.max(frameRates);
1722            mParameters.setPreviewFrameRate(max);
1723        }
1724
1725    }
1726
1727    private void updateCameraParametersZoom() {
1728        // Set zoom.
1729        if (mParameters.isZoomSupported()) {
1730            mParameters.setZoom(mZoomValue);
1731        }
1732    }
1733
1734    private void updateCameraParametersPreference() {
1735        // Set picture size.
1736        String pictureSize = mPreferences.getString(
1737                CameraSettings.KEY_PICTURE_SIZE, null);
1738        if (pictureSize == null) {
1739            CameraSettings.initialCameraPictureSize(this, mParameters);
1740        } else {
1741            List<Size> supported = mParameters.getSupportedPictureSizes();
1742            CameraSettings.setCameraPictureSize(
1743                    pictureSize, supported, mParameters);
1744        }
1745
1746        // Set the preview frame aspect ratio according to the picture size.
1747        Size size = mParameters.getPictureSize();
1748        PreviewFrameLayout frameLayout =
1749                (PreviewFrameLayout) findViewById(R.id.frame_layout);
1750        frameLayout.setAspectRatio((double) size.width / size.height);
1751
1752        // Set a preview size that is closest to the viewfinder height and has
1753        // the right aspect ratio.
1754        List<Size> sizes = mParameters.getSupportedPreviewSizes();
1755        Size optimalSize = getOptimalPreviewSize(
1756                sizes, (double) size.width / size.height);
1757        if (optimalSize != null) {
1758            Size original = mParameters.getPreviewSize();
1759            if (!original.equals(optimalSize)) {
1760                mParameters.setPreviewSize(optimalSize.width, optimalSize.height);
1761
1762                // Zoom related settings will be changed for different preview
1763                // sizes, so set and read the parameters to get lastest values
1764                mCameraDevice.setParameters(mParameters);
1765                mParameters = mCameraDevice.getParameters();
1766            }
1767        }
1768
1769        // Since change scene mode may change supported values,
1770        // Set scene mode first,
1771        mSceneMode = mPreferences.getString(
1772                CameraSettings.KEY_SCENE_MODE,
1773                getString(R.string.pref_camera_scenemode_default));
1774        if (isSupported(mSceneMode, mParameters.getSupportedSceneModes())) {
1775            if (!mParameters.getSceneMode().equals(mSceneMode)) {
1776                mParameters.setSceneMode(mSceneMode);
1777                mCameraDevice.setParameters(mParameters);
1778
1779                // Setting scene mode will change the settings of flash mode,
1780                // white balance, and focus mode. Here we read back the
1781                // parameters, so we can know those settings.
1782                mParameters = mCameraDevice.getParameters();
1783            }
1784        } else {
1785            mSceneMode = mParameters.getSceneMode();
1786            if (mSceneMode == null) {
1787                mSceneMode = Parameters.SCENE_MODE_AUTO;
1788            }
1789        }
1790
1791        // Set JPEG quality.
1792        String jpegQuality = mPreferences.getString(
1793                CameraSettings.KEY_JPEG_QUALITY,
1794                getString(R.string.pref_camera_jpegquality_default));
1795        mParameters.setJpegQuality(JpegEncodingQualityMappings.getQualityNumber(jpegQuality));
1796
1797        // For the following settings, we need to check if the settings are
1798        // still supported by latest driver, if not, ignore the settings.
1799
1800        // Set color effect parameter.
1801        String colorEffect = mPreferences.getString(
1802                CameraSettings.KEY_COLOR_EFFECT,
1803                getString(R.string.pref_camera_coloreffect_default));
1804        if (isSupported(colorEffect, mParameters.getSupportedColorEffects())) {
1805            mParameters.setColorEffect(colorEffect);
1806        }
1807
1808        // Set exposure compensation
1809        String exposure = mPreferences.getString(
1810                CameraSettings.KEY_EXPOSURE,
1811                getString(R.string.pref_exposure_default));
1812        try {
1813            int value = Integer.parseInt(exposure);
1814            int max = mParameters.getMaxExposureCompensation();
1815            int min = mParameters.getMinExposureCompensation();
1816            if (value >= min && value <= max) {
1817                mParameters.setExposureCompensation(value);
1818            } else {
1819                Log.w(TAG, "invalid exposure range: " + exposure);
1820            }
1821        } catch (NumberFormatException e) {
1822            Log.w(TAG, "invalid exposure: " + exposure);
1823        }
1824
1825        if (mGLRootView != null) updateSceneModeInHud();
1826
1827        if (Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) {
1828            // Set flash mode.
1829            String flashMode = mPreferences.getString(
1830                    CameraSettings.KEY_FLASH_MODE,
1831                    getString(R.string.pref_camera_flashmode_default));
1832            List<String> supportedFlash = mParameters.getSupportedFlashModes();
1833            if (isSupported(flashMode, supportedFlash)) {
1834                mParameters.setFlashMode(flashMode);
1835            } else {
1836                flashMode = mParameters.getFlashMode();
1837                if (flashMode == null) {
1838                    flashMode = getString(
1839                            R.string.pref_camera_flashmode_no_flash);
1840                }
1841            }
1842
1843            // Set white balance parameter.
1844            String whiteBalance = mPreferences.getString(
1845                    CameraSettings.KEY_WHITE_BALANCE,
1846                    getString(R.string.pref_camera_whitebalance_default));
1847            if (isSupported(whiteBalance,
1848                    mParameters.getSupportedWhiteBalance())) {
1849                mParameters.setWhiteBalance(whiteBalance);
1850            } else {
1851                whiteBalance = mParameters.getWhiteBalance();
1852                if (whiteBalance == null) {
1853                    whiteBalance = Parameters.WHITE_BALANCE_AUTO;
1854                }
1855            }
1856
1857            // Set focus mode.
1858            mFocusMode = mPreferences.getString(
1859                    CameraSettings.KEY_FOCUS_MODE,
1860                    getString(R.string.pref_camera_focusmode_default));
1861            if (isSupported(mFocusMode, mParameters.getSupportedFocusModes())) {
1862                mParameters.setFocusMode(mFocusMode);
1863            } else {
1864                mFocusMode = mParameters.getFocusMode();
1865                if (mFocusMode == null) {
1866                    mFocusMode = Parameters.FOCUS_MODE_AUTO;
1867                }
1868            }
1869        } else {
1870            mFocusMode = mParameters.getFocusMode();
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            updateCameraParametersPreference();
1890        }
1891
1892        mCameraDevice.setParameters(mParameters);
1893    }
1894
1895    // If the Camera is idle, update the parameters immediately, otherwise
1896    // accumulate them in mUpdateSet and update later.
1897    private void setCameraParametersWhenIdle(int additionalUpdateSet) {
1898        mUpdateSet |= additionalUpdateSet;
1899        if (mCameraDevice == null) {
1900            // We will update all the parameters when we open the device, so
1901            // we don't need to do anything now.
1902            mUpdateSet = 0;
1903            return;
1904        } else if (isCameraIdle()) {
1905            setCameraParameters(mUpdateSet);
1906            mUpdateSet = 0;
1907        } else {
1908            if (!mHandler.hasMessages(SET_CAMERA_PARAMETERS_WHEN_IDLE)) {
1909                mHandler.sendEmptyMessageDelayed(
1910                        SET_CAMERA_PARAMETERS_WHEN_IDLE, 1000);
1911            }
1912        }
1913    }
1914
1915    private void gotoGallery() {
1916        MenuHelper.gotoCameraImageGallery(this);
1917    }
1918
1919    private void viewLastImage() {
1920        if (mThumbController.isUriValid()) {
1921            Intent intent = new Intent(Util.REVIEW_ACTION, mThumbController.getUri());
1922            try {
1923                startActivity(intent);
1924            } catch (ActivityNotFoundException ex) {
1925                Log.e(TAG, "review image fail", ex);
1926            }
1927        } else {
1928            Log.e(TAG, "Can't view last image.");
1929        }
1930    }
1931
1932    private void startReceivingLocationUpdates() {
1933        if (mLocationManager != null) {
1934            try {
1935                mLocationManager.requestLocationUpdates(
1936                        LocationManager.NETWORK_PROVIDER,
1937                        1000,
1938                        0F,
1939                        mLocationListeners[1]);
1940            } catch (java.lang.SecurityException ex) {
1941                Log.i(TAG, "fail to request location update, ignore", ex);
1942            } catch (IllegalArgumentException ex) {
1943                Log.d(TAG, "provider does not exist " + ex.getMessage());
1944            }
1945            try {
1946                mLocationManager.requestLocationUpdates(
1947                        LocationManager.GPS_PROVIDER,
1948                        1000,
1949                        0F,
1950                        mLocationListeners[0]);
1951            } catch (java.lang.SecurityException ex) {
1952                Log.i(TAG, "fail to request location update, ignore", ex);
1953            } catch (IllegalArgumentException ex) {
1954                Log.d(TAG, "provider does not exist " + ex.getMessage());
1955            }
1956        }
1957    }
1958
1959    private void stopReceivingLocationUpdates() {
1960        if (mLocationManager != null) {
1961            for (int i = 0; i < mLocationListeners.length; i++) {
1962                try {
1963                    mLocationManager.removeUpdates(mLocationListeners[i]);
1964                } catch (Exception ex) {
1965                    Log.i(TAG, "fail to remove location listners, ignore", ex);
1966                }
1967            }
1968        }
1969    }
1970
1971    private Location getCurrentLocation() {
1972        // go in best to worst order
1973        for (int i = 0; i < mLocationListeners.length; i++) {
1974            Location l = mLocationListeners[i].current();
1975            if (l != null) return l;
1976        }
1977        return null;
1978    }
1979
1980    private boolean isCameraIdle() {
1981        return mStatus == IDLE && mFocusState == FOCUS_NOT_STARTED;
1982    }
1983
1984    private boolean isImageCaptureIntent() {
1985        String action = getIntent().getAction();
1986        return (MediaStore.ACTION_IMAGE_CAPTURE.equals(action));
1987    }
1988
1989    private void setupCaptureParams() {
1990        Bundle myExtras = getIntent().getExtras();
1991        if (myExtras != null) {
1992            mSaveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT);
1993            mCropValue = myExtras.getString("crop");
1994        }
1995    }
1996
1997    private void showPostCaptureAlert() {
1998        if (mIsImageCaptureIntent) {
1999            findViewById(R.id.shutter_button).setVisibility(View.INVISIBLE);
2000            int[] pickIds = {R.id.btn_retake, R.id.btn_done};
2001            for (int id : pickIds) {
2002                View button = findViewById(id);
2003                ((View) button.getParent()).setVisibility(View.VISIBLE);
2004            }
2005        }
2006    }
2007
2008    private void hidePostCaptureAlert() {
2009        if (mIsImageCaptureIntent) {
2010            findViewById(R.id.shutter_button).setVisibility(View.VISIBLE);
2011            int[] pickIds = {R.id.btn_retake, R.id.btn_done};
2012            for (int id : pickIds) {
2013                View button = findViewById(id);
2014                ((View) button.getParent()).setVisibility(View.GONE);
2015            }
2016        }
2017    }
2018
2019    private int calculatePicturesRemaining() {
2020        mPicturesRemaining = MenuHelper.calculatePicturesRemaining();
2021        return mPicturesRemaining;
2022    }
2023
2024    @Override
2025    public boolean onPrepareOptionsMenu(Menu menu) {
2026        super.onPrepareOptionsMenu(menu);
2027        // Only show the menu when camera is idle.
2028        for (int i = 0; i < menu.size(); i++) {
2029            menu.getItem(i).setVisible(isCameraIdle());
2030        }
2031
2032        return true;
2033    }
2034
2035    @Override
2036    public boolean onCreateOptionsMenu(Menu menu) {
2037        super.onCreateOptionsMenu(menu);
2038
2039        if (mIsImageCaptureIntent) {
2040            // No options menu for attach mode.
2041            return false;
2042        } else {
2043            addBaseMenuItems(menu);
2044        }
2045        return true;
2046    }
2047
2048    private void addBaseMenuItems(Menu menu) {
2049        MenuHelper.addSwitchModeMenuItem(menu, true, new Runnable() {
2050            public void run() {
2051                switchToVideoMode();
2052            }
2053        });
2054        MenuItem gallery = menu.add(Menu.NONE, Menu.NONE,
2055                MenuHelper.POSITION_GOTO_GALLERY,
2056                R.string.camera_gallery_photos_text)
2057                .setOnMenuItemClickListener(new OnMenuItemClickListener() {
2058            public boolean onMenuItemClick(MenuItem item) {
2059                gotoGallery();
2060                return true;
2061            }
2062        });
2063        gallery.setIcon(android.R.drawable.ic_menu_gallery);
2064        mGalleryItems.add(gallery);
2065    }
2066
2067    private boolean switchToVideoMode() {
2068        if (isFinishing() || !isCameraIdle()) return false;
2069        MenuHelper.gotoVideoMode(this);
2070        mHandler.removeMessages(FIRST_TIME_INIT);
2071        finish();
2072        return true;
2073    }
2074
2075    public boolean onSwitchChanged(Switcher source, boolean onOff) {
2076        if (onOff == SWITCH_VIDEO) {
2077            return switchToVideoMode();
2078        } else {
2079            return true;
2080        }
2081    }
2082
2083    private void onSharedPreferenceChanged() {
2084        // ignore the events after "onPause()"
2085        if (mPausing) return;
2086
2087        boolean recordLocation;
2088
2089        recordLocation = RecordLocationPreference.get(
2090                mPreferences, getContentResolver());
2091        mQuickCapture = getQuickCaptureSettings();
2092
2093        if (mRecordLocation != recordLocation) {
2094            mRecordLocation = recordLocation;
2095            if (mRecordLocation) {
2096                startReceivingLocationUpdates();
2097            } else {
2098                stopReceivingLocationUpdates();
2099            }
2100        }
2101
2102        setCameraParametersWhenIdle(UPDATE_PARAM_PREFERENCE);
2103    }
2104
2105    private boolean getQuickCaptureSettings() {
2106        String value = mPreferences.getString(
2107                CameraSettings.KEY_QUICK_CAPTURE,
2108                getString(R.string.pref_camera_quickcapture_default));
2109        return CameraSettings.QUICK_CAPTURE_ON.equals(value);
2110    }
2111
2112    @Override
2113    public void onUserInteraction() {
2114        super.onUserInteraction();
2115        keepScreenOnAwhile();
2116    }
2117
2118    private void resetScreenOn() {
2119        mHandler.removeMessages(CLEAR_SCREEN_DELAY);
2120        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
2121    }
2122
2123    private void keepScreenOnAwhile() {
2124        mHandler.removeMessages(CLEAR_SCREEN_DELAY);
2125        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
2126        mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY);
2127    }
2128
2129    private class MyHeadUpDisplayListener implements HeadUpDisplay.Listener {
2130
2131        public void onSharedPreferencesChanged() {
2132            Camera.this.onSharedPreferenceChanged();
2133        }
2134
2135        public void onRestorePreferencesClicked() {
2136            Camera.this.onRestorePreferencesClicked();
2137        }
2138
2139        public void onPopupWindowVisibilityChanged(int visibility) {
2140        }
2141    }
2142
2143    protected void onRestorePreferencesClicked() {
2144        if (mPausing) return;
2145        Runnable runnable = new Runnable() {
2146            public void run() {
2147                mHeadUpDisplay.restorePreferences(mParameters);
2148            }
2149        };
2150        MenuHelper.confirmAction(this,
2151                getString(R.string.confirm_restore_title),
2152                getString(R.string.confirm_restore_message),
2153                runnable);
2154    }
2155}
2156
2157class FocusRectangle extends View {
2158
2159    @SuppressWarnings("unused")
2160    private static final String TAG = "FocusRectangle";
2161
2162    public FocusRectangle(Context context, AttributeSet attrs) {
2163        super(context, attrs);
2164    }
2165
2166    private void setDrawable(int resid) {
2167        setBackgroundDrawable(getResources().getDrawable(resid));
2168    }
2169
2170    public void showStart() {
2171        setDrawable(R.drawable.focus_focusing);
2172    }
2173
2174    public void showSuccess() {
2175        setDrawable(R.drawable.focus_focused);
2176    }
2177
2178    public void showFail() {
2179        setDrawable(R.drawable.focus_focus_failed);
2180    }
2181
2182    public void clear() {
2183        setBackgroundDrawable(null);
2184    }
2185}
2186
2187/*
2188 * Provide a mapping for Jpeg encoding quality levels
2189 * from String representation to numeric representation.
2190 */
2191class JpegEncodingQualityMappings {
2192    private static final String TAG = "JpegEncodingQualityMappings";
2193    private static final int DEFAULT_QUALITY = 85;
2194    private static HashMap<String, Integer> mHashMap =
2195            new HashMap<String, Integer>();
2196
2197    static {
2198        mHashMap.put("normal",    CameraProfile.QUALITY_LOW);
2199        mHashMap.put("fine",      CameraProfile.QUALITY_MEDIUM);
2200        mHashMap.put("superfine", CameraProfile.QUALITY_HIGH);
2201    }
2202
2203    // Retrieve and return the Jpeg encoding quality number
2204    // for the given quality level.
2205    public static int getQualityNumber(String jpegQuality) {
2206        Integer quality = mHashMap.get(jpegQuality);
2207        if (quality == null) {
2208            Log.w(TAG, "Unknown Jpeg quality: " + jpegQuality);
2209            return DEFAULT_QUALITY;
2210        }
2211        return CameraProfile.getJpegEncodingQualityParameter(quality.intValue());
2212    }
2213}
2214