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