Camera.java revision 1ef634d277d550ed55b5b7089dfd56ed71815bd6
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            try {
1287                startPreview();
1288            } catch (CameraHardwareException e) {
1289                showCameraErrorAndFinish();
1290                return;
1291            }
1292        }
1293
1294        if (mSurfaceHolder != null) {
1295            // If first time initialization is not finished, put it in the
1296            // message queue.
1297            if (!mFirstTimeInitialized) {
1298                mHandler.sendEmptyMessage(FIRST_TIME_INIT);
1299            } else {
1300                initializeSecondTime();
1301            }
1302        }
1303        keepScreenOnAwhile();
1304    }
1305
1306    @Override
1307    public void onConfigurationChanged(Configuration config) {
1308        super.onConfigurationChanged(config);
1309        changeHeadUpDisplayState();
1310    }
1311
1312    private static ImageManager.DataLocation dataLocation() {
1313        return ImageManager.DataLocation.EXTERNAL;
1314    }
1315
1316    @Override
1317    protected void onPause() {
1318        mPausing = true;
1319        stopPreview();
1320        // Close the camera now because other activities may need to use it.
1321        closeCamera();
1322        resetScreenOn();
1323        changeHeadUpDisplayState();
1324
1325        if (mFirstTimeInitialized) {
1326            mOrientationListener.disable();
1327            if (!mIsImageCaptureIntent) {
1328                mThumbController.storeData(
1329                        ImageManager.getLastImageThumbPath());
1330            }
1331            hidePostCaptureAlert();
1332        }
1333
1334        if (mDidRegister) {
1335            unregisterReceiver(mReceiver);
1336            mDidRegister = false;
1337        }
1338        stopReceivingLocationUpdates();
1339
1340        if (mFocusToneGenerator != null) {
1341            mFocusToneGenerator.release();
1342            mFocusToneGenerator = null;
1343        }
1344
1345        if (mStorageHint != null) {
1346            mStorageHint.cancel();
1347            mStorageHint = null;
1348        }
1349
1350        // If we are in an image capture intent and has taken
1351        // a picture, we just clear it in onPause.
1352        mImageCapture.clearLastData();
1353        mImageCapture = null;
1354
1355        // Remove the messages in the event queue.
1356        mHandler.removeMessages(RESTART_PREVIEW);
1357        mHandler.removeMessages(FIRST_TIME_INIT);
1358
1359        super.onPause();
1360    }
1361
1362    @Override
1363    protected void onActivityResult(
1364            int requestCode, int resultCode, Intent data) {
1365        switch (requestCode) {
1366            case CROP_MSG: {
1367                Intent intent = new Intent();
1368                if (data != null) {
1369                    Bundle extras = data.getExtras();
1370                    if (extras != null) {
1371                        intent.putExtras(extras);
1372                    }
1373                }
1374                setResult(resultCode, intent);
1375                finish();
1376
1377                File path = getFileStreamPath(sTempCropFilename);
1378                path.delete();
1379
1380                break;
1381            }
1382        }
1383    }
1384
1385    private boolean canTakePicture() {
1386        return isCameraIdle() && mPreviewing && (mPicturesRemaining > 0);
1387    }
1388
1389    private void autoFocus() {
1390        // Initiate autofocus only when preview is started and snapshot is not
1391        // in progress.
1392        if (canTakePicture()) {
1393            mHeadUpDisplay.setEnabled(false);
1394            Log.v(TAG, "Start autofocus.");
1395            mFocusStartTime = System.currentTimeMillis();
1396            mFocusState = FOCUSING;
1397            updateFocusIndicator();
1398            mCameraDevice.autoFocus(mAutoFocusCallback);
1399        }
1400    }
1401
1402    private void cancelAutoFocus() {
1403        // User releases half-pressed focus key.
1404        if (mFocusState == FOCUSING || mFocusState == FOCUS_SUCCESS
1405                || mFocusState == FOCUS_FAIL) {
1406            Log.v(TAG, "Cancel autofocus.");
1407            mHeadUpDisplay.setEnabled(true);
1408            mCameraDevice.cancelAutoFocus();
1409        }
1410        if (mFocusState != FOCUSING_SNAP_ON_FINISH) {
1411            clearFocusState();
1412        }
1413    }
1414
1415    private void clearFocusState() {
1416        mFocusState = FOCUS_NOT_STARTED;
1417        updateFocusIndicator();
1418    }
1419
1420    private void updateFocusIndicator() {
1421        if (mFocusRectangle == null) return;
1422
1423        if (mFocusState == FOCUSING || mFocusState == FOCUSING_SNAP_ON_FINISH) {
1424            mFocusRectangle.showStart();
1425        } else if (mFocusState == FOCUS_SUCCESS) {
1426            mFocusRectangle.showSuccess();
1427        } else if (mFocusState == FOCUS_FAIL) {
1428            mFocusRectangle.showFail();
1429        } else {
1430            mFocusRectangle.clear();
1431        }
1432    }
1433
1434    @Override
1435    public void onBackPressed() {
1436        if (!isCameraIdle()) {
1437            // ignore backs while we're taking a picture
1438            return;
1439        } else if (mHeadUpDisplay == null || !mHeadUpDisplay.collapse()) {
1440            super.onBackPressed();
1441        }
1442    }
1443
1444    @Override
1445    public boolean onKeyDown(int keyCode, KeyEvent event) {
1446        switch (keyCode) {
1447            case KeyEvent.KEYCODE_FOCUS:
1448                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1449                    doFocus(true);
1450                }
1451                return true;
1452            case KeyEvent.KEYCODE_CAMERA:
1453                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1454                    doSnap();
1455                }
1456                return true;
1457            case KeyEvent.KEYCODE_DPAD_CENTER:
1458                // If we get a dpad center event without any focused view, move
1459                // the focus to the shutter button and press it.
1460                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1461                    // Start auto-focus immediately to reduce shutter lag. After
1462                    // the shutter button gets the focus, doFocus() will be
1463                    // called again but it is fine.
1464                    if (mHeadUpDisplay.collapse()) return true;
1465                    doFocus(true);
1466                    if (mShutterButton.isInTouchMode()) {
1467                        mShutterButton.requestFocusFromTouch();
1468                    } else {
1469                        mShutterButton.requestFocus();
1470                    }
1471                    mShutterButton.setPressed(true);
1472                }
1473                return true;
1474        }
1475
1476        return super.onKeyDown(keyCode, event);
1477    }
1478
1479    @Override
1480    public boolean onKeyUp(int keyCode, KeyEvent event) {
1481        switch (keyCode) {
1482            case KeyEvent.KEYCODE_FOCUS:
1483                if (mFirstTimeInitialized) {
1484                    doFocus(false);
1485                }
1486                return true;
1487        }
1488        return super.onKeyUp(keyCode, event);
1489    }
1490
1491    private void doSnap() {
1492        if (mHeadUpDisplay.collapse()) return;
1493
1494        Log.v(TAG, "doSnap: mFocusState=" + mFocusState);
1495        // If the user has half-pressed the shutter and focus is completed, we
1496        // can take the photo right away. If the focus mode is infinity, we can
1497        // also take the photo.
1498        if (mFocusMode.equals(Parameters.FOCUS_MODE_INFINITY)
1499                || (mFocusState == FOCUS_SUCCESS
1500                || mFocusState == FOCUS_FAIL)) {
1501            mImageCapture.onSnap();
1502        } else if (mFocusState == FOCUSING) {
1503            // Half pressing the shutter (i.e. the focus button event) will
1504            // already have requested AF for us, so just request capture on
1505            // focus here.
1506            mFocusState = FOCUSING_SNAP_ON_FINISH;
1507        } else if (mFocusState == FOCUS_NOT_STARTED) {
1508            // Focus key down event is dropped for some reasons. Just ignore.
1509        }
1510    }
1511
1512    private void doFocus(boolean pressed) {
1513        // Do the focus if the mode is not infinity.
1514        if (mHeadUpDisplay.collapse()) return;
1515        if (!mFocusMode.equals(Parameters.FOCUS_MODE_INFINITY)) {
1516            if (pressed) {  // Focus key down.
1517                autoFocus();
1518            } else {  // Focus key up.
1519                cancelAutoFocus();
1520            }
1521        }
1522    }
1523
1524    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
1525        // Make sure we have a surface in the holder before proceeding.
1526        if (holder.getSurface() == null) {
1527            Log.d(TAG, "holder.getSurface() == null");
1528            return;
1529        }
1530
1531        // We need to save the holder for later use, even when the mCameraDevice
1532        // is null. This could happen if onResume() is invoked after this
1533        // function.
1534        mSurfaceHolder = holder;
1535
1536        // The mCameraDevice will be null if it fails to connect to the camera
1537        // hardware. In this case we will show a dialog and then finish the
1538        // activity, so it's OK to ignore it.
1539        if (mCameraDevice == null) return;
1540
1541        // Sometimes surfaceChanged is called after onPause or before onResume.
1542        // Ignore it.
1543        if (mPausing || isFinishing()) return;
1544
1545        if (mPreviewing && holder.isCreating()) {
1546            // Set preview display if the surface is being created and preview
1547            // was already started. That means preview display was set to null
1548            // and we need to set it now.
1549            setPreviewDisplay(holder);
1550        } else {
1551            // 1. Restart the preview if the size of surface was changed. The
1552            // framework may not support changing preview display on the fly.
1553            // 2. Start the preview now if surface was destroyed and preview
1554            // stopped.
1555            restartPreview();
1556        }
1557
1558        // If first time initialization is not finished, send a message to do
1559        // it later. We want to finish surfaceChanged as soon as possible to let
1560        // user see preview first.
1561        if (!mFirstTimeInitialized) {
1562            mHandler.sendEmptyMessage(FIRST_TIME_INIT);
1563        } else {
1564            initializeSecondTime();
1565        }
1566    }
1567
1568    public void surfaceCreated(SurfaceHolder holder) {
1569    }
1570
1571    public void surfaceDestroyed(SurfaceHolder holder) {
1572        stopPreview();
1573        mSurfaceHolder = null;
1574    }
1575
1576    private void closeCamera() {
1577        if (mCameraDevice != null) {
1578            CameraHolder.instance().release();
1579            mCameraDevice.setZoomChangeListener(null);
1580            mCameraDevice = null;
1581            mPreviewing = false;
1582        }
1583    }
1584
1585    private void ensureCameraDevice() throws CameraHardwareException {
1586        if (mCameraDevice == null) {
1587            mCameraDevice = CameraHolder.instance().open(mCameraId);
1588            Util.setCameraDisplayOrientation(this, mCameraId, mCameraDevice);
1589            mInitialParams = mCameraDevice.getParameters();
1590        }
1591    }
1592
1593    private void updateLastImage() {
1594        IImageList list = ImageManager.makeImageList(
1595            mContentResolver,
1596            dataLocation(),
1597            ImageManager.INCLUDE_IMAGES,
1598            ImageManager.SORT_ASCENDING,
1599            ImageManager.CAMERA_IMAGE_BUCKET_ID);
1600        int count = list.getCount();
1601        if (count > 0) {
1602            IImage image = list.getImageAt(count - 1);
1603            Uri uri = image.fullSizeImageUri();
1604            mThumbController.setData(uri, image.miniThumbBitmap());
1605        } else {
1606            mThumbController.setData(null, null);
1607        }
1608        list.close();
1609    }
1610
1611    private void showCameraErrorAndFinish() {
1612        Resources ress = getResources();
1613        Util.showFatalErrorAndFinish(Camera.this,
1614                ress.getString(R.string.camera_error_title),
1615                ress.getString(R.string.cannot_connect_camera));
1616    }
1617
1618    private void restartPreview() {
1619        try {
1620            startPreview();
1621        } catch (CameraHardwareException e) {
1622            showCameraErrorAndFinish();
1623            return;
1624        }
1625    }
1626
1627    private void setPreviewDisplay(SurfaceHolder holder) {
1628        try {
1629            mCameraDevice.setPreviewDisplay(holder);
1630        } catch (Throwable ex) {
1631            closeCamera();
1632            throw new RuntimeException("setPreviewDisplay failed", ex);
1633        }
1634    }
1635
1636    private void startPreview() throws CameraHardwareException {
1637        if (mPausing || isFinishing()) return;
1638
1639        ensureCameraDevice();
1640
1641        // If we're previewing already, stop the preview first (this will blank
1642        // the screen).
1643        if (mPreviewing) stopPreview();
1644
1645        setPreviewDisplay(mSurfaceHolder);
1646        setCameraParameters(UPDATE_PARAM_ALL);
1647
1648        final long wallTimeStart = SystemClock.elapsedRealtime();
1649        final long threadTimeStart = Debug.threadCpuTimeNanos();
1650
1651        mCameraDevice.setErrorCallback(mErrorCallback);
1652
1653        try {
1654            Log.v(TAG, "startPreview");
1655            mCameraDevice.startPreview();
1656        } catch (Throwable ex) {
1657            closeCamera();
1658            throw new RuntimeException("startPreview failed", ex);
1659        }
1660        mPreviewing = true;
1661        mZoomState = ZOOM_STOPPED;
1662        mStatus = IDLE;
1663    }
1664
1665    private void stopPreview() {
1666        if (mCameraDevice != null && mPreviewing) {
1667            Log.v(TAG, "stopPreview");
1668            mCameraDevice.stopPreview();
1669        }
1670        mPreviewing = false;
1671        // If auto focus was in progress, it would have been canceled.
1672        clearFocusState();
1673    }
1674
1675    private Size getOptimalPreviewSize(List<Size> sizes, double targetRatio) {
1676        final double ASPECT_TOLERANCE = 0.05;
1677        if (sizes == null) return null;
1678
1679        Size optimalSize = null;
1680        double minDiff = Double.MAX_VALUE;
1681
1682        // Because of bugs of overlay and layout, we sometimes will try to
1683        // layout the viewfinder in the portrait orientation and thus get the
1684        // wrong size of mSurfaceView. When we change the preview size, the
1685        // new overlay will be created before the old one closed, which causes
1686        // an exception. For now, just get the screen size
1687
1688        Display display = getWindowManager().getDefaultDisplay();
1689        int targetHeight = Math.min(display.getHeight(), display.getWidth());
1690
1691        if (targetHeight <= 0) {
1692            // We don't know the size of SurefaceView, use screen height
1693            WindowManager windowManager = (WindowManager)
1694                    getSystemService(Context.WINDOW_SERVICE);
1695            targetHeight = windowManager.getDefaultDisplay().getHeight();
1696        }
1697
1698        // Try to find an size match aspect ratio and size
1699        for (Size size : sizes) {
1700            double ratio = (double) size.width / size.height;
1701            if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
1702            if (Math.abs(size.height - targetHeight) < minDiff) {
1703                optimalSize = size;
1704                minDiff = Math.abs(size.height - targetHeight);
1705            }
1706        }
1707
1708        // Cannot find the one match the aspect ratio, ignore the requirement
1709        if (optimalSize == null) {
1710            Log.v(TAG, "No preview size match the aspect ratio");
1711            minDiff = Double.MAX_VALUE;
1712            for (Size size : sizes) {
1713                if (Math.abs(size.height - targetHeight) < minDiff) {
1714                    optimalSize = size;
1715                    minDiff = Math.abs(size.height - targetHeight);
1716                }
1717            }
1718        }
1719        return optimalSize;
1720    }
1721
1722    private static boolean isSupported(String value, List<String> supported) {
1723        return supported == null ? false : supported.indexOf(value) >= 0;
1724    }
1725
1726    private void updateCameraParametersInitialize() {
1727        // Reset preview frame rate to the maximum because it may be lowered by
1728        // video camera application.
1729        List<Integer> frameRates = mParameters.getSupportedPreviewFrameRates();
1730        if (frameRates != null) {
1731            Integer max = Collections.max(frameRates);
1732            mParameters.setPreviewFrameRate(max);
1733        }
1734
1735    }
1736
1737    private void updateCameraParametersZoom() {
1738        // Set zoom.
1739        if (mParameters.isZoomSupported()) {
1740            mParameters.setZoom(mZoomValue);
1741        }
1742    }
1743
1744    private void updateCameraParametersPreference() {
1745        // Set picture size.
1746        String pictureSize = mPreferences.getString(
1747                CameraSettings.KEY_PICTURE_SIZE, null);
1748        if (pictureSize == null) {
1749            CameraSettings.initialCameraPictureSize(this, mParameters);
1750        } else {
1751            List<Size> supported = mParameters.getSupportedPictureSizes();
1752            CameraSettings.setCameraPictureSize(
1753                    pictureSize, supported, mParameters);
1754        }
1755
1756        // Set the preview frame aspect ratio according to the picture size.
1757        Size size = mParameters.getPictureSize();
1758        PreviewFrameLayout frameLayout =
1759                (PreviewFrameLayout) findViewById(R.id.frame_layout);
1760        frameLayout.setAspectRatio((double) size.width / size.height);
1761
1762        // Set a preview size that is closest to the viewfinder height and has
1763        // the right aspect ratio.
1764        List<Size> sizes = mParameters.getSupportedPreviewSizes();
1765        Size optimalSize = getOptimalPreviewSize(
1766                sizes, (double) size.width / size.height);
1767        if (optimalSize != null) {
1768            Size original = mParameters.getPreviewSize();
1769            if (!original.equals(optimalSize)) {
1770                mParameters.setPreviewSize(optimalSize.width, optimalSize.height);
1771
1772                // Zoom related settings will be changed for different preview
1773                // sizes, so set and read the parameters to get lastest values
1774                mCameraDevice.setParameters(mParameters);
1775                mParameters = mCameraDevice.getParameters();
1776            }
1777        }
1778
1779        // Since change scene mode may change supported values,
1780        // Set scene mode first,
1781        mSceneMode = mPreferences.getString(
1782                CameraSettings.KEY_SCENE_MODE,
1783                getString(R.string.pref_camera_scenemode_default));
1784        if (isSupported(mSceneMode, mParameters.getSupportedSceneModes())) {
1785            if (!mParameters.getSceneMode().equals(mSceneMode)) {
1786                mParameters.setSceneMode(mSceneMode);
1787                mCameraDevice.setParameters(mParameters);
1788
1789                // Setting scene mode will change the settings of flash mode,
1790                // white balance, and focus mode. Here we read back the
1791                // parameters, so we can know those settings.
1792                mParameters = mCameraDevice.getParameters();
1793            }
1794        } else {
1795            mSceneMode = mParameters.getSceneMode();
1796            if (mSceneMode == null) {
1797                mSceneMode = Parameters.SCENE_MODE_AUTO;
1798            }
1799        }
1800
1801        // Set JPEG quality.
1802        String jpegQuality = mPreferences.getString(
1803                CameraSettings.KEY_JPEG_QUALITY,
1804                getString(R.string.pref_camera_jpegquality_default));
1805        mParameters.setJpegQuality(JpegEncodingQualityMappings.getQualityNumber(jpegQuality));
1806
1807        // For the following settings, we need to check if the settings are
1808        // still supported by latest driver, if not, ignore the settings.
1809
1810        // Set color effect parameter.
1811        String colorEffect = mPreferences.getString(
1812                CameraSettings.KEY_COLOR_EFFECT,
1813                getString(R.string.pref_camera_coloreffect_default));
1814        if (isSupported(colorEffect, mParameters.getSupportedColorEffects())) {
1815            mParameters.setColorEffect(colorEffect);
1816        }
1817
1818        // Set exposure compensation
1819        String exposure = mPreferences.getString(
1820                CameraSettings.KEY_EXPOSURE,
1821                getString(R.string.pref_exposure_default));
1822        try {
1823            int value = Integer.parseInt(exposure);
1824            int max = mParameters.getMaxExposureCompensation();
1825            int min = mParameters.getMinExposureCompensation();
1826            if (value >= min && value <= max) {
1827                mParameters.setExposureCompensation(value);
1828            } else {
1829                Log.w(TAG, "invalid exposure range: " + exposure);
1830            }
1831        } catch (NumberFormatException e) {
1832            Log.w(TAG, "invalid exposure: " + exposure);
1833        }
1834
1835        if (mGLRootView != null) updateSceneModeInHud();
1836
1837        if (Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) {
1838            // Set flash mode.
1839            String flashMode = mPreferences.getString(
1840                    CameraSettings.KEY_FLASH_MODE,
1841                    getString(R.string.pref_camera_flashmode_default));
1842            List<String> supportedFlash = mParameters.getSupportedFlashModes();
1843            if (isSupported(flashMode, supportedFlash)) {
1844                mParameters.setFlashMode(flashMode);
1845            } else {
1846                flashMode = mParameters.getFlashMode();
1847                if (flashMode == null) {
1848                    flashMode = getString(
1849                            R.string.pref_camera_flashmode_no_flash);
1850                }
1851            }
1852
1853            // Set white balance parameter.
1854            String whiteBalance = mPreferences.getString(
1855                    CameraSettings.KEY_WHITE_BALANCE,
1856                    getString(R.string.pref_camera_whitebalance_default));
1857            if (isSupported(whiteBalance,
1858                    mParameters.getSupportedWhiteBalance())) {
1859                mParameters.setWhiteBalance(whiteBalance);
1860            } else {
1861                whiteBalance = mParameters.getWhiteBalance();
1862                if (whiteBalance == null) {
1863                    whiteBalance = Parameters.WHITE_BALANCE_AUTO;
1864                }
1865            }
1866
1867            // Set focus mode.
1868            mFocusMode = mPreferences.getString(
1869                    CameraSettings.KEY_FOCUS_MODE,
1870                    getString(R.string.pref_camera_focusmode_default));
1871            if (isSupported(mFocusMode, mParameters.getSupportedFocusModes())) {
1872                mParameters.setFocusMode(mFocusMode);
1873            } else {
1874                mFocusMode = mParameters.getFocusMode();
1875                if (mFocusMode == null) {
1876                    mFocusMode = Parameters.FOCUS_MODE_AUTO;
1877                }
1878            }
1879        } else {
1880            mFocusMode = mParameters.getFocusMode();
1881        }
1882
1883        // Set metering mode parameter.
1884        String meteringMode = mPreferences.getString(
1885                CameraSettings.KEY_METERING_MODE,
1886                getString(R.string.pref_camera_meteringmode_default));
1887        if (isSupported(meteringMode, mParameters.getSupportedMeteringModes())) {
1888            mParameters.setMeteringMode(meteringMode);
1889        }
1890    }
1891
1892    // We separate the parameters into several subsets, so we can update only
1893    // the subsets actually need updating. The PREFERENCE set needs extra
1894    // locking because the preference can be changed from GLThread as well.
1895    private void setCameraParameters(int updateSet) {
1896        mParameters = mCameraDevice.getParameters();
1897
1898        if ((updateSet & UPDATE_PARAM_INITIALIZE) != 0) {
1899            updateCameraParametersInitialize();
1900        }
1901
1902        if ((updateSet & UPDATE_PARAM_ZOOM) != 0) {
1903            updateCameraParametersZoom();
1904        }
1905
1906        if ((updateSet & UPDATE_PARAM_PREFERENCE) != 0) {
1907            updateCameraParametersPreference();
1908        }
1909
1910        mCameraDevice.setParameters(mParameters);
1911    }
1912
1913    // If the Camera is idle, update the parameters immediately, otherwise
1914    // accumulate them in mUpdateSet and update later.
1915    private void setCameraParametersWhenIdle(int additionalUpdateSet) {
1916        mUpdateSet |= additionalUpdateSet;
1917        if (mCameraDevice == null) {
1918            // We will update all the parameters when we open the device, so
1919            // we don't need to do anything now.
1920            mUpdateSet = 0;
1921            return;
1922        } else if (isCameraIdle()) {
1923            setCameraParameters(mUpdateSet);
1924            mUpdateSet = 0;
1925        } else {
1926            if (!mHandler.hasMessages(SET_CAMERA_PARAMETERS_WHEN_IDLE)) {
1927                mHandler.sendEmptyMessageDelayed(
1928                        SET_CAMERA_PARAMETERS_WHEN_IDLE, 1000);
1929            }
1930        }
1931    }
1932
1933    private void gotoGallery() {
1934        MenuHelper.gotoCameraImageGallery(this);
1935    }
1936
1937    private void viewLastImage() {
1938        if (mThumbController.isUriValid()) {
1939            Intent intent = new Intent(Util.REVIEW_ACTION, mThumbController.getUri());
1940            try {
1941                startActivity(intent);
1942            } catch (ActivityNotFoundException ex) {
1943                Log.e(TAG, "review image fail", ex);
1944            }
1945        } else {
1946            Log.e(TAG, "Can't view last image.");
1947        }
1948    }
1949
1950    private void startReceivingLocationUpdates() {
1951        if (mLocationManager != null) {
1952            try {
1953                mLocationManager.requestLocationUpdates(
1954                        LocationManager.NETWORK_PROVIDER,
1955                        1000,
1956                        0F,
1957                        mLocationListeners[1]);
1958            } catch (java.lang.SecurityException ex) {
1959                Log.i(TAG, "fail to request location update, ignore", ex);
1960            } catch (IllegalArgumentException ex) {
1961                Log.d(TAG, "provider does not exist " + ex.getMessage());
1962            }
1963            try {
1964                mLocationManager.requestLocationUpdates(
1965                        LocationManager.GPS_PROVIDER,
1966                        1000,
1967                        0F,
1968                        mLocationListeners[0]);
1969            } catch (java.lang.SecurityException ex) {
1970                Log.i(TAG, "fail to request location update, ignore", ex);
1971            } catch (IllegalArgumentException ex) {
1972                Log.d(TAG, "provider does not exist " + ex.getMessage());
1973            }
1974        }
1975    }
1976
1977    private void stopReceivingLocationUpdates() {
1978        if (mLocationManager != null) {
1979            for (int i = 0; i < mLocationListeners.length; i++) {
1980                try {
1981                    mLocationManager.removeUpdates(mLocationListeners[i]);
1982                } catch (Exception ex) {
1983                    Log.i(TAG, "fail to remove location listners, ignore", ex);
1984                }
1985            }
1986        }
1987    }
1988
1989    private Location getCurrentLocation() {
1990        // go in best to worst order
1991        for (int i = 0; i < mLocationListeners.length; i++) {
1992            Location l = mLocationListeners[i].current();
1993            if (l != null) return l;
1994        }
1995        return null;
1996    }
1997
1998    private boolean isCameraIdle() {
1999        return mStatus == IDLE && mFocusState == FOCUS_NOT_STARTED;
2000    }
2001
2002    private boolean isImageCaptureIntent() {
2003        String action = getIntent().getAction();
2004        return (MediaStore.ACTION_IMAGE_CAPTURE.equals(action));
2005    }
2006
2007    private void setupCaptureParams() {
2008        Bundle myExtras = getIntent().getExtras();
2009        if (myExtras != null) {
2010            mSaveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT);
2011            mCropValue = myExtras.getString("crop");
2012        }
2013    }
2014
2015    private void showPostCaptureAlert() {
2016        if (mIsImageCaptureIntent) {
2017            findViewById(R.id.shutter_button).setVisibility(View.INVISIBLE);
2018            int[] pickIds = {R.id.btn_retake, R.id.btn_done};
2019            for (int id : pickIds) {
2020                View button = findViewById(id);
2021                ((View) button.getParent()).setVisibility(View.VISIBLE);
2022            }
2023        }
2024    }
2025
2026    private void hidePostCaptureAlert() {
2027        if (mIsImageCaptureIntent) {
2028            findViewById(R.id.shutter_button).setVisibility(View.VISIBLE);
2029            int[] pickIds = {R.id.btn_retake, R.id.btn_done};
2030            for (int id : pickIds) {
2031                View button = findViewById(id);
2032                ((View) button.getParent()).setVisibility(View.GONE);
2033            }
2034        }
2035    }
2036
2037    private int calculatePicturesRemaining() {
2038        mPicturesRemaining = MenuHelper.calculatePicturesRemaining();
2039        return mPicturesRemaining;
2040    }
2041
2042    @Override
2043    public boolean onPrepareOptionsMenu(Menu menu) {
2044        super.onPrepareOptionsMenu(menu);
2045        // Only show the menu when camera is idle.
2046        for (int i = 0; i < menu.size(); i++) {
2047            menu.getItem(i).setVisible(isCameraIdle());
2048        }
2049
2050        return true;
2051    }
2052
2053    @Override
2054    public boolean onCreateOptionsMenu(Menu menu) {
2055        super.onCreateOptionsMenu(menu);
2056
2057        if (mIsImageCaptureIntent) {
2058            // No options menu for attach mode.
2059            return false;
2060        } else {
2061            addBaseMenuItems(menu);
2062        }
2063        return true;
2064    }
2065
2066    private void addBaseMenuItems(Menu menu) {
2067        MenuHelper.addSwitchModeMenuItem(menu, true, new Runnable() {
2068            public void run() {
2069                switchToVideoMode();
2070            }
2071        });
2072        MenuItem gallery = menu.add(Menu.NONE, Menu.NONE,
2073                MenuHelper.POSITION_GOTO_GALLERY,
2074                R.string.camera_gallery_photos_text)
2075                .setOnMenuItemClickListener(new OnMenuItemClickListener() {
2076            public boolean onMenuItemClick(MenuItem item) {
2077                gotoGallery();
2078                return true;
2079            }
2080        });
2081        gallery.setIcon(android.R.drawable.ic_menu_gallery);
2082        mGalleryItems.add(gallery);
2083
2084        if (mNumberOfCameras > 1) {
2085            menu.add(Menu.NONE, Menu.NONE,
2086                    MenuHelper.POSITION_SWITCH_CAMERA_ID,
2087                    R.string.switch_camera_id)
2088                    .setOnMenuItemClickListener(new OnMenuItemClickListener() {
2089                public boolean onMenuItemClick(MenuItem item) {
2090                    switchCameraId();
2091                    return true;
2092                }
2093            }).setIcon(android.R.drawable.ic_menu_camera);
2094        }
2095    }
2096
2097    private void switchCameraId() {
2098        mSwitching = true;
2099
2100        mCameraId = (mCameraId + 1) % mNumberOfCameras;
2101        CameraSettings.writePreferredCameraId(mPreferences, mCameraId);
2102
2103        stopPreview();
2104        closeCamera();
2105        changeHeadUpDisplayState();
2106
2107        // Remove the messages in the event queue.
2108        mHandler.removeMessages(RESTART_PREVIEW);
2109
2110        // Reset variables
2111        mJpegPictureCallbackTime = 0;
2112        mZoomValue = 0;
2113
2114        // Reload the preferences.
2115        mPreferences.setLocalId(this, mCameraId);
2116        CameraSettings.upgradeLocalPreferences(mPreferences.getLocal());
2117
2118
2119        // Restart the preview.
2120        resetExposureCompensation();
2121        try {
2122            startPreview();
2123        } catch (CameraHardwareException e) {
2124            showCameraErrorAndFinish();
2125            return;
2126        }
2127
2128        initializeZoom();
2129
2130        // Reload the UI.
2131        if (mFirstTimeInitialized) {
2132            initializeHeadUpDisplay();
2133        }
2134
2135        mSwitching = false;
2136        changeHeadUpDisplayState();
2137    }
2138
2139    private boolean switchToVideoMode() {
2140        if (isFinishing() || !isCameraIdle()) return false;
2141        MenuHelper.gotoVideoMode(this);
2142        mHandler.removeMessages(FIRST_TIME_INIT);
2143        finish();
2144        return true;
2145    }
2146
2147    public boolean onSwitchChanged(Switcher source, boolean onOff) {
2148        if (onOff == SWITCH_VIDEO) {
2149            return switchToVideoMode();
2150        } else {
2151            return true;
2152        }
2153    }
2154
2155    private void onSharedPreferenceChanged() {
2156        // ignore the events after "onPause()"
2157        if (mPausing) return;
2158
2159        boolean recordLocation;
2160
2161        recordLocation = RecordLocationPreference.get(
2162                mPreferences, getContentResolver());
2163        mQuickCapture = getQuickCaptureSettings();
2164
2165        if (mRecordLocation != recordLocation) {
2166            mRecordLocation = recordLocation;
2167            if (mRecordLocation) {
2168                startReceivingLocationUpdates();
2169            } else {
2170                stopReceivingLocationUpdates();
2171            }
2172        }
2173
2174        setCameraParametersWhenIdle(UPDATE_PARAM_PREFERENCE);
2175    }
2176
2177    private boolean getQuickCaptureSettings() {
2178        String value = mPreferences.getString(
2179                CameraSettings.KEY_QUICK_CAPTURE,
2180                getString(R.string.pref_camera_quickcapture_default));
2181        return CameraSettings.QUICK_CAPTURE_ON.equals(value);
2182    }
2183
2184    @Override
2185    public void onUserInteraction() {
2186        super.onUserInteraction();
2187        keepScreenOnAwhile();
2188    }
2189
2190    private void resetScreenOn() {
2191        mHandler.removeMessages(CLEAR_SCREEN_DELAY);
2192        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
2193    }
2194
2195    private void keepScreenOnAwhile() {
2196        mHandler.removeMessages(CLEAR_SCREEN_DELAY);
2197        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
2198        mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY);
2199    }
2200
2201    private class MyHeadUpDisplayListener implements HeadUpDisplay.Listener {
2202
2203        public void onSharedPreferencesChanged() {
2204            Camera.this.onSharedPreferenceChanged();
2205        }
2206
2207        public void onRestorePreferencesClicked() {
2208            Camera.this.onRestorePreferencesClicked();
2209        }
2210
2211        public void onPopupWindowVisibilityChanged(int visibility) {
2212        }
2213    }
2214
2215    protected void onRestorePreferencesClicked() {
2216        if (mPausing) return;
2217        Runnable runnable = new Runnable() {
2218            public void run() {
2219                mHeadUpDisplay.restorePreferences(mParameters);
2220            }
2221        };
2222        MenuHelper.confirmAction(this,
2223                getString(R.string.confirm_restore_title),
2224                getString(R.string.confirm_restore_message),
2225                runnable);
2226    }
2227}
2228
2229class FocusRectangle extends View {
2230
2231    @SuppressWarnings("unused")
2232    private static final String TAG = "FocusRectangle";
2233
2234    public FocusRectangle(Context context, AttributeSet attrs) {
2235        super(context, attrs);
2236    }
2237
2238    private void setDrawable(int resid) {
2239        setBackgroundDrawable(getResources().getDrawable(resid));
2240    }
2241
2242    public void showStart() {
2243        setDrawable(R.drawable.focus_focusing);
2244    }
2245
2246    public void showSuccess() {
2247        setDrawable(R.drawable.focus_focused);
2248    }
2249
2250    public void showFail() {
2251        setDrawable(R.drawable.focus_focus_failed);
2252    }
2253
2254    public void clear() {
2255        setBackgroundDrawable(null);
2256    }
2257}
2258
2259/*
2260 * Provide a mapping for Jpeg encoding quality levels
2261 * from String representation to numeric representation.
2262 */
2263class JpegEncodingQualityMappings {
2264    private static final String TAG = "JpegEncodingQualityMappings";
2265    private static final int DEFAULT_QUALITY = 85;
2266    private static HashMap<String, Integer> mHashMap =
2267            new HashMap<String, Integer>();
2268
2269    static {
2270        mHashMap.put("normal",    CameraProfile.QUALITY_LOW);
2271        mHashMap.put("fine",      CameraProfile.QUALITY_MEDIUM);
2272        mHashMap.put("superfine", CameraProfile.QUALITY_HIGH);
2273    }
2274
2275    // Retrieve and return the Jpeg encoding quality number
2276    // for the given quality level.
2277    public static int getQualityNumber(String jpegQuality) {
2278        Integer quality = mHashMap.get(jpegQuality);
2279        if (quality == null) {
2280            Log.w(TAG, "Unknown Jpeg quality: " + jpegQuality);
2281            return DEFAULT_QUALITY;
2282        }
2283        return CameraProfile.getJpegEncodingQualityParameter(quality.intValue());
2284    }
2285}
2286