RecentsImpl.java revision d27dafeadeb38d451826122d0505702abf58bd1d
1/* 2 * Copyright (C) 2015 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; 18 19import static android.app.ActivityManager.StackId.FREEFORM_WORKSPACE_STACK_ID; 20 21import android.app.ActivityManager; 22import android.app.ActivityOptions; 23import android.app.ITaskStackListener; 24import android.app.UiModeManager; 25import android.appwidget.AppWidgetProviderInfo; 26import android.content.ActivityNotFoundException; 27import android.content.Context; 28import android.content.Intent; 29import android.content.res.Configuration; 30import android.content.res.Resources; 31import android.graphics.Bitmap; 32import android.graphics.Canvas; 33import android.graphics.Rect; 34import android.graphics.RectF; 35import android.os.Handler; 36import android.os.SystemClock; 37import android.os.UserHandle; 38import android.util.Log; 39import android.util.MutableBoolean; 40import android.view.AppTransitionAnimationSpec; 41import android.view.LayoutInflater; 42import android.view.View; 43import android.view.ViewConfiguration; 44 45import com.android.internal.logging.MetricsLogger; 46import com.android.systemui.Prefs; 47import com.android.systemui.R; 48import com.android.systemui.SystemUIApplication; 49import com.android.systemui.recents.events.EventBus; 50import com.android.systemui.recents.events.activity.DockingTopTaskEvent; 51import com.android.systemui.recents.events.activity.EnterRecentsWindowLastAnimationFrameEvent; 52import com.android.systemui.recents.events.activity.HideRecentsEvent; 53import com.android.systemui.recents.events.activity.IterateRecentsEvent; 54import com.android.systemui.recents.events.activity.LaunchNextTaskRequestEvent; 55import com.android.systemui.recents.events.activity.RecentsActivityStartingEvent; 56import com.android.systemui.recents.events.activity.ToggleRecentsEvent; 57import com.android.systemui.recents.events.component.RecentsVisibilityChangedEvent; 58import com.android.systemui.recents.events.component.ScreenPinningRequestEvent; 59import com.android.systemui.recents.events.ui.DraggingInRecentsEndedEvent; 60import com.android.systemui.recents.events.ui.DraggingInRecentsEvent; 61import com.android.systemui.recents.misc.DozeTrigger; 62import com.android.systemui.recents.misc.ForegroundThread; 63import com.android.systemui.recents.misc.SystemServicesProxy; 64import com.android.systemui.recents.model.RecentsTaskLoadPlan; 65import com.android.systemui.recents.model.RecentsTaskLoader; 66import com.android.systemui.recents.model.Task; 67import com.android.systemui.recents.model.TaskGrouping; 68import com.android.systemui.recents.model.TaskStack; 69import com.android.systemui.recents.tv.views.TaskStackHorizontalGridView; 70import com.android.systemui.recents.views.TaskStackLayoutAlgorithm; 71import com.android.systemui.recents.views.TaskStackView; 72import com.android.systemui.recents.views.TaskStackViewScroller; 73import com.android.systemui.recents.views.TaskViewHeader; 74import com.android.systemui.recents.views.TaskViewTransform; 75import com.android.systemui.statusbar.BaseStatusBar; 76import com.android.systemui.statusbar.phone.NavigationBarGestureHelper; 77import com.android.systemui.statusbar.phone.PhoneStatusBar; 78 79import java.util.ArrayList; 80 81/** 82 * An implementation of the Recents component for the current user. For secondary users, this can 83 * be called remotely from the system user. 84 */ 85public class RecentsImpl implements ActivityOptions.OnAnimationFinishedListener { 86 87 private final static String TAG = "RecentsImpl"; 88 89 // The minimum amount of time between each recents button press that we will handle 90 private final static int MIN_TOGGLE_DELAY_MS = 350; 91 92 // The duration within which the user releasing the alt tab (from when they pressed alt tab) 93 // that the fast alt-tab animation will run. If the user's alt-tab takes longer than this 94 // duration, then we will toggle recents after this duration. 95 private final static int FAST_ALT_TAB_DELAY_MS = 225; 96 97 public final static String RECENTS_PACKAGE = "com.android.systemui"; 98 public final static String RECENTS_ACTIVITY = "com.android.systemui.recents.RecentsActivity"; 99 public final static String RECENTS_TV_ACTIVITY = "com.android.systemui.recents.tv.RecentsTvActivity"; 100 101 //Used to store tv or non-tv activty for use in creating intents. 102 private final String mRecentsIntentActivityName; 103 104 /** 105 * An implementation of ITaskStackListener, that allows us to listen for changes to the system 106 * task stacks and update recents accordingly. 107 */ 108 class TaskStackListenerImpl extends ITaskStackListener.Stub implements Runnable { 109 Handler mHandler; 110 111 public TaskStackListenerImpl(Handler handler) { 112 mHandler = handler; 113 } 114 115 @Override 116 public void onTaskStackChanged() { 117 // Debounce any task stack changes 118 mHandler.removeCallbacks(this); 119 mHandler.post(this); 120 } 121 122 @Override 123 public void onActivityPinned() { 124 } 125 126 @Override 127 public void onPinnedActivityRestartAttempt() { 128 } 129 130 @Override 131 public void onPinnedStackAnimationEnded() { 132 } 133 134 /** Preloads the next task */ 135 public void run() { 136 RecentsConfiguration config = Recents.getConfiguration(); 137 if (config.svelteLevel == RecentsConfiguration.SVELTE_NONE) { 138 RecentsTaskLoader loader = Recents.getTaskLoader(); 139 SystemServicesProxy ssp = Recents.getSystemServices(); 140 ActivityManager.RunningTaskInfo runningTaskInfo = ssp.getTopMostTask(); 141 142 // Load the next task only if we aren't svelte 143 RecentsTaskLoadPlan plan = loader.createLoadPlan(mContext); 144 loader.preloadTasks(plan, -1, true /* isTopTaskHome */); 145 RecentsTaskLoadPlan.Options launchOpts = new RecentsTaskLoadPlan.Options(); 146 // This callback is made when a new activity is launched and the old one is paused 147 // so ignore the current activity and try and preload the thumbnail for the 148 // previous one. 149 if (runningTaskInfo != null) { 150 launchOpts.runningTaskId = runningTaskInfo.id; 151 } 152 launchOpts.numVisibleTasks = 2; 153 launchOpts.numVisibleTaskThumbnails = 2; 154 launchOpts.onlyLoadForCache = true; 155 launchOpts.onlyLoadPausedActivities = true; 156 loader.loadTasks(mContext, plan, launchOpts); 157 } 158 } 159 } 160 161 private static RecentsTaskLoadPlan sInstanceLoadPlan; 162 163 Context mContext; 164 Handler mHandler; 165 TaskStackListenerImpl mTaskStackListener; 166 RecentsAppWidgetHost mAppWidgetHost; 167 boolean mCanReuseTaskStackViews = true; 168 boolean mDraggingInRecents; 169 boolean mLaunchedWhileDocking; 170 171 // Task launching 172 Rect mSearchBarBounds = new Rect(); 173 Rect mTaskStackBounds = new Rect(); 174 Rect mLastTaskViewBounds = new Rect(); 175 TaskViewTransform mTmpTransform = new TaskViewTransform(); 176 int mStatusBarHeight; 177 int mNavBarHeight; 178 int mNavBarWidth; 179 int mTaskBarHeight; 180 181 // Header (for transition) 182 TaskViewHeader mHeaderBar; 183 final Object mHeaderBarLock = new Object(); 184 TaskStackView mDummyStackView; 185 186 // Variables to keep track of if we need to start recents after binding 187 boolean mTriggeredFromAltTab; 188 long mLastToggleTime; 189 DozeTrigger mFastAltTabTrigger = new DozeTrigger(FAST_ALT_TAB_DELAY_MS, new Runnable() { 190 @Override 191 public void run() { 192 // When this fires, then the user has not released alt-tab for at least 193 // FAST_ALT_TAB_DELAY_MS milliseconds 194 showRecents(mTriggeredFromAltTab, false /* draggingInRecents */, true /* animate */, 195 false /* reloadTasks */); 196 } 197 }); 198 199 Bitmap mThumbnailTransitionBitmapCache; 200 Task mThumbnailTransitionBitmapCacheKey; 201 202 public RecentsImpl(Context context) { 203 mContext = context; 204 mHandler = new Handler(); 205 mAppWidgetHost = new RecentsAppWidgetHost(mContext, RecentsAppWidgetHost.HOST_ID); 206 207 // Initialize the static foreground thread 208 ForegroundThread.get(); 209 210 // Register the task stack listener 211 mTaskStackListener = new TaskStackListenerImpl(mHandler); 212 SystemServicesProxy ssp = Recents.getSystemServices(); 213 ssp.registerTaskStackListener(mTaskStackListener); 214 215 // Initialize the static configuration resources 216 reloadHeaderBarLayout(); 217 updateHeaderBarLayout(true /* tryAndBindSearchWidget */, null /* stack */); 218 219 // When we start, preload the data associated with the previous recent tasks. 220 // We can use a new plan since the caches will be the same. 221 RecentsTaskLoader loader = Recents.getTaskLoader(); 222 RecentsTaskLoadPlan plan = loader.createLoadPlan(mContext); 223 loader.preloadTasks(plan, -1, true /* isTopTaskHome */); 224 RecentsTaskLoadPlan.Options launchOpts = new RecentsTaskLoadPlan.Options(); 225 launchOpts.numVisibleTasks = loader.getIconCacheSize(); 226 launchOpts.numVisibleTaskThumbnails = loader.getThumbnailCacheSize(); 227 launchOpts.onlyLoadForCache = true; 228 loader.loadTasks(mContext, plan, launchOpts); 229 230 //Manager used to determine if we are running on tv or not 231 UiModeManager uiModeManager = (UiModeManager) mContext.getSystemService(Context.UI_MODE_SERVICE); 232 if (uiModeManager.getCurrentModeType() == Configuration.UI_MODE_TYPE_TELEVISION) { 233 mRecentsIntentActivityName = RECENTS_TV_ACTIVITY; 234 } else { 235 mRecentsIntentActivityName = RECENTS_ACTIVITY; 236 } 237 } 238 239 public void onBootCompleted() { 240 updateHeaderBarLayout(true /* tryAndBindSearchWidget */, null /* stack */); 241 } 242 243 public void onConfigurationChanged() { 244 reloadHeaderBarLayout(); 245 updateHeaderBarLayout(true /* tryAndBindSearchWidget */, null /* stack */); 246 // Don't reuse task stack views if the configuration changes 247 mCanReuseTaskStackViews = false; 248 Recents.getConfiguration().updateOnConfigurationChange(); 249 } 250 251 /** 252 * This is only called from the system user's Recents. Secondary users will instead proxy their 253 * visibility change events through to the system user via 254 * {@link Recents#onBusEvent(RecentsVisibilityChangedEvent)}. 255 */ 256 public void onVisibilityChanged(Context context, boolean visible) { 257 SystemUIApplication app = (SystemUIApplication) context; 258 PhoneStatusBar statusBar = app.getComponent(PhoneStatusBar.class); 259 if (statusBar != null) { 260 statusBar.updateRecentsVisibility(visible); 261 } 262 } 263 264 /** 265 * This is only called from the system user's Recents. Secondary users will instead proxy their 266 * visibility change events through to the system user via 267 * {@link Recents#onBusEvent(ScreenPinningRequestEvent)}. 268 */ 269 public void onStartScreenPinning(Context context) { 270 SystemUIApplication app = (SystemUIApplication) context; 271 PhoneStatusBar statusBar = app.getComponent(PhoneStatusBar.class); 272 if (statusBar != null) { 273 statusBar.showScreenPinningRequest(false); 274 } 275 } 276 277 public void showRecents(boolean triggeredFromAltTab, boolean draggingInRecents, 278 boolean animate, boolean launchedWhileDockingTask) { 279 mTriggeredFromAltTab = triggeredFromAltTab; 280 mDraggingInRecents = draggingInRecents; 281 mLaunchedWhileDocking = launchedWhileDockingTask; 282 if (mFastAltTabTrigger.isAsleep()) { 283 // Fast alt-tab duration has elapsed, fall through to showing Recents and reset 284 mFastAltTabTrigger.stopDozing(); 285 } else if (mFastAltTabTrigger.isDozing()) { 286 // Fast alt-tab duration has not elapsed. If this is triggered by a different 287 // showRecents() call, then ignore that call for now. 288 // TODO: We can not handle quick tabs that happen between the initial showRecents() call 289 // that started the activity and the activity starting up. The severity of this 290 // is inversely proportional to the FAST_ALT_TAB_DELAY_MS duration though. 291 if (!triggeredFromAltTab) { 292 return; 293 } 294 mFastAltTabTrigger.stopDozing(); 295 } else if (triggeredFromAltTab) { 296 // The fast alt-tab detector is not yet running, so start the trigger and wait for the 297 // hideRecents() call, or for the fast alt-tab duration to elapse 298 mFastAltTabTrigger.startDozing(); 299 return; 300 } 301 302 try { 303 // Check if the top task is in the home stack, and start the recents activity 304 SystemServicesProxy ssp = Recents.getSystemServices(); 305 ActivityManager.RunningTaskInfo topTask = ssp.getTopMostTask(); 306 MutableBoolean isTopTaskHome = new MutableBoolean(true); 307 if (topTask == null || !ssp.isRecentsTopMost(topTask, isTopTaskHome)) { 308 startRecentsActivity(topTask, isTopTaskHome.value, animate); 309 } 310 } catch (ActivityNotFoundException e) { 311 Log.e(TAG, "Failed to launch RecentsActivity", e); 312 } 313 } 314 315 public void hideRecents(boolean triggeredFromAltTab, boolean triggeredFromHomeKey) { 316 if (triggeredFromAltTab && mFastAltTabTrigger.isDozing()) { 317 // The user has released alt-tab before the trigger has run, so just show the next 318 // task immediately 319 showNextTask(); 320 321 // Cancel the fast alt-tab trigger 322 mFastAltTabTrigger.stopDozing(); 323 return; 324 } 325 326 // Defer to the activity to handle hiding recents, if it handles it, then it must still 327 // be visible 328 EventBus.getDefault().post(new HideRecentsEvent(triggeredFromAltTab, 329 triggeredFromHomeKey)); 330 } 331 332 public void toggleRecents() { 333 // Skip this toggle if we are already waiting to trigger recents via alt-tab 334 if (mFastAltTabTrigger.isDozing()) { 335 return; 336 } 337 338 mDraggingInRecents = false; 339 mLaunchedWhileDocking = false; 340 mTriggeredFromAltTab = false; 341 342 try { 343 SystemServicesProxy ssp = Recents.getSystemServices(); 344 ActivityManager.RunningTaskInfo topTask = ssp.getTopMostTask(); 345 MutableBoolean isTopTaskHome = new MutableBoolean(true); 346 long elapsedTime = SystemClock.elapsedRealtime() - mLastToggleTime; 347 348 if (topTask != null && ssp.isRecentsTopMost(topTask, isTopTaskHome)) { 349 RecentsDebugFlags debugFlags = Recents.getDebugFlags(); 350 RecentsConfiguration config = Recents.getConfiguration(); 351 RecentsActivityLaunchState launchState = config.getLaunchState(); 352 if (!launchState.launchedWithAltTab) { 353 // If the user taps quickly 354 if (!debugFlags.isPagingEnabled() || 355 (ViewConfiguration.getDoubleTapMinTime() < elapsedTime && 356 elapsedTime < ViewConfiguration.getDoubleTapTimeout())) { 357 // Launch the next focused task 358 EventBus.getDefault().post(new LaunchNextTaskRequestEvent()); 359 } else { 360 // Notify recents to move onto the next task 361 EventBus.getDefault().post(new IterateRecentsEvent()); 362 } 363 } else { 364 // If the user has toggled it too quickly, then just eat up the event here (it's 365 // better than showing a janky screenshot). 366 // NOTE: Ideally, the screenshot mechanism would take the window transform into 367 // account 368 if (elapsedTime < MIN_TOGGLE_DELAY_MS) { 369 return; 370 } 371 372 EventBus.getDefault().post(new ToggleRecentsEvent()); 373 mLastToggleTime = SystemClock.elapsedRealtime(); 374 } 375 return; 376 } else { 377 // If the user has toggled it too quickly, then just eat up the event here (it's 378 // better than showing a janky screenshot). 379 // NOTE: Ideally, the screenshot mechanism would take the window transform into 380 // account 381 if (elapsedTime < MIN_TOGGLE_DELAY_MS) { 382 return; 383 } 384 385 // Otherwise, start the recents activity 386 startRecentsActivity(topTask, isTopTaskHome.value, true /* animate */); 387 388 // Only close the other system windows if we are actually showing recents 389 ssp.sendCloseSystemWindows(BaseStatusBar.SYSTEM_DIALOG_REASON_RECENT_APPS); 390 mLastToggleTime = SystemClock.elapsedRealtime(); 391 } 392 } catch (ActivityNotFoundException e) { 393 Log.e(TAG, "Failed to launch RecentsActivity", e); 394 } 395 } 396 397 public void preloadRecents() { 398 // Preload only the raw task list into a new load plan (which will be consumed by the 399 // RecentsActivity) only if there is a task to animate to. 400 SystemServicesProxy ssp = Recents.getSystemServices(); 401 ActivityManager.RunningTaskInfo topTask = ssp.getTopMostTask(); 402 MutableBoolean topTaskHome = new MutableBoolean(true); 403 if (topTask != null && !ssp.isRecentsTopMost(topTask, topTaskHome)) { 404 RecentsTaskLoader loader = Recents.getTaskLoader(); 405 sInstanceLoadPlan = loader.createLoadPlan(mContext); 406 sInstanceLoadPlan.preloadRawTasks(topTaskHome.value); 407 loader.preloadTasks(sInstanceLoadPlan, topTask.id, topTaskHome.value); 408 TaskStack stack = sInstanceLoadPlan.getTaskStack(); 409 if (stack.getTaskCount() > 0) { 410 // We try and draw the thumbnail transition bitmap in parallel before 411 // toggle/show recents is called 412 preCacheThumbnailTransitionBitmapAsync(topTask, stack, mDummyStackView); 413 } 414 } 415 } 416 417 public void cancelPreloadingRecents() { 418 // Do nothing 419 } 420 421 public void onDraggingInRecents(float distanceFromTop) { 422 EventBus.getDefault().sendOntoMainThread(new DraggingInRecentsEvent(distanceFromTop)); 423 } 424 425 public void onDraggingInRecentsEnded(float velocity) { 426 EventBus.getDefault().sendOntoMainThread(new DraggingInRecentsEndedEvent(velocity)); 427 } 428 429 /** 430 * Transitions to the next recent task in the stack. 431 */ 432 public void showNextTask() { 433 SystemServicesProxy ssp = Recents.getSystemServices(); 434 RecentsTaskLoader loader = Recents.getTaskLoader(); 435 RecentsTaskLoadPlan plan = loader.createLoadPlan(mContext); 436 loader.preloadTasks(plan, -1, true /* isTopTaskHome */); 437 TaskStack focusedStack = plan.getTaskStack(); 438 439 // Return early if there are no tasks in the focused stack 440 if (focusedStack == null || focusedStack.getTaskCount() == 0) return; 441 442 ActivityManager.RunningTaskInfo runningTask = ssp.getTopMostTask(); 443 // Return early if there is no running task 444 if (runningTask == null) return; 445 446 // Find the task in the recents list 447 boolean isTopTaskHome = SystemServicesProxy.isHomeStack(runningTask.stackId); 448 ArrayList<Task> tasks = focusedStack.getStackTasks(); 449 Task toTask = null; 450 ActivityOptions launchOpts = null; 451 int taskCount = tasks.size(); 452 for (int i = taskCount - 1; i >= 1; i--) { 453 Task task = tasks.get(i); 454 if (isTopTaskHome) { 455 toTask = tasks.get(i - 1); 456 launchOpts = ActivityOptions.makeCustomAnimation(mContext, 457 R.anim.recents_launch_next_affiliated_task_target, 458 R.anim.recents_fast_toggle_app_home_exit); 459 break; 460 } else if (task.key.id == runningTask.id) { 461 toTask = tasks.get(i - 1); 462 launchOpts = ActivityOptions.makeCustomAnimation(mContext, 463 R.anim.recents_launch_prev_affiliated_task_target, 464 R.anim.recents_launch_prev_affiliated_task_source); 465 break; 466 } 467 } 468 469 // Return early if there is no next task 470 if (toTask == null) { 471 ssp.startInPlaceAnimationOnFrontMostApplication( 472 ActivityOptions.makeCustomInPlaceAnimation(mContext, 473 R.anim.recents_launch_prev_affiliated_task_bounce)); 474 return; 475 } 476 477 // Launch the task 478 ssp.startActivityFromRecents(mContext, toTask.key.id, toTask.title, launchOpts); 479 } 480 481 /** 482 * Transitions to the next affiliated task. 483 */ 484 public void showRelativeAffiliatedTask(boolean showNextTask) { 485 SystemServicesProxy ssp = Recents.getSystemServices(); 486 RecentsTaskLoader loader = Recents.getTaskLoader(); 487 RecentsTaskLoadPlan plan = loader.createLoadPlan(mContext); 488 loader.preloadTasks(plan, -1, true /* isTopTaskHome */); 489 TaskStack focusedStack = plan.getTaskStack(); 490 491 // Return early if there are no tasks in the focused stack 492 if (focusedStack == null || focusedStack.getTaskCount() == 0) return; 493 494 ActivityManager.RunningTaskInfo runningTask = ssp.getTopMostTask(); 495 // Return early if there is no running task (can't determine affiliated tasks in this case) 496 if (runningTask == null) return; 497 // Return early if the running task is in the home stack (optimization) 498 if (SystemServicesProxy.isHomeStack(runningTask.stackId)) return; 499 500 // Find the task in the recents list 501 ArrayList<Task> tasks = focusedStack.getStackTasks(); 502 Task toTask = null; 503 ActivityOptions launchOpts = null; 504 int taskCount = tasks.size(); 505 int numAffiliatedTasks = 0; 506 for (int i = 0; i < taskCount; i++) { 507 Task task = tasks.get(i); 508 if (task.key.id == runningTask.id) { 509 TaskGrouping group = task.group; 510 Task.TaskKey toTaskKey; 511 if (showNextTask) { 512 toTaskKey = group.getNextTaskInGroup(task); 513 launchOpts = ActivityOptions.makeCustomAnimation(mContext, 514 R.anim.recents_launch_next_affiliated_task_target, 515 R.anim.recents_launch_next_affiliated_task_source); 516 } else { 517 toTaskKey = group.getPrevTaskInGroup(task); 518 launchOpts = ActivityOptions.makeCustomAnimation(mContext, 519 R.anim.recents_launch_prev_affiliated_task_target, 520 R.anim.recents_launch_prev_affiliated_task_source); 521 } 522 if (toTaskKey != null) { 523 toTask = focusedStack.findTaskWithId(toTaskKey.id); 524 } 525 numAffiliatedTasks = group.getTaskCount(); 526 break; 527 } 528 } 529 530 // Return early if there is no next task 531 if (toTask == null) { 532 if (numAffiliatedTasks > 1) { 533 if (showNextTask) { 534 ssp.startInPlaceAnimationOnFrontMostApplication( 535 ActivityOptions.makeCustomInPlaceAnimation(mContext, 536 R.anim.recents_launch_next_affiliated_task_bounce)); 537 } else { 538 ssp.startInPlaceAnimationOnFrontMostApplication( 539 ActivityOptions.makeCustomInPlaceAnimation(mContext, 540 R.anim.recents_launch_prev_affiliated_task_bounce)); 541 } 542 } 543 return; 544 } 545 546 // Keep track of actually launched affiliated tasks 547 MetricsLogger.count(mContext, "overview_affiliated_task_launch", 1); 548 549 // Launch the task 550 ssp.startActivityFromRecents(mContext, toTask.key.id, toTask.title, launchOpts); 551 } 552 553 public void showNextAffiliatedTask() { 554 // Keep track of when the affiliated task is triggered 555 MetricsLogger.count(mContext, "overview_affiliated_task_next", 1); 556 showRelativeAffiliatedTask(true); 557 } 558 559 public void showPrevAffiliatedTask() { 560 // Keep track of when the affiliated task is triggered 561 MetricsLogger.count(mContext, "overview_affiliated_task_prev", 1); 562 showRelativeAffiliatedTask(false); 563 } 564 565 public void dockTopTask(int topTaskId, int dragMode, 566 int stackCreateMode, Rect initialBounds) { 567 SystemServicesProxy ssp = Recents.getSystemServices(); 568 569 // Make sure we inform DividerView before we actually start the activity so we can change 570 // the resize mode already. 571 if (ssp.moveTaskToDockedStack(topTaskId, stackCreateMode, initialBounds)) { 572 EventBus.getDefault().send(new DockingTopTaskEvent(dragMode)); 573 showRecents( 574 false /* triggeredFromAltTab */, 575 dragMode == NavigationBarGestureHelper.DRAG_MODE_RECENTS, 576 false /* animate */, 577 true /* launchedWhileDockingTask*/); 578 } 579 } 580 581 /** 582 * Returns the preloaded load plan and invalidates it. 583 */ 584 public static RecentsTaskLoadPlan consumeInstanceLoadPlan() { 585 RecentsTaskLoadPlan plan = sInstanceLoadPlan; 586 sInstanceLoadPlan = null; 587 return plan; 588 } 589 590 /** 591 * Reloads all the layouts for the header bar transition. 592 */ 593 private void reloadHeaderBarLayout() { 594 Resources res = mContext.getResources(); 595 LayoutInflater inflater = LayoutInflater.from(mContext); 596 597 mStatusBarHeight = res.getDimensionPixelSize( 598 com.android.internal.R.dimen.status_bar_height); 599 mNavBarHeight = res.getDimensionPixelSize( 600 com.android.internal.R.dimen.navigation_bar_height); 601 mNavBarWidth = res.getDimensionPixelSize( 602 com.android.internal.R.dimen.navigation_bar_width); 603 mTaskBarHeight = res.getDimensionPixelSize( 604 R.dimen.recents_task_bar_height); 605 mDummyStackView = new TaskStackView(mContext, new TaskStack()); 606 mHeaderBar = (TaskViewHeader) inflater.inflate(R.layout.recents_task_view_header, 607 null, false); 608 } 609 610 /** 611 * Prepares the header bar layout for the next transition, if the task view bounds has changed 612 * since the last call, it will attempt to re-measure and layout the header bar to the new size. 613 * 614 * @param tryAndBindSearchWidget if set, will attempt to fetch and bind the search widget if one 615 * is not already bound (can be expensive) 616 * @param stack the stack to initialize the stack layout with 617 */ 618 private void updateHeaderBarLayout(boolean tryAndBindSearchWidget, 619 TaskStack stack) { 620 RecentsConfiguration config = Recents.getConfiguration(); 621 SystemServicesProxy ssp = Recents.getSystemServices(); 622 Rect systemInsets = new Rect(); 623 ssp.getStableInsets(systemInsets); 624 Rect windowRect = ssp.getWindowRect(); 625 calculateWindowStableInsets(systemInsets, windowRect); 626 windowRect.offsetTo(0, 0); 627 628 // Update the configuration for the current state 629 config.update(systemInsets); 630 631 if (RecentsDebugFlags.Static.EnableSearchBar && tryAndBindSearchWidget) { 632 // Try and pre-emptively bind the search widget on startup to ensure that we 633 // have the right thumbnail bounds to animate to. 634 // Note: We have to reload the widget id before we get the task stack bounds below 635 if (ssp.getOrBindSearchAppWidget(mContext, mAppWidgetHost) != null) { 636 config.getSearchBarBounds(windowRect, mStatusBarHeight, mSearchBarBounds); 637 } 638 } 639 config.getTaskStackBounds(windowRect, systemInsets.top, systemInsets.right, 640 mSearchBarBounds, mTaskStackBounds); 641 642 // Rebind the header bar and draw it for the transition 643 TaskStackLayoutAlgorithm algo = mDummyStackView.getStackAlgorithm(); 644 Rect taskStackBounds = new Rect(mTaskStackBounds); 645 algo.setSystemInsets(systemInsets); 646 if (stack != null) { 647 algo.initialize(taskStackBounds, 648 TaskStackLayoutAlgorithm.StackState.getStackStateForStack(stack)); 649 } 650 Rect taskViewBounds = algo.getUntransformedTaskViewBounds(); 651 if (!taskViewBounds.equals(mLastTaskViewBounds)) { 652 mLastTaskViewBounds.set(taskViewBounds); 653 654 int taskViewWidth = taskViewBounds.width(); 655 synchronized (mHeaderBarLock) { 656 mHeaderBar.measure( 657 View.MeasureSpec.makeMeasureSpec(taskViewWidth, View.MeasureSpec.EXACTLY), 658 View.MeasureSpec.makeMeasureSpec(mTaskBarHeight, View.MeasureSpec.EXACTLY)); 659 mHeaderBar.layout(0, 0, taskViewWidth, mTaskBarHeight); 660 } 661 } 662 } 663 664 /** 665 * Given the stable insets and the rect for our window, calculates the insets that affect our 666 * window. 667 */ 668 private void calculateWindowStableInsets(Rect inOutInsets, Rect windowRect) { 669 Rect displayRect = Recents.getSystemServices().getDisplayRect(); 670 671 // Display rect without insets - available app space 672 Rect appRect = new Rect(displayRect); 673 appRect.inset(inOutInsets); 674 675 // Our window intersected with available app space 676 Rect windowRectWithInsets = new Rect(windowRect); 677 windowRectWithInsets.intersect(appRect); 678 inOutInsets.left = windowRectWithInsets.left - windowRect.left; 679 inOutInsets.top = windowRectWithInsets.top - windowRect.top; 680 inOutInsets.right = windowRect.right - windowRectWithInsets.right; 681 inOutInsets.bottom = windowRect.bottom - windowRectWithInsets.bottom; 682 } 683 684 /** 685 * Preloads the icon of a task. 686 */ 687 private void preloadIcon(ActivityManager.RunningTaskInfo task) { 688 // Ensure that we load the running task's icon 689 RecentsTaskLoadPlan.Options launchOpts = new RecentsTaskLoadPlan.Options(); 690 launchOpts.runningTaskId = task.id; 691 launchOpts.loadThumbnails = false; 692 launchOpts.onlyLoadForCache = true; 693 Recents.getTaskLoader().loadTasks(mContext, sInstanceLoadPlan, launchOpts); 694 } 695 696 /** 697 * Caches the header thumbnail used for a window animation asynchronously into 698 * {@link #mThumbnailTransitionBitmapCache}. 699 */ 700 private void preCacheThumbnailTransitionBitmapAsync(ActivityManager.RunningTaskInfo topTask, 701 TaskStack stack, TaskStackView stackView) { 702 preloadIcon(topTask); 703 704 // Update the header bar if necessary 705 updateHeaderBarLayout(false /* tryAndBindSearchWidget */, stack); 706 707 // Update the destination rect 708 mDummyStackView.updateLayoutForStack(stack); 709 final Task toTask = new Task(); 710 final TaskViewTransform toTransform = getThumbnailTransitionTransform(stackView, toTask); 711 ForegroundThread.getHandler().postAtFrontOfQueue(new Runnable() { 712 @Override 713 public void run() { 714 final Bitmap transitionBitmap = drawThumbnailTransitionBitmap(toTask, toTransform); 715 mHandler.post(new Runnable() { 716 @Override 717 public void run() { 718 mThumbnailTransitionBitmapCache = transitionBitmap; 719 mThumbnailTransitionBitmapCacheKey = toTask; 720 } 721 }); 722 } 723 }); 724 } 725 726 /** 727 * Creates the activity options for a unknown state->recents transition. 728 */ 729 private ActivityOptions getUnknownTransitionActivityOptions() { 730 return ActivityOptions.makeCustomAnimation(mContext, 731 R.anim.recents_from_unknown_enter, 732 R.anim.recents_from_unknown_exit, 733 mHandler, null); 734 } 735 736 /** 737 * Creates the activity options for a home->recents transition. 738 */ 739 private ActivityOptions getHomeTransitionActivityOptions(boolean fromSearchHome) { 740 if (fromSearchHome) { 741 return ActivityOptions.makeCustomAnimation(mContext, 742 R.anim.recents_from_search_launcher_enter, 743 R.anim.recents_from_search_launcher_exit, 744 mHandler, null); 745 } 746 return ActivityOptions.makeCustomAnimation(mContext, 747 R.anim.recents_from_launcher_enter, 748 R.anim.recents_from_launcher_exit, 749 mHandler, null); 750 } 751 752 /** 753 * Creates the activity options for an app->recents transition. 754 */ 755 private ActivityOptions getThumbnailTransitionActivityOptions( 756 ActivityManager.RunningTaskInfo topTask, TaskStackView stackView) { 757 if (topTask.stackId == FREEFORM_WORKSPACE_STACK_ID) { 758 ArrayList<AppTransitionAnimationSpec> specs = new ArrayList<>(); 759 ArrayList<Task> tasks = stackView.getStack().getStackTasks(); 760 TaskStackLayoutAlgorithm stackLayout = stackView.getStackAlgorithm(); 761 TaskStackViewScroller stackScroller = stackView.getScroller(); 762 763 stackView.updateToInitialState(); 764 765 for (int i = tasks.size() - 1; i >= 0; i--) { 766 Task task = tasks.get(i); 767 if (task.isFreeformTask()) { 768 mTmpTransform = stackLayout.getStackTransformScreenCoordinates(task, 769 stackScroller.getStackScroll(), mTmpTransform, null); 770 Rect toTaskRect = new Rect(); 771 mTmpTransform.rect.round(toTaskRect); 772 Bitmap thumbnail = getThumbnailBitmap(topTask, task, mTmpTransform); 773 specs.add(new AppTransitionAnimationSpec(task.key.id, thumbnail, toTaskRect)); 774 } 775 } 776 AppTransitionAnimationSpec[] specsArray = new AppTransitionAnimationSpec[specs.size()]; 777 specs.toArray(specsArray); 778 return ActivityOptions.makeThumbnailAspectScaleDownAnimation(mDummyStackView, 779 specsArray, mHandler, null, this); 780 } else { 781 // Update the destination rect 782 Task toTask = new Task(); 783 TaskViewTransform toTransform = getThumbnailTransitionTransform(stackView, toTask); 784 RectF toTaskRect = toTransform.rect; 785 Bitmap thumbnail = getThumbnailBitmap(topTask, toTask, toTransform); 786 if (thumbnail != null) { 787 return ActivityOptions.makeThumbnailAspectScaleDownAnimation(mDummyStackView, 788 thumbnail, (int) toTaskRect.left, (int) toTaskRect.top, 789 (int) toTaskRect.width(), (int) toTaskRect.height(), mHandler, null); 790 } 791 // If both the screenshot and thumbnail fails, then just fall back to the default transition 792 return getUnknownTransitionActivityOptions(); 793 } 794 } 795 796 private Bitmap getThumbnailBitmap(ActivityManager.RunningTaskInfo topTask, Task toTask, 797 TaskViewTransform toTransform) { 798 Bitmap thumbnail; 799 if (mThumbnailTransitionBitmapCacheKey != null 800 && mThumbnailTransitionBitmapCacheKey.key != null 801 && mThumbnailTransitionBitmapCacheKey.key.equals(toTask.key)) { 802 thumbnail = mThumbnailTransitionBitmapCache; 803 mThumbnailTransitionBitmapCacheKey = null; 804 mThumbnailTransitionBitmapCache = null; 805 } else { 806 preloadIcon(topTask); 807 thumbnail = drawThumbnailTransitionBitmap(toTask, toTransform); 808 } 809 return thumbnail; 810 } 811 812 /** 813 * Returns the transition rect for the given task id. 814 */ 815 private TaskViewTransform getThumbnailTransitionTransform(TaskStackView stackView, 816 Task runningTaskOut) { 817 // Find the running task in the TaskStack 818 TaskStack stack = stackView.getStack(); 819 Task launchTask = stack.getLaunchTarget(); 820 if (launchTask != null) { 821 runningTaskOut.copyFrom(launchTask); 822 } else { 823 // If no task is specified or we can not find the task just use the front most one 824 launchTask = stack.getStackFrontMostTask(true /* includeFreeform */); 825 runningTaskOut.copyFrom(launchTask); 826 } 827 828 // Get the transform for the running task 829 stackView.updateToInitialState(); 830 mTmpTransform = stackView.getStackAlgorithm().getStackTransformScreenCoordinates(launchTask, 831 stackView.getScroller().getStackScroll(), mTmpTransform, null); 832 return mTmpTransform; 833 } 834 835 /** 836 * Draws the header of a task used for the window animation into a bitmap. 837 */ 838 private Bitmap drawThumbnailTransitionBitmap(Task toTask, TaskViewTransform toTransform) { 839 SystemServicesProxy ssp = Recents.getSystemServices(); 840 if (toTransform != null && toTask.key != null) { 841 Bitmap thumbnail; 842 synchronized (mHeaderBarLock) { 843 int toHeaderWidth = (int) toTransform.rect.width(); 844 int toHeaderHeight = (int) (mHeaderBar.getMeasuredHeight() * toTransform.scale); 845 boolean disabledInSafeMode = !toTask.isSystemApp && ssp.isInSafeMode(); 846 mHeaderBar.onTaskViewSizeChanged((int) toTransform.rect.width(), 847 (int) toTransform.rect.height()); 848 thumbnail = Bitmap.createBitmap(toHeaderWidth, toHeaderHeight, 849 Bitmap.Config.ARGB_8888); 850 if (RecentsDebugFlags.Static.EnableTransitionThumbnailDebugMode) { 851 thumbnail.eraseColor(0xFFff0000); 852 } else { 853 Canvas c = new Canvas(thumbnail); 854 c.scale(toTransform.scale, toTransform.scale); 855 mHeaderBar.rebindToTask(toTask, false /* touchExplorationEnabled */, 856 disabledInSafeMode); 857 mHeaderBar.setDimAlpha(toTransform.dimAlpha); 858 mHeaderBar.draw(c); 859 c.setBitmap(null); 860 } 861 } 862 return thumbnail.createAshmemBitmap(); 863 } 864 return null; 865 } 866 867 /** 868 * Shows the recents activity 869 */ 870 private void startRecentsActivity(ActivityManager.RunningTaskInfo topTask, 871 boolean isTopTaskHome, boolean animate) { 872 RecentsTaskLoader loader = Recents.getTaskLoader(); 873 874 // In the case where alt-tab is triggered, we never get a preloadRecents() call, so we 875 // should always preload the tasks now. If we are dragging in recents, reload them as 876 // the stacks might have changed. 877 if (mLaunchedWhileDocking || mTriggeredFromAltTab ||sInstanceLoadPlan == null) { 878 // Create a new load plan if preloadRecents() was never triggered 879 sInstanceLoadPlan = loader.createLoadPlan(mContext); 880 } 881 if (mLaunchedWhileDocking || mTriggeredFromAltTab || !sInstanceLoadPlan.hasTasks()) { 882 loader.preloadTasks(sInstanceLoadPlan, topTask.id, isTopTaskHome); 883 } 884 TaskStack stack = sInstanceLoadPlan.getTaskStack(); 885 886 // Update the header bar if necessary 887 updateHeaderBarLayout(false /* tryAndBindSearchWidget */, stack); 888 889 // Prepare the dummy stack for the transition 890 mDummyStackView.updateLayoutForStack(stack); 891 TaskStackLayoutAlgorithm.VisibilityReport stackVr = 892 mDummyStackView.computeStackVisibilityReport(); 893 894 if (!animate) { 895 ActivityOptions opts = ActivityOptions.makeCustomAnimation(mContext, -1, -1); 896 startRecentsActivity(topTask, opts, false /* fromHome */, 897 false /* fromSearchHome */, false /* fromThumbnail*/, stackVr); 898 return; 899 } 900 901 boolean hasRecentTasks = stack.getTaskCount() > 0; 902 boolean useThumbnailTransition = (topTask != null) && !isTopTaskHome && hasRecentTasks; 903 904 if (useThumbnailTransition) { 905 // Try starting with a thumbnail transition 906 ActivityOptions opts = getThumbnailTransitionActivityOptions(topTask, mDummyStackView); 907 if (opts != null) { 908 startRecentsActivity(topTask, opts, false /* fromHome */, 909 false /* fromSearchHome */, true /* fromThumbnail */, stackVr); 910 } else { 911 // Fall through below to the non-thumbnail transition 912 useThumbnailTransition = false; 913 } 914 } 915 916 if (!useThumbnailTransition) { 917 // If there is no thumbnail transition, but is launching from home into recents, then 918 // use a quick home transition and do the animation from home 919 if (hasRecentTasks) { 920 SystemServicesProxy ssp = Recents.getSystemServices(); 921 String homeActivityPackage = ssp.getHomeActivityPackageName(); 922 String searchWidgetPackage = null; 923 if (RecentsDebugFlags.Static.EnableSearchBar) { 924 searchWidgetPackage = Prefs.getString(mContext, 925 Prefs.Key.OVERVIEW_SEARCH_APP_WIDGET_PACKAGE, null); 926 } else { 927 AppWidgetProviderInfo searchWidgetInfo = ssp.resolveSearchAppWidget(); 928 if (searchWidgetInfo != null) { 929 searchWidgetPackage = searchWidgetInfo.provider.getPackageName(); 930 } 931 } 932 933 // Determine whether we are coming from a search owned home activity 934 boolean fromSearchHome = (homeActivityPackage != null) && 935 homeActivityPackage.equals(searchWidgetPackage); 936 ActivityOptions opts = getHomeTransitionActivityOptions(fromSearchHome); 937 startRecentsActivity(topTask, opts, true /* fromHome */, fromSearchHome, 938 false /* fromThumbnail */, stackVr); 939 } else { 940 // Otherwise we do the normal fade from an unknown source 941 ActivityOptions opts = getUnknownTransitionActivityOptions(); 942 startRecentsActivity(topTask, opts, true /* fromHome */, 943 false /* fromSearchHome */, false /* fromThumbnail */, stackVr); 944 } 945 } 946 mLastToggleTime = SystemClock.elapsedRealtime(); 947 } 948 949 /** 950 * Starts the recents activity. 951 */ 952 private void startRecentsActivity(ActivityManager.RunningTaskInfo topTask, 953 ActivityOptions opts, boolean fromHome, boolean fromSearchHome, 954 boolean fromThumbnail, TaskStackLayoutAlgorithm.VisibilityReport vr) { 955 // Update the configuration based on the launch options 956 RecentsConfiguration config = Recents.getConfiguration(); 957 RecentsActivityLaunchState launchState = config.getLaunchState(); 958 launchState.launchedFromHome = fromSearchHome || fromHome; 959 launchState.launchedFromSearchHome = fromSearchHome; 960 launchState.launchedFromApp = fromThumbnail || mLaunchedWhileDocking; 961 launchState.launchedFromAppDocked = mLaunchedWhileDocking; 962 launchState.launchedToTaskId = (topTask != null) ? topTask.id : -1; 963 launchState.launchedWithAltTab = mTriggeredFromAltTab; 964 launchState.launchedReuseTaskStackViews = mCanReuseTaskStackViews; 965 launchState.launchedNumVisibleTasks = vr.numVisibleTasks; 966 launchState.launchedNumVisibleThumbnails = vr.numVisibleThumbnails; 967 launchState.launchedHasConfigurationChanged = false; 968 launchState.launchedViaDragGesture = mDraggingInRecents; 969 launchState.launchedWhileDocking = mLaunchedWhileDocking; 970 971 Intent intent = new Intent(); 972 intent.setClassName(RECENTS_PACKAGE, mRecentsIntentActivityName); 973 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK 974 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS 975 | Intent.FLAG_ACTIVITY_TASK_ON_HOME); 976 977 if (opts != null) { 978 mContext.startActivityAsUser(intent, opts.toBundle(), UserHandle.CURRENT); 979 } else { 980 mContext.startActivityAsUser(intent, UserHandle.CURRENT); 981 } 982 mCanReuseTaskStackViews = true; 983 EventBus.getDefault().send(new RecentsActivityStartingEvent()); 984 } 985 986 /**** OnAnimationFinishedListener Implementation ****/ 987 988 @Override 989 public void onAnimationFinished() { 990 EventBus.getDefault().post(new EnterRecentsWindowLastAnimationFrameEvent()); 991 } 992} 993