Merge "Converting BgDataModel to Kotlin" into main

This commit is contained in:
Sunny Goyal authored and Android (Google) Code Review committed 2025-04-30 10:19:46 -07:00
commit dd367a2218
4 files changed
+451 -495

No files matched your search

@@ -699,7 +699,7 @@ class TaskbarOverflowTest {
override fun bindCompleteModel(
itemIdMap: IntSparseArrayMap<ItemInfo>,
extraItems: MutableList<FixedContainerItems>,
extraItems: List<FixedContainerItems>,
stringCache: StringCache,
isBindingSync: Boolean,
) = bindItemsAdded(itemIdMap.toList())
@@ -716,7 +716,7 @@ class TaskbarOverflowTest {
}
}
override fun bindWorkspaceComponentsRemoved(matcher: Predicate<ItemInfo>) {
override fun bindWorkspaceComponentsRemoved(matcher: Predicate<ItemInfo?>) {
runOnMainSync {
for (i in hotseatItems.size - 1 downTo 0) {
if (matcher.test(hotseatItems[i])) {
+5 -5
View File
@@ -184,9 +184,9 @@ class ModelCallbacks(private var launcher: Launcher) : BgDataModel.Callbacks {
@UiThread
override fun bindAllApplications(
apps: Array<AppInfo?>?,
apps: Array<AppInfo>,
flags: Int,
packageUserKeytoUidMap: Map<PackageUserKey?, Int?>?,
packageUserKeytoUidMap: Map<PackageUserKey, Int>,
) {
Preconditions.assertUIThread()
val hadWorkApps = launcher.appsView.shouldShowTabs()
@@ -204,11 +204,11 @@ class ModelCallbacks(private var launcher: Launcher) : BgDataModel.Callbacks {
* Copies LauncherModel's map of activities to shortcut counts to Launcher's. This is necessary
* because LauncherModel's map is updated in the background, while Launcher runs on the UI.
*/
override fun bindDeepShortcutMap(deepShortcutMapCopy: HashMap<ComponentKey?, Int?>?) {
override fun bindDeepShortcutMap(deepShortcutMapCopy: HashMap<ComponentKey, Int>) {
launcher.popupDataProvider.setDeepShortcutMap(deepShortcutMapCopy)
}
override fun bindIncrementalDownloadProgressUpdated(app: AppInfo?) {
override fun bindIncrementalDownloadProgressUpdated(app: AppInfo) {
launcher.appsView.appsStore.updateProgressBar(app)
}
@@ -436,7 +436,7 @@ class ModelCallbacks(private var launcher: Launcher) : BgDataModel.Callbacks {
@AnyThread
override fun bindCompleteModelAsync(
itemIdMap: IntSparseArrayMap<ItemInfo>,
extraItems: List<FixedContainerItems?>,
extraItems: List<FixedContainerItems>,
stringCache: StringCache,
isBindingSync: Boolean,
) {
@@ -1,488 +0,0 @@
/*
* Copyright (C) 2016 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 static android.content.pm.LauncherApps.ShortcutQuery.FLAG_GET_KEY_FIELDS_ONLY;
import static com.android.launcher3.BuildConfig.WIDGETS_ENABLED;
import static com.android.launcher3.LauncherSettings.Favorites.CONTAINER_DESKTOP;
import static com.android.launcher3.LauncherSettings.Favorites.CONTAINER_HOTSEAT;
import static com.android.launcher3.LauncherSettings.Favorites.ITEM_TYPE_APP_PAIR;
import static com.android.launcher3.LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT;
import static com.android.launcher3.LauncherSettings.Favorites.ITEM_TYPE_FOLDER;
import static com.android.launcher3.Utilities.SHOULD_SHOW_FIRST_PAGE_WIDGET;
import static com.android.launcher3.shortcuts.ShortcutRequest.PINNED;
import static com.android.launcher3.util.Executors.MAIN_EXECUTOR;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.mapping;
import android.content.Context;
import android.content.pm.LauncherApps;
import android.content.pm.ShortcutInfo;
import android.os.UserHandle;
import android.text.TextUtils;
import android.util.Log;
import androidx.annotation.AnyThread;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.android.launcher3.BuildConfig;
import com.android.launcher3.Flags;
import com.android.launcher3.Workspace;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.dagger.LauncherAppSingleton;
import com.android.launcher3.logging.DumpManager;
import com.android.launcher3.logging.DumpManager.LauncherDumpable;
import com.android.launcher3.logging.FileLog;
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.model.repository.HomeScreenRepository;
import com.android.launcher3.model.repository.HomeScreenRepository.WorkspaceData.ChangeEvent.AddEvent;
import com.android.launcher3.model.repository.HomeScreenRepository.WorkspaceData.ChangeEvent.RemoveEvent;
import com.android.launcher3.model.repository.HomeScreenRepository.WorkspaceData.ChangeEvent.UpdateEvent;
import com.android.launcher3.pm.UserCache;
import com.android.launcher3.shortcuts.ShortcutKey;
import com.android.launcher3.shortcuts.ShortcutRequest;
import com.android.launcher3.shortcuts.ShortcutRequest.QueryResult;
import com.android.launcher3.util.ComponentKey;
import com.android.launcher3.util.DaggerSingletonTracker;
import com.android.launcher3.util.IntArray;
import com.android.launcher3.util.IntSet;
import com.android.launcher3.util.IntSparseArrayMap;
import com.android.launcher3.util.PackageUserKey;
import com.android.launcher3.widget.model.WidgetsListBaseEntry;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.inject.Inject;
import javax.inject.Provider;
/**
* All the data stored in-memory and managed by the LauncherModel
*
* All the static data should be accessed on the background thread, A lock should be acquired on
* this object when accessing any data from this model.
*/
@LauncherAppSingleton
public class BgDataModel implements LauncherDumpable {
private static final String TAG = "BgDataModel";
/**
* Map of all the ItemInfos (shortcuts, folders, and widgets) created by
* LauncherModel to their ids
*/
public final IntSparseArrayMap<ItemInfo> itemsIdMap = new IntSparseArrayMap<>();
/**
* Extra container based items
*/
public final IntSparseArrayMap<FixedContainerItems> extraItems = new IntSparseArrayMap<>();
/**
* Maps all launcher activities to counts of their shortcuts.
*/
public final HashMap<ComponentKey, Integer> deepShortcutMap = new HashMap<>();
/**
* Entire list of widgets.
*/
public final WidgetsModel widgetsModel;
/**
* Cache for strings used in launcher
*/
public final StringCache stringCache = new StringCache();
@Nullable
private final HomeScreenRepository mRepo;
/**
* Id when the model was last bound
*/
public int lastBindId = 0;
/**
* Load id for which the callbacks were successfully bound
*/
public int lastLoadId = -1;
@Inject
public BgDataModel(WidgetsModel widgetsModel,
Provider<HomeScreenRepository> homeDataProvider,
DumpManager dumpManager, DaggerSingletonTracker lifeCycle) {
this.widgetsModel = widgetsModel;
mRepo = Flags.modelRepository() ? homeDataProvider.get() : null;
lifeCycle.addCloseable(dumpManager.register(this));
}
/**
* Clears all the data
*/
public synchronized void clear() {
itemsIdMap.clear();
deepShortcutMap.clear();
extraItems.clear();
}
/**
* Creates an array of valid workspace screens based on current items in the model.
*/
public synchronized IntArray collectWorkspaceScreens() {
IntSet screenSet = new IntSet();
for (ItemInfo item: itemsIdMap) {
if (item.container == CONTAINER_DESKTOP) {
screenSet.add(item.screenId);
}
}
if ((FeatureFlags.QSB_ON_FIRST_SCREEN
&& !SHOULD_SHOW_FIRST_PAGE_WIDGET)
|| screenSet.isEmpty()) {
screenSet.add(Workspace.FIRST_SCREEN_ID);
}
return screenSet.getArray();
}
@Override
public synchronized void dump(@NonNull String prefix, @NonNull PrintWriter writer,
@Nullable String[] args) {
writer.println(prefix + "Data Model:");
writer.println(prefix + " ---- items id map ");
for (int i = 0; i < itemsIdMap.size(); i++) {
writer.println(prefix + '\t' + itemsIdMap.valueAt(i).toString());
}
writer.println(prefix + " ---- extra items ");
for (int i = 0; i < extraItems.size(); i++) {
writer.println(prefix + '\t' + extraItems.valueAt(i).toString());
}
if (args != null && args.length > 0 && TextUtils.equals(args[0], "--all")) {
writer.println(prefix + "shortcut counts ");
for (Integer count : deepShortcutMap.values()) {
writer.print(count + ", ");
}
writer.println();
}
}
public synchronized void removeItem(Context context, ItemInfo... items) {
removeItem(context, Arrays.asList(items));
}
public synchronized void removeItem(Context context, Collection<? extends ItemInfo> items) {
removeItem(context, items, null);
}
public synchronized void removeItem(Context context, Collection<? extends ItemInfo> items,
@Nullable Object owner) {
if (BuildConfig.IS_STUDIO_BUILD) {
items.stream()
.filter(item -> item.itemType == ITEM_TYPE_FOLDER
|| item.itemType == ITEM_TYPE_APP_PAIR)
.forEach(item -> itemsIdMap.stream()
.filter(info -> info.container == item.id)
.filter(info -> !items.contains(info))
// We are deleting a collection which still contains items that
// think they are contained by that collection.
.forEach(info -> Log.e(TAG,
"deleting a collection (" + item + ") which still contains"
+ " items (" + info + ")")));
}
items.forEach(item -> itemsIdMap.remove(item.id));
items.stream().map(info -> info.user).distinct().forEach(
user -> updateShortcutPinnedState(context, user));
if (Flags.modelRepository() && mRepo != null) {
mRepo.dispatchChange(this, new RemoveEvent(new ArrayList<>(items), owner));
}
}
public synchronized void addItem(Context context, ItemInfo item, boolean newItem) {
addItem(context, item, newItem, null);
}
public synchronized void addItem(Context context, ItemInfo item, boolean newItem,
@Nullable Object owner) {
itemsIdMap.put(item.id, item);
if (newItem && item.itemType == ITEM_TYPE_DEEP_SHORTCUT) {
updateShortcutPinnedState(context, item.user);
}
if (Flags.modelRepository() && mRepo != null) {
mRepo.dispatchChange(this, new AddEvent(Collections.singletonList(item), owner));
}
if (BuildConfig.IS_DEBUG_DEVICE
&& newItem
&& item.container != CONTAINER_DESKTOP
&& item.container != CONTAINER_HOTSEAT
&& !(itemsIdMap.get(item.container) instanceof CollectionInfo)) {
// Adding an item to a nonexistent collection.
Log.e(TAG, "attempted to add item: " + item + " to a nonexistent app collection");
}
}
public synchronized void updateItems(List<ItemInfo> items, @Nullable Object owner) {
if (Flags.modelRepository() && mRepo != null) {
mRepo.dispatchChange(this, new UpdateEvent(items, owner));
}
}
public synchronized void dataLoadComplete() {
if (Flags.modelRepository() && mRepo != null) mRepo.onNewBind(this);
}
/**
* Updates the deep shortcuts state in system to match out internal model, pinning any missing
* shortcuts and unpinning any extra shortcuts.
*/
public void updateShortcutPinnedState(Context context) {
for (UserHandle user : UserCache.INSTANCE.get(context).getUserProfiles()) {
updateShortcutPinnedState(context, user);
}
}
/**
* Updates the deep shortucts state in system to match out internal model, pinning any missing
* shortcuts and unpinning any extra shortcuts.
*/
public synchronized void updateShortcutPinnedState(Context context, UserHandle user) {
if (!WIDGETS_ENABLED) {
return;
}
// Collect all system shortcuts
QueryResult result = new ShortcutRequest(context, user)
.query(PINNED | FLAG_GET_KEY_FIELDS_ONLY);
if (!result.wasSuccess()) {
return;
}
// Map of packageName to shortcutIds that are currently in the system
Map<String, Set<String>> systemMap = result.stream()
.collect(groupingBy(ShortcutInfo::getPackage,
mapping(ShortcutInfo::getId, Collectors.toSet())));
// Collect all model shortcuts
Stream.Builder<WorkspaceItemInfo> itemStream = Stream.builder();
forAllWorkspaceItemInfos(user, itemStream::accept);
// Map of packageName to shortcutIds that are currently in our model
Map<String, Set<String>> modelMap = Stream.concat(
// Model shortcuts
itemStream.build()
.filter(wi -> wi.itemType == ITEM_TYPE_DEEP_SHORTCUT)
.map(ShortcutKey::fromItemInfo),
// Pending shortcuts
ItemInstallQueue.INSTANCE.get(context).getPendingShortcuts(user))
.collect(groupingBy(ShortcutKey::getPackageName,
mapping(ShortcutKey::getId, Collectors.toSet())));
// Check for diff
for (Map.Entry<String, Set<String>> entry : modelMap.entrySet()) {
Set<String> modelShortcuts = entry.getValue();
Set<String> systemShortcuts = systemMap.remove(entry.getKey());
if (systemShortcuts == null) {
systemShortcuts = Collections.emptySet();
}
// Do not use .equals as it can vary based on the type of set
if (systemShortcuts.size() != modelShortcuts.size()
|| !systemShortcuts.containsAll(modelShortcuts)) {
// Update system state for this package
try {
FileLog.d(TAG, "updateShortcutPinnedState:"
+ " Pinning Shortcuts: " + entry.getKey() + ": " + modelShortcuts);
context.getSystemService(LauncherApps.class).pinShortcuts(
entry.getKey(), new ArrayList<>(modelShortcuts), user);
} catch (SecurityException | IllegalStateException e) {
Log.w(TAG, "Failed to pin shortcut", e);
}
}
}
// If there are any extra pinned shortcuts, remove them
systemMap.keySet().forEach(packageName -> {
// Update system state
try {
FileLog.d(TAG, "updateShortcutPinnedState:"
+ " Unpinning extra Shortcuts for package: " + packageName
+ ": " + systemMap.get(packageName));
context.getSystemService(LauncherApps.class).pinShortcuts(
packageName, Collections.emptyList(), user);
} catch (SecurityException | IllegalStateException e) {
Log.w(TAG, "Failed to unpin shortcut", e);
}
});
}
/**
* Clear all the deep shortcut counts for the given package, and re-add the new shortcut counts.
*/
public synchronized void updateDeepShortcutCounts(
String packageName, UserHandle user, List<ShortcutInfo> shortcuts) {
if (packageName != null) {
Iterator<ComponentKey> keysIter = deepShortcutMap.keySet().iterator();
while (keysIter.hasNext()) {
ComponentKey next = keysIter.next();
if (next.componentName.getPackageName().equals(packageName)
&& next.user.equals(user)) {
keysIter.remove();
}
}
}
// Now add the new shortcuts to the map.
for (ShortcutInfo shortcut : shortcuts) {
boolean shouldShowInContainer = shortcut.isEnabled()
&& (shortcut.isDeclaredInManifest() || shortcut.isDynamic())
&& shortcut.getActivity() != null;
if (shouldShowInContainer) {
ComponentKey targetComponent
= new ComponentKey(shortcut.getActivity(), shortcut.getUserHandle());
Integer previousCount = deepShortcutMap.get(targetComponent);
deepShortcutMap.put(targetComponent, previousCount == null ? 1 : previousCount + 1);
}
}
}
/**
* Calls the provided {@code op} for all workspaceItems in the in-memory model (both persisted
* items and dynamic/predicted items for the provided {@code userHandle}.
* Note the call is not synchronized over the model, that should be handled by the called.
*/
public void forAllWorkspaceItemInfos(UserHandle userHandle, Consumer<WorkspaceItemInfo> op) {
for (ItemInfo info : itemsIdMap) {
if (info instanceof WorkspaceItemInfo && userHandle.equals(info.user)) {
op.accept((WorkspaceItemInfo) info);
}
}
for (int i = extraItems.size() - 1; i >= 0; i--) {
for (ItemInfo info : extraItems.valueAt(i).items) {
if (info instanceof WorkspaceItemInfo && userHandle.equals(info.user)) {
op.accept((WorkspaceItemInfo) info);
}
}
}
}
/**
* An object containing items corresponding to a fixed container
*/
public static class FixedContainerItems {
public final int containerId;
public final List<ItemInfo> items;
public FixedContainerItems(int containerId, List<ItemInfo> items) {
this.containerId = containerId;
this.items = Collections.unmodifiableList(items);
}
@Override
@NonNull
public final String toString() {
StringBuilder s = new StringBuilder();
s.append("FixedContainerItems:");
s.append(" id=").append(containerId);
s.append(" itemCount=").append(items.size());
for (int i = 0; i < items.size(); i++) {
s.append(" item #").append(i).append(": ").append(items.get(i).toString());
}
return s.toString();
}
}
public interface Callbacks {
// If the launcher has permission to access deep shortcuts.
int FLAG_HAS_SHORTCUT_PERMISSION = 1 << 0;
// If quiet mode is enabled for any user
int FLAG_QUIET_MODE_ENABLED = 1 << 1;
// If launcher can change quiet mode
int FLAG_QUIET_MODE_CHANGE_PERMISSION = 1 << 2;
// If quiet mode is enabled for work profile user
int FLAG_WORK_PROFILE_QUIET_MODE_ENABLED = 1 << 3;
// If quiet mode is enabled for private profile user
int FLAG_PRIVATE_PROFILE_QUIET_MODE_ENABLED = 1 << 4;
/**
* Does a complete model rebind. The callback can be called on any thread and it is up to
* the client to move the executor to appropriate thread
*/
@AnyThread
default void bindCompleteModelAsync(IntSparseArrayMap<ItemInfo> itemIdMap,
List<FixedContainerItems> extraItems, StringCache stringCache,
boolean isBindingSync) {
MAIN_EXECUTOR.execute(
() -> bindCompleteModel(itemIdMap, extraItems, stringCache, isBindingSync));
}
default void bindCompleteModel(IntSparseArrayMap<ItemInfo> itemIdMap,
List<FixedContainerItems> extraItems, StringCache stringCache,
boolean isBindingSync) { }
default void bindItemsAdded(@NonNull List<ItemInfo> items) { }
/** Called when a runtime property of the ItemInfo is updated due to some system event */
default void bindItemsUpdated(Set<ItemInfo> updates) { }
default void bindWorkspaceComponentsRemoved(Predicate<ItemInfo> matcher) { }
/**
* Binds updated incremental download progress
*/
default void bindIncrementalDownloadProgressUpdated(AppInfo app) { }
/**
* Binds the app widgets to the providers that share widgets with the UI.
*/
default void bindAllWidgets(@NonNull List<WidgetsListBaseEntry> widgets) { }
default void bindSmartspaceWidget() { }
default void bindDeepShortcutMap(HashMap<ComponentKey, Integer> deepShortcutMap) { }
/**
* Binds extra item provided any external source
*/
default void bindExtraContainerItems(FixedContainerItems item) { }
default void bindAllApplications(AppInfo[] apps, int flags,
Map<PackageUserKey, Integer> packageUserKeytoUidMap) {
}
/**
* Binds the cache of string resources
*/
default void bindStringCache(StringCache cache) { }
}
}
@@ -0,0 +1,444 @@
/*
* Copyright (C) 2016 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.content.Context
import android.content.pm.LauncherApps
import android.content.pm.LauncherApps.ShortcutQuery
import android.content.pm.ShortcutInfo
import android.os.UserHandle
import android.util.Log
import androidx.annotation.AnyThread
import androidx.core.util.size
import com.android.launcher3.BuildConfig
import com.android.launcher3.Flags
import com.android.launcher3.LauncherSettings.Favorites.CONTAINER_DESKTOP
import com.android.launcher3.LauncherSettings.Favorites.CONTAINER_HOTSEAT
import com.android.launcher3.LauncherSettings.Favorites.ITEM_TYPE_APP_PAIR
import com.android.launcher3.LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT
import com.android.launcher3.LauncherSettings.Favorites.ITEM_TYPE_FOLDER
import com.android.launcher3.Utilities
import com.android.launcher3.Workspace
import com.android.launcher3.dagger.LauncherAppSingleton
import com.android.launcher3.logging.DumpManager
import com.android.launcher3.logging.DumpManager.LauncherDumpable
import com.android.launcher3.logging.FileLog
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.model.repository.HomeScreenRepository
import com.android.launcher3.model.repository.HomeScreenRepository.WorkspaceData.ChangeEvent.AddEvent
import com.android.launcher3.model.repository.HomeScreenRepository.WorkspaceData.ChangeEvent.RemoveEvent
import com.android.launcher3.model.repository.HomeScreenRepository.WorkspaceData.ChangeEvent.UpdateEvent
import com.android.launcher3.pm.UserCache
import com.android.launcher3.shortcuts.ShortcutKey
import com.android.launcher3.shortcuts.ShortcutRequest
import com.android.launcher3.util.ComponentKey
import com.android.launcher3.util.DaggerSingletonTracker
import com.android.launcher3.util.Executors
import com.android.launcher3.util.IntArray
import com.android.launcher3.util.IntSet
import com.android.launcher3.util.IntSparseArrayMap
import com.android.launcher3.util.PackageUserKey
import com.android.launcher3.widget.model.WidgetsListBaseEntry
import java.io.PrintWriter
import java.util.Collections
import java.util.function.Consumer
import java.util.function.Predicate
import javax.inject.Inject
import javax.inject.Provider
/**
* All the data stored in-memory and managed by the LauncherModel
*
* All the static data should be accessed on the background thread, A lock should be acquired on
* this object when accessing any data from this model.
*/
@LauncherAppSingleton
class BgDataModel
@Inject
constructor(
/** Entire list of widgets. */
@JvmField val widgetsModel: WidgetsModel,
homeDataProvider: Provider<HomeScreenRepository?>,
dumpManager: DumpManager,
lifeCycle: DaggerSingletonTracker,
) : LauncherDumpable {
/**
* Map of all the ItemInfos (shortcuts, folders, and widgets) created by LauncherModel to their
* ids
*/
@JvmField val itemsIdMap = IntSparseArrayMap<ItemInfo>()
/** Extra container based items */
@JvmField val extraItems = IntSparseArrayMap<FixedContainerItems>()
/** Maps all launcher activities to counts of their shortcuts. */
@JvmField val deepShortcutMap = HashMap<ComponentKey, Int>()
/** Cache for strings used in launcher */
@JvmField val stringCache = StringCache()
private val repo = if (Flags.modelRepository()) homeDataProvider.get() else null
/** Id when the model was last bound */
@JvmField var lastBindId: Int = 0
/** Load id for which the callbacks were successfully bound */
@JvmField var lastLoadId: Int = -1
init {
lifeCycle.addCloseable(dumpManager.register(this))
}
/** Clears all the data */
@Synchronized
fun clear() {
itemsIdMap.clear()
deepShortcutMap.clear()
extraItems.clear()
}
/** Creates an array of valid workspace screens based on current items in the model. */
@Synchronized
fun collectWorkspaceScreens(): IntArray {
val screenSet = IntSet()
itemsIdMap.forEach { if (it.container == CONTAINER_DESKTOP) screenSet.add(it.screenId) }
if (
(BuildConfig.QSB_ON_FIRST_SCREEN && !Utilities.SHOULD_SHOW_FIRST_PAGE_WIDGET) ||
screenSet.isEmpty
) {
screenSet.add(Workspace.FIRST_SCREEN_ID)
}
return screenSet.array
}
@Synchronized
override fun dump(prefix: String, writer: PrintWriter, args: Array<String>?) {
writer.println(prefix + "Data Model:")
writer.println("$prefix ---- items id map ")
itemsIdMap.forEach { writer.println("$prefix\t$it") }
writer.println("$prefix ---- extra items ")
extraItems.forEach { writer.println("$prefix\t$it") }
if (args?.getOrNull(0) == "--all")
writer.println(prefix + "shortcut counts: ${deepShortcutMap.values.joinToString()}")
}
@Synchronized
fun removeItem(context: Context, vararg items: ItemInfo) {
removeItem(context, listOf(*items))
}
@Synchronized
@JvmOverloads
fun removeItem(context: Context, items: Collection<ItemInfo>, owner: Any? = null) {
if (BuildConfig.IS_STUDIO_BUILD) {
items
.asSequence()
.filter { it.itemType == ITEM_TYPE_FOLDER || it.itemType == ITEM_TYPE_APP_PAIR }
.forEach { item: ItemInfo ->
// We are deleting a collection which still contains items that think they are
// contained by that collection.
itemsIdMap
.filter { it.container == item.id && !items.contains(it) }
.forEach { info: ItemInfo ->
Log.e(
TAG,
"deleting a collection ($item) which still contains item ($info)",
)
}
}
}
items.forEach { itemsIdMap.remove(it.id) }
items
.asSequence()
.map { it.user }
.distinct()
.forEach { updateShortcutPinnedState(context, it) }
if (Flags.modelRepository() && repo != null) {
repo.dispatchChange(this, RemoveEvent(items.toList(), owner))
}
}
@Synchronized
@JvmOverloads
fun addItem(context: Context, item: ItemInfo, newItem: Boolean, owner: Any? = null) {
itemsIdMap.put(item.id, item)
if (newItem && item.itemType == ITEM_TYPE_DEEP_SHORTCUT) {
updateShortcutPinnedState(context, item.user)
}
if (Flags.modelRepository() && repo != null) {
repo.dispatchChange(this, AddEvent(listOf(item), owner))
}
if (
BuildConfig.IS_DEBUG_DEVICE &&
newItem &&
item.container != CONTAINER_DESKTOP &&
item.container != CONTAINER_HOTSEAT &&
(itemsIdMap[item.container] !is CollectionInfo)
) {
// Adding an item to a nonexistent collection.
Log.e(TAG, "attempted to add item: $item to a nonexistent app collection")
}
}
@Synchronized
fun updateItems(items: List<ItemInfo>, owner: Any?) {
if (Flags.modelRepository() && repo != null) {
repo.dispatchChange(this, UpdateEvent(items, owner))
}
}
@Synchronized
fun dataLoadComplete() {
if (Flags.modelRepository() && repo != null) repo.onNewBind(this)
}
/**
* Updates the deep shortcuts state in system to match out internal model, pinning any missing
* shortcuts and unpinning any extra shortcuts.
*/
fun updateShortcutPinnedState(context: Context) {
for (user in UserCache.INSTANCE[context].userProfiles) {
updateShortcutPinnedState(context, user)
}
}
/**
* Updates the deep shortcuts state in system to match out internal model, pinning any missing
* shortcuts and unpinning any extra shortcuts.
*/
@Synchronized
fun updateShortcutPinnedState(context: Context, user: UserHandle) {
if (!BuildConfig.WIDGETS_ENABLED) {
return
}
// Collect all system shortcuts
val result =
ShortcutRequest(context, user)
.query(ShortcutRequest.PINNED or ShortcutQuery.FLAG_GET_KEY_FIELDS_ONLY)
if (!result.wasSuccess()) {
return
}
// Map of packageName to shortcutIds that are currently in the system
val systemMap: MutableMap<String, MutableSet<String>> =
result
.groupingBy { it.`package` }
.foldTo(
destination = mutableMapOf(),
initialValueSelector = { _, element -> mutableSetOf(element.id) },
operation = { _, accumulator, element -> accumulator.apply { add(element.id) } },
)
// Collect all model shortcuts
val allWorkspaceItems =
mutableListOf<ShortcutKey>().apply {
forAllWorkspaceItemInfos(user) {
if (it.itemType == ITEM_TYPE_DEEP_SHORTCUT) add(ShortcutKey.fromItemInfo(it))
}
}
allWorkspaceItems.addAll(
ItemInstallQueue.INSTANCE[context].getPendingShortcuts(user).toList()
)
// Map of packageName to shortcutIds that are currently in our model
val modelMap =
allWorkspaceItems
.groupingBy { it.packageName }
.foldTo(
destination = mutableMapOf(),
initialValueSelector = { _, element -> mutableSetOf(element.id) },
operation = { _, accumulator, element -> accumulator.apply { add(element.id) } },
)
// Check for diff
for ((key, modelShortcuts) in modelMap) {
val systemShortcuts = systemMap.remove(key) ?: emptySet()
// Do not use .equals as it can vary based on the type of set
if (
systemShortcuts.size != modelShortcuts.size ||
!systemShortcuts.containsAll(modelShortcuts)
) {
// Update system state for this package
try {
FileLog.d(
TAG,
("updateShortcutPinnedState:" + " Pinning Shortcuts: $key: $modelShortcuts"),
)
context
.getSystemService(LauncherApps::class.java)
?.pinShortcuts(key, ArrayList(modelShortcuts), user)
} catch (e: SecurityException) {
Log.w(TAG, "Failed to pin shortcut", e)
} catch (e: IllegalStateException) {
Log.w(TAG, "Failed to pin shortcut", e)
}
}
}
// If there are any extra pinned shortcuts, remove them
systemMap.keys.forEach { packageName: String ->
// Update system state
try {
FileLog.d(
TAG,
("updateShortcutPinnedState:" +
" Unpinning extra Shortcuts for package: $packageName: ${systemMap[packageName]}"),
)
context
.getSystemService(LauncherApps::class.java)
?.pinShortcuts(packageName, emptyList(), user)
} catch (e: SecurityException) {
Log.w(TAG, "Failed to unpin shortcut", e)
} catch (e: IllegalStateException) {
Log.w(TAG, "Failed to unpin shortcut", e)
}
}
}
/**
* Clear all the deep shortcut counts for the given package, and re-add the new shortcut counts.
*/
@Synchronized
fun updateDeepShortcutCounts(
packageName: String?,
user: UserHandle,
shortcuts: List<ShortcutInfo>,
) {
if (packageName != null) {
deepShortcutMap.keys.removeAll {
it.componentName.packageName == packageName && it.user == user
}
}
// Now add the new shortcuts to the map.
deepShortcutMap +=
shortcuts
.asSequence()
.filter {
it.isEnabled && (it.isDeclaredInManifest || it.isDynamic) && it.activity != null
}
.groupingBy { ComponentKey(it.activity, it.userHandle) }
.eachCount()
}
/**
* Calls the provided `op` for all workspaceItems in the in-memory model (both persisted items
* and dynamic/predicted items for the provided `userHandle`. Note the call is not synchronized
* over the model, that should be handled by the called.
*/
fun forAllWorkspaceItemInfos(userHandle: UserHandle, op: Consumer<WorkspaceItemInfo>) {
itemsIdMap.forEach { if (it is WorkspaceItemInfo && userHandle == it.user) op.accept(it) }
extraItems.forEach { info ->
info.items.forEach {
if (it is WorkspaceItemInfo && userHandle == it.user) op.accept(it)
}
}
}
/** An object containing items corresponding to a fixed container */
class FixedContainerItems(@JvmField val containerId: Int, items: List<ItemInfo>) {
@JvmField val items: List<ItemInfo> = Collections.unmodifiableList(items)
override fun toString() =
"FixedContainerItems: id=$containerId itemCount=${items.size}, [${items.joinToString()}"
}
interface Callbacks {
/**
* Does a complete model rebind. The callback can be called on any thread and it is up to
* the client to move the executor to appropriate thread
*/
@AnyThread
fun bindCompleteModelAsync(
itemIdMap: IntSparseArrayMap<ItemInfo>,
extraItems: List<FixedContainerItems>,
stringCache: StringCache,
isBindingSync: Boolean,
) {
Executors.MAIN_EXECUTOR.execute {
bindCompleteModel(itemIdMap, extraItems, stringCache, isBindingSync)
}
}
fun bindCompleteModel(
itemIdMap: IntSparseArrayMap<ItemInfo>,
extraItems: List<FixedContainerItems>,
stringCache: StringCache,
isBindingSync: Boolean,
) {}
fun bindItemsAdded(items: List<@JvmSuppressWildcards ItemInfo>) {}
/** Called when a runtime property of the ItemInfo is updated due to some system event */
fun bindItemsUpdated(updates: Set<@JvmSuppressWildcards ItemInfo>) {}
fun bindWorkspaceComponentsRemoved(matcher: Predicate<ItemInfo?>) {}
/** Binds updated incremental download progress */
fun bindIncrementalDownloadProgressUpdated(app: AppInfo) {}
/** Binds the app widgets to the providers that share widgets with the UI. */
fun bindAllWidgets(widgets: List<@JvmSuppressWildcards WidgetsListBaseEntry>) {}
fun bindSmartspaceWidget() {}
fun bindDeepShortcutMap(deepShortcutMap: HashMap<ComponentKey, Int>) {}
/** Binds extra item provided any external source */
fun bindExtraContainerItems(item: FixedContainerItems) {}
fun bindAllApplications(
apps: Array<AppInfo>,
flags: Int,
packageUserKeytoUidMap: Map<PackageUserKey, Int>,
) {}
/** Binds the cache of string resources */
fun bindStringCache(cache: StringCache) {}
companion object {
// If the launcher has permission to access deep shortcuts.
const val FLAG_HAS_SHORTCUT_PERMISSION: Int = 1 shl 0
// If quiet mode is enabled for any user
const val FLAG_QUIET_MODE_ENABLED: Int = 1 shl 1
// If launcher can change quiet mode
const val FLAG_QUIET_MODE_CHANGE_PERMISSION: Int = 1 shl 2
// If quiet mode is enabled for work profile user
const val FLAG_WORK_PROFILE_QUIET_MODE_ENABLED: Int = 1 shl 3
// If quiet mode is enabled for private profile user
const val FLAG_PRIVATE_PROFILE_QUIET_MODE_ENABLED: Int = 1 shl 4
}
}
companion object {
private const val TAG = "BgDataModel"
}
}