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