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