Camera.java revision b02ebbea2d3d98a3ab2c15cb152387b9d201dd18
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, name, null, data);
548                if (mLastContentUri == null) {
549                    // this means we got an error
550                    mCancel = true;
551                }
552                int degree = 0;
553                if (!mCancel) {
554                    degree = ImageManager.getExifOrientation(
555                            ImageManager.CAMERA_IMAGE_BUCKET_NAME + "/" + name);
556                    ImageManager.setImageSize(mContentResolver, mLastContentUri,
557                            new File(ImageManager.CAMERA_IMAGE_BUCKET_NAME,
558                            name).length());
559                }
560                return degree;
561            } catch (Exception ex) {
562                Log.e(TAG, "Exception while compressing image.", ex);
563                return 0;
564            }
565        }
566
567        public void storeImage(final byte[] data,
568                android.hardware.Camera camera, Location loc) {
569            if (!mIsImageCaptureIntent) {
570                int degree = storeImage(data, loc);
571                sendBroadcast(new Intent(
572                        "com.android.camera.NEW_PICTURE", mLastContentUri));
573                setLastPictureThumb(data, degree,
574                        mImageCapture.getLastCaptureUri());
575                mThumbController.updateDisplayIfNeeded();
576            } else {
577                mCaptureOnlyData = data;
578                showPostCaptureAlert();
579            }
580        }
581
582        /**
583         * Initiate the capture of an image.
584         */
585        public void initiate() {
586            if (mCameraDevice == null) {
587                return;
588            }
589
590            mCancel = false;
591
592            capture();
593        }
594
595        public Uri getLastCaptureUri() {
596            return mLastContentUri;
597        }
598
599        public byte[] getLastCaptureData() {
600            return mCaptureOnlyData;
601        }
602
603        private void capture() {
604            mCaptureOnlyData = null;
605
606            // Set rotation.
607            int orientation = mLastOrientation;
608            if (orientation != OrientationEventListener.ORIENTATION_UNKNOWN) {
609                orientation += 90;
610            }
611            orientation = ImageManager.roundOrientation(orientation);
612            Log.v(TAG, "mLastOrientation = " + mLastOrientation
613                    + ", orientation = " + orientation);
614            mParameters.setRotation(orientation);
615
616            // Clear previous GPS location from the parameters.
617            mParameters.removeGpsData();
618
619            // Set GPS location.
620            Location loc = mRecordLocation ? getCurrentLocation() : null;
621            if (loc != null) {
622                double lat = loc.getLatitude();
623                double lon = loc.getLongitude();
624                boolean hasLatLon = (lat != 0.0d) || (lon != 0.0d);
625
626                if (hasLatLon) {
627                    mParameters.setGpsLatitude(lat);
628                    mParameters.setGpsLongitude(lon);
629                    if (loc.hasAltitude()) {
630                        mParameters.setGpsAltitude(loc.getAltitude());
631                    } else {
632                        // for NETWORK_PROVIDER location provider, we may have
633                        // no altitude information, but the driver needs it, so
634                        // we fake one.
635                        mParameters.setGpsAltitude(0);
636                    }
637                    if (loc.getTime() != 0) {
638                        // Location.getTime() is UTC in milliseconds.
639                        // gps-timestamp is UTC in seconds.
640                        long utcTimeSeconds = loc.getTime() / 1000;
641                        mParameters.setGpsTimestamp(utcTimeSeconds);
642                    }
643                } else {
644                    loc = null;
645                }
646            }
647
648            mCameraDevice.setParameters(mParameters);
649
650            mCameraDevice.takePicture(mShutterCallback, mRawPictureCallback,
651                    new JpegPictureCallback(loc));
652            mPreviewing = false;
653        }
654
655        public void onSnap() {
656            // If we are already in the middle of taking a snapshot then ignore.
657            if (mPausing || mStatus == SNAPSHOT_IN_PROGRESS) {
658                return;
659            }
660            mCaptureStartTime = System.currentTimeMillis();
661
662            // Don't check the filesystem here, we can't afford the latency.
663            // Instead, check the cached value which was calculated when the
664            // preview was restarted.
665            if (mPicturesRemaining < 1) {
666                updateStorageHint(mPicturesRemaining);
667                return;
668            }
669
670            mStatus = SNAPSHOT_IN_PROGRESS;
671
672            mImageCapture.initiate();
673        }
674
675        private void clearLastData() {
676            mCaptureOnlyData = null;
677        }
678    }
679
680    public boolean saveDataToFile(String filePath, byte[] data) {
681        FileOutputStream f = null;
682        try {
683            f = new FileOutputStream(filePath);
684            f.write(data);
685        } catch (IOException e) {
686            return false;
687        } finally {
688            MenuHelper.closeSilently(f);
689        }
690        return true;
691    }
692
693    private void setLastPictureThumb(byte[] data, int degree, Uri uri) {
694        BitmapFactory.Options options = new BitmapFactory.Options();
695        options.inSampleSize = 16;
696        Bitmap lastPictureThumb =
697                BitmapFactory.decodeByteArray(data, 0, data.length, options);
698        lastPictureThumb = Util.rotate(lastPictureThumb, degree);
699        mThumbController.setData(uri, lastPictureThumb);
700    }
701
702    private static String createName(long dateTaken) {
703        return DateFormat.format("yyyy-MM-dd kk.mm.ss", dateTaken).toString();
704    }
705
706    @Override
707    public void onCreate(Bundle icicle) {
708        super.onCreate(icicle);
709
710        Window win = getWindow();
711        win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
712        setContentView(R.layout.camera);
713        mSurfaceView = (VideoPreview) findViewById(R.id.camera_preview);
714        mViewFinderHeight = mSurfaceView.getLayoutParams().height;
715        mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
716
717        /*
718         * To reduce startup time, we start the preview in another thread.
719         * We make sure the preview is started at the end of onCreate.
720         */
721        Thread startPreviewThread = new Thread(new Runnable() {
722            public void run() {
723                try {
724                    mStartPreviewFail = false;
725                    startPreview();
726                } catch (CameraHardwareException e) {
727                    // In eng build, we throw the exception so that test tool
728                    // can detect it and report it
729                    if ("eng".equals(Build.TYPE)) {
730                        throw new RuntimeException(e);
731                    }
732                    mStartPreviewFail = true;
733                }
734            }
735        });
736        startPreviewThread.start();
737
738        // don't set mSurfaceHolder here. We have it set ONLY within
739        // surfaceChanged / surfaceDestroyed, other parts of the code
740        // assume that when it is set, the surface is also set.
741        SurfaceHolder holder = mSurfaceView.getHolder();
742        holder.addCallback(this);
743        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
744
745        mIsImageCaptureIntent = isImageCaptureIntent();
746        if (mIsImageCaptureIntent) {
747            setupCaptureParams();
748        }
749
750        LayoutInflater inflater = getLayoutInflater();
751
752        ViewGroup rootView = (ViewGroup) findViewById(R.id.camera);
753        if (mIsImageCaptureIntent) {
754            View controlBar = inflater.inflate(
755                    R.layout.attach_camera_control, rootView);
756            controlBar.findViewById(R.id.btn_cancel).setOnClickListener(this);
757            controlBar.findViewById(R.id.btn_retake).setOnClickListener(this);
758            controlBar.findViewById(R.id.btn_done).setOnClickListener(this);
759        } else {
760            inflater.inflate(R.layout.camera_control, rootView);
761            mSwitcher = ((Switcher) findViewById(R.id.camera_switch));
762            mSwitcher.setOnSwitchListener(this);
763            mSwitcher.addTouchView(findViewById(R.id.camera_switch_set));
764        }
765        findViewById(R.id.btn_gripper)
766                .setOnTouchListener(new GripperTouchListener());
767
768        mFlashIndicator = (IconIndicator) findViewById(R.id.flash_icon);
769
770        // Make sure preview is started.
771        try {
772            startPreviewThread.join();
773            if (mStartPreviewFail) {
774                showCameraErrorAndFinish();
775                return;
776            }
777        } catch (InterruptedException ex) {
778            // ignore
779        }
780
781        // Resize mVideoPreview to the right aspect ratio.
782        resizeForPreviewAspectRatio(mSurfaceView);
783    }
784
785    private class GripperTouchListener implements View.OnTouchListener {
786        public boolean onTouch(View view, MotionEvent event) {
787            switch (event.getAction()) {
788                case MotionEvent.ACTION_DOWN:
789                    return true;
790                case MotionEvent.ACTION_UP:
791                    showOnScreenSettings();
792                    return true;
793            }
794            return false;
795        }
796    }
797
798    @Override
799    public void onStart() {
800        super.onStart();
801        if (!mIsImageCaptureIntent) {
802            mSwitcher.setSwitch(SWITCH_CAMERA);
803        }
804    }
805
806    private void checkStorage() {
807        if (ImageManager.isMediaScannerScanning(getContentResolver())) {
808            mPicturesRemaining = MenuHelper.NO_STORAGE_ERROR;
809        } else {
810            calculatePicturesRemaining();
811        }
812        updateStorageHint(mPicturesRemaining);
813    }
814
815    private void showOnScreenSettings() {
816        if (mSettings == null) {
817            mSettings = new OnScreenSettings(
818                    findViewById(R.id.camera_preview));
819            CameraSettings helper = new CameraSettings(this, mParameters);
820            mSettings.setPreferenceScreen(helper
821                    .getPreferenceScreen(R.xml.camera_preferences));
822            mSettings.setOnVisibilityChangedListener(this);
823        }
824        mSettings.expandPanel();
825    }
826
827    public void onClick(View v) {
828        switch (v.getId()) {
829            case R.id.btn_retake:
830                hidePostCaptureAlert();
831                restartPreview();
832                break;
833            case R.id.review_thumbnail:
834                if (isCameraIdle()) {
835                    viewLastImage();
836                }
837                break;
838            case R.id.btn_done:
839                doAttach();
840                break;
841            case R.id.btn_cancel:
842                doCancel();
843        }
844    }
845
846    private Bitmap createCaptureBitmap(byte[] data) {
847        // This is really stupid...we just want to read the orientation in
848        // the jpeg header.
849        String filepath = ImageManager.getTempJpegPath();
850        int degree = 0;
851        if (saveDataToFile(filepath, data)) {
852            degree = ImageManager.getExifOrientation(filepath);
853            new File(filepath).delete();
854        }
855
856        // Limit to 50k pixels so we can return it in the intent.
857        Bitmap bitmap = Util.makeBitmap(data, 50*1024);
858        bitmap = Util.rotate(bitmap, degree);
859        return bitmap;
860    }
861
862    private void doAttach() {
863        if (mPausing) {
864            return;
865        }
866
867        byte[] data = mImageCapture.getLastCaptureData();
868
869        if (mCropValue == null) {
870            // First handle the no crop case -- just return the value.  If the
871            // caller specifies a "save uri" then write the data to it's
872            // stream. Otherwise, pass back a scaled down version of the bitmap
873            // directly in the extras.
874            if (mSaveUri != null) {
875                OutputStream outputStream = null;
876                try {
877                    outputStream = mContentResolver.openOutputStream(mSaveUri);
878                    outputStream.write(data);
879                    outputStream.close();
880
881                    setResult(RESULT_OK);
882                    finish();
883                } catch (IOException ex) {
884                    // ignore exception
885                } finally {
886                    Util.closeSilently(outputStream);
887                }
888            } else {
889                Bitmap bitmap = createCaptureBitmap(data);
890                setResult(RESULT_OK,
891                        new Intent("inline-data").putExtra("data", bitmap));
892                finish();
893            }
894        } else {
895            // Save the image to a temp file and invoke the cropper
896            Uri tempUri = null;
897            FileOutputStream tempStream = null;
898            try {
899                File path = getFileStreamPath(sTempCropFilename);
900                path.delete();
901                tempStream = openFileOutput(sTempCropFilename, 0);
902                tempStream.write(data);
903                tempStream.close();
904                tempUri = Uri.fromFile(path);
905            } catch (FileNotFoundException ex) {
906                setResult(Activity.RESULT_CANCELED);
907                finish();
908                return;
909            } catch (IOException ex) {
910                setResult(Activity.RESULT_CANCELED);
911                finish();
912                return;
913            } finally {
914                Util.closeSilently(tempStream);
915            }
916
917            Bundle newExtras = new Bundle();
918            if (mCropValue.equals("circle")) {
919                newExtras.putString("circleCrop", "true");
920            }
921            if (mSaveUri != null) {
922                newExtras.putParcelable(MediaStore.EXTRA_OUTPUT, mSaveUri);
923            } else {
924                newExtras.putBoolean("return-data", true);
925            }
926
927            Intent cropIntent = new Intent();
928            cropIntent.setClass(this, CropImage.class);
929            cropIntent.setData(tempUri);
930            cropIntent.putExtras(newExtras);
931
932            startActivityForResult(cropIntent, CROP_MSG);
933        }
934    }
935
936    private void doCancel() {
937        setResult(RESULT_CANCELED, new Intent());
938        finish();
939    }
940
941    public void onShutterButtonFocus(ShutterButton button, boolean pressed) {
942        if (mPausing) {
943            return;
944        }
945        switch (button.getId()) {
946            case R.id.shutter_button:
947                doFocus(pressed);
948                break;
949        }
950    }
951
952    public void onShutterButtonClick(ShutterButton button) {
953        if (mPausing) {
954            return;
955        }
956        switch (button.getId()) {
957            case R.id.shutter_button:
958                doSnap();
959                break;
960        }
961    }
962
963    private OnScreenHint mStorageHint;
964
965    private void updateStorageHint(int remaining) {
966        String noStorageText = null;
967
968        if (remaining == MenuHelper.NO_STORAGE_ERROR) {
969            String state = Environment.getExternalStorageState();
970            if (state == Environment.MEDIA_CHECKING ||
971                    ImageManager.isMediaScannerScanning(getContentResolver())) {
972                noStorageText = getString(R.string.preparing_sd);
973            } else {
974                noStorageText = getString(R.string.no_storage);
975            }
976        } else if (remaining < 1) {
977            noStorageText = getString(R.string.not_enough_space);
978        }
979
980        if (noStorageText != null) {
981            if (mStorageHint == null) {
982                mStorageHint = OnScreenHint.makeText(this, noStorageText);
983            } else {
984                mStorageHint.setText(noStorageText);
985            }
986            mStorageHint.show();
987        } else if (mStorageHint != null) {
988            mStorageHint.cancel();
989            mStorageHint = null;
990        }
991    }
992
993    private void installIntentFilter() {
994        // install an intent filter to receive SD card related events.
995        IntentFilter intentFilter =
996                new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);
997        intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
998        intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);
999        intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
1000        intentFilter.addAction(Intent.ACTION_MEDIA_CHECKING);
1001        intentFilter.addDataScheme("file");
1002        registerReceiver(mReceiver, intentFilter);
1003        mDidRegister = true;
1004    }
1005
1006    private void initializeFocusTone() {
1007        // Initialize focus tone generator.
1008        try {
1009            mFocusToneGenerator = new ToneGenerator(
1010                    AudioManager.STREAM_SYSTEM, FOCUS_BEEP_VOLUME);
1011        } catch (Throwable ex) {
1012            Log.w(TAG, "Exception caught while creating tone generator: ", ex);
1013            mFocusToneGenerator = null;
1014        }
1015    }
1016
1017    private void readPreference() {
1018        mRecordLocation = mPreferences.getBoolean(
1019                "pref_camera_recordlocation_key", false);
1020        mFocusMode = mPreferences.getString(
1021                CameraSettings.KEY_FOCUS_MODE,
1022                getString(R.string.pref_camera_focusmode_default));
1023    }
1024
1025    @Override
1026    public void onResume() {
1027        super.onResume();
1028
1029        mPausing = false;
1030        mJpegPictureCallbackTime = 0;
1031        mImageCapture = new ImageCapture();
1032
1033        // Start the preview if it is not started.
1034        if (!mPreviewing && !mStartPreviewFail) {
1035            try {
1036                startPreview();
1037            } catch (CameraHardwareException e) {
1038                showCameraErrorAndFinish();
1039                return;
1040            }
1041        }
1042
1043        if (mSurfaceHolder != null) {
1044            // If first time initialization is not finished, put it in the
1045            // message queue.
1046            if (!mFirstTimeInitialized) {
1047                mHandler.sendEmptyMessage(FIRST_TIME_INIT);
1048            } else {
1049                initializeSecondTime();
1050            }
1051        }
1052        keepScreenOnAwhile();
1053    }
1054
1055    private static ImageManager.DataLocation dataLocation() {
1056        return ImageManager.DataLocation.EXTERNAL;
1057    }
1058
1059    @Override
1060    protected void onPause() {
1061        mPausing = true;
1062        stopPreview();
1063        // Close the camera now because other activities may need to use it.
1064        closeCamera();
1065        resetScreenOn();
1066
1067        if (mSettings != null && mSettings.isVisible()) {
1068            mSettings.setVisible(false);
1069        }
1070
1071        if (mFirstTimeInitialized) {
1072            mOrientationListener.disable();
1073            mGpsIndicator.setMode(GPS_MODE_OFF);
1074            if (!mIsImageCaptureIntent) {
1075                mThumbController.storeData(
1076                        ImageManager.getLastImageThumbPath());
1077            }
1078            hidePostCaptureAlert();
1079        }
1080
1081        if (mDidRegister) {
1082            unregisterReceiver(mReceiver);
1083            mDidRegister = false;
1084        }
1085        stopReceivingLocationUpdates();
1086
1087        if (mFocusToneGenerator != null) {
1088            mFocusToneGenerator.release();
1089            mFocusToneGenerator = null;
1090        }
1091
1092        if (mStorageHint != null) {
1093            mStorageHint.cancel();
1094            mStorageHint = null;
1095        }
1096
1097        // If we are in an image capture intent and has taken
1098        // a picture, we just clear it in onPause.
1099        mImageCapture.clearLastData();
1100        mImageCapture = null;
1101
1102        // Remove the messages in the event queue.
1103        mHandler.removeMessages(RESTART_PREVIEW);
1104        mHandler.removeMessages(FIRST_TIME_INIT);
1105
1106        super.onPause();
1107    }
1108
1109    @Override
1110    protected void onActivityResult(
1111            int requestCode, int resultCode, Intent data) {
1112        switch (requestCode) {
1113            case CROP_MSG: {
1114                Intent intent = new Intent();
1115                if (data != null) {
1116                    Bundle extras = data.getExtras();
1117                    if (extras != null) {
1118                        intent.putExtras(extras);
1119                    }
1120                }
1121                setResult(resultCode, intent);
1122                finish();
1123
1124                File path = getFileStreamPath(sTempCropFilename);
1125                path.delete();
1126
1127                break;
1128            }
1129        }
1130    }
1131
1132    private boolean canTakePicture() {
1133        return isCameraIdle() && mPreviewing && (mPicturesRemaining > 0);
1134    }
1135
1136    private void autoFocus() {
1137        // Initiate autofocus only when preview is started and snapshot is not
1138        // in progress.
1139        if (canTakePicture()) {
1140            Log.v(TAG, "Start autofocus.");
1141            mFocusStartTime = System.currentTimeMillis();
1142            mFocusState = FOCUSING;
1143            updateFocusIndicator();
1144            mCameraDevice.autoFocus(mAutoFocusCallback);
1145        }
1146    }
1147
1148    private void cancelAutoFocus() {
1149        // User releases half-pressed focus key.
1150        if (mFocusState == FOCUSING || mFocusState == FOCUS_SUCCESS
1151                || mFocusState == FOCUS_FAIL) {
1152            Log.v(TAG, "Cancel autofocus.");
1153            mCameraDevice.cancelAutoFocus();
1154        }
1155        if (mFocusState != FOCUSING_SNAP_ON_FINISH) {
1156            clearFocusState();
1157        }
1158    }
1159
1160    private void clearFocusState() {
1161        mFocusState = FOCUS_NOT_STARTED;
1162        updateFocusIndicator();
1163    }
1164
1165    private void updateFocusIndicator() {
1166        if (mFocusRectangle == null) return;
1167
1168        if (mFocusState == FOCUSING || mFocusState == FOCUSING_SNAP_ON_FINISH) {
1169            mFocusRectangle.showStart();
1170        } else if (mFocusState == FOCUS_SUCCESS) {
1171            mFocusRectangle.showSuccess();
1172        } else if (mFocusState == FOCUS_FAIL) {
1173            mFocusRectangle.showFail();
1174        } else {
1175            mFocusRectangle.clear();
1176        }
1177    }
1178
1179    @Override
1180    public void onBackPressed() {
1181        if (!isCameraIdle()) {
1182            // ignore backs while we're taking a picture
1183            return;
1184        }
1185        super.onBackPressed();
1186    }
1187
1188    @Override
1189    public boolean onKeyDown(int keyCode, KeyEvent event) {
1190        switch (keyCode) {
1191            case KeyEvent.KEYCODE_FOCUS:
1192                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1193                    doFocus(true);
1194                }
1195                return true;
1196            case KeyEvent.KEYCODE_CAMERA:
1197                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1198                    doSnap();
1199                }
1200                return true;
1201            case KeyEvent.KEYCODE_DPAD_CENTER:
1202                // If we get a dpad center event without any focused view, move
1203                // the focus to the shutter button and press it.
1204                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
1205                    // Start auto-focus immediately to reduce shutter lag. After
1206                    // the shutter button gets the focus, doFocus() will be
1207                    // called again but it is fine.
1208                    doFocus(true);
1209                    if (mShutterButton.isInTouchMode()) {
1210                        mShutterButton.requestFocusFromTouch();
1211                    } else {
1212                        mShutterButton.requestFocus();
1213                    }
1214                    mShutterButton.setPressed(true);
1215                }
1216                return true;
1217        }
1218
1219        return super.onKeyDown(keyCode, event);
1220    }
1221
1222    @Override
1223    public boolean onKeyUp(int keyCode, KeyEvent event) {
1224        switch (keyCode) {
1225            case KeyEvent.KEYCODE_FOCUS:
1226                if (mFirstTimeInitialized) {
1227                    doFocus(false);
1228                }
1229                return true;
1230        }
1231        return super.onKeyUp(keyCode, event);
1232    }
1233
1234    private void doSnap() {
1235        // If the user has half-pressed the shutter and focus is completed, we
1236        // can take the photo right away. If the focus mode is infinity, we can
1237        // also take the photo.
1238        if (mFocusMode.equals(Parameters.FOCUS_MODE_INFINITY)
1239                || (mFocusState == FOCUS_SUCCESS
1240                || mFocusState == FOCUS_FAIL)) {
1241            mImageCapture.onSnap();
1242        } else if (mFocusState == FOCUSING) {
1243            // Half pressing the shutter (i.e. the focus button event) will
1244            // already have requested AF for us, so just request capture on
1245            // focus here.
1246            mFocusState = FOCUSING_SNAP_ON_FINISH;
1247        } else if (mFocusState == FOCUS_NOT_STARTED) {
1248            // Focus key down event is dropped for some reasons. Just ignore.
1249        }
1250    }
1251
1252    private void doFocus(boolean pressed) {
1253        // Do the focus if the mode is not infinity.
1254        if (!mFocusMode.equals(Parameters.FOCUS_MODE_INFINITY)) {
1255            if (pressed) {  // Focus key down.
1256                autoFocus();
1257            } else {  // Focus key up.
1258                cancelAutoFocus();
1259            }
1260        }
1261    }
1262
1263    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
1264        // Make sure we have a surface in the holder before proceeding.
1265        if (holder.getSurface() == null) {
1266            Log.d(TAG, "holder.getSurface() == null");
1267            return;
1268        }
1269
1270        // The mCameraDevice will be null if it fails to connect to the camera
1271        // hardware. In this case we will show a dialog and then finish the
1272        // activity, so it's OK to ignore it.
1273        if (mCameraDevice == null) return;
1274
1275        mSurfaceHolder = holder;
1276        mViewFinderHeight = h;
1277
1278        // Sometimes surfaceChanged is called after onPause. Ignore it.
1279        if (mPausing || isFinishing()) return;
1280
1281        // Set preview display if the surface is being created. Preview was
1282        // already started.
1283        if (holder.isCreating()) {
1284            setPreviewDisplay(holder);
1285        }
1286
1287        // If first time initialization is not finished, send a message to do
1288        // it later. We want to finish surfaceChanged as soon as possible to let
1289        // user see preview first.
1290        if (!mFirstTimeInitialized) {
1291            mHandler.sendEmptyMessage(FIRST_TIME_INIT);
1292        } else {
1293            initializeSecondTime();
1294        }
1295    }
1296
1297    public void surfaceCreated(SurfaceHolder holder) {
1298    }
1299
1300    public void surfaceDestroyed(SurfaceHolder holder) {
1301        stopPreview();
1302        mSurfaceHolder = null;
1303    }
1304
1305    private void closeCamera() {
1306        if (mCameraDevice != null) {
1307            CameraHolder.instance().release();
1308            mCameraDevice = null;
1309            mPreviewing = false;
1310        }
1311    }
1312
1313    private void ensureCameraDevice() throws CameraHardwareException {
1314        if (mCameraDevice == null) {
1315            mCameraDevice = CameraHolder.instance().open();
1316        }
1317    }
1318
1319    private void updateLastImage() {
1320        IImageList list = ImageManager.makeImageList(
1321            mContentResolver,
1322            dataLocation(),
1323            ImageManager.INCLUDE_IMAGES,
1324            ImageManager.SORT_ASCENDING,
1325            ImageManager.CAMERA_IMAGE_BUCKET_ID);
1326        int count = list.getCount();
1327        if (count > 0) {
1328            IImage image = list.getImageAt(count - 1);
1329            Uri uri = image.fullSizeImageUri();
1330            mThumbController.setData(uri, image.miniThumbBitmap());
1331        } else {
1332            mThumbController.setData(null, null);
1333        }
1334        list.close();
1335    }
1336
1337    private void showCameraErrorAndFinish() {
1338        Resources ress = getResources();
1339        Util.showFatalErrorAndFinish(Camera.this,
1340                ress.getString(R.string.camera_error_title),
1341                ress.getString(R.string.cannot_connect_camera));
1342    }
1343
1344    private void restartPreview() {
1345        // make sure the surfaceview fills the whole screen when previewing
1346        mSurfaceView.setAspectRatio(VideoPreview.DONT_CARE);
1347        try {
1348            startPreview();
1349        } catch (CameraHardwareException e) {
1350            showCameraErrorAndFinish();
1351            return;
1352        }
1353
1354        // Calculate this in advance of each shot so we don't add to shutter
1355        // latency. It's true that someone else could write to the SD card in
1356        // the mean time and fill it, but that could have happened between the
1357        // shutter press and saving the JPEG too.
1358        calculatePicturesRemaining();
1359    }
1360
1361    private void setPreviewDisplay(SurfaceHolder holder) {
1362        try {
1363            mCameraDevice.setPreviewDisplay(holder);
1364        } catch (Throwable ex) {
1365            closeCamera();
1366            throw new RuntimeException("setPreviewDisplay failed", ex);
1367        }
1368    }
1369
1370    private void startPreview() throws CameraHardwareException {
1371        if (mPausing || isFinishing()) return;
1372
1373        ensureCameraDevice();
1374
1375        // If we're previewing already, stop the preview first (this will blank
1376        // the screen).
1377        if (mPreviewing) stopPreview();
1378
1379        setPreviewDisplay(mSurfaceHolder);
1380        setCameraParameters();
1381
1382        final long wallTimeStart = SystemClock.elapsedRealtime();
1383        final long threadTimeStart = Debug.threadCpuTimeNanos();
1384
1385        // Set one shot preview callback for latency measurement.
1386        mCameraDevice.setOneShotPreviewCallback(mOneShotPreviewCallback);
1387        mCameraDevice.setErrorCallback(mErrorCallback);
1388
1389        try {
1390            Log.v(TAG, "startPreview");
1391            mCameraDevice.startPreview();
1392        } catch (Throwable ex) {
1393            closeCamera();
1394            throw new RuntimeException("startPreview failed", ex);
1395        }
1396        mPreviewing = true;
1397        mStatus = IDLE;
1398
1399        long threadTimeEnd = Debug.threadCpuTimeNanos();
1400        long wallTimeEnd = SystemClock.elapsedRealtime();
1401        if ((wallTimeEnd - wallTimeStart) > 3000) {
1402            Log.w(TAG, "startPreview() to " + (wallTimeEnd - wallTimeStart)
1403                    + " ms. Thread time was"
1404                    + (threadTimeEnd - threadTimeStart) / 1000000 + " ms.");
1405        }
1406    }
1407
1408    private void stopPreview() {
1409        if (mCameraDevice != null && mPreviewing) {
1410            Log.v(TAG, "stopPreview");
1411            mCameraDevice.stopPreview();
1412        }
1413        mPreviewing = false;
1414        // If auto focus was in progress, it would have been canceled.
1415        clearFocusState();
1416    }
1417
1418    private void resizeForPreviewAspectRatio(View v) {
1419        ViewGroup.LayoutParams params;
1420        params = v.getLayoutParams();
1421        Size size = mParameters.getPreviewSize();
1422        params.width = (int) (params.height * size.width / size.height);
1423        Log.v(TAG, "resize to " + params.width + "x" + params.height);
1424        v.setLayoutParams(params);
1425    }
1426
1427    private Size getOptimalPreviewSize(List<Size> sizes) {
1428        Size optimalSize = null;
1429        if (sizes != null) {
1430            optimalSize = sizes.get(0);
1431            for (int i = 1; i < sizes.size(); i++) {
1432                if (Math.abs(sizes.get(i).height - mViewFinderHeight) <
1433                        Math.abs(optimalSize.height - mViewFinderHeight)) {
1434                    optimalSize = sizes.get(i);
1435                }
1436            }
1437            Log.v(TAG, "Optimal preview size is " + optimalSize.width + "x"
1438                    + optimalSize.height);
1439        }
1440        return optimalSize;
1441    }
1442
1443    private static boolean isSupported(String value, List<String> supported) {
1444        return supported == null ? false : supported.indexOf(value) >= 0;
1445    }
1446
1447    private void setCameraParameters() {
1448        mParameters = mCameraDevice.getParameters();
1449
1450        // Reset preview frame rate to the maximum because it may be lowered by
1451        // video camera application.
1452        List<Integer> frameRates = mParameters.getSupportedPreviewFrameRates();
1453        if (frameRates != null) {
1454            Integer max = Collections.max(frameRates);
1455            mParameters.setPreviewFrameRate(max);
1456        }
1457
1458        // Set a preview size that is closest to the viewfinder height.
1459        List<Size> sizes = mParameters.getSupportedPreviewSizes();
1460        Size optimalSize = getOptimalPreviewSize(sizes);
1461        if (optimalSize != null) {
1462            mParameters.setPreviewSize(optimalSize.width, optimalSize.height);
1463        }
1464
1465        // Set picture size.
1466        String pictureSize = mPreferences.getString(
1467                CameraSettings.KEY_PICTURE_SIZE, null);
1468        if (pictureSize == null) {
1469            CameraSettings.initialCameraPictureSize(this, mParameters);
1470        } else {
1471            List<Size> supported = mParameters.getSupportedPictureSizes();
1472            CameraSettings.setCameraPictureSize(
1473                    pictureSize, supported, mParameters);
1474        }
1475
1476        // Set JPEG quality.
1477        String jpegQuality = mPreferences.getString(
1478                CameraSettings.KEY_JPEG_QUALITY,
1479                getString(R.string.pref_camera_jpegquality_default));
1480        mParameters.setJpegQuality(Integer.parseInt(jpegQuality));
1481
1482        // For the following settings, we need to check if the settings are
1483        // still supported by latest driver, if not, ignore the settings.
1484
1485        // Set flash mode.
1486        String flashMode = mPreferences.getString(
1487                CameraSettings.KEY_FLASH_MODE,
1488                getString(R.string.pref_camera_flashmode_default));
1489        List<String> supportedFlash = mParameters.getSupportedFlashModes();
1490        if (isSupported(flashMode, supportedFlash)) {
1491            mParameters.setFlashMode(flashMode);
1492        } else {
1493            // If the current flashMode is not support, show the
1494            // FLASH_MODE_OFF icon.
1495            flashMode = Parameters.FLASH_MODE_OFF;
1496        }
1497
1498        // We post the runner because this function can be called from
1499        // non-UI thread (i.e., startPreviewThread).
1500        final String finalFlashMode = flashMode;
1501        mHandler.post(new Runnable() {
1502            public void run() {
1503                mFlashIndicator.setMode(finalFlashMode);
1504            }
1505        });
1506
1507        // Set white balance parameter.
1508        String whiteBalance = mPreferences.getString(
1509                CameraSettings.KEY_WHITE_BALANCE,
1510                getString(R.string.pref_camera_whitebalance_default));
1511        if (isSupported(whiteBalance, mParameters.getSupportedWhiteBalance())) {
1512            mParameters.setWhiteBalance(whiteBalance);
1513        }
1514
1515        // Set color effect parameter.
1516        String colorEffect = mPreferences.getString(
1517                CameraSettings.KEY_COLOR_EFFECT,
1518                getString(R.string.pref_camera_coloreffect_default));
1519        if (isSupported(colorEffect, mParameters.getSupportedColorEffects())) {
1520            mParameters.setColorEffect(colorEffect);
1521        }
1522
1523        // Set scene mode.
1524        String sceneMode = mPreferences.getString(
1525                CameraSettings.KEY_SCENE_MODE,
1526                getString(R.string.pref_camera_scenemode_default));
1527        if (isSupported(sceneMode, mParameters.getSupportedSceneModes())) {
1528            mParameters.setSceneMode(sceneMode);
1529        }
1530
1531        // Set focus mode.
1532        mFocusMode = mPreferences.getString(
1533                CameraSettings.KEY_FOCUS_MODE,
1534                getString(R.string.pref_camera_focusmode_default));
1535        if (isSupported(mFocusMode, mParameters.getSupportedFocusModes())) {
1536            mParameters.setFocusMode(mFocusMode);
1537        }
1538
1539        mCameraDevice.setParameters(mParameters);
1540    }
1541
1542    private void gotoGallery() {
1543        MenuHelper.gotoCameraImageGallery(this);
1544    }
1545
1546    private void viewLastImage() {
1547        if (mThumbController.isUriValid()) {
1548            Uri targetUri = mThumbController.getUri();
1549            targetUri = targetUri.buildUpon().appendQueryParameter(
1550                    "bucketId", ImageManager.CAMERA_IMAGE_BUCKET_ID).build();
1551            Intent intent = new Intent(this, ReviewImage.class);
1552            intent.setData(targetUri);
1553            intent.putExtra(MediaStore.EXTRA_FULL_SCREEN, true);
1554            intent.putExtra(MediaStore.EXTRA_SHOW_ACTION_ICONS, true);
1555            intent.putExtra("com.android.camera.ReviewMode", true);
1556            try {
1557                startActivity(intent);
1558            } catch (ActivityNotFoundException ex) {
1559                Log.e(TAG, "review image fail", ex);
1560            }
1561        } else {
1562            Log.e(TAG, "Can't view last image.");
1563        }
1564    }
1565
1566    private void startReceivingLocationUpdates() {
1567        if (mLocationManager != null) {
1568            try {
1569                mLocationManager.requestLocationUpdates(
1570                        LocationManager.NETWORK_PROVIDER,
1571                        1000,
1572                        0F,
1573                        mLocationListeners[1]);
1574            } catch (java.lang.SecurityException ex) {
1575                Log.i(TAG, "fail to request location update, ignore", ex);
1576            } catch (IllegalArgumentException ex) {
1577                Log.d(TAG, "provider does not exist " + ex.getMessage());
1578            }
1579            try {
1580                mLocationManager.requestLocationUpdates(
1581                        LocationManager.GPS_PROVIDER,
1582                        1000,
1583                        0F,
1584                        mLocationListeners[0]);
1585            } catch (java.lang.SecurityException ex) {
1586                Log.i(TAG, "fail to request location update, ignore", ex);
1587            } catch (IllegalArgumentException ex) {
1588                Log.d(TAG, "provider does not exist " + ex.getMessage());
1589            }
1590        }
1591    }
1592
1593    private void stopReceivingLocationUpdates() {
1594        if (mLocationManager != null) {
1595            for (int i = 0; i < mLocationListeners.length; i++) {
1596                try {
1597                    mLocationManager.removeUpdates(mLocationListeners[i]);
1598                } catch (Exception ex) {
1599                    Log.i(TAG, "fail to remove location listners, ignore", ex);
1600                }
1601            }
1602        }
1603    }
1604
1605    private Location getCurrentLocation() {
1606        // go in best to worst order
1607        for (int i = 0; i < mLocationListeners.length; i++) {
1608            Location l = mLocationListeners[i].current();
1609            if (l != null) return l;
1610        }
1611        return null;
1612    }
1613
1614    private boolean isCameraIdle() {
1615        return mStatus == IDLE && mFocusState == FOCUS_NOT_STARTED;
1616    }
1617
1618    private boolean isImageCaptureIntent() {
1619        String action = getIntent().getAction();
1620        return (MediaStore.ACTION_IMAGE_CAPTURE.equals(action));
1621    }
1622
1623    private void setupCaptureParams() {
1624        Bundle myExtras = getIntent().getExtras();
1625        if (myExtras != null) {
1626            mSaveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT);
1627            mCropValue = myExtras.getString("crop");
1628        }
1629    }
1630
1631    private void showPostCaptureAlert() {
1632        if (mIsImageCaptureIntent) {
1633            findViewById(R.id.shutter_button).setVisibility(View.INVISIBLE);
1634            int[] pickIds = {R.id.btn_retake, R.id.btn_done};
1635            for (int id : pickIds) {
1636                View button = findViewById(id);
1637                ((View) button.getParent()).setVisibility(View.VISIBLE);
1638            }
1639        }
1640    }
1641
1642    private void hidePostCaptureAlert() {
1643        if (mIsImageCaptureIntent) {
1644            findViewById(R.id.shutter_button).setVisibility(View.VISIBLE);
1645            int[] pickIds = {R.id.btn_retake, R.id.btn_done};
1646            for (int id : pickIds) {
1647                View button = findViewById(id);
1648                ((View) button.getParent()).setVisibility(View.GONE);
1649            }
1650        }
1651    }
1652
1653    private int calculatePicturesRemaining() {
1654        mPicturesRemaining = MenuHelper.calculatePicturesRemaining();
1655        return mPicturesRemaining;
1656    }
1657
1658    @Override
1659    public boolean onPrepareOptionsMenu(Menu menu) {
1660        super.onPrepareOptionsMenu(menu);
1661        // Only show the menu when camera is idle.
1662        for (int i = 0; i < menu.size(); i++) {
1663            menu.getItem(i).setVisible(isCameraIdle());
1664        }
1665
1666        return true;
1667    }
1668
1669    @Override
1670    public boolean onCreateOptionsMenu(Menu menu) {
1671        super.onCreateOptionsMenu(menu);
1672
1673        if (mIsImageCaptureIntent) {
1674            // No options menu for attach mode.
1675            return false;
1676        } else {
1677            addBaseMenuItems(menu);
1678        }
1679        return true;
1680    }
1681
1682    private void addBaseMenuItems(Menu menu) {
1683        MenuItem gallery = menu.add(Menu.NONE, Menu.NONE,
1684                MenuHelper.POSITION_GOTO_GALLERY,
1685                R.string.camera_gallery_photos_text)
1686                .setOnMenuItemClickListener(new OnMenuItemClickListener() {
1687            public boolean onMenuItemClick(MenuItem item) {
1688                gotoGallery();
1689                return true;
1690            }
1691        });
1692        gallery.setIcon(android.R.drawable.ic_menu_gallery);
1693        mGalleryItems.add(gallery);
1694
1695        MenuItem item = menu.add(Menu.NONE, Menu.NONE,
1696                MenuHelper.POSITION_CAMERA_SETTING, R.string.settings)
1697                .setOnMenuItemClickListener(new OnMenuItemClickListener() {
1698            public boolean onMenuItemClick(MenuItem item) {
1699                showOnScreenSettings();
1700                return true;
1701            }
1702        });
1703        item.setIcon(android.R.drawable.ic_menu_preferences);
1704    }
1705
1706    public boolean onSwitchChanged(Switcher source, boolean onOff) {
1707        if (onOff == SWITCH_VIDEO) {
1708            if (!isCameraIdle()) return false;
1709            MenuHelper.gotoVideoMode(this);
1710            finish();
1711        }
1712        return true;
1713    }
1714
1715    public void onSharedPreferenceChanged(
1716            SharedPreferences preferences, String key) {
1717        // ignore the events after "onPause()"
1718        if (mPausing) return;
1719
1720        if (CameraSettings.KEY_RECORD_LOCATION.equals(key)) {
1721            mRecordLocation = preferences.getBoolean(key, false);
1722            if (mRecordLocation) {
1723                startReceivingLocationUpdates();
1724            } else {
1725                stopReceivingLocationUpdates();
1726            }
1727        } else {
1728            // All preferences except RECORD_LOCATION are camera parameters.
1729            // Call setCameraParameters to take effect now.
1730            setCameraParameters();
1731        }
1732    }
1733
1734    @Override
1735    public void onUserInteraction() {
1736        super.onUserInteraction();
1737        keepScreenOnAwhile();
1738    }
1739
1740    private void resetScreenOn() {
1741        mHandler.removeMessages(CLEAR_SCREEN_DELAY);
1742        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1743    }
1744
1745    private void keepScreenOnAwhile() {
1746        mHandler.removeMessages(CLEAR_SCREEN_DELAY);
1747        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1748        mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY);
1749    }
1750}
1751
1752class FocusRectangle extends View {
1753
1754    @SuppressWarnings("unused")
1755    private static final String TAG = "FocusRectangle";
1756
1757    public FocusRectangle(Context context, AttributeSet attrs) {
1758        super(context, attrs);
1759    }
1760
1761    private void setDrawable(int resid) {
1762        setBackgroundDrawable(getResources().getDrawable(resid));
1763    }
1764
1765    public void showStart() {
1766        setDrawable(R.drawable.focus_focusing);
1767    }
1768
1769    public void showSuccess() {
1770        setDrawable(R.drawable.focus_focused);
1771    }
1772
1773    public void showFail() {
1774        setDrawable(R.drawable.focus_focus_failed);
1775    }
1776
1777    public void clear() {
1778        setBackgroundDrawable(null);
1779    }
1780}
1781