ShortcutService.java revision 4554d0e5b69433ddaa698e976ee584f7f4f14948
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 = Binder.clearCallingIdentity(); 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 Binder.restoreCallingIdentity(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 985 // TODO Is MATCH_UNINSTALLED_PACKAGES correct to get SD card app info? 986 987 return mContext.getPackageManager().getPackageUidAsUser(packageName, 988 PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE 989 | PackageManager.MATCH_UNINSTALLED_PACKAGES, userId); 990 } catch (NameNotFoundException e) { 991 return -1; 992 } 993 } 994 995 /** 996 * Throw if {@code numShortcuts} is bigger than {@link #mMaxDynamicShortcuts}. 997 */ 998 void enforceMaxDynamicShortcuts(int numShortcuts) { 999 if (numShortcuts > mMaxDynamicShortcuts) { 1000 throw new IllegalArgumentException("Max number of dynamic shortcuts exceeded"); 1001 } 1002 } 1003 1004 /** 1005 * - Sends a notification to LauncherApps 1006 * - Write to file 1007 */ 1008 private void userPackageChanged(@NonNull String packageName, @UserIdInt int userId) { 1009 notifyListeners(packageName, userId); 1010 scheduleSaveUser(userId); 1011 } 1012 1013 private void notifyListeners(@NonNull String packageName, @UserIdInt int userId) { 1014 final ArrayList<ShortcutChangeListener> copy; 1015 final List<ShortcutInfo> shortcuts = new ArrayList<>(); 1016 synchronized (mLock) { 1017 copy = new ArrayList<>(mListeners); 1018 1019 getPackageShortcutsLocked(packageName, userId) 1020 .findAll(shortcuts, /* query =*/ null, ShortcutInfo.CLONE_REMOVE_NON_KEY_INFO); 1021 } 1022 for (int i = copy.size() - 1; i >= 0; i--) { 1023 copy.get(i).onShortcutChanged(packageName, shortcuts, userId); 1024 } 1025 } 1026 1027 /** 1028 * Clean up / validate an incoming shortcut. 1029 * - Make sure all mandatory fields are set. 1030 * - Make sure the intent's extras are persistable, and them to set 1031 * {@link ShortcutInfo#mIntentPersistableExtras}. Also clear its extras. 1032 * - Clear flags. 1033 * 1034 * TODO Detailed unit tests 1035 */ 1036 private void fixUpIncomingShortcutInfo(@NonNull ShortcutInfo shortcut, boolean forUpdate) { 1037 Preconditions.checkNotNull(shortcut, "Null shortcut detected"); 1038 if (shortcut.getActivityComponent() != null) { 1039 Preconditions.checkState( 1040 shortcut.getPackageName().equals( 1041 shortcut.getActivityComponent().getPackageName()), 1042 "Activity package name mismatch"); 1043 } 1044 1045 if (!forUpdate) { 1046 shortcut.enforceMandatoryFields(); 1047 } 1048 if (shortcut.getIcon() != null) { 1049 ShortcutInfo.validateIcon(shortcut.getIcon()); 1050 } 1051 1052 validateForXml(shortcut.getId()); 1053 validateForXml(shortcut.getTitle()); 1054 validatePersistableBundleForXml(shortcut.getIntentPersistableExtras()); 1055 validatePersistableBundleForXml(shortcut.getExtras()); 1056 1057 shortcut.setFlags(0); 1058 } 1059 1060 // KXmlSerializer is strict and doesn't allow certain characters, so we disallow those 1061 // characters. 1062 1063 private static void validatePersistableBundleForXml(PersistableBundle b) { 1064 if (b == null || b.size() == 0) { 1065 return; 1066 } 1067 for (String key : b.keySet()) { 1068 validateForXml(key); 1069 final Object value = b.get(key); 1070 if (value == null) { 1071 continue; 1072 } else if (value instanceof String) { 1073 validateForXml((String) value); 1074 } else if (value instanceof String[]) { 1075 for (String v : (String[]) value) { 1076 validateForXml(v); 1077 } 1078 } else if (value instanceof PersistableBundle) { 1079 validatePersistableBundleForXml((PersistableBundle) value); 1080 } 1081 } 1082 } 1083 1084 private static void validateForXml(String s) { 1085 if (TextUtils.isEmpty(s)) { 1086 return; 1087 } 1088 for (int i = s.length() - 1; i >= 0; i--) { 1089 if (!isAllowedInXml(s.charAt(i))) { 1090 throw new IllegalArgumentException("Unsupported character detected in: " + s); 1091 } 1092 } 1093 } 1094 1095 private static boolean isAllowedInXml(char c) { 1096 return (c >= 0x20 && c <= 0xd7ff) || (c >= 0xe000 && c <= 0xfffd); 1097 } 1098 1099 // === APIs === 1100 1101 @Override 1102 public boolean setDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList, 1103 @UserIdInt int userId) { 1104 verifyCaller(packageName, userId); 1105 1106 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList(); 1107 final int size = newShortcuts.size(); 1108 1109 synchronized (mLock) { 1110 final PackageShortcuts ps = getPackageShortcutsLocked(packageName, userId); 1111 1112 // Throttling. 1113 if (!ps.tryApiCall(this)) { 1114 return false; 1115 } 1116 enforceMaxDynamicShortcuts(size); 1117 1118 // Validate the shortcuts. 1119 for (int i = 0; i < size; i++) { 1120 fixUpIncomingShortcutInfo(newShortcuts.get(i), /* forUpdate= */ false); 1121 } 1122 1123 // First, remove all un-pinned; dynamic shortcuts 1124 ps.deleteAllDynamicShortcuts(this); 1125 1126 // Then, add/update all. We need to make sure to take over "pinned" flag. 1127 for (int i = 0; i < size; i++) { 1128 final ShortcutInfo newShortcut = newShortcuts.get(i); 1129 newShortcut.addFlags(ShortcutInfo.FLAG_DYNAMIC); 1130 ps.updateShortcutWithCapping(this, newShortcut); 1131 } 1132 } 1133 userPackageChanged(packageName, userId); 1134 return true; 1135 } 1136 1137 @Override 1138 public boolean updateShortcuts(String packageName, ParceledListSlice shortcutInfoList, 1139 @UserIdInt int userId) { 1140 verifyCaller(packageName, userId); 1141 1142 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList(); 1143 final int size = newShortcuts.size(); 1144 1145 synchronized (mLock) { 1146 final PackageShortcuts ps = getPackageShortcutsLocked(packageName, userId); 1147 1148 // Throttling. 1149 if (!ps.tryApiCall(this)) { 1150 return false; 1151 } 1152 1153 for (int i = 0; i < size; i++) { 1154 final ShortcutInfo source = newShortcuts.get(i); 1155 fixUpIncomingShortcutInfo(source, /* forUpdate= */ true); 1156 1157 final ShortcutInfo target = ps.findShortcutById(source.getId()); 1158 if (target != null) { 1159 final boolean replacingIcon = (source.getIcon() != null); 1160 if (replacingIcon) { 1161 removeIcon(userId, target); 1162 } 1163 1164 target.copyNonNullFieldsFrom(source); 1165 1166 if (replacingIcon) { 1167 saveIconAndFixUpShortcut(userId, target); 1168 } 1169 } 1170 } 1171 } 1172 userPackageChanged(packageName, userId); 1173 1174 return true; 1175 } 1176 1177 @Override 1178 public boolean addDynamicShortcut(String packageName, ShortcutInfo newShortcut, 1179 @UserIdInt int userId) { 1180 verifyCaller(packageName, userId); 1181 1182 synchronized (mLock) { 1183 final PackageShortcuts ps = getPackageShortcutsLocked(packageName, userId); 1184 1185 // Throttling. 1186 if (!ps.tryApiCall(this)) { 1187 return false; 1188 } 1189 1190 // Validate the shortcut. 1191 fixUpIncomingShortcutInfo(newShortcut, /* forUpdate= */ false); 1192 1193 // Add it. 1194 newShortcut.addFlags(ShortcutInfo.FLAG_DYNAMIC); 1195 ps.updateShortcutWithCapping(this, newShortcut); 1196 } 1197 userPackageChanged(packageName, userId); 1198 1199 return true; 1200 } 1201 1202 @Override 1203 public void deleteDynamicShortcut(String packageName, String shortcutId, 1204 @UserIdInt int userId) { 1205 verifyCaller(packageName, userId); 1206 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId must be provided"); 1207 1208 synchronized (mLock) { 1209 getPackageShortcutsLocked(packageName, userId).deleteDynamicWithId(this, shortcutId); 1210 } 1211 userPackageChanged(packageName, userId); 1212 } 1213 1214 @Override 1215 public void deleteAllDynamicShortcuts(String packageName, @UserIdInt int userId) { 1216 verifyCaller(packageName, userId); 1217 1218 synchronized (mLock) { 1219 getPackageShortcutsLocked(packageName, userId).deleteAllDynamicShortcuts(this); 1220 } 1221 userPackageChanged(packageName, userId); 1222 } 1223 1224 @Override 1225 public ParceledListSlice<ShortcutInfo> getDynamicShortcuts(String packageName, 1226 @UserIdInt int userId) { 1227 verifyCaller(packageName, userId); 1228 synchronized (mLock) { 1229 return getShortcutsWithQueryLocked( 1230 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR, 1231 ShortcutInfo::isDynamic); 1232 } 1233 } 1234 1235 @Override 1236 public ParceledListSlice<ShortcutInfo> getPinnedShortcuts(String packageName, 1237 @UserIdInt int userId) { 1238 verifyCaller(packageName, userId); 1239 synchronized (mLock) { 1240 return getShortcutsWithQueryLocked( 1241 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR, 1242 ShortcutInfo::isPinned); 1243 } 1244 } 1245 1246 private ParceledListSlice<ShortcutInfo> getShortcutsWithQueryLocked(@NonNull String packageName, 1247 @UserIdInt int userId, int cloneFlags, @NonNull Predicate<ShortcutInfo> query) { 1248 1249 final ArrayList<ShortcutInfo> ret = new ArrayList<>(); 1250 1251 getPackageShortcutsLocked(packageName, userId).findAll(ret, query, cloneFlags); 1252 1253 return new ParceledListSlice<>(ret); 1254 } 1255 1256 @Override 1257 public int getMaxDynamicShortcutCount(String packageName, @UserIdInt int userId) 1258 throws RemoteException { 1259 verifyCaller(packageName, userId); 1260 1261 return mMaxDynamicShortcuts; 1262 } 1263 1264 @Override 1265 public int getRemainingCallCount(String packageName, @UserIdInt int userId) { 1266 verifyCaller(packageName, userId); 1267 1268 synchronized (mLock) { 1269 return mMaxDailyUpdates 1270 - getPackageShortcutsLocked(packageName, userId).getApiCallCount(this); 1271 } 1272 } 1273 1274 @Override 1275 public long getRateLimitResetTime(String packageName, @UserIdInt int userId) { 1276 verifyCaller(packageName, userId); 1277 1278 synchronized (mLock) { 1279 return getNextResetTimeLocked(); 1280 } 1281 } 1282 1283 @Override 1284 public int getIconMaxDimensions(String packageName, int userId) throws RemoteException { 1285 synchronized (mLock) { 1286 return mMaxIconDimension; 1287 } 1288 } 1289 1290 /** 1291 * Reset all throttling, for developer options and command line. Only system/shell can call it. 1292 */ 1293 @Override 1294 public void resetThrottling() { 1295 enforceSystemOrShell(); 1296 1297 resetThrottlingInner(getCallingUserId()); 1298 } 1299 1300 void resetThrottlingInner(@UserIdInt int userId) { 1301 synchronized (mLock) { 1302 getUserShortcutsLocked(userId).resetThrottling(); 1303 } 1304 scheduleSaveUser(userId); 1305 Slog.i(TAG, "ShortcutManager: throttling counter reset"); 1306 } 1307 1308 // We override this method in unit tests to do a simpler check. 1309 boolean hasShortcutHostPermission(@NonNull String callingPackage, int userId) { 1310 return hasShortcutHostPermissionInner(callingPackage, userId); 1311 } 1312 1313 // This method is extracted so we can directly call this method from unit tests, 1314 // even when hasShortcutPermission() is overridden. 1315 @VisibleForTesting 1316 boolean hasShortcutHostPermissionInner(@NonNull String callingPackage, int userId) { 1317 synchronized (mLock) { 1318 long start = 0; 1319 if (DEBUG) { 1320 start = System.currentTimeMillis(); 1321 } 1322 1323 final UserShortcuts user = getUserShortcutsLocked(userId); 1324 1325 final List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 1326 1327 // Default launcher from package manager. 1328 final ComponentName defaultLauncher = injectPackageManagerInternal() 1329 .getHomeActivitiesAsUser(allHomeCandidates, userId); 1330 1331 ComponentName detected; 1332 if (defaultLauncher != null) { 1333 detected = defaultLauncher; 1334 if (DEBUG) { 1335 Slog.v(TAG, "Default launcher from PM: " + detected); 1336 } 1337 } else { 1338 detected = user.getLauncherComponent(); 1339 1340 // TODO: Make sure it's still enabled. 1341 if (DEBUG) { 1342 Slog.v(TAG, "Cached launcher: " + detected); 1343 } 1344 } 1345 1346 if (detected == null) { 1347 // If we reach here, that means it's the first check since the user was created, 1348 // and there's already multiple launchers and there's no default set. 1349 // Find the system one with the highest priority. 1350 // (We need to check the priority too because of FallbackHome in Settings.) 1351 // If there's no system launcher yet, then no one can access shortcuts, until 1352 // the user explicitly 1353 final int size = allHomeCandidates.size(); 1354 1355 int lastPriority = Integer.MIN_VALUE; 1356 for (int i = 0; i < size; i++) { 1357 final ResolveInfo ri = allHomeCandidates.get(i); 1358 if (!ri.activityInfo.applicationInfo.isSystemApp()) { 1359 continue; 1360 } 1361 if (DEBUG) { 1362 Slog.d(TAG, String.format("hasShortcutPermissionInner: pkg=%s prio=%d", 1363 ri.activityInfo.getComponentName(), ri.priority)); 1364 } 1365 if (ri.priority < lastPriority) { 1366 continue; 1367 } 1368 detected = ri.activityInfo.getComponentName(); 1369 lastPriority = ri.priority; 1370 } 1371 } 1372 if (DEBUG) { 1373 long end = System.currentTimeMillis(); 1374 Slog.v(TAG, String.format("hasShortcutPermission took %d ms", end - start)); 1375 } 1376 if (detected != null) { 1377 if (DEBUG) { 1378 Slog.v(TAG, "Detected launcher: " + detected); 1379 } 1380 user.setLauncherComponent(this, detected); 1381 return detected.getPackageName().equals(callingPackage); 1382 } else { 1383 // Default launcher not found. 1384 return false; 1385 } 1386 } 1387 } 1388 1389 /** 1390 * Entry point from {@link LauncherApps}. 1391 */ 1392 private class LocalService extends ShortcutServiceInternal { 1393 @Override 1394 public List<ShortcutInfo> getShortcuts( 1395 @NonNull String callingPackage, long changedSince, 1396 @Nullable String packageName, @Nullable ComponentName componentName, 1397 int queryFlags, int userId) { 1398 final ArrayList<ShortcutInfo> ret = new ArrayList<>(); 1399 final int cloneFlag = 1400 ((queryFlags & ShortcutQuery.FLAG_GET_KEY_FIELDS_ONLY) == 0) 1401 ? ShortcutInfo.CLONE_REMOVE_FOR_LAUNCHER 1402 : ShortcutInfo.CLONE_REMOVE_NON_KEY_INFO; 1403 1404 synchronized (mLock) { 1405 if (packageName != null) { 1406 getShortcutsInnerLocked(packageName, changedSince, componentName, queryFlags, 1407 userId, ret, cloneFlag); 1408 } else { 1409 final ArrayMap<String, PackageShortcuts> packages = 1410 getUserShortcutsLocked(userId).getPackages(); 1411 for (int i = packages.size() - 1; i >= 0; i--) { 1412 getShortcutsInnerLocked( 1413 packages.keyAt(i), 1414 changedSince, componentName, queryFlags, userId, ret, cloneFlag); 1415 } 1416 } 1417 } 1418 return ret; 1419 } 1420 1421 private void getShortcutsInnerLocked(@Nullable String packageName,long changedSince, 1422 @Nullable ComponentName componentName, int queryFlags, 1423 int userId, ArrayList<ShortcutInfo> ret, int cloneFlag) { 1424 getPackageShortcutsLocked(packageName, userId).findAll(ret, 1425 (ShortcutInfo si) -> { 1426 if (si.getLastChangedTimestamp() < changedSince) { 1427 return false; 1428 } 1429 if (componentName != null 1430 && !componentName.equals(si.getActivityComponent())) { 1431 return false; 1432 } 1433 final boolean matchDynamic = 1434 ((queryFlags & ShortcutQuery.FLAG_GET_DYNAMIC) != 0) 1435 && si.isDynamic(); 1436 final boolean matchPinned = 1437 ((queryFlags & ShortcutQuery.FLAG_GET_PINNED) != 0) 1438 && si.isPinned(); 1439 return matchDynamic || matchPinned; 1440 }, cloneFlag); 1441 } 1442 1443 @Override 1444 public List<ShortcutInfo> getShortcutInfo( 1445 @NonNull String callingPackage, 1446 @NonNull String packageName, @Nullable List<String> ids, int userId) { 1447 // Calling permission must be checked by LauncherAppsImpl. 1448 Preconditions.checkStringNotEmpty(packageName, "packageName"); 1449 1450 final ArrayList<ShortcutInfo> ret = new ArrayList<>(ids.size()); 1451 final ArraySet<String> idSet = new ArraySet<>(ids); 1452 synchronized (mLock) { 1453 getPackageShortcutsLocked(packageName, userId).findAll(ret, 1454 (ShortcutInfo si) -> idSet.contains(si.getId()), 1455 ShortcutInfo.CLONE_REMOVE_FOR_LAUNCHER); 1456 } 1457 return ret; 1458 } 1459 1460 @Override 1461 public void pinShortcuts(@NonNull String callingPackage, @NonNull String packageName, 1462 @NonNull List<String> shortcutIds, int userId) { 1463 // Calling permission must be checked by LauncherAppsImpl. 1464 Preconditions.checkStringNotEmpty(packageName, "packageName"); 1465 Preconditions.checkNotNull(shortcutIds, "shortcutIds"); 1466 1467 synchronized (mLock) { 1468 getPackageShortcutsLocked(packageName, userId).replacePinned( 1469 ShortcutService.this, callingPackage, shortcutIds); 1470 } 1471 userPackageChanged(packageName, userId); 1472 } 1473 1474 @Override 1475 public Intent createShortcutIntent(@NonNull String callingPackage, 1476 @NonNull String packageName, @NonNull String shortcutId, int userId) { 1477 // Calling permission must be checked by LauncherAppsImpl. 1478 Preconditions.checkStringNotEmpty(packageName, "packageName can't be empty"); 1479 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId can't be empty"); 1480 1481 synchronized (mLock) { 1482 final ShortcutInfo fullShortcut = 1483 getPackageShortcutsLocked(packageName, userId) 1484 .findShortcutById(shortcutId); 1485 return fullShortcut == null ? null : fullShortcut.getIntent(); 1486 } 1487 } 1488 1489 @Override 1490 public void addListener(@NonNull ShortcutChangeListener listener) { 1491 synchronized (mLock) { 1492 mListeners.add(Preconditions.checkNotNull(listener)); 1493 } 1494 } 1495 1496 @Override 1497 public int getShortcutIconResId(@NonNull String callingPackage, 1498 @NonNull ShortcutInfo shortcut, int userId) { 1499 Preconditions.checkNotNull(shortcut, "shortcut"); 1500 1501 synchronized (mLock) { 1502 final ShortcutInfo shortcutInfo = getPackageShortcutsLocked( 1503 shortcut.getPackageName(), userId).findShortcutById(shortcut.getId()); 1504 return (shortcutInfo != null && shortcutInfo.hasIconResource()) 1505 ? shortcutInfo.getIconResourceId() : 0; 1506 } 1507 } 1508 1509 @Override 1510 public ParcelFileDescriptor getShortcutIconFd(@NonNull String callingPackage, 1511 @NonNull ShortcutInfo shortcutIn, int userId) { 1512 Preconditions.checkNotNull(shortcutIn, "shortcut"); 1513 1514 synchronized (mLock) { 1515 final ShortcutInfo shortcutInfo = getPackageShortcutsLocked( 1516 shortcutIn.getPackageName(), userId).findShortcutById(shortcutIn.getId()); 1517 if (shortcutInfo == null || !shortcutInfo.hasIconFile()) { 1518 return null; 1519 } 1520 try { 1521 if (shortcutInfo.getBitmapPath() == null) { 1522 Slog.w(TAG, "null bitmap detected in getShortcutIconFd()"); 1523 return null; 1524 } 1525 return ParcelFileDescriptor.open( 1526 new File(shortcutInfo.getBitmapPath()), 1527 ParcelFileDescriptor.MODE_READ_ONLY); 1528 } catch (FileNotFoundException e) { 1529 Slog.e(TAG, "Icon file not found: " + shortcutInfo.getBitmapPath()); 1530 return null; 1531 } 1532 } 1533 } 1534 1535 @Override 1536 public boolean hasShortcutHostPermission(@NonNull String callingPackage, int userId) { 1537 return ShortcutService.this.hasShortcutHostPermission(callingPackage, userId); 1538 } 1539 } 1540 1541 // === Dump === 1542 1543 @Override 1544 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 1545 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 1546 != PackageManager.PERMISSION_GRANTED) { 1547 pw.println("Permission Denial: can't dump UserManager from from pid=" 1548 + Binder.getCallingPid() 1549 + ", uid=" + Binder.getCallingUid() 1550 + " without permission " 1551 + android.Manifest.permission.DUMP); 1552 return; 1553 } 1554 dumpInner(pw); 1555 } 1556 1557 @VisibleForTesting 1558 void dumpInner(PrintWriter pw) { 1559 synchronized (mLock) { 1560 final long now = injectCurrentTimeMillis(); 1561 pw.print("Now: ["); 1562 pw.print(now); 1563 pw.print("] "); 1564 pw.print(formatTime(now)); 1565 1566 pw.print(" Raw last reset: ["); 1567 pw.print(mRawLastResetTime); 1568 pw.print("] "); 1569 pw.print(formatTime(mRawLastResetTime)); 1570 1571 final long last = getLastResetTimeLocked(); 1572 pw.print(" Last reset: ["); 1573 pw.print(last); 1574 pw.print("] "); 1575 pw.print(formatTime(last)); 1576 1577 final long next = getNextResetTimeLocked(); 1578 pw.print(" Next reset: ["); 1579 pw.print(next); 1580 pw.print("] "); 1581 pw.print(formatTime(next)); 1582 pw.println(); 1583 1584 pw.print(" Max icon dim: "); 1585 pw.print(mMaxIconDimension); 1586 pw.print(" Icon format: "); 1587 pw.print(mIconPersistFormat); 1588 pw.print(" Icon quality: "); 1589 pw.print(mIconPersistQuality); 1590 pw.println(); 1591 1592 1593 for (int i = 0; i < mUsers.size(); i++) { 1594 pw.println(); 1595 mUsers.valueAt(i).dump(this, pw, " "); 1596 } 1597 } 1598 } 1599 1600 static String formatTime(long time) { 1601 Time tobj = new Time(); 1602 tobj.set(time); 1603 return tobj.format("%Y-%m-%d %H:%M:%S"); 1604 } 1605 1606 // === Shell support === 1607 1608 @Override 1609 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err, 1610 String[] args, ResultReceiver resultReceiver) throws RemoteException { 1611 1612 enforceShell(); 1613 1614 (new MyShellCommand()).exec(this, in, out, err, args, resultReceiver); 1615 } 1616 1617 static class CommandException extends Exception { 1618 public CommandException(String message) { 1619 super(message); 1620 } 1621 } 1622 1623 /** 1624 * Handle "adb shell cmd". 1625 */ 1626 private class MyShellCommand extends ShellCommand { 1627 1628 private int mUserId = UserHandle.USER_SYSTEM; 1629 1630 private void parseOptions(boolean takeUser) 1631 throws CommandException { 1632 String opt; 1633 while ((opt = getNextOption()) != null) { 1634 switch (opt) { 1635 case "--user": 1636 if (takeUser) { 1637 mUserId = UserHandle.parseUserArg(getNextArgRequired()); 1638 break; 1639 } 1640 // fallthrough 1641 default: 1642 throw new CommandException("Unknown option: " + opt); 1643 } 1644 } 1645 } 1646 1647 @Override 1648 public int onCommand(String cmd) { 1649 if (cmd == null) { 1650 return handleDefaultCommands(cmd); 1651 } 1652 final PrintWriter pw = getOutPrintWriter(); 1653 try { 1654 switch (cmd) { 1655 case "reset-package-throttling": 1656 handleResetPackageThrottling(); 1657 break; 1658 case "reset-throttling": 1659 handleResetThrottling(); 1660 break; 1661 case "override-config": 1662 handleOverrideConfig(); 1663 break; 1664 case "reset-config": 1665 handleResetConfig(); 1666 break; 1667 case "clear-default-launcher": 1668 handleClearDefaultLauncher(); 1669 break; 1670 case "get-default-launcher": 1671 handleGetDefaultLauncher(); 1672 break; 1673 case "refresh-default-launcher": 1674 handleRefreshDefaultLauncher(); 1675 break; 1676 default: 1677 return handleDefaultCommands(cmd); 1678 } 1679 } catch (CommandException e) { 1680 pw.println("Error: " + e.getMessage()); 1681 return 1; 1682 } 1683 pw.println("Success"); 1684 return 0; 1685 } 1686 1687 @Override 1688 public void onHelp() { 1689 final PrintWriter pw = getOutPrintWriter(); 1690 pw.println("Usage: cmd shortcut COMMAND [options ...]"); 1691 pw.println(); 1692 pw.println("cmd shortcut reset-package-throttling [--user USER_ID] PACKAGE"); 1693 pw.println(" Reset throttling for a package"); 1694 pw.println(); 1695 pw.println("cmd shortcut reset-throttling"); 1696 pw.println(" Reset throttling for all packages and users"); 1697 pw.println(); 1698 pw.println("cmd shortcut override-config CONFIG"); 1699 pw.println(" Override the configuration for testing (will last until reboot)"); 1700 pw.println(); 1701 pw.println("cmd shortcut reset-config"); 1702 pw.println(" Reset the configuration set with \"update-config\""); 1703 pw.println(); 1704 pw.println("cmd shortcut clear-default-launcher [--user USER_ID]"); 1705 pw.println(" Clear the cached default launcher"); 1706 pw.println(); 1707 pw.println("cmd shortcut get-default-launcher [--user USER_ID]"); 1708 pw.println(" Show the cached default launcher"); 1709 pw.println(); 1710 pw.println("cmd shortcut refresh-default-launcher [--user USER_ID]"); 1711 pw.println(" Refresh the cached default launcher"); 1712 pw.println(); 1713 } 1714 1715 private int handleResetThrottling() throws CommandException { 1716 parseOptions(/* takeUser =*/ true); 1717 1718 resetThrottlingInner(mUserId); 1719 return 0; 1720 } 1721 1722 private void handleResetPackageThrottling() throws CommandException { 1723 parseOptions(/* takeUser =*/ true); 1724 1725 final String packageName = getNextArgRequired(); 1726 1727 synchronized (mLock) { 1728 getPackageShortcutsLocked(packageName, mUserId).resetRateLimitingForCommandLine(); 1729 saveUserLocked(mUserId); 1730 } 1731 } 1732 1733 private void handleOverrideConfig() throws CommandException { 1734 final String config = getNextArgRequired(); 1735 1736 synchronized (mLock) { 1737 if (!updateConfigurationLocked(config)) { 1738 throw new CommandException("override-config failed. See logcat for details."); 1739 } 1740 } 1741 } 1742 1743 private void handleResetConfig() { 1744 synchronized (mLock) { 1745 loadConfigurationLocked(); 1746 } 1747 } 1748 1749 private void clearLauncher() { 1750 synchronized (mLock) { 1751 getUserShortcutsLocked(mUserId).setLauncherComponent( 1752 ShortcutService.this, null); 1753 } 1754 } 1755 1756 private void showLauncher() { 1757 synchronized (mLock) { 1758 // This ensures to set the cached launcher. Package name doesn't matter. 1759 hasShortcutHostPermissionInner("-", mUserId); 1760 1761 getOutPrintWriter().println("Launcher: " 1762 + getUserShortcutsLocked(mUserId).getLauncherComponent()); 1763 } 1764 } 1765 1766 private void handleClearDefaultLauncher() throws CommandException { 1767 parseOptions(/* takeUser =*/ true); 1768 1769 clearLauncher(); 1770 } 1771 1772 private void handleGetDefaultLauncher() throws CommandException { 1773 parseOptions(/* takeUser =*/ true); 1774 1775 showLauncher(); 1776 } 1777 1778 private void handleRefreshDefaultLauncher() throws CommandException { 1779 parseOptions(/* takeUser =*/ true); 1780 1781 clearLauncher(); 1782 showLauncher(); 1783 } 1784 } 1785 1786 // === Unit test support === 1787 1788 // Injection point. 1789 long injectCurrentTimeMillis() { 1790 return System.currentTimeMillis(); 1791 } 1792 1793 // Injection point. 1794 int injectBinderCallingUid() { 1795 return getCallingUid(); 1796 } 1797 1798 final int getCallingUserId() { 1799 return UserHandle.getUserId(injectBinderCallingUid()); 1800 } 1801 1802 File injectSystemDataPath() { 1803 return Environment.getDataSystemDirectory(); 1804 } 1805 1806 File injectUserDataPath(@UserIdInt int userId) { 1807 return new File(Environment.getDataSystemCeDirectory(userId), DIRECTORY_PER_USER); 1808 } 1809 1810 @VisibleForTesting 1811 boolean injectIsLowRamDevice() { 1812 return ActivityManager.isLowRamDeviceStatic(); 1813 } 1814 1815 PackageManagerInternal injectPackageManagerInternal() { 1816 return mPackageManagerInternal; 1817 } 1818 1819 File getUserBitmapFilePath(@UserIdInt int userId) { 1820 return new File(injectUserDataPath(userId), DIRECTORY_BITMAPS); 1821 } 1822 1823 @VisibleForTesting 1824 SparseArray<UserShortcuts> getShortcutsForTest() { 1825 return mUsers; 1826 } 1827 1828 @VisibleForTesting 1829 int getMaxDynamicShortcutsForTest() { 1830 return mMaxDynamicShortcuts; 1831 } 1832 1833 @VisibleForTesting 1834 int getMaxDailyUpdatesForTest() { 1835 return mMaxDailyUpdates; 1836 } 1837 1838 @VisibleForTesting 1839 long getResetIntervalForTest() { 1840 return mResetInterval; 1841 } 1842 1843 @VisibleForTesting 1844 int getMaxIconDimensionForTest() { 1845 return mMaxIconDimension; 1846 } 1847 1848 @VisibleForTesting 1849 CompressFormat getIconPersistFormatForTest() { 1850 return mIconPersistFormat; 1851 } 1852 1853 @VisibleForTesting 1854 int getIconPersistQualityForTest() { 1855 return mIconPersistQuality; 1856 } 1857 1858 @VisibleForTesting 1859 ShortcutInfo getPackageShortcutForTest(String packageName, String shortcutId, int userId) { 1860 synchronized (mLock) { 1861 return getPackageShortcutsLocked(packageName, userId).findShortcutById(shortcutId); 1862 } 1863 } 1864} 1865 1866/** 1867 * Per-user information. 1868 */ 1869class UserShortcuts { 1870 private static final String TAG = ShortcutService.TAG; 1871 1872 @UserIdInt 1873 final int mUserId; 1874 1875 private final ArrayMap<String, PackageShortcuts> mPackages = new ArrayMap<>(); 1876 1877 private ComponentName mLauncherComponent; 1878 1879 public UserShortcuts(int userId) { 1880 mUserId = userId; 1881 } 1882 1883 public ArrayMap<String, PackageShortcuts> getPackages() { 1884 return mPackages; 1885 } 1886 1887 public void saveToXml(XmlSerializer out) throws IOException, XmlPullParserException { 1888 out.startTag(null, ShortcutService.TAG_USER); 1889 1890 ShortcutService.writeTagValue(out, ShortcutService.TAG_LAUNCHER, 1891 mLauncherComponent); 1892 1893 for (int i = 0; i < mPackages.size(); i++) { 1894 mPackages.valueAt(i).saveToXml(out); 1895 } 1896 1897 out.endTag(null, ShortcutService.TAG_USER); 1898 } 1899 1900 public static UserShortcuts loadFromXml(XmlPullParser parser, int userId) 1901 throws IOException, XmlPullParserException { 1902 final UserShortcuts ret = new UserShortcuts(userId); 1903 1904 final int outerDepth = parser.getDepth(); 1905 int type; 1906 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 1907 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 1908 if (type != XmlPullParser.START_TAG) { 1909 continue; 1910 } 1911 final int depth = parser.getDepth(); 1912 final String tag = parser.getName(); 1913 switch (tag) { 1914 case ShortcutService.TAG_LAUNCHER: 1915 ret.mLauncherComponent = ShortcutService.parseComponentNameAttribute( 1916 parser, ShortcutService.ATTR_VALUE); 1917 continue; 1918 case ShortcutService.TAG_PACKAGE: 1919 final PackageShortcuts shortcuts = PackageShortcuts.loadFromXml(parser, userId); 1920 1921 // Don't use addShortcut(), we don't need to save the icon. 1922 ret.getPackages().put(shortcuts.mPackageName, shortcuts); 1923 continue; 1924 } 1925 throw ShortcutService.throwForInvalidTag(depth, tag); 1926 } 1927 return ret; 1928 } 1929 1930 public ComponentName getLauncherComponent() { 1931 return mLauncherComponent; 1932 } 1933 1934 public void setLauncherComponent(ShortcutService s, ComponentName launcherComponent) { 1935 if (Objects.equal(mLauncherComponent, launcherComponent)) { 1936 return; 1937 } 1938 mLauncherComponent = launcherComponent; 1939 s.scheduleSaveUser(mUserId); 1940 } 1941 1942 public void resetThrottling() { 1943 for (int i = mPackages.size() - 1; i >= 0; i--) { 1944 mPackages.valueAt(i).resetThrottling(); 1945 } 1946 } 1947 1948 public void dump(@NonNull ShortcutService s, @NonNull PrintWriter pw, @NonNull String prefix) { 1949 pw.print(prefix); 1950 pw.print("User: "); 1951 pw.print(mUserId); 1952 pw.println(); 1953 1954 pw.print(prefix); 1955 pw.print(" "); 1956 pw.print("Default launcher: "); 1957 pw.print(mLauncherComponent); 1958 pw.println(); 1959 1960 for (int i = 0; i < mPackages.size(); i++) { 1961 mPackages.valueAt(i).dump(s, pw, prefix + " "); 1962 } 1963 } 1964} 1965 1966/** 1967 * All the information relevant to shortcuts from a single package (per-user). 1968 */ 1969class PackageShortcuts { 1970 private static final String TAG = ShortcutService.TAG; 1971 1972 @UserIdInt 1973 final int mUserId; 1974 1975 @NonNull 1976 final String mPackageName; 1977 1978 /** 1979 * All the shortcuts from the package, keyed on IDs. 1980 */ 1981 final private ArrayMap<String, ShortcutInfo> mShortcuts = new ArrayMap<>(); 1982 1983 /** 1984 * # of dynamic shortcuts. 1985 */ 1986 private int mDynamicShortcutCount = 0; 1987 1988 /** 1989 * # of times the package has called rate-limited APIs. 1990 */ 1991 private int mApiCallCount; 1992 1993 /** 1994 * When {@link #mApiCallCount} was reset last time. 1995 */ 1996 private long mLastResetTime; 1997 1998 PackageShortcuts(int userId, String packageName) { 1999 mUserId = userId; 2000 mPackageName = packageName; 2001 } 2002 2003 @Nullable 2004 public ShortcutInfo findShortcutById(String id) { 2005 return mShortcuts.get(id); 2006 } 2007 2008 private ShortcutInfo deleteShortcut(@NonNull ShortcutService s, 2009 @NonNull String id) { 2010 final ShortcutInfo shortcut = mShortcuts.remove(id); 2011 if (shortcut != null) { 2012 s.removeIcon(mUserId, shortcut); 2013 shortcut.clearFlags(ShortcutInfo.FLAG_DYNAMIC | ShortcutInfo.FLAG_PINNED); 2014 } 2015 return shortcut; 2016 } 2017 2018 void addShortcut(@NonNull ShortcutService s, @NonNull ShortcutInfo newShortcut) { 2019 deleteShortcut(s, newShortcut.getId()); 2020 s.saveIconAndFixUpShortcut(mUserId, newShortcut); 2021 mShortcuts.put(newShortcut.getId(), newShortcut); 2022 } 2023 2024 /** 2025 * Add a shortcut, or update one with the same ID, with taking over existing flags. 2026 * 2027 * It checks the max number of dynamic shortcuts. 2028 */ 2029 public void updateShortcutWithCapping(@NonNull ShortcutService s, 2030 @NonNull ShortcutInfo newShortcut) { 2031 final ShortcutInfo oldShortcut = mShortcuts.get(newShortcut.getId()); 2032 2033 int oldFlags = 0; 2034 int newDynamicCount = mDynamicShortcutCount; 2035 2036 if (oldShortcut != null) { 2037 oldFlags = oldShortcut.getFlags(); 2038 if (oldShortcut.isDynamic()) { 2039 newDynamicCount--; 2040 } 2041 } 2042 if (newShortcut.isDynamic()) { 2043 newDynamicCount++; 2044 } 2045 // Make sure there's still room. 2046 s.enforceMaxDynamicShortcuts(newDynamicCount); 2047 2048 // Okay, make it dynamic and add. 2049 newShortcut.addFlags(oldFlags); 2050 2051 addShortcut(s, newShortcut); 2052 mDynamicShortcutCount = newDynamicCount; 2053 } 2054 2055 /** 2056 * Remove all shortcuts that aren't pinned nor dynamic. 2057 */ 2058 private void removeOrphans(@NonNull ShortcutService s) { 2059 ArrayList<String> removeList = null; // Lazily initialize. 2060 2061 for (int i = mShortcuts.size() - 1; i >= 0; i--) { 2062 final ShortcutInfo si = mShortcuts.valueAt(i); 2063 2064 if (si.isPinned() || si.isDynamic()) continue; 2065 2066 if (removeList == null) { 2067 removeList = new ArrayList<>(); 2068 } 2069 removeList.add(si.getId()); 2070 } 2071 if (removeList != null) { 2072 for (int i = removeList.size() - 1 ; i >= 0; i--) { 2073 deleteShortcut(s, removeList.get(i)); 2074 } 2075 } 2076 } 2077 2078 public void deleteAllDynamicShortcuts(@NonNull ShortcutService s) { 2079 for (int i = mShortcuts.size() - 1; i >= 0; i--) { 2080 mShortcuts.valueAt(i).clearFlags(ShortcutInfo.FLAG_DYNAMIC); 2081 } 2082 removeOrphans(s); 2083 mDynamicShortcutCount = 0; 2084 } 2085 2086 public void deleteDynamicWithId(@NonNull ShortcutService s, @NonNull String shortcutId) { 2087 final ShortcutInfo oldShortcut = mShortcuts.get(shortcutId); 2088 2089 if (oldShortcut == null) { 2090 return; 2091 } 2092 if (oldShortcut.isDynamic()) { 2093 mDynamicShortcutCount--; 2094 } 2095 if (oldShortcut.isPinned()) { 2096 oldShortcut.clearFlags(ShortcutInfo.FLAG_DYNAMIC); 2097 } else { 2098 deleteShortcut(s, shortcutId); 2099 } 2100 } 2101 2102 public void replacePinned(@NonNull ShortcutService s, String launcherPackage, 2103 List<String> shortcutIds) { 2104 2105 // TODO Should be per launcherPackage. 2106 2107 // First, un-pin all shortcuts 2108 for (int i = mShortcuts.size() - 1; i >= 0; i--) { 2109 mShortcuts.valueAt(i).clearFlags(ShortcutInfo.FLAG_PINNED); 2110 } 2111 2112 // Then pin ALL 2113 for (int i = shortcutIds.size() - 1; i >= 0; i--) { 2114 final ShortcutInfo shortcut = mShortcuts.get(shortcutIds.get(i)); 2115 if (shortcut != null) { 2116 shortcut.addFlags(ShortcutInfo.FLAG_PINNED); 2117 } 2118 } 2119 2120 removeOrphans(s); 2121 } 2122 2123 /** 2124 * Number of calls that the caller has made, since the last reset. 2125 */ 2126 public int getApiCallCount(@NonNull ShortcutService s) { 2127 final long last = s.getLastResetTimeLocked(); 2128 2129 final long now = s.injectCurrentTimeMillis(); 2130 if (ShortcutService.isClockValid(now) && mLastResetTime > now) { 2131 // Clock rewound. // TODO Test it 2132 mLastResetTime = now; 2133 } 2134 2135 // If not reset yet, then reset. 2136 if (mLastResetTime < last) { 2137 mApiCallCount = 0; 2138 mLastResetTime = last; 2139 } 2140 return mApiCallCount; 2141 } 2142 2143 /** 2144 * If the caller app hasn't been throttled yet, increment {@link #mApiCallCount} 2145 * and return true. Otherwise just return false. 2146 */ 2147 public boolean tryApiCall(@NonNull ShortcutService s) { 2148 if (getApiCallCount(s) >= s.mMaxDailyUpdates) { 2149 return false; 2150 } 2151 mApiCallCount++; 2152 return true; 2153 } 2154 2155 public void resetRateLimitingForCommandLine() { 2156 mApiCallCount = 0; 2157 mLastResetTime = 0; 2158 } 2159 2160 /** 2161 * Find all shortcuts that match {@code query}. 2162 */ 2163 public void findAll(@NonNull List<ShortcutInfo> result, 2164 @Nullable Predicate<ShortcutInfo> query, int cloneFlag) { 2165 for (int i = 0; i < mShortcuts.size(); i++) { 2166 final ShortcutInfo si = mShortcuts.valueAt(i); 2167 if (query == null || query.test(si)) { 2168 result.add(si.clone(cloneFlag)); 2169 } 2170 } 2171 } 2172 2173 public void resetThrottling() { 2174 mApiCallCount = 0; 2175 } 2176 2177 public void dump(@NonNull ShortcutService s, @NonNull PrintWriter pw, @NonNull String prefix) { 2178 pw.print(prefix); 2179 pw.print("Package: "); 2180 pw.print(mPackageName); 2181 pw.println(); 2182 2183 pw.print(prefix); 2184 pw.print(" "); 2185 pw.print("Calls: "); 2186 pw.print(getApiCallCount(s)); 2187 pw.println(); 2188 2189 // This should be after getApiCallCount(), which may update it. 2190 pw.print(prefix); 2191 pw.print(" "); 2192 pw.print("Last reset: ["); 2193 pw.print(mLastResetTime); 2194 pw.print("] "); 2195 pw.print(s.formatTime(mLastResetTime)); 2196 pw.println(); 2197 2198 pw.println(" Shortcuts:"); 2199 long totalBitmapSize = 0; 2200 final ArrayMap<String, ShortcutInfo> shortcuts = mShortcuts; 2201 final int size = shortcuts.size(); 2202 for (int i = 0; i < size; i++) { 2203 final ShortcutInfo si = shortcuts.valueAt(i); 2204 pw.print(" "); 2205 pw.println(si.toInsecureString()); 2206 if (si.getBitmapPath() != null) { 2207 final long len = new File(si.getBitmapPath()).length(); 2208 pw.print(" "); 2209 pw.print("bitmap size="); 2210 pw.println(len); 2211 2212 totalBitmapSize += len; 2213 } 2214 } 2215 pw.print(prefix); 2216 pw.print(" "); 2217 pw.print("Total bitmap size: "); 2218 pw.print(totalBitmapSize); 2219 pw.print(" ("); 2220 pw.print(Formatter.formatFileSize(s.mContext, totalBitmapSize)); 2221 pw.println(")"); 2222 } 2223 2224 public void saveToXml(@NonNull XmlSerializer out) throws IOException, XmlPullParserException { 2225 out.startTag(null, ShortcutService.TAG_PACKAGE); 2226 2227 ShortcutService.writeAttr(out, ShortcutService.ATTR_NAME, mPackageName); 2228 ShortcutService.writeAttr(out, ShortcutService.ATTR_DYNAMIC_COUNT, mDynamicShortcutCount); 2229 ShortcutService.writeAttr(out, ShortcutService.ATTR_CALL_COUNT, mApiCallCount); 2230 ShortcutService.writeAttr(out, ShortcutService.ATTR_LAST_RESET, mLastResetTime); 2231 2232 final int size = mShortcuts.size(); 2233 for (int j = 0; j < size; j++) { 2234 saveShortcut(out, mShortcuts.valueAt(j)); 2235 } 2236 2237 out.endTag(null, ShortcutService.TAG_PACKAGE); 2238 } 2239 2240 private static void saveShortcut(XmlSerializer out, ShortcutInfo si) 2241 throws IOException, XmlPullParserException { 2242 out.startTag(null, ShortcutService.TAG_SHORTCUT); 2243 ShortcutService.writeAttr(out, ShortcutService.ATTR_ID, si.getId()); 2244 // writeAttr(out, "package", si.getPackageName()); // not needed 2245 ShortcutService.writeAttr(out, ShortcutService.ATTR_ACTIVITY, si.getActivityComponent()); 2246 // writeAttr(out, "icon", si.getIcon()); // We don't save it. 2247 ShortcutService.writeAttr(out, ShortcutService.ATTR_TITLE, si.getTitle()); 2248 ShortcutService.writeAttr(out, ShortcutService.ATTR_INTENT, si.getIntentNoExtras()); 2249 ShortcutService.writeAttr(out, ShortcutService.ATTR_WEIGHT, si.getWeight()); 2250 ShortcutService.writeAttr(out, ShortcutService.ATTR_TIMESTAMP, 2251 si.getLastChangedTimestamp()); 2252 ShortcutService.writeAttr(out, ShortcutService.ATTR_FLAGS, si.getFlags()); 2253 ShortcutService.writeAttr(out, ShortcutService.ATTR_ICON_RES, si.getIconResourceId()); 2254 ShortcutService.writeAttr(out, ShortcutService.ATTR_BITMAP_PATH, si.getBitmapPath()); 2255 2256 ShortcutService.writeTagExtra(out, ShortcutService.TAG_INTENT_EXTRAS, 2257 si.getIntentPersistableExtras()); 2258 ShortcutService.writeTagExtra(out, ShortcutService.TAG_EXTRAS, si.getExtras()); 2259 2260 out.endTag(null, ShortcutService.TAG_SHORTCUT); 2261 } 2262 2263 public static PackageShortcuts loadFromXml(XmlPullParser parser, int userId) 2264 throws IOException, XmlPullParserException { 2265 2266 final String packageName = ShortcutService.parseStringAttribute(parser, 2267 ShortcutService.ATTR_NAME); 2268 2269 final PackageShortcuts ret = new PackageShortcuts(userId, packageName); 2270 2271 ret.mDynamicShortcutCount = 2272 ShortcutService.parseIntAttribute(parser, ShortcutService.ATTR_DYNAMIC_COUNT); 2273 ret.mApiCallCount = 2274 ShortcutService.parseIntAttribute(parser, ShortcutService.ATTR_CALL_COUNT); 2275 ret.mLastResetTime = 2276 ShortcutService.parseLongAttribute(parser, ShortcutService.ATTR_LAST_RESET); 2277 2278 final int outerDepth = parser.getDepth(); 2279 int type; 2280 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 2281 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 2282 if (type != XmlPullParser.START_TAG) { 2283 continue; 2284 } 2285 final int depth = parser.getDepth(); 2286 final String tag = parser.getName(); 2287 switch (tag) { 2288 case ShortcutService.TAG_SHORTCUT: 2289 final ShortcutInfo si = parseShortcut(parser, packageName); 2290 2291 // Don't use addShortcut(), we don't need to save the icon. 2292 ret.mShortcuts.put(si.getId(), si); 2293 continue; 2294 } 2295 throw ShortcutService.throwForInvalidTag(depth, tag); 2296 } 2297 return ret; 2298 } 2299 2300 private static ShortcutInfo parseShortcut(XmlPullParser parser, String packageName) 2301 throws IOException, XmlPullParserException { 2302 String id; 2303 ComponentName activityComponent; 2304 // Icon icon; 2305 String title; 2306 Intent intent; 2307 PersistableBundle intentPersistableExtras = null; 2308 int weight; 2309 PersistableBundle extras = null; 2310 long lastChangedTimestamp; 2311 int flags; 2312 int iconRes; 2313 String bitmapPath; 2314 2315 id = ShortcutService.parseStringAttribute(parser, ShortcutService.ATTR_ID); 2316 activityComponent = ShortcutService.parseComponentNameAttribute(parser, 2317 ShortcutService.ATTR_ACTIVITY); 2318 title = ShortcutService.parseStringAttribute(parser, ShortcutService.ATTR_TITLE); 2319 intent = ShortcutService.parseIntentAttribute(parser, ShortcutService.ATTR_INTENT); 2320 weight = (int) ShortcutService.parseLongAttribute(parser, ShortcutService.ATTR_WEIGHT); 2321 lastChangedTimestamp = (int) ShortcutService.parseLongAttribute(parser, 2322 ShortcutService.ATTR_TIMESTAMP); 2323 flags = (int) ShortcutService.parseLongAttribute(parser, ShortcutService.ATTR_FLAGS); 2324 iconRes = (int) ShortcutService.parseLongAttribute(parser, ShortcutService.ATTR_ICON_RES); 2325 bitmapPath = ShortcutService.parseStringAttribute(parser, ShortcutService.ATTR_BITMAP_PATH); 2326 2327 final int outerDepth = parser.getDepth(); 2328 int type; 2329 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 2330 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 2331 if (type != XmlPullParser.START_TAG) { 2332 continue; 2333 } 2334 final int depth = parser.getDepth(); 2335 final String tag = parser.getName(); 2336 if (ShortcutService.DEBUG_LOAD) { 2337 Slog.d(TAG, String.format(" depth=%d type=%d name=%s", 2338 depth, type, tag)); 2339 } 2340 switch (tag) { 2341 case ShortcutService.TAG_INTENT_EXTRAS: 2342 intentPersistableExtras = PersistableBundle.restoreFromXml(parser); 2343 continue; 2344 case ShortcutService.TAG_EXTRAS: 2345 extras = PersistableBundle.restoreFromXml(parser); 2346 continue; 2347 } 2348 throw ShortcutService.throwForInvalidTag(depth, tag); 2349 } 2350 return new ShortcutInfo( 2351 id, packageName, activityComponent, /* icon =*/ null, title, intent, 2352 intentPersistableExtras, weight, extras, lastChangedTimestamp, flags, 2353 iconRes, bitmapPath); 2354 } 2355} 2356