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