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