ShortcutService.java revision bf563b63e5d3672ec102ee191a301e49e472139b
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.IntDef; 19import android.annotation.NonNull; 20import android.annotation.Nullable; 21import android.annotation.UserIdInt; 22import android.app.ActivityManager; 23import android.app.ActivityManagerInternal; 24import android.app.AppGlobals; 25import android.app.IUidObserver; 26import android.app.usage.UsageStatsManagerInternal; 27import android.appwidget.AppWidgetProviderInfo; 28import android.content.BroadcastReceiver; 29import android.content.ComponentName; 30import android.content.Context; 31import android.content.Intent; 32import android.content.IntentFilter; 33import android.content.IntentSender; 34import android.content.IntentSender.SendIntentException; 35import android.content.pm.ActivityInfo; 36import android.content.pm.ApplicationInfo; 37import android.content.pm.IPackageManager; 38import android.content.pm.IShortcutService; 39import android.content.pm.LauncherApps; 40import android.content.pm.LauncherApps.ShortcutQuery; 41import android.content.pm.PackageInfo; 42import android.content.pm.PackageManager; 43import android.content.pm.PackageManager.NameNotFoundException; 44import android.content.pm.PackageManagerInternal; 45import android.content.pm.ParceledListSlice; 46import android.content.pm.ResolveInfo; 47import android.content.pm.ShortcutInfo; 48import android.content.pm.ShortcutServiceInternal; 49import android.content.pm.ShortcutServiceInternal.ShortcutChangeListener; 50import android.content.pm.UserInfo; 51import android.content.res.Resources; 52import android.content.res.XmlResourceParser; 53import android.graphics.Bitmap; 54import android.graphics.Bitmap.CompressFormat; 55import android.graphics.Canvas; 56import android.graphics.RectF; 57import android.graphics.drawable.Icon; 58import android.net.Uri; 59import android.os.Binder; 60import android.os.Build; 61import android.os.Bundle; 62import android.os.Environment; 63import android.os.FileUtils; 64import android.os.Handler; 65import android.os.LocaleList; 66import android.os.Looper; 67import android.os.ParcelFileDescriptor; 68import android.os.PersistableBundle; 69import android.os.Process; 70import android.os.RemoteException; 71import android.os.ResultReceiver; 72import android.os.SELinux; 73import android.os.ServiceManager; 74import android.os.ShellCallback; 75import android.os.ShellCommand; 76import android.os.SystemClock; 77import android.os.UserHandle; 78import android.os.UserManager; 79import android.text.TextUtils; 80import android.text.format.Time; 81import android.util.ArraySet; 82import android.util.AtomicFile; 83import android.util.KeyValueListParser; 84import android.util.Log; 85import android.util.Slog; 86import android.util.SparseArray; 87import android.util.SparseBooleanArray; 88import android.util.SparseIntArray; 89import android.util.SparseLongArray; 90import android.util.TypedValue; 91import android.util.Xml; 92import android.view.IWindowManager; 93 94import com.android.internal.annotations.GuardedBy; 95import com.android.internal.annotations.VisibleForTesting; 96import com.android.internal.os.BackgroundThread; 97import com.android.internal.util.DumpUtils; 98import com.android.internal.util.FastXmlSerializer; 99import com.android.internal.util.Preconditions; 100import com.android.server.LocalServices; 101import com.android.server.SystemService; 102import com.android.server.pm.ShortcutUser.PackageWithUser; 103 104import libcore.io.IoUtils; 105 106import org.json.JSONArray; 107import org.json.JSONException; 108import org.json.JSONObject; 109import org.xmlpull.v1.XmlPullParser; 110import org.xmlpull.v1.XmlPullParserException; 111import org.xmlpull.v1.XmlSerializer; 112 113import java.io.BufferedInputStream; 114import java.io.BufferedOutputStream; 115import java.io.ByteArrayInputStream; 116import java.io.ByteArrayOutputStream; 117import java.io.File; 118import java.io.FileDescriptor; 119import java.io.FileInputStream; 120import java.io.FileNotFoundException; 121import java.io.FileOutputStream; 122import java.io.IOException; 123import java.io.InputStream; 124import java.io.OutputStream; 125import java.io.PrintWriter; 126import java.lang.annotation.Retention; 127import java.lang.annotation.RetentionPolicy; 128import java.net.URISyntaxException; 129import java.nio.charset.StandardCharsets; 130import java.util.ArrayList; 131import java.util.Collections; 132import java.util.List; 133import java.util.concurrent.atomic.AtomicBoolean; 134import java.util.function.Consumer; 135import java.util.function.Predicate; 136 137/** 138 * TODO: 139 * - getIconMaxWidth()/getIconMaxHeight() should use xdpi and ydpi. 140 * -> But TypedValue.applyDimension() doesn't differentiate x and y..? 141 * 142 * - Detect when already registered instances are passed to APIs again, which might break 143 * internal bitmap handling. 144 */ 145public class ShortcutService extends IShortcutService.Stub { 146 static final String TAG = "ShortcutService"; 147 148 static final boolean DEBUG = false; // STOPSHIP if true 149 static final boolean DEBUG_LOAD = false; // STOPSHIP if true 150 static final boolean DEBUG_PROCSTATE = false; // STOPSHIP if true 151 152 @VisibleForTesting 153 static final long DEFAULT_RESET_INTERVAL_SEC = 24 * 60 * 60; // 1 day 154 155 @VisibleForTesting 156 static final int DEFAULT_MAX_UPDATES_PER_INTERVAL = 10; 157 158 @VisibleForTesting 159 static final int DEFAULT_MAX_SHORTCUTS_PER_APP = 5; 160 161 @VisibleForTesting 162 static final int DEFAULT_MAX_ICON_DIMENSION_DP = 96; 163 164 @VisibleForTesting 165 static final int DEFAULT_MAX_ICON_DIMENSION_LOWRAM_DP = 48; 166 167 @VisibleForTesting 168 static final String DEFAULT_ICON_PERSIST_FORMAT = CompressFormat.PNG.name(); 169 170 @VisibleForTesting 171 static final int DEFAULT_ICON_PERSIST_QUALITY = 100; 172 173 @VisibleForTesting 174 static final int DEFAULT_SAVE_DELAY_MS = 3000; 175 176 @VisibleForTesting 177 static final String FILENAME_BASE_STATE = "shortcut_service.xml"; 178 179 @VisibleForTesting 180 static final String DIRECTORY_PER_USER = "shortcut_service"; 181 182 @VisibleForTesting 183 static final String FILENAME_USER_PACKAGES = "shortcuts.xml"; 184 185 static final String DIRECTORY_BITMAPS = "bitmaps"; 186 187 private static final String TAG_ROOT = "root"; 188 private static final String TAG_LAST_RESET_TIME = "last_reset_time"; 189 190 private static final String ATTR_VALUE = "value"; 191 192 private static final String LAUNCHER_INTENT_CATEGORY = Intent.CATEGORY_LAUNCHER; 193 194 private static final String KEY_SHORTCUT = "shortcut"; 195 private static final String KEY_LOW_RAM = "lowRam"; 196 private static final String KEY_ICON_SIZE = "iconSize"; 197 198 private static final String DUMMY_MAIN_ACTIVITY = "android.__dummy__"; 199 200 @VisibleForTesting 201 interface ConfigConstants { 202 /** 203 * Key name for the save delay, in milliseconds. (int) 204 */ 205 String KEY_SAVE_DELAY_MILLIS = "save_delay_ms"; 206 207 /** 208 * Key name for the throttling reset interval, in seconds. (long) 209 */ 210 String KEY_RESET_INTERVAL_SEC = "reset_interval_sec"; 211 212 /** 213 * Key name for the max number of modifying API calls per app for every interval. (int) 214 */ 215 String KEY_MAX_UPDATES_PER_INTERVAL = "max_updates_per_interval"; 216 217 /** 218 * Key name for the max icon dimensions in DP, for non-low-memory devices. 219 */ 220 String KEY_MAX_ICON_DIMENSION_DP = "max_icon_dimension_dp"; 221 222 /** 223 * Key name for the max icon dimensions in DP, for low-memory devices. 224 */ 225 String KEY_MAX_ICON_DIMENSION_DP_LOWRAM = "max_icon_dimension_dp_lowram"; 226 227 /** 228 * Key name for the max dynamic shortcuts per activity. (int) 229 */ 230 String KEY_MAX_SHORTCUTS = "max_shortcuts"; 231 232 /** 233 * Key name for icon compression quality, 0-100. 234 */ 235 String KEY_ICON_QUALITY = "icon_quality"; 236 237 /** 238 * Key name for icon compression format: "PNG", "JPEG" or "WEBP" 239 */ 240 String KEY_ICON_FORMAT = "icon_format"; 241 } 242 243 final Context mContext; 244 245 private final Object mLock = new Object(); 246 247 private static List<ResolveInfo> EMPTY_RESOLVE_INFO = new ArrayList<>(0); 248 249 // Temporarily reverted to anonymous inner class form due to: b/32554459 250 private static Predicate<ResolveInfo> ACTIVITY_NOT_EXPORTED = new Predicate<ResolveInfo>() { 251 public boolean test(ResolveInfo ri) { 252 return !ri.activityInfo.exported; 253 } 254 }; 255 256 // Temporarily reverted to anonymous inner class form due to: b/32554459 257 private static Predicate<PackageInfo> PACKAGE_NOT_INSTALLED = new Predicate<PackageInfo>() { 258 public boolean test(PackageInfo pi) { 259 return !isInstalled(pi); 260 } 261 }; 262 263 private final Handler mHandler; 264 265 @GuardedBy("mLock") 266 private final ArrayList<ShortcutChangeListener> mListeners = new ArrayList<>(1); 267 268 @GuardedBy("mLock") 269 private long mRawLastResetTime; 270 271 /** 272 * User ID -> UserShortcuts 273 */ 274 @GuardedBy("mLock") 275 private final SparseArray<ShortcutUser> mUsers = new SparseArray<>(); 276 277 /** 278 * Max number of dynamic + manifest shortcuts that each application can have at a time. 279 */ 280 private int mMaxShortcuts; 281 282 /** 283 * Max number of updating API calls that each application can make during the interval. 284 */ 285 int mMaxUpdatesPerInterval; 286 287 /** 288 * Actual throttling-reset interval. By default it's a day. 289 */ 290 private long mResetInterval; 291 292 /** 293 * Icon max width/height in pixels. 294 */ 295 private int mMaxIconDimension; 296 297 private CompressFormat mIconPersistFormat; 298 private int mIconPersistQuality; 299 300 private int mSaveDelayMillis; 301 302 private final IPackageManager mIPackageManager; 303 private final PackageManagerInternal mPackageManagerInternal; 304 private final UserManager mUserManager; 305 private final UsageStatsManagerInternal mUsageStatsManagerInternal; 306 private final ActivityManagerInternal mActivityManagerInternal; 307 308 private final ShortcutRequestPinProcessor mShortcutRequestPinProcessor; 309 310 @GuardedBy("mLock") 311 final SparseIntArray mUidState = new SparseIntArray(); 312 313 @GuardedBy("mLock") 314 final SparseLongArray mUidLastForegroundElapsedTime = new SparseLongArray(); 315 316 @GuardedBy("mLock") 317 private List<Integer> mDirtyUserIds = new ArrayList<>(); 318 319 private final AtomicBoolean mBootCompleted = new AtomicBoolean(); 320 321 private static final int PACKAGE_MATCH_FLAGS = 322 PackageManager.MATCH_DIRECT_BOOT_AWARE 323 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE 324 | PackageManager.MATCH_UNINSTALLED_PACKAGES; 325 326 @GuardedBy("mLock") 327 final SparseBooleanArray mUnlockedUsers = new SparseBooleanArray(); 328 329 // Stats 330 @VisibleForTesting 331 interface Stats { 332 int GET_DEFAULT_HOME = 0; 333 int GET_PACKAGE_INFO = 1; 334 int GET_PACKAGE_INFO_WITH_SIG = 2; 335 int GET_APPLICATION_INFO = 3; 336 int LAUNCHER_PERMISSION_CHECK = 4; 337 int CLEANUP_DANGLING_BITMAPS = 5; 338 int GET_ACTIVITY_WITH_METADATA = 6; 339 int GET_INSTALLED_PACKAGES = 7; 340 int CHECK_PACKAGE_CHANGES = 8; 341 int GET_APPLICATION_RESOURCES = 9; 342 int RESOURCE_NAME_LOOKUP = 10; 343 int GET_LAUNCHER_ACTIVITY = 11; 344 int CHECK_LAUNCHER_ACTIVITY = 12; 345 int IS_ACTIVITY_ENABLED = 13; 346 int PACKAGE_UPDATE_CHECK = 14; 347 int ASYNC_PRELOAD_USER_DELAY = 15; 348 int GET_DEFAULT_LAUNCHER = 16; 349 350 int COUNT = GET_DEFAULT_LAUNCHER + 1; 351 } 352 353 private static final String[] STAT_LABELS = { 354 "getHomeActivities()", 355 "Launcher permission check", 356 "getPackageInfo()", 357 "getPackageInfo(SIG)", 358 "getApplicationInfo", 359 "cleanupDanglingBitmaps", 360 "getActivity+metadata", 361 "getInstalledPackages", 362 "checkPackageChanges", 363 "getApplicationResources", 364 "resourceNameLookup", 365 "getLauncherActivity", 366 "checkLauncherActivity", 367 "isActivityEnabled", 368 "packageUpdateCheck", 369 "asyncPreloadUserDelay", 370 "getDefaultLauncher()" 371 }; 372 373 final Object mStatLock = new Object(); 374 375 @GuardedBy("mStatLock") 376 private final int[] mCountStats = new int[Stats.COUNT]; 377 378 @GuardedBy("mStatLock") 379 private final long[] mDurationStats = new long[Stats.COUNT]; 380 381 private static final int PROCESS_STATE_FOREGROUND_THRESHOLD = 382 ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE; 383 384 static final int OPERATION_SET = 0; 385 static final int OPERATION_ADD = 1; 386 static final int OPERATION_UPDATE = 2; 387 388 /** @hide */ 389 @IntDef(value = { 390 OPERATION_SET, 391 OPERATION_ADD, 392 OPERATION_UPDATE 393 }) 394 @Retention(RetentionPolicy.SOURCE) 395 @interface ShortcutOperation { 396 } 397 398 @GuardedBy("mLock") 399 private int mWtfCount = 0; 400 401 @GuardedBy("mLock") 402 private Exception mLastWtfStacktrace; 403 404 static class InvalidFileFormatException extends Exception { 405 public InvalidFileFormatException(String message, Throwable cause) { 406 super(message, cause); 407 } 408 } 409 410 public ShortcutService(Context context) { 411 this(context, BackgroundThread.get().getLooper(), /*onyForPackgeManagerApis*/ false); 412 } 413 414 @VisibleForTesting 415 ShortcutService(Context context, Looper looper, boolean onlyForPackageManagerApis) { 416 mContext = Preconditions.checkNotNull(context); 417 LocalServices.addService(ShortcutServiceInternal.class, new LocalService()); 418 mHandler = new Handler(looper); 419 mIPackageManager = AppGlobals.getPackageManager(); 420 mPackageManagerInternal = Preconditions.checkNotNull( 421 LocalServices.getService(PackageManagerInternal.class)); 422 mUserManager = Preconditions.checkNotNull(context.getSystemService(UserManager.class)); 423 mUsageStatsManagerInternal = Preconditions.checkNotNull( 424 LocalServices.getService(UsageStatsManagerInternal.class)); 425 mActivityManagerInternal = Preconditions.checkNotNull( 426 LocalServices.getService(ActivityManagerInternal.class)); 427 428 mShortcutRequestPinProcessor = new ShortcutRequestPinProcessor(this, mLock); 429 430 if (onlyForPackageManagerApis) { 431 return; // Don't do anything further. For unit tests only. 432 } 433 434 // Register receivers. 435 436 // We need to set a priority, so let's just not use PackageMonitor for now. 437 // TODO Refactor PackageMonitor to support priorities. 438 final IntentFilter packageFilter = new IntentFilter(); 439 packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED); 440 packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED); 441 packageFilter.addAction(Intent.ACTION_PACKAGE_CHANGED); 442 packageFilter.addAction(Intent.ACTION_PACKAGE_DATA_CLEARED); 443 packageFilter.addDataScheme("package"); 444 packageFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY); 445 mContext.registerReceiverAsUser(mPackageMonitor, UserHandle.ALL, 446 packageFilter, null, mHandler); 447 448 final IntentFilter preferedActivityFilter = new IntentFilter(); 449 preferedActivityFilter.addAction(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 450 preferedActivityFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY); 451 mContext.registerReceiverAsUser(mPackageMonitor, UserHandle.ALL, 452 preferedActivityFilter, null, mHandler); 453 454 final IntentFilter localeFilter = new IntentFilter(); 455 localeFilter.addAction(Intent.ACTION_LOCALE_CHANGED); 456 localeFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY); 457 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, 458 localeFilter, null, mHandler); 459 460 injectRegisterUidObserver(mUidObserver, ActivityManager.UID_OBSERVER_PROCSTATE 461 | ActivityManager.UID_OBSERVER_GONE); 462 } 463 464 void logDurationStat(int statId, long start) { 465 synchronized (mStatLock) { 466 mCountStats[statId]++; 467 mDurationStats[statId] += (injectElapsedRealtime() - start); 468 } 469 } 470 471 public String injectGetLocaleTagsForUser(@UserIdInt int userId) { 472 // TODO This should get the per-user locale. b/30123329 b/30119489 473 return LocaleList.getDefault().toLanguageTags(); 474 } 475 476 final private IUidObserver mUidObserver = new IUidObserver.Stub() { 477 @Override 478 public void onUidStateChanged(int uid, int procState, long procStateSeq) 479 throws RemoteException { 480 handleOnUidStateChanged(uid, procState); 481 } 482 483 @Override 484 public void onUidGone(int uid, boolean disabled) throws RemoteException { 485 handleOnUidStateChanged(uid, ActivityManager.PROCESS_STATE_NONEXISTENT); 486 } 487 488 @Override 489 public void onUidActive(int uid) throws RemoteException { 490 } 491 492 @Override 493 public void onUidIdle(int uid, boolean disabled) throws RemoteException { 494 } 495 }; 496 497 void handleOnUidStateChanged(int uid, int procState) { 498 if (DEBUG_PROCSTATE) { 499 Slog.d(TAG, "onUidStateChanged: uid=" + uid + " state=" + procState); 500 } 501 synchronized (mLock) { 502 mUidState.put(uid, procState); 503 504 // We need to keep track of last time an app comes to foreground. 505 // See ShortcutPackage.getApiCallCount() for how it's used. 506 // It doesn't have to be persisted, but it needs to be the elapsed time. 507 if (isProcessStateForeground(procState)) { 508 mUidLastForegroundElapsedTime.put(uid, injectElapsedRealtime()); 509 } 510 } 511 } 512 513 private boolean isProcessStateForeground(int processState) { 514 return processState <= PROCESS_STATE_FOREGROUND_THRESHOLD; 515 } 516 517 boolean isUidForegroundLocked(int uid) { 518 if (uid == Process.SYSTEM_UID) { 519 // IUidObserver doesn't report the state of SYSTEM, but it always has bound services, 520 // so it's foreground anyway. 521 return true; 522 } 523 // First, check with the local cache. 524 if (isProcessStateForeground(mUidState.get(uid, ActivityManager.MAX_PROCESS_STATE))) { 525 return true; 526 } 527 // If the cache says background, reach out to AM. Since it'll internally need to hold 528 // the AM lock, we use it as a last resort. 529 return isProcessStateForeground(mActivityManagerInternal.getUidProcessState(uid)); 530 } 531 532 long getUidLastForegroundElapsedTimeLocked(int uid) { 533 return mUidLastForegroundElapsedTime.get(uid); 534 } 535 536 /** 537 * System service lifecycle. 538 */ 539 public static final class Lifecycle extends SystemService { 540 final ShortcutService mService; 541 542 public Lifecycle(Context context) { 543 super(context); 544 mService = new ShortcutService(context); 545 } 546 547 @Override 548 public void onStart() { 549 publishBinderService(Context.SHORTCUT_SERVICE, mService); 550 } 551 552 @Override 553 public void onBootPhase(int phase) { 554 mService.onBootPhase(phase); 555 } 556 557 @Override 558 public void onStopUser(int userHandle) { 559 mService.handleStopUser(userHandle); 560 } 561 562 @Override 563 public void onUnlockUser(int userId) { 564 mService.handleUnlockUser(userId); 565 } 566 } 567 568 /** lifecycle event */ 569 void onBootPhase(int phase) { 570 if (DEBUG) { 571 Slog.d(TAG, "onBootPhase: " + phase); 572 } 573 switch (phase) { 574 case SystemService.PHASE_LOCK_SETTINGS_READY: 575 initialize(); 576 break; 577 case SystemService.PHASE_BOOT_COMPLETED: 578 mBootCompleted.set(true); 579 break; 580 } 581 } 582 583 /** lifecycle event */ 584 void handleUnlockUser(int userId) { 585 if (DEBUG) { 586 Slog.d(TAG, "handleUnlockUser: user=" + userId); 587 } 588 synchronized (mLock) { 589 mUnlockedUsers.put(userId, true); 590 } 591 592 // Preload the user data. 593 // Note, we don't use mHandler here but instead just start a new thread. 594 // This is because mHandler (which uses com.android.internal.os.BackgroundThread) is very 595 // busy at this point and this could take hundreds of milliseconds, which would be too 596 // late since the launcher would already have started. 597 // So we just create a new thread. This code runs rarely, so we don't use a thread pool 598 // or anything. 599 final long start = injectElapsedRealtime(); 600 injectRunOnNewThread(() -> { 601 synchronized (mLock) { 602 logDurationStat(Stats.ASYNC_PRELOAD_USER_DELAY, start); 603 getUserShortcutsLocked(userId); 604 } 605 }); 606 } 607 608 /** lifecycle event */ 609 void handleStopUser(int userId) { 610 if (DEBUG) { 611 Slog.d(TAG, "handleStopUser: user=" + userId); 612 } 613 synchronized (mLock) { 614 unloadUserLocked(userId); 615 616 mUnlockedUsers.put(userId, false); 617 } 618 } 619 620 private void unloadUserLocked(int userId) { 621 if (DEBUG) { 622 Slog.d(TAG, "unloadUserLocked: user=" + userId); 623 } 624 // Save all dirty information. 625 saveDirtyInfo(); 626 627 // Unload 628 mUsers.delete(userId); 629 } 630 631 /** Return the base state file name */ 632 private AtomicFile getBaseStateFile() { 633 final File path = new File(injectSystemDataPath(), FILENAME_BASE_STATE); 634 path.mkdirs(); 635 return new AtomicFile(path); 636 } 637 638 /** 639 * Init the instance. (load the state file, etc) 640 */ 641 private void initialize() { 642 synchronized (mLock) { 643 loadConfigurationLocked(); 644 loadBaseStateLocked(); 645 } 646 } 647 648 /** 649 * Load the configuration from Settings. 650 */ 651 private void loadConfigurationLocked() { 652 updateConfigurationLocked(injectShortcutManagerConstants()); 653 } 654 655 /** 656 * Load the configuration from Settings. 657 */ 658 @VisibleForTesting 659 boolean updateConfigurationLocked(String config) { 660 boolean result = true; 661 662 final KeyValueListParser parser = new KeyValueListParser(','); 663 try { 664 parser.setString(config); 665 } catch (IllegalArgumentException e) { 666 // Failed to parse the settings string, log this and move on 667 // with defaults. 668 Slog.e(TAG, "Bad shortcut manager settings", e); 669 result = false; 670 } 671 672 mSaveDelayMillis = Math.max(0, (int) parser.getLong(ConfigConstants.KEY_SAVE_DELAY_MILLIS, 673 DEFAULT_SAVE_DELAY_MS)); 674 675 mResetInterval = Math.max(1, parser.getLong( 676 ConfigConstants.KEY_RESET_INTERVAL_SEC, DEFAULT_RESET_INTERVAL_SEC) 677 * 1000L); 678 679 mMaxUpdatesPerInterval = Math.max(0, (int) parser.getLong( 680 ConfigConstants.KEY_MAX_UPDATES_PER_INTERVAL, DEFAULT_MAX_UPDATES_PER_INTERVAL)); 681 682 mMaxShortcuts = Math.max(0, (int) parser.getLong( 683 ConfigConstants.KEY_MAX_SHORTCUTS, DEFAULT_MAX_SHORTCUTS_PER_APP)); 684 685 final int iconDimensionDp = Math.max(1, injectIsLowRamDevice() 686 ? (int) parser.getLong( 687 ConfigConstants.KEY_MAX_ICON_DIMENSION_DP_LOWRAM, 688 DEFAULT_MAX_ICON_DIMENSION_LOWRAM_DP) 689 : (int) parser.getLong( 690 ConfigConstants.KEY_MAX_ICON_DIMENSION_DP, 691 DEFAULT_MAX_ICON_DIMENSION_DP)); 692 693 mMaxIconDimension = injectDipToPixel(iconDimensionDp); 694 695 mIconPersistFormat = CompressFormat.valueOf( 696 parser.getString(ConfigConstants.KEY_ICON_FORMAT, DEFAULT_ICON_PERSIST_FORMAT)); 697 698 mIconPersistQuality = (int) parser.getLong( 699 ConfigConstants.KEY_ICON_QUALITY, 700 DEFAULT_ICON_PERSIST_QUALITY); 701 702 return result; 703 } 704 705 @VisibleForTesting 706 String injectShortcutManagerConstants() { 707 return android.provider.Settings.Global.getString( 708 mContext.getContentResolver(), 709 android.provider.Settings.Global.SHORTCUT_MANAGER_CONSTANTS); 710 } 711 712 @VisibleForTesting 713 int injectDipToPixel(int dip) { 714 return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, 715 mContext.getResources().getDisplayMetrics()); 716 } 717 718 // === Persisting === 719 720 @Nullable 721 static String parseStringAttribute(XmlPullParser parser, String attribute) { 722 return parser.getAttributeValue(null, attribute); 723 } 724 725 static boolean parseBooleanAttribute(XmlPullParser parser, String attribute) { 726 return parseLongAttribute(parser, attribute) == 1; 727 } 728 729 static int parseIntAttribute(XmlPullParser parser, String attribute) { 730 return (int) parseLongAttribute(parser, attribute); 731 } 732 733 static int parseIntAttribute(XmlPullParser parser, String attribute, int def) { 734 return (int) parseLongAttribute(parser, attribute, def); 735 } 736 737 static long parseLongAttribute(XmlPullParser parser, String attribute) { 738 return parseLongAttribute(parser, attribute, 0); 739 } 740 741 static long parseLongAttribute(XmlPullParser parser, String attribute, long def) { 742 final String value = parseStringAttribute(parser, attribute); 743 if (TextUtils.isEmpty(value)) { 744 return def; 745 } 746 try { 747 return Long.parseLong(value); 748 } catch (NumberFormatException e) { 749 Slog.e(TAG, "Error parsing long " + value); 750 return def; 751 } 752 } 753 754 @Nullable 755 static ComponentName parseComponentNameAttribute(XmlPullParser parser, String attribute) { 756 final String value = parseStringAttribute(parser, attribute); 757 if (TextUtils.isEmpty(value)) { 758 return null; 759 } 760 return ComponentName.unflattenFromString(value); 761 } 762 763 @Nullable 764 static Intent parseIntentAttributeNoDefault(XmlPullParser parser, String attribute) { 765 final String value = parseStringAttribute(parser, attribute); 766 Intent parsed = null; 767 if (!TextUtils.isEmpty(value)) { 768 try { 769 parsed = Intent.parseUri(value, /* flags =*/ 0); 770 } catch (URISyntaxException e) { 771 Slog.e(TAG, "Error parsing intent", e); 772 } 773 } 774 return parsed; 775 } 776 777 @Nullable 778 static Intent parseIntentAttribute(XmlPullParser parser, String attribute) { 779 Intent parsed = parseIntentAttributeNoDefault(parser, attribute); 780 if (parsed == null) { 781 // Default intent. 782 parsed = new Intent(Intent.ACTION_VIEW); 783 } 784 return parsed; 785 } 786 787 static void writeTagValue(XmlSerializer out, String tag, String value) throws IOException { 788 if (TextUtils.isEmpty(value)) return; 789 790 out.startTag(null, tag); 791 out.attribute(null, ATTR_VALUE, value); 792 out.endTag(null, tag); 793 } 794 795 static void writeTagValue(XmlSerializer out, String tag, long value) throws IOException { 796 writeTagValue(out, tag, Long.toString(value)); 797 } 798 799 static void writeTagValue(XmlSerializer out, String tag, ComponentName name) throws IOException { 800 if (name == null) return; 801 writeTagValue(out, tag, name.flattenToString()); 802 } 803 804 static void writeTagExtra(XmlSerializer out, String tag, PersistableBundle bundle) 805 throws IOException, XmlPullParserException { 806 if (bundle == null) return; 807 808 out.startTag(null, tag); 809 bundle.saveToXml(out); 810 out.endTag(null, tag); 811 } 812 813 static void writeAttr(XmlSerializer out, String name, CharSequence value) throws IOException { 814 if (TextUtils.isEmpty(value)) return; 815 816 out.attribute(null, name, value.toString()); 817 } 818 819 static void writeAttr(XmlSerializer out, String name, long value) throws IOException { 820 writeAttr(out, name, String.valueOf(value)); 821 } 822 823 static void writeAttr(XmlSerializer out, String name, boolean value) throws IOException { 824 if (value) { 825 writeAttr(out, name, "1"); 826 } 827 } 828 829 static void writeAttr(XmlSerializer out, String name, ComponentName comp) throws IOException { 830 if (comp == null) return; 831 writeAttr(out, name, comp.flattenToString()); 832 } 833 834 static void writeAttr(XmlSerializer out, String name, Intent intent) throws IOException { 835 if (intent == null) return; 836 837 writeAttr(out, name, intent.toUri(/* flags =*/ 0)); 838 } 839 840 @VisibleForTesting 841 void saveBaseStateLocked() { 842 final AtomicFile file = getBaseStateFile(); 843 if (DEBUG) { 844 Slog.d(TAG, "Saving to " + file.getBaseFile()); 845 } 846 847 FileOutputStream outs = null; 848 try { 849 outs = file.startWrite(); 850 851 // Write to XML 852 XmlSerializer out = new FastXmlSerializer(); 853 out.setOutput(outs, StandardCharsets.UTF_8.name()); 854 out.startDocument(null, true); 855 out.startTag(null, TAG_ROOT); 856 857 // Body. 858 writeTagValue(out, TAG_LAST_RESET_TIME, mRawLastResetTime); 859 860 // Epilogue. 861 out.endTag(null, TAG_ROOT); 862 out.endDocument(); 863 864 // Close. 865 file.finishWrite(outs); 866 } catch (IOException e) { 867 Slog.e(TAG, "Failed to write to file " + file.getBaseFile(), e); 868 file.failWrite(outs); 869 } 870 } 871 872 private void loadBaseStateLocked() { 873 mRawLastResetTime = 0; 874 875 final AtomicFile file = getBaseStateFile(); 876 if (DEBUG) { 877 Slog.d(TAG, "Loading from " + file.getBaseFile()); 878 } 879 try (FileInputStream in = file.openRead()) { 880 XmlPullParser parser = Xml.newPullParser(); 881 parser.setInput(in, StandardCharsets.UTF_8.name()); 882 883 int type; 884 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) { 885 if (type != XmlPullParser.START_TAG) { 886 continue; 887 } 888 final int depth = parser.getDepth(); 889 // Check the root tag 890 final String tag = parser.getName(); 891 if (depth == 1) { 892 if (!TAG_ROOT.equals(tag)) { 893 Slog.e(TAG, "Invalid root tag: " + tag); 894 return; 895 } 896 continue; 897 } 898 // Assume depth == 2 899 switch (tag) { 900 case TAG_LAST_RESET_TIME: 901 mRawLastResetTime = parseLongAttribute(parser, ATTR_VALUE); 902 break; 903 default: 904 Slog.e(TAG, "Invalid tag: " + tag); 905 break; 906 } 907 } 908 } catch (FileNotFoundException e) { 909 // Use the default 910 } catch (IOException | XmlPullParserException e) { 911 Slog.e(TAG, "Failed to read file " + file.getBaseFile(), e); 912 913 mRawLastResetTime = 0; 914 } 915 // Adjust the last reset time. 916 getLastResetTimeLocked(); 917 } 918 919 @VisibleForTesting 920 final File getUserFile(@UserIdInt int userId) { 921 return new File(injectUserDataPath(userId), FILENAME_USER_PACKAGES); 922 } 923 924 private void saveUserLocked(@UserIdInt int userId) { 925 final File path = getUserFile(userId); 926 if (DEBUG) { 927 Slog.d(TAG, "Saving to " + path); 928 } 929 path.getParentFile().mkdirs(); 930 final AtomicFile file = new AtomicFile(path); 931 FileOutputStream os = null; 932 try { 933 os = file.startWrite(); 934 935 saveUserInternalLocked(userId, os, /* forBackup= */ false); 936 937 file.finishWrite(os); 938 939 // Remove all dangling bitmap files. 940 cleanupDanglingBitmapDirectoriesLocked(userId); 941 } catch (XmlPullParserException | IOException e) { 942 Slog.e(TAG, "Failed to write to file " + file.getBaseFile(), e); 943 file.failWrite(os); 944 } 945 } 946 947 private void saveUserInternalLocked(@UserIdInt int userId, OutputStream os, 948 boolean forBackup) throws IOException, XmlPullParserException { 949 950 final BufferedOutputStream bos = new BufferedOutputStream(os); 951 952 // Write to XML 953 XmlSerializer out = new FastXmlSerializer(); 954 out.setOutput(bos, StandardCharsets.UTF_8.name()); 955 out.startDocument(null, true); 956 957 getUserShortcutsLocked(userId).saveToXml(out, forBackup); 958 959 out.endDocument(); 960 961 bos.flush(); 962 os.flush(); 963 } 964 965 static IOException throwForInvalidTag(int depth, String tag) throws IOException { 966 throw new IOException(String.format("Invalid tag '%s' found at depth %d", tag, depth)); 967 } 968 969 static void warnForInvalidTag(int depth, String tag) throws IOException { 970 Slog.w(TAG, String.format("Invalid tag '%s' found at depth %d", tag, depth)); 971 } 972 973 @Nullable 974 private ShortcutUser loadUserLocked(@UserIdInt int userId) { 975 final File path = getUserFile(userId); 976 if (DEBUG) { 977 Slog.d(TAG, "Loading from " + path); 978 } 979 final AtomicFile file = new AtomicFile(path); 980 981 final FileInputStream in; 982 try { 983 in = file.openRead(); 984 } catch (FileNotFoundException e) { 985 if (DEBUG) { 986 Slog.d(TAG, "Not found " + path); 987 } 988 return null; 989 } 990 try { 991 final ShortcutUser ret = loadUserInternal(userId, in, /* forBackup= */ false); 992 return ret; 993 } catch (IOException | XmlPullParserException | InvalidFileFormatException e) { 994 Slog.e(TAG, "Failed to read file " + file.getBaseFile(), e); 995 return null; 996 } finally { 997 IoUtils.closeQuietly(in); 998 } 999 } 1000 1001 private ShortcutUser loadUserInternal(@UserIdInt int userId, InputStream is, 1002 boolean fromBackup) throws XmlPullParserException, IOException, 1003 InvalidFileFormatException { 1004 1005 final BufferedInputStream bis = new BufferedInputStream(is); 1006 1007 ShortcutUser ret = null; 1008 XmlPullParser parser = Xml.newPullParser(); 1009 parser.setInput(bis, StandardCharsets.UTF_8.name()); 1010 1011 int type; 1012 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) { 1013 if (type != XmlPullParser.START_TAG) { 1014 continue; 1015 } 1016 final int depth = parser.getDepth(); 1017 1018 final String tag = parser.getName(); 1019 if (DEBUG_LOAD) { 1020 Slog.d(TAG, String.format("depth=%d type=%d name=%s", 1021 depth, type, tag)); 1022 } 1023 if ((depth == 1) && ShortcutUser.TAG_ROOT.equals(tag)) { 1024 ret = ShortcutUser.loadFromXml(this, parser, userId, fromBackup); 1025 continue; 1026 } 1027 throwForInvalidTag(depth, tag); 1028 } 1029 return ret; 1030 } 1031 1032 private void scheduleSaveBaseState() { 1033 scheduleSaveInner(UserHandle.USER_NULL); // Special case -- use USER_NULL for base state. 1034 } 1035 1036 void scheduleSaveUser(@UserIdInt int userId) { 1037 scheduleSaveInner(userId); 1038 } 1039 1040 // In order to re-schedule, we need to reuse the same instance, so keep it in final. 1041 private final Runnable mSaveDirtyInfoRunner = this::saveDirtyInfo; 1042 1043 private void scheduleSaveInner(@UserIdInt int userId) { 1044 if (DEBUG) { 1045 Slog.d(TAG, "Scheduling to save for " + userId); 1046 } 1047 synchronized (mLock) { 1048 if (!mDirtyUserIds.contains(userId)) { 1049 mDirtyUserIds.add(userId); 1050 } 1051 } 1052 // If already scheduled, remove that and re-schedule in N seconds. 1053 mHandler.removeCallbacks(mSaveDirtyInfoRunner); 1054 mHandler.postDelayed(mSaveDirtyInfoRunner, mSaveDelayMillis); 1055 } 1056 1057 @VisibleForTesting 1058 void saveDirtyInfo() { 1059 if (DEBUG) { 1060 Slog.d(TAG, "saveDirtyInfo"); 1061 } 1062 try { 1063 synchronized (mLock) { 1064 for (int i = mDirtyUserIds.size() - 1; i >= 0; i--) { 1065 final int userId = mDirtyUserIds.get(i); 1066 if (userId == UserHandle.USER_NULL) { // USER_NULL for base state. 1067 saveBaseStateLocked(); 1068 } else { 1069 saveUserLocked(userId); 1070 } 1071 } 1072 mDirtyUserIds.clear(); 1073 } 1074 } catch (Exception e) { 1075 wtf("Exception in saveDirtyInfo", e); 1076 } 1077 } 1078 1079 /** Return the last reset time. */ 1080 long getLastResetTimeLocked() { 1081 updateTimesLocked(); 1082 return mRawLastResetTime; 1083 } 1084 1085 /** Return the next reset time. */ 1086 long getNextResetTimeLocked() { 1087 updateTimesLocked(); 1088 return mRawLastResetTime + mResetInterval; 1089 } 1090 1091 static boolean isClockValid(long time) { 1092 return time >= 1420070400; // Thu, 01 Jan 2015 00:00:00 GMT 1093 } 1094 1095 /** 1096 * Update the last reset time. 1097 */ 1098 private void updateTimesLocked() { 1099 1100 final long now = injectCurrentTimeMillis(); 1101 1102 final long prevLastResetTime = mRawLastResetTime; 1103 1104 if (mRawLastResetTime == 0) { // first launch. 1105 // TODO Randomize?? 1106 mRawLastResetTime = now; 1107 } else if (now < mRawLastResetTime) { 1108 // Clock rewound. 1109 if (isClockValid(now)) { 1110 Slog.w(TAG, "Clock rewound"); 1111 // TODO Randomize?? 1112 mRawLastResetTime = now; 1113 } 1114 } else { 1115 if ((mRawLastResetTime + mResetInterval) <= now) { 1116 final long offset = mRawLastResetTime % mResetInterval; 1117 mRawLastResetTime = ((now / mResetInterval) * mResetInterval) + offset; 1118 } 1119 } 1120 if (prevLastResetTime != mRawLastResetTime) { 1121 scheduleSaveBaseState(); 1122 } 1123 } 1124 1125 // Requires mLock held, but "Locked" prefix would look weired so we just say "L". 1126 protected boolean isUserUnlockedL(@UserIdInt int userId) { 1127 // First, check the local copy. 1128 if (mUnlockedUsers.get(userId)) { 1129 return true; 1130 } 1131 // If the local copy says the user is locked, check with AM for the actual state, since 1132 // the user might just have been unlocked. 1133 // Note we just don't use isUserUnlockingOrUnlocked() here, because it'll return false 1134 // when the user is STOPPING, which we still want to consider as "unlocked". 1135 final long token = injectClearCallingIdentity(); 1136 try { 1137 return mUserManager.isUserUnlockingOrUnlocked(userId); 1138 } finally { 1139 injectRestoreCallingIdentity(token); 1140 } 1141 } 1142 1143 // Requires mLock held, but "Locked" prefix would look weired so we jsut say "L". 1144 void throwIfUserLockedL(@UserIdInt int userId) { 1145 if (!isUserUnlockedL(userId)) { 1146 throw new IllegalStateException("User " + userId + " is locked or not running"); 1147 } 1148 } 1149 1150 @GuardedBy("mLock") 1151 @NonNull 1152 private boolean isUserLoadedLocked(@UserIdInt int userId) { 1153 return mUsers.get(userId) != null; 1154 } 1155 1156 /** Return the per-user state. */ 1157 @GuardedBy("mLock") 1158 @NonNull 1159 ShortcutUser getUserShortcutsLocked(@UserIdInt int userId) { 1160 if (!isUserUnlockedL(userId)) { 1161 wtf("User still locked"); 1162 } 1163 1164 ShortcutUser userPackages = mUsers.get(userId); 1165 if (userPackages == null) { 1166 userPackages = loadUserLocked(userId); 1167 if (userPackages == null) { 1168 userPackages = new ShortcutUser(this, userId); 1169 } 1170 mUsers.put(userId, userPackages); 1171 1172 // Also when a user's data is first accessed, scan all packages. 1173 checkPackageChanges(userId); 1174 } 1175 return userPackages; 1176 } 1177 1178 void forEachLoadedUserLocked(@NonNull Consumer<ShortcutUser> c) { 1179 for (int i = mUsers.size() - 1; i >= 0; i--) { 1180 c.accept(mUsers.valueAt(i)); 1181 } 1182 } 1183 1184 /** 1185 * Return the per-user per-package state. If the caller is a publisher, use 1186 * {@link #getPackageShortcutsForPublisherLocked} instead. 1187 */ 1188 @GuardedBy("mLock") 1189 @NonNull 1190 ShortcutPackage getPackageShortcutsLocked( 1191 @NonNull String packageName, @UserIdInt int userId) { 1192 return getUserShortcutsLocked(userId).getPackageShortcuts(packageName); 1193 } 1194 1195 /** Return the per-user per-package state. Use this when the caller is a publisher. */ 1196 @GuardedBy("mLock") 1197 @NonNull 1198 ShortcutPackage getPackageShortcutsForPublisherLocked( 1199 @NonNull String packageName, @UserIdInt int userId) { 1200 final ShortcutPackage ret = getUserShortcutsLocked(userId).getPackageShortcuts(packageName); 1201 ret.getUser().onCalledByPublisher(packageName); 1202 return ret; 1203 } 1204 1205 @GuardedBy("mLock") 1206 @NonNull 1207 ShortcutLauncher getLauncherShortcutsLocked( 1208 @NonNull String packageName, @UserIdInt int ownerUserId, 1209 @UserIdInt int launcherUserId) { 1210 return getUserShortcutsLocked(ownerUserId) 1211 .getLauncherShortcuts(packageName, launcherUserId); 1212 } 1213 1214 // === Caller validation === 1215 1216 void removeIcon(@UserIdInt int userId, ShortcutInfo shortcut) { 1217 // Do not remove the actual bitmap file yet, because if the device crashes before saving 1218 // he XML we'd lose the icon. We just remove all dangling files after saving the XML. 1219 shortcut.setIconResourceId(0); 1220 shortcut.setIconResName(null); 1221 shortcut.clearFlags(ShortcutInfo.FLAG_HAS_ICON_FILE | 1222 ShortcutInfo.FLAG_ADAPTIVE_BITMAP | ShortcutInfo.FLAG_HAS_ICON_RES); 1223 } 1224 1225 public void cleanupBitmapsForPackage(@UserIdInt int userId, String packageName) { 1226 final File packagePath = new File(getUserBitmapFilePath(userId), packageName); 1227 if (!packagePath.isDirectory()) { 1228 return; 1229 } 1230 if (!(FileUtils.deleteContents(packagePath) && packagePath.delete())) { 1231 Slog.w(TAG, "Unable to remove directory " + packagePath); 1232 } 1233 } 1234 1235 private void cleanupDanglingBitmapDirectoriesLocked(@UserIdInt int userId) { 1236 if (DEBUG) { 1237 Slog.d(TAG, "cleanupDanglingBitmaps: userId=" + userId); 1238 } 1239 final long start = injectElapsedRealtime(); 1240 1241 final ShortcutUser user = getUserShortcutsLocked(userId); 1242 1243 final File bitmapDir = getUserBitmapFilePath(userId); 1244 final File[] children = bitmapDir.listFiles(); 1245 if (children == null) { 1246 return; 1247 } 1248 for (File child : children) { 1249 if (!child.isDirectory()) { 1250 continue; 1251 } 1252 final String packageName = child.getName(); 1253 if (DEBUG) { 1254 Slog.d(TAG, "cleanupDanglingBitmaps: Found directory=" + packageName); 1255 } 1256 if (!user.hasPackage(packageName)) { 1257 if (DEBUG) { 1258 Slog.d(TAG, "Removing dangling bitmap directory: " + packageName); 1259 } 1260 cleanupBitmapsForPackage(userId, packageName); 1261 } else { 1262 cleanupDanglingBitmapFilesLocked(userId, user, packageName, child); 1263 } 1264 } 1265 logDurationStat(Stats.CLEANUP_DANGLING_BITMAPS, start); 1266 } 1267 1268 private void cleanupDanglingBitmapFilesLocked(@UserIdInt int userId, @NonNull ShortcutUser user, 1269 @NonNull String packageName, @NonNull File path) { 1270 final ArraySet<String> usedFiles = 1271 user.getPackageShortcuts(packageName).getUsedBitmapFiles(); 1272 1273 for (File child : path.listFiles()) { 1274 if (!child.isFile()) { 1275 continue; 1276 } 1277 final String name = child.getName(); 1278 if (!usedFiles.contains(name)) { 1279 if (DEBUG) { 1280 Slog.d(TAG, "Removing dangling bitmap file: " + child.getAbsolutePath()); 1281 } 1282 child.delete(); 1283 } 1284 } 1285 } 1286 1287 @VisibleForTesting 1288 static class FileOutputStreamWithPath extends FileOutputStream { 1289 private final File mFile; 1290 1291 public FileOutputStreamWithPath(File file) throws FileNotFoundException { 1292 super(file); 1293 mFile = file; 1294 } 1295 1296 public File getFile() { 1297 return mFile; 1298 } 1299 } 1300 1301 /** 1302 * Build the cached bitmap filename for a shortcut icon. 1303 * 1304 * The filename will be based on the ID, except certain characters will be escaped. 1305 */ 1306 @VisibleForTesting 1307 FileOutputStreamWithPath openIconFileForWrite(@UserIdInt int userId, ShortcutInfo shortcut) 1308 throws IOException { 1309 final File packagePath = new File(getUserBitmapFilePath(userId), 1310 shortcut.getPackage()); 1311 if (!packagePath.isDirectory()) { 1312 packagePath.mkdirs(); 1313 if (!packagePath.isDirectory()) { 1314 throw new IOException("Unable to create directory " + packagePath); 1315 } 1316 SELinux.restorecon(packagePath); 1317 } 1318 1319 final String baseName = String.valueOf(injectCurrentTimeMillis()); 1320 for (int suffix = 0; ; suffix++) { 1321 final String filename = (suffix == 0 ? baseName : baseName + "_" + suffix) + ".png"; 1322 final File file = new File(packagePath, filename); 1323 if (!file.exists()) { 1324 if (DEBUG) { 1325 Slog.d(TAG, "Saving icon to " + file.getAbsolutePath()); 1326 } 1327 return new FileOutputStreamWithPath(file); 1328 } 1329 } 1330 } 1331 1332 void saveIconAndFixUpShortcut(@UserIdInt int userId, ShortcutInfo shortcut) { 1333 if (shortcut.hasIconFile() || shortcut.hasIconResource()) { 1334 return; 1335 } 1336 1337 final long token = injectClearCallingIdentity(); 1338 try { 1339 // Clear icon info on the shortcut. 1340 removeIcon(userId, shortcut); 1341 1342 final Icon icon = shortcut.getIcon(); 1343 if (icon == null) { 1344 return; // has no icon 1345 } 1346 1347 Bitmap bitmap; 1348 try { 1349 switch (icon.getType()) { 1350 case Icon.TYPE_RESOURCE: { 1351 injectValidateIconResPackage(shortcut, icon); 1352 1353 shortcut.setIconResourceId(icon.getResId()); 1354 shortcut.addFlags(ShortcutInfo.FLAG_HAS_ICON_RES); 1355 return; 1356 } 1357 case Icon.TYPE_BITMAP: 1358 case Icon.TYPE_ADAPTIVE_BITMAP: { 1359 bitmap = icon.getBitmap(); // Don't recycle in this case. 1360 break; 1361 } 1362 default: 1363 // This shouldn't happen because we've already validated the icon, but 1364 // just in case. 1365 throw ShortcutInfo.getInvalidIconException(); 1366 } 1367 if (bitmap == null) { 1368 Slog.e(TAG, "Null bitmap detected"); 1369 return; 1370 } 1371 // Shrink and write to the file. 1372 File path = null; 1373 try { 1374 final FileOutputStreamWithPath out = openIconFileForWrite(userId, shortcut); 1375 try { 1376 path = out.getFile(); 1377 1378 Bitmap shrunk = shrinkBitmap(bitmap, mMaxIconDimension); 1379 try { 1380 shrunk.compress(mIconPersistFormat, mIconPersistQuality, out); 1381 } finally { 1382 if (bitmap != shrunk) { 1383 shrunk.recycle(); 1384 } 1385 } 1386 1387 shortcut.setBitmapPath(out.getFile().getAbsolutePath()); 1388 shortcut.addFlags(ShortcutInfo.FLAG_HAS_ICON_FILE); 1389 if (icon.getType() == Icon.TYPE_ADAPTIVE_BITMAP) { 1390 shortcut.addFlags(ShortcutInfo.FLAG_ADAPTIVE_BITMAP); 1391 } 1392 } finally { 1393 IoUtils.closeQuietly(out); 1394 } 1395 } catch (IOException | RuntimeException e) { 1396 // STOPSHIP Change wtf to e 1397 Slog.wtf(ShortcutService.TAG, "Unable to write bitmap to file", e); 1398 if (path != null && path.exists()) { 1399 path.delete(); 1400 } 1401 } 1402 } finally { 1403 // Once saved, we won't use the original icon information, so null it out. 1404 shortcut.clearIcon(); 1405 } 1406 } finally { 1407 injectRestoreCallingIdentity(token); 1408 } 1409 } 1410 1411 // Unfortunately we can't do this check in unit tests because we fake creator package names, 1412 // so override in unit tests. 1413 // TODO CTS this case. 1414 void injectValidateIconResPackage(ShortcutInfo shortcut, Icon icon) { 1415 if (!shortcut.getPackage().equals(icon.getResPackage())) { 1416 throw new IllegalArgumentException( 1417 "Icon resource must reside in shortcut owner package"); 1418 } 1419 } 1420 1421 @VisibleForTesting 1422 static Bitmap shrinkBitmap(Bitmap in, int maxSize) { 1423 // Original width/height. 1424 final int ow = in.getWidth(); 1425 final int oh = in.getHeight(); 1426 if ((ow <= maxSize) && (oh <= maxSize)) { 1427 if (DEBUG) { 1428 Slog.d(TAG, String.format("Icon size %dx%d, no need to shrink", ow, oh)); 1429 } 1430 return in; 1431 } 1432 final int longerDimension = Math.max(ow, oh); 1433 1434 // New width and height. 1435 final int nw = ow * maxSize / longerDimension; 1436 final int nh = oh * maxSize / longerDimension; 1437 if (DEBUG) { 1438 Slog.d(TAG, String.format("Icon size %dx%d, shrinking to %dx%d", 1439 ow, oh, nw, nh)); 1440 } 1441 1442 final Bitmap scaledBitmap = Bitmap.createBitmap(nw, nh, Bitmap.Config.ARGB_8888); 1443 final Canvas c = new Canvas(scaledBitmap); 1444 1445 final RectF dst = new RectF(0, 0, nw, nh); 1446 1447 c.drawBitmap(in, /*src=*/ null, dst, /* paint =*/ null); 1448 1449 return scaledBitmap; 1450 } 1451 1452 /** 1453 * For a shortcut, update all resource names from resource IDs, and also update all 1454 * resource-based strings. 1455 */ 1456 void fixUpShortcutResourceNamesAndValues(ShortcutInfo si) { 1457 final Resources publisherRes = injectGetResourcesForApplicationAsUser( 1458 si.getPackage(), si.getUserId()); 1459 if (publisherRes != null) { 1460 final long start = injectElapsedRealtime(); 1461 try { 1462 si.lookupAndFillInResourceNames(publisherRes); 1463 } finally { 1464 logDurationStat(Stats.RESOURCE_NAME_LOOKUP, start); 1465 } 1466 si.resolveResourceStrings(publisherRes); 1467 } 1468 } 1469 1470 // === Caller validation === 1471 1472 private boolean isCallerSystem() { 1473 final int callingUid = injectBinderCallingUid(); 1474 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID); 1475 } 1476 1477 private boolean isCallerShell() { 1478 final int callingUid = injectBinderCallingUid(); 1479 return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID; 1480 } 1481 1482 private void enforceSystemOrShell() { 1483 if (!(isCallerSystem() || isCallerShell())) { 1484 throw new SecurityException("Caller must be system or shell"); 1485 } 1486 } 1487 1488 private void enforceShell() { 1489 if (!isCallerShell()) { 1490 throw new SecurityException("Caller must be shell"); 1491 } 1492 } 1493 1494 private void enforceSystem() { 1495 if (!isCallerSystem()) { 1496 throw new SecurityException("Caller must be system"); 1497 } 1498 } 1499 1500 private void enforceResetThrottlingPermission() { 1501 if (isCallerSystem()) { 1502 return; 1503 } 1504 enforceCallingOrSelfPermission( 1505 android.Manifest.permission.RESET_SHORTCUT_MANAGER_THROTTLING, null); 1506 } 1507 1508 private void enforceCallingOrSelfPermission( 1509 @NonNull String permission, @Nullable String message) { 1510 if (isCallerSystem()) { 1511 return; 1512 } 1513 injectEnforceCallingPermission(permission, message); 1514 } 1515 1516 /** 1517 * Somehow overriding ServiceContext.enforceCallingPermission() in the unit tests would confuse 1518 * mockito. So instead we extracted it here and override it in the tests. 1519 */ 1520 @VisibleForTesting 1521 void injectEnforceCallingPermission( 1522 @NonNull String permission, @Nullable String message) { 1523 mContext.enforceCallingPermission(permission, message); 1524 } 1525 1526 private void verifyCaller(@NonNull String packageName, @UserIdInt int userId) { 1527 Preconditions.checkStringNotEmpty(packageName, "packageName"); 1528 1529 if (isCallerSystem()) { 1530 return; // no check 1531 } 1532 1533 final int callingUid = injectBinderCallingUid(); 1534 1535 // Otherwise, make sure the arguments are valid. 1536 if (UserHandle.getUserId(callingUid) != userId) { 1537 throw new SecurityException("Invalid user-ID"); 1538 } 1539 if (injectGetPackageUid(packageName, userId) != callingUid) { 1540 throw new SecurityException("Calling package name mismatch"); 1541 } 1542 Preconditions.checkState(!isEphemeralApp(packageName, userId), 1543 "Ephemeral apps can't use ShortcutManager"); 1544 } 1545 1546 // Overridden in unit tests to execute r synchronously. 1547 void injectPostToHandler(Runnable r) { 1548 mHandler.post(r); 1549 } 1550 1551 void injectRunOnNewThread(Runnable r) { 1552 new Thread(r).start(); 1553 } 1554 1555 /** 1556 * @throws IllegalArgumentException if {@code numShortcuts} is bigger than 1557 * {@link #getMaxActivityShortcuts()}. 1558 */ 1559 void enforceMaxActivityShortcuts(int numShortcuts) { 1560 if (numShortcuts > mMaxShortcuts) { 1561 throw new IllegalArgumentException("Max number of dynamic shortcuts exceeded"); 1562 } 1563 } 1564 1565 /** 1566 * Return the max number of dynamic + manifest shortcuts for each launcher icon. 1567 */ 1568 int getMaxActivityShortcuts() { 1569 return mMaxShortcuts; 1570 } 1571 1572 /** 1573 * - Sends a notification to LauncherApps 1574 * - Write to file 1575 */ 1576 void packageShortcutsChanged(@NonNull String packageName, @UserIdInt int userId) { 1577 notifyListeners(packageName, userId); 1578 scheduleSaveUser(userId); 1579 } 1580 1581 private void notifyListeners(@NonNull String packageName, @UserIdInt int userId) { 1582 if (DEBUG) { 1583 Slog.d(TAG, String.format( 1584 "Shortcut changes: package=%s, user=%d", packageName, userId)); 1585 } 1586 injectPostToHandler(() -> { 1587 try { 1588 final ArrayList<ShortcutChangeListener> copy; 1589 synchronized (mLock) { 1590 if (!isUserUnlockedL(userId)) { 1591 return; 1592 } 1593 1594 copy = new ArrayList<>(mListeners); 1595 } 1596 // Note onShortcutChanged() needs to be called with the system service permissions. 1597 for (int i = copy.size() - 1; i >= 0; i--) { 1598 copy.get(i).onShortcutChanged(packageName, userId); 1599 } 1600 } catch (Exception ignore) { 1601 } 1602 }); 1603 } 1604 1605 /** 1606 * Clean up / validate an incoming shortcut. 1607 * - Make sure all mandatory fields are set. 1608 * - Make sure the intent's extras are persistable, and them to set 1609 * {@link ShortcutInfo#mIntentPersistableExtrases}. Also clear its extras. 1610 * - Clear flags. 1611 */ 1612 private void fixUpIncomingShortcutInfo(@NonNull ShortcutInfo shortcut, boolean forUpdate, 1613 boolean forPinRequest) { 1614 if (shortcut.isReturnedByServer()) { 1615 Log.w(TAG, 1616 "Re-publishing ShortcutInfo returned by server is not supported." 1617 + " Some information such as icon may lost from shortcut."); 1618 } 1619 Preconditions.checkNotNull(shortcut, "Null shortcut detected"); 1620 if (shortcut.getActivity() != null) { 1621 Preconditions.checkState( 1622 shortcut.getPackage().equals(shortcut.getActivity().getPackageName()), 1623 "Cannot publish shortcut: activity " + shortcut.getActivity() + " does not" 1624 + " belong to package " + shortcut.getPackage()); 1625 Preconditions.checkState( 1626 injectIsMainActivity(shortcut.getActivity(), shortcut.getUserId()), 1627 "Cannot publish shortcut: activity " + shortcut.getActivity() + " is not" 1628 + " main activity"); 1629 } 1630 1631 if (!forUpdate) { 1632 shortcut.enforceMandatoryFields(/* forPinned= */ forPinRequest); 1633 if (!forPinRequest) { 1634 Preconditions.checkState(shortcut.getActivity() != null, 1635 "Cannot publish shortcut: target activity is not set"); 1636 } 1637 } 1638 if (shortcut.getIcon() != null) { 1639 ShortcutInfo.validateIcon(shortcut.getIcon()); 1640 } 1641 1642 shortcut.replaceFlags(0); 1643 } 1644 1645 private void fixUpIncomingShortcutInfo(@NonNull ShortcutInfo shortcut, boolean forUpdate) { 1646 fixUpIncomingShortcutInfo(shortcut, forUpdate, /*forPinRequest=*/ false); 1647 } 1648 1649 public void validateShortcutForPinRequest(@NonNull ShortcutInfo shortcut) { 1650 fixUpIncomingShortcutInfo(shortcut, /* forUpdate= */ false, /*forPinRequest=*/ true); 1651 } 1652 1653 /** 1654 * When a shortcut has no target activity, set the default one from the package. 1655 */ 1656 private void fillInDefaultActivity(List<ShortcutInfo> shortcuts) { 1657 ComponentName defaultActivity = null; 1658 for (int i = shortcuts.size() - 1; i >= 0; i--) { 1659 final ShortcutInfo si = shortcuts.get(i); 1660 if (si.getActivity() == null) { 1661 if (defaultActivity == null) { 1662 defaultActivity = injectGetDefaultMainActivity( 1663 si.getPackage(), si.getUserId()); 1664 Preconditions.checkState(defaultActivity != null, 1665 "Launcher activity not found for package " + si.getPackage()); 1666 } 1667 si.setActivity(defaultActivity); 1668 } 1669 } 1670 } 1671 1672 private void assignImplicitRanks(List<ShortcutInfo> shortcuts) { 1673 for (int i = shortcuts.size() - 1; i >= 0; i--) { 1674 shortcuts.get(i).setImplicitRank(i); 1675 } 1676 } 1677 1678 private List<ShortcutInfo> setReturnedByServer(List<ShortcutInfo> shortcuts) { 1679 for (int i = shortcuts.size() - 1; i >= 0; i--) { 1680 shortcuts.get(i).setReturnedByServer(); 1681 } 1682 return shortcuts; 1683 } 1684 1685 // === APIs === 1686 1687 @Override 1688 public boolean setDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList, 1689 @UserIdInt int userId) { 1690 verifyCaller(packageName, userId); 1691 1692 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList(); 1693 final int size = newShortcuts.size(); 1694 1695 synchronized (mLock) { 1696 throwIfUserLockedL(userId); 1697 1698 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId); 1699 1700 ps.ensureImmutableShortcutsNotIncluded(newShortcuts); 1701 1702 fillInDefaultActivity(newShortcuts); 1703 1704 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_SET); 1705 1706 // Throttling. 1707 if (!ps.tryApiCall()) { 1708 return false; 1709 } 1710 1711 // Initialize the implicit ranks for ShortcutPackage.adjustRanks(). 1712 ps.clearAllImplicitRanks(); 1713 assignImplicitRanks(newShortcuts); 1714 1715 for (int i = 0; i < size; i++) { 1716 fixUpIncomingShortcutInfo(newShortcuts.get(i), /* forUpdate= */ false); 1717 } 1718 1719 // First, remove all un-pinned; dynamic shortcuts 1720 ps.deleteAllDynamicShortcuts(); 1721 1722 // Then, add/update all. We need to make sure to take over "pinned" flag. 1723 for (int i = 0; i < size; i++) { 1724 final ShortcutInfo newShortcut = newShortcuts.get(i); 1725 ps.addOrUpdateDynamicShortcut(newShortcut); 1726 } 1727 1728 // Lastly, adjust the ranks. 1729 ps.adjustRanks(); 1730 } 1731 packageShortcutsChanged(packageName, userId); 1732 1733 verifyStates(); 1734 1735 return true; 1736 } 1737 1738 @Override 1739 public boolean updateShortcuts(String packageName, ParceledListSlice shortcutInfoList, 1740 @UserIdInt int userId) { 1741 verifyCaller(packageName, userId); 1742 1743 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList(); 1744 final int size = newShortcuts.size(); 1745 1746 synchronized (mLock) { 1747 throwIfUserLockedL(userId); 1748 1749 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId); 1750 1751 ps.ensureImmutableShortcutsNotIncluded(newShortcuts); 1752 1753 // For update, don't fill in the default activity. Having null activity means 1754 // "don't update the activity" here. 1755 1756 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_UPDATE); 1757 1758 // Throttling. 1759 if (!ps.tryApiCall()) { 1760 return false; 1761 } 1762 1763 // Initialize the implicit ranks for ShortcutPackage.adjustRanks(). 1764 ps.clearAllImplicitRanks(); 1765 assignImplicitRanks(newShortcuts); 1766 1767 for (int i = 0; i < size; i++) { 1768 final ShortcutInfo source = newShortcuts.get(i); 1769 fixUpIncomingShortcutInfo(source, /* forUpdate= */ true); 1770 1771 final ShortcutInfo target = ps.findShortcutById(source.getId()); 1772 if (target == null) { 1773 continue; 1774 } 1775 1776 if (target.isEnabled() != source.isEnabled()) { 1777 Slog.w(TAG, 1778 "ShortcutInfo.enabled cannot be changed with updateShortcuts()"); 1779 } 1780 1781 // When updating the rank, we need to insert between existing ranks, so set 1782 // this setRankChanged, and also copy the implicit rank fo adjustRanks(). 1783 if (source.hasRank()) { 1784 target.setRankChanged(); 1785 target.setImplicitRank(source.getImplicitRank()); 1786 } 1787 1788 final boolean replacingIcon = (source.getIcon() != null); 1789 if (replacingIcon) { 1790 removeIcon(userId, target); 1791 } 1792 1793 // Note copyNonNullFieldsFrom() does the "updatable with?" check too. 1794 target.copyNonNullFieldsFrom(source); 1795 target.setTimestamp(injectCurrentTimeMillis()); 1796 1797 if (replacingIcon) { 1798 saveIconAndFixUpShortcut(userId, target); 1799 } 1800 1801 // When we're updating any resource related fields, re-extract the res names and 1802 // the values. 1803 if (replacingIcon || source.hasStringResources()) { 1804 fixUpShortcutResourceNamesAndValues(target); 1805 } 1806 } 1807 1808 // Lastly, adjust the ranks. 1809 ps.adjustRanks(); 1810 } 1811 packageShortcutsChanged(packageName, userId); 1812 1813 verifyStates(); 1814 1815 return true; 1816 } 1817 1818 @Override 1819 public boolean addDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList, 1820 @UserIdInt int userId) { 1821 verifyCaller(packageName, userId); 1822 1823 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList(); 1824 final int size = newShortcuts.size(); 1825 1826 synchronized (mLock) { 1827 throwIfUserLockedL(userId); 1828 1829 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId); 1830 1831 ps.ensureImmutableShortcutsNotIncluded(newShortcuts); 1832 1833 fillInDefaultActivity(newShortcuts); 1834 1835 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_ADD); 1836 1837 // Initialize the implicit ranks for ShortcutPackage.adjustRanks(). 1838 ps.clearAllImplicitRanks(); 1839 assignImplicitRanks(newShortcuts); 1840 1841 // Throttling. 1842 if (!ps.tryApiCall()) { 1843 return false; 1844 } 1845 for (int i = 0; i < size; i++) { 1846 final ShortcutInfo newShortcut = newShortcuts.get(i); 1847 1848 // Validate the shortcut. 1849 fixUpIncomingShortcutInfo(newShortcut, /* forUpdate= */ false); 1850 1851 // When ranks are changing, we need to insert between ranks, so set the 1852 // "rank changed" flag. 1853 newShortcut.setRankChanged(); 1854 1855 // Add it. 1856 ps.addOrUpdateDynamicShortcut(newShortcut); 1857 } 1858 1859 // Lastly, adjust the ranks. 1860 ps.adjustRanks(); 1861 } 1862 packageShortcutsChanged(packageName, userId); 1863 1864 verifyStates(); 1865 1866 return true; 1867 } 1868 1869 @Override 1870 public boolean requestPinShortcut(String packageName, ShortcutInfo shortcut, 1871 IntentSender resultIntent, int userId) { 1872 Preconditions.checkNotNull(shortcut); 1873 Preconditions.checkArgument(shortcut.isEnabled(), "Shortcut must be enabled"); 1874 return requestPinItem(packageName, userId, shortcut, null, null, resultIntent); 1875 } 1876 1877 @Override 1878 public Intent createShortcutResultIntent(String packageName, ShortcutInfo shortcut, int userId) 1879 throws RemoteException { 1880 Preconditions.checkNotNull(shortcut); 1881 Preconditions.checkArgument(shortcut.isEnabled(), "Shortcut must be enabled"); 1882 verifyCaller(packageName, userId); 1883 1884 final Intent ret; 1885 synchronized (mLock) { 1886 throwIfUserLockedL(userId); 1887 1888 // Send request to the launcher, if supported. 1889 ret = mShortcutRequestPinProcessor.createShortcutResultIntent(shortcut, userId); 1890 } 1891 1892 verifyStates(); 1893 return ret; 1894 } 1895 1896 /** 1897 * Handles {@link #requestPinShortcut} and {@link ShortcutServiceInternal#requestPinAppWidget}. 1898 * After validating the caller, it passes the request to {@link #mShortcutRequestPinProcessor}. 1899 * Either {@param shortcut} or {@param appWidget} should be non-null. 1900 */ 1901 private boolean requestPinItem(String packageName, int userId, ShortcutInfo shortcut, 1902 AppWidgetProviderInfo appWidget, Bundle extras, IntentSender resultIntent) { 1903 verifyCaller(packageName, userId); 1904 1905 final boolean ret; 1906 synchronized (mLock) { 1907 throwIfUserLockedL(userId); 1908 1909 Preconditions.checkState(isUidForegroundLocked(injectBinderCallingUid()), 1910 "Calling application must have a foreground activity or a foreground service"); 1911 1912 // Send request to the launcher, if supported. 1913 ret = mShortcutRequestPinProcessor.requestPinItemLocked(shortcut, appWidget, extras, 1914 userId, resultIntent); 1915 } 1916 1917 verifyStates(); 1918 1919 return ret; 1920 } 1921 1922 @Override 1923 public void disableShortcuts(String packageName, List shortcutIds, 1924 CharSequence disabledMessage, int disabledMessageResId, @UserIdInt int userId) { 1925 verifyCaller(packageName, userId); 1926 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided"); 1927 1928 synchronized (mLock) { 1929 throwIfUserLockedL(userId); 1930 1931 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId); 1932 1933 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds); 1934 1935 final String disabledMessageString = 1936 (disabledMessage == null) ? null : disabledMessage.toString(); 1937 1938 for (int i = shortcutIds.size() - 1; i >= 0; i--) { 1939 ps.disableWithId(Preconditions.checkStringNotEmpty((String) shortcutIds.get(i)), 1940 disabledMessageString, disabledMessageResId, 1941 /* overrideImmutable=*/ false); 1942 } 1943 1944 // We may have removed dynamic shortcuts which may have left a gap, so adjust the ranks. 1945 ps.adjustRanks(); 1946 } 1947 packageShortcutsChanged(packageName, userId); 1948 1949 verifyStates(); 1950 } 1951 1952 @Override 1953 public void enableShortcuts(String packageName, List shortcutIds, @UserIdInt int userId) { 1954 verifyCaller(packageName, userId); 1955 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided"); 1956 1957 synchronized (mLock) { 1958 throwIfUserLockedL(userId); 1959 1960 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId); 1961 1962 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds); 1963 1964 for (int i = shortcutIds.size() - 1; i >= 0; i--) { 1965 ps.enableWithId((String) shortcutIds.get(i)); 1966 } 1967 } 1968 packageShortcutsChanged(packageName, userId); 1969 1970 verifyStates(); 1971 } 1972 1973 @Override 1974 public void removeDynamicShortcuts(String packageName, List shortcutIds, 1975 @UserIdInt int userId) { 1976 verifyCaller(packageName, userId); 1977 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided"); 1978 1979 synchronized (mLock) { 1980 throwIfUserLockedL(userId); 1981 1982 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId); 1983 1984 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds); 1985 1986 for (int i = shortcutIds.size() - 1; i >= 0; i--) { 1987 ps.deleteDynamicWithId( 1988 Preconditions.checkStringNotEmpty((String) shortcutIds.get(i))); 1989 } 1990 1991 // We may have removed dynamic shortcuts which may have left a gap, so adjust the ranks. 1992 ps.adjustRanks(); 1993 } 1994 packageShortcutsChanged(packageName, userId); 1995 1996 verifyStates(); 1997 } 1998 1999 @Override 2000 public void removeAllDynamicShortcuts(String packageName, @UserIdInt int userId) { 2001 verifyCaller(packageName, userId); 2002 2003 synchronized (mLock) { 2004 throwIfUserLockedL(userId); 2005 2006 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId); 2007 ps.deleteAllDynamicShortcuts(); 2008 } 2009 packageShortcutsChanged(packageName, userId); 2010 2011 verifyStates(); 2012 } 2013 2014 @Override 2015 public ParceledListSlice<ShortcutInfo> getDynamicShortcuts(String packageName, 2016 @UserIdInt int userId) { 2017 verifyCaller(packageName, userId); 2018 2019 synchronized (mLock) { 2020 throwIfUserLockedL(userId); 2021 2022 return getShortcutsWithQueryLocked( 2023 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR, 2024 ShortcutInfo::isDynamic); 2025 } 2026 } 2027 2028 @Override 2029 public ParceledListSlice<ShortcutInfo> getManifestShortcuts(String packageName, 2030 @UserIdInt int userId) { 2031 verifyCaller(packageName, userId); 2032 2033 synchronized (mLock) { 2034 throwIfUserLockedL(userId); 2035 2036 return getShortcutsWithQueryLocked( 2037 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR, 2038 ShortcutInfo::isManifestShortcut); 2039 } 2040 } 2041 2042 @Override 2043 public ParceledListSlice<ShortcutInfo> getPinnedShortcuts(String packageName, 2044 @UserIdInt int userId) { 2045 verifyCaller(packageName, userId); 2046 2047 synchronized (mLock) { 2048 throwIfUserLockedL(userId); 2049 2050 return getShortcutsWithQueryLocked( 2051 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR, 2052 ShortcutInfo::isPinned); 2053 } 2054 } 2055 2056 private ParceledListSlice<ShortcutInfo> getShortcutsWithQueryLocked(@NonNull String packageName, 2057 @UserIdInt int userId, int cloneFlags, @NonNull Predicate<ShortcutInfo> query) { 2058 2059 final ArrayList<ShortcutInfo> ret = new ArrayList<>(); 2060 2061 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId); 2062 ps.findAll(ret, query, cloneFlags); 2063 2064 return new ParceledListSlice<>(setReturnedByServer(ret)); 2065 } 2066 2067 @Override 2068 public int getMaxShortcutCountPerActivity(String packageName, @UserIdInt int userId) 2069 throws RemoteException { 2070 verifyCaller(packageName, userId); 2071 2072 return mMaxShortcuts; 2073 } 2074 2075 @Override 2076 public int getRemainingCallCount(String packageName, @UserIdInt int userId) { 2077 verifyCaller(packageName, userId); 2078 2079 synchronized (mLock) { 2080 throwIfUserLockedL(userId); 2081 2082 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId); 2083 return mMaxUpdatesPerInterval - ps.getApiCallCount(); 2084 } 2085 } 2086 2087 @Override 2088 public long getRateLimitResetTime(String packageName, @UserIdInt int userId) { 2089 verifyCaller(packageName, userId); 2090 2091 synchronized (mLock) { 2092 throwIfUserLockedL(userId); 2093 2094 return getNextResetTimeLocked(); 2095 } 2096 } 2097 2098 @Override 2099 public int getIconMaxDimensions(String packageName, int userId) { 2100 verifyCaller(packageName, userId); 2101 2102 synchronized (mLock) { 2103 return mMaxIconDimension; 2104 } 2105 } 2106 2107 @Override 2108 public void reportShortcutUsed(String packageName, String shortcutId, int userId) { 2109 verifyCaller(packageName, userId); 2110 2111 Preconditions.checkNotNull(shortcutId); 2112 2113 if (DEBUG) { 2114 Slog.d(TAG, String.format("reportShortcutUsed: Shortcut %s package %s used on user %d", 2115 shortcutId, packageName, userId)); 2116 } 2117 2118 synchronized (mLock) { 2119 throwIfUserLockedL(userId); 2120 2121 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId); 2122 2123 if (ps.findShortcutById(shortcutId) == null) { 2124 Log.w(TAG, String.format("reportShortcutUsed: package %s doesn't have shortcut %s", 2125 packageName, shortcutId)); 2126 return; 2127 } 2128 } 2129 2130 final long token = injectClearCallingIdentity(); 2131 try { 2132 mUsageStatsManagerInternal.reportShortcutUsage(packageName, shortcutId, userId); 2133 } finally { 2134 injectRestoreCallingIdentity(token); 2135 } 2136 } 2137 2138 @Override 2139 public boolean isRequestPinItemSupported(int callingUserId, int requestType) { 2140 final long token = injectClearCallingIdentity(); 2141 try { 2142 return mShortcutRequestPinProcessor 2143 .isRequestPinItemSupported(callingUserId, requestType); 2144 } finally { 2145 injectRestoreCallingIdentity(token); 2146 } 2147 } 2148 2149 /** 2150 * Reset all throttling, for developer options and command line. Only system/shell can call 2151 * it. 2152 */ 2153 @Override 2154 public void resetThrottling() { 2155 enforceSystemOrShell(); 2156 2157 resetThrottlingInner(getCallingUserId()); 2158 } 2159 2160 void resetThrottlingInner(@UserIdInt int userId) { 2161 synchronized (mLock) { 2162 if (!isUserUnlockedL(userId)) { 2163 Log.w(TAG, "User " + userId + " is locked or not running"); 2164 return; 2165 } 2166 2167 getUserShortcutsLocked(userId).resetThrottling(); 2168 } 2169 scheduleSaveUser(userId); 2170 Slog.i(TAG, "ShortcutManager: throttling counter reset for user " + userId); 2171 } 2172 2173 void resetAllThrottlingInner() { 2174 synchronized (mLock) { 2175 mRawLastResetTime = injectCurrentTimeMillis(); 2176 } 2177 scheduleSaveBaseState(); 2178 Slog.i(TAG, "ShortcutManager: throttling counter reset for all users"); 2179 } 2180 2181 @Override 2182 public void onApplicationActive(String packageName, int userId) { 2183 if (DEBUG) { 2184 Slog.d(TAG, "onApplicationActive: package=" + packageName + " userid=" + userId); 2185 } 2186 enforceResetThrottlingPermission(); 2187 2188 synchronized (mLock) { 2189 if (!isUserUnlockedL(userId)) { 2190 // This is called by system UI, so no need to throw. Just ignore. 2191 return; 2192 } 2193 2194 getPackageShortcutsLocked(packageName, userId) 2195 .resetRateLimitingForCommandLineNoSaving(); 2196 saveUserLocked(userId); 2197 } 2198 } 2199 2200 // We override this method in unit tests to do a simpler check. 2201 boolean hasShortcutHostPermission(@NonNull String callingPackage, int userId) { 2202 final long start = injectElapsedRealtime(); 2203 try { 2204 return hasShortcutHostPermissionInner(callingPackage, userId); 2205 } finally { 2206 logDurationStat(Stats.LAUNCHER_PERMISSION_CHECK, start); 2207 } 2208 } 2209 2210 // This method is extracted so we can directly call this method from unit tests, 2211 // even when hasShortcutPermission() is overridden. 2212 @VisibleForTesting 2213 boolean hasShortcutHostPermissionInner(@NonNull String packageName, int userId) { 2214 synchronized (mLock) { 2215 throwIfUserLockedL(userId); 2216 2217 final ShortcutUser user = getUserShortcutsLocked(userId); 2218 2219 // Always trust the cached component. 2220 final ComponentName cached = user.getCachedLauncher(); 2221 if (cached != null) { 2222 if (cached.getPackageName().equals(packageName)) { 2223 return true; 2224 } 2225 } 2226 // If the cached one doesn't match, then go ahead 2227 2228 final ComponentName detected = getDefaultLauncher(userId); 2229 2230 // Update the cache. 2231 user.setLauncher(detected); 2232 if (detected != null) { 2233 if (DEBUG) { 2234 Slog.v(TAG, "Detected launcher: " + detected); 2235 } 2236 return detected.getPackageName().equals(packageName); 2237 } else { 2238 // Default launcher not found. 2239 return false; 2240 } 2241 } 2242 } 2243 2244 @Nullable 2245 ComponentName getDefaultLauncher(@UserIdInt int userId) { 2246 final long start = injectElapsedRealtime(); 2247 final long token = injectClearCallingIdentity(); 2248 try { 2249 synchronized (mLock) { 2250 throwIfUserLockedL(userId); 2251 2252 final ShortcutUser user = getUserShortcutsLocked(userId); 2253 2254 final List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 2255 2256 // Default launcher from package manager. 2257 final long startGetHomeActivitiesAsUser = injectElapsedRealtime(); 2258 final ComponentName defaultLauncher = mPackageManagerInternal 2259 .getHomeActivitiesAsUser(allHomeCandidates, userId); 2260 logDurationStat(Stats.GET_DEFAULT_HOME, startGetHomeActivitiesAsUser); 2261 2262 ComponentName detected = null; 2263 if (defaultLauncher != null) { 2264 detected = defaultLauncher; 2265 if (DEBUG) { 2266 Slog.v(TAG, "Default launcher from PM: " + detected); 2267 } 2268 } else { 2269 detected = user.getLastKnownLauncher(); 2270 2271 if (detected != null) { 2272 if (injectIsActivityEnabledAndExported(detected, userId)) { 2273 if (DEBUG) { 2274 Slog.v(TAG, "Cached launcher: " + detected); 2275 } 2276 } else { 2277 Slog.w(TAG, "Cached launcher " + detected + " no longer exists"); 2278 detected = null; 2279 user.clearLauncher(); 2280 } 2281 } 2282 } 2283 2284 if (detected == null) { 2285 // If we reach here, that means it's the first check since the user was created, 2286 // and there's already multiple launchers and there's no default set. 2287 // Find the system one with the highest priority. 2288 // (We need to check the priority too because of FallbackHome in Settings.) 2289 // If there's no system launcher yet, then no one can access shortcuts, until 2290 // the user explicitly 2291 final int size = allHomeCandidates.size(); 2292 2293 int lastPriority = Integer.MIN_VALUE; 2294 for (int i = 0; i < size; i++) { 2295 final ResolveInfo ri = allHomeCandidates.get(i); 2296 if (!ri.activityInfo.applicationInfo.isSystemApp()) { 2297 continue; 2298 } 2299 if (DEBUG) { 2300 Slog.d(TAG, String.format("hasShortcutPermissionInner: pkg=%s prio=%d", 2301 ri.activityInfo.getComponentName(), ri.priority)); 2302 } 2303 if (ri.priority < lastPriority) { 2304 continue; 2305 } 2306 detected = ri.activityInfo.getComponentName(); 2307 lastPriority = ri.priority; 2308 } 2309 } 2310 return detected; 2311 } 2312 } finally { 2313 injectRestoreCallingIdentity(token); 2314 logDurationStat(Stats.GET_DEFAULT_LAUNCHER, start); 2315 } 2316 } 2317 2318 // === House keeping === 2319 2320 private void cleanUpPackageForAllLoadedUsers(String packageName, @UserIdInt int packageUserId, 2321 boolean appStillExists) { 2322 synchronized (mLock) { 2323 forEachLoadedUserLocked(user -> 2324 cleanUpPackageLocked(packageName, user.getUserId(), packageUserId, 2325 appStillExists)); 2326 } 2327 } 2328 2329 /** 2330 * Remove all the information associated with a package. This will really remove all the 2331 * information, including the restore information (i.e. it'll remove packages even if they're 2332 * shadow). 2333 * 2334 * This is called when an app is uninstalled, or an app gets "clear data"ed. 2335 */ 2336 @VisibleForTesting 2337 void cleanUpPackageLocked(String packageName, int owningUserId, int packageUserId, 2338 boolean appStillExists) { 2339 final boolean wasUserLoaded = isUserLoadedLocked(owningUserId); 2340 2341 final ShortcutUser user = getUserShortcutsLocked(owningUserId); 2342 boolean doNotify = false; 2343 2344 // First, remove the package from the package list (if the package is a publisher). 2345 if (packageUserId == owningUserId) { 2346 if (user.removePackage(packageName) != null) { 2347 doNotify = true; 2348 } 2349 } 2350 2351 // Also remove from the launcher list (if the package is a launcher). 2352 user.removeLauncher(packageUserId, packageName); 2353 2354 // Then remove pinned shortcuts from all launchers. 2355 user.forAllLaunchers(l -> l.cleanUpPackage(packageName, packageUserId)); 2356 2357 // Now there may be orphan shortcuts because we removed pinned shortcuts at the previous 2358 // step. Remove them too. 2359 user.forAllPackages(p -> p.refreshPinnedFlags()); 2360 2361 scheduleSaveUser(owningUserId); 2362 2363 if (doNotify) { 2364 notifyListeners(packageName, owningUserId); 2365 } 2366 2367 // If the app still exists (i.e. data cleared), we need to re-publish manifest shortcuts. 2368 if (appStillExists && (packageUserId == owningUserId)) { 2369 // This will do the notification and save when needed, so do it after the above 2370 // notifyListeners. 2371 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true); 2372 } 2373 2374 if (!wasUserLoaded) { 2375 // Note this will execute the scheduled save. 2376 unloadUserLocked(owningUserId); 2377 } 2378 } 2379 2380 /** 2381 * Entry point from {@link LauncherApps}. 2382 */ 2383 private class LocalService extends ShortcutServiceInternal { 2384 2385 @Override 2386 public List<ShortcutInfo> getShortcuts(int launcherUserId, 2387 @NonNull String callingPackage, long changedSince, 2388 @Nullable String packageName, @Nullable List<String> shortcutIds, 2389 @Nullable ComponentName componentName, 2390 int queryFlags, int userId) { 2391 final ArrayList<ShortcutInfo> ret = new ArrayList<>(); 2392 2393 final boolean cloneKeyFieldOnly = 2394 ((queryFlags & ShortcutQuery.FLAG_GET_KEY_FIELDS_ONLY) != 0); 2395 final int cloneFlag = cloneKeyFieldOnly ? ShortcutInfo.CLONE_REMOVE_NON_KEY_INFO 2396 : ShortcutInfo.CLONE_REMOVE_FOR_LAUNCHER; 2397 if (packageName == null) { 2398 shortcutIds = null; // LauncherAppsService already threw for it though. 2399 } 2400 2401 synchronized (mLock) { 2402 throwIfUserLockedL(userId); 2403 throwIfUserLockedL(launcherUserId); 2404 2405 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId) 2406 .attemptToRestoreIfNeededAndSave(); 2407 2408 if (packageName != null) { 2409 getShortcutsInnerLocked(launcherUserId, 2410 callingPackage, packageName, shortcutIds, changedSince, 2411 componentName, queryFlags, userId, ret, cloneFlag); 2412 } else { 2413 final List<String> shortcutIdsF = shortcutIds; 2414 getUserShortcutsLocked(userId).forAllPackages(p -> { 2415 getShortcutsInnerLocked(launcherUserId, 2416 callingPackage, p.getPackageName(), shortcutIdsF, changedSince, 2417 componentName, queryFlags, userId, ret, cloneFlag); 2418 }); 2419 } 2420 } 2421 return setReturnedByServer(ret); 2422 } 2423 2424 private void getShortcutsInnerLocked(int launcherUserId, @NonNull String callingPackage, 2425 @Nullable String packageName, @Nullable List<String> shortcutIds, long changedSince, 2426 @Nullable ComponentName componentName, int queryFlags, 2427 int userId, ArrayList<ShortcutInfo> ret, int cloneFlag) { 2428 final ArraySet<String> ids = shortcutIds == null ? null 2429 : new ArraySet<>(shortcutIds); 2430 2431 final ShortcutPackage p = getUserShortcutsLocked(userId) 2432 .getPackageShortcutsIfExists(packageName); 2433 if (p == null) { 2434 return; // No need to instantiate ShortcutPackage. 2435 } 2436 2437 p.findAll(ret, 2438 (ShortcutInfo si) -> { 2439 if (si.getLastChangedTimestamp() < changedSince) { 2440 return false; 2441 } 2442 if (ids != null && !ids.contains(si.getId())) { 2443 return false; 2444 } 2445 if (componentName != null) { 2446 if (si.getActivity() != null 2447 && !si.getActivity().equals(componentName)) { 2448 return false; 2449 } 2450 } 2451 if (((queryFlags & ShortcutQuery.FLAG_GET_DYNAMIC) != 0) 2452 && si.isDynamic()) { 2453 return true; 2454 } 2455 if (((queryFlags & ShortcutQuery.FLAG_GET_PINNED) != 0) 2456 && si.isPinned()) { 2457 return true; 2458 } 2459 if (((queryFlags & ShortcutQuery.FLAG_GET_MANIFEST) != 0) 2460 && si.isManifestShortcut()) { 2461 return true; 2462 } 2463 return false; 2464 }, cloneFlag, callingPackage, launcherUserId); 2465 } 2466 2467 @Override 2468 public boolean isPinnedByCaller(int launcherUserId, @NonNull String callingPackage, 2469 @NonNull String packageName, @NonNull String shortcutId, int userId) { 2470 Preconditions.checkStringNotEmpty(packageName, "packageName"); 2471 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId"); 2472 2473 synchronized (mLock) { 2474 throwIfUserLockedL(userId); 2475 throwIfUserLockedL(launcherUserId); 2476 2477 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId) 2478 .attemptToRestoreIfNeededAndSave(); 2479 2480 final ShortcutInfo si = getShortcutInfoLocked( 2481 launcherUserId, callingPackage, packageName, shortcutId, userId); 2482 return si != null && si.isPinned(); 2483 } 2484 } 2485 2486 private ShortcutInfo getShortcutInfoLocked( 2487 int launcherUserId, @NonNull String callingPackage, 2488 @NonNull String packageName, @NonNull String shortcutId, int userId) { 2489 Preconditions.checkStringNotEmpty(packageName, "packageName"); 2490 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId"); 2491 2492 throwIfUserLockedL(userId); 2493 throwIfUserLockedL(launcherUserId); 2494 2495 final ShortcutPackage p = getUserShortcutsLocked(userId) 2496 .getPackageShortcutsIfExists(packageName); 2497 if (p == null) { 2498 return null; 2499 } 2500 2501 final ArrayList<ShortcutInfo> list = new ArrayList<>(1); 2502 p.findAll(list, 2503 (ShortcutInfo si) -> shortcutId.equals(si.getId()), 2504 /* clone flags=*/ 0, callingPackage, launcherUserId); 2505 return list.size() == 0 ? null : list.get(0); 2506 } 2507 2508 @Override 2509 public void pinShortcuts(int launcherUserId, 2510 @NonNull String callingPackage, @NonNull String packageName, 2511 @NonNull List<String> shortcutIds, int userId) { 2512 // Calling permission must be checked by LauncherAppsImpl. 2513 Preconditions.checkStringNotEmpty(packageName, "packageName"); 2514 Preconditions.checkNotNull(shortcutIds, "shortcutIds"); 2515 2516 synchronized (mLock) { 2517 throwIfUserLockedL(userId); 2518 throwIfUserLockedL(launcherUserId); 2519 2520 final ShortcutLauncher launcher = 2521 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId); 2522 launcher.attemptToRestoreIfNeededAndSave(); 2523 2524 launcher.pinShortcuts(userId, packageName, shortcutIds); 2525 } 2526 packageShortcutsChanged(packageName, userId); 2527 2528 verifyStates(); 2529 } 2530 2531 @Override 2532 public Intent[] createShortcutIntents(int launcherUserId, 2533 @NonNull String callingPackage, 2534 @NonNull String packageName, @NonNull String shortcutId, int userId) { 2535 // Calling permission must be checked by LauncherAppsImpl. 2536 Preconditions.checkStringNotEmpty(packageName, "packageName can't be empty"); 2537 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId can't be empty"); 2538 2539 synchronized (mLock) { 2540 throwIfUserLockedL(userId); 2541 throwIfUserLockedL(launcherUserId); 2542 2543 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId) 2544 .attemptToRestoreIfNeededAndSave(); 2545 2546 // Make sure the shortcut is actually visible to the launcher. 2547 final ShortcutInfo si = getShortcutInfoLocked( 2548 launcherUserId, callingPackage, packageName, shortcutId, userId); 2549 // "si == null" should suffice here, but check the flags too just to make sure. 2550 if (si == null || !si.isEnabled() || !si.isAlive()) { 2551 Log.e(TAG, "Shortcut " + shortcutId + " does not exist or disabled"); 2552 return null; 2553 } 2554 return si.getIntents(); 2555 } 2556 } 2557 2558 @Override 2559 public void addListener(@NonNull ShortcutChangeListener listener) { 2560 synchronized (mLock) { 2561 mListeners.add(Preconditions.checkNotNull(listener)); 2562 } 2563 } 2564 2565 @Override 2566 public int getShortcutIconResId(int launcherUserId, @NonNull String callingPackage, 2567 @NonNull String packageName, @NonNull String shortcutId, int userId) { 2568 Preconditions.checkNotNull(callingPackage, "callingPackage"); 2569 Preconditions.checkNotNull(packageName, "packageName"); 2570 Preconditions.checkNotNull(shortcutId, "shortcutId"); 2571 2572 synchronized (mLock) { 2573 throwIfUserLockedL(userId); 2574 throwIfUserLockedL(launcherUserId); 2575 2576 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId) 2577 .attemptToRestoreIfNeededAndSave(); 2578 2579 final ShortcutPackage p = getUserShortcutsLocked(userId) 2580 .getPackageShortcutsIfExists(packageName); 2581 if (p == null) { 2582 return 0; 2583 } 2584 2585 final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId); 2586 return (shortcutInfo != null && shortcutInfo.hasIconResource()) 2587 ? shortcutInfo.getIconResourceId() : 0; 2588 } 2589 } 2590 2591 @Override 2592 public ParcelFileDescriptor getShortcutIconFd(int launcherUserId, 2593 @NonNull String callingPackage, @NonNull String packageName, 2594 @NonNull String shortcutId, int userId) { 2595 Preconditions.checkNotNull(callingPackage, "callingPackage"); 2596 Preconditions.checkNotNull(packageName, "packageName"); 2597 Preconditions.checkNotNull(shortcutId, "shortcutId"); 2598 2599 synchronized (mLock) { 2600 throwIfUserLockedL(userId); 2601 throwIfUserLockedL(launcherUserId); 2602 2603 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId) 2604 .attemptToRestoreIfNeededAndSave(); 2605 2606 final ShortcutPackage p = getUserShortcutsLocked(userId) 2607 .getPackageShortcutsIfExists(packageName); 2608 if (p == null) { 2609 return null; 2610 } 2611 2612 final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId); 2613 if (shortcutInfo == null || !shortcutInfo.hasIconFile()) { 2614 return null; 2615 } 2616 try { 2617 if (shortcutInfo.getBitmapPath() == null) { 2618 Slog.w(TAG, "null bitmap detected in getShortcutIconFd()"); 2619 return null; 2620 } 2621 return ParcelFileDescriptor.open( 2622 new File(shortcutInfo.getBitmapPath()), 2623 ParcelFileDescriptor.MODE_READ_ONLY); 2624 } catch (FileNotFoundException e) { 2625 Slog.e(TAG, "Icon file not found: " + shortcutInfo.getBitmapPath()); 2626 return null; 2627 } 2628 } 2629 } 2630 2631 @Override 2632 public boolean hasShortcutHostPermission(int launcherUserId, 2633 @NonNull String callingPackage) { 2634 return ShortcutService.this.hasShortcutHostPermission(callingPackage, launcherUserId); 2635 } 2636 2637 @Override 2638 public boolean requestPinAppWidget(@NonNull String callingPackage, 2639 @NonNull AppWidgetProviderInfo appWidget, @Nullable Bundle extras, 2640 @Nullable IntentSender resultIntent, int userId) { 2641 Preconditions.checkNotNull(appWidget); 2642 return requestPinItem(callingPackage, userId, null, appWidget, extras, resultIntent); 2643 } 2644 2645 @Override 2646 public boolean isRequestPinItemSupported(int callingUserId, int requestType) { 2647 return ShortcutService.this.isRequestPinItemSupported(callingUserId, requestType); 2648 } 2649 } 2650 2651 final BroadcastReceiver mReceiver = new BroadcastReceiver() { 2652 @Override 2653 public void onReceive(Context context, Intent intent) { 2654 if (!mBootCompleted.get()) { 2655 return; // Boot not completed, ignore the broadcast. 2656 } 2657 try { 2658 if (Intent.ACTION_LOCALE_CHANGED.equals(intent.getAction())) { 2659 handleLocaleChanged(); 2660 } 2661 } catch (Exception e) { 2662 wtf("Exception in mReceiver.onReceive", e); 2663 } 2664 } 2665 }; 2666 2667 void handleLocaleChanged() { 2668 if (DEBUG) { 2669 Slog.d(TAG, "handleLocaleChanged"); 2670 } 2671 scheduleSaveBaseState(); 2672 2673 synchronized (mLock) { 2674 final long token = injectClearCallingIdentity(); 2675 try { 2676 forEachLoadedUserLocked(user -> user.detectLocaleChange()); 2677 } finally { 2678 injectRestoreCallingIdentity(token); 2679 } 2680 } 2681 } 2682 2683 /** 2684 * Package event callbacks. 2685 */ 2686 @VisibleForTesting 2687 final BroadcastReceiver mPackageMonitor = new BroadcastReceiver() { 2688 @Override 2689 public void onReceive(Context context, Intent intent) { 2690 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL); 2691 if (userId == UserHandle.USER_NULL) { 2692 Slog.w(TAG, "Intent broadcast does not contain user handle: " + intent); 2693 return; 2694 } 2695 2696 final String action = intent.getAction(); 2697 2698 // This is normally called on Handler, so clearCallingIdentity() isn't needed, 2699 // but we still check it in unit tests. 2700 final long token = injectClearCallingIdentity(); 2701 try { 2702 synchronized (mLock) { 2703 if (!isUserUnlockedL(userId)) { 2704 if (DEBUG) { 2705 Slog.d(TAG, "Ignoring package broadcast " + action 2706 + " for locked/stopped user " + userId); 2707 } 2708 return; 2709 } 2710 2711 // Whenever we get one of those package broadcasts, or get 2712 // ACTION_PREFERRED_ACTIVITY_CHANGED, we purge the default launcher cache. 2713 final ShortcutUser user = getUserShortcutsLocked(userId); 2714 user.clearLauncher(); 2715 } 2716 if (Intent.ACTION_PREFERRED_ACTIVITY_CHANGED.equals(action)) { 2717 // Nothing farther to do. 2718 return; 2719 } 2720 2721 final Uri intentUri = intent.getData(); 2722 final String packageName = (intentUri != null) ? intentUri.getSchemeSpecificPart() 2723 : null; 2724 if (packageName == null) { 2725 Slog.w(TAG, "Intent broadcast does not contain package name: " + intent); 2726 return; 2727 } 2728 2729 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); 2730 2731 switch (action) { 2732 case Intent.ACTION_PACKAGE_ADDED: 2733 if (replacing) { 2734 handlePackageUpdateFinished(packageName, userId); 2735 } else { 2736 handlePackageAdded(packageName, userId); 2737 } 2738 break; 2739 case Intent.ACTION_PACKAGE_REMOVED: 2740 if (!replacing) { 2741 handlePackageRemoved(packageName, userId); 2742 } 2743 break; 2744 case Intent.ACTION_PACKAGE_CHANGED: 2745 handlePackageChanged(packageName, userId); 2746 2747 break; 2748 case Intent.ACTION_PACKAGE_DATA_CLEARED: 2749 handlePackageDataCleared(packageName, userId); 2750 break; 2751 } 2752 } catch (Exception e) { 2753 wtf("Exception in mPackageMonitor.onReceive", e); 2754 } finally { 2755 injectRestoreCallingIdentity(token); 2756 } 2757 } 2758 }; 2759 2760 /** 2761 * Called when a user is unlocked. 2762 * - Check all known packages still exist, and otherwise perform cleanup. 2763 * - If a package still exists, check the version code. If it's been updated, may need to 2764 * update timestamps of its shortcuts. 2765 */ 2766 @VisibleForTesting 2767 void checkPackageChanges(@UserIdInt int ownerUserId) { 2768 if (DEBUG) { 2769 Slog.d(TAG, "checkPackageChanges() ownerUserId=" + ownerUserId); 2770 } 2771 if (injectIsSafeModeEnabled()) { 2772 Slog.i(TAG, "Safe mode, skipping checkPackageChanges()"); 2773 return; 2774 } 2775 2776 final long start = injectElapsedRealtime(); 2777 try { 2778 final ArrayList<PackageWithUser> gonePackages = new ArrayList<>(); 2779 2780 synchronized (mLock) { 2781 final ShortcutUser user = getUserShortcutsLocked(ownerUserId); 2782 2783 // Find packages that have been uninstalled. 2784 user.forAllPackageItems(spi -> { 2785 if (spi.getPackageInfo().isShadow()) { 2786 return; // Don't delete shadow information. 2787 } 2788 if (!isPackageInstalled(spi.getPackageName(), spi.getPackageUserId())) { 2789 if (DEBUG) { 2790 Slog.d(TAG, "Uninstalled: " + spi.getPackageName() 2791 + " user " + spi.getPackageUserId()); 2792 } 2793 gonePackages.add(PackageWithUser.of(spi)); 2794 } 2795 }); 2796 if (gonePackages.size() > 0) { 2797 for (int i = gonePackages.size() - 1; i >= 0; i--) { 2798 final PackageWithUser pu = gonePackages.get(i); 2799 cleanUpPackageLocked(pu.packageName, ownerUserId, pu.userId, 2800 /* appStillExists = */ false); 2801 } 2802 } 2803 2804 rescanUpdatedPackagesLocked(ownerUserId, user.getLastAppScanTime()); 2805 } 2806 } finally { 2807 logDurationStat(Stats.CHECK_PACKAGE_CHANGES, start); 2808 } 2809 verifyStates(); 2810 } 2811 2812 private void rescanUpdatedPackagesLocked(@UserIdInt int userId, long lastScanTime) { 2813 final ShortcutUser user = getUserShortcutsLocked(userId); 2814 2815 // Note after each OTA, we'll need to rescan all system apps, as their lastUpdateTime 2816 // is not reliable. 2817 final long now = injectCurrentTimeMillis(); 2818 final boolean afterOta = 2819 !injectBuildFingerprint().equals(user.getLastAppScanOsFingerprint()); 2820 2821 // Then for each installed app, publish manifest shortcuts when needed. 2822 forUpdatedPackages(userId, lastScanTime, afterOta, ai -> { 2823 user.attemptToRestoreIfNeededAndSave(this, ai.packageName, userId); 2824 2825 user.rescanPackageIfNeeded(ai.packageName, /* forceRescan= */ true); 2826 }); 2827 2828 // Write the time just before the scan, because there may be apps that have just 2829 // been updated, and we want to catch them in the next time. 2830 user.setLastAppScanTime(now); 2831 user.setLastAppScanOsFingerprint(injectBuildFingerprint()); 2832 scheduleSaveUser(userId); 2833 } 2834 2835 private void handlePackageAdded(String packageName, @UserIdInt int userId) { 2836 if (DEBUG) { 2837 Slog.d(TAG, String.format("handlePackageAdded: %s user=%d", packageName, userId)); 2838 } 2839 synchronized (mLock) { 2840 final ShortcutUser user = getUserShortcutsLocked(userId); 2841 user.attemptToRestoreIfNeededAndSave(this, packageName, userId); 2842 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true); 2843 } 2844 verifyStates(); 2845 } 2846 2847 private void handlePackageUpdateFinished(String packageName, @UserIdInt int userId) { 2848 if (DEBUG) { 2849 Slog.d(TAG, String.format("handlePackageUpdateFinished: %s user=%d", 2850 packageName, userId)); 2851 } 2852 synchronized (mLock) { 2853 final ShortcutUser user = getUserShortcutsLocked(userId); 2854 user.attemptToRestoreIfNeededAndSave(this, packageName, userId); 2855 2856 if (isPackageInstalled(packageName, userId)) { 2857 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true); 2858 } 2859 } 2860 verifyStates(); 2861 } 2862 2863 private void handlePackageRemoved(String packageName, @UserIdInt int packageUserId) { 2864 if (DEBUG) { 2865 Slog.d(TAG, String.format("handlePackageRemoved: %s user=%d", packageName, 2866 packageUserId)); 2867 } 2868 cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ false); 2869 2870 verifyStates(); 2871 } 2872 2873 private void handlePackageDataCleared(String packageName, int packageUserId) { 2874 if (DEBUG) { 2875 Slog.d(TAG, String.format("handlePackageDataCleared: %s user=%d", packageName, 2876 packageUserId)); 2877 } 2878 cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ true); 2879 2880 verifyStates(); 2881 } 2882 2883 private void handlePackageChanged(String packageName, int packageUserId) { 2884 if (!isPackageInstalled(packageName, packageUserId)) { 2885 // Probably disabled, which is the same thing as uninstalled. 2886 handlePackageRemoved(packageName, packageUserId); 2887 return; 2888 } 2889 if (DEBUG) { 2890 Slog.d(TAG, String.format("handlePackageChanged: %s user=%d", packageName, 2891 packageUserId)); 2892 } 2893 2894 // Activities may be disabled or enabled. Just rescan the package. 2895 synchronized (mLock) { 2896 final ShortcutUser user = getUserShortcutsLocked(packageUserId); 2897 2898 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true); 2899 } 2900 2901 verifyStates(); 2902 } 2903 2904 // === PackageManager interaction === 2905 2906 /** 2907 * Returns {@link PackageInfo} unless it's uninstalled or disabled. 2908 */ 2909 @Nullable 2910 final PackageInfo getPackageInfoWithSignatures(String packageName, @UserIdInt int userId) { 2911 return getPackageInfo(packageName, userId, true); 2912 } 2913 2914 /** 2915 * Returns {@link PackageInfo} unless it's uninstalled or disabled. 2916 */ 2917 @Nullable 2918 final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId) { 2919 return getPackageInfo(packageName, userId, false); 2920 } 2921 2922 int injectGetPackageUid(@NonNull String packageName, @UserIdInt int userId) { 2923 final long token = injectClearCallingIdentity(); 2924 try { 2925 return mIPackageManager.getPackageUid(packageName, PACKAGE_MATCH_FLAGS, userId); 2926 } catch (RemoteException e) { 2927 // Shouldn't happen. 2928 Slog.wtf(TAG, "RemoteException", e); 2929 return -1; 2930 } finally { 2931 injectRestoreCallingIdentity(token); 2932 } 2933 } 2934 2935 /** 2936 * Returns {@link PackageInfo} unless it's uninstalled or disabled. 2937 */ 2938 @Nullable 2939 @VisibleForTesting 2940 final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId, 2941 boolean getSignatures) { 2942 return isInstalledOrNull(injectPackageInfoWithUninstalled( 2943 packageName, userId, getSignatures)); 2944 } 2945 2946 /** 2947 * Do not use directly; this returns uninstalled packages too. 2948 */ 2949 @Nullable 2950 @VisibleForTesting 2951 PackageInfo injectPackageInfoWithUninstalled(String packageName, @UserIdInt int userId, 2952 boolean getSignatures) { 2953 final long start = injectElapsedRealtime(); 2954 final long token = injectClearCallingIdentity(); 2955 try { 2956 return mIPackageManager.getPackageInfo( 2957 packageName, PACKAGE_MATCH_FLAGS 2958 | (getSignatures ? PackageManager.GET_SIGNATURES : 0), userId); 2959 } catch (RemoteException e) { 2960 // Shouldn't happen. 2961 Slog.wtf(TAG, "RemoteException", e); 2962 return null; 2963 } finally { 2964 injectRestoreCallingIdentity(token); 2965 2966 logDurationStat( 2967 (getSignatures ? Stats.GET_PACKAGE_INFO_WITH_SIG : Stats.GET_PACKAGE_INFO), 2968 start); 2969 } 2970 } 2971 2972 /** 2973 * Returns {@link ApplicationInfo} unless it's uninstalled or disabled. 2974 */ 2975 @Nullable 2976 @VisibleForTesting 2977 final ApplicationInfo getApplicationInfo(String packageName, @UserIdInt int userId) { 2978 return isInstalledOrNull(injectApplicationInfoWithUninstalled(packageName, userId)); 2979 } 2980 2981 /** 2982 * Do not use directly; this returns uninstalled packages too. 2983 */ 2984 @Nullable 2985 @VisibleForTesting 2986 ApplicationInfo injectApplicationInfoWithUninstalled( 2987 String packageName, @UserIdInt int userId) { 2988 final long start = injectElapsedRealtime(); 2989 final long token = injectClearCallingIdentity(); 2990 try { 2991 return mIPackageManager.getApplicationInfo(packageName, PACKAGE_MATCH_FLAGS, userId); 2992 } catch (RemoteException e) { 2993 // Shouldn't happen. 2994 Slog.wtf(TAG, "RemoteException", e); 2995 return null; 2996 } finally { 2997 injectRestoreCallingIdentity(token); 2998 2999 logDurationStat(Stats.GET_APPLICATION_INFO, start); 3000 } 3001 } 3002 3003 /** 3004 * Returns {@link ActivityInfo} with its metadata unless it's uninstalled or disabled. 3005 */ 3006 @Nullable 3007 final ActivityInfo getActivityInfoWithMetadata(ComponentName activity, @UserIdInt int userId) { 3008 return isInstalledOrNull(injectGetActivityInfoWithMetadataWithUninstalled( 3009 activity, userId)); 3010 } 3011 3012 /** 3013 * Do not use directly; this returns uninstalled packages too. 3014 */ 3015 @Nullable 3016 @VisibleForTesting 3017 ActivityInfo injectGetActivityInfoWithMetadataWithUninstalled( 3018 ComponentName activity, @UserIdInt int userId) { 3019 final long start = injectElapsedRealtime(); 3020 final long token = injectClearCallingIdentity(); 3021 try { 3022 return mIPackageManager.getActivityInfo(activity, 3023 (PACKAGE_MATCH_FLAGS | PackageManager.GET_META_DATA), userId); 3024 } catch (RemoteException e) { 3025 // Shouldn't happen. 3026 Slog.wtf(TAG, "RemoteException", e); 3027 return null; 3028 } finally { 3029 injectRestoreCallingIdentity(token); 3030 3031 logDurationStat(Stats.GET_ACTIVITY_WITH_METADATA, start); 3032 } 3033 } 3034 3035 /** 3036 * Return all installed and enabled packages. 3037 */ 3038 @NonNull 3039 @VisibleForTesting 3040 final List<PackageInfo> getInstalledPackages(@UserIdInt int userId) { 3041 final long start = injectElapsedRealtime(); 3042 final long token = injectClearCallingIdentity(); 3043 try { 3044 final List<PackageInfo> all = injectGetPackagesWithUninstalled(userId); 3045 3046 all.removeIf(PACKAGE_NOT_INSTALLED); 3047 3048 return all; 3049 } catch (RemoteException e) { 3050 // Shouldn't happen. 3051 Slog.wtf(TAG, "RemoteException", e); 3052 return null; 3053 } finally { 3054 injectRestoreCallingIdentity(token); 3055 3056 logDurationStat(Stats.GET_INSTALLED_PACKAGES, start); 3057 } 3058 } 3059 3060 /** 3061 * Do not use directly; this returns uninstalled packages too. 3062 */ 3063 @NonNull 3064 @VisibleForTesting 3065 List<PackageInfo> injectGetPackagesWithUninstalled(@UserIdInt int userId) 3066 throws RemoteException { 3067 final ParceledListSlice<PackageInfo> parceledList = 3068 mIPackageManager.getInstalledPackages(PACKAGE_MATCH_FLAGS, userId); 3069 if (parceledList == null) { 3070 return Collections.emptyList(); 3071 } 3072 return parceledList.getList(); 3073 } 3074 3075 private void forUpdatedPackages(@UserIdInt int userId, long lastScanTime, boolean afterOta, 3076 Consumer<ApplicationInfo> callback) { 3077 if (DEBUG) { 3078 Slog.d(TAG, "forUpdatedPackages for user " + userId + ", lastScanTime=" + lastScanTime 3079 + " afterOta=" + afterOta); 3080 } 3081 final List<PackageInfo> list = getInstalledPackages(userId); 3082 for (int i = list.size() - 1; i >= 0; i--) { 3083 final PackageInfo pi = list.get(i); 3084 3085 // If the package has been updated since the last scan time, then scan it. 3086 // Also if it's right after an OTA, always re-scan all apps anyway, since the 3087 // shortcut parser might have changed. 3088 if (afterOta || (pi.lastUpdateTime >= lastScanTime)) { 3089 if (DEBUG) { 3090 Slog.d(TAG, "Found updated package " + pi.packageName 3091 + " updateTime=" + pi.lastUpdateTime); 3092 } 3093 callback.accept(pi.applicationInfo); 3094 } 3095 } 3096 } 3097 3098 private boolean isApplicationFlagSet(@NonNull String packageName, int userId, int flags) { 3099 final ApplicationInfo ai = injectApplicationInfoWithUninstalled(packageName, userId); 3100 return (ai != null) && ((ai.flags & flags) == flags); 3101 } 3102 3103 private static boolean isInstalled(@Nullable ApplicationInfo ai) { 3104 return (ai != null) && ai.enabled && (ai.flags & ApplicationInfo.FLAG_INSTALLED) != 0; 3105 } 3106 3107 private static boolean isEphemeralApp(@Nullable ApplicationInfo ai) { 3108 return (ai != null) && ai.isInstantApp(); 3109 } 3110 3111 private static boolean isInstalled(@Nullable PackageInfo pi) { 3112 return (pi != null) && isInstalled(pi.applicationInfo); 3113 } 3114 3115 private static boolean isInstalled(@Nullable ActivityInfo ai) { 3116 return (ai != null) && isInstalled(ai.applicationInfo); 3117 } 3118 3119 private static ApplicationInfo isInstalledOrNull(ApplicationInfo ai) { 3120 return isInstalled(ai) ? ai : null; 3121 } 3122 3123 private static PackageInfo isInstalledOrNull(PackageInfo pi) { 3124 return isInstalled(pi) ? pi : null; 3125 } 3126 3127 private static ActivityInfo isInstalledOrNull(ActivityInfo ai) { 3128 return isInstalled(ai) ? ai : null; 3129 } 3130 3131 boolean isPackageInstalled(String packageName, int userId) { 3132 return getApplicationInfo(packageName, userId) != null; 3133 } 3134 3135 boolean isEphemeralApp(String packageName, int userId) { 3136 return isEphemeralApp(getApplicationInfo(packageName, userId)); 3137 } 3138 3139 @Nullable 3140 XmlResourceParser injectXmlMetaData(ActivityInfo activityInfo, String key) { 3141 return activityInfo.loadXmlMetaData(mContext.getPackageManager(), key); 3142 } 3143 3144 @Nullable 3145 Resources injectGetResourcesForApplicationAsUser(String packageName, int userId) { 3146 final long start = injectElapsedRealtime(); 3147 final long token = injectClearCallingIdentity(); 3148 try { 3149 return mContext.getPackageManager().getResourcesForApplicationAsUser( 3150 packageName, userId); 3151 } catch (NameNotFoundException e) { 3152 Slog.e(TAG, "Resources for package " + packageName + " not found"); 3153 return null; 3154 } finally { 3155 injectRestoreCallingIdentity(token); 3156 3157 logDurationStat(Stats.GET_APPLICATION_RESOURCES, start); 3158 } 3159 } 3160 3161 private Intent getMainActivityIntent() { 3162 final Intent intent = new Intent(Intent.ACTION_MAIN); 3163 intent.addCategory(LAUNCHER_INTENT_CATEGORY); 3164 return intent; 3165 } 3166 3167 /** 3168 * Same as queryIntentActivitiesAsUser, except it makes sure the package is installed, 3169 * and only returns exported activities. 3170 */ 3171 @NonNull 3172 @VisibleForTesting 3173 List<ResolveInfo> queryActivities(@NonNull Intent baseIntent, 3174 @NonNull String packageName, @Nullable ComponentName activity, int userId) { 3175 3176 baseIntent.setPackage(Preconditions.checkNotNull(packageName)); 3177 if (activity != null) { 3178 baseIntent.setComponent(activity); 3179 } 3180 return queryActivities(baseIntent, userId, /* exportedOnly =*/ true); 3181 } 3182 3183 @NonNull 3184 List<ResolveInfo> queryActivities(@NonNull Intent intent, int userId, 3185 boolean exportedOnly) { 3186 final List<ResolveInfo> resolved; 3187 final long token = injectClearCallingIdentity(); 3188 try { 3189 resolved = 3190 mContext.getPackageManager().queryIntentActivitiesAsUser( 3191 intent, PACKAGE_MATCH_FLAGS, userId); 3192 } finally { 3193 injectRestoreCallingIdentity(token); 3194 } 3195 if (resolved == null || resolved.size() == 0) { 3196 return EMPTY_RESOLVE_INFO; 3197 } 3198 // Make sure the package is installed. 3199 if (!isInstalled(resolved.get(0).activityInfo)) { 3200 return EMPTY_RESOLVE_INFO; 3201 } 3202 if (exportedOnly) { 3203 resolved.removeIf(ACTIVITY_NOT_EXPORTED); 3204 } 3205 return resolved; 3206 } 3207 3208 /** 3209 * Return the main activity that is enabled and exported. If multiple activities are found, 3210 * return the first one. 3211 */ 3212 @Nullable 3213 ComponentName injectGetDefaultMainActivity(@NonNull String packageName, int userId) { 3214 final long start = injectElapsedRealtime(); 3215 try { 3216 final List<ResolveInfo> resolved = 3217 queryActivities(getMainActivityIntent(), packageName, null, userId); 3218 return resolved.size() == 0 ? null : resolved.get(0).activityInfo.getComponentName(); 3219 } finally { 3220 logDurationStat(Stats.GET_LAUNCHER_ACTIVITY, start); 3221 } 3222 } 3223 3224 /** 3225 * Return whether an activity is enabled, exported and main. 3226 */ 3227 boolean injectIsMainActivity(@NonNull ComponentName activity, int userId) { 3228 final long start = injectElapsedRealtime(); 3229 try { 3230 if (activity == null) { 3231 wtf("null activity detected"); 3232 return false; 3233 } 3234 if (DUMMY_MAIN_ACTIVITY.equals(activity.getClassName())) { 3235 return true; 3236 } 3237 final List<ResolveInfo> resolved = queryActivities( 3238 getMainActivityIntent(), activity.getPackageName(), activity, userId); 3239 return resolved.size() > 0; 3240 } finally { 3241 logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start); 3242 } 3243 } 3244 3245 /** 3246 * Create a dummy "main activity" component name which is used to create a dynamic shortcut 3247 * with no main activity temporarily. 3248 */ 3249 @NonNull 3250 ComponentName getDummyMainActivity(@NonNull String packageName) { 3251 return new ComponentName(packageName, DUMMY_MAIN_ACTIVITY); 3252 } 3253 3254 boolean isDummyMainActivity(@Nullable ComponentName name) { 3255 return name != null && DUMMY_MAIN_ACTIVITY.equals(name.getClassName()); 3256 } 3257 3258 /** 3259 * Return all the enabled, exported and main activities from a package. 3260 */ 3261 @NonNull 3262 List<ResolveInfo> injectGetMainActivities(@NonNull String packageName, int userId) { 3263 final long start = injectElapsedRealtime(); 3264 try { 3265 return queryActivities(getMainActivityIntent(), packageName, null, userId); 3266 } finally { 3267 logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start); 3268 } 3269 } 3270 3271 /** 3272 * Return whether an activity is enabled and exported. 3273 */ 3274 @VisibleForTesting 3275 boolean injectIsActivityEnabledAndExported( 3276 @NonNull ComponentName activity, @UserIdInt int userId) { 3277 final long start = injectElapsedRealtime(); 3278 try { 3279 return queryActivities(new Intent(), activity.getPackageName(), activity, userId) 3280 .size() > 0; 3281 } finally { 3282 logDurationStat(Stats.IS_ACTIVITY_ENABLED, start); 3283 } 3284 } 3285 3286 /** 3287 * Get the {@link LauncherApps#ACTION_CONFIRM_PIN_SHORTCUT} or 3288 * {@link LauncherApps#ACTION_CONFIRM_PIN_APPWIDGET} activity in a given package depending on 3289 * the requestType. 3290 */ 3291 @Nullable 3292 ComponentName injectGetPinConfirmationActivity(@NonNull String launcherPackageName, 3293 int launcherUserId, int requestType) { 3294 Preconditions.checkNotNull(launcherPackageName); 3295 String action = requestType == LauncherApps.PinItemRequest.REQUEST_TYPE_SHORTCUT ? 3296 LauncherApps.ACTION_CONFIRM_PIN_SHORTCUT : 3297 LauncherApps.ACTION_CONFIRM_PIN_APPWIDGET; 3298 3299 final Intent confirmIntent = new Intent(action).setPackage(launcherPackageName); 3300 final List<ResolveInfo> candidates = queryActivities( 3301 confirmIntent, launcherUserId, /* exportedOnly =*/ false); 3302 for (ResolveInfo ri : candidates) { 3303 return ri.activityInfo.getComponentName(); 3304 } 3305 return null; 3306 } 3307 3308 boolean injectIsSafeModeEnabled() { 3309 final long token = injectClearCallingIdentity(); 3310 try { 3311 return IWindowManager.Stub 3312 .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE)) 3313 .isSafeModeEnabled(); 3314 } catch (RemoteException e) { 3315 return false; // Shouldn't happen though. 3316 } finally { 3317 injectRestoreCallingIdentity(token); 3318 } 3319 } 3320 3321 /** 3322 * If {@code userId} is of a managed profile, return the parent user ID. Otherwise return 3323 * itself. 3324 */ 3325 int getParentOrSelfUserId(int userId) { 3326 final long token = injectClearCallingIdentity(); 3327 try { 3328 final UserInfo parent = mUserManager.getProfileParent(userId); 3329 return (parent != null) ? parent.id : userId; 3330 } finally { 3331 injectRestoreCallingIdentity(token); 3332 } 3333 } 3334 3335 void injectSendIntentSender(IntentSender intentSender, Intent extras) { 3336 if (intentSender == null) { 3337 return; 3338 } 3339 try { 3340 intentSender.sendIntent(mContext, /* code= */ 0, extras, 3341 /* onFinished=*/ null, /* handler= */ null); 3342 } catch (SendIntentException e) { 3343 Slog.w(TAG, "sendIntent failed().", e); 3344 } 3345 } 3346 3347 // === Backup & restore === 3348 3349 boolean shouldBackupApp(String packageName, int userId) { 3350 return isApplicationFlagSet(packageName, userId, ApplicationInfo.FLAG_ALLOW_BACKUP); 3351 } 3352 3353 boolean shouldBackupApp(PackageInfo pi) { 3354 return (pi.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0; 3355 } 3356 3357 @Override 3358 public byte[] getBackupPayload(@UserIdInt int userId) { 3359 enforceSystem(); 3360 if (DEBUG) { 3361 Slog.d(TAG, "Backing up user " + userId); 3362 } 3363 synchronized (mLock) { 3364 if (!isUserUnlockedL(userId)) { 3365 wtf("Can't backup: user " + userId + " is locked or not running"); 3366 return null; 3367 } 3368 3369 final ShortcutUser user = getUserShortcutsLocked(userId); 3370 if (user == null) { 3371 wtf("Can't backup: user not found: id=" + userId); 3372 return null; 3373 } 3374 3375 // Update the signatures for all packages. 3376 user.forAllPackageItems(spi -> spi.refreshPackageSignatureAndSave()); 3377 3378 // Set the version code for the launchers. 3379 // We shouldn't do this for publisher packages, because we don't want to update the 3380 // version code without rescanning the manifest. 3381 user.forAllLaunchers(launcher -> launcher.ensureVersionInfo()); 3382 3383 // Save to the filesystem. 3384 scheduleSaveUser(userId); 3385 saveDirtyInfo(); 3386 3387 // Then create the backup payload. 3388 final ByteArrayOutputStream os = new ByteArrayOutputStream(32 * 1024); 3389 try { 3390 saveUserInternalLocked(userId, os, /* forBackup */ true); 3391 } catch (XmlPullParserException | IOException e) { 3392 // Shouldn't happen. 3393 Slog.w(TAG, "Backup failed.", e); 3394 return null; 3395 } 3396 return os.toByteArray(); 3397 } 3398 } 3399 3400 @Override 3401 public void applyRestore(byte[] payload, @UserIdInt int userId) { 3402 enforceSystem(); 3403 if (DEBUG) { 3404 Slog.d(TAG, "Restoring user " + userId); 3405 } 3406 synchronized (mLock) { 3407 if (!isUserUnlockedL(userId)) { 3408 wtf("Can't restore: user " + userId + " is locked or not running"); 3409 return; 3410 } 3411 // Actually do restore. 3412 final ShortcutUser restored; 3413 final ByteArrayInputStream is = new ByteArrayInputStream(payload); 3414 try { 3415 restored = loadUserInternal(userId, is, /* fromBackup */ true); 3416 } catch (XmlPullParserException | IOException | InvalidFileFormatException e) { 3417 Slog.w(TAG, "Restoration failed.", e); 3418 return; 3419 } 3420 getUserShortcutsLocked(userId).mergeRestoredFile(restored); 3421 3422 // Rescan all packages to re-publish manifest shortcuts and do other checks. 3423 rescanUpdatedPackagesLocked(userId, 3424 0 // lastScanTime = 0; rescan all packages. 3425 ); 3426 3427 saveUserLocked(userId); 3428 } 3429 } 3430 3431 // === Dump === 3432 3433 @Override 3434 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 3435 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return; 3436 dumpNoCheck(fd, pw, args); 3437 } 3438 3439 @VisibleForTesting 3440 void dumpNoCheck(FileDescriptor fd, PrintWriter pw, String[] args) { 3441 boolean checkin = false; 3442 boolean clear = false; 3443 if (args != null) { 3444 for (String arg : args) { 3445 if ("-c".equals(arg)) { 3446 checkin = true; 3447 } else if ("--checkin".equals(arg)) { 3448 checkin = true; 3449 clear = true; 3450 } 3451 } 3452 } 3453 3454 if (checkin) { 3455 dumpCheckin(pw, clear); 3456 } else { 3457 dumpInner(pw); 3458 } 3459 } 3460 3461 private void dumpInner(PrintWriter pw) { 3462 synchronized (mLock) { 3463 final long now = injectCurrentTimeMillis(); 3464 pw.print("Now: ["); 3465 pw.print(now); 3466 pw.print("] "); 3467 pw.print(formatTime(now)); 3468 3469 pw.print(" Raw last reset: ["); 3470 pw.print(mRawLastResetTime); 3471 pw.print("] "); 3472 pw.print(formatTime(mRawLastResetTime)); 3473 3474 final long last = getLastResetTimeLocked(); 3475 pw.print(" Last reset: ["); 3476 pw.print(last); 3477 pw.print("] "); 3478 pw.print(formatTime(last)); 3479 3480 final long next = getNextResetTimeLocked(); 3481 pw.print(" Next reset: ["); 3482 pw.print(next); 3483 pw.print("] "); 3484 pw.print(formatTime(next)); 3485 3486 pw.print(" Config:"); 3487 pw.print(" Max icon dim: "); 3488 pw.println(mMaxIconDimension); 3489 pw.print(" Icon format: "); 3490 pw.println(mIconPersistFormat); 3491 pw.print(" Icon quality: "); 3492 pw.println(mIconPersistQuality); 3493 pw.print(" saveDelayMillis: "); 3494 pw.println(mSaveDelayMillis); 3495 pw.print(" resetInterval: "); 3496 pw.println(mResetInterval); 3497 pw.print(" maxUpdatesPerInterval: "); 3498 pw.println(mMaxUpdatesPerInterval); 3499 pw.print(" maxShortcutsPerActivity: "); 3500 pw.println(mMaxShortcuts); 3501 pw.println(); 3502 3503 pw.println(" Stats:"); 3504 synchronized (mStatLock) { 3505 for (int i = 0; i < Stats.COUNT; i++) { 3506 dumpStatLS(pw, " ", i); 3507 } 3508 } 3509 3510 pw.println(); 3511 pw.print(" #Failures: "); 3512 pw.println(mWtfCount); 3513 3514 if (mLastWtfStacktrace != null) { 3515 pw.print(" Last failure stack trace: "); 3516 pw.println(Log.getStackTraceString(mLastWtfStacktrace)); 3517 } 3518 3519 for (int i = 0; i < mUsers.size(); i++) { 3520 pw.println(); 3521 mUsers.valueAt(i).dump(pw, " "); 3522 } 3523 3524 pw.println(); 3525 pw.println(" UID state:"); 3526 3527 for (int i = 0; i < mUidState.size(); i++) { 3528 final int uid = mUidState.keyAt(i); 3529 final int state = mUidState.valueAt(i); 3530 pw.print(" UID="); 3531 pw.print(uid); 3532 pw.print(" state="); 3533 pw.print(state); 3534 if (isProcessStateForeground(state)) { 3535 pw.print(" [FG]"); 3536 } 3537 pw.print(" last FG="); 3538 pw.print(mUidLastForegroundElapsedTime.get(uid)); 3539 pw.println(); 3540 } 3541 } 3542 } 3543 3544 static String formatTime(long time) { 3545 Time tobj = new Time(); 3546 tobj.set(time); 3547 return tobj.format("%Y-%m-%d %H:%M:%S"); 3548 } 3549 3550 private void dumpStatLS(PrintWriter pw, String prefix, int statId) { 3551 pw.print(prefix); 3552 final int count = mCountStats[statId]; 3553 final long dur = mDurationStats[statId]; 3554 pw.println(String.format("%s: count=%d, total=%dms, avg=%.1fms", 3555 STAT_LABELS[statId], count, dur, 3556 (count == 0 ? 0 : ((double) dur) / count))); 3557 } 3558 3559 /** 3560 * Dumpsys for checkin. 3561 * 3562 * @param clear if true, clear the history information. Some other system services have this 3563 * behavior but shortcut service doesn't for now. 3564 */ 3565 private void dumpCheckin(PrintWriter pw, boolean clear) { 3566 synchronized (mLock) { 3567 try { 3568 final JSONArray users = new JSONArray(); 3569 3570 for (int i = 0; i < mUsers.size(); i++) { 3571 users.put(mUsers.valueAt(i).dumpCheckin(clear)); 3572 } 3573 3574 final JSONObject result = new JSONObject(); 3575 3576 result.put(KEY_SHORTCUT, users); 3577 result.put(KEY_LOW_RAM, injectIsLowRamDevice()); 3578 result.put(KEY_ICON_SIZE, mMaxIconDimension); 3579 3580 pw.println(result.toString(1)); 3581 } catch (JSONException e) { 3582 Slog.e(TAG, "Unable to write in json", e); 3583 } 3584 } 3585 } 3586 3587 // === Shell support === 3588 3589 @Override 3590 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err, 3591 String[] args, ShellCallback callback, ResultReceiver resultReceiver) { 3592 3593 enforceShell(); 3594 3595 final long token = injectClearCallingIdentity(); 3596 try { 3597 final int status = (new MyShellCommand()).exec(this, in, out, err, args, callback, 3598 resultReceiver); 3599 resultReceiver.send(status, null); 3600 } finally { 3601 injectRestoreCallingIdentity(token); 3602 } 3603 } 3604 3605 static class CommandException extends Exception { 3606 public CommandException(String message) { 3607 super(message); 3608 } 3609 } 3610 3611 /** 3612 * Handle "adb shell cmd". 3613 */ 3614 private class MyShellCommand extends ShellCommand { 3615 3616 private int mUserId = UserHandle.USER_SYSTEM; 3617 3618 private void parseOptionsLocked(boolean takeUser) 3619 throws CommandException { 3620 String opt; 3621 while ((opt = getNextOption()) != null) { 3622 switch (opt) { 3623 case "--user": 3624 if (takeUser) { 3625 mUserId = UserHandle.parseUserArg(getNextArgRequired()); 3626 if (!isUserUnlockedL(mUserId)) { 3627 throw new CommandException( 3628 "User " + mUserId + " is not running or locked"); 3629 } 3630 break; 3631 } 3632 // fallthrough 3633 default: 3634 throw new CommandException("Unknown option: " + opt); 3635 } 3636 } 3637 } 3638 3639 @Override 3640 public int onCommand(String cmd) { 3641 if (cmd == null) { 3642 return handleDefaultCommands(cmd); 3643 } 3644 final PrintWriter pw = getOutPrintWriter(); 3645 try { 3646 switch (cmd) { 3647 case "reset-throttling": 3648 handleResetThrottling(); 3649 break; 3650 case "reset-all-throttling": 3651 handleResetAllThrottling(); 3652 break; 3653 case "override-config": 3654 handleOverrideConfig(); 3655 break; 3656 case "reset-config": 3657 handleResetConfig(); 3658 break; 3659 case "clear-default-launcher": 3660 handleClearDefaultLauncher(); 3661 break; 3662 case "get-default-launcher": 3663 handleGetDefaultLauncher(); 3664 break; 3665 case "unload-user": 3666 handleUnloadUser(); 3667 break; 3668 case "clear-shortcuts": 3669 handleClearShortcuts(); 3670 break; 3671 case "verify-states": // hidden command to verify various internal states. 3672 handleVerifyStates(); 3673 break; 3674 default: 3675 return handleDefaultCommands(cmd); 3676 } 3677 } catch (CommandException e) { 3678 pw.println("Error: " + e.getMessage()); 3679 return 1; 3680 } 3681 pw.println("Success"); 3682 return 0; 3683 } 3684 3685 @Override 3686 public void onHelp() { 3687 final PrintWriter pw = getOutPrintWriter(); 3688 pw.println("Usage: cmd shortcut COMMAND [options ...]"); 3689 pw.println(); 3690 pw.println("cmd shortcut reset-throttling [--user USER_ID]"); 3691 pw.println(" Reset throttling for all packages and users"); 3692 pw.println(); 3693 pw.println("cmd shortcut reset-all-throttling"); 3694 pw.println(" Reset the throttling state for all users"); 3695 pw.println(); 3696 pw.println("cmd shortcut override-config CONFIG"); 3697 pw.println(" Override the configuration for testing (will last until reboot)"); 3698 pw.println(); 3699 pw.println("cmd shortcut reset-config"); 3700 pw.println(" Reset the configuration set with \"update-config\""); 3701 pw.println(); 3702 pw.println("cmd shortcut clear-default-launcher [--user USER_ID]"); 3703 pw.println(" Clear the cached default launcher"); 3704 pw.println(); 3705 pw.println("cmd shortcut get-default-launcher [--user USER_ID]"); 3706 pw.println(" Show the default launcher"); 3707 pw.println(); 3708 pw.println("cmd shortcut unload-user [--user USER_ID]"); 3709 pw.println(" Unload a user from the memory"); 3710 pw.println(" (This should not affect any observable behavior)"); 3711 pw.println(); 3712 pw.println("cmd shortcut clear-shortcuts [--user USER_ID] PACKAGE"); 3713 pw.println(" Remove all shortcuts from a package, including pinned shortcuts"); 3714 pw.println(); 3715 } 3716 3717 private void handleResetThrottling() throws CommandException { 3718 synchronized (mLock) { 3719 parseOptionsLocked(/* takeUser =*/ true); 3720 3721 Slog.i(TAG, "cmd: handleResetThrottling: user=" + mUserId); 3722 3723 resetThrottlingInner(mUserId); 3724 } 3725 } 3726 3727 private void handleResetAllThrottling() { 3728 Slog.i(TAG, "cmd: handleResetAllThrottling"); 3729 3730 resetAllThrottlingInner(); 3731 } 3732 3733 private void handleOverrideConfig() throws CommandException { 3734 final String config = getNextArgRequired(); 3735 3736 Slog.i(TAG, "cmd: handleOverrideConfig: " + config); 3737 3738 synchronized (mLock) { 3739 if (!updateConfigurationLocked(config)) { 3740 throw new CommandException("override-config failed. See logcat for details."); 3741 } 3742 } 3743 } 3744 3745 private void handleResetConfig() { 3746 Slog.i(TAG, "cmd: handleResetConfig"); 3747 3748 synchronized (mLock) { 3749 loadConfigurationLocked(); 3750 } 3751 } 3752 3753 private void clearLauncher() { 3754 synchronized (mLock) { 3755 getUserShortcutsLocked(mUserId).forceClearLauncher(); 3756 } 3757 } 3758 3759 private void showLauncher() { 3760 synchronized (mLock) { 3761 // This ensures to set the cached launcher. Package name doesn't matter. 3762 hasShortcutHostPermissionInner("-", mUserId); 3763 3764 getOutPrintWriter().println("Launcher: " 3765 + getUserShortcutsLocked(mUserId).getLastKnownLauncher()); 3766 } 3767 } 3768 3769 private void handleClearDefaultLauncher() throws CommandException { 3770 synchronized (mLock) { 3771 parseOptionsLocked(/* takeUser =*/ true); 3772 3773 clearLauncher(); 3774 } 3775 } 3776 3777 private void handleGetDefaultLauncher() throws CommandException { 3778 synchronized (mLock) { 3779 parseOptionsLocked(/* takeUser =*/ true); 3780 3781 clearLauncher(); 3782 showLauncher(); 3783 } 3784 } 3785 3786 private void handleUnloadUser() throws CommandException { 3787 synchronized (mLock) { 3788 parseOptionsLocked(/* takeUser =*/ true); 3789 3790 Slog.i(TAG, "cmd: handleUnloadUser: user=" + mUserId); 3791 3792 ShortcutService.this.handleStopUser(mUserId); 3793 } 3794 } 3795 3796 private void handleClearShortcuts() throws CommandException { 3797 synchronized (mLock) { 3798 parseOptionsLocked(/* takeUser =*/ true); 3799 final String packageName = getNextArgRequired(); 3800 3801 Slog.i(TAG, "cmd: handleClearShortcuts: user" + mUserId + ", " + packageName); 3802 3803 ShortcutService.this.cleanUpPackageForAllLoadedUsers(packageName, mUserId, 3804 /* appStillExists = */ true); 3805 } 3806 } 3807 3808 private void handleVerifyStates() throws CommandException { 3809 try { 3810 verifyStatesForce(); // This will throw when there's an issue. 3811 } catch (Throwable th) { 3812 throw new CommandException(th.getMessage() + "\n" + Log.getStackTraceString(th)); 3813 } 3814 } 3815 } 3816 3817 // === Unit test support === 3818 3819 // Injection point. 3820 @VisibleForTesting 3821 long injectCurrentTimeMillis() { 3822 return System.currentTimeMillis(); 3823 } 3824 3825 @VisibleForTesting 3826 long injectElapsedRealtime() { 3827 return SystemClock.elapsedRealtime(); 3828 } 3829 3830 // Injection point. 3831 @VisibleForTesting 3832 int injectBinderCallingUid() { 3833 return getCallingUid(); 3834 } 3835 3836 private int getCallingUserId() { 3837 return UserHandle.getUserId(injectBinderCallingUid()); 3838 } 3839 3840 // Injection point. 3841 @VisibleForTesting 3842 long injectClearCallingIdentity() { 3843 return Binder.clearCallingIdentity(); 3844 } 3845 3846 // Injection point. 3847 @VisibleForTesting 3848 void injectRestoreCallingIdentity(long token) { 3849 Binder.restoreCallingIdentity(token); 3850 } 3851 3852 // Injection point. 3853 @VisibleForTesting 3854 String injectBuildFingerprint() { 3855 return Build.FINGERPRINT; 3856 } 3857 3858 final void wtf(String message) { 3859 wtf(message, /* exception= */ null); 3860 } 3861 3862 // Injection point. 3863 void wtf(String message, Throwable e) { 3864 if (e == null) { 3865 e = new RuntimeException("Stacktrace"); 3866 } 3867 synchronized (mLock) { 3868 mWtfCount++; 3869 mLastWtfStacktrace = new Exception("Last failure was logged here:"); 3870 } 3871 Slog.wtf(TAG, message, e); 3872 } 3873 3874 @VisibleForTesting 3875 File injectSystemDataPath() { 3876 return Environment.getDataSystemDirectory(); 3877 } 3878 3879 @VisibleForTesting 3880 File injectUserDataPath(@UserIdInt int userId) { 3881 return new File(Environment.getDataSystemCeDirectory(userId), DIRECTORY_PER_USER); 3882 } 3883 3884 @VisibleForTesting 3885 boolean injectIsLowRamDevice() { 3886 return ActivityManager.isLowRamDeviceStatic(); 3887 } 3888 3889 @VisibleForTesting 3890 void injectRegisterUidObserver(IUidObserver observer, int which) { 3891 try { 3892 ActivityManager.getService().registerUidObserver(observer, which, 3893 ActivityManager.PROCESS_STATE_UNKNOWN, null); 3894 } catch (RemoteException shouldntHappen) { 3895 } 3896 } 3897 3898 File getUserBitmapFilePath(@UserIdInt int userId) { 3899 return new File(injectUserDataPath(userId), DIRECTORY_BITMAPS); 3900 } 3901 3902 @VisibleForTesting 3903 SparseArray<ShortcutUser> getShortcutsForTest() { 3904 return mUsers; 3905 } 3906 3907 @VisibleForTesting 3908 int getMaxShortcutsForTest() { 3909 return mMaxShortcuts; 3910 } 3911 3912 @VisibleForTesting 3913 int getMaxUpdatesPerIntervalForTest() { 3914 return mMaxUpdatesPerInterval; 3915 } 3916 3917 @VisibleForTesting 3918 long getResetIntervalForTest() { 3919 return mResetInterval; 3920 } 3921 3922 @VisibleForTesting 3923 int getMaxIconDimensionForTest() { 3924 return mMaxIconDimension; 3925 } 3926 3927 @VisibleForTesting 3928 CompressFormat getIconPersistFormatForTest() { 3929 return mIconPersistFormat; 3930 } 3931 3932 @VisibleForTesting 3933 int getIconPersistQualityForTest() { 3934 return mIconPersistQuality; 3935 } 3936 3937 @VisibleForTesting 3938 ShortcutPackage getPackageShortcutForTest(String packageName, int userId) { 3939 synchronized (mLock) { 3940 final ShortcutUser user = mUsers.get(userId); 3941 if (user == null) return null; 3942 3943 return user.getAllPackagesForTest().get(packageName); 3944 } 3945 } 3946 3947 @VisibleForTesting 3948 ShortcutInfo getPackageShortcutForTest(String packageName, String shortcutId, int userId) { 3949 synchronized (mLock) { 3950 final ShortcutPackage pkg = getPackageShortcutForTest(packageName, userId); 3951 if (pkg == null) return null; 3952 3953 return pkg.findShortcutById(shortcutId); 3954 } 3955 } 3956 3957 @VisibleForTesting 3958 ShortcutLauncher getLauncherShortcutForTest(String packageName, int userId) { 3959 synchronized (mLock) { 3960 final ShortcutUser user = mUsers.get(userId); 3961 if (user == null) return null; 3962 3963 return user.getAllLaunchersForTest().get(PackageWithUser.of(userId, packageName)); 3964 } 3965 } 3966 3967 @VisibleForTesting 3968 ShortcutRequestPinProcessor getShortcutRequestPinProcessorForTest() { 3969 return mShortcutRequestPinProcessor; 3970 } 3971 3972 /** 3973 * Control whether {@link #verifyStates} should be performed. We always perform it during unit 3974 * tests. 3975 */ 3976 @VisibleForTesting 3977 boolean injectShouldPerformVerification() { 3978 return DEBUG; 3979 } 3980 3981 /** 3982 * Check various internal states and throws if there's any inconsistency. 3983 * This is normally only enabled during unit tests. 3984 */ 3985 final void verifyStates() { 3986 if (injectShouldPerformVerification()) { 3987 verifyStatesInner(); 3988 } 3989 } 3990 3991 private final void verifyStatesForce() { 3992 verifyStatesInner(); 3993 } 3994 3995 private void verifyStatesInner() { 3996 synchronized (mLock) { 3997 forEachLoadedUserLocked(u -> u.forAllPackageItems(ShortcutPackageItem::verifyStates)); 3998 } 3999 } 4000} 4001