ShortcutPackage.java revision 248a0ef3aa119f92858a2bb95d20595824b8d07b
1/* 2 * Copyright (C) 2016 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16package com.android.server.pm; 17 18import android.annotation.NonNull; 19import android.annotation.Nullable; 20import android.annotation.UserIdInt; 21import android.content.ComponentName; 22import android.content.Intent; 23import android.content.pm.PackageInfo; 24import android.content.pm.ShortcutInfo; 25import android.content.res.Resources; 26import android.os.PersistableBundle; 27import android.text.format.Formatter; 28import android.util.ArrayMap; 29import android.util.ArraySet; 30import android.util.Log; 31import android.util.Slog; 32 33import com.android.internal.annotations.VisibleForTesting; 34import com.android.internal.util.Preconditions; 35import com.android.internal.util.XmlUtils; 36import com.android.server.pm.ShortcutService.ShortcutOperation; 37import com.android.server.pm.ShortcutService.Stats; 38 39import org.json.JSONException; 40import org.json.JSONObject; 41import org.xmlpull.v1.XmlPullParser; 42import org.xmlpull.v1.XmlPullParserException; 43import org.xmlpull.v1.XmlSerializer; 44 45import java.io.File; 46import java.io.IOException; 47import java.io.PrintWriter; 48import java.util.ArrayList; 49import java.util.Collections; 50import java.util.Comparator; 51import java.util.List; 52import java.util.Set; 53import java.util.function.Predicate; 54 55/** 56 * Package information used by {@link ShortcutService}. 57 * User information used by {@link ShortcutService}. 58 * 59 * All methods should be guarded by {@code #mShortcutUser.mService.mLock}. 60 */ 61class ShortcutPackage extends ShortcutPackageItem { 62 private static final String TAG = ShortcutService.TAG; 63 private static final String TAG_VERIFY = ShortcutService.TAG + ".verify"; 64 65 static final String TAG_ROOT = "package"; 66 private static final String TAG_INTENT_EXTRAS_LEGACY = "intent-extras"; 67 private static final String TAG_INTENT = "intent"; 68 private static final String TAG_EXTRAS = "extras"; 69 private static final String TAG_SHORTCUT = "shortcut"; 70 private static final String TAG_CATEGORIES = "categories"; 71 72 private static final String ATTR_NAME = "name"; 73 private static final String ATTR_CALL_COUNT = "call-count"; 74 private static final String ATTR_LAST_RESET = "last-reset"; 75 private static final String ATTR_ID = "id"; 76 private static final String ATTR_ACTIVITY = "activity"; 77 private static final String ATTR_TITLE = "title"; 78 private static final String ATTR_TITLE_RES_ID = "titleid"; 79 private static final String ATTR_TITLE_RES_NAME = "titlename"; 80 private static final String ATTR_TEXT = "text"; 81 private static final String ATTR_TEXT_RES_ID = "textid"; 82 private static final String ATTR_TEXT_RES_NAME = "textname"; 83 private static final String ATTR_DISABLED_MESSAGE = "dmessage"; 84 private static final String ATTR_DISABLED_MESSAGE_RES_ID = "dmessageid"; 85 private static final String ATTR_DISABLED_MESSAGE_RES_NAME = "dmessagename"; 86 private static final String ATTR_INTENT_LEGACY = "intent"; 87 private static final String ATTR_INTENT_NO_EXTRA = "intent-base"; 88 private static final String ATTR_RANK = "rank"; 89 private static final String ATTR_TIMESTAMP = "timestamp"; 90 private static final String ATTR_FLAGS = "flags"; 91 private static final String ATTR_ICON_RES_ID = "icon-res"; 92 private static final String ATTR_ICON_RES_NAME = "icon-resname"; 93 private static final String ATTR_BITMAP_PATH = "bitmap-path"; 94 95 private static final String NAME_CATEGORIES = "categories"; 96 97 private static final String TAG_STRING_ARRAY_XMLUTILS = "string-array"; 98 private static final String ATTR_NAME_XMLUTILS = "name"; 99 100 private static final String KEY_DYNAMIC = "dynamic"; 101 private static final String KEY_MANIFEST = "manifest"; 102 private static final String KEY_PINNED = "pinned"; 103 private static final String KEY_BITMAPS = "bitmaps"; 104 private static final String KEY_BITMAP_BYTES = "bitmapBytes"; 105 106 /** 107 * All the shortcuts from the package, keyed on IDs. 108 */ 109 final private ArrayMap<String, ShortcutInfo> mShortcuts = new ArrayMap<>(); 110 111 /** 112 * # of times the package has called rate-limited APIs. 113 */ 114 private int mApiCallCount; 115 116 /** 117 * When {@link #mApiCallCount} was reset last time. 118 */ 119 private long mLastResetTime; 120 121 private final int mPackageUid; 122 123 private long mLastKnownForegroundElapsedTime; 124 125 private ShortcutPackage(ShortcutUser shortcutUser, 126 int packageUserId, String packageName, ShortcutPackageInfo spi) { 127 super(shortcutUser, packageUserId, packageName, 128 spi != null ? spi : ShortcutPackageInfo.newEmpty()); 129 130 mPackageUid = shortcutUser.mService.injectGetPackageUid(packageName, packageUserId); 131 } 132 133 public ShortcutPackage(ShortcutUser shortcutUser, int packageUserId, String packageName) { 134 this(shortcutUser, packageUserId, packageName, null); 135 } 136 137 @Override 138 public int getOwnerUserId() { 139 // For packages, always owner user == package user. 140 return getPackageUserId(); 141 } 142 143 public int getPackageUid() { 144 return mPackageUid; 145 } 146 147 @Nullable 148 public Resources getPackageResources() { 149 return mShortcutUser.mService.injectGetResourcesForApplicationAsUser( 150 getPackageName(), getPackageUserId()); 151 } 152 153 @Override 154 protected void onRestoreBlocked() { 155 // Can't restore due to version/signature mismatch. Remove all shortcuts. 156 mShortcuts.clear(); 157 } 158 159 @Override 160 protected void onRestored() { 161 // Because some launchers may not have been restored (e.g. allowBackup=false), 162 // we need to re-calculate the pinned shortcuts. 163 refreshPinnedFlags(); 164 } 165 166 /** 167 * Note this does *not* provide a correct view to the calling launcher. 168 */ 169 @Nullable 170 public ShortcutInfo findShortcutById(String id) { 171 return mShortcuts.get(id); 172 } 173 174 private void ensureNotImmutable(@Nullable ShortcutInfo shortcut) { 175 if (shortcut != null && shortcut.isImmutable()) { 176 throw new IllegalArgumentException( 177 "Manifest shortcut ID=" + shortcut.getId() 178 + " may not be manipulated via APIs"); 179 } 180 } 181 182 private void ensureNotImmutable(@NonNull String id) { 183 ensureNotImmutable(mShortcuts.get(id)); 184 } 185 186 public void ensureImmutableShortcutsNotIncludedWithIds(@NonNull List<String> shortcutIds) { 187 for (int i = shortcutIds.size() - 1; i >= 0; i--) { 188 ensureNotImmutable(shortcutIds.get(i)); 189 } 190 } 191 192 public void ensureImmutableShortcutsNotIncluded(@NonNull List<ShortcutInfo> shortcuts) { 193 for (int i = shortcuts.size() - 1; i >= 0; i--) { 194 ensureNotImmutable(shortcuts.get(i).getId()); 195 } 196 } 197 198 private ShortcutInfo deleteShortcutInner(@NonNull String id) { 199 final ShortcutInfo shortcut = mShortcuts.remove(id); 200 if (shortcut != null) { 201 mShortcutUser.mService.removeIcon(getPackageUserId(), shortcut); 202 shortcut.clearFlags(ShortcutInfo.FLAG_DYNAMIC | ShortcutInfo.FLAG_PINNED 203 | ShortcutInfo.FLAG_MANIFEST); 204 } 205 return shortcut; 206 } 207 208 private void addShortcutInner(@NonNull ShortcutInfo newShortcut) { 209 final ShortcutService s = mShortcutUser.mService; 210 211 deleteShortcutInner(newShortcut.getId()); 212 213 // Extract Icon and update the icon res ID and the bitmap path. 214 s.saveIconAndFixUpShortcut(getPackageUserId(), newShortcut); 215 s.fixUpShortcutResourceNamesAndValues(newShortcut); 216 mShortcuts.put(newShortcut.getId(), newShortcut); 217 } 218 219 /** 220 * Add a shortcut, or update one with the same ID, with taking over existing flags. 221 * 222 * It checks the max number of dynamic shortcuts. 223 */ 224 public void addOrUpdateDynamicShortcut(@NonNull ShortcutInfo newShortcut) { 225 226 Preconditions.checkArgument(newShortcut.isEnabled(), 227 "add/setDynamicShortcuts() cannot publish disabled shortcuts"); 228 229 newShortcut.addFlags(ShortcutInfo.FLAG_DYNAMIC); 230 231 final ShortcutInfo oldShortcut = mShortcuts.get(newShortcut.getId()); 232 233 final boolean wasPinned; 234 235 if (oldShortcut == null) { 236 wasPinned = false; 237 } else { 238 // It's an update case. 239 // Make sure the target is updatable. (i.e. should be mutable.) 240 oldShortcut.ensureUpdatableWith(newShortcut); 241 242 wasPinned = oldShortcut.isPinned(); 243 } 244 245 // If it was originally pinned, the new one should be pinned too. 246 if (wasPinned) { 247 newShortcut.addFlags(ShortcutInfo.FLAG_PINNED); 248 } 249 250 addShortcutInner(newShortcut); 251 } 252 253 /** 254 * Remove all shortcuts that aren't pinned nor dynamic. 255 */ 256 private void removeOrphans() { 257 ArrayList<String> removeList = null; // Lazily initialize. 258 259 for (int i = mShortcuts.size() - 1; i >= 0; i--) { 260 final ShortcutInfo si = mShortcuts.valueAt(i); 261 262 if (si.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 if (!isNewApp && !forceRescan) { 639 // Return if the package hasn't changed, ie: 640 // - version code hasn't change 641 // - lastUpdateTime hasn't change 642 // - all target activities are still enabled. 643 644 // Note, system apps timestamps do *not* change after OTAs. (But they do 645 // after an adb sync or a local flash.) 646 // This means if a system app's version code doesn't change on an OTA, 647 // we don't notice it's updated. But that's fine since their version code *should* 648 // really change on OTAs. 649 if ((getPackageInfo().getVersionCode() == pi.versionCode) 650 && (getPackageInfo().getLastUpdateTime() == pi.lastUpdateTime) 651 && areAllActivitiesStillEnabled()) { 652 return false; 653 } 654 } 655 } finally { 656 s.logDurationStat(Stats.PACKAGE_UPDATE_CHECK, start); 657 } 658 659 // Now prepare to publish manifest shortcuts. 660 List<ShortcutInfo> newManifestShortcutList = null; 661 try { 662 newManifestShortcutList = ShortcutParser.parseShortcuts(mShortcutUser.mService, 663 getPackageName(), getPackageUserId()); 664 } catch (IOException|XmlPullParserException e) { 665 Slog.e(TAG, "Failed to load shortcuts from AndroidManifest.xml.", e); 666 } 667 final int manifestShortcutSize = newManifestShortcutList == null ? 0 668 : newManifestShortcutList.size(); 669 if (ShortcutService.DEBUG) { 670 Slog.d(TAG, String.format("Package %s has %d manifest shortcut(s)", 671 getPackageName(), manifestShortcutSize)); 672 } 673 if (isNewApp && (manifestShortcutSize == 0)) { 674 // If it's a new app, and it doesn't have manifest shortcuts, then nothing to do. 675 676 // If it's an update, then it may already have manifest shortcuts, which need to be 677 // disabled. 678 return false; 679 } 680 if (ShortcutService.DEBUG) { 681 Slog.d(TAG, String.format("Package %s %s, version %d -> %d", getPackageName(), 682 (isNewApp ? "added" : "updated"), 683 getPackageInfo().getVersionCode(), pi.versionCode)); 684 } 685 686 getPackageInfo().updateVersionInfo(pi); 687 688 boolean changed = false; 689 690 // For existing shortcuts, update timestamps if they have any resources. 691 // Also check if shortcuts' activities are still main activities. Otherwise, disable them. 692 if (!isNewApp) { 693 Resources publisherRes = null; 694 695 for (int i = mShortcuts.size() - 1; i >= 0; i--) { 696 final ShortcutInfo si = mShortcuts.valueAt(i); 697 698 if (si.isDynamic()) { 699 if (!s.injectIsMainActivity(si.getActivity(), getPackageUserId())) { 700 Slog.w(TAG, String.format( 701 "%s is no longer main activity. Disabling shorcut %s.", 702 getPackageName(), si.getId())); 703 if (disableDynamicWithId(si.getId())) { 704 continue; // Actually removed. 705 } 706 // Still pinned, so fall-through and possibly update the resources. 707 } 708 changed = true; 709 } 710 711 if (si.hasAnyResources()) { 712 if (!si.isOriginallyFromManifest()) { 713 if (publisherRes == null) { 714 publisherRes = getPackageResources(); 715 if (publisherRes == null) { 716 break; // Resources couldn't be loaded. 717 } 718 } 719 720 // If this shortcut is not from a manifest, then update all resource IDs 721 // from resource names. (We don't allow resource strings for 722 // non-manifest at the moment, but icons can still be resources.) 723 si.lookupAndFillInResourceIds(publisherRes); 724 } 725 changed = true; 726 si.setTimestamp(s.injectCurrentTimeMillis()); 727 } 728 } 729 } 730 731 // (Re-)publish manifest shortcut. 732 changed |= publishManifestShortcuts(newManifestShortcutList); 733 734 if (newManifestShortcutList != null) { 735 changed |= pushOutExcessShortcuts(); 736 } 737 738 s.verifyStates(); 739 740 if (changed) { 741 // This will send a notification to the launcher, and also save . 742 s.packageShortcutsChanged(getPackageName(), getPackageUserId()); 743 } else { 744 // Still save the version code. 745 s.scheduleSaveUser(getPackageUserId()); 746 } 747 return changed; 748 } 749 750 private boolean publishManifestShortcuts(List<ShortcutInfo> newManifestShortcutList) { 751 if (ShortcutService.DEBUG) { 752 Slog.d(TAG, String.format( 753 "Package %s: publishing manifest shortcuts", getPackageName())); 754 } 755 boolean changed = false; 756 757 // Keep the previous IDs. 758 ArraySet<String> toDisableList = null; 759 for (int i = mShortcuts.size() - 1; i >= 0; i--) { 760 final ShortcutInfo si = mShortcuts.valueAt(i); 761 762 if (si.isManifestShortcut()) { 763 if (toDisableList == null) { 764 toDisableList = new ArraySet<>(); 765 } 766 toDisableList.add(si.getId()); 767 } 768 } 769 770 // Publish new ones. 771 if (newManifestShortcutList != null) { 772 final int newListSize = newManifestShortcutList.size(); 773 774 for (int i = 0; i < newListSize; i++) { 775 changed = true; 776 777 final ShortcutInfo newShortcut = newManifestShortcutList.get(i); 778 final boolean newDisabled = !newShortcut.isEnabled(); 779 780 final String id = newShortcut.getId(); 781 final ShortcutInfo oldShortcut = mShortcuts.get(id); 782 783 boolean wasPinned = false; 784 785 if (oldShortcut != null) { 786 if (!oldShortcut.isOriginallyFromManifest()) { 787 Slog.e(TAG, "Shortcut with ID=" + newShortcut.getId() 788 + " exists but is not from AndroidManifest.xml, not updating."); 789 continue; 790 } 791 // Take over the pinned flag. 792 if (oldShortcut.isPinned()) { 793 wasPinned = true; 794 newShortcut.addFlags(ShortcutInfo.FLAG_PINNED); 795 } 796 } 797 if (newDisabled && !wasPinned) { 798 // If the shortcut is disabled, and it was *not* pinned, then this 799 // just doesn't have to be published. 800 // Just keep it in toDisableList, so the previous one would be removed. 801 continue; 802 } 803 804 // Note even if enabled=false, we still need to update all fields, so do it 805 // regardless. 806 addShortcutInner(newShortcut); // This will clean up the old one too. 807 808 if (!newDisabled && toDisableList != null) { 809 // Still alive, don't remove. 810 toDisableList.remove(id); 811 } 812 } 813 } 814 815 // Disable the previous manifest shortcuts that are no longer in the manifest. 816 if (toDisableList != null) { 817 if (ShortcutService.DEBUG) { 818 Slog.d(TAG, String.format( 819 "Package %s: disabling %d stale shortcuts", getPackageName(), 820 toDisableList.size())); 821 } 822 for (int i = toDisableList.size() - 1; i >= 0; i--) { 823 changed = true; 824 825 final String id = toDisableList.valueAt(i); 826 827 disableWithId(id, /* disable message =*/ null, /* disable message resid */ 0, 828 /* overrideImmutable=*/ true); 829 } 830 removeOrphans(); 831 } 832 adjustRanks(); 833 return changed; 834 } 835 836 /** 837 * For each target activity, make sure # of dynamic + manifest shortcuts <= max. 838 * If too many, we'll remove the dynamic with the lowest ranks. 839 */ 840 private boolean pushOutExcessShortcuts() { 841 final ShortcutService service = mShortcutUser.mService; 842 final int maxShortcuts = service.getMaxActivityShortcuts(); 843 844 boolean changed = false; 845 846 final ArrayMap<ComponentName, ArrayList<ShortcutInfo>> all = 847 sortShortcutsToActivities(); 848 for (int outer = all.size() - 1; outer >= 0; outer--) { 849 final ArrayList<ShortcutInfo> list = all.valueAt(outer); 850 if (list.size() <= maxShortcuts) { 851 continue; 852 } 853 // Sort by isManifestShortcut() and getRank(). 854 Collections.sort(list, mShortcutTypeAndRankComparator); 855 856 // Keep [0 .. max), and remove (as dynamic) [max .. size) 857 for (int inner = list.size() - 1; inner >= maxShortcuts; inner--) { 858 final ShortcutInfo shortcut = list.get(inner); 859 860 if (shortcut.isManifestShortcut()) { 861 // This shouldn't happen -- excess shortcuts should all be non-manifest. 862 // But just in case. 863 service.wtf("Found manifest shortcuts in excess list."); 864 continue; 865 } 866 deleteDynamicWithId(shortcut.getId()); 867 } 868 } 869 870 return changed; 871 } 872 873 /** 874 * To sort by isManifestShortcut() and getRank(). i.e. manifest shortcuts come before 875 * non-manifest shortcuts, then sort by rank. 876 * 877 * This is used to decide which dynamic shortcuts to remove when an upgraded version has more 878 * manifest shortcuts than before and as a result we need to remove some of the dynamic 879 * shortcuts. We sort manifest + dynamic shortcuts by this order, and remove the ones with 880 * the last ones. 881 * 882 * (Note the number of manifest shortcuts is always <= the max number, because if there are 883 * more, ShortcutParser would ignore the rest.) 884 */ 885 final Comparator<ShortcutInfo> mShortcutTypeAndRankComparator = (ShortcutInfo a, 886 ShortcutInfo b) -> { 887 if (a.isManifestShortcut() && !b.isManifestShortcut()) { 888 return -1; 889 } 890 if (!a.isManifestShortcut() && b.isManifestShortcut()) { 891 return 1; 892 } 893 return Integer.compare(a.getRank(), b.getRank()); 894 }; 895 896 /** 897 * Build a list of shortcuts for each target activity and return as a map. The result won't 898 * contain "floating" shortcuts because they don't belong on any activities. 899 */ 900 private ArrayMap<ComponentName, ArrayList<ShortcutInfo>> sortShortcutsToActivities() { 901 final ArrayMap<ComponentName, ArrayList<ShortcutInfo>> activitiesToShortcuts 902 = new ArrayMap<>(); 903 for (int i = mShortcuts.size() - 1; i >= 0; i--) { 904 final ShortcutInfo si = mShortcuts.valueAt(i); 905 if (si.isFloating()) { 906 continue; // Ignore floating shortcuts, which are not tied to any activities. 907 } 908 909 final ComponentName activity = si.getActivity(); 910 911 ArrayList<ShortcutInfo> list = activitiesToShortcuts.get(activity); 912 if (list == null) { 913 list = new ArrayList<>(); 914 activitiesToShortcuts.put(activity, list); 915 } 916 list.add(si); 917 } 918 return activitiesToShortcuts; 919 } 920 921 /** Used by {@link #enforceShortcutCountsBeforeOperation} */ 922 private void incrementCountForActivity(ArrayMap<ComponentName, Integer> counts, 923 ComponentName cn, int increment) { 924 Integer oldValue = counts.get(cn); 925 if (oldValue == null) { 926 oldValue = 0; 927 } 928 929 counts.put(cn, oldValue + increment); 930 } 931 932 /** 933 * Called by 934 * {@link android.content.pm.ShortcutManager#setDynamicShortcuts}, 935 * {@link android.content.pm.ShortcutManager#addDynamicShortcuts}, and 936 * {@link android.content.pm.ShortcutManager#updateShortcuts} before actually performing 937 * the operation to make sure the operation wouldn't result in the target activities having 938 * more than the allowed number of dynamic/manifest shortcuts. 939 * 940 * @param newList shortcut list passed to set, add or updateShortcuts(). 941 * @param operation add, set or update. 942 * @throws IllegalArgumentException if the operation would result in going over the max 943 * shortcut count for any activity. 944 */ 945 public void enforceShortcutCountsBeforeOperation(List<ShortcutInfo> newList, 946 @ShortcutOperation int operation) { 947 final ShortcutService service = mShortcutUser.mService; 948 949 // Current # of dynamic / manifest shortcuts for each activity. 950 // (If it's for update, then don't count dynamic shortcuts, since they'll be replaced 951 // anyway.) 952 final ArrayMap<ComponentName, Integer> counts = new ArrayMap<>(4); 953 for (int i = mShortcuts.size() - 1; i >= 0; i--) { 954 final ShortcutInfo shortcut = mShortcuts.valueAt(i); 955 956 if (shortcut.isManifestShortcut()) { 957 incrementCountForActivity(counts, shortcut.getActivity(), 1); 958 } else if (shortcut.isDynamic() && (operation != ShortcutService.OPERATION_SET)) { 959 incrementCountForActivity(counts, shortcut.getActivity(), 1); 960 } 961 } 962 963 for (int i = newList.size() - 1; i >= 0; i--) { 964 final ShortcutInfo newShortcut = newList.get(i); 965 final ComponentName newActivity = newShortcut.getActivity(); 966 if (newActivity == null) { 967 if (operation != ShortcutService.OPERATION_UPDATE) { 968 service.wtf("Activity must not be null at this point"); 969 continue; // Just ignore this invalid case. 970 } 971 continue; // Activity can be null for update. 972 } 973 974 final ShortcutInfo original = mShortcuts.get(newShortcut.getId()); 975 if (original == null) { 976 if (operation == ShortcutService.OPERATION_UPDATE) { 977 continue; // When updating, ignore if there's no target. 978 } 979 // Add() or set(), and there's no existing shortcut with the same ID. We're 980 // simply publishing (as opposed to updating) this shortcut, so just +1. 981 incrementCountForActivity(counts, newActivity, 1); 982 continue; 983 } 984 if (original.isFloating() && (operation == ShortcutService.OPERATION_UPDATE)) { 985 // Updating floating shortcuts doesn't affect the count, so ignore. 986 continue; 987 } 988 989 // If it's add() or update(), then need to decrement for the previous activity. 990 // Skip it for set() since it's already been taken care of by not counting the original 991 // dynamic shortcuts in the first loop. 992 if (operation != ShortcutService.OPERATION_SET) { 993 final ComponentName oldActivity = original.getActivity(); 994 if (!original.isFloating()) { 995 incrementCountForActivity(counts, oldActivity, -1); 996 } 997 } 998 incrementCountForActivity(counts, newActivity, 1); 999 } 1000 1001 // Then make sure none of the activities have more than the max number of shortcuts. 1002 for (int i = counts.size() - 1; i >= 0; i--) { 1003 service.enforceMaxActivityShortcuts(counts.valueAt(i)); 1004 } 1005 } 1006 1007 /** 1008 * For all the text fields, refresh the string values if they're from resources. 1009 */ 1010 public void resolveResourceStrings() { 1011 final ShortcutService s = mShortcutUser.mService; 1012 boolean changed = false; 1013 1014 Resources publisherRes = null; 1015 for (int i = mShortcuts.size() - 1; i >= 0; i--) { 1016 final ShortcutInfo si = mShortcuts.valueAt(i); 1017 1018 if (si.hasStringResources()) { 1019 changed = true; 1020 1021 if (publisherRes == null) { 1022 publisherRes = getPackageResources(); 1023 if (publisherRes == null) { 1024 break; // Resources couldn't be loaded. 1025 } 1026 } 1027 1028 si.resolveResourceStrings(publisherRes); 1029 si.setTimestamp(s.injectCurrentTimeMillis()); 1030 } 1031 } 1032 if (changed) { 1033 s.packageShortcutsChanged(getPackageName(), getPackageUserId()); 1034 } 1035 } 1036 1037 /** Clears the implicit ranks for all shortcuts. */ 1038 public void clearAllImplicitRanks() { 1039 for (int i = mShortcuts.size() - 1; i >= 0; i--) { 1040 final ShortcutInfo si = mShortcuts.valueAt(i); 1041 si.clearImplicitRankAndRankChangedFlag(); 1042 } 1043 } 1044 1045 /** 1046 * Used to sort shortcuts for rank auto-adjusting. 1047 */ 1048 final Comparator<ShortcutInfo> mShortcutRankComparator = (ShortcutInfo a, ShortcutInfo b) -> { 1049 // First, sort by rank. 1050 int ret = Integer.compare(a.getRank(), b.getRank()); 1051 if (ret != 0) { 1052 return ret; 1053 } 1054 // When ranks are tie, then prioritize the ones that have just been assigned new ranks. 1055 // e.g. when there are 3 shortcuts, "s1" "s2" and "s3" with rank 0, 1, 2 respectively, 1056 // adding a shortcut "s4" with rank 1 will "insert" it between "s1" and "s2", because 1057 // "s2" and "s4" have the same rank 1 but s4 has isRankChanged() set. 1058 // Similarly, updating s3's rank to 1 will insert it between s1 and s2. 1059 if (a.isRankChanged() != b.isRankChanged()) { 1060 return a.isRankChanged() ? -1 : 1; 1061 } 1062 // If they're still tie, sort by implicit rank -- i.e. preserve the order in which 1063 // they're passed to the API. 1064 ret = Integer.compare(a.getImplicitRank(), b.getImplicitRank()); 1065 if (ret != 0) { 1066 return ret; 1067 } 1068 // If they're stil tie, just sort by their IDs. 1069 // This may happen with updateShortcuts() -- see 1070 // the testUpdateShortcuts_noManifestShortcuts() test. 1071 return a.getId().compareTo(b.getId()); 1072 }; 1073 1074 /** 1075 * Re-calculate the ranks for all shortcuts. 1076 */ 1077 public void adjustRanks() { 1078 final ShortcutService s = mShortcutUser.mService; 1079 final long now = s.injectCurrentTimeMillis(); 1080 1081 // First, clear ranks for floating shortcuts. 1082 for (int i = mShortcuts.size() - 1; i >= 0; i--) { 1083 final ShortcutInfo si = mShortcuts.valueAt(i); 1084 if (si.isFloating()) { 1085 if (si.getRank() != 0) { 1086 si.setTimestamp(now); 1087 si.setRank(0); 1088 } 1089 } 1090 } 1091 1092 // Then adjust ranks. Ranks are unique for each activity, so we first need to sort 1093 // shortcuts to each activity. 1094 // Then sort the shortcuts within each activity with mShortcutRankComparator, and 1095 // assign ranks from 0. 1096 final ArrayMap<ComponentName, ArrayList<ShortcutInfo>> all = 1097 sortShortcutsToActivities(); 1098 for (int outer = all.size() - 1; outer >= 0; outer--) { // For each activity. 1099 final ArrayList<ShortcutInfo> list = all.valueAt(outer); 1100 1101 // Sort by ranks and other signals. 1102 Collections.sort(list, mShortcutRankComparator); 1103 1104 int rank = 0; 1105 1106 final int size = list.size(); 1107 for (int i = 0; i < size; i++) { 1108 final ShortcutInfo si = list.get(i); 1109 if (si.isManifestShortcut()) { 1110 // Don't adjust ranks for manifest shortcuts. 1111 continue; 1112 } 1113 // At this point, it must be dynamic. 1114 if (!si.isDynamic()) { 1115 s.wtf("Non-dynamic shortcut found."); 1116 continue; 1117 } 1118 final int thisRank = rank++; 1119 if (si.getRank() != thisRank) { 1120 si.setTimestamp(now); 1121 si.setRank(thisRank); 1122 } 1123 } 1124 } 1125 } 1126 1127 /** @return true if there's any shortcuts that are not manifest shortcuts. */ 1128 public boolean hasNonManifestShortcuts() { 1129 for (int i = mShortcuts.size() - 1; i >= 0; i--) { 1130 final ShortcutInfo si = mShortcuts.valueAt(i); 1131 if (!si.isDeclaredInManifest()) { 1132 return true; 1133 } 1134 } 1135 return false; 1136 } 1137 1138 public void dump(@NonNull PrintWriter pw, @NonNull String prefix) { 1139 pw.println(); 1140 1141 pw.print(prefix); 1142 pw.print("Package: "); 1143 pw.print(getPackageName()); 1144 pw.print(" UID: "); 1145 pw.print(mPackageUid); 1146 pw.println(); 1147 1148 pw.print(prefix); 1149 pw.print(" "); 1150 pw.print("Calls: "); 1151 pw.print(getApiCallCount()); 1152 pw.println(); 1153 1154 // getApiCallCount() may have updated mLastKnownForegroundElapsedTime. 1155 pw.print(prefix); 1156 pw.print(" "); 1157 pw.print("Last known FG: "); 1158 pw.print(mLastKnownForegroundElapsedTime); 1159 pw.println(); 1160 1161 // This should be after getApiCallCount(), which may update it. 1162 pw.print(prefix); 1163 pw.print(" "); 1164 pw.print("Last reset: ["); 1165 pw.print(mLastResetTime); 1166 pw.print("] "); 1167 pw.print(ShortcutService.formatTime(mLastResetTime)); 1168 pw.println(); 1169 1170 getPackageInfo().dump(pw, prefix + " "); 1171 pw.println(); 1172 1173 pw.print(prefix); 1174 pw.println(" Shortcuts:"); 1175 long totalBitmapSize = 0; 1176 final ArrayMap<String, ShortcutInfo> shortcuts = mShortcuts; 1177 final int size = shortcuts.size(); 1178 for (int i = 0; i < size; i++) { 1179 final ShortcutInfo si = shortcuts.valueAt(i); 1180 pw.print(prefix); 1181 pw.print(" "); 1182 pw.println(si.toInsecureString()); 1183 if (si.getBitmapPath() != null) { 1184 final long len = new File(si.getBitmapPath()).length(); 1185 pw.print(prefix); 1186 pw.print(" "); 1187 pw.print("bitmap size="); 1188 pw.println(len); 1189 1190 totalBitmapSize += len; 1191 } 1192 } 1193 pw.print(prefix); 1194 pw.print(" "); 1195 pw.print("Total bitmap size: "); 1196 pw.print(totalBitmapSize); 1197 pw.print(" ("); 1198 pw.print(Formatter.formatFileSize(mShortcutUser.mService.mContext, totalBitmapSize)); 1199 pw.println(")"); 1200 } 1201 1202 @Override 1203 public JSONObject dumpCheckin(boolean clear) throws JSONException { 1204 final JSONObject result = super.dumpCheckin(clear); 1205 1206 int numDynamic = 0; 1207 int numPinned = 0; 1208 int numManifest = 0; 1209 int numBitmaps = 0; 1210 long totalBitmapSize = 0; 1211 1212 final ArrayMap<String, ShortcutInfo> shortcuts = mShortcuts; 1213 final int size = shortcuts.size(); 1214 for (int i = 0; i < size; i++) { 1215 final ShortcutInfo si = shortcuts.valueAt(i); 1216 1217 if (si.isDynamic()) numDynamic++; 1218 if (si.isDeclaredInManifest()) numManifest++; 1219 if (si.isPinned()) numPinned++; 1220 1221 if (si.getBitmapPath() != null) { 1222 numBitmaps++; 1223 totalBitmapSize += new File(si.getBitmapPath()).length(); 1224 } 1225 } 1226 1227 result.put(KEY_DYNAMIC, numDynamic); 1228 result.put(KEY_MANIFEST, numManifest); 1229 result.put(KEY_PINNED, numPinned); 1230 result.put(KEY_BITMAPS, numBitmaps); 1231 result.put(KEY_BITMAP_BYTES, totalBitmapSize); 1232 1233 // TODO Log update frequency too. 1234 1235 return result; 1236 } 1237 1238 @Override 1239 public void saveToXml(@NonNull XmlSerializer out, boolean forBackup) 1240 throws IOException, XmlPullParserException { 1241 final int size = mShortcuts.size(); 1242 1243 if (size == 0 && mApiCallCount == 0) { 1244 return; // nothing to write. 1245 } 1246 1247 out.startTag(null, TAG_ROOT); 1248 1249 ShortcutService.writeAttr(out, ATTR_NAME, getPackageName()); 1250 ShortcutService.writeAttr(out, ATTR_CALL_COUNT, mApiCallCount); 1251 ShortcutService.writeAttr(out, ATTR_LAST_RESET, mLastResetTime); 1252 getPackageInfo().saveToXml(out); 1253 1254 for (int j = 0; j < size; j++) { 1255 saveShortcut(out, mShortcuts.valueAt(j), forBackup); 1256 } 1257 1258 out.endTag(null, TAG_ROOT); 1259 } 1260 1261 private static void saveShortcut(XmlSerializer out, ShortcutInfo si, boolean forBackup) 1262 throws IOException, XmlPullParserException { 1263 if (forBackup) { 1264 if (!(si.isPinned() && si.isEnabled())) { 1265 return; // We only backup pinned shortcuts that are enabled. 1266 } 1267 } 1268 out.startTag(null, TAG_SHORTCUT); 1269 ShortcutService.writeAttr(out, ATTR_ID, si.getId()); 1270 // writeAttr(out, "package", si.getPackageName()); // not needed 1271 ShortcutService.writeAttr(out, ATTR_ACTIVITY, si.getActivity()); 1272 // writeAttr(out, "icon", si.getIcon()); // We don't save it. 1273 ShortcutService.writeAttr(out, ATTR_TITLE, si.getTitle()); 1274 ShortcutService.writeAttr(out, ATTR_TITLE_RES_ID, si.getTitleResId()); 1275 ShortcutService.writeAttr(out, ATTR_TITLE_RES_NAME, si.getTitleResName()); 1276 ShortcutService.writeAttr(out, ATTR_TEXT, si.getText()); 1277 ShortcutService.writeAttr(out, ATTR_TEXT_RES_ID, si.getTextResId()); 1278 ShortcutService.writeAttr(out, ATTR_TEXT_RES_NAME, si.getTextResName()); 1279 ShortcutService.writeAttr(out, ATTR_DISABLED_MESSAGE, si.getDisabledMessage()); 1280 ShortcutService.writeAttr(out, ATTR_DISABLED_MESSAGE_RES_ID, 1281 si.getDisabledMessageResourceId()); 1282 ShortcutService.writeAttr(out, ATTR_DISABLED_MESSAGE_RES_NAME, 1283 si.getDisabledMessageResName()); 1284 ShortcutService.writeAttr(out, ATTR_TIMESTAMP, 1285 si.getLastChangedTimestamp()); 1286 if (forBackup) { 1287 // Don't write icon information. Also drop the dynamic flag. 1288 ShortcutService.writeAttr(out, ATTR_FLAGS, 1289 si.getFlags() & 1290 ~(ShortcutInfo.FLAG_HAS_ICON_FILE | ShortcutInfo.FLAG_HAS_ICON_RES 1291 | ShortcutInfo.FLAG_DYNAMIC)); 1292 } else { 1293 // When writing for backup, ranks shouldn't be saved, since shortcuts won't be restored 1294 // as dynamic. 1295 ShortcutService.writeAttr(out, ATTR_RANK, si.getRank()); 1296 1297 ShortcutService.writeAttr(out, ATTR_FLAGS, si.getFlags()); 1298 ShortcutService.writeAttr(out, ATTR_ICON_RES_ID, si.getIconResourceId()); 1299 ShortcutService.writeAttr(out, ATTR_ICON_RES_NAME, si.getIconResName()); 1300 ShortcutService.writeAttr(out, ATTR_BITMAP_PATH, si.getBitmapPath()); 1301 } 1302 1303 { 1304 final Set<String> cat = si.getCategories(); 1305 if (cat != null && cat.size() > 0) { 1306 out.startTag(null, TAG_CATEGORIES); 1307 XmlUtils.writeStringArrayXml(cat.toArray(new String[cat.size()]), 1308 NAME_CATEGORIES, out); 1309 out.endTag(null, TAG_CATEGORIES); 1310 } 1311 } 1312 final Intent[] intentsNoExtras = si.getIntentsNoExtras(); 1313 final PersistableBundle[] intentsExtras = si.getIntentPersistableExtrases(); 1314 final int numIntents = intentsNoExtras.length; 1315 for (int i = 0; i < numIntents; i++) { 1316 out.startTag(null, TAG_INTENT); 1317 ShortcutService.writeAttr(out, ATTR_INTENT_NO_EXTRA, intentsNoExtras[i]); 1318 ShortcutService.writeTagExtra(out, TAG_EXTRAS, intentsExtras[i]); 1319 out.endTag(null, TAG_INTENT); 1320 } 1321 1322 ShortcutService.writeTagExtra(out, TAG_EXTRAS, si.getExtras()); 1323 1324 out.endTag(null, TAG_SHORTCUT); 1325 } 1326 1327 public static ShortcutPackage loadFromXml(ShortcutService s, ShortcutUser shortcutUser, 1328 XmlPullParser parser, boolean fromBackup) 1329 throws IOException, XmlPullParserException { 1330 1331 final String packageName = ShortcutService.parseStringAttribute(parser, 1332 ATTR_NAME); 1333 1334 final ShortcutPackage ret = new ShortcutPackage(shortcutUser, 1335 shortcutUser.getUserId(), packageName); 1336 1337 ret.mApiCallCount = 1338 ShortcutService.parseIntAttribute(parser, ATTR_CALL_COUNT); 1339 ret.mLastResetTime = 1340 ShortcutService.parseLongAttribute(parser, ATTR_LAST_RESET); 1341 1342 final int outerDepth = parser.getDepth(); 1343 int type; 1344 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 1345 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 1346 if (type != XmlPullParser.START_TAG) { 1347 continue; 1348 } 1349 final int depth = parser.getDepth(); 1350 final String tag = parser.getName(); 1351 if (depth == outerDepth + 1) { 1352 switch (tag) { 1353 case ShortcutPackageInfo.TAG_ROOT: 1354 ret.getPackageInfo().loadFromXml(parser, fromBackup); 1355 continue; 1356 case TAG_SHORTCUT: 1357 final ShortcutInfo si = parseShortcut(parser, packageName, 1358 shortcutUser.getUserId()); 1359 1360 // Don't use addShortcut(), we don't need to save the icon. 1361 ret.mShortcuts.put(si.getId(), si); 1362 continue; 1363 } 1364 } 1365 ShortcutService.warnForInvalidTag(depth, tag); 1366 } 1367 return ret; 1368 } 1369 1370 private static ShortcutInfo parseShortcut(XmlPullParser parser, String packageName, 1371 @UserIdInt int userId) throws IOException, XmlPullParserException { 1372 String id; 1373 ComponentName activityComponent; 1374 // Icon icon; 1375 String title; 1376 int titleResId; 1377 String titleResName; 1378 String text; 1379 int textResId; 1380 String textResName; 1381 String disabledMessage; 1382 int disabledMessageResId; 1383 String disabledMessageResName; 1384 Intent intentLegacy; 1385 PersistableBundle intentPersistableExtrasLegacy = null; 1386 ArrayList<Intent> intents = new ArrayList<>(); 1387 int rank; 1388 PersistableBundle extras = null; 1389 long lastChangedTimestamp; 1390 int flags; 1391 int iconResId; 1392 String iconResName; 1393 String bitmapPath; 1394 ArraySet<String> categories = null; 1395 1396 id = ShortcutService.parseStringAttribute(parser, ATTR_ID); 1397 activityComponent = ShortcutService.parseComponentNameAttribute(parser, 1398 ATTR_ACTIVITY); 1399 title = ShortcutService.parseStringAttribute(parser, ATTR_TITLE); 1400 titleResId = ShortcutService.parseIntAttribute(parser, ATTR_TITLE_RES_ID); 1401 titleResName = ShortcutService.parseStringAttribute(parser, ATTR_TITLE_RES_NAME); 1402 text = ShortcutService.parseStringAttribute(parser, ATTR_TEXT); 1403 textResId = ShortcutService.parseIntAttribute(parser, ATTR_TEXT_RES_ID); 1404 textResName = ShortcutService.parseStringAttribute(parser, ATTR_TEXT_RES_NAME); 1405 disabledMessage = ShortcutService.parseStringAttribute(parser, ATTR_DISABLED_MESSAGE); 1406 disabledMessageResId = ShortcutService.parseIntAttribute(parser, 1407 ATTR_DISABLED_MESSAGE_RES_ID); 1408 disabledMessageResName = ShortcutService.parseStringAttribute(parser, 1409 ATTR_DISABLED_MESSAGE_RES_NAME); 1410 intentLegacy = ShortcutService.parseIntentAttributeNoDefault(parser, ATTR_INTENT_LEGACY); 1411 rank = (int) ShortcutService.parseLongAttribute(parser, ATTR_RANK); 1412 lastChangedTimestamp = ShortcutService.parseLongAttribute(parser, ATTR_TIMESTAMP); 1413 flags = (int) ShortcutService.parseLongAttribute(parser, ATTR_FLAGS); 1414 iconResId = (int) ShortcutService.parseLongAttribute(parser, ATTR_ICON_RES_ID); 1415 iconResName = ShortcutService.parseStringAttribute(parser, ATTR_ICON_RES_NAME); 1416 bitmapPath = ShortcutService.parseStringAttribute(parser, ATTR_BITMAP_PATH); 1417 1418 final int outerDepth = parser.getDepth(); 1419 int type; 1420 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 1421 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 1422 if (type != XmlPullParser.START_TAG) { 1423 continue; 1424 } 1425 final int depth = parser.getDepth(); 1426 final String tag = parser.getName(); 1427 if (ShortcutService.DEBUG_LOAD) { 1428 Slog.d(TAG, String.format(" depth=%d type=%d name=%s", 1429 depth, type, tag)); 1430 } 1431 switch (tag) { 1432 case TAG_INTENT_EXTRAS_LEGACY: 1433 intentPersistableExtrasLegacy = PersistableBundle.restoreFromXml(parser); 1434 continue; 1435 case TAG_INTENT: 1436 intents.add(parseIntent(parser)); 1437 continue; 1438 case TAG_EXTRAS: 1439 extras = PersistableBundle.restoreFromXml(parser); 1440 continue; 1441 case TAG_CATEGORIES: 1442 // This just contains string-array. 1443 continue; 1444 case TAG_STRING_ARRAY_XMLUTILS: 1445 if (NAME_CATEGORIES.equals(ShortcutService.parseStringAttribute(parser, 1446 ATTR_NAME_XMLUTILS))) { 1447 final String[] ar = XmlUtils.readThisStringArrayXml( 1448 parser, TAG_STRING_ARRAY_XMLUTILS, null); 1449 categories = new ArraySet<>(ar.length); 1450 for (int i = 0; i < ar.length; i++) { 1451 categories.add(ar[i]); 1452 } 1453 } 1454 continue; 1455 } 1456 throw ShortcutService.throwForInvalidTag(depth, tag); 1457 } 1458 1459 if (intentLegacy != null) { 1460 // For the legacy file format which supported only one intent per shortcut. 1461 ShortcutInfo.setIntentExtras(intentLegacy, intentPersistableExtrasLegacy); 1462 intents.clear(); 1463 intents.add(intentLegacy); 1464 } 1465 1466 return new ShortcutInfo( 1467 userId, id, packageName, activityComponent, /* icon =*/ null, 1468 title, titleResId, titleResName, text, textResId, textResName, 1469 disabledMessage, disabledMessageResId, disabledMessageResName, 1470 categories, 1471 intents.toArray(new Intent[intents.size()]), 1472 rank, extras, lastChangedTimestamp, flags, 1473 iconResId, iconResName, bitmapPath); 1474 } 1475 1476 private static Intent parseIntent(XmlPullParser parser) 1477 throws IOException, XmlPullParserException { 1478 1479 Intent intent = ShortcutService.parseIntentAttribute(parser, 1480 ATTR_INTENT_NO_EXTRA); 1481 1482 final int outerDepth = parser.getDepth(); 1483 int type; 1484 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 1485 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 1486 if (type != XmlPullParser.START_TAG) { 1487 continue; 1488 } 1489 final int depth = parser.getDepth(); 1490 final String tag = parser.getName(); 1491 if (ShortcutService.DEBUG_LOAD) { 1492 Slog.d(TAG, String.format(" depth=%d type=%d name=%s", 1493 depth, type, tag)); 1494 } 1495 switch (tag) { 1496 case TAG_EXTRAS: 1497 ShortcutInfo.setIntentExtras(intent, 1498 PersistableBundle.restoreFromXml(parser)); 1499 continue; 1500 } 1501 throw ShortcutService.throwForInvalidTag(depth, tag); 1502 } 1503 return intent; 1504 } 1505 1506 @VisibleForTesting 1507 List<ShortcutInfo> getAllShortcutsForTest() { 1508 return new ArrayList<>(mShortcuts.values()); 1509 } 1510 1511 @Override 1512 public void verifyStates() { 1513 super.verifyStates(); 1514 1515 boolean failed = false; 1516 1517 final ArrayMap<ComponentName, ArrayList<ShortcutInfo>> all = 1518 sortShortcutsToActivities(); 1519 1520 // Make sure each activity won't have more than max shortcuts. 1521 for (int outer = all.size() - 1; outer >= 0; outer--) { 1522 final ArrayList<ShortcutInfo> list = all.valueAt(outer); 1523 if (list.size() > mShortcutUser.mService.getMaxActivityShortcuts()) { 1524 failed = true; 1525 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": activity " + all.keyAt(outer) 1526 + " has " + all.valueAt(outer).size() + " shortcuts."); 1527 } 1528 1529 // Sort by rank. 1530 Collections.sort(list, (a, b) -> Integer.compare(a.getRank(), b.getRank())); 1531 1532 // Split into two arrays for each kind. 1533 final ArrayList<ShortcutInfo> dynamicList = new ArrayList<>(list); 1534 dynamicList.removeIf((si) -> !si.isDynamic()); 1535 1536 final ArrayList<ShortcutInfo> manifestList = new ArrayList<>(list); 1537 dynamicList.removeIf((si) -> !si.isManifestShortcut()); 1538 1539 verifyRanksSequential(dynamicList); 1540 verifyRanksSequential(manifestList); 1541 } 1542 1543 // Verify each shortcut's status. 1544 for (int i = mShortcuts.size() - 1; i >= 0; i--) { 1545 final ShortcutInfo si = mShortcuts.valueAt(i); 1546 if (!(si.isDeclaredInManifest() || si.isDynamic() || si.isPinned())) { 1547 failed = true; 1548 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId() 1549 + " is not manifest, dynamic or pinned."); 1550 } 1551 if (si.isDeclaredInManifest() && si.isDynamic()) { 1552 failed = true; 1553 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId() 1554 + " is both dynamic and manifest at the same time."); 1555 } 1556 if (si.getActivity() == null) { 1557 failed = true; 1558 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId() 1559 + " has null activity."); 1560 } 1561 if ((si.isDynamic() || si.isManifestShortcut()) && !si.isEnabled()) { 1562 failed = true; 1563 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId() 1564 + " is not floating, but is disabled."); 1565 } 1566 if (si.isFloating() && si.getRank() != 0) { 1567 failed = true; 1568 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId() 1569 + " is floating, but has rank=" + si.getRank()); 1570 } 1571 if (si.getIcon() != null) { 1572 failed = true; 1573 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId() 1574 + " still has an icon"); 1575 } 1576 if (si.hasIconFile() && si.hasIconResource()) { 1577 failed = true; 1578 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId() 1579 + " has both resource and bitmap icons"); 1580 } 1581 } 1582 1583 if (failed) { 1584 throw new IllegalStateException("See logcat for errors"); 1585 } 1586 } 1587 1588 private boolean verifyRanksSequential(List<ShortcutInfo> list) { 1589 boolean failed = false; 1590 1591 for (int i = 0; i < list.size(); i++) { 1592 final ShortcutInfo si = list.get(i); 1593 if (si.getRank() != i) { 1594 failed = true; 1595 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId() 1596 + " rank=" + si.getRank() + " but expected to be "+ i); 1597 } 1598 } 1599 return failed; 1600 } 1601} 1602