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