blob: c154b33c50ba24a57f9901be149235b4f7db47e7 [file] [log] [blame]
Winson Chung321e9ee2010-08-09 13:37:56 -07001/*
Adam Cohen7d30a372013-07-01 17:03:59 -07002 * Copyright (C) 2012 The Android Open Source Project
Winson Chung321e9ee2010-08-09 13:37:56 -07003 *
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
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
Winson Chung321e9ee2010-08-09 13:37:56 -070018
Winson Chung228a0fa2011-01-26 22:14:13 -080019import android.animation.Animator;
Winson Chung228a0fa2011-01-26 22:14:13 -080020import android.animation.AnimatorListenerAdapter;
Adam Cohen7d30a372013-07-01 17:03:59 -070021import android.animation.AnimatorSet;
22import android.animation.ObjectAnimator;
23import android.animation.TimeInterpolator;
Winson Chungbb6f6a52011-07-25 17:55:44 -070024import android.animation.ValueAnimator;
Adam Cohen7d30a372013-07-01 17:03:59 -070025import android.animation.ValueAnimator.AnimatorUpdateListener;
Winson Chung321e9ee2010-08-09 13:37:56 -070026import android.content.Context;
Adam Cohen9c4949e2010-10-05 12:27:22 -070027import android.content.res.TypedArray;
Winson Chung321e9ee2010-08-09 13:37:56 -070028import android.graphics.Canvas;
Adam Cohen7d30a372013-07-01 17:03:59 -070029import android.graphics.Matrix;
30import android.graphics.PointF;
Winson Chung321e9ee2010-08-09 13:37:56 -070031import android.graphics.Rect;
Svetoslav Ganov08055f62012-05-15 11:06:36 -070032import android.os.Bundle;
Winson Chung321e9ee2010-08-09 13:37:56 -070033import android.os.Parcel;
34import android.os.Parcelable;
Adam Cohen53805212013-10-01 10:39:23 -070035import android.support.v4.view.accessibility.AccessibilityEventCompat;
Winson Chung321e9ee2010-08-09 13:37:56 -070036import android.util.AttributeSet;
Adam Cohen7d30a372013-07-01 17:03:59 -070037import android.util.DisplayMetrics;
Winson Chung785d2eb2011-04-14 16:08:02 -070038import android.util.Log;
Winson Chung185d7162011-02-28 13:47:29 -080039import android.view.InputDevice;
40import android.view.KeyEvent;
Winson Chung321e9ee2010-08-09 13:37:56 -070041import android.view.MotionEvent;
42import android.view.VelocityTracker;
43import android.view.View;
44import android.view.ViewConfiguration;
45import android.view.ViewGroup;
46import android.view.ViewParent;
Winson Chung6a0f57d2011-06-29 20:10:49 -070047import android.view.accessibility.AccessibilityEvent;
Winson Chungc27d1bb2011-09-29 12:07:42 -070048import android.view.accessibility.AccessibilityManager;
Winson Chung6a0f57d2011-06-29 20:10:49 -070049import android.view.accessibility.AccessibilityNodeInfo;
Adam Cohen7d30a372013-07-01 17:03:59 -070050import android.view.animation.AnimationUtils;
51import android.view.animation.DecelerateInterpolator;
Adam Cohene0f66b52010-11-23 15:06:07 -080052import android.view.animation.Interpolator;
Adam Cohen7d30a372013-07-01 17:03:59 -070053import android.view.animation.LinearInterpolator;
Winson Chung321e9ee2010-08-09 13:37:56 -070054import android.widget.Scroller;
55
Winson Chung6a0f57d2011-06-29 20:10:49 -070056import java.util.ArrayList;
57
Winson Chungc58497e2013-09-03 17:48:37 -070058interface Page {
59 public int getPageChildCount();
60 public View getChildOnPageAt(int i);
61 public void removeAllViewsOnPage();
62 public void removeViewOnPageAt(int i);
63 public int indexOfChildOnPage(View v);
64}
65
Winson Chung321e9ee2010-08-09 13:37:56 -070066/**
67 * An abstraction of the original Workspace which supports browsing through a
Michael Jurka0142d492010-08-25 17:46:15 -070068 * sequential list of "pages"
Winson Chung321e9ee2010-08-09 13:37:56 -070069 */
Michael Jurka8b805b12012-04-18 14:23:14 -070070public abstract class PagedView extends ViewGroup implements ViewGroup.OnHierarchyChangeListener {
Winson Chung321e9ee2010-08-09 13:37:56 -070071 private static final String TAG = "PagedView";
Winson Chung785d2eb2011-04-14 16:08:02 -070072 private static final boolean DEBUG = false;
Michael Jurka0142d492010-08-25 17:46:15 -070073 protected static final int INVALID_PAGE = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -070074
Winson Chung86f77532010-08-24 11:08:22 -070075 // the min drag distance for a fling to register, to prevent random page shifts
Winson Chung9cfd25f2010-10-24 16:09:28 -070076 private static final int MIN_LENGTH_FOR_FLING = 25;
Winson Chung321e9ee2010-08-09 13:37:56 -070077
Adam Cohen7d30a372013-07-01 17:03:59 -070078 protected static final int PAGE_SNAP_ANIMATION_DURATION = 750;
Winson Chungf0c6ae02012-03-21 16:10:31 -070079 protected static final int SLOW_PAGE_SNAP_ANIMATION_DURATION = 950;
Michael Jurka0142d492010-08-25 17:46:15 -070080 protected static final float NANOTIME_DIV = 1000000000.0f;
Winson Chung321e9ee2010-08-09 13:37:56 -070081
Adam Cohenb5ba0972011-09-07 18:02:31 -070082 private static final float OVERSCROLL_ACCELERATE_FACTOR = 2;
Winson Chungb26f3d62011-06-02 10:49:29 -070083 private static final float OVERSCROLL_DAMP_FACTOR = 0.14f;
Winson Chung867ca622012-02-21 15:48:35 -080084
Adam Cohenb64cb5a2011-02-15 13:53:42 -080085 private static final float RETURN_TO_ORIGINAL_PAGE_THRESHOLD = 0.33f;
Adam Cohen00481b32011-11-18 12:03:48 -080086 // The page is moved more than halfway, automatically move to the next page on touch up.
87 private static final float SIGNIFICANT_MOVE_THRESHOLD = 0.4f;
Adam Cohen68d73932010-11-15 10:50:58 -080088
Adam Cohen265b9a62011-12-07 14:37:18 -080089 // The following constants need to be scaled based on density. The scaled versions will be
90 // assigned to the corresponding member variables below.
91 private static final int FLING_THRESHOLD_VELOCITY = 500;
92 private static final int MIN_SNAP_VELOCITY = 1500;
93 private static final int MIN_FLING_VELOCITY = 250;
94
Adam Cohen7d30a372013-07-01 17:03:59 -070095 // We are disabling touch interaction of the widget region for factory ROM.
96 private static final boolean DISABLE_TOUCH_INTERACTION = false;
Adam Cohenf358a4b2013-07-23 16:47:31 -070097 private static final boolean DISABLE_TOUCH_SIDE_PAGES = true;
Adam Cohendedbd962013-07-11 14:21:49 -070098 private static final boolean DISABLE_FLING_TO_DELETE = true;
Adam Cohen7d30a372013-07-01 17:03:59 -070099
Adam Cohen21cd0022013-10-09 18:57:02 -0700100 public static final int INVALID_RESTORE_PAGE = -1001;
101
Adam Cohenf358a4b2013-07-23 16:47:31 -0700102 private boolean mFreeScroll = false;
103 private int mFreeScrollMinScrollX = -1;
104 private int mFreeScrollMaxScrollX = -1;
105
Winson Chung8aad6102012-05-11 16:27:49 -0700106 static final int AUTOMATIC_PAGE_SPACING = -1;
107
Adam Cohen265b9a62011-12-07 14:37:18 -0800108 protected int mFlingThresholdVelocity;
109 protected int mMinFlingVelocity;
110 protected int mMinSnapVelocity;
Michael Jurka0142d492010-08-25 17:46:15 -0700111
Adam Cohenb5ba0972011-09-07 18:02:31 -0700112 protected float mDensity;
Michael Jurka0142d492010-08-25 17:46:15 -0700113 protected float mSmoothingTime;
114 protected float mTouchX;
115
116 protected boolean mFirstLayout = true;
Adam Cohen410f3cd2013-09-22 12:09:32 -0700117 private int mNormalChildHeight;
Michael Jurka0142d492010-08-25 17:46:15 -0700118
119 protected int mCurrentPage;
Adam Cohen21cd0022013-10-09 18:57:02 -0700120 protected int mRestorePage = INVALID_RESTORE_PAGE;
Adam Cohenf698c6e2013-07-17 18:44:25 -0700121 protected int mChildCountOnLastLayout;
Adam Cohene61a9a22013-06-11 15:45:31 -0700122
Michael Jurka0142d492010-08-25 17:46:15 -0700123 protected int mNextPage = INVALID_PAGE;
Adam Cohen68d73932010-11-15 10:50:58 -0800124 protected int mMaxScrollX;
Michael Jurka0142d492010-08-25 17:46:15 -0700125 protected Scroller mScroller;
Winson Chung321e9ee2010-08-09 13:37:56 -0700126 private VelocityTracker mVelocityTracker;
127
Adam Cohen7d30a372013-07-01 17:03:59 -0700128 private float mParentDownMotionX;
129 private float mParentDownMotionY;
Winson Chung321e9ee2010-08-09 13:37:56 -0700130 private float mDownMotionX;
Adam Cohen7d30a372013-07-01 17:03:59 -0700131 private float mDownMotionY;
132 private float mDownScrollX;
Adam Cohenf358a4b2013-07-23 16:47:31 -0700133 private float mDragViewBaselineLeft;
Michael Jurka7426c422010-11-11 15:23:47 -0800134 protected float mLastMotionX;
Winson Chungc0844aa2011-02-02 15:25:58 -0800135 protected float mLastMotionXRemainder;
Michael Jurka7426c422010-11-11 15:23:47 -0800136 protected float mLastMotionY;
Adam Cohenaefd4e12011-02-14 16:39:38 -0800137 protected float mTotalMotionX;
Adam Cohenf34bab52010-09-30 14:11:56 -0700138 private int mLastScreenCenter = -1;
Adam Cohenedb40762013-07-18 16:45:45 -0700139
Adam Cohendbdff6b2013-09-18 19:09:15 -0700140 private boolean mCancelTap;
141
Adam Cohenedb40762013-07-18 16:45:45 -0700142 private int[] mPageScrolls;
Winson Chung321e9ee2010-08-09 13:37:56 -0700143
Michael Jurka0142d492010-08-25 17:46:15 -0700144 protected final static int TOUCH_STATE_REST = 0;
145 protected final static int TOUCH_STATE_SCROLLING = 1;
146 protected final static int TOUCH_STATE_PREV_PAGE = 2;
147 protected final static int TOUCH_STATE_NEXT_PAGE = 3;
Adam Cohen7d30a372013-07-01 17:03:59 -0700148 protected final static int TOUCH_STATE_REORDERING = 4;
149
Adam Cohene45440e2010-10-14 18:33:38 -0700150 protected final static float ALPHA_QUANTIZE_LEVEL = 0.0001f;
Winson Chung321e9ee2010-08-09 13:37:56 -0700151
Michael Jurka0142d492010-08-25 17:46:15 -0700152 protected int mTouchState = TOUCH_STATE_REST;
Adam Cohen2591f6a2011-10-25 14:36:40 -0700153 protected boolean mForceScreenScrolled = false;
Winson Chung321e9ee2010-08-09 13:37:56 -0700154
Michael Jurka0142d492010-08-25 17:46:15 -0700155 protected OnLongClickListener mLongClickListener;
Winson Chung321e9ee2010-08-09 13:37:56 -0700156
Michael Jurka7426c422010-11-11 15:23:47 -0800157 protected int mTouchSlop;
Winson Chung321e9ee2010-08-09 13:37:56 -0700158 private int mPagingTouchSlop;
159 private int mMaximumVelocity;
Adam Cohen9c4949e2010-10-05 12:27:22 -0700160 protected int mPageLayoutPaddingTop;
161 protected int mPageLayoutPaddingBottom;
162 protected int mPageLayoutPaddingLeft;
163 protected int mPageLayoutPaddingRight;
Winson Chungdf4b83d2010-10-20 17:49:27 -0700164 protected int mPageLayoutWidthGap;
165 protected int mPageLayoutHeightGap;
Michael Jurka87b14902011-05-25 22:13:09 -0700166 protected int mCellCountX = 0;
167 protected int mCellCountY = 0;
Winson Chung7da10252010-10-28 16:07:04 -0700168 protected boolean mCenterPagesVertically;
Adam Cohen68d73932010-11-15 10:50:58 -0800169 protected boolean mAllowOverScroll = true;
170 protected int mUnboundedScrollX;
Michael Jurkadde558b2011-11-09 22:09:06 -0800171 protected int[] mTempVisiblePagesRange = new int[2];
Michael Jurka5e368ff2012-05-14 23:13:15 -0700172 protected boolean mForceDrawAllChildrenNextFrame;
Winson Chung321e9ee2010-08-09 13:37:56 -0700173
Michael Jurka8b805b12012-04-18 14:23:14 -0700174 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range. Otherwise
Adam Cohenebea84d2011-11-09 17:20:41 -0800175 // it is equal to the scaled overscroll position. We use a separate value so as to prevent
176 // the screens from continuing to translate beyond the normal bounds.
177 protected int mOverScrollX;
178
Michael Jurka5f1c5092010-09-03 14:15:02 -0700179 protected static final int INVALID_POINTER = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -0700180
Michael Jurka5f1c5092010-09-03 14:15:02 -0700181 protected int mActivePointerId = INVALID_POINTER;
Winson Chung321e9ee2010-08-09 13:37:56 -0700182
Winson Chung86f77532010-08-24 11:08:22 -0700183 private PageSwitchListener mPageSwitchListener;
Winson Chung321e9ee2010-08-09 13:37:56 -0700184
Michael Jurkae326f182011-11-21 14:05:46 -0800185 protected ArrayList<Boolean> mDirtyPageContent;
Winson Chung321e9ee2010-08-09 13:37:56 -0700186
Michael Jurka0142d492010-08-25 17:46:15 -0700187 // If true, syncPages and syncPageItems will be called to refresh pages
188 protected boolean mContentIsRefreshable = true;
189
190 // If true, modify alpha of neighboring pages as user scrolls left/right
Adam Cohen7d30a372013-07-01 17:03:59 -0700191 protected boolean mFadeInAdjacentScreens = false;
Michael Jurka0142d492010-08-25 17:46:15 -0700192
193 // It true, use a different slop parameter (pagingTouchSlop = 2 * touchSlop) for deciding
194 // to switch to a new page
195 protected boolean mUsePagingTouchSlop = true;
196
Michael Jurka8b805b12012-04-18 14:23:14 -0700197 // If true, the subclass should directly update scrollX itself in its computeScroll method
Michael Jurka0142d492010-08-25 17:46:15 -0700198 // (SmoothPagedView does this)
199 protected boolean mDeferScrollUpdate = false;
Winson Chung9c0565f2013-07-19 13:49:06 -0700200 protected boolean mDeferLoadAssociatedPagesUntilScrollCompletes = false;
Michael Jurka0142d492010-08-25 17:46:15 -0700201
Patrick Dubroy1262e362010-10-06 15:49:50 -0700202 protected boolean mIsPageMoving = false;
203
Winson Chungf0ea4d32011-06-06 14:27:16 -0700204 // All syncs and layout passes are deferred until data is ready.
205 protected boolean mIsDataReady = false;
206
Adam Cohen7d30a372013-07-01 17:03:59 -0700207 protected boolean mAllowLongPress = true;
208
Winson Chungd2be3812013-07-16 11:11:32 -0700209 // Page Indicator
210 private int mPageIndicatorViewId;
211 private PageIndicator mPageIndicator;
Winson Chungc58497e2013-09-03 17:48:37 -0700212 private boolean mAllowPagedViewAnimations = true;
Winson Chung007c6982011-06-14 13:27:53 -0700213
Adam Cohen7d30a372013-07-01 17:03:59 -0700214 // The viewport whether the pages are to be contained (the actual view may be larger than the
215 // viewport)
216 private Rect mViewport = new Rect();
217
218 // Reordering
219 // We use the min scale to determine how much to expand the actually PagedView measured
220 // dimensions such that when we are zoomed out, the view is not clipped
221 private int REORDERING_DROP_REPOSITION_DURATION = 200;
222 protected int REORDERING_REORDER_REPOSITION_DURATION = 300;
223 protected int REORDERING_ZOOM_IN_OUT_DURATION = 250;
Adam Cohenf358a4b2013-07-23 16:47:31 -0700224 private int REORDERING_SIDE_PAGE_HOVER_TIMEOUT = 80;
Adam Cohen7d30a372013-07-01 17:03:59 -0700225 private float mMinScale = 1f;
Winson Chungc58497e2013-09-03 17:48:37 -0700226 private boolean mUseMinScale = false;
Adam Cohen7d30a372013-07-01 17:03:59 -0700227 protected View mDragView;
228 protected AnimatorSet mZoomInOutAnim;
229 private Runnable mSidePageHoverRunnable;
230 private int mSidePageHoverIndex = -1;
231 // This variable's scope is only for the duration of startReordering() and endReordering()
232 private boolean mReorderingStarted = false;
233 // This variable's scope is for the duration of startReordering() and after the zoomIn()
234 // animation after endReordering()
235 private boolean mIsReordering;
236 // The runnable that settles the page after snapToPage and animateDragViewToOriginalPosition
237 private int NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT = 2;
238 private int mPostReorderingPreZoomInRemainingAnimationCount;
239 private Runnable mPostReorderingPreZoomInRunnable;
240
Adam Cohen7d30a372013-07-01 17:03:59 -0700241 // Convenience/caching
242 private Matrix mTmpInvMatrix = new Matrix();
243 private float[] mTmpPoint = new float[2];
Winson Chungc9ca2982013-07-19 12:07:38 -0700244 private int[] mTmpIntPoint = new int[2];
Adam Cohen7d30a372013-07-01 17:03:59 -0700245 private Rect mTmpRect = new Rect();
246 private Rect mAltTmpRect = new Rect();
247
248 // Fling to delete
249 private int FLING_TO_DELETE_FADE_OUT_DURATION = 350;
250 private float FLING_TO_DELETE_FRICTION = 0.035f;
251 // The degrees specifies how much deviation from the up vector to still consider a fling "up"
252 private float FLING_TO_DELETE_MAX_FLING_DEGREES = 65f;
253 protected int mFlingToDeleteThresholdVelocity = -1400;
254 // Drag to delete
255 private boolean mDeferringForDelete = false;
256 private int DELETE_SLIDE_IN_SIDE_PAGE_DURATION = 250;
257 private int DRAG_TO_DELETE_FADE_OUT_DURATION = 350;
258
259 // Drop to delete
260 private View mDeleteDropTarget;
261
Adam Cohen7d30a372013-07-01 17:03:59 -0700262 // Bouncer
263 private boolean mTopAlignPageWhenShrinkingForBouncer = false;
Winson Chungb44b5242011-06-13 11:32:14 -0700264
John Spurlock77e1f472013-09-11 10:09:51 -0400265 protected final Rect mInsets = new Rect();
266
Winson Chung86f77532010-08-24 11:08:22 -0700267 public interface PageSwitchListener {
268 void onPageSwitch(View newPage, int newPageIndex);
Winson Chung321e9ee2010-08-09 13:37:56 -0700269 }
270
Winson Chung321e9ee2010-08-09 13:37:56 -0700271 public PagedView(Context context) {
272 this(context, null);
273 }
274
275 public PagedView(Context context, AttributeSet attrs) {
276 this(context, attrs, 0);
277 }
278
279 public PagedView(Context context, AttributeSet attrs, int defStyle) {
280 super(context, attrs, defStyle);
Winson Chungc9ca2982013-07-19 12:07:38 -0700281
Adam Cohen9c4949e2010-10-05 12:27:22 -0700282 TypedArray a = context.obtainStyledAttributes(attrs,
283 R.styleable.PagedView, defStyle, 0);
Adam Cohen0cd0eba2013-10-28 14:22:25 -0700284
Adam Cohen9c4949e2010-10-05 12:27:22 -0700285 mPageLayoutPaddingTop = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800286 R.styleable.PagedView_pageLayoutPaddingTop, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700287 mPageLayoutPaddingBottom = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800288 R.styleable.PagedView_pageLayoutPaddingBottom, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700289 mPageLayoutPaddingLeft = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800290 R.styleable.PagedView_pageLayoutPaddingLeft, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700291 mPageLayoutPaddingRight = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800292 R.styleable.PagedView_pageLayoutPaddingRight, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700293 mPageLayoutWidthGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700294 R.styleable.PagedView_pageLayoutWidthGap, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700295 mPageLayoutHeightGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700296 R.styleable.PagedView_pageLayoutHeightGap, 0);
Winson Chungd2be3812013-07-16 11:11:32 -0700297 mPageIndicatorViewId = a.getResourceId(R.styleable.PagedView_pageIndicator, -1);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700298 a.recycle();
299
Winson Chung321e9ee2010-08-09 13:37:56 -0700300 setHapticFeedbackEnabled(false);
Michael Jurka0142d492010-08-25 17:46:15 -0700301 init();
Winson Chung321e9ee2010-08-09 13:37:56 -0700302 }
303
304 /**
305 * Initializes various states for this workspace.
306 */
Michael Jurka0142d492010-08-25 17:46:15 -0700307 protected void init() {
Winson Chung86f77532010-08-24 11:08:22 -0700308 mDirtyPageContent = new ArrayList<Boolean>();
309 mDirtyPageContent.ensureCapacity(32);
Adam Cohene0f66b52010-11-23 15:06:07 -0800310 mScroller = new Scroller(getContext(), new ScrollInterpolator());
Winson Chung86f77532010-08-24 11:08:22 -0700311 mCurrentPage = 0;
Winson Chung7da10252010-10-28 16:07:04 -0700312 mCenterPagesVertically = true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700313
314 final ViewConfiguration configuration = ViewConfiguration.get(getContext());
Adam Cohen7d30a372013-07-01 17:03:59 -0700315 mTouchSlop = configuration.getScaledPagingTouchSlop();
Winson Chung321e9ee2010-08-09 13:37:56 -0700316 mPagingTouchSlop = configuration.getScaledPagingTouchSlop();
317 mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
Adam Cohenb5ba0972011-09-07 18:02:31 -0700318 mDensity = getResources().getDisplayMetrics().density;
Adam Cohen265b9a62011-12-07 14:37:18 -0800319
Adam Cohen7d30a372013-07-01 17:03:59 -0700320 // Scale the fling-to-delete threshold by the density
321 mFlingToDeleteThresholdVelocity =
322 (int) (mFlingToDeleteThresholdVelocity * mDensity);
323
Adam Cohen265b9a62011-12-07 14:37:18 -0800324 mFlingThresholdVelocity = (int) (FLING_THRESHOLD_VELOCITY * mDensity);
325 mMinFlingVelocity = (int) (MIN_FLING_VELOCITY * mDensity);
326 mMinSnapVelocity = (int) (MIN_SNAP_VELOCITY * mDensity);
Michael Jurka8b805b12012-04-18 14:23:14 -0700327 setOnHierarchyChangeListener(this);
Winson Chung321e9ee2010-08-09 13:37:56 -0700328 }
329
Winson Chungd2be3812013-07-16 11:11:32 -0700330 protected void onAttachedToWindow() {
Adam Cohen53805212013-10-01 10:39:23 -0700331 super.onAttachedToWindow();
332
Winson Chungd2be3812013-07-16 11:11:32 -0700333 // Hook up the page indicator
334 ViewGroup parent = (ViewGroup) getParent();
335 if (mPageIndicator == null && mPageIndicatorViewId > -1) {
336 mPageIndicator = (PageIndicator) parent.findViewById(mPageIndicatorViewId);
Winson Chungc58497e2013-09-03 17:48:37 -0700337 mPageIndicator.removeAllMarkers(mAllowPagedViewAnimations);
Winson Chung82dfe582013-07-26 15:07:49 -0700338
Winson Chung7819a562013-09-19 15:55:45 -0700339 ArrayList<PageIndicator.PageMarkerResources> markers =
340 new ArrayList<PageIndicator.PageMarkerResources>();
Winson Chung82dfe582013-07-26 15:07:49 -0700341 for (int i = 0; i < getChildCount(); ++i) {
342 markers.add(getPageIndicatorMarker(i));
343 }
Adam Cohenf358a4b2013-07-23 16:47:31 -0700344
Winson Chungc58497e2013-09-03 17:48:37 -0700345 mPageIndicator.addMarkers(markers, mAllowPagedViewAnimations);
Adam Cohenfbdf4272013-10-09 13:02:21 -0700346
347 OnClickListener listener = getPageIndicatorClickListener();
348 if (listener != null) {
349 mPageIndicator.setOnClickListener(listener);
350 }
Adam Cohen53805212013-10-01 10:39:23 -0700351 mPageIndicator.setContentDescription(getPageIndicatorDescription());
Winson Chungd2be3812013-07-16 11:11:32 -0700352 }
353 }
354
Adam Cohen53805212013-10-01 10:39:23 -0700355 protected String getPageIndicatorDescription() {
356 return getCurrentPageDescription();
357 }
358
359 protected OnClickListener getPageIndicatorClickListener() {
360 return null;
361 }
362
Winson Chungd2be3812013-07-16 11:11:32 -0700363 protected void onDetachedFromWindow() {
364 // Unhook the page indicator
365 mPageIndicator = null;
366 }
367
Adam Cohen7d30a372013-07-01 17:03:59 -0700368 void setDeleteDropTarget(View v) {
369 mDeleteDropTarget = v;
370 }
371
372 // Convenience methods to map points from self to parent and vice versa
373 float[] mapPointFromViewToParent(View v, float x, float y) {
374 mTmpPoint[0] = x;
375 mTmpPoint[1] = y;
376 v.getMatrix().mapPoints(mTmpPoint);
377 mTmpPoint[0] += v.getLeft();
378 mTmpPoint[1] += v.getTop();
379 return mTmpPoint;
380 }
381 float[] mapPointFromParentToView(View v, float x, float y) {
382 mTmpPoint[0] = x - v.getLeft();
383 mTmpPoint[1] = y - v.getTop();
384 v.getMatrix().invert(mTmpInvMatrix);
385 mTmpInvMatrix.mapPoints(mTmpPoint);
386 return mTmpPoint;
387 }
388
389 void updateDragViewTranslationDuringDrag() {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700390 if (mDragView != null) {
391 float x = (mLastMotionX - mDownMotionX) + (getScrollX() - mDownScrollX) +
392 (mDragViewBaselineLeft - mDragView.getLeft());
393 float y = mLastMotionY - mDownMotionY;
394 mDragView.setTranslationX(x);
395 mDragView.setTranslationY(y);
Adam Cohen7d30a372013-07-01 17:03:59 -0700396
Adam Cohenf358a4b2013-07-23 16:47:31 -0700397 if (DEBUG) Log.d(TAG, "PagedView.updateDragViewTranslationDuringDrag(): "
398 + x + ", " + y);
399 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700400 }
401
402 public void setMinScale(float f) {
403 mMinScale = f;
Winson Chungc58497e2013-09-03 17:48:37 -0700404 mUseMinScale = true;
Adam Cohen7d30a372013-07-01 17:03:59 -0700405 requestLayout();
406 }
407
408 @Override
409 public void setScaleX(float scaleX) {
410 super.setScaleX(scaleX);
411 if (isReordering(true)) {
412 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
413 mLastMotionX = p[0];
414 mLastMotionY = p[1];
415 updateDragViewTranslationDuringDrag();
416 }
417 }
418
419 // Convenience methods to get the actual width/height of the PagedView (since it is measured
420 // to be larger to account for the minimum possible scale)
421 int getViewportWidth() {
422 return mViewport.width();
423 }
424 int getViewportHeight() {
425 return mViewport.height();
426 }
427
428 // Convenience methods to get the offset ASSUMING that we are centering the pages in the
429 // PagedView both horizontally and vertically
430 int getViewportOffsetX() {
431 return (getMeasuredWidth() - getViewportWidth()) / 2;
432 }
433
434 int getViewportOffsetY() {
435 return (getMeasuredHeight() - getViewportHeight()) / 2;
436 }
437
Adam Cohenedb40762013-07-18 16:45:45 -0700438 PageIndicator getPageIndicator() {
439 return mPageIndicator;
440 }
Winson Chung7819a562013-09-19 15:55:45 -0700441 protected PageIndicator.PageMarkerResources getPageIndicatorMarker(int pageIndex) {
442 return new PageIndicator.PageMarkerResources();
Winson Chung82dfe582013-07-26 15:07:49 -0700443 }
Adam Cohenedb40762013-07-18 16:45:45 -0700444
Winson Chung86f77532010-08-24 11:08:22 -0700445 public void setPageSwitchListener(PageSwitchListener pageSwitchListener) {
446 mPageSwitchListener = pageSwitchListener;
447 if (mPageSwitchListener != null) {
448 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700449 }
450 }
451
452 /**
Winson Chung52aee602013-01-30 12:01:02 -0800453 * Note: this is a reimplementation of View.isLayoutRtl() since that is currently hidden api.
454 */
455 public boolean isLayoutRtl() {
456 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
457 }
458
459 /**
Winson Chungf0ea4d32011-06-06 14:27:16 -0700460 * Called by subclasses to mark that data is ready, and that we can begin loading and laying
461 * out pages.
462 */
463 protected void setDataIsReady() {
464 mIsDataReady = true;
465 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700466
Winson Chungf0ea4d32011-06-06 14:27:16 -0700467 protected boolean isDataReady() {
468 return mIsDataReady;
469 }
470
471 /**
Winson Chung86f77532010-08-24 11:08:22 -0700472 * Returns the index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700473 *
Winson Chung86f77532010-08-24 11:08:22 -0700474 * @return The index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700475 */
Winson Chung86f77532010-08-24 11:08:22 -0700476 int getCurrentPage() {
477 return mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -0700478 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700479
Winson Chung360e63f2012-04-27 13:48:05 -0700480 int getNextPage() {
481 return (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
482 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700483
Winson Chung86f77532010-08-24 11:08:22 -0700484 int getPageCount() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700485 return getChildCount();
486 }
487
Winson Chung86f77532010-08-24 11:08:22 -0700488 View getPageAt(int index) {
Winson Chung321e9ee2010-08-09 13:37:56 -0700489 return getChildAt(index);
490 }
491
Adam Cohenae4f1552011-10-20 00:15:42 -0700492 protected int indexToPage(int index) {
493 return index;
494 }
495
Winson Chung321e9ee2010-08-09 13:37:56 -0700496 /**
Winson Chungbbc60d82010-11-11 16:34:41 -0800497 * Updates the scroll of the current page immediately to its final scroll position. We use this
498 * in CustomizePagedView to allow tabs to share the same PagedView while resetting the scroll of
499 * the previous tab page.
500 */
501 protected void updateCurrentPageScroll() {
Adam Cohen0ffac432013-07-10 11:19:26 -0700502 // If the current page is invalid, just reset the scroll position to zero
503 int newX = 0;
504 if (0 <= mCurrentPage && mCurrentPage < getPageCount()) {
Adam Cohenedb40762013-07-18 16:45:45 -0700505 newX = getScrollForPage(mCurrentPage);
Adam Cohen0ffac432013-07-10 11:19:26 -0700506 }
Winson Chungbbc60d82010-11-11 16:34:41 -0800507 scrollTo(newX, 0);
508 mScroller.setFinalX(newX);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800509 mScroller.forceFinished(true);
Winson Chungbbc60d82010-11-11 16:34:41 -0800510 }
511
512 /**
Chet Haasebc2f0822012-10-26 17:59:53 -0700513 * Called during AllApps/Home transitions to avoid unnecessary work. When that other animation
514 * ends, {@link #resumeScrolling()} should be called, along with
515 * {@link #updateCurrentPageScroll()} to correctly set the final state and re-enable scrolling.
516 */
517 void pauseScrolling() {
518 mScroller.forceFinished(true);
Chet Haasebc2f0822012-10-26 17:59:53 -0700519 }
520
521 /**
522 * Enables scrolling again.
523 * @see #pauseScrolling()
524 */
525 void resumeScrolling() {
Chet Haasebc2f0822012-10-26 17:59:53 -0700526 }
527 /**
Winson Chung86f77532010-08-24 11:08:22 -0700528 * Sets the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700529 */
Winson Chung86f77532010-08-24 11:08:22 -0700530 void setCurrentPage(int currentPage) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800531 if (!mScroller.isFinished()) {
532 mScroller.abortAnimation();
Adam Cohen97d53112013-10-01 11:07:24 -0700533 // We need to clean up the next page here to avoid computeScrollHelper from
534 // updating current page on the pass.
535 mNextPage = INVALID_PAGE;
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800536 }
Michael Jurkad3ef3062010-11-23 16:23:58 -0800537 // don't introduce any checks like mCurrentPage == currentPage here-- if we change the
538 // the default
539 if (getChildCount() == 0) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800540 return;
541 }
Adam Cohene61a9a22013-06-11 15:45:31 -0700542 mForceScreenScrolled = true;
Winson Chung86f77532010-08-24 11:08:22 -0700543 mCurrentPage = Math.max(0, Math.min(currentPage, getPageCount() - 1));
Winson Chung181c3dc2013-07-17 15:36:20 -0700544 updateCurrentPageScroll();
Winson Chung86f77532010-08-24 11:08:22 -0700545 notifyPageSwitchListener();
Winson Chunga12a2502010-12-20 14:41:35 -0800546 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -0700547 }
548
Winson Chung8c87cd82013-07-23 16:20:10 -0700549 /**
550 * The restore page will be set in place of the current page at the next (likely first)
551 * layout.
552 */
553 void setRestorePage(int restorePage) {
554 mRestorePage = restorePage;
555 }
556
Michael Jurka0142d492010-08-25 17:46:15 -0700557 protected void notifyPageSwitchListener() {
Winson Chung86f77532010-08-24 11:08:22 -0700558 if (mPageSwitchListener != null) {
559 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700560 }
Winson Chungd2be3812013-07-16 11:11:32 -0700561
562 // Update the page indicator (when we aren't reordering)
563 if (mPageIndicator != null && !isReordering(false)) {
564 mPageIndicator.setActiveMarker(getNextPage());
565 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700566 }
Michael Jurkace7e05f2011-02-01 22:02:35 -0800567 protected void pageBeginMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700568 if (!mIsPageMoving) {
569 mIsPageMoving = true;
570 onPageBeginMoving();
571 }
Patrick Dubroy1262e362010-10-06 15:49:50 -0700572 }
573
Michael Jurkace7e05f2011-02-01 22:02:35 -0800574 protected void pageEndMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700575 if (mIsPageMoving) {
576 mIsPageMoving = false;
577 onPageEndMoving();
578 }
Michael Jurka0142d492010-08-25 17:46:15 -0700579 }
580
Adam Cohen26976d92011-03-22 15:33:33 -0700581 protected boolean isPageMoving() {
582 return mIsPageMoving;
583 }
584
Michael Jurka0142d492010-08-25 17:46:15 -0700585 // a method that subclasses can override to add behavior
Patrick Dubroy1262e362010-10-06 15:49:50 -0700586 protected void onPageBeginMoving() {
587 }
588
589 // a method that subclasses can override to add behavior
590 protected void onPageEndMoving() {
Michael Jurka0142d492010-08-25 17:46:15 -0700591 }
592
Winson Chung321e9ee2010-08-09 13:37:56 -0700593 /**
Winson Chung86f77532010-08-24 11:08:22 -0700594 * Registers the specified listener on each page contained in this workspace.
Winson Chung321e9ee2010-08-09 13:37:56 -0700595 *
596 * @param l The listener used to respond to long clicks.
597 */
598 @Override
599 public void setOnLongClickListener(OnLongClickListener l) {
600 mLongClickListener = l;
Winson Chung86f77532010-08-24 11:08:22 -0700601 final int count = getPageCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700602 for (int i = 0; i < count; i++) {
Winson Chung86f77532010-08-24 11:08:22 -0700603 getPageAt(i).setOnLongClickListener(l);
Winson Chung321e9ee2010-08-09 13:37:56 -0700604 }
Adam Cohen1697b792013-09-17 19:08:21 -0700605 super.setOnLongClickListener(l);
Winson Chung321e9ee2010-08-09 13:37:56 -0700606 }
607
608 @Override
Adam Cohen68d73932010-11-15 10:50:58 -0800609 public void scrollBy(int x, int y) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700610 scrollTo(mUnboundedScrollX + x, getScrollY() + y);
Adam Cohen68d73932010-11-15 10:50:58 -0800611 }
612
613 @Override
Michael Jurka0142d492010-08-25 17:46:15 -0700614 public void scrollTo(int x, int y) {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700615 // In free scroll mode, we clamp the scrollX
616 if (mFreeScroll) {
617 x = Math.min(x, mFreeScrollMaxScrollX);
618 x = Math.max(x, mFreeScrollMinScrollX);
619 }
620
Adam Cohen0ffac432013-07-10 11:19:26 -0700621 final boolean isRtl = isLayoutRtl();
Adam Cohen68d73932010-11-15 10:50:58 -0800622 mUnboundedScrollX = x;
623
Adam Cohen0ffac432013-07-10 11:19:26 -0700624 boolean isXBeforeFirstPage = isRtl ? (x > mMaxScrollX) : (x < 0);
625 boolean isXAfterLastPage = isRtl ? (x < 0) : (x > mMaxScrollX);
626 if (isXBeforeFirstPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800627 super.scrollTo(0, y);
628 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700629 if (isRtl) {
630 overScroll(x - mMaxScrollX);
631 } else {
632 overScroll(x);
633 }
Adam Cohen68d73932010-11-15 10:50:58 -0800634 }
Adam Cohen0ffac432013-07-10 11:19:26 -0700635 } else if (isXAfterLastPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800636 super.scrollTo(mMaxScrollX, y);
637 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700638 if (isRtl) {
639 overScroll(x);
640 } else {
641 overScroll(x - mMaxScrollX);
642 }
Adam Cohen68d73932010-11-15 10:50:58 -0800643 }
644 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -0800645 mOverScrollX = x;
Adam Cohen68d73932010-11-15 10:50:58 -0800646 super.scrollTo(x, y);
647 }
648
Michael Jurka0142d492010-08-25 17:46:15 -0700649 mTouchX = x;
650 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
Adam Cohen7d30a372013-07-01 17:03:59 -0700651
652 // Update the last motion events when scrolling
653 if (isReordering(true)) {
654 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
655 mLastMotionX = p[0];
656 mLastMotionY = p[1];
657 updateDragViewTranslationDuringDrag();
658 }
Michael Jurka0142d492010-08-25 17:46:15 -0700659 }
660
Adam Cohen53805212013-10-01 10:39:23 -0700661 private void sendScrollAccessibilityEvent() {
662 AccessibilityManager am =
663 (AccessibilityManager) getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
664 if (am.isEnabled()) {
665 AccessibilityEvent ev =
666 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_SCROLLED);
Adam Cohen53805212013-10-01 10:39:23 -0700667 ev.setItemCount(getChildCount());
668 ev.setFromIndex(mCurrentPage);
Adam Cohen53805212013-10-01 10:39:23 -0700669
Alan Viverette254139a2013-10-08 13:13:46 -0700670 final int action;
Adam Cohen53805212013-10-01 10:39:23 -0700671 if (getNextPage() >= mCurrentPage) {
672 action = AccessibilityNodeInfo.ACTION_SCROLL_FORWARD;
673 } else {
674 action = AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD;
675 }
676
677 ev.setAction(action);
678 sendAccessibilityEventUnchecked(ev);
679 }
680 }
681
Michael Jurka0142d492010-08-25 17:46:15 -0700682 // we moved this functionality to a helper function so SmoothPagedView can reuse it
683 protected boolean computeScrollHelper() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700684 if (mScroller.computeScrollOffset()) {
Winson Chung557d6ed2011-07-08 15:34:52 -0700685 // Don't bother scrolling if the page does not need to be moved
Michael Jurka8b805b12012-04-18 14:23:14 -0700686 if (getScrollX() != mScroller.getCurrX()
687 || getScrollY() != mScroller.getCurrY()
Michael Jurkab06d95f2012-04-02 06:26:53 -0700688 || mOverScrollX != mScroller.getCurrX()) {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700689 float scaleX = mFreeScroll ? getScaleX() : 1f;
690 int scrollX = (int) (mScroller.getCurrX() * (1 / scaleX));
691 scrollTo(scrollX, mScroller.getCurrY());
Winson Chung557d6ed2011-07-08 15:34:52 -0700692 }
Michael Jurka0142d492010-08-25 17:46:15 -0700693 invalidate();
694 return true;
Winson Chung86f77532010-08-24 11:08:22 -0700695 } else if (mNextPage != INVALID_PAGE) {
Adam Cohen53805212013-10-01 10:39:23 -0700696 sendScrollAccessibilityEvent();
697
Winson Chung86f77532010-08-24 11:08:22 -0700698 mCurrentPage = Math.max(0, Math.min(mNextPage, getPageCount() - 1));
Winson Chung86f77532010-08-24 11:08:22 -0700699 mNextPage = INVALID_PAGE;
Michael Jurka0142d492010-08-25 17:46:15 -0700700 notifyPageSwitchListener();
Winson Chungb44b5242011-06-13 11:32:14 -0700701
Winson Chung9c0565f2013-07-19 13:49:06 -0700702 // Load the associated pages if necessary
703 if (mDeferLoadAssociatedPagesUntilScrollCompletes) {
704 loadAssociatedPages(mCurrentPage);
705 mDeferLoadAssociatedPagesUntilScrollCompletes = false;
706 }
707
Adam Cohen73aa9752010-11-24 16:26:58 -0800708 // We don't want to trigger a page end moving unless the page has settled
709 // and the user has stopped scrolling
710 if (mTouchState == TOUCH_STATE_REST) {
711 pageEndMoving();
712 }
Winson Chungc27d1bb2011-09-29 12:07:42 -0700713
Adam Cohen7d30a372013-07-01 17:03:59 -0700714 onPostReorderingAnimationCompleted();
Adam Cohen53805212013-10-01 10:39:23 -0700715 AccessibilityManager am = (AccessibilityManager)
Adam Cohen0ffac432013-07-10 11:19:26 -0700716 getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
Adam Cohen53805212013-10-01 10:39:23 -0700717 if (am.isEnabled()) {
718 // Notify the user when the page changes
719 announceForAccessibility(getCurrentPageDescription());
Adam Cohen0ffac432013-07-10 11:19:26 -0700720 }
Michael Jurka0142d492010-08-25 17:46:15 -0700721 return true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700722 }
Michael Jurka0142d492010-08-25 17:46:15 -0700723 return false;
724 }
725
726 @Override
727 public void computeScroll() {
728 computeScrollHelper();
Winson Chung321e9ee2010-08-09 13:37:56 -0700729 }
730
Adam Cohen7d30a372013-07-01 17:03:59 -0700731 protected boolean shouldSetTopAlignedPivotForWidget(int childIndex) {
732 return mTopAlignPageWhenShrinkingForBouncer;
733 }
734
Adam Cohen96d30a12013-07-16 18:13:21 -0700735 public static class LayoutParams extends ViewGroup.LayoutParams {
736 public boolean isFullScreenPage = false;
737
738 /**
739 * {@inheritDoc}
740 */
741 public LayoutParams(int width, int height) {
742 super(width, height);
743 }
744
745 public LayoutParams(ViewGroup.LayoutParams source) {
746 super(source);
747 }
748 }
749
750 protected LayoutParams generateDefaultLayoutParams() {
751 return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
752 }
753
Adam Cohenedb40762013-07-18 16:45:45 -0700754 public void addFullScreenPage(View page) {
Adam Cohen96d30a12013-07-16 18:13:21 -0700755 LayoutParams lp = generateDefaultLayoutParams();
756 lp.isFullScreenPage = true;
757 super.addView(page, 0, lp);
758 }
759
Adam Cohen410f3cd2013-09-22 12:09:32 -0700760 public int getNormalChildHeight() {
761 return mNormalChildHeight;
762 }
763
Winson Chung321e9ee2010-08-09 13:37:56 -0700764 @Override
765 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700766 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700767 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
768 return;
769 }
770
Adam Cohen7d30a372013-07-01 17:03:59 -0700771 // We measure the dimensions of the PagedView to be larger than the pages so that when we
772 // zoom out (and scale down), the view is still contained in the parent
Adam Cohen7d30a372013-07-01 17:03:59 -0700773 int widthMode = MeasureSpec.getMode(widthMeasureSpec);
774 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
775 int heightMode = MeasureSpec.getMode(heightMeasureSpec);
Winson Chung8aad6102012-05-11 16:27:49 -0700776 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
Adam Cohen7d30a372013-07-01 17:03:59 -0700777 // NOTE: We multiply by 1.5f to account for the fact that depending on the offset of the
778 // viewport, we can be at most one and a half screens offset once we scale down
779 DisplayMetrics dm = getResources().getDisplayMetrics();
Adam Cohendbdff6b2013-09-18 19:09:15 -0700780 int maxSize = Math.max(dm.widthPixels, dm.heightPixels + mInsets.top + mInsets.bottom);
Adam Cohen410f3cd2013-09-22 12:09:32 -0700781
Winson Chungc58497e2013-09-03 17:48:37 -0700782 int parentWidthSize, parentHeightSize;
783 int scaledWidthSize, scaledHeightSize;
784 if (mUseMinScale) {
785 parentWidthSize = (int) (1.5f * maxSize);
786 parentHeightSize = maxSize;
787 scaledWidthSize = (int) (parentWidthSize / mMinScale);
788 scaledHeightSize = (int) (parentHeightSize / mMinScale);
789 } else {
790 scaledWidthSize = widthSize;
791 scaledHeightSize = heightSize;
792 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700793 mViewport.set(0, 0, widthSize, heightSize);
794
795 if (widthMode == MeasureSpec.UNSPECIFIED || heightMode == MeasureSpec.UNSPECIFIED) {
796 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
797 return;
Winson Chung321e9ee2010-08-09 13:37:56 -0700798 }
799
Winson Chung8aad6102012-05-11 16:27:49 -0700800 // Return early if we aren't given a proper dimension
801 if (widthSize <= 0 || heightSize <= 0) {
802 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
803 return;
804 }
805
Adam Lesinski6b879f02010-11-04 16:15:23 -0700806 /* Allow the height to be set as WRAP_CONTENT. This allows the particular case
807 * of the All apps view on XLarge displays to not take up more space then it needs. Width
808 * is still not allowed to be set as WRAP_CONTENT since many parts of the code expect
809 * each page to have the same width.
810 */
Michael Jurka8b805b12012-04-18 14:23:14 -0700811 final int verticalPadding = getPaddingTop() + getPaddingBottom();
812 final int horizontalPadding = getPaddingLeft() + getPaddingRight();
Winson Chung321e9ee2010-08-09 13:37:56 -0700813
814 // The children are given the same width and height as the workspace
Michael Jurka5f1c5092010-09-03 14:15:02 -0700815 // unless they were set to WRAP_CONTENT
Winson Chung785d2eb2011-04-14 16:08:02 -0700816 if (DEBUG) Log.d(TAG, "PagedView.onMeasure(): " + widthSize + ", " + heightSize);
Adam Cohen7d30a372013-07-01 17:03:59 -0700817 if (DEBUG) Log.d(TAG, "PagedView.scaledSize: " + scaledWidthSize + ", " + scaledHeightSize);
818 if (DEBUG) Log.d(TAG, "PagedView.parentSize: " + parentWidthSize + ", " + parentHeightSize);
819 if (DEBUG) Log.d(TAG, "PagedView.horizontalPadding: " + horizontalPadding);
820 if (DEBUG) Log.d(TAG, "PagedView.verticalPadding: " + verticalPadding);
Winson Chung321e9ee2010-08-09 13:37:56 -0700821 final int childCount = getChildCount();
822 for (int i = 0; i < childCount; i++) {
Michael Jurka5f1c5092010-09-03 14:15:02 -0700823 // disallowing padding in paged view (just pass 0)
Adam Cohen22f823d2011-09-01 17:22:18 -0700824 final View child = getPageAt(i);
Vladimir Marko2824b072013-10-04 16:42:17 +0100825 if (child.getVisibility() != GONE) {
826 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
Michael Jurka5f1c5092010-09-03 14:15:02 -0700827
Vladimir Marko2824b072013-10-04 16:42:17 +0100828 int childWidthMode;
829 int childHeightMode;
830 int childWidth;
831 int childHeight;
Adam Cohen96d30a12013-07-16 18:13:21 -0700832
Vladimir Marko2824b072013-10-04 16:42:17 +0100833 if (!lp.isFullScreenPage) {
834 if (lp.width == LayoutParams.WRAP_CONTENT) {
835 childWidthMode = MeasureSpec.AT_MOST;
836 } else {
837 childWidthMode = MeasureSpec.EXACTLY;
838 }
839
840 if (lp.height == LayoutParams.WRAP_CONTENT) {
841 childHeightMode = MeasureSpec.AT_MOST;
842 } else {
843 childHeightMode = MeasureSpec.EXACTLY;
844 }
845
846 childWidth = widthSize - horizontalPadding;
847 childHeight = heightSize - verticalPadding - mInsets.top - mInsets.bottom;
848 mNormalChildHeight = childHeight;
849
Adam Cohen96d30a12013-07-16 18:13:21 -0700850 } else {
851 childWidthMode = MeasureSpec.EXACTLY;
Adam Cohen96d30a12013-07-16 18:13:21 -0700852 childHeightMode = MeasureSpec.EXACTLY;
Vladimir Marko2824b072013-10-04 16:42:17 +0100853
854 if (mUseMinScale) {
855 childWidth = getViewportWidth();
856 childHeight = getViewportHeight();
857 } else {
858 childWidth = widthSize - getPaddingLeft() - getPaddingRight();
859 childHeight = heightSize - getPaddingTop() - getPaddingBottom();
860 }
Adam Cohen96d30a12013-07-16 18:13:21 -0700861 }
862
Vladimir Marko2824b072013-10-04 16:42:17 +0100863 final int childWidthMeasureSpec =
864 MeasureSpec.makeMeasureSpec(childWidth, childWidthMode);
865 final int childHeightMeasureSpec =
866 MeasureSpec.makeMeasureSpec(childHeight, childHeightMode);
867 child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700868 }
Adam Lesinski6b879f02010-11-04 16:15:23 -0700869 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700870 setMeasuredDimension(scaledWidthSize, scaledHeightSize);
Adam Cohen60b07122011-11-14 17:26:06 -0800871 }
872
Winson Chung321e9ee2010-08-09 13:37:56 -0700873 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -0700874 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700875 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700876 return;
877 }
878
Winson Chung785d2eb2011-04-14 16:08:02 -0700879 if (DEBUG) Log.d(TAG, "PagedView.onLayout()");
Winson Chung321e9ee2010-08-09 13:37:56 -0700880 final int childCount = getChildCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700881
Adam Cohenedb40762013-07-18 16:45:45 -0700882 int screenWidth = getViewportWidth();
883
Adam Cohen7d30a372013-07-01 17:03:59 -0700884 int offsetX = getViewportOffsetX();
885 int offsetY = getViewportOffsetY();
886
887 // Update the viewport offsets
888 mViewport.offset(offsetX, offsetY);
889
Adam Cohen0ffac432013-07-10 11:19:26 -0700890 final boolean isRtl = isLayoutRtl();
891
892 final int startIndex = isRtl ? childCount - 1 : 0;
893 final int endIndex = isRtl ? -1 : childCount;
894 final int delta = isRtl ? -1 : 1;
895
Adam Cohen7d30a372013-07-01 17:03:59 -0700896 int verticalPadding = getPaddingTop() + getPaddingBottom();
Adam Cohenedb40762013-07-18 16:45:45 -0700897
Michael Jurka8fd3adc2013-10-16 13:50:24 -0700898 int childLeft = offsetX + (screenWidth - getChildWidth(startIndex)) / 2;
Adam Cohenedb40762013-07-18 16:45:45 -0700899 if (mPageScrolls == null || getChildCount() != mChildCountOnLastLayout) {
900 mPageScrolls = new int[getChildCount()];
901 }
902
Adam Cohen0ffac432013-07-10 11:19:26 -0700903 for (int i = startIndex; i != endIndex; i += delta) {
Adam Cohen22f823d2011-09-01 17:22:18 -0700904 final View child = getPageAt(i);
Winson Chung321e9ee2010-08-09 13:37:56 -0700905 if (child.getVisibility() != View.GONE) {
Vladimir Marko2824b072013-10-04 16:42:17 +0100906 LayoutParams lp = (LayoutParams) child.getLayoutParams();
907 int childTop;
908 if (lp.isFullScreenPage) {
909 childTop = offsetY;
910 } else {
911 childTop = offsetY + getPaddingTop() + mInsets.top;
912 if (mCenterPagesVertically) {
913 childTop += (getViewportHeight() - mInsets.top - mInsets.bottom - verticalPadding - child.getMeasuredHeight()) / 2;
914 }
915 }
916
Adam Cohen96d30a12013-07-16 18:13:21 -0700917 final int childWidth = child.getMeasuredWidth();
Adam Lesinski6b879f02010-11-04 16:15:23 -0700918 final int childHeight = child.getMeasuredHeight();
Michael Jurkad3ef3062010-11-23 16:23:58 -0800919
Winson Chung785d2eb2011-04-14 16:08:02 -0700920 if (DEBUG) Log.d(TAG, "\tlayout-child" + i + ": " + childLeft + ", " + childTop);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700921 child.layout(childLeft, childTop,
Michael Jurkad3ef3062010-11-23 16:23:58 -0800922 childLeft + child.getMeasuredWidth(), childTop + childHeight);
Adam Cohenedb40762013-07-18 16:45:45 -0700923
924 // We assume the left and right padding are equal, and hence center the pages
925 // horizontally
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700926 int scrollOffset = (getViewportWidth() - childWidth) / 2;
Adam Cohenedb40762013-07-18 16:45:45 -0700927 mPageScrolls[i] = childLeft - scrollOffset - offsetX;
928
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700929 if (i != endIndex - delta) {
Adam Cohenaf9b0e52013-09-23 19:27:38 -0700930 childLeft += childWidth + scrollOffset;
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700931 int nextScrollOffset = (getViewportWidth() - getChildWidth(i + delta)) / 2;
Adam Cohenaf9b0e52013-09-23 19:27:38 -0700932 childLeft += nextScrollOffset;
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700933 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700934 }
935 }
Winson Chungc3665fa2011-09-14 17:56:27 -0700936
937 if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) {
938 setHorizontalScrollBarEnabled(false);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800939 updateCurrentPageScroll();
Winson Chungc3665fa2011-09-14 17:56:27 -0700940 setHorizontalScrollBarEnabled(true);
941 mFirstLayout = false;
942 }
Adam Cohenf698c6e2013-07-17 18:44:25 -0700943
944 if (childCount > 0) {
945 final int index = isLayoutRtl() ? 0 : childCount - 1;
Adam Cohenedb40762013-07-18 16:45:45 -0700946 mMaxScrollX = getScrollForPage(index);
Adam Cohenf698c6e2013-07-17 18:44:25 -0700947 } else {
948 mMaxScrollX = 0;
949 }
950
951 if (mScroller.isFinished() && mChildCountOnLastLayout != getChildCount() &&
952 !mDeferringForDelete) {
Adam Cohen21cd0022013-10-09 18:57:02 -0700953 if (mRestorePage != INVALID_RESTORE_PAGE) {
Winson Chung8c87cd82013-07-23 16:20:10 -0700954 setCurrentPage(mRestorePage);
Adam Cohen21cd0022013-10-09 18:57:02 -0700955 mRestorePage = INVALID_RESTORE_PAGE;
Winson Chung8c87cd82013-07-23 16:20:10 -0700956 } else {
957 setCurrentPage(getNextPage());
958 }
Adam Cohenf698c6e2013-07-17 18:44:25 -0700959 }
960 mChildCountOnLastLayout = getChildCount();
Adam Cohenf358a4b2013-07-23 16:47:31 -0700961
962 if (isReordering(true)) {
963 updateDragViewTranslationDuringDrag();
964 }
Winson Chunge3193b92010-09-10 11:44:42 -0700965 }
966
Adam Cohenf34bab52010-09-30 14:11:56 -0700967 protected void screenScrolled(int screenCenter) {
Michael Jurka869390b2012-05-06 15:55:19 -0700968 boolean isInOverscroll = mOverScrollX < 0 || mOverScrollX > mMaxScrollX;
969
970 if (mFadeInAdjacentScreens && !isInOverscroll) {
Adam Cohen73894962011-10-31 13:17:17 -0700971 for (int i = 0; i < getChildCount(); i++) {
972 View child = getChildAt(i);
973 if (child != null) {
974 float scrollProgress = getScrollProgress(screenCenter, child, i);
975 float alpha = 1 - Math.abs(scrollProgress);
Michael Jurka7372c592012-01-16 04:21:35 -0800976 child.setAlpha(alpha);
Adam Cohen73894962011-10-31 13:17:17 -0700977 }
978 }
979 invalidate();
980 }
Adam Cohenf34bab52010-09-30 14:11:56 -0700981 }
982
Winson Chungc58497e2013-09-03 17:48:37 -0700983 protected void enablePagedViewAnimations() {
984 mAllowPagedViewAnimations = true;
985
986 }
987 protected void disablePagedViewAnimations() {
988 mAllowPagedViewAnimations = false;
989 }
990
Winson Chunge3193b92010-09-10 11:44:42 -0700991 @Override
Michael Jurka8b805b12012-04-18 14:23:14 -0700992 public void onChildViewAdded(View parent, View child) {
Winson Chungd2be3812013-07-16 11:11:32 -0700993 // Update the page indicator, we don't update the page indicator as we
994 // add/remove pages
995 if (mPageIndicator != null && !isReordering(false)) {
Winson Chung82dfe582013-07-26 15:07:49 -0700996 int pageIndex = indexOfChild(child);
Winson Chung7819a562013-09-19 15:55:45 -0700997 mPageIndicator.addMarker(pageIndex,
998 getPageIndicatorMarker(pageIndex),
Winson Chungc58497e2013-09-03 17:48:37 -0700999 mAllowPagedViewAnimations);
Winson Chungd2be3812013-07-16 11:11:32 -07001000 }
1001
Adam Cohen2591f6a2011-10-25 14:36:40 -07001002 // This ensures that when children are added, they get the correct transforms / alphas
1003 // in accordance with any scroll effects.
1004 mForceScreenScrolled = true;
Adam Cohen7a9e58a2013-10-01 18:02:13 -07001005 updateFreescrollBounds();
Adam Cohen2591f6a2011-10-25 14:36:40 -07001006 invalidate();
1007 }
1008
Michael Jurka8b805b12012-04-18 14:23:14 -07001009 @Override
1010 public void onChildViewRemoved(View parent, View child) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001011 mForceScreenScrolled = true;
Adam Cohen7a9e58a2013-10-01 18:02:13 -07001012 updateFreescrollBounds();
Adam Cohen7d30a372013-07-01 17:03:59 -07001013 invalidate();
Michael Jurka8b805b12012-04-18 14:23:14 -07001014 }
1015
Winson Chungd2be3812013-07-16 11:11:32 -07001016 private void removeMarkerForView(int index) {
1017 // Update the page indicator, we don't update the page indicator as we
1018 // add/remove pages
1019 if (mPageIndicator != null && !isReordering(false)) {
Winson Chungc58497e2013-09-03 17:48:37 -07001020 mPageIndicator.removeMarker(index, mAllowPagedViewAnimations);
Winson Chungd2be3812013-07-16 11:11:32 -07001021 }
1022 }
1023
1024 @Override
1025 public void removeView(View v) {
1026 // XXX: We should find a better way to hook into this before the view
1027 // gets removed form its parent...
1028 removeMarkerForView(indexOfChild(v));
1029 super.removeView(v);
1030 }
1031 @Override
1032 public void removeViewInLayout(View v) {
1033 // XXX: We should find a better way to hook into this before the view
1034 // gets removed form its parent...
1035 removeMarkerForView(indexOfChild(v));
1036 super.removeViewInLayout(v);
1037 }
1038 @Override
1039 public void removeViewAt(int index) {
1040 // XXX: We should find a better way to hook into this before the view
1041 // gets removed form its parent...
1042 removeViewAt(index);
1043 super.removeViewAt(index);
1044 }
1045 @Override
1046 public void removeAllViewsInLayout() {
1047 // Update the page indicator, we don't update the page indicator as we
1048 // add/remove pages
1049 if (mPageIndicator != null) {
Winson Chungc58497e2013-09-03 17:48:37 -07001050 mPageIndicator.removeAllMarkers(mAllowPagedViewAnimations);
Winson Chungd2be3812013-07-16 11:11:32 -07001051 }
1052
1053 super.removeAllViewsInLayout();
1054 }
1055
Adam Cohen73894962011-10-31 13:17:17 -07001056 protected int getChildOffset(int index) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001057 if (index < 0 || index > getChildCount() - 1) return 0;
1058
Adam Cohenf698c6e2013-07-17 18:44:25 -07001059 int offset = getPageAt(index).getLeft() - getViewportOffsetX();
Adam Cohen73894962011-10-31 13:17:17 -07001060
Adam Cohenf698c6e2013-07-17 18:44:25 -07001061 return offset;
Adam Cohen73894962011-10-31 13:17:17 -07001062 }
1063
Adam Cohenf358a4b2013-07-23 16:47:31 -07001064 protected void getOverviewModePages(int[] range) {
Winson Chungc9ca2982013-07-19 12:07:38 -07001065 range[0] = 0;
Adam Cohen1f1f45d2013-10-02 09:40:18 -07001066 range[1] = Math.max(0, getChildCount() - 1);
Adam Cohen7d30a372013-07-01 17:03:59 -07001067 }
1068
Michael Jurkadde558b2011-11-09 22:09:06 -08001069 protected void getVisiblePages(int[] range) {
Michael Jurka0142d492010-08-25 17:46:15 -07001070 final int pageCount = getChildCount();
Winson Chungc9ca2982013-07-19 12:07:38 -07001071 mTmpIntPoint[0] = mTmpIntPoint[1] = 0;
Michael Jurka4ff7d792012-04-02 03:46:50 -07001072
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001073 range[0] = -1;
1074 range[1] = -1;
1075
Michael Jurkac4fb9172010-09-02 17:19:20 -07001076 if (pageCount > 0) {
Winson Chungc9ca2982013-07-19 12:07:38 -07001077 int viewportWidth = getViewportWidth();
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001078 int curScreen = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -07001079
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001080 int count = getChildCount();
1081 for (int i = 0; i < count; i++) {
1082 View currPage = getPageAt(i);
Winson Chungc9ca2982013-07-19 12:07:38 -07001083
Winson Chungc9ca2982013-07-19 12:07:38 -07001084 mTmpIntPoint[0] = 0;
Winson Chungc763c4e2013-07-19 13:49:06 -07001085 Utilities.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false);
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001086 if (mTmpIntPoint[0] > viewportWidth) {
1087 if (range[0] == -1) {
1088 continue;
1089 } else {
1090 break;
1091 }
1092 }
1093
Adam Cohen6a678da2013-09-24 10:58:01 -07001094 mTmpIntPoint[0] = currPage.getMeasuredWidth();
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001095 Utilities.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false);
1096 if (mTmpIntPoint[0] < 0) {
1097 if (range[0] == -1) {
1098 continue;
1099 } else {
1100 break;
1101 }
1102 }
1103 curScreen = i;
1104 if (range[0] < 0) {
1105 range[0] = curScreen;
Winson Chungc9ca2982013-07-19 12:07:38 -07001106 }
1107 }
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001108
1109 range[1] = curScreen;
Michael Jurkadde558b2011-11-09 22:09:06 -08001110 } else {
1111 range[0] = -1;
1112 range[1] = -1;
1113 }
1114 }
1115
Michael Jurka920d7f42012-05-14 16:29:55 -07001116 protected boolean shouldDrawChild(View child) {
Adam Cohenf3434992013-09-16 16:52:59 -07001117 return child.getAlpha() > 0 && child.getVisibility() == VISIBLE;
Michael Jurka920d7f42012-05-14 16:29:55 -07001118 }
1119
Michael Jurkadde558b2011-11-09 22:09:06 -08001120 @Override
1121 protected void dispatchDraw(Canvas canvas) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001122 int halfScreenSize = getViewportWidth() / 2;
Michael Jurka8b805b12012-04-18 14:23:14 -07001123 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range.
1124 // Otherwise it is equal to the scaled overscroll position.
Adam Cohenebea84d2011-11-09 17:20:41 -08001125 int screenCenter = mOverScrollX + halfScreenSize;
Michael Jurkadde558b2011-11-09 22:09:06 -08001126
1127 if (screenCenter != mLastScreenCenter || mForceScreenScrolled) {
Michael Jurkab06d95f2012-04-02 06:26:53 -07001128 // set mForceScreenScrolled before calling screenScrolled so that screenScrolled can
1129 // set it for the next frame
1130 mForceScreenScrolled = false;
Michael Jurkadde558b2011-11-09 22:09:06 -08001131 screenScrolled(screenCenter);
1132 mLastScreenCenter = screenCenter;
Michael Jurkadde558b2011-11-09 22:09:06 -08001133 }
1134
1135 // Find out which screens are visible; as an optimization we only call draw on them
1136 final int pageCount = getChildCount();
1137 if (pageCount > 0) {
1138 getVisiblePages(mTempVisiblePagesRange);
1139 final int leftScreen = mTempVisiblePagesRange[0];
1140 final int rightScreen = mTempVisiblePagesRange[1];
Winson Chungc6f10b92011-11-14 11:39:07 -08001141 if (leftScreen != -1 && rightScreen != -1) {
1142 final long drawingTime = getDrawingTime();
1143 // Clip to the bounds
1144 canvas.save();
Michael Jurka8b805b12012-04-18 14:23:14 -07001145 canvas.clipRect(getScrollX(), getScrollY(), getScrollX() + getRight() - getLeft(),
1146 getScrollY() + getBottom() - getTop());
Michael Jurka0142d492010-08-25 17:46:15 -07001147
Adam Cohen7d30a372013-07-01 17:03:59 -07001148 // Draw all the children, leaving the drag view for last
1149 for (int i = pageCount - 1; i >= 0; i--) {
Michael Jurka80c69852011-12-16 14:16:32 -08001150 final View v = getPageAt(i);
Adam Cohen7d30a372013-07-01 17:03:59 -07001151 if (v == mDragView) continue;
Michael Jurka5e368ff2012-05-14 23:13:15 -07001152 if (mForceDrawAllChildrenNextFrame ||
1153 (leftScreen <= i && i <= rightScreen && shouldDrawChild(v))) {
Michael Jurka80c69852011-12-16 14:16:32 -08001154 drawChild(canvas, v, drawingTime);
Michael Jurka80c69852011-12-16 14:16:32 -08001155 }
Winson Chungc6f10b92011-11-14 11:39:07 -08001156 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001157 // Draw the drag view on top (if there is one)
1158 if (mDragView != null) {
1159 drawChild(canvas, mDragView, drawingTime);
1160 }
1161
Michael Jurka5e368ff2012-05-14 23:13:15 -07001162 mForceDrawAllChildrenNextFrame = false;
Winson Chungc6f10b92011-11-14 11:39:07 -08001163 canvas.restore();
Michael Jurkac4fb9172010-09-02 17:19:20 -07001164 }
Michael Jurka0142d492010-08-25 17:46:15 -07001165 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001166 }
1167
1168 @Override
1169 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
Adam Cohenae4f1552011-10-20 00:15:42 -07001170 int page = indexToPage(indexOfChild(child));
Winson Chung86f77532010-08-24 11:08:22 -07001171 if (page != mCurrentPage || !mScroller.isFinished()) {
1172 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001173 return true;
1174 }
1175 return false;
1176 }
1177
1178 @Override
1179 protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
Winson Chung86f77532010-08-24 11:08:22 -07001180 int focusablePage;
1181 if (mNextPage != INVALID_PAGE) {
1182 focusablePage = mNextPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001183 } else {
Winson Chung86f77532010-08-24 11:08:22 -07001184 focusablePage = mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001185 }
Winson Chung86f77532010-08-24 11:08:22 -07001186 View v = getPageAt(focusablePage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001187 if (v != null) {
Adam Cohen76fc0852011-06-17 13:26:23 -07001188 return v.requestFocus(direction, previouslyFocusedRect);
Winson Chung321e9ee2010-08-09 13:37:56 -07001189 }
1190 return false;
1191 }
1192
1193 @Override
1194 public boolean dispatchUnhandledMove(View focused, int direction) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001195 // XXX-RTL: This will be fixed in a future CL
Winson Chung321e9ee2010-08-09 13:37:56 -07001196 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001197 if (getCurrentPage() > 0) {
1198 snapToPage(getCurrentPage() - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001199 return true;
1200 }
1201 } else if (direction == View.FOCUS_RIGHT) {
Winson Chung86f77532010-08-24 11:08:22 -07001202 if (getCurrentPage() < getPageCount() - 1) {
1203 snapToPage(getCurrentPage() + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001204 return true;
1205 }
1206 }
1207 return super.dispatchUnhandledMove(focused, direction);
1208 }
1209
1210 @Override
1211 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001212 // XXX-RTL: This will be fixed in a future CL
Winson Chung86f77532010-08-24 11:08:22 -07001213 if (mCurrentPage >= 0 && mCurrentPage < getPageCount()) {
alanvaf519952012-05-07 17:33:22 -07001214 getPageAt(mCurrentPage).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001215 }
1216 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001217 if (mCurrentPage > 0) {
alanvaf519952012-05-07 17:33:22 -07001218 getPageAt(mCurrentPage - 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001219 }
1220 } else if (direction == View.FOCUS_RIGHT){
Winson Chung86f77532010-08-24 11:08:22 -07001221 if (mCurrentPage < getPageCount() - 1) {
alanvaf519952012-05-07 17:33:22 -07001222 getPageAt(mCurrentPage + 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001223 }
1224 }
1225 }
1226
1227 /**
1228 * If one of our descendant views decides that it could be focused now, only
Winson Chung86f77532010-08-24 11:08:22 -07001229 * pass that along if it's on the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001230 *
Winson Chung86f77532010-08-24 11:08:22 -07001231 * This happens when live folders requery, and if they're off page, they
1232 * end up calling requestFocus, which pulls it on page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001233 */
1234 @Override
1235 public void focusableViewAvailable(View focused) {
Winson Chung86f77532010-08-24 11:08:22 -07001236 View current = getPageAt(mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001237 View v = focused;
1238 while (true) {
1239 if (v == current) {
1240 super.focusableViewAvailable(focused);
1241 return;
1242 }
1243 if (v == this) {
1244 return;
1245 }
1246 ViewParent parent = v.getParent();
1247 if (parent instanceof View) {
1248 v = (View)v.getParent();
1249 } else {
1250 return;
1251 }
1252 }
1253 }
1254
1255 /**
1256 * {@inheritDoc}
1257 */
1258 @Override
1259 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
1260 if (disallowIntercept) {
1261 // We need to make sure to cancel our long press if
1262 // a scrollable widget takes over touch events
Adam Cohen22f823d2011-09-01 17:22:18 -07001263 final View currentPage = getPageAt(mCurrentPage);
Winson Chung86f77532010-08-24 11:08:22 -07001264 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001265 }
1266 super.requestDisallowInterceptTouchEvent(disallowIntercept);
1267 }
1268
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001269 /**
1270 * Return true if a tap at (x, y) should trigger a flip to the previous page.
1271 */
1272 protected boolean hitsPreviousPage(float x, float y) {
Adam Cohenedb40762013-07-18 16:45:45 -07001273 int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2;
Adam Cohen0ffac432013-07-10 11:19:26 -07001274 if (isLayoutRtl()) {
1275 return (x > (getViewportOffsetX() + getViewportWidth() -
Adam Cohen0cd0eba2013-10-28 14:22:25 -07001276 offset));
Adam Cohen0ffac432013-07-10 11:19:26 -07001277 }
Adam Cohen0cd0eba2013-10-28 14:22:25 -07001278 return (x < getViewportOffsetX() + offset);
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001279 }
1280
1281 /**
1282 * Return true if a tap at (x, y) should trigger a flip to the next page.
1283 */
1284 protected boolean hitsNextPage(float x, float y) {
Adam Cohenedb40762013-07-18 16:45:45 -07001285 int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2;
Adam Cohen0ffac432013-07-10 11:19:26 -07001286 if (isLayoutRtl()) {
Adam Cohen0cd0eba2013-10-28 14:22:25 -07001287 return (x < getViewportOffsetX() + offset);
Adam Cohen0ffac432013-07-10 11:19:26 -07001288 }
1289 return (x > (getViewportOffsetX() + getViewportWidth() -
Adam Cohen0cd0eba2013-10-28 14:22:25 -07001290 offset));
Adam Cohen7d30a372013-07-01 17:03:59 -07001291 }
Winson Chung52aee602013-01-30 12:01:02 -08001292
Adam Cohen7d30a372013-07-01 17:03:59 -07001293 /** Returns whether x and y originated within the buffered viewport */
1294 private boolean isTouchPointInViewportWithBuffer(int x, int y) {
1295 mTmpRect.set(mViewport.left - mViewport.width() / 2, mViewport.top,
1296 mViewport.right + mViewport.width() / 2, mViewport.bottom);
1297 return mTmpRect.contains(x, y);
1298 }
1299
Winson Chung321e9ee2010-08-09 13:37:56 -07001300 @Override
1301 public boolean onInterceptTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001302 if (DISABLE_TOUCH_INTERACTION) {
1303 return false;
1304 }
1305
Winson Chung321e9ee2010-08-09 13:37:56 -07001306 /*
1307 * This method JUST determines whether we want to intercept the motion.
1308 * If we return true, onTouchEvent will be called and we do the actual
1309 * scrolling there.
1310 */
Adam Cohen6342bba2011-03-10 11:33:35 -08001311 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001312
Winson Chung45e1d6e2010-11-09 17:19:49 -08001313 // Skip touch handling if there are no pages to swipe
1314 if (getChildCount() <= 0) return super.onInterceptTouchEvent(ev);
1315
Winson Chung321e9ee2010-08-09 13:37:56 -07001316 /*
1317 * Shortcut the most recurring case: the user is in the dragging
1318 * state and he is moving his finger. We want to intercept this
1319 * motion.
1320 */
1321 final int action = ev.getAction();
1322 if ((action == MotionEvent.ACTION_MOVE) &&
1323 (mTouchState == TOUCH_STATE_SCROLLING)) {
1324 return true;
1325 }
1326
Winson Chung321e9ee2010-08-09 13:37:56 -07001327 switch (action & MotionEvent.ACTION_MASK) {
1328 case MotionEvent.ACTION_MOVE: {
1329 /*
1330 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
1331 * whether the user has moved far enough from his original down touch.
1332 */
Michael Jurka1ff706b2010-09-14 17:35:20 -07001333 if (mActivePointerId != INVALID_POINTER) {
1334 determineScrollingStart(ev);
Michael Jurka1ff706b2010-09-14 17:35:20 -07001335 }
1336 // if mActivePointerId is INVALID_POINTER, then we must have missed an ACTION_DOWN
1337 // event. in that case, treat the first occurence of a move event as a ACTION_DOWN
1338 // i.e. fall through to the next case (don't break)
1339 // (We sometimes miss ACTION_DOWN events in Workspace because it ignores all events
1340 // while it's small- this was causing a crash before we checked for INVALID_POINTER)
Adam Cohen93c97562013-09-26 13:48:01 -07001341 break;
Winson Chung321e9ee2010-08-09 13:37:56 -07001342 }
1343
1344 case MotionEvent.ACTION_DOWN: {
1345 final float x = ev.getX();
1346 final float y = ev.getY();
1347 // Remember location of down touch
1348 mDownMotionX = x;
Adam Cohen7d30a372013-07-01 17:03:59 -07001349 mDownMotionY = y;
1350 mDownScrollX = getScrollX();
Winson Chung321e9ee2010-08-09 13:37:56 -07001351 mLastMotionX = x;
1352 mLastMotionY = y;
Adam Cohen7d30a372013-07-01 17:03:59 -07001353 float[] p = mapPointFromViewToParent(this, x, y);
1354 mParentDownMotionX = p[0];
1355 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001356 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001357 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001358 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001359
Winson Chung321e9ee2010-08-09 13:37:56 -07001360 /*
1361 * If being flinged and user touches the screen, initiate drag;
1362 * otherwise don't. mScroller.isFinished should be false when
1363 * being flinged.
1364 */
Michael Jurkafd177c12010-10-19 15:50:43 -07001365 final int xDist = Math.abs(mScroller.getFinalX() - mScroller.getCurrX());
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001366 final boolean finishedScrolling = (mScroller.isFinished() || xDist < mTouchSlop);
1367 if (finishedScrolling) {
1368 mTouchState = TOUCH_STATE_REST;
1369 mScroller.abortAnimation();
1370 } else {
Adam Cohen7d30a372013-07-01 17:03:59 -07001371 if (isTouchPointInViewportWithBuffer((int) mDownMotionX, (int) mDownMotionY)) {
1372 mTouchState = TOUCH_STATE_SCROLLING;
1373 } else {
1374 mTouchState = TOUCH_STATE_REST;
1375 }
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001376 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001377
Winson Chung86f77532010-08-24 11:08:22 -07001378 // check if this can be the beginning of a tap on the side of the pages
Winson Chung321e9ee2010-08-09 13:37:56 -07001379 // to scroll the current page
Adam Cohen7d30a372013-07-01 17:03:59 -07001380 if (!DISABLE_TOUCH_SIDE_PAGES) {
1381 if (mTouchState != TOUCH_STATE_PREV_PAGE && mTouchState != TOUCH_STATE_NEXT_PAGE) {
1382 if (getChildCount() > 0) {
1383 if (hitsPreviousPage(x, y)) {
1384 mTouchState = TOUCH_STATE_PREV_PAGE;
1385 } else if (hitsNextPage(x, y)) {
1386 mTouchState = TOUCH_STATE_NEXT_PAGE;
1387 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001388 }
1389 }
1390 }
1391 break;
1392 }
1393
Winson Chung321e9ee2010-08-09 13:37:56 -07001394 case MotionEvent.ACTION_UP:
Jeff Brown1d0867c2010-12-02 18:27:39 -08001395 case MotionEvent.ACTION_CANCEL:
Adam Cohen7d30a372013-07-01 17:03:59 -07001396 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001397 break;
1398
1399 case MotionEvent.ACTION_POINTER_UP:
1400 onSecondaryPointerUp(ev);
Adam Cohen6342bba2011-03-10 11:33:35 -08001401 releaseVelocityTracker();
Winson Chung321e9ee2010-08-09 13:37:56 -07001402 break;
1403 }
1404
1405 /*
1406 * The only time we want to intercept motion events is if we are in the
1407 * drag mode.
1408 */
1409 return mTouchState != TOUCH_STATE_REST;
1410 }
1411
Adam Cohenf8d28232011-02-01 21:47:00 -08001412 protected void determineScrollingStart(MotionEvent ev) {
1413 determineScrollingStart(ev, 1.0f);
1414 }
1415
Winson Chung321e9ee2010-08-09 13:37:56 -07001416 /*
1417 * Determines if we should change the touch state to start scrolling after the
1418 * user moves their touch point too far.
1419 */
Adam Cohenf8d28232011-02-01 21:47:00 -08001420 protected void determineScrollingStart(MotionEvent ev, float touchSlopScale) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001421 // Disallow scrolling if we don't have a valid pointer index
Winson Chung321e9ee2010-08-09 13:37:56 -07001422 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001423 if (pointerIndex == -1) return;
1424
1425 // Disallow scrolling if we started the gesture from outside the viewport
Winson Chung321e9ee2010-08-09 13:37:56 -07001426 final float x = ev.getX(pointerIndex);
1427 final float y = ev.getY(pointerIndex);
Adam Cohen7d30a372013-07-01 17:03:59 -07001428 if (!isTouchPointInViewportWithBuffer((int) x, (int) y)) return;
1429
Winson Chung321e9ee2010-08-09 13:37:56 -07001430 final int xDiff = (int) Math.abs(x - mLastMotionX);
1431 final int yDiff = (int) Math.abs(y - mLastMotionY);
1432
Adam Cohenf8d28232011-02-01 21:47:00 -08001433 final int touchSlop = Math.round(touchSlopScale * mTouchSlop);
Winson Chung321e9ee2010-08-09 13:37:56 -07001434 boolean xPaged = xDiff > mPagingTouchSlop;
1435 boolean xMoved = xDiff > touchSlop;
1436 boolean yMoved = yDiff > touchSlop;
1437
Adam Cohenf8d28232011-02-01 21:47:00 -08001438 if (xMoved || xPaged || yMoved) {
Michael Jurka0142d492010-08-25 17:46:15 -07001439 if (mUsePagingTouchSlop ? xPaged : xMoved) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001440 // Scroll if the user moved far enough along the X axis
1441 mTouchState = TOUCH_STATE_SCROLLING;
Adam Cohen6342bba2011-03-10 11:33:35 -08001442 mTotalMotionX += Math.abs(mLastMotionX - x);
Winson Chung321e9ee2010-08-09 13:37:56 -07001443 mLastMotionX = x;
Winson Chungc0844aa2011-02-02 15:25:58 -08001444 mLastMotionXRemainder = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -07001445 mTouchX = getViewportOffsetX() + getScrollX();
Michael Jurka0142d492010-08-25 17:46:15 -07001446 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1447 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07001448 }
Adam Cohenf8d28232011-02-01 21:47:00 -08001449 }
1450 }
1451
Adam Cohen7d30a372013-07-01 17:03:59 -07001452 protected float getMaxScrollProgress() {
1453 return 1.0f;
1454 }
1455
Adam Cohenf8d28232011-02-01 21:47:00 -08001456 protected void cancelCurrentPageLongPress() {
1457 if (mAllowLongPress) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001458 //mAllowLongPress = false;
Adam Cohenf8d28232011-02-01 21:47:00 -08001459 // Try canceling the long press. It could also have been scheduled
1460 // by a distant descendant, so use the mAllowLongPress flag to block
1461 // everything
1462 final View currentPage = getPageAt(mCurrentPage);
1463 if (currentPage != null) {
1464 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001465 }
1466 }
1467 }
1468
Adam Cohen7d30a372013-07-01 17:03:59 -07001469 protected float getBoundedScrollProgress(int screenCenter, View v, int page) {
1470 final int halfScreenSize = getViewportWidth() / 2;
1471
1472 screenCenter = Math.min(getScrollX() + halfScreenSize, screenCenter);
1473 screenCenter = Math.max(halfScreenSize, screenCenter);
1474
1475 return getScrollProgress(screenCenter, v, page);
1476 }
1477
Adam Cohenb5ba0972011-09-07 18:02:31 -07001478 protected float getScrollProgress(int screenCenter, View v, int page) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001479 final int halfScreenSize = getViewportWidth() / 2;
Adam Cohenb5ba0972011-09-07 18:02:31 -07001480
Adam Cohen0cd0eba2013-10-28 14:22:25 -07001481 int offset = (getViewportWidth() - getChildWidth(page)) / 2;
1482 int totalDistance = v.getMeasuredWidth() + offset;
Adam Cohenedb40762013-07-18 16:45:45 -07001483 int delta = screenCenter - (getScrollForPage(page) + halfScreenSize);
Adam Cohenb5ba0972011-09-07 18:02:31 -07001484
1485 float scrollProgress = delta / (totalDistance * 1.0f);
Adam Cohen7d30a372013-07-01 17:03:59 -07001486 scrollProgress = Math.min(scrollProgress, getMaxScrollProgress());
1487 scrollProgress = Math.max(scrollProgress, - getMaxScrollProgress());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001488 return scrollProgress;
1489 }
1490
Adam Cohenedb40762013-07-18 16:45:45 -07001491 public int getScrollForPage(int index) {
Adam Cohen1f1f45d2013-10-02 09:40:18 -07001492 if (mPageScrolls == null || index >= mPageScrolls.length || index < 0) {
Adam Cohenedb40762013-07-18 16:45:45 -07001493 return 0;
1494 } else {
1495 return mPageScrolls[index];
1496 }
1497 }
1498
Adam Cohen564a2e72013-10-09 14:47:32 -07001499 // While layout transitions are occurring, a child's position may stray from its baseline
1500 // position. This method returns the magnitude of this stray at any given time.
1501 public int getLayoutTransitionOffsetForPage(int index) {
1502 if (mPageScrolls == null || index >= mPageScrolls.length || index < 0) {
1503 return 0;
1504 } else {
1505 View child = getChildAt(index);
1506 int scrollOffset = (getViewportWidth() - child.getMeasuredWidth()) / 2;
1507 int baselineX = mPageScrolls[index] + scrollOffset + getViewportOffsetX();
1508 return (int) (child.getX() - baselineX);
1509 }
1510 }
1511
Adam Cohene0f66b52010-11-23 15:06:07 -08001512 // This curve determines how the effect of scrolling over the limits of the page dimishes
1513 // as the user pulls further and further from the bounds
1514 private float overScrollInfluenceCurve(float f) {
1515 f -= 1.0f;
1516 return f * f * f + 1.0f;
1517 }
1518
Adam Cohenb5ba0972011-09-07 18:02:31 -07001519 protected void acceleratedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001520 int screenSize = getViewportWidth();
Adam Cohenb5ba0972011-09-07 18:02:31 -07001521
1522 // We want to reach the max over scroll effect when the user has
1523 // over scrolled half the size of the screen
1524 float f = OVERSCROLL_ACCELERATE_FACTOR * (amount / screenSize);
1525
1526 if (f == 0) return;
1527
1528 // Clamp this factor, f, to -1 < f < 1
1529 if (Math.abs(f) >= 1) {
1530 f /= Math.abs(f);
1531 }
1532
1533 int overScrollAmount = (int) Math.round(f * screenSize);
1534 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001535 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001536 super.scrollTo(0, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001537 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001538 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001539 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001540 }
1541 invalidate();
1542 }
1543
1544 protected void dampedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001545 int screenSize = getViewportWidth();
Adam Cohene0f66b52010-11-23 15:06:07 -08001546
1547 float f = (amount / screenSize);
1548
1549 if (f == 0) return;
1550 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1551
Adam Cohen7bfc9792011-01-28 13:52:37 -08001552 // Clamp this factor, f, to -1 < f < 1
1553 if (Math.abs(f) >= 1) {
1554 f /= Math.abs(f);
1555 }
1556
Adam Cohene0f66b52010-11-23 15:06:07 -08001557 int overScrollAmount = (int) Math.round(OVERSCROLL_DAMP_FACTOR * f * screenSize);
Adam Cohen68d73932010-11-15 10:50:58 -08001558 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001559 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001560 super.scrollTo(0, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001561 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001562 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001563 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001564 }
1565 invalidate();
1566 }
1567
Adam Cohenb5ba0972011-09-07 18:02:31 -07001568 protected void overScroll(float amount) {
1569 dampedOverScroll(amount);
1570 }
1571
Michael Jurkac5b262c2011-01-12 20:24:50 -08001572 protected float maxOverScroll() {
1573 // Using the formula in overScroll, assuming that f = 1.0 (which it should generally not
Adam Cohenb5ba0972011-09-07 18:02:31 -07001574 // exceed). Used to find out how much extra wallpaper we need for the over scroll effect
Michael Jurkac5b262c2011-01-12 20:24:50 -08001575 float f = 1.0f;
1576 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1577 return OVERSCROLL_DAMP_FACTOR * f;
1578 }
1579
Adam Cohenf358a4b2013-07-23 16:47:31 -07001580 protected void enableFreeScroll() {
1581 setEnableFreeScroll(true, -1);
1582 }
1583
1584 protected void disableFreeScroll(int snapPage) {
1585 setEnableFreeScroll(false, snapPage);
1586 }
1587
Adam Cohen7a9e58a2013-10-01 18:02:13 -07001588 void updateFreescrollBounds() {
1589 getOverviewModePages(mTempVisiblePagesRange);
1590 if (isLayoutRtl()) {
1591 mFreeScrollMinScrollX = getScrollForPage(mTempVisiblePagesRange[1]);
1592 mFreeScrollMaxScrollX = getScrollForPage(mTempVisiblePagesRange[0]);
1593 } else {
1594 mFreeScrollMinScrollX = getScrollForPage(mTempVisiblePagesRange[0]);
1595 mFreeScrollMaxScrollX = getScrollForPage(mTempVisiblePagesRange[1]);
1596 }
1597 }
1598
Adam Cohenf358a4b2013-07-23 16:47:31 -07001599 private void setEnableFreeScroll(boolean freeScroll, int snapPage) {
1600 mFreeScroll = freeScroll;
1601
1602 if (snapPage == -1) {
1603 snapPage = getPageNearestToCenterOfScreen();
1604 }
1605
Adam Cohenf358a4b2013-07-23 16:47:31 -07001606 if (!mFreeScroll) {
1607 snapToPage(snapPage);
Adam Cohenf358a4b2013-07-23 16:47:31 -07001608 } else {
Adam Cohen7a9e58a2013-10-01 18:02:13 -07001609 updateFreescrollBounds();
1610 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohenf358a4b2013-07-23 16:47:31 -07001611 if (getCurrentPage() < mTempVisiblePagesRange[0]) {
1612 setCurrentPage(mTempVisiblePagesRange[0]);
1613 } else if (getCurrentPage() > mTempVisiblePagesRange[1]) {
1614 setCurrentPage(mTempVisiblePagesRange[1]);
1615 }
1616 }
1617
1618 setEnableOverscroll(!freeScroll);
1619 }
1620
1621 private void setEnableOverscroll(boolean enable) {
1622 mAllowOverScroll = enable;
1623 }
1624
1625 int getNearestHoverOverPageIndex() {
1626 if (mDragView != null) {
1627 int dragX = (int) (mDragView.getLeft() + (mDragView.getMeasuredWidth() / 2)
1628 + mDragView.getTranslationX());
1629 getOverviewModePages(mTempVisiblePagesRange);
1630 int minDistance = Integer.MAX_VALUE;
1631 int minIndex = indexOfChild(mDragView);
1632 for (int i = mTempVisiblePagesRange[0]; i <= mTempVisiblePagesRange[1]; i++) {
1633 View page = getPageAt(i);
1634 int pageX = (int) (page.getLeft() + page.getMeasuredWidth() / 2);
1635 int d = Math.abs(dragX - pageX);
1636 if (d < minDistance) {
1637 minIndex = i;
1638 minDistance = d;
1639 }
1640 }
1641 return minIndex;
1642 }
1643 return -1;
1644 }
1645
Winson Chung321e9ee2010-08-09 13:37:56 -07001646 @Override
1647 public boolean onTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001648 if (DISABLE_TOUCH_INTERACTION) {
1649 return false;
1650 }
1651
Adam Cohen1697b792013-09-17 19:08:21 -07001652 super.onTouchEvent(ev);
1653
Winson Chung45e1d6e2010-11-09 17:19:49 -08001654 // Skip touch handling if there are no pages to swipe
1655 if (getChildCount() <= 0) return super.onTouchEvent(ev);
1656
Michael Jurkab8f06722010-10-10 15:58:46 -07001657 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001658
1659 final int action = ev.getAction();
1660
1661 switch (action & MotionEvent.ACTION_MASK) {
1662 case MotionEvent.ACTION_DOWN:
1663 /*
1664 * If being flinged and user touches, stop the fling. isFinished
1665 * will be false if being flinged.
1666 */
1667 if (!mScroller.isFinished()) {
1668 mScroller.abortAnimation();
1669 }
1670
1671 // Remember where the motion event started
1672 mDownMotionX = mLastMotionX = ev.getX();
Adam Cohen7d30a372013-07-01 17:03:59 -07001673 mDownMotionY = mLastMotionY = ev.getY();
1674 mDownScrollX = getScrollX();
1675 float[] p = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1676 mParentDownMotionX = p[0];
1677 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001678 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001679 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001680 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001681
Michael Jurka0142d492010-08-25 17:46:15 -07001682 if (mTouchState == TOUCH_STATE_SCROLLING) {
1683 pageBeginMoving();
1684 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001685 break;
1686
1687 case MotionEvent.ACTION_MOVE:
1688 if (mTouchState == TOUCH_STATE_SCROLLING) {
1689 // Scroll to follow the motion event
1690 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001691
1692 if (pointerIndex == -1) return true;
1693
Winson Chung321e9ee2010-08-09 13:37:56 -07001694 final float x = ev.getX(pointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001695 final float deltaX = mLastMotionX + mLastMotionXRemainder - x;
Winson Chung321e9ee2010-08-09 13:37:56 -07001696
Adam Cohenaefd4e12011-02-14 16:39:38 -08001697 mTotalMotionX += Math.abs(deltaX);
1698
Winson Chungc0844aa2011-02-02 15:25:58 -08001699 // Only scroll and update mLastMotionX if we have moved some discrete amount. We
1700 // keep the remainder because we are actually testing if we've moved from the last
1701 // scrolled position (which is discrete).
1702 if (Math.abs(deltaX) >= 1.0f) {
Adam Cohen68d73932010-11-15 10:50:58 -08001703 mTouchX += deltaX;
1704 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1705 if (!mDeferScrollUpdate) {
Winson Chungc0844aa2011-02-02 15:25:58 -08001706 scrollBy((int) deltaX, 0);
Winson Chung785d2eb2011-04-14 16:08:02 -07001707 if (DEBUG) Log.d(TAG, "onTouchEvent().Scrolling: " + deltaX);
Adam Cohen68d73932010-11-15 10:50:58 -08001708 } else {
1709 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001710 }
Winson Chungc0844aa2011-02-02 15:25:58 -08001711 mLastMotionX = x;
1712 mLastMotionXRemainder = deltaX - (int) deltaX;
Winson Chung321e9ee2010-08-09 13:37:56 -07001713 } else {
1714 awakenScrollBars();
1715 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001716 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1717 // Update the last motion position
1718 mLastMotionX = ev.getX();
1719 mLastMotionY = ev.getY();
1720
1721 // Update the parent down so that our zoom animations take this new movement into
1722 // account
1723 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1724 mParentDownMotionX = pt[0];
1725 mParentDownMotionY = pt[1];
1726 updateDragViewTranslationDuringDrag();
1727
1728 // Find the closest page to the touch point
1729 final int dragViewIndex = indexOfChild(mDragView);
Adam Cohen7d30a372013-07-01 17:03:59 -07001730
1731 // Change the drag view if we are hovering over the drop target
1732 boolean isHoveringOverDelete = isHoveringOverDeleteDropTarget(
1733 (int) mParentDownMotionX, (int) mParentDownMotionY);
1734 setPageHoveringOverDeleteDropTarget(dragViewIndex, isHoveringOverDelete);
1735
Adam Cohen7d30a372013-07-01 17:03:59 -07001736 if (DEBUG) Log.d(TAG, "mLastMotionX: " + mLastMotionX);
1737 if (DEBUG) Log.d(TAG, "mLastMotionY: " + mLastMotionY);
1738 if (DEBUG) Log.d(TAG, "mParentDownMotionX: " + mParentDownMotionX);
1739 if (DEBUG) Log.d(TAG, "mParentDownMotionY: " + mParentDownMotionY);
1740
Adam Cohenf358a4b2013-07-23 16:47:31 -07001741 final int pageUnderPointIndex = getNearestHoverOverPageIndex();
1742 if (pageUnderPointIndex > -1 && pageUnderPointIndex != indexOfChild(mDragView) &&
1743 !isHoveringOverDelete) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001744 mTempVisiblePagesRange[0] = 0;
1745 mTempVisiblePagesRange[1] = getPageCount() - 1;
Adam Cohenf358a4b2013-07-23 16:47:31 -07001746 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07001747 if (mTempVisiblePagesRange[0] <= pageUnderPointIndex &&
1748 pageUnderPointIndex <= mTempVisiblePagesRange[1] &&
1749 pageUnderPointIndex != mSidePageHoverIndex && mScroller.isFinished()) {
1750 mSidePageHoverIndex = pageUnderPointIndex;
1751 mSidePageHoverRunnable = new Runnable() {
1752 @Override
1753 public void run() {
Adam Cohen7d30a372013-07-01 17:03:59 -07001754 // Setup the scroll to the correct page before we swap the views
1755 snapToPage(pageUnderPointIndex);
1756
1757 // For each of the pages between the paged view and the drag view,
1758 // animate them from the previous position to the new position in
1759 // the layout (as a result of the drag view moving in the layout)
1760 int shiftDelta = (dragViewIndex < pageUnderPointIndex) ? -1 : 1;
1761 int lowerIndex = (dragViewIndex < pageUnderPointIndex) ?
1762 dragViewIndex + 1 : pageUnderPointIndex;
1763 int upperIndex = (dragViewIndex > pageUnderPointIndex) ?
1764 dragViewIndex - 1 : pageUnderPointIndex;
1765 for (int i = lowerIndex; i <= upperIndex; ++i) {
1766 View v = getChildAt(i);
1767 // dragViewIndex < pageUnderPointIndex, so after we remove the
1768 // drag view all subsequent views to pageUnderPointIndex will
1769 // shift down.
1770 int oldX = getViewportOffsetX() + getChildOffset(i);
1771 int newX = getViewportOffsetX() + getChildOffset(i + shiftDelta);
1772
1773 // Animate the view translation from its old position to its new
1774 // position
1775 AnimatorSet anim = (AnimatorSet) v.getTag(ANIM_TAG_KEY);
1776 if (anim != null) {
1777 anim.cancel();
1778 }
1779
1780 v.setTranslationX(oldX - newX);
1781 anim = new AnimatorSet();
1782 anim.setDuration(REORDERING_REORDER_REPOSITION_DURATION);
1783 anim.playTogether(
1784 ObjectAnimator.ofFloat(v, "translationX", 0f));
1785 anim.start();
1786 v.setTag(anim);
1787 }
1788
1789 removeView(mDragView);
1790 onRemoveView(mDragView, false);
1791 addView(mDragView, pageUnderPointIndex);
1792 onAddView(mDragView, pageUnderPointIndex);
1793 mSidePageHoverIndex = -1;
Winson Chungd2be3812013-07-16 11:11:32 -07001794 mPageIndicator.setActiveMarker(getNextPage());
Adam Cohen7d30a372013-07-01 17:03:59 -07001795 }
1796 };
1797 postDelayed(mSidePageHoverRunnable, REORDERING_SIDE_PAGE_HOVER_TIMEOUT);
1798 }
1799 } else {
1800 removeCallbacks(mSidePageHoverRunnable);
1801 mSidePageHoverIndex = -1;
1802 }
Adam Cohen564976a2010-10-13 18:52:07 -07001803 } else {
Winson Chung321e9ee2010-08-09 13:37:56 -07001804 determineScrollingStart(ev);
1805 }
1806 break;
1807
1808 case MotionEvent.ACTION_UP:
1809 if (mTouchState == TOUCH_STATE_SCROLLING) {
1810 final int activePointerId = mActivePointerId;
1811 final int pointerIndex = ev.findPointerIndex(activePointerId);
1812 final float x = ev.getX(pointerIndex);
1813 final VelocityTracker velocityTracker = mVelocityTracker;
1814 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
1815 int velocityX = (int) velocityTracker.getXVelocity(activePointerId);
Winson Chung9cfd25f2010-10-24 16:09:28 -07001816 final int deltaX = (int) (x - mDownMotionX);
Adam Cohen96d30a12013-07-16 18:13:21 -07001817 final int pageWidth = getPageAt(mCurrentPage).getMeasuredWidth();
Adam Cohen00481b32011-11-18 12:03:48 -08001818 boolean isSignificantMove = Math.abs(deltaX) > pageWidth *
1819 SIGNIFICANT_MOVE_THRESHOLD;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001820
Adam Cohenb64cb5a2011-02-15 13:53:42 -08001821 mTotalMotionX += Math.abs(mLastMotionX + mLastMotionXRemainder - x);
1822
Adam Cohen00481b32011-11-18 12:03:48 -08001823 boolean isFling = mTotalMotionX > MIN_LENGTH_FOR_FLING &&
Adam Cohen265b9a62011-12-07 14:37:18 -08001824 Math.abs(velocityX) > mFlingThresholdVelocity;
Adam Cohen00481b32011-11-18 12:03:48 -08001825
Adam Cohenf358a4b2013-07-23 16:47:31 -07001826 if (!mFreeScroll) {
1827 // In the case that the page is moved far to one direction and then is flung
1828 // in the opposite direction, we use a threshold to determine whether we should
1829 // just return to the starting page, or if we should skip one further.
1830 boolean returnToOriginalPage = false;
1831 if (Math.abs(deltaX) > pageWidth * RETURN_TO_ORIGINAL_PAGE_THRESHOLD &&
1832 Math.signum(velocityX) != Math.signum(deltaX) && isFling) {
1833 returnToOriginalPage = true;
1834 }
Adam Cohenaefd4e12011-02-14 16:39:38 -08001835
Adam Cohenf358a4b2013-07-23 16:47:31 -07001836 int finalPage;
1837 // We give flings precedence over large moves, which is why we short-circuit our
1838 // test for a large move if a fling has been registered. That is, a large
1839 // move to the left and fling to the right will register as a fling to the right.
1840 final boolean isRtl = isLayoutRtl();
1841 boolean isDeltaXLeft = isRtl ? deltaX > 0 : deltaX < 0;
1842 boolean isVelocityXLeft = isRtl ? velocityX > 0 : velocityX < 0;
1843 if (((isSignificantMove && !isDeltaXLeft && !isFling) ||
1844 (isFling && !isVelocityXLeft)) && mCurrentPage > 0) {
1845 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage - 1;
1846 snapToPageWithVelocity(finalPage, velocityX);
1847 } else if (((isSignificantMove && isDeltaXLeft && !isFling) ||
1848 (isFling && isVelocityXLeft)) &&
1849 mCurrentPage < getChildCount() - 1) {
1850 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage + 1;
1851 snapToPageWithVelocity(finalPage, velocityX);
1852 } else {
1853 snapToDestination();
1854 } } else if (mTouchState == TOUCH_STATE_PREV_PAGE) {
1855 // at this point we have not moved beyond the touch slop
1856 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1857 // we can just page
1858 int nextPage = Math.max(0, mCurrentPage - 1);
1859 if (nextPage != mCurrentPage) {
1860 snapToPage(nextPage);
1861 } else {
1862 snapToDestination();
1863 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001864 } else {
Adam Cohenf358a4b2013-07-23 16:47:31 -07001865 if (!mScroller.isFinished()) {
1866 mScroller.abortAnimation();
1867 }
1868
1869 float scaleX = getScaleX();
1870 int vX = (int) (-velocityX * scaleX);
1871 int initialScrollX = (int) (getScrollX() * scaleX);
1872
1873 mScroller.fling(initialScrollX,
1874 getScrollY(), vX, 0, Integer.MIN_VALUE, Integer.MAX_VALUE, 0, 0);
1875 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001876 }
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001877 } else if (mTouchState == TOUCH_STATE_NEXT_PAGE) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001878 // at this point we have not moved beyond the touch slop
1879 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1880 // we can just page
Winson Chung86f77532010-08-24 11:08:22 -07001881 int nextPage = Math.min(getChildCount() - 1, mCurrentPage + 1);
1882 if (nextPage != mCurrentPage) {
1883 snapToPage(nextPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001884 } else {
1885 snapToDestination();
1886 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001887 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1888 // Update the last motion position
1889 mLastMotionX = ev.getX();
1890 mLastMotionY = ev.getY();
1891
1892 // Update the parent down so that our zoom animations take this new movement into
1893 // account
1894 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1895 mParentDownMotionX = pt[0];
1896 mParentDownMotionY = pt[1];
1897 updateDragViewTranslationDuringDrag();
1898 boolean handledFling = false;
1899 if (!DISABLE_FLING_TO_DELETE) {
1900 // Check the velocity and see if we are flinging-to-delete
1901 PointF flingToDeleteVector = isFlingingToDelete();
1902 if (flingToDeleteVector != null) {
1903 onFlingToDelete(flingToDeleteVector);
1904 handledFling = true;
1905 }
1906 }
1907 if (!handledFling && isHoveringOverDeleteDropTarget((int) mParentDownMotionX,
1908 (int) mParentDownMotionY)) {
1909 onDropToDelete();
1910 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001911 } else {
Adam Cohendbdff6b2013-09-18 19:09:15 -07001912 if (!mCancelTap) {
1913 onUnhandledTap(ev);
1914 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001915 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001916
1917 // Remove the callback to wait for the side page hover timeout
1918 removeCallbacks(mSidePageHoverRunnable);
1919 // End any intermediate reordering states
1920 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001921 break;
1922
1923 case MotionEvent.ACTION_CANCEL:
Michael Jurkab8f06722010-10-10 15:58:46 -07001924 if (mTouchState == TOUCH_STATE_SCROLLING) {
1925 snapToDestination();
1926 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001927 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001928 break;
1929
1930 case MotionEvent.ACTION_POINTER_UP:
1931 onSecondaryPointerUp(ev);
Adam Cohenf358a4b2013-07-23 16:47:31 -07001932 releaseVelocityTracker();
Winson Chung321e9ee2010-08-09 13:37:56 -07001933 break;
1934 }
1935
1936 return true;
1937 }
1938
Adam Cohen7d30a372013-07-01 17:03:59 -07001939 public void onFlingToDelete(View v) {}
1940 public void onRemoveView(View v, boolean deletePermanently) {}
1941 public void onRemoveViewAnimationCompleted() {}
1942 public void onAddView(View v, int index) {}
1943
1944 private void resetTouchState() {
1945 releaseVelocityTracker();
1946 endReordering();
Adam Cohendbdff6b2013-09-18 19:09:15 -07001947 mCancelTap = false;
Adam Cohen7d30a372013-07-01 17:03:59 -07001948 mTouchState = TOUCH_STATE_REST;
1949 mActivePointerId = INVALID_POINTER;
Adam Cohen7d30a372013-07-01 17:03:59 -07001950 }
1951
Adam Cohen1697b792013-09-17 19:08:21 -07001952 protected void onUnhandledTap(MotionEvent ev) {
1953 ((Launcher) getContext()).onClick(this);
1954 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001955
Winson Chung185d7162011-02-28 13:47:29 -08001956 @Override
1957 public boolean onGenericMotionEvent(MotionEvent event) {
1958 if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
1959 switch (event.getAction()) {
1960 case MotionEvent.ACTION_SCROLL: {
1961 // Handle mouse (or ext. device) by shifting the page depending on the scroll
1962 final float vscroll;
1963 final float hscroll;
1964 if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) {
1965 vscroll = 0;
1966 hscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1967 } else {
1968 vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1969 hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL);
1970 }
1971 if (hscroll != 0 || vscroll != 0) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001972 boolean isForwardScroll = isLayoutRtl() ? (hscroll < 0 || vscroll < 0)
1973 : (hscroll > 0 || vscroll > 0);
1974 if (isForwardScroll) {
Winson Chung185d7162011-02-28 13:47:29 -08001975 scrollRight();
1976 } else {
1977 scrollLeft();
1978 }
1979 return true;
1980 }
1981 }
1982 }
1983 }
1984 return super.onGenericMotionEvent(event);
1985 }
1986
Michael Jurkab8f06722010-10-10 15:58:46 -07001987 private void acquireVelocityTrackerAndAddMovement(MotionEvent ev) {
1988 if (mVelocityTracker == null) {
1989 mVelocityTracker = VelocityTracker.obtain();
1990 }
1991 mVelocityTracker.addMovement(ev);
1992 }
1993
1994 private void releaseVelocityTracker() {
1995 if (mVelocityTracker != null) {
Adam Cohenf358a4b2013-07-23 16:47:31 -07001996 mVelocityTracker.clear();
Michael Jurkab8f06722010-10-10 15:58:46 -07001997 mVelocityTracker.recycle();
1998 mVelocityTracker = null;
1999 }
2000 }
2001
Winson Chung321e9ee2010-08-09 13:37:56 -07002002 private void onSecondaryPointerUp(MotionEvent ev) {
2003 final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
2004 MotionEvent.ACTION_POINTER_INDEX_SHIFT;
2005 final int pointerId = ev.getPointerId(pointerIndex);
2006 if (pointerId == mActivePointerId) {
2007 // This was our active pointer going up. Choose a new
2008 // active pointer and adjust accordingly.
2009 // TODO: Make this decision more intelligent.
2010 final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
2011 mLastMotionX = mDownMotionX = ev.getX(newPointerIndex);
2012 mLastMotionY = ev.getY(newPointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08002013 mLastMotionXRemainder = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07002014 mActivePointerId = ev.getPointerId(newPointerIndex);
2015 if (mVelocityTracker != null) {
2016 mVelocityTracker.clear();
2017 }
2018 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08002019 }
2020
Winson Chung321e9ee2010-08-09 13:37:56 -07002021 @Override
2022 public void requestChildFocus(View child, View focused) {
2023 super.requestChildFocus(child, focused);
Adam Cohenae4f1552011-10-20 00:15:42 -07002024 int page = indexToPage(indexOfChild(child));
Winson Chung97d85d22011-04-13 11:27:36 -07002025 if (page >= 0 && page != getCurrentPage() && !isInTouchMode()) {
Winson Chung86f77532010-08-24 11:08:22 -07002026 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07002027 }
2028 }
2029
Winson Chung1908d072011-02-24 18:09:44 -08002030 protected int getChildWidth(int index) {
Adam Cohen96d30a12013-07-16 18:13:21 -07002031 return getPageAt(index).getMeasuredWidth();
Winson Chung1908d072011-02-24 18:09:44 -08002032 }
2033
Adam Cohen7d30a372013-07-01 17:03:59 -07002034 int getPageNearestToPoint(float x) {
2035 int index = 0;
2036 for (int i = 0; i < getChildCount(); ++i) {
2037 if (x < getChildAt(i).getRight() - getScrollX()) {
2038 return index;
2039 } else {
2040 index++;
2041 }
2042 }
2043 return Math.min(index, getChildCount() - 1);
2044 }
2045
Adam Cohend19d3ca2010-09-15 14:43:42 -07002046 int getPageNearestToCenterOfScreen() {
Adam Cohen22f823d2011-09-01 17:22:18 -07002047 int minDistanceFromScreenCenter = Integer.MAX_VALUE;
Winson Chung321e9ee2010-08-09 13:37:56 -07002048 int minDistanceFromScreenCenterIndex = -1;
Adam Cohen7d30a372013-07-01 17:03:59 -07002049 int screenCenter = getViewportOffsetX() + getScrollX() + (getViewportWidth() / 2);
Winson Chung321e9ee2010-08-09 13:37:56 -07002050 final int childCount = getChildCount();
2051 for (int i = 0; i < childCount; ++i) {
Adam Cohen22f823d2011-09-01 17:22:18 -07002052 View layout = (View) getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -07002053 int childWidth = layout.getMeasuredWidth();
Winson Chung321e9ee2010-08-09 13:37:56 -07002054 int halfChildWidth = (childWidth / 2);
Adam Cohen7d30a372013-07-01 17:03:59 -07002055 int childCenter = getViewportOffsetX() + getChildOffset(i) + halfChildWidth;
Winson Chung321e9ee2010-08-09 13:37:56 -07002056 int distanceFromScreenCenter = Math.abs(childCenter - screenCenter);
2057 if (distanceFromScreenCenter < minDistanceFromScreenCenter) {
2058 minDistanceFromScreenCenter = distanceFromScreenCenter;
2059 minDistanceFromScreenCenterIndex = i;
2060 }
2061 }
Adam Cohend19d3ca2010-09-15 14:43:42 -07002062 return minDistanceFromScreenCenterIndex;
2063 }
2064
2065 protected void snapToDestination() {
2066 snapToPage(getPageNearestToCenterOfScreen(), PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07002067 }
2068
Adam Cohene0f66b52010-11-23 15:06:07 -08002069 private static class ScrollInterpolator implements Interpolator {
2070 public ScrollInterpolator() {
2071 }
2072
2073 public float getInterpolation(float t) {
2074 t -= 1.0f;
2075 return t*t*t*t*t + 1;
2076 }
2077 }
2078
2079 // We want the duration of the page snap animation to be influenced by the distance that
2080 // the screen has to travel, however, we don't want this duration to be effected in a
2081 // purely linear fashion. Instead, we use this method to moderate the effect that the distance
2082 // of travel has on the overall snap duration.
2083 float distanceInfluenceForSnapDuration(float f) {
2084 f -= 0.5f; // center the values about 0.
2085 f *= 0.3f * Math.PI / 2.0f;
2086 return (float) Math.sin(f);
2087 }
2088
Michael Jurka0142d492010-08-25 17:46:15 -07002089 protected void snapToPageWithVelocity(int whichPage, int velocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08002090 whichPage = Math.max(0, Math.min(whichPage, getChildCount() - 1));
Adam Cohen7d30a372013-07-01 17:03:59 -07002091 int halfScreenSize = getViewportWidth() / 2;
Adam Cohene0f66b52010-11-23 15:06:07 -08002092
Adam Cohenedb40762013-07-18 16:45:45 -07002093 final int newX = getScrollForPage(whichPage);
Adam Cohene0f66b52010-11-23 15:06:07 -08002094 int delta = newX - mUnboundedScrollX;
2095 int duration = 0;
2096
Adam Cohen265b9a62011-12-07 14:37:18 -08002097 if (Math.abs(velocity) < mMinFlingVelocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08002098 // If the velocity is low enough, then treat this more as an automatic page advance
2099 // as opposed to an apparent physical response to flinging
2100 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
2101 return;
2102 }
2103
2104 // Here we compute a "distance" that will be used in the computation of the overall
2105 // snap duration. This is a function of the actual distance that needs to be traveled;
2106 // we keep this value close to half screen size in order to reduce the variance in snap
2107 // duration as a function of the distance the page needs to travel.
Michael Jurka20b7ca92011-06-07 20:09:16 -07002108 float distanceRatio = Math.min(1f, 1.0f * Math.abs(delta) / (2 * halfScreenSize));
Adam Cohene0f66b52010-11-23 15:06:07 -08002109 float distance = halfScreenSize + halfScreenSize *
2110 distanceInfluenceForSnapDuration(distanceRatio);
2111
2112 velocity = Math.abs(velocity);
Adam Cohen265b9a62011-12-07 14:37:18 -08002113 velocity = Math.max(mMinSnapVelocity, velocity);
Adam Cohene0f66b52010-11-23 15:06:07 -08002114
2115 // we want the page's snap velocity to approximately match the velocity at which the
2116 // user flings, so we scale the duration by a value near to the derivative of the scroll
Michael Jurka20b7ca92011-06-07 20:09:16 -07002117 // interpolator at zero, ie. 5. We use 4 to make it a little slower.
2118 duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
Adam Cohene0f66b52010-11-23 15:06:07 -08002119
2120 snapToPage(whichPage, delta, duration);
Michael Jurka0142d492010-08-25 17:46:15 -07002121 }
2122
2123 protected void snapToPage(int whichPage) {
Winson Chung5f2aa4e2010-08-20 14:49:25 -07002124 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07002125 }
2126
Adam Cohen7d30a372013-07-01 17:03:59 -07002127 protected void snapToPageImmediately(int whichPage) {
2128 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION, true);
2129 }
2130
Michael Jurka0142d492010-08-25 17:46:15 -07002131 protected void snapToPage(int whichPage, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07002132 snapToPage(whichPage, duration, false);
2133 }
2134
2135 protected void snapToPage(int whichPage, int duration, boolean immediate) {
Winson Chung86f77532010-08-24 11:08:22 -07002136 whichPage = Math.max(0, Math.min(whichPage, getPageCount() - 1));
Winson Chung321e9ee2010-08-09 13:37:56 -07002137
Adam Cohenedb40762013-07-18 16:45:45 -07002138 int newX = getScrollForPage(whichPage);
Adam Cohen68d73932010-11-15 10:50:58 -08002139 final int sX = mUnboundedScrollX;
Winson Chung321e9ee2010-08-09 13:37:56 -07002140 final int delta = newX - sX;
Adam Cohen7d30a372013-07-01 17:03:59 -07002141 snapToPage(whichPage, delta, duration, immediate);
Michael Jurka0142d492010-08-25 17:46:15 -07002142 }
2143
2144 protected void snapToPage(int whichPage, int delta, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07002145 snapToPage(whichPage, delta, duration, false);
2146 }
Michael Jurka0142d492010-08-25 17:46:15 -07002147
Adam Cohen7d30a372013-07-01 17:03:59 -07002148 protected void snapToPage(int whichPage, int delta, int duration, boolean immediate) {
2149 mNextPage = whichPage;
Michael Jurka0142d492010-08-25 17:46:15 -07002150 View focusedChild = getFocusedChild();
2151 if (focusedChild != null && whichPage != mCurrentPage &&
Adam Cohen22f823d2011-09-01 17:22:18 -07002152 focusedChild == getPageAt(mCurrentPage)) {
Michael Jurka0142d492010-08-25 17:46:15 -07002153 focusedChild.clearFocus();
2154 }
2155
Adam Cohen53805212013-10-01 10:39:23 -07002156 sendScrollAccessibilityEvent();
2157
Michael Jurka0142d492010-08-25 17:46:15 -07002158 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07002159 awakenScrollBars(duration);
Adam Cohen7d30a372013-07-01 17:03:59 -07002160 if (immediate) {
2161 duration = 0;
2162 } else if (duration == 0) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002163 duration = Math.abs(delta);
2164 }
2165
Adam Cohenf358a4b2013-07-23 16:47:31 -07002166 if (!mScroller.isFinished()) {
2167 mScroller.abortAnimation();
2168 }
Adam Cohen68d73932010-11-15 10:50:58 -08002169 mScroller.startScroll(mUnboundedScrollX, 0, delta, 0, duration);
Winson Chung80baf5a2010-08-09 16:03:15 -07002170
Michael Jurka0142d492010-08-25 17:46:15 -07002171 notifyPageSwitchListener();
Adam Cohen7d30a372013-07-01 17:03:59 -07002172
2173 // Trigger a compute() to finish switching pages if necessary
2174 if (immediate) {
2175 computeScroll();
2176 }
2177
Winson Chung9c0565f2013-07-19 13:49:06 -07002178 // Defer loading associated pages until the scroll settles
2179 mDeferLoadAssociatedPagesUntilScrollCompletes = true;
2180
Adam Cohen7d30a372013-07-01 17:03:59 -07002181 mForceScreenScrolled = true;
Winson Chung321e9ee2010-08-09 13:37:56 -07002182 invalidate();
2183 }
2184
Winson Chung321e9ee2010-08-09 13:37:56 -07002185 public void scrollLeft() {
Adam Cohen2bf63d52013-09-29 17:46:49 -07002186 if (getNextPage() > 0) snapToPage(getNextPage() - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002187 }
2188
2189 public void scrollRight() {
Adam Cohen2bf63d52013-09-29 17:46:49 -07002190 if (getNextPage() < getChildCount() -1) snapToPage(getNextPage() + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002191 }
2192
Winson Chung86f77532010-08-24 11:08:22 -07002193 public int getPageForView(View v) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002194 int result = -1;
2195 if (v != null) {
2196 ViewParent vp = v.getParent();
2197 int count = getChildCount();
2198 for (int i = 0; i < count; i++) {
Adam Cohen22f823d2011-09-01 17:22:18 -07002199 if (vp == getPageAt(i)) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002200 return i;
2201 }
2202 }
2203 }
2204 return result;
2205 }
2206
2207 /**
2208 * @return True is long presses are still allowed for the current touch
2209 */
2210 public boolean allowLongPress() {
2211 return mAllowLongPress;
2212 }
2213
Adam Cohendbdff6b2013-09-18 19:09:15 -07002214 @Override
2215 public boolean performLongClick() {
2216 mCancelTap = true;
2217 return super.performLongClick();
2218 }
2219
Michael Jurka0142d492010-08-25 17:46:15 -07002220 /**
2221 * Set true to allow long-press events to be triggered, usually checked by
2222 * {@link Launcher} to accept or block dpad-initiated long-presses.
2223 */
2224 public void setAllowLongPress(boolean allowLongPress) {
2225 mAllowLongPress = allowLongPress;
2226 }
2227
Winson Chung321e9ee2010-08-09 13:37:56 -07002228 public static class SavedState extends BaseSavedState {
Winson Chung86f77532010-08-24 11:08:22 -07002229 int currentPage = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -07002230
2231 SavedState(Parcelable superState) {
2232 super(superState);
2233 }
2234
2235 private SavedState(Parcel in) {
2236 super(in);
Winson Chung86f77532010-08-24 11:08:22 -07002237 currentPage = in.readInt();
Winson Chung321e9ee2010-08-09 13:37:56 -07002238 }
2239
2240 @Override
2241 public void writeToParcel(Parcel out, int flags) {
2242 super.writeToParcel(out, flags);
Winson Chung86f77532010-08-24 11:08:22 -07002243 out.writeInt(currentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07002244 }
2245
2246 public static final Parcelable.Creator<SavedState> CREATOR =
2247 new Parcelable.Creator<SavedState>() {
2248 public SavedState createFromParcel(Parcel in) {
2249 return new SavedState(in);
2250 }
2251
2252 public SavedState[] newArray(int size) {
2253 return new SavedState[size];
2254 }
2255 };
2256 }
2257
Winson Chungf314b0e2011-08-16 11:54:27 -07002258 protected void loadAssociatedPages(int page) {
2259 loadAssociatedPages(page, false);
2260 }
2261 protected void loadAssociatedPages(int page, boolean immediateAndOnly) {
Michael Jurka0142d492010-08-25 17:46:15 -07002262 if (mContentIsRefreshable) {
2263 final int count = getChildCount();
2264 if (page < count) {
Winson Chunge3193b92010-09-10 11:44:42 -07002265 int lowerPageBound = getAssociatedLowerPageBound(page);
2266 int upperPageBound = getAssociatedUpperPageBound(page);
Winson Chung785d2eb2011-04-14 16:08:02 -07002267 if (DEBUG) Log.d(TAG, "loadAssociatedPages: " + lowerPageBound + "/"
2268 + upperPageBound);
Michael Jurka0cad1112011-11-16 20:43:29 -08002269 // First, clear any pages that should no longer be loaded
2270 for (int i = 0; i < count; ++i) {
2271 Page layout = (Page) getPageAt(i);
Michael Jurka2a4b1a82011-12-07 14:00:02 -08002272 if ((i < lowerPageBound) || (i > upperPageBound)) {
Michael Jurka0cad1112011-11-16 20:43:29 -08002273 if (layout.getPageChildCount() > 0) {
2274 layout.removeAllViewsOnPage();
2275 }
2276 mDirtyPageContent.set(i, true);
2277 }
2278 }
2279 // Next, load any new pages
Michael Jurka0142d492010-08-25 17:46:15 -07002280 for (int i = 0; i < count; ++i) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002281 if ((i != page) && immediateAndOnly) {
2282 continue;
2283 }
Michael Jurka0142d492010-08-25 17:46:15 -07002284 if (lowerPageBound <= i && i <= upperPageBound) {
2285 if (mDirtyPageContent.get(i)) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002286 syncPageItems(i, (i == page) && immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002287 mDirtyPageContent.set(i, false);
2288 }
Winson Chung86f77532010-08-24 11:08:22 -07002289 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002290 }
2291 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002292 }
2293 }
2294
Winson Chunge3193b92010-09-10 11:44:42 -07002295 protected int getAssociatedLowerPageBound(int page) {
2296 return Math.max(0, page - 1);
2297 }
2298 protected int getAssociatedUpperPageBound(int page) {
2299 final int count = getChildCount();
2300 return Math.min(page + 1, count - 1);
2301 }
2302
Winson Chung86f77532010-08-24 11:08:22 -07002303 /**
2304 * This method is called ONLY to synchronize the number of pages that the paged view has.
2305 * To actually fill the pages with information, implement syncPageItems() below. It is
2306 * guaranteed that syncPageItems() will be called for a particular page before it is shown,
2307 * and therefore, individual page items do not need to be updated in this method.
2308 */
Winson Chung321e9ee2010-08-09 13:37:56 -07002309 public abstract void syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002310
2311 /**
2312 * This method is called to synchronize the items that are on a particular page. If views on
2313 * the page can be reused, then they should be updated within this method.
2314 */
Winson Chungf314b0e2011-08-16 11:54:27 -07002315 public abstract void syncPageItems(int page, boolean immediate);
Winson Chung86f77532010-08-24 11:08:22 -07002316
Patrick Dubroy244d74c2011-05-19 16:48:48 -07002317 protected void invalidatePageData() {
Winson Chungf314b0e2011-08-16 11:54:27 -07002318 invalidatePageData(-1, false);
Winson Chung5a808352011-06-27 19:08:49 -07002319 }
2320 protected void invalidatePageData(int currentPage) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002321 invalidatePageData(currentPage, false);
2322 }
2323 protected void invalidatePageData(int currentPage, boolean immediateAndOnly) {
Winson Chungf0ea4d32011-06-06 14:27:16 -07002324 if (!mIsDataReady) {
2325 return;
2326 }
2327
Michael Jurka0142d492010-08-25 17:46:15 -07002328 if (mContentIsRefreshable) {
Adam Cohen0cd3b642011-10-14 14:58:00 -07002329 // Force all scrolling-related behavior to end
2330 mScroller.forceFinished(true);
2331 mNextPage = INVALID_PAGE;
2332
Michael Jurka0142d492010-08-25 17:46:15 -07002333 // Update all the pages
2334 syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002335
Winson Chung5a808352011-06-27 19:08:49 -07002336 // We must force a measure after we've loaded the pages to update the content width and
2337 // to determine the full scroll width
2338 measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY),
2339 MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY));
2340
2341 // Set a new page as the current page if necessary
2342 if (currentPage > -1) {
Winson Chung5afbf7b2011-07-25 11:53:08 -07002343 setCurrentPage(Math.min(getPageCount() - 1, currentPage));
Winson Chung5a808352011-06-27 19:08:49 -07002344 }
2345
Michael Jurka0142d492010-08-25 17:46:15 -07002346 // Mark each of the pages as dirty
2347 final int count = getChildCount();
2348 mDirtyPageContent.clear();
2349 for (int i = 0; i < count; ++i) {
2350 mDirtyPageContent.add(true);
2351 }
2352
2353 // Load any pages that are necessary for the current window of views
Winson Chungf314b0e2011-08-16 11:54:27 -07002354 loadAssociatedPages(mCurrentPage, immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002355 requestLayout();
Winson Chung86f77532010-08-24 11:08:22 -07002356 }
Adam Cohen06559042013-09-29 18:30:56 -07002357 if (isPageMoving()) {
2358 // If the page is moving, then snap it to the final position to ensure we don't get
2359 // stuck between pages
2360 snapToDestination();
2361 }
Winson Chung321e9ee2010-08-09 13:37:56 -07002362 }
Winson Chung007c6982011-06-14 13:27:53 -07002363
Adam Cohen7d30a372013-07-01 17:03:59 -07002364 // Animate the drag view back to the original position
2365 void animateDragViewToOriginalPosition() {
2366 if (mDragView != null) {
2367 AnimatorSet anim = new AnimatorSet();
2368 anim.setDuration(REORDERING_DROP_REPOSITION_DURATION);
2369 anim.playTogether(
2370 ObjectAnimator.ofFloat(mDragView, "translationX", 0f),
Adam Cohenf358a4b2013-07-23 16:47:31 -07002371 ObjectAnimator.ofFloat(mDragView, "translationY", 0f),
2372 ObjectAnimator.ofFloat(mDragView, "scaleX", 1f),
2373 ObjectAnimator.ofFloat(mDragView, "scaleY", 1f));
Adam Cohen7d30a372013-07-01 17:03:59 -07002374 anim.addListener(new AnimatorListenerAdapter() {
2375 @Override
2376 public void onAnimationEnd(Animator animation) {
2377 onPostReorderingAnimationCompleted();
2378 }
2379 });
2380 anim.start();
2381 }
Winson Chung3ac74c52011-06-30 17:39:37 -07002382 }
2383
Adam Cohen7d30a372013-07-01 17:03:59 -07002384 protected void onStartReordering() {
2385 // Set the touch state to reordering (allows snapping to pages, dragging a child, etc.)
2386 mTouchState = TOUCH_STATE_REORDERING;
2387 mIsReordering = true;
2388
Adam Cohen7d30a372013-07-01 17:03:59 -07002389 // We must invalidate to trigger a redraw to update the layers such that the drag view
2390 // is always drawn on top
2391 invalidate();
2392 }
2393
2394 private void onPostReorderingAnimationCompleted() {
2395 // Trigger the callback when reordering has settled
2396 --mPostReorderingPreZoomInRemainingAnimationCount;
2397 if (mPostReorderingPreZoomInRunnable != null &&
2398 mPostReorderingPreZoomInRemainingAnimationCount == 0) {
2399 mPostReorderingPreZoomInRunnable.run();
2400 mPostReorderingPreZoomInRunnable = null;
2401 }
2402 }
2403
2404 protected void onEndReordering() {
2405 mIsReordering = false;
Adam Cohen7d30a372013-07-01 17:03:59 -07002406 }
2407
Adam Cohenf358a4b2013-07-23 16:47:31 -07002408 public boolean startReordering(View v) {
Adam Cohen93c97562013-09-26 13:48:01 -07002409 int dragViewIndex = indexOfChild(v);
2410
2411 if (mTouchState != TOUCH_STATE_REST) return false;
2412
Adam Cohen7d30a372013-07-01 17:03:59 -07002413 mTempVisiblePagesRange[0] = 0;
2414 mTempVisiblePagesRange[1] = getPageCount() - 1;
Adam Cohenf358a4b2013-07-23 16:47:31 -07002415 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002416 mReorderingStarted = true;
2417
2418 // Check if we are within the reordering range
2419 if (mTempVisiblePagesRange[0] <= dragViewIndex &&
Adam Cohenf358a4b2013-07-23 16:47:31 -07002420 dragViewIndex <= mTempVisiblePagesRange[1]) {
2421 // Find the drag view under the pointer
2422 mDragView = getChildAt(dragViewIndex);
2423 mDragView.animate().scaleX(1.15f).scaleY(1.15f).setDuration(100).start();
2424 mDragViewBaselineLeft = mDragView.getLeft();
2425 disableFreeScroll(-1);
2426 onStartReordering();
Adam Cohen7d30a372013-07-01 17:03:59 -07002427 return true;
2428 }
2429 return false;
2430 }
2431
2432 boolean isReordering(boolean testTouchState) {
2433 boolean state = mIsReordering;
2434 if (testTouchState) {
2435 state &= (mTouchState == TOUCH_STATE_REORDERING);
2436 }
2437 return state;
2438 }
2439 void endReordering() {
2440 // For simplicity, we call endReordering sometimes even if reordering was never started.
2441 // In that case, we don't want to do anything.
2442 if (!mReorderingStarted) return;
2443 mReorderingStarted = false;
2444
2445 // If we haven't flung-to-delete the current child, then we just animate the drag view
2446 // back into position
2447 final Runnable onCompleteRunnable = new Runnable() {
2448 @Override
2449 public void run() {
2450 onEndReordering();
2451 }
2452 };
2453 if (!mDeferringForDelete) {
2454 mPostReorderingPreZoomInRunnable = new Runnable() {
2455 public void run() {
Adam Cohenf358a4b2013-07-23 16:47:31 -07002456 onCompleteRunnable.run();
2457 enableFreeScroll();
Adam Cohen7d30a372013-07-01 17:03:59 -07002458 };
2459 };
2460
2461 mPostReorderingPreZoomInRemainingAnimationCount =
2462 NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT;
2463 // Snap to the current page
2464 snapToPage(indexOfChild(mDragView), 0);
2465 // Animate the drag view back to the front position
2466 animateDragViewToOriginalPosition();
2467 } else {
2468 // Handled in post-delete-animation-callbacks
2469 }
2470 }
2471
Adam Cohen7d30a372013-07-01 17:03:59 -07002472 /*
2473 * Flinging to delete - IN PROGRESS
2474 */
2475 private PointF isFlingingToDelete() {
2476 ViewConfiguration config = ViewConfiguration.get(getContext());
2477 mVelocityTracker.computeCurrentVelocity(1000, config.getScaledMaximumFlingVelocity());
2478
2479 if (mVelocityTracker.getYVelocity() < mFlingToDeleteThresholdVelocity) {
2480 // Do a quick dot product test to ensure that we are flinging upwards
2481 PointF vel = new PointF(mVelocityTracker.getXVelocity(),
2482 mVelocityTracker.getYVelocity());
2483 PointF upVec = new PointF(0f, -1f);
2484 float theta = (float) Math.acos(((vel.x * upVec.x) + (vel.y * upVec.y)) /
2485 (vel.length() * upVec.length()));
2486 if (theta <= Math.toRadians(FLING_TO_DELETE_MAX_FLING_DEGREES)) {
2487 return vel;
2488 }
2489 }
2490 return null;
2491 }
2492
2493 /**
2494 * Creates an animation from the current drag view along its current velocity vector.
2495 * For this animation, the alpha runs for a fixed duration and we update the position
2496 * progressively.
2497 */
2498 private static class FlingAlongVectorAnimatorUpdateListener implements AnimatorUpdateListener {
2499 private View mDragView;
2500 private PointF mVelocity;
2501 private Rect mFrom;
2502 private long mPrevTime;
2503 private float mFriction;
2504
2505 private final TimeInterpolator mAlphaInterpolator = new DecelerateInterpolator(0.75f);
2506
2507 public FlingAlongVectorAnimatorUpdateListener(View dragView, PointF vel, Rect from,
2508 long startTime, float friction) {
2509 mDragView = dragView;
2510 mVelocity = vel;
2511 mFrom = from;
2512 mPrevTime = startTime;
2513 mFriction = 1f - (mDragView.getResources().getDisplayMetrics().density * friction);
2514 }
2515
2516 @Override
2517 public void onAnimationUpdate(ValueAnimator animation) {
2518 float t = ((Float) animation.getAnimatedValue()).floatValue();
2519 long curTime = AnimationUtils.currentAnimationTimeMillis();
2520
2521 mFrom.left += (mVelocity.x * (curTime - mPrevTime) / 1000f);
2522 mFrom.top += (mVelocity.y * (curTime - mPrevTime) / 1000f);
2523
2524 mDragView.setTranslationX(mFrom.left);
2525 mDragView.setTranslationY(mFrom.top);
2526 mDragView.setAlpha(1f - mAlphaInterpolator.getInterpolation(t));
2527
2528 mVelocity.x *= mFriction;
2529 mVelocity.y *= mFriction;
2530 mPrevTime = curTime;
2531 }
2532 };
2533
2534 private static final int ANIM_TAG_KEY = 100;
2535
2536 private Runnable createPostDeleteAnimationRunnable(final View dragView) {
2537 return new Runnable() {
2538 @Override
2539 public void run() {
2540 int dragViewIndex = indexOfChild(dragView);
2541
2542 // For each of the pages around the drag view, animate them from the previous
2543 // position to the new position in the layout (as a result of the drag view moving
2544 // in the layout)
2545 // NOTE: We can make an assumption here because we have side-bound pages that we
2546 // will always have pages to animate in from the left
Adam Cohenf358a4b2013-07-23 16:47:31 -07002547 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002548 boolean isLastWidgetPage = (mTempVisiblePagesRange[0] == mTempVisiblePagesRange[1]);
2549 boolean slideFromLeft = (isLastWidgetPage ||
2550 dragViewIndex > mTempVisiblePagesRange[0]);
2551
2552 // Setup the scroll to the correct page before we swap the views
2553 if (slideFromLeft) {
2554 snapToPageImmediately(dragViewIndex - 1);
2555 }
2556
2557 int firstIndex = (isLastWidgetPage ? 0 : mTempVisiblePagesRange[0]);
2558 int lastIndex = Math.min(mTempVisiblePagesRange[1], getPageCount() - 1);
2559 int lowerIndex = (slideFromLeft ? firstIndex : dragViewIndex + 1 );
2560 int upperIndex = (slideFromLeft ? dragViewIndex - 1 : lastIndex);
2561 ArrayList<Animator> animations = new ArrayList<Animator>();
2562 for (int i = lowerIndex; i <= upperIndex; ++i) {
2563 View v = getChildAt(i);
2564 // dragViewIndex < pageUnderPointIndex, so after we remove the
2565 // drag view all subsequent views to pageUnderPointIndex will
2566 // shift down.
2567 int oldX = 0;
2568 int newX = 0;
2569 if (slideFromLeft) {
2570 if (i == 0) {
Adam Cohen0cd0eba2013-10-28 14:22:25 -07002571 int pageSpace = (getViewportWidth() - getChildWidth(i)) / 2;
Adam Cohen7d30a372013-07-01 17:03:59 -07002572 // Simulate the page being offscreen with the page spacing
2573 oldX = getViewportOffsetX() + getChildOffset(i) - getChildWidth(i)
Adam Cohen0cd0eba2013-10-28 14:22:25 -07002574 - pageSpace;
Adam Cohen7d30a372013-07-01 17:03:59 -07002575 } else {
2576 oldX = getViewportOffsetX() + getChildOffset(i - 1);
2577 }
2578 newX = getViewportOffsetX() + getChildOffset(i);
2579 } else {
2580 oldX = getChildOffset(i) - getChildOffset(i - 1);
2581 newX = 0;
2582 }
2583
2584 // Animate the view translation from its old position to its new
2585 // position
2586 AnimatorSet anim = (AnimatorSet) v.getTag();
2587 if (anim != null) {
2588 anim.cancel();
2589 }
2590
2591 // Note: Hacky, but we want to skip any optimizations to not draw completely
2592 // hidden views
2593 v.setAlpha(Math.max(v.getAlpha(), 0.01f));
2594 v.setTranslationX(oldX - newX);
2595 anim = new AnimatorSet();
2596 anim.playTogether(
2597 ObjectAnimator.ofFloat(v, "translationX", 0f),
2598 ObjectAnimator.ofFloat(v, "alpha", 1f));
2599 animations.add(anim);
2600 v.setTag(ANIM_TAG_KEY, anim);
2601 }
2602
2603 AnimatorSet slideAnimations = new AnimatorSet();
2604 slideAnimations.playTogether(animations);
2605 slideAnimations.setDuration(DELETE_SLIDE_IN_SIDE_PAGE_DURATION);
2606 slideAnimations.addListener(new AnimatorListenerAdapter() {
2607 @Override
2608 public void onAnimationEnd(Animator animation) {
Adam Cohenf358a4b2013-07-23 16:47:31 -07002609 mDeferringForDelete = false;
2610 onEndReordering();
2611 onRemoveViewAnimationCompleted();
Adam Cohen7d30a372013-07-01 17:03:59 -07002612 }
2613 });
2614 slideAnimations.start();
2615
2616 removeView(dragView);
2617 onRemoveView(dragView, true);
2618 }
2619 };
2620 }
2621
2622 public void onFlingToDelete(PointF vel) {
2623 final long startTime = AnimationUtils.currentAnimationTimeMillis();
2624
2625 // NOTE: Because it takes time for the first frame of animation to actually be
2626 // called and we expect the animation to be a continuation of the fling, we have
2627 // to account for the time that has elapsed since the fling finished. And since
2628 // we don't have a startDelay, we will always get call to update when we call
2629 // start() (which we want to ignore).
2630 final TimeInterpolator tInterpolator = new TimeInterpolator() {
2631 private int mCount = -1;
2632 private long mStartTime;
2633 private float mOffset;
2634 /* Anonymous inner class ctor */ {
2635 mStartTime = startTime;
2636 }
2637
2638 @Override
2639 public float getInterpolation(float t) {
2640 if (mCount < 0) {
2641 mCount++;
2642 } else if (mCount == 0) {
2643 mOffset = Math.min(0.5f, (float) (AnimationUtils.currentAnimationTimeMillis() -
2644 mStartTime) / FLING_TO_DELETE_FADE_OUT_DURATION);
2645 mCount++;
2646 }
2647 return Math.min(1f, mOffset + t);
2648 }
2649 };
2650
2651 final Rect from = new Rect();
2652 final View dragView = mDragView;
2653 from.left = (int) dragView.getTranslationX();
2654 from.top = (int) dragView.getTranslationY();
2655 AnimatorUpdateListener updateCb = new FlingAlongVectorAnimatorUpdateListener(dragView, vel,
2656 from, startTime, FLING_TO_DELETE_FRICTION);
2657
2658 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2659
2660 // Create and start the animation
2661 ValueAnimator mDropAnim = new ValueAnimator();
2662 mDropAnim.setInterpolator(tInterpolator);
2663 mDropAnim.setDuration(FLING_TO_DELETE_FADE_OUT_DURATION);
2664 mDropAnim.setFloatValues(0f, 1f);
2665 mDropAnim.addUpdateListener(updateCb);
2666 mDropAnim.addListener(new AnimatorListenerAdapter() {
2667 public void onAnimationEnd(Animator animation) {
2668 onAnimationEndRunnable.run();
2669 }
2670 });
2671 mDropAnim.start();
2672 mDeferringForDelete = true;
2673 }
2674
2675 /* Drag to delete */
2676 private boolean isHoveringOverDeleteDropTarget(int x, int y) {
2677 if (mDeleteDropTarget != null) {
2678 mAltTmpRect.set(0, 0, 0, 0);
2679 View parent = (View) mDeleteDropTarget.getParent();
2680 if (parent != null) {
2681 parent.getGlobalVisibleRect(mAltTmpRect);
2682 }
2683 mDeleteDropTarget.getGlobalVisibleRect(mTmpRect);
2684 mTmpRect.offset(-mAltTmpRect.left, -mAltTmpRect.top);
2685 return mTmpRect.contains(x, y);
2686 }
2687 return false;
2688 }
2689
2690 protected void setPageHoveringOverDeleteDropTarget(int viewIndex, boolean isHovering) {}
2691
2692 private void onDropToDelete() {
2693 final View dragView = mDragView;
2694
2695 final float toScale = 0f;
2696 final float toAlpha = 0f;
2697
2698 // Create and start the complex animation
2699 ArrayList<Animator> animations = new ArrayList<Animator>();
2700 AnimatorSet motionAnim = new AnimatorSet();
2701 motionAnim.setInterpolator(new DecelerateInterpolator(2));
2702 motionAnim.playTogether(
2703 ObjectAnimator.ofFloat(dragView, "scaleX", toScale),
2704 ObjectAnimator.ofFloat(dragView, "scaleY", toScale));
2705 animations.add(motionAnim);
2706
2707 AnimatorSet alphaAnim = new AnimatorSet();
2708 alphaAnim.setInterpolator(new LinearInterpolator());
2709 alphaAnim.playTogether(
2710 ObjectAnimator.ofFloat(dragView, "alpha", toAlpha));
2711 animations.add(alphaAnim);
2712
2713 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2714
2715 AnimatorSet anim = new AnimatorSet();
2716 anim.playTogether(animations);
2717 anim.setDuration(DRAG_TO_DELETE_FADE_OUT_DURATION);
2718 anim.addListener(new AnimatorListenerAdapter() {
2719 public void onAnimationEnd(Animator animation) {
2720 onAnimationEndRunnable.run();
2721 }
2722 });
2723 anim.start();
2724
2725 mDeferringForDelete = true;
Winson Chung007c6982011-06-14 13:27:53 -07002726 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002727
2728 /* Accessibility */
2729 @Override
2730 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
2731 super.onInitializeAccessibilityNodeInfo(info);
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002732 info.setScrollable(getPageCount() > 1);
2733 if (getCurrentPage() < getPageCount() - 1) {
2734 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
2735 }
2736 if (getCurrentPage() > 0) {
2737 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
2738 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002739 }
2740
2741 @Override
Alan Viverette254139a2013-10-08 13:13:46 -07002742 public void sendAccessibilityEvent(int eventType) {
2743 // Don't let the view send real scroll events.
2744 if (eventType != AccessibilityEvent.TYPE_VIEW_SCROLLED) {
2745 super.sendAccessibilityEvent(eventType);
2746 }
2747 }
2748
2749 @Override
Winson Chung6a0f57d2011-06-29 20:10:49 -07002750 public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
2751 super.onInitializeAccessibilityEvent(event);
2752 event.setScrollable(true);
Winson Chung6a0f57d2011-06-29 20:10:49 -07002753 }
2754
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002755 @Override
2756 public boolean performAccessibilityAction(int action, Bundle arguments) {
2757 if (super.performAccessibilityAction(action, arguments)) {
2758 return true;
2759 }
2760 switch (action) {
2761 case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: {
2762 if (getCurrentPage() < getPageCount() - 1) {
2763 scrollRight();
2764 return true;
2765 }
2766 } break;
2767 case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: {
2768 if (getCurrentPage() > 0) {
2769 scrollLeft();
2770 return true;
2771 }
2772 } break;
2773 }
2774 return false;
2775 }
2776
Adam Cohen0ffac432013-07-10 11:19:26 -07002777 protected String getCurrentPageDescription() {
2778 return String.format(getContext().getString(R.string.default_scroll_format),
2779 getNextPage() + 1, getChildCount());
2780 }
2781
Winson Chungd11265e2011-08-30 13:37:23 -07002782 @Override
2783 public boolean onHoverEvent(android.view.MotionEvent event) {
2784 return true;
2785 }
Adam Cohen5084cba2013-09-03 12:01:16 -07002786}