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