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