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