Camera.java revision c6e3c7823339031096af937464cb528f53e045cf
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            // Set JPEG rotation to match the orientation of what users see. The
780            // rotation is relative to the orientation of the camera. The value
781            // from OrientationEventListener is relative to the natural
782            // orientation of the device. CameraInfo.mOrientation is the angle
783            // between camera orientation and natural device orientation. The
784            // sum of the two is the value for setRotation.
785            int rotation = 0;
786            if (mOrientation != OrientationEventListener.ORIENTATION_UNKNOWN) {
787                CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId];
788                rotation = (mOrientation + info.orientation) % 360;
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        } else {
1009            mHeadUpDisplay.setZoomListener(null);
1010        }
1011        updateSceneModeInHud();
1012    }
1013
1014    private void attachHeadUpDisplay() {
1015        mHeadUpDisplay.setOrientation(mOrientationCompensation);
1016        if (mParameters.isZoomSupported()) {
1017            mHeadUpDisplay.setZoomIndex(mZoomValue);
1018        }
1019        FrameLayout frame = (FrameLayout) findViewById(R.id.frame);
1020        mGLRootView = new GLRootView(this);
1021        mGLRootView.setContentPane(mHeadUpDisplay);
1022        frame.addView(mGLRootView);
1023    }
1024
1025    private void detachHeadUpDisplay() {
1026        mHeadUpDisplay.setGpsHasSignal(false);
1027        mHeadUpDisplay.collapse();
1028        ((ViewGroup) mGLRootView.getParent()).removeView(mGLRootView);
1029        mGLRootView = null;
1030    }
1031
1032    public static int roundOrientation(int orientation) {
1033        return ((orientation + 45) / 90 * 90) % 360;
1034    }
1035
1036    private class MyOrientationEventListener
1037            extends OrientationEventListener {
1038        public MyOrientationEventListener(Context context) {
1039            super(context);
1040        }
1041
1042        @Override
1043        public void onOrientationChanged(int orientation) {
1044            // We keep the last known orientation. So if the user first orient
1045            // the camera then point the camera to floor or sky, we still have
1046            // the correct orientation.
1047            if (orientation == ORIENTATION_UNKNOWN) return;
1048            orientation = roundOrientation(orientation);
1049            if (orientation != mOrientation) {
1050                mOrientation = orientation;
1051                mOrientationCompensation = orientation
1052                        + Util.getDisplayRotation(Camera.this);
1053
1054                if (!mIsImageCaptureIntent) {
1055                    setOrientationIndicator(mOrientationCompensation);
1056                }
1057                mHeadUpDisplay.setOrientation(mOrientationCompensation);
1058            }
1059        }
1060    }
1061
1062    private void setOrientationIndicator(int degree) {
1063        ((RotateImageView) findViewById(
1064                R.id.review_thumbnail)).setDegree(degree);
1065        ((RotateImageView) findViewById(
1066                R.id.camera_switch_icon)).setDegree(degree);
1067        ((RotateImageView) findViewById(
1068                R.id.video_switch_icon)).setDegree(degree);
1069    }
1070
1071    @Override
1072    public void onStart() {
1073        super.onStart();
1074        if (!mIsImageCaptureIntent) {
1075            mSwitcher.setSwitch(SWITCH_CAMERA);
1076        }
1077    }
1078
1079    @Override
1080    public void onStop() {
1081        super.onStop();
1082        if (mMediaProviderClient != null) {
1083            mMediaProviderClient.release();
1084            mMediaProviderClient = null;
1085        }
1086    }
1087
1088    private void checkStorage() {
1089        calculatePicturesRemaining();
1090        updateStorageHint(mPicturesRemaining);
1091    }
1092
1093    public void onClick(View v) {
1094        switch (v.getId()) {
1095            case R.id.btn_retake:
1096                hidePostCaptureAlert();
1097                restartPreview();
1098                break;
1099            case R.id.review_thumbnail:
1100                if (isCameraIdle()) {
1101                    viewLastImage();
1102                }
1103                break;
1104            case R.id.btn_done:
1105                doAttach();
1106                break;
1107            case R.id.btn_cancel:
1108                doCancel();
1109        }
1110    }
1111
1112    private Bitmap createCaptureBitmap(byte[] data) {
1113        // This is really stupid...we just want to read the orientation in
1114        // the jpeg header.
1115        String filepath = ImageManager.getTempJpegPath();
1116        int degree = 0;
1117        if (saveDataToFile(filepath, data)) {
1118            degree = ImageManager.getExifOrientation(filepath);
1119            new File(filepath).delete();
1120        }
1121
1122        // Limit to 50k pixels so we can return it in the intent.
1123        Bitmap bitmap = Util.makeBitmap(data, 50 * 1024);
1124        bitmap = Util.rotate(bitmap, degree);
1125        return bitmap;
1126    }
1127
1128    private void doAttach() {
1129        if (mPausing) {
1130            return;
1131        }
1132
1133        byte[] data = mImageCapture.getLastCaptureData();
1134
1135        if (mCropValue == null) {
1136            // First handle the no crop case -- just return the value.  If the
1137            // caller specifies a "save uri" then write the data to it's
1138            // stream. Otherwise, pass back a scaled down version of the bitmap
1139            // directly in the extras.
1140            if (mSaveUri != null) {
1141                OutputStream outputStream = null;
1142                try {
1143                    outputStream = mContentResolver.openOutputStream(mSaveUri);
1144                    outputStream.write(data);
1145                    outputStream.close();
1146
1147                    setResult(RESULT_OK);
1148                    finish();
1149                } catch (IOException ex) {
1150                    // ignore exception
1151                } finally {
1152                    Util.closeSilently(outputStream);
1153                }
1154            } else {
1155                Bitmap bitmap = createCaptureBitmap(data);
1156                setResult(RESULT_OK,
1157                        new Intent("inline-data").putExtra("data", bitmap));
1158                finish();
1159            }
1160        } else {
1161            // Save the image to a temp file and invoke the cropper
1162            Uri tempUri = null;
1163            FileOutputStream tempStream = null;
1164            try {
1165                File path = getFileStreamPath(sTempCropFilename);
1166                path.delete();
1167                tempStream = openFileOutput(sTempCropFilename, 0);
1168                tempStream.write(data);
1169                tempStream.close();
1170                tempUri = Uri.fromFile(path);
1171            } catch (FileNotFoundException ex) {
1172                setResult(Activity.RESULT_CANCELED);
1173                finish();
1174                return;
1175            } catch (IOException ex) {
1176                setResult(Activity.RESULT_CANCELED);
1177                finish();
1178                return;
1179            } finally {
1180                Util.closeSilently(tempStream);
1181            }
1182
1183            Bundle newExtras = new Bundle();
1184            if (mCropValue.equals("circle")) {
1185                newExtras.putString("circleCrop", "true");
1186            }
1187            if (mSaveUri != null) {
1188                newExtras.putParcelable(MediaStore.EXTRA_OUTPUT, mSaveUri);
1189            } else {
1190                newExtras.putBoolean("return-data", true);
1191            }
1192
1193            Intent cropIntent = new Intent("com.android.camera.action.CROP");
1194
1195            cropIntent.setData(tempUri);
1196            cropIntent.putExtras(newExtras);
1197
1198            startActivityForResult(cropIntent, CROP_MSG);
1199        }
1200    }
1201
1202    private void doCancel() {
1203        setResult(RESULT_CANCELED, new Intent());
1204        finish();
1205    }
1206
1207    public void onShutterButtonFocus(ShutterButton button, boolean pressed) {
1208        if (mPausing) {
1209            return;
1210        }
1211        switch (button.getId()) {
1212            case R.id.shutter_button:
1213                doFocus(pressed);
1214                break;
1215        }
1216    }
1217
1218    public void onShutterButtonClick(ShutterButton button) {
1219        if (mPausing) {
1220            return;
1221        }
1222        switch (button.getId()) {
1223            case R.id.shutter_button:
1224                doSnap();
1225                break;
1226        }
1227    }
1228
1229    private OnScreenHint mStorageHint;
1230
1231    private void updateStorageHint(int remaining) {
1232        String noStorageText = null;
1233
1234        if (remaining == MenuHelper.NO_STORAGE_ERROR) {
1235            String state = Environment.getExternalStorageState();
1236            if (state == Environment.MEDIA_CHECKING) {
1237                noStorageText = getString(R.string.preparing_sd);
1238            } else {
1239                noStorageText = getString(R.string.no_storage);
1240            }
1241        } else if (remaining == MenuHelper.CANNOT_STAT_ERROR) {
1242            noStorageText = getString(R.string.access_sd_fail);
1243        } else if (remaining < 1) {
1244            noStorageText = getString(R.string.not_enough_space);
1245        }
1246
1247        if (noStorageText != null) {
1248            if (mStorageHint == null) {
1249                mStorageHint = OnScreenHint.makeText(this, noStorageText);
1250            } else {
1251                mStorageHint.setText(noStorageText);
1252            }
1253            mStorageHint.show();
1254        } else if (mStorageHint != null) {
1255            mStorageHint.cancel();
1256            mStorageHint = null;
1257        }
1258    }
1259
1260    private void installIntentFilter() {
1261        // install an intent filter to receive SD card related events.
1262        IntentFilter intentFilter =
1263                new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);
1264        intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
1265        intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
1266        intentFilter.addAction(Intent.ACTION_MEDIA_CHECKING);
1267        intentFilter.addDataScheme("file");
1268        registerReceiver(mReceiver, intentFilter);
1269        mDidRegister = true;
1270    }
1271
1272    private void initializeFocusTone() {
1273        // Initialize focus tone generator.
1274        try {
1275            mFocusToneGenerator = new ToneGenerator(
1276                    AudioManager.STREAM_SYSTEM, FOCUS_BEEP_VOLUME);
1277        } catch (Throwable ex) {
1278            Log.w(TAG, "Exception caught while creating tone generator: ", ex);
1279            mFocusToneGenerator = null;
1280        }
1281    }
1282
1283    private void initializeScreenBrightness() {
1284        Window win = getWindow();
1285        // Overright the brightness settings if it is automatic
1286        int mode = Settings.System.getInt(
1287                getContentResolver(),
1288                Settings.System.SCREEN_BRIGHTNESS_MODE,
1289                Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
1290        if (mode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
1291            WindowManager.LayoutParams winParams = win.getAttributes();
1292            winParams.screenBrightness = DEFAULT_CAMERA_BRIGHTNESS;
1293            win.setAttributes(winParams);
1294        }
1295    }
1296
1297    @Override
1298    protected void onResume() {
1299        super.onResume();
1300
1301        mPausing = false;
1302        mJpegPictureCallbackTime = 0;
1303        mZoomValue = 0;
1304        mImageCapture = new ImageCapture();
1305
1306        // Start the preview if it is not started.
1307        if (!mPreviewing && !mStartPreviewFail) {
1308            resetExposureCompensation();
1309            if (!restartPreview()) return;
1310        }
1311
1312        if (mSurfaceHolder != null) {
1313            // If first time initialization is not finished, put it in the
1314            // message queue.
1315            if (!mFirstTimeInitialized) {
1316                mHandler.sendEmptyMessage(FIRST_TIME_INIT);
1317            } else {
1318                initializeSecondTime();
1319            }
1320        }
1321        keepScreenOnAwhile();
1322    }
1323
1324    @Override
1325    public void onConfigurationChanged(Configuration config) {
1326        super.onConfigurationChanged(config);
1327        changeHeadUpDisplayState();
1328    }
1329
1330    private static ImageManager.DataLocation dataLocation() {
1331        return ImageManager.DataLocation.EXTERNAL;
1332    }
1333
1334    @Override
1335    protected void onPause() {
1336        mPausing = true;
1337        stopPreview();
1338        // Close the camera now because other activities may need to use it.
1339        closeCamera();
1340        resetScreenOn();
1341        changeHeadUpDisplayState();
1342
1343        if (mFirstTimeInitialized) {
1344            mOrientationListener.disable();
1345            if (!mIsImageCaptureIntent) {
1346                mThumbController.storeData(
1347                        ImageManager.getLastImageThumbPath());
1348            }
1349            hidePostCaptureAlert();
1350        }
1351
1352        if (mDidRegister) {
1353            unregisterReceiver(mReceiver);
1354            mDidRegister = false;
1355        }
1356        stopReceivingLocationUpdates();
1357
1358        if (mFocusToneGenerator != null) {
1359            mFocusToneGenerator.release();
1360            mFocusToneGenerator = null;
1361        }
1362
1363        if (mStorageHint != null) {
1364            mStorageHint.cancel();
1365            mStorageHint = null;
1366        }
1367
1368        // If we are in an image capture intent and has taken
1369        // a picture, we just clear it in onPause.
1370        mImageCapture.clearLastData();
1371        mImageCapture = null;
1372
1373        // Remove the messages in the event queue.
1374        mHandler.removeMessages(RESTART_PREVIEW);
1375        mHandler.removeMessages(FIRST_TIME_INIT);
1376
1377        super.onPause();
1378    }
1379
1380    @Override
1381    protected void onActivityResult(
1382            int requestCode, int resultCode, Intent data) {
1383        switch (requestCode) {
1384            case CROP_MSG: {
1385                Intent intent = new Intent();
1386                if (data != null) {
1387                    Bundle extras = data.getExtras();
1388                    if (extras != null) {
1389                        intent.putExtras(extras);
1390                    }
1391                }
1392                setResult(resultCode, intent);
1393                finish();
1394
1395                File path = getFileStreamPath(sTempCropFilename);
1396                path.delete();
1397
1398                break;
1399            }
1400        }
1401    }
1402
1403    private boolean canTakePicture() {
1404        return isCameraIdle() && mPreviewing && (mPicturesRemaining > 0);
1405    }
1406
1407    private void autoFocus() {
1408        // Initiate autofocus only when preview is started and snapshot is not
1409        // in progress.
1410        if (canTakePicture()) {
1411            mHeadUpDisplay.setEnabled(false);
1412            Log.v(TAG, "Start autofocus.");
1413            mFocusStartTime = System.currentTimeMillis();
1414            mFocusState = FOCUSING;
1415            updateFocusIndicator();
1416            mCameraDevice.autoFocus(mAutoFocusCallback);
1417        }
1418    }
1419
1420    private void cancelAutoFocus() {
1421        // User releases half-pressed focus key.
1422        if (mStatus != SNAPSHOT_IN_PROGRESS && (mFocusState == FOCUSING
1423                || mFocusState == FOCUS_SUCCESS || mFocusState == FOCUS_FAIL)) {
1424            Log.v(TAG, "Cancel autofocus.");
1425            mHeadUpDisplay.setEnabled(true);
1426            mCameraDevice.cancelAutoFocus();
1427        }
1428        if (mFocusState != FOCUSING_SNAP_ON_FINISH) {
1429            clearFocusState();
1430        }
1431    }
1432
1433    private void clearFocusState() {
1434        mFocusState = FOCUS_NOT_STARTED;
1435        updateFocusIndicator();
1436    }
1437
1438    private void updateFocusIndicator() {
1439        if (mFocusRectangle == null) return;
1440
1441        if (mFocusState == FOCUSING || mFocusState == FOCUSING_SNAP_ON_FINISH) {
1442            mFocusRectangle.showStart();
1443        } else if (mFocusState == FOCUS_SUCCESS) {
1444            mFocusRectangle.showSuccess();
1445        } else if (mFocusState == FOCUS_FAIL) {
1446            mFocusRectangle.showFail();
1447        } else {
1448            mFocusRectangle.clear();
1449        }
1450    }
1451
1452    @Override
1453    public void onBackPressed() {
1454        if (!isCameraIdle()) {
1455            // ignore backs while we're taking a picture
1456            return;
1457        } else if (mHeadUpDisplay == null || !mHeadUpDisplay.collapse()) {
1458            super.onBackPressed();
1459        }
1460    }
1461
1462    @Override
1463    public boolean onKeyDown(int keyCode, KeyEvent event) {
1464        switch (keyCode) {
1465            case KeyEvent.KEYCODE_FOCUS:
1466                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1467                    doFocus(true);
1468                }
1469                return true;
1470            case KeyEvent.KEYCODE_CAMERA:
1471                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1472                    doSnap();
1473                }
1474                return true;
1475            case KeyEvent.KEYCODE_DPAD_CENTER:
1476                // If we get a dpad center event without any focused view, move
1477                // the focus to the shutter button and press it.
1478                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1479                    // Start auto-focus immediately to reduce shutter lag. After
1480                    // the shutter button gets the focus, doFocus() will be
1481                    // called again but it is fine.
1482                    if (mHeadUpDisplay.collapse()) return true;
1483                    doFocus(true);
1484                    if (mShutterButton.isInTouchMode()) {
1485                        mShutterButton.requestFocusFromTouch();
1486                    } else {
1487                        mShutterButton.requestFocus();
1488                    }
1489                    mShutterButton.setPressed(true);
1490                }
1491                return true;
1492        }
1493
1494        return super.onKeyDown(keyCode, event);
1495    }
1496
1497    @Override
1498    public boolean onKeyUp(int keyCode, KeyEvent event) {
1499        switch (keyCode) {
1500            case KeyEvent.KEYCODE_FOCUS:
1501                if (mFirstTimeInitialized) {
1502                    doFocus(false);
1503                }
1504                return true;
1505        }
1506        return super.onKeyUp(keyCode, event);
1507    }
1508
1509    private void doSnap() {
1510        if (mHeadUpDisplay.collapse()) return;
1511
1512        Log.v(TAG, "doSnap: mFocusState=" + mFocusState);
1513        // If the user has half-pressed the shutter and focus is completed, we
1514        // can take the photo right away. If the focus mode is infinity, we can
1515        // also take the photo.
1516        if (mFocusMode.equals(Parameters.FOCUS_MODE_INFINITY)
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            if (pressed) {  // Focus key down.
1535                autoFocus();
1536            } else {  // Focus key up.
1537                cancelAutoFocus();
1538            }
1539        }
1540    }
1541
1542    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
1543        // Make sure we have a surface in the holder before proceeding.
1544        if (holder.getSurface() == null) {
1545            Log.d(TAG, "holder.getSurface() == null");
1546            return;
1547        }
1548
1549        // We need to save the holder for later use, even when the mCameraDevice
1550        // is null. This could happen if onResume() is invoked after this
1551        // function.
1552        mSurfaceHolder = holder;
1553
1554        // The mCameraDevice will be null if it fails to connect to the camera
1555        // hardware. In this case we will show a dialog and then finish the
1556        // activity, so it's OK to ignore it.
1557        if (mCameraDevice == null) return;
1558
1559        // Sometimes surfaceChanged is called after onPause or before onResume.
1560        // Ignore it.
1561        if (mPausing || isFinishing()) return;
1562
1563        if (mPreviewing && holder.isCreating()) {
1564            // Set preview display if the surface is being created and preview
1565            // was already started. That means preview display was set to null
1566            // and we need to set it now.
1567            setPreviewDisplay(holder);
1568        } else {
1569            // 1. Restart the preview if the size of surface was changed. The
1570            // framework may not support changing preview display on the fly.
1571            // 2. Start the preview now if surface was destroyed and preview
1572            // stopped.
1573            restartPreview();
1574        }
1575
1576        // If first time initialization is not finished, send a message to do
1577        // it later. We want to finish surfaceChanged as soon as possible to let
1578        // user see preview first.
1579        if (!mFirstTimeInitialized) {
1580            mHandler.sendEmptyMessage(FIRST_TIME_INIT);
1581        } else {
1582            initializeSecondTime();
1583        }
1584    }
1585
1586    public void surfaceCreated(SurfaceHolder holder) {
1587    }
1588
1589    public void surfaceDestroyed(SurfaceHolder holder) {
1590        stopPreview();
1591        mSurfaceHolder = null;
1592    }
1593
1594    private void closeCamera() {
1595        if (mCameraDevice != null) {
1596            CameraHolder.instance().release();
1597            mCameraDevice.setZoomChangeListener(null);
1598            mCameraDevice = null;
1599            mPreviewing = false;
1600        }
1601    }
1602
1603    private void ensureCameraDevice() throws CameraHardwareException {
1604        if (mCameraDevice == null) {
1605            mCameraDevice = CameraHolder.instance().open(mCameraId);
1606            mInitialParams = mCameraDevice.getParameters();
1607        }
1608    }
1609
1610    private void updateLastImage() {
1611        IImageList list = ImageManager.makeImageList(
1612            mContentResolver,
1613            dataLocation(),
1614            ImageManager.INCLUDE_IMAGES,
1615            ImageManager.SORT_ASCENDING,
1616            ImageManager.CAMERA_IMAGE_BUCKET_ID);
1617        int count = list.getCount();
1618        if (count > 0) {
1619            IImage image = list.getImageAt(count - 1);
1620            Uri uri = image.fullSizeImageUri();
1621            mThumbController.setData(uri, image.miniThumbBitmap());
1622        } else {
1623            mThumbController.setData(null, null);
1624        }
1625        list.close();
1626    }
1627
1628    private void showCameraErrorAndFinish() {
1629        Resources ress = getResources();
1630        Util.showFatalErrorAndFinish(Camera.this,
1631                ress.getString(R.string.camera_error_title),
1632                ress.getString(R.string.cannot_connect_camera));
1633    }
1634
1635    private boolean restartPreview() {
1636        try {
1637            startPreview();
1638        } catch (CameraHardwareException e) {
1639            showCameraErrorAndFinish();
1640            return false;
1641        }
1642        return true;
1643    }
1644
1645    private void setPreviewDisplay(SurfaceHolder holder) {
1646        try {
1647            mCameraDevice.setPreviewDisplay(holder);
1648        } catch (Throwable ex) {
1649            closeCamera();
1650            throw new RuntimeException("setPreviewDisplay failed", ex);
1651        }
1652    }
1653
1654    private void startPreview() throws CameraHardwareException {
1655        if (mPausing || isFinishing()) return;
1656
1657        ensureCameraDevice();
1658
1659        // If we're previewing already, stop the preview first (this will blank
1660        // the screen).
1661        if (mPreviewing) stopPreview();
1662
1663        setPreviewDisplay(mSurfaceHolder);
1664        Util.setCameraDisplayOrientation(this, mCameraId, mCameraDevice);
1665        setCameraParameters(UPDATE_PARAM_ALL);
1666
1667        mCameraDevice.setErrorCallback(mErrorCallback);
1668
1669        try {
1670            Log.v(TAG, "startPreview");
1671            mCameraDevice.startPreview();
1672        } catch (Throwable ex) {
1673            closeCamera();
1674            throw new RuntimeException("startPreview failed", ex);
1675        }
1676        mPreviewing = true;
1677        mZoomState = ZOOM_STOPPED;
1678        mStatus = IDLE;
1679    }
1680
1681    private void stopPreview() {
1682        if (mCameraDevice != null && mPreviewing) {
1683            Log.v(TAG, "stopPreview");
1684            mCameraDevice.stopPreview();
1685        }
1686        mPreviewing = false;
1687        // If auto focus was in progress, it would have been canceled.
1688        clearFocusState();
1689    }
1690
1691    private Size getOptimalPreviewSize(List<Size> sizes, double targetRatio) {
1692        final double ASPECT_TOLERANCE = 0.05;
1693        if (sizes == null) return null;
1694
1695        Size optimalSize = null;
1696        double minDiff = Double.MAX_VALUE;
1697
1698        // Because of bugs of overlay and layout, we sometimes will try to
1699        // layout the viewfinder in the portrait orientation and thus get the
1700        // wrong size of mSurfaceView. When we change the preview size, the
1701        // new overlay will be created before the old one closed, which causes
1702        // an exception. For now, just get the screen size
1703
1704        Display display = getWindowManager().getDefaultDisplay();
1705        int targetHeight = Math.min(display.getHeight(), display.getWidth());
1706
1707        if (targetHeight <= 0) {
1708            // We don't know the size of SurefaceView, use screen height
1709            WindowManager windowManager = (WindowManager)
1710                    getSystemService(Context.WINDOW_SERVICE);
1711            targetHeight = windowManager.getDefaultDisplay().getHeight();
1712        }
1713
1714        // Try to find an size match aspect ratio and size
1715        for (Size size : sizes) {
1716            double ratio = (double) size.width / size.height;
1717            if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
1718            if (Math.abs(size.height - targetHeight) < minDiff) {
1719                optimalSize = size;
1720                minDiff = Math.abs(size.height - targetHeight);
1721            }
1722        }
1723
1724        // Cannot find the one match the aspect ratio, ignore the requirement
1725        if (optimalSize == null) {
1726            Log.v(TAG, "No preview size match the aspect ratio");
1727            minDiff = Double.MAX_VALUE;
1728            for (Size size : sizes) {
1729                if (Math.abs(size.height - targetHeight) < minDiff) {
1730                    optimalSize = size;
1731                    minDiff = Math.abs(size.height - targetHeight);
1732                }
1733            }
1734        }
1735        return optimalSize;
1736    }
1737
1738    private static boolean isSupported(String value, List<String> supported) {
1739        return supported == null ? false : supported.indexOf(value) >= 0;
1740    }
1741
1742    private void updateCameraParametersInitialize() {
1743        // Reset preview frame rate to the maximum because it may be lowered by
1744        // video camera application.
1745        List<Integer> frameRates = mParameters.getSupportedPreviewFrameRates();
1746        if (frameRates != null) {
1747            Integer max = Collections.max(frameRates);
1748            mParameters.setPreviewFrameRate(max);
1749        }
1750
1751    }
1752
1753    private void updateCameraParametersZoom() {
1754        // Set zoom.
1755        if (mParameters.isZoomSupported()) {
1756            mParameters.setZoom(mZoomValue);
1757        }
1758    }
1759
1760    private void updateCameraParametersPreference() {
1761        // Set picture size.
1762        String pictureSize = mPreferences.getString(
1763                CameraSettings.KEY_PICTURE_SIZE, null);
1764        if (pictureSize == null) {
1765            CameraSettings.initialCameraPictureSize(this, mParameters);
1766        } else {
1767            List<Size> supported = mParameters.getSupportedPictureSizes();
1768            CameraSettings.setCameraPictureSize(
1769                    pictureSize, supported, mParameters);
1770        }
1771
1772        // Set the preview frame aspect ratio according to the picture size.
1773        Size size = mParameters.getPictureSize();
1774        PreviewFrameLayout frameLayout =
1775                (PreviewFrameLayout) findViewById(R.id.frame_layout);
1776        frameLayout.setAspectRatio((double) size.width / size.height);
1777
1778        // Set a preview size that is closest to the viewfinder height and has
1779        // the right aspect ratio.
1780        List<Size> sizes = mParameters.getSupportedPreviewSizes();
1781        Size optimalSize = getOptimalPreviewSize(
1782                sizes, (double) size.width / size.height);
1783        if (optimalSize != null) {
1784            Size original = mParameters.getPreviewSize();
1785            if (!original.equals(optimalSize)) {
1786                mParameters.setPreviewSize(optimalSize.width, optimalSize.height);
1787
1788                // Zoom related settings will be changed for different preview
1789                // sizes, so set and read the parameters to get lastest values
1790                mCameraDevice.setParameters(mParameters);
1791                mParameters = mCameraDevice.getParameters();
1792            }
1793        }
1794
1795        // Since change scene mode may change supported values,
1796        // Set scene mode first,
1797        mSceneMode = mPreferences.getString(
1798                CameraSettings.KEY_SCENE_MODE,
1799                getString(R.string.pref_camera_scenemode_default));
1800        if (isSupported(mSceneMode, mParameters.getSupportedSceneModes())) {
1801            if (!mParameters.getSceneMode().equals(mSceneMode)) {
1802                mParameters.setSceneMode(mSceneMode);
1803                mCameraDevice.setParameters(mParameters);
1804
1805                // Setting scene mode will change the settings of flash mode,
1806                // white balance, and focus mode. Here we read back the
1807                // parameters, so we can know those settings.
1808                mParameters = mCameraDevice.getParameters();
1809            }
1810        } else {
1811            mSceneMode = mParameters.getSceneMode();
1812            if (mSceneMode == null) {
1813                mSceneMode = Parameters.SCENE_MODE_AUTO;
1814            }
1815        }
1816
1817        // Set JPEG quality.
1818        String jpegQuality = mPreferences.getString(
1819                CameraSettings.KEY_JPEG_QUALITY,
1820                getString(R.string.pref_camera_jpegquality_default));
1821        mParameters.setJpegQuality(JpegEncodingQualityMappings.getQualityNumber(jpegQuality));
1822
1823        // For the following settings, we need to check if the settings are
1824        // still supported by latest driver, if not, ignore the settings.
1825
1826        // Set color effect parameter.
1827        String colorEffect = mPreferences.getString(
1828                CameraSettings.KEY_COLOR_EFFECT,
1829                getString(R.string.pref_camera_coloreffect_default));
1830        if (isSupported(colorEffect, mParameters.getSupportedColorEffects())) {
1831            mParameters.setColorEffect(colorEffect);
1832        }
1833
1834        // Set exposure compensation
1835        String exposure = mPreferences.getString(
1836                CameraSettings.KEY_EXPOSURE,
1837                getString(R.string.pref_exposure_default));
1838        try {
1839            int value = Integer.parseInt(exposure);
1840            int max = mParameters.getMaxExposureCompensation();
1841            int min = mParameters.getMinExposureCompensation();
1842            if (value >= min && value <= max) {
1843                mParameters.setExposureCompensation(value);
1844            } else {
1845                Log.w(TAG, "invalid exposure range: " + exposure);
1846            }
1847        } catch (NumberFormatException e) {
1848            Log.w(TAG, "invalid exposure: " + exposure);
1849        }
1850
1851        if (mHeadUpDisplay != null) updateSceneModeInHud();
1852
1853        if (Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) {
1854            // Set flash mode.
1855            String flashMode = mPreferences.getString(
1856                    CameraSettings.KEY_FLASH_MODE,
1857                    getString(R.string.pref_camera_flashmode_default));
1858            List<String> supportedFlash = mParameters.getSupportedFlashModes();
1859            if (isSupported(flashMode, supportedFlash)) {
1860                mParameters.setFlashMode(flashMode);
1861            } else {
1862                flashMode = mParameters.getFlashMode();
1863                if (flashMode == null) {
1864                    flashMode = getString(
1865                            R.string.pref_camera_flashmode_no_flash);
1866                }
1867            }
1868
1869            // Set white balance parameter.
1870            String whiteBalance = mPreferences.getString(
1871                    CameraSettings.KEY_WHITE_BALANCE,
1872                    getString(R.string.pref_camera_whitebalance_default));
1873            if (isSupported(whiteBalance,
1874                    mParameters.getSupportedWhiteBalance())) {
1875                mParameters.setWhiteBalance(whiteBalance);
1876            } else {
1877                whiteBalance = mParameters.getWhiteBalance();
1878                if (whiteBalance == null) {
1879                    whiteBalance = Parameters.WHITE_BALANCE_AUTO;
1880                }
1881            }
1882
1883            // Set focus mode.
1884            mFocusMode = mPreferences.getString(
1885                    CameraSettings.KEY_FOCUS_MODE,
1886                    getString(R.string.pref_camera_focusmode_default));
1887            if (isSupported(mFocusMode, mParameters.getSupportedFocusModes())) {
1888                mParameters.setFocusMode(mFocusMode);
1889            } else {
1890                mFocusMode = mParameters.getFocusMode();
1891                if (mFocusMode == null) {
1892                    mFocusMode = Parameters.FOCUS_MODE_AUTO;
1893                }
1894            }
1895        } else {
1896            mFocusMode = mParameters.getFocusMode();
1897        }
1898    }
1899
1900    // We separate the parameters into several subsets, so we can update only
1901    // the subsets actually need updating. The PREFERENCE set needs extra
1902    // locking because the preference can be changed from GLThread as well.
1903    private void setCameraParameters(int updateSet) {
1904        mParameters = mCameraDevice.getParameters();
1905
1906        if ((updateSet & UPDATE_PARAM_INITIALIZE) != 0) {
1907            updateCameraParametersInitialize();
1908        }
1909
1910        if ((updateSet & UPDATE_PARAM_ZOOM) != 0) {
1911            updateCameraParametersZoom();
1912        }
1913
1914        if ((updateSet & UPDATE_PARAM_PREFERENCE) != 0) {
1915            updateCameraParametersPreference();
1916        }
1917
1918        mCameraDevice.setParameters(mParameters);
1919    }
1920
1921    // If the Camera is idle, update the parameters immediately, otherwise
1922    // accumulate them in mUpdateSet and update later.
1923    private void setCameraParametersWhenIdle(int additionalUpdateSet) {
1924        mUpdateSet |= additionalUpdateSet;
1925        if (mCameraDevice == null) {
1926            // We will update all the parameters when we open the device, so
1927            // we don't need to do anything now.
1928            mUpdateSet = 0;
1929            return;
1930        } else if (isCameraIdle()) {
1931            setCameraParameters(mUpdateSet);
1932            mUpdateSet = 0;
1933        } else {
1934            if (!mHandler.hasMessages(SET_CAMERA_PARAMETERS_WHEN_IDLE)) {
1935                mHandler.sendEmptyMessageDelayed(
1936                        SET_CAMERA_PARAMETERS_WHEN_IDLE, 1000);
1937            }
1938        }
1939    }
1940
1941    private void gotoGallery() {
1942        MenuHelper.gotoCameraImageGallery(this);
1943    }
1944
1945    private void viewLastImage() {
1946        if (mThumbController.isUriValid()) {
1947            Intent intent = new Intent(Util.REVIEW_ACTION, mThumbController.getUri());
1948            try {
1949                startActivity(intent);
1950            } catch (ActivityNotFoundException ex) {
1951                try {
1952                    intent = new Intent(Intent.ACTION_VIEW, mThumbController.getUri());
1953                    startActivity(intent);
1954                } catch (ActivityNotFoundException e) {
1955                    Log.e(TAG, "review image fail", e);
1956                }
1957            }
1958        } else {
1959            Log.e(TAG, "Can't view last image.");
1960        }
1961    }
1962
1963    private void startReceivingLocationUpdates() {
1964        if (mLocationManager != null) {
1965            try {
1966                mLocationManager.requestLocationUpdates(
1967                        LocationManager.NETWORK_PROVIDER,
1968                        1000,
1969                        0F,
1970                        mLocationListeners[1]);
1971            } catch (java.lang.SecurityException ex) {
1972                Log.i(TAG, "fail to request location update, ignore", ex);
1973            } catch (IllegalArgumentException ex) {
1974                Log.d(TAG, "provider does not exist " + ex.getMessage());
1975            }
1976            try {
1977                mLocationManager.requestLocationUpdates(
1978                        LocationManager.GPS_PROVIDER,
1979                        1000,
1980                        0F,
1981                        mLocationListeners[0]);
1982            } catch (java.lang.SecurityException ex) {
1983                Log.i(TAG, "fail to request location update, ignore", ex);
1984            } catch (IllegalArgumentException ex) {
1985                Log.d(TAG, "provider does not exist " + ex.getMessage());
1986            }
1987        }
1988    }
1989
1990    private void stopReceivingLocationUpdates() {
1991        if (mLocationManager != null) {
1992            for (int i = 0; i < mLocationListeners.length; i++) {
1993                try {
1994                    mLocationManager.removeUpdates(mLocationListeners[i]);
1995                } catch (Exception ex) {
1996                    Log.i(TAG, "fail to remove location listners, ignore", ex);
1997                }
1998            }
1999        }
2000    }
2001
2002    private Location getCurrentLocation() {
2003        // go in best to worst order
2004        for (int i = 0; i < mLocationListeners.length; i++) {
2005            Location l = mLocationListeners[i].current();
2006            if (l != null) return l;
2007        }
2008        return null;
2009    }
2010
2011    private boolean isCameraIdle() {
2012        return mStatus == IDLE && mFocusState == FOCUS_NOT_STARTED;
2013    }
2014
2015    private boolean isImageCaptureIntent() {
2016        String action = getIntent().getAction();
2017        return (MediaStore.ACTION_IMAGE_CAPTURE.equals(action));
2018    }
2019
2020    private void setupCaptureParams() {
2021        Bundle myExtras = getIntent().getExtras();
2022        if (myExtras != null) {
2023            mSaveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT);
2024            mCropValue = myExtras.getString("crop");
2025        }
2026    }
2027
2028    private void showPostCaptureAlert() {
2029        if (mIsImageCaptureIntent) {
2030            findViewById(R.id.shutter_button).setVisibility(View.INVISIBLE);
2031            int[] pickIds = {R.id.btn_retake, R.id.btn_done};
2032            for (int id : pickIds) {
2033                View button = findViewById(id);
2034                ((View) button.getParent()).setVisibility(View.VISIBLE);
2035            }
2036        }
2037    }
2038
2039    private void hidePostCaptureAlert() {
2040        if (mIsImageCaptureIntent) {
2041            findViewById(R.id.shutter_button).setVisibility(View.VISIBLE);
2042            int[] pickIds = {R.id.btn_retake, R.id.btn_done};
2043            for (int id : pickIds) {
2044                View button = findViewById(id);
2045                ((View) button.getParent()).setVisibility(View.GONE);
2046            }
2047        }
2048    }
2049
2050    private int calculatePicturesRemaining() {
2051        mPicturesRemaining = MenuHelper.calculatePicturesRemaining();
2052        return mPicturesRemaining;
2053    }
2054
2055    @Override
2056    public boolean onPrepareOptionsMenu(Menu menu) {
2057        super.onPrepareOptionsMenu(menu);
2058        // Only show the menu when camera is idle.
2059        for (int i = 0; i < menu.size(); i++) {
2060            menu.getItem(i).setVisible(isCameraIdle());
2061        }
2062
2063        return true;
2064    }
2065
2066    @Override
2067    public boolean onCreateOptionsMenu(Menu menu) {
2068        super.onCreateOptionsMenu(menu);
2069
2070        if (mIsImageCaptureIntent) {
2071            // No options menu for attach mode.
2072            return false;
2073        } else {
2074            addBaseMenuItems(menu);
2075        }
2076        return true;
2077    }
2078
2079    private void addBaseMenuItems(Menu menu) {
2080        MenuHelper.addSwitchModeMenuItem(menu, true, new Runnable() {
2081            public void run() {
2082                switchToVideoMode();
2083            }
2084        });
2085        MenuItem gallery = menu.add(Menu.NONE, Menu.NONE,
2086                MenuHelper.POSITION_GOTO_GALLERY,
2087                R.string.camera_gallery_photos_text)
2088                .setOnMenuItemClickListener(new OnMenuItemClickListener() {
2089            public boolean onMenuItemClick(MenuItem item) {
2090                gotoGallery();
2091                return true;
2092            }
2093        });
2094        gallery.setIcon(android.R.drawable.ic_menu_gallery);
2095        mGalleryItems.add(gallery);
2096
2097        if (mNumberOfCameras > 1) {
2098            menu.add(Menu.NONE, Menu.NONE,
2099                    MenuHelper.POSITION_SWITCH_CAMERA_ID,
2100                    R.string.switch_camera_id)
2101                    .setOnMenuItemClickListener(new OnMenuItemClickListener() {
2102                public boolean onMenuItemClick(MenuItem item) {
2103                    switchCameraId((mCameraId + 1) % mNumberOfCameras);
2104                    return true;
2105                }
2106            }).setIcon(android.R.drawable.ic_menu_camera);
2107        }
2108    }
2109
2110    private void switchCameraId(int cameraId) {
2111        if (mPausing || !isCameraIdle()) return;
2112        mCameraId = cameraId;
2113        CameraSettings.writePreferredCameraId(mPreferences, cameraId);
2114
2115        stopPreview();
2116        closeCamera();
2117
2118        // Remove the messages in the event queue.
2119        mHandler.removeMessages(RESTART_PREVIEW);
2120
2121        // Reset variables
2122        mJpegPictureCallbackTime = 0;
2123        mZoomValue = 0;
2124
2125        // Reload the preferences.
2126        mPreferences.setLocalId(this, mCameraId);
2127        CameraSettings.upgradeLocalPreferences(mPreferences.getLocal());
2128
2129        // Restart the preview.
2130        resetExposureCompensation();
2131        if (!restartPreview()) return;
2132
2133        initializeZoom();
2134
2135        // Reload the UI.
2136        if (mFirstTimeInitialized) {
2137            initializeHeadUpDisplay();
2138        }
2139    }
2140
2141    private boolean switchToVideoMode() {
2142        if (isFinishing() || !isCameraIdle()) return false;
2143        MenuHelper.gotoVideoMode(this);
2144        mHandler.removeMessages(FIRST_TIME_INIT);
2145        finish();
2146        return true;
2147    }
2148
2149    public boolean onSwitchChanged(Switcher source, boolean onOff) {
2150        if (onOff == SWITCH_VIDEO) {
2151            return switchToVideoMode();
2152        } else {
2153            return true;
2154        }
2155    }
2156
2157    private void onSharedPreferenceChanged() {
2158        // ignore the events after "onPause()"
2159        if (mPausing) return;
2160
2161        boolean recordLocation;
2162
2163        recordLocation = RecordLocationPreference.get(
2164                mPreferences, getContentResolver());
2165
2166        if (mRecordLocation != recordLocation) {
2167            mRecordLocation = recordLocation;
2168            if (mRecordLocation) {
2169                startReceivingLocationUpdates();
2170            } else {
2171                stopReceivingLocationUpdates();
2172            }
2173        }
2174        int cameraId = CameraSettings.readPreferredCameraId(mPreferences);
2175        if (mCameraId != cameraId) {
2176            switchCameraId(cameraId);
2177        } else {
2178            setCameraParametersWhenIdle(UPDATE_PARAM_PREFERENCE);
2179        }
2180    }
2181
2182    @Override
2183    public void onUserInteraction() {
2184        super.onUserInteraction();
2185        keepScreenOnAwhile();
2186    }
2187
2188    private void resetScreenOn() {
2189        mHandler.removeMessages(CLEAR_SCREEN_DELAY);
2190        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
2191    }
2192
2193    private void keepScreenOnAwhile() {
2194        mHandler.removeMessages(CLEAR_SCREEN_DELAY);
2195        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
2196        mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY);
2197    }
2198
2199    private class MyHeadUpDisplayListener implements HeadUpDisplay.Listener {
2200
2201        public void onSharedPreferencesChanged() {
2202            Camera.this.onSharedPreferenceChanged();
2203        }
2204
2205        public void onRestorePreferencesClicked() {
2206            Camera.this.onRestorePreferencesClicked();
2207        }
2208
2209        public void onPopupWindowVisibilityChanged(int visibility) {
2210        }
2211    }
2212
2213    protected void onRestorePreferencesClicked() {
2214        if (mPausing) return;
2215        Runnable runnable = new Runnable() {
2216            public void run() {
2217                mHeadUpDisplay.restorePreferences(mParameters);
2218            }
2219        };
2220        MenuHelper.confirmAction(this,
2221                getString(R.string.confirm_restore_title),
2222                getString(R.string.confirm_restore_message),
2223                runnable);
2224    }
2225}
2226
2227class FocusRectangle extends View {
2228
2229    @SuppressWarnings("unused")
2230    private static final String TAG = "FocusRectangle";
2231
2232    public FocusRectangle(Context context, AttributeSet attrs) {
2233        super(context, attrs);
2234    }
2235
2236    private void setDrawable(int resid) {
2237        setBackgroundDrawable(getResources().getDrawable(resid));
2238    }
2239
2240    public void showStart() {
2241        setDrawable(R.drawable.focus_focusing);
2242    }
2243
2244    public void showSuccess() {
2245        setDrawable(R.drawable.focus_focused);
2246    }
2247
2248    public void showFail() {
2249        setDrawable(R.drawable.focus_focus_failed);
2250    }
2251
2252    public void clear() {
2253        setBackgroundDrawable(null);
2254    }
2255}
2256
2257/*
2258 * Provide a mapping for Jpeg encoding quality levels
2259 * from String representation to numeric representation.
2260 */
2261class JpegEncodingQualityMappings {
2262    private static final String TAG = "JpegEncodingQualityMappings";
2263    private static final int DEFAULT_QUALITY = 85;
2264    private static HashMap<String, Integer> mHashMap =
2265            new HashMap<String, Integer>();
2266
2267    static {
2268        mHashMap.put("normal",    CameraProfile.QUALITY_LOW);
2269        mHashMap.put("fine",      CameraProfile.QUALITY_MEDIUM);
2270        mHashMap.put("superfine", CameraProfile.QUALITY_HIGH);
2271    }
2272
2273    // Retrieve and return the Jpeg encoding quality number
2274    // for the given quality level.
2275    public static int getQualityNumber(String jpegQuality) {
2276        Integer quality = mHashMap.get(jpegQuality);
2277        if (quality == null) {
2278            Log.w(TAG, "Unknown Jpeg quality: " + jpegQuality);
2279            return DEFAULT_QUALITY;
2280        }
2281        return CameraProfile.getJpegEncodingQualityParameter(quality.intValue());
2282    }
2283}
2284