ShortcutPackage.java revision 84d5934ca0097827cc2ab323b94596064080fd23
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.forAllLaunchers(launcherShortcuts -> {
463            final ArraySet<String> pinned = launcherShortcuts.getPinnedShortcutIds(
464                    getPackageName(), getPackageUserId());
465
466            if (pinned == null || pinned.size() == 0) {
467                return;
468            }
469            for (int i = pinned.size() - 1; i >= 0; i--) {
470                final String id = pinned.valueAt(i);
471                final ShortcutInfo si = mShortcuts.get(id);
472                if (si == null) {
473                    // This happens if a launcher pinned shortcuts from this package, then backup&
474                    // restored, but this package doesn't allow backing up.
475                    // In that case the launcher ends up having a dangling pinned shortcuts.
476                    // That's fine, when the launcher is restored, we'll fix it.
477                    continue;
478                }
479                si.addFlags(ShortcutInfo.FLAG_PINNED);
480            }
481        });
482
483        // Lastly, remove the ones that are no longer pinned nor dynamic.
484        removeOrphans();
485    }
486
487    /**
488     * Number of calls that the caller has made, since the last reset.
489     *
490     * <p>This takes care of the resetting the counter for foreground apps as well as after
491     * locale changes.
492     */
493    public int getApiCallCount() {
494        final ShortcutService s = mShortcutUser.mService;
495
496        // Reset the counter if:
497        // - the package is in foreground now.
498        // - the package is *not* in foreground now, but was in foreground at some point
499        // since the previous time it had been.
500        if (s.isUidForegroundLocked(mPackageUid)
501                || mLastKnownForegroundElapsedTime
502                    < s.getUidLastForegroundElapsedTimeLocked(mPackageUid)) {
503            mLastKnownForegroundElapsedTime = s.injectElapsedRealtime();
504            resetRateLimiting();
505        }
506
507        // Note resetThrottlingIfNeeded() and resetRateLimiting() will set 0 to mApiCallCount,
508        // but we just can't return 0 at this point, because we may have to update
509        // mLastResetTime.
510
511        final long last = s.getLastResetTimeLocked();
512
513        final long now = s.injectCurrentTimeMillis();
514        if (ShortcutService.isClockValid(now) && mLastResetTime > now) {
515            Slog.w(TAG, "Clock rewound");
516            // Clock rewound.
517            mLastResetTime = now;
518            mApiCallCount = 0;
519            return mApiCallCount;
520        }
521
522        // If not reset yet, then reset.
523        if (mLastResetTime < last) {
524            if (ShortcutService.DEBUG) {
525                Slog.d(TAG, String.format("%s: last reset=%d, now=%d, last=%d: resetting",
526                        getPackageName(), mLastResetTime, now, last));
527            }
528            mApiCallCount = 0;
529            mLastResetTime = last;
530        }
531        return mApiCallCount;
532    }
533
534    /**
535     * If the caller app hasn't been throttled yet, increment {@link #mApiCallCount}
536     * and return true.  Otherwise just return false.
537     *
538     * <p>This takes care of the resetting the counter for foreground apps as well as after
539     * locale changes, which is done internally by {@link #getApiCallCount}.
540     */
541    public boolean tryApiCall() {
542        final ShortcutService s = mShortcutUser.mService;
543
544        if (getApiCallCount() >= s.mMaxUpdatesPerInterval) {
545            return false;
546        }
547        mApiCallCount++;
548        s.scheduleSaveUser(getOwnerUserId());
549        return true;
550    }
551
552    public void resetRateLimiting() {
553        if (ShortcutService.DEBUG) {
554            Slog.d(TAG, "resetRateLimiting: " + getPackageName());
555        }
556        if (mApiCallCount > 0) {
557            mApiCallCount = 0;
558            mShortcutUser.mService.scheduleSaveUser(getOwnerUserId());
559        }
560    }
561
562    public void resetRateLimitingForCommandLineNoSaving() {
563        mApiCallCount = 0;
564        mLastResetTime = 0;
565    }
566
567    /**
568     * Find all shortcuts that match {@code query}.
569     */
570    public void findAll(@NonNull List<ShortcutInfo> result,
571            @Nullable Predicate<ShortcutInfo> query, int cloneFlag) {
572        findAll(result, query, cloneFlag, null, 0, /*getPinnedByAnyLauncher=*/ false);
573    }
574
575    /**
576     * Find all shortcuts that match {@code query}.
577     *
578     * This will also provide a "view" for each launcher -- a non-dynamic shortcut that's not pinned
579     * by the calling launcher will not be included in the result, and also "isPinned" will be
580     * adjusted for the caller too.
581     */
582    public void findAll(@NonNull List<ShortcutInfo> result,
583            @Nullable Predicate<ShortcutInfo> query, int cloneFlag,
584            @Nullable String callingLauncher, int launcherUserId, boolean getPinnedByAnyLauncher) {
585        if (getPackageInfo().isShadow()) {
586            // Restored and the app not installed yet, so don't return any.
587            return;
588        }
589
590        final ShortcutService s = mShortcutUser.mService;
591
592        // Set of pinned shortcuts by the calling launcher.
593        final ArraySet<String> pinnedByCallerSet = (callingLauncher == null) ? null
594                : s.getLauncherShortcutsLocked(callingLauncher, getPackageUserId(), launcherUserId)
595                    .getPinnedShortcutIds(getPackageName(), getPackageUserId());
596
597        for (int i = 0; i < mShortcuts.size(); i++) {
598            final ShortcutInfo si = mShortcuts.valueAt(i);
599
600            // Need to adjust PINNED flag depending on the caller.
601            // Basically if the caller is a launcher (callingLauncher != null) and the launcher
602            // isn't pinning it, then we need to clear PINNED for this caller.
603            final boolean isPinnedByCaller = (callingLauncher == null)
604                    || ((pinnedByCallerSet != null) && pinnedByCallerSet.contains(si.getId()));
605
606            if (!getPinnedByAnyLauncher) {
607                if (si.isFloating()) {
608                    if (!isPinnedByCaller) {
609                        continue;
610                    }
611                }
612            }
613            final ShortcutInfo clone = si.clone(cloneFlag);
614
615            // Fix up isPinned for the caller.  Note we need to do it before the "test" callback,
616            // since it may check isPinned.
617            // However, if getPinnedByAnyLauncher is set, we do it after the test.
618            if (!getPinnedByAnyLauncher) {
619                if (!isPinnedByCaller) {
620                    clone.clearFlags(ShortcutInfo.FLAG_PINNED);
621                }
622            }
623            if (query == null || query.test(clone)) {
624                if (!isPinnedByCaller) {
625                    clone.clearFlags(ShortcutInfo.FLAG_PINNED);
626                }
627                result.add(clone);
628            }
629        }
630    }
631
632    public void resetThrottling() {
633        mApiCallCount = 0;
634    }
635
636    /**
637     * Return the filenames (excluding path names) of icon bitmap files from this package.
638     */
639    public ArraySet<String> getUsedBitmapFiles() {
640        final ArraySet<String> usedFiles = new ArraySet<>(mShortcuts.size());
641
642        for (int i = mShortcuts.size() - 1; i >= 0; i--) {
643            final ShortcutInfo si = mShortcuts.valueAt(i);
644            if (si.getBitmapPath() != null) {
645                usedFiles.add(getFileName(si.getBitmapPath()));
646            }
647        }
648        return usedFiles;
649    }
650
651    private static String getFileName(@NonNull String path) {
652        final int sep = path.lastIndexOf(File.separatorChar);
653        if (sep == -1) {
654            return path;
655        } else {
656            return path.substring(sep + 1);
657        }
658    }
659
660    /**
661     * @return false if any of the target activities are no longer enabled.
662     */
663    private boolean areAllActivitiesStillEnabled() {
664        if (mShortcuts.size() == 0) {
665            return true;
666        }
667        final ShortcutService s = mShortcutUser.mService;
668
669        // Normally the number of target activities is 1 or so, so no need to use a complex
670        // structure like a set.
671        final ArrayList<ComponentName> checked = new ArrayList<>(4);
672
673        for (int i = mShortcuts.size() - 1; i >= 0; i--) {
674            final ShortcutInfo si = mShortcuts.valueAt(i);
675            final ComponentName activity = si.getActivity();
676
677            if (checked.contains(activity)) {
678                continue; // Already checked.
679            }
680            checked.add(activity);
681
682            if ((activity != null)
683                    && !s.injectIsActivityEnabledAndExported(activity, getOwnerUserId())) {
684                return false;
685            }
686        }
687        return true;
688    }
689
690    /**
691     * Called when the package may be added or updated, or its activities may be disabled, and
692     * if so, rescan the package and do the necessary stuff.
693     *
694     * Add case:
695     * - Publish manifest shortcuts.
696     *
697     * Update case:
698     * - Re-publish manifest shortcuts.
699     * - If there are shortcuts with resources (icons or strings), update their timestamps.
700     * - Disable shortcuts whose target activities are disabled.
701     *
702     * @return TRUE if any shortcuts have been changed.
703     */
704    public boolean rescanPackageIfNeeded(boolean isNewApp, boolean forceRescan) {
705        final ShortcutService s = mShortcutUser.mService;
706        final long start = s.getStatStartTime();
707
708        final PackageInfo pi;
709        try {
710            pi = mShortcutUser.mService.getPackageInfo(
711                    getPackageName(), getPackageUserId());
712            if (pi == null) {
713                return false; // Shouldn't happen.
714            }
715
716            if (!isNewApp && !forceRescan) {
717                // Return if the package hasn't changed, ie:
718                // - version code hasn't change
719                // - lastUpdateTime hasn't change
720                // - all target activities are still enabled.
721
722                // Note, system apps timestamps do *not* change after OTAs.  (But they do
723                // after an adb sync or a local flash.)
724                // This means if a system app's version code doesn't change on an OTA,
725                // we don't notice it's updated.  But that's fine since their version code *should*
726                // really change on OTAs.
727                if ((getPackageInfo().getVersionCode() == pi.getLongVersionCode())
728                        && (getPackageInfo().getLastUpdateTime() == pi.lastUpdateTime)
729                        && areAllActivitiesStillEnabled()) {
730                    return false;
731                }
732            }
733        } finally {
734            s.logDurationStat(Stats.PACKAGE_UPDATE_CHECK, start);
735        }
736
737        // Now prepare to publish manifest shortcuts.
738        List<ShortcutInfo> newManifestShortcutList = null;
739        try {
740            newManifestShortcutList = ShortcutParser.parseShortcuts(mShortcutUser.mService,
741                    getPackageName(), getPackageUserId());
742        } catch (IOException|XmlPullParserException e) {
743            Slog.e(TAG, "Failed to load shortcuts from AndroidManifest.xml.", e);
744        }
745        final int manifestShortcutSize = newManifestShortcutList == null ? 0
746                : newManifestShortcutList.size();
747        if (ShortcutService.DEBUG) {
748            Slog.d(TAG, String.format("Package %s has %d manifest shortcut(s)",
749                    getPackageName(), manifestShortcutSize));
750        }
751        if (isNewApp && (manifestShortcutSize == 0)) {
752            // If it's a new app, and it doesn't have manifest shortcuts, then nothing to do.
753
754            // If it's an update, then it may already have manifest shortcuts, which need to be
755            // disabled.
756            return false;
757        }
758        if (ShortcutService.DEBUG) {
759            Slog.d(TAG, String.format("Package %s %s, version %d -> %d", getPackageName(),
760                    (isNewApp ? "added" : "updated"),
761                    getPackageInfo().getVersionCode(), pi.getLongVersionCode()));
762        }
763
764        getPackageInfo().updateFromPackageInfo(pi);
765        final long newVersionCode = getPackageInfo().getVersionCode();
766
767        // See if there are any shortcuts that were prevented restoring because the app was of a
768        // lower version, and re-enable them.
769        for (int i = mShortcuts.size() - 1; i >= 0; i--) {
770            final ShortcutInfo si = mShortcuts.valueAt(i);
771            if (si.getDisabledReason() != ShortcutInfo.DISABLED_REASON_VERSION_LOWER) {
772                continue;
773            }
774            if (getPackageInfo().getBackupSourceVersionCode() > newVersionCode) {
775                if (ShortcutService.DEBUG) {
776                    Slog.d(TAG, String.format("Shortcut %s require version %s, still not restored.",
777                            si.getId(), getPackageInfo().getBackupSourceVersionCode()));
778                }
779                continue;
780            }
781            Slog.i(TAG, String.format("Restoring shortcut: %s", si.getId()));
782            si.clearFlags(ShortcutInfo.FLAG_DISABLED);
783            si.setDisabledReason(ShortcutInfo.DISABLED_REASON_NOT_DISABLED);
784        }
785
786        // For existing shortcuts, update timestamps if they have any resources.
787        // Also check if shortcuts' activities are still main activities.  Otherwise, disable them.
788        if (!isNewApp) {
789            Resources publisherRes = null;
790
791            for (int i = mShortcuts.size() - 1; i >= 0; i--) {
792                final ShortcutInfo si = mShortcuts.valueAt(i);
793
794                // Disable dynamic shortcuts whose target activity is gone.
795                if (si.isDynamic()) {
796                    if (si.getActivity() == null) {
797                        // Note if it's dynamic, it must have a target activity, but b/36228253.
798                        s.wtf("null activity detected.");
799                        // TODO Maybe remove it?
800                    } else if (!s.injectIsMainActivity(si.getActivity(), getPackageUserId())) {
801                        Slog.w(TAG, String.format(
802                                "%s is no longer main activity. Disabling shorcut %s.",
803                                getPackageName(), si.getId()));
804                        if (disableDynamicWithId(si.getId(), /*ignoreInvisible*/ false,
805                                ShortcutInfo.DISABLED_REASON_APP_CHANGED)) {
806                            continue; // Actually removed.
807                        }
808                        // Still pinned, so fall-through and possibly update the resources.
809                    }
810                }
811
812                if (si.hasAnyResources()) {
813                    if (!si.isOriginallyFromManifest()) {
814                        if (publisherRes == null) {
815                            publisherRes = getPackageResources();
816                            if (publisherRes == null) {
817                                break; // Resources couldn't be loaded.
818                            }
819                        }
820
821                        // If this shortcut is not from a manifest, then update all resource IDs
822                        // from resource names.  (We don't allow resource strings for
823                        // non-manifest at the moment, but icons can still be resources.)
824                        si.lookupAndFillInResourceIds(publisherRes);
825                    }
826                    si.setTimestamp(s.injectCurrentTimeMillis());
827                }
828            }
829        }
830
831        // (Re-)publish manifest shortcut.
832        publishManifestShortcuts(newManifestShortcutList);
833
834        if (newManifestShortcutList != null) {
835            pushOutExcessShortcuts();
836        }
837
838        s.verifyStates();
839
840        // This will send a notification to the launcher, and also save .
841        s.packageShortcutsChanged(getPackageName(), getPackageUserId());
842        return true; // true means changed.
843    }
844
845    private boolean publishManifestShortcuts(List<ShortcutInfo> newManifestShortcutList) {
846        if (ShortcutService.DEBUG) {
847            Slog.d(TAG, String.format(
848                    "Package %s: publishing manifest shortcuts", getPackageName()));
849        }
850        boolean changed = false;
851
852        // Keep the previous IDs.
853        ArraySet<String> toDisableList = null;
854        for (int i = mShortcuts.size() - 1; i >= 0; i--) {
855            final ShortcutInfo si = mShortcuts.valueAt(i);
856
857            if (si.isManifestShortcut()) {
858                if (toDisableList == null) {
859                    toDisableList = new ArraySet<>();
860                }
861                toDisableList.add(si.getId());
862            }
863        }
864
865        // Publish new ones.
866        if (newManifestShortcutList != null) {
867            final int newListSize = newManifestShortcutList.size();
868
869            for (int i = 0; i < newListSize; i++) {
870                changed = true;
871
872                final ShortcutInfo newShortcut = newManifestShortcutList.get(i);
873                final boolean newDisabled = !newShortcut.isEnabled();
874
875                final String id = newShortcut.getId();
876                final ShortcutInfo oldShortcut = mShortcuts.get(id);
877
878                boolean wasPinned = false;
879
880                if (oldShortcut != null) {
881                    if (!oldShortcut.isOriginallyFromManifest()) {
882                        Slog.e(TAG, "Shortcut with ID=" + newShortcut.getId()
883                                + " exists but is not from AndroidManifest.xml, not updating.");
884                        continue;
885                    }
886                    // Take over the pinned flag.
887                    if (oldShortcut.isPinned()) {
888                        wasPinned = true;
889                        newShortcut.addFlags(ShortcutInfo.FLAG_PINNED);
890                    }
891                }
892                if (newDisabled && !wasPinned) {
893                    // If the shortcut is disabled, and it was *not* pinned, then this
894                    // just doesn't have to be published.
895                    // Just keep it in toDisableList, so the previous one would be removed.
896                    continue;
897                }
898
899                // Note even if enabled=false, we still need to update all fields, so do it
900                // regardless.
901                forceReplaceShortcutInner(newShortcut); // This will clean up the old one too.
902
903                if (!newDisabled && toDisableList != null) {
904                    // Still alive, don't remove.
905                    toDisableList.remove(id);
906                }
907            }
908        }
909
910        // Disable the previous manifest shortcuts that are no longer in the manifest.
911        if (toDisableList != null) {
912            if (ShortcutService.DEBUG) {
913                Slog.d(TAG, String.format(
914                        "Package %s: disabling %d stale shortcuts", getPackageName(),
915                        toDisableList.size()));
916            }
917            for (int i = toDisableList.size() - 1; i >= 0; i--) {
918                changed = true;
919
920                final String id = toDisableList.valueAt(i);
921
922                disableWithId(id, /* disable message =*/ null, /* disable message resid */ 0,
923                        /* overrideImmutable=*/ true, /*ignoreInvisible=*/ false,
924                        ShortcutInfo.DISABLED_REASON_APP_CHANGED);
925            }
926            removeOrphans();
927        }
928        adjustRanks();
929        return changed;
930    }
931
932    /**
933     * For each target activity, make sure # of dynamic + manifest shortcuts <= max.
934     * If too many, we'll remove the dynamic with the lowest ranks.
935     */
936    private boolean pushOutExcessShortcuts() {
937        final ShortcutService service = mShortcutUser.mService;
938        final int maxShortcuts = service.getMaxActivityShortcuts();
939
940        boolean changed = false;
941
942        final ArrayMap<ComponentName, ArrayList<ShortcutInfo>> all =
943                sortShortcutsToActivities();
944        for (int outer = all.size() - 1; outer >= 0; outer--) {
945            final ArrayList<ShortcutInfo> list = all.valueAt(outer);
946            if (list.size() <= maxShortcuts) {
947                continue;
948            }
949            // Sort by isManifestShortcut() and getRank().
950            Collections.sort(list, mShortcutTypeAndRankComparator);
951
952            // Keep [0 .. max), and remove (as dynamic) [max .. size)
953            for (int inner = list.size() - 1; inner >= maxShortcuts; inner--) {
954                final ShortcutInfo shortcut = list.get(inner);
955
956                if (shortcut.isManifestShortcut()) {
957                    // This shouldn't happen -- excess shortcuts should all be non-manifest.
958                    // But just in case.
959                    service.wtf("Found manifest shortcuts in excess list.");
960                    continue;
961                }
962                deleteDynamicWithId(shortcut.getId(), /*ignoreInvisible=*/ true);
963            }
964        }
965
966        return changed;
967    }
968
969    /**
970     * To sort by isManifestShortcut() and getRank(). i.e.  manifest shortcuts come before
971     * non-manifest shortcuts, then sort by rank.
972     *
973     * This is used to decide which dynamic shortcuts to remove when an upgraded version has more
974     * manifest shortcuts than before and as a result we need to remove some of the dynamic
975     * shortcuts.  We sort manifest + dynamic shortcuts by this order, and remove the ones with
976     * the last ones.
977     *
978     * (Note the number of manifest shortcuts is always <= the max number, because if there are
979     * more, ShortcutParser would ignore the rest.)
980     */
981    final Comparator<ShortcutInfo> mShortcutTypeAndRankComparator = (ShortcutInfo a,
982            ShortcutInfo b) -> {
983        if (a.isManifestShortcut() && !b.isManifestShortcut()) {
984            return -1;
985        }
986        if (!a.isManifestShortcut() && b.isManifestShortcut()) {
987            return 1;
988        }
989        return Integer.compare(a.getRank(), b.getRank());
990    };
991
992    /**
993     * Build a list of shortcuts for each target activity and return as a map. The result won't
994     * contain "floating" shortcuts because they don't belong on any activities.
995     */
996    private ArrayMap<ComponentName, ArrayList<ShortcutInfo>> sortShortcutsToActivities() {
997        final ArrayMap<ComponentName, ArrayList<ShortcutInfo>> activitiesToShortcuts
998                = new ArrayMap<>();
999        for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1000            final ShortcutInfo si = mShortcuts.valueAt(i);
1001            if (si.isFloating()) {
1002                continue; // Ignore floating shortcuts, which are not tied to any activities.
1003            }
1004
1005            final ComponentName activity = si.getActivity();
1006            if (activity == null) {
1007                mShortcutUser.mService.wtf("null activity detected.");
1008                continue;
1009            }
1010
1011            ArrayList<ShortcutInfo> list = activitiesToShortcuts.get(activity);
1012            if (list == null) {
1013                list = new ArrayList<>();
1014                activitiesToShortcuts.put(activity, list);
1015            }
1016            list.add(si);
1017        }
1018        return activitiesToShortcuts;
1019    }
1020
1021    /** Used by {@link #enforceShortcutCountsBeforeOperation} */
1022    private void incrementCountForActivity(ArrayMap<ComponentName, Integer> counts,
1023            ComponentName cn, int increment) {
1024        Integer oldValue = counts.get(cn);
1025        if (oldValue == null) {
1026            oldValue = 0;
1027        }
1028
1029        counts.put(cn, oldValue + increment);
1030    }
1031
1032    /**
1033     * Called by
1034     * {@link android.content.pm.ShortcutManager#setDynamicShortcuts},
1035     * {@link android.content.pm.ShortcutManager#addDynamicShortcuts}, and
1036     * {@link android.content.pm.ShortcutManager#updateShortcuts} before actually performing
1037     * the operation to make sure the operation wouldn't result in the target activities having
1038     * more than the allowed number of dynamic/manifest shortcuts.
1039     *
1040     * @param newList shortcut list passed to set, add or updateShortcuts().
1041     * @param operation add, set or update.
1042     * @throws IllegalArgumentException if the operation would result in going over the max
1043     *                                  shortcut count for any activity.
1044     */
1045    public void enforceShortcutCountsBeforeOperation(List<ShortcutInfo> newList,
1046            @ShortcutOperation int operation) {
1047        final ShortcutService service = mShortcutUser.mService;
1048
1049        // Current # of dynamic / manifest shortcuts for each activity.
1050        // (If it's for update, then don't count dynamic shortcuts, since they'll be replaced
1051        // anyway.)
1052        final ArrayMap<ComponentName, Integer> counts = new ArrayMap<>(4);
1053        for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1054            final ShortcutInfo shortcut = mShortcuts.valueAt(i);
1055
1056            if (shortcut.isManifestShortcut()) {
1057                incrementCountForActivity(counts, shortcut.getActivity(), 1);
1058            } else if (shortcut.isDynamic() && (operation != ShortcutService.OPERATION_SET)) {
1059                incrementCountForActivity(counts, shortcut.getActivity(), 1);
1060            }
1061        }
1062
1063        for (int i = newList.size() - 1; i >= 0; i--) {
1064            final ShortcutInfo newShortcut = newList.get(i);
1065            final ComponentName newActivity = newShortcut.getActivity();
1066            if (newActivity == null) {
1067                if (operation != ShortcutService.OPERATION_UPDATE) {
1068                    service.wtf("Activity must not be null at this point");
1069                    continue; // Just ignore this invalid case.
1070                }
1071                continue; // Activity can be null for update.
1072            }
1073
1074            final ShortcutInfo original = mShortcuts.get(newShortcut.getId());
1075            if (original == null) {
1076                if (operation == ShortcutService.OPERATION_UPDATE) {
1077                    continue; // When updating, ignore if there's no target.
1078                }
1079                // Add() or set(), and there's no existing shortcut with the same ID.  We're
1080                // simply publishing (as opposed to updating) this shortcut, so just +1.
1081                incrementCountForActivity(counts, newActivity, 1);
1082                continue;
1083            }
1084            if (original.isFloating() && (operation == ShortcutService.OPERATION_UPDATE)) {
1085                // Updating floating shortcuts doesn't affect the count, so ignore.
1086                continue;
1087            }
1088
1089            // If it's add() or update(), then need to decrement for the previous activity.
1090            // Skip it for set() since it's already been taken care of by not counting the original
1091            // dynamic shortcuts in the first loop.
1092            if (operation != ShortcutService.OPERATION_SET) {
1093                final ComponentName oldActivity = original.getActivity();
1094                if (!original.isFloating()) {
1095                    incrementCountForActivity(counts, oldActivity, -1);
1096                }
1097            }
1098            incrementCountForActivity(counts, newActivity, 1);
1099        }
1100
1101        // Then make sure none of the activities have more than the max number of shortcuts.
1102        for (int i = counts.size() - 1; i >= 0; i--) {
1103            service.enforceMaxActivityShortcuts(counts.valueAt(i));
1104        }
1105    }
1106
1107    /**
1108     * For all the text fields, refresh the string values if they're from resources.
1109     */
1110    public void resolveResourceStrings() {
1111        final ShortcutService s = mShortcutUser.mService;
1112        boolean changed = false;
1113
1114        Resources publisherRes = null;
1115        for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1116            final ShortcutInfo si = mShortcuts.valueAt(i);
1117
1118            if (si.hasStringResources()) {
1119                changed = true;
1120
1121                if (publisherRes == null) {
1122                    publisherRes = getPackageResources();
1123                    if (publisherRes == null) {
1124                        break; // Resources couldn't be loaded.
1125                    }
1126                }
1127
1128                si.resolveResourceStrings(publisherRes);
1129                si.setTimestamp(s.injectCurrentTimeMillis());
1130            }
1131        }
1132        if (changed) {
1133            s.packageShortcutsChanged(getPackageName(), getPackageUserId());
1134        }
1135    }
1136
1137    /** Clears the implicit ranks for all shortcuts. */
1138    public void clearAllImplicitRanks() {
1139        for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1140            final ShortcutInfo si = mShortcuts.valueAt(i);
1141            si.clearImplicitRankAndRankChangedFlag();
1142        }
1143    }
1144
1145    /**
1146     * Used to sort shortcuts for rank auto-adjusting.
1147     */
1148    final Comparator<ShortcutInfo> mShortcutRankComparator = (ShortcutInfo a, ShortcutInfo b) -> {
1149        // First, sort by rank.
1150        int ret = Integer.compare(a.getRank(), b.getRank());
1151        if (ret != 0) {
1152            return ret;
1153        }
1154        // When ranks are tie, then prioritize the ones that have just been assigned new ranks.
1155        // e.g. when there are 3 shortcuts, "s1" "s2" and "s3" with rank 0, 1, 2 respectively,
1156        // adding a shortcut "s4" with rank 1 will "insert" it between "s1" and "s2", because
1157        // "s2" and "s4" have the same rank 1 but s4 has isRankChanged() set.
1158        // Similarly, updating s3's rank to 1 will insert it between s1 and s2.
1159        if (a.isRankChanged() != b.isRankChanged()) {
1160            return a.isRankChanged() ? -1 : 1;
1161        }
1162        // If they're still tie, sort by implicit rank -- i.e. preserve the order in which
1163        // they're passed to the API.
1164        ret = Integer.compare(a.getImplicitRank(), b.getImplicitRank());
1165        if (ret != 0) {
1166            return ret;
1167        }
1168        // If they're still tie, just sort by their IDs.
1169        // This may happen with updateShortcuts() -- see
1170        // the testUpdateShortcuts_noManifestShortcuts() test.
1171        return a.getId().compareTo(b.getId());
1172    };
1173
1174    /**
1175     * Re-calculate the ranks for all shortcuts.
1176     */
1177    public void adjustRanks() {
1178        final ShortcutService s = mShortcutUser.mService;
1179        final long now = s.injectCurrentTimeMillis();
1180
1181        // First, clear ranks for floating shortcuts.
1182        for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1183            final ShortcutInfo si = mShortcuts.valueAt(i);
1184            if (si.isFloating()) {
1185                if (si.getRank() != 0) {
1186                    si.setTimestamp(now);
1187                    si.setRank(0);
1188                }
1189            }
1190        }
1191
1192        // Then adjust ranks.  Ranks are unique for each activity, so we first need to sort
1193        // shortcuts to each activity.
1194        // Then sort the shortcuts within each activity with mShortcutRankComparator, and
1195        // assign ranks from 0.
1196        final ArrayMap<ComponentName, ArrayList<ShortcutInfo>> all =
1197                sortShortcutsToActivities();
1198        for (int outer = all.size() - 1; outer >= 0; outer--) { // For each activity.
1199            final ArrayList<ShortcutInfo> list = all.valueAt(outer);
1200
1201            // Sort by ranks and other signals.
1202            Collections.sort(list, mShortcutRankComparator);
1203
1204            int rank = 0;
1205
1206            final int size = list.size();
1207            for (int i = 0; i < size; i++) {
1208                final ShortcutInfo si = list.get(i);
1209                if (si.isManifestShortcut()) {
1210                    // Don't adjust ranks for manifest shortcuts.
1211                    continue;
1212                }
1213                // At this point, it must be dynamic.
1214                if (!si.isDynamic()) {
1215                    s.wtf("Non-dynamic shortcut found.");
1216                    continue;
1217                }
1218                final int thisRank = rank++;
1219                if (si.getRank() != thisRank) {
1220                    si.setTimestamp(now);
1221                    si.setRank(thisRank);
1222                }
1223            }
1224        }
1225    }
1226
1227    /** @return true if there's any shortcuts that are not manifest shortcuts. */
1228    public boolean hasNonManifestShortcuts() {
1229        for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1230            final ShortcutInfo si = mShortcuts.valueAt(i);
1231            if (!si.isDeclaredInManifest()) {
1232                return true;
1233            }
1234        }
1235        return false;
1236    }
1237
1238    public void dump(@NonNull PrintWriter pw, @NonNull String prefix, DumpFilter filter) {
1239        pw.println();
1240
1241        pw.print(prefix);
1242        pw.print("Package: ");
1243        pw.print(getPackageName());
1244        pw.print("  UID: ");
1245        pw.print(mPackageUid);
1246        pw.println();
1247
1248        pw.print(prefix);
1249        pw.print("  ");
1250        pw.print("Calls: ");
1251        pw.print(getApiCallCount());
1252        pw.println();
1253
1254        // getApiCallCount() may have updated mLastKnownForegroundElapsedTime.
1255        pw.print(prefix);
1256        pw.print("  ");
1257        pw.print("Last known FG: ");
1258        pw.print(mLastKnownForegroundElapsedTime);
1259        pw.println();
1260
1261        // This should be after getApiCallCount(), which may update it.
1262        pw.print(prefix);
1263        pw.print("  ");
1264        pw.print("Last reset: [");
1265        pw.print(mLastResetTime);
1266        pw.print("] ");
1267        pw.print(ShortcutService.formatTime(mLastResetTime));
1268        pw.println();
1269
1270        getPackageInfo().dump(pw, prefix + "  ");
1271        pw.println();
1272
1273        pw.print(prefix);
1274        pw.println("  Shortcuts:");
1275        long totalBitmapSize = 0;
1276        final ArrayMap<String, ShortcutInfo> shortcuts = mShortcuts;
1277        final int size = shortcuts.size();
1278        for (int i = 0; i < size; i++) {
1279            final ShortcutInfo si = shortcuts.valueAt(i);
1280            pw.println(si.toDumpString(prefix + "    "));
1281            if (si.getBitmapPath() != null) {
1282                final long len = new File(si.getBitmapPath()).length();
1283                pw.print(prefix);
1284                pw.print("      ");
1285                pw.print("bitmap size=");
1286                pw.println(len);
1287
1288                totalBitmapSize += len;
1289            }
1290        }
1291        pw.print(prefix);
1292        pw.print("  ");
1293        pw.print("Total bitmap size: ");
1294        pw.print(totalBitmapSize);
1295        pw.print(" (");
1296        pw.print(Formatter.formatFileSize(mShortcutUser.mService.mContext, totalBitmapSize));
1297        pw.println(")");
1298    }
1299
1300    @Override
1301    public JSONObject dumpCheckin(boolean clear) throws JSONException {
1302        final JSONObject result = super.dumpCheckin(clear);
1303
1304        int numDynamic = 0;
1305        int numPinned = 0;
1306        int numManifest = 0;
1307        int numBitmaps = 0;
1308        long totalBitmapSize = 0;
1309
1310        final ArrayMap<String, ShortcutInfo> shortcuts = mShortcuts;
1311        final int size = shortcuts.size();
1312        for (int i = 0; i < size; i++) {
1313            final ShortcutInfo si = shortcuts.valueAt(i);
1314
1315            if (si.isDynamic()) numDynamic++;
1316            if (si.isDeclaredInManifest()) numManifest++;
1317            if (si.isPinned()) numPinned++;
1318
1319            if (si.getBitmapPath() != null) {
1320                numBitmaps++;
1321                totalBitmapSize += new File(si.getBitmapPath()).length();
1322            }
1323        }
1324
1325        result.put(KEY_DYNAMIC, numDynamic);
1326        result.put(KEY_MANIFEST, numManifest);
1327        result.put(KEY_PINNED, numPinned);
1328        result.put(KEY_BITMAPS, numBitmaps);
1329        result.put(KEY_BITMAP_BYTES, totalBitmapSize);
1330
1331        // TODO Log update frequency too.
1332
1333        return result;
1334    }
1335
1336    @Override
1337    public void saveToXml(@NonNull XmlSerializer out, boolean forBackup)
1338            throws IOException, XmlPullParserException {
1339        final int size = mShortcuts.size();
1340
1341        if (size == 0 && mApiCallCount == 0) {
1342            return; // nothing to write.
1343        }
1344
1345        out.startTag(null, TAG_ROOT);
1346
1347        ShortcutService.writeAttr(out, ATTR_NAME, getPackageName());
1348        ShortcutService.writeAttr(out, ATTR_CALL_COUNT, mApiCallCount);
1349        ShortcutService.writeAttr(out, ATTR_LAST_RESET, mLastResetTime);
1350        getPackageInfo().saveToXml(out, forBackup);
1351
1352        for (int j = 0; j < size; j++) {
1353            saveShortcut(out, mShortcuts.valueAt(j), forBackup,
1354                    getPackageInfo().isBackupAllowed());
1355        }
1356
1357        out.endTag(null, TAG_ROOT);
1358    }
1359
1360    private void saveShortcut(XmlSerializer out, ShortcutInfo si, boolean forBackup,
1361            boolean appSupportsBackup)
1362            throws IOException, XmlPullParserException {
1363
1364        final ShortcutService s = mShortcutUser.mService;
1365
1366        if (forBackup) {
1367            if (!(si.isPinned() && si.isEnabled())) {
1368                // We only backup pinned shortcuts that are enabled.
1369                // Note, this means, shortcuts that are restored but are blocked restore, e.g. due
1370                // to a lower version code, will not be ported to a new device.
1371                return;
1372            }
1373        }
1374        final boolean shouldBackupDetails =
1375                !forBackup // It's not backup
1376                || appSupportsBackup; // Or, it's a backup and app supports backup.
1377
1378        // Note: at this point no shortcuts should have bitmaps pending save, but if they do,
1379        // just remove the bitmap.
1380        if (si.isIconPendingSave()) {
1381            s.removeIconLocked(si);
1382        }
1383        out.startTag(null, TAG_SHORTCUT);
1384        ShortcutService.writeAttr(out, ATTR_ID, si.getId());
1385        // writeAttr(out, "package", si.getPackageName()); // not needed
1386        ShortcutService.writeAttr(out, ATTR_ACTIVITY, si.getActivity());
1387        // writeAttr(out, "icon", si.getIcon());  // We don't save it.
1388        ShortcutService.writeAttr(out, ATTR_TITLE, si.getTitle());
1389        ShortcutService.writeAttr(out, ATTR_TITLE_RES_ID, si.getTitleResId());
1390        ShortcutService.writeAttr(out, ATTR_TITLE_RES_NAME, si.getTitleResName());
1391        ShortcutService.writeAttr(out, ATTR_TEXT, si.getText());
1392        ShortcutService.writeAttr(out, ATTR_TEXT_RES_ID, si.getTextResId());
1393        ShortcutService.writeAttr(out, ATTR_TEXT_RES_NAME, si.getTextResName());
1394        if (shouldBackupDetails) {
1395            ShortcutService.writeAttr(out, ATTR_DISABLED_MESSAGE, si.getDisabledMessage());
1396            ShortcutService.writeAttr(out, ATTR_DISABLED_MESSAGE_RES_ID,
1397                    si.getDisabledMessageResourceId());
1398            ShortcutService.writeAttr(out, ATTR_DISABLED_MESSAGE_RES_NAME,
1399                    si.getDisabledMessageResName());
1400        }
1401        ShortcutService.writeAttr(out, ATTR_DISABLED_REASON, si.getDisabledReason());
1402        ShortcutService.writeAttr(out, ATTR_TIMESTAMP,
1403                si.getLastChangedTimestamp());
1404        if (forBackup) {
1405            // Don't write icon information.  Also drop the dynamic flag.
1406
1407            int flags = si.getFlags() &
1408                    ~(ShortcutInfo.FLAG_HAS_ICON_FILE | ShortcutInfo.FLAG_HAS_ICON_RES
1409                            | ShortcutInfo.FLAG_ICON_FILE_PENDING_SAVE
1410                            | ShortcutInfo.FLAG_DYNAMIC);
1411            ShortcutService.writeAttr(out, ATTR_FLAGS, flags);
1412
1413            // Set the publisher version code at every backup.
1414            final long packageVersionCode = getPackageInfo().getVersionCode();
1415            if (packageVersionCode == 0) {
1416                s.wtf("Package version code should be available at this point.");
1417                // However, 0 is a valid version code, so we just go ahead with it...
1418            }
1419        } else {
1420            // When writing for backup, ranks shouldn't be saved, since shortcuts won't be restored
1421            // as dynamic.
1422            ShortcutService.writeAttr(out, ATTR_RANK, si.getRank());
1423
1424            ShortcutService.writeAttr(out, ATTR_FLAGS, si.getFlags());
1425            ShortcutService.writeAttr(out, ATTR_ICON_RES_ID, si.getIconResourceId());
1426            ShortcutService.writeAttr(out, ATTR_ICON_RES_NAME, si.getIconResName());
1427            ShortcutService.writeAttr(out, ATTR_BITMAP_PATH, si.getBitmapPath());
1428        }
1429
1430        if (shouldBackupDetails) {
1431            {
1432                final Set<String> cat = si.getCategories();
1433                if (cat != null && cat.size() > 0) {
1434                    out.startTag(null, TAG_CATEGORIES);
1435                    XmlUtils.writeStringArrayXml(cat.toArray(new String[cat.size()]),
1436                            NAME_CATEGORIES, out);
1437                    out.endTag(null, TAG_CATEGORIES);
1438                }
1439            }
1440            final Intent[] intentsNoExtras = si.getIntentsNoExtras();
1441            final PersistableBundle[] intentsExtras = si.getIntentPersistableExtrases();
1442            final int numIntents = intentsNoExtras.length;
1443            for (int i = 0; i < numIntents; i++) {
1444                out.startTag(null, TAG_INTENT);
1445                ShortcutService.writeAttr(out, ATTR_INTENT_NO_EXTRA, intentsNoExtras[i]);
1446                ShortcutService.writeTagExtra(out, TAG_EXTRAS, intentsExtras[i]);
1447                out.endTag(null, TAG_INTENT);
1448            }
1449
1450            ShortcutService.writeTagExtra(out, TAG_EXTRAS, si.getExtras());
1451        }
1452
1453        out.endTag(null, TAG_SHORTCUT);
1454    }
1455
1456    public static ShortcutPackage loadFromXml(ShortcutService s, ShortcutUser shortcutUser,
1457            XmlPullParser parser, boolean fromBackup)
1458            throws IOException, XmlPullParserException {
1459
1460        final String packageName = ShortcutService.parseStringAttribute(parser,
1461                ATTR_NAME);
1462
1463        final ShortcutPackage ret = new ShortcutPackage(shortcutUser,
1464                shortcutUser.getUserId(), packageName);
1465
1466        ret.mApiCallCount =
1467                ShortcutService.parseIntAttribute(parser, ATTR_CALL_COUNT);
1468        ret.mLastResetTime =
1469                ShortcutService.parseLongAttribute(parser, ATTR_LAST_RESET);
1470
1471
1472        final int outerDepth = parser.getDepth();
1473        int type;
1474        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1475                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1476            if (type != XmlPullParser.START_TAG) {
1477                continue;
1478            }
1479            final int depth = parser.getDepth();
1480            final String tag = parser.getName();
1481            if (depth == outerDepth + 1) {
1482                switch (tag) {
1483                    case ShortcutPackageInfo.TAG_ROOT:
1484                        ret.getPackageInfo().loadFromXml(parser, fromBackup);
1485
1486                        continue;
1487                    case TAG_SHORTCUT:
1488                        final ShortcutInfo si = parseShortcut(parser, packageName,
1489                                shortcutUser.getUserId(), fromBackup);
1490
1491                        // Don't use addShortcut(), we don't need to save the icon.
1492                        ret.mShortcuts.put(si.getId(), si);
1493                        continue;
1494                }
1495            }
1496            ShortcutService.warnForInvalidTag(depth, tag);
1497        }
1498        return ret;
1499    }
1500
1501    private static ShortcutInfo parseShortcut(XmlPullParser parser, String packageName,
1502            @UserIdInt int userId, boolean fromBackup)
1503            throws IOException, XmlPullParserException {
1504        String id;
1505        ComponentName activityComponent;
1506        // Icon icon;
1507        String title;
1508        int titleResId;
1509        String titleResName;
1510        String text;
1511        int textResId;
1512        String textResName;
1513        String disabledMessage;
1514        int disabledMessageResId;
1515        String disabledMessageResName;
1516        int disabledReason;
1517        Intent intentLegacy;
1518        PersistableBundle intentPersistableExtrasLegacy = null;
1519        ArrayList<Intent> intents = new ArrayList<>();
1520        int rank;
1521        PersistableBundle extras = null;
1522        long lastChangedTimestamp;
1523        int flags;
1524        int iconResId;
1525        String iconResName;
1526        String bitmapPath;
1527        int backupVersionCode;
1528        ArraySet<String> categories = null;
1529
1530        id = ShortcutService.parseStringAttribute(parser, ATTR_ID);
1531        activityComponent = ShortcutService.parseComponentNameAttribute(parser,
1532                ATTR_ACTIVITY);
1533        title = ShortcutService.parseStringAttribute(parser, ATTR_TITLE);
1534        titleResId = ShortcutService.parseIntAttribute(parser, ATTR_TITLE_RES_ID);
1535        titleResName = ShortcutService.parseStringAttribute(parser, ATTR_TITLE_RES_NAME);
1536        text = ShortcutService.parseStringAttribute(parser, ATTR_TEXT);
1537        textResId = ShortcutService.parseIntAttribute(parser, ATTR_TEXT_RES_ID);
1538        textResName = ShortcutService.parseStringAttribute(parser, ATTR_TEXT_RES_NAME);
1539        disabledMessage = ShortcutService.parseStringAttribute(parser, ATTR_DISABLED_MESSAGE);
1540        disabledMessageResId = ShortcutService.parseIntAttribute(parser,
1541                ATTR_DISABLED_MESSAGE_RES_ID);
1542        disabledMessageResName = ShortcutService.parseStringAttribute(parser,
1543                ATTR_DISABLED_MESSAGE_RES_NAME);
1544        disabledReason = ShortcutService.parseIntAttribute(parser, ATTR_DISABLED_REASON);
1545        intentLegacy = ShortcutService.parseIntentAttributeNoDefault(parser, ATTR_INTENT_LEGACY);
1546        rank = (int) ShortcutService.parseLongAttribute(parser, ATTR_RANK);
1547        lastChangedTimestamp = ShortcutService.parseLongAttribute(parser, ATTR_TIMESTAMP);
1548        flags = (int) ShortcutService.parseLongAttribute(parser, ATTR_FLAGS);
1549        iconResId = (int) ShortcutService.parseLongAttribute(parser, ATTR_ICON_RES_ID);
1550        iconResName = ShortcutService.parseStringAttribute(parser, ATTR_ICON_RES_NAME);
1551        bitmapPath = ShortcutService.parseStringAttribute(parser, ATTR_BITMAP_PATH);
1552
1553        final int outerDepth = parser.getDepth();
1554        int type;
1555        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1556                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1557            if (type != XmlPullParser.START_TAG) {
1558                continue;
1559            }
1560            final int depth = parser.getDepth();
1561            final String tag = parser.getName();
1562            if (ShortcutService.DEBUG_LOAD) {
1563                Slog.d(TAG, String.format("  depth=%d type=%d name=%s",
1564                        depth, type, tag));
1565            }
1566            switch (tag) {
1567                case TAG_INTENT_EXTRAS_LEGACY:
1568                    intentPersistableExtrasLegacy = PersistableBundle.restoreFromXml(parser);
1569                    continue;
1570                case TAG_INTENT:
1571                    intents.add(parseIntent(parser));
1572                    continue;
1573                case TAG_EXTRAS:
1574                    extras = PersistableBundle.restoreFromXml(parser);
1575                    continue;
1576                case TAG_CATEGORIES:
1577                    // This just contains string-array.
1578                    continue;
1579                case TAG_STRING_ARRAY_XMLUTILS:
1580                    if (NAME_CATEGORIES.equals(ShortcutService.parseStringAttribute(parser,
1581                            ATTR_NAME_XMLUTILS))) {
1582                        final String[] ar = XmlUtils.readThisStringArrayXml(
1583                                parser, TAG_STRING_ARRAY_XMLUTILS, null);
1584                        categories = new ArraySet<>(ar.length);
1585                        for (int i = 0; i < ar.length; i++) {
1586                            categories.add(ar[i]);
1587                        }
1588                    }
1589                    continue;
1590            }
1591            throw ShortcutService.throwForInvalidTag(depth, tag);
1592        }
1593
1594        if (intentLegacy != null) {
1595            // For the legacy file format which supported only one intent per shortcut.
1596            ShortcutInfo.setIntentExtras(intentLegacy, intentPersistableExtrasLegacy);
1597            intents.clear();
1598            intents.add(intentLegacy);
1599        }
1600
1601
1602        if ((disabledReason == ShortcutInfo.DISABLED_REASON_NOT_DISABLED)
1603                && ((flags & ShortcutInfo.FLAG_DISABLED) != 0)) {
1604            // We didn't used to have the disabled reason, so if a shortcut is disabled
1605            // and has no reason, we assume it was disabled by publisher.
1606            disabledReason = ShortcutInfo.DISABLED_REASON_BY_APP;
1607        }
1608
1609        // All restored shortcuts are initially "shadow".
1610        if (fromBackup) {
1611            flags |= ShortcutInfo.FLAG_SHADOW;
1612        }
1613
1614        return new ShortcutInfo(
1615                userId, id, packageName, activityComponent, /* icon =*/ null,
1616                title, titleResId, titleResName, text, textResId, textResName,
1617                disabledMessage, disabledMessageResId, disabledMessageResName,
1618                categories,
1619                intents.toArray(new Intent[intents.size()]),
1620                rank, extras, lastChangedTimestamp, flags,
1621                iconResId, iconResName, bitmapPath, disabledReason);
1622    }
1623
1624    private static Intent parseIntent(XmlPullParser parser)
1625            throws IOException, XmlPullParserException {
1626
1627        Intent intent = ShortcutService.parseIntentAttribute(parser,
1628                ATTR_INTENT_NO_EXTRA);
1629
1630        final int outerDepth = parser.getDepth();
1631        int type;
1632        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1633                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1634            if (type != XmlPullParser.START_TAG) {
1635                continue;
1636            }
1637            final int depth = parser.getDepth();
1638            final String tag = parser.getName();
1639            if (ShortcutService.DEBUG_LOAD) {
1640                Slog.d(TAG, String.format("  depth=%d type=%d name=%s",
1641                        depth, type, tag));
1642            }
1643            switch (tag) {
1644                case TAG_EXTRAS:
1645                    ShortcutInfo.setIntentExtras(intent,
1646                            PersistableBundle.restoreFromXml(parser));
1647                    continue;
1648            }
1649            throw ShortcutService.throwForInvalidTag(depth, tag);
1650        }
1651        return intent;
1652    }
1653
1654    @VisibleForTesting
1655    List<ShortcutInfo> getAllShortcutsForTest() {
1656        return new ArrayList<>(mShortcuts.values());
1657    }
1658
1659    @Override
1660    public void verifyStates() {
1661        super.verifyStates();
1662
1663        boolean failed = false;
1664
1665        final ShortcutService s = mShortcutUser.mService;
1666
1667        final ArrayMap<ComponentName, ArrayList<ShortcutInfo>> all =
1668                sortShortcutsToActivities();
1669
1670        // Make sure each activity won't have more than max shortcuts.
1671        for (int outer = all.size() - 1; outer >= 0; outer--) {
1672            final ArrayList<ShortcutInfo> list = all.valueAt(outer);
1673            if (list.size() > mShortcutUser.mService.getMaxActivityShortcuts()) {
1674                failed = true;
1675                Log.e(TAG_VERIFY, "Package " + getPackageName() + ": activity " + all.keyAt(outer)
1676                        + " has " + all.valueAt(outer).size() + " shortcuts.");
1677            }
1678
1679            // Sort by rank.
1680            Collections.sort(list, (a, b) -> Integer.compare(a.getRank(), b.getRank()));
1681
1682            // Split into two arrays for each kind.
1683            final ArrayList<ShortcutInfo> dynamicList = new ArrayList<>(list);
1684            dynamicList.removeIf((si) -> !si.isDynamic());
1685
1686            final ArrayList<ShortcutInfo> manifestList = new ArrayList<>(list);
1687            dynamicList.removeIf((si) -> !si.isManifestShortcut());
1688
1689            verifyRanksSequential(dynamicList);
1690            verifyRanksSequential(manifestList);
1691        }
1692
1693        // Verify each shortcut's status.
1694        for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1695            final ShortcutInfo si = mShortcuts.valueAt(i);
1696            if (!(si.isDeclaredInManifest() || si.isDynamic() || si.isPinned())) {
1697                failed = true;
1698                Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1699                        + " is not manifest, dynamic or pinned.");
1700            }
1701            if (si.isDeclaredInManifest() && si.isDynamic()) {
1702                failed = true;
1703                Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1704                        + " is both dynamic and manifest at the same time.");
1705            }
1706            if (si.getActivity() == null && !si.isFloating()) {
1707                failed = true;
1708                Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1709                        + " has null activity, but not floating.");
1710            }
1711            if ((si.isDynamic() || si.isManifestShortcut()) && !si.isEnabled()) {
1712                failed = true;
1713                Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1714                        + " is not floating, but is disabled.");
1715            }
1716            if (si.isFloating() && si.getRank() != 0) {
1717                failed = true;
1718                Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1719                        + " is floating, but has rank=" + si.getRank());
1720            }
1721            if (si.getIcon() != null) {
1722                failed = true;
1723                Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1724                        + " still has an icon");
1725            }
1726            if (si.hasAdaptiveBitmap() && !si.hasIconFile()) {
1727                failed = true;
1728                Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1729                    + " has adaptive bitmap but was not saved to a file.");
1730            }
1731            if (si.hasIconFile() && si.hasIconResource()) {
1732                failed = true;
1733                Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1734                        + " has both resource and bitmap icons");
1735            }
1736            if (si.isEnabled()
1737                    != (si.getDisabledReason() == ShortcutInfo.DISABLED_REASON_NOT_DISABLED)) {
1738                failed = true;
1739                Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1740                        + " isEnabled() and getDisabledReason() disagree: "
1741                        + si.isEnabled() + " vs " + si.getDisabledReason());
1742            }
1743            if ((si.getDisabledReason() == ShortcutInfo.DISABLED_REASON_VERSION_LOWER)
1744                    && (getPackageInfo().getBackupSourceVersionCode()
1745                    == ShortcutInfo.VERSION_CODE_UNKNOWN)) {
1746                failed = true;
1747                Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1748                        + " RESTORED_VERSION_LOWER with no backup source version code.");
1749            }
1750            if (s.isDummyMainActivity(si.getActivity())) {
1751                failed = true;
1752                Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1753                        + " has a dummy target activity");
1754            }
1755        }
1756
1757        if (failed) {
1758            throw new IllegalStateException("See logcat for errors");
1759        }
1760    }
1761
1762    private boolean verifyRanksSequential(List<ShortcutInfo> list) {
1763        boolean failed = false;
1764
1765        for (int i = 0; i < list.size(); i++) {
1766            final ShortcutInfo si = list.get(i);
1767            if (si.getRank() != i) {
1768                failed = true;
1769                Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1770                        + " rank=" + si.getRank() + " but expected to be "+ i);
1771            }
1772        }
1773        return failed;
1774    }
1775}
1776