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