ShortcutService.java revision 3ff41200470a05c662d636a22b70d20d44a5917a
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 final long token = injectClearCallingIdentity(); 1314 try { 1315 if (!mUserManager.isUserRunning(userId)) { 1316 return; 1317 } 1318 } finally { 1319 injectRestoreCallingIdentity(token); 1320 } 1321 postToHandler(() -> { 1322 final ArrayList<ShortcutChangeListener> copy; 1323 synchronized (mLock) { 1324 copy = new ArrayList<>(mListeners); 1325 } 1326 // Note onShortcutChanged() needs to be called with the system service permissions. 1327 for (int i = copy.size() - 1; i >= 0; i--) { 1328 copy.get(i).onShortcutChanged(packageName, userId); 1329 } 1330 }); 1331 } 1332 1333 /** 1334 * Clean up / validate an incoming shortcut. 1335 * - Make sure all mandatory fields are set. 1336 * - Make sure the intent's extras are persistable, and them to set 1337 * {@link ShortcutInfo#mIntentPersistableExtras}. Also clear its extras. 1338 * - Clear flags. 1339 * 1340 * TODO Detailed unit tests 1341 */ 1342 private void fixUpIncomingShortcutInfo(@NonNull ShortcutInfo shortcut, boolean forUpdate) { 1343 Preconditions.checkNotNull(shortcut, "Null shortcut detected"); 1344 if (shortcut.getActivityComponent() != null) { 1345 Preconditions.checkState( 1346 shortcut.getPackageName().equals( 1347 shortcut.getActivityComponent().getPackageName()), 1348 "Activity package name mismatch"); 1349 } 1350 1351 if (!forUpdate) { 1352 shortcut.enforceMandatoryFields(); 1353 } 1354 if (shortcut.getIcon() != null) { 1355 ShortcutInfo.validateIcon(shortcut.getIcon()); 1356 } 1357 1358 validateForXml(shortcut.getId()); 1359 validateForXml(shortcut.getTitle()); 1360 validatePersistableBundleForXml(shortcut.getIntentPersistableExtras()); 1361 validatePersistableBundleForXml(shortcut.getExtras()); 1362 1363 shortcut.replaceFlags(0); 1364 } 1365 1366 // KXmlSerializer is strict and doesn't allow certain characters, so we disallow those 1367 // characters. 1368 1369 private static void validatePersistableBundleForXml(PersistableBundle b) { 1370 if (b == null || b.size() == 0) { 1371 return; 1372 } 1373 for (String key : b.keySet()) { 1374 validateForXml(key); 1375 final Object value = b.get(key); 1376 if (value == null) { 1377 continue; 1378 } else if (value instanceof String) { 1379 validateForXml((String) value); 1380 } else if (value instanceof String[]) { 1381 for (String v : (String[]) value) { 1382 validateForXml(v); 1383 } 1384 } else if (value instanceof PersistableBundle) { 1385 validatePersistableBundleForXml((PersistableBundle) value); 1386 } 1387 } 1388 } 1389 1390 private static void validateForXml(String s) { 1391 if (TextUtils.isEmpty(s)) { 1392 return; 1393 } 1394 for (int i = s.length() - 1; i >= 0; i--) { 1395 if (!isAllowedInXml(s.charAt(i))) { 1396 throw new IllegalArgumentException("Unsupported character detected in: " + s); 1397 } 1398 } 1399 } 1400 1401 private static boolean isAllowedInXml(char c) { 1402 return (c >= 0x20 && c <= 0xd7ff) || (c >= 0xe000 && c <= 0xfffd); 1403 } 1404 1405 // === APIs === 1406 1407 @Override 1408 public boolean setDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList, 1409 @UserIdInt int userId) { 1410 verifyCaller(packageName, userId); 1411 1412 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList(); 1413 final int size = newShortcuts.size(); 1414 1415 synchronized (mLock) { 1416 final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId); 1417 1418 // Throttling. 1419 if (!ps.tryApiCall(this)) { 1420 return false; 1421 } 1422 enforceMaxDynamicShortcuts(size); 1423 1424 // Validate the shortcuts. 1425 for (int i = 0; i < size; i++) { 1426 fixUpIncomingShortcutInfo(newShortcuts.get(i), /* forUpdate= */ false); 1427 } 1428 1429 // First, remove all un-pinned; dynamic shortcuts 1430 ps.deleteAllDynamicShortcuts(this); 1431 1432 // Then, add/update all. We need to make sure to take over "pinned" flag. 1433 for (int i = 0; i < size; i++) { 1434 final ShortcutInfo newShortcut = newShortcuts.get(i); 1435 ps.addDynamicShortcut(this, newShortcut); 1436 } 1437 } 1438 packageShortcutsChanged(packageName, userId); 1439 return true; 1440 } 1441 1442 @Override 1443 public boolean updateShortcuts(String packageName, ParceledListSlice shortcutInfoList, 1444 @UserIdInt int userId) { 1445 verifyCaller(packageName, userId); 1446 1447 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList(); 1448 final int size = newShortcuts.size(); 1449 1450 synchronized (mLock) { 1451 final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId); 1452 1453 // Throttling. 1454 if (!ps.tryApiCall(this)) { 1455 return false; 1456 } 1457 1458 for (int i = 0; i < size; i++) { 1459 final ShortcutInfo source = newShortcuts.get(i); 1460 fixUpIncomingShortcutInfo(source, /* forUpdate= */ true); 1461 1462 final ShortcutInfo target = ps.findShortcutById(source.getId()); 1463 if (target != null) { 1464 final boolean replacingIcon = (source.getIcon() != null); 1465 if (replacingIcon) { 1466 removeIcon(userId, target); 1467 } 1468 1469 target.copyNonNullFieldsFrom(source); 1470 1471 if (replacingIcon) { 1472 saveIconAndFixUpShortcut(userId, target); 1473 } 1474 } 1475 } 1476 } 1477 packageShortcutsChanged(packageName, userId); 1478 1479 return true; 1480 } 1481 1482 @Override 1483 public boolean addDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList, 1484 @UserIdInt int userId) { 1485 verifyCaller(packageName, userId); 1486 1487 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList(); 1488 final int size = newShortcuts.size(); 1489 1490 synchronized (mLock) { 1491 final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId); 1492 1493 // Throttling. 1494 if (!ps.tryApiCall(this)) { 1495 return false; 1496 } 1497 for (int i = 0; i < size; i++) { 1498 final ShortcutInfo newShortcut = newShortcuts.get(i); 1499 1500 // Validate the shortcut. 1501 fixUpIncomingShortcutInfo(newShortcut, /* forUpdate= */ false); 1502 1503 // Add it. 1504 ps.addDynamicShortcut(this, newShortcut); 1505 } 1506 } 1507 packageShortcutsChanged(packageName, userId); 1508 1509 return true; 1510 } 1511 1512 @Override 1513 public void removeDynamicShortcuts(String packageName, List shortcutIds, 1514 @UserIdInt int userId) { 1515 verifyCaller(packageName, userId); 1516 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided"); 1517 1518 synchronized (mLock) { 1519 for (int i = shortcutIds.size() - 1; i >= 0; i--) { 1520 getPackageShortcutsLocked(packageName, userId).deleteDynamicWithId(this, 1521 Preconditions.checkStringNotEmpty((String) shortcutIds.get(i))); 1522 } 1523 } 1524 packageShortcutsChanged(packageName, userId); 1525 } 1526 1527 @Override 1528 public void removeAllDynamicShortcuts(String packageName, @UserIdInt int userId) { 1529 verifyCaller(packageName, userId); 1530 1531 synchronized (mLock) { 1532 getPackageShortcutsLocked(packageName, userId).deleteAllDynamicShortcuts(this); 1533 } 1534 packageShortcutsChanged(packageName, userId); 1535 } 1536 1537 @Override 1538 public ParceledListSlice<ShortcutInfo> getDynamicShortcuts(String packageName, 1539 @UserIdInt int userId) { 1540 verifyCaller(packageName, userId); 1541 synchronized (mLock) { 1542 return getShortcutsWithQueryLocked( 1543 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR, 1544 ShortcutInfo::isDynamic); 1545 } 1546 } 1547 1548 @Override 1549 public ParceledListSlice<ShortcutInfo> getPinnedShortcuts(String packageName, 1550 @UserIdInt int userId) { 1551 verifyCaller(packageName, userId); 1552 synchronized (mLock) { 1553 return getShortcutsWithQueryLocked( 1554 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR, 1555 ShortcutInfo::isPinned); 1556 } 1557 } 1558 1559 private ParceledListSlice<ShortcutInfo> getShortcutsWithQueryLocked(@NonNull String packageName, 1560 @UserIdInt int userId, int cloneFlags, @NonNull Predicate<ShortcutInfo> query) { 1561 1562 final ArrayList<ShortcutInfo> ret = new ArrayList<>(); 1563 1564 getPackageShortcutsLocked(packageName, userId).findAll(this, ret, query, cloneFlags); 1565 1566 return new ParceledListSlice<>(ret); 1567 } 1568 1569 @Override 1570 public int getMaxDynamicShortcutCount(String packageName, @UserIdInt int userId) 1571 throws RemoteException { 1572 verifyCaller(packageName, userId); 1573 1574 return mMaxDynamicShortcuts; 1575 } 1576 1577 @Override 1578 public int getRemainingCallCount(String packageName, @UserIdInt int userId) { 1579 verifyCaller(packageName, userId); 1580 1581 synchronized (mLock) { 1582 return mMaxUpdatesPerInterval 1583 - getPackageShortcutsLocked(packageName, userId).getApiCallCount(this); 1584 } 1585 } 1586 1587 @Override 1588 public long getRateLimitResetTime(String packageName, @UserIdInt int userId) { 1589 verifyCaller(packageName, userId); 1590 1591 synchronized (mLock) { 1592 return getNextResetTimeLocked(); 1593 } 1594 } 1595 1596 @Override 1597 public int getIconMaxDimensions(String packageName, int userId) throws RemoteException { 1598 verifyCaller(packageName, userId); 1599 1600 synchronized (mLock) { 1601 return mMaxIconDimension; 1602 } 1603 } 1604 1605 /** 1606 * Reset all throttling, for developer options and command line. Only system/shell can call it. 1607 */ 1608 @Override 1609 public void resetThrottling() { 1610 enforceSystemOrShell(); 1611 1612 resetThrottlingInner(getCallingUserId()); 1613 } 1614 1615 void resetThrottlingInner(@UserIdInt int userId) { 1616 synchronized (mLock) { 1617 getUserShortcutsLocked(userId).resetThrottling(); 1618 } 1619 scheduleSaveUser(userId); 1620 Slog.i(TAG, "ShortcutManager: throttling counter reset for user " + userId); 1621 } 1622 1623 void resetAllThrottlingInner() { 1624 synchronized (mLock) { 1625 mRawLastResetTime = injectCurrentTimeMillis(); 1626 } 1627 scheduleSaveBaseState(); 1628 Slog.i(TAG, "ShortcutManager: throttling counter reset for all users"); 1629 } 1630 1631 void resetPackageThrottling(String packageName, int userId) { 1632 synchronized (mLock) { 1633 getPackageShortcutsLocked(packageName, userId) 1634 .resetRateLimitingForCommandLineNoSaving(); 1635 saveUserLocked(userId); 1636 } 1637 } 1638 1639 @Override 1640 public void onApplicationActive(String packageName, int userId) { 1641 if (DEBUG) { 1642 Slog.d(TAG, "onApplicationActive: package=" + packageName + " userid=" + userId); 1643 } 1644 enforceResetThrottlingPermission(); 1645 resetPackageThrottling(packageName, userId); 1646 } 1647 1648 // We override this method in unit tests to do a simpler check. 1649 boolean hasShortcutHostPermission(@NonNull String callingPackage, int userId) { 1650 return hasShortcutHostPermissionInner(callingPackage, userId); 1651 } 1652 1653 // This method is extracted so we can directly call this method from unit tests, 1654 // even when hasShortcutPermission() is overridden. 1655 @VisibleForTesting 1656 boolean hasShortcutHostPermissionInner(@NonNull String callingPackage, int userId) { 1657 synchronized (mLock) { 1658 final long start = injectElapsedRealtime(); 1659 1660 final ShortcutUser user = getUserShortcutsLocked(userId); 1661 1662 final List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 1663 1664 // Default launcher from package manager. 1665 final long startGetHomeActivitiesAsUser = injectElapsedRealtime(); 1666 final ComponentName defaultLauncher = injectPackageManagerInternal() 1667 .getHomeActivitiesAsUser(allHomeCandidates, userId); 1668 logDurationStat(Stats.GET_DEFAULT_HOME, startGetHomeActivitiesAsUser); 1669 1670 ComponentName detected; 1671 if (defaultLauncher != null) { 1672 detected = defaultLauncher; 1673 if (DEBUG) { 1674 Slog.v(TAG, "Default launcher from PM: " + detected); 1675 } 1676 } else { 1677 detected = user.getLauncherComponent(); 1678 1679 // TODO: Make sure it's still enabled. 1680 if (DEBUG) { 1681 Slog.v(TAG, "Cached launcher: " + detected); 1682 } 1683 } 1684 1685 if (detected == null) { 1686 // If we reach here, that means it's the first check since the user was created, 1687 // and there's already multiple launchers and there's no default set. 1688 // Find the system one with the highest priority. 1689 // (We need to check the priority too because of FallbackHome in Settings.) 1690 // If there's no system launcher yet, then no one can access shortcuts, until 1691 // the user explicitly 1692 final int size = allHomeCandidates.size(); 1693 1694 int lastPriority = Integer.MIN_VALUE; 1695 for (int i = 0; i < size; i++) { 1696 final ResolveInfo ri = allHomeCandidates.get(i); 1697 if (!ri.activityInfo.applicationInfo.isSystemApp()) { 1698 continue; 1699 } 1700 if (DEBUG) { 1701 Slog.d(TAG, String.format("hasShortcutPermissionInner: pkg=%s prio=%d", 1702 ri.activityInfo.getComponentName(), ri.priority)); 1703 } 1704 if (ri.priority < lastPriority) { 1705 continue; 1706 } 1707 detected = ri.activityInfo.getComponentName(); 1708 lastPriority = ri.priority; 1709 } 1710 } 1711 logDurationStat(Stats.LAUNCHER_PERMISSION_CHECK, start); 1712 1713 if (detected != null) { 1714 if (DEBUG) { 1715 Slog.v(TAG, "Detected launcher: " + detected); 1716 } 1717 user.setLauncherComponent(this, detected); 1718 return detected.getPackageName().equals(callingPackage); 1719 } else { 1720 // Default launcher not found. 1721 return false; 1722 } 1723 } 1724 } 1725 1726 // === House keeping === 1727 1728 private void cleanUpPackageForAllLoadedUsers(String packageName, @UserIdInt int packageUserId) { 1729 synchronized (mLock) { 1730 forEachLoadedUserLocked(user -> 1731 cleanUpPackageLocked(packageName, user.getUserId(), packageUserId)); 1732 } 1733 } 1734 1735 /** 1736 * Remove all the information associated with a package. This will really remove all the 1737 * information, including the restore information (i.e. it'll remove packages even if they're 1738 * shadow). 1739 * 1740 * This is called when an app is uninstalled, or an app gets "clear data"ed. 1741 */ 1742 @VisibleForTesting 1743 void cleanUpPackageLocked(String packageName, int owningUserId, int packageUserId) { 1744 final boolean wasUserLoaded = isUserLoadedLocked(owningUserId); 1745 1746 final ShortcutUser user = getUserShortcutsLocked(owningUserId); 1747 boolean doNotify = false; 1748 1749 // First, remove the package from the package list (if the package is a publisher). 1750 if (packageUserId == owningUserId) { 1751 if (user.removePackage(this, packageName) != null) { 1752 doNotify = true; 1753 } 1754 } 1755 1756 // Also remove from the launcher list (if the package is a launcher). 1757 user.removeLauncher(packageUserId, packageName); 1758 1759 // Then remove pinned shortcuts from all launchers. 1760 user.forAllLaunchers(l -> l.cleanUpPackage(packageName, packageUserId)); 1761 1762 // Now there may be orphan shortcuts because we removed pinned shortcuts at the previous 1763 // step. Remove them too. 1764 user.forAllPackages(p -> p.refreshPinnedFlags(this)); 1765 1766 scheduleSaveUser(owningUserId); 1767 1768 if (doNotify) { 1769 notifyListeners(packageName, owningUserId); 1770 } 1771 1772 if (!wasUserLoaded) { 1773 // Note this will execute the scheduled save. 1774 unloadUserLocked(owningUserId); 1775 } 1776 } 1777 1778 /** 1779 * Entry point from {@link LauncherApps}. 1780 */ 1781 private class LocalService extends ShortcutServiceInternal { 1782 1783 @Override 1784 public List<ShortcutInfo> getShortcuts(int launcherUserId, 1785 @NonNull String callingPackage, long changedSince, 1786 @Nullable String packageName, @Nullable List<String> shortcutIds, 1787 @Nullable ComponentName componentName, 1788 int queryFlags, int userId) { 1789 final ArrayList<ShortcutInfo> ret = new ArrayList<>(); 1790 final int cloneFlag = 1791 ((queryFlags & ShortcutQuery.FLAG_GET_KEY_FIELDS_ONLY) == 0) 1792 ? ShortcutInfo.CLONE_REMOVE_FOR_LAUNCHER 1793 : ShortcutInfo.CLONE_REMOVE_NON_KEY_INFO; 1794 if (packageName == null) { 1795 shortcutIds = null; // LauncherAppsService already threw for it though. 1796 } 1797 1798 synchronized (mLock) { 1799 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId) 1800 .attemptToRestoreIfNeededAndSave(ShortcutService.this); 1801 1802 if (packageName != null) { 1803 getShortcutsInnerLocked(launcherUserId, 1804 callingPackage, packageName, shortcutIds, changedSince, 1805 componentName, queryFlags, userId, ret, cloneFlag); 1806 } else { 1807 final List<String> shortcutIdsF = shortcutIds; 1808 getUserShortcutsLocked(userId).forAllPackages(p -> { 1809 getShortcutsInnerLocked(launcherUserId, 1810 callingPackage, p.getPackageName(), shortcutIdsF, changedSince, 1811 componentName, queryFlags, userId, ret, cloneFlag); 1812 }); 1813 } 1814 } 1815 return ret; 1816 } 1817 1818 private void getShortcutsInnerLocked(int launcherUserId, @NonNull String callingPackage, 1819 @Nullable String packageName, @Nullable List<String> shortcutIds, long changedSince, 1820 @Nullable ComponentName componentName, int queryFlags, 1821 int userId, ArrayList<ShortcutInfo> ret, int cloneFlag) { 1822 final ArraySet<String> ids = shortcutIds == null ? null 1823 : new ArraySet<>(shortcutIds); 1824 1825 getPackageShortcutsLocked(packageName, userId).findAll(ShortcutService.this, ret, 1826 (ShortcutInfo si) -> { 1827 if (si.getLastChangedTimestamp() < changedSince) { 1828 return false; 1829 } 1830 if (ids != null && !ids.contains(si.getId())) { 1831 return false; 1832 } 1833 if (componentName != null) { 1834 if (si.getActivityComponent() != null 1835 && !si.getActivityComponent().equals(componentName)) { 1836 return false; 1837 } 1838 } 1839 final boolean matchDynamic = 1840 ((queryFlags & ShortcutQuery.FLAG_GET_DYNAMIC) != 0) 1841 && si.isDynamic(); 1842 final boolean matchPinned = 1843 ((queryFlags & ShortcutQuery.FLAG_GET_PINNED) != 0) 1844 && si.isPinned(); 1845 return matchDynamic || matchPinned; 1846 }, cloneFlag, callingPackage, launcherUserId); 1847 } 1848 1849 @Override 1850 public boolean isPinnedByCaller(int launcherUserId, @NonNull String callingPackage, 1851 @NonNull String packageName, @NonNull String shortcutId, int userId) { 1852 Preconditions.checkStringNotEmpty(packageName, "packageName"); 1853 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId"); 1854 1855 synchronized (mLock) { 1856 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId) 1857 .attemptToRestoreIfNeededAndSave(ShortcutService.this); 1858 1859 final ShortcutInfo si = getShortcutInfoLocked( 1860 launcherUserId, callingPackage, packageName, shortcutId, userId); 1861 return si != null && si.isPinned(); 1862 } 1863 } 1864 1865 private ShortcutInfo getShortcutInfoLocked( 1866 int launcherUserId, @NonNull String callingPackage, 1867 @NonNull String packageName, @NonNull String shortcutId, int userId) { 1868 Preconditions.checkStringNotEmpty(packageName, "packageName"); 1869 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId"); 1870 1871 final ArrayList<ShortcutInfo> list = new ArrayList<>(1); 1872 getPackageShortcutsLocked(packageName, userId).findAll( 1873 ShortcutService.this, list, 1874 (ShortcutInfo si) -> shortcutId.equals(si.getId()), 1875 /* clone flags=*/ 0, callingPackage, launcherUserId); 1876 return list.size() == 0 ? null : list.get(0); 1877 } 1878 1879 @Override 1880 public void pinShortcuts(int launcherUserId, 1881 @NonNull String callingPackage, @NonNull String packageName, 1882 @NonNull List<String> shortcutIds, int userId) { 1883 // Calling permission must be checked by LauncherAppsImpl. 1884 Preconditions.checkStringNotEmpty(packageName, "packageName"); 1885 Preconditions.checkNotNull(shortcutIds, "shortcutIds"); 1886 1887 synchronized (mLock) { 1888 final ShortcutLauncher launcher = 1889 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId); 1890 launcher.attemptToRestoreIfNeededAndSave(ShortcutService.this); 1891 1892 launcher.pinShortcuts( 1893 ShortcutService.this, userId, packageName, shortcutIds); 1894 } 1895 packageShortcutsChanged(packageName, userId); 1896 } 1897 1898 @Override 1899 public Intent createShortcutIntent(int launcherUserId, 1900 @NonNull String callingPackage, 1901 @NonNull String packageName, @NonNull String shortcutId, int userId) { 1902 // Calling permission must be checked by LauncherAppsImpl. 1903 Preconditions.checkStringNotEmpty(packageName, "packageName can't be empty"); 1904 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId can't be empty"); 1905 1906 synchronized (mLock) { 1907 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId) 1908 .attemptToRestoreIfNeededAndSave(ShortcutService.this); 1909 1910 // Make sure the shortcut is actually visible to the launcher. 1911 final ShortcutInfo si = getShortcutInfoLocked( 1912 launcherUserId, callingPackage, packageName, shortcutId, userId); 1913 // "si == null" should suffice here, but check the flags too just to make sure. 1914 if (si == null || !(si.isDynamic() || si.isPinned())) { 1915 return null; 1916 } 1917 return si.getIntent(); 1918 } 1919 } 1920 1921 @Override 1922 public void addListener(@NonNull ShortcutChangeListener listener) { 1923 synchronized (mLock) { 1924 mListeners.add(Preconditions.checkNotNull(listener)); 1925 } 1926 } 1927 1928 @Override 1929 public int getShortcutIconResId(int launcherUserId, @NonNull String callingPackage, 1930 @NonNull String packageName, @NonNull String shortcutId, int userId) { 1931 Preconditions.checkNotNull(callingPackage, "callingPackage"); 1932 Preconditions.checkNotNull(packageName, "packageName"); 1933 Preconditions.checkNotNull(shortcutId, "shortcutId"); 1934 1935 synchronized (mLock) { 1936 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId) 1937 .attemptToRestoreIfNeededAndSave(ShortcutService.this); 1938 1939 final ShortcutInfo shortcutInfo = getPackageShortcutsLocked( 1940 packageName, userId).findShortcutById(shortcutId); 1941 return (shortcutInfo != null && shortcutInfo.hasIconResource()) 1942 ? shortcutInfo.getIconResourceId() : 0; 1943 } 1944 } 1945 1946 @Override 1947 public ParcelFileDescriptor getShortcutIconFd(int launcherUserId, 1948 @NonNull String callingPackage, @NonNull String packageName, 1949 @NonNull String shortcutId, int userId) { 1950 Preconditions.checkNotNull(callingPackage, "callingPackage"); 1951 Preconditions.checkNotNull(packageName, "packageName"); 1952 Preconditions.checkNotNull(shortcutId, "shortcutId"); 1953 1954 synchronized (mLock) { 1955 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId) 1956 .attemptToRestoreIfNeededAndSave(ShortcutService.this); 1957 1958 final ShortcutInfo shortcutInfo = getPackageShortcutsLocked( 1959 packageName, userId).findShortcutById(shortcutId); 1960 if (shortcutInfo == null || !shortcutInfo.hasIconFile()) { 1961 return null; 1962 } 1963 try { 1964 if (shortcutInfo.getBitmapPath() == null) { 1965 Slog.w(TAG, "null bitmap detected in getShortcutIconFd()"); 1966 return null; 1967 } 1968 return ParcelFileDescriptor.open( 1969 new File(shortcutInfo.getBitmapPath()), 1970 ParcelFileDescriptor.MODE_READ_ONLY); 1971 } catch (FileNotFoundException e) { 1972 Slog.e(TAG, "Icon file not found: " + shortcutInfo.getBitmapPath()); 1973 return null; 1974 } 1975 } 1976 } 1977 1978 @Override 1979 public boolean hasShortcutHostPermission(int launcherUserId, 1980 @NonNull String callingPackage) { 1981 return ShortcutService.this.hasShortcutHostPermission(callingPackage, launcherUserId); 1982 } 1983 1984 /** 1985 * Called by AM when the system locale changes *within the AM lock. ABSOLUTELY do not take 1986 * any locks in this method. 1987 */ 1988 @Override 1989 public void onSystemLocaleChangedNoLock() { 1990 // DO NOT HOLD ANY LOCKS HERE. 1991 1992 // We want to reset throttling for all packages for all users. But we can't just do so 1993 // here because: 1994 // - We can't load/save users that are locked. 1995 // - Even for loaded users, resetting the counters would require us to hold mLock. 1996 // 1997 // So we use a "pull" model instead. In here, we just increment the "locale change 1998 // sequence number". Each ShortcutUser has the "last known locale change sequence". 1999 // 2000 // This allows ShortcutUser's to detect the system locale change, so they can reset 2001 // counters. 2002 2003 mLocaleChangeSequenceNumber.incrementAndGet(); 2004 postToHandler(() -> scheduleSaveBaseState()); 2005 } 2006 } 2007 2008 /** 2009 * Package event callbacks. 2010 */ 2011 @VisibleForTesting 2012 final PackageMonitor mPackageMonitor = new PackageMonitor() { 2013 @Override 2014 public void onPackageAdded(String packageName, int uid) { 2015 handlePackageAdded(packageName, getChangingUserId()); 2016 } 2017 2018 @Override 2019 public void onPackageUpdateFinished(String packageName, int uid) { 2020 handlePackageUpdateFinished(packageName, getChangingUserId()); 2021 } 2022 2023 @Override 2024 public void onPackageRemoved(String packageName, int uid) { 2025 handlePackageRemoved(packageName, getChangingUserId()); 2026 } 2027 2028 @Override 2029 public void onPackageDataCleared(String packageName, int uid) { 2030 handlePackageDataCleared(packageName, getChangingUserId()); 2031 } 2032 }; 2033 2034 /** 2035 * Called when a user is unlocked. 2036 * - Check all known packages still exist, and otherwise perform cleanup. 2037 * - If a package still exists, check the version code. If it's been updated, may need to 2038 * update timestamps of its shortcuts. 2039 */ 2040 @VisibleForTesting 2041 void checkPackageChanges(@UserIdInt int ownerUserId) { 2042 if (DEBUG) { 2043 Slog.d(TAG, "checkPackageChanges() ownerUserId=" + ownerUserId); 2044 } 2045 final ArrayList<PackageWithUser> gonePackages = new ArrayList<>(); 2046 2047 synchronized (mLock) { 2048 final ShortcutUser user = getUserShortcutsLocked(ownerUserId); 2049 2050 user.forAllPackageItems(spi -> { 2051 if (spi.getPackageInfo().isShadow()) { 2052 return; // Don't delete shadow information. 2053 } 2054 final int versionCode = getApplicationVersionCode( 2055 spi.getPackageName(), spi.getPackageUserId()); 2056 if (versionCode >= 0) { 2057 // Package still installed, see if it's updated. 2058 getUserShortcutsLocked(ownerUserId).handlePackageUpdated( 2059 this, spi.getPackageName(), versionCode); 2060 } else { 2061 gonePackages.add(PackageWithUser.of(spi)); 2062 } 2063 }); 2064 if (gonePackages.size() > 0) { 2065 for (int i = gonePackages.size() - 1; i >= 0; i--) { 2066 final PackageWithUser pu = gonePackages.get(i); 2067 cleanUpPackageLocked(pu.packageName, ownerUserId, pu.userId); 2068 } 2069 } 2070 } 2071 } 2072 2073 private void handlePackageAdded(String packageName, @UserIdInt int userId) { 2074 if (DEBUG) { 2075 Slog.d(TAG, String.format("handlePackageAdded: %s user=%d", packageName, userId)); 2076 } 2077 synchronized (mLock) { 2078 forEachLoadedUserLocked(user -> 2079 user.attemptToRestoreIfNeededAndSave(this, packageName, userId)); 2080 } 2081 } 2082 2083 private void handlePackageUpdateFinished(String packageName, @UserIdInt int userId) { 2084 if (DEBUG) { 2085 Slog.d(TAG, String.format("handlePackageUpdateFinished: %s user=%d", 2086 packageName, userId)); 2087 } 2088 synchronized (mLock) { 2089 forEachLoadedUserLocked(user -> 2090 user.attemptToRestoreIfNeededAndSave(this, packageName, userId)); 2091 2092 final int versionCode = getApplicationVersionCode(packageName, userId); 2093 if (versionCode < 0) { 2094 return; // shouldn't happen 2095 } 2096 getUserShortcutsLocked(userId).handlePackageUpdated(this, packageName, versionCode); 2097 } 2098 } 2099 2100 private void handlePackageRemoved(String packageName, @UserIdInt int packageUserId) { 2101 if (DEBUG) { 2102 Slog.d(TAG, String.format("handlePackageRemoved: %s user=%d", packageName, 2103 packageUserId)); 2104 } 2105 cleanUpPackageForAllLoadedUsers(packageName, packageUserId); 2106 } 2107 2108 private void handlePackageDataCleared(String packageName, int packageUserId) { 2109 if (DEBUG) { 2110 Slog.d(TAG, String.format("handlePackageDataCleared: %s user=%d", packageName, 2111 packageUserId)); 2112 } 2113 cleanUpPackageForAllLoadedUsers(packageName, packageUserId); 2114 } 2115 2116 // === PackageManager interaction === 2117 2118 PackageInfo getPackageInfoWithSignatures(String packageName, @UserIdInt int userId) { 2119 return injectPackageInfo(packageName, userId, true); 2120 } 2121 2122 int injectGetPackageUid(@NonNull String packageName, @UserIdInt int userId) { 2123 final long token = injectClearCallingIdentity(); 2124 try { 2125 return mIPackageManager.getPackageUid(packageName, PACKAGE_MATCH_FLAGS 2126 , userId); 2127 } catch (RemoteException e) { 2128 // Shouldn't happen. 2129 Slog.wtf(TAG, "RemoteException", e); 2130 return -1; 2131 } finally { 2132 injectRestoreCallingIdentity(token); 2133 } 2134 } 2135 2136 @VisibleForTesting 2137 PackageInfo injectPackageInfo(String packageName, @UserIdInt int userId, 2138 boolean getSignatures) { 2139 final long start = injectElapsedRealtime(); 2140 final long token = injectClearCallingIdentity(); 2141 try { 2142 return mIPackageManager.getPackageInfo(packageName, PACKAGE_MATCH_FLAGS 2143 | (getSignatures ? PackageManager.GET_SIGNATURES : 0) 2144 , userId); 2145 } catch (RemoteException e) { 2146 // Shouldn't happen. 2147 Slog.wtf(TAG, "RemoteException", e); 2148 return null; 2149 } finally { 2150 injectRestoreCallingIdentity(token); 2151 2152 logDurationStat( 2153 (getSignatures ? Stats.GET_PACKAGE_INFO_WITH_SIG : Stats.GET_PACKAGE_INFO), 2154 start); 2155 } 2156 } 2157 2158 @VisibleForTesting 2159 ApplicationInfo injectApplicationInfo(String packageName, @UserIdInt int userId) { 2160 final long start = injectElapsedRealtime(); 2161 final long token = injectClearCallingIdentity(); 2162 try { 2163 return mIPackageManager.getApplicationInfo(packageName, PACKAGE_MATCH_FLAGS, userId); 2164 } catch (RemoteException e) { 2165 // Shouldn't happen. 2166 Slog.wtf(TAG, "RemoteException", e); 2167 return null; 2168 } finally { 2169 injectRestoreCallingIdentity(token); 2170 2171 logDurationStat(Stats.GET_APPLICATION_INFO, start); 2172 } 2173 } 2174 2175 private boolean isApplicationFlagSet(String packageName, int userId, int flags) { 2176 final ApplicationInfo ai = injectApplicationInfo(packageName, userId); 2177 return (ai != null) && ((ai.flags & flags) == flags); 2178 } 2179 2180 boolean isPackageInstalled(String packageName, int userId) { 2181 return isApplicationFlagSet(packageName, userId, ApplicationInfo.FLAG_INSTALLED); 2182 } 2183 2184 /** 2185 * @return the version code of the package, or -1 if the app is not installed. 2186 */ 2187 int getApplicationVersionCode(String packageName, int userId) { 2188 final ApplicationInfo ai = injectApplicationInfo(packageName, userId); 2189 if ((ai == null) || ((ai.flags & ApplicationInfo.FLAG_INSTALLED) == 0)) { 2190 return -1; 2191 } 2192 return ai.versionCode; 2193 } 2194 2195 // === Backup & restore === 2196 2197 boolean shouldBackupApp(String packageName, int userId) { 2198 return isApplicationFlagSet(packageName, userId, ApplicationInfo.FLAG_ALLOW_BACKUP); 2199 } 2200 2201 boolean shouldBackupApp(PackageInfo pi) { 2202 return (pi.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0; 2203 } 2204 2205 @Override 2206 public byte[] getBackupPayload(@UserIdInt int userId) { 2207 enforceSystem(); 2208 if (DEBUG) { 2209 Slog.d(TAG, "Backing up user " + userId); 2210 } 2211 synchronized (mLock) { 2212 final ShortcutUser user = getUserShortcutsLocked(userId); 2213 if (user == null) { 2214 Slog.w(TAG, "Can't backup: user not found: id=" + userId); 2215 return null; 2216 } 2217 2218 user.forAllPackageItems(spi -> spi.refreshPackageInfoAndSave(this)); 2219 2220 // Then save. 2221 final ByteArrayOutputStream os = new ByteArrayOutputStream(32 * 1024); 2222 try { 2223 saveUserInternalLocked(userId, os, /* forBackup */ true); 2224 } catch (XmlPullParserException|IOException e) { 2225 // Shouldn't happen. 2226 Slog.w(TAG, "Backup failed.", e); 2227 return null; 2228 } 2229 return os.toByteArray(); 2230 } 2231 } 2232 2233 @Override 2234 public void applyRestore(byte[] payload, @UserIdInt int userId) { 2235 enforceSystem(); 2236 if (DEBUG) { 2237 Slog.d(TAG, "Restoring user " + userId); 2238 } 2239 final ShortcutUser user; 2240 final ByteArrayInputStream is = new ByteArrayInputStream(payload); 2241 try { 2242 user = loadUserInternal(userId, is, /* fromBackup */ true); 2243 } catch (XmlPullParserException|IOException e) { 2244 Slog.w(TAG, "Restoration failed.", e); 2245 return; 2246 } 2247 synchronized (mLock) { 2248 mUsers.put(userId, user); 2249 2250 // Then purge all the save images. 2251 final File bitmapPath = getUserBitmapFilePath(userId); 2252 final boolean success = FileUtils.deleteContents(bitmapPath); 2253 if (!success) { 2254 Slog.w(TAG, "Failed to delete " + bitmapPath); 2255 } 2256 2257 saveUserLocked(userId); 2258 } 2259 } 2260 2261 // === Dump === 2262 2263 @Override 2264 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 2265 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 2266 != PackageManager.PERMISSION_GRANTED) { 2267 pw.println("Permission Denial: can't dump UserManager from from pid=" 2268 + Binder.getCallingPid() 2269 + ", uid=" + Binder.getCallingUid() 2270 + " without permission " 2271 + android.Manifest.permission.DUMP); 2272 return; 2273 } 2274 dumpInner(pw, args); 2275 } 2276 2277 @VisibleForTesting 2278 void dumpInner(PrintWriter pw, String[] args) { 2279 synchronized (mLock) { 2280 final long now = injectCurrentTimeMillis(); 2281 pw.print("Now: ["); 2282 pw.print(now); 2283 pw.print("] "); 2284 pw.print(formatTime(now)); 2285 2286 pw.print(" Raw last reset: ["); 2287 pw.print(mRawLastResetTime); 2288 pw.print("] "); 2289 pw.print(formatTime(mRawLastResetTime)); 2290 2291 final long last = getLastResetTimeLocked(); 2292 pw.print(" Last reset: ["); 2293 pw.print(last); 2294 pw.print("] "); 2295 pw.print(formatTime(last)); 2296 2297 final long next = getNextResetTimeLocked(); 2298 pw.print(" Next reset: ["); 2299 pw.print(next); 2300 pw.print("] "); 2301 pw.print(formatTime(next)); 2302 2303 pw.print(" Locale change seq#: "); 2304 pw.print(mLocaleChangeSequenceNumber.get()); 2305 pw.println(); 2306 2307 pw.print(" Config:"); 2308 pw.print(" Max icon dim: "); 2309 pw.println(mMaxIconDimension); 2310 pw.print(" Icon format: "); 2311 pw.println(mIconPersistFormat); 2312 pw.print(" Icon quality: "); 2313 pw.println(mIconPersistQuality); 2314 pw.print(" saveDelayMillis: "); 2315 pw.println(mSaveDelayMillis); 2316 pw.print(" resetInterval: "); 2317 pw.println(mResetInterval); 2318 pw.print(" maxUpdatesPerInterval: "); 2319 pw.println(mMaxUpdatesPerInterval); 2320 pw.print(" maxDynamicShortcuts: "); 2321 pw.println(mMaxDynamicShortcuts); 2322 pw.println(); 2323 2324 pw.println(" Stats:"); 2325 synchronized (mStatLock) { 2326 final String p = " "; 2327 dumpStatLS(pw, p, Stats.GET_DEFAULT_HOME, "getHomeActivities()"); 2328 dumpStatLS(pw, p, Stats.LAUNCHER_PERMISSION_CHECK, "Launcher permission check"); 2329 2330 dumpStatLS(pw, p, Stats.GET_PACKAGE_INFO, "getPackageInfo()"); 2331 dumpStatLS(pw, p, Stats.GET_PACKAGE_INFO_WITH_SIG, "getPackageInfo(SIG)"); 2332 dumpStatLS(pw, p, Stats.GET_APPLICATION_INFO, "getApplicationInfo"); 2333 2334 dumpStatLS(pw, p, Stats.CLEANUP_DANGLING_BITMAPS, "cleanupDanglingBitmaps"); 2335 } 2336 2337 for (int i = 0; i < mUsers.size(); i++) { 2338 pw.println(); 2339 mUsers.valueAt(i).dump(this, pw, " "); 2340 } 2341 2342 pw.println(); 2343 pw.println(" UID state:"); 2344 2345 for (int i = 0; i < mUidState.size(); i++) { 2346 final int uid = mUidState.keyAt(i); 2347 final int state = mUidState.valueAt(i); 2348 pw.print(" UID="); 2349 pw.print(uid); 2350 pw.print(" state="); 2351 pw.print(state); 2352 if (isProcessStateForeground(state)) { 2353 pw.print(" [FG]"); 2354 } 2355 pw.print(" last FG="); 2356 pw.print(mUidLastForegroundElapsedTime.get(uid)); 2357 pw.println(); 2358 } 2359 } 2360 } 2361 2362 static String formatTime(long time) { 2363 Time tobj = new Time(); 2364 tobj.set(time); 2365 return tobj.format("%Y-%m-%d %H:%M:%S"); 2366 } 2367 2368 private void dumpStatLS(PrintWriter pw, String prefix, int statId, String label) { 2369 pw.print(prefix); 2370 final int count = mCountStats[statId]; 2371 final long dur = mDurationStats[statId]; 2372 pw.println(String.format("%s: count=%d, total=%dms, avg=%.1fms", 2373 label, count, dur, 2374 (count == 0 ? 0 : ((double) dur) / count))); 2375 } 2376 2377 // === Shell support === 2378 2379 @Override 2380 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err, 2381 String[] args, ResultReceiver resultReceiver) throws RemoteException { 2382 2383 enforceShell(); 2384 2385 (new MyShellCommand()).exec(this, in, out, err, args, resultReceiver); 2386 } 2387 2388 static class CommandException extends Exception { 2389 public CommandException(String message) { 2390 super(message); 2391 } 2392 } 2393 2394 /** 2395 * Handle "adb shell cmd". 2396 */ 2397 private class MyShellCommand extends ShellCommand { 2398 2399 private int mUserId = UserHandle.USER_SYSTEM; 2400 2401 private void parseOptions(boolean takeUser) 2402 throws CommandException { 2403 String opt; 2404 while ((opt = getNextOption()) != null) { 2405 switch (opt) { 2406 case "--user": 2407 if (takeUser) { 2408 mUserId = UserHandle.parseUserArg(getNextArgRequired()); 2409 break; 2410 } 2411 // fallthrough 2412 default: 2413 throw new CommandException("Unknown option: " + opt); 2414 } 2415 } 2416 } 2417 2418 @Override 2419 public int onCommand(String cmd) { 2420 if (cmd == null) { 2421 return handleDefaultCommands(cmd); 2422 } 2423 final PrintWriter pw = getOutPrintWriter(); 2424 try { 2425 switch (cmd) { 2426 case "reset-package-throttling": 2427 handleResetPackageThrottling(); 2428 break; 2429 case "reset-throttling": 2430 handleResetThrottling(); 2431 break; 2432 case "reset-all-throttling": 2433 handleResetAllThrottling(); 2434 break; 2435 case "override-config": 2436 handleOverrideConfig(); 2437 break; 2438 case "reset-config": 2439 handleResetConfig(); 2440 break; 2441 case "clear-default-launcher": 2442 handleClearDefaultLauncher(); 2443 break; 2444 case "get-default-launcher": 2445 handleGetDefaultLauncher(); 2446 break; 2447 case "refresh-default-launcher": 2448 handleRefreshDefaultLauncher(); 2449 break; 2450 case "unload-user": 2451 handleUnloadUser(); 2452 break; 2453 case "clear-shortcuts": 2454 handleClearShortcuts(); 2455 break; 2456 default: 2457 return handleDefaultCommands(cmd); 2458 } 2459 } catch (CommandException e) { 2460 pw.println("Error: " + e.getMessage()); 2461 return 1; 2462 } 2463 pw.println("Success"); 2464 return 0; 2465 } 2466 2467 @Override 2468 public void onHelp() { 2469 final PrintWriter pw = getOutPrintWriter(); 2470 pw.println("Usage: cmd shortcut COMMAND [options ...]"); 2471 pw.println(); 2472 pw.println("cmd shortcut reset-package-throttling [--user USER_ID] PACKAGE"); 2473 pw.println(" Reset throttling for a package"); 2474 pw.println(); 2475 pw.println("cmd shortcut reset-throttling [--user USER_ID]"); 2476 pw.println(" Reset throttling for all packages and users"); 2477 pw.println(); 2478 pw.println("cmd shortcut reset-all-throttling"); 2479 pw.println(" Reset the throttling state for all users"); 2480 pw.println(); 2481 pw.println("cmd shortcut override-config CONFIG"); 2482 pw.println(" Override the configuration for testing (will last until reboot)"); 2483 pw.println(); 2484 pw.println("cmd shortcut reset-config"); 2485 pw.println(" Reset the configuration set with \"update-config\""); 2486 pw.println(); 2487 pw.println("cmd shortcut clear-default-launcher [--user USER_ID]"); 2488 pw.println(" Clear the cached default launcher"); 2489 pw.println(); 2490 pw.println("cmd shortcut get-default-launcher [--user USER_ID]"); 2491 pw.println(" Show the cached default launcher"); 2492 pw.println(); 2493 pw.println("cmd shortcut refresh-default-launcher [--user USER_ID]"); 2494 pw.println(" Refresh the cached default launcher"); 2495 pw.println(); 2496 pw.println("cmd shortcut unload-user [--user USER_ID]"); 2497 pw.println(" Unload a user from the memory"); 2498 pw.println(" (This should not affect any observable behavior)"); 2499 pw.println(); 2500 pw.println("cmd shortcut clear-shortcuts [--user USER_ID] PACKAGE"); 2501 pw.println(" Remove all shortcuts from a package, including pinned shortcuts"); 2502 pw.println(); 2503 } 2504 2505 private void handleResetThrottling() throws CommandException { 2506 parseOptions(/* takeUser =*/ true); 2507 2508 Slog.i(TAG, "cmd: handleResetThrottling"); 2509 2510 resetThrottlingInner(mUserId); 2511 } 2512 2513 private void handleResetAllThrottling() { 2514 Slog.i(TAG, "cmd: handleResetAllThrottling"); 2515 2516 resetAllThrottlingInner(); 2517 } 2518 2519 private void handleResetPackageThrottling() throws CommandException { 2520 parseOptions(/* takeUser =*/ true); 2521 2522 final String packageName = getNextArgRequired(); 2523 2524 Slog.i(TAG, "cmd: handleResetPackageThrottling: " + packageName); 2525 2526 resetPackageThrottling(packageName, mUserId); 2527 } 2528 2529 private void handleOverrideConfig() throws CommandException { 2530 final String config = getNextArgRequired(); 2531 2532 Slog.i(TAG, "cmd: handleOverrideConfig: " + config); 2533 2534 synchronized (mLock) { 2535 if (!updateConfigurationLocked(config)) { 2536 throw new CommandException("override-config failed. See logcat for details."); 2537 } 2538 } 2539 } 2540 2541 private void handleResetConfig() { 2542 Slog.i(TAG, "cmd: handleResetConfig"); 2543 2544 synchronized (mLock) { 2545 loadConfigurationLocked(); 2546 } 2547 } 2548 2549 private void clearLauncher() { 2550 synchronized (mLock) { 2551 getUserShortcutsLocked(mUserId).setLauncherComponent( 2552 ShortcutService.this, null); 2553 } 2554 } 2555 2556 private void showLauncher() { 2557 synchronized (mLock) { 2558 // This ensures to set the cached launcher. Package name doesn't matter. 2559 hasShortcutHostPermissionInner("-", mUserId); 2560 2561 getOutPrintWriter().println("Launcher: " 2562 + getUserShortcutsLocked(mUserId).getLauncherComponent()); 2563 } 2564 } 2565 2566 private void handleClearDefaultLauncher() throws CommandException { 2567 parseOptions(/* takeUser =*/ true); 2568 2569 clearLauncher(); 2570 } 2571 2572 private void handleGetDefaultLauncher() throws CommandException { 2573 parseOptions(/* takeUser =*/ true); 2574 2575 showLauncher(); 2576 } 2577 2578 private void handleRefreshDefaultLauncher() throws CommandException { 2579 parseOptions(/* takeUser =*/ true); 2580 2581 clearLauncher(); 2582 showLauncher(); 2583 } 2584 2585 private void handleUnloadUser() throws CommandException { 2586 parseOptions(/* takeUser =*/ true); 2587 2588 Slog.i(TAG, "cmd: handleUnloadUser: " + mUserId); 2589 2590 ShortcutService.this.handleCleanupUser(mUserId); 2591 } 2592 2593 private void handleClearShortcuts() throws CommandException { 2594 parseOptions(/* takeUser =*/ true); 2595 final String packageName = getNextArgRequired(); 2596 2597 Slog.i(TAG, "cmd: handleClearShortcuts: " + mUserId + ", " + packageName); 2598 2599 ShortcutService.this.cleanUpPackageForAllLoadedUsers(packageName, mUserId); 2600 } 2601 } 2602 2603 // === Unit test support === 2604 2605 // Injection point. 2606 @VisibleForTesting 2607 long injectCurrentTimeMillis() { 2608 return System.currentTimeMillis(); 2609 } 2610 2611 @VisibleForTesting 2612 long injectElapsedRealtime() { 2613 return SystemClock.elapsedRealtime(); 2614 } 2615 2616 // Injection point. 2617 @VisibleForTesting 2618 int injectBinderCallingUid() { 2619 return getCallingUid(); 2620 } 2621 2622 private int getCallingUserId() { 2623 return UserHandle.getUserId(injectBinderCallingUid()); 2624 } 2625 2626 // Injection point. 2627 @VisibleForTesting 2628 long injectClearCallingIdentity() { 2629 return Binder.clearCallingIdentity(); 2630 } 2631 2632 // Injection point. 2633 @VisibleForTesting 2634 void injectRestoreCallingIdentity(long token) { 2635 Binder.restoreCallingIdentity(token); 2636 } 2637 2638 final void wtf(String message) { 2639 wtf( message, /* exception= */ null); 2640 } 2641 2642 // Injection point. 2643 void wtf(String message, Exception e) { 2644 Slog.wtf(TAG, message, e); 2645 } 2646 2647 @VisibleForTesting 2648 File injectSystemDataPath() { 2649 return Environment.getDataSystemDirectory(); 2650 } 2651 2652 @VisibleForTesting 2653 File injectUserDataPath(@UserIdInt int userId) { 2654 return new File(Environment.getDataSystemCeDirectory(userId), DIRECTORY_PER_USER); 2655 } 2656 2657 @VisibleForTesting 2658 boolean injectIsLowRamDevice() { 2659 return ActivityManager.isLowRamDeviceStatic(); 2660 } 2661 2662 @VisibleForTesting 2663 void injectRegisterUidObserver(IUidObserver observer, int which) { 2664 try { 2665 ActivityManagerNative.getDefault().registerUidObserver(observer, which); 2666 } catch (RemoteException shouldntHappen) { 2667 } 2668 } 2669 2670 @VisibleForTesting 2671 PackageManagerInternal injectPackageManagerInternal() { 2672 return mPackageManagerInternal; 2673 } 2674 2675 File getUserBitmapFilePath(@UserIdInt int userId) { 2676 return new File(injectUserDataPath(userId), DIRECTORY_BITMAPS); 2677 } 2678 2679 @VisibleForTesting 2680 SparseArray<ShortcutUser> getShortcutsForTest() { 2681 return mUsers; 2682 } 2683 2684 @VisibleForTesting 2685 int getMaxDynamicShortcutsForTest() { 2686 return mMaxDynamicShortcuts; 2687 } 2688 2689 @VisibleForTesting 2690 int getMaxUpdatesPerIntervalForTest() { 2691 return mMaxUpdatesPerInterval; 2692 } 2693 2694 @VisibleForTesting 2695 long getResetIntervalForTest() { 2696 return mResetInterval; 2697 } 2698 2699 @VisibleForTesting 2700 int getMaxIconDimensionForTest() { 2701 return mMaxIconDimension; 2702 } 2703 2704 @VisibleForTesting 2705 CompressFormat getIconPersistFormatForTest() { 2706 return mIconPersistFormat; 2707 } 2708 2709 @VisibleForTesting 2710 int getIconPersistQualityForTest() { 2711 return mIconPersistQuality; 2712 } 2713 2714 @VisibleForTesting 2715 ShortcutInfo getPackageShortcutForTest(String packageName, String shortcutId, int userId) { 2716 synchronized (mLock) { 2717 final ShortcutUser user = mUsers.get(userId); 2718 if (user == null) return null; 2719 2720 final ShortcutPackage pkg = user.getAllPackagesForTest().get(packageName); 2721 if (pkg == null) return null; 2722 2723 return pkg.findShortcutById(shortcutId); 2724 } 2725 } 2726} 2727