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