2 * Copyright (C) 2013 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.camera.widget;
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;
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;
58 import java.lang.ref.WeakReference;
59 import java.util.ArrayDeque;
60 import java.util.Arrays;
61 import java.util.Queue;
63 public class FilmstripView extends ViewGroup {
65 * An action callback to be used for actions on the local media data items.
67 public static class ActionCallbackImpl implements ActionCallback {
68 private final WeakReference<Activity> mActivity;
71 * The given activity is used to start intents. It is wrapped in a weak
72 * reference to prevent leaks.
74 public ActionCallbackImpl(Activity activity) {
75 mActivity = new WeakReference<Activity>(activity);
79 * Fires an intent to play the video with the given URI and title.
82 public void playVideo(Uri uri, String title) {
83 Activity activity = mActivity.get();
84 if (activity != null) {
85 CameraUtil.playVideo(activity, uri, title);
91 private static final Log.Tag TAG = new Log.Tag("FilmstripView");
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;
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;
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;
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();
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];
135 private FilmstripController.FilmstripListener mListener;
136 private ZoomView mZoomView = null;
138 private MotionEvent mDown;
139 private boolean mCheckToIntercept = true;
141 private TimeInterpolator mViewAnimInterpolator;
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;
148 private boolean mFullScreenUIHidden = false;
149 private final SparseArray<Queue<View>> recycledViews = new SparseArray<Queue<View>>();
152 * A helper class to tract and calculate the view coordination.
154 private class ViewItem {
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;
163 private ValueAnimator mTranslationXAnimator;
164 private ValueAnimator mTranslationYAnimator;
165 private ValueAnimator mAlphaAnimator;
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.
174 public ViewItem(int id, View v, ImageData data) {
180 mMaximumBitmapRequested = false;
182 mViewArea = new RectF();
185 public boolean isMaximumBitmapRequested() {
186 return mMaximumBitmapRequested;
189 public void setMaximumBitmapRequested() {
190 mMaximumBitmapRequested = true;
194 * Returns the data id from
195 * {@link com.android.camera.filmstrip.DataAdapter}.
202 * Sets the data id from
203 * {@link com.android.camera.filmstrip.DataAdapter}.
205 public void setId(int id) {
209 /** Sets the left position of the view in the whole filmstrip. */
210 public void setLeftPosition(int pos) {
214 /** Returns the left position of the view in the whole filmstrip. */
215 public int getLeftPosition() {
216 return mLeftPosition;
219 /** Returns the translation of Y regarding the view scale. */
220 public float getTranslationY() {
221 return mView.getTranslationY() / mScale;
224 /** Returns the translation of X regarding the view scale. */
225 public float getTranslationX() {
226 return mView.getTranslationX() / mScale;
229 /** Sets the translation of Y regarding the view scale. */
230 public void setTranslationY(float transY) {
231 mView.setTranslationY(transY * mScale);
234 /** Sets the translation of X regarding the view scale. */
235 public void setTranslationX(float transX) {
236 mView.setTranslationX(transX * mScale);
239 /** Forwarding of {@link android.view.View#setAlpha(float)}. */
240 public void setAlpha(float alpha) {
241 mView.setAlpha(alpha);
244 /** Forwarding of {@link android.view.View#getAlpha()}. */
245 public float getAlpha() {
246 return mView.getAlpha();
249 /** Forwarding of {@link android.view.View#getMeasuredWidth()}. */
250 public int getMeasuredWidth() {
251 return mView.getMeasuredWidth();
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
261 * @param targetX The final value.
262 * @param duration_ms The duration of the animation.
263 * @param interpolator Time interpolator.
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() {
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().
280 runAnimation(mTranslationXAnimator, getTranslationX(), targetX, duration_ms,
285 * Animates the Y translation of the view.
287 * @param targetY The final value.
288 * @param duration_ms The duration of the animation.
289 * @param interpolator Time interpolator.
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() {
297 public void onAnimationUpdate(ValueAnimator valueAnimator) {
298 setTranslationY((Float) valueAnimator.getAnimatedValue());
302 runAnimation(mTranslationYAnimator, getTranslationY(), targetY, duration_ms,
307 * Animates the alpha value of the view.
309 * @param targetAlpha The final value.
310 * @param duration_ms The duration of the animation.
311 * @param interpolator Time interpolator.
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() {
319 public void onAnimationUpdate(ValueAnimator valueAnimator) {
320 ViewItem.this.setAlpha((Float) valueAnimator.getAnimatedValue());
324 runAnimation(mAlphaAnimator, getAlpha(), targetAlpha, duration_ms, interpolator);
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) {
333 animator.setInterpolator(interpolator);
334 animator.setDuration(duration_ms);
335 animator.setFloatValues(startValue, targetValue);
339 /** Adjusts the translation of X regarding the view scale. */
340 public void translateXScaledBy(float transX) {
341 setTranslationX(getTranslationX() + transX * mScale);
345 * Forwarding of {@link android.view.View#getHitRect(android.graphics.Rect)}.
347 public void getHitRect(Rect rect) {
348 mView.getHitRect(rect);
351 public int getCenterX() {
352 return mLeftPosition + mView.getMeasuredWidth() / 2;
355 /** Forwarding of {@link android.view.View#getVisibility()}. */
356 public int getVisibility() {
357 return mView.getVisibility();
360 /** Forwarding of {@link android.view.View#setVisibility(int)}. */
361 public void setVisibility(int visibility) {
362 mView.setVisibility(visibility);
366 * Notifies the {@link com.android.camera.filmstrip.DataAdapter} to
369 public void resizeView(Context context, int w, int h) {
370 mDataAdapter.resizeView(context, mDataId, mView, w, h);
374 * Adds the view of the data to the view hierarchy if necessary.
376 public void addViewToHierarchy() {
377 if (indexOfChild(mView) < 0) {
382 setVisibility(View.VISIBLE);
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.
392 * @param force {@code true} to remove the view from the hierarchy
393 * regardless of the view type.
395 public void removeViewFromHierarchy(boolean force) {
396 if (force || mData.getViewType() != ImageData.VIEW_TYPE_STICKY) {
398 mData.recycle(mView);
399 recycleView(mView, mDataId);
401 setVisibility(View.INVISIBLE);
406 * Brings the view to front by
407 * {@link #bringChildToFront(android.view.View)}
409 public void bringViewToFront() {
410 bringChildToFront(mView);
414 * The visual x position of this view, in pixels.
416 public float getX() {
421 * The visual y position of this view, in pixels.
423 public float getY() {
428 * Forwarding of {@link android.view.View#measure(int, int)}.
430 public void measure(int widthSpec, int heightSpec) {
431 mView.measure(widthSpec, heightSpec);
434 private void layoutAt(int left, int top) {
435 mView.layout(left, top, left + mView.getMeasuredWidth(),
436 top + mView.getMeasuredHeight());
440 * The bounding rect of the view.
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();
451 private View getView() {
456 * Layouts the view in the area assuming the center of the area is at a
457 * specific point of the whole filmstrip.
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.
464 public void layoutWithTranslationX(Rect drawArea, int refCenter, float scale) {
465 final float translationX =
466 ((mTranslationXAnimator != null && mTranslationXAnimator.isRunning()) ?
467 (Float) mTranslationXAnimator.getAnimatedValue() : 0);
469 (int) (drawArea.centerX() + (mLeftPosition - refCenter + translationX) * scale);
470 int top = (int) (drawArea.centerY() - (mView.getMeasuredHeight() / 2) * scale);
472 mView.setScaleX(scale);
473 mView.setScaleY(scale);
475 // update mViewArea for touch detection.
476 int l = mView.getLeft();
477 int t = mView.getTop();
479 l + mView.getMeasuredWidth() * scale,
480 t + mView.getMeasuredHeight() * scale);
483 /** Returns true if the point is in the view. */
484 public boolean areaContains(float x, float y) {
485 return mViewArea.contains(x, y);
489 * Return the width of the view.
491 public int getWidth() {
492 return mView.getWidth();
496 * Returns the position of the left edge of the view area content is drawn in.
498 public int getDrawAreaLeft() {
499 return Math.round(mViewArea.left);
502 public void copyAttributes(ViewItem item) {
503 setLeftPosition(item.getLeftPosition());
505 setTranslationX(item.getTranslationX());
506 if (item.mTranslationXAnimator != null) {
507 mTranslationXAnimator = item.mTranslationXAnimator;
508 mTranslationXAnimator.removeAllUpdateListeners();
509 mTranslationXAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
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().
521 setTranslationY(item.getTranslationY());
522 if (item.mTranslationYAnimator != null) {
523 mTranslationYAnimator = item.mTranslationYAnimator;
524 mTranslationYAnimator.removeAllUpdateListeners();
525 mTranslationYAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
527 public void onAnimationUpdate(ValueAnimator valueAnimator) {
528 setTranslationY((Float) valueAnimator.getAnimatedValue());
533 setAlpha(item.getAlpha());
534 if (item.mAlphaAnimator != null) {
535 mAlphaAnimator = item.mAlphaAnimator;
536 mAlphaAnimator.removeAllUpdateListeners();
537 mAlphaAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
539 public void onAnimationUpdate(ValueAnimator valueAnimator) {
540 ViewItem.this.setAlpha((Float) valueAnimator.getAnimatedValue());
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.
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,
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);
581 void resetTransform() {
582 mView.setScaleX(FULL_SCREEN_SCALE);
583 mView.setScaleY(FULL_SCREEN_SCALE);
584 mView.setTranslationX(0f);
585 mView.setTranslationY(0f);
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();
601 public FilmstripView(Context context) {
603 init((CameraActivity) context);
607 public FilmstripView(Context context, AttributeSet attrs) {
608 super(context, attrs);
609 init((CameraActivity) context);
613 public FilmstripView(Context context, AttributeSet attrs, int defStyle) {
614 super(context, attrs, defStyle);
615 init((CameraActivity) context);
618 private void init(CameraActivity cameraActivity) {
619 setWillNotDraw(false);
620 mActivity = cameraActivity;
621 mActionCallback = new ActionCallbackImpl(mActivity);
623 mDataIdOnUserScrolling = 0;
624 mController = new MyController(cameraActivity);
625 mViewAnimInterpolator = new DecelerateInterpolator();
626 mZoomView = new ZoomView(cameraActivity);
627 mZoomView.setVisibility(GONE);
630 mGestureListener = new MyGestureReceiver();
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;
645 setAccessibilityDelegate(new AccessibilityDelegate() {
647 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
648 super.onInitializeAccessibilityNodeInfo(host, info);
650 info.setClassName(FilmstripView.class.getName());
651 info.setScrollable(true);
652 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
653 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
657 public boolean performAccessibilityAction(View host, int action, Bundle args) {
658 if (!mController.isScrolling()) {
660 case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: {
661 mController.goToNextItem();
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();
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);
681 return super.performAccessibilityAction(host, action, args);
686 private void recycleView(View view, int dataId) {
687 final int viewType = (Integer) view.getTag(R.id.mediadata_tag_viewtype);
689 Queue<View> recycledViewsForType = recycledViews.get(viewType);
690 if (recycledViewsForType == null) {
691 recycledViewsForType = new ArrayDeque<View>();
692 recycledViews.put(viewType, recycledViewsForType);
694 recycledViewsForType.offer(view);
698 private View getRecycledView(int dataId) {
699 final int viewType = mDataAdapter.getItemViewType(dataId);
700 Queue<View> recycledViewsForType = recycledViews.get(viewType);
702 if (recycledViewsForType != null) {
703 result = recycledViewsForType.poll();
709 * Returns the controller.
711 * @return The {@code Controller}.
713 public FilmstripController getController() {
718 * Returns the draw area width of the current item.
720 public int getCurrentItemLeft() {
721 return mViewItem[mCurrentItem].getDrawAreaLeft();
724 private void setListener(FilmstripController.FilmstripListener l) {
728 private void setViewGap(int viewGap) {
729 mViewGapInPixel = viewGap;
733 * Called after current item or zoom level has changed.
735 public void zoomAtIndexChanged() {
736 if (mViewItem[mCurrentItem] == null) {
739 int id = mViewItem[mCurrentItem].getId();
740 mListener.onZoomAtIndexChanged(id, mScale);
744 * Checks if the data is at the center.
746 * @param id The id of the data to check.
747 * @return {@code True} if the data is currently at the center.
749 private boolean isDataAtCenter(int id) {
750 if (mViewItem[mCurrentItem] == null) {
753 if (mViewItem[mCurrentItem].getId() == id
754 && isCurrentItemCentered()) {
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");
768 Point dim = CameraUtil.resizeToFill(imageData.getWidth(), imageData.getHeight(),
769 imageData.getRotation(), boundWidth, boundHeight);
771 item.measure(MeasureSpec.makeMeasureSpec(dim.x, MeasureSpec.EXACTLY),
772 MeasureSpec.makeMeasureSpec(dim.y, MeasureSpec.EXACTLY));
776 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
777 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
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.
786 for (ViewItem item : mViewItem) {
788 measureViewItem(item, boundWidth, boundHeight);
793 mZoomView.measure(MeasureSpec.makeMeasureSpec(widthMeasureSpec, MeasureSpec.EXACTLY),
794 MeasureSpec.makeMeasureSpec(heightMeasureSpec, MeasureSpec.EXACTLY));
797 private int findTheNearestView(int pointX) {
800 // Find the first non-null ViewItem.
801 while (nearest < BUFFER_SIZE
802 && (mViewItem[nearest] == null || mViewItem[nearest].getLeftPosition() == -1)) {
805 // No existing available ViewItem
806 if (nearest == BUFFER_SIZE) {
810 int min = Math.abs(pointX - mViewItem[nearest].getCenterX());
812 for (int itemID = nearest + 1; itemID < BUFFER_SIZE && mViewItem[itemID] != null; itemID++) {
814 if (mViewItem[itemID].getLeftPosition() == -1) {
818 int c = mViewItem[itemID].getCenterX();
819 int dist = Math.abs(pointX - c);
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");
835 ImageData data = mDataAdapter.getImageData(dataID);
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);
849 View recycled = getRecycledView(dataID);
850 View v = mDataAdapter.getView(mActivity.getAndroidContext(), recycled, dataID,
855 ViewItem item = new ViewItem(dataID, v, data);
856 item.addViewToHierarchy();
860 private void checkItemAtMaxSize() {
861 ViewItem item = mViewItem[mCurrentItem];
862 if (item.isMaximumBitmapRequested()) {
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);
873 private void removeItem(int itemID) {
874 if (itemID >= mViewItem.length || mViewItem[itemID] == null) {
877 ImageData data = mDataAdapter.getImageData(mViewItem[itemID].getId());
879 Log.e(TAG, "trying to remove a null item");
882 mViewItem[itemID].removeViewFromHierarchy(false);
883 mViewItem[itemID] = null;
887 * We try to keep the one closest to the center of the screen at position
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.
896 final int nearest = findTheNearestView(mCenterX);
898 if (nearest == -1 || nearest == mCurrentItem) {
901 int prevDataId = (mViewItem[mCurrentItem] == null ? -1 : mViewItem[mCurrentItem].getId());
902 final int adjust = nearest - mCurrentItem;
904 for (int k = 0; k < adjust; k++) {
907 for (int k = 0; k + adjust < BUFFER_SIZE; k++) {
908 mViewItem[k] = mViewItem[k + adjust];
910 for (int k = BUFFER_SIZE - adjust; k < BUFFER_SIZE; k++) {
912 if (mViewItem[k - 1] != null) {
913 mViewItem[k] = buildItemFromData(mViewItem[k - 1].getId() + 1);
918 for (int k = BUFFER_SIZE - 1; k >= BUFFER_SIZE + adjust; k--) {
921 for (int k = BUFFER_SIZE - 1; k + adjust >= 0; k--) {
922 mViewItem[k] = mViewItem[k + adjust];
924 for (int k = -1 - adjust; k >= 0; k--) {
926 if (mViewItem[k + 1] != null) {
927 mViewItem[k] = buildItemFromData(mViewItem[k + 1].getId() - 1);
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);
939 zoomAtIndexChanged();
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.
946 * @return Whether clamp happened.
948 private boolean clampCenterX() {
949 ViewItem curr = mViewItem[mCurrentItem];
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()) {
960 if (curr.getId() == 0 && mCenterX < curr.getCenterX()) {
961 // Stop at the first ViewItem.
965 if (curr.getId() == mDataAdapter.getTotalNumber() - 1
966 && mCenterX > curr.getCenterX()) {
972 mCenterX = curr.getCenterX();
979 * Reorders the child views to be consistent with their data ID. This method
980 * should be called after adding/removing views.
982 private void adjustChildZOrder() {
983 for (int i = BUFFER_SIZE - 1; i >= 0; i--) {
984 if (mViewItem[i] == null) {
987 mViewItem[i].bringViewToFront();
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);
997 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
998 private void setMaxElevation(View v) {
999 v.setElevation(Float.MAX_VALUE);
1003 * Returns the ID of the current item, or -1 if there is no data.
1005 private int getCurrentId() {
1006 ViewItem current = mViewItem[mCurrentItem];
1007 if (current == null) {
1010 return current.getId();
1014 * Keep the current item in the center. This functions does not check if the
1015 * current item is null.
1017 private void snapInCenter() {
1018 final ViewItem currItem = mViewItem[mCurrentItem];
1019 if (currItem == null) {
1022 final int currentViewCenter = currItem.getCenterX();
1023 if (mController.isScrolling() || mIsUserScrolling
1024 || isCurrentItemCentered()) {
1028 int snapInTime = (int) (SNAP_IN_CENTER_TIME_MS
1029 * ((float) Math.abs(mCenterX - currentViewCenter))
1030 / mDrawArea.width());
1031 mController.scrollToPosition(currentViewCenter,
1033 if (isViewTypeSticky(currItem) && !mController.isScaling() && mScale != FULL_SCREEN_SCALE) {
1034 // Now going to full screen camera
1035 mController.goToFullScreen();
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.
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}.
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.");
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 = "
1066 final int currCenterX = curr.getCenterX();
1067 final int nextCenterX = next.getCenterX();
1068 final int translate = (int) ((nextCenterX - drawAreaWidth
1069 - currCenterX) * scaleFraction);
1071 curr.layoutWithTranslationX(mDrawArea, mCenterX, mScale);
1073 curr.setVisibility(VISIBLE);
1075 if (inFullScreen()) {
1076 curr.setTranslationX(translate * (mCenterX - currCenterX) / (nextCenterX - currCenterX));
1078 curr.setTranslationX(translate);
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.
1086 * @param currItemId The ID of the item to fade.
1088 private void fadeAndScaleRightViewItem(int currItemId) {
1089 if (currItemId < 1 || currItemId > BUFFER_SIZE) {
1090 Log.e(TAG, "currItem id out of bound.");
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 = "
1102 if (currItemId > mCurrentItem + 1) {
1103 // Every item not right next to the mCurrentItem is invisible.
1104 currItem.setVisibility(INVISIBLE);
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);
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);
1124 private void layoutViewItems(boolean layoutChanged) {
1125 if (mViewItem[mCurrentItem] == null ||
1126 mDrawArea.width() == 0 ||
1127 mDrawArea.height() == 0) {
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);
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}
1146 final float scaleFraction = mViewAnimInterpolator.getInterpolation(
1147 (mScale - FILM_STRIP_SCALE) / (FULL_SCREEN_SCALE - FILM_STRIP_SCALE));
1148 final int fullScreenWidth = mDrawArea.width() + mViewGapInPixel;
1150 // Decide the position for all view items on the left and the right
1154 for (int itemID = mCurrentItem - 1; itemID >= 0; itemID--) {
1155 final ViewItem curr = mViewItem[itemID];
1160 // First, layout relatively to the next one.
1161 final int currLeft = mViewItem[itemID + 1].getLeftPosition()
1162 - curr.getMeasuredWidth() - mViewGapInPixel;
1163 curr.setLeftPosition(currLeft);
1166 for (int itemID = mCurrentItem + 1; itemID < BUFFER_SIZE; itemID++) {
1167 final ViewItem curr = mViewItem[itemID];
1172 // First, layout relatively to the previous one.
1173 final ViewItem prev = mViewItem[itemID - 1];
1174 final int currLeft =
1175 prev.getLeftPosition() + prev.getMeasuredWidth()
1177 curr.setLeftPosition(currLeft);
1180 // Special case for the one immediately on the right of the camera
1182 boolean immediateRight =
1183 (mViewItem[mCurrentItem].getId() == 1 &&
1184 mDataAdapter.getImageData(0).getViewType() == ImageData.VIEW_TYPE_STICKY);
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);
1208 currItem.layoutWithTranslationX(mDrawArea, mCenterX, mScale);
1209 currItem.setTranslationX(0f);
1210 currItem.setAlpha(1f);
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);
1221 final int currCenterX = currItem.getCenterX();
1222 final int prevCenterX = mViewItem[mCurrentItem - 1].getCenterX();
1223 final float fadeDownFraction =
1224 ((float) mCenterX - prevCenterX) / (currCenterX - prevCenterX);
1226 (1 - fadeDownFraction) * (1 - scaleFraction) + fadeDownFraction);
1230 // Layout the rest dependent on the current scale.
1232 // Items on the left
1233 for (int itemID = mCurrentItem - 1; itemID >= 0; itemID--) {
1234 final ViewItem curr = mViewItem[itemID];
1238 translateLeftViewItem(itemID, fullScreenWidth, scaleFraction);
1241 // Items on the right
1242 for (int itemID = mCurrentItem + 1; itemID < BUFFER_SIZE; itemID++) {
1243 final ViewItem curr = mViewItem[itemID];
1248 curr.layoutWithTranslationX(mDrawArea, mCenterX, mScale);
1249 if (curr.getId() == 1 && isViewTypeSticky(curr)) {
1250 // Special case for the one next to the camera preview.
1255 if (scaleFraction == 1) {
1256 // It's in full-screen mode.
1257 fadeAndScaleRightViewItem(itemID);
1259 if (curr.getVisibility() == INVISIBLE) {
1260 curr.setVisibility(VISIBLE);
1262 if (itemID == mCurrentItem + 1) {
1263 curr.setAlpha(1f - scaleFraction);
1265 if (scaleFraction == 0f) {
1268 curr.setVisibility(INVISIBLE);
1271 curr.setTranslationX(
1272 (mViewItem[mCurrentItem].getLeftPosition() - curr.getLeftPosition()) *
1280 private boolean isViewTypeSticky(ViewItem item) {
1284 return mDataAdapter.getImageData(item.getId()).getViewType() ==
1285 ImageData.VIEW_TYPE_STICKY;
1289 public void onDraw(Canvas c) {
1290 // TODO: remove layoutViewItems() here.
1291 layoutViewItems(false);
1296 protected void onLayout(boolean changed, int l, int t, int r, int b) {
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
1305 if (!inZoomView() || changed) {
1307 layoutViewItems(changed);
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).
1317 private void resetZoomView() {
1318 if (!inZoomView()) {
1321 ViewItem current = mViewItem[mCurrentItem];
1322 if (current == null) {
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);
1334 private void hideZoomView() {
1336 mController.cancelLoadingZoomedImage();
1337 mZoomView.setVisibility(GONE);
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);
1347 private void animateItemRemoval(int dataID, final ImageData data) {
1348 if (mScale > FULL_SCREEN_SCALE) {
1351 int removedItemId = findItemByDataID(dataID);
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) {
1358 mViewItem[i].setId(mViewItem[i].getId() - 1);
1360 if (removedItemId == -1) {
1364 final ViewItem removedItem = mViewItem[removedItemId];
1365 final int offsetX = removedItem.getMeasuredWidth() + mViewGapInPixel;
1367 for (int i = removedItemId + 1; i < BUFFER_SIZE; i++) {
1368 if (mViewItem[i] != null) {
1369 mViewItem[i].setLeftPosition(mViewItem[i].getLeftPosition() - offsetX);
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
1378 for (int i = removedItemId; i < BUFFER_SIZE - 1; i++) {
1379 mViewItem[i] = mViewItem[i + 1];
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);
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);
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);
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);
1420 // CurrItem should NOT be NULL, but if is, at least don't crash.
1421 Log.w(TAG,"Caught invalid update in removal animation.");
1424 // fill the removed place by right shift
1425 mCenterX -= offsetX;
1427 for (int i = removedItemId; i > 0; i--) {
1428 mViewItem[i] = mViewItem[i - 1];
1431 // pull data out from the DataAdapter for the first one.
1433 int next = curr + 1;
1434 if (mViewItem[next] != null) {
1435 mViewItem[curr] = buildItemFromData(mViewItem[next].getId() - 1);
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);
1446 int transY = getHeight() / 8;
1447 if (removedItem.getTranslationY() < 0) {
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() {
1456 removedItem.removeViewFromHierarchy(false);
1458 }, GEOMETRY_ADJUST_TIME_MS);
1460 adjustChildZOrder();
1463 // Now, slide every one back.
1464 if (mViewItem[mCurrentItem] == null) {
1467 for (int i = 0; i < BUFFER_SIZE; i++) {
1468 if (mViewItem[i] != null
1469 && mViewItem[i].getTranslationX() != 0f) {
1470 slideViewBack(mViewItem[i]);
1473 if (isCurrentItemCentered() && isViewTypeSticky(mViewItem[mCurrentItem])) {
1474 // Special case for scrolling onto the camera preview after removal.
1475 mController.goToFullScreen();
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) {
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
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;
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) {
1510 mViewItem[i].setId(mViewItem[i].getId() + 1);
1512 if (insertedItemId == -1) {
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");
1527 if (insertedItemId >= mCurrentItem) {
1528 if (insertedItemId == mCurrentItem) {
1529 viewItem.setLeftPosition(mViewItem[mCurrentItem].getLeftPosition());
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]);
1541 // Shift left. Put the inserted data on the left instead of the
1544 if (insertedItemId < 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];
1557 mViewItem[insertedItemId] = viewItem;
1558 viewItem.setAlpha(0f);
1559 viewItem.setTranslationY(getHeight() / 8);
1560 slideViewBack(viewItem);
1561 adjustChildZOrder();
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() {
1572 public void onDataLoaded() {
1577 public void onDataUpdated(DataAdapter.UpdateReporter reporter) {
1582 public void onDataInserted(int dataId, ImageData data) {
1583 if (mViewItem[mCurrentItem] == null) {
1584 // empty now, simply do a reload.
1587 updateInsertion(dataId);
1589 if (mListener != null) {
1590 mListener.onDataFocusChanged(dataId, getCurrentId());
1595 public void onDataRemoved(int dataId, ImageData data) {
1596 animateItemRemoval(dataId, data);
1597 if (mListener != null) {
1598 mListener.onDataFocusChanged(dataId, getCurrentId());
1604 private boolean inFilmstrip() {
1605 return (mScale == FILM_STRIP_SCALE);
1608 private boolean inFullScreen() {
1609 return (mScale == FULL_SCREEN_SCALE);
1612 private boolean inZoomView() {
1613 return (mScale > FULL_SCREEN_SCALE);
1616 private boolean isCameraPreview() {
1617 return isViewTypeSticky(mViewItem[mCurrentItem]);
1620 private boolean inCameraFullscreen() {
1621 return isDataAtCenter(0) && inFullScreen()
1622 && (isViewTypeSticky(mViewItem[mCurrentItem]));
1626 public boolean onInterceptTouchEvent(MotionEvent ev) {
1627 if (mController.isScrolling()) {
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;
1640 } else if (ev.getActionMasked() == MotionEvent.ACTION_POINTER_DOWN) {
1641 // Do not intercept touch once child is in zoom mode
1642 mCheckToIntercept = false;
1645 if (!mCheckToIntercept) {
1648 if (ev.getEventTime() - ev.getDownTime() > SWIPE_TIME_OUT) {
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) {
1665 public boolean onTouchEvent(MotionEvent ev) {
1666 return mGestureRecognizer.onTouchEvent(ev);
1670 public boolean onGenericMotionEvent(MotionEvent ev) {
1671 mGestureRecognizer.onGenericMotionEvent(ev);
1675 FilmstripGestureRecognizer.Listener getGestureListener() {
1676 return mGestureListener;
1679 private void updateViewItem(int itemID) {
1680 ViewItem item = mViewItem[itemID];
1682 Log.e(TAG, "trying to update an null item");
1685 item.removeViewFromHierarchy(true);
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();
1694 newItem.copyAttributes(item);
1695 mViewItem[itemID] = newItem;
1696 mZoomView.resetDecoder();
1698 boolean stopScroll = clampCenterX();
1700 mController.stopScrolling(true);
1702 adjustChildZOrder();
1704 if (mListener != null) {
1705 mListener.onDataUpdated(newItem.getId());
1709 /** Some of the data is changed. */
1710 private void update(DataAdapter.UpdateReporter reporter) {
1712 if (mViewItem[mCurrentItem] == null) {
1717 // Check the current one.
1718 ViewItem curr = mViewItem[mCurrentItem];
1719 int dataId = curr.getId();
1720 if (reporter.isDataRemoved(dataId)) {
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;
1737 for (int i = mCurrentItem - 1; i >= 0; i--) {
1738 curr = mViewItem[i];
1740 dataId = curr.getId();
1741 if (reporter.isDataRemoved(dataId) || reporter.isDataUpdated(dataId)) {
1745 ViewItem next = mViewItem[i + 1];
1747 mViewItem[i] = buildItemFromData(next.getId() - 1);
1753 for (int i = mCurrentItem + 1; i < BUFFER_SIZE; i++) {
1754 curr = mViewItem[i];
1756 dataId = curr.getId();
1757 if (reporter.isDataRemoved(dataId) || reporter.isDataUpdated(dataId)) {
1761 ViewItem prev = mViewItem[i - 1];
1763 mViewItem[i] = buildItemFromData(prev.getId() + 1);
1767 adjustChildZOrder();
1768 // Request a layout to find the measured width/height of the view first.
1770 // Update photo sphere visibility after metadata fully written.
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
1778 private void reload() {
1779 mController.stopScrolling(true);
1780 mController.stopScale();
1781 mDataIdOnUserScrolling = 0;
1784 if (mViewItem[mCurrentItem] != null) {
1785 prevId = mViewItem[mCurrentItem].getId();
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) {
1793 mViewItem[i].removeViewFromHierarchy(false);
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) {
1803 mViewItem[mCurrentItem] = buildItemFromData(0);
1804 if (mViewItem[mCurrentItem] == null) {
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) {
1815 // Ensure that the views in mViewItem will layout the first in the
1816 // center of the display upon a reload.
1818 mScale = FILM_STRIP_SCALE;
1820 adjustChildZOrder();
1823 if (mListener != null) {
1824 mListener.onDataReloaded();
1825 mListener.onDataFocusChanged(prevId, mViewItem[mCurrentItem].getId());
1829 private void promoteData(int itemID, int dataID) {
1830 if (mListener != null) {
1831 mListener.onFocusedDataPromoted(dataID);
1835 private void demoteData(int itemID, int dataID) {
1836 if (mListener != null) {
1837 mListener.onFocusedDataDemoted(dataID);
1841 private void onEnterFilmstrip() {
1842 if (mListener != null) {
1843 mListener.onEnterFilmstrip(getCurrentId());
1847 private void onLeaveFilmstrip() {
1848 if (mListener != null) {
1849 mListener.onLeaveFilmstrip(getCurrentId());
1853 private void onEnterFullScreen() {
1854 mFullScreenUIHidden = false;
1855 if (mListener != null) {
1856 mListener.onEnterFullScreenUiShown(getCurrentId());
1860 private void onLeaveFullScreen() {
1861 if (mListener != null) {
1862 mListener.onLeaveFullScreenUiShown(getCurrentId());
1866 private void onEnterFullScreenUiHidden() {
1867 mFullScreenUIHidden = true;
1868 if (mListener != null) {
1869 mListener.onEnterFullScreenUiHidden(getCurrentId());
1873 private void onLeaveFullScreenUiHidden() {
1874 mFullScreenUIHidden = false;
1875 if (mListener != null) {
1876 mListener.onLeaveFullScreenUiHidden(getCurrentId());
1880 private void onEnterZoomView() {
1881 if (mListener != null) {
1882 mListener.onEnterZoomView(getCurrentId());
1886 private void onLeaveZoomView() {
1887 mController.setSurroundingViewsVisible(true);
1891 * MyController controls all the geometry animations. It passively tells the
1892 * geometry information on demand.
1894 private class MyController implements FilmstripController {
1896 private final ValueAnimator mScaleAnimator;
1897 private ValueAnimator mZoomAnimator;
1898 private AnimatorSet mFlingAnimator;
1900 private final MyScroller mScroller;
1901 private boolean mCanStopScroll;
1903 private final MyScroller.Listener mScrollerListener =
1904 new MyScroller.Listener() {
1906 public void onScrollUpdate(int currX, int currY) {
1909 boolean stopScroll = clampCenterX();
1911 mController.stopScrolling(true);
1917 public void onScrollEnd() {
1918 mCanStopScroll = true;
1919 if (mViewItem[mCurrentItem] == null) {
1923 if (isCurrentItemCentered()
1924 && isViewTypeSticky(mViewItem[mCurrentItem])) {
1925 // Special case for the scrolling end on the camera
1932 private final ValueAnimator.AnimatorUpdateListener mScaleAnimatorUpdateListener =
1933 new ValueAnimator.AnimatorUpdateListener() {
1935 public void onAnimationUpdate(ValueAnimator animation) {
1936 if (mViewItem[mCurrentItem] == null) {
1939 mScale = (Float) animation.getAnimatedValue();
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;
1951 mScaleAnimator = new ValueAnimator();
1952 mScaleAnimator.addUpdateListener(mScaleAnimatorUpdateListener);
1953 mScaleAnimator.setInterpolator(decelerateInterpolator);
1954 mScaleAnimator.addListener(new Animator.AnimatorListener() {
1956 public void onAnimationStart(Animator animator) {
1957 if (mScale == FULL_SCREEN_SCALE) {
1958 onLeaveFullScreen();
1960 if (mScale == FILM_STRIP_SCALE) {
1967 public void onAnimationEnd(Animator animator) {
1968 if (mScale == FULL_SCREEN_SCALE) {
1969 onEnterFullScreen();
1971 if (mScale == FILM_STRIP_SCALE) {
1975 zoomAtIndexChanged();
1979 public void onAnimationCancel(Animator animator) {
1984 public void onAnimationRepeat(Animator animator) {
1991 public void setImageGap(int imageGap) {
1992 FilmstripView.this.setViewGap(imageGap);
1996 public int getCurrentId() {
1997 return FilmstripView.this.getCurrentId();
2001 public void setDataAdapter(DataAdapter adapter) {
2002 FilmstripView.this.setDataAdapter(adapter);
2006 public boolean inFilmstrip() {
2007 return FilmstripView.this.inFilmstrip();
2011 public boolean inFullScreen() {
2012 return FilmstripView.this.inFullScreen();
2016 public boolean isCameraPreview() {
2017 return FilmstripView.this.isCameraPreview();
2021 public boolean inCameraFullscreen() {
2022 return FilmstripView.this.inCameraFullscreen();
2026 public void setListener(FilmstripListener l) {
2027 FilmstripView.this.setListener(l);
2031 public boolean isScrolling() {
2032 return !mScroller.isFinished();
2036 public boolean isScaling() {
2037 return mScaleAnimator.isRunning();
2040 private int estimateMinX(int dataID, int leftPos, int viewWidth) {
2041 return leftPos - (dataID + 100) * (viewWidth + mViewGapInPixel);
2044 private int estimateMaxX(int dataID, int leftPos, int viewWidth) {
2046 + (mDataAdapter.getTotalNumber() - dataID + 100)
2047 * (viewWidth + mViewGapInPixel);
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();
2056 // Calculate end scale
2057 final float maxScale = getCurrentDataMaxScale(false);
2058 final float endScale = mScale < maxScale - maxScale * TOLERANCE
2059 ? maxScale : FULL_SCREEN_SCALE;
2061 mZoomAnimator = new ValueAnimator();
2062 mZoomAnimator.setFloatValues(mScale, endScale);
2063 mZoomAnimator.setDuration(ZOOM_ANIMATION_DURATION_MS);
2064 mZoomAnimator.addListener(new Animator.AnimatorListener() {
2066 public void onAnimationStart(Animator animation) {
2067 if (mScale == FULL_SCREEN_SCALE) {
2068 if (mFullScreenUIHidden) {
2069 onLeaveFullScreenUiHidden();
2071 onLeaveFullScreen();
2073 setSurroundingViewsVisible(false);
2074 } else if (inZoomView()) {
2077 cancelLoadingZoomedImage();
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());
2090 if (inFullScreen()) {
2091 setSurroundingViewsVisible(true);
2092 mZoomView.setVisibility(GONE);
2093 current.resetTransform();
2094 onEnterFullScreenUiHidden();
2096 mController.loadZoomedImage();
2099 mZoomAnimator = null;
2100 zoomAtIndexChanged();
2104 public void onAnimationCancel(Animator animation) {
2109 public void onAnimationRepeat(Animator animation) {
2114 mZoomAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
2116 public void onAnimationUpdate(ValueAnimator animation) {
2117 float newScale = (Float) animation.getAnimatedValue();
2118 float postScale = newScale / mScale;
2120 current.postScale(focusX, focusY, postScale, mDrawArea.width(),
2121 mDrawArea.height());
2124 mZoomAnimator.start();
2128 public void scroll(float deltaX) {
2129 if (!stopScrolling(false)) {
2134 boolean stopScroll = clampCenterX();
2136 mController.stopScrolling(true);
2142 public void fling(float velocityX) {
2143 if (!stopScrolling(false)) {
2146 final ViewItem item = mViewItem[mCurrentItem];
2151 float scaledVelocityX = velocityX / mScale;
2152 if (inFullScreen() && isViewTypeSticky(item) && scaledVelocityX < 0) {
2153 // Swipe left in camera preview.
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);
2168 void flingInsideZoomView(float velocityX, float velocityY) {
2169 if (!inZoomView()) {
2173 final ViewItem current = mViewItem[mCurrentItem];
2174 if (current == null) {
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
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))
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))));
2199 final float translationX = current.getTranslationX() * mScale;
2200 final float translationY = current.getTranslationY() * mScale;
2202 final ValueAnimator decelerationX = ValueAnimator.ofFloat(translationX,
2203 translationX + duration / factor * velocityX);
2204 final ValueAnimator decelerationY = ValueAnimator.ofFloat(translationY,
2205 translationY + duration / factor * velocityY);
2207 decelerationY.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
2209 public void onAnimationUpdate(ValueAnimator animation) {
2210 float transX = (Float) decelerationX.getAnimatedValue();
2211 float transY = (Float) decelerationY.getAnimatedValue();
2213 current.updateTransform(transX, transY, mScale,
2214 mScale, mDrawArea.width(), mDrawArea.height());
2218 mFlingAnimator = new AnimatorSet();
2219 mFlingAnimator.play(decelerationX).with(decelerationY);
2220 mFlingAnimator.setDuration((int) (duration * 1000));
2221 mFlingAnimator.setInterpolator(new TimeInterpolator() {
2223 public float getInterpolation(float input) {
2224 return (float) (1.0f - Math.pow((1.0f - input), factor));
2227 mFlingAnimator.addListener(new Animator.AnimatorListener() {
2228 private boolean mCancelled = false;
2231 public void onAnimationStart(Animator animation) {
2236 public void onAnimationEnd(Animator animation) {
2240 mFlingAnimator = null;
2244 public void onAnimationCancel(Animator animation) {
2249 public void onAnimationRepeat(Animator animation) {
2253 mFlingAnimator.start();
2257 public boolean stopScrolling(boolean forced) {
2258 if (!isScrolling()) {
2260 } else if (!mCanStopScroll && !forced) {
2263 mScroller.forceFinished(true);
2267 private void stopScale() {
2268 mScaleAnimator.cancel();
2272 public void scrollToPosition(int position, int duration, boolean interruptible) {
2273 if (mViewItem[mCurrentItem] == null) {
2276 mCanStopScroll = interruptible;
2277 mScroller.startScroll(mCenterX, 0, position - mCenterX, 0, duration);
2281 public boolean goToNextItem() {
2282 return goToItem(mCurrentItem + 1);
2286 public boolean goToPreviousItem() {
2287 return goToItem(mCurrentItem - 1);
2290 private boolean goToItem(int itemIndex) {
2291 final ViewItem nextItem = mViewItem[itemIndex];
2292 if (nextItem == null) {
2295 stopScrolling(true);
2296 scrollToPosition(nextItem.getCenterX(), GEOMETRY_ADJUST_TIME_MS * 2, false);
2298 if (isViewTypeSticky(mViewItem[mCurrentItem])) {
2299 // Special case when moving from camera preview.
2300 scaleTo(FILM_STRIP_SCALE, GEOMETRY_ADJUST_TIME_MS);
2305 private void scaleTo(float scale, int duration) {
2306 if (mViewItem[mCurrentItem] == null) {
2310 mScaleAnimator.setDuration(duration);
2311 mScaleAnimator.setFloatValues(mScale, scale);
2312 mScaleAnimator.start();
2316 public void goToFilmstrip() {
2317 if (mViewItem[mCurrentItem] == null) {
2320 if (mScale == FILM_STRIP_SCALE) {
2323 scaleTo(FILM_STRIP_SCALE, GEOMETRY_ADJUST_TIME_MS);
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);
2332 if (mScale == FILM_STRIP_SCALE) {
2338 public void goToFullScreen() {
2339 if (inFullScreen()) {
2343 scaleTo(FULL_SCREEN_SCALE, GEOMETRY_ADJUST_TIME_MS);
2346 private void cancelFlingAnimation() {
2347 // Cancels flinging for zoomed images
2348 if (isFlingAnimationRunning()) {
2349 mFlingAnimator.cancel();
2353 private void cancelZoomAnimation() {
2354 if (isZoomAnimationRunning()) {
2355 mZoomAnimator.cancel();
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) {
2367 mViewItem[i].setVisibility(visible ? VISIBLE : INVISIBLE);
2371 private Uri getCurrentUri() {
2372 ViewItem curr = mViewItem[mCurrentItem];
2376 return mDataAdapter.getImageData(curr.getId()).getUri();
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.
2384 private float getCurrentDataMaxScale(boolean allowOverScale) {
2385 ViewItem curr = mViewItem[mCurrentItem];
2387 return FULL_SCREEN_SCALE;
2389 ImageData imageData = mDataAdapter.getImageData(curr.getId());
2390 if (imageData == null || !imageData.isUIActionSupported(ImageData.ACTION_ZOOM)) {
2391 return FULL_SCREEN_SCALE;
2393 float imageWidth = imageData.getWidth();
2394 if (imageData.getRotation() == 90
2395 || imageData.getRotation() == 270) {
2396 imageWidth = imageData.getHeight();
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;
2408 private void loadZoomedImage() {
2409 if (!inZoomView()) {
2412 ViewItem curr = mViewItem[mCurrentItem];
2416 ImageData imageData = mDataAdapter.getImageData(curr.getId());
2417 if (!imageData.isUIActionSupported(ImageData.ACTION_ZOOM)) {
2420 Uri uri = getCurrentUri();
2421 RectF viewRect = curr.getViewRect();
2422 if (uri == null || uri == Uri.EMPTY) {
2425 int orientation = imageData.getRotation();
2426 mZoomView.loadBitmap(uri, orientation, viewRect);
2429 private void cancelLoadingZoomedImage() {
2430 mZoomView.cancelPartialDecodingTask();
2434 public void goToFirstItem() {
2435 if (mViewItem[mCurrentItem] == null) {
2439 // TODO: animate to camera if it is still in the mViewItem buffer
2440 // versus a full reload which will perform an immediate transition
2444 public boolean inZoomView() {
2445 return FilmstripView.this.inZoomView();
2448 public boolean isFlingAnimationRunning() {
2449 return mFlingAnimator != null && mFlingAnimator.isRunning();
2452 public boolean isZoomAnimationRunning() {
2453 return mZoomAnimator != null && mZoomAnimator.isRunning();
2457 private boolean isCurrentItemCentered() {
2458 return mViewItem[mCurrentItem].getCenterX() == mCenterX;
2461 private static class MyScroller {
2462 public interface Listener {
2463 public void onScrollUpdate(int currX, int currY);
2465 public void onScrollEnd();
2468 private final Handler mHandler;
2469 private final Listener mListener;
2471 private final Scroller mScroller;
2473 private final ValueAnimator mXScrollAnimator;
2474 private final Runnable mScrollChecker = new Runnable() {
2477 boolean newPosition = mScroller.computeScrollOffset();
2479 mListener.onScrollEnd();
2482 mListener.onScrollUpdate(mScroller.getCurrX(), mScroller.getCurrY());
2483 mHandler.removeCallbacks(this);
2484 mHandler.post(this);
2488 private final ValueAnimator.AnimatorUpdateListener mXScrollAnimatorUpdateListener =
2489 new ValueAnimator.AnimatorUpdateListener() {
2491 public void onAnimationUpdate(ValueAnimator animation) {
2492 mListener.onScrollUpdate((Integer) animation.getAnimatedValue(), 0);
2496 private final Animator.AnimatorListener mXScrollAnimatorListener =
2497 new Animator.AnimatorListener() {
2499 public void onAnimationCancel(Animator animation) {
2504 public void onAnimationEnd(Animator animation) {
2505 mListener.onScrollEnd();
2509 public void onAnimationRepeat(Animator animation) {
2514 public void onAnimationStart(Animator animation) {
2519 public MyScroller(Context ctx, Handler handler, Listener listener,
2520 TimeInterpolator interpolator) {
2522 mListener = listener;
2523 mScroller = new Scroller(ctx);
2524 mXScrollAnimator = new ValueAnimator();
2525 mXScrollAnimator.addUpdateListener(mXScrollAnimatorUpdateListener);
2526 mXScrollAnimator.addListener(mXScrollAnimatorListener);
2527 mXScrollAnimator.setInterpolator(interpolator);
2531 int startX, int startY,
2532 int velocityX, int velocityY,
2534 int minY, int maxY) {
2535 mScroller.fling(startX, startY, velocityX, velocityY, minX, maxX, minY, maxY);
2539 public void startScroll(int startX, int startY, int dx, int dy) {
2540 mScroller.startScroll(startX, startY, dx, dy);
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();
2552 public boolean isFinished() {
2553 return (mScroller.isFinished() && !mXScrollAnimator.isRunning());
2556 public void forceFinished(boolean finished) {
2557 mScroller.forceFinished(finished);
2559 mXScrollAnimator.cancel();
2563 private void runChecker() {
2564 if (mHandler == null || mListener == null) {
2567 mHandler.removeCallbacks(mScrollChecker);
2568 mHandler.post(mScrollChecker);
2572 private class MyGestureReceiver implements FilmstripGestureRecognizer.Listener {
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;
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();
2592 } else if (inFullScreen()) {
2593 if (mFullScreenUIHidden) {
2594 onLeaveFullScreenUiHidden();
2595 onEnterFullScreen();
2597 onLeaveFullScreen();
2598 onEnterFullScreenUiHidden();
2606 public boolean onDoubleTap(float x, float y) {
2607 ViewItem current = mViewItem[mCurrentItem];
2608 if (current == null) {
2611 if (inFilmstrip()) {
2612 mController.goToFullScreen();
2614 } else if (mScale < FULL_SCREEN_SCALE || inCameraFullscreen()) {
2617 if (!mController.stopScrolling(false)) {
2620 if (inFullScreen()) {
2621 mController.zoomAt(current, x, y);
2622 checkItemAtMaxSize();
2624 } else if (mScale > FULL_SCREEN_SCALE) {
2626 mController.zoomAt(current, x, y);
2632 public boolean onDown(float x, float y) {
2633 mLastDownTime = SystemClock.uptimeMillis();
2635 mController.cancelFlingAnimation();
2636 if (!mController.stopScrolling(false)) {
2644 public boolean onUp(float x, float y) {
2645 ViewItem currItem = mViewItem[mCurrentItem];
2646 if (currItem == null) {
2649 if (mController.isZoomAnimationRunning() || mController.isFlingAnimationRunning()) {
2653 mController.loadZoomedImage();
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) {
2667 float transY = mViewItem[i].getTranslationY();
2671 int id = mViewItem[i].getId();
2673 if (mDataAdapter.getImageData(id)
2674 .isUIActionSupported(ImageData.ACTION_DEMOTE)
2675 && ((transY > promoteHeight)
2676 || (transY > velocityPromoteHeight && speedY > PROMOTE_VELOCITY))) {
2678 } else if (mDataAdapter.getImageData(id)
2679 .isUIActionSupported(ImageData.ACTION_PROMOTE)
2680 && (transY < -promoteHeight
2681 || (transY < -velocityPromoteHeight && speedY > PROMOTE_VELOCITY))) {
2684 // put the view back.
2685 slideViewBack(mViewItem[i]);
2689 // The data might be changed. Re-check.
2690 currItem = mViewItem[mCurrentItem];
2691 if (currItem == null) {
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);
2709 if (isCurrentItemCentered() && currId == 0 && isViewTypeSticky(currItem)) {
2710 mController.goToFullScreen();
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
2716 mController.goToFilmstrip();
2717 mDataIdOnUserScrolling = currId;
2725 public void onLongPress(float x, float y) {
2726 final int dataId = getCurrentId();
2730 mListener.onFocusedDataLongPressed(dataId);
2734 public boolean onScroll(float x, float y, float dx, float dy) {
2735 final ViewItem currItem = mViewItem[mCurrentItem];
2736 if (currItem == null) {
2739 if (inFullScreen() && !mDataAdapter.canSwipeInFullScreen(currItem.getId())) {
2743 // When image is zoomed in to be bigger than the screen
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());
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();
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;
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;
2772 mController.scroll(deltaX);
2774 // Vertical part. Promote or demote.
2776 Rect hitRect = new Rect();
2777 for (; hit < BUFFER_SIZE; hit++) {
2778 if (mViewItem[hit] == null) {
2781 mViewItem[hit].getHitRect(hitRect);
2782 if (hitRect.contains((int) x, (int) y)) {
2786 if (hit == BUFFER_SIZE) {
2791 ImageData data = mDataAdapter.getImageData(mViewItem[hit].getId());
2792 float transY = mViewItem[hit].getTranslationY() - dy / mScale;
2793 if (!data.isUIActionSupported(ImageData.ACTION_DEMOTE) &&
2797 if (!data.isUIActionSupported(ImageData.ACTION_PROMOTE) &&
2801 mViewItem[hit].setTranslationY(transY);
2803 } else if (inFullScreen()) {
2804 if (mViewItem[mCurrentItem] == null || (deltaX < 0 && mCenterX <=
2805 currItem.getCenterX() && currItem.getId() == 0)) {
2808 // Multiplied by 1.2 to make it more easy to swipe.
2809 mController.scroll((int) (deltaX * 1.2));
2817 public boolean onMouseScroll(float hscroll, float vscroll) {
2820 hscroll *= MOUSE_SCROLL_FACTOR;
2821 vscroll *= MOUSE_SCROLL_FACTOR;
2823 if (vscroll != 0f) {
2829 if (inFullScreen()) {
2830 onFling(-scroll, 0f);
2831 } else if (inZoomView()) {
2832 onScroll(0f, 0f, hscroll, vscroll);
2834 onScroll(0f, 0f, scroll, 0f);
2841 public boolean onFling(float velocityX, float velocityY) {
2842 final ViewItem currItem = mViewItem[mCurrentItem];
2843 if (currItem == null) {
2846 if (!mDataAdapter.canSwipeInFullScreen(currItem.getId())) {
2850 // Fling within the zoomed image
2851 mController.flingInsideZoomView(velocityX, velocityY);
2854 if (Math.abs(velocityX) < Math.abs(velocityY)) {
2855 // ignore vertical fling.
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();
2864 if (velocityX > 0) { // left
2865 if (mCenterX > currItemCenterX) {
2866 // The visually previous item is actually the current
2868 mController.scrollToPosition(
2869 currItemCenterX, GEOMETRY_ADJUST_TIME_MS, true);
2872 ViewItem prevItem = mViewItem[mCurrentItem - 1];
2873 if (prevItem == null) {
2876 mController.scrollToPosition(
2877 prevItem.getCenterX(), GEOMETRY_ADJUST_TIME_MS, true);
2879 if (mController.stopScrolling(false)) {
2880 if (mCenterX < currItemCenterX) {
2881 // The visually next item is actually the current
2883 mController.scrollToPosition(
2884 currItemCenterX, GEOMETRY_ADJUST_TIME_MS, true);
2887 final ViewItem nextItem = mViewItem[mCurrentItem + 1];
2888 if (nextItem == null) {
2891 mController.scrollToPosition(
2892 nextItem.getCenterX(), GEOMETRY_ADJUST_TIME_MS, true);
2893 if (isViewTypeSticky(currItem)) {
2894 mController.goToFilmstrip();
2900 if (mScale == FILM_STRIP_SCALE) {
2901 mController.fling(velocityX);
2907 public boolean onScaleBegin(float focusX, float focusY) {
2908 if (inCameraFullscreen()) {
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);
2921 public boolean onScale(float focusX, float focusY, float scale) {
2922 if (inCameraFullscreen()) {
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;
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) {
2938 if (newScale == FILM_STRIP_SCALE) {
2944 } else if (mScale < FULL_SCREEN_SCALE && newScale >= FULL_SCREEN_SCALE) {
2945 // Going from smaller than screen size to bigger than or equal
2947 if (mScale == FILM_STRIP_SCALE) {
2950 mScale = FULL_SCREEN_SCALE;
2951 onEnterFullScreen();
2952 mController.setSurroundingViewsVisible(false);
2954 } else if (mScale >= FULL_SCREEN_SCALE && newScale < FULL_SCREEN_SCALE) {
2955 // Going from bigger than or equal to screen size to smaller
2957 if (inFullScreen()) {
2958 if (mFullScreenUIHidden) {
2959 onLeaveFullScreenUiHidden();
2961 onLeaveFullScreen();
2970 // Scaled view bigger than or equal to screen size both before
2971 // and after scaling
2972 if (!inZoomView()) {
2973 mController.setSurroundingViewsVisible(false);
2975 ViewItem curr = mViewItem[mCurrentItem];
2976 // Make sure the image is not overly scaled
2977 newScale = Math.min(newScale, mMaxScale);
2978 if (newScale == mScale) {
2981 float postScale = newScale / mScale;
2982 curr.postScale(focusX, focusY, postScale, mDrawArea.width(), mDrawArea.height());
2984 if (mScale == FULL_SCREEN_SCALE) {
2985 onEnterFullScreen();
2989 checkItemAtMaxSize();
2995 public void onScaleEnd() {
2996 zoomAtIndexChanged();
2997 if (mScale > FULL_SCREEN_SCALE + TOLERANCE) {
3000 mController.setSurroundingViewsVisible(true);
3001 if (mScale <= FILM_STRIP_SCALE + TOLERANCE) {
3002 mController.goToFilmstrip();
3003 } else if (mScaleTrend > 1f || mScale > FULL_SCREEN_SCALE - TOLERANCE) {
3005 mScale = FULL_SCREEN_SCALE;
3008 mController.goToFullScreen();
3010 mController.goToFilmstrip();