blob: 9e6d9555345acb6256f42c13db8aa30db21eba37 [file] [log] [blame]
Eric Erfanian938468d2017-10-24 14:05:52 -07001/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
17package com.android.newbubble;
18
19import android.content.Context;
20import android.graphics.Point;
21import android.support.animation.FloatPropertyCompat;
22import android.support.animation.SpringAnimation;
23import android.support.animation.SpringForce;
24import android.support.annotation.NonNull;
25import android.view.Gravity;
26import android.view.MotionEvent;
27import android.view.VelocityTracker;
28import android.view.View;
29import android.view.View.OnTouchListener;
30import android.view.ViewConfiguration;
31import android.view.WindowManager;
32import android.view.WindowManager.LayoutParams;
33import android.widget.Scroller;
34
35/** Handles touches and manages moving the bubble in response */
36class NewMoveHandler implements OnTouchListener {
37
38 // Amount the ViewConfiguration's minFlingVelocity will be scaled by for our own minVelocity
39 private static final int MIN_FLING_VELOCITY_FACTOR = 8;
40 // The friction multiplier to control how slippery the bubble is when flung
41 private static final float SCROLL_FRICTION_MULTIPLIER = 4f;
42
43 private final Context context;
44 private final WindowManager windowManager;
45 private final NewBubble bubble;
46 private final int minX;
47 private final int minY;
48 private final int maxX;
49 private final int maxY;
50 private final int bubbleSize;
yueg81a77ff2017-12-05 10:29:03 -080051 private final int bubbleShadowPaddingHorizontal;
52 private final int bubbleExpandedViewWidth;
Eric Erfanian938468d2017-10-24 14:05:52 -070053 private final float touchSlopSquared;
54
55 private boolean clickable = true;
56 private boolean isMoving;
57 private float firstX;
58 private float firstY;
59
60 private SpringAnimation moveXAnimation;
61 private SpringAnimation moveYAnimation;
62 private VelocityTracker velocityTracker;
63 private Scroller scroller;
64
65 private static float clamp(float value, float min, float max) {
66 return Math.min(max, Math.max(min, value));
67 }
68
69 // Handles the left/right gravity conversion and centering
70 private final FloatPropertyCompat<WindowManager.LayoutParams> xProperty =
71 new FloatPropertyCompat<LayoutParams>("xProperty") {
72 @Override
73 public float getValue(LayoutParams windowParams) {
74 int realX = windowParams.x;
yueg81a77ff2017-12-05 10:29:03 -080075 // Get bubble center position from real position
76 if (bubble.getDrawerVisibility() == View.INVISIBLE) {
77 realX += bubbleExpandedViewWidth / 2 + bubbleShadowPaddingHorizontal * 2;
78 } else {
79 realX += bubbleSize / 2 + bubbleShadowPaddingHorizontal;
80 }
Eric Erfanian938468d2017-10-24 14:05:52 -070081 if (relativeToRight(windowParams)) {
yueg81a77ff2017-12-05 10:29:03 -080082 // If gravity is right, get distant from bubble center position to screen right edge
Eric Erfanian938468d2017-10-24 14:05:52 -070083 int displayWidth = context.getResources().getDisplayMetrics().widthPixels;
84 realX = displayWidth - realX;
85 }
86 return clamp(realX, minX, maxX);
87 }
88
89 @Override
90 public void setValue(LayoutParams windowParams, float value) {
yueg87111362017-12-08 12:45:50 -080091 boolean wasOnRight = (windowParams.gravity & Gravity.RIGHT) == Gravity.RIGHT;
Eric Erfanian938468d2017-10-24 14:05:52 -070092 int displayWidth = context.getResources().getDisplayMetrics().widthPixels;
93 boolean onRight;
94 Integer gravityOverride = bubble.getGravityOverride();
95 if (gravityOverride == null) {
96 onRight = value > displayWidth / 2;
97 } else {
98 onRight = (gravityOverride & Gravity.RIGHT) == Gravity.RIGHT;
99 }
yueg81a77ff2017-12-05 10:29:03 -0800100 // Get real position from bubble center position
101 int centeringOffset;
102 if (bubble.getDrawerVisibility() == View.INVISIBLE) {
103 centeringOffset = bubbleExpandedViewWidth / 2 + bubbleShadowPaddingHorizontal * 2;
104 } else {
105 centeringOffset = bubbleSize / 2 + bubbleShadowPaddingHorizontal;
106 }
Eric Erfanian938468d2017-10-24 14:05:52 -0700107 windowParams.x =
108 (int) (onRight ? (displayWidth - value - centeringOffset) : value - centeringOffset);
109 windowParams.gravity = Gravity.TOP | (onRight ? Gravity.RIGHT : Gravity.LEFT);
110 if (bubble.isVisible()) {
111 windowManager.updateViewLayout(bubble.getRootView(), windowParams);
yueg87111362017-12-08 12:45:50 -0800112 if (onRight != wasOnRight) {
113 bubble.onLeftRightSwitch(onRight);
114 }
Eric Erfanian938468d2017-10-24 14:05:52 -0700115 }
116 }
117 };
118
119 private final FloatPropertyCompat<WindowManager.LayoutParams> yProperty =
120 new FloatPropertyCompat<LayoutParams>("yProperty") {
121 @Override
122 public float getValue(LayoutParams object) {
123 return clamp(object.y + bubbleSize, minY, maxY);
124 }
125
126 @Override
127 public void setValue(LayoutParams object, float value) {
128 object.y = (int) value - bubbleSize;
129 if (bubble.isVisible()) {
130 windowManager.updateViewLayout(bubble.getRootView(), object);
131 }
132 }
133 };
134
135 public NewMoveHandler(@NonNull View targetView, @NonNull NewBubble bubble) {
136 this.bubble = bubble;
137 context = targetView.getContext();
138 windowManager = context.getSystemService(WindowManager.class);
139
140 bubbleSize = context.getResources().getDimensionPixelSize(R.dimen.bubble_size);
yueg81a77ff2017-12-05 10:29:03 -0800141 bubbleShadowPaddingHorizontal =
142 context.getResources().getDimensionPixelSize(R.dimen.bubble_shadow_padding_size_horizontal);
143 bubbleExpandedViewWidth =
144 context.getResources().getDimensionPixelSize(R.dimen.bubble_expanded_width);
145 // The following value is based on bubble center
Eric Erfanian938468d2017-10-24 14:05:52 -0700146 minX =
yueg81a77ff2017-12-05 10:29:03 -0800147 context.getResources().getDimensionPixelOffset(R.dimen.bubble_off_screen_size_horizontal)
Eric Erfanian938468d2017-10-24 14:05:52 -0700148 + bubbleSize / 2;
149 minY =
150 context.getResources().getDimensionPixelOffset(R.dimen.bubble_safe_margin_vertical)
151 + bubbleSize / 2;
152 maxX = context.getResources().getDisplayMetrics().widthPixels - minX;
153 maxY = context.getResources().getDisplayMetrics().heightPixels - minY;
154
155 // Squared because it will be compared against the square of the touch delta. This is more
156 // efficient than needing to take a square root.
157 touchSlopSquared = (float) Math.pow(ViewConfiguration.get(context).getScaledTouchSlop(), 2);
158
159 targetView.setOnTouchListener(this);
160 }
161
162 public void setClickable(boolean clickable) {
163 this.clickable = clickable;
164 }
165
166 public boolean isMoving() {
167 return isMoving;
168 }
169
170 public void undoGravityOverride() {
171 LayoutParams windowParams = bubble.getWindowParams();
172 xProperty.setValue(windowParams, xProperty.getValue(windowParams));
173 }
174
175 public void snapToBounds() {
176 ensureSprings();
177
178 moveXAnimation.animateToFinalPosition(relativeToRight(bubble.getWindowParams()) ? maxX : minX);
179 moveYAnimation.animateToFinalPosition(yProperty.getValue(bubble.getWindowParams()));
180 }
181
yueg81a77ff2017-12-05 10:29:03 -0800182 public int getMoveUpDistance(int deltaAllowed) {
183 int currentY = (int) yProperty.getValue(bubble.getWindowParams());
184 int currentDelta = maxY - currentY;
185 return currentDelta >= deltaAllowed ? 0 : deltaAllowed - currentDelta;
186 }
187
Eric Erfanian938468d2017-10-24 14:05:52 -0700188 @Override
189 public boolean onTouch(View v, MotionEvent event) {
190 float eventX = event.getRawX();
191 float eventY = event.getRawY();
192 switch (event.getActionMasked()) {
193 case MotionEvent.ACTION_DOWN:
194 firstX = eventX;
195 firstY = eventY;
196 velocityTracker = VelocityTracker.obtain();
197 break;
198 case MotionEvent.ACTION_MOVE:
199 if (isMoving || hasExceededTouchSlop(event)) {
200 if (!isMoving) {
201 isMoving = true;
202 bubble.onMoveStart();
203 }
204
205 ensureSprings();
206
207 moveXAnimation.animateToFinalPosition(clamp(eventX, minX, maxX));
208 moveYAnimation.animateToFinalPosition(clamp(eventY, minY, maxY));
209 }
210
211 velocityTracker.addMovement(event);
212 break;
213 case MotionEvent.ACTION_UP:
214 if (isMoving) {
215 ViewConfiguration viewConfiguration = ViewConfiguration.get(context);
216 velocityTracker.computeCurrentVelocity(
217 1000, viewConfiguration.getScaledMaximumFlingVelocity());
218 float xVelocity = velocityTracker.getXVelocity();
219 float yVelocity = velocityTracker.getYVelocity();
220 boolean isFling = isFling(xVelocity, yVelocity);
221
222 if (isFling) {
223 Point target =
224 findTarget(
225 xVelocity,
226 yVelocity,
227 (int) xProperty.getValue(bubble.getWindowParams()),
228 (int) yProperty.getValue(bubble.getWindowParams()));
229
230 moveXAnimation.animateToFinalPosition(target.x);
231 moveYAnimation.animateToFinalPosition(target.y);
232 } else {
233 snapX();
234 }
235 isMoving = false;
236 bubble.onMoveFinish();
237 } else {
238 v.performClick();
239 if (clickable) {
240 bubble.primaryButtonClick();
241 }
242 }
243 break;
244 default: // fall out
245 }
246 return true;
247 }
248
249 private void ensureSprings() {
250 if (moveXAnimation == null) {
251 moveXAnimation = new SpringAnimation(bubble.getWindowParams(), xProperty);
252 moveXAnimation.setSpring(new SpringForce());
253 moveXAnimation.getSpring().setDampingRatio(SpringForce.DAMPING_RATIO_NO_BOUNCY);
yueg81a77ff2017-12-05 10:29:03 -0800254 // Moving when expanded makes expanded view INVISIBLE, and the whole view is not at the
255 // boundary. It's time to create a viewHolder.
256 moveXAnimation.addEndListener(
257 (animation, canceled, value, velocity) -> {
258 if (!isMoving && bubble.getDrawerVisibility() == View.INVISIBLE) {
259 bubble.replaceViewHolder();
260 }
261 });
Eric Erfanian938468d2017-10-24 14:05:52 -0700262 }
263
264 if (moveYAnimation == null) {
265 moveYAnimation = new SpringAnimation(bubble.getWindowParams(), yProperty);
266 moveYAnimation.setSpring(new SpringForce());
267 moveYAnimation.getSpring().setDampingRatio(SpringForce.DAMPING_RATIO_NO_BOUNCY);
268 }
269 }
270
271 private Point findTarget(float xVelocity, float yVelocity, int startX, int startY) {
272 if (scroller == null) {
273 scroller = new Scroller(context);
274 scroller.setFriction(ViewConfiguration.getScrollFriction() * SCROLL_FRICTION_MULTIPLIER);
275 }
276
277 // Find where a fling would end vertically
278 scroller.fling(startX, startY, (int) xVelocity, (int) yVelocity, minX, maxX, minY, maxY);
279 int targetY = scroller.getFinalY();
280 scroller.abortAnimation();
281
282 // If the x component of the velocity is above the minimum fling velocity, use velocity to
283 // determine edge. Otherwise use its starting position
284 boolean pullRight = isFling(xVelocity, 0) ? xVelocity > 0 : isOnRightHalf(startX);
285 return new Point(pullRight ? maxX : minX, targetY);
286 }
287
288 private boolean isFling(float xVelocity, float yVelocity) {
289 int minFlingVelocity =
290 ViewConfiguration.get(context).getScaledMinimumFlingVelocity() * MIN_FLING_VELOCITY_FACTOR;
291 return getMagnitudeSquared(xVelocity, yVelocity) > minFlingVelocity * minFlingVelocity;
292 }
293
294 private boolean isOnRightHalf(float currentX) {
295 return currentX > (minX + maxX) / 2;
296 }
297
298 private void snapX() {
299 // Check if x value is closer to min or max
300 boolean pullRight = isOnRightHalf(xProperty.getValue(bubble.getWindowParams()));
301 moveXAnimation.animateToFinalPosition(pullRight ? maxX : minX);
302 }
303
304 private boolean relativeToRight(LayoutParams windowParams) {
305 return (windowParams.gravity & Gravity.RIGHT) == Gravity.RIGHT;
306 }
307
308 private boolean hasExceededTouchSlop(MotionEvent event) {
309 return getMagnitudeSquared(event.getRawX() - firstX, event.getRawY() - firstY)
310 > touchSlopSquared;
311 }
312
313 private float getMagnitudeSquared(float deltaX, float deltaY) {
314 return deltaX * deltaX + deltaY * deltaY;
315 }
316}