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