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