OSDN Git Service

Do not scan system apps unless after OTA
[android-x86/frameworks-base.git] / services / core / java / com / android / server / pm / ShortcutPackage.java
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.content.ComponentName;
22 import android.content.Intent;
23 import android.content.pm.PackageInfo;
24 import android.content.pm.ShortcutInfo;
25 import android.content.res.Resources;
26 import android.os.Bundle;
27 import android.os.PersistableBundle;
28 import android.text.format.Formatter;
29 import android.util.ArrayMap;
30 import android.util.ArraySet;
31 import android.util.Log;
32 import android.util.Slog;
33
34 import com.android.internal.annotations.VisibleForTesting;
35 import com.android.internal.util.Preconditions;
36 import com.android.internal.util.XmlUtils;
37 import com.android.server.pm.ShortcutService.ShortcutOperation;
38 import com.android.server.pm.ShortcutService.Stats;
39
40 import org.json.JSONException;
41 import org.json.JSONObject;
42 import org.xmlpull.v1.XmlPullParser;
43 import org.xmlpull.v1.XmlPullParserException;
44 import org.xmlpull.v1.XmlSerializer;
45
46 import java.io.File;
47 import java.io.IOException;
48 import java.io.PrintWriter;
49 import java.util.ArrayList;
50 import java.util.Collections;
51 import java.util.Comparator;
52 import java.util.List;
53 import java.util.Set;
54 import java.util.function.Predicate;
55
56 /**
57  * Package information used by {@link ShortcutService}.
58  * User information used by {@link ShortcutService}.
59  *
60  * All methods should be guarded by {@code #mShortcutUser.mService.mLock}.
61  */
62 class ShortcutPackage extends ShortcutPackageItem {
63     private static final String TAG = ShortcutService.TAG;
64     private static final String TAG_VERIFY = ShortcutService.TAG + ".verify";
65
66     static final String TAG_ROOT = "package";
67     private static final String TAG_INTENT_EXTRAS_LEGACY = "intent-extras";
68     private static final String TAG_INTENT = "intent";
69     private static final String TAG_EXTRAS = "extras";
70     private static final String TAG_SHORTCUT = "shortcut";
71     private static final String TAG_CATEGORIES = "categories";
72
73     private static final String ATTR_NAME = "name";
74     private static final String ATTR_CALL_COUNT = "call-count";
75     private static final String ATTR_LAST_RESET = "last-reset";
76     private static final String ATTR_ID = "id";
77     private static final String ATTR_ACTIVITY = "activity";
78     private static final String ATTR_TITLE = "title";
79     private static final String ATTR_TITLE_RES_ID = "titleid";
80     private static final String ATTR_TITLE_RES_NAME = "titlename";
81     private static final String ATTR_TEXT = "text";
82     private static final String ATTR_TEXT_RES_ID = "textid";
83     private static final String ATTR_TEXT_RES_NAME = "textname";
84     private static final String ATTR_DISABLED_MESSAGE = "dmessage";
85     private static final String ATTR_DISABLED_MESSAGE_RES_ID = "dmessageid";
86     private static final String ATTR_DISABLED_MESSAGE_RES_NAME = "dmessagename";
87     private static final String ATTR_INTENT_LEGACY = "intent";
88     private static final String ATTR_INTENT_NO_EXTRA = "intent-base";
89     private static final String ATTR_RANK = "rank";
90     private static final String ATTR_TIMESTAMP = "timestamp";
91     private static final String ATTR_FLAGS = "flags";
92     private static final String ATTR_ICON_RES_ID = "icon-res";
93     private static final String ATTR_ICON_RES_NAME = "icon-resname";
94     private static final String ATTR_BITMAP_PATH = "bitmap-path";
95
96     private static final String NAME_CATEGORIES = "categories";
97
98     private static final String TAG_STRING_ARRAY_XMLUTILS = "string-array";
99     private static final String ATTR_NAME_XMLUTILS = "name";
100
101     private static final String KEY_DYNAMIC = "dynamic";
102     private static final String KEY_MANIFEST = "manifest";
103     private static final String KEY_PINNED = "pinned";
104     private static final String KEY_BITMAPS = "bitmaps";
105     private static final String KEY_BITMAP_BYTES = "bitmapBytes";
106
107     /**
108      * All the shortcuts from the package, keyed on IDs.
109      */
110     final private ArrayMap<String, ShortcutInfo> mShortcuts = new ArrayMap<>();
111
112     /**
113      * # of times the package has called rate-limited APIs.
114      */
115     private int mApiCallCount;
116
117     /**
118      * When {@link #mApiCallCount} was reset last time.
119      */
120     private long mLastResetTime;
121
122     private final int mPackageUid;
123
124     private long mLastKnownForegroundElapsedTime;
125
126     private ShortcutPackage(ShortcutUser shortcutUser,
127             int packageUserId, String packageName, ShortcutPackageInfo spi) {
128         super(shortcutUser, packageUserId, packageName,
129                 spi != null ? spi : ShortcutPackageInfo.newEmpty());
130
131         mPackageUid = shortcutUser.mService.injectGetPackageUid(packageName, packageUserId);
132     }
133
134     public ShortcutPackage(ShortcutUser shortcutUser, int packageUserId, String packageName) {
135         this(shortcutUser, packageUserId, packageName, null);
136     }
137
138     @Override
139     public int getOwnerUserId() {
140         // For packages, always owner user == package user.
141         return getPackageUserId();
142     }
143
144     public int getPackageUid() {
145         return mPackageUid;
146     }
147
148     /**
149      * Called when a shortcut is about to be published.  At this point we know the publisher
150      * package
151      * exists (as opposed to Launcher trying to fetch shortcuts from a non-existent package), so
152      * we do some initialization for the package.
153      */
154     private void ensurePackageVersionInfo() {
155         // Make sure we have the version code for the app.  We need the version code in
156         // handlePackageUpdated().
157         if (getPackageInfo().getVersionCode() < 0) {
158             final ShortcutService s = mShortcutUser.mService;
159
160             final PackageInfo pi = s.getPackageInfo(getPackageName(), getOwnerUserId());
161             if (pi != null) {
162                 if (ShortcutService.DEBUG) {
163                     Slog.d(TAG, String.format("Package %s version = %d", getPackageName(),
164                             pi.versionCode));
165                 }
166                 getPackageInfo().updateVersionInfo(pi);
167                 s.scheduleSaveUser(getOwnerUserId());
168             }
169         }
170     }
171
172     @Nullable
173     public Resources getPackageResources() {
174         return mShortcutUser.mService.injectGetResourcesForApplicationAsUser(
175                 getPackageName(), getPackageUserId());
176     }
177
178     @Override
179     protected void onRestoreBlocked() {
180         // Can't restore due to version/signature mismatch.  Remove all shortcuts.
181         mShortcuts.clear();
182     }
183
184     @Override
185     protected void onRestored() {
186         // Because some launchers may not have been restored (e.g. allowBackup=false),
187         // we need to re-calculate the pinned shortcuts.
188         refreshPinnedFlags();
189     }
190
191     /**
192      * Note this does *not* provide a correct view to the calling launcher.
193      */
194     @Nullable
195     public ShortcutInfo findShortcutById(String id) {
196         return mShortcuts.get(id);
197     }
198
199     private void ensureNotImmutable(@Nullable ShortcutInfo shortcut) {
200         if (shortcut != null && shortcut.isImmutable()) {
201             throw new IllegalArgumentException(
202                     "Manifest shortcut ID=" + shortcut.getId()
203                             + " may not be manipulated via APIs");
204         }
205     }
206
207     private void ensureNotImmutable(@NonNull String id) {
208         ensureNotImmutable(mShortcuts.get(id));
209     }
210
211     public void ensureImmutableShortcutsNotIncludedWithIds(@NonNull List<String> shortcutIds) {
212         for (int i = shortcutIds.size() - 1; i >= 0; i--) {
213             ensureNotImmutable(shortcutIds.get(i));
214         }
215     }
216
217     public void ensureImmutableShortcutsNotIncluded(@NonNull List<ShortcutInfo> shortcuts) {
218         for (int i = shortcuts.size() - 1; i >= 0; i--) {
219             ensureNotImmutable(shortcuts.get(i).getId());
220         }
221     }
222
223     private ShortcutInfo deleteShortcutInner(@NonNull String id) {
224         final ShortcutInfo shortcut = mShortcuts.remove(id);
225         if (shortcut != null) {
226             mShortcutUser.mService.removeIcon(getPackageUserId(), shortcut);
227             shortcut.clearFlags(ShortcutInfo.FLAG_DYNAMIC | ShortcutInfo.FLAG_PINNED
228                     | ShortcutInfo.FLAG_MANIFEST);
229         }
230         return shortcut;
231     }
232
233     private void addShortcutInner(@NonNull ShortcutInfo newShortcut) {
234         final ShortcutService s = mShortcutUser.mService;
235
236         deleteShortcutInner(newShortcut.getId());
237
238         // Extract Icon and update the icon res ID and the bitmap path.
239         s.saveIconAndFixUpShortcut(getPackageUserId(), newShortcut);
240         s.fixUpShortcutResourceNamesAndValues(newShortcut);
241         mShortcuts.put(newShortcut.getId(), newShortcut);
242     }
243
244     /**
245      * Add a shortcut, or update one with the same ID, with taking over existing flags.
246      *
247      * It checks the max number of dynamic shortcuts.
248      */
249     public void addOrUpdateDynamicShortcut(@NonNull ShortcutInfo newShortcut) {
250
251         Preconditions.checkArgument(newShortcut.isEnabled(),
252                 "add/setDynamicShortcuts() cannot publish disabled shortcuts");
253
254         ensurePackageVersionInfo();
255
256         newShortcut.addFlags(ShortcutInfo.FLAG_DYNAMIC);
257
258         final ShortcutInfo oldShortcut = mShortcuts.get(newShortcut.getId());
259
260         final boolean wasPinned;
261
262         if (oldShortcut == null) {
263             wasPinned = false;
264         } else {
265             // It's an update case.
266             // Make sure the target is updatable. (i.e. should be mutable.)
267             oldShortcut.ensureUpdatableWith(newShortcut);
268
269             wasPinned = oldShortcut.isPinned();
270         }
271
272         // If it was originally pinned, the new one should be pinned too.
273         if (wasPinned) {
274             newShortcut.addFlags(ShortcutInfo.FLAG_PINNED);
275         }
276
277         addShortcutInner(newShortcut);
278     }
279
280     /**
281      * Remove all shortcuts that aren't pinned nor dynamic.
282      */
283     private void removeOrphans() {
284         ArrayList<String> removeList = null; // Lazily initialize.
285
286         for (int i = mShortcuts.size() - 1; i >= 0; i--) {
287             final ShortcutInfo si = mShortcuts.valueAt(i);
288
289             if (si.isAlive()) continue;
290
291             if (removeList == null) {
292                 removeList = new ArrayList<>();
293             }
294             removeList.add(si.getId());
295         }
296         if (removeList != null) {
297             for (int i = removeList.size() - 1; i >= 0; i--) {
298                 deleteShortcutInner(removeList.get(i));
299             }
300         }
301     }
302
303     /**
304      * Remove all dynamic shortcuts.
305      */
306     public void deleteAllDynamicShortcuts() {
307         final long now = mShortcutUser.mService.injectCurrentTimeMillis();
308
309         boolean changed = false;
310         for (int i = mShortcuts.size() - 1; i >= 0; i--) {
311             final ShortcutInfo si = mShortcuts.valueAt(i);
312             if (si.isDynamic()) {
313                 changed = true;
314
315                 si.setTimestamp(now);
316                 si.clearFlags(ShortcutInfo.FLAG_DYNAMIC);
317                 si.setRank(0); // It may still be pinned, so clear the rank.
318             }
319         }
320         if (changed) {
321             removeOrphans();
322         }
323     }
324
325     /**
326      * Remove a dynamic shortcut by ID.  It'll be removed from the dynamic set, but if the shortcut
327      * is pinned, it'll remain as a pinned shortcut, and is still enabled.
328      *
329      * @return true if it's actually removed because it wasn't pinned, or false if it's still
330      * pinned.
331      */
332     public boolean deleteDynamicWithId(@NonNull String shortcutId) {
333         final ShortcutInfo removed = deleteOrDisableWithId(
334                 shortcutId, /* disable =*/ false, /* overrideImmutable=*/ false);
335         return removed == null;
336     }
337
338     /**
339      * Disable a dynamic shortcut by ID.  It'll be removed from the dynamic set, but if the shortcut
340      * is pinned, it'll remain as a pinned shortcut, but will be disabled.
341      *
342      * @return true if it's actually removed because it wasn't pinned, or false if it's still
343      * pinned.
344      */
345     private boolean disableDynamicWithId(@NonNull String shortcutId) {
346         final ShortcutInfo disabled = deleteOrDisableWithId(
347                 shortcutId, /* disable =*/ true, /* overrideImmutable=*/ false);
348         return disabled == null;
349     }
350
351     /**
352      * Disable a dynamic shortcut by ID.  It'll be removed from the dynamic set, but if the shortcut
353      * is pinned, it'll remain as a pinned shortcut but will be disabled.
354      */
355     public void disableWithId(@NonNull String shortcutId, String disabledMessage,
356             int disabledMessageResId, boolean overrideImmutable) {
357         final ShortcutInfo disabled = deleteOrDisableWithId(shortcutId, /* disable =*/ true,
358                 overrideImmutable);
359
360         if (disabled != null) {
361             if (disabledMessage != null) {
362                 disabled.setDisabledMessage(disabledMessage);
363             } else if (disabledMessageResId != 0) {
364                 disabled.setDisabledMessageResId(disabledMessageResId);
365
366                 mShortcutUser.mService.fixUpShortcutResourceNamesAndValues(disabled);
367             }
368         }
369     }
370
371     @Nullable
372     private ShortcutInfo deleteOrDisableWithId(@NonNull String shortcutId, boolean disable,
373             boolean overrideImmutable) {
374         final ShortcutInfo oldShortcut = mShortcuts.get(shortcutId);
375
376         if (oldShortcut == null || !oldShortcut.isEnabled()) {
377             return null; // Doesn't exist or already disabled.
378         }
379         if (!overrideImmutable) {
380             ensureNotImmutable(oldShortcut);
381         }
382         if (oldShortcut.isPinned()) {
383
384             oldShortcut.setRank(0);
385             oldShortcut.clearFlags(ShortcutInfo.FLAG_DYNAMIC | ShortcutInfo.FLAG_MANIFEST);
386             if (disable) {
387                 oldShortcut.addFlags(ShortcutInfo.FLAG_DISABLED);
388             }
389             oldShortcut.setTimestamp(mShortcutUser.mService.injectCurrentTimeMillis());
390
391             return oldShortcut;
392         } else {
393             deleteShortcutInner(shortcutId);
394             return null;
395         }
396     }
397
398     public void enableWithId(@NonNull String shortcutId) {
399         final ShortcutInfo shortcut = mShortcuts.get(shortcutId);
400         if (shortcut != null) {
401             ensureNotImmutable(shortcut);
402             shortcut.clearFlags(ShortcutInfo.FLAG_DISABLED);
403         }
404     }
405
406     /**
407      * Called after a launcher updates the pinned set.  For each shortcut in this package,
408      * set FLAG_PINNED if any launcher has pinned it.  Otherwise, clear it.
409      *
410      * <p>Then remove all shortcuts that are not dynamic and no longer pinned either.
411      */
412     public void refreshPinnedFlags() {
413         // First, un-pin all shortcuts
414         for (int i = mShortcuts.size() - 1; i >= 0; i--) {
415             mShortcuts.valueAt(i).clearFlags(ShortcutInfo.FLAG_PINNED);
416         }
417
418         // Then, for the pinned set for each launcher, set the pin flag one by one.
419         mShortcutUser.mService.getUserShortcutsLocked(getPackageUserId())
420                 .forAllLaunchers(launcherShortcuts -> {
421             final ArraySet<String> pinned = launcherShortcuts.getPinnedShortcutIds(
422                     getPackageName(), getPackageUserId());
423
424             if (pinned == null || pinned.size() == 0) {
425                 return;
426             }
427             for (int i = pinned.size() - 1; i >= 0; i--) {
428                 final String id = pinned.valueAt(i);
429                 final ShortcutInfo si = mShortcuts.get(id);
430                 if (si == null) {
431                     // This happens if a launcher pinned shortcuts from this package, then backup&
432                     // restored, but this package doesn't allow backing up.
433                     // In that case the launcher ends up having a dangling pinned shortcuts.
434                     // That's fine, when the launcher is restored, we'll fix it.
435                     continue;
436                 }
437                 si.addFlags(ShortcutInfo.FLAG_PINNED);
438             }
439         });
440
441         // Lastly, remove the ones that are no longer pinned nor dynamic.
442         removeOrphans();
443     }
444
445     /**
446      * Number of calls that the caller has made, since the last reset.
447      *
448      * <p>This takes care of the resetting the counter for foreground apps as well as after
449      * locale changes.
450      */
451     public int getApiCallCount() {
452         final ShortcutService s = mShortcutUser.mService;
453
454         // Reset the counter if:
455         // - the package is in foreground now.
456         // - the package is *not* in foreground now, but was in foreground at some point
457         // since the previous time it had been.
458         if (s.isUidForegroundLocked(mPackageUid)
459                 || mLastKnownForegroundElapsedTime
460                     < s.getUidLastForegroundElapsedTimeLocked(mPackageUid)) {
461             mLastKnownForegroundElapsedTime = s.injectElapsedRealtime();
462             resetRateLimiting();
463         }
464
465         // Note resetThrottlingIfNeeded() and resetRateLimiting() will set 0 to mApiCallCount,
466         // but we just can't return 0 at this point, because we may have to update
467         // mLastResetTime.
468
469         final long last = s.getLastResetTimeLocked();
470
471         final long now = s.injectCurrentTimeMillis();
472         if (ShortcutService.isClockValid(now) && mLastResetTime > now) {
473             Slog.w(TAG, "Clock rewound");
474             // Clock rewound.
475             mLastResetTime = now;
476             mApiCallCount = 0;
477             return mApiCallCount;
478         }
479
480         // If not reset yet, then reset.
481         if (mLastResetTime < last) {
482             if (ShortcutService.DEBUG) {
483                 Slog.d(TAG, String.format("%s: last reset=%d, now=%d, last=%d: resetting",
484                         getPackageName(), mLastResetTime, now, last));
485             }
486             mApiCallCount = 0;
487             mLastResetTime = last;
488         }
489         return mApiCallCount;
490     }
491
492     /**
493      * If the caller app hasn't been throttled yet, increment {@link #mApiCallCount}
494      * and return true.  Otherwise just return false.
495      *
496      * <p>This takes care of the resetting the counter for foreground apps as well as after
497      * locale changes, which is done internally by {@link #getApiCallCount}.
498      */
499     public boolean tryApiCall() {
500         final ShortcutService s = mShortcutUser.mService;
501
502         if (getApiCallCount() >= s.mMaxUpdatesPerInterval) {
503             return false;
504         }
505         mApiCallCount++;
506         s.scheduleSaveUser(getOwnerUserId());
507         return true;
508     }
509
510     public void resetRateLimiting() {
511         if (ShortcutService.DEBUG) {
512             Slog.d(TAG, "resetRateLimiting: " + getPackageName());
513         }
514         if (mApiCallCount > 0) {
515             mApiCallCount = 0;
516             mShortcutUser.mService.scheduleSaveUser(getOwnerUserId());
517         }
518     }
519
520     public void resetRateLimitingForCommandLineNoSaving() {
521         mApiCallCount = 0;
522         mLastResetTime = 0;
523     }
524
525     /**
526      * Find all shortcuts that match {@code query}.
527      */
528     public void findAll(@NonNull List<ShortcutInfo> result,
529             @Nullable Predicate<ShortcutInfo> query, int cloneFlag) {
530         findAll(result, query, cloneFlag, null, 0);
531     }
532
533     /**
534      * Find all shortcuts that match {@code query}.
535      *
536      * This will also provide a "view" for each launcher -- a non-dynamic shortcut that's not pinned
537      * by the calling launcher will not be included in the result, and also "isPinned" will be
538      * adjusted for the caller too.
539      */
540     public void findAll(@NonNull List<ShortcutInfo> result,
541             @Nullable Predicate<ShortcutInfo> query, int cloneFlag,
542             @Nullable String callingLauncher, int launcherUserId) {
543         if (getPackageInfo().isShadow()) {
544             // Restored and the app not installed yet, so don't return any.
545             return;
546         }
547
548         final ShortcutService s = mShortcutUser.mService;
549
550         // Set of pinned shortcuts by the calling launcher.
551         final ArraySet<String> pinnedByCallerSet = (callingLauncher == null) ? null
552                 : s.getLauncherShortcutsLocked(callingLauncher, getPackageUserId(), launcherUserId)
553                     .getPinnedShortcutIds(getPackageName(), getPackageUserId());
554
555         for (int i = 0; i < mShortcuts.size(); i++) {
556             final ShortcutInfo si = mShortcuts.valueAt(i);
557
558             // Need to adjust PINNED flag depending on the caller.
559             // Basically if the caller is a launcher (callingLauncher != null) and the launcher
560             // isn't pinning it, then we need to clear PINNED for this caller.
561             final boolean isPinnedByCaller = (callingLauncher == null)
562                     || ((pinnedByCallerSet != null) && pinnedByCallerSet.contains(si.getId()));
563
564             if (si.isFloating()) {
565                 if (!isPinnedByCaller) {
566                     continue;
567                 }
568             }
569             final ShortcutInfo clone = si.clone(cloneFlag);
570
571             // Fix up isPinned for the caller.  Note we need to do it before the "test" callback,
572             // since it may check isPinned.
573             if (!isPinnedByCaller) {
574                 clone.clearFlags(ShortcutInfo.FLAG_PINNED);
575             }
576             if (query == null || query.test(clone)) {
577                 result.add(clone);
578             }
579         }
580     }
581
582     public void resetThrottling() {
583         mApiCallCount = 0;
584     }
585
586     /**
587      * Return the filenames (excluding path names) of icon bitmap files from this package.
588      */
589     public ArraySet<String> getUsedBitmapFiles() {
590         final ArraySet<String> usedFiles = new ArraySet<>(mShortcuts.size());
591
592         for (int i = mShortcuts.size() - 1; i >= 0; i--) {
593             final ShortcutInfo si = mShortcuts.valueAt(i);
594             if (si.getBitmapPath() != null) {
595                 usedFiles.add(getFileName(si.getBitmapPath()));
596             }
597         }
598         return usedFiles;
599     }
600
601     private static String getFileName(@NonNull String path) {
602         final int sep = path.lastIndexOf(File.separatorChar);
603         if (sep == -1) {
604             return path;
605         } else {
606             return path.substring(sep + 1);
607         }
608     }
609
610     /**
611      * @return false if any of the target activities are no longer enabled.
612      */
613     private boolean areAllActivitiesStillEnabled() {
614         if (mShortcuts.size() == 0) {
615             return true;
616         }
617         final ShortcutService s = mShortcutUser.mService;
618
619         // Normally the number of target activities is 1 or so, so no need to use a complex
620         // structure like a set.
621         final ArrayList<ComponentName> checked = new ArrayList<>(4);
622
623         for (int i = mShortcuts.size() - 1; i >= 0; i--) {
624             final ShortcutInfo si = mShortcuts.valueAt(i);
625             final ComponentName activity = si.getActivity();
626
627             if (checked.contains(activity)) {
628                 continue; // Already checked.
629             }
630             checked.add(activity);
631
632             if (!s.injectIsActivityEnabledAndExported(activity, getOwnerUserId())) {
633                 return false;
634             }
635         }
636         return true;
637     }
638
639     /**
640      * Called when the package may be added or updated, or its activities may be disabled, and
641      * if so, rescan the package and do the necessary stuff.
642      *
643      * Add case:
644      * - Publish manifest shortcuts.
645      *
646      * Update case:
647      * - Re-publish manifest shortcuts.
648      * - If there are shortcuts with resources (icons or strings), update their timestamps.
649      * - Disable shortcuts whose target activities are disabled.
650      *
651      * @return TRUE if any shortcuts have been changed.
652      */
653     public boolean rescanPackageIfNeeded(boolean isNewApp, boolean forceRescan) {
654         final ShortcutService s = mShortcutUser.mService;
655         final long start = s.injectElapsedRealtime();
656
657         final PackageInfo pi;
658         try {
659             pi = mShortcutUser.mService.getPackageInfo(
660                     getPackageName(), getPackageUserId());
661             if (pi == null) {
662                 return false; // Shouldn't happen.
663             }
664
665             if (!isNewApp && !forceRescan) {
666                 // Return if the package hasn't changed, ie:
667                 // - version code hasn't change
668                 // - lastUpdateTime hasn't change
669                 // - all target activities are still enabled.
670
671                 // Note, system apps timestamps do *not* change after OTAs.  (But they do
672                 // after an adb sync or a local flash.)
673                 // This means if a system app's version code doesn't change on an OTA,
674                 // we don't notice it's updated.  But that's fine since their version code *should*
675                 // really change on OTAs.
676                 if ((getPackageInfo().getVersionCode() == pi.versionCode)
677                         && (getPackageInfo().getLastUpdateTime() == pi.lastUpdateTime)
678                         && areAllActivitiesStillEnabled()) {
679                     return false;
680                 }
681             }
682         } finally {
683             s.logDurationStat(Stats.PACKAGE_UPDATE_CHECK, start);
684         }
685
686         // Now prepare to publish manifest shortcuts.
687         List<ShortcutInfo> newManifestShortcutList = null;
688         try {
689             newManifestShortcutList = ShortcutParser.parseShortcuts(mShortcutUser.mService,
690                     getPackageName(), getPackageUserId());
691         } catch (IOException|XmlPullParserException e) {
692             Slog.e(TAG, "Failed to load shortcuts from AndroidManifest.xml.", e);
693         }
694         final int manifestShortcutSize = newManifestShortcutList == null ? 0
695                 : newManifestShortcutList.size();
696         if (ShortcutService.DEBUG) {
697             Slog.d(TAG, String.format("Package %s has %d manifest shortcut(s)",
698                     getPackageName(), manifestShortcutSize));
699         }
700         if (isNewApp && (manifestShortcutSize == 0)) {
701             // If it's a new app, and it doesn't have manifest shortcuts, then nothing to do.
702
703             // If it's an update, then it may already have manifest shortcuts, which need to be
704             // disabled.
705             return false;
706         }
707         if (ShortcutService.DEBUG) {
708             Slog.d(TAG, String.format("Package %s %s, version %d -> %d", getPackageName(),
709                     (isNewApp ? "added" : "updated"),
710                     getPackageInfo().getVersionCode(), pi.versionCode));
711         }
712
713         getPackageInfo().updateVersionInfo(pi);
714
715         boolean changed = false;
716
717         // For existing shortcuts, update timestamps if they have any resources.
718         // Also check if shortcuts' activities are still main activities.  Otherwise, disable them.
719         if (!isNewApp) {
720             Resources publisherRes = null;
721
722             for (int i = mShortcuts.size() - 1; i >= 0; i--) {
723                 final ShortcutInfo si = mShortcuts.valueAt(i);
724
725                 if (si.isDynamic()) {
726                     if (!s.injectIsMainActivity(si.getActivity(), getPackageUserId())) {
727                         Slog.w(TAG, String.format(
728                                 "%s is no longer main activity. Disabling shorcut %s.",
729                                 getPackageName(), si.getId()));
730                         if (disableDynamicWithId(si.getId())) {
731                             continue; // Actually removed.
732                         }
733                         // Still pinned, so fall-through and possibly update the resources.
734                     }
735                     changed = true;
736                 }
737
738                 if (si.hasAnyResources()) {
739                     if (!si.isOriginallyFromManifest()) {
740                         if (publisherRes == null) {
741                             publisherRes = getPackageResources();
742                             if (publisherRes == null) {
743                                 break; // Resources couldn't be loaded.
744                             }
745                         }
746
747                         // If this shortcut is not from a manifest, then update all resource IDs
748                         // from resource names.  (We don't allow resource strings for
749                         // non-manifest at the moment, but icons can still be resources.)
750                         si.lookupAndFillInResourceIds(publisherRes);
751                     }
752                     changed = true;
753                     si.setTimestamp(s.injectCurrentTimeMillis());
754                 }
755             }
756         }
757
758         // (Re-)publish manifest shortcut.
759         changed |= publishManifestShortcuts(newManifestShortcutList);
760
761         if (newManifestShortcutList != null) {
762             changed |= pushOutExcessShortcuts();
763         }
764
765         s.verifyStates();
766
767         if (changed) {
768             // This will send a notification to the launcher, and also save .
769             s.packageShortcutsChanged(getPackageName(), getPackageUserId());
770         } else {
771             // Still save the version code.
772             s.scheduleSaveUser(getPackageUserId());
773         }
774         return changed;
775     }
776
777     private boolean publishManifestShortcuts(List<ShortcutInfo> newManifestShortcutList) {
778         if (ShortcutService.DEBUG) {
779             Slog.d(TAG, String.format(
780                     "Package %s: publishing manifest shortcuts", getPackageName()));
781         }
782         boolean changed = false;
783
784         // Keep the previous IDs.
785         ArraySet<String> toDisableList = null;
786         for (int i = mShortcuts.size() - 1; i >= 0; i--) {
787             final ShortcutInfo si = mShortcuts.valueAt(i);
788
789             if (si.isManifestShortcut()) {
790                 if (toDisableList == null) {
791                     toDisableList = new ArraySet<>();
792                 }
793                 toDisableList.add(si.getId());
794             }
795         }
796
797         // Publish new ones.
798         if (newManifestShortcutList != null) {
799             final int newListSize = newManifestShortcutList.size();
800
801             for (int i = 0; i < newListSize; i++) {
802                 changed = true;
803
804                 final ShortcutInfo newShortcut = newManifestShortcutList.get(i);
805                 final boolean newDisabled = !newShortcut.isEnabled();
806
807                 final String id = newShortcut.getId();
808                 final ShortcutInfo oldShortcut = mShortcuts.get(id);
809
810                 boolean wasPinned = false;
811
812                 if (oldShortcut != null) {
813                     if (!oldShortcut.isOriginallyFromManifest()) {
814                         Slog.e(TAG, "Shortcut with ID=" + newShortcut.getId()
815                                 + " exists but is not from AndroidManifest.xml, not updating.");
816                         continue;
817                     }
818                     // Take over the pinned flag.
819                     if (oldShortcut.isPinned()) {
820                         wasPinned = true;
821                         newShortcut.addFlags(ShortcutInfo.FLAG_PINNED);
822                     }
823                 }
824                 if (newDisabled && !wasPinned) {
825                     // If the shortcut is disabled, and it was *not* pinned, then this
826                     // just doesn't have to be published.
827                     // Just keep it in toDisableList, so the previous one would be removed.
828                     continue;
829                 }
830
831                 // Note even if enabled=false, we still need to update all fields, so do it
832                 // regardless.
833                 addShortcutInner(newShortcut); // This will clean up the old one too.
834
835                 if (!newDisabled && toDisableList != null) {
836                     // Still alive, don't remove.
837                     toDisableList.remove(id);
838                 }
839             }
840         }
841
842         // Disable the previous manifest shortcuts that are no longer in the manifest.
843         if (toDisableList != null) {
844             if (ShortcutService.DEBUG) {
845                 Slog.d(TAG, String.format(
846                         "Package %s: disabling %d stale shortcuts", getPackageName(),
847                         toDisableList.size()));
848             }
849             for (int i = toDisableList.size() - 1; i >= 0; i--) {
850                 changed = true;
851
852                 final String id = toDisableList.valueAt(i);
853
854                 disableWithId(id, /* disable message =*/ null, /* disable message resid */ 0,
855                         /* overrideImmutable=*/ true);
856             }
857             removeOrphans();
858         }
859         adjustRanks();
860         return changed;
861     }
862
863     /**
864      * For each target activity, make sure # of dynamic + manifest shortcuts <= max.
865      * If too many, we'll remove the dynamic with the lowest ranks.
866      */
867     private boolean pushOutExcessShortcuts() {
868         final ShortcutService service = mShortcutUser.mService;
869         final int maxShortcuts = service.getMaxActivityShortcuts();
870
871         boolean changed = false;
872
873         final ArrayMap<ComponentName, ArrayList<ShortcutInfo>> all =
874                 sortShortcutsToActivities();
875         for (int outer = all.size() - 1; outer >= 0; outer--) {
876             final ArrayList<ShortcutInfo> list = all.valueAt(outer);
877             if (list.size() <= maxShortcuts) {
878                 continue;
879             }
880             // Sort by isManifestShortcut() and getRank().
881             Collections.sort(list, mShortcutTypeAndRankComparator);
882
883             // Keep [0 .. max), and remove (as dynamic) [max .. size)
884             for (int inner = list.size() - 1; inner >= maxShortcuts; inner--) {
885                 final ShortcutInfo shortcut = list.get(inner);
886
887                 if (shortcut.isManifestShortcut()) {
888                     // This shouldn't happen -- excess shortcuts should all be non-manifest.
889                     // But just in case.
890                     service.wtf("Found manifest shortcuts in excess list.");
891                     continue;
892                 }
893                 deleteDynamicWithId(shortcut.getId());
894             }
895         }
896
897         return changed;
898     }
899
900     /**
901      * To sort by isManifestShortcut() and getRank(). i.e.  manifest shortcuts come before
902      * non-manifest shortcuts, then sort by rank.
903      *
904      * This is used to decide which dynamic shortcuts to remove when an upgraded version has more
905      * manifest shortcuts than before and as a result we need to remove some of the dynamic
906      * shortcuts.  We sort manifest + dynamic shortcuts by this order, and remove the ones with
907      * the last ones.
908      *
909      * (Note the number of manifest shortcuts is always <= the max number, because if there are
910      * more, ShortcutParser would ignore the rest.)
911      */
912     final Comparator<ShortcutInfo> mShortcutTypeAndRankComparator = (ShortcutInfo a,
913             ShortcutInfo b) -> {
914         if (a.isManifestShortcut() && !b.isManifestShortcut()) {
915             return -1;
916         }
917         if (!a.isManifestShortcut() && b.isManifestShortcut()) {
918             return 1;
919         }
920         return Integer.compare(a.getRank(), b.getRank());
921     };
922
923     /**
924      * Build a list of shortcuts for each target activity and return as a map. The result won't
925      * contain "floating" shortcuts because they don't belong on any activities.
926      */
927     private ArrayMap<ComponentName, ArrayList<ShortcutInfo>> sortShortcutsToActivities() {
928         final ArrayMap<ComponentName, ArrayList<ShortcutInfo>> activitiesToShortcuts
929                 = new ArrayMap<>();
930         for (int i = mShortcuts.size() - 1; i >= 0; i--) {
931             final ShortcutInfo si = mShortcuts.valueAt(i);
932             if (si.isFloating()) {
933                 continue; // Ignore floating shortcuts, which are not tied to any activities.
934             }
935
936             final ComponentName activity = si.getActivity();
937
938             ArrayList<ShortcutInfo> list = activitiesToShortcuts.get(activity);
939             if (list == null) {
940                 list = new ArrayList<>();
941                 activitiesToShortcuts.put(activity, list);
942             }
943             list.add(si);
944         }
945         return activitiesToShortcuts;
946     }
947
948     /** Used by {@link #enforceShortcutCountsBeforeOperation} */
949     private void incrementCountForActivity(ArrayMap<ComponentName, Integer> counts,
950             ComponentName cn, int increment) {
951         Integer oldValue = counts.get(cn);
952         if (oldValue == null) {
953             oldValue = 0;
954         }
955
956         counts.put(cn, oldValue + increment);
957     }
958
959     /**
960      * Called by
961      * {@link android.content.pm.ShortcutManager#setDynamicShortcuts},
962      * {@link android.content.pm.ShortcutManager#addDynamicShortcuts}, and
963      * {@link android.content.pm.ShortcutManager#updateShortcuts} before actually performing
964      * the operation to make sure the operation wouldn't result in the target activities having
965      * more than the allowed number of dynamic/manifest shortcuts.
966      *
967      * @param newList shortcut list passed to set, add or updateShortcuts().
968      * @param operation add, set or update.
969      * @throws IllegalArgumentException if the operation would result in going over the max
970      *                                  shortcut count for any activity.
971      */
972     public void enforceShortcutCountsBeforeOperation(List<ShortcutInfo> newList,
973             @ShortcutOperation int operation) {
974         final ShortcutService service = mShortcutUser.mService;
975
976         // Current # of dynamic / manifest shortcuts for each activity.
977         // (If it's for update, then don't count dynamic shortcuts, since they'll be replaced
978         // anyway.)
979         final ArrayMap<ComponentName, Integer> counts = new ArrayMap<>(4);
980         for (int i = mShortcuts.size() - 1; i >= 0; i--) {
981             final ShortcutInfo shortcut = mShortcuts.valueAt(i);
982
983             if (shortcut.isManifestShortcut()) {
984                 incrementCountForActivity(counts, shortcut.getActivity(), 1);
985             } else if (shortcut.isDynamic() && (operation != ShortcutService.OPERATION_SET)) {
986                 incrementCountForActivity(counts, shortcut.getActivity(), 1);
987             }
988         }
989
990         for (int i = newList.size() - 1; i >= 0; i--) {
991             final ShortcutInfo newShortcut = newList.get(i);
992             final ComponentName newActivity = newShortcut.getActivity();
993             if (newActivity == null) {
994                 if (operation != ShortcutService.OPERATION_UPDATE) {
995                     service.wtf("Activity must not be null at this point");
996                     continue; // Just ignore this invalid case.
997                 }
998                 continue; // Activity can be null for update.
999             }
1000
1001             final ShortcutInfo original = mShortcuts.get(newShortcut.getId());
1002             if (original == null) {
1003                 if (operation == ShortcutService.OPERATION_UPDATE) {
1004                     continue; // When updating, ignore if there's no target.
1005                 }
1006                 // Add() or set(), and there's no existing shortcut with the same ID.  We're
1007                 // simply publishing (as opposed to updating) this shortcut, so just +1.
1008                 incrementCountForActivity(counts, newActivity, 1);
1009                 continue;
1010             }
1011             if (original.isFloating() && (operation == ShortcutService.OPERATION_UPDATE)) {
1012                 // Updating floating shortcuts doesn't affect the count, so ignore.
1013                 continue;
1014             }
1015
1016             // If it's add() or update(), then need to decrement for the previous activity.
1017             // Skip it for set() since it's already been taken care of by not counting the original
1018             // dynamic shortcuts in the first loop.
1019             if (operation != ShortcutService.OPERATION_SET) {
1020                 final ComponentName oldActivity = original.getActivity();
1021                 if (!original.isFloating()) {
1022                     incrementCountForActivity(counts, oldActivity, -1);
1023                 }
1024             }
1025             incrementCountForActivity(counts, newActivity, 1);
1026         }
1027
1028         // Then make sure none of the activities have more than the max number of shortcuts.
1029         for (int i = counts.size() - 1; i >= 0; i--) {
1030             service.enforceMaxActivityShortcuts(counts.valueAt(i));
1031         }
1032     }
1033
1034     /**
1035      * For all the text fields, refresh the string values if they're from resources.
1036      */
1037     public void resolveResourceStrings() {
1038         final ShortcutService s = mShortcutUser.mService;
1039         boolean changed = false;
1040
1041         Resources publisherRes = null;
1042         for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1043             final ShortcutInfo si = mShortcuts.valueAt(i);
1044
1045             if (si.hasStringResources()) {
1046                 changed = true;
1047
1048                 if (publisherRes == null) {
1049                     publisherRes = getPackageResources();
1050                     if (publisherRes == null) {
1051                         break; // Resources couldn't be loaded.
1052                     }
1053                 }
1054
1055                 si.resolveResourceStrings(publisherRes);
1056                 si.setTimestamp(s.injectCurrentTimeMillis());
1057             }
1058         }
1059         if (changed) {
1060             s.packageShortcutsChanged(getPackageName(), getPackageUserId());
1061         }
1062     }
1063
1064     /** Clears the implicit ranks for all shortcuts. */
1065     public void clearAllImplicitRanks() {
1066         for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1067             final ShortcutInfo si = mShortcuts.valueAt(i);
1068             si.clearImplicitRankAndRankChangedFlag();
1069         }
1070     }
1071
1072     /**
1073      * Used to sort shortcuts for rank auto-adjusting.
1074      */
1075     final Comparator<ShortcutInfo> mShortcutRankComparator = (ShortcutInfo a, ShortcutInfo b) -> {
1076         // First, sort by rank.
1077         int ret = Integer.compare(a.getRank(), b.getRank());
1078         if (ret != 0) {
1079             return ret;
1080         }
1081         // When ranks are tie, then prioritize the ones that have just been assigned new ranks.
1082         // e.g. when there are 3 shortcuts, "s1" "s2" and "s3" with rank 0, 1, 2 respectively,
1083         // adding a shortcut "s4" with rank 1 will "insert" it between "s1" and "s2", because
1084         // "s2" and "s4" have the same rank 1 but s4 has isRankChanged() set.
1085         // Similarly, updating s3's rank to 1 will insert it between s1 and s2.
1086         if (a.isRankChanged() != b.isRankChanged()) {
1087             return a.isRankChanged() ? -1 : 1;
1088         }
1089         // If they're still tie, sort by implicit rank -- i.e. preserve the order in which
1090         // they're passed to the API.
1091         ret = Integer.compare(a.getImplicitRank(), b.getImplicitRank());
1092         if (ret != 0) {
1093             return ret;
1094         }
1095         // If they're stil tie, just sort by their IDs.
1096         // This may happen with updateShortcuts() -- see
1097         // the testUpdateShortcuts_noManifestShortcuts() test.
1098         return a.getId().compareTo(b.getId());
1099     };
1100
1101     /**
1102      * Re-calculate the ranks for all shortcuts.
1103      */
1104     public void adjustRanks() {
1105         final ShortcutService s = mShortcutUser.mService;
1106         final long now = s.injectCurrentTimeMillis();
1107
1108         // First, clear ranks for floating shortcuts.
1109         for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1110             final ShortcutInfo si = mShortcuts.valueAt(i);
1111             if (si.isFloating()) {
1112                 if (si.getRank() != 0) {
1113                     si.setTimestamp(now);
1114                     si.setRank(0);
1115                 }
1116             }
1117         }
1118
1119         // Then adjust ranks.  Ranks are unique for each activity, so we first need to sort
1120         // shortcuts to each activity.
1121         // Then sort the shortcuts within each activity with mShortcutRankComparator, and
1122         // assign ranks from 0.
1123         final ArrayMap<ComponentName, ArrayList<ShortcutInfo>> all =
1124                 sortShortcutsToActivities();
1125         for (int outer = all.size() - 1; outer >= 0; outer--) { // For each activity.
1126             final ArrayList<ShortcutInfo> list = all.valueAt(outer);
1127
1128             // Sort by ranks and other signals.
1129             Collections.sort(list, mShortcutRankComparator);
1130
1131             int rank = 0;
1132
1133             final int size = list.size();
1134             for (int i = 0; i < size; i++) {
1135                 final ShortcutInfo si = list.get(i);
1136                 if (si.isManifestShortcut()) {
1137                     // Don't adjust ranks for manifest shortcuts.
1138                     continue;
1139                 }
1140                 // At this point, it must be dynamic.
1141                 if (!si.isDynamic()) {
1142                     s.wtf("Non-dynamic shortcut found.");
1143                     continue;
1144                 }
1145                 final int thisRank = rank++;
1146                 if (si.getRank() != thisRank) {
1147                     si.setTimestamp(now);
1148                     si.setRank(thisRank);
1149                 }
1150             }
1151         }
1152     }
1153
1154     public void dump(@NonNull PrintWriter pw, @NonNull String prefix) {
1155         pw.println();
1156
1157         pw.print(prefix);
1158         pw.print("Package: ");
1159         pw.print(getPackageName());
1160         pw.print("  UID: ");
1161         pw.print(mPackageUid);
1162         pw.println();
1163
1164         pw.print(prefix);
1165         pw.print("  ");
1166         pw.print("Calls: ");
1167         pw.print(getApiCallCount());
1168         pw.println();
1169
1170         // getApiCallCount() may have updated mLastKnownForegroundElapsedTime.
1171         pw.print(prefix);
1172         pw.print("  ");
1173         pw.print("Last known FG: ");
1174         pw.print(mLastKnownForegroundElapsedTime);
1175         pw.println();
1176
1177         // This should be after getApiCallCount(), which may update it.
1178         pw.print(prefix);
1179         pw.print("  ");
1180         pw.print("Last reset: [");
1181         pw.print(mLastResetTime);
1182         pw.print("] ");
1183         pw.print(ShortcutService.formatTime(mLastResetTime));
1184         pw.println();
1185
1186         getPackageInfo().dump(pw, prefix + "  ");
1187         pw.println();
1188
1189         pw.print(prefix);
1190         pw.println("  Shortcuts:");
1191         long totalBitmapSize = 0;
1192         final ArrayMap<String, ShortcutInfo> shortcuts = mShortcuts;
1193         final int size = shortcuts.size();
1194         for (int i = 0; i < size; i++) {
1195             final ShortcutInfo si = shortcuts.valueAt(i);
1196             pw.print(prefix);
1197             pw.print("    ");
1198             pw.println(si.toInsecureString());
1199             if (si.getBitmapPath() != null) {
1200                 final long len = new File(si.getBitmapPath()).length();
1201                 pw.print(prefix);
1202                 pw.print("      ");
1203                 pw.print("bitmap size=");
1204                 pw.println(len);
1205
1206                 totalBitmapSize += len;
1207             }
1208         }
1209         pw.print(prefix);
1210         pw.print("  ");
1211         pw.print("Total bitmap size: ");
1212         pw.print(totalBitmapSize);
1213         pw.print(" (");
1214         pw.print(Formatter.formatFileSize(mShortcutUser.mService.mContext, totalBitmapSize));
1215         pw.println(")");
1216     }
1217
1218     @Override
1219     public JSONObject dumpCheckin(boolean clear) throws JSONException {
1220         final JSONObject result = super.dumpCheckin(clear);
1221
1222         int numDynamic = 0;
1223         int numPinned = 0;
1224         int numManifest = 0;
1225         int numBitmaps = 0;
1226         long totalBitmapSize = 0;
1227
1228         final ArrayMap<String, ShortcutInfo> shortcuts = mShortcuts;
1229         final int size = shortcuts.size();
1230         for (int i = 0; i < size; i++) {
1231             final ShortcutInfo si = shortcuts.valueAt(i);
1232
1233             if (si.isDynamic()) numDynamic++;
1234             if (si.isDeclaredInManifest()) numManifest++;
1235             if (si.isPinned()) numPinned++;
1236
1237             if (si.getBitmapPath() != null) {
1238                 numBitmaps++;
1239                 totalBitmapSize += new File(si.getBitmapPath()).length();
1240             }
1241         }
1242
1243         result.put(KEY_DYNAMIC, numDynamic);
1244         result.put(KEY_MANIFEST, numManifest);
1245         result.put(KEY_PINNED, numPinned);
1246         result.put(KEY_BITMAPS, numBitmaps);
1247         result.put(KEY_BITMAP_BYTES, totalBitmapSize);
1248
1249         // TODO Log update frequency too.
1250
1251         return result;
1252     }
1253
1254     @Override
1255     public void saveToXml(@NonNull XmlSerializer out, boolean forBackup)
1256             throws IOException, XmlPullParserException {
1257         final int size = mShortcuts.size();
1258
1259         if (size == 0 && mApiCallCount == 0) {
1260             return; // nothing to write.
1261         }
1262
1263         out.startTag(null, TAG_ROOT);
1264
1265         ShortcutService.writeAttr(out, ATTR_NAME, getPackageName());
1266         ShortcutService.writeAttr(out, ATTR_CALL_COUNT, mApiCallCount);
1267         ShortcutService.writeAttr(out, ATTR_LAST_RESET, mLastResetTime);
1268         getPackageInfo().saveToXml(out);
1269
1270         for (int j = 0; j < size; j++) {
1271             saveShortcut(out, mShortcuts.valueAt(j), forBackup);
1272         }
1273
1274         out.endTag(null, TAG_ROOT);
1275     }
1276
1277     private static void saveShortcut(XmlSerializer out, ShortcutInfo si, boolean forBackup)
1278             throws IOException, XmlPullParserException {
1279         if (forBackup) {
1280             if (!(si.isPinned() && si.isEnabled())) {
1281                 return; // We only backup pinned shortcuts that are enabled.
1282             }
1283         }
1284         out.startTag(null, TAG_SHORTCUT);
1285         ShortcutService.writeAttr(out, ATTR_ID, si.getId());
1286         // writeAttr(out, "package", si.getPackageName()); // not needed
1287         ShortcutService.writeAttr(out, ATTR_ACTIVITY, si.getActivity());
1288         // writeAttr(out, "icon", si.getIcon());  // We don't save it.
1289         ShortcutService.writeAttr(out, ATTR_TITLE, si.getTitle());
1290         ShortcutService.writeAttr(out, ATTR_TITLE_RES_ID, si.getTitleResId());
1291         ShortcutService.writeAttr(out, ATTR_TITLE_RES_NAME, si.getTitleResName());
1292         ShortcutService.writeAttr(out, ATTR_TEXT, si.getText());
1293         ShortcutService.writeAttr(out, ATTR_TEXT_RES_ID, si.getTextResId());
1294         ShortcutService.writeAttr(out, ATTR_TEXT_RES_NAME, si.getTextResName());
1295         ShortcutService.writeAttr(out, ATTR_DISABLED_MESSAGE, si.getDisabledMessage());
1296         ShortcutService.writeAttr(out, ATTR_DISABLED_MESSAGE_RES_ID,
1297                 si.getDisabledMessageResourceId());
1298         ShortcutService.writeAttr(out, ATTR_DISABLED_MESSAGE_RES_NAME,
1299                 si.getDisabledMessageResName());
1300         ShortcutService.writeAttr(out, ATTR_TIMESTAMP,
1301                 si.getLastChangedTimestamp());
1302         if (forBackup) {
1303             // Don't write icon information.  Also drop the dynamic flag.
1304             ShortcutService.writeAttr(out, ATTR_FLAGS,
1305                     si.getFlags() &
1306                             ~(ShortcutInfo.FLAG_HAS_ICON_FILE | ShortcutInfo.FLAG_HAS_ICON_RES
1307                             | ShortcutInfo.FLAG_DYNAMIC));
1308         } else {
1309             // When writing for backup, ranks shouldn't be saved, since shortcuts won't be restored
1310             // as dynamic.
1311             ShortcutService.writeAttr(out, ATTR_RANK, si.getRank());
1312
1313             ShortcutService.writeAttr(out, ATTR_FLAGS, si.getFlags());
1314             ShortcutService.writeAttr(out, ATTR_ICON_RES_ID, si.getIconResourceId());
1315             ShortcutService.writeAttr(out, ATTR_ICON_RES_NAME, si.getIconResName());
1316             ShortcutService.writeAttr(out, ATTR_BITMAP_PATH, si.getBitmapPath());
1317         }
1318
1319         {
1320             final Set<String> cat = si.getCategories();
1321             if (cat != null && cat.size() > 0) {
1322                 out.startTag(null, TAG_CATEGORIES);
1323                 XmlUtils.writeStringArrayXml(cat.toArray(new String[cat.size()]),
1324                         NAME_CATEGORIES, out);
1325                 out.endTag(null, TAG_CATEGORIES);
1326             }
1327         }
1328         final Intent[] intentsNoExtras = si.getIntentsNoExtras();
1329         final PersistableBundle[] intentsExtras = si.getIntentPersistableExtrases();
1330         final int numIntents = intentsNoExtras.length;
1331         for (int i = 0; i < numIntents; i++) {
1332             out.startTag(null, TAG_INTENT);
1333             ShortcutService.writeAttr(out, ATTR_INTENT_NO_EXTRA, intentsNoExtras[i]);
1334             ShortcutService.writeTagExtra(out, TAG_EXTRAS, intentsExtras[i]);
1335             out.endTag(null, TAG_INTENT);
1336         }
1337
1338         ShortcutService.writeTagExtra(out, TAG_EXTRAS, si.getExtras());
1339
1340         out.endTag(null, TAG_SHORTCUT);
1341     }
1342
1343     public static ShortcutPackage loadFromXml(ShortcutService s, ShortcutUser shortcutUser,
1344             XmlPullParser parser, boolean fromBackup)
1345             throws IOException, XmlPullParserException {
1346
1347         final String packageName = ShortcutService.parseStringAttribute(parser,
1348                 ATTR_NAME);
1349
1350         final ShortcutPackage ret = new ShortcutPackage(shortcutUser,
1351                 shortcutUser.getUserId(), packageName);
1352
1353         ret.mApiCallCount =
1354                 ShortcutService.parseIntAttribute(parser, ATTR_CALL_COUNT);
1355         ret.mLastResetTime =
1356                 ShortcutService.parseLongAttribute(parser, ATTR_LAST_RESET);
1357
1358         final int outerDepth = parser.getDepth();
1359         int type;
1360         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1361                 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1362             if (type != XmlPullParser.START_TAG) {
1363                 continue;
1364             }
1365             final int depth = parser.getDepth();
1366             final String tag = parser.getName();
1367             if (depth == outerDepth + 1) {
1368                 switch (tag) {
1369                     case ShortcutPackageInfo.TAG_ROOT:
1370                         ret.getPackageInfo().loadFromXml(parser, fromBackup);
1371                         continue;
1372                     case TAG_SHORTCUT:
1373                         final ShortcutInfo si = parseShortcut(parser, packageName,
1374                                 shortcutUser.getUserId());
1375
1376                         // Don't use addShortcut(), we don't need to save the icon.
1377                         ret.mShortcuts.put(si.getId(), si);
1378                         continue;
1379                 }
1380             }
1381             ShortcutService.warnForInvalidTag(depth, tag);
1382         }
1383         return ret;
1384     }
1385
1386     private static ShortcutInfo parseShortcut(XmlPullParser parser, String packageName,
1387             @UserIdInt int userId) throws IOException, XmlPullParserException {
1388         String id;
1389         ComponentName activityComponent;
1390         // Icon icon;
1391         String title;
1392         int titleResId;
1393         String titleResName;
1394         String text;
1395         int textResId;
1396         String textResName;
1397         String disabledMessage;
1398         int disabledMessageResId;
1399         String disabledMessageResName;
1400         Intent intentLegacy;
1401         PersistableBundle intentPersistableExtrasLegacy = null;
1402         ArrayList<Intent> intents = new ArrayList<>();
1403         int rank;
1404         PersistableBundle extras = null;
1405         long lastChangedTimestamp;
1406         int flags;
1407         int iconResId;
1408         String iconResName;
1409         String bitmapPath;
1410         ArraySet<String> categories = null;
1411
1412         id = ShortcutService.parseStringAttribute(parser, ATTR_ID);
1413         activityComponent = ShortcutService.parseComponentNameAttribute(parser,
1414                 ATTR_ACTIVITY);
1415         title = ShortcutService.parseStringAttribute(parser, ATTR_TITLE);
1416         titleResId = ShortcutService.parseIntAttribute(parser, ATTR_TITLE_RES_ID);
1417         titleResName = ShortcutService.parseStringAttribute(parser, ATTR_TITLE_RES_NAME);
1418         text = ShortcutService.parseStringAttribute(parser, ATTR_TEXT);
1419         textResId = ShortcutService.parseIntAttribute(parser, ATTR_TEXT_RES_ID);
1420         textResName = ShortcutService.parseStringAttribute(parser, ATTR_TEXT_RES_NAME);
1421         disabledMessage = ShortcutService.parseStringAttribute(parser, ATTR_DISABLED_MESSAGE);
1422         disabledMessageResId = ShortcutService.parseIntAttribute(parser,
1423                 ATTR_DISABLED_MESSAGE_RES_ID);
1424         disabledMessageResName = ShortcutService.parseStringAttribute(parser,
1425                 ATTR_DISABLED_MESSAGE_RES_NAME);
1426         intentLegacy = ShortcutService.parseIntentAttributeNoDefault(parser, ATTR_INTENT_LEGACY);
1427         rank = (int) ShortcutService.parseLongAttribute(parser, ATTR_RANK);
1428         lastChangedTimestamp = ShortcutService.parseLongAttribute(parser, ATTR_TIMESTAMP);
1429         flags = (int) ShortcutService.parseLongAttribute(parser, ATTR_FLAGS);
1430         iconResId = (int) ShortcutService.parseLongAttribute(parser, ATTR_ICON_RES_ID);
1431         iconResName = ShortcutService.parseStringAttribute(parser, ATTR_ICON_RES_NAME);
1432         bitmapPath = ShortcutService.parseStringAttribute(parser, ATTR_BITMAP_PATH);
1433
1434         final int outerDepth = parser.getDepth();
1435         int type;
1436         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1437                 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1438             if (type != XmlPullParser.START_TAG) {
1439                 continue;
1440             }
1441             final int depth = parser.getDepth();
1442             final String tag = parser.getName();
1443             if (ShortcutService.DEBUG_LOAD) {
1444                 Slog.d(TAG, String.format("  depth=%d type=%d name=%s",
1445                         depth, type, tag));
1446             }
1447             switch (tag) {
1448                 case TAG_INTENT_EXTRAS_LEGACY:
1449                     intentPersistableExtrasLegacy = PersistableBundle.restoreFromXml(parser);
1450                     continue;
1451                 case TAG_INTENT:
1452                     intents.add(parseIntent(parser));
1453                     continue;
1454                 case TAG_EXTRAS:
1455                     extras = PersistableBundle.restoreFromXml(parser);
1456                     continue;
1457                 case TAG_CATEGORIES:
1458                     // This just contains string-array.
1459                     continue;
1460                 case TAG_STRING_ARRAY_XMLUTILS:
1461                     if (NAME_CATEGORIES.equals(ShortcutService.parseStringAttribute(parser,
1462                             ATTR_NAME_XMLUTILS))) {
1463                         final String[] ar = XmlUtils.readThisStringArrayXml(
1464                                 parser, TAG_STRING_ARRAY_XMLUTILS, null);
1465                         categories = new ArraySet<>(ar.length);
1466                         for (int i = 0; i < ar.length; i++) {
1467                             categories.add(ar[i]);
1468                         }
1469                     }
1470                     continue;
1471             }
1472             throw ShortcutService.throwForInvalidTag(depth, tag);
1473         }
1474
1475         if (intentLegacy != null) {
1476             // For the legacy file format which supported only one intent per shortcut.
1477             ShortcutInfo.setIntentExtras(intentLegacy, intentPersistableExtrasLegacy);
1478             intents.clear();
1479             intents.add(intentLegacy);
1480         }
1481
1482         return new ShortcutInfo(
1483                 userId, id, packageName, activityComponent, /* icon =*/ null,
1484                 title, titleResId, titleResName, text, textResId, textResName,
1485                 disabledMessage, disabledMessageResId, disabledMessageResName,
1486                 categories,
1487                 intents.toArray(new Intent[intents.size()]),
1488                 rank, extras, lastChangedTimestamp, flags,
1489                 iconResId, iconResName, bitmapPath);
1490     }
1491
1492     private static Intent parseIntent(XmlPullParser parser)
1493             throws IOException, XmlPullParserException {
1494
1495         Intent intent = ShortcutService.parseIntentAttribute(parser,
1496                 ATTR_INTENT_NO_EXTRA);
1497
1498         final int outerDepth = parser.getDepth();
1499         int type;
1500         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1501                 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1502             if (type != XmlPullParser.START_TAG) {
1503                 continue;
1504             }
1505             final int depth = parser.getDepth();
1506             final String tag = parser.getName();
1507             if (ShortcutService.DEBUG_LOAD) {
1508                 Slog.d(TAG, String.format("  depth=%d type=%d name=%s",
1509                         depth, type, tag));
1510             }
1511             switch (tag) {
1512                 case TAG_EXTRAS:
1513                     ShortcutInfo.setIntentExtras(intent,
1514                             PersistableBundle.restoreFromXml(parser));
1515                     continue;
1516             }
1517             throw ShortcutService.throwForInvalidTag(depth, tag);
1518         }
1519         return intent;
1520     }
1521
1522     @VisibleForTesting
1523     List<ShortcutInfo> getAllShortcutsForTest() {
1524         return new ArrayList<>(mShortcuts.values());
1525     }
1526
1527     @Override
1528     public void verifyStates() {
1529         super.verifyStates();
1530
1531         boolean failed = false;
1532
1533         final ArrayMap<ComponentName, ArrayList<ShortcutInfo>> all =
1534                 sortShortcutsToActivities();
1535
1536         // Make sure each activity won't have more than max shortcuts.
1537         for (int outer = all.size() - 1; outer >= 0; outer--) {
1538             final ArrayList<ShortcutInfo> list = all.valueAt(outer);
1539             if (list.size() > mShortcutUser.mService.getMaxActivityShortcuts()) {
1540                 failed = true;
1541                 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": activity " + all.keyAt(outer)
1542                         + " has " + all.valueAt(outer).size() + " shortcuts.");
1543             }
1544
1545             // Sort by rank.
1546             Collections.sort(list, (a, b) -> Integer.compare(a.getRank(), b.getRank()));
1547
1548             // Split into two arrays for each kind.
1549             final ArrayList<ShortcutInfo> dynamicList = new ArrayList<>(list);
1550             dynamicList.removeIf((si) -> !si.isDynamic());
1551
1552             final ArrayList<ShortcutInfo> manifestList = new ArrayList<>(list);
1553             dynamicList.removeIf((si) -> !si.isManifestShortcut());
1554
1555             verifyRanksSequential(dynamicList);
1556             verifyRanksSequential(manifestList);
1557         }
1558
1559         // Verify each shortcut's status.
1560         for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1561             final ShortcutInfo si = mShortcuts.valueAt(i);
1562             if (!(si.isDeclaredInManifest() || si.isDynamic() || si.isPinned())) {
1563                 failed = true;
1564                 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1565                         + " is not manifest, dynamic or pinned.");
1566             }
1567             if (si.isDeclaredInManifest() && si.isDynamic()) {
1568                 failed = true;
1569                 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1570                         + " is both dynamic and manifest at the same time.");
1571             }
1572             if (si.getActivity() == null) {
1573                 failed = true;
1574                 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1575                         + " has null activity.");
1576             }
1577             if ((si.isDynamic() || si.isManifestShortcut()) && !si.isEnabled()) {
1578                 failed = true;
1579                 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1580                         + " is not floating, but is disabled.");
1581             }
1582             if (si.isFloating() && si.getRank() != 0) {
1583                 failed = true;
1584                 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1585                         + " is floating, but has rank=" + si.getRank());
1586             }
1587             if (si.getIcon() != null) {
1588                 failed = true;
1589                 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1590                         + " still has an icon");
1591             }
1592             if (si.hasIconFile() && si.hasIconResource()) {
1593                 failed = true;
1594                 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1595                         + " has both resource and bitmap icons");
1596             }
1597         }
1598
1599         if (failed) {
1600             throw new IllegalStateException("See logcat for errors");
1601         }
1602     }
1603
1604     private boolean verifyRanksSequential(List<ShortcutInfo> list) {
1605         boolean failed = false;
1606
1607         for (int i = 0; i < list.size(); i++) {
1608             final ShortcutInfo si = list.get(i);
1609             if (si.getRank() != i) {
1610                 failed = true;
1611                 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1612                         + " rank=" + si.getRank() + " but expected to be "+ i);
1613             }
1614         }
1615         return failed;
1616     }
1617 }