PanoramaActivity.java revision d991766dc3bcc03a02c6648e2cfd54ee4f8cbd9e
1/*
2 * Copyright (C) 2011 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.panorama;
18
19import com.android.camera.ActivityBase;
20import com.android.camera.CameraDisabledException;
21import com.android.camera.CameraHardwareException;
22import com.android.camera.CameraHolder;
23import com.android.camera.Exif;
24import com.android.camera.MenuHelper;
25import com.android.camera.ModePicker;
26import com.android.camera.OnClickAttr;
27import com.android.camera.R;
28import com.android.camera.ShutterButton;
29import com.android.camera.Storage;
30import com.android.camera.Thumbnail;
31import com.android.camera.Util;
32import com.android.camera.ui.RotateImageView;
33import com.android.camera.ui.SharePopup;
34
35import android.app.AlertDialog;
36import android.app.ProgressDialog;
37import android.content.ContentResolver;
38import android.content.Context;
39import android.content.DialogInterface;
40import android.content.res.Resources;
41import android.graphics.Bitmap;
42import android.graphics.BitmapFactory;
43import android.graphics.ImageFormat;
44import android.graphics.PixelFormat;
45import android.graphics.Rect;
46import android.graphics.SurfaceTexture;
47import android.graphics.YuvImage;
48import android.hardware.Camera;
49import android.hardware.Camera.Parameters;
50import android.hardware.Camera.Size;
51import android.hardware.Sensor;
52import android.hardware.SensorManager;
53import android.net.Uri;
54import android.os.Bundle;
55import android.os.Handler;
56import android.os.Message;
57import android.util.Log;
58import android.view.Gravity;
59import android.view.Menu;
60import android.view.OrientationEventListener;
61import android.view.View;
62import android.view.Window;
63import android.view.WindowManager;
64import android.widget.ImageView;
65import android.widget.TextView;
66
67import java.io.ByteArrayOutputStream;
68import java.io.File;
69import java.util.List;
70
71/**
72 * Activity to handle panorama capturing.
73 */
74public class PanoramaActivity extends ActivityBase implements
75        ModePicker.OnModeChangeListener, SurfaceTexture.OnFrameAvailableListener,
76        ShutterButton.OnShutterButtonListener,
77        MosaicRendererSurfaceViewRenderer.MosaicSurfaceCreateListener {
78    public static final int DEFAULT_SWEEP_ANGLE = 160;
79    public static final int DEFAULT_BLEND_MODE = Mosaic.BLENDTYPE_HORIZONTAL;
80    public static final int DEFAULT_CAPTURE_PIXELS = 960 * 720;
81
82    private static final int MSG_LOW_RES_FINAL_MOSAIC_READY = 1;
83    private static final int MSG_RESET_TO_PREVIEW_WITH_THUMBNAIL = 2;
84    private static final int MSG_GENERATE_FINAL_MOSAIC_ERROR = 3;
85    private static final int MSG_RESET_TO_PREVIEW = 4;
86
87    private static final String TAG = "PanoramaActivity";
88    private static final int PREVIEW_STOPPED = 0;
89    private static final int PREVIEW_ACTIVE = 1;
90    private static final int CAPTURE_STATE_VIEWFINDER = 0;
91    private static final int CAPTURE_STATE_MOSAIC = 1;
92
93    // Speed is in unit of deg/sec
94    private static final float PANNING_SPEED_THRESHOLD = 20f;
95
96    // Ratio of nanosecond to second
97    private static final float NS2S = 1.0f / 1000000000.0f;
98
99    private boolean mPausing;
100
101    private View mPanoLayout;
102    private View mCaptureLayout;
103    private View mReviewLayout;
104    private ImageView mReview;
105    private TextView mCaptureIndicator;
106    private PanoProgressBar mPanoProgressBar;
107    private PanoProgressBar mSavingProgressBar;
108    private View mFastIndicationBorder;
109    private View mLeftIndicator;
110    private View mRightIndicator;
111    private MosaicRendererSurfaceView mMosaicView;
112    private TextView mTooFastPrompt;
113    private ShutterButton mShutterButton;
114    private Object mWaitObject = new Object();
115
116    private String mPreparePreviewString;
117    private AlertDialog mAlertDialog;
118    private ProgressDialog mProgressDialog;
119    private String mDialogTitle;
120    private String mDialogOk;
121
122    private int mIndicatorColor;
123    private int mIndicatorColorFast;
124
125    private float mCompassValueX;
126    private float mCompassValueY;
127    private float mCompassValueXStart;
128    private float mCompassValueYStart;
129    private float mCompassValueXStartBuffer;
130    private float mCompassValueYStartBuffer;
131    private int mCompassThreshold;
132    private int mTraversedAngleX;
133    private int mTraversedAngleY;
134    private long mTimestamp;
135    // Control variables for the terminate condition.
136    private int mMinAngleX;
137    private int mMaxAngleX;
138    private int mMinAngleY;
139    private int mMaxAngleY;
140
141    private RotateImageView mThumbnailView;
142    private Thumbnail mThumbnail;
143    private SharePopup mSharePopup;
144
145    private int mPreviewWidth;
146    private int mPreviewHeight;
147    private Camera mCameraDevice;
148    private int mCameraState;
149    private int mCaptureState;
150    private SensorManager mSensorManager;
151    private Sensor mSensor;
152    private ModePicker mModePicker;
153    private MosaicFrameProcessor mMosaicFrameProcessor;
154    private long mTimeTaken;
155    private Handler mMainHandler;
156    private SurfaceTexture mSurfaceTexture;
157    private boolean mThreadRunning;
158    private boolean mCancelComputation;
159    private float[] mTransformMatrix;
160    private float mHorizontalViewAngle;
161
162    // Prefer FOCUS_MODE_INFINITY to FOCUS_MODE_CONTINUOUS_VIDEO because of
163    // getting a better image quality by the former.
164    private String mTargetFocusMode = Parameters.FOCUS_MODE_INFINITY;
165
166    private PanoOrientationEventListener mOrientationEventListener;
167    // The value could be 0, 90, 180, 270 for the 4 different orientations measured in clockwise
168    // respectively.
169    private int mDeviceOrientation;
170    private int mOrientationCompensation;
171
172    private class MosaicJpeg {
173        public MosaicJpeg(byte[] data, int width, int height) {
174            this.data = data;
175            this.width = width;
176            this.height = height;
177            this.isValid = true;
178        }
179
180        public MosaicJpeg() {
181            this.data = null;
182            this.width = 0;
183            this.height = 0;
184            this.isValid = false;
185        }
186
187        public final byte[] data;
188        public final int width;
189        public final int height;
190        public final boolean isValid;
191    }
192
193    public static int roundOrientation(int orientation) {
194        return ((orientation + 45) / 90 * 90) % 360;
195    }
196
197    private class PanoOrientationEventListener extends OrientationEventListener {
198        public PanoOrientationEventListener(Context context) {
199            super(context);
200        }
201
202        @Override
203        public void onOrientationChanged(int orientation) {
204            // We keep the last known orientation. So if the user first orient
205            // the camera then point the camera to floor or sky, we still have
206            // the correct orientation.
207            if (orientation == ORIENTATION_UNKNOWN) return;
208            mDeviceOrientation = roundOrientation(orientation);
209            // When the screen is unlocked, display rotation may change. Always
210            // calculate the up-to-date orientationCompensation.
211            int orientationCompensation = mDeviceOrientation
212                    + Util.getDisplayRotation(PanoramaActivity.this);
213            if (mOrientationCompensation != orientationCompensation) {
214                mOrientationCompensation = orientationCompensation;
215                setOrientationIndicator(mOrientationCompensation);
216            }
217        }
218    }
219
220    private void setOrientationIndicator(int degree) {
221        if (mSharePopup != null) mSharePopup.setOrientation(degree);
222    }
223
224    @Override
225    public boolean onCreateOptionsMenu(Menu menu) {
226        super.onCreateOptionsMenu(menu);
227
228        addBaseMenuItems(menu);
229        return true;
230    }
231
232    private void addBaseMenuItems(Menu menu) {
233        MenuHelper.addSwitchModeMenuItem(menu, ModePicker.MODE_CAMERA, new Runnable() {
234            public void run() {
235                switchToOtherMode(ModePicker.MODE_CAMERA);
236            }
237        });
238        MenuHelper.addSwitchModeMenuItem(menu, ModePicker.MODE_VIDEO, new Runnable() {
239            public void run() {
240                switchToOtherMode(ModePicker.MODE_VIDEO);
241            }
242        });
243    }
244
245    @Override
246    public void onCreate(Bundle icicle) {
247        super.onCreate(icicle);
248
249        Window window = getWindow();
250        window.setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
251                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
252        Util.enterLightsOutMode(window);
253        Util.initializeScreenBrightness(window, getContentResolver());
254
255        createContentView();
256
257        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
258        mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
259        if (mSensor == null) {
260            mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
261        }
262
263        mOrientationEventListener = new PanoOrientationEventListener(this);
264
265        mTransformMatrix = new float[16];
266
267        mPreparePreviewString =
268                getResources().getString(R.string.pano_dialog_prepare_preview);
269        mDialogTitle = getResources().getString(R.string.pano_dialog_title);
270        mDialogOk = getResources().getString(R.string.dialog_ok);
271
272        mMainHandler = new Handler() {
273            @Override
274            public void handleMessage(Message msg) {
275                switch (msg.what) {
276                    case MSG_LOW_RES_FINAL_MOSAIC_READY:
277                        onBackgroundThreadFinished();
278                        showFinalMosaic((Bitmap) msg.obj);
279                        saveHighResMosaic();
280                        break;
281                    case MSG_RESET_TO_PREVIEW_WITH_THUMBNAIL:
282                        onBackgroundThreadFinished();
283                        // Set the thumbnail bitmap here because mThumbnailView must be accessed
284                        // from the UI thread.
285                        updateThumbnailButton();
286
287                        // Share popup may still have the reference to the old thumbnail. Clear it.
288                        mSharePopup = null;
289                        resetToPreview();
290                        break;
291                    case MSG_GENERATE_FINAL_MOSAIC_ERROR:
292                        onBackgroundThreadFinished();
293                        if (mPausing) {
294                            resetToPreview();
295                        } else {
296                            mAlertDialog.show();
297                        }
298                        break;
299                    case MSG_RESET_TO_PREVIEW:
300                        onBackgroundThreadFinished();
301                        resetToPreview();
302                }
303                clearMosaicFrameProcessorIfNeeded();
304            }
305        };
306
307        mAlertDialog = (new AlertDialog.Builder(this))
308                .setTitle(mDialogTitle)
309                .setMessage(R.string.pano_dialog_panorama_failed)
310                .create();
311        mAlertDialog.setCancelable(false);
312        mAlertDialog.setButton(DialogInterface.BUTTON_POSITIVE, mDialogOk,
313                new DialogInterface.OnClickListener() {
314                    @Override
315                    public void onClick(DialogInterface dialog, int which) {
316                        dialog.dismiss();
317                        resetToPreview();
318                    }
319                });
320    }
321
322    @Override
323    public void onStart() {
324        super.onStart();
325        updateThumbnailButton();
326    }
327
328    private void setupCamera() {
329        openCamera();
330        Parameters parameters = mCameraDevice.getParameters();
331        setupCaptureParams(parameters);
332        configureCamera(parameters);
333    }
334
335    private void releaseCamera() {
336        if (mCameraDevice != null) {
337            mCameraDevice.setPreviewCallbackWithBuffer(null);
338            CameraHolder.instance().release();
339            mCameraDevice = null;
340            mCameraState = PREVIEW_STOPPED;
341        }
342    }
343
344    private void openCamera() {
345        try {
346            mCameraDevice = Util.openCamera(this, CameraHolder.instance().getBackCameraId());
347        } catch (CameraHardwareException e) {
348            Util.showErrorAndFinish(this, R.string.cannot_connect_camera);
349            return;
350        } catch (CameraDisabledException e) {
351            Util.showErrorAndFinish(this, R.string.camera_disabled);
352            return;
353        }
354    }
355
356    private boolean findBestPreviewSize(List<Size> supportedSizes, boolean need4To3,
357            boolean needSmaller) {
358        int pixelsDiff = DEFAULT_CAPTURE_PIXELS;
359        boolean hasFound = false;
360        for (Size size : supportedSizes) {
361            int h = size.height;
362            int w = size.width;
363            // we only want 4:3 format.
364            int d = DEFAULT_CAPTURE_PIXELS - h * w;
365            if (needSmaller && d < 0) { // no bigger preview than 960x720.
366                continue;
367            }
368            if (need4To3 && (h * 4 != w * 3)) {
369                continue;
370            }
371            d = Math.abs(d);
372            if (d < pixelsDiff) {
373                mPreviewWidth = w;
374                mPreviewHeight = h;
375                pixelsDiff = d;
376                hasFound = true;
377            }
378        }
379        return hasFound;
380    }
381
382    private void setupCaptureParams(Parameters parameters) {
383        List<Size> supportedSizes = parameters.getSupportedPreviewSizes();
384        if (!findBestPreviewSize(supportedSizes, true, true)) {
385            Log.w(TAG, "No 4:3 ratio preview size supported.");
386            if (!findBestPreviewSize(supportedSizes, false, true)) {
387                Log.w(TAG, "Can't find a supported preview size smaller than 960x720.");
388                findBestPreviewSize(supportedSizes, false, false);
389            }
390        }
391        Log.v(TAG, "preview h = " + mPreviewHeight + " , w = " + mPreviewWidth);
392        parameters.setPreviewSize(mPreviewWidth, mPreviewHeight);
393
394        List<int[]> frameRates = parameters.getSupportedPreviewFpsRange();
395        int last = frameRates.size() - 1;
396        int minFps = (frameRates.get(last))[Parameters.PREVIEW_FPS_MIN_INDEX];
397        int maxFps = (frameRates.get(last))[Parameters.PREVIEW_FPS_MAX_INDEX];
398        parameters.setPreviewFpsRange(minFps, maxFps);
399        Log.v(TAG, "preview fps: " + minFps + ", " + maxFps);
400
401        List<String> supportedFocusModes = parameters.getSupportedFocusModes();
402        if (supportedFocusModes.indexOf(mTargetFocusMode) >= 0) {
403            parameters.setFocusMode(mTargetFocusMode);
404        } else {
405            // Use the default focus mode and log a message
406            Log.w(TAG, "Cannot set the focus mode to " + mTargetFocusMode +
407                  " becuase the mode is not supported.");
408        }
409
410        parameters.setRecordingHint(false);
411
412        mHorizontalViewAngle = (((mDeviceOrientation / 90) % 2) == 0) ?
413                parameters.getHorizontalViewAngle() : parameters.getVerticalViewAngle();
414    }
415
416    public int getPreviewBufSize() {
417        PixelFormat pixelInfo = new PixelFormat();
418        PixelFormat.getPixelFormatInfo(mCameraDevice.getParameters().getPreviewFormat(), pixelInfo);
419        // TODO: remove this extra 32 byte after the driver bug is fixed.
420        return (mPreviewWidth * mPreviewHeight * pixelInfo.bitsPerPixel / 8) + 32;
421    }
422
423    private void configureCamera(Parameters parameters) {
424        mCameraDevice.setParameters(parameters);
425    }
426
427    private boolean switchToOtherMode(int mode) {
428        if (isFinishing()) {
429            return false;
430        }
431        MenuHelper.gotoMode(mode, this);
432        finish();
433        return true;
434    }
435
436    public boolean onModeChanged(int mode) {
437        if (mode != ModePicker.MODE_PANORAMA) {
438            return switchToOtherMode(mode);
439        } else {
440            return true;
441        }
442    }
443
444    @Override
445    public void onMosaicSurfaceChanged() {
446        runOnUiThread(new Runnable() {
447            @Override
448            public void run() {
449                if (!mPausing) {
450                    startCameraPreview();
451                }
452            }
453        });
454    }
455
456    @Override
457    public void onMosaicSurfaceCreated(final int textureID) {
458        runOnUiThread(new Runnable() {
459            @Override
460            public void run() {
461                if (mSurfaceTexture != null) {
462                    mSurfaceTexture.release();
463                }
464                mSurfaceTexture = new SurfaceTexture(textureID);
465                if (!mPausing) {
466                    mSurfaceTexture.setOnFrameAvailableListener(PanoramaActivity.this);
467                }
468            }
469        });
470    }
471
472    public void runViewFinder() {
473        mMosaicView.setWarping(false);
474        // Call preprocess to render it to low-res and high-res RGB textures.
475        mMosaicView.preprocess(mTransformMatrix);
476        mMosaicView.setReady();
477        mMosaicView.requestRender();
478    }
479
480    public void runMosaicCapture() {
481        mMosaicView.setWarping(true);
482        // Call preprocess to render it to low-res and high-res RGB textures.
483        mMosaicView.preprocess(mTransformMatrix);
484        // Lock the conditional variable to ensure the order of transferGPUtoCPU and
485        // mMosaicFrame.processFrame().
486        mMosaicView.lockPreviewReadyFlag();
487        // Now, transfer the textures from GPU to CPU memory for processing
488        mMosaicView.transferGPUtoCPU();
489        // Wait on the condition variable (will be opened when GPU->CPU transfer is done).
490        mMosaicView.waitUntilPreviewReady();
491        mMosaicFrameProcessor.processFrame();
492    }
493
494    public synchronized void onFrameAvailable(SurfaceTexture surface) {
495        /* This function may be called by some random thread,
496         * so let's be safe and use synchronize. No OpenGL calls can be done here.
497         */
498        // Updating the texture should be done in the GL thread which mMosaicView is attached.
499        mMosaicView.queueEvent(new Runnable() {
500            @Override
501            public void run() {
502                mSurfaceTexture.updateTexImage();
503                mSurfaceTexture.getTransformMatrix(mTransformMatrix);
504            }
505        });
506        // Update the transformation matrix for mosaic pre-process.
507        if (mCaptureState == CAPTURE_STATE_VIEWFINDER) {
508            runViewFinder();
509        } else {
510            runMosaicCapture();
511        }
512    }
513
514    private void hideDirectionIndicators() {
515        mLeftIndicator.setVisibility(View.GONE);
516        mRightIndicator.setVisibility(View.GONE);
517    }
518
519    private void showDirectionIndicators(int direction) {
520        switch (direction) {
521            case PanoProgressBar.DIRECTION_NONE:
522                mLeftIndicator.setVisibility(View.VISIBLE);
523                mRightIndicator.setVisibility(View.VISIBLE);
524                break;
525            case PanoProgressBar.DIRECTION_LEFT:
526                mLeftIndicator.setVisibility(View.VISIBLE);
527                mRightIndicator.setVisibility(View.GONE);
528                break;
529            case PanoProgressBar.DIRECTION_RIGHT:
530                mLeftIndicator.setVisibility(View.GONE);
531                mRightIndicator.setVisibility(View.VISIBLE);
532                break;
533        }
534    }
535
536    public void startCapture() {
537        // Reset values so we can do this again.
538        mCancelComputation = false;
539        mTimeTaken = System.currentTimeMillis();
540        mCaptureState = CAPTURE_STATE_MOSAIC;
541        mShutterButton.setBackgroundResource(R.drawable.btn_shutter_pan_recording);
542        mCaptureIndicator.setVisibility(View.VISIBLE);
543        showDirectionIndicators(PanoProgressBar.DIRECTION_NONE);
544
545        mCompassValueXStart = mCompassValueXStartBuffer;
546        mCompassValueYStart = mCompassValueYStartBuffer;
547        mMinAngleX = 0;
548        mMaxAngleX = 0;
549        mMinAngleY = 0;
550        mMaxAngleY = 0;
551        mTimestamp = 0;
552
553        mMosaicFrameProcessor.setProgressListener(new MosaicFrameProcessor.ProgressListener() {
554            @Override
555            public void onProgress(boolean isFinished, float panningRateX, float panningRateY,
556                    float progressX, float progressY) {
557                if (isFinished
558                        || (mMaxAngleX - mMinAngleX >= DEFAULT_SWEEP_ANGLE)
559                        || (mMaxAngleY - mMinAngleY >= DEFAULT_SWEEP_ANGLE)) {
560                    stopCapture(false);
561                } else {
562                    updateProgress(panningRateX, progressX, progressY);
563                }
564            }
565        });
566
567        if (mModePicker != null) mModePicker.setEnabled(false);
568
569        mPanoProgressBar.reset();
570        // TODO: calculate the indicator width according to different devices to reflect the actual
571        // angle of view of the camera device.
572        mPanoProgressBar.setIndicatorWidth(20);
573        mPanoProgressBar.setMaxProgress(DEFAULT_SWEEP_ANGLE);
574        mPanoProgressBar.setVisibility(View.VISIBLE);
575    }
576
577    private void stopCapture(boolean aborted) {
578        mCaptureState = CAPTURE_STATE_VIEWFINDER;
579        mCaptureIndicator.setVisibility(View.GONE);
580        hideTooFastIndication();
581        hideDirectionIndicators();
582
583        mMosaicFrameProcessor.setProgressListener(null);
584        stopCameraPreview();
585
586        mSurfaceTexture.setOnFrameAvailableListener(null);
587
588        if (!aborted && !mThreadRunning) {
589            showDialog(mPreparePreviewString);
590            runBackgroundThread(new Thread() {
591                @Override
592                public void run() {
593                    MosaicJpeg jpeg = generateFinalMosaic(false);
594
595                    if (jpeg != null && jpeg.isValid) {
596                        Bitmap bitmap = null;
597                        bitmap = BitmapFactory.decodeByteArray(jpeg.data, 0, jpeg.data.length);
598                        mMainHandler.sendMessage(mMainHandler.obtainMessage(
599                                MSG_LOW_RES_FINAL_MOSAIC_READY, bitmap));
600                    } else {
601                        mMainHandler.sendMessage(mMainHandler.obtainMessage(
602                                MSG_RESET_TO_PREVIEW));
603                    }
604                }
605            });
606        }
607        // do we have to wait for the thread to complete before enabling this?
608        if (mModePicker != null) mModePicker.setEnabled(true);
609    }
610
611    private void showTooFastIndication() {
612        mTooFastPrompt.setVisibility(View.VISIBLE);
613        mFastIndicationBorder.setVisibility(View.VISIBLE);
614        mPanoProgressBar.setIndicatorColor(mIndicatorColorFast);
615        mLeftIndicator.setEnabled(true);
616        mRightIndicator.setEnabled(true);
617    }
618
619    private void hideTooFastIndication() {
620        mTooFastPrompt.setVisibility(View.GONE);
621        mFastIndicationBorder.setVisibility(View.GONE);
622        mPanoProgressBar.setIndicatorColor(mIndicatorColor);
623        mLeftIndicator.setEnabled(false);
624        mRightIndicator.setEnabled(false);
625    }
626
627    private void updateProgress(float panningRate, float progressX, float progressY) {
628        mMosaicView.setReady();
629        mMosaicView.requestRender();
630
631        // TODO: Now we just display warning message by the panning speed.
632        // Since we only support horizontal panning, we should display a warning message
633        // in UI when there're significant vertical movements.
634        if (Math.abs(panningRate * mHorizontalViewAngle) > PANNING_SPEED_THRESHOLD) {
635            showTooFastIndication();
636        } else {
637            hideTooFastIndication();
638        }
639        mPanoProgressBar.setProgress((int) (progressX * mHorizontalViewAngle));
640    }
641
642    private void createContentView() {
643        setContentView(R.layout.panorama);
644
645        mCaptureState = CAPTURE_STATE_VIEWFINDER;
646
647        Resources appRes = getResources();
648
649        mCaptureLayout = (View) findViewById(R.id.pano_capture_layout);
650        mPanoProgressBar = (PanoProgressBar) findViewById(R.id.pano_pan_progress_bar);
651        mPanoProgressBar.setBackgroundColor(appRes.getColor(R.color.pano_progress_empty));
652        mPanoProgressBar.setDoneColor(appRes.getColor(R.color.pano_progress_done));
653        mIndicatorColor = appRes.getColor(R.color.pano_progress_indication);
654        mIndicatorColorFast = appRes.getColor(R.color.pano_progress_indication_fast);
655        mPanoProgressBar.setIndicatorColor(mIndicatorColor);
656        mPanoProgressBar.setOnDirectionChangeListener(
657                new PanoProgressBar.OnDirectionChangeListener () {
658                    @Override
659                    public void onDirectionChange(int direction) {
660                        if (mCaptureState == CAPTURE_STATE_MOSAIC) {
661                            showDirectionIndicators(direction);
662                        }
663                    }
664                });
665
666        mLeftIndicator = (ImageView) findViewById(R.id.pano_pan_left_indicator);
667        mRightIndicator = (ImageView) findViewById(R.id.pano_pan_right_indicator);
668        mLeftIndicator.setEnabled(false);
669        mRightIndicator.setEnabled(false);
670        mTooFastPrompt = (TextView) findViewById(R.id.pano_capture_too_fast_textview);
671        mFastIndicationBorder = (View) findViewById(R.id.pano_speed_indication_border);
672
673        mSavingProgressBar = (PanoProgressBar) findViewById(R.id.pano_saving_progress_bar);
674        mSavingProgressBar.setIndicatorWidth(0);
675        mSavingProgressBar.setMaxProgress(100);
676        mSavingProgressBar.setBackgroundColor(appRes.getColor(R.color.pano_progress_empty));
677        mSavingProgressBar.setDoneColor(appRes.getColor(R.color.pano_progress_indication));
678
679        mCaptureIndicator = (TextView) findViewById(R.id.pano_capture_indicator);
680
681        mThumbnailView = (RotateImageView) findViewById(R.id.thumbnail);
682
683        mReviewLayout = (View) findViewById(R.id.pano_review_layout);
684        mReview = (ImageView) findViewById(R.id.pano_reviewarea);
685        mMosaicView = (MosaicRendererSurfaceView) findViewById(R.id.pano_renderer);
686        mMosaicView.getRenderer().setMosaicSurfaceCreateListener(this);
687
688        mModePicker = (ModePicker) findViewById(R.id.mode_picker);
689        mModePicker.setVisibility(View.VISIBLE);
690        mModePicker.setOnModeChangeListener(this);
691        mModePicker.setCurrentMode(ModePicker.MODE_PANORAMA);
692
693        mShutterButton = (ShutterButton) findViewById(R.id.shutter_button);
694        mShutterButton.setBackgroundResource(R.drawable.btn_shutter_pan);
695        mShutterButton.setOnShutterButtonListener(this);
696
697        mPanoLayout = findViewById(R.id.pano_layout);
698    }
699
700    @Override
701    public void onShutterButtonClick() {
702        // If mSurfaceTexture == null then GL setup is not finished yet.
703        // No buttons can be pressed.
704        if (mPausing || mThreadRunning || mSurfaceTexture == null) return;
705        // Since this button will stay on the screen when capturing, we need to check the state
706        // right now.
707        switch (mCaptureState) {
708            case CAPTURE_STATE_VIEWFINDER:
709                startCapture();
710                break;
711            case CAPTURE_STATE_MOSAIC:
712                stopCapture(false);
713        }
714    }
715
716    @Override
717    public void onShutterButtonFocus(boolean pressed) {
718    }
719
720    public void reportProgress() {
721        mSavingProgressBar.reset();
722        mSavingProgressBar.setRightIncreasing(true);
723        Thread t = new Thread() {
724            @Override
725            public void run() {
726                while (mThreadRunning) {
727                    final int progress = mMosaicFrameProcessor.reportProgress(
728                            true, mCancelComputation);
729
730                    try {
731                        synchronized (mWaitObject) {
732                            mWaitObject.wait(50);
733                        }
734                    } catch (InterruptedException e) {
735                        throw new RuntimeException("Panorama reportProgress failed", e);
736                    }
737                    // Update the progress bar
738                    runOnUiThread(new Runnable() {
739                        public void run() {
740                            mSavingProgressBar.setProgress(progress);
741                        }
742                    });
743                }
744            }
745        };
746        t.start();
747    }
748
749    private void updateThumbnailButton() {
750        // Update last image if URI is invalid and the storage is ready.
751        ContentResolver contentResolver = getContentResolver();
752        if ((mThumbnail == null || !Util.isUriValid(mThumbnail.getUri(), contentResolver))) {
753            mThumbnail = Thumbnail.getLastThumbnail(contentResolver);
754        }
755        if (mThumbnail != null) {
756            mThumbnailView.setBitmap(mThumbnail.getBitmap());
757        } else {
758            mThumbnailView.setBitmap(null);
759        }
760    }
761
762    public void saveHighResMosaic() {
763        runBackgroundThread(new Thread() {
764            @Override
765            public void run() {
766                MosaicJpeg jpeg = generateFinalMosaic(true);
767
768                if (jpeg == null) {  // Cancelled by user.
769                    mMainHandler.sendEmptyMessage(MSG_RESET_TO_PREVIEW);
770                } else if (!jpeg.isValid) {  // Error when generating mosaic.
771                    mMainHandler.sendEmptyMessage(MSG_GENERATE_FINAL_MOSAIC_ERROR);
772                } else {
773                    int orientation = Exif.getOrientation(jpeg.data);
774                    Uri uri = savePanorama(jpeg.data, jpeg.width, jpeg.height, orientation);
775                    if (uri != null) {
776                        // Create a thumbnail whose width is equal or bigger
777                        // than the entire screen.
778                        int ratio = (int) Math.ceil((double) jpeg.width /
779                                mPanoLayout.getWidth());
780                        int inSampleSize = Integer.highestOneBit(ratio);
781                        mThumbnail = Thumbnail.createThumbnail(
782                                jpeg.data, orientation, inSampleSize, uri);
783                    }
784                    mMainHandler.sendMessage(
785                            mMainHandler.obtainMessage(MSG_RESET_TO_PREVIEW_WITH_THUMBNAIL));
786                }
787            }
788        });
789        reportProgress();
790    }
791
792    private void showDialog(String str) {
793          mProgressDialog = new ProgressDialog(this);
794          mProgressDialog.setMessage(str);
795          mProgressDialog.show();
796    }
797
798    private void runBackgroundThread(Thread thread) {
799        mThreadRunning = true;
800        thread.start();
801    }
802
803    private void onBackgroundThreadFinished() {
804        mThreadRunning = false;
805        if (mProgressDialog != null) {
806            mProgressDialog.dismiss();
807            mProgressDialog = null;
808        }
809    }
810
811    private void cancelHighResComputation() {
812        mCancelComputation = true;
813        synchronized (mWaitObject) {
814            mWaitObject.notify();
815        }
816    }
817
818    @OnClickAttr
819    public void onCancelButtonClicked(View v) {
820        if (mPausing || mSurfaceTexture == null) return;
821        cancelHighResComputation();
822    }
823
824    @OnClickAttr
825    public void onThumbnailClicked(View v) {
826        if (mPausing || mThreadRunning || mSurfaceTexture == null) return;
827        showSharePopup();
828    }
829
830    private void showSharePopup() {
831        if (mThumbnail == null) return;
832        Uri uri = mThumbnail.getUri();
833        if (mSharePopup == null || !uri.equals(mSharePopup.getUri())) {
834            // The orientation compensation is set to 0 here because we only support landscape.
835            mSharePopup = new SharePopup(this, uri, mThumbnail.getBitmap(),
836                    mOrientationCompensation,
837                    findViewById(R.id.frame_layout));
838        }
839        mSharePopup.showAtLocation(mThumbnailView, Gravity.NO_GRAVITY, 0, 0);
840    }
841
842    private void reset() {
843        mCaptureState = CAPTURE_STATE_VIEWFINDER;
844
845        mReviewLayout.setVisibility(View.GONE);
846        mShutterButton.setBackgroundResource(R.drawable.btn_shutter_pan);
847        mPanoProgressBar.setVisibility(View.GONE);
848        mCaptureLayout.setVisibility(View.VISIBLE);
849        mMosaicFrameProcessor.reset();
850
851        mSurfaceTexture.setOnFrameAvailableListener(this);
852    }
853
854    private void resetToPreview() {
855        reset();
856        if (!mPausing) startCameraPreview();
857    }
858
859    private void showFinalMosaic(Bitmap bitmap) {
860        if (bitmap != null) {
861            mReview.setImageBitmap(bitmap);
862        }
863        mCaptureLayout.setVisibility(View.GONE);
864        mReviewLayout.setVisibility(View.VISIBLE);
865    }
866
867    private Uri savePanorama(byte[] jpegData, int width, int height, int orientation) {
868        if (jpegData != null) {
869            String imagePath = PanoUtil.createName(
870                    getResources().getString(R.string.pano_file_name_format), mTimeTaken);
871            return Storage.addImage(getContentResolver(), imagePath, mTimeTaken, null,
872                    orientation, jpegData, width, height);
873        }
874        return null;
875    }
876
877    private void clearMosaicFrameProcessorIfNeeded() {
878        if (!mPausing || mThreadRunning) return;
879        mMosaicFrameProcessor.clear();
880    }
881
882    private void initMosaicFrameProcessorIfNeeded() {
883        if (mPausing || mThreadRunning) return;
884        if (mMosaicFrameProcessor == null) {
885            // Start the activity for the first time.
886            mMosaicFrameProcessor = new MosaicFrameProcessor(
887                    mPreviewWidth, mPreviewHeight, getPreviewBufSize());
888        }
889        mMosaicFrameProcessor.initialize();
890    }
891
892    @Override
893    protected void onPause() {
894        super.onPause();
895
896        mPausing = true;
897        cancelHighResComputation();
898        // Stop the capturing first.
899        if (mCaptureState == CAPTURE_STATE_MOSAIC) {
900            stopCapture(true);
901            reset();
902        }
903        if (mSharePopup != null) mSharePopup.dismiss();
904
905        if (mThumbnail != null && !mThumbnail.fromFile()) {
906            mThumbnail.saveTo(new File(getFilesDir(), Thumbnail.LAST_THUMB_FILENAME));
907        }
908
909        releaseCamera();
910        mMosaicView.onPause();
911        clearMosaicFrameProcessorIfNeeded();
912        mOrientationEventListener.disable();
913        System.gc();
914    }
915
916    @Override
917    protected void onResume() {
918        super.onResume();
919
920        mPausing = false;
921        mOrientationEventListener.enable();
922
923        mCaptureState = CAPTURE_STATE_VIEWFINDER;
924        setupCamera();
925
926        // Camera must be initialized before MosaicFrameProcessor is initialized. The preview size
927        // has to be decided by camera device.
928        initMosaicFrameProcessorIfNeeded();
929        mMosaicView.onResume();
930    }
931
932    public MosaicJpeg generateFinalMosaic(boolean highRes) {
933        if (mMosaicFrameProcessor.createMosaic(highRes) == Mosaic.MOSAIC_RET_CANCELLED) {
934            return null;
935        }
936
937        byte[] imageData = mMosaicFrameProcessor.getFinalMosaicNV21();
938        if (imageData == null) {
939            Log.e(TAG, "getFinalMosaicNV21() returned null.");
940            return new MosaicJpeg();
941        }
942
943        int len = imageData.length - 8;
944        int width = (imageData[len + 0] << 24) + ((imageData[len + 1] & 0xFF) << 16)
945                + ((imageData[len + 2] & 0xFF) << 8) + (imageData[len + 3] & 0xFF);
946        int height = (imageData[len + 4] << 24) + ((imageData[len + 5] & 0xFF) << 16)
947                + ((imageData[len + 6] & 0xFF) << 8) + (imageData[len + 7] & 0xFF);
948        Log.v(TAG, "ImLength = " + (len) + ", W = " + width + ", H = " + height);
949
950        if (width <= 0 || height <= 0) {
951            // TODO: pop up a error meesage indicating that the final result is not generated.
952            Log.e(TAG, "width|height <= 0!!, len = " + (len) + ", W = " + width + ", H = " +
953                    height);
954            return new MosaicJpeg();
955        }
956
957        YuvImage yuvimage = new YuvImage(imageData, ImageFormat.NV21, width, height, null);
958        ByteArrayOutputStream out = new ByteArrayOutputStream();
959        yuvimage.compressToJpeg(new Rect(0, 0, width, height), 100, out);
960        try {
961            out.close();
962        } catch (Exception e) {
963            Log.e(TAG, "Exception in storing final mosaic", e);
964            return new MosaicJpeg();
965        }
966        return new MosaicJpeg(out.toByteArray(), width, height);
967    }
968
969    private void setPreviewTexture(SurfaceTexture surface) {
970        try {
971            mCameraDevice.setPreviewTexture(surface);
972        } catch (Throwable ex) {
973            releaseCamera();
974            throw new RuntimeException("setPreviewTexture failed", ex);
975        }
976    }
977
978    private void startCameraPreview() {
979        // If we're previewing already, stop the preview first (this will blank
980        // the screen).
981        if (mCameraState != PREVIEW_STOPPED) stopCameraPreview();
982
983        int orientation = Util.getDisplayOrientation(Util.getDisplayRotation(this),
984                CameraHolder.instance().getBackCameraId());
985        mCameraDevice.setDisplayOrientation(orientation);
986
987        setPreviewTexture(mSurfaceTexture);
988
989        try {
990            Log.v(TAG, "startPreview");
991            mCameraDevice.startPreview();
992        } catch (Throwable ex) {
993            releaseCamera();
994            throw new RuntimeException("startPreview failed", ex);
995        }
996        mCameraState = PREVIEW_ACTIVE;
997    }
998
999    private void stopCameraPreview() {
1000        if (mCameraDevice != null && mCameraState != PREVIEW_STOPPED) {
1001            Log.v(TAG, "stopPreview");
1002            mCameraDevice.stopPreview();
1003        }
1004        mCameraState = PREVIEW_STOPPED;
1005    }
1006}
1007