blob: c8e34dda1e6de9fa3cddc4850bf5ab6bc0cf0045 [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;
35import android.util.AttributeSet;
Adam Cohen7d30a372013-07-01 17:03:59 -070036import android.util.DisplayMetrics;
Winson Chung785d2eb2011-04-14 16:08:02 -070037import android.util.Log;
Winson Chung185d7162011-02-28 13:47:29 -080038import android.view.InputDevice;
39import android.view.KeyEvent;
Winson Chung321e9ee2010-08-09 13:37:56 -070040import android.view.MotionEvent;
41import android.view.VelocityTracker;
42import android.view.View;
43import android.view.ViewConfiguration;
44import android.view.ViewGroup;
45import android.view.ViewParent;
Winson Chung6a0f57d2011-06-29 20:10:49 -070046import android.view.accessibility.AccessibilityEvent;
Winson Chungc27d1bb2011-09-29 12:07:42 -070047import android.view.accessibility.AccessibilityManager;
Winson Chung6a0f57d2011-06-29 20:10:49 -070048import android.view.accessibility.AccessibilityNodeInfo;
Adam Cohen7d30a372013-07-01 17:03:59 -070049import android.view.animation.AnimationUtils;
50import android.view.animation.DecelerateInterpolator;
Adam Cohene0f66b52010-11-23 15:06:07 -080051import android.view.animation.Interpolator;
Adam Cohen7d30a372013-07-01 17:03:59 -070052import android.view.animation.LinearInterpolator;
Winson Chung321e9ee2010-08-09 13:37:56 -070053import android.widget.Scroller;
54
Winson Chung6a0f57d2011-06-29 20:10:49 -070055import java.util.ArrayList;
56
Winson Chungc58497e2013-09-03 17:48:37 -070057interface Page {
58 public int getPageChildCount();
59 public View getChildOnPageAt(int i);
60 public void removeAllViewsOnPage();
61 public void removeViewOnPageAt(int i);
62 public int indexOfChildOnPage(View v);
63}
64
Winson Chung321e9ee2010-08-09 13:37:56 -070065/**
66 * An abstraction of the original Workspace which supports browsing through a
Michael Jurka0142d492010-08-25 17:46:15 -070067 * sequential list of "pages"
Winson Chung321e9ee2010-08-09 13:37:56 -070068 */
Michael Jurka8b805b12012-04-18 14:23:14 -070069public abstract class PagedView extends ViewGroup implements ViewGroup.OnHierarchyChangeListener {
Winson Chung321e9ee2010-08-09 13:37:56 -070070 private static final String TAG = "PagedView";
Winson Chung785d2eb2011-04-14 16:08:02 -070071 private static final boolean DEBUG = false;
Michael Jurka0142d492010-08-25 17:46:15 -070072 protected static final int INVALID_PAGE = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -070073
Winson Chung86f77532010-08-24 11:08:22 -070074 // the min drag distance for a fling to register, to prevent random page shifts
Winson Chung9cfd25f2010-10-24 16:09:28 -070075 private static final int MIN_LENGTH_FOR_FLING = 25;
Winson Chung321e9ee2010-08-09 13:37:56 -070076
Adam Cohen7d30a372013-07-01 17:03:59 -070077 protected static final int PAGE_SNAP_ANIMATION_DURATION = 750;
Winson Chungf0c6ae02012-03-21 16:10:31 -070078 protected static final int SLOW_PAGE_SNAP_ANIMATION_DURATION = 950;
Michael Jurka0142d492010-08-25 17:46:15 -070079 protected static final float NANOTIME_DIV = 1000000000.0f;
Winson Chung321e9ee2010-08-09 13:37:56 -070080
Adam Cohenb5ba0972011-09-07 18:02:31 -070081 private static final float OVERSCROLL_ACCELERATE_FACTOR = 2;
Winson Chungb26f3d62011-06-02 10:49:29 -070082 private static final float OVERSCROLL_DAMP_FACTOR = 0.14f;
Winson Chung867ca622012-02-21 15:48:35 -080083
Adam Cohenb64cb5a2011-02-15 13:53:42 -080084 private static final float RETURN_TO_ORIGINAL_PAGE_THRESHOLD = 0.33f;
Adam Cohen00481b32011-11-18 12:03:48 -080085 // The page is moved more than halfway, automatically move to the next page on touch up.
86 private static final float SIGNIFICANT_MOVE_THRESHOLD = 0.4f;
Adam Cohen68d73932010-11-15 10:50:58 -080087
Adam Cohen265b9a62011-12-07 14:37:18 -080088 // The following constants need to be scaled based on density. The scaled versions will be
89 // assigned to the corresponding member variables below.
90 private static final int FLING_THRESHOLD_VELOCITY = 500;
91 private static final int MIN_SNAP_VELOCITY = 1500;
92 private static final int MIN_FLING_VELOCITY = 250;
93
Adam Cohen7d30a372013-07-01 17:03:59 -070094 // We are disabling touch interaction of the widget region for factory ROM.
95 private static final boolean DISABLE_TOUCH_INTERACTION = false;
Adam Cohenf358a4b2013-07-23 16:47:31 -070096 private static final boolean DISABLE_TOUCH_SIDE_PAGES = true;
Adam Cohendedbd962013-07-11 14:21:49 -070097 private static final boolean DISABLE_FLING_TO_DELETE = true;
Adam Cohen7d30a372013-07-01 17:03:59 -070098
Adam Cohenf358a4b2013-07-23 16:47:31 -070099 private boolean mFreeScroll = false;
100 private int mFreeScrollMinScrollX = -1;
101 private int mFreeScrollMaxScrollX = -1;
102
Winson Chung8aad6102012-05-11 16:27:49 -0700103 static final int AUTOMATIC_PAGE_SPACING = -1;
104
Adam Cohen265b9a62011-12-07 14:37:18 -0800105 protected int mFlingThresholdVelocity;
106 protected int mMinFlingVelocity;
107 protected int mMinSnapVelocity;
Michael Jurka0142d492010-08-25 17:46:15 -0700108
Adam Cohenb5ba0972011-09-07 18:02:31 -0700109 protected float mDensity;
Michael Jurka0142d492010-08-25 17:46:15 -0700110 protected float mSmoothingTime;
111 protected float mTouchX;
112
113 protected boolean mFirstLayout = true;
Adam Cohen410f3cd2013-09-22 12:09:32 -0700114 private int mNormalChildHeight;
Michael Jurka0142d492010-08-25 17:46:15 -0700115
116 protected int mCurrentPage;
Winson Chung8c87cd82013-07-23 16:20:10 -0700117 protected int mRestorePage = -1;
Adam Cohenf698c6e2013-07-17 18:44:25 -0700118 protected int mChildCountOnLastLayout;
Adam Cohene61a9a22013-06-11 15:45:31 -0700119
Michael Jurka0142d492010-08-25 17:46:15 -0700120 protected int mNextPage = INVALID_PAGE;
Adam Cohen68d73932010-11-15 10:50:58 -0800121 protected int mMaxScrollX;
Michael Jurka0142d492010-08-25 17:46:15 -0700122 protected Scroller mScroller;
Winson Chung321e9ee2010-08-09 13:37:56 -0700123 private VelocityTracker mVelocityTracker;
124
Adam Cohen7d30a372013-07-01 17:03:59 -0700125 private float mParentDownMotionX;
126 private float mParentDownMotionY;
Winson Chung321e9ee2010-08-09 13:37:56 -0700127 private float mDownMotionX;
Adam Cohen7d30a372013-07-01 17:03:59 -0700128 private float mDownMotionY;
129 private float mDownScrollX;
Adam Cohenf358a4b2013-07-23 16:47:31 -0700130 private float mDragViewBaselineLeft;
Michael Jurka7426c422010-11-11 15:23:47 -0800131 protected float mLastMotionX;
Winson Chungc0844aa2011-02-02 15:25:58 -0800132 protected float mLastMotionXRemainder;
Michael Jurka7426c422010-11-11 15:23:47 -0800133 protected float mLastMotionY;
Adam Cohenaefd4e12011-02-14 16:39:38 -0800134 protected float mTotalMotionX;
Adam Cohenf34bab52010-09-30 14:11:56 -0700135 private int mLastScreenCenter = -1;
Adam Cohenedb40762013-07-18 16:45:45 -0700136
Adam Cohendbdff6b2013-09-18 19:09:15 -0700137 private boolean mCancelTap;
138
Adam Cohenedb40762013-07-18 16:45:45 -0700139 private int[] mPageScrolls;
Winson Chung321e9ee2010-08-09 13:37:56 -0700140
Michael Jurka0142d492010-08-25 17:46:15 -0700141 protected final static int TOUCH_STATE_REST = 0;
142 protected final static int TOUCH_STATE_SCROLLING = 1;
143 protected final static int TOUCH_STATE_PREV_PAGE = 2;
144 protected final static int TOUCH_STATE_NEXT_PAGE = 3;
Adam Cohen7d30a372013-07-01 17:03:59 -0700145 protected final static int TOUCH_STATE_REORDERING = 4;
146
Adam Cohene45440e2010-10-14 18:33:38 -0700147 protected final static float ALPHA_QUANTIZE_LEVEL = 0.0001f;
Winson Chung321e9ee2010-08-09 13:37:56 -0700148
Michael Jurka0142d492010-08-25 17:46:15 -0700149 protected int mTouchState = TOUCH_STATE_REST;
Adam Cohen2591f6a2011-10-25 14:36:40 -0700150 protected boolean mForceScreenScrolled = false;
Winson Chung321e9ee2010-08-09 13:37:56 -0700151
Michael Jurka0142d492010-08-25 17:46:15 -0700152 protected OnLongClickListener mLongClickListener;
Winson Chung321e9ee2010-08-09 13:37:56 -0700153
Michael Jurka7426c422010-11-11 15:23:47 -0800154 protected int mTouchSlop;
Winson Chung321e9ee2010-08-09 13:37:56 -0700155 private int mPagingTouchSlop;
156 private int mMaximumVelocity;
Adam Cohen9c4949e2010-10-05 12:27:22 -0700157 protected int mPageSpacing;
158 protected int mPageLayoutPaddingTop;
159 protected int mPageLayoutPaddingBottom;
160 protected int mPageLayoutPaddingLeft;
161 protected int mPageLayoutPaddingRight;
Winson Chungdf4b83d2010-10-20 17:49:27 -0700162 protected int mPageLayoutWidthGap;
163 protected int mPageLayoutHeightGap;
Michael Jurka87b14902011-05-25 22:13:09 -0700164 protected int mCellCountX = 0;
165 protected int mCellCountY = 0;
Winson Chung7da10252010-10-28 16:07:04 -0700166 protected boolean mCenterPagesVertically;
Adam Cohen68d73932010-11-15 10:50:58 -0800167 protected boolean mAllowOverScroll = true;
168 protected int mUnboundedScrollX;
Michael Jurkadde558b2011-11-09 22:09:06 -0800169 protected int[] mTempVisiblePagesRange = new int[2];
Michael Jurka5e368ff2012-05-14 23:13:15 -0700170 protected boolean mForceDrawAllChildrenNextFrame;
Winson Chung321e9ee2010-08-09 13:37:56 -0700171
Michael Jurka8b805b12012-04-18 14:23:14 -0700172 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range. Otherwise
Adam Cohenebea84d2011-11-09 17:20:41 -0800173 // it is equal to the scaled overscroll position. We use a separate value so as to prevent
174 // the screens from continuing to translate beyond the normal bounds.
175 protected int mOverScrollX;
176
Michael Jurka5f1c5092010-09-03 14:15:02 -0700177 protected static final int INVALID_POINTER = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -0700178
Michael Jurka5f1c5092010-09-03 14:15:02 -0700179 protected int mActivePointerId = INVALID_POINTER;
Winson Chung321e9ee2010-08-09 13:37:56 -0700180
Winson Chung86f77532010-08-24 11:08:22 -0700181 private PageSwitchListener mPageSwitchListener;
Winson Chung321e9ee2010-08-09 13:37:56 -0700182
Michael Jurkae326f182011-11-21 14:05:46 -0800183 protected ArrayList<Boolean> mDirtyPageContent;
Winson Chung321e9ee2010-08-09 13:37:56 -0700184
Michael Jurka0142d492010-08-25 17:46:15 -0700185 // If true, syncPages and syncPageItems will be called to refresh pages
186 protected boolean mContentIsRefreshable = true;
187
188 // If true, modify alpha of neighboring pages as user scrolls left/right
Adam Cohen7d30a372013-07-01 17:03:59 -0700189 protected boolean mFadeInAdjacentScreens = false;
Michael Jurka0142d492010-08-25 17:46:15 -0700190
191 // It true, use a different slop parameter (pagingTouchSlop = 2 * touchSlop) for deciding
192 // to switch to a new page
193 protected boolean mUsePagingTouchSlop = true;
194
Michael Jurka8b805b12012-04-18 14:23:14 -0700195 // If true, the subclass should directly update scrollX itself in its computeScroll method
Michael Jurka0142d492010-08-25 17:46:15 -0700196 // (SmoothPagedView does this)
197 protected boolean mDeferScrollUpdate = false;
Winson Chung9c0565f2013-07-19 13:49:06 -0700198 protected boolean mDeferLoadAssociatedPagesUntilScrollCompletes = false;
Michael Jurka0142d492010-08-25 17:46:15 -0700199
Patrick Dubroy1262e362010-10-06 15:49:50 -0700200 protected boolean mIsPageMoving = false;
201
Winson Chungf0ea4d32011-06-06 14:27:16 -0700202 // All syncs and layout passes are deferred until data is ready.
203 protected boolean mIsDataReady = false;
204
Adam Cohen7d30a372013-07-01 17:03:59 -0700205 protected boolean mAllowLongPress = true;
206
Winson Chungd2be3812013-07-16 11:11:32 -0700207 // Page Indicator
208 private int mPageIndicatorViewId;
209 private PageIndicator mPageIndicator;
Winson Chungc58497e2013-09-03 17:48:37 -0700210 private boolean mAllowPagedViewAnimations = true;
Winson Chung007c6982011-06-14 13:27:53 -0700211
Adam Cohen7d30a372013-07-01 17:03:59 -0700212 // The viewport whether the pages are to be contained (the actual view may be larger than the
213 // viewport)
214 private Rect mViewport = new Rect();
215
216 // Reordering
217 // We use the min scale to determine how much to expand the actually PagedView measured
218 // dimensions such that when we are zoomed out, the view is not clipped
219 private int REORDERING_DROP_REPOSITION_DURATION = 200;
220 protected int REORDERING_REORDER_REPOSITION_DURATION = 300;
221 protected int REORDERING_ZOOM_IN_OUT_DURATION = 250;
Adam Cohenf358a4b2013-07-23 16:47:31 -0700222 private int REORDERING_SIDE_PAGE_HOVER_TIMEOUT = 80;
Adam Cohen7d30a372013-07-01 17:03:59 -0700223 private float mMinScale = 1f;
Winson Chungc58497e2013-09-03 17:48:37 -0700224 private boolean mUseMinScale = false;
Adam Cohen7d30a372013-07-01 17:03:59 -0700225 protected View mDragView;
226 protected AnimatorSet mZoomInOutAnim;
227 private Runnable mSidePageHoverRunnable;
228 private int mSidePageHoverIndex = -1;
229 // This variable's scope is only for the duration of startReordering() and endReordering()
230 private boolean mReorderingStarted = false;
231 // This variable's scope is for the duration of startReordering() and after the zoomIn()
232 // animation after endReordering()
233 private boolean mIsReordering;
234 // The runnable that settles the page after snapToPage and animateDragViewToOriginalPosition
235 private int NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT = 2;
236 private int mPostReorderingPreZoomInRemainingAnimationCount;
237 private Runnable mPostReorderingPreZoomInRunnable;
238
Adam Cohen7d30a372013-07-01 17:03:59 -0700239 // Convenience/caching
240 private Matrix mTmpInvMatrix = new Matrix();
241 private float[] mTmpPoint = new float[2];
Winson Chungc9ca2982013-07-19 12:07:38 -0700242 private int[] mTmpIntPoint = new int[2];
Adam Cohen7d30a372013-07-01 17:03:59 -0700243 private Rect mTmpRect = new Rect();
244 private Rect mAltTmpRect = new Rect();
245
246 // Fling to delete
247 private int FLING_TO_DELETE_FADE_OUT_DURATION = 350;
248 private float FLING_TO_DELETE_FRICTION = 0.035f;
249 // The degrees specifies how much deviation from the up vector to still consider a fling "up"
250 private float FLING_TO_DELETE_MAX_FLING_DEGREES = 65f;
251 protected int mFlingToDeleteThresholdVelocity = -1400;
252 // Drag to delete
253 private boolean mDeferringForDelete = false;
254 private int DELETE_SLIDE_IN_SIDE_PAGE_DURATION = 250;
255 private int DRAG_TO_DELETE_FADE_OUT_DURATION = 350;
256
257 // Drop to delete
258 private View mDeleteDropTarget;
259
260 private boolean mAutoComputePageSpacing = false;
261 private boolean mRecomputePageSpacing = false;
262
263 // Bouncer
264 private boolean mTopAlignPageWhenShrinkingForBouncer = false;
Winson Chungb44b5242011-06-13 11:32:14 -0700265
John Spurlock77e1f472013-09-11 10:09:51 -0400266 protected final Rect mInsets = new Rect();
267
Michael Jurkafe0ace32013-10-03 01:05:14 -0700268 protected int mFirstChildLeft;
269
Winson Chung86f77532010-08-24 11:08:22 -0700270 public interface PageSwitchListener {
271 void onPageSwitch(View newPage, int newPageIndex);
Winson Chung321e9ee2010-08-09 13:37:56 -0700272 }
273
Winson Chung321e9ee2010-08-09 13:37:56 -0700274 public PagedView(Context context) {
275 this(context, null);
276 }
277
278 public PagedView(Context context, AttributeSet attrs) {
279 this(context, attrs, 0);
280 }
281
282 public PagedView(Context context, AttributeSet attrs, int defStyle) {
283 super(context, attrs, defStyle);
Winson Chungc9ca2982013-07-19 12:07:38 -0700284
Adam Cohen9c4949e2010-10-05 12:27:22 -0700285 TypedArray a = context.obtainStyledAttributes(attrs,
286 R.styleable.PagedView, defStyle, 0);
Adam Cohen60b07122011-11-14 17:26:06 -0800287 setPageSpacing(a.getDimensionPixelSize(R.styleable.PagedView_pageSpacing, 0));
Adam Cohen7d30a372013-07-01 17:03:59 -0700288 if (mPageSpacing < 0) {
289 mAutoComputePageSpacing = mRecomputePageSpacing = true;
290 }
Adam Cohen9c4949e2010-10-05 12:27:22 -0700291 mPageLayoutPaddingTop = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800292 R.styleable.PagedView_pageLayoutPaddingTop, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700293 mPageLayoutPaddingBottom = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800294 R.styleable.PagedView_pageLayoutPaddingBottom, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700295 mPageLayoutPaddingLeft = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800296 R.styleable.PagedView_pageLayoutPaddingLeft, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700297 mPageLayoutPaddingRight = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800298 R.styleable.PagedView_pageLayoutPaddingRight, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700299 mPageLayoutWidthGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700300 R.styleable.PagedView_pageLayoutWidthGap, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700301 mPageLayoutHeightGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700302 R.styleable.PagedView_pageLayoutHeightGap, 0);
Winson Chungd2be3812013-07-16 11:11:32 -0700303 mPageIndicatorViewId = a.getResourceId(R.styleable.PagedView_pageIndicator, -1);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700304 a.recycle();
305
Winson Chung321e9ee2010-08-09 13:37:56 -0700306 setHapticFeedbackEnabled(false);
Michael Jurka0142d492010-08-25 17:46:15 -0700307 init();
Winson Chung321e9ee2010-08-09 13:37:56 -0700308 }
309
310 /**
311 * Initializes various states for this workspace.
312 */
Michael Jurka0142d492010-08-25 17:46:15 -0700313 protected void init() {
Winson Chung86f77532010-08-24 11:08:22 -0700314 mDirtyPageContent = new ArrayList<Boolean>();
315 mDirtyPageContent.ensureCapacity(32);
Adam Cohene0f66b52010-11-23 15:06:07 -0800316 mScroller = new Scroller(getContext(), new ScrollInterpolator());
Winson Chung86f77532010-08-24 11:08:22 -0700317 mCurrentPage = 0;
Winson Chung7da10252010-10-28 16:07:04 -0700318 mCenterPagesVertically = true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700319
320 final ViewConfiguration configuration = ViewConfiguration.get(getContext());
Adam Cohen7d30a372013-07-01 17:03:59 -0700321 mTouchSlop = configuration.getScaledPagingTouchSlop();
Winson Chung321e9ee2010-08-09 13:37:56 -0700322 mPagingTouchSlop = configuration.getScaledPagingTouchSlop();
323 mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
Adam Cohenb5ba0972011-09-07 18:02:31 -0700324 mDensity = getResources().getDisplayMetrics().density;
Adam Cohen265b9a62011-12-07 14:37:18 -0800325
Adam Cohen7d30a372013-07-01 17:03:59 -0700326 // Scale the fling-to-delete threshold by the density
327 mFlingToDeleteThresholdVelocity =
328 (int) (mFlingToDeleteThresholdVelocity * mDensity);
329
Adam Cohen265b9a62011-12-07 14:37:18 -0800330 mFlingThresholdVelocity = (int) (FLING_THRESHOLD_VELOCITY * mDensity);
331 mMinFlingVelocity = (int) (MIN_FLING_VELOCITY * mDensity);
332 mMinSnapVelocity = (int) (MIN_SNAP_VELOCITY * mDensity);
Michael Jurka8b805b12012-04-18 14:23:14 -0700333 setOnHierarchyChangeListener(this);
Winson Chung321e9ee2010-08-09 13:37:56 -0700334 }
335
Winson Chungd2be3812013-07-16 11:11:32 -0700336 protected void onAttachedToWindow() {
337 // Hook up the page indicator
338 ViewGroup parent = (ViewGroup) getParent();
339 if (mPageIndicator == null && mPageIndicatorViewId > -1) {
340 mPageIndicator = (PageIndicator) parent.findViewById(mPageIndicatorViewId);
Winson Chungc58497e2013-09-03 17:48:37 -0700341 mPageIndicator.removeAllMarkers(mAllowPagedViewAnimations);
Winson Chung82dfe582013-07-26 15:07:49 -0700342
Winson Chung7819a562013-09-19 15:55:45 -0700343 ArrayList<PageIndicator.PageMarkerResources> markers =
344 new ArrayList<PageIndicator.PageMarkerResources>();
Winson Chung82dfe582013-07-26 15:07:49 -0700345 for (int i = 0; i < getChildCount(); ++i) {
346 markers.add(getPageIndicatorMarker(i));
347 }
Adam Cohenf358a4b2013-07-23 16:47:31 -0700348
Winson Chungc58497e2013-09-03 17:48:37 -0700349 mPageIndicator.addMarkers(markers, mAllowPagedViewAnimations);
Winson Chungd2be3812013-07-16 11:11:32 -0700350 }
351 }
352
353 protected void onDetachedFromWindow() {
354 // Unhook the page indicator
355 mPageIndicator = null;
356 }
357
Adam Cohen7d30a372013-07-01 17:03:59 -0700358 void setDeleteDropTarget(View v) {
359 mDeleteDropTarget = v;
360 }
361
362 // Convenience methods to map points from self to parent and vice versa
363 float[] mapPointFromViewToParent(View v, float x, float y) {
364 mTmpPoint[0] = x;
365 mTmpPoint[1] = y;
366 v.getMatrix().mapPoints(mTmpPoint);
367 mTmpPoint[0] += v.getLeft();
368 mTmpPoint[1] += v.getTop();
369 return mTmpPoint;
370 }
371 float[] mapPointFromParentToView(View v, float x, float y) {
372 mTmpPoint[0] = x - v.getLeft();
373 mTmpPoint[1] = y - v.getTop();
374 v.getMatrix().invert(mTmpInvMatrix);
375 mTmpInvMatrix.mapPoints(mTmpPoint);
376 return mTmpPoint;
377 }
378
379 void updateDragViewTranslationDuringDrag() {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700380 if (mDragView != null) {
381 float x = (mLastMotionX - mDownMotionX) + (getScrollX() - mDownScrollX) +
382 (mDragViewBaselineLeft - mDragView.getLeft());
383 float y = mLastMotionY - mDownMotionY;
384 mDragView.setTranslationX(x);
385 mDragView.setTranslationY(y);
Adam Cohen7d30a372013-07-01 17:03:59 -0700386
Adam Cohenf358a4b2013-07-23 16:47:31 -0700387 if (DEBUG) Log.d(TAG, "PagedView.updateDragViewTranslationDuringDrag(): "
388 + x + ", " + y);
389 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700390 }
391
392 public void setMinScale(float f) {
393 mMinScale = f;
Winson Chungc58497e2013-09-03 17:48:37 -0700394 mUseMinScale = true;
Adam Cohen7d30a372013-07-01 17:03:59 -0700395 requestLayout();
396 }
397
398 @Override
399 public void setScaleX(float scaleX) {
400 super.setScaleX(scaleX);
401 if (isReordering(true)) {
402 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
403 mLastMotionX = p[0];
404 mLastMotionY = p[1];
405 updateDragViewTranslationDuringDrag();
406 }
407 }
408
409 // Convenience methods to get the actual width/height of the PagedView (since it is measured
410 // to be larger to account for the minimum possible scale)
411 int getViewportWidth() {
412 return mViewport.width();
413 }
414 int getViewportHeight() {
415 return mViewport.height();
416 }
417
418 // Convenience methods to get the offset ASSUMING that we are centering the pages in the
419 // PagedView both horizontally and vertically
420 int getViewportOffsetX() {
421 return (getMeasuredWidth() - getViewportWidth()) / 2;
422 }
423
424 int getViewportOffsetY() {
425 return (getMeasuredHeight() - getViewportHeight()) / 2;
426 }
427
Adam Cohenedb40762013-07-18 16:45:45 -0700428 PageIndicator getPageIndicator() {
429 return mPageIndicator;
430 }
Winson Chung7819a562013-09-19 15:55:45 -0700431 protected PageIndicator.PageMarkerResources getPageIndicatorMarker(int pageIndex) {
432 return new PageIndicator.PageMarkerResources();
Winson Chung82dfe582013-07-26 15:07:49 -0700433 }
Adam Cohenedb40762013-07-18 16:45:45 -0700434
Winson Chung86f77532010-08-24 11:08:22 -0700435 public void setPageSwitchListener(PageSwitchListener pageSwitchListener) {
436 mPageSwitchListener = pageSwitchListener;
437 if (mPageSwitchListener != null) {
438 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700439 }
440 }
441
442 /**
Winson Chung52aee602013-01-30 12:01:02 -0800443 * Note: this is a reimplementation of View.isLayoutRtl() since that is currently hidden api.
444 */
445 public boolean isLayoutRtl() {
446 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
447 }
448
449 /**
Winson Chungf0ea4d32011-06-06 14:27:16 -0700450 * Called by subclasses to mark that data is ready, and that we can begin loading and laying
451 * out pages.
452 */
453 protected void setDataIsReady() {
454 mIsDataReady = true;
455 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700456
Winson Chungf0ea4d32011-06-06 14:27:16 -0700457 protected boolean isDataReady() {
458 return mIsDataReady;
459 }
460
461 /**
Winson Chung86f77532010-08-24 11:08:22 -0700462 * Returns the index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700463 *
Winson Chung86f77532010-08-24 11:08:22 -0700464 * @return The index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700465 */
Winson Chung86f77532010-08-24 11:08:22 -0700466 int getCurrentPage() {
467 return mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -0700468 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700469
Winson Chung360e63f2012-04-27 13:48:05 -0700470 int getNextPage() {
471 return (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
472 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700473
Winson Chung86f77532010-08-24 11:08:22 -0700474 int getPageCount() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700475 return getChildCount();
476 }
477
Winson Chung86f77532010-08-24 11:08:22 -0700478 View getPageAt(int index) {
Winson Chung321e9ee2010-08-09 13:37:56 -0700479 return getChildAt(index);
480 }
481
Adam Cohenae4f1552011-10-20 00:15:42 -0700482 protected int indexToPage(int index) {
483 return index;
484 }
485
Winson Chung321e9ee2010-08-09 13:37:56 -0700486 /**
Winson Chungbbc60d82010-11-11 16:34:41 -0800487 * Updates the scroll of the current page immediately to its final scroll position. We use this
488 * in CustomizePagedView to allow tabs to share the same PagedView while resetting the scroll of
489 * the previous tab page.
490 */
491 protected void updateCurrentPageScroll() {
Adam Cohen0ffac432013-07-10 11:19:26 -0700492 // If the current page is invalid, just reset the scroll position to zero
493 int newX = 0;
494 if (0 <= mCurrentPage && mCurrentPage < getPageCount()) {
Adam Cohenedb40762013-07-18 16:45:45 -0700495 newX = getScrollForPage(mCurrentPage);
Adam Cohen0ffac432013-07-10 11:19:26 -0700496 }
Winson Chungbbc60d82010-11-11 16:34:41 -0800497 scrollTo(newX, 0);
498 mScroller.setFinalX(newX);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800499 mScroller.forceFinished(true);
Winson Chungbbc60d82010-11-11 16:34:41 -0800500 }
501
502 /**
Chet Haasebc2f0822012-10-26 17:59:53 -0700503 * Called during AllApps/Home transitions to avoid unnecessary work. When that other animation
504 * ends, {@link #resumeScrolling()} should be called, along with
505 * {@link #updateCurrentPageScroll()} to correctly set the final state and re-enable scrolling.
506 */
507 void pauseScrolling() {
508 mScroller.forceFinished(true);
Chet Haasebc2f0822012-10-26 17:59:53 -0700509 }
510
511 /**
512 * Enables scrolling again.
513 * @see #pauseScrolling()
514 */
515 void resumeScrolling() {
Chet Haasebc2f0822012-10-26 17:59:53 -0700516 }
517 /**
Winson Chung86f77532010-08-24 11:08:22 -0700518 * Sets the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700519 */
Winson Chung86f77532010-08-24 11:08:22 -0700520 void setCurrentPage(int currentPage) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800521 if (!mScroller.isFinished()) {
522 mScroller.abortAnimation();
Adam Cohen97d53112013-10-01 11:07:24 -0700523 // We need to clean up the next page here to avoid computeScrollHelper from
524 // updating current page on the pass.
525 mNextPage = INVALID_PAGE;
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800526 }
Michael Jurkad3ef3062010-11-23 16:23:58 -0800527 // don't introduce any checks like mCurrentPage == currentPage here-- if we change the
528 // the default
529 if (getChildCount() == 0) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800530 return;
531 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700532
Adam Cohene61a9a22013-06-11 15:45:31 -0700533 mForceScreenScrolled = true;
Winson Chung86f77532010-08-24 11:08:22 -0700534 mCurrentPage = Math.max(0, Math.min(currentPage, getPageCount() - 1));
Winson Chung181c3dc2013-07-17 15:36:20 -0700535 updateCurrentPageScroll();
Winson Chung86f77532010-08-24 11:08:22 -0700536 notifyPageSwitchListener();
Winson Chunga12a2502010-12-20 14:41:35 -0800537 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -0700538 }
539
Winson Chung8c87cd82013-07-23 16:20:10 -0700540 /**
541 * The restore page will be set in place of the current page at the next (likely first)
542 * layout.
543 */
544 void setRestorePage(int restorePage) {
545 mRestorePage = restorePage;
546 }
547
Michael Jurka0142d492010-08-25 17:46:15 -0700548 protected void notifyPageSwitchListener() {
Winson Chung86f77532010-08-24 11:08:22 -0700549 if (mPageSwitchListener != null) {
550 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700551 }
Winson Chungd2be3812013-07-16 11:11:32 -0700552
553 // Update the page indicator (when we aren't reordering)
554 if (mPageIndicator != null && !isReordering(false)) {
555 mPageIndicator.setActiveMarker(getNextPage());
556 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700557 }
Michael Jurkace7e05f2011-02-01 22:02:35 -0800558 protected void pageBeginMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700559 if (!mIsPageMoving) {
560 mIsPageMoving = true;
561 onPageBeginMoving();
562 }
Patrick Dubroy1262e362010-10-06 15:49:50 -0700563 }
564
Michael Jurkace7e05f2011-02-01 22:02:35 -0800565 protected void pageEndMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700566 if (mIsPageMoving) {
567 mIsPageMoving = false;
568 onPageEndMoving();
569 }
Michael Jurka0142d492010-08-25 17:46:15 -0700570 }
571
Adam Cohen26976d92011-03-22 15:33:33 -0700572 protected boolean isPageMoving() {
573 return mIsPageMoving;
574 }
575
Michael Jurka0142d492010-08-25 17:46:15 -0700576 // a method that subclasses can override to add behavior
Patrick Dubroy1262e362010-10-06 15:49:50 -0700577 protected void onPageBeginMoving() {
578 }
579
580 // a method that subclasses can override to add behavior
581 protected void onPageEndMoving() {
Michael Jurka0142d492010-08-25 17:46:15 -0700582 }
583
Winson Chung321e9ee2010-08-09 13:37:56 -0700584 /**
Winson Chung86f77532010-08-24 11:08:22 -0700585 * Registers the specified listener on each page contained in this workspace.
Winson Chung321e9ee2010-08-09 13:37:56 -0700586 *
587 * @param l The listener used to respond to long clicks.
588 */
589 @Override
590 public void setOnLongClickListener(OnLongClickListener l) {
591 mLongClickListener = l;
Winson Chung86f77532010-08-24 11:08:22 -0700592 final int count = getPageCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700593 for (int i = 0; i < count; i++) {
Winson Chung86f77532010-08-24 11:08:22 -0700594 getPageAt(i).setOnLongClickListener(l);
Winson Chung321e9ee2010-08-09 13:37:56 -0700595 }
Adam Cohen1697b792013-09-17 19:08:21 -0700596 super.setOnLongClickListener(l);
Winson Chung321e9ee2010-08-09 13:37:56 -0700597 }
598
599 @Override
Adam Cohen68d73932010-11-15 10:50:58 -0800600 public void scrollBy(int x, int y) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700601 scrollTo(mUnboundedScrollX + x, getScrollY() + y);
Adam Cohen68d73932010-11-15 10:50:58 -0800602 }
603
604 @Override
Michael Jurka0142d492010-08-25 17:46:15 -0700605 public void scrollTo(int x, int y) {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700606 // In free scroll mode, we clamp the scrollX
607 if (mFreeScroll) {
608 x = Math.min(x, mFreeScrollMaxScrollX);
609 x = Math.max(x, mFreeScrollMinScrollX);
610 }
611
Adam Cohen0ffac432013-07-10 11:19:26 -0700612 final boolean isRtl = isLayoutRtl();
Adam Cohen68d73932010-11-15 10:50:58 -0800613 mUnboundedScrollX = x;
614
Adam Cohen0ffac432013-07-10 11:19:26 -0700615 boolean isXBeforeFirstPage = isRtl ? (x > mMaxScrollX) : (x < 0);
616 boolean isXAfterLastPage = isRtl ? (x < 0) : (x > mMaxScrollX);
617 if (isXBeforeFirstPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800618 super.scrollTo(0, y);
619 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700620 if (isRtl) {
621 overScroll(x - mMaxScrollX);
622 } else {
623 overScroll(x);
624 }
Adam Cohen68d73932010-11-15 10:50:58 -0800625 }
Adam Cohen0ffac432013-07-10 11:19:26 -0700626 } else if (isXAfterLastPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800627 super.scrollTo(mMaxScrollX, y);
628 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700629 if (isRtl) {
630 overScroll(x);
631 } else {
632 overScroll(x - mMaxScrollX);
633 }
Adam Cohen68d73932010-11-15 10:50:58 -0800634 }
635 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -0800636 mOverScrollX = x;
Adam Cohen68d73932010-11-15 10:50:58 -0800637 super.scrollTo(x, y);
638 }
639
Michael Jurka0142d492010-08-25 17:46:15 -0700640 mTouchX = x;
641 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
Adam Cohen7d30a372013-07-01 17:03:59 -0700642
643 // Update the last motion events when scrolling
644 if (isReordering(true)) {
645 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
646 mLastMotionX = p[0];
647 mLastMotionY = p[1];
648 updateDragViewTranslationDuringDrag();
649 }
Michael Jurka0142d492010-08-25 17:46:15 -0700650 }
651
652 // we moved this functionality to a helper function so SmoothPagedView can reuse it
653 protected boolean computeScrollHelper() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700654 if (mScroller.computeScrollOffset()) {
Winson Chung557d6ed2011-07-08 15:34:52 -0700655 // Don't bother scrolling if the page does not need to be moved
Michael Jurka8b805b12012-04-18 14:23:14 -0700656 if (getScrollX() != mScroller.getCurrX()
657 || getScrollY() != mScroller.getCurrY()
Michael Jurkab06d95f2012-04-02 06:26:53 -0700658 || mOverScrollX != mScroller.getCurrX()) {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700659 float scaleX = mFreeScroll ? getScaleX() : 1f;
660 int scrollX = (int) (mScroller.getCurrX() * (1 / scaleX));
661 scrollTo(scrollX, mScroller.getCurrY());
Winson Chung557d6ed2011-07-08 15:34:52 -0700662 }
Michael Jurka0142d492010-08-25 17:46:15 -0700663 invalidate();
664 return true;
Winson Chung86f77532010-08-24 11:08:22 -0700665 } else if (mNextPage != INVALID_PAGE) {
666 mCurrentPage = Math.max(0, Math.min(mNextPage, getPageCount() - 1));
Winson Chung86f77532010-08-24 11:08:22 -0700667 mNextPage = INVALID_PAGE;
Michael Jurka0142d492010-08-25 17:46:15 -0700668 notifyPageSwitchListener();
Winson Chungb44b5242011-06-13 11:32:14 -0700669
Winson Chung9c0565f2013-07-19 13:49:06 -0700670 // Load the associated pages if necessary
671 if (mDeferLoadAssociatedPagesUntilScrollCompletes) {
672 loadAssociatedPages(mCurrentPage);
673 mDeferLoadAssociatedPagesUntilScrollCompletes = false;
674 }
675
Adam Cohen73aa9752010-11-24 16:26:58 -0800676 // We don't want to trigger a page end moving unless the page has settled
677 // and the user has stopped scrolling
678 if (mTouchState == TOUCH_STATE_REST) {
679 pageEndMoving();
680 }
Winson Chungc27d1bb2011-09-29 12:07:42 -0700681
Adam Cohen7d30a372013-07-01 17:03:59 -0700682 onPostReorderingAnimationCompleted();
Adam Cohen0ffac432013-07-10 11:19:26 -0700683 // Notify the user when the page changes
684 AccessibilityManager accessibilityManager = (AccessibilityManager)
685 getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
686 if (accessibilityManager.isEnabled()) {
687 AccessibilityEvent ev =
688 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_SCROLLED);
689 ev.getText().add(getCurrentPageDescription());
690 sendAccessibilityEventUnchecked(ev);
691 }
Michael Jurka0142d492010-08-25 17:46:15 -0700692 return true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700693 }
Michael Jurka0142d492010-08-25 17:46:15 -0700694 return false;
695 }
696
697 @Override
698 public void computeScroll() {
699 computeScrollHelper();
Winson Chung321e9ee2010-08-09 13:37:56 -0700700 }
701
Adam Cohen7d30a372013-07-01 17:03:59 -0700702 protected boolean shouldSetTopAlignedPivotForWidget(int childIndex) {
703 return mTopAlignPageWhenShrinkingForBouncer;
704 }
705
Adam Cohen96d30a12013-07-16 18:13:21 -0700706 public static class LayoutParams extends ViewGroup.LayoutParams {
707 public boolean isFullScreenPage = false;
708
709 /**
710 * {@inheritDoc}
711 */
712 public LayoutParams(int width, int height) {
713 super(width, height);
714 }
715
716 public LayoutParams(ViewGroup.LayoutParams source) {
717 super(source);
718 }
719 }
720
721 protected LayoutParams generateDefaultLayoutParams() {
722 return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
723 }
724
Adam Cohenedb40762013-07-18 16:45:45 -0700725 public void addFullScreenPage(View page) {
Adam Cohen96d30a12013-07-16 18:13:21 -0700726 LayoutParams lp = generateDefaultLayoutParams();
727 lp.isFullScreenPage = true;
728 super.addView(page, 0, lp);
729 }
730
Adam Cohen410f3cd2013-09-22 12:09:32 -0700731 public int getNormalChildHeight() {
732 return mNormalChildHeight;
733 }
734
Winson Chung321e9ee2010-08-09 13:37:56 -0700735 @Override
736 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700737 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700738 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
739 return;
740 }
741
Adam Cohen7d30a372013-07-01 17:03:59 -0700742 // We measure the dimensions of the PagedView to be larger than the pages so that when we
743 // zoom out (and scale down), the view is still contained in the parent
Adam Cohen7d30a372013-07-01 17:03:59 -0700744 int widthMode = MeasureSpec.getMode(widthMeasureSpec);
745 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
746 int heightMode = MeasureSpec.getMode(heightMeasureSpec);
Winson Chung8aad6102012-05-11 16:27:49 -0700747 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
Adam Cohen7d30a372013-07-01 17:03:59 -0700748 // NOTE: We multiply by 1.5f to account for the fact that depending on the offset of the
749 // viewport, we can be at most one and a half screens offset once we scale down
750 DisplayMetrics dm = getResources().getDisplayMetrics();
Adam Cohendbdff6b2013-09-18 19:09:15 -0700751 int maxSize = Math.max(dm.widthPixels, dm.heightPixels + mInsets.top + mInsets.bottom);
Adam Cohen410f3cd2013-09-22 12:09:32 -0700752
Winson Chungc58497e2013-09-03 17:48:37 -0700753 int parentWidthSize, parentHeightSize;
754 int scaledWidthSize, scaledHeightSize;
755 if (mUseMinScale) {
756 parentWidthSize = (int) (1.5f * maxSize);
757 parentHeightSize = maxSize;
758 scaledWidthSize = (int) (parentWidthSize / mMinScale);
759 scaledHeightSize = (int) (parentHeightSize / mMinScale);
760 } else {
761 scaledWidthSize = widthSize;
762 scaledHeightSize = heightSize;
763 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700764 mViewport.set(0, 0, widthSize, heightSize);
765
766 if (widthMode == MeasureSpec.UNSPECIFIED || heightMode == MeasureSpec.UNSPECIFIED) {
767 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
768 return;
Winson Chung321e9ee2010-08-09 13:37:56 -0700769 }
770
Winson Chung8aad6102012-05-11 16:27:49 -0700771 // Return early if we aren't given a proper dimension
772 if (widthSize <= 0 || heightSize <= 0) {
773 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
774 return;
775 }
776
Adam Lesinski6b879f02010-11-04 16:15:23 -0700777 /* Allow the height to be set as WRAP_CONTENT. This allows the particular case
778 * of the All apps view on XLarge displays to not take up more space then it needs. Width
779 * is still not allowed to be set as WRAP_CONTENT since many parts of the code expect
780 * each page to have the same width.
781 */
Michael Jurka8b805b12012-04-18 14:23:14 -0700782 final int verticalPadding = getPaddingTop() + getPaddingBottom();
783 final int horizontalPadding = getPaddingLeft() + getPaddingRight();
Winson Chung321e9ee2010-08-09 13:37:56 -0700784
785 // The children are given the same width and height as the workspace
Michael Jurka5f1c5092010-09-03 14:15:02 -0700786 // unless they were set to WRAP_CONTENT
Winson Chung785d2eb2011-04-14 16:08:02 -0700787 if (DEBUG) Log.d(TAG, "PagedView.onMeasure(): " + widthSize + ", " + heightSize);
Adam Cohen7d30a372013-07-01 17:03:59 -0700788 if (DEBUG) Log.d(TAG, "PagedView.scaledSize: " + scaledWidthSize + ", " + scaledHeightSize);
789 if (DEBUG) Log.d(TAG, "PagedView.parentSize: " + parentWidthSize + ", " + parentHeightSize);
790 if (DEBUG) Log.d(TAG, "PagedView.horizontalPadding: " + horizontalPadding);
791 if (DEBUG) Log.d(TAG, "PagedView.verticalPadding: " + verticalPadding);
Winson Chung321e9ee2010-08-09 13:37:56 -0700792 final int childCount = getChildCount();
793 for (int i = 0; i < childCount; i++) {
Michael Jurka5f1c5092010-09-03 14:15:02 -0700794 // disallowing padding in paged view (just pass 0)
Adam Cohen22f823d2011-09-01 17:22:18 -0700795 final View child = getPageAt(i);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700796 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
797
798 int childWidthMode;
Adam Cohen96d30a12013-07-16 18:13:21 -0700799 int childHeightMode;
800 int childWidth;
801 int childHeight;
802
803 if (!lp.isFullScreenPage) {
804 if (lp.width == LayoutParams.WRAP_CONTENT) {
805 childWidthMode = MeasureSpec.AT_MOST;
806 } else {
807 childWidthMode = MeasureSpec.EXACTLY;
808 }
809
810 if (lp.height == LayoutParams.WRAP_CONTENT) {
811 childHeightMode = MeasureSpec.AT_MOST;
812 } else {
813 childHeightMode = MeasureSpec.EXACTLY;
814 }
815
816 childWidth = widthSize - horizontalPadding;
John Spurlock77e1f472013-09-11 10:09:51 -0400817 childHeight = heightSize - verticalPadding - mInsets.top - mInsets.bottom;
Adam Cohen410f3cd2013-09-22 12:09:32 -0700818 mNormalChildHeight = childHeight;
Adam Cohen96d30a12013-07-16 18:13:21 -0700819
Michael Jurka5f1c5092010-09-03 14:15:02 -0700820 } else {
821 childWidthMode = MeasureSpec.EXACTLY;
Michael Jurka5f1c5092010-09-03 14:15:02 -0700822 childHeightMode = MeasureSpec.EXACTLY;
Adam Cohen96d30a12013-07-16 18:13:21 -0700823
Winson Chungc58497e2013-09-03 17:48:37 -0700824 if (mUseMinScale) {
825 childWidth = getViewportWidth();
826 childHeight = getViewportHeight();
827 } else {
828 childWidth = widthSize - getPaddingLeft() - getPaddingRight();
829 childHeight = heightSize - getPaddingTop() - getPaddingBottom();
830 }
Michael Jurka5f1c5092010-09-03 14:15:02 -0700831 }
832
833 final int childWidthMeasureSpec =
Adam Cohen96d30a12013-07-16 18:13:21 -0700834 MeasureSpec.makeMeasureSpec(childWidth, childWidthMode);
835 final int childHeightMeasureSpec =
836 MeasureSpec.makeMeasureSpec(childHeight, childHeightMode);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700837 child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700838 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700839 setMeasuredDimension(scaledWidthSize, scaledHeightSize);
Winson Chungae890b82011-09-13 18:08:54 -0700840
Winson Chunga128a7b2012-04-30 15:23:15 -0700841 if (childCount > 0) {
Winson Chunga128a7b2012-04-30 15:23:15 -0700842 // Calculate the variable page spacing if necessary
Adam Cohen7d30a372013-07-01 17:03:59 -0700843 if (mAutoComputePageSpacing && mRecomputePageSpacing) {
Winson Chunga128a7b2012-04-30 15:23:15 -0700844 // The gap between pages in the PagedView should be equal to the gap from the page
845 // to the edge of the screen (so it is not visible in the current screen). To
846 // account for unequal padding on each side of the paged view, we take the maximum
847 // of the left/right gap and use that as the gap between each page.
Adam Cohenedb40762013-07-18 16:45:45 -0700848 int offset = (getViewportWidth() - getChildWidth(0)) / 2;
Winson Chunga128a7b2012-04-30 15:23:15 -0700849 int spacing = Math.max(offset, widthSize - offset -
850 getChildAt(0).getMeasuredWidth());
851 setPageSpacing(spacing);
Adam Cohen7d30a372013-07-01 17:03:59 -0700852 mRecomputePageSpacing = false;
Winson Chunga128a7b2012-04-30 15:23:15 -0700853 }
854 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700855 }
856
Adam Cohen60b07122011-11-14 17:26:06 -0800857 public void setPageSpacing(int pageSpacing) {
858 mPageSpacing = pageSpacing;
Adam Cohenedb40762013-07-18 16:45:45 -0700859 requestLayout();
Adam Cohen60b07122011-11-14 17:26:06 -0800860 }
861
Michael Jurkafe0ace32013-10-03 01:05:14 -0700862 protected int getFirstChildLeft() {
863 return mFirstChildLeft;
864 }
865
Winson Chung321e9ee2010-08-09 13:37:56 -0700866 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -0700867 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700868 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700869 return;
870 }
871
Winson Chung785d2eb2011-04-14 16:08:02 -0700872 if (DEBUG) Log.d(TAG, "PagedView.onLayout()");
Winson Chung321e9ee2010-08-09 13:37:56 -0700873 final int childCount = getChildCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700874
Adam Cohenedb40762013-07-18 16:45:45 -0700875 int screenWidth = getViewportWidth();
876
Adam Cohen7d30a372013-07-01 17:03:59 -0700877 int offsetX = getViewportOffsetX();
878 int offsetY = getViewportOffsetY();
879
880 // Update the viewport offsets
881 mViewport.offset(offsetX, offsetY);
882
Adam Cohen0ffac432013-07-10 11:19:26 -0700883 final boolean isRtl = isLayoutRtl();
884
885 final int startIndex = isRtl ? childCount - 1 : 0;
886 final int endIndex = isRtl ? -1 : childCount;
887 final int delta = isRtl ? -1 : 1;
888
Adam Cohen7d30a372013-07-01 17:03:59 -0700889 int verticalPadding = getPaddingTop() + getPaddingBottom();
Adam Cohenedb40762013-07-18 16:45:45 -0700890
Michael Jurkafe0ace32013-10-03 01:05:14 -0700891 int childLeft = mFirstChildLeft = offsetX + (screenWidth - getChildWidth(startIndex)) / 2;
Adam Cohenedb40762013-07-18 16:45:45 -0700892 if (mPageScrolls == null || getChildCount() != mChildCountOnLastLayout) {
893 mPageScrolls = new int[getChildCount()];
894 }
895
Adam Cohen0ffac432013-07-10 11:19:26 -0700896 for (int i = startIndex; i != endIndex; i += delta) {
Adam Cohen22f823d2011-09-01 17:22:18 -0700897 final View child = getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -0700898 LayoutParams lp = (LayoutParams) child.getLayoutParams();
899 int childTop;
Adam Cohen96d30a12013-07-16 18:13:21 -0700900 if (lp.isFullScreenPage) {
901 childTop = offsetY;
902 } else {
John Spurlock77e1f472013-09-11 10:09:51 -0400903 childTop = offsetY + getPaddingTop() + mInsets.top;
Adam Cohen96d30a12013-07-16 18:13:21 -0700904 if (mCenterPagesVertically) {
John Spurlock77e1f472013-09-11 10:09:51 -0400905 childTop += (getViewportHeight() - mInsets.top - mInsets.bottom - verticalPadding - child.getMeasuredHeight()) / 2;
Adam Cohen96d30a12013-07-16 18:13:21 -0700906 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700907 }
Adam Cohen96d30a12013-07-16 18:13:21 -0700908
Winson Chung321e9ee2010-08-09 13:37:56 -0700909 if (child.getVisibility() != View.GONE) {
Adam Cohen96d30a12013-07-16 18:13:21 -0700910 final int childWidth = child.getMeasuredWidth();
Adam Lesinski6b879f02010-11-04 16:15:23 -0700911 final int childHeight = child.getMeasuredHeight();
Michael Jurkad3ef3062010-11-23 16:23:58 -0800912
Winson Chung785d2eb2011-04-14 16:08:02 -0700913 if (DEBUG) Log.d(TAG, "\tlayout-child" + i + ": " + childLeft + ", " + childTop);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700914 child.layout(childLeft, childTop,
Michael Jurkad3ef3062010-11-23 16:23:58 -0800915 childLeft + child.getMeasuredWidth(), childTop + childHeight);
Adam Cohenedb40762013-07-18 16:45:45 -0700916
917 // We assume the left and right padding are equal, and hence center the pages
918 // horizontally
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700919 int scrollOffset = (getViewportWidth() - childWidth) / 2;
Adam Cohenedb40762013-07-18 16:45:45 -0700920 mPageScrolls[i] = childLeft - scrollOffset - offsetX;
921
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700922 if (i != endIndex - delta) {
Adam Cohenaf9b0e52013-09-23 19:27:38 -0700923 childLeft += childWidth + scrollOffset;
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700924 int nextScrollOffset = (getViewportWidth() - getChildWidth(i + delta)) / 2;
Adam Cohenaf9b0e52013-09-23 19:27:38 -0700925 childLeft += nextScrollOffset;
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700926 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700927 }
928 }
Winson Chungc3665fa2011-09-14 17:56:27 -0700929
930 if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) {
931 setHorizontalScrollBarEnabled(false);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800932 updateCurrentPageScroll();
Winson Chungc3665fa2011-09-14 17:56:27 -0700933 setHorizontalScrollBarEnabled(true);
934 mFirstLayout = false;
935 }
Adam Cohenf698c6e2013-07-17 18:44:25 -0700936
937 if (childCount > 0) {
938 final int index = isLayoutRtl() ? 0 : childCount - 1;
Adam Cohenedb40762013-07-18 16:45:45 -0700939 mMaxScrollX = getScrollForPage(index);
Adam Cohenf698c6e2013-07-17 18:44:25 -0700940 } else {
941 mMaxScrollX = 0;
942 }
943
944 if (mScroller.isFinished() && mChildCountOnLastLayout != getChildCount() &&
945 !mDeferringForDelete) {
Winson Chung8c87cd82013-07-23 16:20:10 -0700946 if (mRestorePage > -1) {
947 setCurrentPage(mRestorePage);
948 mRestorePage = -1;
949 } else {
950 setCurrentPage(getNextPage());
951 }
Adam Cohenf698c6e2013-07-17 18:44:25 -0700952 }
953 mChildCountOnLastLayout = getChildCount();
Adam Cohenf358a4b2013-07-23 16:47:31 -0700954
955 if (isReordering(true)) {
956 updateDragViewTranslationDuringDrag();
957 }
Winson Chunge3193b92010-09-10 11:44:42 -0700958 }
959
Adam Cohenf34bab52010-09-30 14:11:56 -0700960 protected void screenScrolled(int screenCenter) {
Michael Jurka869390b2012-05-06 15:55:19 -0700961 boolean isInOverscroll = mOverScrollX < 0 || mOverScrollX > mMaxScrollX;
962
963 if (mFadeInAdjacentScreens && !isInOverscroll) {
Adam Cohen73894962011-10-31 13:17:17 -0700964 for (int i = 0; i < getChildCount(); i++) {
965 View child = getChildAt(i);
966 if (child != null) {
967 float scrollProgress = getScrollProgress(screenCenter, child, i);
968 float alpha = 1 - Math.abs(scrollProgress);
Michael Jurka7372c592012-01-16 04:21:35 -0800969 child.setAlpha(alpha);
Adam Cohen73894962011-10-31 13:17:17 -0700970 }
971 }
972 invalidate();
973 }
Adam Cohenf34bab52010-09-30 14:11:56 -0700974 }
975
Winson Chungc58497e2013-09-03 17:48:37 -0700976 protected void enablePagedViewAnimations() {
977 mAllowPagedViewAnimations = true;
978
979 }
980 protected void disablePagedViewAnimations() {
981 mAllowPagedViewAnimations = false;
982 }
983
Winson Chunge3193b92010-09-10 11:44:42 -0700984 @Override
Michael Jurka8b805b12012-04-18 14:23:14 -0700985 public void onChildViewAdded(View parent, View child) {
Winson Chungd2be3812013-07-16 11:11:32 -0700986 // Update the page indicator, we don't update the page indicator as we
987 // add/remove pages
988 if (mPageIndicator != null && !isReordering(false)) {
Winson Chung82dfe582013-07-26 15:07:49 -0700989 int pageIndex = indexOfChild(child);
Winson Chung7819a562013-09-19 15:55:45 -0700990 mPageIndicator.addMarker(pageIndex,
991 getPageIndicatorMarker(pageIndex),
Winson Chungc58497e2013-09-03 17:48:37 -0700992 mAllowPagedViewAnimations);
Winson Chungd2be3812013-07-16 11:11:32 -0700993 }
994
Adam Cohen2591f6a2011-10-25 14:36:40 -0700995 // This ensures that when children are added, they get the correct transforms / alphas
996 // in accordance with any scroll effects.
997 mForceScreenScrolled = true;
Adam Cohen7d30a372013-07-01 17:03:59 -0700998 mRecomputePageSpacing = true;
Adam Cohen7a9e58a2013-10-01 18:02:13 -0700999 updateFreescrollBounds();
Adam Cohen2591f6a2011-10-25 14:36:40 -07001000 invalidate();
1001 }
1002
Michael Jurka8b805b12012-04-18 14:23:14 -07001003 @Override
1004 public void onChildViewRemoved(View parent, View child) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001005 mForceScreenScrolled = true;
Adam Cohen7a9e58a2013-10-01 18:02:13 -07001006 updateFreescrollBounds();
Adam Cohen7d30a372013-07-01 17:03:59 -07001007 invalidate();
Michael Jurka8b805b12012-04-18 14:23:14 -07001008 }
1009
Winson Chungd2be3812013-07-16 11:11:32 -07001010 private void removeMarkerForView(int index) {
1011 // Update the page indicator, we don't update the page indicator as we
1012 // add/remove pages
1013 if (mPageIndicator != null && !isReordering(false)) {
Winson Chungc58497e2013-09-03 17:48:37 -07001014 mPageIndicator.removeMarker(index, mAllowPagedViewAnimations);
Winson Chungd2be3812013-07-16 11:11:32 -07001015 }
1016 }
1017
1018 @Override
1019 public void removeView(View v) {
1020 // XXX: We should find a better way to hook into this before the view
1021 // gets removed form its parent...
1022 removeMarkerForView(indexOfChild(v));
1023 super.removeView(v);
1024 }
1025 @Override
1026 public void removeViewInLayout(View v) {
1027 // XXX: We should find a better way to hook into this before the view
1028 // gets removed form its parent...
1029 removeMarkerForView(indexOfChild(v));
1030 super.removeViewInLayout(v);
1031 }
1032 @Override
1033 public void removeViewAt(int index) {
1034 // XXX: We should find a better way to hook into this before the view
1035 // gets removed form its parent...
1036 removeViewAt(index);
1037 super.removeViewAt(index);
1038 }
1039 @Override
1040 public void removeAllViewsInLayout() {
1041 // Update the page indicator, we don't update the page indicator as we
1042 // add/remove pages
1043 if (mPageIndicator != null) {
Winson Chungc58497e2013-09-03 17:48:37 -07001044 mPageIndicator.removeAllMarkers(mAllowPagedViewAnimations);
Winson Chungd2be3812013-07-16 11:11:32 -07001045 }
1046
1047 super.removeAllViewsInLayout();
1048 }
1049
Adam Cohen73894962011-10-31 13:17:17 -07001050 protected int getChildOffset(int index) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001051 if (index < 0 || index > getChildCount() - 1) return 0;
1052
Adam Cohenf698c6e2013-07-17 18:44:25 -07001053 int offset = getPageAt(index).getLeft() - getViewportOffsetX();
Adam Cohen73894962011-10-31 13:17:17 -07001054
Adam Cohenf698c6e2013-07-17 18:44:25 -07001055 return offset;
Adam Cohen73894962011-10-31 13:17:17 -07001056 }
1057
Adam Cohenf358a4b2013-07-23 16:47:31 -07001058 protected void getOverviewModePages(int[] range) {
Winson Chungc9ca2982013-07-19 12:07:38 -07001059 range[0] = 0;
Adam Cohen1f1f45d2013-10-02 09:40:18 -07001060 range[1] = Math.max(0, getChildCount() - 1);
Adam Cohen7d30a372013-07-01 17:03:59 -07001061 }
1062
Michael Jurkadde558b2011-11-09 22:09:06 -08001063 protected void getVisiblePages(int[] range) {
Michael Jurka0142d492010-08-25 17:46:15 -07001064 final int pageCount = getChildCount();
Winson Chungc9ca2982013-07-19 12:07:38 -07001065 mTmpIntPoint[0] = mTmpIntPoint[1] = 0;
Michael Jurka4ff7d792012-04-02 03:46:50 -07001066
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001067 range[0] = -1;
1068 range[1] = -1;
1069
Michael Jurkac4fb9172010-09-02 17:19:20 -07001070 if (pageCount > 0) {
Winson Chungc9ca2982013-07-19 12:07:38 -07001071 int viewportWidth = getViewportWidth();
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001072 int curScreen = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -07001073
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001074 int count = getChildCount();
1075 for (int i = 0; i < count; i++) {
1076 View currPage = getPageAt(i);
Winson Chungc9ca2982013-07-19 12:07:38 -07001077
Winson Chungc9ca2982013-07-19 12:07:38 -07001078 mTmpIntPoint[0] = 0;
Winson Chungc763c4e2013-07-19 13:49:06 -07001079 Utilities.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false);
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001080 if (mTmpIntPoint[0] > viewportWidth) {
1081 if (range[0] == -1) {
1082 continue;
1083 } else {
1084 break;
1085 }
1086 }
1087
Adam Cohen6a678da2013-09-24 10:58:01 -07001088 mTmpIntPoint[0] = currPage.getMeasuredWidth();
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001089 Utilities.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false);
1090 if (mTmpIntPoint[0] < 0) {
1091 if (range[0] == -1) {
1092 continue;
1093 } else {
1094 break;
1095 }
1096 }
1097 curScreen = i;
1098 if (range[0] < 0) {
1099 range[0] = curScreen;
Winson Chungc9ca2982013-07-19 12:07:38 -07001100 }
1101 }
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001102
1103 range[1] = curScreen;
Michael Jurkadde558b2011-11-09 22:09:06 -08001104 } else {
1105 range[0] = -1;
1106 range[1] = -1;
1107 }
1108 }
1109
Michael Jurka920d7f42012-05-14 16:29:55 -07001110 protected boolean shouldDrawChild(View child) {
Adam Cohenf3434992013-09-16 16:52:59 -07001111 return child.getAlpha() > 0 && child.getVisibility() == VISIBLE;
Michael Jurka920d7f42012-05-14 16:29:55 -07001112 }
1113
Michael Jurkadde558b2011-11-09 22:09:06 -08001114 @Override
1115 protected void dispatchDraw(Canvas canvas) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001116 int halfScreenSize = getViewportWidth() / 2;
Michael Jurka8b805b12012-04-18 14:23:14 -07001117 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range.
1118 // Otherwise it is equal to the scaled overscroll position.
Adam Cohenebea84d2011-11-09 17:20:41 -08001119 int screenCenter = mOverScrollX + halfScreenSize;
Michael Jurkadde558b2011-11-09 22:09:06 -08001120
1121 if (screenCenter != mLastScreenCenter || mForceScreenScrolled) {
Michael Jurkab06d95f2012-04-02 06:26:53 -07001122 // set mForceScreenScrolled before calling screenScrolled so that screenScrolled can
1123 // set it for the next frame
1124 mForceScreenScrolled = false;
Michael Jurkadde558b2011-11-09 22:09:06 -08001125 screenScrolled(screenCenter);
1126 mLastScreenCenter = screenCenter;
Michael Jurkadde558b2011-11-09 22:09:06 -08001127 }
1128
1129 // Find out which screens are visible; as an optimization we only call draw on them
1130 final int pageCount = getChildCount();
1131 if (pageCount > 0) {
1132 getVisiblePages(mTempVisiblePagesRange);
1133 final int leftScreen = mTempVisiblePagesRange[0];
1134 final int rightScreen = mTempVisiblePagesRange[1];
Winson Chungc6f10b92011-11-14 11:39:07 -08001135 if (leftScreen != -1 && rightScreen != -1) {
1136 final long drawingTime = getDrawingTime();
1137 // Clip to the bounds
1138 canvas.save();
Michael Jurka8b805b12012-04-18 14:23:14 -07001139 canvas.clipRect(getScrollX(), getScrollY(), getScrollX() + getRight() - getLeft(),
1140 getScrollY() + getBottom() - getTop());
Michael Jurka0142d492010-08-25 17:46:15 -07001141
Adam Cohen7d30a372013-07-01 17:03:59 -07001142 // Draw all the children, leaving the drag view for last
1143 for (int i = pageCount - 1; i >= 0; i--) {
Michael Jurka80c69852011-12-16 14:16:32 -08001144 final View v = getPageAt(i);
Adam Cohen7d30a372013-07-01 17:03:59 -07001145 if (v == mDragView) continue;
Michael Jurka5e368ff2012-05-14 23:13:15 -07001146 if (mForceDrawAllChildrenNextFrame ||
1147 (leftScreen <= i && i <= rightScreen && shouldDrawChild(v))) {
Michael Jurka80c69852011-12-16 14:16:32 -08001148 drawChild(canvas, v, drawingTime);
Michael Jurka80c69852011-12-16 14:16:32 -08001149 }
Winson Chungc6f10b92011-11-14 11:39:07 -08001150 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001151 // Draw the drag view on top (if there is one)
1152 if (mDragView != null) {
1153 drawChild(canvas, mDragView, drawingTime);
1154 }
1155
Michael Jurka5e368ff2012-05-14 23:13:15 -07001156 mForceDrawAllChildrenNextFrame = false;
Winson Chungc6f10b92011-11-14 11:39:07 -08001157 canvas.restore();
Michael Jurkac4fb9172010-09-02 17:19:20 -07001158 }
Michael Jurka0142d492010-08-25 17:46:15 -07001159 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001160 }
1161
1162 @Override
1163 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
Adam Cohenae4f1552011-10-20 00:15:42 -07001164 int page = indexToPage(indexOfChild(child));
Winson Chung86f77532010-08-24 11:08:22 -07001165 if (page != mCurrentPage || !mScroller.isFinished()) {
1166 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001167 return true;
1168 }
1169 return false;
1170 }
1171
1172 @Override
1173 protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
Winson Chung86f77532010-08-24 11:08:22 -07001174 int focusablePage;
1175 if (mNextPage != INVALID_PAGE) {
1176 focusablePage = mNextPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001177 } else {
Winson Chung86f77532010-08-24 11:08:22 -07001178 focusablePage = mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001179 }
Winson Chung86f77532010-08-24 11:08:22 -07001180 View v = getPageAt(focusablePage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001181 if (v != null) {
Adam Cohen76fc0852011-06-17 13:26:23 -07001182 return v.requestFocus(direction, previouslyFocusedRect);
Winson Chung321e9ee2010-08-09 13:37:56 -07001183 }
1184 return false;
1185 }
1186
1187 @Override
1188 public boolean dispatchUnhandledMove(View focused, int direction) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001189 // XXX-RTL: This will be fixed in a future CL
Winson Chung321e9ee2010-08-09 13:37:56 -07001190 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001191 if (getCurrentPage() > 0) {
1192 snapToPage(getCurrentPage() - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001193 return true;
1194 }
1195 } else if (direction == View.FOCUS_RIGHT) {
Winson Chung86f77532010-08-24 11:08:22 -07001196 if (getCurrentPage() < getPageCount() - 1) {
1197 snapToPage(getCurrentPage() + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001198 return true;
1199 }
1200 }
1201 return super.dispatchUnhandledMove(focused, direction);
1202 }
1203
1204 @Override
1205 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001206 // XXX-RTL: This will be fixed in a future CL
Winson Chung86f77532010-08-24 11:08:22 -07001207 if (mCurrentPage >= 0 && mCurrentPage < getPageCount()) {
alanvaf519952012-05-07 17:33:22 -07001208 getPageAt(mCurrentPage).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001209 }
1210 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001211 if (mCurrentPage > 0) {
alanvaf519952012-05-07 17:33:22 -07001212 getPageAt(mCurrentPage - 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001213 }
1214 } else if (direction == View.FOCUS_RIGHT){
Winson Chung86f77532010-08-24 11:08:22 -07001215 if (mCurrentPage < getPageCount() - 1) {
alanvaf519952012-05-07 17:33:22 -07001216 getPageAt(mCurrentPage + 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001217 }
1218 }
1219 }
1220
1221 /**
1222 * If one of our descendant views decides that it could be focused now, only
Winson Chung86f77532010-08-24 11:08:22 -07001223 * pass that along if it's on the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001224 *
Winson Chung86f77532010-08-24 11:08:22 -07001225 * This happens when live folders requery, and if they're off page, they
1226 * end up calling requestFocus, which pulls it on page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001227 */
1228 @Override
1229 public void focusableViewAvailable(View focused) {
Winson Chung86f77532010-08-24 11:08:22 -07001230 View current = getPageAt(mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001231 View v = focused;
1232 while (true) {
1233 if (v == current) {
1234 super.focusableViewAvailable(focused);
1235 return;
1236 }
1237 if (v == this) {
1238 return;
1239 }
1240 ViewParent parent = v.getParent();
1241 if (parent instanceof View) {
1242 v = (View)v.getParent();
1243 } else {
1244 return;
1245 }
1246 }
1247 }
1248
1249 /**
1250 * {@inheritDoc}
1251 */
1252 @Override
1253 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
1254 if (disallowIntercept) {
1255 // We need to make sure to cancel our long press if
1256 // a scrollable widget takes over touch events
Adam Cohen22f823d2011-09-01 17:22:18 -07001257 final View currentPage = getPageAt(mCurrentPage);
Winson Chung86f77532010-08-24 11:08:22 -07001258 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001259 }
1260 super.requestDisallowInterceptTouchEvent(disallowIntercept);
1261 }
1262
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001263 /**
1264 * Return true if a tap at (x, y) should trigger a flip to the previous page.
1265 */
1266 protected boolean hitsPreviousPage(float x, float y) {
Adam Cohenedb40762013-07-18 16:45:45 -07001267 int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2;
Adam Cohen0ffac432013-07-10 11:19:26 -07001268 if (isLayoutRtl()) {
1269 return (x > (getViewportOffsetX() + getViewportWidth() -
Adam Cohenedb40762013-07-18 16:45:45 -07001270 offset + mPageSpacing));
Adam Cohen0ffac432013-07-10 11:19:26 -07001271 }
Adam Cohenedb40762013-07-18 16:45:45 -07001272 return (x < getViewportOffsetX() + offset - mPageSpacing);
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001273 }
1274
1275 /**
1276 * Return true if a tap at (x, y) should trigger a flip to the next page.
1277 */
1278 protected boolean hitsNextPage(float x, float y) {
Adam Cohenedb40762013-07-18 16:45:45 -07001279 int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2;
Adam Cohen0ffac432013-07-10 11:19:26 -07001280 if (isLayoutRtl()) {
Adam Cohenedb40762013-07-18 16:45:45 -07001281 return (x < getViewportOffsetX() + offset - mPageSpacing);
Adam Cohen0ffac432013-07-10 11:19:26 -07001282 }
1283 return (x > (getViewportOffsetX() + getViewportWidth() -
Adam Cohenedb40762013-07-18 16:45:45 -07001284 offset + mPageSpacing));
Adam Cohen7d30a372013-07-01 17:03:59 -07001285 }
Winson Chung52aee602013-01-30 12:01:02 -08001286
Adam Cohen7d30a372013-07-01 17:03:59 -07001287 /** Returns whether x and y originated within the buffered viewport */
1288 private boolean isTouchPointInViewportWithBuffer(int x, int y) {
1289 mTmpRect.set(mViewport.left - mViewport.width() / 2, mViewport.top,
1290 mViewport.right + mViewport.width() / 2, mViewport.bottom);
1291 return mTmpRect.contains(x, y);
1292 }
1293
Winson Chung321e9ee2010-08-09 13:37:56 -07001294 @Override
1295 public boolean onInterceptTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001296 if (DISABLE_TOUCH_INTERACTION) {
1297 return false;
1298 }
1299
Winson Chung321e9ee2010-08-09 13:37:56 -07001300 /*
1301 * This method JUST determines whether we want to intercept the motion.
1302 * If we return true, onTouchEvent will be called and we do the actual
1303 * scrolling there.
1304 */
Adam Cohen6342bba2011-03-10 11:33:35 -08001305 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001306
Winson Chung45e1d6e2010-11-09 17:19:49 -08001307 // Skip touch handling if there are no pages to swipe
1308 if (getChildCount() <= 0) return super.onInterceptTouchEvent(ev);
1309
Winson Chung321e9ee2010-08-09 13:37:56 -07001310 /*
1311 * Shortcut the most recurring case: the user is in the dragging
1312 * state and he is moving his finger. We want to intercept this
1313 * motion.
1314 */
1315 final int action = ev.getAction();
1316 if ((action == MotionEvent.ACTION_MOVE) &&
1317 (mTouchState == TOUCH_STATE_SCROLLING)) {
1318 return true;
1319 }
1320
Winson Chung321e9ee2010-08-09 13:37:56 -07001321 switch (action & MotionEvent.ACTION_MASK) {
1322 case MotionEvent.ACTION_MOVE: {
1323 /*
1324 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
1325 * whether the user has moved far enough from his original down touch.
1326 */
Michael Jurka1ff706b2010-09-14 17:35:20 -07001327 if (mActivePointerId != INVALID_POINTER) {
1328 determineScrollingStart(ev);
Michael Jurka1ff706b2010-09-14 17:35:20 -07001329 }
1330 // if mActivePointerId is INVALID_POINTER, then we must have missed an ACTION_DOWN
1331 // event. in that case, treat the first occurence of a move event as a ACTION_DOWN
1332 // i.e. fall through to the next case (don't break)
1333 // (We sometimes miss ACTION_DOWN events in Workspace because it ignores all events
1334 // while it's small- this was causing a crash before we checked for INVALID_POINTER)
Adam Cohen93c97562013-09-26 13:48:01 -07001335 break;
Winson Chung321e9ee2010-08-09 13:37:56 -07001336 }
1337
1338 case MotionEvent.ACTION_DOWN: {
1339 final float x = ev.getX();
1340 final float y = ev.getY();
1341 // Remember location of down touch
1342 mDownMotionX = x;
Adam Cohen7d30a372013-07-01 17:03:59 -07001343 mDownMotionY = y;
1344 mDownScrollX = getScrollX();
Winson Chung321e9ee2010-08-09 13:37:56 -07001345 mLastMotionX = x;
1346 mLastMotionY = y;
Adam Cohen7d30a372013-07-01 17:03:59 -07001347 float[] p = mapPointFromViewToParent(this, x, y);
1348 mParentDownMotionX = p[0];
1349 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001350 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001351 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001352 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001353
Winson Chung321e9ee2010-08-09 13:37:56 -07001354 /*
1355 * If being flinged and user touches the screen, initiate drag;
1356 * otherwise don't. mScroller.isFinished should be false when
1357 * being flinged.
1358 */
Michael Jurkafd177c12010-10-19 15:50:43 -07001359 final int xDist = Math.abs(mScroller.getFinalX() - mScroller.getCurrX());
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001360 final boolean finishedScrolling = (mScroller.isFinished() || xDist < mTouchSlop);
1361 if (finishedScrolling) {
1362 mTouchState = TOUCH_STATE_REST;
1363 mScroller.abortAnimation();
1364 } else {
Adam Cohen7d30a372013-07-01 17:03:59 -07001365 if (isTouchPointInViewportWithBuffer((int) mDownMotionX, (int) mDownMotionY)) {
1366 mTouchState = TOUCH_STATE_SCROLLING;
1367 } else {
1368 mTouchState = TOUCH_STATE_REST;
1369 }
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001370 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001371
Winson Chung86f77532010-08-24 11:08:22 -07001372 // check if this can be the beginning of a tap on the side of the pages
Winson Chung321e9ee2010-08-09 13:37:56 -07001373 // to scroll the current page
Adam Cohen7d30a372013-07-01 17:03:59 -07001374 if (!DISABLE_TOUCH_SIDE_PAGES) {
1375 if (mTouchState != TOUCH_STATE_PREV_PAGE && mTouchState != TOUCH_STATE_NEXT_PAGE) {
1376 if (getChildCount() > 0) {
1377 if (hitsPreviousPage(x, y)) {
1378 mTouchState = TOUCH_STATE_PREV_PAGE;
1379 } else if (hitsNextPage(x, y)) {
1380 mTouchState = TOUCH_STATE_NEXT_PAGE;
1381 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001382 }
1383 }
1384 }
1385 break;
1386 }
1387
Winson Chung321e9ee2010-08-09 13:37:56 -07001388 case MotionEvent.ACTION_UP:
Jeff Brown1d0867c2010-12-02 18:27:39 -08001389 case MotionEvent.ACTION_CANCEL:
Adam Cohen7d30a372013-07-01 17:03:59 -07001390 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001391 break;
1392
1393 case MotionEvent.ACTION_POINTER_UP:
1394 onSecondaryPointerUp(ev);
Adam Cohen6342bba2011-03-10 11:33:35 -08001395 releaseVelocityTracker();
Winson Chung321e9ee2010-08-09 13:37:56 -07001396 break;
1397 }
1398
1399 /*
1400 * The only time we want to intercept motion events is if we are in the
1401 * drag mode.
1402 */
1403 return mTouchState != TOUCH_STATE_REST;
1404 }
1405
Adam Cohenf8d28232011-02-01 21:47:00 -08001406 protected void determineScrollingStart(MotionEvent ev) {
1407 determineScrollingStart(ev, 1.0f);
1408 }
1409
Winson Chung321e9ee2010-08-09 13:37:56 -07001410 /*
1411 * Determines if we should change the touch state to start scrolling after the
1412 * user moves their touch point too far.
1413 */
Adam Cohenf8d28232011-02-01 21:47:00 -08001414 protected void determineScrollingStart(MotionEvent ev, float touchSlopScale) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001415 // Disallow scrolling if we don't have a valid pointer index
Winson Chung321e9ee2010-08-09 13:37:56 -07001416 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001417 if (pointerIndex == -1) return;
1418
1419 // Disallow scrolling if we started the gesture from outside the viewport
Winson Chung321e9ee2010-08-09 13:37:56 -07001420 final float x = ev.getX(pointerIndex);
1421 final float y = ev.getY(pointerIndex);
Adam Cohen7d30a372013-07-01 17:03:59 -07001422 if (!isTouchPointInViewportWithBuffer((int) x, (int) y)) return;
1423
Winson Chung321e9ee2010-08-09 13:37:56 -07001424 final int xDiff = (int) Math.abs(x - mLastMotionX);
1425 final int yDiff = (int) Math.abs(y - mLastMotionY);
1426
Adam Cohenf8d28232011-02-01 21:47:00 -08001427 final int touchSlop = Math.round(touchSlopScale * mTouchSlop);
Winson Chung321e9ee2010-08-09 13:37:56 -07001428 boolean xPaged = xDiff > mPagingTouchSlop;
1429 boolean xMoved = xDiff > touchSlop;
1430 boolean yMoved = yDiff > touchSlop;
1431
Adam Cohenf8d28232011-02-01 21:47:00 -08001432 if (xMoved || xPaged || yMoved) {
Michael Jurka0142d492010-08-25 17:46:15 -07001433 if (mUsePagingTouchSlop ? xPaged : xMoved) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001434 // Scroll if the user moved far enough along the X axis
1435 mTouchState = TOUCH_STATE_SCROLLING;
Adam Cohen6342bba2011-03-10 11:33:35 -08001436 mTotalMotionX += Math.abs(mLastMotionX - x);
Winson Chung321e9ee2010-08-09 13:37:56 -07001437 mLastMotionX = x;
Winson Chungc0844aa2011-02-02 15:25:58 -08001438 mLastMotionXRemainder = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -07001439 mTouchX = getViewportOffsetX() + getScrollX();
Michael Jurka0142d492010-08-25 17:46:15 -07001440 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1441 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07001442 }
Adam Cohenf8d28232011-02-01 21:47:00 -08001443 }
1444 }
1445
Adam Cohen7d30a372013-07-01 17:03:59 -07001446 protected float getMaxScrollProgress() {
1447 return 1.0f;
1448 }
1449
Adam Cohenf8d28232011-02-01 21:47:00 -08001450 protected void cancelCurrentPageLongPress() {
1451 if (mAllowLongPress) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001452 //mAllowLongPress = false;
Adam Cohenf8d28232011-02-01 21:47:00 -08001453 // Try canceling the long press. It could also have been scheduled
1454 // by a distant descendant, so use the mAllowLongPress flag to block
1455 // everything
1456 final View currentPage = getPageAt(mCurrentPage);
1457 if (currentPage != null) {
1458 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001459 }
1460 }
1461 }
1462
Adam Cohen7d30a372013-07-01 17:03:59 -07001463 protected float getBoundedScrollProgress(int screenCenter, View v, int page) {
1464 final int halfScreenSize = getViewportWidth() / 2;
1465
1466 screenCenter = Math.min(getScrollX() + halfScreenSize, screenCenter);
1467 screenCenter = Math.max(halfScreenSize, screenCenter);
1468
1469 return getScrollProgress(screenCenter, v, page);
1470 }
1471
Adam Cohenb5ba0972011-09-07 18:02:31 -07001472 protected float getScrollProgress(int screenCenter, View v, int page) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001473 final int halfScreenSize = getViewportWidth() / 2;
Adam Cohenb5ba0972011-09-07 18:02:31 -07001474
Adam Cohen96d30a12013-07-16 18:13:21 -07001475 int totalDistance = v.getMeasuredWidth() + mPageSpacing;
Adam Cohenedb40762013-07-18 16:45:45 -07001476 int delta = screenCenter - (getScrollForPage(page) + halfScreenSize);
Adam Cohenb5ba0972011-09-07 18:02:31 -07001477
1478 float scrollProgress = delta / (totalDistance * 1.0f);
Adam Cohen7d30a372013-07-01 17:03:59 -07001479 scrollProgress = Math.min(scrollProgress, getMaxScrollProgress());
1480 scrollProgress = Math.max(scrollProgress, - getMaxScrollProgress());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001481 return scrollProgress;
1482 }
1483
Adam Cohenedb40762013-07-18 16:45:45 -07001484 public int getScrollForPage(int index) {
Adam Cohen1f1f45d2013-10-02 09:40:18 -07001485 if (mPageScrolls == null || index >= mPageScrolls.length || index < 0) {
Adam Cohenedb40762013-07-18 16:45:45 -07001486 return 0;
1487 } else {
1488 return mPageScrolls[index];
1489 }
1490 }
1491
Adam Cohene0f66b52010-11-23 15:06:07 -08001492 // This curve determines how the effect of scrolling over the limits of the page dimishes
1493 // as the user pulls further and further from the bounds
1494 private float overScrollInfluenceCurve(float f) {
1495 f -= 1.0f;
1496 return f * f * f + 1.0f;
1497 }
1498
Adam Cohenb5ba0972011-09-07 18:02:31 -07001499 protected void acceleratedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001500 int screenSize = getViewportWidth();
Adam Cohenb5ba0972011-09-07 18:02:31 -07001501
1502 // We want to reach the max over scroll effect when the user has
1503 // over scrolled half the size of the screen
1504 float f = OVERSCROLL_ACCELERATE_FACTOR * (amount / screenSize);
1505
1506 if (f == 0) return;
1507
1508 // Clamp this factor, f, to -1 < f < 1
1509 if (Math.abs(f) >= 1) {
1510 f /= Math.abs(f);
1511 }
1512
1513 int overScrollAmount = (int) Math.round(f * screenSize);
1514 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001515 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001516 super.scrollTo(0, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001517 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001518 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001519 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001520 }
1521 invalidate();
1522 }
1523
1524 protected void dampedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001525 int screenSize = getViewportWidth();
Adam Cohene0f66b52010-11-23 15:06:07 -08001526
1527 float f = (amount / screenSize);
1528
1529 if (f == 0) return;
1530 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1531
Adam Cohen7bfc9792011-01-28 13:52:37 -08001532 // Clamp this factor, f, to -1 < f < 1
1533 if (Math.abs(f) >= 1) {
1534 f /= Math.abs(f);
1535 }
1536
Adam Cohene0f66b52010-11-23 15:06:07 -08001537 int overScrollAmount = (int) Math.round(OVERSCROLL_DAMP_FACTOR * f * screenSize);
Adam Cohen68d73932010-11-15 10:50:58 -08001538 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001539 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001540 super.scrollTo(0, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001541 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001542 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001543 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001544 }
1545 invalidate();
1546 }
1547
Adam Cohenb5ba0972011-09-07 18:02:31 -07001548 protected void overScroll(float amount) {
1549 dampedOverScroll(amount);
1550 }
1551
Michael Jurkac5b262c2011-01-12 20:24:50 -08001552 protected float maxOverScroll() {
1553 // Using the formula in overScroll, assuming that f = 1.0 (which it should generally not
Adam Cohenb5ba0972011-09-07 18:02:31 -07001554 // exceed). Used to find out how much extra wallpaper we need for the over scroll effect
Michael Jurkac5b262c2011-01-12 20:24:50 -08001555 float f = 1.0f;
1556 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1557 return OVERSCROLL_DAMP_FACTOR * f;
1558 }
1559
Adam Cohenf358a4b2013-07-23 16:47:31 -07001560 protected void enableFreeScroll() {
1561 setEnableFreeScroll(true, -1);
1562 }
1563
1564 protected void disableFreeScroll(int snapPage) {
1565 setEnableFreeScroll(false, snapPage);
1566 }
1567
Adam Cohen7a9e58a2013-10-01 18:02:13 -07001568 void updateFreescrollBounds() {
1569 getOverviewModePages(mTempVisiblePagesRange);
1570 if (isLayoutRtl()) {
1571 mFreeScrollMinScrollX = getScrollForPage(mTempVisiblePagesRange[1]);
1572 mFreeScrollMaxScrollX = getScrollForPage(mTempVisiblePagesRange[0]);
1573 } else {
1574 mFreeScrollMinScrollX = getScrollForPage(mTempVisiblePagesRange[0]);
1575 mFreeScrollMaxScrollX = getScrollForPage(mTempVisiblePagesRange[1]);
1576 }
1577 }
1578
Adam Cohenf358a4b2013-07-23 16:47:31 -07001579 private void setEnableFreeScroll(boolean freeScroll, int snapPage) {
1580 mFreeScroll = freeScroll;
1581
1582 if (snapPage == -1) {
1583 snapPage = getPageNearestToCenterOfScreen();
1584 }
1585
Adam Cohenf358a4b2013-07-23 16:47:31 -07001586 if (!mFreeScroll) {
1587 snapToPage(snapPage);
Adam Cohenf358a4b2013-07-23 16:47:31 -07001588 } else {
Adam Cohen7a9e58a2013-10-01 18:02:13 -07001589 updateFreescrollBounds();
1590 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohenf358a4b2013-07-23 16:47:31 -07001591 if (getCurrentPage() < mTempVisiblePagesRange[0]) {
1592 setCurrentPage(mTempVisiblePagesRange[0]);
1593 } else if (getCurrentPage() > mTempVisiblePagesRange[1]) {
1594 setCurrentPage(mTempVisiblePagesRange[1]);
1595 }
1596 }
1597
1598 setEnableOverscroll(!freeScroll);
1599 }
1600
1601 private void setEnableOverscroll(boolean enable) {
1602 mAllowOverScroll = enable;
1603 }
1604
1605 int getNearestHoverOverPageIndex() {
1606 if (mDragView != null) {
1607 int dragX = (int) (mDragView.getLeft() + (mDragView.getMeasuredWidth() / 2)
1608 + mDragView.getTranslationX());
1609 getOverviewModePages(mTempVisiblePagesRange);
1610 int minDistance = Integer.MAX_VALUE;
1611 int minIndex = indexOfChild(mDragView);
1612 for (int i = mTempVisiblePagesRange[0]; i <= mTempVisiblePagesRange[1]; i++) {
1613 View page = getPageAt(i);
1614 int pageX = (int) (page.getLeft() + page.getMeasuredWidth() / 2);
1615 int d = Math.abs(dragX - pageX);
1616 if (d < minDistance) {
1617 minIndex = i;
1618 minDistance = d;
1619 }
1620 }
1621 return minIndex;
1622 }
1623 return -1;
1624 }
1625
Winson Chung321e9ee2010-08-09 13:37:56 -07001626 @Override
1627 public boolean onTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001628 if (DISABLE_TOUCH_INTERACTION) {
1629 return false;
1630 }
1631
Adam Cohen1697b792013-09-17 19:08:21 -07001632 super.onTouchEvent(ev);
1633
Winson Chung45e1d6e2010-11-09 17:19:49 -08001634 // Skip touch handling if there are no pages to swipe
1635 if (getChildCount() <= 0) return super.onTouchEvent(ev);
1636
Michael Jurkab8f06722010-10-10 15:58:46 -07001637 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001638
1639 final int action = ev.getAction();
1640
1641 switch (action & MotionEvent.ACTION_MASK) {
1642 case MotionEvent.ACTION_DOWN:
1643 /*
1644 * If being flinged and user touches, stop the fling. isFinished
1645 * will be false if being flinged.
1646 */
1647 if (!mScroller.isFinished()) {
1648 mScroller.abortAnimation();
1649 }
1650
1651 // Remember where the motion event started
1652 mDownMotionX = mLastMotionX = ev.getX();
Adam Cohen7d30a372013-07-01 17:03:59 -07001653 mDownMotionY = mLastMotionY = ev.getY();
1654 mDownScrollX = getScrollX();
1655 float[] p = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1656 mParentDownMotionX = p[0];
1657 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001658 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001659 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001660 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001661
Michael Jurka0142d492010-08-25 17:46:15 -07001662 if (mTouchState == TOUCH_STATE_SCROLLING) {
1663 pageBeginMoving();
1664 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001665 break;
1666
1667 case MotionEvent.ACTION_MOVE:
1668 if (mTouchState == TOUCH_STATE_SCROLLING) {
1669 // Scroll to follow the motion event
1670 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001671
1672 if (pointerIndex == -1) return true;
1673
Winson Chung321e9ee2010-08-09 13:37:56 -07001674 final float x = ev.getX(pointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001675 final float deltaX = mLastMotionX + mLastMotionXRemainder - x;
Winson Chung321e9ee2010-08-09 13:37:56 -07001676
Adam Cohenaefd4e12011-02-14 16:39:38 -08001677 mTotalMotionX += Math.abs(deltaX);
1678
Winson Chungc0844aa2011-02-02 15:25:58 -08001679 // Only scroll and update mLastMotionX if we have moved some discrete amount. We
1680 // keep the remainder because we are actually testing if we've moved from the last
1681 // scrolled position (which is discrete).
1682 if (Math.abs(deltaX) >= 1.0f) {
Adam Cohen68d73932010-11-15 10:50:58 -08001683 mTouchX += deltaX;
1684 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1685 if (!mDeferScrollUpdate) {
Winson Chungc0844aa2011-02-02 15:25:58 -08001686 scrollBy((int) deltaX, 0);
Winson Chung785d2eb2011-04-14 16:08:02 -07001687 if (DEBUG) Log.d(TAG, "onTouchEvent().Scrolling: " + deltaX);
Adam Cohen68d73932010-11-15 10:50:58 -08001688 } else {
1689 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001690 }
Winson Chungc0844aa2011-02-02 15:25:58 -08001691 mLastMotionX = x;
1692 mLastMotionXRemainder = deltaX - (int) deltaX;
Winson Chung321e9ee2010-08-09 13:37:56 -07001693 } else {
1694 awakenScrollBars();
1695 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001696 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1697 // Update the last motion position
1698 mLastMotionX = ev.getX();
1699 mLastMotionY = ev.getY();
1700
1701 // Update the parent down so that our zoom animations take this new movement into
1702 // account
1703 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1704 mParentDownMotionX = pt[0];
1705 mParentDownMotionY = pt[1];
1706 updateDragViewTranslationDuringDrag();
1707
1708 // Find the closest page to the touch point
1709 final int dragViewIndex = indexOfChild(mDragView);
Adam Cohen7d30a372013-07-01 17:03:59 -07001710
1711 // Change the drag view if we are hovering over the drop target
1712 boolean isHoveringOverDelete = isHoveringOverDeleteDropTarget(
1713 (int) mParentDownMotionX, (int) mParentDownMotionY);
1714 setPageHoveringOverDeleteDropTarget(dragViewIndex, isHoveringOverDelete);
1715
Adam Cohen7d30a372013-07-01 17:03:59 -07001716 if (DEBUG) Log.d(TAG, "mLastMotionX: " + mLastMotionX);
1717 if (DEBUG) Log.d(TAG, "mLastMotionY: " + mLastMotionY);
1718 if (DEBUG) Log.d(TAG, "mParentDownMotionX: " + mParentDownMotionX);
1719 if (DEBUG) Log.d(TAG, "mParentDownMotionY: " + mParentDownMotionY);
1720
Adam Cohenf358a4b2013-07-23 16:47:31 -07001721 final int pageUnderPointIndex = getNearestHoverOverPageIndex();
1722 if (pageUnderPointIndex > -1 && pageUnderPointIndex != indexOfChild(mDragView) &&
1723 !isHoveringOverDelete) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001724 mTempVisiblePagesRange[0] = 0;
1725 mTempVisiblePagesRange[1] = getPageCount() - 1;
Adam Cohenf358a4b2013-07-23 16:47:31 -07001726 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07001727 if (mTempVisiblePagesRange[0] <= pageUnderPointIndex &&
1728 pageUnderPointIndex <= mTempVisiblePagesRange[1] &&
1729 pageUnderPointIndex != mSidePageHoverIndex && mScroller.isFinished()) {
1730 mSidePageHoverIndex = pageUnderPointIndex;
1731 mSidePageHoverRunnable = new Runnable() {
1732 @Override
1733 public void run() {
Adam Cohen7d30a372013-07-01 17:03:59 -07001734 // Setup the scroll to the correct page before we swap the views
1735 snapToPage(pageUnderPointIndex);
1736
1737 // For each of the pages between the paged view and the drag view,
1738 // animate them from the previous position to the new position in
1739 // the layout (as a result of the drag view moving in the layout)
1740 int shiftDelta = (dragViewIndex < pageUnderPointIndex) ? -1 : 1;
1741 int lowerIndex = (dragViewIndex < pageUnderPointIndex) ?
1742 dragViewIndex + 1 : pageUnderPointIndex;
1743 int upperIndex = (dragViewIndex > pageUnderPointIndex) ?
1744 dragViewIndex - 1 : pageUnderPointIndex;
1745 for (int i = lowerIndex; i <= upperIndex; ++i) {
1746 View v = getChildAt(i);
1747 // dragViewIndex < pageUnderPointIndex, so after we remove the
1748 // drag view all subsequent views to pageUnderPointIndex will
1749 // shift down.
1750 int oldX = getViewportOffsetX() + getChildOffset(i);
1751 int newX = getViewportOffsetX() + getChildOffset(i + shiftDelta);
1752
1753 // Animate the view translation from its old position to its new
1754 // position
1755 AnimatorSet anim = (AnimatorSet) v.getTag(ANIM_TAG_KEY);
1756 if (anim != null) {
1757 anim.cancel();
1758 }
1759
1760 v.setTranslationX(oldX - newX);
1761 anim = new AnimatorSet();
1762 anim.setDuration(REORDERING_REORDER_REPOSITION_DURATION);
1763 anim.playTogether(
1764 ObjectAnimator.ofFloat(v, "translationX", 0f));
1765 anim.start();
1766 v.setTag(anim);
1767 }
1768
1769 removeView(mDragView);
1770 onRemoveView(mDragView, false);
1771 addView(mDragView, pageUnderPointIndex);
1772 onAddView(mDragView, pageUnderPointIndex);
1773 mSidePageHoverIndex = -1;
Winson Chungd2be3812013-07-16 11:11:32 -07001774 mPageIndicator.setActiveMarker(getNextPage());
Adam Cohen7d30a372013-07-01 17:03:59 -07001775 }
1776 };
1777 postDelayed(mSidePageHoverRunnable, REORDERING_SIDE_PAGE_HOVER_TIMEOUT);
1778 }
1779 } else {
1780 removeCallbacks(mSidePageHoverRunnable);
1781 mSidePageHoverIndex = -1;
1782 }
Adam Cohen564976a2010-10-13 18:52:07 -07001783 } else {
Winson Chung321e9ee2010-08-09 13:37:56 -07001784 determineScrollingStart(ev);
1785 }
1786 break;
1787
1788 case MotionEvent.ACTION_UP:
1789 if (mTouchState == TOUCH_STATE_SCROLLING) {
1790 final int activePointerId = mActivePointerId;
1791 final int pointerIndex = ev.findPointerIndex(activePointerId);
1792 final float x = ev.getX(pointerIndex);
1793 final VelocityTracker velocityTracker = mVelocityTracker;
1794 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
1795 int velocityX = (int) velocityTracker.getXVelocity(activePointerId);
Winson Chung9cfd25f2010-10-24 16:09:28 -07001796 final int deltaX = (int) (x - mDownMotionX);
Adam Cohen96d30a12013-07-16 18:13:21 -07001797 final int pageWidth = getPageAt(mCurrentPage).getMeasuredWidth();
Adam Cohen00481b32011-11-18 12:03:48 -08001798 boolean isSignificantMove = Math.abs(deltaX) > pageWidth *
1799 SIGNIFICANT_MOVE_THRESHOLD;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001800
Adam Cohenb64cb5a2011-02-15 13:53:42 -08001801 mTotalMotionX += Math.abs(mLastMotionX + mLastMotionXRemainder - x);
1802
Adam Cohen00481b32011-11-18 12:03:48 -08001803 boolean isFling = mTotalMotionX > MIN_LENGTH_FOR_FLING &&
Adam Cohen265b9a62011-12-07 14:37:18 -08001804 Math.abs(velocityX) > mFlingThresholdVelocity;
Adam Cohen00481b32011-11-18 12:03:48 -08001805
Adam Cohenf358a4b2013-07-23 16:47:31 -07001806 if (!mFreeScroll) {
1807 // In the case that the page is moved far to one direction and then is flung
1808 // in the opposite direction, we use a threshold to determine whether we should
1809 // just return to the starting page, or if we should skip one further.
1810 boolean returnToOriginalPage = false;
1811 if (Math.abs(deltaX) > pageWidth * RETURN_TO_ORIGINAL_PAGE_THRESHOLD &&
1812 Math.signum(velocityX) != Math.signum(deltaX) && isFling) {
1813 returnToOriginalPage = true;
1814 }
Adam Cohenaefd4e12011-02-14 16:39:38 -08001815
Adam Cohenf358a4b2013-07-23 16:47:31 -07001816 int finalPage;
1817 // We give flings precedence over large moves, which is why we short-circuit our
1818 // test for a large move if a fling has been registered. That is, a large
1819 // move to the left and fling to the right will register as a fling to the right.
1820 final boolean isRtl = isLayoutRtl();
1821 boolean isDeltaXLeft = isRtl ? deltaX > 0 : deltaX < 0;
1822 boolean isVelocityXLeft = isRtl ? velocityX > 0 : velocityX < 0;
1823 if (((isSignificantMove && !isDeltaXLeft && !isFling) ||
1824 (isFling && !isVelocityXLeft)) && mCurrentPage > 0) {
1825 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage - 1;
1826 snapToPageWithVelocity(finalPage, velocityX);
1827 } else if (((isSignificantMove && isDeltaXLeft && !isFling) ||
1828 (isFling && isVelocityXLeft)) &&
1829 mCurrentPage < getChildCount() - 1) {
1830 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage + 1;
1831 snapToPageWithVelocity(finalPage, velocityX);
1832 } else {
1833 snapToDestination();
1834 } } else if (mTouchState == TOUCH_STATE_PREV_PAGE) {
1835 // at this point we have not moved beyond the touch slop
1836 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1837 // we can just page
1838 int nextPage = Math.max(0, mCurrentPage - 1);
1839 if (nextPage != mCurrentPage) {
1840 snapToPage(nextPage);
1841 } else {
1842 snapToDestination();
1843 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001844 } else {
Adam Cohenf358a4b2013-07-23 16:47:31 -07001845 if (!mScroller.isFinished()) {
1846 mScroller.abortAnimation();
1847 }
1848
1849 float scaleX = getScaleX();
1850 int vX = (int) (-velocityX * scaleX);
1851 int initialScrollX = (int) (getScrollX() * scaleX);
1852
1853 mScroller.fling(initialScrollX,
1854 getScrollY(), vX, 0, Integer.MIN_VALUE, Integer.MAX_VALUE, 0, 0);
1855 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001856 }
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001857 } else if (mTouchState == TOUCH_STATE_NEXT_PAGE) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001858 // at this point we have not moved beyond the touch slop
1859 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1860 // we can just page
Winson Chung86f77532010-08-24 11:08:22 -07001861 int nextPage = Math.min(getChildCount() - 1, mCurrentPage + 1);
1862 if (nextPage != mCurrentPage) {
1863 snapToPage(nextPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001864 } else {
1865 snapToDestination();
1866 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001867 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1868 // Update the last motion position
1869 mLastMotionX = ev.getX();
1870 mLastMotionY = ev.getY();
1871
1872 // Update the parent down so that our zoom animations take this new movement into
1873 // account
1874 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1875 mParentDownMotionX = pt[0];
1876 mParentDownMotionY = pt[1];
1877 updateDragViewTranslationDuringDrag();
1878 boolean handledFling = false;
1879 if (!DISABLE_FLING_TO_DELETE) {
1880 // Check the velocity and see if we are flinging-to-delete
1881 PointF flingToDeleteVector = isFlingingToDelete();
1882 if (flingToDeleteVector != null) {
1883 onFlingToDelete(flingToDeleteVector);
1884 handledFling = true;
1885 }
1886 }
1887 if (!handledFling && isHoveringOverDeleteDropTarget((int) mParentDownMotionX,
1888 (int) mParentDownMotionY)) {
1889 onDropToDelete();
1890 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001891 } else {
Adam Cohendbdff6b2013-09-18 19:09:15 -07001892 if (!mCancelTap) {
1893 onUnhandledTap(ev);
1894 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001895 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001896
1897 // Remove the callback to wait for the side page hover timeout
1898 removeCallbacks(mSidePageHoverRunnable);
1899 // End any intermediate reordering states
1900 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001901 break;
1902
1903 case MotionEvent.ACTION_CANCEL:
Michael Jurkab8f06722010-10-10 15:58:46 -07001904 if (mTouchState == TOUCH_STATE_SCROLLING) {
1905 snapToDestination();
1906 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001907 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001908 break;
1909
1910 case MotionEvent.ACTION_POINTER_UP:
1911 onSecondaryPointerUp(ev);
Adam Cohenf358a4b2013-07-23 16:47:31 -07001912 releaseVelocityTracker();
Winson Chung321e9ee2010-08-09 13:37:56 -07001913 break;
1914 }
1915
1916 return true;
1917 }
1918
Adam Cohen7d30a372013-07-01 17:03:59 -07001919 public void onFlingToDelete(View v) {}
1920 public void onRemoveView(View v, boolean deletePermanently) {}
1921 public void onRemoveViewAnimationCompleted() {}
1922 public void onAddView(View v, int index) {}
1923
1924 private void resetTouchState() {
1925 releaseVelocityTracker();
1926 endReordering();
Adam Cohendbdff6b2013-09-18 19:09:15 -07001927 mCancelTap = false;
Adam Cohen7d30a372013-07-01 17:03:59 -07001928 mTouchState = TOUCH_STATE_REST;
1929 mActivePointerId = INVALID_POINTER;
Adam Cohen7d30a372013-07-01 17:03:59 -07001930 }
1931
Adam Cohen1697b792013-09-17 19:08:21 -07001932 protected void onUnhandledTap(MotionEvent ev) {
1933 ((Launcher) getContext()).onClick(this);
1934 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001935
Winson Chung185d7162011-02-28 13:47:29 -08001936 @Override
1937 public boolean onGenericMotionEvent(MotionEvent event) {
1938 if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
1939 switch (event.getAction()) {
1940 case MotionEvent.ACTION_SCROLL: {
1941 // Handle mouse (or ext. device) by shifting the page depending on the scroll
1942 final float vscroll;
1943 final float hscroll;
1944 if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) {
1945 vscroll = 0;
1946 hscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1947 } else {
1948 vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1949 hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL);
1950 }
1951 if (hscroll != 0 || vscroll != 0) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001952 boolean isForwardScroll = isLayoutRtl() ? (hscroll < 0 || vscroll < 0)
1953 : (hscroll > 0 || vscroll > 0);
1954 if (isForwardScroll) {
Winson Chung185d7162011-02-28 13:47:29 -08001955 scrollRight();
1956 } else {
1957 scrollLeft();
1958 }
1959 return true;
1960 }
1961 }
1962 }
1963 }
1964 return super.onGenericMotionEvent(event);
1965 }
1966
Michael Jurkab8f06722010-10-10 15:58:46 -07001967 private void acquireVelocityTrackerAndAddMovement(MotionEvent ev) {
1968 if (mVelocityTracker == null) {
1969 mVelocityTracker = VelocityTracker.obtain();
1970 }
1971 mVelocityTracker.addMovement(ev);
1972 }
1973
1974 private void releaseVelocityTracker() {
1975 if (mVelocityTracker != null) {
Adam Cohenf358a4b2013-07-23 16:47:31 -07001976 mVelocityTracker.clear();
Michael Jurkab8f06722010-10-10 15:58:46 -07001977 mVelocityTracker.recycle();
1978 mVelocityTracker = null;
1979 }
1980 }
1981
Winson Chung321e9ee2010-08-09 13:37:56 -07001982 private void onSecondaryPointerUp(MotionEvent ev) {
1983 final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
1984 MotionEvent.ACTION_POINTER_INDEX_SHIFT;
1985 final int pointerId = ev.getPointerId(pointerIndex);
1986 if (pointerId == mActivePointerId) {
1987 // This was our active pointer going up. Choose a new
1988 // active pointer and adjust accordingly.
1989 // TODO: Make this decision more intelligent.
1990 final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
1991 mLastMotionX = mDownMotionX = ev.getX(newPointerIndex);
1992 mLastMotionY = ev.getY(newPointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001993 mLastMotionXRemainder = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001994 mActivePointerId = ev.getPointerId(newPointerIndex);
1995 if (mVelocityTracker != null) {
1996 mVelocityTracker.clear();
1997 }
1998 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001999 }
2000
Winson Chung321e9ee2010-08-09 13:37:56 -07002001 @Override
2002 public void requestChildFocus(View child, View focused) {
2003 super.requestChildFocus(child, focused);
Adam Cohenae4f1552011-10-20 00:15:42 -07002004 int page = indexToPage(indexOfChild(child));
Winson Chung97d85d22011-04-13 11:27:36 -07002005 if (page >= 0 && page != getCurrentPage() && !isInTouchMode()) {
Winson Chung86f77532010-08-24 11:08:22 -07002006 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07002007 }
2008 }
2009
Winson Chung1908d072011-02-24 18:09:44 -08002010 protected int getChildWidth(int index) {
Adam Cohen96d30a12013-07-16 18:13:21 -07002011 return getPageAt(index).getMeasuredWidth();
Winson Chung1908d072011-02-24 18:09:44 -08002012 }
2013
Adam Cohen7d30a372013-07-01 17:03:59 -07002014 int getPageNearestToPoint(float x) {
2015 int index = 0;
2016 for (int i = 0; i < getChildCount(); ++i) {
2017 if (x < getChildAt(i).getRight() - getScrollX()) {
2018 return index;
2019 } else {
2020 index++;
2021 }
2022 }
2023 return Math.min(index, getChildCount() - 1);
2024 }
2025
Adam Cohend19d3ca2010-09-15 14:43:42 -07002026 int getPageNearestToCenterOfScreen() {
Adam Cohen22f823d2011-09-01 17:22:18 -07002027 int minDistanceFromScreenCenter = Integer.MAX_VALUE;
Winson Chung321e9ee2010-08-09 13:37:56 -07002028 int minDistanceFromScreenCenterIndex = -1;
Adam Cohen7d30a372013-07-01 17:03:59 -07002029 int screenCenter = getViewportOffsetX() + getScrollX() + (getViewportWidth() / 2);
Winson Chung321e9ee2010-08-09 13:37:56 -07002030 final int childCount = getChildCount();
2031 for (int i = 0; i < childCount; ++i) {
Adam Cohen22f823d2011-09-01 17:22:18 -07002032 View layout = (View) getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -07002033 int childWidth = layout.getMeasuredWidth();
Winson Chung321e9ee2010-08-09 13:37:56 -07002034 int halfChildWidth = (childWidth / 2);
Adam Cohen7d30a372013-07-01 17:03:59 -07002035 int childCenter = getViewportOffsetX() + getChildOffset(i) + halfChildWidth;
Winson Chung321e9ee2010-08-09 13:37:56 -07002036 int distanceFromScreenCenter = Math.abs(childCenter - screenCenter);
2037 if (distanceFromScreenCenter < minDistanceFromScreenCenter) {
2038 minDistanceFromScreenCenter = distanceFromScreenCenter;
2039 minDistanceFromScreenCenterIndex = i;
2040 }
2041 }
Adam Cohend19d3ca2010-09-15 14:43:42 -07002042 return minDistanceFromScreenCenterIndex;
2043 }
2044
2045 protected void snapToDestination() {
2046 snapToPage(getPageNearestToCenterOfScreen(), PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07002047 }
2048
Adam Cohene0f66b52010-11-23 15:06:07 -08002049 private static class ScrollInterpolator implements Interpolator {
2050 public ScrollInterpolator() {
2051 }
2052
2053 public float getInterpolation(float t) {
2054 t -= 1.0f;
2055 return t*t*t*t*t + 1;
2056 }
2057 }
2058
2059 // We want the duration of the page snap animation to be influenced by the distance that
2060 // the screen has to travel, however, we don't want this duration to be effected in a
2061 // purely linear fashion. Instead, we use this method to moderate the effect that the distance
2062 // of travel has on the overall snap duration.
2063 float distanceInfluenceForSnapDuration(float f) {
2064 f -= 0.5f; // center the values about 0.
2065 f *= 0.3f * Math.PI / 2.0f;
2066 return (float) Math.sin(f);
2067 }
2068
Michael Jurka0142d492010-08-25 17:46:15 -07002069 protected void snapToPageWithVelocity(int whichPage, int velocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08002070 whichPage = Math.max(0, Math.min(whichPage, getChildCount() - 1));
Adam Cohen7d30a372013-07-01 17:03:59 -07002071 int halfScreenSize = getViewportWidth() / 2;
Adam Cohene0f66b52010-11-23 15:06:07 -08002072
Adam Cohenedb40762013-07-18 16:45:45 -07002073 final int newX = getScrollForPage(whichPage);
Adam Cohene0f66b52010-11-23 15:06:07 -08002074 int delta = newX - mUnboundedScrollX;
2075 int duration = 0;
2076
Adam Cohen265b9a62011-12-07 14:37:18 -08002077 if (Math.abs(velocity) < mMinFlingVelocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08002078 // If the velocity is low enough, then treat this more as an automatic page advance
2079 // as opposed to an apparent physical response to flinging
2080 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
2081 return;
2082 }
2083
2084 // Here we compute a "distance" that will be used in the computation of the overall
2085 // snap duration. This is a function of the actual distance that needs to be traveled;
2086 // we keep this value close to half screen size in order to reduce the variance in snap
2087 // duration as a function of the distance the page needs to travel.
Michael Jurka20b7ca92011-06-07 20:09:16 -07002088 float distanceRatio = Math.min(1f, 1.0f * Math.abs(delta) / (2 * halfScreenSize));
Adam Cohene0f66b52010-11-23 15:06:07 -08002089 float distance = halfScreenSize + halfScreenSize *
2090 distanceInfluenceForSnapDuration(distanceRatio);
2091
2092 velocity = Math.abs(velocity);
Adam Cohen265b9a62011-12-07 14:37:18 -08002093 velocity = Math.max(mMinSnapVelocity, velocity);
Adam Cohene0f66b52010-11-23 15:06:07 -08002094
2095 // we want the page's snap velocity to approximately match the velocity at which the
2096 // user flings, so we scale the duration by a value near to the derivative of the scroll
Michael Jurka20b7ca92011-06-07 20:09:16 -07002097 // interpolator at zero, ie. 5. We use 4 to make it a little slower.
2098 duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
Adam Cohene0f66b52010-11-23 15:06:07 -08002099
2100 snapToPage(whichPage, delta, duration);
Michael Jurka0142d492010-08-25 17:46:15 -07002101 }
2102
2103 protected void snapToPage(int whichPage) {
Winson Chung5f2aa4e2010-08-20 14:49:25 -07002104 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07002105 }
2106
Adam Cohen7d30a372013-07-01 17:03:59 -07002107 protected void snapToPageImmediately(int whichPage) {
2108 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION, true);
2109 }
2110
Michael Jurka0142d492010-08-25 17:46:15 -07002111 protected void snapToPage(int whichPage, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07002112 snapToPage(whichPage, duration, false);
2113 }
2114
2115 protected void snapToPage(int whichPage, int duration, boolean immediate) {
Winson Chung86f77532010-08-24 11:08:22 -07002116 whichPage = Math.max(0, Math.min(whichPage, getPageCount() - 1));
Winson Chung321e9ee2010-08-09 13:37:56 -07002117
Adam Cohenedb40762013-07-18 16:45:45 -07002118 int newX = getScrollForPage(whichPage);
Adam Cohen68d73932010-11-15 10:50:58 -08002119 final int sX = mUnboundedScrollX;
Winson Chung321e9ee2010-08-09 13:37:56 -07002120 final int delta = newX - sX;
Adam Cohen7d30a372013-07-01 17:03:59 -07002121 snapToPage(whichPage, delta, duration, immediate);
Michael Jurka0142d492010-08-25 17:46:15 -07002122 }
2123
2124 protected void snapToPage(int whichPage, int delta, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07002125 snapToPage(whichPage, delta, duration, false);
2126 }
Michael Jurka0142d492010-08-25 17:46:15 -07002127
Adam Cohen7d30a372013-07-01 17:03:59 -07002128 protected void snapToPage(int whichPage, int delta, int duration, boolean immediate) {
2129 mNextPage = whichPage;
Michael Jurka0142d492010-08-25 17:46:15 -07002130 View focusedChild = getFocusedChild();
2131 if (focusedChild != null && whichPage != mCurrentPage &&
Adam Cohen22f823d2011-09-01 17:22:18 -07002132 focusedChild == getPageAt(mCurrentPage)) {
Michael Jurka0142d492010-08-25 17:46:15 -07002133 focusedChild.clearFocus();
2134 }
2135
2136 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07002137 awakenScrollBars(duration);
Adam Cohen7d30a372013-07-01 17:03:59 -07002138 if (immediate) {
2139 duration = 0;
2140 } else if (duration == 0) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002141 duration = Math.abs(delta);
2142 }
2143
Adam Cohenf358a4b2013-07-23 16:47:31 -07002144 if (!mScroller.isFinished()) {
2145 mScroller.abortAnimation();
2146 }
Adam Cohen68d73932010-11-15 10:50:58 -08002147 mScroller.startScroll(mUnboundedScrollX, 0, delta, 0, duration);
Winson Chung80baf5a2010-08-09 16:03:15 -07002148
Michael Jurka0142d492010-08-25 17:46:15 -07002149 notifyPageSwitchListener();
Adam Cohen7d30a372013-07-01 17:03:59 -07002150
2151 // Trigger a compute() to finish switching pages if necessary
2152 if (immediate) {
2153 computeScroll();
2154 }
2155
Winson Chung9c0565f2013-07-19 13:49:06 -07002156 // Defer loading associated pages until the scroll settles
2157 mDeferLoadAssociatedPagesUntilScrollCompletes = true;
2158
Adam Cohen7d30a372013-07-01 17:03:59 -07002159 mForceScreenScrolled = true;
Winson Chung321e9ee2010-08-09 13:37:56 -07002160 invalidate();
2161 }
2162
Winson Chung321e9ee2010-08-09 13:37:56 -07002163 public void scrollLeft() {
Adam Cohen2bf63d52013-09-29 17:46:49 -07002164 if (getNextPage() > 0) snapToPage(getNextPage() - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002165 }
2166
2167 public void scrollRight() {
Adam Cohen2bf63d52013-09-29 17:46:49 -07002168 if (getNextPage() < getChildCount() -1) snapToPage(getNextPage() + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002169 }
2170
Winson Chung86f77532010-08-24 11:08:22 -07002171 public int getPageForView(View v) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002172 int result = -1;
2173 if (v != null) {
2174 ViewParent vp = v.getParent();
2175 int count = getChildCount();
2176 for (int i = 0; i < count; i++) {
Adam Cohen22f823d2011-09-01 17:22:18 -07002177 if (vp == getPageAt(i)) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002178 return i;
2179 }
2180 }
2181 }
2182 return result;
2183 }
2184
2185 /**
2186 * @return True is long presses are still allowed for the current touch
2187 */
2188 public boolean allowLongPress() {
2189 return mAllowLongPress;
2190 }
2191
Adam Cohendbdff6b2013-09-18 19:09:15 -07002192 @Override
2193 public boolean performLongClick() {
2194 mCancelTap = true;
2195 return super.performLongClick();
2196 }
2197
Michael Jurka0142d492010-08-25 17:46:15 -07002198 /**
2199 * Set true to allow long-press events to be triggered, usually checked by
2200 * {@link Launcher} to accept or block dpad-initiated long-presses.
2201 */
2202 public void setAllowLongPress(boolean allowLongPress) {
2203 mAllowLongPress = allowLongPress;
2204 }
2205
Winson Chung321e9ee2010-08-09 13:37:56 -07002206 public static class SavedState extends BaseSavedState {
Winson Chung86f77532010-08-24 11:08:22 -07002207 int currentPage = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -07002208
2209 SavedState(Parcelable superState) {
2210 super(superState);
2211 }
2212
2213 private SavedState(Parcel in) {
2214 super(in);
Winson Chung86f77532010-08-24 11:08:22 -07002215 currentPage = in.readInt();
Winson Chung321e9ee2010-08-09 13:37:56 -07002216 }
2217
2218 @Override
2219 public void writeToParcel(Parcel out, int flags) {
2220 super.writeToParcel(out, flags);
Winson Chung86f77532010-08-24 11:08:22 -07002221 out.writeInt(currentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07002222 }
2223
2224 public static final Parcelable.Creator<SavedState> CREATOR =
2225 new Parcelable.Creator<SavedState>() {
2226 public SavedState createFromParcel(Parcel in) {
2227 return new SavedState(in);
2228 }
2229
2230 public SavedState[] newArray(int size) {
2231 return new SavedState[size];
2232 }
2233 };
2234 }
2235
Winson Chungf314b0e2011-08-16 11:54:27 -07002236 protected void loadAssociatedPages(int page) {
2237 loadAssociatedPages(page, false);
2238 }
2239 protected void loadAssociatedPages(int page, boolean immediateAndOnly) {
Michael Jurka0142d492010-08-25 17:46:15 -07002240 if (mContentIsRefreshable) {
2241 final int count = getChildCount();
2242 if (page < count) {
Winson Chunge3193b92010-09-10 11:44:42 -07002243 int lowerPageBound = getAssociatedLowerPageBound(page);
2244 int upperPageBound = getAssociatedUpperPageBound(page);
Winson Chung785d2eb2011-04-14 16:08:02 -07002245 if (DEBUG) Log.d(TAG, "loadAssociatedPages: " + lowerPageBound + "/"
2246 + upperPageBound);
Michael Jurka0cad1112011-11-16 20:43:29 -08002247 // First, clear any pages that should no longer be loaded
2248 for (int i = 0; i < count; ++i) {
2249 Page layout = (Page) getPageAt(i);
Michael Jurka2a4b1a82011-12-07 14:00:02 -08002250 if ((i < lowerPageBound) || (i > upperPageBound)) {
Michael Jurka0cad1112011-11-16 20:43:29 -08002251 if (layout.getPageChildCount() > 0) {
2252 layout.removeAllViewsOnPage();
2253 }
2254 mDirtyPageContent.set(i, true);
2255 }
2256 }
2257 // Next, load any new pages
Michael Jurka0142d492010-08-25 17:46:15 -07002258 for (int i = 0; i < count; ++i) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002259 if ((i != page) && immediateAndOnly) {
2260 continue;
2261 }
Michael Jurka0142d492010-08-25 17:46:15 -07002262 if (lowerPageBound <= i && i <= upperPageBound) {
2263 if (mDirtyPageContent.get(i)) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002264 syncPageItems(i, (i == page) && immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002265 mDirtyPageContent.set(i, false);
2266 }
Winson Chung86f77532010-08-24 11:08:22 -07002267 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002268 }
2269 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002270 }
2271 }
2272
Winson Chunge3193b92010-09-10 11:44:42 -07002273 protected int getAssociatedLowerPageBound(int page) {
2274 return Math.max(0, page - 1);
2275 }
2276 protected int getAssociatedUpperPageBound(int page) {
2277 final int count = getChildCount();
2278 return Math.min(page + 1, count - 1);
2279 }
2280
Winson Chung86f77532010-08-24 11:08:22 -07002281 /**
2282 * This method is called ONLY to synchronize the number of pages that the paged view has.
2283 * To actually fill the pages with information, implement syncPageItems() below. It is
2284 * guaranteed that syncPageItems() will be called for a particular page before it is shown,
2285 * and therefore, individual page items do not need to be updated in this method.
2286 */
Winson Chung321e9ee2010-08-09 13:37:56 -07002287 public abstract void syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002288
2289 /**
2290 * This method is called to synchronize the items that are on a particular page. If views on
2291 * the page can be reused, then they should be updated within this method.
2292 */
Winson Chungf314b0e2011-08-16 11:54:27 -07002293 public abstract void syncPageItems(int page, boolean immediate);
Winson Chung86f77532010-08-24 11:08:22 -07002294
Patrick Dubroy244d74c2011-05-19 16:48:48 -07002295 protected void invalidatePageData() {
Winson Chungf314b0e2011-08-16 11:54:27 -07002296 invalidatePageData(-1, false);
Winson Chung5a808352011-06-27 19:08:49 -07002297 }
2298 protected void invalidatePageData(int currentPage) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002299 invalidatePageData(currentPage, false);
2300 }
2301 protected void invalidatePageData(int currentPage, boolean immediateAndOnly) {
Winson Chungf0ea4d32011-06-06 14:27:16 -07002302 if (!mIsDataReady) {
2303 return;
2304 }
2305
Michael Jurka0142d492010-08-25 17:46:15 -07002306 if (mContentIsRefreshable) {
Adam Cohen0cd3b642011-10-14 14:58:00 -07002307 // Force all scrolling-related behavior to end
2308 mScroller.forceFinished(true);
2309 mNextPage = INVALID_PAGE;
2310
Michael Jurka0142d492010-08-25 17:46:15 -07002311 // Update all the pages
2312 syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002313
Winson Chung5a808352011-06-27 19:08:49 -07002314 // We must force a measure after we've loaded the pages to update the content width and
2315 // to determine the full scroll width
2316 measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY),
2317 MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY));
2318
2319 // Set a new page as the current page if necessary
2320 if (currentPage > -1) {
Winson Chung5afbf7b2011-07-25 11:53:08 -07002321 setCurrentPage(Math.min(getPageCount() - 1, currentPage));
Winson Chung5a808352011-06-27 19:08:49 -07002322 }
2323
Michael Jurka0142d492010-08-25 17:46:15 -07002324 // Mark each of the pages as dirty
2325 final int count = getChildCount();
2326 mDirtyPageContent.clear();
2327 for (int i = 0; i < count; ++i) {
2328 mDirtyPageContent.add(true);
2329 }
2330
2331 // Load any pages that are necessary for the current window of views
Winson Chungf314b0e2011-08-16 11:54:27 -07002332 loadAssociatedPages(mCurrentPage, immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002333 requestLayout();
Winson Chung86f77532010-08-24 11:08:22 -07002334 }
Adam Cohen06559042013-09-29 18:30:56 -07002335 if (isPageMoving()) {
2336 // If the page is moving, then snap it to the final position to ensure we don't get
2337 // stuck between pages
2338 snapToDestination();
2339 }
Winson Chung321e9ee2010-08-09 13:37:56 -07002340 }
Winson Chung007c6982011-06-14 13:27:53 -07002341
Adam Cohen7d30a372013-07-01 17:03:59 -07002342 // Animate the drag view back to the original position
2343 void animateDragViewToOriginalPosition() {
2344 if (mDragView != null) {
2345 AnimatorSet anim = new AnimatorSet();
2346 anim.setDuration(REORDERING_DROP_REPOSITION_DURATION);
2347 anim.playTogether(
2348 ObjectAnimator.ofFloat(mDragView, "translationX", 0f),
Adam Cohenf358a4b2013-07-23 16:47:31 -07002349 ObjectAnimator.ofFloat(mDragView, "translationY", 0f),
2350 ObjectAnimator.ofFloat(mDragView, "scaleX", 1f),
2351 ObjectAnimator.ofFloat(mDragView, "scaleY", 1f));
Adam Cohen7d30a372013-07-01 17:03:59 -07002352 anim.addListener(new AnimatorListenerAdapter() {
2353 @Override
2354 public void onAnimationEnd(Animator animation) {
2355 onPostReorderingAnimationCompleted();
2356 }
2357 });
2358 anim.start();
2359 }
Winson Chung3ac74c52011-06-30 17:39:37 -07002360 }
2361
Adam Cohen7d30a372013-07-01 17:03:59 -07002362 protected void onStartReordering() {
2363 // Set the touch state to reordering (allows snapping to pages, dragging a child, etc.)
2364 mTouchState = TOUCH_STATE_REORDERING;
2365 mIsReordering = true;
2366
Adam Cohen7d30a372013-07-01 17:03:59 -07002367 // We must invalidate to trigger a redraw to update the layers such that the drag view
2368 // is always drawn on top
2369 invalidate();
2370 }
2371
2372 private void onPostReorderingAnimationCompleted() {
2373 // Trigger the callback when reordering has settled
2374 --mPostReorderingPreZoomInRemainingAnimationCount;
2375 if (mPostReorderingPreZoomInRunnable != null &&
2376 mPostReorderingPreZoomInRemainingAnimationCount == 0) {
2377 mPostReorderingPreZoomInRunnable.run();
2378 mPostReorderingPreZoomInRunnable = null;
2379 }
2380 }
2381
2382 protected void onEndReordering() {
2383 mIsReordering = false;
Adam Cohen7d30a372013-07-01 17:03:59 -07002384 }
2385
Adam Cohenf358a4b2013-07-23 16:47:31 -07002386 public boolean startReordering(View v) {
Adam Cohen93c97562013-09-26 13:48:01 -07002387 int dragViewIndex = indexOfChild(v);
2388
2389 if (mTouchState != TOUCH_STATE_REST) return false;
2390
Adam Cohen7d30a372013-07-01 17:03:59 -07002391 mTempVisiblePagesRange[0] = 0;
2392 mTempVisiblePagesRange[1] = getPageCount() - 1;
Adam Cohenf358a4b2013-07-23 16:47:31 -07002393 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002394 mReorderingStarted = true;
2395
2396 // Check if we are within the reordering range
2397 if (mTempVisiblePagesRange[0] <= dragViewIndex &&
Adam Cohenf358a4b2013-07-23 16:47:31 -07002398 dragViewIndex <= mTempVisiblePagesRange[1]) {
2399 // Find the drag view under the pointer
2400 mDragView = getChildAt(dragViewIndex);
2401 mDragView.animate().scaleX(1.15f).scaleY(1.15f).setDuration(100).start();
2402 mDragViewBaselineLeft = mDragView.getLeft();
2403 disableFreeScroll(-1);
2404 onStartReordering();
Adam Cohen7d30a372013-07-01 17:03:59 -07002405 return true;
2406 }
2407 return false;
2408 }
2409
2410 boolean isReordering(boolean testTouchState) {
2411 boolean state = mIsReordering;
2412 if (testTouchState) {
2413 state &= (mTouchState == TOUCH_STATE_REORDERING);
2414 }
2415 return state;
2416 }
2417 void endReordering() {
2418 // For simplicity, we call endReordering sometimes even if reordering was never started.
2419 // In that case, we don't want to do anything.
2420 if (!mReorderingStarted) return;
2421 mReorderingStarted = false;
2422
2423 // If we haven't flung-to-delete the current child, then we just animate the drag view
2424 // back into position
2425 final Runnable onCompleteRunnable = new Runnable() {
2426 @Override
2427 public void run() {
2428 onEndReordering();
2429 }
2430 };
2431 if (!mDeferringForDelete) {
2432 mPostReorderingPreZoomInRunnable = new Runnable() {
2433 public void run() {
Adam Cohenf358a4b2013-07-23 16:47:31 -07002434 onCompleteRunnable.run();
2435 enableFreeScroll();
Adam Cohen7d30a372013-07-01 17:03:59 -07002436 };
2437 };
2438
2439 mPostReorderingPreZoomInRemainingAnimationCount =
2440 NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT;
2441 // Snap to the current page
2442 snapToPage(indexOfChild(mDragView), 0);
2443 // Animate the drag view back to the front position
2444 animateDragViewToOriginalPosition();
2445 } else {
2446 // Handled in post-delete-animation-callbacks
2447 }
2448 }
2449
Adam Cohen7d30a372013-07-01 17:03:59 -07002450 /*
2451 * Flinging to delete - IN PROGRESS
2452 */
2453 private PointF isFlingingToDelete() {
2454 ViewConfiguration config = ViewConfiguration.get(getContext());
2455 mVelocityTracker.computeCurrentVelocity(1000, config.getScaledMaximumFlingVelocity());
2456
2457 if (mVelocityTracker.getYVelocity() < mFlingToDeleteThresholdVelocity) {
2458 // Do a quick dot product test to ensure that we are flinging upwards
2459 PointF vel = new PointF(mVelocityTracker.getXVelocity(),
2460 mVelocityTracker.getYVelocity());
2461 PointF upVec = new PointF(0f, -1f);
2462 float theta = (float) Math.acos(((vel.x * upVec.x) + (vel.y * upVec.y)) /
2463 (vel.length() * upVec.length()));
2464 if (theta <= Math.toRadians(FLING_TO_DELETE_MAX_FLING_DEGREES)) {
2465 return vel;
2466 }
2467 }
2468 return null;
2469 }
2470
2471 /**
2472 * Creates an animation from the current drag view along its current velocity vector.
2473 * For this animation, the alpha runs for a fixed duration and we update the position
2474 * progressively.
2475 */
2476 private static class FlingAlongVectorAnimatorUpdateListener implements AnimatorUpdateListener {
2477 private View mDragView;
2478 private PointF mVelocity;
2479 private Rect mFrom;
2480 private long mPrevTime;
2481 private float mFriction;
2482
2483 private final TimeInterpolator mAlphaInterpolator = new DecelerateInterpolator(0.75f);
2484
2485 public FlingAlongVectorAnimatorUpdateListener(View dragView, PointF vel, Rect from,
2486 long startTime, float friction) {
2487 mDragView = dragView;
2488 mVelocity = vel;
2489 mFrom = from;
2490 mPrevTime = startTime;
2491 mFriction = 1f - (mDragView.getResources().getDisplayMetrics().density * friction);
2492 }
2493
2494 @Override
2495 public void onAnimationUpdate(ValueAnimator animation) {
2496 float t = ((Float) animation.getAnimatedValue()).floatValue();
2497 long curTime = AnimationUtils.currentAnimationTimeMillis();
2498
2499 mFrom.left += (mVelocity.x * (curTime - mPrevTime) / 1000f);
2500 mFrom.top += (mVelocity.y * (curTime - mPrevTime) / 1000f);
2501
2502 mDragView.setTranslationX(mFrom.left);
2503 mDragView.setTranslationY(mFrom.top);
2504 mDragView.setAlpha(1f - mAlphaInterpolator.getInterpolation(t));
2505
2506 mVelocity.x *= mFriction;
2507 mVelocity.y *= mFriction;
2508 mPrevTime = curTime;
2509 }
2510 };
2511
2512 private static final int ANIM_TAG_KEY = 100;
2513
2514 private Runnable createPostDeleteAnimationRunnable(final View dragView) {
2515 return new Runnable() {
2516 @Override
2517 public void run() {
2518 int dragViewIndex = indexOfChild(dragView);
2519
2520 // For each of the pages around the drag view, animate them from the previous
2521 // position to the new position in the layout (as a result of the drag view moving
2522 // in the layout)
2523 // NOTE: We can make an assumption here because we have side-bound pages that we
2524 // will always have pages to animate in from the left
Adam Cohenf358a4b2013-07-23 16:47:31 -07002525 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002526 boolean isLastWidgetPage = (mTempVisiblePagesRange[0] == mTempVisiblePagesRange[1]);
2527 boolean slideFromLeft = (isLastWidgetPage ||
2528 dragViewIndex > mTempVisiblePagesRange[0]);
2529
2530 // Setup the scroll to the correct page before we swap the views
2531 if (slideFromLeft) {
2532 snapToPageImmediately(dragViewIndex - 1);
2533 }
2534
2535 int firstIndex = (isLastWidgetPage ? 0 : mTempVisiblePagesRange[0]);
2536 int lastIndex = Math.min(mTempVisiblePagesRange[1], getPageCount() - 1);
2537 int lowerIndex = (slideFromLeft ? firstIndex : dragViewIndex + 1 );
2538 int upperIndex = (slideFromLeft ? dragViewIndex - 1 : lastIndex);
2539 ArrayList<Animator> animations = new ArrayList<Animator>();
2540 for (int i = lowerIndex; i <= upperIndex; ++i) {
2541 View v = getChildAt(i);
2542 // dragViewIndex < pageUnderPointIndex, so after we remove the
2543 // drag view all subsequent views to pageUnderPointIndex will
2544 // shift down.
2545 int oldX = 0;
2546 int newX = 0;
2547 if (slideFromLeft) {
2548 if (i == 0) {
2549 // Simulate the page being offscreen with the page spacing
2550 oldX = getViewportOffsetX() + getChildOffset(i) - getChildWidth(i)
2551 - mPageSpacing;
2552 } else {
2553 oldX = getViewportOffsetX() + getChildOffset(i - 1);
2554 }
2555 newX = getViewportOffsetX() + getChildOffset(i);
2556 } else {
2557 oldX = getChildOffset(i) - getChildOffset(i - 1);
2558 newX = 0;
2559 }
2560
2561 // Animate the view translation from its old position to its new
2562 // position
2563 AnimatorSet anim = (AnimatorSet) v.getTag();
2564 if (anim != null) {
2565 anim.cancel();
2566 }
2567
2568 // Note: Hacky, but we want to skip any optimizations to not draw completely
2569 // hidden views
2570 v.setAlpha(Math.max(v.getAlpha(), 0.01f));
2571 v.setTranslationX(oldX - newX);
2572 anim = new AnimatorSet();
2573 anim.playTogether(
2574 ObjectAnimator.ofFloat(v, "translationX", 0f),
2575 ObjectAnimator.ofFloat(v, "alpha", 1f));
2576 animations.add(anim);
2577 v.setTag(ANIM_TAG_KEY, anim);
2578 }
2579
2580 AnimatorSet slideAnimations = new AnimatorSet();
2581 slideAnimations.playTogether(animations);
2582 slideAnimations.setDuration(DELETE_SLIDE_IN_SIDE_PAGE_DURATION);
2583 slideAnimations.addListener(new AnimatorListenerAdapter() {
2584 @Override
2585 public void onAnimationEnd(Animator animation) {
Adam Cohenf358a4b2013-07-23 16:47:31 -07002586 mDeferringForDelete = false;
2587 onEndReordering();
2588 onRemoveViewAnimationCompleted();
Adam Cohen7d30a372013-07-01 17:03:59 -07002589 }
2590 });
2591 slideAnimations.start();
2592
2593 removeView(dragView);
2594 onRemoveView(dragView, true);
2595 }
2596 };
2597 }
2598
2599 public void onFlingToDelete(PointF vel) {
2600 final long startTime = AnimationUtils.currentAnimationTimeMillis();
2601
2602 // NOTE: Because it takes time for the first frame of animation to actually be
2603 // called and we expect the animation to be a continuation of the fling, we have
2604 // to account for the time that has elapsed since the fling finished. And since
2605 // we don't have a startDelay, we will always get call to update when we call
2606 // start() (which we want to ignore).
2607 final TimeInterpolator tInterpolator = new TimeInterpolator() {
2608 private int mCount = -1;
2609 private long mStartTime;
2610 private float mOffset;
2611 /* Anonymous inner class ctor */ {
2612 mStartTime = startTime;
2613 }
2614
2615 @Override
2616 public float getInterpolation(float t) {
2617 if (mCount < 0) {
2618 mCount++;
2619 } else if (mCount == 0) {
2620 mOffset = Math.min(0.5f, (float) (AnimationUtils.currentAnimationTimeMillis() -
2621 mStartTime) / FLING_TO_DELETE_FADE_OUT_DURATION);
2622 mCount++;
2623 }
2624 return Math.min(1f, mOffset + t);
2625 }
2626 };
2627
2628 final Rect from = new Rect();
2629 final View dragView = mDragView;
2630 from.left = (int) dragView.getTranslationX();
2631 from.top = (int) dragView.getTranslationY();
2632 AnimatorUpdateListener updateCb = new FlingAlongVectorAnimatorUpdateListener(dragView, vel,
2633 from, startTime, FLING_TO_DELETE_FRICTION);
2634
2635 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2636
2637 // Create and start the animation
2638 ValueAnimator mDropAnim = new ValueAnimator();
2639 mDropAnim.setInterpolator(tInterpolator);
2640 mDropAnim.setDuration(FLING_TO_DELETE_FADE_OUT_DURATION);
2641 mDropAnim.setFloatValues(0f, 1f);
2642 mDropAnim.addUpdateListener(updateCb);
2643 mDropAnim.addListener(new AnimatorListenerAdapter() {
2644 public void onAnimationEnd(Animator animation) {
2645 onAnimationEndRunnable.run();
2646 }
2647 });
2648 mDropAnim.start();
2649 mDeferringForDelete = true;
2650 }
2651
2652 /* Drag to delete */
2653 private boolean isHoveringOverDeleteDropTarget(int x, int y) {
2654 if (mDeleteDropTarget != null) {
2655 mAltTmpRect.set(0, 0, 0, 0);
2656 View parent = (View) mDeleteDropTarget.getParent();
2657 if (parent != null) {
2658 parent.getGlobalVisibleRect(mAltTmpRect);
2659 }
2660 mDeleteDropTarget.getGlobalVisibleRect(mTmpRect);
2661 mTmpRect.offset(-mAltTmpRect.left, -mAltTmpRect.top);
2662 return mTmpRect.contains(x, y);
2663 }
2664 return false;
2665 }
2666
2667 protected void setPageHoveringOverDeleteDropTarget(int viewIndex, boolean isHovering) {}
2668
2669 private void onDropToDelete() {
2670 final View dragView = mDragView;
2671
2672 final float toScale = 0f;
2673 final float toAlpha = 0f;
2674
2675 // Create and start the complex animation
2676 ArrayList<Animator> animations = new ArrayList<Animator>();
2677 AnimatorSet motionAnim = new AnimatorSet();
2678 motionAnim.setInterpolator(new DecelerateInterpolator(2));
2679 motionAnim.playTogether(
2680 ObjectAnimator.ofFloat(dragView, "scaleX", toScale),
2681 ObjectAnimator.ofFloat(dragView, "scaleY", toScale));
2682 animations.add(motionAnim);
2683
2684 AnimatorSet alphaAnim = new AnimatorSet();
2685 alphaAnim.setInterpolator(new LinearInterpolator());
2686 alphaAnim.playTogether(
2687 ObjectAnimator.ofFloat(dragView, "alpha", toAlpha));
2688 animations.add(alphaAnim);
2689
2690 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2691
2692 AnimatorSet anim = new AnimatorSet();
2693 anim.playTogether(animations);
2694 anim.setDuration(DRAG_TO_DELETE_FADE_OUT_DURATION);
2695 anim.addListener(new AnimatorListenerAdapter() {
2696 public void onAnimationEnd(Animator animation) {
2697 onAnimationEndRunnable.run();
2698 }
2699 });
2700 anim.start();
2701
2702 mDeferringForDelete = true;
Winson Chung007c6982011-06-14 13:27:53 -07002703 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002704
2705 /* Accessibility */
2706 @Override
2707 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
2708 super.onInitializeAccessibilityNodeInfo(info);
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002709 info.setScrollable(getPageCount() > 1);
2710 if (getCurrentPage() < getPageCount() - 1) {
2711 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
2712 }
2713 if (getCurrentPage() > 0) {
2714 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
2715 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002716 }
2717
2718 @Override
2719 public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
2720 super.onInitializeAccessibilityEvent(event);
2721 event.setScrollable(true);
2722 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_SCROLLED) {
2723 event.setFromIndex(mCurrentPage);
2724 event.setToIndex(mCurrentPage);
2725 event.setItemCount(getChildCount());
2726 }
2727 }
2728
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002729 @Override
2730 public boolean performAccessibilityAction(int action, Bundle arguments) {
2731 if (super.performAccessibilityAction(action, arguments)) {
2732 return true;
2733 }
2734 switch (action) {
2735 case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: {
2736 if (getCurrentPage() < getPageCount() - 1) {
2737 scrollRight();
2738 return true;
2739 }
2740 } break;
2741 case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: {
2742 if (getCurrentPage() > 0) {
2743 scrollLeft();
2744 return true;
2745 }
2746 } break;
2747 }
2748 return false;
2749 }
2750
Adam Cohen0ffac432013-07-10 11:19:26 -07002751 protected String getCurrentPageDescription() {
2752 return String.format(getContext().getString(R.string.default_scroll_format),
2753 getNextPage() + 1, getChildCount());
2754 }
2755
Winson Chungd11265e2011-08-30 13:37:23 -07002756 @Override
2757 public boolean onHoverEvent(android.view.MotionEvent event) {
2758 return true;
2759 }
Adam Cohen5084cba2013-09-03 12:01:16 -07002760}