PhotoView.java revision dc10b30ba0366126ed1ad5133b36e97d76335049
1/*
2 * Copyright (C) 2010 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.gallery3d.ui;
18
19import android.content.Context;
20import android.graphics.Color;
21import android.graphics.Matrix;
22import android.graphics.Rect;
23import android.os.Build;
24import android.os.Message;
25import android.util.FloatMath;
26import android.view.MotionEvent;
27import android.view.View.MeasureSpec;
28import android.view.animation.AccelerateInterpolator;
29
30import com.android.gallery3d.R;
31import com.android.gallery3d.app.AbstractGalleryActivity;
32import com.android.gallery3d.common.ApiHelper;
33import com.android.gallery3d.common.Utils;
34import com.android.gallery3d.data.MediaItem;
35import com.android.gallery3d.data.MediaObject;
36import com.android.gallery3d.data.Path;
37import com.android.gallery3d.util.GalleryUtils;
38import com.android.gallery3d.util.RangeArray;
39
40public class PhotoView extends GLView {
41    @SuppressWarnings("unused")
42    private static final String TAG = "PhotoView";
43    private final int mPlaceholderColor;
44
45    public static final int INVALID_SIZE = -1;
46    public static final long INVALID_DATA_VERSION =
47            MediaObject.INVALID_DATA_VERSION;
48
49    public static class Size {
50        public int width;
51        public int height;
52    }
53
54    public interface Model extends TileImageView.Model {
55        public int getCurrentIndex();
56        public void moveTo(int index);
57
58        // Returns the size for the specified picture. If the size information is
59        // not avaiable, width = height = 0.
60        public void getImageSize(int offset, Size size);
61
62        // Returns the media item for the specified picture.
63        public MediaItem getMediaItem(int offset);
64
65        // Returns the rotation for the specified picture.
66        public int getImageRotation(int offset);
67
68        // This amends the getScreenNail() method of TileImageView.Model to get
69        // ScreenNail at previous (negative offset) or next (positive offset)
70        // positions. Returns null if the specified ScreenNail is unavailable.
71        public ScreenNail getScreenNail(int offset);
72
73        // Set this to true if we need the model to provide full images.
74        public void setNeedFullImage(boolean enabled);
75
76        // Returns true if the item is the Camera preview.
77        public boolean isCamera(int offset);
78
79        // Returns true if the item is the Panorama.
80        public boolean isPanorama(int offset);
81
82        // Returns true if the item uses a special panorama viewer
83        public boolean usePanoramaViewer(int offset);
84
85        // Returns true if the item is a static image that represents camera
86        // preview.
87        public boolean isStaticCamera(int offset);
88
89        // Returns true if the item is a Video.
90        public boolean isVideo(int offset);
91
92        // Returns true if the item can be deleted.
93        public boolean isDeletable(int offset);
94
95        public static final int LOADING_INIT = 0;
96        public static final int LOADING_COMPLETE = 1;
97        public static final int LOADING_FAIL = 2;
98
99        public int getLoadingState(int offset);
100
101        // When data change happens, we need to decide which MediaItem to focus
102        // on.
103        //
104        // 1. If focus hint path != null, we try to focus on it if we can find
105        // it.  This is used for undo a deletion, so we can focus on the
106        // undeleted item.
107        //
108        // 2. Otherwise try to focus on the MediaItem that is currently focused,
109        // if we can find it.
110        //
111        // 3. Otherwise try to focus on the previous MediaItem or the next
112        // MediaItem, depending on the value of focus hint direction.
113        public static final int FOCUS_HINT_NEXT = 0;
114        public static final int FOCUS_HINT_PREVIOUS = 1;
115        public void setFocusHintDirection(int direction);
116        public void setFocusHintPath(Path path);
117    }
118
119    public interface Listener {
120        public void onSingleTapUp(int x, int y);
121        public void lockOrientation();
122        public void unlockOrientation();
123        public void onFullScreenChanged(boolean full);
124        public void onActionBarAllowed(boolean allowed);
125        public void onActionBarWanted();
126        public void onCurrentImageUpdated();
127        public void onDeleteImage(Path path, int offset);
128        public void onUndoDeleteImage();
129        public void onCommitDeleteImage();
130        public void onFilmModeChanged(boolean enabled);
131    }
132
133    // The rules about orientation locking:
134    //
135    // (1) We need to lock the orientation if we are in page mode camera
136    // preview, so there is no (unwanted) rotation animation when the user
137    // rotates the device.
138    //
139    // (2) We need to unlock the orientation if we want to show the action bar
140    // because the action bar follows the system orientation.
141    //
142    // The rules about action bar:
143    //
144    // (1) If we are in film mode, we don't show action bar.
145    //
146    // (2) If we go from camera to gallery with capture animation, we show
147    // action bar.
148    private static final int MSG_CANCEL_EXTRA_SCALING = 2;
149    private static final int MSG_SWITCH_FOCUS = 3;
150    private static final int MSG_CAPTURE_ANIMATION_DONE = 4;
151    private static final int MSG_DELETE_ANIMATION_DONE = 5;
152    private static final int MSG_DELETE_DONE = 6;
153    private static final int MSG_UNDO_BAR_TIMEOUT = 7;
154    private static final int MSG_UNDO_BAR_FULL_CAMERA = 8;
155
156    private static final float SWIPE_THRESHOLD = 300f;
157
158    private static final float DEFAULT_TEXT_SIZE = 20;
159    private static float TRANSITION_SCALE_FACTOR = 0.74f;
160    private static final int ICON_RATIO = 6;
161
162    // whether we want to apply card deck effect in page mode.
163    private static final boolean CARD_EFFECT = true;
164
165    // whether we want to apply offset effect in film mode.
166    private static final boolean OFFSET_EFFECT = true;
167
168    // Used to calculate the scaling factor for the card deck effect.
169    private ZInterpolator mScaleInterpolator = new ZInterpolator(0.5f);
170
171    // Used to calculate the alpha factor for the fading animation.
172    private AccelerateInterpolator mAlphaInterpolator =
173            new AccelerateInterpolator(0.9f);
174
175    // We keep this many previous ScreenNails. (also this many next ScreenNails)
176    public static final int SCREEN_NAIL_MAX = 3;
177
178    // These are constants for the delete gesture.
179    private static final int SWIPE_ESCAPE_VELOCITY = 500; // dp/sec
180    private static final int MAX_DISMISS_VELOCITY = 2000; // dp/sec
181
182    // The picture entries, the valid index is from -SCREEN_NAIL_MAX to
183    // SCREEN_NAIL_MAX.
184    private final RangeArray<Picture> mPictures =
185            new RangeArray<Picture>(-SCREEN_NAIL_MAX, SCREEN_NAIL_MAX);
186    private Size[] mSizes = new Size[2 * SCREEN_NAIL_MAX + 1];
187
188    private final MyGestureListener mGestureListener;
189    private final GestureRecognizer mGestureRecognizer;
190    private final PositionController mPositionController;
191
192    private Listener mListener;
193    private Model mModel;
194    private StringTexture mNoThumbnailText;
195    private TileImageView mTileView;
196    private EdgeView mEdgeView;
197    private UndoBarView mUndoBar;
198    private Texture mVideoPlayIcon;
199
200    private SynchronizedHandler mHandler;
201
202    private boolean mCancelExtraScalingPending;
203    private boolean mFilmMode = false;
204    private int mDisplayRotation = 0;
205    private int mCompensation = 0;
206    private boolean mFullScreenCamera;
207    private Rect mCameraRelativeFrame = new Rect();
208    private Rect mCameraRect = new Rect();
209
210    // [mPrevBound, mNextBound] is the range of index for all pictures in the
211    // model, if we assume the index of current focused picture is 0.  So if
212    // there are some previous pictures, mPrevBound < 0, and if there are some
213    // next pictures, mNextBound > 0.
214    private int mPrevBound;
215    private int mNextBound;
216
217    // This variable prevents us doing snapback until its values goes to 0. This
218    // happens if the user gesture is still in progress or we are in a capture
219    // animation.
220    private int mHolding;
221    private static final int HOLD_TOUCH_DOWN = 1;
222    private static final int HOLD_CAPTURE_ANIMATION = 2;
223    private static final int HOLD_DELETE = 4;
224
225    // mTouchBoxIndex is the index of the box that is touched by the down
226    // gesture in film mode. The value Integer.MAX_VALUE means no box was
227    // touched.
228    private int mTouchBoxIndex = Integer.MAX_VALUE;
229    // Whether the box indicated by mTouchBoxIndex is deletable. Only meaningful
230    // if mTouchBoxIndex is not Integer.MAX_VALUE.
231    private boolean mTouchBoxDeletable;
232    // This is the index of the last deleted item. This is only used as a hint
233    // to hide the undo button when we are too far away from the deleted
234    // item. The value Integer.MAX_VALUE means there is no such hint.
235    private int mUndoIndexHint = Integer.MAX_VALUE;
236
237    public PhotoView(AbstractGalleryActivity activity) {
238        mTileView = new TileImageView(activity);
239        addComponent(mTileView);
240        Context context = activity.getAndroidContext();
241        mPlaceholderColor = context.getResources().getColor(
242                R.color.photo_placeholder);
243        mEdgeView = new EdgeView(context);
244        addComponent(mEdgeView);
245        mUndoBar = new UndoBarView(context);
246        addComponent(mUndoBar);
247        mUndoBar.setVisibility(GLView.INVISIBLE);
248        mUndoBar.setOnClickListener(new OnClickListener() {
249                @Override
250                public void onClick(GLView v) {
251                    mListener.onUndoDeleteImage();
252                    hideUndoBar();
253                }
254            });
255        mNoThumbnailText = StringTexture.newInstance(
256                context.getString(R.string.no_thumbnail),
257                DEFAULT_TEXT_SIZE, Color.WHITE);
258
259        mHandler = new MyHandler(activity.getGLRoot());
260
261        mGestureListener = new MyGestureListener();
262        mGestureRecognizer = new GestureRecognizer(context, mGestureListener);
263
264        mPositionController = new PositionController(context,
265                new PositionController.Listener() {
266
267            @Override
268            public void invalidate() {
269                PhotoView.this.invalidate();
270            }
271
272            @Override
273            public boolean isHoldingDown() {
274                return (mHolding & HOLD_TOUCH_DOWN) != 0;
275            }
276
277            @Override
278            public boolean isHoldingDelete() {
279                return (mHolding & HOLD_DELETE) != 0;
280            }
281
282            @Override
283            public void onPull(int offset, int direction) {
284                mEdgeView.onPull(offset, direction);
285            }
286
287            @Override
288            public void onRelease() {
289                mEdgeView.onRelease();
290            }
291
292            @Override
293            public void onAbsorb(int velocity, int direction) {
294                mEdgeView.onAbsorb(velocity, direction);
295            }
296        });
297        mVideoPlayIcon = new ResourceTexture(context, R.drawable.ic_control_play);
298        for (int i = -SCREEN_NAIL_MAX; i <= SCREEN_NAIL_MAX; i++) {
299            if (i == 0) {
300                mPictures.put(i, new FullPicture());
301            } else {
302                mPictures.put(i, new ScreenNailPicture(i));
303            }
304        }
305    }
306
307    public void setModel(Model model) {
308        mModel = model;
309        mTileView.setModel(mModel);
310    }
311
312    class MyHandler extends SynchronizedHandler {
313        public MyHandler(GLRoot root) {
314            super(root);
315        }
316
317        @Override
318        public void handleMessage(Message message) {
319            switch (message.what) {
320                case MSG_CANCEL_EXTRA_SCALING: {
321                    mGestureRecognizer.cancelScale();
322                    mPositionController.setExtraScalingRange(false);
323                    mCancelExtraScalingPending = false;
324                    break;
325                }
326                case MSG_SWITCH_FOCUS: {
327                    switchFocus();
328                    break;
329                }
330                case MSG_CAPTURE_ANIMATION_DONE: {
331                    // message.arg1 is the offset parameter passed to
332                    // switchWithCaptureAnimation().
333                    captureAnimationDone(message.arg1);
334                    break;
335                }
336                case MSG_DELETE_ANIMATION_DONE: {
337                    // message.obj is the Path of the MediaItem which should be
338                    // deleted. message.arg1 is the offset of the image.
339                    mListener.onDeleteImage((Path) message.obj, message.arg1);
340                    // Normally a box which finishes delete animation will hold
341                    // position until the underlying MediaItem is actually
342                    // deleted, and HOLD_DELETE will be cancelled that time. In
343                    // case the MediaItem didn't actually get deleted in 2
344                    // seconds, we will cancel HOLD_DELETE and make it bounce
345                    // back.
346
347                    // We make sure there is at most one MSG_DELETE_DONE
348                    // in the handler.
349                    mHandler.removeMessages(MSG_DELETE_DONE);
350                    Message m = mHandler.obtainMessage(MSG_DELETE_DONE);
351                    mHandler.sendMessageDelayed(m, 2000);
352
353                    int numberOfPictures = mNextBound - mPrevBound + 1;
354                    if (numberOfPictures == 2) {
355                        if (mModel.isCamera(mNextBound)
356                                || mModel.isCamera(mPrevBound)) {
357                            numberOfPictures--;
358                        }
359                    }
360                    showUndoBar(numberOfPictures <= 1);
361                    break;
362                }
363                case MSG_DELETE_DONE: {
364                    if (!mHandler.hasMessages(MSG_DELETE_ANIMATION_DONE)) {
365                        mHolding &= ~HOLD_DELETE;
366                        snapback();
367                    }
368                    break;
369                }
370                case MSG_UNDO_BAR_TIMEOUT: {
371                    checkHideUndoBar(UNDO_BAR_TIMEOUT);
372                    break;
373                }
374                case MSG_UNDO_BAR_FULL_CAMERA: {
375                    checkHideUndoBar(UNDO_BAR_FULL_CAMERA);
376                    break;
377                }
378                default: throw new AssertionError(message.what);
379            }
380        }
381    }
382
383    ////////////////////////////////////////////////////////////////////////////
384    //  Data/Image change notifications
385    ////////////////////////////////////////////////////////////////////////////
386
387    public void notifyDataChange(int[] fromIndex, int prevBound, int nextBound) {
388        mPrevBound = prevBound;
389        mNextBound = nextBound;
390
391        // Update mTouchBoxIndex
392        if (mTouchBoxIndex != Integer.MAX_VALUE) {
393            int k = mTouchBoxIndex;
394            mTouchBoxIndex = Integer.MAX_VALUE;
395            for (int i = 0; i < 2 * SCREEN_NAIL_MAX + 1; i++) {
396                if (fromIndex[i] == k) {
397                    mTouchBoxIndex = i - SCREEN_NAIL_MAX;
398                    break;
399                }
400            }
401        }
402
403        // Hide undo button if we are too far away
404        if (mUndoIndexHint != Integer.MAX_VALUE) {
405            if (Math.abs(mUndoIndexHint - mModel.getCurrentIndex()) >= 3) {
406                hideUndoBar();
407            }
408        }
409
410        // Update the ScreenNails.
411        for (int i = -SCREEN_NAIL_MAX; i <= SCREEN_NAIL_MAX; i++) {
412            Picture p =  mPictures.get(i);
413            p.reload();
414            mSizes[i + SCREEN_NAIL_MAX] = p.getSize();
415        }
416
417        boolean wasDeleting = mPositionController.hasDeletingBox();
418
419        // Move the boxes
420        mPositionController.moveBox(fromIndex, mPrevBound < 0, mNextBound > 0,
421                mModel.isCamera(0), mSizes);
422
423        for (int i = -SCREEN_NAIL_MAX; i <= SCREEN_NAIL_MAX; i++) {
424            setPictureSize(i);
425        }
426
427        boolean isDeleting = mPositionController.hasDeletingBox();
428
429        // If the deletion is done, make HOLD_DELETE persist for only the time
430        // needed for a snapback animation.
431        if (wasDeleting && !isDeleting) {
432            mHandler.removeMessages(MSG_DELETE_DONE);
433            Message m = mHandler.obtainMessage(MSG_DELETE_DONE);
434            mHandler.sendMessageDelayed(
435                    m, PositionController.SNAPBACK_ANIMATION_TIME);
436        }
437
438        invalidate();
439    }
440
441    public boolean isDeleting() {
442        return (mHolding & HOLD_DELETE) != 0
443                && mPositionController.hasDeletingBox();
444    }
445
446    public void notifyImageChange(int index) {
447        if (index == 0) {
448            mListener.onCurrentImageUpdated();
449        }
450        mPictures.get(index).reload();
451        setPictureSize(index);
452        invalidate();
453    }
454
455    private void setPictureSize(int index) {
456        Picture p = mPictures.get(index);
457        mPositionController.setImageSize(index, p.getSize(),
458                index == 0 && p.isCamera() ? mCameraRect : null);
459    }
460
461    @Override
462    protected void onLayout(
463            boolean changeSize, int left, int top, int right, int bottom) {
464        int w = right - left;
465        int h = bottom - top;
466        mTileView.layout(0, 0, w, h);
467        mEdgeView.layout(0, 0, w, h);
468        mUndoBar.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
469        mUndoBar.layout(0, h - mUndoBar.getMeasuredHeight(), w, h);
470
471        GLRoot root = getGLRoot();
472        int displayRotation = root.getDisplayRotation();
473        int compensation = root.getCompensation();
474        if (mDisplayRotation != displayRotation
475                || mCompensation != compensation) {
476            mDisplayRotation = displayRotation;
477            mCompensation = compensation;
478
479            // We need to change the size and rotation of the Camera ScreenNail,
480            // but we don't want it to animate because the size doen't actually
481            // change in the eye of the user.
482            for (int i = -SCREEN_NAIL_MAX; i <= SCREEN_NAIL_MAX; i++) {
483                Picture p = mPictures.get(i);
484                if (p.isCamera()) {
485                    p.forceSize();
486                }
487            }
488        }
489
490        updateCameraRect();
491        mPositionController.setConstrainedFrame(mCameraRect);
492        if (changeSize) {
493            mPositionController.setViewSize(getWidth(), getHeight());
494        }
495    }
496
497    // Update the camera rectangle due to layout change or camera relative frame
498    // change.
499    private void updateCameraRect() {
500        // Get the width and height in framework orientation because the given
501        // mCameraRelativeFrame is in that coordinates.
502        int w = getWidth();
503        int h = getHeight();
504        if (mCompensation % 180 != 0) {
505            int tmp = w;
506            w = h;
507            h = tmp;
508        }
509        int l = mCameraRelativeFrame.left;
510        int t = mCameraRelativeFrame.top;
511        int r = mCameraRelativeFrame.right;
512        int b = mCameraRelativeFrame.bottom;
513
514        // Now convert it to the coordinates we are using.
515        switch (mCompensation) {
516            case 0: mCameraRect.set(l, t, r, b); break;
517            case 90: mCameraRect.set(h - b, l, h - t, r); break;
518            case 180: mCameraRect.set(w - r, h - b, w - l, h - t); break;
519            case 270: mCameraRect.set(t, w - r, b, w - l); break;
520        }
521
522        Log.d(TAG, "compensation = " + mCompensation
523                + ", CameraRelativeFrame = " + mCameraRelativeFrame
524                + ", mCameraRect = " + mCameraRect);
525    }
526
527    public void setCameraRelativeFrame(Rect frame) {
528        mCameraRelativeFrame.set(frame);
529        updateCameraRect();
530        // Originally we do
531        //     mPositionController.setConstrainedFrame(mCameraRect);
532        // here, but it is moved to a parameter of the setImageSize() call, so
533        // it can be updated atomically with the CameraScreenNail's size change.
534    }
535
536    // Returns the rotation we need to do to the camera texture before drawing
537    // it to the canvas, assuming the camera texture is correct when the device
538    // is in its natural orientation.
539    private int getCameraRotation() {
540        return (mCompensation - mDisplayRotation + 360) % 360;
541    }
542
543    private int getPanoramaRotation() {
544        return mCompensation;
545    }
546
547    ////////////////////////////////////////////////////////////////////////////
548    //  Pictures
549    ////////////////////////////////////////////////////////////////////////////
550
551    private interface Picture {
552        void reload();
553        void draw(GLCanvas canvas, Rect r);
554        void setScreenNail(ScreenNail s);
555        boolean isCamera();  // whether the picture is a camera preview
556        boolean isDeletable();  // whether the picture can be deleted
557        void forceSize();  // called when mCompensation changes
558        Size getSize();
559    }
560
561    class FullPicture implements Picture {
562        private int mRotation;
563        private boolean mIsCamera;
564        private boolean mIsPanorama;
565        private boolean mUsePanoramaViewer;
566        private boolean mIsStaticCamera;
567        private boolean mIsVideo;
568        private boolean mIsDeletable;
569        private int mLoadingState = Model.LOADING_INIT;
570        private Size mSize = new Size();
571        private boolean mWasCameraCenter;
572
573        @Override
574        public void reload() {
575            // mImageWidth and mImageHeight will get updated
576            mTileView.notifyModelInvalidated();
577
578            mIsCamera = mModel.isCamera(0);
579            mIsPanorama = mModel.isPanorama(0);
580            mUsePanoramaViewer = mModel.usePanoramaViewer(0);
581            mIsStaticCamera = mModel.isStaticCamera(0);
582            mIsVideo = mModel.isVideo(0);
583            mIsDeletable = mModel.isDeletable(0);
584            mLoadingState = mModel.getLoadingState(0);
585            setScreenNail(mModel.getScreenNail(0));
586            updateSize();
587        }
588
589        @Override
590        public Size getSize() {
591            return mSize;
592        }
593
594        @Override
595        public void forceSize() {
596            updateSize();
597            mPositionController.forceImageSize(0, mSize);
598        }
599
600        private void updateSize() {
601            if (mIsPanorama) {
602                mRotation = getPanoramaRotation();
603            } else if (mIsCamera && !mIsStaticCamera) {
604                mRotation = getCameraRotation();
605            } else {
606                mRotation = mModel.getImageRotation(0);
607            }
608
609            int w = mTileView.mImageWidth;
610            int h = mTileView.mImageHeight;
611            mSize.width = getRotated(mRotation, w, h);
612            mSize.height = getRotated(mRotation, h, w);
613        }
614
615        private boolean mNeedToChangeToFilmstripWhenCentered = false;
616        @Override
617        public void draw(GLCanvas canvas, Rect r) {
618            drawTileView(canvas, r);
619
620            // We want to have the following transitions:
621            // (1) Move camera preview out of its place: switch to film mode
622            // (2) Move camera preview into its place: switch to page mode
623            // The extra mWasCenter check makes sure (1) does not apply if in
624            // page mode, we move _to_ the camera preview from another picture.
625
626            // Holdings except touch-down prevent the transitions.
627            if ((mHolding & ~HOLD_TOUCH_DOWN) != 0) return;
628
629            boolean isCenter = mPositionController.isCenter();
630            boolean isCameraCenter = mIsCamera && isCenter && !canUndoLastPicture();
631
632            if (mWasCameraCenter && mIsCamera && !isCenter && !mFilmMode) {
633                setFilmMode(false);
634                mNeedToChangeToFilmstripWhenCentered = true;
635            } else if (isCenter && mNeedToChangeToFilmstripWhenCentered) {
636                setFilmMode(true);
637                mNeedToChangeToFilmstripWhenCentered = false;
638            } else if (!mWasCameraCenter && isCameraCenter && mFilmMode) {
639                setFilmMode(false);
640            }
641
642            if (isCameraCenter && !mFilmMode) {
643                // Move into camera in page mode, lock
644                mListener.lockOrientation();
645            }
646
647            mWasCameraCenter = isCameraCenter;
648        }
649
650        @Override
651        public void setScreenNail(ScreenNail s) {
652            mTileView.setScreenNail(s);
653        }
654
655        @Override
656        public boolean isCamera() {
657            return mIsCamera;
658        }
659
660        @Override
661        public boolean isDeletable() {
662            return mIsDeletable;
663        }
664
665        private void drawTileView(GLCanvas canvas, Rect r) {
666            float imageScale = mPositionController.getImageScale();
667            int viewW = getWidth();
668            int viewH = getHeight();
669            float cx = r.exactCenterX();
670            float cy = r.exactCenterY();
671            float scale = 1f;  // the scaling factor due to card effect
672
673            canvas.save(GLCanvas.SAVE_FLAG_MATRIX | GLCanvas.SAVE_FLAG_ALPHA);
674            float filmRatio = mPositionController.getFilmRatio();
675            boolean wantsCardEffect = CARD_EFFECT && !mIsCamera
676                    && filmRatio != 1f && !mPictures.get(-1).isCamera()
677                    && !mPositionController.inOpeningAnimation();
678            boolean wantsOffsetEffect = OFFSET_EFFECT && mIsDeletable
679                    && filmRatio == 1f && r.centerY() != viewH / 2;
680            if (wantsCardEffect) {
681                // Calculate the move-out progress value.
682                int left = r.left;
683                int right = r.right;
684                float progress = calculateMoveOutProgress(left, right, viewW);
685                progress = Utils.clamp(progress, -1f, 1f);
686
687                // We only want to apply the fading animation if the scrolling
688                // movement is to the right.
689                if (progress < 0) {
690                    scale = getScrollScale(progress);
691                    float alpha = getScrollAlpha(progress);
692                    scale = interpolate(filmRatio, scale, 1f);
693                    alpha = interpolate(filmRatio, alpha, 1f);
694
695                    imageScale *= scale;
696                    canvas.multiplyAlpha(alpha);
697
698                    float cxPage;  // the cx value in page mode
699                    if (right - left <= viewW) {
700                        // If the picture is narrower than the view, keep it at
701                        // the center of the view.
702                        cxPage = viewW / 2f;
703                    } else {
704                        // If the picture is wider than the view (it's
705                        // zoomed-in), keep the left edge of the object align
706                        // the the left edge of the view.
707                        cxPage = (right - left) * scale / 2f;
708                    }
709                    cx = interpolate(filmRatio, cxPage, cx);
710                }
711            } else if (wantsOffsetEffect) {
712                float offset = (float) (r.centerY() - viewH / 2) / viewH;
713                float alpha = getOffsetAlpha(offset);
714                canvas.multiplyAlpha(alpha);
715            }
716
717            // Draw the tile view.
718            setTileViewPosition(cx, cy, viewW, viewH, imageScale);
719            renderChild(canvas, mTileView);
720
721            // Draw the play video icon and the message.
722            canvas.translate((int) (cx + 0.5f), (int) (cy + 0.5f));
723            int s = (int) (scale * Math.min(r.width(), r.height()) + 0.5f);
724            if (mIsVideo || mUsePanoramaViewer) drawVideoPlayIcon(canvas, s);
725            if (mLoadingState == Model.LOADING_FAIL) {
726                drawLoadingFailMessage(canvas);
727            }
728
729            // Draw a debug indicator showing which picture has focus (index ==
730            // 0).
731            //canvas.fillRect(-10, -10, 20, 20, 0x80FF00FF);
732
733            canvas.restore();
734        }
735
736        // Set the position of the tile view
737        private void setTileViewPosition(float cx, float cy,
738                int viewW, int viewH, float scale) {
739            // Find out the bitmap coordinates of the center of the view
740            int imageW = mPositionController.getImageWidth();
741            int imageH = mPositionController.getImageHeight();
742            int centerX = (int) (imageW / 2f + (viewW / 2f - cx) / scale + 0.5f);
743            int centerY = (int) (imageH / 2f + (viewH / 2f - cy) / scale + 0.5f);
744
745            int inverseX = imageW - centerX;
746            int inverseY = imageH - centerY;
747            int x, y;
748            switch (mRotation) {
749                case 0: x = centerX; y = centerY; break;
750                case 90: x = centerY; y = inverseX; break;
751                case 180: x = inverseX; y = inverseY; break;
752                case 270: x = inverseY; y = centerX; break;
753                default:
754                    throw new RuntimeException(String.valueOf(mRotation));
755            }
756            mTileView.setPosition(x, y, scale, mRotation);
757        }
758    }
759
760    private class ScreenNailPicture implements Picture {
761        private int mIndex;
762        private int mRotation;
763        private ScreenNail mScreenNail;
764        private boolean mIsCamera;
765        private boolean mIsPanorama;
766        private boolean mUsePanoramaViewer;
767        private boolean mIsStaticCamera;
768        private boolean mIsVideo;
769        private boolean mIsDeletable;
770        private int mLoadingState = Model.LOADING_INIT;
771        private Size mSize = new Size();
772
773        public ScreenNailPicture(int index) {
774            mIndex = index;
775        }
776
777        @Override
778        public void reload() {
779            mIsCamera = mModel.isCamera(mIndex);
780            mIsPanorama = mModel.isPanorama(mIndex);
781            mUsePanoramaViewer = mModel.usePanoramaViewer(mIndex);
782            mIsStaticCamera = mModel.isStaticCamera(mIndex);
783            mIsVideo = mModel.isVideo(mIndex);
784            mIsDeletable = mModel.isDeletable(mIndex);
785            mLoadingState = mModel.getLoadingState(mIndex);
786            setScreenNail(mModel.getScreenNail(mIndex));
787            updateSize();
788        }
789
790        @Override
791        public Size getSize() {
792            return mSize;
793        }
794
795        @Override
796        public void draw(GLCanvas canvas, Rect r) {
797            if (mScreenNail == null) {
798                // Draw a placeholder rectange if there should be a picture in
799                // this position (but somehow there isn't).
800                if (mIndex >= mPrevBound && mIndex <= mNextBound) {
801                    drawPlaceHolder(canvas, r);
802                }
803                return;
804            }
805            int w = getWidth();
806            int h = getHeight();
807            if (r.left >= w || r.right <= 0 || r.top >= h || r.bottom <= 0) {
808                mScreenNail.noDraw();
809                return;
810            }
811
812            float filmRatio = mPositionController.getFilmRatio();
813            boolean wantsCardEffect = CARD_EFFECT && mIndex > 0
814                    && filmRatio != 1f && !mPictures.get(0).isCamera();
815            boolean wantsOffsetEffect = OFFSET_EFFECT && mIsDeletable
816                    && filmRatio == 1f && r.centerY() != h / 2;
817            int cx = wantsCardEffect
818                    ? (int) (interpolate(filmRatio, w / 2, r.centerX()) + 0.5f)
819                    : r.centerX();
820            int cy = r.centerY();
821            canvas.save(GLCanvas.SAVE_FLAG_MATRIX | GLCanvas.SAVE_FLAG_ALPHA);
822            canvas.translate(cx, cy);
823            if (wantsCardEffect) {
824                float progress = (float) (w / 2 - r.centerX()) / w;
825                progress = Utils.clamp(progress, -1, 1);
826                float alpha = getScrollAlpha(progress);
827                float scale = getScrollScale(progress);
828                alpha = interpolate(filmRatio, alpha, 1f);
829                scale = interpolate(filmRatio, scale, 1f);
830                canvas.multiplyAlpha(alpha);
831                canvas.scale(scale, scale, 1);
832            } else if (wantsOffsetEffect) {
833                float offset = (float) (r.centerY() - h / 2) / h;
834                float alpha = getOffsetAlpha(offset);
835                canvas.multiplyAlpha(alpha);
836            }
837            if (mRotation != 0) {
838                canvas.rotate(mRotation, 0, 0, 1);
839            }
840            int drawW = getRotated(mRotation, r.width(), r.height());
841            int drawH = getRotated(mRotation, r.height(), r.width());
842            mScreenNail.draw(canvas, -drawW / 2, -drawH / 2, drawW, drawH);
843            if (isScreenNailAnimating()) {
844                invalidate();
845            }
846            int s = Math.min(drawW, drawH);
847            if (mIsVideo || mUsePanoramaViewer) drawVideoPlayIcon(canvas, s);
848            if (mLoadingState == Model.LOADING_FAIL) {
849                drawLoadingFailMessage(canvas);
850            }
851            canvas.restore();
852        }
853
854        private boolean isScreenNailAnimating() {
855            return (mScreenNail instanceof BitmapScreenNail)
856                    && ((BitmapScreenNail) mScreenNail).isAnimating();
857        }
858
859        @Override
860        public void setScreenNail(ScreenNail s) {
861            mScreenNail = s;
862        }
863
864        @Override
865        public void forceSize() {
866            updateSize();
867            mPositionController.forceImageSize(mIndex, mSize);
868        }
869
870        private void updateSize() {
871            if (mIsPanorama) {
872                mRotation = getPanoramaRotation();
873            } else if (mIsCamera && !mIsStaticCamera) {
874                mRotation = getCameraRotation();
875            } else {
876                mRotation = mModel.getImageRotation(mIndex);
877            }
878
879            if (mScreenNail != null) {
880                mSize.width = mScreenNail.getWidth();
881                mSize.height = mScreenNail.getHeight();
882            } else {
883                // If we don't have ScreenNail available, we can still try to
884                // get the size information of it.
885                mModel.getImageSize(mIndex, mSize);
886            }
887
888            int w = mSize.width;
889            int h = mSize.height;
890            mSize.width = getRotated(mRotation, w, h);
891            mSize.height = getRotated(mRotation, h, w);
892        }
893
894        @Override
895        public boolean isCamera() {
896            return mIsCamera;
897        }
898
899        @Override
900        public boolean isDeletable() {
901            return mIsDeletable;
902        }
903    }
904
905    // Draw a gray placeholder in the specified rectangle.
906    private void drawPlaceHolder(GLCanvas canvas, Rect r) {
907        canvas.fillRect(r.left, r.top, r.width(), r.height(), mPlaceholderColor);
908    }
909
910    // Draw the video play icon (in the place where the spinner was)
911    private void drawVideoPlayIcon(GLCanvas canvas, int side) {
912        int s = side / ICON_RATIO;
913        // Draw the video play icon at the center
914        mVideoPlayIcon.draw(canvas, -s / 2, -s / 2, s, s);
915    }
916
917    // Draw the "no thumbnail" message
918    private void drawLoadingFailMessage(GLCanvas canvas) {
919        StringTexture m = mNoThumbnailText;
920        m.draw(canvas, -m.getWidth() / 2, -m.getHeight() / 2);
921    }
922
923    private static int getRotated(int degree, int original, int theother) {
924        return (degree % 180 == 0) ? original : theother;
925    }
926
927    ////////////////////////////////////////////////////////////////////////////
928    //  Gestures Handling
929    ////////////////////////////////////////////////////////////////////////////
930
931    @Override
932    protected boolean onTouch(MotionEvent event) {
933        mGestureRecognizer.onTouchEvent(event);
934        return true;
935    }
936
937    private class MyGestureListener implements GestureRecognizer.Listener {
938        private boolean mIgnoreUpEvent = false;
939        // If we can change mode for this scale gesture.
940        private boolean mCanChangeMode;
941        // If we have changed the film mode in this scaling gesture.
942        private boolean mModeChanged;
943        // If this scaling gesture should be ignored.
944        private boolean mIgnoreScalingGesture;
945        // whether the down action happened while the view is scrolling.
946        private boolean mDownInScrolling;
947        // If we should ignore all gestures other than onSingleTapUp.
948        private boolean mIgnoreSwipingGesture;
949        // If a scrolling has happened after a down gesture.
950        private boolean mScrolledAfterDown;
951        // If the first scrolling move is in X direction. In the film mode, X
952        // direction scrolling is normal scrolling. but Y direction scrolling is
953        // a delete gesture.
954        private boolean mFirstScrollX;
955        // The accumulated Y delta that has been sent to mPositionController.
956        private int mDeltaY;
957        // The accumulated scaling change from a scaling gesture.
958        private float mAccScale;
959
960        @Override
961        public boolean onSingleTapUp(float x, float y) {
962            // On crespo running Android 2.3.6 (gingerbread), a pinch out gesture results in the
963            // following call sequence: onDown(), onUp() and then onSingleTapUp(). The correct
964            // sequence for a single-tap-up gesture should be: onDown(), onSingleTapUp() and onUp().
965            // The call sequence for a pinch out gesture in JB is: onDown(), then onUp() and there's
966            // no onSingleTapUp(). Base on these observations, the following condition is added to
967            // filter out the false alarm where onSingleTapUp() is called within a pinch out
968            // gesture. The framework fix went into ICS. Refer to b/4588114.
969            if (Build.VERSION.SDK_INT < ApiHelper.VERSION_CODES.ICE_CREAM_SANDWICH) {
970                if ((mHolding & HOLD_TOUCH_DOWN) == 0) {
971                    return true;
972                }
973            }
974
975            // We do this in addition to onUp() because we want the snapback of
976            // setFilmMode to happen.
977            mHolding &= ~HOLD_TOUCH_DOWN;
978
979            if (mFilmMode && !mDownInScrolling) {
980                switchToHitPicture((int) (x + 0.5f), (int) (y + 0.5f));
981                setFilmMode(false);
982                mIgnoreUpEvent = true;
983                return true;
984            }
985
986            if (mListener != null) {
987                // Do the inverse transform of the touch coordinates.
988                Matrix m = getGLRoot().getCompensationMatrix();
989                Matrix inv = new Matrix();
990                m.invert(inv);
991                float[] pts = new float[] {x, y};
992                inv.mapPoints(pts);
993                mListener.onSingleTapUp((int) (pts[0] + 0.5f), (int) (pts[1] + 0.5f));
994            }
995            return true;
996        }
997
998        @Override
999        public boolean onDoubleTap(float x, float y) {
1000            if (mIgnoreSwipingGesture) return true;
1001            if (mPictures.get(0).isCamera()) return false;
1002            PositionController controller = mPositionController;
1003            float scale = controller.getImageScale();
1004            // onDoubleTap happened on the second ACTION_DOWN.
1005            // We need to ignore the next UP event.
1006            mIgnoreUpEvent = true;
1007            if (scale <= 1.0f || controller.isAtMinimalScale()) {
1008                controller.zoomIn(x, y, Math.max(1.5f, scale * 1.5f));
1009            } else {
1010                controller.resetToFullView();
1011            }
1012            return true;
1013        }
1014
1015        @Override
1016        public boolean onScroll(float dx, float dy, float totalX, float totalY) {
1017            if (mIgnoreSwipingGesture) return true;
1018            if (!mScrolledAfterDown) {
1019                mScrolledAfterDown = true;
1020                mFirstScrollX = (Math.abs(dx) > Math.abs(dy));
1021            }
1022
1023            int dxi = (int) (-dx + 0.5f);
1024            int dyi = (int) (-dy + 0.5f);
1025            if (mFilmMode) {
1026                if (mFirstScrollX) {
1027                    mPositionController.scrollFilmX(dxi);
1028                } else {
1029                    if (mTouchBoxIndex == Integer.MAX_VALUE) return true;
1030                    int newDeltaY = calculateDeltaY(totalY);
1031                    int d = newDeltaY - mDeltaY;
1032                    if (d != 0) {
1033                        mPositionController.scrollFilmY(mTouchBoxIndex, d);
1034                        mDeltaY = newDeltaY;
1035                    }
1036                }
1037            } else {
1038                mPositionController.scrollPage(dxi, dyi);
1039            }
1040            return true;
1041        }
1042
1043        private int calculateDeltaY(float delta) {
1044            if (mTouchBoxDeletable) return (int) (delta + 0.5f);
1045
1046            // don't let items that can't be deleted be dragged more than
1047            // maxScrollDistance, and make it harder and harder to drag.
1048            int size = getHeight();
1049            float maxScrollDistance = 0.15f * size;
1050            if (Math.abs(delta) >= size) {
1051                delta = delta > 0 ? maxScrollDistance : -maxScrollDistance;
1052            } else {
1053                delta = maxScrollDistance *
1054                        FloatMath.sin((delta / size) * (float) (Math.PI / 2));
1055            }
1056            return (int) (delta + 0.5f);
1057        }
1058
1059        @Override
1060        public boolean onFling(float velocityX, float velocityY) {
1061            if (mIgnoreSwipingGesture) return true;
1062            if (mModeChanged) return true;
1063            if (swipeImages(velocityX, velocityY)) {
1064                mIgnoreUpEvent = true;
1065            } else {
1066                flingImages(velocityX, velocityY);
1067            }
1068            return true;
1069        }
1070
1071        private boolean flingImages(float velocityX, float velocityY) {
1072            int vx = (int) (velocityX + 0.5f);
1073            int vy = (int) (velocityY + 0.5f);
1074            if (!mFilmMode) {
1075                return mPositionController.flingPage(vx, vy);
1076            }
1077            if (Math.abs(velocityX) > Math.abs(velocityY)) {
1078                return mPositionController.flingFilmX(vx);
1079            }
1080            // If we scrolled in Y direction fast enough, treat it as a delete
1081            // gesture.
1082            if (!mFilmMode || mTouchBoxIndex == Integer.MAX_VALUE
1083                    || !mTouchBoxDeletable) {
1084                return false;
1085            }
1086            int maxVelocity = GalleryUtils.dpToPixel(MAX_DISMISS_VELOCITY);
1087            int escapeVelocity = GalleryUtils.dpToPixel(SWIPE_ESCAPE_VELOCITY);
1088            int centerY = mPositionController.getPosition(mTouchBoxIndex)
1089                    .centerY();
1090            boolean fastEnough = (Math.abs(vy) > escapeVelocity)
1091                    && (Math.abs(vy) > Math.abs(vx))
1092                    && ((vy > 0) == (centerY > getHeight() / 2));
1093            if (fastEnough) {
1094                vy = Math.min(vy, maxVelocity);
1095                int duration = mPositionController.flingFilmY(mTouchBoxIndex, vy);
1096                if (duration >= 0) {
1097                    mPositionController.setPopFromTop(vy < 0);
1098                    deleteAfterAnimation(duration);
1099                    // We reset mTouchBoxIndex, so up() won't check if Y
1100                    // scrolled far enough to be a delete gesture.
1101                    mTouchBoxIndex = Integer.MAX_VALUE;
1102                    return true;
1103                }
1104            }
1105            return false;
1106        }
1107
1108        private void deleteAfterAnimation(int duration) {
1109            MediaItem item = mModel.getMediaItem(mTouchBoxIndex);
1110            if (item == null) return;
1111            mListener.onCommitDeleteImage();
1112            mUndoIndexHint = mModel.getCurrentIndex() + mTouchBoxIndex;
1113            mHolding |= HOLD_DELETE;
1114            Message m = mHandler.obtainMessage(MSG_DELETE_ANIMATION_DONE);
1115            m.obj = item.getPath();
1116            m.arg1 = mTouchBoxIndex;
1117            mHandler.sendMessageDelayed(m, duration);
1118        }
1119
1120        @Override
1121        public boolean onScaleBegin(float focusX, float focusY) {
1122            if (mIgnoreSwipingGesture) return true;
1123            // We ignore the scaling gesture if it is a camera preview.
1124            mIgnoreScalingGesture = mPictures.get(0).isCamera();
1125            if (mIgnoreScalingGesture) {
1126                return true;
1127            }
1128            mPositionController.beginScale(focusX, focusY);
1129            // We can change mode if we are in film mode, or we are in page
1130            // mode and at minimal scale.
1131            mCanChangeMode = mFilmMode
1132                    || mPositionController.isAtMinimalScale();
1133            mAccScale = 1f;
1134            return true;
1135        }
1136
1137        @Override
1138        public boolean onScale(float focusX, float focusY, float scale) {
1139            if (mIgnoreSwipingGesture) return true;
1140            if (mIgnoreScalingGesture) return true;
1141            if (mModeChanged) return true;
1142            if (Float.isNaN(scale) || Float.isInfinite(scale)) return false;
1143
1144            int outOfRange = mPositionController.scaleBy(scale, focusX, focusY);
1145
1146            // We wait for a large enough scale change before changing mode.
1147            // Otherwise we may mistakenly treat a zoom-in gesture as zoom-out
1148            // or vice versa.
1149            mAccScale *= scale;
1150            boolean largeEnough = (mAccScale < 0.97f || mAccScale > 1.03f);
1151
1152            // If mode changes, we treat this scaling gesture has ended.
1153            if (mCanChangeMode && largeEnough) {
1154                if ((outOfRange < 0 && !mFilmMode) ||
1155                        (outOfRange > 0 && mFilmMode)) {
1156                    stopExtraScalingIfNeeded();
1157
1158                    // Removing the touch down flag allows snapback to happen
1159                    // for film mode change.
1160                    mHolding &= ~HOLD_TOUCH_DOWN;
1161                    setFilmMode(!mFilmMode);
1162
1163                    // We need to call onScaleEnd() before setting mModeChanged
1164                    // to true.
1165                    onScaleEnd();
1166                    mModeChanged = true;
1167                    return true;
1168                }
1169           }
1170
1171            if (outOfRange != 0) {
1172                startExtraScalingIfNeeded();
1173            } else {
1174                stopExtraScalingIfNeeded();
1175            }
1176            return true;
1177        }
1178
1179        @Override
1180        public void onScaleEnd() {
1181            if (mIgnoreSwipingGesture) return;
1182            if (mIgnoreScalingGesture) return;
1183            if (mModeChanged) return;
1184            mPositionController.endScale();
1185        }
1186
1187        private void startExtraScalingIfNeeded() {
1188            if (!mCancelExtraScalingPending) {
1189                mHandler.sendEmptyMessageDelayed(
1190                        MSG_CANCEL_EXTRA_SCALING, 700);
1191                mPositionController.setExtraScalingRange(true);
1192                mCancelExtraScalingPending = true;
1193            }
1194        }
1195
1196        private void stopExtraScalingIfNeeded() {
1197            if (mCancelExtraScalingPending) {
1198                mHandler.removeMessages(MSG_CANCEL_EXTRA_SCALING);
1199                mPositionController.setExtraScalingRange(false);
1200                mCancelExtraScalingPending = false;
1201            }
1202        }
1203
1204        @Override
1205        public void onDown(float x, float y) {
1206            checkHideUndoBar(UNDO_BAR_TOUCHED);
1207
1208            mDeltaY = 0;
1209            mModeChanged = false;
1210
1211            if (mIgnoreSwipingGesture) return;
1212
1213            mHolding |= HOLD_TOUCH_DOWN;
1214
1215            if (mFilmMode && mPositionController.isScrolling()) {
1216                mDownInScrolling = true;
1217                mPositionController.stopScrolling();
1218            } else {
1219                mDownInScrolling = false;
1220            }
1221
1222            mScrolledAfterDown = false;
1223            if (mFilmMode) {
1224                int xi = (int) (x + 0.5f);
1225                int yi = (int) (y + 0.5f);
1226                mTouchBoxIndex = mPositionController.hitTest(xi, yi);
1227                if (mTouchBoxIndex < mPrevBound || mTouchBoxIndex > mNextBound) {
1228                    mTouchBoxIndex = Integer.MAX_VALUE;
1229                } else {
1230                    mTouchBoxDeletable =
1231                            mPictures.get(mTouchBoxIndex).isDeletable();
1232                }
1233            } else {
1234                mTouchBoxIndex = Integer.MAX_VALUE;
1235            }
1236        }
1237
1238        @Override
1239        public void onUp() {
1240            if (mIgnoreSwipingGesture) return;
1241
1242            mHolding &= ~HOLD_TOUCH_DOWN;
1243            mEdgeView.onRelease();
1244
1245            // If we scrolled in Y direction far enough, treat it as a delete
1246            // gesture.
1247            if (mFilmMode && mScrolledAfterDown && !mFirstScrollX
1248                    && mTouchBoxIndex != Integer.MAX_VALUE) {
1249                Rect r = mPositionController.getPosition(mTouchBoxIndex);
1250                int h = getHeight();
1251                if (Math.abs(r.centerY() - h * 0.5f) > 0.4f * h) {
1252                    int duration = mPositionController
1253                            .flingFilmY(mTouchBoxIndex, 0);
1254                    if (duration >= 0) {
1255                        mPositionController.setPopFromTop(r.centerY() < h * 0.5f);
1256                        deleteAfterAnimation(duration);
1257                    }
1258                }
1259            }
1260
1261            if (mIgnoreUpEvent) {
1262                mIgnoreUpEvent = false;
1263                return;
1264            }
1265
1266            snapback();
1267        }
1268
1269        public void setSwipingEnabled(boolean enabled) {
1270            mIgnoreSwipingGesture = !enabled;
1271        }
1272    }
1273
1274    public void setSwipingEnabled(boolean enabled) {
1275        mGestureListener.setSwipingEnabled(enabled);
1276    }
1277
1278    public void setFilmMode(boolean enabled) {
1279        if (mFilmMode == enabled) return;
1280        mFilmMode = enabled;
1281        mPositionController.setFilmMode(mFilmMode);
1282        mModel.setNeedFullImage(!enabled);
1283        mModel.setFocusHintDirection(
1284                mFilmMode ? Model.FOCUS_HINT_PREVIOUS : Model.FOCUS_HINT_NEXT);
1285        mListener.onFilmModeChanged(enabled);
1286        boolean isCamera = mPictures.get(0).isCamera();
1287        if (isCamera) {
1288            // Move into camera in page mode, lock
1289            if (!enabled) mListener.lockOrientation();
1290            mListener.onActionBarAllowed(false);
1291        } else {
1292            mListener.onActionBarAllowed(true);
1293            if (enabled) mListener.onActionBarWanted();
1294        }
1295    }
1296
1297    public boolean getFilmMode() {
1298        return mFilmMode;
1299    }
1300
1301    ////////////////////////////////////////////////////////////////////////////
1302    //  Framework events
1303    ////////////////////////////////////////////////////////////////////////////
1304
1305    public void pause() {
1306        mPositionController.skipAnimation();
1307        mTileView.freeTextures();
1308        for (int i = -SCREEN_NAIL_MAX; i <= SCREEN_NAIL_MAX; i++) {
1309            mPictures.get(i).setScreenNail(null);
1310        }
1311        hideUndoBar();
1312    }
1313
1314    public void resume() {
1315        mTileView.prepareTextures();
1316    }
1317
1318    // move to the camera preview and show controls after resume
1319    public void resetToFirstPicture() {
1320        mModel.moveTo(0);
1321        mListener.onActionBarAllowed(false);
1322        setFilmMode(false);
1323    }
1324
1325    ////////////////////////////////////////////////////////////////////////////
1326    //  Undo Bar
1327    ////////////////////////////////////////////////////////////////////////////
1328
1329    private int mUndoBarState;
1330    private static final int UNDO_BAR_SHOW = 1;
1331    private static final int UNDO_BAR_TIMEOUT = 2;
1332    private static final int UNDO_BAR_TOUCHED = 4;
1333    private static final int UNDO_BAR_FULL_CAMERA = 8;
1334    private static final int UNDO_BAR_DELETE_LAST = 16;
1335
1336    // "deleteLast" means if the deletion is on the last remaining picture in
1337    // the album.
1338    private void showUndoBar(boolean deleteLast) {
1339        mHandler.removeMessages(MSG_UNDO_BAR_TIMEOUT);
1340        mUndoBarState = UNDO_BAR_SHOW;
1341        if(deleteLast) mUndoBarState |= UNDO_BAR_DELETE_LAST;
1342        mUndoBar.animateVisibility(GLView.VISIBLE);
1343        mHandler.sendEmptyMessageDelayed(MSG_UNDO_BAR_TIMEOUT, 3000);
1344    }
1345
1346    private void hideUndoBar() {
1347        mHandler.removeMessages(MSG_UNDO_BAR_TIMEOUT);
1348        mListener.onCommitDeleteImage();
1349        mUndoBar.animateVisibility(GLView.INVISIBLE);
1350        mUndoBarState = 0;
1351        mUndoIndexHint = Integer.MAX_VALUE;
1352    }
1353
1354    // Check if the one of the conditions for hiding the undo bar has been
1355    // met. The conditions are:
1356    //
1357    // 1. It has been three seconds since last showing, and (a) the user has
1358    // touched, or (b) the deleted picture is the last remaining picture in the
1359    // album.
1360    //
1361    // 2. The camera is shown in full screen.
1362    private void checkHideUndoBar(int addition) {
1363        mUndoBarState |= addition;
1364        if ((mUndoBarState & UNDO_BAR_SHOW) == 0) return;
1365        boolean timeout = (mUndoBarState & UNDO_BAR_TIMEOUT) != 0;
1366        boolean touched = (mUndoBarState & UNDO_BAR_TOUCHED) != 0;
1367        boolean fullCamera = (mUndoBarState & UNDO_BAR_FULL_CAMERA) != 0;
1368        boolean deleteLast = (mUndoBarState & UNDO_BAR_DELETE_LAST) != 0;
1369        if ((timeout && (touched || deleteLast)) || fullCamera) {
1370            hideUndoBar();
1371        }
1372    }
1373
1374    // Returns true if the user can still undo the deletion of the last
1375    // remaining picture in the album. We need to check this and delay making
1376    // the camera preview full screen, otherwise the user won't have a chance to
1377    // undo it.
1378    private boolean canUndoLastPicture() {
1379        if ((mUndoBarState & UNDO_BAR_SHOW) == 0) return false;
1380        return (mUndoBarState & UNDO_BAR_DELETE_LAST) != 0;
1381    }
1382
1383    ////////////////////////////////////////////////////////////////////////////
1384    //  Rendering
1385    ////////////////////////////////////////////////////////////////////////////
1386
1387    @Override
1388    protected void render(GLCanvas canvas) {
1389        // Check if the camera preview occupies the full screen.
1390        boolean full = !mFilmMode && mPictures.get(0).isCamera()
1391                && mPositionController.isCenter()
1392                && mPositionController.isAtMinimalScale();
1393        if (full != mFullScreenCamera) {
1394            mFullScreenCamera = full;
1395            mListener.onFullScreenChanged(full);
1396            if (full) mHandler.sendEmptyMessage(MSG_UNDO_BAR_FULL_CAMERA);
1397        }
1398
1399        // Determine how many photos we need to draw in addition to the center
1400        // one.
1401        int neighbors;
1402        if (mFullScreenCamera) {
1403            neighbors = 0;
1404        } else {
1405            // In page mode, we draw only one previous/next photo. But if we are
1406            // doing capture animation, we want to draw all photos.
1407            boolean inPageMode = (mPositionController.getFilmRatio() == 0f);
1408            boolean inCaptureAnimation =
1409                    ((mHolding & HOLD_CAPTURE_ANIMATION) != 0);
1410            if (inPageMode && !inCaptureAnimation) {
1411                neighbors = 1;
1412            } else {
1413                neighbors = SCREEN_NAIL_MAX;
1414            }
1415        }
1416
1417        // Draw photos from back to front
1418        for (int i = neighbors; i >= -neighbors; i--) {
1419            Rect r = mPositionController.getPosition(i);
1420            mPictures.get(i).draw(canvas, r);
1421        }
1422
1423        renderChild(canvas, mEdgeView);
1424        renderChild(canvas, mUndoBar);
1425
1426        mPositionController.advanceAnimation();
1427        checkFocusSwitching();
1428    }
1429
1430    ////////////////////////////////////////////////////////////////////////////
1431    //  Film mode focus switching
1432    ////////////////////////////////////////////////////////////////////////////
1433
1434    // Runs in GL thread.
1435    private void checkFocusSwitching() {
1436        if (!mFilmMode) return;
1437        if (mHandler.hasMessages(MSG_SWITCH_FOCUS)) return;
1438        if (switchPosition() != 0) {
1439            mHandler.sendEmptyMessage(MSG_SWITCH_FOCUS);
1440        }
1441    }
1442
1443    // Runs in main thread.
1444    private void switchFocus() {
1445        if (mHolding != 0) return;
1446        switch (switchPosition()) {
1447            case -1:
1448                switchToPrevImage();
1449                break;
1450            case 1:
1451                switchToNextImage();
1452                break;
1453        }
1454    }
1455
1456    // Returns -1 if we should switch focus to the previous picture, +1 if we
1457    // should switch to the next, 0 otherwise.
1458    private int switchPosition() {
1459        Rect curr = mPositionController.getPosition(0);
1460        int center = getWidth() / 2;
1461
1462        if (curr.left > center && mPrevBound < 0) {
1463            Rect prev = mPositionController.getPosition(-1);
1464            int currDist = curr.left - center;
1465            int prevDist = center - prev.right;
1466            if (prevDist < currDist) {
1467                return -1;
1468            }
1469        } else if (curr.right < center && mNextBound > 0) {
1470            Rect next = mPositionController.getPosition(1);
1471            int currDist = center - curr.right;
1472            int nextDist = next.left - center;
1473            if (nextDist < currDist) {
1474                return 1;
1475            }
1476        }
1477
1478        return 0;
1479    }
1480
1481    // Switch to the previous or next picture if the hit position is inside
1482    // one of their boxes. This runs in main thread.
1483    private void switchToHitPicture(int x, int y) {
1484        if (mPrevBound < 0) {
1485            Rect r = mPositionController.getPosition(-1);
1486            if (r.right >= x) {
1487                slideToPrevPicture();
1488                return;
1489            }
1490        }
1491
1492        if (mNextBound > 0) {
1493            Rect r = mPositionController.getPosition(1);
1494            if (r.left <= x) {
1495                slideToNextPicture();
1496                return;
1497            }
1498        }
1499    }
1500
1501    ////////////////////////////////////////////////////////////////////////////
1502    //  Page mode focus switching
1503    //
1504    //  We slide image to the next one or the previous one in two cases: 1: If
1505    //  the user did a fling gesture with enough velocity.  2 If the user has
1506    //  moved the picture a lot.
1507    ////////////////////////////////////////////////////////////////////////////
1508
1509    private boolean swipeImages(float velocityX, float velocityY) {
1510        if (mFilmMode) return false;
1511
1512        // Avoid swiping images if we're possibly flinging to view the
1513        // zoomed in picture vertically.
1514        PositionController controller = mPositionController;
1515        boolean isMinimal = controller.isAtMinimalScale();
1516        int edges = controller.getImageAtEdges();
1517        if (!isMinimal && Math.abs(velocityY) > Math.abs(velocityX))
1518            if ((edges & PositionController.IMAGE_AT_TOP_EDGE) == 0
1519                    || (edges & PositionController.IMAGE_AT_BOTTOM_EDGE) == 0)
1520                return false;
1521
1522        // If we are at the edge of the current photo and the sweeping velocity
1523        // exceeds the threshold, slide to the next / previous image.
1524        if (velocityX < -SWIPE_THRESHOLD && (isMinimal
1525                || (edges & PositionController.IMAGE_AT_RIGHT_EDGE) != 0)) {
1526            return slideToNextPicture();
1527        } else if (velocityX > SWIPE_THRESHOLD && (isMinimal
1528                || (edges & PositionController.IMAGE_AT_LEFT_EDGE) != 0)) {
1529            return slideToPrevPicture();
1530        }
1531
1532        return false;
1533    }
1534
1535    private void snapback() {
1536        if ((mHolding & ~HOLD_DELETE) != 0) return;
1537        if (!snapToNeighborImage()) {
1538            mPositionController.snapback();
1539        }
1540    }
1541
1542    private boolean snapToNeighborImage() {
1543        if (mFilmMode) return false;
1544
1545        Rect r = mPositionController.getPosition(0);
1546        int viewW = getWidth();
1547        // Setting the move threshold proportional to the width of the view
1548        int moveThreshold = viewW / 5 ;
1549        int threshold = moveThreshold + gapToSide(r.width(), viewW);
1550
1551        // If we have moved the picture a lot, switching.
1552        if (viewW - r.right > threshold) {
1553            return slideToNextPicture();
1554        } else if (r.left > threshold) {
1555            return slideToPrevPicture();
1556        }
1557
1558        return false;
1559    }
1560
1561    private boolean slideToNextPicture() {
1562        if (mNextBound <= 0) return false;
1563        switchToNextImage();
1564        mPositionController.startHorizontalSlide();
1565        return true;
1566    }
1567
1568    private boolean slideToPrevPicture() {
1569        if (mPrevBound >= 0) return false;
1570        switchToPrevImage();
1571        mPositionController.startHorizontalSlide();
1572        return true;
1573    }
1574
1575    private static int gapToSide(int imageWidth, int viewWidth) {
1576        return Math.max(0, (viewWidth - imageWidth) / 2);
1577    }
1578
1579    ////////////////////////////////////////////////////////////////////////////
1580    //  Focus switching
1581    ////////////////////////////////////////////////////////////////////////////
1582
1583    public void switchToImage(int index) {
1584        mModel.moveTo(index);
1585    }
1586
1587    private void switchToNextImage() {
1588        mModel.moveTo(mModel.getCurrentIndex() + 1);
1589    }
1590
1591    private void switchToPrevImage() {
1592        mModel.moveTo(mModel.getCurrentIndex() - 1);
1593    }
1594
1595    private void switchToFirstImage() {
1596        mModel.moveTo(0);
1597    }
1598
1599    ////////////////////////////////////////////////////////////////////////////
1600    //  Opening Animation
1601    ////////////////////////////////////////////////////////////////////////////
1602
1603    public void setOpenAnimationRect(Rect rect) {
1604        mPositionController.setOpenAnimationRect(rect);
1605    }
1606
1607    ////////////////////////////////////////////////////////////////////////////
1608    //  Capture Animation
1609    ////////////////////////////////////////////////////////////////////////////
1610
1611    public boolean switchWithCaptureAnimation(int offset) {
1612        GLRoot root = getGLRoot();
1613        if(root == null) return false;
1614        root.lockRenderThread();
1615        try {
1616            return switchWithCaptureAnimationLocked(offset);
1617        } finally {
1618            root.unlockRenderThread();
1619        }
1620    }
1621
1622    private boolean switchWithCaptureAnimationLocked(int offset) {
1623        if (mHolding != 0) return true;
1624        if (offset == 1) {
1625            if (mNextBound <= 0) return false;
1626            // Temporary disable action bar until the capture animation is done.
1627            if (!mFilmMode) mListener.onActionBarAllowed(false);
1628            switchToNextImage();
1629            mPositionController.startCaptureAnimationSlide(-1);
1630        } else if (offset == -1) {
1631            if (mPrevBound >= 0) return false;
1632            if (mFilmMode) setFilmMode(false);
1633
1634            // If we are too far away from the first image (so that we don't
1635            // have all the ScreenNails in-between), we go directly without
1636            // animation.
1637            if (mModel.getCurrentIndex() > SCREEN_NAIL_MAX) {
1638                switchToFirstImage();
1639                mPositionController.skipToFinalPosition();
1640                return true;
1641            }
1642
1643            switchToFirstImage();
1644            mPositionController.startCaptureAnimationSlide(1);
1645        } else {
1646            return false;
1647        }
1648        mHolding |= HOLD_CAPTURE_ANIMATION;
1649        Message m = mHandler.obtainMessage(MSG_CAPTURE_ANIMATION_DONE, offset, 0);
1650        mHandler.sendMessageDelayed(m, PositionController.CAPTURE_ANIMATION_TIME);
1651        return true;
1652    }
1653
1654    private void captureAnimationDone(int offset) {
1655        mHolding &= ~HOLD_CAPTURE_ANIMATION;
1656        if (offset == 1 && !mFilmMode) {
1657            // Now the capture animation is done, enable the action bar.
1658            mListener.onActionBarAllowed(true);
1659            mListener.onActionBarWanted();
1660        }
1661        snapback();
1662    }
1663
1664    ////////////////////////////////////////////////////////////////////////////
1665    //  Card deck effect calculation
1666    ////////////////////////////////////////////////////////////////////////////
1667
1668    // Returns the scrolling progress value for an object moving out of a
1669    // view. The progress value measures how much the object has moving out of
1670    // the view. The object currently displays in [left, right), and the view is
1671    // at [0, viewWidth].
1672    //
1673    // The returned value is negative when the object is moving right, and
1674    // positive when the object is moving left. The value goes to -1 or 1 when
1675    // the object just moves out of the view completely. The value is 0 if the
1676    // object currently fills the view.
1677    private static float calculateMoveOutProgress(int left, int right,
1678            int viewWidth) {
1679        // w = object width
1680        // viewWidth = view width
1681        int w = right - left;
1682
1683        // If the object width is smaller than the view width,
1684        //      |....view....|
1685        //                   |<-->|      progress = -1 when left = viewWidth
1686        //          |<-->|               progress = 0 when left = viewWidth / 2 - w / 2
1687        // |<-->|                        progress = 1 when left = -w
1688        if (w < viewWidth) {
1689            int zx = viewWidth / 2 - w / 2;
1690            if (left > zx) {
1691                return -(left - zx) / (float) (viewWidth - zx);  // progress = (0, -1]
1692            } else {
1693                return (left - zx) / (float) (-w - zx);  // progress = [0, 1]
1694            }
1695        }
1696
1697        // If the object width is larger than the view width,
1698        //             |..view..|
1699        //                      |<--------->| progress = -1 when left = viewWidth
1700        //             |<--------->|          progress = 0 between left = 0
1701        //          |<--------->|                          and right = viewWidth
1702        // |<--------->|                      progress = 1 when right = 0
1703        if (left > 0) {
1704            return -left / (float) viewWidth;
1705        }
1706
1707        if (right < viewWidth) {
1708            return (viewWidth - right) / (float) viewWidth;
1709        }
1710
1711        return 0;
1712    }
1713
1714    // Maps a scrolling progress value to the alpha factor in the fading
1715    // animation.
1716    private float getScrollAlpha(float scrollProgress) {
1717        return scrollProgress < 0 ? mAlphaInterpolator.getInterpolation(
1718                     1 - Math.abs(scrollProgress)) : 1.0f;
1719    }
1720
1721    // Maps a scrolling progress value to the scaling factor in the fading
1722    // animation.
1723    private float getScrollScale(float scrollProgress) {
1724        float interpolatedProgress = mScaleInterpolator.getInterpolation(
1725                Math.abs(scrollProgress));
1726        float scale = (1 - interpolatedProgress) +
1727                interpolatedProgress * TRANSITION_SCALE_FACTOR;
1728        return scale;
1729    }
1730
1731
1732    // This interpolator emulates the rate at which the perceived scale of an
1733    // object changes as its distance from a camera increases. When this
1734    // interpolator is applied to a scale animation on a view, it evokes the
1735    // sense that the object is shrinking due to moving away from the camera.
1736    private static class ZInterpolator {
1737        private float focalLength;
1738
1739        public ZInterpolator(float foc) {
1740            focalLength = foc;
1741        }
1742
1743        public float getInterpolation(float input) {
1744            return (1.0f - focalLength / (focalLength + input)) /
1745                (1.0f - focalLength / (focalLength + 1.0f));
1746        }
1747    }
1748
1749    // Returns an interpolated value for the page/film transition.
1750    // When ratio = 0, the result is from.
1751    // When ratio = 1, the result is to.
1752    private static float interpolate(float ratio, float from, float to) {
1753        return from + (to - from) * ratio * ratio;
1754    }
1755
1756    // Returns the alpha factor in film mode if a picture is not in the center.
1757    // The 0.03 lower bound is to make the item always visible a bit.
1758    private float getOffsetAlpha(float offset) {
1759        offset /= 0.5f;
1760        float alpha = (offset > 0) ? (1 - offset) : (1 + offset);
1761        return Utils.clamp(alpha, 0.03f, 1f);
1762    }
1763
1764    ////////////////////////////////////////////////////////////////////////////
1765    //  Simple public utilities
1766    ////////////////////////////////////////////////////////////////////////////
1767
1768    public void setListener(Listener listener) {
1769        mListener = listener;
1770    }
1771
1772    public Rect getPhotoRect(int index) {
1773        return mPositionController.getPosition(index);
1774    }
1775
1776    public PhotoFallbackEffect buildFallbackEffect(GLView root, GLCanvas canvas) {
1777        Rect location = new Rect();
1778        Utils.assertTrue(root.getBoundsOf(this, location));
1779
1780        Rect fullRect = bounds();
1781        PhotoFallbackEffect effect = new PhotoFallbackEffect();
1782        for (int i = -SCREEN_NAIL_MAX; i <= SCREEN_NAIL_MAX; ++i) {
1783            MediaItem item = mModel.getMediaItem(i);
1784            if (item == null) continue;
1785            ScreenNail sc = mModel.getScreenNail(i);
1786            if (!(sc instanceof BitmapScreenNail)
1787                    || ((BitmapScreenNail) sc).isShowingPlaceholder()) continue;
1788
1789            // Now, sc is BitmapScreenNail and is not showing placeholder
1790            Rect rect = new Rect(getPhotoRect(i));
1791            if (!Rect.intersects(fullRect, rect)) continue;
1792            rect.offset(location.left, location.top);
1793
1794            int width = sc.getWidth();
1795            int height = sc.getHeight();
1796
1797            int rotation = mModel.getImageRotation(i);
1798            RawTexture texture;
1799            if ((rotation % 180) == 0) {
1800                texture = new RawTexture(width, height, true);
1801                canvas.beginRenderTarget(texture);
1802                canvas.translate(width / 2f, height / 2f);
1803            } else {
1804                texture = new RawTexture(height, width, true);
1805                canvas.beginRenderTarget(texture);
1806                canvas.translate(height / 2f, width / 2f);
1807            }
1808
1809            canvas.rotate(rotation, 0, 0, 1);
1810            canvas.translate(-width / 2f, -height / 2f);
1811            sc.draw(canvas, 0, 0, width, height);
1812            canvas.endRenderTarget();
1813            effect.addEntry(item.getPath(), rect, texture);
1814        }
1815        return effect;
1816    }
1817}
1818