diff --git a/aconfig/launcher.aconfig b/aconfig/launcher.aconfig
index 0855de741f..368af66803 100644
--- a/aconfig/launcher.aconfig
+++ b/aconfig/launcher.aconfig
@@ -383,13 +383,6 @@ flag {
bug: "345760034"
}
-flag {
- name: "taskbar_overflow"
- namespace: "launcher"
- description: "Show recent apps in the taskbar overflow."
- bug: "368119679"
-}
-
flag {
name: "enable_recents_window_proto_log"
namespace: "lse_desktop_experience"
diff --git a/quickstep/res/layout/task_app_timer_toast.xml b/quickstep/res/layout/task_app_timer_toast.xml
new file mode 100644
index 0000000000..694d1ce497
--- /dev/null
+++ b/quickstep/res/layout/task_app_timer_toast.xml
@@ -0,0 +1,32 @@
+
+
diff --git a/quickstep/res/layout/task_content_view.xml b/quickstep/res/layout/task_content_view.xml
index 478ee55c06..28744b6ab4 100644
--- a/quickstep/res/layout/task_content_view.xml
+++ b/quickstep/res/layout/task_content_view.xml
@@ -14,21 +14,43 @@
~ limitations under the License.
-->
+ android:layout_height="wrap_content"
+ app:layout_constraintStart_toStartOf="parent"
+ app:layout_constraintEnd_toEndOf="parent"
+ app:layout_constraintTop_toTopOf="parent"
+ />
+ app:layout_constraintTop_toTopOf="parent"
+ app:layout_constraintBottom_toBottomOf="parent"
+ app:layout_constraintEnd_toEndOf="parent"
+ app:layout_constraintStart_toStartOf="parent"
+ />
+
\ No newline at end of file
diff --git a/quickstep/src/com/android/launcher3/hybridhotseat/HotseatEduController.java b/quickstep/src/com/android/launcher3/hybridhotseat/HotseatEduController.java
index b77c43fc2f..7c53360ea4 100644
--- a/quickstep/src/com/android/launcher3/hybridhotseat/HotseatEduController.java
+++ b/quickstep/src/com/android/launcher3/hybridhotseat/HotseatEduController.java
@@ -33,7 +33,6 @@ import com.android.launcher3.Utilities;
import com.android.launcher3.Workspace;
import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.model.data.WorkspaceItemInfo;
-import com.android.launcher3.util.IntArray;
import com.android.launcher3.views.ArrowTipView;
import com.android.launcher3.views.Snackbar;
@@ -57,7 +56,6 @@ public class HotseatEduController {
private HotseatEduDialog mActiveDialog;
private ArrayList mNewItems = new ArrayList<>();
- private IntArray mNewScreens = null;
HotseatEduController(Launcher launcher) {
mLauncher = launcher;
@@ -96,7 +94,6 @@ public class HotseatEduController {
}
if (pageId == -1) {
pageId = mLauncher.getModel().getModelDbController().getNewScreenId();
- mNewScreens = IntArray.wrap(pageId);
}
boolean isPortrait = !mLauncher.getDeviceProfile().isVerticalBarLayout();
int hotseatItemsNum = mLauncher.getDeviceProfile().numShownHotseatIcons;
@@ -117,18 +114,7 @@ public class HotseatEduController {
void moveHotseatItems() {
mHotseat.removeAllViewsInLayout();
if (!mNewItems.isEmpty()) {
- int lastPage = mNewItems.get(mNewItems.size() - 1).screenId;
- ArrayList animated = new ArrayList<>();
- ArrayList nonAnimated = new ArrayList<>();
-
- for (ItemInfo info : mNewItems) {
- if (info.screenId == lastPage) {
- animated.add(info);
- } else {
- nonAnimated.add(info);
- }
- }
- mLauncher.bindAppsAdded(mNewScreens, nonAnimated, animated);
+ mLauncher.bindItemsAdded(mNewItems);
}
}
diff --git a/quickstep/src/com/android/launcher3/taskbar/KeyboardQuickSwitchController.java b/quickstep/src/com/android/launcher3/taskbar/KeyboardQuickSwitchController.java
index a434cd1b37..da70bb9a76 100644
--- a/quickstep/src/com/android/launcher3/taskbar/KeyboardQuickSwitchController.java
+++ b/quickstep/src/com/android/launcher3/taskbar/KeyboardQuickSwitchController.java
@@ -15,6 +15,8 @@
*/
package com.android.launcher3.taskbar;
+import static android.window.DesktopModeFlags.ENABLE_TASKBAR_OVERFLOW;
+
import static com.android.launcher3.taskbar.TaskbarDesktopExperienceFlags.enableAltTabKqsFlatenning;
import static com.android.launcher3.taskbar.TaskbarDesktopExperienceFlags.enableAltTabKqsOnConnectedDisplays;
@@ -27,7 +29,6 @@ import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
-import com.android.launcher3.Flags;
import com.android.launcher3.R;
import com.android.launcher3.taskbar.overlay.TaskbarOverlayContext;
import com.android.launcher3.taskbar.overlay.TaskbarOverlayDragLayer;
@@ -187,7 +188,7 @@ public final class KeyboardQuickSwitchController implements
}
mOverlayContext = mControllers.taskbarOverlayController.requestWindow();
- if (Flags.taskbarOverflow()) {
+ if (ENABLE_TASKBAR_OVERFLOW.isTrue()) {
mOverlayContext.getDragLayer().addTouchController(this);
}
KeyboardQuickSwitchView keyboardQuickSwitchView =
@@ -239,8 +240,8 @@ public final class KeyboardQuickSwitchController implements
}
private boolean shouldExcludeTask(GroupTask task, Set taskIdsToExclude) {
- return Flags.taskbarOverflow() && task.getTasks().stream().anyMatch(
- t -> taskIdsToExclude.contains(t.key.id));
+ return ENABLE_TASKBAR_OVERFLOW.isTrue()
+ && task.getTasks().stream().anyMatch(t -> taskIdsToExclude.contains(t.key.id));
}
private void processLoadedTasks(List tasks, Set taskIdsToExclude) {
@@ -376,7 +377,7 @@ public final class KeyboardQuickSwitchController implements
public boolean onControllerInterceptTouchEvent(MotionEvent ev) {
if (mQuickSwitchViewController == null
|| mOverlayContext == null
- || !Flags.taskbarOverflow()) {
+ || !ENABLE_TASKBAR_OVERFLOW.isTrue()) {
return false;
}
@@ -472,7 +473,7 @@ public final class KeyboardQuickSwitchController implements
}
void onCloseComplete() {
- if (Flags.taskbarOverflow() && mOverlayContext != null) {
+ if (ENABLE_TASKBAR_OVERFLOW.isTrue() && mOverlayContext != null) {
mOverlayContext.getDragLayer()
.removeTouchController(KeyboardQuickSwitchController.this);
}
diff --git a/quickstep/src/com/android/launcher3/taskbar/KeyboardQuickSwitchViewController.java b/quickstep/src/com/android/launcher3/taskbar/KeyboardQuickSwitchViewController.java
index 7616ebd8d0..d31051dda4 100644
--- a/quickstep/src/com/android/launcher3/taskbar/KeyboardQuickSwitchViewController.java
+++ b/quickstep/src/com/android/launcher3/taskbar/KeyboardQuickSwitchViewController.java
@@ -15,6 +15,8 @@
*/
package com.android.launcher3.taskbar;
+import static android.window.DesktopModeFlags.ENABLE_TASKBAR_OVERFLOW;
+
import static com.android.launcher3.desktop.DesktopAppLaunchTransition.AppLaunchType.UNMINIMIZE;
import static com.android.launcher3.taskbar.TaskbarDesktopExperienceFlags.enableAltTabKqsFlatenning;
import static com.android.launcher3.util.Executors.MAIN_EXECUTOR;
@@ -35,7 +37,6 @@ import androidx.annotation.Nullable;
import com.android.internal.jank.Cuj;
import com.android.launcher3.DeviceProfile;
-import com.android.launcher3.Flags;
import com.android.launcher3.R;
import com.android.launcher3.Utilities;
import com.android.launcher3.anim.AnimatorListeners;
@@ -124,7 +125,7 @@ public class KeyboardQuickSwitchViewController {
mWasDesktopTaskFilteredOut = wasDesktopTaskFilteredOut;
mWasOpenedFromTaskbar = wasOpenedFromTaskbar;
- if (Flags.taskbarOverflow() && wasOpenedFromTaskbar) {
+ if (ENABLE_TASKBAR_OVERFLOW.isTrue() && wasOpenedFromTaskbar) {
mKeyboardQuickSwitchView.enableScrollArrowSupport();
}
diff --git a/quickstep/src/com/android/launcher3/taskbar/TaskbarLauncherStateController.java b/quickstep/src/com/android/launcher3/taskbar/TaskbarLauncherStateController.java
index f44cae927d..a97893f75a 100644
--- a/quickstep/src/com/android/launcher3/taskbar/TaskbarLauncherStateController.java
+++ b/quickstep/src/com/android/launcher3/taskbar/TaskbarLauncherStateController.java
@@ -505,6 +505,10 @@ public class TaskbarLauncherStateController {
+ ", toAlignment: " + toAlignment);
}
mControllers.bubbleControllers.ifPresent(controllers -> {
+ // Ignore state changes when taskbar is destroyed
+ if (mControllers.taskbarActivityContext.isDestroyed()) {
+ return;
+ }
// Show the bubble bar when on launcher home (hotseat icons visible) or in overview
boolean onOverview = isInLauncher && mLauncherState == LauncherState.OVERVIEW;
boolean hotseatIconsVisible = isInLauncher && mLauncherState.areElementsVisible(
diff --git a/quickstep/src/com/android/launcher3/taskbar/TaskbarModelCallbacks.java b/quickstep/src/com/android/launcher3/taskbar/TaskbarModelCallbacks.java
index 836c06cb38..b610f6786e 100644
--- a/quickstep/src/com/android/launcher3/taskbar/TaskbarModelCallbacks.java
+++ b/quickstep/src/com/android/launcher3/taskbar/TaskbarModelCallbacks.java
@@ -29,12 +29,12 @@ import com.android.launcher3.LauncherSettings.Favorites;
import com.android.launcher3.celllayout.CellInfo;
import com.android.launcher3.model.BgDataModel;
import com.android.launcher3.model.BgDataModel.FixedContainerItems;
+import com.android.launcher3.model.StringCache;
import com.android.launcher3.model.data.AppInfo;
import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.taskbar.TaskbarView.TaskbarLayoutParams;
import com.android.launcher3.util.ComponentKey;
-import com.android.launcher3.util.IntArray;
-import com.android.launcher3.util.IntSet;
+import com.android.launcher3.util.IntSparseArrayMap;
import com.android.launcher3.util.ItemInfoMatcher;
import com.android.launcher3.util.LauncherBindableItemsContainer;
import com.android.launcher3.util.PackageUserKey;
@@ -42,7 +42,6 @@ import com.android.launcher3.util.Preconditions;
import com.android.quickstep.util.GroupTask;
import java.io.PrintWriter;
-import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
@@ -68,7 +67,6 @@ public class TaskbarModelCallbacks implements
// Used to defer any UI updates during the SUW unstash animation.
private boolean mDeferUpdatesForSUW;
private Runnable mDeferredUpdates;
- private boolean mBindingItems = false;
public TaskbarModelCallbacks(
TaskbarActivityContext context, TaskbarView container) {
@@ -81,31 +79,25 @@ public class TaskbarModelCallbacks implements
}
@Override
- public void startBinding() {
- mBindingItems = true;
+ public void bindCompleteModel(IntSparseArrayMap itemIdMap,
+ List extraItems, StringCache stringCache, boolean isBindingSync) {
mHotseatItems.clear();
mPredictedItems = Collections.emptyList();
- }
+ handleItemsAdded(itemIdMap);
- @Override
- public void finishBindingItems(IntSet pagesBoundFirst) {
- mBindingItems = false;
+ for (FixedContainerItems item: extraItems) {
+ if (item.containerId == Favorites.CONTAINER_HOTSEAT_PREDICTION) {
+ mPredictedItems = item.items;
+ } else if (item.containerId == Favorites.CONTAINER_PREDICTION) {
+ mControllers.taskbarAllAppsController.setPredictedApps(item.items);
+ }
+ }
commitItemsToUI();
}
@Override
- public void bindAppsAdded(IntArray newScreens, ArrayList addNotAnimated,
- ArrayList addAnimated) {
- boolean add1 = handleItemsAdded(addNotAnimated);
- boolean add2 = handleItemsAdded(addAnimated);
- if (add1 || add2) {
- commitItemsToUI();
- }
- }
-
- @Override
- public void bindItems(List shortcuts, boolean forceAnimateIcons) {
- if (handleItemsAdded(shortcuts)) {
+ public void bindItemsAdded(List items) {
+ if (handleItemsAdded(items)) {
commitItemsToUI();
}
}
@@ -184,10 +176,6 @@ public class TaskbarModelCallbacks implements
}
private void commitItemsToUI() {
- if (mBindingItems) {
- return;
- }
-
ItemInfo[] hotseatItemInfos =
new ItemInfo[mContext.getDeviceProfile().numShownHotseatIcons];
int predictionSize = mPredictedItems.size();
diff --git a/quickstep/src/com/android/launcher3/taskbar/TaskbarView.java b/quickstep/src/com/android/launcher3/taskbar/TaskbarView.java
index ded746a6f1..e334a49e31 100644
--- a/quickstep/src/com/android/launcher3/taskbar/TaskbarView.java
+++ b/quickstep/src/com/android/launcher3/taskbar/TaskbarView.java
@@ -16,6 +16,7 @@
package com.android.launcher3.taskbar;
import static android.view.accessibility.AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED;
+import static android.window.DesktopModeFlags.ENABLE_TASKBAR_OVERFLOW;
import static android.window.DesktopModeFlags.ENABLE_TASKBAR_RECENTS_LAYOUT_TRANSITION;
import static com.android.launcher3.BubbleTextView.DISPLAY_TASKBAR;
@@ -193,7 +194,7 @@ public class TaskbarView extends FrameLayout implements FolderIcon.FolderIconPar
mTaskbarDividerContainer = new TaskbarDividerContainer(context);
}
- if (Flags.taskbarOverflow()) {
+ if (ENABLE_TASKBAR_OVERFLOW.isTrue()) {
mTaskbarOverflowView = TaskbarOverflowView.inflateIcon(
R.layout.taskbar_overflow_view, this,
mIconTouchSize, mItemPadding);
@@ -261,7 +262,7 @@ public class TaskbarView extends FrameLayout implements FolderIcon.FolderIconPar
* that should be shown in the taskbar.
*/
boolean updateMaxNumIcons() {
- if (!Flags.taskbarOverflow()) {
+ if (!ENABLE_TASKBAR_OVERFLOW.isTrue()) {
return false;
}
int oldMaxNumIcons = mMaxNumIcons;
@@ -359,7 +360,7 @@ public class TaskbarView extends FrameLayout implements FolderIcon.FolderIconPar
mControllerCallbacks.getOverflowOnLongClickListener());
}
- if (Flags.taskbarOverflow()) {
+ if (ENABLE_TASKBAR_OVERFLOW.isTrue()) {
mMaxNumIcons = calculateMaxNumIcons();
}
}
@@ -617,7 +618,7 @@ public class TaskbarView extends FrameLayout implements FolderIcon.FolderIconPar
}
private void updateRecents(List recentTasks, int hotseatSize) {
- boolean supportsOverflow = Flags.taskbarOverflow() && recentTasks.size() > 1;
+ boolean supportsOverflow = ENABLE_TASKBAR_OVERFLOW.isTrue() && recentTasks.size() > 1;
int overflowSize = 0;
boolean hasOverflow = false;
if (supportsOverflow && mTaskbarOverflowView != null) {
diff --git a/quickstep/src/com/android/launcher3/taskbar/TaskbarViewController.java b/quickstep/src/com/android/launcher3/taskbar/TaskbarViewController.java
index 2b3d05da3e..75ad9d3319 100644
--- a/quickstep/src/com/android/launcher3/taskbar/TaskbarViewController.java
+++ b/quickstep/src/com/android/launcher3/taskbar/TaskbarViewController.java
@@ -20,13 +20,13 @@ import static android.animation.LayoutTransition.CHANGE_APPEARING;
import static android.animation.LayoutTransition.CHANGE_DISAPPEARING;
import static android.animation.LayoutTransition.DISAPPEARING;
import static android.view.Display.DEFAULT_DISPLAY;
+import static android.window.DesktopModeFlags.ENABLE_TASKBAR_OVERFLOW;
import static android.window.DesktopModeFlags.ENABLE_TASKBAR_RECENTS_LAYOUT_TRANSITION;
import static com.android.app.animation.Interpolators.EMPHASIZED;
import static com.android.app.animation.Interpolators.FINAL_FRAME;
import static com.android.app.animation.Interpolators.LINEAR;
import static com.android.launcher3.Flags.enableScalingRevealHomeAnimation;
-import static com.android.launcher3.Flags.taskbarOverflow;
import static com.android.launcher3.LauncherAnimUtils.SCALE_PROPERTY;
import static com.android.launcher3.LauncherAnimUtils.VIEW_ALPHA;
import static com.android.launcher3.LauncherAnimUtils.VIEW_TRANSLATE_X;
@@ -782,7 +782,7 @@ public class TaskbarViewController implements TaskbarControllers.LoggableTaskbar
* @return A set of Task ids of running apps that are pinned in the taskbar.
*/
protected Set getTaskIdsForPinnedApps() {
- if (!taskbarOverflow()) {
+ if (!ENABLE_TASKBAR_OVERFLOW.isTrue()) {
return Collections.emptySet();
}
@@ -1229,6 +1229,11 @@ public class TaskbarViewController implements TaskbarControllers.LoggableTaskbar
} else {
taskbarWindowSize = deviceProfile.taskbarHeight + deviceProfile.getTaskbarOffsetY();
}
+ if (mBubbleControllers != null) {
+ int bubbleBarMaxHeight = mBubbleControllers.bubbleBarViewController
+ .getBubbleBarWithFlyoutMaximumHeight();
+ taskbarWindowSize = Math.max(taskbarWindowSize, bubbleBarMaxHeight);
+ }
mActivity.setTaskbarWindowSize(taskbarWindowSize);
mTaskbarNavButtonTranslationY.updateValue(-deviceProfile.getTaskbarOffsetY());
}
diff --git a/quickstep/src/com/android/launcher3/taskbar/overlay/TaskbarOverlayController.java b/quickstep/src/com/android/launcher3/taskbar/overlay/TaskbarOverlayController.java
index a5845d6231..55afefecfc 100644
--- a/quickstep/src/com/android/launcher3/taskbar/overlay/TaskbarOverlayController.java
+++ b/quickstep/src/com/android/launcher3/taskbar/overlay/TaskbarOverlayController.java
@@ -18,6 +18,7 @@ package com.android.launcher3.taskbar.overlay;
import static android.view.WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS;
import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_CONSUME_IME_INSETS;
import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
+import static android.window.DesktopModeFlags.ENABLE_TASKBAR_OVERFLOW;
import static com.android.launcher3.AbstractFloatingView.TYPE_ALL;
import static com.android.launcher3.AbstractFloatingView.TYPE_REBIND_SAFE;
@@ -315,7 +316,7 @@ public final class TaskbarOverlayController {
@Override
protected void handleClose(boolean animate) {
if (!mIsOpen) return;
- if (Flags.taskbarOverflow()) {
+ if (ENABLE_TASKBAR_OVERFLOW.isTrue()) {
// Mark the view closed before attempting to remove it, so the drag layer does not
// schedule another call to close. Needed for taskbar overflow in case the KQS
// view shown for taskbar overflow needs to be reshown - delayed close call would
diff --git a/quickstep/src/com/android/launcher3/uioverrides/touchcontrollers/TaskViewDismissTouchController.kt b/quickstep/src/com/android/launcher3/uioverrides/touchcontrollers/TaskViewDismissTouchController.kt
index 914925fd03..6c4c6fc0f7 100644
--- a/quickstep/src/com/android/launcher3/uioverrides/touchcontrollers/TaskViewDismissTouchController.kt
+++ b/quickstep/src/com/android/launcher3/uioverrides/touchcontrollers/TaskViewDismissTouchController.kt
@@ -107,6 +107,9 @@ CONTAINER : RecentsViewContainer {
}
override fun onControllerInterceptTouchEvent(ev: MotionEvent): Boolean {
+ if (isBlockedDuringDismissal) {
+ return true
+ }
if ((ev.action == MotionEvent.ACTION_UP || ev.action == MotionEvent.ACTION_CANCEL)) {
clearState()
}
diff --git a/quickstep/src/com/android/quickstep/fallback/window/RecentsWindowManager.kt b/quickstep/src/com/android/quickstep/fallback/window/RecentsWindowManager.kt
index b43ef36616..f2459b617a 100644
--- a/quickstep/src/com/android/quickstep/fallback/window/RecentsWindowManager.kt
+++ b/quickstep/src/com/android/quickstep/fallback/window/RecentsWindowManager.kt
@@ -235,12 +235,15 @@ constructor(
override fun destroy() {
super.destroy()
- Executors.MAIN_EXECUTOR.execute { onViewDestroyed() }
- cleanupRecentsWindow()
- callbacks?.removeListener(recentsAnimationListener)
- homeVisibilityState.removeListener(homeVisibilityListener)
- recentsWindowTracker.onContextDestroyed(this)
- recentsView?.destroy()
+ Executors.MAIN_EXECUTOR.execute {
+ tisBindHelper.onDestroy()
+ onViewDestroyed()
+ cleanupRecentsWindow()
+ callbacks?.removeListener(recentsAnimationListener)
+ homeVisibilityState.removeListener(homeVisibilityListener)
+ recentsWindowTracker.onContextDestroyed(this)
+ recentsView?.destroy()
+ }
}
fun startRecentsWindow(callbacks: RecentsAnimationCallbacks? = null) {
diff --git a/quickstep/src/com/android/quickstep/recents/data/TasksRepository.kt b/quickstep/src/com/android/quickstep/recents/data/TasksRepository.kt
index 5274ef3266..312d4538f1 100644
--- a/quickstep/src/com/android/quickstep/recents/data/TasksRepository.kt
+++ b/quickstep/src/com/android/quickstep/recents/data/TasksRepository.kt
@@ -46,30 +46,30 @@ class TasksRepository(
private val dispatcherProvider: DispatcherProvider,
) : RecentTasksRepository {
private val tasks = MutableStateFlow(MapForStateFlow(emptyMap()))
+ private var visibleTaskIds = emptySet()
private val taskRequests = HashMap>()
override fun getAllTaskData(forceRefresh: Boolean): Flow> {
if (forceRefresh) {
recentsModel.getTasks { newTaskList ->
val recentTasks =
- newTaskList
- .flatMap { groupTask -> groupTask.tasks }
- .associateBy { it.key.id }
- .also { newTaskMap ->
- // Clean tasks that are not in the latest group tasks list.
- val tasksNoLongerVisible = tasks.value.keys.subtract(newTaskMap.keys)
- removeTasks(tasksNoLongerVisible)
- }
+ newTaskList.flatMap { groupTask -> groupTask.tasks }.associateBy { it.key.id }
Log.d(
TAG,
"getAllTaskData: oldTasks ${tasks.value.keys}, newTasks: ${recentTasks.keys}",
)
- tasks.value = MapForStateFlow(recentTasks)
+ tasks.update { oldTaskList ->
+ // Copy retrieved visuals to new Task objects
+ recentTasks.forEach { (taskId, task) ->
+ task.thumbnail = oldTaskList[taskId]?.thumbnail
+ task.icon = oldTaskList[taskId]?.icon
+ task.title = oldTaskList[taskId]?.title
+ task.titleDescription = oldTaskList[taskId]?.titleDescription
+ }
+ MapForStateFlow(recentTasks)
+ }
- // Request data for tasks to prevent stale data.
- // This will prevent thumbnail and icon from being replaced and null due to
- // race condition. The new request will hit the cache and return immediately.
- taskRequests.keys.forEach(::requestTaskData)
+ updateTaskRequests()
}
}
return tasks.map { it.values.toList() }
@@ -83,29 +83,38 @@ class TasksRepository(
override fun getCurrentThumbnailById(taskId: Int) = tasks.value[taskId]?.thumbnail
override fun setVisibleTasks(visibleTaskIdList: Set) {
- val tasksNoLongerVisible = taskRequests.keys.subtract(visibleTaskIdList)
- val newlyVisibleTasks = visibleTaskIdList.subtract(taskRequests.keys)
- if (tasksNoLongerVisible.isNotEmpty() || newlyVisibleTasks.isNotEmpty()) {
+ visibleTaskIds = visibleTaskIdList
+ updateTaskRequests()
+ }
+
+ @Synchronized
+ private fun updateTaskRequests() {
+ val requestsNeeded = visibleTaskIds.intersect(tasks.value.keys)
+
+ val taskRequestIds = taskRequests.keys
+ val requestsNoLongerNeeded = taskRequestIds.subtract(requestsNeeded)
+ val newlyRequestedTasks = requestsNeeded.subtract(taskRequestIds)
+ if (requestsNoLongerNeeded.isNotEmpty() || newlyRequestedTasks.isNotEmpty()) {
Log.d(
TAG,
- "setVisibleTasks to: $visibleTaskIdList, " +
- "removed: $tasksNoLongerVisible, added: $newlyVisibleTasks",
+ "updateTaskRequests to: $requestsNeeded, " +
+ "removed: $requestsNoLongerNeeded, added: $newlyRequestedTasks",
)
}
// Remove tasks are no longer visible
- removeTasks(tasksNoLongerVisible)
+ removeTasks(requestsNoLongerNeeded)
// Add new tasks to be requested
- newlyVisibleTasks.forEach { taskId -> requestTaskData(taskId) }
+ newlyRequestedTasks.forEach { taskId -> requestTaskData(taskId) }
}
private fun requestTaskData(taskId: Int) {
val task = tasks.value[taskId] ?: return
+ Log.i(TAG, "requestTaskData: $taskId")
taskRequests[taskId] =
Pair(
task.key,
recentsCoroutineScope.launch(dispatcherProvider.background) {
- Log.i(TAG, "requestTaskData: $taskId")
val thumbnailFetchDeferred = async { fetchThumbnail(task) }
val iconFetchDeferred = async { fetchIcon(task) }
awaitAll(thumbnailFetchDeferred, iconFetchDeferred)
@@ -117,28 +126,30 @@ class TasksRepository(
if (tasksToRemove.isEmpty()) return
Log.i(TAG, "removeTasks: $tasksToRemove")
- tasksToRemove.forEach { taskId ->
- val request = taskRequests.remove(taskId) ?: return
- val (taskKey, job) = request
- job.cancel()
+ tasks.update { currentTasks ->
+ tasksToRemove.forEach { taskId ->
+ val request = taskRequests.remove(taskId) ?: return@forEach
+ val (taskKey, job) = request
+ job.cancel()
- // un-registering callbacks
- taskVisualsChangedDelegate.unregisterTaskIconChangedCallback(taskKey)
- taskVisualsChangedDelegate.unregisterTaskThumbnailChangedCallback(taskKey)
+ // un-registering callbacks
+ taskVisualsChangedDelegate.unregisterTaskIconChangedCallback(taskKey)
+ taskVisualsChangedDelegate.unregisterTaskThumbnailChangedCallback(taskKey)
- // Clearing Task to reduce memory footprint
- tasks.value[taskId]?.apply {
- thumbnail = null
- icon = null
- title = null
- titleDescription = null
+ // Clearing Task to reduce memory footprint
+ currentTasks[taskId]?.apply {
+ thumbnail = null
+ icon = null
+ title = null
+ titleDescription = null
+ }
}
+ MapForStateFlow(currentTasks)
}
- tasks.update { oldValue -> MapForStateFlow(oldValue) }
}
private suspend fun fetchIcon(task: Task) {
- updateIcon(task.key.id, getIconFromDataSource(task)) // Fetch icon from cache
+ updateIcon(task.key.id, getIconFromDataSource(task))
taskVisualsChangedDelegate.registerTaskIconChangedCallback(
task.key,
object : TaskIconChangedCallback {
@@ -180,17 +191,21 @@ class TasksRepository(
}
private fun updateIcon(taskId: Int, iconData: IconData) {
- val task = tasks.value[taskId] ?: return
- task.icon = iconData.icon
- task.titleDescription = iconData.contentDescription
- task.title = iconData.title
- tasks.update { oldValue -> MapForStateFlow(oldValue + (taskId to task)) }
+ tasks.update { currentTasks ->
+ currentTasks[taskId]?.apply {
+ icon = iconData.icon
+ titleDescription = iconData.contentDescription
+ title = iconData.title
+ }
+ MapForStateFlow(currentTasks)
+ }
}
private fun updateThumbnail(taskId: Int, thumbnail: ThumbnailData?) {
- val task = tasks.value[taskId] ?: return
- task.thumbnail = thumbnail
- tasks.update { oldValue -> MapForStateFlow(oldValue + (taskId to task)) }
+ tasks.update { currentTasks ->
+ currentTasks[taskId]?.thumbnail = thumbnail
+ MapForStateFlow(currentTasks)
+ }
}
private suspend fun getThumbnailFromDataSource(task: Task) =
diff --git a/quickstep/src/com/android/quickstep/recents/ui/mapper/TaskUiStateMapper.kt b/quickstep/src/com/android/quickstep/recents/ui/mapper/TaskUiStateMapper.kt
index 7425d361ee..e035015070 100644
--- a/quickstep/src/com/android/quickstep/recents/ui/mapper/TaskUiStateMapper.kt
+++ b/quickstep/src/com/android/quickstep/recents/ui/mapper/TaskUiStateMapper.kt
@@ -18,7 +18,10 @@ package com.android.quickstep.recents.ui.mapper
import android.view.View.OnClickListener
import com.android.launcher3.Flags.enableDesktopExplodedView
+import com.android.launcher3.R
+import com.android.launcher3.util.SplitConfigurationOptions.STAGE_POSITION_BOTTOM_OR_RIGHT
import com.android.quickstep.recents.ui.viewmodel.TaskData
+import com.android.quickstep.task.apptimer.TaskAppTimerUiState
import com.android.quickstep.task.thumbnail.TaskHeaderUiState
import com.android.quickstep.task.thumbnail.TaskThumbnailUiState
import com.android.quickstep.task.thumbnail.TaskThumbnailUiState.BackgroundOnly
@@ -105,4 +108,37 @@ object TaskUiStateMapper {
taskData.icon != null &&
taskData.titleDescription != null &&
clickCloseListener != null
+
+ /**
+ * Converts a [TaskData] object into a [TaskAppTimerUiState] for displaying an app timer toast
+ *
+ * @property taskData The [TaskData] to convert. Can be null or a specific sub-class.
+ * @property stagePosition the position of this task when shown as a group
+ * @return a [TaskAppTimerUiState] representing state for the information displayed in the app
+ * timer toast.
+ */
+ fun toTaskAppTimerUiState(
+ canShowAppTimer: Boolean,
+ stagePosition: Int,
+ taskData: TaskData?,
+ ): TaskAppTimerUiState =
+ when {
+ taskData !is TaskData.Data -> TaskAppTimerUiState.Uninitialized
+
+ !canShowAppTimer || taskData.remainingAppTimerDuration == null ->
+ TaskAppTimerUiState.NoTimer(taskDescription = taskData.titleDescription)
+
+ else ->
+ TaskAppTimerUiState.Timer(
+ taskDescription = taskData.titleDescription,
+ timeRemaining = taskData.remainingAppTimerDuration,
+ taskPackageName = taskData.packageName,
+ accessibilityActionId =
+ if (stagePosition == STAGE_POSITION_BOTTOM_OR_RIGHT) {
+ R.id.action_digital_wellbeing_bottom_right
+ } else {
+ R.id.action_digital_wellbeing_top_left
+ },
+ )
+ }
}
diff --git a/quickstep/src/com/android/quickstep/task/apptimer/DurationFormatter.kt b/quickstep/src/com/android/quickstep/task/apptimer/DurationFormatter.kt
new file mode 100644
index 0000000000..0c4a4d8331
--- /dev/null
+++ b/quickstep/src/com/android/quickstep/task/apptimer/DurationFormatter.kt
@@ -0,0 +1,60 @@
+/*
+ * Copyright (C) 2025 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.quickstep.task.apptimer
+
+import android.content.Context
+import android.icu.text.MeasureFormat
+import android.icu.util.Measure
+import android.icu.util.MeasureUnit
+import androidx.annotation.StringRes
+import java.time.Duration
+import java.util.Locale
+
+/** Formats the given duration as a user friendly text. */
+object DurationFormatter {
+ fun format(
+ context: Context,
+ duration: Duration,
+ @StringRes durationLessThanOneMinuteStringId: Int,
+ ): String {
+ val hours = Math.toIntExact(duration.toHours())
+ val minutes = Math.toIntExact(duration.minusHours(hours.toLong()).toMinutes())
+ return when {
+ // Apply FormatWidth.NARROW if both the hour part and the minute part are non-zero.
+ hours > 0 && minutes > 0 ->
+ MeasureFormat.getInstance(Locale.getDefault(), MeasureFormat.FormatWidth.NARROW)
+ .formatMeasures(
+ Measure(hours, MeasureUnit.HOUR),
+ Measure(minutes, MeasureUnit.MINUTE),
+ )
+ // Apply FormatWidth.WIDE if only the hour part is non-zero (unless forced).
+ hours > 0 ->
+ MeasureFormat.getInstance(Locale.getDefault(), MeasureFormat.FormatWidth.WIDE)
+ .formatMeasures(Measure(hours, MeasureUnit.HOUR))
+ // Apply FormatWidth.WIDE if only the minute part is non-zero (unless forced).
+ minutes > 0 ->
+ MeasureFormat.getInstance(Locale.getDefault(), MeasureFormat.FormatWidth.WIDE)
+ .formatMeasures(Measure(minutes, MeasureUnit.MINUTE))
+ // Use a specific string for usage less than one minute but non-zero.
+ duration > Duration.ZERO -> context.getString(durationLessThanOneMinuteStringId)
+ // Otherwise, return 0-minute string.
+ else ->
+ MeasureFormat.getInstance(Locale.getDefault(), MeasureFormat.FormatWidth.WIDE)
+ .formatMeasures(Measure(0, MeasureUnit.MINUTE))
+ }
+ }
+}
diff --git a/quickstep/src/com/android/quickstep/task/apptimer/TaskAppTimerUiState.kt b/quickstep/src/com/android/quickstep/task/apptimer/TaskAppTimerUiState.kt
new file mode 100644
index 0000000000..08c92db044
--- /dev/null
+++ b/quickstep/src/com/android/quickstep/task/apptimer/TaskAppTimerUiState.kt
@@ -0,0 +1,50 @@
+/*
+ * Copyright (C) 2025 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.quickstep.task.apptimer
+
+import androidx.annotation.IdRes
+import java.time.Duration
+
+/**
+ * UI state of the digital wellbeing app timer toast
+ *
+ * @property taskDescription description of the task for which the timer is being displayed.
+ */
+sealed class TaskAppTimerUiState(open val taskDescription: String?) {
+ /** Timer information not available in UI. */
+ data object Uninitialized : TaskAppTimerUiState(null)
+
+ /** No timer information to display */
+ data class NoTimer(override val taskDescription: String?) :
+ TaskAppTimerUiState(taskDescription)
+
+ /**
+ * Represents the UI state necessary to show an app timer on a task
+ *
+ * @property timeRemaining time remaining on the app timer for the application.
+ * @property taskDescription description of the task for which the timer is being displayed.
+ * @property taskPackageName package name for of the top component for the task's app.
+ * @property accessibilityActionId action id to use for tap like accessibility actions on this
+ * timer.
+ */
+ data class Timer(
+ val timeRemaining: Duration,
+ override val taskDescription: String?,
+ val taskPackageName: String,
+ @IdRes val accessibilityActionId: Int,
+ ) : TaskAppTimerUiState(taskDescription)
+}
diff --git a/quickstep/src/com/android/quickstep/task/apptimer/TimerTextHelper.kt b/quickstep/src/com/android/quickstep/task/apptimer/TimerTextHelper.kt
new file mode 100644
index 0000000000..0d0ca841f4
--- /dev/null
+++ b/quickstep/src/com/android/quickstep/task/apptimer/TimerTextHelper.kt
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2025 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.quickstep.task.apptimer
+
+import android.content.Context
+import com.android.launcher3.R
+import com.android.launcher3.Utilities
+import java.time.Duration
+
+/** A helper class that is responsible for building the digital wellbeing timer text. */
+class TimerTextHelper(private val context: Context, timeLeft: Duration) {
+ val formattedDuration =
+ DurationFormatter.format(context, timeLeft, R.string.shorter_duration_less_than_one_minute)
+
+ /** Provides the time left as a user friendly text that fits in the [availableWidth]. */
+ fun getTextThatFits(availableWidth: Int, textPaint: android.text.TextPaint): CharSequence {
+ val iconOnlyText = Utilities.prefixTextWithIcon(context, R.drawable.ic_hourglass_top, "")
+
+ if (availableWidth == 0) {
+ return iconOnlyText
+ }
+
+ // "$icon $formattedDuration left today"
+ val fullText =
+ Utilities.prefixTextWithIcon(
+ context,
+ R.drawable.ic_hourglass_top,
+ context.getString(R.string.time_left_for_app, formattedDuration),
+ )
+
+ val textWidth = textPaint.measureText(fullText, /* start= */ 0, /* end= */ fullText.length)
+ val textToWidthRatio = textWidth / availableWidth
+ return when {
+ textToWidthRatio > ICON_ONLY_WIDTH_RATIO_THRESHOLD ->
+ // "$icon"
+ iconOnlyText
+
+ textToWidthRatio > ICON_SHORT_TEXT_WIDTH_RATIO_THRESHOLD ->
+ // "$icon $formattedDuration"
+ Utilities.prefixTextWithIcon(
+ context,
+ R.drawable.ic_hourglass_top,
+ formattedDuration,
+ )
+
+ else -> fullText
+ }
+ }
+
+ companion object {
+ // If the full text ("$icon $formattedDuration left today") takes a lot more space than is
+ // available, it is likely short text won't fit either. So, we fallback to just an icon.
+ private const val ICON_ONLY_WIDTH_RATIO_THRESHOLD = 1.2f
+
+ // If the full text fits but leaves very little space, use short text instead for
+ // comfortable viewing.
+ private const val ICON_SHORT_TEXT_WIDTH_RATIO_THRESHOLD = 0.8f
+ }
+}
diff --git a/quickstep/src/com/android/quickstep/task/thumbnail/TaskContentView.kt b/quickstep/src/com/android/quickstep/task/thumbnail/TaskContentView.kt
index a010f81c1f..425448e89d 100644
--- a/quickstep/src/com/android/quickstep/task/thumbnail/TaskContentView.kt
+++ b/quickstep/src/com/android/quickstep/task/thumbnail/TaskContentView.kt
@@ -17,28 +17,50 @@
package com.android.quickstep.task.thumbnail
import android.content.Context
+import android.content.Intent
import android.graphics.Outline
import android.graphics.Path
import android.graphics.Rect
+import android.provider.Settings
import android.util.AttributeSet
import android.view.View
import android.view.ViewOutlineProvider
import android.view.ViewStub
-import android.widget.LinearLayout
+import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction
+import android.widget.TextView
+import androidx.annotation.IdRes
+import androidx.constraintlayout.widget.ConstraintLayout
+import androidx.constraintlayout.widget.ConstraintSet
import androidx.core.view.isInvisible
+import androidx.core.view.isVisible
+import com.android.launcher3.Flags.enableRefactorDigitalWellbeingToast
import com.android.launcher3.R
import com.android.launcher3.util.ViewPool
+import com.android.quickstep.task.apptimer.TaskAppTimerUiState
+import com.android.quickstep.task.apptimer.TimerTextHelper
+import com.android.quickstep.util.setActivityStarterClickListener
import com.android.quickstep.views.TaskHeaderView
/**
- * TaskContentView is a wrapper around the TaskHeaderView and TaskThumbnailView. It is a sibling to
- * DWB, AiAi (TaskOverlay).
+ * TaskContentView is a wrapper around the TaskHeaderView, TaskThumbnailView and Digital wellbeing
+ * app timer toast. It is a sibling to AiAi (TaskOverlay).
+ *
+ * When enableRefactorDigitalWellbeingToast is off, it is sibling to digital wellbeing toast unlike
+ * when the flag is on.
*/
class TaskContentView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) :
- LinearLayout(context, attrs), ViewPool.Reusable {
+ ConstraintLayout(context, attrs), ViewPool.Reusable {
private var taskHeaderView: TaskHeaderView? = null
private var taskThumbnailView: TaskThumbnailView? = null
+ private var taskAppTimerToast: TextView? = null
+
+ private var timerTextHelper: TimerTextHelper? = null
+ private var timerUiState: TaskAppTimerUiState = TaskAppTimerUiState.Uninitialized
+ private var timerUsageAccessibilityAction: AccessibilityAction? = null
+ private val timerToastHeight =
+ context.resources.getDimensionPixelSize(R.dimen.digital_wellbeing_toast_height)
+
private var onSizeChanged: ((width: Int, height: Int) -> Unit)? = null
private val outlinePath = Path()
@@ -104,6 +126,10 @@ class TaskContentView @JvmOverloads constructor(context: Context, attrs: Attribu
outlineBounds = null
alpha = 1.0f
taskThumbnailView?.onRecycle()
+ taskAppTimerToast?.isInvisible = true
+ timerUiState = TaskAppTimerUiState.Uninitialized
+ timerTextHelper = null
+ timerUsageAccessibilityAction = null
}
fun doOnSizeChange(action: (width: Int, height: Int) -> Unit) {
@@ -114,15 +140,45 @@ class TaskContentView @JvmOverloads constructor(context: Context, attrs: Attribu
super.onSizeChanged(w, h, oldw, oldh)
onSizeChanged?.invoke(width, height)
bounds.set(0, 0, w, h)
+ updateTimerText(w)
invalidateOutline()
}
+ fun onParentAnimationProgress(progress: Float) {
+ taskAppTimerToast?.apply { translationY = timerToastHeight * (1f - progress) }
+ }
+
+ /** Returns accessibility actions supported by items in the task content view. */
+ fun getSupportedAccessibilityActions(): List {
+ return listOfNotNull(timerUsageAccessibilityAction)
+ }
+
+ fun handleAccessibilityAction(action: Int): Boolean {
+ timerUsageAccessibilityAction?.let {
+ if (action == it.id) {
+ return taskAppTimerToast?.callOnClick() ?: false
+ }
+ }
+
+ return false
+ }
+
private fun createHeaderView(taskHeaderState: TaskHeaderUiState) {
if (taskHeaderView == null && taskHeaderState is TaskHeaderUiState.ShowHeader) {
taskHeaderView =
findViewById(R.id.task_header_view)
.apply { layoutResource = R.layout.task_header_view }
.inflate() as TaskHeaderView
+
+ // TODO: Move to layout xml when moving away from view stubs.
+ val constraintSet = ConstraintSet().apply { clone(this@TaskContentView) }
+ constraintSet.connect(
+ R.id.snapshot,
+ ConstraintSet.TOP,
+ R.id.task_header_view,
+ ConstraintSet.BOTTOM,
+ )
+ constraintSet.applyTo(this@TaskContentView)
}
}
@@ -135,13 +191,106 @@ class TaskContentView @JvmOverloads constructor(context: Context, attrs: Attribu
}
}
+ private fun createAppTimerToastView(taskAppTimerUiState: TaskAppTimerUiState) {
+ if (
+ enableRefactorDigitalWellbeingToast() &&
+ taskAppTimerToast == null &&
+ taskAppTimerUiState is TaskAppTimerUiState.Timer
+ ) {
+ taskAppTimerToast =
+ findViewById(R.id.task_app_timer_toast)
+ .apply { layoutResource = R.layout.task_app_timer_toast }
+ .inflate() as TextView
+ }
+ }
+
fun setState(
taskHeaderState: TaskHeaderUiState,
taskThumbnailUiState: TaskThumbnailUiState,
+ taskAppTimerUiState: TaskAppTimerUiState,
taskId: Int?,
) {
createHeaderView(taskHeaderState)
taskHeaderView?.setState(taskHeaderState)
taskThumbnailView?.setState(taskThumbnailUiState, taskId)
+ createAppTimerToastView(taskAppTimerUiState)
+ if (enableRefactorDigitalWellbeingToast() && timerUiState != taskAppTimerUiState) {
+ setAppTimerToastState(taskAppTimerUiState)
+ updateContentDescriptionWithTimer(taskAppTimerUiState)
+ }
+ }
+
+ private fun updateContentDescriptionWithTimer(state: TaskAppTimerUiState) {
+ taskThumbnailView?.contentDescription =
+ when (state) {
+ is TaskAppTimerUiState.Uninitialized -> return
+ is TaskAppTimerUiState.NoTimer -> state.taskDescription
+ is TaskAppTimerUiState.Timer ->
+ timerTextHelper?.let {
+ context.getString(
+ R.string.task_contents_description_with_remaining_time,
+ state.taskDescription,
+ context.getString(R.string.time_left_for_app, it.formattedDuration),
+ )
+ }
+ }
+ }
+
+ private fun setAppTimerToastState(state: TaskAppTimerUiState) {
+ timerUiState = state
+
+ taskAppTimerToast?.apply {
+ when (state) {
+ is TaskAppTimerUiState.Uninitialized -> isInvisible = true
+ is TaskAppTimerUiState.NoTimer -> isInvisible = true
+ is TaskAppTimerUiState.Timer -> {
+ timerTextHelper = TimerTextHelper(context, state.timeRemaining)
+ isInvisible = false
+ updateTimerText(width)
+
+ // TODO: add WW logging on the app usage settings click.
+ setActivityStarterClickListener(
+ appUsageSettingsIntent(state.taskPackageName),
+ "app usage settings for task ${state.taskDescription}",
+ )
+
+ timerUsageAccessibilityAction =
+ appUsageSettingsAccessibilityAction(
+ context,
+ state.accessibilityActionId,
+ state.taskDescription,
+ )
+ }
+ }
+ }
+ }
+
+ private fun updateTimerText(width: Int) {
+ taskAppTimerToast?.apply {
+ val helper = timerTextHelper
+
+ if (isVisible && helper != null) {
+ text = helper.getTextThatFits(width, paint)
+ }
+ }
+ }
+
+ companion object {
+ const val TAG = "TaskContentView"
+
+ private fun appUsageSettingsIntent(packageName: String) =
+ Intent(Intent(Settings.ACTION_APP_USAGE_SETTINGS))
+ .putExtra(Intent.EXTRA_PACKAGE_NAME, packageName)
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
+
+ private fun appUsageSettingsAccessibilityAction(
+ context: Context,
+ @IdRes actionId: Int,
+ taskDescription: String?,
+ ) =
+ AccessibilityAction(
+ actionId,
+ context.getString(R.string.split_app_usage_settings, taskDescription),
+ )
}
}
diff --git a/quickstep/src/com/android/quickstep/util/ClickListeners.kt b/quickstep/src/com/android/quickstep/util/ClickListeners.kt
new file mode 100644
index 0000000000..e827e9fe9b
--- /dev/null
+++ b/quickstep/src/com/android/quickstep/util/ClickListeners.kt
@@ -0,0 +1,44 @@
+/*
+ * Copyright (C) 2025 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.quickstep.util
+
+import android.app.ActivityOptions
+import android.content.ActivityNotFoundException
+import android.content.Intent
+import android.util.Log
+import android.view.View
+import com.android.quickstep.task.thumbnail.TaskContentView
+
+/**
+ * Sets a click listener on the view that launches an activity using the provided [intent]
+ *
+ * Performs scale up animation.
+ *
+ * @property intent the intent to use for launching the activity
+ * @property targetDescription a short text describing the target activity beings opened that can be
+ * used for logging (e.g. usage settings for task A).
+ */
+fun View.setActivityStarterClickListener(intent: Intent, targetDescription: String) {
+ setOnClickListener { view ->
+ try {
+ val options = ActivityOptions.makeScaleUpAnimation(view, 0, 0, view.width, view.height)
+ context.startActivity(intent, options.toBundle())
+ } catch (e: ActivityNotFoundException) {
+ Log.e(TaskContentView.TAG, "Failed to open $targetDescription ", e)
+ }
+ }
+}
diff --git a/quickstep/src/com/android/quickstep/views/DesktopTaskView.kt b/quickstep/src/com/android/quickstep/views/DesktopTaskView.kt
index 2d54067b19..fe8a09cec2 100644
--- a/quickstep/src/com/android/quickstep/views/DesktopTaskView.kt
+++ b/quickstep/src/com/android/quickstep/views/DesktopTaskView.kt
@@ -15,6 +15,9 @@
*/
package com.android.quickstep.views
+import android.animation.Animator
+import android.animation.AnimatorListenerAdapter
+import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Matrix
@@ -23,6 +26,7 @@ import android.graphics.Rect
import android.graphics.Rect.intersects
import android.graphics.RectF
import android.util.AttributeSet
+import android.util.FloatProperty
import android.util.Log
import android.util.Size
import android.view.Display.INVALID_DISPLAY
@@ -39,6 +43,7 @@ import com.android.launcher3.R
import com.android.launcher3.statehandlers.DesktopVisibilityController
import com.android.launcher3.testing.TestLogging
import com.android.launcher3.testing.shared.TestProtocol
+import com.android.launcher3.util.KFloatProperty
import com.android.launcher3.util.OverviewReleaseFlags.enableOverviewIconMenu
import com.android.launcher3.util.RunnableList
import com.android.launcher3.util.SplitConfigurationOptions
@@ -127,6 +132,12 @@ class DesktopTaskView @JvmOverloads constructor(context: Context, attrs: Attribu
*/
private var fullscreenTaskPositions: List = emptyList()
+ /**
+ * Holds the previous organized task positions. This is used to animate between two sets of
+ * organized task positions when a task is being dismissed.
+ */
+ private var previousOrganizedDesktopTaskPositions: List? = null
+
/**
* When enableDesktopExplodedView is enabled, this controls the gradual transition from the
* default positions to the organized non-overlapping positions.
@@ -137,6 +148,18 @@ class DesktopTaskView @JvmOverloads constructor(context: Context, attrs: Attribu
positionTaskWindows()
}
+ /**
+ * When enableDesktopExplodedView is enabled, and a task is removed, this controls the gradual
+ * transition from the previous organized task positions to the new.
+ */
+ private var taskRemoveProgress = 0.0f
+ set(value) {
+ field = value
+ positionTaskWindows()
+ }
+
+ private var taskRemoveAnimator: ObjectAnimator? = null
+
var remoteTargetHandles: Array? = null
set(value) {
field = value
@@ -215,7 +238,22 @@ class DesktopTaskView @JvmOverloads constructor(context: Context, attrs: Attribu
val currentTaskBounds =
if (enableDesktopExplodedView()) {
TEMP_OVERVIEW_TASK_POSITION.apply {
- lerpRect(fullscreenTaskBounds, overviewTaskBounds, explodeProgress)
+ // When removing a task, interpolate between its old organized bounds and
+ // [overviewTaskBounds].
+ val previousOrganizedTaskBounds =
+ previousOrganizedDesktopTaskPositions
+ ?.firstOrNull { it.taskId == taskId }
+ ?.bounds
+ if (previousOrganizedTaskBounds != null) {
+ lerpRect(
+ previousOrganizedTaskBounds,
+ overviewTaskBounds,
+ taskRemoveProgress,
+ )
+ } else {
+ set(overviewTaskBounds)
+ }
+ lerpRect(fullscreenTaskBounds, this, explodeProgress)
}
} else {
fullscreenTaskBounds
@@ -393,6 +431,8 @@ class DesktopTaskView @JvmOverloads constructor(context: Context, attrs: Attribu
override fun onRecycle() {
super.onRecycle()
explodeProgress = 0.0f
+ taskRemoveProgress = 0.0f
+ previousOrganizedDesktopTaskPositions = null
viewModel = null
visibility = VISIBLE
taskContainers.forEach { removeAndRecycleThumbnailView(it) }
@@ -528,8 +568,31 @@ class DesktopTaskView @JvmOverloads constructor(context: Context, attrs: Attribu
if (taskContainers.isEmpty()) {
recentsView?.dismissTaskView(this, animate, /* removeTask= */ true)
} else {
- // Otherwise, re-position the remaining task windows.
- // TODO(b/353949276): Implement the re-layout animations.
+ // If this task has a live window, then hide it.
+ // TODO(b/413120214) The dismissed view should fade out.
+ getRemoteTargetHandle(taskId)?.let {
+ it.taskViewSimulator.setTaskRectTransform(Matrix().apply { postScale(0.0f, 0.0f) })
+ it.taskViewSimulator.apply(it.transformParams)
+ }
+
+ // TODO(b/413130378) Nicer handling of multiple quick task dismissals.
+ taskRemoveAnimator?.cancel()
+ taskRemoveAnimator =
+ ObjectAnimator.ofFloat(this, TASK_REMOVE_PROGRESS, 0f, 1f).apply {
+ addListener(
+ object : AnimatorListenerAdapter() {
+ override fun onAnimationEnd(animator: Animator) {
+ previousOrganizedDesktopTaskPositions = null
+ taskRemoveAnimator = null
+ }
+ }
+ )
+ start()
+ }
+
+ // Store the current organized positions before computing new ones. This allows us to
+ // animate from the current layout to the new.
+ previousOrganizedDesktopTaskPositions = viewModel!!.organizedDesktopTaskPositions
updateTaskPositions()
}
}
@@ -573,5 +636,7 @@ class DesktopTaskView @JvmOverloads constructor(context: Context, attrs: Attribu
private val TEMP_OVERVIEW_TASK_POSITION = Rect()
private val TEMP_FROM_RECTF = RectF()
private val TEMP_TO_RECTF = RectF()
+ private val TASK_REMOVE_PROGRESS: FloatProperty =
+ KFloatProperty(DesktopTaskView::taskRemoveProgress)
}
}
diff --git a/quickstep/src/com/android/quickstep/views/DigitalWellBeingToast.kt b/quickstep/src/com/android/quickstep/views/DigitalWellBeingToast.kt
index 51e7602960..10d4377424 100644
--- a/quickstep/src/com/android/quickstep/views/DigitalWellBeingToast.kt
+++ b/quickstep/src/com/android/quickstep/views/DigitalWellBeingToast.kt
@@ -24,9 +24,6 @@ import android.content.pm.LauncherApps
import android.content.pm.LauncherApps.AppUsageLimit
import android.graphics.Outline
import android.graphics.Paint
-import android.icu.text.MeasureFormat
-import android.icu.util.Measure
-import android.icu.util.MeasureUnit
import android.os.UserHandle
import android.provider.Settings
import android.util.AttributeSet
@@ -35,7 +32,6 @@ import android.view.View
import android.view.ViewOutlineProvider
import android.view.accessibility.AccessibilityNodeInfo
import android.widget.TextView
-import androidx.annotation.StringRes
import androidx.annotation.VisibleForTesting
import androidx.core.util.component1
import androidx.core.util.component2
@@ -47,10 +43,10 @@ import com.android.launcher3.util.SplitConfigurationOptions.STAGE_POSITION_TOP_O
import com.android.launcher3.util.SplitConfigurationOptions.STAGE_POSITION_UNDEFINED
import com.android.launcher3.util.SplitConfigurationOptions.StagePosition
import com.android.quickstep.TaskUtils
+import com.android.quickstep.task.apptimer.DurationFormatter
import com.android.systemui.shared.recents.model.Task
import com.android.wm.shell.shared.split.SplitBounds
import java.time.Duration
-import java.util.Locale
@SuppressLint("AppCompatCustomView")
class DigitalWellBeingToast
@@ -200,37 +196,6 @@ constructor(
}
}
- private fun getReadableDuration(
- duration: Duration,
- @StringRes durationLessThanOneMinuteStringId: Int,
- ): String {
- val hours = Math.toIntExact(duration.toHours())
- val minutes = Math.toIntExact(duration.minusHours(hours.toLong()).toMinutes())
- return when {
- // Apply FormatWidth.WIDE if both the hour part and the minute part are non-zero.
- hours > 0 && minutes > 0 ->
- MeasureFormat.getInstance(Locale.getDefault(), MeasureFormat.FormatWidth.NARROW)
- .formatMeasures(
- Measure(hours, MeasureUnit.HOUR),
- Measure(minutes, MeasureUnit.MINUTE),
- )
- // Apply FormatWidth.WIDE if only the hour part is non-zero (unless forced).
- hours > 0 ->
- MeasureFormat.getInstance(Locale.getDefault(), MeasureFormat.FormatWidth.WIDE)
- .formatMeasures(Measure(hours, MeasureUnit.HOUR))
- // Apply FormatWidth.WIDE if only the minute part is non-zero (unless forced).
- minutes > 0 ->
- MeasureFormat.getInstance(Locale.getDefault(), MeasureFormat.FormatWidth.WIDE)
- .formatMeasures(Measure(minutes, MeasureUnit.MINUTE))
- // Use a specific string for usage less than one minute but non-zero.
- duration > Duration.ZERO -> context.getString(durationLessThanOneMinuteStringId)
- // Otherwise, return 0-minute string.
- else ->
- MeasureFormat.getInstance(Locale.getDefault(), MeasureFormat.FormatWidth.WIDE)
- .formatMeasures(Measure(0, MeasureUnit.MINUTE))
- }
- }
-
/**
* Returns text to show for the banner depending on [.getSplitBannerConfig] If {@param
* forContentDesc} is `true`, this will always return the full string corresponding to
@@ -249,7 +214,8 @@ constructor(
else remainingTime
)
val readableDuration =
- getReadableDuration(
+ DurationFormatter.format(
+ context,
duration,
R.string.shorter_duration_less_than_one_minute, /* forceFormatWidth */
)
diff --git a/quickstep/src/com/android/quickstep/views/GroupedTaskView.kt b/quickstep/src/com/android/quickstep/views/GroupedTaskView.kt
index d23c4b726d..65810b6f9c 100644
--- a/quickstep/src/com/android/quickstep/views/GroupedTaskView.kt
+++ b/quickstep/src/com/android/quickstep/views/GroupedTaskView.kt
@@ -23,13 +23,13 @@ import android.util.Log
import android.view.View
import android.view.ViewStub
import com.android.internal.jank.Cuj
+import com.android.launcher3.Flags.enableRefactorDigitalWellbeingToast
import com.android.launcher3.Flags.enableRefactorTaskContentView
import com.android.launcher3.Flags.enableRefactorTaskThumbnail
import com.android.launcher3.R
import com.android.launcher3.Utilities
import com.android.launcher3.util.OverviewReleaseFlags.enableOverviewIconMenu
import com.android.launcher3.util.RunnableList
-import com.android.launcher3.util.SplitConfigurationOptions
import com.android.launcher3.util.SplitConfigurationOptions.STAGE_POSITION_BOTTOM_OR_RIGHT
import com.android.launcher3.util.SplitConfigurationOptions.STAGE_POSITION_TOP_OR_LEFT
import com.android.launcher3.util.SplitConfigurationOptions.STAGE_POSITION_UNDEFINED
@@ -117,9 +117,11 @@ class GroupedTaskView @JvmOverloads constructor(context: Context, attrs: Attribu
else R.layout.icon_view
}
?.inflate()
- findViewById(R.id.bottomRight_digital_wellbeing_toast)
- ?.apply { layoutResource = R.layout.digital_wellbeing_toast }
- ?.inflate()
+ if (!enableRefactorDigitalWellbeingToast()) {
+ findViewById(R.id.bottomRight_digital_wellbeing_toast)
+ ?.apply { layoutResource = R.layout.digital_wellbeing_toast }
+ ?.inflate()
+ }
}
override fun onRecycle() {
diff --git a/quickstep/src/com/android/quickstep/views/RecentsDismissUtils.kt b/quickstep/src/com/android/quickstep/views/RecentsDismissUtils.kt
index 5cb94c39f0..4266c6f2df 100644
--- a/quickstep/src/com/android/quickstep/views/RecentsDismissUtils.kt
+++ b/quickstep/src/com/android/quickstep/views/RecentsDismissUtils.kt
@@ -16,11 +16,17 @@
package com.android.quickstep.views
+import android.app.ActivityTaskManager.INVALID_TASK_ID
+import android.view.View
+import androidx.core.view.children
import androidx.dynamicanimation.animation.FloatPropertyCompat
import androidx.dynamicanimation.animation.FloatValueHolder
import androidx.dynamicanimation.animation.SpringAnimation
import androidx.dynamicanimation.animation.SpringForce
+import com.android.internal.jank.Cuj
+import com.android.launcher3.PagedView
import com.android.launcher3.R
+import com.android.launcher3.logging.StatsLogManager.LauncherEvent
import com.android.launcher3.util.DynamicResource
import com.android.launcher3.util.MSDLPlayerWrapper
import com.android.launcher3.util.OverviewReleaseFlags.enableGridOnlyOverview
@@ -28,7 +34,10 @@ import com.android.launcher3.views.ActivityContext
import com.android.quickstep.util.TaskGridNavHelper
import com.android.quickstep.views.RecentsView.RECENTS_SCALE_PROPERTY
import com.android.quickstep.views.TaskView.Companion.GRID_END_TRANSLATION_X
+import com.android.systemui.shared.system.InteractionJankMonitorWrapper
import com.google.android.msdl.data.model.MSDLToken
+import java.util.concurrent.atomic.AtomicBoolean
+import java.util.concurrent.atomic.AtomicInteger
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.roundToInt
@@ -77,7 +86,7 @@ class RecentsDismissUtils(private val recentsView: RecentsView<*, *>) {
.toInt()
val dismissThreshold = (dismissLength * DEFAULT_DISMISS_THRESHOLD_FRACTION).toInt()
val velocity = mTempRect.height().toFloat()
- val finalPosition = if (isSplitSelection) 0f else dismissLength.toFloat()
+ val finalPosition = dismissLength.toFloat()
return createTaskDismissSettlingSpringAnimation(
draggedTaskView,
velocity,
@@ -180,8 +189,14 @@ class RecentsDismissUtils(private val recentsView: RecentsView<*, *>) {
isSpringDirectionVertical = true,
minVelocity = startVelocity,
)
+ draggedTaskViewSpringAnimation.addEndListener { _, _, _, _ ->
+ InteractionJankMonitorWrapper.cancel(Cuj.CUJ_LAUNCHER_OVERVIEW_TASK_DISMISS)
+ }
+ }
+ return draggedTaskViewSpringAnimation.apply {
+ InteractionJankMonitorWrapper.begin(recentsView, Cuj.CUJ_LAUNCHER_OVERVIEW_TASK_DISMISS)
+ animateToFinalPosition(finalPosition)
}
- return draggedTaskViewSpringAnimation.apply { animateToFinalPosition(finalPosition) }
}
private fun addNeighborSettlingSpringAnimations(
@@ -435,6 +450,15 @@ class RecentsDismissUtils(private val recentsView: RecentsView<*, *>) {
val towardsStart = if (recentsView.isRtl) dismissedTaskGap < 0 else dismissedTaskGap > 0
var startOffset = 0f
recentsView.mTaskViewsDismissPrimaryTranslations.clear()
+ val runOnFinalSpringEnd = {
+ runGridEndTranslation(
+ dismissedTaskView,
+ onEndRunnable,
+ shouldRemoveTaskView,
+ isSplitSelection,
+ )
+ }
+ val springEndManager = SpringEndManager(runOnFinalSpringEnd)
var tasksToReflow: List
// Build the chains of Spring Animations
@@ -450,6 +474,7 @@ class RecentsDismissUtils(private val recentsView: RecentsView<*, *>) {
tasksToReflow,
dismissedTaskGap,
previousSpring = springAnimationDriver,
+ springEndManager,
)
}
dismissedTaskView == null || dismissedTaskView.isLargeTile -> {
@@ -464,6 +489,7 @@ class RecentsDismissUtils(private val recentsView: RecentsView<*, *>) {
tasksToReflow,
dismissedTaskGap,
previousSpring = springAnimationDriver,
+ springEndManager,
)
// Add all top and bottom grid tasks when animating towards the end of the grid.
if (!towardsStart) {
@@ -479,12 +505,14 @@ class RecentsDismissUtils(private val recentsView: RecentsView<*, *>) {
recentsView.mUtils.getTopRowTaskViews(),
dismissedTaskGap,
previousSpring = lastSpringAnimation,
+ springEndManager,
startOffset,
)
buildDismissReflowSpringAnimationChain(
recentsView.mUtils.getBottomRowTaskViews(),
dismissedTaskGap,
previousSpring = lastSpringAnimation,
+ springEndManager,
startOffset,
)
}
@@ -500,6 +528,7 @@ class RecentsDismissUtils(private val recentsView: RecentsView<*, *>) {
tasksToReflow,
dismissedTaskGap,
previousSpring = springAnimationDriver,
+ springEndManager,
)
}
else -> {
@@ -513,18 +542,14 @@ class RecentsDismissUtils(private val recentsView: RecentsView<*, *>) {
tasksToReflow,
dismissedTaskGap,
previousSpring = springAnimationDriver,
+ springEndManager,
)
}
}
val runImmediately = tasksToReflow.isEmpty()
if (runImmediately) {
- runGridEndTranslation(
- dismissedTaskView,
- onEndRunnable,
- DISMISS_IMMEDIATE_DURATION,
- shouldRemoveTaskView,
- )
+ runOnFinalSpringEnd()
} else {
addNeighborSettlingSpringAnimations(
dismissedTaskView,
@@ -534,17 +559,8 @@ class RecentsDismissUtils(private val recentsView: RecentsView<*, *>) {
isSpringDirectionVertical = false,
minVelocity = 0f,
)
- springAnimationDriver.apply {
- addEndListener { _, _, _, _ ->
- runGridEndTranslation(
- dismissedTaskView,
- onEndRunnable,
- DISMISS_DEFAULT_DURATION,
- shouldRemoveTaskView,
- )
- }
- animateToFinalPosition(dismissedTaskGap)
- }
+ springEndManager.addSpring(springAnimationDriver, dismissedTaskGap)
+ springAnimationDriver.animateToFinalPosition(dismissedTaskGap)
}
}
@@ -622,6 +638,7 @@ class RecentsDismissUtils(private val recentsView: RecentsView<*, *>) {
taskViews: Iterable,
dismissedTaskGap: Float,
previousSpring: SpringAnimation,
+ springEndManager: SpringEndManager,
startOffset: Float = 0f,
): SpringAnimation {
var lastTaskViewSpring = previousSpring
@@ -653,6 +670,8 @@ class RecentsDismissUtils(private val recentsView: RecentsView<*, *>) {
lastTaskViewSpring.addUpdateListener { _, value, _ ->
taskViewSpringAnimation.animateToFinalPosition(value)
}
+ // Only run the final runnable once the last spring has ended.
+ springEndManager.addSpring(taskViewSpringAnimation, dismissedTaskGap)
lastTaskViewSpring = taskViewSpringAnimation
recentsView.mTaskViewsDismissPrimaryTranslations[taskView] =
dismissedTaskGap.toInt()
@@ -664,17 +683,35 @@ class RecentsDismissUtils(private val recentsView: RecentsView<*, *>) {
private fun runGridEndTranslation(
dismissedTaskView: TaskView?,
onEndRunnable: () -> Unit,
- dismissDuration: Int,
shouldRemoveTaskView: Boolean,
+ isSplitSelection: Boolean,
) {
val runGridEndAnimationAndRelayout = { gridEndData: GridEndData ->
- recentsView.expressiveDismissTaskView(
- dismissedTaskView,
- onEndRunnable,
- dismissDuration,
- shouldRemoveTaskView,
- gridEndData,
- )
+ with(recentsView) {
+ if (pageCount == 0) {
+ return@with
+ }
+ updateCurveProperties()
+ loadVisibleTaskData(TaskView.FLAG_UPDATE_ALL)
+ val onFinishComplete = {
+ onEndSnappingAndRelayout(
+ dismissedTaskView,
+ shouldRemoveTaskView,
+ isSplitSelection,
+ gridEndData,
+ onEndRunnable,
+ )
+ }
+ if (enableDrawingLiveTile && dismissedTaskView?.isRunningTask == true) {
+ finishRecentsAnimation(
+ /* toRecents */ true, /* shouldPip */
+ false,
+ onFinishComplete,
+ )
+ } else {
+ onFinishComplete()
+ }
+ }
}
val gridEndData = getGridEndData(dismissedTaskView)
val gridEndOffset = gridEndData.gridEndOffset
@@ -687,6 +724,7 @@ class RecentsDismissUtils(private val recentsView: RecentsView<*, *>) {
val gridEndSpring =
SpringAnimation(FloatValueHolder())
.setSpring(createExpressiveGridReflowSpringForce(gridEndOffset))
+ val springEndManager = SpringEndManager { runGridEndAnimationAndRelayout(gridEndData) }
recentsView.mUtils.taskViews.forEach { taskView ->
val taskViewGridEndSpringAnimation =
SpringAnimation(
@@ -707,6 +745,7 @@ class RecentsDismissUtils(private val recentsView: RecentsView<*, *>) {
gridEndSpring.addUpdateListener { _, value, _ ->
taskViewGridEndSpringAnimation.animateToFinalPosition(value)
}
+ springEndManager.addSpring(taskViewGridEndSpringAnimation, gridEndOffset)
}
// Animate alpha of clear all if translating grid to hide it.
if (recentsView.isClearAllHidden) {
@@ -718,7 +757,7 @@ class RecentsDismissUtils(private val recentsView: RecentsView<*, *>) {
.addEndListener { _, _, _, _ -> recentsView.clearAllButton.dismissAlpha = 1f }
.animateToFinalPosition(0f)
}
- gridEndSpring.addEndListener { _, _, _, _ -> runGridEndAnimationAndRelayout(gridEndData) }
+ springEndManager.addSpring(gridEndSpring, gridEndOffset)
gridEndSpring.animateToFinalPosition(gridEndOffset)
}
@@ -888,12 +927,273 @@ class RecentsDismissUtils(private val recentsView: RecentsView<*, *>) {
val currentPageSnapsToEndOfGrid: Boolean,
)
+ private fun onEndSnappingAndRelayout(
+ dismissedTaskView: TaskView?,
+ shouldRemoveTask: Boolean,
+ dismissingForSplitSelection: Boolean,
+ gridEndData: GridEndData,
+ onEndRunnable: () -> Unit,
+ ) {
+ with(recentsView) {
+ // Reset task translations as they may have updated via the dismiss animations.
+ resetTaskVisuals()
+
+ // Denote if any task has been dismissed for grid rebalancing.
+ mAnyTaskHasBeenDismissed = true
+ // Cache group task before removing.
+ handleGroupTaskRemoval(dismissedTaskView, shouldRemoveTask)
+
+ // Get page to snap to before removing dismissed task.
+ val dismissedTaskViewId = dismissedTaskView?.taskViewId ?: INVALID_TASK_ID
+ val pageToSnapTo =
+ when {
+ (dismissedTaskView != null &&
+ (!showAsGrid() || dismissedTaskView.isLargeTile)) -> {
+ getPageToSnapTo(dismissedTaskView)
+ }
+ showAsGrid() -> {
+ getPageToSnapToForGrid(gridEndData, dismissedTaskViewId)
+ }
+ else -> {
+ currentPage
+ }
+ }
+
+ // Remove dismissed task.
+ removeViewInLayout(dismissedTaskView)
+ mTopRowIdSet.remove(dismissedTaskViewId)
+
+ // Update the UI after removal and snap to page.
+ updateUiAfterTaskRemoval(dismissedTaskView, pageToSnapTo)
+
+ // Run the user-provided end-runnable.
+ onEndRunnable()
+
+ if (!dismissingForSplitSelection) {
+ InteractionJankMonitorWrapper.end(Cuj.CUJ_LAUNCHER_OVERVIEW_TASK_DISMISS)
+ }
+ }
+ }
+
+ /**
+ * Caches the groupTask before removing it. As the deskId might become invalid by
+ * removeViewInLayout called on the dismissed task. It might happen before
+ * removeGroupTaskInternal which runs on a helper thread.
+ */
+ private fun handleGroupTaskRemoval(dismissedTaskView: TaskView?, shouldRemoveTask: Boolean) {
+ with(recentsView) {
+ if (shouldRemoveTask && dismissedTaskView != null) {
+ val groupTask = dismissedTaskView.groupTask
+ if (groupTask != null) {
+ if (dismissedTaskView.isRunningTask) {
+ finishRecentsAnimation(/* toRecents */ true, /* shouldPip */ false) {
+ removeGroupTaskInternal(groupTask)
+ }
+ } else {
+ removeGroupTaskInternal(groupTask)
+ }
+ (mContainer as ActivityContext)
+ .statsLogManager
+ .logger()
+ .withItemInfo(dismissedTaskView.itemInfo)
+ .log(LauncherEvent.LAUNCHER_TASK_DISMISS_SWIPE_UP)
+ }
+ }
+ }
+ }
+
+ private fun getPageToSnapTo(dismissedTaskView: TaskView?): Int {
+ with(recentsView) {
+ var pageToSnapTo = currentPage
+ if (
+ indexOfChild(dismissedTaskView) < pageToSnapTo ||
+ pageToSnapTo == indexOfChild(mUtils.getLastTaskView())
+ ) {
+ pageToSnapTo--
+ }
+ return pageToSnapTo
+ }
+ }
+
+ private fun getPageToSnapToForGrid(gridEndData: GridEndData, dismissedTaskViewId: Int): Int {
+ with(recentsView) {
+ var pageToSnapTo = currentPage
+ var taskViewIdToSnapTo = -1
+ currentPageScrollDiff = 0
+
+ if (gridEndData.gridEndOffset != 0f) {
+ if (gridEndData.snapToLastTask) {
+ // Last task will be determined after removing dismissed task.
+ pageToSnapTo = -1
+ } else if (taskViewCount > 2) {
+ pageToSnapTo = indexOfChild(clearAllButton)
+ } else if (isClearAllHidden) {
+ // Snap to focused task if clear all is hidden.
+ pageToSnapTo = indexOfChild(firstTaskView)
+ }
+ } else {
+ val snappedTaskView = currentPageTaskView
+ if (snappedTaskView != null && !gridEndData.snapToLastTask) {
+ val snappedTaskViewId = snappedTaskView.taskViewId
+ val isSnappedTaskInTopRow = mTopRowIdSet.contains(snappedTaskViewId)
+ val taskViewIdArray =
+ if (isSnappedTaskInTopRow) {
+ mUtils.getTopRowIdArray()
+ } else {
+ mUtils.getBottomRowIdArray()
+ }
+ val snappedIndex = taskViewIdArray.indexOf(snappedTaskViewId)
+ taskViewIdArray.removeValue(dismissedTaskViewId)
+ if (snappedIndex >= 0 && snappedIndex < taskViewIdArray.size()) {
+ taskViewIdToSnapTo = taskViewIdArray[snappedIndex]
+ } else if (snappedIndex == taskViewIdArray.size()) {
+ val inverseRowTaskViewIdArray =
+ if (isSnappedTaskInTopRow) {
+ mUtils.getBottomRowIdArray()
+ } else {
+ mUtils.getTopRowIdArray()
+ }
+ if (snappedIndex < inverseRowTaskViewIdArray.size()) {
+ taskViewIdToSnapTo = inverseRowTaskViewIdArray[snappedIndex]
+ }
+ }
+ }
+ val primaryScroll = pagedOrientationHandler.getPrimaryScroll(this)
+ val currentPageScroll = getScrollForPage(currentPage)
+ currentPageScrollDiff = primaryScroll - currentPageScroll
+ }
+
+ // Calculate page to snap to as if the dismissed task view is removed from the grid.
+ val topRowIdArray = mUtils.getTopRowIdArray()
+ val bottomRowIdArray = mUtils.getBottomRowIdArray()
+ topRowIdArray.removeValue(dismissedTaskViewId)
+ bottomRowIdArray.removeValue(dismissedTaskViewId)
+ val children =
+ children.filter { child -> child != getTaskViewFromTaskViewId(dismissedTaskViewId) }
+ if (gridEndData.snapToLastTask) {
+ val lastGridTaskView = getLastGridTaskView(topRowIdArray, bottomRowIdArray)
+ pageToSnapTo =
+ if (lastGridTaskView == null) PagedView.INVALID_PAGE
+ else children.indexOf(lastGridTaskView as View)
+ if (pageToSnapTo == PagedView.INVALID_PAGE) {
+ val lastLargeTaskView = mUtils.getLastLargeTaskView()
+ pageToSnapTo =
+ if (lastLargeTaskView == null) PagedView.INVALID_PAGE
+ else children.indexOf(lastLargeTaskView as View)
+ }
+ } else if (taskViewIdToSnapTo != -1) {
+ // If snapping to another page due to indices rearranging, find
+ // the new index after dismissal & rearrange using the TaskView ID.
+ pageToSnapTo =
+ children.indexOf(getTaskViewFromTaskViewId(taskViewIdToSnapTo) as View)
+ if (!gridEndData.currentPageSnapsToEndOfGrid) {
+ val dismissedTaskViewIndex =
+ indexOfChild(getTaskViewFromTaskViewId(dismissedTaskViewId))
+ currentPageScrollDiff +=
+ getOffsetFromScrollPosition(
+ pageToSnapTo,
+ topRowIdArray,
+ bottomRowIdArray,
+ dismissedTaskViewIndex,
+ )
+ }
+ }
+ return pageToSnapTo
+ }
+ }
+
+ private fun updateUiAfterTaskRemoval(dismissedTaskView: TaskView?, pageToSnapTo: Int) {
+ with(recentsView) {
+ if (taskViewCount == 0) {
+ if (!isSplitSelectionActive) {
+ removeViewInLayout(clearAllButton)
+ removeViewInLayout(addDeskButton)
+ if (dismissedTaskView === homeTaskView) {
+ updateEmptyMessage()
+ } else {
+ startHome()
+ }
+ }
+ } else {
+ updateTaskSize()
+ mUtils.updateChildTaskOrientations()
+ updateScrollSynchronously()
+
+ val highestVisibleTaskView = getHighestVisibleTaskView()
+ if (showAsGrid() && highestVisibleTaskView != null) {
+ rebalanceTasksInGrid(highestVisibleTaskView)
+ }
+ pageBeginTransition()
+ currentPage = pageToSnapTo
+ dispatchScrollChanged()
+ updateActionsViewFocusedScroll()
+ if (
+ isClearAllHidden && !(mContainer as ActivityContext).getDeviceProfile().isTablet
+ ) {
+ actionsView.updateDisabledFlags(OverviewActionsView.DISABLED_SCROLLING, false)
+ }
+ }
+ updateCurrentTaskActionsVisibility()
+ onDismissAnimationEnds()
+ mTaskViewsDismissPrimaryTranslations.clear()
+ }
+ }
+
+ private fun rebalanceTasksInGrid(highestVisibleTaskView: TaskView) {
+ with(recentsView) {
+ val screenStart = pagedOrientationHandler.getPrimaryScroll(this)
+ val taskStart =
+ (pagedOrientationHandler.getChildStart(highestVisibleTaskView) +
+ highestVisibleTaskView.getOffsetAdjustment(true).toInt())
+
+ val shouldRebalance =
+ if (isRtl) {
+ taskStart <= screenStart + pageSpacing
+ } else {
+ val screenEnd = (screenStart + pagedOrientationHandler.getMeasuredSize(this))
+ val taskSize =
+ (pagedOrientationHandler.getMeasuredSize(highestVisibleTaskView) *
+ highestVisibleTaskView.getSizeAdjustment(false))
+ .toInt()
+ val taskEnd = taskStart + taskSize
+ taskEnd >= screenEnd - pageSpacing
+ }
+
+ if (shouldRebalance) {
+ updateGridProperties(highestVisibleTaskView)
+ updateScrollSynchronously()
+ }
+ }
+ }
+
+ /** Tracks multiple springs so end runnable only runs once the last spring has ended. */
+ private class SpringEndManager(val endRunnable: () -> Unit) {
+ val runningSpringCount = AtomicInteger(0)
+
+ fun addSpring(spring: SpringAnimation, endValue: Float) {
+ runningSpringCount.incrementAndGet()
+ val canSpringEnd = AtomicBoolean(false)
+ spring.addUpdateListener { _, value, _ ->
+ // Do not allow end listener to fire until we have reached the end value.
+ if (abs(value - endValue) < spring.minimumVisibleChange && !canSpringEnd.get()) {
+ canSpringEnd.set(true)
+ }
+ }
+ spring.addEndListener { _, _, _, _ ->
+ if (!canSpringEnd.get()) {
+ return@addEndListener
+ }
+ if (runningSpringCount.decrementAndGet() == 0) {
+ endRunnable()
+ }
+ }
+ }
+ }
+
private companion object {
// The additional damping to apply to tasks further from the dismissed task.
private const val ADDITIONAL_DISMISS_DAMPING_RATIO = 0.15f
private const val RECENTS_SCALE_SPRING_MULTIPLIER = 1000f
- private const val DISMISS_DEFAULT_DURATION = 300
- private const val DISMISS_IMMEDIATE_DURATION = 100
private const val DEFAULT_DISMISS_THRESHOLD_FRACTION = 0.5f
}
}
diff --git a/quickstep/src/com/android/quickstep/views/RecentsView.java b/quickstep/src/com/android/quickstep/views/RecentsView.java
index 6c923e8c47..6d1e8efc23 100644
--- a/quickstep/src/com/android/quickstep/views/RecentsView.java
+++ b/quickstep/src/com/android/quickstep/views/RecentsView.java
@@ -859,7 +859,7 @@ public abstract class RecentsView<
* RecentsView being open and displayed to the user. It is reset in the {@link #reset()} method
* i.e. when RecentsView closes.
*/
- private boolean mAnyTaskHasBeenDismissed;
+ protected boolean mAnyTaskHasBeenDismissed;
protected final RecentsViewModel mRecentsViewModel;
private final RecentsViewModelHelper mHelper;
@@ -1525,7 +1525,7 @@ public abstract class RecentsView<
}
@Nullable
- private TaskView getLastGridTaskView(IntArray topRowIdArray, IntArray bottomRowIdArray) {
+ protected TaskView getLastGridTaskView(IntArray topRowIdArray, IntArray bottomRowIdArray) {
if (topRowIdArray.isEmpty() && bottomRowIdArray.isEmpty()) {
return null;
}
@@ -2518,7 +2518,7 @@ public abstract class RecentsView<
return scrolling;
}
- private void updateActionsViewFocusedScroll() {
+ protected void updateActionsViewFocusedScroll() {
if (showAsGrid()) {
float actionsViewAlphaValue = isFocusedTaskInExpectedScrollPosition() ? 1 : 0;
// If animation is already in progress towards the same end value, do not restart.
@@ -2531,6 +2531,10 @@ public abstract class RecentsView<
}
}
+ protected OverviewActionsView getActionsView() {
+ return mActionsView;
+ }
+
private void animateActionsViewAlpha(float alphaValue, long duration) {
mActionsViewAlphaAnimator = ObjectAnimator.ofFloat(mActionsView.getVisibilityAlpha(),
AnimatedFloat.VALUE, alphaValue);
@@ -3237,7 +3241,7 @@ public abstract class RecentsView<
* @param lastVisibleTaskViewDuringDismiss which TaskView to start rebalancing from. Use
* `null` to skip rebalance.
*/
- private void updateGridProperties(TaskView lastVisibleTaskViewDuringDismiss) {
+ protected void updateGridProperties(TaskView lastVisibleTaskViewDuringDismiss) {
if (!hasTaskViews()) {
return;
}
@@ -4355,7 +4359,7 @@ public abstract class RecentsView<
* * Focused view is a single app
* * Device is large screen
*/
- private void updateCurrentTaskActionsVisibility() {
+ protected void updateCurrentTaskActionsVisibility() {
TaskView taskView = getCurrentPageTaskView();
boolean isCurrentSplit = taskView instanceof GroupedTaskView;
GroupedTaskView groupedTaskView = isCurrentSplit ? (GroupedTaskView) taskView : null;
@@ -4382,7 +4386,7 @@ public abstract class RecentsView<
*
* @return the highest visible TaskView between both rows
*/
- private TaskView getHighestVisibleTaskView() {
+ protected TaskView getHighestVisibleTaskView() {
if (mTopRowIdSet.isEmpty()) return null; // return earlier
TaskView lastVisibleTaskView = null;
@@ -4405,7 +4409,7 @@ public abstract class RecentsView<
return lastVisibleTaskView;
}
- private void removeGroupTaskInternal(@NonNull GroupTask groupTask) {
+ protected void removeGroupTaskInternal(@NonNull GroupTask groupTask) {
UI_HELPER_EXECUTOR
.getHandler()
.post(
@@ -4782,6 +4786,14 @@ public abstract class RecentsView<
return getTaskViewAt(getNextPage());
}
+ protected int getCurrentPageScrollDiff() {
+ return mCurrentPageScrollDiff;
+ }
+
+ protected void setCurrentPageScrollDiff(int currentPageScrollDiff) {
+ mCurrentPageScrollDiff = currentPageScrollDiff;
+ }
+
@Nullable
public TaskView getTaskViewNearestToCenterOfScreen() {
return getTaskViewAt(getPageNearestToCenterOfScreen());
@@ -5867,6 +5879,11 @@ public abstract class RecentsView<
}
}
+ @Override
+ protected void pageBeginTransition() {
+ super.pageBeginTransition();
+ }
+
@Override
protected String getCurrentPageDescription() {
return "";
@@ -6379,6 +6396,12 @@ public abstract class RecentsView<
private int getOffsetFromScrollPosition(
int pageIndex, IntArray topRowIdArray, IntArray bottomRowIdArray) {
+ return getOffsetFromScrollPosition(pageIndex, topRowIdArray, bottomRowIdArray,
+ /* removedPageIndex= */ INVALID_PAGE);
+ }
+
+ protected int getOffsetFromScrollPosition(int pageIndex, IntArray topRowIdArray,
+ IntArray bottomRowIdArray, int removedPageIndex) {
if (!showAsGrid()) {
return 0;
}
@@ -6393,7 +6416,12 @@ public abstract class RecentsView<
return 0;
}
- if (getScrollForPage(pageIndex) != getScrollForPage(indexOfChild(lastGridTaskView))) {
+ int lastGridTaskViewIndex = indexOfChild(lastGridTaskView);
+ // When computing offset, account for a removed page if provided.
+ if (removedPageIndex != INVALID_PAGE && removedPageIndex < lastGridTaskViewIndex) {
+ lastGridTaskViewIndex--;
+ }
+ if (getScrollForPage(pageIndex) != getScrollForPage(lastGridTaskViewIndex)) {
return 0;
}
@@ -6835,7 +6863,7 @@ public abstract class RecentsView<
super.requestChildFocus(child, focused);
}
- private void dispatchScrollChanged() {
+ protected void dispatchScrollChanged() {
runActionOnRemoteHandles(remoteTargetHandle ->
remoteTargetHandle.getTaskViewSimulator().setScroll(getScrollOffset()));
for (int i = mScrollListeners.size() - 1; i >= 0; i--) {
diff --git a/quickstep/src/com/android/quickstep/views/TaskContainer.kt b/quickstep/src/com/android/quickstep/views/TaskContainer.kt
index b187df1e99..1fa3f61821 100644
--- a/quickstep/src/com/android/quickstep/views/TaskContainer.kt
+++ b/quickstep/src/com/android/quickstep/views/TaskContainer.kt
@@ -181,12 +181,18 @@ class TaskContainer(
overlay.addChildForAccessibility(outChildren)
}
- fun setState(state: TaskData?, hasHeader: Boolean, clickCloseListener: OnClickListener?) =
+ fun setState(
+ state: TaskData?,
+ hasHeader: Boolean,
+ canShowAppTimer: Boolean,
+ clickCloseListener: OnClickListener?,
+ ) =
traceSection("TaskContainer.setState") {
if (enableRefactorTaskContentView()) {
(taskContentView as TaskContentView).setState(
TaskUiStateMapper.toTaskHeaderState(state, hasHeader, clickCloseListener),
TaskUiStateMapper.toTaskThumbnailUiState(state),
+ TaskUiStateMapper.toTaskAppTimerUiState(canShowAppTimer, stagePosition, state),
state?.taskId,
)
} else {
diff --git a/quickstep/src/com/android/quickstep/views/TaskView.kt b/quickstep/src/com/android/quickstep/views/TaskView.kt
index df93fc488e..4583a63df2 100644
--- a/quickstep/src/com/android/quickstep/views/TaskView.kt
+++ b/quickstep/src/com/android/quickstep/views/TaskView.kt
@@ -33,6 +33,7 @@ import android.util.Log
import android.view.Display
import android.view.MotionEvent
import android.view.View
+import android.view.View.OnClickListener
import android.view.ViewGroup
import android.view.ViewStub
import android.view.accessibility.AccessibilityNodeInfo
@@ -47,6 +48,7 @@ import com.android.launcher3.AbstractFloatingView
import com.android.launcher3.Flags.enableCursorHoverStates
import com.android.launcher3.Flags.enableDesktopExplodedView
import com.android.launcher3.Flags.enableLargeDesktopWindowingTile
+import com.android.launcher3.Flags.enableRefactorDigitalWellbeingToast
import com.android.launcher3.Flags.enableRefactorTaskContentView
import com.android.launcher3.Flags.enableRefactorTaskThumbnail
import com.android.launcher3.R
@@ -735,7 +737,14 @@ constructor(
// Add DWB accessibility action at the end of the list
taskContainers.forEach {
- it.digitalWellBeingToast?.getDWBAccessibilityAction()?.let(::addAction)
+ if (
+ enableRefactorDigitalWellbeingToast() &&
+ it.taskContentView is TaskContentView
+ ) {
+ it.taskContentView.getSupportedAccessibilityActions().forEach(::addAction)
+ } else {
+ it.digitalWellBeingToast?.getDWBAccessibilityAction()?.let(::addAction)
+ }
}
}
@@ -755,8 +764,14 @@ constructor(
override fun performAccessibilityAction(action: Int, arguments: Bundle?): Boolean {
// TODO(b/343708271): Add support for multiple tasks per action.
taskContainers.forEach {
- if (it.digitalWellBeingToast?.handleAccessibilityAction(action) == true) {
- return true
+ if (enableRefactorDigitalWellbeingToast() && it.taskContentView is TaskContentView) {
+ if (it.taskContentView.handleAccessibilityAction(action)) {
+ return true
+ }
+ } else {
+ if (it.digitalWellBeingToast?.handleAccessibilityAction(action) == true) {
+ return true
+ }
}
TaskOverlayFactory.getEnabledShortcuts(this, it).forEach { shortcut ->
@@ -797,9 +812,11 @@ constructor(
}
?.inflate()
- findViewById(R.id.digital_wellbeing_toast)
- ?.apply { layoutResource = R.layout.digital_wellbeing_toast }
- ?.inflate()
+ if (!enableRefactorDigitalWellbeingToast()) {
+ findViewById(R.id.digital_wellbeing_toast)
+ ?.apply { layoutResource = R.layout.digital_wellbeing_toast }
+ ?.inflate()
+ }
}
override fun onAttachedToWindow() =
@@ -826,9 +843,12 @@ constructor(
val taskId = container.task.key.id
val containerState = mapOfTasks[taskId]
val shouldHaveHeader = (type == TaskViewType.DESKTOP) && enableDesktopExplodedView()
+ val shouldShowAppTimer =
+ (type == TaskViewType.SINGLE || type == TaskViewType.GROUPED)
container.setState(
state = containerState,
hasHeader = shouldHaveHeader,
+ canShowAppTimer = shouldShowAppTimer,
clickCloseListener =
if (shouldHaveHeader) {
{
@@ -1024,6 +1044,13 @@ constructor(
val snapshotView =
if (enableRefactorTaskContentView()) taskContentView.findViewById(thumbnailViewId)
else taskContentView
+
+ val digitalWellBeingToast: DigitalWellBeingToast? =
+ if (enableRefactorDigitalWellbeingToast()) {
+ null
+ } else {
+ findViewById(digitalWellbeingBannerId)!!
+ }
return TaskContainer(
this,
task,
@@ -1032,7 +1059,7 @@ constructor(
iconView,
TransformingTouchDelegate(iconView.asView()),
stagePosition,
- findViewById(digitalWellbeingBannerId)!!,
+ digitalWellBeingToast,
findViewById(showWindowViewId)!!,
taskOverlayFactory,
)
@@ -1718,7 +1745,11 @@ constructor(
private fun onSettledProgressUpdated(settledProgress: Float) {
taskContainers.forEach {
it.iconView.setContentAlpha(settledProgress)
- it.digitalWellBeingToast?.bannerOffsetPercentage = 1f - settledProgress
+ if (enableRefactorDigitalWellbeingToast() && it.taskContentView is TaskContentView) {
+ it.taskContentView.onParentAnimationProgress(settledProgress)
+ } else {
+ it.digitalWellBeingToast?.bannerOffsetPercentage = 1f - settledProgress
+ }
}
}
@@ -1864,7 +1895,11 @@ constructor(
isClickable = modalness == 0f
taskContainers.forEach {
it.iconView.setModalAlpha(1f - modalness)
- it.digitalWellBeingToast?.bannerOffsetPercentage = modalness
+ if (enableRefactorDigitalWellbeingToast() && it.taskContentView is TaskContentView) {
+ it.taskContentView.onParentAnimationProgress(1f - modalness)
+ } else {
+ it.digitalWellBeingToast?.bannerOffsetPercentage = modalness
+ }
}
if (enableGridOnlyOverview()) {
modalAlpha = if (isSelectedTask) 1f else (1f - modalness)
diff --git a/quickstep/tests/multivalentScreenshotTests/src/com/android/quickstep/task/apptimer/TaskAppTimerScreenshotTest.kt b/quickstep/tests/multivalentScreenshotTests/src/com/android/quickstep/task/apptimer/TaskAppTimerScreenshotTest.kt
new file mode 100644
index 0000000000..bef8709769
--- /dev/null
+++ b/quickstep/tests/multivalentScreenshotTests/src/com/android/quickstep/task/apptimer/TaskAppTimerScreenshotTest.kt
@@ -0,0 +1,168 @@
+/*
+ * Copyright (C) 2025 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.quickstep.task.apptimer
+
+import android.content.Context
+import android.graphics.Color
+import android.platform.test.flag.junit.SetFlagsRule
+import android.view.Gravity
+import android.view.LayoutInflater
+import android.widget.FrameLayout
+import com.android.launcher3.Flags
+import com.android.launcher3.R
+import com.android.launcher3.util.Themes
+import com.android.launcher3.util.rule.setFlags
+import com.android.quickstep.task.thumbnail.TaskContentView
+import com.android.quickstep.task.thumbnail.TaskHeaderUiState
+import com.android.quickstep.task.thumbnail.TaskThumbnailUiState.BackgroundOnly
+import com.google.android.apps.nexuslauncher.imagecomparison.goldenpathmanager.ViewScreenshotGoldenPathManager
+import java.time.Duration
+import org.junit.Before
+import org.junit.Rule
+import org.junit.Test
+import org.junit.runner.RunWith
+import platform.test.runner.parameterized.ParameterizedAndroidJunit4
+import platform.test.runner.parameterized.Parameters
+import platform.test.screenshot.DeviceEmulationSpec
+import platform.test.screenshot.Displays
+import platform.test.screenshot.ViewScreenshotTestRule
+import platform.test.screenshot.getEmulatedDevicePathConfig
+
+/** Screenshot tests for the digital wellbeing timer shown in the task content view */
+@RunWith(ParameterizedAndroidJunit4::class)
+class TaskAppTimerScreenshotTest(emulationSpec: DeviceEmulationSpec) {
+ @get:Rule(order = 0) val setFlagsRule = SetFlagsRule()
+
+ @get:Rule(order = 1)
+ val screenshotRule =
+ ViewScreenshotTestRule(
+ emulationSpec,
+ ViewScreenshotGoldenPathManager(getEmulatedDevicePathConfig(emulationSpec)),
+ )
+
+ @Before
+ fun setUp() {
+ setFlagsRule.setFlags(
+ true,
+ Flags.FLAG_ENABLE_REFACTOR_TASK_THUMBNAIL,
+ Flags.FLAG_ENABLE_REFACTOR_TASK_CONTENT_VIEW,
+ Flags.FLAG_ENABLE_REFACTOR_DIGITAL_WELLBEING_TOAST,
+ )
+ }
+
+ @Test
+ fun taskAppTimer_iconAndFullText() {
+ screenshotRule.screenshotTest("taskAppTimer_iconAndFullText") { activity ->
+ activity.actionBar?.hide()
+ val container = createContainer(activity)
+ val taskContentView = createTaskContentView(activity)
+ container.addView(taskContentView, CONTAINER_WIDTH_WIDE, CONTAINER_HEIGHT)
+
+ taskContentView.setState(
+ taskHeaderState = TaskHeaderUiState.HideHeader,
+ taskThumbnailUiState = BackgroundOnly(Color.YELLOW),
+ taskAppTimerUiState = TIMER_UI_STATE,
+ taskId = null,
+ )
+
+ container
+ }
+ }
+
+ @Test
+ fun taskAppTimer_iconAndShortText() {
+ screenshotRule.screenshotTest("taskAppTimer_iconAndShortText") { activity ->
+ activity.actionBar?.hide()
+ val container = createContainer(activity)
+ val taskContentView = createTaskContentView(activity)
+ container.addView(taskContentView, CONTAINER_WIDTH_MEDIUM, CONTAINER_HEIGHT)
+
+ taskContentView.setState(
+ taskHeaderState = TaskHeaderUiState.HideHeader,
+ taskThumbnailUiState = BackgroundOnly(Color.YELLOW),
+ taskAppTimerUiState = TIMER_UI_STATE,
+ taskId = null,
+ )
+
+ container
+ }
+ }
+
+ @Test
+ fun taskAppTimer_iconOnly() {
+ screenshotRule.screenshotTest("taskAppTimer_iconOnly") { activity ->
+ activity.actionBar?.hide()
+ val container = createContainer(activity)
+ val taskContentView = createTaskContentView(activity)
+ container.addView(taskContentView, CONTAINER_WIDTH_NARROW, CONTAINER_HEIGHT)
+
+ taskContentView.setState(
+ taskHeaderState = TaskHeaderUiState.HideHeader,
+ taskThumbnailUiState = BackgroundOnly(Color.YELLOW),
+ taskAppTimerUiState = TIMER_UI_STATE,
+ taskId = null,
+ )
+
+ container
+ }
+ }
+
+ private fun createTaskContentView(context: Context): TaskContentView {
+ val taskContentView =
+ LayoutInflater.from(context).inflate(R.layout.task_content_view, null, false)
+ as TaskContentView
+ taskContentView.cornerRadius = Themes.getDialogCornerRadius(context)
+ return taskContentView
+ }
+
+ private fun createContainer(context: Context): FrameLayout {
+ val container = FrameLayout(context)
+ val lp =
+ FrameLayout.LayoutParams(
+ FrameLayout.LayoutParams.WRAP_CONTENT,
+ FrameLayout.LayoutParams.WRAP_CONTENT,
+ Gravity.CENTER,
+ )
+ container.layoutParams = lp
+
+ return container
+ }
+
+ companion object {
+ private const val CONTAINER_HEIGHT = 700
+ private const val CONTAINER_WIDTH_WIDE = 800
+ private const val CONTAINER_WIDTH_MEDIUM = 400
+ private const val CONTAINER_WIDTH_NARROW = 150
+
+ private val TIMER_UI_STATE =
+ TaskAppTimerUiState.Timer(
+ timeRemaining = Duration.ofHours(23).plusMinutes(2),
+ taskDescription = "test",
+ taskPackageName = "com.test",
+ accessibilityActionId = R.id.action_digital_wellbeing_top_left,
+ )
+
+ @Parameters(name = "{0}")
+ @JvmStatic
+ fun getTestSpecs() =
+ DeviceEmulationSpec.forDisplays(
+ Displays.Phone,
+ isDarkTheme = false,
+ isLandscape = false,
+ )
+ }
+}
diff --git a/quickstep/tests/multivalentScreenshotTests/src/com/android/quickstep/task/thumbnail/TaskContentViewScreenshotTest.kt b/quickstep/tests/multivalentScreenshotTests/src/com/android/quickstep/task/thumbnail/TaskContentViewScreenshotTest.kt
index 5e546f7f1a..41d793f8f5 100644
--- a/quickstep/tests/multivalentScreenshotTests/src/com/android/quickstep/task/thumbnail/TaskContentViewScreenshotTest.kt
+++ b/quickstep/tests/multivalentScreenshotTests/src/com/android/quickstep/task/thumbnail/TaskContentViewScreenshotTest.kt
@@ -23,9 +23,11 @@ import android.view.LayoutInflater
import com.android.launcher3.Flags
import com.android.launcher3.R
import com.android.launcher3.util.rule.setFlags
+import com.android.quickstep.task.apptimer.TaskAppTimerUiState
import com.android.quickstep.task.thumbnail.SplashHelper.createSplash
import com.android.quickstep.task.thumbnail.TaskThumbnailUiState.BackgroundOnly
import com.google.android.apps.nexuslauncher.imagecomparison.goldenpathmanager.ViewScreenshotGoldenPathManager
+import java.time.Duration
import org.junit.Before
import org.junit.Rule
import org.junit.Test
@@ -56,17 +58,22 @@ class TaskContentViewScreenshotTest(emulationSpec: DeviceEmulationSpec) {
true,
Flags.FLAG_ENABLE_REFACTOR_TASK_THUMBNAIL,
Flags.FLAG_ENABLE_REFACTOR_TASK_CONTENT_VIEW,
+ Flags.FLAG_ENABLE_REFACTOR_DIGITAL_WELLBEING_TOAST,
)
}
@Test
fun taskContentView_recyclesToUninitialized() {
- screenshotRule.screenshotTest("taskContentView_uninitialized") { activity ->
+ screenshotRule.screenshotTest(
+ "taskContentView_uninitialized",
+ ViewScreenshotTestRule.Mode.MatchSize,
+ ) { activity ->
activity.actionBar?.hide()
val taskContentView = createTaskContentView(activity)
taskContentView.setState(
TaskHeaderUiState.HideHeader,
BackgroundOnly(Color.YELLOW),
+ TIMER_UI_STATE,
null,
)
taskContentView.onRecycle()
@@ -76,7 +83,10 @@ class TaskContentViewScreenshotTest(emulationSpec: DeviceEmulationSpec) {
@Test
fun taskContentView_shows_thumbnail_and_header() {
- screenshotRule.screenshotTest("taskContentView_shows_thumbnail_and_header") { activity ->
+ screenshotRule.screenshotTest(
+ "taskContentView_shows_thumbnail_and_header",
+ ViewScreenshotTestRule.Mode.MatchSize,
+ ) { activity ->
activity.actionBar?.hide()
createTaskContentView(activity).apply {
setState(
@@ -87,6 +97,7 @@ class TaskContentViewScreenshotTest(emulationSpec: DeviceEmulationSpec) {
) {}
),
BackgroundOnly(Color.YELLOW),
+ NO_TIMER_UI_STATE,
null,
)
}
@@ -95,12 +106,20 @@ class TaskContentViewScreenshotTest(emulationSpec: DeviceEmulationSpec) {
@Test
fun taskContentView_scaled_roundRoundedCorners() {
- screenshotRule.screenshotTest("taskContentView_scaledRoundedCorners") { activity ->
+ screenshotRule.screenshotTest(
+ "taskContentView_scaledRoundedCorners",
+ ViewScreenshotTestRule.Mode.MatchSize,
+ ) { activity ->
activity.actionBar?.hide()
createTaskContentView(activity).apply {
scaleX = 0.75f
scaleY = 0.3f
- setState(TaskHeaderUiState.HideHeader, BackgroundOnly(Color.YELLOW), null)
+ setState(
+ TaskHeaderUiState.HideHeader,
+ BackgroundOnly(Color.YELLOW),
+ NO_TIMER_UI_STATE,
+ null,
+ )
}
}
}
@@ -124,5 +143,14 @@ class TaskContentViewScreenshotTest(emulationSpec: DeviceEmulationSpec) {
)
const val CORNER_RADIUS = 56f
+
+ private val TIMER_UI_STATE =
+ TaskAppTimerUiState.Timer(
+ timeRemaining = Duration.ofHours(2).plusMinutes(20L),
+ taskDescription = "test",
+ taskPackageName = "com.test",
+ accessibilityActionId = R.id.action_digital_wellbeing_top_left,
+ )
+ private val NO_TIMER_UI_STATE = TaskAppTimerUiState.NoTimer(taskDescription = "test")
}
}
diff --git a/quickstep/tests/multivalentTests/src/com/android/launcher3/taskbar/TaskbarOverflowTest.kt b/quickstep/tests/multivalentTests/src/com/android/launcher3/taskbar/TaskbarOverflowTest.kt
index 55055bc73e..9e1d25afda 100644
--- a/quickstep/tests/multivalentTests/src/com/android/launcher3/taskbar/TaskbarOverflowTest.kt
+++ b/quickstep/tests/multivalentTests/src/com/android/launcher3/taskbar/TaskbarOverflowTest.kt
@@ -27,11 +27,12 @@ import androidx.test.core.app.ApplicationProvider
import com.android.launcher3.BubbleTextView
import com.android.launcher3.Flags.FLAG_ENABLE_ALT_TAB_KQS_FLATENNING
import com.android.launcher3.Flags.FLAG_ENABLE_MULTI_INSTANCE_MENU_TASKBAR
-import com.android.launcher3.Flags.FLAG_TASKBAR_OVERFLOW
import com.android.launcher3.R
import com.android.launcher3.dagger.LauncherAppSingleton
import com.android.launcher3.dagger.LauncherComponentProvider.appComponent
import com.android.launcher3.model.BgDataModel
+import com.android.launcher3.model.BgDataModel.FixedContainerItems
+import com.android.launcher3.model.StringCache
import com.android.launcher3.model.data.ItemInfo
import com.android.launcher3.model.data.TaskItemInfo
import com.android.launcher3.model.data.WorkspaceItemInfo
@@ -56,6 +57,7 @@ import com.android.launcher3.taskbar.rules.TaskbarUnitTestRule.InjectController
import com.android.launcher3.taskbar.rules.TaskbarWindowSandboxContext
import com.android.launcher3.util.AllModulesForTest
import com.android.launcher3.util.FakePrefsModule
+import com.android.launcher3.util.IntSparseArrayMap
import com.android.launcher3.util.LauncherMultivalentJUnit
import com.android.launcher3.util.LauncherMultivalentJUnit.EmulatedDevices
import com.android.launcher3.util.Preconditions.assertNotNull
@@ -70,6 +72,7 @@ import com.android.systemui.shared.recents.model.Task
import com.android.window.flags.Flags.FLAG_ENABLE_DESKTOP_WINDOWING_MODE
import com.android.window.flags.Flags.FLAG_ENABLE_DESKTOP_WINDOWING_TASKBAR_RUNNING_APPS
import com.android.window.flags.Flags.FLAG_ENABLE_PINNING_APP_WITH_CONTEXT_MENU
+import com.android.window.flags.Flags.FLAG_ENABLE_TASKBAR_OVERFLOW
import com.android.wm.shell.Flags.FLAG_ENABLE_BUBBLE_BAR
import com.android.wm.shell.desktopmode.IDesktopTaskListener
import com.google.common.truth.Truth.assertThat
@@ -88,10 +91,10 @@ import org.mockito.kotlin.whenever
@RunWith(LauncherMultivalentJUnit::class)
@EmulatedDevices(["pixelTablet2023"])
@EnableFlags(
- FLAG_TASKBAR_OVERFLOW,
FLAG_ENABLE_DESKTOP_WINDOWING_TASKBAR_RUNNING_APPS,
FLAG_ENABLE_DESKTOP_WINDOWING_MODE,
FLAG_ENABLE_BUBBLE_BAR,
+ FLAG_ENABLE_TASKBAR_OVERFLOW,
)
@DisableFlags(FLAG_ENABLE_MULTI_INSTANCE_MENU_TASKBAR)
class TaskbarOverflowTest {
@@ -571,7 +574,7 @@ class TaskbarOverflowTest {
taskbarView.updateItems(hotseatItems, recentAppsController.shownTasks)
modelCallback.recentAppsController = recentAppsController
context.baseContext.appComponent.launcherAppState.model.addCallbacksAndLoad(modelCallback)
- modelCallback.bindItems(hotseatItems.toList(), false)
+ modelCallback.bindItemsAdded(hotseatItems.toList())
return taskbarView
}
@@ -694,9 +697,16 @@ class TaskbarOverflowTest {
var hotseatItems = mutableListOf()
var recentAppsController: TaskbarRecentAppsController? = null
- override fun bindItems(shortcuts: List, forceAnimateIcons: Boolean) {
+ override fun bindCompleteModel(
+ itemIdMap: IntSparseArrayMap,
+ extraItems: MutableList,
+ stringCache: StringCache,
+ isBindingSync: Boolean,
+ ) = bindItemsAdded(itemIdMap.toList())
+
+ override fun bindItemsAdded(items: List) {
runOnMainSync {
- shortcuts
+ items
.filter { item ->
item is WorkspaceItemInfo &&
!hotseatItems.any { it.targetPackage == item.targetPackage }
diff --git a/quickstep/tests/multivalentTests/src/com/android/launcher3/taskbar/TaskbarViewWithLayoutTransitionTest.kt b/quickstep/tests/multivalentTests/src/com/android/launcher3/taskbar/TaskbarViewWithLayoutTransitionTest.kt
index 2df4fab457..63fd1607f5 100644
--- a/quickstep/tests/multivalentTests/src/com/android/launcher3/taskbar/TaskbarViewWithLayoutTransitionTest.kt
+++ b/quickstep/tests/multivalentTests/src/com/android/launcher3/taskbar/TaskbarViewWithLayoutTransitionTest.kt
@@ -19,7 +19,6 @@ package com.android.launcher3.taskbar
import android.platform.test.annotations.EnableFlags
import android.platform.test.flag.junit.SetFlagsRule
import android.view.View
-import com.android.launcher3.Flags.FLAG_TASKBAR_OVERFLOW
import com.android.launcher3.R
import com.android.launcher3.statehandlers.DesktopVisibilityController
import com.android.launcher3.taskbar.TaskbarControllerTestUtil.runOnMainSync
@@ -36,6 +35,7 @@ import com.android.launcher3.taskbar.rules.TaskbarUnitTestRule.ForceRtl
import com.android.launcher3.taskbar.rules.TaskbarWindowSandboxContext
import com.android.launcher3.util.LauncherMultivalentJUnit
import com.android.launcher3.util.LauncherMultivalentJUnit.EmulatedDevices
+import com.android.window.flags.Flags.FLAG_ENABLE_TASKBAR_OVERFLOW
import com.android.window.flags.Flags.FLAG_ENABLE_TASKBAR_RECENTS_LAYOUT_TRANSITION
import com.google.common.truth.Truth.assertThat
import org.junit.Before
@@ -46,7 +46,7 @@ import org.mockito.kotlin.whenever
@RunWith(LauncherMultivalentJUnit::class)
@EmulatedDevices(["pixelFoldable2023", "pixelTablet2023"])
-@EnableFlags(FLAG_ENABLE_TASKBAR_RECENTS_LAYOUT_TRANSITION, FLAG_TASKBAR_OVERFLOW)
+@EnableFlags(FLAG_ENABLE_TASKBAR_OVERFLOW, FLAG_ENABLE_TASKBAR_RECENTS_LAYOUT_TRANSITION)
class TaskbarViewWithLayoutTransitionTest {
@get:Rule(order = 0) val setFlagsRule = SetFlagsRule()
diff --git a/quickstep/tests/multivalentTests/src/com/android/quickstep/recents/data/TasksRepositoryTest.kt b/quickstep/tests/multivalentTests/src/com/android/quickstep/recents/data/TasksRepositoryTest.kt
index a3468a7958..8c0b984861 100644
--- a/quickstep/tests/multivalentTests/src/com/android/quickstep/recents/data/TasksRepositoryTest.kt
+++ b/quickstep/tests/multivalentTests/src/com/android/quickstep/recents/data/TasksRepositoryTest.kt
@@ -23,7 +23,6 @@ import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.view.Display.DEFAULT_DISPLAY
import androidx.test.ext.junit.runners.AndroidJUnit4
-import com.android.launcher3.util.SplitConfigurationOptions
import com.android.launcher3.util.TestDispatcherProvider
import com.android.quickstep.util.DesktopTask
import com.android.quickstep.util.SingleTask
@@ -148,6 +147,28 @@ class TasksRepositoryTest {
assertThat(systemUnderTest.getThumbnailById(1).first()!!.thumbnail).isEqualTo(bitmap1)
}
+ @Test
+ fun getAllTaskData_copiesPreviouslyLoadedImagesForTasksStillPresent() =
+ testScope.runTest {
+ recentsModel.seedTasks(defaultTaskList)
+ systemUnderTest.getAllTaskData(forceRefresh = true)
+ systemUnderTest.setVisibleTasks(setOf(0, 1))
+
+ // Seed new task with same id
+ val newTask0 = SingleTask(createTaskWithId(0))
+ val newSeededTasks =
+ defaultTaskList.map {
+ if (it is SingleTask && it.task.key.id == 0) newTask0 else it
+ }
+ recentsModel.seedTasks(newSeededTasks)
+ systemUnderTest.getAllTaskData(forceRefresh = true)
+
+ // Assert no additional loads, assert images present
+ assertThat(systemUnderTest.getThumbnailById(0).first()?.thumbnail)
+ .isEqualTo(taskThumbnailDataSource.taskIdToBitmap[0])
+ assertThat(taskThumbnailDataSource.getNumberOfGetThumbnailCalls(0)).isEqualTo(1)
+ }
+
@Test
fun getAllTaskData_clearsPreviouslyLoadedImagesForRemovedTasks() =
testScope.runTest {
diff --git a/quickstep/tests/multivalentTests/src/com/android/quickstep/recents/ui/mapper/TaskUiStateMapperTest.kt b/quickstep/tests/multivalentTests/src/com/android/quickstep/recents/ui/mapper/TaskUiStateMapperTest.kt
index e55d8e53f2..db78449b2f 100644
--- a/quickstep/tests/multivalentTests/src/com/android/quickstep/recents/ui/mapper/TaskUiStateMapperTest.kt
+++ b/quickstep/tests/multivalentTests/src/com/android/quickstep/recents/ui/mapper/TaskUiStateMapperTest.kt
@@ -26,7 +26,11 @@ import android.view.Surface
import android.view.View
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.android.launcher3.Flags
+import com.android.launcher3.R
+import com.android.launcher3.util.SplitConfigurationOptions.STAGE_POSITION_BOTTOM_OR_RIGHT
+import com.android.launcher3.util.SplitConfigurationOptions.STAGE_POSITION_TOP_OR_LEFT
import com.android.quickstep.recents.ui.viewmodel.TaskData
+import com.android.quickstep.task.apptimer.TaskAppTimerUiState
import com.android.quickstep.task.thumbnail.TaskHeaderUiState
import com.android.quickstep.task.thumbnail.TaskThumbnailUiState
import com.android.quickstep.task.thumbnail.TaskThumbnailUiState.LiveTile
@@ -189,6 +193,96 @@ class TaskUiStateMapperTest {
assertThat(result).isEqualTo(expected)
}
+ @Test
+ fun toTaskAppTimer_nullTaskData_returnsUninitialized() {
+ val result =
+ TaskUiStateMapper.toTaskAppTimerUiState(
+ canShowAppTimer = true,
+ stagePosition = STAGE_POSITION_DEFAULT,
+ taskData = null,
+ )
+
+ val expected = TaskAppTimerUiState.Uninitialized
+ assertThat(result).isEqualTo(expected)
+ }
+
+ @Test
+ fun toTaskAppTimer_noTaskData_returnsUninitialized() {
+ val result =
+ TaskUiStateMapper.toTaskAppTimerUiState(
+ canShowAppTimer = true,
+ stagePosition = STAGE_POSITION_DEFAULT,
+ taskData = TaskData.NoData(TASK_ID),
+ )
+
+ val expected = TaskAppTimerUiState.Uninitialized
+ assertThat(result).isEqualTo(expected)
+ }
+
+ @Test
+ fun toTaskAppTimer_canShowAppTimerFalse_returnsNoTimer() {
+ val result =
+ TaskUiStateMapper.toTaskAppTimerUiState(
+ canShowAppTimer = false,
+ stagePosition = STAGE_POSITION_DEFAULT,
+ taskData = TASK_DATA,
+ )
+
+ val expected = TaskAppTimerUiState.NoTimer(taskDescription = TASK_TITLE_DESCRIPTION)
+ assertThat(result).isEqualTo(expected)
+ }
+
+ @Test
+ fun toTaskAppTimer_timerNullAndCanShow_returnsNoTimer() {
+ val result =
+ TaskUiStateMapper.toTaskAppTimerUiState(
+ canShowAppTimer = false,
+ stagePosition = STAGE_POSITION_DEFAULT,
+ taskData = TASK_DATA.copy(remainingAppTimerDuration = null),
+ )
+
+ val expected = TaskAppTimerUiState.NoTimer(taskDescription = TASK_TITLE_DESCRIPTION)
+ assertThat(result).isEqualTo(expected)
+ }
+
+ @Test
+ fun toTaskAppTimer_timerPresentAndCanShow_returnsTimer() {
+ val result =
+ TaskUiStateMapper.toTaskAppTimerUiState(
+ canShowAppTimer = true,
+ stagePosition = STAGE_POSITION_DEFAULT,
+ taskData = TASK_DATA.copy(remainingAppTimerDuration = TASK_APP_TIMER_DURATION),
+ )
+
+ val expected =
+ TaskAppTimerUiState.Timer(
+ timeRemaining = TASK_APP_TIMER_DURATION,
+ taskDescription = TASK_DATA.titleDescription,
+ taskPackageName = TASK_DATA.packageName,
+ accessibilityActionId = R.id.action_digital_wellbeing_top_left,
+ )
+ assertThat(result).isEqualTo(expected)
+ }
+
+ @Test
+ fun toTaskAppTimer_stagePositionBottomOrRight_returnsTimerWithCorrectActionId() {
+ val result =
+ TaskUiStateMapper.toTaskAppTimerUiState(
+ canShowAppTimer = true,
+ stagePosition = STAGE_POSITION_BOTTOM_OR_RIGHT,
+ taskData = TASK_DATA.copy(remainingAppTimerDuration = TASK_APP_TIMER_DURATION),
+ )
+
+ val expected =
+ TaskAppTimerUiState.Timer(
+ timeRemaining = TASK_APP_TIMER_DURATION,
+ taskDescription = TASK_DATA.titleDescription,
+ taskPackageName = TASK_DATA.packageName,
+ accessibilityActionId = R.id.action_digital_wellbeing_bottom_right,
+ )
+ assertThat(result).isEqualTo(expected)
+ }
+
private companion object {
const val TASK_TITLE_DESCRIPTION = "Title Description 1"
var TASK_ID = 1
@@ -198,6 +292,8 @@ class TaskUiStateMapperTest {
val TASK_THUMBNAIL_DATA =
ThumbnailData(thumbnail = TASK_THUMBNAIL, rotation = Surface.ROTATION_0)
val TASK_BACKGROUND_COLOR = Color.rgb(1, 2, 3)
+ val TASK_APP_TIMER_DURATION: Duration = Duration.ofMillis(30)
+ val STAGE_POSITION_DEFAULT = STAGE_POSITION_TOP_OR_LEFT
val TASK_DATA =
TaskData.Data(
TASK_ID,
@@ -209,7 +305,7 @@ class TaskUiStateMapperTest {
backgroundColor = TASK_BACKGROUND_COLOR,
isLocked = false,
isLiveTile = false,
- remainingAppTimerDuration = Duration.ofMillis(30),
+ remainingAppTimerDuration = TASK_APP_TIMER_DURATION,
)
}
}
diff --git a/quickstep/tests/multivalentTests/src/com/android/quickstep/task/apptimer/DurationFormatterTest.kt b/quickstep/tests/multivalentTests/src/com/android/quickstep/task/apptimer/DurationFormatterTest.kt
new file mode 100644
index 0000000000..685927fada
--- /dev/null
+++ b/quickstep/tests/multivalentTests/src/com/android/quickstep/task/apptimer/DurationFormatterTest.kt
@@ -0,0 +1,87 @@
+/*
+ * Copyright (C) 2025 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.quickstep.task.apptimer
+
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import com.android.launcher3.R
+import com.android.launcher3.util.SandboxApplication
+import com.google.common.truth.Truth.assertThat
+import java.time.Duration
+import java.util.Locale
+import org.junit.After
+import org.junit.Before
+import org.junit.Rule
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@RunWith(AndroidJUnit4::class)
+class DurationFormatterTest {
+ @get:Rule val context = SandboxApplication()
+
+ private var systemLocale: Locale? = null
+
+ @Before
+ fun setup() {
+ systemLocale = Locale.getDefault()
+ val testLocale = Locale("en", "us")
+ Locale.setDefault(testLocale)
+ }
+
+ @Test
+ fun getReadableDuration_hasHoursAndMinutes_returnsNarrowString() {
+ val result =
+ DurationFormatter.format(
+ context,
+ Duration.ofHours(12).plusMinutes(55),
+ durationLessThanOneMinuteStringId = R.string.shorter_duration_less_than_one_minute,
+ )
+
+ val expected = "12h 55m"
+ assertThat(result).isEqualTo(expected)
+ }
+
+ @Test
+ fun getReadableDuration_hasFullHours_returnsWideString() {
+ val result =
+ DurationFormatter.format(
+ context = context,
+ duration = Duration.ofHours(12),
+ durationLessThanOneMinuteStringId = R.string.shorter_duration_less_than_one_minute,
+ )
+
+ val expected = "12 hours"
+ assertThat(result).isEqualTo(expected)
+ }
+
+ @Test
+ fun getReadableDuration_hasFullMinutesNoHours_returnsWideString() {
+ val result =
+ DurationFormatter.format(
+ context = context,
+ duration = Duration.ofMinutes(50),
+ durationLessThanOneMinuteStringId = R.string.shorter_duration_less_than_one_minute,
+ )
+
+ val expected = "50 minutes"
+ assertThat(result).isEqualTo(expected)
+ }
+
+ @After
+ fun tearDown() {
+ Locale.setDefault(systemLocale)
+ }
+}
diff --git a/src/com/android/launcher3/Launcher.java b/src/com/android/launcher3/Launcher.java
index 2d77762563..0dd3ff2c2e 100644
--- a/src/com/android/launcher3/Launcher.java
+++ b/src/com/android/launcher3/Launcher.java
@@ -189,7 +189,6 @@ import com.android.launcher3.dragndrop.DragView;
import com.android.launcher3.dragndrop.LauncherDragController;
import com.android.launcher3.folder.Folder;
import com.android.launcher3.folder.FolderIcon;
-import com.android.launcher3.icons.IconCache;
import com.android.launcher3.keyboard.ViewGroupFocusHelper;
import com.android.launcher3.logger.LauncherAtom;
import com.android.launcher3.logger.LauncherAtom.ContainerInfo;
@@ -202,6 +201,7 @@ import com.android.launcher3.logging.StartupLatencyLogger;
import com.android.launcher3.logging.StatsLogManager;
import com.android.launcher3.logging.StatsLogManager.LauncherLatencyEvent;
import com.android.launcher3.model.BgDataModel.Callbacks;
+import com.android.launcher3.model.BgDataModel.FixedContainerItems;
import com.android.launcher3.model.ItemInstallQueue;
import com.android.launcher3.model.ModelWriter;
import com.android.launcher3.model.StringCache;
@@ -230,8 +230,8 @@ import com.android.launcher3.util.BackPressHandler;
import com.android.launcher3.util.CannedAnimationCoordinator;
import com.android.launcher3.util.ComponentKey;
import com.android.launcher3.util.ContextTracker;
-import com.android.launcher3.util.IntArray;
import com.android.launcher3.util.IntSet;
+import com.android.launcher3.util.IntSparseArrayMap;
import com.android.launcher3.util.ItemInflater;
import com.android.launcher3.util.KeyboardShortcutsDelegate;
import com.android.launcher3.util.LauncherBindableItemsContainer;
@@ -285,7 +285,6 @@ import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import java.util.function.Supplier;
-import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
@@ -372,7 +371,6 @@ public class Launcher extends StatefulActivity
private LauncherModel mModel;
private ModelWriter mModelWriter;
- private IconCache mIconCache;
private LauncherAccessibilityDelegate mAccessibilityDelegate;
private PopupDataProvider mPopupDataProvider;
@@ -525,7 +523,6 @@ public class Launcher extends StatefulActivity
initDeviceProfile(idp);
idp.addOnChangeListener(this);
mSharedPrefs = LauncherPrefs.getPrefs(this);
- mIconCache = app.getIconCache();
mAccessibilityDelegate = createAccessibilityDelegate();
initDragController();
@@ -2200,60 +2197,21 @@ public class Launcher extends StatefulActivity
}
@Override
- public IntSet getPagesToBindSynchronously(IntArray orderedScreenIds) {
- return mModelCallbacks.getPagesToBindSynchronously(orderedScreenIds);
+ public void bindCompleteModelAsync(IntSparseArrayMap itemIdMap,
+ List extraItems, StringCache stringCache, boolean isBindingSync) {
+ mModelCallbacks.bindCompleteModelAsync(itemIdMap, extraItems, stringCache, isBindingSync);
}
@Override
- public void startBinding() {
- mModelCallbacks.startBinding();
+ public void bindItemsAdded(@NonNull List items) {
+ mModelCallbacks.bindItemsAdded(items);
}
- @Override
- public void bindScreens(IntArray orderedScreenIds) {
- mModelCallbacks.bindScreens(orderedScreenIds);
- }
-
- /**
- * Remove odd number because they are already included when isTwoPanels and add the pair screen
- * if not present.
- */
- private IntArray filterTwoPanelScreenIds(IntArray orderedScreenIds) {
- IntSet screenIds = IntSet.wrap(orderedScreenIds);
- orderedScreenIds.forEach(screenId -> {
- if (screenId % 2 == 1) {
- screenIds.remove(screenId);
- // In case the pair is not added, add it
- if (!mWorkspace.containsScreenId(screenId - 1)) {
- screenIds.add(screenId - 1);
- }
- }
- });
- return screenIds.getArray();
- }
-
- @Override
- public void bindAppsAdded(IntArray newScreens, ArrayList addNotAnimated,
- ArrayList addAnimated) {
- mModelCallbacks.bindAppsAdded(newScreens, addNotAnimated, addAnimated);
- }
-
- /**
- * Bind the items start-end from the list.
- *
- * Implementation of the method from LauncherModel.Callbacks.
- */
- @Override
- public void bindItems(final List items, final boolean forceAnimateIcons) {
- bindInflatedItems(items.stream()
- .map(i -> Pair.create(i, getItemInflater().inflateItem(i)))
- .collect(Collectors.toList()),
- forceAnimateIcons ? new AnimatorSet() : null);
- }
-
- @Override
- public void bindInflatedItems(List> items) {
- bindInflatedItems(items, null);
+ /** Inflates the binds the provided item using animation */
+ public void inflateAndBindItemWithAnimation(ItemInfo info) {
+ bindInflatedItems(
+ Collections.singletonList(Pair.create(info, getItemInflater().inflateItem(info))),
+ new AnimatorSet());
}
/**
@@ -2365,6 +2323,9 @@ public class Launcher extends StatefulActivity
return info;
}
+ /** Called when a new LauncherModel data binding is starting */
+ public void startBinding() { }
+
/**
* Call back when ModelCallbacks finish binding the Launcher data.
*/
@@ -2379,19 +2340,11 @@ public class Launcher extends StatefulActivity
.logCardinality(workspaceItemCount)
.logEnd(LauncherLatencyEvent.LAUNCHER_LATENCY_STARTUP_WORKSPACE_LOADER_ASYNC);
}
- MAIN_EXECUTOR.getHandler().postAtFrontOfQueue(() -> {
+ MAIN_EXECUTOR.getHandler().postAtFrontOfQueue(() ->
mStartupLatencyLogger
.logEnd(LAUNCHER_LATENCY_STARTUP_TOTAL_DURATION)
.log()
- .reset();
- });
- }
-
- @Override
- public void onInitialBindComplete(IntSet boundPages, RunnableList pendingTasks,
- RunnableList onCompleteSignal, int workspaceItemCount, boolean isBindSync) {
- mModelCallbacks.onInitialBindComplete(boundPages, pendingTasks, onCompleteSignal,
- workspaceItemCount, isBindSync);
+ .reset());
if (mIsColdStartupAfterReboot) {
Trace.endAsyncSection(COLD_STARTUP_TRACE_METHOD_NAME,
COLD_STARTUP_TRACE_COOKIE);
@@ -2404,7 +2357,7 @@ public class Launcher extends StatefulActivity
* Implementation of the method from LauncherModel.Callbacks.
*/
public void finishBindingItems(IntSet pagesBoundFirst) {
- mModelCallbacks.finishBindingItems(pagesBoundFirst);
+ TestEventEmitter.sendEvent(TestEvent.WORKSPACE_FINISH_LOADING);
}
private boolean canAnimatePageChange() {
@@ -3056,7 +3009,6 @@ public class Launcher extends StatefulActivity
return super.getStatsLogManager().withDefaultInstanceId(mAllAppsSessionLogId);
}
- @Override
@NonNull
public ItemInflater getItemInflater() {
return mItemInflater;
diff --git a/src/com/android/launcher3/LauncherModel.kt b/src/com/android/launcher3/LauncherModel.kt
index 6d35de5020..b3e99050c9 100644
--- a/src/com/android/launcher3/LauncherModel.kt
+++ b/src/com/android/launcher3/LauncherModel.kt
@@ -48,7 +48,6 @@ import com.android.launcher3.model.data.WorkspaceItemInfo
import com.android.launcher3.pm.UserCache
import com.android.launcher3.shortcuts.ShortcutRequest
import com.android.launcher3.util.DaggerSingletonTracker
-import com.android.launcher3.util.Executors.MAIN_EXECUTOR
import com.android.launcher3.util.Executors.MODEL_EXECUTOR
import com.android.launcher3.util.PackageUserKey
import java.io.PrintWriter
@@ -281,9 +280,6 @@ constructor(
val bindAllCallbacks = wasRunning || !bindDirectly || newCallbacks.isEmpty()
val callbacksList = if (bindAllCallbacks) callbacks else newCallbacks
if (callbacksList.isNotEmpty()) {
- // Clear any pending bind-runnables from the synchronized load process.
- callbacksList.forEach { MAIN_EXECUTOR.execute(it::clearPendingBinds) }
-
val launcherBinder = binderFactory.createBinder(callbacksList)
if (bindDirectly) {
// Divide the set of loaded items into those that we are binding synchronously,
diff --git a/src/com/android/launcher3/ModelCallbacks.kt b/src/com/android/launcher3/ModelCallbacks.kt
index cc5ac499a8..d0490c7a13 100644
--- a/src/com/android/launcher3/ModelCallbacks.kt
+++ b/src/com/android/launcher3/ModelCallbacks.kt
@@ -1,25 +1,39 @@
package com.android.launcher3
-import android.annotation.TargetApi
-import android.os.Build
+import android.animation.AnimatorSet
+import android.os.CancellationSignal
import android.os.Trace
import android.util.Log
+import android.util.Pair
+import androidx.annotation.AnyThread
import androidx.annotation.UiThread
+import androidx.annotation.VisibleForTesting
+import com.android.launcher3.BuildConfig.QSB_ON_FIRST_SCREEN
import com.android.launcher3.LauncherConstants.TraceEvents
+import com.android.launcher3.LauncherSettings.Favorites.CONTAINER_DESKTOP
+import com.android.launcher3.LauncherSettings.Favorites.CONTAINER_HOTSEAT
import com.android.launcher3.Utilities.SHOULD_SHOW_FIRST_PAGE_WIDGET
import com.android.launcher3.WorkspaceLayoutManager.FIRST_SCREEN_ID
import com.android.launcher3.allapps.AllAppsStore
import com.android.launcher3.config.FeatureFlags
-import com.android.launcher3.debug.TestEventEmitter
-import com.android.launcher3.debug.TestEventEmitter.TestEvent
import com.android.launcher3.model.BgDataModel
+import com.android.launcher3.model.BgDataModel.FixedContainerItems
+import com.android.launcher3.model.ItemInstallQueue
+import com.android.launcher3.model.ItemInstallQueue.FLAG_LOADER_RUNNING
+import com.android.launcher3.model.ModelUtils.WIDGET_FILTER
+import com.android.launcher3.model.ModelUtils.currentScreenContentFilter
import com.android.launcher3.model.StringCache
import com.android.launcher3.model.data.AppInfo
import com.android.launcher3.model.data.ItemInfo
import com.android.launcher3.popup.PopupContainerWithArrow
import com.android.launcher3.util.ComponentKey
+import com.android.launcher3.util.Executors
+import com.android.launcher3.util.Executors.MAIN_EXECUTOR
import com.android.launcher3.util.IntArray as LIntArray
+import com.android.launcher3.util.IntArray
import com.android.launcher3.util.IntSet as LIntSet
+import com.android.launcher3.util.IntSet
+import com.android.launcher3.util.IntSparseArrayMap
import com.android.launcher3.util.ItemInfoMatcher
import com.android.launcher3.util.PackageUserKey
import com.android.launcher3.util.Preconditions
@@ -28,19 +42,19 @@ import com.android.launcher3.util.TraceHelper
import com.android.launcher3.util.ViewOnDrawExecutor
import com.android.launcher3.widget.PendingAddWidgetInfo
import com.android.launcher3.widget.model.WidgetsListBaseEntry
+import java.util.concurrent.Executor
+import java.util.concurrent.atomic.AtomicReference
import java.util.function.Predicate
-private const val TAG = "ModelCallbacks"
-
class ModelCallbacks(private var launcher: Launcher) : BgDataModel.Callbacks {
- var synchronouslyBoundPages = LIntSet()
- var pagesToBindSynchronously = LIntSet()
+ private var activeBindTask = AtomicReference(CancellationSignal())
+ var synchronouslyBoundPages = IntSet()
+ var pagesToBindSynchronously = IntSet()
var stringCache: StringCache? = null
var pendingExecutor: ViewOnDrawExecutor? = null
-
var workspaceLoading = true
/**
@@ -48,7 +62,7 @@ class ModelCallbacks(private var launcher: Launcher) : BgDataModel.Callbacks {
*
* Implementation of the method from LauncherModel.Callbacks.
*/
- override fun startBinding() {
+ private fun startBinding() {
TraceHelper.INSTANCE.beginSection("startBinding")
// Floating panels (except the full widget sheet) are associated with individual icons. If
// we are starting a fresh bind, close all such panels as all the icons are about
@@ -74,11 +88,11 @@ class ModelCallbacks(private var launcher: Launcher) : BgDataModel.Callbacks {
" and is setting to ${launcher.deviceProfile.isVerticalBarLayout}",
)
launcher.hotseat?.resetLayout(launcher.deviceProfile.isVerticalBarLayout)
+ launcher.startBinding()
TraceHelper.INSTANCE.endSection()
}
- @TargetApi(Build.VERSION_CODES.S)
- override fun onInitialBindComplete(
+ private fun onInitialBindComplete(
boundPages: LIntSet,
pendingTasks: RunnableList,
onCompleteSignal: RunnableList,
@@ -123,7 +137,7 @@ class ModelCallbacks(private var launcher: Launcher) : BgDataModel.Callbacks {
*
* Implementation of the method from LauncherModel.Callbacks.
*/
- override fun finishBindingItems(pagesBoundFirst: LIntSet?) {
+ private fun finishBindingItems(pagesBoundFirst: IntSet?) {
TraceHelper.INSTANCE.beginSection("finishBindingItems")
val deviceProfile = launcher.deviceProfile
launcher.workspace.restoreInstanceStateForRemainingPages()
@@ -137,7 +151,7 @@ class ModelCallbacks(private var launcher: Launcher) : BgDataModel.Callbacks {
// Since we are just resetting the current page without user interaction,
// override the previous page so we don't log the page switch.
launcher.workspace.setCurrentPage(currentPage, currentPage /* overridePrevPage */)
- pagesToBindSynchronously = LIntSet()
+ pagesToBindSynchronously = IntSet()
// Cache one page worth of icons
launcher.viewCache.setCacheSize(
@@ -151,14 +165,14 @@ class ModelCallbacks(private var launcher: Launcher) : BgDataModel.Callbacks {
/*pause=*/ false,
deviceProfile.isTwoPanels,
)
- TestEventEmitter.sendEvent(TestEvent.WORKSPACE_FINISH_LOADING)
+ launcher.finishBindingItems(pagesBoundFirst)
}
/**
* Clear any pending bind callbacks. This is called when is loader is planning to perform a full
* rebind from scratch.
*/
- override fun clearPendingBinds() {
+ fun clearPendingBinds() {
pendingExecutor?.cancel() ?: return
pendingExecutor = null
@@ -213,7 +227,7 @@ class ModelCallbacks(private var launcher: Launcher) : BgDataModel.Callbacks {
.filter { workspace.isContainerSupported(it.container) }
.let {
if (it.isNotEmpty()) {
- launcher.bindItems(it, false)
+ bindItems(it, false)
}
}
workspace.stripEmptyScreens()
@@ -236,7 +250,7 @@ class ModelCallbacks(private var launcher: Launcher) : BgDataModel.Callbacks {
}
/** Returns the ids of the workspaces to bind. */
- override fun getPagesToBindSynchronously(orderedScreenIds: LIntArray): LIntSet {
+ private fun getPagesToBindSynchronously(orderedScreenIds: IntArray): IntSet {
// If workspace binding is still in progress, getCurrentPageScreenIds won't be
// accurate, and we should use mSynchronouslyBoundPages that's set during initial binding.
val visibleIds =
@@ -246,7 +260,7 @@ class ModelCallbacks(private var launcher: Launcher) : BgDataModel.Callbacks {
else -> synchronouslyBoundPages
}
// Launcher IntArray has the same name as Kotlin IntArray
- val result = LIntSet()
+ val result = IntSet()
if (visibleIds.isEmpty) {
return result
}
@@ -301,7 +315,7 @@ class ModelCallbacks(private var launcher: Launcher) : BgDataModel.Callbacks {
)
}
- override fun bindScreens(orderedScreenIds: LIntArray) {
+ private fun bindScreens(orderedScreenIds: LIntArray) {
launcher.workspace.pageIndicator.setPauseScroll(
/*pause=*/ true,
launcher.deviceProfile.isTwoPanels,
@@ -325,26 +339,38 @@ class ModelCallbacks(private var launcher: Launcher) : BgDataModel.Callbacks {
launcher.workspace.unlockWallpaperFromDefaultPageOnNextLayout()
}
- override fun bindAppsAdded(
- newScreens: LIntArray?,
- addNotAnimated: java.util.ArrayList?,
- addAnimated: java.util.ArrayList?,
- ) {
- // Add the new screens
- if (newScreens != null) {
- // newScreens can contain an empty right panel that is already bound, but not known
- // by BgDataModel.
- newScreens.removeAllValues(launcher.workspace.mScreenOrder)
- bindAddScreens(newScreens)
+ override fun bindItemsAdded(items: List) {
+ val newScreens = LIntSet()
+ val nonAnimatedItems = mutableListOf()
+ val animatedItems = mutableListOf()
+ val folderItems = mutableListOf()
+ val lastScreen =
+ items
+ .maxByOrNull { if (it.container == CONTAINER_DESKTOP) it.screenId else 0 }
+ ?.screenId ?: 0
+
+ items.forEach {
+ when (it.container) {
+ CONTAINER_HOTSEAT -> nonAnimatedItems.add(it)
+ CONTAINER_DESKTOP -> {
+ newScreens.add(it.screenId)
+ if (it.screenId == lastScreen) animatedItems.add(it)
+ else nonAnimatedItems.add(it)
+ }
+ else -> folderItems.add(it)
+ }
}
+ launcher.workspace.mScreenOrder.forEach { newScreens.remove(it) }
+ if (!newScreens.isEmpty) bindAddScreens(newScreens.array)
+
// We add the items without animation on non-visible pages, and with
// animations on the new page (which we will try and snap to).
- if (!addNotAnimated.isNullOrEmpty()) {
- launcher.bindItems(addNotAnimated, false)
+ if (nonAnimatedItems.isNotEmpty()) {
+ bindItems(nonAnimatedItems, false)
}
- if (!addAnimated.isNullOrEmpty()) {
- launcher.bindItems(addAnimated, true)
+ if (animatedItems.isNotEmpty()) {
+ bindItems(animatedItems, true)
}
// Remove the extra empty screen
@@ -398,5 +424,188 @@ class ModelCallbacks(private var launcher: Launcher) : BgDataModel.Callbacks {
launcher.appsView.updateWorkUI()
}
- override fun getItemInflater() = launcher.itemInflater
+ /** Bind the items start-end from the list. */
+ @VisibleForTesting
+ fun bindItems(items: List, forceAnimateIcons: Boolean) {
+ launcher.bindInflatedItems(
+ items.map { Pair.create(it, launcher.itemInflater.inflateItem(it)) },
+ if (forceAnimateIcons) AnimatorSet() else null,
+ )
+ }
+
+ @AnyThread
+ override fun bindCompleteModelAsync(
+ itemIdMap: IntSparseArrayMap,
+ extraItems: List,
+ stringCache: StringCache,
+ isBindingSync: Boolean,
+ ) {
+ val taskTracker = CancellationSignal()
+ activeBindTask.getAndSet(taskTracker).cancel()
+
+ val inflater = launcher.itemInflater
+
+ fun executeCallbacksTask(executor: Executor = MAIN_EXECUTOR, task: () -> Unit) {
+ executor.execute {
+ if (taskTracker.isCanceled) {
+ Log.d(TAG, "Too many consecutive reloads, skipping obsolete data-bind")
+ } else {
+ task.invoke()
+ }
+ }
+ }
+
+ // Tries to inflate the items asynchronously and bind. Returns true on success or false if
+ // async-binding is not supported in this case
+ fun inflateAsyncAndBind(items: List, executor: Executor) {
+ if (taskTracker.isCanceled) {
+ Log.d(TAG, "Too many consecutive reloads, skipping obsolete view inflation")
+ return
+ }
+
+ val bindItems = items.map { Pair.create(it, inflater.inflateItem(it, null)) }
+ if (bindItems.isNotEmpty())
+ executeCallbacksTask(executor) { launcher.bindInflatedItems(bindItems, null) }
+ }
+
+ fun bindItemsInChunks(items: List, chuckSize: Int, executor: Executor) {
+ // Bind the workspace items
+ val itemCount = items.size
+ var i = 0
+ while (i < itemCount) {
+ val start = i
+ val end = (start + chuckSize).coerceAtMost(itemCount)
+ executeCallbacksTask(executor) { bindItems(items.subList(start, end), false) }
+ i = end
+ }
+ }
+
+ MAIN_EXECUTOR.execute { clearPendingBinds() }
+
+ val orderedScreenIds =
+ IntSet()
+ .apply {
+ itemIdMap.forEach { if (it.container == CONTAINER_DESKTOP) add(it.screenId) }
+ if ((QSB_ON_FIRST_SCREEN && !SHOULD_SHOW_FIRST_PAGE_WIDGET) || isEmpty)
+ add(Workspace.FIRST_SCREEN_ID)
+ }
+ .array
+ val currentScreenIds = getPagesToBindSynchronously(orderedScreenIds)
+
+ fun setupPendingBind(pendingExecutor: Executor) {
+ executeCallbacksTask(pendingExecutor) { launcher.bindStringCache(stringCache) }
+ executeCallbacksTask(pendingExecutor) { finishBindingItems(currentScreenIds) }
+ pendingExecutor.execute {
+ ItemInstallQueue.INSTANCE[launcher].resumeModelPush(FLAG_LOADER_RUNNING)
+ }
+ }
+
+ // Separate the items that are on the current screen, and all the other remaining items
+ val currentWorkspaceItems = ArrayList()
+ val otherWorkspaceItems = ArrayList()
+ val currentAppWidgets = ArrayList()
+ val otherAppWidgets = ArrayList()
+
+ val currentScreenCheck = currentScreenContentFilter(currentScreenIds)
+ itemIdMap.forEach { item: ItemInfo ->
+ if (currentScreenCheck.test(item)) {
+ (if (WIDGET_FILTER.test(item)) currentAppWidgets else currentWorkspaceItems).add(
+ item
+ )
+ } else if (item.container == CONTAINER_DESKTOP) {
+ (if (WIDGET_FILTER.test(item)) otherAppWidgets else otherWorkspaceItems).add(item)
+ }
+ }
+
+ sortWorkspaceItemsSpatially(currentWorkspaceItems)
+ sortWorkspaceItemsSpatially(otherWorkspaceItems)
+
+ // Tell the workspace that we're about to start binding items
+ executeCallbacksTask {
+ clearPendingBinds()
+ startBinding()
+ }
+
+ // Bind workspace screens
+ executeCallbacksTask { bindScreens(orderedScreenIds) }
+
+ // Load items on the current page.
+ if (Flags.enableWorkspaceInflation()) {
+ inflateAsyncAndBind(currentWorkspaceItems, MAIN_EXECUTOR)
+ inflateAsyncAndBind(currentAppWidgets, MAIN_EXECUTOR)
+ } else {
+ bindItemsInChunks(currentWorkspaceItems, ITEMS_CHUNK, MAIN_EXECUTOR)
+ bindItemsInChunks(currentAppWidgets, 1, MAIN_EXECUTOR)
+ }
+ extraItems.forEach {
+ it?.let { executeCallbacksTask { launcher.bindExtraContainerItems(it) } }
+ }
+
+ val pendingTasks = RunnableList()
+ val pendingExecutor = Executor { pendingTasks.add(it) }
+
+ val onCompleteSignal = RunnableList()
+ onCompleteSignal.add { Log.d(TAG, "Calling onCompleteSignal") }
+
+ if (Flags.enableWorkspaceInflation()) {
+ Log.d(TAG, "Starting async inflation")
+ Executors.MODEL_EXECUTOR.execute {
+ inflateAsyncAndBind(otherWorkspaceItems, pendingExecutor)
+ inflateAsyncAndBind(otherAppWidgets, pendingExecutor)
+ setupPendingBind(pendingExecutor)
+
+ // Wait for the async inflation to complete and then notify the completion
+ // signal on UI thread.
+ MAIN_EXECUTOR.execute { onCompleteSignal.executeAllAndDestroy() }
+ }
+ } else {
+ Log.d(TAG, "Starting sync inflation")
+ bindItemsInChunks(otherWorkspaceItems, ITEMS_CHUNK, pendingExecutor)
+ bindItemsInChunks(otherAppWidgets, 1, pendingExecutor)
+ setupPendingBind(pendingExecutor)
+ onCompleteSignal.executeAllAndDestroy()
+ }
+
+ val workspaceItemCount = itemIdMap.size()
+ executeCallbacksTask {
+ onInitialBindComplete(
+ currentScreenIds,
+ pendingTasks,
+ onCompleteSignal,
+ workspaceItemCount,
+ isBindingSync,
+ )
+ }
+ }
+
+ /**
+ * Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to right)
+ */
+ private fun sortWorkspaceItemsSpatially(workspaceItems: MutableList) {
+ val idp = launcher.deviceProfile.inv
+ val screenCols = idp.numColumns
+ val screenCellCount = idp.numColumns * idp.numRows
+ workspaceItems.sortWith { lhs: ItemInfo, rhs: ItemInfo ->
+ when {
+ // Between containers, order by hotseat, desktop
+ lhs.container != rhs.container -> lhs.container.compareTo(rhs.container)
+
+ // Within workspace, order by their spatial position in that container
+ lhs.container == CONTAINER_DESKTOP ->
+ compareValuesBy(lhs, rhs) {
+ it.screenId * screenCellCount + it.cellY * screenCols + it.cellX
+ }
+
+ // We currently use the screen id as the rank
+ lhs.container == CONTAINER_HOTSEAT -> lhs.screenId.compareTo(rhs.screenId)
+
+ else -> 0
+ }
+ }
+ }
+
+ companion object {
+ private const val TAG = "ModelCallbacks"
+ private const val ITEMS_CHUNK: Int = 6 // batch size for the workspace icons
+ }
}
diff --git a/src/com/android/launcher3/accessibility/LauncherAccessibilityDelegate.java b/src/com/android/launcher3/accessibility/LauncherAccessibilityDelegate.java
index e16a296947..fd596bd62f 100644
--- a/src/com/android/launcher3/accessibility/LauncherAccessibilityDelegate.java
+++ b/src/com/android/launcher3/accessibility/LauncherAccessibilityDelegate.java
@@ -536,7 +536,7 @@ public class LauncherAccessibilityDelegate extends BaseAccessibilityDelegate {
- mContext.bindItems(Collections.singletonList(item), true);
+ mContext.inflateAndBindItemWithAnimation(item);
announceConfirmation(R.string.item_moved);
});
return true;
diff --git a/src/com/android/launcher3/accessibility/ShortcutMenuAccessibilityDelegate.java b/src/com/android/launcher3/accessibility/ShortcutMenuAccessibilityDelegate.java
index c91e78341f..f71d5055f7 100644
--- a/src/com/android/launcher3/accessibility/ShortcutMenuAccessibilityDelegate.java
+++ b/src/com/android/launcher3/accessibility/ShortcutMenuAccessibilityDelegate.java
@@ -28,7 +28,6 @@ import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.shortcuts.DeepShortcutView;
-import java.util.Collections;
import java.util.List;
/**
@@ -64,7 +63,7 @@ public class ShortcutMenuAccessibilityDelegate extends LauncherAccessibilityDele
mContext.getModelWriter().addItemToDatabase(info,
LauncherSettings.Favorites.CONTAINER_DESKTOP,
screenId, coordinates[0], coordinates[1]);
- mContext.bindItems(Collections.singletonList(info), true);
+ mContext.inflateAndBindItemWithAnimation(info);
AbstractFloatingView.closeAllOpenViews(mContext);
}));
return true;
diff --git a/src/com/android/launcher3/graphics/PreloadIconDrawable.java b/src/com/android/launcher3/graphics/PreloadIconDrawable.java
index 3bd9fb54ca..42f970f707 100644
--- a/src/com/android/launcher3/graphics/PreloadIconDrawable.java
+++ b/src/com/android/launcher3/graphics/PreloadIconDrawable.java
@@ -35,6 +35,7 @@ import android.util.Property;
import androidx.annotation.VisibleForTesting;
import androidx.core.graphics.ColorUtils;
+import com.android.launcher3.Flags;
import com.android.launcher3.R;
import com.android.launcher3.Utilities;
import com.android.launcher3.anim.AnimatedFloat;
@@ -72,9 +73,15 @@ public class PreloadIconDrawable extends FastBitmapDrawable {
// Duration = COMPLETE_ANIM_FRACTION * DURATION_SCALE
private static final float COMPLETE_ANIM_FRACTION = 1f;
- private static final float SMALL_SCALE = 0.8f;
+ private static final float SMALL_ICON_SCALE = 0.8f;
private static final float PROGRESS_STROKE_SCALE = 0.055f;
private static final float PROGRESS_BOUNDS_SCALE = 0.075f;
+ private static final float TOTAL_STROKE_SCALE = 3 * PROGRESS_STROKE_SCALE / 2;
+ // Scale for canvas when drawing plate stroke. This is to avoid gaps between icon and plate.
+ // We use icon scale + 2 * plate gap width. This is the same as icon scale + progress scale.
+ private static final float PLATE_SCALE = SMALL_ICON_SCALE + PROGRESS_STROKE_SCALE;
+
+
private static final int PRELOAD_ACCENT_COLOR_INDEX = 0;
private static final int PRELOAD_BACKGROUND_COLOR_INDEX = 1;
@@ -86,6 +93,7 @@ public class PreloadIconDrawable extends FastBitmapDrawable {
// Path in [0, 100] bounds.
private final Path mShapePath;
+ private final Path mScaledPlatePath;
private final Path mScaledTrackPath;
private final Path mScaledProgressPath;
private final Paint mProgressPaint;
@@ -132,6 +140,7 @@ public class PreloadIconDrawable extends FastBitmapDrawable {
super(info.bitmap);
mItem = info;
mShapePath = shapePath;
+ mScaledPlatePath = new Path();
mScaledTrackPath = new Path();
mScaledProgressPath = new Path();
@@ -181,14 +190,22 @@ public class PreloadIconDrawable extends FastBitmapDrawable {
super.onBoundsChange(bounds);
float progressWidth = bounds.width() * PROGRESS_BOUNDS_SCALE;
+ float plateGapWidth = bounds.width() * PROGRESS_BOUNDS_SCALE / 2f;
+
mTmpMatrix.setScale(
(bounds.width() - 2 * progressWidth) / DEFAULT_PATH_SIZE,
(bounds.height() - 2 * progressWidth) / DEFAULT_PATH_SIZE);
mTmpMatrix.postTranslate(bounds.left + progressWidth, bounds.top + progressWidth);
-
mShapePath.transform(mTmpMatrix, mScaledTrackPath);
mProgressPaint.setStrokeWidth(PROGRESS_STROKE_SCALE * bounds.width());
+ mTmpMatrix.setScale(
+ (bounds.width() - 2 * plateGapWidth) / DEFAULT_PATH_SIZE,
+ (bounds.height() - 2 * plateGapWidth) / DEFAULT_PATH_SIZE);
+ mTmpMatrix.postTranslate(bounds.left + plateGapWidth, bounds.top + plateGapWidth);
+ mShapePath.transform(mTmpMatrix, mScaledPlatePath);
+
+
mPathMeasure.setPath(mScaledTrackPath, true);
mTrackLength = mPathMeasure.getLength();
@@ -201,30 +218,76 @@ public class PreloadIconDrawable extends FastBitmapDrawable {
super.drawInternal(canvas, bounds);
return;
}
+ if (Flags.enableLauncherIconShapes()) {
+ // Get original icon width for scaling
+ float width = canvas.getWidth();
+ int saveCount;
+ float scale;
+ if (mInternalStateProgress > 0f) {
+ // Draw icon at scale.
+ saveCount = canvas.save();
+ scale = 1 - mIconScaleMultiplier.value * (1 - SMALL_ICON_SCALE);
+ canvas.scale(scale, scale, bounds.exactCenterX(), bounds.exactCenterY());
+ super.drawInternal(canvas, bounds);
+ canvas.restoreToCount(saveCount);
- if (mInternalStateProgress > 0) {
- // Draw background.
- mProgressPaint.setStyle(Paint.Style.FILL);
- mProgressPaint.setColor(mPlateColor);
- canvas.drawPath(mScaledTrackPath, mProgressPaint);
+
+ // Draw background plate as a stroke around icon.
+ saveCount = canvas.save();
+ scale = PLATE_SCALE;
+ canvas.scale(scale, scale, bounds.exactCenterX(), bounds.exactCenterY());
+ mProgressPaint.setStyle(Paint.Style.STROKE);
+ // Draw plate as total stroke width, then overlay with progress track to leave gap.
+ mProgressPaint.setStrokeWidth(width * TOTAL_STROKE_SCALE);
+ mProgressPaint.setColor(mPlateColor);
+ canvas.drawPath(mScaledPlatePath, mProgressPaint);
+ canvas.restoreToCount(saveCount);
+
+
+ // Draw track and progress.
+ saveCount = canvas.save();
+ scale = 1f;
+ canvas.scale(scale, scale, bounds.exactCenterX(), bounds.exactCenterY());
+ mProgressPaint.setStyle(Paint.Style.STROKE);
+ mProgressPaint.setStrokeWidth(width * PROGRESS_STROKE_SCALE);
+ mProgressPaint.setColor(mTrackColor);
+ canvas.drawPath(mScaledTrackPath, mProgressPaint);
+ mProgressPaint.setAlpha(MAX_PAINT_ALPHA);
+ mProgressPaint.setColor(mProgressColor);
+ canvas.drawPath(mScaledProgressPath, mProgressPaint);
+ canvas.restoreToCount(saveCount);
+ } else {
+ saveCount = canvas.save();
+ scale = 1 - mIconScaleMultiplier.value * (1 - SMALL_ICON_SCALE);
+ canvas.scale(scale, scale, bounds.exactCenterX(), bounds.exactCenterY());
+ super.drawInternal(canvas, bounds);
+ canvas.restoreToCount(saveCount);
+ }
+ } else {
+ if (mInternalStateProgress > 0) {
+ // Draw background.
+ mProgressPaint.setStyle(Paint.Style.FILL);
+ mProgressPaint.setColor(mPlateColor);
+ canvas.drawPath(mScaledTrackPath, mProgressPaint);
+ }
+
+ if (mInternalStateProgress > 0) {
+ // Draw track and progress.
+ mProgressPaint.setStyle(Paint.Style.STROKE);
+ mProgressPaint.setColor(mTrackColor);
+ canvas.drawPath(mScaledTrackPath, mProgressPaint);
+ mProgressPaint.setAlpha(MAX_PAINT_ALPHA);
+ mProgressPaint.setColor(mProgressColor);
+ canvas.drawPath(mScaledProgressPath, mProgressPaint);
+ }
+
+ int saveCount = canvas.save();
+ float scale = 1 - mIconScaleMultiplier.value * (1 - SMALL_ICON_SCALE);
+ canvas.scale(scale, scale, bounds.exactCenterX(), bounds.exactCenterY());
+
+ super.drawInternal(canvas, bounds);
+ canvas.restoreToCount(saveCount);
}
-
- if (mInternalStateProgress > 0) {
- // Draw track and progress.
- mProgressPaint.setStyle(Paint.Style.STROKE);
- mProgressPaint.setColor(mTrackColor);
- canvas.drawPath(mScaledTrackPath, mProgressPaint);
- mProgressPaint.setAlpha(MAX_PAINT_ALPHA);
- mProgressPaint.setColor(mProgressColor);
- canvas.drawPath(mScaledProgressPath, mProgressPaint);
- }
-
- int saveCount = canvas.save();
- float scale = 1 - mIconScaleMultiplier.value * (1 - SMALL_SCALE);
- canvas.scale(scale, scale, bounds.exactCenterX(), bounds.exactCenterY());
-
- super.drawInternal(canvas, bounds);
- canvas.restoreToCount(saveCount);
}
/**
diff --git a/src/com/android/launcher3/model/AddWorkspaceItemsTask.java b/src/com/android/launcher3/model/AddWorkspaceItemsTask.java
index dfba4bb192..abcc0cb031 100644
--- a/src/com/android/launcher3/model/AddWorkspaceItemsTask.java
+++ b/src/com/android/launcher3/model/AddWorkspaceItemsTask.java
@@ -28,12 +28,10 @@ import android.util.Pair;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
-import com.android.launcher3.LauncherModel.CallbackTask;
import com.android.launcher3.LauncherModel.ModelUpdateTask;
import com.android.launcher3.LauncherSettings;
import com.android.launcher3.icons.IconCache;
import com.android.launcher3.logging.FileLog;
-import com.android.launcher3.model.BgDataModel.Callbacks;
import com.android.launcher3.model.data.AppInfo;
import com.android.launcher3.model.data.CollectionInfo;
import com.android.launcher3.model.data.ItemInfo;
@@ -207,26 +205,7 @@ public class AddWorkspaceItemsTask implements ModelUpdateTask {
}
if (!addedItemsFinal.isEmpty()) {
- taskController.scheduleCallbackTask(new CallbackTask() {
- @Override
- public void execute(@NonNull Callbacks callbacks) {
- final ArrayList addAnimated = new ArrayList<>();
- final ArrayList addNotAnimated = new ArrayList<>();
- if (!addedItemsFinal.isEmpty()) {
- ItemInfo info = addedItemsFinal.get(addedItemsFinal.size() - 1);
- int lastScreenId = info.screenId;
- for (ItemInfo i : addedItemsFinal) {
- if (i.screenId == lastScreenId) {
- addAnimated.add(i);
- } else {
- addNotAnimated.add(i);
- }
- }
- }
- callbacks.bindAppsAdded(addedWorkspaceScreensFinal,
- addNotAnimated, addAnimated);
- }
- });
+ taskController.scheduleCallbackTask(cb -> cb.bindItemsAdded(addedItemsFinal));
}
}
diff --git a/src/com/android/launcher3/model/BaseLauncherBinder.java b/src/com/android/launcher3/model/BaseLauncherBinder.java
index 5b95e370ae..dc4b6f02da 100644
--- a/src/com/android/launcher3/model/BaseLauncherBinder.java
+++ b/src/com/android/launcher3/model/BaseLauncherBinder.java
@@ -17,41 +17,24 @@
package com.android.launcher3.model;
import static com.android.launcher3.BuildConfig.WIDGETS_ENABLED;
-import static com.android.launcher3.Flags.enableWorkspaceInflation;
-import static com.android.launcher3.LauncherSettings.Favorites.CONTAINER_DESKTOP;
-import static com.android.launcher3.model.ItemInstallQueue.FLAG_LOADER_RUNNING;
-import static com.android.launcher3.model.ModelUtils.WIDGET_FILTER;
-import static com.android.launcher3.model.ModelUtils.currentScreenContentFilter;
import static com.android.launcher3.util.Executors.MAIN_EXECUTOR;
-import static com.android.launcher3.util.Executors.MODEL_EXECUTOR;
import android.content.Context;
import android.os.Trace;
import android.util.Log;
-import android.util.Pair;
-import android.view.View;
-import androidx.annotation.NonNull;
-
-import com.android.launcher3.InvariantDeviceProfile;
import com.android.launcher3.LauncherModel;
import com.android.launcher3.LauncherModel.CallbackTask;
-import com.android.launcher3.LauncherSettings;
-import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.dagger.ApplicationContext;
import com.android.launcher3.model.BgDataModel.Callbacks;
import com.android.launcher3.model.BgDataModel.FixedContainerItems;
import com.android.launcher3.model.data.AppInfo;
import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.util.ComponentKey;
-import com.android.launcher3.util.IntArray;
-import com.android.launcher3.util.IntSet;
import com.android.launcher3.util.IntSparseArrayMap;
-import com.android.launcher3.util.ItemInflater;
import com.android.launcher3.util.LooperExecutor;
import com.android.launcher3.util.LooperIdleLock;
import com.android.launcher3.util.PackageUserKey;
-import com.android.launcher3.util.RunnableList;
import com.android.launcher3.widget.model.WidgetsListBaseEntriesBuilder;
import com.android.launcher3.widget.model.WidgetsListBaseEntry;
@@ -61,13 +44,10 @@ import dagger.assisted.AssistedInject;
import java.util.ArrayList;
import java.util.Arrays;
-import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import java.util.Objects;
import java.util.concurrent.Executor;
-import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
@@ -76,12 +56,10 @@ import java.util.stream.Collectors;
public class BaseLauncherBinder {
protected static final String TAG = "LauncherBinder";
- private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
protected final LooperExecutor mUiExecutor;
private final Context mContext;
- private final InvariantDeviceProfile mIDP;
private final LauncherModel mModel;
protected final BgDataModel mBgDataModel;
private final AllAppsList mBgAllAppsList;
@@ -93,14 +71,12 @@ public class BaseLauncherBinder {
@AssistedInject
public BaseLauncherBinder(
@ApplicationContext Context context,
- InvariantDeviceProfile idp,
LauncherModel model,
BgDataModel dataModel,
AllAppsList allAppsList,
@Assisted Callbacks[] callbacksList) {
mUiExecutor = MAIN_EXECUTOR;
mContext = context;
- mIDP = idp;
mModel = model;
mBgDataModel = dataModel;
mBgAllAppsList = allAppsList;
@@ -115,24 +91,22 @@ public class BaseLauncherBinder {
try {
// Save a copy of all the bg-thread collections
IntSparseArrayMap itemsIdMap;
- final IntArray orderedScreenIds = new IntArray();
ArrayList extraItems = new ArrayList<>();
- final int workspaceItemCount;
+ StringCache stringCache;
+
synchronized (mBgDataModel) {
itemsIdMap = mBgDataModel.itemsIdMap.clone();
- orderedScreenIds.addAll(mBgDataModel.collectWorkspaceScreens());
mBgDataModel.extraItems.forEach(extraItems::add);
if (incrementBindId) {
mBgDataModel.lastBindId++;
mBgDataModel.lastLoadId = mModel.getLastLoadId();
}
mMyBindingId = mBgDataModel.lastBindId;
- workspaceItemCount = mBgDataModel.itemsIdMap.size();
+ stringCache = mBgDataModel.stringCache.clone();
}
for (Callbacks cb : mCallbacksList) {
- new UnifiedWorkspaceBinder(cb, itemsIdMap, extraItems, orderedScreenIds)
- .bind(isBindSync, workspaceItemCount);
+ cb.bindCompleteModelAsync(itemsIdMap, extraItems, stringCache, isBindSync);
}
} finally {
Trace.endSection();
@@ -190,41 +164,6 @@ public class BaseLauncherBinder {
executeCallbacksTask(c -> c.bindSmartspaceWidget(), mUiExecutor);
}
- /**
- * Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to right)
- */
- protected void sortWorkspaceItemsSpatially(ArrayList workspaceItems) {
- final int screenCols = mIDP.numColumns;
- final int screenCellCount = mIDP.numColumns * mIDP.numRows;
- Collections.sort(workspaceItems, (lhs, rhs) -> {
- if (lhs.container == rhs.container) {
- // Within containers, order by their spatial position in that container
- switch (lhs.container) {
- case LauncherSettings.Favorites.CONTAINER_DESKTOP: {
- int lr = (lhs.screenId * screenCellCount + lhs.cellY * screenCols
- + lhs.cellX);
- int rr = (rhs.screenId * screenCellCount + +rhs.cellY * screenCols
- + rhs.cellX);
- return Integer.compare(lr, rr);
- }
- case LauncherSettings.Favorites.CONTAINER_HOTSEAT: {
- // We currently use the screen id as the rank
- return Integer.compare(lhs.screenId, rhs.screenId);
- }
- default:
- if (FeatureFlags.IS_STUDIO_BUILD) {
- throw new RuntimeException(
- "Unexpected container type when sorting workspace items.");
- }
- return 0;
- }
- } else {
- // Between containers, order by hotseat, desktop
- return Integer.compare(lhs.container, rhs.container);
- }
- });
- }
-
protected void executeCallbacksTask(CallbackTask task, Executor executor) {
executor.execute(() -> {
if (mMyBindingId != mBgDataModel.lastBindId) {
@@ -248,152 +187,6 @@ public class BaseLauncherBinder {
}
return idleLock;
}
-
- private class UnifiedWorkspaceBinder {
-
- private final Callbacks mCallbacks;
-
- private final IntSparseArrayMap mItemIdMap;
- private final IntArray mOrderedScreenIds;
- private final ArrayList mExtraItems;
-
- UnifiedWorkspaceBinder(
- Callbacks callbacks,
- IntSparseArrayMap itemIdMap,
- ArrayList extraItems,
- IntArray orderedScreenIds) {
- mCallbacks = callbacks;
- mItemIdMap = itemIdMap;
- mExtraItems = extraItems;
- mOrderedScreenIds = orderedScreenIds;
- }
-
- private void bind(boolean isBindSync, int workspaceItemCount) {
- final IntSet currentScreenIds =
- mCallbacks.getPagesToBindSynchronously(mOrderedScreenIds);
- Objects.requireNonNull(currentScreenIds, "Null screen ids provided by " + mCallbacks);
-
- // Separate the items that are on the current screen, and all the other remaining items
- ArrayList currentWorkspaceItems = new ArrayList<>();
- ArrayList otherWorkspaceItems = new ArrayList<>();
- ArrayList currentAppWidgets = new ArrayList<>();
- ArrayList otherAppWidgets = new ArrayList<>();
-
- Predicate currentScreenCheck = currentScreenContentFilter(currentScreenIds);
- mItemIdMap.forEach(item -> {
- if (currentScreenCheck.test(item)) {
- (WIDGET_FILTER.test(item) ? currentAppWidgets : currentWorkspaceItems)
- .add(item);
- } else if (item.container == CONTAINER_DESKTOP) {
- (WIDGET_FILTER.test(item) ? otherAppWidgets : otherWorkspaceItems).add(item);
- }
- });
- sortWorkspaceItemsSpatially(currentWorkspaceItems);
- sortWorkspaceItemsSpatially(otherWorkspaceItems);
-
- // Tell the workspace that we're about to start binding items
- executeCallbacksTask(c -> {
- c.clearPendingBinds();
- c.startBinding();
- }, mUiExecutor);
-
- // Bind workspace screens
- executeCallbacksTask(c -> c.bindScreens(mOrderedScreenIds), mUiExecutor);
-
- ItemInflater inflater = mCallbacks.getItemInflater();
-
- // Load items on the current page.
- if (enableWorkspaceInflation() && inflater != null) {
- inflateAsyncAndBind(currentWorkspaceItems, inflater, mUiExecutor);
- inflateAsyncAndBind(currentAppWidgets, inflater, mUiExecutor);
- } else {
- bindItemsInChunks(currentWorkspaceItems, ITEMS_CHUNK, mUiExecutor);
- bindItemsInChunks(currentAppWidgets, 1, mUiExecutor);
- }
- mExtraItems.forEach(item ->
- executeCallbacksTask(c -> c.bindExtraContainerItems(item), mUiExecutor));
-
- RunnableList pendingTasks = new RunnableList();
- Executor pendingExecutor = pendingTasks::add;
-
- RunnableList onCompleteSignal = new RunnableList();
- onCompleteSignal.add(() -> Log.d(TAG, "Calling onCompleteSignal"));
-
- if (enableWorkspaceInflation() && inflater != null) {
- Log.d(TAG, "Starting async inflation");
- MODEL_EXECUTOR.execute(() -> {
- inflateAsyncAndBind(otherWorkspaceItems, inflater, pendingExecutor);
- inflateAsyncAndBind(otherAppWidgets, inflater, pendingExecutor);
- setupPendingBind(currentScreenIds, pendingExecutor);
-
- // Wait for the async inflation to complete and then notify the completion
- // signal on UI thread.
- MAIN_EXECUTOR.execute(onCompleteSignal::executeAllAndDestroy);
- });
- } else {
- Log.d(TAG, "Starting sync inflation");
- bindItemsInChunks(otherWorkspaceItems, ITEMS_CHUNK, pendingExecutor);
- bindItemsInChunks(otherAppWidgets, 1, pendingExecutor);
- setupPendingBind(currentScreenIds, pendingExecutor);
- onCompleteSignal.executeAllAndDestroy();
- }
-
- executeCallbacksTask(c -> c.onInitialBindComplete(currentScreenIds, pendingTasks,
- onCompleteSignal, workspaceItemCount, isBindSync), mUiExecutor);
- }
-
- private void setupPendingBind(
- IntSet currentScreenIds,
- Executor pendingExecutor) {
- StringCache cacheClone = mBgDataModel.stringCache.clone();
- executeCallbacksTask(c -> c.bindStringCache(cacheClone), pendingExecutor);
-
- executeCallbacksTask(c -> c.finishBindingItems(currentScreenIds), pendingExecutor);
- pendingExecutor.execute(() -> ItemInstallQueue.INSTANCE.get(mContext)
- .resumeModelPush(FLAG_LOADER_RUNNING));
- }
-
- /**
- * Tries to inflate the items asynchronously and bind. Returns true on success or false if
- * async-binding is not supported in this case.
- */
- private void inflateAsyncAndBind(
- List items, @NonNull ItemInflater inflater, Executor executor) {
- if (mMyBindingId != mBgDataModel.lastBindId) {
- Log.d(TAG, "Too many consecutive reloads, skipping obsolete view inflation");
- return;
- }
-
- List> bindItems = items.stream()
- .map(i -> Pair.create(i, inflater.inflateItem(i, null)))
- .collect(Collectors.toList());
- executeCallbacksTask(c -> c.bindInflatedItems(bindItems), executor);
- }
-
- private void bindItemsInChunks(
- List workspaceItems, int chunkCount, Executor executor) {
- // Bind the workspace items
- int count = workspaceItems.size();
- for (int i = 0; i < count; i += chunkCount) {
- final int start = i;
- final int chunkSize = (i + chunkCount <= count) ? chunkCount : (count - i);
- executeCallbacksTask(
- c -> c.bindItems(workspaceItems.subList(start, start + chunkSize), false),
- executor);
- }
- }
-
- protected void executeCallbacksTask(CallbackTask task, Executor executor) {
- executor.execute(() -> {
- if (mMyBindingId != mBgDataModel.lastBindId) {
- Log.d(TAG, "Too many consecutive reloads, skipping obsolete data-bind");
- return;
- }
- task.execute(mCallbacks);
- });
- }
- }
-
@AssistedFactory
public interface BaseLauncherBinderFactory {
BaseLauncherBinder createBinder(Callbacks[] callbacks);
diff --git a/src/com/android/launcher3/model/BgDataModel.java b/src/com/android/launcher3/model/BgDataModel.java
index 9189eb8e3a..5e0f8a074f 100644
--- a/src/com/android/launcher3/model/BgDataModel.java
+++ b/src/com/android/launcher3/model/BgDataModel.java
@@ -25,6 +25,7 @@ import static com.android.launcher3.LauncherSettings.Favorites.ITEM_TYPE_DEEP_SH
import static com.android.launcher3.LauncherSettings.Favorites.ITEM_TYPE_FOLDER;
import static com.android.launcher3.Utilities.SHOULD_SHOW_FIRST_PAGE_WIDGET;
import static com.android.launcher3.shortcuts.ShortcutRequest.PINNED;
+import static com.android.launcher3.util.Executors.MAIN_EXECUTOR;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.mapping;
@@ -35,9 +36,8 @@ import android.content.pm.ShortcutInfo;
import android.os.UserHandle;
import android.text.TextUtils;
import android.util.Log;
-import android.util.Pair;
-import android.view.View;
+import androidx.annotation.AnyThread;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
@@ -66,9 +66,7 @@ import com.android.launcher3.util.DaggerSingletonTracker;
import com.android.launcher3.util.IntArray;
import com.android.launcher3.util.IntSet;
import com.android.launcher3.util.IntSparseArrayMap;
-import com.android.launcher3.util.ItemInflater;
import com.android.launcher3.util.PackageUserKey;
-import com.android.launcher3.util.RunnableList;
import com.android.launcher3.widget.model.WidgetsListBaseEntry;
import java.io.PrintWriter;
@@ -439,41 +437,31 @@ public class BgDataModel implements LauncherDumpable {
int FLAG_PRIVATE_PROFILE_QUIET_MODE_ENABLED = 1 << 4;
/**
- * Returns an IntSet of page ids to bind first, synchronously if possible
- * or an empty IntSet
- * @param orderedScreenIds All the page ids to be bound
+ * Does a complete model rebind. The callback can be called on any thread and it is up to
+ * the client to move the executor to appropriate thread
*/
- @NonNull
- default IntSet getPagesToBindSynchronously(IntArray orderedScreenIds) {
- return new IntSet();
+ @AnyThread
+ default void bindCompleteModelAsync(IntSparseArrayMap itemIdMap,
+ List extraItems, StringCache stringCache,
+ boolean isBindingSync) {
+ MAIN_EXECUTOR.execute(
+ () -> bindCompleteModel(itemIdMap, extraItems, stringCache, isBindingSync));
}
- default void clearPendingBinds() { }
- default void startBinding() { }
+ default void bindCompleteModel(IntSparseArrayMap itemIdMap,
+ List extraItems, StringCache stringCache,
+ boolean isBindingSync) { }
- @Nullable
- default ItemInflater getItemInflater() {
- return null;
- }
-
- default void bindItems(@NonNull List shortcuts, boolean forceAnimateIcons) { }
- /** Alternate method to bind preinflated views */
- default void bindInflatedItems(@NonNull List> items) { }
-
- default void bindScreens(IntArray orderedScreenIds) { }
- default void finishBindingItems(IntSet pagesBoundFirst) { }
- default void bindAppsAdded(IntArray newScreens,
- ArrayList addNotAnimated, ArrayList addAnimated) { }
+ default void bindItemsAdded(@NonNull List items) { }
+ /** Called when a runtime property of the ItemInfo is updated due to some system event */
+ default void bindItemsUpdated(Set updates) { }
+ default void bindWorkspaceComponentsRemoved(Predicate matcher) { }
/**
* Binds updated incremental download progress
*/
default void bindIncrementalDownloadProgressUpdated(AppInfo app) { }
- /** Called when a runtime property of the ItemInfo is updated due to some system event */
- default void bindItemsUpdated(Set updates) { }
- default void bindWorkspaceComponentsRemoved(Predicate matcher) { }
-
/**
* Binds the app widgets to the providers that share widgets with the UI.
*/
@@ -481,14 +469,6 @@ public class BgDataModel implements LauncherDumpable {
default void bindSmartspaceWidget() { }
- /** Called when workspace has been bound. */
- default void onInitialBindComplete(@NonNull IntSet boundPages,
- @NonNull RunnableList pendingTasks,
- @NonNull RunnableList onCompleteSignal,
- int workspaceItemCount, boolean isBindSync) {
- pendingTasks.executeAllAndDestroy();
- }
-
default void bindDeepShortcutMap(HashMap deepShortcutMap) { }
/**
diff --git a/src/com/android/launcher3/model/ModelDbController.java b/src/com/android/launcher3/model/ModelDbController.java
index 7561c08ddb..d998cdd284 100644
--- a/src/com/android/launcher3/model/ModelDbController.java
+++ b/src/com/android/launcher3/model/ModelDbController.java
@@ -64,8 +64,8 @@ import com.android.launcher3.provider.RestoreDbTask;
import com.android.launcher3.util.IntArray;
import com.android.launcher3.widget.LauncherWidgetHolder;
-import java.io.File;
import java.util.List;
+import java.util.function.Consumer;
import java.util.stream.Collectors;
import javax.inject.Inject;
@@ -104,31 +104,16 @@ public class ModelDbController {
mLayoutParserFactory = layoutParserFactory;
}
- private void printDBs(String prefix) {
- try {
- File directory = new File(mContext.getDatabasePath(mIdp.dbFile).getParent());
- if (directory.exists()) {
- for (File file : directory.listFiles()) {
- Log.d("b/353505773", prefix + "Database file: " + file.getName());
- }
- } else {
- Log.d("b/353505773", prefix + "No files found in the database directory");
- }
- } catch (Exception e) {
- Log.e("b/353505773", prefix + e.getMessage());
- }
- }
-
private synchronized void createDbIfNotExists() {
if (mOpenHelper == null) {
+ // Initialize the restore task before opening the DB
+ Consumer restoreTask = RestoreDbTask.createRestoreTask(mContext);
String dbFile = mPrefs.get(DB_FILE);
if (dbFile.isEmpty()) {
dbFile = mIdp.dbFile;
}
mOpenHelper = createDatabaseHelper(false /* forMigration */, dbFile);
- printDBs("before: ");
- RestoreDbTask.restoreIfNeeded(mContext, this);
- printDBs("after: ");
+ restoreTask.accept(this);
}
}
diff --git a/src/com/android/launcher3/model/ModelWriter.java b/src/com/android/launcher3/model/ModelWriter.java
index 01e1730f47..d591a75383 100644
--- a/src/com/android/launcher3/model/ModelWriter.java
+++ b/src/com/android/launcher3/model/ModelWriter.java
@@ -242,7 +242,7 @@ public class ModelWriter {
updateItemInfoProps(item, container, screenId, cellX, cellY);
item.id = mModel.getModelDbController().generateNewItemId();
- notifyOtherCallbacks(c -> c.bindItems(Collections.singletonList(item), false));
+ notifyOtherCallbacks(c -> c.bindItemsAdded(Collections.singletonList(item)));
ModelVerifier verifier = new ModelVerifier();
final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
diff --git a/src/com/android/launcher3/model/WorkspaceItemProcessor.kt b/src/com/android/launcher3/model/WorkspaceItemProcessor.kt
index 235ca9fc56..3648ca55a9 100644
--- a/src/com/android/launcher3/model/WorkspaceItemProcessor.kt
+++ b/src/com/android/launcher3/model/WorkspaceItemProcessor.kt
@@ -166,7 +166,14 @@ class WorkspaceItemProcessor(
// If the apk is present and the shortcut points to a specific component.
// If the component is already present
- if (launcherApps.isActivityEnabled(cn, c.user)) {
+ val isActivityEnabled =
+ try {
+ launcherApps.isActivityEnabled(cn, c.user)
+ } catch (exception: Exception) {
+ FileLog.w(TAG, "Error checking activity enabled for component:$cn", exception)
+ false
+ }
+ if (isActivityEnabled) {
// no special handling necessary for this item
c.markRestored()
} else {
diff --git a/src/com/android/launcher3/provider/RestoreDbTask.java b/src/com/android/launcher3/provider/RestoreDbTask.java
index f6ee26baa6..d2a9a43a5c 100644
--- a/src/com/android/launcher3/provider/RestoreDbTask.java
+++ b/src/com/android/launcher3/provider/RestoreDbTask.java
@@ -80,6 +80,7 @@ import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
+import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Collectors;
@@ -106,25 +107,21 @@ public class RestoreDbTask {
"appWidgetId", "restored"};
/**
- * Tries to restore the backup DB if needed
+ * Creates a task for restoring the backed up DB if needed. It performs the initial disk
+ * validation immediately and returns a callback which can be used to complete any database
+ * updates.
*/
- public static void restoreIfNeeded(Context context, ModelDbController dbController) {
+ public static Consumer createRestoreTask(Context context) {
if (!isPending(context)) {
Log.d(TAG, "No restore task pending, exiting RestoreDbTask");
- return;
- }
- if (!performRestore(context, dbController)) {
- dbController.createEmptyDB();
+ return c -> { };
}
// Obtain InvariantDeviceProfile first before setting pending to false, so
// InvariantDeviceProfile won't switch to new grid when initializing.
InvariantDeviceProfile idp = InvariantDeviceProfile.INSTANCE.get(context);
- // Set is pending to false irrespective of the result, so that it doesn't get
- // executed again.
- LauncherPrefs.get(context).removeSync(RESTORE_DEVICE);
-
+ // Perform any disk updates before accessing the actual database.
DeviceGridState deviceGridState = new DeviceGridState(context);
FileLog.d(TAG, "restoreIfNeeded: deviceGridState from context: " + deviceGridState);
String oldPhoneFileName = deviceGridState.getDbFile();
@@ -137,6 +134,16 @@ public class RestoreDbTask {
idp.reset(context);
trySettingPreviousGridAsCurrent(context, idp, oldPhoneFileName, previousDbs);
}
+
+ return dbController -> {
+ if (!performRestore(context, dbController)) {
+ dbController.createEmptyDB();
+ }
+
+ // Set is pending to false irrespective of the result, so that it doesn't get
+ // executed again.
+ LauncherPrefs.get(context).removeSync(RESTORE_DEVICE);
+ };
}
@@ -192,7 +199,7 @@ public class RestoreDbTask {
LauncherFiles.GRID_DB_FILES.stream()
.filter(dbName -> !dbName.equals(oldPhoneDbFileName))
.forEach(dbName -> {
- if (context.getDatabasePath(dbName).delete()) {
+ if (context.deleteDatabase(dbName)) {
FileLog.d(TAG, "Removed old grid db file: " + dbName);
}
});
@@ -433,8 +440,9 @@ public class RestoreDbTask {
public static void setPending(Context context) {
DeviceGridState deviceGridState = new DeviceGridState(context);
FileLog.d(TAG, "restore initiated from backup: DeviceGridState=" + deviceGridState);
- LauncherPrefs.get(context).putSync(RESTORE_DEVICE.to(deviceGridState.getDeviceType()));
- LauncherPrefs.get(context).putSync(IS_FIRST_LOAD_AFTER_RESTORE.to(true));
+ LauncherPrefs.get(context).putSync(
+ RESTORE_DEVICE.to(deviceGridState.getDeviceType()),
+ IS_FIRST_LOAD_AFTER_RESTORE.to(true));
}
@WorkerThread
diff --git a/src/com/android/launcher3/secondarydisplay/SecondaryDisplayLauncher.java b/src/com/android/launcher3/secondarydisplay/SecondaryDisplayLauncher.java
index 54efccdac3..8c0f8378e3 100644
--- a/src/com/android/launcher3/secondarydisplay/SecondaryDisplayLauncher.java
+++ b/src/com/android/launcher3/secondarydisplay/SecondaryDisplayLauncher.java
@@ -234,11 +234,6 @@ public class SecondaryDisplayLauncher extends BaseActivity
animator.start();
}
- @Override
- public void startBinding() {
- mDragController.cancelDrag();
- }
-
@Override
public void bindDeepShortcutMap(HashMap deepShortcutMap) {
mPopupDataProvider.setDeepShortcutMap(deepShortcutMap);
diff --git a/tests/multivalentTests/src/com/android/launcher3/model/AddWorkspaceItemsTaskTest.kt b/tests/multivalentTests/src/com/android/launcher3/model/AddWorkspaceItemsTaskTest.kt
index 6d366db0e6..d19048d87e 100644
--- a/tests/multivalentTests/src/com/android/launcher3/model/AddWorkspaceItemsTaskTest.kt
+++ b/tests/multivalentTests/src/com/android/launcher3/model/AddWorkspaceItemsTaskTest.kt
@@ -61,8 +61,7 @@ class AddWorkspaceItemsTaskTest : AbstractWorkspaceModelTest() {
val addedItems = testAddItems(nonEmptyScreenIds, itemToAdd)
assertThat(addedItems.size).isEqualTo(1)
- assertThat(addedItems.first().itemInfo.screenId).isEqualTo(1)
- assertThat(addedItems.first().isAnimated).isTrue()
+ assertThat(addedItems.first().screenId).isEqualTo(1)
verifyItemSpaceFinderCall(nonEmptyScreenIds, numberOfExpectedCall = 1)
}
@@ -75,8 +74,7 @@ class AddWorkspaceItemsTaskTest : AbstractWorkspaceModelTest() {
val addedItems = testAddItems(nonEmptyScreenIds, *itemsToAdd)
assertThat(addedItems.size).isEqualTo(1)
- assertThat(addedItems.first().itemInfo.screenId).isEqualTo(1)
- assertThat(addedItems.first().isAnimated).isTrue()
+ assertThat(addedItems.first().screenId).isEqualTo(1)
verifyItemSpaceFinderCall(nonEmptyScreenIds, numberOfExpectedCall = 1)
}
@@ -102,8 +100,7 @@ class AddWorkspaceItemsTaskTest : AbstractWorkspaceModelTest() {
val addedItems = testAddItems(nonEmptyScreenIds, itemToAdd)
assertThat(addedItems.size).isEqualTo(1)
- assertThat(addedItems.first().itemInfo.screenId).isEqualTo(2)
- assertThat(addedItems.first().isAnimated).isTrue()
+ assertThat(addedItems.first().screenId).isEqualTo(2)
verifyItemSpaceFinderCall(nonEmptyScreenIds, numberOfExpectedCall = 1)
}
@@ -120,14 +117,12 @@ class AddWorkspaceItemsTaskTest : AbstractWorkspaceModelTest() {
assertThat(addedItems.size).isEqualTo(3)
// Items that are added to the first screen should not be animated
- val itemsAddedToFirstScreen = addedItems.filter { it.itemInfo.screenId == 1 }
+ val itemsAddedToFirstScreen = addedItems.filter { it.screenId == 1 }
assertThat(itemsAddedToFirstScreen.size).isEqualTo(1)
- assertThat(itemsAddedToFirstScreen.first().isAnimated).isFalse()
// Items that are added to the second screen should be animated
- val itemsAddedToSecondScreen = addedItems.filter { it.itemInfo.screenId == 2 }
+ val itemsAddedToSecondScreen = addedItems.filter { it.screenId == 2 }
assertThat(itemsAddedToSecondScreen.size).isEqualTo(2)
- itemsAddedToSecondScreen.forEach { assertThat(it.isAnimated).isTrue() }
verifyItemSpaceFinderCall(nonEmptyScreenIds, numberOfExpectedCall = 3)
}
@@ -160,11 +155,11 @@ class AddWorkspaceItemsTaskTest : AbstractWorkspaceModelTest() {
private fun testAddItems(
nonEmptyScreenIds: List,
vararg itemsToAdd: WorkspaceItemInfo,
- ): List {
+ ): List {
setupWorkspaces(nonEmptyScreenIds)
val task = newTask(*itemsToAdd)
- val addedItems = mutableListOf()
+ val addedItems = mutableListOf()
runOnExecutorSync(Executors.MODEL_EXECUTOR) {
mDataModelCallbacks.addedItems.clear()
@@ -187,18 +182,11 @@ class AddWorkspaceItemsTaskTest : AbstractWorkspaceModelTest() {
.let { AddWorkspaceItemsTask(it, mWorkspaceItemSpaceFinder) }
}
-private data class AddedItem(val itemInfo: ItemInfo, val isAnimated: Boolean)
-
private class MyCallbacks : BgDataModel.Callbacks {
- val addedItems = mutableListOf()
+ val addedItems = mutableListOf()
- override fun bindAppsAdded(
- newScreens: IntArray?,
- addNotAnimated: ArrayList,
- addAnimated: ArrayList,
- ) {
- addedItems.addAll(addAnimated.map { AddedItem(it, true) })
- addedItems.addAll(addNotAnimated.map { AddedItem(it, false) })
+ override fun bindItemsAdded(items: List) {
+ addedItems.addAll(items)
}
}
diff --git a/tests/multivalentTests/src/com/android/launcher3/model/AsyncBindingTest.kt b/tests/multivalentTests/src/com/android/launcher3/model/AsyncBindingTest.kt
index 9f55f392c3..61d96bab00 100644
--- a/tests/multivalentTests/src/com/android/launcher3/model/AsyncBindingTest.kt
+++ b/tests/multivalentTests/src/com/android/launcher3/model/AsyncBindingTest.kt
@@ -17,45 +17,52 @@
package com.android.launcher3.model
import android.os.Looper
+import android.platform.test.annotations.DisableFlags
+import android.platform.test.annotations.EnableFlags
import android.platform.test.flag.junit.SetFlagsRule
-import android.util.Pair
import android.util.SparseArray
import android.view.View
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import com.android.launcher3.Flags
+import com.android.launcher3.InvariantDeviceProfile
+import com.android.launcher3.Launcher
import com.android.launcher3.LauncherAppState
import com.android.launcher3.LauncherModel
-import com.android.launcher3.model.BgDataModel.Callbacks
+import com.android.launcher3.ModelCallbacks
import com.android.launcher3.model.data.ItemInfo
+import com.android.launcher3.pageindicators.PageIndicatorDots
import com.android.launcher3.util.Executors.MAIN_EXECUTOR
import com.android.launcher3.util.Executors.MODEL_EXECUTOR
-import com.android.launcher3.util.IntArray
import com.android.launcher3.util.IntSet
import com.android.launcher3.util.ItemInflater
import com.android.launcher3.util.LauncherLayoutBuilder
import com.android.launcher3.util.LauncherModelHelper.TEST_PACKAGE
import com.android.launcher3.util.ModelTestExtensions.loadModelSync
-import com.android.launcher3.util.RunnableList
import com.android.launcher3.util.SandboxApplication
+import com.android.launcher3.util.TestUtil.runOnExecutorSync
import com.android.launcher3.util.rule.LayoutProviderRule
import org.junit.Assert.assertEquals
-import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
+import org.mockito.Answers
import org.mockito.Mock
import org.mockito.MockitoAnnotations
-import org.mockito.Spy
import org.mockito.kotlin.any
+import org.mockito.kotlin.anyOrNull
import org.mockito.kotlin.argThat
import org.mockito.kotlin.atLeastOnce
+import org.mockito.kotlin.clearInvocations
import org.mockito.kotlin.doAnswer
+import org.mockito.kotlin.doReturn
import org.mockito.kotlin.isNull
import org.mockito.kotlin.never
-import org.mockito.kotlin.reset
+import org.mockito.kotlin.spy
import org.mockito.kotlin.times
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
@@ -69,8 +76,13 @@ class AsyncBindingTest {
@get:Rule val context = SandboxApplication().withModelDependency()
@get:Rule val layoutProvider = LayoutProviderRule(context)
- @Spy private var callbacks = MyCallbacks()
@Mock private lateinit var itemInflater: ItemInflater<*>
+ // PageIndicatorDots need to be mocked separately as Workspace uses generics and doesn't define
+ // the actual class of PageIndicator being used
+ @Mock private lateinit var pageIndicatorDots: PageIndicatorDots
+ @Mock(answer = Answers.RETURNS_DEEP_STUBS) private lateinit var launcher: Launcher
+
+ private lateinit var callbacks: ModelCallbacks
private val inflationLooper = SparseArray()
@@ -79,7 +91,6 @@ class AsyncBindingTest {
@Before
fun setUp() {
- setFlagsRule.enableFlags(Flags.FLAG_ENABLE_WORKSPACE_INFLATION)
MockitoAnnotations.initMocks(this)
doAnswer { i ->
@@ -89,6 +100,13 @@ class AsyncBindingTest {
.whenever(itemInflater)
.inflateItem(any(), isNull())
+ doReturn(itemInflater).whenever(launcher).itemInflater
+ doReturn(InvariantDeviceProfile.INSTANCE.get(context).getDeviceProfile(context))
+ .whenever(launcher)
+ .deviceProfile
+ launcher.workspace.apply { doReturn(pageIndicatorDots).whenever(this).getPageIndicator() }
+ doReturn(context).whenever(launcher).applicationContext
+
// Set up the workspace with 3 pages of apps
layoutProvider.setupDefaultLayoutProvider(
LauncherLayoutBuilder()
@@ -103,30 +121,29 @@ class AsyncBindingTest {
.atWorkspace(0, 1, 2)
.putApp(TEST_PACKAGE, TEST_PACKAGE)
)
+ callbacks =
+ spy(ModelCallbacks(launcher).apply { pagesToBindSynchronously = IntSet.wrap(0) })
}
@Test
+ @DisableFlags(Flags.FLAG_ENABLE_WORKSPACE_INFLATION)
fun test_bind_normally_without_itemInflater() {
MAIN_EXECUTOR.execute { model.addCallbacksAndLoad(callbacks) }
waitForLoaderAndTempMainThread()
- verify(callbacks, never()).bindInflatedItems(any())
verify(callbacks, atLeastOnce()).bindItems(any(), any())
}
@Test
+ @EnableFlags(Flags.FLAG_ENABLE_WORKSPACE_INFLATION)
fun test_bind_inflates_item_on_background() {
- callbacks.inflater = itemInflater
MAIN_EXECUTOR.execute { model.addCallbacksAndLoad(callbacks) }
waitForLoaderAndTempMainThread()
verify(callbacks, never()).bindItems(any(), any())
- verify(callbacks, times(1)).bindInflatedItems(argThat { t -> t.size == 2 })
-
- // Verify remaining items are bound using pendingTasks
- reset(callbacks)
- MAIN_EXECUTOR.submit(callbacks.pendingTasks!!::executeAllAndDestroy).get()
- verify(callbacks, times(1)).bindInflatedItems(argThat { t -> t.size == 3 })
+ // First 2 items were bound and eventually remaining items were bound
+ verify(launcher, times(1)).bindInflatedItems(argThat { size == 2 }, anyOrNull())
+ verify(launcher, times(1)).bindInflatedItems(argThat { size == 3 }, anyOrNull())
// Verify that all items were inflated on the background thread
assertEquals(5, inflationLooper.size())
@@ -134,31 +151,34 @@ class AsyncBindingTest {
}
@Test
+ @EnableFlags(Flags.FLAG_ENABLE_WORKSPACE_INFLATION)
fun test_bind_sync_partially_inflates_on_background() {
model.loadModelSync()
assertTrue(model.isModelLoaded())
- callbacks.inflater = itemInflater
- val firstPageBindIds = IntSet()
+ val firstPageBindIds = mutableSetOf()
+ runOnExecutorSync(MAIN_EXECUTOR) {
+ model.addCallbacksAndLoad(callbacks)
+ verify(callbacks, never()).bindItems(any(), any())
+ verify(launcher, times(1))
+ .bindInflatedItems(
+ argThat {
+ firstPageBindIds.addAll(map { it.first.id })
+ size == 2
+ },
+ anyOrNull(),
+ )
- MAIN_EXECUTOR.submit {
- model.addCallbacksAndLoad(callbacks)
- verify(callbacks, never()).bindItems(any(), any())
- verify(callbacks, times(1))
- .bindInflatedItems(
- argThat { t ->
- t.forEach { firstPageBindIds.add(it.first.id) }
- t.size == 2
- }
- )
-
- // Verify that onInitialBindComplete is called and the binding is not yet complete
- assertFalse(callbacks.onCompleteSignal!!.isDestroyed)
- }
- .get()
+ // Verify that onInitialBindComplete is called and the binding is not yet complete
+ assertNotNull(callbacks.pendingExecutor)
+ clearInvocations(launcher)
+ }
waitForLoaderAndTempMainThread()
- assertTrue(callbacks.onCompleteSignal!!.isDestroyed)
+
+ // Verify remaining 3 times are bound using pending tasks
+ assertNull(callbacks.pendingExecutor)
+ verify(launcher, times(1)).bindInflatedItems(argThat { t -> t.size == 3 }, anyOrNull())
// Verify that firstPageBindIds are loaded on the main thread and remaining
// on the background thread.
@@ -168,45 +188,12 @@ class AsyncBindingTest {
assertEquals(MAIN_EXECUTOR.looper, inflationLooper.valueAt(i))
else assertEquals(MODEL_EXECUTOR.looper, inflationLooper.valueAt(i))
}
-
- MAIN_EXECUTOR.submit {
- reset(callbacks)
- callbacks.pendingTasks!!.executeAllAndDestroy()
- // Verify remaining 3 times are bound using pending tasks
- verify(callbacks, times(1)).bindInflatedItems(argThat { t -> t.size == 3 })
- }
- .get()
}
private fun waitForLoaderAndTempMainThread() {
- MAIN_EXECUTOR.submit {}.get()
- MODEL_EXECUTOR.submit {}.get()
- MAIN_EXECUTOR.submit {}.get()
- }
-
- class MyCallbacks : Callbacks {
-
- var inflater: ItemInflater<*>? = null
- var pendingTasks: RunnableList? = null
- var onCompleteSignal: RunnableList? = null
-
- override fun bindItems(shortcuts: MutableList, forceAnimateIcons: Boolean) {}
-
- override fun bindInflatedItems(items: MutableList>) {}
-
- override fun getPagesToBindSynchronously(orderedScreenIds: IntArray?) = IntSet.wrap(0)
-
- override fun onInitialBindComplete(
- boundPages: IntSet,
- pendingTasks: RunnableList,
- onCompleteSignal: RunnableList,
- workspaceItemCount: Int,
- isBindSync: Boolean,
- ) {
- this.pendingTasks = pendingTasks
- this.onCompleteSignal = onCompleteSignal
+ repeat(5) {
+ runOnExecutorSync(MAIN_EXECUTOR) {}
+ runOnExecutorSync(MODEL_EXECUTOR) {}
}
-
- override fun getItemInflater() = inflater
}
}
diff --git a/tests/multivalentTests/src/com/android/launcher3/util/rule/BackAndRestoreRule.kt b/tests/multivalentTests/src/com/android/launcher3/util/rule/BackAndRestoreRule.kt
index da96939a2b..bbce62be85 100644
--- a/tests/multivalentTests/src/com/android/launcher3/util/rule/BackAndRestoreRule.kt
+++ b/tests/multivalentTests/src/com/android/launcher3/util/rule/BackAndRestoreRule.kt
@@ -16,6 +16,7 @@
package com.android.launcher3.util.rule
+import android.content.Context
import androidx.test.platform.app.InstrumentationRegistry.getInstrumentation
import com.android.launcher3.InvariantDeviceProfile
import com.android.launcher3.LauncherPrefs
@@ -31,13 +32,12 @@ import org.junit.runners.model.Statement
* assets/databases/BackupAndRestore to the device. It also set's the needed LauncherPrefs variables
* needed to kickstart a backup and restore.
*/
-class BackAndRestoreRule : TestRule {
-
- private val phoneContext = getInstrumentation().targetContext
+class BackAndRestoreRule(private val phoneContext: Context = getInstrumentation().targetContext) :
+ TestRule {
private fun dbBackUp() = File(phoneContext.dataDir.path, "/databasesBackUp")
- private fun dbDirectory() = File(phoneContext.dataDir.path, "/databases")
+ private fun dbDirectory() = phoneContext.getDatabasePath("test").parentFile
private fun isWorkspaceDatabase(rawFileName: String): Boolean {
val fileName = Paths.get(rawFileName).fileName.pathString
@@ -58,7 +58,7 @@ class BackAndRestoreRule : TestRule {
}
private fun uploadDatabase(dbName: String) {
- val file = File(File(getInstrumentation().targetContext.dataDir, "/databases"), dbName)
+ val file = phoneContext.getDatabasePath(dbName)
file.writeBytes(
getInstrumentation()
.context
diff --git a/tests/src/com/android/launcher3/backuprestore/BackupAndRestoreDBSelectionTest.kt b/tests/src/com/android/launcher3/backuprestore/BackupAndRestoreDBSelectionTest.kt
index 34d9d40d67..55aed0bbd8 100644
--- a/tests/src/com/android/launcher3/backuprestore/BackupAndRestoreDBSelectionTest.kt
+++ b/tests/src/com/android/launcher3/backuprestore/BackupAndRestoreDBSelectionTest.kt
@@ -16,26 +16,33 @@
package com.android.launcher3.backuprestore
+import android.database.sqlite.SQLiteDatabase
import android.platform.test.annotations.DisableFlags
import android.platform.test.annotations.EnableFlags
import android.platform.test.flag.junit.SetFlagsRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
-import androidx.test.platform.app.InstrumentationRegistry.getInstrumentation
import com.android.launcher3.Flags
import com.android.launcher3.LauncherAppState
import com.android.launcher3.LauncherPrefs
import com.android.launcher3.model.ModelDelegate
import com.android.launcher3.provider.RestoreDbTask
import com.android.launcher3.util.Executors.MODEL_EXECUTOR
+import com.android.launcher3.util.SandboxApplication
import com.android.launcher3.util.TestUtil
import com.android.launcher3.util.rule.BackAndRestoreRule
import com.android.launcher3.util.rule.setFlags
+import java.io.File
+import java.nio.file.Files
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
+import org.mockito.kotlin.any
+import org.mockito.kotlin.doAnswer
import org.mockito.kotlin.mock
+import org.mockito.kotlin.spy
+import org.mockito.kotlin.whenever
/**
* Makes sure to test {@code RestoreDbTask#removeOldDBs}, we need to remove all the dbs that are not
@@ -45,8 +52,29 @@ import org.mockito.kotlin.mock
@MediumTest
class BackupAndRestoreDBSelectionTest {
- @get:Rule var backAndRestoreRule = BackAndRestoreRule()
@get:Rule val setFlagsRule = SetFlagsRule()
+ @get:Rule
+ val context =
+ spy(SandboxApplication()).apply {
+ val tempDir = Files.createTempDirectory(filesDir.toPath(), "bnr_test").toFile()
+ doAnswer { File(tempDir, it.getArgument(0, String::class.java)) }
+ .whenever(this)
+ .getDatabasePath(any())
+
+ doAnswer {
+ try {
+ SQLiteDatabase.deleteDatabase(
+ getDatabasePath(it.getArgument(0, String::class.java))
+ )
+ } catch (e: Exception) {
+ false
+ }
+ }
+ .whenever(this)
+ .deleteDatabase(any())
+ }
+
+ @get:Rule var backAndRestoreRule = BackAndRestoreRule(context)
val modelDelegate = mock()
@@ -67,8 +95,7 @@ class BackupAndRestoreDBSelectionTest {
@Test
fun oldDatabasesNotPresentAfterRestore() {
- val dbController =
- LauncherAppState.getInstance(getInstrumentation().targetContext).model.modelDbController
+ val dbController = LauncherAppState.getInstance(context).model.modelDbController
if (Flags.gridMigrationRefactor()) {
dbController.attemptMigrateDb(null, modelDelegate)
} else {
@@ -78,10 +105,7 @@ class BackupAndRestoreDBSelectionTest {
assert(backAndRestoreRule.getDatabaseFiles().size == 1) {
"There should only be one database after restoring, the last one used. Actual databases ${backAndRestoreRule.getDatabaseFiles()}"
}
- assert(
- !LauncherPrefs.get(getInstrumentation().targetContext)
- .has(LauncherPrefs.RESTORE_DEVICE)
- ) {
+ assert(!LauncherPrefs.get(context).has(LauncherPrefs.RESTORE_DEVICE)) {
"RESTORE_DEVICE shouldn't be present after a backup and restore."
}
}
@@ -89,10 +113,10 @@ class BackupAndRestoreDBSelectionTest {
@Test
fun testExistingDbsAndRemovingDbs() {
- var existingDbs = RestoreDbTask.existingDbs(getInstrumentation().targetContext)
+ var existingDbs = RestoreDbTask.existingDbs(context)
assert(existingDbs.size == 4)
- RestoreDbTask.removeOldDBs(getInstrumentation().targetContext, "launcher_4_by_4.db")
- existingDbs = RestoreDbTask.existingDbs(getInstrumentation().targetContext)
+ RestoreDbTask.removeOldDBs(context, "launcher_4_by_4.db")
+ existingDbs = RestoreDbTask.existingDbs(context)
assert(existingDbs.size == 1)
}
}
diff --git a/tests/src/com/android/launcher3/model/ModelMultiCallbacksTest.java b/tests/src/com/android/launcher3/model/ModelMultiCallbacksTest.java
index 3115899262..d64049d384 100644
--- a/tests/src/com/android/launcher3/model/ModelMultiCallbacksTest.java
+++ b/tests/src/com/android/launcher3/model/ModelMultiCallbacksTest.java
@@ -32,14 +32,13 @@ import androidx.test.filters.SmallTest;
import com.android.launcher3.LauncherAppState;
import com.android.launcher3.LauncherModel;
import com.android.launcher3.model.BgDataModel.Callbacks;
+import com.android.launcher3.model.BgDataModel.FixedContainerItems;
import com.android.launcher3.model.data.AppInfo;
import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.util.Executors;
-import com.android.launcher3.util.IntArray;
-import com.android.launcher3.util.IntSet;
+import com.android.launcher3.util.IntSparseArrayMap;
import com.android.launcher3.util.LauncherLayoutBuilder;
import com.android.launcher3.util.PackageUserKey;
-import com.android.launcher3.util.RunnableList;
import com.android.launcher3.util.SandboxApplication;
import com.android.launcher3.util.TestUtil;
import com.android.launcher3.util.rule.LayoutProviderRule;
@@ -49,7 +48,6 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
-import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
@@ -83,17 +81,16 @@ public class ModelMultiCallbacksTest {
Executors.MAIN_EXECUTOR.execute(() -> getModel().addCallbacksAndLoad(cb1));
waitForLoaderAndTempMainThread();
- cb1.verifySynchronouslyBound(3);
+ cb1.verifyItemsBound(3);
// Add a new callback
cb1.reset();
MyCallbacks cb2 = spy(MyCallbacks.class);
- cb2.mPageToBindSync = IntSet.wrap(2);
Executors.MAIN_EXECUTOR.execute(() -> getModel().addCallbacksAndLoad(cb2));
waitForLoaderAndTempMainThread();
- assertFalse(cb1.bindStarted);
- cb2.verifySynchronouslyBound(3);
+ assertNull(cb1.mItems);
+ cb2.verifyItemsBound(3);
// Remove callbacks
cb1.reset();
@@ -102,14 +99,14 @@ public class ModelMultiCallbacksTest {
// No effect on callbacks when removing an callback
Executors.MAIN_EXECUTOR.execute(() -> getModel().removeCallbacks(cb2));
waitForLoaderAndTempMainThread();
- assertNull(cb1.mPendingTasks);
- assertNull(cb2.mPendingTasks);
+ assertNull(cb1.mItems);
+ assertNull(cb2.mItems);
// Reloading only loads registered callbacks
getModel().startLoader();
waitForLoaderAndTempMainThread();
- cb1.verifySynchronouslyBound(3);
- assertNull(cb2.mPendingTasks);
+ cb1.verifyItemsBound(3);
+ assertNull(cb2.mItems);
}
@Test
@@ -173,30 +170,16 @@ public class ModelMultiCallbacksTest {
private abstract static class MyCallbacks implements Callbacks {
- final List mItems = new ArrayList<>();
- IntSet mPageToBindSync = IntSet.wrap(0);
- IntSet mPageBoundSync = new IntSet();
- RunnableList mPendingTasks;
+ List mItems = null;
AppInfo[] mAppInfos;
- boolean bindStarted;
MyCallbacks() { }
@Override
- public void startBinding() {
- bindStarted = true;
- }
-
- @Override
- public void onInitialBindComplete(IntSet boundPages, RunnableList pendingTasks,
- RunnableList onCompleteSignal, int workspaceItemCount, boolean isBindSync) {
- mPageBoundSync = boundPages;
- mPendingTasks = pendingTasks;
- }
-
- @Override
- public void bindItems(List shortcuts, boolean forceAnimateIcons) {
- mItems.addAll(shortcuts);
+ public void bindCompleteModel(IntSparseArrayMap itemIdMap,
+ List extraItems, StringCache stringCache,
+ boolean isBindingSync) {
+ mItems = itemIdMap.stream().toList();
}
@Override
@@ -205,29 +188,13 @@ public class ModelMultiCallbacksTest {
mAppInfos = apps;
}
- @Override
- public IntSet getPagesToBindSynchronously(IntArray orderedScreenIds) {
- return mPageToBindSync;
- }
-
public void reset() {
- mItems.clear();
- mPageBoundSync = new IntSet();
- mPendingTasks = null;
+ mItems = null;
mAppInfos = null;
- bindStarted = false;
}
- public void verifySynchronouslyBound(int totalItems) {
- // Verify that the requested page is bound synchronously
- assertTrue(bindStarted);
- assertEquals(mPageToBindSync, mPageBoundSync);
- assertEquals(mItems.size(), 1);
- assertEquals(IntSet.wrap(mItems.get(0).screenId), mPageBoundSync);
- assertNotNull(mPendingTasks);
-
- // Verify that all other pages are bound properly
- mPendingTasks.executeAllAndDestroy();
+ public void verifyItemsBound(int totalItems) {
+ assertNotNull(mItems);
assertEquals(mItems.size(), totalItems);
}
@@ -236,9 +203,5 @@ public class ModelMultiCallbacksTest {
.map(ai -> ai.getTargetComponent().getPackageName())
.collect(Collectors.toSet());
}
-
- public void verifyApps(String... apps) {
- assertTrue(allApps().containsAll(Arrays.asList(apps)));
- }
}
}
diff --git a/tests/tapl/com/android/launcher3/tapl/BaseOverview.java b/tests/tapl/com/android/launcher3/tapl/BaseOverview.java
index 214f1587f5..f27c25a159 100644
--- a/tests/tapl/com/android/launcher3/tapl/BaseOverview.java
+++ b/tests/tapl/com/android/launcher3/tapl/BaseOverview.java
@@ -522,11 +522,13 @@ public class BaseOverview extends LauncherInstrumentation.VisibleContainer {
)) {
if (isActionsViewVisible()) {
+ UiObject2 actionsButtons;
if (task.isGrouped()) {
- mLauncher.waitForOverviewObject("action_save_app_pair");
+ actionsButtons = mLauncher.waitForOverviewObject("action_save_app_pair");
} else {
- mLauncher.waitForOverviewObject("action_buttons");
+ actionsButtons = mLauncher.waitForOverviewObject("action_buttons");
}
+ mLauncher.assertTrue("Overview actions is disabled", actionsButtons.isEnabled());
} else {
mLauncher.waitUntilOverviewObjectGone("action_buttons");
mLauncher.waitUntilOverviewObjectGone("action_save_app_pair");