TaskStackView.java revision 9f9679d91ee5f067cd5dcbf4d780a1f5b522e4ba
1/* 2 * Copyright (C) 2014 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.systemui.recents.views; 18 19import android.animation.Animator; 20import android.animation.AnimatorListenerAdapter; 21import android.animation.AnimatorSet; 22import android.animation.ObjectAnimator; 23import android.animation.ValueAnimator; 24import android.app.Activity; 25import android.content.Context; 26import android.graphics.Canvas; 27import android.graphics.Rect; 28import android.graphics.Region; 29import android.util.Pair; 30import android.view.LayoutInflater; 31import android.view.MotionEvent; 32import android.view.VelocityTracker; 33import android.view.View; 34import android.view.ViewConfiguration; 35import android.view.ViewParent; 36import android.widget.FrameLayout; 37import android.widget.OverScroller; 38import com.android.systemui.R; 39import com.android.systemui.recents.BakedBezierInterpolator; 40import com.android.systemui.recents.Console; 41import com.android.systemui.recents.Constants; 42import com.android.systemui.recents.RecentsConfiguration; 43import com.android.systemui.recents.RecentsTaskLoader; 44import com.android.systemui.recents.Utilities; 45import com.android.systemui.recents.model.Task; 46import com.android.systemui.recents.model.TaskStack; 47 48import java.util.ArrayList; 49import java.util.HashMap; 50 51 52/* The visual representation of a task stack view */ 53public class TaskStackView extends FrameLayout implements TaskStack.TaskStackCallbacks, 54 TaskView.TaskViewCallbacks, ViewPool.ViewPoolConsumer<TaskView, Task>, 55 View.OnClickListener, View.OnLongClickListener { 56 57 /** The TaskView callbacks */ 58 interface TaskStackViewCallbacks { 59 public void onTaskLaunched(TaskStackView stackView, TaskView tv, TaskStack stack, Task t); 60 public void onTaskAppInfoLaunched(Task t); 61 } 62 63 TaskStack mStack; 64 TaskStackViewTouchHandler mTouchHandler; 65 TaskStackViewCallbacks mCb; 66 ViewPool<TaskView, Task> mViewPool; 67 68 // The various rects that define the stack view 69 Rect mRect = new Rect(); 70 Rect mStackRect = new Rect(); 71 Rect mStackRectSansPeek = new Rect(); 72 Rect mTaskRect = new Rect(); 73 74 // The virtual stack scroll that we use for the card layout 75 int mStackScroll; 76 int mMinScroll; 77 int mMaxScroll; 78 int mStashedScroll; 79 int mLastInfoPaneStackScroll; 80 OverScroller mScroller; 81 ObjectAnimator mScrollAnimator; 82 83 // Optimizations 84 int mHwLayersRefCount; 85 int mStackViewsAnimationDuration; 86 boolean mStackViewsDirty = true; 87 boolean mAwaitingFirstLayout = true; 88 int[] mTmpVisibleRange = new int[2]; 89 Rect mTmpRect = new Rect(); 90 Rect mTmpRect2 = new Rect(); 91 LayoutInflater mInflater; 92 93 public TaskStackView(Context context, TaskStack stack) { 94 super(context); 95 mStack = stack; 96 mStack.setCallbacks(this); 97 mScroller = new OverScroller(context); 98 mTouchHandler = new TaskStackViewTouchHandler(context, this); 99 mViewPool = new ViewPool<TaskView, Task>(context, this); 100 mInflater = LayoutInflater.from(context); 101 } 102 103 /** Sets the callbacks */ 104 void setCallbacks(TaskStackViewCallbacks cb) { 105 mCb = cb; 106 } 107 108 /** Requests that the views be synchronized with the model */ 109 void requestSynchronizeStackViewsWithModel() { 110 requestSynchronizeStackViewsWithModel(0); 111 } 112 void requestSynchronizeStackViewsWithModel(int duration) { 113 Console.log(Constants.DebugFlags.TaskStack.SynchronizeViewsWithModel, 114 "[TaskStackView|requestSynchronize]", "" + duration + "ms", Console.AnsiYellow); 115 if (!mStackViewsDirty) { 116 invalidate(); 117 } 118 if (mAwaitingFirstLayout) { 119 // Skip the animation if we are awaiting first layout 120 mStackViewsAnimationDuration = 0; 121 } else { 122 mStackViewsAnimationDuration = Math.max(mStackViewsAnimationDuration, duration); 123 } 124 mStackViewsDirty = true; 125 } 126 127 // XXX: Optimization: Use a mapping of Task -> View 128 private TaskView getChildViewForTask(Task t) { 129 int childCount = getChildCount(); 130 for (int i = 0; i < childCount; i++) { 131 TaskView tv = (TaskView) getChildAt(i); 132 if (tv.getTask() == t) { 133 return tv; 134 } 135 } 136 return null; 137 } 138 139 /** Update/get the transform */ 140 public TaskViewTransform getStackTransform(int indexInStack, int stackScroll) { 141 TaskViewTransform transform = new TaskViewTransform(); 142 143 // Return early if we have an invalid index 144 if (indexInStack < 0) return transform; 145 146 // Map the items to an continuous position relative to the specified scroll 147 int numPeekCards = Constants.Values.TaskStackView.StackPeekNumCards; 148 float overlapHeight = Constants.Values.TaskStackView.StackOverlapPct * mTaskRect.height(); 149 float peekHeight = Constants.Values.TaskStackView.StackPeekHeightPct * mStackRect.height(); 150 float t = ((indexInStack * overlapHeight) - stackScroll) / overlapHeight; 151 float boundedT = Math.max(t, -(numPeekCards + 1)); 152 153 // Set the scale relative to its position 154 float minScale = Constants.Values.TaskStackView.StackPeekMinScale; 155 float scaleRange = 1f - minScale; 156 float scaleInc = scaleRange / numPeekCards; 157 float scale = Math.max(minScale, Math.min(1f, 1f + (boundedT * scaleInc))); 158 float scaleYOffset = ((1f - scale) * mTaskRect.height()) / 2; 159 transform.scale = scale; 160 161 // Set the translation 162 if (boundedT < 0f) { 163 transform.translationY = (int) ((Math.max(-numPeekCards, boundedT) / 164 numPeekCards) * peekHeight - scaleYOffset); 165 } else { 166 transform.translationY = (int) (boundedT * overlapHeight - scaleYOffset); 167 } 168 169 // Update the rect and visibility 170 transform.rect.set(mTaskRect); 171 if (t < -(numPeekCards + 1)) { 172 transform.visible = false; 173 } else { 174 transform.rect.offset(0, transform.translationY); 175 Utilities.scaleRectAboutCenter(transform.rect, transform.scale); 176 transform.visible = Rect.intersects(mRect, transform.rect); 177 } 178 transform.t = t; 179 return transform; 180 } 181 182 /** 183 * Gets the stack transforms of a list of tasks, and returns the visible range of tasks. 184 */ 185 private ArrayList<TaskViewTransform> getStackTransforms(ArrayList<Task> tasks, 186 int stackScroll, 187 int[] visibleRangeOut, 188 boolean boundTranslationsToRect) { 189 // XXX: Optimization: Use binary search to find the visible range 190 191 ArrayList<TaskViewTransform> taskTransforms = new ArrayList<TaskViewTransform>(); 192 int taskCount = tasks.size(); 193 int firstVisibleIndex = -1; 194 int lastVisibleIndex = -1; 195 for (int i = 0; i < taskCount; i++) { 196 TaskViewTransform transform = getStackTransform(i, stackScroll); 197 taskTransforms.add(transform); 198 if (transform.visible) { 199 if (firstVisibleIndex < 0) { 200 firstVisibleIndex = i; 201 } 202 lastVisibleIndex = i; 203 } 204 205 if (boundTranslationsToRect) { 206 transform.translationY = Math.min(transform.translationY, mRect.bottom); 207 } 208 } 209 if (visibleRangeOut != null) { 210 visibleRangeOut[0] = firstVisibleIndex; 211 visibleRangeOut[1] = lastVisibleIndex; 212 } 213 return taskTransforms; 214 } 215 216 /** Synchronizes the views with the model */ 217 void synchronizeStackViewsWithModel() { 218 Console.log(Constants.DebugFlags.TaskStack.SynchronizeViewsWithModel, 219 "[TaskStackView|synchronizeViewsWithModel]", 220 "mStackViewsDirty: " + mStackViewsDirty, Console.AnsiYellow); 221 if (mStackViewsDirty) { 222 // XXX: Consider using TaskViewTransform pool to prevent allocations 223 // XXX: Iterate children views, update transforms and remove all that are not visible 224 // For all remaining tasks, update transforms and if visible add the view 225 226 // Get all the task transforms 227 int[] visibleRange = mTmpVisibleRange; 228 int stackScroll = getStackScroll(); 229 ArrayList<Task> tasks = mStack.getTasks(); 230 ArrayList<TaskViewTransform> taskTransforms = getStackTransforms(tasks, stackScroll, 231 visibleRange, false); 232 233 // Update the visible state of all the tasks 234 int taskCount = tasks.size(); 235 for (int i = 0; i < taskCount; i++) { 236 Task task = tasks.get(i); 237 TaskViewTransform transform = taskTransforms.get(i); 238 TaskView tv = getChildViewForTask(task); 239 240 if (transform.visible) { 241 if (tv == null) { 242 tv = mViewPool.pickUpViewFromPool(task, task); 243 // When we are picking up a new view from the view pool, prepare it for any 244 // following animation by putting it in a reasonable place 245 if (mStackViewsAnimationDuration > 0 && i != 0) { 246 int fromIndex = (transform.t < 0) ? (visibleRange[0] - 1) : 247 (visibleRange[1] + 1); 248 tv.updateViewPropertiesToTaskTransform(null, 249 getStackTransform(fromIndex, stackScroll), 0); 250 } 251 } 252 } else { 253 if (tv != null) { 254 mViewPool.returnViewToPool(tv); 255 } 256 } 257 } 258 259 // Update all the remaining view children 260 // NOTE: We have to iterate in reverse where because we are removing views directly 261 int childCount = getChildCount(); 262 for (int i = childCount - 1; i >= 0; i--) { 263 TaskView tv = (TaskView) getChildAt(i); 264 Task task = tv.getTask(); 265 int taskIndex = mStack.indexOfTask(task); 266 if (taskIndex < 0 || !taskTransforms.get(taskIndex).visible) { 267 mViewPool.returnViewToPool(tv); 268 } else { 269 tv.updateViewPropertiesToTaskTransform(null, taskTransforms.get(taskIndex), 270 mStackViewsAnimationDuration); 271 } 272 } 273 274 Console.log(Constants.DebugFlags.TaskStack.SynchronizeViewsWithModel, 275 " [TaskStackView|viewChildren]", "" + getChildCount()); 276 277 mStackViewsAnimationDuration = 0; 278 mStackViewsDirty = false; 279 } 280 } 281 282 /** Sets the current stack scroll */ 283 public void setStackScroll(int value) { 284 mStackScroll = value; 285 requestSynchronizeStackViewsWithModel(); 286 287 // Close any open info panes if the user has scrolled away from them 288 boolean isAnimatingScroll = (mScrollAnimator != null && mScrollAnimator.isRunning()); 289 if (mLastInfoPaneStackScroll > -1 && !isAnimatingScroll) { 290 RecentsConfiguration config = RecentsConfiguration.getInstance(); 291 if (Math.abs(mStackScroll - mLastInfoPaneStackScroll) > 292 config.taskStackScrollDismissInfoPaneDistance) { 293 // Close any open info panes 294 closeOpenInfoPanes(); 295 } 296 } 297 } 298 /** Sets the current stack scroll without synchronizing the stack view with the model */ 299 public void setStackScrollRaw(int value) { 300 mStackScroll = value; 301 } 302 303 /** Gets the current stack scroll */ 304 public int getStackScroll() { 305 return mStackScroll; 306 } 307 308 /** Animates the stack scroll into bounds */ 309 ObjectAnimator animateBoundScroll() { 310 int curScroll = getStackScroll(); 311 int newScroll = Math.max(mMinScroll, Math.min(mMaxScroll, curScroll)); 312 if (newScroll != curScroll) { 313 // Enable hw layers on the stack 314 addHwLayersRefCount("animateBoundScroll"); 315 316 // Start a new scroll animation 317 animateScroll(curScroll, newScroll, new Runnable() { 318 @Override 319 public void run() { 320 // Disable hw layers on the stack 321 decHwLayersRefCount("animateBoundScroll"); 322 } 323 }); 324 } 325 return mScrollAnimator; 326 } 327 328 /** Animates the stack scroll */ 329 void animateScroll(int curScroll, int newScroll, final Runnable postRunnable) { 330 // Abort any current animations 331 abortScroller(); 332 abortBoundScrollAnimation(); 333 334 mScrollAnimator = ObjectAnimator.ofInt(this, "stackScroll", curScroll, newScroll); 335 mScrollAnimator.setDuration(Utilities.calculateTranslationAnimationDuration(newScroll - 336 curScroll, 250)); 337 mScrollAnimator.setInterpolator(BakedBezierInterpolator.INSTANCE); 338 mScrollAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { 339 @Override 340 public void onAnimationUpdate(ValueAnimator animation) { 341 setStackScroll((Integer) animation.getAnimatedValue()); 342 } 343 }); 344 mScrollAnimator.addListener(new AnimatorListenerAdapter() { 345 @Override 346 public void onAnimationEnd(Animator animation) { 347 if (postRunnable != null) { 348 postRunnable.run(); 349 } 350 mScrollAnimator.removeAllListeners(); 351 } 352 }); 353 mScrollAnimator.start(); 354 } 355 356 /** Aborts any current stack scrolls */ 357 void abortBoundScrollAnimation() { 358 if (mScrollAnimator != null) { 359 mScrollAnimator.cancel(); 360 } 361 } 362 363 /** Aborts the scroller and any current fling */ 364 void abortScroller() { 365 if (!mScroller.isFinished()) { 366 // Abort the scroller 367 mScroller.abortAnimation(); 368 // And disable hw layers on the stack 369 decHwLayersRefCount("flingScroll"); 370 } 371 } 372 373 /** Bounds the current scroll if necessary */ 374 public boolean boundScroll() { 375 int curScroll = getStackScroll(); 376 int newScroll = Math.max(mMinScroll, Math.min(mMaxScroll, curScroll)); 377 if (newScroll != curScroll) { 378 setStackScroll(newScroll); 379 return true; 380 } 381 return false; 382 } 383 384 /** 385 * Bounds the current scroll if necessary, but does not synchronize the stack view with the 386 * model. 387 */ 388 public boolean boundScrollRaw() { 389 int curScroll = getStackScroll(); 390 int newScroll = Math.max(mMinScroll, Math.min(mMaxScroll, curScroll)); 391 if (newScroll != curScroll) { 392 setStackScrollRaw(newScroll); 393 return true; 394 } 395 return false; 396 } 397 398 /** Returns whether the current scroll is out of bounds */ 399 boolean isScrollOutOfBounds() { 400 return (getStackScroll() < 0) || (getStackScroll() > mMaxScroll); 401 } 402 403 /** Updates the min and max virtual scroll bounds */ 404 void updateMinMaxScroll(boolean boundScrollToNewMinMax) { 405 // Compute the min and max scroll values 406 int numTasks = Math.max(1, mStack.getTaskCount()); 407 int taskHeight = mTaskRect.height(); 408 int stackHeight = mStackRectSansPeek.height(); 409 int maxScrollHeight = taskHeight + (int) ((numTasks - 1) * 410 Constants.Values.TaskStackView.StackOverlapPct * taskHeight); 411 412 if (numTasks <= 1) { 413 // If there is only one task, then center the task in the stack rect (sans peek) 414 mMinScroll = mMaxScroll = -(stackHeight - taskHeight) / 2; 415 } else { 416 mMinScroll = Math.min(stackHeight, maxScrollHeight) - stackHeight; 417 mMaxScroll = maxScrollHeight - stackHeight; 418 } 419 420 // Debug logging 421 if (Constants.DebugFlags.UI.MeasureAndLayout) { 422 Console.log(" [TaskStack|minScroll] " + mMinScroll); 423 Console.log(" [TaskStack|maxScroll] " + mMaxScroll); 424 } 425 426 if (boundScrollToNewMinMax) { 427 boundScroll(); 428 } 429 } 430 431 /** Closes any open info panes. */ 432 boolean closeOpenInfoPanes() { 433 if (!Constants.DebugFlags.App.EnableInfoPane) return false; 434 435 int childCount = getChildCount(); 436 for (int i = 0; i < childCount; i++) { 437 TaskView tv = (TaskView) getChildAt(i); 438 if (tv.isInfoPaneVisible()) { 439 tv.hideInfoPane(); 440 return true; 441 } 442 } 443 return false; 444 } 445 446 /** Enables the hw layers and increments the hw layer requirement ref count */ 447 void addHwLayersRefCount(String reason) { 448 Console.log(Constants.DebugFlags.UI.HwLayers, 449 "[TaskStackView|addHwLayersRefCount] refCount: " + 450 mHwLayersRefCount + "->" + (mHwLayersRefCount + 1) + " " + reason); 451 if (mHwLayersRefCount == 0) { 452 // Enable hw layers on each of the children 453 int childCount = getChildCount(); 454 for (int i = 0; i < childCount; i++) { 455 TaskView tv = (TaskView) getChildAt(i); 456 tv.enableHwLayers(); 457 } 458 } 459 mHwLayersRefCount++; 460 } 461 462 /** Decrements the hw layer requirement ref count and disables the hw layers when we don't 463 need them anymore. */ 464 void decHwLayersRefCount(String reason) { 465 Console.log(Constants.DebugFlags.UI.HwLayers, 466 "[TaskStackView|decHwLayersRefCount] refCount: " + 467 mHwLayersRefCount + "->" + (mHwLayersRefCount - 1) + " " + reason); 468 mHwLayersRefCount--; 469 if (mHwLayersRefCount == 0) { 470 // Disable hw layers on each of the children 471 int childCount = getChildCount(); 472 for (int i = 0; i < childCount; i++) { 473 TaskView tv = (TaskView) getChildAt(i); 474 tv.disableHwLayers(); 475 } 476 } else if (mHwLayersRefCount < 0) { 477 new Throwable("Invalid hw layers ref count").printStackTrace(); 478 Console.logError(getContext(), "Invalid HW layers ref count"); 479 } 480 } 481 482 @Override 483 public void computeScroll() { 484 if (mScroller.computeScrollOffset()) { 485 setStackScroll(mScroller.getCurrY()); 486 invalidate(); 487 488 // If we just finished scrolling, then disable the hw layers 489 if (mScroller.isFinished()) { 490 decHwLayersRefCount("finishedFlingScroll"); 491 } 492 } 493 } 494 495 @Override 496 public boolean onInterceptTouchEvent(MotionEvent ev) { 497 return mTouchHandler.onInterceptTouchEvent(ev); 498 } 499 500 @Override 501 public boolean onTouchEvent(MotionEvent ev) { 502 return mTouchHandler.onTouchEvent(ev); 503 } 504 505 @Override 506 public void dispatchDraw(Canvas canvas) { 507 Console.log(Constants.DebugFlags.UI.Draw, "[TaskStackView|dispatchDraw]", "", 508 Console.AnsiPurple); 509 synchronizeStackViewsWithModel(); 510 super.dispatchDraw(canvas); 511 } 512 513 @Override 514 protected boolean drawChild(Canvas canvas, View child, long drawingTime) { 515 if (Constants.DebugFlags.App.EnableTaskStackClipping) { 516 TaskView tv = (TaskView) child; 517 TaskView nextTv = null; 518 int curIndex = indexOfChild(tv); 519 if ((curIndex > -1) && (curIndex < (getChildCount() - 1))) { 520 // Clip against the next view (if we aren't animating its alpha) 521 nextTv = (TaskView) getChildAt(curIndex + 1); 522 if (nextTv.getAlpha() == 1f) { 523 Rect curRect = tv.getClippingRect(mTmpRect); 524 Rect nextRect = nextTv.getClippingRect(mTmpRect2); 525 RecentsConfiguration config = RecentsConfiguration.getInstance(); 526 // The hit rects are relative to the task view, which needs to be offset by the 527 // system bar height 528 curRect.offset(0, config.systemInsets.top); 529 nextRect.offset(0, config.systemInsets.top); 530 // Compute the clip region 531 Region clipRegion = new Region(); 532 clipRegion.op(curRect, Region.Op.UNION); 533 clipRegion.op(nextRect, Region.Op.DIFFERENCE); 534 // Clip the canvas 535 int saveCount = canvas.save(Canvas.CLIP_SAVE_FLAG); 536 canvas.clipRegion(clipRegion); 537 boolean invalidate = super.drawChild(canvas, child, drawingTime); 538 canvas.restoreToCount(saveCount); 539 return invalidate; 540 } 541 } 542 } 543 return super.drawChild(canvas, child, drawingTime); 544 } 545 546 /** Computes the stack and task rects */ 547 public void computeRects(int width, int height, int insetBottom) { 548 // Note: We let the stack view be the full height because we want the cards to go under the 549 // navigation bar if possible. However, the stack rects which we use to calculate 550 // max scroll, etc. need to take the nav bar into account 551 552 // Compute the stack rects 553 mRect.set(0, 0, width, height); 554 mStackRect.set(mRect); 555 mStackRect.bottom -= insetBottom; 556 557 int smallestDimension = Math.min(width, height); 558 int padding = (int) (Constants.Values.TaskStackView.StackPaddingPct * smallestDimension / 2f); 559 mStackRect.inset(padding, padding); 560 mStackRectSansPeek.set(mStackRect); 561 mStackRectSansPeek.top += Constants.Values.TaskStackView.StackPeekHeightPct * mStackRect.height(); 562 563 // Compute the task rect 564 int minHeight = (int) (mStackRect.height() - 565 (Constants.Values.TaskStackView.StackPeekHeightPct * mStackRect.height())); 566 int size = Math.min(minHeight, Math.min(mStackRect.width(), mStackRect.height())); 567 mTaskRect.set(mStackRect.left, mStackRectSansPeek.top, 568 mStackRect.right, mStackRectSansPeek.top + size); 569 570 // Update the scroll bounds 571 updateMinMaxScroll(false); 572 } 573 574 @Override 575 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 576 int width = MeasureSpec.getSize(widthMeasureSpec); 577 int height = MeasureSpec.getSize(heightMeasureSpec); 578 Console.log(Constants.DebugFlags.UI.MeasureAndLayout, "[TaskStackView|measure]", 579 "width: " + width + " height: " + height + 580 " awaitingFirstLayout: " + mAwaitingFirstLayout, Console.AnsiGreen); 581 582 // Compute our stack/task rects 583 RecentsConfiguration config = RecentsConfiguration.getInstance(); 584 computeRects(width, height, config.systemInsets.bottom); 585 586 // Debug logging 587 if (Constants.DebugFlags.UI.MeasureAndLayout) { 588 Console.log(" [TaskStack|fullRect] " + mRect); 589 Console.log(" [TaskStack|stackRect] " + mStackRect); 590 Console.log(" [TaskStack|stackRectSansPeek] " + mStackRectSansPeek); 591 Console.log(" [TaskStack|taskRect] " + mTaskRect); 592 } 593 594 // If this is the first layout, then scroll to the front of the stack and synchronize the 595 // stack views immediately 596 if (mAwaitingFirstLayout) { 597 setStackScroll(mMaxScroll); 598 requestSynchronizeStackViewsWithModel(); 599 synchronizeStackViewsWithModel(); 600 601 // Animate the task bar of the first task view 602 if (config.launchedWithThumbnailAnimation && 603 Constants.Values.TaskView.AnimateFrontTaskBarOnEnterRecents) { 604 TaskView tv = (TaskView) getChildAt(getChildCount() - 1); 605 if (tv != null) { 606 tv.animateOnEnterRecents(); 607 } 608 } 609 } 610 611 // Measure each of the children 612 int childCount = getChildCount(); 613 for (int i = 0; i < childCount; i++) { 614 TaskView t = (TaskView) getChildAt(i); 615 t.measure(MeasureSpec.makeMeasureSpec(mTaskRect.width(), MeasureSpec.EXACTLY), 616 MeasureSpec.makeMeasureSpec(mTaskRect.height(), MeasureSpec.EXACTLY)); 617 } 618 619 setMeasuredDimension(width, height); 620 } 621 622 @Override 623 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 624 Console.log(Constants.DebugFlags.UI.MeasureAndLayout, "[TaskStackView|layout]", 625 "" + new Rect(left, top, right, bottom), Console.AnsiGreen); 626 627 // Debug logging 628 if (Constants.DebugFlags.UI.MeasureAndLayout) { 629 Console.log(" [TaskStack|fullRect] " + mRect); 630 Console.log(" [TaskStack|stackRect] " + mStackRect); 631 Console.log(" [TaskStack|stackRectSansPeek] " + mStackRectSansPeek); 632 Console.log(" [TaskStack|taskRect] " + mTaskRect); 633 } 634 635 // Layout each of the children 636 int childCount = getChildCount(); 637 for (int i = 0; i < childCount; i++) { 638 TaskView t = (TaskView) getChildAt(i); 639 t.layout(mTaskRect.left, mStackRectSansPeek.top, 640 mTaskRect.right, mStackRectSansPeek.top + mTaskRect.height()); 641 } 642 643 if (mAwaitingFirstLayout) { 644 mAwaitingFirstLayout = false; 645 } 646 } 647 648 @Override 649 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 650 super.onScrollChanged(l, t, oldl, oldt); 651 requestSynchronizeStackViewsWithModel(); 652 } 653 654 public boolean isTransformedTouchPointInView(float x, float y, View child) { 655 return isTransformedTouchPointInView(x, y, child, null); 656 } 657 658 /**** TaskStackCallbacks Implementation ****/ 659 660 @Override 661 public void onStackTaskAdded(TaskStack stack, Task t) { 662 requestSynchronizeStackViewsWithModel(); 663 } 664 665 @Override 666 public void onStackTaskRemoved(TaskStack stack, Task t) { 667 // Remove the view associated with this task, we can't rely on updateTransforms 668 // to work here because the task is no longer in the list 669 int childCount = getChildCount(); 670 for (int i = childCount - 1; i >= 0; i--) { 671 TaskView tv = (TaskView) getChildAt(i); 672 if (tv.getTask() == t) { 673 mViewPool.returnViewToPool(tv); 674 break; 675 } 676 } 677 678 updateMinMaxScroll(true); 679 int movement = (int) (Constants.Values.TaskStackView.StackOverlapPct * mTaskRect.height()); 680 requestSynchronizeStackViewsWithModel(Utilities.calculateTranslationAnimationDuration(movement)); 681 } 682 683 /** 684 * Creates the animations for all the children views that need to be removed or to move views 685 * to their un/filtered position when we are un/filtering a stack, and returns the duration 686 * for these animations. 687 */ 688 int getExitTransformsForFilterAnimation(ArrayList<Task> curTasks, 689 ArrayList<TaskViewTransform> curTaskTransforms, 690 ArrayList<Task> tasks, ArrayList<TaskViewTransform> taskTransforms, 691 HashMap<TaskView, Pair<Integer, TaskViewTransform>> childViewTransformsOut, 692 ArrayList<TaskView> childrenToRemoveOut, 693 RecentsConfiguration config) { 694 // Animate all of the existing views out of view (if they are not in the visible range in 695 // the new stack) or to their final positions in the new stack 696 int movement = 0; 697 int childCount = getChildCount(); 698 for (int i = 0; i < childCount; i++) { 699 TaskView tv = (TaskView) getChildAt(i); 700 Task task = tv.getTask(); 701 int taskIndex = tasks.indexOf(task); 702 TaskViewTransform toTransform; 703 704 // If the view is no longer visible, then we should just animate it out 705 boolean willBeInvisible = taskIndex < 0 || !taskTransforms.get(taskIndex).visible; 706 if (willBeInvisible) { 707 if (taskIndex < 0) { 708 toTransform = curTaskTransforms.get(curTasks.indexOf(task)); 709 } else { 710 toTransform = new TaskViewTransform(taskTransforms.get(taskIndex)); 711 } 712 tv.prepareTaskTransformForFilterTaskVisible(toTransform); 713 childrenToRemoveOut.add(tv); 714 } else { 715 toTransform = taskTransforms.get(taskIndex); 716 // Use the movement of the visible views to calculate the duration of the animation 717 movement = Math.max(movement, Math.abs(toTransform.translationY - 718 (int) tv.getTranslationY())); 719 } 720 childViewTransformsOut.put(tv, new Pair(0, toTransform)); 721 } 722 return Utilities.calculateTranslationAnimationDuration(movement, 723 config.filteringCurrentViewsMinAnimDuration); 724 } 725 726 /** 727 * Creates the animations for all the children views that need to be animated in when we are 728 * un/filtering a stack, and returns the duration for these animations. 729 */ 730 int getEnterTransformsForFilterAnimation(ArrayList<Task> tasks, 731 ArrayList<TaskViewTransform> taskTransforms, 732 HashMap<TaskView, Pair<Integer, TaskViewTransform>> childViewTransformsOut, 733 RecentsConfiguration config) { 734 int offset = 0; 735 int movement = 0; 736 int taskCount = tasks.size(); 737 for (int i = taskCount - 1; i >= 0; i--) { 738 Task task = tasks.get(i); 739 TaskViewTransform toTransform = taskTransforms.get(i); 740 if (toTransform.visible) { 741 TaskView tv = getChildViewForTask(task); 742 if (tv == null) { 743 // For views that are not already visible, animate them in 744 tv = mViewPool.pickUpViewFromPool(task, task); 745 746 // Compose a new transform to fade and slide the new task in 747 TaskViewTransform fromTransform = new TaskViewTransform(toTransform); 748 tv.prepareTaskTransformForFilterTaskHidden(fromTransform); 749 tv.updateViewPropertiesToTaskTransform(null, fromTransform, 0); 750 751 int startDelay = offset * 752 Constants.Values.TaskStackView.FilterStartDelay; 753 childViewTransformsOut.put(tv, new Pair(startDelay, toTransform)); 754 755 // Use the movement of the new views to calculate the duration of the animation 756 movement = Math.max(movement, 757 Math.abs(toTransform.translationY - fromTransform.translationY)); 758 offset++; 759 } 760 } 761 } 762 return Utilities.calculateTranslationAnimationDuration(movement, 763 config.filteringNewViewsMinAnimDuration); 764 } 765 766 /** Orchestrates the animations of the current child views and any new views. */ 767 void doFilteringAnimation(ArrayList<Task> curTasks, 768 ArrayList<TaskViewTransform> curTaskTransforms, 769 final ArrayList<Task> tasks, 770 final ArrayList<TaskViewTransform> taskTransforms) { 771 final RecentsConfiguration config = RecentsConfiguration.getInstance(); 772 773 // Calculate the transforms to animate out all the existing views if they are not in the 774 // new visible range (or to their final positions in the stack if they are) 775 final ArrayList<TaskView> childrenToRemove = new ArrayList<TaskView>(); 776 final HashMap<TaskView, Pair<Integer, TaskViewTransform>> childViewTransforms = 777 new HashMap<TaskView, Pair<Integer, TaskViewTransform>>(); 778 int duration = getExitTransformsForFilterAnimation(curTasks, curTaskTransforms, tasks, 779 taskTransforms, childViewTransforms, childrenToRemove, config); 780 781 // If all the current views are in the visible range of the new stack, then don't wait for 782 // views to animate out and animate all the new views into their place 783 final boolean unifyNewViewAnimation = childrenToRemove.isEmpty(); 784 if (unifyNewViewAnimation) { 785 int inDuration = getEnterTransformsForFilterAnimation(tasks, taskTransforms, 786 childViewTransforms, config); 787 duration = Math.max(duration, inDuration); 788 } 789 790 // Animate all the views to their final transforms 791 for (final TaskView tv : childViewTransforms.keySet()) { 792 Pair<Integer, TaskViewTransform> t = childViewTransforms.get(tv); 793 tv.animate().cancel(); 794 tv.animate() 795 .setStartDelay(t.first) 796 .withEndAction(new Runnable() { 797 @Override 798 public void run() { 799 childViewTransforms.remove(tv); 800 if (childViewTransforms.isEmpty()) { 801 // Return all the removed children to the view pool 802 for (TaskView tv : childrenToRemove) { 803 mViewPool.returnViewToPool(tv); 804 } 805 806 if (!unifyNewViewAnimation) { 807 // For views that are not already visible, animate them in 808 childViewTransforms.clear(); 809 int duration = getEnterTransformsForFilterAnimation(tasks, 810 taskTransforms, childViewTransforms, config); 811 for (final TaskView tv : childViewTransforms.keySet()) { 812 Pair<Integer, TaskViewTransform> t = childViewTransforms.get(tv); 813 tv.animate().setStartDelay(t.first); 814 tv.updateViewPropertiesToTaskTransform(null, t.second, duration); 815 } 816 } 817 } 818 } 819 }); 820 tv.updateViewPropertiesToTaskTransform(null, t.second, duration); 821 } 822 } 823 824 @Override 825 public void onStackFiltered(TaskStack newStack, final ArrayList<Task> curTasks, 826 Task filteredTask) { 827 // Close any open info panes 828 closeOpenInfoPanes(); 829 830 // Stash the scroll and filtered task for us to restore to when we unfilter 831 mStashedScroll = getStackScroll(); 832 833 // Calculate the current task transforms 834 ArrayList<TaskViewTransform> curTaskTransforms = 835 getStackTransforms(curTasks, getStackScroll(), null, true); 836 837 // Scroll the item to the top of the stack (sans-peek) rect so that we can see it better 838 updateMinMaxScroll(false); 839 float overlapHeight = Constants.Values.TaskStackView.StackOverlapPct * mTaskRect.height(); 840 setStackScrollRaw((int) (newStack.indexOfTask(filteredTask) * overlapHeight)); 841 boundScrollRaw(); 842 843 // Compute the transforms of the items in the new stack after setting the new scroll 844 final ArrayList<Task> tasks = mStack.getTasks(); 845 final ArrayList<TaskViewTransform> taskTransforms = 846 getStackTransforms(mStack.getTasks(), getStackScroll(), null, true); 847 848 // Animate 849 doFilteringAnimation(curTasks, curTaskTransforms, tasks, taskTransforms); 850 } 851 852 @Override 853 public void onStackUnfiltered(TaskStack newStack, final ArrayList<Task> curTasks) { 854 // Close any open info panes 855 closeOpenInfoPanes(); 856 857 // Calculate the current task transforms 858 final ArrayList<TaskViewTransform> curTaskTransforms = 859 getStackTransforms(curTasks, getStackScroll(), null, true); 860 861 // Restore the stashed scroll 862 updateMinMaxScroll(false); 863 setStackScrollRaw(mStashedScroll); 864 boundScrollRaw(); 865 866 // Compute the transforms of the items in the new stack after restoring the stashed scroll 867 final ArrayList<Task> tasks = mStack.getTasks(); 868 final ArrayList<TaskViewTransform> taskTransforms = 869 getStackTransforms(tasks, getStackScroll(), null, true); 870 871 // Animate 872 doFilteringAnimation(curTasks, curTaskTransforms, tasks, taskTransforms); 873 874 // Clear the saved vars 875 mStashedScroll = 0; 876 } 877 878 /**** ViewPoolConsumer Implementation ****/ 879 880 @Override 881 public TaskView createView(Context context) { 882 Console.log(Constants.DebugFlags.ViewPool.PoolCallbacks, "[TaskStackView|createPoolView]"); 883 return (TaskView) mInflater.inflate(R.layout.recents_task_view, this, false); 884 } 885 886 @Override 887 public void prepareViewToEnterPool(TaskView tv) { 888 Task task = tv.getTask(); 889 tv.resetViewProperties(); 890 Console.log(Constants.DebugFlags.ViewPool.PoolCallbacks, "[TaskStackView|returnToPool]", 891 tv.getTask() + " tv: " + tv); 892 893 // Report that this tasks's data is no longer being used 894 RecentsTaskLoader loader = RecentsTaskLoader.getInstance(); 895 loader.unloadTaskData(task); 896 897 // Detach the view from the hierarchy 898 detachViewFromParent(tv); 899 900 // Disable hw layers on this view 901 tv.disableHwLayers(); 902 } 903 904 @Override 905 public void prepareViewToLeavePool(TaskView tv, Task prepareData, boolean isNewView) { 906 Console.log(Constants.DebugFlags.ViewPool.PoolCallbacks, "[TaskStackView|leavePool]", 907 "isNewView: " + isNewView); 908 909 // Setup and attach the view to the window 910 Task task = prepareData; 911 // We try and rebind the task (this MUST be done before the task filled) 912 tv.onTaskBound(task); 913 // Request that this tasks's data be filled 914 RecentsTaskLoader loader = RecentsTaskLoader.getInstance(); 915 loader.loadTaskData(task); 916 917 // Find the index where this task should be placed in the children 918 int insertIndex = -1; 919 int childCount = getChildCount(); 920 for (int i = 0; i < childCount; i++) { 921 Task tvTask = ((TaskView) getChildAt(i)).getTask(); 922 if (mStack.containsTask(task) && (mStack.indexOfTask(task) < mStack.indexOfTask(tvTask))) { 923 insertIndex = i; 924 break; 925 } 926 } 927 928 // Add/attach the view to the hierarchy 929 Console.log(Constants.DebugFlags.ViewPool.PoolCallbacks, " [TaskStackView|insertIndex]", 930 "" + insertIndex); 931 if (isNewView) { 932 addView(tv, insertIndex); 933 934 // Set the callbacks and listeners for this new view 935 tv.setOnClickListener(this); 936 if (Constants.DebugFlags.App.EnableInfoPane) { 937 tv.setOnLongClickListener(this); 938 } 939 tv.setCallbacks(this); 940 } else { 941 attachViewToParent(tv, insertIndex, tv.getLayoutParams()); 942 } 943 944 // Enable hw layers on this view if hw layers are enabled on the stack 945 if (mHwLayersRefCount > 0) { 946 tv.enableHwLayers(); 947 } 948 } 949 950 @Override 951 public boolean hasPreferredData(TaskView tv, Task preferredData) { 952 return (tv.getTask() == preferredData); 953 } 954 955 /**** TaskViewCallbacks Implementation ****/ 956 957 @Override 958 public void onTaskIconClicked(TaskView tv) { 959 Console.log(Constants.DebugFlags.UI.ClickEvents, "[TaskStack|Clicked|Icon]", 960 tv.getTask() + " is currently filtered: " + mStack.hasFilteredTasks(), 961 Console.AnsiCyan); 962 if (Constants.DebugFlags.App.EnableTaskFiltering) { 963 if (mStack.hasFilteredTasks()) { 964 mStack.unfilterTasks(); 965 } else { 966 mStack.filterTasks(tv.getTask()); 967 } 968 } else { 969 Console.logError(getContext(), "Task Filtering TBD"); 970 } 971 } 972 973 @Override 974 public void onTaskInfoPanelShown(TaskView tv) { 975 // Do nothing 976 } 977 978 @Override 979 public void onTaskInfoPanelHidden(TaskView tv) { 980 // Unset the saved scroll 981 mLastInfoPaneStackScroll = -1; 982 } 983 984 @Override 985 public void onTaskAppInfoClicked(TaskView tv) { 986 if (mCb != null) { 987 mCb.onTaskAppInfoLaunched(tv.getTask()); 988 } 989 } 990 991 /**** View.OnClickListener Implementation ****/ 992 993 @Override 994 public void onClick(View v) { 995 TaskView tv = (TaskView) v; 996 Task task = tv.getTask(); 997 Console.log(Constants.DebugFlags.UI.ClickEvents, "[TaskStack|Clicked|Thumbnail]", 998 task + " cb: " + mCb); 999 1000 // Close any open info panes if the user taps on another task 1001 if (closeOpenInfoPanes()) { 1002 return; 1003 } 1004 1005 if (mCb != null) { 1006 mCb.onTaskLaunched(this, tv, mStack, task); 1007 } 1008 } 1009 1010 @Override 1011 public boolean onLongClick(View v) { 1012 if (!Constants.DebugFlags.App.EnableInfoPane) return false; 1013 1014 TaskView tv = (TaskView) v; 1015 1016 // Close any other task info panels if we launch another info pane 1017 closeOpenInfoPanes(); 1018 1019 // Scroll the task view so that it is maximally visible 1020 float overlapHeight = Constants.Values.TaskStackView.StackOverlapPct * mTaskRect.height(); 1021 int taskIndex = mStack.indexOfTask(tv.getTask()); 1022 int curScroll = getStackScroll(); 1023 int newScroll = (int) Math.max(mMinScroll, Math.min(mMaxScroll, taskIndex * overlapHeight)); 1024 TaskViewTransform transform = getStackTransform(taskIndex, curScroll); 1025 Rect nonOverlapRect = new Rect(transform.rect); 1026 if (taskIndex < (mStack.getTaskCount() - 1)) { 1027 nonOverlapRect.bottom = nonOverlapRect.top + (int) overlapHeight; 1028 } 1029 1030 // XXX: Use HW Layers 1031 if (transform.t < 0f) { 1032 animateScroll(curScroll, newScroll, null); 1033 } else if (nonOverlapRect.bottom > mStackRectSansPeek.bottom) { 1034 // Check if we are out of bounds, if so, just scroll it in such that the bottom of the 1035 // task view is visible 1036 newScroll = curScroll - (mStackRectSansPeek.bottom - nonOverlapRect.bottom); 1037 animateScroll(curScroll, newScroll, null); 1038 } 1039 mLastInfoPaneStackScroll = newScroll; 1040 1041 // Show the info pane for this task view 1042 tv.showInfoPane(new Rect(0, 0, 0, (int) overlapHeight)); 1043 return true; 1044 } 1045} 1046 1047/* Handles touch events */ 1048class TaskStackViewTouchHandler implements SwipeHelper.Callback { 1049 static int INACTIVE_POINTER_ID = -1; 1050 1051 TaskStackView mSv; 1052 VelocityTracker mVelocityTracker; 1053 1054 boolean mIsScrolling; 1055 1056 int mInitialMotionX, mInitialMotionY; 1057 int mLastMotionX, mLastMotionY; 1058 int mActivePointerId = INACTIVE_POINTER_ID; 1059 TaskView mActiveTaskView = null; 1060 1061 int mTotalScrollMotion; 1062 int mMinimumVelocity; 1063 int mMaximumVelocity; 1064 // The scroll touch slop is used to calculate when we start scrolling 1065 int mScrollTouchSlop; 1066 // The page touch slop is used to calculate when we start swiping 1067 float mPagingTouchSlop; 1068 1069 SwipeHelper mSwipeHelper; 1070 boolean mInterceptedBySwipeHelper; 1071 1072 public TaskStackViewTouchHandler(Context context, TaskStackView sv) { 1073 ViewConfiguration configuration = ViewConfiguration.get(context); 1074 mMinimumVelocity = configuration.getScaledMinimumFlingVelocity(); 1075 mMaximumVelocity = configuration.getScaledMaximumFlingVelocity(); 1076 mScrollTouchSlop = configuration.getScaledTouchSlop(); 1077 mPagingTouchSlop = configuration.getScaledPagingTouchSlop(); 1078 mSv = sv; 1079 1080 1081 float densityScale = context.getResources().getDisplayMetrics().density; 1082 mSwipeHelper = new SwipeHelper(SwipeHelper.X, this, densityScale, mPagingTouchSlop); 1083 mSwipeHelper.setMinAlpha(1f); 1084 } 1085 1086 /** Velocity tracker helpers */ 1087 void initOrResetVelocityTracker() { 1088 if (mVelocityTracker == null) { 1089 mVelocityTracker = VelocityTracker.obtain(); 1090 } else { 1091 mVelocityTracker.clear(); 1092 } 1093 } 1094 void initVelocityTrackerIfNotExists() { 1095 if (mVelocityTracker == null) { 1096 mVelocityTracker = VelocityTracker.obtain(); 1097 } 1098 } 1099 void recycleVelocityTracker() { 1100 if (mVelocityTracker != null) { 1101 mVelocityTracker.recycle(); 1102 mVelocityTracker = null; 1103 } 1104 } 1105 1106 /** Returns the view at the specified coordinates */ 1107 TaskView findViewAtPoint(int x, int y) { 1108 int childCount = mSv.getChildCount(); 1109 for (int i = childCount - 1; i >= 0; i--) { 1110 TaskView tv = (TaskView) mSv.getChildAt(i); 1111 if (tv.getVisibility() == View.VISIBLE) { 1112 if (mSv.isTransformedTouchPointInView(x, y, tv)) { 1113 return tv; 1114 } 1115 } 1116 } 1117 return null; 1118 } 1119 1120 /** Touch preprocessing for handling below */ 1121 public boolean onInterceptTouchEvent(MotionEvent ev) { 1122 Console.log(Constants.DebugFlags.UI.TouchEvents, 1123 "[TaskStackViewTouchHandler|interceptTouchEvent]", 1124 Console.motionEventActionToString(ev.getAction()), Console.AnsiBlue); 1125 1126 // Return early if we have no children 1127 boolean hasChildren = (mSv.getChildCount() > 0); 1128 if (!hasChildren) { 1129 return false; 1130 } 1131 1132 // Pass through to swipe helper if we are swiping 1133 mInterceptedBySwipeHelper = mSwipeHelper.onInterceptTouchEvent(ev); 1134 if (mInterceptedBySwipeHelper) { 1135 return true; 1136 } 1137 1138 boolean wasScrolling = !mSv.mScroller.isFinished() || 1139 (mSv.mScrollAnimator != null && mSv.mScrollAnimator.isRunning()); 1140 int action = ev.getAction(); 1141 switch (action & MotionEvent.ACTION_MASK) { 1142 case MotionEvent.ACTION_DOWN: { 1143 // Save the touch down info 1144 mInitialMotionX = mLastMotionX = (int) ev.getX(); 1145 mInitialMotionY = mLastMotionY = (int) ev.getY(); 1146 mActivePointerId = ev.getPointerId(0); 1147 mActiveTaskView = findViewAtPoint(mLastMotionX, mLastMotionY); 1148 // Stop the current scroll if it is still flinging 1149 mSv.abortScroller(); 1150 mSv.abortBoundScrollAnimation(); 1151 // Initialize the velocity tracker 1152 initOrResetVelocityTracker(); 1153 mVelocityTracker.addMovement(ev); 1154 // Check if the scroller is finished yet 1155 mIsScrolling = !mSv.mScroller.isFinished(); 1156 break; 1157 } 1158 case MotionEvent.ACTION_MOVE: { 1159 if (mActivePointerId == INACTIVE_POINTER_ID) break; 1160 1161 int activePointerIndex = ev.findPointerIndex(mActivePointerId); 1162 int y = (int) ev.getY(activePointerIndex); 1163 int x = (int) ev.getX(activePointerIndex); 1164 if (Math.abs(y - mInitialMotionY) > mScrollTouchSlop) { 1165 // Save the touch move info 1166 mIsScrolling = true; 1167 // Initialize the velocity tracker if necessary 1168 initVelocityTrackerIfNotExists(); 1169 mVelocityTracker.addMovement(ev); 1170 // Disallow parents from intercepting touch events 1171 final ViewParent parent = mSv.getParent(); 1172 if (parent != null) { 1173 parent.requestDisallowInterceptTouchEvent(true); 1174 } 1175 // Enable HW layers 1176 mSv.addHwLayersRefCount("stackScroll"); 1177 } 1178 1179 mLastMotionX = x; 1180 mLastMotionY = y; 1181 break; 1182 } 1183 case MotionEvent.ACTION_CANCEL: 1184 case MotionEvent.ACTION_UP: { 1185 // Animate the scroll back if we've cancelled 1186 mSv.animateBoundScroll(); 1187 // Disable HW layers 1188 if (mIsScrolling) { 1189 mSv.decHwLayersRefCount("stackScroll"); 1190 } 1191 // Reset the drag state and the velocity tracker 1192 mIsScrolling = false; 1193 mActivePointerId = INACTIVE_POINTER_ID; 1194 mActiveTaskView = null; 1195 mTotalScrollMotion = 0; 1196 recycleVelocityTracker(); 1197 break; 1198 } 1199 } 1200 1201 return wasScrolling || mIsScrolling; 1202 } 1203 1204 /** Handles touch events once we have intercepted them */ 1205 public boolean onTouchEvent(MotionEvent ev) { 1206 Console.log(Constants.DebugFlags.UI.TouchEvents, 1207 "[TaskStackViewTouchHandler|touchEvent]", 1208 Console.motionEventActionToString(ev.getAction()), Console.AnsiBlue); 1209 1210 // Short circuit if we have no children 1211 boolean hasChildren = (mSv.getChildCount() > 0); 1212 if (!hasChildren) { 1213 return false; 1214 } 1215 1216 // Pass through to swipe helper if we are swiping 1217 if (mInterceptedBySwipeHelper && mSwipeHelper.onTouchEvent(ev)) { 1218 return true; 1219 } 1220 1221 // Update the velocity tracker 1222 initVelocityTrackerIfNotExists(); 1223 mVelocityTracker.addMovement(ev); 1224 1225 int action = ev.getAction(); 1226 switch (action & MotionEvent.ACTION_MASK) { 1227 case MotionEvent.ACTION_DOWN: { 1228 // Save the touch down info 1229 mInitialMotionX = mLastMotionX = (int) ev.getX(); 1230 mInitialMotionY = mLastMotionY = (int) ev.getY(); 1231 mActivePointerId = ev.getPointerId(0); 1232 mActiveTaskView = findViewAtPoint(mLastMotionX, mLastMotionY); 1233 // Stop the current scroll if it is still flinging 1234 mSv.abortScroller(); 1235 mSv.abortBoundScrollAnimation(); 1236 // Initialize the velocity tracker 1237 initOrResetVelocityTracker(); 1238 mVelocityTracker.addMovement(ev); 1239 // Disallow parents from intercepting touch events 1240 final ViewParent parent = mSv.getParent(); 1241 if (parent != null) { 1242 parent.requestDisallowInterceptTouchEvent(true); 1243 } 1244 break; 1245 } 1246 case MotionEvent.ACTION_POINTER_DOWN: { 1247 final int index = ev.getActionIndex(); 1248 mActivePointerId = ev.getPointerId(index); 1249 mLastMotionX = (int) ev.getX(index); 1250 mLastMotionY = (int) ev.getY(index); 1251 break; 1252 } 1253 case MotionEvent.ACTION_MOVE: { 1254 if (mActivePointerId == INACTIVE_POINTER_ID) break; 1255 1256 int activePointerIndex = ev.findPointerIndex(mActivePointerId); 1257 int x = (int) ev.getX(activePointerIndex); 1258 int y = (int) ev.getY(activePointerIndex); 1259 int yTotal = Math.abs(y - mInitialMotionY); 1260 int deltaY = mLastMotionY - y; 1261 if (!mIsScrolling) { 1262 if (yTotal > mScrollTouchSlop) { 1263 mIsScrolling = true; 1264 // Initialize the velocity tracker 1265 initOrResetVelocityTracker(); 1266 mVelocityTracker.addMovement(ev); 1267 // Disallow parents from intercepting touch events 1268 final ViewParent parent = mSv.getParent(); 1269 if (parent != null) { 1270 parent.requestDisallowInterceptTouchEvent(true); 1271 } 1272 // Enable HW layers 1273 mSv.addHwLayersRefCount("stackScroll"); 1274 } 1275 } 1276 if (mIsScrolling) { 1277 mSv.setStackScroll(mSv.getStackScroll() + deltaY); 1278 if (mSv.isScrollOutOfBounds()) { 1279 mVelocityTracker.clear(); 1280 } 1281 } 1282 mLastMotionX = x; 1283 mLastMotionY = y; 1284 mTotalScrollMotion += Math.abs(deltaY); 1285 break; 1286 } 1287 case MotionEvent.ACTION_UP: { 1288 final VelocityTracker velocityTracker = mVelocityTracker; 1289 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); 1290 int velocity = (int) velocityTracker.getYVelocity(mActivePointerId); 1291 1292 if (mIsScrolling && (Math.abs(velocity) > mMinimumVelocity)) { 1293 // Enable HW layers on the stack 1294 mSv.addHwLayersRefCount("flingScroll"); 1295 int overscrollRange = (int) (Math.min(1f, 1296 Math.abs((float) velocity / mMaximumVelocity)) * 1297 Constants.Values.TaskStackView.TaskStackOverscrollRange); 1298 1299 Console.log(Constants.DebugFlags.UI.TouchEvents, 1300 "[TaskStackViewTouchHandler|fling]", 1301 "scroll: " + mSv.getStackScroll() + " velocity: " + velocity + 1302 " maxVelocity: " + mMaximumVelocity + 1303 " overscrollRange: " + overscrollRange, 1304 Console.AnsiGreen); 1305 1306 // Fling scroll 1307 mSv.mScroller.fling(0, mSv.getStackScroll(), 1308 0, -velocity, 1309 0, 0, 1310 mSv.mMinScroll, mSv.mMaxScroll, 1311 0, overscrollRange); 1312 // Invalidate to kick off computeScroll 1313 mSv.invalidate(); 1314 } else if (mSv.isScrollOutOfBounds()) { 1315 // Animate the scroll back into bounds 1316 // XXX: Make this animation a function of the velocity OR distance 1317 mSv.animateBoundScroll(); 1318 } 1319 1320 if (mIsScrolling) { 1321 // Disable HW layers 1322 mSv.decHwLayersRefCount("stackScroll"); 1323 } 1324 mActivePointerId = INACTIVE_POINTER_ID; 1325 mIsScrolling = false; 1326 mTotalScrollMotion = 0; 1327 recycleVelocityTracker(); 1328 break; 1329 } 1330 case MotionEvent.ACTION_POINTER_UP: { 1331 int pointerIndex = ev.getActionIndex(); 1332 int pointerId = ev.getPointerId(pointerIndex); 1333 if (pointerId == mActivePointerId) { 1334 // Select a new active pointer id and reset the motion state 1335 final int newPointerIndex = (pointerIndex == 0) ? 1 : 0; 1336 mActivePointerId = ev.getPointerId(newPointerIndex); 1337 mLastMotionX = (int) ev.getX(newPointerIndex); 1338 mLastMotionY = (int) ev.getY(newPointerIndex); 1339 mVelocityTracker.clear(); 1340 } 1341 break; 1342 } 1343 case MotionEvent.ACTION_CANCEL: { 1344 if (mIsScrolling) { 1345 // Disable HW layers 1346 mSv.decHwLayersRefCount("stackScroll"); 1347 } 1348 if (mSv.isScrollOutOfBounds()) { 1349 // Animate the scroll back into bounds 1350 // XXX: Make this animation a function of the velocity OR distance 1351 mSv.animateBoundScroll(); 1352 } 1353 mActivePointerId = INACTIVE_POINTER_ID; 1354 mIsScrolling = false; 1355 mTotalScrollMotion = 0; 1356 recycleVelocityTracker(); 1357 break; 1358 } 1359 } 1360 return true; 1361 } 1362 1363 /**** SwipeHelper Implementation ****/ 1364 1365 @Override 1366 public View getChildAtPosition(MotionEvent ev) { 1367 return findViewAtPoint((int) ev.getX(), (int) ev.getY()); 1368 } 1369 1370 @Override 1371 public boolean canChildBeDismissed(View v) { 1372 return true; 1373 } 1374 1375 @Override 1376 public void onBeginDrag(View v) { 1377 // Enable HW layers 1378 mSv.addHwLayersRefCount("swipeBegin"); 1379 // Disallow parents from intercepting touch events 1380 final ViewParent parent = mSv.getParent(); 1381 if (parent != null) { 1382 parent.requestDisallowInterceptTouchEvent(true); 1383 } 1384 // If the info panel is currently showing on this view, then we need to dismiss it 1385 if (Constants.DebugFlags.App.EnableInfoPane) { 1386 TaskView tv = (TaskView) v; 1387 if (tv.isInfoPaneVisible()) { 1388 tv.hideInfoPane(); 1389 } 1390 } 1391 } 1392 1393 @Override 1394 public void onChildDismissed(View v) { 1395 TaskView tv = (TaskView) v; 1396 Task task = tv.getTask(); 1397 Activity activity = (Activity) mSv.getContext(); 1398 1399 // Remove the task from the view 1400 mSv.mStack.removeTask(task); 1401 1402 // Remove any stored data from the loader 1403 RecentsTaskLoader loader = RecentsTaskLoader.getInstance(); 1404 loader.deleteTaskData(task); 1405 1406 // Remove the task from activity manager 1407 RecentsTaskLoader.getInstance().getSystemServicesProxy().removeTask(tv.getTask().key.id); 1408 1409 // If there are no remaining tasks, then either unfilter the current stack, or just close 1410 // the activity if there are no filtered stacks 1411 if (mSv.mStack.getTaskCount() == 0) { 1412 boolean shouldFinishActivity = true; 1413 if (mSv.mStack.hasFilteredTasks()) { 1414 mSv.mStack.unfilterTasks(); 1415 shouldFinishActivity = (mSv.mStack.getTaskCount() == 0); 1416 } 1417 if (shouldFinishActivity) { 1418 activity.finish(); 1419 } 1420 } 1421 1422 // Disable HW layers 1423 mSv.decHwLayersRefCount("swipeComplete"); 1424 } 1425 1426 @Override 1427 public void onSnapBackCompleted(View v) { 1428 // Do Nothing 1429 } 1430 1431 @Override 1432 public void onDragCancelled(View v) { 1433 // Disable HW layers 1434 mSv.decHwLayersRefCount("swipeCancelled"); 1435 } 1436} 1437