blob: 31a979760d05229b312c122d75402ac1a3c15b57 [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
Winson Chung86f77532010-08-24 11:08:22 -0700268 public interface PageSwitchListener {
269 void onPageSwitch(View newPage, int newPageIndex);
Winson Chung321e9ee2010-08-09 13:37:56 -0700270 }
271
Winson Chung321e9ee2010-08-09 13:37:56 -0700272 public PagedView(Context context) {
273 this(context, null);
274 }
275
276 public PagedView(Context context, AttributeSet attrs) {
277 this(context, attrs, 0);
278 }
279
280 public PagedView(Context context, AttributeSet attrs, int defStyle) {
281 super(context, attrs, defStyle);
Winson Chungc9ca2982013-07-19 12:07:38 -0700282
Adam Cohen9c4949e2010-10-05 12:27:22 -0700283 TypedArray a = context.obtainStyledAttributes(attrs,
284 R.styleable.PagedView, defStyle, 0);
Adam Cohen60b07122011-11-14 17:26:06 -0800285 setPageSpacing(a.getDimensionPixelSize(R.styleable.PagedView_pageSpacing, 0));
Adam Cohen7d30a372013-07-01 17:03:59 -0700286 if (mPageSpacing < 0) {
287 mAutoComputePageSpacing = mRecomputePageSpacing = true;
288 }
Adam Cohen9c4949e2010-10-05 12:27:22 -0700289 mPageLayoutPaddingTop = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800290 R.styleable.PagedView_pageLayoutPaddingTop, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700291 mPageLayoutPaddingBottom = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800292 R.styleable.PagedView_pageLayoutPaddingBottom, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700293 mPageLayoutPaddingLeft = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800294 R.styleable.PagedView_pageLayoutPaddingLeft, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700295 mPageLayoutPaddingRight = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800296 R.styleable.PagedView_pageLayoutPaddingRight, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700297 mPageLayoutWidthGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700298 R.styleable.PagedView_pageLayoutWidthGap, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700299 mPageLayoutHeightGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700300 R.styleable.PagedView_pageLayoutHeightGap, 0);
Winson Chungd2be3812013-07-16 11:11:32 -0700301 mPageIndicatorViewId = a.getResourceId(R.styleable.PagedView_pageIndicator, -1);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700302 a.recycle();
303
Winson Chung321e9ee2010-08-09 13:37:56 -0700304 setHapticFeedbackEnabled(false);
Michael Jurka0142d492010-08-25 17:46:15 -0700305 init();
Winson Chung321e9ee2010-08-09 13:37:56 -0700306 }
307
308 /**
309 * Initializes various states for this workspace.
310 */
Michael Jurka0142d492010-08-25 17:46:15 -0700311 protected void init() {
Winson Chung86f77532010-08-24 11:08:22 -0700312 mDirtyPageContent = new ArrayList<Boolean>();
313 mDirtyPageContent.ensureCapacity(32);
Adam Cohene0f66b52010-11-23 15:06:07 -0800314 mScroller = new Scroller(getContext(), new ScrollInterpolator());
Winson Chung86f77532010-08-24 11:08:22 -0700315 mCurrentPage = 0;
Winson Chung7da10252010-10-28 16:07:04 -0700316 mCenterPagesVertically = true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700317
318 final ViewConfiguration configuration = ViewConfiguration.get(getContext());
Adam Cohen7d30a372013-07-01 17:03:59 -0700319 mTouchSlop = configuration.getScaledPagingTouchSlop();
Winson Chung321e9ee2010-08-09 13:37:56 -0700320 mPagingTouchSlop = configuration.getScaledPagingTouchSlop();
321 mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
Adam Cohenb5ba0972011-09-07 18:02:31 -0700322 mDensity = getResources().getDisplayMetrics().density;
Adam Cohen265b9a62011-12-07 14:37:18 -0800323
Adam Cohen7d30a372013-07-01 17:03:59 -0700324 // Scale the fling-to-delete threshold by the density
325 mFlingToDeleteThresholdVelocity =
326 (int) (mFlingToDeleteThresholdVelocity * mDensity);
327
Adam Cohen265b9a62011-12-07 14:37:18 -0800328 mFlingThresholdVelocity = (int) (FLING_THRESHOLD_VELOCITY * mDensity);
329 mMinFlingVelocity = (int) (MIN_FLING_VELOCITY * mDensity);
330 mMinSnapVelocity = (int) (MIN_SNAP_VELOCITY * mDensity);
Michael Jurka8b805b12012-04-18 14:23:14 -0700331 setOnHierarchyChangeListener(this);
Winson Chung321e9ee2010-08-09 13:37:56 -0700332 }
333
Winson Chungd2be3812013-07-16 11:11:32 -0700334 protected void onAttachedToWindow() {
335 // Hook up the page indicator
336 ViewGroup parent = (ViewGroup) getParent();
337 if (mPageIndicator == null && mPageIndicatorViewId > -1) {
338 mPageIndicator = (PageIndicator) parent.findViewById(mPageIndicatorViewId);
Winson Chungc58497e2013-09-03 17:48:37 -0700339 mPageIndicator.removeAllMarkers(mAllowPagedViewAnimations);
Winson Chung82dfe582013-07-26 15:07:49 -0700340
Winson Chung7819a562013-09-19 15:55:45 -0700341 ArrayList<PageIndicator.PageMarkerResources> markers =
342 new ArrayList<PageIndicator.PageMarkerResources>();
Winson Chung82dfe582013-07-26 15:07:49 -0700343 for (int i = 0; i < getChildCount(); ++i) {
344 markers.add(getPageIndicatorMarker(i));
345 }
Adam Cohenf358a4b2013-07-23 16:47:31 -0700346
Winson Chungc58497e2013-09-03 17:48:37 -0700347 mPageIndicator.addMarkers(markers, mAllowPagedViewAnimations);
Winson Chungd2be3812013-07-16 11:11:32 -0700348 }
349 }
350
351 protected void onDetachedFromWindow() {
352 // Unhook the page indicator
353 mPageIndicator = null;
354 }
355
Adam Cohen7d30a372013-07-01 17:03:59 -0700356 void setDeleteDropTarget(View v) {
357 mDeleteDropTarget = v;
358 }
359
360 // Convenience methods to map points from self to parent and vice versa
361 float[] mapPointFromViewToParent(View v, float x, float y) {
362 mTmpPoint[0] = x;
363 mTmpPoint[1] = y;
364 v.getMatrix().mapPoints(mTmpPoint);
365 mTmpPoint[0] += v.getLeft();
366 mTmpPoint[1] += v.getTop();
367 return mTmpPoint;
368 }
369 float[] mapPointFromParentToView(View v, float x, float y) {
370 mTmpPoint[0] = x - v.getLeft();
371 mTmpPoint[1] = y - v.getTop();
372 v.getMatrix().invert(mTmpInvMatrix);
373 mTmpInvMatrix.mapPoints(mTmpPoint);
374 return mTmpPoint;
375 }
376
377 void updateDragViewTranslationDuringDrag() {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700378 if (mDragView != null) {
379 float x = (mLastMotionX - mDownMotionX) + (getScrollX() - mDownScrollX) +
380 (mDragViewBaselineLeft - mDragView.getLeft());
381 float y = mLastMotionY - mDownMotionY;
382 mDragView.setTranslationX(x);
383 mDragView.setTranslationY(y);
Adam Cohen7d30a372013-07-01 17:03:59 -0700384
Adam Cohenf358a4b2013-07-23 16:47:31 -0700385 if (DEBUG) Log.d(TAG, "PagedView.updateDragViewTranslationDuringDrag(): "
386 + x + ", " + y);
387 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700388 }
389
390 public void setMinScale(float f) {
391 mMinScale = f;
Winson Chungc58497e2013-09-03 17:48:37 -0700392 mUseMinScale = true;
Adam Cohen7d30a372013-07-01 17:03:59 -0700393 requestLayout();
394 }
395
396 @Override
397 public void setScaleX(float scaleX) {
398 super.setScaleX(scaleX);
399 if (isReordering(true)) {
400 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
401 mLastMotionX = p[0];
402 mLastMotionY = p[1];
403 updateDragViewTranslationDuringDrag();
404 }
405 }
406
407 // Convenience methods to get the actual width/height of the PagedView (since it is measured
408 // to be larger to account for the minimum possible scale)
409 int getViewportWidth() {
410 return mViewport.width();
411 }
412 int getViewportHeight() {
413 return mViewport.height();
414 }
415
416 // Convenience methods to get the offset ASSUMING that we are centering the pages in the
417 // PagedView both horizontally and vertically
418 int getViewportOffsetX() {
419 return (getMeasuredWidth() - getViewportWidth()) / 2;
420 }
421
422 int getViewportOffsetY() {
423 return (getMeasuredHeight() - getViewportHeight()) / 2;
424 }
425
Adam Cohenedb40762013-07-18 16:45:45 -0700426 PageIndicator getPageIndicator() {
427 return mPageIndicator;
428 }
Winson Chung7819a562013-09-19 15:55:45 -0700429 protected PageIndicator.PageMarkerResources getPageIndicatorMarker(int pageIndex) {
430 return new PageIndicator.PageMarkerResources();
Winson Chung82dfe582013-07-26 15:07:49 -0700431 }
Adam Cohenedb40762013-07-18 16:45:45 -0700432
Winson Chung86f77532010-08-24 11:08:22 -0700433 public void setPageSwitchListener(PageSwitchListener pageSwitchListener) {
434 mPageSwitchListener = pageSwitchListener;
435 if (mPageSwitchListener != null) {
436 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700437 }
438 }
439
440 /**
Winson Chung52aee602013-01-30 12:01:02 -0800441 * Note: this is a reimplementation of View.isLayoutRtl() since that is currently hidden api.
442 */
443 public boolean isLayoutRtl() {
444 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
445 }
446
447 /**
Winson Chungf0ea4d32011-06-06 14:27:16 -0700448 * Called by subclasses to mark that data is ready, and that we can begin loading and laying
449 * out pages.
450 */
451 protected void setDataIsReady() {
452 mIsDataReady = true;
453 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700454
Winson Chungf0ea4d32011-06-06 14:27:16 -0700455 protected boolean isDataReady() {
456 return mIsDataReady;
457 }
458
459 /**
Winson Chung86f77532010-08-24 11:08:22 -0700460 * Returns the index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700461 *
Winson Chung86f77532010-08-24 11:08:22 -0700462 * @return The index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700463 */
Winson Chung86f77532010-08-24 11:08:22 -0700464 int getCurrentPage() {
465 return mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -0700466 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700467
Winson Chung360e63f2012-04-27 13:48:05 -0700468 int getNextPage() {
469 return (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
470 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700471
Winson Chung86f77532010-08-24 11:08:22 -0700472 int getPageCount() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700473 return getChildCount();
474 }
475
Winson Chung86f77532010-08-24 11:08:22 -0700476 View getPageAt(int index) {
Winson Chung321e9ee2010-08-09 13:37:56 -0700477 return getChildAt(index);
478 }
479
Adam Cohenae4f1552011-10-20 00:15:42 -0700480 protected int indexToPage(int index) {
481 return index;
482 }
483
Winson Chung321e9ee2010-08-09 13:37:56 -0700484 /**
Winson Chungbbc60d82010-11-11 16:34:41 -0800485 * Updates the scroll of the current page immediately to its final scroll position. We use this
486 * in CustomizePagedView to allow tabs to share the same PagedView while resetting the scroll of
487 * the previous tab page.
488 */
489 protected void updateCurrentPageScroll() {
Adam Cohen0ffac432013-07-10 11:19:26 -0700490 // If the current page is invalid, just reset the scroll position to zero
491 int newX = 0;
492 if (0 <= mCurrentPage && mCurrentPage < getPageCount()) {
Adam Cohenedb40762013-07-18 16:45:45 -0700493 newX = getScrollForPage(mCurrentPage);
Adam Cohen0ffac432013-07-10 11:19:26 -0700494 }
Winson Chungbbc60d82010-11-11 16:34:41 -0800495 scrollTo(newX, 0);
496 mScroller.setFinalX(newX);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800497 mScroller.forceFinished(true);
Winson Chungbbc60d82010-11-11 16:34:41 -0800498 }
499
500 /**
Chet Haasebc2f0822012-10-26 17:59:53 -0700501 * Called during AllApps/Home transitions to avoid unnecessary work. When that other animation
502 * ends, {@link #resumeScrolling()} should be called, along with
503 * {@link #updateCurrentPageScroll()} to correctly set the final state and re-enable scrolling.
504 */
505 void pauseScrolling() {
506 mScroller.forceFinished(true);
Chet Haasebc2f0822012-10-26 17:59:53 -0700507 }
508
509 /**
510 * Enables scrolling again.
511 * @see #pauseScrolling()
512 */
513 void resumeScrolling() {
Chet Haasebc2f0822012-10-26 17:59:53 -0700514 }
515 /**
Winson Chung86f77532010-08-24 11:08:22 -0700516 * Sets the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700517 */
Winson Chung86f77532010-08-24 11:08:22 -0700518 void setCurrentPage(int currentPage) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800519 if (!mScroller.isFinished()) {
520 mScroller.abortAnimation();
521 }
Michael Jurkad3ef3062010-11-23 16:23:58 -0800522 // don't introduce any checks like mCurrentPage == currentPage here-- if we change the
523 // the default
524 if (getChildCount() == 0) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800525 return;
526 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700527
Adam Cohene61a9a22013-06-11 15:45:31 -0700528 mForceScreenScrolled = true;
Winson Chung86f77532010-08-24 11:08:22 -0700529 mCurrentPage = Math.max(0, Math.min(currentPage, getPageCount() - 1));
Winson Chung181c3dc2013-07-17 15:36:20 -0700530 updateCurrentPageScroll();
Winson Chung86f77532010-08-24 11:08:22 -0700531 notifyPageSwitchListener();
Winson Chunga12a2502010-12-20 14:41:35 -0800532 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -0700533 }
534
Winson Chung8c87cd82013-07-23 16:20:10 -0700535 /**
536 * The restore page will be set in place of the current page at the next (likely first)
537 * layout.
538 */
539 void setRestorePage(int restorePage) {
540 mRestorePage = restorePage;
541 }
542
Michael Jurka0142d492010-08-25 17:46:15 -0700543 protected void notifyPageSwitchListener() {
Winson Chung86f77532010-08-24 11:08:22 -0700544 if (mPageSwitchListener != null) {
545 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700546 }
Winson Chungd2be3812013-07-16 11:11:32 -0700547
548 // Update the page indicator (when we aren't reordering)
549 if (mPageIndicator != null && !isReordering(false)) {
550 mPageIndicator.setActiveMarker(getNextPage());
551 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700552 }
Michael Jurkace7e05f2011-02-01 22:02:35 -0800553 protected void pageBeginMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700554 if (!mIsPageMoving) {
555 mIsPageMoving = true;
556 onPageBeginMoving();
557 }
Patrick Dubroy1262e362010-10-06 15:49:50 -0700558 }
559
Michael Jurkace7e05f2011-02-01 22:02:35 -0800560 protected void pageEndMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700561 if (mIsPageMoving) {
562 mIsPageMoving = false;
563 onPageEndMoving();
564 }
Michael Jurka0142d492010-08-25 17:46:15 -0700565 }
566
Adam Cohen26976d92011-03-22 15:33:33 -0700567 protected boolean isPageMoving() {
568 return mIsPageMoving;
569 }
570
Michael Jurka0142d492010-08-25 17:46:15 -0700571 // a method that subclasses can override to add behavior
Patrick Dubroy1262e362010-10-06 15:49:50 -0700572 protected void onPageBeginMoving() {
573 }
574
575 // a method that subclasses can override to add behavior
576 protected void onPageEndMoving() {
Michael Jurka0142d492010-08-25 17:46:15 -0700577 }
578
Winson Chung321e9ee2010-08-09 13:37:56 -0700579 /**
Winson Chung86f77532010-08-24 11:08:22 -0700580 * Registers the specified listener on each page contained in this workspace.
Winson Chung321e9ee2010-08-09 13:37:56 -0700581 *
582 * @param l The listener used to respond to long clicks.
583 */
584 @Override
585 public void setOnLongClickListener(OnLongClickListener l) {
586 mLongClickListener = l;
Winson Chung86f77532010-08-24 11:08:22 -0700587 final int count = getPageCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700588 for (int i = 0; i < count; i++) {
Winson Chung86f77532010-08-24 11:08:22 -0700589 getPageAt(i).setOnLongClickListener(l);
Winson Chung321e9ee2010-08-09 13:37:56 -0700590 }
Adam Cohen1697b792013-09-17 19:08:21 -0700591 super.setOnLongClickListener(l);
Winson Chung321e9ee2010-08-09 13:37:56 -0700592 }
593
594 @Override
Adam Cohen68d73932010-11-15 10:50:58 -0800595 public void scrollBy(int x, int y) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700596 scrollTo(mUnboundedScrollX + x, getScrollY() + y);
Adam Cohen68d73932010-11-15 10:50:58 -0800597 }
598
599 @Override
Michael Jurka0142d492010-08-25 17:46:15 -0700600 public void scrollTo(int x, int y) {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700601 // In free scroll mode, we clamp the scrollX
602 if (mFreeScroll) {
603 x = Math.min(x, mFreeScrollMaxScrollX);
604 x = Math.max(x, mFreeScrollMinScrollX);
605 }
606
Adam Cohen0ffac432013-07-10 11:19:26 -0700607 final boolean isRtl = isLayoutRtl();
Adam Cohen68d73932010-11-15 10:50:58 -0800608 mUnboundedScrollX = x;
609
Adam Cohen0ffac432013-07-10 11:19:26 -0700610 boolean isXBeforeFirstPage = isRtl ? (x > mMaxScrollX) : (x < 0);
611 boolean isXAfterLastPage = isRtl ? (x < 0) : (x > mMaxScrollX);
612 if (isXBeforeFirstPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800613 super.scrollTo(0, y);
614 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700615 if (isRtl) {
616 overScroll(x - mMaxScrollX);
617 } else {
618 overScroll(x);
619 }
Adam Cohen68d73932010-11-15 10:50:58 -0800620 }
Adam Cohen0ffac432013-07-10 11:19:26 -0700621 } else if (isXAfterLastPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800622 super.scrollTo(mMaxScrollX, y);
623 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700624 if (isRtl) {
625 overScroll(x);
626 } else {
627 overScroll(x - mMaxScrollX);
628 }
Adam Cohen68d73932010-11-15 10:50:58 -0800629 }
630 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -0800631 mOverScrollX = x;
Adam Cohen68d73932010-11-15 10:50:58 -0800632 super.scrollTo(x, y);
633 }
634
Michael Jurka0142d492010-08-25 17:46:15 -0700635 mTouchX = x;
636 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
Adam Cohen7d30a372013-07-01 17:03:59 -0700637
638 // Update the last motion events when scrolling
639 if (isReordering(true)) {
640 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
641 mLastMotionX = p[0];
642 mLastMotionY = p[1];
643 updateDragViewTranslationDuringDrag();
644 }
Michael Jurka0142d492010-08-25 17:46:15 -0700645 }
646
647 // we moved this functionality to a helper function so SmoothPagedView can reuse it
648 protected boolean computeScrollHelper() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700649 if (mScroller.computeScrollOffset()) {
Winson Chung557d6ed2011-07-08 15:34:52 -0700650 // Don't bother scrolling if the page does not need to be moved
Michael Jurka8b805b12012-04-18 14:23:14 -0700651 if (getScrollX() != mScroller.getCurrX()
652 || getScrollY() != mScroller.getCurrY()
Michael Jurkab06d95f2012-04-02 06:26:53 -0700653 || mOverScrollX != mScroller.getCurrX()) {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700654 float scaleX = mFreeScroll ? getScaleX() : 1f;
655 int scrollX = (int) (mScroller.getCurrX() * (1 / scaleX));
656 scrollTo(scrollX, mScroller.getCurrY());
Winson Chung557d6ed2011-07-08 15:34:52 -0700657 }
Michael Jurka0142d492010-08-25 17:46:15 -0700658 invalidate();
659 return true;
Winson Chung86f77532010-08-24 11:08:22 -0700660 } else if (mNextPage != INVALID_PAGE) {
661 mCurrentPage = Math.max(0, Math.min(mNextPage, getPageCount() - 1));
Winson Chung86f77532010-08-24 11:08:22 -0700662 mNextPage = INVALID_PAGE;
Michael Jurka0142d492010-08-25 17:46:15 -0700663 notifyPageSwitchListener();
Winson Chungb44b5242011-06-13 11:32:14 -0700664
Winson Chung9c0565f2013-07-19 13:49:06 -0700665 // Load the associated pages if necessary
666 if (mDeferLoadAssociatedPagesUntilScrollCompletes) {
667 loadAssociatedPages(mCurrentPage);
668 mDeferLoadAssociatedPagesUntilScrollCompletes = false;
669 }
670
Adam Cohen73aa9752010-11-24 16:26:58 -0800671 // We don't want to trigger a page end moving unless the page has settled
672 // and the user has stopped scrolling
673 if (mTouchState == TOUCH_STATE_REST) {
674 pageEndMoving();
675 }
Winson Chungc27d1bb2011-09-29 12:07:42 -0700676
Adam Cohen7d30a372013-07-01 17:03:59 -0700677 onPostReorderingAnimationCompleted();
Adam Cohen0ffac432013-07-10 11:19:26 -0700678 // Notify the user when the page changes
679 AccessibilityManager accessibilityManager = (AccessibilityManager)
680 getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
681 if (accessibilityManager.isEnabled()) {
682 AccessibilityEvent ev =
683 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_SCROLLED);
684 ev.getText().add(getCurrentPageDescription());
685 sendAccessibilityEventUnchecked(ev);
686 }
Michael Jurka0142d492010-08-25 17:46:15 -0700687 return true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700688 }
Michael Jurka0142d492010-08-25 17:46:15 -0700689 return false;
690 }
691
692 @Override
693 public void computeScroll() {
694 computeScrollHelper();
Winson Chung321e9ee2010-08-09 13:37:56 -0700695 }
696
Adam Cohen7d30a372013-07-01 17:03:59 -0700697 protected boolean shouldSetTopAlignedPivotForWidget(int childIndex) {
698 return mTopAlignPageWhenShrinkingForBouncer;
699 }
700
Adam Cohen96d30a12013-07-16 18:13:21 -0700701 public static class LayoutParams extends ViewGroup.LayoutParams {
702 public boolean isFullScreenPage = false;
703
704 /**
705 * {@inheritDoc}
706 */
707 public LayoutParams(int width, int height) {
708 super(width, height);
709 }
710
711 public LayoutParams(ViewGroup.LayoutParams source) {
712 super(source);
713 }
714 }
715
716 protected LayoutParams generateDefaultLayoutParams() {
717 return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
718 }
719
Adam Cohenedb40762013-07-18 16:45:45 -0700720 public void addFullScreenPage(View page) {
Adam Cohen96d30a12013-07-16 18:13:21 -0700721 LayoutParams lp = generateDefaultLayoutParams();
722 lp.isFullScreenPage = true;
723 super.addView(page, 0, lp);
724 }
725
Adam Cohen410f3cd2013-09-22 12:09:32 -0700726 public int getNormalChildHeight() {
727 return mNormalChildHeight;
728 }
729
Winson Chung321e9ee2010-08-09 13:37:56 -0700730 @Override
731 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700732 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700733 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
734 return;
735 }
736
Adam Cohen7d30a372013-07-01 17:03:59 -0700737 // We measure the dimensions of the PagedView to be larger than the pages so that when we
738 // zoom out (and scale down), the view is still contained in the parent
Adam Cohen7d30a372013-07-01 17:03:59 -0700739 int widthMode = MeasureSpec.getMode(widthMeasureSpec);
740 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
741 int heightMode = MeasureSpec.getMode(heightMeasureSpec);
Winson Chung8aad6102012-05-11 16:27:49 -0700742 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
Adam Cohen7d30a372013-07-01 17:03:59 -0700743 // NOTE: We multiply by 1.5f to account for the fact that depending on the offset of the
744 // viewport, we can be at most one and a half screens offset once we scale down
745 DisplayMetrics dm = getResources().getDisplayMetrics();
Adam Cohendbdff6b2013-09-18 19:09:15 -0700746 int maxSize = Math.max(dm.widthPixels, dm.heightPixels + mInsets.top + mInsets.bottom);
Adam Cohen410f3cd2013-09-22 12:09:32 -0700747
Winson Chungc58497e2013-09-03 17:48:37 -0700748 int parentWidthSize, parentHeightSize;
749 int scaledWidthSize, scaledHeightSize;
750 if (mUseMinScale) {
751 parentWidthSize = (int) (1.5f * maxSize);
752 parentHeightSize = maxSize;
753 scaledWidthSize = (int) (parentWidthSize / mMinScale);
754 scaledHeightSize = (int) (parentHeightSize / mMinScale);
755 } else {
756 scaledWidthSize = widthSize;
757 scaledHeightSize = heightSize;
758 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700759 mViewport.set(0, 0, widthSize, heightSize);
760
761 if (widthMode == MeasureSpec.UNSPECIFIED || heightMode == MeasureSpec.UNSPECIFIED) {
762 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
763 return;
Winson Chung321e9ee2010-08-09 13:37:56 -0700764 }
765
Winson Chung8aad6102012-05-11 16:27:49 -0700766 // Return early if we aren't given a proper dimension
767 if (widthSize <= 0 || heightSize <= 0) {
768 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
769 return;
770 }
771
Adam Lesinski6b879f02010-11-04 16:15:23 -0700772 /* Allow the height to be set as WRAP_CONTENT. This allows the particular case
773 * of the All apps view on XLarge displays to not take up more space then it needs. Width
774 * is still not allowed to be set as WRAP_CONTENT since many parts of the code expect
775 * each page to have the same width.
776 */
Michael Jurka8b805b12012-04-18 14:23:14 -0700777 final int verticalPadding = getPaddingTop() + getPaddingBottom();
778 final int horizontalPadding = getPaddingLeft() + getPaddingRight();
Winson Chung321e9ee2010-08-09 13:37:56 -0700779
780 // The children are given the same width and height as the workspace
Michael Jurka5f1c5092010-09-03 14:15:02 -0700781 // unless they were set to WRAP_CONTENT
Winson Chung785d2eb2011-04-14 16:08:02 -0700782 if (DEBUG) Log.d(TAG, "PagedView.onMeasure(): " + widthSize + ", " + heightSize);
Adam Cohen7d30a372013-07-01 17:03:59 -0700783 if (DEBUG) Log.d(TAG, "PagedView.scaledSize: " + scaledWidthSize + ", " + scaledHeightSize);
784 if (DEBUG) Log.d(TAG, "PagedView.parentSize: " + parentWidthSize + ", " + parentHeightSize);
785 if (DEBUG) Log.d(TAG, "PagedView.horizontalPadding: " + horizontalPadding);
786 if (DEBUG) Log.d(TAG, "PagedView.verticalPadding: " + verticalPadding);
Winson Chung321e9ee2010-08-09 13:37:56 -0700787 final int childCount = getChildCount();
788 for (int i = 0; i < childCount; i++) {
Michael Jurka5f1c5092010-09-03 14:15:02 -0700789 // disallowing padding in paged view (just pass 0)
Adam Cohen22f823d2011-09-01 17:22:18 -0700790 final View child = getPageAt(i);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700791 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
792
793 int childWidthMode;
Adam Cohen96d30a12013-07-16 18:13:21 -0700794 int childHeightMode;
795 int childWidth;
796 int childHeight;
797
798 if (!lp.isFullScreenPage) {
799 if (lp.width == LayoutParams.WRAP_CONTENT) {
800 childWidthMode = MeasureSpec.AT_MOST;
801 } else {
802 childWidthMode = MeasureSpec.EXACTLY;
803 }
804
805 if (lp.height == LayoutParams.WRAP_CONTENT) {
806 childHeightMode = MeasureSpec.AT_MOST;
807 } else {
808 childHeightMode = MeasureSpec.EXACTLY;
809 }
810
811 childWidth = widthSize - horizontalPadding;
John Spurlock77e1f472013-09-11 10:09:51 -0400812 childHeight = heightSize - verticalPadding - mInsets.top - mInsets.bottom;
Adam Cohen410f3cd2013-09-22 12:09:32 -0700813 mNormalChildHeight = childHeight;
Adam Cohen96d30a12013-07-16 18:13:21 -0700814
Michael Jurka5f1c5092010-09-03 14:15:02 -0700815 } else {
816 childWidthMode = MeasureSpec.EXACTLY;
Michael Jurka5f1c5092010-09-03 14:15:02 -0700817 childHeightMode = MeasureSpec.EXACTLY;
Adam Cohen96d30a12013-07-16 18:13:21 -0700818
Winson Chungc58497e2013-09-03 17:48:37 -0700819 if (mUseMinScale) {
820 childWidth = getViewportWidth();
821 childHeight = getViewportHeight();
822 } else {
823 childWidth = widthSize - getPaddingLeft() - getPaddingRight();
824 childHeight = heightSize - getPaddingTop() - getPaddingBottom();
825 }
Michael Jurka5f1c5092010-09-03 14:15:02 -0700826 }
827
828 final int childWidthMeasureSpec =
Adam Cohen96d30a12013-07-16 18:13:21 -0700829 MeasureSpec.makeMeasureSpec(childWidth, childWidthMode);
830 final int childHeightMeasureSpec =
831 MeasureSpec.makeMeasureSpec(childHeight, childHeightMode);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700832 child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700833 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700834 setMeasuredDimension(scaledWidthSize, scaledHeightSize);
Winson Chungae890b82011-09-13 18:08:54 -0700835
Winson Chunga128a7b2012-04-30 15:23:15 -0700836 if (childCount > 0) {
Winson Chunga128a7b2012-04-30 15:23:15 -0700837 // Calculate the variable page spacing if necessary
Adam Cohen7d30a372013-07-01 17:03:59 -0700838 if (mAutoComputePageSpacing && mRecomputePageSpacing) {
Winson Chunga128a7b2012-04-30 15:23:15 -0700839 // The gap between pages in the PagedView should be equal to the gap from the page
840 // to the edge of the screen (so it is not visible in the current screen). To
841 // account for unequal padding on each side of the paged view, we take the maximum
842 // of the left/right gap and use that as the gap between each page.
Adam Cohenedb40762013-07-18 16:45:45 -0700843 int offset = (getViewportWidth() - getChildWidth(0)) / 2;
Winson Chunga128a7b2012-04-30 15:23:15 -0700844 int spacing = Math.max(offset, widthSize - offset -
845 getChildAt(0).getMeasuredWidth());
846 setPageSpacing(spacing);
Adam Cohen7d30a372013-07-01 17:03:59 -0700847 mRecomputePageSpacing = false;
Winson Chunga128a7b2012-04-30 15:23:15 -0700848 }
849 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700850 }
851
Adam Cohen60b07122011-11-14 17:26:06 -0800852 public void setPageSpacing(int pageSpacing) {
853 mPageSpacing = pageSpacing;
Adam Cohenedb40762013-07-18 16:45:45 -0700854 requestLayout();
Adam Cohen60b07122011-11-14 17:26:06 -0800855 }
856
Winson Chung321e9ee2010-08-09 13:37:56 -0700857 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -0700858 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700859 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700860 return;
861 }
862
Winson Chung785d2eb2011-04-14 16:08:02 -0700863 if (DEBUG) Log.d(TAG, "PagedView.onLayout()");
Winson Chung321e9ee2010-08-09 13:37:56 -0700864 final int childCount = getChildCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700865
Adam Cohenedb40762013-07-18 16:45:45 -0700866 int screenWidth = getViewportWidth();
867
Adam Cohen7d30a372013-07-01 17:03:59 -0700868 int offsetX = getViewportOffsetX();
869 int offsetY = getViewportOffsetY();
870
871 // Update the viewport offsets
872 mViewport.offset(offsetX, offsetY);
873
Adam Cohen0ffac432013-07-10 11:19:26 -0700874 final boolean isRtl = isLayoutRtl();
875
876 final int startIndex = isRtl ? childCount - 1 : 0;
877 final int endIndex = isRtl ? -1 : childCount;
878 final int delta = isRtl ? -1 : 1;
879
Adam Cohen7d30a372013-07-01 17:03:59 -0700880 int verticalPadding = getPaddingTop() + getPaddingBottom();
Adam Cohenedb40762013-07-18 16:45:45 -0700881 int childLeft = offsetX + (screenWidth - getChildWidth(startIndex)) / 2;
882
883 if (mPageScrolls == null || getChildCount() != mChildCountOnLastLayout) {
884 mPageScrolls = new int[getChildCount()];
885 }
886
Adam Cohen0ffac432013-07-10 11:19:26 -0700887 for (int i = startIndex; i != endIndex; i += delta) {
Adam Cohen22f823d2011-09-01 17:22:18 -0700888 final View child = getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -0700889 LayoutParams lp = (LayoutParams) child.getLayoutParams();
890 int childTop;
Adam Cohen96d30a12013-07-16 18:13:21 -0700891 if (lp.isFullScreenPage) {
892 childTop = offsetY;
893 } else {
John Spurlock77e1f472013-09-11 10:09:51 -0400894 childTop = offsetY + getPaddingTop() + mInsets.top;
Adam Cohen96d30a12013-07-16 18:13:21 -0700895 if (mCenterPagesVertically) {
John Spurlock77e1f472013-09-11 10:09:51 -0400896 childTop += (getViewportHeight() - mInsets.top - mInsets.bottom - verticalPadding - child.getMeasuredHeight()) / 2;
Adam Cohen96d30a12013-07-16 18:13:21 -0700897 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700898 }
Adam Cohen96d30a12013-07-16 18:13:21 -0700899
Winson Chung321e9ee2010-08-09 13:37:56 -0700900 if (child.getVisibility() != View.GONE) {
Adam Cohen96d30a12013-07-16 18:13:21 -0700901 final int childWidth = child.getMeasuredWidth();
Adam Lesinski6b879f02010-11-04 16:15:23 -0700902 final int childHeight = child.getMeasuredHeight();
Michael Jurkad3ef3062010-11-23 16:23:58 -0800903
Winson Chung785d2eb2011-04-14 16:08:02 -0700904 if (DEBUG) Log.d(TAG, "\tlayout-child" + i + ": " + childLeft + ", " + childTop);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700905 child.layout(childLeft, childTop,
Michael Jurkad3ef3062010-11-23 16:23:58 -0800906 childLeft + child.getMeasuredWidth(), childTop + childHeight);
Adam Cohenedb40762013-07-18 16:45:45 -0700907
908 // We assume the left and right padding are equal, and hence center the pages
909 // horizontally
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700910 int scrollOffset = (getViewportWidth() - childWidth) / 2;
Adam Cohenedb40762013-07-18 16:45:45 -0700911 mPageScrolls[i] = childLeft - scrollOffset - offsetX;
912
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700913 if (i != endIndex - delta) {
914 int nextScrollOffset = (getViewportWidth() - getChildWidth(i + delta)) / 2;
915 childLeft += childWidth + nextScrollOffset;
916 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700917 }
918 }
Winson Chungc3665fa2011-09-14 17:56:27 -0700919
920 if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) {
921 setHorizontalScrollBarEnabled(false);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800922 updateCurrentPageScroll();
Winson Chungc3665fa2011-09-14 17:56:27 -0700923 setHorizontalScrollBarEnabled(true);
924 mFirstLayout = false;
925 }
Adam Cohenf698c6e2013-07-17 18:44:25 -0700926
927 if (childCount > 0) {
928 final int index = isLayoutRtl() ? 0 : childCount - 1;
Adam Cohenedb40762013-07-18 16:45:45 -0700929 mMaxScrollX = getScrollForPage(index);
Adam Cohenf698c6e2013-07-17 18:44:25 -0700930 } else {
931 mMaxScrollX = 0;
932 }
933
934 if (mScroller.isFinished() && mChildCountOnLastLayout != getChildCount() &&
935 !mDeferringForDelete) {
Winson Chung8c87cd82013-07-23 16:20:10 -0700936 if (mRestorePage > -1) {
937 setCurrentPage(mRestorePage);
938 mRestorePage = -1;
939 } else {
940 setCurrentPage(getNextPage());
941 }
Adam Cohenf698c6e2013-07-17 18:44:25 -0700942 }
943 mChildCountOnLastLayout = getChildCount();
Adam Cohenf358a4b2013-07-23 16:47:31 -0700944
945 if (isReordering(true)) {
946 updateDragViewTranslationDuringDrag();
947 }
Winson Chunge3193b92010-09-10 11:44:42 -0700948 }
949
Adam Cohenf34bab52010-09-30 14:11:56 -0700950 protected void screenScrolled(int screenCenter) {
Michael Jurka869390b2012-05-06 15:55:19 -0700951 boolean isInOverscroll = mOverScrollX < 0 || mOverScrollX > mMaxScrollX;
952
953 if (mFadeInAdjacentScreens && !isInOverscroll) {
Adam Cohen73894962011-10-31 13:17:17 -0700954 for (int i = 0; i < getChildCount(); i++) {
955 View child = getChildAt(i);
956 if (child != null) {
957 float scrollProgress = getScrollProgress(screenCenter, child, i);
958 float alpha = 1 - Math.abs(scrollProgress);
Michael Jurka7372c592012-01-16 04:21:35 -0800959 child.setAlpha(alpha);
Adam Cohen73894962011-10-31 13:17:17 -0700960 }
961 }
962 invalidate();
963 }
Adam Cohenf34bab52010-09-30 14:11:56 -0700964 }
965
Winson Chungc58497e2013-09-03 17:48:37 -0700966 protected void enablePagedViewAnimations() {
967 mAllowPagedViewAnimations = true;
968
969 }
970 protected void disablePagedViewAnimations() {
971 mAllowPagedViewAnimations = false;
972 }
973
Winson Chunge3193b92010-09-10 11:44:42 -0700974 @Override
Michael Jurka8b805b12012-04-18 14:23:14 -0700975 public void onChildViewAdded(View parent, View child) {
Winson Chungd2be3812013-07-16 11:11:32 -0700976 // Update the page indicator, we don't update the page indicator as we
977 // add/remove pages
978 if (mPageIndicator != null && !isReordering(false)) {
Winson Chung82dfe582013-07-26 15:07:49 -0700979 int pageIndex = indexOfChild(child);
Winson Chung7819a562013-09-19 15:55:45 -0700980 mPageIndicator.addMarker(pageIndex,
981 getPageIndicatorMarker(pageIndex),
Winson Chungc58497e2013-09-03 17:48:37 -0700982 mAllowPagedViewAnimations);
Winson Chungd2be3812013-07-16 11:11:32 -0700983 }
984
Adam Cohen2591f6a2011-10-25 14:36:40 -0700985 // This ensures that when children are added, they get the correct transforms / alphas
986 // in accordance with any scroll effects.
987 mForceScreenScrolled = true;
Adam Cohen7d30a372013-07-01 17:03:59 -0700988 mRecomputePageSpacing = true;
Adam Cohen96d30a12013-07-16 18:13:21 -0700989
Adam Cohen2591f6a2011-10-25 14:36:40 -0700990 invalidate();
991 }
992
Michael Jurka8b805b12012-04-18 14:23:14 -0700993 @Override
994 public void onChildViewRemoved(View parent, View child) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700995 mForceScreenScrolled = true;
996 invalidate();
Michael Jurka8b805b12012-04-18 14:23:14 -0700997 }
998
Winson Chungd2be3812013-07-16 11:11:32 -0700999 private void removeMarkerForView(int index) {
1000 // Update the page indicator, we don't update the page indicator as we
1001 // add/remove pages
1002 if (mPageIndicator != null && !isReordering(false)) {
Winson Chungc58497e2013-09-03 17:48:37 -07001003 mPageIndicator.removeMarker(index, mAllowPagedViewAnimations);
Winson Chungd2be3812013-07-16 11:11:32 -07001004 }
1005 }
1006
1007 @Override
1008 public void removeView(View v) {
1009 // XXX: We should find a better way to hook into this before the view
1010 // gets removed form its parent...
1011 removeMarkerForView(indexOfChild(v));
1012 super.removeView(v);
1013 }
1014 @Override
1015 public void removeViewInLayout(View v) {
1016 // XXX: We should find a better way to hook into this before the view
1017 // gets removed form its parent...
1018 removeMarkerForView(indexOfChild(v));
1019 super.removeViewInLayout(v);
1020 }
1021 @Override
1022 public void removeViewAt(int index) {
1023 // XXX: We should find a better way to hook into this before the view
1024 // gets removed form its parent...
1025 removeViewAt(index);
1026 super.removeViewAt(index);
1027 }
1028 @Override
1029 public void removeAllViewsInLayout() {
1030 // Update the page indicator, we don't update the page indicator as we
1031 // add/remove pages
1032 if (mPageIndicator != null) {
Winson Chungc58497e2013-09-03 17:48:37 -07001033 mPageIndicator.removeAllMarkers(mAllowPagedViewAnimations);
Winson Chungd2be3812013-07-16 11:11:32 -07001034 }
1035
1036 super.removeAllViewsInLayout();
1037 }
1038
Adam Cohen73894962011-10-31 13:17:17 -07001039 protected int getChildOffset(int index) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001040 if (index < 0 || index > getChildCount() - 1) return 0;
1041
Adam Cohen0ffac432013-07-10 11:19:26 -07001042 final boolean isRtl = isLayoutRtl();
Adam Cohen73894962011-10-31 13:17:17 -07001043
Adam Cohenf698c6e2013-07-17 18:44:25 -07001044 if (isRtl) index = getChildCount() - index - 1;
1045 int offset = getPageAt(index).getLeft() - getViewportOffsetX();
Adam Cohen73894962011-10-31 13:17:17 -07001046
Adam Cohenf698c6e2013-07-17 18:44:25 -07001047 return offset;
Adam Cohen73894962011-10-31 13:17:17 -07001048 }
1049
Adam Cohenf358a4b2013-07-23 16:47:31 -07001050 protected void getOverviewModePages(int[] range) {
Winson Chungc9ca2982013-07-19 12:07:38 -07001051 range[0] = 0;
1052 range[1] = getChildCount() - 1;
Adam Cohen7d30a372013-07-01 17:03:59 -07001053 }
1054
Michael Jurkadde558b2011-11-09 22:09:06 -08001055 protected void getVisiblePages(int[] range) {
Michael Jurka0142d492010-08-25 17:46:15 -07001056 final int pageCount = getChildCount();
Winson Chungc9ca2982013-07-19 12:07:38 -07001057 mTmpIntPoint[0] = mTmpIntPoint[1] = 0;
Michael Jurka4ff7d792012-04-02 03:46:50 -07001058
Michael Jurkac4fb9172010-09-02 17:19:20 -07001059 if (pageCount > 0) {
Winson Chungc9ca2982013-07-19 12:07:38 -07001060 int viewportWidth = getViewportWidth();
Adam Cohen7d30a372013-07-01 17:03:59 -07001061 int leftScreen = 0;
Michael Jurkac4fb9172010-09-02 17:19:20 -07001062 int rightScreen = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -07001063
Winson Chungc9ca2982013-07-19 12:07:38 -07001064 for (leftScreen = getNextPage(); leftScreen >= 0; --leftScreen) {
1065 View currPage = getPageAt(leftScreen);
1066
1067 // Check if the right edge of the page is in the viewport
1068 mTmpIntPoint[0] = currPage.getMeasuredWidth();
Winson Chungc763c4e2013-07-19 13:49:06 -07001069 Utilities.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false);
Winson Chungc9ca2982013-07-19 12:07:38 -07001070 if (mTmpIntPoint[0] < 0) {
1071 break;
1072 }
1073 }
1074 for (rightScreen = getNextPage(); rightScreen < getChildCount(); ++rightScreen) {
1075 View currPage = getPageAt(rightScreen);
1076
1077 // Check if the left edge of the page is in the viewport
1078 mTmpIntPoint[0] = 0;
Winson Chungc763c4e2013-07-19 13:49:06 -07001079 Utilities.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false);
Winson Chungc9ca2982013-07-19 12:07:38 -07001080 if (mTmpIntPoint[0] >= viewportWidth) {
1081 break;
1082 }
1083 }
1084 range[0] = Math.max(0, leftScreen);
1085 range[1] = Math.min(rightScreen, getChildCount() - 1);
Michael Jurkadde558b2011-11-09 22:09:06 -08001086 } else {
1087 range[0] = -1;
1088 range[1] = -1;
1089 }
1090 }
1091
Michael Jurka920d7f42012-05-14 16:29:55 -07001092 protected boolean shouldDrawChild(View child) {
Adam Cohenf3434992013-09-16 16:52:59 -07001093 return child.getAlpha() > 0 && child.getVisibility() == VISIBLE;
Michael Jurka920d7f42012-05-14 16:29:55 -07001094 }
1095
Michael Jurkadde558b2011-11-09 22:09:06 -08001096 @Override
1097 protected void dispatchDraw(Canvas canvas) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001098 int halfScreenSize = getViewportWidth() / 2;
Michael Jurka8b805b12012-04-18 14:23:14 -07001099 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range.
1100 // Otherwise it is equal to the scaled overscroll position.
Adam Cohenebea84d2011-11-09 17:20:41 -08001101 int screenCenter = mOverScrollX + halfScreenSize;
Michael Jurkadde558b2011-11-09 22:09:06 -08001102
1103 if (screenCenter != mLastScreenCenter || mForceScreenScrolled) {
Michael Jurkab06d95f2012-04-02 06:26:53 -07001104 // set mForceScreenScrolled before calling screenScrolled so that screenScrolled can
1105 // set it for the next frame
1106 mForceScreenScrolled = false;
Michael Jurkadde558b2011-11-09 22:09:06 -08001107 screenScrolled(screenCenter);
1108 mLastScreenCenter = screenCenter;
Michael Jurkadde558b2011-11-09 22:09:06 -08001109 }
1110
1111 // Find out which screens are visible; as an optimization we only call draw on them
1112 final int pageCount = getChildCount();
1113 if (pageCount > 0) {
1114 getVisiblePages(mTempVisiblePagesRange);
1115 final int leftScreen = mTempVisiblePagesRange[0];
1116 final int rightScreen = mTempVisiblePagesRange[1];
Winson Chungc6f10b92011-11-14 11:39:07 -08001117 if (leftScreen != -1 && rightScreen != -1) {
1118 final long drawingTime = getDrawingTime();
1119 // Clip to the bounds
1120 canvas.save();
Michael Jurka8b805b12012-04-18 14:23:14 -07001121 canvas.clipRect(getScrollX(), getScrollY(), getScrollX() + getRight() - getLeft(),
1122 getScrollY() + getBottom() - getTop());
Michael Jurka0142d492010-08-25 17:46:15 -07001123
Adam Cohen7d30a372013-07-01 17:03:59 -07001124 // Draw all the children, leaving the drag view for last
1125 for (int i = pageCount - 1; i >= 0; i--) {
Michael Jurka80c69852011-12-16 14:16:32 -08001126 final View v = getPageAt(i);
Adam Cohen7d30a372013-07-01 17:03:59 -07001127 if (v == mDragView) continue;
Michael Jurka5e368ff2012-05-14 23:13:15 -07001128 if (mForceDrawAllChildrenNextFrame ||
1129 (leftScreen <= i && i <= rightScreen && shouldDrawChild(v))) {
Michael Jurka80c69852011-12-16 14:16:32 -08001130 drawChild(canvas, v, drawingTime);
Michael Jurka80c69852011-12-16 14:16:32 -08001131 }
Winson Chungc6f10b92011-11-14 11:39:07 -08001132 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001133 // Draw the drag view on top (if there is one)
1134 if (mDragView != null) {
1135 drawChild(canvas, mDragView, drawingTime);
1136 }
1137
Michael Jurka5e368ff2012-05-14 23:13:15 -07001138 mForceDrawAllChildrenNextFrame = false;
Winson Chungc6f10b92011-11-14 11:39:07 -08001139 canvas.restore();
Michael Jurkac4fb9172010-09-02 17:19:20 -07001140 }
Michael Jurka0142d492010-08-25 17:46:15 -07001141 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001142 }
1143
1144 @Override
1145 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
Adam Cohenae4f1552011-10-20 00:15:42 -07001146 int page = indexToPage(indexOfChild(child));
Winson Chung86f77532010-08-24 11:08:22 -07001147 if (page != mCurrentPage || !mScroller.isFinished()) {
1148 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001149 return true;
1150 }
1151 return false;
1152 }
1153
1154 @Override
1155 protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
Winson Chung86f77532010-08-24 11:08:22 -07001156 int focusablePage;
1157 if (mNextPage != INVALID_PAGE) {
1158 focusablePage = mNextPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001159 } else {
Winson Chung86f77532010-08-24 11:08:22 -07001160 focusablePage = mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001161 }
Winson Chung86f77532010-08-24 11:08:22 -07001162 View v = getPageAt(focusablePage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001163 if (v != null) {
Adam Cohen76fc0852011-06-17 13:26:23 -07001164 return v.requestFocus(direction, previouslyFocusedRect);
Winson Chung321e9ee2010-08-09 13:37:56 -07001165 }
1166 return false;
1167 }
1168
1169 @Override
1170 public boolean dispatchUnhandledMove(View focused, int direction) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001171 // XXX-RTL: This will be fixed in a future CL
Winson Chung321e9ee2010-08-09 13:37:56 -07001172 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001173 if (getCurrentPage() > 0) {
1174 snapToPage(getCurrentPage() - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001175 return true;
1176 }
1177 } else if (direction == View.FOCUS_RIGHT) {
Winson Chung86f77532010-08-24 11:08:22 -07001178 if (getCurrentPage() < getPageCount() - 1) {
1179 snapToPage(getCurrentPage() + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001180 return true;
1181 }
1182 }
1183 return super.dispatchUnhandledMove(focused, direction);
1184 }
1185
1186 @Override
1187 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001188 // XXX-RTL: This will be fixed in a future CL
Winson Chung86f77532010-08-24 11:08:22 -07001189 if (mCurrentPage >= 0 && mCurrentPage < getPageCount()) {
alanvaf519952012-05-07 17:33:22 -07001190 getPageAt(mCurrentPage).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001191 }
1192 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001193 if (mCurrentPage > 0) {
alanvaf519952012-05-07 17:33:22 -07001194 getPageAt(mCurrentPage - 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001195 }
1196 } else if (direction == View.FOCUS_RIGHT){
Winson Chung86f77532010-08-24 11:08:22 -07001197 if (mCurrentPage < getPageCount() - 1) {
alanvaf519952012-05-07 17:33:22 -07001198 getPageAt(mCurrentPage + 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001199 }
1200 }
1201 }
1202
1203 /**
1204 * If one of our descendant views decides that it could be focused now, only
Winson Chung86f77532010-08-24 11:08:22 -07001205 * pass that along if it's on the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001206 *
Winson Chung86f77532010-08-24 11:08:22 -07001207 * This happens when live folders requery, and if they're off page, they
1208 * end up calling requestFocus, which pulls it on page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001209 */
1210 @Override
1211 public void focusableViewAvailable(View focused) {
Winson Chung86f77532010-08-24 11:08:22 -07001212 View current = getPageAt(mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001213 View v = focused;
1214 while (true) {
1215 if (v == current) {
1216 super.focusableViewAvailable(focused);
1217 return;
1218 }
1219 if (v == this) {
1220 return;
1221 }
1222 ViewParent parent = v.getParent();
1223 if (parent instanceof View) {
1224 v = (View)v.getParent();
1225 } else {
1226 return;
1227 }
1228 }
1229 }
1230
1231 /**
1232 * {@inheritDoc}
1233 */
1234 @Override
1235 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
1236 if (disallowIntercept) {
1237 // We need to make sure to cancel our long press if
1238 // a scrollable widget takes over touch events
Adam Cohen22f823d2011-09-01 17:22:18 -07001239 final View currentPage = getPageAt(mCurrentPage);
Winson Chung86f77532010-08-24 11:08:22 -07001240 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001241 }
1242 super.requestDisallowInterceptTouchEvent(disallowIntercept);
1243 }
1244
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001245 /**
1246 * Return true if a tap at (x, y) should trigger a flip to the previous page.
1247 */
1248 protected boolean hitsPreviousPage(float x, float y) {
Adam Cohenedb40762013-07-18 16:45:45 -07001249 int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2;
Adam Cohen0ffac432013-07-10 11:19:26 -07001250 if (isLayoutRtl()) {
1251 return (x > (getViewportOffsetX() + getViewportWidth() -
Adam Cohenedb40762013-07-18 16:45:45 -07001252 offset + mPageSpacing));
Adam Cohen0ffac432013-07-10 11:19:26 -07001253 }
Adam Cohenedb40762013-07-18 16:45:45 -07001254 return (x < getViewportOffsetX() + offset - mPageSpacing);
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001255 }
1256
1257 /**
1258 * Return true if a tap at (x, y) should trigger a flip to the next page.
1259 */
1260 protected boolean hitsNextPage(float x, float y) {
Adam Cohenedb40762013-07-18 16:45:45 -07001261 int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2;
Adam Cohen0ffac432013-07-10 11:19:26 -07001262 if (isLayoutRtl()) {
Adam Cohenedb40762013-07-18 16:45:45 -07001263 return (x < getViewportOffsetX() + offset - mPageSpacing);
Adam Cohen0ffac432013-07-10 11:19:26 -07001264 }
1265 return (x > (getViewportOffsetX() + getViewportWidth() -
Adam Cohenedb40762013-07-18 16:45:45 -07001266 offset + mPageSpacing));
Adam Cohen7d30a372013-07-01 17:03:59 -07001267 }
Winson Chung52aee602013-01-30 12:01:02 -08001268
Adam Cohen7d30a372013-07-01 17:03:59 -07001269 /** Returns whether x and y originated within the buffered viewport */
1270 private boolean isTouchPointInViewportWithBuffer(int x, int y) {
1271 mTmpRect.set(mViewport.left - mViewport.width() / 2, mViewport.top,
1272 mViewport.right + mViewport.width() / 2, mViewport.bottom);
1273 return mTmpRect.contains(x, y);
1274 }
1275
Winson Chung321e9ee2010-08-09 13:37:56 -07001276 @Override
1277 public boolean onInterceptTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001278 if (DISABLE_TOUCH_INTERACTION) {
1279 return false;
1280 }
1281
Winson Chung321e9ee2010-08-09 13:37:56 -07001282 /*
1283 * This method JUST determines whether we want to intercept the motion.
1284 * If we return true, onTouchEvent will be called and we do the actual
1285 * scrolling there.
1286 */
Adam Cohen6342bba2011-03-10 11:33:35 -08001287 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001288
Winson Chung45e1d6e2010-11-09 17:19:49 -08001289 // Skip touch handling if there are no pages to swipe
1290 if (getChildCount() <= 0) return super.onInterceptTouchEvent(ev);
1291
Winson Chung321e9ee2010-08-09 13:37:56 -07001292 /*
1293 * Shortcut the most recurring case: the user is in the dragging
1294 * state and he is moving his finger. We want to intercept this
1295 * motion.
1296 */
1297 final int action = ev.getAction();
1298 if ((action == MotionEvent.ACTION_MOVE) &&
1299 (mTouchState == TOUCH_STATE_SCROLLING)) {
1300 return true;
1301 }
1302
Winson Chung321e9ee2010-08-09 13:37:56 -07001303 switch (action & MotionEvent.ACTION_MASK) {
1304 case MotionEvent.ACTION_MOVE: {
1305 /*
1306 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
1307 * whether the user has moved far enough from his original down touch.
1308 */
Michael Jurka1ff706b2010-09-14 17:35:20 -07001309 if (mActivePointerId != INVALID_POINTER) {
1310 determineScrollingStart(ev);
1311 break;
1312 }
1313 // if mActivePointerId is INVALID_POINTER, then we must have missed an ACTION_DOWN
1314 // event. in that case, treat the first occurence of a move event as a ACTION_DOWN
1315 // i.e. fall through to the next case (don't break)
1316 // (We sometimes miss ACTION_DOWN events in Workspace because it ignores all events
1317 // while it's small- this was causing a crash before we checked for INVALID_POINTER)
Winson Chung321e9ee2010-08-09 13:37:56 -07001318 }
1319
1320 case MotionEvent.ACTION_DOWN: {
1321 final float x = ev.getX();
1322 final float y = ev.getY();
1323 // Remember location of down touch
1324 mDownMotionX = x;
Adam Cohen7d30a372013-07-01 17:03:59 -07001325 mDownMotionY = y;
1326 mDownScrollX = getScrollX();
Winson Chung321e9ee2010-08-09 13:37:56 -07001327 mLastMotionX = x;
1328 mLastMotionY = y;
Adam Cohen7d30a372013-07-01 17:03:59 -07001329 float[] p = mapPointFromViewToParent(this, x, y);
1330 mParentDownMotionX = p[0];
1331 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001332 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001333 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001334 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001335
Winson Chung321e9ee2010-08-09 13:37:56 -07001336 /*
1337 * If being flinged and user touches the screen, initiate drag;
1338 * otherwise don't. mScroller.isFinished should be false when
1339 * being flinged.
1340 */
Michael Jurkafd177c12010-10-19 15:50:43 -07001341 final int xDist = Math.abs(mScroller.getFinalX() - mScroller.getCurrX());
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001342 final boolean finishedScrolling = (mScroller.isFinished() || xDist < mTouchSlop);
1343 if (finishedScrolling) {
1344 mTouchState = TOUCH_STATE_REST;
1345 mScroller.abortAnimation();
1346 } else {
Adam Cohen7d30a372013-07-01 17:03:59 -07001347 if (isTouchPointInViewportWithBuffer((int) mDownMotionX, (int) mDownMotionY)) {
1348 mTouchState = TOUCH_STATE_SCROLLING;
1349 } else {
1350 mTouchState = TOUCH_STATE_REST;
1351 }
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001352 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001353
Winson Chung86f77532010-08-24 11:08:22 -07001354 // check if this can be the beginning of a tap on the side of the pages
Winson Chung321e9ee2010-08-09 13:37:56 -07001355 // to scroll the current page
Adam Cohen7d30a372013-07-01 17:03:59 -07001356 if (!DISABLE_TOUCH_SIDE_PAGES) {
1357 if (mTouchState != TOUCH_STATE_PREV_PAGE && mTouchState != TOUCH_STATE_NEXT_PAGE) {
1358 if (getChildCount() > 0) {
1359 if (hitsPreviousPage(x, y)) {
1360 mTouchState = TOUCH_STATE_PREV_PAGE;
1361 } else if (hitsNextPage(x, y)) {
1362 mTouchState = TOUCH_STATE_NEXT_PAGE;
1363 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001364 }
1365 }
1366 }
1367 break;
1368 }
1369
Winson Chung321e9ee2010-08-09 13:37:56 -07001370 case MotionEvent.ACTION_UP:
Jeff Brown1d0867c2010-12-02 18:27:39 -08001371 case MotionEvent.ACTION_CANCEL:
Adam Cohen7d30a372013-07-01 17:03:59 -07001372 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001373 break;
1374
1375 case MotionEvent.ACTION_POINTER_UP:
1376 onSecondaryPointerUp(ev);
Adam Cohen6342bba2011-03-10 11:33:35 -08001377 releaseVelocityTracker();
Winson Chung321e9ee2010-08-09 13:37:56 -07001378 break;
1379 }
1380
1381 /*
1382 * The only time we want to intercept motion events is if we are in the
1383 * drag mode.
1384 */
1385 return mTouchState != TOUCH_STATE_REST;
1386 }
1387
Adam Cohenf8d28232011-02-01 21:47:00 -08001388 protected void determineScrollingStart(MotionEvent ev) {
1389 determineScrollingStart(ev, 1.0f);
1390 }
1391
Winson Chung321e9ee2010-08-09 13:37:56 -07001392 /*
1393 * Determines if we should change the touch state to start scrolling after the
1394 * user moves their touch point too far.
1395 */
Adam Cohenf8d28232011-02-01 21:47:00 -08001396 protected void determineScrollingStart(MotionEvent ev, float touchSlopScale) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001397 // Disallow scrolling if we don't have a valid pointer index
Winson Chung321e9ee2010-08-09 13:37:56 -07001398 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001399 if (pointerIndex == -1) return;
1400
1401 // Disallow scrolling if we started the gesture from outside the viewport
Winson Chung321e9ee2010-08-09 13:37:56 -07001402 final float x = ev.getX(pointerIndex);
1403 final float y = ev.getY(pointerIndex);
Adam Cohen7d30a372013-07-01 17:03:59 -07001404 if (!isTouchPointInViewportWithBuffer((int) x, (int) y)) return;
1405
Winson Chung321e9ee2010-08-09 13:37:56 -07001406 final int xDiff = (int) Math.abs(x - mLastMotionX);
1407 final int yDiff = (int) Math.abs(y - mLastMotionY);
1408
Adam Cohenf8d28232011-02-01 21:47:00 -08001409 final int touchSlop = Math.round(touchSlopScale * mTouchSlop);
Winson Chung321e9ee2010-08-09 13:37:56 -07001410 boolean xPaged = xDiff > mPagingTouchSlop;
1411 boolean xMoved = xDiff > touchSlop;
1412 boolean yMoved = yDiff > touchSlop;
1413
Adam Cohenf8d28232011-02-01 21:47:00 -08001414 if (xMoved || xPaged || yMoved) {
Michael Jurka0142d492010-08-25 17:46:15 -07001415 if (mUsePagingTouchSlop ? xPaged : xMoved) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001416 // Scroll if the user moved far enough along the X axis
1417 mTouchState = TOUCH_STATE_SCROLLING;
Adam Cohen6342bba2011-03-10 11:33:35 -08001418 mTotalMotionX += Math.abs(mLastMotionX - x);
Winson Chung321e9ee2010-08-09 13:37:56 -07001419 mLastMotionX = x;
Winson Chungc0844aa2011-02-02 15:25:58 -08001420 mLastMotionXRemainder = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -07001421 mTouchX = getViewportOffsetX() + getScrollX();
Michael Jurka0142d492010-08-25 17:46:15 -07001422 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1423 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07001424 }
Adam Cohenf8d28232011-02-01 21:47:00 -08001425 }
1426 }
1427
Adam Cohen7d30a372013-07-01 17:03:59 -07001428 protected float getMaxScrollProgress() {
1429 return 1.0f;
1430 }
1431
Adam Cohenf8d28232011-02-01 21:47:00 -08001432 protected void cancelCurrentPageLongPress() {
1433 if (mAllowLongPress) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001434 //mAllowLongPress = false;
Adam Cohenf8d28232011-02-01 21:47:00 -08001435 // Try canceling the long press. It could also have been scheduled
1436 // by a distant descendant, so use the mAllowLongPress flag to block
1437 // everything
1438 final View currentPage = getPageAt(mCurrentPage);
1439 if (currentPage != null) {
1440 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001441 }
1442 }
1443 }
1444
Adam Cohen7d30a372013-07-01 17:03:59 -07001445 protected float getBoundedScrollProgress(int screenCenter, View v, int page) {
1446 final int halfScreenSize = getViewportWidth() / 2;
1447
1448 screenCenter = Math.min(getScrollX() + halfScreenSize, screenCenter);
1449 screenCenter = Math.max(halfScreenSize, screenCenter);
1450
1451 return getScrollProgress(screenCenter, v, page);
1452 }
1453
Adam Cohenb5ba0972011-09-07 18:02:31 -07001454 protected float getScrollProgress(int screenCenter, View v, int page) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001455 final int halfScreenSize = getViewportWidth() / 2;
Adam Cohenb5ba0972011-09-07 18:02:31 -07001456
Adam Cohen96d30a12013-07-16 18:13:21 -07001457 int totalDistance = v.getMeasuredWidth() + mPageSpacing;
Adam Cohenedb40762013-07-18 16:45:45 -07001458 int delta = screenCenter - (getScrollForPage(page) + halfScreenSize);
Adam Cohenb5ba0972011-09-07 18:02:31 -07001459
1460 float scrollProgress = delta / (totalDistance * 1.0f);
Adam Cohen7d30a372013-07-01 17:03:59 -07001461 scrollProgress = Math.min(scrollProgress, getMaxScrollProgress());
1462 scrollProgress = Math.max(scrollProgress, - getMaxScrollProgress());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001463 return scrollProgress;
1464 }
1465
Adam Cohenedb40762013-07-18 16:45:45 -07001466 public int getScrollForPage(int index) {
1467 if (mPageScrolls == null || index >= mPageScrolls.length) {
1468 return 0;
1469 } else {
1470 return mPageScrolls[index];
1471 }
1472 }
1473
Adam Cohene0f66b52010-11-23 15:06:07 -08001474 // This curve determines how the effect of scrolling over the limits of the page dimishes
1475 // as the user pulls further and further from the bounds
1476 private float overScrollInfluenceCurve(float f) {
1477 f -= 1.0f;
1478 return f * f * f + 1.0f;
1479 }
1480
Adam Cohenb5ba0972011-09-07 18:02:31 -07001481 protected void acceleratedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001482 int screenSize = getViewportWidth();
Adam Cohenb5ba0972011-09-07 18:02:31 -07001483
1484 // We want to reach the max over scroll effect when the user has
1485 // over scrolled half the size of the screen
1486 float f = OVERSCROLL_ACCELERATE_FACTOR * (amount / screenSize);
1487
1488 if (f == 0) return;
1489
1490 // Clamp this factor, f, to -1 < f < 1
1491 if (Math.abs(f) >= 1) {
1492 f /= Math.abs(f);
1493 }
1494
1495 int overScrollAmount = (int) Math.round(f * screenSize);
1496 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001497 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001498 super.scrollTo(0, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001499 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001500 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001501 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001502 }
1503 invalidate();
1504 }
1505
1506 protected void dampedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001507 int screenSize = getViewportWidth();
Adam Cohene0f66b52010-11-23 15:06:07 -08001508
1509 float f = (amount / screenSize);
1510
1511 if (f == 0) return;
1512 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1513
Adam Cohen7bfc9792011-01-28 13:52:37 -08001514 // Clamp this factor, f, to -1 < f < 1
1515 if (Math.abs(f) >= 1) {
1516 f /= Math.abs(f);
1517 }
1518
Adam Cohene0f66b52010-11-23 15:06:07 -08001519 int overScrollAmount = (int) Math.round(OVERSCROLL_DAMP_FACTOR * f * screenSize);
Adam Cohen68d73932010-11-15 10:50:58 -08001520 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001521 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001522 super.scrollTo(0, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001523 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001524 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001525 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001526 }
1527 invalidate();
1528 }
1529
Adam Cohenb5ba0972011-09-07 18:02:31 -07001530 protected void overScroll(float amount) {
1531 dampedOverScroll(amount);
1532 }
1533
Michael Jurkac5b262c2011-01-12 20:24:50 -08001534 protected float maxOverScroll() {
1535 // Using the formula in overScroll, assuming that f = 1.0 (which it should generally not
Adam Cohenb5ba0972011-09-07 18:02:31 -07001536 // exceed). Used to find out how much extra wallpaper we need for the over scroll effect
Michael Jurkac5b262c2011-01-12 20:24:50 -08001537 float f = 1.0f;
1538 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1539 return OVERSCROLL_DAMP_FACTOR * f;
1540 }
1541
Adam Cohenf358a4b2013-07-23 16:47:31 -07001542 protected void enableFreeScroll() {
1543 setEnableFreeScroll(true, -1);
1544 }
1545
1546 protected void disableFreeScroll(int snapPage) {
1547 setEnableFreeScroll(false, snapPage);
1548 }
1549
1550 private void setEnableFreeScroll(boolean freeScroll, int snapPage) {
1551 mFreeScroll = freeScroll;
1552
1553 if (snapPage == -1) {
1554 snapPage = getPageNearestToCenterOfScreen();
1555 }
1556
1557 getOverviewModePages(mTempVisiblePagesRange);
1558 if (!mFreeScroll) {
1559 snapToPage(snapPage);
Adam Cohenf358a4b2013-07-23 16:47:31 -07001560 } else {
1561 mFreeScrollMinScrollX = getScrollForPage(mTempVisiblePagesRange[0]);
1562 mFreeScrollMaxScrollX = getScrollForPage(mTempVisiblePagesRange[1]);
1563
Adam Cohenf358a4b2013-07-23 16:47:31 -07001564 if (getCurrentPage() < mTempVisiblePagesRange[0]) {
1565 setCurrentPage(mTempVisiblePagesRange[0]);
1566 } else if (getCurrentPage() > mTempVisiblePagesRange[1]) {
1567 setCurrentPage(mTempVisiblePagesRange[1]);
1568 }
1569 }
1570
1571 setEnableOverscroll(!freeScroll);
1572 }
1573
1574 private void setEnableOverscroll(boolean enable) {
1575 mAllowOverScroll = enable;
1576 }
1577
1578 int getNearestHoverOverPageIndex() {
1579 if (mDragView != null) {
1580 int dragX = (int) (mDragView.getLeft() + (mDragView.getMeasuredWidth() / 2)
1581 + mDragView.getTranslationX());
1582 getOverviewModePages(mTempVisiblePagesRange);
1583 int minDistance = Integer.MAX_VALUE;
1584 int minIndex = indexOfChild(mDragView);
1585 for (int i = mTempVisiblePagesRange[0]; i <= mTempVisiblePagesRange[1]; i++) {
1586 View page = getPageAt(i);
1587 int pageX = (int) (page.getLeft() + page.getMeasuredWidth() / 2);
1588 int d = Math.abs(dragX - pageX);
1589 if (d < minDistance) {
1590 minIndex = i;
1591 minDistance = d;
1592 }
1593 }
1594 return minIndex;
1595 }
1596 return -1;
1597 }
1598
Winson Chung321e9ee2010-08-09 13:37:56 -07001599 @Override
1600 public boolean onTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001601 if (DISABLE_TOUCH_INTERACTION) {
1602 return false;
1603 }
1604
Adam Cohen1697b792013-09-17 19:08:21 -07001605 super.onTouchEvent(ev);
1606
Winson Chung45e1d6e2010-11-09 17:19:49 -08001607 // Skip touch handling if there are no pages to swipe
1608 if (getChildCount() <= 0) return super.onTouchEvent(ev);
1609
Michael Jurkab8f06722010-10-10 15:58:46 -07001610 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001611
1612 final int action = ev.getAction();
1613
1614 switch (action & MotionEvent.ACTION_MASK) {
1615 case MotionEvent.ACTION_DOWN:
1616 /*
1617 * If being flinged and user touches, stop the fling. isFinished
1618 * will be false if being flinged.
1619 */
1620 if (!mScroller.isFinished()) {
1621 mScroller.abortAnimation();
1622 }
1623
1624 // Remember where the motion event started
1625 mDownMotionX = mLastMotionX = ev.getX();
Adam Cohen7d30a372013-07-01 17:03:59 -07001626 mDownMotionY = mLastMotionY = ev.getY();
1627 mDownScrollX = getScrollX();
1628 float[] p = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1629 mParentDownMotionX = p[0];
1630 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001631 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001632 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001633 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001634
Michael Jurka0142d492010-08-25 17:46:15 -07001635 if (mTouchState == TOUCH_STATE_SCROLLING) {
1636 pageBeginMoving();
1637 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001638 break;
1639
1640 case MotionEvent.ACTION_MOVE:
1641 if (mTouchState == TOUCH_STATE_SCROLLING) {
1642 // Scroll to follow the motion event
1643 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001644
1645 if (pointerIndex == -1) return true;
1646
Winson Chung321e9ee2010-08-09 13:37:56 -07001647 final float x = ev.getX(pointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001648 final float deltaX = mLastMotionX + mLastMotionXRemainder - x;
Winson Chung321e9ee2010-08-09 13:37:56 -07001649
Adam Cohenaefd4e12011-02-14 16:39:38 -08001650 mTotalMotionX += Math.abs(deltaX);
1651
Winson Chungc0844aa2011-02-02 15:25:58 -08001652 // Only scroll and update mLastMotionX if we have moved some discrete amount. We
1653 // keep the remainder because we are actually testing if we've moved from the last
1654 // scrolled position (which is discrete).
1655 if (Math.abs(deltaX) >= 1.0f) {
Adam Cohen68d73932010-11-15 10:50:58 -08001656 mTouchX += deltaX;
1657 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1658 if (!mDeferScrollUpdate) {
Winson Chungc0844aa2011-02-02 15:25:58 -08001659 scrollBy((int) deltaX, 0);
Winson Chung785d2eb2011-04-14 16:08:02 -07001660 if (DEBUG) Log.d(TAG, "onTouchEvent().Scrolling: " + deltaX);
Adam Cohen68d73932010-11-15 10:50:58 -08001661 } else {
1662 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001663 }
Winson Chungc0844aa2011-02-02 15:25:58 -08001664 mLastMotionX = x;
1665 mLastMotionXRemainder = deltaX - (int) deltaX;
Winson Chung321e9ee2010-08-09 13:37:56 -07001666 } else {
1667 awakenScrollBars();
1668 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001669 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1670 // Update the last motion position
1671 mLastMotionX = ev.getX();
1672 mLastMotionY = ev.getY();
1673
1674 // Update the parent down so that our zoom animations take this new movement into
1675 // account
1676 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1677 mParentDownMotionX = pt[0];
1678 mParentDownMotionY = pt[1];
1679 updateDragViewTranslationDuringDrag();
1680
1681 // Find the closest page to the touch point
1682 final int dragViewIndex = indexOfChild(mDragView);
Adam Cohen7d30a372013-07-01 17:03:59 -07001683
1684 // Change the drag view if we are hovering over the drop target
1685 boolean isHoveringOverDelete = isHoveringOverDeleteDropTarget(
1686 (int) mParentDownMotionX, (int) mParentDownMotionY);
1687 setPageHoveringOverDeleteDropTarget(dragViewIndex, isHoveringOverDelete);
1688
Adam Cohen7d30a372013-07-01 17:03:59 -07001689 if (DEBUG) Log.d(TAG, "mLastMotionX: " + mLastMotionX);
1690 if (DEBUG) Log.d(TAG, "mLastMotionY: " + mLastMotionY);
1691 if (DEBUG) Log.d(TAG, "mParentDownMotionX: " + mParentDownMotionX);
1692 if (DEBUG) Log.d(TAG, "mParentDownMotionY: " + mParentDownMotionY);
1693
Adam Cohenf358a4b2013-07-23 16:47:31 -07001694 final int pageUnderPointIndex = getNearestHoverOverPageIndex();
1695 if (pageUnderPointIndex > -1 && pageUnderPointIndex != indexOfChild(mDragView) &&
1696 !isHoveringOverDelete) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001697 mTempVisiblePagesRange[0] = 0;
1698 mTempVisiblePagesRange[1] = getPageCount() - 1;
Adam Cohenf358a4b2013-07-23 16:47:31 -07001699 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07001700 if (mTempVisiblePagesRange[0] <= pageUnderPointIndex &&
1701 pageUnderPointIndex <= mTempVisiblePagesRange[1] &&
1702 pageUnderPointIndex != mSidePageHoverIndex && mScroller.isFinished()) {
1703 mSidePageHoverIndex = pageUnderPointIndex;
1704 mSidePageHoverRunnable = new Runnable() {
1705 @Override
1706 public void run() {
Adam Cohen7d30a372013-07-01 17:03:59 -07001707 // Setup the scroll to the correct page before we swap the views
1708 snapToPage(pageUnderPointIndex);
1709
1710 // For each of the pages between the paged view and the drag view,
1711 // animate them from the previous position to the new position in
1712 // the layout (as a result of the drag view moving in the layout)
1713 int shiftDelta = (dragViewIndex < pageUnderPointIndex) ? -1 : 1;
1714 int lowerIndex = (dragViewIndex < pageUnderPointIndex) ?
1715 dragViewIndex + 1 : pageUnderPointIndex;
1716 int upperIndex = (dragViewIndex > pageUnderPointIndex) ?
1717 dragViewIndex - 1 : pageUnderPointIndex;
1718 for (int i = lowerIndex; i <= upperIndex; ++i) {
1719 View v = getChildAt(i);
1720 // dragViewIndex < pageUnderPointIndex, so after we remove the
1721 // drag view all subsequent views to pageUnderPointIndex will
1722 // shift down.
1723 int oldX = getViewportOffsetX() + getChildOffset(i);
1724 int newX = getViewportOffsetX() + getChildOffset(i + shiftDelta);
1725
1726 // Animate the view translation from its old position to its new
1727 // position
1728 AnimatorSet anim = (AnimatorSet) v.getTag(ANIM_TAG_KEY);
1729 if (anim != null) {
1730 anim.cancel();
1731 }
1732
1733 v.setTranslationX(oldX - newX);
1734 anim = new AnimatorSet();
1735 anim.setDuration(REORDERING_REORDER_REPOSITION_DURATION);
1736 anim.playTogether(
1737 ObjectAnimator.ofFloat(v, "translationX", 0f));
1738 anim.start();
1739 v.setTag(anim);
1740 }
1741
1742 removeView(mDragView);
1743 onRemoveView(mDragView, false);
1744 addView(mDragView, pageUnderPointIndex);
1745 onAddView(mDragView, pageUnderPointIndex);
1746 mSidePageHoverIndex = -1;
Winson Chungd2be3812013-07-16 11:11:32 -07001747 mPageIndicator.setActiveMarker(getNextPage());
Adam Cohen7d30a372013-07-01 17:03:59 -07001748 }
1749 };
1750 postDelayed(mSidePageHoverRunnable, REORDERING_SIDE_PAGE_HOVER_TIMEOUT);
1751 }
1752 } else {
1753 removeCallbacks(mSidePageHoverRunnable);
1754 mSidePageHoverIndex = -1;
1755 }
Adam Cohen564976a2010-10-13 18:52:07 -07001756 } else {
Winson Chung321e9ee2010-08-09 13:37:56 -07001757 determineScrollingStart(ev);
1758 }
1759 break;
1760
1761 case MotionEvent.ACTION_UP:
1762 if (mTouchState == TOUCH_STATE_SCROLLING) {
1763 final int activePointerId = mActivePointerId;
1764 final int pointerIndex = ev.findPointerIndex(activePointerId);
1765 final float x = ev.getX(pointerIndex);
1766 final VelocityTracker velocityTracker = mVelocityTracker;
1767 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
1768 int velocityX = (int) velocityTracker.getXVelocity(activePointerId);
Winson Chung9cfd25f2010-10-24 16:09:28 -07001769 final int deltaX = (int) (x - mDownMotionX);
Adam Cohen96d30a12013-07-16 18:13:21 -07001770 final int pageWidth = getPageAt(mCurrentPage).getMeasuredWidth();
Adam Cohen00481b32011-11-18 12:03:48 -08001771 boolean isSignificantMove = Math.abs(deltaX) > pageWidth *
1772 SIGNIFICANT_MOVE_THRESHOLD;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001773
Adam Cohenb64cb5a2011-02-15 13:53:42 -08001774 mTotalMotionX += Math.abs(mLastMotionX + mLastMotionXRemainder - x);
1775
Adam Cohen00481b32011-11-18 12:03:48 -08001776 boolean isFling = mTotalMotionX > MIN_LENGTH_FOR_FLING &&
Adam Cohen265b9a62011-12-07 14:37:18 -08001777 Math.abs(velocityX) > mFlingThresholdVelocity;
Adam Cohen00481b32011-11-18 12:03:48 -08001778
Adam Cohenf358a4b2013-07-23 16:47:31 -07001779 if (!mFreeScroll) {
1780 // In the case that the page is moved far to one direction and then is flung
1781 // in the opposite direction, we use a threshold to determine whether we should
1782 // just return to the starting page, or if we should skip one further.
1783 boolean returnToOriginalPage = false;
1784 if (Math.abs(deltaX) > pageWidth * RETURN_TO_ORIGINAL_PAGE_THRESHOLD &&
1785 Math.signum(velocityX) != Math.signum(deltaX) && isFling) {
1786 returnToOriginalPage = true;
1787 }
Adam Cohenaefd4e12011-02-14 16:39:38 -08001788
Adam Cohenf358a4b2013-07-23 16:47:31 -07001789 int finalPage;
1790 // We give flings precedence over large moves, which is why we short-circuit our
1791 // test for a large move if a fling has been registered. That is, a large
1792 // move to the left and fling to the right will register as a fling to the right.
1793 final boolean isRtl = isLayoutRtl();
1794 boolean isDeltaXLeft = isRtl ? deltaX > 0 : deltaX < 0;
1795 boolean isVelocityXLeft = isRtl ? velocityX > 0 : velocityX < 0;
1796 if (((isSignificantMove && !isDeltaXLeft && !isFling) ||
1797 (isFling && !isVelocityXLeft)) && mCurrentPage > 0) {
1798 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage - 1;
1799 snapToPageWithVelocity(finalPage, velocityX);
1800 } else if (((isSignificantMove && isDeltaXLeft && !isFling) ||
1801 (isFling && isVelocityXLeft)) &&
1802 mCurrentPage < getChildCount() - 1) {
1803 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage + 1;
1804 snapToPageWithVelocity(finalPage, velocityX);
1805 } else {
1806 snapToDestination();
1807 } } else if (mTouchState == TOUCH_STATE_PREV_PAGE) {
1808 // at this point we have not moved beyond the touch slop
1809 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1810 // we can just page
1811 int nextPage = Math.max(0, mCurrentPage - 1);
1812 if (nextPage != mCurrentPage) {
1813 snapToPage(nextPage);
1814 } else {
1815 snapToDestination();
1816 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001817 } else {
Adam Cohenf358a4b2013-07-23 16:47:31 -07001818 if (!mScroller.isFinished()) {
1819 mScroller.abortAnimation();
1820 }
1821
1822 float scaleX = getScaleX();
1823 int vX = (int) (-velocityX * scaleX);
1824 int initialScrollX = (int) (getScrollX() * scaleX);
1825
1826 mScroller.fling(initialScrollX,
1827 getScrollY(), vX, 0, Integer.MIN_VALUE, Integer.MAX_VALUE, 0, 0);
1828 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001829 }
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001830 } else if (mTouchState == TOUCH_STATE_NEXT_PAGE) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001831 // at this point we have not moved beyond the touch slop
1832 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1833 // we can just page
Winson Chung86f77532010-08-24 11:08:22 -07001834 int nextPage = Math.min(getChildCount() - 1, mCurrentPage + 1);
1835 if (nextPage != mCurrentPage) {
1836 snapToPage(nextPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001837 } else {
1838 snapToDestination();
1839 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001840 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1841 // Update the last motion position
1842 mLastMotionX = ev.getX();
1843 mLastMotionY = ev.getY();
1844
1845 // Update the parent down so that our zoom animations take this new movement into
1846 // account
1847 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1848 mParentDownMotionX = pt[0];
1849 mParentDownMotionY = pt[1];
1850 updateDragViewTranslationDuringDrag();
1851 boolean handledFling = false;
1852 if (!DISABLE_FLING_TO_DELETE) {
1853 // Check the velocity and see if we are flinging-to-delete
1854 PointF flingToDeleteVector = isFlingingToDelete();
1855 if (flingToDeleteVector != null) {
1856 onFlingToDelete(flingToDeleteVector);
1857 handledFling = true;
1858 }
1859 }
1860 if (!handledFling && isHoveringOverDeleteDropTarget((int) mParentDownMotionX,
1861 (int) mParentDownMotionY)) {
1862 onDropToDelete();
1863 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001864 } else {
Adam Cohendbdff6b2013-09-18 19:09:15 -07001865 if (!mCancelTap) {
1866 onUnhandledTap(ev);
1867 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001868 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001869
1870 // Remove the callback to wait for the side page hover timeout
1871 removeCallbacks(mSidePageHoverRunnable);
1872 // End any intermediate reordering states
1873 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001874 break;
1875
1876 case MotionEvent.ACTION_CANCEL:
Michael Jurkab8f06722010-10-10 15:58:46 -07001877 if (mTouchState == TOUCH_STATE_SCROLLING) {
1878 snapToDestination();
1879 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001880 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001881 break;
1882
1883 case MotionEvent.ACTION_POINTER_UP:
1884 onSecondaryPointerUp(ev);
Adam Cohenf358a4b2013-07-23 16:47:31 -07001885 releaseVelocityTracker();
Winson Chung321e9ee2010-08-09 13:37:56 -07001886 break;
1887 }
1888
1889 return true;
1890 }
1891
Adam Cohen7d30a372013-07-01 17:03:59 -07001892 public void onFlingToDelete(View v) {}
1893 public void onRemoveView(View v, boolean deletePermanently) {}
1894 public void onRemoveViewAnimationCompleted() {}
1895 public void onAddView(View v, int index) {}
1896
1897 private void resetTouchState() {
1898 releaseVelocityTracker();
1899 endReordering();
Adam Cohendbdff6b2013-09-18 19:09:15 -07001900 mCancelTap = false;
Adam Cohen7d30a372013-07-01 17:03:59 -07001901 mTouchState = TOUCH_STATE_REST;
1902 mActivePointerId = INVALID_POINTER;
Adam Cohen7d30a372013-07-01 17:03:59 -07001903 }
1904
Adam Cohen1697b792013-09-17 19:08:21 -07001905 protected void onUnhandledTap(MotionEvent ev) {
1906 ((Launcher) getContext()).onClick(this);
1907 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001908
Winson Chung185d7162011-02-28 13:47:29 -08001909 @Override
1910 public boolean onGenericMotionEvent(MotionEvent event) {
1911 if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
1912 switch (event.getAction()) {
1913 case MotionEvent.ACTION_SCROLL: {
1914 // Handle mouse (or ext. device) by shifting the page depending on the scroll
1915 final float vscroll;
1916 final float hscroll;
1917 if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) {
1918 vscroll = 0;
1919 hscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1920 } else {
1921 vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1922 hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL);
1923 }
1924 if (hscroll != 0 || vscroll != 0) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001925 boolean isForwardScroll = isLayoutRtl() ? (hscroll < 0 || vscroll < 0)
1926 : (hscroll > 0 || vscroll > 0);
1927 if (isForwardScroll) {
Winson Chung185d7162011-02-28 13:47:29 -08001928 scrollRight();
1929 } else {
1930 scrollLeft();
1931 }
1932 return true;
1933 }
1934 }
1935 }
1936 }
1937 return super.onGenericMotionEvent(event);
1938 }
1939
Michael Jurkab8f06722010-10-10 15:58:46 -07001940 private void acquireVelocityTrackerAndAddMovement(MotionEvent ev) {
1941 if (mVelocityTracker == null) {
1942 mVelocityTracker = VelocityTracker.obtain();
1943 }
1944 mVelocityTracker.addMovement(ev);
1945 }
1946
1947 private void releaseVelocityTracker() {
1948 if (mVelocityTracker != null) {
Adam Cohenf358a4b2013-07-23 16:47:31 -07001949 mVelocityTracker.clear();
Michael Jurkab8f06722010-10-10 15:58:46 -07001950 mVelocityTracker.recycle();
1951 mVelocityTracker = null;
1952 }
1953 }
1954
Winson Chung321e9ee2010-08-09 13:37:56 -07001955 private void onSecondaryPointerUp(MotionEvent ev) {
1956 final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
1957 MotionEvent.ACTION_POINTER_INDEX_SHIFT;
1958 final int pointerId = ev.getPointerId(pointerIndex);
1959 if (pointerId == mActivePointerId) {
1960 // This was our active pointer going up. Choose a new
1961 // active pointer and adjust accordingly.
1962 // TODO: Make this decision more intelligent.
1963 final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
1964 mLastMotionX = mDownMotionX = ev.getX(newPointerIndex);
1965 mLastMotionY = ev.getY(newPointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001966 mLastMotionXRemainder = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001967 mActivePointerId = ev.getPointerId(newPointerIndex);
1968 if (mVelocityTracker != null) {
1969 mVelocityTracker.clear();
1970 }
1971 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001972 }
1973
Winson Chung321e9ee2010-08-09 13:37:56 -07001974 @Override
1975 public void requestChildFocus(View child, View focused) {
1976 super.requestChildFocus(child, focused);
Adam Cohenae4f1552011-10-20 00:15:42 -07001977 int page = indexToPage(indexOfChild(child));
Winson Chung97d85d22011-04-13 11:27:36 -07001978 if (page >= 0 && page != getCurrentPage() && !isInTouchMode()) {
Winson Chung86f77532010-08-24 11:08:22 -07001979 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001980 }
1981 }
1982
Winson Chung1908d072011-02-24 18:09:44 -08001983 protected int getChildWidth(int index) {
Adam Cohen96d30a12013-07-16 18:13:21 -07001984 return getPageAt(index).getMeasuredWidth();
Winson Chung1908d072011-02-24 18:09:44 -08001985 }
1986
Adam Cohen7d30a372013-07-01 17:03:59 -07001987 int getPageNearestToPoint(float x) {
1988 int index = 0;
1989 for (int i = 0; i < getChildCount(); ++i) {
1990 if (x < getChildAt(i).getRight() - getScrollX()) {
1991 return index;
1992 } else {
1993 index++;
1994 }
1995 }
1996 return Math.min(index, getChildCount() - 1);
1997 }
1998
Adam Cohend19d3ca2010-09-15 14:43:42 -07001999 int getPageNearestToCenterOfScreen() {
Adam Cohen22f823d2011-09-01 17:22:18 -07002000 int minDistanceFromScreenCenter = Integer.MAX_VALUE;
Winson Chung321e9ee2010-08-09 13:37:56 -07002001 int minDistanceFromScreenCenterIndex = -1;
Adam Cohen7d30a372013-07-01 17:03:59 -07002002 int screenCenter = getViewportOffsetX() + getScrollX() + (getViewportWidth() / 2);
Winson Chung321e9ee2010-08-09 13:37:56 -07002003 final int childCount = getChildCount();
2004 for (int i = 0; i < childCount; ++i) {
Adam Cohen22f823d2011-09-01 17:22:18 -07002005 View layout = (View) getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -07002006 int childWidth = layout.getMeasuredWidth();
Winson Chung321e9ee2010-08-09 13:37:56 -07002007 int halfChildWidth = (childWidth / 2);
Adam Cohen7d30a372013-07-01 17:03:59 -07002008 int childCenter = getViewportOffsetX() + getChildOffset(i) + halfChildWidth;
Winson Chung321e9ee2010-08-09 13:37:56 -07002009 int distanceFromScreenCenter = Math.abs(childCenter - screenCenter);
2010 if (distanceFromScreenCenter < minDistanceFromScreenCenter) {
2011 minDistanceFromScreenCenter = distanceFromScreenCenter;
2012 minDistanceFromScreenCenterIndex = i;
2013 }
2014 }
Adam Cohend19d3ca2010-09-15 14:43:42 -07002015 return minDistanceFromScreenCenterIndex;
2016 }
2017
2018 protected void snapToDestination() {
2019 snapToPage(getPageNearestToCenterOfScreen(), PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07002020 }
2021
Adam Cohene0f66b52010-11-23 15:06:07 -08002022 private static class ScrollInterpolator implements Interpolator {
2023 public ScrollInterpolator() {
2024 }
2025
2026 public float getInterpolation(float t) {
2027 t -= 1.0f;
2028 return t*t*t*t*t + 1;
2029 }
2030 }
2031
2032 // We want the duration of the page snap animation to be influenced by the distance that
2033 // the screen has to travel, however, we don't want this duration to be effected in a
2034 // purely linear fashion. Instead, we use this method to moderate the effect that the distance
2035 // of travel has on the overall snap duration.
2036 float distanceInfluenceForSnapDuration(float f) {
2037 f -= 0.5f; // center the values about 0.
2038 f *= 0.3f * Math.PI / 2.0f;
2039 return (float) Math.sin(f);
2040 }
2041
Michael Jurka0142d492010-08-25 17:46:15 -07002042 protected void snapToPageWithVelocity(int whichPage, int velocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08002043 whichPage = Math.max(0, Math.min(whichPage, getChildCount() - 1));
Adam Cohen7d30a372013-07-01 17:03:59 -07002044 int halfScreenSize = getViewportWidth() / 2;
Adam Cohene0f66b52010-11-23 15:06:07 -08002045
Adam Cohenedb40762013-07-18 16:45:45 -07002046 final int newX = getScrollForPage(whichPage);
Adam Cohene0f66b52010-11-23 15:06:07 -08002047 int delta = newX - mUnboundedScrollX;
2048 int duration = 0;
2049
Adam Cohen265b9a62011-12-07 14:37:18 -08002050 if (Math.abs(velocity) < mMinFlingVelocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08002051 // If the velocity is low enough, then treat this more as an automatic page advance
2052 // as opposed to an apparent physical response to flinging
2053 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
2054 return;
2055 }
2056
2057 // Here we compute a "distance" that will be used in the computation of the overall
2058 // snap duration. This is a function of the actual distance that needs to be traveled;
2059 // we keep this value close to half screen size in order to reduce the variance in snap
2060 // duration as a function of the distance the page needs to travel.
Michael Jurka20b7ca92011-06-07 20:09:16 -07002061 float distanceRatio = Math.min(1f, 1.0f * Math.abs(delta) / (2 * halfScreenSize));
Adam Cohene0f66b52010-11-23 15:06:07 -08002062 float distance = halfScreenSize + halfScreenSize *
2063 distanceInfluenceForSnapDuration(distanceRatio);
2064
2065 velocity = Math.abs(velocity);
Adam Cohen265b9a62011-12-07 14:37:18 -08002066 velocity = Math.max(mMinSnapVelocity, velocity);
Adam Cohene0f66b52010-11-23 15:06:07 -08002067
2068 // we want the page's snap velocity to approximately match the velocity at which the
2069 // user flings, so we scale the duration by a value near to the derivative of the scroll
Michael Jurka20b7ca92011-06-07 20:09:16 -07002070 // interpolator at zero, ie. 5. We use 4 to make it a little slower.
2071 duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
Adam Cohene0f66b52010-11-23 15:06:07 -08002072
2073 snapToPage(whichPage, delta, duration);
Michael Jurka0142d492010-08-25 17:46:15 -07002074 }
2075
2076 protected void snapToPage(int whichPage) {
Winson Chung5f2aa4e2010-08-20 14:49:25 -07002077 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07002078 }
2079
Adam Cohen7d30a372013-07-01 17:03:59 -07002080 protected void snapToPageImmediately(int whichPage) {
2081 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION, true);
2082 }
2083
Michael Jurka0142d492010-08-25 17:46:15 -07002084 protected void snapToPage(int whichPage, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07002085 snapToPage(whichPage, duration, false);
2086 }
2087
2088 protected void snapToPage(int whichPage, int duration, boolean immediate) {
Winson Chung86f77532010-08-24 11:08:22 -07002089 whichPage = Math.max(0, Math.min(whichPage, getPageCount() - 1));
Winson Chung321e9ee2010-08-09 13:37:56 -07002090
Adam Cohenedb40762013-07-18 16:45:45 -07002091 int newX = getScrollForPage(whichPage);
Adam Cohen68d73932010-11-15 10:50:58 -08002092 final int sX = mUnboundedScrollX;
Winson Chung321e9ee2010-08-09 13:37:56 -07002093 final int delta = newX - sX;
Adam Cohen7d30a372013-07-01 17:03:59 -07002094 snapToPage(whichPage, delta, duration, immediate);
Michael Jurka0142d492010-08-25 17:46:15 -07002095 }
2096
2097 protected void snapToPage(int whichPage, int delta, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07002098 snapToPage(whichPage, delta, duration, false);
2099 }
Michael Jurka0142d492010-08-25 17:46:15 -07002100
Adam Cohen7d30a372013-07-01 17:03:59 -07002101 protected void snapToPage(int whichPage, int delta, int duration, boolean immediate) {
2102 mNextPage = whichPage;
Michael Jurka0142d492010-08-25 17:46:15 -07002103 View focusedChild = getFocusedChild();
2104 if (focusedChild != null && whichPage != mCurrentPage &&
Adam Cohen22f823d2011-09-01 17:22:18 -07002105 focusedChild == getPageAt(mCurrentPage)) {
Michael Jurka0142d492010-08-25 17:46:15 -07002106 focusedChild.clearFocus();
2107 }
2108
2109 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07002110 awakenScrollBars(duration);
Adam Cohen7d30a372013-07-01 17:03:59 -07002111 if (immediate) {
2112 duration = 0;
2113 } else if (duration == 0) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002114 duration = Math.abs(delta);
2115 }
2116
Adam Cohenf358a4b2013-07-23 16:47:31 -07002117 if (!mScroller.isFinished()) {
2118 mScroller.abortAnimation();
2119 }
Adam Cohen68d73932010-11-15 10:50:58 -08002120 mScroller.startScroll(mUnboundedScrollX, 0, delta, 0, duration);
Winson Chung80baf5a2010-08-09 16:03:15 -07002121
Michael Jurka0142d492010-08-25 17:46:15 -07002122 notifyPageSwitchListener();
Adam Cohen7d30a372013-07-01 17:03:59 -07002123
2124 // Trigger a compute() to finish switching pages if necessary
2125 if (immediate) {
2126 computeScroll();
2127 }
2128
Winson Chung9c0565f2013-07-19 13:49:06 -07002129 // Defer loading associated pages until the scroll settles
2130 mDeferLoadAssociatedPagesUntilScrollCompletes = true;
2131
Adam Cohen7d30a372013-07-01 17:03:59 -07002132 mForceScreenScrolled = true;
Winson Chung321e9ee2010-08-09 13:37:56 -07002133 invalidate();
2134 }
2135
Winson Chung321e9ee2010-08-09 13:37:56 -07002136 public void scrollLeft() {
2137 if (mScroller.isFinished()) {
Winson Chung86f77532010-08-24 11:08:22 -07002138 if (mCurrentPage > 0) snapToPage(mCurrentPage - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002139 } else {
Winson Chung86f77532010-08-24 11:08:22 -07002140 if (mNextPage > 0) snapToPage(mNextPage - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002141 }
2142 }
2143
2144 public void scrollRight() {
2145 if (mScroller.isFinished()) {
Winson Chung86f77532010-08-24 11:08:22 -07002146 if (mCurrentPage < getChildCount() -1) snapToPage(mCurrentPage + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002147 } else {
Winson Chung86f77532010-08-24 11:08:22 -07002148 if (mNextPage < getChildCount() -1) snapToPage(mNextPage + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002149 }
2150 }
2151
Winson Chung86f77532010-08-24 11:08:22 -07002152 public int getPageForView(View v) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002153 int result = -1;
2154 if (v != null) {
2155 ViewParent vp = v.getParent();
2156 int count = getChildCount();
2157 for (int i = 0; i < count; i++) {
Adam Cohen22f823d2011-09-01 17:22:18 -07002158 if (vp == getPageAt(i)) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002159 return i;
2160 }
2161 }
2162 }
2163 return result;
2164 }
2165
2166 /**
2167 * @return True is long presses are still allowed for the current touch
2168 */
2169 public boolean allowLongPress() {
2170 return mAllowLongPress;
2171 }
2172
Adam Cohendbdff6b2013-09-18 19:09:15 -07002173 @Override
2174 public boolean performLongClick() {
2175 mCancelTap = true;
2176 return super.performLongClick();
2177 }
2178
Michael Jurka0142d492010-08-25 17:46:15 -07002179 /**
2180 * Set true to allow long-press events to be triggered, usually checked by
2181 * {@link Launcher} to accept or block dpad-initiated long-presses.
2182 */
2183 public void setAllowLongPress(boolean allowLongPress) {
2184 mAllowLongPress = allowLongPress;
2185 }
2186
Winson Chung321e9ee2010-08-09 13:37:56 -07002187 public static class SavedState extends BaseSavedState {
Winson Chung86f77532010-08-24 11:08:22 -07002188 int currentPage = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -07002189
2190 SavedState(Parcelable superState) {
2191 super(superState);
2192 }
2193
2194 private SavedState(Parcel in) {
2195 super(in);
Winson Chung86f77532010-08-24 11:08:22 -07002196 currentPage = in.readInt();
Winson Chung321e9ee2010-08-09 13:37:56 -07002197 }
2198
2199 @Override
2200 public void writeToParcel(Parcel out, int flags) {
2201 super.writeToParcel(out, flags);
Winson Chung86f77532010-08-24 11:08:22 -07002202 out.writeInt(currentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07002203 }
2204
2205 public static final Parcelable.Creator<SavedState> CREATOR =
2206 new Parcelable.Creator<SavedState>() {
2207 public SavedState createFromParcel(Parcel in) {
2208 return new SavedState(in);
2209 }
2210
2211 public SavedState[] newArray(int size) {
2212 return new SavedState[size];
2213 }
2214 };
2215 }
2216
Winson Chungf314b0e2011-08-16 11:54:27 -07002217 protected void loadAssociatedPages(int page) {
2218 loadAssociatedPages(page, false);
2219 }
2220 protected void loadAssociatedPages(int page, boolean immediateAndOnly) {
Michael Jurka0142d492010-08-25 17:46:15 -07002221 if (mContentIsRefreshable) {
2222 final int count = getChildCount();
2223 if (page < count) {
Winson Chunge3193b92010-09-10 11:44:42 -07002224 int lowerPageBound = getAssociatedLowerPageBound(page);
2225 int upperPageBound = getAssociatedUpperPageBound(page);
Winson Chung785d2eb2011-04-14 16:08:02 -07002226 if (DEBUG) Log.d(TAG, "loadAssociatedPages: " + lowerPageBound + "/"
2227 + upperPageBound);
Michael Jurka0cad1112011-11-16 20:43:29 -08002228 // First, clear any pages that should no longer be loaded
2229 for (int i = 0; i < count; ++i) {
2230 Page layout = (Page) getPageAt(i);
Michael Jurka2a4b1a82011-12-07 14:00:02 -08002231 if ((i < lowerPageBound) || (i > upperPageBound)) {
Michael Jurka0cad1112011-11-16 20:43:29 -08002232 if (layout.getPageChildCount() > 0) {
2233 layout.removeAllViewsOnPage();
2234 }
2235 mDirtyPageContent.set(i, true);
2236 }
2237 }
2238 // Next, load any new pages
Michael Jurka0142d492010-08-25 17:46:15 -07002239 for (int i = 0; i < count; ++i) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002240 if ((i != page) && immediateAndOnly) {
2241 continue;
2242 }
Michael Jurka0142d492010-08-25 17:46:15 -07002243 if (lowerPageBound <= i && i <= upperPageBound) {
2244 if (mDirtyPageContent.get(i)) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002245 syncPageItems(i, (i == page) && immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002246 mDirtyPageContent.set(i, false);
2247 }
Winson Chung86f77532010-08-24 11:08:22 -07002248 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002249 }
2250 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002251 }
2252 }
2253
Winson Chunge3193b92010-09-10 11:44:42 -07002254 protected int getAssociatedLowerPageBound(int page) {
2255 return Math.max(0, page - 1);
2256 }
2257 protected int getAssociatedUpperPageBound(int page) {
2258 final int count = getChildCount();
2259 return Math.min(page + 1, count - 1);
2260 }
2261
Winson Chung86f77532010-08-24 11:08:22 -07002262 /**
2263 * This method is called ONLY to synchronize the number of pages that the paged view has.
2264 * To actually fill the pages with information, implement syncPageItems() below. It is
2265 * guaranteed that syncPageItems() will be called for a particular page before it is shown,
2266 * and therefore, individual page items do not need to be updated in this method.
2267 */
Winson Chung321e9ee2010-08-09 13:37:56 -07002268 public abstract void syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002269
2270 /**
2271 * This method is called to synchronize the items that are on a particular page. If views on
2272 * the page can be reused, then they should be updated within this method.
2273 */
Winson Chungf314b0e2011-08-16 11:54:27 -07002274 public abstract void syncPageItems(int page, boolean immediate);
Winson Chung86f77532010-08-24 11:08:22 -07002275
Patrick Dubroy244d74c2011-05-19 16:48:48 -07002276 protected void invalidatePageData() {
Winson Chungf314b0e2011-08-16 11:54:27 -07002277 invalidatePageData(-1, false);
Winson Chung5a808352011-06-27 19:08:49 -07002278 }
2279 protected void invalidatePageData(int currentPage) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002280 invalidatePageData(currentPage, false);
2281 }
2282 protected void invalidatePageData(int currentPage, boolean immediateAndOnly) {
Winson Chungf0ea4d32011-06-06 14:27:16 -07002283 if (!mIsDataReady) {
2284 return;
2285 }
2286
Michael Jurka0142d492010-08-25 17:46:15 -07002287 if (mContentIsRefreshable) {
Adam Cohen0cd3b642011-10-14 14:58:00 -07002288 // Force all scrolling-related behavior to end
2289 mScroller.forceFinished(true);
2290 mNextPage = INVALID_PAGE;
2291
Michael Jurka0142d492010-08-25 17:46:15 -07002292 // Update all the pages
2293 syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002294
Winson Chung5a808352011-06-27 19:08:49 -07002295 // We must force a measure after we've loaded the pages to update the content width and
2296 // to determine the full scroll width
2297 measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY),
2298 MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY));
2299
2300 // Set a new page as the current page if necessary
2301 if (currentPage > -1) {
Winson Chung5afbf7b2011-07-25 11:53:08 -07002302 setCurrentPage(Math.min(getPageCount() - 1, currentPage));
Winson Chung5a808352011-06-27 19:08:49 -07002303 }
2304
Michael Jurka0142d492010-08-25 17:46:15 -07002305 // Mark each of the pages as dirty
2306 final int count = getChildCount();
2307 mDirtyPageContent.clear();
2308 for (int i = 0; i < count; ++i) {
2309 mDirtyPageContent.add(true);
2310 }
2311
2312 // Load any pages that are necessary for the current window of views
Winson Chungf314b0e2011-08-16 11:54:27 -07002313 loadAssociatedPages(mCurrentPage, immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002314 requestLayout();
Winson Chung86f77532010-08-24 11:08:22 -07002315 }
Winson Chung321e9ee2010-08-09 13:37:56 -07002316 }
Winson Chung007c6982011-06-14 13:27:53 -07002317
Adam Cohen7d30a372013-07-01 17:03:59 -07002318 // Animate the drag view back to the original position
2319 void animateDragViewToOriginalPosition() {
2320 if (mDragView != null) {
2321 AnimatorSet anim = new AnimatorSet();
2322 anim.setDuration(REORDERING_DROP_REPOSITION_DURATION);
2323 anim.playTogether(
2324 ObjectAnimator.ofFloat(mDragView, "translationX", 0f),
Adam Cohenf358a4b2013-07-23 16:47:31 -07002325 ObjectAnimator.ofFloat(mDragView, "translationY", 0f),
2326 ObjectAnimator.ofFloat(mDragView, "scaleX", 1f),
2327 ObjectAnimator.ofFloat(mDragView, "scaleY", 1f));
Adam Cohen7d30a372013-07-01 17:03:59 -07002328 anim.addListener(new AnimatorListenerAdapter() {
2329 @Override
2330 public void onAnimationEnd(Animator animation) {
2331 onPostReorderingAnimationCompleted();
2332 }
2333 });
2334 anim.start();
2335 }
Winson Chung3ac74c52011-06-30 17:39:37 -07002336 }
2337
Adam Cohen7d30a372013-07-01 17:03:59 -07002338 protected void onStartReordering() {
2339 // Set the touch state to reordering (allows snapping to pages, dragging a child, etc.)
2340 mTouchState = TOUCH_STATE_REORDERING;
2341 mIsReordering = true;
2342
Adam Cohen7d30a372013-07-01 17:03:59 -07002343 // We must invalidate to trigger a redraw to update the layers such that the drag view
2344 // is always drawn on top
2345 invalidate();
2346 }
2347
2348 private void onPostReorderingAnimationCompleted() {
2349 // Trigger the callback when reordering has settled
2350 --mPostReorderingPreZoomInRemainingAnimationCount;
2351 if (mPostReorderingPreZoomInRunnable != null &&
2352 mPostReorderingPreZoomInRemainingAnimationCount == 0) {
2353 mPostReorderingPreZoomInRunnable.run();
2354 mPostReorderingPreZoomInRunnable = null;
2355 }
2356 }
2357
2358 protected void onEndReordering() {
2359 mIsReordering = false;
Adam Cohen7d30a372013-07-01 17:03:59 -07002360 }
2361
Adam Cohenf358a4b2013-07-23 16:47:31 -07002362 public boolean startReordering(View v) {
2363 int dragViewIndex = indexOfChild(v);//getPageNearestToCenterOfScreen();
Adam Cohen7d30a372013-07-01 17:03:59 -07002364 mTempVisiblePagesRange[0] = 0;
2365 mTempVisiblePagesRange[1] = getPageCount() - 1;
Adam Cohenf358a4b2013-07-23 16:47:31 -07002366 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002367 mReorderingStarted = true;
2368
2369 // Check if we are within the reordering range
2370 if (mTempVisiblePagesRange[0] <= dragViewIndex &&
Adam Cohenf358a4b2013-07-23 16:47:31 -07002371 dragViewIndex <= mTempVisiblePagesRange[1]) {
2372 // Find the drag view under the pointer
2373 mDragView = getChildAt(dragViewIndex);
2374 mDragView.animate().scaleX(1.15f).scaleY(1.15f).setDuration(100).start();
2375 mDragViewBaselineLeft = mDragView.getLeft();
2376 disableFreeScroll(-1);
2377 onStartReordering();
Adam Cohen7d30a372013-07-01 17:03:59 -07002378 return true;
2379 }
2380 return false;
2381 }
2382
2383 boolean isReordering(boolean testTouchState) {
2384 boolean state = mIsReordering;
2385 if (testTouchState) {
2386 state &= (mTouchState == TOUCH_STATE_REORDERING);
2387 }
2388 return state;
2389 }
2390 void endReordering() {
2391 // For simplicity, we call endReordering sometimes even if reordering was never started.
2392 // In that case, we don't want to do anything.
2393 if (!mReorderingStarted) return;
2394 mReorderingStarted = false;
2395
2396 // If we haven't flung-to-delete the current child, then we just animate the drag view
2397 // back into position
2398 final Runnable onCompleteRunnable = new Runnable() {
2399 @Override
2400 public void run() {
2401 onEndReordering();
2402 }
2403 };
2404 if (!mDeferringForDelete) {
2405 mPostReorderingPreZoomInRunnable = new Runnable() {
2406 public void run() {
Adam Cohenf358a4b2013-07-23 16:47:31 -07002407 onCompleteRunnable.run();
2408 enableFreeScroll();
Adam Cohen7d30a372013-07-01 17:03:59 -07002409 };
2410 };
2411
2412 mPostReorderingPreZoomInRemainingAnimationCount =
2413 NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT;
2414 // Snap to the current page
2415 snapToPage(indexOfChild(mDragView), 0);
2416 // Animate the drag view back to the front position
2417 animateDragViewToOriginalPosition();
2418 } else {
2419 // Handled in post-delete-animation-callbacks
2420 }
2421 }
2422
Adam Cohen7d30a372013-07-01 17:03:59 -07002423 /*
2424 * Flinging to delete - IN PROGRESS
2425 */
2426 private PointF isFlingingToDelete() {
2427 ViewConfiguration config = ViewConfiguration.get(getContext());
2428 mVelocityTracker.computeCurrentVelocity(1000, config.getScaledMaximumFlingVelocity());
2429
2430 if (mVelocityTracker.getYVelocity() < mFlingToDeleteThresholdVelocity) {
2431 // Do a quick dot product test to ensure that we are flinging upwards
2432 PointF vel = new PointF(mVelocityTracker.getXVelocity(),
2433 mVelocityTracker.getYVelocity());
2434 PointF upVec = new PointF(0f, -1f);
2435 float theta = (float) Math.acos(((vel.x * upVec.x) + (vel.y * upVec.y)) /
2436 (vel.length() * upVec.length()));
2437 if (theta <= Math.toRadians(FLING_TO_DELETE_MAX_FLING_DEGREES)) {
2438 return vel;
2439 }
2440 }
2441 return null;
2442 }
2443
2444 /**
2445 * Creates an animation from the current drag view along its current velocity vector.
2446 * For this animation, the alpha runs for a fixed duration and we update the position
2447 * progressively.
2448 */
2449 private static class FlingAlongVectorAnimatorUpdateListener implements AnimatorUpdateListener {
2450 private View mDragView;
2451 private PointF mVelocity;
2452 private Rect mFrom;
2453 private long mPrevTime;
2454 private float mFriction;
2455
2456 private final TimeInterpolator mAlphaInterpolator = new DecelerateInterpolator(0.75f);
2457
2458 public FlingAlongVectorAnimatorUpdateListener(View dragView, PointF vel, Rect from,
2459 long startTime, float friction) {
2460 mDragView = dragView;
2461 mVelocity = vel;
2462 mFrom = from;
2463 mPrevTime = startTime;
2464 mFriction = 1f - (mDragView.getResources().getDisplayMetrics().density * friction);
2465 }
2466
2467 @Override
2468 public void onAnimationUpdate(ValueAnimator animation) {
2469 float t = ((Float) animation.getAnimatedValue()).floatValue();
2470 long curTime = AnimationUtils.currentAnimationTimeMillis();
2471
2472 mFrom.left += (mVelocity.x * (curTime - mPrevTime) / 1000f);
2473 mFrom.top += (mVelocity.y * (curTime - mPrevTime) / 1000f);
2474
2475 mDragView.setTranslationX(mFrom.left);
2476 mDragView.setTranslationY(mFrom.top);
2477 mDragView.setAlpha(1f - mAlphaInterpolator.getInterpolation(t));
2478
2479 mVelocity.x *= mFriction;
2480 mVelocity.y *= mFriction;
2481 mPrevTime = curTime;
2482 }
2483 };
2484
2485 private static final int ANIM_TAG_KEY = 100;
2486
2487 private Runnable createPostDeleteAnimationRunnable(final View dragView) {
2488 return new Runnable() {
2489 @Override
2490 public void run() {
2491 int dragViewIndex = indexOfChild(dragView);
2492
2493 // For each of the pages around the drag view, animate them from the previous
2494 // position to the new position in the layout (as a result of the drag view moving
2495 // in the layout)
2496 // NOTE: We can make an assumption here because we have side-bound pages that we
2497 // will always have pages to animate in from the left
Adam Cohenf358a4b2013-07-23 16:47:31 -07002498 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002499 boolean isLastWidgetPage = (mTempVisiblePagesRange[0] == mTempVisiblePagesRange[1]);
2500 boolean slideFromLeft = (isLastWidgetPage ||
2501 dragViewIndex > mTempVisiblePagesRange[0]);
2502
2503 // Setup the scroll to the correct page before we swap the views
2504 if (slideFromLeft) {
2505 snapToPageImmediately(dragViewIndex - 1);
2506 }
2507
2508 int firstIndex = (isLastWidgetPage ? 0 : mTempVisiblePagesRange[0]);
2509 int lastIndex = Math.min(mTempVisiblePagesRange[1], getPageCount() - 1);
2510 int lowerIndex = (slideFromLeft ? firstIndex : dragViewIndex + 1 );
2511 int upperIndex = (slideFromLeft ? dragViewIndex - 1 : lastIndex);
2512 ArrayList<Animator> animations = new ArrayList<Animator>();
2513 for (int i = lowerIndex; i <= upperIndex; ++i) {
2514 View v = getChildAt(i);
2515 // dragViewIndex < pageUnderPointIndex, so after we remove the
2516 // drag view all subsequent views to pageUnderPointIndex will
2517 // shift down.
2518 int oldX = 0;
2519 int newX = 0;
2520 if (slideFromLeft) {
2521 if (i == 0) {
2522 // Simulate the page being offscreen with the page spacing
2523 oldX = getViewportOffsetX() + getChildOffset(i) - getChildWidth(i)
2524 - mPageSpacing;
2525 } else {
2526 oldX = getViewportOffsetX() + getChildOffset(i - 1);
2527 }
2528 newX = getViewportOffsetX() + getChildOffset(i);
2529 } else {
2530 oldX = getChildOffset(i) - getChildOffset(i - 1);
2531 newX = 0;
2532 }
2533
2534 // Animate the view translation from its old position to its new
2535 // position
2536 AnimatorSet anim = (AnimatorSet) v.getTag();
2537 if (anim != null) {
2538 anim.cancel();
2539 }
2540
2541 // Note: Hacky, but we want to skip any optimizations to not draw completely
2542 // hidden views
2543 v.setAlpha(Math.max(v.getAlpha(), 0.01f));
2544 v.setTranslationX(oldX - newX);
2545 anim = new AnimatorSet();
2546 anim.playTogether(
2547 ObjectAnimator.ofFloat(v, "translationX", 0f),
2548 ObjectAnimator.ofFloat(v, "alpha", 1f));
2549 animations.add(anim);
2550 v.setTag(ANIM_TAG_KEY, anim);
2551 }
2552
2553 AnimatorSet slideAnimations = new AnimatorSet();
2554 slideAnimations.playTogether(animations);
2555 slideAnimations.setDuration(DELETE_SLIDE_IN_SIDE_PAGE_DURATION);
2556 slideAnimations.addListener(new AnimatorListenerAdapter() {
2557 @Override
2558 public void onAnimationEnd(Animator animation) {
Adam Cohenf358a4b2013-07-23 16:47:31 -07002559 mDeferringForDelete = false;
2560 onEndReordering();
2561 onRemoveViewAnimationCompleted();
Adam Cohen7d30a372013-07-01 17:03:59 -07002562 }
2563 });
2564 slideAnimations.start();
2565
2566 removeView(dragView);
2567 onRemoveView(dragView, true);
2568 }
2569 };
2570 }
2571
2572 public void onFlingToDelete(PointF vel) {
2573 final long startTime = AnimationUtils.currentAnimationTimeMillis();
2574
2575 // NOTE: Because it takes time for the first frame of animation to actually be
2576 // called and we expect the animation to be a continuation of the fling, we have
2577 // to account for the time that has elapsed since the fling finished. And since
2578 // we don't have a startDelay, we will always get call to update when we call
2579 // start() (which we want to ignore).
2580 final TimeInterpolator tInterpolator = new TimeInterpolator() {
2581 private int mCount = -1;
2582 private long mStartTime;
2583 private float mOffset;
2584 /* Anonymous inner class ctor */ {
2585 mStartTime = startTime;
2586 }
2587
2588 @Override
2589 public float getInterpolation(float t) {
2590 if (mCount < 0) {
2591 mCount++;
2592 } else if (mCount == 0) {
2593 mOffset = Math.min(0.5f, (float) (AnimationUtils.currentAnimationTimeMillis() -
2594 mStartTime) / FLING_TO_DELETE_FADE_OUT_DURATION);
2595 mCount++;
2596 }
2597 return Math.min(1f, mOffset + t);
2598 }
2599 };
2600
2601 final Rect from = new Rect();
2602 final View dragView = mDragView;
2603 from.left = (int) dragView.getTranslationX();
2604 from.top = (int) dragView.getTranslationY();
2605 AnimatorUpdateListener updateCb = new FlingAlongVectorAnimatorUpdateListener(dragView, vel,
2606 from, startTime, FLING_TO_DELETE_FRICTION);
2607
2608 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2609
2610 // Create and start the animation
2611 ValueAnimator mDropAnim = new ValueAnimator();
2612 mDropAnim.setInterpolator(tInterpolator);
2613 mDropAnim.setDuration(FLING_TO_DELETE_FADE_OUT_DURATION);
2614 mDropAnim.setFloatValues(0f, 1f);
2615 mDropAnim.addUpdateListener(updateCb);
2616 mDropAnim.addListener(new AnimatorListenerAdapter() {
2617 public void onAnimationEnd(Animator animation) {
2618 onAnimationEndRunnable.run();
2619 }
2620 });
2621 mDropAnim.start();
2622 mDeferringForDelete = true;
2623 }
2624
2625 /* Drag to delete */
2626 private boolean isHoveringOverDeleteDropTarget(int x, int y) {
2627 if (mDeleteDropTarget != null) {
2628 mAltTmpRect.set(0, 0, 0, 0);
2629 View parent = (View) mDeleteDropTarget.getParent();
2630 if (parent != null) {
2631 parent.getGlobalVisibleRect(mAltTmpRect);
2632 }
2633 mDeleteDropTarget.getGlobalVisibleRect(mTmpRect);
2634 mTmpRect.offset(-mAltTmpRect.left, -mAltTmpRect.top);
2635 return mTmpRect.contains(x, y);
2636 }
2637 return false;
2638 }
2639
2640 protected void setPageHoveringOverDeleteDropTarget(int viewIndex, boolean isHovering) {}
2641
2642 private void onDropToDelete() {
2643 final View dragView = mDragView;
2644
2645 final float toScale = 0f;
2646 final float toAlpha = 0f;
2647
2648 // Create and start the complex animation
2649 ArrayList<Animator> animations = new ArrayList<Animator>();
2650 AnimatorSet motionAnim = new AnimatorSet();
2651 motionAnim.setInterpolator(new DecelerateInterpolator(2));
2652 motionAnim.playTogether(
2653 ObjectAnimator.ofFloat(dragView, "scaleX", toScale),
2654 ObjectAnimator.ofFloat(dragView, "scaleY", toScale));
2655 animations.add(motionAnim);
2656
2657 AnimatorSet alphaAnim = new AnimatorSet();
2658 alphaAnim.setInterpolator(new LinearInterpolator());
2659 alphaAnim.playTogether(
2660 ObjectAnimator.ofFloat(dragView, "alpha", toAlpha));
2661 animations.add(alphaAnim);
2662
2663 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2664
2665 AnimatorSet anim = new AnimatorSet();
2666 anim.playTogether(animations);
2667 anim.setDuration(DRAG_TO_DELETE_FADE_OUT_DURATION);
2668 anim.addListener(new AnimatorListenerAdapter() {
2669 public void onAnimationEnd(Animator animation) {
2670 onAnimationEndRunnable.run();
2671 }
2672 });
2673 anim.start();
2674
2675 mDeferringForDelete = true;
Winson Chung007c6982011-06-14 13:27:53 -07002676 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002677
2678 /* Accessibility */
2679 @Override
2680 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
2681 super.onInitializeAccessibilityNodeInfo(info);
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002682 info.setScrollable(getPageCount() > 1);
2683 if (getCurrentPage() < getPageCount() - 1) {
2684 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
2685 }
2686 if (getCurrentPage() > 0) {
2687 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
2688 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002689 }
2690
2691 @Override
2692 public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
2693 super.onInitializeAccessibilityEvent(event);
2694 event.setScrollable(true);
2695 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_SCROLLED) {
2696 event.setFromIndex(mCurrentPage);
2697 event.setToIndex(mCurrentPage);
2698 event.setItemCount(getChildCount());
2699 }
2700 }
2701
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002702 @Override
2703 public boolean performAccessibilityAction(int action, Bundle arguments) {
2704 if (super.performAccessibilityAction(action, arguments)) {
2705 return true;
2706 }
2707 switch (action) {
2708 case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: {
2709 if (getCurrentPage() < getPageCount() - 1) {
2710 scrollRight();
2711 return true;
2712 }
2713 } break;
2714 case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: {
2715 if (getCurrentPage() > 0) {
2716 scrollLeft();
2717 return true;
2718 }
2719 } break;
2720 }
2721 return false;
2722 }
2723
Adam Cohen0ffac432013-07-10 11:19:26 -07002724 protected String getCurrentPageDescription() {
2725 return String.format(getContext().getString(R.string.default_scroll_format),
2726 getNextPage() + 1, getChildCount());
2727 }
2728
Winson Chungd11265e2011-08-30 13:37:23 -07002729 @Override
2730 public boolean onHoverEvent(android.view.MotionEvent event) {
2731 return true;
2732 }
Adam Cohen5084cba2013-09-03 12:01:16 -07002733}