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