Camera.java revision c30e5c21c3858c15473427d82608c473d44bf3e4
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.View;
61import android.view.ViewGroup;
62import android.view.Window;
63import android.view.WindowManager;
64import android.view.MenuItem.OnMenuItemClickListener;
65import android.widget.ImageView;
66import android.widget.ZoomButtonsController;
67
68import com.android.camera.gallery.IImage;
69import com.android.camera.gallery.IImageList;
70
71import java.io.File;
72import java.io.FileNotFoundException;
73import java.io.FileOutputStream;
74import java.io.IOException;
75import java.io.OutputStream;
76import java.util.ArrayList;
77import java.util.Collections;
78import java.util.List;
79
80/**
81 * Activity of the Camera which used to see preview and take pictures.
82 */
83public class Camera extends Activity implements View.OnClickListener,
84        ShutterButton.OnShutterButtonListener, SurfaceHolder.Callback,
85        Switcher.OnSwitchListener, OnScreenSettings.OnVisibilityChangedListener,
86        OnSharedPreferenceChangeListener {
87
88    private static final String TAG = "camera";
89
90    private static final int CROP_MSG = 1;
91    private static final int FIRST_TIME_INIT = 2;
92    private static final int RESTART_PREVIEW = 3;
93    private static final int CLEAR_SCREEN_DELAY = 4;
94
95    private static final String GPS_MODE_ON = "on";
96    private static final String GPS_MODE_OFF = "off";
97
98    private static final int SCREEN_DELAY = 2 * 60 * 1000;
99    private static final int FOCUS_BEEP_VOLUME = 100;
100
101    private double mZoomValue;  // The current zoom value.
102    private double mZoomStep;
103    private double mZoomMax;
104    public static final double ZOOM_STEP_MIN = 0.25;
105    public static final String ZOOM_STOP = "stop";
106    public static final String ZOOM_IMMEDIATE = "zoom-immediate";
107    public static final String ZOOM_CONTINUOUS = "zoom-continuous";
108    public static final double ZOOM_MIN = 1.0;
109    public static final String ZOOM_SPEED = "99";
110
111    private Parameters mParameters;
112
113    // The parameter strings to communicate with camera driver.
114    public static final String PARM_ZOOM_STATE = "zoom-state";
115    public static final String PARM_ZOOM_STEP = "zoom-step";
116    public static final String PARM_ZOOM_TO_LEVEL = "zoom-to-level";
117    public static final String PARM_ZOOM_SPEED = "zoom-speed";
118    public static final String PARM_ZOOM_MAX = "max-picture-continuous-zoom";
119
120    private OrientationEventListener mOrientationListener;
121    private int mLastOrientation = OrientationEventListener.ORIENTATION_UNKNOWN;
122    private SharedPreferences mPreferences;
123
124    private static final int IDLE = 1;
125    private static final int SNAPSHOT_IN_PROGRESS = 2;
126
127    private static final boolean SWITCH_CAMERA = true;
128    private static final boolean SWITCH_VIDEO = false;
129
130    private int mStatus = IDLE;
131    private static final String sTempCropFilename = "crop-temp";
132
133    private android.hardware.Camera mCameraDevice;
134    private VideoPreview mSurfaceView;
135    private SurfaceHolder mSurfaceHolder = null;
136    private ShutterButton mShutterButton;
137    private FocusRectangle mFocusRectangle;
138    private IconIndicator mGpsIndicator;
139    private IconIndicator mFlashIndicator;
140    private ToneGenerator mFocusToneGenerator;
141    private ZoomButtonsController mZoomButtons;
142    private GestureDetector mGestureDetector;
143    private Switcher mSwitcher;
144    private boolean mStartPreviewFail = false;
145
146    // mPostCaptureAlert, mLastPictureButton, mThumbController
147    // are non-null only if isImageCaptureIntent() is true.
148    private ImageView mLastPictureButton;
149    private ThumbnailController mThumbController;
150
151    // mCropValue and mSaveUri are used only if isImageCaptureIntent() is true.
152    private String mCropValue;
153    private Uri mSaveUri;
154
155    private int mViewFinderHeight;
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        findViewById(R.id.btn_gripper).setVisibility(
389                visible ? View.INVISIBLE : View.VISIBLE);
390    }
391
392    private boolean isZooming() {
393        mParameters = mCameraDevice.getParameters();
394        return "continuous".equals(mParameters.get(PARM_ZOOM_STATE));
395    }
396
397    private void zoomToLevel(String type, double zoomValue) {
398        if (zoomValue > mZoomMax) zoomValue = mZoomMax;
399        if (zoomValue < ZOOM_MIN) zoomValue = ZOOM_MIN;
400
401        // If the application sets a unchanged zoom value, the driver will stuck
402        // at the zoom state. This is a work-around to ensure the state is at
403        // "stop".
404        mParameters.set(PARM_ZOOM_STATE, ZOOM_STOP);
405        mCameraDevice.setParameters(mParameters);
406
407        mParameters.set(PARM_ZOOM_TO_LEVEL, Double.toString(zoomValue));
408        mParameters.set(PARM_ZOOM_STATE, type);
409        mCameraDevice.setParameters(mParameters);
410
411        if (ZOOM_IMMEDIATE.equals(type)) mZoomValue = zoomValue;
412    }
413
414    private void updateZoomButtonsEnabled() {
415        mZoomButtons.setZoomInEnabled(mZoomValue < mZoomMax);
416        mZoomButtons.setZoomOutEnabled(mZoomValue > ZOOM_MIN);
417    }
418
419    private class ZoomGestureListener extends
420            GestureDetector.SimpleOnGestureListener {
421        @Override
422        public boolean onDown(MotionEvent e) {
423            // Show zoom buttons only when preview is started and snapshot
424            // is not in progress. mZoomButtons may be null if it is not
425            // initialized.
426            if (!mPausing && isCameraIdle() && mPreviewing
427                    && mZoomButtons != null) {
428                mZoomButtons.setVisible(true);
429            }
430            return true;
431        }
432
433        @Override
434        public boolean onDoubleTap(MotionEvent e) {
435            // Perform zoom only when preview is started and snapshot is not in
436            // progress.
437            if (mPausing || !isCameraIdle() || !mPreviewing
438                    || mZoomButtons == null || isZooming()) {
439                return false;
440            }
441
442            if (mZoomValue < mZoomMax) {
443                // Zoom in to the maximum.
444                while (mZoomValue < mZoomMax) {
445                    zoomToLevel(ZOOM_IMMEDIATE, mZoomValue + ZOOM_STEP_MIN);
446                    // Wait for a while so we are not changing zoom too fast.
447                    try {
448                        Thread.sleep(5);
449                    } catch (InterruptedException ex) {
450                    }
451                }
452            } else {
453                // Zoom out to the minimum.
454                while (mZoomValue > ZOOM_MIN) {
455                    zoomToLevel(ZOOM_IMMEDIATE, mZoomValue - ZOOM_STEP_MIN);
456                    // Wait for a while so we are not changing zoom too fast.
457                    try {
458                        Thread.sleep(5);
459                    } catch (InterruptedException ex) {
460                    }
461                }
462            }
463            updateZoomButtonsEnabled();
464            return true;
465        }
466    }
467
468    @Override
469    public boolean dispatchTouchEvent(MotionEvent m) {
470        if (!super.dispatchTouchEvent(m) && mGestureDetector != null) {
471            return mGestureDetector.onTouchEvent(m);
472        }
473        return true;
474    }
475
476    LocationListener [] mLocationListeners = new LocationListener[] {
477            new LocationListener(LocationManager.GPS_PROVIDER),
478            new LocationListener(LocationManager.NETWORK_PROVIDER)
479    };
480
481    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
482        @Override
483        public void onReceive(Context context, Intent intent) {
484            String action = intent.getAction();
485            if (action.equals(Intent.ACTION_MEDIA_MOUNTED)
486                    || action.equals(Intent.ACTION_MEDIA_UNMOUNTED)
487                    || action.equals(Intent.ACTION_MEDIA_CHECKING)
488                    || action.equals(Intent.ACTION_MEDIA_SCANNER_STARTED)) {
489                checkStorage();
490            } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)) {
491                checkStorage();
492                if (!mIsImageCaptureIntent)  {
493                    updateThumbnailButton();
494                }
495            }
496        }
497    };
498
499    private class LocationListener
500            implements android.location.LocationListener {
501        Location mLastLocation;
502        boolean mValid = false;
503        String mProvider;
504
505        public LocationListener(String provider) {
506            mProvider = provider;
507            mLastLocation = new Location(mProvider);
508        }
509
510        public void onLocationChanged(Location newLocation) {
511            if (newLocation.getLatitude() == 0.0
512                    && newLocation.getLongitude() == 0.0) {
513                // Hack to filter out 0.0,0.0 locations
514                return;
515            }
516            // If GPS is available before start camera, we won't get status
517            // update so update GPS indicator when we receive data.
518            if (mRecordLocation
519                    && LocationManager.GPS_PROVIDER.equals(mProvider)) {
520                mGpsIndicator.setMode(GPS_MODE_ON);
521            }
522            mLastLocation.set(newLocation);
523            mValid = true;
524        }
525
526        public void onProviderEnabled(String provider) {
527        }
528
529        public void onProviderDisabled(String provider) {
530            mValid = false;
531        }
532
533        public void onStatusChanged(
534                String provider, int status, Bundle extras) {
535            switch(status) {
536                case LocationProvider.OUT_OF_SERVICE:
537                case LocationProvider.TEMPORARILY_UNAVAILABLE: {
538                    mValid = false;
539                    if (mRecordLocation &&
540                            LocationManager.GPS_PROVIDER.equals(provider)) {
541                        mGpsIndicator.setMode(GPS_MODE_OFF);
542                    }
543                    break;
544                }
545            }
546        }
547
548        public Location current() {
549            return mValid ? mLastLocation : null;
550        }
551    }
552
553    private final class OneShotPreviewCallback
554            implements android.hardware.Camera.PreviewCallback {
555        public void onPreviewFrame(byte[] data,
556                                   android.hardware.Camera camera) {
557            long now = System.currentTimeMillis();
558            if (mJpegPictureCallbackTime != 0) {
559                mJpegPictureCallbackTimeLag = now - mJpegPictureCallbackTime;
560                Log.v(TAG, "mJpegPictureCallbackTimeLag = "
561                        + mJpegPictureCallbackTimeLag + "ms");
562                mJpegPictureCallbackTime = 0;
563            } else {
564                Log.v(TAG, "Got first frame");
565            }
566        }
567    }
568
569    private final class ShutterCallback
570            implements android.hardware.Camera.ShutterCallback {
571        public void onShutter() {
572            mShutterCallbackTime = System.currentTimeMillis();
573            mShutterLag = mShutterCallbackTime - mCaptureStartTime;
574            Log.v(TAG, "mShutterLag = " + mShutterLag + "ms");
575            clearFocusState();
576        }
577    }
578
579    private final class RawPictureCallback implements PictureCallback {
580        public void onPictureTaken(
581                byte [] rawData, android.hardware.Camera camera) {
582            mRawPictureCallbackTime = System.currentTimeMillis();
583            mShutterAndRawPictureCallbackTime =
584                mRawPictureCallbackTime - mShutterCallbackTime;
585            Log.v(TAG, "mShutterAndRawPictureCallbackTime = "
586                    + mShutterAndRawPictureCallbackTime + "ms");
587        }
588    }
589
590    private final class JpegPictureCallback implements PictureCallback {
591        Location mLocation;
592
593        public JpegPictureCallback(Location loc) {
594            mLocation = loc;
595        }
596
597        public void onPictureTaken(
598                final byte [] jpegData, final android.hardware.Camera camera) {
599            if (mPausing) {
600                return;
601            }
602
603            mJpegPictureCallbackTime = System.currentTimeMillis();
604            mRawPictureAndJpegPictureCallbackTime =
605                mJpegPictureCallbackTime - mRawPictureCallbackTime;
606            Log.v(TAG, "mRawPictureAndJpegPictureCallbackTime = "
607                    + mRawPictureAndJpegPictureCallbackTime + "ms");
608            mImageCapture.storeImage(jpegData, camera, mLocation);
609
610            if (!mIsImageCaptureIntent) {
611                long delay = 1200 - (
612                        System.currentTimeMillis() - mRawPictureCallbackTime);
613                mHandler.sendEmptyMessageDelayed(
614                        RESTART_PREVIEW, Math.max(delay, 0));
615            }
616        }
617    }
618
619    private final class AutoFocusCallback
620            implements android.hardware.Camera.AutoFocusCallback {
621        public void onAutoFocus(
622                boolean focused, android.hardware.Camera camera) {
623            mFocusCallbackTime = System.currentTimeMillis();
624            mAutoFocusTime = mFocusCallbackTime - mFocusStartTime;
625            Log.v(TAG, "mAutoFocusTime = " + mAutoFocusTime + "ms");
626            if (mFocusState == FOCUSING_SNAP_ON_FINISH) {
627                // Take the picture no matter focus succeeds or fails. No need
628                // to play the AF sound if we're about to play the shutter
629                // sound.
630                if (focused) {
631                    mFocusState = FOCUS_SUCCESS;
632                } else {
633                    mFocusState = FOCUS_FAIL;
634                }
635                mImageCapture.onSnap();
636            } else if (mFocusState == FOCUSING) {
637                // User is half-pressing the focus key. Play the focus tone.
638                // Do not take the picture now.
639                ToneGenerator tg = mFocusToneGenerator;
640                if (tg != null) {
641                    tg.startTone(ToneGenerator.TONE_PROP_BEEP2);
642                }
643                if (focused) {
644                    mFocusState = FOCUS_SUCCESS;
645                } else {
646                    mFocusState = FOCUS_FAIL;
647                }
648            } else if (mFocusState == FOCUS_NOT_STARTED) {
649                // User has released the focus key before focus completes.
650                // Do nothing.
651            }
652            updateFocusIndicator();
653        }
654    }
655
656    private final class ErrorCallback
657        implements android.hardware.Camera.ErrorCallback {
658        public void onError(int error, android.hardware.Camera camera) {
659            if (error == android.hardware.Camera.CAMERA_ERROR_SERVER_DIED) {
660                 mMediaServerDied = true;
661                 Log.v(TAG, "media server died");
662            }
663        }
664    }
665
666    private final class ZoomCallback
667        implements android.hardware.Camera.ZoomCallback {
668        public void onZoomUpdate(int zoomLevel,
669                                 android.hardware.Camera camera) {
670            mZoomValue = (double) zoomLevel / 1000;
671            Log.v(TAG, "ZoomCallback: zoom level=" + zoomLevel);
672            updateZoomButtonsEnabled();
673        }
674    }
675
676    private class ImageCapture {
677
678        private boolean mCancel = false;
679
680        private Uri mLastContentUri;
681
682        byte[] mCaptureOnlyData;
683
684        // Returns the rotation degree in the jpeg header.
685        private int storeImage(byte[] data, Location loc) {
686            try {
687                long dateTaken = System.currentTimeMillis();
688                String name = createName(dateTaken) + ".jpg";
689                mLastContentUri = ImageManager.addImage(
690                        mContentResolver,
691                        name,
692                        dateTaken,
693                        loc, // location for the database goes here
694                        0, // the dsp will use the right orientation so
695                           // don't "double set it"
696                        ImageManager.CAMERA_IMAGE_BUCKET_NAME,
697                        name);
698                if (mLastContentUri == null) {
699                    // this means we got an error
700                    mCancel = true;
701                }
702                int degree = 0;
703                if (!mCancel) {
704                    degree = ImageManager.storeImage(mLastContentUri, mContentResolver,
705                            null, data);
706                    ImageManager.setImageSize(mContentResolver, mLastContentUri,
707                            new File(ImageManager.CAMERA_IMAGE_BUCKET_NAME,
708                            name).length());
709                }
710                return degree;
711            } catch (Exception ex) {
712                Log.e(TAG, "Exception while compressing image.", ex);
713                return 0;
714            }
715        }
716
717        public void storeImage(final byte[] data,
718                android.hardware.Camera camera, Location loc) {
719            if (!mIsImageCaptureIntent) {
720                int degree = storeImage(data, loc);
721                sendBroadcast(new Intent(
722                        "com.android.camera.NEW_PICTURE", mLastContentUri));
723                setLastPictureThumb(data, degree,
724                        mImageCapture.getLastCaptureUri());
725                mThumbController.updateDisplayIfNeeded();
726            } else {
727                mCaptureOnlyData = data;
728                showPostCaptureAlert();
729            }
730        }
731
732        /**
733         * Initiate the capture of an image.
734         */
735        public void initiate() {
736            if (mCameraDevice == null) {
737                return;
738            }
739
740            mCancel = false;
741
742            capture();
743        }
744
745        public Uri getLastCaptureUri() {
746            return mLastContentUri;
747        }
748
749        public byte[] getLastCaptureData() {
750            return mCaptureOnlyData;
751        }
752
753        private void capture() {
754            mCaptureOnlyData = null;
755
756            // Set rotation.
757            int orientation = mLastOrientation;
758            if (orientation != OrientationEventListener.ORIENTATION_UNKNOWN) {
759                orientation += 90;
760            }
761            orientation = ImageManager.roundOrientation(orientation);
762            Log.v(TAG, "mLastOrientation = " + mLastOrientation
763                    + ", orientation = " + orientation);
764            mParameters.setRotation(orientation);
765
766            // Clear previous GPS location from the parameters.
767            mParameters.removeGpsData();
768
769            // Set GPS location.
770            Location loc = mRecordLocation ? getCurrentLocation() : null;
771            if (loc != null) {
772                double lat = loc.getLatitude();
773                double lon = loc.getLongitude();
774                boolean hasLatLon = (lat != 0.0d) || (lon != 0.0d);
775
776                if (hasLatLon) {
777                    mParameters.setGpsLatitude(lat);
778                    mParameters.setGpsLongitude(lon);
779                    if (loc.hasAltitude()) {
780                        mParameters.setGpsAltitude(loc.getAltitude());
781                    } else {
782                        // for NETWORK_PROVIDER location provider, we may have
783                        // no altitude information, but the driver needs it, so
784                        // we fake one.
785                        mParameters.setGpsAltitude(0);
786                    }
787                    if (loc.getTime() != 0) {
788                        // Location.getTime() is UTC in milliseconds.
789                        // gps-timestamp is UTC in seconds.
790                        long utcTimeSeconds = loc.getTime() / 1000;
791                        mParameters.setGpsTimestamp(utcTimeSeconds);
792                    }
793                } else {
794                    loc = null;
795                }
796            }
797
798            mCameraDevice.setParameters(mParameters);
799
800            mCameraDevice.takePicture(mShutterCallback, mRawPictureCallback,
801                    new JpegPictureCallback(loc));
802            mPreviewing = false;
803        }
804
805        public void onSnap() {
806            // If we are already in the middle of taking a snapshot then ignore.
807            if (mPausing || mStatus == SNAPSHOT_IN_PROGRESS) {
808                return;
809            }
810            mCaptureStartTime = System.currentTimeMillis();
811
812            // Don't check the filesystem here, we can't afford the latency.
813            // Instead, check the cached value which was calculated when the
814            // preview was restarted.
815            if (mPicturesRemaining < 1) {
816                updateStorageHint(mPicturesRemaining);
817                return;
818            }
819
820            mStatus = SNAPSHOT_IN_PROGRESS;
821
822            mImageCapture.initiate();
823        }
824
825        private void clearLastData() {
826            mCaptureOnlyData = null;
827        }
828    }
829
830    public boolean saveDataToFile(String filePath, byte[] data) {
831        FileOutputStream f = null;
832        try {
833            f = new FileOutputStream(filePath);
834            f.write(data);
835        } catch (IOException e) {
836            return false;
837        } finally {
838            MenuHelper.closeSilently(f);
839        }
840        return true;
841    }
842
843    private void setLastPictureThumb(byte[] data, int degree, Uri uri) {
844        BitmapFactory.Options options = new BitmapFactory.Options();
845        options.inSampleSize = 16;
846        Bitmap lastPictureThumb =
847                BitmapFactory.decodeByteArray(data, 0, data.length, options);
848        lastPictureThumb = Util.rotate(lastPictureThumb, degree);
849        mThumbController.setData(uri, lastPictureThumb);
850    }
851
852    private static String createName(long dateTaken) {
853        return DateFormat.format("yyyy-MM-dd kk.mm.ss", dateTaken).toString();
854    }
855
856    @Override
857    public void onCreate(Bundle icicle) {
858        super.onCreate(icicle);
859
860        Window win = getWindow();
861        win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
862        setContentView(R.layout.camera);
863        mSurfaceView = (VideoPreview) findViewById(R.id.camera_preview);
864        mViewFinderHeight = mSurfaceView.getLayoutParams().height;
865        mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
866        mPreferences.registerOnSharedPreferenceChangeListener(this);
867
868        /*
869         * To reduce startup time, we start the preview in another thread.
870         * We make sure the preview is started at the end of onCreate.
871         */
872        Thread startPreviewThread = new Thread(new Runnable() {
873            public void run() {
874                try {
875                    mStartPreviewFail = false;
876                    startPreview();
877                } catch (CameraHardwareException e) {
878                    // In eng build, we throw the exception so that test tool
879                    // can detect it and report it
880                    if ("eng".equals(Build.TYPE)) {
881                        throw new RuntimeException(e);
882                    }
883                    mStartPreviewFail = true;
884                }
885            }
886        });
887        startPreviewThread.start();
888
889        // don't set mSurfaceHolder here. We have it set ONLY within
890        // surfaceChanged / surfaceDestroyed, other parts of the code
891        // assume that when it is set, the surface is also set.
892        SurfaceHolder holder = mSurfaceView.getHolder();
893        holder.addCallback(this);
894        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
895
896        mIsImageCaptureIntent = isImageCaptureIntent();
897        if (mIsImageCaptureIntent) {
898            setupCaptureParams();
899        }
900
901        LayoutInflater inflater = getLayoutInflater();
902
903        ViewGroup rootView = (ViewGroup) findViewById(R.id.camera);
904        if (mIsImageCaptureIntent) {
905            View controlBar = inflater.inflate(
906                    R.layout.attach_camera_control, rootView);
907            controlBar.findViewById(R.id.btn_cancel).setOnClickListener(this);
908            controlBar.findViewById(R.id.btn_retake).setOnClickListener(this);
909            controlBar.findViewById(R.id.btn_done).setOnClickListener(this);
910        } else {
911            inflater.inflate(R.layout.camera_control, rootView);
912            mSwitcher = ((Switcher) findViewById(R.id.camera_switch));
913            mSwitcher.setOnSwitchListener(this);
914            mSwitcher.addTouchView(findViewById(R.id.camera_switch_set));
915        }
916        findViewById(R.id.btn_gripper)
917                .setOnTouchListener(new GripperTouchListener());
918
919        mFlashIndicator = (IconIndicator) findViewById(R.id.flash_icon);
920
921        // Make sure preview is started.
922        try {
923            startPreviewThread.join();
924            if (mStartPreviewFail) {
925                showCameraErrorAndFinish();
926                return;
927            }
928        } catch (InterruptedException ex) {
929            // ignore
930        }
931
932        // Resize mVideoPreview to the right aspect ratio.
933        resizeForPreviewAspectRatio(mSurfaceView);
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 boolean onKeyDown(int keyCode, KeyEvent event) {
1339        switch (keyCode) {
1340            case KeyEvent.KEYCODE_BACK:
1341                if (!isCameraIdle()) {
1342                    // ignore backs while we're taking a picture
1343                    return true;
1344                }
1345                break;
1346            case KeyEvent.KEYCODE_FOCUS:
1347                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1348                    doFocus(true);
1349                }
1350                return true;
1351            case KeyEvent.KEYCODE_CAMERA:
1352                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1353                    doSnap();
1354                }
1355                return true;
1356            case KeyEvent.KEYCODE_DPAD_CENTER:
1357                // If we get a dpad center event without any focused view, move
1358                // the focus to the shutter button and press it.
1359                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1360                    // Start auto-focus immediately to reduce shutter lag. After
1361                    // the shutter button gets the focus, doFocus() will be
1362                    // called again but it is fine.
1363                    doFocus(true);
1364                    if (mShutterButton.isInTouchMode()) {
1365                        mShutterButton.requestFocusFromTouch();
1366                    } else {
1367                        mShutterButton.requestFocus();
1368                    }
1369                    mShutterButton.setPressed(true);
1370                }
1371                return true;
1372        }
1373
1374        return super.onKeyDown(keyCode, event);
1375    }
1376
1377    @Override
1378    public boolean onKeyUp(int keyCode, KeyEvent event) {
1379        switch (keyCode) {
1380            case KeyEvent.KEYCODE_FOCUS:
1381                if (mFirstTimeInitialized) {
1382                    doFocus(false);
1383                }
1384                return true;
1385        }
1386        return super.onKeyUp(keyCode, event);
1387    }
1388
1389    private void doSnap() {
1390        // If the user has half-pressed the shutter and focus is completed, we
1391        // can take the photo right away. If the focus mode is infinity, we can
1392        // also take the photo.
1393        if (mFocusMode.equals(Parameters.FOCUS_MODE_INFINITY)
1394                || (mFocusState == FOCUS_SUCCESS
1395                || mFocusState == FOCUS_FAIL)) {
1396            if (mZoomButtons != null) mZoomButtons.setVisible(false);
1397            mImageCapture.onSnap();
1398        } else if (mFocusState == FOCUSING) {
1399            // Half pressing the shutter (i.e. the focus button event) will
1400            // already have requested AF for us, so just request capture on
1401            // focus here.
1402            mFocusState = FOCUSING_SNAP_ON_FINISH;
1403        } else if (mFocusState == FOCUS_NOT_STARTED) {
1404            // Focus key down event is dropped for some reasons. Just ignore.
1405        }
1406    }
1407
1408    private void doFocus(boolean pressed) {
1409        // Do the focus if the mode is not infinity.
1410        if (!mFocusMode.equals(Parameters.FOCUS_MODE_INFINITY)) {
1411            if (pressed) {  // Focus key down.
1412                autoFocus();
1413            } else {  // Focus key up.
1414                cancelAutoFocus();
1415            }
1416        }
1417    }
1418
1419    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
1420        // Make sure we have a surface in the holder before proceeding.
1421        if (holder.getSurface() == null) {
1422            Log.d(TAG, "holder.getSurface() == null");
1423            return;
1424        }
1425
1426        // The mCameraDevice will be null if it fails to connect to the camera
1427        // hardware. In this case we will show a dialog and then finish the
1428        // activity, so it's OK to ignore it.
1429        if (mCameraDevice == null) return;
1430
1431        mSurfaceHolder = holder;
1432        mViewFinderHeight = h;
1433
1434        // Sometimes surfaceChanged is called after onPause. Ignore it.
1435        if (mPausing || isFinishing()) return;
1436
1437        // Set preview display if the surface is being created. Preview was
1438        // already started.
1439        if (holder.isCreating()) {
1440            setPreviewDisplay(holder);
1441        }
1442
1443        // If first time initialization is not finished, send a message to do
1444        // it later. We want to finish surfaceChanged as soon as possible to let
1445        // user see preview first.
1446        if (!mFirstTimeInitialized) {
1447            mHandler.sendEmptyMessage(FIRST_TIME_INIT);
1448        } else {
1449            initializeSecondTime();
1450        }
1451    }
1452
1453    public void surfaceCreated(SurfaceHolder holder) {
1454    }
1455
1456    public void surfaceDestroyed(SurfaceHolder holder) {
1457        stopPreview();
1458        mSurfaceHolder = null;
1459    }
1460
1461    private void closeCamera() {
1462        if (mCameraDevice != null) {
1463            CameraHolder.instance().release();
1464            mCameraDevice = null;
1465            mPreviewing = false;
1466        }
1467    }
1468
1469    private void ensureCameraDevice() throws CameraHardwareException {
1470        if (mCameraDevice == null) {
1471            mCameraDevice = CameraHolder.instance().open();
1472        }
1473    }
1474
1475    private void updateLastImage() {
1476        IImageList list = ImageManager.makeImageList(
1477            mContentResolver,
1478            dataLocation(),
1479            ImageManager.INCLUDE_IMAGES,
1480            ImageManager.SORT_ASCENDING,
1481            ImageManager.CAMERA_IMAGE_BUCKET_ID);
1482        int count = list.getCount();
1483        if (count > 0) {
1484            IImage image = list.getImageAt(count - 1);
1485            Uri uri = image.fullSizeImageUri();
1486            mThumbController.setData(uri, image.miniThumbBitmap());
1487        } else {
1488            mThumbController.setData(null, null);
1489        }
1490        list.close();
1491    }
1492
1493    private void showCameraErrorAndFinish() {
1494        Resources ress = getResources();
1495        Util.showFatalErrorAndFinish(Camera.this,
1496                ress.getString(R.string.camera_error_title),
1497                ress.getString(R.string.cannot_connect_camera));
1498    }
1499
1500    private void restartPreview() {
1501        // make sure the surfaceview fills the whole screen when previewing
1502        mSurfaceView.setAspectRatio(VideoPreview.DONT_CARE);
1503        try {
1504            startPreview();
1505        } catch (CameraHardwareException e) {
1506            showCameraErrorAndFinish();
1507            return;
1508        }
1509
1510        // Calculate this in advance of each shot so we don't add to shutter
1511        // latency. It's true that someone else could write to the SD card in
1512        // the mean time and fill it, but that could have happened between the
1513        // shutter press and saving the JPEG too.
1514        calculatePicturesRemaining();
1515    }
1516
1517    private void setPreviewDisplay(SurfaceHolder holder) {
1518        try {
1519            mCameraDevice.setPreviewDisplay(holder);
1520        } catch (Throwable ex) {
1521            closeCamera();
1522            throw new RuntimeException("setPreviewDisplay failed", ex);
1523        }
1524    }
1525
1526    private void startPreview() throws CameraHardwareException {
1527        if (mPausing || isFinishing()) return;
1528
1529        ensureCameraDevice();
1530
1531        // If we're previewing already, stop the preview first (this will blank
1532        // the screen).
1533        if (mPreviewing) stopPreview();
1534
1535        setPreviewDisplay(mSurfaceHolder);
1536
1537        setCameraParameters();
1538
1539        final long wallTimeStart = SystemClock.elapsedRealtime();
1540        final long threadTimeStart = Debug.threadCpuTimeNanos();
1541
1542        // Set one shot preview callback for latency measurement.
1543        mCameraDevice.setOneShotPreviewCallback(mOneShotPreviewCallback);
1544        mCameraDevice.setErrorCallback(mErrorCallback);
1545
1546        try {
1547            Log.v(TAG, "startPreview");
1548            mCameraDevice.startPreview();
1549        } catch (Throwable ex) {
1550            closeCamera();
1551            throw new RuntimeException("startPreview failed", ex);
1552        }
1553        mPreviewing = true;
1554        mStatus = IDLE;
1555
1556        long threadTimeEnd = Debug.threadCpuTimeNanos();
1557        long wallTimeEnd = SystemClock.elapsedRealtime();
1558        if ((wallTimeEnd - wallTimeStart) > 3000) {
1559            Log.w(TAG, "startPreview() to " + (wallTimeEnd - wallTimeStart)
1560                    + " ms. Thread time was"
1561                    + (threadTimeEnd - threadTimeStart) / 1000000 + " ms.");
1562        }
1563    }
1564
1565    private void stopPreview() {
1566        if (mCameraDevice != null && mPreviewing) {
1567            Log.v(TAG, "stopPreview");
1568            mCameraDevice.stopPreview();
1569        }
1570        mPreviewing = false;
1571        // If auto focus was in progress, it would have been canceled.
1572        clearFocusState();
1573    }
1574
1575    private void resizeForPreviewAspectRatio(View v) {
1576        ViewGroup.LayoutParams params;
1577        params = v.getLayoutParams();
1578        Size size = mParameters.getPreviewSize();
1579        params.width = (int) (params.height * size.width / size.height);
1580        Log.v(TAG, "resize to " + params.width + "x" + params.height);
1581        v.setLayoutParams(params);
1582    }
1583
1584    private Size getOptimalPreviewSize(List<Size> sizes) {
1585        Size optimalSize = null;
1586        if (sizes != null) {
1587            optimalSize = sizes.get(0);
1588            for (int i = 1; i < sizes.size(); i++) {
1589                if (Math.abs(sizes.get(i).height - mViewFinderHeight) <
1590                        Math.abs(optimalSize.height - mViewFinderHeight)) {
1591                    optimalSize = sizes.get(i);
1592                }
1593            }
1594            Log.v(TAG, "Optimal preview size is " + optimalSize.width + "x"
1595                    + optimalSize.height);
1596        }
1597        return optimalSize;
1598    }
1599
1600    private static boolean isSupported(String value, List<String> supported) {
1601        return supported == null ? false : supported.indexOf(value) >= 0;
1602    }
1603
1604    private void setCameraParameters() {
1605        mParameters = mCameraDevice.getParameters();
1606
1607        // Reset preview frame rate to the maximum because it may be lowered by
1608        // video camera application.
1609        List<Integer> frameRates = mParameters.getSupportedPreviewFrameRates();
1610        if (frameRates != null) {
1611            Integer max = Collections.max(frameRates);
1612            mParameters.setPreviewFrameRate(max);
1613        }
1614
1615        // Set a preview size that is closest to the viewfinder height.
1616        List<Size> sizes = mParameters.getSupportedPreviewSizes();
1617        Size optimalSize = getOptimalPreviewSize(sizes);
1618        if (optimalSize != null) {
1619            mParameters.setPreviewSize(optimalSize.width, optimalSize.height);
1620        }
1621
1622        // Set picture size.
1623        String pictureSize = mPreferences.getString(
1624                CameraSettings.KEY_PICTURE_SIZE,
1625                getString(R.string.pref_camera_picturesize_default));
1626        setCameraPictureSizeIfSupported(pictureSize);
1627
1628        // Set JPEG quality.
1629        String jpegQuality = mPreferences.getString(
1630                CameraSettings.KEY_JPEG_QUALITY,
1631                getString(R.string.pref_camera_jpegquality_default));
1632        mParameters.setJpegQuality(Integer.parseInt(jpegQuality));
1633
1634        // For the following settings, we need to check if the settings are
1635        // still supported by latest driver, if not, ignore the settings.
1636
1637        // Set flash mode.
1638        String flashMode = mPreferences.getString(
1639                CameraSettings.KEY_FLASH_MODE,
1640                getString(R.string.pref_camera_flashmode_default));
1641        List<String> supportedFlash = mParameters.getSupportedFlashModes();
1642        if (isSupported(flashMode, supportedFlash)) {
1643            mParameters.setFlashMode(flashMode);
1644        } else {
1645            // If the current flashMode is not support, show the
1646            // FLASH_MODE_OFF icon.
1647            flashMode = Parameters.FLASH_MODE_OFF;
1648        }
1649
1650        // We post the runner because this function can be called from
1651        // non-UI thread (i.e., startPreviewThread).
1652        final String finalFlashMode = flashMode;
1653        mHandler.post(new Runnable() {
1654            public void run() {
1655                mFlashIndicator.setMode(finalFlashMode);
1656            }
1657        });
1658
1659        // Set white balance parameter.
1660        String whiteBalance = mPreferences.getString(
1661                CameraSettings.KEY_WHITE_BALANCE,
1662                getString(R.string.pref_camera_whitebalance_default));
1663        if (isSupported(whiteBalance, mParameters.getSupportedWhiteBalance())) {
1664            mParameters.setWhiteBalance(whiteBalance);
1665        }
1666
1667        // Set color effect parameter.
1668        String colorEffect = mPreferences.getString(
1669                CameraSettings.KEY_COLOR_EFFECT,
1670                getString(R.string.pref_camera_coloreffect_default));
1671        if (isSupported(colorEffect, mParameters.getSupportedColorEffects())) {
1672            mParameters.setColorEffect(colorEffect);
1673        }
1674
1675        // Set scene mode.
1676        String sceneMode = mPreferences.getString(
1677                CameraSettings.KEY_SCENE_MODE,
1678                getString(R.string.pref_camera_scenemode_default));
1679        if (isSupported(sceneMode, mParameters.getSupportedSceneModes())) {
1680            mParameters.setSceneMode(sceneMode);
1681        }
1682
1683        // Set focus mode.
1684        mFocusMode = mPreferences.getString(
1685                CameraSettings.KEY_FOCUS_MODE,
1686                getString(R.string.pref_camera_focusmode_default));
1687        if (isSupported(mFocusMode, mParameters.getSupportedFocusModes())) {
1688            mParameters.setFocusMode(mFocusMode);
1689        }
1690
1691        mCameraDevice.setParameters(mParameters);
1692    }
1693
1694    private void gotoGallery() {
1695        MenuHelper.gotoCameraImageGallery(this);
1696    }
1697
1698    private void viewLastImage() {
1699        if (mThumbController.isUriValid()) {
1700            Uri targetUri = mThumbController.getUri();
1701            targetUri = targetUri.buildUpon().appendQueryParameter(
1702                    "bucketId", ImageManager.CAMERA_IMAGE_BUCKET_ID).build();
1703            Intent intent = new Intent(this, ReviewImage.class);
1704            intent.setData(targetUri);
1705            intent.putExtra(MediaStore.EXTRA_FULL_SCREEN, true);
1706            intent.putExtra(MediaStore.EXTRA_SHOW_ACTION_ICONS, true);
1707            intent.putExtra("com.android.camera.ReviewMode", true);
1708            try {
1709                startActivity(intent);
1710            } catch (ActivityNotFoundException ex) {
1711                Log.e(TAG, "review image fail", ex);
1712            }
1713        } else {
1714            Log.e(TAG, "Can't view last image.");
1715        }
1716    }
1717
1718    private void startReceivingLocationUpdates() {
1719        if (mLocationManager != null) {
1720            try {
1721                mLocationManager.requestLocationUpdates(
1722                        LocationManager.NETWORK_PROVIDER,
1723                        1000,
1724                        0F,
1725                        mLocationListeners[1]);
1726            } catch (java.lang.SecurityException ex) {
1727                Log.i(TAG, "fail to request location update, ignore", ex);
1728            } catch (IllegalArgumentException ex) {
1729                Log.d(TAG, "provider does not exist " + ex.getMessage());
1730            }
1731            try {
1732                mLocationManager.requestLocationUpdates(
1733                        LocationManager.GPS_PROVIDER,
1734                        1000,
1735                        0F,
1736                        mLocationListeners[0]);
1737            } catch (java.lang.SecurityException ex) {
1738                Log.i(TAG, "fail to request location update, ignore", ex);
1739            } catch (IllegalArgumentException ex) {
1740                Log.d(TAG, "provider does not exist " + ex.getMessage());
1741            }
1742        }
1743    }
1744
1745    private void stopReceivingLocationUpdates() {
1746        if (mLocationManager != null) {
1747            for (int i = 0; i < mLocationListeners.length; i++) {
1748                try {
1749                    mLocationManager.removeUpdates(mLocationListeners[i]);
1750                } catch (Exception ex) {
1751                    Log.i(TAG, "fail to remove location listners, ignore", ex);
1752                }
1753            }
1754        }
1755    }
1756
1757    private Location getCurrentLocation() {
1758        // go in best to worst order
1759        for (int i = 0; i < mLocationListeners.length; i++) {
1760            Location l = mLocationListeners[i].current();
1761            if (l != null) return l;
1762        }
1763        return null;
1764    }
1765
1766    private boolean isCameraIdle() {
1767        return mStatus == IDLE && mFocusState == FOCUS_NOT_STARTED;
1768    }
1769
1770    private boolean isImageCaptureIntent() {
1771        String action = getIntent().getAction();
1772        return (MediaStore.ACTION_IMAGE_CAPTURE.equals(action));
1773    }
1774
1775    private void setupCaptureParams() {
1776        Bundle myExtras = getIntent().getExtras();
1777        if (myExtras != null) {
1778            mSaveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT);
1779            mCropValue = myExtras.getString("crop");
1780        }
1781    }
1782
1783    private void showPostCaptureAlert() {
1784        if (mIsImageCaptureIntent) {
1785            findViewById(R.id.shutter_button).setVisibility(View.INVISIBLE);
1786            int[] pickIds = {R.id.btn_retake, R.id.btn_done};
1787            for (int id : pickIds) {
1788                View button = findViewById(id);
1789                ((View) button.getParent()).setVisibility(View.VISIBLE);
1790            }
1791        }
1792    }
1793
1794    private void hidePostCaptureAlert() {
1795        if (mIsImageCaptureIntent) {
1796            findViewById(R.id.shutter_button).setVisibility(View.VISIBLE);
1797            int[] pickIds = {R.id.btn_retake, R.id.btn_done};
1798            for (int id : pickIds) {
1799                View button = findViewById(id);
1800                ((View) button.getParent()).setVisibility(View.GONE);
1801            }
1802        }
1803    }
1804
1805    private int calculatePicturesRemaining() {
1806        mPicturesRemaining = MenuHelper.calculatePicturesRemaining();
1807        return mPicturesRemaining;
1808    }
1809
1810    @Override
1811    public boolean onPrepareOptionsMenu(Menu menu) {
1812        super.onPrepareOptionsMenu(menu);
1813        // Only show the menu when camera is idle.
1814        for (int i = 0; i < menu.size(); i++) {
1815            menu.getItem(i).setVisible(isCameraIdle());
1816        }
1817
1818        return true;
1819    }
1820
1821    @Override
1822    public boolean onCreateOptionsMenu(Menu menu) {
1823        super.onCreateOptionsMenu(menu);
1824
1825        if (mIsImageCaptureIntent) {
1826            // No options menu for attach mode.
1827            return false;
1828        } else {
1829            addBaseMenuItems(menu);
1830        }
1831        return true;
1832    }
1833
1834    private void addBaseMenuItems(Menu menu) {
1835        MenuItem gallery = menu.add(Menu.NONE, Menu.NONE,
1836                MenuHelper.POSITION_GOTO_GALLERY,
1837                R.string.camera_gallery_photos_text)
1838                .setOnMenuItemClickListener(new OnMenuItemClickListener() {
1839            public boolean onMenuItemClick(MenuItem item) {
1840                gotoGallery();
1841                return true;
1842            }
1843        });
1844        gallery.setIcon(android.R.drawable.ic_menu_gallery);
1845        mGalleryItems.add(gallery);
1846
1847        MenuItem item = menu.add(Menu.NONE, Menu.NONE,
1848                MenuHelper.POSITION_CAMERA_SETTING, R.string.settings)
1849                .setOnMenuItemClickListener(new OnMenuItemClickListener() {
1850            public boolean onMenuItemClick(MenuItem item) {
1851                showOnScreenSettings();
1852                return true;
1853            }
1854        });
1855        item.setIcon(android.R.drawable.ic_menu_preferences);
1856    }
1857
1858    public boolean onSwitchChanged(Switcher source, boolean onOff) {
1859        if (onOff == SWITCH_VIDEO) {
1860            if (!isCameraIdle()) return false;
1861            MenuHelper.gotoVideoMode(this);
1862            finish();
1863        }
1864        return true;
1865    }
1866
1867    private void setCameraPictureSizeIfSupported(String sizeString) {
1868        List<Size> pictureSizes = mParameters.getSupportedPictureSizes();
1869        if (pictureSizes != null) {
1870            int index = sizeString.indexOf('x');
1871            int width = Integer.parseInt(sizeString.substring(0, index));
1872            int height = Integer.parseInt(sizeString.substring(index + 1));
1873            for (Size size: pictureSizes) {
1874                if (size.width == width && size.height == height) {
1875                    mParameters.setPictureSize(width, height);
1876                    break;
1877                }
1878            }
1879        }
1880    }
1881
1882    public void onSharedPreferenceChanged(
1883            SharedPreferences preferences, String key) {
1884        // ignore the events after "onPause()"
1885        if (mPausing) return;
1886
1887        if (CameraSettings.KEY_RECORD_LOCATION.equals(key)) {
1888            mRecordLocation = preferences.getBoolean(key, false);
1889            if (mRecordLocation) {
1890                startReceivingLocationUpdates();
1891            } else {
1892                stopReceivingLocationUpdates();
1893            }
1894        } else {
1895            // All preferences except RECORD_LOCATION are camera parameters.
1896            // Call setCameraParameters to take effect now.
1897            setCameraParameters();
1898        }
1899    }
1900
1901    @Override
1902    public void onUserInteraction() {
1903        super.onUserInteraction();
1904        keepScreenOnAwhile();
1905    }
1906
1907    private void resetScreenOn() {
1908        mHandler.removeMessages(CLEAR_SCREEN_DELAY);
1909        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1910    }
1911
1912    private void keepScreenOnAwhile() {
1913        mHandler.removeMessages(CLEAR_SCREEN_DELAY);
1914        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1915        mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY);
1916    }
1917}
1918
1919class FocusRectangle extends View {
1920
1921    @SuppressWarnings("unused")
1922    private static final String TAG = "FocusRectangle";
1923
1924    public FocusRectangle(Context context, AttributeSet attrs) {
1925        super(context, attrs);
1926    }
1927
1928    private void setDrawable(int resid) {
1929        setBackgroundDrawable(getResources().getDrawable(resid));
1930    }
1931
1932    public void showStart() {
1933        setDrawable(R.drawable.focus_focusing);
1934    }
1935
1936    public void showSuccess() {
1937        setDrawable(R.drawable.focus_focused);
1938    }
1939
1940    public void showFail() {
1941        setDrawable(R.drawable.focus_focus_failed);
1942    }
1943
1944    public void clear() {
1945        setBackgroundDrawable(null);
1946    }
1947}
1948