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