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