ShortcutService.java revision 8a372a0a280127743ce9a7ce4b6198c7a02d2a4f
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.app.ActivityManager; 22import android.content.ComponentName; 23import android.content.ContentProvider; 24import android.content.Context; 25import android.content.Intent; 26import android.content.pm.IShortcutService; 27import android.content.pm.LauncherApps; 28import android.content.pm.LauncherApps.ShortcutQuery; 29import android.content.pm.PackageManager; 30import android.content.pm.PackageManager.NameNotFoundException; 31import android.content.pm.PackageManagerInternal; 32import android.content.pm.ParceledListSlice; 33import android.content.pm.ResolveInfo; 34import android.content.pm.ShortcutInfo; 35import android.content.pm.ShortcutServiceInternal; 36import android.content.pm.ShortcutServiceInternal.ShortcutChangeListener; 37import android.graphics.Bitmap; 38import android.graphics.Bitmap.CompressFormat; 39import android.graphics.BitmapFactory; 40import android.graphics.Canvas; 41import android.graphics.RectF; 42import android.graphics.drawable.Icon; 43import android.net.Uri; 44import android.os.Binder; 45import android.os.Environment; 46import android.os.Handler; 47import android.os.ParcelFileDescriptor; 48import android.os.PersistableBundle; 49import android.os.Process; 50import android.os.RemoteException; 51import android.os.ResultReceiver; 52import android.os.SELinux; 53import android.os.ShellCommand; 54import android.os.UserHandle; 55import android.text.TextUtils; 56import android.text.format.Formatter; 57import android.text.format.Time; 58import android.util.ArrayMap; 59import android.util.ArraySet; 60import android.util.AtomicFile; 61import android.util.KeyValueListParser; 62import android.util.Slog; 63import android.util.SparseArray; 64import android.util.TypedValue; 65import android.util.Xml; 66 67import com.android.internal.annotations.GuardedBy; 68import com.android.internal.annotations.VisibleForTesting; 69import com.android.internal.os.BackgroundThread; 70import com.android.internal.util.FastXmlSerializer; 71import com.android.internal.util.Preconditions; 72import com.android.server.LocalServices; 73import com.android.server.SystemService; 74 75import libcore.io.IoUtils; 76import libcore.util.Objects; 77 78import org.xmlpull.v1.XmlPullParser; 79import org.xmlpull.v1.XmlPullParserException; 80import org.xmlpull.v1.XmlSerializer; 81 82import java.io.File; 83import java.io.FileDescriptor; 84import java.io.FileInputStream; 85import java.io.FileNotFoundException; 86import java.io.FileOutputStream; 87import java.io.IOException; 88import java.io.InputStream; 89import java.io.PrintWriter; 90import java.net.URISyntaxException; 91import java.nio.charset.StandardCharsets; 92import java.util.ArrayList; 93import java.util.List; 94import java.util.function.Predicate; 95 96/** 97 * TODO: 98 * 99 * - Detect when already registered instances are passed to APIs again, which might break 100 * internal bitmap handling. 101 * 102 * - Listen to PACKAGE_*, remove orphan info, update timestamp for icon res 103 * -> Need to scan all packages when a user starts too. 104 * -> Clear data -> remove all dynamic? but not the pinned? 105 * 106 * - Pinned per each launcher package (multiple launchers) 107 * 108 * - Make save async (should we?) 109 * 110 * - Scan and remove orphan bitmaps (just in case). 111 * 112 * - Backup & restore 113 */ 114public class ShortcutService extends IShortcutService.Stub { 115 static final String TAG = "ShortcutService"; 116 117 static final boolean DEBUG = false; // STOPSHIP if true 118 static final boolean DEBUG_LOAD = false; // STOPSHIP if true 119 120 @VisibleForTesting 121 static final long DEFAULT_RESET_INTERVAL_SEC = 24 * 60 * 60; // 1 day 122 123 @VisibleForTesting 124 static final int DEFAULT_MAX_DAILY_UPDATES = 10; 125 126 @VisibleForTesting 127 static final int DEFAULT_MAX_SHORTCUTS_PER_APP = 5; 128 129 @VisibleForTesting 130 static final int DEFAULT_MAX_ICON_DIMENSION_DP = 96; 131 132 @VisibleForTesting 133 static final int DEFAULT_MAX_ICON_DIMENSION_LOWRAM_DP = 48; 134 135 @VisibleForTesting 136 static final String DEFAULT_ICON_PERSIST_FORMAT = CompressFormat.PNG.name(); 137 138 @VisibleForTesting 139 static final int DEFAULT_ICON_PERSIST_QUALITY = 100; 140 141 private static final int SAVE_DELAY_MS = 5000; // in milliseconds. 142 143 @VisibleForTesting 144 static final String FILENAME_BASE_STATE = "shortcut_service.xml"; 145 146 @VisibleForTesting 147 static final String DIRECTORY_PER_USER = "shortcut_service"; 148 149 @VisibleForTesting 150 static final String FILENAME_USER_PACKAGES = "shortcuts.xml"; 151 152 static final String DIRECTORY_BITMAPS = "bitmaps"; 153 154 static final String TAG_ROOT = "root"; 155 static final String TAG_USER = "user"; 156 static final String TAG_PACKAGE = "package"; 157 static final String TAG_LAST_RESET_TIME = "last_reset_time"; 158 static final String TAG_INTENT_EXTRAS = "intent-extras"; 159 static final String TAG_EXTRAS = "extras"; 160 static final String TAG_SHORTCUT = "shortcut"; 161 static final String TAG_LAUNCHER = "launcher"; 162 163 static final String ATTR_VALUE = "value"; 164 static final String ATTR_NAME = "name"; 165 static final String ATTR_DYNAMIC_COUNT = "dynamic-count"; 166 static final String ATTR_CALL_COUNT = "call-count"; 167 static final String ATTR_LAST_RESET = "last-reset"; 168 static final String ATTR_ID = "id"; 169 static final String ATTR_ACTIVITY = "activity"; 170 static final String ATTR_TITLE = "title"; 171 static final String ATTR_INTENT = "intent"; 172 static final String ATTR_WEIGHT = "weight"; 173 static final String ATTR_TIMESTAMP = "timestamp"; 174 static final String ATTR_FLAGS = "flags"; 175 static final String ATTR_ICON_RES = "icon-res"; 176 static final String ATTR_BITMAP_PATH = "bitmap-path"; 177 178 @VisibleForTesting 179 interface ConfigConstants { 180 /** 181 * Key name for the throttling reset interval, in seconds. (long) 182 */ 183 String KEY_RESET_INTERVAL_SEC = "reset_interval_sec"; 184 185 /** 186 * Key name for the max number of modifying API calls per app for every interval. (int) 187 */ 188 String KEY_MAX_DAILY_UPDATES = "max_daily_updates"; 189 190 /** 191 * Key name for the max icon dimensions in DP, for non-low-memory devices. 192 */ 193 String KEY_MAX_ICON_DIMENSION_DP = "max_icon_dimension_dp"; 194 195 /** 196 * Key name for the max icon dimensions in DP, for low-memory devices. 197 */ 198 String KEY_MAX_ICON_DIMENSION_DP_LOWRAM = "max_icon_dimension_dp_lowram"; 199 200 /** 201 * Key name for the max dynamic shortcuts per app. (int) 202 */ 203 String KEY_MAX_SHORTCUTS = "max_shortcuts"; 204 205 /** 206 * Key name for icon compression quality, 0-100. 207 */ 208 String KEY_ICON_QUALITY = "icon_quality"; 209 210 /** 211 * Key name for icon compression format: "PNG", "JPEG" or "WEBP" 212 */ 213 String KEY_ICON_FORMAT = "icon_format"; 214 } 215 216 final Context mContext; 217 218 private final Object mLock = new Object(); 219 220 private final Handler mHandler; 221 222 @GuardedBy("mLock") 223 private final ArrayList<ShortcutChangeListener> mListeners = new ArrayList<>(1); 224 225 @GuardedBy("mLock") 226 private long mRawLastResetTime; 227 228 /** 229 * User ID -> UserShortcuts 230 */ 231 @GuardedBy("mLock") 232 private final SparseArray<UserShortcuts> mUsers = new SparseArray<>(); 233 234 /** 235 * Max number of dynamic shortcuts that each application can have at a time. 236 */ 237 private int mMaxDynamicShortcuts; 238 239 /** 240 * Max number of updating API calls that each application can make a day. 241 */ 242 int mMaxDailyUpdates; 243 244 /** 245 * Actual throttling-reset interval. By default it's a day. 246 */ 247 private long mResetInterval; 248 249 /** 250 * Icon max width/height in pixels. 251 */ 252 private int mMaxIconDimension; 253 254 private CompressFormat mIconPersistFormat; 255 private int mIconPersistQuality; 256 257 private final PackageManagerInternal mPackageManagerInternal; 258 259 public ShortcutService(Context context) { 260 mContext = Preconditions.checkNotNull(context); 261 LocalServices.addService(ShortcutServiceInternal.class, new LocalService()); 262 mHandler = new Handler(BackgroundThread.get().getLooper()); 263 mPackageManagerInternal = LocalServices.getService(PackageManagerInternal.class); 264 } 265 266 /** 267 * System service lifecycle. 268 */ 269 public static final class Lifecycle extends SystemService { 270 final ShortcutService mService; 271 272 public Lifecycle(Context context) { 273 super(context); 274 mService = new ShortcutService(context); 275 } 276 277 @Override 278 public void onStart() { 279 publishBinderService(Context.SHORTCUT_SERVICE, mService); 280 } 281 282 @Override 283 public void onBootPhase(int phase) { 284 mService.onBootPhase(phase); 285 } 286 287 @Override 288 public void onCleanupUser(int userHandle) { 289 synchronized (mService.mLock) { 290 mService.onCleanupUserInner(userHandle); 291 } 292 } 293 294 @Override 295 public void onUnlockUser(int userId) { 296 synchronized (mService.mLock) { 297 mService.onStartUserLocked(userId); 298 } 299 } 300 } 301 302 /** lifecycle event */ 303 void onBootPhase(int phase) { 304 if (DEBUG) { 305 Slog.d(TAG, "onBootPhase: " + phase); 306 } 307 switch (phase) { 308 case SystemService.PHASE_LOCK_SETTINGS_READY: 309 initialize(); 310 break; 311 } 312 } 313 314 /** lifecycle event */ 315 void onStartUserLocked(int userId) { 316 // Preload 317 getUserShortcutsLocked(userId); 318 } 319 320 /** lifecycle event */ 321 void onCleanupUserInner(int userId) { 322 // Unload 323 mUsers.delete(userId); 324 } 325 326 /** Return the base state file name */ 327 private AtomicFile getBaseStateFile() { 328 final File path = new File(injectSystemDataPath(), FILENAME_BASE_STATE); 329 path.mkdirs(); 330 return new AtomicFile(path); 331 } 332 333 /** 334 * Init the instance. (load the state file, etc) 335 */ 336 private void initialize() { 337 synchronized (mLock) { 338 loadConfigurationLocked(); 339 loadBaseStateLocked(); 340 } 341 } 342 343 /** 344 * Load the configuration from Settings. 345 */ 346 private void loadConfigurationLocked() { 347 updateConfigurationLocked(injectShortcutManagerConstants()); 348 } 349 350 /** 351 * Load the configuration from Settings. 352 */ 353 @VisibleForTesting 354 boolean updateConfigurationLocked(String config) { 355 boolean result = true; 356 357 final KeyValueListParser parser = new KeyValueListParser(','); 358 try { 359 parser.setString(config); 360 } catch (IllegalArgumentException e) { 361 // Failed to parse the settings string, log this and move on 362 // with defaults. 363 Slog.e(TAG, "Bad shortcut manager settings", e); 364 result = false; 365 } 366 367 mResetInterval = parser.getLong( 368 ConfigConstants.KEY_RESET_INTERVAL_SEC, DEFAULT_RESET_INTERVAL_SEC) 369 * 1000L; 370 371 mMaxDailyUpdates = (int) parser.getLong( 372 ConfigConstants.KEY_MAX_DAILY_UPDATES, DEFAULT_MAX_DAILY_UPDATES); 373 374 mMaxDynamicShortcuts = (int) parser.getLong( 375 ConfigConstants.KEY_MAX_SHORTCUTS, DEFAULT_MAX_SHORTCUTS_PER_APP); 376 377 final int iconDimensionDp = injectIsLowRamDevice() 378 ? (int) parser.getLong( 379 ConfigConstants.KEY_MAX_ICON_DIMENSION_DP_LOWRAM, 380 DEFAULT_MAX_ICON_DIMENSION_LOWRAM_DP) 381 : (int) parser.getLong( 382 ConfigConstants.KEY_MAX_ICON_DIMENSION_DP, 383 DEFAULT_MAX_ICON_DIMENSION_DP); 384 385 mMaxIconDimension = injectDipToPixel(iconDimensionDp); 386 387 mIconPersistFormat = CompressFormat.valueOf( 388 parser.getString(ConfigConstants.KEY_ICON_FORMAT, DEFAULT_ICON_PERSIST_FORMAT)); 389 390 mIconPersistQuality = (int) parser.getLong( 391 ConfigConstants.KEY_ICON_QUALITY, 392 DEFAULT_ICON_PERSIST_QUALITY); 393 394 return result; 395 } 396 397 @VisibleForTesting 398 String injectShortcutManagerConstants() { 399 return android.provider.Settings.Global.getString( 400 mContext.getContentResolver(), 401 android.provider.Settings.Global.SHORTCUT_MANAGER_CONSTANTS); 402 } 403 404 @VisibleForTesting 405 int injectDipToPixel(int dip) { 406 return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, 407 mContext.getResources().getDisplayMetrics()); 408 } 409 410 // === Persisting === 411 412 @Nullable 413 static String parseStringAttribute(XmlPullParser parser, String attribute) { 414 return parser.getAttributeValue(null, attribute); 415 } 416 417 static int parseIntAttribute(XmlPullParser parser, String attribute) { 418 return (int) parseLongAttribute(parser, attribute); 419 } 420 421 static long parseLongAttribute(XmlPullParser parser, String attribute) { 422 final String value = parseStringAttribute(parser, attribute); 423 if (TextUtils.isEmpty(value)) { 424 return 0; 425 } 426 try { 427 return Long.parseLong(value); 428 } catch (NumberFormatException e) { 429 Slog.e(TAG, "Error parsing long " + value); 430 return 0; 431 } 432 } 433 434 @Nullable 435 static ComponentName parseComponentNameAttribute(XmlPullParser parser, String attribute) { 436 final String value = parseStringAttribute(parser, attribute); 437 if (TextUtils.isEmpty(value)) { 438 return null; 439 } 440 return ComponentName.unflattenFromString(value); 441 } 442 443 @Nullable 444 static Intent parseIntentAttribute(XmlPullParser parser, String attribute) { 445 final String value = parseStringAttribute(parser, attribute); 446 if (TextUtils.isEmpty(value)) { 447 return null; 448 } 449 try { 450 return Intent.parseUri(value, /* flags =*/ 0); 451 } catch (URISyntaxException e) { 452 Slog.e(TAG, "Error parsing intent", e); 453 return null; 454 } 455 } 456 457 static void writeTagValue(XmlSerializer out, String tag, String value) throws IOException { 458 if (TextUtils.isEmpty(value)) return; 459 460 out.startTag(null, tag); 461 out.attribute(null, ATTR_VALUE, value); 462 out.endTag(null, tag); 463 } 464 465 static void writeTagValue(XmlSerializer out, String tag, long value) throws IOException { 466 writeTagValue(out, tag, Long.toString(value)); 467 } 468 469 static void writeTagValue(XmlSerializer out, String tag, ComponentName name) throws IOException { 470 if (name == null) return; 471 writeTagValue(out, tag, name.flattenToString()); 472 } 473 474 static void writeTagExtra(XmlSerializer out, String tag, PersistableBundle bundle) 475 throws IOException, XmlPullParserException { 476 if (bundle == null) return; 477 478 out.startTag(null, tag); 479 bundle.saveToXml(out); 480 out.endTag(null, tag); 481 } 482 483 static void writeAttr(XmlSerializer out, String name, String value) throws IOException { 484 if (TextUtils.isEmpty(value)) return; 485 486 out.attribute(null, name, value); 487 } 488 489 static void writeAttr(XmlSerializer out, String name, long value) throws IOException { 490 writeAttr(out, name, String.valueOf(value)); 491 } 492 493 static void writeAttr(XmlSerializer out, String name, ComponentName comp) throws IOException { 494 if (comp == null) return; 495 writeAttr(out, name, comp.flattenToString()); 496 } 497 498 static void writeAttr(XmlSerializer out, String name, Intent intent) throws IOException { 499 if (intent == null) return; 500 501 writeAttr(out, name, intent.toUri(/* flags =*/ 0)); 502 } 503 504 @VisibleForTesting 505 void saveBaseStateLocked() { 506 final AtomicFile file = getBaseStateFile(); 507 if (DEBUG) { 508 Slog.i(TAG, "Saving to " + file.getBaseFile()); 509 } 510 511 FileOutputStream outs = null; 512 try { 513 outs = file.startWrite(); 514 515 // Write to XML 516 XmlSerializer out = new FastXmlSerializer(); 517 out.setOutput(outs, StandardCharsets.UTF_8.name()); 518 out.startDocument(null, true); 519 out.startTag(null, TAG_ROOT); 520 521 // Body. 522 writeTagValue(out, TAG_LAST_RESET_TIME, mRawLastResetTime); 523 524 // Epilogue. 525 out.endTag(null, TAG_ROOT); 526 out.endDocument(); 527 528 // Close. 529 file.finishWrite(outs); 530 } catch (IOException e) { 531 Slog.e(TAG, "Failed to write to file " + file.getBaseFile(), e); 532 file.failWrite(outs); 533 } 534 } 535 536 private void loadBaseStateLocked() { 537 mRawLastResetTime = 0; 538 539 final AtomicFile file = getBaseStateFile(); 540 if (DEBUG) { 541 Slog.i(TAG, "Loading from " + file.getBaseFile()); 542 } 543 try (FileInputStream in = file.openRead()) { 544 XmlPullParser parser = Xml.newPullParser(); 545 parser.setInput(in, StandardCharsets.UTF_8.name()); 546 547 int type; 548 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) { 549 if (type != XmlPullParser.START_TAG) { 550 continue; 551 } 552 final int depth = parser.getDepth(); 553 // Check the root tag 554 final String tag = parser.getName(); 555 if (depth == 1) { 556 if (!TAG_ROOT.equals(tag)) { 557 Slog.e(TAG, "Invalid root tag: " + tag); 558 return; 559 } 560 continue; 561 } 562 // Assume depth == 2 563 switch (tag) { 564 case TAG_LAST_RESET_TIME: 565 mRawLastResetTime = parseLongAttribute(parser, ATTR_VALUE); 566 break; 567 default: 568 Slog.e(TAG, "Invalid tag: " + tag); 569 break; 570 } 571 } 572 } catch (FileNotFoundException e) { 573 // Use the default 574 } catch (IOException|XmlPullParserException e) { 575 Slog.e(TAG, "Failed to read file " + file.getBaseFile(), e); 576 577 mRawLastResetTime = 0; 578 } 579 // Adjust the last reset time. 580 getLastResetTimeLocked(); 581 } 582 583 private void saveUserLocked(@UserIdInt int userId) { 584 final File path = new File(injectUserDataPath(userId), FILENAME_USER_PACKAGES); 585 if (DEBUG) { 586 Slog.i(TAG, "Saving to " + path); 587 } 588 path.mkdirs(); 589 final AtomicFile file = new AtomicFile(path); 590 FileOutputStream outs = null; 591 try { 592 outs = file.startWrite(); 593 594 // Write to XML 595 XmlSerializer out = new FastXmlSerializer(); 596 out.setOutput(outs, StandardCharsets.UTF_8.name()); 597 out.startDocument(null, true); 598 599 getUserShortcutsLocked(userId).saveToXml(out); 600 601 out.endDocument(); 602 603 // Close. 604 file.finishWrite(outs); 605 } catch (IOException|XmlPullParserException e) { 606 Slog.e(TAG, "Failed to write to file " + file.getBaseFile(), e); 607 file.failWrite(outs); 608 } 609 } 610 611 static IOException throwForInvalidTag(int depth, String tag) throws IOException { 612 throw new IOException(String.format("Invalid tag '%s' found at depth %d", tag, depth)); 613 } 614 615 @Nullable 616 private UserShortcuts loadUserLocked(@UserIdInt int userId) { 617 final File path = new File(injectUserDataPath(userId), FILENAME_USER_PACKAGES); 618 if (DEBUG) { 619 Slog.i(TAG, "Loading from " + path); 620 } 621 final AtomicFile file = new AtomicFile(path); 622 623 final FileInputStream in; 624 try { 625 in = file.openRead(); 626 } catch (FileNotFoundException e) { 627 if (DEBUG) { 628 Slog.i(TAG, "Not found " + path); 629 } 630 return null; 631 } 632 UserShortcuts ret = null; 633 try { 634 XmlPullParser parser = Xml.newPullParser(); 635 parser.setInput(in, StandardCharsets.UTF_8.name()); 636 637 int type; 638 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) { 639 if (type != XmlPullParser.START_TAG) { 640 continue; 641 } 642 final int depth = parser.getDepth(); 643 644 final String tag = parser.getName(); 645 if (DEBUG_LOAD) { 646 Slog.d(TAG, String.format("depth=%d type=%d name=%s", 647 depth, type, tag)); 648 } 649 if ((depth == 1) && TAG_USER.equals(tag)) { 650 ret = UserShortcuts.loadFromXml(parser, userId); 651 continue; 652 } 653 throwForInvalidTag(depth, tag); 654 } 655 return ret; 656 } catch (IOException|XmlPullParserException e) { 657 Slog.e(TAG, "Failed to read file " + file.getBaseFile(), e); 658 return null; 659 } finally { 660 IoUtils.closeQuietly(in); 661 } 662 } 663 664 // TODO Actually make it async. 665 private void scheduleSaveBaseState() { 666 synchronized (mLock) { 667 saveBaseStateLocked(); 668 } 669 } 670 671 // TODO Actually make it async. 672 void scheduleSaveUser(@UserIdInt int userId) { 673 synchronized (mLock) { 674 saveUserLocked(userId); 675 } 676 } 677 678 /** Return the last reset time. */ 679 long getLastResetTimeLocked() { 680 updateTimes(); 681 return mRawLastResetTime; 682 } 683 684 /** Return the next reset time. */ 685 long getNextResetTimeLocked() { 686 updateTimes(); 687 return mRawLastResetTime + mResetInterval; 688 } 689 690 static boolean isClockValid(long time) { 691 return time >= 1420070400; // Thu, 01 Jan 2015 00:00:00 GMT 692 } 693 694 /** 695 * Update the last reset time. 696 */ 697 private void updateTimes() { 698 699 final long now = injectCurrentTimeMillis(); 700 701 final long prevLastResetTime = mRawLastResetTime; 702 703 if (mRawLastResetTime == 0) { // first launch. 704 // TODO Randomize?? 705 mRawLastResetTime = now; 706 } else if (now < mRawLastResetTime) { 707 // Clock rewound. 708 if (isClockValid(now)) { 709 // TODO Randomize?? 710 mRawLastResetTime = now; 711 } 712 } else { 713 // TODO Do it properly. 714 while ((mRawLastResetTime + mResetInterval) <= now) { 715 mRawLastResetTime += mResetInterval; 716 } 717 } 718 if (prevLastResetTime != mRawLastResetTime) { 719 scheduleSaveBaseState(); 720 } 721 } 722 723 /** Return the per-user state. */ 724 @GuardedBy("mLock") 725 @NonNull 726 private UserShortcuts getUserShortcutsLocked(@UserIdInt int userId) { 727 UserShortcuts userPackages = mUsers.get(userId); 728 if (userPackages == null) { 729 userPackages = loadUserLocked(userId); 730 if (userPackages == null) { 731 userPackages = new UserShortcuts(userId); 732 } 733 mUsers.put(userId, userPackages); 734 } 735 return userPackages; 736 } 737 738 /** Return the per-user per-package state. */ 739 @GuardedBy("mLock") 740 @NonNull 741 private PackageShortcuts getPackageShortcutsLocked( 742 @NonNull String packageName, @UserIdInt int userId) { 743 final UserShortcuts userPackages = getUserShortcutsLocked(userId); 744 PackageShortcuts shortcuts = userPackages.getPackages().get(packageName); 745 if (shortcuts == null) { 746 shortcuts = new PackageShortcuts(userId, packageName); 747 userPackages.getPackages().put(packageName, shortcuts); 748 } 749 return shortcuts; 750 } 751 752 // === Caller validation === 753 754 void removeIcon(@UserIdInt int userId, ShortcutInfo shortcut) { 755 if (shortcut.getBitmapPath() != null) { 756 if (DEBUG) { 757 Slog.d(TAG, "Removing " + shortcut.getBitmapPath()); 758 } 759 new File(shortcut.getBitmapPath()).delete(); 760 761 shortcut.setBitmapPath(null); 762 shortcut.setIconResourceId(0); 763 shortcut.clearFlags(ShortcutInfo.FLAG_HAS_ICON_FILE | ShortcutInfo.FLAG_HAS_ICON_RES); 764 } 765 } 766 767 @VisibleForTesting 768 static class FileOutputStreamWithPath extends FileOutputStream { 769 private final File mFile; 770 771 public FileOutputStreamWithPath(File file) throws FileNotFoundException { 772 super(file); 773 mFile = file; 774 } 775 776 public File getFile() { 777 return mFile; 778 } 779 } 780 781 /** 782 * Build the cached bitmap filename for a shortcut icon. 783 * 784 * The filename will be based on the ID, except certain characters will be escaped. 785 */ 786 @VisibleForTesting 787 FileOutputStreamWithPath openIconFileForWrite(@UserIdInt int userId, ShortcutInfo shortcut) 788 throws IOException { 789 final File packagePath = new File(getUserBitmapFilePath(userId), 790 shortcut.getPackageName()); 791 if (!packagePath.isDirectory()) { 792 packagePath.mkdirs(); 793 if (!packagePath.isDirectory()) { 794 throw new IOException("Unable to create directory " + packagePath); 795 } 796 SELinux.restorecon(packagePath); 797 } 798 799 final String baseName = String.valueOf(injectCurrentTimeMillis()); 800 for (int suffix = 0;; suffix++) { 801 final String filename = (suffix == 0 ? baseName : baseName + "_" + suffix) + ".png"; 802 final File file = new File(packagePath, filename); 803 if (!file.exists()) { 804 if (DEBUG) { 805 Slog.d(TAG, "Saving icon to " + file.getAbsolutePath()); 806 } 807 return new FileOutputStreamWithPath(file); 808 } 809 } 810 } 811 812 void saveIconAndFixUpShortcut(@UserIdInt int userId, ShortcutInfo shortcut) { 813 if (shortcut.hasIconFile() || shortcut.hasIconResource()) { 814 return; 815 } 816 817 final long token = injectClearCallingIdentity(); 818 try { 819 // Clear icon info on the shortcut. 820 shortcut.setIconResourceId(0); 821 shortcut.setBitmapPath(null); 822 823 final Icon icon = shortcut.getIcon(); 824 if (icon == null) { 825 return; // has no icon 826 } 827 828 Bitmap bitmap = null; 829 try { 830 switch (icon.getType()) { 831 case Icon.TYPE_RESOURCE: { 832 injectValidateIconResPackage(shortcut, icon); 833 834 shortcut.setIconResourceId(icon.getResId()); 835 shortcut.addFlags(ShortcutInfo.FLAG_HAS_ICON_RES); 836 return; 837 } 838 case Icon.TYPE_BITMAP: { 839 bitmap = icon.getBitmap(); 840 break; 841 } 842 case Icon.TYPE_URI: { 843 final Uri uri = ContentProvider.maybeAddUserId(icon.getUri(), userId); 844 845 try (InputStream is = mContext.getContentResolver().openInputStream(uri)) { 846 847 bitmap = BitmapFactory.decodeStream(is); 848 849 } catch (IOException e) { 850 Slog.e(TAG, "Unable to load icon from " + uri); 851 return; 852 } 853 break; 854 } 855 default: 856 // This shouldn't happen because we've already validated the icon, but 857 // just in case. 858 throw ShortcutInfo.getInvalidIconException(); 859 } 860 if (bitmap == null) { 861 Slog.e(TAG, "Null bitmap detected"); 862 return; 863 } 864 // Shrink and write to the file. 865 File path = null; 866 try { 867 final FileOutputStreamWithPath out = openIconFileForWrite(userId, shortcut); 868 try { 869 path = out.getFile(); 870 871 shrinkBitmap(bitmap, mMaxIconDimension) 872 .compress(mIconPersistFormat, mIconPersistQuality, out); 873 874 shortcut.setBitmapPath(out.getFile().getAbsolutePath()); 875 shortcut.addFlags(ShortcutInfo.FLAG_HAS_ICON_FILE); 876 } finally { 877 IoUtils.closeQuietly(out); 878 } 879 } catch (IOException|RuntimeException e) { 880 // STOPSHIP Change wtf to e 881 Slog.wtf(ShortcutService.TAG, "Unable to write bitmap to file", e); 882 if (path != null && path.exists()) { 883 path.delete(); 884 } 885 } 886 } finally { 887 if (bitmap != null) { 888 bitmap.recycle(); 889 } 890 // Once saved, we won't use the original icon information, so null it out. 891 shortcut.clearIcon(); 892 } 893 } finally { 894 injectRestoreCallingIdentity(token); 895 } 896 } 897 898 // Unfortunately we can't do this check in unit tests because we fake creator package names, 899 // so override in unit tests. 900 // TODO CTS this case. 901 void injectValidateIconResPackage(ShortcutInfo shortcut, Icon icon) { 902 if (!shortcut.getPackageName().equals(icon.getResPackage())) { 903 throw new IllegalArgumentException( 904 "Icon resource must reside in shortcut owner package"); 905 } 906 } 907 908 @VisibleForTesting 909 static Bitmap shrinkBitmap(Bitmap in, int maxSize) { 910 // Original width/height. 911 final int ow = in.getWidth(); 912 final int oh = in.getHeight(); 913 if ((ow <= maxSize) && (oh <= maxSize)) { 914 if (DEBUG) { 915 Slog.d(TAG, String.format("Icon size %dx%d, no need to shrink", ow, oh)); 916 } 917 return in; 918 } 919 final int longerDimension = Math.max(ow, oh); 920 921 // New width and height. 922 final int nw = ow * maxSize / longerDimension; 923 final int nh = oh * maxSize / longerDimension; 924 if (DEBUG) { 925 Slog.d(TAG, String.format("Icon size %dx%d, shrinking to %dx%d", 926 ow, oh, nw, nh)); 927 } 928 929 final Bitmap scaledBitmap = Bitmap.createBitmap(nw, nh, Bitmap.Config.ARGB_8888); 930 final Canvas c = new Canvas(scaledBitmap); 931 932 final RectF dst = new RectF(0, 0, nw, nh); 933 934 c.drawBitmap(in, /*src=*/ null, dst, /* paint =*/ null); 935 936 in.recycle(); 937 938 return scaledBitmap; 939 } 940 941 // === Caller validation === 942 943 private boolean isCallerSystem() { 944 final int callingUid = injectBinderCallingUid(); 945 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID); 946 } 947 948 private boolean isCallerShell() { 949 final int callingUid = injectBinderCallingUid(); 950 return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID; 951 } 952 953 private void enforceSystemOrShell() { 954 Preconditions.checkState(isCallerSystem() || isCallerShell(), 955 "Caller must be system or shell"); 956 } 957 958 private void enforceShell() { 959 Preconditions.checkState(isCallerShell(), "Caller must be shell"); 960 } 961 962 private void verifyCaller(@NonNull String packageName, @UserIdInt int userId) { 963 Preconditions.checkStringNotEmpty(packageName, "packageName"); 964 965 if (isCallerSystem()) { 966 return; // no check 967 } 968 969 final int callingUid = injectBinderCallingUid(); 970 971 // Otherwise, make sure the arguments are valid. 972 if (UserHandle.getUserId(callingUid) != userId) { 973 throw new SecurityException("Invalid user-ID"); 974 } 975 if (injectGetPackageUid(packageName, userId) == injectBinderCallingUid()) { 976 return; // Caller is valid. 977 } 978 throw new SecurityException("Caller UID= doesn't own " + packageName); 979 } 980 981 // Test overrides it. 982 int injectGetPackageUid(@NonNull String packageName, @UserIdInt int userId) { 983 try { 984 return mContext.getPackageManager().getPackageUidAsUser(packageName, 985 PackageManager.MATCH_DIRECT_BOOT_AWARE 986 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE 987 | PackageManager.MATCH_UNINSTALLED_PACKAGES, 988 userId); 989 } catch (NameNotFoundException e) { 990 return -1; 991 } 992 } 993 994 void postToHandler(Runnable r) { 995 mHandler.post(r); 996 } 997 998 /** 999 * Throw if {@code numShortcuts} is bigger than {@link #mMaxDynamicShortcuts}. 1000 */ 1001 void enforceMaxDynamicShortcuts(int numShortcuts) { 1002 if (numShortcuts > mMaxDynamicShortcuts) { 1003 throw new IllegalArgumentException("Max number of dynamic shortcuts exceeded"); 1004 } 1005 } 1006 1007 /** 1008 * - Sends a notification to LauncherApps 1009 * - Write to file 1010 */ 1011 private void userPackageChanged(@NonNull String packageName, @UserIdInt int userId) { 1012 notifyListeners(packageName, userId); 1013 scheduleSaveUser(userId); 1014 } 1015 1016 private void notifyListeners(@NonNull String packageName, @UserIdInt int userId) { 1017 postToHandler(() -> { 1018 final ArrayList<ShortcutChangeListener> copy; 1019 synchronized (mLock) { 1020 copy = new ArrayList<>(mListeners); 1021 } 1022 // Note onShortcutChanged() needs to be called with the system service permissions. 1023 for (int i = copy.size() - 1; i >= 0; i--) { 1024 copy.get(i).onShortcutChanged(packageName, userId); 1025 } 1026 }); 1027 } 1028 1029 /** 1030 * Clean up / validate an incoming shortcut. 1031 * - Make sure all mandatory fields are set. 1032 * - Make sure the intent's extras are persistable, and them to set 1033 * {@link ShortcutInfo#mIntentPersistableExtras}. Also clear its extras. 1034 * - Clear flags. 1035 * 1036 * TODO Detailed unit tests 1037 */ 1038 private void fixUpIncomingShortcutInfo(@NonNull ShortcutInfo shortcut, boolean forUpdate) { 1039 Preconditions.checkNotNull(shortcut, "Null shortcut detected"); 1040 if (shortcut.getActivityComponent() != null) { 1041 Preconditions.checkState( 1042 shortcut.getPackageName().equals( 1043 shortcut.getActivityComponent().getPackageName()), 1044 "Activity package name mismatch"); 1045 } 1046 1047 if (!forUpdate) { 1048 shortcut.enforceMandatoryFields(); 1049 } 1050 if (shortcut.getIcon() != null) { 1051 ShortcutInfo.validateIcon(shortcut.getIcon()); 1052 } 1053 1054 validateForXml(shortcut.getId()); 1055 validateForXml(shortcut.getTitle()); 1056 validatePersistableBundleForXml(shortcut.getIntentPersistableExtras()); 1057 validatePersistableBundleForXml(shortcut.getExtras()); 1058 1059 shortcut.setFlags(0); 1060 } 1061 1062 // KXmlSerializer is strict and doesn't allow certain characters, so we disallow those 1063 // characters. 1064 1065 private static void validatePersistableBundleForXml(PersistableBundle b) { 1066 if (b == null || b.size() == 0) { 1067 return; 1068 } 1069 for (String key : b.keySet()) { 1070 validateForXml(key); 1071 final Object value = b.get(key); 1072 if (value == null) { 1073 continue; 1074 } else if (value instanceof String) { 1075 validateForXml((String) value); 1076 } else if (value instanceof String[]) { 1077 for (String v : (String[]) value) { 1078 validateForXml(v); 1079 } 1080 } else if (value instanceof PersistableBundle) { 1081 validatePersistableBundleForXml((PersistableBundle) value); 1082 } 1083 } 1084 } 1085 1086 private static void validateForXml(String s) { 1087 if (TextUtils.isEmpty(s)) { 1088 return; 1089 } 1090 for (int i = s.length() - 1; i >= 0; i--) { 1091 if (!isAllowedInXml(s.charAt(i))) { 1092 throw new IllegalArgumentException("Unsupported character detected in: " + s); 1093 } 1094 } 1095 } 1096 1097 private static boolean isAllowedInXml(char c) { 1098 return (c >= 0x20 && c <= 0xd7ff) || (c >= 0xe000 && c <= 0xfffd); 1099 } 1100 1101 // === APIs === 1102 1103 @Override 1104 public boolean setDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList, 1105 @UserIdInt int userId) { 1106 verifyCaller(packageName, userId); 1107 1108 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList(); 1109 final int size = newShortcuts.size(); 1110 1111 synchronized (mLock) { 1112 final PackageShortcuts ps = getPackageShortcutsLocked(packageName, userId); 1113 1114 // Throttling. 1115 if (!ps.tryApiCall(this)) { 1116 return false; 1117 } 1118 enforceMaxDynamicShortcuts(size); 1119 1120 // Validate the shortcuts. 1121 for (int i = 0; i < size; i++) { 1122 fixUpIncomingShortcutInfo(newShortcuts.get(i), /* forUpdate= */ false); 1123 } 1124 1125 // First, remove all un-pinned; dynamic shortcuts 1126 ps.deleteAllDynamicShortcuts(this); 1127 1128 // Then, add/update all. We need to make sure to take over "pinned" flag. 1129 for (int i = 0; i < size; i++) { 1130 final ShortcutInfo newShortcut = newShortcuts.get(i); 1131 newShortcut.addFlags(ShortcutInfo.FLAG_DYNAMIC); 1132 ps.updateShortcutWithCapping(this, newShortcut); 1133 } 1134 } 1135 userPackageChanged(packageName, userId); 1136 return true; 1137 } 1138 1139 @Override 1140 public boolean updateShortcuts(String packageName, ParceledListSlice shortcutInfoList, 1141 @UserIdInt int userId) { 1142 verifyCaller(packageName, userId); 1143 1144 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList(); 1145 final int size = newShortcuts.size(); 1146 1147 synchronized (mLock) { 1148 final PackageShortcuts ps = getPackageShortcutsLocked(packageName, userId); 1149 1150 // Throttling. 1151 if (!ps.tryApiCall(this)) { 1152 return false; 1153 } 1154 1155 for (int i = 0; i < size; i++) { 1156 final ShortcutInfo source = newShortcuts.get(i); 1157 fixUpIncomingShortcutInfo(source, /* forUpdate= */ true); 1158 1159 final ShortcutInfo target = ps.findShortcutById(source.getId()); 1160 if (target != null) { 1161 final boolean replacingIcon = (source.getIcon() != null); 1162 if (replacingIcon) { 1163 removeIcon(userId, target); 1164 } 1165 1166 target.copyNonNullFieldsFrom(source); 1167 1168 if (replacingIcon) { 1169 saveIconAndFixUpShortcut(userId, target); 1170 } 1171 } 1172 } 1173 } 1174 userPackageChanged(packageName, userId); 1175 1176 return true; 1177 } 1178 1179 @Override 1180 public boolean addDynamicShortcut(String packageName, ShortcutInfo newShortcut, 1181 @UserIdInt int userId) { 1182 verifyCaller(packageName, userId); 1183 1184 synchronized (mLock) { 1185 final PackageShortcuts ps = getPackageShortcutsLocked(packageName, userId); 1186 1187 // Throttling. 1188 if (!ps.tryApiCall(this)) { 1189 return false; 1190 } 1191 1192 // Validate the shortcut. 1193 fixUpIncomingShortcutInfo(newShortcut, /* forUpdate= */ false); 1194 1195 // Add it. 1196 newShortcut.addFlags(ShortcutInfo.FLAG_DYNAMIC); 1197 ps.updateShortcutWithCapping(this, newShortcut); 1198 } 1199 userPackageChanged(packageName, userId); 1200 1201 return true; 1202 } 1203 1204 @Override 1205 public void deleteDynamicShortcut(String packageName, String shortcutId, 1206 @UserIdInt int userId) { 1207 verifyCaller(packageName, userId); 1208 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId must be provided"); 1209 1210 synchronized (mLock) { 1211 getPackageShortcutsLocked(packageName, userId).deleteDynamicWithId(this, shortcutId); 1212 } 1213 userPackageChanged(packageName, userId); 1214 } 1215 1216 @Override 1217 public void deleteAllDynamicShortcuts(String packageName, @UserIdInt int userId) { 1218 verifyCaller(packageName, userId); 1219 1220 synchronized (mLock) { 1221 getPackageShortcutsLocked(packageName, userId).deleteAllDynamicShortcuts(this); 1222 } 1223 userPackageChanged(packageName, userId); 1224 } 1225 1226 @Override 1227 public ParceledListSlice<ShortcutInfo> getDynamicShortcuts(String packageName, 1228 @UserIdInt int userId) { 1229 verifyCaller(packageName, userId); 1230 synchronized (mLock) { 1231 return getShortcutsWithQueryLocked( 1232 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR, 1233 ShortcutInfo::isDynamic); 1234 } 1235 } 1236 1237 @Override 1238 public ParceledListSlice<ShortcutInfo> getPinnedShortcuts(String packageName, 1239 @UserIdInt int userId) { 1240 verifyCaller(packageName, userId); 1241 synchronized (mLock) { 1242 return getShortcutsWithQueryLocked( 1243 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR, 1244 ShortcutInfo::isPinned); 1245 } 1246 } 1247 1248 private ParceledListSlice<ShortcutInfo> getShortcutsWithQueryLocked(@NonNull String packageName, 1249 @UserIdInt int userId, int cloneFlags, @NonNull Predicate<ShortcutInfo> query) { 1250 1251 final ArrayList<ShortcutInfo> ret = new ArrayList<>(); 1252 1253 getPackageShortcutsLocked(packageName, userId).findAll(ret, query, cloneFlags); 1254 1255 return new ParceledListSlice<>(ret); 1256 } 1257 1258 @Override 1259 public int getMaxDynamicShortcutCount(String packageName, @UserIdInt int userId) 1260 throws RemoteException { 1261 verifyCaller(packageName, userId); 1262 1263 return mMaxDynamicShortcuts; 1264 } 1265 1266 @Override 1267 public int getRemainingCallCount(String packageName, @UserIdInt int userId) { 1268 verifyCaller(packageName, userId); 1269 1270 synchronized (mLock) { 1271 return mMaxDailyUpdates 1272 - getPackageShortcutsLocked(packageName, userId).getApiCallCount(this); 1273 } 1274 } 1275 1276 @Override 1277 public long getRateLimitResetTime(String packageName, @UserIdInt int userId) { 1278 verifyCaller(packageName, userId); 1279 1280 synchronized (mLock) { 1281 return getNextResetTimeLocked(); 1282 } 1283 } 1284 1285 @Override 1286 public int getIconMaxDimensions(String packageName, int userId) throws RemoteException { 1287 synchronized (mLock) { 1288 return mMaxIconDimension; 1289 } 1290 } 1291 1292 /** 1293 * Reset all throttling, for developer options and command line. Only system/shell can call it. 1294 */ 1295 @Override 1296 public void resetThrottling() { 1297 enforceSystemOrShell(); 1298 1299 resetThrottlingInner(getCallingUserId()); 1300 } 1301 1302 void resetThrottlingInner(@UserIdInt int userId) { 1303 synchronized (mLock) { 1304 getUserShortcutsLocked(userId).resetThrottling(); 1305 } 1306 scheduleSaveUser(userId); 1307 Slog.i(TAG, "ShortcutManager: throttling counter reset"); 1308 } 1309 1310 // We override this method in unit tests to do a simpler check. 1311 boolean hasShortcutHostPermission(@NonNull String callingPackage, int userId) { 1312 return hasShortcutHostPermissionInner(callingPackage, userId); 1313 } 1314 1315 // This method is extracted so we can directly call this method from unit tests, 1316 // even when hasShortcutPermission() is overridden. 1317 @VisibleForTesting 1318 boolean hasShortcutHostPermissionInner(@NonNull String callingPackage, int userId) { 1319 synchronized (mLock) { 1320 long start = 0; 1321 if (DEBUG) { 1322 start = System.currentTimeMillis(); 1323 } 1324 1325 final UserShortcuts user = getUserShortcutsLocked(userId); 1326 1327 final List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 1328 1329 // Default launcher from package manager. 1330 final ComponentName defaultLauncher = injectPackageManagerInternal() 1331 .getHomeActivitiesAsUser(allHomeCandidates, userId); 1332 1333 ComponentName detected; 1334 if (defaultLauncher != null) { 1335 detected = defaultLauncher; 1336 if (DEBUG) { 1337 Slog.v(TAG, "Default launcher from PM: " + detected); 1338 } 1339 } else { 1340 detected = user.getLauncherComponent(); 1341 1342 // TODO: Make sure it's still enabled. 1343 if (DEBUG) { 1344 Slog.v(TAG, "Cached launcher: " + detected); 1345 } 1346 } 1347 1348 if (detected == null) { 1349 // If we reach here, that means it's the first check since the user was created, 1350 // and there's already multiple launchers and there's no default set. 1351 // Find the system one with the highest priority. 1352 // (We need to check the priority too because of FallbackHome in Settings.) 1353 // If there's no system launcher yet, then no one can access shortcuts, until 1354 // the user explicitly 1355 final int size = allHomeCandidates.size(); 1356 1357 int lastPriority = Integer.MIN_VALUE; 1358 for (int i = 0; i < size; i++) { 1359 final ResolveInfo ri = allHomeCandidates.get(i); 1360 if (!ri.activityInfo.applicationInfo.isSystemApp()) { 1361 continue; 1362 } 1363 if (DEBUG) { 1364 Slog.d(TAG, String.format("hasShortcutPermissionInner: pkg=%s prio=%d", 1365 ri.activityInfo.getComponentName(), ri.priority)); 1366 } 1367 if (ri.priority < lastPriority) { 1368 continue; 1369 } 1370 detected = ri.activityInfo.getComponentName(); 1371 lastPriority = ri.priority; 1372 } 1373 } 1374 if (DEBUG) { 1375 long end = System.currentTimeMillis(); 1376 Slog.v(TAG, String.format("hasShortcutPermission took %d ms", end - start)); 1377 } 1378 if (detected != null) { 1379 if (DEBUG) { 1380 Slog.v(TAG, "Detected launcher: " + detected); 1381 } 1382 user.setLauncherComponent(this, detected); 1383 return detected.getPackageName().equals(callingPackage); 1384 } else { 1385 // Default launcher not found. 1386 return false; 1387 } 1388 } 1389 } 1390 1391 /** 1392 * Entry point from {@link LauncherApps}. 1393 */ 1394 private class LocalService extends ShortcutServiceInternal { 1395 @Override 1396 public List<ShortcutInfo> getShortcuts( 1397 @NonNull String callingPackage, long changedSince, 1398 @Nullable String packageName, @Nullable ComponentName componentName, 1399 int queryFlags, int userId) { 1400 final ArrayList<ShortcutInfo> ret = new ArrayList<>(); 1401 final int cloneFlag = 1402 ((queryFlags & ShortcutQuery.FLAG_GET_KEY_FIELDS_ONLY) == 0) 1403 ? ShortcutInfo.CLONE_REMOVE_FOR_LAUNCHER 1404 : ShortcutInfo.CLONE_REMOVE_NON_KEY_INFO; 1405 1406 synchronized (mLock) { 1407 if (packageName != null) { 1408 getShortcutsInnerLocked(packageName, changedSince, componentName, queryFlags, 1409 userId, ret, cloneFlag); 1410 } else { 1411 final ArrayMap<String, PackageShortcuts> packages = 1412 getUserShortcutsLocked(userId).getPackages(); 1413 for (int i = packages.size() - 1; i >= 0; i--) { 1414 getShortcutsInnerLocked( 1415 packages.keyAt(i), 1416 changedSince, componentName, queryFlags, userId, ret, cloneFlag); 1417 } 1418 } 1419 } 1420 return ret; 1421 } 1422 1423 private void getShortcutsInnerLocked(@Nullable String packageName,long changedSince, 1424 @Nullable ComponentName componentName, int queryFlags, 1425 int userId, ArrayList<ShortcutInfo> ret, int cloneFlag) { 1426 getPackageShortcutsLocked(packageName, userId).findAll(ret, 1427 (ShortcutInfo si) -> { 1428 if (si.getLastChangedTimestamp() < changedSince) { 1429 return false; 1430 } 1431 if (componentName != null 1432 && !componentName.equals(si.getActivityComponent())) { 1433 return false; 1434 } 1435 final boolean matchDynamic = 1436 ((queryFlags & ShortcutQuery.FLAG_GET_DYNAMIC) != 0) 1437 && si.isDynamic(); 1438 final boolean matchPinned = 1439 ((queryFlags & ShortcutQuery.FLAG_GET_PINNED) != 0) 1440 && si.isPinned(); 1441 return matchDynamic || matchPinned; 1442 }, cloneFlag); 1443 } 1444 1445 @Override 1446 public List<ShortcutInfo> getShortcutInfo( 1447 @NonNull String callingPackage, 1448 @NonNull String packageName, @Nullable List<String> ids, int userId) { 1449 // Calling permission must be checked by LauncherAppsImpl. 1450 Preconditions.checkStringNotEmpty(packageName, "packageName"); 1451 1452 final ArrayList<ShortcutInfo> ret = new ArrayList<>(ids.size()); 1453 final ArraySet<String> idSet = new ArraySet<>(ids); 1454 synchronized (mLock) { 1455 getPackageShortcutsLocked(packageName, userId).findAll(ret, 1456 (ShortcutInfo si) -> idSet.contains(si.getId()), 1457 ShortcutInfo.CLONE_REMOVE_FOR_LAUNCHER); 1458 } 1459 return ret; 1460 } 1461 1462 @Override 1463 public void pinShortcuts(@NonNull String callingPackage, @NonNull String packageName, 1464 @NonNull List<String> shortcutIds, int userId) { 1465 // Calling permission must be checked by LauncherAppsImpl. 1466 Preconditions.checkStringNotEmpty(packageName, "packageName"); 1467 Preconditions.checkNotNull(shortcutIds, "shortcutIds"); 1468 1469 synchronized (mLock) { 1470 getPackageShortcutsLocked(packageName, userId).replacePinned( 1471 ShortcutService.this, callingPackage, shortcutIds); 1472 } 1473 userPackageChanged(packageName, userId); 1474 } 1475 1476 @Override 1477 public Intent createShortcutIntent(@NonNull String callingPackage, 1478 @NonNull String packageName, @NonNull String shortcutId, int userId) { 1479 // Calling permission must be checked by LauncherAppsImpl. 1480 Preconditions.checkStringNotEmpty(packageName, "packageName can't be empty"); 1481 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId can't be empty"); 1482 1483 synchronized (mLock) { 1484 final ShortcutInfo fullShortcut = 1485 getPackageShortcutsLocked(packageName, userId) 1486 .findShortcutById(shortcutId); 1487 return fullShortcut == null ? null : fullShortcut.getIntent(); 1488 } 1489 } 1490 1491 @Override 1492 public void addListener(@NonNull ShortcutChangeListener listener) { 1493 synchronized (mLock) { 1494 mListeners.add(Preconditions.checkNotNull(listener)); 1495 } 1496 } 1497 1498 @Override 1499 public int getShortcutIconResId(@NonNull String callingPackage, 1500 @NonNull ShortcutInfo shortcut, int userId) { 1501 Preconditions.checkNotNull(shortcut, "shortcut"); 1502 1503 synchronized (mLock) { 1504 final ShortcutInfo shortcutInfo = getPackageShortcutsLocked( 1505 shortcut.getPackageName(), userId).findShortcutById(shortcut.getId()); 1506 return (shortcutInfo != null && shortcutInfo.hasIconResource()) 1507 ? shortcutInfo.getIconResourceId() : 0; 1508 } 1509 } 1510 1511 @Override 1512 public ParcelFileDescriptor getShortcutIconFd(@NonNull String callingPackage, 1513 @NonNull ShortcutInfo shortcutIn, int userId) { 1514 Preconditions.checkNotNull(shortcutIn, "shortcut"); 1515 1516 synchronized (mLock) { 1517 final ShortcutInfo shortcutInfo = getPackageShortcutsLocked( 1518 shortcutIn.getPackageName(), userId).findShortcutById(shortcutIn.getId()); 1519 if (shortcutInfo == null || !shortcutInfo.hasIconFile()) { 1520 return null; 1521 } 1522 try { 1523 if (shortcutInfo.getBitmapPath() == null) { 1524 Slog.w(TAG, "null bitmap detected in getShortcutIconFd()"); 1525 return null; 1526 } 1527 return ParcelFileDescriptor.open( 1528 new File(shortcutInfo.getBitmapPath()), 1529 ParcelFileDescriptor.MODE_READ_ONLY); 1530 } catch (FileNotFoundException e) { 1531 Slog.e(TAG, "Icon file not found: " + shortcutInfo.getBitmapPath()); 1532 return null; 1533 } 1534 } 1535 } 1536 1537 @Override 1538 public boolean hasShortcutHostPermission(@NonNull String callingPackage, int userId) { 1539 return ShortcutService.this.hasShortcutHostPermission(callingPackage, userId); 1540 } 1541 } 1542 1543 // === Dump === 1544 1545 @Override 1546 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 1547 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 1548 != PackageManager.PERMISSION_GRANTED) { 1549 pw.println("Permission Denial: can't dump UserManager from from pid=" 1550 + Binder.getCallingPid() 1551 + ", uid=" + Binder.getCallingUid() 1552 + " without permission " 1553 + android.Manifest.permission.DUMP); 1554 return; 1555 } 1556 dumpInner(pw); 1557 } 1558 1559 @VisibleForTesting 1560 void dumpInner(PrintWriter pw) { 1561 synchronized (mLock) { 1562 final long now = injectCurrentTimeMillis(); 1563 pw.print("Now: ["); 1564 pw.print(now); 1565 pw.print("] "); 1566 pw.print(formatTime(now)); 1567 1568 pw.print(" Raw last reset: ["); 1569 pw.print(mRawLastResetTime); 1570 pw.print("] "); 1571 pw.print(formatTime(mRawLastResetTime)); 1572 1573 final long last = getLastResetTimeLocked(); 1574 pw.print(" Last reset: ["); 1575 pw.print(last); 1576 pw.print("] "); 1577 pw.print(formatTime(last)); 1578 1579 final long next = getNextResetTimeLocked(); 1580 pw.print(" Next reset: ["); 1581 pw.print(next); 1582 pw.print("] "); 1583 pw.print(formatTime(next)); 1584 pw.println(); 1585 1586 pw.print(" Max icon dim: "); 1587 pw.print(mMaxIconDimension); 1588 pw.print(" Icon format: "); 1589 pw.print(mIconPersistFormat); 1590 pw.print(" Icon quality: "); 1591 pw.print(mIconPersistQuality); 1592 pw.println(); 1593 1594 1595 for (int i = 0; i < mUsers.size(); i++) { 1596 pw.println(); 1597 mUsers.valueAt(i).dump(this, pw, " "); 1598 } 1599 } 1600 } 1601 1602 static String formatTime(long time) { 1603 Time tobj = new Time(); 1604 tobj.set(time); 1605 return tobj.format("%Y-%m-%d %H:%M:%S"); 1606 } 1607 1608 // === Shell support === 1609 1610 @Override 1611 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err, 1612 String[] args, ResultReceiver resultReceiver) throws RemoteException { 1613 1614 enforceShell(); 1615 1616 (new MyShellCommand()).exec(this, in, out, err, args, resultReceiver); 1617 } 1618 1619 static class CommandException extends Exception { 1620 public CommandException(String message) { 1621 super(message); 1622 } 1623 } 1624 1625 /** 1626 * Handle "adb shell cmd". 1627 */ 1628 private class MyShellCommand extends ShellCommand { 1629 1630 private int mUserId = UserHandle.USER_SYSTEM; 1631 1632 private void parseOptions(boolean takeUser) 1633 throws CommandException { 1634 String opt; 1635 while ((opt = getNextOption()) != null) { 1636 switch (opt) { 1637 case "--user": 1638 if (takeUser) { 1639 mUserId = UserHandle.parseUserArg(getNextArgRequired()); 1640 break; 1641 } 1642 // fallthrough 1643 default: 1644 throw new CommandException("Unknown option: " + opt); 1645 } 1646 } 1647 } 1648 1649 @Override 1650 public int onCommand(String cmd) { 1651 if (cmd == null) { 1652 return handleDefaultCommands(cmd); 1653 } 1654 final PrintWriter pw = getOutPrintWriter(); 1655 try { 1656 switch (cmd) { 1657 case "reset-package-throttling": 1658 handleResetPackageThrottling(); 1659 break; 1660 case "reset-throttling": 1661 handleResetThrottling(); 1662 break; 1663 case "override-config": 1664 handleOverrideConfig(); 1665 break; 1666 case "reset-config": 1667 handleResetConfig(); 1668 break; 1669 case "clear-default-launcher": 1670 handleClearDefaultLauncher(); 1671 break; 1672 case "get-default-launcher": 1673 handleGetDefaultLauncher(); 1674 break; 1675 case "refresh-default-launcher": 1676 handleRefreshDefaultLauncher(); 1677 break; 1678 default: 1679 return handleDefaultCommands(cmd); 1680 } 1681 } catch (CommandException e) { 1682 pw.println("Error: " + e.getMessage()); 1683 return 1; 1684 } 1685 pw.println("Success"); 1686 return 0; 1687 } 1688 1689 @Override 1690 public void onHelp() { 1691 final PrintWriter pw = getOutPrintWriter(); 1692 pw.println("Usage: cmd shortcut COMMAND [options ...]"); 1693 pw.println(); 1694 pw.println("cmd shortcut reset-package-throttling [--user USER_ID] PACKAGE"); 1695 pw.println(" Reset throttling for a package"); 1696 pw.println(); 1697 pw.println("cmd shortcut reset-throttling"); 1698 pw.println(" Reset throttling for all packages and users"); 1699 pw.println(); 1700 pw.println("cmd shortcut override-config CONFIG"); 1701 pw.println(" Override the configuration for testing (will last until reboot)"); 1702 pw.println(); 1703 pw.println("cmd shortcut reset-config"); 1704 pw.println(" Reset the configuration set with \"update-config\""); 1705 pw.println(); 1706 pw.println("cmd shortcut clear-default-launcher [--user USER_ID]"); 1707 pw.println(" Clear the cached default launcher"); 1708 pw.println(); 1709 pw.println("cmd shortcut get-default-launcher [--user USER_ID]"); 1710 pw.println(" Show the cached default launcher"); 1711 pw.println(); 1712 pw.println("cmd shortcut refresh-default-launcher [--user USER_ID]"); 1713 pw.println(" Refresh the cached default launcher"); 1714 pw.println(); 1715 } 1716 1717 private int handleResetThrottling() throws CommandException { 1718 parseOptions(/* takeUser =*/ true); 1719 1720 resetThrottlingInner(mUserId); 1721 return 0; 1722 } 1723 1724 private void handleResetPackageThrottling() throws CommandException { 1725 parseOptions(/* takeUser =*/ true); 1726 1727 final String packageName = getNextArgRequired(); 1728 1729 synchronized (mLock) { 1730 getPackageShortcutsLocked(packageName, mUserId).resetRateLimitingForCommandLine(); 1731 saveUserLocked(mUserId); 1732 } 1733 } 1734 1735 private void handleOverrideConfig() throws CommandException { 1736 final String config = getNextArgRequired(); 1737 1738 synchronized (mLock) { 1739 if (!updateConfigurationLocked(config)) { 1740 throw new CommandException("override-config failed. See logcat for details."); 1741 } 1742 } 1743 } 1744 1745 private void handleResetConfig() { 1746 synchronized (mLock) { 1747 loadConfigurationLocked(); 1748 } 1749 } 1750 1751 private void clearLauncher() { 1752 synchronized (mLock) { 1753 getUserShortcutsLocked(mUserId).setLauncherComponent( 1754 ShortcutService.this, null); 1755 } 1756 } 1757 1758 private void showLauncher() { 1759 synchronized (mLock) { 1760 // This ensures to set the cached launcher. Package name doesn't matter. 1761 hasShortcutHostPermissionInner("-", mUserId); 1762 1763 getOutPrintWriter().println("Launcher: " 1764 + getUserShortcutsLocked(mUserId).getLauncherComponent()); 1765 } 1766 } 1767 1768 private void handleClearDefaultLauncher() throws CommandException { 1769 parseOptions(/* takeUser =*/ true); 1770 1771 clearLauncher(); 1772 } 1773 1774 private void handleGetDefaultLauncher() throws CommandException { 1775 parseOptions(/* takeUser =*/ true); 1776 1777 showLauncher(); 1778 } 1779 1780 private void handleRefreshDefaultLauncher() throws CommandException { 1781 parseOptions(/* takeUser =*/ true); 1782 1783 clearLauncher(); 1784 showLauncher(); 1785 } 1786 } 1787 1788 // === Unit test support === 1789 1790 // Injection point. 1791 long injectCurrentTimeMillis() { 1792 return System.currentTimeMillis(); 1793 } 1794 1795 // Injection point. 1796 int injectBinderCallingUid() { 1797 return getCallingUid(); 1798 } 1799 1800 final int getCallingUserId() { 1801 return UserHandle.getUserId(injectBinderCallingUid()); 1802 } 1803 1804 // Injection point. 1805 long injectClearCallingIdentity() { 1806 return Binder.clearCallingIdentity(); 1807 } 1808 1809 // Injection point. 1810 void injectRestoreCallingIdentity(long token) { 1811 Binder.restoreCallingIdentity(token); 1812 } 1813 1814 File injectSystemDataPath() { 1815 return Environment.getDataSystemDirectory(); 1816 } 1817 1818 File injectUserDataPath(@UserIdInt int userId) { 1819 return new File(Environment.getDataSystemCeDirectory(userId), DIRECTORY_PER_USER); 1820 } 1821 1822 @VisibleForTesting 1823 boolean injectIsLowRamDevice() { 1824 return ActivityManager.isLowRamDeviceStatic(); 1825 } 1826 1827 PackageManagerInternal injectPackageManagerInternal() { 1828 return mPackageManagerInternal; 1829 } 1830 1831 File getUserBitmapFilePath(@UserIdInt int userId) { 1832 return new File(injectUserDataPath(userId), DIRECTORY_BITMAPS); 1833 } 1834 1835 @VisibleForTesting 1836 SparseArray<UserShortcuts> getShortcutsForTest() { 1837 return mUsers; 1838 } 1839 1840 @VisibleForTesting 1841 int getMaxDynamicShortcutsForTest() { 1842 return mMaxDynamicShortcuts; 1843 } 1844 1845 @VisibleForTesting 1846 int getMaxDailyUpdatesForTest() { 1847 return mMaxDailyUpdates; 1848 } 1849 1850 @VisibleForTesting 1851 long getResetIntervalForTest() { 1852 return mResetInterval; 1853 } 1854 1855 @VisibleForTesting 1856 int getMaxIconDimensionForTest() { 1857 return mMaxIconDimension; 1858 } 1859 1860 @VisibleForTesting 1861 CompressFormat getIconPersistFormatForTest() { 1862 return mIconPersistFormat; 1863 } 1864 1865 @VisibleForTesting 1866 int getIconPersistQualityForTest() { 1867 return mIconPersistQuality; 1868 } 1869 1870 @VisibleForTesting 1871 ShortcutInfo getPackageShortcutForTest(String packageName, String shortcutId, int userId) { 1872 synchronized (mLock) { 1873 return getPackageShortcutsLocked(packageName, userId).findShortcutById(shortcutId); 1874 } 1875 } 1876} 1877 1878/** 1879 * Per-user information. 1880 */ 1881class UserShortcuts { 1882 private static final String TAG = ShortcutService.TAG; 1883 1884 @UserIdInt 1885 final int mUserId; 1886 1887 private final ArrayMap<String, PackageShortcuts> mPackages = new ArrayMap<>(); 1888 1889 private ComponentName mLauncherComponent; 1890 1891 public UserShortcuts(int userId) { 1892 mUserId = userId; 1893 } 1894 1895 public ArrayMap<String, PackageShortcuts> getPackages() { 1896 return mPackages; 1897 } 1898 1899 public void saveToXml(XmlSerializer out) throws IOException, XmlPullParserException { 1900 out.startTag(null, ShortcutService.TAG_USER); 1901 1902 ShortcutService.writeTagValue(out, ShortcutService.TAG_LAUNCHER, 1903 mLauncherComponent); 1904 1905 for (int i = 0; i < mPackages.size(); i++) { 1906 mPackages.valueAt(i).saveToXml(out); 1907 } 1908 1909 out.endTag(null, ShortcutService.TAG_USER); 1910 } 1911 1912 public static UserShortcuts loadFromXml(XmlPullParser parser, int userId) 1913 throws IOException, XmlPullParserException { 1914 final UserShortcuts ret = new UserShortcuts(userId); 1915 1916 final int outerDepth = parser.getDepth(); 1917 int type; 1918 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 1919 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 1920 if (type != XmlPullParser.START_TAG) { 1921 continue; 1922 } 1923 final int depth = parser.getDepth(); 1924 final String tag = parser.getName(); 1925 switch (tag) { 1926 case ShortcutService.TAG_LAUNCHER: 1927 ret.mLauncherComponent = ShortcutService.parseComponentNameAttribute( 1928 parser, ShortcutService.ATTR_VALUE); 1929 continue; 1930 case ShortcutService.TAG_PACKAGE: 1931 final PackageShortcuts shortcuts = PackageShortcuts.loadFromXml(parser, userId); 1932 1933 // Don't use addShortcut(), we don't need to save the icon. 1934 ret.getPackages().put(shortcuts.mPackageName, shortcuts); 1935 continue; 1936 } 1937 throw ShortcutService.throwForInvalidTag(depth, tag); 1938 } 1939 return ret; 1940 } 1941 1942 public ComponentName getLauncherComponent() { 1943 return mLauncherComponent; 1944 } 1945 1946 public void setLauncherComponent(ShortcutService s, ComponentName launcherComponent) { 1947 if (Objects.equal(mLauncherComponent, launcherComponent)) { 1948 return; 1949 } 1950 mLauncherComponent = launcherComponent; 1951 s.scheduleSaveUser(mUserId); 1952 } 1953 1954 public void resetThrottling() { 1955 for (int i = mPackages.size() - 1; i >= 0; i--) { 1956 mPackages.valueAt(i).resetThrottling(); 1957 } 1958 } 1959 1960 public void dump(@NonNull ShortcutService s, @NonNull PrintWriter pw, @NonNull String prefix) { 1961 pw.print(prefix); 1962 pw.print("User: "); 1963 pw.print(mUserId); 1964 pw.println(); 1965 1966 pw.print(prefix); 1967 pw.print(" "); 1968 pw.print("Default launcher: "); 1969 pw.print(mLauncherComponent); 1970 pw.println(); 1971 1972 for (int i = 0; i < mPackages.size(); i++) { 1973 mPackages.valueAt(i).dump(s, pw, prefix + " "); 1974 } 1975 } 1976} 1977 1978/** 1979 * All the information relevant to shortcuts from a single package (per-user). 1980 */ 1981class PackageShortcuts { 1982 private static final String TAG = ShortcutService.TAG; 1983 1984 @UserIdInt 1985 final int mUserId; 1986 1987 @NonNull 1988 final String mPackageName; 1989 1990 /** 1991 * All the shortcuts from the package, keyed on IDs. 1992 */ 1993 final private ArrayMap<String, ShortcutInfo> mShortcuts = new ArrayMap<>(); 1994 1995 /** 1996 * # of dynamic shortcuts. 1997 */ 1998 private int mDynamicShortcutCount = 0; 1999 2000 /** 2001 * # of times the package has called rate-limited APIs. 2002 */ 2003 private int mApiCallCount; 2004 2005 /** 2006 * When {@link #mApiCallCount} was reset last time. 2007 */ 2008 private long mLastResetTime; 2009 2010 PackageShortcuts(int userId, String packageName) { 2011 mUserId = userId; 2012 mPackageName = packageName; 2013 } 2014 2015 @Nullable 2016 public ShortcutInfo findShortcutById(String id) { 2017 return mShortcuts.get(id); 2018 } 2019 2020 private ShortcutInfo deleteShortcut(@NonNull ShortcutService s, 2021 @NonNull String id) { 2022 final ShortcutInfo shortcut = mShortcuts.remove(id); 2023 if (shortcut != null) { 2024 s.removeIcon(mUserId, shortcut); 2025 shortcut.clearFlags(ShortcutInfo.FLAG_DYNAMIC | ShortcutInfo.FLAG_PINNED); 2026 } 2027 return shortcut; 2028 } 2029 2030 void addShortcut(@NonNull ShortcutService s, @NonNull ShortcutInfo newShortcut) { 2031 deleteShortcut(s, newShortcut.getId()); 2032 s.saveIconAndFixUpShortcut(mUserId, newShortcut); 2033 mShortcuts.put(newShortcut.getId(), newShortcut); 2034 } 2035 2036 /** 2037 * Add a shortcut, or update one with the same ID, with taking over existing flags. 2038 * 2039 * It checks the max number of dynamic shortcuts. 2040 */ 2041 public void updateShortcutWithCapping(@NonNull ShortcutService s, 2042 @NonNull ShortcutInfo newShortcut) { 2043 final ShortcutInfo oldShortcut = mShortcuts.get(newShortcut.getId()); 2044 2045 int oldFlags = 0; 2046 int newDynamicCount = mDynamicShortcutCount; 2047 2048 if (oldShortcut != null) { 2049 oldFlags = oldShortcut.getFlags(); 2050 if (oldShortcut.isDynamic()) { 2051 newDynamicCount--; 2052 } 2053 } 2054 if (newShortcut.isDynamic()) { 2055 newDynamicCount++; 2056 } 2057 // Make sure there's still room. 2058 s.enforceMaxDynamicShortcuts(newDynamicCount); 2059 2060 // Okay, make it dynamic and add. 2061 newShortcut.addFlags(oldFlags); 2062 2063 addShortcut(s, newShortcut); 2064 mDynamicShortcutCount = newDynamicCount; 2065 } 2066 2067 /** 2068 * Remove all shortcuts that aren't pinned nor dynamic. 2069 */ 2070 private void removeOrphans(@NonNull ShortcutService s) { 2071 ArrayList<String> removeList = null; // Lazily initialize. 2072 2073 for (int i = mShortcuts.size() - 1; i >= 0; i--) { 2074 final ShortcutInfo si = mShortcuts.valueAt(i); 2075 2076 if (si.isPinned() || si.isDynamic()) continue; 2077 2078 if (removeList == null) { 2079 removeList = new ArrayList<>(); 2080 } 2081 removeList.add(si.getId()); 2082 } 2083 if (removeList != null) { 2084 for (int i = removeList.size() - 1 ; i >= 0; i--) { 2085 deleteShortcut(s, removeList.get(i)); 2086 } 2087 } 2088 } 2089 2090 public void deleteAllDynamicShortcuts(@NonNull ShortcutService s) { 2091 for (int i = mShortcuts.size() - 1; i >= 0; i--) { 2092 mShortcuts.valueAt(i).clearFlags(ShortcutInfo.FLAG_DYNAMIC); 2093 } 2094 removeOrphans(s); 2095 mDynamicShortcutCount = 0; 2096 } 2097 2098 public void deleteDynamicWithId(@NonNull ShortcutService s, @NonNull String shortcutId) { 2099 final ShortcutInfo oldShortcut = mShortcuts.get(shortcutId); 2100 2101 if (oldShortcut == null) { 2102 return; 2103 } 2104 if (oldShortcut.isDynamic()) { 2105 mDynamicShortcutCount--; 2106 } 2107 if (oldShortcut.isPinned()) { 2108 oldShortcut.clearFlags(ShortcutInfo.FLAG_DYNAMIC); 2109 } else { 2110 deleteShortcut(s, shortcutId); 2111 } 2112 } 2113 2114 public void replacePinned(@NonNull ShortcutService s, String launcherPackage, 2115 List<String> shortcutIds) { 2116 2117 // TODO Should be per launcherPackage. 2118 2119 // First, un-pin all shortcuts 2120 for (int i = mShortcuts.size() - 1; i >= 0; i--) { 2121 mShortcuts.valueAt(i).clearFlags(ShortcutInfo.FLAG_PINNED); 2122 } 2123 2124 // Then pin ALL 2125 for (int i = shortcutIds.size() - 1; i >= 0; i--) { 2126 final ShortcutInfo shortcut = mShortcuts.get(shortcutIds.get(i)); 2127 if (shortcut != null) { 2128 shortcut.addFlags(ShortcutInfo.FLAG_PINNED); 2129 } 2130 } 2131 2132 removeOrphans(s); 2133 } 2134 2135 /** 2136 * Number of calls that the caller has made, since the last reset. 2137 */ 2138 public int getApiCallCount(@NonNull ShortcutService s) { 2139 final long last = s.getLastResetTimeLocked(); 2140 2141 final long now = s.injectCurrentTimeMillis(); 2142 if (ShortcutService.isClockValid(now) && mLastResetTime > now) { 2143 // Clock rewound. // TODO Test it 2144 mLastResetTime = now; 2145 } 2146 2147 // If not reset yet, then reset. 2148 if (mLastResetTime < last) { 2149 mApiCallCount = 0; 2150 mLastResetTime = last; 2151 } 2152 return mApiCallCount; 2153 } 2154 2155 /** 2156 * If the caller app hasn't been throttled yet, increment {@link #mApiCallCount} 2157 * and return true. Otherwise just return false. 2158 */ 2159 public boolean tryApiCall(@NonNull ShortcutService s) { 2160 if (getApiCallCount(s) >= s.mMaxDailyUpdates) { 2161 return false; 2162 } 2163 mApiCallCount++; 2164 return true; 2165 } 2166 2167 public void resetRateLimitingForCommandLine() { 2168 mApiCallCount = 0; 2169 mLastResetTime = 0; 2170 } 2171 2172 /** 2173 * Find all shortcuts that match {@code query}. 2174 */ 2175 public void findAll(@NonNull List<ShortcutInfo> result, 2176 @Nullable Predicate<ShortcutInfo> query, int cloneFlag) { 2177 for (int i = 0; i < mShortcuts.size(); i++) { 2178 final ShortcutInfo si = mShortcuts.valueAt(i); 2179 if (query == null || query.test(si)) { 2180 result.add(si.clone(cloneFlag)); 2181 } 2182 } 2183 } 2184 2185 public void resetThrottling() { 2186 mApiCallCount = 0; 2187 } 2188 2189 public void dump(@NonNull ShortcutService s, @NonNull PrintWriter pw, @NonNull String prefix) { 2190 pw.print(prefix); 2191 pw.print("Package: "); 2192 pw.print(mPackageName); 2193 pw.println(); 2194 2195 pw.print(prefix); 2196 pw.print(" "); 2197 pw.print("Calls: "); 2198 pw.print(getApiCallCount(s)); 2199 pw.println(); 2200 2201 // This should be after getApiCallCount(), which may update it. 2202 pw.print(prefix); 2203 pw.print(" "); 2204 pw.print("Last reset: ["); 2205 pw.print(mLastResetTime); 2206 pw.print("] "); 2207 pw.print(s.formatTime(mLastResetTime)); 2208 pw.println(); 2209 2210 pw.println(" Shortcuts:"); 2211 long totalBitmapSize = 0; 2212 final ArrayMap<String, ShortcutInfo> shortcuts = mShortcuts; 2213 final int size = shortcuts.size(); 2214 for (int i = 0; i < size; i++) { 2215 final ShortcutInfo si = shortcuts.valueAt(i); 2216 pw.print(" "); 2217 pw.println(si.toInsecureString()); 2218 if (si.getBitmapPath() != null) { 2219 final long len = new File(si.getBitmapPath()).length(); 2220 pw.print(" "); 2221 pw.print("bitmap size="); 2222 pw.println(len); 2223 2224 totalBitmapSize += len; 2225 } 2226 } 2227 pw.print(prefix); 2228 pw.print(" "); 2229 pw.print("Total bitmap size: "); 2230 pw.print(totalBitmapSize); 2231 pw.print(" ("); 2232 pw.print(Formatter.formatFileSize(s.mContext, totalBitmapSize)); 2233 pw.println(")"); 2234 } 2235 2236 public void saveToXml(@NonNull XmlSerializer out) throws IOException, XmlPullParserException { 2237 out.startTag(null, ShortcutService.TAG_PACKAGE); 2238 2239 ShortcutService.writeAttr(out, ShortcutService.ATTR_NAME, mPackageName); 2240 ShortcutService.writeAttr(out, ShortcutService.ATTR_DYNAMIC_COUNT, mDynamicShortcutCount); 2241 ShortcutService.writeAttr(out, ShortcutService.ATTR_CALL_COUNT, mApiCallCount); 2242 ShortcutService.writeAttr(out, ShortcutService.ATTR_LAST_RESET, mLastResetTime); 2243 2244 final int size = mShortcuts.size(); 2245 for (int j = 0; j < size; j++) { 2246 saveShortcut(out, mShortcuts.valueAt(j)); 2247 } 2248 2249 out.endTag(null, ShortcutService.TAG_PACKAGE); 2250 } 2251 2252 private static void saveShortcut(XmlSerializer out, ShortcutInfo si) 2253 throws IOException, XmlPullParserException { 2254 out.startTag(null, ShortcutService.TAG_SHORTCUT); 2255 ShortcutService.writeAttr(out, ShortcutService.ATTR_ID, si.getId()); 2256 // writeAttr(out, "package", si.getPackageName()); // not needed 2257 ShortcutService.writeAttr(out, ShortcutService.ATTR_ACTIVITY, si.getActivityComponent()); 2258 // writeAttr(out, "icon", si.getIcon()); // We don't save it. 2259 ShortcutService.writeAttr(out, ShortcutService.ATTR_TITLE, si.getTitle()); 2260 ShortcutService.writeAttr(out, ShortcutService.ATTR_INTENT, si.getIntentNoExtras()); 2261 ShortcutService.writeAttr(out, ShortcutService.ATTR_WEIGHT, si.getWeight()); 2262 ShortcutService.writeAttr(out, ShortcutService.ATTR_TIMESTAMP, 2263 si.getLastChangedTimestamp()); 2264 ShortcutService.writeAttr(out, ShortcutService.ATTR_FLAGS, si.getFlags()); 2265 ShortcutService.writeAttr(out, ShortcutService.ATTR_ICON_RES, si.getIconResourceId()); 2266 ShortcutService.writeAttr(out, ShortcutService.ATTR_BITMAP_PATH, si.getBitmapPath()); 2267 2268 ShortcutService.writeTagExtra(out, ShortcutService.TAG_INTENT_EXTRAS, 2269 si.getIntentPersistableExtras()); 2270 ShortcutService.writeTagExtra(out, ShortcutService.TAG_EXTRAS, si.getExtras()); 2271 2272 out.endTag(null, ShortcutService.TAG_SHORTCUT); 2273 } 2274 2275 public static PackageShortcuts loadFromXml(XmlPullParser parser, int userId) 2276 throws IOException, XmlPullParserException { 2277 2278 final String packageName = ShortcutService.parseStringAttribute(parser, 2279 ShortcutService.ATTR_NAME); 2280 2281 final PackageShortcuts ret = new PackageShortcuts(userId, packageName); 2282 2283 ret.mDynamicShortcutCount = 2284 ShortcutService.parseIntAttribute(parser, ShortcutService.ATTR_DYNAMIC_COUNT); 2285 ret.mApiCallCount = 2286 ShortcutService.parseIntAttribute(parser, ShortcutService.ATTR_CALL_COUNT); 2287 ret.mLastResetTime = 2288 ShortcutService.parseLongAttribute(parser, ShortcutService.ATTR_LAST_RESET); 2289 2290 final int outerDepth = parser.getDepth(); 2291 int type; 2292 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 2293 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 2294 if (type != XmlPullParser.START_TAG) { 2295 continue; 2296 } 2297 final int depth = parser.getDepth(); 2298 final String tag = parser.getName(); 2299 switch (tag) { 2300 case ShortcutService.TAG_SHORTCUT: 2301 final ShortcutInfo si = parseShortcut(parser, packageName); 2302 2303 // Don't use addShortcut(), we don't need to save the icon. 2304 ret.mShortcuts.put(si.getId(), si); 2305 continue; 2306 } 2307 throw ShortcutService.throwForInvalidTag(depth, tag); 2308 } 2309 return ret; 2310 } 2311 2312 private static ShortcutInfo parseShortcut(XmlPullParser parser, String packageName) 2313 throws IOException, XmlPullParserException { 2314 String id; 2315 ComponentName activityComponent; 2316 // Icon icon; 2317 String title; 2318 Intent intent; 2319 PersistableBundle intentPersistableExtras = null; 2320 int weight; 2321 PersistableBundle extras = null; 2322 long lastChangedTimestamp; 2323 int flags; 2324 int iconRes; 2325 String bitmapPath; 2326 2327 id = ShortcutService.parseStringAttribute(parser, ShortcutService.ATTR_ID); 2328 activityComponent = ShortcutService.parseComponentNameAttribute(parser, 2329 ShortcutService.ATTR_ACTIVITY); 2330 title = ShortcutService.parseStringAttribute(parser, ShortcutService.ATTR_TITLE); 2331 intent = ShortcutService.parseIntentAttribute(parser, ShortcutService.ATTR_INTENT); 2332 weight = (int) ShortcutService.parseLongAttribute(parser, ShortcutService.ATTR_WEIGHT); 2333 lastChangedTimestamp = (int) ShortcutService.parseLongAttribute(parser, 2334 ShortcutService.ATTR_TIMESTAMP); 2335 flags = (int) ShortcutService.parseLongAttribute(parser, ShortcutService.ATTR_FLAGS); 2336 iconRes = (int) ShortcutService.parseLongAttribute(parser, ShortcutService.ATTR_ICON_RES); 2337 bitmapPath = ShortcutService.parseStringAttribute(parser, ShortcutService.ATTR_BITMAP_PATH); 2338 2339 final int outerDepth = parser.getDepth(); 2340 int type; 2341 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 2342 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 2343 if (type != XmlPullParser.START_TAG) { 2344 continue; 2345 } 2346 final int depth = parser.getDepth(); 2347 final String tag = parser.getName(); 2348 if (ShortcutService.DEBUG_LOAD) { 2349 Slog.d(TAG, String.format(" depth=%d type=%d name=%s", 2350 depth, type, tag)); 2351 } 2352 switch (tag) { 2353 case ShortcutService.TAG_INTENT_EXTRAS: 2354 intentPersistableExtras = PersistableBundle.restoreFromXml(parser); 2355 continue; 2356 case ShortcutService.TAG_EXTRAS: 2357 extras = PersistableBundle.restoreFromXml(parser); 2358 continue; 2359 } 2360 throw ShortcutService.throwForInvalidTag(depth, tag); 2361 } 2362 return new ShortcutInfo( 2363 id, packageName, activityComponent, /* icon =*/ null, title, intent, 2364 intentPersistableExtras, weight, extras, lastChangedTimestamp, flags, 2365 iconRes, bitmapPath); 2366 } 2367} 2368