1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package com.android.launcher3.model;
17 
18 import static com.android.launcher3.model.BgDataModel.Callbacks.FLAG_QUIET_MODE_ENABLED;
19 import static com.android.launcher3.model.data.WorkspaceItemInfo.FLAG_AUTOINSTALL_ICON;
20 import static com.android.launcher3.model.data.WorkspaceItemInfo.FLAG_RESTORED_ICON;
21 
22 import android.content.ComponentName;
23 import android.content.Context;
24 import android.content.Intent;
25 import android.content.pm.LauncherActivityInfo;
26 import android.content.pm.LauncherApps;
27 import android.content.pm.ShortcutInfo;
28 import android.os.UserHandle;
29 import android.os.UserManager;
30 import android.util.Log;
31 
32 import com.android.launcher3.Launcher;
33 import com.android.launcher3.LauncherAppState;
34 import com.android.launcher3.LauncherSettings;
35 import com.android.launcher3.LauncherSettings.Favorites;
36 import com.android.launcher3.config.FeatureFlags;
37 import com.android.launcher3.icons.BitmapInfo;
38 import com.android.launcher3.icons.IconCache;
39 import com.android.launcher3.icons.LauncherIcons;
40 import com.android.launcher3.logging.FileLog;
41 import com.android.launcher3.model.data.ItemInfo;
42 import com.android.launcher3.model.data.LauncherAppWidgetInfo;
43 import com.android.launcher3.model.data.WorkspaceItemInfo;
44 import com.android.launcher3.pm.PackageInstallInfo;
45 import com.android.launcher3.pm.UserCache;
46 import com.android.launcher3.shortcuts.ShortcutRequest;
47 import com.android.launcher3.util.FlagOp;
48 import com.android.launcher3.util.IntSet;
49 import com.android.launcher3.util.ItemInfoMatcher;
50 import com.android.launcher3.util.PackageManagerHelper;
51 import com.android.launcher3.util.PackageUserKey;
52 import com.android.launcher3.util.SafeCloseable;
53 
54 import java.util.ArrayList;
55 import java.util.Arrays;
56 import java.util.Collections;
57 import java.util.HashMap;
58 import java.util.HashSet;
59 import java.util.List;
60 
61 /**
62  * Handles updates due to changes in package manager (app installed/updated/removed)
63  * or when a user availability changes.
64  */
65 public class PackageUpdatedTask extends BaseModelUpdateTask {
66 
67     private static final boolean DEBUG = false;
68     private static final String TAG = "PackageUpdatedTask";
69 
70     public static final int OP_NONE = 0;
71     public static final int OP_ADD = 1;
72     public static final int OP_UPDATE = 2;
73     public static final int OP_REMOVE = 3; // uninstalled
74     public static final int OP_UNAVAILABLE = 4; // external media unmounted
75     public static final int OP_SUSPEND = 5; // package suspended
76     public static final int OP_UNSUSPEND = 6; // package unsuspended
77     public static final int OP_USER_AVAILABILITY_CHANGE = 7; // user available/unavailable
78 
79     private final int mOp;
80     private final UserHandle mUser;
81     private final String[] mPackages;
82 
PackageUpdatedTask(int op, UserHandle user, String... packages)83     public PackageUpdatedTask(int op, UserHandle user, String... packages) {
84         mOp = op;
85         mUser = user;
86         mPackages = packages;
87     }
88 
89     @Override
execute(LauncherAppState app, BgDataModel dataModel, AllAppsList appsList)90     public void execute(LauncherAppState app, BgDataModel dataModel, AllAppsList appsList) {
91         final Context context = app.getContext();
92         final IconCache iconCache = app.getIconCache();
93 
94         final String[] packages = mPackages;
95         final int N = packages.length;
96         final FlagOp flagOp;
97         final HashSet<String> packageSet = new HashSet<>(Arrays.asList(packages));
98         final ItemInfoMatcher matcher = mOp == OP_USER_AVAILABILITY_CHANGE
99                 ? ItemInfoMatcher.ofUser(mUser) // We want to update all packages for this user
100                 : ItemInfoMatcher.ofPackages(packageSet, mUser);
101         final HashSet<ComponentName> removedComponents = new HashSet<>();
102         final HashMap<String, List<LauncherActivityInfo>> activitiesLists = new HashMap<>();
103 
104         switch (mOp) {
105             case OP_ADD: {
106                 for (int i = 0; i < N; i++) {
107                     if (DEBUG) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
108                     iconCache.updateIconsForPkg(packages[i], mUser);
109                     if (FeatureFlags.PROMISE_APPS_IN_ALL_APPS.get()) {
110                         appsList.removePackage(packages[i], mUser);
111                     }
112                     activitiesLists.put(
113                             packages[i], appsList.addPackage(context, packages[i], mUser));
114                 }
115                 flagOp = FlagOp.removeFlag(WorkspaceItemInfo.FLAG_DISABLED_NOT_AVAILABLE);
116                 break;
117             }
118             case OP_UPDATE:
119                 try (SafeCloseable t =
120                              appsList.trackRemoves(a -> removedComponents.add(a.componentName))) {
121                     for (int i = 0; i < N; i++) {
122                         if (DEBUG) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
123                         iconCache.updateIconsForPkg(packages[i], mUser);
124                         activitiesLists.put(
125                                 packages[i], appsList.updatePackage(context, packages[i], mUser));
126 
127                         // The update may have changed which shortcuts/widgets are available.
128                         // Refresh the widgets for the package if we have an activity running.
129                         Launcher launcher = Launcher.ACTIVITY_TRACKER.getCreatedActivity();
130                         if (launcher != null) {
131                             launcher.refreshAndBindWidgetsForPackageUser(
132                                     new PackageUserKey(packages[i], mUser));
133                         }
134                     }
135                 }
136                 // Since package was just updated, the target must be available now.
137                 flagOp = FlagOp.removeFlag(WorkspaceItemInfo.FLAG_DISABLED_NOT_AVAILABLE);
138                 break;
139             case OP_REMOVE: {
140                 for (int i = 0; i < N; i++) {
141                     FileLog.d(TAG, "Removing app icon" + packages[i]);
142                     iconCache.removeIconsForPkg(packages[i], mUser);
143                 }
144                 // Fall through
145             }
146             case OP_UNAVAILABLE:
147                 for (int i = 0; i < N; i++) {
148                     if (DEBUG) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
149                     appsList.removePackage(packages[i], mUser);
150                 }
151                 flagOp = FlagOp.addFlag(WorkspaceItemInfo.FLAG_DISABLED_NOT_AVAILABLE);
152                 break;
153             case OP_SUSPEND:
154             case OP_UNSUSPEND:
155                 flagOp = mOp == OP_SUSPEND ?
156                         FlagOp.addFlag(WorkspaceItemInfo.FLAG_DISABLED_SUSPENDED) :
157                         FlagOp.removeFlag(WorkspaceItemInfo.FLAG_DISABLED_SUSPENDED);
158                 if (DEBUG) Log.d(TAG, "mAllAppsList.(un)suspend " + N);
159                 appsList.updateDisabledFlags(matcher, flagOp);
160                 break;
161             case OP_USER_AVAILABILITY_CHANGE: {
162                 UserManagerState ums = new UserManagerState();
163                 ums.init(UserCache.INSTANCE.get(context),
164                         context.getSystemService(UserManager.class));
165                 flagOp = ums.isUserQuiet(mUser)
166                         ? FlagOp.addFlag(WorkspaceItemInfo.FLAG_DISABLED_QUIET_USER)
167                         : FlagOp.removeFlag(WorkspaceItemInfo.FLAG_DISABLED_QUIET_USER);
168                 appsList.updateDisabledFlags(matcher, flagOp);
169 
170                 // We are not synchronizing here, as int operations are atomic
171                 appsList.setFlags(FLAG_QUIET_MODE_ENABLED, ums.isAnyProfileQuietModeEnabled());
172                 break;
173             }
174             default:
175                 flagOp = FlagOp.NO_OP;
176                 break;
177         }
178 
179         bindApplicationsIfNeeded();
180 
181         final IntSet removedShortcuts = new IntSet();
182         // Shortcuts to keep even if the corresponding app was removed
183         final IntSet forceKeepShortcuts = new IntSet();
184 
185         // Update shortcut infos
186         if (mOp == OP_ADD || flagOp != FlagOp.NO_OP) {
187             final ArrayList<WorkspaceItemInfo> updatedWorkspaceItems = new ArrayList<>();
188             final ArrayList<LauncherAppWidgetInfo> widgets = new ArrayList<>();
189 
190             // For system apps, package manager send OP_UPDATE when an app is enabled.
191             final boolean isNewApkAvailable = mOp == OP_ADD || mOp == OP_UPDATE;
192             synchronized (dataModel) {
193                 dataModel.forAllWorkspaceItemInfos(mUser, si -> {
194 
195                     boolean infoUpdated = false;
196                     boolean shortcutUpdated = false;
197 
198                     // Update shortcuts which use iconResource.
199                     if ((si.iconResource != null)
200                             && packageSet.contains(si.iconResource.packageName)) {
201                         LauncherIcons li = LauncherIcons.obtain(context);
202                         BitmapInfo iconInfo = li.createIconBitmap(si.iconResource);
203                         li.recycle();
204                         if (iconInfo != null) {
205                             si.bitmap = iconInfo;
206                             infoUpdated = true;
207                         }
208                     }
209 
210                     ComponentName cn = si.getTargetComponent();
211                     if (cn != null && matcher.matches(si, cn)) {
212                         String packageName = cn.getPackageName();
213 
214                         if (si.hasStatusFlag(WorkspaceItemInfo.FLAG_SUPPORTS_WEB_UI)) {
215                             forceKeepShortcuts.add(si.id);
216                             if (mOp == OP_REMOVE) {
217                                 return;
218                             }
219                         }
220 
221                         if (si.isPromise() && isNewApkAvailable) {
222                             boolean isTargetValid = !cn.getClassName().equals(
223                                     IconCache.EMPTY_CLASS_NAME);
224                             if (si.itemType == Favorites.ITEM_TYPE_DEEP_SHORTCUT) {
225                                 List<ShortcutInfo> shortcut =
226                                         new ShortcutRequest(context, mUser)
227                                                 .forPackage(cn.getPackageName(),
228                                                         si.getDeepShortcutId())
229                                                 .query(ShortcutRequest.PINNED);
230                                 if (shortcut.isEmpty()) {
231                                     isTargetValid = false;
232                                 } else {
233                                     si.updateFromDeepShortcutInfo(shortcut.get(0), context);
234                                     infoUpdated = true;
235                                 }
236                             } else if (isTargetValid) {
237                                 isTargetValid = context.getSystemService(LauncherApps.class)
238                                         .isActivityEnabled(cn, mUser);
239                             }
240                             if (!isTargetValid && si.hasStatusFlag(
241                                     FLAG_RESTORED_ICON | FLAG_AUTOINSTALL_ICON)) {
242                                 if (updateWorkspaceItemIntent(context, si, packageName)) {
243                                     infoUpdated = true;
244                                 } else if (si.hasPromiseIconUi()) {
245                                     removedShortcuts.add(si.id);
246                                     return;
247                                 }
248                             } else if (!isTargetValid) {
249                                 removedShortcuts.add(si.id);
250                                 FileLog.e(TAG, "Restored shortcut no longer valid "
251                                         + si.getIntent());
252                                 return;
253                             } else {
254                                 si.status = WorkspaceItemInfo.DEFAULT;
255                                 infoUpdated = true;
256                             }
257                         } else if (isNewApkAvailable && removedComponents.contains(cn)) {
258                             if (updateWorkspaceItemIntent(context, si, packageName)) {
259                                 infoUpdated = true;
260                             }
261                         }
262 
263                         if (isNewApkAvailable) {
264                             List<LauncherActivityInfo> activities = activitiesLists.get(
265                                     packageName);
266                             si.setProgressLevel(
267                                     activities == null || activities.isEmpty()
268                                             ? 100
269                                             : PackageManagerHelper.getLoadingProgress(
270                                                     activities.get(0)),
271                                     PackageInstallInfo.STATUS_INSTALLED_DOWNLOADING);
272                             if (si.itemType == Favorites.ITEM_TYPE_APPLICATION) {
273                                 iconCache.getTitleAndIcon(si, si.usingLowResIcon());
274                                 infoUpdated = true;
275                             }
276                         }
277 
278                         int oldRuntimeFlags = si.runtimeStatusFlags;
279                         si.runtimeStatusFlags = flagOp.apply(si.runtimeStatusFlags);
280                         if (si.runtimeStatusFlags != oldRuntimeFlags) {
281                             shortcutUpdated = true;
282                         }
283                     }
284 
285                     if (infoUpdated || shortcutUpdated) {
286                         updatedWorkspaceItems.add(si);
287                     }
288                     if (infoUpdated && si.id != ItemInfo.NO_ID) {
289                         getModelWriter().updateItemInDatabase(si);
290                     }
291                 });
292 
293                 for (LauncherAppWidgetInfo widgetInfo : dataModel.appWidgets) {
294                     if (mUser.equals(widgetInfo.user)
295                             && widgetInfo.hasRestoreFlag(
296                                     LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY)
297                             && packageSet.contains(widgetInfo.providerName.getPackageName())) {
298                         widgetInfo.restoreStatus &=
299                                 ~LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY
300                                         & ~LauncherAppWidgetInfo.FLAG_RESTORE_STARTED;
301 
302                         // adding this flag ensures that launcher shows 'click to setup'
303                         // if the widget has a config activity. In case there is no config
304                         // activity, it will be marked as 'restored' during bind.
305                         widgetInfo.restoreStatus |= LauncherAppWidgetInfo.FLAG_UI_NOT_READY;
306 
307                         widgets.add(widgetInfo);
308                         getModelWriter().updateItemInDatabase(widgetInfo);
309                     }
310                 }
311             }
312 
313             bindUpdatedWorkspaceItems(updatedWorkspaceItems);
314             if (!removedShortcuts.isEmpty()) {
315                 deleteAndBindComponentsRemoved(ItemInfoMatcher.ofItemIds(removedShortcuts));
316             }
317 
318             if (!widgets.isEmpty()) {
319                 scheduleCallbackTask(c -> c.bindWidgetsRestored(widgets));
320             }
321         }
322 
323         final HashSet<String> removedPackages = new HashSet<>();
324         if (mOp == OP_REMOVE) {
325             // Mark all packages in the broadcast to be removed
326             Collections.addAll(removedPackages, packages);
327 
328             // No need to update the removedComponents as
329             // removedPackages is a super-set of removedComponents
330         } else if (mOp == OP_UPDATE) {
331             // Mark disabled packages in the broadcast to be removed
332             final LauncherApps launcherApps = context.getSystemService(LauncherApps.class);
333             for (int i=0; i<N; i++) {
334                 if (!launcherApps.isPackageEnabled(packages[i], mUser)) {
335                     removedPackages.add(packages[i]);
336                 }
337             }
338         }
339 
340         if (!removedPackages.isEmpty() || !removedComponents.isEmpty()) {
341             ItemInfoMatcher removeMatch = ItemInfoMatcher.ofPackages(removedPackages, mUser)
342                     .or(ItemInfoMatcher.ofComponents(removedComponents, mUser))
343                     .and(ItemInfoMatcher.ofItemIds(forceKeepShortcuts).negate());
344             deleteAndBindComponentsRemoved(removeMatch);
345 
346             // Remove any queued items from the install queue
347             ItemInstallQueue.INSTANCE.get(context)
348                     .removeFromInstallQueue(removedPackages, mUser);
349         }
350 
351         if (mOp == OP_ADD) {
352             // Load widgets for the new package. Changes due to app updates are handled through
353             // AppWidgetHost events, this is just to initialize the long-press options.
354             for (int i = 0; i < N; i++) {
355                 dataModel.widgetsModel.update(app, new PackageUserKey(packages[i], mUser));
356             }
357             bindUpdatedWidgets(dataModel);
358         }
359     }
360 
361     /**
362      * Updates {@param si}'s intent to point to a new ComponentName.
363      * @return Whether the shortcut intent was changed.
364      */
updateWorkspaceItemIntent(Context context, WorkspaceItemInfo si, String packageName)365     private boolean updateWorkspaceItemIntent(Context context,
366             WorkspaceItemInfo si, String packageName) {
367         if (si.itemType == LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT) {
368             // Do not update intent for deep shortcuts as they contain additional information
369             // about the shortcut.
370             return false;
371         }
372         // Try to find the best match activity.
373         Intent intent = new PackageManagerHelper(context).getAppLaunchIntent(packageName, mUser);
374         if (intent != null) {
375             si.intent = intent;
376             si.status = WorkspaceItemInfo.DEFAULT;
377             return true;
378         }
379         return false;
380     }
381 }
382