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