Camera.java revision c1dd72054122befb49aa1ca11ffa589b00186f80
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.ContentProviderClient;
23import android.content.ContentResolver;
24import android.content.Context;
25import android.content.Intent;
26import android.content.IntentFilter;
27import android.content.SharedPreferences;
28import android.content.SharedPreferences.Editor;
29import android.content.res.Configuration;
30import android.content.res.Resources;
31import android.graphics.Bitmap;
32import android.graphics.BitmapFactory;
33import android.hardware.Camera.CameraInfo;
34import android.hardware.Camera.Parameters;
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.CameraProfile;
42import android.media.ToneGenerator;
43import android.net.Uri;
44import android.os.Build;
45import android.os.Bundle;
46import android.os.Debug;
47import android.os.Environment;
48import android.os.Handler;
49import android.os.Looper;
50import android.os.Message;
51import android.os.MessageQueue;
52import android.os.SystemClock;
53import android.provider.MediaStore;
54import android.provider.Settings;
55import android.util.AttributeSet;
56import android.util.Log;
57import android.view.Display;
58import android.view.GestureDetector;
59import android.view.KeyEvent;
60import android.view.LayoutInflater;
61import android.view.Menu;
62import android.view.MenuItem;
63import android.view.MotionEvent;
64import android.view.OrientationEventListener;
65import android.view.SurfaceHolder;
66import android.view.SurfaceView;
67import android.view.View;
68import android.view.ViewGroup;
69import android.view.Window;
70import android.view.WindowManager;
71import android.view.MenuItem.OnMenuItemClickListener;
72import android.widget.FrameLayout;
73import android.widget.ImageView;
74
75import com.android.camera.gallery.IImage;
76import com.android.camera.gallery.IImageList;
77import com.android.camera.ui.CameraHeadUpDisplay;
78import com.android.camera.ui.GLRootView;
79import com.android.camera.ui.HeadUpDisplay;
80import com.android.camera.ui.ZoomControllerListener;
81
82import java.io.File;
83import java.io.FileNotFoundException;
84import java.io.FileOutputStream;
85import java.io.IOException;
86import java.io.OutputStream;
87import java.text.SimpleDateFormat;
88import java.util.ArrayList;
89import java.util.Collections;
90import java.util.Date;
91import java.util.HashMap;
92import java.util.List;
93
94/** The Camera activity which can preview and take pictures. */
95public class Camera extends NoSearchActivity implements View.OnClickListener,
96        ShutterButton.OnShutterButtonListener, SurfaceHolder.Callback,
97        Switcher.OnSwitchListener {
98
99    private static final String TAG = "camera";
100
101    private static final int CROP_MSG = 1;
102    private static final int FIRST_TIME_INIT = 2;
103    private static final int RESTART_PREVIEW = 3;
104    private static final int CLEAR_SCREEN_DELAY = 4;
105    private static final int SET_CAMERA_PARAMETERS_WHEN_IDLE = 5;
106
107    // The subset of parameters we need to update in setCameraParameters().
108    private static final int UPDATE_PARAM_INITIALIZE = 1;
109    private static final int UPDATE_PARAM_ZOOM = 2;
110    private static final int UPDATE_PARAM_PREFERENCE = 4;
111    private static final int UPDATE_PARAM_ALL = -1;
112
113    // When setCameraParametersWhenIdle() is called, we accumulate the subsets
114    // needed to be updated in mUpdateSet.
115    private int mUpdateSet;
116
117    // The brightness settings used when it is set to automatic in the system.
118    // The reason why it is set to 0.7 is just because 1.0 is too bright.
119    private static final float DEFAULT_CAMERA_BRIGHTNESS = 0.7f;
120
121    private static final int SCREEN_DELAY = 2 * 60 * 1000;
122    private static final int FOCUS_BEEP_VOLUME = 100;
123
124    private static final int ZOOM_STOPPED = 0;
125    private static final int ZOOM_START = 1;
126    private static final int ZOOM_STOPPING = 2;
127
128    private int mZoomState = ZOOM_STOPPED;
129    private boolean mSmoothZoomSupported = false;
130    private int mZoomValue;  // The current zoom value.
131    private int mZoomMax;
132    private int mTargetZoomValue;
133
134    private Parameters mParameters;
135    private Parameters mInitialParams;
136
137    private MyOrientationEventListener mOrientationListener;
138    // The device orientation in degrees. Default is unknown.
139    private int mOrientation = OrientationEventListener.ORIENTATION_UNKNOWN;
140    // The orientation compensation for icons and thumbnails.
141    private int mOrientationCompensation = 0;
142    private ComboPreferences mPreferences;
143
144    private static final int IDLE = 1;
145    private static final int SNAPSHOT_IN_PROGRESS = 2;
146
147    private static final boolean SWITCH_CAMERA = true;
148    private static final boolean SWITCH_VIDEO = false;
149
150    private int mStatus = IDLE;
151    private static final String sTempCropFilename = "crop-temp";
152
153    private android.hardware.Camera mCameraDevice;
154    private ContentProviderClient mMediaProviderClient;
155    private SurfaceView mSurfaceView;
156    private SurfaceHolder mSurfaceHolder = null;
157    private ShutterButton mShutterButton;
158    private FocusRectangle mFocusRectangle;
159    private ToneGenerator mFocusToneGenerator;
160    private GestureDetector mGestureDetector;
161    private Switcher mSwitcher;
162    private boolean mStartPreviewFail = false;
163
164    private GLRootView mGLRootView;
165
166    // mPostCaptureAlert, mLastPictureButton, mThumbController
167    // are non-null only if isImageCaptureIntent() is true.
168    private ImageView mLastPictureButton;
169    private ThumbnailController mThumbController;
170
171    // mCropValue and mSaveUri are used only if isImageCaptureIntent() is true.
172    private String mCropValue;
173    private Uri mSaveUri;
174
175    private ImageCapture mImageCapture = null;
176
177    private boolean mPreviewing;
178    private boolean mPausing;
179    private boolean mFirstTimeInitialized;
180    private boolean mIsImageCaptureIntent;
181    private boolean mRecordLocation;
182
183    private static final int FOCUS_NOT_STARTED = 0;
184    private static final int FOCUSING = 1;
185    private static final int FOCUSING_SNAP_ON_FINISH = 2;
186    private static final int FOCUS_SUCCESS = 3;
187    private static final int FOCUS_FAIL = 4;
188    private int mFocusState = FOCUS_NOT_STARTED;
189
190    private ContentResolver mContentResolver;
191    private boolean mDidRegister = false;
192
193    private final ArrayList<MenuItem> mGalleryItems = new ArrayList<MenuItem>();
194
195    private LocationManager mLocationManager = null;
196
197    private final ShutterCallback mShutterCallback = new ShutterCallback();
198    private final PostViewPictureCallback mPostViewPictureCallback =
199            new PostViewPictureCallback();
200    private final RawPictureCallback mRawPictureCallback =
201            new RawPictureCallback();
202    private final AutoFocusCallback mAutoFocusCallback =
203            new AutoFocusCallback();
204    private final ZoomListener mZoomListener = new ZoomListener();
205    // Use the ErrorCallback to capture the crash count
206    // on the mediaserver
207    private final ErrorCallback mErrorCallback = new ErrorCallback();
208
209    private long mFocusStartTime;
210    private long mFocusCallbackTime;
211    private long mCaptureStartTime;
212    private long mShutterCallbackTime;
213    private long mPostViewPictureCallbackTime;
214    private long mRawPictureCallbackTime;
215    private long mJpegPictureCallbackTime;
216    private int mPicturesRemaining;
217
218    // These latency time are for the CameraLatency test.
219    public long mAutoFocusTime;
220    public long mShutterLag;
221    public long mShutterToPictureDisplayedTime;
222    public long mPictureDisplayedToJpegCallbackTime;
223    public long mJpegCallbackFinishTime;
224
225    // Add for test
226    public static boolean mMediaServerDied = false;
227
228    // Focus mode. Options are pref_camera_focusmode_entryvalues.
229    private String mFocusMode;
230    private String mSceneMode;
231
232    private final Handler mHandler = new MainHandler();
233    private CameraHeadUpDisplay mHeadUpDisplay;
234
235    // multiple cameras support
236    private int mNumberOfCameras;
237    private int mCameraId;
238
239    /**
240     * This Handler is used to post message back onto the main thread of the
241     * application
242     */
243    private class MainHandler extends Handler {
244        @Override
245        public void handleMessage(Message msg) {
246            switch (msg.what) {
247                case RESTART_PREVIEW: {
248                    restartPreview();
249                    if (mJpegPictureCallbackTime != 0) {
250                        long now = System.currentTimeMillis();
251                        mJpegCallbackFinishTime = now - mJpegPictureCallbackTime;
252                        Log.v(TAG, "mJpegCallbackFinishTime = "
253                                + mJpegCallbackFinishTime + "ms");
254                        mJpegPictureCallbackTime = 0;
255                    }
256                    break;
257                }
258
259                case CLEAR_SCREEN_DELAY: {
260                    getWindow().clearFlags(
261                            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
262                    break;
263                }
264
265                case FIRST_TIME_INIT: {
266                    initializeFirstTime();
267                    break;
268                }
269
270                case SET_CAMERA_PARAMETERS_WHEN_IDLE: {
271                    setCameraParametersWhenIdle(0);
272                    break;
273                }
274            }
275        }
276    }
277
278    private void resetExposureCompensation() {
279        String value = mPreferences.getString(CameraSettings.KEY_EXPOSURE,
280                CameraSettings.EXPOSURE_DEFAULT_VALUE);
281        if (!CameraSettings.EXPOSURE_DEFAULT_VALUE.equals(value)) {
282            Editor editor = mPreferences.edit();
283            editor.putString(CameraSettings.KEY_EXPOSURE, "0");
284            editor.apply();
285            if (mHeadUpDisplay != null) {
286                mHeadUpDisplay.reloadPreferences();
287            }
288        }
289    }
290
291    private void keepMediaProviderInstance() {
292        // We want to keep a reference to MediaProvider in camera's lifecycle.
293        // TODO: Utilize mMediaProviderClient instance to replace
294        // ContentResolver calls.
295        if (mMediaProviderClient == null) {
296            mMediaProviderClient = getContentResolver()
297                    .acquireContentProviderClient(MediaStore.AUTHORITY);
298        }
299    }
300
301    // Snapshots can only be taken after this is called. It should be called
302    // once only. We could have done these things in onCreate() but we want to
303    // make preview screen appear as soon as possible.
304    private void initializeFirstTime() {
305        if (mFirstTimeInitialized) return;
306
307        // Create orientation listenter. This should be done first because it
308        // takes some time to get first orientation.
309        mOrientationListener = new MyOrientationEventListener(Camera.this);
310        mOrientationListener.enable();
311
312        // Initialize location sevice.
313        mLocationManager = (LocationManager)
314                getSystemService(Context.LOCATION_SERVICE);
315        mRecordLocation = RecordLocationPreference.get(
316                mPreferences, getContentResolver());
317        if (mRecordLocation) startReceivingLocationUpdates();
318
319        keepMediaProviderInstance();
320        checkStorage();
321
322        // Initialize last picture button.
323        mContentResolver = getContentResolver();
324        if (!mIsImageCaptureIntent)  {
325            findViewById(R.id.camera_switch).setOnClickListener(this);
326            mLastPictureButton =
327                    (ImageView) findViewById(R.id.review_thumbnail);
328            mLastPictureButton.setOnClickListener(this);
329            mThumbController = new ThumbnailController(
330                    getResources(), mLastPictureButton, mContentResolver);
331            mThumbController.loadData(ImageManager.getLastImageThumbPath());
332            // Update last image thumbnail.
333            updateThumbnailButton();
334        }
335
336        // Initialize shutter button.
337        mShutterButton = (ShutterButton) findViewById(R.id.shutter_button);
338        mShutterButton.setOnShutterButtonListener(this);
339        mShutterButton.setVisibility(View.VISIBLE);
340
341        mFocusRectangle = (FocusRectangle) findViewById(R.id.focus_rectangle);
342        updateFocusIndicator();
343
344        initializeScreenBrightness();
345        installIntentFilter();
346        initializeFocusTone();
347        initializeZoom();
348        mHeadUpDisplay = new CameraHeadUpDisplay(this);
349        mHeadUpDisplay.setListener(new MyHeadUpDisplayListener());
350        initializeHeadUpDisplay();
351        mFirstTimeInitialized = true;
352        changeHeadUpDisplayState();
353        addIdleHandler();
354    }
355
356    private void addIdleHandler() {
357        MessageQueue queue = Looper.myQueue();
358        queue.addIdleHandler(new MessageQueue.IdleHandler() {
359            public boolean queueIdle() {
360                ImageManager.ensureOSXCompatibleFolder();
361                return false;
362            }
363        });
364    }
365
366    private void updateThumbnailButton() {
367        // Update last image if URI is invalid and the storage is ready.
368        if (!mThumbController.isUriValid() && mPicturesRemaining >= 0) {
369            updateLastImage();
370        }
371        mThumbController.updateDisplayIfNeeded();
372    }
373
374    // If the activity is paused and resumed, this method will be called in
375    // onResume.
376    private void initializeSecondTime() {
377        // Start orientation listener as soon as possible because it takes
378        // some time to get first orientation.
379        mOrientationListener.enable();
380
381        // Start location update if needed.
382        mRecordLocation = RecordLocationPreference.get(
383                mPreferences, getContentResolver());
384        if (mRecordLocation) startReceivingLocationUpdates();
385
386        installIntentFilter();
387        initializeFocusTone();
388        initializeZoom();
389        changeHeadUpDisplayState();
390
391        keepMediaProviderInstance();
392        checkStorage();
393
394        if (!mIsImageCaptureIntent) {
395            updateThumbnailButton();
396        }
397    }
398
399    private void initializeZoom() {
400        if (!mParameters.isZoomSupported()) return;
401
402        mZoomMax = mParameters.getMaxZoom();
403        mSmoothZoomSupported = mParameters.isSmoothZoomSupported();
404        mGestureDetector = new GestureDetector(this, new ZoomGestureListener());
405
406        mCameraDevice.setZoomChangeListener(mZoomListener);
407    }
408
409    private void onZoomValueChanged(int index) {
410        if (mSmoothZoomSupported) {
411            if (mTargetZoomValue != index && mZoomState != ZOOM_STOPPED) {
412                mTargetZoomValue = index;
413                if (mZoomState == ZOOM_START) {
414                    mZoomState = ZOOM_STOPPING;
415                    mCameraDevice.stopSmoothZoom();
416                }
417            } else if (mZoomState == ZOOM_STOPPED && mZoomValue != index) {
418                mTargetZoomValue = index;
419                mCameraDevice.startSmoothZoom(index);
420                mZoomState = ZOOM_START;
421            }
422        } else {
423            mZoomValue = index;
424            setCameraParametersWhenIdle(UPDATE_PARAM_ZOOM);
425        }
426    }
427
428    private float[] getZoomRatios() {
429        if(!mParameters.isZoomSupported()) return null;
430        List<Integer> zoomRatios = mParameters.getZoomRatios();
431        float result[] = new float[zoomRatios.size()];
432        for (int i = 0, n = result.length; i < n; ++i) {
433            result[i] = (float) zoomRatios.get(i) / 100f;
434        }
435        return result;
436    }
437
438    private class ZoomGestureListener extends
439            GestureDetector.SimpleOnGestureListener {
440
441        @Override
442        public boolean onDoubleTap(MotionEvent e) {
443            // Perform zoom only when preview is started and snapshot is not in
444            // progress.
445            if (mPausing || !isCameraIdle() || !mPreviewing
446                    || mZoomState != ZOOM_STOPPED) {
447                return false;
448            }
449
450            if (mZoomValue < mZoomMax) {
451                // Zoom in to the maximum.
452                mZoomValue = mZoomMax;
453            } else {
454                mZoomValue = 0;
455            }
456
457            setCameraParametersWhenIdle(UPDATE_PARAM_ZOOM);
458
459            mHeadUpDisplay.setZoomIndex(mZoomValue);
460            return true;
461        }
462    }
463
464    @Override
465    public boolean dispatchTouchEvent(MotionEvent m) {
466        if (!super.dispatchTouchEvent(m) && mGestureDetector != null) {
467            return mGestureDetector.onTouchEvent(m);
468        }
469        return true;
470    }
471
472    LocationListener [] mLocationListeners = new LocationListener[] {
473            new LocationListener(LocationManager.GPS_PROVIDER),
474            new LocationListener(LocationManager.NETWORK_PROVIDER)
475    };
476
477    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
478        @Override
479        public void onReceive(Context context, Intent intent) {
480            String action = intent.getAction();
481            if (action.equals(Intent.ACTION_MEDIA_MOUNTED)
482                    || action.equals(Intent.ACTION_MEDIA_UNMOUNTED)
483                    || action.equals(Intent.ACTION_MEDIA_CHECKING)) {
484                checkStorage();
485            } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)) {
486                checkStorage();
487                if (!mIsImageCaptureIntent)  {
488                    updateThumbnailButton();
489                }
490            }
491        }
492    };
493
494    private class LocationListener
495            implements android.location.LocationListener {
496        Location mLastLocation;
497        boolean mValid = false;
498        String mProvider;
499
500        public LocationListener(String provider) {
501            mProvider = provider;
502            mLastLocation = new Location(mProvider);
503        }
504
505        public void onLocationChanged(Location newLocation) {
506            if (newLocation.getLatitude() == 0.0
507                    && newLocation.getLongitude() == 0.0) {
508                // Hack to filter out 0.0,0.0 locations
509                return;
510            }
511            // If GPS is available before start camera, we won't get status
512            // update so update GPS indicator when we receive data.
513            if (mRecordLocation
514                    && LocationManager.GPS_PROVIDER.equals(mProvider)) {
515                if (mHeadUpDisplay != null) {
516                    mHeadUpDisplay.setGpsHasSignal(true);
517                }
518            }
519            mLastLocation.set(newLocation);
520            mValid = true;
521        }
522
523        public void onProviderEnabled(String provider) {
524        }
525
526        public void onProviderDisabled(String provider) {
527            mValid = false;
528        }
529
530        public void onStatusChanged(
531                String provider, int status, Bundle extras) {
532            switch(status) {
533                case LocationProvider.OUT_OF_SERVICE:
534                case LocationProvider.TEMPORARILY_UNAVAILABLE: {
535                    mValid = false;
536                    if (mRecordLocation &&
537                            LocationManager.GPS_PROVIDER.equals(provider)) {
538                        if (mHeadUpDisplay != null) {
539                            mHeadUpDisplay.setGpsHasSignal(false);
540                        }
541                    }
542                    break;
543                }
544            }
545        }
546
547        public Location current() {
548            return mValid ? mLastLocation : null;
549        }
550    }
551
552    private final class ShutterCallback
553            implements android.hardware.Camera.ShutterCallback {
554        public void onShutter() {
555            mShutterCallbackTime = System.currentTimeMillis();
556            mShutterLag = mShutterCallbackTime - mCaptureStartTime;
557            Log.v(TAG, "mShutterLag = " + mShutterLag + "ms");
558            clearFocusState();
559        }
560    }
561
562    private final class PostViewPictureCallback implements PictureCallback {
563        public void onPictureTaken(
564                byte [] data, android.hardware.Camera camera) {
565            mPostViewPictureCallbackTime = System.currentTimeMillis();
566            Log.v(TAG, "mShutterToPostViewCallbackTime = "
567                    + (mPostViewPictureCallbackTime - mShutterCallbackTime)
568                    + "ms");
569        }
570    }
571
572    private final class RawPictureCallback implements PictureCallback {
573        public void onPictureTaken(
574                byte [] rawData, android.hardware.Camera camera) {
575            mRawPictureCallbackTime = System.currentTimeMillis();
576            Log.v(TAG, "mShutterToRawCallbackTime = "
577                    + (mRawPictureCallbackTime - mShutterCallbackTime) + "ms");
578        }
579    }
580
581    private final class JpegPictureCallback implements PictureCallback {
582        Location mLocation;
583
584        public JpegPictureCallback(Location loc) {
585            mLocation = loc;
586        }
587
588        public void onPictureTaken(
589                final byte [] jpegData, final android.hardware.Camera camera) {
590            if (mPausing) {
591                return;
592            }
593
594            mJpegPictureCallbackTime = System.currentTimeMillis();
595            // If postview callback has arrived, the captured image is displayed
596            // in postview callback. If not, the captured image is displayed in
597            // raw picture callback.
598            if (mPostViewPictureCallbackTime != 0) {
599                mShutterToPictureDisplayedTime =
600                        mPostViewPictureCallbackTime - mShutterCallbackTime;
601                mPictureDisplayedToJpegCallbackTime =
602                        mJpegPictureCallbackTime - mPostViewPictureCallbackTime;
603            } else {
604                mShutterToPictureDisplayedTime =
605                        mRawPictureCallbackTime - mShutterCallbackTime;
606                mPictureDisplayedToJpegCallbackTime =
607                        mJpegPictureCallbackTime - mRawPictureCallbackTime;
608            }
609            Log.v(TAG, "mPictureDisplayedToJpegCallbackTime = "
610                    + mPictureDisplayedToJpegCallbackTime + "ms");
611            mHeadUpDisplay.setEnabled(true);
612
613            if (!mIsImageCaptureIntent) {
614                // We want to show the taken picture for a while, so we wait
615                // for at least 1.2 second before restarting the preview.
616                long delay = 1200 - mPictureDisplayedToJpegCallbackTime;
617                if (delay < 0) {
618                    restartPreview();
619                } else {
620                    mHandler.sendEmptyMessageDelayed(RESTART_PREVIEW, delay);
621                }
622            }
623            mImageCapture.storeImage(jpegData, camera, mLocation);
624
625            // Calculate this in advance of each shot so we don't add to shutter
626            // latency. It's true that someone else could write to the SD card in
627            // the mean time and fill it, but that could have happened between the
628            // shutter press and saving the JPEG too.
629            calculatePicturesRemaining();
630
631            if (mPicturesRemaining < 1) {
632                updateStorageHint(mPicturesRemaining);
633            }
634
635            if (!mHandler.hasMessages(RESTART_PREVIEW)) {
636                long now = System.currentTimeMillis();
637                mJpegCallbackFinishTime = now - mJpegPictureCallbackTime;
638                Log.v(TAG, "mJpegCallbackFinishTime = "
639                        + mJpegCallbackFinishTime + "ms");
640                mJpegPictureCallbackTime = 0;
641            }
642        }
643    }
644
645    private final class AutoFocusCallback
646            implements android.hardware.Camera.AutoFocusCallback {
647        public void onAutoFocus(
648                boolean focused, android.hardware.Camera camera) {
649            mFocusCallbackTime = System.currentTimeMillis();
650            mAutoFocusTime = mFocusCallbackTime - mFocusStartTime;
651            Log.v(TAG, "mAutoFocusTime = " + mAutoFocusTime + "ms");
652            if (mFocusState == FOCUSING_SNAP_ON_FINISH) {
653                // Take the picture no matter focus succeeds or fails. No need
654                // to play the AF sound if we're about to play the shutter
655                // sound.
656                if (focused) {
657                    mFocusState = FOCUS_SUCCESS;
658                } else {
659                    mFocusState = FOCUS_FAIL;
660                }
661                mImageCapture.onSnap();
662            } else if (mFocusState == FOCUSING) {
663                // User is half-pressing the focus key. Play the focus tone.
664                // Do not take the picture now.
665                ToneGenerator tg = mFocusToneGenerator;
666                if (tg != null) {
667                    tg.startTone(ToneGenerator.TONE_PROP_BEEP2);
668                }
669                if (focused) {
670                    mFocusState = FOCUS_SUCCESS;
671                } else {
672                    mFocusState = FOCUS_FAIL;
673                }
674            } else if (mFocusState == FOCUS_NOT_STARTED) {
675                // User has released the focus key before focus completes.
676                // Do nothing.
677            }
678            updateFocusIndicator();
679        }
680    }
681
682    private static final class ErrorCallback
683        implements android.hardware.Camera.ErrorCallback {
684        public void onError(int error, android.hardware.Camera camera) {
685            if (error == android.hardware.Camera.CAMERA_ERROR_SERVER_DIED) {
686                 mMediaServerDied = true;
687                 Log.v(TAG, "media server died");
688            }
689        }
690    }
691
692    private final class ZoomListener
693            implements android.hardware.Camera.OnZoomChangeListener {
694        public void onZoomChange(
695                int value, boolean stopped, android.hardware.Camera camera) {
696            Log.v(TAG, "Zoom changed: value=" + value + ". stopped="+ stopped);
697            mZoomValue = value;
698            // Keep mParameters up to date. We do not getParameter again in
699            // takePicture. If we do not do this, wrong zoom value will be set.
700            mParameters.setZoom(value);
701            // We only care if the zoom is stopped. mZooming is set to true when
702            // we start smooth zoom.
703            if (stopped && mZoomState != ZOOM_STOPPED) {
704                if (value != mTargetZoomValue) {
705                    mCameraDevice.startSmoothZoom(mTargetZoomValue);
706                    mZoomState = ZOOM_START;
707                } else {
708                    mZoomState = ZOOM_STOPPED;
709                }
710            }
711        }
712    }
713
714    private class ImageCapture {
715
716        private Uri mLastContentUri;
717
718        byte[] mCaptureOnlyData;
719
720        // Returns the rotation degree in the jpeg header.
721        private int storeImage(byte[] data, Location loc) {
722            try {
723                long dateTaken = System.currentTimeMillis();
724                String title = createName(dateTaken);
725                String filename = title + ".jpg";
726                int[] degree = new int[1];
727                mLastContentUri = ImageManager.addImage(
728                        mContentResolver,
729                        title,
730                        dateTaken,
731                        loc, // location from gps/network
732                        ImageManager.CAMERA_IMAGE_BUCKET_NAME, filename,
733                        null, data,
734                        degree);
735                return degree[0];
736            } catch (Exception ex) {
737                Log.e(TAG, "Exception while compressing image.", ex);
738                return 0;
739            }
740        }
741
742        public void storeImage(final byte[] data,
743                android.hardware.Camera camera, Location loc) {
744            if (!mIsImageCaptureIntent) {
745                int degree = storeImage(data, loc);
746                sendBroadcast(new Intent(
747                        "com.android.camera.NEW_PICTURE", mLastContentUri));
748                setLastPictureThumb(data, degree,
749                        mImageCapture.getLastCaptureUri());
750                mThumbController.updateDisplayIfNeeded();
751            } else {
752                mCaptureOnlyData = data;
753                showPostCaptureAlert();
754            }
755        }
756
757        /**
758         * Initiate the capture of an image.
759         */
760        public void initiate() {
761            if (mCameraDevice == null) {
762                return;
763            }
764
765            capture();
766        }
767
768        public Uri getLastCaptureUri() {
769            return mLastContentUri;
770        }
771
772        public byte[] getLastCaptureData() {
773            return mCaptureOnlyData;
774        }
775
776        private void capture() {
777            mCaptureOnlyData = null;
778
779            // See android.hardware.Camera.Parameters.setRotation for
780            // documentation.
781            int rotation = 0;
782            if (mOrientation != OrientationEventListener.ORIENTATION_UNKNOWN) {
783                CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId];
784                if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
785                    rotation = (info.orientation - mOrientation + 360) % 360;
786                } else {  // back-facing camera
787                    rotation = (info.orientation + mOrientation) % 360;
788                }
789            }
790            mParameters.setRotation(rotation);
791
792            // Clear previous GPS location from the parameters.
793            mParameters.removeGpsData();
794
795            // We always encode GpsTimeStamp
796            mParameters.setGpsTimestamp(System.currentTimeMillis() / 1000);
797
798            // Set GPS location.
799            Location loc = mRecordLocation ? getCurrentLocation() : null;
800            if (loc != null) {
801                double lat = loc.getLatitude();
802                double lon = loc.getLongitude();
803                boolean hasLatLon = (lat != 0.0d) || (lon != 0.0d);
804
805                if (hasLatLon) {
806                    mParameters.setGpsLatitude(lat);
807                    mParameters.setGpsLongitude(lon);
808                    mParameters.setGpsProcessingMethod(loc.getProvider().toUpperCase());
809                    if (loc.hasAltitude()) {
810                        mParameters.setGpsAltitude(loc.getAltitude());
811                    } else {
812                        // for NETWORK_PROVIDER location provider, we may have
813                        // no altitude information, but the driver needs it, so
814                        // we fake one.
815                        mParameters.setGpsAltitude(0);
816                    }
817                    if (loc.getTime() != 0) {
818                        // Location.getTime() is UTC in milliseconds.
819                        // gps-timestamp is UTC in seconds.
820                        long utcTimeSeconds = loc.getTime() / 1000;
821                        mParameters.setGpsTimestamp(utcTimeSeconds);
822                    }
823                } else {
824                    loc = null;
825                }
826            }
827
828            mCameraDevice.setParameters(mParameters);
829
830            mCameraDevice.takePicture(mShutterCallback, mRawPictureCallback,
831                    mPostViewPictureCallback, new JpegPictureCallback(loc));
832            mPreviewing = false;
833        }
834
835        public void onSnap() {
836            // If we are already in the middle of taking a snapshot then ignore.
837            if (mPausing || mStatus == SNAPSHOT_IN_PROGRESS) {
838                return;
839            }
840            mCaptureStartTime = System.currentTimeMillis();
841            mPostViewPictureCallbackTime = 0;
842            mHeadUpDisplay.setEnabled(false);
843            mStatus = SNAPSHOT_IN_PROGRESS;
844
845            mImageCapture.initiate();
846        }
847
848        private void clearLastData() {
849            mCaptureOnlyData = null;
850        }
851    }
852
853    private boolean saveDataToFile(String filePath, byte[] data) {
854        FileOutputStream f = null;
855        try {
856            f = new FileOutputStream(filePath);
857            f.write(data);
858        } catch (IOException e) {
859            return false;
860        } finally {
861            MenuHelper.closeSilently(f);
862        }
863        return true;
864    }
865
866    private void setLastPictureThumb(byte[] data, int degree, Uri uri) {
867        BitmapFactory.Options options = new BitmapFactory.Options();
868        options.inSampleSize = 16;
869        Bitmap lastPictureThumb =
870                BitmapFactory.decodeByteArray(data, 0, data.length, options);
871        lastPictureThumb = Util.rotate(lastPictureThumb, degree);
872        mThumbController.setData(uri, lastPictureThumb);
873    }
874
875    private String createName(long dateTaken) {
876        Date date = new Date(dateTaken);
877        SimpleDateFormat dateFormat = new SimpleDateFormat(
878                getString(R.string.image_file_name_format));
879
880        return dateFormat.format(date);
881    }
882
883    @Override
884    public void onCreate(Bundle icicle) {
885        super.onCreate(icicle);
886
887        setContentView(R.layout.camera);
888        mSurfaceView = (SurfaceView) findViewById(R.id.camera_preview);
889
890        mPreferences = new ComboPreferences(this);
891        CameraSettings.upgradeGlobalPreferences(mPreferences.getGlobal());
892        mCameraId = CameraSettings.readPreferredCameraId(mPreferences);
893        mPreferences.setLocalId(this, mCameraId);
894        CameraSettings.upgradeLocalPreferences(mPreferences.getLocal());
895
896        mNumberOfCameras = CameraHolder.instance().getNumberOfCameras();
897
898        // we need to reset exposure for the preview
899        resetExposureCompensation();
900        /*
901         * To reduce startup time, we start the preview in another thread.
902         * We make sure the preview is started at the end of onCreate.
903         */
904        Thread startPreviewThread = new Thread(new Runnable() {
905            public void run() {
906                try {
907                    mStartPreviewFail = false;
908                    startPreview();
909                } catch (CameraHardwareException e) {
910                    // In eng build, we throw the exception so that test tool
911                    // can detect it and report it
912                    if ("eng".equals(Build.TYPE)) {
913                        throw new RuntimeException(e);
914                    }
915                    mStartPreviewFail = true;
916                }
917            }
918        });
919        startPreviewThread.start();
920
921        // don't set mSurfaceHolder here. We have it set ONLY within
922        // surfaceChanged / surfaceDestroyed, other parts of the code
923        // assume that when it is set, the surface is also set.
924        SurfaceHolder holder = mSurfaceView.getHolder();
925        holder.addCallback(this);
926        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
927
928        mIsImageCaptureIntent = isImageCaptureIntent();
929        if (mIsImageCaptureIntent) {
930            setupCaptureParams();
931        }
932
933        LayoutInflater inflater = getLayoutInflater();
934
935        ViewGroup rootView = (ViewGroup) findViewById(R.id.camera);
936        if (mIsImageCaptureIntent) {
937            View controlBar = inflater.inflate(
938                    R.layout.attach_camera_control, rootView);
939            controlBar.findViewById(R.id.btn_cancel).setOnClickListener(this);
940            controlBar.findViewById(R.id.btn_retake).setOnClickListener(this);
941            controlBar.findViewById(R.id.btn_done).setOnClickListener(this);
942        } else {
943            inflater.inflate(R.layout.camera_control, rootView);
944            mSwitcher = ((Switcher) findViewById(R.id.camera_switch));
945            mSwitcher.setOnSwitchListener(this);
946            mSwitcher.addTouchView(findViewById(R.id.camera_switch_set));
947        }
948
949        // Make sure preview is started.
950        try {
951            startPreviewThread.join();
952            if (mStartPreviewFail) {
953                showCameraErrorAndFinish();
954                return;
955            }
956        } catch (InterruptedException ex) {
957            // ignore
958        }
959    }
960
961    private void changeHeadUpDisplayState() {
962        // If the camera resumes behind the lock screen, the orientation
963        // will be portrait. That causes OOM when we try to allocation GPU
964        // memory for the GLSurfaceView again when the orientation changes. So,
965        // we delayed initialization of HeadUpDisplay until the orientation
966        // becomes landscape.
967        Configuration config = getResources().getConfiguration();
968        if (config.orientation == Configuration.ORIENTATION_LANDSCAPE
969                && !mPausing && mFirstTimeInitialized) {
970            if (mGLRootView == null) attachHeadUpDisplay();
971        } else if (mGLRootView != null) {
972            detachHeadUpDisplay();
973        }
974    }
975
976    private void overrideHudSettings(final String flashMode,
977            final String whiteBalance, final String focusMode) {
978        mHeadUpDisplay.overrideSettings(
979                CameraSettings.KEY_FLASH_MODE, flashMode,
980                CameraSettings.KEY_WHITE_BALANCE, whiteBalance,
981                CameraSettings.KEY_FOCUS_MODE, focusMode);
982    }
983
984    private void updateSceneModeInHud() {
985        // If scene mode is set, we cannot set flash mode, white balance, and
986        // focus mode, instead, we read it from driver
987        if (!Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) {
988            overrideHudSettings(mParameters.getFlashMode(),
989                    mParameters.getWhiteBalance(), mParameters.getFocusMode());
990        } else {
991            overrideHudSettings(null, null, null);
992        }
993    }
994
995    private void initializeHeadUpDisplay() {
996        CameraSettings settings = new CameraSettings(this, mInitialParams,
997                CameraHolder.instance().getCameraInfo());
998        mHeadUpDisplay.initialize(this,
999                settings.getPreferenceGroup(R.xml.camera_preferences),
1000                getZoomRatios(), mOrientationCompensation);
1001        if (mParameters.isZoomSupported()) {
1002            mHeadUpDisplay.setZoomListener(new ZoomControllerListener() {
1003                public void onZoomChanged(
1004                        int index, float ratio, boolean isMoving) {
1005                    onZoomValueChanged(index);
1006                }
1007            });
1008        }
1009        updateSceneModeInHud();
1010    }
1011
1012    private void attachHeadUpDisplay() {
1013        mHeadUpDisplay.setOrientation(mOrientationCompensation);
1014        if (mParameters.isZoomSupported()) {
1015            mHeadUpDisplay.setZoomIndex(mZoomValue);
1016        }
1017        FrameLayout frame = (FrameLayout) findViewById(R.id.frame);
1018        mGLRootView = new GLRootView(this);
1019        mGLRootView.setContentPane(mHeadUpDisplay);
1020        frame.addView(mGLRootView);
1021    }
1022
1023    private void detachHeadUpDisplay() {
1024        mHeadUpDisplay.setGpsHasSignal(false);
1025        mHeadUpDisplay.collapse();
1026        ((ViewGroup) mGLRootView.getParent()).removeView(mGLRootView);
1027        mGLRootView = null;
1028    }
1029
1030    public static int roundOrientation(int orientation) {
1031        return ((orientation + 45) / 90 * 90) % 360;
1032    }
1033
1034    private class MyOrientationEventListener
1035            extends OrientationEventListener {
1036        public MyOrientationEventListener(Context context) {
1037            super(context);
1038        }
1039
1040        @Override
1041        public void onOrientationChanged(int orientation) {
1042            // We keep the last known orientation. So if the user first orient
1043            // the camera then point the camera to floor or sky, we still have
1044            // the correct orientation.
1045            if (orientation == ORIENTATION_UNKNOWN) return;
1046            orientation = roundOrientation(orientation);
1047            if (orientation != mOrientation) {
1048                mOrientation = orientation;
1049                mOrientationCompensation = orientation
1050                        + Util.getDisplayRotation(Camera.this);
1051
1052                if (!mIsImageCaptureIntent) {
1053                    setOrientationIndicator(mOrientationCompensation);
1054                }
1055                mHeadUpDisplay.setOrientation(mOrientationCompensation);
1056            }
1057        }
1058    }
1059
1060    private void setOrientationIndicator(int degree) {
1061        ((RotateImageView) findViewById(
1062                R.id.review_thumbnail)).setDegree(degree);
1063        ((RotateImageView) findViewById(
1064                R.id.camera_switch_icon)).setDegree(degree);
1065        ((RotateImageView) findViewById(
1066                R.id.video_switch_icon)).setDegree(degree);
1067    }
1068
1069    @Override
1070    public void onStart() {
1071        super.onStart();
1072        if (!mIsImageCaptureIntent) {
1073            mSwitcher.setSwitch(SWITCH_CAMERA);
1074        }
1075    }
1076
1077    @Override
1078    public void onStop() {
1079        super.onStop();
1080        if (mMediaProviderClient != null) {
1081            mMediaProviderClient.release();
1082            mMediaProviderClient = null;
1083        }
1084    }
1085
1086    private void checkStorage() {
1087        calculatePicturesRemaining();
1088        updateStorageHint(mPicturesRemaining);
1089    }
1090
1091    public void onClick(View v) {
1092        switch (v.getId()) {
1093            case R.id.btn_retake:
1094                hidePostCaptureAlert();
1095                restartPreview();
1096                break;
1097            case R.id.review_thumbnail:
1098                if (isCameraIdle()) {
1099                    viewLastImage();
1100                }
1101                break;
1102            case R.id.btn_done:
1103                doAttach();
1104                break;
1105            case R.id.btn_cancel:
1106                doCancel();
1107        }
1108    }
1109
1110    private Bitmap createCaptureBitmap(byte[] data) {
1111        // This is really stupid...we just want to read the orientation in
1112        // the jpeg header.
1113        String filepath = ImageManager.getTempJpegPath();
1114        int degree = 0;
1115        if (saveDataToFile(filepath, data)) {
1116            degree = ImageManager.getExifOrientation(filepath);
1117            new File(filepath).delete();
1118        }
1119
1120        // Limit to 50k pixels so we can return it in the intent.
1121        Bitmap bitmap = Util.makeBitmap(data, 50 * 1024);
1122        bitmap = Util.rotate(bitmap, degree);
1123        return bitmap;
1124    }
1125
1126    private void doAttach() {
1127        if (mPausing) {
1128            return;
1129        }
1130
1131        byte[] data = mImageCapture.getLastCaptureData();
1132
1133        if (mCropValue == null) {
1134            // First handle the no crop case -- just return the value.  If the
1135            // caller specifies a "save uri" then write the data to it's
1136            // stream. Otherwise, pass back a scaled down version of the bitmap
1137            // directly in the extras.
1138            if (mSaveUri != null) {
1139                OutputStream outputStream = null;
1140                try {
1141                    outputStream = mContentResolver.openOutputStream(mSaveUri);
1142                    outputStream.write(data);
1143                    outputStream.close();
1144
1145                    setResult(RESULT_OK);
1146                    finish();
1147                } catch (IOException ex) {
1148                    // ignore exception
1149                } finally {
1150                    Util.closeSilently(outputStream);
1151                }
1152            } else {
1153                Bitmap bitmap = createCaptureBitmap(data);
1154                setResult(RESULT_OK,
1155                        new Intent("inline-data").putExtra("data", bitmap));
1156                finish();
1157            }
1158        } else {
1159            // Save the image to a temp file and invoke the cropper
1160            Uri tempUri = null;
1161            FileOutputStream tempStream = null;
1162            try {
1163                File path = getFileStreamPath(sTempCropFilename);
1164                path.delete();
1165                tempStream = openFileOutput(sTempCropFilename, 0);
1166                tempStream.write(data);
1167                tempStream.close();
1168                tempUri = Uri.fromFile(path);
1169            } catch (FileNotFoundException ex) {
1170                setResult(Activity.RESULT_CANCELED);
1171                finish();
1172                return;
1173            } catch (IOException ex) {
1174                setResult(Activity.RESULT_CANCELED);
1175                finish();
1176                return;
1177            } finally {
1178                Util.closeSilently(tempStream);
1179            }
1180
1181            Bundle newExtras = new Bundle();
1182            if (mCropValue.equals("circle")) {
1183                newExtras.putString("circleCrop", "true");
1184            }
1185            if (mSaveUri != null) {
1186                newExtras.putParcelable(MediaStore.EXTRA_OUTPUT, mSaveUri);
1187            } else {
1188                newExtras.putBoolean("return-data", true);
1189            }
1190
1191            Intent cropIntent = new Intent("com.android.camera.action.CROP");
1192
1193            cropIntent.setData(tempUri);
1194            cropIntent.putExtras(newExtras);
1195
1196            startActivityForResult(cropIntent, CROP_MSG);
1197        }
1198    }
1199
1200    private void doCancel() {
1201        setResult(RESULT_CANCELED, new Intent());
1202        finish();
1203    }
1204
1205    public void onShutterButtonFocus(ShutterButton button, boolean pressed) {
1206        if (mPausing) {
1207            return;
1208        }
1209        switch (button.getId()) {
1210            case R.id.shutter_button:
1211                doFocus(pressed);
1212                break;
1213        }
1214    }
1215
1216    public void onShutterButtonClick(ShutterButton button) {
1217        if (mPausing) {
1218            return;
1219        }
1220        switch (button.getId()) {
1221            case R.id.shutter_button:
1222                doSnap();
1223                break;
1224        }
1225    }
1226
1227    private OnScreenHint mStorageHint;
1228
1229    private void updateStorageHint(int remaining) {
1230        String noStorageText = null;
1231
1232        if (remaining == MenuHelper.NO_STORAGE_ERROR) {
1233            String state = Environment.getExternalStorageState();
1234            if (state == Environment.MEDIA_CHECKING) {
1235                noStorageText = getString(R.string.preparing_sd);
1236            } else {
1237                noStorageText = getString(R.string.no_storage);
1238            }
1239        } else if (remaining == MenuHelper.CANNOT_STAT_ERROR) {
1240            noStorageText = getString(R.string.access_sd_fail);
1241        } else if (remaining < 1) {
1242            noStorageText = getString(R.string.not_enough_space);
1243        }
1244
1245        if (noStorageText != null) {
1246            if (mStorageHint == null) {
1247                mStorageHint = OnScreenHint.makeText(this, noStorageText);
1248            } else {
1249                mStorageHint.setText(noStorageText);
1250            }
1251            mStorageHint.show();
1252        } else if (mStorageHint != null) {
1253            mStorageHint.cancel();
1254            mStorageHint = null;
1255        }
1256    }
1257
1258    private void installIntentFilter() {
1259        // install an intent filter to receive SD card related events.
1260        IntentFilter intentFilter =
1261                new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);
1262        intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
1263        intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
1264        intentFilter.addAction(Intent.ACTION_MEDIA_CHECKING);
1265        intentFilter.addDataScheme("file");
1266        registerReceiver(mReceiver, intentFilter);
1267        mDidRegister = true;
1268    }
1269
1270    private void initializeFocusTone() {
1271        // Initialize focus tone generator.
1272        try {
1273            mFocusToneGenerator = new ToneGenerator(
1274                    AudioManager.STREAM_SYSTEM, FOCUS_BEEP_VOLUME);
1275        } catch (Throwable ex) {
1276            Log.w(TAG, "Exception caught while creating tone generator: ", ex);
1277            mFocusToneGenerator = null;
1278        }
1279    }
1280
1281    private void initializeScreenBrightness() {
1282        Window win = getWindow();
1283        // Overright the brightness settings if it is automatic
1284        int mode = Settings.System.getInt(
1285                getContentResolver(),
1286                Settings.System.SCREEN_BRIGHTNESS_MODE,
1287                Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
1288        if (mode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
1289            WindowManager.LayoutParams winParams = win.getAttributes();
1290            winParams.screenBrightness = DEFAULT_CAMERA_BRIGHTNESS;
1291            win.setAttributes(winParams);
1292        }
1293    }
1294
1295    @Override
1296    protected void onResume() {
1297        super.onResume();
1298
1299        mPausing = false;
1300        mJpegPictureCallbackTime = 0;
1301        mZoomValue = 0;
1302        mImageCapture = new ImageCapture();
1303
1304        // Start the preview if it is not started.
1305        if (!mPreviewing && !mStartPreviewFail) {
1306            resetExposureCompensation();
1307            if (!restartPreview()) return;
1308        }
1309
1310        if (mSurfaceHolder != null) {
1311            // If first time initialization is not finished, put it in the
1312            // message queue.
1313            if (!mFirstTimeInitialized) {
1314                mHandler.sendEmptyMessage(FIRST_TIME_INIT);
1315            } else {
1316                initializeSecondTime();
1317            }
1318        }
1319        keepScreenOnAwhile();
1320    }
1321
1322    @Override
1323    public void onConfigurationChanged(Configuration config) {
1324        super.onConfigurationChanged(config);
1325        changeHeadUpDisplayState();
1326    }
1327
1328    private static ImageManager.DataLocation dataLocation() {
1329        return ImageManager.DataLocation.EXTERNAL;
1330    }
1331
1332    @Override
1333    protected void onPause() {
1334        mPausing = true;
1335        stopPreview();
1336        // Close the camera now because other activities may need to use it.
1337        closeCamera();
1338        resetScreenOn();
1339        changeHeadUpDisplayState();
1340
1341        if (mFirstTimeInitialized) {
1342            mOrientationListener.disable();
1343            if (!mIsImageCaptureIntent) {
1344                mThumbController.storeData(
1345                        ImageManager.getLastImageThumbPath());
1346            }
1347            hidePostCaptureAlert();
1348        }
1349
1350        if (mDidRegister) {
1351            unregisterReceiver(mReceiver);
1352            mDidRegister = false;
1353        }
1354        stopReceivingLocationUpdates();
1355
1356        if (mFocusToneGenerator != null) {
1357            mFocusToneGenerator.release();
1358            mFocusToneGenerator = null;
1359        }
1360
1361        if (mStorageHint != null) {
1362            mStorageHint.cancel();
1363            mStorageHint = null;
1364        }
1365
1366        // If we are in an image capture intent and has taken
1367        // a picture, we just clear it in onPause.
1368        mImageCapture.clearLastData();
1369        mImageCapture = null;
1370
1371        // Remove the messages in the event queue.
1372        mHandler.removeMessages(RESTART_PREVIEW);
1373        mHandler.removeMessages(FIRST_TIME_INIT);
1374
1375        super.onPause();
1376    }
1377
1378    @Override
1379    protected void onActivityResult(
1380            int requestCode, int resultCode, Intent data) {
1381        switch (requestCode) {
1382            case CROP_MSG: {
1383                Intent intent = new Intent();
1384                if (data != null) {
1385                    Bundle extras = data.getExtras();
1386                    if (extras != null) {
1387                        intent.putExtras(extras);
1388                    }
1389                }
1390                setResult(resultCode, intent);
1391                finish();
1392
1393                File path = getFileStreamPath(sTempCropFilename);
1394                path.delete();
1395
1396                break;
1397            }
1398        }
1399    }
1400
1401    private boolean canTakePicture() {
1402        return isCameraIdle() && mPreviewing && (mPicturesRemaining > 0);
1403    }
1404
1405    private void autoFocus() {
1406        // Initiate autofocus only when preview is started and snapshot is not
1407        // in progress.
1408        if (canTakePicture()) {
1409            mHeadUpDisplay.setEnabled(false);
1410            Log.v(TAG, "Start autofocus.");
1411            mFocusStartTime = System.currentTimeMillis();
1412            mFocusState = FOCUSING;
1413            updateFocusIndicator();
1414            mCameraDevice.autoFocus(mAutoFocusCallback);
1415        }
1416    }
1417
1418    private void cancelAutoFocus() {
1419        // User releases half-pressed focus key.
1420        if (mStatus != SNAPSHOT_IN_PROGRESS && (mFocusState == FOCUSING
1421                || mFocusState == FOCUS_SUCCESS || mFocusState == FOCUS_FAIL)) {
1422            Log.v(TAG, "Cancel autofocus.");
1423            mHeadUpDisplay.setEnabled(true);
1424            mCameraDevice.cancelAutoFocus();
1425        }
1426        if (mFocusState != FOCUSING_SNAP_ON_FINISH) {
1427            clearFocusState();
1428        }
1429    }
1430
1431    private void clearFocusState() {
1432        mFocusState = FOCUS_NOT_STARTED;
1433        updateFocusIndicator();
1434    }
1435
1436    private void updateFocusIndicator() {
1437        if (mFocusRectangle == null) return;
1438
1439        if (mFocusState == FOCUSING || mFocusState == FOCUSING_SNAP_ON_FINISH) {
1440            mFocusRectangle.showStart();
1441        } else if (mFocusState == FOCUS_SUCCESS) {
1442            mFocusRectangle.showSuccess();
1443        } else if (mFocusState == FOCUS_FAIL) {
1444            mFocusRectangle.showFail();
1445        } else {
1446            mFocusRectangle.clear();
1447        }
1448    }
1449
1450    @Override
1451    public void onBackPressed() {
1452        if (!isCameraIdle()) {
1453            // ignore backs while we're taking a picture
1454            return;
1455        } else if (mHeadUpDisplay == null || !mHeadUpDisplay.collapse()) {
1456            super.onBackPressed();
1457        }
1458    }
1459
1460    @Override
1461    public boolean onKeyDown(int keyCode, KeyEvent event) {
1462        switch (keyCode) {
1463            case KeyEvent.KEYCODE_FOCUS:
1464                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1465                    doFocus(true);
1466                }
1467                return true;
1468            case KeyEvent.KEYCODE_CAMERA:
1469                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1470                    doSnap();
1471                }
1472                return true;
1473            case KeyEvent.KEYCODE_DPAD_CENTER:
1474                // If we get a dpad center event without any focused view, move
1475                // the focus to the shutter button and press it.
1476                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1477                    // Start auto-focus immediately to reduce shutter lag. After
1478                    // the shutter button gets the focus, doFocus() will be
1479                    // called again but it is fine.
1480                    if (mHeadUpDisplay.collapse()) return true;
1481                    doFocus(true);
1482                    if (mShutterButton.isInTouchMode()) {
1483                        mShutterButton.requestFocusFromTouch();
1484                    } else {
1485                        mShutterButton.requestFocus();
1486                    }
1487                    mShutterButton.setPressed(true);
1488                }
1489                return true;
1490        }
1491
1492        return super.onKeyDown(keyCode, event);
1493    }
1494
1495    @Override
1496    public boolean onKeyUp(int keyCode, KeyEvent event) {
1497        switch (keyCode) {
1498            case KeyEvent.KEYCODE_FOCUS:
1499                if (mFirstTimeInitialized) {
1500                    doFocus(false);
1501                }
1502                return true;
1503        }
1504        return super.onKeyUp(keyCode, event);
1505    }
1506
1507    private void doSnap() {
1508        if (mHeadUpDisplay.collapse()) return;
1509
1510        Log.v(TAG, "doSnap: mFocusState=" + mFocusState);
1511        // If the user has half-pressed the shutter and focus is completed, we
1512        // can take the photo right away. If the focus mode is infinity, we can
1513        // also take the photo.
1514        if (mFocusMode.equals(Parameters.FOCUS_MODE_INFINITY)
1515                || mFocusMode.equals(Parameters.FOCUS_MODE_FIXED)
1516                || mFocusMode.equals(Parameters.FOCUS_MODE_EDOF)
1517                || (mFocusState == FOCUS_SUCCESS
1518                || mFocusState == FOCUS_FAIL)) {
1519            mImageCapture.onSnap();
1520        } else if (mFocusState == FOCUSING) {
1521            // Half pressing the shutter (i.e. the focus button event) will
1522            // already have requested AF for us, so just request capture on
1523            // focus here.
1524            mFocusState = FOCUSING_SNAP_ON_FINISH;
1525        } else if (mFocusState == FOCUS_NOT_STARTED) {
1526            // Focus key down event is dropped for some reasons. Just ignore.
1527        }
1528    }
1529
1530    private void doFocus(boolean pressed) {
1531        // Do the focus if the mode is not infinity.
1532        if (mHeadUpDisplay.collapse()) return;
1533        if (!(mFocusMode.equals(Parameters.FOCUS_MODE_INFINITY)
1534                  || mFocusMode.equals(Parameters.FOCUS_MODE_FIXED)
1535                  || mFocusMode.equals(Parameters.FOCUS_MODE_EDOF))) {
1536            if (pressed) {  // Focus key down.
1537                autoFocus();
1538            } else {  // Focus key up.
1539                cancelAutoFocus();
1540            }
1541        }
1542    }
1543
1544    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
1545        // Make sure we have a surface in the holder before proceeding.
1546        if (holder.getSurface() == null) {
1547            Log.d(TAG, "holder.getSurface() == null");
1548            return;
1549        }
1550
1551        // We need to save the holder for later use, even when the mCameraDevice
1552        // is null. This could happen if onResume() is invoked after this
1553        // function.
1554        mSurfaceHolder = holder;
1555
1556        // The mCameraDevice will be null if it fails to connect to the camera
1557        // hardware. In this case we will show a dialog and then finish the
1558        // activity, so it's OK to ignore it.
1559        if (mCameraDevice == null) return;
1560
1561        // Sometimes surfaceChanged is called after onPause or before onResume.
1562        // Ignore it.
1563        if (mPausing || isFinishing()) return;
1564
1565        if (mPreviewing && holder.isCreating()) {
1566            // Set preview display if the surface is being created and preview
1567            // was already started. That means preview display was set to null
1568            // and we need to set it now.
1569            setPreviewDisplay(holder);
1570        } else {
1571            // 1. Restart the preview if the size of surface was changed. The
1572            // framework may not support changing preview display on the fly.
1573            // 2. Start the preview now if surface was destroyed and preview
1574            // stopped.
1575            restartPreview();
1576        }
1577
1578        // If first time initialization is not finished, send a message to do
1579        // it later. We want to finish surfaceChanged as soon as possible to let
1580        // user see preview first.
1581        if (!mFirstTimeInitialized) {
1582            mHandler.sendEmptyMessage(FIRST_TIME_INIT);
1583        } else {
1584            initializeSecondTime();
1585        }
1586    }
1587
1588    public void surfaceCreated(SurfaceHolder holder) {
1589    }
1590
1591    public void surfaceDestroyed(SurfaceHolder holder) {
1592        stopPreview();
1593        mSurfaceHolder = null;
1594    }
1595
1596    private void closeCamera() {
1597        if (mCameraDevice != null) {
1598            CameraHolder.instance().release();
1599            mCameraDevice.setZoomChangeListener(null);
1600            mCameraDevice = null;
1601            mPreviewing = false;
1602        }
1603    }
1604
1605    private void ensureCameraDevice() throws CameraHardwareException {
1606        if (mCameraDevice == null) {
1607            mCameraDevice = CameraHolder.instance().open(mCameraId);
1608            mInitialParams = mCameraDevice.getParameters();
1609        }
1610    }
1611
1612    private void updateLastImage() {
1613        IImageList list = ImageManager.makeImageList(
1614            mContentResolver,
1615            dataLocation(),
1616            ImageManager.INCLUDE_IMAGES,
1617            ImageManager.SORT_ASCENDING,
1618            ImageManager.CAMERA_IMAGE_BUCKET_ID);
1619        int count = list.getCount();
1620        if (count > 0) {
1621            IImage image = list.getImageAt(count - 1);
1622            Uri uri = image.fullSizeImageUri();
1623            mThumbController.setData(uri, image.miniThumbBitmap());
1624        } else {
1625            mThumbController.setData(null, null);
1626        }
1627        list.close();
1628    }
1629
1630    private void showCameraErrorAndFinish() {
1631        Resources ress = getResources();
1632        Util.showFatalErrorAndFinish(Camera.this,
1633                ress.getString(R.string.camera_error_title),
1634                ress.getString(R.string.cannot_connect_camera));
1635    }
1636
1637    private boolean restartPreview() {
1638        try {
1639            startPreview();
1640        } catch (CameraHardwareException e) {
1641            showCameraErrorAndFinish();
1642            return false;
1643        }
1644        return true;
1645    }
1646
1647    private void setPreviewDisplay(SurfaceHolder holder) {
1648        try {
1649            mCameraDevice.setPreviewDisplay(holder);
1650        } catch (Throwable ex) {
1651            closeCamera();
1652            throw new RuntimeException("setPreviewDisplay failed", ex);
1653        }
1654    }
1655
1656    private void startPreview() throws CameraHardwareException {
1657        if (mPausing || isFinishing()) return;
1658
1659        ensureCameraDevice();
1660
1661        // If we're previewing already, stop the preview first (this will blank
1662        // the screen).
1663        if (mPreviewing) stopPreview();
1664
1665        setPreviewDisplay(mSurfaceHolder);
1666        Util.setCameraDisplayOrientation(this, mCameraId, mCameraDevice);
1667        setCameraParameters(UPDATE_PARAM_ALL);
1668
1669        mCameraDevice.setErrorCallback(mErrorCallback);
1670
1671        try {
1672            Log.v(TAG, "startPreview");
1673            mCameraDevice.startPreview();
1674        } catch (Throwable ex) {
1675            closeCamera();
1676            throw new RuntimeException("startPreview failed", ex);
1677        }
1678        mPreviewing = true;
1679        mZoomState = ZOOM_STOPPED;
1680        mStatus = IDLE;
1681    }
1682
1683    private void stopPreview() {
1684        if (mCameraDevice != null && mPreviewing) {
1685            Log.v(TAG, "stopPreview");
1686            mCameraDevice.stopPreview();
1687        }
1688        mPreviewing = false;
1689        // If auto focus was in progress, it would have been canceled.
1690        clearFocusState();
1691    }
1692
1693    private Size getOptimalPreviewSize(List<Size> sizes, double targetRatio) {
1694        final double ASPECT_TOLERANCE = 0.05;
1695        if (sizes == null) return null;
1696
1697        Size optimalSize = null;
1698        double minDiff = Double.MAX_VALUE;
1699
1700        // Because of bugs of overlay and layout, we sometimes will try to
1701        // layout the viewfinder in the portrait orientation and thus get the
1702        // wrong size of mSurfaceView. When we change the preview size, the
1703        // new overlay will be created before the old one closed, which causes
1704        // an exception. For now, just get the screen size
1705
1706        Display display = getWindowManager().getDefaultDisplay();
1707        int targetHeight = Math.min(display.getHeight(), display.getWidth());
1708
1709        if (targetHeight <= 0) {
1710            // We don't know the size of SurefaceView, use screen height
1711            WindowManager windowManager = (WindowManager)
1712                    getSystemService(Context.WINDOW_SERVICE);
1713            targetHeight = windowManager.getDefaultDisplay().getHeight();
1714        }
1715
1716        // Try to find an size match aspect ratio and size
1717        for (Size size : sizes) {
1718            double ratio = (double) size.width / size.height;
1719            if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
1720            if (Math.abs(size.height - targetHeight) < minDiff) {
1721                optimalSize = size;
1722                minDiff = Math.abs(size.height - targetHeight);
1723            }
1724        }
1725
1726        // Cannot find the one match the aspect ratio, ignore the requirement
1727        if (optimalSize == null) {
1728            Log.v(TAG, "No preview size match the aspect ratio");
1729            minDiff = Double.MAX_VALUE;
1730            for (Size size : sizes) {
1731                if (Math.abs(size.height - targetHeight) < minDiff) {
1732                    optimalSize = size;
1733                    minDiff = Math.abs(size.height - targetHeight);
1734                }
1735            }
1736        }
1737        return optimalSize;
1738    }
1739
1740    private static boolean isSupported(String value, List<String> supported) {
1741        return supported == null ? false : supported.indexOf(value) >= 0;
1742    }
1743
1744    private void updateCameraParametersInitialize() {
1745        // Reset preview frame rate to the maximum because it may be lowered by
1746        // video camera application.
1747        List<Integer> frameRates = mParameters.getSupportedPreviewFrameRates();
1748        if (frameRates != null) {
1749            Integer max = Collections.max(frameRates);
1750            mParameters.setPreviewFrameRate(max);
1751        }
1752
1753    }
1754
1755    private void updateCameraParametersZoom() {
1756        // Set zoom.
1757        if (mParameters.isZoomSupported()) {
1758            mParameters.setZoom(mZoomValue);
1759        }
1760    }
1761
1762    private void updateCameraParametersPreference() {
1763        // Set picture size.
1764        String pictureSize = mPreferences.getString(
1765                CameraSettings.KEY_PICTURE_SIZE, null);
1766        if (pictureSize == null) {
1767            CameraSettings.initialCameraPictureSize(this, mParameters);
1768        } else {
1769            List<Size> supported = mParameters.getSupportedPictureSizes();
1770            CameraSettings.setCameraPictureSize(
1771                    pictureSize, supported, mParameters);
1772        }
1773
1774        // Set the preview frame aspect ratio according to the picture size.
1775        Size size = mParameters.getPictureSize();
1776        PreviewFrameLayout frameLayout =
1777                (PreviewFrameLayout) findViewById(R.id.frame_layout);
1778        frameLayout.setAspectRatio((double) size.width / size.height);
1779
1780        // Set a preview size that is closest to the viewfinder height and has
1781        // the right aspect ratio.
1782        List<Size> sizes = mParameters.getSupportedPreviewSizes();
1783        Size optimalSize = getOptimalPreviewSize(
1784                sizes, (double) size.width / size.height);
1785        if (optimalSize != null) {
1786            Size original = mParameters.getPreviewSize();
1787            if (!original.equals(optimalSize)) {
1788                mParameters.setPreviewSize(optimalSize.width, optimalSize.height);
1789
1790                // Zoom related settings will be changed for different preview
1791                // sizes, so set and read the parameters to get lastest values
1792                mCameraDevice.setParameters(mParameters);
1793                mParameters = mCameraDevice.getParameters();
1794            }
1795        }
1796
1797        // Since change scene mode may change supported values,
1798        // Set scene mode first,
1799        mSceneMode = mPreferences.getString(
1800                CameraSettings.KEY_SCENE_MODE,
1801                getString(R.string.pref_camera_scenemode_default));
1802        if (isSupported(mSceneMode, mParameters.getSupportedSceneModes())) {
1803            if (!mParameters.getSceneMode().equals(mSceneMode)) {
1804                mParameters.setSceneMode(mSceneMode);
1805                mCameraDevice.setParameters(mParameters);
1806
1807                // Setting scene mode will change the settings of flash mode,
1808                // white balance, and focus mode. Here we read back the
1809                // parameters, so we can know those settings.
1810                mParameters = mCameraDevice.getParameters();
1811            }
1812        } else {
1813            mSceneMode = mParameters.getSceneMode();
1814            if (mSceneMode == null) {
1815                mSceneMode = Parameters.SCENE_MODE_AUTO;
1816            }
1817        }
1818
1819        // Set JPEG quality.
1820        String jpegQuality = mPreferences.getString(
1821                CameraSettings.KEY_JPEG_QUALITY,
1822                getString(R.string.pref_camera_jpegquality_default));
1823        mParameters.setJpegQuality(JpegEncodingQualityMappings.getQualityNumber(jpegQuality));
1824
1825        // For the following settings, we need to check if the settings are
1826        // still supported by latest driver, if not, ignore the settings.
1827
1828        // Set color effect parameter.
1829        String colorEffect = mPreferences.getString(
1830                CameraSettings.KEY_COLOR_EFFECT,
1831                getString(R.string.pref_camera_coloreffect_default));
1832        if (isSupported(colorEffect, mParameters.getSupportedColorEffects())) {
1833            mParameters.setColorEffect(colorEffect);
1834        }
1835
1836        // Set exposure compensation
1837        String exposure = mPreferences.getString(
1838                CameraSettings.KEY_EXPOSURE,
1839                getString(R.string.pref_exposure_default));
1840        try {
1841            int value = Integer.parseInt(exposure);
1842            int max = mParameters.getMaxExposureCompensation();
1843            int min = mParameters.getMinExposureCompensation();
1844            if (value >= min && value <= max) {
1845                mParameters.setExposureCompensation(value);
1846            } else {
1847                Log.w(TAG, "invalid exposure range: " + exposure);
1848            }
1849        } catch (NumberFormatException e) {
1850            Log.w(TAG, "invalid exposure: " + exposure);
1851        }
1852
1853        if (mHeadUpDisplay != null) updateSceneModeInHud();
1854
1855        if (Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) {
1856            // Set flash mode.
1857            String flashMode = mPreferences.getString(
1858                    CameraSettings.KEY_FLASH_MODE,
1859                    getString(R.string.pref_camera_flashmode_default));
1860            List<String> supportedFlash = mParameters.getSupportedFlashModes();
1861            if (isSupported(flashMode, supportedFlash)) {
1862                mParameters.setFlashMode(flashMode);
1863            } else {
1864                flashMode = mParameters.getFlashMode();
1865                if (flashMode == null) {
1866                    flashMode = getString(
1867                            R.string.pref_camera_flashmode_no_flash);
1868                }
1869            }
1870
1871            // Set white balance parameter.
1872            String whiteBalance = mPreferences.getString(
1873                    CameraSettings.KEY_WHITE_BALANCE,
1874                    getString(R.string.pref_camera_whitebalance_default));
1875            if (isSupported(whiteBalance,
1876                    mParameters.getSupportedWhiteBalance())) {
1877                mParameters.setWhiteBalance(whiteBalance);
1878            } else {
1879                whiteBalance = mParameters.getWhiteBalance();
1880                if (whiteBalance == null) {
1881                    whiteBalance = Parameters.WHITE_BALANCE_AUTO;
1882                }
1883            }
1884
1885            // Set focus mode.
1886            mFocusMode = mPreferences.getString(
1887                    CameraSettings.KEY_FOCUS_MODE,
1888                    getString(R.string.pref_camera_focusmode_default));
1889            if (isSupported(mFocusMode, mParameters.getSupportedFocusModes())) {
1890                mParameters.setFocusMode(mFocusMode);
1891            } else {
1892                mFocusMode = mParameters.getFocusMode();
1893                if (mFocusMode == null) {
1894                    mFocusMode = Parameters.FOCUS_MODE_AUTO;
1895                }
1896            }
1897        } else {
1898            mFocusMode = mParameters.getFocusMode();
1899        }
1900    }
1901
1902    // We separate the parameters into several subsets, so we can update only
1903    // the subsets actually need updating. The PREFERENCE set needs extra
1904    // locking because the preference can be changed from GLThread as well.
1905    private void setCameraParameters(int updateSet) {
1906        mParameters = mCameraDevice.getParameters();
1907
1908        if ((updateSet & UPDATE_PARAM_INITIALIZE) != 0) {
1909            updateCameraParametersInitialize();
1910        }
1911
1912        if ((updateSet & UPDATE_PARAM_ZOOM) != 0) {
1913            updateCameraParametersZoom();
1914        }
1915
1916        if ((updateSet & UPDATE_PARAM_PREFERENCE) != 0) {
1917            updateCameraParametersPreference();
1918        }
1919
1920        mCameraDevice.setParameters(mParameters);
1921    }
1922
1923    // If the Camera is idle, update the parameters immediately, otherwise
1924    // accumulate them in mUpdateSet and update later.
1925    private void setCameraParametersWhenIdle(int additionalUpdateSet) {
1926        mUpdateSet |= additionalUpdateSet;
1927        if (mCameraDevice == null) {
1928            // We will update all the parameters when we open the device, so
1929            // we don't need to do anything now.
1930            mUpdateSet = 0;
1931            return;
1932        } else if (isCameraIdle()) {
1933            setCameraParameters(mUpdateSet);
1934            mUpdateSet = 0;
1935        } else {
1936            if (!mHandler.hasMessages(SET_CAMERA_PARAMETERS_WHEN_IDLE)) {
1937                mHandler.sendEmptyMessageDelayed(
1938                        SET_CAMERA_PARAMETERS_WHEN_IDLE, 1000);
1939            }
1940        }
1941    }
1942
1943    private void gotoGallery() {
1944        MenuHelper.gotoCameraImageGallery(this);
1945    }
1946
1947    private void viewLastImage() {
1948        if (mThumbController.isUriValid()) {
1949            Intent intent = new Intent(Util.REVIEW_ACTION, mThumbController.getUri());
1950            try {
1951                startActivity(intent);
1952            } catch (ActivityNotFoundException ex) {
1953                try {
1954                    intent = new Intent(Intent.ACTION_VIEW, mThumbController.getUri());
1955                    startActivity(intent);
1956                } catch (ActivityNotFoundException e) {
1957                    Log.e(TAG, "review image fail", e);
1958                }
1959            }
1960        } else {
1961            Log.e(TAG, "Can't view last image.");
1962        }
1963    }
1964
1965    private void startReceivingLocationUpdates() {
1966        if (mLocationManager != null) {
1967            try {
1968                mLocationManager.requestLocationUpdates(
1969                        LocationManager.NETWORK_PROVIDER,
1970                        1000,
1971                        0F,
1972                        mLocationListeners[1]);
1973            } catch (java.lang.SecurityException ex) {
1974                Log.i(TAG, "fail to request location update, ignore", ex);
1975            } catch (IllegalArgumentException ex) {
1976                Log.d(TAG, "provider does not exist " + ex.getMessage());
1977            }
1978            try {
1979                mLocationManager.requestLocationUpdates(
1980                        LocationManager.GPS_PROVIDER,
1981                        1000,
1982                        0F,
1983                        mLocationListeners[0]);
1984            } catch (java.lang.SecurityException ex) {
1985                Log.i(TAG, "fail to request location update, ignore", ex);
1986            } catch (IllegalArgumentException ex) {
1987                Log.d(TAG, "provider does not exist " + ex.getMessage());
1988            }
1989        }
1990    }
1991
1992    private void stopReceivingLocationUpdates() {
1993        if (mLocationManager != null) {
1994            for (int i = 0; i < mLocationListeners.length; i++) {
1995                try {
1996                    mLocationManager.removeUpdates(mLocationListeners[i]);
1997                } catch (Exception ex) {
1998                    Log.i(TAG, "fail to remove location listners, ignore", ex);
1999                }
2000            }
2001        }
2002    }
2003
2004    private Location getCurrentLocation() {
2005        // go in best to worst order
2006        for (int i = 0; i < mLocationListeners.length; i++) {
2007            Location l = mLocationListeners[i].current();
2008            if (l != null) return l;
2009        }
2010        return null;
2011    }
2012
2013    private boolean isCameraIdle() {
2014        return mStatus == IDLE && mFocusState == FOCUS_NOT_STARTED;
2015    }
2016
2017    private boolean isImageCaptureIntent() {
2018        String action = getIntent().getAction();
2019        return (MediaStore.ACTION_IMAGE_CAPTURE.equals(action));
2020    }
2021
2022    private void setupCaptureParams() {
2023        Bundle myExtras = getIntent().getExtras();
2024        if (myExtras != null) {
2025            mSaveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT);
2026            mCropValue = myExtras.getString("crop");
2027        }
2028    }
2029
2030    private void showPostCaptureAlert() {
2031        if (mIsImageCaptureIntent) {
2032            findViewById(R.id.shutter_button).setVisibility(View.INVISIBLE);
2033            int[] pickIds = {R.id.btn_retake, R.id.btn_done};
2034            for (int id : pickIds) {
2035                View button = findViewById(id);
2036                ((View) button.getParent()).setVisibility(View.VISIBLE);
2037            }
2038        }
2039    }
2040
2041    private void hidePostCaptureAlert() {
2042        if (mIsImageCaptureIntent) {
2043            findViewById(R.id.shutter_button).setVisibility(View.VISIBLE);
2044            int[] pickIds = {R.id.btn_retake, R.id.btn_done};
2045            for (int id : pickIds) {
2046                View button = findViewById(id);
2047                ((View) button.getParent()).setVisibility(View.GONE);
2048            }
2049        }
2050    }
2051
2052    private int calculatePicturesRemaining() {
2053        mPicturesRemaining = MenuHelper.calculatePicturesRemaining();
2054        return mPicturesRemaining;
2055    }
2056
2057    @Override
2058    public boolean onPrepareOptionsMenu(Menu menu) {
2059        super.onPrepareOptionsMenu(menu);
2060        // Only show the menu when camera is idle.
2061        for (int i = 0; i < menu.size(); i++) {
2062            menu.getItem(i).setVisible(isCameraIdle());
2063        }
2064
2065        return true;
2066    }
2067
2068    @Override
2069    public boolean onCreateOptionsMenu(Menu menu) {
2070        super.onCreateOptionsMenu(menu);
2071
2072        if (mIsImageCaptureIntent) {
2073            // No options menu for attach mode.
2074            return false;
2075        } else {
2076            addBaseMenuItems(menu);
2077        }
2078        return true;
2079    }
2080
2081    private void addBaseMenuItems(Menu menu) {
2082        MenuHelper.addSwitchModeMenuItem(menu, true, new Runnable() {
2083            public void run() {
2084                switchToVideoMode();
2085            }
2086        });
2087        MenuItem gallery = menu.add(Menu.NONE, Menu.NONE,
2088                MenuHelper.POSITION_GOTO_GALLERY,
2089                R.string.camera_gallery_photos_text)
2090                .setOnMenuItemClickListener(new OnMenuItemClickListener() {
2091            public boolean onMenuItemClick(MenuItem item) {
2092                gotoGallery();
2093                return true;
2094            }
2095        });
2096        gallery.setIcon(android.R.drawable.ic_menu_gallery);
2097        mGalleryItems.add(gallery);
2098
2099        if (mNumberOfCameras > 1) {
2100            menu.add(Menu.NONE, Menu.NONE,
2101                    MenuHelper.POSITION_SWITCH_CAMERA_ID,
2102                    R.string.switch_camera_id)
2103                    .setOnMenuItemClickListener(new OnMenuItemClickListener() {
2104                public boolean onMenuItemClick(MenuItem item) {
2105                    switchCameraId((mCameraId + 1) % mNumberOfCameras);
2106                    return true;
2107                }
2108            }).setIcon(android.R.drawable.ic_menu_camera);
2109        }
2110    }
2111
2112    private void switchCameraId(int cameraId) {
2113        if (mPausing || !isCameraIdle()) return;
2114        mCameraId = cameraId;
2115        CameraSettings.writePreferredCameraId(mPreferences, cameraId);
2116
2117        stopPreview();
2118        closeCamera();
2119
2120        // Remove the messages in the event queue.
2121        mHandler.removeMessages(RESTART_PREVIEW);
2122
2123        // Reset variables
2124        mJpegPictureCallbackTime = 0;
2125        mZoomValue = 0;
2126
2127        // Reload the preferences.
2128        mPreferences.setLocalId(this, mCameraId);
2129        CameraSettings.upgradeLocalPreferences(mPreferences.getLocal());
2130
2131        // Restart the preview.
2132        resetExposureCompensation();
2133        if (!restartPreview()) return;
2134
2135        initializeZoom();
2136
2137        // Reload the UI.
2138        if (mFirstTimeInitialized) {
2139            initializeHeadUpDisplay();
2140        }
2141    }
2142
2143    private boolean switchToVideoMode() {
2144        if (isFinishing() || !isCameraIdle()) return false;
2145        MenuHelper.gotoVideoMode(this);
2146        mHandler.removeMessages(FIRST_TIME_INIT);
2147        finish();
2148        return true;
2149    }
2150
2151    public boolean onSwitchChanged(Switcher source, boolean onOff) {
2152        if (onOff == SWITCH_VIDEO) {
2153            return switchToVideoMode();
2154        } else {
2155            return true;
2156        }
2157    }
2158
2159    private void onSharedPreferenceChanged() {
2160        // ignore the events after "onPause()"
2161        if (mPausing) return;
2162
2163        boolean recordLocation;
2164
2165        recordLocation = RecordLocationPreference.get(
2166                mPreferences, getContentResolver());
2167
2168        if (mRecordLocation != recordLocation) {
2169            mRecordLocation = recordLocation;
2170            if (mRecordLocation) {
2171                startReceivingLocationUpdates();
2172            } else {
2173                stopReceivingLocationUpdates();
2174            }
2175        }
2176        int cameraId = CameraSettings.readPreferredCameraId(mPreferences);
2177        if (mCameraId != cameraId) {
2178            switchCameraId(cameraId);
2179        } else {
2180            setCameraParametersWhenIdle(UPDATE_PARAM_PREFERENCE);
2181        }
2182    }
2183
2184    @Override
2185    public void onUserInteraction() {
2186        super.onUserInteraction();
2187        keepScreenOnAwhile();
2188    }
2189
2190    private void resetScreenOn() {
2191        mHandler.removeMessages(CLEAR_SCREEN_DELAY);
2192        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
2193    }
2194
2195    private void keepScreenOnAwhile() {
2196        mHandler.removeMessages(CLEAR_SCREEN_DELAY);
2197        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
2198        mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY);
2199    }
2200
2201    private class MyHeadUpDisplayListener implements HeadUpDisplay.Listener {
2202
2203        public void onSharedPreferencesChanged() {
2204            Camera.this.onSharedPreferenceChanged();
2205        }
2206
2207        public void onRestorePreferencesClicked() {
2208            Camera.this.onRestorePreferencesClicked();
2209        }
2210
2211        public void onPopupWindowVisibilityChanged(int visibility) {
2212        }
2213    }
2214
2215    protected void onRestorePreferencesClicked() {
2216        if (mPausing) return;
2217        Runnable runnable = new Runnable() {
2218            public void run() {
2219                mHeadUpDisplay.restorePreferences(mParameters);
2220            }
2221        };
2222        MenuHelper.confirmAction(this,
2223                getString(R.string.confirm_restore_title),
2224                getString(R.string.confirm_restore_message),
2225                runnable);
2226    }
2227}
2228
2229class FocusRectangle extends View {
2230
2231    @SuppressWarnings("unused")
2232    private static final String TAG = "FocusRectangle";
2233
2234    public FocusRectangle(Context context, AttributeSet attrs) {
2235        super(context, attrs);
2236    }
2237
2238    private void setDrawable(int resid) {
2239        setBackgroundDrawable(getResources().getDrawable(resid));
2240    }
2241
2242    public void showStart() {
2243        setDrawable(R.drawable.focus_focusing);
2244    }
2245
2246    public void showSuccess() {
2247        setDrawable(R.drawable.focus_focused);
2248    }
2249
2250    public void showFail() {
2251        setDrawable(R.drawable.focus_focus_failed);
2252    }
2253
2254    public void clear() {
2255        setBackgroundDrawable(null);
2256    }
2257}
2258
2259/*
2260 * Provide a mapping for Jpeg encoding quality levels
2261 * from String representation to numeric representation.
2262 */
2263class JpegEncodingQualityMappings {
2264    private static final String TAG = "JpegEncodingQualityMappings";
2265    private static final int DEFAULT_QUALITY = 85;
2266    private static HashMap<String, Integer> mHashMap =
2267            new HashMap<String, Integer>();
2268
2269    static {
2270        mHashMap.put("normal",    CameraProfile.QUALITY_LOW);
2271        mHashMap.put("fine",      CameraProfile.QUALITY_MEDIUM);
2272        mHashMap.put("superfine", CameraProfile.QUALITY_HIGH);
2273    }
2274
2275    // Retrieve and return the Jpeg encoding quality number
2276    // for the given quality level.
2277    public static int getQualityNumber(String jpegQuality) {
2278        Integer quality = mHashMap.get(jpegQuality);
2279        if (quality == null) {
2280            Log.w(TAG, "Unknown Jpeg quality: " + jpegQuality);
2281            return DEFAULT_QUALITY;
2282        }
2283        return CameraProfile.getJpegEncodingQualityParameter(quality.intValue());
2284    }
2285}
2286