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