Moving WorkspaceItemFactory to dagger as PredictedItemFactory so that it can be reused

Bug: 390572144
Flag: EXEMPTY refactor
Test: Presubmit
Change-Id: I41c5fea73452d7f4c1fd9980a89bcb7199eb19d7
This commit is contained in:
Sunny Goyal committed 2025-05-02 08:55:21 -07:00
1 parent 9b468c5b24
commit 46b13eb184
12 files changed
+270 -340

No files matched your search

@@ -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;
}
}
}