OSDN Git Service

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