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