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