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