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