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