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