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