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