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