PhotoModule.java revision 861ea12f1386e2061b7ad25d8886004f57ecf5bf
1/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.camera;
18
19import android.annotation.TargetApi;
20import android.app.Activity;
21import android.app.AlertDialog;
22import android.content.ContentProviderClient;
23import android.content.ContentResolver;
24import android.content.DialogInterface;
25import android.content.Intent;
26import android.content.SharedPreferences.Editor;
27import android.content.res.Configuration;
28import android.graphics.Bitmap;
29import android.graphics.SurfaceTexture;
30import android.hardware.Camera.CameraInfo;
31import android.hardware.Camera.Face;
32import android.hardware.Camera.FaceDetectionListener;
33import android.hardware.Camera.Parameters;
34import android.hardware.Camera.PictureCallback;
35import android.hardware.Camera.Size;
36import android.location.Location;
37import android.media.CameraProfile;
38import android.net.Uri;
39import android.os.Bundle;
40import android.os.ConditionVariable;
41import android.os.Handler;
42import android.os.Looper;
43import android.os.Message;
44import android.os.MessageQueue;
45import android.os.SystemClock;
46import android.provider.MediaStore;
47import android.util.Log;
48import android.view.Gravity;
49import android.view.KeyEvent;
50import android.view.LayoutInflater;
51import android.view.MotionEvent;
52import android.view.OrientationEventListener;
53import android.view.SurfaceHolder;
54import android.view.View;
55import android.view.View.OnClickListener;
56import android.view.ViewGroup;
57import android.view.WindowManager;
58import android.widget.FrameLayout;
59import android.widget.FrameLayout.LayoutParams;
60import android.widget.ImageView;
61import android.widget.Toast;
62
63import com.android.camera.CameraManager.CameraProxy;
64import com.android.camera.ui.AbstractSettingPopup;
65import com.android.camera.ui.FaceView;
66import com.android.camera.ui.PieRenderer;
67import com.android.camera.ui.PopupManager;
68import com.android.camera.ui.PreviewSurfaceView;
69import com.android.camera.ui.RenderOverlay;
70import com.android.camera.ui.Rotatable;
71import com.android.camera.ui.RotateLayout;
72import com.android.camera.ui.RotateTextToast;
73import com.android.camera.ui.TwoStateImageView;
74import com.android.camera.ui.ZoomRenderer;
75import com.android.gallery3d.app.CropImage;
76import com.android.gallery3d.common.ApiHelper;
77
78import java.io.File;
79import java.io.FileNotFoundException;
80import java.io.FileOutputStream;
81import java.io.IOException;
82import java.io.OutputStream;
83import java.util.ArrayList;
84import java.util.Collections;
85import java.util.Formatter;
86import java.util.List;
87
88public class PhotoModule
89    implements CameraModule,
90    FocusOverlayManager.Listener,
91    CameraPreference.OnPreferenceChangedListener,
92    LocationManager.Listener,
93    PreviewFrameLayout.OnSizeChangedListener,
94    ShutterButton.OnShutterButtonListener,
95    SurfaceHolder.Callback,
96    PieRenderer.PieListener {
97
98    private static final String TAG = "CAM_PhotoModule";
99
100    // We number the request code from 1000 to avoid collision with Gallery.
101    private static final int REQUEST_CROP = 1000;
102
103    private static final int SETUP_PREVIEW = 1;
104    private static final int FIRST_TIME_INIT = 2;
105    private static final int CLEAR_SCREEN_DELAY = 3;
106    private static final int SET_CAMERA_PARAMETERS_WHEN_IDLE = 4;
107    private static final int CHECK_DISPLAY_ROTATION = 5;
108    private static final int SHOW_TAP_TO_FOCUS_TOAST = 6;
109    private static final int SWITCH_CAMERA = 7;
110    private static final int SWITCH_CAMERA_START_ANIMATION = 8;
111    private static final int CAMERA_OPEN_DONE = 9;
112    private static final int START_PREVIEW_DONE = 10;
113    private static final int OPEN_CAMERA_FAIL = 11;
114    private static final int CAMERA_DISABLED = 12;
115
116    // The subset of parameters we need to update in setCameraParameters().
117    private static final int UPDATE_PARAM_INITIALIZE = 1;
118    private static final int UPDATE_PARAM_ZOOM = 2;
119    private static final int UPDATE_PARAM_PREFERENCE = 4;
120    private static final int UPDATE_PARAM_ALL = -1;
121
122    // This is the timeout to keep the camera in onPause for the first time
123    // after screen on if the activity is started from secure lock screen.
124    private static final int KEEP_CAMERA_TIMEOUT = 1000; // ms
125
126    // copied from Camera hierarchy
127    private CameraActivity mActivity;
128    private View mRootView;
129    private CameraProxy mCameraDevice;
130    private int mCameraId;
131    private Parameters mParameters;
132    private boolean mPaused;
133    private AbstractSettingPopup mPopup;
134
135    // these are only used by Camera
136
137    // The activity is going to switch to the specified camera id. This is
138    // needed because texture copy is done in GL thread. -1 means camera is not
139    // switching.
140    protected int mPendingSwitchCameraId = -1;
141    private boolean mOpenCameraFail;
142    private boolean mCameraDisabled;
143
144    // When setCameraParametersWhenIdle() is called, we accumulate the subsets
145    // needed to be updated in mUpdateSet.
146    private int mUpdateSet;
147
148    private static final int SCREEN_DELAY = 2 * 60 * 1000;
149
150    private int mZoomValue;  // The current zoom value.
151    private int mZoomMax;
152    private List<Integer> mZoomRatios;
153
154    private Parameters mInitialParams;
155    private boolean mFocusAreaSupported;
156    private boolean mMeteringAreaSupported;
157    private boolean mAeLockSupported;
158    private boolean mAwbLockSupported;
159    private boolean mContinousFocusSupported;
160
161    // The degrees of the device rotated clockwise from its natural orientation.
162    private int mOrientation = OrientationEventListener.ORIENTATION_UNKNOWN;
163    // The orientation compensation for icons and dialogs. Ex: if the value
164    // is 90, the UI components should be rotated 90 degrees counter-clockwise.
165    private int mOrientationCompensation = 0;
166    private ComboPreferences mPreferences;
167
168    private static final String sTempCropFilename = "crop-temp";
169
170    private ContentProviderClient mMediaProviderClient;
171    private ShutterButton mShutterButton;
172    private boolean mFaceDetectionStarted = false;
173
174    private PreviewFrameLayout mPreviewFrameLayout;
175    private Object mSurfaceTexture;
176
177    // for API level 10
178    private PreviewSurfaceView mPreviewSurfaceView;
179    private volatile SurfaceHolder mCameraSurfaceHolder;
180
181    private FaceView mFaceView;
182    private RenderOverlay mRenderOverlay;
183    private Rotatable mReviewCancelButton;
184    private Rotatable mReviewDoneButton;
185    private View mReviewRetakeButton;
186
187    // mCropValue and mSaveUri are used only if isImageCaptureIntent() is true.
188    private String mCropValue;
189    private Uri mSaveUri;
190
191    private View mMenu;
192    private View mBlocker;
193
194    // Small indicators which show the camera settings in the viewfinder.
195    private ImageView mExposureIndicator;
196    private ImageView mFlashIndicator;
197    private ImageView mSceneIndicator;
198    private ImageView mHdrIndicator;
199    // A view group that contains all the small indicators.
200    private RotateLayout mOnScreenIndicators;
201
202    // We use a thread in ImageSaver to do the work of saving images. This
203    // reduces the shot-to-shot time.
204    private ImageSaver mImageSaver;
205    // Similarly, we use a thread to generate the name of the picture and insert
206    // it into MediaStore while picture taking is still in progress.
207    private ImageNamer mImageNamer;
208
209    private Runnable mDoSnapRunnable = new Runnable() {
210        @Override
211        public void run() {
212            onShutterButtonClick();
213        }
214    };
215
216    private final StringBuilder mBuilder = new StringBuilder();
217    private final Formatter mFormatter = new Formatter(mBuilder);
218    private final Object[] mFormatterArgs = new Object[1];
219
220    /**
221     * An unpublished intent flag requesting to return as soon as capturing
222     * is completed.
223     *
224     * TODO: consider publishing by moving into MediaStore.
225     */
226    private static final String EXTRA_QUICK_CAPTURE =
227            "android.intent.extra.quickCapture";
228
229    // The display rotation in degrees. This is only valid when mCameraState is
230    // not PREVIEW_STOPPED.
231    private int mDisplayRotation;
232    // The value for android.hardware.Camera.setDisplayOrientation.
233    private int mCameraDisplayOrientation;
234    // The value for UI components like indicators.
235    private int mDisplayOrientation;
236    // The value for android.hardware.Camera.Parameters.setRotation.
237    private int mJpegRotation;
238    private boolean mFirstTimeInitialized;
239    private boolean mIsImageCaptureIntent;
240
241    private static final int PREVIEW_STOPPED = 0;
242    private static final int IDLE = 1;  // preview is active
243    // Focus is in progress. The exact focus state is in Focus.java.
244    private static final int FOCUSING = 2;
245    private static final int SNAPSHOT_IN_PROGRESS = 3;
246    // Switching between cameras.
247    private static final int SWITCHING_CAMERA = 4;
248    private int mCameraState = PREVIEW_STOPPED;
249    private boolean mSnapshotOnIdle = false;
250
251    private ContentResolver mContentResolver;
252
253    private LocationManager mLocationManager;
254
255    private final ShutterCallback mShutterCallback = new ShutterCallback();
256    private final PostViewPictureCallback mPostViewPictureCallback =
257            new PostViewPictureCallback();
258    private final RawPictureCallback mRawPictureCallback =
259            new RawPictureCallback();
260    private final AutoFocusCallback mAutoFocusCallback =
261            new AutoFocusCallback();
262    private final Object mAutoFocusMoveCallback =
263            ApiHelper.HAS_AUTO_FOCUS_MOVE_CALLBACK
264            ? new AutoFocusMoveCallback()
265            : null;
266
267    private final CameraErrorCallback mErrorCallback = new CameraErrorCallback();
268
269    private long mFocusStartTime;
270    private long mShutterCallbackTime;
271    private long mPostViewPictureCallbackTime;
272    private long mRawPictureCallbackTime;
273    private long mJpegPictureCallbackTime;
274    private long mOnResumeTime;
275    private byte[] mJpegImageData;
276
277    // These latency time are for the CameraLatency test.
278    public long mAutoFocusTime;
279    public long mShutterLag;
280    public long mShutterToPictureDisplayedTime;
281    public long mPictureDisplayedToJpegCallbackTime;
282    public long mJpegCallbackFinishTime;
283    public long mCaptureStartTime;
284
285    // This handles everything about focus.
286    private FocusOverlayManager mFocusManager;
287
288    private PieRenderer mPieRenderer;
289    private PhotoController mPhotoControl;
290
291    private ZoomRenderer mZoomRenderer;
292
293    private String mSceneMode;
294    private Toast mNotSelectableToast;
295
296    private final Handler mHandler = new MainHandler();
297    private PreferenceGroup mPreferenceGroup;
298
299    private boolean mQuickCapture;
300
301    CameraStartUpThread mCameraStartUpThread;
302    ConditionVariable mStartPreviewPrerequisiteReady = new ConditionVariable();
303
304    private PreviewGestures mGestures;
305
306    // The purpose is not to block the main thread in onCreate and onResume.
307    private class CameraStartUpThread extends Thread {
308        private volatile boolean mCancelled;
309
310        public void cancel() {
311            mCancelled = true;
312        }
313
314        @Override
315        public void run() {
316            try {
317                // We need to check whether the activity is paused before long
318                // operations to ensure that onPause() can be done ASAP.
319                if (mCancelled) return;
320                mCameraDevice = Util.openCamera(mActivity, mCameraId);
321                mParameters = mCameraDevice.getParameters();
322                // Wait until all the initialization needed by startPreview are
323                // done.
324                mStartPreviewPrerequisiteReady.block();
325
326                initializeCapabilities();
327                if (mFocusManager == null) initializeFocusManager();
328                if (mCancelled) return;
329                setCameraParameters(UPDATE_PARAM_ALL);
330                mHandler.sendEmptyMessage(CAMERA_OPEN_DONE);
331                if (mCancelled) return;
332                startPreview();
333                mHandler.sendEmptyMessage(START_PREVIEW_DONE);
334                mOnResumeTime = SystemClock.uptimeMillis();
335                mHandler.sendEmptyMessage(CHECK_DISPLAY_ROTATION);
336            } catch (CameraHardwareException e) {
337                mHandler.sendEmptyMessage(OPEN_CAMERA_FAIL);
338            } catch (CameraDisabledException e) {
339                mHandler.sendEmptyMessage(CAMERA_DISABLED);
340            }
341        }
342    }
343
344    /**
345     * This Handler is used to post message back onto the main thread of the
346     * application
347     */
348    private class MainHandler extends Handler {
349        @Override
350        public void handleMessage(Message msg) {
351            switch (msg.what) {
352                case SETUP_PREVIEW: {
353                    setupPreview();
354                    break;
355                }
356
357                case CLEAR_SCREEN_DELAY: {
358                    mActivity.getWindow().clearFlags(
359                            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
360                    break;
361                }
362
363                case FIRST_TIME_INIT: {
364                    initializeFirstTime();
365                    break;
366                }
367
368                case SET_CAMERA_PARAMETERS_WHEN_IDLE: {
369                    setCameraParametersWhenIdle(0);
370                    break;
371                }
372
373                case CHECK_DISPLAY_ROTATION: {
374                    // Set the display orientation if display rotation has changed.
375                    // Sometimes this happens when the device is held upside
376                    // down and camera app is opened. Rotation animation will
377                    // take some time and the rotation value we have got may be
378                    // wrong. Framework does not have a callback for this now.
379                    if (Util.getDisplayRotation(mActivity) != mDisplayRotation) {
380                        setDisplayOrientation();
381                    }
382                    if (SystemClock.uptimeMillis() - mOnResumeTime < 5000) {
383                        mHandler.sendEmptyMessageDelayed(CHECK_DISPLAY_ROTATION, 100);
384                    }
385                    break;
386                }
387
388                case SHOW_TAP_TO_FOCUS_TOAST: {
389                    showTapToFocusToast();
390                    break;
391                }
392
393                case SWITCH_CAMERA: {
394                    switchCamera();
395                    break;
396                }
397
398                case SWITCH_CAMERA_START_ANIMATION: {
399                    ((CameraScreenNail) mActivity.mCameraScreenNail).animateSwitchCamera();
400                    break;
401                }
402
403                case CAMERA_OPEN_DONE: {
404                    initializeAfterCameraOpen();
405                    break;
406                }
407
408                case START_PREVIEW_DONE: {
409                    mCameraStartUpThread = null;
410                    setCameraState(IDLE);
411                    if (!ApiHelper.HAS_SURFACE_TEXTURE) {
412                        // This may happen if surfaceCreated has arrived.
413                        mCameraDevice.setPreviewDisplayAsync(mCameraSurfaceHolder);
414                    }
415                    startFaceDetection();
416                    locationFirstRun();
417                    break;
418                }
419
420                case OPEN_CAMERA_FAIL: {
421                    mCameraStartUpThread = null;
422                    mOpenCameraFail = true;
423                    Util.showErrorAndFinish(mActivity,
424                            R.string.cannot_connect_camera);
425                    break;
426                }
427
428                case CAMERA_DISABLED: {
429                    mCameraStartUpThread = null;
430                    mCameraDisabled = true;
431                    Util.showErrorAndFinish(mActivity,
432                            R.string.camera_disabled);
433                    break;
434                }
435            }
436        }
437    }
438
439    @Override
440    public void init(CameraActivity activity, View parent, boolean reuseNail) {
441        mActivity = activity;
442        mRootView = parent;
443        mPreferences = new ComboPreferences(mActivity);
444        CameraSettings.upgradeGlobalPreferences(mPreferences.getGlobal());
445        mCameraId = getPreferredCameraId(mPreferences);
446
447        mContentResolver = mActivity.getContentResolver();
448
449        // To reduce startup time, open the camera and start the preview in
450        // another thread.
451        mCameraStartUpThread = new CameraStartUpThread();
452        mCameraStartUpThread.start();
453
454        mActivity.getLayoutInflater().inflate(R.layout.photo_module, (ViewGroup) mRootView);
455
456        // Surface texture is from camera screen nail and startPreview needs it.
457        // This must be done before startPreview.
458        mIsImageCaptureIntent = isImageCaptureIntent();
459        if (reuseNail) {
460            mActivity.reuseCameraScreenNail(!mIsImageCaptureIntent);
461        } else {
462            mActivity.createCameraScreenNail(!mIsImageCaptureIntent);
463        }
464
465        mPreferences.setLocalId(mActivity, mCameraId);
466        CameraSettings.upgradeLocalPreferences(mPreferences.getLocal());
467        // we need to reset exposure for the preview
468        resetExposureCompensation();
469        // Starting the preview needs preferences, camera screen nail, and
470        // focus area indicator.
471        mStartPreviewPrerequisiteReady.open();
472
473        initializeControlByIntent();
474        mQuickCapture = mActivity.getIntent().getBooleanExtra(EXTRA_QUICK_CAPTURE, false);
475        initializeMiscControls();
476        mLocationManager = new LocationManager(mActivity, this);
477        initOnScreenIndicator();
478    }
479
480    // Prompt the user to pick to record location for the very first run of
481    // camera only
482    private void locationFirstRun() {
483        if (RecordLocationPreference.isSet(mPreferences)) {
484            return;
485        }
486        // Check if the back camera exists
487        int backCameraId = CameraHolder.instance().getBackCameraId();
488        if (backCameraId == -1) {
489            // If there is no back camera, do not show the prompt.
490            return;
491        }
492
493        new AlertDialog.Builder(mActivity)
494            .setTitle(R.string.remember_location_title)
495            .setMessage(R.string.remember_location_prompt)
496            .setPositiveButton(R.string.remember_location_yes, new DialogInterface.OnClickListener() {
497                @Override
498                public void onClick(DialogInterface dialog, int arg1) {
499                    setLocationPreference(RecordLocationPreference.VALUE_ON);
500                }
501            })
502            .setNegativeButton(R.string.remember_location_no, new DialogInterface.OnClickListener() {
503                @Override
504                public void onClick(DialogInterface dialog, int arg1) {
505                    dialog.cancel();
506                }
507            })
508            .setOnCancelListener(new DialogInterface.OnCancelListener() {
509                @Override
510                public void onCancel(DialogInterface dialog) {
511                    setLocationPreference(RecordLocationPreference.VALUE_OFF);
512                }
513            })
514            .show();
515    }
516
517    private void setLocationPreference(String value) {
518        mPreferences.edit()
519            .putString(RecordLocationPreference.KEY, value)
520            .apply();
521        // TODO: Fix this to use the actual onSharedPreferencesChanged listener
522        // instead of invoking manually
523        onSharedPreferenceChanged();
524    }
525
526    private void initializeRenderOverlay() {
527        if (mPieRenderer != null) {
528            mRenderOverlay.addRenderer(mPieRenderer);
529            mFocusManager.setFocusRenderer(mPieRenderer);
530        }
531        if (mZoomRenderer != null) {
532            mRenderOverlay.addRenderer(mZoomRenderer);
533        }
534        if (mGestures != null) {
535            mGestures.clearTouchReceivers();
536            mGestures.setRenderOverlay(mRenderOverlay);
537            mGestures.addTouchReceiver(mMenu);
538            mGestures.addTouchReceiver(mBlocker);
539
540            if (isImageCaptureIntent()) {
541                if (mReviewCancelButton != null) {
542                    mGestures.addTouchReceiver((View) mReviewCancelButton);
543                }
544                if (mReviewDoneButton != null) {
545                    mGestures.addTouchReceiver((View) mReviewDoneButton);
546                }
547            }
548        }
549        mRenderOverlay.requestLayout();
550    }
551
552    private void initializeAfterCameraOpen() {
553        if (mPieRenderer == null) {
554            mPieRenderer = new PieRenderer(mActivity);
555            mPhotoControl = new PhotoController(mActivity, this, mPieRenderer);
556            mPhotoControl.setListener(this);
557            mPieRenderer.setPieListener(this);
558        }
559        if (mZoomRenderer == null) {
560            mZoomRenderer = new ZoomRenderer(mActivity);
561        }
562        if (mGestures == null) {
563            // this will handle gesture disambiguation and dispatching
564            mGestures = new PreviewGestures(mActivity, this, mZoomRenderer, mPieRenderer);
565        }
566        initializeRenderOverlay();
567        initializePhotoControl();
568
569        // These depend on camera parameters.
570        setPreviewFrameLayoutAspectRatio();
571        mFocusManager.setPreviewSize(mPreviewFrameLayout.getWidth(),
572                mPreviewFrameLayout.getHeight());
573        loadCameraPreferences();
574        initializeZoom();
575        updateOnScreenIndicators();
576        showTapToFocusToastIfNeeded();
577    }
578
579    private void initializePhotoControl() {
580        loadCameraPreferences();
581        if (mPhotoControl != null) {
582            mPhotoControl.initialize(mPreferenceGroup);
583        }
584        updateSceneModeUI();
585    }
586
587
588    private void resetExposureCompensation() {
589        String value = mPreferences.getString(CameraSettings.KEY_EXPOSURE,
590                CameraSettings.EXPOSURE_DEFAULT_VALUE);
591        if (!CameraSettings.EXPOSURE_DEFAULT_VALUE.equals(value)) {
592            Editor editor = mPreferences.edit();
593            editor.putString(CameraSettings.KEY_EXPOSURE, "0");
594            editor.apply();
595        }
596    }
597
598    private void keepMediaProviderInstance() {
599        // We want to keep a reference to MediaProvider in camera's lifecycle.
600        // TODO: Utilize mMediaProviderClient instance to replace
601        // ContentResolver calls.
602        if (mMediaProviderClient == null) {
603            mMediaProviderClient = mContentResolver
604                    .acquireContentProviderClient(MediaStore.AUTHORITY);
605        }
606    }
607
608    // Snapshots can only be taken after this is called. It should be called
609    // once only. We could have done these things in onCreate() but we want to
610    // make preview screen appear as soon as possible.
611    private void initializeFirstTime() {
612        if (mFirstTimeInitialized) return;
613
614        // Initialize location service.
615        boolean recordLocation = RecordLocationPreference.get(
616                mPreferences, mContentResolver);
617        mLocationManager.recordLocation(recordLocation);
618
619        keepMediaProviderInstance();
620
621        // Initialize shutter button.
622        mShutterButton = mActivity.getShutterButton();
623        mShutterButton.setImageResource(R.drawable.btn_new_shutter);
624        mShutterButton.setOnShutterButtonListener(this);
625        mShutterButton.setVisibility(View.VISIBLE);
626
627        mImageSaver = new ImageSaver();
628        mImageNamer = new ImageNamer();
629
630        mFirstTimeInitialized = true;
631        addIdleHandler();
632
633        mActivity.updateStorageSpaceAndHint();
634    }
635
636    private void showTapToFocusToastIfNeeded() {
637        // Show the tap to focus toast if this is the first start.
638        if (mFocusAreaSupported &&
639                mPreferences.getBoolean(CameraSettings.KEY_CAMERA_FIRST_USE_HINT_SHOWN, true)) {
640            // Delay the toast for one second to wait for orientation.
641            mHandler.sendEmptyMessageDelayed(SHOW_TAP_TO_FOCUS_TOAST, 1000);
642        }
643    }
644
645    private void addIdleHandler() {
646        MessageQueue queue = Looper.myQueue();
647        queue.addIdleHandler(new MessageQueue.IdleHandler() {
648            @Override
649            public boolean queueIdle() {
650                Storage.ensureOSXCompatible();
651                return false;
652            }
653        });
654    }
655
656    // If the activity is paused and resumed, this method will be called in
657    // onResume.
658    private void initializeSecondTime() {
659
660        // Start location update if needed.
661        boolean recordLocation = RecordLocationPreference.get(
662                mPreferences, mContentResolver);
663        mLocationManager.recordLocation(recordLocation);
664
665        mImageSaver = new ImageSaver();
666        mImageNamer = new ImageNamer();
667        initializeZoom();
668        keepMediaProviderInstance();
669        hidePostCaptureAlert();
670
671        if (mPhotoControl != null) {
672            mPhotoControl.reloadPreferences();
673        }
674    }
675
676    private class ZoomChangeListener implements ZoomRenderer.OnZoomChangedListener {
677        @Override
678        public void onZoomValueChanged(int index) {
679            // Not useful to change zoom value when the activity is paused.
680            if (mPaused) return;
681            mZoomValue = index;
682            if (mParameters == null || mCameraDevice != null) return;
683            // Set zoom parameters asynchronously
684            mParameters.setZoom(mZoomValue);
685            mCameraDevice.setParametersAsync(mParameters);
686            if (mZoomRenderer != null) {
687                Parameters p = mCameraDevice.getParameters();
688                mZoomRenderer.setZoomValue(mZoomRatios.get(p.getZoom()));
689            }
690        }
691
692        @Override
693        public void onZoomStart() {
694            if (mPieRenderer != null) {
695                mPieRenderer.setBlockFocus(true);
696            }
697        }
698
699        @Override
700        public void onZoomEnd() {
701            if (mPieRenderer != null) {
702                mPieRenderer.setBlockFocus(false);
703            }
704        }
705    }
706
707    private void initializeZoom() {
708        if (!mParameters.isZoomSupported() || (mZoomRenderer == null)) return;
709        mZoomMax = mParameters.getMaxZoom();
710        mZoomRatios = mParameters.getZoomRatios();
711        // Currently we use immediate zoom for fast zooming to get better UX and
712        // there is no plan to take advantage of the smooth zoom.
713        if (mZoomRenderer != null) {
714            mZoomRenderer.setZoomMax(mZoomMax);
715            mZoomRenderer.setZoom(mParameters.getZoom());
716            mZoomRenderer.setZoomValue(mZoomRatios.get(mParameters.getZoom()));
717            mZoomRenderer.setOnZoomChangeListener(new ZoomChangeListener());
718        }
719    }
720
721    @TargetApi(ApiHelper.VERSION_CODES.ICE_CREAM_SANDWICH)
722    @Override
723    public void startFaceDetection() {
724        if (!ApiHelper.HAS_FACE_DETECTION) return;
725        if (mFaceDetectionStarted) return;
726        if (mParameters.getMaxNumDetectedFaces() > 0) {
727            mFaceDetectionStarted = true;
728            mFaceView.clear();
729            mFaceView.setVisibility(View.VISIBLE);
730            mFaceView.setDisplayOrientation(mDisplayOrientation);
731            CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId];
732            mFaceView.setMirror(info.facing == CameraInfo.CAMERA_FACING_FRONT);
733            mFaceView.resume();
734            mFocusManager.setFaceView(mFaceView);
735            mCameraDevice.setFaceDetectionListener(new FaceDetectionListener() {
736                @Override
737                public void onFaceDetection(Face[] faces, android.hardware.Camera camera) {
738                    mFaceView.setFaces(faces);
739                }
740            });
741            mCameraDevice.startFaceDetection();
742        }
743    }
744
745    @TargetApi(ApiHelper.VERSION_CODES.ICE_CREAM_SANDWICH)
746    @Override
747    public void stopFaceDetection() {
748        if (!ApiHelper.HAS_FACE_DETECTION) return;
749        if (!mFaceDetectionStarted) return;
750        if (mParameters.getMaxNumDetectedFaces() > 0) {
751            mFaceDetectionStarted = false;
752            mCameraDevice.setFaceDetectionListener(null);
753            mCameraDevice.stopFaceDetection();
754            if (mFaceView != null) mFaceView.clear();
755        }
756    }
757
758    @Override
759    public boolean dispatchTouchEvent(MotionEvent m) {
760        if (mCameraState == SWITCHING_CAMERA) return true;
761        if (mPopup != null) {
762            return mActivity.superDispatchTouchEvent(m);
763        } else if (mGestures != null && mRenderOverlay != null) {
764            return mGestures.dispatchTouch(m);
765        }
766        return false;
767    }
768
769    private void initOnScreenIndicator() {
770        mOnScreenIndicators = (RotateLayout) mRootView.findViewById(R.id.on_screen_indicators);
771        mExposureIndicator = (ImageView) mOnScreenIndicators.findViewById(R.id.menu_exposure_indicator);
772        mFlashIndicator = (ImageView) mOnScreenIndicators.findViewById(R.id.menu_flash_indicator);
773        mSceneIndicator = (ImageView) mOnScreenIndicators.findViewById(R.id.menu_scenemode_indicator);
774        mHdrIndicator = (ImageView) mOnScreenIndicators.findViewById(R.id.menu_hdr_indicator);
775    }
776
777    @Override
778    public void showGpsOnScreenIndicator(boolean hasSignal) { }
779
780    @Override
781    public void hideGpsOnScreenIndicator() { }
782
783    private void updateExposureOnScreenIndicator(int value) {
784        if (mExposureIndicator == null) {
785            return;
786        }
787        int id = 0;
788        float step = mParameters.getExposureCompensationStep();
789        value = (int) Math.round(value * step);
790        switch(value) {
791        case -3:
792            id = R.drawable.ic_indicator_ev_n3;
793            break;
794        case -2:
795            id = R.drawable.ic_indicator_ev_n2;
796            break;
797        case -1:
798            id = R.drawable.ic_indicator_ev_n1;
799            break;
800        case 0:
801            id = R.drawable.ic_indicator_ev_0;
802            break;
803        case 1:
804            id = R.drawable.ic_indicator_ev_p1;
805            break;
806        case 2:
807            id = R.drawable.ic_indicator_ev_p2;
808            break;
809        case 3:
810            id = R.drawable.ic_indicator_ev_p3;
811            break;
812        }
813        mExposureIndicator.setImageResource(id);
814
815    }
816
817    private void updateFlashOnScreenIndicator(String value) {
818        if (mFlashIndicator == null) {
819            return;
820        }
821        if (value == null || Parameters.FLASH_MODE_OFF.equals(value)) {
822            mFlashIndicator.setImageResource(R.drawable.ic_indicator_flash_off);
823        } else {
824            if (Parameters.FLASH_MODE_AUTO.equals(value)) {
825                mFlashIndicator.setImageResource(R.drawable.ic_indicator_flash_auto);
826            } else if (Parameters.FLASH_MODE_ON.equals(value)) {
827                mFlashIndicator.setImageResource(R.drawable.ic_indicator_flash_on);
828            } else {
829                mFlashIndicator.setImageResource(R.drawable.ic_indicator_flash_off);
830            }
831        }
832    }
833
834    private void updateSceneOnScreenIndicator(String value) {
835        if (mSceneIndicator == null) {
836            return;
837        }
838        if ((value == null) || Parameters.SCENE_MODE_AUTO.equals(value)
839                || Parameters.SCENE_MODE_HDR.equals(value)) {
840            mSceneIndicator.setImageResource(R.drawable.ic_indicator_sce_off);
841        } else {
842            mSceneIndicator.setImageResource(R.drawable.ic_indicator_sce_on);
843        }
844    }
845
846    private void updateHdrOnScreenIndicator(String value) {
847        if (mHdrIndicator == null) {
848            return;
849        }
850        if ((value != null) && Parameters.SCENE_MODE_HDR.equals(value)) {
851            mHdrIndicator.setImageResource(R.drawable.ic_indicator_hdr_on);
852        } else {
853            mHdrIndicator.setImageResource(R.drawable.ic_indicator_hdr_off);
854        }
855    }
856
857    private void updateOnScreenIndicators() {
858        updateSceneOnScreenIndicator(mParameters.getSceneMode());
859        updateExposureOnScreenIndicator(CameraSettings.readExposure(mPreferences));
860        updateFlashOnScreenIndicator(mParameters.getFlashMode());
861        updateHdrOnScreenIndicator(mParameters.getSceneMode());
862    }
863
864    private final class ShutterCallback
865            implements android.hardware.Camera.ShutterCallback {
866        @Override
867        public void onShutter() {
868            mShutterCallbackTime = System.currentTimeMillis();
869            mShutterLag = mShutterCallbackTime - mCaptureStartTime;
870            Log.v(TAG, "mShutterLag = " + mShutterLag + "ms");
871        }
872    }
873
874    private final class PostViewPictureCallback implements PictureCallback {
875        @Override
876        public void onPictureTaken(
877                byte [] data, android.hardware.Camera camera) {
878            mPostViewPictureCallbackTime = System.currentTimeMillis();
879            Log.v(TAG, "mShutterToPostViewCallbackTime = "
880                    + (mPostViewPictureCallbackTime - mShutterCallbackTime)
881                    + "ms");
882        }
883    }
884
885    private final class RawPictureCallback implements PictureCallback {
886        @Override
887        public void onPictureTaken(
888                byte [] rawData, android.hardware.Camera camera) {
889            mRawPictureCallbackTime = System.currentTimeMillis();
890            Log.v(TAG, "mShutterToRawCallbackTime = "
891                    + (mRawPictureCallbackTime - mShutterCallbackTime) + "ms");
892        }
893    }
894
895    private final class JpegPictureCallback implements PictureCallback {
896        Location mLocation;
897
898        public JpegPictureCallback(Location loc) {
899            mLocation = loc;
900        }
901
902        @Override
903        public void onPictureTaken(
904                final byte [] jpegData, final android.hardware.Camera camera) {
905            if (mPaused) {
906                return;
907            }
908            if (mSceneMode == Util.SCENE_MODE_HDR) {
909                mActivity.showSwitcher();
910            }
911
912            mJpegPictureCallbackTime = System.currentTimeMillis();
913            // If postview callback has arrived, the captured image is displayed
914            // in postview callback. If not, the captured image is displayed in
915            // raw picture callback.
916            if (mPostViewPictureCallbackTime != 0) {
917                mShutterToPictureDisplayedTime =
918                        mPostViewPictureCallbackTime - mShutterCallbackTime;
919                mPictureDisplayedToJpegCallbackTime =
920                        mJpegPictureCallbackTime - mPostViewPictureCallbackTime;
921            } else {
922                mShutterToPictureDisplayedTime =
923                        mRawPictureCallbackTime - mShutterCallbackTime;
924                mPictureDisplayedToJpegCallbackTime =
925                        mJpegPictureCallbackTime - mRawPictureCallbackTime;
926            }
927            Log.v(TAG, "mPictureDisplayedToJpegCallbackTime = "
928                    + mPictureDisplayedToJpegCallbackTime + "ms");
929
930            // Only animate when in full screen capture mode
931            // i.e. If monkey/a user swipes to the gallery during picture taking,
932            // don't show animation
933            if (ApiHelper.HAS_SURFACE_TEXTURE && !mIsImageCaptureIntent
934                    && mActivity.mShowCameraAppView) {
935                // Finish capture animation
936                ((CameraScreenNail) mActivity.mCameraScreenNail).animateSlide();
937            }
938            mFocusManager.updateFocusUI(); // Ensure focus indicator is hidden.
939            if (!mIsImageCaptureIntent) {
940                if (ApiHelper.CAN_START_PREVIEW_IN_JPEG_CALLBACK) {
941                    setupPreview();
942                } else {
943                    // Camera HAL of some devices have a bug. Starting preview
944                    // immediately after taking a picture will fail. Wait some
945                    // time before starting the preview.
946                    mHandler.sendEmptyMessageDelayed(SETUP_PREVIEW, 300);
947                }
948            }
949
950            if (!mIsImageCaptureIntent) {
951                // Calculate the width and the height of the jpeg.
952                Size s = mParameters.getPictureSize();
953                int orientation = Exif.getOrientation(jpegData);
954                int width, height;
955                if ((mJpegRotation + orientation) % 180 == 0) {
956                    width = s.width;
957                    height = s.height;
958                } else {
959                    width = s.height;
960                    height = s.width;
961                }
962                Uri uri = mImageNamer.getUri();
963                mActivity.addSecureAlbumItemIfNeeded(false, uri);
964                String title = mImageNamer.getTitle();
965                mImageSaver.addImage(jpegData, uri, title, mLocation,
966                        width, height, orientation);
967            } else {
968                mJpegImageData = jpegData;
969                if (!mQuickCapture) {
970                    showPostCaptureAlert();
971                } else {
972                    doAttach();
973                }
974            }
975
976            // Check this in advance of each shot so we don't add to shutter
977            // latency. It's true that someone else could write to the SD card in
978            // the mean time and fill it, but that could have happened between the
979            // shutter press and saving the JPEG too.
980            mActivity.updateStorageSpaceAndHint();
981
982            long now = System.currentTimeMillis();
983            mJpegCallbackFinishTime = now - mJpegPictureCallbackTime;
984            Log.v(TAG, "mJpegCallbackFinishTime = "
985                    + mJpegCallbackFinishTime + "ms");
986            mJpegPictureCallbackTime = 0;
987        }
988    }
989
990    private final class AutoFocusCallback
991            implements android.hardware.Camera.AutoFocusCallback {
992        @Override
993        public void onAutoFocus(
994                boolean focused, android.hardware.Camera camera) {
995            if (mPaused) return;
996
997            mAutoFocusTime = System.currentTimeMillis() - mFocusStartTime;
998            Log.v(TAG, "mAutoFocusTime = " + mAutoFocusTime + "ms");
999            setCameraState(IDLE);
1000            mFocusManager.onAutoFocus(focused);
1001        }
1002    }
1003
1004    @TargetApi(ApiHelper.VERSION_CODES.JELLY_BEAN)
1005    private final class AutoFocusMoveCallback
1006            implements android.hardware.Camera.AutoFocusMoveCallback {
1007        @Override
1008        public void onAutoFocusMoving(
1009            boolean moving, android.hardware.Camera camera) {
1010                mFocusManager.onAutoFocusMoving(moving);
1011        }
1012    }
1013
1014    // Each SaveRequest remembers the data needed to save an image.
1015    private static class SaveRequest {
1016        byte[] data;
1017        Uri uri;
1018        String title;
1019        Location loc;
1020        int width, height;
1021        int orientation;
1022    }
1023
1024    // We use a queue to store the SaveRequests that have not been completed
1025    // yet. The main thread puts the request into the queue. The saver thread
1026    // gets it from the queue, does the work, and removes it from the queue.
1027    //
1028    // The main thread needs to wait for the saver thread to finish all the work
1029    // in the queue, when the activity's onPause() is called, we need to finish
1030    // all the work, so other programs (like Gallery) can see all the images.
1031    //
1032    // If the queue becomes too long, adding a new request will block the main
1033    // thread until the queue length drops below the threshold (QUEUE_LIMIT).
1034    // If we don't do this, we may face several problems: (1) We may OOM
1035    // because we are holding all the jpeg data in memory. (2) We may ANR
1036    // when we need to wait for saver thread finishing all the work (in
1037    // onPause() or gotoGallery()) because the time to finishing a long queue
1038    // of work may be too long.
1039    private class ImageSaver extends Thread {
1040        private static final int QUEUE_LIMIT = 3;
1041
1042        private ArrayList<SaveRequest> mQueue;
1043        private boolean mStop;
1044
1045        // Runs in main thread
1046        public ImageSaver() {
1047            mQueue = new ArrayList<SaveRequest>();
1048            start();
1049        }
1050
1051        // Runs in main thread
1052        public void addImage(final byte[] data, Uri uri, String title,
1053                Location loc, int width, int height, int orientation) {
1054            SaveRequest r = new SaveRequest();
1055            r.data = data;
1056            r.uri = uri;
1057            r.title = title;
1058            r.loc = (loc == null) ? null : new Location(loc);  // make a copy
1059            r.width = width;
1060            r.height = height;
1061            r.orientation = orientation;
1062            synchronized (this) {
1063                while (mQueue.size() >= QUEUE_LIMIT) {
1064                    try {
1065                        wait();
1066                    } catch (InterruptedException ex) {
1067                        // ignore.
1068                    }
1069                }
1070                mQueue.add(r);
1071                notifyAll();  // Tell saver thread there is new work to do.
1072            }
1073        }
1074
1075        // Runs in saver thread
1076        @Override
1077        public void run() {
1078            while (true) {
1079                SaveRequest r;
1080                synchronized (this) {
1081                    if (mQueue.isEmpty()) {
1082                        notifyAll();  // notify main thread in waitDone
1083
1084                        // Note that we can only stop after we saved all images
1085                        // in the queue.
1086                        if (mStop) break;
1087
1088                        try {
1089                            wait();
1090                        } catch (InterruptedException ex) {
1091                            // ignore.
1092                        }
1093                        continue;
1094                    }
1095                    r = mQueue.get(0);
1096                }
1097                storeImage(r.data, r.uri, r.title, r.loc, r.width, r.height,
1098                        r.orientation);
1099                synchronized (this) {
1100                    mQueue.remove(0);
1101                    notifyAll();  // the main thread may wait in addImage
1102                }
1103            }
1104        }
1105
1106        // Runs in main thread
1107        public void waitDone() {
1108            synchronized (this) {
1109                while (!mQueue.isEmpty()) {
1110                    try {
1111                        wait();
1112                    } catch (InterruptedException ex) {
1113                        // ignore.
1114                    }
1115                }
1116            }
1117        }
1118
1119        // Runs in main thread
1120        public void finish() {
1121            waitDone();
1122            synchronized (this) {
1123                mStop = true;
1124                notifyAll();
1125            }
1126            try {
1127                join();
1128            } catch (InterruptedException ex) {
1129                // ignore.
1130            }
1131        }
1132
1133        // Runs in saver thread
1134        private void storeImage(final byte[] data, Uri uri, String title,
1135                Location loc, int width, int height, int orientation) {
1136            boolean ok = Storage.updateImage(mContentResolver, uri, title, loc,
1137                    orientation, data, width, height);
1138            if (ok) {
1139                Util.broadcastNewPicture(mActivity, uri);
1140            }
1141        }
1142    }
1143
1144    private static class ImageNamer extends Thread {
1145        private boolean mRequestPending;
1146        private ContentResolver mResolver;
1147        private long mDateTaken;
1148        private int mWidth, mHeight;
1149        private boolean mStop;
1150        private Uri mUri;
1151        private String mTitle;
1152
1153        // Runs in main thread
1154        public ImageNamer() {
1155            start();
1156        }
1157
1158        // Runs in main thread
1159        public synchronized void prepareUri(ContentResolver resolver,
1160                long dateTaken, int width, int height, int rotation) {
1161            if (rotation % 180 != 0) {
1162                int tmp = width;
1163                width = height;
1164                height = tmp;
1165            }
1166            mRequestPending = true;
1167            mResolver = resolver;
1168            mDateTaken = dateTaken;
1169            mWidth = width;
1170            mHeight = height;
1171            notifyAll();
1172        }
1173
1174        // Runs in main thread
1175        public synchronized Uri getUri() {
1176            // wait until the request is done.
1177            while (mRequestPending) {
1178                try {
1179                    wait();
1180                } catch (InterruptedException ex) {
1181                    // ignore.
1182                }
1183            }
1184
1185            // return the uri generated
1186            Uri uri = mUri;
1187            mUri = null;
1188            return uri;
1189        }
1190
1191        // Runs in main thread, should be called after getUri().
1192        public synchronized String getTitle() {
1193            return mTitle;
1194        }
1195
1196        // Runs in namer thread
1197        @Override
1198        public synchronized void run() {
1199            while (true) {
1200                if (mStop) break;
1201                if (!mRequestPending) {
1202                    try {
1203                        wait();
1204                    } catch (InterruptedException ex) {
1205                        // ignore.
1206                    }
1207                    continue;
1208                }
1209                cleanOldUri();
1210                generateUri();
1211                mRequestPending = false;
1212                notifyAll();
1213            }
1214            cleanOldUri();
1215        }
1216
1217        // Runs in main thread
1218        public synchronized void finish() {
1219            mStop = true;
1220            notifyAll();
1221        }
1222
1223        // Runs in namer thread
1224        private void generateUri() {
1225            mTitle = Util.createJpegName(mDateTaken);
1226            mUri = Storage.newImage(mResolver, mTitle, mDateTaken, mWidth, mHeight);
1227        }
1228
1229        // Runs in namer thread
1230        private void cleanOldUri() {
1231            if (mUri == null) return;
1232            Storage.deleteImage(mResolver, mUri);
1233            mUri = null;
1234        }
1235    }
1236
1237    private void setCameraState(int state) {
1238        mCameraState = state;
1239        switch (state) {
1240            case PREVIEW_STOPPED:
1241            case SNAPSHOT_IN_PROGRESS:
1242            case FOCUSING:
1243            case SWITCHING_CAMERA:
1244                if (mGestures != null) mGestures.setEnabled(false);
1245                break;
1246            case IDLE:
1247                if (mGestures != null && mActivity.mShowCameraAppView) {
1248                    // Enable gestures only when the camera app view is visible
1249                    mGestures.setEnabled(true);
1250                }
1251                break;
1252        }
1253    }
1254
1255    private void animateFlash() {
1256        // Only animate when in full screen capture mode
1257        // i.e. If monkey/a user swipes to the gallery during picture taking,
1258        // don't show animation
1259        if (ApiHelper.HAS_SURFACE_TEXTURE && !mIsImageCaptureIntent
1260                && mActivity.mShowCameraAppView) {
1261            // Start capture animation.
1262            ((CameraScreenNail) mActivity.mCameraScreenNail).animateFlash(mDisplayRotation);
1263        }
1264    }
1265
1266    @Override
1267    public boolean capture() {
1268        // If we are already in the middle of taking a snapshot then ignore.
1269        if (mCameraDevice == null || mCameraState == SNAPSHOT_IN_PROGRESS
1270                || mCameraState == SWITCHING_CAMERA) {
1271            return false;
1272        }
1273        mCaptureStartTime = System.currentTimeMillis();
1274        mPostViewPictureCallbackTime = 0;
1275        mJpegImageData = null;
1276
1277        final boolean animateBefore = (mSceneMode == Util.SCENE_MODE_HDR);
1278
1279        if (animateBefore) {
1280            animateFlash();
1281            mActivity.hideSwitcher();
1282        }
1283
1284        // Set rotation and gps data.
1285        mJpegRotation = Util.getJpegRotation(mCameraId, mOrientation);
1286        mParameters.setRotation(mJpegRotation);
1287        Location loc = mLocationManager.getCurrentLocation();
1288        Util.setGpsParameters(mParameters, loc);
1289        mCameraDevice.setParameters(mParameters);
1290
1291        mCameraDevice.takePicture2(mShutterCallback, mRawPictureCallback,
1292                mPostViewPictureCallback, new JpegPictureCallback(loc),
1293                mCameraState, mFocusManager.getFocusState());
1294
1295        if (!animateBefore) {
1296            animateFlash();
1297        }
1298
1299        Size size = mParameters.getPictureSize();
1300        mImageNamer.prepareUri(mContentResolver, mCaptureStartTime,
1301                size.width, size.height, mJpegRotation);
1302
1303        mFaceDetectionStarted = false;
1304        setCameraState(SNAPSHOT_IN_PROGRESS);
1305        return true;
1306    }
1307
1308    @Override
1309    public void setFocusParameters() {
1310        setCameraParameters(UPDATE_PARAM_PREFERENCE);
1311    }
1312
1313    private int getPreferredCameraId(ComboPreferences preferences) {
1314        int intentCameraId = Util.getCameraFacingIntentExtras(mActivity);
1315        if (intentCameraId != -1) {
1316            // Testing purpose. Launch a specific camera through the intent
1317            // extras.
1318            return intentCameraId;
1319        } else {
1320            return CameraSettings.readPreferredCameraId(preferences);
1321        }
1322    }
1323
1324    private void setShowMenu(boolean show) {
1325        if (mOnScreenIndicators != null) {
1326            mOnScreenIndicators.setVisibility(show ? View.VISIBLE : View.GONE);
1327        }
1328        if (mMenu != null) {
1329            mMenu.setVisibility(show ? View.VISIBLE : View.GONE);
1330        }
1331    }
1332
1333    @Override
1334    public void onFullScreenChanged(boolean full) {
1335        if (mFaceView != null) {
1336            mFaceView.setBlockDraw(!full);
1337        }
1338        if (mPopup != null) {
1339            dismissPopup(false, full);
1340        }
1341        if (mGestures != null) {
1342            mGestures.setEnabled(full);
1343        }
1344        if (mRenderOverlay != null) {
1345            // this can not happen in capture mode
1346            mRenderOverlay.setVisibility(full ? View.VISIBLE : View.GONE);
1347        }
1348        if (mPieRenderer != null) {
1349            mPieRenderer.setBlockFocus(!full);
1350        }
1351        setShowMenu(full);
1352        if (mBlocker != null) {
1353            mBlocker.setVisibility(full ? View.VISIBLE : View.GONE);
1354        }
1355        if (ApiHelper.HAS_SURFACE_TEXTURE) {
1356            if (mActivity.mCameraScreenNail != null) {
1357                ((CameraScreenNail) mActivity.mCameraScreenNail).setFullScreen(full);
1358            }
1359            return;
1360        }
1361        if (full) {
1362            mPreviewSurfaceView.expand();
1363        } else {
1364            mPreviewSurfaceView.shrink();
1365        }
1366    }
1367
1368    @Override
1369    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
1370        Log.v(TAG, "surfaceChanged:" + holder + " width=" + width + ". height="
1371                + height);
1372    }
1373
1374    @Override
1375    public void surfaceCreated(SurfaceHolder holder) {
1376        Log.v(TAG, "surfaceCreated: " + holder);
1377        mCameraSurfaceHolder = holder;
1378        // Do not access the camera if camera start up thread is not finished.
1379        if (mCameraDevice == null || mCameraStartUpThread != null) return;
1380
1381        mCameraDevice.setPreviewDisplayAsync(holder);
1382        // This happens when onConfigurationChanged arrives, surface has been
1383        // destroyed, and there is no onFullScreenChanged.
1384        if (mCameraState == PREVIEW_STOPPED) {
1385            setupPreview();
1386        }
1387    }
1388
1389    @Override
1390    public void surfaceDestroyed(SurfaceHolder holder) {
1391        Log.v(TAG, "surfaceDestroyed: " + holder);
1392        mCameraSurfaceHolder = null;
1393        stopPreview();
1394    }
1395
1396    private void updateSceneModeUI() {
1397        // If scene mode is set, we cannot set flash mode, white balance, and
1398        // focus mode, instead, we read it from driver
1399        if (!Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) {
1400            overrideCameraSettings(mParameters.getFlashMode(),
1401                    mParameters.getWhiteBalance(), mParameters.getFocusMode());
1402        } else {
1403            overrideCameraSettings(null, null, null);
1404        }
1405    }
1406
1407    private void overrideCameraSettings(final String flashMode,
1408            final String whiteBalance, final String focusMode) {
1409        if (mPhotoControl != null) {
1410//            mPieControl.enableFilter(true);
1411            mPhotoControl.overrideSettings(
1412                    CameraSettings.KEY_FLASH_MODE, flashMode,
1413                    CameraSettings.KEY_WHITE_BALANCE, whiteBalance,
1414                    CameraSettings.KEY_FOCUS_MODE, focusMode);
1415//            mPieControl.enableFilter(false);
1416        }
1417    }
1418
1419    private void loadCameraPreferences() {
1420        CameraSettings settings = new CameraSettings(mActivity, mInitialParams,
1421                mCameraId, CameraHolder.instance().getCameraInfo());
1422        mPreferenceGroup = settings.getPreferenceGroup(R.xml.camera_preferences);
1423    }
1424
1425    @Override
1426    public boolean collapseCameraControls() {
1427        // Remove all the popups/dialog boxes
1428        boolean ret = false;
1429        if (mPopup != null) {
1430            dismissPopup(false);
1431            ret = true;
1432        }
1433        return ret;
1434    }
1435
1436    public boolean removeTopLevelPopup() {
1437        // Remove the top level popup or dialog box and return true if there's any
1438        if (mPopup != null) {
1439            dismissPopup(true);
1440            return true;
1441        }
1442        return false;
1443    }
1444
1445    @Override
1446    public void onOrientationChanged(int orientation) {
1447        // We keep the last known orientation. So if the user first orient
1448        // the camera then point the camera to floor or sky, we still have
1449        // the correct orientation.
1450        if (orientation == OrientationEventListener.ORIENTATION_UNKNOWN) return;
1451        mOrientation = Util.roundOrientation(orientation, mOrientation);
1452        // When the screen is unlocked, display rotation may change. Always
1453        // calculate the up-to-date orientationCompensation.
1454        int orientationCompensation =
1455                (mOrientation + Util.getDisplayRotation(mActivity)) % 360;
1456        if (mOrientationCompensation != orientationCompensation) {
1457            mOrientationCompensation = orientationCompensation;
1458            if (mFaceView != null) {
1459                mFaceView.setOrientation(mOrientationCompensation, true);
1460            }
1461            setDisplayOrientation();
1462        }
1463
1464        // Show the toast after getting the first orientation changed.
1465        if (mHandler.hasMessages(SHOW_TAP_TO_FOCUS_TOAST)) {
1466            mHandler.removeMessages(SHOW_TAP_TO_FOCUS_TOAST);
1467            showTapToFocusToast();
1468        }
1469    }
1470
1471    @Override
1472    public void onStop() {
1473        if (mMediaProviderClient != null) {
1474            mMediaProviderClient.release();
1475            mMediaProviderClient = null;
1476        }
1477    }
1478
1479    // onClick handler for R.id.btn_done
1480    @OnClickAttr
1481    public void onReviewDoneClicked(View v) {
1482        doAttach();
1483    }
1484
1485    // onClick handler for R.id.btn_cancel
1486    @OnClickAttr
1487    public void onReviewCancelClicked(View v) {
1488        doCancel();
1489    }
1490
1491    // onClick handler for R.id.btn_retake
1492    @OnClickAttr
1493    public void onReviewRetakeClicked(View v) {
1494        if (mPaused)
1495            return;
1496
1497        hidePostCaptureAlert();
1498        setupPreview();
1499    }
1500
1501    private void doAttach() {
1502        if (mPaused) {
1503            return;
1504        }
1505
1506        byte[] data = mJpegImageData;
1507
1508        if (mCropValue == null) {
1509            // First handle the no crop case -- just return the value.  If the
1510            // caller specifies a "save uri" then write the data to its
1511            // stream. Otherwise, pass back a scaled down version of the bitmap
1512            // directly in the extras.
1513            if (mSaveUri != null) {
1514                OutputStream outputStream = null;
1515                try {
1516                    outputStream = mContentResolver.openOutputStream(mSaveUri);
1517                    outputStream.write(data);
1518                    outputStream.close();
1519
1520                    mActivity.setResultEx(Activity.RESULT_OK);
1521                    mActivity.finish();
1522                } catch (IOException ex) {
1523                    // ignore exception
1524                } finally {
1525                    Util.closeSilently(outputStream);
1526                }
1527            } else {
1528                int orientation = Exif.getOrientation(data);
1529                Bitmap bitmap = Util.makeBitmap(data, 50 * 1024);
1530                bitmap = Util.rotate(bitmap, orientation);
1531                mActivity.setResultEx(Activity.RESULT_OK,
1532                        new Intent("inline-data").putExtra("data", bitmap));
1533                mActivity.finish();
1534            }
1535        } else {
1536            // Save the image to a temp file and invoke the cropper
1537            Uri tempUri = null;
1538            FileOutputStream tempStream = null;
1539            try {
1540                File path = mActivity.getFileStreamPath(sTempCropFilename);
1541                path.delete();
1542                tempStream = mActivity.openFileOutput(sTempCropFilename, 0);
1543                tempStream.write(data);
1544                tempStream.close();
1545                tempUri = Uri.fromFile(path);
1546            } catch (FileNotFoundException ex) {
1547                mActivity.setResultEx(Activity.RESULT_CANCELED);
1548                mActivity.finish();
1549                return;
1550            } catch (IOException ex) {
1551                mActivity.setResultEx(Activity.RESULT_CANCELED);
1552                mActivity.finish();
1553                return;
1554            } finally {
1555                Util.closeSilently(tempStream);
1556            }
1557
1558            Bundle newExtras = new Bundle();
1559            if (mCropValue.equals("circle")) {
1560                newExtras.putString("circleCrop", "true");
1561            }
1562            if (mSaveUri != null) {
1563                newExtras.putParcelable(MediaStore.EXTRA_OUTPUT, mSaveUri);
1564            } else {
1565                newExtras.putBoolean("return-data", true);
1566            }
1567            if (mActivity.isSecureCamera()) {
1568                newExtras.putBoolean(CropImage.KEY_SHOW_WHEN_LOCKED, true);
1569            }
1570
1571            Intent cropIntent = new Intent("com.android.camera.action.CROP");
1572
1573            cropIntent.setData(tempUri);
1574            cropIntent.putExtras(newExtras);
1575
1576            mActivity.startActivityForResult(cropIntent, REQUEST_CROP);
1577        }
1578    }
1579
1580    private void doCancel() {
1581        mActivity.setResultEx(Activity.RESULT_CANCELED, new Intent());
1582        mActivity.finish();
1583    }
1584
1585    @Override
1586    public void onShutterButtonFocus(boolean pressed) {
1587        if (mPaused || collapseCameraControls()
1588                || (mCameraState == SNAPSHOT_IN_PROGRESS)
1589                || (mCameraState == PREVIEW_STOPPED)) return;
1590
1591        // Do not do focus if there is not enough storage.
1592        if (pressed && !canTakePicture()) return;
1593
1594        if (pressed) {
1595            mFocusManager.onShutterDown();
1596        } else {
1597            mFocusManager.onShutterUp();
1598        }
1599    }
1600
1601    @Override
1602    public void onShutterButtonClick() {
1603        if (mPaused || collapseCameraControls()
1604                || (mCameraState == SWITCHING_CAMERA)
1605                || (mCameraState == PREVIEW_STOPPED)) return;
1606
1607        // Do not take the picture if there is not enough storage.
1608        if (mActivity.getStorageSpace() <= Storage.LOW_STORAGE_THRESHOLD) {
1609            Log.i(TAG, "Not enough space or storage not ready. remaining="
1610                    + mActivity.getStorageSpace());
1611            return;
1612        }
1613        Log.v(TAG, "onShutterButtonClick: mCameraState=" + mCameraState);
1614
1615        // If the user wants to do a snapshot while the previous one is still
1616        // in progress, remember the fact and do it after we finish the previous
1617        // one and re-start the preview. Snapshot in progress also includes the
1618        // state that autofocus is focusing and a picture will be taken when
1619        // focus callback arrives.
1620        if ((mFocusManager.isFocusingSnapOnFinish() || mCameraState == SNAPSHOT_IN_PROGRESS)
1621                && !mIsImageCaptureIntent) {
1622            mSnapshotOnIdle = true;
1623            return;
1624        }
1625
1626        mSnapshotOnIdle = false;
1627        mFocusManager.doSnap();
1628    }
1629
1630    @Override
1631    public void installIntentFilter() {
1632    }
1633
1634    @Override
1635    public boolean updateStorageHintOnResume() {
1636        return mFirstTimeInitialized;
1637    }
1638
1639    @Override
1640    public void updateCameraAppView() {
1641    }
1642
1643    @Override
1644    public void onResumeBeforeSuper() {
1645        mPaused = false;
1646    }
1647
1648    @Override
1649    public void onResumeAfterSuper() {
1650        if (mOpenCameraFail || mCameraDisabled) return;
1651
1652        mJpegPictureCallbackTime = 0;
1653        mZoomValue = 0;
1654
1655        // Start the preview if it is not started.
1656        if (mCameraState == PREVIEW_STOPPED && mCameraStartUpThread == null) {
1657            resetExposureCompensation();
1658            mCameraStartUpThread = new CameraStartUpThread();
1659            mCameraStartUpThread.start();
1660        }
1661
1662        // If first time initialization is not finished, put it in the
1663        // message queue.
1664        if (!mFirstTimeInitialized) {
1665            mHandler.sendEmptyMessage(FIRST_TIME_INIT);
1666        } else {
1667            initializeSecondTime();
1668        }
1669        keepScreenOnAwhile();
1670
1671        // Dismiss open menu if exists.
1672        PopupManager.getInstance(mActivity).notifyShowPopup(null);
1673    }
1674
1675    void waitCameraStartUpThread() {
1676        try {
1677            if (mCameraStartUpThread != null) {
1678                mCameraStartUpThread.cancel();
1679                mCameraStartUpThread.join();
1680                mCameraStartUpThread = null;
1681                setCameraState(IDLE);
1682            }
1683        } catch (InterruptedException e) {
1684            // ignore
1685        }
1686    }
1687
1688    @Override
1689    public void onPauseBeforeSuper() {
1690        mPaused = true;
1691    }
1692
1693    @Override
1694    public void onPauseAfterSuper() {
1695        // Wait the camera start up thread to finish.
1696        waitCameraStartUpThread();
1697
1698        // When camera is started from secure lock screen for the first time
1699        // after screen on, the activity gets onCreate->onResume->onPause->onResume.
1700        // To reduce the latency, keep the camera for a short time so it does
1701        // not need to be opened again.
1702        if (mCameraDevice != null && mActivity.isSecureCamera()
1703                && ActivityBase.isFirstStartAfterScreenOn()) {
1704            ActivityBase.resetFirstStartAfterScreenOn();
1705            CameraHolder.instance().keep(KEEP_CAMERA_TIMEOUT);
1706        }
1707        // Reset the focus first. Camera CTS does not guarantee that
1708        // cancelAutoFocus is allowed after preview stops.
1709        if (mCameraDevice != null && mCameraState != PREVIEW_STOPPED) {
1710            mCameraDevice.cancelAutoFocus();
1711        }
1712        stopPreview();
1713        // Close the camera now because other activities may need to use it.
1714        closeCamera();
1715        if (mSurfaceTexture != null) {
1716            ((CameraScreenNail) mActivity.mCameraScreenNail).releaseSurfaceTexture();
1717            mSurfaceTexture = null;
1718        }
1719        resetScreenOn();
1720
1721        // Clear UI.
1722        collapseCameraControls();
1723        if (mFaceView != null) mFaceView.clear();
1724
1725        if (mFirstTimeInitialized) {
1726            if (mImageSaver != null) {
1727                mImageSaver.finish();
1728                mImageSaver = null;
1729                mImageNamer.finish();
1730                mImageNamer = null;
1731            }
1732        }
1733
1734        if (mLocationManager != null) mLocationManager.recordLocation(false);
1735        updateExposureOnScreenIndicator(0);
1736
1737        // If we are in an image capture intent and has taken
1738        // a picture, we just clear it in onPause.
1739        mJpegImageData = null;
1740
1741        // Remove the messages in the event queue.
1742        mHandler.removeMessages(SETUP_PREVIEW);
1743        mHandler.removeMessages(FIRST_TIME_INIT);
1744        mHandler.removeMessages(CHECK_DISPLAY_ROTATION);
1745        mHandler.removeMessages(SWITCH_CAMERA);
1746        mHandler.removeMessages(SWITCH_CAMERA_START_ANIMATION);
1747        mHandler.removeMessages(CAMERA_OPEN_DONE);
1748        mHandler.removeMessages(START_PREVIEW_DONE);
1749        mHandler.removeMessages(OPEN_CAMERA_FAIL);
1750        mHandler.removeMessages(CAMERA_DISABLED);
1751
1752        mPendingSwitchCameraId = -1;
1753        if (mFocusManager != null) mFocusManager.removeMessages();
1754    }
1755
1756    private void initializeControlByIntent() {
1757        mBlocker = mRootView.findViewById(R.id.blocker);
1758        mMenu = mRootView.findViewById(R.id.menu);
1759        mMenu.setOnClickListener(new OnClickListener() {
1760            @Override
1761            public void onClick(View v) {
1762                if (mPieRenderer != null) {
1763                    mPieRenderer.showInCenter();
1764                }
1765            }
1766        });
1767        if (mIsImageCaptureIntent) {
1768
1769            mActivity.hideSwitcher();
1770            // Cannot use RotateImageView for "done" and "cancel" button because
1771            // the tablet layout uses RotateLayout, which cannot be cast to
1772            // RotateImageView.
1773            mReviewDoneButton = (Rotatable) mRootView.findViewById(R.id.btn_done);
1774            mReviewCancelButton = (Rotatable) mRootView.findViewById(R.id.btn_cancel);
1775            mReviewRetakeButton = mRootView.findViewById(R.id.btn_retake);
1776            ((View) mReviewCancelButton).setVisibility(View.VISIBLE);
1777
1778            ((View) mReviewDoneButton).setOnClickListener(new OnClickListener() {
1779                @Override
1780                public void onClick(View v) {
1781                    onReviewDoneClicked(v);
1782                }
1783            });
1784            ((View) mReviewCancelButton).setOnClickListener(new OnClickListener() {
1785                @Override
1786                public void onClick(View v) {
1787                    onReviewCancelClicked(v);
1788                }
1789            });
1790
1791            mReviewRetakeButton.setOnClickListener(new OnClickListener() {
1792                @Override
1793                public void onClick(View v) {
1794                    onReviewRetakeClicked(v);
1795                }
1796            });
1797
1798            // Not grayed out upon disabled, to make the follow-up fade-out
1799            // effect look smooth. Note that the review done button in tablet
1800            // layout is not a TwoStateImageView.
1801            if (mReviewDoneButton instanceof TwoStateImageView) {
1802                ((TwoStateImageView) mReviewDoneButton).enableFilter(false);
1803            }
1804
1805            setupCaptureParams();
1806        }
1807    }
1808
1809    /**
1810     * The focus manager is the first UI related element to get initialized,
1811     * and it requires the RenderOverlay, so initialize it here
1812     */
1813    private void initializeFocusManager() {
1814        // Create FocusManager object. startPreview needs it.
1815        mRenderOverlay = (RenderOverlay) mRootView.findViewById(R.id.render_overlay);
1816        // if mFocusManager not null, reuse it
1817        // otherwise create a new instance
1818        if (mFocusManager != null) {
1819            mFocusManager.removeMessages();
1820        } else {
1821            CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId];
1822            boolean mirror = (info.facing == CameraInfo.CAMERA_FACING_FRONT);
1823            String[] defaultFocusModes = mActivity.getResources().getStringArray(
1824                    R.array.pref_camera_focusmode_default_array);
1825            mFocusManager = new FocusOverlayManager(mPreferences, defaultFocusModes,
1826                    mInitialParams, this, mirror,
1827                    mActivity.getMainLooper());
1828        }
1829    }
1830
1831    private void initializeMiscControls() {
1832        // startPreview needs this.
1833        mPreviewFrameLayout = (PreviewFrameLayout) mRootView.findViewById(R.id.frame);
1834        // Set touch focus listener.
1835        mActivity.setSingleTapUpListener(mPreviewFrameLayout);
1836
1837        mFaceView = (FaceView) mRootView.findViewById(R.id.face_view);
1838        mPreviewFrameLayout.setOnSizeChangedListener(this);
1839        mPreviewFrameLayout.setOnLayoutChangeListener(mActivity);
1840        if (!ApiHelper.HAS_SURFACE_TEXTURE) {
1841            mPreviewSurfaceView =
1842                    (PreviewSurfaceView) mRootView.findViewById(R.id.preview_surface_view);
1843            mPreviewSurfaceView.setVisibility(View.VISIBLE);
1844            mPreviewSurfaceView.getHolder().addCallback(this);
1845        }
1846    }
1847
1848    @Override
1849    public void onConfigurationChanged(Configuration newConfig) {
1850        Log.v(TAG, "onConfigurationChanged");
1851        setDisplayOrientation();
1852
1853        ((ViewGroup) mRootView).removeAllViews();
1854        LayoutInflater inflater = mActivity.getLayoutInflater();
1855        inflater.inflate(R.layout.photo_module, (ViewGroup) mRootView);
1856
1857        // from onCreate()
1858        initializeControlByIntent();
1859
1860        initializeFocusManager();
1861        initializeMiscControls();
1862        loadCameraPreferences();
1863
1864        // from initializeFirstTime()
1865        mShutterButton = mActivity.getShutterButton();
1866        mShutterButton.setOnShutterButtonListener(this);
1867        initializeZoom();
1868        initOnScreenIndicator();
1869        updateOnScreenIndicators();
1870        if (mFaceView != null) {
1871            mFaceView.clear();
1872            mFaceView.setVisibility(View.VISIBLE);
1873            mFaceView.setDisplayOrientation(mDisplayOrientation);
1874            CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId];
1875            mFaceView.setMirror(info.facing == CameraInfo.CAMERA_FACING_FRONT);
1876            mFaceView.resume();
1877            mFocusManager.setFaceView(mFaceView);
1878        }
1879        initializeRenderOverlay();
1880        onFullScreenChanged(mActivity.isInCameraApp());
1881        if (mJpegImageData != null) {  // Jpeg data found, picture has been taken.
1882            showPostCaptureAlert();
1883        }
1884    }
1885
1886    @Override
1887    public void onActivityResult(
1888            int requestCode, int resultCode, Intent data) {
1889        switch (requestCode) {
1890            case REQUEST_CROP: {
1891                Intent intent = new Intent();
1892                if (data != null) {
1893                    Bundle extras = data.getExtras();
1894                    if (extras != null) {
1895                        intent.putExtras(extras);
1896                    }
1897                }
1898                mActivity.setResultEx(resultCode, intent);
1899                mActivity.finish();
1900
1901                File path = mActivity.getFileStreamPath(sTempCropFilename);
1902                path.delete();
1903
1904                break;
1905            }
1906        }
1907    }
1908
1909    private boolean canTakePicture() {
1910        return isCameraIdle() && (mActivity.getStorageSpace() > Storage.LOW_STORAGE_THRESHOLD);
1911    }
1912
1913    @Override
1914    public void autoFocus() {
1915        mFocusStartTime = System.currentTimeMillis();
1916        mCameraDevice.autoFocus(mAutoFocusCallback);
1917        setCameraState(FOCUSING);
1918    }
1919
1920    @Override
1921    public void cancelAutoFocus() {
1922        mCameraDevice.cancelAutoFocus();
1923        setCameraState(IDLE);
1924        setCameraParameters(UPDATE_PARAM_PREFERENCE);
1925    }
1926
1927    // Preview area is touched. Handle touch focus.
1928    @Override
1929    public void onSingleTapUp(View view, int x, int y) {
1930        if (mPaused || mCameraDevice == null || !mFirstTimeInitialized
1931                || mCameraState == SNAPSHOT_IN_PROGRESS
1932                || mCameraState == SWITCHING_CAMERA
1933                || mCameraState == PREVIEW_STOPPED) {
1934            return;
1935        }
1936
1937        // Do not trigger touch focus if popup window is opened.
1938        if (removeTopLevelPopup()) return;
1939
1940        // Check if metering area or focus area is supported.
1941        if (!mFocusAreaSupported && !mMeteringAreaSupported) return;
1942        mFocusManager.onSingleTapUp(x, y);
1943    }
1944
1945    @Override
1946    public boolean onBackPressed() {
1947        if (mPieRenderer != null && mPieRenderer.showsItems()) {
1948            mPieRenderer.hide();
1949            return true;
1950        }
1951        // In image capture mode, back button should:
1952        // 1) if there is any popup, dismiss them, 2) otherwise, get out of image capture
1953        if (mIsImageCaptureIntent) {
1954            if (!removeTopLevelPopup()) {
1955                // no popup to dismiss, cancel image capture
1956                doCancel();
1957            }
1958            return true;
1959        } else if (!isCameraIdle()) {
1960            // ignore backs while we're taking a picture
1961            return true;
1962        } else {
1963            return removeTopLevelPopup();
1964        }
1965    }
1966
1967    @Override
1968    public boolean onKeyDown(int keyCode, KeyEvent event) {
1969        switch (keyCode) {
1970            case KeyEvent.KEYCODE_FOCUS:
1971                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1972                    onShutterButtonFocus(true);
1973                }
1974                return true;
1975            case KeyEvent.KEYCODE_CAMERA:
1976                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1977                    onShutterButtonClick();
1978                }
1979                return true;
1980            case KeyEvent.KEYCODE_DPAD_CENTER:
1981                // If we get a dpad center event without any focused view, move
1982                // the focus to the shutter button and press it.
1983                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1984                    // Start auto-focus immediately to reduce shutter lag. After
1985                    // the shutter button gets the focus, onShutterButtonFocus()
1986                    // will be called again but it is fine.
1987                    if (removeTopLevelPopup()) return true;
1988                    onShutterButtonFocus(true);
1989                    if (mShutterButton.isInTouchMode()) {
1990                        mShutterButton.requestFocusFromTouch();
1991                    } else {
1992                        mShutterButton.requestFocus();
1993                    }
1994                    mShutterButton.setPressed(true);
1995                }
1996                return true;
1997        }
1998        return false;
1999    }
2000
2001    @Override
2002    public boolean onKeyUp(int keyCode, KeyEvent event) {
2003        switch (keyCode) {
2004            case KeyEvent.KEYCODE_FOCUS:
2005                if (mFirstTimeInitialized) {
2006                    onShutterButtonFocus(false);
2007                }
2008                return true;
2009        }
2010        return false;
2011    }
2012
2013    @TargetApi(ApiHelper.VERSION_CODES.ICE_CREAM_SANDWICH)
2014    private void closeCamera() {
2015        if (mCameraDevice != null) {
2016            mCameraDevice.setZoomChangeListener(null);
2017            if(ApiHelper.HAS_FACE_DETECTION) {
2018                mCameraDevice.setFaceDetectionListener(null);
2019            }
2020            mCameraDevice.setErrorCallback(null);
2021            CameraHolder.instance().release();
2022            mFaceDetectionStarted = false;
2023            mCameraDevice = null;
2024            setCameraState(PREVIEW_STOPPED);
2025            mFocusManager.onCameraReleased();
2026        }
2027    }
2028
2029    private void setDisplayOrientation() {
2030        mDisplayRotation = Util.getDisplayRotation(mActivity);
2031        mDisplayOrientation = Util.getDisplayOrientation(mDisplayRotation, mCameraId);
2032        mCameraDisplayOrientation = Util.getDisplayOrientation(0, mCameraId);
2033        if (mFaceView != null) {
2034            mFaceView.setDisplayOrientation(mDisplayOrientation);
2035        }
2036        if (mFocusManager != null) {
2037            mFocusManager.setDisplayOrientation(mDisplayOrientation);
2038        }
2039        // GLRoot also uses the DisplayRotation, and needs to be told to layout to update
2040        mActivity.getGLRoot().requestLayoutContentPane();
2041    }
2042
2043    // Only called by UI thread.
2044    private void setupPreview() {
2045        mFocusManager.resetTouchFocus();
2046        startPreview();
2047        setCameraState(IDLE);
2048        startFaceDetection();
2049    }
2050
2051    // This can be called by UI Thread or CameraStartUpThread. So this should
2052    // not modify the views.
2053    private void startPreview() {
2054        mCameraDevice.setErrorCallback(mErrorCallback);
2055
2056        // ICS camera frameworks has a bug. Face detection state is not cleared
2057        // after taking a picture. Stop the preview to work around it. The bug
2058        // was fixed in JB.
2059        if (mCameraState != PREVIEW_STOPPED) stopPreview();
2060
2061        setDisplayOrientation();
2062
2063        if (!mSnapshotOnIdle) {
2064            // If the focus mode is continuous autofocus, call cancelAutoFocus to
2065            // resume it because it may have been paused by autoFocus call.
2066            if (Util.FOCUS_MODE_CONTINUOUS_PICTURE.equals(mFocusManager.getFocusMode())) {
2067                mCameraDevice.cancelAutoFocus();
2068            }
2069            mFocusManager.setAeAwbLock(false); // Unlock AE and AWB.
2070        }
2071        setCameraParameters(UPDATE_PARAM_ALL);
2072
2073        if (ApiHelper.HAS_SURFACE_TEXTURE) {
2074            CameraScreenNail screenNail = (CameraScreenNail) mActivity.mCameraScreenNail;
2075            if (mSurfaceTexture == null) {
2076                Size size = mParameters.getPreviewSize();
2077                if (mCameraDisplayOrientation % 180 == 0) {
2078                    screenNail.setSize(size.width, size.height);
2079                } else {
2080                    screenNail.setSize(size.height, size.width);
2081                }
2082                screenNail.enableAspectRatioClamping();
2083                mActivity.notifyScreenNailChanged();
2084                screenNail.acquireSurfaceTexture();
2085                mSurfaceTexture = screenNail.getSurfaceTexture();
2086            }
2087            mCameraDevice.setDisplayOrientation(mCameraDisplayOrientation);
2088            mCameraDevice.setPreviewTextureAsync((SurfaceTexture) mSurfaceTexture);
2089        } else {
2090            mCameraDevice.setDisplayOrientation(mDisplayOrientation);
2091            mCameraDevice.setPreviewDisplayAsync(mCameraSurfaceHolder);
2092        }
2093
2094        Log.v(TAG, "startPreview");
2095        mCameraDevice.startPreviewAsync();
2096
2097        mFocusManager.onPreviewStarted();
2098
2099        if (mSnapshotOnIdle) {
2100            mHandler.post(mDoSnapRunnable);
2101        }
2102    }
2103
2104    private void stopPreview() {
2105        if (mCameraDevice != null && mCameraState != PREVIEW_STOPPED) {
2106            Log.v(TAG, "stopPreview");
2107            mCameraDevice.stopPreview();
2108            mFaceDetectionStarted = false;
2109        }
2110        setCameraState(PREVIEW_STOPPED);
2111        if (mFocusManager != null) mFocusManager.onPreviewStopped();
2112    }
2113
2114    @SuppressWarnings("deprecation")
2115    private void updateCameraParametersInitialize() {
2116        // Reset preview frame rate to the maximum because it may be lowered by
2117        // video camera application.
2118        List<Integer> frameRates = mParameters.getSupportedPreviewFrameRates();
2119        if (frameRates != null) {
2120            Integer max = Collections.max(frameRates);
2121            mParameters.setPreviewFrameRate(max);
2122        }
2123
2124        mParameters.set(Util.RECORDING_HINT, Util.FALSE);
2125
2126        // Disable video stabilization. Convenience methods not available in API
2127        // level <= 14
2128        String vstabSupported = mParameters.get("video-stabilization-supported");
2129        if ("true".equals(vstabSupported)) {
2130            mParameters.set("video-stabilization", "false");
2131        }
2132    }
2133
2134    private void updateCameraParametersZoom() {
2135        // Set zoom.
2136        if (mParameters.isZoomSupported()) {
2137            mParameters.setZoom(mZoomValue);
2138        }
2139    }
2140
2141    @TargetApi(ApiHelper.VERSION_CODES.JELLY_BEAN)
2142    private void setAutoExposureLockIfSupported() {
2143        if (mAeLockSupported) {
2144            mParameters.setAutoExposureLock(mFocusManager.getAeAwbLock());
2145        }
2146    }
2147
2148    @TargetApi(ApiHelper.VERSION_CODES.JELLY_BEAN)
2149    private void setAutoWhiteBalanceLockIfSupported() {
2150        if (mAwbLockSupported) {
2151            mParameters.setAutoWhiteBalanceLock(mFocusManager.getAeAwbLock());
2152        }
2153    }
2154
2155    @TargetApi(ApiHelper.VERSION_CODES.ICE_CREAM_SANDWICH)
2156    private void setFocusAreasIfSupported() {
2157        if (mFocusAreaSupported) {
2158            mParameters.setFocusAreas(mFocusManager.getFocusAreas());
2159        }
2160    }
2161
2162    @TargetApi(ApiHelper.VERSION_CODES.ICE_CREAM_SANDWICH)
2163    private void setMeteringAreasIfSupported() {
2164        if (mMeteringAreaSupported) {
2165            // Use the same area for focus and metering.
2166            mParameters.setMeteringAreas(mFocusManager.getMeteringAreas());
2167        }
2168    }
2169
2170    private void updateCameraParametersPreference() {
2171        setAutoExposureLockIfSupported();
2172        setAutoWhiteBalanceLockIfSupported();
2173        setFocusAreasIfSupported();
2174        setMeteringAreasIfSupported();
2175
2176        // Set picture size.
2177        String pictureSize = mPreferences.getString(
2178                CameraSettings.KEY_PICTURE_SIZE, null);
2179        if (pictureSize == null) {
2180            CameraSettings.initialCameraPictureSize(mActivity, mParameters);
2181        } else {
2182            List<Size> supported = mParameters.getSupportedPictureSizes();
2183            CameraSettings.setCameraPictureSize(
2184                    pictureSize, supported, mParameters);
2185        }
2186        Size size = mParameters.getPictureSize();
2187
2188        // Set a preview size that is closest to the viewfinder height and has
2189        // the right aspect ratio.
2190        List<Size> sizes = mParameters.getSupportedPreviewSizes();
2191        Size optimalSize = Util.getOptimalPreviewSize(mActivity, sizes,
2192                (double) size.width / size.height);
2193        Size original = mParameters.getPreviewSize();
2194        if (!original.equals(optimalSize)) {
2195            mParameters.setPreviewSize(optimalSize.width, optimalSize.height);
2196
2197            // Zoom related settings will be changed for different preview
2198            // sizes, so set and read the parameters to get latest values
2199            mCameraDevice.setParameters(mParameters);
2200            mParameters = mCameraDevice.getParameters();
2201        }
2202        Log.v(TAG, "Preview size is " + optimalSize.width + "x" + optimalSize.height);
2203
2204        // Since changing scene mode may change supported values, set scene mode
2205        // first. HDR is a scene mode. To promote it in UI, it is stored in a
2206        // separate preference.
2207        String hdr = mPreferences.getString(CameraSettings.KEY_CAMERA_HDR,
2208                mActivity.getString(R.string.pref_camera_hdr_default));
2209        if (mActivity.getString(R.string.setting_on_value).equals(hdr)) {
2210            mSceneMode = Util.SCENE_MODE_HDR;
2211        } else {
2212            mSceneMode = mPreferences.getString(
2213                CameraSettings.KEY_SCENE_MODE,
2214                mActivity.getString(R.string.pref_camera_scenemode_default));
2215        }
2216        if (Util.isSupported(mSceneMode, mParameters.getSupportedSceneModes())) {
2217            if (!mParameters.getSceneMode().equals(mSceneMode)) {
2218                mParameters.setSceneMode(mSceneMode);
2219
2220                // Setting scene mode will change the settings of flash mode,
2221                // white balance, and focus mode. Here we read back the
2222                // parameters, so we can know those settings.
2223                mCameraDevice.setParameters(mParameters);
2224                mParameters = mCameraDevice.getParameters();
2225            }
2226        } else {
2227            mSceneMode = mParameters.getSceneMode();
2228            if (mSceneMode == null) {
2229                mSceneMode = Parameters.SCENE_MODE_AUTO;
2230            }
2231        }
2232
2233        // Set JPEG quality.
2234        int jpegQuality = CameraProfile.getJpegEncodingQualityParameter(mCameraId,
2235                CameraProfile.QUALITY_HIGH);
2236        mParameters.setJpegQuality(jpegQuality);
2237
2238        // For the following settings, we need to check if the settings are
2239        // still supported by latest driver, if not, ignore the settings.
2240
2241        // Set exposure compensation
2242        int value = CameraSettings.readExposure(mPreferences);
2243        int max = mParameters.getMaxExposureCompensation();
2244        int min = mParameters.getMinExposureCompensation();
2245        if (value >= min && value <= max) {
2246            mParameters.setExposureCompensation(value);
2247        } else {
2248            Log.w(TAG, "invalid exposure range: " + value);
2249        }
2250
2251        if (Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) {
2252            // Set flash mode.
2253            String flashMode = mPreferences.getString(
2254                    CameraSettings.KEY_FLASH_MODE,
2255                    mActivity.getString(R.string.pref_camera_flashmode_default));
2256            List<String> supportedFlash = mParameters.getSupportedFlashModes();
2257            if (Util.isSupported(flashMode, supportedFlash)) {
2258                mParameters.setFlashMode(flashMode);
2259            } else {
2260                flashMode = mParameters.getFlashMode();
2261                if (flashMode == null) {
2262                    flashMode = mActivity.getString(
2263                            R.string.pref_camera_flashmode_no_flash);
2264                }
2265            }
2266
2267            // Set white balance parameter.
2268            String whiteBalance = mPreferences.getString(
2269                    CameraSettings.KEY_WHITE_BALANCE,
2270                    mActivity.getString(R.string.pref_camera_whitebalance_default));
2271            if (Util.isSupported(whiteBalance,
2272                    mParameters.getSupportedWhiteBalance())) {
2273                mParameters.setWhiteBalance(whiteBalance);
2274            } else {
2275                whiteBalance = mParameters.getWhiteBalance();
2276                if (whiteBalance == null) {
2277                    whiteBalance = Parameters.WHITE_BALANCE_AUTO;
2278                }
2279            }
2280
2281            // Set focus mode.
2282            mFocusManager.overrideFocusMode(null);
2283            mParameters.setFocusMode(mFocusManager.getFocusMode());
2284        } else {
2285            mFocusManager.overrideFocusMode(mParameters.getFocusMode());
2286        }
2287
2288        if (mContinousFocusSupported && ApiHelper.HAS_AUTO_FOCUS_MOVE_CALLBACK) {
2289            updateAutoFocusMoveCallback();
2290        }
2291    }
2292
2293    @TargetApi(ApiHelper.VERSION_CODES.JELLY_BEAN)
2294    private void updateAutoFocusMoveCallback() {
2295        if (mParameters.getFocusMode().equals(Util.FOCUS_MODE_CONTINUOUS_PICTURE)) {
2296            mCameraDevice.setAutoFocusMoveCallback(
2297                (AutoFocusMoveCallback) mAutoFocusMoveCallback);
2298        } else {
2299            mCameraDevice.setAutoFocusMoveCallback(null);
2300        }
2301    }
2302
2303    // We separate the parameters into several subsets, so we can update only
2304    // the subsets actually need updating. The PREFERENCE set needs extra
2305    // locking because the preference can be changed from GLThread as well.
2306    private void setCameraParameters(int updateSet) {
2307        if ((updateSet & UPDATE_PARAM_INITIALIZE) != 0) {
2308            updateCameraParametersInitialize();
2309        }
2310
2311        if ((updateSet & UPDATE_PARAM_ZOOM) != 0) {
2312            updateCameraParametersZoom();
2313        }
2314
2315        if ((updateSet & UPDATE_PARAM_PREFERENCE) != 0) {
2316            updateCameraParametersPreference();
2317        }
2318
2319        mCameraDevice.setParameters(mParameters);
2320    }
2321
2322    // If the Camera is idle, update the parameters immediately, otherwise
2323    // accumulate them in mUpdateSet and update later.
2324    private void setCameraParametersWhenIdle(int additionalUpdateSet) {
2325        mUpdateSet |= additionalUpdateSet;
2326        if (mCameraDevice == null) {
2327            // We will update all the parameters when we open the device, so
2328            // we don't need to do anything now.
2329            mUpdateSet = 0;
2330            return;
2331        } else if (isCameraIdle()) {
2332            setCameraParameters(mUpdateSet);
2333            updateSceneModeUI();
2334            mUpdateSet = 0;
2335        } else {
2336            if (!mHandler.hasMessages(SET_CAMERA_PARAMETERS_WHEN_IDLE)) {
2337                mHandler.sendEmptyMessageDelayed(
2338                        SET_CAMERA_PARAMETERS_WHEN_IDLE, 1000);
2339            }
2340        }
2341    }
2342
2343    private boolean isCameraIdle() {
2344        return (mCameraState == IDLE) ||
2345                ((mFocusManager != null) && mFocusManager.isFocusCompleted()
2346                        && (mCameraState != SWITCHING_CAMERA));
2347    }
2348
2349    private boolean isImageCaptureIntent() {
2350        String action = mActivity.getIntent().getAction();
2351        return (MediaStore.ACTION_IMAGE_CAPTURE.equals(action)
2352                || ActivityBase.ACTION_IMAGE_CAPTURE_SECURE.equals(action));
2353    }
2354
2355    private void setupCaptureParams() {
2356        Bundle myExtras = mActivity.getIntent().getExtras();
2357        if (myExtras != null) {
2358            mSaveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT);
2359            mCropValue = myExtras.getString("crop");
2360        }
2361    }
2362
2363    private void showPostCaptureAlert() {
2364        if (mIsImageCaptureIntent) {
2365            mOnScreenIndicators.setVisibility(View.GONE);
2366            mMenu.setVisibility(View.GONE);
2367            Util.fadeIn((View) mReviewDoneButton);
2368            mShutterButton.setVisibility(View.INVISIBLE);
2369            Util.fadeIn(mReviewRetakeButton);
2370        }
2371    }
2372
2373    private void hidePostCaptureAlert() {
2374        if (mIsImageCaptureIntent) {
2375            mOnScreenIndicators.setVisibility(View.VISIBLE);
2376            mMenu.setVisibility(View.VISIBLE);
2377            Util.fadeOut((View) mReviewDoneButton);
2378            mShutterButton.setVisibility(View.VISIBLE);
2379            Util.fadeOut(mReviewRetakeButton);
2380        }
2381    }
2382
2383    @Override
2384    public void onSharedPreferenceChanged() {
2385        // ignore the events after "onPause()"
2386        if (mPaused) return;
2387
2388        boolean recordLocation = RecordLocationPreference.get(
2389                mPreferences, mContentResolver);
2390        mLocationManager.recordLocation(recordLocation);
2391
2392        setCameraParametersWhenIdle(UPDATE_PARAM_PREFERENCE);
2393        setPreviewFrameLayoutAspectRatio();
2394        updateOnScreenIndicators();
2395    }
2396
2397    @Override
2398    public void onCameraPickerClicked(int cameraId) {
2399        if (mPaused || mPendingSwitchCameraId != -1) return;
2400
2401        mPendingSwitchCameraId = cameraId;
2402        if (ApiHelper.HAS_SURFACE_TEXTURE) {
2403            Log.v(TAG, "Start to copy texture. cameraId=" + cameraId);
2404            // We need to keep a preview frame for the animation before
2405            // releasing the camera. This will trigger onPreviewTextureCopied.
2406            ((CameraScreenNail) mActivity.mCameraScreenNail).copyTexture();
2407            // Disable all camera controls.
2408            setCameraState(SWITCHING_CAMERA);
2409        } else {
2410            switchCamera();
2411        }
2412    }
2413
2414    private void switchCamera() {
2415        if (mPaused) return;
2416
2417        Log.v(TAG, "Start to switch camera. id=" + mPendingSwitchCameraId);
2418        mCameraId = mPendingSwitchCameraId;
2419        mPendingSwitchCameraId = -1;
2420        mPhotoControl.setCameraId(mCameraId);
2421
2422        // from onPause
2423        closeCamera();
2424        collapseCameraControls();
2425        if (mFaceView != null) mFaceView.clear();
2426        if (mFocusManager != null) mFocusManager.removeMessages();
2427
2428        // Restart the camera and initialize the UI. From onCreate.
2429        mPreferences.setLocalId(mActivity, mCameraId);
2430        CameraSettings.upgradeLocalPreferences(mPreferences.getLocal());
2431        try {
2432            mCameraDevice = Util.openCamera(mActivity, mCameraId);
2433            mParameters = mCameraDevice.getParameters();
2434        } catch (CameraHardwareException e) {
2435            Util.showErrorAndFinish(mActivity, R.string.cannot_connect_camera);
2436            return;
2437        } catch (CameraDisabledException e) {
2438            Util.showErrorAndFinish(mActivity, R.string.camera_disabled);
2439            return;
2440        }
2441        initializeCapabilities();
2442        CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId];
2443        boolean mirror = (info.facing == CameraInfo.CAMERA_FACING_FRONT);
2444        mFocusManager.setMirror(mirror);
2445        mFocusManager.setParameters(mInitialParams);
2446        setupPreview();
2447        loadCameraPreferences();
2448        initializePhotoControl();
2449
2450        // from initializeFirstTime
2451        initializeZoom();
2452        updateOnScreenIndicators();
2453        showTapToFocusToastIfNeeded();
2454
2455        if (ApiHelper.HAS_SURFACE_TEXTURE) {
2456            // Start switch camera animation. Post a message because
2457            // onFrameAvailable from the old camera may already exist.
2458            mHandler.sendEmptyMessage(SWITCH_CAMERA_START_ANIMATION);
2459        }
2460    }
2461
2462    @Override
2463    public void onPieOpened(int centerX, int centerY) {
2464        mActivity.cancelActivityTouchHandling();
2465        mActivity.setSwipingEnabled(false);
2466        if (mFaceView != null) {
2467            mFaceView.setBlockDraw(true);
2468        }
2469    }
2470
2471    @Override
2472    public void onPieClosed() {
2473        mActivity.setSwipingEnabled(true);
2474        if (mFaceView != null) {
2475            mFaceView.setBlockDraw(false);
2476        }
2477    }
2478
2479    // Preview texture has been copied. Now camera can be released and the
2480    // animation can be started.
2481    @Override
2482    public void onPreviewTextureCopied() {
2483        mHandler.sendEmptyMessage(SWITCH_CAMERA);
2484    }
2485
2486    @Override
2487    public void onCaptureTextureCopied() {
2488    }
2489
2490    @Override
2491    public void onUserInteraction() {
2492        if (!mActivity.isFinishing()) keepScreenOnAwhile();
2493    }
2494
2495    private void resetScreenOn() {
2496        mHandler.removeMessages(CLEAR_SCREEN_DELAY);
2497        mActivity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
2498    }
2499
2500    private void keepScreenOnAwhile() {
2501        mHandler.removeMessages(CLEAR_SCREEN_DELAY);
2502        mActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
2503        mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY);
2504    }
2505
2506    // TODO: Delete this function after old camera code is removed
2507    @Override
2508    public void onRestorePreferencesClicked() {
2509    }
2510
2511    @Override
2512    public void onOverriddenPreferencesClicked() {
2513        if (mPaused) return;
2514        if (mNotSelectableToast == null) {
2515            String str = mActivity.getResources().getString(R.string.not_selectable_in_scene_mode);
2516            mNotSelectableToast = Toast.makeText(mActivity, str, Toast.LENGTH_SHORT);
2517        }
2518        mNotSelectableToast.show();
2519    }
2520
2521    private void showTapToFocusToast() {
2522        new RotateTextToast(mActivity, R.string.tap_to_focus, mOrientationCompensation).show();
2523        // Clear the preference.
2524        Editor editor = mPreferences.edit();
2525        editor.putBoolean(CameraSettings.KEY_CAMERA_FIRST_USE_HINT_SHOWN, false);
2526        editor.apply();
2527    }
2528
2529    private void initializeCapabilities() {
2530        mInitialParams = mCameraDevice.getParameters();
2531        mFocusAreaSupported = Util.isFocusAreaSupported(mInitialParams);
2532        mMeteringAreaSupported = Util.isMeteringAreaSupported(mInitialParams);
2533        mAeLockSupported = Util.isAutoExposureLockSupported(mInitialParams);
2534        mAwbLockSupported = Util.isAutoWhiteBalanceLockSupported(mInitialParams);
2535        mContinousFocusSupported = mInitialParams.getSupportedFocusModes().contains(
2536                Util.FOCUS_MODE_CONTINUOUS_PICTURE);
2537    }
2538
2539    // PreviewFrameLayout size has changed.
2540    @Override
2541    public void onSizeChanged(int width, int height) {
2542        if (mFocusManager != null) mFocusManager.setPreviewSize(width, height);
2543    }
2544
2545    void setPreviewFrameLayoutAspectRatio() {
2546        // Set the preview frame aspect ratio according to the picture size.
2547        Size size = mParameters.getPictureSize();
2548        mPreviewFrameLayout.setAspectRatio((double) size.width / size.height);
2549    }
2550
2551    @Override
2552    public boolean needsSwitcher() {
2553        return !mIsImageCaptureIntent;
2554    }
2555
2556    public void showPopup(AbstractSettingPopup popup) {
2557        mActivity.hideUI();
2558        mBlocker.setVisibility(View.INVISIBLE);
2559        setShowMenu(false);
2560        mPopup = popup;
2561        // Make sure popup is brought up with the right orientation
2562        mPopup.setOrientation(mOrientationCompensation, false);
2563        mPopup.setVisibility(View.VISIBLE);
2564        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
2565                LayoutParams.WRAP_CONTENT);
2566        lp.gravity = Gravity.CENTER;
2567        ((FrameLayout) mRootView).addView(mPopup, lp);
2568    }
2569
2570    public void dismissPopup(boolean topPopupOnly) {
2571        dismissPopup(topPopupOnly, true);
2572    }
2573
2574    private void dismissPopup(boolean topOnly, boolean fullScreen) {
2575        if (fullScreen) {
2576            mActivity.showUI();
2577            mBlocker.setVisibility(View.VISIBLE);
2578        }
2579        setShowMenu(fullScreen);
2580        if (mPopup != null) {
2581            ((FrameLayout) mRootView).removeView(mPopup);
2582            mPopup = null;
2583        }
2584        mPhotoControl.popupDismissed(topOnly);
2585    }
2586
2587    @Override
2588    public void onShowSwitcherPopup() {
2589        if (mPieRenderer != null && mPieRenderer.showsItems()) {
2590            mPieRenderer.hide();
2591        }
2592    }
2593
2594}
2595