ShortcutService.java revision 82fb2eb057032bb7f38f547fb3667c7bf2547517
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.ShortcutServiceInternal; 50import android.content.pm.ShortcutServiceInternal.ShortcutChangeListener; 51import android.content.pm.UserInfo; 52import android.content.res.Resources; 53import android.content.res.XmlResourceParser; 54import android.graphics.Bitmap; 55import android.graphics.Bitmap.CompressFormat; 56import android.graphics.Canvas; 57import android.graphics.RectF; 58import android.graphics.drawable.Icon; 59import android.net.Uri; 60import android.os.Binder; 61import android.os.Build; 62import android.os.Bundle; 63import android.os.Environment; 64import android.os.FileUtils; 65import android.os.Handler; 66import android.os.LocaleList; 67import android.os.Looper; 68import android.os.Parcel; 69import android.os.ParcelFileDescriptor; 70import android.os.PersistableBundle; 71import android.os.Process; 72import android.os.RemoteException; 73import android.os.ResultReceiver; 74import android.os.SELinux; 75import android.os.ServiceManager; 76import android.os.ShellCallback; 77import android.os.ShellCommand; 78import android.os.SystemClock; 79import android.os.UserHandle; 80import android.os.UserManager; 81import android.text.TextUtils; 82import android.text.format.Time; 83import android.util.ArraySet; 84import android.util.AtomicFile; 85import android.util.KeyValueListParser; 86import android.util.Log; 87import android.util.Slog; 88import android.util.SparseArray; 89import android.util.SparseBooleanArray; 90import android.util.SparseIntArray; 91import android.util.SparseLongArray; 92import android.util.TypedValue; 93import android.util.Xml; 94import android.view.IWindowManager; 95 96import com.android.internal.annotations.GuardedBy; 97import com.android.internal.annotations.VisibleForTesting; 98import com.android.internal.os.BackgroundThread; 99import com.android.internal.util.FastXmlSerializer; 100import com.android.internal.util.Preconditions; 101import com.android.server.LocalServices; 102import com.android.server.SystemService; 103import com.android.server.pm.ShortcutUser.PackageWithUser; 104 105import libcore.io.IoUtils; 106 107import org.json.JSONArray; 108import org.json.JSONException; 109import org.json.JSONObject; 110import org.xmlpull.v1.XmlPullParser; 111import org.xmlpull.v1.XmlPullParserException; 112import org.xmlpull.v1.XmlSerializer; 113 114import java.io.BufferedInputStream; 115import java.io.BufferedOutputStream; 116import java.io.ByteArrayInputStream; 117import java.io.ByteArrayOutputStream; 118import java.io.File; 119import java.io.FileDescriptor; 120import java.io.FileInputStream; 121import java.io.FileNotFoundException; 122import java.io.FileOutputStream; 123import java.io.IOException; 124import java.io.InputStream; 125import java.io.OutputStream; 126import java.io.PrintWriter; 127import java.lang.annotation.Retention; 128import java.lang.annotation.RetentionPolicy; 129import java.net.URISyntaxException; 130import java.nio.charset.StandardCharsets; 131import java.util.ArrayList; 132import java.util.Collections; 133import java.util.List; 134import java.util.concurrent.atomic.AtomicBoolean; 135import java.util.function.Consumer; 136import java.util.function.Predicate; 137 138/** 139 * TODO: 140 * - getIconMaxWidth()/getIconMaxHeight() should use xdpi and ydpi. 141 * -> But TypedValue.applyDimension() doesn't differentiate x and y..? 142 * 143 * - Detect when already registered instances are passed to APIs again, which might break 144 * internal bitmap handling. 145 */ 146public class ShortcutService extends IShortcutService.Stub { 147 static final String TAG = "ShortcutService"; 148 149 static final boolean DEBUG = false; // STOPSHIP if true 150 static final boolean DEBUG_LOAD = false; // STOPSHIP if true 151 static final boolean DEBUG_PROCSTATE = false; // STOPSHIP if true 152 153 @VisibleForTesting 154 static final long DEFAULT_RESET_INTERVAL_SEC = 24 * 60 * 60; // 1 day 155 156 @VisibleForTesting 157 static final int DEFAULT_MAX_UPDATES_PER_INTERVAL = 10; 158 159 @VisibleForTesting 160 static final int DEFAULT_MAX_SHORTCUTS_PER_APP = 5; 161 162 @VisibleForTesting 163 static final int DEFAULT_MAX_ICON_DIMENSION_DP = 96; 164 165 @VisibleForTesting 166 static final int DEFAULT_MAX_ICON_DIMENSION_LOWRAM_DP = 48; 167 168 @VisibleForTesting 169 static final String DEFAULT_ICON_PERSIST_FORMAT = CompressFormat.PNG.name(); 170 171 @VisibleForTesting 172 static final int DEFAULT_ICON_PERSIST_QUALITY = 100; 173 174 @VisibleForTesting 175 static final int DEFAULT_SAVE_DELAY_MS = 3000; 176 177 @VisibleForTesting 178 static final String FILENAME_BASE_STATE = "shortcut_service.xml"; 179 180 @VisibleForTesting 181 static final String DIRECTORY_PER_USER = "shortcut_service"; 182 183 @VisibleForTesting 184 static final String FILENAME_USER_PACKAGES = "shortcuts.xml"; 185 186 static final String DIRECTORY_BITMAPS = "bitmaps"; 187 188 private static final String TAG_ROOT = "root"; 189 private static final String TAG_LAST_RESET_TIME = "last_reset_time"; 190 191 private static final String ATTR_VALUE = "value"; 192 193 private static final String LAUNCHER_INTENT_CATEGORY = Intent.CATEGORY_LAUNCHER; 194 195 private static final String KEY_SHORTCUT = "shortcut"; 196 private static final String KEY_LOW_RAM = "lowRam"; 197 private static final String KEY_ICON_SIZE = "iconSize"; 198 199 private static final String DUMMY_MAIN_ACTIVITY = "android.__dummy__"; 200 201 @VisibleForTesting 202 interface ConfigConstants { 203 /** 204 * Key name for the save delay, in milliseconds. (int) 205 */ 206 String KEY_SAVE_DELAY_MILLIS = "save_delay_ms"; 207 208 /** 209 * Key name for the throttling reset interval, in seconds. (long) 210 */ 211 String KEY_RESET_INTERVAL_SEC = "reset_interval_sec"; 212 213 /** 214 * Key name for the max number of modifying API calls per app for every interval. (int) 215 */ 216 String KEY_MAX_UPDATES_PER_INTERVAL = "max_updates_per_interval"; 217 218 /** 219 * Key name for the max icon dimensions in DP, for non-low-memory devices. 220 */ 221 String KEY_MAX_ICON_DIMENSION_DP = "max_icon_dimension_dp"; 222 223 /** 224 * Key name for the max icon dimensions in DP, for low-memory devices. 225 */ 226 String KEY_MAX_ICON_DIMENSION_DP_LOWRAM = "max_icon_dimension_dp_lowram"; 227 228 /** 229 * Key name for the max dynamic shortcuts per activity. (int) 230 */ 231 String KEY_MAX_SHORTCUTS = "max_shortcuts"; 232 233 /** 234 * Key name for icon compression quality, 0-100. 235 */ 236 String KEY_ICON_QUALITY = "icon_quality"; 237 238 /** 239 * Key name for icon compression format: "PNG", "JPEG" or "WEBP" 240 */ 241 String KEY_ICON_FORMAT = "icon_format"; 242 } 243 244 final Context mContext; 245 246 private final Object mLock = new Object(); 247 248 private static List<ResolveInfo> EMPTY_RESOLVE_INFO = new ArrayList<>(0); 249 250 // Temporarily reverted to anonymous inner class form due to: b/32554459 251 private static Predicate<ResolveInfo> ACTIVITY_NOT_EXPORTED = new Predicate<ResolveInfo>() { 252 public boolean test(ResolveInfo ri) { 253 return !ri.activityInfo.exported; 254 } 255 }; 256 257 // Temporarily reverted to anonymous inner class form due to: b/32554459 258 private static Predicate<PackageInfo> PACKAGE_NOT_INSTALLED = new Predicate<PackageInfo>() { 259 public boolean test(PackageInfo pi) { 260 return !isInstalled(pi); 261 } 262 }; 263 264 private final Handler mHandler; 265 266 @GuardedBy("mLock") 267 private final ArrayList<ShortcutChangeListener> mListeners = new ArrayList<>(1); 268 269 @GuardedBy("mLock") 270 private long mRawLastResetTime; 271 272 /** 273 * User ID -> UserShortcuts 274 */ 275 @GuardedBy("mLock") 276 private final SparseArray<ShortcutUser> mUsers = new SparseArray<>(); 277 278 /** 279 * Max number of dynamic + manifest shortcuts that each application can have at a time. 280 */ 281 private int mMaxShortcuts; 282 283 /** 284 * Max number of updating API calls that each application can make during the interval. 285 */ 286 int mMaxUpdatesPerInterval; 287 288 /** 289 * Actual throttling-reset interval. By default it's a day. 290 */ 291 private long mResetInterval; 292 293 /** 294 * Icon max width/height in pixels. 295 */ 296 private int mMaxIconDimension; 297 298 private CompressFormat mIconPersistFormat; 299 private int mIconPersistQuality; 300 301 private int mSaveDelayMillis; 302 303 private final IPackageManager mIPackageManager; 304 private final PackageManagerInternal mPackageManagerInternal; 305 private final UserManager mUserManager; 306 private final UsageStatsManagerInternal mUsageStatsManagerInternal; 307 private final ActivityManagerInternal mActivityManagerInternal; 308 309 private final ShortcutRequestPinProcessor mShortcutRequestPinProcessor; 310 311 @GuardedBy("mLock") 312 final SparseIntArray mUidState = new SparseIntArray(); 313 314 @GuardedBy("mLock") 315 final SparseLongArray mUidLastForegroundElapsedTime = new SparseLongArray(); 316 317 @GuardedBy("mLock") 318 private List<Integer> mDirtyUserIds = new ArrayList<>(); 319 320 private final AtomicBoolean mBootCompleted = new AtomicBoolean(); 321 322 private static final int PACKAGE_MATCH_FLAGS = 323 PackageManager.MATCH_DIRECT_BOOT_AWARE 324 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE 325 | PackageManager.MATCH_UNINSTALLED_PACKAGES; 326 327 @GuardedBy("mLock") 328 final SparseBooleanArray mUnlockedUsers = new SparseBooleanArray(); 329 330 // Stats 331 @VisibleForTesting 332 interface Stats { 333 int GET_DEFAULT_HOME = 0; 334 int GET_PACKAGE_INFO = 1; 335 int GET_PACKAGE_INFO_WITH_SIG = 2; 336 int GET_APPLICATION_INFO = 3; 337 int LAUNCHER_PERMISSION_CHECK = 4; 338 int CLEANUP_DANGLING_BITMAPS = 5; 339 int GET_ACTIVITY_WITH_METADATA = 6; 340 int GET_INSTALLED_PACKAGES = 7; 341 int CHECK_PACKAGE_CHANGES = 8; 342 int GET_APPLICATION_RESOURCES = 9; 343 int RESOURCE_NAME_LOOKUP = 10; 344 int GET_LAUNCHER_ACTIVITY = 11; 345 int CHECK_LAUNCHER_ACTIVITY = 12; 346 int IS_ACTIVITY_ENABLED = 13; 347 int PACKAGE_UPDATE_CHECK = 14; 348 int ASYNC_PRELOAD_USER_DELAY = 15; 349 int GET_DEFAULT_LAUNCHER = 16; 350 351 int COUNT = GET_DEFAULT_LAUNCHER + 1; 352 } 353 354 private static final String[] STAT_LABELS = { 355 "getHomeActivities()", 356 "Launcher permission check", 357 "getPackageInfo()", 358 "getPackageInfo(SIG)", 359 "getApplicationInfo", 360 "cleanupDanglingBitmaps", 361 "getActivity+metadata", 362 "getInstalledPackages", 363 "checkPackageChanges", 364 "getApplicationResources", 365 "resourceNameLookup", 366 "getLauncherActivity", 367 "checkLauncherActivity", 368 "isActivityEnabled", 369 "packageUpdateCheck", 370 "asyncPreloadUserDelay", 371 "getDefaultLauncher()" 372 }; 373 374 final Object mStatLock = new Object(); 375 376 @GuardedBy("mStatLock") 377 private final int[] mCountStats = new int[Stats.COUNT]; 378 379 @GuardedBy("mStatLock") 380 private final long[] mDurationStats = new long[Stats.COUNT]; 381 382 private static final int PROCESS_STATE_FOREGROUND_THRESHOLD = 383 ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE; 384 385 static final int OPERATION_SET = 0; 386 static final int OPERATION_ADD = 1; 387 static final int OPERATION_UPDATE = 2; 388 389 /** @hide */ 390 @IntDef(value = { 391 OPERATION_SET, 392 OPERATION_ADD, 393 OPERATION_UPDATE 394 }) 395 @Retention(RetentionPolicy.SOURCE) 396 @interface ShortcutOperation { 397 } 398 399 @GuardedBy("mLock") 400 private int mWtfCount = 0; 401 402 @GuardedBy("mLock") 403 private Exception mLastWtfStacktrace; 404 405 static class InvalidFileFormatException extends Exception { 406 public InvalidFileFormatException(String message, Throwable cause) { 407 super(message, cause); 408 } 409 } 410 411 public ShortcutService(Context context) { 412 this(context, BackgroundThread.get().getLooper(), /*onyForPackgeManagerApis*/ false); 413 } 414 415 @VisibleForTesting 416 ShortcutService(Context context, Looper looper, boolean onlyForPackageManagerApis) { 417 mContext = Preconditions.checkNotNull(context); 418 LocalServices.addService(ShortcutServiceInternal.class, new LocalService()); 419 mHandler = new Handler(looper); 420 mIPackageManager = AppGlobals.getPackageManager(); 421 mPackageManagerInternal = Preconditions.checkNotNull( 422 LocalServices.getService(PackageManagerInternal.class)); 423 mUserManager = Preconditions.checkNotNull(context.getSystemService(UserManager.class)); 424 mUsageStatsManagerInternal = Preconditions.checkNotNull( 425 LocalServices.getService(UsageStatsManagerInternal.class)); 426 mActivityManagerInternal = Preconditions.checkNotNull( 427 LocalServices.getService(ActivityManagerInternal.class)); 428 429 mShortcutRequestPinProcessor = new ShortcutRequestPinProcessor(this, mLock); 430 431 if (onlyForPackageManagerApis) { 432 return; // Don't do anything further. For unit tests only. 433 } 434 435 // Register receivers. 436 437 // We need to set a priority, so let's just not use PackageMonitor for now. 438 // TODO Refactor PackageMonitor to support priorities. 439 final IntentFilter packageFilter = new IntentFilter(); 440 packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED); 441 packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED); 442 packageFilter.addAction(Intent.ACTION_PACKAGE_CHANGED); 443 packageFilter.addAction(Intent.ACTION_PACKAGE_DATA_CLEARED); 444 packageFilter.addDataScheme("package"); 445 packageFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY); 446 mContext.registerReceiverAsUser(mPackageMonitor, UserHandle.ALL, 447 packageFilter, null, mHandler); 448 449 final IntentFilter preferedActivityFilter = new IntentFilter(); 450 preferedActivityFilter.addAction(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 451 preferedActivityFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY); 452 mContext.registerReceiverAsUser(mPackageMonitor, UserHandle.ALL, 453 preferedActivityFilter, null, mHandler); 454 455 final IntentFilter localeFilter = new IntentFilter(); 456 localeFilter.addAction(Intent.ACTION_LOCALE_CHANGED); 457 localeFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY); 458 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, 459 localeFilter, null, mHandler); 460 461 injectRegisterUidObserver(mUidObserver, ActivityManager.UID_OBSERVER_PROCSTATE 462 | ActivityManager.UID_OBSERVER_GONE); 463 } 464 465 void logDurationStat(int statId, long start) { 466 synchronized (mStatLock) { 467 mCountStats[statId]++; 468 mDurationStats[statId] += (injectElapsedRealtime() - start); 469 } 470 } 471 472 public String injectGetLocaleTagsForUser(@UserIdInt int userId) { 473 // TODO This should get the per-user locale. b/30123329 b/30119489 474 return LocaleList.getDefault().toLanguageTags(); 475 } 476 477 final private IUidObserver mUidObserver = new IUidObserver.Stub() { 478 @Override 479 public void onUidStateChanged(int uid, int procState, long procStateSeq) 480 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_ADAPTIVE_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_ADAPTIVE_BITMAP: { 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_ADAPTIVE_BITMAP) { 1391 shortcut.addFlags(ShortcutInfo.FLAG_ADAPTIVE_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 notifyListeners(packageName, userId); 1579 scheduleSaveUser(userId); 1580 } 1581 1582 private void notifyListeners(@NonNull String packageName, @UserIdInt int userId) { 1583 if (DEBUG) { 1584 Slog.d(TAG, String.format( 1585 "Shortcut changes: package=%s, user=%d", packageName, userId)); 1586 } 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 (!isPackageInstalled(packageName, packageUserId)) { 2900 // Probably disabled, which is the same thing as uninstalled. 2901 handlePackageRemoved(packageName, packageUserId); 2902 return; 2903 } 2904 if (DEBUG) { 2905 Slog.d(TAG, String.format("handlePackageChanged: %s user=%d", packageName, 2906 packageUserId)); 2907 } 2908 2909 // Activities may be disabled or enabled. Just rescan the package. 2910 synchronized (mLock) { 2911 final ShortcutUser user = getUserShortcutsLocked(packageUserId); 2912 2913 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true); 2914 } 2915 2916 verifyStates(); 2917 } 2918 2919 // === PackageManager interaction === 2920 2921 /** 2922 * Returns {@link PackageInfo} unless it's uninstalled or disabled. 2923 */ 2924 @Nullable 2925 final PackageInfo getPackageInfoWithSignatures(String packageName, @UserIdInt int userId) { 2926 return getPackageInfo(packageName, userId, true); 2927 } 2928 2929 /** 2930 * Returns {@link PackageInfo} unless it's uninstalled or disabled. 2931 */ 2932 @Nullable 2933 final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId) { 2934 return getPackageInfo(packageName, userId, false); 2935 } 2936 2937 int injectGetPackageUid(@NonNull String packageName, @UserIdInt int userId) { 2938 final long token = injectClearCallingIdentity(); 2939 try { 2940 return mIPackageManager.getPackageUid(packageName, PACKAGE_MATCH_FLAGS, userId); 2941 } catch (RemoteException e) { 2942 // Shouldn't happen. 2943 Slog.wtf(TAG, "RemoteException", e); 2944 return -1; 2945 } finally { 2946 injectRestoreCallingIdentity(token); 2947 } 2948 } 2949 2950 /** 2951 * Returns {@link PackageInfo} unless it's uninstalled or disabled. 2952 */ 2953 @Nullable 2954 @VisibleForTesting 2955 final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId, 2956 boolean getSignatures) { 2957 return isInstalledOrNull(injectPackageInfoWithUninstalled( 2958 packageName, userId, getSignatures)); 2959 } 2960 2961 /** 2962 * Do not use directly; this returns uninstalled packages too. 2963 */ 2964 @Nullable 2965 @VisibleForTesting 2966 PackageInfo injectPackageInfoWithUninstalled(String packageName, @UserIdInt int userId, 2967 boolean getSignatures) { 2968 final long start = injectElapsedRealtime(); 2969 final long token = injectClearCallingIdentity(); 2970 try { 2971 return mIPackageManager.getPackageInfo( 2972 packageName, PACKAGE_MATCH_FLAGS 2973 | (getSignatures ? PackageManager.GET_SIGNATURES : 0), userId); 2974 } catch (RemoteException e) { 2975 // Shouldn't happen. 2976 Slog.wtf(TAG, "RemoteException", e); 2977 return null; 2978 } finally { 2979 injectRestoreCallingIdentity(token); 2980 2981 logDurationStat( 2982 (getSignatures ? Stats.GET_PACKAGE_INFO_WITH_SIG : Stats.GET_PACKAGE_INFO), 2983 start); 2984 } 2985 } 2986 2987 /** 2988 * Returns {@link ApplicationInfo} unless it's uninstalled or disabled. 2989 */ 2990 @Nullable 2991 @VisibleForTesting 2992 final ApplicationInfo getApplicationInfo(String packageName, @UserIdInt int userId) { 2993 return isInstalledOrNull(injectApplicationInfoWithUninstalled(packageName, userId)); 2994 } 2995 2996 /** 2997 * Do not use directly; this returns uninstalled packages too. 2998 */ 2999 @Nullable 3000 @VisibleForTesting 3001 ApplicationInfo injectApplicationInfoWithUninstalled( 3002 String packageName, @UserIdInt int userId) { 3003 final long start = injectElapsedRealtime(); 3004 final long token = injectClearCallingIdentity(); 3005 try { 3006 return mIPackageManager.getApplicationInfo(packageName, PACKAGE_MATCH_FLAGS, userId); 3007 } catch (RemoteException e) { 3008 // Shouldn't happen. 3009 Slog.wtf(TAG, "RemoteException", e); 3010 return null; 3011 } finally { 3012 injectRestoreCallingIdentity(token); 3013 3014 logDurationStat(Stats.GET_APPLICATION_INFO, start); 3015 } 3016 } 3017 3018 /** 3019 * Returns {@link ActivityInfo} with its metadata unless it's uninstalled or disabled. 3020 */ 3021 @Nullable 3022 final ActivityInfo getActivityInfoWithMetadata(ComponentName activity, @UserIdInt int userId) { 3023 return isInstalledOrNull(injectGetActivityInfoWithMetadataWithUninstalled( 3024 activity, userId)); 3025 } 3026 3027 /** 3028 * Do not use directly; this returns uninstalled packages too. 3029 */ 3030 @Nullable 3031 @VisibleForTesting 3032 ActivityInfo injectGetActivityInfoWithMetadataWithUninstalled( 3033 ComponentName activity, @UserIdInt int userId) { 3034 final long start = injectElapsedRealtime(); 3035 final long token = injectClearCallingIdentity(); 3036 try { 3037 return mIPackageManager.getActivityInfo(activity, 3038 (PACKAGE_MATCH_FLAGS | PackageManager.GET_META_DATA), userId); 3039 } catch (RemoteException e) { 3040 // Shouldn't happen. 3041 Slog.wtf(TAG, "RemoteException", e); 3042 return null; 3043 } finally { 3044 injectRestoreCallingIdentity(token); 3045 3046 logDurationStat(Stats.GET_ACTIVITY_WITH_METADATA, start); 3047 } 3048 } 3049 3050 /** 3051 * Return all installed and enabled packages. 3052 */ 3053 @NonNull 3054 @VisibleForTesting 3055 final List<PackageInfo> getInstalledPackages(@UserIdInt int userId) { 3056 final long start = injectElapsedRealtime(); 3057 final long token = injectClearCallingIdentity(); 3058 try { 3059 final List<PackageInfo> all = injectGetPackagesWithUninstalled(userId); 3060 3061 all.removeIf(PACKAGE_NOT_INSTALLED); 3062 3063 return all; 3064 } catch (RemoteException e) { 3065 // Shouldn't happen. 3066 Slog.wtf(TAG, "RemoteException", e); 3067 return null; 3068 } finally { 3069 injectRestoreCallingIdentity(token); 3070 3071 logDurationStat(Stats.GET_INSTALLED_PACKAGES, start); 3072 } 3073 } 3074 3075 /** 3076 * Do not use directly; this returns uninstalled packages too. 3077 */ 3078 @NonNull 3079 @VisibleForTesting 3080 List<PackageInfo> injectGetPackagesWithUninstalled(@UserIdInt int userId) 3081 throws RemoteException { 3082 final ParceledListSlice<PackageInfo> parceledList = 3083 mIPackageManager.getInstalledPackages(PACKAGE_MATCH_FLAGS, userId); 3084 if (parceledList == null) { 3085 return Collections.emptyList(); 3086 } 3087 return parceledList.getList(); 3088 } 3089 3090 private void forUpdatedPackages(@UserIdInt int userId, long lastScanTime, boolean afterOta, 3091 Consumer<ApplicationInfo> callback) { 3092 if (DEBUG) { 3093 Slog.d(TAG, "forUpdatedPackages for user " + userId + ", lastScanTime=" + lastScanTime 3094 + " afterOta=" + afterOta); 3095 } 3096 final List<PackageInfo> list = getInstalledPackages(userId); 3097 for (int i = list.size() - 1; i >= 0; i--) { 3098 final PackageInfo pi = list.get(i); 3099 3100 // If the package has been updated since the last scan time, then scan it. 3101 // Also if it's right after an OTA, always re-scan all apps anyway, since the 3102 // shortcut parser might have changed. 3103 if (afterOta || (pi.lastUpdateTime >= lastScanTime)) { 3104 if (DEBUG) { 3105 Slog.d(TAG, "Found updated package " + pi.packageName 3106 + " updateTime=" + pi.lastUpdateTime); 3107 } 3108 callback.accept(pi.applicationInfo); 3109 } 3110 } 3111 } 3112 3113 private boolean isApplicationFlagSet(@NonNull String packageName, int userId, int flags) { 3114 final ApplicationInfo ai = injectApplicationInfoWithUninstalled(packageName, userId); 3115 return (ai != null) && ((ai.flags & flags) == flags); 3116 } 3117 3118 private static boolean isInstalled(@Nullable ApplicationInfo ai) { 3119 return (ai != null) && ai.enabled && (ai.flags & ApplicationInfo.FLAG_INSTALLED) != 0; 3120 } 3121 3122 private static boolean isEphemeralApp(@Nullable ApplicationInfo ai) { 3123 return (ai != null) && ai.isInstantApp(); 3124 } 3125 3126 private static boolean isInstalled(@Nullable PackageInfo pi) { 3127 return (pi != null) && isInstalled(pi.applicationInfo); 3128 } 3129 3130 private static boolean isInstalled(@Nullable ActivityInfo ai) { 3131 return (ai != null) && isInstalled(ai.applicationInfo); 3132 } 3133 3134 private static ApplicationInfo isInstalledOrNull(ApplicationInfo ai) { 3135 return isInstalled(ai) ? ai : null; 3136 } 3137 3138 private static PackageInfo isInstalledOrNull(PackageInfo pi) { 3139 return isInstalled(pi) ? pi : null; 3140 } 3141 3142 private static ActivityInfo isInstalledOrNull(ActivityInfo ai) { 3143 return isInstalled(ai) ? ai : null; 3144 } 3145 3146 boolean isPackageInstalled(String packageName, int userId) { 3147 return getApplicationInfo(packageName, userId) != null; 3148 } 3149 3150 boolean isEphemeralApp(String packageName, int userId) { 3151 return isEphemeralApp(getApplicationInfo(packageName, userId)); 3152 } 3153 3154 @Nullable 3155 XmlResourceParser injectXmlMetaData(ActivityInfo activityInfo, String key) { 3156 return activityInfo.loadXmlMetaData(mContext.getPackageManager(), key); 3157 } 3158 3159 @Nullable 3160 Resources injectGetResourcesForApplicationAsUser(String packageName, int userId) { 3161 final long start = injectElapsedRealtime(); 3162 final long token = injectClearCallingIdentity(); 3163 try { 3164 return mContext.getPackageManager().getResourcesForApplicationAsUser( 3165 packageName, userId); 3166 } catch (NameNotFoundException e) { 3167 Slog.e(TAG, "Resources for package " + packageName + " not found"); 3168 return null; 3169 } finally { 3170 injectRestoreCallingIdentity(token); 3171 3172 logDurationStat(Stats.GET_APPLICATION_RESOURCES, start); 3173 } 3174 } 3175 3176 private Intent getMainActivityIntent() { 3177 final Intent intent = new Intent(Intent.ACTION_MAIN); 3178 intent.addCategory(LAUNCHER_INTENT_CATEGORY); 3179 return intent; 3180 } 3181 3182 /** 3183 * Same as queryIntentActivitiesAsUser, except it makes sure the package is installed, 3184 * and only returns exported activities. 3185 */ 3186 @NonNull 3187 @VisibleForTesting 3188 List<ResolveInfo> queryActivities(@NonNull Intent baseIntent, 3189 @NonNull String packageName, @Nullable ComponentName activity, int userId) { 3190 3191 baseIntent.setPackage(Preconditions.checkNotNull(packageName)); 3192 if (activity != null) { 3193 baseIntent.setComponent(activity); 3194 } 3195 return queryActivities(baseIntent, userId, /* exportedOnly =*/ true); 3196 } 3197 3198 @NonNull 3199 List<ResolveInfo> queryActivities(@NonNull Intent intent, int userId, 3200 boolean exportedOnly) { 3201 final List<ResolveInfo> resolved; 3202 final long token = injectClearCallingIdentity(); 3203 try { 3204 resolved = 3205 mContext.getPackageManager().queryIntentActivitiesAsUser( 3206 intent, PACKAGE_MATCH_FLAGS, userId); 3207 } finally { 3208 injectRestoreCallingIdentity(token); 3209 } 3210 if (resolved == null || resolved.size() == 0) { 3211 return EMPTY_RESOLVE_INFO; 3212 } 3213 // Make sure the package is installed. 3214 if (!isInstalled(resolved.get(0).activityInfo)) { 3215 return EMPTY_RESOLVE_INFO; 3216 } 3217 if (exportedOnly) { 3218 resolved.removeIf(ACTIVITY_NOT_EXPORTED); 3219 } 3220 return resolved; 3221 } 3222 3223 /** 3224 * Return the main activity that is enabled and exported. If multiple activities are found, 3225 * return the first one. 3226 */ 3227 @Nullable 3228 ComponentName injectGetDefaultMainActivity(@NonNull String packageName, int userId) { 3229 final long start = injectElapsedRealtime(); 3230 try { 3231 final List<ResolveInfo> resolved = 3232 queryActivities(getMainActivityIntent(), packageName, null, userId); 3233 return resolved.size() == 0 ? null : resolved.get(0).activityInfo.getComponentName(); 3234 } finally { 3235 logDurationStat(Stats.GET_LAUNCHER_ACTIVITY, start); 3236 } 3237 } 3238 3239 /** 3240 * Return whether an activity is enabled, exported and main. 3241 */ 3242 boolean injectIsMainActivity(@NonNull ComponentName activity, int userId) { 3243 final long start = injectElapsedRealtime(); 3244 try { 3245 if (activity == null) { 3246 wtf("null activity detected"); 3247 return false; 3248 } 3249 if (DUMMY_MAIN_ACTIVITY.equals(activity.getClassName())) { 3250 return true; 3251 } 3252 final List<ResolveInfo> resolved = queryActivities( 3253 getMainActivityIntent(), activity.getPackageName(), activity, userId); 3254 return resolved.size() > 0; 3255 } finally { 3256 logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start); 3257 } 3258 } 3259 3260 /** 3261 * Create a dummy "main activity" component name which is used to create a dynamic shortcut 3262 * with no main activity temporarily. 3263 */ 3264 @NonNull 3265 ComponentName getDummyMainActivity(@NonNull String packageName) { 3266 return new ComponentName(packageName, DUMMY_MAIN_ACTIVITY); 3267 } 3268 3269 boolean isDummyMainActivity(@Nullable ComponentName name) { 3270 return name != null && DUMMY_MAIN_ACTIVITY.equals(name.getClassName()); 3271 } 3272 3273 /** 3274 * Return all the enabled, exported and main activities from a package. 3275 */ 3276 @NonNull 3277 List<ResolveInfo> injectGetMainActivities(@NonNull String packageName, int userId) { 3278 final long start = injectElapsedRealtime(); 3279 try { 3280 return queryActivities(getMainActivityIntent(), packageName, null, userId); 3281 } finally { 3282 logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start); 3283 } 3284 } 3285 3286 /** 3287 * Return whether an activity is enabled and exported. 3288 */ 3289 @VisibleForTesting 3290 boolean injectIsActivityEnabledAndExported( 3291 @NonNull ComponentName activity, @UserIdInt int userId) { 3292 final long start = injectElapsedRealtime(); 3293 try { 3294 return queryActivities(new Intent(), activity.getPackageName(), activity, userId) 3295 .size() > 0; 3296 } finally { 3297 logDurationStat(Stats.IS_ACTIVITY_ENABLED, start); 3298 } 3299 } 3300 3301 /** 3302 * Get the {@link LauncherApps#ACTION_CONFIRM_PIN_SHORTCUT} or 3303 * {@link LauncherApps#ACTION_CONFIRM_PIN_APPWIDGET} activity in a given package depending on 3304 * the requestType. 3305 */ 3306 @Nullable 3307 ComponentName injectGetPinConfirmationActivity(@NonNull String launcherPackageName, 3308 int launcherUserId, int requestType) { 3309 Preconditions.checkNotNull(launcherPackageName); 3310 String action = requestType == LauncherApps.PinItemRequest.REQUEST_TYPE_SHORTCUT ? 3311 LauncherApps.ACTION_CONFIRM_PIN_SHORTCUT : 3312 LauncherApps.ACTION_CONFIRM_PIN_APPWIDGET; 3313 3314 final Intent confirmIntent = new Intent(action).setPackage(launcherPackageName); 3315 final List<ResolveInfo> candidates = queryActivities( 3316 confirmIntent, launcherUserId, /* exportedOnly =*/ false); 3317 for (ResolveInfo ri : candidates) { 3318 return ri.activityInfo.getComponentName(); 3319 } 3320 return null; 3321 } 3322 3323 boolean injectIsSafeModeEnabled() { 3324 final long token = injectClearCallingIdentity(); 3325 try { 3326 return IWindowManager.Stub 3327 .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE)) 3328 .isSafeModeEnabled(); 3329 } catch (RemoteException e) { 3330 return false; // Shouldn't happen though. 3331 } finally { 3332 injectRestoreCallingIdentity(token); 3333 } 3334 } 3335 3336 /** 3337 * If {@code userId} is of a managed profile, return the parent user ID. Otherwise return 3338 * itself. 3339 */ 3340 int getParentOrSelfUserId(int userId) { 3341 final long token = injectClearCallingIdentity(); 3342 try { 3343 final UserInfo parent = mUserManager.getProfileParent(userId); 3344 return (parent != null) ? parent.id : userId; 3345 } finally { 3346 injectRestoreCallingIdentity(token); 3347 } 3348 } 3349 3350 void injectSendIntentSender(IntentSender intentSender, Intent extras) { 3351 if (intentSender == null) { 3352 return; 3353 } 3354 try { 3355 intentSender.sendIntent(mContext, /* code= */ 0, extras, 3356 /* onFinished=*/ null, /* handler= */ null); 3357 } catch (SendIntentException e) { 3358 Slog.w(TAG, "sendIntent failed().", e); 3359 } 3360 } 3361 3362 // === Backup & restore === 3363 3364 boolean shouldBackupApp(String packageName, int userId) { 3365 return isApplicationFlagSet(packageName, userId, ApplicationInfo.FLAG_ALLOW_BACKUP); 3366 } 3367 3368 boolean shouldBackupApp(PackageInfo pi) { 3369 return (pi.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0; 3370 } 3371 3372 @Override 3373 public byte[] getBackupPayload(@UserIdInt int userId) { 3374 enforceSystem(); 3375 if (DEBUG) { 3376 Slog.d(TAG, "Backing up user " + userId); 3377 } 3378 synchronized (mLock) { 3379 if (!isUserUnlockedL(userId)) { 3380 wtf("Can't backup: user " + userId + " is locked or not running"); 3381 return null; 3382 } 3383 3384 final ShortcutUser user = getUserShortcutsLocked(userId); 3385 if (user == null) { 3386 wtf("Can't backup: user not found: id=" + userId); 3387 return null; 3388 } 3389 3390 // Update the signatures for all packages. 3391 user.forAllPackageItems(spi -> spi.refreshPackageSignatureAndSave()); 3392 3393 // Set the version code for the launchers. 3394 // We shouldn't do this for publisher packages, because we don't want to update the 3395 // version code without rescanning the manifest. 3396 user.forAllLaunchers(launcher -> launcher.ensureVersionInfo()); 3397 3398 // Save to the filesystem. 3399 scheduleSaveUser(userId); 3400 saveDirtyInfo(); 3401 3402 // Then create the backup payload. 3403 final ByteArrayOutputStream os = new ByteArrayOutputStream(32 * 1024); 3404 try { 3405 saveUserInternalLocked(userId, os, /* forBackup */ true); 3406 } catch (XmlPullParserException | IOException e) { 3407 // Shouldn't happen. 3408 Slog.w(TAG, "Backup failed.", e); 3409 return null; 3410 } 3411 return os.toByteArray(); 3412 } 3413 } 3414 3415 @Override 3416 public void applyRestore(byte[] payload, @UserIdInt int userId) { 3417 enforceSystem(); 3418 if (DEBUG) { 3419 Slog.d(TAG, "Restoring user " + userId); 3420 } 3421 synchronized (mLock) { 3422 if (!isUserUnlockedL(userId)) { 3423 wtf("Can't restore: user " + userId + " is locked or not running"); 3424 return; 3425 } 3426 // Actually do restore. 3427 final ShortcutUser restored; 3428 final ByteArrayInputStream is = new ByteArrayInputStream(payload); 3429 try { 3430 restored = loadUserInternal(userId, is, /* fromBackup */ true); 3431 } catch (XmlPullParserException | IOException | InvalidFileFormatException e) { 3432 Slog.w(TAG, "Restoration failed.", e); 3433 return; 3434 } 3435 getUserShortcutsLocked(userId).mergeRestoredFile(restored); 3436 3437 // Rescan all packages to re-publish manifest shortcuts and do other checks. 3438 rescanUpdatedPackagesLocked(userId, 3439 0 // lastScanTime = 0; rescan all packages. 3440 ); 3441 3442 saveUserLocked(userId); 3443 } 3444 } 3445 3446 // === Dump === 3447 3448 @Override 3449 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 3450 enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, 3451 "can't dump by this caller"); 3452 boolean checkin = false; 3453 boolean clear = false; 3454 if (args != null) { 3455 for (String arg : args) { 3456 if ("-c".equals(arg)) { 3457 checkin = true; 3458 } else if ("--checkin".equals(arg)) { 3459 checkin = true; 3460 clear = true; 3461 } 3462 } 3463 } 3464 3465 if (checkin) { 3466 dumpCheckin(pw, clear); 3467 } else { 3468 dumpInner(pw); 3469 } 3470 } 3471 3472 private void dumpInner(PrintWriter pw) { 3473 synchronized (mLock) { 3474 final long now = injectCurrentTimeMillis(); 3475 pw.print("Now: ["); 3476 pw.print(now); 3477 pw.print("] "); 3478 pw.print(formatTime(now)); 3479 3480 pw.print(" Raw last reset: ["); 3481 pw.print(mRawLastResetTime); 3482 pw.print("] "); 3483 pw.print(formatTime(mRawLastResetTime)); 3484 3485 final long last = getLastResetTimeLocked(); 3486 pw.print(" Last reset: ["); 3487 pw.print(last); 3488 pw.print("] "); 3489 pw.print(formatTime(last)); 3490 3491 final long next = getNextResetTimeLocked(); 3492 pw.print(" Next reset: ["); 3493 pw.print(next); 3494 pw.print("] "); 3495 pw.print(formatTime(next)); 3496 3497 pw.print(" Config:"); 3498 pw.print(" Max icon dim: "); 3499 pw.println(mMaxIconDimension); 3500 pw.print(" Icon format: "); 3501 pw.println(mIconPersistFormat); 3502 pw.print(" Icon quality: "); 3503 pw.println(mIconPersistQuality); 3504 pw.print(" saveDelayMillis: "); 3505 pw.println(mSaveDelayMillis); 3506 pw.print(" resetInterval: "); 3507 pw.println(mResetInterval); 3508 pw.print(" maxUpdatesPerInterval: "); 3509 pw.println(mMaxUpdatesPerInterval); 3510 pw.print(" maxShortcutsPerActivity: "); 3511 pw.println(mMaxShortcuts); 3512 pw.println(); 3513 3514 pw.println(" Stats:"); 3515 synchronized (mStatLock) { 3516 for (int i = 0; i < Stats.COUNT; i++) { 3517 dumpStatLS(pw, " ", i); 3518 } 3519 } 3520 3521 pw.println(); 3522 pw.print(" #Failures: "); 3523 pw.println(mWtfCount); 3524 3525 if (mLastWtfStacktrace != null) { 3526 pw.print(" Last failure stack trace: "); 3527 pw.println(Log.getStackTraceString(mLastWtfStacktrace)); 3528 } 3529 3530 for (int i = 0; i < mUsers.size(); i++) { 3531 pw.println(); 3532 mUsers.valueAt(i).dump(pw, " "); 3533 } 3534 3535 pw.println(); 3536 pw.println(" UID state:"); 3537 3538 for (int i = 0; i < mUidState.size(); i++) { 3539 final int uid = mUidState.keyAt(i); 3540 final int state = mUidState.valueAt(i); 3541 pw.print(" UID="); 3542 pw.print(uid); 3543 pw.print(" state="); 3544 pw.print(state); 3545 if (isProcessStateForeground(state)) { 3546 pw.print(" [FG]"); 3547 } 3548 pw.print(" last FG="); 3549 pw.print(mUidLastForegroundElapsedTime.get(uid)); 3550 pw.println(); 3551 } 3552 } 3553 } 3554 3555 static String formatTime(long time) { 3556 Time tobj = new Time(); 3557 tobj.set(time); 3558 return tobj.format("%Y-%m-%d %H:%M:%S"); 3559 } 3560 3561 private void dumpStatLS(PrintWriter pw, String prefix, int statId) { 3562 pw.print(prefix); 3563 final int count = mCountStats[statId]; 3564 final long dur = mDurationStats[statId]; 3565 pw.println(String.format("%s: count=%d, total=%dms, avg=%.1fms", 3566 STAT_LABELS[statId], count, dur, 3567 (count == 0 ? 0 : ((double) dur) / count))); 3568 } 3569 3570 /** 3571 * Dumpsys for checkin. 3572 * 3573 * @param clear if true, clear the history information. Some other system services have this 3574 * behavior but shortcut service doesn't for now. 3575 */ 3576 private void dumpCheckin(PrintWriter pw, boolean clear) { 3577 synchronized (mLock) { 3578 try { 3579 final JSONArray users = new JSONArray(); 3580 3581 for (int i = 0; i < mUsers.size(); i++) { 3582 users.put(mUsers.valueAt(i).dumpCheckin(clear)); 3583 } 3584 3585 final JSONObject result = new JSONObject(); 3586 3587 result.put(KEY_SHORTCUT, users); 3588 result.put(KEY_LOW_RAM, injectIsLowRamDevice()); 3589 result.put(KEY_ICON_SIZE, mMaxIconDimension); 3590 3591 pw.println(result.toString(1)); 3592 } catch (JSONException e) { 3593 Slog.e(TAG, "Unable to write in json", e); 3594 } 3595 } 3596 } 3597 3598 // === Shell support === 3599 3600 @Override 3601 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err, 3602 String[] args, ShellCallback callback, ResultReceiver resultReceiver) { 3603 3604 enforceShell(); 3605 3606 final long token = injectClearCallingIdentity(); 3607 try { 3608 final int status = (new MyShellCommand()).exec(this, in, out, err, args, callback, 3609 resultReceiver); 3610 resultReceiver.send(status, null); 3611 } finally { 3612 injectRestoreCallingIdentity(token); 3613 } 3614 } 3615 3616 static class CommandException extends Exception { 3617 public CommandException(String message) { 3618 super(message); 3619 } 3620 } 3621 3622 /** 3623 * Handle "adb shell cmd". 3624 */ 3625 private class MyShellCommand extends ShellCommand { 3626 3627 private int mUserId = UserHandle.USER_SYSTEM; 3628 3629 private void parseOptionsLocked(boolean takeUser) 3630 throws CommandException { 3631 String opt; 3632 while ((opt = getNextOption()) != null) { 3633 switch (opt) { 3634 case "--user": 3635 if (takeUser) { 3636 mUserId = UserHandle.parseUserArg(getNextArgRequired()); 3637 if (!isUserUnlockedL(mUserId)) { 3638 throw new CommandException( 3639 "User " + mUserId + " is not running or locked"); 3640 } 3641 break; 3642 } 3643 // fallthrough 3644 default: 3645 throw new CommandException("Unknown option: " + opt); 3646 } 3647 } 3648 } 3649 3650 @Override 3651 public int onCommand(String cmd) { 3652 if (cmd == null) { 3653 return handleDefaultCommands(cmd); 3654 } 3655 final PrintWriter pw = getOutPrintWriter(); 3656 try { 3657 switch (cmd) { 3658 case "reset-throttling": 3659 handleResetThrottling(); 3660 break; 3661 case "reset-all-throttling": 3662 handleResetAllThrottling(); 3663 break; 3664 case "override-config": 3665 handleOverrideConfig(); 3666 break; 3667 case "reset-config": 3668 handleResetConfig(); 3669 break; 3670 case "clear-default-launcher": 3671 handleClearDefaultLauncher(); 3672 break; 3673 case "get-default-launcher": 3674 handleGetDefaultLauncher(); 3675 break; 3676 case "unload-user": 3677 handleUnloadUser(); 3678 break; 3679 case "clear-shortcuts": 3680 handleClearShortcuts(); 3681 break; 3682 case "verify-states": // hidden command to verify various internal states. 3683 handleVerifyStates(); 3684 break; 3685 default: 3686 return handleDefaultCommands(cmd); 3687 } 3688 } catch (CommandException e) { 3689 pw.println("Error: " + e.getMessage()); 3690 return 1; 3691 } 3692 pw.println("Success"); 3693 return 0; 3694 } 3695 3696 @Override 3697 public void onHelp() { 3698 final PrintWriter pw = getOutPrintWriter(); 3699 pw.println("Usage: cmd shortcut COMMAND [options ...]"); 3700 pw.println(); 3701 pw.println("cmd shortcut reset-throttling [--user USER_ID]"); 3702 pw.println(" Reset throttling for all packages and users"); 3703 pw.println(); 3704 pw.println("cmd shortcut reset-all-throttling"); 3705 pw.println(" Reset the throttling state for all users"); 3706 pw.println(); 3707 pw.println("cmd shortcut override-config CONFIG"); 3708 pw.println(" Override the configuration for testing (will last until reboot)"); 3709 pw.println(); 3710 pw.println("cmd shortcut reset-config"); 3711 pw.println(" Reset the configuration set with \"update-config\""); 3712 pw.println(); 3713 pw.println("cmd shortcut clear-default-launcher [--user USER_ID]"); 3714 pw.println(" Clear the cached default launcher"); 3715 pw.println(); 3716 pw.println("cmd shortcut get-default-launcher [--user USER_ID]"); 3717 pw.println(" Show the default launcher"); 3718 pw.println(); 3719 pw.println("cmd shortcut unload-user [--user USER_ID]"); 3720 pw.println(" Unload a user from the memory"); 3721 pw.println(" (This should not affect any observable behavior)"); 3722 pw.println(); 3723 pw.println("cmd shortcut clear-shortcuts [--user USER_ID] PACKAGE"); 3724 pw.println(" Remove all shortcuts from a package, including pinned shortcuts"); 3725 pw.println(); 3726 } 3727 3728 private void handleResetThrottling() throws CommandException { 3729 synchronized (mLock) { 3730 parseOptionsLocked(/* takeUser =*/ true); 3731 3732 Slog.i(TAG, "cmd: handleResetThrottling: user=" + mUserId); 3733 3734 resetThrottlingInner(mUserId); 3735 } 3736 } 3737 3738 private void handleResetAllThrottling() { 3739 Slog.i(TAG, "cmd: handleResetAllThrottling"); 3740 3741 resetAllThrottlingInner(); 3742 } 3743 3744 private void handleOverrideConfig() throws CommandException { 3745 final String config = getNextArgRequired(); 3746 3747 Slog.i(TAG, "cmd: handleOverrideConfig: " + config); 3748 3749 synchronized (mLock) { 3750 if (!updateConfigurationLocked(config)) { 3751 throw new CommandException("override-config failed. See logcat for details."); 3752 } 3753 } 3754 } 3755 3756 private void handleResetConfig() { 3757 Slog.i(TAG, "cmd: handleResetConfig"); 3758 3759 synchronized (mLock) { 3760 loadConfigurationLocked(); 3761 } 3762 } 3763 3764 private void clearLauncher() { 3765 synchronized (mLock) { 3766 getUserShortcutsLocked(mUserId).forceClearLauncher(); 3767 } 3768 } 3769 3770 private void showLauncher() { 3771 synchronized (mLock) { 3772 // This ensures to set the cached launcher. Package name doesn't matter. 3773 hasShortcutHostPermissionInner("-", mUserId); 3774 3775 getOutPrintWriter().println("Launcher: " 3776 + getUserShortcutsLocked(mUserId).getLastKnownLauncher()); 3777 } 3778 } 3779 3780 private void handleClearDefaultLauncher() throws CommandException { 3781 synchronized (mLock) { 3782 parseOptionsLocked(/* takeUser =*/ true); 3783 3784 clearLauncher(); 3785 } 3786 } 3787 3788 private void handleGetDefaultLauncher() throws CommandException { 3789 synchronized (mLock) { 3790 parseOptionsLocked(/* takeUser =*/ true); 3791 3792 clearLauncher(); 3793 showLauncher(); 3794 } 3795 } 3796 3797 private void handleUnloadUser() throws CommandException { 3798 synchronized (mLock) { 3799 parseOptionsLocked(/* takeUser =*/ true); 3800 3801 Slog.i(TAG, "cmd: handleUnloadUser: user=" + mUserId); 3802 3803 ShortcutService.this.handleCleanupUser(mUserId); 3804 } 3805 } 3806 3807 private void handleClearShortcuts() throws CommandException { 3808 synchronized (mLock) { 3809 parseOptionsLocked(/* takeUser =*/ true); 3810 final String packageName = getNextArgRequired(); 3811 3812 Slog.i(TAG, "cmd: handleClearShortcuts: user" + mUserId + ", " + packageName); 3813 3814 ShortcutService.this.cleanUpPackageForAllLoadedUsers(packageName, mUserId, 3815 /* appStillExists = */ true); 3816 } 3817 } 3818 3819 private void handleVerifyStates() throws CommandException { 3820 try { 3821 verifyStatesForce(); // This will throw when there's an issue. 3822 } catch (Throwable th) { 3823 throw new CommandException(th.getMessage() + "\n" + Log.getStackTraceString(th)); 3824 } 3825 } 3826 } 3827 3828 // === Unit test support === 3829 3830 // Injection point. 3831 @VisibleForTesting 3832 long injectCurrentTimeMillis() { 3833 return System.currentTimeMillis(); 3834 } 3835 3836 @VisibleForTesting 3837 long injectElapsedRealtime() { 3838 return SystemClock.elapsedRealtime(); 3839 } 3840 3841 // Injection point. 3842 @VisibleForTesting 3843 int injectBinderCallingUid() { 3844 return getCallingUid(); 3845 } 3846 3847 private int getCallingUserId() { 3848 return UserHandle.getUserId(injectBinderCallingUid()); 3849 } 3850 3851 // Injection point. 3852 @VisibleForTesting 3853 long injectClearCallingIdentity() { 3854 return Binder.clearCallingIdentity(); 3855 } 3856 3857 // Injection point. 3858 @VisibleForTesting 3859 void injectRestoreCallingIdentity(long token) { 3860 Binder.restoreCallingIdentity(token); 3861 } 3862 3863 // Injection point. 3864 @VisibleForTesting 3865 String injectBuildFingerprint() { 3866 return Build.FINGERPRINT; 3867 } 3868 3869 final void wtf(String message) { 3870 wtf(message, /* exception= */ null); 3871 } 3872 3873 // Injection point. 3874 void wtf(String message, Throwable e) { 3875 if (e == null) { 3876 e = new RuntimeException("Stacktrace"); 3877 } 3878 synchronized (mLock) { 3879 mWtfCount++; 3880 mLastWtfStacktrace = new Exception("Last failure was logged here:"); 3881 } 3882 Slog.wtf(TAG, message, e); 3883 } 3884 3885 @VisibleForTesting 3886 File injectSystemDataPath() { 3887 return Environment.getDataSystemDirectory(); 3888 } 3889 3890 @VisibleForTesting 3891 File injectUserDataPath(@UserIdInt int userId) { 3892 return new File(Environment.getDataSystemCeDirectory(userId), DIRECTORY_PER_USER); 3893 } 3894 3895 @VisibleForTesting 3896 boolean injectIsLowRamDevice() { 3897 return ActivityManager.isLowRamDeviceStatic(); 3898 } 3899 3900 @VisibleForTesting 3901 void injectRegisterUidObserver(IUidObserver observer, int which) { 3902 try { 3903 ActivityManager.getService().registerUidObserver(observer, which, 3904 ActivityManager.PROCESS_STATE_UNKNOWN, null); 3905 } catch (RemoteException shouldntHappen) { 3906 } 3907 } 3908 3909 File getUserBitmapFilePath(@UserIdInt int userId) { 3910 return new File(injectUserDataPath(userId), DIRECTORY_BITMAPS); 3911 } 3912 3913 @VisibleForTesting 3914 SparseArray<ShortcutUser> getShortcutsForTest() { 3915 return mUsers; 3916 } 3917 3918 @VisibleForTesting 3919 int getMaxShortcutsForTest() { 3920 return mMaxShortcuts; 3921 } 3922 3923 @VisibleForTesting 3924 int getMaxUpdatesPerIntervalForTest() { 3925 return mMaxUpdatesPerInterval; 3926 } 3927 3928 @VisibleForTesting 3929 long getResetIntervalForTest() { 3930 return mResetInterval; 3931 } 3932 3933 @VisibleForTesting 3934 int getMaxIconDimensionForTest() { 3935 return mMaxIconDimension; 3936 } 3937 3938 @VisibleForTesting 3939 CompressFormat getIconPersistFormatForTest() { 3940 return mIconPersistFormat; 3941 } 3942 3943 @VisibleForTesting 3944 int getIconPersistQualityForTest() { 3945 return mIconPersistQuality; 3946 } 3947 3948 @VisibleForTesting 3949 ShortcutPackage getPackageShortcutForTest(String packageName, int userId) { 3950 synchronized (mLock) { 3951 final ShortcutUser user = mUsers.get(userId); 3952 if (user == null) return null; 3953 3954 return user.getAllPackagesForTest().get(packageName); 3955 } 3956 } 3957 3958 @VisibleForTesting 3959 ShortcutInfo getPackageShortcutForTest(String packageName, String shortcutId, int userId) { 3960 synchronized (mLock) { 3961 final ShortcutPackage pkg = getPackageShortcutForTest(packageName, userId); 3962 if (pkg == null) return null; 3963 3964 return pkg.findShortcutById(shortcutId); 3965 } 3966 } 3967 3968 @VisibleForTesting 3969 ShortcutLauncher getLauncherShortcutForTest(String packageName, int userId) { 3970 synchronized (mLock) { 3971 final ShortcutUser user = mUsers.get(userId); 3972 if (user == null) return null; 3973 3974 return user.getAllLaunchersForTest().get(PackageWithUser.of(userId, packageName)); 3975 } 3976 } 3977 3978 @VisibleForTesting 3979 ShortcutRequestPinProcessor getShortcutRequestPinProcessorForTest() { 3980 return mShortcutRequestPinProcessor; 3981 } 3982 3983 /** 3984 * Control whether {@link #verifyStates} should be performed. We always perform it during unit 3985 * tests. 3986 */ 3987 @VisibleForTesting 3988 boolean injectShouldPerformVerification() { 3989 return DEBUG; 3990 } 3991 3992 /** 3993 * Check various internal states and throws if there's any inconsistency. 3994 * This is normally only enabled during unit tests. 3995 */ 3996 final void verifyStates() { 3997 if (injectShouldPerformVerification()) { 3998 verifyStatesInner(); 3999 } 4000 } 4001 4002 private final void verifyStatesForce() { 4003 verifyStatesInner(); 4004 } 4005 4006 private void verifyStatesInner() { 4007 synchronized (mLock) { 4008 forEachLoadedUserLocked(u -> u.forAllPackageItems(ShortcutPackageItem::verifyStates)); 4009 } 4010 } 4011} 4012