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