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