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