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