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