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