OSDN Git Service

am 7dabda68: Show capturing UI before review UI in intent countdown timer
[android-x86/packages-apps-Camera2.git] / src / com / android / camera / widget / FilmstripView.java
1 /*
2  * Copyright (C) 2013 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
17 package com.android.camera.widget;
18
19 import android.animation.Animator;
20 import android.animation.AnimatorSet;
21 import android.animation.TimeInterpolator;
22 import android.animation.ValueAnimator;
23 import android.annotation.TargetApi;
24 import android.content.Context;
25 import android.graphics.Canvas;
26 import android.graphics.Point;
27 import android.graphics.Rect;
28 import android.graphics.RectF;
29 import android.net.Uri;
30 import android.os.Build;
31 import android.os.Bundle;
32 import android.os.Handler;
33 import android.os.SystemClock;
34 import android.util.AttributeSet;
35 import android.util.DisplayMetrics;
36 import android.util.SparseArray;
37 import android.view.KeyEvent;
38 import android.view.MotionEvent;
39 import android.view.View;
40 import android.view.ViewGroup;
41 import android.view.accessibility.AccessibilityNodeInfo;
42 import android.view.animation.DecelerateInterpolator;
43 import android.widget.Scroller;
44
45 import com.android.camera.CameraActivity;
46 import com.android.camera.debug.Log;
47 import com.android.camera.filmstrip.DataAdapter;
48 import com.android.camera.filmstrip.FilmstripController;
49 import com.android.camera.filmstrip.ImageData;
50 import com.android.camera.ui.FilmstripGestureRecognizer;
51 import com.android.camera.ui.ZoomView;
52 import com.android.camera.util.ApiHelper;
53 import com.android.camera.util.CameraUtil;
54 import com.android.camera2.R;
55
56 import java.util.ArrayDeque;
57 import java.util.Arrays;
58 import java.util.Queue;
59
60 public class FilmstripView extends ViewGroup {
61     private static final Log.Tag TAG = new Log.Tag("FilmstripView");
62
63     private static final int BUFFER_SIZE = 5;
64     private static final int GEOMETRY_ADJUST_TIME_MS = 400;
65     private static final int SNAP_IN_CENTER_TIME_MS = 600;
66     private static final float FLING_COASTING_DURATION_S = 0.05f;
67     private static final int ZOOM_ANIMATION_DURATION_MS = 200;
68     private static final int CAMERA_PREVIEW_SWIPE_THRESHOLD = 300;
69     private static final float FILM_STRIP_SCALE = 0.7f;
70     private static final float FULL_SCREEN_SCALE = 1f;
71
72     // The min velocity at which the user must have moved their finger in
73     // pixels per millisecond to count a vertical gesture as a promote/demote
74     // at short vertical distances.
75     private static final float PROMOTE_VELOCITY = 3.5f;
76     // The min distance relative to this view's height the user must have
77     // moved their finger to count a vertical gesture as a promote/demote if
78     // they moved their finger at least at PROMOTE_VELOCITY.
79     private static final float VELOCITY_PROMOTE_HEIGHT_RATIO = 1/10f;
80     // The min distance relative to this view's height the user must have
81     // moved their finger to count a vertical gesture as a promote/demote if
82     // they moved their finger at less than PROMOTE_VELOCITY.
83     private static final float PROMOTE_HEIGHT_RATIO = 1/2f;
84
85     private static final float TOLERANCE = 0.1f;
86     // Only check for intercepting touch events within first 500ms
87     private static final int SWIPE_TIME_OUT = 500;
88     private static final int DECELERATION_FACTOR = 4;
89     private static final float MOUSE_SCROLL_FACTOR = 128f;
90
91     private CameraActivity mActivity;
92     private FilmstripGestureRecognizer mGestureRecognizer;
93     private FilmstripGestureRecognizer.Listener mGestureListener;
94     private DataAdapter mDataAdapter;
95     private int mViewGapInPixel;
96     private final Rect mDrawArea = new Rect();
97
98     private final int mCurrentItem = (BUFFER_SIZE - 1) / 2;
99     private float mScale;
100     private MyController mController;
101     private int mCenterX = -1;
102     private final ViewItem[] mViewItem = new ViewItem[BUFFER_SIZE];
103
104     private FilmstripController.FilmstripListener mListener;
105     private ZoomView mZoomView = null;
106
107     private MotionEvent mDown;
108     private boolean mCheckToIntercept = true;
109     private int mSlop;
110     private TimeInterpolator mViewAnimInterpolator;
111
112     // This is true if and only if the user is scrolling,
113     private boolean mIsUserScrolling;
114     private int mDataIdOnUserScrolling;
115     private float mOverScaleFactor = 1f;
116
117     private boolean mFullScreenUIHidden = false;
118     private final SparseArray<Queue<View>> recycledViews = new SparseArray<Queue<View>>();
119
120     /**
121      * A helper class to tract and calculate the view coordination.
122      */
123     private class ViewItem {
124         private int mDataId;
125         /** The position of the left of the view in the whole filmstrip. */
126         private int mLeftPosition;
127         private final View mView;
128         private final ImageData mData;
129         private final RectF mViewArea;
130         private boolean mMaximumBitmapRequested;
131
132         private ValueAnimator mTranslationXAnimator;
133         private ValueAnimator mTranslationYAnimator;
134         private ValueAnimator mAlphaAnimator;
135
136         /**
137          * Constructor.
138          *
139          * @param id The id of the data from
140          *            {@link com.android.camera.filmstrip.DataAdapter}.
141          * @param v The {@code View} representing the data.
142          */
143         public ViewItem(int id, View v, ImageData data) {
144             v.setPivotX(0f);
145             v.setPivotY(0f);
146             mDataId = id;
147             mData = data;
148             mView = v;
149             mMaximumBitmapRequested = false;
150             mLeftPosition = -1;
151             mViewArea = new RectF();
152         }
153
154         public boolean isMaximumBitmapRequested() {
155             return mMaximumBitmapRequested;
156         }
157
158         public void setMaximumBitmapRequested() {
159             mMaximumBitmapRequested = true;
160         }
161
162         /**
163          * Returns the data id from
164          * {@link com.android.camera.filmstrip.DataAdapter}.
165          */
166         public int getId() {
167             return mDataId;
168         }
169
170         /**
171          * Sets the data id from
172          * {@link com.android.camera.filmstrip.DataAdapter}.
173          */
174         public void setId(int id) {
175             mDataId = id;
176         }
177
178         /** Sets the left position of the view in the whole filmstrip. */
179         public void setLeftPosition(int pos) {
180             mLeftPosition = pos;
181         }
182
183         /** Returns the left position of the view in the whole filmstrip. */
184         public int getLeftPosition() {
185             return mLeftPosition;
186         }
187
188         /** Returns the translation of Y regarding the view scale. */
189         public float getTranslationY() {
190             return mView.getTranslationY() / mScale;
191         }
192
193         /** Returns the translation of X regarding the view scale. */
194         public float getTranslationX() {
195             return mView.getTranslationX() / mScale;
196         }
197
198         /** Sets the translation of Y regarding the view scale. */
199         public void setTranslationY(float transY) {
200             mView.setTranslationY(transY * mScale);
201         }
202
203         /** Sets the translation of X regarding the view scale. */
204         public void setTranslationX(float transX) {
205             mView.setTranslationX(transX * mScale);
206         }
207
208         /** Forwarding of {@link android.view.View#setAlpha(float)}. */
209         public void setAlpha(float alpha) {
210             mView.setAlpha(alpha);
211         }
212
213         /** Forwarding of {@link android.view.View#getAlpha()}. */
214         public float getAlpha() {
215             return mView.getAlpha();
216         }
217
218         /** Forwarding of {@link android.view.View#getMeasuredWidth()}. */
219         public int getMeasuredWidth() {
220             return mView.getMeasuredWidth();
221         }
222
223         /**
224          * Animates the X translation of the view. Note: the animated value is
225          * not set directly by {@link android.view.View#setTranslationX(float)}
226          * because the value might be changed during in {@code onLayout()}.
227          * The animated value of X translation is specially handled in {@code
228          * layoutIn()}.
229          *
230          * @param targetX The final value.
231          * @param duration_ms The duration of the animation.
232          * @param interpolator Time interpolator.
233          */
234         public void animateTranslationX(
235                 float targetX, long duration_ms, TimeInterpolator interpolator) {
236             if (mTranslationXAnimator == null) {
237                 mTranslationXAnimator = new ValueAnimator();
238                 mTranslationXAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
239                     @Override
240                     public void onAnimationUpdate(ValueAnimator valueAnimator) {
241                         // We invalidate the filmstrip view instead of setting the
242                         // translation X because the translation X of the view is
243                         // touched in onLayout(). See the documentation of
244                         // animateTranslationX().
245                         invalidate();
246                     }
247                 });
248             }
249             runAnimation(mTranslationXAnimator, getTranslationX(), targetX, duration_ms,
250                     interpolator);
251         }
252
253         /**
254          * Animates the Y translation of the view.
255          *
256          * @param targetY The final value.
257          * @param duration_ms The duration of the animation.
258          * @param interpolator Time interpolator.
259          */
260         public void animateTranslationY(
261                 float targetY, long duration_ms, TimeInterpolator interpolator) {
262             if (mTranslationYAnimator == null) {
263                 mTranslationYAnimator = new ValueAnimator();
264                 mTranslationYAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
265                     @Override
266                     public void onAnimationUpdate(ValueAnimator valueAnimator) {
267                         setTranslationY((Float) valueAnimator.getAnimatedValue());
268                     }
269                 });
270             }
271             runAnimation(mTranslationYAnimator, getTranslationY(), targetY, duration_ms,
272                     interpolator);
273         }
274
275         /**
276          * Animates the alpha value of the view.
277          *
278          * @param targetAlpha The final value.
279          * @param duration_ms The duration of the animation.
280          * @param interpolator Time interpolator.
281          */
282         public void animateAlpha(float targetAlpha, long duration_ms,
283                 TimeInterpolator interpolator) {
284             if (mAlphaAnimator == null) {
285                 mAlphaAnimator = new ValueAnimator();
286                 mAlphaAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
287                     @Override
288                     public void onAnimationUpdate(ValueAnimator valueAnimator) {
289                         ViewItem.this.setAlpha((Float) valueAnimator.getAnimatedValue());
290                     }
291                 });
292             }
293             runAnimation(mAlphaAnimator, getAlpha(), targetAlpha, duration_ms, interpolator);
294         }
295
296         private void runAnimation(final ValueAnimator animator, final float startValue,
297                 final float targetValue, final long duration_ms,
298                 final TimeInterpolator interpolator) {
299             if (startValue == targetValue) {
300                 return;
301             }
302             animator.setInterpolator(interpolator);
303             animator.setDuration(duration_ms);
304             animator.setFloatValues(startValue, targetValue);
305             animator.start();
306         }
307
308         /** Adjusts the translation of X regarding the view scale. */
309         public void translateXScaledBy(float transX) {
310             setTranslationX(getTranslationX() + transX * mScale);
311         }
312
313         /**
314          * Forwarding of {@link android.view.View#getHitRect(android.graphics.Rect)}.
315          */
316         public void getHitRect(Rect rect) {
317             mView.getHitRect(rect);
318         }
319
320         public int getCenterX() {
321             return mLeftPosition + mView.getMeasuredWidth() / 2;
322         }
323
324         /** Forwarding of {@link android.view.View#getVisibility()}. */
325         public int getVisibility() {
326             return mView.getVisibility();
327         }
328
329         /** Forwarding of {@link android.view.View#setVisibility(int)}. */
330         public void setVisibility(int visibility) {
331             mView.setVisibility(visibility);
332         }
333
334         /**
335          * Notifies the {@link com.android.camera.filmstrip.DataAdapter} to
336          * resize the view.
337          */
338         public void resizeView(Context context, int w, int h) {
339             mDataAdapter.resizeView(context, mDataId, mView, w, h);
340         }
341
342         /**
343          * Adds the view of the data to the view hierarchy if necessary.
344          */
345         public void addViewToHierarchy() {
346             if (indexOfChild(mView) < 0) {
347                 mData.prepare();
348                 addView(mView);
349             }
350
351             setVisibility(View.VISIBLE);
352             setAlpha(1f);
353             setTranslationX(0);
354             setTranslationY(0);
355         }
356
357         /**
358          * Removes from the hierarchy. Keeps the view in the view hierarchy if
359          * view type is {@code VIEW_TYPE_STICKY} and set to invisible instead.
360          *
361          * @param force {@code true} to remove the view from the hierarchy
362          *                          regardless of the view type.
363          */
364         public void removeViewFromHierarchy(boolean force) {
365             if (force || mData.getViewType() != ImageData.VIEW_TYPE_STICKY) {
366                 removeView(mView);
367                 mData.recycle(mView);
368                 recycleView(mView, mDataId);
369             } else {
370                 setVisibility(View.INVISIBLE);
371             }
372         }
373
374         /**
375          * Brings the view to front by
376          * {@link #bringChildToFront(android.view.View)}
377          */
378         public void bringViewToFront() {
379             bringChildToFront(mView);
380         }
381
382         /**
383          * The visual x position of this view, in pixels.
384          */
385         public float getX() {
386             return mView.getX();
387         }
388
389         /**
390          * The visual y position of this view, in pixels.
391          */
392         public float getY() {
393             return mView.getY();
394         }
395
396         /**
397          * Forwarding of {@link android.view.View#measure(int, int)}.
398          */
399         public void measure(int widthSpec, int heightSpec) {
400             mView.measure(widthSpec, heightSpec);
401         }
402
403         private void layoutAt(int left, int top) {
404             mView.layout(left, top, left + mView.getMeasuredWidth(),
405                     top + mView.getMeasuredHeight());
406         }
407
408         /**
409          * The bounding rect of the view.
410          */
411         public RectF getViewRect() {
412             RectF r = new RectF();
413             r.left = mView.getX();
414             r.top = mView.getY();
415             r.right = r.left + mView.getWidth() * mView.getScaleX();
416             r.bottom = r.top + mView.getHeight() * mView.getScaleY();
417             return r;
418         }
419
420         private View getView() {
421             return mView;
422         }
423
424         /**
425          * Layouts the view in the area assuming the center of the area is at a
426          * specific point of the whole filmstrip.
427          *
428          * @param drawArea The area when filmstrip will show in.
429          * @param refCenter The absolute X coordination in the whole filmstrip
430          *            of the center of {@code drawArea}.
431          * @param scale The scale of the view on the filmstrip.
432          */
433         public void layoutWithTranslationX(Rect drawArea, int refCenter, float scale) {
434             final float translationX =
435                     ((mTranslationXAnimator != null && mTranslationXAnimator.isRunning()) ?
436                             (Float) mTranslationXAnimator.getAnimatedValue() : 0);
437             int left =
438                     (int) (drawArea.centerX() + (mLeftPosition - refCenter + translationX) * scale);
439             int top = (int) (drawArea.centerY() - (mView.getMeasuredHeight() / 2) * scale);
440             layoutAt(left, top);
441             mView.setScaleX(scale);
442             mView.setScaleY(scale);
443
444             // update mViewArea for touch detection.
445             int l = mView.getLeft();
446             int t = mView.getTop();
447             mViewArea.set(l, t,
448                     l + mView.getMeasuredWidth() * scale,
449                     t + mView.getMeasuredHeight() * scale);
450         }
451
452         /** Returns true if the point is in the view. */
453         public boolean areaContains(float x, float y) {
454             return mViewArea.contains(x, y);
455         }
456
457         /**
458          * Return the width of the view.
459          */
460         public int getWidth() {
461             return mView.getWidth();
462         }
463
464         /**
465          * Returns the position of the left edge of the view area content is drawn in.
466          */
467         public int getDrawAreaLeft() {
468             return Math.round(mViewArea.left);
469         }
470
471         public void copyAttributes(ViewItem item) {
472             setLeftPosition(item.getLeftPosition());
473             // X
474             setTranslationX(item.getTranslationX());
475             if (item.mTranslationXAnimator != null) {
476                 mTranslationXAnimator = item.mTranslationXAnimator;
477                 mTranslationXAnimator.removeAllUpdateListeners();
478                 mTranslationXAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
479                     @Override
480                     public void onAnimationUpdate(ValueAnimator valueAnimator) {
481                         // We invalidate the filmstrip view instead of setting the
482                         // translation X because the translation X of the view is
483                         // touched in onLayout(). See the documentation of
484                         // animateTranslationX().
485                         invalidate();
486                     }
487                 });
488             }
489             // Y
490             setTranslationY(item.getTranslationY());
491             if (item.mTranslationYAnimator != null) {
492                 mTranslationYAnimator = item.mTranslationYAnimator;
493                 mTranslationYAnimator.removeAllUpdateListeners();
494                 mTranslationYAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
495                     @Override
496                     public void onAnimationUpdate(ValueAnimator valueAnimator) {
497                         setTranslationY((Float) valueAnimator.getAnimatedValue());
498                     }
499                 });
500             }
501             // Alpha
502             setAlpha(item.getAlpha());
503             if (item.mAlphaAnimator != null) {
504                 mAlphaAnimator = item.mAlphaAnimator;
505                 mAlphaAnimator.removeAllUpdateListeners();
506                 mAlphaAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
507                     @Override
508                     public void onAnimationUpdate(ValueAnimator valueAnimator) {
509                         ViewItem.this.setAlpha((Float) valueAnimator.getAnimatedValue());
510                     }
511                 });
512             }
513         }
514
515         /**
516          * Apply a scale factor (i.e. {@code postScale}) on top of current scale at
517          * pivot point ({@code focusX}, {@code focusY}). Visually it should be the
518          * same as post concatenating current view's matrix with specified scale.
519          */
520         void postScale(float focusX, float focusY, float postScale, int viewportWidth,
521                 int viewportHeight) {
522             float transX = mView.getTranslationX();
523             float transY = mView.getTranslationY();
524             // Pivot point is top left of the view, so we need to translate
525             // to scale around focus point
526             transX -= (focusX - getX()) * (postScale - 1f);
527             transY -= (focusY - getY()) * (postScale - 1f);
528             float scaleX = mView.getScaleX() * postScale;
529             float scaleY = mView.getScaleY() * postScale;
530             updateTransform(transX, transY, scaleX, scaleY, viewportWidth,
531                     viewportHeight);
532         }
533
534         void updateTransform(float transX, float transY, float scaleX, float scaleY,
535                 int viewportWidth, int viewportHeight) {
536             float left = transX + mView.getLeft();
537             float top = transY + mView.getTop();
538             RectF r = ZoomView.adjustToFitInBounds(new RectF(left, top,
539                     left + mView.getWidth() * scaleX,
540                     top + mView.getHeight() * scaleY),
541                     viewportWidth, viewportHeight);
542             mView.setScaleX(scaleX);
543             mView.setScaleY(scaleY);
544             transX = r.left - mView.getLeft();
545             transY = r.top - mView.getTop();
546             mView.setTranslationX(transX);
547             mView.setTranslationY(transY);
548         }
549
550         void resetTransform() {
551             mView.setScaleX(FULL_SCREEN_SCALE);
552             mView.setScaleY(FULL_SCREEN_SCALE);
553             mView.setTranslationX(0f);
554             mView.setTranslationY(0f);
555         }
556
557         @Override
558         public String toString() {
559             return "DataID = " + mDataId + "\n\t left = " + mLeftPosition
560                     + "\n\t viewArea = " + mViewArea
561                     + "\n\t centerX = " + getCenterX()
562                     + "\n\t view MeasuredSize = "
563                     + mView.getMeasuredWidth() + ',' + mView.getMeasuredHeight()
564                     + "\n\t view Size = " + mView.getWidth() + ',' + mView.getHeight()
565                     + "\n\t view scale = " + mView.getScaleX();
566         }
567     }
568
569     /** Constructor. */
570     public FilmstripView(Context context) {
571         super(context);
572         init((CameraActivity) context);
573     }
574
575     /** Constructor. */
576     public FilmstripView(Context context, AttributeSet attrs) {
577         super(context, attrs);
578         init((CameraActivity) context);
579     }
580
581     /** Constructor. */
582     public FilmstripView(Context context, AttributeSet attrs, int defStyle) {
583         super(context, attrs, defStyle);
584         init((CameraActivity) context);
585     }
586
587     private void init(CameraActivity cameraActivity) {
588         setWillNotDraw(false);
589         mActivity = cameraActivity;
590         mScale = 1.0f;
591         mDataIdOnUserScrolling = 0;
592         mController = new MyController(cameraActivity);
593         mViewAnimInterpolator = new DecelerateInterpolator();
594         mZoomView = new ZoomView(cameraActivity);
595         mZoomView.setVisibility(GONE);
596         addView(mZoomView);
597
598         mGestureListener = new MyGestureReceiver();
599         mGestureRecognizer =
600                 new FilmstripGestureRecognizer(cameraActivity, mGestureListener);
601         mSlop = (int) getContext().getResources().getDimension(R.dimen.pie_touch_slop);
602         DisplayMetrics metrics = new DisplayMetrics();
603         mActivity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
604         // Allow over scaling because on high density screens, pixels are too
605         // tiny to clearly see the details at 1:1 zoom. We should not scale
606         // beyond what 1:1 would look like on a medium density screen, as
607         // scaling beyond that would only yield blur.
608         mOverScaleFactor = (float) metrics.densityDpi / (float) DisplayMetrics.DENSITY_HIGH;
609         if (mOverScaleFactor < 1f) {
610             mOverScaleFactor = 1f;
611         }
612
613         setAccessibilityDelegate(new AccessibilityDelegate() {
614             @Override
615             public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
616                 super.onInitializeAccessibilityNodeInfo(host, info);
617
618                 info.setClassName(FilmstripView.class.getName());
619                 info.setScrollable(true);
620                 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
621                 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
622             }
623
624             @Override
625             public boolean performAccessibilityAction(View host, int action, Bundle args) {
626                 if (!mController.isScrolling()) {
627                     switch (action) {
628                         case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: {
629                             mController.goToNextItem();
630                             return true;
631                         }
632                         case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: {
633                             boolean wentToPrevious = mController.goToPreviousItem();
634                             if (!wentToPrevious) {
635                                 // at beginning of filmstrip, hide and go back to preview
636                                 mActivity.getCameraAppUI().hideFilmstrip();
637                             }
638                             return true;
639                         }
640                         case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
641                             // Prevent the view group itself from being selected.
642                             // Instead, select the item in the center
643                             final ViewItem currentItem = mViewItem[mCurrentItem];
644                             currentItem.getView().performAccessibilityAction(action, args);
645                             return true;
646                         }
647                     }
648                 }
649                 return super.performAccessibilityAction(host, action, args);
650             }
651         });
652     }
653
654     private void recycleView(View view, int dataId) {
655         final int viewType = (Integer) view.getTag(R.id.mediadata_tag_viewtype);
656         if (viewType > 0) {
657             Queue<View> recycledViewsForType = recycledViews.get(viewType);
658             if (recycledViewsForType == null) {
659                 recycledViewsForType = new ArrayDeque<View>();
660                 recycledViews.put(viewType, recycledViewsForType);
661             }
662             recycledViewsForType.offer(view);
663         }
664     }
665
666     private View getRecycledView(int dataId) {
667         final int viewType = mDataAdapter.getItemViewType(dataId);
668         Queue<View> recycledViewsForType = recycledViews.get(viewType);
669         View result = null;
670         if (recycledViewsForType != null) {
671             result = recycledViewsForType.poll();
672         }
673         return result;
674     }
675
676     /**
677      * Returns the controller.
678      *
679      * @return The {@code Controller}.
680      */
681     public FilmstripController getController() {
682         return mController;
683     }
684
685     /**
686      * Returns the draw area width of the current item.
687      */
688     public int  getCurrentItemLeft() {
689         return mViewItem[mCurrentItem].getDrawAreaLeft();
690     }
691
692     private void setListener(FilmstripController.FilmstripListener l) {
693         mListener = l;
694     }
695
696     private void setViewGap(int viewGap) {
697         mViewGapInPixel = viewGap;
698     }
699
700     /**
701      * Called after current item or zoom level has changed.
702      */
703     public void zoomAtIndexChanged() {
704         if (mViewItem[mCurrentItem] == null) {
705             return;
706         }
707         int id = mViewItem[mCurrentItem].getId();
708         mListener.onZoomAtIndexChanged(id, mScale);
709     }
710
711     /**
712      * Checks if the data is at the center.
713      *
714      * @param id The id of the data to check.
715      * @return {@code True} if the data is currently at the center.
716      */
717     private boolean isDataAtCenter(int id) {
718         if (mViewItem[mCurrentItem] == null) {
719             return false;
720         }
721         if (mViewItem[mCurrentItem].getId() == id
722                 && isCurrentItemCentered()) {
723             return true;
724         }
725         return false;
726     }
727
728     private void measureViewItem(ViewItem item, int boundWidth, int boundHeight) {
729         int id = item.getId();
730         ImageData imageData = mDataAdapter.getImageData(id);
731         if (imageData == null) {
732             Log.e(TAG, "trying to measure a null item");
733             return;
734         }
735
736         Point dim = CameraUtil.resizeToFill(imageData.getWidth(), imageData.getHeight(),
737                 imageData.getRotation(), boundWidth, boundHeight);
738
739         item.measure(MeasureSpec.makeMeasureSpec(dim.x, MeasureSpec.EXACTLY),
740                 MeasureSpec.makeMeasureSpec(dim.y, MeasureSpec.EXACTLY));
741     }
742
743     @Override
744     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
745         super.onMeasure(widthMeasureSpec, heightMeasureSpec);
746
747         int boundWidth = MeasureSpec.getSize(widthMeasureSpec);
748         int boundHeight = MeasureSpec.getSize(heightMeasureSpec);
749         if (boundWidth == 0 || boundHeight == 0) {
750             // Either width or height is unknown, can't measure children yet.
751             return;
752         }
753
754         for (ViewItem item : mViewItem) {
755             if (item != null) {
756                 measureViewItem(item, boundWidth, boundHeight);
757             }
758         }
759         clampCenterX();
760         // Measure zoom view
761         mZoomView.measure(MeasureSpec.makeMeasureSpec(widthMeasureSpec, MeasureSpec.EXACTLY),
762                 MeasureSpec.makeMeasureSpec(heightMeasureSpec, MeasureSpec.EXACTLY));
763     }
764
765     private int findTheNearestView(int pointX) {
766
767         int nearest = 0;
768         // Find the first non-null ViewItem.
769         while (nearest < BUFFER_SIZE
770                 && (mViewItem[nearest] == null || mViewItem[nearest].getLeftPosition() == -1)) {
771             nearest++;
772         }
773         // No existing available ViewItem
774         if (nearest == BUFFER_SIZE) {
775             return -1;
776         }
777
778         int min = Math.abs(pointX - mViewItem[nearest].getCenterX());
779
780         for (int itemID = nearest + 1; itemID < BUFFER_SIZE && mViewItem[itemID] != null; itemID++) {
781             // Not measured yet.
782             if (mViewItem[itemID].getLeftPosition() == -1) {
783                 continue;
784             }
785
786             int c = mViewItem[itemID].getCenterX();
787             int dist = Math.abs(pointX - c);
788             if (dist < min) {
789                 min = dist;
790                 nearest = itemID;
791             }
792         }
793         return nearest;
794     }
795
796     private ViewItem buildItemFromData(int dataID) {
797         if (mActivity.isDestroyed()) {
798             // Loading item data is call from multiple AsyncTasks and the
799             // activity may be finished when buildItemFromData is called.
800             Log.d(TAG, "Activity destroyed, don't load data");
801             return null;
802         }
803         ImageData data = mDataAdapter.getImageData(dataID);
804         if (data == null) {
805             return null;
806         }
807
808         // Always scale by fixed filmstrip scale, since we only show items when
809         // in filmstrip. Preloading images with a different scale and bounds
810         // interferes with caching.
811         int width = Math.round(FILM_STRIP_SCALE * getWidth());
812         int height = Math.round(FILM_STRIP_SCALE * getHeight());
813         Log.v(TAG, "suggesting item bounds: " + width + "x" + height);
814         mDataAdapter.suggestViewSizeBound(width, height);
815
816         data.prepare();
817         View recycled = getRecycledView(dataID);
818         View v = mDataAdapter.getView(mActivity, recycled, dataID);
819         if (v == null) {
820             return null;
821         }
822         ViewItem item = new ViewItem(dataID, v, data);
823         item.addViewToHierarchy();
824         return item;
825     }
826
827     private void checkItemAtMaxSize() {
828         ViewItem item = mViewItem[mCurrentItem];
829         if (item.isMaximumBitmapRequested()) {
830             return;
831         };
832         item.setMaximumBitmapRequested();
833         // Request full size bitmap, or max that DataAdapter will create.
834         int id = item.getId();
835         int h = mDataAdapter.getImageData(id).getHeight();
836         int w = mDataAdapter.getImageData(id).getWidth();
837         item.resizeView(mActivity, w, h);
838     }
839
840     private void removeItem(int itemID) {
841         if (itemID >= mViewItem.length || mViewItem[itemID] == null) {
842             return;
843         }
844         ImageData data = mDataAdapter.getImageData(mViewItem[itemID].getId());
845         if (data == null) {
846             Log.e(TAG, "trying to remove a null item");
847             return;
848         }
849         mViewItem[itemID].removeViewFromHierarchy(false);
850         mViewItem[itemID] = null;
851     }
852
853     /**
854      * We try to keep the one closest to the center of the screen at position
855      * mCurrentItem.
856      */
857     private void stepIfNeeded() {
858         if (!inFilmstrip() && !inFullScreen()) {
859             // The good timing to step to the next view is when everything is
860             // not in transition.
861             return;
862         }
863         final int nearest = findTheNearestView(mCenterX);
864         // no change made.
865         if (nearest == -1 || nearest == mCurrentItem) {
866             return;
867         }
868         int prevDataId = (mViewItem[mCurrentItem] == null ? -1 : mViewItem[mCurrentItem].getId());
869         final int adjust = nearest - mCurrentItem;
870         if (adjust > 0) {
871             for (int k = 0; k < adjust; k++) {
872                 removeItem(k);
873             }
874             for (int k = 0; k + adjust < BUFFER_SIZE; k++) {
875                 mViewItem[k] = mViewItem[k + adjust];
876             }
877             for (int k = BUFFER_SIZE - adjust; k < BUFFER_SIZE; k++) {
878                 mViewItem[k] = null;
879                 if (mViewItem[k - 1] != null) {
880                     mViewItem[k] = buildItemFromData(mViewItem[k - 1].getId() + 1);
881                 }
882             }
883             adjustChildZOrder();
884         } else {
885             for (int k = BUFFER_SIZE - 1; k >= BUFFER_SIZE + adjust; k--) {
886                 removeItem(k);
887             }
888             for (int k = BUFFER_SIZE - 1; k + adjust >= 0; k--) {
889                 mViewItem[k] = mViewItem[k + adjust];
890             }
891             for (int k = -1 - adjust; k >= 0; k--) {
892                 mViewItem[k] = null;
893                 if (mViewItem[k + 1] != null) {
894                     mViewItem[k] = buildItemFromData(mViewItem[k + 1].getId() - 1);
895                 }
896             }
897         }
898         invalidate();
899         if (mListener != null) {
900             mListener.onDataFocusChanged(prevDataId, mViewItem[mCurrentItem].getId());
901             final int firstVisible = mViewItem[mCurrentItem].getId() - 2;
902             final int visibleItemCount = firstVisible + BUFFER_SIZE;
903             final int totalItemCount = mDataAdapter.getTotalNumber();
904             mListener.onScroll(firstVisible, visibleItemCount, totalItemCount);
905         }
906         zoomAtIndexChanged();
907     }
908
909     /**
910      * Check the bounds of {@code mCenterX}. Always call this function after: 1.
911      * Any changes to {@code mCenterX}. 2. Any size change of the view items.
912      *
913      * @return Whether clamp happened.
914      */
915     private boolean clampCenterX() {
916         ViewItem curr = mViewItem[mCurrentItem];
917         if (curr == null) {
918             return false;
919         }
920
921         boolean stopScroll = false;
922         if (curr.getId() == 1 && mCenterX < curr.getCenterX() && mDataIdOnUserScrolling > 1 &&
923                 mDataAdapter.getImageData(0).getViewType() == ImageData.VIEW_TYPE_STICKY &&
924                 mController.isScrolling()) {
925             stopScroll = true;
926         } else {
927             if (curr.getId() == 0 && mCenterX < curr.getCenterX()) {
928                 // Stop at the first ViewItem.
929                 stopScroll = true;
930             }
931         }
932         if (curr.getId() == mDataAdapter.getTotalNumber() - 1
933                 && mCenterX > curr.getCenterX()) {
934             // Stop at the end.
935             stopScroll = true;
936         }
937
938         if (stopScroll) {
939             mCenterX = curr.getCenterX();
940         }
941
942         return stopScroll;
943     }
944
945     /**
946      * Reorders the child views to be consistent with their data ID. This method
947      * should be called after adding/removing views.
948      */
949     private void adjustChildZOrder() {
950         for (int i = BUFFER_SIZE - 1; i >= 0; i--) {
951             if (mViewItem[i] == null) {
952                 continue;
953             }
954             mViewItem[i].bringViewToFront();
955         }
956         // ZoomView is a special case to always be in the front. In L set to
957         // max elevation to make sure ZoomView is above other elevated views.
958         bringChildToFront(mZoomView);
959         if (ApiHelper.isLOrHigher()) {
960             setMaxElevation(mZoomView);
961         }
962     }
963
964     @TargetApi(Build.VERSION_CODES.LOLLIPOP)
965     private void setMaxElevation(View v) {
966         v.setElevation(Float.MAX_VALUE);
967     }
968
969     /**
970      * Returns the ID of the current item, or -1 if there is no data.
971      */
972     private int getCurrentId() {
973         ViewItem current = mViewItem[mCurrentItem];
974         if (current == null) {
975             return -1;
976         }
977         return current.getId();
978     }
979
980     /**
981      * Keep the current item in the center. This functions does not check if the
982      * current item is null.
983      */
984     private void snapInCenter() {
985         final ViewItem currItem = mViewItem[mCurrentItem];
986         if (currItem == null) {
987             return;
988         }
989         final int currentViewCenter = currItem.getCenterX();
990         if (mController.isScrolling() || mIsUserScrolling
991                 || isCurrentItemCentered()) {
992             return;
993         }
994
995         int snapInTime = (int) (SNAP_IN_CENTER_TIME_MS
996                 * ((float) Math.abs(mCenterX - currentViewCenter))
997                 / mDrawArea.width());
998         mController.scrollToPosition(currentViewCenter,
999                 snapInTime, false);
1000         if (isViewTypeSticky(currItem) && !mController.isScaling() && mScale != FULL_SCREEN_SCALE) {
1001             // Now going to full screen camera
1002             mController.goToFullScreen();
1003         }
1004     }
1005
1006     /**
1007      * Translates the {@link ViewItem} on the left of the current one to match
1008      * the full-screen layout. In full-screen, we show only one {@link ViewItem}
1009      * which occupies the whole screen. The other left ones are put on the left
1010      * side in full scales. Does nothing if there's no next item.
1011      *
1012      * @param currItem The item ID of the current one to be translated.
1013      * @param drawAreaWidth The width of the current draw area.
1014      * @param scaleFraction A {@code float} between 0 and 1. 0 if the current
1015      *            scale is {@code FILM_STRIP_SCALE}. 1 if the current scale is
1016      *            {@code FULL_SCREEN_SCALE}.
1017      */
1018     private void translateLeftViewItem(
1019             int currItem, int drawAreaWidth, float scaleFraction) {
1020         if (currItem < 0 || currItem > BUFFER_SIZE - 1) {
1021             Log.e(TAG, "currItem id out of bound.");
1022             return;
1023         }
1024
1025         final ViewItem curr = mViewItem[currItem];
1026         final ViewItem next = mViewItem[currItem + 1];
1027         if (curr == null || next == null) {
1028             Log.e(TAG, "Invalid view item (curr or next == null). curr = "
1029                     + currItem);
1030             return;
1031         }
1032
1033         final int currCenterX = curr.getCenterX();
1034         final int nextCenterX = next.getCenterX();
1035         final int translate = (int) ((nextCenterX - drawAreaWidth
1036                 - currCenterX) * scaleFraction);
1037
1038         curr.layoutWithTranslationX(mDrawArea, mCenterX, mScale);
1039         curr.setAlpha(1f);
1040         curr.setVisibility(VISIBLE);
1041
1042         if (inFullScreen()) {
1043             curr.setTranslationX(translate * (mCenterX - currCenterX) / (nextCenterX - currCenterX));
1044         } else {
1045             curr.setTranslationX(translate);
1046         }
1047     }
1048
1049     /**
1050      * Fade out the {@link ViewItem} on the right of the current one in
1051      * full-screen layout. Does nothing if there's no previous item.
1052      *
1053      * @param currItemId The ID of the item to fade.
1054      */
1055     private void fadeAndScaleRightViewItem(int currItemId) {
1056         if (currItemId < 1 || currItemId > BUFFER_SIZE) {
1057             Log.e(TAG, "currItem id out of bound.");
1058             return;
1059         }
1060
1061         final ViewItem currItem = mViewItem[currItemId];
1062         final ViewItem prevItem = mViewItem[currItemId - 1];
1063         if (currItem == null || prevItem == null) {
1064             Log.e(TAG, "Invalid view item (curr or prev == null). curr = "
1065                     + currItemId);
1066             return;
1067         }
1068
1069         if (currItemId > mCurrentItem + 1) {
1070             // Every item not right next to the mCurrentItem is invisible.
1071             currItem.setVisibility(INVISIBLE);
1072             return;
1073         }
1074         final int prevCenterX = prevItem.getCenterX();
1075         if (mCenterX <= prevCenterX) {
1076             // Shortcut. If the position is at the center of the previous one,
1077             // set to invisible too.
1078             currItem.setVisibility(INVISIBLE);
1079             return;
1080         }
1081         final int currCenterX = currItem.getCenterX();
1082         final float fadeDownFraction =
1083                 ((float) mCenterX - prevCenterX) / (currCenterX - prevCenterX);
1084         currItem.layoutWithTranslationX(mDrawArea, currCenterX,
1085                 FILM_STRIP_SCALE + (1f - FILM_STRIP_SCALE) * fadeDownFraction);
1086         currItem.setAlpha(fadeDownFraction);
1087         currItem.setTranslationX(0);
1088         currItem.setVisibility(VISIBLE);
1089     }
1090
1091     private void layoutViewItems(boolean layoutChanged) {
1092         if (mViewItem[mCurrentItem] == null ||
1093                 mDrawArea.width() == 0 ||
1094                 mDrawArea.height() == 0) {
1095             return;
1096         }
1097
1098         // If the layout changed, we need to adjust the current position so
1099         // that if an item is centered before the change, it's still centered.
1100         if (layoutChanged) {
1101             mViewItem[mCurrentItem].setLeftPosition(
1102                     mCenterX - mViewItem[mCurrentItem].getMeasuredWidth() / 2);
1103         }
1104
1105         if (inZoomView()) {
1106             return;
1107         }
1108         /**
1109          * Transformed scale fraction between 0 and 1. 0 if the scale is
1110          * {@link FILM_STRIP_SCALE}. 1 if the scale is {@link FULL_SCREEN_SCALE}
1111          * .
1112          */
1113         final float scaleFraction = mViewAnimInterpolator.getInterpolation(
1114                 (mScale - FILM_STRIP_SCALE) / (FULL_SCREEN_SCALE - FILM_STRIP_SCALE));
1115         final int fullScreenWidth = mDrawArea.width() + mViewGapInPixel;
1116
1117         // Decide the position for all view items on the left and the right
1118         // first.
1119
1120         // Left items.
1121         for (int itemID = mCurrentItem - 1; itemID >= 0; itemID--) {
1122             final ViewItem curr = mViewItem[itemID];
1123             if (curr == null) {
1124                 break;
1125             }
1126
1127             // First, layout relatively to the next one.
1128             final int currLeft = mViewItem[itemID + 1].getLeftPosition()
1129                     - curr.getMeasuredWidth() - mViewGapInPixel;
1130             curr.setLeftPosition(currLeft);
1131         }
1132         // Right items.
1133         for (int itemID = mCurrentItem + 1; itemID < BUFFER_SIZE; itemID++) {
1134             final ViewItem curr = mViewItem[itemID];
1135             if (curr == null) {
1136                 break;
1137             }
1138
1139             // First, layout relatively to the previous one.
1140             final ViewItem prev = mViewItem[itemID - 1];
1141             final int currLeft =
1142                     prev.getLeftPosition() + prev.getMeasuredWidth()
1143                             + mViewGapInPixel;
1144             curr.setLeftPosition(currLeft);
1145         }
1146
1147         // Special case for the one immediately on the right of the camera
1148         // preview.
1149         boolean immediateRight =
1150                 (mViewItem[mCurrentItem].getId() == 1 &&
1151                 mDataAdapter.getImageData(0).getViewType() == ImageData.VIEW_TYPE_STICKY);
1152
1153         // Layout the current ViewItem first.
1154         if (immediateRight) {
1155             // Just do a simple layout without any special translation or
1156             // fading. The implementation in Gallery does not push the first
1157             // photo to the bottom of the camera preview. Simply place the
1158             // photo on the right of the preview.
1159             final ViewItem currItem = mViewItem[mCurrentItem];
1160             currItem.layoutWithTranslationX(mDrawArea, mCenterX, mScale);
1161             currItem.setTranslationX(0f);
1162             currItem.setAlpha(1f);
1163         } else if (scaleFraction == 1f) {
1164             final ViewItem currItem = mViewItem[mCurrentItem];
1165             final int currCenterX = currItem.getCenterX();
1166             if (mCenterX < currCenterX) {
1167                 // In full-screen and mCenterX is on the left of the center,
1168                 // we draw the current one to "fade down".
1169                 fadeAndScaleRightViewItem(mCurrentItem);
1170             } else if (mCenterX > currCenterX) {
1171                 // In full-screen and mCenterX is on the right of the center,
1172                 // we draw the current one translated.
1173                 translateLeftViewItem(mCurrentItem, fullScreenWidth, scaleFraction);
1174             } else {
1175                 currItem.layoutWithTranslationX(mDrawArea, mCenterX, mScale);
1176                 currItem.setTranslationX(0f);
1177                 currItem.setAlpha(1f);
1178             }
1179         } else {
1180             final ViewItem currItem = mViewItem[mCurrentItem];
1181             // The normal filmstrip has no translation for the current item. If
1182             // it has translation before, gradually set it to zero.
1183             currItem.setTranslationX(currItem.getTranslationX() * scaleFraction);
1184             currItem.layoutWithTranslationX(mDrawArea, mCenterX, mScale);
1185             if (mViewItem[mCurrentItem - 1] == null) {
1186                 currItem.setAlpha(1f);
1187             } else {
1188                 final int currCenterX = currItem.getCenterX();
1189                 final int prevCenterX = mViewItem[mCurrentItem - 1].getCenterX();
1190                 final float fadeDownFraction =
1191                         ((float) mCenterX - prevCenterX) / (currCenterX - prevCenterX);
1192                 currItem.setAlpha(
1193                         (1 - fadeDownFraction) * (1 - scaleFraction) + fadeDownFraction);
1194             }
1195         }
1196
1197         // Layout the rest dependent on the current scale.
1198
1199         // Items on the left
1200         for (int itemID = mCurrentItem - 1; itemID >= 0; itemID--) {
1201             final ViewItem curr = mViewItem[itemID];
1202             if (curr == null) {
1203                 break;
1204             }
1205             translateLeftViewItem(itemID, fullScreenWidth, scaleFraction);
1206         }
1207
1208         // Items on the right
1209         for (int itemID = mCurrentItem + 1; itemID < BUFFER_SIZE; itemID++) {
1210             final ViewItem curr = mViewItem[itemID];
1211             if (curr == null) {
1212                 break;
1213             }
1214
1215             curr.layoutWithTranslationX(mDrawArea, mCenterX, mScale);
1216             if (curr.getId() == 1 && isViewTypeSticky(curr)) {
1217                 // Special case for the one next to the camera preview.
1218                 curr.setAlpha(1f);
1219                 continue;
1220             }
1221
1222             if (scaleFraction == 1) {
1223                 // It's in full-screen mode.
1224                 fadeAndScaleRightViewItem(itemID);
1225             } else {
1226                 if (curr.getVisibility() == INVISIBLE) {
1227                     curr.setVisibility(VISIBLE);
1228                 }
1229                 if (itemID == mCurrentItem + 1) {
1230                     curr.setAlpha(1f - scaleFraction);
1231                 } else {
1232                     if (scaleFraction == 0f) {
1233                         curr.setAlpha(1f);
1234                     } else {
1235                         curr.setVisibility(INVISIBLE);
1236                     }
1237                 }
1238                 curr.setTranslationX(
1239                         (mViewItem[mCurrentItem].getLeftPosition() - curr.getLeftPosition()) *
1240                                 scaleFraction);
1241             }
1242         }
1243
1244         stepIfNeeded();
1245     }
1246
1247     private boolean isViewTypeSticky(ViewItem item) {
1248         if (item == null) {
1249             return false;
1250         }
1251         return mDataAdapter.getImageData(item.getId()).getViewType() ==
1252                 ImageData.VIEW_TYPE_STICKY;
1253     }
1254
1255     @Override
1256     public void onDraw(Canvas c) {
1257         // TODO: remove layoutViewItems() here.
1258         layoutViewItems(false);
1259         super.onDraw(c);
1260     }
1261
1262     @Override
1263     protected void onLayout(boolean changed, int l, int t, int r, int b) {
1264         mDrawArea.left = 0;
1265         mDrawArea.top = 0;
1266         mDrawArea.right = r - l;
1267         mDrawArea.bottom = b - t;
1268         mZoomView.layout(mDrawArea.left, mDrawArea.top, mDrawArea.right, mDrawArea.bottom);
1269         // TODO: Need a more robust solution to decide when to re-layout
1270         // If in the middle of zooming, only re-layout when the layout has
1271         // changed.
1272         if (!inZoomView() || changed) {
1273             resetZoomView();
1274             layoutViewItems(changed);
1275         }
1276     }
1277
1278     /**
1279      * Clears the translation and scale that has been set on the view, cancels
1280      * any loading request for image partial decoding, and hides zoom view. This
1281      * is needed for when there is a layout change (e.g. when users re-enter the
1282      * app, or rotate the device, etc).
1283      */
1284     private void resetZoomView() {
1285         if (!inZoomView()) {
1286             return;
1287         }
1288         ViewItem current = mViewItem[mCurrentItem];
1289         if (current == null) {
1290             return;
1291         }
1292         mScale = FULL_SCREEN_SCALE;
1293         mController.cancelZoomAnimation();
1294         mController.cancelFlingAnimation();
1295         current.resetTransform();
1296         mController.cancelLoadingZoomedImage();
1297         mZoomView.setVisibility(GONE);
1298         mController.setSurroundingViewsVisible(true);
1299     }
1300
1301     private void hideZoomView() {
1302         if (inZoomView()) {
1303             mController.cancelLoadingZoomedImage();
1304             mZoomView.setVisibility(GONE);
1305         }
1306     }
1307
1308     private void slideViewBack(ViewItem item) {
1309         item.animateTranslationX(0, GEOMETRY_ADJUST_TIME_MS, mViewAnimInterpolator);
1310         item.animateTranslationY(0, GEOMETRY_ADJUST_TIME_MS, mViewAnimInterpolator);
1311         item.animateAlpha(1f, GEOMETRY_ADJUST_TIME_MS, mViewAnimInterpolator);
1312     }
1313
1314     private void animateItemRemoval(int dataID, final ImageData data) {
1315         if (mScale > FULL_SCREEN_SCALE) {
1316             resetZoomView();
1317         }
1318         int removedItemId = findItemByDataID(dataID);
1319
1320         // adjust the data id to be consistent
1321         for (int i = 0; i < BUFFER_SIZE; i++) {
1322             if (mViewItem[i] == null || mViewItem[i].getId() <= dataID) {
1323                 continue;
1324             }
1325             mViewItem[i].setId(mViewItem[i].getId() - 1);
1326         }
1327         if (removedItemId == -1) {
1328             return;
1329         }
1330
1331         final ViewItem removedItem = mViewItem[removedItemId];
1332         final int offsetX = removedItem.getMeasuredWidth() + mViewGapInPixel;
1333
1334         for (int i = removedItemId + 1; i < BUFFER_SIZE; i++) {
1335             if (mViewItem[i] != null) {
1336                 mViewItem[i].setLeftPosition(mViewItem[i].getLeftPosition() - offsetX);
1337             }
1338         }
1339
1340         if (removedItemId >= mCurrentItem
1341                 && mViewItem[removedItemId].getId() < mDataAdapter.getTotalNumber()) {
1342             // Fill the removed item by left shift when the current one or
1343             // anyone on the right is removed, and there's more data on the
1344             // right available.
1345             for (int i = removedItemId; i < BUFFER_SIZE - 1; i++) {
1346                 mViewItem[i] = mViewItem[i + 1];
1347             }
1348
1349             // pull data out from the DataAdapter for the last one.
1350             int curr = BUFFER_SIZE - 1;
1351             int prev = curr - 1;
1352             if (mViewItem[prev] != null) {
1353                 mViewItem[curr] = buildItemFromData(mViewItem[prev].getId() + 1);
1354             }
1355
1356             // The animation part.
1357             if (inFullScreen()) {
1358                 mViewItem[mCurrentItem].setVisibility(VISIBLE);
1359                 ViewItem nextItem = mViewItem[mCurrentItem + 1];
1360                 if (nextItem != null) {
1361                     nextItem.setVisibility(INVISIBLE);
1362                 }
1363             }
1364
1365             // Translate the views to their original places.
1366             for (int i = removedItemId; i < BUFFER_SIZE; i++) {
1367                 if (mViewItem[i] != null) {
1368                     mViewItem[i].setTranslationX(offsetX);
1369                 }
1370             }
1371
1372             // The end of the filmstrip might have been changed.
1373             // The mCenterX might be out of the bound.
1374             ViewItem currItem = mViewItem[mCurrentItem];
1375             if(currItem!=null) {
1376                 if (currItem.getId() == mDataAdapter.getTotalNumber() - 1
1377                         && mCenterX > currItem.getCenterX()) {
1378                     int adjustDiff = currItem.getCenterX() - mCenterX;
1379                     mCenterX = currItem.getCenterX();
1380                     for (int i = 0; i < BUFFER_SIZE; i++) {
1381                         if (mViewItem[i] != null) {
1382                             mViewItem[i].translateXScaledBy(adjustDiff);
1383                         }
1384                     }
1385                 }
1386             } else {
1387                 // CurrItem should NOT be NULL, but if is, at least don't crash.
1388                 Log.w(TAG,"Caught invalid update in removal animation.");
1389             }
1390         } else {
1391             // fill the removed place by right shift
1392             mCenterX -= offsetX;
1393
1394             for (int i = removedItemId; i > 0; i--) {
1395                 mViewItem[i] = mViewItem[i - 1];
1396             }
1397
1398             // pull data out from the DataAdapter for the first one.
1399             int curr = 0;
1400             int next = curr + 1;
1401             if (mViewItem[next] != null) {
1402                 mViewItem[curr] = buildItemFromData(mViewItem[next].getId() - 1);
1403             }
1404
1405             // Translate the views to their original places.
1406             for (int i = removedItemId; i >= 0; i--) {
1407                 if (mViewItem[i] != null) {
1408                     mViewItem[i].setTranslationX(-offsetX);
1409                 }
1410             }
1411         }
1412
1413         int transY = getHeight() / 8;
1414         if (removedItem.getTranslationY() < 0) {
1415             transY = -transY;
1416         }
1417         removedItem.animateTranslationY(removedItem.getTranslationY() + transY,
1418                 GEOMETRY_ADJUST_TIME_MS, mViewAnimInterpolator);
1419         removedItem.animateAlpha(0f, GEOMETRY_ADJUST_TIME_MS, mViewAnimInterpolator);
1420         postDelayed(new Runnable() {
1421             @Override
1422             public void run() {
1423                 removedItem.removeViewFromHierarchy(false);
1424             }
1425         }, GEOMETRY_ADJUST_TIME_MS);
1426
1427         adjustChildZOrder();
1428         invalidate();
1429
1430         // Now, slide every one back.
1431         if (mViewItem[mCurrentItem] == null) {
1432             return;
1433         }
1434         for (int i = 0; i < BUFFER_SIZE; i++) {
1435             if (mViewItem[i] != null
1436                     && mViewItem[i].getTranslationX() != 0f) {
1437                 slideViewBack(mViewItem[i]);
1438             }
1439         }
1440         if (isCurrentItemCentered() && isViewTypeSticky(mViewItem[mCurrentItem])) {
1441             // Special case for scrolling onto the camera preview after removal.
1442             mController.goToFullScreen();
1443         }
1444     }
1445
1446     // returns -1 on failure.
1447     private int findItemByDataID(int dataID) {
1448         for (int i = 0; i < BUFFER_SIZE; i++) {
1449             if (mViewItem[i] != null
1450                     && mViewItem[i].getId() == dataID) {
1451                 return i;
1452             }
1453         }
1454         return -1;
1455     }
1456
1457     private void updateInsertion(int dataID) {
1458         int insertedItemId = findItemByDataID(dataID);
1459         if (insertedItemId == -1) {
1460             // Not in the current item buffers. Check if it's inserted
1461             // at the end.
1462             if (dataID == mDataAdapter.getTotalNumber() - 1) {
1463                 int prev = findItemByDataID(dataID - 1);
1464                 if (prev >= 0 && prev < BUFFER_SIZE - 1) {
1465                     // The previous data is in the buffer and we still
1466                     // have room for the inserted data.
1467                     insertedItemId = prev + 1;
1468                 }
1469             }
1470         }
1471
1472         // adjust the data id to be consistent
1473         for (int i = 0; i < BUFFER_SIZE; i++) {
1474             if (mViewItem[i] == null || mViewItem[i].getId() < dataID) {
1475                 continue;
1476             }
1477             mViewItem[i].setId(mViewItem[i].getId() + 1);
1478         }
1479         if (insertedItemId == -1) {
1480             return;
1481         }
1482
1483         final ImageData data = mDataAdapter.getImageData(dataID);
1484         Point dim = CameraUtil
1485                 .resizeToFill(data.getWidth(), data.getHeight(), data.getRotation(),
1486                         getMeasuredWidth(), getMeasuredHeight());
1487         final int offsetX = dim.x + mViewGapInPixel;
1488         ViewItem viewItem = buildItemFromData(dataID);
1489
1490         if (insertedItemId >= mCurrentItem) {
1491             if (insertedItemId == mCurrentItem) {
1492                 viewItem.setLeftPosition(mViewItem[mCurrentItem].getLeftPosition());
1493             }
1494             // Shift right to make rooms for newly inserted item.
1495             removeItem(BUFFER_SIZE - 1);
1496             for (int i = BUFFER_SIZE - 1; i > insertedItemId; i--) {
1497                 mViewItem[i] = mViewItem[i - 1];
1498                 if (mViewItem[i] != null) {
1499                     mViewItem[i].setTranslationX(-offsetX);
1500                     slideViewBack(mViewItem[i]);
1501                 }
1502             }
1503         } else {
1504             // Shift left. Put the inserted data on the left instead of the
1505             // found position.
1506             --insertedItemId;
1507             if (insertedItemId < 0) {
1508                 return;
1509             }
1510             removeItem(0);
1511             for (int i = 1; i <= insertedItemId; i++) {
1512                 if (mViewItem[i] != null) {
1513                     mViewItem[i].setTranslationX(offsetX);
1514                     slideViewBack(mViewItem[i]);
1515                     mViewItem[i - 1] = mViewItem[i];
1516                 }
1517             }
1518         }
1519
1520         mViewItem[insertedItemId] = viewItem;
1521         viewItem.setAlpha(0f);
1522         viewItem.setTranslationY(getHeight() / 8);
1523         slideViewBack(viewItem);
1524         adjustChildZOrder();
1525         invalidate();
1526     }
1527
1528     private void setDataAdapter(DataAdapter adapter) {
1529         mDataAdapter = adapter;
1530         int maxEdge = (int) (Math.max(this.getHeight(), this.getWidth())
1531                 * FILM_STRIP_SCALE);
1532         mDataAdapter.suggestViewSizeBound(maxEdge, maxEdge);
1533         mDataAdapter.setListener(new DataAdapter.Listener() {
1534             @Override
1535             public void onDataLoaded() {
1536                 reload();
1537             }
1538
1539             @Override
1540             public void onDataUpdated(DataAdapter.UpdateReporter reporter) {
1541                 update(reporter);
1542             }
1543
1544             @Override
1545             public void onDataInserted(int dataId, ImageData data) {
1546                 if (mViewItem[mCurrentItem] == null) {
1547                     // empty now, simply do a reload.
1548                     reload();
1549                 } else {
1550                     updateInsertion(dataId);
1551                 }
1552                 if (mListener != null) {
1553                     mListener.onDataFocusChanged(dataId, getCurrentId());
1554                 }
1555             }
1556
1557             @Override
1558             public void onDataRemoved(int dataId, ImageData data) {
1559                 animateItemRemoval(dataId, data);
1560                 if (mListener != null) {
1561                     mListener.onDataFocusChanged(dataId, getCurrentId());
1562                 }
1563             }
1564         });
1565     }
1566
1567     private boolean inFilmstrip() {
1568         return (mScale == FILM_STRIP_SCALE);
1569     }
1570
1571     private boolean inFullScreen() {
1572         return (mScale == FULL_SCREEN_SCALE);
1573     }
1574
1575     private boolean inZoomView() {
1576         return (mScale > FULL_SCREEN_SCALE);
1577     }
1578
1579     private boolean isCameraPreview() {
1580         return isViewTypeSticky(mViewItem[mCurrentItem]);
1581     }
1582
1583     private boolean inCameraFullscreen() {
1584         return isDataAtCenter(0) && inFullScreen()
1585                 && (isViewTypeSticky(mViewItem[mCurrentItem]));
1586     }
1587
1588     @Override
1589     public boolean onInterceptTouchEvent(MotionEvent ev) {
1590         if (mController.isScrolling()) {
1591             return true;
1592         }
1593
1594         if (ev.getActionMasked() == MotionEvent.ACTION_DOWN) {
1595             mCheckToIntercept = true;
1596             mDown = MotionEvent.obtain(ev);
1597             ViewItem viewItem = mViewItem[mCurrentItem];
1598             // Do not intercept touch if swipe is not enabled
1599             if (viewItem != null && !mDataAdapter.canSwipeInFullScreen(viewItem.getId())) {
1600                 mCheckToIntercept = false;
1601             }
1602             return false;
1603         } else if (ev.getActionMasked() == MotionEvent.ACTION_POINTER_DOWN) {
1604             // Do not intercept touch once child is in zoom mode
1605             mCheckToIntercept = false;
1606             return false;
1607         } else {
1608             if (!mCheckToIntercept) {
1609                 return false;
1610             }
1611             if (ev.getEventTime() - ev.getDownTime() > SWIPE_TIME_OUT) {
1612                 return false;
1613             }
1614             int deltaX = (int) (ev.getX() - mDown.getX());
1615             int deltaY = (int) (ev.getY() - mDown.getY());
1616             if (ev.getActionMasked() == MotionEvent.ACTION_MOVE
1617                     && deltaX < mSlop * (-1)) {
1618                 // intercept left swipe
1619                 if (Math.abs(deltaX) >= Math.abs(deltaY) * 2) {
1620                     return true;
1621                 }
1622             }
1623         }
1624         return false;
1625     }
1626
1627     @Override
1628     public boolean onTouchEvent(MotionEvent ev) {
1629         return mGestureRecognizer.onTouchEvent(ev);
1630     }
1631
1632     @Override
1633     public boolean onGenericMotionEvent(MotionEvent ev) {
1634         mGestureRecognizer.onGenericMotionEvent(ev);
1635         return true;
1636     }
1637
1638     FilmstripGestureRecognizer.Listener getGestureListener() {
1639         return mGestureListener;
1640     }
1641
1642     private void updateViewItem(int itemID) {
1643         ViewItem item = mViewItem[itemID];
1644         if (item == null) {
1645             Log.e(TAG, "trying to update an null item");
1646             return;
1647         }
1648         item.removeViewFromHierarchy(true);
1649
1650         ViewItem newItem = buildItemFromData(item.getId());
1651         if (newItem == null) {
1652             Log.e(TAG, "new item is null");
1653             // keep using the old data.
1654             item.addViewToHierarchy();
1655             return;
1656         }
1657         newItem.copyAttributes(item);
1658         mViewItem[itemID] = newItem;
1659         mZoomView.resetDecoder();
1660
1661         boolean stopScroll = clampCenterX();
1662         if (stopScroll) {
1663             mController.stopScrolling(true);
1664         }
1665         adjustChildZOrder();
1666         invalidate();
1667         if (mListener != null) {
1668             mListener.onDataUpdated(newItem.getId());
1669         }
1670     }
1671
1672     /** Some of the data is changed. */
1673     private void update(DataAdapter.UpdateReporter reporter) {
1674         // No data yet.
1675         if (mViewItem[mCurrentItem] == null) {
1676             reload();
1677             return;
1678         }
1679
1680         // Check the current one.
1681         ViewItem curr = mViewItem[mCurrentItem];
1682         int dataId = curr.getId();
1683         if (reporter.isDataRemoved(dataId)) {
1684             reload();
1685             return;
1686         }
1687         if (reporter.isDataUpdated(dataId)) {
1688             updateViewItem(mCurrentItem);
1689             final ImageData data = mDataAdapter.getImageData(dataId);
1690             if (!mIsUserScrolling && !mController.isScrolling()) {
1691                 // If there is no scrolling at all, adjust mCenterX to place
1692                 // the current item at the center.
1693                 Point dim = CameraUtil.resizeToFill(data.getWidth(), data.getHeight(),
1694                         data.getRotation(), getMeasuredWidth(), getMeasuredHeight());
1695                 mCenterX = curr.getLeftPosition() + dim.x / 2;
1696             }
1697         }
1698
1699         // Check left
1700         for (int i = mCurrentItem - 1; i >= 0; i--) {
1701             curr = mViewItem[i];
1702             if (curr != null) {
1703                 dataId = curr.getId();
1704                 if (reporter.isDataRemoved(dataId) || reporter.isDataUpdated(dataId)) {
1705                     updateViewItem(i);
1706                 }
1707             } else {
1708                 ViewItem next = mViewItem[i + 1];
1709                 if (next != null) {
1710                     mViewItem[i] = buildItemFromData(next.getId() - 1);
1711                 }
1712             }
1713         }
1714
1715         // Check right
1716         for (int i = mCurrentItem + 1; i < BUFFER_SIZE; i++) {
1717             curr = mViewItem[i];
1718             if (curr != null) {
1719                 dataId = curr.getId();
1720                 if (reporter.isDataRemoved(dataId) || reporter.isDataUpdated(dataId)) {
1721                     updateViewItem(i);
1722                 }
1723             } else {
1724                 ViewItem prev = mViewItem[i - 1];
1725                 if (prev != null) {
1726                     mViewItem[i] = buildItemFromData(prev.getId() + 1);
1727                 }
1728             }
1729         }
1730         adjustChildZOrder();
1731         // Request a layout to find the measured width/height of the view first.
1732         requestLayout();
1733         // Update photo sphere visibility after metadata fully written.
1734     }
1735
1736     /**
1737      * The whole data might be totally different. Flush all and load from the
1738      * start. Filmstrip will be centered on the first item, i.e. the camera
1739      * preview.
1740      */
1741     private void reload() {
1742         mController.stopScrolling(true);
1743         mController.stopScale();
1744         mDataIdOnUserScrolling = 0;
1745
1746         int prevId = -1;
1747         if (mViewItem[mCurrentItem] != null) {
1748             prevId = mViewItem[mCurrentItem].getId();
1749         }
1750
1751         // Remove all views from the mViewItem buffer, except the camera view.
1752         for (int i = 0; i < mViewItem.length; i++) {
1753             if (mViewItem[i] == null) {
1754                 continue;
1755             }
1756             mViewItem[i].removeViewFromHierarchy(false);
1757         }
1758
1759         // Clear out the mViewItems and rebuild with camera in the center.
1760         Arrays.fill(mViewItem, null);
1761         int dataNumber = mDataAdapter.getTotalNumber();
1762         if (dataNumber == 0) {
1763             return;
1764         }
1765
1766         mViewItem[mCurrentItem] = buildItemFromData(0);
1767         if (mViewItem[mCurrentItem] == null) {
1768             return;
1769         }
1770         mViewItem[mCurrentItem].setLeftPosition(0);
1771         for (int i = mCurrentItem + 1; i < BUFFER_SIZE; i++) {
1772             mViewItem[i] = buildItemFromData(mViewItem[i - 1].getId() + 1);
1773             if (mViewItem[i] == null) {
1774                 break;
1775             }
1776         }
1777
1778         // Ensure that the views in mViewItem will layout the first in the
1779         // center of the display upon a reload.
1780         mCenterX = -1;
1781         mScale = FILM_STRIP_SCALE;
1782
1783         adjustChildZOrder();
1784         invalidate();
1785
1786         if (mListener != null) {
1787             mListener.onDataReloaded();
1788             mListener.onDataFocusChanged(prevId, mViewItem[mCurrentItem].getId());
1789         }
1790     }
1791
1792     private void promoteData(int itemID, int dataID) {
1793         if (mListener != null) {
1794             mListener.onFocusedDataPromoted(dataID);
1795         }
1796     }
1797
1798     private void demoteData(int itemID, int dataID) {
1799         if (mListener != null) {
1800             mListener.onFocusedDataDemoted(dataID);
1801         }
1802     }
1803
1804     private void onEnterFilmstrip() {
1805         if (mListener != null) {
1806             mListener.onEnterFilmstrip(getCurrentId());
1807         }
1808     }
1809
1810     private void onLeaveFilmstrip() {
1811         if (mListener != null) {
1812             mListener.onLeaveFilmstrip(getCurrentId());
1813         }
1814     }
1815
1816     private void onEnterFullScreen() {
1817         mFullScreenUIHidden = false;
1818         if (mListener != null) {
1819             mListener.onEnterFullScreenUiShown(getCurrentId());
1820         }
1821     }
1822
1823     private void onLeaveFullScreen() {
1824         if (mListener != null) {
1825             mListener.onLeaveFullScreenUiShown(getCurrentId());
1826         }
1827     }
1828
1829     private void onEnterFullScreenUiHidden() {
1830         mFullScreenUIHidden = true;
1831         if (mListener != null) {
1832             mListener.onEnterFullScreenUiHidden(getCurrentId());
1833         }
1834     }
1835
1836     private void onLeaveFullScreenUiHidden() {
1837         mFullScreenUIHidden = false;
1838         if (mListener != null) {
1839             mListener.onLeaveFullScreenUiHidden(getCurrentId());
1840         }
1841     }
1842
1843     private void onEnterZoomView() {
1844         if (mListener != null) {
1845             mListener.onEnterZoomView(getCurrentId());
1846         }
1847     }
1848
1849     private void onLeaveZoomView() {
1850         mController.setSurroundingViewsVisible(true);
1851     }
1852
1853     /**
1854      * MyController controls all the geometry animations. It passively tells the
1855      * geometry information on demand.
1856      */
1857     private class MyController implements FilmstripController {
1858
1859         private final ValueAnimator mScaleAnimator;
1860         private ValueAnimator mZoomAnimator;
1861         private AnimatorSet mFlingAnimator;
1862
1863         private final MyScroller mScroller;
1864         private boolean mCanStopScroll;
1865
1866         private final MyScroller.Listener mScrollerListener =
1867                 new MyScroller.Listener() {
1868                     @Override
1869                     public void onScrollUpdate(int currX, int currY) {
1870                         mCenterX = currX;
1871
1872                         boolean stopScroll = clampCenterX();
1873                         if (stopScroll) {
1874                             mController.stopScrolling(true);
1875                         }
1876                         invalidate();
1877                     }
1878
1879                     @Override
1880                     public void onScrollEnd() {
1881                         mCanStopScroll = true;
1882                         if (mViewItem[mCurrentItem] == null) {
1883                             return;
1884                         }
1885                         snapInCenter();
1886                         if (isCurrentItemCentered()
1887                                 && isViewTypeSticky(mViewItem[mCurrentItem])) {
1888                             // Special case for the scrolling end on the camera
1889                             // preview.
1890                             goToFullScreen();
1891                         }
1892                     }
1893                 };
1894
1895         private final ValueAnimator.AnimatorUpdateListener mScaleAnimatorUpdateListener =
1896                 new ValueAnimator.AnimatorUpdateListener() {
1897                     @Override
1898                     public void onAnimationUpdate(ValueAnimator animation) {
1899                         if (mViewItem[mCurrentItem] == null) {
1900                             return;
1901                         }
1902                         mScale = (Float) animation.getAnimatedValue();
1903                         invalidate();
1904                     }
1905                 };
1906
1907         MyController(Context context) {
1908             TimeInterpolator decelerateInterpolator = new DecelerateInterpolator(1.5f);
1909             mScroller = new MyScroller(mActivity,
1910                     new Handler(mActivity.getMainLooper()),
1911                     mScrollerListener, decelerateInterpolator);
1912             mCanStopScroll = true;
1913
1914             mScaleAnimator = new ValueAnimator();
1915             mScaleAnimator.addUpdateListener(mScaleAnimatorUpdateListener);
1916             mScaleAnimator.setInterpolator(decelerateInterpolator);
1917             mScaleAnimator.addListener(new Animator.AnimatorListener() {
1918                 @Override
1919                 public void onAnimationStart(Animator animator) {
1920                     if (mScale == FULL_SCREEN_SCALE) {
1921                         onLeaveFullScreen();
1922                     } else {
1923                         if (mScale == FILM_STRIP_SCALE) {
1924                             onLeaveFilmstrip();
1925                         }
1926                     }
1927                 }
1928
1929                 @Override
1930                 public void onAnimationEnd(Animator animator) {
1931                     if (mScale == FULL_SCREEN_SCALE) {
1932                         onEnterFullScreen();
1933                     } else {
1934                         if (mScale == FILM_STRIP_SCALE) {
1935                             onEnterFilmstrip();
1936                         }
1937                     }
1938                     zoomAtIndexChanged();
1939                 }
1940
1941                 @Override
1942                 public void onAnimationCancel(Animator animator) {
1943
1944                 }
1945
1946                 @Override
1947                 public void onAnimationRepeat(Animator animator) {
1948
1949                 }
1950             });
1951         }
1952
1953         @Override
1954         public void setImageGap(int imageGap) {
1955             FilmstripView.this.setViewGap(imageGap);
1956         }
1957
1958         @Override
1959         public int getCurrentId() {
1960             return FilmstripView.this.getCurrentId();
1961         }
1962
1963         @Override
1964         public void setDataAdapter(DataAdapter adapter) {
1965             FilmstripView.this.setDataAdapter(adapter);
1966         }
1967
1968         @Override
1969         public boolean inFilmstrip() {
1970             return FilmstripView.this.inFilmstrip();
1971         }
1972
1973         @Override
1974         public boolean inFullScreen() {
1975             return FilmstripView.this.inFullScreen();
1976         }
1977
1978         @Override
1979         public boolean isCameraPreview() {
1980             return FilmstripView.this.isCameraPreview();
1981         }
1982
1983         @Override
1984         public boolean inCameraFullscreen() {
1985             return FilmstripView.this.inCameraFullscreen();
1986         }
1987
1988         @Override
1989         public void setListener(FilmstripListener l) {
1990             FilmstripView.this.setListener(l);
1991         }
1992
1993         @Override
1994         public boolean isScrolling() {
1995             return !mScroller.isFinished();
1996         }
1997
1998         @Override
1999         public boolean isScaling() {
2000             return mScaleAnimator.isRunning();
2001         }
2002
2003         private int estimateMinX(int dataID, int leftPos, int viewWidth) {
2004             return leftPos - (dataID + 100) * (viewWidth + mViewGapInPixel);
2005         }
2006
2007         private int estimateMaxX(int dataID, int leftPos, int viewWidth) {
2008             return leftPos
2009                     + (mDataAdapter.getTotalNumber() - dataID + 100)
2010                     * (viewWidth + mViewGapInPixel);
2011         }
2012
2013         /** Zoom all the way in or out on the image at the given pivot point. */
2014         private void zoomAt(final ViewItem current, final float focusX, final float focusY) {
2015             // End previous zoom animation, if any
2016             if (mZoomAnimator != null) {
2017                 mZoomAnimator.end();
2018             }
2019             // Calculate end scale
2020             final float maxScale = getCurrentDataMaxScale(false);
2021             final float endScale = mScale < maxScale - maxScale * TOLERANCE
2022                     ? maxScale : FULL_SCREEN_SCALE;
2023
2024             mZoomAnimator = new ValueAnimator();
2025             mZoomAnimator.setFloatValues(mScale, endScale);
2026             mZoomAnimator.setDuration(ZOOM_ANIMATION_DURATION_MS);
2027             mZoomAnimator.addListener(new Animator.AnimatorListener() {
2028                 @Override
2029                 public void onAnimationStart(Animator animation) {
2030                     if (mScale == FULL_SCREEN_SCALE) {
2031                         if (mFullScreenUIHidden) {
2032                             onLeaveFullScreenUiHidden();
2033                         } else {
2034                             onLeaveFullScreen();
2035                         }
2036                         setSurroundingViewsVisible(false);
2037                     } else if (inZoomView()) {
2038                         onLeaveZoomView();
2039                     }
2040                     cancelLoadingZoomedImage();
2041                 }
2042
2043                 @Override
2044                 public void onAnimationEnd(Animator animation) {
2045                     // Make sure animation ends up having the correct scale even
2046                     // if it is cancelled before it finishes
2047                     if (mScale != endScale) {
2048                         current.postScale(focusX, focusY, endScale / mScale, mDrawArea.width(),
2049                                 mDrawArea.height());
2050                         mScale = endScale;
2051                     }
2052
2053                     if (inFullScreen()) {
2054                         setSurroundingViewsVisible(true);
2055                         mZoomView.setVisibility(GONE);
2056                         current.resetTransform();
2057                         onEnterFullScreenUiHidden();
2058                     } else {
2059                         mController.loadZoomedImage();
2060                         onEnterZoomView();
2061                     }
2062                     mZoomAnimator = null;
2063                     zoomAtIndexChanged();
2064                 }
2065
2066                 @Override
2067                 public void onAnimationCancel(Animator animation) {
2068                     // Do nothing.
2069                 }
2070
2071                 @Override
2072                 public void onAnimationRepeat(Animator animation) {
2073                     // Do nothing.
2074                 }
2075             });
2076
2077             mZoomAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
2078                 @Override
2079                 public void onAnimationUpdate(ValueAnimator animation) {
2080                     float newScale = (Float) animation.getAnimatedValue();
2081                     float postScale = newScale / mScale;
2082                     mScale = newScale;
2083                     current.postScale(focusX, focusY, postScale, mDrawArea.width(),
2084                             mDrawArea.height());
2085                 }
2086             });
2087             mZoomAnimator.start();
2088         }
2089
2090         @Override
2091         public void scroll(float deltaX) {
2092             if (!stopScrolling(false)) {
2093                 return;
2094             }
2095             mCenterX += deltaX;
2096
2097             boolean stopScroll = clampCenterX();
2098             if (stopScroll) {
2099                 mController.stopScrolling(true);
2100             }
2101             invalidate();
2102         }
2103
2104         @Override
2105         public void fling(float velocityX) {
2106             if (!stopScrolling(false)) {
2107                 return;
2108             }
2109             final ViewItem item = mViewItem[mCurrentItem];
2110             if (item == null) {
2111                 return;
2112             }
2113
2114             float scaledVelocityX = velocityX / mScale;
2115             if (inFullScreen() && isViewTypeSticky(item) && scaledVelocityX < 0) {
2116                 // Swipe left in camera preview.
2117                 goToFilmstrip();
2118             }
2119
2120             int w = getWidth();
2121             // Estimation of possible length on the left. To ensure the
2122             // velocity doesn't become too slow eventually, we add a huge number
2123             // to the estimated maximum.
2124             int minX = estimateMinX(item.getId(), item.getLeftPosition(), w);
2125             // Estimation of possible length on the right. Likewise, exaggerate
2126             // the possible maximum too.
2127             int maxX = estimateMaxX(item.getId(), item.getLeftPosition(), w);
2128             mScroller.fling(mCenterX, 0, (int) -velocityX, 0, minX, maxX, 0, 0);
2129         }
2130
2131         void flingInsideZoomView(float velocityX, float velocityY) {
2132             if (!inZoomView()) {
2133                 return;
2134             }
2135
2136             final ViewItem current = mViewItem[mCurrentItem];
2137             if (current == null) {
2138                 return;
2139             }
2140
2141             final int factor = DECELERATION_FACTOR;
2142             // Deceleration curve for distance:
2143             // S(t) = s + (e - s) * (1 - (1 - t/T) ^ factor)
2144             // Need to find the ending distance (e), so that the starting
2145             // velocity is the velocity of fling.
2146             // Velocity is the derivative of distance
2147             // V(t) = (e - s) * factor * (-1) * (1 - t/T) ^ (factor - 1) * (-1/T)
2148             //      = (e - s) * factor * (1 - t/T) ^ (factor - 1) / T
2149             // Since V(0) = V0, we have e = T / factor * V0 + s
2150
2151             // Duration T should be long enough so that at the end of the fling,
2152             // image moves at 1 pixel/s for about P = 50ms = 0.05s
2153             // i.e. V(T - P) = 1
2154             // V(T - P) = V0 * (1 - (T -P) /T) ^ (factor - 1) = 1
2155             // T = P * V0 ^ (1 / (factor -1))
2156
2157             final float velocity = Math.max(Math.abs(velocityX), Math.abs(velocityY));
2158             // Dynamically calculate duration
2159             final float duration = (float) (FLING_COASTING_DURATION_S
2160                     * Math.pow(velocity, (1f / (factor - 1f))));
2161
2162             final float translationX = current.getTranslationX() * mScale;
2163             final float translationY = current.getTranslationY() * mScale;
2164
2165             final ValueAnimator decelerationX = ValueAnimator.ofFloat(translationX,
2166                     translationX + duration / factor * velocityX);
2167             final ValueAnimator decelerationY = ValueAnimator.ofFloat(translationY,
2168                     translationY + duration / factor * velocityY);
2169
2170             decelerationY.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
2171                 @Override
2172                 public void onAnimationUpdate(ValueAnimator animation) {
2173                     float transX = (Float) decelerationX.getAnimatedValue();
2174                     float transY = (Float) decelerationY.getAnimatedValue();
2175
2176                     current.updateTransform(transX, transY, mScale,
2177                             mScale, mDrawArea.width(), mDrawArea.height());
2178                 }
2179             });
2180
2181             mFlingAnimator = new AnimatorSet();
2182             mFlingAnimator.play(decelerationX).with(decelerationY);
2183             mFlingAnimator.setDuration((int) (duration * 1000));
2184             mFlingAnimator.setInterpolator(new TimeInterpolator() {
2185                 @Override
2186                 public float getInterpolation(float input) {
2187                     return (float) (1.0f - Math.pow((1.0f - input), factor));
2188                 }
2189             });
2190             mFlingAnimator.addListener(new Animator.AnimatorListener() {
2191                 private boolean mCancelled = false;
2192
2193                 @Override
2194                 public void onAnimationStart(Animator animation) {
2195
2196                 }
2197
2198                 @Override
2199                 public void onAnimationEnd(Animator animation) {
2200                     if (!mCancelled) {
2201                         loadZoomedImage();
2202                     }
2203                     mFlingAnimator = null;
2204                 }
2205
2206                 @Override
2207                 public void onAnimationCancel(Animator animation) {
2208                     mCancelled = true;
2209                 }
2210
2211                 @Override
2212                 public void onAnimationRepeat(Animator animation) {
2213
2214                 }
2215             });
2216             mFlingAnimator.start();
2217         }
2218
2219         @Override
2220         public boolean stopScrolling(boolean forced) {
2221             if (!isScrolling()) {
2222                 return true;
2223             } else if (!mCanStopScroll && !forced) {
2224                 return false;
2225             }
2226             mScroller.forceFinished(true);
2227             return true;
2228         }
2229
2230         private void stopScale() {
2231             mScaleAnimator.cancel();
2232         }
2233
2234         @Override
2235         public void scrollToPosition(int position, int duration, boolean interruptible) {
2236             if (mViewItem[mCurrentItem] == null) {
2237                 return;
2238             }
2239             mCanStopScroll = interruptible;
2240             mScroller.startScroll(mCenterX, 0, position - mCenterX, 0, duration);
2241         }
2242
2243         @Override
2244         public boolean goToNextItem() {
2245             return goToItem(mCurrentItem + 1);
2246         }
2247
2248         @Override
2249         public boolean goToPreviousItem() {
2250             return goToItem(mCurrentItem - 1);
2251         }
2252
2253         private boolean goToItem(int itemIndex) {
2254             final ViewItem nextItem = mViewItem[itemIndex];
2255             if (nextItem == null) {
2256                 return false;
2257             }
2258             stopScrolling(true);
2259             scrollToPosition(nextItem.getCenterX(), GEOMETRY_ADJUST_TIME_MS * 2, false);
2260
2261             if (isViewTypeSticky(mViewItem[mCurrentItem])) {
2262                 // Special case when moving from camera preview.
2263                 scaleTo(FILM_STRIP_SCALE, GEOMETRY_ADJUST_TIME_MS);
2264             }
2265             return true;
2266         }
2267
2268         private void scaleTo(float scale, int duration) {
2269             if (mViewItem[mCurrentItem] == null) {
2270                 return;
2271             }
2272             stopScale();
2273             mScaleAnimator.setDuration(duration);
2274             mScaleAnimator.setFloatValues(mScale, scale);
2275             mScaleAnimator.start();
2276         }
2277
2278         @Override
2279         public void goToFilmstrip() {
2280             if (mViewItem[mCurrentItem] == null) {
2281                 return;
2282             }
2283             if (mScale == FILM_STRIP_SCALE) {
2284                 return;
2285             }
2286             scaleTo(FILM_STRIP_SCALE, GEOMETRY_ADJUST_TIME_MS);
2287
2288             final ViewItem currItem = mViewItem[mCurrentItem];
2289             final ViewItem nextItem = mViewItem[mCurrentItem + 1];
2290             if (currItem.getId() == 0 && isViewTypeSticky(currItem) && nextItem != null) {
2291                 // Deal with the special case of swiping in camera preview.
2292                 scrollToPosition(nextItem.getCenterX(), GEOMETRY_ADJUST_TIME_MS, false);
2293             }
2294
2295             if (mScale == FILM_STRIP_SCALE) {
2296                 onLeaveFilmstrip();
2297             }
2298         }
2299
2300         @Override
2301         public void goToFullScreen() {
2302             if (inFullScreen()) {
2303                 return;
2304             }
2305
2306             scaleTo(FULL_SCREEN_SCALE, GEOMETRY_ADJUST_TIME_MS);
2307         }
2308
2309         private void cancelFlingAnimation() {
2310             // Cancels flinging for zoomed images
2311             if (isFlingAnimationRunning()) {
2312                 mFlingAnimator.cancel();
2313             }
2314         }
2315
2316         private void cancelZoomAnimation() {
2317             if (isZoomAnimationRunning()) {
2318                 mZoomAnimator.cancel();
2319             }
2320         }
2321
2322         private void setSurroundingViewsVisible(boolean visible) {
2323             // Hide everything on the left
2324             // TODO: Need to find a better way to toggle the visibility of views
2325             // around the current view.
2326             for (int i = 0; i < mCurrentItem; i++) {
2327                 if (i == mCurrentItem || mViewItem[i] == null) {
2328                     continue;
2329                 }
2330                 mViewItem[i].setVisibility(visible ? VISIBLE : INVISIBLE);
2331             }
2332         }
2333
2334         private Uri getCurrentUri() {
2335             ViewItem curr = mViewItem[mCurrentItem];
2336             if (curr == null) {
2337                 return Uri.EMPTY;
2338             }
2339             return mDataAdapter.getImageData(curr.getId()).getUri();
2340         }
2341
2342         /**
2343          * Here we only support up to 1:1 image zoom (i.e. a 100% view of the
2344          * actual pixels). The max scale that we can apply on the view should
2345          * make the view same size as the image, in pixels.
2346          */
2347         private float getCurrentDataMaxScale(boolean allowOverScale) {
2348             ViewItem curr = mViewItem[mCurrentItem];
2349             if (curr == null) {
2350                 return FULL_SCREEN_SCALE;
2351             }
2352             ImageData imageData = mDataAdapter.getImageData(curr.getId());
2353             if (imageData == null || !imageData.isUIActionSupported(ImageData.ACTION_ZOOM)) {
2354                 return FULL_SCREEN_SCALE;
2355             }
2356             float imageWidth = imageData.getWidth();
2357             if (imageData.getRotation() == 90
2358                     || imageData.getRotation() == 270) {
2359                 imageWidth = imageData.getHeight();
2360             }
2361             float scale = imageWidth / curr.getWidth();
2362             if (allowOverScale) {
2363                 // In addition to the scale we apply to the view for 100% view
2364                 // (i.e. each pixel on screen corresponds to a pixel in image)
2365                 // we allow scaling beyond that for better detail viewing.
2366                 scale *= mOverScaleFactor;
2367             }
2368             return scale;
2369         }
2370
2371         private void loadZoomedImage() {
2372             if (!inZoomView()) {
2373                 return;
2374             }
2375             ViewItem curr = mViewItem[mCurrentItem];
2376             if (curr == null) {
2377                 return;
2378             }
2379             ImageData imageData = mDataAdapter.getImageData(curr.getId());
2380             if (!imageData.isUIActionSupported(ImageData.ACTION_ZOOM)) {
2381                 return;
2382             }
2383             Uri uri = getCurrentUri();
2384             RectF viewRect = curr.getViewRect();
2385             if (uri == null || uri == Uri.EMPTY) {
2386                 return;
2387             }
2388             int orientation = imageData.getRotation();
2389             mZoomView.loadBitmap(uri, orientation, viewRect);
2390         }
2391
2392         private void cancelLoadingZoomedImage() {
2393             mZoomView.cancelPartialDecodingTask();
2394         }
2395
2396         @Override
2397         public void goToFirstItem() {
2398             if (mViewItem[mCurrentItem] == null) {
2399                 return;
2400             }
2401             resetZoomView();
2402             // TODO: animate to camera if it is still in the mViewItem buffer
2403             // versus a full reload which will perform an immediate transition
2404             reload();
2405         }
2406
2407         public boolean inZoomView() {
2408             return FilmstripView.this.inZoomView();
2409         }
2410
2411         public boolean isFlingAnimationRunning() {
2412             return mFlingAnimator != null && mFlingAnimator.isRunning();
2413         }
2414
2415         public boolean isZoomAnimationRunning() {
2416             return mZoomAnimator != null && mZoomAnimator.isRunning();
2417         }
2418     }
2419
2420     private boolean isCurrentItemCentered() {
2421         return mViewItem[mCurrentItem].getCenterX() == mCenterX;
2422     }
2423
2424     private static class MyScroller {
2425         public interface Listener {
2426             public void onScrollUpdate(int currX, int currY);
2427
2428             public void onScrollEnd();
2429         }
2430
2431         private final Handler mHandler;
2432         private final Listener mListener;
2433
2434         private final Scroller mScroller;
2435
2436         private final ValueAnimator mXScrollAnimator;
2437         private final Runnable mScrollChecker = new Runnable() {
2438             @Override
2439             public void run() {
2440                 boolean newPosition = mScroller.computeScrollOffset();
2441                 if (!newPosition) {
2442                     mListener.onScrollEnd();
2443                     return;
2444                 }
2445                 mListener.onScrollUpdate(mScroller.getCurrX(), mScroller.getCurrY());
2446                 mHandler.removeCallbacks(this);
2447                 mHandler.post(this);
2448             }
2449         };
2450
2451         private final ValueAnimator.AnimatorUpdateListener mXScrollAnimatorUpdateListener =
2452                 new ValueAnimator.AnimatorUpdateListener() {
2453                     @Override
2454                     public void onAnimationUpdate(ValueAnimator animation) {
2455                         mListener.onScrollUpdate((Integer) animation.getAnimatedValue(), 0);
2456                     }
2457                 };
2458
2459         private final Animator.AnimatorListener mXScrollAnimatorListener =
2460                 new Animator.AnimatorListener() {
2461                     @Override
2462                     public void onAnimationCancel(Animator animation) {
2463                         // Do nothing.
2464                     }
2465
2466                     @Override
2467                     public void onAnimationEnd(Animator animation) {
2468                         mListener.onScrollEnd();
2469                     }
2470
2471                     @Override
2472                     public void onAnimationRepeat(Animator animation) {
2473                         // Do nothing.
2474                     }
2475
2476                     @Override
2477                     public void onAnimationStart(Animator animation) {
2478                         // Do nothing.
2479                     }
2480                 };
2481
2482         public MyScroller(Context ctx, Handler handler, Listener listener,
2483                 TimeInterpolator interpolator) {
2484             mHandler = handler;
2485             mListener = listener;
2486             mScroller = new Scroller(ctx);
2487             mXScrollAnimator = new ValueAnimator();
2488             mXScrollAnimator.addUpdateListener(mXScrollAnimatorUpdateListener);
2489             mXScrollAnimator.addListener(mXScrollAnimatorListener);
2490             mXScrollAnimator.setInterpolator(interpolator);
2491         }
2492
2493         public void fling(
2494                 int startX, int startY,
2495                 int velocityX, int velocityY,
2496                 int minX, int maxX,
2497                 int minY, int maxY) {
2498             mScroller.fling(startX, startY, velocityX, velocityY, minX, maxX, minY, maxY);
2499             runChecker();
2500         }
2501
2502         public void startScroll(int startX, int startY, int dx, int dy) {
2503             mScroller.startScroll(startX, startY, dx, dy);
2504             runChecker();
2505         }
2506
2507         /** Only starts and updates scroll in x-axis. */
2508         public void startScroll(int startX, int startY, int dx, int dy, int duration) {
2509             mXScrollAnimator.cancel();
2510             mXScrollAnimator.setDuration(duration);
2511             mXScrollAnimator.setIntValues(startX, startX + dx);
2512             mXScrollAnimator.start();
2513         }
2514
2515         public boolean isFinished() {
2516             return (mScroller.isFinished() && !mXScrollAnimator.isRunning());
2517         }
2518
2519         public void forceFinished(boolean finished) {
2520             mScroller.forceFinished(finished);
2521             if (finished) {
2522                 mXScrollAnimator.cancel();
2523             }
2524         }
2525
2526         private void runChecker() {
2527             if (mHandler == null || mListener == null) {
2528                 return;
2529             }
2530             mHandler.removeCallbacks(mScrollChecker);
2531             mHandler.post(mScrollChecker);
2532         }
2533     }
2534
2535     private class MyGestureReceiver implements FilmstripGestureRecognizer.Listener {
2536
2537         private static final int SCROLL_DIR_NONE = 0;
2538         private static final int SCROLL_DIR_VERTICAL = 1;
2539         private static final int SCROLL_DIR_HORIZONTAL = 2;
2540         // Indicating the current trend of scaling is up (>1) or down (<1).
2541         private float mScaleTrend;
2542         private float mMaxScale;
2543         private int mScrollingDirection = SCROLL_DIR_NONE;
2544         private long mLastDownTime;
2545         private float mLastDownY;
2546
2547         @Override
2548         public boolean onSingleTapUp(float x, float y) {
2549             ViewItem centerItem = mViewItem[mCurrentItem];
2550             if (inFilmstrip()) {
2551                 if (centerItem != null && centerItem.areaContains(x, y)) {
2552                     mController.goToFullScreen();
2553                     return true;
2554                 }
2555             } else if (inFullScreen()) {
2556                 if (mFullScreenUIHidden) {
2557                     onLeaveFullScreenUiHidden();
2558                     onEnterFullScreen();
2559                 } else {
2560                     onLeaveFullScreen();
2561                     onEnterFullScreenUiHidden();
2562                 }
2563                 return true;
2564             }
2565             return false;
2566         }
2567
2568         @Override
2569         public boolean onDoubleTap(float x, float y) {
2570             ViewItem current = mViewItem[mCurrentItem];
2571             if (current == null) {
2572                 return false;
2573             }
2574             if (inFilmstrip()) {
2575                 mController.goToFullScreen();
2576                 return true;
2577             } else if (mScale < FULL_SCREEN_SCALE || inCameraFullscreen()) {
2578                 return false;
2579             }
2580             if (!mController.stopScrolling(false)) {
2581                 return false;
2582             }
2583             if (inFullScreen()) {
2584                 mController.zoomAt(current, x, y);
2585                 checkItemAtMaxSize();
2586                 return true;
2587             } else if (mScale > FULL_SCREEN_SCALE) {
2588                 // In zoom view.
2589                 mController.zoomAt(current, x, y);
2590             }
2591             return false;
2592         }
2593
2594         @Override
2595         public boolean onDown(float x, float y) {
2596             mLastDownTime = SystemClock.uptimeMillis();
2597             mLastDownY = y;
2598             mController.cancelFlingAnimation();
2599             if (!mController.stopScrolling(false)) {
2600                 return false;
2601             }
2602
2603             return true;
2604         }
2605
2606         @Override
2607         public boolean onUp(float x, float y) {
2608             ViewItem currItem = mViewItem[mCurrentItem];
2609             if (currItem == null) {
2610                 return false;
2611             }
2612             if (mController.isZoomAnimationRunning() || mController.isFlingAnimationRunning()) {
2613                 return false;
2614             }
2615             if (inZoomView()) {
2616                 mController.loadZoomedImage();
2617                 return true;
2618             }
2619             float promoteHeight = getHeight() * PROMOTE_HEIGHT_RATIO;
2620             float velocityPromoteHeight = getHeight() * VELOCITY_PROMOTE_HEIGHT_RATIO;
2621             mIsUserScrolling = false;
2622             mScrollingDirection = SCROLL_DIR_NONE;
2623             // Finds items promoted/demoted.
2624             float speedY = Math.abs(y - mLastDownY)
2625                     / (SystemClock.uptimeMillis() - mLastDownTime);
2626             for (int i = 0; i < BUFFER_SIZE; i++) {
2627                 if (mViewItem[i] == null) {
2628                     continue;
2629                 }
2630                 float transY = mViewItem[i].getTranslationY();
2631                 if (transY == 0) {
2632                     continue;
2633                 }
2634                 int id = mViewItem[i].getId();
2635
2636                 if (mDataAdapter.getImageData(id)
2637                         .isUIActionSupported(ImageData.ACTION_DEMOTE)
2638                         && ((transY > promoteHeight)
2639                             || (transY > velocityPromoteHeight && speedY > PROMOTE_VELOCITY))) {
2640                     demoteData(i, id);
2641                 } else if (mDataAdapter.getImageData(id)
2642                         .isUIActionSupported(ImageData.ACTION_PROMOTE)
2643                         && (transY < -promoteHeight
2644                             || (transY < -velocityPromoteHeight && speedY > PROMOTE_VELOCITY))) {
2645                     promoteData(i, id);
2646                 } else {
2647                     // put the view back.
2648                     slideViewBack(mViewItem[i]);
2649                 }
2650             }
2651
2652             // The data might be changed. Re-check.
2653             currItem = mViewItem[mCurrentItem];
2654             if (currItem == null) {
2655                 return true;
2656             }
2657
2658             int currId = currItem.getId();
2659             if (mCenterX > currItem.getCenterX() + CAMERA_PREVIEW_SWIPE_THRESHOLD && currId == 0 &&
2660                     isViewTypeSticky(currItem) && mDataIdOnUserScrolling == 0) {
2661                 mController.goToFilmstrip();
2662                 // Special case to go from camera preview to the next photo.
2663                 if (mViewItem[mCurrentItem + 1] != null) {
2664                     mController.scrollToPosition(
2665                             mViewItem[mCurrentItem + 1].getCenterX(),
2666                             GEOMETRY_ADJUST_TIME_MS, false);
2667                 } else {
2668                     // No next photo.
2669                     snapInCenter();
2670                 }
2671             }
2672             if (isCurrentItemCentered() && currId == 0 && isViewTypeSticky(currItem)) {
2673                 mController.goToFullScreen();
2674             } else {
2675                 if (mDataIdOnUserScrolling == 0 && currId != 0) {
2676                     // Special case to go to filmstrip when the user scroll away
2677                     // from the camera preview and the current one is not the
2678                     // preview anymore.
2679                     mController.goToFilmstrip();
2680                     mDataIdOnUserScrolling = currId;
2681                 }
2682                 snapInCenter();
2683             }
2684             return false;
2685         }
2686
2687         @Override
2688         public void onLongPress(float x, float y) {
2689             final int dataId = getCurrentId();
2690             if (dataId == -1) {
2691                 return;
2692             }
2693             mListener.onFocusedDataLongPressed(dataId);
2694         }
2695
2696         @Override
2697         public boolean onScroll(float x, float y, float dx, float dy) {
2698             final ViewItem currItem = mViewItem[mCurrentItem];
2699             if (currItem == null) {
2700                 return false;
2701             }
2702             if (inFullScreen() && !mDataAdapter.canSwipeInFullScreen(currItem.getId())) {
2703                 return false;
2704             }
2705             hideZoomView();
2706             // When image is zoomed in to be bigger than the screen
2707             if (inZoomView()) {
2708                 ViewItem curr = mViewItem[mCurrentItem];
2709                 float transX = curr.getTranslationX() * mScale - dx;
2710                 float transY = curr.getTranslationY() * mScale - dy;
2711                 curr.updateTransform(transX, transY, mScale, mScale, mDrawArea.width(),
2712                         mDrawArea.height());
2713                 return true;
2714             }
2715             int deltaX = (int) (dx / mScale);
2716             // Forces the current scrolling to stop.
2717             mController.stopScrolling(true);
2718             if (!mIsUserScrolling) {
2719                 mIsUserScrolling = true;
2720                 mDataIdOnUserScrolling = mViewItem[mCurrentItem].getId();
2721             }
2722             if (inFilmstrip()) {
2723                 // Disambiguate horizontal/vertical first.
2724                 if (mScrollingDirection == SCROLL_DIR_NONE) {
2725                     mScrollingDirection = (Math.abs(dx) > Math.abs(dy)) ? SCROLL_DIR_HORIZONTAL :
2726                             SCROLL_DIR_VERTICAL;
2727                 }
2728                 if (mScrollingDirection == SCROLL_DIR_HORIZONTAL) {
2729                     if (mCenterX == currItem.getCenterX() && currItem.getId() == 0 && dx < 0) {
2730                         // Already at the beginning, don't process the swipe.
2731                         mIsUserScrolling = false;
2732                         mScrollingDirection = SCROLL_DIR_NONE;
2733                         return false;
2734                     }
2735                     mController.scroll(deltaX);
2736                 } else {
2737                     // Vertical part. Promote or demote.
2738                     int hit = 0;
2739                     Rect hitRect = new Rect();
2740                     for (; hit < BUFFER_SIZE; hit++) {
2741                         if (mViewItem[hit] == null) {
2742                             continue;
2743                         }
2744                         mViewItem[hit].getHitRect(hitRect);
2745                         if (hitRect.contains((int) x, (int) y)) {
2746                             break;
2747                         }
2748                     }
2749                     if (hit == BUFFER_SIZE) {
2750                         // Hit none.
2751                         return true;
2752                     }
2753
2754                     ImageData data = mDataAdapter.getImageData(mViewItem[hit].getId());
2755                     float transY = mViewItem[hit].getTranslationY() - dy / mScale;
2756                     if (!data.isUIActionSupported(ImageData.ACTION_DEMOTE) &&
2757                             transY > 0f) {
2758                         transY = 0f;
2759                     }
2760                     if (!data.isUIActionSupported(ImageData.ACTION_PROMOTE) &&
2761                             transY < 0f) {
2762                         transY = 0f;
2763                     }
2764                     mViewItem[hit].setTranslationY(transY);
2765                 }
2766             } else if (inFullScreen()) {
2767                 if (mViewItem[mCurrentItem] == null || (deltaX < 0 && mCenterX <=
2768                         currItem.getCenterX() && currItem.getId() == 0)) {
2769                     return false;
2770                 }
2771                 // Multiplied by 1.2 to make it more easy to swipe.
2772                 mController.scroll((int) (deltaX * 1.2));
2773             }
2774             invalidate();
2775
2776             return true;
2777         }
2778
2779         @Override
2780         public boolean onMouseScroll(float hscroll, float vscroll) {
2781             final float scroll;
2782
2783             hscroll *= MOUSE_SCROLL_FACTOR;
2784             vscroll *= MOUSE_SCROLL_FACTOR;
2785
2786             if (vscroll != 0f) {
2787                 scroll = vscroll;
2788             } else {
2789                 scroll = hscroll;
2790             }
2791
2792             if (inFullScreen()) {
2793                 onFling(-scroll, 0f);
2794             } else if (inZoomView()) {
2795                 onScroll(0f, 0f, hscroll, vscroll);
2796             } else {
2797                 onScroll(0f, 0f, scroll, 0f);
2798             }
2799
2800             return true;
2801         }
2802
2803         @Override
2804         public boolean onFling(float velocityX, float velocityY) {
2805             final ViewItem currItem = mViewItem[mCurrentItem];
2806             if (currItem == null) {
2807                 return false;
2808             }
2809             if (!mDataAdapter.canSwipeInFullScreen(currItem.getId())) {
2810                 return false;
2811             }
2812             if (inZoomView()) {
2813                 // Fling within the zoomed image
2814                 mController.flingInsideZoomView(velocityX, velocityY);
2815                 return true;
2816             }
2817             if (Math.abs(velocityX) < Math.abs(velocityY)) {
2818                 // ignore vertical fling.
2819                 return true;
2820             }
2821
2822             // In full-screen, fling of a velocity above a threshold should go
2823             // to the next/prev photos
2824             if (mScale == FULL_SCREEN_SCALE) {
2825                 int currItemCenterX = currItem.getCenterX();
2826
2827                 if (velocityX > 0) { // left
2828                     if (mCenterX > currItemCenterX) {
2829                         // The visually previous item is actually the current
2830                         // item.
2831                         mController.scrollToPosition(
2832                                 currItemCenterX, GEOMETRY_ADJUST_TIME_MS, true);
2833                         return true;
2834                     }
2835                     ViewItem prevItem = mViewItem[mCurrentItem - 1];
2836                     if (prevItem == null) {
2837                         return false;
2838                     }
2839                     mController.scrollToPosition(
2840                             prevItem.getCenterX(), GEOMETRY_ADJUST_TIME_MS, true);
2841                 } else { // right
2842                     if (mController.stopScrolling(false)) {
2843                         if (mCenterX < currItemCenterX) {
2844                             // The visually next item is actually the current
2845                             // item.
2846                             mController.scrollToPosition(
2847                                     currItemCenterX, GEOMETRY_ADJUST_TIME_MS, true);
2848                             return true;
2849                         }
2850                         final ViewItem nextItem = mViewItem[mCurrentItem + 1];
2851                         if (nextItem == null) {
2852                             return false;
2853                         }
2854                         mController.scrollToPosition(
2855                                 nextItem.getCenterX(), GEOMETRY_ADJUST_TIME_MS, true);
2856                         if (isViewTypeSticky(currItem)) {
2857                             mController.goToFilmstrip();
2858                         }
2859                     }
2860                 }
2861             }
2862
2863             if (mScale == FILM_STRIP_SCALE) {
2864                 mController.fling(velocityX);
2865             }
2866             return true;
2867         }
2868
2869         @Override
2870         public boolean onScaleBegin(float focusX, float focusY) {
2871             if (inCameraFullscreen()) {
2872                 return false;
2873             }
2874
2875             hideZoomView();
2876             mScaleTrend = 1f;
2877             // If the image is smaller than screen size, we should allow to zoom
2878             // in to full screen size
2879             mMaxScale = Math.max(mController.getCurrentDataMaxScale(true), FULL_SCREEN_SCALE);
2880             return true;
2881         }
2882
2883         @Override
2884         public boolean onScale(float focusX, float focusY, float scale) {
2885             if (inCameraFullscreen()) {
2886                 return false;
2887             }
2888
2889             mScaleTrend = mScaleTrend * 0.3f + scale * 0.7f;
2890             float newScale = mScale * scale;
2891             if (mScale < FULL_SCREEN_SCALE && newScale < FULL_SCREEN_SCALE) {
2892                 if (newScale <= FILM_STRIP_SCALE) {
2893                     newScale = FILM_STRIP_SCALE;
2894                 }
2895                 // Scaled view is smaller than or equal to screen size both
2896                 // before and after scaling
2897                 if (mScale != newScale) {
2898                     if (mScale == FILM_STRIP_SCALE) {
2899                         onLeaveFilmstrip();
2900                     }
2901                     if (newScale == FILM_STRIP_SCALE) {
2902                         onEnterFilmstrip();
2903                     }
2904                 }
2905                 mScale = newScale;
2906                 invalidate();
2907             } else if (mScale < FULL_SCREEN_SCALE && newScale >= FULL_SCREEN_SCALE) {
2908                 // Going from smaller than screen size to bigger than or equal
2909                 // to screen size
2910                 if (mScale == FILM_STRIP_SCALE) {
2911                     onLeaveFilmstrip();
2912                 }
2913                 mScale = FULL_SCREEN_SCALE;
2914                 onEnterFullScreen();
2915                 mController.setSurroundingViewsVisible(false);
2916                 invalidate();
2917             } else if (mScale >= FULL_SCREEN_SCALE && newScale < FULL_SCREEN_SCALE) {
2918                 // Going from bigger than or equal to screen size to smaller
2919                 // than screen size
2920                 if (inFullScreen()) {
2921                     if (mFullScreenUIHidden) {
2922                         onLeaveFullScreenUiHidden();
2923                     } else {
2924                         onLeaveFullScreen();
2925                     }
2926                 } else {
2927                     onLeaveZoomView();
2928                 }
2929                 mScale = newScale;
2930                 onEnterFilmstrip();
2931                 invalidate();
2932             } else {
2933                 // Scaled view bigger than or equal to screen size both before
2934                 // and after scaling
2935                 if (!inZoomView()) {
2936                     mController.setSurroundingViewsVisible(false);
2937                 }
2938                 ViewItem curr = mViewItem[mCurrentItem];
2939                 // Make sure the image is not overly scaled
2940                 newScale = Math.min(newScale, mMaxScale);
2941                 if (newScale == mScale) {
2942                     return true;
2943                 }
2944                 float postScale = newScale / mScale;
2945                 curr.postScale(focusX, focusY, postScale, mDrawArea.width(), mDrawArea.height());
2946                 mScale = newScale;
2947                 if (mScale == FULL_SCREEN_SCALE) {
2948                     onEnterFullScreen();
2949                 } else {
2950                     onEnterZoomView();
2951                 }
2952                 checkItemAtMaxSize();
2953             }
2954             return true;
2955         }
2956
2957         @Override
2958         public void onScaleEnd() {
2959             zoomAtIndexChanged();
2960             if (mScale > FULL_SCREEN_SCALE + TOLERANCE) {
2961                 return;
2962             }
2963             mController.setSurroundingViewsVisible(true);
2964             if (mScale <= FILM_STRIP_SCALE + TOLERANCE) {
2965                 mController.goToFilmstrip();
2966             } else if (mScaleTrend > 1f || mScale > FULL_SCREEN_SCALE - TOLERANCE) {
2967                 if (inZoomView()) {
2968                     mScale = FULL_SCREEN_SCALE;
2969                     resetZoomView();
2970                 }
2971                 mController.goToFullScreen();
2972             } else {
2973                 mController.goToFilmstrip();
2974             }
2975             mScaleTrend = 1f;
2976         }
2977     }
2978 }