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