Camera.java revision 068a2e745b284b33af161d629adb9b7839be32d1
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            Util.setCameraDisplayOrientation(this, mCameraId, mCameraDevice);
1584            mInitialParams = mCameraDevice.getParameters();
1585        }
1586    }
1587
1588    private void updateLastImage() {
1589        IImageList list = ImageManager.makeImageList(
1590            mContentResolver,
1591            dataLocation(),
1592            ImageManager.INCLUDE_IMAGES,
1593            ImageManager.SORT_ASCENDING,
1594            ImageManager.CAMERA_IMAGE_BUCKET_ID);
1595        int count = list.getCount();
1596        if (count > 0) {
1597            IImage image = list.getImageAt(count - 1);
1598            Uri uri = image.fullSizeImageUri();
1599            mThumbController.setData(uri, image.miniThumbBitmap());
1600        } else {
1601            mThumbController.setData(null, null);
1602        }
1603        list.close();
1604    }
1605
1606    private void showCameraErrorAndFinish() {
1607        Resources ress = getResources();
1608        Util.showFatalErrorAndFinish(Camera.this,
1609                ress.getString(R.string.camera_error_title),
1610                ress.getString(R.string.cannot_connect_camera));
1611    }
1612
1613    private boolean restartPreview() {
1614        try {
1615            startPreview();
1616        } catch (CameraHardwareException e) {
1617            showCameraErrorAndFinish();
1618            return false;
1619        }
1620        return true;
1621    }
1622
1623    private void setPreviewDisplay(SurfaceHolder holder) {
1624        try {
1625            mCameraDevice.setPreviewDisplay(holder);
1626        } catch (Throwable ex) {
1627            closeCamera();
1628            throw new RuntimeException("setPreviewDisplay failed", ex);
1629        }
1630    }
1631
1632    private void startPreview() throws CameraHardwareException {
1633        if (mPausing || isFinishing()) return;
1634
1635        ensureCameraDevice();
1636
1637        // If we're previewing already, stop the preview first (this will blank
1638        // the screen).
1639        if (mPreviewing) stopPreview();
1640
1641        setPreviewDisplay(mSurfaceHolder);
1642        setCameraParameters(UPDATE_PARAM_ALL);
1643
1644        final long wallTimeStart = SystemClock.elapsedRealtime();
1645        final long threadTimeStart = Debug.threadCpuTimeNanos();
1646
1647        mCameraDevice.setErrorCallback(mErrorCallback);
1648
1649        try {
1650            Log.v(TAG, "startPreview");
1651            mCameraDevice.startPreview();
1652        } catch (Throwable ex) {
1653            closeCamera();
1654            throw new RuntimeException("startPreview failed", ex);
1655        }
1656        mPreviewing = true;
1657        mZoomState = ZOOM_STOPPED;
1658        mStatus = IDLE;
1659    }
1660
1661    private void stopPreview() {
1662        if (mCameraDevice != null && mPreviewing) {
1663            Log.v(TAG, "stopPreview");
1664            mCameraDevice.stopPreview();
1665        }
1666        mPreviewing = false;
1667        // If auto focus was in progress, it would have been canceled.
1668        clearFocusState();
1669    }
1670
1671    private Size getOptimalPreviewSize(List<Size> sizes, double targetRatio) {
1672        final double ASPECT_TOLERANCE = 0.05;
1673        if (sizes == null) return null;
1674
1675        Size optimalSize = null;
1676        double minDiff = Double.MAX_VALUE;
1677
1678        // Because of bugs of overlay and layout, we sometimes will try to
1679        // layout the viewfinder in the portrait orientation and thus get the
1680        // wrong size of mSurfaceView. When we change the preview size, the
1681        // new overlay will be created before the old one closed, which causes
1682        // an exception. For now, just get the screen size
1683
1684        Display display = getWindowManager().getDefaultDisplay();
1685        int targetHeight = Math.min(display.getHeight(), display.getWidth());
1686
1687        if (targetHeight <= 0) {
1688            // We don't know the size of SurefaceView, use screen height
1689            WindowManager windowManager = (WindowManager)
1690                    getSystemService(Context.WINDOW_SERVICE);
1691            targetHeight = windowManager.getDefaultDisplay().getHeight();
1692        }
1693
1694        // Try to find an size match aspect ratio and size
1695        for (Size size : sizes) {
1696            double ratio = (double) size.width / size.height;
1697            if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
1698            if (Math.abs(size.height - targetHeight) < minDiff) {
1699                optimalSize = size;
1700                minDiff = Math.abs(size.height - targetHeight);
1701            }
1702        }
1703
1704        // Cannot find the one match the aspect ratio, ignore the requirement
1705        if (optimalSize == null) {
1706            Log.v(TAG, "No preview size match the aspect ratio");
1707            minDiff = Double.MAX_VALUE;
1708            for (Size size : sizes) {
1709                if (Math.abs(size.height - targetHeight) < minDiff) {
1710                    optimalSize = size;
1711                    minDiff = Math.abs(size.height - targetHeight);
1712                }
1713            }
1714        }
1715        return optimalSize;
1716    }
1717
1718    private static boolean isSupported(String value, List<String> supported) {
1719        return supported == null ? false : supported.indexOf(value) >= 0;
1720    }
1721
1722    private void updateCameraParametersInitialize() {
1723        // Reset preview frame rate to the maximum because it may be lowered by
1724        // video camera application.
1725        List<Integer> frameRates = mParameters.getSupportedPreviewFrameRates();
1726        if (frameRates != null) {
1727            Integer max = Collections.max(frameRates);
1728            mParameters.setPreviewFrameRate(max);
1729        }
1730
1731    }
1732
1733    private void updateCameraParametersZoom() {
1734        // Set zoom.
1735        if (mParameters.isZoomSupported()) {
1736            mParameters.setZoom(mZoomValue);
1737        }
1738    }
1739
1740    private void updateCameraParametersPreference() {
1741        // Set picture size.
1742        String pictureSize = mPreferences.getString(
1743                CameraSettings.KEY_PICTURE_SIZE, null);
1744        if (pictureSize == null) {
1745            CameraSettings.initialCameraPictureSize(this, mParameters);
1746        } else {
1747            List<Size> supported = mParameters.getSupportedPictureSizes();
1748            CameraSettings.setCameraPictureSize(
1749                    pictureSize, supported, mParameters);
1750        }
1751
1752        // Set the preview frame aspect ratio according to the picture size.
1753        Size size = mParameters.getPictureSize();
1754        PreviewFrameLayout frameLayout =
1755                (PreviewFrameLayout) findViewById(R.id.frame_layout);
1756        frameLayout.setAspectRatio((double) size.width / size.height);
1757
1758        // Set a preview size that is closest to the viewfinder height and has
1759        // the right aspect ratio.
1760        List<Size> sizes = mParameters.getSupportedPreviewSizes();
1761        Size optimalSize = getOptimalPreviewSize(
1762                sizes, (double) size.width / size.height);
1763        if (optimalSize != null) {
1764            Size original = mParameters.getPreviewSize();
1765            if (!original.equals(optimalSize)) {
1766                mParameters.setPreviewSize(optimalSize.width, optimalSize.height);
1767
1768                // Zoom related settings will be changed for different preview
1769                // sizes, so set and read the parameters to get lastest values
1770                mCameraDevice.setParameters(mParameters);
1771                mParameters = mCameraDevice.getParameters();
1772            }
1773        }
1774
1775        // Since change scene mode may change supported values,
1776        // Set scene mode first,
1777        mSceneMode = mPreferences.getString(
1778                CameraSettings.KEY_SCENE_MODE,
1779                getString(R.string.pref_camera_scenemode_default));
1780        if (isSupported(mSceneMode, mParameters.getSupportedSceneModes())) {
1781            if (!mParameters.getSceneMode().equals(mSceneMode)) {
1782                mParameters.setSceneMode(mSceneMode);
1783                mCameraDevice.setParameters(mParameters);
1784
1785                // Setting scene mode will change the settings of flash mode,
1786                // white balance, and focus mode. Here we read back the
1787                // parameters, so we can know those settings.
1788                mParameters = mCameraDevice.getParameters();
1789            }
1790        } else {
1791            mSceneMode = mParameters.getSceneMode();
1792            if (mSceneMode == null) {
1793                mSceneMode = Parameters.SCENE_MODE_AUTO;
1794            }
1795        }
1796
1797        // Set JPEG quality.
1798        String jpegQuality = mPreferences.getString(
1799                CameraSettings.KEY_JPEG_QUALITY,
1800                getString(R.string.pref_camera_jpegquality_default));
1801        mParameters.setJpegQuality(JpegEncodingQualityMappings.getQualityNumber(jpegQuality));
1802
1803        // For the following settings, we need to check if the settings are
1804        // still supported by latest driver, if not, ignore the settings.
1805
1806        // Set color effect parameter.
1807        String colorEffect = mPreferences.getString(
1808                CameraSettings.KEY_COLOR_EFFECT,
1809                getString(R.string.pref_camera_coloreffect_default));
1810        if (isSupported(colorEffect, mParameters.getSupportedColorEffects())) {
1811            mParameters.setColorEffect(colorEffect);
1812        }
1813
1814        // Set exposure compensation
1815        String exposure = mPreferences.getString(
1816                CameraSettings.KEY_EXPOSURE,
1817                getString(R.string.pref_exposure_default));
1818        try {
1819            int value = Integer.parseInt(exposure);
1820            int max = mParameters.getMaxExposureCompensation();
1821            int min = mParameters.getMinExposureCompensation();
1822            if (value >= min && value <= max) {
1823                mParameters.setExposureCompensation(value);
1824            } else {
1825                Log.w(TAG, "invalid exposure range: " + exposure);
1826            }
1827        } catch (NumberFormatException e) {
1828            Log.w(TAG, "invalid exposure: " + exposure);
1829        }
1830
1831        if (mGLRootView != null) updateSceneModeInHud();
1832
1833        if (Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) {
1834            // Set flash mode.
1835            String flashMode = mPreferences.getString(
1836                    CameraSettings.KEY_FLASH_MODE,
1837                    getString(R.string.pref_camera_flashmode_default));
1838            List<String> supportedFlash = mParameters.getSupportedFlashModes();
1839            if (isSupported(flashMode, supportedFlash)) {
1840                mParameters.setFlashMode(flashMode);
1841            } else {
1842                flashMode = mParameters.getFlashMode();
1843                if (flashMode == null) {
1844                    flashMode = getString(
1845                            R.string.pref_camera_flashmode_no_flash);
1846                }
1847            }
1848
1849            // Set white balance parameter.
1850            String whiteBalance = mPreferences.getString(
1851                    CameraSettings.KEY_WHITE_BALANCE,
1852                    getString(R.string.pref_camera_whitebalance_default));
1853            if (isSupported(whiteBalance,
1854                    mParameters.getSupportedWhiteBalance())) {
1855                mParameters.setWhiteBalance(whiteBalance);
1856            } else {
1857                whiteBalance = mParameters.getWhiteBalance();
1858                if (whiteBalance == null) {
1859                    whiteBalance = Parameters.WHITE_BALANCE_AUTO;
1860                }
1861            }
1862
1863            // Set focus mode.
1864            mFocusMode = mPreferences.getString(
1865                    CameraSettings.KEY_FOCUS_MODE,
1866                    getString(R.string.pref_camera_focusmode_default));
1867            if (isSupported(mFocusMode, mParameters.getSupportedFocusModes())) {
1868                mParameters.setFocusMode(mFocusMode);
1869            } else {
1870                mFocusMode = mParameters.getFocusMode();
1871                if (mFocusMode == null) {
1872                    mFocusMode = Parameters.FOCUS_MODE_AUTO;
1873                }
1874            }
1875        } else {
1876            mFocusMode = mParameters.getFocusMode();
1877        }
1878    }
1879
1880    // We separate the parameters into several subsets, so we can update only
1881    // the subsets actually need updating. The PREFERENCE set needs extra
1882    // locking because the preference can be changed from GLThread as well.
1883    private void setCameraParameters(int updateSet) {
1884        mParameters = mCameraDevice.getParameters();
1885
1886        if ((updateSet & UPDATE_PARAM_INITIALIZE) != 0) {
1887            updateCameraParametersInitialize();
1888        }
1889
1890        if ((updateSet & UPDATE_PARAM_ZOOM) != 0) {
1891            updateCameraParametersZoom();
1892        }
1893
1894        if ((updateSet & UPDATE_PARAM_PREFERENCE) != 0) {
1895            updateCameraParametersPreference();
1896        }
1897
1898        mCameraDevice.setParameters(mParameters);
1899    }
1900
1901    // If the Camera is idle, update the parameters immediately, otherwise
1902    // accumulate them in mUpdateSet and update later.
1903    private void setCameraParametersWhenIdle(int additionalUpdateSet) {
1904        mUpdateSet |= additionalUpdateSet;
1905        if (mCameraDevice == null) {
1906            // We will update all the parameters when we open the device, so
1907            // we don't need to do anything now.
1908            mUpdateSet = 0;
1909            return;
1910        } else if (isCameraIdle()) {
1911            setCameraParameters(mUpdateSet);
1912            mUpdateSet = 0;
1913        } else {
1914            if (!mHandler.hasMessages(SET_CAMERA_PARAMETERS_WHEN_IDLE)) {
1915                mHandler.sendEmptyMessageDelayed(
1916                        SET_CAMERA_PARAMETERS_WHEN_IDLE, 1000);
1917            }
1918        }
1919    }
1920
1921    private void gotoGallery() {
1922        MenuHelper.gotoCameraImageGallery(this);
1923    }
1924
1925    private void viewLastImage() {
1926        if (mThumbController.isUriValid()) {
1927            Intent intent = new Intent(Util.REVIEW_ACTION, mThumbController.getUri());
1928            try {
1929                startActivity(intent);
1930            } catch (ActivityNotFoundException ex) {
1931                Log.e(TAG, "review image fail", ex);
1932            }
1933        } else {
1934            Log.e(TAG, "Can't view last image.");
1935        }
1936    }
1937
1938    private void startReceivingLocationUpdates() {
1939        if (mLocationManager != null) {
1940            try {
1941                mLocationManager.requestLocationUpdates(
1942                        LocationManager.NETWORK_PROVIDER,
1943                        1000,
1944                        0F,
1945                        mLocationListeners[1]);
1946            } catch (java.lang.SecurityException ex) {
1947                Log.i(TAG, "fail to request location update, ignore", ex);
1948            } catch (IllegalArgumentException ex) {
1949                Log.d(TAG, "provider does not exist " + ex.getMessage());
1950            }
1951            try {
1952                mLocationManager.requestLocationUpdates(
1953                        LocationManager.GPS_PROVIDER,
1954                        1000,
1955                        0F,
1956                        mLocationListeners[0]);
1957            } catch (java.lang.SecurityException ex) {
1958                Log.i(TAG, "fail to request location update, ignore", ex);
1959            } catch (IllegalArgumentException ex) {
1960                Log.d(TAG, "provider does not exist " + ex.getMessage());
1961            }
1962        }
1963    }
1964
1965    private void stopReceivingLocationUpdates() {
1966        if (mLocationManager != null) {
1967            for (int i = 0; i < mLocationListeners.length; i++) {
1968                try {
1969                    mLocationManager.removeUpdates(mLocationListeners[i]);
1970                } catch (Exception ex) {
1971                    Log.i(TAG, "fail to remove location listners, ignore", ex);
1972                }
1973            }
1974        }
1975    }
1976
1977    private Location getCurrentLocation() {
1978        // go in best to worst order
1979        for (int i = 0; i < mLocationListeners.length; i++) {
1980            Location l = mLocationListeners[i].current();
1981            if (l != null) return l;
1982        }
1983        return null;
1984    }
1985
1986    private boolean isCameraIdle() {
1987        return mStatus == IDLE && mFocusState == FOCUS_NOT_STARTED;
1988    }
1989
1990    private boolean isImageCaptureIntent() {
1991        String action = getIntent().getAction();
1992        return (MediaStore.ACTION_IMAGE_CAPTURE.equals(action));
1993    }
1994
1995    private void setupCaptureParams() {
1996        Bundle myExtras = getIntent().getExtras();
1997        if (myExtras != null) {
1998            mSaveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT);
1999            mCropValue = myExtras.getString("crop");
2000        }
2001    }
2002
2003    private void showPostCaptureAlert() {
2004        if (mIsImageCaptureIntent) {
2005            findViewById(R.id.shutter_button).setVisibility(View.INVISIBLE);
2006            int[] pickIds = {R.id.btn_retake, R.id.btn_done};
2007            for (int id : pickIds) {
2008                View button = findViewById(id);
2009                ((View) button.getParent()).setVisibility(View.VISIBLE);
2010            }
2011        }
2012    }
2013
2014    private void hidePostCaptureAlert() {
2015        if (mIsImageCaptureIntent) {
2016            findViewById(R.id.shutter_button).setVisibility(View.VISIBLE);
2017            int[] pickIds = {R.id.btn_retake, R.id.btn_done};
2018            for (int id : pickIds) {
2019                View button = findViewById(id);
2020                ((View) button.getParent()).setVisibility(View.GONE);
2021            }
2022        }
2023    }
2024
2025    private int calculatePicturesRemaining() {
2026        mPicturesRemaining = MenuHelper.calculatePicturesRemaining();
2027        return mPicturesRemaining;
2028    }
2029
2030    @Override
2031    public boolean onPrepareOptionsMenu(Menu menu) {
2032        super.onPrepareOptionsMenu(menu);
2033        // Only show the menu when camera is idle.
2034        for (int i = 0; i < menu.size(); i++) {
2035            menu.getItem(i).setVisible(isCameraIdle());
2036        }
2037
2038        return true;
2039    }
2040
2041    @Override
2042    public boolean onCreateOptionsMenu(Menu menu) {
2043        super.onCreateOptionsMenu(menu);
2044
2045        if (mIsImageCaptureIntent) {
2046            // No options menu for attach mode.
2047            return false;
2048        } else {
2049            addBaseMenuItems(menu);
2050        }
2051        return true;
2052    }
2053
2054    private void addBaseMenuItems(Menu menu) {
2055        MenuHelper.addSwitchModeMenuItem(menu, true, new Runnable() {
2056            public void run() {
2057                switchToVideoMode();
2058            }
2059        });
2060        MenuItem gallery = menu.add(Menu.NONE, Menu.NONE,
2061                MenuHelper.POSITION_GOTO_GALLERY,
2062                R.string.camera_gallery_photos_text)
2063                .setOnMenuItemClickListener(new OnMenuItemClickListener() {
2064            public boolean onMenuItemClick(MenuItem item) {
2065                gotoGallery();
2066                return true;
2067            }
2068        });
2069        gallery.setIcon(android.R.drawable.ic_menu_gallery);
2070        mGalleryItems.add(gallery);
2071
2072        if (mNumberOfCameras > 1) {
2073            menu.add(Menu.NONE, Menu.NONE,
2074                    MenuHelper.POSITION_SWITCH_CAMERA_ID,
2075                    R.string.switch_camera_id)
2076                    .setOnMenuItemClickListener(new OnMenuItemClickListener() {
2077                public boolean onMenuItemClick(MenuItem item) {
2078                    switchCameraId();
2079                    return true;
2080                }
2081            }).setIcon(android.R.drawable.ic_menu_camera);
2082        }
2083    }
2084
2085    private void switchCameraId() {
2086        mSwitching = true;
2087
2088        mCameraId = (mCameraId + 1) % mNumberOfCameras;
2089        CameraSettings.writePreferredCameraId(mPreferences, mCameraId);
2090
2091        stopPreview();
2092        closeCamera();
2093        changeHeadUpDisplayState();
2094
2095        // Remove the messages in the event queue.
2096        mHandler.removeMessages(RESTART_PREVIEW);
2097
2098        // Reset variables
2099        mJpegPictureCallbackTime = 0;
2100        mZoomValue = 0;
2101
2102        // Reload the preferences.
2103        mPreferences.setLocalId(this, mCameraId);
2104        CameraSettings.upgradeLocalPreferences(mPreferences.getLocal());
2105
2106
2107        // Restart the preview.
2108        resetExposureCompensation();
2109        if (!restartPreview()) return;
2110
2111        initializeZoom();
2112
2113        // Reload the UI.
2114        if (mFirstTimeInitialized) {
2115            initializeHeadUpDisplay();
2116        }
2117
2118        mSwitching = false;
2119        changeHeadUpDisplayState();
2120    }
2121
2122    private boolean switchToVideoMode() {
2123        if (isFinishing() || !isCameraIdle()) return false;
2124        MenuHelper.gotoVideoMode(this);
2125        mHandler.removeMessages(FIRST_TIME_INIT);
2126        finish();
2127        return true;
2128    }
2129
2130    public boolean onSwitchChanged(Switcher source, boolean onOff) {
2131        if (onOff == SWITCH_VIDEO) {
2132            return switchToVideoMode();
2133        } else {
2134            return true;
2135        }
2136    }
2137
2138    private void onSharedPreferenceChanged() {
2139        // ignore the events after "onPause()"
2140        if (mPausing) return;
2141
2142        boolean recordLocation;
2143
2144        recordLocation = RecordLocationPreference.get(
2145                mPreferences, getContentResolver());
2146        mQuickCapture = getQuickCaptureSettings();
2147
2148        if (mRecordLocation != recordLocation) {
2149            mRecordLocation = recordLocation;
2150            if (mRecordLocation) {
2151                startReceivingLocationUpdates();
2152            } else {
2153                stopReceivingLocationUpdates();
2154            }
2155        }
2156
2157        setCameraParametersWhenIdle(UPDATE_PARAM_PREFERENCE);
2158    }
2159
2160    private boolean getQuickCaptureSettings() {
2161        String value = mPreferences.getString(
2162                CameraSettings.KEY_QUICK_CAPTURE,
2163                getString(R.string.pref_camera_quickcapture_default));
2164        return CameraSettings.QUICK_CAPTURE_ON.equals(value);
2165    }
2166
2167    @Override
2168    public void onUserInteraction() {
2169        super.onUserInteraction();
2170        keepScreenOnAwhile();
2171    }
2172
2173    private void resetScreenOn() {
2174        mHandler.removeMessages(CLEAR_SCREEN_DELAY);
2175        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
2176    }
2177
2178    private void keepScreenOnAwhile() {
2179        mHandler.removeMessages(CLEAR_SCREEN_DELAY);
2180        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
2181        mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY);
2182    }
2183
2184    private class MyHeadUpDisplayListener implements HeadUpDisplay.Listener {
2185
2186        public void onSharedPreferencesChanged() {
2187            Camera.this.onSharedPreferenceChanged();
2188        }
2189
2190        public void onRestorePreferencesClicked() {
2191            Camera.this.onRestorePreferencesClicked();
2192        }
2193
2194        public void onPopupWindowVisibilityChanged(int visibility) {
2195        }
2196    }
2197
2198    protected void onRestorePreferencesClicked() {
2199        if (mPausing) return;
2200        Runnable runnable = new Runnable() {
2201            public void run() {
2202                mHeadUpDisplay.restorePreferences(mParameters);
2203            }
2204        };
2205        MenuHelper.confirmAction(this,
2206                getString(R.string.confirm_restore_title),
2207                getString(R.string.confirm_restore_message),
2208                runnable);
2209    }
2210}
2211
2212class FocusRectangle extends View {
2213
2214    @SuppressWarnings("unused")
2215    private static final String TAG = "FocusRectangle";
2216
2217    public FocusRectangle(Context context, AttributeSet attrs) {
2218        super(context, attrs);
2219    }
2220
2221    private void setDrawable(int resid) {
2222        setBackgroundDrawable(getResources().getDrawable(resid));
2223    }
2224
2225    public void showStart() {
2226        setDrawable(R.drawable.focus_focusing);
2227    }
2228
2229    public void showSuccess() {
2230        setDrawable(R.drawable.focus_focused);
2231    }
2232
2233    public void showFail() {
2234        setDrawable(R.drawable.focus_focus_failed);
2235    }
2236
2237    public void clear() {
2238        setBackgroundDrawable(null);
2239    }
2240}
2241
2242/*
2243 * Provide a mapping for Jpeg encoding quality levels
2244 * from String representation to numeric representation.
2245 */
2246class JpegEncodingQualityMappings {
2247    private static final String TAG = "JpegEncodingQualityMappings";
2248    private static final int DEFAULT_QUALITY = 85;
2249    private static HashMap<String, Integer> mHashMap =
2250            new HashMap<String, Integer>();
2251
2252    static {
2253        mHashMap.put("normal",    CameraProfile.QUALITY_LOW);
2254        mHashMap.put("fine",      CameraProfile.QUALITY_MEDIUM);
2255        mHashMap.put("superfine", CameraProfile.QUALITY_HIGH);
2256    }
2257
2258    // Retrieve and return the Jpeg encoding quality number
2259    // for the given quality level.
2260    public static int getQualityNumber(String jpegQuality) {
2261        Integer quality = mHashMap.get(jpegQuality);
2262        if (quality == null) {
2263            Log.w(TAG, "Unknown Jpeg quality: " + jpegQuality);
2264            return DEFAULT_QUALITY;
2265        }
2266        return CameraProfile.getJpegEncodingQualityParameter(quality.intValue());
2267    }
2268}
2269