From 2164771130ad7b9cb7ebbd2c68fcdc25cdfda0f3 Mon Sep 17 00:00:00 2001 From: Sebastian Franco Date: Wed, 5 Feb 2025 13:13:36 -0800 Subject: [PATCH 001/153] Fix null ptr exception on createUpdateRunnable lambda Fix: 394043832 Test: NA Flag: EXEMPT bugfix Change-Id: I60b85c520e7553318ea741da8768951c974dcc7e --- src/com/android/launcher3/popup/PopupPopulator.java | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/com/android/launcher3/popup/PopupPopulator.java b/src/com/android/launcher3/popup/PopupPopulator.java index b7480116f9..bc5064d87a 100644 --- a/src/com/android/launcher3/popup/PopupPopulator.java +++ b/src/com/android/launcher3/popup/PopupPopulator.java @@ -110,13 +110,16 @@ public class PopupPopulator { public static Runnable createUpdateRunnable( final T context, final ItemInfo originalInfo, - final Handler uiHandler, final PopupContainerWithArrow container, - final List shortcutViews) { + final Handler uiHandler, + final PopupContainerWithArrow container, + final List shortcutViews + ) { final ComponentName activity = originalInfo.getTargetComponent(); final UserHandle user = originalInfo.user; + final String targetPackage = originalInfo.getTargetPackage(); return () -> { ApplicationInfoWrapper infoWrapper = - new ApplicationInfoWrapper(context, originalInfo.getTargetPackage(), user); + new ApplicationInfoWrapper(context, targetPackage, user); List shortcuts = new ShortcutRequest(context, user) .withContainer(activity) .query(ShortcutRequest.PUBLISHED); From 573fe8c72b96b8b4c61e2b44685b8b960e2569a2 Mon Sep 17 00:00:00 2001 From: Brandon Dayauon Date: Tue, 11 Feb 2025 00:43:18 +0000 Subject: [PATCH 002/153] Add logs to components in AllApps to verify click. Adding logs for investigation to verify related bugs where work profile may seem inactive but is supposed to be active. This also helps verify if touch is being received. Bug: 383301695 Test: manually- screenshot in bug Flag: EXEMPT adding logs Change-Id: I9f42d7013c8a127767b5cbcfbe5c416cebb2adbd --- .../allapps/ActivityAllAppsContainerView.java | 3 +++ src/com/android/launcher3/allapps/WorkPausedCard.java | 3 +++ .../android/launcher3/allapps/WorkProfileManager.java | 1 + src/com/android/launcher3/allapps/WorkUtilityView.java | 10 +++++++--- 4 files changed, 14 insertions(+), 3 deletions(-) diff --git a/src/com/android/launcher3/allapps/ActivityAllAppsContainerView.java b/src/com/android/launcher3/allapps/ActivityAllAppsContainerView.java index b0001af5d3..bc3c5cd6ed 100644 --- a/src/com/android/launcher3/allapps/ActivityAllAppsContainerView.java +++ b/src/com/android/launcher3/allapps/ActivityAllAppsContainerView.java @@ -116,6 +116,7 @@ public class ActivityAllAppsContainerView ScrimView.ScrimDrawingController { + private static final String TAG = "ActivityAllAppsContainerView"; public static final float PULL_MULTIPLIER = .02f; public static final float FLING_VELOCITY_MULTIPLIER = 1200f; protected static final String BUNDLE_KEY_CURRENT_PAGE = "launcher.allapps.current_page"; @@ -605,6 +606,7 @@ public class ActivityAllAppsContainerView mViewPager.getPageIndicator().setActiveMarker(AdapterHolder.MAIN); findViewById(R.id.tab_personal) .setOnClickListener((View view) -> { + Log.d(TAG, "rebindAdapters: " + "Clicked personal tab."); if (mViewPager.snapToPage(AdapterHolder.MAIN)) { mActivityContext.getStatsLogManager().logger() .log(LAUNCHER_ALLAPPS_TAP_ON_PERSONAL_TAB); @@ -612,6 +614,7 @@ public class ActivityAllAppsContainerView }); findViewById(R.id.tab_work) .setOnClickListener((View view) -> { + Log.d(TAG, "rebindAdapters: " + "Clicked work tab."); if (mViewPager.snapToPage(AdapterHolder.WORK)) { mActivityContext.getStatsLogManager().logger() .log(LAUNCHER_ALLAPPS_TAP_ON_WORK_TAB); diff --git a/src/com/android/launcher3/allapps/WorkPausedCard.java b/src/com/android/launcher3/allapps/WorkPausedCard.java index a14ac9819a..864ede8840 100644 --- a/src/com/android/launcher3/allapps/WorkPausedCard.java +++ b/src/com/android/launcher3/allapps/WorkPausedCard.java @@ -20,6 +20,7 @@ import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCH import android.content.Context; import android.content.res.Configuration; import android.util.AttributeSet; +import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; @@ -34,6 +35,7 @@ import com.android.launcher3.views.ActivityContext; */ public class WorkPausedCard extends LinearLayout implements View.OnClickListener { + private static final String TAG = "WorkPausedCard"; private final ActivityContext mActivityContext; private Button mBtn; @@ -79,6 +81,7 @@ public class WorkPausedCard extends LinearLayout implements View.OnClickListener @Override public void onClick(View view) { + Log.d(TAG, "WorkPausedCard clicked."); mActivityContext.getAppsView().getWorkManager().setWorkProfileEnabled(true); mActivityContext.getStatsLogManager().logger().log(LAUNCHER_TURN_ON_WORK_APPS_TAP); } diff --git a/src/com/android/launcher3/allapps/WorkProfileManager.java b/src/com/android/launcher3/allapps/WorkProfileManager.java index 6d7d1930fd..920efa4f64 100644 --- a/src/com/android/launcher3/allapps/WorkProfileManager.java +++ b/src/com/android/launcher3/allapps/WorkProfileManager.java @@ -200,6 +200,7 @@ public class WorkProfileManager extends UserProfileManager private void onWorkFabClicked(View view) { if (getCurrentState() == STATE_ENABLED && mWorkUtilityView.isEnabled()) { + Log.d(TAG, "Work FAB clicked."); logEvents(LAUNCHER_TURN_OFF_WORK_APPS_TAP); setWorkProfileEnabled(false); } diff --git a/src/com/android/launcher3/allapps/WorkUtilityView.java b/src/com/android/launcher3/allapps/WorkUtilityView.java index bccc279442..eb8f508ab6 100644 --- a/src/com/android/launcher3/allapps/WorkUtilityView.java +++ b/src/com/android/launcher3/allapps/WorkUtilityView.java @@ -25,6 +25,7 @@ import android.content.Intent; import android.graphics.Rect; import android.text.TextUtils; import android.util.AttributeSet; +import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.view.WindowInsets; @@ -57,6 +58,7 @@ import java.util.ArrayList; public class WorkUtilityView extends LinearLayout implements Insettable, KeyboardInsetAnimationCallback.KeyboardInsetListener { + private static final String TAG = "WorkUtilityView"; private static final int TEXT_EXPAND_OPACITY_DURATION = 300; private static final int TEXT_COLLAPSE_OPACITY_DURATION = 50; private static final int EXPAND_COLLAPSE_DURATION = 300; @@ -133,9 +135,11 @@ public class WorkUtilityView extends LinearLayout implements Insettable, mSchedulerButton.setOnClickListener(null); if (shouldUseScheduler()) { mSchedulerButton.setVisibility(VISIBLE); - mSchedulerButton.setOnClickListener(view -> - mActivityContext.startActivitySafely(view, - new Intent(mWorkSchedulerIntentAction), null /* itemInfo */)); + mSchedulerButton.setOnClickListener(view -> { + Log.d(TAG, "WorkScheduler button clicked."); + mActivityContext.startActivitySafely(view, + new Intent(mWorkSchedulerIntentAction), null /* itemInfo */); + }); } } From f9c1e2976683b715df0a8d7624a96e6c66af0455 Mon Sep 17 00:00:00 2001 From: Schneider Victor-Tulias Date: Tue, 11 Feb 2025 11:14:51 -0500 Subject: [PATCH 003/153] Add debug logs to AbsSwipeUpHandler.calculateEndTarget Flag: EXEMPT debug logs Bug: 394364217 Test: logcat Change-Id: I2b95cbbae4fdfb84dc29ebc90e7339aae199237d --- .../com/android/quickstep/AbsSwipeUpHandler.java | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/quickstep/src/com/android/quickstep/AbsSwipeUpHandler.java b/quickstep/src/com/android/quickstep/AbsSwipeUpHandler.java index f46f9ae12a..d66ffbba8e 100644 --- a/quickstep/src/com/android/quickstep/AbsSwipeUpHandler.java +++ b/quickstep/src/com/android/quickstep/AbsSwipeUpHandler.java @@ -1112,6 +1112,9 @@ public abstract class AbsSwipeUpHandler< public void onGestureEnded(float endVelocityPxPerMs, PointF velocityPxPerMs) { float flingThreshold = mContext.getResources() .getDimension(R.dimen.quickstep_fling_threshold_speed); + Log.d(TAG, "onGestureEnded: mGestureStarted=" + mGestureStarted + + ", mIsMotionPaused=" + mIsMotionPaused + + ", flingThresholdPassed=" + (Math.abs(endVelocityPxPerMs) > flingThreshold)); boolean isFling = mGestureStarted && !mIsMotionPaused && Math.abs(endVelocityPxPerMs) > flingThreshold; mStateCallback.setStateOnUiThread(STATE_GESTURE_COMPLETED); @@ -1260,12 +1263,12 @@ public abstract class AbsSwipeUpHandler< dpiFromPx(velocityPxPerMs.x), dpiFromPx(velocityPxPerMs.y), Math.toDegrees(Math.atan2(-velocityPxPerMs.y, velocityPxPerMs.x))); - if (mGestureState.isHandlingAtomicEvent()) { // Button mode, this is only used to go to recents. return RECENTS; } + Log.d(TAG, "calculateEndTarget: isCancel=" + isCancel + ", isFlingY=" + isFlingY); GestureEndTarget endTarget; if (isCancel) { endTarget = LAST_TASK; @@ -1275,6 +1278,7 @@ public abstract class AbsSwipeUpHandler< endTarget = calculateEndTargetForNonFling(velocityPxPerMs); } + Log.d(TAG, "calculateEndTarget: endTarget(1)=" + endTarget); if (mDeviceState.isOverviewDisabled() && endTarget == RECENTS) { return LAST_TASK; } @@ -1293,6 +1297,7 @@ public abstract class AbsSwipeUpHandler< return LAST_TASK; } } + Log.d(TAG, "calculateEndTarget: endTarget(2)=" + endTarget); return endTarget; } @@ -1301,9 +1306,12 @@ public abstract class AbsSwipeUpHandler< final boolean willGoToNewTask = isScrollingToNewTask() && Math.abs(velocity.x) > Math.abs(endVelocity); final boolean isSwipeUp = endVelocity < 0; + Log.d(TAG, "calculateEndTargetForFlingY: willGoToNewTask=" + willGoToNewTask + + ", isSwipeUp=" + isSwipeUp); if (!isSwipeUp) { final boolean isCenteredOnNewTask = mRecentsView != null && mRecentsView.getDestinationPage() != mRecentsView.getRunningTaskIndex(); + Log.d(TAG, "calculateEndTargetForFlingY: isCenteredOnNewTask=" + isCenteredOnNewTask); return willGoToNewTask || isCenteredOnNewTask ? NEW_TASK : LAST_TASK; } @@ -1316,6 +1324,9 @@ public abstract class AbsSwipeUpHandler< // Fully gestural mode. final boolean isFlingX = Math.abs(velocity.x) > mContext.getResources() .getDimension(R.dimen.quickstep_fling_threshold_speed); + Log.d(TAG, "calculateEndTargetForNonFling: isScrollingToNewTask=" + isScrollingToNewTask + + ", isFlingX=" + isFlingX + + ", mIsMotionPaused=" + mIsMotionPaused); if (isScrollingToNewTask && isFlingX) { // Flinging towards new task takes precedence over mIsMotionPaused (which only // checks y-velocity). @@ -1325,6 +1336,7 @@ public abstract class AbsSwipeUpHandler< } else if (isScrollingToNewTask) { return NEW_TASK; } + Log.d(TAG, "calculateEndTargetForNonFling: mCanSlowSwipeGoHome=" + mCanSlowSwipeGoHome); return velocity.y < 0 && mCanSlowSwipeGoHome ? HOME : LAST_TASK; } From b0a7ca0dbb7e827a5fb7ed3d1d8fcfb60cfa9994 Mon Sep 17 00:00:00 2001 From: Owner Cleanup Bot Date: Tue, 11 Feb 2025 16:02:45 -0800 Subject: [PATCH 004/153] [owners] Remove zakcohen@google.com from src/com/android/launcher3/widget/picker/OWNERS This suggested change is automatically generated based on group memberships and affiliations. If this change is unnecessary or in error, vote the lowest CR value (i.e. reject the CL) and the bot will abandon it. Vote the highest CR to approve this change. You may also abandon this change. See the owner's recent activity for context: https://android-review.googlesource.com/q/zakcohen@google.com To report an issue, file a bug in the Infra>Codereview component. Change-Id: Ibb729a15daafdf804c57c080a72ab8004f6861a0 --- src/com/android/launcher3/widget/picker/OWNERS | 1 - 1 file changed, 1 deletion(-) diff --git a/src/com/android/launcher3/widget/picker/OWNERS b/src/com/android/launcher3/widget/picker/OWNERS index 6aabbfa119..991193f799 100644 --- a/src/com/android/launcher3/widget/picker/OWNERS +++ b/src/com/android/launcher3/widget/picker/OWNERS @@ -6,7 +6,6 @@ set noparent # # Widget Picker OWNERS -zakcohen@google.com shamalip@google.com wvk@google.com From 41ed20667e2cdb2e4067b15f3c01e295d55bdc06 Mon Sep 17 00:00:00 2001 From: Owner Cleanup Bot Date: Tue, 11 Feb 2025 16:02:55 -0800 Subject: [PATCH 005/153] [owners] Remove zakcohen@google.com from tests/multivalentTests/src/com/android/launcher3/widget/picker/OWNERS This suggested change is automatically generated based on group memberships and affiliations. If this change is unnecessary or in error, vote the lowest CR value (i.e. reject the CL) and the bot will abandon it. Vote the highest CR to approve this change. You may also abandon this change. See the owner's recent activity for context: https://android-review.googlesource.com/q/zakcohen@google.com To report an issue, file a bug in the Infra>Codereview component. Change-Id: I72cb2c5e66ee297e9ff09257969d3d8934aad373 --- .../src/com/android/launcher3/widget/picker/OWNERS | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/multivalentTests/src/com/android/launcher3/widget/picker/OWNERS b/tests/multivalentTests/src/com/android/launcher3/widget/picker/OWNERS index 775b0c7d9b..716ab90043 100644 --- a/tests/multivalentTests/src/com/android/launcher3/widget/picker/OWNERS +++ b/tests/multivalentTests/src/com/android/launcher3/widget/picker/OWNERS @@ -5,7 +5,6 @@ set noparent # # Widget Picker OWNERS -zakcohen@google.com shamalip@google.com wvk@google.com From 40e6a538ab05c9bf04a1302ef315e4e5b5d98326 Mon Sep 17 00:00:00 2001 From: Owner Cleanup Bot Date: Tue, 11 Feb 2025 16:03:06 -0800 Subject: [PATCH 006/153] [owners] Remove zakcohen@google.com from tests/src/com/android/launcher3/widget/picker/OWNERS This suggested change is automatically generated based on group memberships and affiliations. If this change is unnecessary or in error, vote the lowest CR value (i.e. reject the CL) and the bot will abandon it. Vote the highest CR to approve this change. You may also abandon this change. See the owner's recent activity for context: https://android-review.googlesource.com/q/zakcohen@google.com To report an issue, file a bug in the Infra>Codereview component. Change-Id: I012d61af6b55dd1ae2f00be846af393bc7bc2f38 --- tests/src/com/android/launcher3/widget/picker/OWNERS | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/src/com/android/launcher3/widget/picker/OWNERS b/tests/src/com/android/launcher3/widget/picker/OWNERS index 775b0c7d9b..716ab90043 100644 --- a/tests/src/com/android/launcher3/widget/picker/OWNERS +++ b/tests/src/com/android/launcher3/widget/picker/OWNERS @@ -5,7 +5,6 @@ set noparent # # Widget Picker OWNERS -zakcohen@google.com shamalip@google.com wvk@google.com From 7dce7a09c70f0ad5a6b3327779ac242f1917c123 Mon Sep 17 00:00:00 2001 From: Brian Isganitis Date: Tue, 17 Dec 2024 19:54:02 -0500 Subject: [PATCH 007/153] Have per-environment bindings for Taskbar multivalent tests. Flag: TEST_ONLY Bug: 230027385 Test: go/testedequals Change-Id: I7dba1e052855da19c9b58c87a0a8b5258ee0dc7c --- .../taskbar/rules/TaskbarWindowSandboxContext.kt | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/quickstep/tests/multivalentTests/src/com/android/launcher3/taskbar/rules/TaskbarWindowSandboxContext.kt b/quickstep/tests/multivalentTests/src/com/android/launcher3/taskbar/rules/TaskbarWindowSandboxContext.kt index 95e8980cdb..e6806b70bf 100644 --- a/quickstep/tests/multivalentTests/src/com/android/launcher3/taskbar/rules/TaskbarWindowSandboxContext.kt +++ b/quickstep/tests/multivalentTests/src/com/android/launcher3/taskbar/rules/TaskbarWindowSandboxContext.kt @@ -26,7 +26,7 @@ import com.android.launcher3.LauncherPrefs import com.android.launcher3.dagger.ApplicationContext import com.android.launcher3.dagger.LauncherAppComponent import com.android.launcher3.dagger.LauncherAppSingleton -import com.android.launcher3.util.AllModulesForTest +import com.android.launcher3.util.AllModulesMinusWMProxy import com.android.launcher3.util.DaggerSingletonTracker import com.android.launcher3.util.DisplayController import com.android.launcher3.util.FakePrefsModule @@ -138,7 +138,13 @@ abstract class DisplayControllerModule { @LauncherAppSingleton @Component( - modules = [AllModulesForTest::class, FakePrefsModule::class, DisplayControllerModule::class] + modules = + [ + AllModulesMinusWMProxy::class, + FakePrefsModule::class, + DisplayControllerModule::class, + TaskbarSandboxModule::class, + ] ) interface TaskbarSandboxComponent : LauncherAppComponent { From 88df64edbb95488835dee7c9ff04e15fe3ab715a Mon Sep 17 00:00:00 2001 From: Jordan Silva Date: Thu, 13 Feb 2025 16:36:00 +0000 Subject: [PATCH 008/153] Convert IconAppChipView from Java to Kotlin Fix: 396401083 Flag: com.android.launcher3.enable_overview_icon_menu Test: OverviewImageTest Test: Manual Change-Id: Ie9b82a6ee531a8afb7dcfaf86d14d44acafeddc4 --- .../util/SplitAnimationController.kt | 40 +- .../quickstep/views/GroupedTaskView.kt | 6 +- .../quickstep/views/IconAppChipView.java | 471 ------------------ .../quickstep/views/IconAppChipView.kt | 438 ++++++++++++++++ 4 files changed, 466 insertions(+), 489 deletions(-) delete mode 100644 quickstep/src/com/android/quickstep/views/IconAppChipView.java create mode 100644 quickstep/src/com/android/quickstep/views/IconAppChipView.kt diff --git a/quickstep/src/com/android/quickstep/util/SplitAnimationController.kt b/quickstep/src/com/android/quickstep/util/SplitAnimationController.kt index 88d14b7e51..82a8cab223 100644 --- a/quickstep/src/com/android/quickstep/util/SplitAnimationController.kt +++ b/quickstep/src/com/android/quickstep/util/SplitAnimationController.kt @@ -215,13 +215,13 @@ class SplitAnimationController(val splitSelectStateController: SplitSelectStateC if (enableOverviewIconMenu()) { builder.add( ObjectAnimator.ofFloat( - (iconView as IconAppChipView).splitTranslationX, + (iconView as IconAppChipView).getSplitTranslationX(), MULTI_PROPERTY_VALUE, 0f, ) ) builder.add( - ObjectAnimator.ofFloat(iconView.splitTranslationY, MULTI_PROPERTY_VALUE, 0f) + ObjectAnimator.ofFloat(iconView.getSplitTranslationY(), MULTI_PROPERTY_VALUE, 0f) ) } @@ -985,12 +985,11 @@ class SplitAnimationController(val splitSelectStateController: SplitSelectStateC val splitTree: Pair>? = extractTopParentAndChildren(transitionInfo) check(splitTree != null) { "Could not find a split root candidate" } val rootCandidate = splitTree.first - val stageRootTaskIds: Set = splitTree.second - .map { it.taskInfo!!.taskId } - .toSet() - val leafTasks: List = transitionInfo.changes - .filter { it.taskInfo != null && it.taskInfo!!.parentTaskId in stageRootTaskIds} - .toList() + val stageRootTaskIds: Set = splitTree.second.map { it.taskInfo!!.taskId }.toSet() + val leafTasks: List = + transitionInfo.changes + .filter { it.taskInfo != null && it.taskInfo!!.parentTaskId in stageRootTaskIds } + .toList() // Starting position is a 34% size tile centered in the middle of the screen. // Ending position is the full device screen. @@ -1031,8 +1030,13 @@ class SplitAnimationController(val splitSelectStateController: SplitSelectStateC val endAbsBounds = leaf.endAbsBounds t.setAlpha(leaf.leash, 1f) - t.setCrop(leaf.leash, 0f, 0f, - endAbsBounds.width().toFloat(), endAbsBounds.height().toFloat()) + t.setCrop( + leaf.leash, + 0f, + 0f, + endAbsBounds.width().toFloat(), + endAbsBounds.height().toFloat(), + ) t.setPosition(leaf.leash, 0f, 0f) } @@ -1040,10 +1044,18 @@ class SplitAnimationController(val splitSelectStateController: SplitSelectStateC val endAbsBounds = stageRoot.endAbsBounds t.setAlpha(stageRoot.leash, 1f) - t.setCrop(stageRoot.leash, 0f, 0f, - endAbsBounds.width().toFloat(), endAbsBounds.height().toFloat()) - t.setPosition(stageRoot.leash, endAbsBounds.left.toFloat(), - endAbsBounds.top.toFloat()) + t.setCrop( + stageRoot.leash, + 0f, + 0f, + endAbsBounds.width().toFloat(), + endAbsBounds.height().toFloat(), + ) + t.setPosition( + stageRoot.leash, + endAbsBounds.left.toFloat(), + endAbsBounds.top.toFloat(), + ) } t.apply() } diff --git a/quickstep/src/com/android/quickstep/views/GroupedTaskView.kt b/quickstep/src/com/android/quickstep/views/GroupedTaskView.kt index 229c8f5ba1..2abfb13abd 100644 --- a/quickstep/src/com/android/quickstep/views/GroupedTaskView.kt +++ b/quickstep/src/com/android/quickstep/views/GroupedTaskView.kt @@ -171,12 +171,10 @@ class GroupedTaskView @JvmOverloads constructor(context: Context, attrs: Attribu val iconMargins = (iconViewMarginStart + iconViewBackgroundMarginStart) * 2 // setMaxWidth() needs to be called before mIconView.setIconOrientation which is // called in the super below. - (leftTopTaskContainer.iconView as IconAppChipView).setMaxWidth( + (leftTopTaskContainer.iconView as IconAppChipView).maxWidth = groupedTaskViewSizes.first.x - iconMargins - ) - (rightBottomTaskContainer.iconView as IconAppChipView).setMaxWidth( + (rightBottomTaskContainer.iconView as IconAppChipView).maxWidth = groupedTaskViewSizes.second.x - iconMargins - ) } } super.setOrientationState(orientationState) diff --git a/quickstep/src/com/android/quickstep/views/IconAppChipView.java b/quickstep/src/com/android/quickstep/views/IconAppChipView.java deleted file mode 100644 index 52704772d0..0000000000 --- a/quickstep/src/com/android/quickstep/views/IconAppChipView.java +++ /dev/null @@ -1,471 +0,0 @@ -/* - * Copyright (C) 2023 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.views; - -import static com.android.app.animation.Interpolators.EMPHASIZED; -import static com.android.app.animation.Interpolators.LINEAR; -import static com.android.launcher3.LauncherAnimUtils.SCALE_PROPERTY; -import static com.android.launcher3.LauncherAnimUtils.VIEW_TRANSLATE_X; -import static com.android.launcher3.LauncherAnimUtils.VIEW_TRANSLATE_Y; - -import android.animation.Animator; -import android.animation.AnimatorSet; -import android.animation.ObjectAnimator; -import android.animation.RectEvaluator; -import android.animation.ValueAnimator; -import android.content.Context; -import android.content.res.Resources; -import android.graphics.Outline; -import android.graphics.Rect; -import android.graphics.drawable.Drawable; -import android.util.AttributeSet; -import android.view.View; -import android.view.ViewAnimationUtils; -import android.view.ViewOutlineProvider; -import android.widget.FrameLayout; -import android.widget.ImageView; -import android.widget.TextView; - -import androidx.annotation.Nullable; - -import com.android.launcher3.R; -import com.android.launcher3.Utilities; -import com.android.launcher3.util.MultiPropertyFactory; -import com.android.launcher3.util.MultiValueAlpha; -import com.android.quickstep.orientation.RecentsPagedOrientationHandler; -import com.android.quickstep.util.RecentsOrientedState; - -/** - * An icon app menu view which can be used in place of an IconView in overview TaskViews. - */ -public class IconAppChipView extends FrameLayout implements TaskViewIcon { - - private static final int MENU_BACKGROUND_REVEAL_DURATION = 417; - private static final int MENU_BACKGROUND_HIDE_DURATION = 333; - - private static final int NUM_ALPHA_CHANNELS = 4; - private static final int INDEX_CONTENT_ALPHA = 0; - private static final int INDEX_COLOR_FILTER_ALPHA = 1; - private static final int INDEX_MODAL_ALPHA = 2; - /** Used to hide the app chip for 90:10 flex split. */ - private static final int INDEX_MINIMUM_RATIO_ALPHA = 3; - - private final MultiValueAlpha mMultiValueAlpha; - - private View mMenuAnchorView; - private IconView mIconView; - // Two textview so we can ellipsize the collapsed view and crossfade on expand to the full name. - private TextView mIconTextCollapsedView; - private TextView mIconTextExpandedView; - private ImageView mIconArrowView; - private final Rect mBackgroundRelativeLtrLocation = new Rect(); - final RectEvaluator mBackgroundAnimationRectEvaluator = - new RectEvaluator(mBackgroundRelativeLtrLocation); - private final int mCollapsedMenuDefaultWidth; - private final int mExpandedMenuDefaultWidth; - private final int mCollapsedMenuDefaultHeight; - private final int mExpandedMenuDefaultHeight; - private final int mIconMenuMarginTopStart; - private final int mMenuToChipGap; - private final int mBackgroundMarginTopStart; - private final int mAppNameHorizontalMargin; - private final int mIconViewMarginStart; - private final int mAppIconSize; - private final int mArrowSize; - private final int mIconViewDrawableExpandedSize; - private final int mArrowMarginEnd; - private AnimatorSet mAnimator; - - private int mMaxWidth = Integer.MAX_VALUE; - - private static final int INDEX_SPLIT_TRANSLATION = 0; - private static final int INDEX_MENU_TRANSLATION = 1; - private static final int INDEX_COUNT_TRANSLATION = 2; - - private final MultiPropertyFactory mViewTranslationX; - private final MultiPropertyFactory mViewTranslationY; - - /** - * Gets the view split x-axis translation - */ - public MultiPropertyFactory.MultiProperty getSplitTranslationX() { - return mViewTranslationX.get(INDEX_SPLIT_TRANSLATION); - } - - /** - * Sets the view split x-axis translation - * @param translationX x-axis translation - */ - public void setSplitTranslationX(float translationX) { - getSplitTranslationX().setValue(translationX); - } - - /** - * Gets the view split y-axis translation - */ - public MultiPropertyFactory.MultiProperty getSplitTranslationY() { - return mViewTranslationY.get(INDEX_SPLIT_TRANSLATION); - } - - /** - * Sets the view split y-axis translation - * @param translationY y-axis translation - */ - public void setSplitTranslationY(float translationY) { - getSplitTranslationY().setValue(translationY); - } - - /** - * Gets the menu x-axis translation for split task - */ - public MultiPropertyFactory.MultiProperty getMenuTranslationX() { - return mViewTranslationX.get(INDEX_MENU_TRANSLATION); - } - - /** - * Gets the menu y-axis translation for split task - */ - public MultiPropertyFactory.MultiProperty getMenuTranslationY() { - return mViewTranslationY.get(INDEX_MENU_TRANSLATION); - } - - public IconAppChipView(Context context) { - this(context, null); - } - - public IconAppChipView(Context context, AttributeSet attrs) { - this(context, attrs, 0); - } - - public IconAppChipView(Context context, AttributeSet attrs, int defStyleAttr) { - this(context, attrs, defStyleAttr, 0); - } - - public IconAppChipView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, - int defStyleRes) { - super(context, attrs, defStyleAttr, defStyleRes); - Resources res = getResources(); - mMultiValueAlpha = new MultiValueAlpha(this, NUM_ALPHA_CHANNELS); - mMultiValueAlpha.setUpdateVisibility(/* updateVisibility= */ true); - - // Menu dimensions - mCollapsedMenuDefaultWidth = - res.getDimensionPixelSize(R.dimen.task_thumbnail_icon_menu_collapsed_width); - mExpandedMenuDefaultWidth = - res.getDimensionPixelSize(R.dimen.task_thumbnail_icon_menu_expanded_width); - mCollapsedMenuDefaultHeight = - res.getDimensionPixelSize(R.dimen.task_thumbnail_icon_menu_collapsed_height); - mExpandedMenuDefaultHeight = - res.getDimensionPixelSize(R.dimen.task_thumbnail_icon_menu_expanded_height); - mIconMenuMarginTopStart = res.getDimensionPixelSize( - R.dimen.task_thumbnail_icon_menu_expanded_top_start_margin); - mMenuToChipGap = res.getDimensionPixelSize( - R.dimen.task_thumbnail_icon_menu_expanded_gap); - - // Background dimensions - mBackgroundMarginTopStart = res.getDimensionPixelSize( - R.dimen.task_thumbnail_icon_menu_background_margin_top_start); - - // Contents dimensions - mAppNameHorizontalMargin = res.getDimensionPixelSize( - R.dimen.task_thumbnail_icon_menu_app_name_margin_horizontal_collapsed); - mArrowMarginEnd = res.getDimensionPixelSize(R.dimen.task_thumbnail_icon_menu_arrow_margin); - mIconViewMarginStart = res.getDimensionPixelSize( - R.dimen.task_thumbnail_icon_view_start_margin); - mAppIconSize = res.getDimensionPixelSize( - R.dimen.task_thumbnail_icon_menu_app_icon_collapsed_size); - mArrowSize = res.getDimensionPixelSize( - R.dimen.task_thumbnail_icon_menu_arrow_size); - mIconViewDrawableExpandedSize = res.getDimensionPixelSize( - R.dimen.task_thumbnail_icon_menu_app_icon_expanded_size); - - mViewTranslationX = new MultiPropertyFactory<>(this, VIEW_TRANSLATE_X, - INDEX_COUNT_TRANSLATION, - Float::sum); - mViewTranslationY = new MultiPropertyFactory<>(this, VIEW_TRANSLATE_Y, - INDEX_COUNT_TRANSLATION, - Float::sum); - } - - @Override - protected void onFinishInflate() { - super.onFinishInflate(); - mIconView = findViewById(R.id.icon_view); - mIconTextCollapsedView = findViewById(R.id.icon_text_collapsed); - mIconTextExpandedView = findViewById(R.id.icon_text_expanded); - mIconArrowView = findViewById(R.id.icon_arrow); - mMenuAnchorView = findViewById(R.id.icon_view_menu_anchor); - } - - protected IconView getIconView() { - return mIconView; - } - - @Override - public void setText(CharSequence text) { - if (mIconTextCollapsedView != null) { - mIconTextCollapsedView.setText(text); - } - if (mIconTextExpandedView != null) { - mIconTextExpandedView.setText(text); - } - } - - @Override - public Drawable getDrawable() { - return mIconView == null ? null : mIconView.getDrawable(); - } - - @Override - public void setDrawable(Drawable icon) { - if (mIconView != null) { - mIconView.setDrawable(icon); - } - } - - @Override - public void setDrawableSize(int iconWidth, int iconHeight) { - if (mIconView != null) { - mIconView.setDrawableSize(iconWidth, iconHeight); - } - } - - /** - * Sets the maximum width of this Icon Menu. This is usually used when space is limited for - * split screen. - */ - public void setMaxWidth(int maxWidth) { - // Width showing only the app icon and arrow. Max width should not be set to less than this. - int minimumMaxWidth = mIconViewMarginStart + mAppIconSize + mArrowSize + mArrowMarginEnd; - mMaxWidth = Math.max(maxWidth, minimumMaxWidth); - } - - @Override - public void setIconOrientation(RecentsOrientedState orientationState, boolean isGridTask) { - RecentsPagedOrientationHandler orientationHandler = - orientationState.getOrientationHandler(); - // Layout params for anchor view - LayoutParams anchorLayoutParams = (LayoutParams) mMenuAnchorView.getLayoutParams(); - anchorLayoutParams.topMargin = mExpandedMenuDefaultHeight + mMenuToChipGap; - mMenuAnchorView.setLayoutParams(anchorLayoutParams); - - // Layout Params for the Menu View (this) - LayoutParams iconMenuParams = (LayoutParams) getLayoutParams(); - iconMenuParams.width = mExpandedMenuDefaultWidth; - iconMenuParams.height = mExpandedMenuDefaultHeight; - orientationHandler.setIconAppChipMenuParams(this, iconMenuParams, mIconMenuMarginTopStart, - mIconMenuMarginTopStart); - setLayoutParams(iconMenuParams); - - // Layout params for the background - Rect collapsedBackgroundBounds = getCollapsedBackgroundLtrBounds(); - mBackgroundRelativeLtrLocation.set(collapsedBackgroundBounds); - setOutlineProvider(new ViewOutlineProvider() { - final Rect mRtlAppliedOutlineBounds = new Rect(); - @Override - public void getOutline(View view, Outline outline) { - mRtlAppliedOutlineBounds.set(mBackgroundRelativeLtrLocation); - if (isLayoutRtl()) { - int width = getWidth(); - mRtlAppliedOutlineBounds.left = width - mBackgroundRelativeLtrLocation.right; - mRtlAppliedOutlineBounds.right = width - mBackgroundRelativeLtrLocation.left; - } - outline.setRoundRect( - mRtlAppliedOutlineBounds, mRtlAppliedOutlineBounds.height() / 2f); - } - }); - - // Layout Params for the Icon View - LayoutParams iconParams = (LayoutParams) mIconView.getLayoutParams(); - int iconMarginStartRelativeToParent = mIconViewMarginStart + mBackgroundMarginTopStart; - orientationHandler.setIconAppChipChildrenParams( - iconParams, iconMarginStartRelativeToParent); - - mIconView.setLayoutParams(iconParams); - mIconView.setDrawableSize(mAppIconSize, mAppIconSize); - - // Layout Params for the collapsed Icon Text View - int textMarginStart = - iconMarginStartRelativeToParent + mAppIconSize + mAppNameHorizontalMargin; - LayoutParams iconTextCollapsedParams = - (LayoutParams) mIconTextCollapsedView.getLayoutParams(); - orientationHandler.setIconAppChipChildrenParams(iconTextCollapsedParams, textMarginStart); - int collapsedTextWidth = collapsedBackgroundBounds.width() - mIconViewMarginStart - - mAppIconSize - mArrowSize - mAppNameHorizontalMargin - mArrowMarginEnd; - iconTextCollapsedParams.width = collapsedTextWidth; - mIconTextCollapsedView.setLayoutParams(iconTextCollapsedParams); - mIconTextCollapsedView.setAlpha(1f); - - // Layout Params for the expanded Icon Text View - LayoutParams iconTextExpandedParams = - (LayoutParams) mIconTextExpandedView.getLayoutParams(); - orientationHandler.setIconAppChipChildrenParams(iconTextExpandedParams, textMarginStart); - mIconTextExpandedView.setLayoutParams(iconTextExpandedParams); - mIconTextExpandedView.setAlpha(0f); - mIconTextExpandedView.setRevealClip(true, 0, mAppIconSize / 2f, collapsedTextWidth); - - // Layout Params for the Icon Arrow View - LayoutParams iconArrowParams = (LayoutParams) mIconArrowView.getLayoutParams(); - int arrowMarginStart = collapsedBackgroundBounds.right - mArrowMarginEnd - mArrowSize; - orientationHandler.setIconAppChipChildrenParams(iconArrowParams, arrowMarginStart); - mIconArrowView.setPivotY(iconArrowParams.height / 2f); - mIconArrowView.setLayoutParams(iconArrowParams); - - // This method is called twice sometimes (like when rotating split tasks). It is called - // once before onMeasure and onLayout, and again after onMeasure but before onLayout with - // a new width. This happens because we update widths on rotation and on measure of - // grouped task views. Calling requestLayout() does not guarantee a call to onMeasure if - // it has just measured, so we explicitly call it here. - measure(MeasureSpec.makeMeasureSpec(getLayoutParams().width, MeasureSpec.EXACTLY), - MeasureSpec.makeMeasureSpec(getLayoutParams().height, MeasureSpec.EXACTLY)); - } - - @Override - public void setIconColorTint(int color, float amount) { - // RecentsView's COLOR_TINT animates between 0 and 0.5f, we want to hide the app chip menu. - float colorTintAlpha = Utilities.mapToRange(amount, 0f, 0.5f, 1f, 0f, LINEAR); - mMultiValueAlpha.get(INDEX_COLOR_FILTER_ALPHA).setValue(colorTintAlpha); - } - - @Override - public void setContentAlpha(float alpha) { - mMultiValueAlpha.get(INDEX_CONTENT_ALPHA).setValue(alpha); - } - - @Override - public void setModalAlpha(float alpha) { - mMultiValueAlpha.get(INDEX_MODAL_ALPHA).setValue(alpha); - } - - @Override - public void setFlexSplitAlpha(float alpha) { - mMultiValueAlpha.get(INDEX_MINIMUM_RATIO_ALPHA).setValue(alpha); - } - - @Override - public int getDrawableWidth() { - return mIconView == null ? 0 : mIconView.getDrawableWidth(); - } - - @Override - public int getDrawableHeight() { - return mIconView == null ? 0 : mIconView.getDrawableHeight(); - } - - protected void revealAnim(boolean isRevealing) { - cancelInProgressAnimations(); - final Rect collapsedBackgroundBounds = getCollapsedBackgroundLtrBounds(); - final Rect expandedBackgroundBounds = getExpandedBackgroundLtrBounds(); - final Rect initialBackground = new Rect(mBackgroundRelativeLtrLocation); - mAnimator = new AnimatorSet(); - - if (isRevealing) { - boolean isRtl = isLayoutRtl(); - bringToFront(); - // Clip expanded text with reveal animation so it doesn't go beyond the edge of the menu - Animator expandedTextRevealAnim = ViewAnimationUtils.createCircularReveal( - mIconTextExpandedView, 0, mIconTextExpandedView.getHeight() / 2, - mIconTextCollapsedView.getWidth(), mIconTextExpandedView.getWidth()); - // Animate background clipping - ValueAnimator backgroundAnimator = ValueAnimator.ofObject( - mBackgroundAnimationRectEvaluator, - initialBackground, - expandedBackgroundBounds); - backgroundAnimator.addUpdateListener(valueAnimator -> invalidateOutline()); - - float iconViewScaling = mIconViewDrawableExpandedSize / (float) mAppIconSize; - float arrowTranslationX = - expandedBackgroundBounds.right - collapsedBackgroundBounds.right; - float iconCenterToTextCollapsed = mAppIconSize / 2f + mAppNameHorizontalMargin; - float iconCenterToTextExpanded = - mIconViewDrawableExpandedSize / 2f + mAppNameHorizontalMargin; - float textTranslationX = iconCenterToTextExpanded - iconCenterToTextCollapsed; - - float textTranslationXWithRtl = isRtl ? -textTranslationX : textTranslationX; - float arrowTranslationWithRtl = isRtl ? -arrowTranslationX : arrowTranslationX; - - mAnimator.playTogether( - expandedTextRevealAnim, - backgroundAnimator, - ObjectAnimator.ofFloat(mIconView, SCALE_X, iconViewScaling), - ObjectAnimator.ofFloat(mIconView, SCALE_Y, iconViewScaling), - ObjectAnimator.ofFloat(mIconTextCollapsedView, TRANSLATION_X, - textTranslationXWithRtl), - ObjectAnimator.ofFloat(mIconTextExpandedView, TRANSLATION_X, - textTranslationXWithRtl), - ObjectAnimator.ofFloat(mIconTextCollapsedView, ALPHA, 0), - ObjectAnimator.ofFloat(mIconTextExpandedView, ALPHA, 1), - ObjectAnimator.ofFloat(mIconArrowView, TRANSLATION_X, arrowTranslationWithRtl), - ObjectAnimator.ofFloat(mIconArrowView, SCALE_Y, -1)); - mAnimator.setDuration(MENU_BACKGROUND_REVEAL_DURATION); - } else { - // Clip expanded text with reveal animation so it doesn't go beyond the edge of the menu - Animator expandedTextClipAnim = ViewAnimationUtils.createCircularReveal( - mIconTextExpandedView, 0, mIconTextExpandedView.getHeight() / 2, - mIconTextExpandedView.getWidth(), mIconTextCollapsedView.getWidth()); - - // Animate background clipping - ValueAnimator backgroundAnimator = ValueAnimator.ofObject( - mBackgroundAnimationRectEvaluator, - initialBackground, - collapsedBackgroundBounds); - backgroundAnimator.addUpdateListener(valueAnimator -> invalidateOutline()); - - mAnimator.playTogether( - expandedTextClipAnim, - backgroundAnimator, - ObjectAnimator.ofFloat(mIconView, SCALE_PROPERTY, 1), - ObjectAnimator.ofFloat(mIconTextCollapsedView, TRANSLATION_X, 0), - ObjectAnimator.ofFloat(mIconTextExpandedView, TRANSLATION_X, 0), - ObjectAnimator.ofFloat(mIconTextCollapsedView, ALPHA, 1), - ObjectAnimator.ofFloat(mIconTextExpandedView, ALPHA, 0), - ObjectAnimator.ofFloat(mIconArrowView, TRANSLATION_X, 0), - ObjectAnimator.ofFloat(mIconArrowView, SCALE_Y, 1)); - mAnimator.setDuration(MENU_BACKGROUND_HIDE_DURATION); - } - - mAnimator.setInterpolator(EMPHASIZED); - mAnimator.start(); - } - - private Rect getCollapsedBackgroundLtrBounds() { - Rect bounds = new Rect( - 0, - 0, - Math.min(mMaxWidth, mCollapsedMenuDefaultWidth), - mCollapsedMenuDefaultHeight); - bounds.offset(mBackgroundMarginTopStart, mBackgroundMarginTopStart); - return bounds; - } - - private Rect getExpandedBackgroundLtrBounds() { - return new Rect(0, 0, mExpandedMenuDefaultWidth, mExpandedMenuDefaultHeight); - } - - private void cancelInProgressAnimations() { - // We null the `AnimatorSet` because it holds references to the `Animators` which aren't - // expecting to be mutable and will cause a crash if they are re-used. - if (mAnimator != null && mAnimator.isStarted()) { - mAnimator.cancel(); - mAnimator = null; - } - } - - @Override - public View asView() { - return this; - } -} diff --git a/quickstep/src/com/android/quickstep/views/IconAppChipView.kt b/quickstep/src/com/android/quickstep/views/IconAppChipView.kt new file mode 100644 index 0000000000..85d14cc5ab --- /dev/null +++ b/quickstep/src/com/android/quickstep/views/IconAppChipView.kt @@ -0,0 +1,438 @@ +/* + * Copyright (C) 2023 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.views + +import android.animation.AnimatorSet +import android.animation.ObjectAnimator +import android.animation.RectEvaluator +import android.animation.ValueAnimator +import android.content.Context +import android.graphics.Outline +import android.graphics.Rect +import android.graphics.drawable.Drawable +import android.util.AttributeSet +import android.view.View +import android.view.ViewAnimationUtils +import android.view.ViewOutlineProvider +import android.widget.FrameLayout +import android.widget.ImageView +import android.widget.TextView +import com.android.app.animation.Interpolators +import com.android.launcher3.LauncherAnimUtils.SCALE_PROPERTY +import com.android.launcher3.LauncherAnimUtils.VIEW_TRANSLATE_X +import com.android.launcher3.LauncherAnimUtils.VIEW_TRANSLATE_Y +import com.android.launcher3.R +import com.android.launcher3.Utilities +import com.android.launcher3.util.MultiPropertyFactory +import com.android.launcher3.util.MultiPropertyFactory.FloatBiFunction +import com.android.launcher3.util.MultiValueAlpha +import com.android.quickstep.util.RecentsOrientedState +import kotlin.math.max +import kotlin.math.min + +/** An icon app menu view which can be used in place of an IconView in overview TaskViews. */ +class IconAppChipView +@JvmOverloads +constructor( + context: Context, + attrs: AttributeSet? = null, + defStyleAttr: Int = 0, + defStyleRes: Int = 0, +) : FrameLayout(context, attrs, defStyleAttr, defStyleRes), TaskViewIcon { + + private var iconView: IconView? = null + private var iconArrowView: ImageView? = null + private var menuAnchorView: View? = null + // Two textview so we can ellipsize the collapsed view and crossfade on expand to the full name. + private var iconTextCollapsedView: TextView? = null + private var iconTextExpandedView: TextView? = null + + private val backgroundRelativeLtrLocation = Rect() + private val backgroundAnimationRectEvaluator = RectEvaluator(backgroundRelativeLtrLocation) + + // Menu dimensions + private val collapsedMenuDefaultWidth: Int = + resources.getDimensionPixelSize(R.dimen.task_thumbnail_icon_menu_collapsed_width) + private val expandedMenuDefaultWidth: Int = + resources.getDimensionPixelSize(R.dimen.task_thumbnail_icon_menu_expanded_width) + private val collapsedMenuDefaultHeight = + resources.getDimensionPixelSize(R.dimen.task_thumbnail_icon_menu_collapsed_height) + private val expandedMenuDefaultHeight = + resources.getDimensionPixelSize(R.dimen.task_thumbnail_icon_menu_expanded_height) + private val iconMenuMarginTopStart = + resources.getDimensionPixelSize(R.dimen.task_thumbnail_icon_menu_expanded_top_start_margin) + private val menuToChipGap: Int = + resources.getDimensionPixelSize(R.dimen.task_thumbnail_icon_menu_expanded_gap) + + // Background dimensions + private val backgroundMarginTopStart: Int = + resources.getDimensionPixelSize( + R.dimen.task_thumbnail_icon_menu_background_margin_top_start + ) + + // Contents dimensions + private val appNameHorizontalMargin = + resources.getDimensionPixelSize( + R.dimen.task_thumbnail_icon_menu_app_name_margin_horizontal_collapsed + ) + private val arrowMarginEnd = + resources.getDimensionPixelSize(R.dimen.task_thumbnail_icon_menu_arrow_margin) + private val iconViewMarginStart = + resources.getDimensionPixelSize(R.dimen.task_thumbnail_icon_view_start_margin) + private val appIconSize = + resources.getDimensionPixelSize(R.dimen.task_thumbnail_icon_menu_app_icon_collapsed_size) + private val arrowSize = + resources.getDimensionPixelSize(R.dimen.task_thumbnail_icon_menu_arrow_size) + private val iconViewDrawableExpandedSize = + resources.getDimensionPixelSize(R.dimen.task_thumbnail_icon_menu_app_icon_expanded_size) + + private var animator: AnimatorSet? = null + + private val multiValueAlpha: MultiValueAlpha = + MultiValueAlpha(this, NUM_ALPHA_CHANNELS).apply { setUpdateVisibility(true) } + + private val viewTranslationX: MultiPropertyFactory = + MultiPropertyFactory(this, VIEW_TRANSLATE_X, INDEX_COUNT_TRANSLATION, SUM_AGGREGATOR) + + private val viewTranslationY: MultiPropertyFactory = + MultiPropertyFactory(this, VIEW_TRANSLATE_Y, INDEX_COUNT_TRANSLATION, SUM_AGGREGATOR) + + var maxWidth = Int.MAX_VALUE + /** + * Sets the maximum width of this Icon Menu. This is usually used when space is limited for + * split screen. + */ + set(value) { + // Width showing only the app icon and arrow. Max width should not be set to less than + // this. + val minMaxWidth = iconViewMarginStart + appIconSize + arrowSize + arrowMarginEnd + field = max(value, minMaxWidth) + } + + override fun onFinishInflate() { + super.onFinishInflate() + iconView = findViewById(R.id.icon_view) + iconTextCollapsedView = findViewById(R.id.icon_text_collapsed) + iconTextExpandedView = findViewById(R.id.icon_text_expanded) + iconArrowView = findViewById(R.id.icon_arrow) + menuAnchorView = findViewById(R.id.icon_view_menu_anchor) + } + + override fun setText(text: CharSequence?) { + iconTextCollapsedView?.text = text + iconTextExpandedView?.text = text + } + + override fun getDrawable(): Drawable? = iconView?.drawable + + override fun setDrawable(icon: Drawable?) { + iconView?.drawable = icon + } + + override fun setDrawableSize(iconWidth: Int, iconHeight: Int) { + iconView?.setDrawableSize(iconWidth, iconHeight) + } + + override fun setIconOrientation(orientationState: RecentsOrientedState, isGridTask: Boolean) { + val orientationHandler = orientationState.orientationHandler + // Layout params for anchor view + val anchorLayoutParams = menuAnchorView!!.layoutParams as LayoutParams + anchorLayoutParams.topMargin = expandedMenuDefaultHeight + menuToChipGap + menuAnchorView!!.layoutParams = anchorLayoutParams + + // Layout Params for the Menu View (this) + val iconMenuParams = layoutParams as LayoutParams + iconMenuParams.width = expandedMenuDefaultWidth + iconMenuParams.height = expandedMenuDefaultHeight + orientationHandler.setIconAppChipMenuParams( + this, + iconMenuParams, + iconMenuMarginTopStart, + iconMenuMarginTopStart, + ) + layoutParams = iconMenuParams + + // Layout params for the background + val collapsedBackgroundBounds = getCollapsedBackgroundLtrBounds() + backgroundRelativeLtrLocation.set(collapsedBackgroundBounds) + outlineProvider = + object : ViewOutlineProvider() { + val mRtlAppliedOutlineBounds: Rect = Rect() + + override fun getOutline(view: View, outline: Outline) { + mRtlAppliedOutlineBounds.set(backgroundRelativeLtrLocation) + if (isLayoutRtl) { + val width = width + mRtlAppliedOutlineBounds.left = width - backgroundRelativeLtrLocation.right + mRtlAppliedOutlineBounds.right = width - backgroundRelativeLtrLocation.left + } + outline.setRoundRect( + mRtlAppliedOutlineBounds, + mRtlAppliedOutlineBounds.height() / 2f, + ) + } + } + + // Layout Params for the Icon View + val iconParams = iconView!!.layoutParams as LayoutParams + val iconMarginStartRelativeToParent = iconViewMarginStart + backgroundMarginTopStart + orientationHandler.setIconAppChipChildrenParams(iconParams, iconMarginStartRelativeToParent) + + iconView!!.layoutParams = iconParams + iconView!!.setDrawableSize(appIconSize, appIconSize) + + // Layout Params for the collapsed Icon Text View + val textMarginStart = + iconMarginStartRelativeToParent + appIconSize + appNameHorizontalMargin + val iconTextCollapsedParams = iconTextCollapsedView!!.layoutParams as LayoutParams + orientationHandler.setIconAppChipChildrenParams(iconTextCollapsedParams, textMarginStart) + val collapsedTextWidth = + (collapsedBackgroundBounds.width() - + iconViewMarginStart - + appIconSize - + arrowSize - + appNameHorizontalMargin - + arrowMarginEnd) + iconTextCollapsedParams.width = collapsedTextWidth + iconTextCollapsedView!!.layoutParams = iconTextCollapsedParams + iconTextCollapsedView!!.alpha = 1f + + // Layout Params for the expanded Icon Text View + val iconTextExpandedParams = iconTextExpandedView!!.layoutParams as LayoutParams + orientationHandler.setIconAppChipChildrenParams(iconTextExpandedParams, textMarginStart) + iconTextExpandedView!!.layoutParams = iconTextExpandedParams + iconTextExpandedView!!.alpha = 0f + iconTextExpandedView!!.setRevealClip( + true, + 0f, + appIconSize / 2f, + collapsedTextWidth.toFloat(), + ) + + // Layout Params for the Icon Arrow View + val iconArrowParams = iconArrowView!!.layoutParams as LayoutParams + val arrowMarginStart = collapsedBackgroundBounds.right - arrowMarginEnd - arrowSize + orientationHandler.setIconAppChipChildrenParams(iconArrowParams, arrowMarginStart) + iconArrowView!!.pivotY = iconArrowParams.height / 2f + iconArrowView!!.layoutParams = iconArrowParams + + // This method is called twice sometimes (like when rotating split tasks). It is called + // once before onMeasure and onLayout, and again after onMeasure but before onLayout with + // a new width. This happens because we update widths on rotation and on measure of + // grouped task views. Calling requestLayout() does not guarantee a call to onMeasure if + // it has just measured, so we explicitly call it here. + measure( + MeasureSpec.makeMeasureSpec(layoutParams.width, MeasureSpec.EXACTLY), + MeasureSpec.makeMeasureSpec(layoutParams.height, MeasureSpec.EXACTLY), + ) + } + + override fun setIconColorTint(color: Int, amount: Float) { + // RecentsView's COLOR_TINT animates between 0 and 0.5f, we want to hide the app chip menu. + val colorTintAlpha = Utilities.mapToRange(amount, 0f, 0.5f, 1f, 0f, Interpolators.LINEAR) + multiValueAlpha[INDEX_COLOR_FILTER_ALPHA].value = colorTintAlpha + } + + override fun setContentAlpha(alpha: Float) { + multiValueAlpha[INDEX_CONTENT_ALPHA].value = alpha + } + + override fun setModalAlpha(alpha: Float) { + multiValueAlpha[INDEX_MODAL_ALPHA].value = alpha + } + + override fun setFlexSplitAlpha(alpha: Float) { + multiValueAlpha[INDEX_MINIMUM_RATIO_ALPHA].value = alpha + } + + override fun getDrawableWidth(): Int = iconView?.drawableWidth ?: 0 + + override fun getDrawableHeight(): Int = iconView?.drawableHeight ?: 0 + + /** Gets the view split x-axis translation */ + fun getSplitTranslationX(): MultiPropertyFactory.MultiProperty = + viewTranslationX.get(INDEX_SPLIT_TRANSLATION) + + /** + * Sets the view split x-axis translation + * + * @param value x-axis translation + */ + fun setSplitTranslationX(value: Float) { + getSplitTranslationX().value = value + } + + /** Gets the view split y-axis translation */ + fun getSplitTranslationY(): MultiPropertyFactory.MultiProperty = + viewTranslationY[INDEX_SPLIT_TRANSLATION] + + /** + * Sets the view split y-axis translation + * + * @param value y-axis translation + */ + fun setSplitTranslationY(value: Float) { + getSplitTranslationY().value = value + } + + /** Gets the menu x-axis translation for split task */ + fun getMenuTranslationX(): MultiPropertyFactory.MultiProperty = + viewTranslationX[INDEX_MENU_TRANSLATION] + + /** Gets the menu y-axis translation for split task */ + fun getMenuTranslationY(): MultiPropertyFactory.MultiProperty = + viewTranslationY[INDEX_MENU_TRANSLATION] + + internal fun revealAnim(isRevealing: Boolean) { + cancelInProgressAnimations() + val collapsedBackgroundBounds = getCollapsedBackgroundLtrBounds() + val expandedBackgroundBounds = getExpandedBackgroundLtrBounds() + val initialBackground = Rect(backgroundRelativeLtrLocation) + animator = AnimatorSet() + + if (isRevealing) { + val isRtl = isLayoutRtl + bringToFront() + // Clip expanded text with reveal animation so it doesn't go beyond the edge of the menu + val expandedTextRevealAnim = + ViewAnimationUtils.createCircularReveal( + iconTextExpandedView, + 0, + iconTextExpandedView!!.height / 2, + iconTextCollapsedView!!.width.toFloat(), + iconTextExpandedView!!.width.toFloat(), + ) + // Animate background clipping + val backgroundAnimator = + ValueAnimator.ofObject( + backgroundAnimationRectEvaluator, + initialBackground, + expandedBackgroundBounds, + ) + backgroundAnimator.addUpdateListener { invalidateOutline() } + + val iconViewScaling = iconViewDrawableExpandedSize / appIconSize.toFloat() + val arrowTranslationX = + (expandedBackgroundBounds.right - collapsedBackgroundBounds.right).toFloat() + val iconCenterToTextCollapsed = appIconSize / 2f + appNameHorizontalMargin + val iconCenterToTextExpanded = + iconViewDrawableExpandedSize / 2f + appNameHorizontalMargin + val textTranslationX = iconCenterToTextExpanded - iconCenterToTextCollapsed + + val textTranslationXWithRtl = if (isRtl) -textTranslationX else textTranslationX + val arrowTranslationWithRtl = if (isRtl) -arrowTranslationX else arrowTranslationX + + animator!!.playTogether( + expandedTextRevealAnim, + backgroundAnimator, + ObjectAnimator.ofFloat(iconView, SCALE_X, iconViewScaling), + ObjectAnimator.ofFloat(iconView, SCALE_Y, iconViewScaling), + ObjectAnimator.ofFloat( + iconTextCollapsedView, + TRANSLATION_X, + textTranslationXWithRtl, + ), + ObjectAnimator.ofFloat( + iconTextExpandedView, + TRANSLATION_X, + textTranslationXWithRtl, + ), + ObjectAnimator.ofFloat(iconTextCollapsedView, ALPHA, 0f), + ObjectAnimator.ofFloat(iconTextExpandedView, ALPHA, 1f), + ObjectAnimator.ofFloat(iconArrowView, TRANSLATION_X, arrowTranslationWithRtl), + ObjectAnimator.ofFloat(iconArrowView, SCALE_Y, -1f), + ) + animator!!.setDuration(MENU_BACKGROUND_REVEAL_DURATION.toLong()) + } else { + // Clip expanded text with reveal animation so it doesn't go beyond the edge of the menu + val expandedTextClipAnim = + ViewAnimationUtils.createCircularReveal( + iconTextExpandedView, + 0, + iconTextExpandedView!!.height / 2, + iconTextExpandedView!!.width.toFloat(), + iconTextCollapsedView!!.width.toFloat(), + ) + + // Animate background clipping + val backgroundAnimator = + ValueAnimator.ofObject( + backgroundAnimationRectEvaluator, + initialBackground, + collapsedBackgroundBounds, + ) + backgroundAnimator.addUpdateListener { valueAnimator: ValueAnimator? -> + invalidateOutline() + } + + animator!!.playTogether( + expandedTextClipAnim, + backgroundAnimator, + ObjectAnimator.ofFloat(iconView, SCALE_PROPERTY, 1f), + ObjectAnimator.ofFloat(iconTextCollapsedView, TRANSLATION_X, 0f), + ObjectAnimator.ofFloat(iconTextExpandedView, TRANSLATION_X, 0f), + ObjectAnimator.ofFloat(iconTextCollapsedView, ALPHA, 1f), + ObjectAnimator.ofFloat(iconTextExpandedView, ALPHA, 0f), + ObjectAnimator.ofFloat(iconArrowView, TRANSLATION_X, 0f), + ObjectAnimator.ofFloat(iconArrowView, SCALE_Y, 1f), + ) + animator!!.setDuration(MENU_BACKGROUND_HIDE_DURATION.toLong()) + } + + animator!!.interpolator = Interpolators.EMPHASIZED + animator!!.start() + } + + private fun getCollapsedBackgroundLtrBounds(): Rect { + val bounds = + Rect(0, 0, min(maxWidth, collapsedMenuDefaultWidth), collapsedMenuDefaultHeight) + bounds.offset(backgroundMarginTopStart, backgroundMarginTopStart) + return bounds + } + + private fun getExpandedBackgroundLtrBounds() = + Rect(0, 0, expandedMenuDefaultWidth, expandedMenuDefaultHeight) + + private fun cancelInProgressAnimations() { + // We null the `AnimatorSet` because it holds references to the `Animators` which aren't + // expecting to be mutable and will cause a crash if they are re-used. + if (animator != null && animator!!.isStarted) { + animator!!.cancel() + animator = null + } + } + + override fun asView(): View = this + + private companion object { + private val SUM_AGGREGATOR = FloatBiFunction { a: Float, b: Float -> a + b } + + private const val MENU_BACKGROUND_REVEAL_DURATION = 417 + private const val MENU_BACKGROUND_HIDE_DURATION = 333 + + private const val NUM_ALPHA_CHANNELS = 4 + private const val INDEX_CONTENT_ALPHA = 0 + private const val INDEX_COLOR_FILTER_ALPHA = 1 + private const val INDEX_MODAL_ALPHA = 2 + + /** Used to hide the app chip for 90:10 flex split. */ + private const val INDEX_MINIMUM_RATIO_ALPHA = 3 + + private const val INDEX_SPLIT_TRANSLATION = 0 + private const val INDEX_MENU_TRANSLATION = 1 + private const val INDEX_COUNT_TRANSLATION = 2 + } +} From a0f8368e2e83e67adaef08b0fa9778d3c66a9666 Mon Sep 17 00:00:00 2001 From: minch Date: Thu, 13 Feb 2025 21:27:40 +0000 Subject: [PATCH 009/153] Do not translate the AddDesktopButton on dismissing a TaskView Flag: com.android.window.flags.enable_multiple_desktops_frontend Flag: com.android.window.flags.enable_multiple_desktops_backend Bug: 391872496 Test: m Change-Id: I5b91ea1c419958b766db7da2f553f355a3817d2d --- quickstep/src/com/android/quickstep/views/RecentsView.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/quickstep/src/com/android/quickstep/views/RecentsView.java b/quickstep/src/com/android/quickstep/views/RecentsView.java index 424271a4c5..7a724d71d8 100644 --- a/quickstep/src/com/android/quickstep/views/RecentsView.java +++ b/quickstep/src/com/android/quickstep/views/RecentsView.java @@ -4346,6 +4346,11 @@ public abstract class RecentsView< PendingAnimation pendingAnimation, SplitAnimationTimings splitTimings, int index) { + // No need to translate the AddDesktopButton on dismissing a TaskView, which should be + // always at the right most position, even when dismissing the last TaskView. + if (view instanceof AddDesktopButton) { + return; + } FloatProperty translationProperty = view instanceof TaskView ? ((TaskView) view).getPrimaryDismissTranslationProperty() : getPagedOrientationHandler().getPrimaryViewTranslate(); From 7128c6fcfb54d5830700f1ffbe98ec90fc6aab8b Mon Sep 17 00:00:00 2001 From: Anushree Ganjam Date: Tue, 11 Feb 2025 17:15:31 -0800 Subject: [PATCH 010/153] Refactor TestEmitter and it doesn't need to be MainThreadInitializedObject Bug: 361850561 Test: Presubmit Flag: EXEMPT dagger Change-Id: I30e7c3c165db698785e9e4d7e2256ab061ff71a2 --- src/com/android/launcher3/Launcher.java | 4 +- src/com/android/launcher3/ModelCallbacks.kt | 4 +- src/com/android/launcher3/Workspace.java | 4 +- .../launcher3/debug/TestEventEmitter.java | 45 ++++++++++++++ .../debug/TestEventsEmitterProduction.kt | 59 ------------------- tests/Android.bp | 1 + ...mitterImplementation.kt => EventWaiter.kt} | 40 +------------ .../integrationtest/events/EventsRule.kt | 58 ++++++++++++++---- 8 files changed, 99 insertions(+), 116 deletions(-) create mode 100644 src/com/android/launcher3/debug/TestEventEmitter.java delete mode 100644 src/com/android/launcher3/debug/TestEventsEmitterProduction.kt rename tests/src/com/android/launcher3/celllayout/integrationtest/events/{TestEventsEmitterImplementation.kt => EventWaiter.kt} (58%) diff --git a/src/com/android/launcher3/Launcher.java b/src/com/android/launcher3/Launcher.java index 315301a9bb..db79662216 100644 --- a/src/com/android/launcher3/Launcher.java +++ b/src/com/android/launcher3/Launcher.java @@ -182,8 +182,8 @@ import com.android.launcher3.celllayout.CellPosMapper.CellPos; import com.android.launcher3.celllayout.CellPosMapper.TwoPanelCellPosMapper; import com.android.launcher3.compat.AccessibilityManagerCompat; import com.android.launcher3.config.FeatureFlags; -import com.android.launcher3.debug.TestEvent; import com.android.launcher3.debug.TestEventEmitter; +import com.android.launcher3.debug.TestEventEmitter.TestEvent; import com.android.launcher3.dot.DotInfo; import com.android.launcher3.dragndrop.DragController; import com.android.launcher3.dragndrop.DragLayer; @@ -610,7 +610,7 @@ public class Launcher extends StatefulActivity RuleController.getInstance(this).setRules( RuleController.parseRules(this, R.xml.split_configuration)); } - TestEventEmitter.INSTANCE.get(this).sendEvent(TestEvent.LAUNCHER_ON_CREATE); + TestEventEmitter.sendEvent(TestEvent.LAUNCHER_ON_CREATE); } protected ModelCallbacks createModelCallbacks() { diff --git a/src/com/android/launcher3/ModelCallbacks.kt b/src/com/android/launcher3/ModelCallbacks.kt index 5338fb435f..d01f35dc83 100644 --- a/src/com/android/launcher3/ModelCallbacks.kt +++ b/src/com/android/launcher3/ModelCallbacks.kt @@ -11,8 +11,8 @@ 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.TestEvent import com.android.launcher3.debug.TestEventEmitter +import com.android.launcher3.debug.TestEventEmitter.TestEvent import com.android.launcher3.model.BgDataModel import com.android.launcher3.model.StringCache import com.android.launcher3.model.data.AppInfo @@ -154,7 +154,7 @@ class ModelCallbacks(private var launcher: Launcher) : BgDataModel.Callbacks { /*pause=*/ false, deviceProfile.isTwoPanels, ) - TestEventEmitter.INSTANCE.get(launcher).sendEvent(TestEvent.WORKSPACE_FINISH_LOADING) + TestEventEmitter.sendEvent(TestEvent.WORKSPACE_FINISH_LOADING) } /** diff --git a/src/com/android/launcher3/Workspace.java b/src/com/android/launcher3/Workspace.java index b41a425846..cfb116147c 100644 --- a/src/com/android/launcher3/Workspace.java +++ b/src/com/android/launcher3/Workspace.java @@ -80,8 +80,8 @@ import com.android.launcher3.celllayout.CellLayoutLayoutParams; import com.android.launcher3.celllayout.CellPosMapper; import com.android.launcher3.celllayout.CellPosMapper.CellPos; import com.android.launcher3.config.FeatureFlags; -import com.android.launcher3.debug.TestEvent; import com.android.launcher3.debug.TestEventEmitter; +import com.android.launcher3.debug.TestEventEmitter.TestEvent; import com.android.launcher3.dot.FolderDotInfo; import com.android.launcher3.dragndrop.DragController; import com.android.launcher3.dragndrop.DragLayer; @@ -2255,7 +2255,7 @@ public class Workspace extends PagedView if (d.stateAnnouncer != null && !droppedOnOriginalCell) { d.stateAnnouncer.completeAction(R.string.item_moved); } - TestEventEmitter.INSTANCE.get(getContext()).sendEvent(TestEvent.WORKSPACE_ON_DROP); + TestEventEmitter.sendEvent(TestEvent.WORKSPACE_ON_DROP); } @Nullable diff --git a/src/com/android/launcher3/debug/TestEventEmitter.java b/src/com/android/launcher3/debug/TestEventEmitter.java new file mode 100644 index 0000000000..ed3b4bbac9 --- /dev/null +++ b/src/com/android/launcher3/debug/TestEventEmitter.java @@ -0,0 +1,45 @@ +/* + * 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.launcher3.debug; + +/** + * TestEventsEmitter shouldn't do anything since it runs on the launcher code and not on + * tests. This is just a placeholder and test should mock the static sendEvent method. + * See "EventsRule.kt" in tests folder where sendEvent is statically mocked to change the + * behavior in tests. + */ +public class TestEventEmitter { + public static void sendEvent(TestEvent event) { + } + + /** Events fired by the launcher. */ + public enum TestEvent { + + LAUNCHER_ON_CREATE("LAUNCHER_ON_CREATE"), + WORKSPACE_ON_DROP("WORKSPACE_ON_DROP"), + RESIZE_FRAME_SHOWING("RESIZE_FRAME_SHOWING"), + WORKSPACE_FINISH_LOADING("WORKSPACE_FINISH_LOADING"), + SPRING_LOADED_STATE_STARTED("SPRING_LOADED_STATE_STARTED"), + SPRING_LOADED_STATE_COMPLETED("SPRING_LOADED_STATE_COMPLETED"); + + TestEvent(String event) { + } + + } +} + + diff --git a/src/com/android/launcher3/debug/TestEventsEmitterProduction.kt b/src/com/android/launcher3/debug/TestEventsEmitterProduction.kt deleted file mode 100644 index 52b454f2b7..0000000000 --- a/src/com/android/launcher3/debug/TestEventsEmitterProduction.kt +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (C) 2024 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.launcher3.debug - -import android.content.Context -import android.util.Log -import com.android.launcher3.util.MainThreadInitializedObject -import com.android.launcher3.util.SafeCloseable - -/** Events fired by the launcher. */ -enum class TestEvent(val event: String) { - LAUNCHER_ON_CREATE("LAUNCHER_ON_CREATE"), - WORKSPACE_ON_DROP("WORKSPACE_ON_DROP"), - RESIZE_FRAME_SHOWING("RESIZE_FRAME_SHOWING"), - WORKSPACE_FINISH_LOADING("WORKSPACE_FINISH_LOADING"), - SPRING_LOADED_STATE_STARTED("SPRING_LOADED_STATE_STARTED"), - SPRING_LOADED_STATE_COMPLETED("SPRING_LOADED_STATE_COMPLETED"), -} - -/** Interface to create TestEventEmitters. */ -interface TestEventEmitter : SafeCloseable { - - companion object { - @JvmField - val INSTANCE = - MainThreadInitializedObject { _: Context? -> - TestEventsEmitterProduction() - } - } - - fun sendEvent(event: TestEvent) -} - -/** - * TestEventsEmitterProduction shouldn't do anything since it runs on the launcher code and not on - * tests. This is just a placeholder and test should override this class. - */ -class TestEventsEmitterProduction : TestEventEmitter { - - override fun close() {} - - override fun sendEvent(event: TestEvent) { - Log.d("TestEventsEmitterProduction", "Event sent ${event.event}") - } -} diff --git a/tests/Android.bp b/tests/Android.bp index 4bc654c7d0..fc08e86284 100644 --- a/tests/Android.bp +++ b/tests/Android.bp @@ -168,6 +168,7 @@ filegroup { "src/**/*Test.java", "src/**/*Test.kt", "src/**/RoboApiWrapper.kt", + "src/**/EventsRule.kt", "multivalentTests/src/**/*Test.java", "multivalentTests/src/**/*Test.kt", ], diff --git a/tests/src/com/android/launcher3/celllayout/integrationtest/events/TestEventsEmitterImplementation.kt b/tests/src/com/android/launcher3/celllayout/integrationtest/events/EventWaiter.kt similarity index 58% rename from tests/src/com/android/launcher3/celllayout/integrationtest/events/TestEventsEmitterImplementation.kt rename to tests/src/com/android/launcher3/celllayout/integrationtest/events/EventWaiter.kt index 5e062d0584..20ad60f11b 100644 --- a/tests/src/com/android/launcher3/celllayout/integrationtest/events/TestEventsEmitterImplementation.kt +++ b/tests/src/com/android/launcher3/celllayout/integrationtest/events/EventWaiter.kt @@ -16,9 +16,7 @@ package com.android.launcher3.celllayout.integrationtest.events -import android.util.Log -import com.android.launcher3.debug.TestEvent -import com.android.launcher3.debug.TestEventEmitter +import com.android.launcher3.debug.TestEventEmitter.TestEvent import java.util.concurrent.TimeUnit import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.runBlocking @@ -52,39 +50,3 @@ class EventWaiter(val eventToWait: TestEvent) { deferrable.complete(EventStatus.SUCCESS) } } - -class TestEventsEmitterImplementation() : TestEventEmitter { - companion object { - private const val TAG = "TestEvents" - } - - private val expectedEvents: ArrayDeque = ArrayDeque() - - fun createEventWaiter(expectedEvent: TestEvent): EventWaiter { - val eventWaiter = EventWaiter(expectedEvent) - expectedEvents.add(eventWaiter) - return eventWaiter - } - - private fun clearQueue() { - expectedEvents.clear() - } - - override fun sendEvent(event: TestEvent) { - Log.d(TAG, "Signal received $event") - Log.d(TAG, "Total expected events ${expectedEvents.size}") - if (expectedEvents.isEmpty()) return - val eventWaiter = expectedEvents.last() - if (eventWaiter.eventToWait == event) { - Log.d(TAG, "Removing $event") - expectedEvents.removeLast() - eventWaiter.terminate() - } else { - Log.d(TAG, "Not matching $event") - } - } - - override fun close() { - clearQueue() - } -} diff --git a/tests/src/com/android/launcher3/celllayout/integrationtest/events/EventsRule.kt b/tests/src/com/android/launcher3/celllayout/integrationtest/events/EventsRule.kt index fb61cedaa8..45eb5e1889 100644 --- a/tests/src/com/android/launcher3/celllayout/integrationtest/events/EventsRule.kt +++ b/tests/src/com/android/launcher3/celllayout/integrationtest/events/EventsRule.kt @@ -17,11 +17,15 @@ package com.android.launcher3.celllayout.integrationtest.events import android.content.Context -import com.android.launcher3.debug.TestEvent +import android.util.Log +import com.android.dx.mockito.inline.extended.ExtendedMockito.* +import com.android.dx.mockito.inline.extended.StaticMockitoSession import com.android.launcher3.debug.TestEventEmitter +import com.android.launcher3.debug.TestEventEmitter.TestEvent import org.junit.rules.TestRule import org.junit.runner.Description import org.junit.runners.model.Statement +import org.mockito.quality.Strictness /** * Rule to create EventWaiters to wait for events that happens on the Launcher. For reference look @@ -30,35 +34,65 @@ import org.junit.runners.model.Statement * Waiting for event should be used to prevent race conditions, it provides a more precise way of * waiting for events compared to [AbstractLauncherUiTest#waitForLauncherCondition]. * - * This class overrides the [TestEventEmitter] with [TestEventsEmitterImplementation] and makes sure - * to return the [TestEventEmitter] to the previous value when finished. + * This class mocks the static method [TestEventEmitter.sendEvent] */ class EventsRule(val context: Context) : TestRule { - private var prevEventEmitter: TestEventEmitter? = null + private val expectedEvents: ArrayDeque = ArrayDeque() - private val eventEmitter = TestEventsEmitterImplementation() + private lateinit var mockitoSession: StaticMockitoSession override fun apply(base: Statement, description: Description?): Statement { return object : Statement() { override fun evaluate() { - beforeTest() - base.evaluate() - afterTest() + try { + beforeTest() + base.evaluate() + } finally { + afterTest() + } } } } fun createEventWaiter(expectedEvent: TestEvent): EventWaiter { - return eventEmitter.createEventWaiter(expectedEvent) + val eventWaiter = EventWaiter(expectedEvent) + expectedEvents.add(eventWaiter) + return eventWaiter } private fun beforeTest() { - prevEventEmitter = TestEventEmitter.INSTANCE.get(context) - TestEventEmitter.INSTANCE.initializeForTesting(eventEmitter) + mockitoSession = + mockitoSession() + .strictness(Strictness.LENIENT) + .spyStatic(TestEventEmitter::class.java) + .startMocking() + + doAnswer { invocation -> + val event = (invocation.arguments[0] as TestEvent) + Log.d(TAG, "Signal received $event") + Log.d(TAG, "Total expected events ${expectedEvents.size}") + if (!expectedEvents.isEmpty()) { + val eventWaiter = expectedEvents.last() + if (eventWaiter.eventToWait == event) { + Log.d(TAG, "Removing $event") + expectedEvents.removeLast() + eventWaiter.terminate() + } else { + Log.d(TAG, "Not matching $event") + } + } + null + } + .`when` { TestEventEmitter.sendEvent(any()) } } private fun afterTest() { - TestEventEmitter.INSTANCE.initializeForTesting(prevEventEmitter) + mockitoSession.finishMocking() + expectedEvents.clear() + } + + companion object { + private const val TAG = "TestEvents" } } From 29f9c3d231e15131248ce78083e8db462048f1be Mon Sep 17 00:00:00 2001 From: Sunny Goyal Date: Thu, 13 Feb 2025 22:02:30 -0800 Subject: [PATCH 011/153] Merging IconShape with ThemeManager The order of initialization for IconShape is closely tied to ThemeManager which makes it difficult for change listeners to work. Merging these keeps all the theming information at one place Bug: 381897614 Test: Updated tests Flag: EXEMPT refactor Change-Id: Ie29efa20c3308a24be3e284c1c93ed7444b68d58 --- .../uioverrides/PredictedAppIcon.java | 4 +- src/com/android/launcher3/BubbleTextView.java | 6 +- src/com/android/launcher3/DeviceProfile.java | 20 ++-- .../launcher3/InvariantDeviceProfile.java | 10 +- .../dagger/LauncherBaseAppComponent.java | 2 - .../android/launcher3/dragndrop/DragView.java | 6 +- .../folder/FolderAnimationManager.java | 6 +- .../launcher3/folder/PreviewBackground.java | 6 +- .../graphics/PreloadIconDrawable.java | 2 +- .../{IconShape.kt => ShapeDelegate.kt} | 99 +++++++------------ .../launcher3/graphics/ThemeManager.kt | 37 +++++-- .../launcher3/icons/LauncherIconProvider.java | 10 +- .../android/launcher3/icons/LauncherIcons.kt | 6 +- .../android/launcher3/views/ClipIconView.java | 7 +- .../FakeInvariantDeviceProfileTest.kt | 2 +- ...{IconShapeTest.kt => ShapeDelegateTest.kt} | 16 +-- .../launcher3/shapes/ShapesProviderTest.kt | 2 +- 17 files changed, 116 insertions(+), 125 deletions(-) rename src/com/android/launcher3/graphics/{IconShape.kt => ShapeDelegate.kt} (81%) rename tests/multivalentTests/src/com/android/launcher3/graphics/{IconShapeTest.kt => ShapeDelegateTest.kt} (93%) diff --git a/quickstep/src/com/android/launcher3/uioverrides/PredictedAppIcon.java b/quickstep/src/com/android/launcher3/uioverrides/PredictedAppIcon.java index b25f99905d..37b8dc7bd8 100644 --- a/quickstep/src/com/android/launcher3/uioverrides/PredictedAppIcon.java +++ b/quickstep/src/com/android/launcher3/uioverrides/PredictedAppIcon.java @@ -51,7 +51,7 @@ import com.android.launcher3.anim.AnimatedFloat; import com.android.launcher3.anim.AnimatorListeners; import com.android.launcher3.celllayout.CellLayoutLayoutParams; import com.android.launcher3.celllayout.DelegatedCellDrawing; -import com.android.launcher3.graphics.IconShape; +import com.android.launcher3.graphics.ThemeManager; import com.android.launcher3.icons.FastBitmapDrawable; import com.android.launcher3.icons.IconNormalizer; import com.android.launcher3.icons.LauncherIcons; @@ -142,7 +142,7 @@ public class PredictedAppIcon extends DoubleShadowBubbleTextView { int shadowSize = context.getResources().getDimensionPixelSize( R.dimen.blur_size_thin_outline); mShadowFilter = new BlurMaskFilter(shadowSize, BlurMaskFilter.Blur.OUTER); - mShapePath = IconShape.INSTANCE.get(context).getShape().getPath(mNormalizedIconSize); + mShapePath = ThemeManager.INSTANCE.get(context).getIconShape().getPath(mNormalizedIconSize); } @Override diff --git a/src/com/android/launcher3/BubbleTextView.java b/src/com/android/launcher3/BubbleTextView.java index e6b34574a9..03dd943f50 100644 --- a/src/com/android/launcher3/BubbleTextView.java +++ b/src/com/android/launcher3/BubbleTextView.java @@ -75,8 +75,8 @@ import com.android.launcher3.dot.DotInfo; import com.android.launcher3.dragndrop.DragOptions.PreDragCondition; import com.android.launcher3.dragndrop.DraggableView; import com.android.launcher3.folder.FolderIcon; -import com.android.launcher3.graphics.IconShape; import com.android.launcher3.graphics.PreloadIconDrawable; +import com.android.launcher3.graphics.ShapeDelegate; import com.android.launcher3.icons.DotRenderer; import com.android.launcher3.icons.FastBitmapDrawable; import com.android.launcher3.icons.IconCache.ItemInfoUpdateReceiver; @@ -724,7 +724,7 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver, if (!mForceHideDot && (hasDot() || mDotParams.scale > 0)) { getIconBounds(mDotParams.iconBounds); Utilities.scaleRectAboutCenter(mDotParams.iconBounds, - IconShape.INSTANCE.get(getContext()).getNormalizationScale()); + ShapeDelegate.getNormalizationScale()); final int scrollX = getScrollX(); final int scrollY = getScrollY(); canvas.translate(scrollX, scrollY); @@ -775,7 +775,7 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver, getIconBounds(mRunningAppIconBounds); Utilities.scaleRectAboutCenter( mRunningAppIconBounds, - IconShape.INSTANCE.get(getContext()).getNormalizationScale()); + ShapeDelegate.getNormalizationScale()); final boolean isMinimized = mRunningAppState == RunningAppState.MINIMIZED; final int indicatorTop = mRunningAppIconBounds.bottom + mRunningAppIndicatorTopMargin; diff --git a/src/com/android/launcher3/DeviceProfile.java b/src/com/android/launcher3/DeviceProfile.java index 3b283c3cb0..f34add8d3f 100644 --- a/src/com/android/launcher3/DeviceProfile.java +++ b/src/com/android/launcher3/DeviceProfile.java @@ -52,7 +52,7 @@ import androidx.core.content.res.ResourcesCompat; import com.android.launcher3.CellLayout.ContainerType; import com.android.launcher3.DevicePaddings.DevicePadding; import com.android.launcher3.folder.ClippedFolderIconLayoutRule; -import com.android.launcher3.graphics.IconShape; +import com.android.launcher3.graphics.ThemeManager; import com.android.launcher3.icons.DotRenderer; import com.android.launcher3.icons.IconNormalizer; import com.android.launcher3.model.data.ItemInfo; @@ -388,7 +388,7 @@ public class DeviceProfile { /** TODO: Once we fully migrate to staged split, remove "isMultiWindowMode" */ DeviceProfile(Context context, InvariantDeviceProfile inv, Info info, - WindowManagerProxy wmProxy, IconShape iconShape, WindowBounds windowBounds, + WindowManagerProxy wmProxy, ThemeManager themeManager, WindowBounds windowBounds, SparseArray dotRendererCache, boolean isMultiWindowMode, boolean transposeLayoutWithOrientation, boolean isMultiDisplay, boolean isGestureMode, @NonNull final ViewScaleProvider viewScaleProvider, @@ -846,8 +846,8 @@ public class DeviceProfile { dimensionOverrideProvider.accept(this); // This is done last, after iconSizePx is calculated above. - mDotRendererWorkSpace = createDotRenderer(iconShape, iconSizePx, dotRendererCache); - mDotRendererAllApps = createDotRenderer(iconShape, allAppsIconSizePx, dotRendererCache); + mDotRendererWorkSpace = createDotRenderer(themeManager, iconSizePx, dotRendererCache); + mDotRendererAllApps = createDotRenderer(themeManager, allAppsIconSizePx, dotRendererCache); } /** @@ -869,12 +869,12 @@ public class DeviceProfile { } private static DotRenderer createDotRenderer( - @NonNull IconShape iconShape, int size, @NonNull SparseArray cache) { + @NonNull ThemeManager themeManager, int size, @NonNull SparseArray cache) { DotRenderer renderer = cache.get(size); if (renderer == null) { renderer = new DotRenderer( size, - iconShape.getShape().getPath(DEFAULT_DOT_SIZE), + themeManager.getIconShape().getPath(DEFAULT_DOT_SIZE), DEFAULT_DOT_SIZE); cache.put(size, renderer); } @@ -2478,7 +2478,7 @@ public class DeviceProfile { private final InvariantDeviceProfile mInv; private final Info mInfo; private final WindowManagerProxy mWMProxy; - private final IconShape mIconShape; + private final ThemeManager mThemeManager; private WindowBounds mWindowBounds; private boolean mIsMultiDisplay; @@ -2495,12 +2495,12 @@ public class DeviceProfile { private boolean mIsTransientTaskbar; public Builder(Context context, InvariantDeviceProfile inv, Info info, - WindowManagerProxy wmProxy, IconShape iconShape) { + WindowManagerProxy wmProxy, ThemeManager themeManager) { mContext = context; mInv = inv; mInfo = info; mWMProxy = wmProxy; - mIconShape = iconShape; + mThemeManager = themeManager; mIsTransientTaskbar = info.isTransientTaskbar(); } @@ -2581,7 +2581,7 @@ public class DeviceProfile { if (mOverrideProvider == null) { mOverrideProvider = DEFAULT_DIMENSION_PROVIDER; } - return new DeviceProfile(mContext, mInv, mInfo, mWMProxy, mIconShape, + return new DeviceProfile(mContext, mInv, mInfo, mWMProxy, mThemeManager, mWindowBounds, mDotRendererCache, mIsMultiWindowMode, mTransposeLayoutWithOrientation, mIsMultiDisplay, mIsGestureMode, mViewScaleProvider, mOverrideProvider, mIsTransientTaskbar); diff --git a/src/com/android/launcher3/InvariantDeviceProfile.java b/src/com/android/launcher3/InvariantDeviceProfile.java index 4107c8fdea..c2d6df52a3 100644 --- a/src/com/android/launcher3/InvariantDeviceProfile.java +++ b/src/com/android/launcher3/InvariantDeviceProfile.java @@ -57,7 +57,7 @@ import com.android.launcher3.config.FeatureFlags; import com.android.launcher3.dagger.ApplicationContext; import com.android.launcher3.dagger.LauncherAppComponent; import com.android.launcher3.dagger.LauncherAppSingleton; -import com.android.launcher3.graphics.IconShape; +import com.android.launcher3.graphics.ThemeManager; import com.android.launcher3.icons.DotRenderer; import com.android.launcher3.logging.FileLog; import com.android.launcher3.model.DeviceGridState; @@ -136,7 +136,7 @@ public class InvariantDeviceProfile { private final DisplayController mDisplayController; private final WindowManagerProxy mWMProxy; private final LauncherPrefs mPrefs; - private final IconShape mIconShape; + private final ThemeManager mThemeManager; /** * Number of icons per row and column in the workspace. @@ -260,12 +260,12 @@ public class InvariantDeviceProfile { LauncherPrefs prefs, DisplayController dc, WindowManagerProxy wmProxy, - IconShape iconShape, + ThemeManager themeManager, DaggerSingletonTracker lifeCycle) { mDisplayController = dc; mWMProxy = wmProxy; mPrefs = prefs; - mIconShape = iconShape; + mThemeManager = themeManager; String gridName = prefs.get(GRID_NAME); initGrid(context, gridName); @@ -490,7 +490,7 @@ public class InvariantDeviceProfile { } DeviceProfile.Builder newDPBuilder(Context context, Info info) { - return new DeviceProfile.Builder(context, this, info, mWMProxy, mIconShape); + return new DeviceProfile.Builder(context, this, info, mWMProxy, mThemeManager); } public void addOnChangeListener(OnIDPChangeListener listener) { diff --git a/src/com/android/launcher3/dagger/LauncherBaseAppComponent.java b/src/com/android/launcher3/dagger/LauncherBaseAppComponent.java index 35ae68f903..31d0da08db 100644 --- a/src/com/android/launcher3/dagger/LauncherBaseAppComponent.java +++ b/src/com/android/launcher3/dagger/LauncherBaseAppComponent.java @@ -20,7 +20,6 @@ import android.content.Context; import com.android.launcher3.InvariantDeviceProfile; import com.android.launcher3.LauncherPrefs; -import com.android.launcher3.graphics.IconShape; import com.android.launcher3.graphics.ThemeManager; import com.android.launcher3.icons.LauncherIcons.IconPool; import com.android.launcher3.model.ItemInstallQueue; @@ -57,7 +56,6 @@ public interface LauncherBaseAppComponent { ApiWrapper getApiWrapper(); CustomWidgetManager getCustomWidgetManager(); DynamicResource getDynamicResource(); - IconShape getIconShape(); InstallSessionHelper getInstallSessionHelper(); ItemInstallQueue getItemInstallQueue(); RefreshRateTracker getRefreshRateTracker(); diff --git a/src/com/android/launcher3/dragndrop/DragView.java b/src/com/android/launcher3/dragndrop/DragView.java index 072673d1ea..bff323ceb3 100644 --- a/src/com/android/launcher3/dragndrop/DragView.java +++ b/src/com/android/launcher3/dragndrop/DragView.java @@ -60,7 +60,7 @@ import androidx.dynamicanimation.animation.SpringForce; import com.android.app.animation.Interpolators; import com.android.launcher3.R; import com.android.launcher3.Utilities; -import com.android.launcher3.graphics.IconShape; +import com.android.launcher3.graphics.ThemeManager; import com.android.launcher3.icons.FastBitmapDrawable; import com.android.launcher3.icons.LauncherIcons; import com.android.launcher3.model.data.ItemInfo; @@ -274,9 +274,9 @@ public abstract class DragView extends Fram Utilities.scaleRectAboutCenter(shrunkBounds, 0.98f); adaptiveIcon.setBounds(shrunkBounds); - IconShape iconShape = IconShape.INSTANCE.get(getContext()); + ThemeManager themeManager = ThemeManager.INSTANCE.get(getContext()); final Path mask = (adaptiveIcon instanceof FolderAdaptiveIcon - ? iconShape.getFolderShape() : iconShape.getShape()) + ? themeManager.getFolderShape() : themeManager.getIconShape()) .getPath(shrunkBounds); mTranslateX = new SpringFloatValue(DragView.this, diff --git a/src/com/android/launcher3/folder/FolderAnimationManager.java b/src/com/android/launcher3/folder/FolderAnimationManager.java index 215761083b..d2354c18e1 100644 --- a/src/com/android/launcher3/folder/FolderAnimationManager.java +++ b/src/com/android/launcher3/folder/FolderAnimationManager.java @@ -46,8 +46,8 @@ import com.android.launcher3.Utilities; import com.android.launcher3.anim.PropertyResetListener; import com.android.launcher3.apppairs.AppPairIcon; import com.android.launcher3.celllayout.CellLayoutLayoutParams; -import com.android.launcher3.graphics.IconShape; -import com.android.launcher3.graphics.IconShape.ShapeDelegate; +import com.android.launcher3.graphics.ShapeDelegate; +import com.android.launcher3.graphics.ThemeManager; import com.android.launcher3.util.Themes; import com.android.launcher3.views.BaseDragLayer; @@ -237,7 +237,7 @@ public class FolderAnimationManager { } play(a, getAnimator(mFolder.mFooter, ALPHA, 0, 1f), footerStartDelay, footerAlphaDuration); - ShapeDelegate shapeDelegate = IconShape.INSTANCE.get(mContext).getFolderShape(); + ShapeDelegate shapeDelegate = ThemeManager.INSTANCE.get(mContext).getFolderShape(); // Create reveal animator for the folder background play(a, shapeDelegate.createRevealAnimator( mFolder, startRect, endRect, finalRadius, !mIsOpening)); diff --git a/src/com/android/launcher3/folder/PreviewBackground.java b/src/com/android/launcher3/folder/PreviewBackground.java index 77fa355803..ba8a290392 100644 --- a/src/com/android/launcher3/folder/PreviewBackground.java +++ b/src/com/android/launcher3/folder/PreviewBackground.java @@ -47,8 +47,8 @@ import com.android.launcher3.CellLayout; import com.android.launcher3.DeviceProfile; import com.android.launcher3.R; import com.android.launcher3.celllayout.DelegatedCellDrawing; -import com.android.launcher3.graphics.IconShape; -import com.android.launcher3.graphics.IconShape.ShapeDelegate; +import com.android.launcher3.graphics.ShapeDelegate; +import com.android.launcher3.graphics.ThemeManager; import com.android.launcher3.util.Themes; import com.android.launcher3.views.ActivityContext; @@ -260,7 +260,7 @@ public class PreviewBackground extends DelegatedCellDrawing { } private ShapeDelegate getShape() { - return IconShape.INSTANCE.get(mContext).getFolderShape(); + return ThemeManager.INSTANCE.get(mContext).getFolderShape(); } public void drawShadow(Canvas canvas) { diff --git a/src/com/android/launcher3/graphics/PreloadIconDrawable.java b/src/com/android/launcher3/graphics/PreloadIconDrawable.java index 50d6d1c4d6..3bd9fb54ca 100644 --- a/src/com/android/launcher3/graphics/PreloadIconDrawable.java +++ b/src/com/android/launcher3/graphics/PreloadIconDrawable.java @@ -119,7 +119,7 @@ public class PreloadIconDrawable extends FastBitmapDrawable { IconPalette.getPreloadProgressColor(context, info.bitmap.color), getPreloadColors(context), Utilities.isDarkTheme(context), - IconShape.INSTANCE.get(context).getShape().getPath(DEFAULT_PATH_SIZE) + ThemeManager.INSTANCE.get(context).getIconShape().getPath(DEFAULT_PATH_SIZE) ); } diff --git a/src/com/android/launcher3/graphics/IconShape.kt b/src/com/android/launcher3/graphics/ShapeDelegate.kt similarity index 81% rename from src/com/android/launcher3/graphics/IconShape.kt rename to src/com/android/launcher3/graphics/ShapeDelegate.kt index eac34406c2..df0c8f9aa6 100644 --- a/src/com/android/launcher3/graphics/IconShape.kt +++ b/src/com/android/launcher3/graphics/ShapeDelegate.kt @@ -42,78 +42,38 @@ import androidx.graphics.shapes.rectangle import androidx.graphics.shapes.toPath import androidx.graphics.shapes.transformed import com.android.launcher3.anim.RoundedRectRevealOutlineProvider -import com.android.launcher3.dagger.LauncherAppComponent -import com.android.launcher3.dagger.LauncherAppSingleton -import com.android.launcher3.graphics.ThemeManager.ThemeChangeListener import com.android.launcher3.icons.GraphicsUtils import com.android.launcher3.icons.IconNormalizer.normalizeAdaptiveIcon -import com.android.launcher3.util.DaggerSingletonObject -import com.android.launcher3.util.DaggerSingletonTracker import com.android.launcher3.views.ClipPathView -import javax.inject.Inject /** Abstract representation of the shape of an icon shape */ -@LauncherAppSingleton -class IconShape -@Inject -constructor(private val themeManager: ThemeManager, lifeCycle: DaggerSingletonTracker) { +interface ShapeDelegate { - val normalizationScale = - normalizeAdaptiveIcon( - AdaptiveIconDrawable(null, ColorDrawable(Color.BLACK)), - AREA_CALC_SIZE, - ) + fun getPath(pathSize: Float = DEFAULT_PATH_SIZE) = + Path().apply { addToPath(this, 0f, 0f, pathSize / 2) } - var shape: ShapeDelegate = pickBestShape(themeManager.iconState.iconMask) - private set - - var folderShape: ShapeDelegate = - themeManager.iconState.run { - if (folderShapeMask == iconMask || folderShapeMask.isEmpty()) shape - else pickBestShape(folderShapeMask) + fun getPath(bounds: Rect) = + Path().apply { + addToPath( + this, + bounds.left.toFloat(), + bounds.top.toFloat(), + // Radius is half of the average size of the icon + (bounds.width() + bounds.height()) / 4f, + ) } - private set - init { - val changeListener = ThemeChangeListener { - shape = pickBestShape(themeManager.iconState.iconMask) - folderShape = - themeManager.iconState.run { - if (folderShapeMask == iconMask || folderShapeMask.isEmpty()) shape - else pickBestShape(folderShapeMask) - } - } - themeManager.addChangeListener(changeListener) - lifeCycle.addCloseable { themeManager.removeChangeListener(changeListener) } - } + fun drawShape(canvas: Canvas, offsetX: Float, offsetY: Float, radius: Float, paint: Paint) - interface ShapeDelegate { - fun getPath(pathSize: Float = DEFAULT_PATH_SIZE) = - Path().apply { addToPath(this, 0f, 0f, pathSize / 2) } + fun addToPath(path: Path, offsetX: Float, offsetY: Float, radius: Float) - fun getPath(bounds: Rect) = - Path().apply { - addToPath( - this, - bounds.left.toFloat(), - bounds.top.toFloat(), - // Radius is half of the average size of the icon - (bounds.width() + bounds.height()) / 4f, - ) - } - - fun drawShape(canvas: Canvas, offsetX: Float, offsetY: Float, radius: Float, paint: Paint) - - fun addToPath(path: Path, offsetX: Float, offsetY: Float, radius: Float) - - fun createRevealAnimator( - target: T, - startRect: Rect, - endRect: Rect, - endRadius: Float, - isReversed: Boolean, - ): ValueAnimator where T : View, T : ClipPathView - } + fun createRevealAnimator( + target: T, + startRect: Rect, + endRect: Rect, + endRadius: Float, + isReversed: Boolean, + ): ValueAnimator where T : View, T : ClipPathView class Circle : RoundedSquare(1f) { @@ -179,10 +139,15 @@ constructor(private val themeManager: ThemeManager, lifeCycle: DaggerSingletonTr } .createRevealAnimator(target, isReversed) } + + override fun equals(other: Any?) = + other is RoundedSquare && other.radiusRatio == radiusRatio + + override fun hashCode() = radiusRatio.hashCode() } /** Generic shape delegate with pathString in bounds [0, 0, 100, 100] */ - class GenericPathShape(pathString: String) : ShapeDelegate { + data class GenericPathShape(private val pathString: String) : ShapeDelegate { private val poly = RoundedPolygon( features = SvgPathParser.parseFeatures(pathString), @@ -287,7 +252,6 @@ constructor(private val themeManager: ThemeManager, lifeCycle: DaggerSingletonTr } companion object { - @JvmField var INSTANCE = DaggerSingletonObject(LauncherAppComponent::getIconShape) const val TAG = "IconShape" const val DEFAULT_PATH_SIZE = 100f @@ -312,7 +276,6 @@ constructor(private val themeManager: ThemeManager, lifeCycle: DaggerSingletonTr } } - @VisibleForTesting fun pickBestShape(shapeStr: String): ShapeDelegate { val baseShape = if (shapeStr.isNotEmpty()) { @@ -332,7 +295,6 @@ constructor(private val themeManager: ThemeManager, lifeCycle: DaggerSingletonTr return pickBestShape(baseShape, shapeStr) } - @VisibleForTesting fun pickBestShape(baseShape: Path, shapeStr: String): ShapeDelegate { val calcAreaDiff = areaDiffCalculator(baseShape) @@ -380,5 +342,12 @@ constructor(private val themeManager: ThemeManager, lifeCycle: DaggerSingletonTr centerY = (bottom - top) / 2, rounding = CornerRounding(cornerR), ) + + @JvmStatic + val normalizationScale = + normalizeAdaptiveIcon( + AdaptiveIconDrawable(null, ColorDrawable(Color.BLACK)), + AREA_CALC_SIZE, + ) } } diff --git a/src/com/android/launcher3/graphics/ThemeManager.kt b/src/com/android/launcher3/graphics/ThemeManager.kt index e767290d8d..4a0ff8c58c 100644 --- a/src/com/android/launcher3/graphics/ThemeManager.kt +++ b/src/com/android/launcher3/graphics/ThemeManager.kt @@ -25,6 +25,7 @@ import com.android.launcher3.LauncherPrefs.Companion.backedUpItem import com.android.launcher3.dagger.ApplicationContext import com.android.launcher3.dagger.LauncherAppComponent import com.android.launcher3.dagger.LauncherAppSingleton +import com.android.launcher3.graphics.ShapeDelegate.Companion.pickBestShape import com.android.launcher3.icons.IconThemeController import com.android.launcher3.icons.mono.MonoIconThemeController import com.android.launcher3.shapes.ShapesProvider @@ -46,19 +47,25 @@ constructor( ) { /** Representation of the current icon state */ - var iconState = parseIconState() + var iconState = parseIconState(null) private set var isMonoThemeEnabled set(value) = prefs.put(THEMED_ICONS, value) get() = prefs.get(THEMED_ICONS) - val themeController: IconThemeController? + val themeController get() = iconState.themeController - val isIconThemeEnabled: Boolean + val isIconThemeEnabled get() = themeController != null + val iconShape + get() = iconState.iconShape + + val folderShape + get() = iconState.folderShape + private val listeners = CopyOnWriteArrayList() init { @@ -80,7 +87,7 @@ constructor( } protected fun verifyIconState() { - val newState = parseIconState() + val newState = parseIconState(iconState) if (newState == iconState) return iconState = newState @@ -91,7 +98,7 @@ constructor( fun removeChangeListener(listener: ThemeChangeListener) = listeners.remove(listener) - private fun parseIconState(): IconState { + private fun parseIconState(oldState: IconState?): IconState { val shapeModel = prefs.get(PREF_ICON_SHAPE).let { shapeOverride -> ShapesProvider.iconShapes.values.firstOrNull { it.key == shapeOverride } @@ -102,11 +109,27 @@ constructor( CONFIG_ICON_MASK_RES_ID == Resources.ID_NULL -> "" else -> context.resources.getString(CONFIG_ICON_MASK_RES_ID) } + + val iconShape = + if (oldState != null && oldState.iconMask == iconMask) oldState.iconShape + else pickBestShape(iconMask) + + val folderShapeMask = shapeModel?.folderPathString ?: iconMask + val folderShape = + when { + oldState != null && oldState.folderShapeMask == folderShapeMask -> + oldState.folderShape + folderShapeMask == iconMask || folderShapeMask.isEmpty() -> iconShape + else -> pickBestShape(folderShapeMask) + } + return IconState( iconMask = iconMask, - folderShapeMask = shapeModel?.folderPathString ?: iconMask, + folderShapeMask = folderShapeMask, themeController = createThemeController(), iconScale = shapeModel?.iconScale ?: 1f, + iconShape = iconShape, + folderShape = folderShape, ) } @@ -120,6 +143,8 @@ constructor( val themeController: IconThemeController?, val themeCode: String = themeController?.themeID ?: "no-theme", val iconScale: Float = 1f, + val iconShape: ShapeDelegate, + val folderShape: ShapeDelegate, ) { fun toUniqueId() = "${iconMask.hashCode()},$themeCode" } diff --git a/src/com/android/launcher3/icons/LauncherIconProvider.java b/src/com/android/launcher3/icons/LauncherIconProvider.java index 482360cb0b..836b7d1c00 100644 --- a/src/com/android/launcher3/icons/LauncherIconProvider.java +++ b/src/com/android/launcher3/icons/LauncherIconProvider.java @@ -30,7 +30,7 @@ import androidx.annotation.Nullable; import com.android.launcher3.R; import com.android.launcher3.config.FeatureFlags; -import com.android.launcher3.graphics.IconShape; +import com.android.launcher3.graphics.ShapeDelegate; import com.android.launcher3.graphics.ThemeManager; import com.android.launcher3.util.ApiWrapper; @@ -54,13 +54,13 @@ public class LauncherIconProvider extends IconProvider { private Map mThemedIconMap; private final ApiWrapper mApiWrapper; - private final IconShape mIconShape; + private final ThemeManager mThemeManager; public LauncherIconProvider(Context context) { super(context); - setIconThemeSupported(ThemeManager.INSTANCE.get(context).isMonoThemeEnabled()); + mThemeManager = ThemeManager.INSTANCE.get(context); mApiWrapper = ApiWrapper.INSTANCE.get(context); - mIconShape = IconShape.INSTANCE.get(context); + setIconThemeSupported(mThemeManager.isMonoThemeEnabled()); } /** @@ -91,7 +91,7 @@ public class LauncherIconProvider extends IconProvider { @Override protected Drawable loadAppInfoIcon(ApplicationInfo info, Resources resources, int density) { // Tries to load the round icon res, if the app defines it as an adaptive icon - if (mIconShape.getShape() instanceof IconShape.Circle) { + if (mThemeManager.getIconShape() instanceof ShapeDelegate.Circle) { int roundIconRes = mApiWrapper.getRoundIconRes(info); if (roundIconRes != 0 && roundIconRes != info.icon) { try { diff --git a/src/com/android/launcher3/icons/LauncherIcons.kt b/src/com/android/launcher3/icons/LauncherIcons.kt index d173fd657c..6c018e87eb 100644 --- a/src/com/android/launcher3/icons/LauncherIcons.kt +++ b/src/com/android/launcher3/icons/LauncherIcons.kt @@ -27,7 +27,6 @@ import com.android.launcher3.InvariantDeviceProfile import com.android.launcher3.dagger.ApplicationContext import com.android.launcher3.dagger.LauncherAppSingleton import com.android.launcher3.dagger.LauncherComponentProvider.appComponent -import com.android.launcher3.graphics.IconShape import com.android.launcher3.graphics.ThemeManager import com.android.launcher3.pm.UserCache import com.android.launcher3.util.UserIconInfo @@ -46,9 +45,8 @@ class LauncherIcons internal constructor( @ApplicationContext context: Context, idp: InvariantDeviceProfile, - themeManager: ThemeManager, + private var themeManager: ThemeManager, private var userCache: UserCache, - private var iconShape: IconShape, @Assisted private val pool: ConcurrentLinkedQueue, ) : BaseIconFactory(context, idp.fillResIconDpi, idp.iconBitmapSize), AutoCloseable { @@ -70,7 +68,7 @@ internal constructor( public override fun getShapePath(drawable: AdaptiveIconDrawable, iconBounds: Rect): Path { if (!Flags.enableLauncherIconShapes()) return drawable.iconMask - return iconShape.shape.getPath(iconBounds) + return themeManager.iconShape.getPath(iconBounds) } override fun drawAdaptiveIcon( diff --git a/src/com/android/launcher3/views/ClipIconView.java b/src/com/android/launcher3/views/ClipIconView.java index f90a3e4dd1..ddf18dfbaa 100644 --- a/src/com/android/launcher3/views/ClipIconView.java +++ b/src/com/android/launcher3/views/ClipIconView.java @@ -47,7 +47,8 @@ import com.android.launcher3.DeviceProfile; import com.android.launcher3.R; import com.android.launcher3.Utilities; import com.android.launcher3.dragndrop.FolderAdaptiveIcon; -import com.android.launcher3.graphics.IconShape; +import com.android.launcher3.graphics.ShapeDelegate; +import com.android.launcher3.graphics.ThemeManager; /** * A view used to draw both layers of an {@link AdaptiveIconDrawable}. @@ -174,7 +175,7 @@ public class ClipIconView extends View implements ClipPathView { if (mIsAdaptiveIcon) { if (!isOpening && progress >= shapeProgressStart) { if (mRevealAnimator == null) { - mRevealAnimator = IconShape.INSTANCE.get(getContext()).getShape() + mRevealAnimator = ThemeManager.INSTANCE.get(getContext()).getIconShape() .createRevealAnimator(this, mStartRevealRect, mOutline, mTaskCornerRadius, !isOpening); mRevealAnimator.addListener(forEndCallback(() -> mRevealAnimator = null)); @@ -259,7 +260,7 @@ public class ClipIconView extends View implements ClipPathView { if (!isFolderIcon) { Utilities.scaleRectAboutCenter(mStartRevealRect, - IconShape.INSTANCE.get(getContext()).getNormalizationScale()); + ShapeDelegate.getNormalizationScale()); } if (dp.isLandscape) { diff --git a/tests/multivalentTests/src/com/android/launcher3/FakeInvariantDeviceProfileTest.kt b/tests/multivalentTests/src/com/android/launcher3/FakeInvariantDeviceProfileTest.kt index 060c28c8e2..f855c51f8e 100644 --- a/tests/multivalentTests/src/com/android/launcher3/FakeInvariantDeviceProfileTest.kt +++ b/tests/multivalentTests/src/com/android/launcher3/FakeInvariantDeviceProfileTest.kt @@ -71,7 +71,7 @@ abstract class FakeInvariantDeviceProfileTest { inv, info, context.appComponent.wmProxy, - context.appComponent.iconShape, + context.appComponent.themeManager, windowBounds, SparseArray(), /*isMultiWindowMode=*/ false, diff --git a/tests/multivalentTests/src/com/android/launcher3/graphics/IconShapeTest.kt b/tests/multivalentTests/src/com/android/launcher3/graphics/ShapeDelegateTest.kt similarity index 93% rename from tests/multivalentTests/src/com/android/launcher3/graphics/IconShapeTest.kt rename to tests/multivalentTests/src/com/android/launcher3/graphics/ShapeDelegateTest.kt index 311676a34b..7e38f0e0ea 100644 --- a/tests/multivalentTests/src/com/android/launcher3/graphics/IconShapeTest.kt +++ b/tests/multivalentTests/src/com/android/launcher3/graphics/ShapeDelegateTest.kt @@ -28,13 +28,13 @@ import android.view.View import androidx.core.graphics.PathParser import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.SmallTest -import com.android.launcher3.graphics.IconShape.Circle -import com.android.launcher3.graphics.IconShape.Companion.AREA_CALC_SIZE -import com.android.launcher3.graphics.IconShape.Companion.AREA_DIFF_THRESHOLD -import com.android.launcher3.graphics.IconShape.Companion.areaDiffCalculator -import com.android.launcher3.graphics.IconShape.Companion.pickBestShape -import com.android.launcher3.graphics.IconShape.GenericPathShape -import com.android.launcher3.graphics.IconShape.RoundedSquare +import com.android.launcher3.graphics.ShapeDelegate.Circle +import com.android.launcher3.graphics.ShapeDelegate.Companion.AREA_CALC_SIZE +import com.android.launcher3.graphics.ShapeDelegate.Companion.AREA_DIFF_THRESHOLD +import com.android.launcher3.graphics.ShapeDelegate.Companion.areaDiffCalculator +import com.android.launcher3.graphics.ShapeDelegate.Companion.pickBestShape +import com.android.launcher3.graphics.ShapeDelegate.GenericPathShape +import com.android.launcher3.graphics.ShapeDelegate.RoundedSquare import com.android.launcher3.icons.GraphicsUtils import com.android.launcher3.views.ClipPathView import com.google.common.truth.Truth.assertThat @@ -43,7 +43,7 @@ import org.junit.runner.RunWith @SmallTest @RunWith(AndroidJUnit4::class) -class IconShapeTest { +class ShapeDelegateTest { @Test fun `areaDiffCalculator increases with outwards shape`() { diff --git a/tests/multivalentTests/src/com/android/launcher3/shapes/ShapesProviderTest.kt b/tests/multivalentTests/src/com/android/launcher3/shapes/ShapesProviderTest.kt index 2b8896ec9e..508c9a492d 100644 --- a/tests/multivalentTests/src/com/android/launcher3/shapes/ShapesProviderTest.kt +++ b/tests/multivalentTests/src/com/android/launcher3/shapes/ShapesProviderTest.kt @@ -22,7 +22,7 @@ import androidx.core.graphics.PathParser import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.SmallTest import com.android.launcher3.Flags.FLAG_ENABLE_LAUNCHER_ICON_SHAPES -import com.android.launcher3.graphics.IconShape.GenericPathShape +import com.android.launcher3.graphics.ShapeDelegate.GenericPathShape import com.android.systemui.shared.Flags.FLAG_NEW_CUSTOMIZATION_PICKER_UI import org.junit.Rule import org.junit.Test From edec1fbbfd7a50c6890c0a91fe2fdd9e5f6b4c24 Mon Sep 17 00:00:00 2001 From: Sukesh Ram Date: Tue, 11 Feb 2025 14:12:00 -0800 Subject: [PATCH 012/153] [CD Taskbar] Staging - Add/Remove Taskbars Tablet to Monitor connection renders Extended Mode. Test: Manual Bug: 390426030 Flag: com.android.window.flags.enable_taskbar_connected_displays Change-Id: I16e2e4911446c42d5351d7086154d6c720bca284 --- .../taskbar/TaskbarActivityContext.java | 7 +- .../launcher3/taskbar/TaskbarManager.java | 470 ++++++++++++------ .../uioverrides/QuickstepLauncher.java | 2 +- 3 files changed, 314 insertions(+), 165 deletions(-) diff --git a/quickstep/src/com/android/launcher3/taskbar/TaskbarActivityContext.java b/quickstep/src/com/android/launcher3/taskbar/TaskbarActivityContext.java index b9d1275f56..11cc22dfa9 100644 --- a/quickstep/src/com/android/launcher3/taskbar/TaskbarActivityContext.java +++ b/quickstep/src/com/android/launcher3/taskbar/TaskbarActivityContext.java @@ -47,7 +47,6 @@ import static com.android.quickstep.util.AnimUtils.completeRunnableListCallback; import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_NOTIFICATION_PANEL_VISIBLE; import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_VOICE_INTERACTION_WINDOW_SHOWING; import static com.android.window.flags.Flags.enableStartLaunchTransitionFromTaskbarBugfix; -import static com.android.window.flags.Flags.enableTaskbarConnectedDisplays; import static com.android.wm.shell.Flags.enableTinyTaskbar; import static java.lang.invoke.MethodHandles.Lookup.PROTECTED; @@ -77,6 +76,7 @@ import android.view.WindowInsets; import android.view.WindowManager; import android.widget.FrameLayout; import android.widget.Toast; +import android.window.DesktopExperienceFlags; import android.window.DesktopModeFlags; import android.window.RemoteTransition; @@ -434,8 +434,9 @@ public class TaskbarActivityContext extends BaseTaskbarContext { .setIsTransientTaskbar(true) .build(); } - mNavMode = (enableTaskbarConnectedDisplays() && !mIsPrimaryDisplay) - ? NavigationMode.THREE_BUTTONS : DisplayController.getNavigationMode(this); + mNavMode = (DesktopExperienceFlags.ENABLE_TASKBAR_CONNECTED_DISPLAYS.isTrue() + && !mIsPrimaryDisplay) ? NavigationMode.THREE_BUTTONS + : DisplayController.getNavigationMode(this); } diff --git a/quickstep/src/com/android/launcher3/taskbar/TaskbarManager.java b/quickstep/src/com/android/launcher3/taskbar/TaskbarManager.java index 96bcffd487..46802c3f9e 100644 --- a/quickstep/src/com/android/launcher3/taskbar/TaskbarManager.java +++ b/quickstep/src/com/android/launcher3/taskbar/TaskbarManager.java @@ -32,7 +32,6 @@ import static com.android.launcher3.util.Executors.UI_HELPER_EXECUTOR; import static com.android.launcher3.util.FlagDebugUtils.formatFlagChange; import static com.android.quickstep.util.SystemActionConstants.ACTION_SHOW_TASKBAR; import static com.android.quickstep.util.SystemActionConstants.SYSTEM_ACTION_ID_TASKBAR; -import static com.android.window.flags.Flags.enableTaskbarConnectedDisplays; import android.annotation.SuppressLint; import android.app.PendingIntent; @@ -53,6 +52,7 @@ import android.view.Display; import android.view.MotionEvent; import android.view.WindowManager; import android.widget.FrameLayout; +import android.window.DesktopExperienceFlags; import androidx.annotation.NonNull; import androidx.annotation.Nullable; @@ -118,11 +118,12 @@ public class TaskbarManager { Settings.Secure.NAV_BAR_KIDS_MODE); private final Context mBaseContext; + private TaskbarNavButtonCallbacks mNavCallbacks; // TODO: Remove this during the connected displays lifecycle refactor. private final Context mPrimaryWindowContext; private WindowManager mPrimaryWindowManager; - private final TaskbarNavButtonController mDefaultNavButtonController; - private final ComponentCallbacks mDefaultComponentCallbacks; + private TaskbarNavButtonController mPrimaryNavButtonController; + private ComponentCallbacks mPrimaryComponentCallbacks; private final SimpleBroadcastReceiver mShutdownReceiver; @@ -140,6 +141,11 @@ public class TaskbarManager { private final SparseArray mRootLayouts = new SparseArray<>(); /** DisplayId - {@link Boolean} map indicating if RootLayout was added to window. */ private final SparseBooleanArray mAddedRootLayouts = new SparseBooleanArray(); + /** DisplayId - {@link TaskbarNavButtonController} map for Connected Display. */ + private final SparseArray mNavButtonControllers = + new SparseArray<>(); + /** DisplayId - {@link ComponentCallbacks} map for Connected Display. */ + private final SparseArray mComponentCallbacks = new SparseArray<>(); private StatefulActivity mActivity; private RecentsViewContainer mRecentsViewContainer; @@ -158,27 +164,35 @@ public class TaskbarManager { private class RecreationListener implements DisplayController.DisplayInfoChangeListener { @Override public void onDisplayInfoChanged(Context context, DisplayController.Info info, int flags) { - if ((flags & CHANGE_DENSITY) != 0) { - Log.d(NULL_TASKBAR_ROOT_LAYOUT_TAG, "Display density changed"); + debugTaskbarManager("onDisplayInfoChanged - Display density changed", + context.getDisplayId()); } if ((flags & CHANGE_NAVIGATION_MODE) != 0) { - Log.d(NULL_TASKBAR_ROOT_LAYOUT_TAG, "Navigation mode changed"); + debugTaskbarManager("onDisplayInfoChanged - Navigation mode changed", + context.getDisplayId()); } if ((flags & CHANGE_DESKTOP_MODE) != 0) { - Log.d(NULL_TASKBAR_ROOT_LAYOUT_TAG, "Desktop mode changed"); + debugTaskbarManager("onDisplayInfoChanged - Desktop mode changed", + context.getDisplayId()); } if ((flags & CHANGE_TASKBAR_PINNING) != 0) { - Log.d(NULL_TASKBAR_ROOT_LAYOUT_TAG, "Taskbar pinning changed"); + debugTaskbarManager("onDisplayInfoChanged - Taskbar pinning changed", + context.getDisplayId()); } if ((flags & (CHANGE_DENSITY | CHANGE_NAVIGATION_MODE | CHANGE_DESKTOP_MODE | CHANGE_TASKBAR_PINNING)) != 0) { + debugTaskbarManager("onDisplayInfoChanged - Recreating Taskbar!", + context.getDisplayId()); recreateTaskbar(); } } } - private final SettingsCache.OnChangeListener mOnSettingsChangeListener = c -> recreateTaskbar(); + private final SettingsCache.OnChangeListener mOnSettingsChangeListener = c -> { + debugTaskbarManager("Settings changed! Recreating Taskbar!"); + recreateTaskbar(); + }; private boolean mUserUnlocked = false; @@ -191,6 +205,7 @@ public class TaskbarManager { @Override public void run() { int displayId = getDefaultDisplayId(); + debugTaskbarManager("mActivityOnDestroyCallback running!", displayId); if (mActivity != null) { displayId = mActivity.getDisplayId(); mActivity.removeOnDeviceProfileChangeListener( @@ -204,7 +219,6 @@ public class TaskbarManager { mRecentsViewContainer = null; } mActivity = null; - debugWhyTaskbarNotDestroyed("clearActivity"); TaskbarActivityContext taskbar = getTaskbarForDisplay(displayId); if (taskbar != null) { taskbar.setUIController(TaskbarUIController.DEFAULT); @@ -217,28 +231,27 @@ public class TaskbarManager { new UnfoldTransitionProgressProvider.TransitionProgressListener() { @Override public void onTransitionStarted() { - Log.d(TASKBAR_NOT_DESTROYED_TAG, - "fold/unfold transition started getting called."); + debugTaskbarManager("fold/unfold transition started getting called."); } @Override public void onTransitionProgress(float progress) { - Log.d(TASKBAR_NOT_DESTROYED_TAG, - "fold/unfold transition progress : " + progress); + debugTaskbarManager( + "fold/unfold transition progress getting called. | progress=" + + progress); } @Override public void onTransitionFinishing() { - Log.d(TASKBAR_NOT_DESTROYED_TAG, + debugTaskbarManager( "fold/unfold transition finishing getting called."); } @Override public void onTransitionFinished() { - Log.d(TASKBAR_NOT_DESTROYED_TAG, + debugTaskbarManager( "fold/unfold transition finished getting called."); - } }; @@ -250,20 +263,22 @@ public class TaskbarManager { RecentsDisplayModel recentsDisplayModel) { mBaseContext = context; mAllAppsActionManager = allAppsActionManager; + mNavCallbacks = navCallbacks; mRecentsDisplayModel = recentsDisplayModel; - mPrimaryWindowContext = createWindowContext(getDefaultDisplayId()); - if (enableTaskbarNoRecreate()) { - mPrimaryWindowManager = mPrimaryWindowContext.getSystemService(WindowManager.class); - createTaskbarRootLayout(getDefaultDisplayId()); - } - mDefaultNavButtonController = createDefaultNavButtonController(context, navCallbacks); - mDefaultComponentCallbacks = createDefaultComponentCallbacks(); + + // Set up primary display. + int primaryDisplayId = getDefaultDisplayId(); + debugTaskbarManager("TaskbarManager constructor", primaryDisplayId); + mPrimaryWindowContext = createWindowContext(primaryDisplayId); + mPrimaryWindowManager = mPrimaryWindowContext.getSystemService(WindowManager.class); + createTaskbarRootLayout(primaryDisplayId); + createNavButtonController(primaryDisplayId); + createAndRegisterComponentCallbacks(primaryDisplayId); + SettingsCache.INSTANCE.get(mPrimaryWindowContext) .register(USER_SETUP_COMPLETE_URI, mOnSettingsChangeListener); SettingsCache.INSTANCE.get(mPrimaryWindowContext) .register(NAV_BAR_KIDS_MODE, mOnSettingsChangeListener); - Log.d(TASKBAR_NOT_DESTROYED_TAG, "registering component callbacks from constructor."); - mPrimaryWindowContext.registerComponentCallbacks(mDefaultComponentCallbacks); mShutdownReceiver = new SimpleBroadcastReceiver( mPrimaryWindowContext, UI_HELPER_EXECUTOR, i -> destroyAllTaskbars()); @@ -281,82 +296,10 @@ public class TaskbarManager { mTaskbarBroadcastReceiver.register(RECEIVER_NOT_EXPORTED, ACTION_SHOW_TASKBAR); }); - debugWhyTaskbarNotDestroyed("TaskbarManager created"); + debugTaskbarManager("TaskbarManager created"); recreateTaskbar(); } - @NonNull - private TaskbarNavButtonController createDefaultNavButtonController(Context context, - TaskbarNavButtonCallbacks navCallbacks) { - return new TaskbarNavButtonController( - context, - navCallbacks, - SystemUiProxy.INSTANCE.get(mPrimaryWindowContext), - new Handler(), - new ContextualSearchInvoker(mPrimaryWindowContext)); - } - - private ComponentCallbacks createDefaultComponentCallbacks() { - return new ComponentCallbacks() { - private Configuration mOldConfig = - mPrimaryWindowContext.getResources().getConfiguration(); - - @Override - public void onConfigurationChanged(Configuration newConfig) { - Trace.instantForTrack(Trace.TRACE_TAG_APP, "TaskbarManager", - "onConfigurationChanged: " + newConfig); - debugWhyTaskbarNotDestroyed( - "TaskbarManager#mComponentCallbacks.onConfigurationChanged: " + newConfig); - // TODO: adapt this logic to be specific to different displays. - DeviceProfile dp = mUserUnlocked - ? LauncherAppState.getIDP(mPrimaryWindowContext).getDeviceProfile( - mPrimaryWindowContext) - : null; - int configDiff = mOldConfig.diff(newConfig) & ~SKIP_RECREATE_CONFIG_CHANGES; - - if ((configDiff & ActivityInfo.CONFIG_UI_MODE) != 0) { - Log.d(ILLEGAL_ARGUMENT_WM_ADD_VIEW, "onConfigurationChanged: theme changed"); - // Only recreate for theme changes, not other UI mode changes such as docking. - int oldUiNightMode = (mOldConfig.uiMode & Configuration.UI_MODE_NIGHT_MASK); - int newUiNightMode = (newConfig.uiMode & Configuration.UI_MODE_NIGHT_MASK); - if (oldUiNightMode == newUiNightMode) { - configDiff &= ~ActivityInfo.CONFIG_UI_MODE; - } - } - - debugWhyTaskbarNotDestroyed("ComponentCallbacks#onConfigurationChanged() " - + "configDiff=" + Configuration.configurationDiffToString(configDiff)); - if (configDiff != 0 || getCurrentActivityContext() == null) { - recreateTaskbar(); - } else { - // Config change might be handled without re-creating the taskbar - if (dp != null && !isTaskbarEnabled(dp)) { - destroyDefaultTaskbar(); - } else { - if (dp != null && isTaskbarEnabled(dp)) { - if (ENABLE_TASKBAR_NAVBAR_UNIFICATION) { - // Re-initialize for screen size change? Should this be done - // by looking at screen-size change flag in configDiff in the - // block above? - recreateTaskbar(); - } else { - getCurrentActivityContext().updateDeviceProfile(dp); - } - } - getCurrentActivityContext().onConfigurationChanged(configDiff); - } - } - mOldConfig = new Configuration(newConfig); - // reset taskbar was pinned value, so we don't automatically unstash taskbar upon - // user unfolding the device. - mSharedState.setTaskbarWasPinned(false); - } - - @Override - public void onLowMemory() { } - }; - } - private void destroyAllTaskbars() { for (int i = 0; i < mTaskbars.size(); i++) { int displayId = mTaskbars.keyAt(i); @@ -365,23 +308,18 @@ public class TaskbarManager { } } - private void destroyDefaultTaskbar() { - destroyTaskbarForDisplay(getDefaultDisplayId()); - } - private void destroyTaskbarForDisplay(int displayId) { Log.d(ILLEGAL_ARGUMENT_WM_ADD_VIEW, "destroyTaskbarForDisplay: " + displayId); TaskbarActivityContext taskbar = getTaskbarForDisplay(displayId); - debugWhyTaskbarNotDestroyed("destroyTaskbarForDisplay: " + taskbar, displayId); + debugTaskbarManager("destroyTaskbarForDisplay: " + taskbar, displayId); if (taskbar != null) { taskbar.onDestroy(); // remove all defaults that we store removeTaskbarFromMap(displayId); } - // make this display-specific - DeviceProfile dp = mUserUnlocked ? - LauncherAppState.getIDP(getWindowContext(displayId)).getDeviceProfile( - getWindowContext(displayId)) : null; + // TODO (b/381113004): make this display-specific via getWindowContext() + DeviceProfile dp = mUserUnlocked ? LauncherAppState.getIDP( + mPrimaryWindowContext).getDeviceProfile(mPrimaryWindowContext) : null; if (dp == null || !isTaskbarEnabled(dp)) { removeTaskbarRootViewFromWindow(displayId); } @@ -431,7 +369,10 @@ public class TaskbarManager { DisplayController.INSTANCE.get(mPrimaryWindowContext).addChangeListener( mRecreationListener); recreateTaskbar(); - addTaskbarRootViewToWindow(getDefaultDisplayId()); + for (int i = 0; i < mTaskbars.size(); i++) { + int displayId = mTaskbars.keyAt(i); + addTaskbarRootViewToWindow(displayId); + } } /** @@ -443,7 +384,7 @@ public class TaskbarManager { } removeActivityCallbacksAndListeners(); mActivity = activity; - debugWhyTaskbarNotDestroyed("Set mActivity=" + mActivity); + debugTaskbarManager("Set mActivity=" + mActivity); mActivity.addOnDeviceProfileChangeListener(mDebugActivityDeviceProfileChanged); Log.d(TASKBAR_NOT_DESTROYED_TAG, "registering activity lifecycle callbacks from setActivity()."); @@ -492,7 +433,7 @@ public class TaskbarManager { return ql.getUnfoldTransitionProgressProvider(); } } else { - return SystemUiProxy.INSTANCE.get(mPrimaryWindowContext).getUnfoldTransitionProvider(); + return SystemUiProxy.INSTANCE.get(mBaseContext).getUnfoldTransitionProvider(); } return null; } @@ -530,13 +471,21 @@ public class TaskbarManager { /** * This method is called multiple times (ex. initial init, then when user unlocks) in which case - * we fully want to destroy the existing default display's taskbar and create a new one. + * we fully want to destroy existing taskbars and create all desired new ones. * In other case (folding/unfolding) we don't need to remove and add window. */ @VisibleForTesting public synchronized void recreateTaskbar() { - // TODO: make this recreate all taskbars in map. - recreateTaskbarForDisplay(getDefaultDisplayId()); + // Handles initial creation case. + if (mTaskbars.size() == 0) { + recreateTaskbarForDisplay(getDefaultDisplayId()); + return; + } + + for (int i = 0; i < mTaskbars.size(); i++) { + int displayId = mTaskbars.keyAt(i); + recreateTaskbarForDisplay(displayId); + } } /** @@ -545,13 +494,12 @@ public class TaskbarManager { * In other case (folding/unfolding) we don't need to remove and add window. */ private void recreateTaskbarForDisplay(int displayId) { - Trace.beginSection("recreateTaskbar"); + Trace.beginSection("recreateTaskbarForDisplay"); try { Log.d(ILLEGAL_ARGUMENT_WM_ADD_VIEW, "recreateTaskbarForDisplay: " + displayId); - // TODO: make this code display specific - DeviceProfile dp = mUserUnlocked ? - LauncherAppState.getIDP(getWindowContext(displayId)).getDeviceProfile( - getWindowContext(displayId)) : null; + // TODO (b/381113004): make this display-specific via getWindowContext() + DeviceProfile dp = mUserUnlocked ? LauncherAppState.getIDP( + mPrimaryWindowContext).getDeviceProfile(mPrimaryWindowContext) : null; // All Apps action is unrelated to navbar unification, so we only need to check DP. final boolean isLargeScreenTaskbar = dp != null && dp.isTaskbarPresent; @@ -559,15 +507,17 @@ public class TaskbarManager { destroyTaskbarForDisplay(displayId); + boolean displayExists = getDisplay(displayId) != null; boolean isTaskbarEnabled = dp != null && isTaskbarEnabled(dp); - debugWhyTaskbarNotDestroyed("recreateTaskbar: isTaskbarEnabled=" + isTaskbarEnabled + debugTaskbarManager("recreateTaskbarForDisplay: isTaskbarEnabled=" + isTaskbarEnabled + " [dp != null (i.e. mUserUnlocked)]=" + (dp != null) + " FLAG_HIDE_NAVBAR_WINDOW=" + ENABLE_TASKBAR_NAVBAR_UNIFICATION - + " dp.isTaskbarPresent=" + (dp == null ? "null" : dp.isTaskbarPresent)); - if (!isTaskbarEnabled || !isLargeScreenTaskbar) { - SystemUiProxy.INSTANCE.get(mPrimaryWindowContext) + + " dp.isTaskbarPresent=" + (dp == null ? "null" : dp.isTaskbarPresent) + + " displayExists=" + displayExists); + if (!isTaskbarEnabled || !isLargeScreenTaskbar || !displayExists) { + SystemUiProxy.INSTANCE.get(mBaseContext) .notifyTaskbarStatus(/* visible */ false, /* stashed */ false); - if (!isTaskbarEnabled) { + if (!isTaskbarEnabled || !displayExists) { return; } } @@ -575,6 +525,11 @@ public class TaskbarManager { TaskbarActivityContext taskbar = getTaskbarForDisplay(displayId); if (enableTaskbarNoRecreate() || taskbar == null) { taskbar = createTaskbarActivityContext(dp, displayId); + if (taskbar == null) { + debugTaskbarManager( + "recreateTaskbarForDisplay: new taskbar instance is null!", displayId); + return; + } } else { taskbar.updateDeviceProfile(dp); } @@ -585,7 +540,8 @@ public class TaskbarManager { // Non default displays should not use LauncherTaskbarUIController as they shouldn't // have access to the Launcher activity. - if (enableTaskbarConnectedDisplays() && !isDefaultDisplay(displayId)) { + if (!isDefaultDisplay(displayId) + && DesktopExperienceFlags.ENABLE_TASKBAR_CONNECTED_DISPLAYS.isTrue()) { taskbar.setUIController(createTaskbarUIControllerForNonDefaultDisplay(displayId)); } else if (mRecentsViewContainer != null) { taskbar.setUIController( @@ -622,8 +578,8 @@ public class TaskbarManager { } public void onLongPressHomeEnabled(boolean assistantLongPressEnabled) { - if (mDefaultNavButtonController != null) { - mDefaultNavButtonController.setAssistantLongPressEnabled(assistantLongPressEnabled); + if (mPrimaryNavButtonController != null) { + mPrimaryNavButtonController.setAssistantLongPressEnabled(assistantLongPressEnabled); } } @@ -746,13 +702,26 @@ public class TaskbarManager { * primary device or a previously mirroring display is switched to extended mode. */ public void onDisplayAddSystemDecorations(int displayId) { - if (isDefaultDisplay(displayId) || !enableTaskbarConnectedDisplays()) { + Display display = getDisplay(displayId); + if (!DesktopExperienceFlags.ENABLE_TASKBAR_CONNECTED_DISPLAYS.isTrue() || isDefaultDisplay( + displayId) || display == null) { + debugTaskbarManager("onDisplayAddSystemDecorations: not adding display"); + return; + } + + // TODO (b/391965805): remove once onDisplayAddSystemDecorations is working. + WindowManager wm = getWindowManager(displayId); + if (wm == null || !wm.shouldShowSystemDecors(displayId)) { return; } Context newWindowContext = createWindowContext(displayId); if (newWindowContext != null) { addWindowContextToMap(displayId, newWindowContext); + createTaskbarRootLayout(displayId); + createNavButtonController(displayId); + createAndRegisterComponentCallbacks(displayId); + recreateTaskbarForDisplay(displayId); } } @@ -761,12 +730,16 @@ public class TaskbarManager { * removed from the primary device. */ public void onDisplayRemoved(int displayId) { - if (isDefaultDisplay(displayId) || !enableTaskbarConnectedDisplays()) { + if (!DesktopExperienceFlags.ENABLE_TASKBAR_CONNECTED_DISPLAYS.isTrue() || isDefaultDisplay( + displayId)) { return; } Context windowContext = getWindowContext(displayId); if (windowContext != null) { + removeNavButtonController(displayId); + removeAndUnregisterComponentCallbacks(displayId); + destroyTaskbarForDisplay(displayId); removeWindowContextFromMap(displayId); } } @@ -796,7 +769,7 @@ public class TaskbarManager { */ public void destroy() { mRecentsViewContainer = null; - debugWhyTaskbarNotDestroyed("TaskbarManager#destroy()"); + debugTaskbarManager("TaskbarManager#destroy()"); removeActivityCallbacksAndListeners(); mTaskbarBroadcastReceiver.unregisterReceiverSafely(); @@ -809,7 +782,7 @@ public class TaskbarManager { SettingsCache.INSTANCE.get(mPrimaryWindowContext) .unregister(NAV_BAR_KIDS_MODE, mOnSettingsChangeListener); Log.d(TASKBAR_NOT_DESTROYED_TAG, "unregistering component callbacks from destroy()."); - mPrimaryWindowContext.unregisterComponentCallbacks(mDefaultComponentCallbacks); + removeAndUnregisterComponentCallbacks(getDefaultDisplayId()); mShutdownReceiver.unregisterReceiverSafely(); destroyAllTaskbars(); } @@ -836,15 +809,20 @@ public class TaskbarManager { private void addTaskbarRootViewToWindow(int displayId) { TaskbarActivityContext taskbar = getTaskbarForDisplay(displayId); if (!enableTaskbarNoRecreate() || taskbar == null) { - Log.d(NULL_TASKBAR_ROOT_LAYOUT_TAG, - "addTaskbarRootViewToWindow - taskbar null | displayId=" + displayId); + debugTaskbarManager("addTaskbarRootViewToWindow - taskbar null", displayId); + return; + } + + if (getDisplay(displayId) == null) { + debugTaskbarManager("addTaskbarRootViewToWindow - display null", displayId); return; } if (!isTaskbarRootLayoutAddedForDisplay(displayId)) { FrameLayout rootLayout = getTaskbarRootLayoutForDisplay(displayId); - if (rootLayout != null) { - getWindowManager(displayId).addView(rootLayout, taskbar.getWindowLayoutParams()); + WindowManager windowManager = getWindowManager(displayId); + if (rootLayout != null && windowManager != null) { + windowManager.addView(rootLayout, taskbar.getWindowLayoutParams()); mAddedRootLayouts.put(displayId, true); } else { Log.d(ILLEGAL_ARGUMENT_WM_ADD_VIEW, @@ -864,10 +842,14 @@ public class TaskbarManager { return; } - if (isTaskbarRootLayoutAddedForDisplay(displayId)) { - getWindowManager(displayId).removeViewImmediate(rootLayout); + WindowManager windowManager = getWindowManager(displayId); + if (isTaskbarRootLayoutAddedForDisplay(displayId) && windowManager != null) { + windowManager.removeViewImmediate(rootLayout); mAddedRootLayouts.put(displayId, false); removeTaskbarRootLayoutFromMap(displayId); + } else { + debugTaskbarManager("removeTaskbarRootViewFromWindow - WindowManager is null", + displayId); } } @@ -913,23 +895,163 @@ public class TaskbarManager { /** * Creates a {@link TaskbarActivityContext} for the given display and adds it to the map. + * @param dp The {@link DeviceProfile} for the display. + * @param displayId The ID of the display. */ - private TaskbarActivityContext createTaskbarActivityContext(DeviceProfile dp, int displayId) { - Display display = mBaseContext.getSystemService(DisplayManager.class).getDisplay( - displayId); - Context navigationBarPanelContext = ENABLE_TASKBAR_NAVBAR_UNIFICATION - ? mBaseContext.createWindowContext(display, TYPE_NAVIGATION_BAR_PANEL, null) - : null; + private @Nullable TaskbarActivityContext createTaskbarActivityContext(DeviceProfile dp, + int displayId) { + Display display = getDisplay(displayId); + if (display == null) { + debugTaskbarManager("createTaskbarActivityContext: display null", displayId); + return null; + } + + Context navigationBarPanelContext = null; + if (ENABLE_TASKBAR_NAVBAR_UNIFICATION) { + navigationBarPanelContext = mBaseContext.createWindowContext(display, + TYPE_NAVIGATION_BAR_PANEL, null); + } + + boolean isPrimaryDisplay = isDefaultDisplay(displayId) + || !DesktopExperienceFlags.ENABLE_TASKBAR_CONNECTED_DISPLAYS.isTrue(); TaskbarActivityContext newTaskbar = new TaskbarActivityContext(getWindowContext(displayId), - navigationBarPanelContext, dp, mDefaultNavButtonController, - mUnfoldProgressProvider, isDefaultDisplay(displayId), - SystemUiProxy.INSTANCE.get(mPrimaryWindowContext)); + navigationBarPanelContext, dp, getNavButtonController(displayId), + mUnfoldProgressProvider, isPrimaryDisplay, + SystemUiProxy.INSTANCE.get(mBaseContext)); addTaskbarToMap(displayId, newTaskbar); return newTaskbar; } + /** + * Create {@link ComponentCallbacks} for the given display and register it to the relevant + * WindowContext. For external displays, populate maps. + * @param displayId The ID of the display. + */ + private void createAndRegisterComponentCallbacks(int displayId) { + ComponentCallbacks callbacks = new ComponentCallbacks() { + private Configuration mOldConfig = + getWindowContext(displayId).getResources().getConfiguration(); + + @Override + public void onConfigurationChanged(Configuration newConfig) { + Trace.instantForTrack(Trace.TRACE_TAG_APP, "TaskbarManager", + "onConfigurationChanged: " + newConfig); + debugTaskbarManager( + "TaskbarManager#mComponentCallbacks.onConfigurationChanged: " + newConfig); + // TODO (b/381113004): make this display-specific via getWindowContext() + DeviceProfile dp = mUserUnlocked ? LauncherAppState.getIDP( + mPrimaryWindowContext).getDeviceProfile(mPrimaryWindowContext) : null; + int configDiff = mOldConfig.diff(newConfig) & ~SKIP_RECREATE_CONFIG_CHANGES; + + if ((configDiff & ActivityInfo.CONFIG_UI_MODE) != 0) { + Log.d(ILLEGAL_ARGUMENT_WM_ADD_VIEW, "onConfigurationChanged: theme changed"); + // Only recreate for theme changes, not other UI mode changes such as docking. + int oldUiNightMode = (mOldConfig.uiMode & Configuration.UI_MODE_NIGHT_MASK); + int newUiNightMode = (newConfig.uiMode & Configuration.UI_MODE_NIGHT_MASK); + if (oldUiNightMode == newUiNightMode) { + configDiff &= ~ActivityInfo.CONFIG_UI_MODE; + } + } + + debugTaskbarManager("ComponentCallbacks#onConfigurationChanged() " + + "configDiff=" + Configuration.configurationDiffToString(configDiff)); + if (configDiff != 0 || getCurrentActivityContext() == null) { + recreateTaskbar(); + } else { + // Config change might be handled without re-creating the taskbar + if (dp != null && !isTaskbarEnabled(dp)) { + destroyTaskbarForDisplay(getDefaultDisplayId()); + } else { + if (dp != null && isTaskbarEnabled(dp)) { + if (ENABLE_TASKBAR_NAVBAR_UNIFICATION) { + // Re-initialize for screen size change? Should this be done + // by looking at screen-size change flag in configDiff in the + // block above? + recreateTaskbar(); + } else { + getCurrentActivityContext().updateDeviceProfile(dp); + } + } + getCurrentActivityContext().onConfigurationChanged(configDiff); + } + } + mOldConfig = new Configuration(newConfig); + // reset taskbar was pinned value, so we don't automatically unstash taskbar upon + // user unfolding the device. + mSharedState.setTaskbarWasPinned(false); + } + + @Override + public void onLowMemory() { } + }; + if (isDefaultDisplay(displayId) + || !DesktopExperienceFlags.ENABLE_TASKBAR_CONNECTED_DISPLAYS.isTrue()) { + mPrimaryComponentCallbacks = callbacks; + mPrimaryWindowContext.registerComponentCallbacks(callbacks); + } else { + mComponentCallbacks.put(displayId, callbacks); + getWindowContext(displayId).registerComponentCallbacks(callbacks); + } + } + + /** + * Unregister {@link ComponentCallbacks} for the given display from its WindowContext. For + * external displays, remove from the map. + * @param displayId The ID of the display. + */ + private void removeAndUnregisterComponentCallbacks(int displayId) { + if (isDefaultDisplay(displayId) + || !DesktopExperienceFlags.ENABLE_TASKBAR_CONNECTED_DISPLAYS.isTrue()) { + mPrimaryWindowContext.unregisterComponentCallbacks(mPrimaryComponentCallbacks); + } else { + ComponentCallbacks callbacks = mComponentCallbacks.get(displayId); + getWindowContext(displayId).unregisterComponentCallbacks(callbacks); + mComponentCallbacks.delete(displayId); + } + } + + /** + * Creates a {@link TaskbarNavButtonController} for the given display and adds it to the map + * if it doesn't already exist. + * @param displayId The ID of the display + */ + private void createNavButtonController(int displayId) { + if (isDefaultDisplay(displayId) + || !DesktopExperienceFlags.ENABLE_TASKBAR_CONNECTED_DISPLAYS.isTrue()) { + mPrimaryNavButtonController = new TaskbarNavButtonController( + mPrimaryWindowContext, + mNavCallbacks, + SystemUiProxy.INSTANCE.get(mBaseContext), + new Handler(), + new ContextualSearchInvoker(mBaseContext)); + } else { + TaskbarNavButtonController navButtonController = new TaskbarNavButtonController( + getWindowContext(displayId), + mNavCallbacks, + SystemUiProxy.INSTANCE.get(mBaseContext), + new Handler(), + new ContextualSearchInvoker(mBaseContext)); + mNavButtonControllers.put(displayId, navButtonController); + } + } + + private TaskbarNavButtonController getNavButtonController(int displayId) { + return (isDefaultDisplay(displayId) + || !DesktopExperienceFlags.ENABLE_TASKBAR_CONNECTED_DISPLAYS.isTrue()) + ? mPrimaryNavButtonController : mNavButtonControllers.get(displayId); + } + + private void removeNavButtonController(int displayId) { + if (isDefaultDisplay(displayId) + || !DesktopExperienceFlags.ENABLE_TASKBAR_CONNECTED_DISPLAYS.isTrue()) { + mPrimaryNavButtonController = null; + } else { + mNavButtonControllers.delete(displayId); + } + } + /** * Adds the {@link TaskbarActivityContext} associated with the given display ID to taskbar * map if there is not already a taskbar mapped to that displayId. @@ -958,12 +1080,16 @@ public class TaskbarManager { */ private void createTaskbarRootLayout(int displayId) { Log.d(ILLEGAL_ARGUMENT_WM_ADD_VIEW, "createTaskbarRootLayout: " + displayId); + if (!enableTaskbarNoRecreate()) { + return; + } + FrameLayout newTaskbarRootLayout = new FrameLayout(getWindowContext(displayId)) { @Override public boolean dispatchTouchEvent(MotionEvent ev) { // The motion events can be outside the view bounds of task bar, and hence // manually dispatching them to the drag layer here. - TaskbarActivityContext taskbar = getTaskbarForDisplay(getDefaultDisplayId()); + TaskbarActivityContext taskbar = getTaskbarForDisplay(displayId); if (taskbar != null && taskbar.getDragLayer().isAttachedToWindow()) { return taskbar.getDragLayer().dispatchTouchEvent(ev); } @@ -1029,13 +1155,10 @@ public class TaskbarManager { * @param displayId The ID of the display for which to create the window context. */ private @Nullable Context createWindowContext(int displayId) { - DisplayManager displayManager = mBaseContext.getSystemService(DisplayManager.class); - if (displayManager == null) { - return null; - } - - Display display = displayManager.getDisplay(displayId); + debugTaskbarManager("createWindowContext: " + displayId); + Display display = getDisplay(displayId); if (display == null) { + debugTaskbarManager("createWindowContext: display null", displayId); return null; } @@ -1043,10 +1166,29 @@ public class TaskbarManager { if (ENABLE_TASKBAR_NAVBAR_UNIFICATION && isDefaultDisplay(displayId)) { windowType = TYPE_NAVIGATION_BAR; } + debugTaskbarManager( + "createWindowContext: windowType=" + ((windowType == TYPE_NAVIGATION_BAR) + ? "TYPE_NAVIGATION_BAR" : "TYPE_NAVIGATION_BAR_PANEL"), displayId); return mBaseContext.createWindowContext(display, windowType, null); } + private @Nullable Display getDisplay(int displayId) { + DisplayManager displayManager = mBaseContext.getSystemService(DisplayManager.class); + if (displayManager == null) { + debugTaskbarManager("cannot get DisplayManager", displayId); + return null; + } + + Display display = displayManager.getDisplay(displayId); + if (display == null) { + debugTaskbarManager("Cannot get display!", displayId); + return null; + } + + return displayManager.getDisplay(displayId); + } + /** * Retrieves the window context of the taskbar for the specified display. * @@ -1054,7 +1196,8 @@ public class TaskbarManager { * @return The Window Context {@link Context} for a given display or {@code null}. */ private Context getWindowContext(int displayId) { - return (isDefaultDisplay(displayId) || !enableTaskbarConnectedDisplays()) + return (isDefaultDisplay(displayId) + || !DesktopExperienceFlags.ENABLE_TASKBAR_CONNECTED_DISPLAYS.isTrue()) ? mPrimaryWindowContext : mWindowContexts.get(displayId); } @@ -1070,12 +1213,15 @@ public class TaskbarManager { * @return The window manager {@link WindowManager} for a given display or {@code null}. */ private @Nullable WindowManager getWindowManager(int displayId) { - if (isDefaultDisplay(displayId) || !enableTaskbarConnectedDisplays()) { + if (isDefaultDisplay(displayId) + || !DesktopExperienceFlags.ENABLE_TASKBAR_CONNECTED_DISPLAYS.isTrue()) { + debugTaskbarManager("cannot get mPrimaryWindowManager", displayId); return mPrimaryWindowManager; } Context externalDisplayContext = getWindowContext(displayId); if (externalDisplayContext == null) { + debugTaskbarManager("cannot get externalDisplayContext", displayId); return null; } @@ -1110,18 +1256,20 @@ public class TaskbarManager { } /** Temp logs for b/254119092. */ - public void debugWhyTaskbarNotDestroyed(String debugReason) { - debugWhyTaskbarNotDestroyed(debugReason, getDefaultDisplayId()); + public void debugTaskbarManager(String debugReason) { + debugTaskbarManager(debugReason, getDefaultDisplayId()); } /** Temp logs for b/254119092. */ - public void debugWhyTaskbarNotDestroyed(String debugReason, int displayId) { + public void debugTaskbarManager(String debugReason, int displayId) { StringJoiner log = new StringJoiner("\n"); - log.add(debugReason + " displayId=" + displayId); + log.add(debugReason + " displayId=" + displayId + " isDefaultDisplay=" + isDefaultDisplay( + displayId)); boolean activityTaskbarPresent = mActivity != null && mActivity.getDeviceProfile().isTaskbarPresent; - Context windowContext = getWindowContext(displayId); + // TODO (b/381113004): make this display-specific via getWindowContext() + Context windowContext = mPrimaryWindowContext; if (windowContext == null) { log.add("window context for displayId" + displayId); return; @@ -1160,6 +1308,6 @@ public class TaskbarManager { } private final DeviceProfile.OnDeviceProfileChangeListener mDebugActivityDeviceProfileChanged = - dp -> debugWhyTaskbarNotDestroyed("mActivity onDeviceProfileChanged"); + dp -> debugTaskbarManager("mActivity onDeviceProfileChanged"); } diff --git a/quickstep/src/com/android/launcher3/uioverrides/QuickstepLauncher.java b/quickstep/src/com/android/launcher3/uioverrides/QuickstepLauncher.java index bb57d6eb74..019e7466dd 100644 --- a/quickstep/src/com/android/launcher3/uioverrides/QuickstepLauncher.java +++ b/quickstep/src/com/android/launcher3/uioverrides/QuickstepLauncher.java @@ -1380,7 +1380,7 @@ public class QuickstepLauncher extends Launcher implements RecentsViewContainer, SystemUiProxy.INSTANCE.get(this).setLauncherAppIconSize(mDeviceProfile.iconSizePx); TaskbarManager taskbarManager = mTISBindHelper.getTaskbarManager(); if (taskbarManager != null) { - taskbarManager.debugWhyTaskbarNotDestroyed("QuickstepLauncher#onDeviceProfileChanged"); + taskbarManager.debugTaskbarManager("QuickstepLauncher#onDeviceProfileChanged"); } } From 9c8926bff52c4ab2cf4ae3cf5b00bea180ff2345 Mon Sep 17 00:00:00 2001 From: Sergey Pinkevich Date: Mon, 3 Feb 2025 10:28:45 +0000 Subject: [PATCH 013/153] Open and close animation for trampoline task Moving most of the logic from DesktopAppLaunchTransition to DesktopAppLaunchAnimatorHelper to make it more testable Bug: 391548553 Flag: com.android.window.flags.enable_desktop_trampoline_close_animation_bugfix Test: DesktopAppLaunchAnimatorHelperTest Change-Id: I606fc3fc25250ea4128f3089b701a1ae153dc47a --- .../desktop/DesktopAppLaunchAnimatorHelper.kt | 192 ++++++++++++ .../desktop/DesktopAppLaunchTransition.kt | 98 +----- .../DesktopAppLaunchTransitionManager.kt | 2 +- .../KeyboardQuickSwitchViewController.java | 4 +- .../taskbar/TaskbarActivityContext.java | 4 +- .../DesktopAppLaunchAnimatorHelperTest.kt | 279 ++++++++++++++++++ 6 files changed, 489 insertions(+), 90 deletions(-) create mode 100644 quickstep/src/com/android/launcher3/desktop/DesktopAppLaunchAnimatorHelper.kt create mode 100644 quickstep/tests/src/com/android/quickstep/desktop/DesktopAppLaunchAnimatorHelperTest.kt diff --git a/quickstep/src/com/android/launcher3/desktop/DesktopAppLaunchAnimatorHelper.kt b/quickstep/src/com/android/launcher3/desktop/DesktopAppLaunchAnimatorHelper.kt new file mode 100644 index 0000000000..adbcc75728 --- /dev/null +++ b/quickstep/src/com/android/launcher3/desktop/DesktopAppLaunchAnimatorHelper.kt @@ -0,0 +1,192 @@ +/* + * 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.launcher3.desktop + +import android.animation.Animator +import android.animation.AnimatorSet +import android.animation.ValueAnimator +import android.content.Context +import android.graphics.Rect +import android.view.Choreographer +import android.view.SurfaceControl.Transaction +import android.view.WindowManager.TRANSIT_CLOSE +import android.view.WindowManager.TRANSIT_OPEN +import android.view.WindowManager.TRANSIT_TO_BACK +import android.window.DesktopModeFlags +import android.window.TransitionInfo +import android.window.TransitionInfo.Change +import androidx.core.animation.addListener +import androidx.core.util.Supplier +import com.android.app.animation.Interpolators +import com.android.internal.jank.Cuj +import com.android.internal.jank.InteractionJankMonitor +import com.android.internal.policy.ScreenDecorationsUtils +import com.android.launcher3.desktop.DesktopAppLaunchTransition.AppLaunchType +import com.android.launcher3.desktop.DesktopAppLaunchTransition.Companion.LAUNCH_CHANGE_MODES +import com.android.wm.shell.shared.animation.MinimizeAnimator +import com.android.wm.shell.shared.animation.WindowAnimator + +/** + * Helper class responsible for creating and managing animators for desktop app launch and related + * transitions. + * + *

This class handles the complex logic of creating various animators, including launch, + * minimize, and trampoline close animations, based on the provided transition information and + * launch type. It also utilizes {@link InteractionJankMonitor} to monitor animation jank. + * + * @param context The application context. + * @param launchType The type of app launch, containing animation parameters. + * @param cujType The CUJ (Critical User Journey) type for jank monitoring. + */ +class DesktopAppLaunchAnimatorHelper( + private val context: Context, + private val launchType: AppLaunchType, + @Cuj.CujType private val cujType: Int, + private val transactionSupplier: Supplier, +) { + + private val interactionJankMonitor = InteractionJankMonitor.getInstance() + + fun createAnimators(info: TransitionInfo, finishCallback: (Animator) -> Unit): List { + val launchChange = getLaunchChange(info) + requireNotNull(launchChange) { "expected an app launch Change" } + + val transaction = transactionSupplier.get() + + val minimizeChange = getMinimizeChange(info) + val trampolineCloseChange = getTrampolineCloseChange(info) + + val launchAnimator = + createLaunchAnimator( + launchChange, + transaction, + finishCallback, + isTrampoline = trampolineCloseChange != null, + ) + val animatorsList = mutableListOf(launchAnimator) + if (minimizeChange != null) { + val minimizeAnimator = + createMinimizeAnimator(minimizeChange, transaction, finishCallback) + animatorsList.add(minimizeAnimator) + } + if (trampolineCloseChange != null) { + val trampolineCloseAnimator = + createTrampolineCloseAnimator(trampolineCloseChange, transaction) + animatorsList.add(trampolineCloseAnimator) + } + return animatorsList + } + + private fun getLaunchChange(info: TransitionInfo): Change? = + info.changes.firstOrNull { change -> change.mode in LAUNCH_CHANGE_MODES } + + private fun getMinimizeChange(info: TransitionInfo): Change? = + info.changes.firstOrNull { change -> change.mode == TRANSIT_TO_BACK } + + private fun getTrampolineCloseChange(info: TransitionInfo): Change? { + if ( + info.changes.size < 2 || + !DesktopModeFlags.ENABLE_DESKTOP_TRAMPOLINE_CLOSE_ANIMATION_BUGFIX.isTrue + ) { + return null + } + val openChange = + info.changes.firstOrNull { change -> + change.mode == TRANSIT_OPEN && change.taskInfo?.isFreeform == true + } + val closeChange = + info.changes.firstOrNull { change -> + change.mode == TRANSIT_CLOSE && change.taskInfo?.isFreeform == true + } + val openPackage = openChange?.taskInfo?.baseIntent?.component?.packageName + val closePackage = closeChange?.taskInfo?.baseIntent?.component?.packageName + return if (openPackage != null && closePackage != null && openPackage == closePackage) { + closeChange + } else { + null + } + } + + private fun createLaunchAnimator( + change: Change, + transaction: Transaction, + onAnimFinish: (Animator) -> Unit, + isTrampoline: Boolean, + ): Animator { + val boundsAnimator = + WindowAnimator.createBoundsAnimator( + context.resources.displayMetrics, + launchType.boundsAnimationParams, + change, + transaction, + ) + val alphaAnimator = + ValueAnimator.ofFloat(0f, 1f).apply { + duration = launchType.alphaDurationMs + interpolator = Interpolators.LINEAR + addUpdateListener { animation -> + transaction + .setAlpha(change.leash, animation.animatedValue as Float) + .setFrameTimeline(Choreographer.getInstance().vsyncId) + .apply() + } + } + val clipRect = Rect(change.endAbsBounds).apply { offsetTo(0, 0) } + transaction.setCrop(change.leash, clipRect) + transaction.setCornerRadius( + change.leash, + ScreenDecorationsUtils.getWindowCornerRadius(context), + ) + return AnimatorSet().apply { + interactionJankMonitor.begin(change.leash, context, context.mainThreadHandler, cujType) + if (isTrampoline) { + play(alphaAnimator) + } else { + playTogether(boundsAnimator, alphaAnimator) + } + addListener( + onEnd = { animation -> + onAnimFinish(animation) + interactionJankMonitor.end(cujType) + } + ) + } + } + + private fun createMinimizeAnimator( + change: Change, + transaction: Transaction, + onAnimFinish: (Animator) -> Unit, + ): Animator { + return MinimizeAnimator.create( + context.resources.displayMetrics, + change, + transaction, + onAnimFinish, + ) + } + + private fun createTrampolineCloseAnimator(change: Change, transaction: Transaction): Animator { + return ValueAnimator.ofFloat(1f, 0f).apply { + duration = 100L + interpolator = Interpolators.LINEAR + addUpdateListener { animation -> + transaction.setAlpha(change.leash, animation.animatedValue as Float).apply() + } + } + } +} diff --git a/quickstep/src/com/android/launcher3/desktop/DesktopAppLaunchTransition.kt b/quickstep/src/com/android/launcher3/desktop/DesktopAppLaunchTransition.kt index 2406fb6620..578bba5c0d 100644 --- a/quickstep/src/com/android/launcher3/desktop/DesktopAppLaunchTransition.kt +++ b/quickstep/src/com/android/launcher3/desktop/DesktopAppLaunchTransition.kt @@ -17,27 +17,18 @@ package com.android.launcher3.desktop import android.animation.Animator -import android.animation.AnimatorSet -import android.animation.ValueAnimator import android.content.Context -import android.graphics.Rect import android.os.IBinder -import android.view.Choreographer import android.view.SurfaceControl.Transaction import android.view.WindowManager.TRANSIT_OPEN -import android.view.WindowManager.TRANSIT_TO_BACK import android.view.WindowManager.TRANSIT_TO_FRONT import android.window.IRemoteTransitionFinishedCallback import android.window.RemoteTransitionStub import android.window.TransitionInfo -import android.window.TransitionInfo.Change -import androidx.core.animation.addListener +import androidx.core.util.Supplier import com.android.app.animation.Interpolators import com.android.internal.jank.Cuj -import com.android.internal.jank.InteractionJankMonitor -import com.android.internal.policy.ScreenDecorationsUtils import com.android.quickstep.RemoteRunnable -import com.android.wm.shell.shared.animation.MinimizeAnimator import com.android.wm.shell.shared.animation.WindowAnimator import java.util.concurrent.Executor @@ -48,14 +39,18 @@ import java.util.concurrent.Executor * ([android.view.WindowManager.TRANSIT_TO_BACK]) this transition will apply a minimize animation to * that window. */ -class DesktopAppLaunchTransition( - private val context: Context, - private val mainExecutor: Executor, - private val launchType: AppLaunchType, +class DesktopAppLaunchTransition +@JvmOverloads +constructor( + context: Context, + launchType: AppLaunchType, @Cuj.CujType private val cujType: Int, + private val mainExecutor: Executor, + transactionSupplier: Supplier = Supplier { Transaction() }, ) : RemoteTransitionStub() { - private val interactionJankMonitor = InteractionJankMonitor.getInstance() + private val animatorHelper: DesktopAppLaunchAnimatorHelper = + DesktopAppLaunchAnimatorHelper(context, launchType, cujType, transactionSupplier) enum class AppLaunchType( val boundsAnimationParams: WindowAnimator.BoundsAnimationParams, @@ -68,7 +63,7 @@ class DesktopAppLaunchTransition( override fun startAnimation( token: IBinder, info: TransitionInfo, - t: Transaction, + transaction: Transaction, transitionFinishedCallback: IRemoteTransitionFinishedCallback, ) { val safeTransitionFinishedCallback = RemoteRunnable { @@ -76,7 +71,7 @@ class DesktopAppLaunchTransition( } mainExecutor.execute { runAnimators(info, safeTransitionFinishedCallback) - t.apply() + transaction.apply() } } @@ -86,77 +81,10 @@ class DesktopAppLaunchTransition( animators -= animator if (animators.isEmpty()) finishedCallback.run() } - animators += createAnimators(info, animatorFinishedCallback) + animators += animatorHelper.createAnimators(info, animatorFinishedCallback) animators.forEach { it.start() } } - private fun createAnimators( - info: TransitionInfo, - finishCallback: (Animator) -> Unit, - ): List { - val transaction = Transaction() - val launchAnimator = - createLaunchAnimator(getLaunchChange(info), transaction, finishCallback) - val minimizeChange = getMinimizeChange(info) ?: return listOf(launchAnimator) - val minimizeAnimator = - MinimizeAnimator.create( - context.resources.displayMetrics, - minimizeChange, - transaction, - finishCallback, - ) - return listOf(launchAnimator, minimizeAnimator) - } - - private fun getLaunchChange(info: TransitionInfo): Change = - requireNotNull(info.changes.firstOrNull { change -> change.mode in LAUNCH_CHANGE_MODES }) { - "expected an app launch Change" - } - - private fun getMinimizeChange(info: TransitionInfo): Change? = - info.changes.firstOrNull { change -> change.mode == TRANSIT_TO_BACK } - - private fun createLaunchAnimator( - change: Change, - transaction: Transaction, - onAnimFinish: (Animator) -> Unit, - ): Animator { - val boundsAnimator = - WindowAnimator.createBoundsAnimator( - context.resources.displayMetrics, - launchType.boundsAnimationParams, - change, - transaction, - ) - val alphaAnimator = - ValueAnimator.ofFloat(0f, 1f).apply { - duration = launchType.alphaDurationMs - interpolator = Interpolators.LINEAR - addUpdateListener { animation -> - transaction - .setAlpha(change.leash, animation.animatedValue as Float) - .setFrameTimeline(Choreographer.getInstance().vsyncId) - .apply() - } - } - val clipRect = Rect(change.endAbsBounds).apply { offsetTo(0, 0) } - transaction.setCrop(change.leash, clipRect) - transaction.setCornerRadius( - change.leash, - ScreenDecorationsUtils.getWindowCornerRadius(context), - ) - return AnimatorSet().apply { - interactionJankMonitor.begin(change.leash, context, context.mainThreadHandler, cujType) - playTogether(boundsAnimator, alphaAnimator) - addListener( - onEnd = { animation -> - onAnimFinish(animation) - interactionJankMonitor.end(cujType) - } - ) - } - } - companion object { /** Change modes that represent a task becoming visible / launching in Desktop mode. */ val LAUNCH_CHANGE_MODES = intArrayOf(TRANSIT_OPEN, TRANSIT_TO_FRONT) diff --git a/quickstep/src/com/android/launcher3/desktop/DesktopAppLaunchTransitionManager.kt b/quickstep/src/com/android/launcher3/desktop/DesktopAppLaunchTransitionManager.kt index 36c5fbad36..a72b5c43c5 100644 --- a/quickstep/src/com/android/launcher3/desktop/DesktopAppLaunchTransitionManager.kt +++ b/quickstep/src/com/android/launcher3/desktop/DesktopAppLaunchTransitionManager.kt @@ -48,9 +48,9 @@ class DesktopAppLaunchTransitionManager( RemoteTransition( DesktopAppLaunchTransition( context, - MAIN_EXECUTOR, AppLaunchType.UNMINIMIZE, Cuj.CUJ_DESKTOP_MODE_APP_LAUNCH_FROM_INTENT, + MAIN_EXECUTOR, ), "DesktopWindowLimitUnminimize", ) diff --git a/quickstep/src/com/android/launcher3/taskbar/KeyboardQuickSwitchViewController.java b/quickstep/src/com/android/launcher3/taskbar/KeyboardQuickSwitchViewController.java index 5af7ff8933..5f7a026469 100644 --- a/quickstep/src/com/android/launcher3/taskbar/KeyboardQuickSwitchViewController.java +++ b/quickstep/src/com/android/launcher3/taskbar/KeyboardQuickSwitchViewController.java @@ -290,9 +290,9 @@ public class KeyboardQuickSwitchViewController { remoteTransition = new RemoteTransition( new DesktopAppLaunchTransition( context, - MAIN_EXECUTOR, UNMINIMIZE, - Cuj.CUJ_DESKTOP_MODE_KEYBOARD_QUICK_SWITCH_APP_LAUNCH + Cuj.CUJ_DESKTOP_MODE_KEYBOARD_QUICK_SWITCH_APP_LAUNCH, + MAIN_EXECUTOR ), "DesktopKeyboardQuickSwitchUnminimize"); } diff --git a/quickstep/src/com/android/launcher3/taskbar/TaskbarActivityContext.java b/quickstep/src/com/android/launcher3/taskbar/TaskbarActivityContext.java index b9d1275f56..8c807ee84c 100644 --- a/quickstep/src/com/android/launcher3/taskbar/TaskbarActivityContext.java +++ b/quickstep/src/com/android/launcher3/taskbar/TaskbarActivityContext.java @@ -1533,9 +1533,9 @@ public class TaskbarActivityContext extends BaseTaskbarContext { return new RemoteTransition( new DesktopAppLaunchTransition( this, - getMainExecutor(), appLaunchType, - cujType + cujType, + getMainExecutor() ), "TaskbarDesktopAppLaunch"); } diff --git a/quickstep/tests/src/com/android/quickstep/desktop/DesktopAppLaunchAnimatorHelperTest.kt b/quickstep/tests/src/com/android/quickstep/desktop/DesktopAppLaunchAnimatorHelperTest.kt new file mode 100644 index 0000000000..b4d9f5b396 --- /dev/null +++ b/quickstep/tests/src/com/android/quickstep/desktop/DesktopAppLaunchAnimatorHelperTest.kt @@ -0,0 +1,279 @@ +/* + * 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.desktop + +import android.animation.Animator +import android.animation.AnimatorSet +import android.animation.ValueAnimator +import android.app.ActivityManager +import android.app.WindowConfiguration +import android.content.ComponentName +import android.content.Context +import android.content.Intent +import android.content.res.Resources +import android.platform.test.annotations.DisableFlags +import android.platform.test.annotations.EnableFlags +import android.platform.test.flag.junit.SetFlagsRule +import android.util.DisplayMetrics +import android.view.SurfaceControl +import android.view.WindowManager +import android.window.TransitionInfo +import androidx.core.util.Supplier +import com.android.app.animation.Interpolators +import com.android.internal.jank.Cuj +import com.android.launcher3.desktop.DesktopAppLaunchAnimatorHelper +import com.android.launcher3.desktop.DesktopAppLaunchTransition.AppLaunchType +import com.android.launcher3.util.Executors.MAIN_EXECUTOR +import com.android.window.flags.Flags +import com.google.common.truth.Truth.assertThat +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever + +class DesktopAppLaunchAnimatorHelperTest { + + @get:Rule val setFlagsRule = SetFlagsRule() + + private val context = mock() + private val resources = mock() + private val transaction = mock() + private val transactionSupplier = mock>() + + private lateinit var helper: DesktopAppLaunchAnimatorHelper + + @Before + fun setUp() { + helper = + DesktopAppLaunchAnimatorHelper( + context = context, + launchType = AppLaunchType.LAUNCH, + cujType = Cuj.CUJ_DESKTOP_MODE_APP_LAUNCH_FROM_INTENT, + transactionSupplier = transactionSupplier, + ) + whenever(transactionSupplier.get()).thenReturn(transaction) + whenever(transaction.setCrop(any(), any())).thenReturn(transaction) + whenever(transaction.setCornerRadius(any(), any())).thenReturn(transaction) + + whenever(context.resources).thenReturn(resources) + whenever(resources.displayMetrics).thenReturn(DisplayMetrics()) + whenever(context.mainThreadHandler).thenReturn(MAIN_EXECUTOR.handler) + } + + @Test + fun launchTransition_returnsLaunchAnimator() { + val openChange = + TransitionInfo.Change(mock(), mock()).apply { + mode = WindowManager.TRANSIT_OPEN + taskInfo = TASK_INFO_FREEFORM + } + val transitionInfo = TransitionInfo(WindowManager.TRANSIT_NONE, 0) + transitionInfo.addChange(openChange) + + val actual = helper.createAnimators(transitionInfo, finishCallback = {}) + + assertThat(actual).hasSize(1) + assertLaunchAnimator(actual[0]) + } + + @Test + fun minimizeTransition_returnsLaunchAndMinimizeAnimator() { + val openChange = + TransitionInfo.Change(mock(), mock()).apply { + mode = WindowManager.TRANSIT_OPEN + taskInfo = TASK_INFO_FREEFORM + } + val minimizeChange = + TransitionInfo.Change(mock(), mock()).apply { + mode = WindowManager.TRANSIT_TO_BACK + taskInfo = TASK_INFO_FREEFORM + } + val transitionInfo = TransitionInfo(WindowManager.TRANSIT_NONE, 0) + transitionInfo.addChange(openChange) + transitionInfo.addChange(minimizeChange) + + val actual = helper.createAnimators(transitionInfo, finishCallback = {}) + + assertThat(actual).hasSize(2) + assertLaunchAnimator(actual[0]) + assertMinimizeAnimator(actual[1]) + } + + @Test + @EnableFlags(Flags.FLAG_ENABLE_DESKTOP_TRAMPOLINE_CLOSE_ANIMATION_BUGFIX) + fun trampolineTransition_flagEnabled_returnsLaunchAndCloseAnimator() { + val openChange = + TransitionInfo.Change(mock(), mock()).apply { + mode = WindowManager.TRANSIT_OPEN + taskInfo = TASK_INFO_FREEFORM + } + val closeChange = + TransitionInfo.Change(mock(), mock()).apply { + mode = WindowManager.TRANSIT_CLOSE + taskInfo = TASK_INFO_FREEFORM + } + val transitionInfo = TransitionInfo(WindowManager.TRANSIT_NONE, 0) + transitionInfo.addChange(openChange) + transitionInfo.addChange(closeChange) + + val actual = helper.createAnimators(transitionInfo, finishCallback = {}) + + assertThat(actual).hasSize(2) + assertTrampolineLaunchAnimator(actual[0]) + assertCloseAnimator(actual[1]) + } + + @Test + @DisableFlags(Flags.FLAG_ENABLE_DESKTOP_TRAMPOLINE_CLOSE_ANIMATION_BUGFIX) + fun trampolineTransition_flagDisabled_returnsLaunchAnimator() { + val openChange = + TransitionInfo.Change(mock(), mock()).apply { + mode = WindowManager.TRANSIT_OPEN + taskInfo = TASK_INFO_FREEFORM + } + val closeChange = + TransitionInfo.Change(mock(), mock()).apply { + mode = WindowManager.TRANSIT_CLOSE + taskInfo = TASK_INFO_FREEFORM + } + val transitionInfo = TransitionInfo(WindowManager.TRANSIT_NONE, 0) + transitionInfo.addChange(openChange) + transitionInfo.addChange(closeChange) + + val actual = helper.createAnimators(transitionInfo, finishCallback = {}) + + assertThat(actual).hasSize(1) + assertLaunchAnimator(actual[0]) + } + + @Test + @EnableFlags(Flags.FLAG_ENABLE_DESKTOP_TRAMPOLINE_CLOSE_ANIMATION_BUGFIX) + fun trampolineTransition_flagEnabled_hitDesktopWindowLimit_returnsLaunchMinimizeCloseAnimator() { + val openChange = + TransitionInfo.Change(mock(), mock()).apply { + mode = WindowManager.TRANSIT_OPEN + taskInfo = TASK_INFO_FREEFORM + } + val minimizeChange = + TransitionInfo.Change(mock(), mock()).apply { + mode = WindowManager.TRANSIT_TO_BACK + taskInfo = TASK_INFO_FREEFORM + } + val closeChange = + TransitionInfo.Change(mock(), mock()).apply { + mode = WindowManager.TRANSIT_CLOSE + taskInfo = TASK_INFO_FREEFORM + } + val transitionInfo = TransitionInfo(WindowManager.TRANSIT_NONE, 0) + transitionInfo.addChange(openChange) + transitionInfo.addChange(minimizeChange) + transitionInfo.addChange(closeChange) + + val actual = helper.createAnimators(transitionInfo, finishCallback = {}) + + assertThat(actual).hasSize(3) + assertTrampolineLaunchAnimator(actual[0]) + assertMinimizeAnimator(actual[1]) + assertCloseAnimator(actual[2]) + } + + @Test + @DisableFlags(Flags.FLAG_ENABLE_DESKTOP_TRAMPOLINE_CLOSE_ANIMATION_BUGFIX) + fun trampolineTransition_flagDisabled_hitDesktopWindowLimit_returnsLaunchMinimizeAnimator() { + val openChange = + TransitionInfo.Change(mock(), mock()).apply { + mode = WindowManager.TRANSIT_OPEN + taskInfo = TASK_INFO_FREEFORM + } + val minimizeChange = + TransitionInfo.Change(mock(), mock()).apply { + mode = WindowManager.TRANSIT_TO_BACK + taskInfo = TASK_INFO_FREEFORM + } + val closeChange = + TransitionInfo.Change(mock(), mock()).apply { + mode = WindowManager.TRANSIT_CLOSE + taskInfo = TASK_INFO_FREEFORM + } + val transitionInfo = TransitionInfo(WindowManager.TRANSIT_NONE, 0) + transitionInfo.addChange(openChange) + transitionInfo.addChange(minimizeChange) + transitionInfo.addChange(closeChange) + + val actual = helper.createAnimators(transitionInfo, finishCallback = {}) + + assertThat(actual).hasSize(2) + assertLaunchAnimator(actual[0]) + assertMinimizeAnimator(actual[1]) + } + + private fun assertLaunchAnimator(animator: Animator) { + assertThat(animator).isInstanceOf(AnimatorSet::class.java) + assertThat((animator as AnimatorSet).childAnimations.size).isEqualTo(2) + assertThat(animator.childAnimations[0]).isInstanceOf(ValueAnimator::class.java) + assertThat(animator.childAnimations[0].interpolator) + .isEqualTo(AppLaunchType.LAUNCH.boundsAnimationParams.interpolator) + assertThat(animator.childAnimations[0].duration) + .isEqualTo(AppLaunchType.LAUNCH.boundsAnimationParams.durationMs) + assertThat(animator.childAnimations[1]).isInstanceOf(ValueAnimator::class.java) + assertThat(animator.childAnimations[1].interpolator).isEqualTo(Interpolators.LINEAR) + assertThat(animator.childAnimations[1].duration) + .isEqualTo(AppLaunchType.LAUNCH.alphaDurationMs) + } + + private fun assertTrampolineLaunchAnimator(animator: Animator) { + assertThat(animator).isInstanceOf(AnimatorSet::class.java) + assertThat((animator as AnimatorSet).childAnimations.size).isEqualTo(1) + assertThat(animator.childAnimations[0]).isInstanceOf(ValueAnimator::class.java) + assertThat(animator.childAnimations[0].interpolator).isEqualTo(Interpolators.LINEAR) + assertThat(animator.childAnimations[0].duration) + .isEqualTo(AppLaunchType.LAUNCH.alphaDurationMs) + } + + private fun assertMinimizeAnimator(animator: Animator) { + assertThat(animator).isInstanceOf(AnimatorSet::class.java) + assertThat((animator as AnimatorSet).childAnimations.size).isEqualTo(2) + assertThat(animator.childAnimations[0]).isInstanceOf(ValueAnimator::class.java) + assertThat(animator.childAnimations[0].interpolator) + .isInstanceOf(Interpolators.STANDARD_ACCELERATE::class.java) + assertThat(animator.childAnimations[0].duration).isEqualTo(200) + assertThat(animator.childAnimations[1]).isInstanceOf(ValueAnimator::class.java) + assertThat(animator.childAnimations[1].interpolator) + .isInstanceOf(Interpolators.LINEAR::class.java) + assertThat(animator.childAnimations[1].duration).isEqualTo(100) + } + + private fun assertCloseAnimator(animator: Animator) { + assertThat(animator).isInstanceOf(ValueAnimator::class.java) + assertThat(animator.interpolator).isInstanceOf(Interpolators.LINEAR::class.java) + assertThat(animator.duration).isEqualTo(100) + } + + private companion object { + val TASK_INFO_FREEFORM = + ActivityManager.RunningTaskInfo().apply { + baseIntent = + Intent().apply { + component = ComponentName("com.example.app", "com.example.app.MainActivity") + } + configuration.windowConfiguration.windowingMode = + WindowConfiguration.WINDOWING_MODE_FREEFORM + } + } +} From 0ae28ca5d002fd10c1dfd80ff0491d5a12e4e0b4 Mon Sep 17 00:00:00 2001 From: Schneider Victor-Tulias Date: Thu, 13 Feb 2025 11:39:51 -0500 Subject: [PATCH 014/153] Update KQS text font family to match new specs Flag: com.android.launcher3.expressive_theme_in_taskbar_and_navigation Fixes: 393615634 Test: opened KQS, be before/after in bug Change-Id: Ia953e2b927b6e69c0c150df01925436b6247d751 --- ...keyboard_quick_switch_desktop_taskview.xml | 4 +- .../taskbar/KeyboardQuickSwitchTaskView.java | 13 ++++- .../taskbar/KeyboardQuickSwitchView.java | 6 ++- .../launcher3/taskbar/TypefaceUtils.kt | 47 +++++++++++++++++++ 4 files changed, 65 insertions(+), 5 deletions(-) create mode 100644 quickstep/src/com/android/launcher3/taskbar/TypefaceUtils.kt diff --git a/quickstep/res/layout/keyboard_quick_switch_desktop_taskview.xml b/quickstep/res/layout/keyboard_quick_switch_desktop_taskview.xml index 71c782d7e0..db47ff08ba 100644 --- a/quickstep/res/layout/keyboard_quick_switch_desktop_taskview.xml +++ b/quickstep/res/layout/keyboard_quick_switch_desktop_taskview.xml @@ -48,13 +48,13 @@ app:layout_constraintVertical_chainStyle="packed" app:layout_constraintTop_toTopOf="parent" - app:layout_constraintBottom_toTopOf="@id/text" + app:layout_constraintBottom_toTopOf="@id/small_text" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent"/> findViewById(R.id.text).setText( + desktopButton.findViewById(R.id.small_text).setText( resources.getString(R.string.quick_switch_desktop)); } mDisplayingRecentTasks = !groupTasks.isEmpty() || useDesktopTaskView; diff --git a/quickstep/src/com/android/launcher3/taskbar/TypefaceUtils.kt b/quickstep/src/com/android/launcher3/taskbar/TypefaceUtils.kt new file mode 100644 index 0000000000..fa551b84ad --- /dev/null +++ b/quickstep/src/com/android/launcher3/taskbar/TypefaceUtils.kt @@ -0,0 +1,47 @@ +/* + * 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.launcher3.taskbar + +import android.graphics.Typeface +import android.widget.TextView +import com.android.launcher3.Flags + +/** + * Helper util class to set pre-defined typefaces to textviews + * + * If the typeface font family is already defined here, you can just reuse it directly. Otherwise, + * please define it here for future use. You do not need to define the font style. If you need + * anything other than [Typeface.NORMAL], pass it inline when calling [setTypeface] + */ +class TypefaceUtils { + + companion object { + const val FONT_FAMILY_HEADLINE_LARGE_EMPHASIZED = "variable-headline-large-emphasized" + const val FONT_FAMILY_LABEL_LARGE_BASELINE = "variable-label-large" + + @JvmStatic + @JvmOverloads + fun setTypeface( + textView: TextView?, + fontFamilyName: String, + fontStyle: Int = Typeface.NORMAL, + ) { + if (!Flags.expressiveThemeInTaskbarAndNavigation()) return + textView?.typeface = Typeface.create(fontFamilyName, fontStyle) + } + } +} From 3b355f645bd3a3a4cefa2483ac8ac99dc406e8f7 Mon Sep 17 00:00:00 2001 From: Pat Manning Date: Wed, 12 Feb 2025 15:04:33 +0000 Subject: [PATCH 015/153] Scale recents on drag of tasks during dismiss. Fix: 389083567 Test: TaplTestsQuickstep#testDismissCancel Flag: com.android.launcher3.enable_expressive_dismiss_task_motion Change-Id: Ibeb0a742cdfb4392c920deb64dd5bd4f221a9564 --- .../TaskViewDismissTouchController.kt | 56 +++++++++++++++++++ .../android/quickstep/views/RecentsView.java | 7 +++ .../quickstep/views/RecentsViewUtils.kt | 34 ++++++++++- 3 files changed, 94 insertions(+), 3 deletions(-) diff --git a/quickstep/src/com/android/launcher3/uioverrides/touchcontrollers/TaskViewDismissTouchController.kt b/quickstep/src/com/android/launcher3/uioverrides/touchcontrollers/TaskViewDismissTouchController.kt index 98737a5568..7a3cdb765b 100644 --- a/quickstep/src/com/android/launcher3/uioverrides/touchcontrollers/TaskViewDismissTouchController.kt +++ b/quickstep/src/com/android/launcher3/uioverrides/touchcontrollers/TaskViewDismissTouchController.kt @@ -19,6 +19,7 @@ import android.content.Context import android.view.MotionEvent import androidx.dynamicanimation.animation.SpringAnimation import com.android.app.animation.Interpolators.DECELERATE +import com.android.app.animation.Interpolators.LINEAR import com.android.launcher3.AbstractFloatingView import com.android.launcher3.R import com.android.launcher3.Utilities.EDGE_NAV_BAR @@ -29,6 +30,7 @@ import com.android.launcher3.touch.SingleAxisSwipeDetector import com.android.launcher3.util.MSDLPlayerWrapper import com.android.launcher3.util.TouchController import com.android.quickstep.views.RecentsView +import com.android.quickstep.views.RecentsView.RECENTS_SCALE_PROPERTY import com.android.quickstep.views.RecentsViewContainer import com.android.quickstep.views.TaskView import com.google.android.msdl.data.model.MSDLToken @@ -57,6 +59,7 @@ CONTAINER : RecentsViewContainer { private var verticalFactor: Int = 0 private var hasDismissThresholdHapticRun = false private var initialDisplacement: Float = 0f + private var recentsScaleAnimation: SpringAnimation? = null private fun canInterceptTouch(ev: MotionEvent): Boolean = when { @@ -98,6 +101,7 @@ CONTAINER : RecentsViewContainer { private fun onActionDown(ev: MotionEvent): Boolean { springAnimation?.cancel() + recentsScaleAnimation?.cancel() if (!canInterceptTouch(ev)) { return false } @@ -162,6 +166,8 @@ CONTAINER : RecentsViewContainer { } recentsView.redrawLiveTile() } + val dismissFraction = displacement / (dismissLength * verticalFactor).toFloat() + RECENTS_SCALE_PROPERTY.setValue(recentsView, getRecentsScale(dismissFraction)) playDismissThresholdHaptic(displacement) return true } @@ -216,6 +222,10 @@ CONTAINER : RecentsViewContainer { if (isDismissing) (dismissLength * verticalFactor).toFloat() else 0f ) } + recentsScaleAnimation = + recentsView.animateRecentsScale(RECENTS_SCALE_DEFAULT).addEndListener { _, _, _, _ -> + recentsScaleAnimation = null + } } // Returns if the current task being dragged is towards "positive" (e.g. dismissal). @@ -230,8 +240,54 @@ CONTAINER : RecentsViewContainer { springAnimation = null } + private fun getRecentsScale(dismissFraction: Float): Float { + return when { + // Do not scale recents when dragging below origin. + dismissFraction <= 0 -> { + RECENTS_SCALE_DEFAULT + } + // Initially scale recents as the drag begins, up to the first threshold. + dismissFraction < RECENTS_SCALE_FIRST_THRESHOLD_FRACTION -> { + mapToRange( + dismissFraction, + 0f, + RECENTS_SCALE_FIRST_THRESHOLD_FRACTION, + RECENTS_SCALE_DEFAULT, + RECENTS_SCALE_ON_DISMISS_CANCEL, + LINEAR, + ) + } + // Keep scale consistent until dragging to the dismiss threshold. + dismissFraction < RECENTS_SCALE_DISMISS_THRESHOLD_FRACTION -> { + RECENTS_SCALE_ON_DISMISS_CANCEL + } + // Scale beyond the dismiss threshold again, to indicate dismiss will occur on release. + dismissFraction < RECENTS_SCALE_SECOND_THRESHOLD_FRACTION -> { + mapToRange( + dismissFraction, + RECENTS_SCALE_DISMISS_THRESHOLD_FRACTION, + RECENTS_SCALE_SECOND_THRESHOLD_FRACTION, + RECENTS_SCALE_ON_DISMISS_CANCEL, + RECENTS_SCALE_ON_DISMISS_SUCCESS, + LINEAR, + ) + } + // Keep scale beyond the dismiss threshold scaling consistent. + else -> { + RECENTS_SCALE_ON_DISMISS_SUCCESS + } + } + } + companion object { private const val DISMISS_THRESHOLD_FRACTION = 0.5f private const val DISMISS_THRESHOLD_HAPTIC_RANGE = 10f + + private const val RECENTS_SCALE_ON_DISMISS_CANCEL = 0.9875f + private const val RECENTS_SCALE_ON_DISMISS_SUCCESS = 0.975f + private const val RECENTS_SCALE_DEFAULT = 1f + private const val RECENTS_SCALE_FIRST_THRESHOLD_FRACTION = 0.2f + private const val RECENTS_SCALE_DISMISS_THRESHOLD_FRACTION = 0.5f + private const val RECENTS_SCALE_SECOND_THRESHOLD_FRACTION = 0.575f } } diff --git a/quickstep/src/com/android/quickstep/views/RecentsView.java b/quickstep/src/com/android/quickstep/views/RecentsView.java index 424271a4c5..d37fe9a450 100644 --- a/quickstep/src/com/android/quickstep/views/RecentsView.java +++ b/quickstep/src/com/android/quickstep/views/RecentsView.java @@ -6950,6 +6950,13 @@ public abstract class RecentsView< isDismissing, detector, dismissLength, onEndRunnable); } + /** + * Animates RecentsView's scale to the provided value, using spring animations. + */ + public SpringAnimation animateRecentsScale(float scale) { + return mUtils.animateRecentsScale(scale); + } + public interface TaskLaunchListener { void onTaskLaunched(); } diff --git a/quickstep/src/com/android/quickstep/views/RecentsViewUtils.kt b/quickstep/src/com/android/quickstep/views/RecentsViewUtils.kt index d18a5f7fe8..5ee661e926 100644 --- a/quickstep/src/com/android/quickstep/views/RecentsViewUtils.kt +++ b/quickstep/src/com/android/quickstep/views/RecentsViewUtils.kt @@ -35,6 +35,7 @@ import com.android.launcher3.util.MSDLPlayerWrapper import com.android.quickstep.util.GroupTask import com.android.quickstep.util.TaskGridNavHelper import com.android.quickstep.util.isExternalDisplay +import com.android.quickstep.views.RecentsView.RECENTS_SCALE_PROPERTY import com.android.quickstep.views.RecentsView.RUNNING_TASK_ATTACH_ALPHA import com.android.systemui.shared.recents.model.ThumbnailData import com.google.android.msdl.data.model.MSDLToken @@ -362,7 +363,6 @@ class RecentsViewUtils(private val recentsView: RecentsView<*, *>) { addNeighboringSpringAnimationsForDismissCancel( draggedTaskView, draggedTaskViewSpringAnimation, - recentsView.pageCount, ) } return draggedTaskViewSpringAnimation @@ -371,7 +371,6 @@ class RecentsViewUtils(private val recentsView: RecentsView<*, *>) { private fun addNeighboringSpringAnimationsForDismissCancel( draggedTaskView: TaskView, draggedTaskViewSpringAnimation: SpringAnimation, - taskCount: Int, ) { // Empty spring animation exists for conditional start, and to drive neighboring springs. val neighborsToSettle = @@ -559,10 +558,39 @@ class RecentsViewUtils(private val recentsView: RecentsView<*, *>) { ) } + /** Animates RecentsView's scale to the provided value, using spring animations. */ + fun animateRecentsScale(scale: Float): SpringAnimation { + val resourceProvider = DynamicResource.provider(recentsView.mContainer) + val dampingRatio = resourceProvider.getFloat(R.dimen.swipe_up_rect_scale_damping_ratio) + val stiffness = resourceProvider.getFloat(R.dimen.swipe_up_rect_scale_stiffness) + + // Spring which sets the Recents scale on update. This is needed, as the SpringAnimation + // struggles to animate small values like changing recents scale from 0.9 to 1. So + // we animate over a larger range (e.g. 900 to 1000) and convert back to the required value. + // (This is instead of converting RECENTS_SCALE_PROPERTY to a FloatPropertyCompat and + // animating it directly via springs.) + val initialRecentsScaleSpringValue = + RECENTS_SCALE_SPRING_MULTIPLIER * RECENTS_SCALE_PROPERTY.get(recentsView) + return SpringAnimation(FloatValueHolder(initialRecentsScaleSpringValue)) + .setSpring( + SpringForce(initialRecentsScaleSpringValue) + .setDampingRatio(dampingRatio) + .setStiffness(stiffness) + ) + .addUpdateListener { _, value, _ -> + RECENTS_SCALE_PROPERTY.setValue( + recentsView, + value / RECENTS_SCALE_SPRING_MULTIPLIER, + ) + } + .apply { animateToFinalPosition(RECENTS_SCALE_SPRING_MULTIPLIER * scale) } + } + companion object { val TEMP_RECT = Rect() // The additional damping to apply to tasks further from the dismissed task. - const val ADDITIONAL_DISMISS_DAMPING_RATIO = 0.15f + private const val ADDITIONAL_DISMISS_DAMPING_RATIO = 0.15f + private const val RECENTS_SCALE_SPRING_MULTIPLIER = 1000f } } From fe5101d8de38ed36c019c474d6f5511743a45d1b Mon Sep 17 00:00:00 2001 From: Sunny Goyal Date: Tue, 14 Jan 2025 11:28:00 -0800 Subject: [PATCH 016/153] Simplifying icon normalization for adaptive icons Bug: 366237794 Flag: EXEMPT refactor Test: PResubmit and screenshot tests Change-Id: Id21e57c9d4ba83983f27aa7988a08db3fd618ce3 --- .../launcher3/uioverrides/PredictedAppIcon.java | 4 ++-- src/com/android/launcher3/BubbleTextView.java | 9 +++------ src/com/android/launcher3/DeviceProfile.java | 3 +-- src/com/android/launcher3/dragndrop/DragView.java | 11 +++-------- src/com/android/launcher3/graphics/ShapeDelegate.kt | 8 -------- src/com/android/launcher3/views/ClipIconView.java | 5 ++--- src/com/android/launcher3/views/FloatingIconView.java | 7 ++----- 7 files changed, 13 insertions(+), 34 deletions(-) diff --git a/quickstep/src/com/android/launcher3/uioverrides/PredictedAppIcon.java b/quickstep/src/com/android/launcher3/uioverrides/PredictedAppIcon.java index 37b8dc7bd8..15a27d15c0 100644 --- a/quickstep/src/com/android/launcher3/uioverrides/PredictedAppIcon.java +++ b/quickstep/src/com/android/launcher3/uioverrides/PredictedAppIcon.java @@ -17,6 +17,7 @@ package com.android.launcher3.uioverrides; import static com.android.app.animation.Interpolators.ACCELERATE_DECELERATE; import static com.android.launcher3.icons.FastBitmapDrawable.getDisabledColorFilter; +import static com.android.launcher3.icons.IconNormalizer.ICON_VISIBLE_AREA_FACTOR; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; @@ -53,7 +54,6 @@ import com.android.launcher3.celllayout.CellLayoutLayoutParams; import com.android.launcher3.celllayout.DelegatedCellDrawing; import com.android.launcher3.graphics.ThemeManager; import com.android.launcher3.icons.FastBitmapDrawable; -import com.android.launcher3.icons.IconNormalizer; import com.android.launcher3.icons.LauncherIcons; import com.android.launcher3.model.data.ItemInfoWithIcon; import com.android.launcher3.model.data.WorkspaceItemInfo; @@ -138,7 +138,7 @@ public class PredictedAppIcon extends DoubleShadowBubbleTextView { public PredictedAppIcon(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mDeviceProfile = ActivityContext.lookupContext(context).getDeviceProfile(); - mNormalizedIconSize = IconNormalizer.getNormalizedCircleSize(getIconSize()); + mNormalizedIconSize = Math.round(getIconSize() * ICON_VISIBLE_AREA_FACTOR); int shadowSize = context.getResources().getDimensionPixelSize( R.dimen.blur_size_thin_outline); mShadowFilter = new BlurMaskFilter(shadowSize, BlurMaskFilter.Blur.OUTER); diff --git a/src/com/android/launcher3/BubbleTextView.java b/src/com/android/launcher3/BubbleTextView.java index 03dd943f50..bd42b2b855 100644 --- a/src/com/android/launcher3/BubbleTextView.java +++ b/src/com/android/launcher3/BubbleTextView.java @@ -27,6 +27,7 @@ import static com.android.launcher3.icons.BitmapInfo.FLAG_NO_BADGE; import static com.android.launcher3.icons.BitmapInfo.FLAG_SKIP_USER_BADGE; import static com.android.launcher3.icons.BitmapInfo.FLAG_THEMED; import static com.android.launcher3.icons.GraphicsUtils.setColorAlphaBound; +import static com.android.launcher3.icons.IconNormalizer.ICON_VISIBLE_AREA_FACTOR; import static com.android.launcher3.model.data.ItemInfoWithIcon.FLAG_INCREMENTAL_DOWNLOAD_ACTIVE; import static com.android.launcher3.model.data.ItemInfoWithIcon.FLAG_INSTALL_SESSION_ACTIVE; import static com.android.launcher3.model.data.ItemInfoWithIcon.FLAG_SHOW_DOWNLOAD_PROGRESS_MASK; @@ -76,7 +77,6 @@ import com.android.launcher3.dragndrop.DragOptions.PreDragCondition; import com.android.launcher3.dragndrop.DraggableView; import com.android.launcher3.folder.FolderIcon; import com.android.launcher3.graphics.PreloadIconDrawable; -import com.android.launcher3.graphics.ShapeDelegate; import com.android.launcher3.icons.DotRenderer; import com.android.launcher3.icons.FastBitmapDrawable; import com.android.launcher3.icons.IconCache.ItemInfoUpdateReceiver; @@ -723,8 +723,7 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver, protected void drawDotIfNecessary(Canvas canvas) { if (!mForceHideDot && (hasDot() || mDotParams.scale > 0)) { getIconBounds(mDotParams.iconBounds); - Utilities.scaleRectAboutCenter(mDotParams.iconBounds, - ShapeDelegate.getNormalizationScale()); + Utilities.scaleRectAboutCenter(mDotParams.iconBounds, ICON_VISIBLE_AREA_FACTOR); final int scrollX = getScrollX(); final int scrollY = getScrollY(); canvas.translate(scrollX, scrollY); @@ -773,9 +772,7 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver, return; } getIconBounds(mRunningAppIconBounds); - Utilities.scaleRectAboutCenter( - mRunningAppIconBounds, - ShapeDelegate.getNormalizationScale()); + Utilities.scaleRectAboutCenter(mRunningAppIconBounds, ICON_VISIBLE_AREA_FACTOR); final boolean isMinimized = mRunningAppState == RunningAppState.MINIMIZED; final int indicatorTop = mRunningAppIconBounds.bottom + mRunningAppIndicatorTopMargin; diff --git a/src/com/android/launcher3/DeviceProfile.java b/src/com/android/launcher3/DeviceProfile.java index f34add8d3f..22cc805932 100644 --- a/src/com/android/launcher3/DeviceProfile.java +++ b/src/com/android/launcher3/DeviceProfile.java @@ -54,7 +54,6 @@ import com.android.launcher3.DevicePaddings.DevicePadding; import com.android.launcher3.folder.ClippedFolderIconLayoutRule; import com.android.launcher3.graphics.ThemeManager; import com.android.launcher3.icons.DotRenderer; -import com.android.launcher3.icons.IconNormalizer; import com.android.launcher3.model.data.ItemInfo; import com.android.launcher3.responsive.CalculatedCellSpec; import com.android.launcher3.responsive.CalculatedHotseatSpec; @@ -1371,7 +1370,7 @@ public class DeviceProfile { updateHotseatSizes(iconSizePx); // Folder icon - folderIconSizePx = IconNormalizer.getNormalizedCircleSize(iconSizePx); + folderIconSizePx = Math.round(iconSizePx * ICON_VISIBLE_AREA_FACTOR); folderIconOffsetYPx = (iconSizePx - folderIconSizePx) / 2; // Update widget padding: diff --git a/src/com/android/launcher3/dragndrop/DragView.java b/src/com/android/launcher3/dragndrop/DragView.java index bff323ceb3..22797b247c 100644 --- a/src/com/android/launcher3/dragndrop/DragView.java +++ b/src/com/android/launcher3/dragndrop/DragView.java @@ -62,7 +62,7 @@ import com.android.launcher3.R; import com.android.launcher3.Utilities; import com.android.launcher3.graphics.ThemeManager; import com.android.launcher3.icons.FastBitmapDrawable; -import com.android.launcher3.icons.LauncherIcons; +import com.android.launcher3.icons.IconNormalizer; import com.android.launcher3.model.data.ItemInfo; import com.android.launcher3.util.RunnableList; import com.android.launcher3.views.ActivityContext; @@ -261,12 +261,7 @@ public abstract class DragView extends Fram // be scaled down due to icon normalization. mBadge = fullDrawable.second; FastBitmapDrawable.setBadgeBounds(mBadge, bounds); - - try (LauncherIcons li = LauncherIcons.obtain(mActivity)) { - // Since we just want the scale, avoid heavy drawing operations - Utilities.scaleRectAboutCenter(bounds, li.getNormalizer().getScale( - new AdaptiveIconDrawable(new ColorDrawable(Color.BLACK), null))); - } + Utilities.scaleRectAboutCenter(bounds, IconNormalizer.ICON_VISIBLE_AREA_FACTOR); // Shrink very tiny bit so that the clip path is smaller than the original bitmap // that has anti aliased edges and shadows. @@ -567,7 +562,7 @@ public abstract class DragView extends Fram return mContentViewParent; } - /** Return true if {@link mContent} is a {@link AppWidgetHostView}. */ + /** Return true if {@link #mContent} is a {@link AppWidgetHostView}. */ public boolean containsAppWidgetHostView() { return mContent instanceof AppWidgetHostView; } diff --git a/src/com/android/launcher3/graphics/ShapeDelegate.kt b/src/com/android/launcher3/graphics/ShapeDelegate.kt index df0c8f9aa6..9033eac049 100644 --- a/src/com/android/launcher3/graphics/ShapeDelegate.kt +++ b/src/com/android/launcher3/graphics/ShapeDelegate.kt @@ -43,7 +43,6 @@ import androidx.graphics.shapes.toPath import androidx.graphics.shapes.transformed import com.android.launcher3.anim.RoundedRectRevealOutlineProvider import com.android.launcher3.icons.GraphicsUtils -import com.android.launcher3.icons.IconNormalizer.normalizeAdaptiveIcon import com.android.launcher3.views.ClipPathView /** Abstract representation of the shape of an icon shape */ @@ -342,12 +341,5 @@ interface ShapeDelegate { centerY = (bottom - top) / 2, rounding = CornerRounding(cornerR), ) - - @JvmStatic - val normalizationScale = - normalizeAdaptiveIcon( - AdaptiveIconDrawable(null, ColorDrawable(Color.BLACK)), - AREA_CALC_SIZE, - ) } } diff --git a/src/com/android/launcher3/views/ClipIconView.java b/src/com/android/launcher3/views/ClipIconView.java index ddf18dfbaa..3e86c0ccd4 100644 --- a/src/com/android/launcher3/views/ClipIconView.java +++ b/src/com/android/launcher3/views/ClipIconView.java @@ -20,6 +20,7 @@ import static com.android.launcher3.Flags.enableAdditionalHomeAnimations; import static com.android.launcher3.Utilities.boundToRange; import static com.android.launcher3.Utilities.mapToRange; import static com.android.launcher3.anim.AnimatorListeners.forEndCallback; +import static com.android.launcher3.icons.IconNormalizer.ICON_VISIBLE_AREA_FACTOR; import static com.android.launcher3.views.FloatingIconView.SHAPE_PROGRESS_DURATION; import static java.lang.Math.max; @@ -47,7 +48,6 @@ import com.android.launcher3.DeviceProfile; import com.android.launcher3.R; import com.android.launcher3.Utilities; import com.android.launcher3.dragndrop.FolderAdaptiveIcon; -import com.android.launcher3.graphics.ShapeDelegate; import com.android.launcher3.graphics.ThemeManager; /** @@ -259,8 +259,7 @@ public class ClipIconView extends View implements ClipPathView { mStartRevealRect.set(0, 0, originalWidth, originalHeight); if (!isFolderIcon) { - Utilities.scaleRectAboutCenter(mStartRevealRect, - ShapeDelegate.getNormalizationScale()); + Utilities.scaleRectAboutCenter(mStartRevealRect, ICON_VISIBLE_AREA_FACTOR); } if (dp.isLandscape) { diff --git a/src/com/android/launcher3/views/FloatingIconView.java b/src/com/android/launcher3/views/FloatingIconView.java index 22857b1f40..5b3abc383a 100644 --- a/src/com/android/launcher3/views/FloatingIconView.java +++ b/src/com/android/launcher3/views/FloatingIconView.java @@ -55,7 +55,7 @@ import com.android.launcher3.dragndrop.DragLayer; import com.android.launcher3.folder.FolderIcon; import com.android.launcher3.graphics.PreloadIconDrawable; import com.android.launcher3.icons.FastBitmapDrawable; -import com.android.launcher3.icons.LauncherIcons; +import com.android.launcher3.icons.IconNormalizer; import com.android.launcher3.model.data.ItemInfo; import com.android.launcher3.model.data.ItemInfoWithIcon; import com.android.launcher3.popup.SystemShortcut; @@ -463,10 +463,7 @@ public class FloatingIconView extends FrameLayout implements Rect bounds = new Rect(0, 0, (int) position.width() + blurSizeOutline, (int) position.height() + blurSizeOutline); bounds.inset(blurSizeOutline / 2, blurSizeOutline / 2); - - try (LauncherIcons li = LauncherIcons.obtain(l)) { - Utilities.scaleRectAboutCenter(bounds, li.getNormalizer().getScale(drawable)); - } + Utilities.scaleRectAboutCenter(bounds, IconNormalizer.ICON_VISIBLE_AREA_FACTOR); bounds.inset( (int) (-bounds.width() * AdaptiveIconDrawable.getExtraInsetFraction()), From b8030e962706e39c2367ced003719250bc8b2a3a Mon Sep 17 00:00:00 2001 From: Federico Baron Date: Thu, 13 Feb 2025 19:39:42 +0000 Subject: [PATCH 017/153] Fix issue where hotseat apps don't migrate to the new grid Hotseat apps would not migrate to a new grid if the new grid already had hosteat filled out. This resolves the issue and addresses the issue of workspace spots showing up as occuppied when they should be available Bug: 395786587 Test: GridSizeMigrationTest, GridMigrationTest, ValidGridMigrationTest Flag: EXEMPT bugfix Change-Id: I79613986702c7dddf15a9a31c29b4ef59eac2b3a --- .../model/GridSizeMigrationDBController.java | 12 +- .../launcher3/model/GridSizeMigrationLogic.kt | 7 +- .../launcher3/model/GridSizeMigrationTest.kt | 193 ++++++++++++------ 3 files changed, 141 insertions(+), 71 deletions(-) diff --git a/src/com/android/launcher3/model/GridSizeMigrationDBController.java b/src/com/android/launcher3/model/GridSizeMigrationDBController.java index 47f13bd636..5d0a7bd6a2 100644 --- a/src/com/android/launcher3/model/GridSizeMigrationDBController.java +++ b/src/com/android/launcher3/model/GridSizeMigrationDBController.java @@ -238,16 +238,19 @@ public class GridSizeMigrationDBController { Collections.sort(hotseatToBeAdded); Collections.sort(workspaceToBeAdded); - List idsInUse = dstWorkspaceItems.stream() + List remainingDstHotseatItems = destReader.loadHotseatEntries(); + List remainingDstWorkspaceItems = destReader.loadAllWorkspaceEntries(); + List idsInUse = remainingDstHotseatItems.stream() .map(entry -> entry.id) .collect(Collectors.toList()); - idsInUse.addAll(dstHotseatItems.stream() + idsInUse.addAll(remainingDstWorkspaceItems.stream() .map(entry -> entry.id) .collect(Collectors.toList())); + // Migrate hotseat solveHotseatPlacement(helper, destHotseatSize, - srcReader, destReader, dstHotseatItems, hotseatToBeAdded, idsInUse); + srcReader, destReader, remainingDstHotseatItems, hotseatToBeAdded, idsInUse); // Migrate workspace. // First we create a collection of the screens @@ -467,7 +470,7 @@ public class GridSizeMigrationDBController { final Context mContext; int mLastScreenId = -1; - final Map> mWorkspaceEntriesByScreenId = + Map> mWorkspaceEntriesByScreenId = new ArrayMap<>(); public DbReader(SQLiteDatabase db, String tableName, Context context) { @@ -539,6 +542,7 @@ public class GridSizeMigrationDBController { } protected List loadAllWorkspaceEntries() { + mWorkspaceEntriesByScreenId.clear(); final List workspaceEntries = new ArrayList<>(); Cursor c = queryWorkspace( new String[]{ diff --git a/src/com/android/launcher3/model/GridSizeMigrationLogic.kt b/src/com/android/launcher3/model/GridSizeMigrationLogic.kt index 9586bf3015..5df135a98f 100644 --- a/src/com/android/launcher3/model/GridSizeMigrationLogic.kt +++ b/src/com/android/launcher3/model/GridSizeMigrationLogic.kt @@ -183,9 +183,11 @@ class GridSizeMigrationLogic { ) } + val remainingDstHotseatItems = destReader.loadHotseatEntries() + placeHotseatItems( itemsToBeAdded, - dstHotseatItems, + remainingDstHotseatItems, destHotseatSize, helper, srcReader, @@ -265,9 +267,10 @@ class GridSizeMigrationLogic { ) } + val remainingDstWorkspaceItems = destReader.loadAllWorkspaceEntries() placeWorkspaceItems( workspaceToBeAdded, - dstWorkspaceItems, + remainingDstWorkspaceItems, targetSize.x, targetSize.y, helper, diff --git a/tests/multivalentTests/src/com/android/launcher3/model/GridSizeMigrationTest.kt b/tests/multivalentTests/src/com/android/launcher3/model/GridSizeMigrationTest.kt index adf38fea93..5607bb4641 100644 --- a/tests/multivalentTests/src/com/android/launcher3/model/GridSizeMigrationTest.kt +++ b/tests/multivalentTests/src/com/android/launcher3/model/GridSizeMigrationTest.kt @@ -275,36 +275,15 @@ class GridSizeMigrationTest { val readerGridA = DbReader(db, TMP_TABLE, context) val readerGridB = DbReader(db, TABLE_NAME, context) // migrate from A -> B - if (Flags.gridMigrationRefactor()) { - var gridSizeMigrationLogic = GridSizeMigrationLogic() - val idsInUse = mutableListOf() - gridSizeMigrationLogic.migrateHotseat( - 5, - idp.numDatabaseHotseatIcons, - readerGridA, - readerGridB, - dbHelper, - idsInUse, - ) - gridSizeMigrationLogic.migrateWorkspace( - readerGridA, - readerGridB, - dbHelper, - Point(idp.numColumns, idp.numRows), - idsInUse, - ) - } else { - GridSizeMigrationDBController.migrate( - dbHelper, - readerGridA, - readerGridB, - 5, - idp.numDatabaseHotseatIcons, - Point(idp.numColumns, idp.numRows), - DeviceGridState(context), - DeviceGridState(idp), - ) - } + migrateGrid( + dbHelper, + readerGridA, + readerGridB, + 5, + idp.numDatabaseHotseatIcons, + idp.numColumns, + idp.numRows, + ) // Check hotseat items in grid B var c = @@ -388,8 +367,8 @@ class GridSizeMigrationTest { locMap = parseLocMap(c) // Expected workspace items in grid A // _ _ _ _ _ - // _ _ _ _ 5 - // 9 _ 6 _ 7 + // 9 _ _ _ 5 + // _ _ 6 _ 7 // _ _ 8 _ _ // _ _ _ _ _ assertThat(locMap.size.toLong()).isEqualTo(5) @@ -399,7 +378,7 @@ class GridSizeMigrationTest { assertThat(locMap[testPackage7]).isEqualTo(Triple(0, 4, 2)) assertThat(locMap[testPackage8]).isEqualTo(Triple(0, 2, 3)) // Verify items that didn't exist in grid A are added in new screen - assertThat(locMap[testPackage9]).isEqualTo(Triple(0, 0, 2)) + assertThat(locMap[testPackage9]).isEqualTo(Triple(0, 0, 1)) // remove item from B db.delete(TMP_TABLE, "$_ID=7", null) @@ -493,37 +472,15 @@ class GridSizeMigrationTest { val readerGridA = DbReader(db, TMP_TABLE, context) val readerGridB = DbReader(db, TABLE_NAME, context) // migrate from A -> B - if (Flags.gridMigrationRefactor()) { - var gridSizeMigrationLogic = GridSizeMigrationLogic() - val idsInUse = mutableListOf() - gridSizeMigrationLogic.migrateHotseat( - 5, - idp.numDatabaseHotseatIcons, - readerGridA, - readerGridB, - dbHelper, - idsInUse, - ) - gridSizeMigrationLogic.migrateWorkspace( - readerGridA, - readerGridB, - dbHelper, - Point(idp.numColumns, idp.numRows), - idsInUse, - ) - } else { - GridSizeMigrationDBController.migrate( - dbHelper, - readerGridA, - readerGridB, - 5, - idp.numDatabaseHotseatIcons, - Point(idp.numColumns, idp.numRows), - DeviceGridState(context), - DeviceGridState(idp), - ) - } - + migrateGrid( + dbHelper, + readerGridA, + readerGridB, + 5, + idp.numDatabaseHotseatIcons, + idp.numColumns, + idp.numRows, + ) // Check hotseat items in grid B var c = db.query( @@ -597,6 +554,112 @@ class GridSizeMigrationTest { ) } + @Test + @Throws(Exception::class) + @EnableFlags(Flags.FLAG_GRID_MIGRATION_REFACTOR) + fun testMigrationToFullGridFlagOn() { + testMigrationToFullGrid() + } + + @Test + @Throws(Exception::class) + @DisableFlags(Flags.FLAG_GRID_MIGRATION_REFACTOR) + fun testHotseatMigrationToFullGridFlagOff() { + testMigrationToFullGrid() + } + + @Throws(Exception::class) + fun testMigrationToFullGrid() { + // Hotseat items in grid A + // 1 2 3 4 5 + addItem(ITEM_TYPE_APPLICATION, 0, CONTAINER_HOTSEAT, 0, 0, testPackage1, 1, TMP_TABLE) + addItem(ITEM_TYPE_DEEP_SHORTCUT, 1, CONTAINER_HOTSEAT, 0, 0, testPackage2, 2, TMP_TABLE) + addItem(ITEM_TYPE_DEEP_SHORTCUT, 2, CONTAINER_HOTSEAT, 0, 0, testPackage3, 3, TMP_TABLE) + addItem(ITEM_TYPE_APPLICATION, 3, CONTAINER_HOTSEAT, 0, 0, testPackage4, 4, TMP_TABLE) + addItem(ITEM_TYPE_APPLICATION, 4, CONTAINER_HOTSEAT, 0, 0, testPackage5, 5, TMP_TABLE) + + // Hotseat items in grid B + // 6 7 8 9 + addItem(ITEM_TYPE_DEEP_SHORTCUT, 0, CONTAINER_HOTSEAT, 0, 0, testPackage6) + addItem(ITEM_TYPE_DEEP_SHORTCUT, 1, CONTAINER_HOTSEAT, 0, 0, testPackage7) + addItem(ITEM_TYPE_APPLICATION, 2, CONTAINER_HOTSEAT, 0, 0, testPackage8) + addItem(ITEM_TYPE_APPLICATION, 3, CONTAINER_HOTSEAT, 0, 0, testPackage9) + + // Workspace items in grid A + // _ _ _ _ _ + // 6 _ _ _ _ + // _ _ _ _ _ + // _ _ _ _ _ + // _ _ _ _ _ + addItem(ITEM_TYPE_APPLICATION, 0, CONTAINER_DESKTOP, 0, 1, testPackage6, 6, TMP_TABLE) + + // Workspace items in grid B + // _ _ _ _ + // 1 2 3 4 + // _ _ _ _ + // _ _ _ _ + addItem(ITEM_TYPE_APPLICATION, 0, CONTAINER_DESKTOP, 0, 1, testPackage1) + addItem(ITEM_TYPE_APPLICATION, 0, CONTAINER_DESKTOP, 1, 1, testPackage2) + addItem(ITEM_TYPE_APPLICATION, 0, CONTAINER_DESKTOP, 2, 1, testPackage3) + addItem(ITEM_TYPE_APPLICATION, 0, CONTAINER_DESKTOP, 3, 1, testPackage4) + + idp.numDatabaseHotseatIcons = 4 + idp.numColumns = 4 + idp.numRows = 4 + val readerGridA = DbReader(db, TMP_TABLE, context) + val readerGridB = DbReader(db, TABLE_NAME, context) + + // migrate from A -> B + migrateGrid( + dbHelper, + readerGridA, + readerGridB, + 5, + idp.numDatabaseHotseatIcons, + idp.numColumns, + idp.numRows, + ) + + // Check hotseat items in grid B + var c = + db.query( + TABLE_NAME, + arrayOf(SCREEN, INTENT), + "container=$CONTAINER_HOTSEAT", + null, + SCREEN, + null, + null, + ) ?: throw IllegalStateException() + // Expected hotseat items in grid B + // 1 2 3 4 + verifyHotseat( + c, + mutableListOf(testPackage1, testPackage2, testPackage3, testPackage4).toList(), + 4, + ) + + // Check workspace items in grid B + c = + db.query( + TABLE_NAME, + arrayOf(SCREEN, CELLX, CELLY, INTENT), + "container=$CONTAINER_DESKTOP", + null, + null, + null, + null, + ) ?: throw IllegalStateException() + val locMap = parseLocMap(c) + // Expected workspace items in grid B + // _ _ _ _ + // 6 _ _ _ + // _ _ _ _ + // _ _ _ _ + assertThat(locMap.size.toLong()).isEqualTo(1) + assertThat(locMap[testPackage6]).isEqualTo(Triple(0, 0, 1)) + } + private fun migrateGrid( dbHelper: DatabaseHelper, srcReader: DbReader, @@ -621,7 +684,7 @@ class GridSizeMigrationTest { srcReader, destReader, dbHelper, - Point(idp.numColumns, idp.numRows), + Point(pointX, pointY), idsInUse, ) } else { From 8bda4f6b5f8c6e6d64136b94c6200787d7ea4ba4 Mon Sep 17 00:00:00 2001 From: Pat Manning Date: Wed, 12 Feb 2025 15:34:05 +0000 Subject: [PATCH 018/153] Update dismiss length for tasks to bring them off screen. Fix: 393553524 Test: TaplTestsQuickstep#testDismissBottomRow Flag: com.android.launcher3.enable_expressive_dismiss_task_motion Change-Id: I959bcc86ad986abfe4546add62146e99f3707cc4 --- .../TaskViewDismissTouchController.kt | 6 ++++- .../quickstep/views/RecentsViewUtils.kt | 2 -- .../android/quickstep/TaplTestsQuickstep.java | 22 +++++++++++++++++++ .../android/launcher3/tapl/OverviewTask.java | 2 +- 4 files changed, 28 insertions(+), 4 deletions(-) diff --git a/quickstep/src/com/android/launcher3/uioverrides/touchcontrollers/TaskViewDismissTouchController.kt b/quickstep/src/com/android/launcher3/uioverrides/touchcontrollers/TaskViewDismissTouchController.kt index 98737a5568..4ecf409415 100644 --- a/quickstep/src/com/android/launcher3/uioverrides/touchcontrollers/TaskViewDismissTouchController.kt +++ b/quickstep/src/com/android/launcher3/uioverrides/touchcontrollers/TaskViewDismissTouchController.kt @@ -16,6 +16,7 @@ package com.android.launcher3.uioverrides.touchcontrollers import android.content.Context +import android.graphics.Rect import android.view.MotionEvent import androidx.dynamicanimation.animation.SpringAnimation import com.android.app.animation.Interpolators.DECELERATE @@ -50,6 +51,7 @@ CONTAINER : RecentsViewContainer { recentsView.pagedOrientationHandler.upDownSwipeDirection, ) private val isRtl = isRtl(container.resources) + private val tempTaskThumbnailBounds = Rect() private var taskBeingDragged: TaskView? = null private var springAnimation: SpringAnimation? = null @@ -108,7 +110,9 @@ CONTAINER : RecentsViewContainer { recentsView.isTaskViewVisible(it) && container.dragLayer.isEventOverView(it, ev) } ?.also { - dismissLength = recentsView.pagedOrientationHandler.getSecondaryDimension(it) + // Dismiss length as bottom of task so it is fully off screen when dismissed. + it.getThumbnailBounds(tempTaskThumbnailBounds, relativeToDragLayer = true) + dismissLength = tempTaskThumbnailBounds.bottom verticalFactor = recentsView.pagedOrientationHandler.secondaryTranslationDirectionFactor } diff --git a/quickstep/src/com/android/quickstep/views/RecentsViewUtils.kt b/quickstep/src/com/android/quickstep/views/RecentsViewUtils.kt index d18a5f7fe8..7b4f4eef5b 100644 --- a/quickstep/src/com/android/quickstep/views/RecentsViewUtils.kt +++ b/quickstep/src/com/android/quickstep/views/RecentsViewUtils.kt @@ -335,8 +335,6 @@ class RecentsViewUtils(private val recentsView: RecentsView<*, *>) { .setStartVelocity(if (detector.isFling(velocity)) velocity else 0f) .addUpdateListener { animation, value, _ -> if (isDismissing && abs(value) >= abs(dismissLength)) { - // TODO(b/393553524): Remove 0 alpha, instead animate task fully off screen. - draggedTaskView.alpha = 0f animation.cancel() } else if (draggedTaskView.isRunningTask && recentsView.enableDrawingLiveTile) { recentsView.runActionOnRemoteHandles { remoteTargetHandle -> diff --git a/quickstep/tests/src/com/android/quickstep/TaplTestsQuickstep.java b/quickstep/tests/src/com/android/quickstep/TaplTestsQuickstep.java index 79d3c19a0f..aaaa0e45da 100644 --- a/quickstep/tests/src/com/android/quickstep/TaplTestsQuickstep.java +++ b/quickstep/tests/src/com/android/quickstep/TaplTestsQuickstep.java @@ -62,6 +62,7 @@ import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; +import java.util.Comparator; import java.util.function.Consumer; import java.util.function.Function; @@ -557,6 +558,27 @@ public class TaplTestsQuickstep extends AbstractQuickStepTest { numTasks == null ? 0 : numTasks, recentsView.getTaskViewCount())); } + @Test + @PortraitLandscape + public void testDismissBottomRow() throws Exception { + assumeTrue(mLauncher.isTablet()); + mLauncher.goHome().switchToOverview().dismissAllTasks(); + startTestAppsWithCheck(); + Overview overview = mLauncher.goHome().switchToOverview(); + assertIsInState("Launcher internal state didn't switch to Overview", + ExpectedState.OVERVIEW); + final Integer numTasks = getFromRecentsView(RecentsView::getTaskViewCount); + OverviewTask bottomTask = overview.getCurrentTasksForTablet().stream().max( + Comparator.comparingInt(OverviewTask::getTaskCenterY)).get(); + assertNotNull("bottomTask null", bottomTask); + + bottomTask.dismiss(); + + runOnRecentsView(recentsView -> assertEquals( + "Dismissing a bottomTask didn't remove 1 bottomTask from Overview", + numTasks - 1, recentsView.getTaskViewCount())); + } + private void startTestAppsWithCheck() throws Exception { startTestApps(); expectLaunchedAppState(); diff --git a/tests/tapl/com/android/launcher3/tapl/OverviewTask.java b/tests/tapl/com/android/launcher3/tapl/OverviewTask.java index 1158521db2..4e94e1e7c6 100644 --- a/tests/tapl/com/android/launcher3/tapl/OverviewTask.java +++ b/tests/tapl/com/android/launcher3/tapl/OverviewTask.java @@ -129,7 +129,7 @@ public final class OverviewTask { return mTask.getVisibleCenter().x; } - int getTaskCenterY() { + public int getTaskCenterY() { return mTask.getVisibleCenter().y; } From 33bf137ee9f87f960e2df5f10391cfa24ecffb1e Mon Sep 17 00:00:00 2001 From: Sunny Goyal Date: Fri, 14 Feb 2025 11:19:35 -0800 Subject: [PATCH 019/153] Changing ThemeManager to take IconControllerFactory as a parameter This allows customizing different parts of ThemeManager independently Bug: 381897614 Flag: com.android.launcher3.extendible_theme_manager Test: Presubmit Change-Id: Iea266793eff47ac54e5c4fcddbab1c36c955dbb7 --- .../launcher3/graphics/ThemeManager.kt | 41 +++++++++++-------- 1 file changed, 24 insertions(+), 17 deletions(-) diff --git a/src/com/android/launcher3/graphics/ThemeManager.kt b/src/com/android/launcher3/graphics/ThemeManager.kt index 4a0ff8c58c..de854601b3 100644 --- a/src/com/android/launcher3/graphics/ThemeManager.kt +++ b/src/com/android/launcher3/graphics/ThemeManager.kt @@ -19,6 +19,7 @@ package com.android.launcher3.graphics import android.content.Context import android.content.res.Resources import com.android.launcher3.EncryptionType +import com.android.launcher3.Item import com.android.launcher3.LauncherPrefChangeListener import com.android.launcher3.LauncherPrefs import com.android.launcher3.LauncherPrefs.Companion.backedUpItem @@ -38,11 +39,12 @@ import javax.inject.Inject /** Centralized class for managing Launcher icon theming */ @LauncherAppSingleton -open class ThemeManager +class ThemeManager @Inject constructor( - @ApplicationContext protected val context: Context, - protected val prefs: LauncherPrefs, + @ApplicationContext private val context: Context, + private val prefs: LauncherPrefs, + private val iconControllerFactory: IconControllerFactory, lifecycle: DaggerSingletonTracker, ) { @@ -72,21 +74,21 @@ constructor( val receiver = SimpleBroadcastReceiver(context, MAIN_EXECUTOR) { verifyIconState() } receiver.registerPkgActions("android", ACTION_OVERLAY_CHANGED) - val prefListener = LauncherPrefChangeListener { key -> - when (key) { - KEY_THEMED_ICONS, - KEY_ICON_SHAPE -> verifyIconState() - } - } - prefs.addListener(prefListener, THEMED_ICONS, PREF_ICON_SHAPE) + val keys = (iconControllerFactory.prefKeys + PREF_ICON_SHAPE) + val keysArray = keys.toTypedArray() + val prefKeySet = keys.map { it.sharedPrefKey } + val prefListener = LauncherPrefChangeListener { key -> + if (prefKeySet.contains(key)) verifyIconState() + } + prefs.addListener(prefListener, *keysArray) lifecycle.addCloseable { receiver.unregisterReceiverSafely() - prefs.removeListener(prefListener) + prefs.removeListener(prefListener, *keysArray) } } - protected fun verifyIconState() { + private fun verifyIconState() { val newState = parseIconState(iconState) if (newState == iconState) return iconState = newState @@ -126,17 +128,13 @@ constructor( return IconState( iconMask = iconMask, folderShapeMask = folderShapeMask, - themeController = createThemeController(), + themeController = iconControllerFactory.createThemeController(), iconScale = shapeModel?.iconScale ?: 1f, iconShape = iconShape, folderShape = folderShape, ) } - protected open fun createThemeController(): IconThemeController? { - return if (isMonoThemeEnabled) MONO_THEME_CONTROLLER else null - } - data class IconState( val iconMask: String, val folderShapeMask: String, @@ -154,6 +152,15 @@ constructor( fun onThemeChanged() } + open class IconControllerFactory @Inject constructor(protected val prefs: LauncherPrefs) { + + open val prefKeys: List = listOf(THEMED_ICONS) + + open fun createThemeController(): IconThemeController? { + return if (prefs.get(THEMED_ICONS)) MONO_THEME_CONTROLLER else null + } + } + companion object { @JvmField val INSTANCE = DaggerSingletonObject(LauncherAppComponent::getThemeManager) From 0072b81db81b1cb4d8d6a7106eb0f43c0e7f08e6 Mon Sep 17 00:00:00 2001 From: Bill Yi Date: Fri, 14 Feb 2025 11:24:24 -0800 Subject: [PATCH 020/153] Import translations. DO NOT MERGE ANYWHERE Auto-generated-cl: translation import Change-Id: I340f82be9a7deae5c0e300455d131e927409bea5 --- quickstep/res/values-de/strings.xml | 2 +- quickstep/res/values-es-rUS/strings.xml | 2 +- quickstep/res/values-gl/strings.xml | 2 +- quickstep/res/values-pt/strings.xml | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/quickstep/res/values-de/strings.xml b/quickstep/res/values-de/strings.xml index e937410f0e..7986a5595f 100644 --- a/quickstep/res/values-de/strings.xml +++ b/quickstep/res/values-de/strings.xml @@ -118,7 +118,7 @@ "Taskleiste immer anzeigen" "Damit die Taskleiste immer unten angezeigt wird, halte den Teiler gedrückt" "Aktionstaste gedrückt halten, um auf dem Bildschirm zu suchen" - "Dieses Produkt verwendet den ausgewählten Teil deines Bildschirms für die Suche. Es gelten die <a href="%1$s">Datenschutzerklärung</a> und die <a href="%2$s">Nutzungsbedingungen</a> von Google." + "Dieses Produkt sucht dann anhand des ausgewählten Teils deines Displays nach weiteren Informationen. Es gelten die <a href="%1$s">Datenschutzerklärung</a> und die <a href="%2$s">Nutzungsbedingungen</a> von Google." "Schließen" "Fertig" "Startbildschirm" diff --git a/quickstep/res/values-es-rUS/strings.xml b/quickstep/res/values-es-rUS/strings.xml index 5ba32126ce..6cd544c3a5 100644 --- a/quickstep/res/values-es-rUS/strings.xml +++ b/quickstep/res/values-es-rUS/strings.xml @@ -118,7 +118,7 @@ "Mostrar siempre la Barra de tareas" "Mantén presionado el divisor para mostrar siempre la Barra de tareas en la parte inferior de la pantalla" "Mantén presionada la tecla de acción para buscar qué hay en la pantalla" - "Este producto usa la parte seleccionada de la pantalla para buscar. Se aplican la <a href="%1$s">Política de Privacidad</a> y las <a href="%2$s">Condiciones del Servicio</a> de Google." + "Este producto usa la parte seleccionada de la pantalla para hacer búsquedas. Se aplican la <a href="%1$s">Política de Privacidad</a> y las <a href="%2$s">Condiciones del Servicio</a> de Google." "Cerrar" "Listo" "Botón de inicio" diff --git a/quickstep/res/values-gl/strings.xml b/quickstep/res/values-gl/strings.xml index edd55d5eee..df665ed959 100644 --- a/quickstep/res/values-gl/strings.xml +++ b/quickstep/res/values-gl/strings.xml @@ -96,7 +96,7 @@ "Compartir" "Facer captura" "Dividir" - "Gardar parella apps" + "Gardar parella de apps" "Para usar a pantalla dividida, toca outra app" "Escolle outra aplicación para usar a pantalla dividida." "Cancelar" diff --git a/quickstep/res/values-pt/strings.xml b/quickstep/res/values-pt/strings.xml index ede50cc7b0..fad3164cfb 100644 --- a/quickstep/res/values-pt/strings.xml +++ b/quickstep/res/values-pt/strings.xml @@ -118,7 +118,7 @@ "Sempre mostrar a Barra de tarefas" "Toque e pressione o divisor para sempre mostrar a Barra de tarefas na parte de baixo da tela" "Toque na tecla de ação e pressione para pesquisar o que está na tela" - "O produto usa a parte selecionada da tela para pesquisar. O uso desses dados está sujeito à <a href="%1$s">Política de Privacidade</a> e aos <a href="%2$s">Termos de Serviço</a> do Google." + "Este produto usa a parte selecionada da tela para pesquisar. O uso desses dados está sujeito à <a href="%1$s">Política de Privacidade</a> e aos <a href="%2$s">Termos de Serviço</a> do Google." "Fechar" "Concluído" "Início" From 1b2fb0b5583b7727f001a24b82dd9da2086ff40c Mon Sep 17 00:00:00 2001 From: Bill Yi Date: Fri, 14 Feb 2025 11:25:10 -0800 Subject: [PATCH 021/153] Import translations. DO NOT MERGE ANYWHERE Auto-generated-cl: translation import Change-Id: Icc34d77c51e6046143fe06f680a2c3fa74949269 --- res/values-lt/strings.xml | 2 +- res/values-or/strings.xml | 2 +- res/values-pa/strings.xml | 2 +- res/values-te/strings.xml | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/res/values-lt/strings.xml b/res/values-lt/strings.xml index bd792acebe..1a4a3f26c4 100644 --- a/res/values-lt/strings.xml +++ b/res/values-lt/strings.xml @@ -28,7 +28,7 @@ "Sparčiojo klavišo negalima naudoti" "Pagrindinis" "Nustatykite „%1$s“ kaip numatytąją pagrindinę programą skiltyje „Nustatymai“" - "Išskaidyto ekrano režimas" + "Išskaidytas ekranas" "Programos „%1$s“ informacija" "„%1$s“ naudojimo nustatymai" "Naujas langas" diff --git a/res/values-or/strings.xml b/res/values-or/strings.xml index 3031259e75..46aadc00fe 100644 --- a/res/values-or/strings.xml +++ b/res/values-or/strings.xml @@ -63,7 +63,7 @@ "ସନ୍ଧାନ କରନ୍ତୁ" "ସନ୍ଧାନ ବାକ୍ସରୁ ଟେକ୍ସଟ୍ ଖାଲି କରନ୍ତୁ" "ୱିଜେଟ୍ ଏବଂ ସର୍ଟକଟଗୁଡ଼ିକ ଉପଲବ୍ଧ ନାହିଁ" - "କୌଣସି ୱିଜେଟ୍ କିମ୍ବା ସର୍ଟକଟ୍ ମିଳିଲା ନାହିଁ" + "କୌଣସି ୱିଜେଟ କିମ୍ବା ସର୍ଟକଟ ମିଳିଲା ନାହିଁ" "ବ୍ୟକ୍ତିଗତ" "ୱାର୍କ" "ବାର୍ତ୍ତାଳାପଗୁଡ଼ିକ" diff --git a/res/values-pa/strings.xml b/res/values-pa/strings.xml index c15e2e9599..17ecb78c66 100644 --- a/res/values-pa/strings.xml +++ b/res/values-pa/strings.xml @@ -94,7 +94,7 @@ "ਕਾਰਜ-ਸਥਾਨ ਸੰਬੰਧੀ ਐਪਾਂ ਦੀ ਸੂਚੀ" "ਹਟਾਓ" "ਅਣਸਥਾਪਤ ਕਰੋ" - "ਐਪ ਜਾਣਕਾਰੀ" + "ਐਪ ਸੰਬੰਧੀ ਜਾਣਕਾਰੀ" "ਪ੍ਰਾਈਵੇਟ ਵਜੋਂ ਸਥਾਪਤ ਕਰੋ" "ਐਪ ਅਣਸਥਾਪਤ ਕਰੋ" "ਸਥਾਪਤ ਕਰੋ" diff --git a/res/values-te/strings.xml b/res/values-te/strings.xml index b6563b00ab..4145fb6433 100644 --- a/res/values-te/strings.xml +++ b/res/values-te/strings.xml @@ -46,14 +46,14 @@ "%1$d వెడల్పు X %2$d ఎత్తు" "%1$s విడ్జెట్" "%1$s విడ్జెట్, %2$d వెడల్పు %3$d ఎత్తు ఉండాలి" - "విడ్జెట్‌ను మొదటి స్క్రీన్‌లో తిప్పడానికి దాన్ని తాకి, & నొక్కి పట్టుకోండి" + "విడ్జెట్‌ను మొదటి స్క్రీన్‌లో అటు, ఇటు కదపడానికి దాన్ని తాకి, నొక్కి పట్టుకోండి" "మొదటి స్క్రీన్‌కు జోడించండి" "మొదటి స్క్రీన్‌కు %1$s విడ్జెట్ జోడించబడింది" "సూచనలు" "నిత్యావసరాలు" "వార్తలు & మ్యాగజైన్లు" "వినోదం" - "సామాజికం" + "సోషల్ మీడియా" "మీ కోసం సూచించినవి" "కుడి వైపున %1$s విడ్జెట్‌లు, ఎడమ వైపున సెర్చ్, ఇతర ఆప్షన్‌లు" "{count,plural, =1{# విడ్జెట్}other{# విడ్జెట్‌లు}}" From 24e65da8b34970286cb60e76d1214113da743250 Mon Sep 17 00:00:00 2001 From: Charlie Anderson Date: Fri, 14 Feb 2025 13:39:57 -0500 Subject: [PATCH 022/153] Temporarily disable shapes flag in image and device dump tests. Will re-enable after more shapes changes, as part of b/396211437 Bug: 396211437 Bug: 395952745 Flag: com.android.launcher3.enable_launcher_icon_shapes Test: Presubmit Change-Id: Ib0c85167df2723632adce9dadae718a2a1b7b757 --- .../src/com/android/launcher3/AbstractDeviceProfileTest.kt | 2 ++ .../com/android/launcher3/nonquickstep/DeviceProfileDumpTest.kt | 1 - 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/multivalentTests/src/com/android/launcher3/AbstractDeviceProfileTest.kt b/tests/multivalentTests/src/com/android/launcher3/AbstractDeviceProfileTest.kt index 9d42e1ba3c..8cdf380314 100644 --- a/tests/multivalentTests/src/com/android/launcher3/AbstractDeviceProfileTest.kt +++ b/tests/multivalentTests/src/com/android/launcher3/AbstractDeviceProfileTest.kt @@ -294,6 +294,8 @@ abstract class AbstractDeviceProfileTest { gridName: String? = GRID_NAME.defaultValue, ) { setFlagsRule.setFlags(true, Flags.FLAG_ENABLE_TWOLINE_TOGGLE) + // TODO: re-enable as part of b/396211437 + setFlagsRule.setFlags(false, Flags.FLAG_ENABLE_LAUNCHER_ICON_SHAPES) val windowsBounds = perDisplayBoundsCache[displayInfo]!! val realBounds = windowsBounds[rotation] whenever(windowManagerProxy.getDisplayInfo(any())).thenReturn(displayInfo) diff --git a/tests/src/com/android/launcher3/nonquickstep/DeviceProfileDumpTest.kt b/tests/src/com/android/launcher3/nonquickstep/DeviceProfileDumpTest.kt index f6e45a381e..05cf926aa1 100644 --- a/tests/src/com/android/launcher3/nonquickstep/DeviceProfileDumpTest.kt +++ b/tests/src/com/android/launcher3/nonquickstep/DeviceProfileDumpTest.kt @@ -40,7 +40,6 @@ class DeviceProfileDumpTest : AbstractDeviceProfileTest() { Flags.FLAG_ENABLE_SCALING_REVEAL_HOME_ANIMATION, ) setFlagsRule.setFlags(false, Flags.FLAG_ONE_GRID_SPECS) - setFlagsRule.setFlags(false, Flags.FLAG_ENABLE_LAUNCHER_ICON_SHAPES) } @Test From 00cccdca4c4e7e0fb4609cdef78341ebceba14b4 Mon Sep 17 00:00:00 2001 From: Sukesh Ram Date: Fri, 14 Feb 2025 12:46:28 -0800 Subject: [PATCH 023/153] [CD Taskbar] Fix - Make Taskbar Icons Launch The base TaskbarUIController returns null for recents view.This makes icons on external display's taskbar unable to launch on external displays. Test: m Bug: 395954042 Flag: com.android.window.flags.enable_taskbar_connected_displays Change-Id: I389a0fa102f63ab93b8a29de722cce0a446a2ea1 --- .../android/launcher3/taskbar/TaskbarActivityContext.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/quickstep/src/com/android/launcher3/taskbar/TaskbarActivityContext.java b/quickstep/src/com/android/launcher3/taskbar/TaskbarActivityContext.java index b9d1275f56..aa1a111be4 100644 --- a/quickstep/src/com/android/launcher3/taskbar/TaskbarActivityContext.java +++ b/quickstep/src/com/android/launcher3/taskbar/TaskbarActivityContext.java @@ -77,6 +77,7 @@ import android.view.WindowInsets; import android.view.WindowManager; import android.widget.FrameLayout; import android.widget.Toast; +import android.window.DesktopExperienceFlags; import android.window.DesktopModeFlags; import android.window.RemoteTransition; @@ -1558,7 +1559,10 @@ public class TaskbarActivityContext extends BaseTaskbarContext { */ private void launchFromInAppTaskbar(@Nullable RecentsView recents, @Nullable View launchingIconView, List itemInfos) { - if (recents == null) { + boolean launchedFromExternalDisplay = + DesktopExperienceFlags.ENABLE_TASKBAR_CONNECTED_DISPLAYS.isTrue() + && !mIsPrimaryDisplay; + if (recents == null && !launchedFromExternalDisplay) { return; } From 768019357fbd2b94aa79cf5f0fdf66c30c00309c Mon Sep 17 00:00:00 2001 From: Mady Mellor Date: Thu, 6 Feb 2025 10:28:08 -0800 Subject: [PATCH 024/153] Allow bubble bar to show on phones if the flag is enabled * Check for bubble bar on phone being enabled in most places tiny taskbar was checking * Forces taskbar to always be stashed when bubble bar is enabled * There are a couple of visual issues with the flag enabled: - extra space in overview - the hotseat is a lil squished on home when bubbles are there Flag: com.android.wm.shell.enable_bubble_bar_on_phones Test: manual - enable bubble bar on phones observe that bubble bar is enabled and kind of works Bug: 394869612 Change-Id: I56d3045c78c6c31dcacf16744033b34c9aa5f6e0 --- .../taskbar/StashedHandleViewController.java | 3 ++- .../launcher3/taskbar/TaskbarActivityContext.java | 11 +++++++++-- .../launcher3/taskbar/TaskbarBackgroundRenderer.kt | 2 +- .../launcher3/taskbar/TaskbarStashController.java | 8 ++++++-- src/com/android/launcher3/DeviceProfile.java | 5 ++++- 5 files changed, 22 insertions(+), 7 deletions(-) diff --git a/quickstep/src/com/android/launcher3/taskbar/StashedHandleViewController.java b/quickstep/src/com/android/launcher3/taskbar/StashedHandleViewController.java index b6b090c39b..2e5bebcb1b 100644 --- a/quickstep/src/com/android/launcher3/taskbar/StashedHandleViewController.java +++ b/quickstep/src/com/android/launcher3/taskbar/StashedHandleViewController.java @@ -119,7 +119,8 @@ public class StashedHandleViewController implements TaskbarControllers.LoggableT mControllers = controllers; DeviceProfile deviceProfile = mActivity.getDeviceProfile(); Resources resources = mActivity.getResources(); - if (mActivity.isPhoneGestureNavMode() || mActivity.isTinyTaskbar()) { + if (mActivity.isPhoneGestureNavMode() || mActivity.isTinyTaskbar() + || mActivity.isBubbleBarOnPhone()) { mTaskbarSize = resources.getDimensionPixelSize(R.dimen.taskbar_phone_size); mStashedHandleWidth = resources.getDimensionPixelSize(R.dimen.taskbar_stashed_small_screen); diff --git a/quickstep/src/com/android/launcher3/taskbar/TaskbarActivityContext.java b/quickstep/src/com/android/launcher3/taskbar/TaskbarActivityContext.java index 11cc22dfa9..f8821feb8a 100644 --- a/quickstep/src/com/android/launcher3/taskbar/TaskbarActivityContext.java +++ b/quickstep/src/com/android/launcher3/taskbar/TaskbarActivityContext.java @@ -47,6 +47,8 @@ import static com.android.quickstep.util.AnimUtils.completeRunnableListCallback; import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_NOTIFICATION_PANEL_VISIBLE; import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_VOICE_INTERACTION_WINDOW_SHOWING; import static com.android.window.flags.Flags.enableStartLaunchTransitionFromTaskbarBugfix; +import static com.android.wm.shell.Flags.enableBubbleBar; +import static com.android.wm.shell.Flags.enableBubbleBarOnPhones; import static com.android.wm.shell.Flags.enableTinyTaskbar; import static java.lang.invoke.MethodHandles.Lookup.PROTECTED; @@ -298,9 +300,10 @@ public class TaskbarActivityContext extends BaseTaskbarContext { // If Bubble bar is present, TaskbarControllers depends on it so build it first. Optional bubbleControllersOptional = Optional.empty(); BubbleBarController.onTaskbarRecreated(); + final boolean deviceBubbleBarEnabled = enableBubbleBarOnPhones() + || (!mDeviceProfile.isPhone && !mDeviceProfile.isVerticalBarLayout()); if (BubbleBarController.isBubbleBarEnabled() - && !mDeviceProfile.isPhone - && !mDeviceProfile.isVerticalBarLayout() + && deviceBubbleBarEnabled && bubbleBarView != null ) { Optional bubbleHandleController = Optional.empty(); @@ -512,6 +515,10 @@ public class TaskbarActivityContext extends BaseTaskbarContext { return enableTinyTaskbar() && mDeviceProfile.isPhone && mDeviceProfile.isTaskbarPresent; } + public boolean isBubbleBarOnPhone() { + return enableBubbleBarOnPhones() && enableBubbleBar() && mDeviceProfile.isPhone; + } + /** * Returns {@code true} iff bubble bar is enabled (but not necessarily visible / * containing bubbles). diff --git a/quickstep/src/com/android/launcher3/taskbar/TaskbarBackgroundRenderer.kt b/quickstep/src/com/android/launcher3/taskbar/TaskbarBackgroundRenderer.kt index e44bce1a07..6d238530a4 100644 --- a/quickstep/src/com/android/launcher3/taskbar/TaskbarBackgroundRenderer.kt +++ b/quickstep/src/com/android/launcher3/taskbar/TaskbarBackgroundRenderer.kt @@ -108,7 +108,7 @@ class TaskbarBackgroundRenderer(private val context: TaskbarActivityContext) { fun updateStashedHandleWidth(context: TaskbarActivityContext, res: Resources) { stashedHandleWidth = res.getDimensionPixelSize( - if (context.isPhoneMode || context.isTinyTaskbar) { + if (context.isPhoneMode || context.isTinyTaskbar || context.isBubbleBarOnPhone) { R.dimen.taskbar_stashed_small_screen } else { R.dimen.taskbar_stashed_handle_width diff --git a/quickstep/src/com/android/launcher3/taskbar/TaskbarStashController.java b/quickstep/src/com/android/launcher3/taskbar/TaskbarStashController.java index 6016394c60..95724ad6d2 100644 --- a/quickstep/src/com/android/launcher3/taskbar/TaskbarStashController.java +++ b/quickstep/src/com/android/launcher3/taskbar/TaskbarStashController.java @@ -104,6 +104,8 @@ public class TaskbarStashController implements TaskbarControllers.LoggableTaskba private static final int FLAG_DELAY_TASKBAR_BG_TAG = 1 << 12; public static final int FLAG_STASHED_FOR_BUBBLES = 1 << 13; // show handle for stashed hotseat public static final int FLAG_TASKBAR_HIDDEN = 1 << 14; // taskbar hidden during dream, etc... + // taskbar should always be stashed for bubble bar on phone + public static final int FLAG_STASHED_BUBBLE_BAR_ON_PHONE = 1 << 15; // If any of these flags are enabled, isInApp should return true. private static final int FLAGS_IN_APP = FLAG_IN_APP | FLAG_IN_SETUP; @@ -126,7 +128,7 @@ public class TaskbarStashController implements TaskbarControllers.LoggableTaskba // If any of these flags are enabled, the taskbar must be stashed. private static final int FLAGS_FORCE_STASHED = FLAG_STASHED_SYSUI | FLAG_STASHED_DEVICE_LOCKED | FLAG_STASHED_IN_TASKBAR_ALL_APPS | FLAG_STASHED_SMALL_SCREEN - | FLAG_STASHED_FOR_BUBBLES; + | FLAG_STASHED_FOR_BUBBLES | FLAG_STASHED_BUBBLE_BAR_ON_PHONE; /** * How long to stash/unstash when manually invoked via long press. @@ -359,6 +361,7 @@ public class TaskbarStashController implements TaskbarControllers.LoggableTaskba // For now, assume we're in an app, since LauncherTaskbarUIController won't be able to tell // us that we're paused until a bit later. This avoids flickering upon recreating taskbar. updateStateForFlag(FLAG_IN_APP, true); + updateStateForFlag(FLAG_STASHED_BUBBLE_BAR_ON_PHONE, mActivity.isBubbleBarOnPhone()); applyState(/* duration = */ 0); @@ -574,7 +577,8 @@ public class TaskbarStashController implements TaskbarControllers.LoggableTaskba */ public void updateAndAnimateTransientTaskbar(boolean stash, boolean shouldBubblesFollow, boolean delayTaskbarBackground) { - if (!DisplayController.isTransientTaskbar(mActivity)) { + if (!DisplayController.isTransientTaskbar(mActivity) + || mActivity.isBubbleBarOnPhone()) { return; } diff --git a/src/com/android/launcher3/DeviceProfile.java b/src/com/android/launcher3/DeviceProfile.java index f34add8d3f..456150684a 100644 --- a/src/com/android/launcher3/DeviceProfile.java +++ b/src/com/android/launcher3/DeviceProfile.java @@ -31,6 +31,7 @@ import static com.android.launcher3.testing.shared.ResourceUtils.pxFromDp; import static com.android.launcher3.testing.shared.ResourceUtils.roundPxValueFromFloat; import static com.android.wm.shell.Flags.enableBubbleBar; import static com.android.wm.shell.Flags.enableTinyTaskbar; +import static com.android.wm.shell.Flags.enableBubbleBarOnPhones; import android.annotation.SuppressLint; import android.content.Context; @@ -420,7 +421,9 @@ public class DeviceProfile { isTablet = info.isTablet(windowBounds); isPhone = !isTablet; isTwoPanels = isTablet && isMultiDisplay; - isTaskbarPresent = (isTablet || (enableTinyTaskbar() && isGestureMode)) + boolean taskbarOrBubbleBarOnPhones = enableTinyTaskbar() + || (enableBubbleBar() && enableBubbleBarOnPhones()); + isTaskbarPresent = (isTablet || (taskbarOrBubbleBarOnPhones && isGestureMode)) && wmProxy.isTaskbarDrawnInProcess(); // Some more constants. From 62f205b9e4880faf08261be8058701656283f0b7 Mon Sep 17 00:00:00 2001 From: Andy Wickham Date: Fri, 14 Feb 2025 02:01:00 +0000 Subject: [PATCH 025/153] Fix performance regressions with handheld apps panel. Theory: We are now rendering the wallpaper and workspace while All Apps is open. This is causing additional rendering to be done, leading to dropped frames and other regressions. Here I remove workspace/hotseat on phones where the panel will fully cover them anyway. I also remove the depth controller during the all apps transition. Using the "debug overdraw" developer setting, I verified that Workspace and Hotseat are not drawn below the All Apps panel on handheld. I ran ABTD on this change and verified the p95 dropped frames went back to 0. Bug: 393188362 Bug: 393088056 Test: abtd commands in the bug Flag: com.android.launcher3.all_apps_sheet_for_handheld Change-Id: I47287f3356d401a3bd4202e61fd44199855a4a3c --- .../launcher3/uioverrides/states/AllAppsState.java | 4 ++-- .../launcher3/touch/AllAppsSwipeController.java | 10 ++++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/quickstep/src/com/android/launcher3/uioverrides/states/AllAppsState.java b/quickstep/src/com/android/launcher3/uioverrides/states/AllAppsState.java index 10513c08c6..b27c6e8381 100644 --- a/quickstep/src/com/android/launcher3/uioverrides/states/AllAppsState.java +++ b/quickstep/src/com/android/launcher3/uioverrides/states/AllAppsState.java @@ -153,7 +153,7 @@ public class AllAppsState extends LauncherState { return new PageAlphaProvider(DECELERATE_2) { @Override public float getPageAlpha(int pageIndex) { - return launcher.getDeviceProfile().shouldShowAllAppsOnSheet() + return launcher.getDeviceProfile().isTablet ? superPageAlphaProvider.getPageAlpha(pageIndex) : 0; } @@ -164,7 +164,7 @@ public class AllAppsState extends LauncherState { public int getVisibleElements(Launcher launcher) { int elements = ALL_APPS_CONTENT | FLOATING_SEARCH_BAR; // When All Apps is presented on a bottom sheet, HOTSEAT_ICONS are visible. - if (launcher.getDeviceProfile().shouldShowAllAppsOnSheet()) { + if (launcher.getDeviceProfile().isTablet) { elements |= HOTSEAT_ICONS; } return elements; diff --git a/src/com/android/launcher3/touch/AllAppsSwipeController.java b/src/com/android/launcher3/touch/AllAppsSwipeController.java index 107bcc1226..2cc4909712 100644 --- a/src/com/android/launcher3/touch/AllAppsSwipeController.java +++ b/src/com/android/launcher3/touch/AllAppsSwipeController.java @@ -207,6 +207,11 @@ public class AllAppsSwipeController extends AbstractStateChangeTouchController { } config.setInterpolator(ANIM_WORKSPACE_SCALE, DECELERATED_EASE); config.setInterpolator(ANIM_DEPTH, DECELERATED_EASE); + if (launcher.getDeviceProfile().isPhone) { + config.setInterpolator(ANIM_WORKSPACE_FADE, INSTANT); + config.setInterpolator(ANIM_HOTSEAT_FADE, INSTANT); + config.animFlags |= StateAnimationConfig.SKIP_DEPTH_CONTROLLER; + } } else { if (config.isUserControlled()) { config.setInterpolator(ANIM_DEPTH, Interpolators.reverse(BLUR_MANUAL)); @@ -248,6 +253,11 @@ public class AllAppsSwipeController extends AbstractStateChangeTouchController { } config.setInterpolator(ANIM_WORKSPACE_SCALE, DECELERATED_EASE); config.setInterpolator(ANIM_DEPTH, DECELERATED_EASE); + if (launcher.getDeviceProfile().isPhone) { + config.setInterpolator(ANIM_WORKSPACE_FADE, FINAL_FRAME); + config.setInterpolator(ANIM_HOTSEAT_FADE, FINAL_FRAME); + config.animFlags |= StateAnimationConfig.SKIP_DEPTH_CONTROLLER; + } } else { config.setInterpolator(ANIM_DEPTH, config.isUserControlled() ? BLUR_MANUAL : BLUR_ATOMIC); From e6036ab358e7f07b4b4aa304f9513e8b77b1f52b Mon Sep 17 00:00:00 2001 From: Saumya Prakash Date: Fri, 14 Feb 2025 23:26:16 +0000 Subject: [PATCH 026/153] Update Taskbar edu with new font style This change applies the new expressive font style if the expressive theme is enabled. Screenshots are available in the bug Fix: 393610004 Test: Check that the fonts change when the expresssive theme is enabled Flag: com.android.launcher3.expressive_theme_in_taskbar_and_navigation Change-Id: I5fa34ab08486c7fdeb37ccd9afeda77b577a9404 --- quickstep/res/layout/taskbar_edu_features.xml | 8 ++-- quickstep/res/layout/taskbar_edu_pinning.xml | 4 +- quickstep/res/layout/taskbar_edu_search.xml | 4 +- quickstep/res/layout/taskbar_edu_swipe.xml | 4 +- .../taskbar/TaskbarEduTooltipController.kt | 37 +++++++++++++++++++ .../launcher3/taskbar/TypefaceUtils.kt | 3 ++ 6 files changed, 50 insertions(+), 10 deletions(-) diff --git a/quickstep/res/layout/taskbar_edu_features.xml b/quickstep/res/layout/taskbar_edu_features.xml index a7bd184a9f..aa1312e53d 100644 --- a/quickstep/res/layout/taskbar_edu_features.xml +++ b/quickstep/res/layout/taskbar_edu_features.xml @@ -20,7 +20,7 @@ android:layout_height="wrap_content"> + app:layout_constraintTop_toBottomOf="@id/taskbar_edu_title" /> + app:layout_constraintTop_toBottomOf="@id/taskbar_edu_title" /> + app:layout_constraintTop_toBottomOf="@id/taskbar_edu_title" /> diff --git a/quickstep/res/layout/taskbar_edu_search.xml b/quickstep/res/layout/taskbar_edu_search.xml index ca84f351ce..ec4d4b4adc 100644 --- a/quickstep/res/layout/taskbar_edu_search.xml +++ b/quickstep/res/layout/taskbar_edu_search.xml @@ -19,7 +19,7 @@ android:layout_height="wrap_content"> diff --git a/quickstep/res/layout/taskbar_edu_swipe.xml b/quickstep/res/layout/taskbar_edu_swipe.xml index 3f5e81919e..9b4809e97c 100644 --- a/quickstep/res/layout/taskbar_edu_swipe.xml +++ b/quickstep/res/layout/taskbar_edu_swipe.xml @@ -19,7 +19,7 @@ android:layout_height="wrap_content"> diff --git a/quickstep/src/com/android/launcher3/taskbar/TaskbarEduTooltipController.kt b/quickstep/src/com/android/launcher3/taskbar/TaskbarEduTooltipController.kt index 26a552e80f..b4ffb744df 100644 --- a/quickstep/src/com/android/launcher3/taskbar/TaskbarEduTooltipController.kt +++ b/quickstep/src/com/android/launcher3/taskbar/TaskbarEduTooltipController.kt @@ -141,6 +141,10 @@ open class TaskbarEduTooltipController(context: Context) : tooltipStep = TOOLTIP_STEP_FEATURES inflateTooltip(R.layout.taskbar_edu_swipe) tooltip?.run { + TypefaceUtils.setTypeface( + requireViewById(R.id.taskbar_edu_title), + TypefaceUtils.FONT_FAMILY_HEADLINE_SMALL_EMPHASIZED, + ) requireViewById(R.id.swipe_animation).supportLightTheme() show() } @@ -180,6 +184,23 @@ open class TaskbarEduTooltipController(context: Context) : pinningEdu.visibility = GONE } + TypefaceUtils.setTypeface( + requireViewById(R.id.taskbar_edu_title), + TypefaceUtils.FONT_FAMILY_HEADLINE_SMALL_EMPHASIZED, + ) + TypefaceUtils.setTypeface( + requireViewById(R.id.splitscreen_text), + TypefaceUtils.FONT_FAMILY_BODY_MEDIUM_BASELINE, + ) + TypefaceUtils.setTypeface( + requireViewById(R.id.suggestions_text), + TypefaceUtils.FONT_FAMILY_BODY_MEDIUM_BASELINE, + ) + TypefaceUtils.setTypeface( + requireViewById(R.id.pinning_text), + TypefaceUtils.FONT_FAMILY_BODY_MEDIUM_BASELINE, + ) + // Set up layout parameters. content.updateLayoutParams { width = MATCH_PARENT } updateLayoutParams { @@ -231,6 +252,15 @@ open class TaskbarEduTooltipController(context: Context) : requireViewById(R.id.standalone_pinning_animation) .supportLightTheme() + TypefaceUtils.setTypeface( + requireViewById(R.id.taskbar_edu_title), + TypefaceUtils.FONT_FAMILY_HEADLINE_SMALL_EMPHASIZED, + ) + TypefaceUtils.setTypeface( + requireViewById(R.id.pinning_text), + TypefaceUtils.FONT_FAMILY_BODY_MEDIUM_BASELINE, + ) + updateLayoutParams { if (DisplayController.isTransientTaskbar(activityContext)) { bottomMargin += activityContext.deviceProfile.taskbarHeight @@ -276,6 +306,13 @@ open class TaskbarEduTooltipController(context: Context) : allowTouchDismissal = true requireViewById(R.id.search_edu_animation).supportLightTheme() val eduSubtitle: TextView = requireViewById(R.id.search_edu_text) + + TypefaceUtils.setTypeface( + requireViewById(R.id.taskbar_edu_title), + TypefaceUtils.FONT_FAMILY_HEADLINE_SMALL_EMPHASIZED, + ) + TypefaceUtils.setTypeface(eduSubtitle, TypefaceUtils.FONT_FAMILY_BODY_SMALL_BASELINE) + showDisclosureText(eduSubtitle) updateLayoutParams { if (DisplayController.isTransientTaskbar(activityContext)) { diff --git a/quickstep/src/com/android/launcher3/taskbar/TypefaceUtils.kt b/quickstep/src/com/android/launcher3/taskbar/TypefaceUtils.kt index fa551b84ad..8b53ff192a 100644 --- a/quickstep/src/com/android/launcher3/taskbar/TypefaceUtils.kt +++ b/quickstep/src/com/android/launcher3/taskbar/TypefaceUtils.kt @@ -30,7 +30,10 @@ import com.android.launcher3.Flags class TypefaceUtils { companion object { + const val FONT_FAMILY_HEADLINE_SMALL_EMPHASIZED = "variable-headline-small-emphasized" const val FONT_FAMILY_HEADLINE_LARGE_EMPHASIZED = "variable-headline-large-emphasized" + const val FONT_FAMILY_BODY_SMALL_BASELINE = "variable-body-small" + const val FONT_FAMILY_BODY_MEDIUM_BASELINE = "variable-body-medium" const val FONT_FAMILY_LABEL_LARGE_BASELINE = "variable-label-large" @JvmStatic From 1189ee33c6295298479c9d2f947c180a6e3fd614 Mon Sep 17 00:00:00 2001 From: David Stevens Date: Fri, 27 Sep 2024 14:55:06 +0900 Subject: [PATCH 027/153] Mark tasks on launcher as perceptible Mark all tasks on launcher as perceptible tasks. Flag enablement is for desktop devices only. Bug: 370890207 Test: Manual Flag: com.android.server.am.perceptible_tasks Change-Id: Ic9022dcb07f2fc2d1bd1277bc1a83233ebc5626e --- .../launcher3/taskbar/TaskbarManager.java | 78 +++++++++++++++++++ 1 file changed, 78 insertions(+) diff --git a/quickstep/src/com/android/launcher3/taskbar/TaskbarManager.java b/quickstep/src/com/android/launcher3/taskbar/TaskbarManager.java index 46802c3f9e..ce1ddd0e33 100644 --- a/quickstep/src/com/android/launcher3/taskbar/TaskbarManager.java +++ b/quickstep/src/com/android/launcher3/taskbar/TaskbarManager.java @@ -45,6 +45,7 @@ import android.net.Uri; import android.os.Handler; import android.os.Trace; import android.provider.Settings; +import android.util.ArraySet; import android.util.Log; import android.util.SparseArray; import android.util.SparseBooleanArray; @@ -75,14 +76,20 @@ import com.android.quickstep.SystemUiProxy; import com.android.quickstep.fallback.window.RecentsDisplayModel; import com.android.quickstep.fallback.window.RecentsWindowManager; import com.android.quickstep.util.ContextualSearchInvoker; +import com.android.quickstep.util.GroupTask; import com.android.quickstep.views.RecentsViewContainer; +import com.android.systemui.shared.recents.model.Task; import com.android.systemui.shared.statusbar.phone.BarTransitions; +import com.android.systemui.shared.system.ActivityManagerWrapper; import com.android.systemui.shared.system.QuickStepContract; import com.android.systemui.shared.system.QuickStepContract.SystemUiStateFlags; +import com.android.systemui.shared.system.TaskStackChangeListener; +import com.android.systemui.shared.system.TaskStackChangeListeners; import com.android.systemui.unfold.UnfoldTransitionProgressProvider; import com.android.systemui.unfold.util.ScopedUnfoldTransitionProgressProvider; import java.io.PrintWriter; +import java.util.Set; import java.util.StringJoiner; /** @@ -194,6 +201,65 @@ public class TaskbarManager { recreateTaskbar(); }; + private final PerceptibleTaskListener mTaskStackListener; + + private class PerceptibleTaskListener implements TaskStackChangeListener { + private ArraySet mPerceptibleTasks = new ArraySet(); + + @Override + public void onTaskMovedToFront(int taskId) { + if (mPerceptibleTasks.contains(taskId)) { + return; + } + + // This listens to any Task, so we filter them by the ones shown in the launcher. + // For Tasks restored after startup, they will by default not be Perceptible, and no + // need to until user interacts with it by bringing it to the foreground. + for (int i = 0; i < mTaskbars.size(); i++) { + // get pinned tasks + Set taskbarPinnedTasks = + mTaskbars.valueAt(i).getControllers().taskbarViewController + .getTaskIdsForPinnedApps(); + + // mark as perceptible if the foregrounded task is in the list of apps shown in + // the launcher. + if (taskbarPinnedTasks.contains(taskId) + && ActivityManagerWrapper.getInstance() + .setTaskIsPerceptible(taskId, true) + ) { + mPerceptibleTasks.add(taskId); + } + } + } + + /** + * Launcher also can display recently launched tasks that are not pinned. Also add + * these as perceptible + */ + @Override + public void onRecentTaskListUpdated() { + for (int i = 0; i < mTaskbars.size(); i++) { + for (GroupTask gTask : mTaskbars.valueAt(i).getControllers() + .taskbarRecentAppsController.getShownTasks()) { + for (Task task : gTask.getTasks()) { + int taskId = task.key.id; + + if (!mPerceptibleTasks.contains(taskId)) { + ActivityManagerWrapper.getInstance() + .setTaskIsPerceptible(taskId, true); + mPerceptibleTasks.add(taskId); + } + } + } + } + } + + @Override + public void onTaskRemoved(int taskId) { + mPerceptibleTasks.remove(taskId); + } + }; + private boolean mUserUnlocked = false; private final SimpleBroadcastReceiver mTaskbarBroadcastReceiver; @@ -296,6 +362,12 @@ public class TaskbarManager { mTaskbarBroadcastReceiver.register(RECEIVER_NOT_EXPORTED, ACTION_SHOW_TASKBAR); }); + if (ActivityManagerWrapper.usePerceptibleTasks(getPrimaryWindowContext())) { + mTaskStackListener = new PerceptibleTaskListener(); + TaskStackChangeListeners.getInstance().registerTaskStackListener(mTaskStackListener); + } else { + mTaskStackListener = null; + } debugTaskbarManager("TaskbarManager created"); recreateTaskbar(); } @@ -784,6 +856,12 @@ public class TaskbarManager { Log.d(TASKBAR_NOT_DESTROYED_TAG, "unregistering component callbacks from destroy()."); removeAndUnregisterComponentCallbacks(getDefaultDisplayId()); mShutdownReceiver.unregisterReceiverSafely(); + if (ActivityManagerWrapper.usePerceptibleTasks(getPrimaryWindowContext())) { + for (Integer taskId: mTaskStackListener.mPerceptibleTasks) { + ActivityManagerWrapper.getInstance().setTaskIsPerceptible(taskId, false); + } + } + TaskStackChangeListeners.getInstance().unregisterTaskStackListener(mTaskStackListener); destroyAllTaskbars(); } From c7106806f13518f1f7cbef9ff3525838fe600178 Mon Sep 17 00:00:00 2001 From: mpodolian Date: Tue, 11 Feb 2025 15:39:42 -0800 Subject: [PATCH 028/153] Made the bubble bar react to drag events from the Shell. Added logic to show and hide the bubble bar drop target on Shell drag-and-drop events. Test: Manual. Drag a shortcut or an application icon from the taskbar to the bubble bar drop zone. Observe that if the bubble bar is showing bubbles, the background stroke color becomes non-transparent; if there are no bubbles, the drop zone appears. Drag the app icon to the opposite side and observe that the bubble bar location is animated or the drop zone appears on the dragged side. Drop the application icon or shortcut on any side and observe that a new bubble is added and immediately expanded. Additionally, the bubble bar remains at the drop location. expanded. Bug: 388894910 Flag: com.android.wm.shell.enable_create_any_bubble Change-Id: I581dddf2c76ac982a5c78bc32d94b79bf63fd2b9 --- .../taskbar/TaskbarDragController.java | 28 ++++++++- .../taskbar/bubbles/BubbleBarBackground.kt | 23 +++++++- .../taskbar/bubbles/BubbleBarController.java | 22 +++++-- .../taskbar/bubbles/BubbleBarView.java | 10 ++++ .../bubbles/BubbleBarViewController.java | 59 ++++++++++++++++++- 5 files changed, 132 insertions(+), 10 deletions(-) diff --git a/quickstep/src/com/android/launcher3/taskbar/TaskbarDragController.java b/quickstep/src/com/android/launcher3/taskbar/TaskbarDragController.java index 3a83db2959..4b709ac92e 100644 --- a/quickstep/src/com/android/launcher3/taskbar/TaskbarDragController.java +++ b/quickstep/src/com/android/launcher3/taskbar/TaskbarDragController.java @@ -51,6 +51,7 @@ import android.view.ViewRootImpl; import android.window.SurfaceSyncGroup; import androidx.annotation.Nullable; +import androidx.annotation.VisibleForTesting; import com.android.app.animation.Interpolators; import com.android.internal.logging.InstanceId; @@ -74,6 +75,7 @@ import com.android.launcher3.model.data.WorkspaceItemInfo; import com.android.launcher3.popup.PopupContainerWithArrow; import com.android.launcher3.shortcuts.DeepShortcutView; import com.android.launcher3.shortcuts.ShortcutDragPreviewProvider; +import com.android.launcher3.taskbar.bubbles.BubbleBarViewController; import com.android.launcher3.testing.TestLogging; import com.android.launcher3.testing.shared.TestProtocol; import com.android.launcher3.util.DisplayController; @@ -511,6 +513,7 @@ public class TaskbarDragController extends DragController im return mIsSystemDragInProgress; } + @VisibleForTesting private void maybeOnDragEnd() { if (!isDragging()) { ((BubbleTextView) mDragObject.originalView).setIconDisabled(false); @@ -518,17 +521,38 @@ public class TaskbarDragController extends DragController im TaskbarAutohideSuspendController.FLAG_AUTOHIDE_SUSPEND_DRAGGING, false); mActivity.onDragEnd(); if (mReturnAnimator == null) { + // If an item is dropped on the bubble bar, the bubble bar handles the drop, + // so it should not collapse along with the taskbar. + boolean droppedOnBubbleBar = notifyBubbleBarItemDropped(); // Upon successful drag, immediately stash taskbar. // Note, this must be done last to ensure no AutohideSuspendFlags are active, as // that will prevent us from stashing until the timeout. - mControllers.taskbarStashController.updateAndAnimateTransientTaskbar(true); - + mControllers.taskbarStashController.updateAndAnimateTransientTaskbar( + /* stash = */ true, + /* shouldBubblesFollow = */ !droppedOnBubbleBar + ); mActivity.getStatsLogManager().logger().withItemInfo(mDragObject.dragInfo) .log(LAUNCHER_APP_LAUNCH_DRAGDROP); } } } + /** + * Exits the Bubble Bar drop target mode if applicable. + * + * @return {@code true} if drop target mode was active. + */ + private boolean notifyBubbleBarItemDropped() { + return mControllers.bubbleControllers.map(bc -> { + BubbleBarViewController bubbleBarViewController = bc.bubbleBarViewController; + boolean showingDropTarget = bubbleBarViewController.isShowingDropTarget(); + if (showingDropTarget) { + bubbleBarViewController.onItemDroppedInBubbleBarDragZone(); + } + return showingDropTarget; + }).orElse(false); + } + @Override protected void endDrag() { if (mDisallowGlobalDrag) { diff --git a/quickstep/src/com/android/launcher3/taskbar/bubbles/BubbleBarBackground.kt b/quickstep/src/com/android/launcher3/taskbar/bubbles/BubbleBarBackground.kt index 249773d3df..97be2e87b1 100644 --- a/quickstep/src/com/android/launcher3/taskbar/bubbles/BubbleBarBackground.kt +++ b/quickstep/src/com/android/launcher3/taskbar/bubbles/BubbleBarBackground.kt @@ -44,10 +44,13 @@ class BubbleBarBackground(context: Context, private var backgroundHeight: Float) private val arrowVisibleHeight: Float private val strokeAlpha: Int + private val strokeColor: Int + private val strokeColorDropTarget: Int private val shadowAlpha: Int private val shadowBlur: Float private val keyShadowDistance: Float private var arrowHeightFraction = 1f + private var isShowingDropTarget: Boolean = false var arrowPositionX: Float = 0f private set @@ -100,7 +103,9 @@ class BubbleBarBackground(context: Context, private var backgroundHeight: Float) fillPaint.flags = Paint.ANTI_ALIAS_FLAG fillPaint.style = Paint.Style.FILL // configure stroke paint - strokePaint.color = context.getColor(R.color.taskbar_stroke) + strokeColor = context.getColor(R.color.taskbar_stroke) + strokeColorDropTarget = context.getColor(com.android.internal.R.color.system_primary_fixed) + strokePaint.color = strokeColor strokePaint.flags = Paint.ANTI_ALIAS_FLAG strokePaint.style = Paint.Style.STROKE strokePaint.strokeWidth = res.getDimension(R.dimen.transient_taskbar_stroke_width) @@ -235,9 +240,25 @@ class BubbleBarBackground(context: Context, private var backgroundHeight: Float) return max(0f, getScaledArrowHeight() - (arrowHeight - arrowVisibleHeight)) } + /** Set whether the background should show the drop target */ + fun showDropTarget(isDropTarget: Boolean) { + if (isShowingDropTarget == isDropTarget) { + return + } + isShowingDropTarget = isDropTarget + val strokeColor = if (isDropTarget) strokeColorDropTarget else strokeColor + val alpha = if (isDropTarget) DRAG_STROKE_ALPHA else strokeAlpha + strokePaint.color = strokeColor + strokePaint.alpha = alpha + invalidateSelf() + } + + fun isShowingDropTarget() = isShowingDropTarget + companion object { private const val DARK_THEME_STROKE_ALPHA = 51 private const val LIGHT_THEME_STROKE_ALPHA = 41 + private const val DRAG_STROKE_ALPHA = 255 private const val DARK_THEME_SHADOW_ALPHA = 51 private const val LIGHT_THEME_SHADOW_ALPHA = 25 } diff --git a/quickstep/src/com/android/launcher3/taskbar/bubbles/BubbleBarController.java b/quickstep/src/com/android/launcher3/taskbar/bubbles/BubbleBarController.java index 4e029e32be..5ddbe032f9 100644 --- a/quickstep/src/com/android/launcher3/taskbar/bubbles/BubbleBarController.java +++ b/quickstep/src/com/android/launcher3/taskbar/bubbles/BubbleBarController.java @@ -33,7 +33,8 @@ import android.os.Bundle; import android.os.SystemProperties; import android.util.ArrayMap; import android.util.Log; -import android.widget.Toast; + +import androidx.annotation.NonNull; import com.android.launcher3.taskbar.TaskbarSharedState; import com.android.launcher3.taskbar.bubbles.stashing.BubbleStashController; @@ -589,15 +590,24 @@ public class BubbleBarController extends IBubblesListener.Stub { } @Override - public void onDragItemOverBubbleBarDragZone(BubbleBarLocation location) { - //TODO(b/388894910): add meaningful implementation - MAIN_EXECUTOR.execute(() -> - Toast.makeText(mContext, "onDragItemOver " + location, Toast.LENGTH_SHORT).show()); + public void onDragItemOverBubbleBarDragZone(@NonNull BubbleBarLocation bubbleBarLocation) { + MAIN_EXECUTOR.execute(() -> { + mBubbleBarViewController.onDragItemOverBubbleBarDragZone(bubbleBarLocation); + if (mBubbleBarViewController.isLocationUpdatedForDropTarget()) { + mBubbleBarLocationListener.onBubbleBarLocationAnimated(bubbleBarLocation); + } + }); } @Override public void onItemDraggedOutsideBubbleBarDropZone() { - + MAIN_EXECUTOR.execute(() -> { + if (mBubbleBarViewController.isLocationUpdatedForDropTarget()) { + BubbleBarLocation original = mBubbleBarViewController.getBubbleBarLocation(); + mBubbleBarLocationListener.onBubbleBarLocationAnimated(original); + } + mBubbleBarViewController.onItemDraggedOutsideBubbleBarDropZone(); + }); } /** Notifies WMShell to show the expanded view. */ diff --git a/quickstep/src/com/android/launcher3/taskbar/bubbles/BubbleBarView.java b/quickstep/src/com/android/launcher3/taskbar/bubbles/BubbleBarView.java index c00112383b..d43ebe2977 100644 --- a/quickstep/src/com/android/launcher3/taskbar/bubbles/BubbleBarView.java +++ b/quickstep/src/com/android/launcher3/taskbar/bubbles/BubbleBarView.java @@ -536,6 +536,16 @@ public class BubbleBarView extends FrameLayout { return (float) (displayWidth - getWidth() - margin); } + /** Set whether the background should show the drop target */ + public void showDropTarget(boolean isDropTarget) { + mBubbleBarBackground.showDropTarget(isDropTarget); + } + + /** Returns whether the Bubble Bar is currently displaying a drop target. */ + public boolean isShowingDropTarget() { + return mBubbleBarBackground.isShowingDropTarget(); + } + /** * Animate bubble bar to the given location transiently. Does not modify the layout or the value * returned by {@link #getBubbleBarLocation()}. diff --git a/quickstep/src/com/android/launcher3/taskbar/bubbles/BubbleBarViewController.java b/quickstep/src/com/android/launcher3/taskbar/bubbles/BubbleBarViewController.java index 026f239152..b02b85fad4 100644 --- a/quickstep/src/com/android/launcher3/taskbar/bubbles/BubbleBarViewController.java +++ b/quickstep/src/com/android/launcher3/taskbar/bubbles/BubbleBarViewController.java @@ -131,12 +131,13 @@ public class BubbleBarViewController { // Whether the bar is hidden when stashed private boolean mHiddenForStashed; private boolean mShouldShowEducation; - public boolean mOverflowAdded; + private boolean mIsLocationUpdatedForDropTarget = false; private BubbleBarViewAnimator mBubbleBarViewAnimator; private final FrameLayout mBubbleBarContainer; private BubbleBarFlyoutController mBubbleBarFlyoutController; + private BubbleBarPinController mBubbleBarPinController; private TaskbarSharedState mTaskbarSharedState; private final TimeSource mTimeSource = System::currentTimeMillis; private final int mTaskbarTranslationDelta; @@ -166,6 +167,7 @@ public class BubbleBarViewController { mBubbleStashController = bubbleControllers.bubbleStashController; mBubbleBarController = bubbleControllers.bubbleBarController; mBubbleDragController = bubbleControllers.bubbleDragController; + mBubbleBarPinController = bubbleControllers.bubbleBarPinController; mTaskbarStashController = controllers.taskbarStashController; mTaskbarInsetsController = controllers.taskbarInsetsController; mBubbleBarFlyoutController = new BubbleBarFlyoutController( @@ -524,6 +526,61 @@ public class BubbleBarViewController { mBarView.animateToBubbleBarLocation(bubbleBarLocation); } + /** Returns whether the Bubble Bar is currently displaying a drop target. */ + public boolean isShowingDropTarget() { + return mBarView.isShowingDropTarget(); + } + + /** + * Notifies the controller that a drag event is over the Bubble Bar drop zone. The controller + * will display the appropriate drop target and enter drop target mode. The controller will also + * update the return value of {@link #isLocationUpdatedForDropTarget()} to true if location was + * updated. + */ + public void onDragItemOverBubbleBarDragZone(@NonNull BubbleBarLocation bubbleBarLocation) { + mBarView.showDropTarget(/* isDropTarget = */ true); + mIsLocationUpdatedForDropTarget = getBubbleBarLocation() != bubbleBarLocation; + if (mIsLocationUpdatedForDropTarget) { + animateBubbleBarLocation(bubbleBarLocation); + } + if (!hasBubbles()) { + mBubbleBarPinController.showDropTarget(bubbleBarLocation); + } + } + + /** + * Returns {@code true} if location was updated after most recent + * {@link #onDragItemOverBubbleBarDragZone}}. + */ + public boolean isLocationUpdatedForDropTarget() { + return mIsLocationUpdatedForDropTarget; + } + + /** + * Notifies the controller that the drag event is outside the Bubble Bar drop zone. + * This will hide the drop target zone if there are no bubbles or return the + * Bubble Bar to its original location. The controller will also exit drop target + * mode and reset the value returned from {@link #isLocationUpdatedForDropTarget()} to false. + */ + public void onItemDraggedOutsideBubbleBarDropZone() { + mBarView.showDropTarget(/* isDropTarget = */ false); + if (mIsLocationUpdatedForDropTarget) { + animateBubbleBarLocation(getBubbleBarLocation()); + } + mBubbleBarPinController.hideDropTarget(); + mIsLocationUpdatedForDropTarget = false; + } + + /** + * Notifies the controller that the drag has completed over the Bubble Bar drop zone. + * The controller will hide the drop target if there are no bubbles and exit drop target mode. + */ + public void onItemDroppedInBubbleBarDragZone() { + mBarView.showDropTarget(/* isDropTarget = */ false); + mBubbleBarPinController.hideDropTarget(); + mIsLocationUpdatedForDropTarget = false; + } + /** * The bounds of the bubble bar. */ From 3f203087436793fc41ea6aa1d94b68e6d7b21690 Mon Sep 17 00:00:00 2001 From: wilsonshih Date: Tue, 18 Feb 2025 07:09:45 +0000 Subject: [PATCH 029/153] Release predict_back animaton leash in Launcher. Release the animation leash after back_to_home animation done. Flag: EXEMPT bugfix Bug: 395035430 Test: Use the back gesture to trigger the back_to_home animation multiple times and perform multiple random transitions, dumping the Surface Flinger to check the predict_back leashes not remain in the offscreen layer. Change-Id: I7ed9dfd510e38bed28b51762df9976d33c4a5644 --- .../android/quickstep/LauncherBackAnimationController.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/quickstep/src/com/android/quickstep/LauncherBackAnimationController.java b/quickstep/src/com/android/quickstep/LauncherBackAnimationController.java index be0a3390bf..783ec2c7da 100644 --- a/quickstep/src/com/android/quickstep/LauncherBackAnimationController.java +++ b/quickstep/src/com/android/quickstep/LauncherBackAnimationController.java @@ -514,7 +514,13 @@ public class LauncherBackAnimationController { private void finishAnimation() { mLauncher.setPredictiveBackToHomeInProgress(false); + if (mBackTarget != null && mBackTarget.leash.isValid()) { + mBackTarget.leash.release(); + } mBackTarget = null; + if (mLauncherTarget != null && mLauncherTarget.leash.isValid()) { + mLauncherTarget.leash.release(); + } mLauncherTarget = null; mBackInProgress = false; mBackProgress = 0; From 28d82757375df90f98a2bc303ef2b24cf8059e7f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cosmin=20B=C4=83ie=C8=99?= Date: Tue, 18 Feb 2025 11:57:14 +0100 Subject: [PATCH 030/153] Use FLAG_ALT_FOCUSABLE_IM in taskbar when needed Previously taskbar would only set/remove the FLAG_NOT_FOCUSABLE, which also made it IME focusable. This was toggled when a tasbkar folder was opened/closed, as well as opening the popup by long pressing an app in the taskbar. Folders do require IME focusability, as the folder name can be edited. However, the popup does not require IME focusability, and this lead to the IME suddenly disappearing when the popup is shown. This fixes the issue by also setting FLAG_ALT_FOCUSABLE_IM as needed, only when the taskbar is also focusable. This follows the same logic as in NotificationShadeWindowControllerImpl. Flag: EXEMPT bugfix Test: switch to gesture nav, show IME in app, show popup and verify IME is still visible open folder in either taskbar or launcher and verify IME can be shown Bug: 361046041 Change-Id: Idb9b4503d5622222e99735f0f6981a17add12360 --- .../taskbar/TaskbarActivityContext.java | 31 ++++++++++++++----- 1 file changed, 24 insertions(+), 7 deletions(-) diff --git a/quickstep/src/com/android/launcher3/taskbar/TaskbarActivityContext.java b/quickstep/src/com/android/launcher3/taskbar/TaskbarActivityContext.java index e62288f591..c089e3eef5 100644 --- a/quickstep/src/com/android/launcher3/taskbar/TaskbarActivityContext.java +++ b/quickstep/src/com/android/launcher3/taskbar/TaskbarActivityContext.java @@ -18,6 +18,7 @@ package com.android.launcher3.taskbar; import static android.os.Trace.TRACE_TAG_APP; import static android.view.Display.DEFAULT_DISPLAY; import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; +import static android.view.WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM; import static android.view.WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE; import static android.view.WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS; import static android.view.WindowManager.LayoutParams.TYPE_NAVIGATION_BAR; @@ -869,7 +870,7 @@ public class TaskbarActivityContext extends BaseTaskbarContext { @Override public void onPopupVisibilityChanged(boolean isVisible) { - setTaskbarWindowFocusable(isVisible); + setTaskbarWindowFocusable(isVisible /* focusable */, false /* imeFocusable */); } @Override @@ -1228,17 +1229,29 @@ public class TaskbarActivityContext extends BaseTaskbarContext { } /** - * Either adds or removes {@link WindowManager.LayoutParams#FLAG_NOT_FOCUSABLE} on the taskbar - * window. + * Sets whether the taskbar window should be focusable and IME focusable. This won't be IME + * focusable unless it is also focusable. + * + * @param focusable whether it should be focusable. + * @param imeFocusable whether it should be IME focusable. + * + * @see WindowManager.LayoutParams#FLAG_NOT_FOCUSABLE + * @see WindowManager.LayoutParams#FLAG_ALT_FOCUSABLE_IM */ - public void setTaskbarWindowFocusable(boolean focusable) { + public void setTaskbarWindowFocusable(boolean focusable, boolean imeFocusable) { if (isPhoneMode()) { return; } if (focusable) { mWindowLayoutParams.flags &= ~FLAG_NOT_FOCUSABLE; + if (imeFocusable) { + mWindowLayoutParams.flags &= ~FLAG_ALT_FOCUSABLE_IM; + } else { + mWindowLayoutParams.flags |= FLAG_ALT_FOCUSABLE_IM; + } } else { mWindowLayoutParams.flags |= FLAG_NOT_FOCUSABLE; + mWindowLayoutParams.flags &= ~FLAG_ALT_FOCUSABLE_IM; } notifyUpdateLayoutParams(); } @@ -1259,8 +1272,12 @@ public class TaskbarActivityContext extends BaseTaskbarContext { } /** - * Either adds or removes {@link WindowManager.LayoutParams#FLAG_NOT_FOCUSABLE} on the taskbar - * window. If we're now focusable, also move nav buttons to a separate window above IME. + * Sets whether the taskbar window should be focusable, as well as IME focusable. If we're now + * focusable, also move nav buttons to a separate window above IME. + * + * @param focusable whether it should be focusable. + * + * @see WindowManager.LayoutParams#FLAG_NOT_FOCUSABLE */ public void setTaskbarWindowFocusableForIme(boolean focusable) { if (focusable) { @@ -1268,7 +1285,7 @@ public class TaskbarActivityContext extends BaseTaskbarContext { } else { mControllers.navbarButtonsViewController.moveNavButtonsBackToTaskbarWindow(); } - setTaskbarWindowFocusable(focusable); + setTaskbarWindowFocusable(focusable, true /* imeFocusable */); } /** Adds the given view to WindowManager with the provided LayoutParams (creates new window). */ From 73120a210baa5d5496755cc50e4b218dd3163d32 Mon Sep 17 00:00:00 2001 From: Jordan Silva Date: Mon, 17 Feb 2025 18:22:51 +0000 Subject: [PATCH 031/153] Clean-up unused dependencies from TaskContainer and RecentsDependencies Fix: 397222030 Doc: go/launcher-overview-unified-taskviewmodel Flag: com.android.launcher3.enable_refactor_task_thumbnail Test: OverviewImageTest Test: TaskViewModelTest Test: GetThumbnailPositionUseCaseTest Test: GetThumbnailUseCaseTest Change-Id: Idc1793039b4fc57d666dc19c55b984ba617c67bd --- .../recents/di/RecentsDependencies.kt | 4 +- .../recents/usecase/GetThumbnailUseCase.kt | 26 ------ .../android/quickstep/views/TaskContainer.kt | 11 --- .../usecase/GetThumbnailUseCaseTest.kt | 83 ------------------- 4 files changed, 1 insertion(+), 123 deletions(-) delete mode 100644 quickstep/src/com/android/quickstep/recents/usecase/GetThumbnailUseCase.kt delete mode 100644 quickstep/tests/multivalentTests/src/com/android/quickstep/recents/usecase/GetThumbnailUseCaseTest.kt diff --git a/quickstep/src/com/android/quickstep/recents/di/RecentsDependencies.kt b/quickstep/src/com/android/quickstep/recents/di/RecentsDependencies.kt index 4b3bef38cf..c6b3d6ac00 100644 --- a/quickstep/src/com/android/quickstep/recents/di/RecentsDependencies.kt +++ b/quickstep/src/com/android/quickstep/recents/di/RecentsDependencies.kt @@ -31,7 +31,6 @@ import com.android.quickstep.recents.domain.usecase.GetTaskUseCase import com.android.quickstep.recents.domain.usecase.GetThumbnailPositionUseCase import com.android.quickstep.recents.domain.usecase.IsThumbnailValidUseCase import com.android.quickstep.recents.domain.usecase.OrganizeDesktopTasksUseCase -import com.android.quickstep.recents.usecase.GetThumbnailUseCase import com.android.quickstep.recents.viewmodel.RecentsViewData import com.android.quickstep.task.viewmodel.TaskOverlayViewModel import com.android.systemui.shared.recents.model.Task @@ -42,7 +41,7 @@ import kotlinx.coroutines.SupervisorJob internal typealias RecentsScopeId = String -class RecentsDependencies private constructor(private val appContext: Context) { +class RecentsDependencies private constructor(appContext: Context) { private val scopes = mutableMapOf() init { @@ -185,7 +184,6 @@ class RecentsDependencies private constructor(private val appContext: Context) { IsThumbnailValidUseCase::class.java -> IsThumbnailValidUseCase(rotationStateRepository = inject()) GetTaskUseCase::class.java -> GetTaskUseCase(repository = inject()) - GetThumbnailUseCase::class.java -> GetThumbnailUseCase(taskRepository = inject()) GetSysUiStatusNavFlagsUseCase::class.java -> GetSysUiStatusNavFlagsUseCase() GetThumbnailPositionUseCase::class.java -> GetThumbnailPositionUseCase( diff --git a/quickstep/src/com/android/quickstep/recents/usecase/GetThumbnailUseCase.kt b/quickstep/src/com/android/quickstep/recents/usecase/GetThumbnailUseCase.kt deleted file mode 100644 index b9e9e026bc..0000000000 --- a/quickstep/src/com/android/quickstep/recents/usecase/GetThumbnailUseCase.kt +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (C) 2024 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.recents.usecase - -import android.graphics.Bitmap -import com.android.quickstep.recents.data.RecentTasksRepository - -/** Use case for retrieving thumbnail. */ -class GetThumbnailUseCase(private val taskRepository: RecentTasksRepository) { - /** Returns the latest thumbnail associated with [taskId] if loaded, or null otherwise */ - fun run(taskId: Int): Bitmap? = taskRepository.getCurrentThumbnailById(taskId)?.thumbnail -} diff --git a/quickstep/src/com/android/quickstep/views/TaskContainer.kt b/quickstep/src/com/android/quickstep/views/TaskContainer.kt index ce20bf9b9b..7301cfc3ca 100644 --- a/quickstep/src/com/android/quickstep/views/TaskContainer.kt +++ b/quickstep/src/com/android/quickstep/views/TaskContainer.kt @@ -25,8 +25,6 @@ import com.android.launcher3.util.SplitConfigurationOptions import com.android.launcher3.util.TransformingTouchDelegate import com.android.quickstep.TaskOverlayFactory import com.android.quickstep.ViewUtils.addAccessibleChildToList -import com.android.quickstep.recents.di.RecentsDependencies -import com.android.quickstep.recents.di.getScope import com.android.quickstep.recents.ui.mapper.TaskUiStateMapper import com.android.quickstep.recents.ui.viewmodel.TaskData import com.android.quickstep.task.thumbnail.TaskThumbnailView @@ -57,13 +55,6 @@ class TaskContainer( init { if (enableRefactorTaskThumbnail()) { require(snapshotView is TaskThumbnailView) - RecentsDependencies.getScope(snapshotView).apply { - val taskViewScope = RecentsDependencies.getScope(taskView) - linkTo(taskViewScope) - - val taskContainerScope = RecentsDependencies.getScope(this@TaskContainer) - linkTo(taskContainerScope) - } } else { require(snapshotView is TaskThumbnailViewDeprecated) } @@ -116,8 +107,6 @@ class TaskContainer( snapshotView.scaleY = 1f overlay.destroy() if (enableRefactorTaskThumbnail()) { - RecentsDependencies.getInstance().removeScope(snapshotView) - RecentsDependencies.getInstance().removeScope(this) isThumbnailValid = false } else { thumbnailViewDeprecated.setShowSplashForSplitSelection(false) diff --git a/quickstep/tests/multivalentTests/src/com/android/quickstep/recents/usecase/GetThumbnailUseCaseTest.kt b/quickstep/tests/multivalentTests/src/com/android/quickstep/recents/usecase/GetThumbnailUseCaseTest.kt deleted file mode 100644 index 90ef61d931..0000000000 --- a/quickstep/tests/multivalentTests/src/com/android/quickstep/recents/usecase/GetThumbnailUseCaseTest.kt +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (C) 2024 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.recents.usecase - -import android.content.ComponentName -import android.content.Intent -import android.graphics.Bitmap -import android.graphics.Color -import com.android.quickstep.recents.data.FakeTasksRepository -import com.android.systemui.shared.recents.model.Task -import com.android.systemui.shared.recents.model.ThumbnailData -import com.google.common.truth.Truth.assertThat -import org.junit.Test -import org.mockito.kotlin.mock -import org.mockito.kotlin.whenever - -/** Test for [GetThumbnailUseCase] */ -class GetThumbnailUseCaseTest { - private val task = - Task(Task.TaskKey(TASK_ID, 0, Intent(), ComponentName("", ""), 0, 2000)).apply { - colorBackground = Color.BLACK - } - private val thumbnailData = - ThumbnailData( - thumbnail = - mock().apply { - whenever(width).thenReturn(THUMBNAIL_WIDTH) - whenever(height).thenReturn(THUMBNAIL_HEIGHT) - } - ) - - private val tasksRepository = FakeTasksRepository() - private val systemUnderTest = GetThumbnailUseCase(tasksRepository) - - @Test - fun taskNotSeeded_returnsNull() { - assertThat(systemUnderTest.run(TASK_ID)).isNull() - } - - @Test - fun taskNotLoaded_returnsNull() { - tasksRepository.seedTasks(listOf(task)) - - assertThat(systemUnderTest.run(TASK_ID)).isNull() - } - - @Test - fun taskNotVisible_returnsNull() { - tasksRepository.seedTasks(listOf(task)) - tasksRepository.seedThumbnailData(mapOf(TASK_ID to thumbnailData)) - - assertThat(systemUnderTest.run(TASK_ID)).isNull() - } - - @Test - fun taskVisible_returnsThumbnail() { - tasksRepository.seedTasks(listOf(task)) - tasksRepository.seedThumbnailData(mapOf(TASK_ID to thumbnailData)) - tasksRepository.setVisibleTasks(setOf(TASK_ID)) - - assertThat(systemUnderTest.run(TASK_ID)).isEqualTo(thumbnailData.thumbnail) - } - - private companion object { - const val TASK_ID = 0 - const val THUMBNAIL_WIDTH = 100 - const val THUMBNAIL_HEIGHT = 200 - } -} From 668f630d925b21c16ab2e3ba59a66a355d2c5ab3 Mon Sep 17 00:00:00 2001 From: Sergey Pinkevich Date: Fri, 14 Feb 2025 16:50:27 +0000 Subject: [PATCH 032/153] Add logs for DesktopAppLaunchTransition when animation starts/no launch change Bug: 395495925 Flag: NONE only adding logs, not change of actual code Test: manually Change-Id: I02d436b6a7bd2210f7917211648124b11d7bb972 --- .../desktop/DesktopAppLaunchAnimatorHelper.kt | 19 ++++++++++++++++++- .../desktop/DesktopAppLaunchTransition.kt | 5 ++++- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/quickstep/src/com/android/launcher3/desktop/DesktopAppLaunchAnimatorHelper.kt b/quickstep/src/com/android/launcher3/desktop/DesktopAppLaunchAnimatorHelper.kt index adbcc75728..533a86aedf 100644 --- a/quickstep/src/com/android/launcher3/desktop/DesktopAppLaunchAnimatorHelper.kt +++ b/quickstep/src/com/android/launcher3/desktop/DesktopAppLaunchAnimatorHelper.kt @@ -21,6 +21,7 @@ import android.animation.AnimatorSet import android.animation.ValueAnimator import android.content.Context import android.graphics.Rect +import android.util.Log import android.view.Choreographer import android.view.SurfaceControl.Transaction import android.view.WindowManager.TRANSIT_CLOSE @@ -63,7 +64,19 @@ class DesktopAppLaunchAnimatorHelper( fun createAnimators(info: TransitionInfo, finishCallback: (Animator) -> Unit): List { val launchChange = getLaunchChange(info) - requireNotNull(launchChange) { "expected an app launch Change" } + requireNotNull(launchChange) { + val changesString = + info.changes.joinToString(", ") { change -> + "Change: mode=${change.mode}, " + + "taskId=${change.taskInfo?.id}, " + + "isFreeform=${change.taskInfo?.isFreeform}" + } + Log.e( + TAG, + "No launch change found: Transition type=${info.type}, changes=$changesString", + ) + "expected an app launch Change" + } val transaction = transactionSupplier.get() @@ -189,4 +202,8 @@ class DesktopAppLaunchAnimatorHelper( } } } + + private companion object { + const val TAG = "DesktopAppLaunchAnimatorHelper" + } } diff --git a/quickstep/src/com/android/launcher3/desktop/DesktopAppLaunchTransition.kt b/quickstep/src/com/android/launcher3/desktop/DesktopAppLaunchTransition.kt index 578bba5c0d..79072a6441 100644 --- a/quickstep/src/com/android/launcher3/desktop/DesktopAppLaunchTransition.kt +++ b/quickstep/src/com/android/launcher3/desktop/DesktopAppLaunchTransition.kt @@ -19,6 +19,7 @@ package com.android.launcher3.desktop import android.animation.Animator import android.content.Context import android.os.IBinder +import android.util.Log import android.view.SurfaceControl.Transaction import android.view.WindowManager.TRANSIT_OPEN import android.view.WindowManager.TRANSIT_TO_FRONT @@ -43,7 +44,7 @@ class DesktopAppLaunchTransition @JvmOverloads constructor( context: Context, - launchType: AppLaunchType, + private val launchType: AppLaunchType, @Cuj.CujType private val cujType: Int, private val mainExecutor: Executor, transactionSupplier: Supplier = Supplier { Transaction() }, @@ -66,6 +67,7 @@ constructor( transaction: Transaction, transitionFinishedCallback: IRemoteTransitionFinishedCallback, ) { + Log.v(TAG, "startAnimation: launchType=$launchType, cujType=$cujType") val safeTransitionFinishedCallback = RemoteRunnable { transitionFinishedCallback.onTransitionFinished(/* wct= */ null, /* sct= */ null) } @@ -86,6 +88,7 @@ constructor( } companion object { + const val TAG = "DesktopAppLaunchTransition" /** Change modes that represent a task becoming visible / launching in Desktop mode. */ val LAUNCH_CHANGE_MODES = intArrayOf(TRANSIT_OPEN, TRANSIT_TO_FRONT) From 2719edd9a3fa0206e0e84aceb476fa61be0383ad Mon Sep 17 00:00:00 2001 From: Ajinkya Chalke Date: Mon, 17 Feb 2025 20:08:06 +0000 Subject: [PATCH 033/153] [CD][Alt+Tab] Add aconfig flag for flattening KQS - Next will update DesktopExperienceFlags to include this and Alt+Tab CD flag. Bug: 382769617 Flag: EXEMPT adding flag Test: EXEMPT adding flag Change-Id: Id0958ce48b4b733da11ea089ce6f7045d9eaf061 --- aconfig/launcher.aconfig | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/aconfig/launcher.aconfig b/aconfig/launcher.aconfig index d4cea8d0f5..4f5b1a03ef 100644 --- a/aconfig/launcher.aconfig +++ b/aconfig/launcher.aconfig @@ -622,3 +622,10 @@ flag { description: "Enables custom theme manager in Launcher" bug: "381897614" } + +flag { + name: "enable_alt_tab_kqs_flatenning" + namespace: "lse_desktop_experience" + description: "Enable Alt + Tab KQS view to show apps in flattened structure" + bug: "382769617" +} From 861a31e8fdbe3282ffc92054b6eed1d2c343f613 Mon Sep 17 00:00:00 2001 From: Sergey Pinkevich Date: Mon, 10 Feb 2025 20:04:50 +0000 Subject: [PATCH 034/153] Convert DesktopAppLaunchTransitionManagerTest to multivalent Bug: 378096575 Flag: NONE test fix, not actual code editing Test: DesktopAppLaunchTransitionManagerTest Change-Id: I6dc335fea156f4e830e9c2cadf3c98ff01fb7c4f --- .../DesktopAppLaunchTransitionManagerTest.kt | 14 -------------- 1 file changed, 14 deletions(-) rename quickstep/tests/{src/com/android/quickstep => multivalentTests/src/com/android/launcher3}/desktop/DesktopAppLaunchTransitionManagerTest.kt (90%) diff --git a/quickstep/tests/src/com/android/quickstep/desktop/DesktopAppLaunchTransitionManagerTest.kt b/quickstep/tests/multivalentTests/src/com/android/launcher3/desktop/DesktopAppLaunchTransitionManagerTest.kt similarity index 90% rename from quickstep/tests/src/com/android/quickstep/desktop/DesktopAppLaunchTransitionManagerTest.kt rename to quickstep/tests/multivalentTests/src/com/android/launcher3/desktop/DesktopAppLaunchTransitionManagerTest.kt index 9ca9fe4df5..7ebef45d27 100644 --- a/quickstep/tests/src/com/android/quickstep/desktop/DesktopAppLaunchTransitionManagerTest.kt +++ b/quickstep/tests/multivalentTests/src/com/android/launcher3/desktop/DesktopAppLaunchTransitionManagerTest.kt @@ -27,12 +27,10 @@ import android.view.WindowManager.TRANSIT_TO_FRONT import android.window.TransitionFilter import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.SmallTest -import com.android.dx.mockito.inline.extended.ExtendedMockito.mockitoSession import com.android.quickstep.SystemUiProxy import com.android.window.flags.Flags.FLAG_ENABLE_DESKTOP_APP_LAUNCH_TRANSITIONS_BUGFIX import com.android.wm.shell.shared.desktopmode.DesktopModeStatus import com.google.common.truth.Truth.assertThat -import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.Test @@ -43,7 +41,6 @@ import org.mockito.kotlin.mock import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever -import org.mockito.quality.Strictness @SmallTest @RunWith(AndroidJUnit4::class) @@ -51,12 +48,6 @@ class DesktopAppLaunchTransitionManagerTest { @get:Rule val mSetFlagsRule = SetFlagsRule() - private val mockitoSession = - mockitoSession() - .strictness(Strictness.LENIENT) - .mockStatic(DesktopModeStatus::class.java) - .startMocking() - private val context = mock() private val systemUiProxy = mock() private lateinit var transitionManager: DesktopAppLaunchTransitionManager @@ -68,11 +59,6 @@ class DesktopAppLaunchTransitionManagerTest { transitionManager = DesktopAppLaunchTransitionManager(context, systemUiProxy) } - @After - fun tearDown() { - mockitoSession.finishMocking() - } - @Test @EnableFlags(FLAG_ENABLE_DESKTOP_APP_LAUNCH_TRANSITIONS_BUGFIX) fun registerTransitions_appLaunchFlagEnabled_registersTransition() { From d09352625998322ced1b713d62e73c314d37f6ce Mon Sep 17 00:00:00 2001 From: Pat Manning Date: Wed, 12 Feb 2025 17:57:14 +0000 Subject: [PATCH 035/153] Move dismiss utils into new Util class. Fix: 396111473 Test: Manual. Does everything build. Flag: com.android.launcher3.enable_expressive_dismiss_task_motion Change-Id: I039fc38c133245e52b7ca30ff5231ddba7b77e47 --- .../quickstep/views/RecentsDismissUtils.kt | 294 ++++++++++++++++++ .../android/quickstep/views/RecentsView.java | 5 +- .../quickstep/views/RecentsViewUtils.kt | 267 ---------------- 3 files changed, 297 insertions(+), 269 deletions(-) create mode 100644 quickstep/src/com/android/quickstep/views/RecentsDismissUtils.kt diff --git a/quickstep/src/com/android/quickstep/views/RecentsDismissUtils.kt b/quickstep/src/com/android/quickstep/views/RecentsDismissUtils.kt new file mode 100644 index 0000000000..96eed87a5f --- /dev/null +++ b/quickstep/src/com/android/quickstep/views/RecentsDismissUtils.kt @@ -0,0 +1,294 @@ +/* + * 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.views + +import android.os.VibrationAttributes +import androidx.dynamicanimation.animation.FloatPropertyCompat +import androidx.dynamicanimation.animation.FloatValueHolder +import androidx.dynamicanimation.animation.SpringAnimation +import androidx.dynamicanimation.animation.SpringForce +import com.android.launcher3.R +import com.android.launcher3.Utilities.boundToRange +import com.android.launcher3.touch.SingleAxisSwipeDetector +import com.android.launcher3.util.DynamicResource +import com.android.launcher3.util.MSDLPlayerWrapper +import com.android.quickstep.util.TaskGridNavHelper +import com.android.quickstep.views.RecentsView.RECENTS_SCALE_PROPERTY +import com.google.android.msdl.data.model.MSDLToken +import com.google.android.msdl.domain.InteractionProperties +import kotlin.math.abs + +/** + * Helper class for [RecentsView]. This util class contains refactored and extracted functions from + * RecentsView related to TaskView dismissal. + */ +class RecentsDismissUtils(private val recentsView: RecentsView<*, *>) { + + /** + * Creates the spring animations which run when a dragged task view in overview is released. + * + *

When a task dismiss is cancelled, the task will return to its original position via a + * spring animation. As it passes the threshold of its settling state, its neighbors will spring + * in response to the perceived impact of the settling task. + */ + fun createTaskDismissSettlingSpringAnimation( + draggedTaskView: TaskView?, + velocity: Float, + isDismissing: Boolean, + detector: SingleAxisSwipeDetector, + dismissLength: Int, + onEndRunnable: () -> Unit, + ): SpringAnimation? { + draggedTaskView ?: return null + val taskDismissFloatProperty = + FloatPropertyCompat.createFloatPropertyCompat( + draggedTaskView.secondaryDismissTranslationProperty + ) + // Animate dragged task towards dismissal or rest state. + val draggedTaskViewSpringAnimation = + SpringAnimation(draggedTaskView, taskDismissFloatProperty) + .setSpring(createExpressiveDismissSpringForce()) + .setStartVelocity(if (detector.isFling(velocity)) velocity else 0f) + .addUpdateListener { animation, value, _ -> + if (isDismissing && abs(value) >= abs(dismissLength)) { + animation.cancel() + } else if (draggedTaskView.isRunningTask && recentsView.enableDrawingLiveTile) { + recentsView.runActionOnRemoteHandles { remoteTargetHandle -> + remoteTargetHandle.taskViewSimulator.taskSecondaryTranslation.value = + taskDismissFloatProperty.getValue(draggedTaskView) + } + recentsView.redrawLiveTile() + } + } + .addEndListener { _, _, _, _ -> + if (isDismissing) { + recentsView.dismissTask( + draggedTaskView, + /* animateTaskView = */ false, + /* removeTask = */ true, + ) + } else { + recentsView.onDismissAnimationEnds() + } + onEndRunnable() + } + if (!isDismissing) { + addNeighboringSpringAnimationsForDismissCancel( + draggedTaskView, + draggedTaskViewSpringAnimation, + ) + } + return draggedTaskViewSpringAnimation + } + + private fun addNeighboringSpringAnimationsForDismissCancel( + draggedTaskView: TaskView, + draggedTaskViewSpringAnimation: SpringAnimation, + ) { + // Empty spring animation exists for conditional start, and to drive neighboring springs. + val neighborsToSettle = + SpringAnimation(FloatValueHolder()).setSpring(createExpressiveDismissSpringForce()) + var lastPosition = 0f + var startSettling = false + draggedTaskViewSpringAnimation.addUpdateListener { _, value, velocity -> + // Start the settling animation the first time the dragged task passes the origin (from + // negative displacement to positive displacement). We do not check for an exact value + // to compare to, as the update listener does not necessarily hit every value (e.g. a + // value of zero). Do not check again once it has started settling, as a spring can + // bounce past the origin multiple times depending on the stiffness and damping ratio. + if (startSettling) return@addUpdateListener + if (lastPosition < 0 && value >= 0) { + startSettling = true + } + lastPosition = value + if (startSettling) { + neighborsToSettle.setStartVelocity(velocity).animateToFinalPosition(0f) + playDismissSettlingHaptic(velocity) + } + } + + // Add tasks before dragged index, fanning out from the dragged task. + // The order they are added matters, as each spring drives the next. + var previousNeighbor = neighborsToSettle + getTasksOffsetPairAdjacentToDraggedTask(draggedTaskView, towardsStart = true).forEach { + (taskView, offset) -> + previousNeighbor = + createNeighboringTaskViewSpringAnimation( + taskView, + offset * ADDITIONAL_DISMISS_DAMPING_RATIO, + previousNeighbor, + ) + } + // Add tasks after dragged index, fanning out from the dragged task. + // The order they are added matters, as each spring drives the next. + previousNeighbor = neighborsToSettle + getTasksOffsetPairAdjacentToDraggedTask(draggedTaskView, towardsStart = false).forEach { + (taskView, offset) -> + previousNeighbor = + createNeighboringTaskViewSpringAnimation( + taskView, + offset * ADDITIONAL_DISMISS_DAMPING_RATIO, + previousNeighbor, + ) + } + } + + /** + * Gets pairs of (TaskView, offset) adjacent the dragged task in visual order. + * + *

Gets tasks either before or after the dragged task along with their offset from it. The + * offset is the distance between indices for carousels, or distance between columns for grids. + */ + private fun getTasksOffsetPairAdjacentToDraggedTask( + draggedTaskView: TaskView, + towardsStart: Boolean, + ): Sequence> { + if (recentsView.showAsGrid()) { + val taskGridNavHelper = + TaskGridNavHelper( + recentsView.topRowIdArray, + recentsView.bottomRowIdArray, + recentsView.mUtils.getLargeTaskViewIds(), + hasAddDesktopButton = false, + ) + return taskGridNavHelper + .gridTaskViewIdOffsetPairInTabOrderSequence( + draggedTaskView.taskViewId, + towardsStart, + ) + .mapNotNull { (taskViewId, columnOffset) -> + recentsView.getTaskViewFromTaskViewId(taskViewId)?.let { taskView -> + Pair(taskView, columnOffset) + } + } + } else { + val taskViewList = recentsView.mUtils.taskViews.toList() + val draggedTaskViewIndex = taskViewList.indexOf(draggedTaskView) + + return if (towardsStart) { + taskViewList + .take(draggedTaskViewIndex) + .reversed() + .mapIndexed { index, taskView -> Pair(taskView, index + 1) } + .asSequence() + } else { + taskViewList + .takeLast(taskViewList.size - draggedTaskViewIndex - 1) + .mapIndexed { index, taskView -> Pair(taskView, index + 1) } + .asSequence() + } + } + } + + /** Creates a neighboring task view spring, driven by the spring of its neighbor. */ + private fun createNeighboringTaskViewSpringAnimation( + taskView: TaskView, + dampingOffsetRatio: Float, + previousNeighborSpringAnimation: SpringAnimation, + ): SpringAnimation { + val neighboringTaskViewSpringAnimation = + SpringAnimation( + taskView, + FloatPropertyCompat.createFloatPropertyCompat( + taskView.secondaryDismissTranslationProperty + ), + ) + .setSpring(createExpressiveDismissSpringForce(dampingOffsetRatio)) + // Update live tile on spring animation. + if (taskView.isRunningTask && recentsView.enableDrawingLiveTile) { + neighboringTaskViewSpringAnimation.addUpdateListener { _, _, _ -> + recentsView.runActionOnRemoteHandles { remoteTargetHandle -> + remoteTargetHandle.taskViewSimulator.taskSecondaryTranslation.value = + taskView.secondaryDismissTranslationProperty.get(taskView) + } + recentsView.redrawLiveTile() + } + } + // Drive current neighbor's spring with the previous neighbor's. + previousNeighborSpringAnimation.addUpdateListener { _, value, _ -> + neighboringTaskViewSpringAnimation.animateToFinalPosition(value) + } + return neighboringTaskViewSpringAnimation + } + + private fun createExpressiveDismissSpringForce(dampingRatioOffset: Float = 0f): SpringForce { + val resourceProvider = DynamicResource.provider(recentsView.mContainer) + return SpringForce() + .setDampingRatio( + resourceProvider.getFloat(R.dimen.expressive_dismiss_task_trans_y_damping_ratio) + + dampingRatioOffset + ) + .setStiffness( + resourceProvider.getFloat(R.dimen.expressive_dismiss_task_trans_y_stiffness) + ) + } + + /** + * Plays a haptic as the dragged task view settles back into its rest state. + * + *

Haptic intensity is proportional to velocity. + */ + private fun playDismissSettlingHaptic(velocity: Float) { + val maxDismissSettlingVelocity = + recentsView.pagedOrientationHandler.getSecondaryDimension(recentsView) + MSDLPlayerWrapper.INSTANCE.get(recentsView.context) + .playToken( + MSDLToken.CANCEL, + InteractionProperties.DynamicVibrationScale( + boundToRange(velocity / maxDismissSettlingVelocity, 0f, 1f), + VibrationAttributes.Builder() + .setUsage(VibrationAttributes.USAGE_TOUCH) + .setFlags(VibrationAttributes.FLAG_PIPELINED_EFFECT) + .build(), + ), + ) + } + + /** Animates RecentsView's scale to the provided value, using spring animations. */ + fun animateRecentsScale(scale: Float): SpringAnimation { + val resourceProvider = DynamicResource.provider(recentsView.mContainer) + val dampingRatio = resourceProvider.getFloat(R.dimen.swipe_up_rect_scale_damping_ratio) + val stiffness = resourceProvider.getFloat(R.dimen.swipe_up_rect_scale_stiffness) + + // Spring which sets the Recents scale on update. This is needed, as the SpringAnimation + // struggles to animate small values like changing recents scale from 0.9 to 1. So + // we animate over a larger range (e.g. 900 to 1000) and convert back to the required value. + // (This is instead of converting RECENTS_SCALE_PROPERTY to a FloatPropertyCompat and + // animating it directly via springs.) + val initialRecentsScaleSpringValue = + RECENTS_SCALE_SPRING_MULTIPLIER * RECENTS_SCALE_PROPERTY.get(recentsView) + return SpringAnimation(FloatValueHolder(initialRecentsScaleSpringValue)) + .setSpring( + SpringForce(initialRecentsScaleSpringValue) + .setDampingRatio(dampingRatio) + .setStiffness(stiffness) + ) + .addUpdateListener { _, value, _ -> + RECENTS_SCALE_PROPERTY.setValue( + recentsView, + value / RECENTS_SCALE_SPRING_MULTIPLIER, + ) + } + .apply { animateToFinalPosition(RECENTS_SCALE_SPRING_MULTIPLIER * scale) } + } + + 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 + } +} diff --git a/quickstep/src/com/android/quickstep/views/RecentsView.java b/quickstep/src/com/android/quickstep/views/RecentsView.java index 0218a581cc..e69bc58354 100644 --- a/quickstep/src/com/android/quickstep/views/RecentsView.java +++ b/quickstep/src/com/android/quickstep/views/RecentsView.java @@ -851,6 +851,7 @@ public abstract class RecentsView< private final RecentsViewModel mRecentsViewModel; private final RecentsViewModelHelper mHelper; protected final RecentsViewUtils mUtils = new RecentsViewUtils(this); + protected final RecentsDismissUtils mDismissUtils = new RecentsDismissUtils(this); private final Matrix mTmpMatrix = new Matrix(); @@ -6943,7 +6944,7 @@ public abstract class RecentsView< public SpringAnimation createTaskDismissSettlingSpringAnimation(TaskView draggedTaskView, float velocity, boolean isDismissing, SingleAxisSwipeDetector detector, int dismissLength, Function0 onEndRunnable) { - return mUtils.createTaskDismissSettlingSpringAnimation(draggedTaskView, velocity, + return mDismissUtils.createTaskDismissSettlingSpringAnimation(draggedTaskView, velocity, isDismissing, detector, dismissLength, onEndRunnable); } @@ -6951,7 +6952,7 @@ public abstract class RecentsView< * Animates RecentsView's scale to the provided value, using spring animations. */ public SpringAnimation animateRecentsScale(float scale) { - return mUtils.animateRecentsScale(scale); + return mDismissUtils.animateRecentsScale(scale); } public interface TaskLaunchListener { diff --git a/quickstep/src/com/android/quickstep/views/RecentsViewUtils.kt b/quickstep/src/com/android/quickstep/views/RecentsViewUtils.kt index 0e350bb4e8..94e8c03360 100644 --- a/quickstep/src/com/android/quickstep/views/RecentsViewUtils.kt +++ b/quickstep/src/com/android/quickstep/views/RecentsViewUtils.kt @@ -17,31 +17,16 @@ package com.android.quickstep.views import android.graphics.Rect -import android.os.VibrationAttributes 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.launcher3.Flags.enableLargeDesktopWindowingTile import com.android.launcher3.Flags.enableSeparateExternalDisplayTasks -import com.android.launcher3.R -import com.android.launcher3.Utilities.boundToRange -import com.android.launcher3.touch.SingleAxisSwipeDetector -import com.android.launcher3.util.DynamicResource import com.android.launcher3.util.IntArray -import com.android.launcher3.util.MSDLPlayerWrapper import com.android.quickstep.util.GroupTask -import com.android.quickstep.util.TaskGridNavHelper import com.android.quickstep.util.isExternalDisplay -import com.android.quickstep.views.RecentsView.RECENTS_SCALE_PROPERTY import com.android.quickstep.views.RecentsView.RUNNING_TASK_ATTACH_ALPHA import com.android.systemui.shared.recents.model.ThumbnailData -import com.google.android.msdl.data.model.MSDLToken -import com.google.android.msdl.domain.InteractionProperties import java.util.function.BiConsumer -import kotlin.math.abs /** * Helper class for [RecentsView]. This util class contains refactored and extracted functions from @@ -309,259 +294,7 @@ class RecentsViewUtils(private val recentsView: RecentsView<*, *>) { } } - /** - * Creates the spring animations which run when a dragged task view in overview is released. - * - *

When a task dismiss is cancelled, the task will return to its original position via a - * spring animation. As it passes the threshold of its settling state, its neighbors will spring - * in response to the perceived impact of the settling task. - */ - fun createTaskDismissSettlingSpringAnimation( - draggedTaskView: TaskView?, - velocity: Float, - isDismissing: Boolean, - detector: SingleAxisSwipeDetector, - dismissLength: Int, - onEndRunnable: () -> Unit, - ): SpringAnimation? { - draggedTaskView ?: return null - val taskDismissFloatProperty = - FloatPropertyCompat.createFloatPropertyCompat( - draggedTaskView.secondaryDismissTranslationProperty - ) - // Animate dragged task towards dismissal or rest state. - val draggedTaskViewSpringAnimation = - SpringAnimation(draggedTaskView, taskDismissFloatProperty) - .setSpring(createExpressiveDismissSpringForce()) - .setStartVelocity(if (detector.isFling(velocity)) velocity else 0f) - .addUpdateListener { animation, value, _ -> - if (isDismissing && abs(value) >= abs(dismissLength)) { - animation.cancel() - } else if (draggedTaskView.isRunningTask && recentsView.enableDrawingLiveTile) { - recentsView.runActionOnRemoteHandles { remoteTargetHandle -> - remoteTargetHandle.taskViewSimulator.taskSecondaryTranslation.value = - taskDismissFloatProperty.getValue(draggedTaskView) - } - recentsView.redrawLiveTile() - } - } - .addEndListener { _, _, _, _ -> - if (isDismissing) { - recentsView.dismissTask( - draggedTaskView, - /* animateTaskView = */ false, - /* removeTask = */ true, - ) - } else { - recentsView.onDismissAnimationEnds() - } - onEndRunnable() - } - if (!isDismissing) { - addNeighboringSpringAnimationsForDismissCancel( - draggedTaskView, - draggedTaskViewSpringAnimation, - ) - } - return draggedTaskViewSpringAnimation - } - - private fun addNeighboringSpringAnimationsForDismissCancel( - draggedTaskView: TaskView, - draggedTaskViewSpringAnimation: SpringAnimation, - ) { - // Empty spring animation exists for conditional start, and to drive neighboring springs. - val neighborsToSettle = - SpringAnimation(FloatValueHolder()).setSpring(createExpressiveDismissSpringForce()) - var lastPosition = 0f - var startSettling = false - draggedTaskViewSpringAnimation.addUpdateListener { _, value, velocity -> - // Start the settling animation the first time the dragged task passes the origin (from - // negative displacement to positive displacement). We do not check for an exact value - // to compare to, as the update listener does not necessarily hit every value (e.g. a - // value of zero). Do not check again once it has started settling, as a spring can - // bounce past the origin multiple times depending on the stiffness and damping ratio. - if (startSettling) return@addUpdateListener - if (lastPosition < 0 && value >= 0) { - startSettling = true - } - lastPosition = value - if (startSettling) { - neighborsToSettle.setStartVelocity(velocity).animateToFinalPosition(0f) - playDismissSettlingHaptic(velocity) - } - } - - // Add tasks before dragged index, fanning out from the dragged task. - // The order they are added matters, as each spring drives the next. - var previousNeighbor = neighborsToSettle - getTasksOffsetPairAdjacentToDraggedTask(draggedTaskView, towardsStart = true).forEach { - (taskView, offset) -> - previousNeighbor = - createNeighboringTaskViewSpringAnimation( - taskView, - offset * ADDITIONAL_DISMISS_DAMPING_RATIO, - previousNeighbor, - ) - } - // Add tasks after dragged index, fanning out from the dragged task. - // The order they are added matters, as each spring drives the next. - previousNeighbor = neighborsToSettle - getTasksOffsetPairAdjacentToDraggedTask(draggedTaskView, towardsStart = false).forEach { - (taskView, offset) -> - previousNeighbor = - createNeighboringTaskViewSpringAnimation( - taskView, - offset * ADDITIONAL_DISMISS_DAMPING_RATIO, - previousNeighbor, - ) - } - } - - /** - * Gets pairs of (TaskView, offset) adjacent the dragged task in visual order. - * - *

Gets tasks either before or after the dragged task along with their offset from it. The - * offset is the distance between indices for carousels, or distance between columns for grids. - */ - private fun getTasksOffsetPairAdjacentToDraggedTask( - draggedTaskView: TaskView, - towardsStart: Boolean, - ): Sequence> { - if (recentsView.showAsGrid()) { - val taskGridNavHelper = - TaskGridNavHelper( - recentsView.topRowIdArray, - recentsView.bottomRowIdArray, - getLargeTaskViewIds(), - hasAddDesktopButton = false, - ) - return taskGridNavHelper - .gridTaskViewIdOffsetPairInTabOrderSequence( - draggedTaskView.taskViewId, - towardsStart, - ) - .mapNotNull { (taskViewId, columnOffset) -> - recentsView.getTaskViewFromTaskViewId(taskViewId)?.let { taskView -> - Pair(taskView, columnOffset) - } - } - } else { - val taskViewList = taskViews.toList() - val draggedTaskViewIndex = taskViewList.indexOf(draggedTaskView) - - return if (towardsStart) { - taskViewList - .take(draggedTaskViewIndex) - .reversed() - .mapIndexed { index, taskView -> Pair(taskView, index + 1) } - .asSequence() - } else { - taskViewList - .takeLast(taskViewList.size - draggedTaskViewIndex - 1) - .mapIndexed { index, taskView -> Pair(taskView, index + 1) } - .asSequence() - } - } - } - - /** Creates a neighboring task view spring, driven by the spring of its neighbor. */ - private fun createNeighboringTaskViewSpringAnimation( - taskView: TaskView, - dampingOffsetRatio: Float, - previousNeighborSpringAnimation: SpringAnimation, - ): SpringAnimation { - val neighboringTaskViewSpringAnimation = - SpringAnimation( - taskView, - FloatPropertyCompat.createFloatPropertyCompat( - taskView.secondaryDismissTranslationProperty - ), - ) - .setSpring(createExpressiveDismissSpringForce(dampingOffsetRatio)) - // Update live tile on spring animation. - if (taskView.isRunningTask && recentsView.enableDrawingLiveTile) { - neighboringTaskViewSpringAnimation.addUpdateListener { _, _, _ -> - recentsView.runActionOnRemoteHandles { remoteTargetHandle -> - remoteTargetHandle.taskViewSimulator.taskSecondaryTranslation.value = - taskView.secondaryDismissTranslationProperty.get(taskView) - } - recentsView.redrawLiveTile() - } - } - // Drive current neighbor's spring with the previous neighbor's. - previousNeighborSpringAnimation.addUpdateListener { _, value, _ -> - neighboringTaskViewSpringAnimation.animateToFinalPosition(value) - } - return neighboringTaskViewSpringAnimation - } - - private fun createExpressiveDismissSpringForce(dampingRatioOffset: Float = 0f): SpringForce { - val resourceProvider = DynamicResource.provider(recentsView.mContainer) - return SpringForce() - .setDampingRatio( - resourceProvider.getFloat(R.dimen.expressive_dismiss_task_trans_y_damping_ratio) + - dampingRatioOffset - ) - .setStiffness( - resourceProvider.getFloat(R.dimen.expressive_dismiss_task_trans_y_stiffness) - ) - } - - /** - * Plays a haptic as the dragged task view settles back into its rest state. - * - *

Haptic intensity is proportional to velocity. - */ - private fun playDismissSettlingHaptic(velocity: Float) { - val maxDismissSettlingVelocity = - recentsView.pagedOrientationHandler.getSecondaryDimension(recentsView) - MSDLPlayerWrapper.INSTANCE.get(recentsView.context) - .playToken( - MSDLToken.CANCEL, - InteractionProperties.DynamicVibrationScale( - boundToRange(velocity / maxDismissSettlingVelocity, 0f, 1f), - VibrationAttributes.Builder() - .setUsage(VibrationAttributes.USAGE_TOUCH) - .setFlags(VibrationAttributes.FLAG_PIPELINED_EFFECT) - .build(), - ), - ) - } - - /** Animates RecentsView's scale to the provided value, using spring animations. */ - fun animateRecentsScale(scale: Float): SpringAnimation { - val resourceProvider = DynamicResource.provider(recentsView.mContainer) - val dampingRatio = resourceProvider.getFloat(R.dimen.swipe_up_rect_scale_damping_ratio) - val stiffness = resourceProvider.getFloat(R.dimen.swipe_up_rect_scale_stiffness) - - // Spring which sets the Recents scale on update. This is needed, as the SpringAnimation - // struggles to animate small values like changing recents scale from 0.9 to 1. So - // we animate over a larger range (e.g. 900 to 1000) and convert back to the required value. - // (This is instead of converting RECENTS_SCALE_PROPERTY to a FloatPropertyCompat and - // animating it directly via springs.) - val initialRecentsScaleSpringValue = - RECENTS_SCALE_SPRING_MULTIPLIER * RECENTS_SCALE_PROPERTY.get(recentsView) - return SpringAnimation(FloatValueHolder(initialRecentsScaleSpringValue)) - .setSpring( - SpringForce(initialRecentsScaleSpringValue) - .setDampingRatio(dampingRatio) - .setStiffness(stiffness) - ) - .addUpdateListener { _, value, _ -> - RECENTS_SCALE_PROPERTY.setValue( - recentsView, - value / RECENTS_SCALE_SPRING_MULTIPLIER, - ) - } - .apply { animateToFinalPosition(RECENTS_SCALE_SPRING_MULTIPLIER * scale) } - } - companion object { val TEMP_RECT = Rect() - - // 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 } } From 5a148aef440b24309ea95fd42d2d62683bcd4235 Mon Sep 17 00:00:00 2001 From: Uwais Ashraf Date: Tue, 18 Feb 2025 08:40:41 +0000 Subject: [PATCH 036/153] Reduce ViewPool sizes for Desktop/GroupedTaskView to save RAM. Bug: 395287683 Flag: com.android.launcher3.enable_refactor_task_thumbnail Test: Manual - split tasks displaying correctly Change-Id: Ib4496ee1859cc5245ec4ef76f0723de8fbd55b7c --- quickstep/src/com/android/quickstep/views/RecentsView.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/quickstep/src/com/android/quickstep/views/RecentsView.java b/quickstep/src/com/android/quickstep/views/RecentsView.java index 0218a581cc..93d414f4f5 100644 --- a/quickstep/src/com/android/quickstep/views/RecentsView.java +++ b/quickstep/src/com/android/quickstep/views/RecentsView.java @@ -916,10 +916,12 @@ public abstract class RecentsView< mTaskViewPool = new ViewPool<>(context, this, R.layout.task, 20 /* max size */, 10 /* initial size */); + int groupedViewPoolInitialSize = enableRefactorTaskThumbnail() ? 2 : 10; mGroupedTaskViewPool = new ViewPool<>(context, this, - R.layout.task_grouped, 20 /* max size */, 10 /* initial size */); + R.layout.task_grouped, 20 /* max size */, groupedViewPoolInitialSize); + int desktopViewPoolInitialSize = DesktopModeStatus.canEnterDesktopMode(mContext) ? 1 : 0; mDesktopTaskViewPool = new ViewPool<>(context, this, R.layout.task_desktop, - 5 /* max size */, 1 /* initial size */); + 5 /* max size */, desktopViewPoolInitialSize); setOrientationHandler(mOrientationState.getOrientationHandler()); mIsRtl = getPagedOrientationHandler().getRecentsRtlSetting(getResources()); From 9063bd7a46a28e415cf8b0d140b9c9e524176627 Mon Sep 17 00:00:00 2001 From: Alex Chau Date: Fri, 14 Feb 2025 18:42:31 +0000 Subject: [PATCH 037/153] Update Desktop tasks's corner radius to match Shell side Fix: 384517710 Test: OverviewDesktopTaskImageTest Flag: EXEMPT BUG_FIX Change-Id: I021c3cd4e8c1cc13066def470536535c5dbc791e --- .../src/com/android/quickstep/DesktopFullscreenDrawParams.kt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/quickstep/src/com/android/quickstep/DesktopFullscreenDrawParams.kt b/quickstep/src/com/android/quickstep/DesktopFullscreenDrawParams.kt index bafb0b2ca6..444e77d38d 100644 --- a/quickstep/src/com/android/quickstep/DesktopFullscreenDrawParams.kt +++ b/quickstep/src/com/android/quickstep/DesktopFullscreenDrawParams.kt @@ -17,7 +17,7 @@ package com.android.quickstep import android.content.Context -import com.android.systemui.shared.system.QuickStepContract +import com.android.launcher3.R // DesktopTaskView thumbnail's corner radius is independent of fullscreenProgress. open class DesktopFullscreenDrawParams @@ -28,6 +28,6 @@ constructor(context: Context, cornerRadiusProvider: (Context) -> Float = ::compu // computeCornerRadius is used as cornerRadiusProvider, so // QuickStepContract::getWindowCornerRadius can be mocked properly. private fun computeCornerRadius(context: Context): Float = - QuickStepContract.getWindowCornerRadius(context) + context.resources.getDimension(R.dimen.desktop_windowing_freeform_rounded_corner_radius) } } From ef06ef332885bb9a3d4eeb8efcb51cd8bed27b10 Mon Sep 17 00:00:00 2001 From: Schneider Victor-Tulias Date: Tue, 18 Feb 2025 12:08:45 -0500 Subject: [PATCH 038/153] Send intent boradcast when AllSetActivity ends and reaches launcher Flag: EXEMPT supporting new SUW behaviour Bug: 396378163 Test: registered temporary broadcast receiver and checked logs Change-Id: Ib39da6bf17efd7e72c8e45bc2528781e1b9aa8d3 --- .../src/com/android/quickstep/interaction/AllSetActivity.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/quickstep/src/com/android/quickstep/interaction/AllSetActivity.java b/quickstep/src/com/android/quickstep/interaction/AllSetActivity.java index c986b88e1d..953b0c56b4 100644 --- a/quickstep/src/com/android/quickstep/interaction/AllSetActivity.java +++ b/quickstep/src/com/android/quickstep/interaction/AllSetActivity.java @@ -92,6 +92,8 @@ public class AllSetActivity extends Activity { private static final String LOG_TAG = "AllSetActivity"; private static final String URI_SYSTEM_NAVIGATION_SETTING = "#Intent;action=com.android.settings.SEARCH_RESULT_TRAMPOLINE;S.:settings:fragment_args_key=gesture_system_navigation_input_summary;S.:settings:show_fragment=com.android.settings.gestures.SystemNavigationGestureSettings;end"; + private static final String INTENT_ACTION_ACTIVITY_CLOSED = + "com.android.quickstep.interaction.ACTION_ALL_SET_ACTIVITY_CLOSED"; private static final String EXTRA_ACCENT_COLOR_DARK_MODE = "suwColorAccentDark"; private static final String EXTRA_ACCENT_COLOR_LIGHT_MODE = "suwColorAccentLight"; private static final String EXTRA_DEVICE_NAME = "suwDeviceName"; @@ -332,6 +334,7 @@ public class AllSetActivity extends Activity { mLauncherStartAnim.dispatchOnEnd(); mLauncherStartAnim = null; } + sendBroadcast(new Intent(INTENT_ACTION_ACTIVITY_CLOSED)); } @Override From 65c04b0f0572a8021ed05103f35f8e8208a82038 Mon Sep 17 00:00:00 2001 From: Alex Chau Date: Mon, 17 Feb 2025 16:43:09 +0000 Subject: [PATCH 039/153] Fix live tile in dismiss and swipe down animation - Add separate property for grid translation in TaskViewSimulator, so it doesn't get reset when other translations (e.g. dismiss) is applied to live tile - In createAdjacentPageAnimForTaskLaunch, use onAnimationStart without isReverse parameter, so it's actually called when the PendingAniamtion starts - Also reset pivot if we have overriden it during createAdjacentPageAnimForTaskLaunch - Also avoid applying addOverviewToAppAnim on live tile if it's not launching, otherwise recentsViewScale will be applied twice with addOverviewToAppAnim applying wrong value - Use pivot instead of recentsViewScroll to bring non scroll position live tiel to fullscreen, to avoid a trajectory that will otherwise travel left and then right Fix: 391146807 Fix: 321013528 Test: launching via swipe down with non-launching live tile Test: dismissing live tile Test: launching live tile in non scroll position Flag: com.android.launcher3.enable_grid_only_overview Change-Id: I24ee85399b09b25e157a8986103658bb4803a87e --- .../com/android/quickstep/TaskViewUtils.java | 60 ++++++++++----- .../quickstep/util/TaskViewSimulator.java | 5 ++ .../android/quickstep/views/RecentsView.java | 76 +++++++++++++------ 3 files changed, 98 insertions(+), 43 deletions(-) diff --git a/quickstep/src/com/android/quickstep/TaskViewUtils.java b/quickstep/src/com/android/quickstep/TaskViewUtils.java index 35a6e72378..37c2d1c17b 100644 --- a/quickstep/src/com/android/quickstep/TaskViewUtils.java +++ b/quickstep/src/com/android/quickstep/TaskViewUtils.java @@ -38,6 +38,7 @@ import static com.android.launcher3.QuickstepTransitionManager.SPLIT_DIVIDER_ANI import static com.android.launcher3.QuickstepTransitionManager.SPLIT_LAUNCH_DURATION; import static com.android.launcher3.Utilities.getDescendantCoordRelativeToAncestor; import static com.android.launcher3.util.MultiPropertyFactory.MULTI_PROPERTY_VALUE; +import static com.android.quickstep.BaseContainerInterface.getTaskDimension; import static com.android.quickstep.util.AnimUtils.clampToDuration; import static com.android.wm.shell.shared.TransitionUtil.TYPE_SPLIT_SCREEN_DIM_LAYER; @@ -65,6 +66,7 @@ import androidx.annotation.Nullable; import com.android.app.animation.Interpolators; import com.android.internal.jank.Cuj; import com.android.launcher3.DeviceProfile; +import com.android.launcher3.Utilities; import com.android.launcher3.anim.AnimatedFloat; import com.android.launcher3.anim.AnimationSuccessListener; import com.android.launcher3.anim.AnimatorPlaybackController; @@ -102,6 +104,11 @@ public final class TaskViewUtils { private TaskViewUtils() {} + private static final Rect TEMP_THUMBNAIL_BOUNDS = new Rect(); + private static final Rect TEMP_FULLSCREEN_BOUNDS = new Rect(); + private static final PointF TEMP_TASK_DIMENSION = new PointF(); + private static final PointF TEMP_PIVOT = new PointF(); + /** * Try to find a TaskView that corresponds with the component of the launched view. * @@ -164,7 +171,7 @@ public final class TaskViewUtils { public static > void createRecentsWindowAnimator( @NonNull RecentsView recentsView, - @NonNull TaskView v, + @NonNull TaskView taskView, boolean skipViewChanges, @NonNull RemoteAnimationTarget[] appTargets, @NonNull RemoteAnimationTarget[] wallpaperTargets, @@ -172,31 +179,31 @@ public final class TaskViewUtils { @Nullable DepthController depthController, @Nullable TransitionInfo transitionInfo, PendingAnimation out) { - boolean isQuickSwitch = v.isEndQuickSwitchCuj(); - v.setEndQuickSwitchCuj(false); + boolean isQuickSwitch = taskView.isEndQuickSwitchCuj(); + taskView.setEndQuickSwitchCuj(false); final RemoteAnimationTargets targets = new RemoteAnimationTargets(appTargets, wallpaperTargets, nonAppTargets, MODE_OPENING); final RemoteAnimationTarget navBarTarget = targets.getNavBarRemoteAnimationTarget(); - SurfaceTransactionApplier applier = new SurfaceTransactionApplier(v); + SurfaceTransactionApplier applier = new SurfaceTransactionApplier(taskView); targets.addReleaseCheck(applier); RemoteTargetHandle[] remoteTargetHandles; RemoteTargetHandle[] recentsViewHandles = recentsView.getRemoteTargetHandles(); - if (v.isRunningTask() && recentsViewHandles != null) { + if (taskView.isRunningTask() && recentsViewHandles != null) { // Re-use existing handles remoteTargetHandles = recentsViewHandles; } else { - boolean forDesktop = v instanceof DesktopTaskView; - RemoteTargetGluer gluer = new RemoteTargetGluer(v.getContext(), + boolean forDesktop = taskView instanceof DesktopTaskView; + RemoteTargetGluer gluer = new RemoteTargetGluer(taskView.getContext(), recentsView.getSizeStrategy(), targets, forDesktop); if (forDesktop) { remoteTargetHandles = gluer.assignTargetsForDesktop(targets, transitionInfo); - } else if (v.containsMultipleTasks()) { + } else if (taskView.containsMultipleTasks()) { remoteTargetHandles = gluer.assignTargetsForSplitScreen(targets, - ((GroupedTaskView) v).getSplitBoundsConfig()); + ((GroupedTaskView) taskView).getSplitBoundsConfig()); } else { remoteTargetHandles = gluer.assignTargets(targets); } @@ -210,8 +217,8 @@ public final class TaskViewUtils { remoteTargetHandle.getTransformParams().setSyncTransactionApplier(applier); } - int taskIndex = recentsView.indexOfChild(v); - Context context = v.getContext(); + int taskIndex = recentsView.indexOfChild(taskView); + Context context = taskView.getContext(); T container = RecentsViewContainer.containerFromContext(context); DeviceProfile dp = container.getDeviceProfile(); @@ -219,11 +226,11 @@ public final class TaskViewUtils { boolean parallaxCenterAndAdjacentTask = !showAsGrid && taskIndex != recentsView.getCurrentPage(); int taskRectTranslationPrimary = recentsView.getScrollOffset(taskIndex); - int taskRectTranslationSecondary = showAsGrid ? (int) v.getGridTranslationY() : 0; + int taskRectTranslationSecondary = showAsGrid ? (int) taskView.getGridTranslationY() : 0; RemoteTargetHandle[] topMostSimulators = null; - if (!v.isRunningTask()) { + if (!taskView.isRunningTask()) { // TVSs already initialized from the running task, no need to re-init for (RemoteTargetHandle targetHandle : remoteTargetHandles) { TaskViewSimulator tvsLocal = targetHandle.getTaskViewSimulator(); @@ -237,13 +244,13 @@ public final class TaskViewUtils { tvsLocal.fullScreenProgress.value = 0; tvsLocal.recentsViewScale.value = 1; if (!enableGridOnlyOverview()) { - tvsLocal.setIsGridTask(v.isGridTask()); + tvsLocal.setIsGridTask(taskView.isGridTask()); } tvsLocal.getOrientationState().getOrientationHandler().set(tvsLocal, TaskViewSimulator::setTaskRectTranslation, taskRectTranslationPrimary, taskRectTranslationSecondary); - if (v instanceof DesktopTaskView) { + if (taskView instanceof DesktopTaskView) { targetHandle.getTransformParams().setTargetAlpha(1f); } else { // Fade in the task during the initial 20% of the animation @@ -260,8 +267,11 @@ public final class TaskViewUtils { out.setFloat(tvsLocal.recentsViewScale, AnimatedFloat.VALUE, tvsLocal.getFullScreenScale(), TOUCH_RESPONSE); - out.setFloat(tvsLocal.recentsViewScroll, AnimatedFloat.VALUE, 0, - TOUCH_RESPONSE); + if (!enableGridOnlyOverview()) { + out.setFloat(tvsLocal.recentsViewScroll, AnimatedFloat.VALUE, 0, + TOUCH_RESPONSE); + } + out.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { @@ -271,6 +281,18 @@ public final class TaskViewUtils { showTransaction.getTransaction().show(targets.apps[i].leash); } applier.scheduleApply(showTransaction); + + if (enableGridOnlyOverview()) { + taskView.getThumbnailBounds(TEMP_THUMBNAIL_BOUNDS, /*relativeToDragLayer=*/ + true); + getTaskDimension(context, container.getDeviceProfile(), + TEMP_TASK_DIMENSION); + TEMP_FULLSCREEN_BOUNDS.set(0, 0, (int) TEMP_TASK_DIMENSION.x, + (int) TEMP_TASK_DIMENSION.y); + Utilities.getPivotsForScalingRectToRect(TEMP_THUMBNAIL_BOUNDS, + TEMP_FULLSCREEN_BOUNDS, TEMP_PIVOT); + tvsLocal.setPivotOverride(TEMP_PIVOT); + } } }); out.addOnFrameCallback(() -> { @@ -321,7 +343,7 @@ public final class TaskViewUtils { if (!skipViewChanges && parallaxCenterAndAdjacentTask && topMostSimulators != null && topMostSimulators.length > 0) { - out.addFloat(v, VIEW_ALPHA, 1, 0, clampToProgress(LINEAR, 0.2f, 0.4f)); + out.addFloat(taskView, VIEW_ALPHA, 1, 0, clampToProgress(LINEAR, 0.2f, 0.4f)); RemoteTargetHandle[] simulatorCopies = topMostSimulators; for (RemoteTargetHandle handle : simulatorCopies) { @@ -340,7 +362,7 @@ public final class TaskViewUtils { // During animation we apply transformation on the thumbnailView (and not the rootView) // to follow the TaskViewSimulator. So the final matrix applied on the thumbnailView is: // Mt K(0)` K(t) Mt` - View[] thumbnails = v.getSnapshotViews(); + View[] thumbnails = taskView.getSnapshotViews(); // In case simulator copies and thumbnail size do no match, ensure we get the lesser. // This ensures we do not create arrays with empty elements or attempt to references diff --git a/quickstep/src/com/android/quickstep/util/TaskViewSimulator.java b/quickstep/src/com/android/quickstep/util/TaskViewSimulator.java index 09e9c8b119..b844079a14 100644 --- a/quickstep/src/com/android/quickstep/util/TaskViewSimulator.java +++ b/quickstep/src/com/android/quickstep/util/TaskViewSimulator.java @@ -97,6 +97,8 @@ public class TaskViewSimulator implements TransformParams.BuilderProxy { private final FullscreenDrawParams mCurrentFullscreenParams; public final AnimatedFloat taskPrimaryTranslation = new AnimatedFloat(); public final AnimatedFloat taskSecondaryTranslation = new AnimatedFloat(); + public final AnimatedFloat taskGridTranslationX = new AnimatedFloat(); + public final AnimatedFloat taskGridTranslationY = new AnimatedFloat(); // Carousel properties public final AnimatedFloat carouselScale = new AnimatedFloat(); @@ -445,6 +447,7 @@ public class TaskViewSimulator implements TransformParams.BuilderProxy { taskPrimaryTranslation.value); mOrientationState.getOrientationHandler().setSecondary(mMatrix, MATRIX_POST_TRANSLATE, taskSecondaryTranslation.value); + mMatrix.postTranslate(taskGridTranslationX.value, taskGridTranslationY.value); mMatrix.postScale(carouselScale.value, carouselScale.value, mIsRecentsRtl ? mCarouselTaskSize.right : mCarouselTaskSize.left, @@ -484,6 +487,8 @@ public class TaskViewSimulator implements TransformParams.BuilderProxy { + " taskRect: " + mTaskRect + " taskPrimaryT: " + taskPrimaryTranslation.value + " taskSecondaryT: " + taskSecondaryTranslation.value + + " taskGridTranslationX: " + taskGridTranslationX.value + + " taskGridTranslationY: " + taskGridTranslationY.value + " recentsPrimaryT: " + recentsViewPrimaryTranslation.value + " recentsSecondaryT: " + recentsViewSecondaryTranslation.value + " recentsScroll: " + recentsViewScroll.value diff --git a/quickstep/src/com/android/quickstep/views/RecentsView.java b/quickstep/src/com/android/quickstep/views/RecentsView.java index 5bfcf43c18..d1d08ac8c8 100644 --- a/quickstep/src/com/android/quickstep/views/RecentsView.java +++ b/quickstep/src/com/android/quickstep/views/RecentsView.java @@ -2917,28 +2917,40 @@ public abstract class RecentsView< BaseState endState = mSizeStrategy.stateFromGestureEndTarget(endTarget); if (endState.displayOverviewTasksAsGrid(mContainer.getDeviceProfile())) { TaskView runningTaskView = getRunningTaskView(); - float runningTaskPrimaryGridTranslation = 0; - float runningTaskSecondaryGridTranslation = 0; + float runningTaskGridTranslationX = 0; + float runningTaskGridTranslationY = 0; if (runningTaskView != null) { // Apply the grid translation to running task unless it's being snapped to // and removes the current translation applied to the running task. - runningTaskPrimaryGridTranslation = runningTaskView.getGridTranslationX() + runningTaskGridTranslationX = runningTaskView.getGridTranslationX() - runningTaskView.getNonGridTranslationX(); - runningTaskSecondaryGridTranslation = runningTaskView.getGridTranslationY(); + runningTaskGridTranslationY = runningTaskView.getGridTranslationY(); } for (RemoteTargetHandle remoteTargetHandle : remoteTargetHandles) { TaskViewSimulator tvs = remoteTargetHandle.getTaskViewSimulator(); if (animatorSet == null) { setGridProgress(1); - tvs.taskPrimaryTranslation.value = runningTaskPrimaryGridTranslation; - tvs.taskSecondaryTranslation.value = runningTaskSecondaryGridTranslation; + if (enableGridOnlyOverview()) { + tvs.taskGridTranslationX.value = runningTaskGridTranslationX; + tvs.taskGridTranslationY.value = runningTaskGridTranslationY; + } else { + tvs.taskPrimaryTranslation.value = runningTaskGridTranslationX; + tvs.taskSecondaryTranslation.value = runningTaskGridTranslationY; + } } else { animatorSet.play(ObjectAnimator.ofFloat(this, RECENTS_GRID_PROGRESS, 1)); - animatorSet.play(tvs.carouselScale.animateToValue(1)); - animatorSet.play(tvs.taskPrimaryTranslation.animateToValue( - runningTaskPrimaryGridTranslation)); - animatorSet.play(tvs.taskSecondaryTranslation.animateToValue( - runningTaskSecondaryGridTranslation)); + if (enableGridOnlyOverview()) { + animatorSet.play(tvs.carouselScale.animateToValue(1)); + animatorSet.play(tvs.taskGridTranslationX.animateToValue( + runningTaskGridTranslationX)); + animatorSet.play(tvs.taskGridTranslationY.animateToValue( + runningTaskGridTranslationY)); + } else { + animatorSet.play(tvs.taskPrimaryTranslation.animateToValue( + runningTaskGridTranslationX)); + animatorSet.play(tvs.taskSecondaryTranslation.animateToValue( + runningTaskGridTranslationY)); + } } } } @@ -3491,8 +3503,13 @@ public abstract class RecentsView< final TaskView runningTask = getRunningTaskView(); if (showAsGrid() && enableGridOnlyOverview() && runningTask != null) { runActionOnRemoteHandles( - remoteTargetHandle -> remoteTargetHandle.getTaskViewSimulator() - .taskSecondaryTranslation.value = runningTask.getGridTranslationY() + remoteTargetHandle -> { + remoteTargetHandle.getTaskViewSimulator().taskGridTranslationX.value = + runningTask.getGridTranslationX() + - runningTask.getNonGridTranslationX(); + remoteTargetHandle.getTaskViewSimulator().taskGridTranslationY.value = + runningTask.getGridTranslationY(); + } ); } @@ -3606,12 +3623,9 @@ public abstract class RecentsView< if (taskView.isRunningTask()) { anim.addOnFrameCallback(() -> { if (!mEnableDrawingLiveTile) return; - runActionOnRemoteHandles( - remoteTargetHandle -> remoteTargetHandle.getTaskViewSimulator() - .taskSecondaryTranslation.value = getPagedOrientationHandler() - .getSecondaryValue(taskView.getTranslationX(), - taskView.getTranslationY() - )); + runActionOnRemoteHandles(remoteTargetHandle -> + remoteTargetHandle.getTaskViewSimulator().taskSecondaryTranslation.value = + taskView.getSecondaryDismissTranslationProperty().get(taskView)); redrawLiveTile(); }); } @@ -5655,7 +5669,7 @@ public abstract class RecentsView< anim.play(ObjectAnimator.ofFloat(this, FULLSCREEN_PROGRESS, 1)); anim.addListener(new AnimatorListenerAdapter() { @Override - public void onAnimationStart(@NonNull Animator animation, boolean isReverse) { + public void onAnimationStart(@NonNull Animator animation) { taskView.getThumbnailBounds(mTempRect, /*relativeToDragLayer=*/true); getTaskDimension(mContext, mContainer.getDeviceProfile(), mTempPointF); Rect fullscreenBounds = new Rect(0, 0, (int) mTempPointF.x, @@ -5677,6 +5691,18 @@ public abstract class RecentsView< }); } } + + @Override + public void onAnimationEnd(Animator animation) { + // If live tile is not launching, reset the pivot applied above. + if (!taskView.isRunningTask()) { + runActionOnRemoteHandles( + remoteTargetHandle -> { + remoteTargetHandle.getTaskViewSimulator().setPivotOverride( + null); + }); + } + } }); } else if (!showAsGrid) { // We are launching an adjacent task, so parallax the center and other adjacent task. @@ -5785,10 +5811,12 @@ public abstract class RecentsView< mPendingAnimation = new PendingAnimation(duration); mPendingAnimation.add(anim); - runActionOnRemoteHandles( - remoteTargetHandle -> remoteTargetHandle.getTaskViewSimulator() - .addOverviewToAppAnim(mPendingAnimation, interpolator)); - mPendingAnimation.addOnFrameCallback(this::redrawLiveTile); + if (taskView.isRunningTask()) { + runActionOnRemoteHandles( + remoteTargetHandle -> remoteTargetHandle.getTaskViewSimulator() + .addOverviewToAppAnim(mPendingAnimation, interpolator)); + mPendingAnimation.addOnFrameCallback(this::redrawLiveTile); + } mPendingAnimation.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { From a3e196083e5c554ca11d7b49994ce49a91792171 Mon Sep 17 00:00:00 2001 From: Vinay Joglekar Date: Tue, 18 Feb 2025 10:07:00 -0800 Subject: [PATCH 040/153] Add feature flag for background wallpaper blur in overview. Change-Id: I3a4b06270538a9bd42ad3552374885d9f3d6fa35 Fix: 397438303 Flag: com.android.launcher3.enable_overview_background_wallpaper_blur Test: None. Flag addition. --- aconfig/launcher_overview.aconfig | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/aconfig/launcher_overview.aconfig b/aconfig/launcher_overview.aconfig index f379e22b7d..999e784b3b 100644 --- a/aconfig/launcher_overview.aconfig +++ b/aconfig/launcher_overview.aconfig @@ -96,3 +96,10 @@ flag { description: "Enable overview on connected displays." bug: "363251602" } + +flag { + name: "enable_overview_background_wallpaper_blur" + namespace: "launcher_overview" + description: "Enable wallpaper blur in overview." + bug: "369975912" +} From 754e24c52119877a9eb4a90c70974566d8d4f5cb Mon Sep 17 00:00:00 2001 From: minch Date: Mon, 10 Feb 2025 17:27:55 +0000 Subject: [PATCH 041/153] Indices correction inside RecentsView Audit all the functions inside RecentsView with the TaskView index as a parameter. Make sure the AddDesktopButton is considered while setting the value of these parameters. Flag: EXEMPT refactor Bug: 379942019 Test: m alt+tab to the "# more apps" button insde KQS view, the first hidden TaskView inside the RecentsView will be focused. Change-Id: I92cd3e38700e83e72d362dc47d3adae538695b60 --- .../quickstep/OverviewCommandHelper.kt | 20 +++++------ .../android/quickstep/views/RecentsView.java | 34 +++++++------------ .../quickstep/views/RecentsViewUtils.kt | 4 +-- 3 files changed, 24 insertions(+), 34 deletions(-) diff --git a/quickstep/src/com/android/quickstep/OverviewCommandHelper.kt b/quickstep/src/com/android/quickstep/OverviewCommandHelper.kt index 42aa86e9e0..afdb403897 100644 --- a/quickstep/src/com/android/quickstep/OverviewCommandHelper.kt +++ b/quickstep/src/com/android/quickstep/OverviewCommandHelper.kt @@ -293,10 +293,6 @@ constructor( val recentsView: RecentsView<*, *>? = recentsViewContainer?.getOverviewPanel() val deviceProfile = recentsViewContainer?.getDeviceProfile() val uiController = containerInterface.getTaskbarController() - val allowQuickSwitch = - uiController != null && - deviceProfile != null && - (deviceProfile.isTablet || deviceProfile.isTwoPanels) val focusedDisplayId = focusState.focusedDisplayId val focusedDisplayUIController: TaskbarUIController? = @@ -322,26 +318,26 @@ constructor( when (command.type) { HIDE -> { - if (!allowQuickSwitch) return true + if (uiController == null || deviceProfile?.isTablet == false) return true keyboardTaskFocusIndex = if ( enableAltTabKqsOnConnectedDisplays() && focusedDisplayUIController != null ) { focusedDisplayUIController.launchFocusedTask() } else { - uiController!!.launchFocusedTask() + uiController.launchFocusedTask() } if (keyboardTaskFocusIndex == -1) return true } KEYBOARD_INPUT -> - if (allowQuickSwitch) { + if (uiController != null && deviceProfile?.isTablet == true) { if ( enableAltTabKqsOnConnectedDisplays() && focusedDisplayUIController != null ) { focusedDisplayUIController.openQuickSwitchView() } else { - uiController!!.openQuickSwitchView() + uiController.openQuickSwitchView() } return true } else { @@ -365,7 +361,11 @@ constructor( TOGGLE -> {} } - recentsView?.setKeyboardTaskFocusIndex(keyboardTaskFocusIndex) + recentsView?.setKeyboardTaskFocusIndex( + recentsView.indexOfChild(recentsView.taskViews.elementAtOrNull(keyboardTaskFocusIndex)) + ?: -1 + ) + // Handle recents view focus when launching from home val animatorListener: Animator.AnimatorListener = object : AnimatorListenerAdapter() { @@ -526,7 +526,7 @@ constructor( // Stops requesting focused after first view gets focused. recentsView.getTaskViewAt(keyboardTaskFocusIndex).requestFocus() || recentsView.nextTaskView.requestFocus() || - recentsView.getFirstTaskView().requestFocus() || + recentsView.firstTaskView.requestFocus() || recentsView.requestFocus() } diff --git a/quickstep/src/com/android/quickstep/views/RecentsView.java b/quickstep/src/com/android/quickstep/views/RecentsView.java index 58300d27cc..e6e8fa4d68 100644 --- a/quickstep/src/com/android/quickstep/views/RecentsView.java +++ b/quickstep/src/com/android/quickstep/views/RecentsView.java @@ -2013,7 +2013,7 @@ public abstract class RecentsView< } // If the list changed, maybe the focused task doesn't exist anymore. if (newFocusedTaskView == null) { - newFocusedTaskView = mUtils.getExpectedFocusedTask(); + newFocusedTaskView = mUtils.getFirstNonDesktopTaskView(); } } setFocusedTaskViewId( @@ -2119,15 +2119,6 @@ public abstract class RecentsView< return mTaskViewCount; } - /** - * Transverse RecentsView children to calculate the amount of DesktopTaskViews. - * - * @return Number of children that are instances of DesktopTaskView - */ - private int getDesktopTaskViewCount() { - return mUtils.getDesktopTaskViewCount(); - } - /** Counts {@link TaskView}s that are not {@link DesktopTaskView} instances. */ public int getNonDesktopTaskViewCount() { return mUtils.getNonDesktopTaskViewCount(); @@ -3067,7 +3058,7 @@ public abstract class RecentsView< focusedTaskViewId = INVALID_TASK_ID; } else if (enableLargeDesktopWindowingTile() && getRunningTaskView() instanceof DesktopTaskView) { - TaskView focusedTaskView = getTaskViewAt(getDesktopTaskViewCount()); + TaskView focusedTaskView = mUtils.getFirstNonDesktopTaskView(); focusedTaskViewId = focusedTaskView != null ? focusedTaskView.getTaskViewId() : INVALID_TASK_ID; } else { @@ -3936,9 +3927,9 @@ public abstract class RecentsView< int distanceFromDismissedTask = 1; int slidingTranslation = 0; if (isSlidingTasks) { - int nextSnappedPage = isStagingFocusedTask - ? indexOfChild(mUtils.getFirstSmallTaskView()) - : mUtils.getDesktopTaskViewCount(); + int nextSnappedPage = indexOfChild(isStagingFocusedTask + ? mUtils.getFirstSmallTaskView() + : mUtils.getFirstNonDesktopTaskView()); slidingTranslation = getPagedOrientationHandler().getPrimaryScroll(this) - getScrollForPage(nextSnappedPage); slidingTranslation += mIsRtl ? newClearAllShortTotalWidthTranslation @@ -3964,7 +3955,7 @@ public abstract class RecentsView< Math.abs(i - dismissedIndex), scrollDiff, anim, - splitTimings, i); + splitTimings); needsCurveUpdates = true; } } else if (child instanceof TaskView taskView) { @@ -4340,8 +4331,7 @@ public abstract class RecentsView< int indexDiff, int scrollDiffPerPage, PendingAnimation pendingAnimation, - SplitAnimationTimings splitTimings, - int index) { + SplitAnimationTimings splitTimings) { // No need to translate the AddDesktopButton on dismissing a TaskView, which should be // always at the right most position, even when dismissing the last TaskView. if (view instanceof AddDesktopButton) { @@ -6249,12 +6239,12 @@ public abstract class RecentsView< } @Override - protected int getChildVisibleSize(int index) { - final TaskView taskView = getTaskViewAt(index); + protected int getChildVisibleSize(int childIndex) { + final TaskView taskView = getTaskViewAt(childIndex); if (taskView == null) { - return super.getChildVisibleSize(index); + return super.getChildVisibleSize(childIndex); } - return (int) (super.getChildVisibleSize(index) * taskView.getSizeAdjustment( + return (int) (super.getChildVisibleSize(childIndex) * taskView.getSizeAdjustment( showAsFullscreen())); } @@ -6313,7 +6303,7 @@ public abstract class RecentsView< * Returns how many pixels the page is offset on the currently laid out dominant axis. */ private int getUnclampedScrollOffset(int pageIndex) { - if (pageIndex == -1) { + if (pageIndex == INVALID_PAGE) { return 0; } // Don't dampen the scroll (due to overscroll) if the adjacent tasks are offscreen, so that diff --git a/quickstep/src/com/android/quickstep/views/RecentsViewUtils.kt b/quickstep/src/com/android/quickstep/views/RecentsViewUtils.kt index 94e8c03360..f742ec3898 100644 --- a/quickstep/src/com/android/quickstep/views/RecentsViewUtils.kt +++ b/quickstep/src/com/android/quickstep/views/RecentsViewUtils.kt @@ -73,7 +73,7 @@ class RecentsViewUtils(private val recentsView: RecentsView<*, *>) { } /** Counts [TaskView]s that are [DesktopTaskView] instances. */ - fun getDesktopTaskViewCount(): Int = taskViews.count { it is DesktopTaskView } + private fun getDesktopTaskViewCount(): Int = taskViews.count { it is DesktopTaskView } /** Counts [TaskView]s that are not [DesktopTaskView] instances. */ fun getNonDesktopTaskViewCount(): Int = taskViews.count { it !is DesktopTaskView } @@ -91,7 +91,7 @@ class RecentsViewUtils(private val recentsView: RecentsView<*, *>) { } /** Returns the expected focus task. */ - fun getExpectedFocusedTask(): TaskView? = + fun getFirstNonDesktopTaskView(): TaskView? = if (enableLargeDesktopWindowingTile()) taskViews.firstOrNull { it !is DesktopTaskView } else taskViews.firstOrNull() From e4d50cf4226d4b3558187ac74f8d06548068da64 Mon Sep 17 00:00:00 2001 From: Uwais Ashraf Date: Wed, 12 Feb 2025 22:14:31 +0000 Subject: [PATCH 042/153] Add view based screenshot for remaining TTV UI states Bug: 344800402 Flag: com.android.launcher3.enable_refactor_task_thumbnail Test: TaskThumbnailViewScreenshotTest Change-Id: Ib67eea313d12631e1ff3bd83b4874d8eb3ebeb39 --- .../TaskThumbnailViewScreenshotTest.kt | 123 ++++++++++++++++++ 1 file changed, 123 insertions(+) diff --git a/quickstep/tests/multivalentScreenshotTests/src/com/android/quickstep/task/thumbnail/TaskThumbnailViewScreenshotTest.kt b/quickstep/tests/multivalentScreenshotTests/src/com/android/quickstep/task/thumbnail/TaskThumbnailViewScreenshotTest.kt index b9d2fed9c7..6f0aaeb652 100644 --- a/quickstep/tests/multivalentScreenshotTests/src/com/android/quickstep/task/thumbnail/TaskThumbnailViewScreenshotTest.kt +++ b/quickstep/tests/multivalentScreenshotTests/src/com/android/quickstep/task/thumbnail/TaskThumbnailViewScreenshotTest.kt @@ -16,10 +16,19 @@ package com.android.quickstep.task.thumbnail import android.content.Context +import android.graphics.Bitmap +import android.graphics.Canvas import android.graphics.Color +import android.graphics.Matrix +import android.graphics.Paint +import android.graphics.drawable.BitmapDrawable import android.view.LayoutInflater +import android.view.Surface.ROTATION_0 +import androidx.core.graphics.set import com.android.launcher3.R import com.android.quickstep.task.thumbnail.TaskThumbnailUiState.BackgroundOnly +import com.android.quickstep.task.thumbnail.TaskThumbnailUiState.Snapshot +import com.android.quickstep.task.thumbnail.TaskThumbnailUiState.SnapshotSplash import com.android.quickstep.task.thumbnail.TaskThumbnailUiState.Uninitialized import com.google.android.apps.nexuslauncher.imagecomparison.goldenpathmanager.ViewScreenshotGoldenPathManager import org.junit.Rule @@ -80,6 +89,96 @@ class TaskThumbnailViewScreenshotTest(emulationSpec: DeviceEmulationSpec) { } } + @Test + fun taskThumbnailView_liveTile_withoutHeader() { + screenshotRule.screenshotTest("taskThumbnailView_liveTile") { activity -> + activity.actionBar?.hide() + createTaskThumbnailView(activity).apply { + setState(TaskThumbnailUiState.LiveTile.WithoutHeader) + } + } + } + + @Test + fun taskThumbnailView_image_withoutHeader() { + screenshotRule.screenshotTest("taskThumbnailView_image") { activity -> + activity.actionBar?.hide() + createTaskThumbnailView(activity).apply { + setState( + SnapshotSplash( + Snapshot.WithoutHeader(createBitmap(), ROTATION_0, Color.DKGRAY), + null, + ) + ) + } + } + } + + @Test + fun taskThumbnailView_image_withoutHeader_withImageMatrix() { + screenshotRule.screenshotTest("taskThumbnailView_image_withMatrix") { activity -> + activity.actionBar?.hide() + createTaskThumbnailView(activity).apply { + val lessThanHeightMatchingAspectRatio = (VIEW_ENV_HEIGHT / 2) - 200 + setState( + SnapshotSplash( + Snapshot.WithoutHeader( + createBitmap( + width = VIEW_ENV_WIDTH / 2, + height = lessThanHeightMatchingAspectRatio, + ), + ROTATION_0, + Color.DKGRAY, + ), + null, + ) + ) + setImageMatrix(Matrix().apply { postScale(2f, 2f) }) + } + } + } + + @Test + fun taskThumbnailView_splash_withoutHeader() { + screenshotRule.screenshotTest("taskThumbnailView_partial_splash") { activity -> + activity.actionBar?.hide() + createTaskThumbnailView(activity).apply { + setState( + SnapshotSplash( + Snapshot.WithoutHeader(createBitmap(), ROTATION_0, Color.DKGRAY), + BitmapDrawable(activity.resources, createSplash()), + ) + ) + updateSplashAlpha(0.5f) + } + } + } + + @Test + fun taskThumbnailView_splash_withoutHeader_withImageMatrix() { + screenshotRule.screenshotTest("taskThumbnailView_partial_splash_withMatrix") { activity -> + activity.actionBar?.hide() + createTaskThumbnailView(activity).apply { + val lessThanHeightMatchingAspectRatio = (VIEW_ENV_HEIGHT / 2) - 200 + setState( + SnapshotSplash( + Snapshot.WithoutHeader( + createBitmap( + width = VIEW_ENV_WIDTH / 2, + height = lessThanHeightMatchingAspectRatio, + ), + ROTATION_0, + Color.DKGRAY, + ), + BitmapDrawable(activity.resources, createSplash()), + ) + ) + setImageMatrix(Matrix().apply { postScale(2f, 2f) }) + updateSplashAlpha(0.5f) + } + } + } + @Test fun taskThumbnailView_dimmed_tintAmount() { screenshotRule.screenshotTest("taskThumbnailView_dimmed_40") { activity -> @@ -122,6 +221,27 @@ class TaskThumbnailViewScreenshotTest(emulationSpec: DeviceEmulationSpec) { return taskThumbnailView } + private fun createSplash() = createBitmap(width = 20, height = 20, rectColorRotation = 1) + + private fun createBitmap( + width: Int = VIEW_ENV_WIDTH, + height: Int = VIEW_ENV_HEIGHT, + rectColorRotation: Int = 0, + ) = + Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888).apply { + Canvas(this).apply { + val paint = Paint() + paint.color = BITMAP_RECT_COLORS[rectColorRotation % 4] + drawRect(0f, 0f, width / 2f, height / 2f, paint) + paint.color = BITMAP_RECT_COLORS[(1 + rectColorRotation) % 4] + drawRect(width / 2f, 0f, width.toFloat(), height / 2f, paint) + paint.color = BITMAP_RECT_COLORS[(2 + rectColorRotation) % 4] + drawRect(0f, height / 2f, width / 2f, height.toFloat(), paint) + paint.color = BITMAP_RECT_COLORS[(3 + rectColorRotation) % 4] + drawRect(width / 2f, height / 2f, width.toFloat(), height.toFloat(), paint) + } + } + companion object { @Parameters(name = "{0}") @JvmStatic @@ -133,5 +253,8 @@ class TaskThumbnailViewScreenshotTest(emulationSpec: DeviceEmulationSpec) { ) const val CORNER_RADIUS = 56f + val BITMAP_RECT_COLORS = listOf(Color.GREEN, Color.RED, Color.BLUE, Color.CYAN) + const val VIEW_ENV_WIDTH = 1440 + const val VIEW_ENV_HEIGHT = 3120 } } From 43f4b55bdb2a0bb99c085c1175c703747fe88b43 Mon Sep 17 00:00:00 2001 From: Charlie Anderson Date: Thu, 13 Feb 2025 20:49:46 +0000 Subject: [PATCH 043/153] Use selected shape during app launch animation Bug: 372906633 Flag: com.android.launcher3.enable_launcher_icon_shapes Test: manually launching apps Change-Id: I86879e51df95b791266e9a5678042859a3fb27f0 --- .../android/launcher3/views/ClipIconView.java | 22 ++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/src/com/android/launcher3/views/ClipIconView.java b/src/com/android/launcher3/views/ClipIconView.java index ddf18dfbaa..e80aa339c3 100644 --- a/src/com/android/launcher3/views/ClipIconView.java +++ b/src/com/android/launcher3/views/ClipIconView.java @@ -44,6 +44,7 @@ import androidx.annotation.Nullable; import androidx.core.util.Consumer; import com.android.launcher3.DeviceProfile; +import com.android.launcher3.Flags; import com.android.launcher3.R; import com.android.launcher3.Utilities; import com.android.launcher3.dragndrop.FolderAdaptiveIcon; @@ -68,6 +69,7 @@ public class ClipIconView extends View implements ClipPathView { private boolean mIsAdaptiveIcon = false; private ValueAnimator mRevealAnimator; + private float mIconScale; private final Rect mStartRevealRect = new Rect(); private final Rect mEndRevealRect = new Rect(); @@ -173,9 +175,12 @@ public class ClipIconView extends View implements ClipPathView { mTaskCornerRadius = cornerRadius / scale; if (mIsAdaptiveIcon) { - if (!isOpening && progress >= shapeProgressStart) { + final ThemeManager themeManager = ThemeManager.INSTANCE.get(getContext()); + mIconScale = themeManager.getIconState().getIconScale(); + if ((!isOpening || Flags.enableLauncherIconShapes()) + && progress >= shapeProgressStart) { if (mRevealAnimator == null) { - mRevealAnimator = ThemeManager.INSTANCE.get(getContext()).getIconShape() + mRevealAnimator = themeManager.getIconShape() .createRevealAnimator(this, mStartRevealRect, mOutline, mTaskCornerRadius, !isOpening); mRevealAnimator.addListener(forEndCallback(() -> mRevealAnimator = null)); @@ -310,17 +315,24 @@ public class ClipIconView extends View implements ClipPathView { @Override public void draw(Canvas canvas) { - int count = canvas.save(); + int count1 = canvas.save(); if (mClipPath != null) { canvas.clipPath(mClipPath); } - super.draw(canvas); + int count2 = canvas.save(); + float iconCenterX = + (mFinalDrawableBounds.right - mFinalDrawableBounds.left) / 2f * mIconScale; + float iconCenterY = + (mFinalDrawableBounds.bottom - mFinalDrawableBounds.top) / 2f * mIconScale; + canvas.scale(mIconScale, mIconScale, iconCenterX, iconCenterY); if (mBackground != null) { mBackground.draw(canvas); } if (mForeground != null) { mForeground.draw(canvas); } + canvas.restoreToCount(count2); + super.draw(canvas); if (mTaskViewArtist != null) { canvas.saveLayerAlpha( 0, @@ -334,7 +346,7 @@ public class ClipIconView extends View implements ClipPathView { canvas.scale(drawScale, drawScale); mTaskViewArtist.taskViewDrawCallback.accept(canvas); } - canvas.restoreToCount(count); + canvas.restoreToCount(count1); } void recycle() { From 0e18dee91dbc06cf84d5181e00a5c95c6ceff8eb Mon Sep 17 00:00:00 2001 From: Charlie Anderson Date: Tue, 18 Feb 2025 13:42:48 -0500 Subject: [PATCH 044/153] Fix WorkspaceItemProcessorTest for HSUM Bug: 395684478 Test: WorkspaceItemProcessorTest Flag: EXEMPT test fix Change-Id: Ib884af01fd225a01a7ba5408bcb38991b7b4c2c4 --- .../android/launcher3/model/WorkspaceItemProcessorTest.kt | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/multivalentTests/src/com/android/launcher3/model/WorkspaceItemProcessorTest.kt b/tests/multivalentTests/src/com/android/launcher3/model/WorkspaceItemProcessorTest.kt index 7a403e1826..a55d64ba4f 100644 --- a/tests/multivalentTests/src/com/android/launcher3/model/WorkspaceItemProcessorTest.kt +++ b/tests/multivalentTests/src/com/android/launcher3/model/WorkspaceItemProcessorTest.kt @@ -454,7 +454,7 @@ class WorkspaceItemProcessorTest { assertThat(mAllDeepShortcuts).isEmpty() verify(mockCursor) .markDeleted( - "Pinned shortcut not found from request. package=pkg, user=UserHandle{0}", + "Pinned shortcut not found from request. package=pkg, user=$mUserHandle", "shortcut_not_found", ) } @@ -513,7 +513,7 @@ class WorkspaceItemProcessorTest { verify(mockCursor, times(0)).checkAndAddItem(any(), any(), anyOrNull()) verify(mockCursor) .markDeleted( - "Pinned shortcut not found from request. package=pkg, user=UserHandle{0}", + "Pinned shortcut not found from request. package=pkg, user=$mUserHandle", "shortcut_not_found", ) } @@ -533,7 +533,7 @@ class WorkspaceItemProcessorTest { whenever(disabledMessage).thenReturn("") whenever(disabledReason).thenReturn(0) whenever(persons).thenReturn(EMPTY_PERSON_ARRAY) - whenever(userHandle).thenReturn(Process.myUserHandle()) + whenever(userHandle).thenReturn(mUserHandle) } mIconRequestInfos = mutableListOf() // Make sure shortcuts map has expected key from expected package @@ -565,7 +565,7 @@ class WorkspaceItemProcessorTest { mockBgDataModel = mock() mockCursor = mock().apply { - user = UserHandle(0) + user = mUserHandle itemType = ITEM_TYPE_FOLDER id = 1 container = 100 From 39c4bf24482aeb85a7bc10874a7f7383619490d0 Mon Sep 17 00:00:00 2001 From: mpodolian Date: Thu, 13 Feb 2025 16:56:16 -0800 Subject: [PATCH 045/153] Handle new bubble notification while drag is in progress. Handle new bubble notification while drag is in progress. Updated logic to react to new bubble notifications arriving during drag operations before a drop occurs. Bug: 388894910 Flag: com.android.wm.shell.enable_create_any_bubble Test: BubbleBarViewAnimatorTest Test: Manual. Go to some application and have no bubbles. Start dragging the taskbar icon over the bubble bar drop zone. Trigger new bubble with the bubbles test application. Observe drop target is hidden and new bubble is animated in, followed by flyout. When flyout disappears, bubble bar remains on the screen. Release icon over the bubble bar. Observe newly added application bubble is expanded. Repeat same test, but drag the taskbar icon to the opposite side. Test: Manual. Go to some application, but have bubbles. Start dragging the taskbar icon over the bubble bar drop zone. Trigger new bubble with the bubbles test application. Observe new bubble is added and the flyout is shown. When flyout disappears, bubble bar remains on the screen. Release icon over the bubble bar. Observe newly added application bubble is expanded. Repeat same test, but drag the taskbar icon to the opposite side. Change-Id: I6fe1139ef56f4ad40d36a804016d23a9b34abf5f --- .../bubbles/BubbleBarViewController.java | 12 +++- .../animation/BubbleBarViewAnimator.kt | 30 +++++---- .../animation/BubbleBarViewAnimatorTest.kt | 66 +++++++++++++++++++ 3 files changed, 94 insertions(+), 14 deletions(-) diff --git a/quickstep/src/com/android/launcher3/taskbar/bubbles/BubbleBarViewController.java b/quickstep/src/com/android/launcher3/taskbar/bubbles/BubbleBarViewController.java index b02b85fad4..b90a5b001a 100644 --- a/quickstep/src/com/android/launcher3/taskbar/bubbles/BubbleBarViewController.java +++ b/quickstep/src/com/android/launcher3/taskbar/bubbles/BubbleBarViewController.java @@ -276,7 +276,10 @@ public class BubbleBarViewController { @Override public boolean isOnLeft() { - return mBarView.getBubbleBarLocation().isOnLeft(mBarView.isLayoutRtl()); + boolean shouldRevertLocation = + mBarView.isShowingDropTarget() && mIsLocationUpdatedForDropTarget; + boolean isOnLeft = mBarView.getBubbleBarLocation().isOnLeft(mBarView.isLayoutRtl()); + return shouldRevertLocation != isOnLeft; } @Override @@ -1053,7 +1056,12 @@ public class BubbleBarViewController { boolean isInApp = mTaskbarStashController.isInApp(); // if this is the first bubble, animate to the initial state. if (mBarView.getBubbleChildCount() == 1 && !isUpdate) { - mBubbleBarViewAnimator.animateToInitialState(bubble, isInApp, isExpanding); + // If a drop target is visible and the first bubble is added, hide the empty drop target + if (mBarView.isShowingDropTarget()) { + mBubbleBarPinController.hideDropTarget(); + } + mBubbleBarViewAnimator.animateToInitialState(bubble, isInApp, isExpanding, + mBarView.isShowingDropTarget()); return; } // if we're not stashed or we're in persistent taskbar, animate for collapsed state. diff --git a/quickstep/src/com/android/launcher3/taskbar/bubbles/animation/BubbleBarViewAnimator.kt b/quickstep/src/com/android/launcher3/taskbar/bubbles/animation/BubbleBarViewAnimator.kt index 745c689541..30cfafe694 100644 --- a/quickstep/src/com/android/launcher3/taskbar/bubbles/animation/BubbleBarViewAnimator.kt +++ b/quickstep/src/com/android/launcher3/taskbar/bubbles/animation/BubbleBarViewAnimator.kt @@ -365,7 +365,12 @@ constructor( } /** Animates to the initial state of the bubble bar, when there are no previous bubbles. */ - fun animateToInitialState(b: BubbleBarBubble, isInApp: Boolean, isExpanding: Boolean) { + fun animateToInitialState( + b: BubbleBarBubble, + isInApp: Boolean, + isExpanding: Boolean, + isDragging: Boolean = false, + ) { val bubbleView = b.view val animator = PhysicsAnimator.getInstance(bubbleView) if (animator.isRunning()) animator.cancel() @@ -374,15 +379,12 @@ constructor( // bubble bar to the handle if we're in an app. val showAnimation = buildBubbleBarSpringInAnimation() val hideAnimation = - if (isInApp && !isExpanding) { + if (isInApp && !isExpanding && !isDragging) { buildBubbleBarToHandleAnimation() } else { Runnable { - moveToState(AnimatingBubble.State.ANIMATING_OUT) - bubbleBarFlyoutController.collapseFlyout { - onFlyoutRemoved() - clearAnimatingBubble() - } + collapseFlyoutAndUpdateState() + if (isDragging) return@Runnable bubbleStashController.showBubbleBarImmediate() bubbleStashController.updateTaskbarTouchRegion() } @@ -440,11 +442,7 @@ constructor( // first bounce the bubble bar and show the flyout. Then hide the flyout. val showAnimation = buildBubbleBarBounceAnimation() val hideAnimation = Runnable { - moveToState(AnimatingBubble.State.ANIMATING_OUT) - bubbleBarFlyoutController.collapseFlyout { - onFlyoutRemoved() - clearAnimatingBubble() - } + collapseFlyoutAndUpdateState() bubbleStashController.showBubbleBarImmediate() bubbleStashController.updateTaskbarTouchRegion() } @@ -454,6 +452,14 @@ constructor( scheduler.postDelayed(FLYOUT_DELAY_MS, hideAnimation) } + private fun collapseFlyoutAndUpdateState() { + moveToState(AnimatingBubble.State.ANIMATING_OUT) + bubbleBarFlyoutController.collapseFlyout { + onFlyoutRemoved() + clearAnimatingBubble() + } + } + /** * The bubble bar animation when it is collapsed is divided into 2 chained animations. The first * animation is a regular accelerate animation that moves the bubble bar upwards. When it ends diff --git a/quickstep/tests/multivalentTests/src/com/android/launcher3/taskbar/bubbles/animation/BubbleBarViewAnimatorTest.kt b/quickstep/tests/multivalentTests/src/com/android/launcher3/taskbar/bubbles/animation/BubbleBarViewAnimatorTest.kt index 46b5659ce9..a456fb9c73 100644 --- a/quickstep/tests/multivalentTests/src/com/android/launcher3/taskbar/bubbles/animation/BubbleBarViewAnimatorTest.kt +++ b/quickstep/tests/multivalentTests/src/com/android/launcher3/taskbar/bubbles/animation/BubbleBarViewAnimatorTest.kt @@ -60,6 +60,7 @@ import org.mockito.kotlin.any import org.mockito.kotlin.atLeastOnce import org.mockito.kotlin.eq import org.mockito.kotlin.mock +import org.mockito.kotlin.never import org.mockito.kotlin.verify import org.mockito.kotlin.whenever @@ -572,6 +573,71 @@ class BubbleBarViewAnimatorTest { verify(bubbleStashController).stashBubbleBarImmediate() } + @Test + fun animateToInitialState_whileDragging_inApp() { + setUpBubbleBar() + setUpBubbleStashController() + whenever(bubbleStashController.bubbleBarTranslationY) + .thenReturn(BAR_TRANSLATION_Y_FOR_TASKBAR) + + val handle = View(context) + val handleAnimator = PhysicsAnimator.getInstance(handle) + whenever(bubbleStashController.getStashedHandlePhysicsAnimator()).thenReturn(handleAnimator) + + val barAnimator = PhysicsAnimator.getInstance(bubbleBarView) + + var notifiedBubbleBarVisible = false + val onBubbleBarVisible = Runnable { notifiedBubbleBarVisible = true } + val animator = + BubbleBarViewAnimator( + bubbleBarView, + bubbleStashController, + flyoutController, + bubbleBarParentViewController, + onExpanded = emptyRunnable, + onBubbleBarVisible = onBubbleBarVisible, + animatorScheduler, + ) + + InstrumentationRegistry.getInstrumentation().runOnMainSync { + bubbleBarView.visibility = INVISIBLE + animator.animateToInitialState( + bubble, + isInApp = true, + isExpanding = false, + isDragging = true, + ) + } + + InstrumentationRegistry.getInstrumentation().runOnMainSync {} + PhysicsAnimatorTestUtils.blockUntilAnimationsEnd(DynamicAnimation.TRANSLATION_Y) + + barAnimator.assertIsNotRunning() + assertThat(animator.isAnimating).isTrue() + assertThat(bubbleBarView.alpha).isEqualTo(1) + assertThat(bubbleBarView.translationY).isEqualTo(BAR_TRANSLATION_Y_FOR_TASKBAR) + assertThat(bubbleBarParentViewController.timesInvoked).isEqualTo(1) + waitForFlyoutToShow() + + assertThat(animatorScheduler.delayedBlock).isNotNull() + InstrumentationRegistry.getInstrumentation().runOnMainSync(animatorScheduler.delayedBlock!!) + + waitForFlyoutToHide() + + InstrumentationRegistry.getInstrumentation().runOnMainSync {} + PhysicsAnimatorTestUtils.blockUntilAnimationsEnd(DynamicAnimation.TRANSLATION_Y) + + InstrumentationRegistry.getInstrumentation().waitForIdleSync() + assertThat(bubbleBarParentViewController.timesInvoked).isEqualTo(2) + assertThat(animator.isAnimating).isFalse() + assertThat(bubbleBarView.alpha).isEqualTo(1) + assertThat(handle.translationY).isEqualTo(0) + assertThat(bubbleBarView.visibility).isEqualTo(VISIBLE) + assertThat(notifiedBubbleBarVisible).isTrue() + + verify(bubbleStashController, never()).stashBubbleBarImmediate() + } + @Test fun animateToInitialState_inApp_autoExpanding() { setUpBubbleBar() From 41111bd8f6f78d990c59c860b52ebc73a72cac40 Mon Sep 17 00:00:00 2001 From: Ahmed Fakhry Date: Sat, 15 Feb 2025 04:17:35 +0000 Subject: [PATCH 046/153] Do not crash DesktopVisibilityController on unknown displays Instead of requiring that a valid display ID is given to the APIs in `DesktopVisibilityController` and crashing the Launcher, this CL lets the code handle invalid IDs gracefully, and adds a test that fails without the fix. Bug: 392986431 Test: atest NexusLauncherTests:com.android.launcher3.statehandlers.DesktopVisibilityControllerTest Flag: com.android.window.flags.enable_multiple_desktops_frontend Flag: com.android.window.flags.enable_multiple_desktops_backend Change-Id: Id1bc7876ce654b96191c85089557b9279963acd8 --- .../DesktopVisibilityController.kt | 20 ++--- .../DesktopVisibilityControllerTest.kt | 80 +++++++++++++++++++ 2 files changed, 90 insertions(+), 10 deletions(-) create mode 100644 quickstep/tests/src/com/android/launcher3/statehandlers/DesktopVisibilityControllerTest.kt diff --git a/quickstep/src/com/android/launcher3/statehandlers/DesktopVisibilityController.kt b/quickstep/src/com/android/launcher3/statehandlers/DesktopVisibilityController.kt index 3773d027ed..37e8d4dcd0 100644 --- a/quickstep/src/com/android/launcher3/statehandlers/DesktopVisibilityController.kt +++ b/quickstep/src/com/android/launcher3/statehandlers/DesktopVisibilityController.kt @@ -18,6 +18,7 @@ package com.android.launcher3.statehandlers import android.content.Context import android.os.Debug import android.util.Log +import android.util.Slog import android.util.SparseArray import android.view.Display.DEFAULT_DISPLAY import android.window.DesktopModeFlags.ENABLE_DESKTOP_WINDOWING_WALLPAPER_ACTIVITY @@ -152,7 +153,8 @@ constructor( return areDesktopTasksVisible() } - val isInDesktopMode = displaysDesksConfigsMap[displayId].activeDeskId != INACTIVE_DESK_ID + val activeDeskId = getDisplayDeskConfig(displayId)?.activeDeskId ?: INACTIVE_DESK_ID + val isInDesktopMode = activeDeskId != INACTIVE_DESK_ID if (DEBUG) { Log.d(TAG, "isInDesktopMode: $isInDesktopMode") } @@ -409,18 +411,16 @@ constructor( } } - private fun getDisplayDeskConfig(displayId: Int): DisplayDeskConfig { - return checkNotNull(displaysDesksConfigsMap[displayId]) { - "Expected non-null desk config for display: $displayId" - } - } + private fun getDisplayDeskConfig(displayId: Int) = + displaysDesksConfigsMap[displayId] + ?: null.also { Slog.e(TAG, "Expected non-null desk config for display: $displayId") } private fun onCanCreateDesksChanged(displayId: Int, canCreateDesks: Boolean) { if (!DesktopModeStatus.enableMultipleDesktops(context)) { return } - getDisplayDeskConfig(displayId).canCreateDesks = canCreateDesks + getDisplayDeskConfig(displayId)?.canCreateDesks = canCreateDesks } private fun onDeskAdded(displayId: Int, deskId: Int) { @@ -428,7 +428,7 @@ constructor( return } - getDisplayDeskConfig(displayId).also { + getDisplayDeskConfig(displayId)?.also { check(it.deskIds.add(deskId)) { "Found a duplicate desk Id: $deskId on display: $displayId" } @@ -440,7 +440,7 @@ constructor( return } - getDisplayDeskConfig(displayId).also { + getDisplayDeskConfig(displayId)?.also { check(it.deskIds.remove(deskId)) { "Removing non-existing desk Id: $deskId on display: $displayId" } @@ -457,7 +457,7 @@ constructor( val wasInDesktopMode = isInDesktopModeAndNotInOverview(displayId) - getDisplayDeskConfig(displayId).also { + getDisplayDeskConfig(displayId)?.also { check(oldActiveDesk == it.activeDeskId) { "Mismatch between the Shell's oldActiveDesk: $oldActiveDesk, and Launcher's: ${it.activeDeskId}" } diff --git a/quickstep/tests/src/com/android/launcher3/statehandlers/DesktopVisibilityControllerTest.kt b/quickstep/tests/src/com/android/launcher3/statehandlers/DesktopVisibilityControllerTest.kt new file mode 100644 index 0000000000..4b8f2a2348 --- /dev/null +++ b/quickstep/tests/src/com/android/launcher3/statehandlers/DesktopVisibilityControllerTest.kt @@ -0,0 +1,80 @@ +/* + * 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.launcher3.statehandlers + +import android.content.Context +import android.platform.test.annotations.EnableFlags +import android.platform.test.flag.junit.SetFlagsRule +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.filters.SmallTest +import com.android.dx.mockito.inline.extended.ExtendedMockito.mockitoSession +import com.android.launcher3.util.DaggerSingletonTracker +import com.android.quickstep.SystemUiProxy +import com.android.window.flags.Flags.FLAG_ENABLE_MULTIPLE_DESKTOPS_BACKEND +import com.android.window.flags.Flags.FLAG_ENABLE_MULTIPLE_DESKTOPS_FRONTEND +import com.android.wm.shell.shared.desktopmode.DesktopModeStatus +import org.junit.After +import org.junit.Assert.assertFalse +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever +import org.mockito.quality.Strictness + +/** + * Tests the behavior of [DesktopVisibilityController] in regards to multiple desktops and multiple + * displays. + */ +@SmallTest +@RunWith(AndroidJUnit4::class) +class DesktopVisibilityControllerTest { + + @get:Rule val setFlagsRule = SetFlagsRule() + + private val mockitoSession = + mockitoSession() + .strictness(Strictness.LENIENT) + .mockStatic(DesktopModeStatus::class.java) + .startMocking() + + private val context = mock() + private val systemUiProxy = mock() + private val lifeCycleTracker = mock() + private lateinit var desktopVisibilityController: DesktopVisibilityController + + @Before + fun setUp() { + whenever(context.resources).thenReturn(mock()) + whenever(DesktopModeStatus.enableMultipleDesktops(context)).thenReturn(true) + desktopVisibilityController = + DesktopVisibilityController(context, systemUiProxy, lifeCycleTracker) + } + + @After + fun tearDown() { + mockitoSession.finishMocking() + } + + @Test + @EnableFlags(FLAG_ENABLE_MULTIPLE_DESKTOPS_BACKEND, FLAG_ENABLE_MULTIPLE_DESKTOPS_FRONTEND) + fun noCrashWhenCheckingNonExistentDisplay() { + assertFalse(desktopVisibilityController.isInDesktopMode(displayId = 500)) + assertFalse(desktopVisibilityController.isInDesktopModeAndNotInOverview(displayId = 300)) + } +} From b82394758f99fdc00b9e4bd57b9c186d09cab198 Mon Sep 17 00:00:00 2001 From: Sunny Goyal Date: Fri, 14 Feb 2025 13:08:00 -0800 Subject: [PATCH 047/153] Moving LauncherModel initialization to a separate class Bug: 361850561 Test: Presubmit Flag: EXEMPT dagger Change-Id: Ie210473a9e158faa421c00f115ffcca680f84ae4 --- .../launcher3/InvariantDeviceProfile.java | 3 +- .../android/launcher3/LauncherAppState.java | 141 ++------------- src/com/android/launcher3/LauncherModel.kt | 14 +- .../launcher3/model/ModelInitializer.kt | 165 ++++++++++++++++++ .../launcher3/pm/InstallSessionTracker.java | 7 +- .../launcher3/pm/InstallSessionTrackerTest.kt | 2 +- 6 files changed, 191 insertions(+), 141 deletions(-) create mode 100644 src/com/android/launcher3/model/ModelInitializer.kt diff --git a/src/com/android/launcher3/InvariantDeviceProfile.java b/src/com/android/launcher3/InvariantDeviceProfile.java index c2d6df52a3..870e6d63ef 100644 --- a/src/com/android/launcher3/InvariantDeviceProfile.java +++ b/src/com/android/launcher3/InvariantDeviceProfile.java @@ -85,6 +85,7 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Objects; +import java.util.concurrent.CopyOnWriteArrayList; import java.util.stream.Collectors; import javax.inject.Inject; @@ -252,7 +253,7 @@ public class InvariantDeviceProfile { public Point defaultWallpaperSize; - private final ArrayList mChangeListeners = new ArrayList<>(); + private final List mChangeListeners = new CopyOnWriteArrayList<>(); @Inject InvariantDeviceProfile( diff --git a/src/com/android/launcher3/LauncherAppState.java b/src/com/android/launcher3/LauncherAppState.java index 71013c3fa6..bf2ad92e61 100644 --- a/src/com/android/launcher3/LauncherAppState.java +++ b/src/com/android/launcher3/LauncherAppState.java @@ -16,54 +16,32 @@ package com.android.launcher3; -import static android.app.admin.DevicePolicyManager.ACTION_DEVICE_POLICY_RESOURCE_UPDATED; -import static android.content.Context.RECEIVER_EXPORTED; - -import static com.android.launcher3.Flags.enableSmartspaceRemovalToggle; -import static com.android.launcher3.model.LoaderTask.SMARTSPACE_ON_HOME_SCREEN; -import static com.android.launcher3.util.Executors.MODEL_EXECUTOR; -import static com.android.launcher3.util.Executors.UI_HELPER_EXECUTOR; -import static com.android.launcher3.util.SettingsCache.NOTIFICATION_BADGING_URI; -import static com.android.launcher3.util.SettingsCache.PRIVATE_SPACE_HIDE_WHEN_LOCKED_URI; - -import android.content.ComponentName; import android.content.Context; -import android.content.SharedPreferences; -import android.content.SharedPreferences.OnSharedPreferenceChangeListener; -import android.content.pm.LauncherApps; -import android.content.pm.LauncherApps.ArchiveCompatibilityParams; import android.util.Log; import androidx.annotation.Nullable; -import androidx.core.os.BuildCompat; +import com.android.launcher3.dagger.LauncherComponentProvider; import com.android.launcher3.graphics.ThemeManager; -import com.android.launcher3.graphics.ThemeManager.ThemeChangeListener; import com.android.launcher3.icons.IconCache; import com.android.launcher3.icons.IconProvider; import com.android.launcher3.icons.LauncherIconProvider; -import com.android.launcher3.icons.LauncherIcons; -import com.android.launcher3.model.ModelLauncherCallbacks; +import com.android.launcher3.model.ModelInitializer; import com.android.launcher3.model.WidgetsFilterDataProvider; -import com.android.launcher3.notification.NotificationListener; import com.android.launcher3.pm.InstallSessionHelper; -import com.android.launcher3.pm.InstallSessionTracker; import com.android.launcher3.pm.UserCache; -import com.android.launcher3.util.LockedUserState; import com.android.launcher3.util.MainThreadInitializedObject; import com.android.launcher3.util.PackageManagerHelper; import com.android.launcher3.util.Preconditions; import com.android.launcher3.util.RunnableList; import com.android.launcher3.util.SafeCloseable; import com.android.launcher3.util.SettingsCache; -import com.android.launcher3.util.SimpleBroadcastReceiver; import com.android.launcher3.util.TraceHelper; import com.android.launcher3.widget.custom.CustomWidgetManager; public class LauncherAppState implements SafeCloseable { public static final String TAG = "LauncherAppState"; - public static final String ACTION_FORCE_ROLOAD = "force-reload-launcher"; // We do not need any synchronization for this variable as its only written on UI thread. public static final MainThreadInitializedObject INSTANCE = @@ -94,82 +72,21 @@ public class LauncherAppState implements SafeCloseable { mIsSafeModeEnabled = TraceHelper.allowIpcs("isSafeMode", () -> context.getPackageManager().isSafeMode()); - mInvariantDeviceProfile.addOnChangeListener(modelPropertiesChanged -> { - if (modelPropertiesChanged) { - refreshAndReloadLauncher(); - } - }); - ThemeChangeListener themeChangeListener = this::refreshAndReloadLauncher; - ThemeManager.INSTANCE.get(context).addChangeListener(themeChangeListener); - mOnTerminateCallback.add(() -> - ThemeManager.INSTANCE.get(context).removeChangeListener(themeChangeListener)); - - ModelLauncherCallbacks callbacks = mModel.newModelCallbacks(); - LauncherApps launcherApps = mContext.getSystemService(LauncherApps.class); - launcherApps.registerCallback(callbacks); - mOnTerminateCallback.add(() -> - mContext.getSystemService(LauncherApps.class).unregisterCallback(callbacks)); - - if (BuildCompat.isAtLeastV() && Flags.enableSupportForArchiving()) { - ArchiveCompatibilityParams params = new ArchiveCompatibilityParams(); - params.setEnableUnarchivalConfirmation(false); - params.setEnableIconOverlay(!Flags.useNewIconForArchivedApps()); - launcherApps.setArchiveCompatibility(params); - } - - SimpleBroadcastReceiver modelChangeReceiver = - new SimpleBroadcastReceiver(context, UI_HELPER_EXECUTOR, mModel::onBroadcastIntent); - modelChangeReceiver.register( - ACTION_DEVICE_POLICY_RESOURCE_UPDATED); - if (BuildConfig.IS_STUDIO_BUILD) { - modelChangeReceiver.register(RECEIVER_EXPORTED, ACTION_FORCE_ROLOAD); - } - mOnTerminateCallback.add(() -> modelChangeReceiver.unregisterReceiverSafely()); - - SafeCloseable userChangeListener = UserCache.INSTANCE.get(mContext) - .addUserEventListener(mModel::onUserEvent); - mOnTerminateCallback.add(userChangeListener::close); - - if (enableSmartspaceRemovalToggle()) { - OnSharedPreferenceChangeListener firstPagePinnedItemListener = - new OnSharedPreferenceChangeListener() { - @Override - public void onSharedPreferenceChanged( - SharedPreferences sharedPreferences, String key) { - if (SMARTSPACE_ON_HOME_SCREEN.equals(key)) { - mModel.forceReload(); - } - } - }; - LauncherPrefs.getPrefs(mContext).registerOnSharedPreferenceChangeListener( - firstPagePinnedItemListener); - mOnTerminateCallback.add(() -> LauncherPrefs.getPrefs(mContext) - .unregisterOnSharedPreferenceChangeListener(firstPagePinnedItemListener)); - } - - LockedUserState.get(context).runOnUserUnlocked(() -> { - CustomWidgetManager cwm = CustomWidgetManager.INSTANCE.get(mContext); - mOnTerminateCallback.add(cwm.addWidgetRefreshCallback(mModel::rebindCallbacks)::close); - - SafeCloseable iconChangeTracker = mIconProvider.registerIconChangeListener( - mModel::onAppIconChanged, MODEL_EXECUTOR.getHandler()); - mOnTerminateCallback.add(iconChangeTracker::close); - - InstallSessionTracker installSessionTracker = - InstallSessionHelper.INSTANCE.get(context).registerInstallTracker(callbacks); - mOnTerminateCallback.add(installSessionTracker::unregister); - }); - - // Register an observer to rebind the notification listener when dots are re-enabled. - SettingsCache settingsCache = SettingsCache.INSTANCE.get(mContext); - SettingsCache.OnChangeListener notificationLister = this::onNotificationSettingsChanged; - settingsCache.register(NOTIFICATION_BADGING_URI, notificationLister); - onNotificationSettingsChanged(settingsCache.getValue(NOTIFICATION_BADGING_URI)); - mOnTerminateCallback.add(() -> - settingsCache.unregister(NOTIFICATION_BADGING_URI, notificationLister)); - // Register an observer to notify Launcher about Private Space settings toggle. - registerPrivateSpaceHideWhenLockListener(settingsCache); + ModelInitializer initializer = new ModelInitializer( + context, + LauncherComponentProvider.get(context).getIconPool(), + mIconCache, + mInvariantDeviceProfile, + ThemeManager.INSTANCE.get(context), + UserCache.INSTANCE.get(context), + SettingsCache.INSTANCE.get(context), + mIconProvider, + CustomWidgetManager.INSTANCE.get(context), + InstallSessionHelper.INSTANCE.get(context), + closeable -> mOnTerminateCallback.add(closeable::close) + ); + initializer.initialize(mModel); } public LauncherAppState(Context context, @Nullable String iconCacheFileName) { @@ -186,32 +103,6 @@ public class LauncherAppState implements SafeCloseable { mOnTerminateCallback.add(mModel::destroy); } - private void onNotificationSettingsChanged(boolean areNotificationDotsEnabled) { - if (areNotificationDotsEnabled) { - NotificationListener.requestRebind(new ComponentName( - mContext, NotificationListener.class)); - } - } - - private void registerPrivateSpaceHideWhenLockListener(SettingsCache settingsCache) { - SettingsCache.OnChangeListener psHideWhenLockChangedListener = - this::onPrivateSpaceHideWhenLockChanged; - settingsCache.register(PRIVATE_SPACE_HIDE_WHEN_LOCKED_URI, psHideWhenLockChangedListener); - mOnTerminateCallback.add(() -> settingsCache.unregister(PRIVATE_SPACE_HIDE_WHEN_LOCKED_URI, - psHideWhenLockChangedListener)); - } - - private void onPrivateSpaceHideWhenLockChanged(boolean isPrivateSpaceHideOnLockEnabled) { - mModel.forceReload(); - } - - private void refreshAndReloadLauncher() { - LauncherIcons.clearPool(mContext); - mIconCache.updateIconParams( - mInvariantDeviceProfile.fillResIconDpi, mInvariantDeviceProfile.iconBitmapSize); - mModel.forceReload(); - } - /** * Call from Application.onTerminate(), which is not guaranteed to ever be called. */ diff --git a/src/com/android/launcher3/LauncherModel.kt b/src/com/android/launcher3/LauncherModel.kt index 185629b30e..6e4276d3e9 100644 --- a/src/com/android/launcher3/LauncherModel.kt +++ b/src/com/android/launcher3/LauncherModel.kt @@ -15,13 +15,11 @@ */ package com.android.launcher3 -import android.app.admin.DevicePolicyManager import android.content.Context import android.content.Intent import android.content.pm.ShortcutInfo import android.os.UserHandle import android.text.TextUtils -import android.util.Log import android.util.Pair import androidx.annotation.WorkerThread import com.android.launcher3.celllayout.CellPosMapper @@ -47,7 +45,6 @@ import com.android.launcher3.model.data.ItemInfo import com.android.launcher3.model.data.WorkspaceItemInfo import com.android.launcher3.pm.UserCache import com.android.launcher3.shortcuts.ShortcutRequest -import com.android.launcher3.testing.shared.TestProtocol.sDebugTracing import com.android.launcher3.util.Executors.MAIN_EXECUTOR import com.android.launcher3.util.Executors.MODEL_EXECUTOR import com.android.launcher3.util.PackageManagerHelper @@ -173,15 +170,8 @@ class LauncherModel( } } - fun onBroadcastIntent(intent: Intent) { - if (DEBUG_RECEIVER || sDebugTracing) Log.d(TAG, "onReceive intent=$intent") - when (intent.action) { - LauncherAppState.ACTION_FORCE_ROLOAD -> - // If we have changed locale we need to clear out the labels in all apps/workspace. - forceReload() - DevicePolicyManager.ACTION_DEVICE_POLICY_RESOURCE_UPDATED -> - enqueueModelUpdateTask(ReloadStringCacheTask(this.modelDelegate)) - } + fun reloadStringCache() { + enqueueModelUpdateTask(ReloadStringCacheTask(this.modelDelegate)) } /** diff --git a/src/com/android/launcher3/model/ModelInitializer.kt b/src/com/android/launcher3/model/ModelInitializer.kt new file mode 100644 index 0000000000..69a320a0e2 --- /dev/null +++ b/src/com/android/launcher3/model/ModelInitializer.kt @@ -0,0 +1,165 @@ +/* + * 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.launcher3.model + +import android.app.admin.DevicePolicyManager.ACTION_DEVICE_POLICY_RESOURCE_UPDATED +import android.content.ComponentName +import android.content.Context +import android.content.SharedPreferences +import android.content.pm.LauncherApps +import android.content.pm.LauncherApps.ArchiveCompatibilityParams +import com.android.launcher3.BuildConfig +import com.android.launcher3.Flags +import com.android.launcher3.InvariantDeviceProfile +import com.android.launcher3.InvariantDeviceProfile.OnIDPChangeListener +import com.android.launcher3.LauncherModel +import com.android.launcher3.LauncherPrefs.Companion.getPrefs +import com.android.launcher3.Utilities +import com.android.launcher3.dagger.ApplicationContext +import com.android.launcher3.graphics.ThemeManager +import com.android.launcher3.graphics.ThemeManager.ThemeChangeListener +import com.android.launcher3.icons.IconCache +import com.android.launcher3.icons.LauncherIconProvider +import com.android.launcher3.icons.LauncherIcons.IconPool +import com.android.launcher3.notification.NotificationListener +import com.android.launcher3.pm.InstallSessionHelper +import com.android.launcher3.pm.UserCache +import com.android.launcher3.util.Executors.MODEL_EXECUTOR +import com.android.launcher3.util.Executors.UI_HELPER_EXECUTOR +import com.android.launcher3.util.SafeCloseable +import com.android.launcher3.util.SettingsCache +import com.android.launcher3.util.SettingsCache.NOTIFICATION_BADGING_URI +import com.android.launcher3.util.SettingsCache.PRIVATE_SPACE_HIDE_WHEN_LOCKED_URI +import com.android.launcher3.util.SimpleBroadcastReceiver +import com.android.launcher3.widget.custom.CustomWidgetManager +import java.util.function.Consumer + +/** Utility class for initializing all model callbacks */ +class ModelInitializer( + @ApplicationContext private val context: Context, + private val iconPool: IconPool, + private val iconCache: IconCache, + private val idp: InvariantDeviceProfile, + private val themeManager: ThemeManager, + private val userCache: UserCache, + private val settingsCache: SettingsCache, + private val iconProvider: LauncherIconProvider, + private val customWidgetManager: CustomWidgetManager, + private val installSessionHelper: InstallSessionHelper, + private val closeActions: Consumer, +) { + + fun initialize(model: LauncherModel) { + fun refreshAndReloadLauncher() { + iconPool.clear() + iconCache.updateIconParams(idp.fillResIconDpi, idp.iconBitmapSize) + model.forceReload() + } + + // IDP changes + val idpChangeListener = OnIDPChangeListener { modelChanged -> + if (modelChanged) refreshAndReloadLauncher() + } + idp.addOnChangeListener(idpChangeListener) + closeActions.accept { idp.removeOnChangeListener(idpChangeListener) } + + // Theme changes + val themeChangeListener = ThemeChangeListener { refreshAndReloadLauncher() } + themeManager.addChangeListener(themeChangeListener) + closeActions.accept { themeManager.removeChangeListener(themeChangeListener) } + + // System changes + val modelCallbacks = model.newModelCallbacks() + val launcherApps = context.getSystemService(LauncherApps::class.java)!! + launcherApps.registerCallback(modelCallbacks) + closeActions.accept { launcherApps.unregisterCallback(modelCallbacks) } + + if (Utilities.ATLEAST_V && Flags.enableSupportForArchiving()) { + launcherApps.setArchiveCompatibility( + ArchiveCompatibilityParams().apply { + setEnableUnarchivalConfirmation(false) + setEnableIconOverlay(!Flags.useNewIconForArchivedApps()) + } + ) + } + + // Device profile policy changes + val dpUpdateReceiver = + SimpleBroadcastReceiver(context, UI_HELPER_EXECUTOR) { model.reloadStringCache() } + dpUpdateReceiver.register(ACTION_DEVICE_POLICY_RESOURCE_UPDATED) + closeActions.accept { dpUpdateReceiver.unregisterReceiverSafely() } + + // Development helper + if (BuildConfig.IS_STUDIO_BUILD) { + val reloadReceiver = + SimpleBroadcastReceiver(context, UI_HELPER_EXECUTOR) { model.forceReload() } + reloadReceiver.register(Context.RECEIVER_EXPORTED, ACTION_FORCE_RELOAD) + closeActions.accept { reloadReceiver.unregisterReceiverSafely() } + } + + // User changes + closeActions.accept(userCache.addUserEventListener(model::onUserEvent)) + + // Private space settings changes + val psSettingsListener = SettingsCache.OnChangeListener { model.forceReload() } + settingsCache.register(PRIVATE_SPACE_HIDE_WHEN_LOCKED_URI, psSettingsListener) + closeActions.accept { + settingsCache.unregister(PRIVATE_SPACE_HIDE_WHEN_LOCKED_URI, psSettingsListener) + } + + // Notification dots changes + val notificationChanges = + SettingsCache.OnChangeListener { dotsEnabled -> + if (dotsEnabled) + NotificationListener.requestRebind( + ComponentName(context, NotificationListener::class.java) + ) + } + settingsCache.register(NOTIFICATION_BADGING_URI, notificationChanges) + notificationChanges.onSettingsChanged(settingsCache.getValue(NOTIFICATION_BADGING_URI)) + closeActions.accept { + settingsCache.unregister(NOTIFICATION_BADGING_URI, notificationChanges) + } + + // removable smartspace + if (Flags.enableSmartspaceRemovalToggle()) { + val smartSpacePrefChanges = + SharedPreferences.OnSharedPreferenceChangeListener { _, key -> + if (LoaderTask.SMARTSPACE_ON_HOME_SCREEN == key) model.forceReload() + } + getPrefs(context).registerOnSharedPreferenceChangeListener(smartSpacePrefChanges) + closeActions.accept { + getPrefs(context).unregisterOnSharedPreferenceChangeListener(smartSpacePrefChanges) + } + } + + // Custom widgets + closeActions.accept(customWidgetManager.addWidgetRefreshCallback(model::rebindCallbacks)) + + // Icon changes + closeActions.accept( + iconProvider.registerIconChangeListener(model::onAppIconChanged, MODEL_EXECUTOR.handler) + ) + + // Install session changes + closeActions.accept(installSessionHelper.registerInstallTracker(modelCallbacks)) + } + + companion object { + private const val ACTION_FORCE_RELOAD = "force-reload-launcher" + } +} diff --git a/src/com/android/launcher3/pm/InstallSessionTracker.java b/src/com/android/launcher3/pm/InstallSessionTracker.java index b9c928c50b..7451ce2630 100644 --- a/src/com/android/launcher3/pm/InstallSessionTracker.java +++ b/src/com/android/launcher3/pm/InstallSessionTracker.java @@ -34,13 +34,15 @@ import androidx.annotation.WorkerThread; import com.android.launcher3.Flags; import com.android.launcher3.util.PackageUserKey; +import com.android.launcher3.util.SafeCloseable; import java.lang.ref.WeakReference; import java.util.Objects; @SuppressWarnings("NewApi") @WorkerThread -public class InstallSessionTracker extends PackageInstaller.SessionCallback { +public class InstallSessionTracker extends PackageInstaller.SessionCallback implements + SafeCloseable { public static final String TAG = "InstallSessionTracker"; @@ -196,7 +198,8 @@ public class InstallSessionTracker extends PackageInstaller.SessionCallback { } } - public void unregister() { + @Override + public void close() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) { mInstaller.unregisterSessionCallback(this); } else { diff --git a/tests/multivalentTests/src/com/android/launcher3/pm/InstallSessionTrackerTest.kt b/tests/multivalentTests/src/com/android/launcher3/pm/InstallSessionTrackerTest.kt index 15a9964a5f..23c1da98c5 100644 --- a/tests/multivalentTests/src/com/android/launcher3/pm/InstallSessionTrackerTest.kt +++ b/tests/multivalentTests/src/com/android/launcher3/pm/InstallSessionTrackerTest.kt @@ -219,7 +219,7 @@ class InstallSessionTrackerTest { .whenever(launcherApps) .unregisterPackageInstallerSessionCallback(installSessionTracker) // When - installSessionTracker.unregister() + installSessionTracker.close() // Then verify(launcherApps).unregisterPackageInstallerSessionCallback(installSessionTracker) } From aa69e18fc833f9e44ccd0f3e4bd5792da65e5a16 Mon Sep 17 00:00:00 2001 From: Sihua Ma Date: Tue, 18 Feb 2025 23:17:21 +0000 Subject: [PATCH 048/153] Fix work badge theme issue when dropping icons Fix: 397257046 Test: Manual Flag: EXEMPT bug fix Change-Id: I83280f990fa70dd6b7b78fc23506a9757125f59c --- src/com/android/launcher3/dragndrop/DragView.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/com/android/launcher3/dragndrop/DragView.java b/src/com/android/launcher3/dragndrop/DragView.java index bff323ceb3..6109131a8d 100644 --- a/src/com/android/launcher3/dragndrop/DragView.java +++ b/src/com/android/launcher3/dragndrop/DragView.java @@ -246,10 +246,12 @@ public abstract class DragView extends Fram public void setItemInfo(final ItemInfo info) { // Load the adaptive icon on a background thread and add the view in ui thread. MODEL_EXECUTOR.getHandler().postAtFrontOfQueue(() -> { + ThemeManager themeManager = ThemeManager.INSTANCE.get(getContext()); int w = mWidth; int h = mHeight; Pair fullDrawable = Utilities.getFullDrawable( - mActivity, info, w, h, true /* shouldThemeIcon */); + mActivity, info, w, h, + themeManager.isIconThemeEnabled()); if (fullDrawable != null) { AdaptiveIconDrawable adaptiveIcon = fullDrawable.first; int blurMargin = (int) mActivity.getResources() @@ -274,7 +276,6 @@ public abstract class DragView extends Fram Utilities.scaleRectAboutCenter(shrunkBounds, 0.98f); adaptiveIcon.setBounds(shrunkBounds); - ThemeManager themeManager = ThemeManager.INSTANCE.get(getContext()); final Path mask = (adaptiveIcon instanceof FolderAdaptiveIcon ? themeManager.getFolderShape() : themeManager.getIconShape()) .getPath(shrunkBounds); From 190f3263a2874aa27230423ff09218afbf996e7d Mon Sep 17 00:00:00 2001 From: Sebastian Franco Date: Thu, 16 Jan 2025 15:30:44 -0800 Subject: [PATCH 049/153] Add DeviceProfile dump files into artifacts Artifacts are collected from: Defined in NexusLauncherTests.xml, by writing the files into that directory the files should show in the artifacts section when a test fails. Bug: 390496167 Flag: TEST_ONLY Test: all dumpTest Test: dump files should now be available in test artifacts Change-Id: I046b1482afaea647351462983c4cbab5f3bc29bc --- .../com/android/launcher3/AbstractDeviceProfileTest.kt | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/tests/multivalentTests/src/com/android/launcher3/AbstractDeviceProfileTest.kt b/tests/multivalentTests/src/com/android/launcher3/AbstractDeviceProfileTest.kt index 8cdf380314..3658989384 100644 --- a/tests/multivalentTests/src/com/android/launcher3/AbstractDeviceProfileTest.kt +++ b/tests/multivalentTests/src/com/android/launcher3/AbstractDeviceProfileTest.kt @@ -364,7 +364,13 @@ abstract class AbstractDeviceProfileTest { context.assets.open("dumpTests/$fileName").bufferedReader().use(BufferedReader::readText) private fun writeToDevice(context: Context, fileName: String, content: String) { - File(context.getDir("dumpTests", Context.MODE_PRIVATE), fileName).writeText(content) + val dir = + File(context.filesDir, "dumpTests").also { + if (!it.exists()) { + it.mkdirs() + } + } + File(dir, fileName).writeText(content) } protected fun Float.dpToPx(): Float { From 27cff24c0066803977d9184b07117dbaf56c6731 Mon Sep 17 00:00:00 2001 From: Fengjiang Li Date: Tue, 18 Feb 2025 21:18:03 -0800 Subject: [PATCH 050/153] [Memory Leak] Fix leak of NexusLauncehrActivity via AbsSwipeUpHandler#mRecentsAnimationStartCallbacks -> SurfaceTransactionApplier Fix: 397559243 Flag: NONE - released code Test: presubmit Change-Id: I8a1a03575e98bdbe44c70f2bd691f6930ac8b8fd --- quickstep/src/com/android/quickstep/AbsSwipeUpHandler.java | 1 + 1 file changed, 1 insertion(+) diff --git a/quickstep/src/com/android/quickstep/AbsSwipeUpHandler.java b/quickstep/src/com/android/quickstep/AbsSwipeUpHandler.java index 3640e1f9c0..67a54e6c44 100644 --- a/quickstep/src/com/android/quickstep/AbsSwipeUpHandler.java +++ b/quickstep/src/com/android/quickstep/AbsSwipeUpHandler.java @@ -223,6 +223,7 @@ public abstract class AbsSwipeUpHandler< mRecentsView = null; mContainer = null; mStateCallback.clearState(STATE_LAUNCHER_PRESENT); + mRecentsAnimationStartCallbacks.clear(); }; private static int FLAG_COUNT = 0; From 0392cb8a7d1434f8f2460886541dbc8558c3eb83 Mon Sep 17 00:00:00 2001 From: Lingyu Feng Date: Tue, 18 Feb 2025 22:37:44 -0800 Subject: [PATCH 051/153] Remove taskbar when display mirroring starts Bug: 397095099 Change-Id: I0d21650af45aec084c0b48b50e22e8072d3f9192 Test: adb shell settings put secure mirror_built_in_display 1 Flag: com.android.server.display.feature.flags.enable_display_content_mode_management --- .../src/com/android/launcher3/taskbar/TaskbarManager.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/quickstep/src/com/android/launcher3/taskbar/TaskbarManager.java b/quickstep/src/com/android/launcher3/taskbar/TaskbarManager.java index 46802c3f9e..6cd2979341 100644 --- a/quickstep/src/com/android/launcher3/taskbar/TaskbarManager.java +++ b/quickstep/src/com/android/launcher3/taskbar/TaskbarManager.java @@ -747,7 +747,11 @@ public class TaskbarManager { /** * Signal from SysUI indicating that system decorations should be removed from the display. */ - public void onDisplayRemoveSystemDecorations(int displayId) {} + public void onDisplayRemoveSystemDecorations(int displayId) { + // The display mirroring starts. The handling logic is the same as when removing a + // display. + onDisplayRemoved(displayId); + } private void removeActivityCallbacksAndListeners() { if (mActivity != null) { From 2aa0a0dde8adc919f9c0343569e2155eec9567e3 Mon Sep 17 00:00:00 2001 From: Massimo Carli Date: Wed, 19 Feb 2025 09:09:44 +0000 Subject: [PATCH 052/153] [2/n] Fix tests before adding modal permission check Flag: com.android.window.flags.enable_modals_fullscreen_with_permission Bug: 394714626 Test: atest NexusLauncherTests:com.android.quickstep.DesktopSystemShortcutTest Test: atest NexusLauncherTests:com.android.quickstep.ExternalDisplaySystemShortcutTest Change-Id: I74ad0ca6b089a790a8f84ee6ba735b9d01acdc2f --- .../src/com/android/quickstep/DesktopSystemShortcutTest.kt | 2 ++ .../com/android/quickstep/ExternalDisplaySystemShortcutTest.kt | 2 ++ 2 files changed, 4 insertions(+) diff --git a/quickstep/tests/src/com/android/quickstep/DesktopSystemShortcutTest.kt b/quickstep/tests/src/com/android/quickstep/DesktopSystemShortcutTest.kt index 76aab39f1b..a523e02196 100644 --- a/quickstep/tests/src/com/android/quickstep/DesktopSystemShortcutTest.kt +++ b/quickstep/tests/src/com/android/quickstep/DesktopSystemShortcutTest.kt @@ -20,6 +20,7 @@ import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.pm.PackageManager +import android.platform.test.annotations.DisableFlags import android.platform.test.annotations.EnableFlags import android.view.Display.DEFAULT_DISPLAY import androidx.test.platform.app.InstrumentationRegistry @@ -106,6 +107,7 @@ class DesktopSystemShortcutTest { @Test @EnableFlags(Flags.FLAG_ENABLE_DESKTOP_WINDOWING_MODALS_POLICY) + @DisableFlags(Flags.FLAG_ENABLE_MODALS_FULLSCREEN_WITH_PERMISSION) fun createDesktopTaskShortcutFactory_transparentTask() { val baseComponent = ComponentName("", /* class */ "") val taskKey = diff --git a/quickstep/tests/src/com/android/quickstep/ExternalDisplaySystemShortcutTest.kt b/quickstep/tests/src/com/android/quickstep/ExternalDisplaySystemShortcutTest.kt index 818841a70c..2db94f6f1a 100644 --- a/quickstep/tests/src/com/android/quickstep/ExternalDisplaySystemShortcutTest.kt +++ b/quickstep/tests/src/com/android/quickstep/ExternalDisplaySystemShortcutTest.kt @@ -20,6 +20,7 @@ import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.pm.PackageManager +import android.platform.test.annotations.DisableFlags import android.platform.test.annotations.EnableFlags import android.platform.test.flag.junit.SetFlagsRule import android.view.Display.DEFAULT_DISPLAY @@ -113,6 +114,7 @@ class ExternalDisplaySystemShortcutTest { Flags.FLAG_MOVE_TO_EXTERNAL_DISPLAY_SHORTCUT, Flags.FLAG_ENABLE_DESKTOP_WINDOWING_MODALS_POLICY, ) + @DisableFlags(Flags.FLAG_ENABLE_MODALS_FULLSCREEN_WITH_PERMISSION) fun createExternalDisplayTaskShortcut_transparentTask() { val baseComponent = ComponentName("", /* class */ "") val taskKey = From 3661a5005c7cb43b87a1bf2296c66263de7fab43 Mon Sep 17 00:00:00 2001 From: Vinay Joglekar Date: Wed, 19 Feb 2025 02:26:24 -0800 Subject: [PATCH 053/153] Add feature flag for desktop tile wallpaper background in overview. Change-Id: Ia070d530e43220a00a3f81b33b77ea70ea96cbfb Fix: 397438316 Flag: com.android.launcher3.enable_overview_desktop_tile_wallpaper_background Test: None. Flag addition. --- aconfig/launcher_overview.aconfig | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/aconfig/launcher_overview.aconfig b/aconfig/launcher_overview.aconfig index 999e784b3b..5749c517d3 100644 --- a/aconfig/launcher_overview.aconfig +++ b/aconfig/launcher_overview.aconfig @@ -103,3 +103,10 @@ flag { description: "Enable wallpaper blur in overview." bug: "369975912" } + +flag { + name: "enable_overview_desktop_tile_wallpaper_background" + namespace: "launcher_overview" + description: "Enable wallpaper background for desktop tasks in overview." + bug: "363257721" +} From 7c1e78acef06f0d6e7e2e91877074635c61b0cfa Mon Sep 17 00:00:00 2001 From: Jordan Silva Date: Wed, 19 Feb 2025 16:16:20 +0000 Subject: [PATCH 054/153] Fix cropping app chip text with largest display and font size Bug: 313648249 Flag: com.android.launcher3.enable_overview_icon_menu Test: OverviewImageTest Change-Id: I724c09647694214d59713d57269dc9378c01dc96 --- quickstep/res/layout/icon_app_chip_view.xml | 4 ++-- quickstep/res/values/styles.xml | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/quickstep/res/layout/icon_app_chip_view.xml b/quickstep/res/layout/icon_app_chip_view.xml index 00b5392ba1..0972be16e3 100644 --- a/quickstep/res/layout/icon_app_chip_view.xml +++ b/quickstep/res/layout/icon_app_chip_view.xml @@ -51,7 +51,7 @@ google-sans-text-medium @dimen/task_thumbnail_icon_menu_text_size @color/materialColorOnSurface + false 0.025 20sp From 09933afac9b415b0e521684a022658f9f181635b Mon Sep 17 00:00:00 2001 From: Uwais Ashraf Date: Wed, 19 Feb 2025 14:02:28 +0000 Subject: [PATCH 055/153] Prevent high res callback from fetching when not needed. Fix: 395636649 Flag: com.android.launcher3.enable_refactor_task_thumbnail Test: TasksRepositoryTest Test: TaskVisualsChangedDelegate Change-Id: I7e0f47adb07455c1fed4761d67de901b56bdeb52 --- .../data/TaskVisualsChangedDelegate.kt | 10 ++- .../quickstep/recents/data/TasksRepository.kt | 12 +++- .../data/FakeTaskThumbnailDataSource.kt | 10 +-- .../data/TaskVisualsChangedDelegateTest.kt | 50 +++++++++---- .../recents/data/TasksRepositoryTest.kt | 72 +++++++++++++++++-- 5 files changed, 128 insertions(+), 26 deletions(-) diff --git a/quickstep/src/com/android/quickstep/recents/data/TaskVisualsChangedDelegate.kt b/quickstep/src/com/android/quickstep/recents/data/TaskVisualsChangedDelegate.kt index 608fafd9b2..12616a8f84 100644 --- a/quickstep/src/com/android/quickstep/recents/data/TaskVisualsChangedDelegate.kt +++ b/quickstep/src/com/android/quickstep/recents/data/TaskVisualsChangedDelegate.kt @@ -17,6 +17,7 @@ package com.android.quickstep.recents.data import android.os.UserHandle +import android.util.Log import com.android.quickstep.HighResLoadingState.HighResLoadingStateChangedCallback import com.android.quickstep.recents.data.TaskVisualsChangedDelegate.TaskIconChangedCallback import com.android.quickstep.recents.data.TaskVisualsChangedDelegate.TaskThumbnailChangedCallback @@ -58,7 +59,7 @@ interface TaskVisualsChangedDelegate : fun onTaskThumbnailChanged(thumbnailData: ThumbnailData?) /** Informs the listener that the default resolution for loading thumbnails has changed */ - fun onHighResLoadingStateChanged() + fun onHighResLoadingStateChanged(highResEnabled: Boolean) } } @@ -91,8 +92,9 @@ class TaskVisualsChangedDelegateImpl( } override fun onHighResLoadingStateChanged(enabled: Boolean) { + Log.d(TAG, "onHighResLoadingStateChanged(enabled = $enabled)") taskThumbnailChangedCallbacks.values.forEach { (_, callback) -> - callback.onHighResLoadingStateChanged() + callback.onHighResLoadingStateChanged(enabled) } } @@ -142,4 +144,8 @@ class TaskVisualsChangedDelegateImpl( } } } + + companion object { + const val TAG = "TaskVisualsChangedDelegateImpl" + } } diff --git a/quickstep/src/com/android/quickstep/recents/data/TasksRepository.kt b/quickstep/src/com/android/quickstep/recents/data/TasksRepository.kt index b1a59202ae..5274ef3266 100644 --- a/quickstep/src/com/android/quickstep/recents/data/TasksRepository.kt +++ b/quickstep/src/com/android/quickstep/recents/data/TasksRepository.kt @@ -160,7 +160,17 @@ class TasksRepository( updateThumbnail(task.key.id, thumbnailData) } - override fun onHighResLoadingStateChanged() { + override fun onHighResLoadingStateChanged(highResEnabled: Boolean) { + val isTaskVisible = taskRequests.containsKey(task.key.id) + if (!isTaskVisible) return + + val isCurrentThumbnailLowRes = + tasks.value[task.key.id]?.thumbnail?.reducedResolution + val isRequestedResHigherThanCurrent = + isCurrentThumbnailLowRes == null || + (isCurrentThumbnailLowRes && highResEnabled) + if (!isRequestedResHigherThanCurrent) return + recentsCoroutineScope.launch(dispatcherProvider.background) { updateThumbnail(task.key.id, getThumbnailFromDataSource(task)) } diff --git a/quickstep/tests/multivalentTests/src/com/android/quickstep/recents/data/FakeTaskThumbnailDataSource.kt b/quickstep/tests/multivalentTests/src/com/android/quickstep/recents/data/FakeTaskThumbnailDataSource.kt index e10afc47bb..40d5e0264c 100644 --- a/quickstep/tests/multivalentTests/src/com/android/quickstep/recents/data/FakeTaskThumbnailDataSource.kt +++ b/quickstep/tests/multivalentTests/src/com/android/quickstep/recents/data/FakeTaskThumbnailDataSource.kt @@ -22,7 +22,6 @@ import com.android.systemui.shared.recents.model.Task import com.android.systemui.shared.recents.model.ThumbnailData import kotlinx.coroutines.yield import org.mockito.kotlin.mock -import org.mockito.kotlin.whenever class FakeTaskThumbnailDataSource : TaskThumbnailDataSource { @@ -31,6 +30,8 @@ class FakeTaskThumbnailDataSource : TaskThumbnailDataSource { private val completionPrevented: MutableSet = mutableSetOf() private val getThumbnailCalls = mutableMapOf() + var highResEnabled = true + /** Retrieves and sets a thumbnail on [task] from [taskIdToBitmap]. */ override suspend fun getThumbnail(task: Task): ThumbnailData { getThumbnailCalls[task.key.id] = (getThumbnailCalls[task.key.id] ?: 0) + 1 @@ -38,9 +39,10 @@ class FakeTaskThumbnailDataSource : TaskThumbnailDataSource { while (task.key.id in completionPrevented) { yield() } - return mock().also { - whenever(it.thumbnail).thenReturn(taskIdToBitmap[task.key.id]) - } + return ThumbnailData( + thumbnail = taskIdToBitmap[task.key.id], + reducedResolution = !highResEnabled, + ) } fun getNumberOfGetThumbnailCalls(taskId: Int): Int = getThumbnailCalls[taskId] ?: 0 diff --git a/quickstep/tests/multivalentTests/src/com/android/quickstep/recents/data/TaskVisualsChangedDelegateTest.kt b/quickstep/tests/multivalentTests/src/com/android/quickstep/recents/data/TaskVisualsChangedDelegateTest.kt index 41f6bfdf75..b91f8bd6fd 100644 --- a/quickstep/tests/multivalentTests/src/com/android/quickstep/recents/data/TaskVisualsChangedDelegateTest.kt +++ b/quickstep/tests/multivalentTests/src/com/android/quickstep/recents/data/TaskVisualsChangedDelegateTest.kt @@ -19,16 +19,19 @@ package com.android.quickstep.recents.data import android.content.ComponentName import android.content.Intent import android.os.UserHandle +import androidx.test.ext.junit.runners.AndroidJUnit4 import com.android.quickstep.recents.data.TaskVisualsChangedDelegate.TaskIconChangedCallback import com.android.quickstep.recents.data.TaskVisualsChangedDelegate.TaskThumbnailChangedCallback import com.android.systemui.shared.recents.model.Task.TaskKey import com.android.systemui.shared.recents.model.ThumbnailData import com.google.common.truth.Truth.assertThat import org.junit.Test +import org.junit.runner.RunWith import org.mockito.kotlin.mock import org.mockito.kotlin.verify import org.mockito.kotlin.verifyNoMoreInteractions +@RunWith(AndroidJUnit4::class) class TaskVisualsChangedDelegateTest { private val taskVisualsChangeNotifier = FakeTaskVisualsChangeNotifier() private val highResLoadingStateNotifier = FakeHighResLoadingStateNotifier() @@ -83,21 +86,21 @@ class TaskVisualsChangedDelegateTest { // Correct match systemUnderTest.registerTaskIconChangedCallback( createTaskKey(id = 1, pkg = ALTERNATIVE_PACKAGE_NAME, userId = 1), - expectedListener + expectedListener, ) // 1 out of 2 match systemUnderTest.registerTaskIconChangedCallback( createTaskKey(id = 2, pkg = PACKAGE_NAME, userId = 1), - listener + listener, ) systemUnderTest.registerTaskIconChangedCallback( createTaskKey(id = 3, pkg = ALTERNATIVE_PACKAGE_NAME, userId = 2), - listener + listener, ) // 0 out of 2 match systemUnderTest.registerTaskIconChangedCallback( createTaskKey(id = 4, pkg = PACKAGE_NAME, userId = 2), - listener + listener, ) systemUnderTest.onTaskIconChanged(ALTERNATIVE_PACKAGE_NAME, UserHandle(1)) @@ -112,11 +115,11 @@ class TaskVisualsChangedDelegateTest { val newListener = mock() systemUnderTest.registerTaskIconChangedCallback( createTaskKey(id = 1, pkg = ALTERNATIVE_PACKAGE_NAME, userId = 1), - replacedListener + replacedListener, ) systemUnderTest.registerTaskIconChangedCallback( createTaskKey(id = 1, pkg = ALTERNATIVE_PACKAGE_NAME, userId = 1), - newListener + newListener, ) systemUnderTest.onTaskIconChanged(ALTERNATIVE_PACKAGE_NAME, UserHandle(1)) @@ -132,11 +135,11 @@ class TaskVisualsChangedDelegateTest { val expectedThumbnailData = ThumbnailData(snapshotId = 12345) systemUnderTest.registerTaskThumbnailChangedCallback( createTaskKey(id = 1), - expectedListener + expectedListener, ) systemUnderTest.registerTaskThumbnailChangedCallback( createTaskKey(id = 2), - additionalListener + additionalListener, ) systemUnderTest.onTaskThumbnailChanged(1, expectedThumbnailData) @@ -146,22 +149,41 @@ class TaskVisualsChangedDelegateTest { } @Test - fun onHighResLoadingStateChanged_notifiesAllListeners() { + fun onHighResLoadingStateChanged_toEnabled_notifiesAllListeners() { val expectedListener = mock() val additionalListener = mock() systemUnderTest.registerTaskThumbnailChangedCallback( createTaskKey(id = 1), - expectedListener + expectedListener, ) systemUnderTest.registerTaskThumbnailChangedCallback( createTaskKey(id = 2), - additionalListener + additionalListener, ) systemUnderTest.onHighResLoadingStateChanged(true) - verify(expectedListener).onHighResLoadingStateChanged() - verify(additionalListener).onHighResLoadingStateChanged() + verify(expectedListener).onHighResLoadingStateChanged(true) + verify(additionalListener).onHighResLoadingStateChanged(true) + } + + @Test + fun onHighResLoadingStateChanged_toDisabled_notifiesAllListeners() { + val expectedListener = mock() + val additionalListener = mock() + systemUnderTest.registerTaskThumbnailChangedCallback( + createTaskKey(id = 1), + expectedListener, + ) + systemUnderTest.registerTaskThumbnailChangedCallback( + createTaskKey(id = 2), + additionalListener, + ) + + systemUnderTest.onHighResLoadingStateChanged(false) + + verify(expectedListener).onHighResLoadingStateChanged(false) + verify(additionalListener).onHighResLoadingStateChanged(false) } @Test @@ -171,7 +193,7 @@ class TaskVisualsChangedDelegateTest { val expectedThumbnailData = ThumbnailData(snapshotId = 12345) systemUnderTest.registerTaskThumbnailChangedCallback( createTaskKey(id = 1), - replacedListener1 + replacedListener1, ) systemUnderTest.registerTaskThumbnailChangedCallback(createTaskKey(id = 1), newListener1) 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 823f808bc9..10be6fdb96 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 @@ -326,8 +326,9 @@ class TasksRepositoryTest { } @Test - fun onHighResLoadingStateChanged_setsNewThumbnailDataOnTask() = + fun onHighResLoadingStateChanged_highResReplacesLowResThumbnail() = testScope.runTest { + taskThumbnailDataSource.highResEnabled = false recentsModel.seedTasks(defaultTaskList) systemUnderTest.getAllTaskData(forceRefresh = true) @@ -337,16 +338,77 @@ class TasksRepositoryTest { val expectedPreviousBitmap = taskThumbnailDataSource.taskIdToBitmap[1] val taskDataFlow = systemUnderTest.getTaskDataById(1) - val task1ThumbnailValues = mutableListOf() + val task1ThumbnailValues = mutableListOf() testScope.backgroundScope.launch { - taskDataFlow.map { it?.thumbnail?.thumbnail }.toList(task1ThumbnailValues) + taskDataFlow.map { it?.thumbnail }.toList(task1ThumbnailValues) } taskThumbnailDataSource.taskIdToBitmap[1] = expectedBitmap + taskThumbnailDataSource.highResEnabled = true taskVisualsChangedDelegate.onHighResLoadingStateChanged(true) - assertThat(task1ThumbnailValues.first()).isEqualTo(expectedPreviousBitmap) - assertThat(task1ThumbnailValues.last()).isEqualTo(expectedBitmap) + val firstThumbnailValue = task1ThumbnailValues.first()!! + assertThat(firstThumbnailValue.thumbnail).isEqualTo(expectedPreviousBitmap) + assertThat(firstThumbnailValue.reducedResolution).isTrue() + + val lastThumbnailValue = task1ThumbnailValues.last()!! + assertThat(lastThumbnailValue.thumbnail).isEqualTo(expectedBitmap) + assertThat(lastThumbnailValue.reducedResolution).isFalse() + } + + @Test + fun onHighResLoadingStateChanged_invisibleTaskIgnored() = + testScope.runTest { + taskThumbnailDataSource.highResEnabled = false + recentsModel.seedTasks(defaultTaskList) + systemUnderTest.getAllTaskData(forceRefresh = true) + + systemUnderTest.setVisibleTasks(setOf(1)) + + val invisibleTaskId = 2 + val taskDataFlow = systemUnderTest.getTaskDataById(invisibleTaskId) + + val task2ThumbnailValues = mutableListOf() + testScope.backgroundScope.launch { + taskDataFlow.map { it?.thumbnail }.toList(task2ThumbnailValues) + } + + taskThumbnailDataSource.highResEnabled = true + taskVisualsChangedDelegate.onHighResLoadingStateChanged(true) + + assertThat(task2ThumbnailValues.filterNotNull()).isEmpty() + assertThat(taskThumbnailDataSource.getNumberOfGetThumbnailCalls(2)).isEqualTo(0) + } + + @Test + fun onHighResLoadingStateChanged_lowResDoesNotReplaceHighResThumbnail() = + testScope.runTest { + taskThumbnailDataSource.highResEnabled = true + recentsModel.seedTasks(defaultTaskList) + systemUnderTest.getAllTaskData(forceRefresh = true) + + systemUnderTest.setVisibleTasks(setOf(1)) + + val expectedBitmap = mock() + val expectedPreviousBitmap = taskThumbnailDataSource.taskIdToBitmap[1] + val taskDataFlow = systemUnderTest.getTaskDataById(1) + + val task1ThumbnailValues = mutableListOf() + testScope.backgroundScope.launch { + taskDataFlow.map { it?.thumbnail }.toList(task1ThumbnailValues) + } + + taskThumbnailDataSource.taskIdToBitmap[1] = expectedBitmap + taskThumbnailDataSource.highResEnabled = false + taskVisualsChangedDelegate.onHighResLoadingStateChanged(false) + + val firstThumbnailValue = task1ThumbnailValues.first()!! + assertThat(firstThumbnailValue.thumbnail).isEqualTo(expectedPreviousBitmap) + assertThat(firstThumbnailValue.reducedResolution).isFalse() + + val lastThumbnailValue = task1ThumbnailValues.last()!! + assertThat(lastThumbnailValue.thumbnail).isEqualTo(expectedPreviousBitmap) + assertThat(lastThumbnailValue.reducedResolution).isFalse() } @Test From acf4dc0a1c819d02376aaffb874a66c3516188e4 Mon Sep 17 00:00:00 2001 From: Uwais Ashraf Date: Wed, 19 Feb 2025 11:25:03 +0000 Subject: [PATCH 056/153] Use scale adjusted path to avoid warped rounded corners. Fix: 355429331 Flag: com.android.launcher3.enable_refactor_task_thumbnail Test: TaskThumbnailViewScreenshotTest Change-Id: I7f218b53cc2dd644ce61a0d343901a25cc8b0604 --- .../task/thumbnail/TaskThumbnailView.kt | 17 ++++++++++++++++- .../TaskThumbnailViewScreenshotTest.kt | 12 ++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/quickstep/src/com/android/quickstep/task/thumbnail/TaskThumbnailView.kt b/quickstep/src/com/android/quickstep/task/thumbnail/TaskThumbnailView.kt index e672ec4abc..e91073ac7a 100644 --- a/quickstep/src/com/android/quickstep/task/thumbnail/TaskThumbnailView.kt +++ b/quickstep/src/com/android/quickstep/task/thumbnail/TaskThumbnailView.kt @@ -20,6 +20,7 @@ import android.content.Context import android.graphics.Color import android.graphics.Matrix import android.graphics.Outline +import android.graphics.Path import android.graphics.Rect import android.graphics.drawable.ShapeDrawable import android.util.AttributeSet @@ -52,6 +53,7 @@ class TaskThumbnailView : FrameLayout, ViewPool.Reusable { private val dimAlpha: MultiPropertyFactory by lazy { MultiPropertyFactory(scrimView, VIEW_ALPHA, ScrimViewAlpha.entries.size, ::maxOf) } + private val outlinePath = Path() private var onSizeChanged: ((width: Int, height: Int) -> Unit)? = null private var taskThumbnailViewHeader: TaskThumbnailViewHeader? = null @@ -96,7 +98,20 @@ class TaskThumbnailView : FrameLayout, ViewPool.Reusable { outlineProvider = object : ViewOutlineProvider() { override fun getOutline(view: View, outline: Outline) { - outline.setRoundRect(outlineBounds ?: bounds, cornerRadius) + val outlineRect = outlineBounds ?: bounds + outlinePath.apply { + rewind() + addRoundRect( + outlineRect.left.toFloat(), + outlineRect.top.toFloat(), + outlineRect.right.toFloat(), + outlineRect.bottom.toFloat(), + cornerRadius / scaleX, + cornerRadius / scaleY, + Path.Direction.CW, + ) + } + outline.setPath(outlinePath) } } } diff --git a/quickstep/tests/multivalentScreenshotTests/src/com/android/quickstep/task/thumbnail/TaskThumbnailViewScreenshotTest.kt b/quickstep/tests/multivalentScreenshotTests/src/com/android/quickstep/task/thumbnail/TaskThumbnailViewScreenshotTest.kt index b9d2fed9c7..99972a5208 100644 --- a/quickstep/tests/multivalentScreenshotTests/src/com/android/quickstep/task/thumbnail/TaskThumbnailViewScreenshotTest.kt +++ b/quickstep/tests/multivalentScreenshotTests/src/com/android/quickstep/task/thumbnail/TaskThumbnailViewScreenshotTest.kt @@ -114,6 +114,18 @@ class TaskThumbnailViewScreenshotTest(emulationSpec: DeviceEmulationSpec) { } } + @Test + fun taskThumbnailView_scaled_roundRoundedCorners() { + screenshotRule.screenshotTest("taskThumbnailView_scaledRoundedCorners") { activity -> + activity.actionBar?.hide() + createTaskThumbnailView(activity).apply { + scaleX = 0.75f + scaleY = 0.3f + setState(BackgroundOnly(Color.YELLOW)) + } + } + } + private fun createTaskThumbnailView(context: Context): TaskThumbnailView { val taskThumbnailView = LayoutInflater.from(context).inflate(R.layout.task_thumbnail, null, false) From 96fa7a4c797ccaa9807502901a0fb9369b4cf3d5 Mon Sep 17 00:00:00 2001 From: Charlie Anderson Date: Wed, 19 Feb 2025 17:34:57 +0000 Subject: [PATCH 057/153] Removing Sunny shape option Bug: 397683324 Test: selecting shapes, and presubmit Flag: com.android.launcher3.enable_launcher_icon_shapes Change-Id: I3d9ea0096674c07a860ba3d7dcc8074c4342a299 --- src/com/android/launcher3/shapes/ShapesProvider.kt | 9 --------- .../com/android/launcher3/shapes/ShapesProviderTest.kt | 9 --------- 2 files changed, 18 deletions(-) diff --git a/src/com/android/launcher3/shapes/ShapesProvider.kt b/src/com/android/launcher3/shapes/ShapesProvider.kt index 463c81623f..5427c89f71 100644 --- a/src/com/android/launcher3/shapes/ShapesProvider.kt +++ b/src/com/android/launcher3/shapes/ShapesProvider.kt @@ -193,15 +193,6 @@ object ShapesProvider { "M50 0C77.614 0 100 22.386 100 50C100 85.471 100 86.476 99.9 87.321 99.116 93.916 93.916 99.116 87.321 99.9 86.476 100 85.471 100 83.46 100H16.54C14.529 100 13.524 100 12.679 99.9 6.084 99.116 .884 93.916 .1 87.321 0 86.476 0 85.471 0 83.46L0 50C0 22.386 22.386 0 50 0Z", folderPathString = folderShapes["arch"]!!, ), - "sunny" to - IconShapeModel( - key = "sunny", - title = "sunny", - pathString = - "M42.846 4.873C46.084 -.531 53.916 -.531 57.154 4.873L60.796 10.951C62.685 14.103 66.414 15.647 69.978 14.754L76.851 13.032C82.962 11.5 88.5 17.038 86.968 23.149L85.246 30.022C84.353 33.586 85.897 37.315 89.049 39.204L95.127 42.846C100.531 46.084 100.531 53.916 95.127 57.154L89.049 60.796C85.897 62.685 84.353 66.414 85.246 69.978L86.968 76.851C88.5 82.962 82.962 88.5 76.851 86.968L69.978 85.246C66.414 84.353 62.685 85.898 60.796 89.049L57.154 95.127C53.916 100.531 46.084 100.531 42.846 95.127L39.204 89.049C37.315 85.898 33.586 84.353 30.022 85.246L23.149 86.968C17.038 88.5 11.5 82.962 13.032 76.851L14.754 69.978C15.647 66.414 14.103 62.685 10.951 60.796L4.873 57.154C -.531 53.916 -.531 46.084 4.873 42.846L10.951 39.204C14.103 37.315 15.647 33.586 14.754 30.022L13.032 23.149C11.5 17.038 17.038 11.5 23.149 13.032L30.022 14.754C33.586 15.647 37.315 14.103 39.204 10.951L42.846 4.873Z", - folderPathString = folderShapes["clover"]!!, - iconScale = 72f / 92f, - ), ) } else { mapOf( diff --git a/tests/multivalentTests/src/com/android/launcher3/shapes/ShapesProviderTest.kt b/tests/multivalentTests/src/com/android/launcher3/shapes/ShapesProviderTest.kt index 508c9a492d..49d305b5d1 100644 --- a/tests/multivalentTests/src/com/android/launcher3/shapes/ShapesProviderTest.kt +++ b/tests/multivalentTests/src/com/android/launcher3/shapes/ShapesProviderTest.kt @@ -61,15 +61,6 @@ class ShapesProviderTest { } } - @Test - @EnableFlags(FLAG_ENABLE_LAUNCHER_ICON_SHAPES, FLAG_NEW_CUSTOMIZATION_PICKER_UI) - fun `verify valid path sunny`() { - ShapesProvider.iconShapes["sunny"]?.apply { - GenericPathShape(pathString) - PathParser.createPathFromPathData(pathString) - } - } - @Test @EnableFlags(FLAG_ENABLE_LAUNCHER_ICON_SHAPES, FLAG_NEW_CUSTOMIZATION_PICKER_UI) fun `verify valid path circle`() { From 097efdc8ac879da86efb419db8f321017c77345c Mon Sep 17 00:00:00 2001 From: Sihua Ma Date: Tue, 18 Feb 2025 08:47:18 +0000 Subject: [PATCH 058/153] Exclude dynamic shortcuts from being force themed Test: Manual Bug: 397501448 Flag: com.android.launcher3.force_monochrome_app_icons Change-Id: Iff1010e268c99ce192e1445ec124229c84420b23 --- .../android/launcher3/uioverrides/SystemApiWrapper.kt | 5 ++++- .../android/launcher3/icons/CacheableShortcutInfo.kt | 11 ++++++++++- src/com/android/launcher3/util/ApiWrapper.java | 7 +++++++ 3 files changed, 21 insertions(+), 2 deletions(-) diff --git a/quickstep/src/com/android/launcher3/uioverrides/SystemApiWrapper.kt b/quickstep/src/com/android/launcher3/uioverrides/SystemApiWrapper.kt index 6e901ee6d1..1f34969a49 100644 --- a/quickstep/src/com/android/launcher3/uioverrides/SystemApiWrapper.kt +++ b/quickstep/src/com/android/launcher3/uioverrides/SystemApiWrapper.kt @@ -144,7 +144,7 @@ open class SystemApiWrapper @Inject constructor(@ApplicationContext context: Con override fun isNonResizeableActivity(lai: LauncherActivityInfo) = lai.activityInfo.resizeMode == ActivityInfo.RESIZE_MODE_UNRESIZEABLE - override fun supportsMultiInstance(lai: LauncherActivityInfo) : Boolean { + override fun supportsMultiInstance(lai: LauncherActivityInfo): Boolean { return try { super.supportsMultiInstance(lai) || lai.supportsMultiInstance() } catch (e: Exception) { @@ -202,4 +202,7 @@ open class SystemApiWrapper @Inject constructor(@ApplicationContext context: Con (appInfo.sourceDir?.hashCode() ?: 0).toString() + " " + appInfo.longVersionCode override fun getRoundIconRes(appInfo: ApplicationInfo) = appInfo.roundIconRes + + override fun isFileDrawable(shortcutInfo: ShortcutInfo) = + shortcutInfo.hasIconFile() || shortcutInfo.hasIconUri() } diff --git a/src/com/android/launcher3/icons/CacheableShortcutInfo.kt b/src/com/android/launcher3/icons/CacheableShortcutInfo.kt index 225e12f47a..50dd146ca6 100644 --- a/src/com/android/launcher3/icons/CacheableShortcutInfo.kt +++ b/src/com/android/launcher3/icons/CacheableShortcutInfo.kt @@ -30,6 +30,7 @@ import com.android.launcher3.icons.BaseIconFactory.IconOptions import com.android.launcher3.icons.cache.BaseIconCache import com.android.launcher3.icons.cache.CachingLogic import com.android.launcher3.shortcuts.ShortcutKey +import com.android.launcher3.util.ApiWrapper import com.android.launcher3.util.ApplicationInfoWrapper import com.android.launcher3.util.PackageUserKey import com.android.launcher3.util.Themes @@ -114,7 +115,15 @@ object CacheableShortcutCachingLogic : CachingLogic { d, IconOptions() .setExtractedColor(Themes.getColorAccent(context)) - .setSourceHint(getSourceHint(info, cache)), + .setSourceHint( + getSourceHint(info, cache) + .copy( + isFileDrawable = + ApiWrapper.INSTANCE[context].isFileDrawable( + info.shortcutInfo + ) + ) + ), ) } ?: BitmapInfo.LOW_RES_INFO } diff --git a/src/com/android/launcher3/util/ApiWrapper.java b/src/com/android/launcher3/util/ApiWrapper.java index 56337b08e1..0510d591e4 100644 --- a/src/com/android/launcher3/util/ApiWrapper.java +++ b/src/com/android/launcher3/util/ApiWrapper.java @@ -216,6 +216,13 @@ public class ApiWrapper { return 0; } + /** + * Checks if the shortcut is using an icon with file or URI source + */ + public boolean isFileDrawable(@NonNull ShortcutInfo shortcutInfo) { + return false; + } + private static class NoopDrawable extends ColorDrawable { @Override public int getIntrinsicHeight() { From 3c4c943772ca859295b9d063ee116a2c6c960f37 Mon Sep 17 00:00:00 2001 From: Randy Pfohl Date: Thu, 13 Feb 2025 23:14:56 +0000 Subject: [PATCH 059/153] Fixing crash, and no touch input while mid animation Test: Local testing currently, will add more to bug Flag: com.android.launcher3.enable_fallback_overview_in_window com.android.launcher3.enable_launcher_overview_in_window Bug: 292269949 Change-Id: I5acfa734e434c625ef0f5efbce0cf09e2c5a179d --- .../quickstep/TaskAnimationManager.java | 52 +++++++++---------- .../fallback/window/RecentsWindowManager.kt | 2 +- .../android/quickstep/views/RecentsView.java | 2 +- 3 files changed, 27 insertions(+), 29 deletions(-) diff --git a/quickstep/src/com/android/quickstep/TaskAnimationManager.java b/quickstep/src/com/android/quickstep/TaskAnimationManager.java index 63b8aaf06e..d80cf48121 100644 --- a/quickstep/src/com/android/quickstep/TaskAnimationManager.java +++ b/quickstep/src/com/android/quickstep/TaskAnimationManager.java @@ -284,8 +284,32 @@ public class TaskAnimationManager implements RecentsAnimationCallbacks.RecentsAn mCallbacks.addListener(listener); final ActivityOptions options = ActivityOptions.makeBasic(); + options.setPendingIntentBackgroundActivityStartMode( + ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOW_ALWAYS); + options.setTransientLaunch(); + options.setSourceInfo(ActivityOptions.SourceInfo.TYPE_RECENTS_ANIMATION, eventTime); + + // Notify taskbar that we should skip reacting to launcher visibility change to + // avoid a jumping taskbar. + TaskbarUIController taskbarUIController = containerInterface.getTaskbarController(); + if (enableScalingRevealHomeAnimation() && taskbarUIController != null) { + taskbarUIController.setSkipLauncherVisibilityChange(true); + + mCallbacks.addListener(new RecentsAnimationCallbacks.RecentsAnimationListener() { + @Override + public void onRecentsAnimationCanceled( + @NonNull HashMap thumbnailDatas) { + taskbarUIController.setSkipLauncherVisibilityChange(false); + } + + @Override + public void onRecentsAnimationFinished( + @NonNull RecentsAnimationController controller) { + taskbarUIController.setSkipLauncherVisibilityChange(false); + } + }); + } - // TODO:(b/365777482) if flag is enabled, but on launcher it will crash. if(containerInterface.getCreatedContainer() instanceof RecentsWindowManager && (Flags.enableFallbackOverviewInWindow() || Flags.enableLauncherOverviewInWindow())) { @@ -295,32 +319,6 @@ public class TaskAnimationManager implements RecentsAnimationCallbacks.RecentsAn .getRecentsWindowManager(mDeviceState.getDisplayId()) .startRecentsWindow(mCallbacks); } else { - options.setPendingIntentBackgroundActivityStartMode( - ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOW_ALWAYS); - options.setTransientLaunch(); - options.setSourceInfo(ActivityOptions.SourceInfo.TYPE_RECENTS_ANIMATION, eventTime); - - // Notify taskbar that we should skip reacting to launcher visibility change to - // avoid a jumping taskbar. - TaskbarUIController taskbarUIController = containerInterface.getTaskbarController(); - if (enableScalingRevealHomeAnimation() && taskbarUIController != null) { - taskbarUIController.setSkipLauncherVisibilityChange(true); - - mCallbacks.addListener(new RecentsAnimationCallbacks.RecentsAnimationListener() { - @Override - public void onRecentsAnimationCanceled( - @NonNull HashMap thumbnailDatas) { - taskbarUIController.setSkipLauncherVisibilityChange(false); - } - - @Override - public void onRecentsAnimationFinished( - @NonNull RecentsAnimationController controller) { - taskbarUIController.setSkipLauncherVisibilityChange(false); - } - }); - } - mRecentsAnimationStartPending = getSystemUiProxy().startRecentsActivity(intent, options, mCallbacks, false /* useSyntheticRecentsTransition */); } diff --git a/quickstep/src/com/android/quickstep/fallback/window/RecentsWindowManager.kt b/quickstep/src/com/android/quickstep/fallback/window/RecentsWindowManager.kt index 3082dc6898..e9ed425de0 100644 --- a/quickstep/src/com/android/quickstep/fallback/window/RecentsWindowManager.kt +++ b/quickstep/src/com/android/quickstep/fallback/window/RecentsWindowManager.kt @@ -178,7 +178,7 @@ class RecentsWindowManager(context: Context, wallpaperColorHints: Int) : val recentsView: RecentsView<*, *> = getOverviewPanel() if (!finishRecentsAnimation) { - recentsView.switchToScreenshot(/* onFinishRunnable= */ null) + recentsView.switchToScreenshot /* onFinishRunnable= */ {} startHomeInternal() return } diff --git a/quickstep/src/com/android/quickstep/views/RecentsView.java b/quickstep/src/com/android/quickstep/views/RecentsView.java index a8f9dd4fe3..6e9246cc56 100644 --- a/quickstep/src/com/android/quickstep/views/RecentsView.java +++ b/quickstep/src/com/android/quickstep/views/RecentsView.java @@ -241,8 +241,8 @@ import com.android.wm.shell.shared.desktopmode.DesktopModeTransitionSource; import kotlin.Unit; import kotlin.collections.CollectionsKt; - import kotlin.jvm.functions.Function0; + import kotlinx.coroutines.CoroutineScope; import java.util.ArrayList; From 5b15f3855329856aafcae269cc20cddf73925213 Mon Sep 17 00:00:00 2001 From: Randy Pfohl Date: Thu, 13 Feb 2025 23:24:38 +0000 Subject: [PATCH 060/153] enabling animations to return to home Summary: Not entirely sure why this was false, but animating this looks much more clean then what it was. Test: Local testing currently, will add more to bug Flag: com.android.launcher3.enable_fallback_overview_in_window com.android.launcher3.enable_launcher_overview_in_window Bug: 292269949 Change-Id: Ib5e380a394cb5fd1f57933eb454eee3789f2057e --- .../android/quickstep/fallback/window/RecentsWindowManager.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/quickstep/src/com/android/quickstep/fallback/window/RecentsWindowManager.kt b/quickstep/src/com/android/quickstep/fallback/window/RecentsWindowManager.kt index e9ed425de0..9e8d69b868 100644 --- a/quickstep/src/com/android/quickstep/fallback/window/RecentsWindowManager.kt +++ b/quickstep/src/com/android/quickstep/fallback/window/RecentsWindowManager.kt @@ -229,7 +229,7 @@ class RecentsWindowManager(context: Context, wallpaperColorHints: Int) : anim, this@RecentsWindowManager, { - getStateManager().goToState(BG_LAUNCHER, false) + getStateManager().goToState(BG_LAUNCHER, true) cleanupRecentsWindow() }, true, /* skipFirstFrame */ From d08484669c38709c7af6690f0694e75ab1bf47c1 Mon Sep 17 00:00:00 2001 From: Randy Pfohl Date: Fri, 14 Feb 2025 03:42:20 +0000 Subject: [PATCH 061/153] Respond to configuration changes in RecentsWindowManager Summary: Will respond appropriately to config changes, there are additional issues within recentsview itself with some issues with the viewmodel binding. Test: Local testing currently, will add more to bug Flag: com.android.launcher3.enable_fallback_overview_in_window com.android.launcher3.enable_launcher_overview_in_window Change-Id: I854de2204b11d36941849703076def0c039060bf --- .../fallback/window/RecentsWindowContext.kt | 11 +- .../fallback/window/RecentsWindowManager.kt | 163 ++++++++++-------- 2 files changed, 96 insertions(+), 78 deletions(-) diff --git a/quickstep/src/com/android/quickstep/fallback/window/RecentsWindowContext.kt b/quickstep/src/com/android/quickstep/fallback/window/RecentsWindowContext.kt index 047658c419..cd4813631d 100644 --- a/quickstep/src/com/android/quickstep/fallback/window/RecentsWindowContext.kt +++ b/quickstep/src/com/android/quickstep/fallback/window/RecentsWindowContext.kt @@ -61,9 +61,13 @@ open class RecentsWindowContext(windowContext: Context, wallpaperColorHints: Int return dragLayer } + fun initDeviceProfile() { + deviceProfile = InvariantDeviceProfile.INSTANCE[this].getDeviceProfile(this) + } + override fun getDeviceProfile(): DeviceProfile { if (deviceProfile == null) { - deviceProfile = InvariantDeviceProfile.INSTANCE[this].getDeviceProfile(this).copy(this) + initDeviceProfile() } return deviceProfile!! } @@ -79,7 +83,10 @@ open class RecentsWindowContext(windowContext: Context, wallpaperColorHints: Int * @param type The window type to pass to the created WindowManager.LayoutParams. * @param title The window title to pass to the created WindowManager.LayoutParams. */ - fun createDefaultWindowLayoutParams(type: Int, title: String): WindowManager.LayoutParams { + private fun createDefaultWindowLayoutParams( + type: Int, + title: String, + ): WindowManager.LayoutParams { var windowFlags = (WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS or WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS or diff --git a/quickstep/src/com/android/quickstep/fallback/window/RecentsWindowManager.kt b/quickstep/src/com/android/quickstep/fallback/window/RecentsWindowManager.kt index 9e8d69b868..02bdedd50b 100644 --- a/quickstep/src/com/android/quickstep/fallback/window/RecentsWindowManager.kt +++ b/quickstep/src/com/android/quickstep/fallback/window/RecentsWindowManager.kt @@ -21,6 +21,7 @@ import android.app.ActivityOptions import android.content.ComponentName import android.content.Context import android.content.LocusId +import android.content.res.Configuration import android.os.Bundle import android.view.KeyEvent import android.view.LayoutInflater @@ -32,6 +33,7 @@ import android.view.View import android.view.WindowManager import android.view.WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY import android.window.RemoteTransition +import com.android.launcher3.AbstractFloatingView import com.android.launcher3.BaseActivity import com.android.launcher3.LauncherAnimationRunner import com.android.launcher3.LauncherAnimationRunner.RemoteAnimationFactory @@ -135,73 +137,6 @@ class RecentsWindowManager(context: Context, wallpaperColorHints: Int) : listOf(RunnableList(), RunnableList(), RunnableList(), RunnableList()) private var onInitListener: Predicate? = null - private val taskStackChangeListener = - object : TaskStackChangeListener { - override fun onTaskMovedToFront(taskId: Int) { - if ((isShowing() && isInState(DEFAULT))) { - // handling state where we end recents animation by swiping livetile away - // TODO: animate this switch. - cleanupRecentsWindow() - } - } - } - - private val recentsAnimationListener = - object : RecentsAnimationListener { - override fun onRecentsAnimationCanceled(thumbnailDatas: HashMap) { - recentAnimationStopped() - } - - override fun onRecentsAnimationFinished(controller: RecentsAnimationController) { - recentAnimationStopped() - } - } - - init { - TaskStackChangeListeners.getInstance().registerTaskStackListener(taskStackChangeListener) - } - - override fun destroy() { - super.destroy() - cleanupRecentsWindow() - TaskStackChangeListeners.getInstance().unregisterTaskStackListener(taskStackChangeListener) - callbacks?.removeListener(recentsAnimationListener) - recentsWindowTracker.onContextDestroyed(this) - recentsView?.destroy() - } - - override fun startHome() { - startHome(/* finishRecentsAnimation= */ true) - } - - fun startHome(finishRecentsAnimation: Boolean) { - val recentsView: RecentsView<*, *> = getOverviewPanel() - - if (!finishRecentsAnimation) { - recentsView.switchToScreenshot /* onFinishRunnable= */ {} - startHomeInternal() - return - } - recentsView.switchToScreenshot { - recentsView.finishRecentsAnimation(/* toRecents= */ true) { startHomeInternal() } - } - } - - private fun startHomeInternal() { - val runner = LauncherAnimationRunner(mainThreadHandler, animationToHomeFactory, true) - val options = - ActivityOptions.makeRemoteAnimation( - RemoteAnimationAdapter(runner, HOME_APPEAR_DURATION, 0), - RemoteTransition( - runner.toRemoteTransition(), - iApplicationThread, - "StartHomeFromRecents", - ), - ) - OverviewComponentObserver.startHomeIntentSafely(this, options.toBundle(), TAG) - stateManager.moveToRestState() - } - private val animationToHomeFactory = RemoteAnimationFactory { _: Int, @@ -242,17 +177,49 @@ class RecentsWindowManager(context: Context, wallpaperColorHints: Int) : TestLogging.recordEvent(SEQUENCE_MAIN, "onBackInvoked") } - private fun cleanupRecentsWindow() { - RecentsWindowProtoLogProxy.logCleanup(isShowing()) - if (isShowing()) { - windowManager.removeViewImmediate(windowView) + private val taskStackChangeListener = + object : TaskStackChangeListener { + override fun onTaskMovedToFront(taskId: Int) { + if ((isShowing() && isInState(DEFAULT))) { + // handling state where we end recents animation by swiping livetile away + // TODO: animate this switch. + cleanupRecentsWindow() + } + } } - stateManager.moveToRestState() - callbacks?.removeListener(recentsAnimationListener) + + private val recentsAnimationListener = + object : RecentsAnimationListener { + override fun onRecentsAnimationCanceled(thumbnailDatas: HashMap) { + recentAnimationStopped() + } + + override fun onRecentsAnimationFinished(controller: RecentsAnimationController) { + recentAnimationStopped() + } + } + + init { + TaskStackChangeListeners.getInstance().registerTaskStackListener(taskStackChangeListener) } - private fun isShowing(): Boolean { - return windowView?.parent != null + override fun handleConfigurationChanged(configuration: Configuration?) { + initDeviceProfile() + AbstractFloatingView.closeOpenViews( + this, + true, + AbstractFloatingView.TYPE_ALL and AbstractFloatingView.TYPE_REBIND_SAFE.inv(), + ) + dispatchDeviceProfileChanged() + } + + override fun destroy() { + super.destroy() + cleanupRecentsWindow() + TaskStackChangeListeners.getInstance().unregisterTaskStackListener(taskStackChangeListener) + callbacks?.removeListener(recentsAnimationListener) + recentsWindowTracker.onContextDestroyed(this) + recentsView?.destroy() } fun startRecentsWindow(callbacks: RecentsAnimationCallbacks? = null) { @@ -301,6 +268,51 @@ class RecentsWindowManager(context: Context, wallpaperColorHints: Int) : callbacks?.addListener(recentsAnimationListener) } + override fun startHome() { + startHome(/* finishRecentsAnimation= */ true) + } + + fun startHome(finishRecentsAnimation: Boolean) { + val recentsView: RecentsView<*, *> = getOverviewPanel() + + if (!finishRecentsAnimation) { + recentsView.switchToScreenshot /* onFinishRunnable= */ {} + startHomeInternal() + return + } + recentsView.switchToScreenshot { + recentsView.finishRecentsAnimation(/* toRecents= */ true) { startHomeInternal() } + } + } + + private fun startHomeInternal() { + val runner = LauncherAnimationRunner(mainThreadHandler, animationToHomeFactory, true) + val options = + ActivityOptions.makeRemoteAnimation( + RemoteAnimationAdapter(runner, HOME_APPEAR_DURATION, 0), + RemoteTransition( + runner.toRemoteTransition(), + iApplicationThread, + "StartHomeFromRecents", + ), + ) + OverviewComponentObserver.startHomeIntentSafely(this, options.toBundle(), TAG) + stateManager.moveToRestState() + } + + private fun cleanupRecentsWindow() { + RecentsWindowProtoLogProxy.logCleanup(isShowing()) + if (isShowing()) { + windowManager.removeViewImmediate(windowView) + } + stateManager.moveToRestState() + callbacks?.removeListener(recentsAnimationListener) + } + + private fun isShowing(): Boolean { + return windowView?.parent != null + } + private fun recentAnimationStopped() { if (isInState(BACKGROUND_APP)) { cleanupRecentsWindow() @@ -352,7 +364,6 @@ class RecentsWindowManager(context: Context, wallpaperColorHints: Int) : override fun onStateSetEnd(state: RecentsState) { super.onStateSetEnd(state) RecentsWindowProtoLogProxy.logOnStateSetEnd(getStateName(state)) - if (state == HOME || state == BG_LAUNCHER) { cleanupRecentsWindow() } From 4b695cab69c195e316de5541743b92d5fa811253 Mon Sep 17 00:00:00 2001 From: Hongwei Wang Date: Wed, 19 Feb 2025 11:18:32 -0800 Subject: [PATCH 062/153] Switch to PictureInPictureParams#isSameAspectRatio Switch to PictureInPictureParams#isSameAspectRatio on Launcher side, the same check has been applied in CTS tests. Flag: EXEMPT bugfix Bug: 352118806 Test: atest PinnedStackTests Change-Id: I26f87ef12b95204c7ee58467611b525aa24c3e3a --- .../android/quickstep/util/SwipePipToHomeAnimator.java | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/quickstep/src/com/android/quickstep/util/SwipePipToHomeAnimator.java b/quickstep/src/com/android/quickstep/util/SwipePipToHomeAnimator.java index 7d5b471f02..d2f9652d69 100644 --- a/quickstep/src/com/android/quickstep/util/SwipePipToHomeAnimator.java +++ b/quickstep/src/com/android/quickstep/util/SwipePipToHomeAnimator.java @@ -18,6 +18,7 @@ package com.android.quickstep.util; import android.animation.Animator; import android.animation.RectEvaluator; +import android.app.PictureInPictureParams; import android.content.ComponentName; import android.content.Context; import android.content.pm.ActivityInfo; @@ -25,6 +26,7 @@ import android.graphics.Matrix; import android.graphics.Rect; import android.graphics.RectF; import android.util.Log; +import android.util.Rational; import android.view.Surface; import android.view.SurfaceControl; import android.view.View; @@ -50,8 +52,6 @@ public class SwipePipToHomeAnimator extends RectFSpringAnim { private static final float END_PROGRESS = 1.0f; - private static final float PIP_ASPECT_RATIO_MISMATCH_THRESHOLD = 0.01f; - private final int mTaskId; private final ActivityInfo mActivityInfo; private final SurfaceControl mLeash; @@ -158,9 +158,8 @@ public class SwipePipToHomeAnimator extends RectFSpringAnim { // not a valid rectangle to use for cropping app surface reasonForCreateOverlay = "Source rect hint exceeds display bounds " + sourceRectHint; sourceRectHint.setEmpty(); - } else if (Math.abs( - aspectRatio - (sourceRectHint.width() / (float) sourceRectHint.height())) - > PIP_ASPECT_RATIO_MISMATCH_THRESHOLD) { + } else if (!PictureInPictureParams.isSameAspectRatio(sourceRectHint, + new Rational(destinationBounds.width(), destinationBounds.height()))) { // The source rect hint does not aspect ratio reasonForCreateOverlay = "Source rect hint does not match aspect ratio " + sourceRectHint + " aspect ratio " + aspectRatio; From c07bf539eea0cdd66b6830ad73fdc13f202bc635 Mon Sep 17 00:00:00 2001 From: Federico Baron Date: Fri, 14 Feb 2025 22:44:39 +0000 Subject: [PATCH 063/153] Don't modify invariant device profile We flag guard the code that modifies IDP as that's not needed with one grid, and we don't want to modify idp outside of it Bug: 332974074 Flag: com.android.launcher3.one_grid_specs Test: verified manually with b&r Change-Id: Ica2ffa79638fa693cde421adb13feebb0d09cbc4 --- src/com/android/launcher3/InvariantDeviceProfile.java | 3 ++- src/com/android/launcher3/provider/RestoreDbTask.java | 9 ++++++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/com/android/launcher3/InvariantDeviceProfile.java b/src/com/android/launcher3/InvariantDeviceProfile.java index 4107c8fdea..fc071d7093 100644 --- a/src/com/android/launcher3/InvariantDeviceProfile.java +++ b/src/com/android/launcher3/InvariantDeviceProfile.java @@ -312,7 +312,7 @@ public class InvariantDeviceProfile { context, gridName, displayInfo, - RestoreDbTask.isPending(mPrefs), + (RestoreDbTask.isPending(mPrefs) && !Flags.oneGridSpecs()), mPrefs.get(FIXED_LANDSCAPE_MODE) ); @@ -505,6 +505,7 @@ public class InvariantDeviceProfile { * Updates the current grid, this triggers a new IDP, reloads the database and triggers a grid * migration. */ + @VisibleForTesting public void setCurrentGrid(Context context, String newGridName) { mPrefs.put(GRID_NAME, newGridName); MAIN_EXECUTOR.execute(() -> { diff --git a/src/com/android/launcher3/provider/RestoreDbTask.java b/src/com/android/launcher3/provider/RestoreDbTask.java index 34c9117f1f..0da431f007 100644 --- a/src/com/android/launcher3/provider/RestoreDbTask.java +++ b/src/com/android/launcher3/provider/RestoreDbTask.java @@ -51,6 +51,7 @@ import androidx.annotation.NonNull; import androidx.annotation.VisibleForTesting; import androidx.annotation.WorkerThread; +import com.android.launcher3.Flags; import com.android.launcher3.InvariantDeviceProfile; import com.android.launcher3.LauncherAppState; import com.android.launcher3.LauncherFiles; @@ -130,9 +131,11 @@ public class RestoreDbTask { removeOldDBs(context, oldPhoneFileName); // The idp before this contains data about the old phone, after this it becomes the idp // of the current phone. - FileLog.d(TAG, "Resetting IDP to default for restore dest device"); - idp.reset(context); - trySettingPreviousGridAsCurrent(context, idp, oldPhoneFileName, previousDbs); + if (!Flags.oneGridSpecs()) { + FileLog.d(TAG, "Resetting IDP to default for restore dest device"); + idp.reset(context); + trySettingPreviousGridAsCurrent(context, idp, oldPhoneFileName, previousDbs); + } } From 1b4d00e250c0289cc20572a059d0ebdb209c7240 Mon Sep 17 00:00:00 2001 From: Sukesh Ram Date: Tue, 18 Feb 2025 16:30:35 -0800 Subject: [PATCH 064/153] [CD Taskbar] Create new taskbars only when we have system decor Only allow for new taskbars when wm.shouldShowSystemDecors=true. Bug: 397250946 Change-Id: I29577224e763ca44a2b1878691dce3e3aa1534ff Test: m Flag: com.android.window.flags.enable_taskbar_connected_displays --- .../com/android/launcher3/taskbar/TaskbarManager.java | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/quickstep/src/com/android/launcher3/taskbar/TaskbarManager.java b/quickstep/src/com/android/launcher3/taskbar/TaskbarManager.java index 46802c3f9e..de65676704 100644 --- a/quickstep/src/com/android/launcher3/taskbar/TaskbarManager.java +++ b/quickstep/src/com/android/launcher3/taskbar/TaskbarManager.java @@ -709,15 +709,14 @@ public class TaskbarManager { return; } - // TODO (b/391965805): remove once onDisplayAddSystemDecorations is working. - WindowManager wm = getWindowManager(displayId); - if (wm == null || !wm.shouldShowSystemDecors(displayId)) { - return; - } - Context newWindowContext = createWindowContext(displayId); if (newWindowContext != null) { addWindowContextToMap(displayId, newWindowContext); + // TODO (b/391965805): remove once onDisplayAddSystemDecorations is working. + WindowManager wm = getWindowManager(displayId); + if (wm == null || !wm.shouldShowSystemDecors(displayId)) { + return; + } createTaskbarRootLayout(displayId); createNavButtonController(displayId); createAndRegisterComponentCallbacks(displayId); From 92cb978575bd014ec4972497786c78b006baa87a Mon Sep 17 00:00:00 2001 From: minch Date: Fri, 14 Feb 2025 21:20:32 +0000 Subject: [PATCH 065/153] Make can create new desks a global state Bug: 389209338 Test: m Flag: EXEMPT new APIs update without impl yet. Change-Id: Id7ebfbc1d03d823932515df42fa51e22f44f8116 --- .../DesktopVisibilityController.kt | 34 +++++++++++++------ .../android/quickstep/views/RecentsView.java | 29 +++++++++++++--- .../util/window/WindowManagerProxy.java | 12 ++++++- 3 files changed, 58 insertions(+), 17 deletions(-) diff --git a/quickstep/src/com/android/launcher3/statehandlers/DesktopVisibilityController.kt b/quickstep/src/com/android/launcher3/statehandlers/DesktopVisibilityController.kt index 37e8d4dcd0..6ee43ff04d 100644 --- a/quickstep/src/com/android/launcher3/statehandlers/DesktopVisibilityController.kt +++ b/quickstep/src/com/android/launcher3/statehandlers/DesktopVisibilityController.kt @@ -62,8 +62,6 @@ constructor( * (Used only when multiple desks are enabled). * * @property displayId The ID of the display this object represents. - * @property canCreateDesks true if it's possible to create new desks on the display represented - * by this object. * @property activeDeskId The ID of the active desk on the associated display (if any). It has a * value of `INACTIVE_DESK_ID` (-1) if there are no active desks. Note that there can only be * at most one active desk on each display. @@ -71,11 +69,18 @@ constructor( */ private data class DisplayDeskConfig( val displayId: Int, - var canCreateDesks: Boolean, var activeDeskId: Int = INACTIVE_DESK_ID, val deskIds: MutableSet, ) + /** True if it is possible to create new desks on current setup. */ + var canCreateDesks: Boolean = false + private set(value) { + if (field == value) return + field = value + desktopVisibilityListeners.forEach { it.onCanCreateDesksChanged(field) } + } + /** Maps each display by its ID to its desks configuration. */ private val displaysDesksConfigsMap = SparseArray() @@ -393,7 +398,10 @@ constructor( } } - private fun onListenerConnected(displayDeskStates: Array) { + private fun onListenerConnected( + displayDeskStates: Array, + canCreateDesks: Boolean, + ) { if (!DesktopModeStatus.enableMultipleDesktops(context)) { return } @@ -404,23 +412,24 @@ constructor( displaysDesksConfigsMap[displayDeskState.displayId] = DisplayDeskConfig( displayId = displayDeskState.displayId, - canCreateDesks = displayDeskState.canCreateDesk, activeDeskId = displayDeskState.activeDeskId, deskIds = displayDeskState.deskIds.toMutableSet(), ) } + + this.canCreateDesks = canCreateDesks } private fun getDisplayDeskConfig(displayId: Int) = displaysDesksConfigsMap[displayId] ?: null.also { Slog.e(TAG, "Expected non-null desk config for display: $displayId") } - private fun onCanCreateDesksChanged(displayId: Int, canCreateDesks: Boolean) { + private fun onCanCreateDesksChanged(canCreateDesks: Boolean) { if (!DesktopModeStatus.enableMultipleDesktops(context)) { return } - getDisplayDeskConfig(displayId)?.canCreateDesks = canCreateDesks + this.canCreateDesks = canCreateDesks } private fun onDeskAdded(displayId: Int, deskId: Int) { @@ -525,9 +534,12 @@ constructor( ) : Stub() { private val controller = WeakReference(controller) - override fun onListenerConnected(displayDeskStates: Array) { + override fun onListenerConnected( + displayDeskStates: Array, + canCreateDesks: Boolean, + ) { Executors.MAIN_EXECUTOR.execute { - controller.get()?.onListenerConnected(displayDeskStates) + controller.get()?.onListenerConnected(displayDeskStates, canCreateDesks) } } @@ -565,9 +577,9 @@ constructor( override fun onExitDesktopModeTransitionStarted(transitionDuration: Int) {} - override fun onCanCreateDesksChanged(displayId: Int, canCreateDesks: Boolean) { + override fun onCanCreateDesksChanged(canCreateDesks: Boolean) { Executors.MAIN_EXECUTOR.execute { - controller.get()?.onCanCreateDesksChanged(displayId, canCreateDesks) + controller.get()?.onCanCreateDesksChanged(canCreateDesks) } } diff --git a/quickstep/src/com/android/quickstep/views/RecentsView.java b/quickstep/src/com/android/quickstep/views/RecentsView.java index a29d3028bc..c5a76cb067 100644 --- a/quickstep/src/com/android/quickstep/views/RecentsView.java +++ b/quickstep/src/com/android/quickstep/views/RecentsView.java @@ -157,6 +157,7 @@ import com.android.launcher3.logger.LauncherAtom; import com.android.launcher3.logging.StatsLogManager; import com.android.launcher3.model.data.ItemInfo; import com.android.launcher3.statehandlers.DepthController; +import com.android.launcher3.statehandlers.DesktopVisibilityController; import com.android.launcher3.statemanager.BaseState; import com.android.launcher3.statemanager.StateManager; import com.android.launcher3.statemanager.StatefulContainer; @@ -179,6 +180,7 @@ import com.android.launcher3.util.TranslateEdgeEffect; import com.android.launcher3.util.VibratorWrapper; import com.android.launcher3.util.ViewPool; import com.android.launcher3.util.coroutines.DispatcherProvider; +import com.android.launcher3.util.window.WindowManagerProxy.DesktopVisibilityListener; import com.android.quickstep.BaseContainerInterface; import com.android.quickstep.GestureState; import com.android.quickstep.HighResLoadingState; @@ -265,7 +267,7 @@ public abstract class RecentsView< CONTAINER_TYPE extends Context & RecentsViewContainer & StatefulContainer, STATE_TYPE extends BaseState> extends PagedView implements Insettable, HighResLoadingState.HighResLoadingStateChangedCallback, - TaskVisualsChangeListener { + TaskVisualsChangeListener, DesktopVisibilityListener { private static final String TAG = "RecentsView"; private static final boolean DEBUG = false; @@ -556,6 +558,10 @@ public abstract class RecentsView< private final Rect mTaskViewDeadZoneRect = new Rect(); private final Rect mTopRowDeadZoneRect = new Rect(); private final Rect mBottomRowDeadZoneRect = new Rect(); + + @Nullable + private DesktopVisibilityController mDesktopVisibilityController = null; + /** * Reflects if Recents is currently in the middle of a gesture, and if so, which tasks are * running. If a gesture is not in progress, this will be null. @@ -913,6 +919,8 @@ public abstract class RecentsView< mAddDesktopButton = (AddDesktopButton) LayoutInflater.from(context).inflate( R.layout.overview_add_desktop_button, this, false); mAddDesktopButton.setOnClickListener(this::createDesk); + + mDesktopVisibilityController = DesktopVisibilityController.INSTANCE.get(mContext); } mTaskViewPool = new ViewPool<>(context, this, R.layout.task, 20 /* max size */, @@ -1227,13 +1235,16 @@ public abstract class RecentsView< mSyncTransactionApplier = new SurfaceTransactionApplier(this); runActionOnRemoteHandles(remoteTargetHandle -> remoteTargetHandle.getTransformParams() .setSyncTransactionApplier(mSyncTransactionApplier)); - RecentsModel.INSTANCE.get(getContext()).addThumbnailChangeListener(this); + RecentsModel.INSTANCE.get(mContext).addThumbnailChangeListener(this); mIPipAnimationListener.setActivityAndRecentsView(mContainer, this); - SystemUiProxy.INSTANCE.get(getContext()).setPipAnimationListener( + SystemUiProxy.INSTANCE.get(mContext).setPipAnimationListener( mIPipAnimationListener); mOrientationState.initListeners(); mTaskOverlayFactory.initListeners(); mSplitSelectStateController.registerSplitListener(mSplitSelectionListener); + if (mDesktopVisibilityController != null) { + mDesktopVisibilityController.registerDesktopVisibilityListener(this); + } } @Override @@ -1248,12 +1259,15 @@ public abstract class RecentsView< runActionOnRemoteHandles(remoteTargetHandle -> remoteTargetHandle.getTransformParams() .setSyncTransactionApplier(null)); executeSideTaskLaunchCallback(); - RecentsModel.INSTANCE.get(getContext()).removeThumbnailChangeListener(this); - SystemUiProxy.INSTANCE.get(getContext()).setPipAnimationListener(null); + RecentsModel.INSTANCE.get(mContext).removeThumbnailChangeListener(this); + SystemUiProxy.INSTANCE.get(mContext).setPipAnimationListener(null); mIPipAnimationListener.setActivityAndRecentsView(null, null); mOrientationState.destroyListeners(); mTaskOverlayFactory.removeListeners(); mSplitSelectStateController.unregisterSplitListener(mSplitSelectionListener); + if (mDesktopVisibilityController != null) { + mDesktopVisibilityController.unregisterDesktopVisibilityListener(this); + } reset(); } @@ -6859,6 +6873,11 @@ public abstract class RecentsView< } } + @Override + public void onCanCreateDesksChanged(boolean canCreateDesks) { + // TODO: b/389209338 - update the AddDesktopButton's visibility on this. + } + /** Get the color used for foreground scrimming the RecentsView for sharing. */ public static int getForegroundScrimDimColor(Context context) { return context.getColor(R.color.overview_foreground_scrim_color); diff --git a/src/com/android/launcher3/util/window/WindowManagerProxy.java b/src/com/android/launcher3/util/window/WindowManagerProxy.java index 647d170340..11f0bc21b9 100644 --- a/src/com/android/launcher3/util/window/WindowManagerProxy.java +++ b/src/com/android/launcher3/util/window/WindowManagerProxy.java @@ -509,7 +509,17 @@ public class WindowManagerProxy { * @param isInDesktopModeAndNotInOverview True if a desktop is currently active on the given * display, and Overview is currently inactive. */ - void onIsInDesktopModeChanged(int displayId, boolean isInDesktopModeAndNotInOverview); + default void onIsInDesktopModeChanged(int displayId, + boolean isInDesktopModeAndNotInOverview) { + } + + /** + * Called whenever the conditions that allow the creation of desks change. + * + * @param canCreateDesks whether it is possible to create new desks. + */ + default void onCanCreateDesksChanged(boolean canCreateDesks) { + } } } From c926dd5be286ed2e46bed571d423ce8b9bbc7206 Mon Sep 17 00:00:00 2001 From: Fengjiang Li Date: Wed, 19 Feb 2025 10:24:04 -0800 Subject: [PATCH 066/153] [Memory Leak] Attempt to fix leak caused by onEndCallback created for open app animation not running Fix: 397690719 Flag: NONE - release code Test: presubmit Change-Id: Icf36b744f21f50b7182c81437ef29b5886c2d43d --- .../launcher3/QuickstepTransitionManager.java | 24 ++++++++++++++++--- .../TaskRestartedDuringLaunchListener.java | 5 ---- 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/quickstep/src/com/android/launcher3/QuickstepTransitionManager.java b/quickstep/src/com/android/launcher3/QuickstepTransitionManager.java index c7483851b1..67feb6a6b8 100644 --- a/quickstep/src/com/android/launcher3/QuickstepTransitionManager.java +++ b/quickstep/src/com/android/launcher3/QuickstepTransitionManager.java @@ -226,7 +226,6 @@ public class QuickstepTransitionManager implements OnDeviceProfileChangeListener private static final int TASKBAR_TO_HOME_DURATION_FAST = 300; private static final int TASKBAR_TO_HOME_DURATION_SLOW = 1000; protected static final int CONTENT_SCALE_DURATION = 350; - protected static final int CONTENT_SCRIM_DURATION = 350; private static final int MAX_NUM_TASKS = 5; @@ -244,7 +243,13 @@ public class QuickstepTransitionManager implements OnDeviceProfileChangeListener private final StartingWindowListener mStartingWindowListener = new StartingWindowListener(this); - private ContentObserver mAnimationRemovalObserver = new ContentObserver( + + // TODO(b/397690719): Investigate the memory leak from TaskStackChangeListeners#mImpl + // This is a temporary fix of memory leak b/397690719. We track registered + // {@link TaskRestartedDuringLaunchListener}, and remove them on activity destroy. + private final List mRegisteredTaskStackChangeListener = + new ArrayList<>(); + private final ContentObserver mAnimationRemovalObserver = new ContentObserver( ORDERED_BG_EXECUTOR.getHandler()) { @Override public void onChange(boolean selfChange) { @@ -338,7 +343,14 @@ public class QuickstepTransitionManager implements OnDeviceProfileChangeListener TaskRestartedDuringLaunchListener restartedListener = new TaskRestartedDuringLaunchListener(); restartedListener.register(onEndCallback::executeAllAndDestroy); - onEndCallback.add(restartedListener::unregister); + mRegisteredTaskStackChangeListener.add(restartedListener); + onEndCallback.add(new Runnable() { + @Override + public void run() { + restartedListener.unregister(); + mRegisteredTaskStackChangeListener.remove(restartedListener); + } + }); RemoteAnimationRunnerCompat runner = createAppLaunchRunner(v, onEndCallback); @@ -1210,6 +1222,12 @@ public class QuickstepTransitionManager implements OnDeviceProfileChangeListener SystemUiProxy.INSTANCE.get(mLauncher).setStartingWindowListener(null); ORDERED_BG_EXECUTOR.execute(() -> mLauncher.getContentResolver() .unregisterContentObserver(mAnimationRemovalObserver)); + if (BuildConfig.IS_STUDIO_BUILD && !mRegisteredTaskStackChangeListener.isEmpty()) { + throw new IllegalStateException("Failed to run onEndCallback created from" + + " getActivityLaunchOptions()"); + } + mRegisteredTaskStackChangeListener.forEach(TaskRestartedDuringLaunchListener::unregister); + mRegisteredTaskStackChangeListener.clear(); } /** diff --git a/quickstep/src/com/android/quickstep/util/TaskRestartedDuringLaunchListener.java b/quickstep/src/com/android/quickstep/util/TaskRestartedDuringLaunchListener.java index 91e8376990..6e2d469d18 100644 --- a/quickstep/src/com/android/quickstep/util/TaskRestartedDuringLaunchListener.java +++ b/quickstep/src/com/android/quickstep/util/TaskRestartedDuringLaunchListener.java @@ -16,16 +16,11 @@ package com.android.quickstep.util; -import static android.app.ActivityTaskManager.INVALID_TASK_ID; - -import android.app.Activity; import android.app.ActivityManager; import android.util.Log; import androidx.annotation.NonNull; -import com.android.launcher3.util.ActivityLifecycleCallbacksAdapter; -import com.android.quickstep.RecentsModel; import com.android.systemui.shared.system.TaskStackChangeListener; import com.android.systemui.shared.system.TaskStackChangeListeners; From f275bd9bccd06fb5cdd44366383afd34330bf9bc Mon Sep 17 00:00:00 2001 From: Gustav Sennton Date: Tue, 28 Jan 2025 14:55:22 +0000 Subject: [PATCH 067/153] Log minimize CUJ in MinimizeAnimator Flag: NONE refactor Test: manual Bug: 374206096 Change-Id: Id8ab050e5f2f519cccc460b690c2e8edd7c20561 --- .../launcher3/desktop/DesktopAppLaunchAnimatorHelper.kt | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/quickstep/src/com/android/launcher3/desktop/DesktopAppLaunchAnimatorHelper.kt b/quickstep/src/com/android/launcher3/desktop/DesktopAppLaunchAnimatorHelper.kt index adbcc75728..6423ea3ad3 100644 --- a/quickstep/src/com/android/launcher3/desktop/DesktopAppLaunchAnimatorHelper.kt +++ b/quickstep/src/com/android/launcher3/desktop/DesktopAppLaunchAnimatorHelper.kt @@ -173,10 +173,12 @@ class DesktopAppLaunchAnimatorHelper( onAnimFinish: (Animator) -> Unit, ): Animator { return MinimizeAnimator.create( - context.resources.displayMetrics, + context, change, transaction, onAnimFinish, + interactionJankMonitor, + context.mainThreadHandler, ) } From e79ccd9c96504940d666ffdfc929d1517c4f54e0 Mon Sep 17 00:00:00 2001 From: Pat Manning Date: Thu, 20 Feb 2025 14:08:18 +0000 Subject: [PATCH 068/153] Add screen record to determine flake of testDismissCancel. Bug: 396447643 Test: TaplTestsQuickstep#testDismissCancel Flag: com.android.launcher3.enable_expressive_dismiss_task_motion Change-Id: Iec03b7ed64d21dc425cf84c62dea4131a050b7b2 --- .../tests/src/com/android/quickstep/TaplTestsQuickstep.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/quickstep/tests/src/com/android/quickstep/TaplTestsQuickstep.java b/quickstep/tests/src/com/android/quickstep/TaplTestsQuickstep.java index aaaa0e45da..1c7f51ceeb 100644 --- a/quickstep/tests/src/com/android/quickstep/TaplTestsQuickstep.java +++ b/quickstep/tests/src/com/android/quickstep/TaplTestsQuickstep.java @@ -50,6 +50,7 @@ import com.android.launcher3.tapl.Workspace; import com.android.launcher3.ui.PortraitLandscapeRunner.PortraitLandscape; import com.android.launcher3.util.TestUtil; import com.android.launcher3.util.Wait; +import com.android.launcher3.util.rule.ScreenRecordRule; import com.android.launcher3.util.rule.TestStabilityRule; import com.android.quickstep.NavigationModeSwitchRule.NavigationModeSwitch; import com.android.quickstep.TaskbarModeSwitchRule.TaskbarModeSwitch; @@ -542,6 +543,7 @@ public class TaplTestsQuickstep extends AbstractQuickStepTest { @Test @PortraitLandscape + @ScreenRecordRule.ScreenRecord // TODO(b/396447643): Remove screen record. public void testDismissCancel() throws Exception { startTestAppsWithCheck(); Overview overview = mLauncher.goHome().switchToOverview(); From 19381579f1e910f0ec3d65ba46485af7676dd3eb Mon Sep 17 00:00:00 2001 From: Uwais Ashraf Date: Thu, 20 Feb 2025 16:26:41 +0000 Subject: [PATCH 069/153] Copy drawable so that mutations don't affect other uses of the drawable Fix: 397770855 Flag: EXEMPT - test fix Test: OverviewTaskSelectImageTest Change-Id: I9e0fa179ab3c7de6edf566f50459c51c6efb4377 --- quickstep/src/com/android/quickstep/views/IconView.kt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/quickstep/src/com/android/quickstep/views/IconView.kt b/quickstep/src/com/android/quickstep/views/IconView.kt index 6da52d666c..cb69b22de0 100644 --- a/quickstep/src/com/android/quickstep/views/IconView.kt +++ b/quickstep/src/com/android/quickstep/views/IconView.kt @@ -78,7 +78,8 @@ class IconView : View, TaskViewIcon { override fun setDrawable(d: Drawable?) { drawable?.callback = null - drawable = d + // Copy drawable so that mutations below do not affect other users of the drawable + drawable = d?.constantState?.newDrawable()?.mutate() drawable?.let { it.callback = this setDrawableSizeInternal(width, height) From 91370114ea6aacf3189a57eac25c960509208dd6 Mon Sep 17 00:00:00 2001 From: Uwais Ashraf Date: Thu, 20 Feb 2025 17:03:27 +0000 Subject: [PATCH 070/153] Add null checks to prevent NPE on ViewModel. ViewModel can be null if onRecycle completes before coroutineJob is cancelled. Fix: 395751707 Flag: Exempt - test fix Test: OpenActivityEmbeddingPlaceholderSplitTest in postsubmit Change-Id: I12e1f6e2e5951ae04264fc8ea9d45b6ac6d43308 --- quickstep/src/com/android/quickstep/views/TaskView.kt | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/quickstep/src/com/android/quickstep/views/TaskView.kt b/quickstep/src/com/android/quickstep/views/TaskView.kt index 49ec31dbab..ba5423217e 100644 --- a/quickstep/src/com/android/quickstep/views/TaskView.kt +++ b/quickstep/src/com/android/quickstep/views/TaskView.kt @@ -789,11 +789,11 @@ constructor( private fun updateThumbnailValidity(container: TaskContainer) { container.isThumbnailValid = - viewModel!!.isThumbnailValid( + viewModel?.isThumbnailValid( thumbnail = container.thumbnailData, width = container.thumbnailView.width, height = container.thumbnailView.height, - ) + ) ?: return applyThumbnailSplashAlpha() } @@ -810,7 +810,8 @@ constructor( */ private fun updateThumbnailMatrix(container: TaskContainer, width: Int, height: Int) { val thumbnailPosition = - viewModel!!.getThumbnailPosition(container.thumbnailData, width, height, isLayoutRtl) + viewModel?.getThumbnailPosition(container.thumbnailData, width, height, isLayoutRtl) + ?: return container.updateThumbnailMatrix(thumbnailPosition.matrix) } From c8ee653eef8bd1ef7e865bfc84a69e1d4d80c46d Mon Sep 17 00:00:00 2001 From: Vania Desmonda Date: Wed, 19 Feb 2025 16:00:55 +0000 Subject: [PATCH 071/153] Launch app pair when one of them is in freeform. Call launchAppPair when one of the tasks is in freeform to prevent only launching one app to the side and choosing the DesktopWallpaperActivity as the other app pair. Fixes: 394917143 Flag: com.android.window.flags.enable_desktop_windowing_mode Test: atest NexusLauncherRoboTests Change-Id: I3967473fa648f2b245ac8b4f16e6112f6d8f077f --- .../quickstep/util/AppPairsController.java | 20 ++++-- .../quickstep/util/AppPairsControllerTest.kt | 68 +++++++++++++++++++ 2 files changed, 84 insertions(+), 4 deletions(-) diff --git a/quickstep/src/com/android/quickstep/util/AppPairsController.java b/quickstep/src/com/android/quickstep/util/AppPairsController.java index f20d7a551d..8385485253 100644 --- a/quickstep/src/com/android/quickstep/util/AppPairsController.java +++ b/quickstep/src/com/android/quickstep/util/AppPairsController.java @@ -26,6 +26,7 @@ import static com.android.launcher3.util.Executors.MAIN_EXECUTOR; import static com.android.launcher3.util.Executors.MODEL_EXECUTOR; import static com.android.launcher3.util.SplitConfigurationOptions.STAGE_POSITION_BOTTOM_OR_RIGHT; import static com.android.launcher3.util.SplitConfigurationOptions.STAGE_POSITION_TOP_OR_LEFT; +import static com.android.systemui.shared.recents.utilities.Utilities.isFreeformTask; import static com.android.wm.shell.shared.split.SplitScreenConstants.SNAP_TO_2_50_50; import static com.android.wm.shell.shared.split.SplitScreenConstants.SNAP_TO_NONE; import static com.android.wm.shell.shared.split.SplitScreenConstants.getIndex; @@ -69,6 +70,7 @@ import com.android.quickstep.views.TaskContainer; import com.android.quickstep.views.TaskView; import com.android.systemui.shared.recents.model.Task; import com.android.systemui.shared.system.InteractionJankMonitorWrapper; +import com.android.wm.shell.shared.desktopmode.DesktopModeStatus; import com.android.wm.shell.shared.split.SplitScreenConstants.PersistentSnapPosition; import java.util.Arrays; @@ -337,10 +339,12 @@ public class AppPairsController { * c) App B is on-screen, but App A isn't. * d) Neither is on-screen. * - * If the user tapped an app pair while inside a single app, there are 3 cases: - * a) The on-screen app is App A of the app pair. - * b) The on-screen app is App B of the app pair. - * c) It is neither. + * If the user tapped an app pair while a fullscreen or freeform app is visible on screen, + * there are 4 cases: + * a) At least one of the apps in the app pair is in freeform windowing mode. + * b) The on-screen app is App A of the app pair. + * c) The on-screen app is App B of the app pair. + * d) It is neither. * * For each case, we call the appropriate animation and split launch type. */ @@ -422,6 +426,14 @@ public class AppPairsController { foundTasks -> { Task foundTask1 = foundTasks[0]; Task foundTask2 = foundTasks[1]; + + if (DesktopModeStatus.canEnterDesktopMode(context) && (isFreeformTask( + foundTask1) || isFreeformTask(foundTask2))) { + launchAppPair(launchingIconView, + CUJ_LAUNCHER_LAUNCH_APP_PAIR_FROM_TASKBAR); + return; + } + boolean task1IsOnScreen; boolean task2IsOnScreen; if (com.android.wm.shell.Flags.enableShellTopTaskTracking()) { diff --git a/quickstep/tests/multivalentTests/src/com/android/quickstep/util/AppPairsControllerTest.kt b/quickstep/tests/multivalentTests/src/com/android/quickstep/util/AppPairsControllerTest.kt index ee70e0a9d3..76d36d3658 100644 --- a/quickstep/tests/multivalentTests/src/com/android/quickstep/util/AppPairsControllerTest.kt +++ b/quickstep/tests/multivalentTests/src/com/android/quickstep/util/AppPairsControllerTest.kt @@ -16,7 +16,9 @@ package com.android.quickstep.util +import android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM import android.content.Context +import android.content.res.Resources import androidx.test.ext.junit.runners.AndroidJUnit4 import com.android.launcher3.apppairs.AppPairIcon import com.android.launcher3.logging.StatsLogManager @@ -28,6 +30,7 @@ import com.android.quickstep.TopTaskTracker import com.android.quickstep.TopTaskTracker.CachedTaskInfo import com.android.systemui.shared.recents.model.Task import com.android.systemui.shared.recents.model.Task.TaskKey +import com.android.wm.shell.shared.desktopmode.DesktopModeStatus import com.android.wm.shell.shared.split.SplitScreenConstants.SNAP_TO_2_33_66 import com.android.wm.shell.shared.split.SplitScreenConstants.SNAP_TO_2_50_50 import com.android.wm.shell.shared.split.SplitScreenConstants.SNAP_TO_2_66_33 @@ -54,6 +57,7 @@ import org.mockito.kotlin.whenever @RunWith(AndroidJUnit4::class) class AppPairsControllerTest { @Mock lateinit var context: Context + @Mock lateinit var resources: Resources @Mock lateinit var splitSelectStateController: SplitSelectStateController @Mock lateinit var statsLogManager: StatsLogManager @@ -109,6 +113,8 @@ class AppPairsControllerTest { doNothing() .whenever(spyAppPairsController) .launchToSide(anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull()) + whenever(mockAppPairIcon.context.resources).thenReturn(resources) + whenever(DesktopModeStatus.canEnterDesktopMode(mockAppPairIcon.context)).thenReturn(false) } @Test @@ -391,6 +397,68 @@ class AppPairsControllerTest { .launchToSide(anyOrNull(), anyOrNull(), anyOrNull(), eq(STAGE_POSITION_TOP_OR_LEFT)) } + @Test + fun handleAppPairLaunchInApp_freeformTask1IsOnScreen_shouldLaunchAppPair() { + whenever(DesktopModeStatus.canEnterDesktopMode(mockAppPairIcon.context)).thenReturn(true) + /// Test launching apps 1 and 2 from app pair + whenever(mockTaskKey1.getId()).thenReturn(1) + whenever(mockTaskKey2.getId()).thenReturn(2) + // Task 1 is in freeform windowing mode + mockTaskKey1.windowingMode = WINDOWING_MODE_FREEFORM + // ... and app 1 is already on screen + if (com.android.wm.shell.Flags.enableShellTopTaskTracking()) { + whenever(mockCachedTaskInfo.topGroupedTaskContainsTask(eq(1))).thenReturn(true) + } else { + whenever(mockCachedTaskInfo.taskId).thenReturn(1) + } + + // Trigger app pair launch, capture and run callback from findLastActiveTasksAndRunCallback + spyAppPairsController.handleAppPairLaunchInApp( + mockAppPairIcon, + listOf(mockItemInfo1, mockItemInfo2), + ) + verify(splitSelectStateController) + .findLastActiveTasksAndRunCallback(any(), any(), callbackCaptor.capture()) + val callback: Consumer> = callbackCaptor.value + callback.accept(arrayOf(mockTask1, mockTask2)) + + // Verify that launchAppPair was called + verify(spyAppPairsController, times(1)).launchAppPair(any(), any()) + verify(spyAppPairsController, never()) + .launchToSide(anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull()) + } + + @Test + fun handleAppPairLaunchInApp_freeformTask2IsOnScreen_shouldLaunchAppPair() { + whenever(DesktopModeStatus.canEnterDesktopMode(mockAppPairIcon.context)).thenReturn(true) + /// Test launching apps 1 and 2 from app pair + whenever(mockTaskKey1.getId()).thenReturn(1) + whenever(mockTaskKey2.getId()).thenReturn(2) + // Task 2 is in freeform windowing mode + mockTaskKey1.windowingMode = WINDOWING_MODE_FREEFORM + // ... and app 2 is already on screen + if (com.android.wm.shell.Flags.enableShellTopTaskTracking()) { + whenever(mockCachedTaskInfo.topGroupedTaskContainsTask(eq(2))).thenReturn(true) + } else { + whenever(mockCachedTaskInfo.taskId).thenReturn(2) + } + + // Trigger app pair launch, capture and run callback from findLastActiveTasksAndRunCallback + spyAppPairsController.handleAppPairLaunchInApp( + mockAppPairIcon, + listOf(mockItemInfo1, mockItemInfo2), + ) + verify(splitSelectStateController) + .findLastActiveTasksAndRunCallback(any(), any(), callbackCaptor.capture()) + val callback: Consumer> = callbackCaptor.value + callback.accept(arrayOf(mockTask1, mockTask2)) + + // Verify that launchAppPair was called + verify(spyAppPairsController, times(1)).launchAppPair(any(), any()) + verify(spyAppPairsController, never()) + .launchToSide(anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull()) + } + @Test fun handleAppPairLaunchInApp_shouldLaunchAppPairNormallyWhenUnrelatedSingleAppIsFullscreen() { // Test launching apps 1 and 2 from app pair From 2caae623a6f59bb216a49ffcb55ab0f81c209598 Mon Sep 17 00:00:00 2001 From: Pat Manning Date: Thu, 20 Feb 2025 15:18:10 +0000 Subject: [PATCH 072/153] Close gap between grid and clear all for expressive dismiss. Fix: 397891454 Test: TaplTestsQuickstep#testDismissLastGridRow Flag: com.android.launcher3.enable_expressive_dismiss_task_motion Change-Id: Id49447819c38f307f05cd4ecc3d501bd51766443 --- .../android/quickstep/views/RecentsView.java | 4 ++- .../android/quickstep/TaplTestsQuickstep.java | 34 +++++++++++++++++++ .../android/launcher3/tapl/BaseOverview.java | 18 ++++++---- .../android/launcher3/tapl/OverviewTask.java | 2 +- 4 files changed, 50 insertions(+), 8 deletions(-) diff --git a/quickstep/src/com/android/quickstep/views/RecentsView.java b/quickstep/src/com/android/quickstep/views/RecentsView.java index a29d3028bc..16ce2bd3f8 100644 --- a/quickstep/src/com/android/quickstep/views/RecentsView.java +++ b/quickstep/src/com/android/quickstep/views/RecentsView.java @@ -38,6 +38,7 @@ import static com.android.launcher3.BaseActivity.STATE_HANDLER_INVISIBILITY_FLAG import static com.android.launcher3.Flags.enableAdditionalHomeAnimations; import static com.android.launcher3.Flags.enableDesktopExplodedView; import static com.android.launcher3.Flags.enableDesktopTaskAlphaAnimation; +import static com.android.launcher3.Flags.enableExpressiveDismissTaskMotion; import static com.android.launcher3.Flags.enableGridOnlyOverview; import static com.android.launcher3.Flags.enableLargeDesktopWindowingTile; import static com.android.launcher3.Flags.enableRefactorTaskThumbnail; @@ -3840,7 +3841,8 @@ public abstract class RecentsView< newClearAllShortTotalWidthTranslation = expectedFirstTaskStart - firstTaskStart; } } - if (lastGridTaskView != null && lastGridTaskView.isVisibleToUser()) { + if (lastGridTaskView != null && (lastGridTaskView.isVisibleToUser() || ( + enableExpressiveDismissTaskMotion() && lastGridTaskView == dismissedTaskView))) { // After dismissal, animate translation of the remaining tasks to fill any gap left // between the end of the grid and the clear all button. Only animate if the clear // all button is visible or would become visible after dismissal. diff --git a/quickstep/tests/src/com/android/quickstep/TaplTestsQuickstep.java b/quickstep/tests/src/com/android/quickstep/TaplTestsQuickstep.java index aaaa0e45da..6761e9b85e 100644 --- a/quickstep/tests/src/com/android/quickstep/TaplTestsQuickstep.java +++ b/quickstep/tests/src/com/android/quickstep/TaplTestsQuickstep.java @@ -23,6 +23,7 @@ import static com.android.quickstep.TaskbarModeSwitchRule.Mode.TRANSIENT; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeFalse; @@ -579,6 +580,39 @@ public class TaplTestsQuickstep extends AbstractQuickStepTest { numTasks - 1, recentsView.getTaskViewCount())); } + @Test + @PortraitLandscape + public void testDismissLastGridRow() throws Exception { + assumeTrue(mLauncher.isTablet()); + mLauncher.goHome().switchToOverview().dismissAllTasks(); + startTestAppsWithCheck(); + startTestActivity(3); + startTestActivity(4); + runOnRecentsView( + recentsView -> assertNotEquals("Grid overview should have unequal row counts", + recentsView.getTopRowTaskCountForTablet(), + recentsView.getBottomRowTaskCountForTablet())); + Overview overview = mLauncher.goHome().switchToOverview(); + assertIsInState("Launcher internal state didn't switch to Overview", + ExpectedState.OVERVIEW); + overview.flingForwardUntilClearAllVisible(); + assertTrue("Clear All not visible.", overview.isClearAllVisible()); + final Integer numTasks = getFromRecentsView(RecentsView::getTaskViewCount); + OverviewTask lastGridTask = overview.getCurrentTasksForTablet().stream().min( + Comparator.comparingInt(OverviewTask::getTaskCenterX)).get(); + assertNotNull("lastGridTask null.", lastGridTask); + + lastGridTask.dismiss(); + + runOnRecentsView(recentsView -> assertEquals( + "Dismissing a lastGridTask didn't remove 1 lastGridTask from Overview", + numTasks - 1, recentsView.getTaskViewCount())); + runOnRecentsView(recentsView -> assertEquals("Grid overview should have equal row counts.", + recentsView.getTopRowTaskCountForTablet(), + recentsView.getBottomRowTaskCountForTablet())); + assertTrue("Clear All not visible.", overview.isClearAllVisible()); + } + private void startTestAppsWithCheck() throws Exception { startTestApps(); expectLaunchedAppState(); diff --git a/tests/tapl/com/android/launcher3/tapl/BaseOverview.java b/tests/tapl/com/android/launcher3/tapl/BaseOverview.java index ef72a0f6f1..f633d48363 100644 --- a/tests/tapl/com/android/launcher3/tapl/BaseOverview.java +++ b/tests/tapl/com/android/launcher3/tapl/BaseOverview.java @@ -157,12 +157,7 @@ public class BaseOverview extends LauncherInstrumentation.VisibleContainer { LauncherInstrumentation.Closable c = mLauncher.addContextLayer( "dismissing all tasks")) { final BySelector clearAllSelector = mLauncher.getOverviewObjectSelector("clear_all"); - for (int i = 0; - i < FLINGS_FOR_DISMISS_LIMIT - && !verifyActiveContainer().hasObject(clearAllSelector); - ++i) { - flingForwardImpl(); - } + flingForwardUntilClearAllVisible(); final Runnable clickClearAll = () -> mLauncher.clickLauncherObject( mLauncher.waitForObjectInContainer(verifyActiveContainer(), @@ -182,6 +177,17 @@ public class BaseOverview extends LauncherInstrumentation.VisibleContainer { } } + /** + * Scrolls until Clear-all button is visible. + */ + public void flingForwardUntilClearAllVisible() { + final BySelector clearAllSelector = mLauncher.getOverviewObjectSelector("clear_all"); + for (int i = 0; i < FLINGS_FOR_DISMISS_LIMIT + && !verifyActiveContainer().hasObject(clearAllSelector); ++i) { + flingForwardImpl(); + } + } + /** * Touch to the right of current task. This should dismiss overview and go back to Workspace. */ diff --git a/tests/tapl/com/android/launcher3/tapl/OverviewTask.java b/tests/tapl/com/android/launcher3/tapl/OverviewTask.java index 4e94e1e7c6..8fbb5e3172 100644 --- a/tests/tapl/com/android/launcher3/tapl/OverviewTask.java +++ b/tests/tapl/com/android/launcher3/tapl/OverviewTask.java @@ -125,7 +125,7 @@ public final class OverviewTask { return right - left; } - int getTaskCenterX() { + public int getTaskCenterX() { return mTask.getVisibleCenter().x; } From 3fd385c1cd5b4dcc7f086f20b82dca684581a89b Mon Sep 17 00:00:00 2001 From: Sunny Goyal Date: Wed, 19 Feb 2025 15:45:59 -0800 Subject: [PATCH 073/153] Moving grid customization provider to Dagger Bug: 361850561 Test: Presubmit Flag: EXEMPT dagger Change-Id: I0ebc2a614b9448e5de97d3dda43d98b951989689 --- Android.bp | 9 ++ AndroidManifest-common.xml | 2 +- .../dagger/LauncherBaseAppComponent.java | 3 + ...ider.java => GridCustomizationsProxy.java} | 96 +++++++++---------- .../graphics/LauncherCustomizationProvider.kt | 29 ++++++ .../graphics/PreviewSurfaceRenderer.java | 2 +- .../testing/TestInformationProvider.java | 69 +++++-------- .../launcher3/util/ContentProviderProxy.kt | 86 +++++++++++++++++ 8 files changed, 196 insertions(+), 100 deletions(-) rename src/com/android/launcher3/graphics/{GridCustomizationsProvider.java => GridCustomizationsProxy.java} (87%) create mode 100644 src/com/android/launcher3/graphics/LauncherCustomizationProvider.kt create mode 100644 src/com/android/launcher3/util/ContentProviderProxy.kt diff --git a/Android.bp b/Android.bp index 1e1e0ad6cc..a4a058fce0 100644 --- a/Android.bp +++ b/Android.bp @@ -455,6 +455,9 @@ android_app { extra_check_modules: ["Launcher3LintChecker"], baseline_filename: "lint-baseline.xml", }, + kotlincflags: [ + "-Xjvm-default=all", + ], } // Library with all the dependencies for building quickstep @@ -519,6 +522,9 @@ android_library { min_sdk_version: "current", // TODO(b/319712088): re-enable use_resource_processor use_resource_processor: false, + kotlincflags: [ + "-Xjvm-default=all", + ], } // Library with all the source code and dependencies for building Quickstep @@ -552,6 +558,9 @@ android_library { min_sdk_version: "current", // TODO(b/319712088): re-enable use_resource_processor use_resource_processor: false, + kotlincflags: [ + "-Xjvm-default=all", + ], } // Build rule for Quickstep app. diff --git a/AndroidManifest-common.xml b/AndroidManifest-common.xml index 80d2eaca23..fe57da11fc 100644 --- a/AndroidManifest-common.xml +++ b/AndroidManifest-common.xml @@ -136,7 +136,7 @@ TODO: Add proper permissions --> diff --git a/src/com/android/launcher3/dagger/LauncherBaseAppComponent.java b/src/com/android/launcher3/dagger/LauncherBaseAppComponent.java index 31d0da08db..f6acda46a1 100644 --- a/src/com/android/launcher3/dagger/LauncherBaseAppComponent.java +++ b/src/com/android/launcher3/dagger/LauncherBaseAppComponent.java @@ -20,6 +20,7 @@ import android.content.Context; import com.android.launcher3.InvariantDeviceProfile; import com.android.launcher3.LauncherPrefs; +import com.android.launcher3.graphics.GridCustomizationsProxy; import com.android.launcher3.graphics.ThemeManager; import com.android.launcher3.icons.LauncherIcons.IconPool; import com.android.launcher3.model.ItemInstallQueue; @@ -75,6 +76,8 @@ public interface LauncherBaseAppComponent { InvariantDeviceProfile getIDP(); IconPool getIconPool(); + GridCustomizationsProxy getGridCustomizationsProxy(); + /** Builder for LauncherBaseAppComponent. */ interface Builder { @BindsInstance Builder appContext(@ApplicationContext Context context); diff --git a/src/com/android/launcher3/graphics/GridCustomizationsProvider.java b/src/com/android/launcher3/graphics/GridCustomizationsProxy.java similarity index 87% rename from src/com/android/launcher3/graphics/GridCustomizationsProvider.java rename to src/com/android/launcher3/graphics/GridCustomizationsProxy.java index 12c65c72cd..01c9d7ec4f 100644 --- a/src/com/android/launcher3/graphics/GridCustomizationsProvider.java +++ b/src/com/android/launcher3/graphics/GridCustomizationsProxy.java @@ -22,7 +22,6 @@ import static com.android.launcher3.util.Executors.UI_HELPER_EXECUTOR; import static java.util.Objects.requireNonNullElse; -import android.content.ContentProvider; import android.content.ContentValues; import android.content.Context; import android.content.pm.PackageManager; @@ -45,9 +44,13 @@ import com.android.launcher3.InvariantDeviceProfile.GridOption; import com.android.launcher3.LauncherAppState; import com.android.launcher3.LauncherModel; import com.android.launcher3.LauncherPrefs; +import com.android.launcher3.dagger.ApplicationContext; +import com.android.launcher3.dagger.LauncherAppSingleton; import com.android.launcher3.model.BgDataModel; import com.android.launcher3.shapes.IconShapeModel; import com.android.launcher3.shapes.ShapesProvider; +import com.android.launcher3.util.ContentProviderProxy.ProxyProvider; +import com.android.launcher3.util.DaggerSingletonTracker; import com.android.launcher3.util.Executors; import com.android.launcher3.util.Preconditions; import com.android.launcher3.util.RunnableList; @@ -62,6 +65,8 @@ import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; +import javax.inject.Inject; + /** * Exposes various launcher grid options and allows the caller to change them. * APIs: @@ -76,7 +81,7 @@ import java.util.concurrent.ExecutionException; * rows: number of rows in the grid * cols: number of columns in the grid * preview_count: number of previews available for this grid option. The preview uri - * looks like /preview// + * looks like /preview/[grid-name]/[preview index starting with 0] * is_default: true if this grid option is currently set to the system * * /get_preview: Open a file stream for the grid preview @@ -85,7 +90,8 @@ import java.util.concurrent.ExecutionException; * shape_key: key of the shape to apply * name: key of the grid to apply */ -public class GridCustomizationsProvider extends ContentProvider { +@LauncherAppSingleton +public class GridCustomizationsProxy implements ProxyProvider { private static final String TAG = "GridCustomizationsProvider"; @@ -132,17 +138,31 @@ public class GridCustomizationsProvider extends ContentProvider { private final Set mActivePreviews = Collections.newSetFromMap(new ConcurrentHashMap<>()); - @Override - public boolean onCreate() { - return true; + private final Context mContext; + private final ThemeManager mThemeManager; + private final LauncherPrefs mPrefs; + private final InvariantDeviceProfile mIdp; + + @Inject + GridCustomizationsProxy( + @ApplicationContext Context context, + ThemeManager themeManager, + LauncherPrefs prefs, + InvariantDeviceProfile idp, + DaggerSingletonTracker lifeCycle + ) { + mContext = context; + mThemeManager = themeManager; + mPrefs = prefs; + mIdp = idp; + lifeCycle.addCloseable(() -> mActivePreviews.forEach(PreviewLifecycleObserver::binderDied)); } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { - Context context = getContext(); String path = uri.getPath(); - if (context == null || path == null) { + if (path == null) { return null; } @@ -151,8 +171,7 @@ public class GridCustomizationsProvider extends ContentProvider { if (Flags.newCustomizationPickerUi()) { MatrixCursor cursor = new MatrixCursor(new String[]{ KEY_SHAPE_KEY, KEY_SHAPE_TITLE, KEY_PATH, KEY_IS_DEFAULT}); - String currentShapePath = - ThemeManager.INSTANCE.get(context).getIconState().getIconMask(); + String currentShapePath = mThemeManager.getIconState().getIconMask(); Optional selectedShape = ShapesProvider.INSTANCE.getIconShapes() .values() .stream() @@ -180,8 +199,7 @@ public class GridCustomizationsProvider extends ContentProvider { MatrixCursor cursor = new MatrixCursor(new String[]{ KEY_NAME, KEY_GRID_TITLE, KEY_ROWS, KEY_COLS, KEY_PREVIEW_COUNT, KEY_IS_DEFAULT, KEY_GRID_ICON_ID}); - InvariantDeviceProfile idp = InvariantDeviceProfile.INSTANCE.get(getContext()); - List gridOptionList = idp.parseAllGridOptions(getContext()); + List gridOptionList = mIdp.parseAllGridOptions(mContext); if (com.android.launcher3.Flags.oneGridSpecs()) { gridOptionList.sort(Comparator .comparingInt((GridOption option) -> option.numColumns) @@ -194,8 +212,8 @@ public class GridCustomizationsProvider extends ContentProvider { .add(KEY_ROWS, gridOption.numRows) .add(KEY_COLS, gridOption.numColumns) .add(KEY_PREVIEW_COUNT, 1) - .add(KEY_IS_DEFAULT, idp.numColumns == gridOption.numColumns - && idp.numRows == gridOption.numRows) + .add(KEY_IS_DEFAULT, mIdp.numColumns == gridOption.numColumns + && mIdp.numRows == gridOption.numRows) .add(KEY_GRID_ICON_ID, gridOption.gridIconId); } return cursor; @@ -203,8 +221,7 @@ public class GridCustomizationsProvider extends ContentProvider { case GET_ICON_THEMED: case ICON_THEMED: { MatrixCursor cursor = new MatrixCursor(new String[]{BOOLEAN_VALUE}); - cursor.newRow().add(BOOLEAN_VALUE, - ThemeManager.INSTANCE.get(getContext()).isMonoThemeEnabled() ? 1 : 0); + cursor.newRow().add(BOOLEAN_VALUE, mThemeManager.isMonoThemeEnabled() ? 1 : 0); return cursor; } default: @@ -212,39 +229,22 @@ public class GridCustomizationsProvider extends ContentProvider { } } - @Override - public String getType(Uri uri) { - return "vnd.android.cursor.dir/launcher_grid"; - } - - @Override - public Uri insert(Uri uri, ContentValues initialValues) { - return null; - } - - @Override - public int delete(Uri uri, String selection, String[] selectionArgs) { - return 0; - } - @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { String path = uri.getPath(); - Context context = getContext(); - if (path == null || context == null) { + if (path == null) { return 0; } switch (path) { case KEY_DEFAULT_GRID: { if (Flags.newCustomizationPickerUi()) { - LauncherPrefs.INSTANCE.get(context).put(PREF_ICON_SHAPE, + mPrefs.put(PREF_ICON_SHAPE, requireNonNullElse(values.getAsString(KEY_SHAPE_KEY), "")); } String gridName = values.getAsString(KEY_NAME); - InvariantDeviceProfile idp = InvariantDeviceProfile.INSTANCE.get(context); // Verify that this is a valid grid option GridOption match = null; - for (GridOption option : idp.parseAllGridOptions(context)) { + for (GridOption option : mIdp.parseAllGridOptions(mContext)) { String name = option.name; if (name != null && name.equals(gridName)) { match = option; @@ -255,23 +255,22 @@ public class GridCustomizationsProvider extends ContentProvider { return 0; } - idp.setCurrentGrid(context, gridName); + mIdp.setCurrentGrid(mContext, gridName); if (Flags.newCustomizationPickerUi()) { try { // Wait for device profile to be fully reloaded and applied to the launcher - loadModelSync(context); + loadModelSync(mContext); } catch (ExecutionException | InterruptedException e) { Log.e(TAG, "Fail to load model", e); } } - context.getContentResolver().notifyChange(uri, null); + mContext.getContentResolver().notifyChange(uri, null); return 1; } case ICON_THEMED: case SET_ICON_THEMED: { - ThemeManager.INSTANCE.get(context) - .setMonoThemeEnabled(values.getAsBoolean(BOOLEAN_VALUE)); - context.getContentResolver().notifyChange(uri, null); + mThemeManager.setMonoThemeEnabled(values.getAsBoolean(BOOLEAN_VALUE)); + mContext.getContentResolver().notifyChange(uri, null); return 1; } default: @@ -298,12 +297,7 @@ public class GridCustomizationsProvider extends ContentProvider { @Override public Bundle call(@NonNull String method, String arg, Bundle extras) { - Context context = getContext(); - if (context == null) { - return null; - } - - if (context.checkPermission("android.permission.BIND_WALLPAPER", + if (mContext.checkPermission("android.permission.BIND_WALLPAPER", Binder.getCallingPid(), Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) { return null; @@ -317,14 +311,10 @@ public class GridCustomizationsProvider extends ContentProvider { } private synchronized Bundle getPreview(Bundle request) { - Context context = getContext(); - if (context == null) { - return null; - } RunnableList lifeCycleTracker = new RunnableList(); try { PreviewSurfaceRenderer renderer = new PreviewSurfaceRenderer( - getContext(), lifeCycleTracker, request); + mContext, lifeCycleTracker, request); PreviewLifecycleObserver observer = new PreviewLifecycleObserver(lifeCycleTracker, renderer); diff --git a/src/com/android/launcher3/graphics/LauncherCustomizationProvider.kt b/src/com/android/launcher3/graphics/LauncherCustomizationProvider.kt new file mode 100644 index 0000000000..c949e2ec17 --- /dev/null +++ b/src/com/android/launcher3/graphics/LauncherCustomizationProvider.kt @@ -0,0 +1,29 @@ +/* + * Copyright (C) 2023 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.launcher3.graphics + +import android.content.Context +import android.net.Uri +import com.android.launcher3.dagger.LauncherComponentProvider.appComponent +import com.android.launcher3.util.ContentProviderProxy + +/** Provider for various Launcher customizations exposed via a ContentProvider API */ +class LauncherCustomizationProvider : ContentProviderProxy() { + + override fun getProxy(ctx: Context): ProxyProvider? = ctx.appComponent.gridCustomizationsProxy + + override fun getType(uri: Uri) = "vnd.android.cursor.dir/launcher_grid" +} diff --git a/src/com/android/launcher3/graphics/PreviewSurfaceRenderer.java b/src/com/android/launcher3/graphics/PreviewSurfaceRenderer.java index f0d670e59a..6fe5804da6 100644 --- a/src/com/android/launcher3/graphics/PreviewSurfaceRenderer.java +++ b/src/com/android/launcher3/graphics/PreviewSurfaceRenderer.java @@ -124,7 +124,7 @@ public class PreviewSurfaceRenderer { if (Flags.newCustomizationPickerUi()) { updateColorOverrides(bundle); } - mHideQsb = bundle.getBoolean(GridCustomizationsProvider.KEY_HIDE_BOTTOM_ROW); + mHideQsb = bundle.getBoolean(GridCustomizationsProxy.KEY_HIDE_BOTTOM_ROW); mHostToken = bundle.getBinder(KEY_HOST_TOKEN); mWidth = bundle.getInt(KEY_VIEW_WIDTH); diff --git a/src/com/android/launcher3/testing/TestInformationProvider.java b/src/com/android/launcher3/testing/TestInformationProvider.java index 17b472a473..4b592e7627 100644 --- a/src/com/android/launcher3/testing/TestInformationProvider.java +++ b/src/com/android/launcher3/testing/TestInformationProvider.java @@ -16,61 +16,40 @@ package com.android.launcher3.testing; -import android.content.ContentProvider; -import android.content.ContentValues; -import android.database.Cursor; -import android.net.Uri; +import android.content.Context; import android.os.Bundle; import android.util.Log; -import com.android.launcher3.Utilities; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; -public class TestInformationProvider extends ContentProvider { +import com.android.launcher3.Utilities; +import com.android.launcher3.util.ContentProviderProxy; + +public class TestInformationProvider extends ContentProviderProxy { private static final String TAG = "TestInformationProvider"; + @Nullable @Override - public boolean onCreate() { - return true; - } - - @Override - public int update(Uri uri, ContentValues contentValues, String s, String[] strings) { - return 0; - } - - @Override - public int delete(Uri uri, String s, String[] strings) { - return 0; - } - - @Override - public Uri insert(Uri uri, ContentValues contentValues) { - return null; - } - - @Override - public String getType(Uri uri) { - return null; - } - - @Override - public Cursor query(Uri uri, String[] strings, String s, String[] strings1, String s1) { - return null; - } - - @Override - public Bundle call(String method, String arg, Bundle extras) { + public ProxyProvider getProxy(@NonNull Context context) { if (Utilities.isRunningInTestHarness()) { - TestInformationHandler handler = TestInformationHandler.newInstance(getContext()); - handler.init(getContext()); + return new ProxyProvider() { + @Nullable + @Override + public Bundle call(@NonNull String method, @Nullable String arg, + @Nullable Bundle extras) { + TestInformationHandler handler = TestInformationHandler.newInstance(context); + handler.init(context); - Bundle response = handler.call(method, arg, extras); - if (response == null) { - Log.e(TAG, "Couldn't handle method: " + method + "; current handler=" - + handler.getClass().getSimpleName()); - } - return response; + Bundle response = handler.call(method, arg, extras); + if (response == null) { + Log.e(TAG, "Couldn't handle method: " + method + "; current handler=" + + handler.getClass().getSimpleName()); + } + return response; + } + }; } return null; } diff --git a/src/com/android/launcher3/util/ContentProviderProxy.kt b/src/com/android/launcher3/util/ContentProviderProxy.kt new file mode 100644 index 0000000000..db693db7ff --- /dev/null +++ b/src/com/android/launcher3/util/ContentProviderProxy.kt @@ -0,0 +1,86 @@ +/* + * 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.launcher3.util + +import android.content.ContentProvider +import android.content.ContentValues +import android.content.Context +import android.database.Cursor +import android.net.Uri +import android.os.Bundle + +/** Wrapper around [ContentProvider] which allows delegating all calls to an interface */ +abstract class ContentProviderProxy : ContentProvider() { + + override fun onCreate() = true + + override fun delete(uri: Uri, selection: String?, selectionArgs: Array?): Int = + checkGetProxy()?.delete(uri, selection, selectionArgs) ?: 0 + + /** Do not route this call through proxy as it doesn't generally require initializing objects */ + override fun getType(uri: Uri): String? = null + + override fun insert(uri: Uri, values: ContentValues?): Uri? = + checkGetProxy()?.insert(uri, values) + + override fun query( + uri: Uri, + projection: Array?, + selection: String?, + selectionArgs: Array?, + sortOrder: String?, + ): Cursor? = checkGetProxy()?.query(uri, projection, selection, selectionArgs, sortOrder) + + override fun update( + uri: Uri, + values: ContentValues?, + selection: String?, + selectionArgs: Array?, + ): Int = checkGetProxy()?.update(uri, values, selection, selectionArgs) ?: 0 + + override fun call(method: String, arg: String?, extras: Bundle?): Bundle? = + checkGetProxy()?.call(method, arg, extras) + + private fun checkGetProxy(): ProxyProvider? = context?.let { getProxy(it) } + + abstract fun getProxy(ctx: Context): ProxyProvider? + + /** Interface for handling the actual content provider calls */ + interface ProxyProvider { + + fun delete(uri: Uri, selection: String?, selectionArgs: Array?): Int = 0 + + fun insert(uri: Uri, values: ContentValues?): Uri? = null + + fun query( + uri: Uri, + projection: Array?, + selection: String?, + selectionArgs: Array?, + sortOrder: String?, + ): Cursor? = null + + fun update( + uri: Uri, + values: ContentValues?, + selection: String?, + selectionArgs: Array?, + ): Int = 0 + + fun call(method: String, arg: String?, extras: Bundle?): Bundle? = null + } +} From b8db0313bcca45296d59a6a260723598f068501b Mon Sep 17 00:00:00 2001 From: Vania Desmonda Date: Thu, 20 Feb 2025 18:18:14 +0000 Subject: [PATCH 074/153] Update usage of flags to dev options. Bug: 361366053 Bug: 345296916 Bug: 381866902 Flag: EXEMPT refactoring flag Test: presubmits Change-Id: I7653ca4e7a2476402cfccbbc72194b14b10cb93f --- .../com/android/launcher3/taskbar/TaskbarActivityContext.java | 3 +-- .../touchcontrollers/NoButtonQuickSwitchTouchController.java | 4 ++-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/quickstep/src/com/android/launcher3/taskbar/TaskbarActivityContext.java b/quickstep/src/com/android/launcher3/taskbar/TaskbarActivityContext.java index d1e63f3b14..54e4344b7c 100644 --- a/quickstep/src/com/android/launcher3/taskbar/TaskbarActivityContext.java +++ b/quickstep/src/com/android/launcher3/taskbar/TaskbarActivityContext.java @@ -46,7 +46,6 @@ import static com.android.launcher3.util.Executors.UI_HELPER_EXECUTOR; import static com.android.quickstep.util.AnimUtils.completeRunnableListCallback; import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_NOTIFICATION_PANEL_VISIBLE; import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_VOICE_INTERACTION_WINDOW_SHOWING; -import static com.android.window.flags.Flags.enableStartLaunchTransitionFromTaskbarBugfix; import static com.android.wm.shell.Flags.enableBubbleBar; import static com.android.wm.shell.Flags.enableBubbleBarOnPhones; import static com.android.wm.shell.Flags.enableTinyTaskbar; @@ -1710,7 +1709,7 @@ public class TaskbarActivityContext extends BaseTaskbarContext { } // There is no task associated with this launch - launch a new task through an intent ActivityOptionsWrapper opts = getActivityLaunchDesktopOptions(); - if (enableStartLaunchTransitionFromTaskbarBugfix()) { + if (DesktopModeFlags.ENABLE_START_LAUNCH_TRANSITION_FROM_TASKBAR_BUGFIX.isTrue()) { mSysUiProxy.startLaunchIntentTransition(intent, opts.options.toBundle(), displayId); } else { startActivity(intent, opts.options.toBundle()); diff --git a/quickstep/src/com/android/launcher3/uioverrides/touchcontrollers/NoButtonQuickSwitchTouchController.java b/quickstep/src/com/android/launcher3/uioverrides/touchcontrollers/NoButtonQuickSwitchTouchController.java index 05d12c31af..58b274a47c 100644 --- a/quickstep/src/com/android/launcher3/uioverrides/touchcontrollers/NoButtonQuickSwitchTouchController.java +++ b/quickstep/src/com/android/launcher3/uioverrides/touchcontrollers/NoButtonQuickSwitchTouchController.java @@ -64,6 +64,7 @@ import android.animation.ValueAnimator; import android.graphics.PointF; import android.view.MotionEvent; import android.view.animation.Interpolator; +import android.window.DesktopModeFlags; import com.android.internal.jank.Cuj; import com.android.launcher3.LauncherState; @@ -86,7 +87,6 @@ import com.android.quickstep.util.MotionPauseDetector; import com.android.quickstep.util.WorkspaceRevealAnim; import com.android.quickstep.views.RecentsView; import com.android.systemui.shared.system.InteractionJankMonitorWrapper; -import com.android.window.flags.Flags; import com.android.wm.shell.shared.desktopmode.DesktopModeStatus; /** @@ -188,7 +188,7 @@ public class NoButtonQuickSwitchTouchController implements TouchController, } if (DesktopModeStatus.canEnterDesktopMode(mLauncher) //TODO(b/345296916): replace with dev option once in teamfood - && Flags.enableQuickswitchDesktopSplitBugfix() + && DesktopModeFlags.ENABLE_QUICKSWITCH_DESKTOP_SPLIT_BUGFIX.isTrue() && mRecentsView.getNonDesktopTaskViewCount() < 1) { return false; } From db724a010ce572701884bad15a7cf125877b2c23 Mon Sep 17 00:00:00 2001 From: Sunny Goyal Date: Thu, 20 Feb 2025 12:26:07 -0800 Subject: [PATCH 075/153] Removing temporary debug tracing Bug: 378167329 Flag: EXEMPT bugfix Test: Presubmit Change-Id: I06ed0d96a83c13b1bce9aff8e2e21fa1510bc4c2 --- tests/src/com/android/launcher3/allapps/KeyboardFocusTest.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/tests/src/com/android/launcher3/allapps/KeyboardFocusTest.java b/tests/src/com/android/launcher3/allapps/KeyboardFocusTest.java index 1e21ee5b3a..44df5b8e0a 100644 --- a/tests/src/com/android/launcher3/allapps/KeyboardFocusTest.java +++ b/tests/src/com/android/launcher3/allapps/KeyboardFocusTest.java @@ -23,7 +23,6 @@ import androidx.test.filters.SmallTest; import com.android.launcher3.Launcher; import com.android.launcher3.LauncherState; import com.android.launcher3.util.BaseLauncherActivityTest; -import com.android.launcher3.util.rule.ScreenRecordRule.ScreenRecord; import com.android.launcher3.views.ActivityContext; import org.junit.Test; @@ -64,7 +63,6 @@ public class KeyboardFocusTest extends BaseLauncherActivityTest { } @Test - @ScreenRecord //b/378167329 public void testAllAppsExitSearchAndFocusSearchResults() { loadLauncherSync(); goToState(LauncherState.ALL_APPS); From b392f61ced6f7fa6890e8ae827eeeda59536dd2b Mon Sep 17 00:00:00 2001 From: Jeremy Sim Date: Wed, 19 Feb 2025 15:38:27 -0800 Subject: [PATCH 076/153] Refactor SplitBounds to always use creation-time measurements In flexible split ratios like 90:10 and 10:90, we hide the Overview icon of the smaller app completely (ag/30949010). However, there was an unintentional side effect where one of the icons would disappear when rotating the display. This happened (basically) because SplitBounds is not recalculated on device rotation, so fields like leftTaskPercent and topTaskPercent should not be used directly when the rotation state is not known. I added an API to SplitBounds that hopefully makes it harder to write bugs like this in the future. Fixes: 395783367 Flag: com.android.wm.shell.enable_flexible_two_app_split Test: Icons do not disappear on rotation. When app chip menus are enabled, the (existing) correct behavior is not changed. Change-Id: I2c1b38f4bd9a76dfb127b7bbf230897d747d3c49 --- .../taskbar/KeyboardQuickSwitchTaskView.java | 3 +- .../orientation/LandscapePagedViewHandler.kt | 30 +++----------- .../orientation/PortraitPagedViewHandler.java | 34 +++++---------- .../orientation/SeascapePagedViewHandler.kt | 24 ++--------- .../quickstep/views/DigitalWellBeingToast.kt | 4 +- .../quickstep/views/GroupedTaskView.kt | 16 +++----- .../util/SplitConfigurationOptions.java | 41 +++++++++++++++++-- 7 files changed, 65 insertions(+), 87 deletions(-) diff --git a/quickstep/src/com/android/launcher3/taskbar/KeyboardQuickSwitchTaskView.java b/quickstep/src/com/android/launcher3/taskbar/KeyboardQuickSwitchTaskView.java index bf5c0c862f..f80dc909f8 100644 --- a/quickstep/src/com/android/launcher3/taskbar/KeyboardQuickSwitchTaskView.java +++ b/quickstep/src/com/android/launcher3/taskbar/KeyboardQuickSwitchTaskView.java @@ -197,8 +197,7 @@ public class KeyboardQuickSwitchTaskView extends ConstraintLayout { final boolean isLeftRightSplit = !splitBounds.appsStackedVertically; - final float leftOrTopTaskPercent = isLeftRightSplit - ? splitBounds.leftTaskPercent : splitBounds.topTaskPercent; + final float leftOrTopTaskPercent = splitBounds.getLeftTopTaskPercent(); ConstraintLayout.LayoutParams leftTopParams = (ConstraintLayout.LayoutParams) mThumbnailView1.getLayoutParams(); diff --git a/quickstep/src/com/android/quickstep/orientation/LandscapePagedViewHandler.kt b/quickstep/src/com/android/quickstep/orientation/LandscapePagedViewHandler.kt index e72ccbfb7b..59ea8fa98a 100644 --- a/quickstep/src/com/android/quickstep/orientation/LandscapePagedViewHandler.kt +++ b/quickstep/src/com/android/quickstep/orientation/LandscapePagedViewHandler.kt @@ -285,11 +285,7 @@ open class LandscapePagedViewHandler : RecentsPagedOrientationHandler { translationY = snapshotParams.topMargin.toFloat() } else { val topLeftTaskPlusDividerPercent = - if (splitBounds.appsStackedVertically) { - splitBounds.topTaskPercent + splitBounds.dividerHeightPercent - } else { - splitBounds.leftTaskPercent + splitBounds.dividerWidthPercent - } + splitBounds.leftTopTaskPercent + splitBounds.dividerPercent translationY = snapshotParams.topMargin + (taskViewHeight - snapshotParams.topMargin) * topLeftTaskPlusDividerPercent @@ -440,15 +436,8 @@ open class LandscapePagedViewHandler : RecentsPagedOrientationHandler { splitInfo: SplitBounds, desiredStagePosition: Int ) { - val topLeftTaskPercent: Float - val dividerBarPercent: Float - if (splitInfo.appsStackedVertically) { - topLeftTaskPercent = splitInfo.topTaskPercent - dividerBarPercent = splitInfo.dividerHeightPercent - } else { - topLeftTaskPercent = splitInfo.leftTaskPercent - dividerBarPercent = splitInfo.dividerWidthPercent - } + val topLeftTaskPercent = splitInfo.leftTopTaskPercent + val dividerBarPercent = splitInfo.dividerPercent if (desiredStagePosition == STAGE_POSITION_TOP_OR_LEFT) { outRect.bottom = outRect.top + (outRect.height() * topLeftTaskPercent).toInt() @@ -510,12 +499,7 @@ open class LandscapePagedViewHandler : RecentsPagedOrientationHandler { val totalThumbnailHeight = parentHeight - spaceAboveSnapshot val dividerBar = getDividerBarSize(totalThumbnailHeight, splitBoundsConfig) - val taskPercent = - if (splitBoundsConfig.appsStackedVertically) { - splitBoundsConfig.topTaskPercent - } else { - splitBoundsConfig.leftTaskPercent - } + val taskPercent = splitBoundsConfig.leftTopTaskPercent val firstTaskViewSize = Point(parentWidth, (totalThumbnailHeight * taskPercent).toInt()) val secondTaskViewSize = Point(parentWidth, totalThumbnailHeight - firstTaskViewSize.y - dividerBar) @@ -715,11 +699,7 @@ open class LandscapePagedViewHandler : RecentsPagedOrientationHandler { * @return The divider size for the group task view. */ protected fun getDividerBarSize(totalThumbnailHeight: Int, splitConfig: SplitBounds): Int { - return Math.round( - totalThumbnailHeight * - if (splitConfig.appsStackedVertically) splitConfig.dividerHeightPercent - else splitConfig.dividerWidthPercent - ) + return Math.round(totalThumbnailHeight * splitConfig.dividerPercent) } /** diff --git a/quickstep/src/com/android/quickstep/orientation/PortraitPagedViewHandler.java b/quickstep/src/com/android/quickstep/orientation/PortraitPagedViewHandler.java index c1e1c2b115..d9ad7cec3b 100644 --- a/quickstep/src/com/android/quickstep/orientation/PortraitPagedViewHandler.java +++ b/quickstep/src/com/android/quickstep/orientation/PortraitPagedViewHandler.java @@ -271,12 +271,8 @@ public class PortraitPagedViewHandler extends DefaultPagedViewHandler implements if (splitBounds != null) { if (deviceProfile.isLeftRightSplit) { if (desiredTaskId == splitBounds.rightBottomTaskId) { - float leftTopTaskPercent = splitBounds.appsStackedVertically - ? splitBounds.topTaskPercent - : splitBounds.leftTaskPercent; - float dividerThicknessPercent = splitBounds.appsStackedVertically - ? splitBounds.dividerHeightPercent - : splitBounds.dividerWidthPercent; + float leftTopTaskPercent = splitBounds.getLeftTopTaskPercent(); + float dividerThicknessPercent = splitBounds.getDividerPercent(); translationX = ((taskViewWidth * leftTopTaskPercent) + (taskViewWidth * dividerThicknessPercent)); } @@ -285,9 +281,9 @@ public class PortraitPagedViewHandler extends DefaultPagedViewHandler implements FrameLayout.LayoutParams snapshotParams = (FrameLayout.LayoutParams) thumbnailViews[0] .getLayoutParams(); - float bottomRightTaskPlusDividerPercent = splitBounds.appsStackedVertically - ? (1f - splitBounds.topTaskPercent) - : (1f - splitBounds.leftTaskPercent); + float bottomRightTaskPlusDividerPercent = + splitBounds.getRightBottomTaskPercent() + + splitBounds.getDividerPercent(); translationY = -((taskViewHeight - snapshotParams.topMargin) * bottomRightTaskPlusDividerPercent); } @@ -506,12 +502,8 @@ public class PortraitPagedViewHandler extends DefaultPagedViewHandler implements @Override public void setSplitTaskSwipeRect(DeviceProfile dp, Rect outRect, SplitBounds splitInfo, int desiredStagePosition) { - float topLeftTaskPercent = splitInfo.appsStackedVertically - ? splitInfo.topTaskPercent - : splitInfo.leftTaskPercent; - float dividerBarPercent = splitInfo.appsStackedVertically - ? splitInfo.dividerHeightPercent - : splitInfo.dividerWidthPercent; + float topLeftTaskPercent = splitInfo.getLeftTopTaskPercent(); + float dividerBarPercent = splitInfo.getDividerPercent(); int taskbarHeight = dp.isTransientTaskbar ? 0 : dp.taskbarHeight; float scale = (float) outRect.height() / (dp.availableHeightPx - taskbarHeight); @@ -559,9 +551,7 @@ public class PortraitPagedViewHandler extends DefaultPagedViewHandler implements primaryParams.topMargin = spaceAboveSnapshot; int totalThumbnailHeight = parentHeight - spaceAboveSnapshot; - float dividerScale = splitBoundsConfig.appsStackedVertically - ? splitBoundsConfig.dividerHeightPercent - : splitBoundsConfig.dividerWidthPercent; + float dividerScale = splitBoundsConfig.getDividerPercent(); Pair taskViewSizes = getGroupedTaskViewSizes(dp, splitBoundsConfig, parentWidth, parentHeight); if (!inSplitSelection) { @@ -610,12 +600,8 @@ public class PortraitPagedViewHandler extends DefaultPagedViewHandler implements int parentHeight) { int spaceAboveSnapshot = dp.overviewTaskThumbnailTopMarginPx; int totalThumbnailHeight = parentHeight - spaceAboveSnapshot; - float dividerScale = splitBoundsConfig.appsStackedVertically - ? splitBoundsConfig.dividerHeightPercent - : splitBoundsConfig.dividerWidthPercent; - float taskPercent = splitBoundsConfig.appsStackedVertically - ? splitBoundsConfig.topTaskPercent - : splitBoundsConfig.leftTaskPercent; + float dividerScale = splitBoundsConfig.getDividerPercent(); + float taskPercent = splitBoundsConfig.getLeftTopTaskPercent(); Point firstTaskViewSize = new Point(); Point secondTaskViewSize = new Point(); diff --git a/quickstep/src/com/android/quickstep/orientation/SeascapePagedViewHandler.kt b/quickstep/src/com/android/quickstep/orientation/SeascapePagedViewHandler.kt index 3fb4f54ae5..9bfa2bf722 100644 --- a/quickstep/src/com/android/quickstep/orientation/SeascapePagedViewHandler.kt +++ b/quickstep/src/com/android/quickstep/orientation/SeascapePagedViewHandler.kt @@ -106,15 +106,8 @@ class SeascapePagedViewHandler : LandscapePagedViewHandler() { splitInfo: SplitBounds, desiredStagePosition: Int ) { - val topLeftTaskPercent: Float - val dividerBarPercent: Float - if (splitInfo.appsStackedVertically) { - topLeftTaskPercent = splitInfo.topTaskPercent - dividerBarPercent = splitInfo.dividerHeightPercent - } else { - topLeftTaskPercent = splitInfo.leftTaskPercent - dividerBarPercent = splitInfo.dividerWidthPercent - } + val topLeftTaskPercent = splitInfo.leftTopTaskPercent + val dividerBarPercent = splitInfo.dividerPercent // In seascape, the primary thumbnail is counterintuitively placed at the physical bottom of // the screen. This is to preserve consistency when the user rotates: From the user's POV, @@ -166,11 +159,7 @@ class SeascapePagedViewHandler : LandscapePagedViewHandler() { } else { if (desiredTaskId == splitBounds.leftTopTaskId) { val bottomRightTaskPlusDividerPercent = - if (splitBounds.appsStackedVertically) { - 1f - splitBounds.topTaskPercent - } else { - 1f - splitBounds.leftTaskPercent - } + splitBounds.rightBottomTaskPercent + splitBounds.dividerPercent translationY = banner.height - (taskViewHeight - snapshotParams.topMargin) * @@ -331,12 +320,7 @@ class SeascapePagedViewHandler : LandscapePagedViewHandler() { val totalThumbnailHeight = parentHeight - spaceAboveSnapshot val dividerBar = getDividerBarSize(totalThumbnailHeight, splitBoundsConfig) - val taskPercent = - if (splitBoundsConfig.appsStackedVertically) { - splitBoundsConfig.topTaskPercent - } else { - splitBoundsConfig.leftTaskPercent - } + val taskPercent = splitBoundsConfig.leftTopTaskPercent val firstTaskViewSize = Point(parentWidth, (totalThumbnailHeight * taskPercent).toInt()) val secondTaskViewSize = Point(parentWidth, totalThumbnailHeight - firstTaskViewSize.y - dividerBar) diff --git a/quickstep/src/com/android/quickstep/views/DigitalWellBeingToast.kt b/quickstep/src/com/android/quickstep/views/DigitalWellBeingToast.kt index c07b7fbfb1..5c4a35da63 100644 --- a/quickstep/src/com/android/quickstep/views/DigitalWellBeingToast.kt +++ b/quickstep/src/com/android/quickstep/views/DigitalWellBeingToast.kt @@ -189,11 +189,11 @@ constructor( SplitBannerConfig.SPLIT_GRID_BANNER_LARGE // For landscape grid, for 30% width we only show icon, otherwise show icon and time task.key.id == splitBounds.leftTopTaskId -> - if (splitBounds.leftTaskPercent < THRESHOLD_LEFT_ICON_ONLY) + if (splitBounds.leftTopTaskPercent < THRESHOLD_LEFT_ICON_ONLY) SplitBannerConfig.SPLIT_GRID_BANNER_SMALL else SplitBannerConfig.SPLIT_GRID_BANNER_LARGE else -> - if (splitBounds.leftTaskPercent > THRESHOLD_RIGHT_ICON_ONLY) + if (splitBounds.leftTopTaskPercent > THRESHOLD_RIGHT_ICON_ONLY) SplitBannerConfig.SPLIT_GRID_BANNER_SMALL else SplitBannerConfig.SPLIT_GRID_BANNER_LARGE } diff --git a/quickstep/src/com/android/quickstep/views/GroupedTaskView.kt b/quickstep/src/com/android/quickstep/views/GroupedTaskView.kt index 2abfb13abd..25011d784e 100644 --- a/quickstep/src/com/android/quickstep/views/GroupedTaskView.kt +++ b/quickstep/src/com/android/quickstep/views/GroupedTaskView.kt @@ -189,16 +189,12 @@ class GroupedTaskView @JvmOverloads constructor(context: Context, attrs: Attribu val inSplitSelection = getThisTaskCurrentlyInSplitSelection() != INVALID_TASK_ID if (enableFlexibleTwoAppSplit()) { - val topLeftTaskPercent = - if (deviceProfile.isLeftRightSplit) splitBoundsConfig.leftTaskPercent - else splitBoundsConfig.topTaskPercent - val bottomRightTaskPercent = 1 - topLeftTaskPercent - leftTopTaskContainer.iconView.setFlexSplitAlpha( - if (topLeftTaskPercent < MINIMUM_RATIO_TO_SHOW_ICON) 0f else 1f - ) - rightBottomTaskContainer.iconView.setFlexSplitAlpha( - if (bottomRightTaskPercent < MINIMUM_RATIO_TO_SHOW_ICON) 0f else 1f - ) + val topLeftTaskPercent = splitBoundsConfig.leftTopTaskPercent + val bottomRightTaskPercent = splitBoundsConfig.rightBottomTaskPercent + val hideTopLeftIcon = topLeftTaskPercent < MINIMUM_RATIO_TO_SHOW_ICON + val hideBottomRightIcon = bottomRightTaskPercent < MINIMUM_RATIO_TO_SHOW_ICON + leftTopTaskContainer.iconView.setFlexSplitAlpha(if (hideTopLeftIcon) 0f else 1f) + rightBottomTaskContainer.iconView.setFlexSplitAlpha(if (hideBottomRightIcon) 0f else 1f) } if (enableOverviewIconMenu()) { diff --git a/src/com/android/launcher3/util/SplitConfigurationOptions.java b/src/com/android/launcher3/util/SplitConfigurationOptions.java index 44a7c6fa74..e1ef77a00a 100644 --- a/src/com/android/launcher3/util/SplitConfigurationOptions.java +++ b/src/com/android/launcher3/util/SplitConfigurationOptions.java @@ -127,10 +127,10 @@ public final class SplitConfigurationOptions { /** This rect represents the actual gap between the two apps */ public final Rect visualDividerBounds; // This class is orientation-agnostic, so we compute both for later use - public final float topTaskPercent; - public final float leftTaskPercent; - public final float dividerWidthPercent; - public final float dividerHeightPercent; + private final float topTaskPercent; + private final float leftTaskPercent; + private final float dividerWidthPercent; + private final float dividerHeightPercent; public final int snapPosition; /** @@ -190,6 +190,39 @@ public final class SplitConfigurationOptions { dividerHeightPercent = visualDividerBounds.height() / totalHeight; } + /** + * Returns the percentage size of the left/top task (compared to the full width/height of + * the split pair). E.g. if the left task is 4 units wide, the divider is 2 units, and the + * right task is 4 units, this method will return 0.4f. + */ + public float getLeftTopTaskPercent() { + // topTaskPercent and leftTaskPercent are defined at creation time, and are not updated + // on device rotate, so we have to check appsStackedVertically to return the right + // creation-time measurements. + return appsStackedVertically ? topTaskPercent : leftTaskPercent; + } + + /** + * Returns the percentage size of the divider's thickness (compared to the full width/height + * of the split pair). E.g. if the left task is 4 units wide, the divider is 2 units, and + * the right task is 4 units, this method will return 0.2f. + */ + public float getDividerPercent() { + // dividerHeightPercent and dividerWidthPercent are defined at creation time, and are + // not updated on device rotate, so we have to check appsStackedVertically to return + // the right creation-time measurements. + return appsStackedVertically ? dividerHeightPercent : dividerWidthPercent; + } + + /** + * Returns the percentage size of the right/bottom task (compared to the full width/height + * of the split pair). E.g. if the left task is 4 units wide, the divider is 2 units, and + * the right task is 4 units, this method will return 0.4f. + */ + public float getRightBottomTaskPercent() { + return 1 - (getLeftTopTaskPercent() + getDividerPercent()); + } + @Override public String toString() { return "LeftTop: " + leftTopBounds + ", taskId: " + leftTopTaskId + "\n" From c0fda71c36051ffd2a2239ad212eef0a8bde68d2 Mon Sep 17 00:00:00 2001 From: Charlie Anderson Date: Thu, 20 Feb 2025 17:18:14 +0000 Subject: [PATCH 077/153] Expose icon scale to properly shape themed icons Bug: 394902299 Test: tested with themed/forced-themed icons on and off Flag: com.android.launcher3.enable_launcher_icon_shapes Change-Id: I5b189b8dcfefe195e42b8cfad1bda9e18fd80a29 --- src/com/android/launcher3/icons/LauncherIcons.kt | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/com/android/launcher3/icons/LauncherIcons.kt b/src/com/android/launcher3/icons/LauncherIcons.kt index 6c018e87eb..29c0de1e5a 100644 --- a/src/com/android/launcher3/icons/LauncherIcons.kt +++ b/src/com/android/launcher3/icons/LauncherIcons.kt @@ -66,11 +66,16 @@ internal constructor( return userCache.getUserInfo(user) } - public override fun getShapePath(drawable: AdaptiveIconDrawable, iconBounds: Rect): Path { - if (!Flags.enableLauncherIconShapes()) return drawable.iconMask + override fun getShapePath(drawable: AdaptiveIconDrawable, iconBounds: Rect): Path { + if (!Flags.enableLauncherIconShapes()) return super.getShapePath(drawable, iconBounds) return themeManager.iconShape.getPath(iconBounds) } + override fun getIconScale(): Float { + if (!Flags.enableLauncherIconShapes()) return super.getIconScale() + return themeManager.iconState.iconScale + } + override fun drawAdaptiveIcon( canvas: Canvas, drawable: AdaptiveIconDrawable, From 57794d10257cc38b390035a05c0b8f41b112b2f8 Mon Sep 17 00:00:00 2001 From: Saumya Prakash Date: Thu, 20 Feb 2025 21:54:25 +0000 Subject: [PATCH 078/153] Add developer option to launch gesture nav tutorial This change allows you to start the full, continuous gesture navigation tutorial by tapping the "Launch Full Gesture Tutorial" option in launcher developer settings. Fix: 398018882 Test: Go to developer settings and launch tutorial. It should be continuous and automatically move on to each gesture. Flag: EXEMPT bugfix Change-Id: I5da176e13b4403e1748b9ccba74b24145dafed2c --- .../launcher3/uioverrides/flags/DevOptionsUiHelper.kt | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/quickstep/src/com/android/launcher3/uioverrides/flags/DevOptionsUiHelper.kt b/quickstep/src/com/android/launcher3/uioverrides/flags/DevOptionsUiHelper.kt index 7c09e9a8ec..0d2cfbf028 100644 --- a/quickstep/src/com/android/launcher3/uioverrides/flags/DevOptionsUiHelper.kt +++ b/quickstep/src/com/android/launcher3/uioverrides/flags/DevOptionsUiHelper.kt @@ -315,6 +315,12 @@ class DevOptionsUiHelper(c: Context, attr: AttributeSet?) : PreferenceGroup(c, a intent = Intent(launchSandboxIntent).putExtra("use_tutorial_menu", true) } ) + addPreference( + Preference(context).apply { + title = "Launch Full Gesture Tutorial" + intent = Intent(launchSandboxIntent).putExtra("use_tutorial_menu", false) + } + ) addPreference( Preference(context).apply { title = "Launch Back Tutorial" From f6efa25a496444249c41e7d9c81ebf0a71c03a46 Mon Sep 17 00:00:00 2001 From: Shamali P Date: Thu, 20 Feb 2025 18:33:25 +0000 Subject: [PATCH 079/153] Update widgetsModel to return pickable vs all widgets separately. Earlier wallpaper preview was reading widgets that were eligible for displaying in picker, which means widgets that are marked as hidden in picker wouldn't show up in wallpaper preview. This fix updates widgets model to maintain map of all widgets (instead of just pickable widgets like before), so that the existing `getWidgetsByComponentKey` function used by wallpaper preview can see all widgets. And, updates picker specific methods to use separate functions (suffixed `forPicker` that filter out picker ineligible widgets when read by picker code). Bug: 385695615 Test: WidgetsModelTest, WidgetsPredictionUpdateTaskTest and demo Flag: EXEMPT BUGFIX Change-Id: I59efe38be0ce1f8a956ba4be42fb6e8b48b5d323 --- .../launcher3/WidgetPickerActivity.java | 5 +- .../model/WidgetsPredictionUpdateTask.java | 2 +- .../WidgetsPredicationUpdateTaskTest.java | 35 +++++++++++- .../launcher3/model/BaseLauncherBinder.java | 2 +- .../launcher3/model/ModelTaskController.kt | 2 +- .../android/launcher3/model/WidgetsModel.java | 55 ++++++++++++++++--- .../launcher3/model/WidgetsModelTest.kt | 50 +++++++++++++++-- .../android/launcher3/util/WidgetUtils.java | 20 ++++++- 8 files changed, 151 insertions(+), 20 deletions(-) diff --git a/quickstep/src/com/android/launcher3/WidgetPickerActivity.java b/quickstep/src/com/android/launcher3/WidgetPickerActivity.java index 1cf7dda3af..f992913cde 100644 --- a/quickstep/src/com/android/launcher3/WidgetPickerActivity.java +++ b/quickstep/src/com/android/launcher3/WidgetPickerActivity.java @@ -322,13 +322,14 @@ public class WidgetPickerActivity extends BaseActivity { stringCache.loadStrings(this); bindStringCache(stringCache); - bindWidgets(mModel.getWidgetsByPackageItem(), mModel.getDefaultWidgetsFilter()); + bindWidgets(mModel.getWidgetsByPackageItemForPicker(), + mModel.getDefaultWidgetsFilter()); // Open sheet once widgets are available, so that it doesn't interrupt the open // animation. openWidgetsSheet(); if (mUiSurface != null) { mWidgetPredictionsRequester = new WidgetPredictionsRequester(app.getContext(), - mUiSurface, mModel.getWidgetsByComponentKey()); + mUiSurface, mModel.getWidgetsByComponentKeyForPicker()); mWidgetPredictionsRequester.request(mAddedWidgets, this::bindRecommendedWidgets); } }); diff --git a/quickstep/src/com/android/launcher3/model/WidgetsPredictionUpdateTask.java b/quickstep/src/com/android/launcher3/model/WidgetsPredictionUpdateTask.java index 40e1c10d1c..9626a61e80 100644 --- a/quickstep/src/com/android/launcher3/model/WidgetsPredictionUpdateTask.java +++ b/quickstep/src/com/android/launcher3/model/WidgetsPredictionUpdateTask.java @@ -79,7 +79,7 @@ public final class WidgetsPredictionUpdateTask implements ModelUpdateTask { // Widgets (excluding shortcuts & already added widgets) that belong to apps eligible for // being in predictions. Map allEligibleWidgets = - dataModel.widgetsModel.getWidgetsByComponentKey() + dataModel.widgetsModel.getWidgetsByComponentKeyForPicker() .entrySet() .stream() .filter(entry -> entry.getValue().widgetInfo != null diff --git a/quickstep/tests/src/com/android/launcher3/model/WidgetsPredicationUpdateTaskTest.java b/quickstep/tests/src/com/android/launcher3/model/WidgetsPredicationUpdateTaskTest.java index fa2eb1ee14..d52d0548f9 100644 --- a/quickstep/tests/src/com/android/launcher3/model/WidgetsPredicationUpdateTaskTest.java +++ b/quickstep/tests/src/com/android/launcher3/model/WidgetsPredicationUpdateTaskTest.java @@ -91,6 +91,7 @@ public final class WidgetsPredicationUpdateTaskTest { private AppWidgetProviderInfo mApp4Provider1; private AppWidgetProviderInfo mApp4Provider2; private AppWidgetProviderInfo mApp5Provider1; + private AppWidgetProviderInfo mApp6PinOnlyProvider1; private List allWidgets; private FakeBgDataModelCallback mCallback = new FakeBgDataModelCallback(); @@ -117,8 +118,14 @@ public final class WidgetsPredicationUpdateTaskTest { ComponentName.createRelative("app4", ".provider2")); mApp5Provider1 = createAppWidgetProviderInfo( ComponentName.createRelative("app5", "provider1")); + mApp6PinOnlyProvider1 = createAppWidgetProviderInfo( + ComponentName.createRelative("app6", "provider1"), + /*hideFromPicker=*/ true + ); + + allWidgets = Arrays.asList(mApp1Provider1, mApp1Provider2, mApp2Provider1, - mApp4Provider1, mApp4Provider2, mApp5Provider1); + mApp4Provider1, mApp4Provider2, mApp5Provider1, mApp6PinOnlyProvider1); mLauncherApps = mModelHelper.sandboxContext.spyService(LauncherApps.class); doAnswer(i -> { @@ -270,6 +277,32 @@ public final class WidgetsPredicationUpdateTaskTest { }); } + @Test + public void widgetsRecommendations_excludesWidgetsHiddenForPicker() { + runOnExecutorSync(MODEL_EXECUTOR, () -> { + + // Not installed widget - hence eligible + AppTarget widget1 = new AppTarget(new AppTargetId("app1"), "app1", "provider1", + mUserHandle); + // Provider marked as hidden from picker - hence not eligible + AppTarget widget6 = new AppTarget(new AppTargetId("app6"), "app6", "provider1", + mUserHandle); + + mCallback.mRecommendedWidgets = null; + mModelHelper.getModel().enqueueModelUpdateTask( + newWidgetsPredicationTask(List.of(widget1, widget6))); + runOnExecutorSync(MAIN_EXECUTOR, () -> { }); + + // Only widget 1 (and no widget 6 as its meant to be hidden from picker). + List recommendedWidgets = mCallback.mRecommendedWidgets.items + .stream() + .map(itemInfo -> (PendingAddWidgetInfo) itemInfo) + .collect(Collectors.toList()); + assertThat(recommendedWidgets).hasSize(1); + assertThat(recommendedWidgets.get(0).componentName.getPackageName()).isEqualTo("app1"); + }); + } + private void assertWidgetInfo( LauncherAppWidgetProviderInfo actual, AppWidgetProviderInfo expected) { assertThat(actual.provider).isEqualTo(expected.provider); diff --git a/src/com/android/launcher3/model/BaseLauncherBinder.java b/src/com/android/launcher3/model/BaseLauncherBinder.java index 003bef3311..3ee8b87db0 100644 --- a/src/com/android/launcher3/model/BaseLauncherBinder.java +++ b/src/com/android/launcher3/model/BaseLauncherBinder.java @@ -167,7 +167,7 @@ public class BaseLauncherBinder { return; } Map> - widgetsByPackageItem = mBgDataModel.widgetsModel.getWidgetsByPackageItem(); + widgetsByPackageItem = mBgDataModel.widgetsModel.getWidgetsByPackageItemForPicker(); List widgets = new WidgetsListBaseEntriesBuilder(mApp.getContext()) .build(widgetsByPackageItem); Predicate filter = mBgDataModel.widgetsModel.getDefaultWidgetsFilter(); diff --git a/src/com/android/launcher3/model/ModelTaskController.kt b/src/com/android/launcher3/model/ModelTaskController.kt index 40ea17d437..6e3e35ea1b 100644 --- a/src/com/android/launcher3/model/ModelTaskController.kt +++ b/src/com/android/launcher3/model/ModelTaskController.kt @@ -77,7 +77,7 @@ class ModelTaskController( } fun bindUpdatedWidgets(dataModel: BgDataModel) { - val widgetsByPackageItem = dataModel.widgetsModel.widgetsByPackageItem + val widgetsByPackageItem = dataModel.widgetsModel.widgetsByPackageItemForPicker val allWidgets = WidgetsListBaseEntriesBuilder(app.context).build(widgetsByPackageItem) val defaultWidgetsFilter = dataModel.widgetsModel.defaultWidgetsFilter diff --git a/src/com/android/launcher3/model/WidgetsModel.java b/src/com/android/launcher3/model/WidgetsModel.java index a17646556b..ab960d8169 100644 --- a/src/com/android/launcher3/model/WidgetsModel.java +++ b/src/com/android/launcher3/model/WidgetsModel.java @@ -70,6 +70,7 @@ public class WidgetsModel { private final Map> mWidgetsByPackageItem = new HashMap<>(); @Nullable private Predicate mDefaultWidgetsFilter = null; @Nullable private Predicate mPredictedWidgetsFilter = null; + @Nullable private WidgetValidityCheckForPicker mWidgetValidityCheckForPicker = null; /** * Returns all widgets keyed by their component key. @@ -87,13 +88,44 @@ public class WidgetsModel { } /** - * Returns widgets grouped by the package item that they should belong to. + * Returns widgets (eligible for display in picker) keyed by their component key. */ - public synchronized Map> getWidgetsByPackageItem() { - if (!WIDGETS_ENABLED) { + public synchronized Map getWidgetsByComponentKeyForPicker() { + if (!WIDGETS_ENABLED || mWidgetValidityCheckForPicker == null) { return Collections.emptyMap(); } - return new HashMap<>(mWidgetsByPackageItem); + + return mWidgetsByPackageItem.values().stream() + .flatMap(Collection::stream).distinct() + .filter(widgetItem -> mWidgetValidityCheckForPicker.test(widgetItem)) + .collect(Collectors.toMap( + widget -> new ComponentKey(widget.componentName, widget.user), + Function.identity() + )); + } + + /** + * Returns widgets (displayable in the widget picker) grouped by the package item that + * they should belong to. + */ + public synchronized Map> getWidgetsByPackageItemForPicker() { + if (!WIDGETS_ENABLED || mWidgetValidityCheckForPicker == null) { + return Collections.emptyMap(); + } + + return mWidgetsByPackageItem.entrySet().stream() + .collect( + Collectors.toMap( + Map.Entry::getKey, + entry -> entry.getValue().stream() + .filter(widgetItem -> + mWidgetValidityCheckForPicker.test(widgetItem)) + .collect(Collectors.toList()) + ) + ) + .entrySet().stream() + .filter(entry -> !entry.getValue().isEmpty()) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } /** @@ -181,6 +213,9 @@ public class WidgetsModel { Log.d(TAG, "addWidgetsAndShortcuts, widgetsShortcuts#=" + rawWidgetsShortcuts.size()); } + // Refresh the validity checker with latest app state. + mWidgetValidityCheckForPicker = new WidgetValidityCheckForPicker(app); + // Temporary cache for {@link PackageItemInfos} to avoid having to go through // {@link mPackageItemInfos} to locate the key to be used for {@link #mWidgetsList} PackageItemInfoCache packageItemInfoCache = new PackageItemInfoCache(); @@ -195,7 +230,6 @@ public class WidgetsModel { // add and update. mWidgetsByPackageItem.putAll(rawWidgetsShortcuts.stream() - .filter(new WidgetValidityCheck(app)) .filter(new WidgetFlagCheck()) .flatMap(widgetItem -> getPackageUserKeys(app.getContext(), widgetItem).stream() .map(key -> new Pair<>(packageItemInfoCache.getOrCreate(key), widgetItem))) @@ -270,12 +304,15 @@ public class WidgetsModel { return packageUserKeys; } - private static class WidgetValidityCheck implements Predicate { + /** + * Checks if widgets are eligible for displaying in widget picker / tray. + */ + private static class WidgetValidityCheckForPicker implements Predicate { private final InvariantDeviceProfile mIdp; private final AppFilter mAppFilter; - WidgetValidityCheck(LauncherAppState app) { + WidgetValidityCheckForPicker(LauncherAppState app) { mIdp = app.getInvariantDeviceProfile(); mAppFilter = new AppFilter(app.getContext()); } @@ -310,6 +347,10 @@ public class WidgetsModel { } } + /** + * Checks if certain widgets that are available behind flag can be used across all surfaces in + * launcher. + */ private static class WidgetFlagCheck implements Predicate { private static final String BUBBLES_SHORTCUT_WIDGET = diff --git a/tests/multivalentTests/src/com/android/launcher3/model/WidgetsModelTest.kt b/tests/multivalentTests/src/com/android/launcher3/model/WidgetsModelTest.kt index ae4ff042d5..d704195052 100644 --- a/tests/multivalentTests/src/com/android/launcher3/model/WidgetsModelTest.kt +++ b/tests/multivalentTests/src/com/android/launcher3/model/WidgetsModelTest.kt @@ -119,6 +119,11 @@ class WidgetsModelTest { // A widget in different package (none of that app's widgets are in widget // sections xml) createAppWidgetProviderInfo(AppBTestWidgetComponent), + // A widget in different app that is meant to be hidden from picker + createAppWidgetProviderInfo( + AppCPinOnlyTestWidgetComponent, + /*hideFromPicker=*/ true, + ), ) ) @@ -129,12 +134,13 @@ class WidgetsModelTest { } @Test - fun widgetsByPackage_treatsWidgetSectionsAsSeparatePackageItems() { + fun widgetsByPackageForPicker_treatsWidgetSectionsAsSeparatePackageItems() { loadWidgets() - val packages: Map> = underTest.widgetsByPackageItem + val packages: Map> = + underTest.widgetsByPackageItemForPicker - // expect 3 package items + // expect 3 package items (no app C as its widget is hidden from picker) // one for the custom section with widget from appA // one for package section for second widget from appA (that wasn't listed in xml) // and one for package section for appB @@ -167,6 +173,13 @@ class WidgetsModelTest { assertThat(appBPackageSection).hasSize(1) val widgetsInAppBSection = appBPackageSection.entries.first().value assertThat(widgetsInAppBSection).hasSize(1) + + // No App C's package section - as the only widget hosted by it is hidden in picker + val appCPackageSection = + packageSections.filter { + it.key.packageName == AppCPinOnlyTestWidgetComponent.packageName + } + assertThat(appCPackageSection).isEmpty() } @Test @@ -175,7 +188,29 @@ class WidgetsModelTest { val widgetsByComponentKey: Map = underTest.widgetsByComponentKey + // Has all widgets including ones not visible in picker + assertThat(widgetsByComponentKey).hasSize(4) + widgetsByComponentKey.forEach { entry -> + assertThat(entry.key).isEqualTo(entry.value as ComponentKey) + } + } + + @Test + fun widgetComponentMapForPicker_excludesWidgetsHiddenInPicker() { + loadWidgets() + + val widgetsByComponentKey: Map = + underTest.widgetsByComponentKeyForPicker + + // Has all widgets excluding the appC's widget. assertThat(widgetsByComponentKey).hasSize(3) + assertThat( + widgetsByComponentKey.filter { + it.key.componentName == AppCPinOnlyTestWidgetComponent + } + ) + .isEmpty() + // widgets mapped correctly widgetsByComponentKey.forEach { entry -> assertThat(entry.key).isEqualTo(entry.value as ComponentKey) } @@ -189,7 +224,7 @@ class WidgetsModelTest { } @Test - fun getWidgetsByPackageItem_returnsACopyOfMap() { + fun getWidgetsByPackageItemForPicker_returnsACopyOfMap() { loadWidgets() val latch = CountDownLatch(1) @@ -198,8 +233,8 @@ class WidgetsModelTest { // each "widgetsByPackageItem" read returns a different copy of the map held internally. // Modifying one shouldn't impact another. - for ((_, _) in underTest.widgetsByPackageItem.entries) { - underTest.widgetsByPackageItem.clear() + for ((_, _) in underTest.widgetsByPackageItemForPicker.entries) { + underTest.widgetsByPackageItemForPicker.clear() if (update) { // trigger update update = false // Similarly, model could update its code independently while a client is @@ -256,6 +291,9 @@ class WidgetsModelTest { private val AppBTestWidgetComponent: ComponentName = ComponentName.createRelative("com.test.package", "TestProvider") + private val AppCPinOnlyTestWidgetComponent: ComponentName = + ComponentName.createRelative("com.testC.package", "PinOnlyTestProvider") + private const val LOAD_WIDGETS_TIMEOUT_SECONDS = 2L } } diff --git a/tests/multivalentTests/src/com/android/launcher3/util/WidgetUtils.java b/tests/multivalentTests/src/com/android/launcher3/util/WidgetUtils.java index a87a208187..9fbd7ff311 100644 --- a/tests/multivalentTests/src/com/android/launcher3/util/WidgetUtils.java +++ b/tests/multivalentTests/src/com/android/launcher3/util/WidgetUtils.java @@ -15,6 +15,8 @@ */ package com.android.launcher3.util; +import static android.appwidget.AppWidgetProviderInfo.WIDGET_FEATURE_HIDE_FROM_PICKER; + import android.appwidget.AppWidgetProviderInfo; import android.content.ComponentName; import android.content.Context; @@ -83,14 +85,30 @@ public class WidgetUtils { /** * Creates a {@link AppWidgetProviderInfo} for the provided component name + * + * @param cn component name of the appwidget provider + * @param hideFromPicker indicates if the widget should appear in widget picker */ - public static AppWidgetProviderInfo createAppWidgetProviderInfo(ComponentName cn) { + public static AppWidgetProviderInfo createAppWidgetProviderInfo(ComponentName cn, + boolean hideFromPicker) { ActivityInfo activityInfo = new ActivityInfo(); activityInfo.applicationInfo = new ApplicationInfo(); activityInfo.applicationInfo.uid = Process.myUid(); AppWidgetProviderInfo info = new AppWidgetProviderInfo(); + if (hideFromPicker) { + info.widgetFeatures = WIDGET_FEATURE_HIDE_FROM_PICKER; + } info.providerInfo = activityInfo; info.provider = cn; return info; } + + /** + * Creates a {@link AppWidgetProviderInfo} for the provided component name + * + * @param cn component name of the appwidget provider + */ + public static AppWidgetProviderInfo createAppWidgetProviderInfo(ComponentName cn) { + return createAppWidgetProviderInfo(cn, /*hideFromPicker=*/ false); + } } From 8fabc6d1117d1103d338a3f718d6e4bff5193efe Mon Sep 17 00:00:00 2001 From: Andy Wickham Date: Wed, 19 Feb 2025 23:02:32 +0000 Subject: [PATCH 080/153] Log LPNH abandon times at least 200ms. Restricting to 200ms+ to reduce the spamminess of these logs. The idea is to log the latency of LPNH abandons to see the effect of prewarming at x ms. Bug: 397484410 Flag: EXEMPT logging Test: Manual and updated NavHandleLongPressInputConsumerTest. Change-Id: I93f94ed0757508b68fcb48d61bdd194564dcc573 --- .../NavHandleLongPressInputConsumer.java | 27 ++++++- .../NavHandleLongPressInputConsumerTest.java | 78 ++++++++++++++++++- .../launcher3/logging/StatsLogManager.java | 4 + 3 files changed, 105 insertions(+), 4 deletions(-) diff --git a/quickstep/src/com/android/quickstep/inputconsumers/NavHandleLongPressInputConsumer.java b/quickstep/src/com/android/quickstep/inputconsumers/NavHandleLongPressInputConsumer.java index afe988d4eb..a703c23865 100644 --- a/quickstep/src/com/android/quickstep/inputconsumers/NavHandleLongPressInputConsumer.java +++ b/quickstep/src/com/android/quickstep/inputconsumers/NavHandleLongPressInputConsumer.java @@ -19,6 +19,7 @@ import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCH import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_DEEP_PRESS_STASHED_TASKBAR; import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_LONG_PRESS_NAVBAR; import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_LONG_PRESS_STASHED_TASKBAR; +import static com.android.launcher3.logging.StatsLogManager.LauncherLatencyEvent.LAUNCHER_LATENCY_CONTEXTUAL_SEARCH_LPNH_ABANDON; import static com.android.launcher3.util.Executors.MAIN_EXECUTOR; import static com.android.launcher3.util.LogConfig.NAV_HANDLE_LONG_PRESS; @@ -30,6 +31,7 @@ import android.view.ViewConfiguration; import androidx.annotation.VisibleForTesting; import com.android.launcher3.Utilities; +import com.android.launcher3.logging.InstanceIdSequence; import com.android.launcher3.logging.StatsLogManager; import com.android.launcher3.util.DisplayController; import com.android.quickstep.DeviceConfigWrapper; @@ -49,6 +51,8 @@ public class NavHandleLongPressInputConsumer extends DelegateInputConsumer { private static final String TAG = "NavHandleLongPressIC"; private static final boolean DEBUG_NAV_HANDLE = Utilities.isPropertyEnabled( NAV_HANDLE_LONG_PRESS); + // Minimum time between touch down and abandon to log. + @VisibleForTesting static final long MIN_TIME_TO_LOG_ABANDON_MS = 200; private NavHandleLongPressHandler mNavHandleLongPressHandler; private final float mNavHandleWidth; @@ -62,11 +66,12 @@ public class NavHandleLongPressInputConsumer extends DelegateInputConsumer { private final int mOuterLongPressTimeout; private final boolean mDeepPressEnabled; private final NavHandle mNavHandle; - private final StatsLogManager mStatsLogManager; + private StatsLogManager mStatsLogManager; private final TopTaskTracker mTopTaskTracker; private final GestureState mGestureState; - private MotionEvent mCurrentDownEvent; + private MotionEvent mCurrentDownEvent; // Down event that started the current gesture. + private MotionEvent mCurrentMotionEvent; // Most recent motion event. private boolean mDeepPressLogged; // Whether deep press has been logged for the current touch. public NavHandleLongPressInputConsumer(Context context, InputConsumer delegate, @@ -125,6 +130,10 @@ public class NavHandleLongPressInputConsumer extends DelegateInputConsumer { @Override public void onMotionEvent(MotionEvent ev) { + if (mCurrentMotionEvent != null) { + mCurrentMotionEvent.recycle(); + } + mCurrentMotionEvent = MotionEvent.obtain(ev); if (mDelegate.allowInterceptByParent()) { handleMotionEvent(ev); } else if (MAIN_EXECUTOR.getHandler().hasCallbacks(mTriggerLongPress)) { @@ -244,6 +253,15 @@ public class NavHandleLongPressInputConsumer extends DelegateInputConsumer { if (DEBUG_NAV_HANDLE) { Log.d(TAG, "cancelLongPress: " + reason); } + // Log LPNH abandon latency if we didn't trigger but were still prepared to. + long latencyMs = mCurrentMotionEvent.getEventTime() - mCurrentDownEvent.getEventTime(); + if (mState != STATE_ACTIVE && MAIN_EXECUTOR.getHandler().hasCallbacks(mTriggerLongPress) + && latencyMs >= MIN_TIME_TO_LOG_ABANDON_MS) { + mStatsLogManager.latencyLogger() + .withInstanceId(new InstanceIdSequence().newInstanceId()) + .withLatency(latencyMs) + .log(LAUNCHER_LATENCY_CONTEXTUAL_SEARCH_LPNH_ABANDON); + } mGestureState.setIsInExtendedSlopRegion(false); MAIN_EXECUTOR.getHandler().removeCallbacks(mTriggerLongPress); mNavHandleLongPressHandler.onTouchFinished(mNavHandle, reason); @@ -274,4 +292,9 @@ public class NavHandleLongPressInputConsumer extends DelegateInputConsumer { void setNavHandleLongPressHandler(NavHandleLongPressHandler navHandleLongPressHandler) { mNavHandleLongPressHandler = navHandleLongPressHandler; } + + @VisibleForTesting + void setStatsLogManager(StatsLogManager statsLogManager) { + mStatsLogManager = statsLogManager; + } } diff --git a/quickstep/tests/multivalentTests/src/com/android/quickstep/inputconsumers/NavHandleLongPressInputConsumerTest.java b/quickstep/tests/multivalentTests/src/com/android/quickstep/inputconsumers/NavHandleLongPressInputConsumerTest.java index 7776351517..de6920bd46 100644 --- a/quickstep/tests/multivalentTests/src/com/android/quickstep/inputconsumers/NavHandleLongPressInputConsumerTest.java +++ b/quickstep/tests/multivalentTests/src/com/android/quickstep/inputconsumers/NavHandleLongPressInputConsumerTest.java @@ -24,6 +24,8 @@ import static android.view.MotionEvent.ACTION_UP; import static androidx.test.core.app.ApplicationProvider.getApplicationContext; +import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_LONG_PRESS_NAVBAR; +import static com.android.launcher3.logging.StatsLogManager.LauncherLatencyEvent.LAUNCHER_LATENCY_CONTEXTUAL_SEARCH_LPNH_ABANDON; import static com.android.launcher3.util.Executors.MAIN_EXECUTOR; import static com.android.quickstep.DeviceConfigWrapper.DEFAULT_LPNH_TIMEOUT_MS; @@ -33,9 +35,11 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import android.os.SystemClock; @@ -47,6 +51,7 @@ import androidx.test.platform.app.InstrumentationRegistry; import com.android.launcher3.dagger.LauncherAppComponent; import com.android.launcher3.dagger.LauncherAppSingleton; +import com.android.launcher3.logging.StatsLogManager; import com.android.launcher3.util.AllModulesForTest; import com.android.launcher3.util.DisplayController; import com.android.launcher3.util.MainThreadInitializedObject.SandboxContext; @@ -83,6 +88,7 @@ public class NavHandleLongPressInputConsumerTest { private NavHandleLongPressInputConsumer mUnderTest; private SandboxContext mContext; private float mScreenWidth; + private long mDownTimeMs; @Mock InputConsumer mDelegate; @Mock InputMonitorCompat mInputMonitor; @Mock RecentsAnimationDeviceState mDeviceState; @@ -91,6 +97,9 @@ public class NavHandleLongPressInputConsumerTest { @Mock NavHandleLongPressHandler mNavHandleLongPressHandler; @Mock TopTaskTracker mTopTaskTracker; @Mock TopTaskTracker.CachedTaskInfo mTaskInfo; + @Mock StatsLogManager mStatsLogManager; + @Mock StatsLogManager.StatsLogger mStatsLogger; + @Mock StatsLogManager.StatsLatencyLogger mStatsLatencyLogger; @Before public void setup() { @@ -100,6 +109,11 @@ public class NavHandleLongPressInputConsumerTest { when(mDelegate.allowInterceptByParent()).thenReturn(true); mLongPressTriggered.set(false); when(mNavHandleLongPressHandler.getLongPressRunnable(any())).thenReturn(mLongPressRunnable); + when(mStatsLogger.withPackageName(any())).thenReturn(mStatsLogger); + when(mStatsLatencyLogger.withInstanceId(any())).thenReturn(mStatsLatencyLogger); + when(mStatsLatencyLogger.withLatency(anyLong())).thenReturn(mStatsLatencyLogger); + when(mStatsLogManager.logger()).thenReturn(mStatsLogger); + when(mStatsLogManager.latencyLogger()).thenReturn(mStatsLatencyLogger); initializeObjectUnderTest(); } @@ -124,17 +138,24 @@ public class NavHandleLongPressInputConsumerTest { assertThat(mUnderTest.mState).isEqualTo(DelegateInputConsumer.STATE_INACTIVE); verify(mNavHandleLongPressHandler, never()).onTouchStarted(any()); verify(mNavHandleLongPressHandler, never()).onTouchFinished(any(), any()); + verifyNoMoreInteractions(mStatsLogManager); + verifyNoMoreInteractions(mStatsLogger); + verifyNoMoreInteractions(mStatsLatencyLogger); } @Test public void testDelegateDisallowsTouchInterceptAfterTouchDown() { + // Touch down and wait the minimum abandonment time. mUnderTest.onMotionEvent(generateCenteredMotionEvent(ACTION_DOWN)); + SystemClock.sleep(NavHandleLongPressInputConsumer.MIN_TIME_TO_LOG_ABANDON_MS); + InstrumentationRegistry.getInstrumentation().waitForIdleSync(); // Delegate should still get touches unless long press is triggered. verify(mDelegate).onMotionEvent(any()); verify(mNavHandleLongPressHandler, times(1)).onTouchStarted(any()); verify(mNavHandleLongPressHandler, never()).onTouchFinished(any(), any()); + // Child delegate blocks us from intercepting further motion events. when(mDelegate.allowInterceptByParent()).thenReturn(false); mUnderTest.onMotionEvent(generateCenteredMotionEvent(ACTION_MOVE)); @@ -144,6 +165,9 @@ public class NavHandleLongPressInputConsumerTest { assertThat(mUnderTest.mState).isEqualTo(DelegateInputConsumer.STATE_INACTIVE); verify(mNavHandleLongPressHandler, times(1)).onTouchStarted(any()); verify(mNavHandleLongPressHandler, times(1)).onTouchFinished(any(), any()); + verifyNoMoreInteractions(mStatsLogger); + // Because we handled touch down before the child blocked additional events, log abandon. + verify(mStatsLatencyLogger).log(LAUNCHER_LATENCY_CONTEXTUAL_SEARCH_LPNH_ABANDON); } @Test @@ -156,6 +180,12 @@ public class NavHandleLongPressInputConsumerTest { assertTrue(mLongPressTriggered.get()); verify(mNavHandleLongPressHandler, times(1)).onTouchStarted(any()); verify(mNavHandleLongPressHandler, never()).onTouchFinished(any(), any()); + verify(mStatsLogger).log(LAUNCHER_LONG_PRESS_NAVBAR); + verifyNoMoreInteractions(mStatsLatencyLogger); + + // Ensure abandon latency is still not logged after long press. + mUnderTest.onMotionEvent(generateCenteredMotionEvent(ACTION_UP)); + verifyNoMoreInteractions(mStatsLatencyLogger); } @Test @@ -170,6 +200,8 @@ public class NavHandleLongPressInputConsumerTest { assertTrue(mLongPressTriggered.get()); verify(mNavHandleLongPressHandler, times(1)).onTouchStarted(any()); verify(mNavHandleLongPressHandler, never()).onTouchFinished(any(), any()); + verify(mStatsLogger).log(LAUNCHER_LONG_PRESS_NAVBAR); + verifyNoMoreInteractions(mStatsLatencyLogger); } @Test @@ -184,6 +216,8 @@ public class NavHandleLongPressInputConsumerTest { assertTrue(mLongPressTriggered.get()); verify(mNavHandleLongPressHandler, times(1)).onTouchStarted(any()); verify(mNavHandleLongPressHandler, never()).onTouchFinished(any(), any()); + verify(mStatsLogger).log(LAUNCHER_LONG_PRESS_NAVBAR); + verifyNoMoreInteractions(mStatsLatencyLogger); } @Test @@ -215,6 +249,8 @@ public class NavHandleLongPressInputConsumerTest { assertTrue(mLongPressTriggered.get()); verify(mNavHandleLongPressHandler, times(1)).onTouchStarted(any()); verify(mNavHandleLongPressHandler, never()).onTouchFinished(any(), any()); + verify(mStatsLogger).log(LAUNCHER_LONG_PRESS_NAVBAR); + verifyNoMoreInteractions(mStatsLatencyLogger); } catch (Exception e) { throw new RuntimeException(e); } @@ -235,6 +271,8 @@ public class NavHandleLongPressInputConsumerTest { assertTrue(mLongPressTriggered.get()); verify(mNavHandleLongPressHandler, times(1)).onTouchStarted(any()); verify(mNavHandleLongPressHandler, never()).onTouchFinished(any(), any()); + verify(mStatsLogger).log(LAUNCHER_LONG_PRESS_NAVBAR); + verifyNoMoreInteractions(mStatsLatencyLogger); } catch (Exception e) { throw new RuntimeException(e); } @@ -258,6 +296,8 @@ public class NavHandleLongPressInputConsumerTest { assertFalse(mLongPressTriggered.get()); verify(mNavHandleLongPressHandler, times(1)).onTouchStarted(any()); verify(mNavHandleLongPressHandler, times(1)).onTouchFinished(any(), any()); + verifyNoMoreInteractions(mStatsLogger); + verify(mStatsLatencyLogger).log(LAUNCHER_LATENCY_CONTEXTUAL_SEARCH_LPNH_ABANDON); } @Test @@ -278,6 +318,8 @@ public class NavHandleLongPressInputConsumerTest { assertFalse(mLongPressTriggered.get()); verify(mNavHandleLongPressHandler, times(1)).onTouchStarted(any()); verify(mNavHandleLongPressHandler, times(1)).onTouchFinished(any(), any()); + verifyNoMoreInteractions(mStatsLogger); + verify(mStatsLatencyLogger).log(LAUNCHER_LATENCY_CONTEXTUAL_SEARCH_LPNH_ABANDON); } @Test @@ -299,6 +341,8 @@ public class NavHandleLongPressInputConsumerTest { assertFalse(mLongPressTriggered.get()); verify(mNavHandleLongPressHandler, times(1)).onTouchStarted(any()); verify(mNavHandleLongPressHandler, times(1)).onTouchFinished(any(), any()); + verifyNoMoreInteractions(mStatsLogger); + verify(mStatsLatencyLogger).log(LAUNCHER_LATENCY_CONTEXTUAL_SEARCH_LPNH_ABANDON); } @Test @@ -320,6 +364,8 @@ public class NavHandleLongPressInputConsumerTest { assertFalse(mLongPressTriggered.get()); verify(mNavHandleLongPressHandler, times(1)).onTouchStarted(any()); verify(mNavHandleLongPressHandler, times(1)).onTouchFinished(any(), any()); + verifyNoMoreInteractions(mStatsLogger); + verify(mStatsLatencyLogger).log(LAUNCHER_LATENCY_CONTEXTUAL_SEARCH_LPNH_ABANDON); } @Test @@ -354,6 +400,8 @@ public class NavHandleLongPressInputConsumerTest { verify(mNavHandleLongPressHandler, times(1)).onTouchStarted(any()); // Touch cancelled. verify(mNavHandleLongPressHandler, times(1)).onTouchFinished(any(), any()); + verifyNoMoreInteractions(mStatsLogger); + verify(mStatsLatencyLogger).log(LAUNCHER_LATENCY_CONTEXTUAL_SEARCH_LPNH_ABANDON); } catch (Exception e) { throw new RuntimeException(e); } @@ -391,6 +439,8 @@ public class NavHandleLongPressInputConsumerTest { verify(mNavHandleLongPressHandler, times(1)).onTouchStarted(any()); // Touch cancelled. verify(mNavHandleLongPressHandler, times(1)).onTouchFinished(any(), any()); + verifyNoMoreInteractions(mStatsLogger); + verify(mStatsLatencyLogger).log(LAUNCHER_LATENCY_CONTEXTUAL_SEARCH_LPNH_ABANDON); } catch (Exception e) { throw new RuntimeException(e); } @@ -408,6 +458,9 @@ public class NavHandleLongPressInputConsumerTest { assertFalse(mLongPressTriggered.get()); verify(mNavHandleLongPressHandler, never()).onTouchStarted(any()); verify(mNavHandleLongPressHandler, never()).onTouchFinished(any(), any()); + verifyNoMoreInteractions(mStatsLogManager); + verifyNoMoreInteractions(mStatsLogger); + verifyNoMoreInteractions(mStatsLatencyLogger); } @Test @@ -422,6 +475,21 @@ public class NavHandleLongPressInputConsumerTest { mUnderTest.onHoverEvent(generateCenteredMotionEvent(ACTION_HOVER_ENTER)); verify(mDelegate, times(2)).onHoverEvent(any()); + + verifyNoMoreInteractions(mStatsLogManager); + verifyNoMoreInteractions(mStatsLogger); + verifyNoMoreInteractions(mStatsLatencyLogger); + } + + @Test + public void testNoLogsForShortTouch() { + mUnderTest.onMotionEvent(generateCenteredMotionEvent(ACTION_DOWN)); + SystemClock.sleep(10); + InstrumentationRegistry.getInstrumentation().waitForIdleSync(); + mUnderTest.onMotionEvent(generateCenteredMotionEvent(ACTION_UP)); + verifyNoMoreInteractions(mStatsLogManager); + verifyNoMoreInteractions(mStatsLogger); + verifyNoMoreInteractions(mStatsLatencyLogger); } private void initializeObjectUnderTest() { @@ -437,6 +505,8 @@ public class NavHandleLongPressInputConsumerTest { mUnderTest = new NavHandleLongPressInputConsumer(mContext, mDelegate, mInputMonitor, mDeviceState, mNavHandle, mGestureState); mUnderTest.setNavHandleLongPressHandler(mNavHandleLongPressHandler); + mUnderTest.setStatsLogManager(mStatsLogManager); + mDownTimeMs = 0; } /** Generate a motion event centered horizontally in the screen. */ @@ -449,8 +519,12 @@ public class NavHandleLongPressInputConsumerTest { return generateMotionEvent(motionAction, mScreenWidth / 2f, y); } - private static MotionEvent generateMotionEvent(int motionAction, float x, float y) { - return MotionEvent.obtain(0, 0, motionAction, x, y, 0); + private MotionEvent generateMotionEvent(int motionAction, float x, float y) { + if (motionAction == ACTION_DOWN) { + mDownTimeMs = SystemClock.uptimeMillis(); + } + long eventTime = SystemClock.uptimeMillis(); + return MotionEvent.obtain(mDownTimeMs, eventTime, motionAction, x, y, 0); } private static AutoCloseable overrideTwoStageFlag(boolean value) { diff --git a/src/com/android/launcher3/logging/StatsLogManager.java b/src/com/android/launcher3/logging/StatsLogManager.java index 9a1c8742f2..2f1af68329 100644 --- a/src/com/android/launcher3/logging/StatsLogManager.java +++ b/src/com/android/launcher3/logging/StatsLogManager.java @@ -905,6 +905,10 @@ public class StatsLogManager implements ResourceBasedOverride { @UiEvent(doc = "Time passed between Contextual Search runnable creation and execution. This" + " ensures that Recent animations have finished before Contextual Search starts.") LAUNCHER_LATENCY_OMNI_RUNNABLE(1546), + + @UiEvent(doc = "Time passed between nav handle touch down and cancellation without " + + "triggering Contextual Search") + LAUNCHER_LATENCY_CONTEXTUAL_SEARCH_LPNH_ABANDON(2171), ; private final int mId; From 1422e89e92141863df239a9c7e4a03cec6352568 Mon Sep 17 00:00:00 2001 From: Daniel Andersson Date: Tue, 11 Feb 2025 15:05:44 -0800 Subject: [PATCH 081/153] desktop-exploded-view: Explode desktops when swiping up from home This change makes it so that the explode animation only happens when swiping up from the desk. In other cases, the desk is immediately set to its exploded state. The desk explode progress is now exposed as a FloatProperty in RecentsViewUtils. Flag: com.android.launcher3.enable_desktop_exploded_view Test: Manual Bug: 367353392 Change-Id: I5adec7db1fdc933860dce7fcca0a47cec0672ee7 --- .../uioverrides/RecentsViewStateController.kt | 18 ++++++++++++++++++ .../FallbackRecentsStateController.java | 6 ++++++ .../android/quickstep/views/DesktopTaskView.kt | 5 ----- .../android/quickstep/views/RecentsView.java | 13 ++++++++----- .../quickstep/views/RecentsViewUtils.kt | 18 ++++++++++++++++++ 5 files changed, 50 insertions(+), 10 deletions(-) diff --git a/quickstep/src/com/android/launcher3/uioverrides/RecentsViewStateController.kt b/quickstep/src/com/android/launcher3/uioverrides/RecentsViewStateController.kt index c8f46a9dd7..cca8bf8e17 100644 --- a/quickstep/src/com/android/launcher3/uioverrides/RecentsViewStateController.kt +++ b/quickstep/src/com/android/launcher3/uioverrides/RecentsViewStateController.kt @@ -20,6 +20,7 @@ import com.android.app.animation.Interpolators.AGGRESSIVE_EASE_IN_OUT import com.android.app.animation.Interpolators.FINAL_FRAME import com.android.app.animation.Interpolators.INSTANT import com.android.app.animation.Interpolators.LINEAR +import com.android.launcher3.Flags.enableDesktopExplodedView import com.android.launcher3.Flags.enableLargeDesktopWindowingTile import com.android.launcher3.LauncherState import com.android.launcher3.anim.AnimatedFloat @@ -51,6 +52,7 @@ import com.android.quickstep.views.RecentsView.TASK_PRIMARY_SPLIT_TRANSLATION import com.android.quickstep.views.RecentsView.TASK_SECONDARY_SPLIT_TRANSLATION import com.android.quickstep.views.RecentsView.TASK_SECONDARY_TRANSLATION import com.android.quickstep.views.RecentsView.TASK_THUMBNAIL_SPLASH_ALPHA +import com.android.quickstep.views.RecentsViewUtils.Companion.DESK_EXPLODE_PROGRESS import com.android.quickstep.views.TaskView.Companion.FLAG_UPDATE_ALL /** @@ -74,6 +76,13 @@ class RecentsViewStateController(private val launcher: QuickstepLauncher) : recentsView, if (state.displayOverviewTasksAsGrid(launcher.deviceProfile)) 1f else 0f, ) + if (enableDesktopExplodedView()) { + DESK_EXPLODE_PROGRESS.set( + recentsView, + if (state.displayOverviewTasksAsGrid(launcher.deviceProfile)) 1f else 0f, + ) + } + TASK_THUMBNAIL_SPLASH_ALPHA.set( recentsView, if (state.showTaskThumbnailSplash()) 1f else 0f, @@ -156,6 +165,15 @@ class RecentsViewStateController(private val launcher: QuickstepLauncher) : getOverviewInterpolator(fromState, toState), ) + if (enableDesktopExplodedView()) { + builder.setFloat( + recentsView, + DESK_EXPLODE_PROGRESS, + if (toState.isRecentsViewVisible) 1f else 0f, + getOverviewInterpolator(fromState, toState), + ) + } + if (enableLargeDesktopWindowingTile()) { builder.setFloat( recentsView, diff --git a/quickstep/src/com/android/quickstep/fallback/FallbackRecentsStateController.java b/quickstep/src/com/android/quickstep/fallback/FallbackRecentsStateController.java index b4b80c5705..56dd696550 100644 --- a/quickstep/src/com/android/quickstep/fallback/FallbackRecentsStateController.java +++ b/quickstep/src/com/android/quickstep/fallback/FallbackRecentsStateController.java @@ -18,6 +18,7 @@ package com.android.quickstep.fallback; import static com.android.app.animation.Interpolators.FINAL_FRAME; import static com.android.app.animation.Interpolators.INSTANT; import static com.android.app.animation.Interpolators.LINEAR; +import static com.android.launcher3.Flags.enableDesktopExplodedView; import static com.android.launcher3.Flags.enableLargeDesktopWindowingTile; import static com.android.launcher3.states.StateAnimationConfig.ANIM_OVERVIEW_MODAL; import static com.android.launcher3.states.StateAnimationConfig.ANIM_OVERVIEW_SCALE; @@ -36,6 +37,7 @@ import static com.android.quickstep.views.RecentsView.TASK_PRIMARY_SPLIT_TRANSLA import static com.android.quickstep.views.RecentsView.TASK_SECONDARY_SPLIT_TRANSLATION; import static com.android.quickstep.views.RecentsView.TASK_SECONDARY_TRANSLATION; import static com.android.quickstep.views.RecentsView.TASK_THUMBNAIL_SPLASH_ALPHA; +import static com.android.quickstep.views.RecentsViewUtils.DESK_EXPLODE_PROGRESS; import static com.android.quickstep.views.TaskView.FLAG_UPDATE_ALL; import android.util.FloatProperty; @@ -123,6 +125,10 @@ public class FallbackRecentsStateController implements StateHandler explodeProgress = progress }.animateToValue(0.0f, 1.0f) - private fun positionTaskWindows() { if (taskContainers.isEmpty()) { return diff --git a/quickstep/src/com/android/quickstep/views/RecentsView.java b/quickstep/src/com/android/quickstep/views/RecentsView.java index c5a76cb067..32854a7c10 100644 --- a/quickstep/src/com/android/quickstep/views/RecentsView.java +++ b/quickstep/src/com/android/quickstep/views/RecentsView.java @@ -72,6 +72,7 @@ import static com.android.quickstep.views.OverviewActionsView.HIDDEN_NON_ZERO_RO import static com.android.quickstep.views.OverviewActionsView.HIDDEN_NO_RECENTS; import static com.android.quickstep.views.OverviewActionsView.HIDDEN_NO_TASKS; import static com.android.quickstep.views.OverviewActionsView.HIDDEN_SPLIT_SELECT_ACTIVE; +import static com.android.quickstep.views.RecentsViewUtils.DESK_EXPLODE_PROGRESS; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; @@ -2910,13 +2911,15 @@ public abstract class RecentsView< } if (enableDesktopExplodedView()) { + if (animatorSet == null) { + mUtils.setDeskExplodeProgress(1); + } else { + animatorSet.play( + ObjectAnimator.ofFloat(this, DESK_EXPLODE_PROGRESS, 1)); + } + for (TaskView taskView : getTaskViews()) { if (taskView instanceof DesktopTaskView desktopTaskView) { - if (animatorSet == null) { - desktopTaskView.setExplodeProgress(1.0f); - } else { - animatorSet.play(desktopTaskView.startWindowExplodeAnimation()); - } desktopTaskView.setRemoteTargetHandles(remoteTargetHandles); } } diff --git a/quickstep/src/com/android/quickstep/views/RecentsViewUtils.kt b/quickstep/src/com/android/quickstep/views/RecentsViewUtils.kt index f742ec3898..8df743053c 100644 --- a/quickstep/src/com/android/quickstep/views/RecentsViewUtils.kt +++ b/quickstep/src/com/android/quickstep/views/RecentsViewUtils.kt @@ -17,6 +17,7 @@ package com.android.quickstep.views import android.graphics.Rect +import android.util.FloatProperty import android.view.View import androidx.core.view.children import com.android.launcher3.Flags.enableLargeDesktopWindowingTile @@ -294,7 +295,24 @@ class RecentsViewUtils(private val recentsView: RecentsView<*, *>) { } } + var deskExplodeProgress: Float = 0f + set(value) { + field = value + taskViews.filterIsInstance().forEach { it.explodeProgress = field } + } + companion object { + @JvmField + val DESK_EXPLODE_PROGRESS = + object : FloatProperty>("deskExplodeProgress") { + override fun setValue(recentsView: RecentsView<*, *>, value: Float) { + recentsView.mUtils.deskExplodeProgress = value + } + + override fun get(recentsView: RecentsView<*, *>) = + recentsView.mUtils.deskExplodeProgress + } + val TEMP_RECT = Rect() } } From f7e64649a19ea5d7a89bba4707706a14d74c2c1a Mon Sep 17 00:00:00 2001 From: Ahmed Fakhry Date: Wed, 19 Feb 2025 04:26:15 +0000 Subject: [PATCH 082/153] Launcher: Make `RecentTasksController.getRecentTasks()` multi-desks aware This is the Launcher-side CL of the companion CL ag/31825217. This CL changes `GroupedTaskInfo` and `RecentTasksController.getRecentTasks()` such that multiple desktops are supported. Bug: 395911284 Test: m Flag: com.android.window.flags.enable_multiple_desktops_frontend Flag: com.android.window.flags.enable_multiple_desktops_backend Change-Id: I856768d03460054ccd7056f87e16dcb65ced47fb --- .../src/com/android/quickstep/RecentTasksList.java | 4 ++-- .../com/android/quickstep/RecentTasksListTest.java | 11 ++++++----- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/quickstep/src/com/android/quickstep/RecentTasksList.java b/quickstep/src/com/android/quickstep/RecentTasksList.java index bb72408690..561bab4e62 100644 --- a/quickstep/src/com/android/quickstep/RecentTasksList.java +++ b/quickstep/src/com/android/quickstep/RecentTasksList.java @@ -21,7 +21,7 @@ import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS; import static com.android.launcher3.Flags.enableSeparateExternalDisplayTasks; import static com.android.launcher3.util.Executors.UI_HELPER_EXECUTOR; import static com.android.quickstep.util.SplitScreenUtils.convertShellSplitBoundsToLauncher; -import static com.android.wm.shell.shared.GroupedTaskInfo.TYPE_FREEFORM; +import static com.android.wm.shell.shared.GroupedTaskInfo.TYPE_DESK; import static com.android.wm.shell.shared.GroupedTaskInfo.TYPE_SPLIT; import android.app.ActivityManager.RunningTaskInfo; @@ -353,7 +353,7 @@ public class RecentTasksList { int numVisibleTasks = 0; for (GroupedTaskInfo rawTask : rawTasks) { - if (rawTask.isBaseType(TYPE_FREEFORM)) { + if (rawTask.isBaseType(TYPE_DESK)) { // TYPE_FREEFORM tasks is only created when desktop mode can be entered, // leftover TYPE_FREEFORM tasks created when flag was on should be ignored. if (DesktopModeStatus.canEnterDesktopMode(mContext)) { diff --git a/quickstep/tests/multivalentTests/src/com/android/quickstep/RecentTasksListTest.java b/quickstep/tests/multivalentTests/src/com/android/quickstep/RecentTasksListTest.java index 8b17958177..ad9bbb9534 100644 --- a/quickstep/tests/multivalentTests/src/com/android/quickstep/RecentTasksListTest.java +++ b/quickstep/tests/multivalentTests/src/com/android/quickstep/RecentTasksListTest.java @@ -177,8 +177,8 @@ public class RecentTasksListTest { createRecentTaskInfo(4 /* taskId */, DEFAULT_DISPLAY), createRecentTaskInfo(5 /* taskId */, 1 /* displayId */), createRecentTaskInfo(6 /* taskId */, 1 /* displayId */)); - GroupedTaskInfo recentTaskInfos = GroupedTaskInfo.forFreeformTasks( - tasks, Collections.emptySet() /* minimizedTaskIds */); + GroupedTaskInfo recentTaskInfos = GroupedTaskInfo.forDeskTasks( + 0 /* deskId */, tasks, Collections.emptySet() /* minimizedTaskIds */); when(mSystemUiProxy.getRecentTasks(anyInt(), anyInt())) .thenReturn(new ArrayList<>(Collections.singletonList(recentTaskInfos))); @@ -207,8 +207,8 @@ public class RecentTasksListTest { createRecentTaskInfo(4 /* taskId */, DEFAULT_DISPLAY), createRecentTaskInfo(5 /* taskId */, 1 /* displayId */), createRecentTaskInfo(6 /* taskId */, 1 /* displayId */)); - GroupedTaskInfo recentTaskInfos = GroupedTaskInfo.forFreeformTasks( - tasks, Collections.emptySet() /* minimizedTaskIds */); + GroupedTaskInfo recentTaskInfos = GroupedTaskInfo.forDeskTasks( + 0 /* deskId */, tasks, Collections.emptySet() /* minimizedTaskIds */); when(mSystemUiProxy.getRecentTasks(anyInt(), anyInt())) .thenReturn(new ArrayList<>(Collections.singletonList(recentTaskInfos))); @@ -241,7 +241,8 @@ public class RecentTasksListTest { createRecentTaskInfo(5 /* taskId */, DEFAULT_DISPLAY)); Set minimizedTaskIds = Arrays.stream(new Integer[]{1, 4, 5}).collect(Collectors.toSet()); - GroupedTaskInfo recentTaskInfos = GroupedTaskInfo.forFreeformTasks(tasks, minimizedTaskIds); + GroupedTaskInfo recentTaskInfos = GroupedTaskInfo.forDeskTasks( + 0 /* deskId */, tasks, minimizedTaskIds); when(mSystemUiProxy.getRecentTasks(anyInt(), anyInt())) .thenReturn(new ArrayList<>(Collections.singletonList(recentTaskInfos))); From cf37c5ba7e6b49af39e7449882c8921d0e9050cc Mon Sep 17 00:00:00 2001 From: Charlie Anderson Date: Wed, 19 Feb 2025 16:03:05 +0000 Subject: [PATCH 083/153] Add more checks around archived shortcut restore Bug: 375414891 Test: Launcher B&R and WorkspaceItemProcessorTest Flag: com.android.launcher3.restore_archived_shortcuts Change-Id: I58332dcee9563bb6c87aeff7255c8a9e2a8ca2c7 --- .../launcher3/model/WorkspaceItemProcessor.kt | 20 ++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/src/com/android/launcher3/model/WorkspaceItemProcessor.kt b/src/com/android/launcher3/model/WorkspaceItemProcessor.kt index 3919eb76dd..99f2837dd0 100644 --- a/src/com/android/launcher3/model/WorkspaceItemProcessor.kt +++ b/src/com/android/launcher3/model/WorkspaceItemProcessor.kt @@ -194,29 +194,35 @@ class WorkspaceItemProcessor( if (intent.`package` == null) { intent.`package` = targetPkg } - val isPreArchived = appInfoWrapper.isArchived() && c.restoreFlag != 0 + + val isPreArchivedShortcut = + Flags.restoreArchivedShortcuts() && + appInfoWrapper.isArchived() && + c.itemType == Favorites.ITEM_TYPE_DEEP_SHORTCUT && + c.restoreFlag != 0 // else if cn == null => can't infer much, leave it // else if !validPkg => could be restored icon or missing sd-card when { - !TextUtils.isEmpty(targetPkg) && (!validTarget || isPreArchived) -> { + !TextUtils.isEmpty(targetPkg) && (!validTarget || isPreArchivedShortcut) -> { // Points to a valid app (superset of cn != null) but the apk // is not available. when { - c.restoreFlag != 0 || isPreArchived -> { + c.restoreFlag != 0 || isPreArchivedShortcut -> { // Package is not yet available but might be // installed later. FileLog.d( TAG, "package not yet restored: $targetPkg, itemType=${c.itemType}" + - "isPreArchived=$isPreArchived, restoreFlag=${c.restoreFlag}", + ", isPreArchivedShortcut=$isPreArchivedShortcut" + + ", restoreFlag=${c.restoreFlag}", ) tempPackageKey.update(targetPkg, c.user) when { c.hasRestoreFlag(WorkspaceItemInfo.FLAG_RESTORE_STARTED) -> { // Restore has started once. } - installingPkgs.containsKey(tempPackageKey) || isPreArchived -> { + installingPkgs.containsKey(tempPackageKey) || isPreArchivedShortcut -> { // App restore has started. Update the flag c.restoreFlag = c.restoreFlag or WorkspaceItemInfo.FLAG_RESTORE_STARTED @@ -268,7 +274,7 @@ class WorkspaceItemProcessor( ) validTarget = false } - if (validTarget && !isPreArchived) { + if (validTarget && !isPreArchivedShortcut) { FileLog.d( TAG, "valid target true, marking restored: $targetPkg," + @@ -283,7 +289,7 @@ class WorkspaceItemProcessor( when { c.restoreFlag != 0 -> { // Already verified above that user is same as default user - info = c.getRestoredItemInfo(intent, isPreArchived) + info = c.getRestoredItemInfo(intent, isPreArchivedShortcut) } c.itemType == Favorites.ITEM_TYPE_APPLICATION -> info = c.getAppShortcutInfo(intent, allowMissingTarget, useLowResIcon, false) From 4742d62285643f473c3c8237a928b7deab35dca1 Mon Sep 17 00:00:00 2001 From: Sunny Goyal Date: Thu, 20 Feb 2025 12:57:56 -0800 Subject: [PATCH 084/153] Moving LooperExecutor to kotlin > Will improve priority changes in a followup cl Bug: 396250724 Flag: EXEMPT refactor Test: Presubmit Change-Id: Ic9646e9b1b8faf80996f6e63159e8abbf00fc0b7 --- src/com/android/launcher3/LauncherModel.kt | 5 +- .../android/launcher3/icons/IconCache.java | 2 +- .../android/launcher3/logging/FileLog.java | 2 +- src/com/android/launcher3/util/Executors.java | 34 ++--- .../launcher3/util/LooperExecutor.java | 118 ------------------ .../android/launcher3/util/LooperExecutor.kt | 95 ++++++++++++++ 6 files changed, 107 insertions(+), 149 deletions(-) delete mode 100644 src/com/android/launcher3/util/LooperExecutor.java create mode 100644 src/com/android/launcher3/util/LooperExecutor.kt diff --git a/src/com/android/launcher3/LauncherModel.kt b/src/com/android/launcher3/LauncherModel.kt index 6e4276d3e9..7871ccedf0 100644 --- a/src/com/android/launcher3/LauncherModel.kt +++ b/src/com/android/launcher3/LauncherModel.kt @@ -304,7 +304,7 @@ class LauncherModel( launcherBinder.bindWidgets() return true } else { - mLoaderTask = + val task = LoaderTask( mApp, mBgAllAppsList, @@ -313,10 +313,11 @@ class LauncherModel( launcherBinder, widgetsFilterDataProvider, ) + mLoaderTask = task // Always post the loader task, instead of running directly // (even on same thread) so that we exit any nested synchronized blocks - MODEL_EXECUTOR.post(mLoaderTask) + MODEL_EXECUTOR.post(task) } } } diff --git a/src/com/android/launcher3/icons/IconCache.java b/src/com/android/launcher3/icons/IconCache.java index 9f99e8f00a..f09cd75823 100644 --- a/src/com/android/launcher3/icons/IconCache.java +++ b/src/com/android/launcher3/icons/IconCache.java @@ -199,7 +199,7 @@ public class IconCache extends BaseIconCache { private void onIconRequestEnd() { mPendingIconRequestCount--; if (mPendingIconRequestCount <= 0) { - MODEL_EXECUTOR.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); + MODEL_EXECUTOR.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); } } diff --git a/src/com/android/launcher3/logging/FileLog.java b/src/com/android/launcher3/logging/FileLog.java index 924a44062c..5b254183b1 100644 --- a/src/com/android/launcher3/logging/FileLog.java +++ b/src/com/android/launcher3/logging/FileLog.java @@ -1,6 +1,6 @@ package com.android.launcher3.logging; -import static com.android.launcher3.util.Executors.createAndStartNewLooper; +import static com.android.launcher3.util.LooperExecutor.createAndStartNewLooper; import android.os.Handler; import android.os.HandlerThread; diff --git a/src/com/android/launcher3/util/Executors.java b/src/com/android/launcher3/util/Executors.java index c622b71108..296fc8ad27 100644 --- a/src/com/android/launcher3/util/Executors.java +++ b/src/com/android/launcher3/util/Executors.java @@ -16,8 +16,8 @@ package com.android.launcher3.util; import static android.os.Process.THREAD_PRIORITY_BACKGROUND; +import static android.os.Process.THREAD_PRIORITY_FOREGROUND; -import android.os.HandlerThread; import android.os.Looper; import android.os.Process; @@ -51,21 +51,20 @@ public class Executors { /** * An {@link LooperExecutor} to be used with async task where order is important. */ - public static final LooperExecutor ORDERED_BG_EXECUTOR = new LooperExecutor( - createAndStartNewLooper("BackgroundExecutor", THREAD_PRIORITY_BACKGROUND)); + public static final LooperExecutor ORDERED_BG_EXECUTOR = + new LooperExecutor("BackgroundExecutor", THREAD_PRIORITY_BACKGROUND); /** * Returns the executor for running tasks on the main thread. */ public static final LooperExecutor MAIN_EXECUTOR = - new LooperExecutor(Looper.getMainLooper()); + new LooperExecutor(Looper.getMainLooper(), THREAD_PRIORITY_FOREGROUND); /** * A background executor for using time sensitive actions where user is waiting for response. */ public static final LooperExecutor UI_HELPER_EXECUTOR = - new LooperExecutor( - createAndStartNewLooper("UiThreadHelper", Process.THREAD_PRIORITY_FOREGROUND)); + new LooperExecutor("UiThreadHelper", Process.THREAD_PRIORITY_FOREGROUND); /** A background executor to preinflate views. */ @@ -74,27 +73,10 @@ public class Executors { new SimpleThreadFactory( "preinflate-allapps-icons", THREAD_PRIORITY_BACKGROUND)); - /** - * Utility method to get a started handler thread statically - */ - public static Looper createAndStartNewLooper(String name) { - return createAndStartNewLooper(name, Process.THREAD_PRIORITY_DEFAULT); - } - - /** - * Utility method to get a started handler thread statically with the provided priority - */ - public static Looper createAndStartNewLooper(String name, int priority) { - HandlerThread thread = new HandlerThread(name, priority); - thread.start(); - return thread.getLooper(); - } - /** * Executor used for running Launcher model related tasks (eg loading icons or updated db) */ - public static final LooperExecutor MODEL_EXECUTOR = - new LooperExecutor(createAndStartNewLooper("launcher-loader")); + public static final LooperExecutor MODEL_EXECUTOR = new LooperExecutor("launcher-loader"); /** * Returns and caches a single thread executor for a given package. @@ -102,9 +84,7 @@ public class Executors { * @param packageName Package associated with the executor. */ public static LooperExecutor getPackageExecutor(String packageName) { - return PACKAGE_EXECUTORS.computeIfAbsent( - packageName, p -> new LooperExecutor( - createAndStartNewLooper(p, Process.THREAD_PRIORITY_DEFAULT))); + return PACKAGE_EXECUTORS.computeIfAbsent(packageName, LooperExecutor::new); } /** diff --git a/src/com/android/launcher3/util/LooperExecutor.java b/src/com/android/launcher3/util/LooperExecutor.java deleted file mode 100644 index 3a8a13c8bb..0000000000 --- a/src/com/android/launcher3/util/LooperExecutor.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright (C) 2017 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.launcher3.util; - -import android.os.Handler; -import android.os.HandlerThread; -import android.os.Looper; -import android.os.Process; - -import java.util.List; -import java.util.concurrent.AbstractExecutorService; -import java.util.concurrent.TimeUnit; - -/** - * Extension of {@link AbstractExecutorService} which executed on a provided looper. - */ -public class LooperExecutor extends AbstractExecutorService { - - private final Handler mHandler; - - public LooperExecutor(Looper looper) { - mHandler = new Handler(looper); - } - - public Handler getHandler() { - return mHandler; - } - - @Override - public void execute(Runnable runnable) { - if (getHandler().getLooper() == Looper.myLooper()) { - runnable.run(); - } else { - getHandler().post(runnable); - } - } - - /** - * Same as execute, but never runs the action inline. - */ - public void post(Runnable runnable) { - getHandler().post(runnable); - } - - /** - * Not supported and throws an exception when used. - */ - @Override - @Deprecated - public void shutdown() { - throw new UnsupportedOperationException(); - } - - /** - * Not supported and throws an exception when used. - */ - @Override - @Deprecated - public List shutdownNow() { - throw new UnsupportedOperationException(); - } - - @Override - public boolean isShutdown() { - return false; - } - - @Override - public boolean isTerminated() { - return false; - } - - /** - * Not supported and throws an exception when used. - */ - @Override - @Deprecated - public boolean awaitTermination(long l, TimeUnit timeUnit) { - throw new UnsupportedOperationException(); - } - - /** - * Returns the thread for this executor - */ - public Thread getThread() { - return getHandler().getLooper().getThread(); - } - - /** - * Returns the looper for this executor - */ - public Looper getLooper() { - return getHandler().getLooper(); - } - - /** - * Set the priority of a thread, based on Linux priorities. - * @param priority Linux priority level, from -20 for highest scheduling priority - * to 19 for lowest scheduling priority. - * @see Process#setThreadPriority(int, int) - */ - public void setThreadPriority(int priority) { - Process.setThreadPriority(((HandlerThread) getThread()).getThreadId(), priority); - } -} diff --git a/src/com/android/launcher3/util/LooperExecutor.kt b/src/com/android/launcher3/util/LooperExecutor.kt new file mode 100644 index 0000000000..f5ba906342 --- /dev/null +++ b/src/com/android/launcher3/util/LooperExecutor.kt @@ -0,0 +1,95 @@ +/* + * Copyright (C) 2017 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.launcher3.util + +import android.os.Handler +import android.os.HandlerThread +import android.os.Looper +import android.os.Process +import java.util.concurrent.AbstractExecutorService +import java.util.concurrent.TimeUnit + +/** Extension of [AbstractExecutorService] which executed on a provided looper. */ +class LooperExecutor(looper: Looper, private val defaultPriority: Int) : AbstractExecutorService() { + val handler: Handler = Handler(looper) + + @JvmOverloads + constructor( + name: String, + defaultPriority: Int = Process.THREAD_PRIORITY_DEFAULT, + ) : this(createAndStartNewLooper(name, defaultPriority), defaultPriority) + + /** Returns the thread for this executor */ + val thread: Thread + get() = handler.looper.thread + + /** Returns the looper for this executor */ + val looper: Looper + get() = handler.looper + + override fun execute(runnable: Runnable) { + if (handler.looper == Looper.myLooper()) { + runnable.run() + } else { + handler.post(runnable) + } + } + + /** Same as execute, but never runs the action inline. */ + fun post(runnable: Runnable) { + handler.post(runnable) + } + + @Deprecated("Not supported and throws an exception when used") + override fun shutdown() { + throw UnsupportedOperationException() + } + + @Deprecated("Not supported and throws an exception when used.") + override fun shutdownNow(): List { + throw UnsupportedOperationException() + } + + override fun isShutdown() = false + + override fun isTerminated() = false + + @Deprecated("Not supported and throws an exception when used.") + override fun awaitTermination(l: Long, timeUnit: TimeUnit): Boolean { + throw UnsupportedOperationException() + } + + /** + * Set the priority of a thread, based on Linux priorities. + * + * @param priority Linux priority level, from -20 for highest scheduling priority to 19 for + * lowest scheduling priority. + * @see Process.setThreadPriority + */ + fun setThreadPriority(priority: Int) { + Process.setThreadPriority((thread as HandlerThread).threadId, priority) + } + + companion object { + /** Utility method to get a started handler thread statically with the provided priority */ + @JvmOverloads + @JvmStatic + fun createAndStartNewLooper( + name: String, + priority: Int = Process.THREAD_PRIORITY_DEFAULT, + ): Looper = HandlerThread(name, priority).apply { start() }.looper + } +} From c9f697aeb5e35eed45c7f396ec2c8164ba8c82c5 Mon Sep 17 00:00:00 2001 From: Sunny Goyal Date: Tue, 18 Feb 2025 13:03:05 -0800 Subject: [PATCH 085/153] Converting LauncherAppState to Dagger Bug: 361850561 Test: Presubmit Flag: EXEMPT dagger Change-Id: I336a233d2703c23a7e9065474bde471786886144 --- .../com/android/launcher3/dagger/AppModule.kt | 9 +- quickstep/res/values/config.xml | 1 - .../model/QuickstepModelDelegate.java | 84 ++++++----- .../model/WidgetPredictionsRequester.java | 2 +- .../model/WidgetsPredictionUpdateTask.java | 2 +- .../logging/StatsLogCompatManager.java | 21 ++- .../model/QuickstepModelDelegateTest.kt | 11 +- res/values/config.xml | 3 - src/com/android/launcher3/AppFilter.java | 7 +- .../android/launcher3/LauncherAppState.java | 140 ------------------ src/com/android/launcher3/LauncherAppState.kt | 48 ++++++ .../launcher3/LauncherApplication.java | 12 +- src/com/android/launcher3/LauncherModel.kt | 80 ++++++---- .../android/launcher3/LauncherProvider.java | 9 +- .../dagger/LauncherBaseAppComponent.java | 8 + .../dagger/LauncherComponentProvider.kt | 6 +- .../graphics/LauncherPreviewRenderer.java | 3 - .../android/launcher3/icons/IconCache.java | 35 ++++- .../launcher3/icons/LauncherIconProvider.java | 17 ++- .../launcher3/model/ModelDelegate.java | 41 ++--- .../launcher3/model/ModelInitializer.kt | 36 ++--- .../model/data/ItemInfoWithIcon.java | 2 + .../launcher3/provider/RestoreDbTask.java | 2 +- .../WidgetRecommendationCategoryProvider.java | 14 +- .../launcher3/icons/IconCacheTest.java | 12 +- .../model/AddWorkspaceItemsTaskTest.kt | 2 +- .../launcher3/model/LoaderCursorTest.java | 6 +- .../launcher3/util/LauncherModelHelper.java | 16 +- .../folder/PreviewItemManagerTest.kt | 12 +- .../android/launcher3/model/LoaderTaskTest.kt | 48 +++--- 30 files changed, 332 insertions(+), 357 deletions(-) delete mode 100644 src/com/android/launcher3/LauncherAppState.java create mode 100644 src/com/android/launcher3/LauncherAppState.kt rename tests/{multivalentTests => }/src/com/android/launcher3/folder/PreviewItemManagerTest.kt (97%) diff --git a/quickstep/dagger/com/android/launcher3/dagger/AppModule.kt b/quickstep/dagger/com/android/launcher3/dagger/AppModule.kt index 29586c4afc..d88fc94d5b 100644 --- a/quickstep/dagger/com/android/launcher3/dagger/AppModule.kt +++ b/quickstep/dagger/com/android/launcher3/dagger/AppModule.kt @@ -16,10 +16,17 @@ package com.android.launcher3.dagger +import com.android.launcher3.model.ModelDelegate +import com.android.launcher3.model.QuickstepModelDelegate +import dagger.Binds import dagger.Module /** * Module containing bindings for the final derivative app, an implementation of this module should * be included in the final app code. */ -@Module abstract class AppModule {} +@Module +abstract class AppModule { + + @Binds abstract fun bindModelDelegate(impl: QuickstepModelDelegate): ModelDelegate +} diff --git a/quickstep/res/values/config.xml b/quickstep/res/values/config.xml index a530325f04..d699cdf49e 100644 --- a/quickstep/res/values/config.xml +++ b/quickstep/res/values/config.xml @@ -27,7 +27,6 @@ com.android.quickstep.InstantAppResolverImpl com.android.launcher3.appprediction.PredictionAppTracker com.android.quickstep.QuickstepProcessInitializer - com.android.launcher3.model.QuickstepModelDelegate com.android.launcher3.secondarydisplay.SecondaryDisplayPredictionsImpl com.android.launcher3.taskbar.TaskbarModelCallbacksFactory com.android.launcher3.taskbar.TaskbarViewCallbacksFactory diff --git a/quickstep/src/com/android/launcher3/model/QuickstepModelDelegate.java b/quickstep/src/com/android/launcher3/model/QuickstepModelDelegate.java index 40e8fc2484..74b73d4bdf 100644 --- a/quickstep/src/com/android/launcher3/model/QuickstepModelDelegate.java +++ b/quickstep/src/com/android/launcher3/model/QuickstepModelDelegate.java @@ -47,6 +47,7 @@ import android.content.pm.LauncherApps; import android.content.pm.ShortcutInfo; import android.os.Bundle; import android.os.UserHandle; +import android.text.TextUtils; import android.util.Log; import android.util.StatsEvent; @@ -61,6 +62,7 @@ import com.android.launcher3.ConstantItem; import com.android.launcher3.InvariantDeviceProfile; import com.android.launcher3.LauncherAppState; import com.android.launcher3.LauncherPrefs; +import com.android.launcher3.dagger.ApplicationContext; import com.android.launcher3.icons.cache.CacheLookupFlag; import com.android.launcher3.logger.LauncherAtom; import com.android.launcher3.logging.InstanceId; @@ -89,6 +91,9 @@ import java.util.Map; import java.util.Objects; import java.util.stream.IntStream; +import javax.inject.Inject; +import javax.inject.Named; + /** * Model delegate which loads prediction items */ @@ -114,18 +119,29 @@ public class QuickstepModelDelegate extends ModelDelegate { CONTAINER_WIDGETS_PREDICTION, "widgets_prediction", DESKTOP_ICON_FLAG); private final InvariantDeviceProfile mIDP; + private final PackageManagerHelper mPmHelper; private final AppEventProducer mAppEventProducer; + private final StatsManager mStatsManager; protected boolean mActive = false; - public QuickstepModelDelegate(Context context) { + @Inject + public QuickstepModelDelegate(@ApplicationContext Context context, + InvariantDeviceProfile idp, + PackageManagerHelper pmHelper, + @Nullable @Named("ICONS_DB") String dbFileName) { super(context); - mAppEventProducer = new AppEventProducer(context, this::onAppTargetEvent); + mIDP = idp; + mPmHelper = pmHelper; - mIDP = InvariantDeviceProfile.INSTANCE.get(context); + mAppEventProducer = new AppEventProducer(context, this::onAppTargetEvent); StatsLogCompatManager.LOGS_CONSUMER.add(mAppEventProducer); - mStatsManager = context.getSystemService(StatsManager.class); + + // Only register for launcher snapshot logging if this is the primary ModelDelegate + // instance, as there will be additional instances that may be destroyed at any time. + mStatsManager = TextUtils.isEmpty(dbFileName) + ? null : context.getSystemService(StatsManager.class); } @CallSuper @@ -154,10 +170,10 @@ public class QuickstepModelDelegate extends ModelDelegate { // TODO: Implement caching and preloading WorkspaceItemFactory factory = - new WorkspaceItemFactory(mApp, ums, mPmHelper, pinnedShortcuts, numColumns, + new WorkspaceItemFactory(mContext, ums, mPmHelper, pinnedShortcuts, numColumns, state.containerId, state.lookupFlag); FixedContainerItems fci = new FixedContainerItems(state.containerId, - state.storage.read(mApp.getContext(), factory, ums.allUsers::get)); + state.storage.read(mContext, factory, ums.allUsers::get)); mDataModel.extraItems.put(state.containerId, fci); } @@ -220,7 +236,7 @@ public class QuickstepModelDelegate extends ModelDelegate { super.modelLoadComplete(); // Log snapshot of the model - LauncherPrefs prefs = LauncherPrefs.get(mApp.getContext()); + LauncherPrefs prefs = LauncherPrefs.get(mContext); long lastSnapshotTimeMillis = prefs.get(LAST_SNAPSHOT_TIME_MILLIS); // Log snapshot only if previous snapshot was older than a day long now = System.currentTimeMillis(); @@ -245,11 +261,7 @@ public class QuickstepModelDelegate extends ModelDelegate { prefs.put(LAST_SNAPSHOT_TIME_MILLIS, now); } - // Only register for launcher snapshot logging if this is the primary ModelDelegate - // instance, as there will be additional instances that may be destroyed at any time. - if (mIsPrimaryInstance) { - registerSnapshotLoggingCallback(); - } + registerSnapshotLoggingCallback(); } protected void additionalSnapshotEvents(InstanceId snapshotInstanceId){} @@ -257,9 +269,9 @@ public class QuickstepModelDelegate extends ModelDelegate { /** * Registers a callback to log launcher workspace layout using Statsd pulled atom. */ - protected void registerSnapshotLoggingCallback() { + private void registerSnapshotLoggingCallback() { if (mStatsManager == null) { - Log.d(TAG, "Failed to get StatsManager"); + Log.d(TAG, "Skipping snapshot logging"); } try { @@ -332,7 +344,7 @@ public class QuickstepModelDelegate extends ModelDelegate { super.destroy(); mActive = false; StatsLogCompatManager.LOGS_CONSUMER.remove(mAppEventProducer); - if (mIsPrimaryInstance && mStatsManager != null) { + if (mStatsManager != null) { try { mStatsManager.clearPullAtomCallback(SysUiStatsLog.LAUNCHER_LAYOUT_SNAPSHOT); } catch (RuntimeException e) { @@ -354,25 +366,24 @@ public class QuickstepModelDelegate extends ModelDelegate { if (!mActive) { return; } - Context context = mApp.getContext(); - AppPredictionManager apm = context.getSystemService(AppPredictionManager.class); + AppPredictionManager apm = mContext.getSystemService(AppPredictionManager.class); if (apm == null) { return; } registerPredictor(mAllAppsState, apm.createAppPredictionSession( - new AppPredictionContext.Builder(context) + new AppPredictionContext.Builder(mContext) .setUiSurface("home") .setPredictedTargetCount(mIDP.numDatabaseAllAppsColumns) .build())); // TODO: get bundle - registerHotseatPredictor(apm, context); + registerHotseatPredictor(apm, mContext); registerWidgetsPredictor(apm.createAppPredictionSession( - new AppPredictionContext.Builder(context) + new AppPredictionContext.Builder(mContext) .setUiSurface("widgets") - .setExtras(getBundleForWidgetsOnWorkspace(context, mDataModel)) + .setExtras(getBundleForWidgetsOnWorkspace(mContext, mDataModel)) .setPredictedTargetCount(NUM_OF_RECOMMENDED_WIDGETS_PREDICATION) .build())); } @@ -383,12 +394,11 @@ public class QuickstepModelDelegate extends ModelDelegate { if (!mActive) { return; } - Context context = mApp.getContext(); - AppPredictionManager apm = context.getSystemService(AppPredictionManager.class); + AppPredictionManager apm = mContext.getSystemService(AppPredictionManager.class); if (apm == null) { return; } - registerHotseatPredictor(apm, context); + registerHotseatPredictor(apm, mContext); } private void registerHotseatPredictor(AppPredictionManager apm, Context context) { @@ -413,7 +423,7 @@ public class QuickstepModelDelegate extends ModelDelegate { // No diff, skip return; } - mApp.getModel().enqueueModelUpdateTask(new PredictionUpdateTask(state, targets)); + mModel.enqueueModelUpdateTask(new PredictionUpdateTask(state, targets)); } private void registerWidgetsPredictor(AppPredictor predictor) { @@ -424,7 +434,7 @@ public class QuickstepModelDelegate extends ModelDelegate { // No diff, skip return; } - mApp.getModel().enqueueModelUpdateTask( + mModel.enqueueModelUpdateTask( new WidgetsPredictionUpdateTask(mWidgetsRecommendationState, targets)); }); mWidgetsRecommendationState.predictor.requestPredictionUpdate(); @@ -536,7 +546,7 @@ public class QuickstepModelDelegate extends ModelDelegate { private static class WorkspaceItemFactory implements PersistedItemArray.ItemFactory { - private final LauncherAppState mAppState; + private final Context mContext; private final UserManagerState mUMS; private final PackageManagerHelper mPmHelper; private final Map mPinnedShortcuts; @@ -546,10 +556,11 @@ public class QuickstepModelDelegate extends ModelDelegate { private int mReadCount = 0; - protected WorkspaceItemFactory(LauncherAppState appState, UserManagerState ums, + protected WorkspaceItemFactory( + Context context, UserManagerState ums, PackageManagerHelper pmHelper, Map pinnedShortcuts, int maxCount, int container, CacheLookupFlag lookupFlag) { - mAppState = appState; + mContext = context; mUMS = ums; mPmHelper = pmHelper; mPinnedShortcuts = pinnedShortcuts; @@ -566,7 +577,7 @@ public class QuickstepModelDelegate extends ModelDelegate { } switch (itemType) { case ITEM_TYPE_APPLICATION: { - LauncherActivityInfo lai = mAppState.getContext() + LauncherActivityInfo lai = mContext .getSystemService(LauncherApps.class) .resolveActivity(intent, user); if (lai == null) { @@ -574,14 +585,15 @@ public class QuickstepModelDelegate extends ModelDelegate { } AppInfo info = new AppInfo( lai, - UserCache.INSTANCE.get(mAppState.getContext()).getUserInfo(user), - ApiWrapper.INSTANCE.get(mAppState.getContext()), + UserCache.INSTANCE.get(mContext).getUserInfo(user), + ApiWrapper.INSTANCE.get(mContext), mPmHelper, mUMS.isUserQuiet(user)); info.container = mContainer; - mAppState.getIconCache().getTitleAndIcon(info, lai, mLookupFlag); + LauncherAppState.getInstance(mContext).getIconCache() + .getTitleAndIcon(info, lai, mLookupFlag); mReadCount++; - return info.makeWorkspaceItem(mAppState.getContext()); + return info.makeWorkspaceItem(mContext); } case ITEM_TYPE_DEEP_SHORTCUT: { ShortcutKey key = ShortcutKey.fromIntent(intent, user); @@ -592,9 +604,9 @@ public class QuickstepModelDelegate extends ModelDelegate { if (si == null) { return null; } - WorkspaceItemInfo wii = new WorkspaceItemInfo(si, mAppState.getContext()); + WorkspaceItemInfo wii = new WorkspaceItemInfo(si, mContext); wii.container = mContainer; - mAppState.getIconCache().getShortcutIcon(wii, si); + LauncherAppState.getInstance(mContext).getIconCache().getShortcutIcon(wii, si); mReadCount++; return wii; } diff --git a/quickstep/src/com/android/launcher3/model/WidgetPredictionsRequester.java b/quickstep/src/com/android/launcher3/model/WidgetPredictionsRequester.java index 8c98babc0a..d3ac975052 100644 --- a/quickstep/src/com/android/launcher3/model/WidgetPredictionsRequester.java +++ b/quickstep/src/com/android/launcher3/model/WidgetPredictionsRequester.java @@ -203,7 +203,7 @@ public class WidgetPredictionsRequester { List items; if (enableCategorizedWidgetSuggestions()) { WidgetRecommendationCategoryProvider categoryProvider = - WidgetRecommendationCategoryProvider.newInstance(mContext); + new WidgetRecommendationCategoryProvider(); items = widgetItems.stream() .map(it -> new PendingAddWidgetInfo(it.widgetInfo, CONTAINER_WIDGETS_PREDICTION, categoryProvider.getWidgetRecommendationCategory(mContext, it))) diff --git a/quickstep/src/com/android/launcher3/model/WidgetsPredictionUpdateTask.java b/quickstep/src/com/android/launcher3/model/WidgetsPredictionUpdateTask.java index 40e1c10d1c..aa81695d28 100644 --- a/quickstep/src/com/android/launcher3/model/WidgetsPredictionUpdateTask.java +++ b/quickstep/src/com/android/launcher3/model/WidgetsPredictionUpdateTask.java @@ -137,7 +137,7 @@ public final class WidgetsPredictionUpdateTask implements ModelUpdateTask { List items; if (enableCategorizedWidgetSuggestions()) { WidgetRecommendationCategoryProvider categoryProvider = - WidgetRecommendationCategoryProvider.newInstance(context); + new WidgetRecommendationCategoryProvider(); items = servicePredictedItems.stream() .map(it -> new PendingAddWidgetInfo(it.widgetInfo, CONTAINER_WIDGETS_PREDICTION, categoryProvider.getWidgetRecommendationCategory(context, it))) diff --git a/quickstep/src/com/android/quickstep/logging/StatsLogCompatManager.java b/quickstep/src/com/android/quickstep/logging/StatsLogCompatManager.java index 594c99a9c8..58e54cffbf 100644 --- a/quickstep/src/com/android/quickstep/logging/StatsLogCompatManager.java +++ b/quickstep/src/com/android/quickstep/logging/StatsLogCompatManager.java @@ -382,18 +382,15 @@ public class StatsLogCompatManager extends StatsLogManager { return; } - if (mItemInfo.container < 0 || !LauncherAppState.INSTANCE.executeIfCreated(app -> { - // Item is inside a collection, fetch collection info in a BG thread - // and then write to StatsLog. - app.getModel().enqueueModelUpdateTask((taskController, dataModel, apps) -> - write(event, applyOverwrites(mItemInfo.buildProto( - (CollectionInfo) dataModel.itemsIdMap.get(mItemInfo.container), - mContext)))); - })) { - // Write log on the model thread so that logs do not go out of order - // (for eg: drop comes after drag) - Executors.MODEL_EXECUTOR.execute( - () -> write(event, applyOverwrites(mItemInfo.buildProto(mContext)))); + // Item is inside a collection, fetch collection info in a BG thread + // and then write to StatsLog. + if (mItemInfo.container < 0) { + LauncherAppState.INSTANCE.get(mContext).getModel().enqueueModelUpdateTask( + (taskController, dataModel, apps) -> write(event, applyOverwrites( + mItemInfo.buildProto( + (CollectionInfo) dataModel.itemsIdMap + .get(mItemInfo.container), + mContext)))); } } diff --git a/quickstep/tests/multivalentTests/src/com/android/launcher3/model/QuickstepModelDelegateTest.kt b/quickstep/tests/multivalentTests/src/com/android/launcher3/model/QuickstepModelDelegateTest.kt index 0005df6a6e..09c62aae1a 100644 --- a/quickstep/tests/multivalentTests/src/com/android/launcher3/model/QuickstepModelDelegateTest.kt +++ b/quickstep/tests/multivalentTests/src/com/android/launcher3/model/QuickstepModelDelegateTest.kt @@ -19,7 +19,6 @@ import android.app.prediction.AppPredictor import android.app.prediction.AppTarget import android.app.prediction.AppTargetEvent import androidx.test.ext.junit.runners.AndroidJUnit4 -import com.android.launcher3.LauncherAppState import com.android.launcher3.LauncherSettings.Favorites.CONTAINER_HOTSEAT_PREDICTION import com.android.launcher3.LauncherSettings.Favorites.CONTAINER_PREDICTION import com.android.launcher3.LauncherSettings.Favorites.CONTAINER_WALLPAPERS @@ -54,11 +53,17 @@ class QuickstepModelDelegateTest { fun setUp() { MockitoAnnotations.initMocks(this) modelHelper = LauncherModelHelper() - underTest = QuickstepModelDelegate(modelHelper.sandboxContext) + underTest = + QuickstepModelDelegate( + modelHelper.sandboxContext, + modelHelper.sandboxContext.appComponent.idp, + modelHelper.sandboxContext.appComponent.packageManagerHelper, + "", /* dbFileName */ + ) underTest.mAllAppsState.predictor = allAppsPredictor underTest.mHotseatState.predictor = hotseatPredictor underTest.mWidgetsRecommendationState.predictor = widgetRecommendationPredictor - underTest.mApp = LauncherAppState.getInstance(modelHelper.sandboxContext) + underTest.mModel = modelHelper.model underTest.mDataModel = BgDataModel() } diff --git a/res/values/config.xml b/res/values/config.xml index 07f97bc4b7..1a2ac9e928 100644 --- a/res/values/config.xml +++ b/res/values/config.xml @@ -67,7 +67,6 @@ - @@ -75,8 +74,6 @@ - - diff --git a/src/com/android/launcher3/AppFilter.java b/src/com/android/launcher3/AppFilter.java index 3db456cbdb..8ee7053ccb 100644 --- a/src/com/android/launcher3/AppFilter.java +++ b/src/com/android/launcher3/AppFilter.java @@ -3,10 +3,14 @@ package com.android.launcher3; import android.content.ComponentName; import android.content.Context; +import com.android.launcher3.dagger.ApplicationContext; + import java.util.Arrays; import java.util.Set; import java.util.stream.Collectors; +import javax.inject.Inject; + /** * Utility class to filter out components from various lists */ @@ -14,7 +18,8 @@ public class AppFilter { private final Set mFilteredComponents; - public AppFilter(Context context) { + @Inject + public AppFilter(@ApplicationContext Context context) { mFilteredComponents = Arrays.stream( context.getResources().getStringArray(R.array.filtered_components)) .map(ComponentName::unflattenFromString) diff --git a/src/com/android/launcher3/LauncherAppState.java b/src/com/android/launcher3/LauncherAppState.java deleted file mode 100644 index bf2ad92e61..0000000000 --- a/src/com/android/launcher3/LauncherAppState.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright (C) 2013 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.launcher3; - -import android.content.Context; -import android.util.Log; - -import androidx.annotation.Nullable; - -import com.android.launcher3.dagger.LauncherComponentProvider; -import com.android.launcher3.graphics.ThemeManager; -import com.android.launcher3.icons.IconCache; -import com.android.launcher3.icons.IconProvider; -import com.android.launcher3.icons.LauncherIconProvider; -import com.android.launcher3.model.ModelInitializer; -import com.android.launcher3.model.WidgetsFilterDataProvider; -import com.android.launcher3.pm.InstallSessionHelper; -import com.android.launcher3.pm.UserCache; -import com.android.launcher3.util.MainThreadInitializedObject; -import com.android.launcher3.util.PackageManagerHelper; -import com.android.launcher3.util.Preconditions; -import com.android.launcher3.util.RunnableList; -import com.android.launcher3.util.SafeCloseable; -import com.android.launcher3.util.SettingsCache; -import com.android.launcher3.util.TraceHelper; -import com.android.launcher3.widget.custom.CustomWidgetManager; - -public class LauncherAppState implements SafeCloseable { - - public static final String TAG = "LauncherAppState"; - - // We do not need any synchronization for this variable as its only written on UI thread. - public static final MainThreadInitializedObject INSTANCE = - new MainThreadInitializedObject<>(LauncherAppState::new); - - private final Context mContext; - private final LauncherModel mModel; - private final LauncherIconProvider mIconProvider; - private final IconCache mIconCache; - private final InvariantDeviceProfile mInvariantDeviceProfile; - private boolean mIsSafeModeEnabled; - - private final RunnableList mOnTerminateCallback = new RunnableList(); - - public static LauncherAppState getInstance(Context context) { - return INSTANCE.get(context); - } - - public Context getContext() { - return mContext; - } - - @SuppressWarnings("NewApi") - public LauncherAppState(Context context) { - this(context, LauncherFiles.APP_ICONS_DB); - Log.v(Launcher.TAG, "LauncherAppState initiated"); - Preconditions.assertUIThread(); - - mIsSafeModeEnabled = TraceHelper.allowIpcs("isSafeMode", - () -> context.getPackageManager().isSafeMode()); - - ModelInitializer initializer = new ModelInitializer( - context, - LauncherComponentProvider.get(context).getIconPool(), - mIconCache, - mInvariantDeviceProfile, - ThemeManager.INSTANCE.get(context), - UserCache.INSTANCE.get(context), - SettingsCache.INSTANCE.get(context), - mIconProvider, - CustomWidgetManager.INSTANCE.get(context), - InstallSessionHelper.INSTANCE.get(context), - closeable -> mOnTerminateCallback.add(closeable::close) - ); - initializer.initialize(mModel); - } - - public LauncherAppState(Context context, @Nullable String iconCacheFileName) { - mContext = context; - - mInvariantDeviceProfile = InvariantDeviceProfile.INSTANCE.get(context); - mIconProvider = new LauncherIconProvider(context); - mIconCache = new IconCache(mContext, mInvariantDeviceProfile, - iconCacheFileName, mIconProvider); - mModel = new LauncherModel(context, this, mIconCache, - WidgetsFilterDataProvider.Companion.newInstance(context), new AppFilter(mContext), - PackageManagerHelper.INSTANCE.get(context), iconCacheFileName != null); - mOnTerminateCallback.add(mIconCache::close); - mOnTerminateCallback.add(mModel::destroy); - } - - /** - * Call from Application.onTerminate(), which is not guaranteed to ever be called. - */ - @Override - public void close() { - mOnTerminateCallback.executeAllAndDestroy(); - } - - public IconProvider getIconProvider() { - return mIconProvider; - } - - public IconCache getIconCache() { - return mIconCache; - } - - public LauncherModel getModel() { - return mModel; - } - - public InvariantDeviceProfile getInvariantDeviceProfile() { - return mInvariantDeviceProfile; - } - - public boolean isSafeModeEnabled() { - return mIsSafeModeEnabled; - } - - /** - * Shorthand for {@link #getInvariantDeviceProfile()} - */ - public static InvariantDeviceProfile getIDP(Context context) { - return InvariantDeviceProfile.INSTANCE.get(context); - } -} diff --git a/src/com/android/launcher3/LauncherAppState.kt b/src/com/android/launcher3/LauncherAppState.kt new file mode 100644 index 0000000000..ff84c3c863 --- /dev/null +++ b/src/com/android/launcher3/LauncherAppState.kt @@ -0,0 +1,48 @@ +/* + * Copyright (C) 2013 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.launcher3 + +import android.content.Context +import com.android.launcher3.dagger.ApplicationContext +import com.android.launcher3.icons.IconCache +import com.android.launcher3.icons.LauncherIconProvider +import com.android.launcher3.util.DaggerSingletonObject +import javax.inject.Inject +import javax.inject.Named + +/** A collection of common dependencies used across Launcher */ +@Deprecated("Inject the specific targets directly instead of using LauncherAppState") +data class LauncherAppState +@Inject +constructor( + @ApplicationContext val context: Context, + val iconProvider: LauncherIconProvider, + val iconCache: IconCache, + val model: LauncherModel, + val invariantDeviceProfile: InvariantDeviceProfile, + @Named("SAFE_MODE") val isSafeModeEnabled: Boolean, +) { + + companion object { + + @JvmField var INSTANCE = DaggerSingletonObject { it.launcherAppState } + + @JvmStatic fun getInstance(context: Context) = INSTANCE[context] + + /** Shorthand for [.getInvariantDeviceProfile] */ + @JvmStatic fun getIDP(context: Context) = InvariantDeviceProfile.INSTANCE[context] + } +} diff --git a/src/com/android/launcher3/LauncherApplication.java b/src/com/android/launcher3/LauncherApplication.java index 678901b5b2..03eaeea178 100644 --- a/src/com/android/launcher3/LauncherApplication.java +++ b/src/com/android/launcher3/LauncherApplication.java @@ -20,6 +20,7 @@ import android.app.Application; import com.android.launcher3.dagger.DaggerLauncherAppComponent; import com.android.launcher3.dagger.LauncherAppComponent; import com.android.launcher3.dagger.LauncherBaseAppComponent; +import com.android.launcher3.util.TraceHelper; /** * Main application class for Launcher @@ -41,7 +42,8 @@ public class LauncherApplication extends Application { if (mAppComponent == null) { // Initialize the dagger component on demand as content providers can get // accessed before the Launcher application (b/36917845#comment4) - initDaggerComponent(DaggerLauncherAppComponent.builder()); + initDaggerComponent(DaggerLauncherAppComponent.builder() + .iconsDbName(LauncherFiles.APP_ICONS_DB)); } } } @@ -55,7 +57,11 @@ public class LauncherApplication extends Application { /** * Init with the desired dagger component. */ - public void initDaggerComponent(LauncherAppComponent.Builder componentBuilder) { - mAppComponent = componentBuilder.appContext(this).build(); + public void initDaggerComponent(LauncherBaseAppComponent.Builder componentBuilder) { + mAppComponent = componentBuilder + .appContext(this) + .setSafeModeEnabled(TraceHelper.allowIpcs( + "isSafeMode", () -> getPackageManager().isSafeMode())) + .build(); } } diff --git a/src/com/android/launcher3/LauncherModel.kt b/src/com/android/launcher3/LauncherModel.kt index 6e4276d3e9..33b63ce5d1 100644 --- a/src/com/android/launcher3/LauncherModel.kt +++ b/src/com/android/launcher3/LauncherModel.kt @@ -23,6 +23,8 @@ import android.text.TextUtils import android.util.Pair import androidx.annotation.WorkerThread import com.android.launcher3.celllayout.CellPosMapper +import com.android.launcher3.dagger.ApplicationContext +import com.android.launcher3.dagger.LauncherAppSingleton import com.android.launcher3.icons.IconCache import com.android.launcher3.model.AddWorkspaceItemsTask import com.android.launcher3.model.AllAppsList @@ -33,6 +35,7 @@ import com.android.launcher3.model.ItemInstallQueue import com.android.launcher3.model.LoaderTask import com.android.launcher3.model.ModelDbController import com.android.launcher3.model.ModelDelegate +import com.android.launcher3.model.ModelInitializer import com.android.launcher3.model.ModelLauncherCallbacks import com.android.launcher3.model.ModelTaskController import com.android.launcher3.model.ModelWriter @@ -45,31 +48,42 @@ import com.android.launcher3.model.data.ItemInfo 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.PackageManagerHelper import com.android.launcher3.util.PackageUserKey import com.android.launcher3.util.Preconditions import java.io.FileDescriptor import java.io.PrintWriter import java.util.concurrent.CancellationException import java.util.function.Consumer +import javax.inject.Inject +import javax.inject.Named +import javax.inject.Provider /** * Maintains in-memory state of the Launcher. It is expected that there should be only one * LauncherModel object held in a static. Also provide APIs for updating the database state for the * Launcher. */ -class LauncherModel( - private val context: Context, - private val mApp: LauncherAppState, +@LauncherAppSingleton +class LauncherModel +@Inject +constructor( + @ApplicationContext private val context: Context, + private val appProvider: Provider, private val iconCache: IconCache, - private val widgetsFilterDataProvider: WidgetsFilterDataProvider, + private val prefs: LauncherPrefs, + private val installQueue: ItemInstallQueue, appFilter: AppFilter, - mPmHelper: PackageManagerHelper, - isPrimaryInstance: Boolean, + @Named("ICONS_DB") dbFileName: String?, + initializer: ModelInitializer, + lifecycle: DaggerSingletonTracker, + val modelDelegate: ModelDelegate, ) { + private val widgetsFilterDataProvider = WidgetsFilterDataProvider.newInstance(context) + private val mCallbacksList = ArrayList(1) // < only access in worker thread > @@ -81,16 +95,6 @@ class LauncherModel( */ private val mBgDataModel = BgDataModel() - val modelDelegate: ModelDelegate = - ModelDelegate.newInstance( - context, - mApp, - mPmHelper, - mBgAllAppsList, - mBgDataModel, - isPrimaryInstance, - ) - val modelDbController = ModelDbController(context) private val mLock = Any() @@ -125,6 +129,14 @@ class LauncherModel( } } + init { + if (!dbFileName.isNullOrEmpty()) { + initializer.initialize(this) + } + lifecycle.addCloseable { destroy() } + modelDelegate.init(this, mBgAllAppsList, mBgDataModel) + } + fun newModelCallbacks() = ModelLauncherCallbacks(this::enqueueModelUpdateTask) /** Adds the provided items to the workspace. */ @@ -137,7 +149,7 @@ class LauncherModel( verifyChanges: Boolean, cellPosMapper: CellPosMapper?, owner: BgDataModel.Callbacks?, - ) = ModelWriter(mApp.context, this, mBgDataModel, verifyChanges, cellPosMapper, owner) + ) = ModelWriter(context, this, mBgDataModel, verifyChanges, cellPosMapper, owner) /** Returns the [WidgetsFilterDataProvider] that manages widget filters. */ fun getWidgetsFilterDataProvider(): WidgetsFilterDataProvider { @@ -202,7 +214,7 @@ class LauncherModel( UserCache.ACTION_PROFILE_UNLOCKED -> enqueueModelUpdateTask(UserLockStateChangedTask(user, true)) Intent.ACTION_MANAGED_PROFILE_REMOVED -> { - LauncherPrefs.get(mApp.context).put(LauncherPrefs.WORK_EDU_STEP, 0) + prefs.put(LauncherPrefs.WORK_EDU_STEP, 0) forceReload() } UserCache.ACTION_PROFILE_ADDED, @@ -233,6 +245,13 @@ class LauncherModel( rebindCallbacks() } + /** Reloads the model if it is already in use */ + fun reloadIfActive() { + val wasActive: Boolean + synchronized(mLock) { wasActive = mModelLoaded || stopLoader() } + if (wasActive) forceReload() + } + /** Rebinds all existing callbacks with already loaded model */ fun rebindCallbacks() { if (hasCallbacks()) { @@ -280,7 +299,7 @@ class LauncherModel( private fun startLoader(newCallbacks: Array): Boolean { // Enable queue before starting loader. It will get disabled in Launcher#finishBindingItems - ItemInstallQueue.INSTANCE.get(context).pauseModelPush(ItemInstallQueue.FLAG_LOADER_RUNNING) + installQueue.pauseModelPush(ItemInstallQueue.FLAG_LOADER_RUNNING) synchronized(mLock) { // If there is already one running, tell it to stop. val wasRunning = stopLoader() @@ -292,7 +311,12 @@ class LauncherModel( callbacksList.forEach { MAIN_EXECUTOR.execute(it::clearPendingBinds) } val launcherBinder = - BaseLauncherBinder(mApp, mBgDataModel, mBgAllAppsList, callbacksList) + BaseLauncherBinder( + appProvider.get(), + mBgDataModel, + mBgAllAppsList, + callbacksList, + ) if (bindDirectly) { // Divide the set of loaded items into those that we are binding synchronously, // and everything else that is to be bound normally (asynchronously). @@ -306,7 +330,7 @@ class LauncherModel( } else { mLoaderTask = LoaderTask( - mApp, + appProvider.get(), mBgAllAppsList, mBgDataModel, this.modelDelegate, @@ -412,7 +436,7 @@ class LauncherModel( /** Called when the labels for the widgets has updated in the icon cache. */ fun onWidgetLabelsUpdated(updatedPackages: HashSet, user: UserHandle) { enqueueModelUpdateTask { taskController, dataModel, _ -> - dataModel.widgetsModel.onPackageIconsUpdated(updatedPackages, user, mApp) + dataModel.widgetsModel.onPackageIconsUpdated(updatedPackages, user, appProvider.get()) taskController.bindUpdatedWidgets(dataModel) } } @@ -435,7 +459,13 @@ class LauncherModel( return@execute } task.execute( - ModelTaskController(mApp, mBgDataModel, mBgAllAppsList, this, MAIN_EXECUTOR), + ModelTaskController( + appProvider.get(), + mBgDataModel, + mBgAllAppsList, + this, + MAIN_EXECUTOR, + ), mBgDataModel, mBgAllAppsList, ) @@ -496,8 +526,6 @@ class LauncherModel( } companion object { - private const val DEBUG_RECEIVER = false - const val TAG = "Launcher.Model" } } diff --git a/src/com/android/launcher3/LauncherProvider.java b/src/com/android/launcher3/LauncherProvider.java index a526b89532..03ecf14ef6 100644 --- a/src/com/android/launcher3/LauncherProvider.java +++ b/src/com/android/launcher3/LauncherProvider.java @@ -61,11 +61,10 @@ public class LauncherProvider extends ContentProvider { */ @Override public void dump(FileDescriptor fd, PrintWriter writer, String[] args) { - LauncherAppState.INSTANCE.executeIfCreated(appState -> { - if (appState.getModel().isModelLoaded()) { - appState.getModel().dumpState("", fd, writer, args); - } - }); + LauncherModel model = LauncherAppState.INSTANCE.get(getContext()).getModel(); + if (model.isModelLoaded()) { + model.dumpState("", fd, writer, args); + } } @Override diff --git a/src/com/android/launcher3/dagger/LauncherBaseAppComponent.java b/src/com/android/launcher3/dagger/LauncherBaseAppComponent.java index 31d0da08db..be385d22c7 100644 --- a/src/com/android/launcher3/dagger/LauncherBaseAppComponent.java +++ b/src/com/android/launcher3/dagger/LauncherBaseAppComponent.java @@ -18,7 +18,10 @@ package com.android.launcher3.dagger; import android.content.Context; +import androidx.annotation.Nullable; + import com.android.launcher3.InvariantDeviceProfile; +import com.android.launcher3.LauncherAppState; import com.android.launcher3.LauncherPrefs; import com.android.launcher3.graphics.ThemeManager; import com.android.launcher3.icons.LauncherIcons.IconPool; @@ -43,6 +46,8 @@ import com.android.launcher3.widget.custom.CustomWidgetManager; import dagger.BindsInstance; +import javax.inject.Named; + /** * Launcher base component for Dagger injection. * @@ -74,10 +79,13 @@ public interface LauncherBaseAppComponent { LockedUserState getLockedUserState(); InvariantDeviceProfile getIDP(); IconPool getIconPool(); + LauncherAppState getLauncherAppState(); /** Builder for LauncherBaseAppComponent. */ interface Builder { @BindsInstance Builder appContext(@ApplicationContext Context context); + @BindsInstance Builder iconsDbName(@Nullable @Named("ICONS_DB") String dbFileName); + @BindsInstance Builder setSafeModeEnabled(@Named("SAFE_MODE") boolean safeModeEnabled); LauncherBaseAppComponent build(); } } diff --git a/src/com/android/launcher3/dagger/LauncherComponentProvider.kt b/src/com/android/launcher3/dagger/LauncherComponentProvider.kt index 71e3354abf..61991494b4 100644 --- a/src/com/android/launcher3/dagger/LauncherComponentProvider.kt +++ b/src/com/android/launcher3/dagger/LauncherComponentProvider.kt @@ -39,8 +39,10 @@ object LauncherComponentProvider { // Create a new component return Holder( - DaggerLauncherAppComponent.builder().appContext(app).build() - as LauncherAppComponent, + DaggerLauncherAppComponent.builder() + .appContext(app) + .setSafeModeEnabled(true) + .build() as LauncherAppComponent, existingFilter, ) .apply { inflater.filter = this } diff --git a/src/com/android/launcher3/graphics/LauncherPreviewRenderer.java b/src/com/android/launcher3/graphics/LauncherPreviewRenderer.java index 03f05820b7..332a6bbc36 100644 --- a/src/com/android/launcher3/graphics/LauncherPreviewRenderer.java +++ b/src/com/android/launcher3/graphics/LauncherPreviewRenderer.java @@ -67,7 +67,6 @@ import com.android.launcher3.DeviceProfile.OnDeviceProfileChangeListener; import com.android.launcher3.Hotseat; import com.android.launcher3.InsettableFrameLayout; import com.android.launcher3.InvariantDeviceProfile; -import com.android.launcher3.LauncherAppState; import com.android.launcher3.LauncherPrefs; import com.android.launcher3.LauncherSettings.Favorites; import com.android.launcher3.ProxyPrefs; @@ -146,8 +145,6 @@ public class LauncherPreviewRenderer extends ContextWrapper prefs.put(GRID_NAME, gridName); initDaggerComponent( DaggerLauncherPreviewRenderer_PreviewAppComponent.builder().bindPrefs(prefs)); - putObject(LauncherAppState.INSTANCE, - new LauncherAppState(this, null /* iconCacheFileName */)); } @Override diff --git a/src/com/android/launcher3/icons/IconCache.java b/src/com/android/launcher3/icons/IconCache.java index 9f99e8f00a..fc0c1bbf57 100644 --- a/src/com/android/launcher3/icons/IconCache.java +++ b/src/com/android/launcher3/icons/IconCache.java @@ -51,6 +51,8 @@ import androidx.core.util.Pair; import com.android.launcher3.Flags; import com.android.launcher3.InvariantDeviceProfile; import com.android.launcher3.Utilities; +import com.android.launcher3.dagger.ApplicationContext; +import com.android.launcher3.dagger.LauncherAppSingleton; import com.android.launcher3.icons.cache.BaseIconCache; import com.android.launcher3.icons.cache.CacheLookupFlag; import com.android.launcher3.icons.cache.CachedObject; @@ -66,6 +68,7 @@ import com.android.launcher3.pm.InstallSessionHelper; import com.android.launcher3.pm.UserCache; import com.android.launcher3.util.CancellableTask; import com.android.launcher3.util.ComponentKey; +import com.android.launcher3.util.DaggerSingletonTracker; import com.android.launcher3.util.InstantAppResolver; import com.android.launcher3.util.PackageUserKey; import com.android.launcher3.widget.WidgetSections; @@ -79,9 +82,13 @@ import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Stream; +import javax.inject.Inject; +import javax.inject.Named; + /** * Cache of application icons. Icons can be made from any thread. */ +@LauncherAppSingleton public class IconCache extends BaseIconCache { // Shortcut extra which can point to a packageName and can be used to indicate an alternate @@ -96,24 +103,39 @@ public class IconCache extends BaseIconCache { private final LauncherApps mLauncherApps; private final UserCache mUserManager; + private final InstallSessionHelper mInstallSessionHelper; private final InstantAppResolver mInstantAppResolver; private final CancellableTask mCancelledTask; + private final LauncherIcons.IconPool mIconPool; private final SparseArray mWidgetCategoryBitmapInfos; private int mPendingIconRequestCount = 0; - public IconCache(Context context, InvariantDeviceProfile idp, String dbFileName, - IconProvider iconProvider) { + @Inject + public IconCache( + @ApplicationContext Context context, + InvariantDeviceProfile idp, + @Nullable @Named("ICONS_DB") String dbFileName, + UserCache userCache, + LauncherIconProvider iconProvider, + InstallSessionHelper installSessionHelper, + LauncherIcons.IconPool iconPool, + DaggerSingletonTracker lifecycle) { super(context, dbFileName, MODEL_EXECUTOR.getLooper(), idp.fillResIconDpi, idp.iconBitmapSize, true /* inMemoryCache */, iconProvider); mLauncherApps = context.getSystemService(LauncherApps.class); - mUserManager = UserCache.INSTANCE.get(context); + mUserManager = userCache; + mInstallSessionHelper = installSessionHelper; + mIconPool = iconPool; + mInstantAppResolver = InstantAppResolver.newInstance(context); mWidgetCategoryBitmapInfos = new SparseArray<>(); mCancelledTask = new CancellableTask(() -> null, MAIN_EXECUTOR, c -> { }); mCancelledTask.cancel(); + + lifecycle.addCloseable(this::close); } @Override @@ -129,7 +151,7 @@ public class IconCache extends BaseIconCache { @NonNull @Override public BaseIconFactory getIconFactory() { - return LauncherIcons.obtain(context); + return mIconPool.obtain(); } /** @@ -279,8 +301,7 @@ public class IconCache extends BaseIconCache { String override = shortcutInfo.getExtras() == null ? null : shortcutInfo.getExtras().getString(EXTRA_SHORTCUT_BADGE_OVERRIDE_PACKAGE); if (!TextUtils.isEmpty(override) - && InstallSessionHelper.INSTANCE.get(context) - .isTrustedPackage(pkg, shortcutInfo.getUserHandle())) { + && mInstallSessionHelper.isTrustedPackage(pkg, shortcutInfo.getUserHandle())) { pkg = override; } else { // Try component based badge before trying the normal package badge @@ -536,7 +557,7 @@ public class IconCache extends BaseIconCache { return; } - try (LauncherIcons li = LauncherIcons.obtain(context)) { + try (LauncherIcons li = mIconPool.obtain()) { final BitmapInfo tempBitmap = li.createBadgedIconBitmap( context.getDrawable(widgetSection.mSectionDrawable), new BaseIconFactory.IconOptions()); diff --git a/src/com/android/launcher3/icons/LauncherIconProvider.java b/src/com/android/launcher3/icons/LauncherIconProvider.java index 836b7d1c00..72411984d7 100644 --- a/src/com/android/launcher3/icons/LauncherIconProvider.java +++ b/src/com/android/launcher3/icons/LauncherIconProvider.java @@ -30,6 +30,8 @@ import androidx.annotation.Nullable; import com.android.launcher3.R; import com.android.launcher3.config.FeatureFlags; +import com.android.launcher3.dagger.ApplicationContext; +import com.android.launcher3.dagger.LauncherAppSingleton; import com.android.launcher3.graphics.ShapeDelegate; import com.android.launcher3.graphics.ThemeManager; import com.android.launcher3.util.ApiWrapper; @@ -39,9 +41,12 @@ import org.xmlpull.v1.XmlPullParser; import java.util.Collections; import java.util.Map; +import javax.inject.Inject; + /** * Extension of {@link IconProvider} with support for overriding theme icons */ +@LauncherAppSingleton public class LauncherIconProvider extends IconProvider { private static final String TAG_ICON = "icon"; @@ -56,10 +61,14 @@ public class LauncherIconProvider extends IconProvider { private final ApiWrapper mApiWrapper; private final ThemeManager mThemeManager; - public LauncherIconProvider(Context context) { + @Inject + public LauncherIconProvider( + @ApplicationContext Context context, + ThemeManager themeManager, + ApiWrapper apiWrapper) { super(context); - mThemeManager = ThemeManager.INSTANCE.get(context); - mApiWrapper = ApiWrapper.INSTANCE.get(context); + mThemeManager = themeManager; + mApiWrapper = apiWrapper; setIconThemeSupported(mThemeManager.isMonoThemeEnabled()); } @@ -79,7 +88,7 @@ public class LauncherIconProvider extends IconProvider { @Override public void updateSystemState() { super.updateSystemState(); - mSystemState += "," + ThemeManager.INSTANCE.get(mContext).getIconState().toUniqueId(); + mSystemState += "," + mThemeManager.getIconState().toUniqueId(); } @Override diff --git a/src/com/android/launcher3/model/ModelDelegate.java b/src/com/android/launcher3/model/ModelDelegate.java index 5a2aef0ce9..52a2188ca2 100644 --- a/src/com/android/launcher3/model/ModelDelegate.java +++ b/src/com/android/launcher3/model/ModelDelegate.java @@ -23,62 +23,45 @@ import android.content.pm.ShortcutInfo; import androidx.annotation.NonNull; import androidx.annotation.WorkerThread; -import com.android.launcher3.LauncherAppState; -import com.android.launcher3.R; +import com.android.launcher3.LauncherModel; +import com.android.launcher3.dagger.ApplicationContext; import com.android.launcher3.shortcuts.ShortcutKey; -import com.android.launcher3.util.PackageManagerHelper; -import com.android.launcher3.util.ResourceBasedOverride; import java.io.FileDescriptor; import java.io.PrintWriter; import java.util.Map; +import javax.inject.Inject; + /** * Class to extend LauncherModel functionality to provide extra data */ -public class ModelDelegate implements ResourceBasedOverride { - - /** - * Creates and initializes a new instance of the delegate - */ - public static ModelDelegate newInstance( - Context context, LauncherAppState app, PackageManagerHelper pmHelper, - AllAppsList appsList, BgDataModel dataModel, boolean isPrimaryInstance) { - ModelDelegate delegate = Overrides.getObject( - ModelDelegate.class, context, R.string.model_delegate_class); - delegate.init(app, pmHelper, appsList, dataModel, isPrimaryInstance); - return delegate; - } +public class ModelDelegate { protected final Context mContext; - protected PackageManagerHelper mPmHelper; - protected LauncherAppState mApp; + protected LauncherModel mModel; protected AllAppsList mAppsList; protected BgDataModel mDataModel; - protected boolean mIsPrimaryInstance; - public ModelDelegate(Context context) { + @Inject + public ModelDelegate(@ApplicationContext Context context) { mContext = context; } /** * Initializes the object with the given params. */ - private void init(LauncherAppState app, PackageManagerHelper pmHelper, AllAppsList appsList, - BgDataModel dataModel, boolean isPrimaryInstance) { - this.mApp = app; - this.mPmHelper = pmHelper; + public void init(LauncherModel model, AllAppsList appsList, BgDataModel dataModel) { + this.mModel = model; this.mAppsList = appsList; this.mDataModel = dataModel; - this.mIsPrimaryInstance = isPrimaryInstance; } /** Called periodically to validate and update any data */ @WorkerThread public void validateData() { - if (hasShortcutsPermission(mApp.getContext()) - != mAppsList.hasShortcutHostPermission()) { - mApp.getModel().forceReload(); + if (hasShortcutsPermission(mContext) != mAppsList.hasShortcutHostPermission()) { + mModel.forceReload(); } } diff --git a/src/com/android/launcher3/model/ModelInitializer.kt b/src/com/android/launcher3/model/ModelInitializer.kt index 69a320a0e2..735a52aac6 100644 --- a/src/com/android/launcher3/model/ModelInitializer.kt +++ b/src/com/android/launcher3/model/ModelInitializer.kt @@ -38,18 +38,20 @@ import com.android.launcher3.icons.LauncherIcons.IconPool import com.android.launcher3.notification.NotificationListener import com.android.launcher3.pm.InstallSessionHelper import com.android.launcher3.pm.UserCache +import com.android.launcher3.util.DaggerSingletonTracker import com.android.launcher3.util.Executors.MODEL_EXECUTOR import com.android.launcher3.util.Executors.UI_HELPER_EXECUTOR -import com.android.launcher3.util.SafeCloseable import com.android.launcher3.util.SettingsCache import com.android.launcher3.util.SettingsCache.NOTIFICATION_BADGING_URI import com.android.launcher3.util.SettingsCache.PRIVATE_SPACE_HIDE_WHEN_LOCKED_URI import com.android.launcher3.util.SimpleBroadcastReceiver import com.android.launcher3.widget.custom.CustomWidgetManager -import java.util.function.Consumer +import javax.inject.Inject /** Utility class for initializing all model callbacks */ -class ModelInitializer( +class ModelInitializer +@Inject +constructor( @ApplicationContext private val context: Context, private val iconPool: IconPool, private val iconCache: IconCache, @@ -60,7 +62,7 @@ class ModelInitializer( private val iconProvider: LauncherIconProvider, private val customWidgetManager: CustomWidgetManager, private val installSessionHelper: InstallSessionHelper, - private val closeActions: Consumer, + private val lifeCycle: DaggerSingletonTracker, ) { fun initialize(model: LauncherModel) { @@ -75,18 +77,18 @@ class ModelInitializer( if (modelChanged) refreshAndReloadLauncher() } idp.addOnChangeListener(idpChangeListener) - closeActions.accept { idp.removeOnChangeListener(idpChangeListener) } + lifeCycle.addCloseable { idp.removeOnChangeListener(idpChangeListener) } // Theme changes val themeChangeListener = ThemeChangeListener { refreshAndReloadLauncher() } themeManager.addChangeListener(themeChangeListener) - closeActions.accept { themeManager.removeChangeListener(themeChangeListener) } + lifeCycle.addCloseable { themeManager.removeChangeListener(themeChangeListener) } // System changes val modelCallbacks = model.newModelCallbacks() val launcherApps = context.getSystemService(LauncherApps::class.java)!! - launcherApps.registerCallback(modelCallbacks) - closeActions.accept { launcherApps.unregisterCallback(modelCallbacks) } + launcherApps.registerCallback(modelCallbacks, MODEL_EXECUTOR.handler) + lifeCycle.addCloseable { launcherApps.unregisterCallback(modelCallbacks) } if (Utilities.ATLEAST_V && Flags.enableSupportForArchiving()) { launcherApps.setArchiveCompatibility( @@ -101,23 +103,23 @@ class ModelInitializer( val dpUpdateReceiver = SimpleBroadcastReceiver(context, UI_HELPER_EXECUTOR) { model.reloadStringCache() } dpUpdateReceiver.register(ACTION_DEVICE_POLICY_RESOURCE_UPDATED) - closeActions.accept { dpUpdateReceiver.unregisterReceiverSafely() } + lifeCycle.addCloseable { dpUpdateReceiver.unregisterReceiverSafely() } // Development helper if (BuildConfig.IS_STUDIO_BUILD) { val reloadReceiver = SimpleBroadcastReceiver(context, UI_HELPER_EXECUTOR) { model.forceReload() } reloadReceiver.register(Context.RECEIVER_EXPORTED, ACTION_FORCE_RELOAD) - closeActions.accept { reloadReceiver.unregisterReceiverSafely() } + lifeCycle.addCloseable { reloadReceiver.unregisterReceiverSafely() } } // User changes - closeActions.accept(userCache.addUserEventListener(model::onUserEvent)) + lifeCycle.addCloseable(userCache.addUserEventListener(model::onUserEvent)) // Private space settings changes val psSettingsListener = SettingsCache.OnChangeListener { model.forceReload() } settingsCache.register(PRIVATE_SPACE_HIDE_WHEN_LOCKED_URI, psSettingsListener) - closeActions.accept { + lifeCycle.addCloseable { settingsCache.unregister(PRIVATE_SPACE_HIDE_WHEN_LOCKED_URI, psSettingsListener) } @@ -131,7 +133,7 @@ class ModelInitializer( } settingsCache.register(NOTIFICATION_BADGING_URI, notificationChanges) notificationChanges.onSettingsChanged(settingsCache.getValue(NOTIFICATION_BADGING_URI)) - closeActions.accept { + lifeCycle.addCloseable { settingsCache.unregister(NOTIFICATION_BADGING_URI, notificationChanges) } @@ -142,21 +144,21 @@ class ModelInitializer( if (LoaderTask.SMARTSPACE_ON_HOME_SCREEN == key) model.forceReload() } getPrefs(context).registerOnSharedPreferenceChangeListener(smartSpacePrefChanges) - closeActions.accept { + lifeCycle.addCloseable { getPrefs(context).unregisterOnSharedPreferenceChangeListener(smartSpacePrefChanges) } } // Custom widgets - closeActions.accept(customWidgetManager.addWidgetRefreshCallback(model::rebindCallbacks)) + lifeCycle.addCloseable(customWidgetManager.addWidgetRefreshCallback(model::rebindCallbacks)) // Icon changes - closeActions.accept( + lifeCycle.addCloseable( iconProvider.registerIconChangeListener(model::onAppIconChanged, MODEL_EXECUTOR.handler) ) // Install session changes - closeActions.accept(installSessionHelper.registerInstallTracker(modelCallbacks)) + lifeCycle.addCloseable(installSessionHelper.registerInstallTracker(modelCallbacks)) } companion object { diff --git a/src/com/android/launcher3/model/data/ItemInfoWithIcon.java b/src/com/android/launcher3/model/data/ItemInfoWithIcon.java index ff40f30bba..b60b8cc670 100644 --- a/src/com/android/launcher3/model/data/ItemInfoWithIcon.java +++ b/src/com/android/launcher3/model/data/ItemInfoWithIcon.java @@ -22,6 +22,7 @@ import android.content.Context; import android.content.Intent; import android.os.Process; +import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.android.launcher3.Flags; @@ -44,6 +45,7 @@ public abstract class ItemInfoWithIcon extends ItemInfo { /** * The bitmap for the application icon */ + @NonNull public BitmapInfo bitmap = BitmapInfo.LOW_RES_INFO; /** diff --git a/src/com/android/launcher3/provider/RestoreDbTask.java b/src/com/android/launcher3/provider/RestoreDbTask.java index 34c9117f1f..5ad8af2296 100644 --- a/src/com/android/launcher3/provider/RestoreDbTask.java +++ b/src/com/android/launcher3/provider/RestoreDbTask.java @@ -535,7 +535,7 @@ public class RestoreDbTask { } logFavoritesTable(controller.getDb(), "launcher db after remap widget ids", null, null); - LauncherAppState.INSTANCE.executeIfCreated(app -> app.getModel().forceReload()); + LauncherAppState.INSTANCE.get(context).getModel().reloadIfActive(); } private static void logDatabaseWidgetInfo(ModelDbController controller) { diff --git a/src/com/android/launcher3/widget/picker/WidgetRecommendationCategoryProvider.java b/src/com/android/launcher3/widget/picker/WidgetRecommendationCategoryProvider.java index f8dc6b0bb2..8f34fe3572 100644 --- a/src/com/android/launcher3/widget/picker/WidgetRecommendationCategoryProvider.java +++ b/src/com/android/launcher3/widget/picker/WidgetRecommendationCategoryProvider.java @@ -35,19 +35,7 @@ import com.android.launcher3.util.ResourceBasedOverride; * own implementation. Method {@code getWidgetRecommendationCategory} is called per widget to get * the category.

*/ -public class WidgetRecommendationCategoryProvider implements ResourceBasedOverride { - private static final String TAG = "WidgetRecommendationCategoryProvider"; - - /** - * Retrieve instance of this object that can be overridden in runtime based on the build - * variant of the application. - */ - public static WidgetRecommendationCategoryProvider newInstance(Context context) { - Preconditions.assertWorkerThread(); - return Overrides.getObject( - WidgetRecommendationCategoryProvider.class, context.getApplicationContext(), - R.string.widget_recommendation_category_provider_class); - } +public class WidgetRecommendationCategoryProvider { /** * Returns a {@link WidgetRecommendationCategory} for the provided widget item that can be used diff --git a/tests/multivalentTests/src/com/android/launcher3/icons/IconCacheTest.java b/tests/multivalentTests/src/com/android/launcher3/icons/IconCacheTest.java index 9026748f60..0aaf4d7c40 100644 --- a/tests/multivalentTests/src/com/android/launcher3/icons/IconCacheTest.java +++ b/tests/multivalentTests/src/com/android/launcher3/icons/IconCacheTest.java @@ -56,7 +56,7 @@ import androidx.annotation.Nullable; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.filters.SmallTest; -import com.android.launcher3.InvariantDeviceProfile; +import com.android.launcher3.LauncherAppState; import com.android.launcher3.icons.cache.CachingLogic; import com.android.launcher3.icons.cache.IconCacheUpdateHandler; import com.android.launcher3.icons.cache.LauncherActivityCachingLogic; @@ -69,11 +69,13 @@ import com.android.launcher3.shortcuts.ShortcutKey; import com.android.launcher3.util.ApplicationInfoWrapper; import com.android.launcher3.util.ComponentKey; import com.android.launcher3.util.PackageUserKey; +import com.android.launcher3.util.SandboxApplication; import com.google.common.truth.Truth; import org.junit.After; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; @@ -85,20 +87,18 @@ import java.util.Set; @RunWith(AndroidJUnit4.class) public class IconCacheTest { - private Context mContext; + @Rule public SandboxApplication mContext = new SandboxApplication(); + private IconCache mIconCache; private ComponentName mMyComponent; @Before public void setup() { - mContext = getInstrumentation().getTargetContext(); mMyComponent = new ComponentName(mContext, SettingsActivity.class); // In memory icon cache - mIconCache = new IconCache(mContext, - InvariantDeviceProfile.INSTANCE.get(mContext), null, - new LauncherIconProvider(mContext)); + mIconCache = LauncherAppState.getInstance(mContext).getIconCache(); } @After diff --git a/tests/multivalentTests/src/com/android/launcher3/model/AddWorkspaceItemsTaskTest.kt b/tests/multivalentTests/src/com/android/launcher3/model/AddWorkspaceItemsTaskTest.kt index ce0468270d..08b8f81c11 100644 --- a/tests/multivalentTests/src/com/android/launcher3/model/AddWorkspaceItemsTaskTest.kt +++ b/tests/multivalentTests/src/com/android/launcher3/model/AddWorkspaceItemsTaskTest.kt @@ -155,7 +155,7 @@ class AddWorkspaceItemsTaskTest : AbstractWorkspaceModelTest() { private fun verifyItemSpaceFinderCall(nonEmptyScreenIds: List, numberOfExpectedCall: Int) { verify(mWorkspaceItemSpaceFinder, times(numberOfExpectedCall)) .findSpaceForItem( - same(mAppState), + eq(mAppState), same(mModelHelper.bgDataModel), eq(IntArray.wrap(*nonEmptyScreenIds.toIntArray())), eq(IntArray()), diff --git a/tests/multivalentTests/src/com/android/launcher3/model/LoaderCursorTest.java b/tests/multivalentTests/src/com/android/launcher3/model/LoaderCursorTest.java index 11047fb8d4..ad408185b2 100644 --- a/tests/multivalentTests/src/com/android/launcher3/model/LoaderCursorTest.java +++ b/tests/multivalentTests/src/com/android/launcher3/model/LoaderCursorTest.java @@ -70,6 +70,7 @@ import androidx.test.filters.SmallTest; import com.android.launcher3.Flags; import com.android.launcher3.InvariantDeviceProfile; import com.android.launcher3.LauncherAppState; +import com.android.launcher3.icons.BitmapInfo; import com.android.launcher3.icons.LauncherIcons; import com.android.launcher3.model.data.ItemInfo; import com.android.launcher3.model.data.WorkspaceItemInfo; @@ -258,7 +259,6 @@ public class LoaderCursorTest { initCursor(ITEM_TYPE_APPLICATION, "title"); assertTrue(mLoaderCursor.moveToNext()); WorkspaceItemInfo itemInfo = new WorkspaceItemInfo(); - itemInfo.bitmap = null; itemInfo.runtimeStatusFlags |= FLAG_ARCHIVED; Bitmap expectedBitmap = LauncherIcons.obtain(mContext) .createIconBitmap(decodeByteArray(sTestBlob, 0, sTestBlob.length)) @@ -289,7 +289,7 @@ public class LoaderCursorTest { initCursor(ITEM_TYPE_APPLICATION, "title"); assertTrue(mLoaderCursor.moveToNext()); WorkspaceItemInfo itemInfo = new WorkspaceItemInfo(); - itemInfo.bitmap = null; + BitmapInfo original = itemInfo.bitmap; itemInfo.runtimeStatusFlags |= FLAG_ARCHIVED; Intent intent = new Intent(); intent.setComponent(new ComponentName("package", "class")); @@ -297,7 +297,7 @@ public class LoaderCursorTest { // When mLoaderCursor.loadWorkspaceTitleAndIcon(false, false, itemInfo); // Then - assertThat(itemInfo.bitmap).isNull(); + assertThat(itemInfo.bitmap).isEqualTo(original); } @Test diff --git a/tests/multivalentTests/src/com/android/launcher3/util/LauncherModelHelper.java b/tests/multivalentTests/src/com/android/launcher3/util/LauncherModelHelper.java index 09b9a3bf7c..cee5559c39 100644 --- a/tests/multivalentTests/src/com/android/launcher3/util/LauncherModelHelper.java +++ b/tests/multivalentTests/src/com/android/launcher3/util/LauncherModelHelper.java @@ -21,8 +21,8 @@ import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentat import static com.android.launcher3.util.Executors.MAIN_EXECUTOR; import static com.android.launcher3.util.Executors.MODEL_EXECUTOR; -import static com.android.launcher3.util.TestUtil.runOnExecutorSync; import static com.android.launcher3.util.TestUtil.grantWriteSecurePermission; +import static com.android.launcher3.util.TestUtil.runOnExecutorSync; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.eq; @@ -51,6 +51,7 @@ import androidx.test.core.app.ApplicationProvider; import com.android.launcher3.InvariantDeviceProfile; import com.android.launcher3.LauncherAppState; import com.android.launcher3.LauncherModel; +import com.android.launcher3.dagger.LauncherBaseAppComponent; import com.android.launcher3.model.BgDataModel; import com.android.launcher3.model.BgDataModel.Callbacks; import com.android.launcher3.model.ModelDbController; @@ -266,14 +267,6 @@ public class LauncherModelHelper { mDbDir = new File(getCacheDir(), UUID.randomUUID().toString()); } - @Override - public T createObject(MainThreadInitializedObject object) { - if (object == LauncherAppState.INSTANCE) { - return (T) new LauncherAppState(this, null /* iconCacheFileName */); - } - return super.createObject(object); - } - @Override public File getDatabasePath(String name) { if (!mDbDir.exists()) { @@ -342,5 +335,10 @@ public class LauncherModelHelper { } return success; } + + @Override + public void initDaggerComponent(LauncherBaseAppComponent.Builder componentBuilder) { + super.initDaggerComponent(componentBuilder.iconsDbName(null)); + } } } diff --git a/tests/multivalentTests/src/com/android/launcher3/folder/PreviewItemManagerTest.kt b/tests/src/com/android/launcher3/folder/PreviewItemManagerTest.kt similarity index 97% rename from tests/multivalentTests/src/com/android/launcher3/folder/PreviewItemManagerTest.kt rename to tests/src/com/android/launcher3/folder/PreviewItemManagerTest.kt index 15accbda2a..c956395503 100644 --- a/tests/multivalentTests/src/com/android/launcher3/folder/PreviewItemManagerTest.kt +++ b/tests/src/com/android/launcher3/folder/PreviewItemManagerTest.kt @@ -1,5 +1,5 @@ /* - * Copyright (C) 2023 The Android Open Source Project + * 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. @@ -20,6 +20,7 @@ import android.R import android.os.Process import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.SmallTest +import com.android.dx.mockito.inline.extended.ExtendedMockito.spyOn import com.android.launcher3.LauncherAppState import com.android.launcher3.LauncherPrefs import com.android.launcher3.LauncherSettings.Favorites.ITEM_TYPE_FOLDER @@ -61,11 +62,11 @@ import org.junit.rules.TestRule import org.junit.runner.Description import org.junit.runner.RunWith import org.junit.runners.model.Statement +import org.mockito.MockitoAnnotations import org.mockito.kotlin.any import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.doReturn import org.mockito.kotlin.eq -import org.mockito.kotlin.spy import org.mockito.kotlin.verify import org.mockito.kotlin.whenever @@ -85,6 +86,7 @@ class PreviewItemManagerTest { @Before fun setup() { + MockitoAnnotations.initMocks(this) modelHelper = LauncherModelHelper() context = modelHelper.sandboxContext context.initDaggerComponent(DaggerPreviewItemManagerTestComponent.builder()) @@ -93,10 +95,8 @@ class PreviewItemManagerTest { } folderIcon = FolderIcon(ActivityContextWrapper(context)) - val app = spy(LauncherAppState.getInstance(context)) - iconCache = spy(app.iconCache) - doReturn(iconCache).whenever(app).iconCache - context.putObject(LauncherAppState.INSTANCE, app) + iconCache = LauncherAppState.INSTANCE[context].iconCache + spyOn(iconCache) doReturn(null).whenever(iconCache).updateIconInBackground(any(), any()) previewItemManager = PreviewItemManager(folderIcon) diff --git a/tests/src/com/android/launcher3/model/LoaderTaskTest.kt b/tests/src/com/android/launcher3/model/LoaderTaskTest.kt index 8f64e841b8..582cf3c082 100644 --- a/tests/src/com/android/launcher3/model/LoaderTaskTest.kt +++ b/tests/src/com/android/launcher3/model/LoaderTaskTest.kt @@ -14,6 +14,7 @@ import android.provider.Settings import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.SmallTest import com.android.dx.mockito.inline.extended.ExtendedMockito +import com.android.dx.mockito.inline.extended.ExtendedMockito.spyOn import com.android.launcher3.Flags import com.android.launcher3.LauncherAppState import com.android.launcher3.LauncherModel @@ -67,7 +68,6 @@ import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock -import org.mockito.kotlin.spy import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import org.mockito.quality.Strictness @@ -92,7 +92,6 @@ class LoaderTaskTest { ) private lateinit var mockitoSession: MockitoSession - @Mock private lateinit var app: LauncherAppState @Mock private lateinit var bgAllAppsList: AllAppsList @Mock private lateinit var modelDelegate: ModelDelegate @Mock private lateinit var launcherBinder: BaseLauncherBinder @@ -108,6 +107,9 @@ class LoaderTaskTest { @get:Rule val setFlagsRule = SetFlagsRule() + private val app: LauncherAppState + get() = context.appComponent.launcherAppState + @Before fun setup() { MockitoAnnotations.initMocks(this) @@ -118,32 +120,28 @@ class LoaderTaskTest { .strictness(Strictness.LENIENT) .mockStatic(FirstScreenBroadcastHelper::class.java) .startMocking() - val idp = - context.appComponent.idp.apply { - numRows = 5 - numColumns = 6 - numDatabaseHotseatIcons = 5 - } - context.putObject(LauncherAppState.INSTANCE, app) - doReturn(TestViewHelpers.findWidgetProvider(false)) .`when`(context.spyService(AppWidgetManager::class.java)) .getAppWidgetInfo(any()) - `when`(app.context).thenReturn(context) - `when`(app.model).thenReturn(launcherModel) `when`(launcherModel.beginLoader(any())).thenReturn(transaction) - `when`(app.iconCache).thenReturn(iconCache) `when`(launcherModel.modelDbController) .thenReturn(FactitiousDbController(context, INSERTION_STATEMENT_FILE)) - `when`(app.invariantDeviceProfile).thenReturn(idp) `when`(launcherBinder.newIdleLock(any())).thenReturn(idleLock) `when`(idleLock.awaitLocked(1000)).thenReturn(false) `when`(iconCache.getUpdateHandler()).thenReturn(iconCacheUpdateHandler) `when`(widgetsFilterDataProvider.getDefaultWidgetsFilter()).thenReturn(Predicate { true }) context.initDaggerComponent( - DaggerLoaderTaskTest_TestComponent.builder().bindUserCache(userCache) + DaggerLoaderTaskTest_TestComponent.builder() + .bindUserCache(userCache) + .bindIconCache(iconCache) + .bindLauncherModel(launcherModel) ) + context.appComponent.idp.apply { + numRows = 5 + numColumns = 6 + numDatabaseHotseatIcons = 5 + } TestUtil.grantWriteSecurePermission() } @@ -281,8 +279,8 @@ class LoaderTaskTest { @EnableFlags(Flags.FLAG_ENABLE_FIRST_SCREEN_BROADCAST_ARCHIVING_EXTRAS) fun `When broadcast flag on and is restore and secure setting off then send new broadcast`() { // Given - val spyContext = spy(context) - `when`(app.context).thenReturn(spyContext) + spyOn(context) + val spyContext = context whenever( FirstScreenBroadcastHelper.createModelsForFirstScreenBroadcast( any(), @@ -357,8 +355,8 @@ class LoaderTaskTest { @EnableFlags(Flags.FLAG_ENABLE_FIRST_SCREEN_BROADCAST_ARCHIVING_EXTRAS) fun `When not a restore then installed item broadcast not sent`() { // Given - val spyContext = spy(context) - `when`(app.context).thenReturn(spyContext) + spyOn(context) + val spyContext = context whenever( FirstScreenBroadcastHelper.createModelsForFirstScreenBroadcast( any(), @@ -398,8 +396,8 @@ class LoaderTaskTest { @DisableFlags(Flags.FLAG_ENABLE_FIRST_SCREEN_BROADCAST_ARCHIVING_EXTRAS) fun `When broadcast flag off then installed item broadcast not sent`() { // Given - val spyContext = spy(context) - `when`(app.context).thenReturn(spyContext) + spyOn(context) + val spyContext = context whenever( FirstScreenBroadcastHelper.createModelsForFirstScreenBroadcast( any(), @@ -444,8 +442,8 @@ class LoaderTaskTest { @EnableFlags(Flags.FLAG_ENABLE_FIRST_SCREEN_BROADCAST_ARCHIVING_EXTRAS) fun `When failsafe secure setting on then installed item broadcast not sent`() { // Given - val spyContext = spy(context) - `when`(app.context).thenReturn(spyContext) + spyOn(context) + val spyContext = context whenever( FirstScreenBroadcastHelper.createModelsForFirstScreenBroadcast( any(), @@ -644,6 +642,10 @@ class LoaderTaskTest { interface Builder : LauncherAppComponent.Builder { @BindsInstance fun bindUserCache(userCache: UserCache): Builder + @BindsInstance fun bindLauncherModel(model: LauncherModel): Builder + + @BindsInstance fun bindIconCache(iconCache: IconCache): Builder + override fun build(): TestComponent } } From f20b4e9e4fd95239930a77a7e7e23ce4c07be4b3 Mon Sep 17 00:00:00 2001 From: Bill Yi Date: Thu, 20 Feb 2025 20:23:44 -0800 Subject: [PATCH 086/153] Import translations. DO NOT MERGE ANYWHERE Auto-generated-cl: translation import Change-Id: I7b58aa89a399c9d5f79dac7e319414823522ae6c --- quickstep/res/values-fr-rCA/strings.xml | 2 +- quickstep/res/values-uk/strings.xml | 2 +- quickstep/res/values-uz/strings.xml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/quickstep/res/values-fr-rCA/strings.xml b/quickstep/res/values-fr-rCA/strings.xml index e7619c2159..3201886213 100644 --- a/quickstep/res/values-fr-rCA/strings.xml +++ b/quickstep/res/values-fr-rCA/strings.xml @@ -90,7 +90,7 @@ "Tout est prêt!" "Balayez l\'écran vers le haut pour accéder à l\'écran d\'accueil" "Toucher le bouton d\'accueil pour passer sur votre écran d\'accueil" - "Vous êtes maintenant prêt à utiliser votre %1$s" + "Vous êtes maintenant prêt à utiliser votre %1$s." "appareil" "Paramètres de navigation du système" "Partager" diff --git a/quickstep/res/values-uk/strings.xml b/quickstep/res/values-uk/strings.xml index dab58d7715..2313a07b79 100644 --- a/quickstep/res/values-uk/strings.xml +++ b/quickstep/res/values-uk/strings.xml @@ -92,7 +92,7 @@ "Натисніть кнопку головного екрана, щоб відкрити його" "Тепер ви можете використовувати %1$s" "пристрій" - "Системні налаштування навігації" + "Налаштування навігації в системі" "Поділитися" "Знімок екрана" "Розділити" diff --git a/quickstep/res/values-uz/strings.xml b/quickstep/res/values-uz/strings.xml index 1cd2e87f14..06ca97a2a1 100644 --- a/quickstep/res/values-uz/strings.xml +++ b/quickstep/res/values-uz/strings.xml @@ -90,7 +90,7 @@ "Hammasi tayyor!" "Boshiga qaytish uchun tepaga suring" "Bosh ekranga oʻtish uchun bosh ekran tugmasini bosing" - "%1$s xizmatga tayyor" + "Sizning %1$s xizmatga tayyor" "qurilma" "Tizim navigatsiya sozlamalari" "Ulashish" From 77a5570d169fca1156633fa787f62383ae4b0e7b Mon Sep 17 00:00:00 2001 From: Bill Yi Date: Thu, 20 Feb 2025 20:24:33 -0800 Subject: [PATCH 087/153] Import translations. DO NOT MERGE ANYWHERE Auto-generated-cl: translation import Change-Id: I64be39ef9954803287b1eca87bc57b6302211250 --- res/values-bg/strings.xml | 2 +- res/values-bs/strings.xml | 2 +- res/values-cs/strings.xml | 4 ++-- res/values-gu/strings.xml | 2 +- res/values-it/strings.xml | 2 +- res/values-ky/strings.xml | 2 +- res/values-or/strings.xml | 4 ++-- res/values-te/strings.xml | 4 ++-- res/values-tr/strings.xml | 2 +- res/values-ur/strings.xml | 2 +- res/values-zh-rCN/strings.xml | 2 +- 11 files changed, 14 insertions(+), 14 deletions(-) diff --git a/res/values-bg/strings.xml b/res/values-bg/strings.xml index 6d44a97606..98571addce 100644 --- a/res/values-bg/strings.xml +++ b/res/values-bg/strings.xml @@ -62,7 +62,7 @@ "Приспособления" "Търсене" "Изчистване на текста от полето за търсене" - "Няма налице преки пътища и приспособления" + "Няма налични преки пътища и приспособления" "Няма открити преки пътища или приспособления" "Лични" "Служебни" diff --git a/res/values-bs/strings.xml b/res/values-bs/strings.xml index ff8a541022..c0568bf28f 100644 --- a/res/values-bs/strings.xml +++ b/res/values-bs/strings.xml @@ -41,7 +41,7 @@ "Dodirnite i zadržite da pomjerite vidžet." "Dvaput dodirnite i zadržite da pomjerite vidžet ili da koristite prilagođene radnje." "Više opcija" - "Prikazuj sve vidžete" + "Prikaži sve vidžete" "%1$d × %2$d" "Širina %1$d, visina %2$d" "Vidžet %1$s" diff --git a/res/values-cs/strings.xml b/res/values-cs/strings.xml index 2ac7233b54..f96b9079a0 100644 --- a/res/values-cs/strings.xml +++ b/res/values-cs/strings.xml @@ -46,12 +46,12 @@ "šířka %1$d, výška %2$d" "%1$s widget" "Widget %1$s, šířka %2$d, výška %3$d" - "Pokud chcete widgetem pohybovat po ploše, podržte ho" + "Pokud chcete widgetem pohybovat po ploše, podržte ho." "Přidat na plochu" "Widget %1$s byl přidán na plochu" "Návrhy" "Nejdůležitější aplikace" - "Zprávy a časopisy" + "Noviny a časopisy" "Zábava" "Sociální sítě" "Návrhy pro vás" diff --git a/res/values-gu/strings.xml b/res/values-gu/strings.xml index 49252945b3..5a33983b64 100644 --- a/res/values-gu/strings.xml +++ b/res/values-gu/strings.xml @@ -60,7 +60,7 @@ "{count,plural, =1{# શૉર્ટકટ}one{# શૉર્ટકટ}other{# શૉર્ટકટ}}" "%1$s, %2$s" "વિજેટ" - "શોધ" + "શોધો" "શોધ બૉક્સમાંથી ટેક્સ્ટ સાફ કરો" "વિજેટ અને શૉર્ટકટ ઉપલબ્ધ નથી" "કોઈ વિજેટ અથવા શૉર્ટકટ મળ્યા નથી" diff --git a/res/values-it/strings.xml b/res/values-it/strings.xml index 75e7cd28dd..314513367f 100644 --- a/res/values-it/strings.xml +++ b/res/values-it/strings.xml @@ -46,7 +46,7 @@ "%1$d di larghezza per %2$d di altezza" "Widget %1$s" "Widget %1$s, %2$d di larghezza per %3$d di altezza" - "Tocca e tieni premuto il widget per spostarlo nella schermata Home" + "Tieni premuto il widget per spostarlo nella schermata Home" "Aggiungi alla schermata Home" "Widget %1$s aggiunto alla schermata Home" "Suggerimenti" diff --git a/res/values-ky/strings.xml b/res/values-ky/strings.xml index b6b5b66849..b98b61d2cc 100644 --- a/res/values-ky/strings.xml +++ b/res/values-ky/strings.xml @@ -46,7 +46,7 @@ "Туурасы: %1$d, бийиктиги: %2$d" "%1$s виджети" "%1$s виджети, кеңдиги %2$d жана бийиктиги %3$d" - "Башкы экранга жылдыруу үчүн виджетти коё бербей басып туруңуз" + "Вижетти коё бербей басып туруп башкы экранга жылдырыңыз" "Башкы экранга кошуу" "%1$s виджети башкы экранга кошулду" "Сунуштар" diff --git a/res/values-or/strings.xml b/res/values-or/strings.xml index 46aadc00fe..3eb680fb66 100644 --- a/res/values-or/strings.xml +++ b/res/values-or/strings.xml @@ -60,7 +60,7 @@ "{count,plural, =1{#ଟି ସର୍ଟକଟ୍}other{#ଟି ସର୍ଟକଟ୍}}" "%1$s, %2$s" "ୱିଜେଟ୍‌" - "ସନ୍ଧାନ କରନ୍ତୁ" + "ସର୍ଚ୍ଚ କରନ୍ତୁ" "ସନ୍ଧାନ ବାକ୍ସରୁ ଟେକ୍ସଟ୍ ଖାଲି କରନ୍ତୁ" "ୱିଜେଟ୍ ଏବଂ ସର୍ଟକଟଗୁଡ଼ିକ ଉପଲବ୍ଧ ନାହିଁ" "କୌଣସି ୱିଜେଟ କିମ୍ବା ସର୍ଟକଟ ମିଳିଲା ନାହିଁ" @@ -164,7 +164,7 @@ "ହୋମ ସ୍କ୍ରିନରେ ଯୋଗ କରନ୍ତୁ" "ଆଇଟମ୍‌କୁ ଏଠାକୁ ଘୁଞ୍ଚାନ୍ତୁ" "ଆଇଟମକୁ କାଢ଼ି ଦିଆଯାଇଛି" - "ପୂର୍ବବତ କରନ୍ତୁ" + "ଅନଡୁ କରନ୍ତୁ" "ଆଇଟମ୍‌ ଘୁଞ୍ଚାନ୍ତୁ" "%3$sରେ ଧାଡି %1$s ସ୍ତମ୍ଭ %2$sକୁ ମୁଭ କରନ୍ତୁ" "%1$s ସ୍ଥିତିକୁ ନିଅନ୍ତୁ" diff --git a/res/values-te/strings.xml b/res/values-te/strings.xml index 4145fb6433..4b2591299e 100644 --- a/res/values-te/strings.xml +++ b/res/values-te/strings.xml @@ -64,8 +64,8 @@ "సెర్చ్ బాక్స్ నుండి టెక్స్ట్‌ను క్లియర్ చేయండి" "విడ్జెట్‌లు, షార్ట్‌కట్‌లు అందుబాటులో లేవు" "విడ్జెట్‌లు లేదా షార్ట్‌కట్‌లు కనుగొనబడలేదు" - "వ్యక్తిగత గ్యాడ్జెట్స్" - "ఆఫీస్" + "వ్యక్తిగత విడ్జెట్స్" + "వర్క్ విడ్జెట్స్" "సంభాషణలు" "నోట్-టేకింగ్" "యాడ్‌ చేసే (జోడించే) బటన్‌ను చూపండి" diff --git a/res/values-tr/strings.xml b/res/values-tr/strings.xml index cb47400387..3fdae5946a 100644 --- a/res/values-tr/strings.xml +++ b/res/values-tr/strings.xml @@ -31,7 +31,7 @@ "Bölünmüş ekran" "%1$s uygulama bilgileri" "%1$s ile ilgili kullanım ayarları" - "Yeni Pencere" + "Yeni pencere" "Pencereleri yönet" "Uygulama çiftini kaydedin" "%1$s | %2$s" diff --git a/res/values-ur/strings.xml b/res/values-ur/strings.xml index ed002bae0b..855a8c33b2 100644 --- a/res/values-ur/strings.xml +++ b/res/values-ur/strings.xml @@ -32,7 +32,7 @@ "‏%1$s کے لیے ایپ کی معلومات" "‏%1$s کیلئے استعمال کی ترتیبات" "نئی ونڈو" - "‏‫Windows کا نظم کریں" + "ونڈوز کا نظم کریں" "ایپس کے جوڑے کو محفوظ کریں" "%1$s | %2$s" "ایپس کا یہ جوڑا اس آلے پر تعاون یافتہ نہیں ہے" diff --git a/res/values-zh-rCN/strings.xml b/res/values-zh-rCN/strings.xml index cecfedba04..febc8c2764 100644 --- a/res/values-zh-rCN/strings.xml +++ b/res/values-zh-rCN/strings.xml @@ -127,7 +127,7 @@ "文件夹:%1$s,%2$d 个或更多项目" "未命名文件夹" "应用对:“%1$s”和“%2$s”" - "壁纸与个性化" + "壁纸与风格" "修改主屏幕" "主屏幕设置" "已被您的管理员停用" From e0553d7da30fb7e7d6e488bc344bedc1d63b9a06 Mon Sep 17 00:00:00 2001 From: Fengjiang Li Date: Thu, 20 Feb 2025 21:55:05 -0800 Subject: [PATCH 088/153] [Memory Leak] Fix leak of LauncherAppWidgetHostView via StateManager.StateListener Rather than register a StateListener for each LauncherAppWidgetHostView, just register one StateListener which, upon launcher state is changed to NORMAL, iterate over all child views under Workspace and perform a11y action if view tag is set. Fix: 397978703 Test: presubmit Flag: EXEMPT bug fix Change-Id: I044d012b74eaa5356196c5503318fa8ab389ec46 --- res/values/id.xml | 1 + src/com/android/launcher3/CellLayout.java | 16 ++------- src/com/android/launcher3/Workspace.java | 44 +++++++++++++++++------ 3 files changed, 37 insertions(+), 24 deletions(-) diff --git a/res/values/id.xml b/res/values/id.xml index 67692d8fee..78b8308cc9 100644 --- a/res/values/id.xml +++ b/res/values/id.xml @@ -79,6 +79,7 @@ + diff --git a/src/com/android/launcher3/CellLayout.java b/src/com/android/launcher3/CellLayout.java index 257f911852..0ce966b99b 100644 --- a/src/com/android/launcher3/CellLayout.java +++ b/src/com/android/launcher3/CellLayout.java @@ -16,7 +16,6 @@ package com.android.launcher3; -import static com.android.launcher3.LauncherState.NORMAL; import static com.android.launcher3.dragndrop.DraggableView.DRAGGABLE_ICON; import static com.android.launcher3.icons.IconNormalizer.ICON_VISIBLE_AREA_FACTOR; import static com.android.launcher3.util.MultiTranslateDelegate.INDEX_REORDER_PREVIEW_OFFSET; @@ -71,7 +70,6 @@ import com.android.launcher3.dragndrop.DraggableView; import com.android.launcher3.folder.PreviewBackground; import com.android.launcher3.model.data.ItemInfo; import com.android.launcher3.model.data.LauncherAppWidgetInfo; -import com.android.launcher3.statemanager.StateManager; import com.android.launcher3.util.CellAndSpan; import com.android.launcher3.util.GridOccupancy; import com.android.launcher3.util.MSDLPlayerWrapper; @@ -791,18 +789,8 @@ public class CellLayout extends ViewGroup { // Whenever an app is added, if Accessibility service is enabled, focus on that app. if (mActivity instanceof Launcher) { - Launcher.cast(mActivity).getStateManager().addStateListener( - new StateManager.StateListener() { - @Override - public void onStateTransitionComplete(LauncherState finalState) { - if (finalState == NORMAL) { - child.performAccessibilityAction( - AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS, null); - Launcher.cast(mActivity).getStateManager() - .removeStateListener(this); - } - } - }); + child.setTag(R.id.perform_a11y_action_on_launcher_state_normal_tag, + AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); } if (markCells) markCellsAsOccupiedForView(child); diff --git a/src/com/android/launcher3/Workspace.java b/src/com/android/launcher3/Workspace.java index cfb116147c..94ff44145b 100644 --- a/src/com/android/launcher3/Workspace.java +++ b/src/com/android/launcher3/Workspace.java @@ -53,6 +53,7 @@ import android.graphics.Point; import android.graphics.PointF; import android.graphics.Rect; import android.graphics.drawable.Drawable; +import android.os.Bundle; import android.os.Parcelable; import android.util.AttributeSet; import android.util.Log; @@ -299,6 +300,17 @@ public class Workspace extends PagedView private final StatsLogManager mStatsLogManager; private final MSDLPlayerWrapper mMSDLPlayerWrapper; + + private final StateManager.StateListener mAccessibilityDropListener = + new StateListener<>() { + @Override + public void onStateTransitionComplete(LauncherState finalState) { + if (finalState == NORMAL) { + performAccessibilityActionOnViewTree(Workspace.this); + } + } + }; + @Nullable private DragController.DragListener mAccessibilityDragListener; @@ -1454,11 +1466,13 @@ public class Workspace extends PagedView super.onAttachedToWindow(); mWallpaperOffset.setWindowToken(getWindowToken()); computeScroll(); + mLauncher.getStateManager().addStateListener(mAccessibilityDropListener); } protected void onDetachedFromWindow() { super.onDetachedFromWindow(); mWallpaperOffset.setWindowToken(null); + mLauncher.getStateManager().removeStateListener(mAccessibilityDropListener); } @Override @@ -2239,16 +2253,8 @@ public class Workspace extends PagedView // the order of operations in this method related to the StateListener below, please // test that accessibility moves retain focus after accessibility dropping an item. // Accessibility focus must be requested after launcher is back to a normal state - mLauncher.getStateManager().addStateListener(new StateListener() { - @Override - public void onStateTransitionComplete(LauncherState finalState) { - if (finalState == NORMAL) { - cell.performAccessibilityAction( - AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS, null); - mLauncher.getStateManager().removeStateListener(this); - } - } - }); + cell.setTag(R.id.perform_a11y_action_on_launcher_state_normal_tag, + AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); } } @@ -3580,4 +3586,22 @@ public class Workspace extends PagedView onEndStateTransition(); } } + + /** + * Recursively check view tag {@link R.id.perform_a11y_action_on_launcher_state_normal_tag} and + * call {@link View#performAccessibilityAction(int, Bundle)} on view tree. The tag is cleared + * after this call. + */ + private static void performAccessibilityActionOnViewTree(View view) { + Object tag = view.getTag(R.id.perform_a11y_action_on_launcher_state_normal_tag); + if (tag instanceof Integer) { + view.performAccessibilityAction((int) tag, null); + view.setTag(R.id.perform_a11y_action_on_launcher_state_normal_tag, null); + } + if (view instanceof ViewGroup viewgroup) { + for (int i = 0; i < viewgroup.getChildCount(); i++) { + performAccessibilityActionOnViewTree(viewgroup.getChildAt(i)); + } + } + } } From 1c028b7ccb10e5083440b0ad3dbc6138cda45133 Mon Sep 17 00:00:00 2001 From: minch Date: Fri, 21 Feb 2025 16:51:43 +0000 Subject: [PATCH 089/153] Correct the page scrolls of the AddDesktopButton Do not apply the button's grid translation to its page scrolls if it is not showing as a grid,otherwise the `mCurrentPage` may not be set correctly while checking `ensureWithinScrollBounds`. Bug: 396146789 Flag: com.android.window.flags.enable_multiple_desktops_frontend Flag: com.android.window.flags.enable_multiple_desktops_backend Test: m Change-Id: Ia1378a997e681abda60fa1cb3c125660916df4c5 --- quickstep/src/com/android/quickstep/views/AddDesktopButton.kt | 3 +++ quickstep/src/com/android/quickstep/views/RecentsView.java | 4 ++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/quickstep/src/com/android/quickstep/views/AddDesktopButton.kt b/quickstep/src/com/android/quickstep/views/AddDesktopButton.kt index 9f3c017fbe..99437709de 100644 --- a/quickstep/src/com/android/quickstep/views/AddDesktopButton.kt +++ b/quickstep/src/com/android/quickstep/views/AddDesktopButton.kt @@ -91,6 +91,9 @@ class AddDesktopButton @JvmOverloads constructor(context: Context, attrs: Attrib } } + protected fun getScrollAdjustment(showAsGrid: Boolean): Int = + if (showAsGrid) gridTranslationX.toInt() else 0 + private fun getBorderBounds(bounds: Rect) { bounds.set(0, 0, width, height) val outlinePadding = diff --git a/quickstep/src/com/android/quickstep/views/RecentsView.java b/quickstep/src/com/android/quickstep/views/RecentsView.java index c5a76cb067..11e65722f1 100644 --- a/quickstep/src/com/android/quickstep/views/RecentsView.java +++ b/quickstep/src/com/android/quickstep/views/RecentsView.java @@ -6243,8 +6243,8 @@ public abstract class RecentsView< int addDesktopButtonIndex = indexOfChild(mAddDesktopButton); if (addDesktopButtonIndex != -1 && addDesktopButtonIndex < outPageScrolls.length) { outPageScrolls[addDesktopButtonIndex] = - newPageScrolls[addDesktopButtonIndex] + Math.round( - mAddDesktopButton.getGridTranslationX()); + newPageScrolls[addDesktopButtonIndex] + mAddDesktopButton.getScrollAdjustment( + showAsGrid); } int lastTaskScroll = getLastTaskScroll(clearAllScroll, clearAllWidth); From dafc2d4c42437ec096f16d2e50ce621175caca9b Mon Sep 17 00:00:00 2001 From: Ahmed Fakhry Date: Thu, 20 Feb 2025 06:47:07 +0000 Subject: [PATCH 090/153] Add `deskId` to `DesktopTask`. Now that `GroupedTaskInfo` propagates the `deskId` from Shell (see ag/31825217), we need to plumb this value in Launcher through `DesktopTask`. Future CLs will use this value in Overview. Bug: 395911284 Test: m, modified existing tests. Flag: com.android.window.flags.enable_multiple_desktops_frontend Flag: com.android.window.flags.enable_multiple_desktops_backend Change-Id: I396250e0cac761c4c5f7e8b2d6cddbe68e646217 --- .../DesktopVisibilityController.kt | 16 +++++++++++- .../android/quickstep/RecentTasksList.java | 21 ++++++++++++---- .../com/android/quickstep/util/DesktopTask.kt | 10 +++++--- .../android/quickstep/views/RecentsView.java | 6 ++++- .../launcher3/taskbar/TaskbarOverflowTest.kt | 2 +- .../TaskbarRecentAppsControllerTest.kt | 2 +- .../recents/data/TasksRepositoryTest.kt | 2 +- .../android/quickstep/util/DesktopTaskTest.kt | 25 ++++++++++++------- .../android/quickstep/util/GroupTaskTest.kt | 2 +- 9 files changed, 62 insertions(+), 24 deletions(-) diff --git a/quickstep/src/com/android/launcher3/statehandlers/DesktopVisibilityController.kt b/quickstep/src/com/android/launcher3/statehandlers/DesktopVisibilityController.kt index 6ee43ff04d..138f40a2dd 100644 --- a/quickstep/src/com/android/launcher3/statehandlers/DesktopVisibilityController.kt +++ b/quickstep/src/com/android/launcher3/statehandlers/DesktopVisibilityController.kt @@ -152,6 +152,20 @@ constructor( } } + /** + * Returns the ID of the active desk (if any) on the display whose ID is [displayId], or + * [INACTIVE_DESK_ID] if no desk is currently active or the multiple desks feature is disabled. + */ + fun getActiveDeskId(displayId: Int): Int { + if (!DesktopModeStatus.enableMultipleDesktops(context)) { + // When the multiple desks feature is disabled, callers should not rely on the concept + // of a desk ID. + return INACTIVE_DESK_ID + } + + return getDisplayDeskConfig(displayId)?.activeDeskId ?: INACTIVE_DESK_ID + } + /** Returns whether a desk is currently active on the display with the given [displayId]. */ fun isInDesktopMode(displayId: Int): Boolean { if (!DesktopModeStatus.enableMultipleDesktops(context)) { @@ -615,6 +629,6 @@ constructor( private const val TAG = "DesktopVisController" private const val DEBUG = false - private const val INACTIVE_DESK_ID = -1 + public const val INACTIVE_DESK_ID = -1 } } diff --git a/quickstep/src/com/android/quickstep/RecentTasksList.java b/quickstep/src/com/android/quickstep/RecentTasksList.java index 561bab4e62..2c4c2f9806 100644 --- a/quickstep/src/com/android/quickstep/RecentTasksList.java +++ b/quickstep/src/com/android/quickstep/RecentTasksList.java @@ -32,10 +32,12 @@ import android.content.Context; import android.os.Process; import android.os.RemoteException; import android.util.SparseBooleanArray; +import android.window.DesktopExperienceFlags; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; +import com.android.launcher3.statehandlers.DesktopVisibilityController; import com.android.launcher3.util.LooperExecutor; import com.android.launcher3.util.SplitConfigurationOptions; import com.android.quickstep.util.DesktopTask; @@ -354,8 +356,8 @@ public class RecentTasksList { int numVisibleTasks = 0; for (GroupedTaskInfo rawTask : rawTasks) { if (rawTask.isBaseType(TYPE_DESK)) { - // TYPE_FREEFORM tasks is only created when desktop mode can be entered, - // leftover TYPE_FREEFORM tasks created when flag was on should be ignored. + // TYPE_DESK tasks is only created when desktop mode can be entered, + // leftover TYPE_DESK tasks created when flag was on should be ignored. if (DesktopModeStatus.canEnterDesktopMode(mContext)) { List desktopTasks = createDesktopTasks( rawTask.getBaseGroupedTask()); @@ -442,7 +444,11 @@ public class RecentTasksList { Set minimizedTaskIds = minimizedTaskIdArray != null ? CollectionsKt.toSet(ArraysKt.asIterable(minimizedTaskIdArray)) : Collections.emptySet(); - if (enableSeparateExternalDisplayTasks()) { + if (enableSeparateExternalDisplayTasks() + && !DesktopExperienceFlags.ENABLE_MULTIPLE_DESKTOPS_BACKEND.isTrue()) { + // This code is not needed when the multiple desktop feature is enabled, since Shell + // will send a single `GroupedTaskInfo` for each desk with a unique `deskId` across + // all displays. Map> perDisplayTasks = new HashMap<>(); for (TaskInfo taskInfo : recentTaskInfo.getTaskInfoList()) { Task task = createTask(taskInfo, minimizedTaskIds); @@ -450,11 +456,16 @@ public class RecentTasksList { k -> new ArrayList<>()); tasks.add(task); } - return MapsKt.map(perDisplayTasks, it -> new DesktopTask(it.getValue())); + // When the multiple desktop feature is disabled, there can only be up to a single desk + // on each display, The desk ID doesn't matter and should not be used. + return MapsKt.map(perDisplayTasks, + it -> new DesktopTask(DesktopVisibilityController.INACTIVE_DESK_ID, + it.getValue())); } else { + final int deskId = recentTaskInfo.getDeskId(); List tasks = CollectionsKt.map(recentTaskInfo.getTaskInfoList(), it -> createTask(it, minimizedTaskIds)); - return List.of(new DesktopTask(tasks)); + return List.of(new DesktopTask(deskId, tasks)); } } diff --git a/quickstep/src/com/android/quickstep/util/DesktopTask.kt b/quickstep/src/com/android/quickstep/util/DesktopTask.kt index 53ea022a23..fbe3bc64d0 100644 --- a/quickstep/src/com/android/quickstep/util/DesktopTask.kt +++ b/quickstep/src/com/android/quickstep/util/DesktopTask.kt @@ -20,17 +20,19 @@ import com.android.systemui.shared.recents.model.Task /** * A [Task] container that can contain N number of tasks that are part of the desktop in recent - * tasks list. Note that desktops can be empty with no tasks in them. + * tasks list. Note that desktops can be empty with no tasks in them. The [deskId] makes sense only + * when the multiple desks feature is enabled. */ -class DesktopTask(tasks: List) : GroupTask(tasks, TaskViewType.DESKTOP) { +class DesktopTask(val deskId: Int, tasks: List) : GroupTask(tasks, TaskViewType.DESKTOP) { - override fun copy() = DesktopTask(tasks) + override fun copy() = DesktopTask(deskId, tasks) - override fun toString() = "type=$taskViewType tasks=$tasks" + override fun toString() = "type=$taskViewType deskId=$deskId tasks=$tasks" override fun equals(o: Any?): Boolean { if (this === o) return true if (o !is DesktopTask) return false + if (deskId != o.deskId) return false return super.equals(o) } } diff --git a/quickstep/src/com/android/quickstep/views/RecentsView.java b/quickstep/src/com/android/quickstep/views/RecentsView.java index c5a76cb067..36af01a2e1 100644 --- a/quickstep/src/com/android/quickstep/views/RecentsView.java +++ b/quickstep/src/com/android/quickstep/views/RecentsView.java @@ -3044,8 +3044,12 @@ public abstract class RecentsView< // Add an empty view for now until the task plan is loaded and applied final TaskView taskView; if (needDesktopTask) { + final int activeDeskId = + DesktopVisibilityController.INSTANCE.get(mContext).getActiveDeskId( + mContainer.getDisplay().getDisplayId()); taskView = getTaskViewFromPool(TaskViewType.DESKTOP); - ((DesktopTaskView) taskView).bind(new DesktopTask(Arrays.asList(runningTasks)), + ((DesktopTaskView) taskView).bind( + new DesktopTask(activeDeskId, Arrays.asList(runningTasks)), mOrientationState, mTaskOverlayFactory); } else if (needGroupTaskView) { taskView = getTaskViewFromPool(TaskViewType.GROUPED); 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 bfd53ef480..2cd09cc4a1 100644 --- a/quickstep/tests/multivalentTests/src/com/android/launcher3/taskbar/TaskbarOverflowTest.kt +++ b/quickstep/tests/multivalentTests/src/com/android/launcher3/taskbar/TaskbarOverflowTest.kt @@ -332,7 +332,7 @@ class TaskbarOverflowTest { (0..().apply { if (!runningTasks.isEmpty()) { - add(DesktopTask(ArrayList(runningTasks))) + add(DesktopTask(deskId = 0, ArrayList(runningTasks))) } addAll(recentTasks) } 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 10be6fdb96..6790567a85 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 @@ -64,7 +64,7 @@ class TasksRepositoryTest { /* snapPosition = */ SNAP_TO_2_50_50, ), ), - DesktopTask(tasks.subList(3, 6)), + DesktopTask(deskId = 0, tasks.subList(3, 6)), ) private val recentsModel = FakeRecentTasksDataSource() private val taskThumbnailDataSource = FakeTaskThumbnailDataSource() diff --git a/quickstep/tests/multivalentTests/src/com/android/quickstep/util/DesktopTaskTest.kt b/quickstep/tests/multivalentTests/src/com/android/quickstep/util/DesktopTaskTest.kt index 7aed579f44..6fbf4823b7 100644 --- a/quickstep/tests/multivalentTests/src/com/android/quickstep/util/DesktopTaskTest.kt +++ b/quickstep/tests/multivalentTests/src/com/android/quickstep/util/DesktopTaskTest.kt @@ -29,35 +29,42 @@ class DesktopTaskTest { @Test fun testDesktopTask_sameInstance_isEqual() { - val task = DesktopTask(createTasks(1)) + val task = DesktopTask(deskId = 0, createTasks(1)) assertThat(task).isEqualTo(task) } @Test fun testDesktopTask_identicalConstructor_isEqual() { - val task1 = DesktopTask(createTasks(1)) - val task2 = DesktopTask(createTasks(1)) + val task1 = DesktopTask(deskId = 0, createTasks(1)) + val task2 = DesktopTask(deskId = 0, createTasks(1)) assertThat(task1).isEqualTo(task2) } @Test fun testDesktopTask_copy_isEqual() { - val task1 = DesktopTask(createTasks(1)) + val task1 = DesktopTask(deskId = 0, createTasks(1)) val task2 = task1.copy() assertThat(task1).isEqualTo(task2) } @Test - fun testDesktopTask_differentId_isNotEqual() { - val task1 = DesktopTask(createTasks(1)) - val task2 = DesktopTask(createTasks(2)) + fun testDesktopTask_differentDeskIds_isNotEqual() { + val task1 = DesktopTask(deskId = 0, createTasks(1)) + val task2 = DesktopTask(deskId = 1, createTasks(1)) + assertThat(task1).isNotEqualTo(task2) + } + + @Test + fun testDesktopTask_differentTaskIds_isNotEqual() { + val task1 = DesktopTask(deskId = 0, createTasks(1)) + val task2 = DesktopTask(deskId = 0, createTasks(2)) assertThat(task1).isNotEqualTo(task2) } @Test fun testDesktopTask_differentLength_isNotEqual() { - val task1 = DesktopTask(createTasks(1)) - val task2 = DesktopTask(createTasks(1, 2)) + val task1 = DesktopTask(deskId = 0, createTasks(1)) + val task2 = DesktopTask(deskId = 0, createTasks(1, 2)) assertThat(task1).isNotEqualTo(task2) } diff --git a/quickstep/tests/multivalentTests/src/com/android/quickstep/util/GroupTaskTest.kt b/quickstep/tests/multivalentTests/src/com/android/quickstep/util/GroupTaskTest.kt index fa043b969a..67fc62f772 100644 --- a/quickstep/tests/multivalentTests/src/com/android/quickstep/util/GroupTaskTest.kt +++ b/quickstep/tests/multivalentTests/src/com/android/quickstep/util/GroupTaskTest.kt @@ -98,7 +98,7 @@ class GroupTaskTest { @Test fun testGroupTask_differentType_isNotEqual() { val task1 = SingleTask(createTask(1)) - val task2 = DesktopTask(listOf(createTask(1))) + val task2 = DesktopTask(deskId = 0, listOf(createTask(1))) assertThat(task1).isNotEqualTo(task2) } From 7d4767989272539bb8eb42956d369bab076ab434 Mon Sep 17 00:00:00 2001 From: Alex Chau Date: Tue, 18 Feb 2025 18:07:34 +0000 Subject: [PATCH 091/153] Fix jump when dismissing last grid task View - Calcualte the scroll diff to bring large tile to middle of screen - Additional compensate for scroll diff between last task and ClearAllButton if ClearAllButton is visible Fix: 395883390 Test: manual, not adding e2e because animation jump cannot be caught by e2e test Flag: com.android.launcher3.enable_grid_only_overview Change-Id: I6a506f2af46ded4daf21fe49329ab71b59e3f19d --- .../com/android/quickstep/views/RecentsView.java | 16 ++++++++++++++++ .../android/quickstep/views/RecentsViewUtils.kt | 3 +++ 2 files changed, 19 insertions(+) diff --git a/quickstep/src/com/android/quickstep/views/RecentsView.java b/quickstep/src/com/android/quickstep/views/RecentsView.java index 1ca14a5dae..d719fd96a5 100644 --- a/quickstep/src/com/android/quickstep/views/RecentsView.java +++ b/quickstep/src/com/android/quickstep/views/RecentsView.java @@ -3901,6 +3901,22 @@ public abstract class RecentsView< // the only invariant point in landscape split screen. snapToLastTask = true; } + if (mUtils.getGridTaskCount() == 1 && dismissedTaskView.isGridTask()) { + TaskView lastLargeTile = mUtils.getLastLargeTaskView(); + if (lastLargeTile != null) { + // Calculate the distance to put last large tile back to middle of the screen. + int primaryScroll = getPagedOrientationHandler().getPrimaryScroll(this); + int lastLargeTileScroll = getScrollForPage(indexOfChild(lastLargeTile)); + longGridRowWidthDiff = primaryScroll - lastLargeTileScroll; + + if (!isClearAllHidden) { + // If ClearAllButton is visible, reduce the distance by scroll difference + // between ClearAllButton and the last task. + longGridRowWidthDiff += getLastTaskScroll(/*clearAllScroll=*/0, + getPagedOrientationHandler().getPrimarySize(mClearAllButton)); + } + } + } // If we need to animate the grid to compensate the clear all gap, we split the second // half of the dismiss pending animation (in which the non-dismissed tasks slide into diff --git a/quickstep/src/com/android/quickstep/views/RecentsViewUtils.kt b/quickstep/src/com/android/quickstep/views/RecentsViewUtils.kt index f742ec3898..c62b804f7d 100644 --- a/quickstep/src/com/android/quickstep/views/RecentsViewUtils.kt +++ b/quickstep/src/com/android/quickstep/views/RecentsViewUtils.kt @@ -84,6 +84,9 @@ class RecentsViewUtils(private val recentsView: RecentsView<*, *>) { /** Counts [TaskView]s that are large tiles. */ fun getLargeTileCount(): Int = taskViews.count { it.isLargeTile } + /** Counts [TaskView]s that are grid tasks. */ + fun getGridTaskCount(): Int = taskViews.count { it.isGridTask } + /** Returns the first TaskView that should be displayed as a large tile. */ fun getFirstLargeTaskView(): TaskView? = taskViews.firstOrNull { From 1393d559c274c543a0a941d70a133caa9b40ab6a Mon Sep 17 00:00:00 2001 From: Saumya Prakash Date: Wed, 19 Feb 2025 20:00:25 +0000 Subject: [PATCH 092/153] Update gesture nav tutorial to new font style This change applies the new expressive font style if the expressive theme is enabled. Screenshots are available in the bug Fix: 393615349 Test: Check that the fonts change when the expressive theme is enabled Flag: com.android.launcher3.expressive_theme_in_taskbar_and_navigation Change-Id: Ib67e81edfd7aa125b9aa824946616c02e24c13e6 --- .../launcher3/taskbar/TypefaceUtils.kt | 7 +++-- .../interaction/TutorialController.java | 30 +++++++++++++++++-- 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/quickstep/src/com/android/launcher3/taskbar/TypefaceUtils.kt b/quickstep/src/com/android/launcher3/taskbar/TypefaceUtils.kt index 8b53ff192a..e9c62d19c9 100644 --- a/quickstep/src/com/android/launcher3/taskbar/TypefaceUtils.kt +++ b/quickstep/src/com/android/launcher3/taskbar/TypefaceUtils.kt @@ -30,11 +30,14 @@ import com.android.launcher3.Flags class TypefaceUtils { companion object { - const val FONT_FAMILY_HEADLINE_SMALL_EMPHASIZED = "variable-headline-small-emphasized" - const val FONT_FAMILY_HEADLINE_LARGE_EMPHASIZED = "variable-headline-large-emphasized" const val FONT_FAMILY_BODY_SMALL_BASELINE = "variable-body-small" const val FONT_FAMILY_BODY_MEDIUM_BASELINE = "variable-body-medium" + const val FONT_FAMILY_BODY_LARGE_BASELINE = "variable-body-large" const val FONT_FAMILY_LABEL_LARGE_BASELINE = "variable-label-large" + const val FONT_FAMILY_DISPLAY_SMALL_EMPHASIZED = "variable-display-small-emphasized" + const val FONT_FAMILY_DISPLAY_MEDIUM_EMPHASIZED = "variable-display-medium-emphasized" + const val FONT_FAMILY_HEADLINE_SMALL_EMPHASIZED = "variable-headline-small-emphasized" + const val FONT_FAMILY_HEADLINE_LARGE_EMPHASIZED = "variable-headline-large-emphasized" @JvmStatic @JvmOverloads diff --git a/quickstep/src/com/android/quickstep/interaction/TutorialController.java b/quickstep/src/com/android/quickstep/interaction/TutorialController.java index 0fc95e2102..e73fb3b67c 100644 --- a/quickstep/src/com/android/quickstep/interaction/TutorialController.java +++ b/quickstep/src/com/android/quickstep/interaction/TutorialController.java @@ -57,6 +57,7 @@ import com.android.launcher3.DeviceProfile; import com.android.launcher3.R; import com.android.launcher3.Utilities; import com.android.launcher3.anim.AnimatorListeners; +import com.android.launcher3.taskbar.TypefaceUtils; import com.android.launcher3.views.ClipIconView; import com.android.quickstep.interaction.EdgeBackGestureHandler.BackGestureAttemptCallback; import com.android.quickstep.interaction.NavBarGestureHandler.NavBarGestureAttemptCallback; @@ -177,6 +178,7 @@ abstract class TutorialController implements BackGestureAttemptCallback, mFeedbackTitleView.setText(getIntroductionTitle()); mFeedbackSubtitleView.setText(getIntroductionSubtitle()); + setTitleTypefaces(); mExitingAppView.setClipToOutline(true); mExitingAppView.setOutlineProvider(new ViewOutlineProvider() { @@ -434,6 +436,10 @@ abstract class TutorialController implements BackGestureAttemptCallback, if (isGestureSuccessful) { if (mTutorialFragment.isAtFinalStep()) { + TypefaceUtils.setTypeface( + mDoneButton, + TypefaceUtils.FONT_FAMILY_LABEL_LARGE_BASELINE + ); showActionButton(); } @@ -458,7 +464,8 @@ abstract class TutorialController implements BackGestureAttemptCallback, pauseAndHideLottieAnimation(); mCheckmarkAnimation.setVisibility(View.VISIBLE); mCheckmarkAnimation.playAnimation(); - mFeedbackTitleView.setTextAppearance(mContext, getSuccessTitleTextAppearance()); + mFeedbackTitleView.setTextAppearance(getSuccessTitleTextAppearance()); + setTitleTypefaces(); } public boolean isGestureCompleted() { @@ -513,8 +520,10 @@ abstract class TutorialController implements BackGestureAttemptCallback, updateDrawables(); updateLayout(); - mFeedbackTitleView.setTextAppearance(mContext, getTitleTextAppearance()); - mDoneButton.setTextAppearance(mContext, getDoneButtonTextAppearance()); + mFeedbackTitleView.setTextAppearance(getTitleTextAppearance()); + mDoneButton.setTextAppearance(getDoneButtonTextAppearance()); + + setTitleTypefaces(); mDoneButton.getBackground().setTint(getDoneButtonColor()); mCheckmarkAnimation.setAnimation(mTutorialFragment.isAtFinalStep() ? R.raw.checkmark_animation_end @@ -533,6 +542,21 @@ abstract class TutorialController implements BackGestureAttemptCallback, } } + /** + * Apply expressive typefaces to the feedback title and subtitle views. + */ + private void setTitleTypefaces() { + TypefaceUtils.setTypeface( + mFeedbackTitleView, + mTutorialFragment.isLargeScreen() + ? TypefaceUtils.FONT_FAMILY_DISPLAY_MEDIUM_EMPHASIZED + : TypefaceUtils.FONT_FAMILY_DISPLAY_SMALL_EMPHASIZED); + TypefaceUtils.setTypeface( + mFeedbackSubtitleView, + TypefaceUtils.FONT_FAMILY_BODY_LARGE_BASELINE + ); + } + protected void resetViewsForBackGesture() { mFakeTaskView.setVisibility(View.VISIBLE); mFakeTaskView.setBackgroundColor(getFakeTaskViewColor()); From de15672e6fea7adeb2cfe2f50678ba0bf9b2177e Mon Sep 17 00:00:00 2001 From: Charlie Anderson Date: Fri, 21 Feb 2025 20:04:34 +0000 Subject: [PATCH 093/153] Initialize shape with PreviewContext init and remove nullability Bug: 372887760 Bug: 348664593 Flag: com.android.launcher3.enable_launcher_icon_shapes Test: previewing shapes with flag on/off Change-Id: I4d7278c54a0d69e38142d31dd7a9605a74db3348 --- .../graphics/GridCustomizationsProxy.java | 4 +++- .../graphics/LauncherPreviewRenderer.java | 4 +++- .../launcher3/graphics/PreviewSurfaceRenderer.java | 14 ++++++-------- 3 files changed, 12 insertions(+), 10 deletions(-) diff --git a/src/com/android/launcher3/graphics/GridCustomizationsProxy.java b/src/com/android/launcher3/graphics/GridCustomizationsProxy.java index 01c9d7ec4f..062c753758 100644 --- a/src/com/android/launcher3/graphics/GridCustomizationsProxy.java +++ b/src/com/android/launcher3/graphics/GridCustomizationsProxy.java @@ -377,7 +377,9 @@ public class GridCustomizationsProxy implements ProxyProvider { if (Flags.newCustomizationPickerUi() && com.android.launcher3.Flags.enableLauncherIconShapes()) { String shapeKey = message.getData().getString(KEY_SHAPE_KEY); - renderer.updateShape(shapeKey); + if (!TextUtils.isEmpty(shapeKey)) { + renderer.updateShape(shapeKey); + } } break; case MESSAGE_ID_UPDATE_GRID: diff --git a/src/com/android/launcher3/graphics/LauncherPreviewRenderer.java b/src/com/android/launcher3/graphics/LauncherPreviewRenderer.java index 332a6bbc36..740b87b02e 100644 --- a/src/com/android/launcher3/graphics/LauncherPreviewRenderer.java +++ b/src/com/android/launcher3/graphics/LauncherPreviewRenderer.java @@ -28,6 +28,7 @@ import static com.android.launcher3.LauncherPrefs.GRID_NAME; import static com.android.launcher3.LauncherSettings.Favorites.CONTAINER_HOTSEAT; import static com.android.launcher3.LauncherSettings.Favorites.CONTAINER_HOTSEAT_PREDICTION; import static com.android.launcher3.Utilities.SHOULD_SHOW_FIRST_PAGE_WIDGET; +import static com.android.launcher3.graphics.ThemeManager.PREF_ICON_SHAPE; import static com.android.launcher3.model.ModelUtils.currentScreenContentFilter; import android.app.Fragment; @@ -137,12 +138,13 @@ public class LauncherPreviewRenderer extends ContextWrapper private final String mPrefName; - public PreviewContext(Context base, String gridName) { + public PreviewContext(Context base, String gridName, String shapeKey) { super(base); mPrefName = "preview-" + UUID.randomUUID().toString(); LauncherPrefs prefs = new ProxyPrefs(this, getSharedPreferences(mPrefName, MODE_PRIVATE)); prefs.put(GRID_NAME, gridName); + prefs.put(PREF_ICON_SHAPE, shapeKey); initDaggerComponent( DaggerLauncherPreviewRenderer_PreviewAppComponent.builder().bindPrefs(prefs)); } diff --git a/src/com/android/launcher3/graphics/PreviewSurfaceRenderer.java b/src/com/android/launcher3/graphics/PreviewSurfaceRenderer.java index 6fe5804da6..4dd9c5bea5 100644 --- a/src/com/android/launcher3/graphics/PreviewSurfaceRenderer.java +++ b/src/com/android/launcher3/graphics/PreviewSurfaceRenderer.java @@ -73,7 +73,6 @@ import com.android.systemui.shared.Flags; import java.util.ArrayList; import java.util.Map; -import java.util.Objects; import java.util.concurrent.TimeUnit; /** Render preview using surface view. */ @@ -120,6 +119,7 @@ public class PreviewSurfaceRenderer { if (mGridName == null) { mGridName = LauncherPrefs.get(context).get(GRID_NAME); } + mShapeKey = LauncherPrefs.get(context).get(PREF_ICON_SHAPE); mWallpaperColors = bundle.getParcelable(KEY_COLORS); if (Flags.newCustomizationPickerUi()) { updateColorOverrides(bundle); @@ -225,8 +225,8 @@ public class PreviewSurfaceRenderer { * * @param shapeKey key for the IconShape model */ - public void updateShape(@Nullable String shapeKey) { - if (Objects.equals(mShapeKey, shapeKey)) { + public void updateShape(String shapeKey) { + if (shapeKey.equals(mShapeKey)) { Log.w(TAG, "Preview shape already set, skipping. shape=" + mShapeKey); return; } @@ -332,12 +332,10 @@ public class PreviewSurfaceRenderer { private void loadModelData() { final Context inflationContext = getPreviewContext(); if (!mGridName.equals(LauncherPrefs.INSTANCE.get(mContext).get(GRID_NAME)) - || mShapeKey != null) { + || !mShapeKey.equals(LauncherPrefs.INSTANCE.get(mContext).get(PREF_ICON_SHAPE))) { // Start the migration - PreviewContext previewContext = new PreviewContext(inflationContext, mGridName); - if (mShapeKey != null) { - LauncherPrefs.INSTANCE.get(previewContext).put(PREF_ICON_SHAPE, mShapeKey); - } + PreviewContext previewContext = + new PreviewContext(inflationContext, mGridName, mShapeKey); // Copy existing data to preview DB LauncherDbUtils.copyTable(LauncherAppState.getInstance(mContext) .getModel().getModelDbController().getDb(), From 9e50a01e926ec2e4acd0114e081c725e92d0e514 Mon Sep 17 00:00:00 2001 From: Charlie Anderson Date: Fri, 21 Feb 2025 13:55:24 -0500 Subject: [PATCH 094/153] Simplify some package update logic around restoring archived/unarchived shortcuts - also avoids race condition where unarchived shortcut is not pinned in shortcut service after restore, and then marked as broken Bug: 375414891 Test: Launcher B&R w/ archiving Flag: com.android.launcher3.restore_archived_shortcuts Change-Id: I2b5331117be93d66e4acbded49b65cd5ce9f8f83 --- .../launcher3/model/PackageUpdatedTask.java | 30 +++++++++++-------- 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/src/com/android/launcher3/model/PackageUpdatedTask.java b/src/com/android/launcher3/model/PackageUpdatedTask.java index d1eceb905a..3cdb2500e1 100644 --- a/src/com/android/launcher3/model/PackageUpdatedTask.java +++ b/src/com/android/launcher3/model/PackageUpdatedTask.java @@ -239,25 +239,31 @@ public class PackageUpdatedTask implements ModelUpdateTask { boolean isTargetValid = !cn.getClassName().equals( IconCache.EMPTY_CLASS_NAME); if (itemInfo.itemType == ITEM_TYPE_DEEP_SHORTCUT) { + int requestQuery = ShortcutRequest.PINNED; + if (Flags.restoreArchivedShortcuts()) { + // Avoid race condition where shortcut service has no record of + // unarchived shortcut being pinned after restore. + // Launcher should be source-of-truth for if shortcut is pinned. + requestQuery = ShortcutRequest.ALL; + } List shortcut = new ShortcutRequest(context, mUser) .forPackage(cn.getPackageName(), itemInfo.getDeepShortcutId()) - .query(ShortcutRequest.PINNED); - if (shortcut.isEmpty() - && !(Flags.restoreArchivedShortcuts() - && !itemInfo.isArchived()) - ) { + .query(requestQuery); + if (shortcut.isEmpty()) { isTargetValid = false; if (DEBUG) { - Log.d(TAG, "Pinned Shortcut not found for updated" - + " package=" + itemInfo.getTargetPackage()); - } - } else if (!shortcut.isEmpty()) { - if (DEBUG) { - Log.d(TAG, "Found pinned shortcut for updated" + Log.d(TAG, "Shortcut not found for updated" + " package=" + itemInfo.getTargetPackage() - + ", isTargetValid=" + isTargetValid); + + ", isArchived=" + itemInfo.isArchived()); + } + } else { + if (DEBUG) { + Log.d(TAG, "Found shortcut for updated" + + " package=" + itemInfo.getTargetPackage() + + ", isTargetValid=" + isTargetValid + + ", isArchived=" + itemInfo.isArchived()); } itemInfo.updateFromDeepShortcutInfo(shortcut.get(0), context); infoUpdated = true; From 6aca9bedd532c258cb5ed8f049451735d312f85d Mon Sep 17 00:00:00 2001 From: Xiaoqian Dai Date: Sat, 1 Feb 2025 03:06:08 +0000 Subject: [PATCH 095/153] desktop-exploded-view: Implement the close button and its behavior Flag: com.android.launcher3.enable_desktop_exploded_view Test: Manual + newly added tapl tests in a following CL Bug: 353965691 Change-Id: Iba4603b84928885b1d50f5551adbacbd31e98cc3 --- .../res/layout/task_thumbnail_view_header.xml | 2 + .../quickstep/TaskShortcutFactory.java | 2 +- .../recents/ui/mapper/TaskUiStateMapper.kt | 43 ++++++++--- .../task/thumbnail/TaskThumbnailUiState.kt | 7 +- .../quickstep/views/DesktopTaskView.kt | 73 +++++++++++++------ .../quickstep/views/RecentsDismissUtils.kt | 2 +- .../android/quickstep/views/RecentsView.java | 22 ++++-- .../android/quickstep/views/TaskContainer.kt | 15 +++- .../views/TaskThumbnailViewHeader.kt | 3 + .../com/android/quickstep/views/TaskView.kt | 21 +++++- .../ui/mapper/TaskUiStateMapperTest.kt | 21 +++++- 11 files changed, 164 insertions(+), 47 deletions(-) diff --git a/quickstep/res/layout/task_thumbnail_view_header.xml b/quickstep/res/layout/task_thumbnail_view_header.xml index ecc1559c10..70e4a42b41 100644 --- a/quickstep/res/layout/task_thumbnail_view_header.xml +++ b/quickstep/res/layout/task_thumbnail_view_header.xml @@ -18,6 +18,7 @@ xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" + android:id="@+id/task_thumbnail_view_header" android:background="@drawable/task_thumbnail_header_bg"> recentsView = taskView.getRecentsView(); if (recentsView != null) { dismissTaskMenuView(); - recentsView.dismissTask(taskView, true, true); + recentsView.dismissTaskView(taskView, true, true); mTarget.getStatsLogManager().logger().withItemInfo(mTaskContainer.getItemInfo()) .log(LAUNCHER_SYSTEM_SHORTCUT_CLOSE_APP_TAP); } 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 fb622686dc..619075ff83 100644 --- a/quickstep/src/com/android/quickstep/recents/ui/mapper/TaskUiStateMapper.kt +++ b/quickstep/src/com/android/quickstep/recents/ui/mapper/TaskUiStateMapper.kt @@ -16,6 +16,7 @@ package com.android.quickstep.recents.ui.mapper +import android.view.View.OnClickListener import com.android.quickstep.recents.ui.viewmodel.TaskData import com.android.quickstep.task.thumbnail.TaskThumbnailUiState import com.android.quickstep.task.thumbnail.TaskThumbnailUiState.BackgroundOnly @@ -36,29 +37,38 @@ object TaskUiStateMapper { * @param taskData The [TaskData] to convert. Can be null or a specific subclass. * @param isLiveTile A flag indicating whether the task data represents live tile. * @param hasHeader A flag indicating whether the UI should display a header. + * @param clickCloseListener A callback when the close button in the UI is clicked. * @return A [TaskThumbnailUiState] representing the UI state for the given task data. */ fun toTaskThumbnailUiState( taskData: TaskData?, isLiveTile: Boolean, hasHeader: Boolean, + clickCloseListener: OnClickListener?, ): TaskThumbnailUiState = when { taskData !is TaskData.Data -> Uninitialized - isLiveTile -> createLiveTileState(taskData, hasHeader) + isLiveTile -> createLiveTileState(taskData, hasHeader, clickCloseListener) isBackgroundOnly(taskData) -> BackgroundOnly(taskData.backgroundColor) isSnapshotSplash(taskData) -> - SnapshotSplash(createSnapshotState(taskData, hasHeader), taskData.icon) + SnapshotSplash( + createSnapshotState(taskData, hasHeader, clickCloseListener), + taskData.icon, + ) else -> Uninitialized } - private fun createSnapshotState(taskData: TaskData.Data, hasHeader: Boolean): Snapshot = - if (canHeaderBeCreated(taskData, hasHeader)) { + private fun createSnapshotState( + taskData: TaskData.Data, + hasHeader: Boolean, + clickCloseListener: OnClickListener?, + ): Snapshot = + if (canHeaderBeCreated(taskData, hasHeader, clickCloseListener)) { Snapshot.WithHeader( taskData.thumbnailData?.thumbnail!!, taskData.thumbnailData.rotation, taskData.backgroundColor, - ThumbnailHeader(taskData.icon!!, taskData.titleDescription!!), + ThumbnailHeader(taskData.icon!!, taskData.titleDescription!!, clickCloseListener!!), ) } else { Snapshot.WithoutHeader( @@ -74,13 +84,26 @@ object TaskUiStateMapper { private fun isSnapshotSplash(taskData: TaskData.Data) = taskData.thumbnailData?.thumbnail != null && !taskData.isLocked - private fun canHeaderBeCreated(taskData: TaskData.Data, hasHeader: Boolean) = - hasHeader && taskData.icon != null && taskData.titleDescription != null + private fun canHeaderBeCreated( + taskData: TaskData.Data, + hasHeader: Boolean, + clickCloseListener: OnClickListener?, + ) = + hasHeader && + taskData.icon != null && + taskData.titleDescription != null && + clickCloseListener != null - private fun createLiveTileState(taskData: TaskData.Data, hasHeader: Boolean) = - if (canHeaderBeCreated(taskData, hasHeader)) { + private fun createLiveTileState( + taskData: TaskData.Data, + hasHeader: Boolean, + clickCloseListener: OnClickListener?, + ) = + if (canHeaderBeCreated(taskData, hasHeader, clickCloseListener)) { // TODO(http://b/353965691): figure out what to do when `icon` or `titleDescription` is // null. - LiveTile.WithHeader(ThumbnailHeader(taskData.icon!!, taskData.titleDescription!!)) + LiveTile.WithHeader( + ThumbnailHeader(taskData.icon!!, taskData.titleDescription!!, clickCloseListener!!) + ) } else LiveTile.WithoutHeader } diff --git a/quickstep/src/com/android/quickstep/task/thumbnail/TaskThumbnailUiState.kt b/quickstep/src/com/android/quickstep/task/thumbnail/TaskThumbnailUiState.kt index 61185448be..db593d34d3 100644 --- a/quickstep/src/com/android/quickstep/task/thumbnail/TaskThumbnailUiState.kt +++ b/quickstep/src/com/android/quickstep/task/thumbnail/TaskThumbnailUiState.kt @@ -19,6 +19,7 @@ package com.android.quickstep.task.thumbnail import android.graphics.Bitmap import android.graphics.drawable.Drawable import android.view.Surface +import android.view.View.OnClickListener import androidx.annotation.ColorInt sealed class TaskThumbnailUiState { @@ -54,5 +55,9 @@ sealed class TaskThumbnailUiState { ) : Snapshot() } - data class ThumbnailHeader(val icon: Drawable, val title: String) + data class ThumbnailHeader( + val icon: Drawable, + val title: String, + val clickCloseListener: OnClickListener, + ) } diff --git a/quickstep/src/com/android/quickstep/views/DesktopTaskView.kt b/quickstep/src/com/android/quickstep/views/DesktopTaskView.kt index 9bb8f3dd07..75f3b69140 100644 --- a/quickstep/src/com/android/quickstep/views/DesktopTaskView.kt +++ b/quickstep/src/com/android/quickstep/views/DesktopTaskView.kt @@ -345,14 +345,7 @@ class DesktopTaskView @JvmOverloads constructor(context: Context, attrs: Attribu explodeProgress = 0.0f viewModel = null visibility = VISIBLE - taskContainers.forEach { - contentView.removeView(it.snapshotView) - if (enableRefactorTaskThumbnail()) { - taskThumbnailViewPool!!.recycle(it.thumbnailView) - } else { - taskThumbnailViewDeprecatedPool!!.recycle(it.thumbnailViewDeprecated) - } - } + taskContainers.forEach { removeAndRecycleThumbnailView(it) } } @SuppressLint("RtlHardcoded") @@ -360,19 +353,7 @@ class DesktopTaskView @JvmOverloads constructor(context: Context, attrs: Attribu super.updateTaskSize(lastComputedTaskSize, lastComputedGridTaskSize) this.lastComputedTaskSize.set(lastComputedTaskSize) - BaseContainerInterface.getTaskDimension(mContext, container.deviceProfile, tempPointF) - val desktopSize = Size(tempPointF.x.toInt(), tempPointF.y.toInt()) - DEFAULT_BOUNDS.set(0, 0, desktopSize.width / 4, desktopSize.height / 4) - - fullscreenTaskPositions = - taskContainers.map { - DesktopTaskBoundsData(it.task.key.id, it.task.appBounds ?: DEFAULT_BOUNDS) - } - - if (enableDesktopExplodedView()) { - viewModel?.organizeDesktopTasks(desktopSize, fullscreenTaskPositions) - } - positionTaskWindows() + updateTaskPositions() } override fun onTaskListVisibilityChanged(visible: Boolean, changes: Int) { @@ -458,6 +439,56 @@ class DesktopTaskView @JvmOverloads constructor(context: Context, attrs: Attribu ViewUtils.addAccessibleChildToList(backgroundView, outChildren) } + fun removeTaskFromExplodedView(taskId: Int, animate: Boolean) { + if (!enableDesktopExplodedView()) { + Log.e( + TAG, + "removeTaskFromExplodedView called when enableDesktopExplodedView flag is false", + ) + return + } + + // Remove the task's [taskContainer] and its associated Views. + val taskContainer = getTaskContainerById(taskId) ?: return + removeAndRecycleThumbnailView(taskContainer) + taskContainer.destroy() + taskContainers = taskContainers.filterNot { it == taskContainer } + + // Dismiss the current DesktopTaskView if all its windows are closed. + 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. + updateTaskPositions() + } + } + + private fun removeAndRecycleThumbnailView(taskContainer: TaskContainer) { + contentView.removeView(taskContainer.snapshotView) + if (enableRefactorTaskThumbnail()) { + taskThumbnailViewPool!!.recycle(taskContainer.thumbnailView) + } else { + taskThumbnailViewDeprecatedPool!!.recycle(taskContainer.thumbnailViewDeprecated) + } + } + + private fun updateTaskPositions() { + BaseContainerInterface.getTaskDimension(mContext, container.deviceProfile, tempPointF) + val desktopSize = Size(tempPointF.x.toInt(), tempPointF.y.toInt()) + DEFAULT_BOUNDS.set(0, 0, desktopSize.width / 4, desktopSize.height / 4) + + fullscreenTaskPositions = + taskContainers.map { + DesktopTaskBoundsData(it.task.key.id, it.task.appBounds ?: DEFAULT_BOUNDS) + } + + if (enableDesktopExplodedView()) { + viewModel?.organizeDesktopTasks(desktopSize, fullscreenTaskPositions) + } + positionTaskWindows() + } + companion object { private const val TAG = "DesktopTaskView" private const val DEBUG = false diff --git a/quickstep/src/com/android/quickstep/views/RecentsDismissUtils.kt b/quickstep/src/com/android/quickstep/views/RecentsDismissUtils.kt index 96eed87a5f..3430b39ac1 100644 --- a/quickstep/src/com/android/quickstep/views/RecentsDismissUtils.kt +++ b/quickstep/src/com/android/quickstep/views/RecentsDismissUtils.kt @@ -76,7 +76,7 @@ class RecentsDismissUtils(private val recentsView: RecentsView<*, *>) { } .addEndListener { _, _, _, _ -> if (isDismissing) { - recentsView.dismissTask( + recentsView.dismissTaskView( draggedTaskView, /* animateTaskView = */ false, /* removeTask = */ true, diff --git a/quickstep/src/com/android/quickstep/views/RecentsView.java b/quickstep/src/com/android/quickstep/views/RecentsView.java index 9e53f11679..edcffb86d4 100644 --- a/quickstep/src/com/android/quickstep/views/RecentsView.java +++ b/quickstep/src/com/android/quickstep/views/RecentsView.java @@ -676,11 +676,11 @@ public abstract class RecentsView< MAIN_EXECUTOR, apkRemoved -> { if (apkRemoved) { - dismissTask(taskId); + dismissTask(taskId, /*animate=*/true, /*removeTask=*/false); } else { mModel.isTaskRemoved(taskKey.id, taskRemoved -> { if (taskRemoved) { - dismissTask(taskId); + dismissTask(taskId, /*animate=*/true, /*removeTask=*/false); } }, RecentsFilterState.getFilter(mFilterState.getPackageNameToFilter())); } @@ -4627,17 +4627,27 @@ public abstract class RecentsView< } @UiThread - private void dismissTask(int taskId) { + public void dismissTask(int taskId, boolean animate, boolean removeTask) { TaskView taskView = getTaskViewByTaskId(taskId); if (taskView == null) { Log.d(TAG, "dismissTask: " + taskId + ", no associated TaskView"); return; } Log.d(TAG, "dismissTask: " + taskId); - dismissTask(taskView, true /* animate */, false /* removeTask */); + + if (enableDesktopExplodedView() && taskView instanceof DesktopTaskView desktopTaskView) { + desktopTaskView.removeTaskFromExplodedView(taskId, animate); + + if (removeTask) { + ActivityManagerWrapper.getInstance().removeTask(taskId); + } + } else { + dismissTaskView(taskView, animate, removeTask); + } } - public void dismissTask(TaskView taskView, boolean animateTaskView, boolean removeTask) { + /** Dismisses the entire [taskView]. */ + public void dismissTaskView(TaskView taskView, boolean animateTaskView, boolean removeTask) { PendingAnimation pa = new PendingAnimation(DISMISS_TASK_DURATION); createTaskDismissAnimation(pa, taskView, animateTaskView, removeTask, DISMISS_TASK_DURATION, false /* dismissingForSplitSelection*/); @@ -4653,7 +4663,7 @@ public abstract class RecentsView< private void dismissCurrentTask() { TaskView taskView = getNextPageTaskView(); if (taskView != null) { - dismissTask(taskView, true /*animateTaskView*/, true /*removeTask*/); + dismissTaskView(taskView, true /*animateTaskView*/, true /*removeTask*/); } } diff --git a/quickstep/src/com/android/quickstep/views/TaskContainer.kt b/quickstep/src/com/android/quickstep/views/TaskContainer.kt index 7301cfc3ca..6339c5e1d3 100644 --- a/quickstep/src/com/android/quickstep/views/TaskContainer.kt +++ b/quickstep/src/com/android/quickstep/views/TaskContainer.kt @@ -19,6 +19,7 @@ package com.android.quickstep.views import android.graphics.Bitmap import android.graphics.Matrix import android.view.View +import android.view.View.OnClickListener import com.android.launcher3.Flags.enableRefactorTaskThumbnail import com.android.launcher3.model.data.TaskViewItemInfo import com.android.launcher3.util.SplitConfigurationOptions @@ -127,9 +128,19 @@ class TaskContainer( overlay.addChildForAccessibility(outChildren) } - fun setState(state: TaskData?, liveTile: Boolean, hasHeader: Boolean) { + fun setState( + state: TaskData?, + liveTile: Boolean, + hasHeader: Boolean, + clickCloseListener: OnClickListener?, + ) { thumbnailView.setState( - TaskUiStateMapper.toTaskThumbnailUiState(state, liveTile, hasHeader), + TaskUiStateMapper.toTaskThumbnailUiState( + state, + liveTile, + hasHeader, + clickCloseListener, + ), state?.taskId, ) thumbnailData = if (state is TaskData.Data) state.thumbnailData else null diff --git a/quickstep/src/com/android/quickstep/views/TaskThumbnailViewHeader.kt b/quickstep/src/com/android/quickstep/views/TaskThumbnailViewHeader.kt index 9eb294ac76..9a8805bf0f 100644 --- a/quickstep/src/com/android/quickstep/views/TaskThumbnailViewHeader.kt +++ b/quickstep/src/com/android/quickstep/views/TaskThumbnailViewHeader.kt @@ -19,6 +19,7 @@ package com.android.quickstep.views import android.content.Context import android.util.AttributeSet import android.widget.FrameLayout +import android.widget.ImageButton import android.widget.ImageView import android.widget.TextView import com.android.launcher3.R @@ -30,9 +31,11 @@ constructor(context: Context, attrs: AttributeSet? = null) : FrameLayout(context private val headerTitleView: TextView by lazy { findViewById(R.id.header_app_title) } private val headerIconView: ImageView by lazy { findViewById(R.id.header_app_icon) } + private val headerCloseButton: ImageButton by lazy { findViewById(R.id.header_close_button) } fun setHeader(header: ThumbnailHeader) { headerTitleView.setText(header.title) headerIconView.setImageDrawable(header.icon) + headerCloseButton.setOnClickListener(header.clickCloseListener) } } diff --git a/quickstep/src/com/android/quickstep/views/TaskView.kt b/quickstep/src/com/android/quickstep/views/TaskView.kt index ba5423217e..0e5382a235 100644 --- a/quickstep/src/com/android/quickstep/views/TaskView.kt +++ b/quickstep/src/com/android/quickstep/views/TaskView.kt @@ -44,6 +44,7 @@ import androidx.annotation.VisibleForTesting import androidx.core.view.updateLayoutParams import com.android.app.animation.Interpolators import com.android.launcher3.Flags.enableCursorHoverStates +import com.android.launcher3.Flags.enableDesktopExplodedView import com.android.launcher3.Flags.enableGridOnlyOverview import com.android.launcher3.Flags.enableHoverOfChildElementsInTaskview import com.android.launcher3.Flags.enableLargeDesktopWindowingTile @@ -768,11 +769,27 @@ constructor( // Updating containers val mapOfTasks = state.tasks.associateBy { it.taskId } taskContainers.forEach { container -> - val containerState = mapOfTasks[container.task.key.id] + val taskId = container.task.key.id + val containerState = mapOfTasks[taskId] + val shouldHaveHeader = (type == TaskViewType.DESKTOP) && enableDesktopExplodedView() container.setState( state = containerState, liveTile = state.isLiveTile, - hasHeader = state.hasHeader, + hasHeader = shouldHaveHeader, + clickCloseListener = + if (shouldHaveHeader) { + { + // Update the layout UI to remove this task from the layout grid, and + // remove the task from ActivityManager afterwards. + recentsView?.dismissTask( + taskId, + /* animate= */ true, + /* removeTask= */ true, + ) + } + } else { + null + }, ) updateThumbnailValidity(container) updateThumbnailMatrix( 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 124045fd69..7ca194afcf 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 @@ -21,6 +21,7 @@ import android.graphics.Color import android.graphics.drawable.ShapeDrawable import android.platform.test.annotations.EnableFlags import android.view.Surface +import android.view.View import androidx.test.ext.junit.runners.AndroidJUnit4 import com.android.launcher3.Flags import com.android.quickstep.recents.ui.viewmodel.TaskData @@ -43,6 +44,7 @@ class TaskUiStateMapperTest { taskData = null, isLiveTile = false, hasHeader = false, + clickCloseListener = null, ) assertThat(result).isEqualTo(TaskThumbnailUiState.Uninitialized) } @@ -57,6 +59,7 @@ class TaskUiStateMapperTest { taskData = input, isLiveTile = true, hasHeader = false, + clickCloseListener = null, ) assertThat(result).isEqualTo(LiveTile.WithoutHeader) } @@ -72,14 +75,18 @@ class TaskUiStateMapperTest { TASK_DATA.copy(isLocked = true), TASK_DATA.copy(title = null), ) + val closeCallback = View.OnClickListener {} val expected = - LiveTile.WithHeader(header = ThumbnailHeader(TASK_ICON, TASK_TITLE_DESCRIPTION)) + LiveTile.WithHeader( + header = ThumbnailHeader(TASK_ICON, TASK_TITLE_DESCRIPTION, closeCallback) + ) inputs.forEach { taskData -> val result = TaskUiStateMapper.toTaskThumbnailUiState( taskData = taskData, isLiveTile = true, hasHeader = true, + clickCloseListener = closeCallback, ) assertThat(result).isEqualTo(expected) } @@ -101,6 +108,7 @@ class TaskUiStateMapperTest { taskData = taskData, isLiveTile = true, hasHeader = true, + clickCloseListener = {}, ) assertThat(result).isEqualTo(LiveTile.WithoutHeader) } @@ -113,6 +121,7 @@ class TaskUiStateMapperTest { taskData = TASK_DATA, isLiveTile = false, hasHeader = false, + clickCloseListener = null, ) val expected = @@ -133,6 +142,7 @@ class TaskUiStateMapperTest { @Test fun taskData_isStaticTile_withHeader_returns_SnapshotSplashWithHeader() { val inputs = listOf(TASK_DATA, TASK_DATA.copy(title = null)) + val closeCallback = View.OnClickListener {} val expected = TaskThumbnailUiState.SnapshotSplash( snapshot = @@ -140,7 +150,7 @@ class TaskUiStateMapperTest { backgroundColor = TASK_BACKGROUND_COLOR, bitmap = TASK_THUMBNAIL, thumbnailRotation = Surface.ROTATION_0, - header = ThumbnailHeader(TASK_ICON, TASK_TITLE_DESCRIPTION), + header = ThumbnailHeader(TASK_ICON, TASK_TITLE_DESCRIPTION, closeCallback), ), splash = TASK_ICON, ) @@ -150,6 +160,7 @@ class TaskUiStateMapperTest { taskData = taskData, isLiveTile = false, hasHeader = true, + clickCloseListener = closeCallback, ) assertThat(result).isEqualTo(expected) } @@ -176,6 +187,7 @@ class TaskUiStateMapperTest { taskData = taskData, isLiveTile = false, hasHeader = true, + clickCloseListener = {}, ) assertThat(result).isInstanceOf(TaskThumbnailUiState.SnapshotSplash::class.java) @@ -191,6 +203,7 @@ class TaskUiStateMapperTest { taskData = TASK_DATA.copy(thumbnailData = null), isLiveTile = false, hasHeader = false, + clickCloseListener = null, ) val expected = TaskThumbnailUiState.BackgroundOnly(TASK_BACKGROUND_COLOR) @@ -204,6 +217,7 @@ class TaskUiStateMapperTest { taskData = TASK_DATA.copy(isLocked = true), isLiveTile = false, hasHeader = false, + clickCloseListener = null, ) val expected = TaskThumbnailUiState.BackgroundOnly(TASK_BACKGROUND_COLOR) @@ -212,6 +226,7 @@ class TaskUiStateMapperTest { private companion object { const val TASK_TITLE_DESCRIPTION = "Title Description 1" + var TASK_ID = 1 val TASK_ICON = ShapeDrawable() val TASK_THUMBNAIL = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888) val TASK_THUMBNAIL_DATA = @@ -219,7 +234,7 @@ class TaskUiStateMapperTest { val TASK_BACKGROUND_COLOR = Color.rgb(1, 2, 3) val TASK_DATA = TaskData.Data( - 1, + TASK_ID, title = "Task 1", titleDescription = TASK_TITLE_DESCRIPTION, icon = TASK_ICON, From 29ae91c36f380f4536bdfdc11244f2cd1b8fbe4a Mon Sep 17 00:00:00 2001 From: Brandon Dayauon Date: Fri, 21 Feb 2025 22:10:12 +0000 Subject: [PATCH 096/153] Change ps_install app icon to adaptive drawable In the before pic, you can see that the original drawable is small/compressed with a white ring around it. You can't really see that in the light theme since the white ring is blended. It is much clearer in the dark theme that this is the case. Changing the vector drawable to adaptive-icon will fix the white ring in the icon. bug:396346767 Test: manual screenshot: before: light theme: https://hsv.googleplex.com/6358252685099008 dark theme: https://hsv.googleplex.com/6567188726022144 after: light theme: https://hsv.googleplex.com/4762286056013824 dark theme: https://hsv.googleplex.com/4821700083449856 Flag: EXEMPT bug fix Change-Id: Ib557bcf5fce5e58b6be4bb8bc82673441816b2d7 --- .../private_space_install_app_icon.xml | 20 +++------------ ...vate_space_install_app_icon_foreground.xml | 25 +++++++++++++++++++ 2 files changed, 29 insertions(+), 16 deletions(-) create mode 100644 res/drawable/private_space_install_app_icon_foreground.xml diff --git a/res/drawable/private_space_install_app_icon.xml b/res/drawable/private_space_install_app_icon.xml index cfec2b126d..1e7fe43527 100644 --- a/res/drawable/private_space_install_app_icon.xml +++ b/res/drawable/private_space_install_app_icon.xml @@ -13,19 +13,7 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --> - - - - - - - + + + + diff --git a/res/drawable/private_space_install_app_icon_foreground.xml b/res/drawable/private_space_install_app_icon_foreground.xml new file mode 100644 index 0000000000..d55abe7304 --- /dev/null +++ b/res/drawable/private_space_install_app_icon_foreground.xml @@ -0,0 +1,25 @@ + + + + + From 362fa9e96a1bfe40408bff421ea392c624f8be3e Mon Sep 17 00:00:00 2001 From: Sunny Goyal Date: Fri, 21 Feb 2025 15:59:36 -0800 Subject: [PATCH 097/153] Fixing model thread priority getting set to background while loading Bug: 396250724 Flag: EXEMPT bugfix Test: Manual Change-Id: I587d6c64f75a4fd2b68c4e98c3b1cab30864879c --- .../android/launcher3/icons/IconCache.java | 6 +-- .../launcher3/model/BaseLauncherBinder.java | 19 ++-------- .../android/launcher3/model/LoaderTask.java | 3 ++ .../android/launcher3/util/LooperExecutor.kt | 37 +++++++++++++++---- 4 files changed, 40 insertions(+), 25 deletions(-) diff --git a/src/com/android/launcher3/icons/IconCache.java b/src/com/android/launcher3/icons/IconCache.java index b8f64244d9..119a6b122b 100644 --- a/src/com/android/launcher3/icons/IconCache.java +++ b/src/com/android/launcher3/icons/IconCache.java @@ -20,6 +20,7 @@ import static com.android.launcher3.LauncherSettings.Favorites.ITEM_TYPE_DEEP_SH import static com.android.launcher3.icons.cache.CacheLookupFlag.DEFAULT_LOOKUP_FLAG; import static com.android.launcher3.util.Executors.MAIN_EXECUTOR; import static com.android.launcher3.util.Executors.MODEL_EXECUTOR; +import static com.android.launcher3.util.LooperExecutor.CALLER_ICON_CACHE; import static com.android.launcher3.widget.WidgetSections.NO_CATEGORY; import static java.util.stream.Collectors.groupingBy; @@ -35,7 +36,6 @@ import android.content.pm.ShortcutInfo; import android.database.Cursor; import android.database.sqlite.SQLiteException; import android.os.Looper; -import android.os.Process; import android.os.Trace; import android.os.UserHandle; import android.text.TextUtils; @@ -204,7 +204,7 @@ public class IconCache extends BaseIconCache { Runnable endRunnable; if (Looper.myLooper() == Looper.getMainLooper()) { if (mPendingIconRequestCount <= 0) { - MODEL_EXECUTOR.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND); + MODEL_EXECUTOR.elevatePriority(CALLER_ICON_CACHE); } mPendingIconRequestCount++; endRunnable = this::onIconRequestEnd; @@ -221,7 +221,7 @@ public class IconCache extends BaseIconCache { private void onIconRequestEnd() { mPendingIconRequestCount--; if (mPendingIconRequestCount <= 0) { - MODEL_EXECUTOR.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); + MODEL_EXECUTOR.restorePriority(CALLER_ICON_CACHE); } } diff --git a/src/com/android/launcher3/model/BaseLauncherBinder.java b/src/com/android/launcher3/model/BaseLauncherBinder.java index 3ee8b87db0..a2ca6b61a1 100644 --- a/src/com/android/launcher3/model/BaseLauncherBinder.java +++ b/src/com/android/launcher3/model/BaseLauncherBinder.java @@ -28,7 +28,6 @@ import static com.android.launcher3.util.Executors.MODEL_EXECUTOR; import static java.util.Collections.emptyList; -import android.os.Process; import android.os.Trace; import android.util.Log; import android.util.Pair; @@ -352,14 +351,8 @@ public class BaseLauncherBinder { onCompleteSignal.executeAllAndDestroy(); } - executeCallbacksTask( - c -> { - if (!enableWorkspaceInflation()) { - MODEL_EXECUTOR.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); - } - c.onInitialBindComplete(currentScreenIds, pendingTasks, onCompleteSignal, - workspaceItemCount, isBindSync); - }, mUiExecutor); + executeCallbacksTask(c -> c.onInitialBindComplete(currentScreenIds, pendingTasks, + onCompleteSignal, workspaceItemCount, isBindSync), mUiExecutor); } private void setupPendingBind( @@ -369,12 +362,8 @@ public class BaseLauncherBinder { executeCallbacksTask(c -> c.bindStringCache(cacheClone), pendingExecutor); executeCallbacksTask(c -> c.finishBindingItems(currentScreenIds), pendingExecutor); - pendingExecutor.execute( - () -> { - MODEL_EXECUTOR.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); - ItemInstallQueue.INSTANCE.get(mApp.getContext()) - .resumeModelPush(FLAG_LOADER_RUNNING); - }); + pendingExecutor.execute(() -> ItemInstallQueue.INSTANCE.get(mApp.getContext()) + .resumeModelPush(FLAG_LOADER_RUNNING)); } /** diff --git a/src/com/android/launcher3/model/LoaderTask.java b/src/com/android/launcher3/model/LoaderTask.java index c1ee69b729..d44b289db4 100644 --- a/src/com/android/launcher3/model/LoaderTask.java +++ b/src/com/android/launcher3/model/LoaderTask.java @@ -36,6 +36,7 @@ import static com.android.launcher3.model.ModelUtils.WIDGET_FILTER; import static com.android.launcher3.model.ModelUtils.currentScreenContentFilter; import static com.android.launcher3.model.data.ItemInfoWithIcon.FLAG_INSTALL_SESSION_ACTIVE; import static com.android.launcher3.util.Executors.MODEL_EXECUTOR; +import static com.android.launcher3.util.LooperExecutor.CALLER_LOADER_TASK; import static com.android.launcher3.util.PackageManagerHelper.hasShortcutsPermission; import android.appwidget.AppWidgetProviderInfo; @@ -251,6 +252,7 @@ public class LoaderTask implements Runnable { } TraceHelper.INSTANCE.beginSection(TAG); + MODEL_EXECUTOR.elevatePriority(CALLER_LOADER_TASK); LoaderMemoryLogger memoryLogger = new LoaderMemoryLogger(); mIsRestoreFromBackup = LauncherPrefs.get(mApp.getContext()).get(IS_FIRST_LOAD_AFTER_RESTORE); @@ -403,6 +405,7 @@ public class LoaderTask implements Runnable { memoryLogger.printLogs(); throw e; } + MODEL_EXECUTOR.restorePriority(CALLER_LOADER_TASK); TraceHelper.INSTANCE.endSection(); } diff --git a/src/com/android/launcher3/util/LooperExecutor.kt b/src/com/android/launcher3/util/LooperExecutor.kt index f5ba906342..6ff528d264 100644 --- a/src/com/android/launcher3/util/LooperExecutor.kt +++ b/src/com/android/launcher3/util/LooperExecutor.kt @@ -19,8 +19,11 @@ import android.os.Handler import android.os.HandlerThread import android.os.Looper import android.os.Process +import android.os.Process.THREAD_PRIORITY_FOREGROUND +import androidx.annotation.IntDef import java.util.concurrent.AbstractExecutorService import java.util.concurrent.TimeUnit +import kotlin.annotation.AnnotationRetention.SOURCE /** Extension of [AbstractExecutorService] which executed on a provided looper. */ class LooperExecutor(looper: Looper, private val defaultPriority: Int) : AbstractExecutorService() { @@ -40,6 +43,8 @@ class LooperExecutor(looper: Looper, private val defaultPriority: Int) : Abstrac val looper: Looper get() = handler.looper + @ElevationCaller private var elevationFlags: Int = 0 + override fun execute(runnable: Runnable) { if (handler.looper == Looper.myLooper()) { runnable.run() @@ -73,16 +78,31 @@ class LooperExecutor(looper: Looper, private val defaultPriority: Int) : Abstrac } /** - * Set the priority of a thread, based on Linux priorities. - * - * @param priority Linux priority level, from -20 for highest scheduling priority to 19 for - * lowest scheduling priority. - * @see Process.setThreadPriority + * Increases the priority of the thread for the [caller]. Multiple calls with same caller are + * ignored. The priority is reset once wall callers have restored priority */ - fun setThreadPriority(priority: Int) { - Process.setThreadPriority((thread as HandlerThread).threadId, priority) + fun elevatePriority(@ElevationCaller caller: Int) { + val wasElevated = elevationFlags != 0 + elevationFlags = elevationFlags.or(caller) + if (elevationFlags != 0 && !wasElevated) + Process.setThreadPriority( + (thread as HandlerThread).threadId, + THREAD_PRIORITY_FOREGROUND, + ) } + /** Restores to default priority if it was previously elevated */ + fun restorePriority(@ElevationCaller caller: Int) { + val wasElevated = elevationFlags != 0 + elevationFlags = elevationFlags.and(caller.inv()) + if (elevationFlags == 0 && wasElevated) + Process.setThreadPriority((thread as HandlerThread).threadId, defaultPriority) + } + + @Retention(SOURCE) + @IntDef(value = [CALLER_LOADER_TASK, CALLER_ICON_CACHE], flag = true) + annotation class ElevationCaller + companion object { /** Utility method to get a started handler thread statically with the provided priority */ @JvmOverloads @@ -91,5 +111,8 @@ class LooperExecutor(looper: Looper, private val defaultPriority: Int) : Abstrac name: String, priority: Int = Process.THREAD_PRIORITY_DEFAULT, ): Looper = HandlerThread(name, priority).apply { start() }.looper + + const val CALLER_LOADER_TASK = 1 shl 0 + const val CALLER_ICON_CACHE = 1 shl 1 } } From 471ad8400f9ba1ef508dc05eae998bd6b8175cc0 Mon Sep 17 00:00:00 2001 From: Andy Wickham Date: Sat, 22 Feb 2025 02:20:55 +0000 Subject: [PATCH 098/153] Update NavHandle tests to use more conservative timings. On some devices, the long press would trigger due to an overly long wait in the test. Separately, the small slop tests were using a slop that would trigger the second stage if that flag was enabled, so the trigger didn't happen (WAI). We already test 2 stage, so I updated these tests to use a smaller slop that should not trigger with or without 2 stage. Test: atest NexusLauncherTests:com.android.quickstep.inputconsumers.NavHandleLongPressInputConsumerTest -- --abi arm64-v8a Flag: EXEMPT tests Fix: 398216382 Change-Id: Iec633d01eff63eac8ba072fef4ac1e7b452d8242 --- .../NavHandleLongPressInputConsumerTest.java | 75 +++++++------------ 1 file changed, 29 insertions(+), 46 deletions(-) diff --git a/quickstep/tests/multivalentTests/src/com/android/quickstep/inputconsumers/NavHandleLongPressInputConsumerTest.java b/quickstep/tests/multivalentTests/src/com/android/quickstep/inputconsumers/NavHandleLongPressInputConsumerTest.java index de6920bd46..99a34ea69c 100644 --- a/quickstep/tests/multivalentTests/src/com/android/quickstep/inputconsumers/NavHandleLongPressInputConsumerTest.java +++ b/quickstep/tests/multivalentTests/src/com/android/quickstep/inputconsumers/NavHandleLongPressInputConsumerTest.java @@ -28,6 +28,7 @@ import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCH import static com.android.launcher3.logging.StatsLogManager.LauncherLatencyEvent.LAUNCHER_LATENCY_CONTEXTUAL_SEARCH_LPNH_ABANDON; import static com.android.launcher3.util.Executors.MAIN_EXECUTOR; import static com.android.quickstep.DeviceConfigWrapper.DEFAULT_LPNH_TIMEOUT_MS; +import static com.android.quickstep.inputconsumers.NavHandleLongPressInputConsumer.MIN_TIME_TO_LOG_ABANDON_MS; import static com.google.common.truth.Truth.assertThat; @@ -147,8 +148,7 @@ public class NavHandleLongPressInputConsumerTest { public void testDelegateDisallowsTouchInterceptAfterTouchDown() { // Touch down and wait the minimum abandonment time. mUnderTest.onMotionEvent(generateCenteredMotionEvent(ACTION_DOWN)); - SystemClock.sleep(NavHandleLongPressInputConsumer.MIN_TIME_TO_LOG_ABANDON_MS); - InstrumentationRegistry.getInstrumentation().waitForIdleSync(); + sleep(MIN_TIME_TO_LOG_ABANDON_MS); // Delegate should still get touches unless long press is triggered. verify(mDelegate).onMotionEvent(any()); @@ -173,8 +173,7 @@ public class NavHandleLongPressInputConsumerTest { @Test public void testLongPressTriggered() { mUnderTest.onMotionEvent(generateCenteredMotionEvent(ACTION_DOWN)); - SystemClock.sleep(DEFAULT_LPNH_TIMEOUT_MS); - InstrumentationRegistry.getInstrumentation().waitForIdleSync(); + sleep(DEFAULT_LPNH_TIMEOUT_MS); assertThat(mUnderTest.mState).isEqualTo(DelegateInputConsumer.STATE_ACTIVE); assertTrue(mLongPressTriggered.get()); @@ -191,10 +190,8 @@ public class NavHandleLongPressInputConsumerTest { @Test public void testLongPressTriggeredWithSlightVerticalMovement() { mUnderTest.onMotionEvent(generateCenteredMotionEvent(ACTION_DOWN)); - mUnderTest.onMotionEvent(generateCenteredMotionEventWithYOffset(ACTION_MOVE, - -(TOUCH_SLOP - 1))); - SystemClock.sleep(DEFAULT_LPNH_TIMEOUT_MS); - InstrumentationRegistry.getInstrumentation().waitForIdleSync(); + mUnderTest.onMotionEvent(generateCenteredMotionEventWithYOffset(ACTION_MOVE, 1)); + sleep(DEFAULT_LPNH_TIMEOUT_MS); assertThat(mUnderTest.mState).isEqualTo(DelegateInputConsumer.STATE_ACTIVE); assertTrue(mLongPressTriggered.get()); @@ -207,10 +204,8 @@ public class NavHandleLongPressInputConsumerTest { @Test public void testLongPressTriggeredWithSlightHorizontalMovement() { mUnderTest.onMotionEvent(generateCenteredMotionEvent(ACTION_DOWN)); - mUnderTest.onMotionEvent(generateMotionEvent(ACTION_MOVE, - mScreenWidth / 2f - (TOUCH_SLOP - 1), 0)); - SystemClock.sleep(DEFAULT_LPNH_TIMEOUT_MS); - InstrumentationRegistry.getInstrumentation().waitForIdleSync(); + mUnderTest.onMotionEvent(generateMotionEvent(ACTION_MOVE, mScreenWidth / 2f + 1, 0)); + sleep(DEFAULT_LPNH_TIMEOUT_MS); assertThat(mUnderTest.mState).isEqualTo(DelegateInputConsumer.STATE_ACTIVE); assertTrue(mLongPressTriggered.get()); @@ -230,8 +225,7 @@ public class NavHandleLongPressInputConsumerTest { mUnderTest.onMotionEvent(generateMotionEvent(ACTION_MOVE, mScreenWidth / 2f - (TOUCH_SLOP - 1), 0)); // We have entered the second stage, so the normal timeout shouldn't trigger. - SystemClock.sleep(DEFAULT_LPNH_TIMEOUT_MS); - InstrumentationRegistry.getInstrumentation().waitForIdleSync(); + sleep(DEFAULT_LPNH_TIMEOUT_MS); assertThat(mUnderTest.mState).isEqualTo(DelegateInputConsumer.STATE_INACTIVE); assertFalse(mLongPressTriggered.get()); @@ -241,9 +235,8 @@ public class NavHandleLongPressInputConsumerTest { // After an extended time, the long press should trigger. float extendedDurationMultiplier = (DeviceConfigWrapper.get().getTwoStageDurationPercentage() / 100f); - SystemClock.sleep((long) (DEFAULT_LPNH_TIMEOUT_MS + sleep((long) (DEFAULT_LPNH_TIMEOUT_MS * (extendedDurationMultiplier - 1))); // -1 because we already waited 1x - InstrumentationRegistry.getInstrumentation().waitForIdleSync(); assertThat(mUnderTest.mState).isEqualTo(DelegateInputConsumer.STATE_ACTIVE); assertTrue(mLongPressTriggered.get()); @@ -264,8 +257,7 @@ public class NavHandleLongPressInputConsumerTest { mUnderTest.onMotionEvent(generateCenteredMotionEvent(ACTION_DOWN)); // We have not entered the second stage, so the normal timeout should trigger. - SystemClock.sleep(DEFAULT_LPNH_TIMEOUT_MS); - InstrumentationRegistry.getInstrumentation().waitForIdleSync(); + sleep(DEFAULT_LPNH_TIMEOUT_MS); assertThat(mUnderTest.mState).isEqualTo(DelegateInputConsumer.STATE_ACTIVE); assertTrue(mLongPressTriggered.get()); @@ -281,16 +273,14 @@ public class NavHandleLongPressInputConsumerTest { @Test public void testLongPressAbortedByTouchUp() { mUnderTest.onMotionEvent(generateCenteredMotionEvent(ACTION_DOWN)); - SystemClock.sleep(DEFAULT_LPNH_TIMEOUT_MS - 10); - InstrumentationRegistry.getInstrumentation().waitForIdleSync(); + sleep(MIN_TIME_TO_LOG_ABANDON_MS); assertThat(mUnderTest.mState).isEqualTo(DelegateInputConsumer.STATE_INACTIVE); assertFalse(mLongPressTriggered.get()); mUnderTest.onMotionEvent(generateCenteredMotionEvent(ACTION_UP)); // Wait past the long press timeout, to be extra sure it wouldn't have triggered. - SystemClock.sleep(20); - InstrumentationRegistry.getInstrumentation().waitForIdleSync(); + sleep(DEFAULT_LPNH_TIMEOUT_MS); assertThat(mUnderTest.mState).isEqualTo(DelegateInputConsumer.STATE_INACTIVE); assertFalse(mLongPressTriggered.get()); @@ -303,16 +293,14 @@ public class NavHandleLongPressInputConsumerTest { @Test public void testLongPressAbortedByTouchCancel() { mUnderTest.onMotionEvent(generateCenteredMotionEvent(ACTION_DOWN)); - SystemClock.sleep(DEFAULT_LPNH_TIMEOUT_MS - 10); - InstrumentationRegistry.getInstrumentation().waitForIdleSync(); + sleep(MIN_TIME_TO_LOG_ABANDON_MS); assertThat(mUnderTest.mState).isEqualTo(DelegateInputConsumer.STATE_INACTIVE); assertFalse(mLongPressTriggered.get()); mUnderTest.onMotionEvent(generateCenteredMotionEvent(ACTION_CANCEL)); // Wait past the long press timeout, to be extra sure it wouldn't have triggered. - SystemClock.sleep(20); - InstrumentationRegistry.getInstrumentation().waitForIdleSync(); + sleep(DEFAULT_LPNH_TIMEOUT_MS); assertThat(mUnderTest.mState).isEqualTo(DelegateInputConsumer.STATE_INACTIVE); assertFalse(mLongPressTriggered.get()); @@ -325,8 +313,7 @@ public class NavHandleLongPressInputConsumerTest { @Test public void testLongPressAbortedByTouchSlopPassedVertically() { mUnderTest.onMotionEvent(generateCenteredMotionEvent(ACTION_DOWN)); - SystemClock.sleep(DEFAULT_LPNH_TIMEOUT_MS - 10); - InstrumentationRegistry.getInstrumentation().waitForIdleSync(); + sleep(MIN_TIME_TO_LOG_ABANDON_MS); assertThat(mUnderTest.mState).isEqualTo(DelegateInputConsumer.STATE_INACTIVE); assertFalse(mLongPressTriggered.get()); @@ -334,8 +321,7 @@ public class NavHandleLongPressInputConsumerTest { mUnderTest.onMotionEvent(generateCenteredMotionEventWithYOffset(ACTION_MOVE, -(TOUCH_SLOP + 1))); // Wait past the long press timeout, to be extra sure it wouldn't have triggered. - SystemClock.sleep(20); - InstrumentationRegistry.getInstrumentation().waitForIdleSync(); + sleep(DEFAULT_LPNH_TIMEOUT_MS); assertThat(mUnderTest.mState).isEqualTo(DelegateInputConsumer.STATE_INACTIVE); assertFalse(mLongPressTriggered.get()); @@ -348,8 +334,7 @@ public class NavHandleLongPressInputConsumerTest { @Test public void testLongPressAbortedByTouchSlopPassedHorizontally() { mUnderTest.onMotionEvent(generateCenteredMotionEvent(ACTION_DOWN)); - SystemClock.sleep(DEFAULT_LPNH_TIMEOUT_MS - 10); - InstrumentationRegistry.getInstrumentation().waitForIdleSync(); + sleep(MIN_TIME_TO_LOG_ABANDON_MS); assertThat(mUnderTest.mState).isEqualTo(DelegateInputConsumer.STATE_INACTIVE); assertFalse(mLongPressTriggered.get()); @@ -357,8 +342,7 @@ public class NavHandleLongPressInputConsumerTest { mUnderTest.onMotionEvent(generateMotionEvent(ACTION_MOVE, mScreenWidth / 2f - (TOUCH_SLOP + 1), 0)); // Wait past the long press timeout, to be extra sure it wouldn't have triggered. - SystemClock.sleep(20); - InstrumentationRegistry.getInstrumentation().waitForIdleSync(); + sleep(DEFAULT_LPNH_TIMEOUT_MS); assertThat(mUnderTest.mState).isEqualTo(DelegateInputConsumer.STATE_INACTIVE); assertFalse(mLongPressTriggered.get()); @@ -379,8 +363,7 @@ public class NavHandleLongPressInputConsumerTest { mUnderTest.onMotionEvent(generateCenteredMotionEventWithYOffset(ACTION_MOVE, -(TOUCH_SLOP - 1))); // Normal duration shouldn't trigger. - SystemClock.sleep(DEFAULT_LPNH_TIMEOUT_MS); - InstrumentationRegistry.getInstrumentation().waitForIdleSync(); + sleep(DEFAULT_LPNH_TIMEOUT_MS); assertThat(mUnderTest.mState).isEqualTo(DelegateInputConsumer.STATE_INACTIVE); assertFalse(mLongPressTriggered.get()); @@ -391,9 +374,8 @@ public class NavHandleLongPressInputConsumerTest { // Wait past the extended long press timeout, to be sure it wouldn't have triggered. float extendedDurationMultiplier = (DeviceConfigWrapper.get().getTwoStageDurationPercentage() / 100f); - SystemClock.sleep((long) (DEFAULT_LPNH_TIMEOUT_MS + sleep((long) (DEFAULT_LPNH_TIMEOUT_MS * (extendedDurationMultiplier - 1))); // -1 because we already waited 1x - InstrumentationRegistry.getInstrumentation().waitForIdleSync(); assertThat(mUnderTest.mState).isEqualTo(DelegateInputConsumer.STATE_INACTIVE); assertFalse(mLongPressTriggered.get()); @@ -418,8 +400,7 @@ public class NavHandleLongPressInputConsumerTest { mUnderTest.onMotionEvent(generateMotionEvent(ACTION_MOVE, mScreenWidth / 2f - (TOUCH_SLOP - 1), 0)); // Normal duration shouldn't trigger. - SystemClock.sleep(DEFAULT_LPNH_TIMEOUT_MS); - InstrumentationRegistry.getInstrumentation().waitForIdleSync(); + sleep(DEFAULT_LPNH_TIMEOUT_MS); assertThat(mUnderTest.mState).isEqualTo(DelegateInputConsumer.STATE_INACTIVE); assertFalse(mLongPressTriggered.get()); @@ -430,9 +411,8 @@ public class NavHandleLongPressInputConsumerTest { // Wait past the extended long press timeout, to be sure it wouldn't have triggered. float extendedDurationMultiplier = (DeviceConfigWrapper.get().getTwoStageDurationPercentage() / 100f); - SystemClock.sleep((long) (DEFAULT_LPNH_TIMEOUT_MS + sleep((long) (DEFAULT_LPNH_TIMEOUT_MS * (extendedDurationMultiplier - 1))); // -1 because we already waited 1x - InstrumentationRegistry.getInstrumentation().waitForIdleSync(); assertThat(mUnderTest.mState).isEqualTo(DelegateInputConsumer.STATE_INACTIVE); assertFalse(mLongPressTriggered.get()); @@ -450,8 +430,7 @@ public class NavHandleLongPressInputConsumerTest { public void testTouchOutsideNavHandleIgnored() { // Touch the far left side of the screen. (y=0 is top of navbar region, picked arbitrarily) mUnderTest.onMotionEvent(generateMotionEvent(ACTION_DOWN, 0, 0)); - SystemClock.sleep(DEFAULT_LPNH_TIMEOUT_MS); - InstrumentationRegistry.getInstrumentation().waitForIdleSync(); + sleep(DEFAULT_LPNH_TIMEOUT_MS); // Should be ignored because the x position was not centered in the navbar region. assertThat(mUnderTest.mState).isEqualTo(DelegateInputConsumer.STATE_INACTIVE); @@ -484,8 +463,7 @@ public class NavHandleLongPressInputConsumerTest { @Test public void testNoLogsForShortTouch() { mUnderTest.onMotionEvent(generateCenteredMotionEvent(ACTION_DOWN)); - SystemClock.sleep(10); - InstrumentationRegistry.getInstrumentation().waitForIdleSync(); + sleep(10); mUnderTest.onMotionEvent(generateCenteredMotionEvent(ACTION_UP)); verifyNoMoreInteractions(mStatsLogManager); verifyNoMoreInteractions(mStatsLogger); @@ -509,6 +487,11 @@ public class NavHandleLongPressInputConsumerTest { mDownTimeMs = 0; } + private static void sleep(long sleepMs) { + SystemClock.sleep(sleepMs); + InstrumentationRegistry.getInstrumentation().waitForIdleSync(); + } + /** Generate a motion event centered horizontally in the screen. */ private MotionEvent generateCenteredMotionEvent(int motionAction) { return generateCenteredMotionEventWithYOffset(motionAction, 0); From 5e3331dc6f344f38ce49484672c2d591b72a43ea Mon Sep 17 00:00:00 2001 From: Uwais Ashraf Date: Mon, 24 Feb 2025 07:24:37 +0000 Subject: [PATCH 099/153] Add missing bits of cleanup to TV recycle stage Bug: 395331030 Flag: com.android.launcher3.enable_refactor_task_thumbnail Test: Manual heap dump comparison Change-Id: Ifa40d7bf874b0437fb0dc59a964748366ffe9986 --- .../com/android/quickstep/task/thumbnail/TaskThumbnailView.kt | 2 ++ quickstep/src/com/android/quickstep/views/TaskContainer.kt | 2 ++ 2 files changed, 4 insertions(+) diff --git a/quickstep/src/com/android/quickstep/task/thumbnail/TaskThumbnailView.kt b/quickstep/src/com/android/quickstep/task/thumbnail/TaskThumbnailView.kt index e91073ac7a..0edbacc710 100644 --- a/quickstep/src/com/android/quickstep/task/thumbnail/TaskThumbnailView.kt +++ b/quickstep/src/com/android/quickstep/task/thumbnail/TaskThumbnailView.kt @@ -181,8 +181,10 @@ class TaskThumbnailView : FrameLayout, ViewPool.Reusable { private fun resetViews() { liveTileView.isInvisible = true thumbnailView.isInvisible = true + thumbnailView.setImageBitmap(null) splashBackground.alpha = 0f splashIcon.alpha = 0f + splashIcon.setImageDrawable(null) scrimView.alpha = 0f setBackgroundColor(Color.BLACK) taskThumbnailViewHeader?.isInvisible = true diff --git a/quickstep/src/com/android/quickstep/views/TaskContainer.kt b/quickstep/src/com/android/quickstep/views/TaskContainer.kt index 6339c5e1d3..2b9d0365a9 100644 --- a/quickstep/src/com/android/quickstep/views/TaskContainer.kt +++ b/quickstep/src/com/android/quickstep/views/TaskContainer.kt @@ -109,6 +109,8 @@ class TaskContainer( overlay.destroy() if (enableRefactorTaskThumbnail()) { isThumbnailValid = false + thumbnailData = null + thumbnailView.onRecycle() } else { thumbnailViewDeprecated.setShowSplashForSplitSelection(false) } From e49214080f15874ecaa497dd931f252fde5cf305 Mon Sep 17 00:00:00 2001 From: Jagrut Desai Date: Tue, 18 Feb 2025 11:06:56 -0800 Subject: [PATCH 100/153] Fix Taskbar Edu accessibility anmimation This cl include: Allows user to click on lottie animation views to play and pause animations. If user have choosen to remove animations we will honor it and not play the animation from begaining. Test: Manual, Presubmit Bug: 378980835 Flag: EXEMPT bugfix Change-Id: Ieaaf771bc307837f042f6e59d8f02fefb2e8286a --- .../launcher3/QuickstepTransitionManager.java | 31 +---- .../taskbar/TaskbarEduTooltipController.kt | 37 +++++- src/com/android/launcher3/PagedView.java | 6 +- .../RemoveAnimationSettingsTracker.kt | 110 ++++++++++++++++++ .../dagger/LauncherBaseAppComponent.java | 3 +- 5 files changed, 149 insertions(+), 38 deletions(-) create mode 100644 src/com/android/launcher3/RemoveAnimationSettingsTracker.kt diff --git a/quickstep/src/com/android/launcher3/QuickstepTransitionManager.java b/quickstep/src/com/android/launcher3/QuickstepTransitionManager.java index 67feb6a6b8..9f81124a26 100644 --- a/quickstep/src/com/android/launcher3/QuickstepTransitionManager.java +++ b/quickstep/src/com/android/launcher3/QuickstepTransitionManager.java @@ -56,7 +56,6 @@ import static com.android.launcher3.config.FeatureFlags.SEPARATE_RECENTS_ACTIVIT import static com.android.launcher3.testing.shared.TestProtocol.WALLPAPER_OPEN_ANIMATION_FINISHED_MESSAGE; import static com.android.launcher3.util.DisplayController.isTransientTaskbar; import static com.android.launcher3.util.Executors.MAIN_EXECUTOR; -import static com.android.launcher3.util.Executors.ORDERED_BG_EXECUTOR; import static com.android.launcher3.util.MultiPropertyFactory.MULTI_PROPERTY_VALUE; import static com.android.launcher3.util.window.RefreshRateTracker.getSingleFrameMs; import static com.android.launcher3.views.FloatingIconView.SHAPE_PROGRESS_DURATION; @@ -79,7 +78,6 @@ import android.app.role.RoleManager; import android.content.ComponentName; import android.content.Context; import android.content.res.Resources; -import android.database.ContentObserver; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Point; @@ -94,7 +92,6 @@ import android.os.Looper; import android.os.SystemProperties; import android.os.UserHandle; import android.provider.Settings; -import android.provider.Settings.Global; import android.util.Pair; import android.util.Size; import android.view.CrossWindowBlurListeners; @@ -249,16 +246,6 @@ public class QuickstepTransitionManager implements OnDeviceProfileChangeListener // {@link TaskRestartedDuringLaunchListener}, and remove them on activity destroy. private final List mRegisteredTaskStackChangeListener = new ArrayList<>(); - private final ContentObserver mAnimationRemovalObserver = new ContentObserver( - ORDERED_BG_EXECUTOR.getHandler()) { - @Override - public void onChange(boolean selfChange) { - mAreAnimationsEnabled = Global.getFloat(mLauncher.getContentResolver(), - Global.ANIMATOR_DURATION_SCALE, 1f) > 0 - || Global.getFloat(mLauncher.getContentResolver(), - Global.TRANSITION_ANIMATION_SCALE, 1f) > 0; - } - }; private DeviceProfile mDeviceProfile; @@ -287,7 +274,6 @@ public class QuickstepTransitionManager implements OnDeviceProfileChangeListener // Pairs of window starting type and starting window background color for starting tasks // Will never be larger than MAX_NUM_TASKS private LinkedHashMap> mTaskStartParams; - private boolean mAreAnimationsEnabled = true; private final Interpolator mOpeningXInterpolator; private final Interpolator mOpeningInterpolator; @@ -298,7 +284,6 @@ public class QuickstepTransitionManager implements OnDeviceProfileChangeListener mHandler = new Handler(Looper.getMainLooper()); mDeviceProfile = mLauncher.getDeviceProfile(); mBackAnimationController = new LauncherBackAnimationController(mLauncher, this); - checkAndMonitorIfAnimationsAreEnabled(); Resources res = mLauncher.getResources(); mClosingWindowTransY = res.getDimensionPixelSize(R.dimen.closing_window_trans_y); @@ -1220,8 +1205,6 @@ public class QuickstepTransitionManager implements OnDeviceProfileChangeListener unregisterRemoteTransitions(); mLauncher.removeOnDeviceProfileChangeListener(this); SystemUiProxy.INSTANCE.get(mLauncher).setStartingWindowListener(null); - ORDERED_BG_EXECUTOR.execute(() -> mLauncher.getContentResolver() - .unregisterContentObserver(mAnimationRemovalObserver)); if (BuildConfig.IS_STUDIO_BUILD && !mRegisteredTaskStackChangeListener.isEmpty()) { throw new IllegalStateException("Failed to run onEndCallback created from" + " getActivityLaunchOptions()"); @@ -1275,17 +1258,6 @@ public class QuickstepTransitionManager implements OnDeviceProfileChangeListener } } - private void checkAndMonitorIfAnimationsAreEnabled() { - ORDERED_BG_EXECUTOR.execute(() -> { - mAnimationRemovalObserver.onChange(true); - mLauncher.getContentResolver().registerContentObserver(Global.getUriFor( - Global.ANIMATOR_DURATION_SCALE), false, mAnimationRemovalObserver); - mLauncher.getContentResolver().registerContentObserver(Global.getUriFor( - Global.TRANSITION_ANIMATION_SCALE), false, mAnimationRemovalObserver); - - }); - } - private boolean launcherIsATargetWithMode(RemoteAnimationTarget[] targets, int mode) { for (RemoteAnimationTarget target : targets) { if (target.mode == mode && target.taskInfo != null @@ -1421,7 +1393,8 @@ public class QuickstepTransitionManager implements OnDeviceProfileChangeListener (LauncherAppWidgetHostView) launcherView, targetRect, windowSize, mDeviceProfile.isMultiWindowMode ? 0 : getWindowCornerRadius(mLauncher), isTransluscent, fallbackBackgroundColor); - } else if (launcherView != null && mAreAnimationsEnabled) { + } else if (launcherView != null && !RemoveAnimationSettingsTracker.INSTANCE.get( + mLauncher).isRemoveAnimationEnabled()) { floatingIconView = getFloatingIconView(mLauncher, launcherView, null, mLauncher.getTaskbarUIController() == null ? null diff --git a/quickstep/src/com/android/launcher3/taskbar/TaskbarEduTooltipController.kt b/quickstep/src/com/android/launcher3/taskbar/TaskbarEduTooltipController.kt index b4ffb744df..5d1288c106 100644 --- a/quickstep/src/com/android/launcher3/taskbar/TaskbarEduTooltipController.kt +++ b/quickstep/src/com/android/launcher3/taskbar/TaskbarEduTooltipController.kt @@ -39,6 +39,7 @@ import androidx.core.view.updateLayoutParams import com.airbnb.lottie.LottieAnimationView import com.android.launcher3.LauncherPrefs import com.android.launcher3.R +import com.android.launcher3.RemoveAnimationSettingsTracker import com.android.launcher3.Utilities import com.android.launcher3.config.FeatureFlags.enableTaskbarPinning import com.android.launcher3.taskbar.TaskbarAutohideSuspendController.FLAG_AUTOHIDE_SUSPEND_EDU_OPEN @@ -128,6 +129,26 @@ open class TaskbarEduTooltipController(context: Context) : activityContext.dragLayer.post { maybeShowSearchEdu() } } + /** + * Turns off auto play of lottie animations if user has opted to remove animation else attaches + * click listener to allow user to play or pause animations. + */ + fun handleEduAnimations(animationViews: List) { + for (animationView in animationViews) { + if ( + RemoveAnimationSettingsTracker.INSTANCE.get(animationView.context) + .isRemoveAnimationEnabled() + ) { + animationView.pauseAnimation() + } else { + animationView.setOnClickListener { + if (animationView.isAnimating) animationView.pauseAnimation() + else animationView.playAnimation() + } + } + } + } + /** Shows swipe EDU tooltip if it is the current [tooltipStep]. */ fun maybeShowSwipeEdu() { if ( @@ -145,7 +166,9 @@ open class TaskbarEduTooltipController(context: Context) : requireViewById(R.id.taskbar_edu_title), TypefaceUtils.FONT_FAMILY_HEADLINE_SMALL_EMPHASIZED, ) - requireViewById(R.id.swipe_animation).supportLightTheme() + val swipeAnimation = requireViewById(R.id.swipe_animation) + swipeAnimation.supportLightTheme() + handleEduAnimations(listOf(swipeAnimation)) show() } } @@ -174,6 +197,7 @@ open class TaskbarEduTooltipController(context: Context) : splitscreenAnim.supportLightTheme() suggestionsAnim.supportLightTheme() pinningAnim.supportLightTheme() + handleEduAnimations(listOf(splitscreenAnim, suggestionsAnim, pinningAnim)) if (DisplayController.isTransientTaskbar(activityContext)) { splitscreenAnim.setAnimation(R.raw.taskbar_edu_splitscreen_transient) suggestionsAnim.setAnimation(R.raw.taskbar_edu_suggestions_transient) @@ -249,9 +273,6 @@ open class TaskbarEduTooltipController(context: Context) : tooltip?.run { allowTouchDismissal = true - requireViewById(R.id.standalone_pinning_animation) - .supportLightTheme() - TypefaceUtils.setTypeface( requireViewById(R.id.taskbar_edu_title), TypefaceUtils.FONT_FAMILY_HEADLINE_SMALL_EMPHASIZED, @@ -261,6 +282,10 @@ open class TaskbarEduTooltipController(context: Context) : TypefaceUtils.FONT_FAMILY_BODY_MEDIUM_BASELINE, ) + val pinningAnim = + requireViewById(R.id.standalone_pinning_animation) + pinningAnim.supportLightTheme() + handleEduAnimations(listOf(pinningAnim)) updateLayoutParams { if (DisplayController.isTransientTaskbar(activityContext)) { bottomMargin += activityContext.deviceProfile.taskbarHeight @@ -304,7 +329,9 @@ open class TaskbarEduTooltipController(context: Context) : inflateTooltip(R.layout.taskbar_edu_search) tooltip?.run { allowTouchDismissal = true - requireViewById(R.id.search_edu_animation).supportLightTheme() + val searchEdu = requireViewById(R.id.search_edu_animation) + searchEdu.supportLightTheme() + handleEduAnimations(listOf(searchEdu)) val eduSubtitle: TextView = requireViewById(R.id.search_edu_text) TypefaceUtils.setTypeface( diff --git a/src/com/android/launcher3/PagedView.java b/src/com/android/launcher3/PagedView.java index 5072e37314..d6abb56286 100644 --- a/src/com/android/launcher3/PagedView.java +++ b/src/com/android/launcher3/PagedView.java @@ -17,6 +17,7 @@ package com.android.launcher3; import static com.android.app.animation.Interpolators.SCROLL; +import static com.android.launcher3.RemoveAnimationSettingsTracker.WINDOW_ANIMATION_SCALE_URI; import static com.android.launcher3.compat.AccessibilityManagerCompat.isAccessibilityEnabled; import static com.android.launcher3.compat.AccessibilityManagerCompat.isObservedEventType; import static com.android.launcher3.testing.shared.TestProtocol.SCROLL_FINISHED_MESSAGE; @@ -33,7 +34,6 @@ import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Rect; import android.os.Bundle; -import android.provider.Settings; import android.util.AttributeSet; import android.util.Log; import android.view.InputDevice; @@ -1756,8 +1756,8 @@ public abstract class PagedView extends ViewGrou } if (FeatureFlags.IS_STUDIO_BUILD && !Utilities.isRunningInTestHarness()) { - duration *= Settings.Global.getFloat(getContext().getContentResolver(), - Settings.Global.WINDOW_ANIMATION_SCALE, 1); + duration *= RemoveAnimationSettingsTracker.INSTANCE.get(getContext()).getValue( + WINDOW_ANIMATION_SCALE_URI); } whichPage = validateNewPage(whichPage); diff --git a/src/com/android/launcher3/RemoveAnimationSettingsTracker.kt b/src/com/android/launcher3/RemoveAnimationSettingsTracker.kt new file mode 100644 index 0000000000..dbc04f1613 --- /dev/null +++ b/src/com/android/launcher3/RemoveAnimationSettingsTracker.kt @@ -0,0 +1,110 @@ +/* + * 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.launcher3 + +import android.content.Context +import android.database.ContentObserver +import android.net.Uri +import android.os.Handler +import android.os.Looper +import android.provider.Settings +import android.provider.Settings.Global.ANIMATOR_DURATION_SCALE +import android.provider.Settings.Global.TRANSITION_ANIMATION_SCALE +import android.provider.Settings.Global.WINDOW_ANIMATION_SCALE +import com.android.launcher3.dagger.ApplicationContext +import com.android.launcher3.dagger.LauncherAppComponent +import com.android.launcher3.dagger.LauncherAppSingleton +import com.android.launcher3.util.DaggerSingletonObject +import com.android.launcher3.util.DaggerSingletonTracker +import com.android.launcher3.util.Executors.UI_HELPER_EXECUTOR +import java.util.concurrent.ConcurrentHashMap +import javax.inject.Inject + +/** Tracker Class for when user turns on/off remove animation setting. */ +@LauncherAppSingleton +class RemoveAnimationSettingsTracker +@Inject +constructor(@ApplicationContext val context: Context, tracker: DaggerSingletonTracker) : + ContentObserver(Handler(Looper.getMainLooper())) { + + private val contentResolver = context.contentResolver + + /** Caches the last seen value for registered keys. */ + private val cache: MutableMap = ConcurrentHashMap() + + init { + UI_HELPER_EXECUTOR.execute { + contentResolver.registerContentObserver(WINDOW_ANIMATION_SCALE_URI, false, this) + contentResolver.registerContentObserver(TRANSITION_ANIMATION_SCALE_URI, false, this) + contentResolver.registerContentObserver(ANIMATOR_DURATION_SCALE_URI, false, this) + } + + tracker.addCloseable { + UI_HELPER_EXECUTOR.execute { contentResolver.unregisterContentObserver(this) } + } + } + + /** + * Returns the value for this classes key from the cache. If not in cache, will call + * [updateValue] to fetch. + */ + fun getValue(uri: Uri): Float { + return getValue(uri, 1f) + } + + /** + * Returns the value for this classes key from the cache. If not in cache, will call + * [getValueFromSettingsGlobal] to fetch. + */ + private fun getValue(uri: Uri, defaultValue: Float): Float { + return cache.computeIfAbsent(uri) { getValueFromSettingsGlobal(uri, defaultValue) } + } + + /** Returns if user has opted into having no animation on their device. */ + fun isRemoveAnimationEnabled(): Boolean { + return getValue(WINDOW_ANIMATION_SCALE_URI) == 0f && + getValue(TRANSITION_ANIMATION_SCALE_URI) == 0f && + getValue(ANIMATOR_DURATION_SCALE_URI) == 0f + } + + override fun onChange(selfChange: Boolean, uri: Uri?) { + if (uri == null) return + updateValue(uri) + } + + private fun getValueFromSettingsGlobal(uri: Uri, defaultValue: Float = 1f): Float { + return Settings.Global.getFloat(contentResolver, uri.lastPathSegment, defaultValue) + } + + private fun updateValue(uri: Uri, defaultValue: Float = 1f) { + val newValue = getValueFromSettingsGlobal(uri, defaultValue) + cache[uri] = newValue + } + + companion object { + @JvmField + val INSTANCE = + DaggerSingletonObject(LauncherAppComponent::getRemoveAnimationSettingsTracker) + @JvmField + val WINDOW_ANIMATION_SCALE_URI: Uri = Settings.Global.getUriFor(WINDOW_ANIMATION_SCALE) + @JvmField + val TRANSITION_ANIMATION_SCALE_URI: Uri = + Settings.Global.getUriFor(TRANSITION_ANIMATION_SCALE) + @JvmField + val ANIMATOR_DURATION_SCALE_URI: Uri = Settings.Global.getUriFor(ANIMATOR_DURATION_SCALE) + } +} diff --git a/src/com/android/launcher3/dagger/LauncherBaseAppComponent.java b/src/com/android/launcher3/dagger/LauncherBaseAppComponent.java index 249a2141b7..150761f75c 100644 --- a/src/com/android/launcher3/dagger/LauncherBaseAppComponent.java +++ b/src/com/android/launcher3/dagger/LauncherBaseAppComponent.java @@ -23,6 +23,7 @@ import androidx.annotation.Nullable; import com.android.launcher3.InvariantDeviceProfile; import com.android.launcher3.LauncherAppState; import com.android.launcher3.LauncherPrefs; +import com.android.launcher3.RemoveAnimationSettingsTracker; import com.android.launcher3.graphics.GridCustomizationsProxy; import com.android.launcher3.graphics.ThemeManager; import com.android.launcher3.icons.LauncherIcons.IconPool; @@ -80,8 +81,8 @@ public interface LauncherBaseAppComponent { LockedUserState getLockedUserState(); InvariantDeviceProfile getIDP(); IconPool getIconPool(); + RemoveAnimationSettingsTracker getRemoveAnimationSettingsTracker(); LauncherAppState getLauncherAppState(); - GridCustomizationsProxy getGridCustomizationsProxy(); /** Builder for LauncherBaseAppComponent. */ From de841f609253aabd1c9926159559ff349797002e Mon Sep 17 00:00:00 2001 From: Schneider Victor-Tulias Date: Fri, 21 Feb 2025 12:59:59 -0500 Subject: [PATCH 101/153] Respect accessibility animation guidelines in AllSetActivity - Disabling the background animation if the user has opted out - Allow the user to pause/resume the animation Flag: EXEMPT bug fix Fixes: 386743741 Test: launched AllSetActivity with animations on/off; tapped screen in both cases Change-Id: I2bdbef24d6c582b4229441149fffcb67ba488882 --- quickstep/res/layout/activity_allset.xml | 6 ++-- quickstep/res/values-sw600dp-land/dimens.xml | 2 +- quickstep/res/values-sw600dp/dimens.xml | 2 +- quickstep/res/values/dimens.xml | 2 +- .../quickstep/interaction/AllSetActivity.java | 28 +++++++++++++++++-- 5 files changed, 31 insertions(+), 9 deletions(-) diff --git a/quickstep/res/layout/activity_allset.xml b/quickstep/res/layout/activity_allset.xml index 625d9b361d..3d68dfb93a 100644 --- a/quickstep/res/layout/activity_allset.xml +++ b/quickstep/res/layout/activity_allset.xml @@ -29,7 +29,6 @@ android:layout_height="match_parent" android:gravity="center" android:scaleType="centerCrop" - app:lottie_autoPlay="true" app:lottie_loop="true" app:layout_constraintTop_toTopOf="parent" @@ -49,11 +48,10 @@ app:layout_constraintEnd_toEndOf="parent"> - 48dp + 48dp 48dp diff --git a/quickstep/res/values-sw600dp/dimens.xml b/quickstep/res/values-sw600dp/dimens.xml index 49965822ea..3e726519ac 100644 --- a/quickstep/res/values-sw600dp/dimens.xml +++ b/quickstep/res/values-sw600dp/dimens.xml @@ -37,7 +37,7 @@ 24dp - 120dp + 120dp 38sp 15sp diff --git a/quickstep/res/values/dimens.xml b/quickstep/res/values/dimens.xml index 05f0695b7c..52ebdae31c 100644 --- a/quickstep/res/values/dimens.xml +++ b/quickstep/res/values/dimens.xml @@ -277,7 +277,7 @@ 24dp - 40dp + 40dp 36sp 14sp diff --git a/quickstep/src/com/android/quickstep/interaction/AllSetActivity.java b/quickstep/src/com/android/quickstep/interaction/AllSetActivity.java index 953b0c56b4..c1bb2501b6 100644 --- a/quickstep/src/com/android/quickstep/interaction/AllSetActivity.java +++ b/quickstep/src/com/android/quickstep/interaction/AllSetActivity.java @@ -64,6 +64,7 @@ import com.android.launcher3.DeviceProfile; import com.android.launcher3.InvariantDeviceProfile; import com.android.launcher3.LauncherAppState; import com.android.launcher3.R; +import com.android.launcher3.RemoveAnimationSettingsTracker; import com.android.launcher3.Utilities; import com.android.launcher3.anim.AnimatedFloat; import com.android.launcher3.anim.AnimatorPlaybackController; @@ -107,6 +108,9 @@ public class AllSetActivity extends Activity { private static final float ANIMATION_PAUSE_ALPHA_THRESHOLD = 0.1f; + private static final String KEY_BACKGROUND_ANIMATION_TOGGLED_ON = + "background_animation_toggled_on"; + private final AnimatedFloat mSwipeProgress = new AnimatedFloat(this::onSwipeProgressUpdate); private final InvariantDeviceProfile.OnIDPChangeListener mOnIDPChangeListener = @@ -124,6 +128,9 @@ public class AllSetActivity extends Activity { private AnimatorPlaybackController mLauncherStartAnim = null; + // Auto play background animation by default + private boolean mBackgroundAnimationToggledOn = true; + private TextView mHintView; private final OverviewChangeListener mOverviewChangeListener = this::onOverviewTargetChange; @@ -200,6 +207,15 @@ public class AllSetActivity extends Activity { LOTTIE_TERTIARY_COLOR_TOKEN, R.color.all_set_bg_tertiary), getTheme()); + mBackgroundAnimationToggledOn = savedInstanceState == null + || savedInstanceState.getBoolean(KEY_BACKGROUND_ANIMATION_TOGGLED_ON, true); + // The animated background is behind a scroll view, which intercepts all input. + // However, the content view also covers the full screen + requireViewById(R.id.content).setOnClickListener(v -> { + mBackgroundAnimationToggledOn = !mBackgroundAnimationToggledOn; + maybeResumeOrPauseBackgroundAnimation(); + }); + setUpBackgroundAnimation(getDP().isTablet); getIDP().addOnChangeListener(mOnIDPChangeListener); @@ -208,6 +224,12 @@ public class AllSetActivity extends Activity { ActivityPreloadUtil.preloadOverviewForSUWAllSet(this); } + @Override + protected void onSaveInstanceState(Bundle outState) { + super.onSaveInstanceState(outState); + outState.putBoolean(KEY_BACKGROUND_ANIMATION_TOGGLED_ON, mBackgroundAnimationToggledOn); + } + private InvariantDeviceProfile getIDP() { return LauncherAppState.getInstance(this).getInvariantDeviceProfile(); } @@ -368,8 +390,10 @@ public class AllSetActivity extends Activity { private void maybeResumeOrPauseBackgroundAnimation() { boolean shouldPlayAnimation = - getContentViewAlphaForSwipeProgress() > ANIMATION_PAUSE_ALPHA_THRESHOLD - && isResumed(); + !RemoveAnimationSettingsTracker.INSTANCE.get(this).isRemoveAnimationEnabled() + && getContentViewAlphaForSwipeProgress() > ANIMATION_PAUSE_ALPHA_THRESHOLD + && isResumed() + && mBackgroundAnimationToggledOn; if (mAnimatedBackground.isAnimating() && !shouldPlayAnimation) { mAnimatedBackground.pauseAnimation(); } else if (!mAnimatedBackground.isAnimating() && shouldPlayAnimation) { From b1fab90e26ed05d53fd07e7af41f53ef8963b4ff Mon Sep 17 00:00:00 2001 From: Sunny Goyal Date: Mon, 24 Feb 2025 10:25:45 -0800 Subject: [PATCH 102/153] Enforcing grid customization permission in manifest instead of code Bug: 389173244 Test: Updated tests Flag: EXEMPT manifest change Change-Id: I0fee57f935156da6b2b5a612259db2c4b3605846 --- AndroidManifest-common.xml | 6 ++---- .../launcher3/graphics/GridCustomizationsProxy.java | 8 -------- .../launcher3/ui/workspace/ThemeIconsTest.java | 13 ++++++------- 3 files changed, 8 insertions(+), 19 deletions(-) diff --git a/AndroidManifest-common.xml b/AndroidManifest-common.xml index fe57da11fc..46f0e41cdb 100644 --- a/AndroidManifest-common.xml +++ b/AndroidManifest-common.xml @@ -131,13 +131,11 @@ android:writePermission="${applicationId}.permission.WRITE_SETTINGS" android:readPermission="${applicationId}.permission.READ_SETTINGS" /> - + 6dp + 4dp 10dp diff --git a/src/com/android/launcher3/pageindicators/PageIndicatorDots.java b/src/com/android/launcher3/pageindicators/PageIndicatorDots.java index a691e45097..37f51899aa 100644 --- a/src/com/android/launcher3/pageindicators/PageIndicatorDots.java +++ b/src/com/android/launcher3/pageindicators/PageIndicatorDots.java @@ -16,6 +16,7 @@ package com.android.launcher3.pageindicators; +import static com.android.launcher3.Flags.enableLauncherVisualRefresh; import static com.android.launcher3.config.FeatureFlags.FOLDABLE_SINGLE_PAGE; import android.animation.Animator; @@ -57,8 +58,8 @@ import com.android.launcher3.util.Themes; public class PageIndicatorDots extends View implements Insettable, PageIndicator { private static final float SHIFT_PER_ANIMATION = 0.5f; - private static final float SHIFT_THRESHOLD = 0.1f; - private static final long ANIMATION_DURATION = 150; + private static final float SHIFT_THRESHOLD = (enableLauncherVisualRefresh() ? 0.5f : 0.2f); + private static final long ANIMATION_DURATION = (enableLauncherVisualRefresh() ? 200 : 150); private static final int PAGINATION_FADE_DELAY = ViewConfiguration.getScrollDefaultDelay(); private static final int PAGINATION_FADE_IN_DURATION = 83; private static final int PAGINATION_FADE_OUT_DURATION = 167; @@ -78,6 +79,7 @@ public class PageIndicatorDots extends View implements Insettable, PageIndicator // This value approximately overshoots to 1.5 times the original size. private static final float ENTER_ANIMATION_OVERSHOOT_TENSION = 4.9f; + // This is used to optimize the onDraw method by not constructing a new RectF each draw. private static final RectF sTempRect = new RectF(); private static final FloatProperty CURRENT_POSITION = @@ -93,7 +95,7 @@ public class PageIndicatorDots extends View implements Insettable, PageIndicator obj.invalidate(); obj.invalidateOutline(); } - }; + }; private static final IntProperty PAGINATION_ALPHA = new IntProperty("pagination_alpha") { @@ -111,6 +113,7 @@ public class PageIndicatorDots extends View implements Insettable, PageIndicator private final Handler mDelayedPaginationFadeHandler = new Handler(Looper.getMainLooper()); private final float mDotRadius; + private final float mGapWidth; private final float mCircleGap; private final boolean mIsRtl; @@ -130,6 +133,7 @@ public class PageIndicatorDots extends View implements Insettable, PageIndicator * 1.0 => Active dot is at position 1 */ private float mCurrentPosition; + private int mLastPosition; private float mFinalPosition; private boolean mIsScrollPaused; @VisibleForTesting @@ -157,7 +161,10 @@ public class PageIndicatorDots extends View implements Insettable, PageIndicator mPaginationPaint.setStyle(Style.FILL); mPaginationPaint.setColor(Themes.getAttrColor(context, R.attr.pageIndicatorDotColor)); mDotRadius = getResources().getDimension(R.dimen.page_indicator_dot_size) / 2; - mCircleGap = DOT_GAP_FACTOR * mDotRadius; + mGapWidth = getResources().getDimension(R.dimen.page_indicator_gap_width); + mCircleGap = (enableLauncherVisualRefresh()) + ? mDotRadius * 2 + mGapWidth + : DOT_GAP_FACTOR * mDotRadius; setOutlineProvider(new MyOutlineProver()); mIsRtl = Utilities.isRtl(getResources()); } @@ -188,29 +195,40 @@ public class PageIndicatorDots extends View implements Insettable, PageIndicator mTotalScroll = totalScroll; - int scrollPerPage = totalScroll / (mNumPages - 1); - int pageToLeft = scrollPerPage == 0 ? 0 : currentScroll / scrollPerPage; - int pageToLeftScroll = pageToLeft * scrollPerPage; - int pageToRightScroll = pageToLeftScroll + scrollPerPage; + if (enableLauncherVisualRefresh()) { + float scrollPerPage = (float) totalScroll / (mNumPages - 1); + float position = currentScroll / scrollPerPage; + animateToPosition(Math.round(position)); - float scrollThreshold = SHIFT_THRESHOLD * scrollPerPage; - if (currentScroll < pageToLeftScroll + scrollThreshold) { - // scroll is within the left page's threshold - animateToPosition(pageToLeft); - if (mShouldAutoHide) { - hideAfterDelay(); - } - } else if (currentScroll > pageToRightScroll - scrollThreshold) { - // scroll is far enough from left page to go to the right page - animateToPosition(pageToLeft + 1); - if (mShouldAutoHide) { + float delta = Math.abs((int) position - position); + if (mShouldAutoHide && (delta < 0.1 || delta > 0.9)) { hideAfterDelay(); } } else { - // scroll is between left and right page - animateToPosition(pageToLeft + SHIFT_PER_ANIMATION); - if (mShouldAutoHide) { - mDelayedPaginationFadeHandler.removeCallbacksAndMessages(null); + int scrollPerPage = totalScroll / (mNumPages - 1); + int pageToLeft = scrollPerPage == 0 ? 0 : currentScroll / scrollPerPage; + int pageToLeftScroll = pageToLeft * scrollPerPage; + int pageToRightScroll = pageToLeftScroll + scrollPerPage; + + float scrollThreshold = SHIFT_THRESHOLD * scrollPerPage; + if (currentScroll < pageToLeftScroll + scrollThreshold) { + // scroll is within the left page's threshold + animateToPosition(pageToLeft); + if (mShouldAutoHide) { + hideAfterDelay(); + } + } else if (currentScroll > pageToRightScroll - scrollThreshold) { + // scroll is far enough from left page to go to the right page + animateToPosition(pageToLeft + 1); + if (mShouldAutoHide) { + hideAfterDelay(); + } + } else { + // scroll is between left and right page + animateToPosition(pageToLeft + SHIFT_PER_ANIMATION); + if (mShouldAutoHide) { + mDelayedPaginationFadeHandler.removeCallbacksAndMessages(null); + } } } } @@ -283,15 +301,23 @@ public class PageIndicatorDots extends View implements Insettable, PageIndicator private void animateToPosition(float position) { mFinalPosition = position; - if (Math.abs(mCurrentPosition - mFinalPosition) < SHIFT_THRESHOLD) { + if (!enableLauncherVisualRefresh() + && Math.abs(mCurrentPosition - mFinalPosition) < SHIFT_THRESHOLD) { mCurrentPosition = mFinalPosition; } - if (mAnimator == null && Float.compare(mCurrentPosition, mFinalPosition) != 0) { - float positionForThisAnim = mCurrentPosition > mFinalPosition ? - mCurrentPosition - SHIFT_PER_ANIMATION : mCurrentPosition + SHIFT_PER_ANIMATION; + if (mAnimator == null && Float.compare(mCurrentPosition, position) != 0) { + float positionForThisAnim = enableLauncherVisualRefresh() + ? position + : (mCurrentPosition > mFinalPosition + ? mCurrentPosition - SHIFT_PER_ANIMATION + : mCurrentPosition + SHIFT_PER_ANIMATION); mAnimator = ObjectAnimator.ofFloat(this, CURRENT_POSITION, positionForThisAnim); mAnimator.addListener(new AnimationCycleListener()); mAnimator.setDuration(ANIMATION_DURATION); + if (enableLauncherVisualRefresh()) { + mLastPosition = (int) mCurrentPosition; + mAnimator.setInterpolator(new OvershootInterpolator()); + } mAnimator.start(); } } @@ -314,6 +340,7 @@ public class PageIndicatorDots extends View implements Insettable, PageIndicator invalidate(); } + // TODO(b/394355070): Verify Folder Entry Animation works correctly with visual updates public void playEntryAnimation() { int count = mEntryAnimationRadiusFactors.length; if (count == 0) { @@ -391,6 +418,7 @@ public class PageIndicatorDots extends View implements Insettable, PageIndicator @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + // TODO(b/394355070): Verify Folder Entry Animation works correctly with visual updates // Add extra spacing of mDotRadius on all sides so than entry animation could be run. int width = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY ? MeasureSpec.getSize(widthMeasureSpec) : (int) ((mNumPages * 3 + 2) * mDotRadius); @@ -410,17 +438,14 @@ public class PageIndicatorDots extends View implements Insettable, PageIndicator return; } - // Draw all page indicators; float circleGap = mCircleGap; - float startX = ((float) getWidth() / 2) - - (mCircleGap * (((float) mNumPages - 1) / 2)) - - mDotRadius; - - float x = startX + mDotRadius; + float x = ((float) getWidth() / 2) - (mCircleGap * ((float) mNumPages - 1) / 2); float y = getHeight() / 2; if (mEntryAnimationRadiusFactors != null) { // During entry animation, only draw the circles + // TODO(b/394355070): Verify Folder Entry Animation works correctly - visual updates + if (mIsRtl) { x = getWidth() - x; circleGap = -circleGap; @@ -432,18 +457,84 @@ public class PageIndicatorDots extends View implements Insettable, PageIndicator x += circleGap; } } else { + // Save the current alpha value, so we can reset to it again after drawing the dots int alpha = mPaginationPaint.getAlpha(); - // Here we draw the dots - mPaginationPaint.setAlpha((int) (alpha * DOT_ALPHA_FRACTION)); - for (int i = 0; i < mNumPages; i++) { - canvas.drawCircle(x, y, mDotRadius, mPaginationPaint); - x += circleGap; + if (enableLauncherVisualRefresh()) { + int nonActiveAlpha = (int) (alpha * DOT_ALPHA_FRACTION); + + float diameter = 2 * mDotRadius; + sTempRect.top = y - mDotRadius; + sTempRect.bottom = y + mDotRadius; + sTempRect.left = x - diameter; + + float posDif = Math.abs(mLastPosition - mCurrentPosition); + float boundedPosition = (posDif > 1) + ? Math.round(mCurrentPosition) + : mCurrentPosition; + float bounceProgress = (posDif > 1) ? posDif - 1 : 0; + float bounceAdjustment = Math.abs(mCurrentPosition - boundedPosition) * diameter; + + // Here we draw the dots, one at a time from the left-most dot to the right-most dot + // 1.0 => 000000 000000111111 000000 + // 1.3 => 000000 0000001111 11000000 + // 1.6 => 000000 00000011 1111000000 + // 2.0 => 000000 000000 111111000000 + for (int i = 0; i < mNumPages; i++) { + mPaginationPaint.setAlpha(nonActiveAlpha); + float delta = Math.abs(boundedPosition - i); + if (delta <= SHIFT_THRESHOLD) { + mPaginationPaint.setAlpha(alpha); + } + + // If boundedPosition is 3.3, both 3 and 4 should enter this condition. + // If boundedPosition is 3, only 3 should enter this condition. + if (delta < 1) { + sTempRect.right = sTempRect.left + diameter + ((1 - delta) * diameter); + + // While the animation is shifting the active pagination dots size from + // the previously active one, to the newly active dot, there is no bounce + // adjustment. The bounce happens in the "Overshoot" phase of the animation. + // mLastPosition is used to determine when the currentPosition is just + // leaving the page, or if it is in the overshoot phase. + if (boundedPosition == i && bounceProgress != 0) { + if (mLastPosition < mCurrentPosition) { + sTempRect.left -= bounceAdjustment; + } else { + sTempRect.right += bounceAdjustment; + } + } + } else { + sTempRect.right = sTempRect.left + diameter; + + if (mLastPosition == i && bounceProgress != 0) { + if (mLastPosition > mCurrentPosition) { + sTempRect.left += bounceAdjustment; + } else { + sTempRect.right -= bounceAdjustment; + } + } + } + canvas.drawRoundRect(sTempRect, mDotRadius, mDotRadius, mPaginationPaint); + + // TODO(b/394355070) Verify RTL experience works correctly with visual updates + sTempRect.left = sTempRect.right + mGapWidth; + } + } else { + // Here we draw the dots + mPaginationPaint.setAlpha((int) (alpha * DOT_ALPHA_FRACTION)); + for (int i = 0; i < mNumPages; i++) { + canvas.drawCircle(x, y, mDotRadius, mPaginationPaint); + x += circleGap; + } + + // Here we draw the current page indicator + mPaginationPaint.setAlpha(alpha); + canvas.drawRoundRect(getActiveRect(), mDotRadius, mDotRadius, mPaginationPaint); } - // Here we draw the current page indicator + // Reset the alpha so it doesn't become progressively more transparent each onDraw call mPaginationPaint.setAlpha(alpha); - canvas.drawRoundRect(getActiveRect(), mDotRadius, mDotRadius, mPaginationPaint); } } @@ -499,6 +590,7 @@ public class PageIndicatorDots extends View implements Insettable, PageIndicator @Override public void getOutline(View view, Outline outline) { if (mEntryAnimationRadiusFactors == null) { + // TODO(b/394355070): Verify Outline works correctly with visual updates RectF activeRect = getActiveRect(); outline.setRoundRect( (int) activeRect.left, From 3fe4e7d90fc6c3d09b39f93c438a24864bbfe260 Mon Sep 17 00:00:00 2001 From: Saumya Prakash Date: Wed, 26 Feb 2025 05:41:08 +0000 Subject: [PATCH 124/153] Ensure Talkback announces text correctly in Gesture tutorial This change modifies how Talkback announces the title and the subtitle in the gesture navigation tutorial. It no longer shifts the focus to the subtitle, but instead makes the whole window focusable. Fix: 386884587 Test: Open the gesture tutorial with talkback and ensure the text is announced without change of focus. Ensure the Done button doesn't get announced Flag: EXEMPT bugfix Change-Id: Id28382acbebe763f2f64f4e49eb00d6ea61e0553 --- .../redesigned_gesture_tutorial_fragment.xml | 5 +-- .../interaction/TutorialController.java | 43 ++----------------- 2 files changed, 5 insertions(+), 43 deletions(-) diff --git a/quickstep/res/layout/redesigned_gesture_tutorial_fragment.xml b/quickstep/res/layout/redesigned_gesture_tutorial_fragment.xml index 7530c286f4..8ca59c4591 100644 --- a/quickstep/res/layout/redesigned_gesture_tutorial_fragment.xml +++ b/quickstep/res/layout/redesigned_gesture_tutorial_fragment.xml @@ -137,6 +137,7 @@ android:layout_above="@id/gesture_tutorial_fragment_action_button" android:layout_centerHorizontal="true" android:background="@android:color/transparent" + android:screenReaderFocusable="true" android:paddingTop="24dp" android:paddingHorizontal="24dp" android:layout_marginBottom="16dp"> @@ -146,8 +147,6 @@ android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="104dp" - android:accessibilityHeading="true" - android:accessibilityTraversalBefore="@id/gesture_tutorial_fragment_feedback_subtitle" android:gravity="top" android:lineSpacingExtra="-1sp" android:textAppearance="@style/TextAppearance.GestureTutorial.MainTitle" @@ -162,8 +161,6 @@ android:layout_marginTop="24dp" android:lineSpacingExtra="4sp" android:textAppearance="@style/TextAppearance.GestureTutorial.MainSubtitle" - android:accessibilityTraversalAfter="@id/gesture_tutorial_fragment_feedback_title" - android:accessibilityTraversalBefore="@id/gesture_tutorial_fragment_action_button" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@id/gesture_tutorial_fragment_feedback_title" /> diff --git a/quickstep/src/com/android/quickstep/interaction/TutorialController.java b/quickstep/src/com/android/quickstep/interaction/TutorialController.java index 0fc95e2102..5c48668504 100644 --- a/quickstep/src/com/android/quickstep/interaction/TutorialController.java +++ b/quickstep/src/com/android/quickstep/interaction/TutorialController.java @@ -36,7 +36,6 @@ import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.view.ViewOutlineProvider; -import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityManager; import android.widget.Button; import android.widget.FrameLayout; @@ -123,13 +122,10 @@ abstract class TutorialController implements BackGestureAttemptCallback, // These runnables should be used when posting callbacks to their views and cleared from their // views before posting new callbacks. - private final Runnable mTitleViewCallback; - private final Runnable mSubtitleViewCallback; @Nullable private Runnable mFeedbackViewCallback; @Nullable private Runnable mFakeTaskViewCallback; @Nullable private Runnable mFakeTaskbarViewCallback; private final Runnable mShowFeedbackRunnable; - private final AccessibilityManager mAccessibilityManager; TutorialController(TutorialFragment tutorialFragment, TutorialType tutorialType) { mTutorialFragment = tutorialFragment; @@ -185,17 +181,6 @@ abstract class TutorialController implements BackGestureAttemptCallback, outline.setRoundRect(mExitingAppRect, mExitingAppRadius); } }); - - mAccessibilityManager = AccessibilityManager.getInstance(mContext); - mTitleViewCallback = () -> { - mFeedbackTitleView.requestFocus(); - mFeedbackTitleView.sendAccessibilityEvent( - AccessibilityEvent.TYPE_VIEW_FOCUSED); - }; - mSubtitleViewCallback = () -> { - mFeedbackSubtitleView.requestFocus(); - mFeedbackSubtitleView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); - }; mShowFeedbackRunnable = () -> { mFeedbackView.setAlpha(0f); mFeedbackView.setScaleX(0.95f); @@ -214,14 +199,14 @@ abstract class TutorialController implements BackGestureAttemptCallback, mFeedbackViewCallback = mTutorialFragment::continueTutorial; mFeedbackView.postDelayed( mFeedbackViewCallback, - mAccessibilityManager.getRecommendedTimeoutMillis( - ADVANCE_TUTORIAL_TIMEOUT_MS, - AccessibilityManager.FLAG_CONTENT_TEXT + AccessibilityManager.getInstance(mContext) + .getRecommendedTimeoutMillis( + ADVANCE_TUTORIAL_TIMEOUT_MS, + AccessibilityManager.FLAG_CONTENT_TEXT | AccessibilityManager.FLAG_CONTENT_CONTROLS)); } }) .start(); - mFeedbackTitleView.postDelayed(mTitleViewCallback, FEEDBACK_ANIMATION_MS); }; } @@ -414,8 +399,6 @@ abstract class TutorialController implements BackGestureAttemptCallback, int titleResId, int subtitleResId, boolean isGestureSuccessful) { - mFeedbackTitleView.removeCallbacks(mTitleViewCallback); - mFeedbackSubtitleView.removeCallbacks(mSubtitleViewCallback); if (mFeedbackViewCallback != null) { mFeedbackView.removeCallbacks(mFeedbackViewCallback); mFeedbackViewCallback = null; @@ -423,15 +406,6 @@ abstract class TutorialController implements BackGestureAttemptCallback, mFeedbackTitleView.setText(titleResId); mFeedbackSubtitleView.setText(subtitleResId); - mFeedbackTitleView.postDelayed(mTitleViewCallback, mAccessibilityManager - .getRecommendedTimeoutMillis( - FEEDBACK_ANIMATION_MS, - AccessibilityManager.FLAG_CONTENT_TEXT)); - mFeedbackSubtitleView.postDelayed(mSubtitleViewCallback, mAccessibilityManager - .getRecommendedTimeoutMillis( - SUBTITLE_ANNOUNCE_DELAY_MS, - AccessibilityManager.FLAG_CONTENT_TEXT)); - if (isGestureSuccessful) { if (mTutorialFragment.isAtFinalStep()) { showActionButton(); @@ -487,8 +461,6 @@ abstract class TutorialController implements BackGestureAttemptCallback, mFakeTaskbarView.removeCallbacks(mFakeTaskbarViewCallback); mFakeTaskbarViewCallback = null; } - mFeedbackTitleView.removeCallbacks(mTitleViewCallback); - mFeedbackSubtitleView.removeCallbacks(mSubtitleViewCallback); } private void playFeedbackAnimation() { @@ -564,13 +536,6 @@ abstract class TutorialController implements BackGestureAttemptCallback, mSkipButton.setVisibility(GONE); mDoneButton.setVisibility(View.VISIBLE); mDoneButton.setOnClickListener(this::onActionButtonClicked); - mDoneButton.postDelayed(() -> { - mDoneButton.requestFocus(); - mDoneButton.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); - }, mAccessibilityManager - .getRecommendedTimeoutMillis( - DONE_BUTTON_ANNOUNCE_DELAY_MS, - AccessibilityManager.FLAG_CONTENT_CONTROLS)); } void hideFakeTaskbar(boolean animateToHotseat) { From b8aacf2d933cd438bb65acb7fff66b92d74278c7 Mon Sep 17 00:00:00 2001 From: minch Date: Tue, 25 Feb 2025 06:02:19 +0000 Subject: [PATCH 125/153] Convert ClearAllButton to Kotlin Bug: 389209338 Flag: EXEMPT refactor Test: m Change-Id: Iaafe69ae14744e418d3c30d4d9fc6f417f36f230 --- .../quickstep/views/ClearAllButton.java | 333 ------------------ .../android/quickstep/views/ClearAllButton.kt | 269 ++++++++++++++ 2 files changed, 269 insertions(+), 333 deletions(-) delete mode 100644 quickstep/src/com/android/quickstep/views/ClearAllButton.java create mode 100644 quickstep/src/com/android/quickstep/views/ClearAllButton.kt diff --git a/quickstep/src/com/android/quickstep/views/ClearAllButton.java b/quickstep/src/com/android/quickstep/views/ClearAllButton.java deleted file mode 100644 index 24266974ce..0000000000 --- a/quickstep/src/com/android/quickstep/views/ClearAllButton.java +++ /dev/null @@ -1,333 +0,0 @@ -/* - * Copyright (C) 2018 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.views; - -import static com.android.quickstep.util.BorderAnimator.DEFAULT_BORDER_COLOR; - -import android.content.Context; -import android.content.res.Resources; -import android.content.res.TypedArray; -import android.graphics.Canvas; -import android.graphics.Rect; -import android.util.AttributeSet; -import android.util.FloatProperty; -import android.widget.Button; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; - -import com.android.launcher3.Flags; -import com.android.launcher3.R; -import com.android.quickstep.orientation.RecentsPagedOrientationHandler; -import com.android.quickstep.util.BorderAnimator; - -import kotlin.Unit; - -public class ClearAllButton extends Button { - - public static final FloatProperty VISIBILITY_ALPHA = - new FloatProperty("visibilityAlpha") { - @Override - public Float get(ClearAllButton view) { - return view.mVisibilityAlpha; - } - - @Override - public void setValue(ClearAllButton view, float v) { - view.setVisibilityAlpha(v); - } - }; - - public static final FloatProperty DISMISS_ALPHA = - new FloatProperty("dismissAlpha") { - @Override - public Float get(ClearAllButton view) { - return view.mDismissAlpha; - } - - @Override - public void setValue(ClearAllButton view, float v) { - view.setDismissAlpha(v); - } - }; - - private float mScrollAlpha = 1; - private float mContentAlpha = 1; - private float mVisibilityAlpha = 1; - private float mDismissAlpha = 1; - private float mFullscreenProgress = 1; - private float mGridProgress = 1; - - private boolean mIsRtl; - private float mNormalTranslationPrimary; - private float mFullscreenTranslationPrimary; - private float mGridTranslationPrimary; - private float mTaskAlignmentTranslationY; - private float mGridScrollOffset; - private float mScrollOffsetPrimary; - - private int mSidePadding; - private int mOutlinePadding; - private boolean mBorderEnabled; - @Nullable - private final BorderAnimator mFocusBorderAnimator; - - public ClearAllButton(Context context, AttributeSet attrs) { - super(context, attrs); - mIsRtl = getLayoutDirection() == LAYOUT_DIRECTION_RTL; - - if (Flags.enableFocusOutline()) { - TypedArray styledAttrs = context.obtainStyledAttributes(attrs, - R.styleable.ClearAllButton); - Resources resources = getResources(); - mOutlinePadding = resources.getDimensionPixelSize( - R.dimen.recents_clear_all_outline_padding); - mFocusBorderAnimator = - BorderAnimator.createSimpleBorderAnimator( - /* borderRadiusPx= */ resources.getDimensionPixelSize( - R.dimen.recents_clear_all_outline_radius), - /* borderWidthPx= */ context.getResources().getDimensionPixelSize( - R.dimen.keyboard_quick_switch_border_width), - /* boundsBuilder= */ this::updateBorderBounds, - /* targetView= */ this, - /* borderColor= */ styledAttrs.getColor( - R.styleable.ClearAllButton_focusBorderColor, - DEFAULT_BORDER_COLOR)); - styledAttrs.recycle(); - } else { - mFocusBorderAnimator = null; - } - } - - private Unit updateBorderBounds(@NonNull Rect bounds) { - bounds.set(0, 0, getWidth(), getHeight()); - // Make the value negative to form a padding between button and outline - bounds.inset(-mOutlinePadding, -mOutlinePadding); - return Unit.INSTANCE; - } - - @Override - public void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) { - super.onFocusChanged(gainFocus, direction, previouslyFocusedRect); - if (mFocusBorderAnimator != null && mBorderEnabled) { - mFocusBorderAnimator.setBorderVisibility(gainFocus, /* animated= */ true); - } - } - - /** - * Enable or disable showing border on focus change - */ - public void setBorderEnabled(boolean enabled) { - if (mBorderEnabled == enabled) { - return; - } - - mBorderEnabled = enabled; - if (mFocusBorderAnimator != null) { - mFocusBorderAnimator.setBorderVisibility(/* visible= */ - enabled && isFocused(), /* animated= */true); - } - } - - @Override - public void draw(Canvas canvas) { - if (mFocusBorderAnimator != null) { - mFocusBorderAnimator.drawBorder(canvas); - } - super.draw(canvas); - } - - @Override - protected void onLayout(boolean changed, int left, int top, int right, int bottom) { - super.onLayout(changed, left, top, right, bottom); - RecentsPagedOrientationHandler orientationHandler = - getRecentsView().getPagedOrientationHandler(); - mSidePadding = orientationHandler.getClearAllSidePadding(getRecentsView(), mIsRtl); - } - - private RecentsView getRecentsView() { - return (RecentsView) getParent(); - } - - @Override - public void onRtlPropertiesChanged(int layoutDirection) { - super.onRtlPropertiesChanged(layoutDirection); - mIsRtl = getLayoutDirection() == LAYOUT_DIRECTION_RTL; - } - - @Override - public boolean hasOverlappingRendering() { - return false; - } - - public float getScrollAlpha() { - return mScrollAlpha; - } - - public void setContentAlpha(float alpha) { - if (mContentAlpha != alpha) { - mContentAlpha = alpha; - updateAlpha(); - } - } - - public void setVisibilityAlpha(float alpha) { - if (mVisibilityAlpha != alpha) { - mVisibilityAlpha = alpha; - updateAlpha(); - } - } - - public void setDismissAlpha(float alpha) { - if (mDismissAlpha != alpha) { - mDismissAlpha = alpha; - updateAlpha(); - } - } - - public void onRecentsViewScroll(int scroll, boolean gridEnabled) { - RecentsView recentsView = getRecentsView(); - if (recentsView == null) { - return; - } - - RecentsPagedOrientationHandler orientationHandler = - recentsView.getPagedOrientationHandler(); - float orientationSize = orientationHandler.getPrimaryValue(getWidth(), getHeight()); - if (orientationSize == 0) { - return; - } - - int clearAllScroll = recentsView.getClearAllScroll(); - int adjustedScrollFromEdge = Math.abs(scroll - clearAllScroll); - float shift = Math.min(adjustedScrollFromEdge, orientationSize); - mNormalTranslationPrimary = mIsRtl ? -shift : shift; - if (!gridEnabled) { - mNormalTranslationPrimary += mSidePadding; - } - applyPrimaryTranslation(); - applySecondaryTranslation(); - float clearAllSpacing = - recentsView.getPageSpacing() + recentsView.getClearAllExtraPageSpacing(); - clearAllSpacing = mIsRtl ? -clearAllSpacing : clearAllSpacing; - mScrollAlpha = Math.max((clearAllScroll + clearAllSpacing - scroll) / clearAllSpacing, 0); - updateAlpha(); - } - - private void updateAlpha() { - final float alpha = mScrollAlpha * mContentAlpha * mVisibilityAlpha * mDismissAlpha; - setAlpha(alpha); - setClickable(Math.min(alpha, 1) == 1); - } - - public void setFullscreenTranslationPrimary(float fullscreenTranslationPrimary) { - mFullscreenTranslationPrimary = fullscreenTranslationPrimary; - applyPrimaryTranslation(); - } - - /** - * Sets `mTaskAlignmentTranslationY` to the given `value`. In order to put the button at the - * middle in the secondary coordinate. - */ - public void setTaskAlignmentTranslationY(float value) { - mTaskAlignmentTranslationY = value; - applySecondaryTranslation(); - } - - public void setGridTranslationPrimary(float gridTranslationPrimary) { - mGridTranslationPrimary = gridTranslationPrimary; - applyPrimaryTranslation(); - } - - public void setGridScrollOffset(float gridScrollOffset) { - mGridScrollOffset = gridScrollOffset; - } - - public void setScrollOffsetPrimary(float scrollOffsetPrimary) { - mScrollOffsetPrimary = scrollOffsetPrimary; - } - - public float getScrollAdjustment(boolean fullscreenEnabled, boolean gridEnabled) { - float scrollAdjustment = 0; - if (fullscreenEnabled) { - scrollAdjustment += mFullscreenTranslationPrimary; - } - if (gridEnabled) { - scrollAdjustment += mGridTranslationPrimary + mGridScrollOffset; - } - scrollAdjustment += mScrollOffsetPrimary; - return scrollAdjustment; - } - - public float getOffsetAdjustment(boolean fullscreenEnabled, boolean gridEnabled) { - return getScrollAdjustment(fullscreenEnabled, gridEnabled); - } - - /** - * Adjust translation when this TaskView is about to be shown fullscreen. - * - * @param progress: 0 = no translation; 1 = translate according to TaskVIew translations. - */ - public void setFullscreenProgress(float progress) { - mFullscreenProgress = progress; - applyPrimaryTranslation(); - } - - /** - * Moves ClearAllButton between carousel and 2 row grid. - * - * @param gridProgress 0 = carousel; 1 = 2 row grid. - */ - public void setGridProgress(float gridProgress) { - mGridProgress = gridProgress; - applyPrimaryTranslation(); - } - - private void applyPrimaryTranslation() { - RecentsView recentsView = getRecentsView(); - if (recentsView == null) { - return; - } - - RecentsPagedOrientationHandler orientationHandler = - recentsView.getPagedOrientationHandler(); - orientationHandler.getPrimaryViewTranslate().set(this, - orientationHandler.getPrimaryValue(0f, mTaskAlignmentTranslationY) - + mNormalTranslationPrimary + getFullscreenTrans( - mFullscreenTranslationPrimary) + getGridTrans(mGridTranslationPrimary)); - } - - private void applySecondaryTranslation() { - RecentsView recentsView = getRecentsView(); - if (recentsView == null) { - return; - } - - RecentsPagedOrientationHandler orientationHandler = - recentsView.getPagedOrientationHandler(); - orientationHandler.getSecondaryViewTranslate().set(this, - orientationHandler.getSecondaryValue(0f, mTaskAlignmentTranslationY)); - } - - private float getFullscreenTrans(float endTranslation) { - return mFullscreenProgress > 0 ? endTranslation : 0; - } - - private float getGridTrans(float endTranslation) { - return mGridProgress > 0 ? endTranslation : 0; - } -} diff --git a/quickstep/src/com/android/quickstep/views/ClearAllButton.kt b/quickstep/src/com/android/quickstep/views/ClearAllButton.kt new file mode 100644 index 0000000000..ef62597738 --- /dev/null +++ b/quickstep/src/com/android/quickstep/views/ClearAllButton.kt @@ -0,0 +1,269 @@ +/* + * 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.views + +import android.content.Context +import android.graphics.Canvas +import android.graphics.Rect +import android.util.AttributeSet +import android.util.FloatProperty +import android.widget.Button +import com.android.launcher3.Flags.enableFocusOutline +import com.android.launcher3.R +import com.android.quickstep.util.BorderAnimator +import com.android.quickstep.util.BorderAnimator.Companion.createSimpleBorderAnimator +import kotlin.math.abs +import kotlin.math.min + +class ClearAllButton @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : + Button(context, attrs) { + + var scrollAlpha = 1f + set(value) { + field = value + updateAlpha() + } + + var contentAlpha = 1f + set(value) { + field = value + updateAlpha() + } + + var visibilityAlpha = 1f + set(value) { + field = value + updateAlpha() + } + + var dismissAlpha = 1f + set(value) { + field = value + updateAlpha() + } + + var fullscreenProgress = 1f + set(value) { + if (field == value) { + return + } + field = value + applyPrimaryTranslation() + } + + /** + * Moves ClearAllButton between carousel and 2 row grid. + * + * 0 = carousel; 1 = 2 row grid. + */ + var gridProgress = 1f + set(value) { + if (field == value) { + return + } + field = value + applyPrimaryTranslation() + } + + private var normalTranslationPrimary = 0f + var fullscreenTranslationPrimary = 0f + set(value) { + if (field == value) { + return + } + field = value + applyPrimaryTranslation() + } + + var gridTranslationPrimary = 0f + set(value) { + if (field == value) { + return + } + field = value + applyPrimaryTranslation() + } + + /** Used to put the button at the middle in the secondary coordinate. */ + var taskAlignmentTranslationY = 0f + set(value) { + if (field == value) { + return + } + field = value + applySecondaryTranslation() + } + + var gridScrollOffset = 0f + var scrollOffsetPrimary = 0f + + private var sidePadding = 0 + var borderEnabled = false + set(value) { + if (field == value) { + return + } + field = value + focusBorderAnimator?.setBorderVisibility(visible = field && isFocused, animated = true) + } + + private val focusBorderAnimator: BorderAnimator? = + if (enableFocusOutline()) + createSimpleBorderAnimator( + context.resources.getDimensionPixelSize(R.dimen.recents_clear_all_outline_radius), + context.resources.getDimensionPixelSize(R.dimen.keyboard_quick_switch_border_width), + this::getBorderBounds, + this, + context + .obtainStyledAttributes(attrs, R.styleable.ClearAllButton) + .getColor( + R.styleable.ClearAllButton_focusBorderColor, + BorderAnimator.DEFAULT_BORDER_COLOR, + ), + ) + else null + + private fun getBorderBounds(bounds: Rect) { + bounds.set(0, 0, width, height) + val outlinePadding = + context.resources.getDimensionPixelSize(R.dimen.recents_clear_all_outline_padding) + // Make the value negative to form a padding between button and outline + bounds.inset(-outlinePadding, -outlinePadding) + } + + public override fun onFocusChanged( + gainFocus: Boolean, + direction: Int, + previouslyFocusedRect: Rect?, + ) { + super.onFocusChanged(gainFocus, direction, previouslyFocusedRect) + if (borderEnabled) { + focusBorderAnimator?.setBorderVisibility(gainFocus, /* animated= */ true) + } + } + + override fun draw(canvas: Canvas) { + focusBorderAnimator?.drawBorder(canvas) + super.draw(canvas) + } + + override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { + super.onLayout(changed, left, top, right, bottom) + sidePadding = + recentsView?.let { it.pagedOrientationHandler?.getClearAllSidePadding(it, isLayoutRtl) } + ?: 0 + } + + private val recentsView: RecentsView<*, *>? + get() = parent as? RecentsView<*, *>? + + override fun hasOverlappingRendering() = false + + fun onRecentsViewScroll(scroll: Int, gridEnabled: Boolean) { + val recentsView = recentsView ?: return + + val orientationSize = + recentsView.pagedOrientationHandler.getPrimaryValue(width, height).toFloat() + if (orientationSize == 0f) { + return + } + + val clearAllScroll = recentsView.clearAllScroll + val adjustedScrollFromEdge = abs((scroll - clearAllScroll)).toFloat() + val shift = min(adjustedScrollFromEdge, orientationSize) + normalTranslationPrimary = if (isLayoutRtl) -shift else shift + if (!gridEnabled) { + normalTranslationPrimary += sidePadding.toFloat() + } + applyPrimaryTranslation() + applySecondaryTranslation() + var clearAllSpacing = recentsView.pageSpacing + recentsView.clearAllExtraPageSpacing + clearAllSpacing = if (isLayoutRtl) -clearAllSpacing else clearAllSpacing + scrollAlpha = + ((clearAllScroll + clearAllSpacing - scroll) / clearAllSpacing.toFloat()).coerceAtLeast( + 0f + ) + } + + private fun updateAlpha() { + val alpha = scrollAlpha * contentAlpha * visibilityAlpha * dismissAlpha + this.alpha = alpha + isClickable = alpha >= 1f + } + + fun getScrollAdjustment(fullscreenEnabled: Boolean, gridEnabled: Boolean): Float { + var scrollAdjustment = 0f + if (fullscreenEnabled) { + scrollAdjustment += fullscreenTranslationPrimary + } + if (gridEnabled) { + scrollAdjustment += gridTranslationPrimary + gridScrollOffset + } + scrollAdjustment += scrollOffsetPrimary + return scrollAdjustment + } + + fun getOffsetAdjustment(fullscreenEnabled: Boolean, gridEnabled: Boolean) = + getScrollAdjustment(fullscreenEnabled, gridEnabled) + + private fun applyPrimaryTranslation() { + val recentsView = recentsView ?: return + val orientationHandler = recentsView.pagedOrientationHandler + orientationHandler.primaryViewTranslate.set( + this, + (orientationHandler.getPrimaryValue(0f, taskAlignmentTranslationY) + + normalTranslationPrimary + + getFullscreenTrans(fullscreenTranslationPrimary) + + getGridTrans(gridTranslationPrimary)), + ) + } + + private fun applySecondaryTranslation() { + val recentsView = recentsView ?: return + val orientationHandler = recentsView.pagedOrientationHandler + orientationHandler.secondaryViewTranslate.set( + this, + orientationHandler.getSecondaryValue(0f, taskAlignmentTranslationY), + ) + } + + private fun getFullscreenTrans(endTranslation: Float) = + if (fullscreenProgress > 0) endTranslation else 0f + + private fun getGridTrans(endTranslation: Float) = if (gridProgress > 0) endTranslation else 0f + + companion object { + @JvmField + val VISIBILITY_ALPHA: FloatProperty = + object : FloatProperty("visibilityAlpha") { + override fun setValue(clearAllButton: ClearAllButton, value: Float) { + clearAllButton.visibilityAlpha = value + } + + override fun get(clearAllButton: ClearAllButton) = clearAllButton.visibilityAlpha + } + + @JvmField + val DISMISS_ALPHA: FloatProperty = + object : FloatProperty("dismissAlpha") { + override fun setValue(clearAllButton: ClearAllButton, value: Float) { + clearAllButton.dismissAlpha = value + } + + override fun get(clearAllButton: ClearAllButton) = clearAllButton.dismissAlpha + } + } +} From 93f530707bf80a3167b856c620e1c45e31cbf389 Mon Sep 17 00:00:00 2001 From: Pat Manning Date: Wed, 26 Feb 2025 12:52:16 +0000 Subject: [PATCH 126/153] Convert PortraitPagedViewHandler to Kotlin. Fix: 399332680 Test: Everything builds. Flag: EXEMPT. Simple conversion. Change-Id: Ib9fbaf14991716ed4135d0430945729d8448b4cd --- .../orientation/LandscapePagedViewHandler.kt | 67 +- .../orientation/PortraitPagedViewHandler.java | 872 ----------------- .../orientation/PortraitPagedViewHandler.kt | 903 ++++++++++++++++++ .../orientation/SeascapePagedViewHandler.kt | 39 +- 4 files changed, 954 insertions(+), 927 deletions(-) delete mode 100644 quickstep/src/com/android/quickstep/orientation/PortraitPagedViewHandler.java create mode 100644 quickstep/src/com/android/quickstep/orientation/PortraitPagedViewHandler.kt diff --git a/quickstep/src/com/android/quickstep/orientation/LandscapePagedViewHandler.kt b/quickstep/src/com/android/quickstep/orientation/LandscapePagedViewHandler.kt index 17f861d77c..ee9b3e8542 100644 --- a/quickstep/src/com/android/quickstep/orientation/LandscapePagedViewHandler.kt +++ b/quickstep/src/com/android/quickstep/orientation/LandscapePagedViewHandler.kt @@ -103,7 +103,7 @@ open class LandscapePagedViewHandler : RecentsPagedOrientationHandler { target: T, action: Int2DAction, primaryParam: Int, - secondaryParam: Int + secondaryParam: Int, ) = action.call(target, secondaryParam, primaryParam) override fun getPrimaryDirection(event: MotionEvent, pointerIndex: Int): Float = @@ -171,7 +171,7 @@ open class LandscapePagedViewHandler : RecentsPagedOrientationHandler { override fun getSplitTranslationDirectionFactor( stagePosition: Int, - deviceProfile: DeviceProfile + deviceProfile: DeviceProfile, ): Int = if (stagePosition == STAGE_POSITION_BOTTOM_OR_RIGHT) -1 else 1 override fun getTaskMenuX( @@ -179,7 +179,7 @@ open class LandscapePagedViewHandler : RecentsPagedOrientationHandler { thumbnailView: View, deviceProfile: DeviceProfile, taskInsetMargin: Float, - taskViewIcon: View + taskViewIcon: View, ): Float = thumbnailView.measuredWidth + x - taskInsetMargin override fun getTaskMenuY( @@ -188,7 +188,7 @@ open class LandscapePagedViewHandler : RecentsPagedOrientationHandler { stagePosition: Int, taskMenuView: View, taskInsetMargin: Float, - taskViewIcon: View + taskViewIcon: View, ): Float { val layoutParams = taskMenuView.layoutParams as BaseDragLayer.LayoutParams var taskMenuY = y + taskInsetMargin @@ -203,7 +203,7 @@ open class LandscapePagedViewHandler : RecentsPagedOrientationHandler { override fun getTaskMenuWidth( thumbnailView: View, deviceProfile: DeviceProfile, - @StagePosition stagePosition: Int + @StagePosition stagePosition: Int, ): Int = when { Flags.enableOverviewIconMenu() -> @@ -218,14 +218,14 @@ open class LandscapePagedViewHandler : RecentsPagedOrientationHandler { taskInsetMargin: Float, deviceProfile: DeviceProfile, taskMenuX: Float, - taskMenuY: Float + taskMenuY: Float, ): Int = (taskMenuX - taskInsetMargin).toInt() override fun setTaskOptionsMenuLayoutOrientation( deviceProfile: DeviceProfile, taskMenuLayout: LinearLayout, dividerSpacing: Int, - dividerDrawable: ShapeDrawable + dividerDrawable: ShapeDrawable, ) { taskMenuLayout.orientation = LinearLayout.VERTICAL dividerDrawable.intrinsicHeight = dividerSpacing @@ -235,7 +235,7 @@ open class LandscapePagedViewHandler : RecentsPagedOrientationHandler { override fun setLayoutParamsForTaskMenuOptionItem( lp: LinearLayout.LayoutParams, viewGroup: LinearLayout, - deviceProfile: DeviceProfile + deviceProfile: DeviceProfile, ) { // Phone fake landscape viewGroup.orientation = LinearLayout.HORIZONTAL @@ -250,7 +250,7 @@ open class LandscapePagedViewHandler : RecentsPagedOrientationHandler { deviceProfile: DeviceProfile, snapshotViewWidth: Int, snapshotViewHeight: Int, - banner: View + banner: View, ) { banner.pivotX = 0f banner.pivotY = 0f @@ -273,7 +273,7 @@ open class LandscapePagedViewHandler : RecentsPagedOrientationHandler { deviceProfile: DeviceProfile, thumbnailViews: Array, desiredTaskId: Int, - banner: View + banner: View, ): Pair { val snapshotParams = thumbnailViews[0].layoutParams as FrameLayout.LayoutParams val translationX = banner.height.toFloat() @@ -317,7 +317,7 @@ open class LandscapePagedViewHandler : RecentsPagedOrientationHandler { child: View, childStart: Int, pageCenter: Int, - layoutChild: Boolean + layoutChild: Boolean, ): ChildBounds { val childHeight = child.measuredHeight val childWidth = child.measuredWidth @@ -338,7 +338,7 @@ open class LandscapePagedViewHandler : RecentsPagedOrientationHandler { R.drawable.ic_split_horizontal, R.string.recent_task_option_split_screen, STAGE_POSITION_TOP_OR_LEFT, - STAGE_TYPE_MAIN + STAGE_TYPE_MAIN, ) ) @@ -347,7 +347,7 @@ open class LandscapePagedViewHandler : RecentsPagedOrientationHandler { placeholderInset: Int, dp: DeviceProfile, @StagePosition stagePosition: Int, - out: Rect + out: Rect, ) { // In fake land/seascape, the placeholder always needs to go to the "top" of the device, // which is the same bounds as 0 rotation. @@ -374,7 +374,7 @@ open class LandscapePagedViewHandler : RecentsPagedOrientationHandler { drawableWidth: Int, drawableHeight: Int, dp: DeviceProfile, - @StagePosition stagePosition: Int + @StagePosition stagePosition: Int, ) { val insetAdjustment = getPlaceholderSizeAdjustment(dp) / 2f out.x = (onScreenRectCenterX / fullscreenScaleX - 1.0f * drawableWidth / 2) @@ -393,7 +393,7 @@ open class LandscapePagedViewHandler : RecentsPagedOrientationHandler { out: View, dp: DeviceProfile, splitInstructionsHeight: Int, - splitInstructionsWidth: Int + splitInstructionsWidth: Int, ) { out.pivotX = 0f out.pivotY = splitInstructionsHeight.toFloat() @@ -421,7 +421,7 @@ open class LandscapePagedViewHandler : RecentsPagedOrientationHandler { dp: DeviceProfile, @StagePosition stagePosition: Int, out1: Rect, - out2: Rect + out2: Rect, ) { // In fake land/seascape, the window bounds are always top and bottom half val screenHeight = dp.heightPx @@ -434,7 +434,7 @@ open class LandscapePagedViewHandler : RecentsPagedOrientationHandler { dp: DeviceProfile, outRect: Rect, splitInfo: SplitBounds, - desiredStagePosition: Int + desiredStagePosition: Int, ) { val topLeftTaskPercent = splitInfo.leftTopTaskPercent val dividerBarPercent = splitInfo.dividerPercent @@ -448,7 +448,7 @@ open class LandscapePagedViewHandler : RecentsPagedOrientationHandler { /** * @param inSplitSelection Whether user currently has a task from this task group staged for - * split screen. Currently this state is not reachable in fake landscape. + * split screen. Currently this state is not reachable in fake landscape. */ override fun measureGroupedTaskViewThumbnailBounds( primarySnapshot: View, @@ -458,7 +458,7 @@ open class LandscapePagedViewHandler : RecentsPagedOrientationHandler { splitBoundsConfig: SplitBounds, dp: DeviceProfile, isRtl: Boolean, - inSplitSelection: Boolean + inSplitSelection: Boolean, ) { val primaryParams = primarySnapshot.layoutParams as FrameLayout.LayoutParams val secondaryParams = secondarySnapshot.layoutParams as FrameLayout.LayoutParams @@ -479,13 +479,13 @@ open class LandscapePagedViewHandler : RecentsPagedOrientationHandler { primarySnapshot.translationY = spaceAboveSnapshot.toFloat() primarySnapshot.measure( MeasureSpec.makeMeasureSpec(taskViewFirst.x, MeasureSpec.EXACTLY), - MeasureSpec.makeMeasureSpec(taskViewFirst.y, MeasureSpec.EXACTLY) + MeasureSpec.makeMeasureSpec(taskViewFirst.y, MeasureSpec.EXACTLY), ) val translationY = taskViewFirst.y + spaceAboveSnapshot + dividerBar secondarySnapshot.translationY = (translationY - spaceAboveSnapshot).toFloat() secondarySnapshot.measure( MeasureSpec.makeMeasureSpec(taskViewSecond.x, MeasureSpec.EXACTLY), - MeasureSpec.makeMeasureSpec(taskViewSecond.y, MeasureSpec.EXACTLY) + MeasureSpec.makeMeasureSpec(taskViewSecond.y, MeasureSpec.EXACTLY), ) } @@ -493,7 +493,7 @@ open class LandscapePagedViewHandler : RecentsPagedOrientationHandler { dp: DeviceProfile, splitBoundsConfig: SplitBounds, parentWidth: Int, - parentHeight: Int + parentHeight: Int, ): Pair { val spaceAboveSnapshot = dp.overviewTaskThumbnailTopMarginPx val totalThumbnailHeight = parentHeight - spaceAboveSnapshot @@ -511,7 +511,7 @@ open class LandscapePagedViewHandler : RecentsPagedOrientationHandler { taskIconMargin: Int, taskIconHeight: Int, thumbnailTopMargin: Int, - isRtl: Boolean + isRtl: Boolean, ) { iconParams.gravity = if (isRtl) { @@ -527,7 +527,7 @@ open class LandscapePagedViewHandler : RecentsPagedOrientationHandler { override fun setIconAppChipChildrenParams( iconParams: FrameLayout.LayoutParams, - chipChildMarginStart: Int + chipChildMarginStart: Int, ) { iconParams.gravity = Gravity.START or Gravity.CENTER_VERTICAL iconParams.marginStart = chipChildMarginStart @@ -538,7 +538,7 @@ open class LandscapePagedViewHandler : RecentsPagedOrientationHandler { iconAppChipView: IconAppChipView, iconMenuParams: FrameLayout.LayoutParams, iconMenuMargin: Int, - thumbnailTopMargin: Int + thumbnailTopMargin: Int, ) { val isRtl = iconAppChipView.layoutDirection == View.LAYOUT_DIRECTION_RTL @@ -564,7 +564,7 @@ open class LandscapePagedViewHandler : RecentsPagedOrientationHandler { /** * @param inSplitSelection Whether user currently has a task from this task group staged for - * split screen. Currently this state is not reachable in fake landscape. + * split screen. Currently this state is not reachable in fake landscape. */ override fun setSplitIconParams( primaryIconView: View, @@ -606,20 +606,20 @@ open class LandscapePagedViewHandler : RecentsPagedOrientationHandler { override fun getSplitSelectTaskOffset( primary: FloatProperty, secondary: FloatProperty, - deviceProfile: DeviceProfile + deviceProfile: DeviceProfile, ): Pair, FloatProperty> = Pair(primary, secondary) override fun getFloatingTaskOffscreenTranslationTarget( floatingTask: View, onScreenRect: RectF, @StagePosition stagePosition: Int, - dp: DeviceProfile + dp: DeviceProfile, ): Float = floatingTask.translationY - onScreenRect.height() override fun setFloatingTaskPrimaryTranslation( floatingTask: View, translation: Float, - dp: DeviceProfile + dp: DeviceProfile, ) { floatingTask.translationY = translation } @@ -660,12 +660,11 @@ open class LandscapePagedViewHandler : RecentsPagedOrientationHandler { } else { if (oneIconHiddenDueToSmallWidth) { // Center both icons - val centerY = primarySnapshotHeight + overviewTaskMarginPx + + val centerY = + primarySnapshotHeight + + overviewTaskMarginPx + ((taskIconHeight + dividerSize) / 2) - SplitIconPositions( - topLeftY = centerY, - bottomRightY = centerY, - ) + SplitIconPositions(topLeftY = centerY, bottomRightY = centerY) } else { val topLeftY = primarySnapshotHeight + overviewTaskMarginPx SplitIconPositions( diff --git a/quickstep/src/com/android/quickstep/orientation/PortraitPagedViewHandler.java b/quickstep/src/com/android/quickstep/orientation/PortraitPagedViewHandler.java deleted file mode 100644 index c4e82d6a02..0000000000 --- a/quickstep/src/com/android/quickstep/orientation/PortraitPagedViewHandler.java +++ /dev/null @@ -1,872 +0,0 @@ -/* - * Copyright (C) 2024 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.orientation; - -import static android.view.Gravity.BOTTOM; -import static android.view.Gravity.CENTER_HORIZONTAL; -import static android.view.Gravity.END; -import static android.view.Gravity.START; -import static android.view.Gravity.TOP; -import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; -import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT; - -import static com.android.launcher3.Flags.enableOverviewIconMenu; -import static com.android.launcher3.LauncherAnimUtils.VIEW_TRANSLATE_X; -import static com.android.launcher3.LauncherAnimUtils.VIEW_TRANSLATE_Y; -import static com.android.launcher3.touch.SingleAxisSwipeDetector.VERTICAL; -import static com.android.launcher3.util.SplitConfigurationOptions.STAGE_POSITION_BOTTOM_OR_RIGHT; -import static com.android.launcher3.util.SplitConfigurationOptions.STAGE_POSITION_TOP_OR_LEFT; -import static com.android.launcher3.util.SplitConfigurationOptions.STAGE_TYPE_MAIN; - -import android.graphics.Matrix; -import android.graphics.Point; -import android.graphics.PointF; -import android.graphics.Rect; -import android.graphics.RectF; -import android.graphics.drawable.ShapeDrawable; -import android.util.FloatProperty; -import android.util.Pair; -import android.view.Gravity; -import android.view.Surface; -import android.view.View; -import android.widget.FrameLayout; -import android.widget.LinearLayout; - -import androidx.annotation.NonNull; - -import com.android.launcher3.DeviceProfile; -import com.android.launcher3.R; -import com.android.launcher3.Utilities; -import com.android.launcher3.logger.LauncherAtom; -import com.android.launcher3.touch.DefaultPagedViewHandler; -import com.android.launcher3.touch.SingleAxisSwipeDetector; -import com.android.launcher3.util.SplitConfigurationOptions; -import com.android.launcher3.util.SplitConfigurationOptions.SplitBounds; -import com.android.launcher3.util.SplitConfigurationOptions.SplitPositionOption; -import com.android.launcher3.util.SplitConfigurationOptions.StagePosition; -import com.android.quickstep.views.IconAppChipView; - -import java.util.ArrayList; -import java.util.List; - -public class PortraitPagedViewHandler extends DefaultPagedViewHandler implements - RecentsPagedOrientationHandler { - - private final Matrix mTmpMatrix = new Matrix(); - private final RectF mTmpRectF = new RectF(); - - @Override - public T getPrimaryValue(T x, T y) { - return x; - } - - @Override - public T getSecondaryValue(T x, T y) { - return y; - } - - @Override - public boolean isLayoutNaturalToLauncher() { - return true; - } - - @Override - public void adjustFloatingIconStartVelocity(PointF velocity) { - //no-op - } - - @Override - public void fixBoundsForHomeAnimStartRect(RectF outStartRect, DeviceProfile deviceProfile) { - if (outStartRect.left > deviceProfile.widthPx) { - outStartRect.offsetTo(0, outStartRect.top); - } else if (outStartRect.left < -deviceProfile.widthPx) { - outStartRect.offsetTo(0, outStartRect.top); - } - } - - @Override - public void setSecondary(T target, Float2DAction action, float param) { - action.call(target, 0, param); - } - - @Override - public void set(T target, Int2DAction action, int primaryParam, - int secondaryParam) { - action.call(target, primaryParam, secondaryParam); - } - - @Override - public int getPrimarySize(View view) { - return view.getWidth(); - } - - @Override - public float getPrimarySize(RectF rect) { - return rect.width(); - } - - @Override - public float getStart(RectF rect) { - return rect.left; - } - - @Override - public float getEnd(RectF rect) { - return rect.right; - } - - @Override - public void rotateInsets(@NonNull Rect insets, @NonNull Rect outInsets) { - outInsets.set(insets); - } - - @Override - public int getClearAllSidePadding(View view, boolean isRtl) { - return (isRtl ? view.getPaddingRight() : - view.getPaddingLeft()) / 2; - } - - @Override - public int getSecondaryDimension(View view) { - return view.getHeight(); - } - - @Override - public FloatProperty getPrimaryViewTranslate() { - return VIEW_TRANSLATE_X; - } - - @Override - public FloatProperty getSecondaryViewTranslate() { - return VIEW_TRANSLATE_Y; - } - - @Override - public float getDegreesRotated() { - return 0; - } - - @Override - public int getRotation() { - return Surface.ROTATION_0; - } - - @Override - public void setPrimaryScale(View view, float scale) { - view.setScaleX(scale); - } - - @Override - public void setSecondaryScale(View view, float scale) { - view.setScaleY(scale); - } - - public int getSecondaryTranslationDirectionFactor() { - return -1; - } - - @Override - public int getSplitTranslationDirectionFactor(int stagePosition, DeviceProfile deviceProfile) { - if (deviceProfile.isLeftRightSplit && stagePosition == STAGE_POSITION_BOTTOM_OR_RIGHT) { - return -1; - } else { - return 1; - } - } - - @Override - public float getTaskMenuX(float x, View thumbnailView, - DeviceProfile deviceProfile, float taskInsetMargin, View taskViewIcon) { - if (deviceProfile.isLandscape) { - return x + taskInsetMargin - + (thumbnailView.getMeasuredWidth() - thumbnailView.getMeasuredHeight()) / 2f; - } else { - return x + taskInsetMargin; - } - } - - @Override - public float getTaskMenuY(float y, View thumbnailView, int stagePosition, - View taskMenuView, float taskInsetMargin, View taskViewIcon) { - return y + taskInsetMargin; - } - - @Override - public int getTaskMenuWidth(View thumbnailView, DeviceProfile deviceProfile, - @StagePosition int stagePosition) { - if (enableOverviewIconMenu()) { - return thumbnailView.getResources().getDimensionPixelSize( - R.dimen.task_thumbnail_icon_menu_expanded_width); - } - int padding = thumbnailView.getResources() - .getDimensionPixelSize(R.dimen.task_menu_edge_padding); - return (deviceProfile.isLandscape && !deviceProfile.isTablet - ? thumbnailView.getMeasuredHeight() - : thumbnailView.getMeasuredWidth()) - (2 * padding); - } - - @Override - public int getTaskMenuHeight(float taskInsetMargin, DeviceProfile deviceProfile, - float taskMenuX, float taskMenuY) { - return (int) (deviceProfile.heightPx - deviceProfile.getInsets().top - taskMenuY - - deviceProfile.getOverviewActionsClaimedSpaceBelow()); - } - - @Override - public void setTaskOptionsMenuLayoutOrientation(DeviceProfile deviceProfile, - LinearLayout taskMenuLayout, int dividerSpacing, - ShapeDrawable dividerDrawable) { - taskMenuLayout.setOrientation(LinearLayout.VERTICAL); - dividerDrawable.setIntrinsicHeight(dividerSpacing); - taskMenuLayout.setDividerDrawable(dividerDrawable); - } - - @Override - public void setLayoutParamsForTaskMenuOptionItem(LinearLayout.LayoutParams lp, - LinearLayout viewGroup, DeviceProfile deviceProfile) { - viewGroup.setOrientation(LinearLayout.HORIZONTAL); - lp.width = LinearLayout.LayoutParams.MATCH_PARENT; - lp.height = WRAP_CONTENT; - } - - @Override - public void updateDwbBannerLayout(int taskViewWidth, int taskViewHeight, - boolean isGroupedTaskView, @NonNull DeviceProfile deviceProfile, - int snapshotViewWidth, int snapshotViewHeight, @NonNull View banner) { - FrameLayout.LayoutParams bannerParams = (FrameLayout.LayoutParams) banner.getLayoutParams(); - banner.setPivotX(0); - banner.setPivotY(0); - banner.setRotation(getDegreesRotated()); - if (isGroupedTaskView) { - bannerParams.gravity = - BOTTOM | (deviceProfile.isLeftRightSplit ? START : CENTER_HORIZONTAL); - bannerParams.width = snapshotViewWidth; - } else { - bannerParams.width = MATCH_PARENT; - bannerParams.gravity = BOTTOM | CENTER_HORIZONTAL; - } - banner.setLayoutParams(bannerParams); - } - - @NonNull - @Override - public Pair getDwbBannerTranslations(int taskViewWidth, - int taskViewHeight, SplitBounds splitBounds, @NonNull DeviceProfile deviceProfile, - @NonNull View[] thumbnailViews, int desiredTaskId, @NonNull View banner) { - float translationX = 0; - float translationY = 0; - if (splitBounds != null) { - if (deviceProfile.isLeftRightSplit) { - if (desiredTaskId == splitBounds.rightBottomTaskId) { - float leftTopTaskPercent = splitBounds.getLeftTopTaskPercent(); - float dividerThicknessPercent = splitBounds.getDividerPercent(); - translationX = ((taskViewWidth * leftTopTaskPercent) - + (taskViewWidth * dividerThicknessPercent)); - } - } else { - if (desiredTaskId == splitBounds.leftTopTaskId) { - FrameLayout.LayoutParams snapshotParams = - (FrameLayout.LayoutParams) thumbnailViews[0] - .getLayoutParams(); - float bottomRightTaskPlusDividerPercent = - splitBounds.getRightBottomTaskPercent() - + splitBounds.getDividerPercent(); - translationY = -((taskViewHeight - snapshotParams.topMargin) - * bottomRightTaskPlusDividerPercent); - } - } - } - return new Pair<>(translationX, translationY); - } - - /* ---------- The following are only used by TaskViewTouchHandler. ---------- */ - - @Override - public SingleAxisSwipeDetector.Direction getUpDownSwipeDirection() { - return VERTICAL; - } - - @Override - public int getUpDirection(boolean isRtl) { - // Ignore rtl since it only affects X value displacement, Y displacement doesn't change - return SingleAxisSwipeDetector.DIRECTION_POSITIVE; - } - - @Override - public int getDownDirection(boolean isRtl) { - // Ignore rtl since it only affects X value displacement, Y displacement doesn't change - return SingleAxisSwipeDetector.DIRECTION_NEGATIVE; - } - - @Override - public boolean isGoingUp(float displacement, boolean isRtl) { - // Ignore rtl since it only affects X value displacement, Y displacement doesn't change - return displacement < 0; - } - - @Override - public int getTaskDragDisplacementFactor(boolean isRtl) { - // Ignore rtl since it only affects X value displacement, Y displacement doesn't change - return 1; - } - - /* -------------------- */ - @Override - public int getDistanceToBottomOfRect(DeviceProfile dp, Rect rect) { - return dp.heightPx - rect.bottom; - } - - @Override - public List getSplitPositionOptions(DeviceProfile dp) { - if (dp.isTablet) { - return Utilities.getSplitPositionOptions(dp); - } - - List options = new ArrayList<>(); - if (dp.isSeascape()) { - options.add(new SplitPositionOption( - R.drawable.ic_split_horizontal, R.string.recent_task_option_split_screen, - STAGE_POSITION_BOTTOM_OR_RIGHT, STAGE_TYPE_MAIN)); - } else if (dp.isLeftRightSplit) { - options.add(new SplitPositionOption( - R.drawable.ic_split_horizontal, R.string.recent_task_option_split_screen, - STAGE_POSITION_TOP_OR_LEFT, STAGE_TYPE_MAIN)); - } else { - // Only add top option - options.add(new SplitPositionOption( - R.drawable.ic_split_vertical, R.string.recent_task_option_split_screen, - STAGE_POSITION_TOP_OR_LEFT, STAGE_TYPE_MAIN)); - } - return options; - } - - @Override - public void getInitialSplitPlaceholderBounds(int placeholderHeight, int placeholderInset, - DeviceProfile dp, @StagePosition int stagePosition, Rect out) { - int screenWidth = dp.widthPx; - int screenHeight = dp.heightPx; - boolean pinToRight = stagePosition == STAGE_POSITION_BOTTOM_OR_RIGHT; - int insetSizeAdjustment = getPlaceholderSizeAdjustment(dp, pinToRight); - - out.set(0, 0, screenWidth, placeholderHeight + insetSizeAdjustment); - if (!dp.isLeftRightSplit) { - // portrait, phone or tablet - spans width of screen, nothing else to do - out.inset(placeholderInset, 0); - - // Adjust the top to account for content off screen. This will help to animate the view - // in with rounded corners. - int totalHeight = (int) (1.0f * screenHeight / 2 * (screenWidth - 2 * placeholderInset) - / screenWidth); - out.top -= (totalHeight - placeholderHeight); - return; - } - - // Now we rotate the portrait rect depending on what side we want pinned - - float postRotateScale = (float) screenHeight / screenWidth; - mTmpMatrix.reset(); - mTmpMatrix.postRotate(pinToRight ? 90 : 270); - mTmpMatrix.postTranslate(pinToRight ? screenWidth : 0, pinToRight ? 0 : screenWidth); - // The placeholder height stays constant after rotation, so we don't change width scale - mTmpMatrix.postScale(1, postRotateScale); - - mTmpRectF.set(out); - mTmpMatrix.mapRect(mTmpRectF); - mTmpRectF.inset(0, placeholderInset); - mTmpRectF.roundOut(out); - - // Adjust the top to account for content off screen. This will help to animate the view in - // with rounded corners. - int totalWidth = (int) (1.0f * screenWidth / 2 * (screenHeight - 2 * placeholderInset) - / screenHeight); - int width = out.width(); - if (pinToRight) { - out.right += totalWidth - width; - } else { - out.left -= totalWidth - width; - } - } - - @Override - public void updateSplitIconParams(View out, float onScreenRectCenterX, - float onScreenRectCenterY, float fullscreenScaleX, float fullscreenScaleY, - int drawableWidth, int drawableHeight, DeviceProfile dp, - @StagePosition int stagePosition) { - boolean pinToRight = stagePosition == STAGE_POSITION_BOTTOM_OR_RIGHT; - float insetAdjustment = getPlaceholderSizeAdjustment(dp, pinToRight) / 2f; - if (!dp.isLeftRightSplit) { - out.setX(onScreenRectCenterX / fullscreenScaleX - - 1.0f * drawableWidth / 2); - out.setY((onScreenRectCenterY + insetAdjustment) / fullscreenScaleY - - 1.0f * drawableHeight / 2); - } else { - if (pinToRight) { - out.setX((onScreenRectCenterX - insetAdjustment) / fullscreenScaleX - - 1.0f * drawableWidth / 2); - } else { - out.setX((onScreenRectCenterX + insetAdjustment) / fullscreenScaleX - - 1.0f * drawableWidth / 2); - } - out.setY(onScreenRectCenterY / fullscreenScaleY - - 1.0f * drawableHeight / 2); - } - } - - /** - * The split placeholder comes with a default inset to buffer the icon from the top of the - * screen. But if the device already has a large inset (from cutouts etc), use that instead. - */ - private int getPlaceholderSizeAdjustment(DeviceProfile dp, boolean pinToRight) { - int insetThickness; - if (!dp.isLandscape) { - insetThickness = dp.getInsets().top; - } else { - insetThickness = pinToRight ? dp.getInsets().right : dp.getInsets().left; - } - return Math.max(insetThickness - dp.splitPlaceholderInset, 0); - } - - @Override - public void setSplitInstructionsParams(View out, DeviceProfile dp, int splitInstructionsHeight, - int splitInstructionsWidth) { - out.setPivotX(0); - out.setPivotY(splitInstructionsHeight); - out.setRotation(getDegreesRotated()); - int distanceToEdge; - if (dp.isPhone) { - if (dp.isLandscape) { - distanceToEdge = out.getResources().getDimensionPixelSize( - R.dimen.split_instructions_bottom_margin_phone_landscape); - } else { - distanceToEdge = out.getResources().getDimensionPixelSize( - R.dimen.split_instructions_bottom_margin_phone_portrait); - } - } else { - distanceToEdge = dp.getOverviewActionsClaimedSpaceBelow(); - } - - // Center the view in case of unbalanced insets on left or right of screen - int insetCorrectionX = (dp.getInsets().right - dp.getInsets().left) / 2; - // Adjust for any insets on the bottom edge - int insetCorrectionY = dp.getInsets().bottom; - out.setTranslationX(insetCorrectionX); - out.setTranslationY(-distanceToEdge + insetCorrectionY); - FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) out.getLayoutParams(); - lp.gravity = CENTER_HORIZONTAL | BOTTOM; - out.setLayoutParams(lp); - } - - @Override - public void getFinalSplitPlaceholderBounds(int splitDividerSize, DeviceProfile dp, - @StagePosition int stagePosition, Rect out1, Rect out2) { - int screenHeight = dp.heightPx; - int screenWidth = dp.widthPx; - out1.set(0, 0, screenWidth, screenHeight / 2 - splitDividerSize); - out2.set(0, screenHeight / 2 + splitDividerSize, screenWidth, screenHeight); - if (!dp.isLeftRightSplit) { - // Portrait - the window bounds are always top and bottom half - return; - } - - // Now we rotate the portrait rect depending on what side we want pinned - boolean pinToRight = stagePosition == STAGE_POSITION_BOTTOM_OR_RIGHT; - float postRotateScale = (float) screenHeight / screenWidth; - - mTmpMatrix.reset(); - mTmpMatrix.postRotate(pinToRight ? 90 : 270); - mTmpMatrix.postTranslate(pinToRight ? screenHeight : 0, pinToRight ? 0 : screenWidth); - mTmpMatrix.postScale(1 / postRotateScale, postRotateScale); - - mTmpRectF.set(out1); - mTmpMatrix.mapRect(mTmpRectF); - mTmpRectF.roundOut(out1); - - mTmpRectF.set(out2); - mTmpMatrix.mapRect(mTmpRectF); - mTmpRectF.roundOut(out2); - } - - @Override - public void setSplitTaskSwipeRect(DeviceProfile dp, Rect outRect, - SplitBounds splitInfo, int desiredStagePosition) { - float topLeftTaskPercent = splitInfo.getLeftTopTaskPercent(); - float dividerBarPercent = splitInfo.getDividerPercent(); - - int taskbarHeight = dp.isTransientTaskbar ? 0 : dp.taskbarHeight; - float scale = (float) outRect.height() / (dp.availableHeightPx - taskbarHeight); - float topTaskHeight = dp.availableHeightPx * topLeftTaskPercent; - float scaledTopTaskHeight = topTaskHeight * scale; - float dividerHeight = dp.availableHeightPx * dividerBarPercent; - float scaledDividerHeight = dividerHeight * scale; - - if (desiredStagePosition == SplitConfigurationOptions.STAGE_POSITION_TOP_OR_LEFT) { - if (dp.isLeftRightSplit) { - outRect.right = outRect.left + Math.round(outRect.width() * topLeftTaskPercent); - } else { - outRect.bottom = Math.round(outRect.top + scaledTopTaskHeight); - } - } else { - if (dp.isLeftRightSplit) { - outRect.left += Math.round(outRect.width() - * (topLeftTaskPercent + dividerBarPercent)); - } else { - outRect.top += Math.round(scaledTopTaskHeight + scaledDividerHeight); - } - } - } - - /** - * @param inSplitSelection Whether user currently has a task from this task group staged for - * split screen. If true, we have custom translations/scaling in place - * for the remaining snapshot, so we'll skip setting translation/scale - * here. - */ - @Override - public void measureGroupedTaskViewThumbnailBounds(View primarySnapshot, View secondarySnapshot, - int parentWidth, int parentHeight, SplitBounds splitBoundsConfig, - DeviceProfile dp, boolean isRtl, boolean inSplitSelection) { - int spaceAboveSnapshot = dp.overviewTaskThumbnailTopMarginPx; - - FrameLayout.LayoutParams primaryParams = - (FrameLayout.LayoutParams) primarySnapshot.getLayoutParams(); - FrameLayout.LayoutParams secondaryParams = - (FrameLayout.LayoutParams) secondarySnapshot.getLayoutParams(); - - // Reset margins that aren't used in this method, but are used in other - // `RecentsPagedOrientationHandler` variants. - secondaryParams.topMargin = 0; - primaryParams.topMargin = spaceAboveSnapshot; - - int totalThumbnailHeight = parentHeight - spaceAboveSnapshot; - float dividerScale = splitBoundsConfig.getDividerPercent(); - Pair taskViewSizes = - getGroupedTaskViewSizes(dp, splitBoundsConfig, parentWidth, parentHeight); - if (!inSplitSelection) { - // Reset translations that aren't used in this method, but are used in other - // `RecentsPagedOrientationHandler` variants. - primarySnapshot.setTranslationY(0); - - if (dp.isLeftRightSplit) { - int scaledDividerBar = Math.round(parentWidth * dividerScale); - if (isRtl) { - int translationX = taskViewSizes.second.x + scaledDividerBar; - primarySnapshot.setTranslationX(-translationX); - secondarySnapshot.setTranslationX(0); - } else { - int translationX = taskViewSizes.first.x + scaledDividerBar; - secondarySnapshot.setTranslationX(translationX); - primarySnapshot.setTranslationX(0); - } - secondarySnapshot.setTranslationY(spaceAboveSnapshot); - } else { - float finalDividerHeight = Math.round(totalThumbnailHeight * dividerScale); - float translationY = - taskViewSizes.first.y + spaceAboveSnapshot + finalDividerHeight; - secondarySnapshot.setTranslationY(translationY); - - // Reset unused translations. - secondarySnapshot.setTranslationX(0); - primarySnapshot.setTranslationX(0); - } - } - - primarySnapshot.measure( - View.MeasureSpec.makeMeasureSpec(taskViewSizes.first.x, View.MeasureSpec.EXACTLY), - View.MeasureSpec.makeMeasureSpec(taskViewSizes.first.y, View.MeasureSpec.EXACTLY)); - secondarySnapshot.measure( - View.MeasureSpec.makeMeasureSpec(taskViewSizes.second.x, View.MeasureSpec.EXACTLY), - View.MeasureSpec.makeMeasureSpec(taskViewSizes.second.y, - View.MeasureSpec.EXACTLY)); - } - - @Override - public Pair getGroupedTaskViewSizes( - DeviceProfile dp, - SplitBounds splitBoundsConfig, - int parentWidth, - int parentHeight) { - int spaceAboveSnapshot = dp.overviewTaskThumbnailTopMarginPx; - int totalThumbnailHeight = parentHeight - spaceAboveSnapshot; - float dividerScale = splitBoundsConfig.getDividerPercent(); - float taskPercent = splitBoundsConfig.getLeftTopTaskPercent(); - - Point firstTaskViewSize = new Point(); - Point secondTaskViewSize = new Point(); - - if (dp.isLeftRightSplit) { - int scaledDividerBar = Math.round(parentWidth * dividerScale); - firstTaskViewSize.x = Math.round(parentWidth * taskPercent); - firstTaskViewSize.y = totalThumbnailHeight; - - secondTaskViewSize.x = parentWidth - firstTaskViewSize.x - scaledDividerBar; - secondTaskViewSize.y = totalThumbnailHeight; - } else { - int taskbarHeight = dp.isTransientTaskbar ? 0 : dp.taskbarHeight; - float scale = (float) totalThumbnailHeight / (dp.availableHeightPx - taskbarHeight); - float topTaskHeight = dp.availableHeightPx * taskPercent; - float finalDividerHeight = Math.round(totalThumbnailHeight * dividerScale); - float scaledTopTaskHeight = topTaskHeight * scale; - firstTaskViewSize.x = parentWidth; - firstTaskViewSize.y = Math.round(scaledTopTaskHeight); - - secondTaskViewSize.x = parentWidth; - secondTaskViewSize.y = Math.round(totalThumbnailHeight - firstTaskViewSize.y - - finalDividerHeight); - } - - return new Pair<>(firstTaskViewSize, secondTaskViewSize); - } - - @Override - public void setTaskIconParams(FrameLayout.LayoutParams iconParams, int taskIconMargin, - int taskIconHeight, int thumbnailTopMargin, boolean isRtl) { - iconParams.gravity = TOP | CENTER_HORIZONTAL; - // Reset margins, since they may have been set on rotation - iconParams.leftMargin = iconParams.rightMargin = 0; - iconParams.topMargin = iconParams.bottomMargin = 0; - } - - @Override - public void setIconAppChipChildrenParams(FrameLayout.LayoutParams iconParams, - int chipChildMarginStart) { - iconParams.setMarginStart(chipChildMarginStart); - iconParams.gravity = Gravity.START | Gravity.CENTER_VERTICAL; - iconParams.topMargin = 0; - } - - @Override - public void setIconAppChipMenuParams(IconAppChipView iconAppChipView, - FrameLayout.LayoutParams iconMenuParams, int iconMenuMargin, int thumbnailTopMargin) { - iconMenuParams.gravity = TOP | START; - iconMenuParams.setMarginStart(iconMenuMargin); - iconMenuParams.topMargin = thumbnailTopMargin; - iconMenuParams.bottomMargin = 0; - iconMenuParams.setMarginEnd(0); - - iconAppChipView.setPivotX(0); - iconAppChipView.setPivotY(0); - iconAppChipView.setSplitTranslationY(0); - iconAppChipView.setRotation(getDegreesRotated()); - } - - /** - * @param inSplitSelection Whether user currently has a task from this task group staged for - * split screen. If true, we have custom translations in place for the - * remaining icon, so we'll skip setting translations here. - */ - @Override - public void setSplitIconParams(View primaryIconView, View secondaryIconView, - int taskIconHeight, int primarySnapshotWidth, int primarySnapshotHeight, - int groupedTaskViewHeight, int groupedTaskViewWidth, boolean isRtl, - DeviceProfile deviceProfile, SplitBounds splitConfig, boolean inSplitSelection, - boolean oneIconHiddenDueToSmallWidth) { - FrameLayout.LayoutParams primaryIconParams = - (FrameLayout.LayoutParams) primaryIconView.getLayoutParams(); - FrameLayout.LayoutParams secondaryIconParams = enableOverviewIconMenu() - ? (FrameLayout.LayoutParams) secondaryIconView.getLayoutParams() - : new FrameLayout.LayoutParams(primaryIconParams); - - if (enableOverviewIconMenu()) { - IconAppChipView primaryAppChipView = (IconAppChipView) primaryIconView; - IconAppChipView secondaryAppChipView = (IconAppChipView) secondaryIconView; - primaryIconParams.gravity = TOP | START; - secondaryIconParams.gravity = TOP | START; - secondaryIconParams.topMargin = primaryIconParams.topMargin; - secondaryIconParams.setMarginStart(primaryIconParams.getMarginStart()); - if (!inSplitSelection) { - if (deviceProfile.isLeftRightSplit) { - if (isRtl) { - int secondarySnapshotWidth = groupedTaskViewWidth - primarySnapshotWidth; - primaryAppChipView.setSplitTranslationX(-secondarySnapshotWidth); - } else { - secondaryAppChipView.setSplitTranslationX(primarySnapshotWidth); - } - } else { - primaryAppChipView.setSplitTranslationX(0); - secondaryAppChipView.setSplitTranslationX(0); - int dividerThickness = Math.min(splitConfig.visualDividerBounds.width(), - splitConfig.visualDividerBounds.height()); - secondaryAppChipView.setSplitTranslationY( - primarySnapshotHeight + (deviceProfile.isTablet ? 0 - : dividerThickness)); - } - } - } else if (deviceProfile.isLeftRightSplit) { - // We calculate the "midpoint" of the thumbnail area, and place the icons there. - // This is the place where the thumbnail area splits by default, in a near-50/50 split. - // It is usually not exactly 50/50, due to insets/screen cutouts. - int fullscreenInsetThickness = deviceProfile.isSeascape() - ? deviceProfile.getInsets().right - : deviceProfile.getInsets().left; - int fullscreenMidpointFromBottom = ((deviceProfile.widthPx - - fullscreenInsetThickness) / 2); - float midpointFromEndPct = (float) fullscreenMidpointFromBottom - / deviceProfile.widthPx; - float insetPct = (float) fullscreenInsetThickness / deviceProfile.widthPx; - int spaceAboveSnapshots = 0; - int overviewThumbnailAreaThickness = groupedTaskViewWidth - spaceAboveSnapshots; - int bottomToMidpointOffset = (int) (overviewThumbnailAreaThickness - * midpointFromEndPct); - int insetOffset = (int) (overviewThumbnailAreaThickness * insetPct); - - if (deviceProfile.isSeascape()) { - primaryIconParams.gravity = TOP | (isRtl ? END : START); - secondaryIconParams.gravity = TOP | (isRtl ? END : START); - if (!inSplitSelection) { - if (splitConfig.initiatedFromSeascape) { - if (oneIconHiddenDueToSmallWidth) { - // Center both icons - float centerX = bottomToMidpointOffset - (taskIconHeight / 2f); - primaryIconView.setTranslationX(centerX); - secondaryIconView.setTranslationX(centerX); - } else { - // the task on the right (secondary) is slightly larger - primaryIconView.setTranslationX( - bottomToMidpointOffset - taskIconHeight); - secondaryIconView.setTranslationX(bottomToMidpointOffset); - } - } else { - if (oneIconHiddenDueToSmallWidth) { - // Center both icons - float centerX = - bottomToMidpointOffset + insetOffset - (taskIconHeight / 2f); - primaryIconView.setTranslationX(centerX); - secondaryIconView.setTranslationX(centerX); - } else { - // the task on the left (primary) is slightly larger - primaryIconView.setTranslationX(bottomToMidpointOffset + insetOffset - - taskIconHeight); - secondaryIconView.setTranslationX(bottomToMidpointOffset + insetOffset); - } - } - } - } else { - primaryIconParams.gravity = TOP | (isRtl ? START : END); - secondaryIconParams.gravity = TOP | (isRtl ? START : END); - if (!inSplitSelection) { - if (!splitConfig.initiatedFromSeascape) { - if (oneIconHiddenDueToSmallWidth) { - // Center both icons - float centerX = -bottomToMidpointOffset + (taskIconHeight / 2f); - primaryIconView.setTranslationX(centerX); - secondaryIconView.setTranslationX(centerX); - } else { - // the task on the left (primary) is slightly larger - primaryIconView.setTranslationX(-bottomToMidpointOffset); - secondaryIconView.setTranslationX( - -bottomToMidpointOffset + taskIconHeight); - } - } else { - if (oneIconHiddenDueToSmallWidth) { - // Center both icons - float centerX = - -bottomToMidpointOffset - insetOffset + (taskIconHeight / 2f); - primaryIconView.setTranslationX(centerX); - secondaryIconView.setTranslationX(centerX); - } else { - // the task on the right (secondary) is slightly larger - primaryIconView.setTranslationX(-bottomToMidpointOffset - insetOffset); - secondaryIconView.setTranslationX(-bottomToMidpointOffset - insetOffset - + taskIconHeight); - } - } - } - } - } else { - primaryIconParams.gravity = TOP | CENTER_HORIZONTAL; - secondaryIconParams.gravity = TOP | CENTER_HORIZONTAL; - if (!inSplitSelection) { - if (oneIconHiddenDueToSmallWidth) { - // Center both icons - primaryIconView.setTranslationX(0); - secondaryIconView.setTranslationX(0); - } else { - // shifts icon half a width left (height is used here since icons are square) - primaryIconView.setTranslationX(-(taskIconHeight / 2f)); - secondaryIconView.setTranslationX(taskIconHeight / 2f); - } - } - } - if (!enableOverviewIconMenu() && !inSplitSelection) { - primaryIconView.setTranslationY(0); - secondaryIconView.setTranslationY(0); - } - - - primaryIconView.setLayoutParams(primaryIconParams); - secondaryIconView.setLayoutParams(secondaryIconParams); - } - - @Override - public int getDefaultSplitPosition(DeviceProfile deviceProfile) { - if (!deviceProfile.isTablet) { - throw new IllegalStateException("Default position available only for large screens"); - } - if (deviceProfile.isLeftRightSplit) { - return STAGE_POSITION_BOTTOM_OR_RIGHT; - } else { - return STAGE_POSITION_TOP_OR_LEFT; - } - } - - @Override - public Pair getSplitSelectTaskOffset(FloatProperty primary, - FloatProperty secondary, DeviceProfile deviceProfile) { - if (deviceProfile.isLeftRightSplit) { // or seascape - return new Pair<>(primary, secondary); - } else { - return new Pair<>(secondary, primary); - } - } - - @Override - public float getFloatingTaskOffscreenTranslationTarget(View floatingTask, RectF onScreenRect, - @StagePosition int stagePosition, DeviceProfile dp) { - if (dp.isLeftRightSplit) { - float currentTranslationX = floatingTask.getTranslationX(); - return stagePosition == STAGE_POSITION_TOP_OR_LEFT - ? currentTranslationX - onScreenRect.width() - : currentTranslationX + onScreenRect.width(); - } else { - float currentTranslationY = floatingTask.getTranslationY(); - return currentTranslationY - onScreenRect.height(); - } - } - - @Override - public void setFloatingTaskPrimaryTranslation(View floatingTask, float translation, - DeviceProfile dp) { - if (dp.isLeftRightSplit) { - floatingTask.setTranslationX(translation); - } else { - floatingTask.setTranslationY(translation); - } - - } - - @Override - public float getFloatingTaskPrimaryTranslation(View floatingTask, DeviceProfile dp) { - return dp.isLeftRightSplit - ? floatingTask.getTranslationX() - : floatingTask.getTranslationY(); - } - - @NonNull - @Override - public LauncherAtom.TaskSwitcherContainer.OrientationHandler getHandlerTypeForLogging() { - return LauncherAtom.TaskSwitcherContainer.OrientationHandler.PORTRAIT; - } -} diff --git a/quickstep/src/com/android/quickstep/orientation/PortraitPagedViewHandler.kt b/quickstep/src/com/android/quickstep/orientation/PortraitPagedViewHandler.kt new file mode 100644 index 0000000000..f2e53fc6fa --- /dev/null +++ b/quickstep/src/com/android/quickstep/orientation/PortraitPagedViewHandler.kt @@ -0,0 +1,903 @@ +/* + * 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.orientation + +import android.graphics.Matrix +import android.graphics.Point +import android.graphics.PointF +import android.graphics.Rect +import android.graphics.RectF +import android.graphics.drawable.ShapeDrawable +import android.util.FloatProperty +import android.util.Pair +import android.view.Gravity +import android.view.Surface +import android.view.View +import android.view.ViewGroup +import android.widget.FrameLayout +import android.widget.LinearLayout +import androidx.core.view.updateLayoutParams +import com.android.launcher3.DeviceProfile +import com.android.launcher3.Flags.enableOverviewIconMenu +import com.android.launcher3.LauncherAnimUtils +import com.android.launcher3.R +import com.android.launcher3.Utilities +import com.android.launcher3.logger.LauncherAtom +import com.android.launcher3.touch.DefaultPagedViewHandler +import com.android.launcher3.touch.PagedOrientationHandler.Float2DAction +import com.android.launcher3.touch.PagedOrientationHandler.Int2DAction +import com.android.launcher3.touch.SingleAxisSwipeDetector +import com.android.launcher3.util.SplitConfigurationOptions +import com.android.launcher3.util.SplitConfigurationOptions.SplitPositionOption +import com.android.launcher3.util.SplitConfigurationOptions.StagePosition +import com.android.quickstep.views.IconAppChipView +import kotlin.math.max +import kotlin.math.min + +class PortraitPagedViewHandler : DefaultPagedViewHandler(), RecentsPagedOrientationHandler { + private val tmpMatrix = Matrix() + private val tmpRectF = RectF() + + override fun getPrimaryValue(x: T, y: T): T = x + + override fun getSecondaryValue(x: T, y: T): T = y + + override val isLayoutNaturalToLauncher: Boolean = true + + override fun adjustFloatingIconStartVelocity(velocity: PointF) { + // no-op + } + + override fun fixBoundsForHomeAnimStartRect(outStartRect: RectF, deviceProfile: DeviceProfile) { + if (outStartRect.left > deviceProfile.widthPx) { + outStartRect.offsetTo(0f, outStartRect.top) + } else if (outStartRect.left < -deviceProfile.widthPx) { + outStartRect.offsetTo(0f, outStartRect.top) + } + } + + override fun setSecondary(target: T, action: Float2DAction, param: Float) = + action.call(target, 0f, param) + + override fun set( + target: T, + action: Int2DAction, + primaryParam: Int, + secondaryParam: Int, + ) = action.call(target, primaryParam, secondaryParam) + + override fun getPrimarySize(view: View): Int = view.width + + override fun getPrimarySize(rect: RectF): Float = rect.width() + + override fun getStart(rect: RectF): Float = rect.left + + override fun getEnd(rect: RectF): Float = rect.right + + override fun rotateInsets(insets: Rect, outInsets: Rect) = outInsets.set(insets) + + override fun getClearAllSidePadding(view: View, isRtl: Boolean): Int = + (if (isRtl) view.paddingRight else -view.paddingLeft) / 2 + + override fun getSecondaryDimension(view: View): Int = view.height + + override val primaryViewTranslate: FloatProperty = LauncherAnimUtils.VIEW_TRANSLATE_X + + override val secondaryViewTranslate: FloatProperty = LauncherAnimUtils.VIEW_TRANSLATE_Y + + override val degreesRotated: Float = 0f + + override val rotation: Int = Surface.ROTATION_0 + + override fun setPrimaryScale(view: View, scale: Float) { + view.scaleX = scale + } + + override fun setSecondaryScale(view: View, scale: Float) { + view.scaleY = scale + } + + override val secondaryTranslationDirectionFactor: Int + get() = -1 + + override fun getSplitTranslationDirectionFactor( + stagePosition: Int, + deviceProfile: DeviceProfile, + ): Int = + if ( + deviceProfile.isLeftRightSplit && + stagePosition == SplitConfigurationOptions.STAGE_POSITION_BOTTOM_OR_RIGHT + ) { + -1 + } else { + 1 + } + + override fun getTaskMenuX( + x: Float, + thumbnailView: View, + deviceProfile: DeviceProfile, + taskInsetMargin: Float, + taskViewIcon: View, + ): Float = + if (deviceProfile.isLandscape) { + (x + + taskInsetMargin + + (thumbnailView.measuredWidth - thumbnailView.measuredHeight) / 2f) + } else { + x + taskInsetMargin + } + + override fun getTaskMenuY( + y: Float, + thumbnailView: View, + stagePosition: Int, + taskMenuView: View, + taskInsetMargin: Float, + taskViewIcon: View, + ): Float = y + taskInsetMargin + + override fun getTaskMenuWidth( + thumbnailView: View, + deviceProfile: DeviceProfile, + @StagePosition stagePosition: Int, + ): Int = + when { + enableOverviewIconMenu() -> { + thumbnailView.resources.getDimensionPixelSize( + R.dimen.task_thumbnail_icon_menu_expanded_width + ) + } + + (deviceProfile.isLandscape && !deviceProfile.isTablet) -> { + val padding = + thumbnailView.resources.getDimensionPixelSize(R.dimen.task_menu_edge_padding) + thumbnailView.measuredHeight - (2 * padding) + } + + else -> { + val padding = + thumbnailView.resources.getDimensionPixelSize(R.dimen.task_menu_edge_padding) + thumbnailView.measuredWidth - (2 * padding) + } + } + + override fun getTaskMenuHeight( + taskInsetMargin: Float, + deviceProfile: DeviceProfile, + taskMenuX: Float, + taskMenuY: Float, + ): Int = + deviceProfile.heightPx - + deviceProfile.insets.top - + taskMenuY.toInt() - + deviceProfile.overviewActionsClaimedSpaceBelow + + override fun setTaskOptionsMenuLayoutOrientation( + deviceProfile: DeviceProfile, + taskMenuLayout: LinearLayout, + dividerSpacing: Int, + dividerDrawable: ShapeDrawable, + ) { + taskMenuLayout.orientation = LinearLayout.VERTICAL + dividerDrawable.intrinsicHeight = dividerSpacing + taskMenuLayout.dividerDrawable = dividerDrawable + } + + override fun setLayoutParamsForTaskMenuOptionItem( + lp: LinearLayout.LayoutParams, + viewGroup: LinearLayout, + deviceProfile: DeviceProfile, + ) { + viewGroup.orientation = LinearLayout.HORIZONTAL + lp.width = LinearLayout.LayoutParams.MATCH_PARENT + lp.height = ViewGroup.LayoutParams.WRAP_CONTENT + } + + override fun updateDwbBannerLayout( + taskViewWidth: Int, + taskViewHeight: Int, + isGroupedTaskView: Boolean, + deviceProfile: DeviceProfile, + snapshotViewWidth: Int, + snapshotViewHeight: Int, + banner: View, + ) { + banner.pivotX = 0f + banner.pivotY = 0f + banner.rotation = degreesRotated + banner.updateLayoutParams { + if (isGroupedTaskView) { + gravity = + Gravity.BOTTOM or + (if (deviceProfile.isLeftRightSplit) Gravity.START + else Gravity.CENTER_HORIZONTAL) + width = snapshotViewWidth + } else { + width = ViewGroup.LayoutParams.MATCH_PARENT + gravity = Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL + } + } + } + + override fun getDwbBannerTranslations( + taskViewWidth: Int, + taskViewHeight: Int, + splitBounds: SplitConfigurationOptions.SplitBounds?, + deviceProfile: DeviceProfile, + thumbnailViews: Array, + desiredTaskId: Int, + banner: View, + ): Pair { + var translationX = 0f + var translationY = 0f + if (splitBounds != null) { + if (deviceProfile.isLeftRightSplit) { + if (desiredTaskId == splitBounds.rightBottomTaskId) { + val leftTopTaskPercent = splitBounds.leftTopTaskPercent + val dividerThicknessPercent = splitBounds.dividerPercent + translationX = + ((taskViewWidth * leftTopTaskPercent) + + (taskViewWidth * dividerThicknessPercent)) + } + } else { + if (desiredTaskId == splitBounds.leftTopTaskId) { + val snapshotParams = thumbnailViews[0].layoutParams as FrameLayout.LayoutParams + val bottomRightTaskPlusDividerPercent = + (splitBounds.rightBottomTaskPercent + splitBounds.dividerPercent) + translationY = + -((taskViewHeight - snapshotParams.topMargin) * + bottomRightTaskPlusDividerPercent) + } + } + } + return Pair(translationX, translationY) + } + + /* ---------- The following are only used by TaskViewTouchHandler. ---------- */ + + override val upDownSwipeDirection: SingleAxisSwipeDetector.Direction = + SingleAxisSwipeDetector.VERTICAL + + // Ignore rtl since it only affects X value displacement, Y displacement doesn't change + override fun getUpDirection(isRtl: Boolean): Int = SingleAxisSwipeDetector.DIRECTION_POSITIVE + + // Ignore rtl since it only affects X value displacement, Y displacement doesn't change + override fun getDownDirection(isRtl: Boolean): Int = SingleAxisSwipeDetector.DIRECTION_NEGATIVE + + // Ignore rtl since it only affects X value displacement, Y displacement doesn't change + override fun isGoingUp(displacement: Float, isRtl: Boolean): Boolean = displacement < 0 + + // Ignore rtl since it only affects X value displacement, Y displacement doesn't change + override fun getTaskDragDisplacementFactor(isRtl: Boolean): Int = 1 + + /* -------------------- */ + + override fun getDistanceToBottomOfRect(dp: DeviceProfile, rect: Rect): Int = + dp.heightPx - rect.bottom + + override fun getSplitPositionOptions(dp: DeviceProfile): List = + when { + dp.isTablet -> { + Utilities.getSplitPositionOptions(dp) + } + + dp.isSeascape -> { + listOf( + SplitPositionOption( + R.drawable.ic_split_horizontal, + R.string.recent_task_option_split_screen, + SplitConfigurationOptions.STAGE_POSITION_BOTTOM_OR_RIGHT, + SplitConfigurationOptions.STAGE_TYPE_MAIN, + ) + ) + } + + dp.isLeftRightSplit -> { + listOf( + SplitPositionOption( + R.drawable.ic_split_horizontal, + R.string.recent_task_option_split_screen, + SplitConfigurationOptions.STAGE_POSITION_TOP_OR_LEFT, + SplitConfigurationOptions.STAGE_TYPE_MAIN, + ) + ) + } + + else -> { + // Only add top option + listOf( + SplitPositionOption( + R.drawable.ic_split_vertical, + R.string.recent_task_option_split_screen, + SplitConfigurationOptions.STAGE_POSITION_TOP_OR_LEFT, + SplitConfigurationOptions.STAGE_TYPE_MAIN, + ) + ) + } + } + + override fun getInitialSplitPlaceholderBounds( + placeholderHeight: Int, + placeholderInset: Int, + dp: DeviceProfile, + @StagePosition stagePosition: Int, + out: Rect, + ) { + val screenWidth = dp.widthPx + val screenHeight = dp.heightPx + val pinToRight = stagePosition == SplitConfigurationOptions.STAGE_POSITION_BOTTOM_OR_RIGHT + val insetSizeAdjustment = getPlaceholderSizeAdjustment(dp, pinToRight) + + out.set(0, 0, screenWidth, placeholderHeight + insetSizeAdjustment) + if (!dp.isLeftRightSplit) { + // portrait, phone or tablet - spans width of screen, nothing else to do + out.inset(placeholderInset, 0) + + // Adjust the top to account for content off screen. This will help to animate the view + // in with rounded corners. + val totalHeight = + (1.0f * screenHeight / 2 * (screenWidth - 2 * placeholderInset) / screenWidth) + .toInt() + out.top -= (totalHeight - placeholderHeight) + return + } + + // Now we rotate the portrait rect depending on what side we want pinned + val postRotateScale = screenHeight.toFloat() / screenWidth + tmpMatrix.reset() + tmpMatrix.postRotate(if (pinToRight) 90f else 270f) + tmpMatrix.postTranslate( + (if (pinToRight) screenWidth else 0).toFloat(), + (if (pinToRight) 0 else screenWidth).toFloat(), + ) + // The placeholder height stays constant after rotation, so we don't change width scale + tmpMatrix.postScale(1f, postRotateScale) + + tmpRectF.set(out) + tmpMatrix.mapRect(tmpRectF) + tmpRectF.inset(0f, placeholderInset.toFloat()) + tmpRectF.roundOut(out) + + // Adjust the top to account for content off screen. This will help to animate the view in + // with rounded corners. + val totalWidth = + (1.0f * screenWidth / 2 * (screenHeight - 2 * placeholderInset) / screenHeight).toInt() + val width = out.width() + if (pinToRight) { + out.right += totalWidth - width + } else { + out.left -= totalWidth - width + } + } + + override fun updateSplitIconParams( + out: View, + onScreenRectCenterX: Float, + onScreenRectCenterY: Float, + fullscreenScaleX: Float, + fullscreenScaleY: Float, + drawableWidth: Int, + drawableHeight: Int, + dp: DeviceProfile, + @StagePosition stagePosition: Int, + ) { + val pinToRight = stagePosition == SplitConfigurationOptions.STAGE_POSITION_BOTTOM_OR_RIGHT + val insetAdjustment = getPlaceholderSizeAdjustment(dp, pinToRight) / 2f + if (!dp.isLeftRightSplit) { + out.x = (onScreenRectCenterX / fullscreenScaleX - 1.0f * drawableWidth / 2) + out.y = + ((onScreenRectCenterY + insetAdjustment) / fullscreenScaleY - + 1.0f * drawableHeight / 2) + } else { + if (pinToRight) { + out.x = + ((onScreenRectCenterX - insetAdjustment) / fullscreenScaleX - + 1.0f * drawableWidth / 2) + } else { + out.x = + ((onScreenRectCenterX + insetAdjustment) / fullscreenScaleX - + 1.0f * drawableWidth / 2) + } + out.y = (onScreenRectCenterY / fullscreenScaleY - 1.0f * drawableHeight / 2) + } + } + + /** + * The split placeholder comes with a default inset to buffer the icon from the top of the + * screen. But if the device already has a large inset (from cutouts etc), use that instead. + */ + private fun getPlaceholderSizeAdjustment(dp: DeviceProfile, pinToRight: Boolean): Int { + val insetThickness = + if (!dp.isLandscape) { + dp.insets.top + } else { + if (pinToRight) dp.insets.right else dp.insets.left + } + return max((insetThickness - dp.splitPlaceholderInset).toDouble(), 0.0).toInt() + } + + override fun setSplitInstructionsParams( + out: View, + dp: DeviceProfile, + splitInstructionsHeight: Int, + splitInstructionsWidth: Int, + ) { + out.pivotX = 0f + out.pivotY = splitInstructionsHeight.toFloat() + out.rotation = degreesRotated + val distanceToEdge = + if (dp.isPhone) { + if (dp.isLandscape) { + out.resources.getDimensionPixelSize( + R.dimen.split_instructions_bottom_margin_phone_landscape + ) + } else { + out.resources.getDimensionPixelSize( + R.dimen.split_instructions_bottom_margin_phone_portrait + ) + } + } else { + dp.overviewActionsClaimedSpaceBelow + } + + // Center the view in case of unbalanced insets on left or right of screen + val insetCorrectionX = (dp.insets.right - dp.insets.left) / 2 + // Adjust for any insets on the bottom edge + val insetCorrectionY = dp.insets.bottom + out.translationX = insetCorrectionX.toFloat() + out.translationY = (-distanceToEdge + insetCorrectionY).toFloat() + val lp = out.layoutParams as FrameLayout.LayoutParams + lp.gravity = Gravity.CENTER_HORIZONTAL or Gravity.BOTTOM + out.layoutParams = lp + } + + override fun getFinalSplitPlaceholderBounds( + splitDividerSize: Int, + dp: DeviceProfile, + @StagePosition stagePosition: Int, + out1: Rect, + out2: Rect, + ) { + val screenHeight = dp.heightPx + val screenWidth = dp.widthPx + out1.set(0, 0, screenWidth, screenHeight / 2 - splitDividerSize) + out2.set(0, screenHeight / 2 + splitDividerSize, screenWidth, screenHeight) + if (!dp.isLeftRightSplit) { + // Portrait - the window bounds are always top and bottom half + return + } + + // Now we rotate the portrait rect depending on what side we want pinned + val pinToRight = stagePosition == SplitConfigurationOptions.STAGE_POSITION_BOTTOM_OR_RIGHT + val postRotateScale = screenHeight.toFloat() / screenWidth + + tmpMatrix.reset() + tmpMatrix.postRotate(if (pinToRight) 90f else 270f) + tmpMatrix.postTranslate( + (if (pinToRight) screenHeight else 0).toFloat(), + (if (pinToRight) 0 else screenWidth).toFloat(), + ) + tmpMatrix.postScale(1 / postRotateScale, postRotateScale) + + tmpRectF.set(out1) + tmpMatrix.mapRect(tmpRectF) + tmpRectF.roundOut(out1) + + tmpRectF.set(out2) + tmpMatrix.mapRect(tmpRectF) + tmpRectF.roundOut(out2) + } + + override fun setSplitTaskSwipeRect( + dp: DeviceProfile, + outRect: Rect, + splitInfo: SplitConfigurationOptions.SplitBounds, + desiredStagePosition: Int, + ) { + val topLeftTaskPercent = splitInfo.leftTopTaskPercent + val dividerBarPercent = splitInfo.dividerPercent + + val taskbarHeight = if (dp.isTransientTaskbar) 0 else dp.taskbarHeight + val scale = outRect.height().toFloat() / (dp.availableHeightPx - taskbarHeight) + val topTaskHeight = dp.availableHeightPx * topLeftTaskPercent + val scaledTopTaskHeight = topTaskHeight * scale + val dividerHeight = dp.availableHeightPx * dividerBarPercent + val scaledDividerHeight = dividerHeight * scale + + if (desiredStagePosition == SplitConfigurationOptions.STAGE_POSITION_TOP_OR_LEFT) { + if (dp.isLeftRightSplit) { + outRect.right = outRect.left + Math.round(outRect.width() * topLeftTaskPercent) + } else { + outRect.bottom = Math.round(outRect.top + scaledTopTaskHeight) + } + } else { + if (dp.isLeftRightSplit) { + outRect.left += + Math.round(outRect.width() * (topLeftTaskPercent + dividerBarPercent)) + } else { + outRect.top += Math.round(scaledTopTaskHeight + scaledDividerHeight) + } + } + } + + /** + * @param inSplitSelection Whether user currently has a task from this task group staged for + * split screen. If true, we have custom translations/scaling in place for the remaining + * snapshot, so we'll skip setting translation/scale here. + */ + override fun measureGroupedTaskViewThumbnailBounds( + primarySnapshot: View, + secondarySnapshot: View, + parentWidth: Int, + parentHeight: Int, + splitBoundsConfig: SplitConfigurationOptions.SplitBounds, + dp: DeviceProfile, + isRtl: Boolean, + inSplitSelection: Boolean, + ) { + val spaceAboveSnapshot = dp.overviewTaskThumbnailTopMarginPx + + val primaryParams = primarySnapshot.layoutParams as FrameLayout.LayoutParams + val secondaryParams = secondarySnapshot.layoutParams as FrameLayout.LayoutParams + + // Reset margins that aren't used in this method, but are used in other + // `RecentsPagedOrientationHandler` variants. + secondaryParams.topMargin = 0 + primaryParams.topMargin = spaceAboveSnapshot + + val totalThumbnailHeight = parentHeight - spaceAboveSnapshot + val dividerScale = splitBoundsConfig.dividerPercent + val taskViewSizes = + getGroupedTaskViewSizes(dp, splitBoundsConfig, parentWidth, parentHeight) + if (!inSplitSelection) { + // Reset translations that aren't used in this method, but are used in other + // `RecentsPagedOrientationHandler` variants. + primarySnapshot.translationY = 0f + + if (dp.isLeftRightSplit) { + val scaledDividerBar = Math.round(parentWidth * dividerScale) + if (isRtl) { + val translationX = taskViewSizes.second.x + scaledDividerBar + primarySnapshot.translationX = -translationX.toFloat() + secondarySnapshot.translationX = 0f + } else { + val translationX = taskViewSizes.first.x + scaledDividerBar + secondarySnapshot.translationX = translationX.toFloat() + primarySnapshot.translationX = 0f + } + secondarySnapshot.translationY = spaceAboveSnapshot.toFloat() + } else { + val finalDividerHeight = Math.round(totalThumbnailHeight * dividerScale).toFloat() + val translationY = taskViewSizes.first.y + spaceAboveSnapshot + finalDividerHeight + secondarySnapshot.translationY = translationY + + // Reset unused translations. + secondarySnapshot.translationX = 0f + primarySnapshot.translationX = 0f + } + } + + primarySnapshot.measure( + View.MeasureSpec.makeMeasureSpec(taskViewSizes.first.x, View.MeasureSpec.EXACTLY), + View.MeasureSpec.makeMeasureSpec(taskViewSizes.first.y, View.MeasureSpec.EXACTLY), + ) + secondarySnapshot.measure( + View.MeasureSpec.makeMeasureSpec(taskViewSizes.second.x, View.MeasureSpec.EXACTLY), + View.MeasureSpec.makeMeasureSpec(taskViewSizes.second.y, View.MeasureSpec.EXACTLY), + ) + } + + override fun getGroupedTaskViewSizes( + dp: DeviceProfile, + splitBoundsConfig: SplitConfigurationOptions.SplitBounds, + parentWidth: Int, + parentHeight: Int, + ): Pair { + val spaceAboveSnapshot = dp.overviewTaskThumbnailTopMarginPx + val totalThumbnailHeight = parentHeight - spaceAboveSnapshot + val dividerScale = splitBoundsConfig.dividerPercent + val taskPercent = splitBoundsConfig.leftTopTaskPercent + + val firstTaskViewSize = Point() + val secondTaskViewSize = Point() + + if (dp.isLeftRightSplit) { + val scaledDividerBar = Math.round(parentWidth * dividerScale) + firstTaskViewSize.x = Math.round(parentWidth * taskPercent) + firstTaskViewSize.y = totalThumbnailHeight + + secondTaskViewSize.x = parentWidth - firstTaskViewSize.x - scaledDividerBar + secondTaskViewSize.y = totalThumbnailHeight + } else { + val taskbarHeight = if (dp.isTransientTaskbar) 0 else dp.taskbarHeight + val scale = totalThumbnailHeight.toFloat() / (dp.availableHeightPx - taskbarHeight) + val topTaskHeight = dp.availableHeightPx * taskPercent + val finalDividerHeight = Math.round(totalThumbnailHeight * dividerScale).toFloat() + val scaledTopTaskHeight = topTaskHeight * scale + firstTaskViewSize.x = parentWidth + firstTaskViewSize.y = Math.round(scaledTopTaskHeight) + + secondTaskViewSize.x = parentWidth + secondTaskViewSize.y = + Math.round((totalThumbnailHeight - firstTaskViewSize.y - finalDividerHeight)) + } + + return Pair(firstTaskViewSize, secondTaskViewSize) + } + + override fun setTaskIconParams( + iconParams: FrameLayout.LayoutParams, + taskIconMargin: Int, + taskIconHeight: Int, + thumbnailTopMargin: Int, + isRtl: Boolean, + ) { + iconParams.gravity = Gravity.TOP or Gravity.CENTER_HORIZONTAL + // Reset margins, since they may have been set on rotation + iconParams.rightMargin = 0 + iconParams.leftMargin = iconParams.rightMargin + iconParams.bottomMargin = 0 + iconParams.topMargin = iconParams.bottomMargin + } + + override fun setIconAppChipChildrenParams( + iconParams: FrameLayout.LayoutParams, + chipChildMarginStart: Int, + ) { + iconParams.marginStart = chipChildMarginStart + iconParams.gravity = Gravity.START or Gravity.CENTER_VERTICAL + iconParams.topMargin = 0 + } + + override fun setIconAppChipMenuParams( + iconAppChipView: IconAppChipView, + iconMenuParams: FrameLayout.LayoutParams, + iconMenuMargin: Int, + thumbnailTopMargin: Int, + ) { + iconMenuParams.gravity = Gravity.TOP or Gravity.START + iconMenuParams.marginStart = iconMenuMargin + iconMenuParams.topMargin = thumbnailTopMargin + iconMenuParams.bottomMargin = 0 + iconMenuParams.marginEnd = 0 + + iconAppChipView.pivotX = 0f + iconAppChipView.pivotY = 0f + iconAppChipView.setSplitTranslationY(0f) + iconAppChipView.rotation = degreesRotated + } + + /** + * @param inSplitSelection Whether user currently has a task from this task group staged for + * split screen. If true, we have custom translations in place for the remaining icon, so + * we'll skip setting translations here. + */ + override fun setSplitIconParams( + primaryIconView: View, + secondaryIconView: View, + taskIconHeight: Int, + primarySnapshotWidth: Int, + primarySnapshotHeight: Int, + groupedTaskViewHeight: Int, + groupedTaskViewWidth: Int, + isRtl: Boolean, + deviceProfile: DeviceProfile, + splitConfig: SplitConfigurationOptions.SplitBounds, + inSplitSelection: Boolean, + oneIconHiddenDueToSmallWidth: Boolean, + ) { + val primaryIconParams = primaryIconView.layoutParams as FrameLayout.LayoutParams + val secondaryIconParams = + if (enableOverviewIconMenu()) secondaryIconView.layoutParams as FrameLayout.LayoutParams + else FrameLayout.LayoutParams(primaryIconParams) + + if (enableOverviewIconMenu()) { + val primaryAppChipView = primaryIconView as IconAppChipView + val secondaryAppChipView = secondaryIconView as IconAppChipView + primaryIconParams.gravity = Gravity.TOP or Gravity.START + secondaryIconParams.gravity = Gravity.TOP or Gravity.START + secondaryIconParams.topMargin = primaryIconParams.topMargin + secondaryIconParams.marginStart = primaryIconParams.marginStart + if (!inSplitSelection) { + if (deviceProfile.isLeftRightSplit) { + if (isRtl) { + val secondarySnapshotWidth = groupedTaskViewWidth - primarySnapshotWidth + primaryAppChipView.setSplitTranslationX(-secondarySnapshotWidth.toFloat()) + } else { + secondaryAppChipView.setSplitTranslationX(primarySnapshotWidth.toFloat()) + } + } else { + primaryAppChipView.setSplitTranslationX(0f) + secondaryAppChipView.setSplitTranslationX(0f) + val dividerThickness = + min( + splitConfig.visualDividerBounds.width().toDouble(), + splitConfig.visualDividerBounds.height().toDouble(), + ) + .toInt() + secondaryAppChipView.setSplitTranslationY( + (primarySnapshotHeight + + (if (deviceProfile.isTablet) 0 else dividerThickness)) + .toFloat() + ) + } + } + } else if (deviceProfile.isLeftRightSplit) { + // We calculate the "midpoint" of the thumbnail area, and place the icons there. + // This is the place where the thumbnail area splits by default, in a near-50/50 split. + // It is usually not exactly 50/50, due to insets/screen cutouts. + val fullscreenInsetThickness = + if (deviceProfile.isSeascape) deviceProfile.insets.right + else deviceProfile.insets.left + val fullscreenMidpointFromBottom = + ((deviceProfile.widthPx - fullscreenInsetThickness) / 2) + val midpointFromEndPct = fullscreenMidpointFromBottom.toFloat() / deviceProfile.widthPx + val insetPct = fullscreenInsetThickness.toFloat() / deviceProfile.widthPx + val spaceAboveSnapshots = 0 + val overviewThumbnailAreaThickness = groupedTaskViewWidth - spaceAboveSnapshots + val bottomToMidpointOffset = + (overviewThumbnailAreaThickness * midpointFromEndPct).toInt() + val insetOffset = (overviewThumbnailAreaThickness * insetPct).toInt() + + if (deviceProfile.isSeascape) { + primaryIconParams.gravity = + Gravity.TOP or (if (isRtl) Gravity.END else Gravity.START) + secondaryIconParams.gravity = + Gravity.TOP or (if (isRtl) Gravity.END else Gravity.START) + if (!inSplitSelection) { + if (splitConfig.initiatedFromSeascape) { + if (oneIconHiddenDueToSmallWidth) { + // Center both icons + val centerX = bottomToMidpointOffset - (taskIconHeight / 2f) + primaryIconView.translationX = centerX + secondaryIconView.translationX = centerX + } else { + // the task on the right (secondary) is slightly larger + primaryIconView.translationX = + (bottomToMidpointOffset - taskIconHeight).toFloat() + secondaryIconView.translationX = bottomToMidpointOffset.toFloat() + } + } else { + if (oneIconHiddenDueToSmallWidth) { + // Center both icons + val centerX = + bottomToMidpointOffset + insetOffset - (taskIconHeight / 2f) + primaryIconView.translationX = centerX + secondaryIconView.translationX = centerX + } else { + // the task on the left (primary) is slightly larger + primaryIconView.translationX = + (bottomToMidpointOffset + insetOffset - taskIconHeight).toFloat() + secondaryIconView.translationX = + (bottomToMidpointOffset + insetOffset).toFloat() + } + } + } + } else { + primaryIconParams.gravity = + Gravity.TOP or (if (isRtl) Gravity.START else Gravity.END) + secondaryIconParams.gravity = + Gravity.TOP or (if (isRtl) Gravity.START else Gravity.END) + if (!inSplitSelection) { + if (!splitConfig.initiatedFromSeascape) { + if (oneIconHiddenDueToSmallWidth) { + // Center both icons + val centerX = -bottomToMidpointOffset + (taskIconHeight / 2f) + primaryIconView.translationX = centerX + secondaryIconView.translationX = centerX + } else { + // the task on the left (primary) is slightly larger + primaryIconView.translationX = -bottomToMidpointOffset.toFloat() + secondaryIconView.translationX = + (-bottomToMidpointOffset + taskIconHeight).toFloat() + } + } else { + if (oneIconHiddenDueToSmallWidth) { + // Center both icons + val centerX = + -bottomToMidpointOffset - insetOffset + (taskIconHeight / 2f) + primaryIconView.translationX = centerX + secondaryIconView.translationX = centerX + } else { + // the task on the right (secondary) is slightly larger + primaryIconView.translationX = + (-bottomToMidpointOffset - insetOffset).toFloat() + secondaryIconView.translationX = + (-bottomToMidpointOffset - insetOffset + taskIconHeight).toFloat() + } + } + } + } + } else { + primaryIconParams.gravity = Gravity.TOP or Gravity.CENTER_HORIZONTAL + secondaryIconParams.gravity = Gravity.TOP or Gravity.CENTER_HORIZONTAL + if (!inSplitSelection) { + if (oneIconHiddenDueToSmallWidth) { + // Center both icons + primaryIconView.translationX = 0f + secondaryIconView.translationX = 0f + } else { + // shifts icon half a width left (height is used here since icons are square) + primaryIconView.translationX = -(taskIconHeight / 2f) + secondaryIconView.translationX = taskIconHeight / 2f + } + } + } + if (!enableOverviewIconMenu() && !inSplitSelection) { + primaryIconView.translationY = 0f + secondaryIconView.translationY = 0f + } + + primaryIconView.layoutParams = primaryIconParams + secondaryIconView.layoutParams = secondaryIconParams + } + + override fun getDefaultSplitPosition(deviceProfile: DeviceProfile): Int { + check(deviceProfile.isTablet) { "Default position available only for large screens" } + return if (deviceProfile.isLeftRightSplit) { + SplitConfigurationOptions.STAGE_POSITION_BOTTOM_OR_RIGHT + } else { + SplitConfigurationOptions.STAGE_POSITION_TOP_OR_LEFT + } + } + + override fun getSplitSelectTaskOffset( + primary: FloatProperty, + secondary: FloatProperty, + deviceProfile: DeviceProfile, + ): Pair, FloatProperty> = + if (deviceProfile.isLeftRightSplit) { // or seascape + Pair(primary, secondary) + } else { + Pair(secondary, primary) + } + + override fun getFloatingTaskOffscreenTranslationTarget( + floatingTask: View, + onScreenRect: RectF, + @StagePosition stagePosition: Int, + dp: DeviceProfile, + ): Float { + if (dp.isLeftRightSplit) { + val currentTranslationX = floatingTask.translationX + return if (stagePosition == SplitConfigurationOptions.STAGE_POSITION_TOP_OR_LEFT) + currentTranslationX - onScreenRect.width() + else currentTranslationX + onScreenRect.width() + } else { + val currentTranslationY = floatingTask.translationY + return currentTranslationY - onScreenRect.height() + } + } + + override fun setFloatingTaskPrimaryTranslation( + floatingTask: View, + translation: Float, + dp: DeviceProfile, + ) { + if (dp.isLeftRightSplit) { + floatingTask.translationX = translation + } else { + floatingTask.translationY = translation + } + } + + override fun getFloatingTaskPrimaryTranslation(floatingTask: View, dp: DeviceProfile): Float = + if (dp.isLeftRightSplit) floatingTask.translationX else floatingTask.translationY + + override fun getHandlerTypeForLogging(): LauncherAtom.TaskSwitcherContainer.OrientationHandler = + LauncherAtom.TaskSwitcherContainer.OrientationHandler.PORTRAIT +} diff --git a/quickstep/src/com/android/quickstep/orientation/SeascapePagedViewHandler.kt b/quickstep/src/com/android/quickstep/orientation/SeascapePagedViewHandler.kt index 0cb983dbe9..7fea55d3d6 100644 --- a/quickstep/src/com/android/quickstep/orientation/SeascapePagedViewHandler.kt +++ b/quickstep/src/com/android/quickstep/orientation/SeascapePagedViewHandler.kt @@ -53,7 +53,7 @@ class SeascapePagedViewHandler : LandscapePagedViewHandler() { override fun getSplitTranslationDirectionFactor( stagePosition: Int, - deviceProfile: DeviceProfile + deviceProfile: DeviceProfile, ): Int = if (stagePosition == STAGE_POSITION_BOTTOM_OR_RIGHT) -1 else 1 override fun getRecentsRtlSetting(resources: Resources): Boolean = Utilities.isRtl(resources) @@ -70,7 +70,7 @@ class SeascapePagedViewHandler : LandscapePagedViewHandler() { thumbnailView: View, deviceProfile: DeviceProfile, taskInsetMargin: Float, - taskViewIcon: View + taskViewIcon: View, ): Float = x + taskInsetMargin override fun getTaskMenuY( @@ -79,7 +79,7 @@ class SeascapePagedViewHandler : LandscapePagedViewHandler() { stagePosition: Int, taskMenuView: View, taskInsetMargin: Float, - taskViewIcon: View + taskViewIcon: View, ): Float { if (Flags.enableOverviewIconMenu()) { return y @@ -97,14 +97,14 @@ class SeascapePagedViewHandler : LandscapePagedViewHandler() { taskInsetMargin: Float, deviceProfile: DeviceProfile, taskMenuX: Float, - taskMenuY: Float + taskMenuY: Float, ): Int = (deviceProfile.availableWidthPx - taskInsetMargin - taskMenuX).toInt() override fun setSplitTaskSwipeRect( dp: DeviceProfile, outRect: Rect, splitInfo: SplitBounds, - desiredStagePosition: Int + desiredStagePosition: Int, ) { val topLeftTaskPercent = splitInfo.leftTopTaskPercent val dividerBarPercent = splitInfo.dividerPercent @@ -126,7 +126,7 @@ class SeascapePagedViewHandler : LandscapePagedViewHandler() { deviceProfile: DeviceProfile, snapshotViewWidth: Int, snapshotViewHeight: Int, - banner: View + banner: View, ) { banner.pivotX = 0f banner.pivotY = 0f @@ -149,7 +149,7 @@ class SeascapePagedViewHandler : LandscapePagedViewHandler() { deviceProfile: DeviceProfile, thumbnailViews: Array, desiredTaskId: Int, - banner: View + banner: View, ): Pair { val snapshotParams = thumbnailViews[0].layoutParams as FrameLayout.LayoutParams val translationX: Float = (taskViewWidth - banner.height).toFloat() @@ -181,7 +181,7 @@ class SeascapePagedViewHandler : LandscapePagedViewHandler() { R.drawable.ic_split_horizontal, R.string.recent_task_option_split_screen, STAGE_POSITION_BOTTOM_OR_RIGHT, - STAGE_TYPE_MAIN + STAGE_TYPE_MAIN, ) ) @@ -189,7 +189,7 @@ class SeascapePagedViewHandler : LandscapePagedViewHandler() { out: View, dp: DeviceProfile, splitInstructionsHeight: Int, - splitInstructionsWidth: Int + splitInstructionsWidth: Int, ) { out.pivotX = 0f out.pivotY = splitInstructionsHeight.toFloat() @@ -217,7 +217,7 @@ class SeascapePagedViewHandler : LandscapePagedViewHandler() { taskIconMargin: Int, taskIconHeight: Int, thumbnailTopMargin: Int, - isRtl: Boolean + isRtl: Boolean, ) { iconParams.gravity = if (isRtl) { @@ -230,7 +230,7 @@ class SeascapePagedViewHandler : LandscapePagedViewHandler() { override fun setIconAppChipChildrenParams( iconParams: FrameLayout.LayoutParams, - chipChildMarginStart: Int + chipChildMarginStart: Int, ) { iconParams.setMargins(0, 0, 0, 0) iconParams.marginStart = chipChildMarginStart @@ -241,7 +241,7 @@ class SeascapePagedViewHandler : LandscapePagedViewHandler() { iconAppChipView: IconAppChipView, iconMenuParams: FrameLayout.LayoutParams, iconMenuMargin: Int, - thumbnailTopMargin: Int + thumbnailTopMargin: Int, ) { val isRtl = iconAppChipView.layoutDirection == View.LAYOUT_DIRECTION_RTL val iconCenter = iconAppChipView.getHeight() / 2f @@ -268,7 +268,7 @@ class SeascapePagedViewHandler : LandscapePagedViewHandler() { /** * @param inSplitSelection Whether user currently has a task from this task group staged for - * split screen. Currently this state is not reachable in fake seascape. + * split screen. Currently this state is not reachable in fake seascape. */ override fun measureGroupedTaskViewThumbnailBounds( primarySnapshot: View, @@ -278,7 +278,7 @@ class SeascapePagedViewHandler : LandscapePagedViewHandler() { splitBoundsConfig: SplitBounds, dp: DeviceProfile, isRtl: Boolean, - inSplitSelection: Boolean + inSplitSelection: Boolean, ) { val primaryParams = primarySnapshot.layoutParams as FrameLayout.LayoutParams val secondaryParams = secondarySnapshot.layoutParams as FrameLayout.LayoutParams @@ -300,11 +300,11 @@ class SeascapePagedViewHandler : LandscapePagedViewHandler() { (taskViewSecond.y + spaceAboveSnapshot + dividerBar).toFloat() primarySnapshot.measure( MeasureSpec.makeMeasureSpec(taskViewFirst.x, MeasureSpec.EXACTLY), - MeasureSpec.makeMeasureSpec(taskViewFirst.y, MeasureSpec.EXACTLY) + MeasureSpec.makeMeasureSpec(taskViewFirst.y, MeasureSpec.EXACTLY), ) secondarySnapshot.measure( MeasureSpec.makeMeasureSpec(taskViewSecond.x, MeasureSpec.EXACTLY), - MeasureSpec.makeMeasureSpec(taskViewSecond.y, MeasureSpec.EXACTLY) + MeasureSpec.makeMeasureSpec(taskViewSecond.y, MeasureSpec.EXACTLY), ) } @@ -312,7 +312,7 @@ class SeascapePagedViewHandler : LandscapePagedViewHandler() { dp: DeviceProfile, splitBoundsConfig: SplitBounds, parentWidth: Int, - parentHeight: Int + parentHeight: Int, ): Pair { // Measure and layout the thumbnails bottom up, since the primary is on the visual left // (portrait bottom) and secondary is on the right (portrait top) @@ -376,10 +376,7 @@ class SeascapePagedViewHandler : LandscapePagedViewHandler() { if (oneIconHiddenDueToSmallWidth) { // Center both icons val centerY = primarySnapshotHeight + ((dividerSize - taskIconHeight) / 2) - SplitIconPositions( - topLeftY = centerY, - bottomRightY = centerY, - ) + SplitIconPositions(topLeftY = centerY, bottomRightY = centerY) } else { SplitIconPositions( topLeftY = primarySnapshotHeight - taskIconHeight, From 87ed2ec7dd607b54f959332d2a3261e1d925303a Mon Sep 17 00:00:00 2001 From: Charlie Anderson Date: Wed, 26 Feb 2025 11:00:18 -0500 Subject: [PATCH 127/153] Make ModelTestExtensions default to process userhandle for HSUM Bug: 398857280 Test: BackupAndRestoreTest Flag: EXEMPT test fix Change-Id: I1781ffd0a04c31ee01108fb5802278051cdff4dc --- .../src/com/android/launcher3/util/ModelTestExtensions.kt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/multivalentTests/src/com/android/launcher3/util/ModelTestExtensions.kt b/tests/multivalentTests/src/com/android/launcher3/util/ModelTestExtensions.kt index 547d05e198..ceefb0dced 100644 --- a/tests/multivalentTests/src/com/android/launcher3/util/ModelTestExtensions.kt +++ b/tests/multivalentTests/src/com/android/launcher3/util/ModelTestExtensions.kt @@ -1,6 +1,7 @@ package com.android.launcher3.util import android.content.ContentValues +import android.os.Process import com.android.launcher3.Flags import com.android.launcher3.LauncherModel import com.android.launcher3.LauncherSettings.Favorites @@ -66,7 +67,7 @@ object ModelTestExtensions { spanX: Int = 1, spanY: Int = 1, id: Int = 0, - profileId: Int = 0, + profileId: Int = Process.myUserHandle().identifier, tableName: String = Favorites.TABLE_NAME, appWidgetId: Int = -1, appWidgetSource: Int = -1, From 604906bb3c5c3f585677034c766d07fcb5945315 Mon Sep 17 00:00:00 2001 From: Jordan Silva Date: Wed, 26 Feb 2025 16:51:37 +0000 Subject: [PATCH 128/153] Skip animation when clicking on menu action from App Chip Menu. Also, skips chip collapse animation when isSplitSelection is active to improve the performance. This animation is not visible for the user, so we reduced the duration to 0 and reset the chip to the correct state. Bug: 398318613 Flag: com.android.launcher3.enable_overview_icon_menu Test: OverviewImageTest Change-Id: I79d543167eb172e6d3a8306122035396e9ee2e7c --- .../android/quickstep/views/IconAppChipView.kt | 3 ++- .../com/android/quickstep/views/TaskMenuView.kt | 17 +++++++++-------- .../src/com/android/quickstep/views/TaskView.kt | 3 ++- 3 files changed, 13 insertions(+), 10 deletions(-) diff --git a/quickstep/src/com/android/quickstep/views/IconAppChipView.kt b/quickstep/src/com/android/quickstep/views/IconAppChipView.kt index 85d14cc5ab..8d535524f5 100644 --- a/quickstep/src/com/android/quickstep/views/IconAppChipView.kt +++ b/quickstep/src/com/android/quickstep/views/IconAppChipView.kt @@ -296,7 +296,7 @@ constructor( fun getMenuTranslationY(): MultiPropertyFactory.MultiProperty = viewTranslationY[INDEX_MENU_TRANSLATION] - internal fun revealAnim(isRevealing: Boolean) { + internal fun revealAnim(isRevealing: Boolean, animated: Boolean = true) { cancelInProgressAnimations() val collapsedBackgroundBounds = getCollapsedBackgroundLtrBounds() val expandedBackgroundBounds = getExpandedBackgroundLtrBounds() @@ -392,6 +392,7 @@ constructor( animator!!.setDuration(MENU_BACKGROUND_HIDE_DURATION.toLong()) } + if (!animated) animator!!.duration = 0 animator!!.interpolator = Interpolators.EMPHASIZED animator!!.start() } diff --git a/quickstep/src/com/android/quickstep/views/TaskMenuView.kt b/quickstep/src/com/android/quickstep/views/TaskMenuView.kt index 95336cfe19..4777f4f140 100644 --- a/quickstep/src/com/android/quickstep/views/TaskMenuView.kt +++ b/quickstep/src/com/android/quickstep/views/TaskMenuView.kt @@ -75,7 +75,7 @@ constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int = 0) : if (ev.action == MotionEvent.ACTION_DOWN) { if (!recentsViewContainer.dragLayer.isEventOverView(this, ev)) { // TODO: log this once we have a new container type for it? - close(true) + animateOpenOrClosed(true) return true } } @@ -83,7 +83,7 @@ constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int = 0) : } override fun handleClose(animate: Boolean) { - animateClose() + animateOpenOrClosed(true, animated = false) } override fun isOfType(type: Int): Boolean = (type and TYPE_TASK_MENU) != 0 @@ -260,11 +260,7 @@ constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int = 0) : private val iconView: View get() = taskContainer.iconView.asView() - private fun animateClose() { - animateOpenOrClosed(true) - } - - private fun animateOpenOrClosed(closing: Boolean) { + private fun animateOpenOrClosed(closing: Boolean, animated: Boolean = true) { openCloseAnimator?.let { if (it.isRunning) it.cancel() } openCloseAnimator = AnimatorSet() // If we're opening, we just start from the beginning as a new `TaskMenuView` is created @@ -312,7 +308,12 @@ constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int = 0) : } } ) - val animationDuration = if (closing) REVEAL_CLOSE_DURATION else REVEAL_OPEN_DURATION + val animationDuration = + when { + animated && closing -> REVEAL_CLOSE_DURATION + animated && !closing -> REVEAL_OPEN_DURATION + else -> 0L + } openCloseAnimator!!.setDuration(animationDuration) openCloseAnimator!!.start() } diff --git a/quickstep/src/com/android/quickstep/views/TaskView.kt b/quickstep/src/com/android/quickstep/views/TaskView.kt index 27db6d6188..c5b8e8cca1 100644 --- a/quickstep/src/com/android/quickstep/views/TaskView.kt +++ b/quickstep/src/com/android/quickstep/views/TaskView.kt @@ -1476,7 +1476,8 @@ constructor( return if (enableOverviewIconMenu() && menuContainer.iconView is IconAppChipView) { menuContainer.iconView.revealAnim(/* isRevealing= */ true) TaskMenuView.showForTask(menuContainer) { - menuContainer.iconView.revealAnim(/* isRevealing= */ false) + val isAnimated = !recentsView.isSplitSelectionActive + menuContainer.iconView.revealAnim(/* isRevealing= */ false, isAnimated) if (enableHoverOfChildElementsInTaskview()) { recentsView.setTaskBorderEnabled(true) } From cd33516a5cea45c300697c111eb40d194808df40 Mon Sep 17 00:00:00 2001 From: Owner Cleanup Bot Date: Wed, 26 Feb 2025 09:44:57 -0800 Subject: [PATCH 129/153] [owners] Remove mateuszc@google.com from tests/multivalentTests/shared/com/android/launcher3/testing/OWNERS This suggested change is automatically generated based on group memberships and affiliations. Please approve this change and vote the highest CR. This will keep the OWNERs file tidy. We ask that you do not ignore this change and approve it unless you know a reason the OWNER should remain. It can always be reverted if needed. If this change is in error, vote the lowest CR value (i.e. reject the CL) and the bot will abandon it. See the owner's recent review activity for context: https://android-review.googlesource.com/q/mateuszc@google.com To report an issue, file a bug in the Infra>Codereview component. Change-Id: Ib310e8949235516783ea820d35fa113e06cd34c3 --- .../multivalentTests/shared/com/android/launcher3/testing/OWNERS | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/multivalentTests/shared/com/android/launcher3/testing/OWNERS b/tests/multivalentTests/shared/com/android/launcher3/testing/OWNERS index a818d5e611..02e8ebcaba 100644 --- a/tests/multivalentTests/shared/com/android/launcher3/testing/OWNERS +++ b/tests/multivalentTests/shared/com/android/launcher3/testing/OWNERS @@ -2,4 +2,3 @@ vadimt@google.com sunnygoyal@google.com winsonc@google.com hyunyoungs@google.com -mateuszc@google.com \ No newline at end of file From f1fe5c0af8b90af24803059d0d577a4247dd5ae1 Mon Sep 17 00:00:00 2001 From: Pat Manning Date: Tue, 25 Feb 2025 14:14:45 +0000 Subject: [PATCH 130/153] Handle dismiss in land/seascape. Determine correct "vertical" direction based on page orientation and rtl. Fix: 398850444 Test: Manual Flag: com.android.launcher3.enable_expressive_dismiss_task_motion Change-Id: If1857c5315f98fb3cc18a643d56c3c7d539deac0 --- .../TaskViewDismissTouchController.kt | 44 ++++++++-------- .../TaskViewLaunchTouchController.kt | 24 +++++---- .../orientation/LandscapePagedViewHandler.kt | 8 +++ .../orientation/PortraitPagedViewHandler.kt | 8 +++ .../RecentsPagedOrientationHandler.kt | 51 +++++++++++-------- .../orientation/SeascapePagedViewHandler.kt | 8 +++ 6 files changed, 93 insertions(+), 50 deletions(-) diff --git a/quickstep/src/com/android/launcher3/uioverrides/touchcontrollers/TaskViewDismissTouchController.kt b/quickstep/src/com/android/launcher3/uioverrides/touchcontrollers/TaskViewDismissTouchController.kt index 88b71559a1..454a307300 100644 --- a/quickstep/src/com/android/launcher3/uioverrides/touchcontrollers/TaskViewDismissTouchController.kt +++ b/quickstep/src/com/android/launcher3/uioverrides/touchcontrollers/TaskViewDismissTouchController.kt @@ -36,7 +36,6 @@ import com.android.quickstep.views.RecentsViewContainer import com.android.quickstep.views.TaskView import com.google.android.msdl.data.model.MSDLToken import kotlin.math.abs -import kotlin.math.sign /** Touch controller for handling task view card dismiss swipes */ class TaskViewDismissTouchController( @@ -53,6 +52,8 @@ CONTAINER : RecentsViewContainer { recentsView.pagedOrientationHandler.upDownSwipeDirection, ) private val isRtl = isRtl(container.resources) + private val upDirection: Int = recentsView.pagedOrientationHandler.getUpDirection(isRtl) + private val tempTaskThumbnailBounds = Rect() private var taskBeingDragged: TaskView? = null @@ -96,7 +97,11 @@ CONTAINER : RecentsViewContainer { } onControllerTouchEvent(ev) - return detector.isDraggingState && detector.wasInitialTouchPositive() + val upDirectionIsPositive = upDirection == SingleAxisSwipeDetector.DIRECTION_POSITIVE + val wasInitialTouchUp = + (upDirectionIsPositive && detector.wasInitialTouchPositive()) || + (!upDirectionIsPositive && !detector.wasInitialTouchPositive()) + return detector.isDraggingState && wasInitialTouchUp } override fun onControllerTouchEvent(ev: MotionEvent?): Boolean = detector.onTouchEvent(ev) @@ -107,25 +112,27 @@ CONTAINER : RecentsViewContainer { if (!canInterceptTouch(ev)) { return false } - taskBeingDragged = recentsView.taskViews .firstOrNull { recentsView.isTaskViewVisible(it) && container.dragLayer.isEventOverView(it, ev) } ?.also { + val secondaryLayerDimension = + recentsView.pagedOrientationHandler.getSecondaryDimension( + container.dragLayer + ) // Dismiss length as bottom of task so it is fully off screen when dismissed. it.getThumbnailBounds(tempTaskThumbnailBounds, relativeToDragLayer = true) - dismissLength = tempTaskThumbnailBounds.bottom + dismissLength = + recentsView.pagedOrientationHandler.getTaskDismissLength( + secondaryLayerDimension, + tempTaskThumbnailBounds, + ) verticalFactor = - recentsView.pagedOrientationHandler.secondaryTranslationDirectionFactor + recentsView.pagedOrientationHandler.getTaskDismissVerticalDirection() } - - detector.setDetectableScrollConditions( - recentsView.pagedOrientationHandler.getUpDirection(isRtl), - /* ignoreSlop = */ false, - ) - + detector.setDetectableScrollConditions(upDirection, /* ignoreSlop= */ false) return true } @@ -148,8 +155,8 @@ CONTAINER : RecentsViewContainer { boundToRange(abs(currentDisplacement), 0f, dismissLength.toFloat()) // When swiping below origin, allow slight undershoot to simulate resisting the movement. val totalDisplacement = - if (isDisplacementPositiveDirection(currentDisplacement)) - boundedDisplacement * sign(currentDisplacement) + if (recentsView.pagedOrientationHandler.isGoingUp(currentDisplacement, isRtl)) + boundedDisplacement * verticalFactor else mapToRange( boundedDisplacement, @@ -158,7 +165,7 @@ CONTAINER : RecentsViewContainer { 0f, container.resources.getDimension(R.dimen.task_dismiss_max_undershoot), DECELERATE, - ) + ) * -verticalFactor taskBeingDragged.secondaryDismissTranslationProperty.setValue( taskBeingDragged, totalDisplacement, @@ -207,8 +214,9 @@ CONTAINER : RecentsViewContainer { } val isBeyondDismissThreshold = abs(currentDisplacement) > abs(DISMISS_THRESHOLD_FRACTION * dismissLength) - val isFlingingTowardsDismiss = detector.isFling(velocity) && velocity < 0 - val isFlingingTowardsRestState = detector.isFling(velocity) && velocity > 0 + val velocityIsGoingUp = recentsView.pagedOrientationHandler.isGoingUp(velocity, isRtl) + val isFlingingTowardsDismiss = detector.isFling(velocity) && velocityIsGoingUp + val isFlingingTowardsRestState = detector.isFling(velocity) && !velocityIsGoingUp val isDismissing = isFlingingTowardsDismiss || (isBeyondDismissThreshold && !isFlingingTowardsRestState) springAnimation = @@ -232,10 +240,6 @@ CONTAINER : RecentsViewContainer { } } - // Returns if the current task being dragged is towards "positive" (e.g. dismissal). - private fun isDisplacementPositiveDirection(displacement: Float): Boolean = - sign(displacement) == sign(verticalFactor.toFloat()) - private fun clearState() { detector.finishedScrolling() detector.setDetectableScrollConditions(0, false) diff --git a/quickstep/src/com/android/launcher3/uioverrides/touchcontrollers/TaskViewLaunchTouchController.kt b/quickstep/src/com/android/launcher3/uioverrides/touchcontrollers/TaskViewLaunchTouchController.kt index c740dadbcd..8ee552d046 100644 --- a/quickstep/src/com/android/launcher3/uioverrides/touchcontrollers/TaskViewLaunchTouchController.kt +++ b/quickstep/src/com/android/launcher3/uioverrides/touchcontrollers/TaskViewLaunchTouchController.kt @@ -53,6 +53,7 @@ CONTAINER : RecentsViewContainer { recentsView.pagedOrientationHandler.upDownSwipeDirection, ) private val isRtl = isRtl(container.resources) + private val downDirection = recentsView.pagedOrientationHandler.getDownDirection(isRtl) private var taskBeingDragged: TaskView? = null private var launchEndDisplacement: Float = 0f @@ -104,7 +105,11 @@ CONTAINER : RecentsViewContainer { } } onControllerTouchEvent(ev) - return detector.isDraggingState && !detector.wasInitialTouchPositive() + val downDirectionIsNegative = downDirection == SingleAxisSwipeDetector.DIRECTION_NEGATIVE + val wasInitialTouchDown = + (downDirectionIsNegative && !detector.wasInitialTouchPositive()) || + (!downDirectionIsNegative && detector.wasInitialTouchPositive()) + return detector.isDraggingState && wasInitialTouchDown } override fun onControllerTouchEvent(ev: MotionEvent) = detector.onTouchEvent(ev) @@ -120,15 +125,12 @@ CONTAINER : RecentsViewContainer { } ?.also { verticalFactor = - recentsView.pagedOrientationHandler.secondaryTranslationDirectionFactor + recentsView.pagedOrientationHandler.getTaskDragDisplacementFactor(isRtl) } if (!canTaskLaunchTaskView(taskBeingDragged)) { return false } - detector.setDetectableScrollConditions( - recentsView.pagedOrientationHandler.getDownDirection(isRtl), - /* ignoreSlop = */ false, - ) + detector.setDetectableScrollConditions(downDirection, /* ignoreSlop= */ false) return true } @@ -143,7 +145,10 @@ CONTAINER : RecentsViewContainer { recentsView.createTaskLaunchAnimation(taskBeingDragged, maxDuration, ZOOM_IN) // Since the thumbnail is what is filling the screen, based the end displacement on it. taskBeingDragged.getThumbnailBounds(tempRect, /* relativeToDragLayer= */ true) - launchEndDisplacement = (secondaryLayerDimension - tempRect.bottom).toFloat() + launchEndDisplacement = + recentsView.pagedOrientationHandler + .getTaskLaunchLength(secondaryLayerDimension, tempRect) + .toFloat() * verticalFactor playbackController = pendingAnimation.createPlaybackController()?.apply { taskViewRecentsTouchContext.onUserControlledAnimationCreated(this) @@ -163,8 +168,9 @@ CONTAINER : RecentsViewContainer { val isBeyondLaunchThreshold = abs(playbackController.progressFraction) > abs(LAUNCH_THRESHOLD_FRACTION) - val isFlingingTowardsLaunch = detector.isFling(velocity) && velocity > 0 - val isFlingingTowardsRestState = detector.isFling(velocity) && velocity < 0 + val velocityIsNegative = !recentsView.pagedOrientationHandler.isGoingUp(velocity, isRtl) + val isFlingingTowardsLaunch = detector.isFling(velocity) && velocityIsNegative + val isFlingingTowardsRestState = detector.isFling(velocity) && !velocityIsNegative val isLaunching = isFlingingTowardsLaunch || (isBeyondLaunchThreshold && !isFlingingTowardsRestState) diff --git a/quickstep/src/com/android/quickstep/orientation/LandscapePagedViewHandler.kt b/quickstep/src/com/android/quickstep/orientation/LandscapePagedViewHandler.kt index ee9b3e8542..e3c9b2bb65 100644 --- a/quickstep/src/com/android/quickstep/orientation/LandscapePagedViewHandler.kt +++ b/quickstep/src/com/android/quickstep/orientation/LandscapePagedViewHandler.kt @@ -311,6 +311,14 @@ open class LandscapePagedViewHandler : RecentsPagedOrientationHandler { override fun getTaskDragDisplacementFactor(isRtl: Boolean): Int = if (isRtl) 1 else -1 + override fun getTaskDismissVerticalDirection(): Int = 1 + + override fun getTaskDismissLength(secondaryDimension: Int, taskThumbnailBounds: Rect): Int = + secondaryDimension - taskThumbnailBounds.left + + override fun getTaskLaunchLength(secondaryDimension: Int, taskThumbnailBounds: Rect): Int = + taskThumbnailBounds.left + /* -------------------- */ override fun getChildBounds( diff --git a/quickstep/src/com/android/quickstep/orientation/PortraitPagedViewHandler.kt b/quickstep/src/com/android/quickstep/orientation/PortraitPagedViewHandler.kt index f2e53fc6fa..18836492b6 100644 --- a/quickstep/src/com/android/quickstep/orientation/PortraitPagedViewHandler.kt +++ b/quickstep/src/com/android/quickstep/orientation/PortraitPagedViewHandler.kt @@ -284,6 +284,14 @@ class PortraitPagedViewHandler : DefaultPagedViewHandler(), RecentsPagedOrientat // Ignore rtl since it only affects X value displacement, Y displacement doesn't change override fun getTaskDragDisplacementFactor(isRtl: Boolean): Int = 1 + override fun getTaskDismissVerticalDirection(): Int = -1 + + override fun getTaskDismissLength(secondaryDimension: Int, taskThumbnailBounds: Rect): Int = + taskThumbnailBounds.bottom + + override fun getTaskLaunchLength(secondaryDimension: Int, taskThumbnailBounds: Rect): Int = + secondaryDimension - taskThumbnailBounds.bottom + /* -------------------- */ override fun getDistanceToBottomOfRect(dp: DeviceProfile, rect: Rect): Int = diff --git a/quickstep/src/com/android/quickstep/orientation/RecentsPagedOrientationHandler.kt b/quickstep/src/com/android/quickstep/orientation/RecentsPagedOrientationHandler.kt index 9b3c4679b1..a7bc93b3d4 100644 --- a/quickstep/src/com/android/quickstep/orientation/RecentsPagedOrientationHandler.kt +++ b/quickstep/src/com/android/quickstep/orientation/RecentsPagedOrientationHandler.kt @@ -82,13 +82,13 @@ interface RecentsPagedOrientationHandler : PagedOrientationHandler { fun getSplitTranslationDirectionFactor( @StagePosition stagePosition: Int, - deviceProfile: DeviceProfile + deviceProfile: DeviceProfile, ): Int fun getSplitSelectTaskOffset( primary: FloatProperty, secondary: FloatProperty, - deviceProfile: DeviceProfile + deviceProfile: DeviceProfile, ): Pair, FloatProperty> fun getDistanceToBottomOfRect(dp: DeviceProfile, rect: Rect): Int @@ -101,7 +101,7 @@ interface RecentsPagedOrientationHandler : PagedOrientationHandler { placeholderInset: Int, dp: DeviceProfile, @StagePosition stagePosition: Int, - out: Rect + out: Rect, ) /** @@ -128,7 +128,7 @@ interface RecentsPagedOrientationHandler : PagedOrientationHandler { drawableWidth: Int, drawableHeight: Int, dp: DeviceProfile, - @StagePosition stagePosition: Int + @StagePosition stagePosition: Int, ) /** @@ -143,7 +143,7 @@ interface RecentsPagedOrientationHandler : PagedOrientationHandler { out: View, dp: DeviceProfile, splitInstructionsHeight: Int, - splitInstructionsWidth: Int + splitInstructionsWidth: Int, ) /** @@ -159,7 +159,7 @@ interface RecentsPagedOrientationHandler : PagedOrientationHandler { dp: DeviceProfile, @StagePosition stagePosition: Int, out1: Rect, - out2: Rect + out2: Rect, ) fun getDefaultSplitPosition(deviceProfile: DeviceProfile): Int @@ -174,7 +174,7 @@ interface RecentsPagedOrientationHandler : PagedOrientationHandler { dp: DeviceProfile, outRect: Rect, splitInfo: SplitConfigurationOptions.SplitBounds, - @StagePosition desiredStagePosition: Int + @StagePosition desiredStagePosition: Int, ) fun measureGroupedTaskViewThumbnailBounds( @@ -185,7 +185,7 @@ interface RecentsPagedOrientationHandler : PagedOrientationHandler { splitBoundsConfig: SplitConfigurationOptions.SplitBounds, dp: DeviceProfile, isRtl: Boolean, - inSplitSelection: Boolean + inSplitSelection: Boolean, ) /** @@ -198,7 +198,7 @@ interface RecentsPagedOrientationHandler : PagedOrientationHandler { dp: DeviceProfile, splitBoundsConfig: SplitConfigurationOptions.SplitBounds, parentWidth: Int, - parentHeight: Int + parentHeight: Int, ): Pair // Overview TaskMenuView methods @@ -208,7 +208,7 @@ interface RecentsPagedOrientationHandler : PagedOrientationHandler { taskIconMargin: Int, taskIconHeight: Int, thumbnailTopMargin: Int, - isRtl: Boolean + isRtl: Boolean, ) /** @@ -216,14 +216,14 @@ interface RecentsPagedOrientationHandler : PagedOrientationHandler { */ fun setIconAppChipChildrenParams( iconParams: FrameLayout.LayoutParams, - chipChildMarginStart: Int + chipChildMarginStart: Int, ) fun setIconAppChipMenuParams( iconAppChipView: IconAppChipView, iconMenuParams: FrameLayout.LayoutParams, iconMenuMargin: Int, - thumbnailTopMargin: Int + thumbnailTopMargin: Int, ) fun setSplitIconParams( @@ -252,7 +252,7 @@ interface RecentsPagedOrientationHandler : PagedOrientationHandler { thumbnailView: View, deviceProfile: DeviceProfile, taskInsetMargin: Float, - taskViewIcon: View + taskViewIcon: View, ): Float fun getTaskMenuY( @@ -261,20 +261,20 @@ interface RecentsPagedOrientationHandler : PagedOrientationHandler { stagePosition: Int, taskMenuView: View, taskInsetMargin: Float, - taskViewIcon: View + taskViewIcon: View, ): Float fun getTaskMenuWidth( thumbnailView: View, deviceProfile: DeviceProfile, - @StagePosition stagePosition: Int + @StagePosition stagePosition: Int, ): Int fun getTaskMenuHeight( taskInsetMargin: Float, deviceProfile: DeviceProfile, taskMenuX: Float, - taskMenuY: Float + taskMenuY: Float, ): Int /** @@ -285,7 +285,7 @@ interface RecentsPagedOrientationHandler : PagedOrientationHandler { deviceProfile: DeviceProfile, taskMenuLayout: LinearLayout, dividerSpacing: Int, - dividerDrawable: ShapeDrawable + dividerDrawable: ShapeDrawable, ) /** @@ -295,7 +295,7 @@ interface RecentsPagedOrientationHandler : PagedOrientationHandler { fun setLayoutParamsForTaskMenuOptionItem( lp: LinearLayout.LayoutParams, viewGroup: LinearLayout, - deviceProfile: DeviceProfile + deviceProfile: DeviceProfile, ) /** Layout a Digital Wellbeing Banner on its parent. TaskView. */ @@ -306,7 +306,7 @@ interface RecentsPagedOrientationHandler : PagedOrientationHandler { deviceProfile: DeviceProfile, snapshotViewWidth: Int, snapshotViewHeight: Int, - banner: View + banner: View, ) /** @@ -322,7 +322,7 @@ interface RecentsPagedOrientationHandler : PagedOrientationHandler { deviceProfile: DeviceProfile, thumbnailViews: Array, desiredTaskId: Int, - banner: View + banner: View, ): Pair // The following are only used by TaskViewTouchHandler. @@ -342,6 +342,15 @@ interface RecentsPagedOrientationHandler : PagedOrientationHandler { /** @return Either 1 or -1, a factor to multiply by so the animation goes the correct way. */ fun getTaskDragDisplacementFactor(isRtl: Boolean): Int + /** @return Either 1 or -1, the direction sign towards task dismiss. */ + fun getTaskDismissVerticalDirection(): Int + + /** @return the length to drag a task off screen for dismiss. */ + fun getTaskDismissLength(secondaryDimension: Int, taskThumbnailBounds: Rect): Int + + /** @return the length to drag a task to full screen for launch. */ + fun getTaskLaunchLength(secondaryDimension: Int, taskThumbnailBounds: Rect): Int + /** * Maps the velocity from the coordinate plane of the foreground app to that of Launcher's * (which now will always be portrait) @@ -371,7 +380,7 @@ interface RecentsPagedOrientationHandler : PagedOrientationHandler { floatingTask: View, onScreenRect: RectF, @StagePosition stagePosition: Int, - dp: DeviceProfile + dp: DeviceProfile, ): Float /** diff --git a/quickstep/src/com/android/quickstep/orientation/SeascapePagedViewHandler.kt b/quickstep/src/com/android/quickstep/orientation/SeascapePagedViewHandler.kt index 7fea55d3d6..1f9f75290c 100644 --- a/quickstep/src/com/android/quickstep/orientation/SeascapePagedViewHandler.kt +++ b/quickstep/src/com/android/quickstep/orientation/SeascapePagedViewHandler.kt @@ -344,6 +344,14 @@ class SeascapePagedViewHandler : LandscapePagedViewHandler() { override fun getTaskDragDisplacementFactor(isRtl: Boolean): Int = if (isRtl) -1 else 1 + override fun getTaskDismissVerticalDirection(): Int = -1 + + override fun getTaskDismissLength(secondaryDimension: Int, taskThumbnailBounds: Rect): Int = + taskThumbnailBounds.right + + override fun getTaskLaunchLength(secondaryDimension: Int, taskThumbnailBounds: Rect): Int = + secondaryDimension - taskThumbnailBounds.right + /* -------------------- */ override fun getSplitIconsPosition( From ba7f9048be66257a979fbcc5f6ac9ab85553bc9d Mon Sep 17 00:00:00 2001 From: Schneider Victor-Tulias Date: Wed, 19 Feb 2025 16:21:53 -0500 Subject: [PATCH 131/153] Add aconfig flag for gesture nav handling on connected displays. Flag: EXEMPT adding the flag Bug: 382130680 Bug: 398881237 Test: ran launcher Change-Id: Ic39582bd2f20e7d2bbf15bd4c23ae11cf4d73182 --- aconfig/launcher.aconfig | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/aconfig/launcher.aconfig b/aconfig/launcher.aconfig index 4f5b1a03ef..cc746eb7ec 100644 --- a/aconfig/launcher.aconfig +++ b/aconfig/launcher.aconfig @@ -629,3 +629,10 @@ flag { description: "Enable Alt + Tab KQS view to show apps in flattened structure" bug: "382769617" } + +flag { + name: "enable_gesture_nav_on_connected_displays" + namespace: "lse_desktop_experience" + description: "Enables gesture navigation handling on connected displays" + bug: "382130680" +} From e9355c622d8d61a0e5a7bcd7d47576485196a033 Mon Sep 17 00:00:00 2001 From: Sunny Goyal Date: Wed, 26 Feb 2025 10:51:42 -0800 Subject: [PATCH 132/153] Removing unnecessary ActivityContextDelegate Bug: 393703968 Flag: EXEMPT refactor Test: Presubmit Change-Id: Ib95b26de000a2fe8204fdbc46c8a9da4f65c7eab --- src/com/android/launcher3/BaseActivity.java | 6 ++---- .../recyclerview/AllAppsRecyclerViewPool.kt | 11 ++++------- .../android/launcher3/views/ActivityContext.java | 16 ++-------------- 3 files changed, 8 insertions(+), 25 deletions(-) diff --git a/src/com/android/launcher3/BaseActivity.java b/src/com/android/launcher3/BaseActivity.java index 6277e41c14..84c80402b2 100644 --- a/src/com/android/launcher3/BaseActivity.java +++ b/src/com/android/launcher3/BaseActivity.java @@ -481,10 +481,8 @@ public abstract class BaseActivity extends Activity implements ActivityContext, public static T fromContext(Context context) { if (context instanceof BaseActivity) { return (T) context; - } else if (context instanceof ActivityContextDelegate) { - return (T) ((ActivityContextDelegate) context).mDelegate; - } else if (context instanceof ContextWrapper) { - return fromContext(((ContextWrapper) context).getBaseContext()); + } else if (context instanceof ContextWrapper cw) { + return fromContext(cw.getBaseContext()); } else { throw new IllegalArgumentException("Cannot find BaseActivity in parent tree"); } diff --git a/src/com/android/launcher3/recyclerview/AllAppsRecyclerViewPool.kt b/src/com/android/launcher3/recyclerview/AllAppsRecyclerViewPool.kt index e4c50f08b1..2d1a5f5a36 100644 --- a/src/com/android/launcher3/recyclerview/AllAppsRecyclerViewPool.kt +++ b/src/com/android/launcher3/recyclerview/AllAppsRecyclerViewPool.kt @@ -18,6 +18,7 @@ package com.android.launcher3.recyclerview import android.content.Context import android.util.Log +import android.view.ContextThemeWrapper import android.view.InflateException import androidx.annotation.VisibleForTesting import androidx.annotation.VisibleForTesting.Companion.PROTECTED @@ -33,8 +34,6 @@ import com.android.launcher3.util.Executors.MAIN_EXECUTOR import com.android.launcher3.util.Executors.VIEW_PREINFLATION_EXECUTOR import com.android.launcher3.util.Themes import com.android.launcher3.views.ActivityContext -import com.android.launcher3.views.ActivityContext.ActivityContextDelegate -import java.lang.IllegalStateException const val PREINFLATE_ICONS_ROW_COUNT = 4 const val EXTRA_ICONS_COUNT = 2 @@ -80,11 +79,9 @@ class AllAppsRecyclerViewPool : RecycledViewPool() where T : Context, T : Act // create a separate AssetManager obj internally to avoid lock contention with // AssetManager obj that is associated with the launcher context on the main thread. val allAppsPreInflationContext = - ActivityContextDelegate( - context.createConfigurationContext(context.resources.configuration), - Themes.getActivityThemeRes(context), - context, - ) + ContextThemeWrapper(context, Themes.getActivityThemeRes(context)).apply { + applyOverrideConfiguration(context.resources.configuration) + } // Because we perform onCreateViewHolder() on worker thread, we need a separate // adapter/inflator object as they are not thread-safe. Note that the adapter diff --git a/src/com/android/launcher3/views/ActivityContext.java b/src/com/android/launcher3/views/ActivityContext.java index 81968fce58..bbea043820 100644 --- a/src/com/android/launcher3/views/ActivityContext.java +++ b/src/com/android/launcher3/views/ActivityContext.java @@ -43,7 +43,6 @@ import android.os.IBinder; import android.os.Process; import android.os.UserHandle; import android.util.Log; -import android.view.ContextThemeWrapper; import android.view.Display; import android.view.LayoutInflater; import android.view.View; @@ -552,21 +551,10 @@ public interface ActivityContext { static T lookupContextNoThrow(Context context) { if (context instanceof ActivityContext) { return (T) context; - } else if (context instanceof ActivityContextDelegate acd) { - return (T) acd.mDelegate; - } else if (context instanceof ContextWrapper) { - return lookupContextNoThrow(((ContextWrapper) context).getBaseContext()); + } else if (context instanceof ContextWrapper cw) { + return lookupContextNoThrow(cw.getBaseContext()); } else { return null; } } - - class ActivityContextDelegate extends ContextThemeWrapper { - public final ActivityContext mDelegate; - - public ActivityContextDelegate(Context base, int themeResId, ActivityContext delegate) { - super(base, themeResId); - mDelegate = delegate; - } - } } From 1a39494c82b8f1cff9849157b587077e3ecd3a4d Mon Sep 17 00:00:00 2001 From: minch Date: Tue, 25 Feb 2025 16:40:54 +0000 Subject: [PATCH 133/153] Use MultiValueAlpha in ClearAllButton Bug: 389209338 Flag: EXEMPT refactor Test: m Change-Id: Ia6f3f9059444161829c76373b80b354a155fd69d --- .../uioverrides/RecentsViewStateController.kt | 5 +- .../FallbackRecentsStateController.java | 5 +- .../android/quickstep/views/ClearAllButton.kt | 75 ++++++++----------- .../android/quickstep/views/RecentsView.java | 4 +- 4 files changed, 39 insertions(+), 50 deletions(-) diff --git a/quickstep/src/com/android/launcher3/uioverrides/RecentsViewStateController.kt b/quickstep/src/com/android/launcher3/uioverrides/RecentsViewStateController.kt index 04e1905578..b230fa6ed4 100644 --- a/quickstep/src/com/android/launcher3/uioverrides/RecentsViewStateController.kt +++ b/quickstep/src/com/android/launcher3/uioverrides/RecentsViewStateController.kt @@ -38,7 +38,6 @@ import com.android.launcher3.states.StateAnimationConfig.ANIM_OVERVIEW_TRANSLATE import com.android.launcher3.states.StateAnimationConfig.SKIP_OVERVIEW import com.android.launcher3.util.MultiPropertyFactory.MULTI_PROPERTY_VALUE import com.android.quickstep.util.AnimUtils -import com.android.quickstep.views.ClearAllButton import com.android.quickstep.views.RecentsView import com.android.quickstep.views.RecentsView.ADJACENT_PAGE_HORIZONTAL_OFFSET import com.android.quickstep.views.RecentsView.CONTENT_ALPHA @@ -288,8 +287,8 @@ class RecentsViewStateController(private val launcher: QuickstepLauncher) : val clearAllButtonAlpha = if (state.areElementsVisible(launcher, LauncherState.CLEAR_ALL_BUTTON)) 1f else 0f propertySetter.setFloat( - recentsView.clearAllButton, - ClearAllButton.VISIBILITY_ALPHA, + recentsView.clearAllButton.visibilityAlphaProperty, + MULTI_PROPERTY_VALUE, clearAllButtonAlpha, LINEAR, ) diff --git a/quickstep/src/com/android/quickstep/fallback/FallbackRecentsStateController.java b/quickstep/src/com/android/quickstep/fallback/FallbackRecentsStateController.java index 537092f8f4..51f2a33529 100644 --- a/quickstep/src/com/android/quickstep/fallback/FallbackRecentsStateController.java +++ b/quickstep/src/com/android/quickstep/fallback/FallbackRecentsStateController.java @@ -52,7 +52,6 @@ import com.android.launcher3.anim.PendingAnimation; import com.android.launcher3.anim.PropertySetter; import com.android.launcher3.statemanager.StateManager.StateHandler; import com.android.launcher3.states.StateAnimationConfig; -import com.android.quickstep.views.ClearAllButton; import com.android.quickstep.views.RecentsView; import com.android.quickstep.views.RecentsViewContainer; @@ -98,8 +97,8 @@ public class FallbackRecentsStateController implements StateHandler= 1f + } } - var contentAlpha = 1f + var scrollAlpha set(value) { - field = value - updateAlpha() + clearAllButtonAlpha.get(Alpha.SCROLL.ordinal).value = value } + get() = clearAllButtonAlpha.get(Alpha.SCROLL.ordinal).value - var visibilityAlpha = 1f + var contentAlpha set(value) { - field = value - updateAlpha() + clearAllButtonAlpha.get(Alpha.CONTENT.ordinal).value = value } + get() = clearAllButtonAlpha.get(Alpha.CONTENT.ordinal).value - var dismissAlpha = 1f + @JvmField + val visibilityAlphaProperty: MultiPropertyFactory.MultiProperty = + clearAllButtonAlpha.get(Alpha.VISIBILITY.ordinal) + + var dismissAlpha set(value) { - field = value - updateAlpha() + dismissAlphaProperty.value = value } + get() = dismissAlphaProperty.value + + @JvmField + val dismissAlphaProperty: MultiPropertyFactory.MultiProperty = + clearAllButtonAlpha.get(Alpha.DISMISS.ordinal) var fullscreenProgress = 1f set(value) { @@ -198,12 +217,6 @@ class ClearAllButton @JvmOverloads constructor(context: Context, attrs: Attribut ) } - private fun updateAlpha() { - val alpha = scrollAlpha * contentAlpha * visibilityAlpha * dismissAlpha - this.alpha = alpha - isClickable = alpha >= 1f - } - fun getScrollAdjustment(fullscreenEnabled: Boolean, gridEnabled: Boolean): Float { var scrollAdjustment = 0f if (fullscreenEnabled) { @@ -244,26 +257,4 @@ class ClearAllButton @JvmOverloads constructor(context: Context, attrs: Attribut if (fullscreenProgress > 0) endTranslation else 0f private fun getGridTrans(endTranslation: Float) = if (gridProgress > 0) endTranslation else 0f - - companion object { - @JvmField - val VISIBILITY_ALPHA: FloatProperty = - object : FloatProperty("visibilityAlpha") { - override fun setValue(clearAllButton: ClearAllButton, value: Float) { - clearAllButton.visibilityAlpha = value - } - - override fun get(clearAllButton: ClearAllButton) = clearAllButton.visibilityAlpha - } - - @JvmField - val DISMISS_ALPHA: FloatProperty = - object : FloatProperty("dismissAlpha") { - override fun setValue(clearAllButton: ClearAllButton, value: Float) { - clearAllButton.dismissAlpha = value - } - - override fun get(clearAllButton: ClearAllButton) = clearAllButton.dismissAlpha - } - } } diff --git a/quickstep/src/com/android/quickstep/views/RecentsView.java b/quickstep/src/com/android/quickstep/views/RecentsView.java index 6b91df1b95..983c393256 100644 --- a/quickstep/src/com/android/quickstep/views/RecentsView.java +++ b/quickstep/src/com/android/quickstep/views/RecentsView.java @@ -66,7 +66,6 @@ import static com.android.launcher3.util.SystemUiController.UI_STATE_FULLSCREEN_ import static com.android.quickstep.BaseContainerInterface.getTaskDimension; import static com.android.quickstep.TaskUtils.checkCurrentOrManagedUserId; import static com.android.quickstep.util.LogUtils.splitFailureMessage; -import static com.android.quickstep.views.ClearAllButton.DISMISS_ALPHA; import static com.android.quickstep.views.OverviewActionsView.HIDDEN_ACTIONS_IN_MENU; import static com.android.quickstep.views.OverviewActionsView.HIDDEN_DESKTOP; import static com.android.quickstep.views.OverviewActionsView.HIDDEN_NON_ZERO_ROTATION; @@ -3962,7 +3961,8 @@ public abstract class RecentsView< // Change alpha of clear all if translating grid to hide it if (isClearAllHidden) { - anim.setFloat(mClearAllButton, DISMISS_ALPHA, 0, LINEAR); + anim.setFloat(mClearAllButton.dismissAlphaProperty, MULTI_PROPERTY_VALUE, 0, + LINEAR); anim.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { From b8d4758d4ea7721af2ccc2c6aa26550d86db82ad Mon Sep 17 00:00:00 2001 From: minch Date: Mon, 24 Feb 2025 22:55:59 +0000 Subject: [PATCH 134/153] Let TaskView allow empty TaskContainers Bug: 391918297 Flag: EXEMPT refactor Test: m Change-Id: Ia12c01746e6b31ac980c367f1c0144e69765f2a5 --- .../src/com/android/quickstep/util/SplitAnimationController.kt | 2 +- quickstep/src/com/android/quickstep/views/TaskView.kt | 2 +- .../com/android/quickstep/util/SplitAnimationControllerTest.kt | 1 + 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/quickstep/src/com/android/quickstep/util/SplitAnimationController.kt b/quickstep/src/com/android/quickstep/util/SplitAnimationController.kt index a9dbbf2022..96a5733a46 100644 --- a/quickstep/src/com/android/quickstep/util/SplitAnimationController.kt +++ b/quickstep/src/com/android/quickstep/util/SplitAnimationController.kt @@ -143,7 +143,7 @@ class SplitAnimationController(val splitSelectStateController: SplitSelectStateC } else { // Initiating split from overview on fullscreen task TaskView val taskView = taskViewSupplier.get() - taskView.taskContainers.first().let { + taskView.firstTaskContainer!!.let { val drawable = getDrawable(it.iconView, splitSelectSource) return SplitAnimInitProps( it.snapshotView, diff --git a/quickstep/src/com/android/quickstep/views/TaskView.kt b/quickstep/src/com/android/quickstep/views/TaskView.kt index 0e5382a235..7544c3b33b 100644 --- a/quickstep/src/com/android/quickstep/views/TaskView.kt +++ b/quickstep/src/com/android/quickstep/views/TaskView.kt @@ -301,7 +301,7 @@ constructor( var sysUiStatusNavFlags: Int = 0 get() = if (enableRefactorTaskThumbnail()) field - else taskContainers.first().thumbnailViewDeprecated.sysUiStatusNavFlags + else firstTaskContainer?.thumbnailViewDeprecated?.sysUiStatusNavFlags ?: 0 private set // Various animation progress variables. diff --git a/quickstep/tests/multivalentTests/src/com/android/quickstep/util/SplitAnimationControllerTest.kt b/quickstep/tests/multivalentTests/src/com/android/quickstep/util/SplitAnimationControllerTest.kt index 9d000a4687..c9d7e1dee9 100644 --- a/quickstep/tests/multivalentTests/src/com/android/quickstep/util/SplitAnimationControllerTest.kt +++ b/quickstep/tests/multivalentTests/src/com/android/quickstep/util/SplitAnimationControllerTest.kt @@ -94,6 +94,7 @@ class SplitAnimationControllerTest { whenever(mockTaskContainer.task).thenReturn(mockTask) whenever(mockIconView.drawable).thenReturn(mockTaskViewDrawable) whenever(mockTaskView.taskContainers).thenReturn(List(1) { mockTaskContainer }) + whenever(mockTaskView.firstTaskContainer).thenReturn(mockTaskContainer) whenever(splitSelectSource.drawable).thenReturn(mockSplitSourceDrawable) whenever(splitSelectSource.view).thenReturn(mockSplitSourceView) From e6065f5a944b7273296b7fbcda566618151dbf3e Mon Sep 17 00:00:00 2001 From: Anushree Ganjam Date: Tue, 25 Feb 2025 16:02:56 -0800 Subject: [PATCH 135/153] Move MainThreadInitializedObject to Launcher3 Go. Move SandboxContext to a separate class. Remove all MainThreadInitializedObject references in Launcher3 and tests. Remove ObjectSandbox interface and make RoboApplication extend SandboxContext Bug: 361850561 Test: Presubmit Flag: EXEMPT dagger Change-Id: I1a8af5e6ae59df44d8ad6732b4d6e949ac402d6c --- .../util/MainThreadInitializedObject.java | 71 ++++++ .../taskbar/TaskbarViewController.java | 2 +- .../launcher3/model/AppEventProducerTest.java | 2 +- .../model/data/TaskViewItemInfoTest.kt | 2 +- .../taskbar/rules/TaskbarModeRule.kt | 5 +- .../rules/TaskbarWindowSandboxContext.kt | 3 +- .../NavHandleLongPressInputConsumerTest.java | 2 +- .../graphics/LauncherPreviewRenderer.java | 2 +- .../launcher3/util/DaggerSingletonObject.java | 3 +- .../util/DaggerSingletonTracker.java | 2 +- .../util/MainThreadInitializedObject.java | 214 ------------------ .../android/launcher3/util/SandboxContext.kt | 56 +++++ .../launcher3/AbstractDeviceProfileTest.kt | 2 +- .../launcher3/util/LauncherModelHelper.java | 1 - .../launcher3/util/SandboxApplication.kt | 3 +- .../launcher3/util/SandboxApplicationTest.kt | 13 -- .../util/TestSandboxModelContextWrapper.java | 4 +- 17 files changed, 140 insertions(+), 247 deletions(-) create mode 100644 go/quickstep/src/com/android/launcher3/util/MainThreadInitializedObject.java delete mode 100644 src/com/android/launcher3/util/MainThreadInitializedObject.java create mode 100644 src/com/android/launcher3/util/SandboxContext.kt diff --git a/go/quickstep/src/com/android/launcher3/util/MainThreadInitializedObject.java b/go/quickstep/src/com/android/launcher3/util/MainThreadInitializedObject.java new file mode 100644 index 0000000000..e1f3508018 --- /dev/null +++ b/go/quickstep/src/com/android/launcher3/util/MainThreadInitializedObject.java @@ -0,0 +1,71 @@ +/* + * Copyright (C) 2018 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.launcher3.util; + +import static com.android.launcher3.util.Executors.MAIN_EXECUTOR; + +import android.content.Context; +import android.os.Looper; + +import java.util.concurrent.ExecutionException; + +/** + * Utility class for defining singletons which are initiated on main thread. + */ +public class MainThreadInitializedObject { + + private final ObjectProvider mProvider; + private T mValue; + + public MainThreadInitializedObject(ObjectProvider provider) { + mProvider = provider; + } + + public T get(Context context) { + Context app = context.getApplicationContext(); + if (app instanceof ObjectSandbox sc) { + return sc.getObject(this); + } + + if (mValue == null) { + if (Looper.myLooper() == Looper.getMainLooper()) { + mValue = TraceHelper.allowIpcs("main.thread.object", () -> mProvider.get(app)); + } else { + try { + return MAIN_EXECUTOR.submit(() -> get(context)).get(); + } catch (InterruptedException | ExecutionException e) { + throw new RuntimeException(e); + } + } + } + return mValue; + } + + public interface ObjectProvider { + + T get(Context context); + } + + /** Sandbox for isolating {@link MainThreadInitializedObject} instances from Launcher. */ + public interface ObjectSandbox { + + /** + * Find a cached object from mObjectMap if we have already created one. If not, generate + * an object using the provider. + */ + T getObject(MainThreadInitializedObject object); + } +} diff --git a/quickstep/src/com/android/launcher3/taskbar/TaskbarViewController.java b/quickstep/src/com/android/launcher3/taskbar/TaskbarViewController.java index 384468c9fc..8cb6cd30b6 100644 --- a/quickstep/src/com/android/launcher3/taskbar/TaskbarViewController.java +++ b/quickstep/src/com/android/launcher3/taskbar/TaskbarViewController.java @@ -86,11 +86,11 @@ import com.android.launcher3.taskbar.bubbles.BubbleControllers; import com.android.launcher3.util.DisplayController; import com.android.launcher3.util.ItemInfoMatcher; import com.android.launcher3.util.LauncherBindableItemsContainer; -import com.android.launcher3.util.MainThreadInitializedObject.SandboxContext; import com.android.launcher3.util.MultiPropertyFactory; import com.android.launcher3.util.MultiPropertyFactory.MultiProperty; import com.android.launcher3.util.MultiTranslateDelegate; import com.android.launcher3.util.MultiValueAlpha; +import com.android.launcher3.util.SandboxContext; import com.android.quickstep.util.GroupTask; import com.android.quickstep.util.SingleTask; import com.android.systemui.shared.recents.model.Task; diff --git a/quickstep/tests/multivalentTests/src/com/android/launcher3/model/AppEventProducerTest.java b/quickstep/tests/multivalentTests/src/com/android/launcher3/model/AppEventProducerTest.java index 06a939a06d..91f9e53eaa 100644 --- a/quickstep/tests/multivalentTests/src/com/android/launcher3/model/AppEventProducerTest.java +++ b/quickstep/tests/multivalentTests/src/com/android/launcher3/model/AppEventProducerTest.java @@ -41,7 +41,7 @@ import com.android.launcher3.logger.LauncherAtom; import com.android.launcher3.model.data.AppInfo; import com.android.launcher3.pm.UserCache; import com.android.launcher3.util.AllModulesForTest; -import com.android.launcher3.util.MainThreadInitializedObject.SandboxContext; +import com.android.launcher3.util.SandboxContext; import com.android.launcher3.util.UserIconInfo; import com.android.systemui.shared.system.SysUiStatsLog; diff --git a/quickstep/tests/multivalentTests/src/com/android/launcher3/model/data/TaskViewItemInfoTest.kt b/quickstep/tests/multivalentTests/src/com/android/launcher3/model/data/TaskViewItemInfoTest.kt index adfbca567d..8d20ba8e7f 100644 --- a/quickstep/tests/multivalentTests/src/com/android/launcher3/model/data/TaskViewItemInfoTest.kt +++ b/quickstep/tests/multivalentTests/src/com/android/launcher3/model/data/TaskViewItemInfoTest.kt @@ -28,7 +28,7 @@ import com.android.launcher3.model.data.ItemInfoWithIcon.FLAG_NOT_PINNABLE import com.android.launcher3.model.data.TaskViewItemInfo.Companion.createTaskViewAtom import com.android.launcher3.pm.UserCache import com.android.launcher3.util.AllModulesForTest -import com.android.launcher3.util.MainThreadInitializedObject.SandboxContext +import com.android.launcher3.util.SandboxContext import com.android.launcher3.util.SplitConfigurationOptions import com.android.launcher3.util.TransformingTouchDelegate import com.android.launcher3.util.UserIconInfo diff --git a/quickstep/tests/multivalentTests/src/com/android/launcher3/taskbar/rules/TaskbarModeRule.kt b/quickstep/tests/multivalentTests/src/com/android/launcher3/taskbar/rules/TaskbarModeRule.kt index 3cf912c8e3..f22580719f 100644 --- a/quickstep/tests/multivalentTests/src/com/android/launcher3/taskbar/rules/TaskbarModeRule.kt +++ b/quickstep/tests/multivalentTests/src/com/android/launcher3/taskbar/rules/TaskbarModeRule.kt @@ -20,7 +20,6 @@ import androidx.test.platform.app.InstrumentationRegistry.getInstrumentation import com.android.launcher3.taskbar.rules.TaskbarModeRule.Mode import com.android.launcher3.taskbar.rules.TaskbarModeRule.TaskbarMode import com.android.launcher3.util.DisplayController -import com.android.launcher3.util.MainThreadInitializedObject import com.android.launcher3.util.NavigationMode import org.junit.rules.TestRule import org.junit.runner.Description @@ -31,8 +30,8 @@ import org.mockito.kotlin.spy /** * Allows tests to specify which Taskbar [Mode] to run under. * - * [context] should match the test's target context, so that [MainThreadInitializedObject] instances - * are properly sandboxed. + * [context] should match the test's target context, so that Dagger singleton instances are properly + * sandboxed. * * Annotate tests with [TaskbarMode] to set a mode. If the annotation is omitted for any tests, this * rule is a no-op. diff --git a/quickstep/tests/multivalentTests/src/com/android/launcher3/taskbar/rules/TaskbarWindowSandboxContext.kt b/quickstep/tests/multivalentTests/src/com/android/launcher3/taskbar/rules/TaskbarWindowSandboxContext.kt index e6806b70bf..6d53e8e312 100644 --- a/quickstep/tests/multivalentTests/src/com/android/launcher3/taskbar/rules/TaskbarWindowSandboxContext.kt +++ b/quickstep/tests/multivalentTests/src/com/android/launcher3/taskbar/rules/TaskbarWindowSandboxContext.kt @@ -30,7 +30,6 @@ import com.android.launcher3.util.AllModulesMinusWMProxy import com.android.launcher3.util.DaggerSingletonTracker import com.android.launcher3.util.DisplayController import com.android.launcher3.util.FakePrefsModule -import com.android.launcher3.util.MainThreadInitializedObject.ObjectSandbox import com.android.launcher3.util.SandboxApplication import com.android.launcher3.util.SettingsCache import com.android.launcher3.util.SettingsCacheSandbox @@ -58,7 +57,7 @@ private constructor( private val base: SandboxApplication, val virtualDisplay: VirtualDisplay, private val params: SandboxParams, -) : ContextWrapper(base), ObjectSandbox by base, TestRule { +) : ContextWrapper(base), TestRule { val settingsCacheSandbox = SettingsCacheSandbox() diff --git a/quickstep/tests/multivalentTests/src/com/android/quickstep/inputconsumers/NavHandleLongPressInputConsumerTest.java b/quickstep/tests/multivalentTests/src/com/android/quickstep/inputconsumers/NavHandleLongPressInputConsumerTest.java index 99a34ea69c..b3056f5c46 100644 --- a/quickstep/tests/multivalentTests/src/com/android/quickstep/inputconsumers/NavHandleLongPressInputConsumerTest.java +++ b/quickstep/tests/multivalentTests/src/com/android/quickstep/inputconsumers/NavHandleLongPressInputConsumerTest.java @@ -55,7 +55,7 @@ import com.android.launcher3.dagger.LauncherAppSingleton; import com.android.launcher3.logging.StatsLogManager; import com.android.launcher3.util.AllModulesForTest; import com.android.launcher3.util.DisplayController; -import com.android.launcher3.util.MainThreadInitializedObject.SandboxContext; +import com.android.launcher3.util.SandboxContext; import com.android.quickstep.DeviceConfigWrapper; import com.android.quickstep.GestureState; import com.android.quickstep.InputConsumer; diff --git a/src/com/android/launcher3/graphics/LauncherPreviewRenderer.java b/src/com/android/launcher3/graphics/LauncherPreviewRenderer.java index 740b87b02e..3836f7d3ac 100644 --- a/src/com/android/launcher3/graphics/LauncherPreviewRenderer.java +++ b/src/com/android/launcher3/graphics/LauncherPreviewRenderer.java @@ -94,7 +94,7 @@ import com.android.launcher3.util.ComponentKey; import com.android.launcher3.util.DisplayController; import com.android.launcher3.util.IntArray; import com.android.launcher3.util.IntSet; -import com.android.launcher3.util.MainThreadInitializedObject.SandboxContext; +import com.android.launcher3.util.SandboxContext; import com.android.launcher3.util.WindowBounds; import com.android.launcher3.util.window.WindowManagerProxy; import com.android.launcher3.views.ActivityContext; diff --git a/src/com/android/launcher3/util/DaggerSingletonObject.java b/src/com/android/launcher3/util/DaggerSingletonObject.java index a245761fb7..a4bd30a193 100644 --- a/src/com/android/launcher3/util/DaggerSingletonObject.java +++ b/src/com/android/launcher3/util/DaggerSingletonObject.java @@ -24,8 +24,7 @@ import com.android.launcher3.dagger.LauncherComponentProvider; import java.util.function.Function; /** - * A class to provide DaggerSingleton objects in a traditional way for - * {@link MainThreadInitializedObject}. + * A class to provide DaggerSingleton objects in a traditional way. * We should delete this class at the end and use @Inject to get dagger provided singletons. */ diff --git a/src/com/android/launcher3/util/DaggerSingletonTracker.java b/src/com/android/launcher3/util/DaggerSingletonTracker.java index b7a88dbf44..34b376091e 100644 --- a/src/com/android/launcher3/util/DaggerSingletonTracker.java +++ b/src/com/android/launcher3/util/DaggerSingletonTracker.java @@ -45,7 +45,7 @@ public class DaggerSingletonTracker implements SafeCloseable { * Adds the SafeCloseable Singletons to the mLauncherAppSingletons list. * This helps to track the singletons and close them appropriately. * See {@link DaggerSingletonTracker#close()} and - * {@link MainThreadInitializedObject.SandboxContext#onDestroy()} + * {@link SandboxContext#onDestroy()} */ public void addCloseable(SafeCloseable closeable) { MAIN_EXECUTOR.execute(() -> { diff --git a/src/com/android/launcher3/util/MainThreadInitializedObject.java b/src/com/android/launcher3/util/MainThreadInitializedObject.java deleted file mode 100644 index 356a5517e2..0000000000 --- a/src/com/android/launcher3/util/MainThreadInitializedObject.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * Copyright (C) 2018 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.launcher3.util; - -import static com.android.launcher3.util.Executors.MAIN_EXECUTOR; - -import android.content.Context; -import android.os.Looper; -import android.util.Log; - -import androidx.annotation.UiThread; -import androidx.annotation.VisibleForTesting; - -import com.android.launcher3.LauncherApplication; -import com.android.launcher3.util.ResourceBasedOverride.Overrides; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.ExecutionException; -import java.util.function.Consumer; - -/** - * Utility class for defining singletons which are initiated on main thread. - * - * TODO(b/361850561): Do not delete MainThreadInitializedObject until we find a way to - * unregister and understand how singleton objects are destroyed in dagger graph. - */ -public class MainThreadInitializedObject { - - private final ObjectProvider mProvider; - private T mValue; - - public MainThreadInitializedObject(ObjectProvider provider) { - mProvider = provider; - } - - public T get(Context context) { - Context app = context.getApplicationContext(); - if (app instanceof ObjectSandbox sc) { - return sc.getObject(this); - } - - if (mValue == null) { - if (Looper.myLooper() == Looper.getMainLooper()) { - mValue = TraceHelper.allowIpcs("main.thread.object", () -> mProvider.get(app)); - } else { - try { - return MAIN_EXECUTOR.submit(() -> get(context)).get(); - } catch (InterruptedException|ExecutionException e) { - throw new RuntimeException(e); - } - } - } - return mValue; - } - - /** - * Executes the callback is the value is already created - * @return true if the callback was executed, false otherwise - */ - public boolean executeIfCreated(Consumer callback) { - T v = mValue; - if (v != null) { - callback.accept(v); - return true; - } else { - return false; - } - } - - @VisibleForTesting - public void initializeForTesting(T value) { - mValue = value; - } - - /** - * Initializes a provider based on resource overrides - */ - public static MainThreadInitializedObject - forOverride(Class clazz, int resourceId) { - return new MainThreadInitializedObject<>(c -> Overrides.getObject(clazz, c, resourceId)); - } - - public interface ObjectProvider { - - T get(Context context); - } - - /** Sandbox for isolating {@link MainThreadInitializedObject} instances from Launcher. */ - public interface ObjectSandbox { - - /** - * Find a cached object from mObjectMap if we have already created one. If not, generate - * an object using the provider. - */ - T getObject(MainThreadInitializedObject object); - - - /** - * Put a value into cache, can be used to put mocked MainThreadInitializedObject - * instances. - */ - void putObject(MainThreadInitializedObject object, T value); - - /** - * Returns whether this sandbox should cleanup all objects when its destroyed or leave it - * to the GC. - * These objects can have listeners attached to the system server and mey not be able to get - * GCed themselves when running on a device. - * Some environments like Robolectric tear down the whole system at the end of the test, - * so manual cleanup may not be required. - */ - default boolean shouldCleanUpOnDestroy() { - return true; - } - - @UiThread - default T createObject(MainThreadInitializedObject object) { - return object.mProvider.get((Context) this); - } - } - - /** - * Abstract Context which allows custom implementations for - * {@link MainThreadInitializedObject} providers - */ - public static class SandboxContext extends LauncherApplication implements ObjectSandbox { - - private static final String TAG = "SandboxContext"; - - private final Map mObjectMap = new HashMap<>(); - private final ArrayList mOrderedObjects = new ArrayList<>(); - - private final Object mDestroyLock = new Object(); - private boolean mDestroyed = false; - - public SandboxContext(Context base) { - attachBaseContext(base); - } - - @Override - public Context getApplicationContext() { - return this; - } - - @Override - public boolean shouldCleanUpOnDestroy() { - return (getBaseContext().getApplicationContext() instanceof ObjectSandbox os) - ? os.shouldCleanUpOnDestroy() : true; - } - - public void onDestroy() { - if (shouldCleanUpOnDestroy()) { - cleanUpObjects(); - } - } - - protected void cleanUpObjects() { - getAppComponent().getDaggerSingletonTracker().close(); - synchronized (mDestroyLock) { - // Destroy in reverse order - for (int i = mOrderedObjects.size() - 1; i >= 0; i--) { - mOrderedObjects.get(i).close(); - } - mDestroyed = true; - } - } - - @Override - public T getObject(MainThreadInitializedObject object) { - synchronized (mDestroyLock) { - if (mDestroyed) { - Log.e(TAG, "Static object access with a destroyed context"); - } - T t = (T) mObjectMap.get(object); - if (t != null) { - return t; - } - if (Looper.myLooper() == Looper.getMainLooper()) { - t = createObject(object); - mObjectMap.put(object, t); - mOrderedObjects.add(t); - return t; - } - } - - try { - return MAIN_EXECUTOR.submit(() -> getObject(object)).get(); - } catch (InterruptedException | ExecutionException e) { - throw new RuntimeException(e); - } - } - - @Override - public void putObject( - MainThreadInitializedObject object, T value) { - mObjectMap.put(object, value); - } - } -} diff --git a/src/com/android/launcher3/util/SandboxContext.kt b/src/com/android/launcher3/util/SandboxContext.kt new file mode 100644 index 0000000000..c6224e2327 --- /dev/null +++ b/src/com/android/launcher3/util/SandboxContext.kt @@ -0,0 +1,56 @@ +/* + * 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.launcher3.util + +import android.content.Context +import com.android.launcher3.LauncherApplication + +/** Abstract Context which allows custom implementations for dagger components. */ +open class SandboxContext(base: Context?) : LauncherApplication() { + init { + base?.let { attachBaseContext(it) } + } + + override fun getApplicationContext(): Context { + return this + } + + /** + * Returns whether this sandbox should cleanup all objects when its destroyed or leave it to the + * GC. These objects can have listeners attached to the system server and mey not be able to get + * GCed themselves when running on a device. Some environments like Robolectric tear down the + * whole system at the end of the test, so manual cleanup may not be required. + */ + open fun shouldCleanUpOnDestroy(): Boolean { + return (getBaseContext().getApplicationContext() as? SandboxContext) + ?.shouldCleanUpOnDestroy() ?: true + } + + fun onDestroy() { + if (shouldCleanUpOnDestroy()) { + cleanUpObjects() + } + } + + open protected fun cleanUpObjects() { + appComponent.daggerSingletonTracker.close() + } + + companion object { + private const val TAG = "SandboxContext" + } +} diff --git a/tests/multivalentTests/src/com/android/launcher3/AbstractDeviceProfileTest.kt b/tests/multivalentTests/src/com/android/launcher3/AbstractDeviceProfileTest.kt index 3658989384..ad6afcf1ac 100644 --- a/tests/multivalentTests/src/com/android/launcher3/AbstractDeviceProfileTest.kt +++ b/tests/multivalentTests/src/com/android/launcher3/AbstractDeviceProfileTest.kt @@ -35,8 +35,8 @@ import com.android.launcher3.testing.shared.ResourceUtils import com.android.launcher3.util.AllModulesMinusWMProxy import com.android.launcher3.util.DisplayController import com.android.launcher3.util.FakePrefsModule -import com.android.launcher3.util.MainThreadInitializedObject.SandboxContext import com.android.launcher3.util.NavigationMode +import com.android.launcher3.util.SandboxContext import com.android.launcher3.util.WindowBounds import com.android.launcher3.util.rule.TestStabilityRule import com.android.launcher3.util.rule.setFlags diff --git a/tests/multivalentTests/src/com/android/launcher3/util/LauncherModelHelper.java b/tests/multivalentTests/src/com/android/launcher3/util/LauncherModelHelper.java index cee5559c39..4458e8fb01 100644 --- a/tests/multivalentTests/src/com/android/launcher3/util/LauncherModelHelper.java +++ b/tests/multivalentTests/src/com/android/launcher3/util/LauncherModelHelper.java @@ -56,7 +56,6 @@ import com.android.launcher3.model.BgDataModel; import com.android.launcher3.model.BgDataModel.Callbacks; import com.android.launcher3.model.ModelDbController; import com.android.launcher3.testing.TestInformationProvider; -import com.android.launcher3.util.MainThreadInitializedObject.SandboxContext; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; diff --git a/tests/multivalentTests/src/com/android/launcher3/util/SandboxApplication.kt b/tests/multivalentTests/src/com/android/launcher3/util/SandboxApplication.kt index 0da8891e47..2fa4cad61d 100644 --- a/tests/multivalentTests/src/com/android/launcher3/util/SandboxApplication.kt +++ b/tests/multivalentTests/src/com/android/launcher3/util/SandboxApplication.kt @@ -27,7 +27,6 @@ import android.os.UserHandle import android.view.Display import androidx.test.core.app.ApplicationProvider import com.android.launcher3.util.LauncherModelHelper.SandboxModelContext -import com.android.launcher3.util.MainThreadInitializedObject.ObjectSandbox import org.junit.Rule import org.junit.rules.ExternalResource import org.junit.rules.TestRule @@ -69,7 +68,7 @@ class SandboxApplication private constructor(private val base: SandboxApplicatio // Defer to the true application to decide whether to clean up. For instance, we do not want // to cleanup under Robolectric. val app = ApplicationProvider.getApplicationContext() - return if (app is ObjectSandbox) app.shouldCleanUpOnDestroy() else true + return (app as? SandboxContext)?.shouldCleanUpOnDestroy() ?: true } override fun apply(statement: Statement, description: Description): Statement { diff --git a/tests/multivalentTests/src/com/android/launcher3/util/SandboxApplicationTest.kt b/tests/multivalentTests/src/com/android/launcher3/util/SandboxApplicationTest.kt index d87a4063ec..8a21cff6a7 100644 --- a/tests/multivalentTests/src/com/android/launcher3/util/SandboxApplicationTest.kt +++ b/tests/multivalentTests/src/com/android/launcher3/util/SandboxApplicationTest.kt @@ -16,7 +16,6 @@ package com.android.launcher3.util -import android.content.Context import android.hardware.display.DisplayManager import android.view.Display import android.view.Display.DEFAULT_DISPLAY @@ -63,16 +62,4 @@ class SandboxApplicationTest { onDestroy() } } - - @Test - fun testGetObject_objectCreatesDisplayContext_isSandboxed() { - class TestSingleton(context: Context) : SafeCloseable { - override fun close() = Unit - - val displayContext = context.createDisplayContext(display) - } - - val displayContext = MainThreadInitializedObject { TestSingleton(it) }[app].displayContext - assertThat(displayContext.applicationContext).isEqualTo(app) - } } diff --git a/tests/multivalentTests/src/com/android/launcher3/util/TestSandboxModelContextWrapper.java b/tests/multivalentTests/src/com/android/launcher3/util/TestSandboxModelContextWrapper.java index 393282f442..98d067c86a 100644 --- a/tests/multivalentTests/src/com/android/launcher3/util/TestSandboxModelContextWrapper.java +++ b/tests/multivalentTests/src/com/android/launcher3/util/TestSandboxModelContextWrapper.java @@ -18,8 +18,6 @@ package com.android.launcher3.util; import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation; -import static com.android.launcher3.util.MainThreadInitializedObject.SandboxContext; - import android.content.ContextWrapper; import androidx.annotation.Nullable; @@ -44,7 +42,7 @@ import java.util.concurrent.CountDownLatch; * There are 2 constructors in this class. The base context can be {@link SandboxContext} or * Instrumentation target context. * Using {@link SandboxContext} as base context allows custom implementations for - * MainThreadInitializedObject providers. + * providing objects in Dagger components. */ public class TestSandboxModelContextWrapper extends ActivityContextWrapper implements From 3c3d636dc938b6b03ff9703fdd0ad6493c29fcd7 Mon Sep 17 00:00:00 2001 From: Alex Chau Date: Wed, 26 Feb 2025 22:57:26 +0000 Subject: [PATCH 136/153] Multi property refactor - Introduced MultiPropertyDelegate to delegate Kotlin var to MultipPropertyFactory, allowing easy creation of var for MultiPropertyFactory - Introduced KFloatProperty to map any Kotlin var to a FloatProperty, which simplify the code to creaet FloatProperty a lot - Combined the above to refactor usage of MultipPropertyFactory, use var to simplfiy things, and expose them as FloatProperty directly when needed Fix: 399635468 Test: Smoke test main flow of enter Overview, task launching etc. Test: presubmit Flag: EXEMPT REFACTOR Change-Id: Ie7dd8b69da7e3bda9026a0ef7b0377c26a78a332 --- .../uioverrides/RecentsViewStateController.kt | 11 +- .../FallbackRecentsStateController.java | 11 +- .../quickstep/views/AddDesktopButton.kt | 57 +++--- .../android/quickstep/views/ClearAllButton.kt | 59 +++--- .../android/quickstep/views/RecentsView.java | 8 +- .../quickstep/views/RecentsViewUtils.kt | 20 +- .../com/android/quickstep/views/TaskView.kt | 173 +++++------------- .../android/launcher3/util/KFloatProperty.kt | 30 +++ .../launcher3/util/MultiPropertyDelegate.kt | 30 +++ 9 files changed, 185 insertions(+), 214 deletions(-) create mode 100644 src/com/android/launcher3/util/KFloatProperty.kt create mode 100644 src/com/android/launcher3/util/MultiPropertyDelegate.kt diff --git a/quickstep/src/com/android/launcher3/uioverrides/RecentsViewStateController.kt b/quickstep/src/com/android/launcher3/uioverrides/RecentsViewStateController.kt index b230fa6ed4..79328df325 100644 --- a/quickstep/src/com/android/launcher3/uioverrides/RecentsViewStateController.kt +++ b/quickstep/src/com/android/launcher3/uioverrides/RecentsViewStateController.kt @@ -36,8 +36,9 @@ import com.android.launcher3.states.StateAnimationConfig.ANIM_OVERVIEW_SCALE import com.android.launcher3.states.StateAnimationConfig.ANIM_OVERVIEW_TRANSLATE_X import com.android.launcher3.states.StateAnimationConfig.ANIM_OVERVIEW_TRANSLATE_Y import com.android.launcher3.states.StateAnimationConfig.SKIP_OVERVIEW -import com.android.launcher3.util.MultiPropertyFactory.MULTI_PROPERTY_VALUE import com.android.quickstep.util.AnimUtils +import com.android.quickstep.views.AddDesktopButton +import com.android.quickstep.views.ClearAllButton import com.android.quickstep.views.RecentsView import com.android.quickstep.views.RecentsView.ADJACENT_PAGE_HORIZONTAL_OFFSET import com.android.quickstep.views.RecentsView.CONTENT_ALPHA @@ -287,8 +288,8 @@ class RecentsViewStateController(private val launcher: QuickstepLauncher) : val clearAllButtonAlpha = if (state.areElementsVisible(launcher, LauncherState.CLEAR_ALL_BUTTON)) 1f else 0f propertySetter.setFloat( - recentsView.clearAllButton.visibilityAlphaProperty, - MULTI_PROPERTY_VALUE, + recentsView.clearAllButton, + ClearAllButton.VISIBILITY_ALPHA, clearAllButtonAlpha, LINEAR, ) @@ -302,8 +303,8 @@ class RecentsViewStateController(private val launcher: QuickstepLauncher) : ) recentsView.addDeskButton?.let { propertySetter.setFloat( - it.visibilityAlphaProperty, - MULTI_PROPERTY_VALUE, + it, + AddDesktopButton.VISIBILITY_ALPHA, if (state.areElementsVisible(launcher, LauncherState.ADD_DESK_BUTTON)) 1f else 0f, LINEAR, ) diff --git a/quickstep/src/com/android/quickstep/fallback/FallbackRecentsStateController.java b/quickstep/src/com/android/quickstep/fallback/FallbackRecentsStateController.java index 51f2a33529..2631efea1c 100644 --- a/quickstep/src/com/android/quickstep/fallback/FallbackRecentsStateController.java +++ b/quickstep/src/com/android/quickstep/fallback/FallbackRecentsStateController.java @@ -26,7 +26,6 @@ import static com.android.launcher3.states.StateAnimationConfig.ANIM_OVERVIEW_TR import static com.android.launcher3.states.StateAnimationConfig.ANIM_OVERVIEW_TRANSLATE_Y; import static com.android.launcher3.states.StateAnimationConfig.ANIM_SCRIM_FADE; import static com.android.launcher3.states.StateAnimationConfig.SKIP_OVERVIEW; -import static com.android.launcher3.util.MultiPropertyFactory.MULTI_PROPERTY_VALUE; import static com.android.quickstep.fallback.RecentsState.OVERVIEW_SPLIT_SELECT; import static com.android.quickstep.views.RecentsView.ADJACENT_PAGE_HORIZONTAL_OFFSET; import static com.android.quickstep.views.RecentsView.DESKTOP_CAROUSEL_DETACH_PROGRESS; @@ -52,6 +51,8 @@ import com.android.launcher3.anim.PendingAnimation; import com.android.launcher3.anim.PropertySetter; import com.android.launcher3.statemanager.StateManager.StateHandler; import com.android.launcher3.states.StateAnimationConfig; +import com.android.quickstep.views.AddDesktopButton; +import com.android.quickstep.views.ClearAllButton; import com.android.quickstep.views.RecentsView; import com.android.quickstep.views.RecentsViewContainer; @@ -97,12 +98,12 @@ public class FallbackRecentsStateController implements StateHandler.MultiProperty - get() = addDeskButtonAlpha.get(Alpha.VISIBILITY.ordinal) - - private enum class TranslationX { - GRID, - OFFSET, - } + var contentAlpha by MultiPropertyDelegate(addDeskButtonAlpha, Alpha.CONTENT) + var visibilityAlpha by MultiPropertyDelegate(addDeskButtonAlpha, Alpha.VISIBILITY) private val multiTranslationX = MultiPropertyFactory(this, VIEW_TRANSLATE_X, TranslationX.entries.size) { a: Float, b: Float -> a + b } - - var gridTranslationX - get() = multiTranslationX[TranslationX.GRID.ordinal].value - set(value) { - multiTranslationX[TranslationX.GRID.ordinal].value = value - } - - var offsetTranslationX - get() = multiTranslationX[TranslationX.OFFSET.ordinal].value - set(value) { - multiTranslationX[TranslationX.OFFSET.ordinal].value = value - } + var gridTranslationX by MultiPropertyDelegate(multiTranslationX, TranslationX.GRID) + var offsetTranslationX by MultiPropertyDelegate(multiTranslationX, TranslationX.OFFSET) private val focusBorderAnimator: BorderAnimator = createSimpleBorderAnimator( @@ -109,7 +84,7 @@ class AddDesktopButton @JvmOverloads constructor(context: Context, attrs: Attrib } } - protected fun getScrollAdjustment(showAsGrid: Boolean): Int = + fun getScrollAdjustment(showAsGrid: Boolean): Int = if (showAsGrid) gridTranslationX.toInt() else 0 private fun getBorderBounds(bounds: Rect) { @@ -123,4 +98,20 @@ class AddDesktopButton @JvmOverloads constructor(context: Context, attrs: Attrib focusBorderAnimator.drawBorder(canvas) super.draw(canvas) } + + companion object { + private enum class Alpha { + CONTENT, + VISIBILITY, + } + + private enum class TranslationX { + GRID, + OFFSET, + } + + @JvmField + val VISIBILITY_ALPHA: FloatProperty = + KFloatProperty(AddDesktopButton::visibilityAlpha) + } } diff --git a/quickstep/src/com/android/quickstep/views/ClearAllButton.kt b/quickstep/src/com/android/quickstep/views/ClearAllButton.kt index 6420ece95c..69c85eeaeb 100644 --- a/quickstep/src/com/android/quickstep/views/ClearAllButton.kt +++ b/quickstep/src/com/android/quickstep/views/ClearAllButton.kt @@ -19,11 +19,12 @@ import android.content.Context import android.graphics.Canvas import android.graphics.Rect import android.util.AttributeSet -import android.view.View +import android.util.FloatProperty import android.widget.Button import com.android.launcher3.Flags.enableFocusOutline import com.android.launcher3.R -import com.android.launcher3.util.MultiPropertyFactory +import com.android.launcher3.util.KFloatProperty +import com.android.launcher3.util.MultiPropertyDelegate import com.android.launcher3.util.MultiValueAlpha import com.android.quickstep.util.BorderAnimator import com.android.quickstep.util.BorderAnimator.Companion.createSimpleBorderAnimator @@ -33,13 +34,6 @@ import kotlin.math.min class ClearAllButton @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : Button(context, attrs) { - private enum class Alpha { - SCROLL, - CONTENT, - VISIBILITY, - DISMISS, - } - private val clearAllButtonAlpha = object : MultiValueAlpha(this, Alpha.entries.size) { override fun apply(value: Float) { @@ -47,32 +41,10 @@ class ClearAllButton @JvmOverloads constructor(context: Context, attrs: Attribut isClickable = value >= 1f } } - - var scrollAlpha - set(value) { - clearAllButtonAlpha.get(Alpha.SCROLL.ordinal).value = value - } - get() = clearAllButtonAlpha.get(Alpha.SCROLL.ordinal).value - - var contentAlpha - set(value) { - clearAllButtonAlpha.get(Alpha.CONTENT.ordinal).value = value - } - get() = clearAllButtonAlpha.get(Alpha.CONTENT.ordinal).value - - @JvmField - val visibilityAlphaProperty: MultiPropertyFactory.MultiProperty = - clearAllButtonAlpha.get(Alpha.VISIBILITY.ordinal) - - var dismissAlpha - set(value) { - dismissAlphaProperty.value = value - } - get() = dismissAlphaProperty.value - - @JvmField - val dismissAlphaProperty: MultiPropertyFactory.MultiProperty = - clearAllButtonAlpha.get(Alpha.DISMISS.ordinal) + var scrollAlpha by MultiPropertyDelegate(clearAllButtonAlpha, Alpha.SCROLL) + var contentAlpha by MultiPropertyDelegate(clearAllButtonAlpha, Alpha.CONTENT) + var visibilityAlpha by MultiPropertyDelegate(clearAllButtonAlpha, Alpha.VISIBILITY) + var dismissAlpha by MultiPropertyDelegate(clearAllButtonAlpha, Alpha.DISMISS) var fullscreenProgress = 1f set(value) { @@ -257,4 +229,21 @@ class ClearAllButton @JvmOverloads constructor(context: Context, attrs: Attribut if (fullscreenProgress > 0) endTranslation else 0f private fun getGridTrans(endTranslation: Float) = if (gridProgress > 0) endTranslation else 0f + + companion object { + private enum class Alpha { + SCROLL, + CONTENT, + VISIBILITY, + DISMISS, + } + + @JvmField + val VISIBILITY_ALPHA: FloatProperty = + KFloatProperty(ClearAllButton::visibilityAlpha) + + @JvmField + val DISMISS_ALPHA: FloatProperty = + KFloatProperty(ClearAllButton::dismissAlpha) + } } diff --git a/quickstep/src/com/android/quickstep/views/RecentsView.java b/quickstep/src/com/android/quickstep/views/RecentsView.java index e1868384ef..44bf82c7b8 100644 --- a/quickstep/src/com/android/quickstep/views/RecentsView.java +++ b/quickstep/src/com/android/quickstep/views/RecentsView.java @@ -66,6 +66,7 @@ import static com.android.launcher3.util.SystemUiController.UI_STATE_FULLSCREEN_ import static com.android.quickstep.BaseContainerInterface.getTaskDimension; import static com.android.quickstep.TaskUtils.checkCurrentOrManagedUserId; import static com.android.quickstep.util.LogUtils.splitFailureMessage; +import static com.android.quickstep.views.ClearAllButton.DISMISS_ALPHA; import static com.android.quickstep.views.OverviewActionsView.HIDDEN_ACTIONS_IN_MENU; import static com.android.quickstep.views.OverviewActionsView.HIDDEN_DESKTOP; import static com.android.quickstep.views.OverviewActionsView.HIDDEN_NON_ZERO_ROTATION; @@ -73,6 +74,7 @@ import static com.android.quickstep.views.OverviewActionsView.HIDDEN_NO_RECENTS; import static com.android.quickstep.views.OverviewActionsView.HIDDEN_NO_TASKS; import static com.android.quickstep.views.OverviewActionsView.HIDDEN_SPLIT_SELECT_ACTIVE; import static com.android.quickstep.views.RecentsViewUtils.DESK_EXPLODE_PROGRESS; +import static com.android.quickstep.views.TaskView.SPLIT_ALPHA; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; @@ -3974,8 +3976,7 @@ public abstract class RecentsView< // Change alpha of clear all if translating grid to hide it if (isClearAllHidden) { - anim.setFloat(mClearAllButton.dismissAlphaProperty, MULTI_PROPERTY_VALUE, 0, - LINEAR); + anim.setFloat(mClearAllButton, DISMISS_ALPHA, 0, LINEAR); anim.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { @@ -5354,8 +5355,7 @@ public abstract class RecentsView< clampToProgress(timings.getDesktopTaskScaleInterpolator(), 0f, timings.getDesktopFadeSplitAnimationEndOffset())); } - builder.addFloat(taskView.getSplitAlphaProperty(), - MULTI_PROPERTY_VALUE, 1f, 0f, + builder.addFloat(taskView, SPLIT_ALPHA, 1f, 0f, clampToProgress(deskTopFadeInterPolator, 0f, timings.getDesktopFadeSplitAnimationEndOffset())); } diff --git a/quickstep/src/com/android/quickstep/views/RecentsViewUtils.kt b/quickstep/src/com/android/quickstep/views/RecentsViewUtils.kt index 67318acc74..31ae890d97 100644 --- a/quickstep/src/com/android/quickstep/views/RecentsViewUtils.kt +++ b/quickstep/src/com/android/quickstep/views/RecentsViewUtils.kt @@ -28,6 +28,7 @@ import com.android.quickstep.util.isExternalDisplay import com.android.quickstep.views.RecentsView.RUNNING_TASK_ATTACH_ALPHA import com.android.systemui.shared.recents.model.ThumbnailData import java.util.function.BiConsumer +import kotlin.reflect.KMutableProperty1 /** * Helper class for [RecentsView]. This util class contains refactored and extracted functions from @@ -305,16 +306,19 @@ class RecentsViewUtils(private val recentsView: RecentsView<*, *>) { } companion object { - @JvmField - val DESK_EXPLODE_PROGRESS = - object : FloatProperty>("deskExplodeProgress") { - override fun setValue(recentsView: RecentsView<*, *>, value: Float) { - recentsView.mUtils.deskExplodeProgress = value - } + class RecentsViewFloatProperty( + private val utilsProperty: KMutableProperty1 + ) : FloatProperty>(utilsProperty.name) { + override fun get(recentsView: RecentsView<*, *>): Float = + utilsProperty.get(recentsView.mUtils) - override fun get(recentsView: RecentsView<*, *>) = - recentsView.mUtils.deskExplodeProgress + override fun setValue(recentsView: RecentsView<*, *>, value: Float) { + utilsProperty.set(recentsView.mUtils, value) } + } + + @JvmField + val DESK_EXPLODE_PROGRESS = RecentsViewFloatProperty(RecentsViewUtils::deskExplodeProgress) val TEMP_RECT = Rect() } diff --git a/quickstep/src/com/android/quickstep/views/TaskView.kt b/quickstep/src/com/android/quickstep/views/TaskView.kt index ad60329814..276318c2db 100644 --- a/quickstep/src/com/android/quickstep/views/TaskView.kt +++ b/quickstep/src/com/android/quickstep/views/TaskView.kt @@ -61,8 +61,9 @@ import com.android.launcher3.testing.TestLogging import com.android.launcher3.testing.shared.TestProtocol import com.android.launcher3.util.CancellableTask import com.android.launcher3.util.Executors +import com.android.launcher3.util.KFloatProperty +import com.android.launcher3.util.MultiPropertyDelegate import com.android.launcher3.util.MultiPropertyFactory -import com.android.launcher3.util.MultiPropertyFactory.MULTI_PROPERTY_VALUE import com.android.launcher3.util.MultiValueAlpha import com.android.launcher3.util.RunnableList import com.android.launcher3.util.SplitConfigurationOptions.STAGE_POSITION_UNDEFINED @@ -440,28 +441,10 @@ constructor( applyTranslationX() } - private val taskViewAlpha = MultiValueAlpha(this, NUM_ALPHA_CHANNELS) - - protected var stableAlpha - set(value) { - taskViewAlpha.get(ALPHA_INDEX_STABLE).value = value - } - get() = taskViewAlpha.get(ALPHA_INDEX_STABLE).value - - var attachAlpha - set(value) { - taskViewAlpha.get(ALPHA_INDEX_ATTACH).value = value - } - get() = taskViewAlpha.get(ALPHA_INDEX_ATTACH).value - - var splitAlpha - set(value) { - splitAlphaProperty.value = value - } - get() = splitAlphaProperty.value - - val splitAlphaProperty: MultiPropertyFactory.MultiProperty - get() = taskViewAlpha.get(ALPHA_INDEX_SPLIT) + private val taskViewAlpha = MultiValueAlpha(this, Alpha.entries.size) + protected var stableAlpha by MultiPropertyDelegate(taskViewAlpha, Alpha.STABLE) + var attachAlpha by MultiPropertyDelegate(taskViewAlpha, Alpha.ATTACH) + var splitAlpha by MultiPropertyDelegate(taskViewAlpha, Alpha.SPLIT) protected var shouldShowScreenshot = false get() = !isRunningTask || field @@ -515,16 +498,16 @@ constructor( MultiPropertyFactory( this, SETTLED_PROGRESS, - SETTLED_PROGRESS_INDEX_COUNT, + SettledProgress.entries.size, { x: Float, y: Float -> x * y }, 1f, ) - private val settledProgressFullscreen = - settledProgressPropertyFactory.get(SETTLED_PROGRESS_INDEX_FULLSCREEN) - private val settledProgressGesture = - settledProgressPropertyFactory.get(SETTLED_PROGRESS_INDEX_GESTURE) - private val settledProgressDismiss = - settledProgressPropertyFactory.get(SETTLED_PROGRESS_INDEX_DISMISS) + private var settledProgressFullscreen by + MultiPropertyDelegate(settledProgressPropertyFactory, SettledProgress.Fullscreen) + private var settledProgressGesture by + MultiPropertyDelegate(settledProgressPropertyFactory, SettledProgress.Gesture) + private var settledProgressDismiss by + MultiPropertyDelegate(settledProgressPropertyFactory, SettledProgress.Dismiss) private var viewModel: TaskViewModel? = null private val dispatcherProvider: DispatcherProvider by RecentsDependencies.inject() @@ -536,7 +519,7 @@ constructor( * interpolator. */ fun getDismissIconFadeInAnimator(): ObjectAnimator = - ObjectAnimator.ofFloat(settledProgressDismiss, MULTI_PROPERTY_VALUE, 1f).apply { + ObjectAnimator.ofFloat(this, SETTLED_PROGRESS_DISMISS, 1f).apply { duration = FADE_IN_ICON_DURATION interpolator = FADE_IN_ICON_INTERPOLATOR } @@ -548,8 +531,7 @@ constructor( */ fun getDismissIconFadeOutAnimator(): ObjectAnimator = AnimatedFloat { v -> - settledProgressDismiss.value = - SETTLED_PROGRESS_FAST_OUT_INTERPOLATOR.getInterpolation(v) + settledProgressDismiss = SETTLED_PROGRESS_FAST_OUT_INTERPOLATOR.getInterpolation(v) } .animateToValue(1f, 0f) @@ -1603,7 +1585,7 @@ constructor( fun startIconFadeInOnGestureComplete() { iconFadeInOnGestureCompleteAnimator?.cancel() iconFadeInOnGestureCompleteAnimator = - ObjectAnimator.ofFloat(settledProgressGesture, MULTI_PROPERTY_VALUE, 1f).apply { + ObjectAnimator.ofFloat(this, SETTLED_PROGRESS_GESTURE, 1f).apply { duration = FADE_IN_ICON_DURATION interpolator = Interpolators.LINEAR addListener( @@ -1619,7 +1601,7 @@ constructor( fun setIconVisibleForGesture(isVisible: Boolean) { iconFadeInOnGestureCompleteAnimator?.cancel() - settledProgressGesture.value = if (isVisible) 1f else 0f + settledProgressGesture = if (isVisible) 1f else 0f } /** Set a color tint on the snapshot and supporting views. */ @@ -1708,7 +1690,7 @@ constructor( it.iconView.setVisibility(if (fullscreenProgress < 1) VISIBLE else INVISIBLE) it.overlay.setFullscreenProgress(fullscreenProgress) } - settledProgressFullscreen.value = + settledProgressFullscreen = SETTLED_PROGRESS_FAST_OUT_INTERPOLATOR.getInterpolation(1 - fullscreenProgress) updateFullscreenParams() } @@ -1766,7 +1748,7 @@ constructor( dismissScale = 1f translationZ = 0f setIconVisibleForGesture(true) - settledProgressDismiss.value = 1f + settledProgressDismiss = 1f setColorTint(0f, 0) } @@ -1788,23 +1770,25 @@ constructor( companion object { private const val TAG = "TaskView" + + private enum class Alpha { + STABLE, + ATTACH, + SPLIT, + } + + private enum class SettledProgress { + Fullscreen, + Gesture, + Dismiss, + } + const val FLAG_UPDATE_ICON = 1 const val FLAG_UPDATE_THUMBNAIL = FLAG_UPDATE_ICON shl 1 const val FLAG_UPDATE_CORNER_RADIUS = FLAG_UPDATE_THUMBNAIL shl 1 const val FLAG_UPDATE_ALL = (FLAG_UPDATE_ICON or FLAG_UPDATE_THUMBNAIL or FLAG_UPDATE_CORNER_RADIUS) - const val SETTLED_PROGRESS_INDEX_FULLSCREEN = 0 - const val SETTLED_PROGRESS_INDEX_GESTURE = 1 - const val SETTLED_PROGRESS_INDEX_DISMISS = 2 - const val SETTLED_PROGRESS_INDEX_COUNT = 3 - - private const val ALPHA_INDEX_STABLE = 0 - private const val ALPHA_INDEX_ATTACH = 1 - private const val ALPHA_INDEX_SPLIT = 2 - - private const val NUM_ALPHA_CHANNELS = 3 - /** The maximum amount that a task view can be scrimmed, dimmed or tinted. */ const val MAX_PAGE_SCRIM_ALPHA = 0.4f const val FADE_IN_ICON_DURATION: Long = 120 @@ -1821,104 +1805,45 @@ constructor( private val SYSTEM_GESTURE_EXCLUSION_RECT = listOf(Rect()) private val SETTLED_PROGRESS: FloatProperty = - object : FloatProperty("settleTransition") { - override fun setValue(taskView: TaskView, v: Float) { - taskView.settledProgress = v - } + KFloatProperty(TaskView::settledProgress) - override fun get(taskView: TaskView) = taskView.settledProgress - } + private val SETTLED_PROGRESS_GESTURE: FloatProperty = + KFloatProperty(TaskView::settledProgressGesture) + + private val SETTLED_PROGRESS_DISMISS: FloatProperty = + KFloatProperty(TaskView::settledProgressDismiss) private val SPLIT_SELECT_TRANSLATION_X: FloatProperty = - object : FloatProperty("splitSelectTranslationX") { - override fun setValue(taskView: TaskView, v: Float) { - taskView.splitSelectTranslationX = v - } - - override fun get(taskView: TaskView) = taskView.splitSelectTranslationX - } + KFloatProperty(TaskView::splitSelectTranslationX) private val SPLIT_SELECT_TRANSLATION_Y: FloatProperty = - object : FloatProperty("splitSelectTranslationY") { - override fun setValue(taskView: TaskView, v: Float) { - taskView.splitSelectTranslationY = v - } - - override fun get(taskView: TaskView) = taskView.splitSelectTranslationY - } + KFloatProperty(TaskView::splitSelectTranslationY) private val DISMISS_TRANSLATION_X: FloatProperty = - object : FloatProperty("dismissTranslationX") { - override fun setValue(taskView: TaskView, v: Float) { - taskView.dismissTranslationX = v - } - - override fun get(taskView: TaskView) = taskView.dismissTranslationX - } + KFloatProperty(TaskView::dismissTranslationX) private val DISMISS_TRANSLATION_Y: FloatProperty = - object : FloatProperty("dismissTranslationY") { - override fun setValue(taskView: TaskView, v: Float) { - taskView.dismissTranslationY = v - } - - override fun get(taskView: TaskView) = taskView.dismissTranslationY - } + KFloatProperty(TaskView::dismissTranslationY) private val TASK_OFFSET_TRANSLATION_X: FloatProperty = - object : FloatProperty("taskOffsetTranslationX") { - override fun setValue(taskView: TaskView, v: Float) { - taskView.taskOffsetTranslationX = v - } - - override fun get(taskView: TaskView) = taskView.taskOffsetTranslationX - } + KFloatProperty(TaskView::taskOffsetTranslationX) private val TASK_OFFSET_TRANSLATION_Y: FloatProperty = - object : FloatProperty("taskOffsetTranslationY") { - override fun setValue(taskView: TaskView, v: Float) { - taskView.taskOffsetTranslationY = v - } - - override fun get(taskView: TaskView) = taskView.taskOffsetTranslationY - } + KFloatProperty(TaskView::taskOffsetTranslationY) private val TASK_RESISTANCE_TRANSLATION_X: FloatProperty = - object : FloatProperty("taskResistanceTranslationX") { - override fun setValue(taskView: TaskView, v: Float) { - taskView.taskResistanceTranslationX = v - } - - override fun get(taskView: TaskView) = taskView.taskResistanceTranslationX - } + KFloatProperty(TaskView::taskResistanceTranslationX) private val TASK_RESISTANCE_TRANSLATION_Y: FloatProperty = - object : FloatProperty("taskResistanceTranslationY") { - override fun setValue(taskView: TaskView, v: Float) { - taskView.taskResistanceTranslationY = v - } - - override fun get(taskView: TaskView) = taskView.taskResistanceTranslationY - } + KFloatProperty(TaskView::taskResistanceTranslationY) @JvmField val GRID_END_TRANSLATION_X: FloatProperty = - object : FloatProperty("gridEndTranslationX") { - override fun setValue(taskView: TaskView, v: Float) { - taskView.gridEndTranslationX = v - } - - override fun get(taskView: TaskView) = taskView.gridEndTranslationX - } + KFloatProperty(TaskView::gridEndTranslationX) @JvmField - val DISMISS_SCALE: FloatProperty = - object : FloatProperty("dismissScale") { - override fun setValue(taskView: TaskView, v: Float) { - taskView.dismissScale = v - } + val DISMISS_SCALE: FloatProperty = KFloatProperty(TaskView::dismissScale) - override fun get(taskView: TaskView) = taskView.dismissScale - } + @JvmField val SPLIT_ALPHA: FloatProperty = KFloatProperty(TaskView::splitAlpha) } } diff --git a/src/com/android/launcher3/util/KFloatProperty.kt b/src/com/android/launcher3/util/KFloatProperty.kt new file mode 100644 index 0000000000..55792415f7 --- /dev/null +++ b/src/com/android/launcher3/util/KFloatProperty.kt @@ -0,0 +1,30 @@ +/* + * 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.launcher3.util + +import android.util.FloatProperty +import kotlin.reflect.KMutableProperty1 + +/** Maps any Kotlin mutable property (var) to [FloatProperty]. */ +class KFloatProperty(private val kProperty: KMutableProperty1) : + FloatProperty(kProperty.name) { + override fun get(target: T) = kProperty.get(target) + + override fun setValue(target: T, value: Float) { + kProperty.set(target, value) + } +} diff --git a/src/com/android/launcher3/util/MultiPropertyDelegate.kt b/src/com/android/launcher3/util/MultiPropertyDelegate.kt new file mode 100644 index 0000000000..837a586045 --- /dev/null +++ b/src/com/android/launcher3/util/MultiPropertyDelegate.kt @@ -0,0 +1,30 @@ +/* + * 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.launcher3.util + +import kotlin.reflect.KProperty + +/** Delegate Kotlin mutable property (var) to a property in [MultiPropertyFactory] */ +class MultiPropertyDelegate(private val property: MultiPropertyFactory<*>.MultiProperty) { + constructor(factory: MultiPropertyFactory<*>, enum: Enum<*>) : this(factory[enum.ordinal]) + + operator fun getValue(thisRef: Any?, kProperty: KProperty<*>): Float = property.value + + operator fun setValue(thisRef: Any?, kProperty: KProperty<*>, value: Float) { + property.value = value + } +} From d8e5ddb4cdc687e2baab19dc5c9fc421df85bd53 Mon Sep 17 00:00:00 2001 From: Sunny Goyal Date: Wed, 26 Feb 2025 13:42:41 -0800 Subject: [PATCH 137/153] Removing unnecessary isBindingItems method from ActivityContext Bug: 393703968 Flag: EXEMPT refactor Test: Presubmit Change-Id: I06fd1dcc81da5e5502a9fb0751c2701b26fd4621 --- .../launcher3/taskbar/TaskbarActivityContext.java | 12 ------------ .../launcher3/taskbar/TaskbarModelCallbacks.java | 7 ++++--- .../taskbar/overlay/TaskbarOverlayContext.java | 5 ----- src/com/android/launcher3/Launcher.java | 5 ----- .../secondarydisplay/SecondaryDisplayLauncher.java | 13 ------------- .../android/launcher3/views/ActivityContext.java | 5 ----- 6 files changed, 4 insertions(+), 43 deletions(-) diff --git a/quickstep/src/com/android/launcher3/taskbar/TaskbarActivityContext.java b/quickstep/src/com/android/launcher3/taskbar/TaskbarActivityContext.java index 57bcc14ff3..6241111040 100644 --- a/quickstep/src/com/android/launcher3/taskbar/TaskbarActivityContext.java +++ b/quickstep/src/com/android/launcher3/taskbar/TaskbarActivityContext.java @@ -229,7 +229,6 @@ public class TaskbarActivityContext extends BaseTaskbarContext { private boolean mIsDestroyed = false; // The flag to know if the window is excluded from magnification region computation. private boolean mIsExcludeFromMagnificationRegion = false; - private boolean mBindingItems = false; private boolean mAddedWindow = false; // The bounds of the taskbar items relative to TaskbarDragLayer @@ -894,15 +893,6 @@ public class TaskbarActivityContext extends BaseTaskbarContext { return mAccessibilityDelegate; } - @Override - public boolean isBindingItems() { - return mBindingItems; - } - - public void setBindingItems(boolean bindingItems) { - mBindingItems = bindingItems; - } - @Override public void onDragStart() { setTaskbarWindowFullscreen(true); @@ -2049,8 +2039,6 @@ public class TaskbarActivityContext extends BaseTaskbarContext { "%s\tmIsUserSetupComplete=%b", prefix, mIsUserSetupComplete)); pw.println(String.format( "%s\tmWindowLayoutParams.height=%dpx", prefix, mWindowLayoutParams.height)); - pw.println(String.format( - "%s\tmBindInProgress=%b", prefix, mBindingItems)); mControllers.dumpLogs(prefix + "\t", pw); mDeviceProfile.dump(this, prefix, pw); } diff --git a/quickstep/src/com/android/launcher3/taskbar/TaskbarModelCallbacks.java b/quickstep/src/com/android/launcher3/taskbar/TaskbarModelCallbacks.java index 6815f97e16..0fa82aef97 100644 --- a/quickstep/src/com/android/launcher3/taskbar/TaskbarModelCallbacks.java +++ b/quickstep/src/com/android/launcher3/taskbar/TaskbarModelCallbacks.java @@ -61,6 +61,7 @@ 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) { @@ -74,14 +75,14 @@ public class TaskbarModelCallbacks implements @Override public void startBinding() { - mContext.setBindingItems(true); + mBindingItems = true; mHotseatItems.clear(); mPredictedItems = Collections.emptyList(); } @Override public void finishBindingItems(IntSet pagesBoundFirst) { - mContext.setBindingItems(false); + mBindingItems = false; commitItemsToUI(); } @@ -167,7 +168,7 @@ public class TaskbarModelCallbacks implements } private void commitItemsToUI() { - if (mContext.isBindingItems()) { + if (mBindingItems) { return; } diff --git a/quickstep/src/com/android/launcher3/taskbar/overlay/TaskbarOverlayContext.java b/quickstep/src/com/android/launcher3/taskbar/overlay/TaskbarOverlayContext.java index 64cc47c739..0fce2379fc 100644 --- a/quickstep/src/com/android/launcher3/taskbar/overlay/TaskbarOverlayContext.java +++ b/quickstep/src/com/android/launcher3/taskbar/overlay/TaskbarOverlayContext.java @@ -115,11 +115,6 @@ public class TaskbarOverlayContext extends BaseTaskbarContext { return mDragLayer.findViewById(R.id.apps_view); } - @Override - public boolean isBindingItems() { - return mTaskbarContext.isBindingItems(); - } - @Override public View.OnClickListener getItemOnClickListener() { return mTaskbarContext.getItemOnClickListener(); diff --git a/src/com/android/launcher3/Launcher.java b/src/com/android/launcher3/Launcher.java index 3edba990e7..84de1c2f53 100644 --- a/src/com/android/launcher3/Launcher.java +++ b/src/com/android/launcher3/Launcher.java @@ -2948,11 +2948,6 @@ public class Launcher extends StatefulActivity return mModelCallbacks.getWorkspaceLoading(); } - @Override - public boolean isBindingItems() { - return isWorkspaceLoading(); - } - /** * Returns true if a touch interaction is in progress */ diff --git a/src/com/android/launcher3/secondarydisplay/SecondaryDisplayLauncher.java b/src/com/android/launcher3/secondarydisplay/SecondaryDisplayLauncher.java index b1653d0fab..2a2108571e 100644 --- a/src/com/android/launcher3/secondarydisplay/SecondaryDisplayLauncher.java +++ b/src/com/android/launcher3/secondarydisplay/SecondaryDisplayLauncher.java @@ -57,7 +57,6 @@ import com.android.launcher3.popup.PopupContainerWithArrow; import com.android.launcher3.popup.PopupDataProvider; import com.android.launcher3.touch.ItemClickHandler.ItemClickProxy; import com.android.launcher3.util.ComponentKey; -import com.android.launcher3.util.IntSet; import com.android.launcher3.util.PackageUserKey; import com.android.launcher3.util.Preconditions; import com.android.launcher3.util.Themes; @@ -83,7 +82,6 @@ public class SecondaryDisplayLauncher extends BaseActivity private boolean mAppDrawerShown = false; private StringCache mStringCache; - private boolean mBindingItems = false; private SecondaryDisplayPredictions mSecondaryDisplayPredictions; private final int[] mTempXY = new int[2]; @@ -260,20 +258,9 @@ public class SecondaryDisplayLauncher extends BaseActivity @Override public void startBinding() { - mBindingItems = true; mDragController.cancelDrag(); } - @Override - public boolean isBindingItems() { - return mBindingItems; - } - - @Override - public void finishBindingItems(IntSet pagesBoundFirst) { - mBindingItems = false; - } - @Override public void bindDeepShortcutMap(HashMap deepShortcutMap) { mPopupDataProvider.setDeepShortcutMap(deepShortcutMap); diff --git a/src/com/android/launcher3/views/ActivityContext.java b/src/com/android/launcher3/views/ActivityContext.java index bbea043820..5a04539fce 100644 --- a/src/com/android/launcher3/views/ActivityContext.java +++ b/src/com/android/launcher3/views/ActivityContext.java @@ -270,11 +270,6 @@ public interface ActivityContext { */ default void applyOverwritesToLogItem(LauncherAtom.ItemInfo.Builder itemInfoBuilder) { } - /** Returns {@code true} if items are currently being bound within this context. */ - default boolean isBindingItems() { - return false; - } - default View.OnClickListener getItemOnClickListener() { return v -> { // No op. From 39063bf16735b216150792de91d1f02c6c30b6cb Mon Sep 17 00:00:00 2001 From: Sunny Goyal Date: Wed, 26 Feb 2025 12:59:51 -0800 Subject: [PATCH 138/153] Merging some notification dots implementation Bug: 393703968 Flag: EXEMPT refactor Test: Presubmit Change-Id: Ie02311afba85f06fbafd265a5015cd23bd356a36 --- .../taskbar/TaskbarActivityContext.java | 19 ++++--- .../taskbar/TaskbarPopupController.java | 42 +-------------- .../launcher3/taskbar/TaskbarView.java | 15 ------ .../taskbar/TaskbarViewController.java | 7 +-- .../allapps/TaskbarAllAppsController.java | 13 ++--- .../overlay/TaskbarOverlayContext.java | 9 +--- src/com/android/launcher3/Launcher.java | 20 +++----- src/com/android/launcher3/Workspace.java | 34 ------------- .../launcher3/popup/PopupDataProvider.java | 51 ++++++++++++++++--- .../SecondaryDisplayLauncher.java | 6 ++- .../launcher3/views/ActivityContext.java | 21 +++++--- .../util/TestSandboxModelContextWrapper.java | 5 +- 12 files changed, 97 insertions(+), 145 deletions(-) diff --git a/quickstep/src/com/android/launcher3/taskbar/TaskbarActivityContext.java b/quickstep/src/com/android/launcher3/taskbar/TaskbarActivityContext.java index 57bcc14ff3..976ad42d09 100644 --- a/quickstep/src/com/android/launcher3/taskbar/TaskbarActivityContext.java +++ b/quickstep/src/com/android/launcher3/taskbar/TaskbarActivityContext.java @@ -97,12 +97,12 @@ import com.android.launcher3.DeviceProfile; import com.android.launcher3.LauncherPrefs; import com.android.launcher3.LauncherSettings.Favorites; import com.android.launcher3.R; +import com.android.launcher3.allapps.ActivityAllAppsContainerView; import com.android.launcher3.anim.AnimatorPlaybackController; import com.android.launcher3.apppairs.AppPairIcon; import com.android.launcher3.config.FeatureFlags; import com.android.launcher3.desktop.DesktopAppLaunchTransition; import com.android.launcher3.desktop.DesktopAppLaunchTransition.AppLaunchType; -import com.android.launcher3.dot.DotInfo; import com.android.launcher3.folder.Folder; import com.android.launcher3.folder.FolderIcon; import com.android.launcher3.logger.LauncherAtom; @@ -149,6 +149,7 @@ import com.android.launcher3.util.ApplicationInfoWrapper; import com.android.launcher3.util.ComponentKey; import com.android.launcher3.util.DisplayController; import com.android.launcher3.util.Executors; +import com.android.launcher3.util.LauncherBindableItemsContainer; import com.android.launcher3.util.MultiPropertyFactory; import com.android.launcher3.util.NavigationMode; import com.android.launcher3.util.RunnableList; @@ -878,17 +879,23 @@ public class TaskbarActivityContext extends BaseTaskbarContext { } } - @Override - public DotInfo getDotInfoForItem(ItemInfo info) { - return getPopupDataProvider().getDotInfoForItem(info); - } - @NonNull @Override public PopupDataProvider getPopupDataProvider() { return mControllers.taskbarPopupController.getPopupDataProvider(); } + @NonNull + @Override + public LauncherBindableItemsContainer getContent() { + return mControllers.taskbarViewController.getContent(); + } + + @Override + public ActivityAllAppsContainerView getAppsView() { + return mControllers.taskbarAllAppsController.getAppsView(); + } + @Override public View.AccessibilityDelegate getAccessibilityDelegate() { return mAccessibilityDelegate; diff --git a/quickstep/src/com/android/launcher3/taskbar/TaskbarPopupController.java b/quickstep/src/com/android/launcher3/taskbar/TaskbarPopupController.java index 5d8b8212a8..a9ee584e95 100644 --- a/quickstep/src/com/android/launcher3/taskbar/TaskbarPopupController.java +++ b/quickstep/src/com/android/launcher3/taskbar/TaskbarPopupController.java @@ -35,11 +35,7 @@ import com.android.launcher3.BubbleTextView; import com.android.launcher3.Flags; import com.android.launcher3.LauncherSettings; import com.android.launcher3.R; -import com.android.launcher3.dot.FolderDotInfo; -import com.android.launcher3.folder.Folder; -import com.android.launcher3.folder.FolderIcon; import com.android.launcher3.model.data.AppInfo; -import com.android.launcher3.model.data.FolderInfo; import com.android.launcher3.model.data.ItemInfo; import com.android.launcher3.model.data.WorkspaceItemInfo; import com.android.launcher3.notification.NotificationListener; @@ -49,8 +45,6 @@ import com.android.launcher3.popup.SystemShortcut; import com.android.launcher3.shortcuts.DeepShortcutView; import com.android.launcher3.splitscreen.SplitShortcut; import com.android.launcher3.util.ComponentKey; -import com.android.launcher3.util.LauncherBindableItemsContainer; -import com.android.launcher3.util.PackageUserKey; import com.android.launcher3.util.ShortcutUtil; import com.android.launcher3.util.SplitConfigurationOptions.SplitPositionOption; import com.android.launcher3.views.ActivityContext; @@ -65,7 +59,6 @@ import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Objects; -import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -93,7 +86,7 @@ public class TaskbarPopupController implements TaskbarControllers.LoggableTaskba public TaskbarPopupController(TaskbarActivityContext context) { mContext = context; - mPopupDataProvider = new PopupDataProvider(this::updateNotificationDots); + mPopupDataProvider = new PopupDataProvider(mContext); } public void init(TaskbarControllers controllers) { @@ -132,39 +125,6 @@ public class TaskbarPopupController implements TaskbarControllers.LoggableTaskba mAllowInitialSplitSelection = allowInitialSplitSelection; } - private void updateNotificationDots(Predicate updatedDots) { - final PackageUserKey packageUserKey = new PackageUserKey(null, null); - Predicate matcher = info -> !packageUserKey.updateFromItemInfo(info) - || updatedDots.test(packageUserKey); - - LauncherBindableItemsContainer.ItemOperator op = (info, v) -> { - if (info instanceof WorkspaceItemInfo && v instanceof BubbleTextView) { - if (matcher.test(info)) { - ((BubbleTextView) v).applyDotState(info, true /* animate */); - } - } else if (info instanceof FolderInfo && v instanceof FolderIcon) { - FolderInfo fi = (FolderInfo) info; - if (fi.anyMatch(matcher)) { - FolderDotInfo folderDotInfo = new FolderDotInfo(); - for (ItemInfo si : fi.getContents()) { - folderDotInfo.addDotInfo(mPopupDataProvider.getDotInfoForItem(si)); - } - ((FolderIcon) v).setDotInfo(folderDotInfo); - } - } - - // process all the shortcuts - return false; - }; - - mControllers.taskbarViewController.mapOverItems(op); - Folder folder = Folder.getOpen(mContext); - if (folder != null) { - folder.iterateOverItems(op); - } - mControllers.taskbarAllAppsController.updateNotificationDots(updatedDots); - } - /** * Shows the notifications and deep shortcuts associated with a Taskbar {@param icon}. * @return the container if shown or null. diff --git a/quickstep/src/com/android/launcher3/taskbar/TaskbarView.java b/quickstep/src/com/android/launcher3/taskbar/TaskbarView.java index c92f20b283..de8e28639b 100644 --- a/quickstep/src/com/android/launcher3/taskbar/TaskbarView.java +++ b/quickstep/src/com/android/launcher3/taskbar/TaskbarView.java @@ -62,7 +62,6 @@ import com.android.launcher3.taskbar.customization.TaskbarAllAppsButtonContainer import com.android.launcher3.taskbar.customization.TaskbarDividerContainer; import com.android.launcher3.uioverrides.PredictedAppIcon; import com.android.launcher3.util.DisplayController; -import com.android.launcher3.util.LauncherBindableItemsContainer; import com.android.launcher3.util.Themes; import com.android.launcher3.views.ActivityContext; import com.android.quickstep.util.GroupTask; @@ -1097,20 +1096,6 @@ public class TaskbarView extends FrameLayout implements FolderIcon.FolderIconPar return mAllAppsButtonTranslationOffset; } - /** - * Maps {@code op} over all the child views. - */ - public void mapOverItems(LauncherBindableItemsContainer.ItemOperator op) { - // map over all the shortcuts on the taskbar - for (int i = 0; i < getChildCount(); i++) { - View item = getChildAt(i); - // TODO(b/344657629): Support GroupTask as well for notification dots/popup - if (item.getTag() instanceof ItemInfo itemInfo && op.evaluate(itemInfo, item)) { - return; - } - } - } - /** * Finds the first icon to match one of the given matchers, from highest to lowest priority. * diff --git a/quickstep/src/com/android/launcher3/taskbar/TaskbarViewController.java b/quickstep/src/com/android/launcher3/taskbar/TaskbarViewController.java index 384468c9fc..d7110f2699 100644 --- a/quickstep/src/com/android/launcher3/taskbar/TaskbarViewController.java +++ b/quickstep/src/com/android/launcher3/taskbar/TaskbarViewController.java @@ -1167,11 +1167,8 @@ public class TaskbarViewController implements TaskbarControllers.LoggableTaskbar mTaskbarNavButtonTranslationY.updateValue(-deviceProfile.getTaskbarOffsetY()); } - /** - * Maps the given operator to all the top-level children of TaskbarView. - */ - public void mapOverItems(LauncherBindableItemsContainer.ItemOperator op) { - mTaskbarView.mapOverItems(op); + public LauncherBindableItemsContainer getContent() { + return mModelCallbacks; } /** diff --git a/quickstep/src/com/android/launcher3/taskbar/allapps/TaskbarAllAppsController.java b/quickstep/src/com/android/launcher3/taskbar/allapps/TaskbarAllAppsController.java index ddbf3b7fc6..6c55b28845 100644 --- a/quickstep/src/com/android/launcher3/taskbar/allapps/TaskbarAllAppsController.java +++ b/quickstep/src/com/android/launcher3/taskbar/allapps/TaskbarAllAppsController.java @@ -35,7 +35,6 @@ import com.android.launcher3.util.PackageUserKey; import java.util.Collections; import java.util.List; import java.util.Map; -import java.util.function.Predicate; /** * Handles the all apps overlay window initialization, updates, and its data. *

@@ -120,13 +119,6 @@ public final class TaskbarAllAppsController { mZeroStateSearchSuggestions = zeroStateSearchSuggestions; } - /** Updates the current notification dots. */ - public void updateNotificationDots(Predicate updatedDots) { - if (mAppsView != null) { - mAppsView.getAppsStore().updateNotificationDots(updatedDots); - } - } - /** Toggles visibility of {@link TaskbarAllAppsContainerView} in the overlay window. */ public void toggle() { toggle(false); @@ -218,6 +210,11 @@ public final class TaskbarAllAppsController { mAppsView = null; } + @Nullable + public TaskbarAllAppsContainerView getAppsView() { + return mAppsView; + } + @VisibleForTesting public int getTaskbarAllAppsTopPadding() { // Allow null-pointer since this should only be null if the apps view is not showing. diff --git a/quickstep/src/com/android/launcher3/taskbar/overlay/TaskbarOverlayContext.java b/quickstep/src/com/android/launcher3/taskbar/overlay/TaskbarOverlayContext.java index 64cc47c739..b6917c0eae 100644 --- a/quickstep/src/com/android/launcher3/taskbar/overlay/TaskbarOverlayContext.java +++ b/quickstep/src/com/android/launcher3/taskbar/overlay/TaskbarOverlayContext.java @@ -18,12 +18,11 @@ package com.android.launcher3.taskbar.overlay; import android.content.Context; import android.view.View; +import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.android.launcher3.DeviceProfile; import com.android.launcher3.R; -import com.android.launcher3.dot.DotInfo; -import com.android.launcher3.model.data.ItemInfo; import com.android.launcher3.popup.PopupDataProvider; import com.android.launcher3.taskbar.BaseTaskbarContext; import com.android.launcher3.taskbar.TaskbarActivityContext; @@ -130,6 +129,7 @@ public class TaskbarOverlayContext extends BaseTaskbarContext { return mDragController::startDragOnLongClick; } + @NonNull @Override public PopupDataProvider getPopupDataProvider() { return mTaskbarContext.getPopupDataProvider(); @@ -140,11 +140,6 @@ public class TaskbarOverlayContext extends BaseTaskbarContext { mUiController.startSplitSelection(splitSelectSource); } - @Override - public DotInfo getDotInfoForItem(ItemInfo info) { - return mTaskbarContext.getDotInfoForItem(info); - } - @Override public void onDragStart() {} diff --git a/src/com/android/launcher3/Launcher.java b/src/com/android/launcher3/Launcher.java index 3edba990e7..cf17361780 100644 --- a/src/com/android/launcher3/Launcher.java +++ b/src/com/android/launcher3/Launcher.java @@ -185,7 +185,6 @@ import com.android.launcher3.compat.AccessibilityManagerCompat; import com.android.launcher3.config.FeatureFlags; import com.android.launcher3.debug.TestEventEmitter; import com.android.launcher3.debug.TestEventEmitter.TestEvent; -import com.android.launcher3.dot.DotInfo; import com.android.launcher3.dragndrop.DragController; import com.android.launcher3.dragndrop.DragLayer; import com.android.launcher3.dragndrop.DragView; @@ -237,6 +236,7 @@ import com.android.launcher3.util.IntArray; import com.android.launcher3.util.IntSet; import com.android.launcher3.util.ItemInflater; import com.android.launcher3.util.KeyboardShortcutsDelegate; +import com.android.launcher3.util.LauncherBindableItemsContainer; import com.android.launcher3.util.LockedUserState; import com.android.launcher3.util.MSDLPlayerWrapper; import com.android.launcher3.util.PackageUserKey; @@ -544,7 +544,7 @@ public class Launcher extends StatefulActivity mItemInflater = new ItemInflater<>(this, mAppWidgetHolder, getItemOnClickListener(), mFocusHandler, new CellLayout(mWorkspace.getContext(), mWorkspace)); - mPopupDataProvider = new PopupDataProvider(this::updateNotificationDots); + mPopupDataProvider = new PopupDataProvider(this); mWidgetPickerDataProvider = new WidgetPickerDataProvider(); PillColorProvider.getInstance(mWorkspace.getContext()).registerObserver(); @@ -1598,11 +1598,6 @@ public class Launcher extends StatefulActivity private final ScreenOnListener mScreenOnListener = this::onScreenOnChanged; - private void updateNotificationDots(Predicate updatedDots) { - mWorkspace.updateNotificationDots(updatedDots); - mAppsView.getAppsStore().updateNotificationDots(updatedDots); - } - @Override public void onAttachedToWindow() { super.onAttachedToWindow(); @@ -3027,11 +3022,6 @@ public class Launcher extends StatefulActivity return mWidgetPickerDataProvider; } - @Override - public DotInfo getDotInfoForItem(ItemInfo info) { - return mPopupDataProvider.getDotInfoForItem(info); - } - @NonNull public LauncherOverlayManager getOverlayManager() { return mOverlayManager; @@ -3046,6 +3036,12 @@ public class Launcher extends StatefulActivity return mDragLayer; } + @NonNull + @Override + public LauncherBindableItemsContainer getContent() { + return mWorkspace; + } + @Override public ActivityAllAppsContainerView getAppsView() { return mAppsView; diff --git a/src/com/android/launcher3/Workspace.java b/src/com/android/launcher3/Workspace.java index 94ff44145b..559582879e 100644 --- a/src/com/android/launcher3/Workspace.java +++ b/src/com/android/launcher3/Workspace.java @@ -83,7 +83,6 @@ import com.android.launcher3.celllayout.CellPosMapper.CellPos; import com.android.launcher3.config.FeatureFlags; import com.android.launcher3.debug.TestEventEmitter; import com.android.launcher3.debug.TestEventEmitter.TestEvent; -import com.android.launcher3.dot.FolderDotInfo; import com.android.launcher3.dragndrop.DragController; import com.android.launcher3.dragndrop.DragLayer; import com.android.launcher3.dragndrop.DragOptions; @@ -119,7 +118,6 @@ import com.android.launcher3.util.IntSparseArrayMap; import com.android.launcher3.util.LauncherBindableItemsContainer; import com.android.launcher3.util.MSDLPlayerWrapper; import com.android.launcher3.util.OverlayEdgeEffect; -import com.android.launcher3.util.PackageUserKey; import com.android.launcher3.util.RunnableList; import com.android.launcher3.util.Thunk; import com.android.launcher3.util.WallpaperOffsetInterpolator; @@ -3419,38 +3417,6 @@ public class Workspace extends PagedView return null; } - public void updateNotificationDots(Predicate updatedDots) { - final PackageUserKey packageUserKey = new PackageUserKey(null, null); - Predicate matcher = info -> !packageUserKey.updateFromItemInfo(info) - || updatedDots.test(packageUserKey); - - ItemOperator op = (info, v) -> { - if (info instanceof WorkspaceItemInfo && v instanceof BubbleTextView) { - if (matcher.test(info)) { - ((BubbleTextView) v).applyDotState(info, true /* animate */); - } - } else if (info instanceof FolderInfo && v instanceof FolderIcon) { - FolderInfo fi = (FolderInfo) info; - if (fi.anyMatch(matcher)) { - FolderDotInfo folderDotInfo = new FolderDotInfo(); - for (ItemInfo si : fi.getContents()) { - folderDotInfo.addDotInfo(mLauncher.getDotInfoForItem(si)); - } - ((FolderIcon) v).setDotInfo(folderDotInfo); - } - } - - // process all the shortcuts - return false; - }; - - mapOverItems(op); - Folder folder = Folder.getOpen(mLauncher); - if (folder != null) { - folder.iterateOverItems(op); - } - } - /** * Remove workspace icons & widget information related to items in matcher. * diff --git a/src/com/android/launcher3/popup/PopupDataProvider.java b/src/com/android/launcher3/popup/PopupDataProvider.java index 8a5e388c50..318b3ceffa 100644 --- a/src/com/android/launcher3/popup/PopupDataProvider.java +++ b/src/com/android/launcher3/popup/PopupDataProvider.java @@ -23,20 +23,27 @@ import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; +import com.android.launcher3.BubbleTextView; +import com.android.launcher3.allapps.ActivityAllAppsContainerView; import com.android.launcher3.dot.DotInfo; +import com.android.launcher3.dot.FolderDotInfo; +import com.android.launcher3.folder.Folder; +import com.android.launcher3.folder.FolderIcon; +import com.android.launcher3.model.data.FolderInfo; import com.android.launcher3.model.data.ItemInfo; import com.android.launcher3.notification.NotificationKeyData; import com.android.launcher3.notification.NotificationListener; import com.android.launcher3.util.ComponentKey; +import com.android.launcher3.util.LauncherBindableItemsContainer.ItemOperator; import com.android.launcher3.util.PackageUserKey; import com.android.launcher3.util.ShortcutUtil; +import com.android.launcher3.views.ActivityContext; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.function.Consumer; import java.util.function.Predicate; /** @@ -47,19 +54,49 @@ public class PopupDataProvider implements NotificationListener.NotificationsChan private static final boolean LOGD = false; private static final String TAG = "PopupDataProvider"; - private final Consumer> mNotificationDotsChangeListener; + private final ActivityContext mContext; + + /** Maps packages to their DotInfo's . */ + private final Map mPackageUserToDotInfos = new HashMap<>(); /** Maps launcher activity components to a count of how many shortcuts they have. */ private HashMap mDeepShortcutMap = new HashMap<>(); - /** Maps packages to their DotInfo's . */ - private Map mPackageUserToDotInfos = new HashMap<>(); - public PopupDataProvider(Consumer> notificationDotsChangeListener) { - mNotificationDotsChangeListener = notificationDotsChangeListener; + public PopupDataProvider(ActivityContext context) { + mContext = context; } private void updateNotificationDots(Predicate updatedDots) { - mNotificationDotsChangeListener.accept(updatedDots); + final PackageUserKey packageUserKey = new PackageUserKey(null, null); + Predicate matcher = info -> !packageUserKey.updateFromItemInfo(info) + || updatedDots.test(packageUserKey); + + ItemOperator op = (info, v) -> { + if (v instanceof BubbleTextView && info != null && matcher.test(info)) { + ((BubbleTextView) v).applyDotState(info, true /* animate */); + } else if (v instanceof FolderIcon icon + && info instanceof FolderInfo fi && fi.anyMatch(matcher)) { + FolderDotInfo folderDotInfo = new FolderDotInfo(); + for (ItemInfo si : fi.getContents()) { + folderDotInfo.addDotInfo(getDotInfoForItem(si)); + } + icon.setDotInfo(folderDotInfo); + } + + // process all the shortcuts + return false; + }; + + mContext.getContent().mapOverItems(op); + Folder folder = Folder.getOpen(mContext); + if (folder != null) { + folder.iterateOverItems(op); + } + + ActivityAllAppsContainerView appsView = mContext.getAppsView(); + if (appsView != null) { + appsView.getAppsStore().updateNotificationDots(updatedDots); + } } @Override diff --git a/src/com/android/launcher3/secondarydisplay/SecondaryDisplayLauncher.java b/src/com/android/launcher3/secondarydisplay/SecondaryDisplayLauncher.java index b1653d0fab..0c7e69b95f 100644 --- a/src/com/android/launcher3/secondarydisplay/SecondaryDisplayLauncher.java +++ b/src/com/android/launcher3/secondarydisplay/SecondaryDisplayLauncher.java @@ -29,6 +29,7 @@ import android.view.View.OnClickListener; import android.view.ViewAnimationUtils; import android.view.inputmethod.InputMethodManager; +import androidx.annotation.NonNull; import androidx.annotation.UiThread; import com.android.launcher3.AbstractFloatingView; @@ -131,8 +132,7 @@ public class SecondaryDisplayLauncher extends BaseActivity } mDragController.addDragListener(this); - mPopupDataProvider = new PopupDataProvider( - mAppsView.getAppsStore()::updateNotificationDots); + mPopupDataProvider = new PopupDataProvider(this); mModel.addCallbacksAndLoad(this); } @@ -306,6 +306,8 @@ public class SecondaryDisplayLauncher extends BaseActivity mStringCache = cache; } + @Override + @NonNull public PopupDataProvider getPopupDataProvider() { return mPopupDataProvider; } diff --git a/src/com/android/launcher3/views/ActivityContext.java b/src/com/android/launcher3/views/ActivityContext.java index bbea043820..9733e27399 100644 --- a/src/com/android/launcher3/views/ActivityContext.java +++ b/src/com/android/launcher3/views/ActivityContext.java @@ -80,6 +80,7 @@ import com.android.launcher3.model.data.WorkspaceItemInfo; import com.android.launcher3.popup.PopupDataProvider; import com.android.launcher3.util.ActivityOptionsWrapper; import com.android.launcher3.util.ApplicationInfoWrapper; +import com.android.launcher3.util.LauncherBindableItemsContainer; import com.android.launcher3.util.Preconditions; import com.android.launcher3.util.RunnableList; import com.android.launcher3.util.SplitConfigurationOptions; @@ -101,10 +102,6 @@ public interface ActivityContext { return false; } - default DotInfo getDotInfoForItem(ItemInfo info) { - return null; - } - default AccessibilityDelegate getAccessibilityDelegate() { return null; } @@ -193,6 +190,14 @@ public interface ActivityContext { return null; } + /** + * Returns the primary content of this context + */ + @NonNull + default LauncherBindableItemsContainer getContent() { + return op -> { }; + } + /** * The all apps container, if it exists in this context. */ @@ -286,9 +291,13 @@ public interface ActivityContext { return v -> false; } - @Nullable + @NonNull default PopupDataProvider getPopupDataProvider() { - return null; + return new PopupDataProvider(this); + } + + default DotInfo getDotInfoForItem(ItemInfo info) { + return getPopupDataProvider().getDotInfoForItem(info); } /** diff --git a/tests/multivalentTests/src/com/android/launcher3/util/TestSandboxModelContextWrapper.java b/tests/multivalentTests/src/com/android/launcher3/util/TestSandboxModelContextWrapper.java index 393282f442..7183cfd83c 100644 --- a/tests/multivalentTests/src/com/android/launcher3/util/TestSandboxModelContextWrapper.java +++ b/tests/multivalentTests/src/com/android/launcher3/util/TestSandboxModelContextWrapper.java @@ -22,6 +22,7 @@ import static com.android.launcher3.util.MainThreadInitializedObject.SandboxCont import android.content.ContextWrapper; +import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.test.platform.app.InstrumentationRegistry; @@ -57,7 +58,7 @@ public class TestSandboxModelContextWrapper extends ActivityContextWrapper imple protected ActivityAllAppsContainerView mAppsView; - private final PopupDataProvider mPopupDataProvider = new PopupDataProvider(i -> {}); + private final PopupDataProvider mPopupDataProvider = new PopupDataProvider(this); private final WidgetPickerDataProvider mWidgetPickerDataProvider = new WidgetPickerDataProvider(); protected final UserCache mUserCache; @@ -80,7 +81,7 @@ public class TestSandboxModelContextWrapper extends ActivityContextWrapper imple mAllAppsStore = mAppsView.getAppsStore(); } - @Nullable + @NonNull @Override public PopupDataProvider getPopupDataProvider() { return mPopupDataProvider; From 39f902cd840a7e007bd817371f87771a98bc25a8 Mon Sep 17 00:00:00 2001 From: Charlie Anderson Date: Wed, 26 Feb 2025 19:30:53 +0000 Subject: [PATCH 139/153] Make Folder preview items appear as square grid instead of circle - Eventually we should remove circular geometry from ClippedFolderIconLayoutRule altogether Bug: 392610664 Test: changing shapes with different size folders Flag: com.android.launcher3.enable_launcher_icon_shapes Change-Id: I15c854c19186a3e4262e8d2b40960f3519ec2729 --- .../folder/ClippedFolderIconLayoutRule.java | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/com/android/launcher3/folder/ClippedFolderIconLayoutRule.java b/src/com/android/launcher3/folder/ClippedFolderIconLayoutRule.java index cf5150a751..36dad89e9a 100644 --- a/src/com/android/launcher3/folder/ClippedFolderIconLayoutRule.java +++ b/src/com/android/launcher3/folder/ClippedFolderIconLayoutRule.java @@ -53,8 +53,18 @@ public class ClippedFolderIconLayoutRule { } else if (index >= MAX_NUM_ITEMS_IN_PREVIEW) { // Items beyond those displayed in the preview are animated to the center mTmpPoint[0] = mTmpPoint[1] = mAvailableSpace / 2 - (mIconSize * totalScale) / 2; - } else { - getPosition(index, curNumItems, mTmpPoint); + } else if (index == 0) { + // top left + getGridPosition(0, 0, mTmpPoint); + } else if (index == 1) { + // top right + getGridPosition(0, 1, mTmpPoint); + } else if (index == 2) { + // bottom left + getGridPosition(1, 0, mTmpPoint); + } else if (index == 3) { + // bottom right + getGridPosition(1, 1, mTmpPoint); } transX = mTmpPoint[0]; From 536097dec202066c5ef2d4509ac26b71fd99d54a Mon Sep 17 00:00:00 2001 From: Jagrut Desai Date: Thu, 27 Feb 2025 09:34:58 -0800 Subject: [PATCH 140/153] Update Taskbar Icon content description to include state description This cl inlcudes: while user is in desktop mode, we will add state description(active, minimized) of each app icon to it's content description. Test: Manual Bug: 397555157 Flag: EXEMPT bugfix Change-Id: Iaec18e7099108e8b076b76c637a41e29ed837265 --- .../taskbar/TaskbarViewController.java | 13 ++++++++++ res/values/strings.xml | 3 +++ src/com/android/launcher3/BubbleTextView.java | 26 +++++++++++++++++-- 3 files changed, 40 insertions(+), 2 deletions(-) diff --git a/quickstep/src/com/android/launcher3/taskbar/TaskbarViewController.java b/quickstep/src/com/android/launcher3/taskbar/TaskbarViewController.java index 384468c9fc..78c22d2fbf 100644 --- a/quickstep/src/com/android/launcher3/taskbar/TaskbarViewController.java +++ b/quickstep/src/com/android/launcher3/taskbar/TaskbarViewController.java @@ -83,6 +83,8 @@ import com.android.launcher3.model.data.ItemInfo; import com.android.launcher3.model.data.TaskItemInfo; import com.android.launcher3.taskbar.bubbles.BubbleBarController; import com.android.launcher3.taskbar.bubbles.BubbleControllers; +import com.android.launcher3.taskbar.customization.TaskbarAllAppsButtonContainer; +import com.android.launcher3.taskbar.customization.TaskbarDividerContainer; import com.android.launcher3.util.DisplayController; import com.android.launcher3.util.ItemInfoMatcher; import com.android.launcher3.util.LauncherBindableItemsContainer; @@ -735,10 +737,21 @@ public class TaskbarViewController implements TaskbarControllers.LoggableTaskbar for (View iconView : getIconViews()) { if (iconView instanceof BubbleTextView btv) { btv.updateRunningState(getRunningAppState(btv)); + if (shouldUpdateIconContentDescription(btv)) { + btv.setContentDescription( + btv.getContentDescription() + " " + btv.getIconStateDescription()); + } } } } + private boolean shouldUpdateIconContentDescription(BubbleTextView btv) { + boolean isInDesktopMode = mControllers.taskbarDesktopModeController.isInDesktopMode(); + boolean isAllAppsButton = btv instanceof TaskbarAllAppsButtonContainer; + boolean isDividerButton = btv instanceof TaskbarDividerContainer; + return isInDesktopMode && !isAllAppsButton && !isDividerButton; + } + /** * @return A set of Task ids of running apps that are pinned in the taskbar. */ diff --git a/res/values/strings.xml b/res/values/strings.xml index a02516a44f..56befd679f 100644 --- a/res/values/strings.xml +++ b/res/values/strings.xml @@ -293,6 +293,9 @@ New home screen page + Active + Minimized + Folder opened, %1$d by %2$d diff --git a/src/com/android/launcher3/BubbleTextView.java b/src/com/android/launcher3/BubbleTextView.java index bd42b2b855..730ad7858e 100644 --- a/src/com/android/launcher3/BubbleTextView.java +++ b/src/com/android/launcher3/BubbleTextView.java @@ -20,6 +20,9 @@ import static android.graphics.fonts.FontStyle.FONT_WEIGHT_BOLD; import static android.graphics.fonts.FontStyle.FONT_WEIGHT_NORMAL; import static android.text.Layout.Alignment.ALIGN_NORMAL; +import static com.android.launcher3.BubbleTextView.RunningAppState.RUNNING; +import static com.android.launcher3.BubbleTextView.RunningAppState.NOT_RUNNING; +import static com.android.launcher3.BubbleTextView.RunningAppState.MINIMIZED; import static com.android.launcher3.Flags.enableContrastTiles; import static com.android.launcher3.Flags.enableCursorHoverStates; import static com.android.launcher3.graphics.PreloadIconDrawable.newPendingIcon; @@ -208,6 +211,9 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver, private final int mRunningAppIndicatorColor; private final int mMinimizedAppIndicatorColor; + private final String mMinimizedStateDescription; + private final String mRunningStateDescription; + /** * Various options for the running state of an app. */ @@ -240,6 +246,9 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver, super(context, attrs, defStyle); mActivity = ActivityContext.lookupContext(context); FastBitmapDrawable.setFlagHoverEnabled(enableCursorHoverStates()); + mMinimizedStateDescription = getContext().getString( + R.string.app_minimized_state_description); + mRunningStateDescription = getContext().getString(R.string.app_running_state_description); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.BubbleTextView, defStyle, 0); @@ -432,6 +441,19 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver, invalidate(); } + /** + * Returns state description of this icon. + */ + public String getIconStateDescription() { + if (mRunningAppState == MINIMIZED) { + return mMinimizedStateDescription; + } else if (mRunningAppState == RUNNING) { + return mRunningStateDescription; + } else { + return ""; + } + } + protected void setItemInfo(ItemInfoWithIcon itemInfo) { setTag(itemInfo); } @@ -768,13 +790,13 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver, /** Draws a line under the app icon if this is representing a running app in Desktop Mode. */ protected void drawRunningAppIndicatorIfNecessary(Canvas canvas) { - if (mRunningAppState == RunningAppState.NOT_RUNNING || mDisplay != DISPLAY_TASKBAR) { + if (mRunningAppState == NOT_RUNNING || mDisplay != DISPLAY_TASKBAR) { return; } getIconBounds(mRunningAppIconBounds); Utilities.scaleRectAboutCenter(mRunningAppIconBounds, ICON_VISIBLE_AREA_FACTOR); - final boolean isMinimized = mRunningAppState == RunningAppState.MINIMIZED; + final boolean isMinimized = mRunningAppState == MINIMIZED; final int indicatorTop = mRunningAppIconBounds.bottom + mRunningAppIndicatorTopMargin; final int indicatorWidth = isMinimized ? mMinimizedAppIndicatorWidth : mRunningAppIndicatorWidth; From d237c9587b70ccd8e4123ed46ace5fea70328841 Mon Sep 17 00:00:00 2001 From: Sunny Goyal Date: Thu, 27 Feb 2025 10:33:50 -0800 Subject: [PATCH 141/153] Converting LauncherBindableItemsContainer to kotlin Bug: 393703968 Flag: EXEMPT refactor Test: Presubmit Change-Id: I4d2fa18b6b275742d84de16ed604987c2deee6e8 --- .../util/LauncherBindableItemsContainer.java | 86 ------------------- .../util/LauncherBindableItemsContainer.kt | 74 ++++++++++++++++ 2 files changed, 74 insertions(+), 86 deletions(-) delete mode 100644 src/com/android/launcher3/util/LauncherBindableItemsContainer.java create mode 100644 src/com/android/launcher3/util/LauncherBindableItemsContainer.kt diff --git a/src/com/android/launcher3/util/LauncherBindableItemsContainer.java b/src/com/android/launcher3/util/LauncherBindableItemsContainer.java deleted file mode 100644 index 20e3eafcfb..0000000000 --- a/src/com/android/launcher3/util/LauncherBindableItemsContainer.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (C) 2021 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.launcher3.util; - -import android.view.View; - -import com.android.launcher3.BubbleTextView; -import com.android.launcher3.apppairs.AppPairIcon; -import com.android.launcher3.folder.Folder; -import com.android.launcher3.folder.FolderIcon; -import com.android.launcher3.model.data.AppPairInfo; -import com.android.launcher3.model.data.FolderInfo; -import com.android.launcher3.model.data.ItemInfo; -import com.android.launcher3.model.data.WorkspaceItemInfo; -import com.android.launcher3.views.ActivityContext; -import com.android.launcher3.widget.PendingAppWidgetHostView; - -import java.util.Set; - -/** - * Interface representing a container which can bind Launcher items with some utility methods - */ -public interface LauncherBindableItemsContainer { - - /** - * Called to update workspace items as a result of - * {@link com.android.launcher3.model.BgDataModel.Callbacks#bindItemsUpdated(Set)} - */ - default void updateContainerItems(Set updates, ActivityContext context) { - ItemOperator op = (info, v) -> { - if (v instanceof BubbleTextView shortcut - && info instanceof WorkspaceItemInfo wii - && updates.contains(info)) { - shortcut.applyFromWorkspaceItem(wii); - } else if (info instanceof FolderInfo && v instanceof FolderIcon folderIcon) { - folderIcon.updatePreviewItems(updates::contains); - } else if (info instanceof AppPairInfo && v instanceof AppPairIcon appPairIcon) { - appPairIcon.maybeRedrawForWorkspaceUpdate(updates::contains); - } else if (v instanceof PendingAppWidgetHostView pendingView - && updates.contains(info)) { - pendingView.applyState(); - pendingView.postProviderAvailabilityCheck(); - } - - // Iterate all items - return false; - }; - - mapOverItems(op); - Folder openFolder = Folder.getOpen(context); - if (openFolder != null) { - openFolder.iterateOverItems(op); - } - } - - /** - * Map the operator over the shortcuts and widgets. - * - * @param op the operator to map over the shortcuts - */ - void mapOverItems(ItemOperator op); - - interface ItemOperator { - /** - * Process the next itemInfo, possibly with side-effect on the next item. - * - * @param info info for the shortcut - * @param view view for the shortcut - * @return true if done, false to continue the map - */ - boolean evaluate(ItemInfo info, View view); - } -} diff --git a/src/com/android/launcher3/util/LauncherBindableItemsContainer.kt b/src/com/android/launcher3/util/LauncherBindableItemsContainer.kt new file mode 100644 index 0000000000..16617962bd --- /dev/null +++ b/src/com/android/launcher3/util/LauncherBindableItemsContainer.kt @@ -0,0 +1,74 @@ +/* + * Copyright (C) 2021 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.launcher3.util + +import android.view.View +import com.android.launcher3.BubbleTextView +import com.android.launcher3.apppairs.AppPairIcon +import com.android.launcher3.folder.Folder +import com.android.launcher3.folder.FolderIcon +import com.android.launcher3.model.data.AppPairInfo +import com.android.launcher3.model.data.FolderInfo +import com.android.launcher3.model.data.ItemInfo +import com.android.launcher3.model.data.WorkspaceItemInfo +import com.android.launcher3.views.ActivityContext +import com.android.launcher3.widget.PendingAppWidgetHostView + +/** Interface representing a container which can bind Launcher items with some utility methods */ +interface LauncherBindableItemsContainer { + + /** + * Called to update workspace items as a result of {@link + * com.android.launcher3.model.BgDataModel.Callbacks#bindItemsUpdated(Set)} + */ + fun updateContainerItems(updates: Set, context: ActivityContext) { + val op = ItemOperator { info, v -> + when { + v is BubbleTextView && info is WorkspaceItemInfo && updates.contains(info) -> + v.applyFromWorkspaceItem(info) + v is FolderIcon && info is FolderInfo -> v.updatePreviewItems(updates::contains) + v is AppPairIcon && info is AppPairInfo -> + v.maybeRedrawForWorkspaceUpdate(updates::contains) + v is PendingAppWidgetHostView && updates.contains(info) -> { + v.applyState() + v.postProviderAvailabilityCheck() + } + } + + // Iterate all items + false + } + + mapOverItems(op) + Folder.getOpen(context)?.iterateOverItems(op) + } + + /** Map the [op] over the shortcuts and widgets. */ + fun mapOverItems(op: ItemOperator) + + fun interface ItemOperator { + + /** + * Process the next itemInfo, possibly with side-effect on the next item. + * + * @param info info for the shortcut + * @param view view for the shortcut + * @return true if done, false to continue the map + */ + fun evaluate(info: ItemInfo?, view: View): Boolean + } +} From 4160ad396772fcf66052532c482d61a04fbe5466 Mon Sep 17 00:00:00 2001 From: Sihua Ma Date: Thu, 27 Feb 2025 00:29:53 +0000 Subject: [PATCH 142/153] Fix jumpcuts in folder background color when opening/closing Background drawable is not associated with any folder view, and as a result invalidating the drawable doesn't cause it to be redrawn on the screen Fix: 392617057 Bug: 399674389 Test: Manual Flag: EXEMPT bug fix Change-Id: I6d2bd97f66b53cdbeb4a715e53ff89b3450546f0 --- src/com/android/launcher3/folder/Folder.java | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/com/android/launcher3/folder/Folder.java b/src/com/android/launcher3/folder/Folder.java index fb48a4d559..0ce72494a8 100644 --- a/src/com/android/launcher3/folder/Folder.java +++ b/src/com/android/launcher3/folder/Folder.java @@ -65,6 +65,7 @@ import android.view.inputmethod.EditorInfo; import android.widget.TextView; import androidx.annotation.IntDef; +import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import androidx.core.content.res.ResourcesCompat; @@ -261,7 +262,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo @Nullable private KeyboardInsetAnimationCallback mKeyboardInsetAnimationCallback; - private GradientDrawable mBackground; + private final @NonNull GradientDrawable mBackground; /** * Used to inflate the Workspace from XML. @@ -283,6 +284,10 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo // click). setFocusableInTouchMode(true); + mBackground = (GradientDrawable) Objects.requireNonNull( + ResourcesCompat.getDrawable(getResources(), + R.drawable.round_rect_folder, getContext().getTheme())); + mBackground.setCallback(this); } @Override @@ -296,9 +301,6 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo final DeviceProfile dp = mActivityContext.getDeviceProfile(); final int paddingLeftRight = dp.folderContentPaddingLeftRight; - mBackground = (GradientDrawable) ResourcesCompat.getDrawable(getResources(), - R.drawable.round_rect_folder, getContext().getTheme()); - mContent = findViewById(R.id.folder_content); mContent.setPadding(paddingLeftRight, dp.folderContentPaddingTop, paddingLeftRight, 0); mContent.setFolder(this); @@ -345,6 +347,11 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo return true; } + @Override + protected boolean verifyDrawable(@NonNull Drawable who) { + return super.verifyDrawable(who) || (who == mBackground); + } + void callBeginDragShared(View v, DragOptions options) { mLauncherDelegate.beginDragShared(v, this, options); } From 94e276c1c5f477d687a0cced04c1d715ce8e111c Mon Sep 17 00:00:00 2001 From: Shamali P Date: Wed, 26 Feb 2025 15:14:32 +0000 Subject: [PATCH 143/153] Fix home screen page description when removing an existing page. When we remove an in-between or last empty page, we manually set the current page but don't update the description that's set on the accessibility view. Due to which, when talkback focuses on it, it sees the stale page count in the description. This fix ensures to keep the state updated during removal. Bug: 390360063 Fix: 390360063 Test: Talkback Flag: EXEMPT BUGFIX Change-Id: Idd9a54d3a1ee43e56f51db78e614776eca6a12f7 --- src/com/android/launcher3/Workspace.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/com/android/launcher3/Workspace.java b/src/com/android/launcher3/Workspace.java index 94ff44145b..632cdf929b 100644 --- a/src/com/android/launcher3/Workspace.java +++ b/src/com/android/launcher3/Workspace.java @@ -893,6 +893,9 @@ public class Workspace extends PagedView mScreenOrder.removeValue(extraEmptyPageId); }); + // Since we removed some screens, before moving to next page, update the state + // description with correct page numbers. + updateAccessibilityViewPageDescription(); setCurrentPage(getNextPage()); // Update the page indicator to reflect the removed page. @@ -1118,6 +1121,9 @@ public class Workspace extends PagedView if (pageShift >= 0) { setCurrentPage(currentPage - pageShift); } + + // Now that we have removed some pages, ensure state description is up to date. + updateAccessibilityViewPageDescription(); } /** @@ -3513,6 +3519,18 @@ public class Workspace extends PagedView protected void announcePageForAccessibility() { // Talkback focuses on AccessibilityActionView by default, so we need to modify the state // description there in order for the change in page scroll to be announced. + updateAccessibilityViewPageDescription(); + } + + /** + * Updates the state description that is set on the accessibility actions view for the + * workspace. + *

The updated value is called out when talkback focuses on the view and is not disruptive. + *

+ */ + protected void updateAccessibilityViewPageDescription() { + // Set the state description on accessibility action view so that when it is focused, + // talkback describes the correct state of home screen pages. ViewCompat.setStateDescription(mLauncher.getAccessibilityActionView(), getCurrentPageDescription()); } From 29b75b52492133b568015d3e2aefb603c48d7f12 Mon Sep 17 00:00:00 2001 From: Justin Yun Date: Fri, 28 Feb 2025 05:29:09 +0900 Subject: [PATCH 144/153] Launcher3 is in system_ext container As Launcher3 is installed in system_ext, com_android_launcher3_flags is in the system_ext container. Aconfig flags must set the same container with their declaration. Bug: 385213580 Test: "adb shell aflags list" must not be changed. Flag: EXEMPT refactor Change-Id: I433756dda120de253909db663a6ecfd47d26c65d --- aconfig/launcher_growth.aconfig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/aconfig/launcher_growth.aconfig b/aconfig/launcher_growth.aconfig index 35a91d72a8..a880538dbf 100644 --- a/aconfig/launcher_growth.aconfig +++ b/aconfig/launcher_growth.aconfig @@ -1,5 +1,5 @@ package: "com.android.launcher3" -container: "system" +container: "system_ext" flag { name: "enable_growth_nudge" From fc2735ed960a021953860b8a626c0bbdd2c0665b Mon Sep 17 00:00:00 2001 From: Sunny Goyal Date: Thu, 27 Feb 2025 12:33:21 -0800 Subject: [PATCH 145/153] Fixing widgets broken during reconfiguration Async widget inflation may complete after the updates have been deferred, leading the widget to a broken state. Reapply widget if its root content changed while deferred Bug: 375442765 Bug: 327696338 Test: Verified manually Flag: EXEMPT bugfix Change-Id: I78d0f4ce92ee9bd2ee001de3a0e181f2e727218c --- .../widget/LauncherAppWidgetHostView.java | 32 +++++++++++++------ 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/src/com/android/launcher3/widget/LauncherAppWidgetHostView.java b/src/com/android/launcher3/widget/LauncherAppWidgetHostView.java index b07d8076ec..7a44c6ac89 100644 --- a/src/com/android/launcher3/widget/LauncherAppWidgetHostView.java +++ b/src/com/android/launcher3/widget/LauncherAppWidgetHostView.java @@ -79,7 +79,8 @@ public class LauncherAppWidgetHostView extends BaseLauncherAppWidgetHostView private Runnable mAutoAdvanceRunnable; private long mDeferUpdatesUntilMillis = 0; - RemoteViews mLastRemoteViews; + private RemoteViews mLastRemoteViews; + private boolean mReapplyOnResumeUpdates = false; private boolean mTrackingWidgetUpdate = false; @@ -138,11 +139,11 @@ public class LauncherAppWidgetHostView extends BaseLauncherAppWidgetHostView TRACE_METHOD_NAME + getAppWidgetInfo().provider, getAppWidgetId()); mTrackingWidgetUpdate = false; } - if (isDeferringUpdates()) { - mLastRemoteViews = remoteViews; + mLastRemoteViews = remoteViews; + mReapplyOnResumeUpdates = isDeferringUpdates(); + if (mReapplyOnResumeUpdates) { return; } - mLastRemoteViews = null; super.updateAppWidget(remoteViews); @@ -150,6 +151,18 @@ public class LauncherAppWidgetHostView extends BaseLauncherAppWidgetHostView checkIfAutoAdvance(); } + @Override + public void onViewAdded(View child) { + super.onViewAdded(child); + mReapplyOnResumeUpdates |= isDeferringUpdates(); + } + + @Override + public void onViewRemoved(View child) { + super.onViewRemoved(child); + mReapplyOnResumeUpdates |= isDeferringUpdates(); + } + private boolean checkScrollableRecursively(ViewGroup viewGroup) { if (viewGroup instanceof AdapterView) { return true; @@ -204,18 +217,16 @@ public class LauncherAppWidgetHostView extends BaseLauncherAppWidgetHostView * {@link #updateAppWidget} and apply any deferred updates. */ public void endDeferringUpdates() { - RemoteViews remoteViews; mDeferUpdatesUntilMillis = 0; - remoteViews = mLastRemoteViews; - - if (remoteViews != null) { - updateAppWidget(remoteViews); + if (mReapplyOnResumeUpdates) { + updateAppWidget(mLastRemoteViews); } } + @Override public boolean onInterceptTouchEvent(MotionEvent ev) { if (ev.getAction() == MotionEvent.ACTION_DOWN) { - BaseDragLayer dragLayer = mActivityContext.getDragLayer(); + BaseDragLayer dragLayer = mActivityContext.getDragLayer(); if (mIsScrollable) { dragLayer.requestDisallowInterceptTouchEvent(true); } @@ -225,6 +236,7 @@ public class LauncherAppWidgetHostView extends BaseLauncherAppWidgetHostView return mLongPressHelper.hasPerformedLongPress(); } + @Override public boolean onTouchEvent(MotionEvent ev) { mLongPressHelper.onTouchEvent(ev); // We want to keep receiving though events to be able to cancel long press on ACTION_UP From c666b9587b5c43f0973c9d8a6b42f5de960c848b Mon Sep 17 00:00:00 2001 From: mpodolian Date: Mon, 24 Feb 2025 15:49:58 -0800 Subject: [PATCH 146/153] Added BubbleBarLocation drop target. A drop target for the BubbleBarLocation has been added. This implementation enables the Launcher process to handle application drag-and-drop actions onto the bubble bar. Known issues: 1) Upon dropping, the dragged icon animates back to its original taskbar position from the top-left corner. 2) The expanded view drop target is not presented. 3) When an icon is dropped on the opposite side of the bubble bar, the resulting location does not change, even though the drop target is correctly displayed. Bug: 397459664 Flag: com.android.wm.shell.enable_create_any_bubble Test: Manual. Navigate to the overview screen, drag a taskbar icon to the left or right side, targeting the bubble bar drop zone. Verify the drop target's appearance. Then, drop the icon and observe that a new application bubble is added. Change-Id: I0f64a664620959f2503ac3fd711476b354a09348 --- .../taskbar/TaskbarDragController.java | 8 +- .../bubbles/BubbleBarLocationDropTarget.kt | 96 +++++++++++++++++++ .../bubbles/BubbleBarViewController.java | 84 +++++++++++++++- src/com/android/launcher3/DropTarget.java | 6 ++ .../launcher3/dragndrop/DragController.java | 2 +- 5 files changed, 192 insertions(+), 4 deletions(-) create mode 100644 quickstep/src/com/android/launcher3/taskbar/bubbles/BubbleBarLocationDropTarget.kt diff --git a/quickstep/src/com/android/launcher3/taskbar/TaskbarDragController.java b/quickstep/src/com/android/launcher3/taskbar/TaskbarDragController.java index d531e2c5a8..9b7e320892 100644 --- a/quickstep/src/com/android/launcher3/taskbar/TaskbarDragController.java +++ b/quickstep/src/com/android/launcher3/taskbar/TaskbarDragController.java @@ -68,6 +68,7 @@ import com.android.launcher3.dragndrop.DragDriver; import com.android.launcher3.dragndrop.DragOptions; import com.android.launcher3.dragndrop.DragView; import com.android.launcher3.dragndrop.DraggableView; +import com.android.launcher3.folder.Folder; import com.android.launcher3.graphics.DragPreviewProvider; import com.android.launcher3.logger.LauncherAtom.ContainerInfo; import com.android.launcher3.logging.StatsLogManager; @@ -765,8 +766,11 @@ public class TaskbarDragController extends DragController im @Override public void addDropTarget(DropTarget target) { - // No-op as Taskbar currently doesn't support any drop targets internally. - // Note: if we do add internal DropTargets, we'll still need to ignore Folder. + if (target instanceof Folder) { + // we need to ignore Folder. + return; + } + super.addDropTarget(target); } @Override diff --git a/quickstep/src/com/android/launcher3/taskbar/bubbles/BubbleBarLocationDropTarget.kt b/quickstep/src/com/android/launcher3/taskbar/bubbles/BubbleBarLocationDropTarget.kt new file mode 100644 index 0000000000..383f4d2020 --- /dev/null +++ b/quickstep/src/com/android/launcher3/taskbar/bubbles/BubbleBarLocationDropTarget.kt @@ -0,0 +1,96 @@ +/* + * 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.launcher3.taskbar.bubbles + +import android.graphics.Rect +import android.view.View +import com.android.launcher3.DropTarget +import com.android.launcher3.dragndrop.DragOptions +import com.android.launcher3.model.data.ItemInfo +import com.android.wm.shell.shared.bubbles.BubbleBarLocation + +/** + * Implementation of the {@link DropTarget} that handles drag and drop events over the bubble bar + * locations. + */ +class BubbleBarLocationDropTarget( + private val bubbleBarLocation: BubbleBarLocation, + private val bubbleBarDragListener: BubbleBarDragListener, +) : DropTarget { + + /** Controller that takes care of the bubble bar drag events inside launcher process. */ + interface BubbleBarDragListener { + + /** Called when the drag event is over the bubble bar drop zone. */ + fun onLauncherItemDraggedOverBubbleBarDragZone(location: BubbleBarLocation) + + /** Called when the drag event leaves the bubble bar drop zone. */ + fun onLauncherItemDraggedOutsideBubbleBarDropZone() + + /** Called when the drop event happens over the bubble bar drop zone. */ + fun onLauncherItemDroppedOverBubbleBarDragZone( + location: BubbleBarLocation, + itemInfo: ItemInfo, + ) + + /** Gets the hit [rect][android.graphics.Rect] of the bubble bar location. */ + fun getBubbleBarLocationHitRect(bubbleBarLocation: BubbleBarLocation, outRect: Rect) + + /** Provides the view that will accept the drop. */ + fun getDropView(): View + } + + private var isShowingDropTarget = false + + override fun isDropEnabled(): Boolean = true + + override fun onDrop(dragObject: DropTarget.DragObject, options: DragOptions) { + val itemInfo = dragObject.dragInfo ?: return + // TODO(b/397459664) : fix task bar icon animation after drop + // TODO(b/397459664) : update bubble bar location + bubbleBarDragListener.onLauncherItemDroppedOverBubbleBarDragZone( + bubbleBarLocation, + itemInfo, + ) + } + + override fun onDragEnter(dragObject: DropTarget.DragObject) {} + + override fun onDragOver(dragObject: DropTarget.DragObject) { + if (isShowingDropTarget) return + isShowingDropTarget = true + bubbleBarDragListener.onLauncherItemDraggedOverBubbleBarDragZone(bubbleBarLocation) + } + + override fun onDragExit(dragObject: DropTarget.DragObject) { + // TODO(b/397459664) : fix the issue for no bubbles, when moving task bar icon out of + // the bubble bar drag zone drag ends and swipes gesture swipes the overview + if (!isShowingDropTarget) return + isShowingDropTarget = false + bubbleBarDragListener.onLauncherItemDraggedOutsideBubbleBarDropZone() + } + + override fun acceptDrop(dragObject: DropTarget.DragObject): Boolean = true + + override fun prepareAccessibilityDrop() {} + + override fun getHitRectRelativeToDragLayer(outRect: Rect) { + bubbleBarDragListener.getBubbleBarLocationHitRect(bubbleBarLocation, outRect) + } + + override fun getDropView(): View = bubbleBarDragListener.getDropView() +} diff --git a/quickstep/src/com/android/launcher3/taskbar/bubbles/BubbleBarViewController.java b/quickstep/src/com/android/launcher3/taskbar/bubbles/BubbleBarViewController.java index b90a5b001a..beda30c3b3 100644 --- a/quickstep/src/com/android/launcher3/taskbar/bubbles/BubbleBarViewController.java +++ b/quickstep/src/com/android/launcher3/taskbar/bubbles/BubbleBarViewController.java @@ -24,6 +24,8 @@ import static com.android.launcher3.taskbar.TaskbarPinningController.PINNING_TRA import android.animation.Animator; import android.animation.AnimatorSet; +import android.content.Intent; +import android.content.pm.ShortcutInfo; import android.content.res.Resources; import android.graphics.Point; import android.graphics.PointF; @@ -43,11 +45,15 @@ import com.android.launcher3.DeviceProfile; import com.android.launcher3.R; import com.android.launcher3.anim.AnimatedFloat; import com.android.launcher3.anim.RoundedRectRevealOutlineProvider; +import com.android.launcher3.model.data.ItemInfo; +import com.android.launcher3.model.data.WorkspaceItemInfo; import com.android.launcher3.taskbar.TaskbarActivityContext; import com.android.launcher3.taskbar.TaskbarControllers; +import com.android.launcher3.taskbar.TaskbarDragController; import com.android.launcher3.taskbar.TaskbarInsetsController; import com.android.launcher3.taskbar.TaskbarSharedState; import com.android.launcher3.taskbar.TaskbarStashController; +import com.android.launcher3.taskbar.bubbles.BubbleBarLocationDropTarget.BubbleBarDragListener; import com.android.launcher3.taskbar.bubbles.animation.BubbleBarViewAnimator; import com.android.launcher3.taskbar.bubbles.flyout.BubbleBarFlyoutController; import com.android.launcher3.taskbar.bubbles.flyout.BubbleBarFlyoutPositioner; @@ -59,6 +65,7 @@ import com.android.launcher3.util.MultiValueAlpha; import com.android.quickstep.SystemUiProxy; import com.android.wm.shell.Flags; import com.android.wm.shell.shared.bubbles.BubbleBarLocation; +import com.android.wm.shell.shared.bubbles.DeviceConfig; import java.io.PrintWriter; import java.util.List; @@ -117,6 +124,61 @@ public class BubbleBarViewController { updateTranslationY(); setBubbleBarScaleAndPadding(pinningProgress); }); + private final BubbleBarDragListener mDragListener = new BubbleBarDragListener() { + + @NonNull + @Override + public void getBubbleBarLocationHitRect(@NonNull BubbleBarLocation bubbleBarLocation, + Rect outRect) { + Point screenSize = DisplayController.INSTANCE.get(mActivity).getInfo().currentSize; + outRect.top = screenSize.y - mBubbleBarDropTargetSize; + outRect.bottom = screenSize.y; + if (bubbleBarLocation.isOnLeft(mBarView.isLayoutRtl())) { + outRect.left = 0; + outRect.right = mBubbleBarDropTargetSize; + } else { + outRect.left = screenSize.x - mBubbleBarDropTargetSize; + outRect.right = screenSize.x; + } + } + + @Override + public void onLauncherItemDroppedOverBubbleBarDragZone(@NonNull BubbleBarLocation location, + @NonNull ItemInfo itemInfo) { + //TODO(b/397459664) : fix task bar icon animation after drop + //TODO(b/397459664) : update bubble bar location + ShortcutInfo shortcutInfo = null; + if (itemInfo instanceof WorkspaceItemInfo) { + shortcutInfo = ((WorkspaceItemInfo) itemInfo).getDeepShortcutInfo(); + } + Intent itemIntent = itemInfo.getIntent(); + SystemUiProxy systemUiProxy = SystemUiProxy.INSTANCE.get(mActivity); + if (shortcutInfo != null) { + systemUiProxy.showShortcutBubble(shortcutInfo); + } else if (itemIntent != null && itemIntent.getComponent() != null) { + systemUiProxy.showAppBubble(itemIntent, itemInfo.user); + } + } + + @Override + public void onLauncherItemDraggedOutsideBubbleBarDropZone() { + //TODO(b/397459664) : hide expanded view drop target + onItemDraggedOutsideBubbleBarDropZone(); + } + + @Override + public void onLauncherItemDraggedOverBubbleBarDragZone( + @NonNull BubbleBarLocation location) { + //TODO(b/397459664) : show expanded view drop target + onDragItemOverBubbleBarDragZone(location); + } + + @NonNull + @Override + public View getDropView() { + return mBarView; + } + }; // Modified when swipe up is happening on the bubble bar or task bar. private float mBubbleBarSwipeUpTranslationY; @@ -139,8 +201,12 @@ public class BubbleBarViewController { private BubbleBarFlyoutController mBubbleBarFlyoutController; private BubbleBarPinController mBubbleBarPinController; private TaskbarSharedState mTaskbarSharedState; + private TaskbarDragController mTaskbarDragController; + private final BubbleBarLocationDropTarget mBubbleBarLeftDropTarget; + private final BubbleBarLocationDropTarget mBubbleBarRightDropTarget; private final TimeSource mTimeSource = System::currentTimeMillis; private final int mTaskbarTranslationDelta; + private final int mBubbleBarDropTargetSize; @Nullable private BubbleBarBoundsChangeListener mBoundsChangeListener; @@ -158,11 +224,21 @@ public class BubbleBarViewController { R.dimen.bubblebar_transient_taskbar_min_distance); mDragElevation = res.getDimensionPixelSize(R.dimen.bubblebar_drag_elevation); mTaskbarTranslationDelta = getBubbleBarTranslationDeltaForTaskbar(activity); + if (DeviceConfig.isSmallTablet(mActivity)) { + mBubbleBarDropTargetSize = res.getDimensionPixelSize(R.dimen.drag_zone_bubble_fold); + } else { + mBubbleBarDropTargetSize = res.getDimensionPixelSize(R.dimen.drag_zone_bubble_tablet); + } + mBubbleBarLeftDropTarget = new BubbleBarLocationDropTarget(BubbleBarLocation.LEFT, + mDragListener); + mBubbleBarRightDropTarget = new BubbleBarLocationDropTarget(BubbleBarLocation.RIGHT, + mDragListener); } /** Initializes controller. */ public void init(TaskbarControllers controllers, BubbleControllers bubbleControllers, TaskbarViewPropertiesProvider taskbarViewPropertiesProvider) { + mTaskbarDragController = controllers.taskbarDragController; mTaskbarSharedState = controllers.getSharedState(); mBubbleStashController = bubbleControllers.bubbleStashController; mBubbleBarController = bubbleControllers.bubbleBarController; @@ -264,6 +340,8 @@ public class BubbleBarViewController { mBubbleBarController.updateBubbleBarLocation(location, source); } }; + mTaskbarDragController.addDropTarget(mBubbleBarLeftDropTarget); + mTaskbarDragController.addDropTarget(mBubbleBarRightDropTarget); } /** Returns animated float property responsible for pinning transition animation. */ @@ -542,7 +620,9 @@ public class BubbleBarViewController { */ public void onDragItemOverBubbleBarDragZone(@NonNull BubbleBarLocation bubbleBarLocation) { mBarView.showDropTarget(/* isDropTarget = */ true); - mIsLocationUpdatedForDropTarget = getBubbleBarLocation() != bubbleBarLocation; + boolean isRtl = mBarView.isLayoutRtl(); + mIsLocationUpdatedForDropTarget = getBubbleBarLocation().isOnLeft(isRtl) + != bubbleBarLocation.isOnLeft(isRtl); if (mIsLocationUpdatedForDropTarget) { animateBubbleBarLocation(bubbleBarLocation); } @@ -1278,6 +1358,8 @@ public class BubbleBarViewController { /** Called when the controller is destroyed. */ public void onDestroy() { adjustTaskbarAndHotseatToBubbleBarState(/*isBubbleBarExpanded = */false); + mTaskbarDragController.removeDropTarget(mBubbleBarLeftDropTarget); + mTaskbarDragController.removeDropTarget(mBubbleBarRightDropTarget); } /** diff --git a/src/com/android/launcher3/DropTarget.java b/src/com/android/launcher3/DropTarget.java index 2d995103e7..7f0c7b50c0 100644 --- a/src/com/android/launcher3/DropTarget.java +++ b/src/com/android/launcher3/DropTarget.java @@ -18,6 +18,7 @@ package com.android.launcher3; import android.content.Context; import android.graphics.Rect; +import android.view.View; import com.android.launcher3.accessibility.DragViewStateAnnouncer; import com.android.launcher3.dragndrop.DragOptions; @@ -145,4 +146,9 @@ public interface DropTarget { // These methods are implemented in Views void getHitRectRelativeToDragLayer(Rect outRect); + + /** Returns the drop target view. By default, the implementor class is cast to the view. */ + default View getDropView() { + return (View) this; + } } diff --git a/src/com/android/launcher3/dragndrop/DragController.java b/src/com/android/launcher3/dragndrop/DragController.java index c50c008f30..613b4308eb 100644 --- a/src/com/android/launcher3/dragndrop/DragController.java +++ b/src/com/android/launcher3/dragndrop/DragController.java @@ -558,7 +558,7 @@ public abstract class DragController target.getHitRectRelativeToDragLayer(r); if (r.contains(x, y)) { - mActivity.getDragLayer().mapCoordInSelfToDescendant((View) target, + mActivity.getDragLayer().mapCoordInSelfToDescendant(target.getDropView(), mCoordinatesTemp); mDragObject.x = mCoordinatesTemp[0]; mDragObject.y = mCoordinatesTemp[1]; From 8bab8eb1716f518f7ca1f523c256a6c937e8cd48 Mon Sep 17 00:00:00 2001 From: Brian Isganitis Date: Tue, 25 Feb 2025 19:03:08 -0500 Subject: [PATCH 147/153] Remove TYPE_TASKBAR_OVERLAY_PROXY from TYPE_ACCESSIBLE. The invisible proxy view was preventing anything below it from being accessible. Flag: EXEMPT bugfix Fix: 377526512 Test: #14 in bug. Change-Id: I9d4596ebbbc4317a9ff7ded37b43b5fa1885e6ea --- src/com/android/launcher3/AbstractFloatingView.java | 3 ++- .../com/android/launcher3/tapl/LauncherInstrumentation.java | 4 +++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/com/android/launcher3/AbstractFloatingView.java b/src/com/android/launcher3/AbstractFloatingView.java index 753b2e2978..b90200b88c 100644 --- a/src/com/android/launcher3/AbstractFloatingView.java +++ b/src/com/android/launcher3/AbstractFloatingView.java @@ -126,7 +126,8 @@ public abstract class AbstractFloatingView extends LinearLayout implements Touch /** Type of popups that should get exclusive accessibility focus. */ public static final int TYPE_ACCESSIBLE = TYPE_ALL & ~TYPE_DISCOVERY_BOUNCE & ~TYPE_LISTENER & ~TYPE_ALL_APPS_EDU & ~TYPE_TASKBAR_ALL_APPS & ~TYPE_PIN_IME_POPUP - & ~TYPE_WIDGET_RESIZE_FRAME & ~TYPE_ONE_GRID_MIGRATION_EDU & ~TYPE_ON_BOARD_POPUP; + & ~TYPE_WIDGET_RESIZE_FRAME & ~TYPE_ONE_GRID_MIGRATION_EDU & ~TYPE_ON_BOARD_POPUP + & ~TYPE_TASKBAR_OVERLAY_PROXY; // These view all have particular operation associated with swipe down interaction. public static final int TYPE_STATUS_BAR_SWIPE_DOWN_DISALLOW = TYPE_WIDGETS_BOTTOM_SHEET | diff --git a/tests/tapl/com/android/launcher3/tapl/LauncherInstrumentation.java b/tests/tapl/com/android/launcher3/tapl/LauncherInstrumentation.java index 16faf14d86..de31c4dd9a 100644 --- a/tests/tapl/com/android/launcher3/tapl/LauncherInstrumentation.java +++ b/tests/tapl/com/android/launcher3/tapl/LauncherInstrumentation.java @@ -947,7 +947,9 @@ public final class LauncherInstrumentation { waitUntilLauncherObjectGone(WORKSPACE_RES_ID); waitUntilLauncherObjectGone(WIDGETS_RES_ID); waitUntilSystemLauncherObjectGone(OVERVIEW_RES_ID); - waitUntilSystemLauncherObjectGone(TASKBAR_RES_ID); + if (isTransientTaskbar()) { + waitUntilSystemLauncherObjectGone(TASKBAR_RES_ID); + } waitUntilSystemLauncherObjectGone(SPLIT_PLACEHOLDER_RES_ID); waitUntilLauncherObjectGone(KEYBOARD_QUICK_SWITCH_RES_ID); From 6bccfb49c24aa32b4061d179c1fa48423d075ed7 Mon Sep 17 00:00:00 2001 From: Nicolo' Mazzucato Date: Tue, 25 Feb 2025 18:15:10 +0000 Subject: [PATCH 148/153] Propagate the display id with SysUIState changes to launcher This changes the ILauncherProxy.aidl interface to also allow propagating the display id from SysUI to launcher for each SysUIState update. The SysUI part of filling SysUI state correctly has not been implemented yet. But for now, only default display flags are propagated anyway. On the launcher side, the sysui state is propagated correctly to each taskbar instance (there is one for each display) Bug: 362719719 Bug: 398011576 Bug: 399371607 Test: LauncherProxyServiceTest Flag: com.android.systemui.shade_window_goes_around Change-Id: Ic9fa55ca82e4fe395a915c4d611afc8835c5d65d --- .../launcher3/taskbar/TaskbarManager.java | 5 +- .../RecentsAnimationDeviceState.java | 100 +++++++++++++----- .../quickstep/TouchInteractionService.java | 35 ++++-- .../RecentsAnimationDeviceStateTest.kt | 41 ++++++- 4 files changed, 137 insertions(+), 44 deletions(-) diff --git a/quickstep/src/com/android/launcher3/taskbar/TaskbarManager.java b/quickstep/src/com/android/launcher3/taskbar/TaskbarManager.java index 5155ffcdd3..4a8a3de10e 100644 --- a/quickstep/src/com/android/launcher3/taskbar/TaskbarManager.java +++ b/quickstep/src/com/android/launcher3/taskbar/TaskbarManager.java @@ -705,13 +705,14 @@ public class TaskbarManager { } } - public void onSystemUiFlagsChanged(@SystemUiStateFlags long systemUiStateFlags) { + /** Called when the SysUI flags for a given display change. */ + public void onSystemUiFlagsChanged(@SystemUiStateFlags long systemUiStateFlags, int displayId) { if (DEBUG) { Log.d(TAG, "SysUI flags changed: " + formatFlagChange(systemUiStateFlags, mSharedState.sysuiStateFlags, QuickStepContract::getSystemUiStateString)); } mSharedState.sysuiStateFlags = systemUiStateFlags; - TaskbarActivityContext taskbar = getTaskbarForDisplay(getDefaultDisplayId()); + TaskbarActivityContext taskbar = getTaskbarForDisplay(displayId); if (taskbar != null) { taskbar.updateSysuiStateFlags(systemUiStateFlags, false /* fromInit */); } diff --git a/quickstep/src/com/android/quickstep/RecentsAnimationDeviceState.java b/quickstep/src/com/android/quickstep/RecentsAnimationDeviceState.java index 090ccdc869..74f24ee3e7 100644 --- a/quickstep/src/com/android/quickstep/RecentsAnimationDeviceState.java +++ b/quickstep/src/com/android/quickstep/RecentsAnimationDeviceState.java @@ -88,6 +88,9 @@ import com.android.systemui.shared.system.TaskStackChangeListener; import com.android.systemui.shared.system.TaskStackChangeListeners; import java.io.PrintWriter; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; import javax.inject.Inject; @@ -119,6 +122,7 @@ public class RecentsAnimationDeviceState implements DisplayInfoChangeListener, E InputMethodService.canImeRenderGesturalNavButtons(); private @SystemUiStateFlags long mSystemUiStateFlags = QuickStepContract.SYSUI_STATE_AWAKE; + private final Map mSysUIStateFlagsPerDisplay = new ConcurrentHashMap<>(); private NavigationMode mMode = THREE_BUTTONS; private NavBarPosition mNavBarPosition; @@ -353,21 +357,50 @@ public class RecentsAnimationDeviceState implements DisplayInfoChangeListener, E } /** - * Updates the system ui state flags from SystemUI. + * Updates the system ui state flags from SystemUI for a specific display. + * + * @param stateFlags the current {@link SystemUiStateFlags} for the display. + * @param displayId the display's ID. */ - public void setSystemUiFlags(@SystemUiStateFlags long stateFlags) { - mSystemUiStateFlags = stateFlags; + public void setSysUIStateFlagsForDisplay(@SystemUiStateFlags long stateFlags, + int displayId) { + mSysUIStateFlagsPerDisplay.put(displayId, stateFlags); } /** - * @return the system ui state flags. + * Clears the system ui state flags for a specific display. This is called when the display is + * destroyed. + * + * @param displayId the display's ID. + */ + public void clearSysUIStateFlagsForDisplay(int displayId) { + mSysUIStateFlagsPerDisplay.remove(displayId); + } + + /** + * @return the system ui state flags for the default display. */ // TODO(141886704): See if we can remove this @SystemUiStateFlags - public long getSystemUiStateFlags() { - return mSystemUiStateFlags; + public long getSysuiStateFlag() { + return getSystemUiStateFlags(DEFAULT_DISPLAY); } + /** + * @return the system ui state flags for a given display ID. + */ + @SystemUiStateFlags + public long getSystemUiStateFlags(int displayId) { + return mSysUIStateFlagsPerDisplay.getOrDefault(displayId, + QuickStepContract.SYSUI_STATE_AWAKE); + } + + /** + * @return the display ids that have sysui state. + */ + public Set getDisplaysWithSysUIState() { + return mSysUIStateFlagsPerDisplay.keySet(); + } /** * Sets the flag that indicates whether a predictive back-to-home animation is in progress */ @@ -386,8 +419,8 @@ public class RecentsAnimationDeviceState implements DisplayInfoChangeListener, E * @return whether SystemUI is in a state where we can start a system gesture. */ public boolean canStartSystemGesture() { - boolean canStartWithNavHidden = (mSystemUiStateFlags & SYSUI_STATE_NAV_BAR_HIDDEN) == 0 - || (mSystemUiStateFlags & SYSUI_STATE_ALLOW_GESTURE_IGNORING_BAR_VISIBILITY) != 0 + boolean canStartWithNavHidden = (getSysuiStateFlag() & SYSUI_STATE_NAV_BAR_HIDDEN) == 0 + || (getSysuiStateFlag() & SYSUI_STATE_ALLOW_GESTURE_IGNORING_BAR_VISIBILITY) != 0 || mRotationTouchHelper.isTaskListFrozen(); return canStartWithNavHidden && canStartAnyGesture(); } @@ -399,7 +432,7 @@ public class RecentsAnimationDeviceState implements DisplayInfoChangeListener, E */ public boolean canStartTrackpadGesture() { boolean trackpadGesturesEnabled = - (mSystemUiStateFlags & SYSUI_STATE_TOUCHPAD_GESTURES_DISABLED) == 0; + (getSysuiStateFlag() & SYSUI_STATE_TOUCHPAD_GESTURES_DISABLED) == 0; return trackpadGesturesEnabled && canStartAnyGesture(); } @@ -407,8 +440,8 @@ public class RecentsAnimationDeviceState implements DisplayInfoChangeListener, E * Common logic to determine if either trackpad or finger gesture can be started */ private boolean canStartAnyGesture() { - boolean homeOrOverviewEnabled = (mSystemUiStateFlags & SYSUI_STATE_HOME_DISABLED) == 0 - || (mSystemUiStateFlags & SYSUI_STATE_OVERVIEW_DISABLED) == 0; + boolean homeOrOverviewEnabled = (getSysuiStateFlag() & SYSUI_STATE_HOME_DISABLED) == 0 + || (getSysuiStateFlag() & SYSUI_STATE_OVERVIEW_DISABLED) == 0; long gestureDisablingStates = SYSUI_STATE_NOTIFICATION_PANEL_EXPANDED | SYSUI_STATE_STATUS_BAR_KEYGUARD_SHOWING | SYSUI_STATE_QUICK_SETTINGS_EXPANDED @@ -416,7 +449,7 @@ public class RecentsAnimationDeviceState implements DisplayInfoChangeListener, E | SYSUI_STATE_DEVICE_DREAMING | SYSUI_STATE_DISABLE_GESTURE_SPLIT_INVOCATION | SYSUI_STATE_DISABLE_GESTURE_PIP_ANIMATING; - return (gestureDisablingStates & mSystemUiStateFlags) == 0 && homeOrOverviewEnabled; + return (gestureDisablingStates & getSysuiStateFlag()) == 0 && homeOrOverviewEnabled; } /** @@ -424,35 +457,35 @@ public class RecentsAnimationDeviceState implements DisplayInfoChangeListener, E * (like camera or maps) */ public boolean isKeyguardShowingOccluded() { - return (mSystemUiStateFlags & SYSUI_STATE_STATUS_BAR_KEYGUARD_SHOWING_OCCLUDED) != 0; + return (getSysuiStateFlag() & SYSUI_STATE_STATUS_BAR_KEYGUARD_SHOWING_OCCLUDED) != 0; } /** * @return whether screen pinning is enabled and active */ public boolean isScreenPinningActive() { - return (mSystemUiStateFlags & SYSUI_STATE_SCREEN_PINNING) != 0; + return (getSysuiStateFlag() & SYSUI_STATE_SCREEN_PINNING) != 0; } /** * @return whether assistant gesture is constraint */ public boolean isAssistantGestureIsConstrained() { - return (mSystemUiStateFlags & SYSUI_STATE_ASSIST_GESTURE_CONSTRAINED) != 0; + return (getSysuiStateFlag() & SYSUI_STATE_ASSIST_GESTURE_CONSTRAINED) != 0; } /** * @return whether the bubble stack is expanded */ public boolean isBubblesExpanded() { - return (mSystemUiStateFlags & SYSUI_STATE_BUBBLES_EXPANDED) != 0; + return (getSysuiStateFlag() & SYSUI_STATE_BUBBLES_EXPANDED) != 0; } /** * @return whether the global actions dialog is showing */ public boolean isSystemUiDialogShowing() { - return (mSystemUiStateFlags & SYSUI_STATE_DIALOG_SHOWING) != 0; + return (getSysuiStateFlag() & SYSUI_STATE_DIALOG_SHOWING) != 0; } /** @@ -466,35 +499,35 @@ public class RecentsAnimationDeviceState implements DisplayInfoChangeListener, E * @return whether the accessibility menu is available. */ public boolean isAccessibilityMenuAvailable() { - return (mSystemUiStateFlags & SYSUI_STATE_A11Y_BUTTON_CLICKABLE) != 0; + return (getSysuiStateFlag() & SYSUI_STATE_A11Y_BUTTON_CLICKABLE) != 0; } /** * @return whether the accessibility menu shortcut is available. */ public boolean isAccessibilityMenuShortcutAvailable() { - return (mSystemUiStateFlags & SYSUI_STATE_A11Y_BUTTON_LONG_CLICKABLE) != 0; + return (getSysuiStateFlag() & SYSUI_STATE_A11Y_BUTTON_LONG_CLICKABLE) != 0; } /** * @return whether home is disabled (either by SUW/SysUI/device policy) */ public boolean isHomeDisabled() { - return (mSystemUiStateFlags & SYSUI_STATE_HOME_DISABLED) != 0; + return (getSysuiStateFlag() & SYSUI_STATE_HOME_DISABLED) != 0; } /** * @return whether overview is disabled (either by SUW/SysUI/device policy) */ public boolean isOverviewDisabled() { - return (mSystemUiStateFlags & SYSUI_STATE_OVERVIEW_DISABLED) != 0; + return (getSysuiStateFlag() & SYSUI_STATE_OVERVIEW_DISABLED) != 0; } /** * @return whether one-handed mode is enabled and active */ public boolean isOneHandedModeActive() { - return (mSystemUiStateFlags & SYSUI_STATE_ONE_HANDED_ACTIVE) != 0; + return (getSysuiStateFlag() & SYSUI_STATE_ONE_HANDED_ACTIVE) != 0; } /** @@ -557,7 +590,7 @@ public class RecentsAnimationDeviceState implements DisplayInfoChangeListener, E */ public boolean canTriggerAssistantAction(MotionEvent ev) { return mAssistantAvailable - && !QuickStepContract.isAssistantGestureDisabled(mSystemUiStateFlags) + && !QuickStepContract.isAssistantGestureDisabled(getSysuiStateFlag()) && mRotationTouchHelper.touchInAssistantRegion(ev) && !isTrackpadScroll(ev) && !isLockToAppActive(); @@ -597,7 +630,7 @@ public class RecentsAnimationDeviceState implements DisplayInfoChangeListener, E /** Returns whether IME is rendering nav buttons, and IME is currently showing. */ public boolean isImeRenderingNavButtons() { return mCanImeRenderGesturalNavButtons && mMode == NO_BUTTON - && ((mSystemUiStateFlags & SYSUI_STATE_IME_VISIBLE) != 0); + && ((getSysuiStateFlag() & SYSUI_STATE_IME_VISIBLE) != 0); } /** @@ -629,24 +662,37 @@ public class RecentsAnimationDeviceState implements DisplayInfoChangeListener, E return touchSlop * touchSlop; } + /** Returns a string representation of the system ui state flags for the default display. */ public String getSystemUiStateString() { - return QuickStepContract.getSystemUiStateString(mSystemUiStateFlags); + return getSystemUiStateString(getSysuiStateFlag()); + } + + /** Returns a string representation of the system ui state flags. */ + public String getSystemUiStateString(long flags) { + return QuickStepContract.getSystemUiStateString(flags); } public void dump(PrintWriter pw) { pw.println("DeviceState:"); pw.println(" canStartSystemGesture=" + canStartSystemGesture()); - pw.println(" systemUiFlags=" + mSystemUiStateFlags); + pw.println(" systemUiFlagsForDefaultDisplay=" + getSysuiStateFlag()); pw.println(" systemUiFlagsDesc=" + getSystemUiStateString()); pw.println(" assistantAvailable=" + mAssistantAvailable); pw.println(" assistantDisabled=" - + QuickStepContract.isAssistantGestureDisabled(mSystemUiStateFlags)); + + QuickStepContract.isAssistantGestureDisabled(getSysuiStateFlag())); pw.println(" isOneHandedModeEnabled=" + mIsOneHandedModeEnabled); pw.println(" isSwipeToNotificationEnabled=" + mIsSwipeToNotificationEnabled); pw.println(" deferredGestureRegion=" + mDeferredGestureRegion.getBounds()); pw.println(" exclusionRegion=" + mExclusionRegion.getBounds()); pw.println(" pipIsActive=" + mPipIsActive); pw.println(" predictiveBackToHomeInProgress=" + mIsPredictiveBackToHomeInProgress); + for (int displayId : mSysUIStateFlagsPerDisplay.keySet()) { + pw.println(" systemUiFlagsForDisplay" + displayId + "=" + getSystemUiStateFlags( + displayId)); + pw.println(" systemUiFlagsForDisplay" + displayId + "Desc=" + getSystemUiStateString( + getSystemUiStateFlags(displayId))); + } + pw.println(" RotationTouchHelper:"); mRotationTouchHelper.dump(pw); } } diff --git a/quickstep/src/com/android/quickstep/TouchInteractionService.java b/quickstep/src/com/android/quickstep/TouchInteractionService.java index ba4c65a293..5ca9319772 100644 --- a/quickstep/src/com/android/quickstep/TouchInteractionService.java +++ b/quickstep/src/com/android/quickstep/TouchInteractionService.java @@ -53,6 +53,7 @@ import android.os.RemoteException; import android.os.SystemClock; import android.util.Log; import android.view.Choreographer; +import android.view.Display; import android.view.InputDevice; import android.view.InputEvent; import android.view.MotionEvent; @@ -274,11 +275,12 @@ public class TouchInteractionService extends Service { } @BinderThread - public void onSystemUiStateChanged(@SystemUiStateFlags long stateFlags) { + public void onSystemUiStateChanged(@SystemUiStateFlags long stateFlags, int displayId) { MAIN_EXECUTOR.execute(() -> executeForTouchInteractionService(tis -> { - long lastFlags = tis.mDeviceState.getSystemUiStateFlags(); - tis.mDeviceState.setSystemUiFlags(stateFlags); - tis.onSystemUiFlagsChanged(lastFlags); + // Last flags is only used for the default display case. + long lastFlags = tis.mDeviceState.getSysuiStateFlag(); + tis.mDeviceState.setSysUIStateFlagsForDisplay(stateFlags, displayId); + tis.onSystemUiFlagsChanged(lastFlags, displayId); })); } @@ -312,6 +314,9 @@ public class TouchInteractionService extends Service { public void onDisplayRemoved(int displayId) { executeForTaskbarManager(taskbarManager -> taskbarManager.onDisplayRemoved(displayId)); + executeForTouchInteractionService(tis -> { + tis.mDeviceState.clearSysUIStateFlagsForDisplay(displayId); + }); } @BinderThread @@ -649,7 +654,9 @@ public class TouchInteractionService extends Service { mResetGestureInputConsumer = new ResetGestureInputConsumer( mTaskAnimationManager, mTaskbarManager::getCurrentActivityContext); mInputConsumer.registerInputConsumer(); - onSystemUiFlagsChanged(mDeviceState.getSystemUiStateFlags()); + for (int displayId : mDeviceState.getDisplaysWithSysUIState()) { + onSystemUiFlagsChanged(mDeviceState.getSystemUiStateFlags(displayId), displayId); + } onAssistantVisibilityChanged(); // Initialize the task tracker @@ -711,13 +718,19 @@ public class TouchInteractionService extends Service { } @UiThread - private void onSystemUiFlagsChanged(@SystemUiStateFlags long lastSysUIFlags) { + private void onSystemUiFlagsChanged(@SystemUiStateFlags long lastSysUIFlags, int displayId) { if (LockedUserState.get(this).isUserUnlocked()) { - long systemUiStateFlags = mDeviceState.getSystemUiStateFlags(); - SystemUiProxy.INSTANCE.get(this).setLastSystemUiStateFlags(systemUiStateFlags); - mOverviewComponentObserver.setHomeDisabled(mDeviceState.isHomeDisabled()); - mTaskbarManager.onSystemUiFlagsChanged(systemUiStateFlags); - mTaskAnimationManager.onSystemUiFlagsChanged(lastSysUIFlags, systemUiStateFlags); + long systemUiStateFlags = mDeviceState.getSystemUiStateFlags(displayId); + mTaskbarManager.onSystemUiFlagsChanged(systemUiStateFlags, displayId); + if (displayId == Display.DEFAULT_DISPLAY) { + // The following don't care about non-default displays, at least for now. If they + // ever will, they should be taken care of. + SystemUiProxy.INSTANCE.get(this).setLastSystemUiStateFlags(systemUiStateFlags); + mOverviewComponentObserver.setHomeDisabled(mDeviceState.isHomeDisabled()); + // TODO b/399371607 - Propagate to taskAnimationManager once overview is multi + // display. + mTaskAnimationManager.onSystemUiFlagsChanged(lastSysUIFlags, systemUiStateFlags); + } } } diff --git a/quickstep/tests/multivalentTests/src/com/android/quickstep/RecentsAnimationDeviceStateTest.kt b/quickstep/tests/multivalentTests/src/com/android/quickstep/RecentsAnimationDeviceStateTest.kt index b652ee8df4..a7370b02e9 100644 --- a/quickstep/tests/multivalentTests/src/com/android/quickstep/RecentsAnimationDeviceStateTest.kt +++ b/quickstep/tests/multivalentTests/src/com/android/quickstep/RecentsAnimationDeviceStateTest.kt @@ -1,5 +1,6 @@ package com.android.quickstep +import android.view.Display import androidx.test.annotation.UiThreadTest import androidx.test.filters.SmallTest import com.android.launcher3.dagger.LauncherComponentProvider @@ -13,6 +14,7 @@ import com.android.launcher3.util.LauncherMultivalentJUnit import com.android.launcher3.util.NavigationMode import com.android.launcher3.util.SandboxApplication import com.android.quickstep.util.GestureExclusionManager +import com.android.systemui.shared.system.QuickStepContract import com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_ALLOW_GESTURE_IGNORING_BAR_VISIBILITY import com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_DEVICE_DREAMING import com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_DISABLE_GESTURE_SPLIT_INVOCATION @@ -150,7 +152,7 @@ class RecentsAnimationDeviceStateTest { allSysUiStates().forEach { state -> val canStartGesture = !disablingStates.contains(state) - underTest.setSystemUiFlags(state) + underTest.setSysUIStateFlagsForDisplay(state, Display.DEFAULT_DISPLAY) assertThat(underTest.canStartTrackpadGesture()).isEqualTo(canStartGesture) } } @@ -166,7 +168,7 @@ class RecentsAnimationDeviceStateTest { ) stateToExpectedResult.forEach { (state, allowed) -> - underTest.setSystemUiFlags(state) + underTest.setSysUIStateFlagsForDisplay(state, Display.DEFAULT_DISPLAY) assertThat(underTest.canStartTrackpadGesture()).isEqualTo(allowed) } } @@ -177,7 +179,7 @@ class RecentsAnimationDeviceStateTest { allSysUiStates().forEach { state -> val canStartGesture = !disablingStates.contains(state) - underTest.setSystemUiFlags(state) + underTest.setSysUIStateFlagsForDisplay(state, Display.DEFAULT_DISPLAY) assertThat(underTest.canStartSystemGesture()).isEqualTo(canStartGesture) } } @@ -197,11 +199,42 @@ class RecentsAnimationDeviceStateTest { ) stateToExpectedResult.forEach { (state, gestureAllowed) -> - underTest.setSystemUiFlags(state) + underTest.setSysUIStateFlagsForDisplay(state, Display.DEFAULT_DISPLAY) assertThat(underTest.canStartSystemGesture()).isEqualTo(gestureAllowed) } } + @Test + fun getSystemUiStateFlags_defaultAwake() { + val NOT_EXISTENT_DISPLAY = 2 + assertThat(underTest.getSystemUiStateFlags(NOT_EXISTENT_DISPLAY)) + .isEqualTo(QuickStepContract.SYSUI_STATE_AWAKE) + } + + @Test + fun clearSysUIStateFlagsForDisplay_displayNotReturnedAnymore() { + underTest.setSysUIStateFlagsForDisplay(1, /* displayId= */ 1) + + assertThat(underTest.displaysWithSysUIState).contains(1) + assertThat(underTest.getSystemUiStateFlags(1)).isEqualTo(1) + + underTest.clearSysUIStateFlagsForDisplay(1) + + assertThat(underTest.displaysWithSysUIState).doesNotContain(1) + assertThat(underTest.getSystemUiStateFlags(1)) + .isEqualTo(QuickStepContract.SYSUI_STATE_AWAKE) + } + + @Test + fun setSysUIStateFlagsForDisplay_setsCorrectly() { + underTest.setSysUIStateFlagsForDisplay(1, /* displayId= */ 1) + underTest.setSysUIStateFlagsForDisplay(2, /* displayId= */ 2) + + assertThat(underTest.getSystemUiStateFlags(1)).isEqualTo(1) + assertThat(underTest.getSystemUiStateFlags(2)).isEqualTo(2) + assertThat(underTest.displaysWithSysUIState).containsAtLeast(1, 2) + } + private fun allSysUiStates(): List { // SYSUI_STATES_* are binary flags return (0..SYSUI_STATES_COUNT).map { 1L shl it } From 5e99882d757ea8708d5f7c9cfd93130564d7e78b Mon Sep 17 00:00:00 2001 From: Orhan Uysal Date: Fri, 28 Feb 2025 15:42:37 +0000 Subject: [PATCH 149/153] Change the misused logic Refactor from ag/31915496 was wrong. We should skip the transparent activity tiles when there is a visible task already found not when visible tasks are not found. Bug: 397190111 Test: Enter any app, trigger circle to search, see only one tile produced. Flag: EXEMPT Bug fix Change-Id: Ic19710a7d1f5be78e96aa5ac25553358732acf3b --- quickstep/src/com/android/quickstep/RecentTasksList.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/quickstep/src/com/android/quickstep/RecentTasksList.java b/quickstep/src/com/android/quickstep/RecentTasksList.java index a178c3cc6b..f506039a1b 100644 --- a/quickstep/src/com/android/quickstep/RecentTasksList.java +++ b/quickstep/src/com/android/quickstep/RecentTasksList.java @@ -410,7 +410,7 @@ public class RecentTasksList { tmpLockedUsers.get(task2Key.userId) /* isLocked */); } else { // Is fullscreen task - if (!isFirstVisibleTaskFound) { + if (isFirstVisibleTaskFound) { boolean isExcluded = (taskInfo1.baseIntent.getFlags() & FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) != 0; if (taskInfo1.isTopActivityTransparent && isExcluded) { From 672a32a18b0a67879aeca9b9e6cac68fde8d8122 Mon Sep 17 00:00:00 2001 From: mpodolian Date: Fri, 28 Feb 2025 10:01:13 -0800 Subject: [PATCH 150/153] Removed fly-back animation after a taskbar item drop on the bubble bar Added logic to track whether the drop target handled the app icon drop, in order to prevent the fly-back animation in those cases. Bug: 397459664 Flag: com.android.wm.shell.enable_create_any_bubble Test: Manual. Drop a taskbar icon onto the bubble bar. Observe that no fly-back animation is performed for the dropped icon. Change-Id: If439d7280fe9f713c181531ac899ac8ad37ed481 --- .../android/launcher3/taskbar/TaskbarDragController.java | 6 ++++-- .../launcher3/taskbar/bubbles/BubbleBarViewController.java | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/quickstep/src/com/android/launcher3/taskbar/TaskbarDragController.java b/quickstep/src/com/android/launcher3/taskbar/TaskbarDragController.java index 9b7e320892..1b516bef4d 100644 --- a/quickstep/src/com/android/launcher3/taskbar/TaskbarDragController.java +++ b/quickstep/src/com/android/launcher3/taskbar/TaskbarDragController.java @@ -117,6 +117,7 @@ public class TaskbarDragController extends DragController im private int mRegistrationY; private boolean mIsSystemDragInProgress; + private boolean mIsDropHandledByDropTarget; // Animation for the drag shadow back into position after an unsuccessful drag private ValueAnimator mReturnAnimator; @@ -253,7 +254,8 @@ public class TaskbarDragController extends DragController im /* originalView = */ btv, dragLayerX + dragOffset.x, dragLayerY + dragOffset.y, - (View target, DropTarget.DragObject d, boolean success) -> {} /* DragSource */, + (View target, DropTarget.DragObject d, boolean success) -> + mIsDropHandledByDropTarget = success /* DragSource */, btv.getTag() instanceof ItemInfo itemInfo ? itemInfo : null, dragRect, scale * iconScale, @@ -562,7 +564,7 @@ public class TaskbarDragController extends DragController im @Override protected void endDrag() { - if (mDisallowGlobalDrag) { + if (mDisallowGlobalDrag && !mIsDropHandledByDropTarget) { // We need to explicitly set deferDragViewCleanupPostAnimation to true here so the // super call doesn't remove it from the drag layer before the animation completes. // This variable gets set in to false in super.dispatchDropComplete() because it diff --git a/quickstep/src/com/android/launcher3/taskbar/bubbles/BubbleBarViewController.java b/quickstep/src/com/android/launcher3/taskbar/bubbles/BubbleBarViewController.java index beda30c3b3..1f5c5419f4 100644 --- a/quickstep/src/com/android/launcher3/taskbar/bubbles/BubbleBarViewController.java +++ b/quickstep/src/com/android/launcher3/taskbar/bubbles/BubbleBarViewController.java @@ -145,7 +145,7 @@ public class BubbleBarViewController { @Override public void onLauncherItemDroppedOverBubbleBarDragZone(@NonNull BubbleBarLocation location, @NonNull ItemInfo itemInfo) { - //TODO(b/397459664) : fix task bar icon animation after drop + //TODO(b/397459664) : fix drag interruption when there are no bubbles //TODO(b/397459664) : update bubble bar location ShortcutInfo shortcutInfo = null; if (itemInfo instanceof WorkspaceItemInfo) { From 66999f0a197eb7544c354ec7566420a72498dd8b Mon Sep 17 00:00:00 2001 From: Federico Baron Date: Fri, 28 Feb 2025 21:27:07 +0000 Subject: [PATCH 151/153] Add screenrecord for uninstallWorkspaceIcon Bug: 399756302 Flag: EXEMPT TEST_ONLY Test: TaplUninstallRemoveTest Change-Id: I4bdf8087276a93f8f736c23ba95f35acb7f05c3a --- .../com/android/launcher3/dragging/TaplUninstallRemoveTest.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/src/com/android/launcher3/dragging/TaplUninstallRemoveTest.java b/tests/src/com/android/launcher3/dragging/TaplUninstallRemoveTest.java index f490bd6381..95d50764a4 100644 --- a/tests/src/com/android/launcher3/dragging/TaplUninstallRemoveTest.java +++ b/tests/src/com/android/launcher3/dragging/TaplUninstallRemoveTest.java @@ -36,6 +36,7 @@ import com.android.launcher3.ui.AbstractLauncherUiTest; import com.android.launcher3.ui.PortraitLandscapeRunner.PortraitLandscape; import com.android.launcher3.util.TestUtil; import com.android.launcher3.util.Wait; +import com.android.launcher3.util.rule.ScreenRecordRule; import org.junit.Test; @@ -126,6 +127,7 @@ public class TaplUninstallRemoveTest extends AbstractLauncherUiTest { * Adds three icons to the workspace and removes one of them by dragging to uninstall. */ @Test + @ScreenRecordRule.ScreenRecord // b/399756302 @PlatinumTest(focusArea = "launcher") public void uninstallWorkspaceIcon() throws IOException { Point[] gridPositions = TestUtil.getCornersAndCenterPositions(mLauncher); From 26ad16592a56962fc197da55bcf028bed18c89bf Mon Sep 17 00:00:00 2001 From: Toni Barzic Date: Thu, 13 Feb 2025 17:50:08 +0000 Subject: [PATCH 152/153] Taskbar on home should open all apps that support drag to workspace If taskbar is shown on home screen, have the taskbar all apps button toggle the launcher activity version of all apps UI. This makes the behavior consistent with how all apps system action (keyboard shortcut) works, and addresses a gap in functionality where users are unable to drag apps from the taskbar all apps UI to the workspace. Bug: 392118517 Flag: com.android.window.flags.enter_desktop_by_default_on_freeform_displays Test: On desktop device, toggle all apps from taskbar on home screen, drag and app from all apps to workspace. Change-Id: Ida0f230bf38c6e1e35041556f33de1be85daf785 --- .../taskbar/LauncherTaskbarUIController.java | 9 +++++++-- .../taskbar/TaskbarActivityContext.java | 14 -------------- .../launcher3/taskbar/TaskbarManager.java | 8 ++++---- .../launcher3/taskbar/TaskbarUIController.java | 15 ++++++++++++--- .../launcher3/taskbar/TaskbarViewCallbacks.java | 11 ++++++++++- .../quickstep/TouchInteractionService.java | 2 +- src/com/android/launcher3/Launcher.java | 16 ++++++++++------ 7 files changed, 44 insertions(+), 31 deletions(-) diff --git a/quickstep/src/com/android/launcher3/taskbar/LauncherTaskbarUIController.java b/quickstep/src/com/android/launcher3/taskbar/LauncherTaskbarUIController.java index 3f3700bb04..2272d11c38 100644 --- a/quickstep/src/com/android/launcher3/taskbar/LauncherTaskbarUIController.java +++ b/quickstep/src/com/android/launcher3/taskbar/LauncherTaskbarUIController.java @@ -467,10 +467,15 @@ public class LauncherTaskbarUIController extends TaskbarUIController { } @Override - protected boolean canToggleHomeAllApps() { - return mLauncher.isResumed() + protected void toggleAllApps(boolean focusSearch) { + boolean canToggleHomeAllApps = mLauncher.isResumed() && !mTaskbarLauncherStateController.isInOverviewUi() && !mLauncher.areDesktopTasksVisible(); + if (canToggleHomeAllApps) { + mLauncher.toggleAllApps(focusSearch); + return; + } + super.toggleAllApps(focusSearch); } @Override diff --git a/quickstep/src/com/android/launcher3/taskbar/TaskbarActivityContext.java b/quickstep/src/com/android/launcher3/taskbar/TaskbarActivityContext.java index 57bcc14ff3..4dc212b956 100644 --- a/quickstep/src/com/android/launcher3/taskbar/TaskbarActivityContext.java +++ b/quickstep/src/com/android/launcher3/taskbar/TaskbarActivityContext.java @@ -608,16 +608,6 @@ public class TaskbarActivityContext extends BaseTaskbarContext { mControllers.taskbarStashController.updateAndAnimateTransientTaskbar(false); } - /** Toggles Taskbar All Apps overlay. */ - public void toggleAllApps() { - mControllers.taskbarAllAppsController.toggle(); - } - - /** Toggles Taskbar All Apps overlay with keyboard ready for search. */ - public void toggleAllAppsSearch() { - mControllers.taskbarAllAppsController.toggleSearch(); - } - @Override public DeviceProfile getDeviceProfile() { return mDeviceProfile; @@ -2075,10 +2065,6 @@ public class TaskbarActivityContext extends BaseTaskbarContext { mControllers.keyboardQuickSwitchController.closeQuickSwitchView(false); } - boolean canToggleHomeAllApps() { - return mControllers.uiController.canToggleHomeAllApps(); - } - boolean isIconAlignedWithHotseat() { return mControllers.uiController.isIconAlignedWithHotseat(); } diff --git a/quickstep/src/com/android/launcher3/taskbar/TaskbarManager.java b/quickstep/src/com/android/launcher3/taskbar/TaskbarManager.java index 943c44ed5c..70fa1ec1ab 100644 --- a/quickstep/src/com/android/launcher3/taskbar/TaskbarManager.java +++ b/quickstep/src/com/android/launcher3/taskbar/TaskbarManager.java @@ -511,14 +511,14 @@ public class TaskbarManager { /** * Toggles All Apps for Taskbar or Launcher depending on the current state. */ - public void toggleAllApps() { + public void toggleAllAppsSearch() { TaskbarActivityContext taskbar = getTaskbarForDisplay(getDefaultDisplayId()); - if (taskbar == null || taskbar.canToggleHomeAllApps()) { + if (taskbar == null) { // Home All Apps should be toggled from this class, because the controllers are not // initialized when Taskbar is disabled (i.e. TaskbarActivityContext is null). - if (mActivity instanceof Launcher l) l.toggleAllAppsSearch(); + if (mActivity instanceof Launcher l) l.toggleAllApps(true); } else { - taskbar.toggleAllAppsSearch(); + taskbar.getControllers().uiController.toggleAllApps(true); } } diff --git a/quickstep/src/com/android/launcher3/taskbar/TaskbarUIController.java b/quickstep/src/com/android/launcher3/taskbar/TaskbarUIController.java index 89bcb41fc9..ea0b81eeea 100644 --- a/quickstep/src/com/android/launcher3/taskbar/TaskbarUIController.java +++ b/quickstep/src/com/android/launcher3/taskbar/TaskbarUIController.java @@ -207,9 +207,18 @@ public class TaskbarUIController implements BubbleBarController.BubbleBarLocatio return false; } - /** Returns {@code true} if Home All Apps available instead of Taskbar All Apps. */ - protected boolean canToggleHomeAllApps() { - return false; + + /** + * Toggles all apps UI. Default implementation opens Taskbar All Apps, but may be overridden to + * open different Alls Apps variant depending on the context. + * @param focusSearch indicates whether All Apps should be opened with search input focused. + */ + protected void toggleAllApps(boolean focusSearch) { + if (focusSearch) { + mControllers.taskbarAllAppsController.toggleSearch(); + } else { + mControllers.taskbarAllAppsController.toggle(); + } } @CallSuper diff --git a/quickstep/src/com/android/launcher3/taskbar/TaskbarViewCallbacks.java b/quickstep/src/com/android/launcher3/taskbar/TaskbarViewCallbacks.java index c7ef960a52..066d4df2f3 100644 --- a/quickstep/src/com/android/launcher3/taskbar/TaskbarViewCallbacks.java +++ b/quickstep/src/com/android/launcher3/taskbar/TaskbarViewCallbacks.java @@ -66,7 +66,16 @@ public class TaskbarViewCallbacks { InteractionJankMonitorWrapper.begin(v, Cuj.CUJ_LAUNCHER_OPEN_ALL_APPS, /* tag= */ "TASKBAR_BUTTON"); mActivity.getStatsLogManager().logger().log(LAUNCHER_TASKBAR_ALLAPPS_BUTTON_TAP); - mControllers.taskbarAllAppsController.toggle(); + if (DisplayController.showLockedTaskbarOnHome(mActivity) + || DisplayController.showDesktopTaskbarForFreeformDisplay(mActivity)) { + // If the taskbar can be shown on the home screen, use mAllAppsToggler to toggle all + // apps, which will toggle the launcher activity all apps when on home screen. + // TODO(b/395913143): Reconsider this if a gap in taskbar all apps functionality that + // prevents users to drag items to workspace is addressed. + mControllers.uiController.toggleAllApps(false); + } else { + mControllers.taskbarAllAppsController.toggle(); + } } /** Trigger All Apps button long click action. */ diff --git a/quickstep/src/com/android/quickstep/TouchInteractionService.java b/quickstep/src/com/android/quickstep/TouchInteractionService.java index ba4c65a293..7c72af95c7 100644 --- a/quickstep/src/com/android/quickstep/TouchInteractionService.java +++ b/quickstep/src/com/android/quickstep/TouchInteractionService.java @@ -705,7 +705,7 @@ public class TouchInteractionService extends Service { public void send(int code, Intent intent, String resolvedType, IBinder allowlistToken, IIntentReceiver finishedReceiver, String requiredPermission, Bundle options) { - MAIN_EXECUTOR.execute(() -> mTaskbarManager.toggleAllApps()); + MAIN_EXECUTOR.execute(() -> mTaskbarManager.toggleAllAppsSearch()); } }); } diff --git a/src/com/android/launcher3/Launcher.java b/src/com/android/launcher3/Launcher.java index 3edba990e7..64d61c126b 100644 --- a/src/com/android/launcher3/Launcher.java +++ b/src/com/android/launcher3/Launcher.java @@ -1674,7 +1674,7 @@ public class Launcher extends StatefulActivity } else if (Intent.ACTION_ALL_APPS.equals(intent.getAction())) { showAllAppsFromIntent(alreadyOnHome); } else if (INTENT_ACTION_ALL_APPS_TOGGLE.equals(intent.getAction())) { - toggleAllAppsSearch(alreadyOnHome); + toggleAllApps(alreadyOnHome, true); } else if (Intent.ACTION_SHOW_WORK_APPS.equals(intent.getAction())) { showAllAppsWithSelectedTabFromIntent(alreadyOnHome, ActivityAllAppsContainerView.AdapterHolder.WORK); @@ -1688,12 +1688,15 @@ public class Launcher extends StatefulActivity // Overridden } - /** Toggles Launcher All Apps with keyboard ready for search. */ - public void toggleAllAppsSearch() { - toggleAllAppsSearch(/* alreadyOnHome= */ true); + /** + * Toggles Launcher All Apps. + * @param focusSearch Indicates whether to make All Apps keyboard ready for search. + */ + public void toggleAllApps(boolean focusSearch) { + toggleAllApps(/* alreadyOnHome= */ true, focusSearch); } - protected void toggleAllAppsSearch(boolean alreadyOnHome) { + private void toggleAllApps(boolean alreadyOnHome, boolean focusSearch) { if (getStateManager().isInStableState(ALL_APPS)) { getStateManager().goToState(NORMAL, alreadyOnHome); } else { @@ -1705,7 +1708,8 @@ public class Launcher extends StatefulActivity new AnimationSuccessListener() { @Override public void onAnimationSuccess(Animator animator) { - if (mAppsView.getSearchUiManager().getEditText() != null) { + if (focusSearch + && mAppsView.getSearchUiManager().getEditText() != null) { mAppsView.getSearchUiManager().getEditText().requestFocus(); } } From 4e4ad8969649885ed107e2cd24834d402dc7e6c8 Mon Sep 17 00:00:00 2001 From: Charlie Anderson Date: Fri, 28 Feb 2025 21:38:06 +0000 Subject: [PATCH 153/153] Fix LauncherPrefs crash by allowing sub-types of Set Bug: 396616795 Test: LauncherPrefsTest Flag: EXEMPT bugfix Change-Id: Id380a6e4bb5eb809978070ff1b523c9e98e6b869 --- src/com/android/launcher3/LauncherPrefs.kt | 47 ++++++++++--------- .../android/launcher3/LauncherPrefsTest.kt | 44 ++++++++++++++++- 2 files changed, 66 insertions(+), 25 deletions(-) diff --git a/src/com/android/launcher3/LauncherPrefs.kt b/src/com/android/launcher3/LauncherPrefs.kt index 2a5cd63752..7a04b0f950 100644 --- a/src/com/android/launcher3/LauncherPrefs.kt +++ b/src/com/android/launcher3/LauncherPrefs.kt @@ -75,18 +75,18 @@ constructor(@ApplicationContext private val encryptedContext: Context) { @Suppress("IMPLICIT_CAST_TO_ANY", "UNCHECKED_CAST") private fun getInner(item: Item, default: T): T { val sp = getSharedPrefs(item) - - return when (item.type) { - String::class.java -> sp.getString(item.sharedPrefKey, default as? String) - Boolean::class.java, - java.lang.Boolean::class.java -> sp.getBoolean(item.sharedPrefKey, default as Boolean) - Int::class.java, - java.lang.Integer::class.java -> sp.getInt(item.sharedPrefKey, default as Int) - Float::class.java, - java.lang.Float::class.java -> sp.getFloat(item.sharedPrefKey, default as Float) - Long::class.java, - java.lang.Long::class.java -> sp.getLong(item.sharedPrefKey, default as Long) - Set::class.java -> sp.getStringSet(item.sharedPrefKey, default as? Set) + return when { + item.type == String::class.java -> sp.getString(item.sharedPrefKey, default as? String) + item.type == Boolean::class.java || item.type == java.lang.Boolean::class.java -> + sp.getBoolean(item.sharedPrefKey, default as Boolean) + item.type == Int::class.java || item.type == java.lang.Integer::class.java -> + sp.getInt(item.sharedPrefKey, default as Int) + item.type == Float::class.java || item.type == java.lang.Float::class.java -> + sp.getFloat(item.sharedPrefKey, default as Float) + item.type == Long::class.java || item.type == java.lang.Long::class.java -> + sp.getLong(item.sharedPrefKey, default as Long) + Set::class.java.isAssignableFrom(item.type) -> + sp.getStringSet(item.sharedPrefKey, default as? Set) else -> throw IllegalArgumentException( "item type: ${item.type}" + " is not compatible with sharedPref methods" @@ -147,17 +147,18 @@ constructor(@ApplicationContext private val encryptedContext: Context) { item: Item, value: Any?, ): SharedPreferences.Editor = - when (item.type) { - String::class.java -> putString(item.sharedPrefKey, value as? String) - Boolean::class.java, - java.lang.Boolean::class.java -> putBoolean(item.sharedPrefKey, value as Boolean) - Int::class.java, - java.lang.Integer::class.java -> putInt(item.sharedPrefKey, value as Int) - Float::class.java, - java.lang.Float::class.java -> putFloat(item.sharedPrefKey, value as Float) - Long::class.java, - java.lang.Long::class.java -> putLong(item.sharedPrefKey, value as Long) - Set::class.java -> putStringSet(item.sharedPrefKey, value as? Set) + when { + item.type == String::class.java -> putString(item.sharedPrefKey, value as? String) + item.type == Boolean::class.java || item.type == java.lang.Boolean::class.java -> + putBoolean(item.sharedPrefKey, value as Boolean) + item.type == Int::class.java || item.type == java.lang.Integer::class.java -> + putInt(item.sharedPrefKey, value as Int) + item.type == Float::class.java || item.type == java.lang.Float::class.java -> + putFloat(item.sharedPrefKey, value as Float) + item.type == Long::class.java || item.type == java.lang.Long::class.java -> + putLong(item.sharedPrefKey, value as Long) + Set::class.java.isAssignableFrom(item.type) -> + putStringSet(item.sharedPrefKey, value as? Set) else -> throw IllegalArgumentException( "item type: ${item.type} is not compatible with sharedPref methods" diff --git a/tests/multivalentTests/src/com/android/launcher3/LauncherPrefsTest.kt b/tests/multivalentTests/src/com/android/launcher3/LauncherPrefsTest.kt index 4aeef2e671..da9cc8635d 100644 --- a/tests/multivalentTests/src/com/android/launcher3/LauncherPrefsTest.kt +++ b/tests/multivalentTests/src/com/android/launcher3/LauncherPrefsTest.kt @@ -24,12 +24,18 @@ import com.android.launcher3.LauncherPrefs.Companion.BOOT_AWARE_PREFS_KEY import com.google.common.truth.Truth.assertThat import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit +import org.junit.Assert.assertThrows import org.junit.Test import org.junit.runner.RunWith private val TEST_BOOLEAN_ITEM = LauncherPrefs.nonRestorableItem("1", false) private val TEST_STRING_ITEM = LauncherPrefs.nonRestorableItem("2", "( ͡❛ ͜ʖ ͡❛)") private val TEST_INT_ITEM = LauncherPrefs.nonRestorableItem("3", -1) +private val TEST_FLOAT_ITEM = LauncherPrefs.nonRestorableItem("4", -1f) +private val TEST_LONG_ITEM = LauncherPrefs.nonRestorableItem("5", -1L) +private val TEST_SET_ITEM = LauncherPrefs.nonRestorableItem("6", setOf()) +private val TEST_HASHSET_ITEM = LauncherPrefs.nonRestorableItem("7", hashSetOf()) + private val TEST_CONTEXTUAL_ITEM = ContextualItem("4", true, { true }, EncryptionType.ENCRYPTED, Boolean::class.java) @@ -143,6 +149,17 @@ class LauncherPrefsTest { } } + @Test + fun whenItemType_isInvalid_thenThrowException() { + val badItem = LauncherPrefs.nonRestorableItem("8", mapOf()) + with(launcherPrefs) { + assertThrows(IllegalArgumentException::class.java) { + putSync(badItem.to(badItem.defaultValue)) + } + assertThrows(IllegalArgumentException::class.java) { get(badItem) } + } + } + @Test fun put_storesListOfItemsInLauncherPrefs_successfully() { with(launcherPrefs) { @@ -150,9 +167,32 @@ class LauncherPrefsTest { TEST_STRING_ITEM.to(TEST_STRING_ITEM.defaultValue), TEST_INT_ITEM.to(TEST_INT_ITEM.defaultValue), TEST_BOOLEAN_ITEM.to(TEST_BOOLEAN_ITEM.defaultValue), + TEST_FLOAT_ITEM.to(TEST_FLOAT_ITEM.defaultValue), + TEST_LONG_ITEM.to(TEST_LONG_ITEM.defaultValue), + TEST_SET_ITEM.to(TEST_SET_ITEM.defaultValue), + TEST_HASHSET_ITEM.to(TEST_HASHSET_ITEM.defaultValue), + ) + assertThat( + has( + TEST_STRING_ITEM, + TEST_INT_ITEM, + TEST_BOOLEAN_ITEM, + TEST_FLOAT_ITEM, + TEST_LONG_ITEM, + TEST_SET_ITEM, + TEST_HASHSET_ITEM, + ) + ) + .isTrue() + remove( + TEST_STRING_ITEM, + TEST_INT_ITEM, + TEST_BOOLEAN_ITEM, + TEST_FLOAT_ITEM, + TEST_LONG_ITEM, + TEST_SET_ITEM, + TEST_HASHSET_ITEM, ) - assertThat(has(TEST_BOOLEAN_ITEM, TEST_INT_ITEM, TEST_STRING_ITEM)).isTrue() - remove(TEST_STRING_ITEM, TEST_INT_ITEM, TEST_BOOLEAN_ITEM) } }