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