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