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