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