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