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