Camera.java revision 9926791171e0ba550be21b4498043fbd15acbf35
1/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.camera;
18
19import android.app.Activity;
20import android.content.ActivityNotFoundException;
21import android.content.BroadcastReceiver;
22import android.content.ContentResolver;
23import android.content.Context;
24import android.content.Intent;
25import android.content.IntentFilter;
26import android.content.SharedPreferences;
27import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
28import android.content.res.Resources;
29import android.graphics.Bitmap;
30import android.graphics.BitmapFactory;
31import android.hardware.Camera.Parameters;
32import android.hardware.Camera.PictureCallback;
33import android.hardware.Camera.Size;
34import android.location.Location;
35import android.location.LocationManager;
36import android.location.LocationProvider;
37import android.media.AudioManager;
38import android.media.ToneGenerator;
39import android.net.Uri;
40import android.os.Build;
41import android.os.Bundle;
42import android.os.Debug;
43import android.os.Environment;
44import android.os.Handler;
45import android.os.Message;
46import android.os.SystemClock;
47import android.preference.PreferenceManager;
48import android.provider.MediaStore;
49import android.text.format.DateFormat;
50import android.util.AttributeSet;
51import android.util.Log;
52import android.view.GestureDetector;
53import android.view.KeyEvent;
54import android.view.LayoutInflater;
55import android.view.Menu;
56import android.view.MenuItem;
57import android.view.MotionEvent;
58import android.view.OrientationEventListener;
59import android.view.SurfaceHolder;
60import android.view.View;
61import android.view.ViewGroup;
62import android.view.Window;
63import android.view.WindowManager;
64import android.view.MenuItem.OnMenuItemClickListener;
65import android.widget.ImageView;
66
67import com.android.camera.gallery.IImage;
68import com.android.camera.gallery.IImageList;
69
70import java.io.File;
71import java.io.FileNotFoundException;
72import java.io.FileOutputStream;
73import java.io.IOException;
74import java.io.OutputStream;
75import java.util.ArrayList;
76import java.util.Collections;
77import java.util.List;
78
79/**
80 * Activity of the Camera which used to see preview and take pictures.
81 */
82public class Camera extends Activity implements View.OnClickListener,
83        ShutterButton.OnShutterButtonListener, SurfaceHolder.Callback,
84        Switcher.OnSwitchListener, OnScreenSettings.OnVisibilityChangedListener,
85        OnSharedPreferenceChangeListener {
86
87    private static final String TAG = "camera";
88
89    private static final int CROP_MSG = 1;
90    private static final int FIRST_TIME_INIT = 2;
91    private static final int RESTART_PREVIEW = 3;
92    private static final int CLEAR_SCREEN_DELAY = 4;
93
94    private static final String GPS_MODE_ON = "on";
95    private static final String GPS_MODE_OFF = "off";
96
97    private static final int SCREEN_DELAY = 2 * 60 * 1000;
98    private static final int FOCUS_BEEP_VOLUME = 100;
99
100    private Parameters mParameters;
101
102    private OrientationEventListener mOrientationListener;
103    private int mLastOrientation = OrientationEventListener.ORIENTATION_UNKNOWN;
104    private SharedPreferences mPreferences;
105
106    private static final int IDLE = 1;
107    private static final int SNAPSHOT_IN_PROGRESS = 2;
108
109    private static final boolean SWITCH_CAMERA = true;
110    private static final boolean SWITCH_VIDEO = false;
111
112    private int mStatus = IDLE;
113    private static final String sTempCropFilename = "crop-temp";
114
115    private android.hardware.Camera mCameraDevice;
116    private VideoPreview mSurfaceView;
117    private SurfaceHolder mSurfaceHolder = null;
118    private ShutterButton mShutterButton;
119    private FocusRectangle mFocusRectangle;
120    private IconIndicator mGpsIndicator;
121    private IconIndicator mFlashIndicator;
122    private ToneGenerator mFocusToneGenerator;
123    private GestureDetector mGestureDetector;
124    private Switcher mSwitcher;
125    private boolean mStartPreviewFail = false;
126
127    // mPostCaptureAlert, mLastPictureButton, mThumbController
128    // are non-null only if isImageCaptureIntent() is true.
129    private ImageView mLastPictureButton;
130    private ThumbnailController mThumbController;
131
132    // mCropValue and mSaveUri are used only if isImageCaptureIntent() is true.
133    private String mCropValue;
134    private Uri mSaveUri;
135
136    private int mViewFinderHeight;
137
138    private ImageCapture mImageCapture = null;
139
140    private boolean mPreviewing;
141    private boolean mPausing;
142    private boolean mFirstTimeInitialized;
143    private boolean mIsImageCaptureIntent;
144    private boolean mRecordLocation;
145
146    private static final int FOCUS_NOT_STARTED = 0;
147    private static final int FOCUSING = 1;
148    private static final int FOCUSING_SNAP_ON_FINISH = 2;
149    private static final int FOCUS_SUCCESS = 3;
150    private static final int FOCUS_FAIL = 4;
151    private int mFocusState = FOCUS_NOT_STARTED;
152
153    private ContentResolver mContentResolver;
154    private boolean mDidRegister = false;
155
156    private final ArrayList<MenuItem> mGalleryItems = new ArrayList<MenuItem>();
157
158    private LocationManager mLocationManager = null;
159
160    // Use OneShotPreviewCallback to measure the time between
161    // JpegPictureCallback and preview.
162    private final OneShotPreviewCallback mOneShotPreviewCallback =
163            new OneShotPreviewCallback();
164    private final ShutterCallback mShutterCallback = new ShutterCallback();
165    private final RawPictureCallback mRawPictureCallback =
166            new RawPictureCallback();
167    private final AutoFocusCallback mAutoFocusCallback =
168            new AutoFocusCallback();
169    // Use the ErrorCallback to capture the crash count
170    // on the mediaserver
171    private final ErrorCallback mErrorCallback = new ErrorCallback();
172
173    private long mFocusStartTime;
174    private long mFocusCallbackTime;
175    private long mCaptureStartTime;
176    private long mShutterCallbackTime;
177    private long mRawPictureCallbackTime;
178    private long mJpegPictureCallbackTime;
179    private int mPicturesRemaining;
180
181    // These latency time are for the CameraLatency test.
182    public long mAutoFocusTime;
183    public long mShutterLag;
184    public long mShutterAndRawPictureCallbackTime;
185    public long mJpegPictureCallbackTimeLag;
186    public long mRawPictureAndJpegPictureCallbackTime;
187
188    // Add the media server tag
189    public static boolean mMediaServerDied = false;
190    // Focus mode. Options are pref_camera_focusmode_entryvalues.
191    private String mFocusMode;
192
193    private final Handler mHandler = new MainHandler();
194    private OnScreenSettings mSettings;
195
196    /**
197     * This Handler is used to post message back onto the main thread of the
198     * application
199     */
200    private class MainHandler extends Handler {
201        @Override
202        public void handleMessage(Message msg) {
203            switch (msg.what) {
204                case RESTART_PREVIEW: {
205                    restartPreview();
206                    break;
207                }
208
209                case CLEAR_SCREEN_DELAY: {
210                    getWindow().clearFlags(
211                            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
212                    break;
213                }
214
215                case FIRST_TIME_INIT: {
216                    initializeFirstTime();
217                    break;
218                }
219            }
220        }
221    }
222
223    // Snapshots can only be taken after this is called. It should be called
224    // once only. We could have done these things in onCreate() but we want to
225    // make preview screen appear as soon as possible.
226    private void initializeFirstTime() {
227        if (mFirstTimeInitialized) return;
228
229        // Create orientation listenter. This should be done first because it
230        // takes some time to get first orientation.
231        mOrientationListener =
232                new OrientationEventListener(Camera.this) {
233            @Override
234            public void onOrientationChanged(int orientation) {
235                // We keep the last known orientation. So if the user
236                // first orient the camera then point the camera to
237                // floor/sky, we still have the correct orientation.
238                if (orientation != ORIENTATION_UNKNOWN) {
239                    mLastOrientation = orientation;
240                }
241            }
242        };
243        mOrientationListener.enable();
244
245        // Initialize location sevice.
246        mLocationManager = (LocationManager)
247                getSystemService(Context.LOCATION_SERVICE);
248        readPreference();
249        if (mRecordLocation) startReceivingLocationUpdates();
250
251        checkStorage();
252
253        // Initialize last picture button.
254        mContentResolver = getContentResolver();
255        if (!mIsImageCaptureIntent)  {
256            findViewById(R.id.camera_switch).setOnClickListener(this);
257            mLastPictureButton =
258                    (ImageView) findViewById(R.id.review_thumbnail);
259            mLastPictureButton.setOnClickListener(this);
260            mThumbController = new ThumbnailController(
261                    getResources(), mLastPictureButton, mContentResolver);
262            mThumbController.loadData(ImageManager.getLastImageThumbPath());
263            // Update last image thumbnail.
264            updateThumbnailButton();
265        }
266
267        // Initialize shutter button.
268        mShutterButton = (ShutterButton) findViewById(R.id.shutter_button);
269        mShutterButton.setOnShutterButtonListener(this);
270        mShutterButton.setVisibility(View.VISIBLE);
271
272        mFocusRectangle = (FocusRectangle) findViewById(R.id.focus_rectangle);
273        updateFocusIndicator();
274
275        // Initialize GPS indicator.
276        mGpsIndicator = (IconIndicator) findViewById(R.id.gps_icon);
277
278        ImageManager.ensureOSXCompatibleFolder();
279
280        installIntentFilter();
281
282        initializeFocusTone();
283
284        mFirstTimeInitialized = true;
285    }
286
287    private void updateThumbnailButton() {
288        // Update last image if URI is invalid and the storage is ready.
289        if (!mThumbController.isUriValid() && mPicturesRemaining >= 0) {
290            updateLastImage();
291        }
292        mThumbController.updateDisplayIfNeeded();
293    }
294
295    // If the activity is paused and resumed, this method will be called in
296    // onResume.
297    private void initializeSecondTime() {
298        // Start orientation listener as soon as possible because it takes
299        // some time to get first orientation.
300        mOrientationListener.enable();
301
302        // Start location update if needed.
303        readPreference();
304        if (mRecordLocation) startReceivingLocationUpdates();
305
306        installIntentFilter();
307
308        initializeFocusTone();
309
310        checkStorage();
311
312        if (!mIsImageCaptureIntent) {
313            updateThumbnailButton();
314        }
315    }
316
317    public void onVisibilityChanged(boolean visible) {
318        // When the on-screen setting is not displayed, we show the gripper.
319        // When the on-screen setting is displayed, we hide the gripper.
320        findViewById(R.id.btn_gripper).setVisibility(
321                visible ? View.INVISIBLE : View.VISIBLE);
322        if (visible) {
323            mPreferences.registerOnSharedPreferenceChangeListener(this);
324        } else {
325            mPreferences.unregisterOnSharedPreferenceChangeListener(this);
326        }
327    }
328
329    @Override
330    public boolean dispatchTouchEvent(MotionEvent m) {
331        if (!super.dispatchTouchEvent(m) && mGestureDetector != null) {
332            return mGestureDetector.onTouchEvent(m);
333        }
334        return true;
335    }
336
337    LocationListener [] mLocationListeners = new LocationListener[] {
338            new LocationListener(LocationManager.GPS_PROVIDER),
339            new LocationListener(LocationManager.NETWORK_PROVIDER)
340    };
341
342    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
343        @Override
344        public void onReceive(Context context, Intent intent) {
345            String action = intent.getAction();
346            if (action.equals(Intent.ACTION_MEDIA_MOUNTED)
347                    || action.equals(Intent.ACTION_MEDIA_UNMOUNTED)
348                    || action.equals(Intent.ACTION_MEDIA_CHECKING)
349                    || action.equals(Intent.ACTION_MEDIA_SCANNER_STARTED)) {
350                checkStorage();
351            } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)) {
352                checkStorage();
353                if (!mIsImageCaptureIntent)  {
354                    updateThumbnailButton();
355                }
356            }
357        }
358    };
359
360    private class LocationListener
361            implements android.location.LocationListener {
362        Location mLastLocation;
363        boolean mValid = false;
364        String mProvider;
365
366        public LocationListener(String provider) {
367            mProvider = provider;
368            mLastLocation = new Location(mProvider);
369        }
370
371        public void onLocationChanged(Location newLocation) {
372            if (newLocation.getLatitude() == 0.0
373                    && newLocation.getLongitude() == 0.0) {
374                // Hack to filter out 0.0,0.0 locations
375                return;
376            }
377            // If GPS is available before start camera, we won't get status
378            // update so update GPS indicator when we receive data.
379            if (mRecordLocation
380                    && LocationManager.GPS_PROVIDER.equals(mProvider)) {
381                mGpsIndicator.setMode(GPS_MODE_ON);
382            }
383            mLastLocation.set(newLocation);
384            mValid = true;
385        }
386
387        public void onProviderEnabled(String provider) {
388        }
389
390        public void onProviderDisabled(String provider) {
391            mValid = false;
392        }
393
394        public void onStatusChanged(
395                String provider, int status, Bundle extras) {
396            switch(status) {
397                case LocationProvider.OUT_OF_SERVICE:
398                case LocationProvider.TEMPORARILY_UNAVAILABLE: {
399                    mValid = false;
400                    if (mRecordLocation &&
401                            LocationManager.GPS_PROVIDER.equals(provider)) {
402                        mGpsIndicator.setMode(GPS_MODE_OFF);
403                    }
404                    break;
405                }
406            }
407        }
408
409        public Location current() {
410            return mValid ? mLastLocation : null;
411        }
412    }
413
414    private final class OneShotPreviewCallback
415            implements android.hardware.Camera.PreviewCallback {
416        public void onPreviewFrame(byte[] data,
417                                   android.hardware.Camera camera) {
418            long now = System.currentTimeMillis();
419            if (mJpegPictureCallbackTime != 0) {
420                mJpegPictureCallbackTimeLag = now - mJpegPictureCallbackTime;
421                Log.v(TAG, "mJpegPictureCallbackTimeLag = "
422                        + mJpegPictureCallbackTimeLag + "ms");
423                mJpegPictureCallbackTime = 0;
424            } else {
425                Log.v(TAG, "Got first frame");
426            }
427        }
428    }
429
430    private final class ShutterCallback
431            implements android.hardware.Camera.ShutterCallback {
432        public void onShutter() {
433            mShutterCallbackTime = System.currentTimeMillis();
434            mShutterLag = mShutterCallbackTime - mCaptureStartTime;
435            Log.v(TAG, "mShutterLag = " + mShutterLag + "ms");
436            clearFocusState();
437        }
438    }
439
440    private final class RawPictureCallback implements PictureCallback {
441        public void onPictureTaken(
442                byte [] rawData, android.hardware.Camera camera) {
443            mRawPictureCallbackTime = System.currentTimeMillis();
444            mShutterAndRawPictureCallbackTime =
445                mRawPictureCallbackTime - mShutterCallbackTime;
446            Log.v(TAG, "mShutterAndRawPictureCallbackTime = "
447                    + mShutterAndRawPictureCallbackTime + "ms");
448        }
449    }
450
451    private final class JpegPictureCallback implements PictureCallback {
452        Location mLocation;
453
454        public JpegPictureCallback(Location loc) {
455            mLocation = loc;
456        }
457
458        public void onPictureTaken(
459                final byte [] jpegData, final android.hardware.Camera camera) {
460            if (mPausing) {
461                return;
462            }
463
464            mJpegPictureCallbackTime = System.currentTimeMillis();
465            mRawPictureAndJpegPictureCallbackTime =
466                mJpegPictureCallbackTime - mRawPictureCallbackTime;
467            Log.v(TAG, "mRawPictureAndJpegPictureCallbackTime = "
468                    + mRawPictureAndJpegPictureCallbackTime + "ms");
469            mImageCapture.storeImage(jpegData, camera, mLocation);
470
471            if (!mIsImageCaptureIntent) {
472                long delay = 1200 - (
473                        System.currentTimeMillis() - mRawPictureCallbackTime);
474                mHandler.sendEmptyMessageDelayed(
475                        RESTART_PREVIEW, Math.max(delay, 0));
476            }
477        }
478    }
479
480    private final class AutoFocusCallback
481            implements android.hardware.Camera.AutoFocusCallback {
482        public void onAutoFocus(
483                boolean focused, android.hardware.Camera camera) {
484            mFocusCallbackTime = System.currentTimeMillis();
485            mAutoFocusTime = mFocusCallbackTime - mFocusStartTime;
486            Log.v(TAG, "mAutoFocusTime = " + mAutoFocusTime + "ms");
487            if (mFocusState == FOCUSING_SNAP_ON_FINISH) {
488                // Take the picture no matter focus succeeds or fails. No need
489                // to play the AF sound if we're about to play the shutter
490                // sound.
491                if (focused) {
492                    mFocusState = FOCUS_SUCCESS;
493                } else {
494                    mFocusState = FOCUS_FAIL;
495                }
496                mImageCapture.onSnap();
497            } else if (mFocusState == FOCUSING) {
498                // User is half-pressing the focus key. Play the focus tone.
499                // Do not take the picture now.
500                ToneGenerator tg = mFocusToneGenerator;
501                if (tg != null) {
502                    tg.startTone(ToneGenerator.TONE_PROP_BEEP2);
503                }
504                if (focused) {
505                    mFocusState = FOCUS_SUCCESS;
506                } else {
507                    mFocusState = FOCUS_FAIL;
508                }
509            } else if (mFocusState == FOCUS_NOT_STARTED) {
510                // User has released the focus key before focus completes.
511                // Do nothing.
512            }
513            updateFocusIndicator();
514        }
515    }
516
517    private final class ErrorCallback
518        implements android.hardware.Camera.ErrorCallback {
519        public void onError(int error, android.hardware.Camera camera) {
520            if (error == android.hardware.Camera.CAMERA_ERROR_SERVER_DIED) {
521                 mMediaServerDied = true;
522                 Log.v(TAG, "media server died");
523            }
524        }
525    }
526
527    private class ImageCapture {
528
529        private boolean mCancel = false;
530
531        private Uri mLastContentUri;
532
533        byte[] mCaptureOnlyData;
534
535        // Returns the rotation degree in the jpeg header.
536        private int storeImage(byte[] data, Location loc) {
537            try {
538                long dateTaken = System.currentTimeMillis();
539                String name = createName(dateTaken) + ".jpg";
540                mLastContentUri = ImageManager.addImage(
541                        mContentResolver,
542                        name,
543                        dateTaken,
544                        loc, // location for the database goes here
545                        0, // the dsp will use the right orientation so
546                           // don't "double set it"
547                        ImageManager.CAMERA_IMAGE_BUCKET_NAME,
548                        name);
549                if (mLastContentUri == null) {
550                    // this means we got an error
551                    mCancel = true;
552                }
553                int degree = 0;
554                if (!mCancel) {
555                    degree = ImageManager.storeImage(mLastContentUri, mContentResolver,
556                            null, data);
557                    ImageManager.setImageSize(mContentResolver, mLastContentUri,
558                            new File(ImageManager.CAMERA_IMAGE_BUCKET_NAME,
559                            name).length());
560                }
561                return degree;
562            } catch (Exception ex) {
563                Log.e(TAG, "Exception while compressing image.", ex);
564                return 0;
565            }
566        }
567
568        public void storeImage(final byte[] data,
569                android.hardware.Camera camera, Location loc) {
570            if (!mIsImageCaptureIntent) {
571                int degree = storeImage(data, loc);
572                sendBroadcast(new Intent(
573                        "com.android.camera.NEW_PICTURE", mLastContentUri));
574                setLastPictureThumb(data, degree,
575                        mImageCapture.getLastCaptureUri());
576                mThumbController.updateDisplayIfNeeded();
577            } else {
578                mCaptureOnlyData = data;
579                showPostCaptureAlert();
580            }
581        }
582
583        /**
584         * Initiate the capture of an image.
585         */
586        public void initiate() {
587            if (mCameraDevice == null) {
588                return;
589            }
590
591            mCancel = false;
592
593            capture();
594        }
595
596        public Uri getLastCaptureUri() {
597            return mLastContentUri;
598        }
599
600        public byte[] getLastCaptureData() {
601            return mCaptureOnlyData;
602        }
603
604        private void capture() {
605            mCaptureOnlyData = null;
606
607            // Set rotation.
608            int orientation = mLastOrientation;
609            if (orientation != OrientationEventListener.ORIENTATION_UNKNOWN) {
610                orientation += 90;
611            }
612            orientation = ImageManager.roundOrientation(orientation);
613            Log.v(TAG, "mLastOrientation = " + mLastOrientation
614                    + ", orientation = " + orientation);
615            mParameters.setRotation(orientation);
616
617            // Clear previous GPS location from the parameters.
618            mParameters.removeGpsData();
619
620            // Set GPS location.
621            Location loc = mRecordLocation ? getCurrentLocation() : null;
622            if (loc != null) {
623                double lat = loc.getLatitude();
624                double lon = loc.getLongitude();
625                boolean hasLatLon = (lat != 0.0d) || (lon != 0.0d);
626
627                if (hasLatLon) {
628                    mParameters.setGpsLatitude(lat);
629                    mParameters.setGpsLongitude(lon);
630                    if (loc.hasAltitude()) {
631                        mParameters.setGpsAltitude(loc.getAltitude());
632                    } else {
633                        // for NETWORK_PROVIDER location provider, we may have
634                        // no altitude information, but the driver needs it, so
635                        // we fake one.
636                        mParameters.setGpsAltitude(0);
637                    }
638                    if (loc.getTime() != 0) {
639                        // Location.getTime() is UTC in milliseconds.
640                        // gps-timestamp is UTC in seconds.
641                        long utcTimeSeconds = loc.getTime() / 1000;
642                        mParameters.setGpsTimestamp(utcTimeSeconds);
643                    }
644                } else {
645                    loc = null;
646                }
647            }
648
649            mCameraDevice.setParameters(mParameters);
650
651            mCameraDevice.takePicture(mShutterCallback, mRawPictureCallback,
652                    new JpegPictureCallback(loc));
653            mPreviewing = false;
654        }
655
656        public void onSnap() {
657            // If we are already in the middle of taking a snapshot then ignore.
658            if (mPausing || mStatus == SNAPSHOT_IN_PROGRESS) {
659                return;
660            }
661            mCaptureStartTime = System.currentTimeMillis();
662
663            // Don't check the filesystem here, we can't afford the latency.
664            // Instead, check the cached value which was calculated when the
665            // preview was restarted.
666            if (mPicturesRemaining < 1) {
667                updateStorageHint(mPicturesRemaining);
668                return;
669            }
670
671            mStatus = SNAPSHOT_IN_PROGRESS;
672
673            mImageCapture.initiate();
674        }
675
676        private void clearLastData() {
677            mCaptureOnlyData = null;
678        }
679    }
680
681    public boolean saveDataToFile(String filePath, byte[] data) {
682        FileOutputStream f = null;
683        try {
684            f = new FileOutputStream(filePath);
685            f.write(data);
686        } catch (IOException e) {
687            return false;
688        } finally {
689            MenuHelper.closeSilently(f);
690        }
691        return true;
692    }
693
694    private void setLastPictureThumb(byte[] data, int degree, Uri uri) {
695        BitmapFactory.Options options = new BitmapFactory.Options();
696        options.inSampleSize = 16;
697        Bitmap lastPictureThumb =
698                BitmapFactory.decodeByteArray(data, 0, data.length, options);
699        lastPictureThumb = Util.rotate(lastPictureThumb, degree);
700        mThumbController.setData(uri, lastPictureThumb);
701    }
702
703    private static String createName(long dateTaken) {
704        return DateFormat.format("yyyy-MM-dd kk.mm.ss", dateTaken).toString();
705    }
706
707    @Override
708    public void onCreate(Bundle icicle) {
709        super.onCreate(icicle);
710
711        Window win = getWindow();
712        win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
713        setContentView(R.layout.camera);
714        mSurfaceView = (VideoPreview) findViewById(R.id.camera_preview);
715        mViewFinderHeight = mSurfaceView.getLayoutParams().height;
716        mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
717
718        /*
719         * To reduce startup time, we start the preview in another thread.
720         * We make sure the preview is started at the end of onCreate.
721         */
722        Thread startPreviewThread = new Thread(new Runnable() {
723            public void run() {
724                try {
725                    mStartPreviewFail = false;
726                    startPreview();
727                } catch (CameraHardwareException e) {
728                    // In eng build, we throw the exception so that test tool
729                    // can detect it and report it
730                    if ("eng".equals(Build.TYPE)) {
731                        throw new RuntimeException(e);
732                    }
733                    mStartPreviewFail = true;
734                }
735            }
736        });
737        startPreviewThread.start();
738
739        // don't set mSurfaceHolder here. We have it set ONLY within
740        // surfaceChanged / surfaceDestroyed, other parts of the code
741        // assume that when it is set, the surface is also set.
742        SurfaceHolder holder = mSurfaceView.getHolder();
743        holder.addCallback(this);
744        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
745
746        mIsImageCaptureIntent = isImageCaptureIntent();
747        if (mIsImageCaptureIntent) {
748            setupCaptureParams();
749        }
750
751        LayoutInflater inflater = getLayoutInflater();
752
753        ViewGroup rootView = (ViewGroup) findViewById(R.id.camera);
754        if (mIsImageCaptureIntent) {
755            View controlBar = inflater.inflate(
756                    R.layout.attach_camera_control, rootView);
757            controlBar.findViewById(R.id.btn_cancel).setOnClickListener(this);
758            controlBar.findViewById(R.id.btn_retake).setOnClickListener(this);
759            controlBar.findViewById(R.id.btn_done).setOnClickListener(this);
760        } else {
761            inflater.inflate(R.layout.camera_control, rootView);
762            mSwitcher = ((Switcher) findViewById(R.id.camera_switch));
763            mSwitcher.setOnSwitchListener(this);
764            mSwitcher.addTouchView(findViewById(R.id.camera_switch_set));
765        }
766        findViewById(R.id.btn_gripper)
767                .setOnTouchListener(new GripperTouchListener());
768
769        mFlashIndicator = (IconIndicator) findViewById(R.id.flash_icon);
770
771        // Make sure preview is started.
772        try {
773            startPreviewThread.join();
774            if (mStartPreviewFail) {
775                showCameraErrorAndFinish();
776                return;
777            }
778        } catch (InterruptedException ex) {
779            // ignore
780        }
781
782        // Resize mVideoPreview to the right aspect ratio.
783        resizeForPreviewAspectRatio(mSurfaceView);
784    }
785
786    private class GripperTouchListener implements View.OnTouchListener {
787        public boolean onTouch(View view, MotionEvent event) {
788            switch (event.getAction()) {
789                case MotionEvent.ACTION_DOWN:
790                    return true;
791                case MotionEvent.ACTION_UP:
792                    showOnScreenSettings();
793                    return true;
794            }
795            return false;
796        }
797    }
798
799    @Override
800    public void onStart() {
801        super.onStart();
802        if (!mIsImageCaptureIntent) {
803            mSwitcher.setSwitch(SWITCH_CAMERA);
804        }
805    }
806
807    private void checkStorage() {
808        if (ImageManager.isMediaScannerScanning(getContentResolver())) {
809            mPicturesRemaining = MenuHelper.NO_STORAGE_ERROR;
810        } else {
811            calculatePicturesRemaining();
812        }
813        updateStorageHint(mPicturesRemaining);
814    }
815
816    private void showOnScreenSettings() {
817        if (mSettings == null) {
818            mSettings = new OnScreenSettings(
819                    findViewById(R.id.camera_preview));
820            CameraSettings helper = new CameraSettings(this, mParameters);
821            mSettings.setPreferenceScreen(helper
822                    .getPreferenceScreen(R.xml.camera_preferences));
823            mSettings.setOnVisibilityChangedListener(this);
824        }
825        mSettings.expandPanel();
826    }
827
828    public void onClick(View v) {
829        switch (v.getId()) {
830            case R.id.btn_retake:
831                hidePostCaptureAlert();
832                restartPreview();
833                break;
834            case R.id.review_thumbnail:
835                if (isCameraIdle()) {
836                    viewLastImage();
837                }
838                break;
839            case R.id.btn_done:
840                doAttach();
841                break;
842            case R.id.btn_cancel:
843                doCancel();
844        }
845    }
846
847    private Bitmap createCaptureBitmap(byte[] data) {
848        // This is really stupid...we just want to read the orientation in
849        // the jpeg header.
850        String filepath = ImageManager.getTempJpegPath();
851        int degree = 0;
852        if (saveDataToFile(filepath, data)) {
853            degree = ImageManager.getExifOrientation(filepath);
854            new File(filepath).delete();
855        }
856
857        // Limit to 50k pixels so we can return it in the intent.
858        Bitmap bitmap = Util.makeBitmap(data, 50*1024);
859        bitmap = Util.rotate(bitmap, degree);
860        return bitmap;
861    }
862
863    private void doAttach() {
864        if (mPausing) {
865            return;
866        }
867
868        byte[] data = mImageCapture.getLastCaptureData();
869
870        if (mCropValue == null) {
871            // First handle the no crop case -- just return the value.  If the
872            // caller specifies a "save uri" then write the data to it's
873            // stream. Otherwise, pass back a scaled down version of the bitmap
874            // directly in the extras.
875            if (mSaveUri != null) {
876                OutputStream outputStream = null;
877                try {
878                    outputStream = mContentResolver.openOutputStream(mSaveUri);
879                    outputStream.write(data);
880                    outputStream.close();
881
882                    setResult(RESULT_OK);
883                    finish();
884                } catch (IOException ex) {
885                    // ignore exception
886                } finally {
887                    Util.closeSilently(outputStream);
888                }
889            } else {
890                Bitmap bitmap = createCaptureBitmap(data);
891                setResult(RESULT_OK,
892                        new Intent("inline-data").putExtra("data", bitmap));
893                finish();
894            }
895        } else {
896            // Save the image to a temp file and invoke the cropper
897            Uri tempUri = null;
898            FileOutputStream tempStream = null;
899            try {
900                File path = getFileStreamPath(sTempCropFilename);
901                path.delete();
902                tempStream = openFileOutput(sTempCropFilename, 0);
903                tempStream.write(data);
904                tempStream.close();
905                tempUri = Uri.fromFile(path);
906            } catch (FileNotFoundException ex) {
907                setResult(Activity.RESULT_CANCELED);
908                finish();
909                return;
910            } catch (IOException ex) {
911                setResult(Activity.RESULT_CANCELED);
912                finish();
913                return;
914            } finally {
915                Util.closeSilently(tempStream);
916            }
917
918            Bundle newExtras = new Bundle();
919            if (mCropValue.equals("circle")) {
920                newExtras.putString("circleCrop", "true");
921            }
922            if (mSaveUri != null) {
923                newExtras.putParcelable(MediaStore.EXTRA_OUTPUT, mSaveUri);
924            } else {
925                newExtras.putBoolean("return-data", true);
926            }
927
928            Intent cropIntent = new Intent();
929            cropIntent.setClass(this, CropImage.class);
930            cropIntent.setData(tempUri);
931            cropIntent.putExtras(newExtras);
932
933            startActivityForResult(cropIntent, CROP_MSG);
934        }
935    }
936
937    private void doCancel() {
938        setResult(RESULT_CANCELED, new Intent());
939        finish();
940    }
941
942    public void onShutterButtonFocus(ShutterButton button, boolean pressed) {
943        if (mPausing) {
944            return;
945        }
946        switch (button.getId()) {
947            case R.id.shutter_button:
948                doFocus(pressed);
949                break;
950        }
951    }
952
953    public void onShutterButtonClick(ShutterButton button) {
954        if (mPausing) {
955            return;
956        }
957        switch (button.getId()) {
958            case R.id.shutter_button:
959                doSnap();
960                break;
961        }
962    }
963
964    private OnScreenHint mStorageHint;
965
966    private void updateStorageHint(int remaining) {
967        String noStorageText = null;
968
969        if (remaining == MenuHelper.NO_STORAGE_ERROR) {
970            String state = Environment.getExternalStorageState();
971            if (state == Environment.MEDIA_CHECKING ||
972                    ImageManager.isMediaScannerScanning(getContentResolver())) {
973                noStorageText = getString(R.string.preparing_sd);
974            } else {
975                noStorageText = getString(R.string.no_storage);
976            }
977        } else if (remaining < 1) {
978            noStorageText = getString(R.string.not_enough_space);
979        }
980
981        if (noStorageText != null) {
982            if (mStorageHint == null) {
983                mStorageHint = OnScreenHint.makeText(this, noStorageText);
984            } else {
985                mStorageHint.setText(noStorageText);
986            }
987            mStorageHint.show();
988        } else if (mStorageHint != null) {
989            mStorageHint.cancel();
990            mStorageHint = null;
991        }
992    }
993
994    private void installIntentFilter() {
995        // install an intent filter to receive SD card related events.
996        IntentFilter intentFilter =
997                new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);
998        intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
999        intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);
1000        intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
1001        intentFilter.addAction(Intent.ACTION_MEDIA_CHECKING);
1002        intentFilter.addDataScheme("file");
1003        registerReceiver(mReceiver, intentFilter);
1004        mDidRegister = true;
1005    }
1006
1007    private void initializeFocusTone() {
1008        // Initialize focus tone generator.
1009        try {
1010            mFocusToneGenerator = new ToneGenerator(
1011                    AudioManager.STREAM_SYSTEM, FOCUS_BEEP_VOLUME);
1012        } catch (Throwable ex) {
1013            Log.w(TAG, "Exception caught while creating tone generator: ", ex);
1014            mFocusToneGenerator = null;
1015        }
1016    }
1017
1018    private void readPreference() {
1019        mRecordLocation = mPreferences.getBoolean(
1020                "pref_camera_recordlocation_key", false);
1021        mFocusMode = mPreferences.getString(
1022                CameraSettings.KEY_FOCUS_MODE,
1023                getString(R.string.pref_camera_focusmode_default));
1024    }
1025
1026    @Override
1027    public void onResume() {
1028        super.onResume();
1029
1030        mPausing = false;
1031        mJpegPictureCallbackTime = 0;
1032        mImageCapture = new ImageCapture();
1033
1034        // Start the preview if it is not started.
1035        if (!mPreviewing && !mStartPreviewFail) {
1036            try {
1037                startPreview();
1038            } catch (CameraHardwareException e) {
1039                showCameraErrorAndFinish();
1040                return;
1041            }
1042        }
1043
1044        if (mSurfaceHolder != null) {
1045            // If first time initialization is not finished, put it in the
1046            // message queue.
1047            if (!mFirstTimeInitialized) {
1048                mHandler.sendEmptyMessage(FIRST_TIME_INIT);
1049            } else {
1050                initializeSecondTime();
1051            }
1052        }
1053        keepScreenOnAwhile();
1054    }
1055
1056    private static ImageManager.DataLocation dataLocation() {
1057        return ImageManager.DataLocation.EXTERNAL;
1058    }
1059
1060    @Override
1061    protected void onPause() {
1062        mPausing = true;
1063        stopPreview();
1064        // Close the camera now because other activities may need to use it.
1065        closeCamera();
1066        resetScreenOn();
1067
1068        if (mSettings != null && mSettings.isVisible()) {
1069            mSettings.setVisible(false);
1070        }
1071
1072        if (mFirstTimeInitialized) {
1073            mOrientationListener.disable();
1074            mGpsIndicator.setMode(GPS_MODE_OFF);
1075            if (!mIsImageCaptureIntent) {
1076                mThumbController.storeData(
1077                        ImageManager.getLastImageThumbPath());
1078            }
1079            hidePostCaptureAlert();
1080        }
1081
1082        if (mDidRegister) {
1083            unregisterReceiver(mReceiver);
1084            mDidRegister = false;
1085        }
1086        stopReceivingLocationUpdates();
1087
1088        if (mFocusToneGenerator != null) {
1089            mFocusToneGenerator.release();
1090            mFocusToneGenerator = null;
1091        }
1092
1093        if (mStorageHint != null) {
1094            mStorageHint.cancel();
1095            mStorageHint = null;
1096        }
1097
1098        // If we are in an image capture intent and has taken
1099        // a picture, we just clear it in onPause.
1100        mImageCapture.clearLastData();
1101        mImageCapture = null;
1102
1103        // Remove the messages in the event queue.
1104        mHandler.removeMessages(RESTART_PREVIEW);
1105        mHandler.removeMessages(FIRST_TIME_INIT);
1106
1107        super.onPause();
1108    }
1109
1110    @Override
1111    protected void onActivityResult(
1112            int requestCode, int resultCode, Intent data) {
1113        switch (requestCode) {
1114            case CROP_MSG: {
1115                Intent intent = new Intent();
1116                if (data != null) {
1117                    Bundle extras = data.getExtras();
1118                    if (extras != null) {
1119                        intent.putExtras(extras);
1120                    }
1121                }
1122                setResult(resultCode, intent);
1123                finish();
1124
1125                File path = getFileStreamPath(sTempCropFilename);
1126                path.delete();
1127
1128                break;
1129            }
1130        }
1131    }
1132
1133    private boolean canTakePicture() {
1134        return isCameraIdle() && mPreviewing && (mPicturesRemaining > 0);
1135    }
1136
1137    private void autoFocus() {
1138        // Initiate autofocus only when preview is started and snapshot is not
1139        // in progress.
1140        if (canTakePicture()) {
1141            Log.v(TAG, "Start autofocus.");
1142            mFocusStartTime = System.currentTimeMillis();
1143            mFocusState = FOCUSING;
1144            updateFocusIndicator();
1145            mCameraDevice.autoFocus(mAutoFocusCallback);
1146        }
1147    }
1148
1149    private void cancelAutoFocus() {
1150        // User releases half-pressed focus key.
1151        if (mFocusState == FOCUSING || mFocusState == FOCUS_SUCCESS
1152                || mFocusState == FOCUS_FAIL) {
1153            Log.v(TAG, "Cancel autofocus.");
1154            mCameraDevice.cancelAutoFocus();
1155        }
1156        if (mFocusState != FOCUSING_SNAP_ON_FINISH) {
1157            clearFocusState();
1158        }
1159    }
1160
1161    private void clearFocusState() {
1162        mFocusState = FOCUS_NOT_STARTED;
1163        updateFocusIndicator();
1164    }
1165
1166    private void updateFocusIndicator() {
1167        if (mFocusRectangle == null) return;
1168
1169        if (mFocusState == FOCUSING || mFocusState == FOCUSING_SNAP_ON_FINISH) {
1170            mFocusRectangle.showStart();
1171        } else if (mFocusState == FOCUS_SUCCESS) {
1172            mFocusRectangle.showSuccess();
1173        } else if (mFocusState == FOCUS_FAIL) {
1174            mFocusRectangle.showFail();
1175        } else {
1176            mFocusRectangle.clear();
1177        }
1178    }
1179
1180    @Override
1181    public boolean onKeyDown(int keyCode, KeyEvent event) {
1182        switch (keyCode) {
1183            case KeyEvent.KEYCODE_BACK:
1184                if (!isCameraIdle()) {
1185                    // ignore backs while we're taking a picture
1186                    return true;
1187                }
1188                break;
1189            case KeyEvent.KEYCODE_FOCUS:
1190                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1191                    doFocus(true);
1192                }
1193                return true;
1194            case KeyEvent.KEYCODE_CAMERA:
1195                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1196                    doSnap();
1197                }
1198                return true;
1199            case KeyEvent.KEYCODE_DPAD_CENTER:
1200                // If we get a dpad center event without any focused view, move
1201                // the focus to the shutter button and press it.
1202                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1203                    // Start auto-focus immediately to reduce shutter lag. After
1204                    // the shutter button gets the focus, doFocus() will be
1205                    // called again but it is fine.
1206                    doFocus(true);
1207                    if (mShutterButton.isInTouchMode()) {
1208                        mShutterButton.requestFocusFromTouch();
1209                    } else {
1210                        mShutterButton.requestFocus();
1211                    }
1212                    mShutterButton.setPressed(true);
1213                }
1214                return true;
1215        }
1216
1217        return super.onKeyDown(keyCode, event);
1218    }
1219
1220    @Override
1221    public boolean onKeyUp(int keyCode, KeyEvent event) {
1222        switch (keyCode) {
1223            case KeyEvent.KEYCODE_FOCUS:
1224                if (mFirstTimeInitialized) {
1225                    doFocus(false);
1226                }
1227                return true;
1228        }
1229        return super.onKeyUp(keyCode, event);
1230    }
1231
1232    private void doSnap() {
1233        // If the user has half-pressed the shutter and focus is completed, we
1234        // can take the photo right away. If the focus mode is infinity, we can
1235        // also take the photo.
1236        if (mFocusMode.equals(Parameters.FOCUS_MODE_INFINITY)
1237                || (mFocusState == FOCUS_SUCCESS
1238                || mFocusState == FOCUS_FAIL)) {
1239            mImageCapture.onSnap();
1240        } else if (mFocusState == FOCUSING) {
1241            // Half pressing the shutter (i.e. the focus button event) will
1242            // already have requested AF for us, so just request capture on
1243            // focus here.
1244            mFocusState = FOCUSING_SNAP_ON_FINISH;
1245        } else if (mFocusState == FOCUS_NOT_STARTED) {
1246            // Focus key down event is dropped for some reasons. Just ignore.
1247        }
1248    }
1249
1250    private void doFocus(boolean pressed) {
1251        // Do the focus if the mode is not infinity.
1252        if (!mFocusMode.equals(Parameters.FOCUS_MODE_INFINITY)) {
1253            if (pressed) {  // Focus key down.
1254                autoFocus();
1255            } else {  // Focus key up.
1256                cancelAutoFocus();
1257            }
1258        }
1259    }
1260
1261    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
1262        // Make sure we have a surface in the holder before proceeding.
1263        if (holder.getSurface() == null) {
1264            Log.d(TAG, "holder.getSurface() == null");
1265            return;
1266        }
1267
1268        // The mCameraDevice will be null if it fails to connect to the camera
1269        // hardware. In this case we will show a dialog and then finish the
1270        // activity, so it's OK to ignore it.
1271        if (mCameraDevice == null) return;
1272
1273        mSurfaceHolder = holder;
1274        mViewFinderHeight = h;
1275
1276        // Sometimes surfaceChanged is called after onPause. Ignore it.
1277        if (mPausing || isFinishing()) return;
1278
1279        // Set preview display if the surface is being created. Preview was
1280        // already started.
1281        if (holder.isCreating()) {
1282            setPreviewDisplay(holder);
1283        }
1284
1285        // If first time initialization is not finished, send a message to do
1286        // it later. We want to finish surfaceChanged as soon as possible to let
1287        // user see preview first.
1288        if (!mFirstTimeInitialized) {
1289            mHandler.sendEmptyMessage(FIRST_TIME_INIT);
1290        } else {
1291            initializeSecondTime();
1292        }
1293    }
1294
1295    public void surfaceCreated(SurfaceHolder holder) {
1296    }
1297
1298    public void surfaceDestroyed(SurfaceHolder holder) {
1299        stopPreview();
1300        mSurfaceHolder = null;
1301    }
1302
1303    private void closeCamera() {
1304        if (mCameraDevice != null) {
1305            CameraHolder.instance().release();
1306            mCameraDevice = null;
1307            mPreviewing = false;
1308        }
1309    }
1310
1311    private void ensureCameraDevice() throws CameraHardwareException {
1312        if (mCameraDevice == null) {
1313            mCameraDevice = CameraHolder.instance().open();
1314        }
1315    }
1316
1317    private void updateLastImage() {
1318        IImageList list = ImageManager.makeImageList(
1319            mContentResolver,
1320            dataLocation(),
1321            ImageManager.INCLUDE_IMAGES,
1322            ImageManager.SORT_ASCENDING,
1323            ImageManager.CAMERA_IMAGE_BUCKET_ID);
1324        int count = list.getCount();
1325        if (count > 0) {
1326            IImage image = list.getImageAt(count - 1);
1327            Uri uri = image.fullSizeImageUri();
1328            mThumbController.setData(uri, image.miniThumbBitmap());
1329        } else {
1330            mThumbController.setData(null, null);
1331        }
1332        list.close();
1333    }
1334
1335    private void showCameraErrorAndFinish() {
1336        Resources ress = getResources();
1337        Util.showFatalErrorAndFinish(Camera.this,
1338                ress.getString(R.string.camera_error_title),
1339                ress.getString(R.string.cannot_connect_camera));
1340    }
1341
1342    private void restartPreview() {
1343        // make sure the surfaceview fills the whole screen when previewing
1344        mSurfaceView.setAspectRatio(VideoPreview.DONT_CARE);
1345        try {
1346            startPreview();
1347        } catch (CameraHardwareException e) {
1348            showCameraErrorAndFinish();
1349            return;
1350        }
1351
1352        // Calculate this in advance of each shot so we don't add to shutter
1353        // latency. It's true that someone else could write to the SD card in
1354        // the mean time and fill it, but that could have happened between the
1355        // shutter press and saving the JPEG too.
1356        calculatePicturesRemaining();
1357    }
1358
1359    private void setPreviewDisplay(SurfaceHolder holder) {
1360        try {
1361            mCameraDevice.setPreviewDisplay(holder);
1362        } catch (Throwable ex) {
1363            closeCamera();
1364            throw new RuntimeException("setPreviewDisplay failed", ex);
1365        }
1366    }
1367
1368    private void startPreview() throws CameraHardwareException {
1369        if (mPausing || isFinishing()) return;
1370
1371        ensureCameraDevice();
1372
1373        // If we're previewing already, stop the preview first (this will blank
1374        // the screen).
1375        if (mPreviewing) stopPreview();
1376
1377        setPreviewDisplay(mSurfaceHolder);
1378        setCameraParameters();
1379
1380        final long wallTimeStart = SystemClock.elapsedRealtime();
1381        final long threadTimeStart = Debug.threadCpuTimeNanos();
1382
1383        // Set one shot preview callback for latency measurement.
1384        mCameraDevice.setOneShotPreviewCallback(mOneShotPreviewCallback);
1385        mCameraDevice.setErrorCallback(mErrorCallback);
1386
1387        try {
1388            Log.v(TAG, "startPreview");
1389            mCameraDevice.startPreview();
1390        } catch (Throwable ex) {
1391            closeCamera();
1392            throw new RuntimeException("startPreview failed", ex);
1393        }
1394        mPreviewing = true;
1395        mStatus = IDLE;
1396
1397        long threadTimeEnd = Debug.threadCpuTimeNanos();
1398        long wallTimeEnd = SystemClock.elapsedRealtime();
1399        if ((wallTimeEnd - wallTimeStart) > 3000) {
1400            Log.w(TAG, "startPreview() to " + (wallTimeEnd - wallTimeStart)
1401                    + " ms. Thread time was"
1402                    + (threadTimeEnd - threadTimeStart) / 1000000 + " ms.");
1403        }
1404    }
1405
1406    private void stopPreview() {
1407        if (mCameraDevice != null && mPreviewing) {
1408            Log.v(TAG, "stopPreview");
1409            mCameraDevice.stopPreview();
1410        }
1411        mPreviewing = false;
1412        // If auto focus was in progress, it would have been canceled.
1413        clearFocusState();
1414    }
1415
1416    private void resizeForPreviewAspectRatio(View v) {
1417        ViewGroup.LayoutParams params;
1418        params = v.getLayoutParams();
1419        Size size = mParameters.getPreviewSize();
1420        params.width = (int) (params.height * size.width / size.height);
1421        Log.v(TAG, "resize to " + params.width + "x" + params.height);
1422        v.setLayoutParams(params);
1423    }
1424
1425    private Size getOptimalPreviewSize(List<Size> sizes) {
1426        Size optimalSize = null;
1427        if (sizes != null) {
1428            optimalSize = sizes.get(0);
1429            for (int i = 1; i < sizes.size(); i++) {
1430                if (Math.abs(sizes.get(i).height - mViewFinderHeight) <
1431                        Math.abs(optimalSize.height - mViewFinderHeight)) {
1432                    optimalSize = sizes.get(i);
1433                }
1434            }
1435            Log.v(TAG, "Optimal preview size is " + optimalSize.width + "x"
1436                    + optimalSize.height);
1437        }
1438        return optimalSize;
1439    }
1440
1441    private static boolean isSupported(String value, List<String> supported) {
1442        return supported == null ? false : supported.indexOf(value) >= 0;
1443    }
1444
1445    private void setCameraParameters() {
1446        mParameters = mCameraDevice.getParameters();
1447
1448        // Reset preview frame rate to the maximum because it may be lowered by
1449        // video camera application.
1450        List<Integer> frameRates = mParameters.getSupportedPreviewFrameRates();
1451        if (frameRates != null) {
1452            Integer max = Collections.max(frameRates);
1453            mParameters.setPreviewFrameRate(max);
1454        }
1455
1456        // Set a preview size that is closest to the viewfinder height.
1457        List<Size> sizes = mParameters.getSupportedPreviewSizes();
1458        Size optimalSize = getOptimalPreviewSize(sizes);
1459        if (optimalSize != null) {
1460            mParameters.setPreviewSize(optimalSize.width, optimalSize.height);
1461        }
1462
1463        // Set picture size.
1464        String pictureSize = mPreferences.getString(
1465                CameraSettings.KEY_PICTURE_SIZE, null);
1466        if (pictureSize == null) {
1467            CameraSettings.initialCameraPictureSize(this, mParameters);
1468        } else {
1469            List<Size> supported = mParameters.getSupportedPictureSizes();
1470            CameraSettings.setCameraPictureSize(
1471                    pictureSize, supported, mParameters);
1472        }
1473
1474        // Set JPEG quality.
1475        String jpegQuality = mPreferences.getString(
1476                CameraSettings.KEY_JPEG_QUALITY,
1477                getString(R.string.pref_camera_jpegquality_default));
1478        mParameters.setJpegQuality(Integer.parseInt(jpegQuality));
1479
1480        // For the following settings, we need to check if the settings are
1481        // still supported by latest driver, if not, ignore the settings.
1482
1483        // Set flash mode.
1484        String flashMode = mPreferences.getString(
1485                CameraSettings.KEY_FLASH_MODE,
1486                getString(R.string.pref_camera_flashmode_default));
1487        List<String> supportedFlash = mParameters.getSupportedFlashModes();
1488        if (isSupported(flashMode, supportedFlash)) {
1489            mParameters.setFlashMode(flashMode);
1490        } else {
1491            // If the current flashMode is not support, show the
1492            // FLASH_MODE_OFF icon.
1493            flashMode = Parameters.FLASH_MODE_OFF;
1494        }
1495
1496        // We post the runner because this function can be called from
1497        // non-UI thread (i.e., startPreviewThread).
1498        final String finalFlashMode = flashMode;
1499        mHandler.post(new Runnable() {
1500            public void run() {
1501                mFlashIndicator.setMode(finalFlashMode);
1502            }
1503        });
1504
1505        // Set white balance parameter.
1506        String whiteBalance = mPreferences.getString(
1507                CameraSettings.KEY_WHITE_BALANCE,
1508                getString(R.string.pref_camera_whitebalance_default));
1509        if (isSupported(whiteBalance, mParameters.getSupportedWhiteBalance())) {
1510            mParameters.setWhiteBalance(whiteBalance);
1511        }
1512
1513        // Set color effect parameter.
1514        String colorEffect = mPreferences.getString(
1515                CameraSettings.KEY_COLOR_EFFECT,
1516                getString(R.string.pref_camera_coloreffect_default));
1517        if (isSupported(colorEffect, mParameters.getSupportedColorEffects())) {
1518            mParameters.setColorEffect(colorEffect);
1519        }
1520
1521        // Set scene mode.
1522        String sceneMode = mPreferences.getString(
1523                CameraSettings.KEY_SCENE_MODE,
1524                getString(R.string.pref_camera_scenemode_default));
1525        if (isSupported(sceneMode, mParameters.getSupportedSceneModes())) {
1526            mParameters.setSceneMode(sceneMode);
1527        }
1528
1529        // Set focus mode.
1530        mFocusMode = mPreferences.getString(
1531                CameraSettings.KEY_FOCUS_MODE,
1532                getString(R.string.pref_camera_focusmode_default));
1533        if (isSupported(mFocusMode, mParameters.getSupportedFocusModes())) {
1534            mParameters.setFocusMode(mFocusMode);
1535        }
1536
1537        mCameraDevice.setParameters(mParameters);
1538    }
1539
1540    private void gotoGallery() {
1541        MenuHelper.gotoCameraImageGallery(this);
1542    }
1543
1544    private void viewLastImage() {
1545        if (mThumbController.isUriValid()) {
1546            Uri targetUri = mThumbController.getUri();
1547            targetUri = targetUri.buildUpon().appendQueryParameter(
1548                    "bucketId", ImageManager.CAMERA_IMAGE_BUCKET_ID).build();
1549            Intent intent = new Intent(this, ReviewImage.class);
1550            intent.setData(targetUri);
1551            intent.putExtra(MediaStore.EXTRA_FULL_SCREEN, true);
1552            intent.putExtra(MediaStore.EXTRA_SHOW_ACTION_ICONS, true);
1553            intent.putExtra("com.android.camera.ReviewMode", true);
1554            try {
1555                startActivity(intent);
1556            } catch (ActivityNotFoundException ex) {
1557                Log.e(TAG, "review image fail", ex);
1558            }
1559        } else {
1560            Log.e(TAG, "Can't view last image.");
1561        }
1562    }
1563
1564    private void startReceivingLocationUpdates() {
1565        if (mLocationManager != null) {
1566            try {
1567                mLocationManager.requestLocationUpdates(
1568                        LocationManager.NETWORK_PROVIDER,
1569                        1000,
1570                        0F,
1571                        mLocationListeners[1]);
1572            } catch (java.lang.SecurityException ex) {
1573                Log.i(TAG, "fail to request location update, ignore", ex);
1574            } catch (IllegalArgumentException ex) {
1575                Log.d(TAG, "provider does not exist " + ex.getMessage());
1576            }
1577            try {
1578                mLocationManager.requestLocationUpdates(
1579                        LocationManager.GPS_PROVIDER,
1580                        1000,
1581                        0F,
1582                        mLocationListeners[0]);
1583            } catch (java.lang.SecurityException ex) {
1584                Log.i(TAG, "fail to request location update, ignore", ex);
1585            } catch (IllegalArgumentException ex) {
1586                Log.d(TAG, "provider does not exist " + ex.getMessage());
1587            }
1588        }
1589    }
1590
1591    private void stopReceivingLocationUpdates() {
1592        if (mLocationManager != null) {
1593            for (int i = 0; i < mLocationListeners.length; i++) {
1594                try {
1595                    mLocationManager.removeUpdates(mLocationListeners[i]);
1596                } catch (Exception ex) {
1597                    Log.i(TAG, "fail to remove location listners, ignore", ex);
1598                }
1599            }
1600        }
1601    }
1602
1603    private Location getCurrentLocation() {
1604        // go in best to worst order
1605        for (int i = 0; i < mLocationListeners.length; i++) {
1606            Location l = mLocationListeners[i].current();
1607            if (l != null) return l;
1608        }
1609        return null;
1610    }
1611
1612    private boolean isCameraIdle() {
1613        return mStatus == IDLE && mFocusState == FOCUS_NOT_STARTED;
1614    }
1615
1616    private boolean isImageCaptureIntent() {
1617        String action = getIntent().getAction();
1618        return (MediaStore.ACTION_IMAGE_CAPTURE.equals(action));
1619    }
1620
1621    private void setupCaptureParams() {
1622        Bundle myExtras = getIntent().getExtras();
1623        if (myExtras != null) {
1624            mSaveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT);
1625            mCropValue = myExtras.getString("crop");
1626        }
1627    }
1628
1629    private void showPostCaptureAlert() {
1630        if (mIsImageCaptureIntent) {
1631            findViewById(R.id.shutter_button).setVisibility(View.INVISIBLE);
1632            int[] pickIds = {R.id.btn_retake, R.id.btn_done};
1633            for (int id : pickIds) {
1634                View button = findViewById(id);
1635                ((View) button.getParent()).setVisibility(View.VISIBLE);
1636            }
1637        }
1638    }
1639
1640    private void hidePostCaptureAlert() {
1641        if (mIsImageCaptureIntent) {
1642            findViewById(R.id.shutter_button).setVisibility(View.VISIBLE);
1643            int[] pickIds = {R.id.btn_retake, R.id.btn_done};
1644            for (int id : pickIds) {
1645                View button = findViewById(id);
1646                ((View) button.getParent()).setVisibility(View.GONE);
1647            }
1648        }
1649    }
1650
1651    private int calculatePicturesRemaining() {
1652        mPicturesRemaining = MenuHelper.calculatePicturesRemaining();
1653        return mPicturesRemaining;
1654    }
1655
1656    @Override
1657    public boolean onPrepareOptionsMenu(Menu menu) {
1658        super.onPrepareOptionsMenu(menu);
1659        // Only show the menu when camera is idle.
1660        for (int i = 0; i < menu.size(); i++) {
1661            menu.getItem(i).setVisible(isCameraIdle());
1662        }
1663
1664        return true;
1665    }
1666
1667    @Override
1668    public boolean onCreateOptionsMenu(Menu menu) {
1669        super.onCreateOptionsMenu(menu);
1670
1671        if (mIsImageCaptureIntent) {
1672            // No options menu for attach mode.
1673            return false;
1674        } else {
1675            addBaseMenuItems(menu);
1676        }
1677        return true;
1678    }
1679
1680    private void addBaseMenuItems(Menu menu) {
1681        MenuItem gallery = menu.add(Menu.NONE, Menu.NONE,
1682                MenuHelper.POSITION_GOTO_GALLERY,
1683                R.string.camera_gallery_photos_text)
1684                .setOnMenuItemClickListener(new OnMenuItemClickListener() {
1685            public boolean onMenuItemClick(MenuItem item) {
1686                gotoGallery();
1687                return true;
1688            }
1689        });
1690        gallery.setIcon(android.R.drawable.ic_menu_gallery);
1691        mGalleryItems.add(gallery);
1692
1693        MenuItem item = menu.add(Menu.NONE, Menu.NONE,
1694                MenuHelper.POSITION_CAMERA_SETTING, R.string.settings)
1695                .setOnMenuItemClickListener(new OnMenuItemClickListener() {
1696            public boolean onMenuItemClick(MenuItem item) {
1697                showOnScreenSettings();
1698                return true;
1699            }
1700        });
1701        item.setIcon(android.R.drawable.ic_menu_preferences);
1702    }
1703
1704    public boolean onSwitchChanged(Switcher source, boolean onOff) {
1705        if (onOff == SWITCH_VIDEO) {
1706            if (!isCameraIdle()) return false;
1707            MenuHelper.gotoVideoMode(this);
1708            finish();
1709        }
1710        return true;
1711    }
1712
1713    public void onSharedPreferenceChanged(
1714            SharedPreferences preferences, String key) {
1715        // ignore the events after "onPause()"
1716        if (mPausing) return;
1717
1718        if (CameraSettings.KEY_RECORD_LOCATION.equals(key)) {
1719            mRecordLocation = preferences.getBoolean(key, false);
1720            if (mRecordLocation) {
1721                startReceivingLocationUpdates();
1722            } else {
1723                stopReceivingLocationUpdates();
1724            }
1725        } else {
1726            // All preferences except RECORD_LOCATION are camera parameters.
1727            // Call setCameraParameters to take effect now.
1728            setCameraParameters();
1729        }
1730    }
1731
1732    @Override
1733    public void onUserInteraction() {
1734        super.onUserInteraction();
1735        keepScreenOnAwhile();
1736    }
1737
1738    private void resetScreenOn() {
1739        mHandler.removeMessages(CLEAR_SCREEN_DELAY);
1740        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1741    }
1742
1743    private void keepScreenOnAwhile() {
1744        mHandler.removeMessages(CLEAR_SCREEN_DELAY);
1745        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1746        mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY);
1747    }
1748}
1749
1750class FocusRectangle extends View {
1751
1752    @SuppressWarnings("unused")
1753    private static final String TAG = "FocusRectangle";
1754
1755    public FocusRectangle(Context context, AttributeSet attrs) {
1756        super(context, attrs);
1757    }
1758
1759    private void setDrawable(int resid) {
1760        setBackgroundDrawable(getResources().getDrawable(resid));
1761    }
1762
1763    public void showStart() {
1764        setDrawable(R.drawable.focus_focusing);
1765    }
1766
1767    public void showSuccess() {
1768        setDrawable(R.drawable.focus_focused);
1769    }
1770
1771    public void showFail() {
1772        setDrawable(R.drawable.focus_focus_failed);
1773    }
1774
1775    public void clear() {
1776        setBackgroundDrawable(null);
1777    }
1778}
1779