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