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