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