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