• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.server.pm;
17 
18 import android.annotation.NonNull;
19 import android.annotation.Nullable;
20 import android.annotation.UserIdInt;
21 import android.app.Person;
22 import android.content.ComponentName;
23 import android.content.Intent;
24 import android.content.IntentFilter;
25 import android.content.LocusId;
26 import android.content.pm.PackageInfo;
27 import android.content.pm.ShortcutInfo;
28 import android.content.pm.ShortcutManager;
29 import android.content.res.Resources;
30 import android.graphics.drawable.Icon;
31 import android.os.PersistableBundle;
32 import android.text.format.Formatter;
33 import android.util.ArrayMap;
34 import android.util.ArraySet;
35 import android.util.AtomicFile;
36 import android.util.Log;
37 import android.util.Slog;
38 import android.util.Xml;
39 
40 import com.android.internal.annotations.VisibleForTesting;
41 import com.android.internal.util.ArrayUtils;
42 import com.android.internal.util.CollectionUtils;
43 import com.android.internal.util.Preconditions;
44 import com.android.internal.util.XmlUtils;
45 import com.android.server.pm.ShortcutService.DumpFilter;
46 import com.android.server.pm.ShortcutService.ShortcutOperation;
47 import com.android.server.pm.ShortcutService.Stats;
48 
49 import libcore.io.IoUtils;
50 
51 import org.json.JSONException;
52 import org.json.JSONObject;
53 import org.xmlpull.v1.XmlPullParser;
54 import org.xmlpull.v1.XmlPullParserException;
55 import org.xmlpull.v1.XmlSerializer;
56 
57 import java.io.BufferedInputStream;
58 import java.io.File;
59 import java.io.FileInputStream;
60 import java.io.FileNotFoundException;
61 import java.io.IOException;
62 import java.io.PrintWriter;
63 import java.nio.charset.StandardCharsets;
64 import java.util.ArrayList;
65 import java.util.Collections;
66 import java.util.Comparator;
67 import java.util.List;
68 import java.util.Objects;
69 import java.util.Set;
70 import java.util.function.Predicate;
71 
72 /**
73  * Package information used by {@link ShortcutService}.
74  * User information used by {@link ShortcutService}.
75  *
76  * All methods should be guarded by {@code #mShortcutUser.mService.mLock}.
77  */
78 class ShortcutPackage extends ShortcutPackageItem {
79     private static final String TAG = ShortcutService.TAG;
80     private static final String TAG_VERIFY = ShortcutService.TAG + ".verify";
81 
82     static final String TAG_ROOT = "package";
83     private static final String TAG_INTENT_EXTRAS_LEGACY = "intent-extras";
84     private static final String TAG_INTENT = "intent";
85     private static final String TAG_EXTRAS = "extras";
86     private static final String TAG_SHORTCUT = "shortcut";
87     private static final String TAG_SHARE_TARGET = "share-target";
88     private static final String TAG_CATEGORIES = "categories";
89     private static final String TAG_PERSON = "person";
90 
91     private static final String ATTR_NAME = "name";
92     private static final String ATTR_CALL_COUNT = "call-count";
93     private static final String ATTR_LAST_RESET = "last-reset";
94     private static final String ATTR_ID = "id";
95     private static final String ATTR_ACTIVITY = "activity";
96     private static final String ATTR_TITLE = "title";
97     private static final String ATTR_TITLE_RES_ID = "titleid";
98     private static final String ATTR_TITLE_RES_NAME = "titlename";
99     private static final String ATTR_TEXT = "text";
100     private static final String ATTR_TEXT_RES_ID = "textid";
101     private static final String ATTR_TEXT_RES_NAME = "textname";
102     private static final String ATTR_DISABLED_MESSAGE = "dmessage";
103     private static final String ATTR_DISABLED_MESSAGE_RES_ID = "dmessageid";
104     private static final String ATTR_DISABLED_MESSAGE_RES_NAME = "dmessagename";
105     private static final String ATTR_DISABLED_REASON = "disabled-reason";
106     private static final String ATTR_INTENT_LEGACY = "intent";
107     private static final String ATTR_INTENT_NO_EXTRA = "intent-base";
108     private static final String ATTR_RANK = "rank";
109     private static final String ATTR_TIMESTAMP = "timestamp";
110     private static final String ATTR_FLAGS = "flags";
111     private static final String ATTR_ICON_RES_ID = "icon-res";
112     private static final String ATTR_ICON_RES_NAME = "icon-resname";
113     private static final String ATTR_BITMAP_PATH = "bitmap-path";
114     private static final String ATTR_ICON_URI = "icon-uri";
115     private static final String ATTR_LOCUS_ID = "locus-id";
116 
117     private static final String ATTR_PERSON_NAME = "name";
118     private static final String ATTR_PERSON_URI = "uri";
119     private static final String ATTR_PERSON_KEY = "key";
120     private static final String ATTR_PERSON_IS_BOT = "is-bot";
121     private static final String ATTR_PERSON_IS_IMPORTANT = "is-important";
122 
123     private static final String NAME_CATEGORIES = "categories";
124 
125     private static final String TAG_STRING_ARRAY_XMLUTILS = "string-array";
126     private static final String ATTR_NAME_XMLUTILS = "name";
127 
128     private static final String KEY_DYNAMIC = "dynamic";
129     private static final String KEY_MANIFEST = "manifest";
130     private static final String KEY_PINNED = "pinned";
131     private static final String KEY_BITMAPS = "bitmaps";
132     private static final String KEY_BITMAP_BYTES = "bitmapBytes";
133 
134     /**
135      * All the shortcuts from the package, keyed on IDs.
136      */
137     final private ArrayMap<String, ShortcutInfo> mShortcuts = new ArrayMap<>();
138 
139     /**
140      * All the share targets from the package
141      */
142     private final ArrayList<ShareTargetInfo> mShareTargets = new ArrayList<>(0);
143 
144     /**
145      * # of times the package has called rate-limited APIs.
146      */
147     private int mApiCallCount;
148 
149     /**
150      * When {@link #mApiCallCount} was reset last time.
151      */
152     private long mLastResetTime;
153 
154     private final int mPackageUid;
155 
156     private long mLastKnownForegroundElapsedTime;
157 
ShortcutPackage(ShortcutUser shortcutUser, int packageUserId, String packageName, ShortcutPackageInfo spi)158     private ShortcutPackage(ShortcutUser shortcutUser,
159             int packageUserId, String packageName, ShortcutPackageInfo spi) {
160         super(shortcutUser, packageUserId, packageName,
161                 spi != null ? spi : ShortcutPackageInfo.newEmpty());
162 
163         mPackageUid = shortcutUser.mService.injectGetPackageUid(packageName, packageUserId);
164     }
165 
ShortcutPackage(ShortcutUser shortcutUser, int packageUserId, String packageName)166     public ShortcutPackage(ShortcutUser shortcutUser, int packageUserId, String packageName) {
167         this(shortcutUser, packageUserId, packageName, null);
168     }
169 
170     @Override
getOwnerUserId()171     public int getOwnerUserId() {
172         // For packages, always owner user == package user.
173         return getPackageUserId();
174     }
175 
getPackageUid()176     public int getPackageUid() {
177         return mPackageUid;
178     }
179 
180     @Nullable
getPackageResources()181     public Resources getPackageResources() {
182         return mShortcutUser.mService.injectGetResourcesForApplicationAsUser(
183                 getPackageName(), getPackageUserId());
184     }
185 
getShortcutCount()186     public int getShortcutCount() {
187         return mShortcuts.size();
188     }
189 
190     @Override
canRestoreAnyVersion()191     protected boolean canRestoreAnyVersion() {
192         return false;
193     }
194 
195     @Override
onRestored(int restoreBlockReason)196     protected void onRestored(int restoreBlockReason) {
197         // Shortcuts have been restored.
198         // - Unshadow all shortcuts.
199         // - Set disabled reason.
200         // - Disable if needed.
201         for (int i = mShortcuts.size() - 1; i >= 0; i--) {
202             ShortcutInfo si = mShortcuts.valueAt(i);
203             si.clearFlags(ShortcutInfo.FLAG_SHADOW);
204 
205             si.setDisabledReason(restoreBlockReason);
206             if (restoreBlockReason != ShortcutInfo.DISABLED_REASON_NOT_DISABLED) {
207                 si.addFlags(ShortcutInfo.FLAG_DISABLED);
208             }
209         }
210         // Because some launchers may not have been restored (e.g. allowBackup=false),
211         // we need to re-calculate the pinned shortcuts.
212         refreshPinnedFlags();
213     }
214 
215     /**
216      * Note this does *not* provide a correct view to the calling launcher.
217      */
218     @Nullable
findShortcutById(String id)219     public ShortcutInfo findShortcutById(String id) {
220         return mShortcuts.get(id);
221     }
222 
isShortcutExistsAndInvisibleToPublisher(String id)223     public boolean isShortcutExistsAndInvisibleToPublisher(String id) {
224         ShortcutInfo si = findShortcutById(id);
225         return si != null && !si.isVisibleToPublisher();
226     }
227 
isShortcutExistsAndVisibleToPublisher(String id)228     public boolean isShortcutExistsAndVisibleToPublisher(String id) {
229         ShortcutInfo si = findShortcutById(id);
230         return si != null && si.isVisibleToPublisher();
231     }
232 
ensureNotImmutable(@ullable ShortcutInfo shortcut, boolean ignoreInvisible)233     private void ensureNotImmutable(@Nullable ShortcutInfo shortcut, boolean ignoreInvisible) {
234         if (shortcut != null && shortcut.isImmutable()
235                 && (!ignoreInvisible || shortcut.isVisibleToPublisher())) {
236             throw new IllegalArgumentException(
237                     "Manifest shortcut ID=" + shortcut.getId()
238                             + " may not be manipulated via APIs");
239         }
240     }
241 
ensureNotImmutable(@onNull String id, boolean ignoreInvisible)242     public void ensureNotImmutable(@NonNull String id, boolean ignoreInvisible) {
243         ensureNotImmutable(mShortcuts.get(id), ignoreInvisible);
244     }
245 
ensureImmutableShortcutsNotIncludedWithIds(@onNull List<String> shortcutIds, boolean ignoreInvisible)246     public void ensureImmutableShortcutsNotIncludedWithIds(@NonNull List<String> shortcutIds,
247             boolean ignoreInvisible) {
248         for (int i = shortcutIds.size() - 1; i >= 0; i--) {
249             ensureNotImmutable(shortcutIds.get(i), ignoreInvisible);
250         }
251     }
252 
ensureImmutableShortcutsNotIncluded(@onNull List<ShortcutInfo> shortcuts, boolean ignoreInvisible)253     public void ensureImmutableShortcutsNotIncluded(@NonNull List<ShortcutInfo> shortcuts,
254             boolean ignoreInvisible) {
255         for (int i = shortcuts.size() - 1; i >= 0; i--) {
256             ensureNotImmutable(shortcuts.get(i).getId(), ignoreInvisible);
257         }
258     }
259 
ensureNoBitmapIconIfShortcutIsLongLived(@onNull List<ShortcutInfo> shortcuts)260     public void ensureNoBitmapIconIfShortcutIsLongLived(@NonNull List<ShortcutInfo> shortcuts) {
261         for (int i = shortcuts.size() - 1; i >= 0; i--) {
262             final ShortcutInfo si = shortcuts.get(i);
263             if (!si.isLongLived()) {
264                 continue;
265             }
266             final Icon icon = si.getIcon();
267             if (icon != null && icon.getType() != Icon.TYPE_BITMAP
268                     && icon.getType() == Icon.TYPE_ADAPTIVE_BITMAP) {
269                 continue;
270             }
271             if (icon == null && !si.hasIconFile()) {
272                 continue;
273             }
274 
275             // TODO: Throw IllegalArgumentException instead.
276             Slog.e(TAG, "Invalid icon type in shortcut " + si.getId() + ". Bitmaps are not allowed"
277                     + " in long-lived shortcuts. Use Resource icons, or Uri-based icons instead.");
278             return;  // Do not spam and return early.
279         }
280     }
281 
282     /**
283      * Delete a shortcut by ID. This will *always* remove it even if it's immutable or invisible.
284      */
forceDeleteShortcutInner(@onNull String id)285     private ShortcutInfo forceDeleteShortcutInner(@NonNull String id) {
286         final ShortcutInfo shortcut = mShortcuts.remove(id);
287         if (shortcut != null) {
288             mShortcutUser.mService.removeIconLocked(shortcut);
289             shortcut.clearFlags(ShortcutInfo.FLAG_DYNAMIC | ShortcutInfo.FLAG_PINNED
290                     | ShortcutInfo.FLAG_MANIFEST | ShortcutInfo.FLAG_CACHED_ALL);
291         }
292         return shortcut;
293     }
294 
295     /**
296      * Force replace a shortcut. If there's already a shortcut with the same ID, it'll be removed,
297      * even if it's invisible.
298      */
forceReplaceShortcutInner(@onNull ShortcutInfo newShortcut)299     private void forceReplaceShortcutInner(@NonNull ShortcutInfo newShortcut) {
300         final ShortcutService s = mShortcutUser.mService;
301 
302         forceDeleteShortcutInner(newShortcut.getId());
303 
304         // Extract Icon and update the icon res ID and the bitmap path.
305         s.saveIconAndFixUpShortcutLocked(newShortcut);
306         s.fixUpShortcutResourceNamesAndValues(newShortcut);
307         mShortcuts.put(newShortcut.getId(), newShortcut);
308     }
309 
310     /**
311      * Add a shortcut. If there's already a one with the same ID, it'll be removed, even if it's
312      * invisible.
313      *
314      * It checks the max number of dynamic shortcuts.
315      *
316      * @return True if it replaced an existing shortcut, False otherwise.
317      */
addOrReplaceDynamicShortcut(@onNull ShortcutInfo newShortcut)318     public boolean addOrReplaceDynamicShortcut(@NonNull ShortcutInfo newShortcut) {
319 
320         Preconditions.checkArgument(newShortcut.isEnabled(),
321                 "add/setDynamicShortcuts() cannot publish disabled shortcuts");
322 
323         newShortcut.addFlags(ShortcutInfo.FLAG_DYNAMIC);
324 
325         final ShortcutInfo oldShortcut = mShortcuts.get(newShortcut.getId());
326         if (oldShortcut != null) {
327             // It's an update case.
328             // Make sure the target is updatable. (i.e. should be mutable.)
329             oldShortcut.ensureUpdatableWith(newShortcut, /*isUpdating=*/ false);
330 
331             // If it was originally pinned or cached, the new one should be pinned or cached too.
332             newShortcut.addFlags(oldShortcut.getFlags()
333                     & (ShortcutInfo.FLAG_PINNED | ShortcutInfo.FLAG_CACHED_ALL));
334         }
335 
336         forceReplaceShortcutInner(newShortcut);
337         return oldShortcut != null;
338     }
339 
340     /**
341      * Push a shortcut. If the max number of dynamic shortcuts is already reached, remove the
342      * shortcut with the lowest rank before adding the new shortcut.
343      *
344      * Any shortcut that gets altered (removed or changed) as a result of this push operation will
345      * be included and returned in changedShortcuts.
346      *
347      * @return True if a shortcut had to be removed to complete this operation, False otherwise.
348      */
pushDynamicShortcut(@onNull ShortcutInfo newShortcut, @NonNull List<ShortcutInfo> changedShortcuts)349     public boolean pushDynamicShortcut(@NonNull ShortcutInfo newShortcut,
350             @NonNull List<ShortcutInfo> changedShortcuts) {
351         Preconditions.checkArgument(newShortcut.isEnabled(),
352                 "pushDynamicShortcuts() cannot publish disabled shortcuts");
353 
354         newShortcut.addFlags(ShortcutInfo.FLAG_DYNAMIC);
355 
356         changedShortcuts.clear();
357         final ShortcutInfo oldShortcut = mShortcuts.get(newShortcut.getId());
358         boolean deleted = false;
359 
360         if (oldShortcut == null) {
361             final ShortcutService service = mShortcutUser.mService;
362             final int maxShortcuts = service.getMaxActivityShortcuts();
363 
364             final ArrayMap<ComponentName, ArrayList<ShortcutInfo>> all =
365                     sortShortcutsToActivities();
366             final ArrayList<ShortcutInfo> activityShortcuts = all.get(newShortcut.getActivity());
367 
368             if (activityShortcuts != null && activityShortcuts.size() == maxShortcuts) {
369                 // Max has reached. Delete the shortcut with lowest rank.
370 
371                 // Sort by isManifestShortcut() and getRank().
372                 Collections.sort(activityShortcuts, mShortcutTypeAndRankComparator);
373 
374                 final ShortcutInfo shortcut = activityShortcuts.get(maxShortcuts - 1);
375                 if (shortcut.isManifestShortcut()) {
376                     // All shortcuts are manifest shortcuts and cannot be removed.
377                     Slog.e(TAG, "Failed to remove manifest shortcut while pushing dynamic shortcut "
378                             + newShortcut.getId());
379                     return true;  // poppedShortcuts is empty which indicates a failure.
380                 }
381 
382                 changedShortcuts.add(shortcut);
383                 deleted = deleteDynamicWithId(shortcut.getId(), /*ignoreInvisible=*/ true) != null;
384             }
385         } else {
386             // It's an update case.
387             // Make sure the target is updatable. (i.e. should be mutable.)
388             oldShortcut.ensureUpdatableWith(newShortcut, /*isUpdating=*/ false);
389 
390             // If it was originally pinned or cached, the new one should be pinned or cached too.
391             newShortcut.addFlags(oldShortcut.getFlags()
392                     & (ShortcutInfo.FLAG_PINNED | ShortcutInfo.FLAG_CACHED_ALL));
393         }
394 
395         forceReplaceShortcutInner(newShortcut);
396         return deleted;
397     }
398 
399     /**
400      * Remove all shortcuts that aren't pinned, cached nor dynamic.
401      *
402      * @return List of removed shortcuts.
403      */
removeOrphans()404     private List<ShortcutInfo> removeOrphans() {
405         List<ShortcutInfo> removeList = null;
406 
407         for (int i = mShortcuts.size() - 1; i >= 0; i--) {
408             final ShortcutInfo si = mShortcuts.valueAt(i);
409 
410             if (si.isAlive()) continue;
411 
412             if (removeList == null) {
413                 removeList = new ArrayList<>();
414             }
415             removeList.add(si);
416         }
417         if (removeList != null) {
418             for (int i = removeList.size() - 1; i >= 0; i--) {
419                 forceDeleteShortcutInner(removeList.get(i).getId());
420             }
421         }
422 
423         return removeList;
424     }
425 
426     /**
427      * Remove all dynamic shortcuts.
428      *
429      * @return List of shortcuts that actually got removed.
430      */
deleteAllDynamicShortcuts(boolean ignoreInvisible)431     public List<ShortcutInfo> deleteAllDynamicShortcuts(boolean ignoreInvisible) {
432         final long now = mShortcutUser.mService.injectCurrentTimeMillis();
433 
434         boolean changed = false;
435         for (int i = mShortcuts.size() - 1; i >= 0; i--) {
436             final ShortcutInfo si = mShortcuts.valueAt(i);
437             if (si.isDynamic() && (!ignoreInvisible || si.isVisibleToPublisher())) {
438                 changed = true;
439 
440                 si.setTimestamp(now);
441                 si.clearFlags(ShortcutInfo.FLAG_DYNAMIC);
442                 si.setRank(0); // It may still be pinned, so clear the rank.
443             }
444         }
445         if (changed) {
446             return removeOrphans();
447         }
448         return null;
449     }
450 
451     /**
452      * Remove a dynamic shortcut by ID.  It'll be removed from the dynamic set, but if the shortcut
453      * is pinned or cached, it'll remain as a pinned or cached shortcut, and is still enabled.
454      *
455      * @return The deleted shortcut, or null if it was not actually removed because it is either
456      * pinned or cached.
457      */
deleteDynamicWithId(@onNull String shortcutId, boolean ignoreInvisible)458     public ShortcutInfo deleteDynamicWithId(@NonNull String shortcutId, boolean ignoreInvisible) {
459         return deleteOrDisableWithId(
460                 shortcutId, /* disable =*/ false, /* overrideImmutable=*/ false, ignoreInvisible,
461                 ShortcutInfo.DISABLED_REASON_NOT_DISABLED);
462     }
463 
464     /**
465      * Disable a dynamic shortcut by ID. It'll be removed from the dynamic set, but if the shortcut
466      * is pinned, it'll remain as a pinned shortcut, but will be disabled.
467      *
468      * @return Shortcut if the disabled shortcut got removed because it wasn't pinned. Or null if
469      * it's still pinned.
470      */
disableDynamicWithId(@onNull String shortcutId, boolean ignoreInvisible, int disabledReason)471     private ShortcutInfo disableDynamicWithId(@NonNull String shortcutId, boolean ignoreInvisible,
472             int disabledReason) {
473         return deleteOrDisableWithId(shortcutId, /* disable =*/ true, /* overrideImmutable=*/ false,
474                 ignoreInvisible, disabledReason);
475     }
476 
477     /**
478      * Remove a long lived shortcut by ID. If the shortcut is pinned, it'll remain as a pinned
479      * shortcut, and is still enabled.
480      *
481      * @return The deleted shortcut, or null if it was not actually removed because it's pinned.
482      */
deleteLongLivedWithId(@onNull String shortcutId, boolean ignoreInvisible)483     public ShortcutInfo deleteLongLivedWithId(@NonNull String shortcutId, boolean ignoreInvisible) {
484         final ShortcutInfo shortcut = mShortcuts.get(shortcutId);
485         if (shortcut != null) {
486             shortcut.clearFlags(ShortcutInfo.FLAG_CACHED_ALL);
487         }
488         return deleteOrDisableWithId(
489                 shortcutId, /* disable =*/ false, /* overrideImmutable=*/ false, ignoreInvisible,
490                 ShortcutInfo.DISABLED_REASON_NOT_DISABLED);
491     }
492 
493     /**
494      * Disable a dynamic shortcut by ID.  It'll be removed from the dynamic set, but if the shortcut
495      * is pinned, it'll remain as a pinned shortcut but will be disabled.
496      *
497      * @return Shortcut if the disabled shortcut got removed because it wasn't pinned. Or null if
498      * it's still pinned.
499      */
disableWithId(@onNull String shortcutId, String disabledMessage, int disabledMessageResId, boolean overrideImmutable, boolean ignoreInvisible, int disabledReason)500     public ShortcutInfo disableWithId(@NonNull String shortcutId, String disabledMessage,
501             int disabledMessageResId, boolean overrideImmutable, boolean ignoreInvisible,
502             int disabledReason) {
503         final ShortcutInfo deleted = deleteOrDisableWithId(shortcutId, /* disable =*/ true,
504                 overrideImmutable, ignoreInvisible, disabledReason);
505 
506         // If disabled id still exists, it is pinned and we need to update the disabled message.
507         final ShortcutInfo disabled = mShortcuts.get(shortcutId);
508         if (disabled != null) {
509             if (disabledMessage != null) {
510                 disabled.setDisabledMessage(disabledMessage);
511             } else if (disabledMessageResId != 0) {
512                 disabled.setDisabledMessageResId(disabledMessageResId);
513                 mShortcutUser.mService.fixUpShortcutResourceNamesAndValues(disabled);
514             }
515         }
516 
517         return deleted;
518     }
519 
520     @Nullable
deleteOrDisableWithId(@onNull String shortcutId, boolean disable, boolean overrideImmutable, boolean ignoreInvisible, int disabledReason)521     private ShortcutInfo deleteOrDisableWithId(@NonNull String shortcutId, boolean disable,
522             boolean overrideImmutable, boolean ignoreInvisible, int disabledReason) {
523         Preconditions.checkState(
524                 (disable == (disabledReason != ShortcutInfo.DISABLED_REASON_NOT_DISABLED)),
525                 "disable and disabledReason disagree: " + disable + " vs " + disabledReason);
526         final ShortcutInfo oldShortcut = mShortcuts.get(shortcutId);
527 
528         if (oldShortcut == null || !oldShortcut.isEnabled()
529                 && (ignoreInvisible && !oldShortcut.isVisibleToPublisher())) {
530             return null; // Doesn't exist or already disabled.
531         }
532         if (!overrideImmutable) {
533             ensureNotImmutable(oldShortcut, /*ignoreInvisible=*/ true);
534         }
535         if (oldShortcut.isPinned() || oldShortcut.isCached()) {
536 
537             oldShortcut.setRank(0);
538             oldShortcut.clearFlags(ShortcutInfo.FLAG_DYNAMIC | ShortcutInfo.FLAG_MANIFEST);
539             if (disable) {
540                 oldShortcut.addFlags(ShortcutInfo.FLAG_DISABLED);
541                 // Do not overwrite the disabled reason if one is alreay set.
542                 if (oldShortcut.getDisabledReason() == ShortcutInfo.DISABLED_REASON_NOT_DISABLED) {
543                     oldShortcut.setDisabledReason(disabledReason);
544                 }
545             }
546             oldShortcut.setTimestamp(mShortcutUser.mService.injectCurrentTimeMillis());
547 
548             // See ShortcutRequestPinProcessor.directPinShortcut().
549             if (mShortcutUser.mService.isDummyMainActivity(oldShortcut.getActivity())) {
550                 oldShortcut.setActivity(null);
551             }
552 
553             return null;
554         } else {
555             forceDeleteShortcutInner(shortcutId);
556             return oldShortcut;
557         }
558     }
559 
enableWithId(@onNull String shortcutId)560     public void enableWithId(@NonNull String shortcutId) {
561         final ShortcutInfo shortcut = mShortcuts.get(shortcutId);
562         if (shortcut != null) {
563             ensureNotImmutable(shortcut, /*ignoreInvisible=*/ true);
564             shortcut.clearFlags(ShortcutInfo.FLAG_DISABLED);
565             shortcut.setDisabledReason(ShortcutInfo.DISABLED_REASON_NOT_DISABLED);
566         }
567     }
568 
updateInvisibleShortcutForPinRequestWith(@onNull ShortcutInfo shortcut)569     public void updateInvisibleShortcutForPinRequestWith(@NonNull ShortcutInfo shortcut) {
570         final ShortcutInfo source = mShortcuts.get(shortcut.getId());
571         Objects.requireNonNull(source);
572 
573         mShortcutUser.mService.validateShortcutForPinRequest(shortcut);
574 
575         shortcut.addFlags(ShortcutInfo.FLAG_PINNED);
576 
577         forceReplaceShortcutInner(shortcut);
578 
579         adjustRanks();
580     }
581 
582     /**
583      * Called after a launcher updates the pinned set.  For each shortcut in this package,
584      * set FLAG_PINNED if any launcher has pinned it.  Otherwise, clear it.
585      *
586      * <p>Then remove all shortcuts that are not dynamic and no longer pinned either.
587      */
refreshPinnedFlags()588     public void refreshPinnedFlags() {
589         // First, un-pin all shortcuts
590         for (int i = mShortcuts.size() - 1; i >= 0; i--) {
591             mShortcuts.valueAt(i).clearFlags(ShortcutInfo.FLAG_PINNED);
592         }
593 
594         // Then, for the pinned set for each launcher, set the pin flag one by one.
595         mShortcutUser.forAllLaunchers(launcherShortcuts -> {
596             final ArraySet<String> pinned = launcherShortcuts.getPinnedShortcutIds(
597                     getPackageName(), getPackageUserId());
598 
599             if (pinned == null || pinned.size() == 0) {
600                 return;
601             }
602             for (int i = pinned.size() - 1; i >= 0; i--) {
603                 final String id = pinned.valueAt(i);
604                 final ShortcutInfo si = mShortcuts.get(id);
605                 if (si == null) {
606                     // This happens if a launcher pinned shortcuts from this package, then backup&
607                     // restored, but this package doesn't allow backing up.
608                     // In that case the launcher ends up having a dangling pinned shortcuts.
609                     // That's fine, when the launcher is restored, we'll fix it.
610                     continue;
611                 }
612                 si.addFlags(ShortcutInfo.FLAG_PINNED);
613             }
614         });
615 
616         // Lastly, remove the ones that are no longer pinned, cached nor dynamic.
617         removeOrphans();
618     }
619 
620     /**
621      * Number of calls that the caller has made, since the last reset.
622      *
623      * <p>This takes care of the resetting the counter for foreground apps as well as after
624      * locale changes.
625      */
getApiCallCount(boolean unlimited)626     public int getApiCallCount(boolean unlimited) {
627         final ShortcutService s = mShortcutUser.mService;
628 
629         // Reset the counter if:
630         // - the package is in foreground now.
631         // - the package is *not* in foreground now, but was in foreground at some point
632         // since the previous time it had been.
633         if (s.isUidForegroundLocked(mPackageUid)
634                 || (mLastKnownForegroundElapsedTime
635                     < s.getUidLastForegroundElapsedTimeLocked(mPackageUid))
636                 || unlimited) {
637             mLastKnownForegroundElapsedTime = s.injectElapsedRealtime();
638             resetRateLimiting();
639         }
640 
641         // Note resetThrottlingIfNeeded() and resetRateLimiting() will set 0 to mApiCallCount,
642         // but we just can't return 0 at this point, because we may have to update
643         // mLastResetTime.
644 
645         final long last = s.getLastResetTimeLocked();
646 
647         final long now = s.injectCurrentTimeMillis();
648         if (ShortcutService.isClockValid(now) && mLastResetTime > now) {
649             Slog.w(TAG, "Clock rewound");
650             // Clock rewound.
651             mLastResetTime = now;
652             mApiCallCount = 0;
653             return mApiCallCount;
654         }
655 
656         // If not reset yet, then reset.
657         if (mLastResetTime < last) {
658             if (ShortcutService.DEBUG) {
659                 Slog.d(TAG, String.format("%s: last reset=%d, now=%d, last=%d: resetting",
660                         getPackageName(), mLastResetTime, now, last));
661             }
662             mApiCallCount = 0;
663             mLastResetTime = last;
664         }
665         return mApiCallCount;
666     }
667 
668     /**
669      * If the caller app hasn't been throttled yet, increment {@link #mApiCallCount}
670      * and return true.  Otherwise just return false.
671      *
672      * <p>This takes care of the resetting the counter for foreground apps as well as after
673      * locale changes, which is done internally by {@link #getApiCallCount}.
674      */
tryApiCall(boolean unlimited)675     public boolean tryApiCall(boolean unlimited) {
676         final ShortcutService s = mShortcutUser.mService;
677 
678         if (getApiCallCount(unlimited) >= s.mMaxUpdatesPerInterval) {
679             return false;
680         }
681         mApiCallCount++;
682         s.scheduleSaveUser(getOwnerUserId());
683         return true;
684     }
685 
resetRateLimiting()686     public void resetRateLimiting() {
687         if (ShortcutService.DEBUG) {
688             Slog.d(TAG, "resetRateLimiting: " + getPackageName());
689         }
690         if (mApiCallCount > 0) {
691             mApiCallCount = 0;
692             mShortcutUser.mService.scheduleSaveUser(getOwnerUserId());
693         }
694     }
695 
resetRateLimitingForCommandLineNoSaving()696     public void resetRateLimitingForCommandLineNoSaving() {
697         mApiCallCount = 0;
698         mLastResetTime = 0;
699     }
700 
701     /**
702      * Find all shortcuts that match {@code query}.
703      */
findAll(@onNull List<ShortcutInfo> result, @Nullable Predicate<ShortcutInfo> query, int cloneFlag)704     public void findAll(@NonNull List<ShortcutInfo> result,
705             @Nullable Predicate<ShortcutInfo> query, int cloneFlag) {
706         findAll(result, query, cloneFlag, null, 0, /*getPinnedByAnyLauncher=*/ false);
707     }
708 
709     /**
710      * Find all shortcuts that match {@code query}.
711      *
712      * This will also provide a "view" for each launcher -- a non-dynamic shortcut that's not pinned
713      * by the calling launcher will not be included in the result, and also "isPinned" will be
714      * adjusted for the caller too.
715      */
findAll(@onNull List<ShortcutInfo> result, @Nullable Predicate<ShortcutInfo> query, int cloneFlag, @Nullable String callingLauncher, int launcherUserId, boolean getPinnedByAnyLauncher)716     public void findAll(@NonNull List<ShortcutInfo> result,
717             @Nullable Predicate<ShortcutInfo> query, int cloneFlag,
718             @Nullable String callingLauncher, int launcherUserId, boolean getPinnedByAnyLauncher) {
719         if (getPackageInfo().isShadow()) {
720             // Restored and the app not installed yet, so don't return any.
721             return;
722         }
723 
724         final ShortcutService s = mShortcutUser.mService;
725 
726         // Set of pinned shortcuts by the calling launcher.
727         final ArraySet<String> pinnedByCallerSet = (callingLauncher == null) ? null
728                 : s.getLauncherShortcutsLocked(callingLauncher, getPackageUserId(), launcherUserId)
729                     .getPinnedShortcutIds(getPackageName(), getPackageUserId());
730 
731         for (int i = 0; i < mShortcuts.size(); i++) {
732             final ShortcutInfo si = mShortcuts.valueAt(i);
733 
734             // Need to adjust PINNED flag depending on the caller.
735             // Basically if the caller is a launcher (callingLauncher != null) and the launcher
736             // isn't pinning it, then we need to clear PINNED for this caller.
737             final boolean isPinnedByCaller = (callingLauncher == null)
738                     || ((pinnedByCallerSet != null) && pinnedByCallerSet.contains(si.getId()));
739 
740             if (!getPinnedByAnyLauncher) {
741                 if (si.isFloating()) {
742                     if (!isPinnedByCaller) {
743                         continue;
744                     }
745                 }
746             }
747             final ShortcutInfo clone = si.clone(cloneFlag);
748 
749             // Fix up isPinned for the caller.  Note we need to do it before the "test" callback,
750             // since it may check isPinned.
751             // However, if getPinnedByAnyLauncher is set, we do it after the test.
752             if (!getPinnedByAnyLauncher) {
753                 if (!isPinnedByCaller) {
754                     clone.clearFlags(ShortcutInfo.FLAG_PINNED);
755                 }
756             }
757             if (query == null || query.test(clone)) {
758                 if (!isPinnedByCaller) {
759                     clone.clearFlags(ShortcutInfo.FLAG_PINNED);
760                 }
761                 result.add(clone);
762             }
763         }
764     }
765 
resetThrottling()766     public void resetThrottling() {
767         mApiCallCount = 0;
768     }
769 
770     /**
771      * Returns a list of ShortcutInfos that match the given intent filter and the category of
772      * available ShareTarget definitions in this package.
773      */
getMatchingShareTargets( @onNull IntentFilter filter)774     public List<ShortcutManager.ShareShortcutInfo> getMatchingShareTargets(
775             @NonNull IntentFilter filter) {
776         final List<ShareTargetInfo> matchedTargets = new ArrayList<>();
777         for (int i = 0; i < mShareTargets.size(); i++) {
778             final ShareTargetInfo target = mShareTargets.get(i);
779             for (ShareTargetInfo.TargetData data : target.mTargetData) {
780                 if (filter.hasDataType(data.mMimeType)) {
781                     // Matched at least with one data type
782                     matchedTargets.add(target);
783                     break;
784                 }
785             }
786         }
787 
788         if (matchedTargets.isEmpty()) {
789             return new ArrayList<>();
790         }
791 
792         // Get the list of all dynamic shortcuts in this package.
793         final ArrayList<ShortcutInfo> shortcuts = new ArrayList<>();
794         findAll(shortcuts, ShortcutInfo::isNonManifestVisible,
795                 ShortcutInfo.CLONE_REMOVE_FOR_APP_PREDICTION);
796 
797         final List<ShortcutManager.ShareShortcutInfo> result = new ArrayList<>();
798         for (int i = 0; i < shortcuts.size(); i++) {
799             final Set<String> categories = shortcuts.get(i).getCategories();
800             if (categories == null || categories.isEmpty()) {
801                 continue;
802             }
803             for (int j = 0; j < matchedTargets.size(); j++) {
804                 // Shortcut must have all of share target categories
805                 boolean hasAllCategories = true;
806                 final ShareTargetInfo target = matchedTargets.get(j);
807                 for (int q = 0; q < target.mCategories.length; q++) {
808                     if (!categories.contains(target.mCategories[q])) {
809                         hasAllCategories = false;
810                         break;
811                     }
812                 }
813                 if (hasAllCategories) {
814                     result.add(new ShortcutManager.ShareShortcutInfo(shortcuts.get(i),
815                             new ComponentName(getPackageName(), target.mTargetClass)));
816                     break;
817                 }
818             }
819         }
820         return result;
821     }
822 
hasShareTargets()823     public boolean hasShareTargets() {
824         return !mShareTargets.isEmpty();
825     }
826 
827     /**
828      * Returns the number of shortcuts that can be used as a share target in the ShareSheet. Such
829      * shortcuts must have a matching category with at least one of the defined ShareTargets from
830      * the app's Xml resource.
831      */
getSharingShortcutCount()832     int getSharingShortcutCount() {
833         if (mShortcuts.isEmpty() || mShareTargets.isEmpty()) {
834             return 0;
835         }
836 
837         // Get the list of all dynamic shortcuts in this package
838         final ArrayList<ShortcutInfo> shortcuts = new ArrayList<>();
839         findAll(shortcuts, ShortcutInfo::isNonManifestVisible,
840                 ShortcutInfo.CLONE_REMOVE_FOR_LAUNCHER);
841 
842         int sharingShortcutCount = 0;
843         for (int i = 0; i < shortcuts.size(); i++) {
844             final Set<String> categories = shortcuts.get(i).getCategories();
845             if (categories == null || categories.isEmpty()) {
846                 continue;
847             }
848             for (int j = 0; j < mShareTargets.size(); j++) {
849                 // A SharingShortcut must have all of share target categories
850                 boolean hasAllCategories = true;
851                 final ShareTargetInfo target = mShareTargets.get(j);
852                 for (int q = 0; q < target.mCategories.length; q++) {
853                     if (!categories.contains(target.mCategories[q])) {
854                         hasAllCategories = false;
855                         break;
856                     }
857                 }
858                 if (hasAllCategories) {
859                     sharingShortcutCount++;
860                     break;
861                 }
862             }
863         }
864         return sharingShortcutCount;
865     }
866 
867     /**
868      * Return the filenames (excluding path names) of icon bitmap files from this package.
869      */
getUsedBitmapFiles()870     public ArraySet<String> getUsedBitmapFiles() {
871         final ArraySet<String> usedFiles = new ArraySet<>(mShortcuts.size());
872 
873         for (int i = mShortcuts.size() - 1; i >= 0; i--) {
874             final ShortcutInfo si = mShortcuts.valueAt(i);
875             if (si.getBitmapPath() != null) {
876                 usedFiles.add(getFileName(si.getBitmapPath()));
877             }
878         }
879         return usedFiles;
880     }
881 
getFileName(@onNull String path)882     private static String getFileName(@NonNull String path) {
883         final int sep = path.lastIndexOf(File.separatorChar);
884         if (sep == -1) {
885             return path;
886         } else {
887             return path.substring(sep + 1);
888         }
889     }
890 
891     /**
892      * @return false if any of the target activities are no longer enabled.
893      */
areAllActivitiesStillEnabled()894     private boolean areAllActivitiesStillEnabled() {
895         if (mShortcuts.size() == 0) {
896             return true;
897         }
898         final ShortcutService s = mShortcutUser.mService;
899 
900         // Normally the number of target activities is 1 or so, so no need to use a complex
901         // structure like a set.
902         final ArrayList<ComponentName> checked = new ArrayList<>(4);
903 
904         for (int i = mShortcuts.size() - 1; i >= 0; i--) {
905             final ShortcutInfo si = mShortcuts.valueAt(i);
906             final ComponentName activity = si.getActivity();
907 
908             if (checked.contains(activity)) {
909                 continue; // Already checked.
910             }
911             checked.add(activity);
912 
913             if ((activity != null)
914                     && !s.injectIsActivityEnabledAndExported(activity, getOwnerUserId())) {
915                 return false;
916             }
917         }
918         return true;
919     }
920 
921     /**
922      * Called when the package may be added or updated, or its activities may be disabled, and
923      * if so, rescan the package and do the necessary stuff.
924      *
925      * Add case:
926      * - Publish manifest shortcuts.
927      *
928      * Update case:
929      * - Re-publish manifest shortcuts.
930      * - If there are shortcuts with resources (icons or strings), update their timestamps.
931      * - Disable shortcuts whose target activities are disabled.
932      *
933      * @return TRUE if any shortcuts have been changed.
934      */
rescanPackageIfNeeded(boolean isNewApp, boolean forceRescan)935     public boolean rescanPackageIfNeeded(boolean isNewApp, boolean forceRescan) {
936         final ShortcutService s = mShortcutUser.mService;
937         final long start = s.getStatStartTime();
938 
939         final PackageInfo pi;
940         try {
941             pi = mShortcutUser.mService.getPackageInfo(
942                     getPackageName(), getPackageUserId());
943             if (pi == null) {
944                 return false; // Shouldn't happen.
945             }
946 
947             if (!isNewApp && !forceRescan) {
948                 // Return if the package hasn't changed, ie:
949                 // - version code hasn't change
950                 // - lastUpdateTime hasn't change
951                 // - all target activities are still enabled.
952 
953                 // Note, system apps timestamps do *not* change after OTAs.  (But they do
954                 // after an adb sync or a local flash.)
955                 // This means if a system app's version code doesn't change on an OTA,
956                 // we don't notice it's updated.  But that's fine since their version code *should*
957                 // really change on OTAs.
958                 if ((getPackageInfo().getVersionCode() == pi.getLongVersionCode())
959                         && (getPackageInfo().getLastUpdateTime() == pi.lastUpdateTime)
960                         && areAllActivitiesStillEnabled()) {
961                     return false;
962                 }
963             }
964         } finally {
965             s.logDurationStat(Stats.PACKAGE_UPDATE_CHECK, start);
966         }
967 
968         // Now prepare to publish manifest shortcuts.
969         List<ShortcutInfo> newManifestShortcutList = null;
970         try {
971             newManifestShortcutList = ShortcutParser.parseShortcuts(mShortcutUser.mService,
972                     getPackageName(), getPackageUserId(), mShareTargets);
973         } catch (IOException|XmlPullParserException e) {
974             Slog.e(TAG, "Failed to load shortcuts from AndroidManifest.xml.", e);
975         }
976         final int manifestShortcutSize = newManifestShortcutList == null ? 0
977                 : newManifestShortcutList.size();
978         if (ShortcutService.DEBUG) {
979             Slog.d(TAG,
980                     String.format("Package %s has %d manifest shortcut(s), and %d share target(s)",
981                             getPackageName(), manifestShortcutSize, mShareTargets.size()));
982         }
983         if (isNewApp && (manifestShortcutSize == 0)) {
984             // If it's a new app, and it doesn't have manifest shortcuts, then nothing to do.
985 
986             // If it's an update, then it may already have manifest shortcuts, which need to be
987             // disabled.
988             return false;
989         }
990         if (ShortcutService.DEBUG) {
991             Slog.d(TAG, String.format("Package %s %s, version %d -> %d", getPackageName(),
992                     (isNewApp ? "added" : "updated"),
993                     getPackageInfo().getVersionCode(), pi.getLongVersionCode()));
994         }
995 
996         getPackageInfo().updateFromPackageInfo(pi);
997         final long newVersionCode = getPackageInfo().getVersionCode();
998 
999         // See if there are any shortcuts that were prevented restoring because the app was of a
1000         // lower version, and re-enable them.
1001         for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1002             final ShortcutInfo si = mShortcuts.valueAt(i);
1003             if (si.getDisabledReason() != ShortcutInfo.DISABLED_REASON_VERSION_LOWER) {
1004                 continue;
1005             }
1006             if (getPackageInfo().getBackupSourceVersionCode() > newVersionCode) {
1007                 if (ShortcutService.DEBUG) {
1008                     Slog.d(TAG, String.format("Shortcut %s require version %s, still not restored.",
1009                             si.getId(), getPackageInfo().getBackupSourceVersionCode()));
1010                 }
1011                 continue;
1012             }
1013             Slog.i(TAG, String.format("Restoring shortcut: %s", si.getId()));
1014             si.clearFlags(ShortcutInfo.FLAG_DISABLED);
1015             si.setDisabledReason(ShortcutInfo.DISABLED_REASON_NOT_DISABLED);
1016         }
1017 
1018         // For existing shortcuts, update timestamps if they have any resources.
1019         // Also check if shortcuts' activities are still main activities.  Otherwise, disable them.
1020         if (!isNewApp) {
1021             Resources publisherRes = null;
1022 
1023             for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1024                 final ShortcutInfo si = mShortcuts.valueAt(i);
1025 
1026                 // Disable dynamic shortcuts whose target activity is gone.
1027                 if (si.isDynamic()) {
1028                     if (si.getActivity() == null) {
1029                         // Note if it's dynamic, it must have a target activity, but b/36228253.
1030                         s.wtf("null activity detected.");
1031                         // TODO Maybe remove it?
1032                     } else if (!s.injectIsMainActivity(si.getActivity(), getPackageUserId())) {
1033                         Slog.w(TAG, String.format(
1034                                 "%s is no longer main activity. Disabling shorcut %s.",
1035                                 getPackageName(), si.getId()));
1036                         if (disableDynamicWithId(si.getId(), /*ignoreInvisible*/ false,
1037                                 ShortcutInfo.DISABLED_REASON_APP_CHANGED) != null) {
1038                             continue; // Actually removed.
1039                         }
1040                         // Still pinned, so fall-through and possibly update the resources.
1041                     }
1042                 }
1043 
1044                 if (si.hasAnyResources()) {
1045                     if (!si.isOriginallyFromManifest()) {
1046                         if (publisherRes == null) {
1047                             publisherRes = getPackageResources();
1048                             if (publisherRes == null) {
1049                                 break; // Resources couldn't be loaded.
1050                             }
1051                         }
1052 
1053                         // If this shortcut is not from a manifest, then update all resource IDs
1054                         // from resource names.  (We don't allow resource strings for
1055                         // non-manifest at the moment, but icons can still be resources.)
1056                         si.lookupAndFillInResourceIds(publisherRes);
1057                     }
1058                     si.setTimestamp(s.injectCurrentTimeMillis());
1059                 }
1060             }
1061         }
1062 
1063         // (Re-)publish manifest shortcut.
1064         publishManifestShortcuts(newManifestShortcutList);
1065 
1066         if (newManifestShortcutList != null) {
1067             pushOutExcessShortcuts();
1068         }
1069 
1070         s.verifyStates();
1071 
1072         // This will send a notification to the launcher, and also save .
1073         // TODO: List changed and removed manifest shortcuts and pass to packageShortcutsChanged()
1074         s.packageShortcutsChanged(getPackageName(), getPackageUserId(), null, null);
1075         return true; // true means changed.
1076     }
1077 
publishManifestShortcuts(List<ShortcutInfo> newManifestShortcutList)1078     private boolean publishManifestShortcuts(List<ShortcutInfo> newManifestShortcutList) {
1079         if (ShortcutService.DEBUG) {
1080             Slog.d(TAG, String.format(
1081                     "Package %s: publishing manifest shortcuts", getPackageName()));
1082         }
1083         boolean changed = false;
1084 
1085         // Keep the previous IDs.
1086         ArraySet<String> toDisableList = null;
1087         for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1088             final ShortcutInfo si = mShortcuts.valueAt(i);
1089 
1090             if (si.isManifestShortcut()) {
1091                 if (toDisableList == null) {
1092                     toDisableList = new ArraySet<>();
1093                 }
1094                 toDisableList.add(si.getId());
1095             }
1096         }
1097 
1098         // Publish new ones.
1099         if (newManifestShortcutList != null) {
1100             final int newListSize = newManifestShortcutList.size();
1101 
1102             for (int i = 0; i < newListSize; i++) {
1103                 changed = true;
1104 
1105                 final ShortcutInfo newShortcut = newManifestShortcutList.get(i);
1106                 final boolean newDisabled = !newShortcut.isEnabled();
1107 
1108                 final String id = newShortcut.getId();
1109                 final ShortcutInfo oldShortcut = mShortcuts.get(id);
1110 
1111                 boolean wasPinned = false;
1112 
1113                 if (oldShortcut != null) {
1114                     if (!oldShortcut.isOriginallyFromManifest()) {
1115                         Slog.e(TAG, "Shortcut with ID=" + newShortcut.getId()
1116                                 + " exists but is not from AndroidManifest.xml, not updating.");
1117                         continue;
1118                     }
1119                     // Take over the pinned flag.
1120                     if (oldShortcut.isPinned()) {
1121                         wasPinned = true;
1122                         newShortcut.addFlags(ShortcutInfo.FLAG_PINNED);
1123                     }
1124                 }
1125                 if (newDisabled && !wasPinned) {
1126                     // If the shortcut is disabled, and it was *not* pinned, then this
1127                     // just doesn't have to be published.
1128                     // Just keep it in toDisableList, so the previous one would be removed.
1129                     continue;
1130                 }
1131 
1132                 // Note even if enabled=false, we still need to update all fields, so do it
1133                 // regardless.
1134                 forceReplaceShortcutInner(newShortcut); // This will clean up the old one too.
1135 
1136                 if (!newDisabled && toDisableList != null) {
1137                     // Still alive, don't remove.
1138                     toDisableList.remove(id);
1139                 }
1140             }
1141         }
1142 
1143         // Disable the previous manifest shortcuts that are no longer in the manifest.
1144         if (toDisableList != null) {
1145             if (ShortcutService.DEBUG) {
1146                 Slog.d(TAG, String.format(
1147                         "Package %s: disabling %d stale shortcuts", getPackageName(),
1148                         toDisableList.size()));
1149             }
1150             for (int i = toDisableList.size() - 1; i >= 0; i--) {
1151                 changed = true;
1152 
1153                 final String id = toDisableList.valueAt(i);
1154 
1155                 disableWithId(id, /* disable message =*/ null, /* disable message resid */ 0,
1156                         /* overrideImmutable=*/ true, /*ignoreInvisible=*/ false,
1157                         ShortcutInfo.DISABLED_REASON_APP_CHANGED);
1158             }
1159             removeOrphans();
1160         }
1161         adjustRanks();
1162         return changed;
1163     }
1164 
1165     /**
1166      * For each target activity, make sure # of dynamic + manifest shortcuts <= max.
1167      * If too many, we'll remove the dynamic with the lowest ranks.
1168      */
pushOutExcessShortcuts()1169     private boolean pushOutExcessShortcuts() {
1170         final ShortcutService service = mShortcutUser.mService;
1171         final int maxShortcuts = service.getMaxActivityShortcuts();
1172 
1173         boolean changed = false;
1174 
1175         final ArrayMap<ComponentName, ArrayList<ShortcutInfo>> all =
1176                 sortShortcutsToActivities();
1177         for (int outer = all.size() - 1; outer >= 0; outer--) {
1178             final ArrayList<ShortcutInfo> list = all.valueAt(outer);
1179             if (list.size() <= maxShortcuts) {
1180                 continue;
1181             }
1182             // Sort by isManifestShortcut() and getRank().
1183             Collections.sort(list, mShortcutTypeAndRankComparator);
1184 
1185             // Keep [0 .. max), and remove (as dynamic) [max .. size)
1186             for (int inner = list.size() - 1; inner >= maxShortcuts; inner--) {
1187                 final ShortcutInfo shortcut = list.get(inner);
1188 
1189                 if (shortcut.isManifestShortcut()) {
1190                     // This shouldn't happen -- excess shortcuts should all be non-manifest.
1191                     // But just in case.
1192                     service.wtf("Found manifest shortcuts in excess list.");
1193                     continue;
1194                 }
1195                 deleteDynamicWithId(shortcut.getId(), /*ignoreInvisible=*/ true);
1196             }
1197         }
1198 
1199         return changed;
1200     }
1201 
1202     /**
1203      * To sort by isManifestShortcut() and getRank(). i.e.  manifest shortcuts come before
1204      * non-manifest shortcuts, then sort by rank.
1205      *
1206      * This is used to decide which dynamic shortcuts to remove when an upgraded version has more
1207      * manifest shortcuts than before and as a result we need to remove some of the dynamic
1208      * shortcuts.  We sort manifest + dynamic shortcuts by this order, and remove the ones with
1209      * the last ones.
1210      *
1211      * (Note the number of manifest shortcuts is always <= the max number, because if there are
1212      * more, ShortcutParser would ignore the rest.)
1213      */
1214     final Comparator<ShortcutInfo> mShortcutTypeAndRankComparator = (ShortcutInfo a,
1215             ShortcutInfo b) -> {
1216         if (a.isManifestShortcut() && !b.isManifestShortcut()) {
1217             return -1;
1218         }
1219         if (!a.isManifestShortcut() && b.isManifestShortcut()) {
1220             return 1;
1221         }
1222         return Integer.compare(a.getRank(), b.getRank());
1223     };
1224 
1225     /**
1226      * Build a list of shortcuts for each target activity and return as a map. The result won't
1227      * contain "floating" shortcuts because they don't belong on any activities.
1228      */
sortShortcutsToActivities()1229     private ArrayMap<ComponentName, ArrayList<ShortcutInfo>> sortShortcutsToActivities() {
1230         final ArrayMap<ComponentName, ArrayList<ShortcutInfo>> activitiesToShortcuts
1231                 = new ArrayMap<>();
1232         for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1233             final ShortcutInfo si = mShortcuts.valueAt(i);
1234             if (si.isFloating()) {
1235                 continue; // Ignore floating shortcuts, which are not tied to any activities.
1236             }
1237 
1238             final ComponentName activity = si.getActivity();
1239             if (activity == null) {
1240                 mShortcutUser.mService.wtf("null activity detected.");
1241                 continue;
1242             }
1243 
1244             ArrayList<ShortcutInfo> list = activitiesToShortcuts.get(activity);
1245             if (list == null) {
1246                 list = new ArrayList<>();
1247                 activitiesToShortcuts.put(activity, list);
1248             }
1249             list.add(si);
1250         }
1251         return activitiesToShortcuts;
1252     }
1253 
1254     /** Used by {@link #enforceShortcutCountsBeforeOperation} */
incrementCountForActivity(ArrayMap<ComponentName, Integer> counts, ComponentName cn, int increment)1255     private void incrementCountForActivity(ArrayMap<ComponentName, Integer> counts,
1256             ComponentName cn, int increment) {
1257         Integer oldValue = counts.get(cn);
1258         if (oldValue == null) {
1259             oldValue = 0;
1260         }
1261 
1262         counts.put(cn, oldValue + increment);
1263     }
1264 
1265     /**
1266      * Called by
1267      * {@link android.content.pm.ShortcutManager#setDynamicShortcuts},
1268      * {@link android.content.pm.ShortcutManager#addDynamicShortcuts}, and
1269      * {@link android.content.pm.ShortcutManager#updateShortcuts} before actually performing
1270      * the operation to make sure the operation wouldn't result in the target activities having
1271      * more than the allowed number of dynamic/manifest shortcuts.
1272      *
1273      * @param newList shortcut list passed to set, add or updateShortcuts().
1274      * @param operation add, set or update.
1275      * @throws IllegalArgumentException if the operation would result in going over the max
1276      *                                  shortcut count for any activity.
1277      */
enforceShortcutCountsBeforeOperation(List<ShortcutInfo> newList, @ShortcutOperation int operation)1278     public void enforceShortcutCountsBeforeOperation(List<ShortcutInfo> newList,
1279             @ShortcutOperation int operation) {
1280         final ShortcutService service = mShortcutUser.mService;
1281 
1282         // Current # of dynamic / manifest shortcuts for each activity.
1283         // (If it's for update, then don't count dynamic shortcuts, since they'll be replaced
1284         // anyway.)
1285         final ArrayMap<ComponentName, Integer> counts = new ArrayMap<>(4);
1286         for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1287             final ShortcutInfo shortcut = mShortcuts.valueAt(i);
1288 
1289             if (shortcut.isManifestShortcut()) {
1290                 incrementCountForActivity(counts, shortcut.getActivity(), 1);
1291             } else if (shortcut.isDynamic() && (operation != ShortcutService.OPERATION_SET)) {
1292                 incrementCountForActivity(counts, shortcut.getActivity(), 1);
1293             }
1294         }
1295 
1296         for (int i = newList.size() - 1; i >= 0; i--) {
1297             final ShortcutInfo newShortcut = newList.get(i);
1298             final ComponentName newActivity = newShortcut.getActivity();
1299             if (newActivity == null) {
1300                 if (operation != ShortcutService.OPERATION_UPDATE) {
1301                     service.wtf("Activity must not be null at this point");
1302                     continue; // Just ignore this invalid case.
1303                 }
1304                 continue; // Activity can be null for update.
1305             }
1306 
1307             final ShortcutInfo original = mShortcuts.get(newShortcut.getId());
1308             if (original == null) {
1309                 if (operation == ShortcutService.OPERATION_UPDATE) {
1310                     continue; // When updating, ignore if there's no target.
1311                 }
1312                 // Add() or set(), and there's no existing shortcut with the same ID.  We're
1313                 // simply publishing (as opposed to updating) this shortcut, so just +1.
1314                 incrementCountForActivity(counts, newActivity, 1);
1315                 continue;
1316             }
1317             if (original.isFloating() && (operation == ShortcutService.OPERATION_UPDATE)) {
1318                 // Updating floating shortcuts doesn't affect the count, so ignore.
1319                 continue;
1320             }
1321 
1322             // If it's add() or update(), then need to decrement for the previous activity.
1323             // Skip it for set() since it's already been taken care of by not counting the original
1324             // dynamic shortcuts in the first loop.
1325             if (operation != ShortcutService.OPERATION_SET) {
1326                 final ComponentName oldActivity = original.getActivity();
1327                 if (!original.isFloating()) {
1328                     incrementCountForActivity(counts, oldActivity, -1);
1329                 }
1330             }
1331             incrementCountForActivity(counts, newActivity, 1);
1332         }
1333 
1334         // Then make sure none of the activities have more than the max number of shortcuts.
1335         for (int i = counts.size() - 1; i >= 0; i--) {
1336             service.enforceMaxActivityShortcuts(counts.valueAt(i));
1337         }
1338     }
1339 
1340     /**
1341      * For all the text fields, refresh the string values if they're from resources.
1342      */
resolveResourceStrings()1343     public void resolveResourceStrings() {
1344         final ShortcutService s = mShortcutUser.mService;
1345 
1346         List<ShortcutInfo> changedShortcuts = null;
1347 
1348         Resources publisherRes = null;
1349         for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1350             final ShortcutInfo si = mShortcuts.valueAt(i);
1351 
1352             if (si.hasStringResources()) {
1353                 if (publisherRes == null) {
1354                     publisherRes = getPackageResources();
1355                     if (publisherRes == null) {
1356                         break; // Resources couldn't be loaded.
1357                     }
1358                 }
1359 
1360                 si.resolveResourceStrings(publisherRes);
1361                 si.setTimestamp(s.injectCurrentTimeMillis());
1362 
1363                 if (changedShortcuts == null) {
1364                     changedShortcuts = new ArrayList<>(1);
1365                 }
1366                 changedShortcuts.add(si);
1367             }
1368         }
1369         if (!CollectionUtils.isEmpty(changedShortcuts)) {
1370             s.packageShortcutsChanged(getPackageName(), getPackageUserId(), changedShortcuts, null);
1371         }
1372     }
1373 
1374     /** Clears the implicit ranks for all shortcuts. */
clearAllImplicitRanks()1375     public void clearAllImplicitRanks() {
1376         for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1377             final ShortcutInfo si = mShortcuts.valueAt(i);
1378             si.clearImplicitRankAndRankChangedFlag();
1379         }
1380     }
1381 
1382     /**
1383      * Used to sort shortcuts for rank auto-adjusting.
1384      */
1385     final Comparator<ShortcutInfo> mShortcutRankComparator = (ShortcutInfo a, ShortcutInfo b) -> {
1386         // First, sort by rank.
1387         int ret = Integer.compare(a.getRank(), b.getRank());
1388         if (ret != 0) {
1389             return ret;
1390         }
1391         // When ranks are tie, then prioritize the ones that have just been assigned new ranks.
1392         // e.g. when there are 3 shortcuts, "s1" "s2" and "s3" with rank 0, 1, 2 respectively,
1393         // adding a shortcut "s4" with rank 1 will "insert" it between "s1" and "s2", because
1394         // "s2" and "s4" have the same rank 1 but s4 has isRankChanged() set.
1395         // Similarly, updating s3's rank to 1 will insert it between s1 and s2.
1396         if (a.isRankChanged() != b.isRankChanged()) {
1397             return a.isRankChanged() ? -1 : 1;
1398         }
1399         // If they're still tie, sort by implicit rank -- i.e. preserve the order in which
1400         // they're passed to the API.
1401         ret = Integer.compare(a.getImplicitRank(), b.getImplicitRank());
1402         if (ret != 0) {
1403             return ret;
1404         }
1405         // If they're still tie, just sort by their IDs.
1406         // This may happen with updateShortcuts() -- see
1407         // the testUpdateShortcuts_noManifestShortcuts() test.
1408         return a.getId().compareTo(b.getId());
1409     };
1410 
1411     /**
1412      * Re-calculate the ranks for all shortcuts.
1413      */
adjustRanks()1414     public void adjustRanks() {
1415         final ShortcutService s = mShortcutUser.mService;
1416         final long now = s.injectCurrentTimeMillis();
1417 
1418         // First, clear ranks for floating shortcuts.
1419         for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1420             final ShortcutInfo si = mShortcuts.valueAt(i);
1421             if (si.isFloating()) {
1422                 if (si.getRank() != 0) {
1423                     si.setTimestamp(now);
1424                     si.setRank(0);
1425                 }
1426             }
1427         }
1428 
1429         // Then adjust ranks.  Ranks are unique for each activity, so we first need to sort
1430         // shortcuts to each activity.
1431         // Then sort the shortcuts within each activity with mShortcutRankComparator, and
1432         // assign ranks from 0.
1433         final ArrayMap<ComponentName, ArrayList<ShortcutInfo>> all =
1434                 sortShortcutsToActivities();
1435         for (int outer = all.size() - 1; outer >= 0; outer--) { // For each activity.
1436             final ArrayList<ShortcutInfo> list = all.valueAt(outer);
1437 
1438             // Sort by ranks and other signals.
1439             Collections.sort(list, mShortcutRankComparator);
1440 
1441             int rank = 0;
1442 
1443             final int size = list.size();
1444             for (int i = 0; i < size; i++) {
1445                 final ShortcutInfo si = list.get(i);
1446                 if (si.isManifestShortcut()) {
1447                     // Don't adjust ranks for manifest shortcuts.
1448                     continue;
1449                 }
1450                 // At this point, it must be dynamic.
1451                 if (!si.isDynamic()) {
1452                     s.wtf("Non-dynamic shortcut found.");
1453                     continue;
1454                 }
1455                 final int thisRank = rank++;
1456                 if (si.getRank() != thisRank) {
1457                     si.setTimestamp(now);
1458                     si.setRank(thisRank);
1459                 }
1460             }
1461         }
1462     }
1463 
1464     /** @return true if there's any shortcuts that are not manifest shortcuts. */
hasNonManifestShortcuts()1465     public boolean hasNonManifestShortcuts() {
1466         for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1467             final ShortcutInfo si = mShortcuts.valueAt(i);
1468             if (!si.isDeclaredInManifest()) {
1469                 return true;
1470             }
1471         }
1472         return false;
1473     }
1474 
dump(@onNull PrintWriter pw, @NonNull String prefix, DumpFilter filter)1475     public void dump(@NonNull PrintWriter pw, @NonNull String prefix, DumpFilter filter) {
1476         pw.println();
1477 
1478         pw.print(prefix);
1479         pw.print("Package: ");
1480         pw.print(getPackageName());
1481         pw.print("  UID: ");
1482         pw.print(mPackageUid);
1483         pw.println();
1484 
1485         pw.print(prefix);
1486         pw.print("  ");
1487         pw.print("Calls: ");
1488         pw.print(getApiCallCount(/*unlimited=*/ false));
1489         pw.println();
1490 
1491         // getApiCallCount() may have updated mLastKnownForegroundElapsedTime.
1492         pw.print(prefix);
1493         pw.print("  ");
1494         pw.print("Last known FG: ");
1495         pw.print(mLastKnownForegroundElapsedTime);
1496         pw.println();
1497 
1498         // This should be after getApiCallCount(), which may update it.
1499         pw.print(prefix);
1500         pw.print("  ");
1501         pw.print("Last reset: [");
1502         pw.print(mLastResetTime);
1503         pw.print("] ");
1504         pw.print(ShortcutService.formatTime(mLastResetTime));
1505         pw.println();
1506 
1507         getPackageInfo().dump(pw, prefix + "  ");
1508         pw.println();
1509 
1510         pw.print(prefix);
1511         pw.println("  Shortcuts:");
1512         long totalBitmapSize = 0;
1513         final ArrayMap<String, ShortcutInfo> shortcuts = mShortcuts;
1514         final int size = shortcuts.size();
1515         for (int i = 0; i < size; i++) {
1516             final ShortcutInfo si = shortcuts.valueAt(i);
1517             pw.println(si.toDumpString(prefix + "    "));
1518             if (si.getBitmapPath() != null) {
1519                 final long len = new File(si.getBitmapPath()).length();
1520                 pw.print(prefix);
1521                 pw.print("      ");
1522                 pw.print("bitmap size=");
1523                 pw.println(len);
1524 
1525                 totalBitmapSize += len;
1526             }
1527         }
1528         pw.print(prefix);
1529         pw.print("  ");
1530         pw.print("Total bitmap size: ");
1531         pw.print(totalBitmapSize);
1532         pw.print(" (");
1533         pw.print(Formatter.formatFileSize(mShortcutUser.mService.mContext, totalBitmapSize));
1534         pw.println(")");
1535     }
1536 
1537     @Override
dumpCheckin(boolean clear)1538     public JSONObject dumpCheckin(boolean clear) throws JSONException {
1539         final JSONObject result = super.dumpCheckin(clear);
1540 
1541         int numDynamic = 0;
1542         int numPinned = 0;
1543         int numManifest = 0;
1544         int numBitmaps = 0;
1545         long totalBitmapSize = 0;
1546 
1547         final ArrayMap<String, ShortcutInfo> shortcuts = mShortcuts;
1548         final int size = shortcuts.size();
1549         for (int i = 0; i < size; i++) {
1550             final ShortcutInfo si = shortcuts.valueAt(i);
1551 
1552             if (si.isDynamic()) numDynamic++;
1553             if (si.isDeclaredInManifest()) numManifest++;
1554             if (si.isPinned()) numPinned++;
1555 
1556             if (si.getBitmapPath() != null) {
1557                 numBitmaps++;
1558                 totalBitmapSize += new File(si.getBitmapPath()).length();
1559             }
1560         }
1561 
1562         result.put(KEY_DYNAMIC, numDynamic);
1563         result.put(KEY_MANIFEST, numManifest);
1564         result.put(KEY_PINNED, numPinned);
1565         result.put(KEY_BITMAPS, numBitmaps);
1566         result.put(KEY_BITMAP_BYTES, totalBitmapSize);
1567 
1568         // TODO Log update frequency too.
1569 
1570         return result;
1571     }
1572 
1573     @Override
saveToXml(@onNull XmlSerializer out, boolean forBackup)1574     public void saveToXml(@NonNull XmlSerializer out, boolean forBackup)
1575             throws IOException, XmlPullParserException {
1576         final int size = mShortcuts.size();
1577         final int shareTargetSize = mShareTargets.size();
1578 
1579         if (size == 0 && shareTargetSize == 0 && mApiCallCount == 0) {
1580             return; // nothing to write.
1581         }
1582 
1583         out.startTag(null, TAG_ROOT);
1584 
1585         ShortcutService.writeAttr(out, ATTR_NAME, getPackageName());
1586         ShortcutService.writeAttr(out, ATTR_CALL_COUNT, mApiCallCount);
1587         ShortcutService.writeAttr(out, ATTR_LAST_RESET, mLastResetTime);
1588         getPackageInfo().saveToXml(mShortcutUser.mService, out, forBackup);
1589 
1590         for (int j = 0; j < size; j++) {
1591             saveShortcut(out, mShortcuts.valueAt(j), forBackup,
1592                     getPackageInfo().isBackupAllowed());
1593         }
1594 
1595         if (!forBackup) {
1596             for (int j = 0; j < shareTargetSize; j++) {
1597                 mShareTargets.get(j).saveToXml(out);
1598             }
1599         }
1600 
1601         out.endTag(null, TAG_ROOT);
1602     }
1603 
saveShortcut(XmlSerializer out, ShortcutInfo si, boolean forBackup, boolean appSupportsBackup)1604     private void saveShortcut(XmlSerializer out, ShortcutInfo si, boolean forBackup,
1605             boolean appSupportsBackup)
1606             throws IOException, XmlPullParserException {
1607 
1608         final ShortcutService s = mShortcutUser.mService;
1609 
1610         if (forBackup) {
1611             if (!(si.isPinned() && si.isEnabled())) {
1612                 // We only backup pinned shortcuts that are enabled.
1613                 // Note, this means, shortcuts that are restored but are blocked restore, e.g. due
1614                 // to a lower version code, will not be ported to a new device.
1615                 return;
1616             }
1617         }
1618         final boolean shouldBackupDetails =
1619                 !forBackup // It's not backup
1620                 || appSupportsBackup; // Or, it's a backup and app supports backup.
1621 
1622         // Note: at this point no shortcuts should have bitmaps pending save, but if they do,
1623         // just remove the bitmap.
1624         if (si.isIconPendingSave()) {
1625             s.removeIconLocked(si);
1626         }
1627         out.startTag(null, TAG_SHORTCUT);
1628         ShortcutService.writeAttr(out, ATTR_ID, si.getId());
1629         // writeAttr(out, "package", si.getPackageName()); // not needed
1630         ShortcutService.writeAttr(out, ATTR_ACTIVITY, si.getActivity());
1631         // writeAttr(out, "icon", si.getIcon());  // We don't save it.
1632         ShortcutService.writeAttr(out, ATTR_TITLE, si.getTitle());
1633         ShortcutService.writeAttr(out, ATTR_TITLE_RES_ID, si.getTitleResId());
1634         ShortcutService.writeAttr(out, ATTR_TITLE_RES_NAME, si.getTitleResName());
1635         ShortcutService.writeAttr(out, ATTR_TEXT, si.getText());
1636         ShortcutService.writeAttr(out, ATTR_TEXT_RES_ID, si.getTextResId());
1637         ShortcutService.writeAttr(out, ATTR_TEXT_RES_NAME, si.getTextResName());
1638         if (shouldBackupDetails) {
1639             ShortcutService.writeAttr(out, ATTR_DISABLED_MESSAGE, si.getDisabledMessage());
1640             ShortcutService.writeAttr(out, ATTR_DISABLED_MESSAGE_RES_ID,
1641                     si.getDisabledMessageResourceId());
1642             ShortcutService.writeAttr(out, ATTR_DISABLED_MESSAGE_RES_NAME,
1643                     si.getDisabledMessageResName());
1644         }
1645         ShortcutService.writeAttr(out, ATTR_DISABLED_REASON, si.getDisabledReason());
1646         ShortcutService.writeAttr(out, ATTR_TIMESTAMP,
1647                 si.getLastChangedTimestamp());
1648         final LocusId locusId = si.getLocusId();
1649         if (locusId != null) {
1650             ShortcutService.writeAttr(out, ATTR_LOCUS_ID, si.getLocusId().getId());
1651         }
1652         if (forBackup) {
1653             // Don't write icon information.  Also drop the dynamic flag.
1654 
1655             int flags = si.getFlags() &
1656                     ~(ShortcutInfo.FLAG_HAS_ICON_FILE | ShortcutInfo.FLAG_HAS_ICON_RES
1657                             | ShortcutInfo.FLAG_ICON_FILE_PENDING_SAVE
1658                             | ShortcutInfo.FLAG_DYNAMIC
1659                             | ShortcutInfo.FLAG_HAS_ICON_URI | ShortcutInfo.FLAG_ADAPTIVE_BITMAP);
1660             ShortcutService.writeAttr(out, ATTR_FLAGS, flags);
1661 
1662             // Set the publisher version code at every backup.
1663             final long packageVersionCode = getPackageInfo().getVersionCode();
1664             if (packageVersionCode == 0) {
1665                 s.wtf("Package version code should be available at this point.");
1666                 // However, 0 is a valid version code, so we just go ahead with it...
1667             }
1668         } else {
1669             // When writing for backup, ranks shouldn't be saved, since shortcuts won't be restored
1670             // as dynamic.
1671             ShortcutService.writeAttr(out, ATTR_RANK, si.getRank());
1672 
1673             ShortcutService.writeAttr(out, ATTR_FLAGS, si.getFlags());
1674             ShortcutService.writeAttr(out, ATTR_ICON_RES_ID, si.getIconResourceId());
1675             ShortcutService.writeAttr(out, ATTR_ICON_RES_NAME, si.getIconResName());
1676             ShortcutService.writeAttr(out, ATTR_BITMAP_PATH, si.getBitmapPath());
1677             ShortcutService.writeAttr(out, ATTR_ICON_URI, si.getIconUri());
1678         }
1679 
1680         if (shouldBackupDetails) {
1681             {
1682                 final Set<String> cat = si.getCategories();
1683                 if (cat != null && cat.size() > 0) {
1684                     out.startTag(null, TAG_CATEGORIES);
1685                     XmlUtils.writeStringArrayXml(cat.toArray(new String[cat.size()]),
1686                             NAME_CATEGORIES, out);
1687                     out.endTag(null, TAG_CATEGORIES);
1688                 }
1689             }
1690             if (!forBackup) {  // Don't backup the persons field.
1691                 final Person[] persons = si.getPersons();
1692                 if (!ArrayUtils.isEmpty(persons)) {
1693                     for (int i = 0; i < persons.length; i++) {
1694                         final Person p = persons[i];
1695 
1696                         out.startTag(null, TAG_PERSON);
1697                         ShortcutService.writeAttr(out, ATTR_PERSON_NAME, p.getName());
1698                         ShortcutService.writeAttr(out, ATTR_PERSON_URI, p.getUri());
1699                         ShortcutService.writeAttr(out, ATTR_PERSON_KEY, p.getKey());
1700                         ShortcutService.writeAttr(out, ATTR_PERSON_IS_BOT, p.isBot());
1701                         ShortcutService.writeAttr(out, ATTR_PERSON_IS_IMPORTANT, p.isImportant());
1702                         out.endTag(null, TAG_PERSON);
1703                     }
1704                 }
1705             }
1706             final Intent[] intentsNoExtras = si.getIntentsNoExtras();
1707             final PersistableBundle[] intentsExtras = si.getIntentPersistableExtrases();
1708             final int numIntents = intentsNoExtras.length;
1709             for (int i = 0; i < numIntents; i++) {
1710                 out.startTag(null, TAG_INTENT);
1711                 ShortcutService.writeAttr(out, ATTR_INTENT_NO_EXTRA, intentsNoExtras[i]);
1712                 ShortcutService.writeTagExtra(out, TAG_EXTRAS, intentsExtras[i]);
1713                 out.endTag(null, TAG_INTENT);
1714             }
1715 
1716             ShortcutService.writeTagExtra(out, TAG_EXTRAS, si.getExtras());
1717         }
1718 
1719         out.endTag(null, TAG_SHORTCUT);
1720     }
1721 
loadFromFile(ShortcutService s, ShortcutUser shortcutUser, File path, boolean fromBackup)1722     public static ShortcutPackage loadFromFile(ShortcutService s, ShortcutUser shortcutUser,
1723             File path, boolean fromBackup) {
1724 
1725         final AtomicFile file = new AtomicFile(path);
1726         final FileInputStream in;
1727         try {
1728             in = file.openRead();
1729         } catch (FileNotFoundException e) {
1730             if (ShortcutService.DEBUG) {
1731                 Slog.d(TAG, "Not found " + path);
1732             }
1733             return null;
1734         }
1735 
1736         try {
1737             final BufferedInputStream bis = new BufferedInputStream(in);
1738 
1739             ShortcutPackage ret = null;
1740             XmlPullParser parser = Xml.newPullParser();
1741             parser.setInput(bis, StandardCharsets.UTF_8.name());
1742 
1743             int type;
1744             while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1745                 if (type != XmlPullParser.START_TAG) {
1746                     continue;
1747                 }
1748                 final int depth = parser.getDepth();
1749 
1750                 final String tag = parser.getName();
1751                 if (ShortcutService.DEBUG_LOAD) {
1752                     Slog.d(TAG, String.format("depth=%d type=%d name=%s", depth, type, tag));
1753                 }
1754                 if ((depth == 1) && TAG_ROOT.equals(tag)) {
1755                     ret = loadFromXml(s, shortcutUser, parser, fromBackup);
1756                     continue;
1757                 }
1758                 ShortcutService.throwForInvalidTag(depth, tag);
1759             }
1760             return ret;
1761         } catch (IOException | XmlPullParserException e) {
1762             Slog.e(TAG, "Failed to read file " + file.getBaseFile(), e);
1763             return null;
1764         } finally {
1765             IoUtils.closeQuietly(in);
1766         }
1767     }
1768 
loadFromXml(ShortcutService s, ShortcutUser shortcutUser, XmlPullParser parser, boolean fromBackup)1769     public static ShortcutPackage loadFromXml(ShortcutService s, ShortcutUser shortcutUser,
1770             XmlPullParser parser, boolean fromBackup)
1771             throws IOException, XmlPullParserException {
1772 
1773         final String packageName = ShortcutService.parseStringAttribute(parser,
1774                 ATTR_NAME);
1775 
1776         final ShortcutPackage ret = new ShortcutPackage(shortcutUser,
1777                 shortcutUser.getUserId(), packageName);
1778 
1779         ret.mApiCallCount =
1780                 ShortcutService.parseIntAttribute(parser, ATTR_CALL_COUNT);
1781         ret.mLastResetTime =
1782                 ShortcutService.parseLongAttribute(parser, ATTR_LAST_RESET);
1783 
1784 
1785         final int outerDepth = parser.getDepth();
1786         int type;
1787         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1788                 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1789             if (type != XmlPullParser.START_TAG) {
1790                 continue;
1791             }
1792             final int depth = parser.getDepth();
1793             final String tag = parser.getName();
1794             if (depth == outerDepth + 1) {
1795                 switch (tag) {
1796                     case ShortcutPackageInfo.TAG_ROOT:
1797                         ret.getPackageInfo().loadFromXml(parser, fromBackup);
1798 
1799                         continue;
1800                     case TAG_SHORTCUT:
1801                         final ShortcutInfo si = parseShortcut(parser, packageName,
1802                                 shortcutUser.getUserId(), fromBackup);
1803 
1804                         // Don't use addShortcut(), we don't need to save the icon.
1805                         ret.mShortcuts.put(si.getId(), si);
1806                         continue;
1807                     case TAG_SHARE_TARGET:
1808                         ret.mShareTargets.add(ShareTargetInfo.loadFromXml(parser));
1809                         continue;
1810                 }
1811             }
1812             ShortcutService.warnForInvalidTag(depth, tag);
1813         }
1814         return ret;
1815     }
1816 
parseShortcut(XmlPullParser parser, String packageName, @UserIdInt int userId, boolean fromBackup)1817     private static ShortcutInfo parseShortcut(XmlPullParser parser, String packageName,
1818             @UserIdInt int userId, boolean fromBackup)
1819             throws IOException, XmlPullParserException {
1820         String id;
1821         ComponentName activityComponent;
1822         // Icon icon;
1823         String title;
1824         int titleResId;
1825         String titleResName;
1826         String text;
1827         int textResId;
1828         String textResName;
1829         String disabledMessage;
1830         int disabledMessageResId;
1831         String disabledMessageResName;
1832         int disabledReason;
1833         Intent intentLegacy;
1834         PersistableBundle intentPersistableExtrasLegacy = null;
1835         ArrayList<Intent> intents = new ArrayList<>();
1836         int rank;
1837         PersistableBundle extras = null;
1838         long lastChangedTimestamp;
1839         int flags;
1840         int iconResId;
1841         String iconResName;
1842         String bitmapPath;
1843         String iconUri;
1844         final String locusIdString;
1845         int backupVersionCode;
1846         ArraySet<String> categories = null;
1847         ArrayList<Person> persons = new ArrayList<>();
1848 
1849         id = ShortcutService.parseStringAttribute(parser, ATTR_ID);
1850         activityComponent = ShortcutService.parseComponentNameAttribute(parser,
1851                 ATTR_ACTIVITY);
1852         title = ShortcutService.parseStringAttribute(parser, ATTR_TITLE);
1853         titleResId = ShortcutService.parseIntAttribute(parser, ATTR_TITLE_RES_ID);
1854         titleResName = ShortcutService.parseStringAttribute(parser, ATTR_TITLE_RES_NAME);
1855         text = ShortcutService.parseStringAttribute(parser, ATTR_TEXT);
1856         textResId = ShortcutService.parseIntAttribute(parser, ATTR_TEXT_RES_ID);
1857         textResName = ShortcutService.parseStringAttribute(parser, ATTR_TEXT_RES_NAME);
1858         disabledMessage = ShortcutService.parseStringAttribute(parser, ATTR_DISABLED_MESSAGE);
1859         disabledMessageResId = ShortcutService.parseIntAttribute(parser,
1860                 ATTR_DISABLED_MESSAGE_RES_ID);
1861         disabledMessageResName = ShortcutService.parseStringAttribute(parser,
1862                 ATTR_DISABLED_MESSAGE_RES_NAME);
1863         disabledReason = ShortcutService.parseIntAttribute(parser, ATTR_DISABLED_REASON);
1864         intentLegacy = ShortcutService.parseIntentAttributeNoDefault(parser, ATTR_INTENT_LEGACY);
1865         rank = (int) ShortcutService.parseLongAttribute(parser, ATTR_RANK);
1866         lastChangedTimestamp = ShortcutService.parseLongAttribute(parser, ATTR_TIMESTAMP);
1867         flags = (int) ShortcutService.parseLongAttribute(parser, ATTR_FLAGS);
1868         iconResId = (int) ShortcutService.parseLongAttribute(parser, ATTR_ICON_RES_ID);
1869         iconResName = ShortcutService.parseStringAttribute(parser, ATTR_ICON_RES_NAME);
1870         bitmapPath = ShortcutService.parseStringAttribute(parser, ATTR_BITMAP_PATH);
1871         iconUri = ShortcutService.parseStringAttribute(parser, ATTR_ICON_URI);
1872         locusIdString = ShortcutService.parseStringAttribute(parser, ATTR_LOCUS_ID);
1873 
1874         final int outerDepth = parser.getDepth();
1875         int type;
1876         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1877                 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1878             if (type != XmlPullParser.START_TAG) {
1879                 continue;
1880             }
1881             final int depth = parser.getDepth();
1882             final String tag = parser.getName();
1883             if (ShortcutService.DEBUG_LOAD) {
1884                 Slog.d(TAG, String.format("  depth=%d type=%d name=%s",
1885                         depth, type, tag));
1886             }
1887             switch (tag) {
1888                 case TAG_INTENT_EXTRAS_LEGACY:
1889                     intentPersistableExtrasLegacy = PersistableBundle.restoreFromXml(parser);
1890                     continue;
1891                 case TAG_INTENT:
1892                     intents.add(parseIntent(parser));
1893                     continue;
1894                 case TAG_EXTRAS:
1895                     extras = PersistableBundle.restoreFromXml(parser);
1896                     continue;
1897                 case TAG_CATEGORIES:
1898                     // This just contains string-array.
1899                     continue;
1900                 case TAG_PERSON:
1901                     persons.add(parsePerson(parser));
1902                     continue;
1903                 case TAG_STRING_ARRAY_XMLUTILS:
1904                     if (NAME_CATEGORIES.equals(ShortcutService.parseStringAttribute(parser,
1905                             ATTR_NAME_XMLUTILS))) {
1906                         final String[] ar = XmlUtils.readThisStringArrayXml(
1907                                 parser, TAG_STRING_ARRAY_XMLUTILS, null);
1908                         categories = new ArraySet<>(ar.length);
1909                         for (int i = 0; i < ar.length; i++) {
1910                             categories.add(ar[i]);
1911                         }
1912                     }
1913                     continue;
1914             }
1915             throw ShortcutService.throwForInvalidTag(depth, tag);
1916         }
1917 
1918         if (intentLegacy != null) {
1919             // For the legacy file format which supported only one intent per shortcut.
1920             ShortcutInfo.setIntentExtras(intentLegacy, intentPersistableExtrasLegacy);
1921             intents.clear();
1922             intents.add(intentLegacy);
1923         }
1924 
1925 
1926         if ((disabledReason == ShortcutInfo.DISABLED_REASON_NOT_DISABLED)
1927                 && ((flags & ShortcutInfo.FLAG_DISABLED) != 0)) {
1928             // We didn't used to have the disabled reason, so if a shortcut is disabled
1929             // and has no reason, we assume it was disabled by publisher.
1930             disabledReason = ShortcutInfo.DISABLED_REASON_BY_APP;
1931         }
1932 
1933         // All restored shortcuts are initially "shadow".
1934         if (fromBackup) {
1935             flags |= ShortcutInfo.FLAG_SHADOW;
1936         }
1937 
1938         final LocusId locusId = locusIdString == null ? null : new LocusId(locusIdString);
1939 
1940         return new ShortcutInfo(
1941                 userId, id, packageName, activityComponent, /* icon= */ null,
1942                 title, titleResId, titleResName, text, textResId, textResName,
1943                 disabledMessage, disabledMessageResId, disabledMessageResName,
1944                 categories,
1945                 intents.toArray(new Intent[intents.size()]),
1946                 rank, extras, lastChangedTimestamp, flags,
1947                 iconResId, iconResName, bitmapPath, iconUri,
1948                 disabledReason, persons.toArray(new Person[persons.size()]), locusId);
1949     }
1950 
parseIntent(XmlPullParser parser)1951     private static Intent parseIntent(XmlPullParser parser)
1952             throws IOException, XmlPullParserException {
1953 
1954         Intent intent = ShortcutService.parseIntentAttribute(parser,
1955                 ATTR_INTENT_NO_EXTRA);
1956 
1957         final int outerDepth = parser.getDepth();
1958         int type;
1959         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1960                 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1961             if (type != XmlPullParser.START_TAG) {
1962                 continue;
1963             }
1964             final int depth = parser.getDepth();
1965             final String tag = parser.getName();
1966             if (ShortcutService.DEBUG_LOAD) {
1967                 Slog.d(TAG, String.format("  depth=%d type=%d name=%s",
1968                         depth, type, tag));
1969             }
1970             switch (tag) {
1971                 case TAG_EXTRAS:
1972                     ShortcutInfo.setIntentExtras(intent,
1973                             PersistableBundle.restoreFromXml(parser));
1974                     continue;
1975             }
1976             throw ShortcutService.throwForInvalidTag(depth, tag);
1977         }
1978         return intent;
1979     }
1980 
parsePerson(XmlPullParser parser)1981     private static Person parsePerson(XmlPullParser parser)
1982             throws IOException, XmlPullParserException {
1983         CharSequence name = ShortcutService.parseStringAttribute(parser, ATTR_PERSON_NAME);
1984         String uri = ShortcutService.parseStringAttribute(parser, ATTR_PERSON_URI);
1985         String key = ShortcutService.parseStringAttribute(parser, ATTR_PERSON_KEY);
1986         boolean isBot = ShortcutService.parseBooleanAttribute(parser, ATTR_PERSON_IS_BOT);
1987         boolean isImportant = ShortcutService.parseBooleanAttribute(parser,
1988                 ATTR_PERSON_IS_IMPORTANT);
1989 
1990         Person.Builder builder = new Person.Builder();
1991         builder.setName(name).setUri(uri).setKey(key).setBot(isBot).setImportant(isImportant);
1992         return builder.build();
1993     }
1994 
1995     @VisibleForTesting
getAllShortcutsForTest()1996     List<ShortcutInfo> getAllShortcutsForTest() {
1997         return new ArrayList<>(mShortcuts.values());
1998     }
1999 
2000     @VisibleForTesting
getAllShareTargetsForTest()2001     List<ShareTargetInfo> getAllShareTargetsForTest() {
2002         return new ArrayList<>(mShareTargets);
2003     }
2004 
2005     @Override
verifyStates()2006     public void verifyStates() {
2007         super.verifyStates();
2008 
2009         boolean failed = false;
2010 
2011         final ShortcutService s = mShortcutUser.mService;
2012 
2013         final ArrayMap<ComponentName, ArrayList<ShortcutInfo>> all =
2014                 sortShortcutsToActivities();
2015 
2016         // Make sure each activity won't have more than max shortcuts.
2017         for (int outer = all.size() - 1; outer >= 0; outer--) {
2018             final ArrayList<ShortcutInfo> list = all.valueAt(outer);
2019             if (list.size() > mShortcutUser.mService.getMaxActivityShortcuts()) {
2020                 failed = true;
2021                 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": activity " + all.keyAt(outer)
2022                         + " has " + all.valueAt(outer).size() + " shortcuts.");
2023             }
2024 
2025             // Sort by rank.
2026             Collections.sort(list, (a, b) -> Integer.compare(a.getRank(), b.getRank()));
2027 
2028             // Split into two arrays for each kind.
2029             final ArrayList<ShortcutInfo> dynamicList = new ArrayList<>(list);
2030             dynamicList.removeIf((si) -> !si.isDynamic());
2031 
2032             final ArrayList<ShortcutInfo> manifestList = new ArrayList<>(list);
2033             manifestList.removeIf((si) -> !si.isManifestShortcut());
2034 
2035             verifyRanksSequential(dynamicList);
2036             verifyRanksSequential(manifestList);
2037         }
2038 
2039         // Verify each shortcut's status.
2040         for (int i = mShortcuts.size() - 1; i >= 0; i--) {
2041             final ShortcutInfo si = mShortcuts.valueAt(i);
2042             if (!(si.isDeclaredInManifest() || si.isDynamic() || si.isPinned() || si.isCached())) {
2043                 failed = true;
2044                 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
2045                         + " is not manifest, dynamic or pinned.");
2046             }
2047             if (si.isDeclaredInManifest() && si.isDynamic()) {
2048                 failed = true;
2049                 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
2050                         + " is both dynamic and manifest at the same time.");
2051             }
2052             if (si.getActivity() == null && !si.isFloating()) {
2053                 failed = true;
2054                 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
2055                         + " has null activity, but not floating.");
2056             }
2057             if ((si.isDynamic() || si.isManifestShortcut()) && !si.isEnabled()) {
2058                 failed = true;
2059                 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
2060                         + " is not floating, but is disabled.");
2061             }
2062             if (si.isFloating() && si.getRank() != 0) {
2063                 failed = true;
2064                 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
2065                         + " is floating, but has rank=" + si.getRank());
2066             }
2067             if (si.getIcon() != null) {
2068                 failed = true;
2069                 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
2070                         + " still has an icon");
2071             }
2072             if (si.hasAdaptiveBitmap() && !(si.hasIconFile() || si.hasIconUri())) {
2073                 failed = true;
2074                 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
2075                         + " has adaptive bitmap but was not saved to a file nor has icon uri.");
2076             }
2077             if (si.hasIconFile() && si.hasIconResource()) {
2078                 failed = true;
2079                 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
2080                         + " has both resource and bitmap icons");
2081             }
2082             if (si.hasIconFile() && si.hasIconUri()) {
2083                 failed = true;
2084                 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
2085                         + " has both url and bitmap icons");
2086             }
2087             if (si.hasIconUri() && si.hasIconResource()) {
2088                 failed = true;
2089                 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
2090                         + " has both url and resource icons");
2091             }
2092             if (si.isEnabled()
2093                     != (si.getDisabledReason() == ShortcutInfo.DISABLED_REASON_NOT_DISABLED)) {
2094                 failed = true;
2095                 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
2096                         + " isEnabled() and getDisabledReason() disagree: "
2097                         + si.isEnabled() + " vs " + si.getDisabledReason());
2098             }
2099             if ((si.getDisabledReason() == ShortcutInfo.DISABLED_REASON_VERSION_LOWER)
2100                     && (getPackageInfo().getBackupSourceVersionCode()
2101                     == ShortcutInfo.VERSION_CODE_UNKNOWN)) {
2102                 failed = true;
2103                 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
2104                         + " RESTORED_VERSION_LOWER with no backup source version code.");
2105             }
2106             if (s.isDummyMainActivity(si.getActivity())) {
2107                 failed = true;
2108                 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
2109                         + " has a dummy target activity");
2110             }
2111         }
2112 
2113         if (failed) {
2114             throw new IllegalStateException("See logcat for errors");
2115         }
2116     }
2117 
verifyRanksSequential(List<ShortcutInfo> list)2118     private boolean verifyRanksSequential(List<ShortcutInfo> list) {
2119         boolean failed = false;
2120 
2121         for (int i = 0; i < list.size(); i++) {
2122             final ShortcutInfo si = list.get(i);
2123             if (si.getRank() != i) {
2124                 failed = true;
2125                 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
2126                         + " rank=" + si.getRank() + " but expected to be "+ i);
2127             }
2128         }
2129         return failed;
2130     }
2131 }
2132