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