Home | History | Annotate | Download | only in camera
      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 
     17 package com.android.camera;
     18 
     19 import com.android.camera.ui.CameraPicker;
     20 import com.android.camera.ui.FaceView;
     21 import com.android.camera.ui.IndicatorControlContainer;
     22 import com.android.camera.ui.Rotatable;
     23 import com.android.camera.ui.RotateImageView;
     24 import com.android.camera.ui.RotateLayout;
     25 import com.android.camera.ui.SharePopup;
     26 import com.android.camera.ui.ZoomControl;
     27 
     28 import android.app.Activity;
     29 import android.content.BroadcastReceiver;
     30 import android.content.ContentProviderClient;
     31 import android.content.ContentResolver;
     32 import android.content.Context;
     33 import android.content.Intent;
     34 import android.content.IntentFilter;
     35 import android.content.SharedPreferences.Editor;
     36 import android.graphics.Bitmap;
     37 import android.hardware.Camera.CameraInfo;
     38 import android.hardware.Camera.Face;
     39 import android.hardware.Camera.FaceDetectionListener;
     40 import android.hardware.Camera.Parameters;
     41 import android.hardware.Camera.PictureCallback;
     42 import android.hardware.Camera.Size;
     43 import android.location.Location;
     44 import android.media.CameraProfile;
     45 import android.net.Uri;
     46 import android.os.Bundle;
     47 import android.os.Handler;
     48 import android.os.Looper;
     49 import android.os.Message;
     50 import android.os.MessageQueue;
     51 import android.os.SystemClock;
     52 import android.provider.MediaStore;
     53 import android.util.Log;
     54 import android.view.GestureDetector;
     55 import android.view.Gravity;
     56 import android.view.KeyEvent;
     57 import android.view.Menu;
     58 import android.view.MenuItem;
     59 import android.view.MenuItem.OnMenuItemClickListener;
     60 import android.view.MotionEvent;
     61 import android.view.OrientationEventListener;
     62 import android.view.SurfaceHolder;
     63 import android.view.SurfaceView;
     64 import android.view.View;
     65 import android.view.WindowManager;
     66 import android.view.animation.AnimationUtils;
     67 import android.widget.TextView;
     68 import android.widget.Toast;
     69 
     70 import java.io.File;
     71 import java.io.FileNotFoundException;
     72 import java.io.FileOutputStream;
     73 import java.io.IOException;
     74 import java.io.OutputStream;
     75 import java.util.ArrayList;
     76 import java.util.Collections;
     77 import java.util.Formatter;
     78 import java.util.List;
     79 
     80 /** The Camera activity which can preview and take pictures. */
     81 public class Camera extends ActivityBase implements FocusManager.Listener,
     82         View.OnTouchListener, ShutterButton.OnShutterButtonListener,
     83         SurfaceHolder.Callback, ModePicker.OnModeChangeListener,
     84         FaceDetectionListener, CameraPreference.OnPreferenceChangedListener,
     85         LocationManager.Listener, ShutterButton.OnShutterButtonLongPressListener {
     86 
     87     private static final String TAG = "camera";
     88 
     89     private static final int CROP_MSG = 1;
     90     private static final int FIRST_TIME_INIT = 2;
     91     private static final int CLEAR_SCREEN_DELAY = 3;
     92     private static final int SET_CAMERA_PARAMETERS_WHEN_IDLE = 4;
     93     private static final int CHECK_DISPLAY_ROTATION = 5;
     94     private static final int SHOW_TAP_TO_FOCUS_TOAST = 6;
     95     private static final int DISMISS_TAP_TO_FOCUS_TOAST = 7;
     96     private static final int UPDATE_THUMBNAIL = 8;
     97 
     98     // The subset of parameters we need to update in setCameraParameters().
     99     private static final int UPDATE_PARAM_INITIALIZE = 1;
    100     private static final int UPDATE_PARAM_ZOOM = 2;
    101     private static final int UPDATE_PARAM_PREFERENCE = 4;
    102     private static final int UPDATE_PARAM_ALL = -1;
    103 
    104     // When setCameraParametersWhenIdle() is called, we accumulate the subsets
    105     // needed to be updated in mUpdateSet.
    106     private int mUpdateSet;
    107 
    108     private static final int SCREEN_DELAY = 2 * 60 * 1000;
    109 
    110     private static final int ZOOM_STOPPED = 0;
    111     private static final int ZOOM_START = 1;
    112     private static final int ZOOM_STOPPING = 2;
    113 
    114     private int mZoomState = ZOOM_STOPPED;
    115     private boolean mSmoothZoomSupported = false;
    116     private int mZoomValue;  // The current zoom value.
    117     private int mZoomMax;
    118     private int mTargetZoomValue;
    119     private ZoomControl mZoomControl;
    120 
    121     private Parameters mParameters;
    122     private Parameters mInitialParams;
    123     private boolean mFocusAreaSupported;
    124     private boolean mMeteringAreaSupported;
    125     private boolean mAeLockSupported;
    126     private boolean mAwbLockSupported;
    127 
    128     private MyOrientationEventListener mOrientationListener;
    129     // The degrees of the device rotated clockwise from its natural orientation.
    130     private int mOrientation = OrientationEventListener.ORIENTATION_UNKNOWN;
    131     // The orientation compensation for icons and thumbnails. Ex: if the value
    132     // is 90, the UI components should be rotated 90 degrees counter-clockwise.
    133     private int mOrientationCompensation = 0;
    134     private ComboPreferences mPreferences;
    135 
    136     private static final String sTempCropFilename = "crop-temp";
    137 
    138     private ContentProviderClient mMediaProviderClient;
    139     private SurfaceHolder mSurfaceHolder = null;
    140     private ShutterButton mShutterButton;
    141     private GestureDetector mPopupGestureDetector;
    142     private boolean mOpenCameraFail = false;
    143     private boolean mCameraDisabled = false;
    144 
    145     private View mPreviewPanel;  // The container of PreviewFrameLayout.
    146     private PreviewFrameLayout mPreviewFrameLayout;
    147     private View mPreviewFrame;  // Preview frame area.
    148 
    149     // A popup window that contains a bigger thumbnail and a list of apps to share.
    150     private SharePopup mSharePopup;
    151     // The bitmap of the last captured picture thumbnail and the URI of the
    152     // original picture.
    153     private Thumbnail mThumbnail;
    154     // An imageview showing showing the last captured picture thumbnail.
    155     private RotateImageView mThumbnailView;
    156     private ModePicker mModePicker;
    157     private FaceView mFaceView;
    158     private RotateLayout mFocusIndicator;
    159     private Rotatable mReviewCancelButton;
    160     private Rotatable mReviewDoneButton;
    161 
    162     // mCropValue and mSaveUri are used only if isImageCaptureIntent() is true.
    163     private String mCropValue;
    164     private Uri mSaveUri;
    165 
    166     // On-screen indicator
    167     private View mGpsNoSignalIndicator;
    168     private View mGpsHasSignalIndicator;
    169     private TextView mExposureIndicator;
    170 
    171     // We use a thread in ImageSaver to do the work of saving images and
    172     // generating thumbnails. This reduces the shot-to-shot time.
    173     private ImageSaver mImageSaver;
    174 
    175     private Runnable mDoSnapRunnable = new Runnable() {
    176         public void run() {
    177             onShutterButtonClick();
    178         }
    179     };
    180 
    181     private final StringBuilder mBuilder = new StringBuilder();
    182     private final Formatter mFormatter = new Formatter(mBuilder);
    183     private final Object[] mFormatterArgs = new Object[1];
    184 
    185     /**
    186      * An unpublished intent flag requesting to return as soon as capturing
    187      * is completed.
    188      *
    189      * TODO: consider publishing by moving into MediaStore.
    190      */
    191     private final static String EXTRA_QUICK_CAPTURE =
    192             "android.intent.extra.quickCapture";
    193 
    194     // The display rotation in degrees. This is only valid when mCameraState is
    195     // not PREVIEW_STOPPED.
    196     private int mDisplayRotation;
    197     // The value for android.hardware.Camera.setDisplayOrientation.
    198     private int mDisplayOrientation;
    199     private boolean mPausing;
    200     private boolean mFirstTimeInitialized;
    201     private boolean mIsImageCaptureIntent;
    202 
    203     private static final int PREVIEW_STOPPED = 0;
    204     private static final int IDLE = 1;  // preview is active
    205     // Focus is in progress. The exact focus state is in Focus.java.
    206     private static final int FOCUSING = 2;
    207     private static final int SNAPSHOT_IN_PROGRESS = 3;
    208     private int mCameraState = PREVIEW_STOPPED;
    209     private boolean mSnapshotOnIdle = false;
    210 
    211     private ContentResolver mContentResolver;
    212     private boolean mDidRegister = false;
    213 
    214     private LocationManager mLocationManager;
    215 
    216     private final ShutterCallback mShutterCallback = new ShutterCallback();
    217     private final PostViewPictureCallback mPostViewPictureCallback =
    218             new PostViewPictureCallback();
    219     private final RawPictureCallback mRawPictureCallback =
    220             new RawPictureCallback();
    221     private final AutoFocusCallback mAutoFocusCallback =
    222             new AutoFocusCallback();
    223     private final ZoomListener mZoomListener = new ZoomListener();
    224     private final CameraErrorCallback mErrorCallback = new CameraErrorCallback();
    225 
    226     private long mFocusStartTime;
    227     private long mCaptureStartTime;
    228     private long mShutterCallbackTime;
    229     private long mPostViewPictureCallbackTime;
    230     private long mRawPictureCallbackTime;
    231     private long mJpegPictureCallbackTime;
    232     private long mOnResumeTime;
    233     private long mPicturesRemaining;
    234     private byte[] mJpegImageData;
    235 
    236     // These latency time are for the CameraLatency test.
    237     public long mAutoFocusTime;
    238     public long mShutterLag;
    239     public long mShutterToPictureDisplayedTime;
    240     public long mPictureDisplayedToJpegCallbackTime;
    241     public long mJpegCallbackFinishTime;
    242 
    243     // This handles everything about focus.
    244     private FocusManager mFocusManager;
    245     private String mSceneMode;
    246     private Toast mNotSelectableToast;
    247     private Toast mNoShareToast;
    248 
    249     private final Handler mHandler = new MainHandler();
    250     private IndicatorControlContainer mIndicatorControlContainer;
    251     private PreferenceGroup mPreferenceGroup;
    252 
    253     // multiple cameras support
    254     private int mNumberOfCameras;
    255     private int mCameraId;
    256     private int mFrontCameraId;
    257     private int mBackCameraId;
    258 
    259     private boolean mQuickCapture;
    260 
    261     /**
    262      * This Handler is used to post message back onto the main thread of the
    263      * application
    264      */
    265     private class MainHandler extends Handler {
    266         @Override
    267         public void handleMessage(Message msg) {
    268             switch (msg.what) {
    269                 case CLEAR_SCREEN_DELAY: {
    270                     getWindow().clearFlags(
    271                             WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    272                     break;
    273                 }
    274 
    275                 case FIRST_TIME_INIT: {
    276                     initializeFirstTime();
    277                     break;
    278                 }
    279 
    280                 case SET_CAMERA_PARAMETERS_WHEN_IDLE: {
    281                     setCameraParametersWhenIdle(0);
    282                     break;
    283                 }
    284 
    285                 case CHECK_DISPLAY_ROTATION: {
    286                     // Set the display orientation if display rotation has changed.
    287                     // Sometimes this happens when the device is held upside
    288                     // down and camera app is opened. Rotation animation will
    289                     // take some time and the rotation value we have got may be
    290                     // wrong. Framework does not have a callback for this now.
    291                     if (Util.getDisplayRotation(Camera.this) != mDisplayRotation) {
    292                         setDisplayOrientation();
    293                     }
    294                     if (SystemClock.uptimeMillis() - mOnResumeTime < 5000) {
    295                         mHandler.sendEmptyMessageDelayed(CHECK_DISPLAY_ROTATION, 100);
    296                     }
    297                     break;
    298                 }
    299 
    300                 case SHOW_TAP_TO_FOCUS_TOAST: {
    301                     showTapToFocusToast();
    302                     break;
    303                 }
    304 
    305                 case DISMISS_TAP_TO_FOCUS_TOAST: {
    306                     View v = findViewById(R.id.tap_to_focus_prompt);
    307                     v.setVisibility(View.GONE);
    308                     v.setAnimation(AnimationUtils.loadAnimation(Camera.this,
    309                             R.anim.on_screen_hint_exit));
    310                     break;
    311                 }
    312 
    313                 case UPDATE_THUMBNAIL: {
    314                     mImageSaver.updateThumbnail();
    315                     break;
    316                 }
    317             }
    318         }
    319     }
    320 
    321     private void resetExposureCompensation() {
    322         String value = mPreferences.getString(CameraSettings.KEY_EXPOSURE,
    323                 CameraSettings.EXPOSURE_DEFAULT_VALUE);
    324         if (!CameraSettings.EXPOSURE_DEFAULT_VALUE.equals(value)) {
    325             Editor editor = mPreferences.edit();
    326             editor.putString(CameraSettings.KEY_EXPOSURE, "0");
    327             editor.apply();
    328             if (mIndicatorControlContainer != null) {
    329                 mIndicatorControlContainer.reloadPreferences();
    330             }
    331         }
    332     }
    333 
    334     private void keepMediaProviderInstance() {
    335         // We want to keep a reference to MediaProvider in camera's lifecycle.
    336         // TODO: Utilize mMediaProviderClient instance to replace
    337         // ContentResolver calls.
    338         if (mMediaProviderClient == null) {
    339             mMediaProviderClient = getContentResolver()
    340                     .acquireContentProviderClient(MediaStore.AUTHORITY);
    341         }
    342     }
    343 
    344     // Snapshots can only be taken after this is called. It should be called
    345     // once only. We could have done these things in onCreate() but we want to
    346     // make preview screen appear as soon as possible.
    347     private void initializeFirstTime() {
    348         if (mFirstTimeInitialized) return;
    349 
    350         // Create orientation listenter. This should be done first because it
    351         // takes some time to get first orientation.
    352         mOrientationListener = new MyOrientationEventListener(Camera.this);
    353         mOrientationListener.enable();
    354 
    355         // Initialize location sevice.
    356         boolean recordLocation = RecordLocationPreference.get(
    357                 mPreferences, getContentResolver());
    358         initOnScreenIndicator();
    359         mLocationManager.recordLocation(recordLocation);
    360 
    361         keepMediaProviderInstance();
    362         checkStorage();
    363 
    364         // Initialize last picture button.
    365         mContentResolver = getContentResolver();
    366         if (!mIsImageCaptureIntent) {  // no thumbnail in image capture intent
    367             initThumbnailButton();
    368         }
    369 
    370         // Initialize shutter button.
    371         mShutterButton = (ShutterButton) findViewById(R.id.shutter_button);
    372         mShutterButton.setOnShutterButtonListener(this);
    373         mShutterButton.setOnShutterButtonLongPressListener(this);
    374         mShutterButton.setVisibility(View.VISIBLE);
    375 
    376         // Initialize focus UI.
    377         mPreviewFrame = findViewById(R.id.camera_preview);
    378         mPreviewFrame.setOnTouchListener(this);
    379         mFocusIndicator = (RotateLayout) findViewById(R.id.focus_indicator_rotate_layout);
    380         CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId];
    381         boolean mirror = (info.facing == CameraInfo.CAMERA_FACING_FRONT);
    382         mFocusManager.initialize(mFocusIndicator, mPreviewFrame, mFaceView, this,
    383                 mirror, mDisplayOrientation);
    384         mFocusManager.initializeSoundPlayer(getResources().openRawResourceFd(R.raw.camera_focus));
    385         mImageSaver = new ImageSaver();
    386         Util.initializeScreenBrightness(getWindow(), getContentResolver());
    387         installIntentFilter();
    388         initializeZoom();
    389         startFaceDetection();
    390         // Show the tap to focus toast if this is the first start.
    391         if (mFocusAreaSupported &&
    392                 mPreferences.getBoolean(CameraSettings.KEY_TAP_TO_FOCUS_PROMPT_SHOWN, true)) {
    393             // Delay the toast for one second to wait for orientation.
    394             mHandler.sendEmptyMessageDelayed(SHOW_TAP_TO_FOCUS_TOAST, 1000);
    395         }
    396 
    397         mFirstTimeInitialized = true;
    398         addIdleHandler();
    399     }
    400 
    401     private void addIdleHandler() {
    402         MessageQueue queue = Looper.myQueue();
    403         queue.addIdleHandler(new MessageQueue.IdleHandler() {
    404             public boolean queueIdle() {
    405                 Storage.ensureOSXCompatible();
    406                 return false;
    407             }
    408         });
    409     }
    410 
    411     private void initThumbnailButton() {
    412         // Load the thumbnail from the disk.
    413         mThumbnail = Thumbnail.loadFrom(new File(getFilesDir(), Thumbnail.LAST_THUMB_FILENAME));
    414         updateThumbnailButton();
    415     }
    416 
    417     private void updateThumbnailButton() {
    418         // Update last image if URI is invalid and the storage is ready.
    419         if ((mThumbnail == null || !Util.isUriValid(mThumbnail.getUri(), mContentResolver))
    420                 && mPicturesRemaining >= 0) {
    421             mThumbnail = Thumbnail.getLastThumbnail(mContentResolver);
    422         }
    423         if (mThumbnail != null) {
    424             mThumbnailView.setBitmap(mThumbnail.getBitmap());
    425         } else {
    426             mThumbnailView.setBitmap(null);
    427         }
    428     }
    429 
    430     // If the activity is paused and resumed, this method will be called in
    431     // onResume.
    432     private void initializeSecondTime() {
    433         // Start orientation listener as soon as possible because it takes
    434         // some time to get first orientation.
    435         mOrientationListener.enable();
    436 
    437         // Start location update if needed.
    438         boolean recordLocation = RecordLocationPreference.get(
    439                 mPreferences, getContentResolver());
    440         mLocationManager.recordLocation(recordLocation);
    441 
    442         installIntentFilter();
    443         mFocusManager.initializeSoundPlayer(getResources().openRawResourceFd(R.raw.camera_focus));
    444         mImageSaver = new ImageSaver();
    445         initializeZoom();
    446         keepMediaProviderInstance();
    447         checkStorage();
    448         hidePostCaptureAlert();
    449 
    450         if (!mIsImageCaptureIntent) {
    451             updateThumbnailButton();
    452             mModePicker.setCurrentMode(ModePicker.MODE_CAMERA);
    453         }
    454     }
    455 
    456     private class ZoomChangeListener implements ZoomControl.OnZoomChangedListener {
    457         // only for immediate zoom
    458         @Override
    459         public void onZoomValueChanged(int index) {
    460             Camera.this.onZoomValueChanged(index);
    461         }
    462 
    463         // only for smooth zoom
    464         @Override
    465         public void onZoomStateChanged(int state) {
    466             if (mPausing) return;
    467 
    468             Log.v(TAG, "zoom picker state=" + state);
    469             if (state == ZoomControl.ZOOM_IN) {
    470                 Camera.this.onZoomValueChanged(mZoomMax);
    471             } else if (state == ZoomControl.ZOOM_OUT) {
    472                 Camera.this.onZoomValueChanged(0);
    473             } else {
    474                 mTargetZoomValue = -1;
    475                 if (mZoomState == ZOOM_START) {
    476                     mZoomState = ZOOM_STOPPING;
    477                     mCameraDevice.stopSmoothZoom();
    478                 }
    479             }
    480         }
    481     }
    482 
    483     private void initializeZoom() {
    484         // Get the parameter to make sure we have the up-to-date zoom value.
    485         mParameters = mCameraDevice.getParameters();
    486         if (!mParameters.isZoomSupported()) return;
    487         mZoomMax = mParameters.getMaxZoom();
    488         // Currently we use immediate zoom for fast zooming to get better UX and
    489         // there is no plan to take advantage of the smooth zoom.
    490         mZoomControl.setZoomMax(mZoomMax);
    491         mZoomControl.setZoomIndex(mParameters.getZoom());
    492         mZoomControl.setSmoothZoomSupported(mSmoothZoomSupported);
    493         mZoomControl.setOnZoomChangeListener(new ZoomChangeListener());
    494         mCameraDevice.setZoomChangeListener(mZoomListener);
    495     }
    496 
    497     private void onZoomValueChanged(int index) {
    498         // Not useful to change zoom value when the activity is paused.
    499         if (mPausing) return;
    500 
    501         if (mSmoothZoomSupported) {
    502             if (mTargetZoomValue != index && mZoomState != ZOOM_STOPPED) {
    503                 mTargetZoomValue = index;
    504                 if (mZoomState == ZOOM_START) {
    505                     mZoomState = ZOOM_STOPPING;
    506                     mCameraDevice.stopSmoothZoom();
    507                 }
    508             } else if (mZoomState == ZOOM_STOPPED && mZoomValue != index) {
    509                 mTargetZoomValue = index;
    510                 mCameraDevice.startSmoothZoom(index);
    511                 mZoomState = ZOOM_START;
    512             }
    513         } else {
    514             mZoomValue = index;
    515             setCameraParametersWhenIdle(UPDATE_PARAM_ZOOM);
    516         }
    517     }
    518 
    519     @Override
    520     public void startFaceDetection() {
    521         if (mParameters.getMaxNumDetectedFaces() > 0) {
    522             mFaceView = (FaceView) findViewById(R.id.face_view);
    523             mFaceView.clear();
    524             mFaceView.setVisibility(View.VISIBLE);
    525             mFaceView.setDisplayOrientation(mDisplayOrientation);
    526             CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId];
    527             mFaceView.setMirror(info.facing == CameraInfo.CAMERA_FACING_FRONT);
    528             mFaceView.resume();
    529             mCameraDevice.setFaceDetectionListener(this);
    530             mCameraDevice.startFaceDetection();
    531         }
    532     }
    533 
    534     @Override
    535     public void stopFaceDetection() {
    536         if (mParameters.getMaxNumDetectedFaces() > 0) {
    537             mCameraDevice.setFaceDetectionListener(null);
    538             mCameraDevice.stopFaceDetection();
    539             if (mFaceView != null) mFaceView.clear();
    540         }
    541     }
    542 
    543     private class PopupGestureListener
    544             extends GestureDetector.SimpleOnGestureListener {
    545         @Override
    546         public boolean onDown(MotionEvent e) {
    547             // Check if the popup window is visible.
    548             View popup = mIndicatorControlContainer.getActiveSettingPopup();
    549             if (popup == null) return false;
    550 
    551 
    552             // Let popup window, indicator control or preview frame handle the
    553             // event by themselves. Dismiss the popup window if users touch on
    554             // other areas.
    555             if (!Util.pointInView(e.getX(), e.getY(), popup)
    556                     && !Util.pointInView(e.getX(), e.getY(), mIndicatorControlContainer)
    557                     && !Util.pointInView(e.getX(), e.getY(), mPreviewFrame)) {
    558                 mIndicatorControlContainer.dismissSettingPopup();
    559                 // Let event fall through.
    560             }
    561             return false;
    562         }
    563     }
    564 
    565     @Override
    566     public boolean dispatchTouchEvent(MotionEvent m) {
    567         // Check if the popup window should be dismissed first.
    568         if (mPopupGestureDetector != null && mPopupGestureDetector.onTouchEvent(m)) {
    569             return true;
    570         }
    571 
    572         return super.dispatchTouchEvent(m);
    573     }
    574 
    575     private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    576         @Override
    577         public void onReceive(Context context, Intent intent) {
    578             String action = intent.getAction();
    579             Log.d(TAG, "Received intent action=" + action);
    580             if (action.equals(Intent.ACTION_MEDIA_MOUNTED)
    581                     || action.equals(Intent.ACTION_MEDIA_UNMOUNTED)
    582                     || action.equals(Intent.ACTION_MEDIA_CHECKING)) {
    583                 checkStorage();
    584             } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)) {
    585                 checkStorage();
    586                 if (!mIsImageCaptureIntent) {
    587                     updateThumbnailButton();
    588                 }
    589             }
    590         }
    591     };
    592 
    593     private void initOnScreenIndicator() {
    594         mGpsNoSignalIndicator = findViewById(R.id.onscreen_gps_indicator_no_signal);
    595         mGpsHasSignalIndicator = findViewById(R.id.onscreen_gps_indicator_on);
    596         mExposureIndicator = (TextView) findViewById(R.id.onscreen_exposure_indicator);
    597     }
    598 
    599     @Override
    600     public void showGpsOnScreenIndicator(boolean hasSignal) {
    601         if (hasSignal) {
    602             if (mGpsNoSignalIndicator != null) {
    603                 mGpsNoSignalIndicator.setVisibility(View.GONE);
    604             }
    605             if (mGpsHasSignalIndicator != null) {
    606                 mGpsHasSignalIndicator.setVisibility(View.VISIBLE);
    607             }
    608         } else {
    609             if (mGpsNoSignalIndicator != null) {
    610                 mGpsNoSignalIndicator.setVisibility(View.VISIBLE);
    611             }
    612             if (mGpsHasSignalIndicator != null) {
    613                 mGpsHasSignalIndicator.setVisibility(View.GONE);
    614             }
    615         }
    616     }
    617 
    618     @Override
    619     public void hideGpsOnScreenIndicator() {
    620         if (mGpsNoSignalIndicator != null) mGpsNoSignalIndicator.setVisibility(View.GONE);
    621         if (mGpsHasSignalIndicator != null) mGpsHasSignalIndicator.setVisibility(View.GONE);
    622     }
    623 
    624     private void updateExposureOnScreenIndicator(int value) {
    625         if (mExposureIndicator == null) return;
    626 
    627         if (value == 0) {
    628             mExposureIndicator.setText("");
    629             mExposureIndicator.setVisibility(View.GONE);
    630         } else {
    631             float step = mParameters.getExposureCompensationStep();
    632             mFormatterArgs[0] = value * step;
    633             mBuilder.delete(0, mBuilder.length());
    634             mFormatter.format("%+1.1f", mFormatterArgs);
    635             String exposure = mFormatter.toString();
    636             mExposureIndicator.setText(exposure);
    637             mExposureIndicator.setVisibility(View.VISIBLE);
    638         }
    639     }
    640 
    641     private final class ShutterCallback
    642             implements android.hardware.Camera.ShutterCallback {
    643         public void onShutter() {
    644             mShutterCallbackTime = System.currentTimeMillis();
    645             mShutterLag = mShutterCallbackTime - mCaptureStartTime;
    646             Log.v(TAG, "mShutterLag = " + mShutterLag + "ms");
    647             mFocusManager.onShutter();
    648         }
    649     }
    650 
    651     private final class PostViewPictureCallback implements PictureCallback {
    652         public void onPictureTaken(
    653                 byte [] data, android.hardware.Camera camera) {
    654             mPostViewPictureCallbackTime = System.currentTimeMillis();
    655             Log.v(TAG, "mShutterToPostViewCallbackTime = "
    656                     + (mPostViewPictureCallbackTime - mShutterCallbackTime)
    657                     + "ms");
    658         }
    659     }
    660 
    661     private final class RawPictureCallback implements PictureCallback {
    662         public void onPictureTaken(
    663                 byte [] rawData, android.hardware.Camera camera) {
    664             mRawPictureCallbackTime = System.currentTimeMillis();
    665             Log.v(TAG, "mShutterToRawCallbackTime = "
    666                     + (mRawPictureCallbackTime - mShutterCallbackTime) + "ms");
    667         }
    668     }
    669 
    670     private final class JpegPictureCallback implements PictureCallback {
    671         Location mLocation;
    672 
    673         public JpegPictureCallback(Location loc) {
    674             mLocation = loc;
    675         }
    676 
    677         public void onPictureTaken(
    678                 final byte [] jpegData, final android.hardware.Camera camera) {
    679             if (mPausing) {
    680                 return;
    681             }
    682 
    683             mJpegPictureCallbackTime = System.currentTimeMillis();
    684             // If postview callback has arrived, the captured image is displayed
    685             // in postview callback. If not, the captured image is displayed in
    686             // raw picture callback.
    687             if (mPostViewPictureCallbackTime != 0) {
    688                 mShutterToPictureDisplayedTime =
    689                         mPostViewPictureCallbackTime - mShutterCallbackTime;
    690                 mPictureDisplayedToJpegCallbackTime =
    691                         mJpegPictureCallbackTime - mPostViewPictureCallbackTime;
    692             } else {
    693                 mShutterToPictureDisplayedTime =
    694                         mRawPictureCallbackTime - mShutterCallbackTime;
    695                 mPictureDisplayedToJpegCallbackTime =
    696                         mJpegPictureCallbackTime - mRawPictureCallbackTime;
    697             }
    698             Log.v(TAG, "mPictureDisplayedToJpegCallbackTime = "
    699                     + mPictureDisplayedToJpegCallbackTime + "ms");
    700 
    701             if (!mIsImageCaptureIntent) {
    702                 enableCameraControls(true);
    703 
    704                 startPreview();
    705                 startFaceDetection();
    706             }
    707 
    708             if (!mIsImageCaptureIntent) {
    709                 Size s = mParameters.getPictureSize();
    710                 mImageSaver.addImage(jpegData, mLocation, s.width, s.height);
    711             } else {
    712                 mJpegImageData = jpegData;
    713                 if (!mQuickCapture) {
    714                     showPostCaptureAlert();
    715                 } else {
    716                     doAttach();
    717                 }
    718             }
    719 
    720             // Check this in advance of each shot so we don't add to shutter
    721             // latency. It's true that someone else could write to the SD card in
    722             // the mean time and fill it, but that could have happened between the
    723             // shutter press and saving the JPEG too.
    724             checkStorage();
    725 
    726             long now = System.currentTimeMillis();
    727             mJpegCallbackFinishTime = now - mJpegPictureCallbackTime;
    728             Log.v(TAG, "mJpegCallbackFinishTime = "
    729                     + mJpegCallbackFinishTime + "ms");
    730             mJpegPictureCallbackTime = 0;
    731         }
    732     }
    733 
    734     private final class AutoFocusCallback
    735             implements android.hardware.Camera.AutoFocusCallback {
    736         public void onAutoFocus(
    737                 boolean focused, android.hardware.Camera camera) {
    738             if (mPausing) return;
    739 
    740             mAutoFocusTime = System.currentTimeMillis() - mFocusStartTime;
    741             Log.v(TAG, "mAutoFocusTime = " + mAutoFocusTime + "ms");
    742             mFocusManager.onAutoFocus(focused);
    743             // If focus completes and the snapshot is not started, enable the
    744             // controls.
    745             if (mFocusManager.isFocusCompleted()) {
    746                 enableCameraControls(true);
    747             }
    748         }
    749     }
    750 
    751     private final class ZoomListener
    752             implements android.hardware.Camera.OnZoomChangeListener {
    753         @Override
    754         public void onZoomChange(
    755                 int value, boolean stopped, android.hardware.Camera camera) {
    756             Log.v(TAG, "Zoom changed: value=" + value + ". stopped=" + stopped);
    757             mZoomValue = value;
    758 
    759             // Update the UI when we get zoom value.
    760             mZoomControl.setZoomIndex(value);
    761 
    762             // Keep mParameters up to date. We do not getParameter again in
    763             // takePicture. If we do not do this, wrong zoom value will be set.
    764             mParameters.setZoom(value);
    765 
    766             if (stopped && mZoomState != ZOOM_STOPPED) {
    767                 if (mTargetZoomValue != -1 && value != mTargetZoomValue) {
    768                     mCameraDevice.startSmoothZoom(mTargetZoomValue);
    769                     mZoomState = ZOOM_START;
    770                 } else {
    771                     mZoomState = ZOOM_STOPPED;
    772                 }
    773             }
    774         }
    775     }
    776 
    777     // Each SaveRequest remembers the data needed to save an image.
    778     private static class SaveRequest {
    779         byte[] data;
    780         Location loc;
    781         int width, height;
    782         long dateTaken;
    783         int previewWidth;
    784     }
    785 
    786     // We use a queue to store the SaveRequests that have not been completed
    787     // yet. The main thread puts the request into the queue. The saver thread
    788     // gets it from the queue, does the work, and removes it from the queue.
    789     //
    790     // There are several cases the main thread needs to wait for the saver
    791     // thread to finish all the work in the queue:
    792     // (1) When the activity's onPause() is called, we need to finish all the
    793     // work, so other programs (like Gallery) can see all the images.
    794     // (2) When we need to show the SharePop, we need to finish all the work
    795     // too, because we want to show the thumbnail of the last image taken.
    796     //
    797     // If the queue becomes too long, adding a new request will block the main
    798     // thread until the queue length drops below the threshold (QUEUE_LIMIT).
    799     // If we don't do this, we may face several problems: (1) We may OOM
    800     // because we are holding all the jpeg data in memory. (2) We may ANR
    801     // when we need to wait for saver thread finishing all the work (in
    802     // onPause() or showSharePopup()) because the time to finishing a long queue
    803     // of work may be too long.
    804     private class ImageSaver extends Thread {
    805         private static final int QUEUE_LIMIT = 3;
    806 
    807         private ArrayList<SaveRequest> mQueue;
    808         private Thumbnail mPendingThumbnail;
    809         private Object mUpdateThumbnailLock = new Object();
    810         private boolean mStop;
    811 
    812         // Runs in main thread
    813         public ImageSaver() {
    814             mQueue = new ArrayList<SaveRequest>();
    815             start();
    816         }
    817 
    818         // Runs in main thread
    819         public void addImage(final byte[] data, Location loc, int width,
    820                 int height) {
    821             SaveRequest r = new SaveRequest();
    822             r.data = data;
    823             r.loc = (loc == null) ? null : new Location(loc);  // make a copy
    824             r.width = width;
    825             r.height = height;
    826             r.dateTaken = System.currentTimeMillis();
    827             r.previewWidth = mPreviewFrameLayout.getWidth();
    828             synchronized (this) {
    829                 while (mQueue.size() >= QUEUE_LIMIT) {
    830                     try {
    831                         wait();
    832                     } catch (InterruptedException ex) {
    833                         // ignore.
    834                     }
    835                 }
    836                 mQueue.add(r);
    837                 notifyAll();  // Tell saver thread there is new work to do.
    838             }
    839         }
    840 
    841         // Runs in saver thread
    842         @Override
    843         public void run() {
    844             while (true) {
    845                 SaveRequest r;
    846                 synchronized (this) {
    847                     if (mQueue.isEmpty()) {
    848                         notifyAll();  // notify main thread in waitDone
    849 
    850                         // Note that we can only stop after we saved all images
    851                         // in the queue.
    852                         if (mStop) break;
    853 
    854                         try {
    855                             wait();
    856                         } catch (InterruptedException ex) {
    857                             // ignore.
    858                         }
    859                         continue;
    860                     }
    861                     r = mQueue.get(0);
    862                 }
    863                 storeImage(r.data, r.loc, r.width, r.height, r.dateTaken,
    864                         r.previewWidth);
    865                 synchronized(this) {
    866                     mQueue.remove(0);
    867                     notifyAll();  // the main thread may wait in addImage
    868                 }
    869             }
    870         }
    871 
    872         // Runs in main thread
    873         public void waitDone() {
    874             synchronized (this) {
    875                 while (!mQueue.isEmpty()) {
    876                     try {
    877                         wait();
    878                     } catch (InterruptedException ex) {
    879                         // ignore.
    880                     }
    881                 }
    882             }
    883             updateThumbnail();
    884         }
    885 
    886         // Runs in main thread
    887         public void finish() {
    888             waitDone();
    889             synchronized (this) {
    890                 mStop = true;
    891                 notifyAll();
    892             }
    893             try {
    894                 join();
    895             } catch (InterruptedException ex) {
    896                 // ignore.
    897             }
    898         }
    899 
    900         // Runs in main thread (because we need to update mThumbnailView in the
    901         // main thread)
    902         public void updateThumbnail() {
    903             Thumbnail t;
    904             synchronized (mUpdateThumbnailLock) {
    905                 mHandler.removeMessages(UPDATE_THUMBNAIL);
    906                 t = mPendingThumbnail;
    907                 mPendingThumbnail = null;
    908             }
    909 
    910             if (t != null) {
    911                 mThumbnail = t;
    912                 mThumbnailView.setBitmap(mThumbnail.getBitmap());
    913             }
    914             // Share popup may still have the reference to the old thumbnail. Clear it.
    915             mSharePopup = null;
    916         }
    917 
    918         // Runs in saver thread
    919         private void storeImage(final byte[] data, Location loc, int width,
    920                 int height, long dateTaken, int previewWidth) {
    921             String title = Util.createJpegName(dateTaken);
    922             int orientation = Exif.getOrientation(data);
    923             Uri uri = Storage.addImage(mContentResolver, title, dateTaken,
    924                     loc, orientation, data, width, height);
    925             if (uri != null) {
    926                 boolean needThumbnail;
    927                 synchronized (this) {
    928                     // If the number of requests in the queue (include the
    929                     // current one) is greater than 1, we don't need to generate
    930                     // thumbnail for this image. Because we'll soon replace it
    931                     // with the thumbnail for some image later in the queue.
    932                     needThumbnail = (mQueue.size() <= 1);
    933                 }
    934                 if (needThumbnail) {
    935                     // Create a thumbnail whose width is equal or bigger than
    936                     // that of the preview.
    937                     int ratio = (int) Math.ceil((double) width / previewWidth);
    938                     int inSampleSize = Integer.highestOneBit(ratio);
    939                     Thumbnail t = Thumbnail.createThumbnail(
    940                                 data, orientation, inSampleSize, uri);
    941                     synchronized (mUpdateThumbnailLock) {
    942                         // We need to update the thumbnail in the main thread,
    943                         // so send a message to run updateThumbnail().
    944                         mPendingThumbnail = t;
    945                         mHandler.sendEmptyMessage(UPDATE_THUMBNAIL);
    946                     }
    947                 }
    948                 Util.broadcastNewPicture(Camera.this, uri);
    949             }
    950         }
    951     }
    952 
    953     @Override
    954     public boolean capture() {
    955         // If we are already in the middle of taking a snapshot then ignore.
    956         if (mCameraState == SNAPSHOT_IN_PROGRESS || mCameraDevice == null) {
    957             return false;
    958         }
    959         mCaptureStartTime = System.currentTimeMillis();
    960         mPostViewPictureCallbackTime = 0;
    961         enableCameraControls(false);
    962         mJpegImageData = null;
    963 
    964         // Set rotation and gps data.
    965         Util.setRotationParameter(mParameters, mCameraId, mOrientation);
    966         Location loc = mLocationManager.getCurrentLocation();
    967         Util.setGpsParameters(mParameters, loc);
    968         mCameraDevice.setParameters(mParameters);
    969 
    970         mCameraDevice.takePicture(mShutterCallback, mRawPictureCallback,
    971                 mPostViewPictureCallback, new JpegPictureCallback(loc));
    972         mCameraState = SNAPSHOT_IN_PROGRESS;
    973         return true;
    974     }
    975 
    976     @Override
    977     public void setFocusParameters() {
    978         setCameraParameters(UPDATE_PARAM_PREFERENCE);
    979     }
    980 
    981     private boolean saveDataToFile(String filePath, byte[] data) {
    982         FileOutputStream f = null;
    983         try {
    984             f = new FileOutputStream(filePath);
    985             f.write(data);
    986         } catch (IOException e) {
    987             return false;
    988         } finally {
    989             Util.closeSilently(f);
    990         }
    991         return true;
    992     }
    993 
    994     private void getPreferredCameraId() {
    995         mPreferences = new ComboPreferences(this);
    996         CameraSettings.upgradeGlobalPreferences(mPreferences.getGlobal());
    997         mCameraId = CameraSettings.readPreferredCameraId(mPreferences);
    998 
    999         // Testing purpose. Launch a specific camera through the intent extras.
   1000         int intentCameraId = Util.getCameraFacingIntentExtras(this);
   1001         if (intentCameraId != -1) {
   1002             mCameraId = intentCameraId;
   1003         }
   1004     }
   1005 
   1006     Thread mCameraOpenThread = new Thread(new Runnable() {
   1007         public void run() {
   1008             try {
   1009                 mCameraDevice = Util.openCamera(Camera.this, mCameraId);
   1010             } catch (CameraHardwareException e) {
   1011                 mOpenCameraFail = true;
   1012             } catch (CameraDisabledException e) {
   1013                 mCameraDisabled = true;
   1014             }
   1015         }
   1016     });
   1017 
   1018     Thread mCameraPreviewThread = new Thread(new Runnable() {
   1019         public void run() {
   1020             initializeCapabilities();
   1021             startPreview();
   1022         }
   1023     });
   1024 
   1025     @Override
   1026     public void onCreate(Bundle icicle) {
   1027         super.onCreate(icicle);
   1028         getPreferredCameraId();
   1029         mFocusManager = new FocusManager(mPreferences,
   1030                 getString(R.string.pref_camera_focusmode_default));
   1031 
   1032         /*
   1033          * To reduce startup time, we start the camera open and preview threads.
   1034          * We make sure the preview is started at the end of onCreate.
   1035          */
   1036         mCameraOpenThread.start();
   1037 
   1038         mIsImageCaptureIntent = isImageCaptureIntent();
   1039         setContentView(R.layout.camera);
   1040         if (mIsImageCaptureIntent) {
   1041             mReviewDoneButton = (Rotatable) findViewById(R.id.btn_done);
   1042             mReviewCancelButton = (Rotatable) findViewById(R.id.btn_cancel);
   1043             findViewById(R.id.btn_cancel).setVisibility(View.VISIBLE);
   1044         } else {
   1045             mThumbnailView = (RotateImageView) findViewById(R.id.thumbnail);
   1046             mThumbnailView.enableFilter(false);
   1047             mThumbnailView.setVisibility(View.VISIBLE);
   1048         }
   1049 
   1050         mPreferences.setLocalId(this, mCameraId);
   1051         CameraSettings.upgradeLocalPreferences(mPreferences.getLocal());
   1052 
   1053         mNumberOfCameras = CameraHolder.instance().getNumberOfCameras();
   1054         mQuickCapture = getIntent().getBooleanExtra(EXTRA_QUICK_CAPTURE, false);
   1055 
   1056         // we need to reset exposure for the preview
   1057         resetExposureCompensation();
   1058 
   1059         Util.enterLightsOutMode(getWindow());
   1060 
   1061         // don't set mSurfaceHolder here. We have it set ONLY within
   1062         // surfaceChanged / surfaceDestroyed, other parts of the code
   1063         // assume that when it is set, the surface is also set.
   1064         SurfaceView preview = (SurfaceView) findViewById(R.id.camera_preview);
   1065         SurfaceHolder holder = preview.getHolder();
   1066         holder.addCallback(this);
   1067         holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
   1068 
   1069         // Make sure camera device is opened.
   1070         try {
   1071             mCameraOpenThread.join();
   1072             mCameraOpenThread = null;
   1073             if (mOpenCameraFail) {
   1074                 Util.showErrorAndFinish(this, R.string.cannot_connect_camera);
   1075                 return;
   1076             } else if (mCameraDisabled) {
   1077                 Util.showErrorAndFinish(this, R.string.camera_disabled);
   1078                 return;
   1079             }
   1080         } catch (InterruptedException ex) {
   1081             // ignore
   1082         }
   1083         mCameraPreviewThread.start();
   1084 
   1085         if (mIsImageCaptureIntent) {
   1086             setupCaptureParams();
   1087         } else {
   1088             mModePicker = (ModePicker) findViewById(R.id.mode_picker);
   1089             mModePicker.setVisibility(View.VISIBLE);
   1090             mModePicker.setOnModeChangeListener(this);
   1091             mModePicker.setCurrentMode(ModePicker.MODE_CAMERA);
   1092         }
   1093 
   1094         mZoomControl = (ZoomControl) findViewById(R.id.zoom_control);
   1095         mLocationManager = new LocationManager(this, this);
   1096 
   1097         mBackCameraId = CameraHolder.instance().getBackCameraId();
   1098         mFrontCameraId = CameraHolder.instance().getFrontCameraId();
   1099 
   1100         // Wait until the camera settings are retrieved.
   1101         synchronized (mCameraPreviewThread) {
   1102             try {
   1103                 mCameraPreviewThread.wait();
   1104             } catch (InterruptedException ex) {
   1105                 // ignore
   1106             }
   1107         }
   1108 
   1109         // Do this after starting preview because it depends on camera
   1110         // parameters.
   1111         initializeIndicatorControl();
   1112 
   1113         // Make sure preview is started.
   1114         try {
   1115             mCameraPreviewThread.join();
   1116         } catch (InterruptedException ex) {
   1117             // ignore
   1118         }
   1119         mCameraPreviewThread = null;
   1120     }
   1121 
   1122     private void overrideCameraSettings(final String flashMode,
   1123             final String whiteBalance, final String focusMode) {
   1124         if (mIndicatorControlContainer != null) {
   1125             mIndicatorControlContainer.overrideSettings(
   1126                     CameraSettings.KEY_FLASH_MODE, flashMode,
   1127                     CameraSettings.KEY_WHITE_BALANCE, whiteBalance,
   1128                     CameraSettings.KEY_FOCUS_MODE, focusMode);
   1129         }
   1130     }
   1131 
   1132     private void updateSceneModeUI() {
   1133         // If scene mode is set, we cannot set flash mode, white balance, and
   1134         // focus mode, instead, we read it from driver
   1135         if (!Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) {
   1136             overrideCameraSettings(mParameters.getFlashMode(),
   1137                     mParameters.getWhiteBalance(), mParameters.getFocusMode());
   1138         } else {
   1139             overrideCameraSettings(null, null, null);
   1140         }
   1141     }
   1142 
   1143     private void loadCameraPreferences() {
   1144         CameraSettings settings = new CameraSettings(this, mInitialParams,
   1145                 mCameraId, CameraHolder.instance().getCameraInfo());
   1146         mPreferenceGroup = settings.getPreferenceGroup(R.xml.camera_preferences);
   1147     }
   1148 
   1149     private void initializeIndicatorControl() {
   1150         // setting the indicator buttons.
   1151         mIndicatorControlContainer =
   1152                 (IndicatorControlContainer) findViewById(R.id.indicator_control);
   1153         if (mIndicatorControlContainer == null) return;
   1154         loadCameraPreferences();
   1155         final String[] SETTING_KEYS = {
   1156                 CameraSettings.KEY_FLASH_MODE,
   1157                 CameraSettings.KEY_WHITE_BALANCE,
   1158                 CameraSettings.KEY_EXPOSURE,
   1159                 CameraSettings.KEY_SCENE_MODE};
   1160         final String[] OTHER_SETTING_KEYS = {
   1161                 CameraSettings.KEY_RECORD_LOCATION,
   1162                 CameraSettings.KEY_PICTURE_SIZE,
   1163                 CameraSettings.KEY_FOCUS_MODE};
   1164 
   1165         CameraPicker.setImageResourceId(R.drawable.ic_switch_photo_facing_holo_light);
   1166         mIndicatorControlContainer.initialize(this, mPreferenceGroup,
   1167                 mParameters.isZoomSupported(),
   1168                 SETTING_KEYS, OTHER_SETTING_KEYS);
   1169         updateSceneModeUI();
   1170         mIndicatorControlContainer.setListener(this);
   1171     }
   1172 
   1173     private boolean collapseCameraControls() {
   1174         if ((mIndicatorControlContainer != null)
   1175                 && mIndicatorControlContainer.dismissSettingPopup()) {
   1176             return true;
   1177         }
   1178         return false;
   1179     }
   1180 
   1181     private void enableCameraControls(boolean enable) {
   1182         if (mIndicatorControlContainer != null) {
   1183             mIndicatorControlContainer.setEnabled(enable);
   1184         }
   1185         if (mModePicker != null) mModePicker.setEnabled(enable);
   1186         if (mZoomControl != null) mZoomControl.setEnabled(enable);
   1187         if (mThumbnailView != null) mThumbnailView.setEnabled(enable);
   1188     }
   1189 
   1190     private class MyOrientationEventListener
   1191             extends OrientationEventListener {
   1192         public MyOrientationEventListener(Context context) {
   1193             super(context);
   1194         }
   1195 
   1196         @Override
   1197         public void onOrientationChanged(int orientation) {
   1198             // We keep the last known orientation. So if the user first orient
   1199             // the camera then point the camera to floor or sky, we still have
   1200             // the correct orientation.
   1201             if (orientation == ORIENTATION_UNKNOWN) return;
   1202             mOrientation = Util.roundOrientation(orientation, mOrientation);
   1203             // When the screen is unlocked, display rotation may change. Always
   1204             // calculate the up-to-date orientationCompensation.
   1205             int orientationCompensation = mOrientation
   1206                     + Util.getDisplayRotation(Camera.this);
   1207             if (mOrientationCompensation != orientationCompensation) {
   1208                 mOrientationCompensation = orientationCompensation;
   1209                 setOrientationIndicator(mOrientationCompensation);
   1210             }
   1211 
   1212             // Show the toast after getting the first orientation changed.
   1213             if (mHandler.hasMessages(SHOW_TAP_TO_FOCUS_TOAST)) {
   1214                 mHandler.removeMessages(SHOW_TAP_TO_FOCUS_TOAST);
   1215                 showTapToFocusToast();
   1216             }
   1217         }
   1218     }
   1219 
   1220     private void setOrientationIndicator(int degree) {
   1221         if (mThumbnailView != null) mThumbnailView.setDegree(degree);
   1222         if (mModePicker != null) mModePicker.setDegree(degree);
   1223         if (mSharePopup != null) mSharePopup.setOrientation(degree);
   1224         if (mIndicatorControlContainer != null) mIndicatorControlContainer.setDegree(degree);
   1225         if (mZoomControl != null) mZoomControl.setDegree(degree);
   1226         if (mFocusIndicator != null) mFocusIndicator.setOrientation(degree);
   1227         if (mFaceView != null) mFaceView.setOrientation(degree);
   1228         if (mReviewCancelButton != null) mReviewCancelButton.setOrientation(degree);
   1229         if (mReviewDoneButton != null) mReviewDoneButton.setOrientation(degree);
   1230     }
   1231 
   1232     @Override
   1233     public void onStop() {
   1234         super.onStop();
   1235         if (mMediaProviderClient != null) {
   1236             mMediaProviderClient.release();
   1237             mMediaProviderClient = null;
   1238         }
   1239     }
   1240 
   1241     private void checkStorage() {
   1242         mPicturesRemaining = Storage.getAvailableSpace();
   1243         if (mPicturesRemaining > Storage.LOW_STORAGE_THRESHOLD) {
   1244             mPicturesRemaining = (mPicturesRemaining - Storage.LOW_STORAGE_THRESHOLD)
   1245                     / Storage.PICTURE_SIZE;
   1246         } else if (mPicturesRemaining > 0) {
   1247             mPicturesRemaining = 0;
   1248         }
   1249 
   1250         updateStorageHint();
   1251     }
   1252 
   1253     @OnClickAttr
   1254     public void onThumbnailClicked(View v) {
   1255         if (isCameraIdle() && mThumbnail != null) {
   1256             showSharePopup();
   1257         }
   1258     }
   1259 
   1260     @OnClickAttr
   1261     public void onReviewRetakeClicked(View v) {
   1262         hidePostCaptureAlert();
   1263         startPreview();
   1264         startFaceDetection();
   1265     }
   1266 
   1267     @OnClickAttr
   1268     public void onReviewDoneClicked(View v) {
   1269         doAttach();
   1270     }
   1271 
   1272     @OnClickAttr
   1273     public void onReviewCancelClicked(View v) {
   1274         doCancel();
   1275     }
   1276 
   1277     private void doAttach() {
   1278         if (mPausing) {
   1279             return;
   1280         }
   1281 
   1282         byte[] data = mJpegImageData;
   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                     setResultEx(RESULT_OK);
   1297                     finish();
   1298                 } catch (IOException ex) {
   1299                     // ignore exception
   1300                 } finally {
   1301                     Util.closeSilently(outputStream);
   1302                 }
   1303             } else {
   1304                 int orientation = Exif.getOrientation(data);
   1305                 Bitmap bitmap = Util.makeBitmap(data, 50 * 1024);
   1306                 bitmap = Util.rotate(bitmap, orientation);
   1307                 setResultEx(RESULT_OK,
   1308                         new Intent("inline-data").putExtra("data", bitmap));
   1309                 finish();
   1310             }
   1311         } else {
   1312             // Save the image to a temp file and invoke the cropper
   1313             Uri tempUri = null;
   1314             FileOutputStream tempStream = null;
   1315             try {
   1316                 File path = getFileStreamPath(sTempCropFilename);
   1317                 path.delete();
   1318                 tempStream = openFileOutput(sTempCropFilename, 0);
   1319                 tempStream.write(data);
   1320                 tempStream.close();
   1321                 tempUri = Uri.fromFile(path);
   1322             } catch (FileNotFoundException ex) {
   1323                 setResultEx(Activity.RESULT_CANCELED);
   1324                 finish();
   1325                 return;
   1326             } catch (IOException ex) {
   1327                 setResultEx(Activity.RESULT_CANCELED);
   1328                 finish();
   1329                 return;
   1330             } finally {
   1331                 Util.closeSilently(tempStream);
   1332             }
   1333 
   1334             Bundle newExtras = new Bundle();
   1335             if (mCropValue.equals("circle")) {
   1336                 newExtras.putString("circleCrop", "true");
   1337             }
   1338             if (mSaveUri != null) {
   1339                 newExtras.putParcelable(MediaStore.EXTRA_OUTPUT, mSaveUri);
   1340             } else {
   1341                 newExtras.putBoolean("return-data", true);
   1342             }
   1343 
   1344             Intent cropIntent = new Intent("com.android.camera.action.CROP");
   1345 
   1346             cropIntent.setData(tempUri);
   1347             cropIntent.putExtras(newExtras);
   1348 
   1349             startActivityForResult(cropIntent, CROP_MSG);
   1350         }
   1351     }
   1352 
   1353     private void doCancel() {
   1354         setResultEx(RESULT_CANCELED, new Intent());
   1355         finish();
   1356     }
   1357 
   1358     @Override
   1359     public void onShutterButtonFocus(boolean pressed) {
   1360         if (mPausing || collapseCameraControls() || mCameraState == SNAPSHOT_IN_PROGRESS) return;
   1361 
   1362         // Do not do focus if there is not enough storage.
   1363         if (pressed && !canTakePicture()) return;
   1364 
   1365         if (pressed) {
   1366             mFocusManager.onShutterDown();
   1367         } else {
   1368             mFocusManager.onShutterUp();
   1369         }
   1370     }
   1371 
   1372     @Override
   1373     public void onShutterButtonClick() {
   1374         if (mPausing || collapseCameraControls()) return;
   1375 
   1376         // Do not take the picture if there is not enough storage.
   1377         if (mPicturesRemaining <= 0) {
   1378             Log.i(TAG, "Not enough space or storage not ready. remaining=" + mPicturesRemaining);
   1379             return;
   1380         }
   1381 
   1382         Log.v(TAG, "onShutterButtonClick: mCameraState=" + mCameraState);
   1383 
   1384         // If the user wants to do a snapshot while the previous one is still
   1385         // in progress, remember the fact and do it after we finish the previous
   1386         // one and re-start the preview.
   1387         if (mCameraState == SNAPSHOT_IN_PROGRESS) {
   1388             mSnapshotOnIdle = true;
   1389             return;
   1390         }
   1391 
   1392         mSnapshotOnIdle = false;
   1393         mFocusManager.doSnap();
   1394     }
   1395 
   1396     @Override
   1397     public void onShutterButtonLongPressed() {
   1398         if (mPausing || mCameraState == SNAPSHOT_IN_PROGRESS
   1399                 || mCameraDevice == null || mPicturesRemaining <= 0) return;
   1400 
   1401         Log.v(TAG, "onShutterButtonLongPressed");
   1402         mFocusManager.shutterLongPressed();
   1403     }
   1404 
   1405     private OnScreenHint mStorageHint;
   1406 
   1407     private void updateStorageHint() {
   1408         String noStorageText = null;
   1409 
   1410         if (mPicturesRemaining == Storage.UNAVAILABLE) {
   1411             noStorageText = getString(R.string.no_storage);
   1412         } else if (mPicturesRemaining == Storage.PREPARING) {
   1413             noStorageText = getString(R.string.preparing_sd);
   1414         } else if (mPicturesRemaining == Storage.UNKNOWN_SIZE) {
   1415             noStorageText = getString(R.string.access_sd_fail);
   1416         } else if (mPicturesRemaining < 1L) {
   1417             noStorageText = getString(R.string.not_enough_space);
   1418         }
   1419 
   1420         if (noStorageText != null) {
   1421             if (mStorageHint == null) {
   1422                 mStorageHint = OnScreenHint.makeText(this, noStorageText);
   1423             } else {
   1424                 mStorageHint.setText(noStorageText);
   1425             }
   1426             mStorageHint.show();
   1427         } else if (mStorageHint != null) {
   1428             mStorageHint.cancel();
   1429             mStorageHint = null;
   1430         }
   1431     }
   1432 
   1433     private void installIntentFilter() {
   1434         // install an intent filter to receive SD card related events.
   1435         IntentFilter intentFilter =
   1436                 new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);
   1437         intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
   1438         intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
   1439         intentFilter.addAction(Intent.ACTION_MEDIA_CHECKING);
   1440         intentFilter.addDataScheme("file");
   1441         registerReceiver(mReceiver, intentFilter);
   1442         mDidRegister = true;
   1443     }
   1444 
   1445     @Override
   1446     protected void doOnResume() {
   1447         if (mOpenCameraFail || mCameraDisabled) return;
   1448 
   1449         mPausing = false;
   1450 
   1451         mJpegPictureCallbackTime = 0;
   1452         mZoomValue = 0;
   1453 
   1454         // Start the preview if it is not started.
   1455         if (mCameraState == PREVIEW_STOPPED) {
   1456             try {
   1457                 mCameraDevice = Util.openCamera(this, mCameraId);
   1458                 initializeCapabilities();
   1459                 resetExposureCompensation();
   1460                 startPreview();
   1461                 if (mFirstTimeInitialized) startFaceDetection();
   1462             } catch (CameraHardwareException e) {
   1463                 Util.showErrorAndFinish(this, R.string.cannot_connect_camera);
   1464                 return;
   1465             } catch (CameraDisabledException e) {
   1466                 Util.showErrorAndFinish(this, R.string.camera_disabled);
   1467                 return;
   1468             }
   1469         }
   1470 
   1471         if (mSurfaceHolder != null) {
   1472             // If first time initialization is not finished, put it in the
   1473             // message queue.
   1474             if (!mFirstTimeInitialized) {
   1475                 mHandler.sendEmptyMessage(FIRST_TIME_INIT);
   1476             } else {
   1477                 initializeSecondTime();
   1478             }
   1479         }
   1480         keepScreenOnAwhile();
   1481 
   1482         if (mCameraState == IDLE) {
   1483             mOnResumeTime = SystemClock.uptimeMillis();
   1484             mHandler.sendEmptyMessageDelayed(CHECK_DISPLAY_ROTATION, 100);
   1485         }
   1486     }
   1487 
   1488     @Override
   1489     protected void onPause() {
   1490         mPausing = true;
   1491         stopPreview();
   1492         // Close the camera now because other activities may need to use it.
   1493         closeCamera();
   1494         resetScreenOn();
   1495 
   1496         // Clear UI.
   1497         collapseCameraControls();
   1498         if (mSharePopup != null) mSharePopup.dismiss();
   1499         if (mFaceView != null) mFaceView.clear();
   1500 
   1501         if (mFirstTimeInitialized) {
   1502             mOrientationListener.disable();
   1503             if (mImageSaver != null) {
   1504                 mImageSaver.finish();
   1505                 mImageSaver = null;
   1506             }
   1507             if (!mIsImageCaptureIntent && mThumbnail != null && !mThumbnail.fromFile()) {
   1508                 mThumbnail.saveTo(new File(getFilesDir(), Thumbnail.LAST_THUMB_FILENAME));
   1509             }
   1510         }
   1511 
   1512         if (mDidRegister) {
   1513             unregisterReceiver(mReceiver);
   1514             mDidRegister = false;
   1515         }
   1516         if (mLocationManager != null) mLocationManager.recordLocation(false);
   1517         updateExposureOnScreenIndicator(0);
   1518 
   1519         mFocusManager.releaseSoundPlayer();
   1520 
   1521         if (mStorageHint != null) {
   1522             mStorageHint.cancel();
   1523             mStorageHint = null;
   1524         }
   1525 
   1526         // If we are in an image capture intent and has taken
   1527         // a picture, we just clear it in onPause.
   1528         mJpegImageData = null;
   1529 
   1530         // Remove the messages in the event queue.
   1531         mHandler.removeMessages(FIRST_TIME_INIT);
   1532         mHandler.removeMessages(CHECK_DISPLAY_ROTATION);
   1533         mFocusManager.removeMessages();
   1534 
   1535         super.onPause();
   1536     }
   1537 
   1538     @Override
   1539     protected void onActivityResult(
   1540             int requestCode, int resultCode, Intent data) {
   1541         switch (requestCode) {
   1542             case CROP_MSG: {
   1543                 Intent intent = new Intent();
   1544                 if (data != null) {
   1545                     Bundle extras = data.getExtras();
   1546                     if (extras != null) {
   1547                         intent.putExtras(extras);
   1548                     }
   1549                 }
   1550                 setResultEx(resultCode, intent);
   1551                 finish();
   1552 
   1553                 File path = getFileStreamPath(sTempCropFilename);
   1554                 path.delete();
   1555 
   1556                 break;
   1557             }
   1558         }
   1559     }
   1560 
   1561     private boolean canTakePicture() {
   1562         return isCameraIdle() && (mPicturesRemaining > 0);
   1563     }
   1564 
   1565     @Override
   1566     public void autoFocus() {
   1567         mFocusStartTime = System.currentTimeMillis();
   1568         mCameraDevice.autoFocus(mAutoFocusCallback);
   1569         mCameraState = FOCUSING;
   1570         enableCameraControls(false);
   1571     }
   1572 
   1573     @Override
   1574     public void cancelAutoFocus() {
   1575         mCameraDevice.cancelAutoFocus();
   1576         mCameraState = IDLE;
   1577         enableCameraControls(true);
   1578         setCameraParameters(UPDATE_PARAM_PREFERENCE);
   1579     }
   1580 
   1581     // Preview area is touched. Handle touch focus.
   1582     @Override
   1583     public boolean onTouch(View v, MotionEvent e) {
   1584         if (mPausing || mCameraDevice == null || !mFirstTimeInitialized
   1585                 || mCameraState == SNAPSHOT_IN_PROGRESS) {
   1586             return false;
   1587         }
   1588 
   1589         // Do not trigger touch focus if popup window is opened.
   1590         if (collapseCameraControls()) return false;
   1591 
   1592         // Check if metering area or focus area is supported.
   1593         if (!mFocusAreaSupported && !mMeteringAreaSupported) return false;
   1594 
   1595         return mFocusManager.onTouch(e);
   1596     }
   1597 
   1598     @Override
   1599     public void onBackPressed() {
   1600         if (!isCameraIdle()) {
   1601             // ignore backs while we're taking a picture
   1602             return;
   1603         } else if (!collapseCameraControls()) {
   1604             super.onBackPressed();
   1605         }
   1606     }
   1607 
   1608     @Override
   1609     public boolean onKeyDown(int keyCode, KeyEvent event) {
   1610         switch (keyCode) {
   1611             case KeyEvent.KEYCODE_FOCUS:
   1612                 if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
   1613                     onShutterButtonFocus(true);
   1614                 }
   1615                 return true;
   1616             case KeyEvent.KEYCODE_CAMERA:
   1617                 if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
   1618                     onShutterButtonClick();
   1619                 }
   1620                 return true;
   1621             case KeyEvent.KEYCODE_DPAD_CENTER:
   1622                 // If we get a dpad center event without any focused view, move
   1623                 // the focus to the shutter button and press it.
   1624                 if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
   1625                     // Start auto-focus immediately to reduce shutter lag. After
   1626                     // the shutter button gets the focus, onShutterButtonFocus()
   1627                     // will be called again but it is fine.
   1628                     if (collapseCameraControls()) return true;
   1629                     onShutterButtonFocus(true);
   1630                     if (mShutterButton.isInTouchMode()) {
   1631                         mShutterButton.requestFocusFromTouch();
   1632                     } else {
   1633                         mShutterButton.requestFocus();
   1634                     }
   1635                     mShutterButton.setPressed(true);
   1636                 }
   1637                 return true;
   1638         }
   1639 
   1640         return super.onKeyDown(keyCode, event);
   1641     }
   1642 
   1643     @Override
   1644     public boolean onKeyUp(int keyCode, KeyEvent event) {
   1645         switch (keyCode) {
   1646             case KeyEvent.KEYCODE_FOCUS:
   1647                 if (mFirstTimeInitialized) {
   1648                     onShutterButtonFocus(false);
   1649                 }
   1650                 return true;
   1651         }
   1652         return super.onKeyUp(keyCode, event);
   1653     }
   1654 
   1655     public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
   1656         // Make sure we have a surface in the holder before proceeding.
   1657         if (holder.getSurface() == null) {
   1658             Log.d(TAG, "holder.getSurface() == null");
   1659             return;
   1660         }
   1661 
   1662         Log.v(TAG, "surfaceChanged. w=" + w + ". h=" + h);
   1663 
   1664         // We need to save the holder for later use, even when the mCameraDevice
   1665         // is null. This could happen if onResume() is invoked after this
   1666         // function.
   1667         mSurfaceHolder = holder;
   1668 
   1669         // The mCameraDevice will be null if it fails to connect to the camera
   1670         // hardware. In this case we will show a dialog and then finish the
   1671         // activity, so it's OK to ignore it.
   1672         if (mCameraDevice == null) return;
   1673 
   1674         // Sometimes surfaceChanged is called after onPause or before onResume.
   1675         // Ignore it.
   1676         if (mPausing || isFinishing()) return;
   1677 
   1678         // Set preview display if the surface is being created. Preview was
   1679         // already started. Also restart the preview if display rotation has
   1680         // changed. Sometimes this happens when the device is held in portrait
   1681         // and camera app is opened. Rotation animation takes some time and
   1682         // display rotation in onCreate may not be what we want.
   1683         if (mCameraState == PREVIEW_STOPPED) {
   1684             startPreview();
   1685             if (mFirstTimeInitialized) startFaceDetection();
   1686         } else {
   1687             if (Util.getDisplayRotation(this) != mDisplayRotation) {
   1688                 setDisplayOrientation();
   1689             }
   1690             if (holder.isCreating()) {
   1691                 // Set preview display if the surface is being created and preview
   1692                 // was already started. That means preview display was set to null
   1693                 // and we need to set it now.
   1694                 setPreviewDisplay(holder);
   1695             }
   1696         }
   1697 
   1698         // If first time initialization is not finished, send a message to do
   1699         // it later. We want to finish surfaceChanged as soon as possible to let
   1700         // user see preview first.
   1701         if (!mFirstTimeInitialized) {
   1702             mHandler.sendEmptyMessage(FIRST_TIME_INIT);
   1703         } else {
   1704             initializeSecondTime();
   1705         }
   1706     }
   1707 
   1708     public void surfaceCreated(SurfaceHolder holder) {
   1709     }
   1710 
   1711     public void surfaceDestroyed(SurfaceHolder holder) {
   1712         stopPreview();
   1713         mSurfaceHolder = null;
   1714     }
   1715 
   1716     private void closeCamera() {
   1717         if (mCameraDevice != null) {
   1718             CameraHolder.instance().release();
   1719             mCameraDevice.setZoomChangeListener(null);
   1720             mCameraDevice.setFaceDetectionListener(null);
   1721             mCameraDevice.setErrorCallback(null);
   1722             mCameraDevice = null;
   1723             mCameraState = PREVIEW_STOPPED;
   1724             mFocusManager.onCameraReleased();
   1725         }
   1726     }
   1727 
   1728     private void setPreviewDisplay(SurfaceHolder holder) {
   1729         try {
   1730             mCameraDevice.setPreviewDisplay(holder);
   1731         } catch (Throwable ex) {
   1732             closeCamera();
   1733             throw new RuntimeException("setPreviewDisplay failed", ex);
   1734         }
   1735     }
   1736 
   1737     private void setDisplayOrientation() {
   1738         mDisplayRotation = Util.getDisplayRotation(this);
   1739         mDisplayOrientation = Util.getDisplayOrientation(mDisplayRotation, mCameraId);
   1740         mCameraDevice.setDisplayOrientation(mDisplayOrientation);
   1741         if (mFaceView != null) {
   1742             mFaceView.setDisplayOrientation(mDisplayOrientation);
   1743         }
   1744     }
   1745 
   1746     private void startPreview() {
   1747         if (mPausing || isFinishing()) return;
   1748 
   1749         mFocusManager.resetTouchFocus();
   1750 
   1751         mCameraDevice.setErrorCallback(mErrorCallback);
   1752 
   1753         // If we're previewing already, stop the preview first (this will blank
   1754         // the screen).
   1755         if (mCameraState != PREVIEW_STOPPED) stopPreview();
   1756 
   1757         setPreviewDisplay(mSurfaceHolder);
   1758         setDisplayOrientation();
   1759 
   1760         mFocusManager.setAeAwbLock(false); // Unlock AE and AWB.
   1761         setCameraParameters(UPDATE_PARAM_ALL);
   1762         // If the focus mode is continuous autofocus, call cancelAutoFocus to
   1763         // resume it because it may have been paused by autoFocus call.
   1764         if (Parameters.FOCUS_MODE_CONTINUOUS_PICTURE.equals(mParameters.getFocusMode())) {
   1765             mCameraDevice.cancelAutoFocus();
   1766         }
   1767 
   1768         // Inform the mainthread to go on the UI initialization.
   1769         if (mCameraPreviewThread != null) {
   1770             synchronized (mCameraPreviewThread) {
   1771                 mCameraPreviewThread.notify();
   1772             }
   1773         }
   1774 
   1775         try {
   1776             Log.v(TAG, "startPreview");
   1777             mCameraDevice.startPreview();
   1778         } catch (Throwable ex) {
   1779             closeCamera();
   1780             throw new RuntimeException("startPreview failed", ex);
   1781         }
   1782 
   1783         mZoomState = ZOOM_STOPPED;
   1784         mCameraState = IDLE;
   1785         mFocusManager.onPreviewStarted();
   1786 
   1787         if (mSnapshotOnIdle) {
   1788             mHandler.post(mDoSnapRunnable);
   1789         }
   1790     }
   1791 
   1792     private void stopPreview() {
   1793         if (mCameraDevice != null && mCameraState != PREVIEW_STOPPED) {
   1794             Log.v(TAG, "stopPreview");
   1795             mCameraDevice.cancelAutoFocus(); // Reset the focus.
   1796             mCameraDevice.stopPreview();
   1797         }
   1798         mCameraState = PREVIEW_STOPPED;
   1799         mFocusManager.onPreviewStopped();
   1800     }
   1801 
   1802     private static boolean isSupported(String value, List<String> supported) {
   1803         return supported == null ? false : supported.indexOf(value) >= 0;
   1804     }
   1805 
   1806     private void updateCameraParametersInitialize() {
   1807         // Reset preview frame rate to the maximum because it may be lowered by
   1808         // video camera application.
   1809         List<Integer> frameRates = mParameters.getSupportedPreviewFrameRates();
   1810         if (frameRates != null) {
   1811             Integer max = Collections.max(frameRates);
   1812             mParameters.setPreviewFrameRate(max);
   1813         }
   1814 
   1815         mParameters.setRecordingHint(false);
   1816 
   1817         // Disable video stabilization. Convenience methods not available in API
   1818         // level <= 14
   1819         String vstabSupported = mParameters.get("video-stabilization-supported");
   1820         if ("true".equals(vstabSupported)) {
   1821             mParameters.set("video-stabilization", "false");
   1822         }
   1823     }
   1824 
   1825     private void updateCameraParametersZoom() {
   1826         // Set zoom.
   1827         if (mParameters.isZoomSupported()) {
   1828             mParameters.setZoom(mZoomValue);
   1829         }
   1830     }
   1831 
   1832     private void updateCameraParametersPreference() {
   1833         if (mAeLockSupported) {
   1834             mParameters.setAutoExposureLock(mFocusManager.getAeAwbLock());
   1835         }
   1836 
   1837         if (mAwbLockSupported) {
   1838             mParameters.setAutoWhiteBalanceLock(mFocusManager.getAeAwbLock());
   1839         }
   1840 
   1841         if (mFocusAreaSupported) {
   1842             mParameters.setFocusAreas(mFocusManager.getFocusAreas());
   1843         }
   1844 
   1845         if (mMeteringAreaSupported) {
   1846             // Use the same area for focus and metering.
   1847             mParameters.setMeteringAreas(mFocusManager.getMeteringAreas());
   1848         }
   1849 
   1850         // Set picture size.
   1851         String pictureSize = mPreferences.getString(
   1852                 CameraSettings.KEY_PICTURE_SIZE, null);
   1853         if (pictureSize == null) {
   1854             CameraSettings.initialCameraPictureSize(this, mParameters);
   1855         } else {
   1856             List<Size> supported = mParameters.getSupportedPictureSizes();
   1857             CameraSettings.setCameraPictureSize(
   1858                     pictureSize, supported, mParameters);
   1859         }
   1860 
   1861         // Set the preview frame aspect ratio according to the picture size.
   1862         Size size = mParameters.getPictureSize();
   1863 
   1864         mPreviewPanel = findViewById(R.id.frame_layout);
   1865         mPreviewFrameLayout = (PreviewFrameLayout) findViewById(R.id.frame);
   1866         mPreviewFrameLayout.setAspectRatio((double) size.width / size.height);
   1867 
   1868         // Set a preview size that is closest to the viewfinder height and has
   1869         // the right aspect ratio.
   1870         List<Size> sizes = mParameters.getSupportedPreviewSizes();
   1871         Size optimalSize = Util.getOptimalPreviewSize(this,
   1872                 sizes, (double) size.width / size.height);
   1873         Size original = mParameters.getPreviewSize();
   1874         if (!original.equals(optimalSize)) {
   1875             mParameters.setPreviewSize(optimalSize.width, optimalSize.height);
   1876 
   1877             // Zoom related settings will be changed for different preview
   1878             // sizes, so set and read the parameters to get lastest values
   1879             mCameraDevice.setParameters(mParameters);
   1880             mParameters = mCameraDevice.getParameters();
   1881         }
   1882         Log.v(TAG, "Preview size is " + optimalSize.width + "x" + optimalSize.height);
   1883 
   1884         // Since change scene mode may change supported values,
   1885         // Set scene mode first,
   1886         mSceneMode = mPreferences.getString(
   1887                 CameraSettings.KEY_SCENE_MODE,
   1888                 getString(R.string.pref_camera_scenemode_default));
   1889         if (isSupported(mSceneMode, mParameters.getSupportedSceneModes())) {
   1890             if (!mParameters.getSceneMode().equals(mSceneMode)) {
   1891                 mParameters.setSceneMode(mSceneMode);
   1892                 mCameraDevice.setParameters(mParameters);
   1893 
   1894                 // Setting scene mode will change the settings of flash mode,
   1895                 // white balance, and focus mode. Here we read back the
   1896                 // parameters, so we can know those settings.
   1897                 mParameters = mCameraDevice.getParameters();
   1898             }
   1899         } else {
   1900             mSceneMode = mParameters.getSceneMode();
   1901             if (mSceneMode == null) {
   1902                 mSceneMode = Parameters.SCENE_MODE_AUTO;
   1903             }
   1904         }
   1905 
   1906         // Set JPEG quality.
   1907         int jpegQuality = CameraProfile.getJpegEncodingQualityParameter(mCameraId,
   1908                 CameraProfile.QUALITY_HIGH);
   1909         mParameters.setJpegQuality(jpegQuality);
   1910 
   1911         // For the following settings, we need to check if the settings are
   1912         // still supported by latest driver, if not, ignore the settings.
   1913 
   1914         // Set exposure compensation
   1915         int value = CameraSettings.readExposure(mPreferences);
   1916         int max = mParameters.getMaxExposureCompensation();
   1917         int min = mParameters.getMinExposureCompensation();
   1918         if (value >= min && value <= max) {
   1919             mParameters.setExposureCompensation(value);
   1920         } else {
   1921             Log.w(TAG, "invalid exposure range: " + value);
   1922         }
   1923 
   1924         if (Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) {
   1925             // Set flash mode.
   1926             String flashMode = mPreferences.getString(
   1927                     CameraSettings.KEY_FLASH_MODE,
   1928                     getString(R.string.pref_camera_flashmode_default));
   1929             List<String> supportedFlash = mParameters.getSupportedFlashModes();
   1930             if (isSupported(flashMode, supportedFlash)) {
   1931                 mParameters.setFlashMode(flashMode);
   1932             } else {
   1933                 flashMode = mParameters.getFlashMode();
   1934                 if (flashMode == null) {
   1935                     flashMode = getString(
   1936                             R.string.pref_camera_flashmode_no_flash);
   1937                 }
   1938             }
   1939 
   1940             // Set white balance parameter.
   1941             String whiteBalance = mPreferences.getString(
   1942                     CameraSettings.KEY_WHITE_BALANCE,
   1943                     getString(R.string.pref_camera_whitebalance_default));
   1944             if (isSupported(whiteBalance,
   1945                     mParameters.getSupportedWhiteBalance())) {
   1946                 mParameters.setWhiteBalance(whiteBalance);
   1947             } else {
   1948                 whiteBalance = mParameters.getWhiteBalance();
   1949                 if (whiteBalance == null) {
   1950                     whiteBalance = Parameters.WHITE_BALANCE_AUTO;
   1951                 }
   1952             }
   1953 
   1954             // Set focus mode.
   1955             mFocusManager.overrideFocusMode(null);
   1956             mParameters.setFocusMode(mFocusManager.getFocusMode());
   1957         } else {
   1958             mFocusManager.overrideFocusMode(mParameters.getFocusMode());
   1959         }
   1960     }
   1961 
   1962     // We separate the parameters into several subsets, so we can update only
   1963     // the subsets actually need updating. The PREFERENCE set needs extra
   1964     // locking because the preference can be changed from GLThread as well.
   1965     private void setCameraParameters(int updateSet) {
   1966         mParameters = mCameraDevice.getParameters();
   1967 
   1968         if ((updateSet & UPDATE_PARAM_INITIALIZE) != 0) {
   1969             updateCameraParametersInitialize();
   1970         }
   1971 
   1972         if ((updateSet & UPDATE_PARAM_ZOOM) != 0) {
   1973             updateCameraParametersZoom();
   1974         }
   1975 
   1976         if ((updateSet & UPDATE_PARAM_PREFERENCE) != 0) {
   1977             updateCameraParametersPreference();
   1978         }
   1979 
   1980         mCameraDevice.setParameters(mParameters);
   1981     }
   1982 
   1983     // If the Camera is idle, update the parameters immediately, otherwise
   1984     // accumulate them in mUpdateSet and update later.
   1985     private void setCameraParametersWhenIdle(int additionalUpdateSet) {
   1986         mUpdateSet |= additionalUpdateSet;
   1987         if (mCameraDevice == null) {
   1988             // We will update all the parameters when we open the device, so
   1989             // we don't need to do anything now.
   1990             mUpdateSet = 0;
   1991             return;
   1992         } else if (isCameraIdle()) {
   1993             setCameraParameters(mUpdateSet);
   1994             updateSceneModeUI();
   1995             mUpdateSet = 0;
   1996         } else {
   1997             if (!mHandler.hasMessages(SET_CAMERA_PARAMETERS_WHEN_IDLE)) {
   1998                 mHandler.sendEmptyMessageDelayed(
   1999                         SET_CAMERA_PARAMETERS_WHEN_IDLE, 1000);
   2000             }
   2001         }
   2002     }
   2003 
   2004     private void gotoGallery() {
   2005         MenuHelper.gotoCameraImageGallery(this);
   2006     }
   2007 
   2008     private boolean isCameraIdle() {
   2009         return (mCameraState == IDLE) || (mFocusManager.isFocusCompleted());
   2010     }
   2011 
   2012     private boolean isImageCaptureIntent() {
   2013         String action = getIntent().getAction();
   2014         return (MediaStore.ACTION_IMAGE_CAPTURE.equals(action));
   2015     }
   2016 
   2017     private void setupCaptureParams() {
   2018         Bundle myExtras = getIntent().getExtras();
   2019         if (myExtras != null) {
   2020             mSaveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT);
   2021             mCropValue = myExtras.getString("crop");
   2022         }
   2023     }
   2024 
   2025     private void showPostCaptureAlert() {
   2026         if (mIsImageCaptureIntent) {
   2027             Util.fadeOut(mIndicatorControlContainer);
   2028             Util.fadeOut(mShutterButton);
   2029 
   2030             int[] pickIds = {R.id.btn_retake, R.id.btn_done};
   2031             for (int id : pickIds) {
   2032                 Util.fadeIn(findViewById(id));
   2033             }
   2034         }
   2035     }
   2036 
   2037     private void hidePostCaptureAlert() {
   2038         if (mIsImageCaptureIntent) {
   2039             enableCameraControls(true);
   2040 
   2041             int[] pickIds = {R.id.btn_retake, R.id.btn_done};
   2042             for (int id : pickIds) {
   2043                 Util.fadeOut(findViewById(id));
   2044             }
   2045 
   2046             Util.fadeIn(mShutterButton);
   2047             Util.fadeIn(mIndicatorControlContainer);
   2048         }
   2049     }
   2050 
   2051     @Override
   2052     public boolean onPrepareOptionsMenu(Menu menu) {
   2053         super.onPrepareOptionsMenu(menu);
   2054         // Only show the menu when camera is idle.
   2055         for (int i = 0; i < menu.size(); i++) {
   2056             menu.getItem(i).setVisible(isCameraIdle());
   2057         }
   2058 
   2059         return true;
   2060     }
   2061 
   2062     @Override
   2063     public boolean onCreateOptionsMenu(Menu menu) {
   2064         super.onCreateOptionsMenu(menu);
   2065 
   2066         if (mIsImageCaptureIntent) {
   2067             // No options menu for attach mode.
   2068             return false;
   2069         } else {
   2070             addBaseMenuItems(menu);
   2071         }
   2072         return true;
   2073     }
   2074 
   2075     private void addBaseMenuItems(Menu menu) {
   2076         MenuHelper.addSwitchModeMenuItem(menu, ModePicker.MODE_VIDEO, new Runnable() {
   2077             public void run() {
   2078                 switchToOtherMode(ModePicker.MODE_VIDEO);
   2079             }
   2080         });
   2081         MenuHelper.addSwitchModeMenuItem(menu, ModePicker.MODE_PANORAMA, new Runnable() {
   2082             public void run() {
   2083                 switchToOtherMode(ModePicker.MODE_PANORAMA);
   2084             }
   2085         });
   2086 
   2087         if (mNumberOfCameras > 1) {
   2088             menu.add(R.string.switch_camera_id)
   2089                     .setOnMenuItemClickListener(new OnMenuItemClickListener() {
   2090                 public boolean onMenuItemClick(MenuItem item) {
   2091                     CameraSettings.writePreferredCameraId(mPreferences,
   2092                             ((mCameraId == mFrontCameraId)
   2093                             ? mBackCameraId : mFrontCameraId));
   2094                     onSharedPreferenceChanged();
   2095                     return true;
   2096                 }
   2097             }).setIcon(android.R.drawable.ic_menu_camera);
   2098         }
   2099     }
   2100 
   2101     private boolean switchToOtherMode(int mode) {
   2102         if (isFinishing()) return false;
   2103         if (mImageSaver != null) mImageSaver.waitDone();
   2104         MenuHelper.gotoMode(mode, Camera.this);
   2105         mHandler.removeMessages(FIRST_TIME_INIT);
   2106         finish();
   2107         return true;
   2108     }
   2109 
   2110     public boolean onModeChanged(int mode) {
   2111         if (mode != ModePicker.MODE_CAMERA) {
   2112             return switchToOtherMode(mode);
   2113         } else {
   2114             return true;
   2115         }
   2116     }
   2117 
   2118     public void onSharedPreferenceChanged() {
   2119         // ignore the events after "onPause()"
   2120         if (mPausing) return;
   2121 
   2122         boolean recordLocation = RecordLocationPreference.get(
   2123                 mPreferences, getContentResolver());
   2124         mLocationManager.recordLocation(recordLocation);
   2125 
   2126         int cameraId = CameraSettings.readPreferredCameraId(mPreferences);
   2127         if (mCameraId != cameraId) {
   2128             // Restart the activity to have a crossfade animation.
   2129             // TODO: Use SurfaceTexture to implement a better and faster
   2130             // animation.
   2131             if (mIsImageCaptureIntent) {
   2132                 // If the intent is camera capture, stay in camera capture mode.
   2133                 MenuHelper.gotoCameraMode(this, getIntent());
   2134             } else {
   2135                 MenuHelper.gotoCameraMode(this);
   2136             }
   2137 
   2138             finish();
   2139         } else {
   2140             setCameraParametersWhenIdle(UPDATE_PARAM_PREFERENCE);
   2141         }
   2142 
   2143         int exposureValue = CameraSettings.readExposure(mPreferences);
   2144         updateExposureOnScreenIndicator(exposureValue);
   2145     }
   2146 
   2147     @Override
   2148     public void onUserInteraction() {
   2149         super.onUserInteraction();
   2150         keepScreenOnAwhile();
   2151     }
   2152 
   2153     private void resetScreenOn() {
   2154         mHandler.removeMessages(CLEAR_SCREEN_DELAY);
   2155         getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
   2156     }
   2157 
   2158     private void keepScreenOnAwhile() {
   2159         mHandler.removeMessages(CLEAR_SCREEN_DELAY);
   2160         getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
   2161         mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY);
   2162     }
   2163 
   2164     public void onRestorePreferencesClicked() {
   2165         if (mPausing) return;
   2166         Runnable runnable = new Runnable() {
   2167             public void run() {
   2168                 restorePreferences();
   2169             }
   2170         };
   2171         MenuHelper.confirmAction(this,
   2172                 getString(R.string.confirm_restore_title),
   2173                 getString(R.string.confirm_restore_message),
   2174                 runnable);
   2175     }
   2176 
   2177     private void restorePreferences() {
   2178         // Reset the zoom. Zoom value is not stored in preference.
   2179         if (mParameters.isZoomSupported()) {
   2180             mZoomValue = 0;
   2181             setCameraParametersWhenIdle(UPDATE_PARAM_ZOOM);
   2182             mZoomControl.setZoomIndex(0);
   2183         }
   2184         if (mIndicatorControlContainer != null) {
   2185             mIndicatorControlContainer.dismissSettingPopup();
   2186             CameraSettings.restorePreferences(Camera.this, mPreferences,
   2187                     mParameters);
   2188             mIndicatorControlContainer.reloadPreferences();
   2189             onSharedPreferenceChanged();
   2190         }
   2191     }
   2192 
   2193     public void onOverriddenPreferencesClicked() {
   2194         if (mPausing) return;
   2195         if (mNotSelectableToast == null) {
   2196             String str = getResources().getString(R.string.not_selectable_in_scene_mode);
   2197             mNotSelectableToast = Toast.makeText(Camera.this, str, Toast.LENGTH_SHORT);
   2198         }
   2199         mNotSelectableToast.show();
   2200     }
   2201 
   2202     private void showSharePopup() {
   2203         mImageSaver.waitDone();
   2204         Uri uri = mThumbnail.getUri();
   2205         if (mSharePopup == null || !uri.equals(mSharePopup.getUri())) {
   2206             // SharePopup window takes the mPreviewPanel as its size reference.
   2207             mSharePopup = new SharePopup(this, uri, mThumbnail.getBitmap(),
   2208                     mOrientationCompensation, mPreviewPanel);
   2209         }
   2210         mSharePopup.showAtLocation(mThumbnailView, Gravity.NO_GRAVITY, 0, 0);
   2211     }
   2212 
   2213     @Override
   2214     public void onFaceDetection(Face[] faces, android.hardware.Camera camera) {
   2215         mFaceView.setFaces(faces);
   2216     }
   2217 
   2218     private void showTapToFocusToast() {
   2219         // Show the toast.
   2220         RotateLayout v = (RotateLayout) findViewById(R.id.tap_to_focus_prompt);
   2221         v.setOrientation(mOrientationCompensation);
   2222         v.startAnimation(AnimationUtils.loadAnimation(this, R.anim.on_screen_hint_enter));
   2223         v.setVisibility(View.VISIBLE);
   2224         mHandler.sendEmptyMessageDelayed(DISMISS_TAP_TO_FOCUS_TOAST, 5000);
   2225         // Clear the preference.
   2226         Editor editor = mPreferences.edit();
   2227         editor.putBoolean(CameraSettings.KEY_TAP_TO_FOCUS_PROMPT_SHOWN, false);
   2228         editor.apply();
   2229     }
   2230 
   2231     private void initializeCapabilities() {
   2232         mInitialParams = mCameraDevice.getParameters();
   2233         mFocusManager.initializeParameters(mInitialParams);
   2234         mFocusAreaSupported = (mInitialParams.getMaxNumFocusAreas() > 0
   2235                 && isSupported(Parameters.FOCUS_MODE_AUTO,
   2236                         mInitialParams.getSupportedFocusModes()));
   2237         mMeteringAreaSupported = (mInitialParams.getMaxNumMeteringAreas() > 0);
   2238         mAeLockSupported = mInitialParams.isAutoExposureLockSupported();
   2239         mAwbLockSupported = mInitialParams.isAutoWhiteBalanceLockSupported();
   2240     }
   2241 }
   2242