Camera.java revision 55319ceeef829274a95e2a41e7e365228acf5ccd
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 com.android.camera.gallery.Cancelable;
20import com.android.camera.gallery.IImage;
21import com.android.camera.gallery.IImageList;
22
23import android.app.Activity;
24import android.content.ActivityNotFoundException;
25import android.content.BroadcastReceiver;
26import android.content.ContentResolver;
27import android.content.Context;
28import android.content.Intent;
29import android.content.IntentFilter;
30import android.content.SharedPreferences;
31import android.graphics.Bitmap;
32import android.graphics.BitmapFactory;
33import android.graphics.Matrix;
34import android.graphics.drawable.BitmapDrawable;
35import android.hardware.Camera.PictureCallback;
36import android.hardware.Camera.Size;
37import android.location.Location;
38import android.location.LocationManager;
39import android.location.LocationProvider;
40import android.media.AudioManager;
41import android.media.ToneGenerator;
42import android.net.Uri;
43import android.os.Bundle;
44import android.os.Debug;
45import android.os.Environment;
46import android.os.Handler;
47import android.os.Message;
48import android.os.SystemClock;
49import android.preference.PreferenceManager;
50import android.provider.MediaStore;
51import android.text.format.DateFormat;
52import android.util.AttributeSet;
53import android.util.Log;
54import android.view.Gravity;
55import android.view.KeyEvent;
56import android.view.Menu;
57import android.view.MenuItem;
58import android.view.MotionEvent;
59import android.view.OrientationEventListener;
60import android.view.SurfaceHolder;
61import android.view.View;
62import android.view.ViewGroup;
63import android.view.Window;
64import android.view.WindowManager;
65import android.view.MenuItem.OnMenuItemClickListener;
66import android.view.animation.AlphaAnimation;
67import android.view.animation.Animation;
68import android.widget.ImageView;
69import android.widget.Toast;
70import android.widget.ZoomButtonsController;
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.StringTokenizer;
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
86    private static final String TAG = "camera";
87
88    private static final int CROP_MSG = 1;
89    private static final int FIRST_TIME_INIT = 2;
90    private static final int RESTART_PREVIEW = 3;
91    private static final int CLEAR_SCREEN_DELAY = 4;
92    private static final int STORE_IMAGE_DONE = 5;
93
94    private static final int SCREEN_DELAY = 2 * 60 * 1000;
95    private static final int FOCUS_BEEP_VOLUME = 100;
96
97    public static final int MENU_SWITCH_TO_VIDEO = 0;
98    public static final int MENU_SWITCH_TO_CAMERA = 1;
99    public static final int MENU_FLASH_SETTING = 2;
100    public static final int MENU_FLASH_AUTO = 3;
101    public static final int MENU_FLASH_ON = 4;
102    public static final int MENU_FLASH_OFF = 5;
103    public static final int MENU_SETTINGS = 6;
104    public static final int MENU_GALLERY_PHOTOS = 7;
105    public static final int MENU_GALLERY_VIDEOS = 8;
106    public static final int MENU_SAVE_SELECT_PHOTOS = 30;
107    public static final int MENU_SAVE_NEW_PHOTO = 31;
108    public static final int MENU_SAVE_GALLERY_PHOTO = 34;
109    public static final int MENU_SAVE_GALLERY_VIDEO_PHOTO = 35;
110    public static final int MENU_SAVE_CAMERA_DONE = 36;
111    public static final int MENU_SAVE_CAMERA_VIDEO_DONE = 37;
112
113    private android.hardware.Camera.Parameters mParameters;
114    private int mZoomIndex = 0;  // The index of the current zoom value.
115    private String[] mZoomValues;  // All possible zoom values.
116
117    // The parameter strings to communicate with camera driver.
118    public static final String PARM_ZOOM = "zoom";
119    public static final String PARM_PICTURE_SIZE = "picture-size";
120    public static final String PARM_JPEG_QUALITY = "jpeg-quality";
121    public static final String PARM_ROTATION = "rotation";
122    public static final String PARM_GPS_LATITUDE = "gps-latitude";
123    public static final String PARM_GPS_LONGITUDE = "gps-longitude";
124    public static final String PARM_GPS_ALTITUDE = "gps-altitude";
125    public static final String PARM_GPS_TIMESTAMP = "gps-timestamp";
126    public static final String SUPPORTED_ZOOM = "zoom-values";
127    public static final String SUPPORTED_PICTURE_SIZE = "picture-size-values";
128
129    private OrientationEventListener mOrientationListener;
130    private int mLastOrientation = OrientationEventListener.ORIENTATION_UNKNOWN;
131    private SharedPreferences mPreferences;
132
133    private static final int IDLE = 1;
134    private static final int SNAPSHOT_IN_PROGRESS = 2;
135
136    private int mStatus = IDLE;
137    private static final String sTempCropFilename = "crop-temp";
138
139    private android.hardware.Camera mCameraDevice;
140    private VideoPreview mSurfaceView;
141    private SurfaceHolder mSurfaceHolder = null;
142    private ShutterButton mShutterButton;
143    private FocusRectangle mFocusRectangle;
144    private ImageView mGpsIndicator;
145    private ToneGenerator mFocusToneGenerator;
146    private ZoomButtonsController mZoomButtons;
147
148    // mPostCaptureAlert, mLastPictureButton, mThumbController
149    // are non-null only if isImageCaptureIntent() is true.
150    private View mPostCaptureAlert;
151    private ImageView mLastPictureButton;
152    private ThumbnailController mThumbController;
153
154    private int mViewFinderWidth, mViewFinderHeight;
155
156    private ImageCapture mImageCapture = null;
157
158    private boolean mPreviewing;
159    private boolean mPausing;
160    private boolean mFirstTimeInitialized;
161    private boolean mIsImageCaptureIntent;
162    private boolean mRecordLocation;
163
164    private static final int FOCUS_NOT_STARTED = 0;
165    private static final int FOCUSING = 1;
166    private static final int FOCUSING_SNAP_ON_FINISH = 2;
167    private static final int FOCUS_SUCCESS = 3;
168    private static final int FOCUS_FAIL = 4;
169    private int mFocusState = FOCUS_NOT_STARTED;
170
171    private ContentResolver mContentResolver;
172    private boolean mDidRegister = false;
173
174    private final ArrayList<MenuItem> mGalleryItems = new ArrayList<MenuItem>();
175
176    private LocationManager mLocationManager = null;
177
178    // Use OneShotPreviewCallback to measure the time between
179    // JpegPictureCallback and preview.
180    private final OneShotPreviewCallback mOneShotPreviewCallback =
181            new OneShotPreviewCallback();
182    private final ShutterCallback mShutterCallback = new ShutterCallback();
183    private final RawPictureCallback mRawPictureCallback =
184            new RawPictureCallback();
185    private final AutoFocusCallback mAutoFocusCallback =
186            new AutoFocusCallback();
187    private long mFocusStartTime;
188    private long mFocusCallbackTime;
189    private long mCaptureStartTime;
190    private long mShutterCallbackTime;
191    private long mRawPictureCallbackTime;
192    private long mJpegPictureCallbackTime;
193    private int mPicturesRemaining;
194
195    //Add the camera latency time
196    public static long mAutoFocusTime;
197    public static long mShutterLag;
198    public static long mShutterAndRawPictureCallbackTime;
199    public static long mJpegPictureCallbackTimeLag;
200    public static long mRawPictureAndJpegPictureCallbackTime;
201
202    // Focus mode. Options are pref_camera_focusmode_entryvalues.
203    private String mFocusMode;
204
205    private Thread mStoreImageThread = null;
206    private final Handler mHandler = new MainHandler();
207
208    private interface Capturer {
209        Uri getLastCaptureUri();
210        void onSnap();
211    }
212
213    /**
214     * This Handler is used to post message back onto the main thread of the
215     * application
216     */
217    private class MainHandler extends Handler {
218        @Override
219        public void handleMessage(Message msg) {
220            switch (msg.what) {
221                case RESTART_PREVIEW: {
222                    restartPreview();
223                    break;
224                }
225
226                case STORE_IMAGE_DONE: {
227                    if (!mIsImageCaptureIntent) {
228                        setLastPictureThumb((byte[])msg.obj, mImageCapture.getLastCaptureUri());
229                        updateThumbnailButton();
230                    } else {
231                        showPostCaptureAlert();
232                    }
233                    mStoreImageThread = null;
234                    break;
235                }
236
237                case CLEAR_SCREEN_DELAY: {
238                    getWindow().clearFlags(
239                            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
240                    break;
241                }
242
243                case FIRST_TIME_INIT: {
244                    initializeFirstTime();
245                    break;
246                }
247            }
248        }
249    }
250
251    // Snapshots can only be taken after this is called. It should be called
252    // once only. We could have done these things in onCreate() but we want to
253    // make preview screen appear as soon as possible.
254    void initializeFirstTime() {
255        if (mFirstTimeInitialized) return;
256
257        // Create orientation listenter. This should be done first because it
258        // takes some time to get first orientation.
259        mOrientationListener =
260                new OrientationEventListener(Camera.this) {
261            @Override
262            public void onOrientationChanged(int orientation) {
263                // We keep the last known orientation. So if the user
264                // first orient the camera then point the camera to
265                // floor/sky, we still have the correct orientation.
266                if (orientation != ORIENTATION_UNKNOWN) {
267                    mLastOrientation = orientation;
268                }
269            }
270        };
271        mOrientationListener.enable();
272
273        // Initialize location sevice.
274        mLocationManager = (LocationManager)
275                getSystemService(Context.LOCATION_SERVICE);
276        readPreference();
277        if (mRecordLocation) startReceivingLocationUpdates();
278
279        // Initialize last picture button.
280        mContentResolver = getContentResolver();
281        if (!mIsImageCaptureIntent)  {
282            findViewById(R.id.video_button).setOnClickListener(this);
283            mLastPictureButton = (ImageView) findViewById(R.id.review_button);
284            mLastPictureButton.setOnClickListener(this);
285            mThumbController = new ThumbnailController(
286                    mLastPictureButton, mContentResolver);
287            mThumbController.loadData(ImageManager.getLastImageThumbPath());
288            // Update last image thumbnail.
289            updateThumbnailButton();
290        } else {
291            findViewById(R.id.review_button).setVisibility(View.INVISIBLE);
292            findViewById(R.id.video_button).setVisibility(View.INVISIBLE);
293            ViewGroup cameraView = (ViewGroup) findViewById(R.id.camera);
294            getLayoutInflater().inflate(
295                    R.layout.post_picture_panel, cameraView);
296            mPostCaptureAlert = findViewById(R.id.post_picture_panel);
297        }
298
299        findViewById(R.id.photo_indicator).setVisibility(View.VISIBLE);
300        // Initialize shutter button.
301        mShutterButton = (ShutterButton) findViewById(R.id.camera_button);
302        mShutterButton.setOnShutterButtonListener(this);
303        mShutterButton.setVisibility(View.VISIBLE);
304
305        mFocusRectangle = (FocusRectangle) findViewById(R.id.focus_rectangle);
306        updateFocusIndicator();
307
308        // Initialize GPS indicator.
309        mGpsIndicator = (ImageView) findViewById(R.id.gps_indicator);
310        mGpsIndicator.setImageResource(R.drawable.ic_gps_active_camera);
311
312        ImageManager.ensureOSXCompatibleFolder();
313
314        calculatePicturesRemaining();
315
316        installIntentFilter();
317
318        initializeFocusTone();
319
320        // Disable zoom until driver is ready.
321        // TODO: enable this.
322        //initializeZoom();
323
324        mFirstTimeInitialized = true;
325    }
326
327    private void updateThumbnailButton() {
328        if (!mThumbController.isUriValid()) {
329            updateLastImage();
330        }
331        mThumbController.updateDisplayIfNeeded();
332    }
333
334    // If the activity is paused and resumed, this method will be called in
335    // onResume.
336    void initializeSecondTime() {
337        // Start orientation listener as soon as possible because it takes
338        // some time to get first orientation.
339        mOrientationListener.enable();
340
341        // Start location update if needed.
342        readPreference();
343        if (mRecordLocation) startReceivingLocationUpdates();
344
345        installIntentFilter();
346
347        initializeFocusTone();
348
349        if (!mIsImageCaptureIntent) {
350            updateThumbnailButton();
351        }
352    }
353
354    private void initializeZoom() {
355        String zoomValuesStr = mParameters.get(SUPPORTED_ZOOM);
356        if (zoomValuesStr == null) return;
357
358        mZoomValues = getZoomValues(zoomValuesStr);
359        if (mZoomValues == null) return;
360
361        mZoomButtons = new ZoomButtonsController(mSurfaceView);
362        mZoomButtons.setAutoDismissed(true);
363        mZoomButtons.setOnZoomListener(
364                new ZoomButtonsController.OnZoomListener() {
365            public void onVisibilityChanged(boolean visible) {
366                if (visible) {
367                    updateZoomButtonsEnabled();
368                }
369            }
370
371            public void onZoom(boolean zoomIn) {
372                if (zoomIn) {
373                    zoomIn();
374                } else {
375                    zoomOut();
376                }
377                updateZoomButtonsEnabled();
378            }
379        });
380    }
381
382    private void zoomIn() {
383        if (mZoomIndex < mZoomValues.length - 1) {
384            mZoomIndex++;
385            mParameters.set(PARM_ZOOM, mZoomValues[mZoomIndex]);
386            mCameraDevice.setParameters(mParameters);
387        }
388    }
389
390    private void zoomOut() {
391        if (mZoomIndex > 0) {
392            mZoomIndex--;
393            mParameters.set(PARM_ZOOM, mZoomValues[mZoomIndex]);
394            mCameraDevice.setParameters(mParameters);
395        }
396    }
397
398    private void updateZoomButtonsEnabled() {
399        mZoomButtons.setZoomInEnabled(mZoomIndex < mZoomValues.length - 1);
400        mZoomButtons.setZoomOutEnabled(mZoomIndex > 0);
401    }
402
403    private String[] getZoomValues(String zoomValuesStr) {
404        ArrayList<String> list = new ArrayList<String>();
405        String[] zoomValues = null;
406        StringTokenizer tokenizer = new StringTokenizer(zoomValuesStr, ",");
407
408        while (tokenizer.hasMoreElements()) {
409            list.add(tokenizer.nextToken());
410        }
411        if (list.size() > 0) {
412            zoomValues = list.toArray(new String[list.size()]);
413        }
414        return zoomValues;
415    }
416
417
418    LocationListener [] mLocationListeners = new LocationListener[] {
419            new LocationListener(LocationManager.GPS_PROVIDER),
420            new LocationListener(LocationManager.NETWORK_PROVIDER)
421    };
422
423
424    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
425        @Override
426        public void onReceive(Context context, Intent intent) {
427            String action = intent.getAction();
428            if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
429                // SD card available
430                updateStorageHint(calculatePicturesRemaining());
431            } else if (action.equals(Intent.ACTION_MEDIA_UNMOUNTED) ||
432                    action.equals(Intent.ACTION_MEDIA_CHECKING)) {
433                // SD card unavailable
434                mPicturesRemaining = MenuHelper.NO_STORAGE_ERROR;
435                updateStorageHint(mPicturesRemaining);
436            } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_STARTED)) {
437                Toast.makeText(Camera.this,
438                        getResources().getString(R.string.wait), 5000);
439            } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)) {
440                updateStorageHint();
441            }
442        }
443    };
444
445    private class LocationListener
446            implements android.location.LocationListener {
447        Location mLastLocation;
448        boolean mValid = false;
449        String mProvider;
450
451        public LocationListener(String provider) {
452            mProvider = provider;
453            mLastLocation = new Location(mProvider);
454        }
455
456        public void onLocationChanged(Location newLocation) {
457            if (newLocation.getLatitude() == 0.0
458                    && newLocation.getLongitude() == 0.0) {
459                // Hack to filter out 0.0,0.0 locations
460                return;
461            }
462            // If GPS is available before start camera, we won't get status
463            // update so update GPS indicator when we receive data.
464            if (mRecordLocation
465                    && LocationManager.GPS_PROVIDER.equals(mProvider)) {
466                mGpsIndicator.setVisibility(View.VISIBLE);
467            }
468            mLastLocation.set(newLocation);
469            mValid = true;
470        }
471
472        public void onProviderEnabled(String provider) {
473        }
474
475        public void onProviderDisabled(String provider) {
476            mValid = false;
477        }
478
479        public void onStatusChanged(
480                String provider, int status, Bundle extras) {
481            switch(status) {
482                case LocationProvider.OUT_OF_SERVICE:
483                case LocationProvider.TEMPORARILY_UNAVAILABLE: {
484                    mValid = false;
485                    if (mRecordLocation &&
486                            LocationManager.GPS_PROVIDER.equals(provider)) {
487                        mGpsIndicator.setVisibility(View.INVISIBLE);
488                    }
489                    break;
490                }
491            }
492        }
493
494        public Location current() {
495            return mValid ? mLastLocation : null;
496        }
497    }
498
499    private final class OneShotPreviewCallback
500            implements android.hardware.Camera.PreviewCallback {
501        public void onPreviewFrame(byte[] data,
502                                   android.hardware.Camera camera) {
503            long now = System.currentTimeMillis();
504            if (mJpegPictureCallbackTime != 0) {
505                mJpegPictureCallbackTimeLag = now - mJpegPictureCallbackTime;
506                Log.v(TAG, "mJpegPictureCallbackTimeLag = "
507                        + mJpegPictureCallbackTimeLag + "ms");
508                mJpegPictureCallbackTime = 0;
509            }
510        }
511    }
512
513    private final class ShutterCallback
514            implements android.hardware.Camera.ShutterCallback {
515        public void onShutter() {
516            mShutterCallbackTime = System.currentTimeMillis();
517            mShutterLag = mShutterCallbackTime - mCaptureStartTime;
518            Log.v(TAG, "mShutterLag = " + mShutterLag + "ms");
519            clearFocusState();
520        }
521    }
522
523    private final class RawPictureCallback implements PictureCallback {
524        public void onPictureTaken(
525                byte [] rawData, android.hardware.Camera camera) {
526            mRawPictureCallbackTime = System.currentTimeMillis();
527            mShutterAndRawPictureCallbackTime =
528                mRawPictureCallbackTime - mShutterCallbackTime;
529            Log.v(TAG, "mShutterAndRawPictureCallbackTime = "
530                    + mShutterAndRawPictureCallbackTime + "ms");
531        }
532    }
533
534    private final class JpegPictureCallback implements PictureCallback {
535        Location mLocation;
536
537        public JpegPictureCallback(Location loc) {
538            mLocation = loc;
539        }
540
541        public void onPictureTaken(
542                final byte [] jpegData, final android.hardware.Camera camera) {
543            if (mPausing) {
544                return;
545            }
546
547            mJpegPictureCallbackTime = System.currentTimeMillis();
548            mRawPictureAndJpegPictureCallbackTime =
549                mJpegPictureCallbackTime - mRawPictureCallbackTime;
550            Log.v(TAG, "mRawPictureAndJpegPictureCallbackTime = "
551                    + mRawPictureAndJpegPictureCallbackTime +"ms");
552            if (jpegData != null) {
553                mStoreImageThread = new Thread() {
554                     public void run() {
555                         mImageCapture.storeImage(jpegData, camera, mLocation);
556                     }
557                };
558                mStoreImageThread.start();
559            }
560
561            if (!mIsImageCaptureIntent) {
562                long delay = 1500 - (
563                        System.currentTimeMillis() - mRawPictureCallbackTime);
564                mHandler.sendEmptyMessageDelayed(
565                        RESTART_PREVIEW, Math.max(delay, 0));
566            }
567        }
568    }
569
570    private final class AutoFocusCallback
571            implements android.hardware.Camera.AutoFocusCallback {
572        public void onAutoFocus(
573                boolean focused, android.hardware.Camera camera) {
574            mFocusCallbackTime = System.currentTimeMillis();
575            mAutoFocusTime = mFocusCallbackTime - mFocusStartTime;
576            Log.v(TAG, "mAutoFocusTime = " + mAutoFocusTime + "ms");
577            if (mFocusState == FOCUSING_SNAP_ON_FINISH) {
578                // Take the picture no matter focus succeeds or fails. No need
579                // to play the AF sound if we're about to play the shutter
580                // sound.
581                if (focused) {
582                    mFocusState = FOCUS_SUCCESS;
583                } else {
584                    mFocusState = FOCUS_FAIL;
585                }
586                mImageCapture.onSnap();
587            } else if (mFocusState == FOCUSING) {
588                // User is half-pressing the focus key. Play the focus tone.
589                // Do not take the picture now.
590                ToneGenerator tg = mFocusToneGenerator;
591                if (tg != null) {
592                    tg.startTone(ToneGenerator.TONE_PROP_BEEP2);
593                }
594                if (focused) {
595                    mFocusState = FOCUS_SUCCESS;
596                } else {
597                    mFocusState = FOCUS_FAIL;
598                }
599            } else if (mFocusState == FOCUS_NOT_STARTED) {
600                // User has released the focus key before focus completes.
601                // Do nothing.
602            }
603            updateFocusIndicator();
604        }
605    }
606
607    private class ImageCapture implements Capturer {
608
609        private boolean mCancel = false;
610
611        private Uri mLastContentUri;
612        private Cancelable<Void> mAddImageCancelable;
613
614        Bitmap mCaptureOnlyBitmap;
615
616        private void storeImage(byte[] data, Location loc) {
617            try {
618                long dateTaken = System.currentTimeMillis();
619                String name = createName(dateTaken) + ".jpg";
620                mLastContentUri = ImageManager.addImage(
621                        mContentResolver,
622                        name,
623                        dateTaken,
624                        loc, // location for the database goes here
625                        0, // the dsp will use the right orientation so
626                           // don't "double set it"
627                        ImageManager.CAMERA_IMAGE_BUCKET_NAME,
628                        name);
629                if (mLastContentUri == null) {
630                    // this means we got an error
631                    mCancel = true;
632                }
633                if (!mCancel) {
634                    mAddImageCancelable = ImageManager.storeImage(
635                            mLastContentUri, mContentResolver,
636                            0, null, data);
637                    mAddImageCancelable.get();
638                    mAddImageCancelable = null;
639                    ImageManager.setImageSize(mContentResolver, mLastContentUri,
640                            new File(ImageManager.CAMERA_IMAGE_BUCKET_NAME,
641                            name).length());
642                }
643            } catch (Exception ex) {
644                Log.e(TAG, "Exception while compressing image.", ex);
645            }
646        }
647
648        public void storeImage(
649                final byte[] data, android.hardware.Camera camera, Location loc) {
650            Message msg = mHandler.obtainMessage(STORE_IMAGE_DONE);
651            if (!mIsImageCaptureIntent) {
652                storeImage(data, loc);
653                sendBroadcast(new Intent(
654                        "com.android.camera.NEW_PICTURE", mLastContentUri));
655                msg.obj = data;
656            } else {
657                BitmapFactory.Options options = new BitmapFactory.Options();
658                options.inSampleSize = 4;
659
660                mCaptureOnlyBitmap = BitmapFactory.decodeByteArray(
661                        data, 0, data.length, options);
662            }
663            mHandler.sendMessage(msg);
664        }
665
666        /**
667         * Initiate the capture of an image.
668         */
669        public void initiate() {
670            if (mCameraDevice == null) {
671                return;
672            }
673
674            mCancel = false;
675
676            capture();
677        }
678
679        public Uri getLastCaptureUri() {
680            return mLastContentUri;
681        }
682
683        public Bitmap getLastBitmap() {
684            return mCaptureOnlyBitmap;
685        }
686
687        private void capture() {
688            mCaptureOnlyBitmap = null;
689
690            int orientation = mLastOrientation;
691            if (orientation != OrientationEventListener.ORIENTATION_UNKNOWN) {
692                orientation += 90;
693            }
694            orientation = ImageManager.roundOrientation(orientation);
695            Log.v(TAG, "mLastOrientation = " + mLastOrientation
696                    + ", orientation = " + orientation);
697
698            mParameters.set(PARM_ROTATION, orientation);
699
700            Location loc = mRecordLocation ? getCurrentLocation() : null;
701
702            mParameters.remove(PARM_GPS_LATITUDE);
703            mParameters.remove(PARM_GPS_LONGITUDE);
704            mParameters.remove(PARM_GPS_ALTITUDE);
705            mParameters.remove(PARM_GPS_TIMESTAMP);
706
707            if (loc != null) {
708                double lat = loc.getLatitude();
709                double lon = loc.getLongitude();
710                boolean hasLatLon = (lat != 0.0d) || (lon != 0.0d);
711
712                if (hasLatLon) {
713                    String latString = String.valueOf(lat);
714                    String lonString = String.valueOf(lon);
715                    mParameters.set(PARM_GPS_LATITUDE,  latString);
716                    mParameters.set(PARM_GPS_LONGITUDE, lonString);
717                    if (loc.hasAltitude()) {
718                        mParameters.set(PARM_GPS_ALTITUDE,
719                                        String.valueOf(loc.getAltitude()));
720                    } else {
721                        // for NETWORK_PROVIDER location provider, we may have
722                        // no altitude information, but the driver needs it, so
723                        // we fake one.
724                        mParameters.set(PARM_GPS_ALTITUDE,  "0");
725                    }
726                    if (loc.getTime() != 0) {
727                        // Location.getTime() is UTC in milliseconds.
728                        // gps-timestamp is UTC in seconds.
729                        long utcTimeSeconds = loc.getTime() / 1000;
730                        mParameters.set(PARM_GPS_TIMESTAMP,
731                                        String.valueOf(utcTimeSeconds));
732                    }
733                } else {
734                    loc = null;
735                }
736            }
737
738            mCameraDevice.setParameters(mParameters);
739
740            mCameraDevice.takePicture(mShutterCallback, mRawPictureCallback,
741                    new JpegPictureCallback(loc));
742            mPreviewing = false;
743        }
744
745        public void onSnap() {
746            // If we are already in the middle of taking a snapshot then ignore.
747            if (mPausing || mStatus == SNAPSHOT_IN_PROGRESS) {
748                return;
749            }
750            mCaptureStartTime = System.currentTimeMillis();
751
752            // Don't check the filesystem here, we can't afford the latency.
753            // Instead, check the cached value which was calculated when the
754            // preview was restarted.
755            if (mPicturesRemaining < 1) {
756                updateStorageHint(mPicturesRemaining);
757                return;
758            }
759
760            mStatus = SNAPSHOT_IN_PROGRESS;
761
762            mImageCapture.initiate();
763        }
764
765        private void clearLastBitmap() {
766            if (mCaptureOnlyBitmap != null) {
767                mCaptureOnlyBitmap.recycle();
768                mCaptureOnlyBitmap = null;
769            }
770        }
771    }
772
773    private void setLastPictureThumb(byte[] data, Uri uri) {
774        BitmapFactory.Options options = new BitmapFactory.Options();
775        options.inSampleSize = 16;
776        Bitmap lastPictureThumb =
777                BitmapFactory.decodeByteArray(data, 0, data.length, options);
778        mThumbController.setData(uri, lastPictureThumb);
779    }
780
781    private static String createName(long dateTaken) {
782        return DateFormat.format("yyyy-MM-dd kk.mm.ss", dateTaken).toString();
783    }
784
785    public static Matrix getDisplayMatrix(Bitmap b, ImageView v) {
786        Matrix m = new Matrix();
787        float bw = b.getWidth();
788        float bh = b.getHeight();
789        float vw = v.getWidth();
790        float vh = v.getHeight();
791        float scale, x, y;
792        if (bw * vh > vw * bh) {
793            scale = vh / bh;
794            x = (vw - scale * bw) * 0.5F;
795            y = 0;
796        } else {
797            scale = vw / bw;
798            x = 0;
799            y = (vh - scale * bh) * 0.5F;
800        }
801        m.setScale(scale, scale, 0.5F, 0.5F);
802        m.postTranslate(x, y);
803        return m;
804    }
805
806    @Override
807    public void onCreate(Bundle icicle) {
808        super.onCreate(icicle);
809
810        /*
811         * To reduce startup time, we open camera device in another thread.
812         * We make sure the camera is opened at the end of onCreate.
813         */
814        Thread openCameraThread = new Thread(new Runnable() {
815            public void run() {
816                mCameraDevice = CameraHolder.instance().open();
817            }
818        });
819        openCameraThread.start();
820
821        mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
822
823        Window win = getWindow();
824        win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
825        setContentView(R.layout.camera);
826
827        mSurfaceView = (VideoPreview) findViewById(R.id.camera_preview);
828
829        // don't set mSurfaceHolder here. We have it set ONLY within
830        // surfaceChanged / surfaceDestroyed, other parts of the code
831        // assume that when it is set, the surface is also set.
832        SurfaceHolder holder = mSurfaceView.getHolder();
833        holder.addCallback(this);
834        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
835
836        mIsImageCaptureIntent = isImageCaptureIntent();
837        getLayoutInflater().inflate(
838                R.layout.button_bar, (ViewGroup) findViewById(R.id.camera));
839
840        // Make sure the services are loaded.
841        try {
842            openCameraThread.join();
843        } catch (InterruptedException ex) {
844            // ignore
845        }
846    }
847
848    @Override
849    public void onStart() {
850        super.onStart();
851
852        Thread t = new Thread(new Runnable() {
853            public void run() {
854                final boolean storageOK = calculatePicturesRemaining() > 0;
855                if (!storageOK) {
856                    mHandler.post(new Runnable() {
857                        public void run() {
858                            updateStorageHint(mPicturesRemaining);
859                        }
860                    });
861                }
862            }
863        });
864        t.start();
865    }
866
867    public void onClick(View v) {
868        switch (v.getId()) {
869            case R.id.video_button:
870                if (isCameraIdle()) {
871                    MenuHelper.gotoVideoMode(this);
872                }
873                break;
874            case R.id.review_button:
875                if (isCameraIdle()) {
876                    // Make sure image storing has completed before viewing
877                    // last image.
878                    waitForStoreImageThread();
879                    viewLastImage();
880                }
881                break;
882            case R.id.attach:
883                doAttach();
884                break;
885            case R.id.cancel:
886                doCancel();
887        }
888    }
889
890    private void doAttach() {
891        if (mPausing) {
892            return;
893        }
894        Bitmap bitmap = mImageCapture.getLastBitmap();
895
896        String cropValue = null;
897        Uri saveUri = null;
898
899        Bundle myExtras = getIntent().getExtras();
900        if (myExtras != null) {
901            saveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT);
902            cropValue = myExtras.getString("crop");
903        }
904
905
906        if (cropValue == null) {
907            // First handle the no crop case -- just return the value.  If the
908            // caller specifies a "save uri" then write the data to it's
909            // stream. Otherwise, pass back a scaled down version of the bitmap
910            // directly in the extras.
911            if (saveUri != null) {
912                OutputStream outputStream = null;
913                try {
914                    outputStream = mContentResolver.openOutputStream(saveUri);
915                    bitmap.compress(Bitmap.CompressFormat.JPEG, 75,
916                            outputStream);
917                    outputStream.close();
918
919                    setResult(RESULT_OK);
920                    finish();
921                } catch (IOException ex) {
922                    // ignore exception
923                } finally {
924                    if (outputStream != null) {
925                        try {
926                            outputStream.close();
927                        } catch (IOException ex) {
928                            // ignore exception
929                        }
930                    }
931                }
932            } else {
933                float scale = .5F;
934                Matrix m = new Matrix();
935                m.setScale(scale, scale);
936
937                bitmap = Bitmap.createBitmap(bitmap, 0, 0,
938                        bitmap.getWidth(),
939                        bitmap.getHeight(),
940                        m, true);
941
942                setResult(RESULT_OK,
943                        new Intent("inline-data").putExtra("data", bitmap));
944                finish();
945            }
946        } else {
947            // Save the image to a temp file and invoke the cropper
948            Uri tempUri = null;
949            FileOutputStream tempStream = null;
950            try {
951                File path = getFileStreamPath(sTempCropFilename);
952                path.delete();
953                tempStream = openFileOutput(sTempCropFilename, 0);
954                bitmap.compress(Bitmap.CompressFormat.JPEG, 75, tempStream);
955                tempStream.close();
956                tempUri = Uri.fromFile(path);
957            } catch (FileNotFoundException ex) {
958                setResult(Activity.RESULT_CANCELED);
959                finish();
960                return;
961            } catch (IOException ex) {
962                setResult(Activity.RESULT_CANCELED);
963                finish();
964                return;
965            } finally {
966                if (tempStream != null) {
967                    try {
968                        tempStream.close();
969                    } catch (IOException ex) {
970                        // ignore exception
971                    }
972                }
973            }
974
975            Bundle newExtras = new Bundle();
976            if (cropValue.equals("circle")) {
977                newExtras.putString("circleCrop", "true");
978            }
979            if (saveUri != null) {
980                newExtras.putParcelable(MediaStore.EXTRA_OUTPUT, saveUri);
981            } else {
982                newExtras.putBoolean("return-data", true);
983            }
984
985            Intent cropIntent = new Intent();
986            cropIntent.setClass(Camera.this, CropImage.class);
987            cropIntent.setData(tempUri);
988            cropIntent.putExtras(newExtras);
989
990            startActivityForResult(cropIntent, CROP_MSG);
991        }
992    }
993
994    private void doCancel() {
995        setResult(RESULT_CANCELED, new Intent());
996        finish();
997    }
998
999    public void onShutterButtonFocus(ShutterButton button, boolean pressed) {
1000        if (mPausing) {
1001            return;
1002        }
1003        switch (button.getId()) {
1004            case R.id.camera_button:
1005                if (mStoreImageThread == null) {
1006                    doFocus(pressed);
1007                } else {
1008                    Toast.makeText(Camera.this,
1009                            getResources().getString(R.string.wait),
1010                            Toast.LENGTH_SHORT);
1011                }
1012                break;
1013        }
1014    }
1015
1016    public void onShutterButtonClick(ShutterButton button) {
1017        if (mPausing) {
1018            return;
1019        }
1020        switch (button.getId()) {
1021            case R.id.camera_button:
1022                if (mIsImageCaptureIntent
1023                        && mPostCaptureAlert.getVisibility() == View.VISIBLE) {
1024                    // User was reviewing the capture image. Hide the action
1025                    // items and start the preview now.
1026                    hidePostCaptureAlert();
1027                    restartPreview();
1028                } else if (mStoreImageThread == null) {
1029                    // Take a picture.
1030                    doSnap();
1031                } else {
1032                    Toast.makeText(Camera.this,
1033                            getResources().getString(R.string.wait),
1034                            Toast.LENGTH_SHORT);
1035                }
1036                break;
1037        }
1038    }
1039
1040    private void updateStorageHint() {
1041        updateStorageHint(MenuHelper.calculatePicturesRemaining());
1042    }
1043
1044    private OnScreenHint mStorageHint;
1045
1046    private void updateStorageHint(int remaining) {
1047        String noStorageText = null;
1048
1049        if (remaining == MenuHelper.NO_STORAGE_ERROR) {
1050            String state = Environment.getExternalStorageState();
1051            if (state == Environment.MEDIA_CHECKING) {
1052                noStorageText = getString(R.string.preparing_sd);
1053            } else {
1054                noStorageText = getString(R.string.no_storage);
1055            }
1056        } else if (remaining < 1) {
1057            noStorageText = getString(R.string.not_enough_space);
1058        }
1059
1060        if (noStorageText != null) {
1061            if (mStorageHint == null) {
1062                mStorageHint = OnScreenHint.makeText(this, noStorageText);
1063            } else {
1064                mStorageHint.setText(noStorageText);
1065            }
1066            mStorageHint.show();
1067        } else if (mStorageHint != null) {
1068            mStorageHint.cancel();
1069            mStorageHint = null;
1070        }
1071    }
1072
1073    void installIntentFilter() {
1074        // install an intent filter to receive SD card related events.
1075        IntentFilter intentFilter =
1076                new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);
1077        intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
1078        intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);
1079        intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
1080        intentFilter.addAction(Intent.ACTION_MEDIA_CHECKING);
1081        intentFilter.addDataScheme("file");
1082        registerReceiver(mReceiver, intentFilter);
1083        mDidRegister = true;
1084    }
1085
1086    void initializeFocusTone() {
1087        // Initialize focus tone generator.
1088        try {
1089            mFocusToneGenerator = new ToneGenerator(
1090                    AudioManager.STREAM_SYSTEM, FOCUS_BEEP_VOLUME);
1091        } catch (Throwable ex) {
1092            Log.w(TAG, "Exception caught while creating tone generator: ", ex);
1093            mFocusToneGenerator = null;
1094        }
1095    }
1096
1097    void readPreference() {
1098        mRecordLocation = mPreferences.getBoolean(
1099                "pref_camera_recordlocation_key", false);
1100        mFocusMode = mPreferences.getString(
1101                CameraSettings.KEY_FOCUS_MODE,
1102                getString(R.string.pref_camera_focusmode_default));
1103    }
1104
1105    @Override
1106    public void onResume() {
1107        super.onResume();
1108
1109        mPausing = false;
1110        mJpegPictureCallbackTime = 0;
1111        mImageCapture = new ImageCapture();
1112
1113        if (mSurfaceHolder != null) {
1114            // If surface holder is created, start the preview now. Otherwise,
1115            // wait until surfaceChanged.
1116            mSurfaceView.setAspectRatio(VideoPreview.DONT_CARE);
1117            startPreview();
1118
1119            // If first time initialization is not finished, put it in the
1120            // message queue.
1121            if (!mFirstTimeInitialized) {
1122                mHandler.sendEmptyMessage(FIRST_TIME_INIT);
1123            } else {
1124                initializeSecondTime();
1125            }
1126        }
1127
1128        mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY);
1129    }
1130
1131    private static ImageManager.DataLocation dataLocation() {
1132        return ImageManager.DataLocation.EXTERNAL;
1133    }
1134
1135    private void waitForStoreImageThread() {
1136        if (mStoreImageThread != null) {
1137            try {
1138                mStoreImageThread.join();
1139            } catch (InterruptedException ex) {
1140                // Ignore this exception.
1141                Log.e(TAG, "", ex);
1142            } finally {
1143                mStoreImageThread = null;
1144            }
1145        }
1146    }
1147
1148    @Override
1149    protected void onPause() {
1150        mPausing = true;
1151        stopPreview();
1152        // Close the camera now because other activities may need to use it.
1153        closeCamera();
1154
1155        waitForStoreImageThread();
1156
1157        if (mFirstTimeInitialized) {
1158            mOrientationListener.disable();
1159            mGpsIndicator.setVisibility(View.INVISIBLE);
1160            if (!mIsImageCaptureIntent) {
1161                mThumbController.storeData(
1162                        ImageManager.getLastImageThumbPath());
1163            }
1164            hidePostCaptureAlert();
1165        }
1166
1167        if (mDidRegister) {
1168            unregisterReceiver(mReceiver);
1169            mDidRegister = false;
1170        }
1171        stopReceivingLocationUpdates();
1172
1173        if (mFocusToneGenerator != null) {
1174            mFocusToneGenerator.release();
1175            mFocusToneGenerator = null;
1176        }
1177
1178        if (mStorageHint != null) {
1179            mStorageHint.cancel();
1180            mStorageHint = null;
1181        }
1182
1183        // If we are in an image capture intent and has taken
1184        // a picture, we just clear it in onPause.
1185        mImageCapture.clearLastBitmap();
1186        mImageCapture = null;
1187
1188        // This is necessary to make the ZoomButtonsController unregister
1189        // its configuration change receiver.
1190        if (mZoomButtons != null) {
1191            mZoomButtons.setVisible(false);
1192        }
1193
1194        // Remove the messages in the event queue.
1195        mHandler.removeMessages(CLEAR_SCREEN_DELAY);
1196        mHandler.removeMessages(RESTART_PREVIEW);
1197        mHandler.removeMessages(FIRST_TIME_INIT);
1198        mHandler.removeMessages(STORE_IMAGE_DONE);
1199
1200        super.onPause();
1201    }
1202
1203    @Override
1204    protected void onActivityResult(
1205            int requestCode, int resultCode, Intent data) {
1206        switch (requestCode) {
1207            case CROP_MSG: {
1208                Intent intent = new Intent();
1209                if (data != null) {
1210                    Bundle extras = data.getExtras();
1211                    if (extras != null) {
1212                        intent.putExtras(extras);
1213                    }
1214                }
1215                setResult(resultCode, intent);
1216                finish();
1217
1218                File path = getFileStreamPath(sTempCropFilename);
1219                path.delete();
1220
1221                break;
1222            }
1223        }
1224    }
1225
1226    private void autoFocus() {
1227        // Initiate autofocus only when preview is started and snapshot is not
1228        // in progress.
1229        if (isCameraIdle() && mPreviewing) {
1230            Log.v(TAG, "Start autofocus.");
1231            if (mZoomButtons != null) mZoomButtons.setVisible(false);
1232            mFocusStartTime = System.currentTimeMillis();
1233            mFocusState = FOCUSING;
1234            updateFocusIndicator();
1235            mCameraDevice.autoFocus(mAutoFocusCallback);
1236        }
1237    }
1238
1239    private void clearFocusState() {
1240        mFocusState = FOCUS_NOT_STARTED;
1241        updateFocusIndicator();
1242    }
1243
1244    private void updateFocusIndicator() {
1245        if (mFocusRectangle == null) return;
1246
1247        if (mFocusState == FOCUSING || mFocusState == FOCUSING_SNAP_ON_FINISH) {
1248            mFocusRectangle.showStart();
1249        } else if (mFocusState == FOCUS_SUCCESS) {
1250            mFocusRectangle.showSuccess();
1251        } else if (mFocusState == FOCUS_FAIL) {
1252            mFocusRectangle.showFail();
1253        } else {
1254            mFocusRectangle.clear();
1255        }
1256    }
1257
1258    @Override
1259    public boolean onKeyDown(int keyCode, KeyEvent event) {
1260        mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY);
1261        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1262
1263        switch (keyCode) {
1264            case KeyEvent.KEYCODE_BACK:
1265                if (!isCameraIdle()) {
1266                    // ignore backs while we're taking a picture
1267                    return true;
1268                }
1269                break;
1270            case KeyEvent.KEYCODE_FOCUS:
1271                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1272                    doFocus(true);
1273                }
1274                return true;
1275            case KeyEvent.KEYCODE_CAMERA:
1276                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1277                    doSnap();
1278                }
1279                return true;
1280            case KeyEvent.KEYCODE_DPAD_CENTER:
1281                // If we get a dpad center event without any focused view, move
1282                // the focus to the shutter button and press it.
1283                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1284                    // Start auto-focus immediately to reduce shutter lag. After
1285                    // the shutter button gets the focus, doFocus() will be
1286                    // called again but it is fine.
1287                    doFocus(true);
1288                    if (mShutterButton.isInTouchMode()) {
1289                        mShutterButton.requestFocusFromTouch();
1290                    } else {
1291                        mShutterButton.requestFocus();
1292                    }
1293                    mShutterButton.setPressed(true);
1294                }
1295                return true;
1296        }
1297
1298        return super.onKeyDown(keyCode, event);
1299    }
1300
1301    @Override
1302    public boolean onKeyUp(int keyCode, KeyEvent event) {
1303        switch (keyCode) {
1304            case KeyEvent.KEYCODE_FOCUS:
1305                if (mFirstTimeInitialized) {
1306                    doFocus(false);
1307                }
1308                return true;
1309        }
1310        return super.onKeyUp(keyCode, event);
1311    }
1312
1313    @Override
1314    public boolean onTouchEvent(MotionEvent event) {
1315        switch (event.getAction()) {
1316            case MotionEvent.ACTION_DOWN:
1317                // Show zoom buttons only when preview is started and snapshot
1318                // is not in progress. mZoomButtons may be null if it is not
1319                // initialized.
1320                if (!mPausing && isCameraIdle() && mPreviewing
1321                        && mZoomButtons != null) {
1322                    mZoomButtons.setVisible(true);
1323                }
1324                return true;
1325        }
1326        return super.onTouchEvent(event);
1327    }
1328
1329    private void doSnap() {
1330        // If the user has half-pressed the shutter and focus is completed, we
1331        // can take the photo right away. If the focus mode is infinity, we can
1332        // also take the photo.
1333        if (mFocusMode.equals(getString(
1334                R.string.pref_camera_focusmode_value_infinity))
1335                || (mFocusState == FOCUS_SUCCESS || mFocusState == FOCUS_FAIL)) {
1336            if (mZoomButtons != null) mZoomButtons.setVisible(false);
1337            mImageCapture.onSnap();
1338        } else if (mFocusState == FOCUSING) {
1339            // Half pressing the shutter (i.e. the focus button event) will
1340            // already have requested AF for us, so just request capture on
1341            // focus here.
1342            mFocusState = FOCUSING_SNAP_ON_FINISH;
1343        } else if (mFocusState == FOCUS_NOT_STARTED) {
1344            // Focus key down event is dropped for some reasons. Just ignore.
1345        }
1346    }
1347
1348    private void doFocus(boolean pressed) {
1349        // Do the focus if the mode is auto. No focus needed in infinity mode.
1350        if (mFocusMode.equals(getString(
1351                R.string.pref_camera_focusmode_value_auto))) {
1352            if (pressed) {  // Focus key down.
1353                autoFocus();
1354            } else {  // Focus key up.
1355                if (mFocusState != FOCUSING_SNAP_ON_FINISH) {
1356                    // User releases half-pressed focus key.
1357                    clearFocusState();
1358                }
1359            }
1360        }
1361    }
1362
1363    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
1364        // Make sure we have a surface in the holder before proceeding.
1365        if (holder.getSurface() == null) {
1366            Log.d(TAG, "holder.getSurface() == null");
1367            return;
1368        }
1369
1370        mSurfaceHolder = holder;
1371        mViewFinderWidth = w;
1372        mViewFinderHeight = h;
1373
1374        // Sometimes surfaceChanged is called after onPause. Ignore it.
1375        if (mPausing) return;
1376
1377        // Start the preview.
1378        startPreview();
1379
1380        // If first time initialization is not finished, send a message to do
1381        // it later. We want to finish surfaceChanged as soon as possible to let
1382        // user see preview first.
1383        if (!mFirstTimeInitialized) {
1384            mHandler.sendEmptyMessage(FIRST_TIME_INIT);
1385        } else {
1386            initializeSecondTime();
1387        }
1388    }
1389
1390    public void surfaceCreated(SurfaceHolder holder) {
1391    }
1392
1393    public void surfaceDestroyed(SurfaceHolder holder) {
1394        stopPreview();
1395        mSurfaceHolder = null;
1396    }
1397
1398    private void closeCamera() {
1399        if (mCameraDevice != null) {
1400            CameraHolder.instance().release();
1401            mCameraDevice = null;
1402            mPreviewing = false;
1403        }
1404    }
1405
1406    private boolean ensureCameraDevice() {
1407        if (mCameraDevice == null) {
1408            mCameraDevice = CameraHolder.instance().open();
1409        }
1410        return mCameraDevice != null;
1411    }
1412
1413    private void updateLastImage() {
1414        IImageList list = ImageManager.allImages(
1415            mContentResolver,
1416            dataLocation(),
1417            ImageManager.INCLUDE_IMAGES,
1418            ImageManager.SORT_ASCENDING,
1419            ImageManager.CAMERA_IMAGE_BUCKET_ID);
1420        int count = list.getCount();
1421        if (count > 0) {
1422            IImage image = list.getImageAt(count - 1);
1423            Uri uri = image.fullSizeImageUri();
1424            mThumbController.setData(uri, image.miniThumbBitmap());
1425        } else {
1426            mThumbController.setData(null, null);
1427        }
1428        list.deactivate();
1429    }
1430
1431    private void restartPreview() {
1432        // make sure the surfaceview fills the whole screen when previewing
1433        mSurfaceView.setAspectRatio(VideoPreview.DONT_CARE);
1434        startPreview();
1435
1436        // Calculate this in advance of each shot so we don't add to shutter
1437        // latency. It's true that someone else could write to the SD card in
1438        // the mean time and fill it, but that could have happened between the
1439        // shutter press and saving the JPEG too.
1440        calculatePicturesRemaining();
1441    }
1442
1443    private void startPreview() {
1444        if (mPausing) return;
1445
1446        if (!ensureCameraDevice()) return;
1447
1448        if (mSurfaceHolder == null) return;
1449
1450        if (isFinishing()) return;
1451
1452        // If we're previewing already, stop the preview first (this will blank
1453        // the screen).
1454        if (mPreviewing) stopPreview();
1455
1456        // this blanks the screen if the surface changed, no-op otherwise
1457        try {
1458            mCameraDevice.setPreviewDisplay(mSurfaceHolder);
1459        } catch (Throwable ex) {
1460            closeCamera();
1461            throw new RuntimeException("setPreviewDisplay failed", ex);
1462        }
1463
1464        setCameraParameter();
1465
1466        final long wallTimeStart = SystemClock.elapsedRealtime();
1467        final long threadTimeStart = Debug.threadCpuTimeNanos();
1468
1469        // Set one shot preview callback for latency measurement.
1470        mCameraDevice.setOneShotPreviewCallback(mOneShotPreviewCallback);
1471
1472        try {
1473            Log.v(TAG, "startPreview");
1474            mCameraDevice.startPreview();
1475        } catch (Throwable ex) {
1476            closeCamera();
1477            throw new RuntimeException("startPreview failed", ex);
1478        }
1479        mPreviewing = true;
1480        mStatus = IDLE;
1481
1482        long threadTimeEnd = Debug.threadCpuTimeNanos();
1483        long wallTimeEnd = SystemClock.elapsedRealtime();
1484        if ((wallTimeEnd - wallTimeStart) > 3000) {
1485            Log.w(TAG, "startPreview() to " + (wallTimeEnd - wallTimeStart)
1486                    + " ms. Thread time was"
1487                    + (threadTimeEnd - threadTimeStart) / 1000000 + " ms.");
1488        }
1489    }
1490
1491    private void stopPreview() {
1492        if (mCameraDevice != null && mPreviewing) {
1493            Log.v(TAG, "stopPreview");
1494            mCameraDevice.stopPreview();
1495        }
1496        mPreviewing = false;
1497        // If auto focus was in progress, it would have been canceled.
1498        clearFocusState();
1499    }
1500
1501    private void setCameraParameter() {
1502        // request the preview size, the hardware may not honor it,
1503        // if we depended on it we would have to query the size again
1504        mParameters = mCameraDevice.getParameters();
1505        mParameters.setPreviewSize(mViewFinderWidth, mViewFinderHeight);
1506
1507        // Set picture size parameter.
1508        String pictureSize = mPreferences.getString(
1509                CameraSettings.KEY_PICTURE_SIZE,
1510                getString(R.string.pref_camera_picturesize_default));
1511        mParameters.set(PARM_PICTURE_SIZE, pictureSize);
1512
1513        // Set JPEG quality parameter.
1514        String jpegQuality = mPreferences.getString(
1515                CameraSettings.KEY_JPEG_QUALITY,
1516                getString(R.string.pref_camera_jpegquality_default));
1517        mParameters.set(PARM_JPEG_QUALITY, jpegQuality);
1518
1519        // Set zoom.
1520        if (mZoomValues != null) {
1521            mParameters.set(PARM_ZOOM, mZoomValues[mZoomIndex]);
1522        }
1523
1524        mCameraDevice.setParameters(mParameters);
1525    }
1526
1527    void gotoGallery() {
1528        MenuHelper.gotoCameraImageGallery(this);
1529    }
1530
1531    private void viewLastImage() {
1532        if (mThumbController.isUriValid()) {
1533            Uri targetUri = mThumbController.getUri();
1534            targetUri = targetUri.buildUpon().appendQueryParameter(
1535                    "bucketId", ImageManager.CAMERA_IMAGE_BUCKET_ID).build();
1536            Intent intent = new Intent(Intent.ACTION_VIEW, targetUri);
1537            intent.putExtra(MediaStore.EXTRA_FULL_SCREEN, true);
1538            intent.putExtra(MediaStore.EXTRA_SHOW_ACTION_ICONS, true);
1539            intent.putExtra("com.android.camera.ReviewMode", true);
1540            try {
1541                startActivity(intent);
1542            } catch (ActivityNotFoundException ex) {
1543                Log.e(TAG, "review image fail", ex);
1544            }
1545        } else {
1546            Log.e(TAG, "Can't view last image.");
1547        }
1548    }
1549
1550    private void startReceivingLocationUpdates() {
1551        if (mLocationManager != null) {
1552            try {
1553                mLocationManager.requestLocationUpdates(
1554                        LocationManager.NETWORK_PROVIDER,
1555                        1000,
1556                        0F,
1557                        mLocationListeners[1]);
1558            } catch (java.lang.SecurityException ex) {
1559                Log.i(TAG, "fail to request location update, ignore", ex);
1560            } catch (IllegalArgumentException ex) {
1561                Log.d(TAG, "provider does not exist " + ex.getMessage());
1562            }
1563            try {
1564                mLocationManager.requestLocationUpdates(
1565                        LocationManager.GPS_PROVIDER,
1566                        1000,
1567                        0F,
1568                        mLocationListeners[0]);
1569            } catch (java.lang.SecurityException ex) {
1570                Log.i(TAG, "fail to request location update, ignore", ex);
1571            } catch (IllegalArgumentException ex) {
1572                Log.d(TAG, "provider does not exist " + ex.getMessage());
1573            }
1574        }
1575    }
1576
1577    private void stopReceivingLocationUpdates() {
1578        if (mLocationManager != null) {
1579            for (int i = 0; i < mLocationListeners.length; i++) {
1580                try {
1581                    mLocationManager.removeUpdates(mLocationListeners[i]);
1582                } catch (Exception ex) {
1583                    Log.i(TAG, "fail to remove location listners, ignore", ex);
1584                }
1585            }
1586        }
1587    }
1588
1589    private Location getCurrentLocation() {
1590        // go in best to worst order
1591        for (int i = 0; i < mLocationListeners.length; i++) {
1592            Location l = mLocationListeners[i].current();
1593            if (l != null) return l;
1594        }
1595        return null;
1596    }
1597
1598    private boolean isCameraIdle() {
1599        return mStatus == IDLE && mFocusState == FOCUS_NOT_STARTED;
1600    }
1601
1602    private boolean isImageCaptureIntent() {
1603        String action = getIntent().getAction();
1604        return (MediaStore.ACTION_IMAGE_CAPTURE.equals(action));
1605    }
1606
1607    private void showPostCaptureAlert() {
1608        if (mIsImageCaptureIntent) {
1609            mPostCaptureAlert.setVisibility(View.VISIBLE);
1610            int[] pickIds = {R.id.attach, R.id.cancel};
1611            for (int id : pickIds) {
1612                View view = mPostCaptureAlert.findViewById(id);
1613                view.setOnClickListener(this);
1614                Animation animation = new AlphaAnimation(0F, 1F);
1615                animation.setDuration(500);
1616                view.setAnimation(animation);
1617            }
1618        }
1619    }
1620
1621    private void hidePostCaptureAlert() {
1622        if (mIsImageCaptureIntent) {
1623            mPostCaptureAlert.setVisibility(View.INVISIBLE);
1624        }
1625    }
1626
1627    private int calculatePicturesRemaining() {
1628        mPicturesRemaining = MenuHelper.calculatePicturesRemaining();
1629        return mPicturesRemaining;
1630    }
1631
1632    @Override
1633    public boolean onPrepareOptionsMenu(Menu menu) {
1634        super.onPrepareOptionsMenu(menu);
1635
1636        for (int i = 1; i <= MenuHelper.MENU_ITEM_MAX; i++) {
1637            menu.setGroupVisible(i, false);
1638        }
1639
1640        // Only show the menu when camera is idle.
1641        if (isCameraIdle()) {
1642            menu.setGroupVisible(MenuHelper.GENERIC_ITEM, true);
1643            menu.setGroupVisible(MenuHelper.IMAGE_MODE_ITEM, true);
1644        }
1645
1646        return true;
1647    }
1648
1649    @Override
1650    public boolean onCreateOptionsMenu(Menu menu) {
1651        super.onCreateOptionsMenu(menu);
1652
1653        if (mIsImageCaptureIntent) {
1654            // No options menu for attach mode.
1655            return false;
1656        } else {
1657            addBaseMenuItems(menu);
1658        }
1659        return true;
1660    }
1661
1662    private void addBaseMenuItems(Menu menu) {
1663        MenuHelper.addSwitchModeMenuItem(menu, this, true);
1664        {
1665            MenuItem gallery = menu.add(
1666                    MenuHelper.IMAGE_MODE_ITEM, MENU_GALLERY_PHOTOS, 0,
1667                    R.string.camera_gallery_photos_text)
1668                    .setOnMenuItemClickListener(new OnMenuItemClickListener() {
1669                public boolean onMenuItemClick(MenuItem item) {
1670                    gotoGallery();
1671                    return true;
1672                }
1673            });
1674            gallery.setIcon(android.R.drawable.ic_menu_gallery);
1675            mGalleryItems.add(gallery);
1676        }
1677        {
1678            MenuItem gallery = menu.add(
1679                    MenuHelper.VIDEO_MODE_ITEM, MENU_GALLERY_VIDEOS, 0,
1680                    R.string.camera_gallery_photos_text)
1681                    .setOnMenuItemClickListener(new OnMenuItemClickListener() {
1682                public boolean onMenuItemClick(MenuItem item) {
1683                    gotoGallery();
1684                    return true;
1685                }
1686            });
1687            gallery.setIcon(android.R.drawable.ic_menu_gallery);
1688            mGalleryItems.add(gallery);
1689        }
1690
1691        MenuItem item = menu.add(MenuHelper.GENERIC_ITEM, MENU_SETTINGS,
1692                0, R.string.settings)
1693                .setOnMenuItemClickListener(new OnMenuItemClickListener() {
1694            public boolean onMenuItemClick(MenuItem item) {
1695                // Keep the camera instance for a while.
1696                // This avoids re-opening the camera and saves time.
1697                CameraHolder.instance().keep();
1698
1699                Intent intent = new Intent();
1700                intent.setClass(Camera.this, CameraSettings.class);
1701                startActivity(intent);
1702                return true;
1703            }
1704        });
1705        item.setIcon(android.R.drawable.ic_menu_preferences);
1706    }
1707}
1708
1709class FocusRectangle extends View {
1710
1711    @SuppressWarnings("unused")
1712    private static final String TAG = "FocusRectangle";
1713
1714    public FocusRectangle(Context context, AttributeSet attrs) {
1715        super(context, attrs);
1716    }
1717
1718    private void setDrawable(int resid) {
1719        BitmapDrawable d = (BitmapDrawable) getResources().getDrawable(resid);
1720        // We do this because we don't want the bitmap to be scaled.
1721        d.setGravity(Gravity.CENTER);
1722        setBackgroundDrawable(d);
1723    }
1724
1725    public void showStart() {
1726        setDrawable(R.drawable.frame_autofocus_rectangle);
1727    }
1728
1729    public void showSuccess() {
1730        setDrawable(R.drawable.frame_focused_rectangle);
1731    }
1732
1733    public void showFail() {
1734        setDrawable(R.drawable.frame_nofocus_rectangle);
1735    }
1736
1737    public void clear() {
1738        setBackgroundDrawable(null);
1739    }
1740}
1741