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