Snap for 13442527 from 7a2d5b454f to 25Q3-release

Change-Id: Ia55284cffca47cead4829848b14f843bde12a90e
This commit is contained in:
Android Build Coastguard Worker committed 2025-05-02 18:18:46 -07:00
commit be0aa1cb03
40 files changed
+463 -511

No files matched your search

+5 -2
View File
@@ -312,6 +312,8 @@ android_library {
srcs: [
"tests/tapl/**/*.java",
"tests/tapl/**/*.kt",
"tests/src_tapl_build_config/**/*.java",
"tests/src_tapl_build_config/**/*.kt",
],
resource_dirs: [],
manifest: "tests/tapl/AndroidManifest.xml",
@@ -388,6 +390,7 @@ android_library {
"//frameworks/libs/systemui:view_capture",
"//frameworks/libs/systemui:animationlib",
"//frameworks/libs/systemui:contextualeducationlib",
"//frameworks/libs/systemui:mechanics",
"//frameworks/libs/systemui:msdl",
"SystemUI-statsd",
"WindowManager-Shell-shared-AOSP",
@@ -404,7 +407,7 @@ android_library {
"com_android_systemui_shared_flags_lib",
"launcher-dagger-qualifiers",
"launcher-executor-qualifiers",
"launcher-executors-module"
"launcher-executors-module",
],
manifest: "AndroidManifest-common.xml",
sdk_version: "current",
@@ -430,7 +433,7 @@ android_app {
srcs: [
":launcher-src",
":launcher-src_no_quickstep",
":launcher-build-config"
":launcher-build-config",
],
optimize: {
+2
View File
@@ -94,6 +94,8 @@
<!-- How much a task being dragged for dismissal can undershoot the origin when dragged back to its start position. -->
<dimen name="task_dismiss_max_undershoot">25dp</dimen>
<!-- How much a task should be dragged from the origin before it detaches (or reattaches). -->
<dimen name="task_dismiss_detach_threshold">100dp</dimen>
<dimen name="task_icon_cache_default_icon_size">72dp</dimen>
<item name="overview_modal_max_scale" format="float" type="dimen">1.1</item>
@@ -0,0 +1,187 @@
/*
* 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.prediction.AppPredictionContext
import android.app.prediction.AppPredictionManager
import android.app.prediction.AppPredictor
import android.app.prediction.AppTarget
import android.app.prediction.AppTargetEvent
import android.content.Context
import android.content.Intent
import android.content.pm.LauncherApps
import android.content.pm.ShortcutInfo
import android.os.UserHandle
import android.os.UserManager
import androidx.annotation.VisibleForTesting
import com.android.launcher3.LauncherModel
import com.android.launcher3.LauncherModel.ModelUpdateTask
import com.android.launcher3.LauncherSettings.Favorites
import com.android.launcher3.dagger.ApplicationContext
import com.android.launcher3.icons.IconCache
import com.android.launcher3.icons.cache.CacheLookupFlag
import com.android.launcher3.model.data.AppInfo
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.ShortcutKey
import com.android.launcher3.shortcuts.ShortcutRequest
import com.android.launcher3.util.ApiWrapper
import com.android.launcher3.util.Executors.MODEL_EXECUTOR
import com.android.launcher3.util.PackageManagerHelper
import com.android.launcher3.util.PersistedItemArray
import com.android.launcher3.util.PersistedItemArray.ItemFactory
import dagger.assisted.Assisted
import dagger.assisted.AssistedFactory
import dagger.assisted.AssistedInject
/** [PersistedItemArray.ItemFactory] to parse predicted items */
class PredictedItemFactory
@AssistedInject
constructor(
@ApplicationContext private val context: Context,
private val pmHelper: PackageManagerHelper,
private val userCache: UserCache,
private val apiWrapper: ApiWrapper,
private val iconCache: IconCache,
@Assisted private val maxItemCount: Int,
@Assisted private val predictorState: PredictorState,
) : ItemFactory<ItemInfo> {
private val quietModeCache = mutableMapOf<UserHandle, Boolean>()
// Number of items persisted can be different than what is needed if the grid changed between
// the two operations
private var readCount = 0
override fun createInfo(itemType: Int, user: UserHandle, intent: Intent): ItemInfo? {
if (readCount >= maxItemCount) {
return null
}
when (itemType) {
Favorites.ITEM_TYPE_APPLICATION -> {
val lai =
context
.getSystemService(LauncherApps::class.java)
?.resolveActivity(intent, user) ?: return null
val info =
AppInfo(
lai,
userCache.getUserInfo(user),
apiWrapper,
pmHelper,
quietModeCache.getOrPut(user) {
context
.getSystemService(UserManager::class.java)
?.isQuietModeEnabled(user) ?: true
},
)
info.container = predictorState.containerId
iconCache.getTitleAndIcon(info, lai, predictorState.lookupFlag)
readCount++
return info.makeWorkspaceItem(context)
}
Favorites.ITEM_TYPE_DEEP_SHORTCUT -> {
val key = ShortcutKey.fromIntent(intent, user) ?: return null
val si: ShortcutInfo =
key.buildRequest(context).query(ShortcutRequest.PINNED).getOrNull(0)
?: return null
val wii = WorkspaceItemInfo(si, context)
wii.container = predictorState.containerId
iconCache.getShortcutIcon(wii, si)
readCount++
return wii
}
}
return null
}
@AssistedFactory
interface Factory {
fun newParser(maxItemCount: Int, predictorState: PredictorState): PredictedItemFactory
}
}
/** Class to manage predicted items for a particular prediction type */
class PredictorState(
@JvmField val containerId: Int,
storageName: String,
@JvmField val lookupFlag: CacheLookupFlag,
) {
@JvmField val storage: PersistedItemArray<ItemInfo> = PersistedItemArray(storageName)
@VisibleForTesting var predictor: AppPredictor? = null
private var lastTargets: List<AppTarget> = emptyList()
/** Creates and registers a predictor, and destroys any previously created predictor */
fun registerPredictor(
ctx: Context,
predictionContext: AppPredictionContext,
model: LauncherModel,
taskFactory: (PredictorState, List<AppTarget>) -> ModelUpdateTask,
) {
destroyPredictor()
val apm = ctx.getSystemService(AppPredictionManager::class.java) ?: return
lastTargets = emptyList()
predictor =
apm.createAppPredictionSession(predictionContext).apply {
registerPredictionUpdates(MODEL_EXECUTOR) {
val oldTargets = lastTargets
lastTargets = it
// If no diff, skip
if (
oldTargets.size != lastTargets.size ||
oldTargets.zip(lastTargets).any { (a1, a2) ->
!areAppTargetsSame(a1, a2)
}
) {
model.enqueueModelUpdateTask(taskFactory.invoke(this@PredictorState, it))
}
}
requestPredictionUpdate()
}
}
/** Destroys a previously created predictor */
fun destroyPredictor() {
predictor?.destroy()
predictor = null
}
/** see [AppPredictor.requestPredictionUpdate] */
fun requestPredictionUpdate() = predictor?.requestPredictionUpdate()
/** see [AppPredictor.notifyAppTargetEvent] */
fun notifyAppTargetEvent(event: AppTargetEvent) = predictor?.notifyAppTargetEvent(event)
/** Compares two targets for the properties which we care about */
private fun areAppTargetsSame(t1: AppTarget, t2: AppTarget): Boolean {
if (
(t1.packageName != t2.packageName) ||
(t1.user != t2.user) ||
(t1.className != t2.className)
) {
return false
}
return t1.shortcutInfo?.id == t2.shortcutInfo?.id
}
}
@@ -35,7 +35,6 @@ import com.android.launcher3.LauncherModel.ModelUpdateTask;
import com.android.launcher3.LauncherPrefs;
import com.android.launcher3.icons.IconCache;
import com.android.launcher3.model.BgDataModel.FixedContainerItems;
import com.android.launcher3.model.QuickstepModelDelegate.PredictorState;
import com.android.launcher3.model.data.AppInfo;
import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.model.data.WorkspaceItemInfo;
@@ -24,8 +24,6 @@ import static com.android.launcher3.LauncherSettings.Favorites.CONTAINER_HOTSEAT
import static com.android.launcher3.LauncherSettings.Favorites.CONTAINER_ALL_APPS_PREDICTION;
import static com.android.launcher3.LauncherSettings.Favorites.CONTAINER_WIDGETS_PREDICTION;
import static com.android.launcher3.LauncherSettings.Favorites.DESKTOP_ICON_FLAG;
import static com.android.launcher3.LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
import static com.android.launcher3.LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT;
import static com.android.launcher3.hybridhotseat.HotseatPredictionModel.convertDataModelToAppTargetBundle;
import static com.android.launcher3.icons.cache.CacheLookupFlag.DEFAULT_LOOKUP_FLAG;
import static com.android.launcher3.model.PredictionHelper.getAppTargetFromItemInfo;
@@ -36,22 +34,14 @@ import static java.util.stream.Collectors.toCollection;
import android.app.StatsManager;
import android.app.prediction.AppPredictionContext;
import android.app.prediction.AppPredictionManager;
import android.app.prediction.AppPredictor;
import android.app.prediction.AppTarget;
import android.app.prediction.AppTargetEvent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.LauncherActivityInfo;
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;
import androidx.annotation.AnyThread;
import androidx.annotation.CallSuper;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
@@ -60,36 +50,23 @@ import androidx.annotation.WorkerThread;
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;
import com.android.launcher3.logging.InstanceIdSequence;
import com.android.launcher3.model.BgDataModel.FixedContainerItems;
import com.android.launcher3.model.data.AppInfo;
import com.android.launcher3.model.data.CollectionInfo;
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.ShortcutKey;
import com.android.launcher3.util.ApiWrapper;
import com.android.launcher3.util.Executors;
import com.android.launcher3.util.IntSparseArrayMap;
import com.android.launcher3.util.PackageManagerHelper;
import com.android.launcher3.util.PersistedItemArray;
import com.android.quickstep.logging.SettingsChangeLogger;
import com.android.quickstep.logging.StatsLogCompatManager;
import com.android.quickstep.util.ContextualSearchStateManager;
import com.android.systemui.shared.system.SysUiStatsLog;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.IntStream;
import javax.inject.Inject;
import javax.inject.Named;
@@ -109,17 +86,18 @@ public class QuickstepModelDelegate extends ModelDelegate {
nonRestorableItem("LAST_SNAPSHOT_TIME_MILLIS", 0L, ENCRYPTED);
@VisibleForTesting
final PredictorState mAllAppsState = new PredictorState(
final PredictorState mAllPredictionAppsState = new PredictorState(
CONTAINER_ALL_APPS_PREDICTION, "all_apps_predictions", DEFAULT_LOOKUP_FLAG);
@VisibleForTesting
final PredictorState mHotseatState = new PredictorState(
final PredictorState mHotseatPredictionState = new PredictorState(
CONTAINER_HOTSEAT_PREDICTION, "hotseat_predictions", DESKTOP_ICON_FLAG);
@VisibleForTesting
final PredictorState mWidgetsRecommendationState = new PredictorState(
CONTAINER_WIDGETS_PREDICTION, "widgets_prediction", DESKTOP_ICON_FLAG);
private final InvariantDeviceProfile mIDP;
private final PackageManagerHelper mPmHelper;
private final UserCache mUserCache;
private final PredictedItemFactory.Factory mItemParserFactory;
private final AppEventProducer mAppEventProducer;
private final StatsManager mStatsManager;
@@ -129,11 +107,15 @@ public class QuickstepModelDelegate extends ModelDelegate {
@Inject
public QuickstepModelDelegate(@ApplicationContext Context context,
InvariantDeviceProfile idp,
PackageManagerHelper pmHelper,
UserCache userCache,
PredictedItemFactory.Factory itemParserFactory,
@Nullable @Named("ICONS_DB") String dbFileName) {
super(context);
mIDP = idp;
mPmHelper = pmHelper;
mUserCache = userCache;
mItemParserFactory = itemParserFactory;
mAppEventProducer = new AppEventProducer(context, this::onAppTargetEvent);
StatsLogCompatManager.LOGS_CONSUMER.add(mAppEventProducer);
@@ -146,74 +128,32 @@ public class QuickstepModelDelegate extends ModelDelegate {
@CallSuper
@Override
public void loadAndBindWorkspaceItems(@NonNull UserManagerState ums,
@NonNull BgDataModel.Callbacks[] callbacks,
@NonNull Map<ShortcutKey, ShortcutInfo> pinnedShortcuts) {
loadAndBindItems(ums, pinnedShortcuts, callbacks, mIDP.numDatabaseHotseatIcons,
mHotseatState);
public void loadAndBindWorkspaceItems() {
loadAndBindPredictedItems(mIDP.numDatabaseHotseatIcons, mHotseatPredictionState);
}
@CallSuper
@Override
public void loadAndBindAllAppsItems(@NonNull UserManagerState ums,
@NonNull BgDataModel.Callbacks[] callbacks,
@NonNull Map<ShortcutKey, ShortcutInfo> pinnedShortcuts) {
loadAndBindItems(ums, pinnedShortcuts, callbacks, mIDP.numDatabaseAllAppsColumns,
mAllAppsState);
public void loadAndBindAllAppsItems() {
loadAndBindPredictedItems(mIDP.numDatabaseAllAppsColumns, mAllPredictionAppsState);
}
@WorkerThread
private void loadAndBindItems(@NonNull UserManagerState ums,
@NonNull Map<ShortcutKey, ShortcutInfo> pinnedShortcuts,
@NonNull BgDataModel.Callbacks[] callbacks,
private void loadAndBindPredictedItems(
int numColumns, @NonNull PredictorState state) {
// TODO: Implement caching and preloading
WorkspaceItemFactory factory =
new WorkspaceItemFactory(mContext, ums, mPmHelper, pinnedShortcuts, numColumns,
state.containerId, state.lookupFlag);
PredictedItemFactory parser = mItemParserFactory.newParser(numColumns, state);
FixedContainerItems fci = new FixedContainerItems(state.containerId,
state.storage.read(mContext, factory, ums.allUsers::get));
state.storage.read(mContext, parser, mUserCache::getUserForSerialNumber));
mDataModel.extraItems.put(state.containerId, fci);
}
@CallSuper
@Override
public void loadAndBindOtherItems(@NonNull BgDataModel.Callbacks[] callbacks) {
public void loadAndBindOtherItems() {
FixedContainerItems widgetPredictionFCI = new FixedContainerItems(
mWidgetsRecommendationState.containerId, new ArrayList<>());
// Widgets prediction isn't used frequently. And thus, it is not persisted on disk.
mDataModel.extraItems.put(mWidgetsRecommendationState.containerId, widgetPredictionFCI);
bindPredictionItems(callbacks, widgetPredictionFCI);
loadStringCache(mDataModel.stringCache);
}
@AnyThread
private void bindPredictionItems(@NonNull BgDataModel.Callbacks[] callbacks,
@NonNull FixedContainerItems fci) {
Executors.MAIN_EXECUTOR.execute(() -> {
for (BgDataModel.Callbacks c : callbacks) {
c.bindExtraContainerItems(fci);
}
});
}
@Override
@WorkerThread
public void bindAllModelExtras(@NonNull BgDataModel.Callbacks[] callbacks) {
Iterable<FixedContainerItems> containerItems;
synchronized (mDataModel.extraItems) {
containerItems = mDataModel.extraItems.clone();
}
Executors.MAIN_EXECUTOR.execute(() -> {
for (BgDataModel.Callbacks c : callbacks) {
for (FixedContainerItems fci : containerItems) {
c.bindExtraContainerItems(fci);
}
}
});
}
public void markActive() {
@@ -330,12 +270,8 @@ public class QuickstepModelDelegate extends ModelDelegate {
@Override
public void validateData() {
super.validateData();
if (mAllAppsState.predictor != null) {
mAllAppsState.predictor.requestPredictionUpdate();
}
if (mWidgetsRecommendationState.predictor != null) {
mWidgetsRecommendationState.predictor.requestPredictionUpdate();
}
mAllPredictionAppsState.requestPredictionUpdate();
mWidgetsRecommendationState.requestPredictionUpdate();
}
@WorkerThread
@@ -355,8 +291,8 @@ public class QuickstepModelDelegate extends ModelDelegate {
}
private void destroyPredictors() {
mAllAppsState.destroyPredictor();
mHotseatState.destroyPredictor();
mAllPredictionAppsState.destroyPredictor();
mHotseatPredictionState.destroyPredictor();
mWidgetsRecommendationState.destroyPredictor();
}
@@ -366,78 +302,45 @@ public class QuickstepModelDelegate extends ModelDelegate {
if (!mActive) {
return;
}
AppPredictionManager apm = mContext.getSystemService(AppPredictionManager.class);
if (apm == null) {
return;
}
registerPredictor(mAllAppsState, apm.createAppPredictionSession(
mAllPredictionAppsState.registerPredictor(mContext,
new AppPredictionContext.Builder(mContext)
.setUiSurface("home")
.setPredictedTargetCount(mIDP.numDatabaseAllAppsColumns)
.build()));
.setUiSurface("home")
.setPredictedTargetCount(mIDP.numDatabaseAllAppsColumns)
.build(),
mModel,
PredictionUpdateTask::new);
// TODO: get bundle
registerHotseatPredictor(apm, mContext);
registerHotseatPredictor(mContext);
registerWidgetsPredictor(apm.createAppPredictionSession(
mWidgetsRecommendationState.registerPredictor(mContext,
new AppPredictionContext.Builder(mContext)
.setUiSurface("widgets")
.setExtras(getBundleForWidgetsOnWorkspace(mContext, mDataModel))
.setPredictedTargetCount(NUM_OF_RECOMMENDED_WIDGETS_PREDICATION)
.build()));
.setUiSurface("widgets")
.setExtras(getBundleForWidgetsOnWorkspace(mContext, mDataModel))
.setPredictedTargetCount(NUM_OF_RECOMMENDED_WIDGETS_PREDICATION)
.build(),
mModel,
WidgetsPredictionUpdateTask::new);
}
@WorkerThread
private void recreateHotseatPredictor() {
mHotseatState.destroyPredictor();
if (!mActive) {
return;
mHotseatPredictionState.destroyPredictor();
if (mActive) {
registerHotseatPredictor(mContext);
}
AppPredictionManager apm = mContext.getSystemService(AppPredictionManager.class);
if (apm == null) {
return;
}
registerHotseatPredictor(apm, mContext);
}
private void registerHotseatPredictor(AppPredictionManager apm, Context context) {
registerPredictor(mHotseatState, apm.createAppPredictionSession(
private void registerHotseatPredictor(Context context) {
mHotseatPredictionState.registerPredictor(context,
new AppPredictionContext.Builder(context)
.setUiSurface("hotseat")
.setPredictedTargetCount(mIDP.numDatabaseHotseatIcons)
.setExtras(convertDataModelToAppTargetBundle(context, mDataModel))
.build()));
}
private void registerPredictor(PredictorState state, AppPredictor predictor) {
state.setTargets(Collections.emptyList());
state.predictor = predictor;
state.predictor.registerPredictionUpdates(
MODEL_EXECUTOR, t -> handleUpdate(state, t));
state.predictor.requestPredictionUpdate();
}
private void handleUpdate(PredictorState state, List<AppTarget> targets) {
if (state.setTargets(targets)) {
// No diff, skip
return;
}
mModel.enqueueModelUpdateTask(new PredictionUpdateTask(state, targets));
}
private void registerWidgetsPredictor(AppPredictor predictor) {
mWidgetsRecommendationState.predictor = predictor;
mWidgetsRecommendationState.predictor.registerPredictionUpdates(
MODEL_EXECUTOR, targets -> {
if (mWidgetsRecommendationState.setTargets(targets)) {
// No diff, skip
return;
}
mModel.enqueueModelUpdateTask(
new WidgetsPredictionUpdateTask(mWidgetsRecommendationState, targets));
});
mWidgetsRecommendationState.predictor.requestPredictionUpdate();
.setUiSurface("hotseat")
.setPredictedTargetCount(mIDP.numDatabaseHotseatIcons)
.setExtras(convertDataModelToAppTargetBundle(context, mDataModel))
.build(),
mModel, PredictionUpdateTask::new);
}
@VisibleForTesting
@@ -445,27 +348,26 @@ public class QuickstepModelDelegate extends ModelDelegate {
PredictorState state;
switch(client) {
case CONTAINER_ALL_APPS_PREDICTION:
state = mAllAppsState;
state = mAllPredictionAppsState;
break;
case CONTAINER_WIDGETS_PREDICTION:
state = mWidgetsRecommendationState;
break;
case CONTAINER_HOTSEAT_PREDICTION:
default:
state = mHotseatState;
state = mHotseatPredictionState;
break;
}
if (state.predictor != null) {
state.predictor.notifyAppTargetEvent(event);
Log.d(TAG, "notifyAppTargetEvent action=" + event.getAction()
+ " launchLocation=" + event.getLaunchLocation());
if (state == mHotseatState
&& (event.getAction() == AppTargetEvent.ACTION_PIN
|| event.getAction() == AppTargetEvent.ACTION_UNPIN)) {
// Recreate hot seat predictor when we need to query for hot seat due to pin or
// unpin app icons.
recreateHotseatPredictor();
}
state.notifyAppTargetEvent(event);
Log.d(TAG, "notifyAppTargetEvent action=" + event.getAction()
+ " launchLocation=" + event.getLaunchLocation());
if (state == mHotseatPredictionState
&& (event.getAction() == AppTargetEvent.ACTION_PIN
|| event.getAction() == AppTargetEvent.ACTION_UNPIN)) {
// Recreate hot seat predictor when we need to query for hot seat due to pin or
// unpin app icons.
recreateHotseatPredictor();
}
}
@@ -485,133 +387,4 @@ public class QuickstepModelDelegate extends ModelDelegate {
bundle.putParcelableArrayList(BUNDLE_KEY_ADDED_APP_WIDGETS, widgetEvents);
return bundle;
}
static class PredictorState {
public final int containerId;
public final PersistedItemArray<ItemInfo> storage;
public AppPredictor predictor;
public CacheLookupFlag lookupFlag;
private List<AppTarget> mLastTargets;
PredictorState(int containerId, String storageName, CacheLookupFlag lookupFlag) {
this.containerId = containerId;
storage = new PersistedItemArray<>(storageName);
mLastTargets = Collections.emptyList();
this.lookupFlag = lookupFlag;
}
public void destroyPredictor() {
if (predictor != null) {
predictor.destroy();
predictor = null;
}
}
/**
* Sets the new targets and returns true if it was the same as before.
*/
boolean setTargets(List<AppTarget> newTargets) {
List<AppTarget> oldTargets = mLastTargets;
mLastTargets = newTargets;
int size = oldTargets.size();
return size == newTargets.size() && IntStream.range(0, size)
.allMatch(i -> areAppTargetsSame(oldTargets.get(i), newTargets.get(i)));
}
}
/**
* Compares two targets for the properties which we care about
*/
private static boolean areAppTargetsSame(AppTarget t1, AppTarget t2) {
if (!Objects.equals(t1.getPackageName(), t2.getPackageName())
|| !Objects.equals(t1.getUser(), t2.getUser())
|| !Objects.equals(t1.getClassName(), t2.getClassName())) {
return false;
}
ShortcutInfo s1 = t1.getShortcutInfo();
ShortcutInfo s2 = t2.getShortcutInfo();
if (s1 != null) {
if (s2 == null || !Objects.equals(s1.getId(), s2.getId())) {
return false;
}
} else if (s2 != null) {
return false;
}
return true;
}
private static class WorkspaceItemFactory implements PersistedItemArray.ItemFactory<ItemInfo> {
private final Context mContext;
private final UserManagerState mUMS;
private final PackageManagerHelper mPmHelper;
private final Map<ShortcutKey, ShortcutInfo> mPinnedShortcuts;
private final int mMaxCount;
private final int mContainer;
private final CacheLookupFlag mLookupFlag;
private int mReadCount = 0;
protected WorkspaceItemFactory(
Context context, UserManagerState ums,
PackageManagerHelper pmHelper, Map<ShortcutKey, ShortcutInfo> pinnedShortcuts,
int maxCount, int container, CacheLookupFlag lookupFlag) {
mContext = context;
mUMS = ums;
mPmHelper = pmHelper;
mPinnedShortcuts = pinnedShortcuts;
mMaxCount = maxCount;
mContainer = container;
mLookupFlag = lookupFlag;
}
@Nullable
@Override
public ItemInfo createInfo(int itemType, UserHandle user, Intent intent) {
if (mReadCount >= mMaxCount) {
return null;
}
switch (itemType) {
case ITEM_TYPE_APPLICATION: {
LauncherActivityInfo lai = mContext
.getSystemService(LauncherApps.class)
.resolveActivity(intent, user);
if (lai == null) {
return null;
}
AppInfo info = new AppInfo(
lai,
UserCache.INSTANCE.get(mContext).getUserInfo(user),
ApiWrapper.INSTANCE.get(mContext),
mPmHelper,
mUMS.isUserQuiet(user));
info.container = mContainer;
LauncherAppState.getInstance(mContext).getIconCache()
.getTitleAndIcon(info, lai, mLookupFlag);
mReadCount++;
return info.makeWorkspaceItem(mContext);
}
case ITEM_TYPE_DEEP_SHORTCUT: {
ShortcutKey key = ShortcutKey.fromIntent(intent, user);
if (key == null) {
return null;
}
ShortcutInfo si = mPinnedShortcuts.get(key);
if (si == null) {
return null;
}
WorkspaceItemInfo wii = new WorkspaceItemInfo(si, mContext);
wii.container = mContainer;
LauncherAppState.getInstance(mContext).getIconCache().getShortcutIcon(wii, si);
mReadCount++;
return wii;
}
}
return null;
}
}
}
@@ -32,7 +32,6 @@ import androidx.annotation.NonNull;
import com.android.launcher3.LauncherModel.ModelUpdateTask;
import com.android.launcher3.R;
import com.android.launcher3.model.BgDataModel.FixedContainerItems;
import com.android.launcher3.model.QuickstepModelDelegate.PredictorState;
import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.util.ComponentKey;
import com.android.launcher3.widget.PendingAddWidgetInfo;
@@ -281,16 +281,18 @@ public class KeyboardQuickSwitchViewController {
if (task == null) {
return mOnDesktop ? 1 : Math.max(0, index);
}
if (mControllerCallbacks.isTaskRunning(task)) {
// Ignore attempts to run the selected task if it is already running.
return -1;
}
if (enableAltTabKqsFlatenning.isTrue()
&& tryLaunchingCombinedTask(task, slideInTransition, systemUiProxy)) {
return -1;
}
// TODO b/414410702: move this check to before tryLaunchingCombinedTask() call.
if (mControllerCallbacks.isTaskRunning(task)) {
// Ignore attempts to run the selected task if it is already running.
return -1;
}
RemoteTransition remoteTransition = slideInTransition;
boolean canUnminimizeDesktopTask = task instanceof SingleTask singleTask
&& mControllers.taskbarActivityContext.canUnminimizeDesktopTask(
@@ -17,6 +17,8 @@ package com.android.launcher3.taskbar;
import static android.view.Display.DEFAULT_DISPLAY;
import static com.android.launcher3.EncryptionType.ENCRYPTED;
import static com.android.launcher3.LauncherPrefs.nonRestorableItem;
import static com.android.launcher3.taskbar.Utilities.getShapedTaskbarRadius;
import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_NAV_BAR_HIDDEN;
@@ -24,13 +26,13 @@ import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Outline;
import android.graphics.Rect;
import android.view.View;
import android.view.ViewOutlineProvider;
import com.android.launcher3.ConstantItem;
import com.android.launcher3.DeviceProfile;
import com.android.launcher3.Flags;
import com.android.launcher3.LauncherPrefs;
@@ -69,8 +71,11 @@ public class StashedHandleViewController implements TaskbarControllers.LoggableT
private static final String SHARED_PREFS_STASHED_HANDLE_REGION_DARK_KEY =
"stashed_handle_region_is_dark";
private static final ConstantItem<Boolean> STASHED_HANDLE_REGION_IS_DARK =
nonRestorableItem(SHARED_PREFS_STASHED_HANDLE_REGION_DARK_KEY, false, ENCRYPTED);
private final TaskbarActivityContext mActivity;
private final SharedPreferences mPrefs;
private final LauncherPrefs mPrefs;
private final StashedHandleView mStashedHandleView;
private int mStashedHandleWidth;
private final int mStashedHandleHeight;
@@ -104,13 +109,12 @@ public class StashedHandleViewController implements TaskbarControllers.LoggableT
public StashedHandleViewController(TaskbarActivityContext activity,
StashedHandleView stashedHandleView) {
mActivity = activity;
mPrefs = LauncherPrefs.getPrefs(mActivity);
mPrefs = LauncherPrefs.get(mActivity);
mStashedHandleView = stashedHandleView;
mTaskbarStashedHandleAlpha = new MultiValueAlpha(mStashedHandleView, NUM_ALPHA_CHANNELS);
mTaskbarStashedHandleAlpha.setUpdateVisibility(true);
mStashedHandleView.updateHandleColor(
mPrefs.getBoolean(SHARED_PREFS_STASHED_HANDLE_REGION_DARK_KEY, false),
false /* animate */);
mPrefs.get(STASHED_HANDLE_REGION_IS_DARK), false /* animate */);
final Resources resources = mActivity.getResources();
mStashedHandleHeight = resources.getDimensionPixelSize(
R.dimen.taskbar_stashed_handle_height);
@@ -184,8 +188,7 @@ public class StashedHandleViewController implements TaskbarControllers.LoggableT
@Override
public void onRegionDarknessChanged(boolean isRegionDark) {
mStashedHandleView.updateHandleColor(isRegionDark, true /* animate */);
mPrefs.edit().putBoolean(SHARED_PREFS_STASHED_HANDLE_REGION_DARK_KEY,
isRegionDark).apply();
mPrefs.put(STASHED_HANDLE_REGION_IS_DARK, isRegionDark);
}
@Override
@@ -729,10 +729,10 @@ public class TaskbarManagerImpl implements DisplayDecorationListener {
/** Creates a {@link TaskbarUIController} to use with non default displays. */
private TaskbarUIController createTaskbarUIControllerForNonDefaultDisplay(int displayId) {
debugPrimaryTaskbar("createTaskbarUIControllerForNonDefaultDisplay");
debugTaskbarManager("createTaskbarUIControllerForNonDefaultDisplay", displayId);
RecentsViewContainer rvc = OverviewComponentObserver.INSTANCE.get(
mBaseContext).getContainerInterface(displayId).getCreatedContainer();
if (rvc != null) {
if (rvc instanceof RecentsWindowManager) {
return createTaskbarUIControllerForRecentsViewContainer(rvc);
}
@@ -268,13 +268,11 @@ public class TaskbarAllAppsSlideInView extends AbstractSlideInView<TaskbarOverla
@Override
protected int getScrimColor(Context context) {
if (!mActivityContext.getDeviceProfile().shouldShowAllAppsOnSheet()) {
// Always use an opaque scrim if there's no sheet.
return context.getResources().getColor(R.color.materialColorSurfaceDim);
if (mActivityContext.getDeviceProfile().shouldShowAllAppsOnSheet()
&& !Flags.allAppsBlur()) {
return context.getResources().getColor(R.color.widgets_picker_scrim);
}
return Flags.allAppsBlur() ? Themes.getAttrColor(context, R.attr.allAppsScrimColor)
: context.getResources().getColor(R.color.widgets_picker_scrim);
return Themes.getAttrColor(context, R.attr.allAppsScrimColor);
}
@Override
@@ -204,12 +204,9 @@ public class AllAppsState extends LauncherState {
@Override
public int getWorkspaceScrimColor(Launcher launcher) {
if (!launcher.getDeviceProfile().shouldShowAllAppsOnSheet()) {
// Always use an opaque scrim if there's no sheet.
return launcher.getResources().getColor(R.color.materialColorSurfaceDim);
if (launcher.getDeviceProfile().shouldShowAllAppsOnSheet() && !Flags.allAppsBlur()) {
return launcher.getResources().getColor(R.color.widgets_picker_scrim);
}
return Flags.allAppsBlur() ? Themes.getAttrColor(launcher, R.attr.allAppsScrimColor)
: launcher.getResources().getColor(R.color.widgets_picker_scrim);
return Themes.getAttrColor(launcher, R.attr.allAppsScrimColor);
}
}
@@ -34,6 +34,18 @@ import com.android.launcher3.statemanager.StatefulContainer
import com.android.launcher3.touch.SingleAxisSwipeDetector
import com.android.launcher3.util.MSDLPlayerWrapper
import com.android.launcher3.util.TouchController
import com.android.mechanics.spec.Breakpoint
import com.android.mechanics.spec.Breakpoint.Companion.maxLimit
import com.android.mechanics.spec.Breakpoint.Companion.minLimit
import com.android.mechanics.spec.BreakpointKey
import com.android.mechanics.spec.DirectionalMotionSpec
import com.android.mechanics.spec.Guarantee
import com.android.mechanics.spec.InputDirection
import com.android.mechanics.spec.Mapping
import com.android.mechanics.spec.MotionSpec
import com.android.mechanics.spring.SpringParameters
import com.android.mechanics.view.DistanceGestureContext
import com.android.mechanics.view.ViewMotionValue
import com.android.quickstep.views.RecentsView
import com.android.quickstep.views.RecentsView.RECENTS_SCALE_PROPERTY
import com.android.quickstep.views.RecentsViewContainer
@@ -59,6 +71,10 @@ CONTAINER : StatefulContainer<T> {
)
private val isRtl = isRtl(container.resources)
private val upDirection: Int = recentsView.pagedOrientationHandler.getUpDirection(isRtl)
private val maxUndershoot =
container.resources.getDimension(R.dimen.task_dismiss_max_undershoot)
private val detachThreshold =
container.resources.getDimension(R.dimen.task_dismiss_detach_threshold)
private val stateListener =
object : StateListener<T> {
override fun onStateTransitionStart(toState: T) {
@@ -69,6 +85,7 @@ CONTAINER : StatefulContainer<T> {
private val tempTaskThumbnailBounds = Rect()
private var taskBeingDragged: TaskView? = null
private var taskDragDisplacementValue: ViewMotionValue? = null
private var springAnimation: SpringAnimation? = null
private var dismissLength: Int = 0
private var verticalFactor: Int = 0
@@ -196,6 +213,24 @@ CONTAINER : StatefulContainer<T> {
initialDisplacement =
taskBeingDragged.secondaryDismissTranslationProperty.get(taskBeingDragged)
taskDragDisplacementValue =
generateMotionValue(
initialDisplacement,
detachThreshold * verticalFactor,
container.asContext(),
) { currentDisplacement ->
taskBeingDragged.secondaryDismissTranslationProperty.setValue(
taskBeingDragged,
currentDisplacement,
)
if (taskBeingDragged.isRunningTask && recentsView.enableDrawingLiveTile) {
recentsView.runActionOnRemoteHandles { remoteTargetHandle ->
remoteTargetHandle.taskViewSimulator.taskSecondaryTranslation.value =
currentDisplacement
}
recentsView.redrawLiveTile()
}
}
// Add a tiny bit of translation Z, so that it draws on top of other views. This is relevant
// (e.g.) when we dismiss a task by sliding it upward: if there is a row of icons above, we
@@ -205,35 +240,26 @@ CONTAINER : StatefulContainer<T> {
override fun onDrag(displacement: Float): Boolean {
if (isBlockedDuringDismissal) return true
val taskBeingDragged = taskBeingDragged ?: return false
taskBeingDragged ?: return false
val currentDisplacement = displacement + initialDisplacement
val boundedDisplacement =
boundToRange(abs(currentDisplacement), 0f, dismissLength.toFloat())
// When swiping below origin, allow slight undershoot to simulate resisting the movement.
val isAboveOrigin =
recentsView.pagedOrientationHandler.isGoingUp(currentDisplacement, isRtl)
val totalDisplacement =
if (recentsView.pagedOrientationHandler.isGoingUp(currentDisplacement, isRtl))
boundedDisplacement * verticalFactor
if (isAboveOrigin) boundedDisplacement * verticalFactor
else
mapToRange(
boundedDisplacement,
0f,
dismissLength.toFloat(),
0f,
container.resources.getDimension(R.dimen.task_dismiss_max_undershoot),
maxUndershoot,
DECELERATE,
) * -verticalFactor
taskBeingDragged.secondaryDismissTranslationProperty.setValue(
taskBeingDragged,
totalDisplacement,
)
if (taskBeingDragged.isRunningTask && recentsView.enableDrawingLiveTile) {
recentsView.runActionOnRemoteHandles { remoteTargetHandle ->
remoteTargetHandle.taskViewSimulator.taskSecondaryTranslation.value =
totalDisplacement
}
recentsView.redrawLiveTile()
}
val dismissFraction = displacement / (dismissLength * verticalFactor).toFloat()
taskDragDisplacementValue?.input = totalDisplacement
RECENTS_SCALE_PROPERTY.setValue(recentsView, getRecentsScale(dismissFraction))
playDismissThresholdHaptic(displacement)
return true
@@ -262,6 +288,7 @@ CONTAINER : StatefulContainer<T> {
override fun onDragEnd(velocity: Float) {
if (isBlockedDuringDismissal) return
val taskBeingDragged = taskBeingDragged ?: return
taskDragDisplacementValue?.dispose()
val currentDisplacement =
taskBeingDragged.secondaryDismissTranslationProperty.get(taskBeingDragged)
@@ -299,6 +326,7 @@ CONTAINER : StatefulContainer<T> {
taskBeingDragged?.translationZ = 0f
taskBeingDragged = null
springAnimation = null
taskDragDisplacementValue = null
isBlockedDuringDismissal = false
}
@@ -341,6 +369,43 @@ CONTAINER : StatefulContainer<T> {
}
}
private fun generateMotionValue(
initialDisplacement: Float,
detachThreshold: Float,
context: Context,
updateCallback: (Float) -> Unit,
): ViewMotionValue {
val direction = if (initialDisplacement < 0) InputDirection.Max else InputDirection.Min
val distanceGestureContext =
DistanceGestureContext.create(context, initialDisplacement, direction)
val viewMotionValue =
ViewMotionValue(
initialDisplacement,
distanceGestureContext,
generateMotionSpec(detachThreshold),
label = "taskDismiss::displacement",
)
viewMotionValue.addUpdateCallback { motionValue -> updateCallback(motionValue.output) }
return viewMotionValue
}
/** Motion spec for an initial magnetic detach. Track linearly otherwise. No reattach. */
private fun generateMotionSpec(detachThreshold: Float): MotionSpec {
val spring = SpringParameters(stiffness = 800f, dampingRatio = 0.95f)
val detachKey = BreakpointKey("TaskDismiss::Detach")
val breakpoints = mutableListOf<Breakpoint>()
val mappings = mutableListOf<Mapping>()
breakpoints.add(minLimit)
mappings.add(Mapping.Identity)
breakpoints.add(Breakpoint(detachKey, detachThreshold, spring, Guarantee.None))
mappings.add(Mapping.Linear(0.3f))
breakpoints.add(maxLimit)
return MotionSpec(DirectionalMotionSpec(breakpoints, mappings))
}
companion object {
private const val TAG = "TaskViewDismissTouchController"
@@ -343,6 +343,7 @@ constructor(
}
stateManager.moveToRestState()
callbacks?.removeListener(recentsAnimationListener)
callbacks = null
}
private fun isShowing(): Boolean {
@@ -402,7 +402,10 @@ class DesktopTaskView @JvmOverloads constructor(context: Context, attrs: Attribu
} else {
taskContentView
}
if (enableDesktopExplodedView()) {
if (enableDesktopExplodedView() && !enableMultipleDesktops(context)) {
// Note, currently there are some issues with launching an individual app window
// with multi-desks enabled, see b/413378320. Will enable this functionality
// after b/413378320 is fixed.
snapshotView.setOnClickListener {
launchTaskWithDesktopController(animated = true, task.key.id)
}
@@ -1289,6 +1289,7 @@ public abstract class RecentsView<
if (mDesktopVisibilityController != null) {
mDesktopVisibilityController.unregisterDesktopVisibilityListener(mUtils);
}
mOnTaskLaunchCancelledRunnable = null;
reset();
}
@@ -19,7 +19,7 @@ package com.android.quickstep.util;
import static com.android.quickstep.util.QuickstepProtoLogGroup.RECENTS_WINDOW;
import static com.android.quickstep.util.QuickstepProtoLogGroup.isProtoLogInitialized;
import android.window.DesktopModeFlags;
import android.window.DesktopExperienceFlags;
import androidx.annotation.NonNull;
@@ -37,8 +37,13 @@ import com.android.launcher3.Flags;
* method. Or, if an existing entry needs to be modified, simply update it here.
*/
public class RecentsWindowProtoLogProxy {
private static final DesktopModeFlags.DesktopModeFlag ENABLE_RECENTS_WINDOW_PROTO_LOG =
new DesktopModeFlags.DesktopModeFlag(Flags::enableRecentsWindowProtoLog, true);
private static final DesktopExperienceFlags.DesktopExperienceFlag
ENABLE_RECENTS_WINDOW_PROTO_LOG =
new DesktopExperienceFlags.DesktopExperienceFlag(
Flags::enableRecentsWindowProtoLog,
false,
Flags.FLAG_ENABLE_RECENTS_WINDOW_PROTO_LOG);
public static void logOnStateSetStart(@NonNull String stateName) {
if (!ENABLE_RECENTS_WINDOW_PROTO_LOG.isTrue() || !isProtoLogInitialized()) return;
ProtoLog.d(RECENTS_WINDOW, "onStateSetStart: %s", stateName);
@@ -51,6 +51,7 @@ class QuickstepModelDelegateTest {
@Mock private lateinit var allAppsPredictor: AppPredictor
@Mock private lateinit var hotseatPredictor: AppPredictor
@Mock private lateinit var widgetRecommendationPredictor: AppPredictor
@Mock private lateinit var itemParserFactory: PredictedItemFactory.Factory
@Before
fun setUp() {
@@ -59,11 +60,12 @@ class QuickstepModelDelegateTest {
QuickstepModelDelegate(
context,
context.appComponent.idp,
context.appComponent.packageManagerHelper,
context.appComponent.userCache,
itemParserFactory,
"", /* dbFileName */
)
underTest.mAllAppsState.predictor = allAppsPredictor
underTest.mHotseatState.predictor = hotseatPredictor
underTest.mAllPredictionAppsState.predictor = allAppsPredictor
underTest.mHotseatPredictionState.predictor = hotseatPredictor
underTest.mWidgetsRecommendationState.predictor = widgetRecommendationPredictor
underTest.mModel = LauncherAppState.getInstance(context).model
underTest.mDataModel =
@@ -113,31 +115,31 @@ class QuickstepModelDelegateTest {
@Test
fun hotseatActionPin_recreateHotSeat() {
assertSame(underTest.mHotseatState.predictor, hotseatPredictor)
assertSame(underTest.mHotseatPredictionState.predictor, hotseatPredictor)
val appTargetEvent = AppTargetEvent.Builder(target, AppTargetEvent.ACTION_PIN).build()
underTest.markActive()
underTest.onAppTargetEvent(appTargetEvent, CONTAINER_HOTSEAT_PREDICTION)
verify(hotseatPredictor).destroy()
assertNotSame(underTest.mHotseatState.predictor, hotseatPredictor)
assertNotSame(underTest.mHotseatPredictionState.predictor, hotseatPredictor)
}
@Test
fun hotseatActionUnpin_recreateHotSeat() {
assertSame(underTest.mHotseatState.predictor, hotseatPredictor)
assertSame(underTest.mHotseatPredictionState.predictor, hotseatPredictor)
underTest.markActive()
val appTargetEvent = AppTargetEvent.Builder(target, AppTargetEvent.ACTION_UNPIN).build()
underTest.onAppTargetEvent(appTargetEvent, CONTAINER_HOTSEAT_PREDICTION)
verify(hotseatPredictor).destroy()
assertNotSame(underTest.mHotseatState.predictor, hotseatPredictor)
assertNotSame(underTest.mHotseatPredictionState.predictor, hotseatPredictor)
}
@Test
fun container_actionPin_notRecreateHotSeat() {
assertSame(underTest.mHotseatState.predictor, hotseatPredictor)
assertSame(underTest.mHotseatPredictionState.predictor, hotseatPredictor)
val appTargetEvent = AppTargetEvent.Builder(target, AppTargetEvent.ACTION_UNPIN).build()
underTest.markActive()
@@ -145,6 +147,6 @@ class QuickstepModelDelegateTest {
verify(allAppsPredictor, never()).destroy()
verify(hotseatPredictor, never()).destroy()
assertSame(underTest.mHotseatState.predictor, hotseatPredictor)
assertSame(underTest.mHotseatPredictionState.predictor, hotseatPredictor)
}
}
@@ -60,6 +60,7 @@ import com.android.wm.shell.shared.split.SplitScreenConstants
import com.google.common.truth.Truth.assertThat
import dagger.BindsInstance
import dagger.Component
import org.junit.Ignore;
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@@ -75,6 +76,7 @@ import org.mockito.kotlin.whenever
@RunWith(LauncherMultivalentJUnit::class)
@EmulatedDevices(["pixelTablet2023"])
@Ignore("b/413540825")
class KeyboardQuickSwitchControllerTest {
private var systemUiProxySpy: SystemUiProxy? = null
private var desktopTaskListener: IDesktopTaskListener? = null
@@ -55,7 +55,6 @@ import com.android.launcher3.Flags;
import com.android.launcher3.LauncherAppState;
import com.android.launcher3.LauncherModel;
import com.android.launcher3.model.BgDataModel.FixedContainerItems;
import com.android.launcher3.model.QuickstepModelDelegate.PredictorState;
import com.android.launcher3.util.LauncherLayoutBuilder;
import com.android.launcher3.util.ModelTestExtensions;
import com.android.launcher3.util.SandboxApplication;
@@ -41,6 +41,7 @@ import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.RemoteException;
import android.platform.test.rule.ExtendedLongPressTimeoutRule;
import androidx.test.filters.LargeTest;
import androidx.test.runner.AndroidJUnit4;
@@ -57,7 +58,6 @@ import com.android.launcher3.testcomponent.TestCommandReceiver;
import com.android.launcher3.ui.AbstractLauncherUiTest;
import com.android.launcher3.util.TestUtil;
import com.android.launcher3.util.Wait;
import com.android.launcher3.util.rule.ExtendedLongPressTimeoutRule;
import com.android.launcher3.util.rule.FailureWatcher;
import com.android.launcher3.util.rule.MutualExclusionRule;
import com.android.launcher3.util.rule.SamplerRule;
@@ -205,12 +205,16 @@ public class NavigationModeSwitchRule implements TestRule {
private static void assertTrue(LauncherInstrumentation launcher, String message,
boolean condition, Description description) {
launcher.checkForAnomaly(true, true);
if (!condition) {
try {
launcher.checkForAnomaly(true, true);
if (!condition) {
throw new AssertionError(message);
}
} catch (Throwable e) {
if (description != null) {
FailureWatcher.onError(launcher, description);
}
throw new AssertionError(message);
throw e;
}
}
}
@@ -152,7 +152,7 @@ public class TaplTestsKeyboardQuickSwitch extends AbstractQuickStepTest {
@Test
public void testLaunchSingleRecentTask() {
mLauncher.getLaunchedAppState().switchToOverview().dismissAllTasks();
clearAllRecentTasks();
startAppFast(CALCULATOR_APP_PACKAGE);
mLauncher.goHome().showQuickSwitchView().launchFocusedAppTask(CALCULATOR_APP_PACKAGE);
}
@@ -35,10 +35,7 @@ import org.junit.Test
class TaplTestsOverviewDesktop : AbstractQuickStepTest() {
@Before
fun setup() {
val overview = mLauncher.goHome().switchToOverview()
if (overview.hasTasks()) {
overview.dismissAllTasks()
}
clearAllRecentTasks()
startTestAppsWithCheck()
mLauncher.goHome()
}
@@ -548,7 +548,7 @@ public class TaplTestsQuickstep extends AbstractQuickStepTest {
@EnableFlags(value = Flags.FLAG_ENABLE_GRID_ONLY_OVERVIEW)
public void testDismissBottomRow() throws Exception {
assumeTrue(mLauncher.isTablet());
mLauncher.goHome().switchToOverview().dismissAllTasks();
clearAllRecentTasks();
startTestAppsWithCheck();
Overview overview = mLauncher.goHome().switchToOverview();
@@ -570,7 +570,7 @@ public class TaplTestsQuickstep extends AbstractQuickStepTest {
@EnableFlags(value = Flags.FLAG_ENABLE_GRID_ONLY_OVERVIEW)
public void testDismissLastGridRow() throws Exception {
assumeTrue(mLauncher.isTablet());
mLauncher.goHome().switchToOverview().dismissAllTasks();
clearAllRecentTasks();
startTestAppsWithCheck();
startTestActivity(3);
startTestActivity(4);
@@ -40,7 +40,6 @@ import com.android.launcher3.model.ModelLauncherCallbacks
import com.android.launcher3.model.ModelTaskController
import com.android.launcher3.model.ModelWriter
import com.android.launcher3.model.PackageUpdatedTask
import com.android.launcher3.model.ReloadStringCacheTask
import com.android.launcher3.model.ShortcutsChangedTask
import com.android.launcher3.model.UserLockStateChangedTask
import com.android.launcher3.model.UserManagerState
@@ -157,10 +156,6 @@ constructor(
MODEL_EXECUTOR.execute { modelDelegate.destroy() }
}
fun reloadStringCache() {
enqueueModelUpdateTask(ReloadStringCacheTask(this.modelDelegate))
}
/**
* Called then there use a user event
*
@@ -185,7 +185,7 @@ public class FirstScreenBroadcast {
* is always modified on UI thread.
*/
@AnyThread
private static List<WorkspaceItemInfo> cloneOnMainThread(ArrayList<WorkspaceItemInfo> list) {
private static List<WorkspaceItemInfo> cloneOnMainThread(List<WorkspaceItemInfo> list) {
try {
return MAIN_EXECUTOR.submit(() -> new ArrayList(list)).get();
} catch (Exception e) {
@@ -348,7 +348,7 @@ object FirstScreenBroadcastHelper {
* always modified on UI thread.
*/
@AnyThread
private fun cloneOnMainThread(list: ArrayList<WorkspaceItemInfo>): List<WorkspaceItemInfo> {
private fun cloneOnMainThread(list: List<WorkspaceItemInfo>): List<WorkspaceItemInfo> {
return try {
return Executors.MAIN_EXECUTOR.submit<ArrayList<WorkspaceItemInfo>> { ArrayList(list) }
.get()
@@ -509,11 +509,10 @@ public class LoaderTask implements Runnable {
IOUtils.closeSilently(c);
}
mModelDelegate.loadAndBindWorkspaceItems(mUserManagerState,
mLauncherBinder.mCallbacksList, mShortcutKeyToPinnedShortcuts);
mModelDelegate.loadAndBindAllAppsItems(mUserManagerState,
mLauncherBinder.mCallbacksList, mShortcutKeyToPinnedShortcuts);
mModelDelegate.loadAndBindOtherItems(mLauncherBinder.mCallbacksList);
mModelDelegate.loadAndBindWorkspaceItems();
mModelDelegate.loadAndBindAllAppsItems();
mModelDelegate.loadAndBindOtherItems();
mBgDataModel.stringCache.loadStrings(mContext);
mModelDelegate.markActive();
// Break early if we've stopped loading
@@ -18,16 +18,12 @@ package com.android.launcher3.model;
import static com.android.launcher3.util.PackageManagerHelper.hasShortcutsPermission;
import android.content.Context;
import android.content.pm.ShortcutInfo;
import androidx.annotation.NonNull;
import androidx.annotation.WorkerThread;
import com.android.launcher3.LauncherModel;
import com.android.launcher3.dagger.ApplicationContext;
import com.android.launcher3.shortcuts.ShortcutKey;
import java.util.Map;
import javax.inject.Inject;
@@ -65,33 +61,19 @@ public class ModelDelegate {
/** Load workspace items (for example, those in the hot seat) if any in the data model */
@WorkerThread
public void loadAndBindWorkspaceItems(@NonNull UserManagerState ums,
@NonNull BgDataModel.Callbacks[] callbacks,
@NonNull Map<ShortcutKey, ShortcutInfo> pinnedShortcuts) { }
public void loadAndBindWorkspaceItems() { }
/** Load all apps items if any in the data model */
@WorkerThread
public void loadAndBindAllAppsItems(@NonNull UserManagerState ums,
@NonNull BgDataModel.Callbacks[] callbacks,
@NonNull Map<ShortcutKey, ShortcutInfo> pinnedShortcuts) { }
public void loadAndBindAllAppsItems() { }
/** Load other items like widget recommendations if any in the data model */
@WorkerThread
public void loadAndBindOtherItems(@NonNull BgDataModel.Callbacks[] callbacks) { }
/** binds everything not bound by launcherBinder */
@WorkerThread
public void bindAllModelExtras(@NonNull BgDataModel.Callbacks[] callbacks) { }
public void loadAndBindOtherItems() { }
/** Marks the ModelDelegate as active */
public void markActive() { }
/** Load String cache */
@WorkerThread
public void loadStringCache(@NonNull StringCache cache) {
cache.loadStrings(mContext);
}
/**
* Called during loader after workspace loading is complete
*/
@@ -99,7 +99,9 @@ constructor(
// Device profile policy changes
val dpUpdateReceiver =
SimpleBroadcastReceiver(context, UI_HELPER_EXECUTOR) { model.reloadStringCache() }
SimpleBroadcastReceiver(context, UI_HELPER_EXECUTOR) {
model.enqueueModelUpdateTask(ReloadStringCacheTask())
}
dpUpdateReceiver.register(ACTION_DEVICE_POLICY_RESOURCE_UPDATED)
lifeCycle.addCloseable { dpUpdateReceiver.unregisterReceiverSafely() }
@@ -25,18 +25,11 @@ import com.android.launcher3.LauncherModel.ModelUpdateTask;
*/
public class ReloadStringCacheTask implements ModelUpdateTask {
@NonNull
private ModelDelegate mModelDelegate;
public ReloadStringCacheTask(@NonNull final ModelDelegate modelDelegate) {
mModelDelegate = modelDelegate;
}
@Override
public void execute(@NonNull ModelTaskController taskController, @NonNull BgDataModel dataModel,
@NonNull AllAppsList apps) {
synchronized (dataModel) {
mModelDelegate.loadStringCache(dataModel.stringCache);
dataModel.stringCache.loadStrings(taskController.getContext());
StringCache cloneSC = dataModel.stringCache.clone();
taskController.scheduleCallbackTask(c -> c.bindStringCache(cloneSC));
}
@@ -23,11 +23,10 @@ import com.android.launcher3.R
import com.android.launcher3.icons.IconCache
import com.android.launcher3.logger.LauncherAtom
import com.android.launcher3.views.ActivityContext
import java.util.stream.Collectors
/** A type of app collection that launches multiple apps into split screen. */
class AppPairInfo() : CollectionInfo() {
private var contents: ArrayList<WorkspaceItemInfo> = ArrayList()
private var contents = mutableListOf<WorkspaceItemInfo>()
init {
itemType = LauncherSettings.Favorites.ITEM_TYPE_APP_PAIR
@@ -40,7 +39,7 @@ class AppPairInfo() : CollectionInfo() {
/** Creates a new AppPairInfo that is a copy of the provided one. */
constructor(appPairInfo: AppPairInfo) : this() {
contents = appPairInfo.contents.clone() as ArrayList<WorkspaceItemInfo>
contents = appPairInfo.contents.toMutableList()
copyFrom(appPairInfo)
}
@@ -54,11 +53,10 @@ class AppPairInfo() : CollectionInfo() {
}
/** Returns the app pair's member apps as an ArrayList of [ItemInfo]. */
override fun getContents(): ArrayList<ItemInfo> =
ArrayList(contents.stream().map { it as ItemInfo }.collect(Collectors.toList()))
override fun getContents(): List<ItemInfo> = contents.map { it }
/** Returns the app pair's member apps as an ArrayList of [WorkspaceItemInfo]. */
override fun getAppContents(): ArrayList<WorkspaceItemInfo> = contents
override fun getAppContents(): List<WorkspaceItemInfo> = contents
/** Returns the first app in the pair. */
fun getFirstApp() = contents[0]
@@ -82,9 +80,8 @@ class AppPairInfo() : CollectionInfo() {
/** Fetches high-res icons for member apps if needed. */
fun fetchHiResIconsIfNeeded(iconCache: IconCache) {
getAppContents()
.stream()
.filter { it.matchingLookupFlag.isVisuallyLessThan(DESKTOP_ICON_FLAG) }
.forEach { member -> iconCache.getTitleAndIcon(member, DESKTOP_ICON_FLAG) }
.forEach { iconCache.getTitleAndIcon(it, DESKTOP_ICON_FLAG) }
}
/**
@@ -25,17 +25,17 @@ abstract class CollectionInfo : ItemInfo() {
abstract fun add(item: ItemInfo)
/** Returns the collection's contents as an ArrayList of [ItemInfo]. */
abstract fun getContents(): ArrayList<ItemInfo>
abstract fun getContents(): List<ItemInfo>
/**
* Returns the collection's contents as an ArrayList of [WorkspaceItemInfo]. Does not include
* other collection [ItemInfo]s that are inside this collection; rather, it should collect
* *their* contents and adds them to the ArrayList.
*/
abstract fun getAppContents(): ArrayList<WorkspaceItemInfo>
abstract fun getAppContents(): List<WorkspaceItemInfo>
/** Convenience function. Checks contents to see if any match a given predicate. */
fun anyMatch(matcher: Predicate<ItemInfo>) = getContents().stream().anyMatch(matcher)
fun anyMatch(matcher: Predicate<ItemInfo>) = getContents().any { matcher.test(it) }
override fun onAddToDatabase(writer: ContentWriter) {
super.onAddToDatabase(writer)
@@ -38,7 +38,6 @@ import android.view.accessibility.AccessibilityEvent;
import android.widget.FrameLayout;
import com.android.launcher3.AbstractFloatingView;
import com.android.launcher3.DeviceProfile;
import com.android.launcher3.InsettableFrameLayout;
import com.android.launcher3.Utilities;
import com.android.launcher3.testing.shared.ResourceUtils;
@@ -559,20 +558,13 @@ public abstract class BaseDragLayer<T extends Context & ActivityContext>
@Override
public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
Insets gestureInsets = insets.getMandatorySystemGestureInsets();
int gestureInsetBottom = gestureInsets.bottom;
Insets imeInset = insets.getInsets(WindowInsets.Type.ime());
DeviceProfile dp = mContainer.getDeviceProfile();
if (dp.isTaskbarPresent) {
mSystemGestureRegion.set(gestureInsets.left, gestureInsets.top, gestureInsets.right,
gestureInsets.bottom);
if (mContainer.getDeviceProfile().isTaskbarPresent) {
// Ignore taskbar gesture insets to avoid interfering with TouchControllers.
gestureInsetBottom = ResourceUtils.getNavbarSize(
mSystemGestureRegion.bottom = ResourceUtils.getNavbarSize(
ResourceUtils.NAVBAR_BOTTOM_GESTURE_SIZE, getResources());
}
mSystemGestureRegion.set(
Math.max(gestureInsets.left, imeInset.left),
Math.max(gestureInsets.top, imeInset.top),
Math.max(gestureInsets.right, imeInset.right),
Math.max(gestureInsetBottom, imeInset.bottom)
);
return super.dispatchApplyWindowInsets(insets);
}
}
@@ -218,12 +218,12 @@ class LoaderTaskTest {
verify(launcherBinder).bindWorkspace(true, false)
verify(modelDelegate).workspaceLoadComplete()
verify(modelDelegate).loadAndBindAllAppsItems(any(), anyOrNull(), any())
verify(modelDelegate).loadAndBindAllAppsItems()
verify(launcherBinder).bindAllApps()
verify(iconCacheUpdateHandler, times(4)).updateIcons(any(), any<CachingLogic<Any>>(), any())
verify(launcherBinder).bindDeepShortcuts()
verify(launcherBinder).bindWidgets()
verify(modelDelegate).loadAndBindOtherItems(anyOrNull())
verify(modelDelegate).loadAndBindOtherItems()
verify(iconCacheUpdateHandler).finish()
verify(modelDelegate).modelLoadComplete()
verify(transaction).commit()
@@ -40,6 +40,7 @@ import android.os.RemoteException;
import android.os.UserHandle;
import android.os.UserManager;
import android.platform.test.flag.junit.SetFlagsRule;
import android.platform.test.rule.ExtendedLongPressTimeoutRule;
import android.platform.test.rule.LimitDevicesRule;
import android.util.Log;
@@ -57,7 +58,6 @@ import com.android.launcher3.tapl.LauncherInstrumentation;
import com.android.launcher3.tapl.TestHelpers;
import com.android.launcher3.util.TestUtil;
import com.android.launcher3.util.Wait;
import com.android.launcher3.util.rule.ExtendedLongPressTimeoutRule;
import com.android.launcher3.util.rule.FailureWatcher;
import com.android.launcher3.util.rule.MutualExclusionRule;
import com.android.launcher3.util.rule.SamplerRule;
@@ -1,88 +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.util.rule;
import static com.android.launcher3.util.TestUtil.grantWriteSecurePermission;
import android.content.ContentResolver;
import android.provider.Settings;
import android.util.Log;
import android.view.ViewConfiguration;
import androidx.test.InstrumentationRegistry;
import com.android.launcher3.BuildConfig;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
/**
* Increases the device's long-press timeout in remote tests to reduce flakiness in slow-running
* devices.
*/
public class ExtendedLongPressTimeoutRule implements TestRule {
private static final String TAG = "ExtendedLongPressTimeoutRule";
private static final float LONG_PRESS_TIMEOUT_MULTIPLIER = 10f;
@Override
public Statement apply(Statement base, Description description) {
if (BuildConfig.IS_STUDIO_BUILD) {
// Skip rule on studio builds since cancelling a test run will not run the finally block
return base;
}
return new Statement() {
@Override
public void evaluate() throws Throwable {
ContentResolver contentResolver = InstrumentationRegistry.getInstrumentation()
.getContext()
.getContentResolver();
int prevLongPressTimeout = Settings.Secure.getInt(
contentResolver,
Settings.Secure.LONG_PRESS_TIMEOUT,
ViewConfiguration.getLongPressTimeout());
int newLongPressTimeout =
(int) (prevLongPressTimeout * LONG_PRESS_TIMEOUT_MULTIPLIER);
try {
Log.d(TAG, "In try-block: Setting long press timeout from "
+ prevLongPressTimeout + "ms to " + newLongPressTimeout + "ms");
grantWriteSecurePermission();
Settings.Secure.putInt(
contentResolver,
Settings.Secure.LONG_PRESS_TIMEOUT,
(int) (prevLongPressTimeout * LONG_PRESS_TIMEOUT_MULTIPLIER));
base.evaluate();
} catch (Exception e) {
Log.e(TAG, "Error", e);
throw e;
} finally {
Log.d(TAG, "In finally-block: resetting long press timeout to "
+ prevLongPressTimeout + "ms");
grantWriteSecurePermission();
Settings.Secure.putInt(
contentResolver,
Settings.Secure.LONG_PRESS_TIMEOUT,
prevLongPressTimeout);
}
}
};
}
}
@@ -0,0 +1,24 @@
/*
* 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.testing;
public final class BuildConfig {
public static final boolean DEBUG = Boolean.parseBoolean("true");
// Field from default config.
public static final boolean IS_STUDIO_BUILD = false;
}
@@ -152,6 +152,10 @@ public class BaseOverview extends LauncherInstrumentation.VisibleContainer {
/**
* Dismissed all tasks by scrolling to Clear-all button and pressing it.
* <p>
* NOTE: Fails if there are already no recent tasks. If a test needs to start with an empty task
* list, check {@link #hasTasks} before calling this since the previous test may have already
* cleared the task list.
*/
public void dismissAllTasks() {
try (LauncherInstrumentation.Closable e = mLauncher.eventsCheck();
@@ -254,6 +254,7 @@ public final class Widgets extends LauncherInstrumentation.VisibleContainer
targetAppSelector);
final UiObject2 searchBar = findSearchBar();
// If header's title is under or above search bar, let's not process the header yet,
// scroll a bit more to bring the header into visible area.
if (headerTitle != null
@@ -270,6 +271,14 @@ public final class Widgets extends LauncherInstrumentation.VisibleContainer
// to briefly appear to handle the gesture, which can break our test.
boolean isHeaderOutOfGestureRegion = headerTitle.getVisibleCenter().y
< mLauncher.getBottomGestureStartOnScreen();
if (!isHeaderOutOfGestureRegion) {
log("Test app's header is not out of gesture region, scrolling up");
mLauncher.scrollDownByDistance(widgetListView, scrollDistance);
isHeaderOutOfGestureRegion = true;
}
if (!hasHeaderExpanded && isHeaderOutOfGestureRegion) {
log("Header has not been expanded. Click to expand.");
hasHeaderExpanded = true;
@@ -286,6 +295,7 @@ public final class Widgets extends LauncherInstrumentation.VisibleContainer
UiObject2 widgetsContainer = mLauncher.findObjectInContainer(
rightPane != null ? rightPane : widgetListView,
widgetsContainerSelector);
if (widgetsContainer != null) {
log("Widgets container found.");
return widgetsContainer;