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