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