ShortcutService.java revision 634cecb899f4dabccf57411f48838d99650a9479
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 int callingPid, int callingUid) { 2237 if (injectCheckAccessShortcutsPermission(callingPid, callingUid)) { 2238 return true; 2239 } 2240 final long start = injectElapsedRealtime(); 2241 try { 2242 return hasShortcutHostPermissionInner(callingPackage, userId); 2243 } finally { 2244 logDurationStat(Stats.LAUNCHER_PERMISSION_CHECK, start); 2245 } 2246 } 2247 2248 /** 2249 * Returns true if the caller has the "ACCESS_SHORTCUTS" permission. 2250 */ 2251 boolean injectCheckAccessShortcutsPermission(int callingPid, int callingUid) { 2252 return mContext.checkPermission(android.Manifest.permission.ACCESS_SHORTCUTS, 2253 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED; 2254 } 2255 2256 // This method is extracted so we can directly call this method from unit tests, 2257 // even when hasShortcutPermission() is overridden. 2258 @VisibleForTesting 2259 boolean hasShortcutHostPermissionInner(@NonNull String packageName, int userId) { 2260 synchronized (mLock) { 2261 throwIfUserLockedL(userId); 2262 2263 final ShortcutUser user = getUserShortcutsLocked(userId); 2264 2265 // Always trust the cached component. 2266 final ComponentName cached = user.getCachedLauncher(); 2267 if (cached != null) { 2268 if (cached.getPackageName().equals(packageName)) { 2269 return true; 2270 } 2271 } 2272 // If the cached one doesn't match, then go ahead 2273 2274 final ComponentName detected = getDefaultLauncher(userId); 2275 2276 // Update the cache. 2277 user.setLauncher(detected); 2278 if (detected != null) { 2279 if (DEBUG) { 2280 Slog.v(TAG, "Detected launcher: " + detected); 2281 } 2282 return detected.getPackageName().equals(packageName); 2283 } else { 2284 // Default launcher not found. 2285 return false; 2286 } 2287 } 2288 } 2289 2290 @Nullable 2291 ComponentName getDefaultLauncher(@UserIdInt int userId) { 2292 final long start = injectElapsedRealtime(); 2293 final long token = injectClearCallingIdentity(); 2294 try { 2295 synchronized (mLock) { 2296 throwIfUserLockedL(userId); 2297 2298 final ShortcutUser user = getUserShortcutsLocked(userId); 2299 2300 final List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 2301 2302 // Default launcher from package manager. 2303 final long startGetHomeActivitiesAsUser = injectElapsedRealtime(); 2304 final ComponentName defaultLauncher = mPackageManagerInternal 2305 .getHomeActivitiesAsUser(allHomeCandidates, userId); 2306 logDurationStat(Stats.GET_DEFAULT_HOME, startGetHomeActivitiesAsUser); 2307 2308 ComponentName detected = null; 2309 if (defaultLauncher != null) { 2310 detected = defaultLauncher; 2311 if (DEBUG) { 2312 Slog.v(TAG, "Default launcher from PM: " + detected); 2313 } 2314 } else { 2315 detected = user.getLastKnownLauncher(); 2316 2317 if (detected != null) { 2318 if (injectIsActivityEnabledAndExported(detected, userId)) { 2319 if (DEBUG) { 2320 Slog.v(TAG, "Cached launcher: " + detected); 2321 } 2322 } else { 2323 Slog.w(TAG, "Cached launcher " + detected + " no longer exists"); 2324 detected = null; 2325 user.clearLauncher(); 2326 } 2327 } 2328 } 2329 2330 if (detected == null) { 2331 // If we reach here, that means it's the first check since the user was created, 2332 // and there's already multiple launchers and there's no default set. 2333 // Find the system one with the highest priority. 2334 // (We need to check the priority too because of FallbackHome in Settings.) 2335 // If there's no system launcher yet, then no one can access shortcuts, until 2336 // the user explicitly 2337 final int size = allHomeCandidates.size(); 2338 2339 int lastPriority = Integer.MIN_VALUE; 2340 for (int i = 0; i < size; i++) { 2341 final ResolveInfo ri = allHomeCandidates.get(i); 2342 if (!ri.activityInfo.applicationInfo.isSystemApp()) { 2343 continue; 2344 } 2345 if (DEBUG) { 2346 Slog.d(TAG, String.format("hasShortcutPermissionInner: pkg=%s prio=%d", 2347 ri.activityInfo.getComponentName(), ri.priority)); 2348 } 2349 if (ri.priority < lastPriority) { 2350 continue; 2351 } 2352 detected = ri.activityInfo.getComponentName(); 2353 lastPriority = ri.priority; 2354 } 2355 } 2356 return detected; 2357 } 2358 } finally { 2359 injectRestoreCallingIdentity(token); 2360 logDurationStat(Stats.GET_DEFAULT_LAUNCHER, start); 2361 } 2362 } 2363 2364 // === House keeping === 2365 2366 private void cleanUpPackageForAllLoadedUsers(String packageName, @UserIdInt int packageUserId, 2367 boolean appStillExists) { 2368 synchronized (mLock) { 2369 forEachLoadedUserLocked(user -> 2370 cleanUpPackageLocked(packageName, user.getUserId(), packageUserId, 2371 appStillExists)); 2372 } 2373 } 2374 2375 /** 2376 * Remove all the information associated with a package. This will really remove all the 2377 * information, including the restore information (i.e. it'll remove packages even if they're 2378 * shadow). 2379 * 2380 * This is called when an app is uninstalled, or an app gets "clear data"ed. 2381 */ 2382 @VisibleForTesting 2383 void cleanUpPackageLocked(String packageName, int owningUserId, int packageUserId, 2384 boolean appStillExists) { 2385 final boolean wasUserLoaded = isUserLoadedLocked(owningUserId); 2386 2387 final ShortcutUser user = getUserShortcutsLocked(owningUserId); 2388 boolean doNotify = false; 2389 2390 // First, remove the package from the package list (if the package is a publisher). 2391 if (packageUserId == owningUserId) { 2392 if (user.removePackage(packageName) != null) { 2393 doNotify = true; 2394 } 2395 } 2396 2397 // Also remove from the launcher list (if the package is a launcher). 2398 user.removeLauncher(packageUserId, packageName); 2399 2400 // Then remove pinned shortcuts from all launchers. 2401 user.forAllLaunchers(l -> l.cleanUpPackage(packageName, packageUserId)); 2402 2403 // Now there may be orphan shortcuts because we removed pinned shortcuts at the previous 2404 // step. Remove them too. 2405 user.forAllPackages(p -> p.refreshPinnedFlags()); 2406 2407 scheduleSaveUser(owningUserId); 2408 2409 if (doNotify) { 2410 notifyListeners(packageName, owningUserId); 2411 } 2412 2413 // If the app still exists (i.e. data cleared), we need to re-publish manifest shortcuts. 2414 if (appStillExists && (packageUserId == owningUserId)) { 2415 // This will do the notification and save when needed, so do it after the above 2416 // notifyListeners. 2417 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true); 2418 } 2419 2420 if (!wasUserLoaded) { 2421 // Note this will execute the scheduled save. 2422 unloadUserLocked(owningUserId); 2423 } 2424 } 2425 2426 /** 2427 * Entry point from {@link LauncherApps}. 2428 */ 2429 private class LocalService extends ShortcutServiceInternal { 2430 2431 @Override 2432 public List<ShortcutInfo> getShortcuts(int launcherUserId, 2433 @NonNull String callingPackage, long changedSince, 2434 @Nullable String packageName, @Nullable List<String> shortcutIds, 2435 @Nullable ComponentName componentName, 2436 int queryFlags, int userId, int callingPid, int callingUid) { 2437 final ArrayList<ShortcutInfo> ret = new ArrayList<>(); 2438 2439 final boolean cloneKeyFieldOnly = 2440 ((queryFlags & ShortcutQuery.FLAG_GET_KEY_FIELDS_ONLY) != 0); 2441 final int cloneFlag = cloneKeyFieldOnly ? ShortcutInfo.CLONE_REMOVE_NON_KEY_INFO 2442 : ShortcutInfo.CLONE_REMOVE_FOR_LAUNCHER; 2443 if (packageName == null) { 2444 shortcutIds = null; // LauncherAppsService already threw for it though. 2445 } 2446 2447 synchronized (mLock) { 2448 throwIfUserLockedL(userId); 2449 throwIfUserLockedL(launcherUserId); 2450 2451 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId) 2452 .attemptToRestoreIfNeededAndSave(); 2453 2454 if (packageName != null) { 2455 getShortcutsInnerLocked(launcherUserId, 2456 callingPackage, packageName, shortcutIds, changedSince, 2457 componentName, queryFlags, userId, ret, cloneFlag, 2458 callingPid, callingUid); 2459 } else { 2460 final List<String> shortcutIdsF = shortcutIds; 2461 getUserShortcutsLocked(userId).forAllPackages(p -> { 2462 getShortcutsInnerLocked(launcherUserId, 2463 callingPackage, p.getPackageName(), shortcutIdsF, changedSince, 2464 componentName, queryFlags, userId, ret, cloneFlag, 2465 callingPid, callingUid); 2466 }); 2467 } 2468 } 2469 return setReturnedByServer(ret); 2470 } 2471 2472 private void getShortcutsInnerLocked(int launcherUserId, @NonNull String callingPackage, 2473 @Nullable String packageName, @Nullable List<String> shortcutIds, long changedSince, 2474 @Nullable ComponentName componentName, int queryFlags, 2475 int userId, ArrayList<ShortcutInfo> ret, int cloneFlag, 2476 int callingPid, int callingUid) { 2477 final ArraySet<String> ids = shortcutIds == null ? null 2478 : new ArraySet<>(shortcutIds); 2479 2480 final ShortcutPackage p = getUserShortcutsLocked(userId) 2481 .getPackageShortcutsIfExists(packageName); 2482 if (p == null) { 2483 return; // No need to instantiate ShortcutPackage. 2484 } 2485 final boolean matchDynamic = (queryFlags & ShortcutQuery.FLAG_MATCH_DYNAMIC) != 0; 2486 final boolean matchPinned = (queryFlags & ShortcutQuery.FLAG_MATCH_PINNED) != 0; 2487 final boolean matchManifest = (queryFlags & ShortcutQuery.FLAG_MATCH_MANIFEST) != 0; 2488 2489 final boolean getPinnedByAnyLauncher = 2490 ((queryFlags & ShortcutQuery.FLAG_MATCH_ALL_PINNED) != 0) 2491 && injectCheckAccessShortcutsPermission(callingPid, callingUid); 2492 2493 p.findAll(ret, 2494 (ShortcutInfo si) -> { 2495 if (si.getLastChangedTimestamp() < changedSince) { 2496 return false; 2497 } 2498 if (ids != null && !ids.contains(si.getId())) { 2499 return false; 2500 } 2501 if (componentName != null) { 2502 if (si.getActivity() != null 2503 && !si.getActivity().equals(componentName)) { 2504 return false; 2505 } 2506 } 2507 if (matchDynamic && si.isDynamic()) { 2508 return true; 2509 } 2510 if ((matchPinned && si.isPinned()) || getPinnedByAnyLauncher) { 2511 return true; 2512 } 2513 if (matchManifest && si.isDeclaredInManifest()) { 2514 return true; 2515 } 2516 return false; 2517 }, cloneFlag, callingPackage, launcherUserId, getPinnedByAnyLauncher); 2518 } 2519 2520 @Override 2521 public boolean isPinnedByCaller(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 synchronized (mLock) { 2527 throwIfUserLockedL(userId); 2528 throwIfUserLockedL(launcherUserId); 2529 2530 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId) 2531 .attemptToRestoreIfNeededAndSave(); 2532 2533 final ShortcutInfo si = getShortcutInfoLocked( 2534 launcherUserId, callingPackage, packageName, shortcutId, userId, 2535 /*getPinnedByAnyLauncher=*/ false); 2536 return si != null && si.isPinned(); 2537 } 2538 } 2539 2540 private ShortcutInfo getShortcutInfoLocked( 2541 int launcherUserId, @NonNull String callingPackage, 2542 @NonNull String packageName, @NonNull String shortcutId, int userId, 2543 boolean getPinnedByAnyLauncher) { 2544 Preconditions.checkStringNotEmpty(packageName, "packageName"); 2545 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId"); 2546 2547 throwIfUserLockedL(userId); 2548 throwIfUserLockedL(launcherUserId); 2549 2550 final ShortcutPackage p = getUserShortcutsLocked(userId) 2551 .getPackageShortcutsIfExists(packageName); 2552 if (p == null) { 2553 return null; 2554 } 2555 2556 final ArrayList<ShortcutInfo> list = new ArrayList<>(1); 2557 p.findAll(list, 2558 (ShortcutInfo si) -> shortcutId.equals(si.getId()), 2559 /* clone flags=*/ 0, callingPackage, launcherUserId, getPinnedByAnyLauncher); 2560 return list.size() == 0 ? null : list.get(0); 2561 } 2562 2563 @Override 2564 public void pinShortcuts(int launcherUserId, 2565 @NonNull String callingPackage, @NonNull String packageName, 2566 @NonNull List<String> shortcutIds, int userId) { 2567 // Calling permission must be checked by LauncherAppsImpl. 2568 Preconditions.checkStringNotEmpty(packageName, "packageName"); 2569 Preconditions.checkNotNull(shortcutIds, "shortcutIds"); 2570 2571 synchronized (mLock) { 2572 throwIfUserLockedL(userId); 2573 throwIfUserLockedL(launcherUserId); 2574 2575 final ShortcutLauncher launcher = 2576 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId); 2577 launcher.attemptToRestoreIfNeededAndSave(); 2578 2579 launcher.pinShortcuts(userId, packageName, shortcutIds, /*forPinRequest=*/ false); 2580 } 2581 packageShortcutsChanged(packageName, userId); 2582 2583 verifyStates(); 2584 } 2585 2586 @Override 2587 public Intent[] createShortcutIntents(int launcherUserId, 2588 @NonNull String callingPackage, 2589 @NonNull String packageName, @NonNull String shortcutId, int userId, 2590 int callingPid, int callingUid) { 2591 // Calling permission must be checked by LauncherAppsImpl. 2592 Preconditions.checkStringNotEmpty(packageName, "packageName can't be empty"); 2593 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId can't be empty"); 2594 2595 synchronized (mLock) { 2596 throwIfUserLockedL(userId); 2597 throwIfUserLockedL(launcherUserId); 2598 2599 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId) 2600 .attemptToRestoreIfNeededAndSave(); 2601 2602 final boolean getPinnedByAnyLauncher = 2603 injectCheckAccessShortcutsPermission(callingPid, callingUid); 2604 2605 // Make sure the shortcut is actually visible to the launcher. 2606 final ShortcutInfo si = getShortcutInfoLocked( 2607 launcherUserId, callingPackage, packageName, shortcutId, userId, 2608 getPinnedByAnyLauncher); 2609 // "si == null" should suffice here, but check the flags too just to make sure. 2610 if (si == null || !si.isEnabled() || !si.isAlive()) { 2611 Log.e(TAG, "Shortcut " + shortcutId + " does not exist or disabled"); 2612 return null; 2613 } 2614 return si.getIntents(); 2615 } 2616 } 2617 2618 @Override 2619 public void addListener(@NonNull ShortcutChangeListener listener) { 2620 synchronized (mLock) { 2621 mListeners.add(Preconditions.checkNotNull(listener)); 2622 } 2623 } 2624 2625 @Override 2626 public int getShortcutIconResId(int launcherUserId, @NonNull String callingPackage, 2627 @NonNull String packageName, @NonNull String shortcutId, int userId) { 2628 Preconditions.checkNotNull(callingPackage, "callingPackage"); 2629 Preconditions.checkNotNull(packageName, "packageName"); 2630 Preconditions.checkNotNull(shortcutId, "shortcutId"); 2631 2632 synchronized (mLock) { 2633 throwIfUserLockedL(userId); 2634 throwIfUserLockedL(launcherUserId); 2635 2636 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId) 2637 .attemptToRestoreIfNeededAndSave(); 2638 2639 final ShortcutPackage p = getUserShortcutsLocked(userId) 2640 .getPackageShortcutsIfExists(packageName); 2641 if (p == null) { 2642 return 0; 2643 } 2644 2645 final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId); 2646 return (shortcutInfo != null && shortcutInfo.hasIconResource()) 2647 ? shortcutInfo.getIconResourceId() : 0; 2648 } 2649 } 2650 2651 @Override 2652 public ParcelFileDescriptor getShortcutIconFd(int launcherUserId, 2653 @NonNull String callingPackage, @NonNull String packageName, 2654 @NonNull String shortcutId, int userId) { 2655 Preconditions.checkNotNull(callingPackage, "callingPackage"); 2656 Preconditions.checkNotNull(packageName, "packageName"); 2657 Preconditions.checkNotNull(shortcutId, "shortcutId"); 2658 2659 synchronized (mLock) { 2660 throwIfUserLockedL(userId); 2661 throwIfUserLockedL(launcherUserId); 2662 2663 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId) 2664 .attemptToRestoreIfNeededAndSave(); 2665 2666 final ShortcutPackage p = getUserShortcutsLocked(userId) 2667 .getPackageShortcutsIfExists(packageName); 2668 if (p == null) { 2669 return null; 2670 } 2671 2672 final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId); 2673 if (shortcutInfo == null || !shortcutInfo.hasIconFile()) { 2674 return null; 2675 } 2676 final String path = mShortcutBitmapSaver.getBitmapPathMayWaitLocked(shortcutInfo); 2677 if (path == null) { 2678 Slog.w(TAG, "null bitmap detected in getShortcutIconFd()"); 2679 return null; 2680 } 2681 try { 2682 return ParcelFileDescriptor.open( 2683 new File(path), 2684 ParcelFileDescriptor.MODE_READ_ONLY); 2685 } catch (FileNotFoundException e) { 2686 Slog.e(TAG, "Icon file not found: " + path); 2687 return null; 2688 } 2689 } 2690 } 2691 2692 @Override 2693 public boolean hasShortcutHostPermission(int launcherUserId, 2694 @NonNull String callingPackage, int callingPid, int callingUid) { 2695 return ShortcutService.this.hasShortcutHostPermission(callingPackage, launcherUserId, 2696 callingPid, callingUid); 2697 } 2698 2699 @Override 2700 public boolean requestPinAppWidget(@NonNull String callingPackage, 2701 @NonNull AppWidgetProviderInfo appWidget, @Nullable Bundle extras, 2702 @Nullable IntentSender resultIntent, int userId) { 2703 Preconditions.checkNotNull(appWidget); 2704 return requestPinItem(callingPackage, userId, null, appWidget, extras, resultIntent); 2705 } 2706 2707 @Override 2708 public boolean isRequestPinItemSupported(int callingUserId, int requestType) { 2709 return ShortcutService.this.isRequestPinItemSupported(callingUserId, requestType); 2710 } 2711 } 2712 2713 final BroadcastReceiver mReceiver = new BroadcastReceiver() { 2714 @Override 2715 public void onReceive(Context context, Intent intent) { 2716 if (!mBootCompleted.get()) { 2717 return; // Boot not completed, ignore the broadcast. 2718 } 2719 try { 2720 if (Intent.ACTION_LOCALE_CHANGED.equals(intent.getAction())) { 2721 handleLocaleChanged(); 2722 } 2723 } catch (Exception e) { 2724 wtf("Exception in mReceiver.onReceive", e); 2725 } 2726 } 2727 }; 2728 2729 void handleLocaleChanged() { 2730 if (DEBUG) { 2731 Slog.d(TAG, "handleLocaleChanged"); 2732 } 2733 scheduleSaveBaseState(); 2734 2735 synchronized (mLock) { 2736 final long token = injectClearCallingIdentity(); 2737 try { 2738 forEachLoadedUserLocked(user -> user.detectLocaleChange()); 2739 } finally { 2740 injectRestoreCallingIdentity(token); 2741 } 2742 } 2743 } 2744 2745 /** 2746 * Package event callbacks. 2747 */ 2748 @VisibleForTesting 2749 final BroadcastReceiver mPackageMonitor = new BroadcastReceiver() { 2750 @Override 2751 public void onReceive(Context context, Intent intent) { 2752 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL); 2753 if (userId == UserHandle.USER_NULL) { 2754 Slog.w(TAG, "Intent broadcast does not contain user handle: " + intent); 2755 return; 2756 } 2757 2758 final String action = intent.getAction(); 2759 2760 // This is normally called on Handler, so clearCallingIdentity() isn't needed, 2761 // but we still check it in unit tests. 2762 final long token = injectClearCallingIdentity(); 2763 try { 2764 synchronized (mLock) { 2765 if (!isUserUnlockedL(userId)) { 2766 if (DEBUG) { 2767 Slog.d(TAG, "Ignoring package broadcast " + action 2768 + " for locked/stopped user " + userId); 2769 } 2770 return; 2771 } 2772 2773 // Whenever we get one of those package broadcasts, or get 2774 // ACTION_PREFERRED_ACTIVITY_CHANGED, we purge the default launcher cache. 2775 final ShortcutUser user = getUserShortcutsLocked(userId); 2776 user.clearLauncher(); 2777 } 2778 if (Intent.ACTION_PREFERRED_ACTIVITY_CHANGED.equals(action)) { 2779 // Nothing farther to do. 2780 return; 2781 } 2782 2783 final Uri intentUri = intent.getData(); 2784 final String packageName = (intentUri != null) ? intentUri.getSchemeSpecificPart() 2785 : null; 2786 if (packageName == null) { 2787 Slog.w(TAG, "Intent broadcast does not contain package name: " + intent); 2788 return; 2789 } 2790 2791 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); 2792 2793 switch (action) { 2794 case Intent.ACTION_PACKAGE_ADDED: 2795 if (replacing) { 2796 handlePackageUpdateFinished(packageName, userId); 2797 } else { 2798 handlePackageAdded(packageName, userId); 2799 } 2800 break; 2801 case Intent.ACTION_PACKAGE_REMOVED: 2802 if (!replacing) { 2803 handlePackageRemoved(packageName, userId); 2804 } 2805 break; 2806 case Intent.ACTION_PACKAGE_CHANGED: 2807 handlePackageChanged(packageName, userId); 2808 2809 break; 2810 case Intent.ACTION_PACKAGE_DATA_CLEARED: 2811 handlePackageDataCleared(packageName, userId); 2812 break; 2813 } 2814 } catch (Exception e) { 2815 wtf("Exception in mPackageMonitor.onReceive", e); 2816 } finally { 2817 injectRestoreCallingIdentity(token); 2818 } 2819 } 2820 }; 2821 2822 /** 2823 * Called when a user is unlocked. 2824 * - Check all known packages still exist, and otherwise perform cleanup. 2825 * - If a package still exists, check the version code. If it's been updated, may need to 2826 * update timestamps of its shortcuts. 2827 */ 2828 @VisibleForTesting 2829 void checkPackageChanges(@UserIdInt int ownerUserId) { 2830 if (DEBUG) { 2831 Slog.d(TAG, "checkPackageChanges() ownerUserId=" + ownerUserId); 2832 } 2833 if (injectIsSafeModeEnabled()) { 2834 Slog.i(TAG, "Safe mode, skipping checkPackageChanges()"); 2835 return; 2836 } 2837 2838 final long start = injectElapsedRealtime(); 2839 try { 2840 final ArrayList<PackageWithUser> gonePackages = new ArrayList<>(); 2841 2842 synchronized (mLock) { 2843 final ShortcutUser user = getUserShortcutsLocked(ownerUserId); 2844 2845 // Find packages that have been uninstalled. 2846 user.forAllPackageItems(spi -> { 2847 if (spi.getPackageInfo().isShadow()) { 2848 return; // Don't delete shadow information. 2849 } 2850 if (!isPackageInstalled(spi.getPackageName(), spi.getPackageUserId())) { 2851 if (DEBUG) { 2852 Slog.d(TAG, "Uninstalled: " + spi.getPackageName() 2853 + " user " + spi.getPackageUserId()); 2854 } 2855 gonePackages.add(PackageWithUser.of(spi)); 2856 } 2857 }); 2858 if (gonePackages.size() > 0) { 2859 for (int i = gonePackages.size() - 1; i >= 0; i--) { 2860 final PackageWithUser pu = gonePackages.get(i); 2861 cleanUpPackageLocked(pu.packageName, ownerUserId, pu.userId, 2862 /* appStillExists = */ false); 2863 } 2864 } 2865 2866 rescanUpdatedPackagesLocked(ownerUserId, user.getLastAppScanTime()); 2867 } 2868 } finally { 2869 logDurationStat(Stats.CHECK_PACKAGE_CHANGES, start); 2870 } 2871 verifyStates(); 2872 } 2873 2874 private void rescanUpdatedPackagesLocked(@UserIdInt int userId, long lastScanTime) { 2875 final ShortcutUser user = getUserShortcutsLocked(userId); 2876 2877 // Note after each OTA, we'll need to rescan all system apps, as their lastUpdateTime 2878 // is not reliable. 2879 final long now = injectCurrentTimeMillis(); 2880 final boolean afterOta = 2881 !injectBuildFingerprint().equals(user.getLastAppScanOsFingerprint()); 2882 2883 // Then for each installed app, publish manifest shortcuts when needed. 2884 forUpdatedPackages(userId, lastScanTime, afterOta, ai -> { 2885 user.attemptToRestoreIfNeededAndSave(this, ai.packageName, userId); 2886 2887 user.rescanPackageIfNeeded(ai.packageName, /* forceRescan= */ true); 2888 }); 2889 2890 // Write the time just before the scan, because there may be apps that have just 2891 // been updated, and we want to catch them in the next time. 2892 user.setLastAppScanTime(now); 2893 user.setLastAppScanOsFingerprint(injectBuildFingerprint()); 2894 scheduleSaveUser(userId); 2895 } 2896 2897 private void handlePackageAdded(String packageName, @UserIdInt int userId) { 2898 if (DEBUG) { 2899 Slog.d(TAG, String.format("handlePackageAdded: %s user=%d", packageName, userId)); 2900 } 2901 synchronized (mLock) { 2902 final ShortcutUser user = getUserShortcutsLocked(userId); 2903 user.attemptToRestoreIfNeededAndSave(this, packageName, userId); 2904 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true); 2905 } 2906 verifyStates(); 2907 } 2908 2909 private void handlePackageUpdateFinished(String packageName, @UserIdInt int userId) { 2910 if (DEBUG) { 2911 Slog.d(TAG, String.format("handlePackageUpdateFinished: %s user=%d", 2912 packageName, userId)); 2913 } 2914 synchronized (mLock) { 2915 final ShortcutUser user = getUserShortcutsLocked(userId); 2916 user.attemptToRestoreIfNeededAndSave(this, packageName, userId); 2917 2918 if (isPackageInstalled(packageName, userId)) { 2919 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true); 2920 } 2921 } 2922 verifyStates(); 2923 } 2924 2925 private void handlePackageRemoved(String packageName, @UserIdInt int packageUserId) { 2926 if (DEBUG) { 2927 Slog.d(TAG, String.format("handlePackageRemoved: %s user=%d", packageName, 2928 packageUserId)); 2929 } 2930 cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ false); 2931 2932 verifyStates(); 2933 } 2934 2935 private void handlePackageDataCleared(String packageName, int packageUserId) { 2936 if (DEBUG) { 2937 Slog.d(TAG, String.format("handlePackageDataCleared: %s user=%d", packageName, 2938 packageUserId)); 2939 } 2940 cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ true); 2941 2942 verifyStates(); 2943 } 2944 2945 private void handlePackageChanged(String packageName, int packageUserId) { 2946 if (!isPackageInstalled(packageName, packageUserId)) { 2947 // Probably disabled, which is the same thing as uninstalled. 2948 handlePackageRemoved(packageName, packageUserId); 2949 return; 2950 } 2951 if (DEBUG) { 2952 Slog.d(TAG, String.format("handlePackageChanged: %s user=%d", packageName, 2953 packageUserId)); 2954 } 2955 2956 // Activities may be disabled or enabled. Just rescan the package. 2957 synchronized (mLock) { 2958 final ShortcutUser user = getUserShortcutsLocked(packageUserId); 2959 2960 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true); 2961 } 2962 2963 verifyStates(); 2964 } 2965 2966 // === PackageManager interaction === 2967 2968 /** 2969 * Returns {@link PackageInfo} unless it's uninstalled or disabled. 2970 */ 2971 @Nullable 2972 final PackageInfo getPackageInfoWithSignatures(String packageName, @UserIdInt int userId) { 2973 return getPackageInfo(packageName, userId, true); 2974 } 2975 2976 /** 2977 * Returns {@link PackageInfo} unless it's uninstalled or disabled. 2978 */ 2979 @Nullable 2980 final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId) { 2981 return getPackageInfo(packageName, userId, false); 2982 } 2983 2984 int injectGetPackageUid(@NonNull String packageName, @UserIdInt int userId) { 2985 final long token = injectClearCallingIdentity(); 2986 try { 2987 return mIPackageManager.getPackageUid(packageName, PACKAGE_MATCH_FLAGS, userId); 2988 } catch (RemoteException e) { 2989 // Shouldn't happen. 2990 Slog.wtf(TAG, "RemoteException", e); 2991 return -1; 2992 } finally { 2993 injectRestoreCallingIdentity(token); 2994 } 2995 } 2996 2997 /** 2998 * Returns {@link PackageInfo} unless it's uninstalled or disabled. 2999 */ 3000 @Nullable 3001 @VisibleForTesting 3002 final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId, 3003 boolean getSignatures) { 3004 return isInstalledOrNull(injectPackageInfoWithUninstalled( 3005 packageName, userId, getSignatures)); 3006 } 3007 3008 /** 3009 * Do not use directly; this returns uninstalled packages too. 3010 */ 3011 @Nullable 3012 @VisibleForTesting 3013 PackageInfo injectPackageInfoWithUninstalled(String packageName, @UserIdInt int userId, 3014 boolean getSignatures) { 3015 final long start = injectElapsedRealtime(); 3016 final long token = injectClearCallingIdentity(); 3017 try { 3018 return mIPackageManager.getPackageInfo( 3019 packageName, PACKAGE_MATCH_FLAGS 3020 | (getSignatures ? PackageManager.GET_SIGNATURES : 0), userId); 3021 } catch (RemoteException e) { 3022 // Shouldn't happen. 3023 Slog.wtf(TAG, "RemoteException", e); 3024 return null; 3025 } finally { 3026 injectRestoreCallingIdentity(token); 3027 3028 logDurationStat( 3029 (getSignatures ? Stats.GET_PACKAGE_INFO_WITH_SIG : Stats.GET_PACKAGE_INFO), 3030 start); 3031 } 3032 } 3033 3034 /** 3035 * Returns {@link ApplicationInfo} unless it's uninstalled or disabled. 3036 */ 3037 @Nullable 3038 @VisibleForTesting 3039 final ApplicationInfo getApplicationInfo(String packageName, @UserIdInt int userId) { 3040 return isInstalledOrNull(injectApplicationInfoWithUninstalled(packageName, userId)); 3041 } 3042 3043 /** 3044 * Do not use directly; this returns uninstalled packages too. 3045 */ 3046 @Nullable 3047 @VisibleForTesting 3048 ApplicationInfo injectApplicationInfoWithUninstalled( 3049 String packageName, @UserIdInt int userId) { 3050 final long start = injectElapsedRealtime(); 3051 final long token = injectClearCallingIdentity(); 3052 try { 3053 return mIPackageManager.getApplicationInfo(packageName, PACKAGE_MATCH_FLAGS, userId); 3054 } catch (RemoteException e) { 3055 // Shouldn't happen. 3056 Slog.wtf(TAG, "RemoteException", e); 3057 return null; 3058 } finally { 3059 injectRestoreCallingIdentity(token); 3060 3061 logDurationStat(Stats.GET_APPLICATION_INFO, start); 3062 } 3063 } 3064 3065 /** 3066 * Returns {@link ActivityInfo} with its metadata unless it's uninstalled or disabled. 3067 */ 3068 @Nullable 3069 final ActivityInfo getActivityInfoWithMetadata(ComponentName activity, @UserIdInt int userId) { 3070 return isInstalledOrNull(injectGetActivityInfoWithMetadataWithUninstalled( 3071 activity, userId)); 3072 } 3073 3074 /** 3075 * Do not use directly; this returns uninstalled packages too. 3076 */ 3077 @Nullable 3078 @VisibleForTesting 3079 ActivityInfo injectGetActivityInfoWithMetadataWithUninstalled( 3080 ComponentName activity, @UserIdInt int userId) { 3081 final long start = injectElapsedRealtime(); 3082 final long token = injectClearCallingIdentity(); 3083 try { 3084 return mIPackageManager.getActivityInfo(activity, 3085 (PACKAGE_MATCH_FLAGS | PackageManager.GET_META_DATA), userId); 3086 } catch (RemoteException e) { 3087 // Shouldn't happen. 3088 Slog.wtf(TAG, "RemoteException", e); 3089 return null; 3090 } finally { 3091 injectRestoreCallingIdentity(token); 3092 3093 logDurationStat(Stats.GET_ACTIVITY_WITH_METADATA, start); 3094 } 3095 } 3096 3097 /** 3098 * Return all installed and enabled packages. 3099 */ 3100 @NonNull 3101 @VisibleForTesting 3102 final List<PackageInfo> getInstalledPackages(@UserIdInt int userId) { 3103 final long start = injectElapsedRealtime(); 3104 final long token = injectClearCallingIdentity(); 3105 try { 3106 final List<PackageInfo> all = injectGetPackagesWithUninstalled(userId); 3107 3108 all.removeIf(PACKAGE_NOT_INSTALLED); 3109 3110 return all; 3111 } catch (RemoteException e) { 3112 // Shouldn't happen. 3113 Slog.wtf(TAG, "RemoteException", e); 3114 return null; 3115 } finally { 3116 injectRestoreCallingIdentity(token); 3117 3118 logDurationStat(Stats.GET_INSTALLED_PACKAGES, start); 3119 } 3120 } 3121 3122 /** 3123 * Do not use directly; this returns uninstalled packages too. 3124 */ 3125 @NonNull 3126 @VisibleForTesting 3127 List<PackageInfo> injectGetPackagesWithUninstalled(@UserIdInt int userId) 3128 throws RemoteException { 3129 final ParceledListSlice<PackageInfo> parceledList = 3130 mIPackageManager.getInstalledPackages(PACKAGE_MATCH_FLAGS, userId); 3131 if (parceledList == null) { 3132 return Collections.emptyList(); 3133 } 3134 return parceledList.getList(); 3135 } 3136 3137 private void forUpdatedPackages(@UserIdInt int userId, long lastScanTime, boolean afterOta, 3138 Consumer<ApplicationInfo> callback) { 3139 if (DEBUG) { 3140 Slog.d(TAG, "forUpdatedPackages for user " + userId + ", lastScanTime=" + lastScanTime 3141 + " afterOta=" + afterOta); 3142 } 3143 final List<PackageInfo> list = getInstalledPackages(userId); 3144 for (int i = list.size() - 1; i >= 0; i--) { 3145 final PackageInfo pi = list.get(i); 3146 3147 // If the package has been updated since the last scan time, then scan it. 3148 // Also if it's right after an OTA, always re-scan all apps anyway, since the 3149 // shortcut parser might have changed. 3150 if (afterOta || (pi.lastUpdateTime >= lastScanTime)) { 3151 if (DEBUG) { 3152 Slog.d(TAG, "Found updated package " + pi.packageName 3153 + " updateTime=" + pi.lastUpdateTime); 3154 } 3155 callback.accept(pi.applicationInfo); 3156 } 3157 } 3158 } 3159 3160 private boolean isApplicationFlagSet(@NonNull String packageName, int userId, int flags) { 3161 final ApplicationInfo ai = injectApplicationInfoWithUninstalled(packageName, userId); 3162 return (ai != null) && ((ai.flags & flags) == flags); 3163 } 3164 3165 private static boolean isInstalled(@Nullable ApplicationInfo ai) { 3166 return (ai != null) && ai.enabled && (ai.flags & ApplicationInfo.FLAG_INSTALLED) != 0; 3167 } 3168 3169 private static boolean isEphemeralApp(@Nullable ApplicationInfo ai) { 3170 return (ai != null) && ai.isInstantApp(); 3171 } 3172 3173 private static boolean isInstalled(@Nullable PackageInfo pi) { 3174 return (pi != null) && isInstalled(pi.applicationInfo); 3175 } 3176 3177 private static boolean isInstalled(@Nullable ActivityInfo ai) { 3178 return (ai != null) && isInstalled(ai.applicationInfo); 3179 } 3180 3181 private static ApplicationInfo isInstalledOrNull(ApplicationInfo ai) { 3182 return isInstalled(ai) ? ai : null; 3183 } 3184 3185 private static PackageInfo isInstalledOrNull(PackageInfo pi) { 3186 return isInstalled(pi) ? pi : null; 3187 } 3188 3189 private static ActivityInfo isInstalledOrNull(ActivityInfo ai) { 3190 return isInstalled(ai) ? ai : null; 3191 } 3192 3193 boolean isPackageInstalled(String packageName, int userId) { 3194 return getApplicationInfo(packageName, userId) != null; 3195 } 3196 3197 boolean isEphemeralApp(String packageName, int userId) { 3198 return isEphemeralApp(getApplicationInfo(packageName, userId)); 3199 } 3200 3201 @Nullable 3202 XmlResourceParser injectXmlMetaData(ActivityInfo activityInfo, String key) { 3203 return activityInfo.loadXmlMetaData(mContext.getPackageManager(), key); 3204 } 3205 3206 @Nullable 3207 Resources injectGetResourcesForApplicationAsUser(String packageName, int userId) { 3208 final long start = injectElapsedRealtime(); 3209 final long token = injectClearCallingIdentity(); 3210 try { 3211 return mContext.getPackageManager().getResourcesForApplicationAsUser( 3212 packageName, userId); 3213 } catch (NameNotFoundException e) { 3214 Slog.e(TAG, "Resources for package " + packageName + " not found"); 3215 return null; 3216 } finally { 3217 injectRestoreCallingIdentity(token); 3218 3219 logDurationStat(Stats.GET_APPLICATION_RESOURCES, start); 3220 } 3221 } 3222 3223 private Intent getMainActivityIntent() { 3224 final Intent intent = new Intent(Intent.ACTION_MAIN); 3225 intent.addCategory(LAUNCHER_INTENT_CATEGORY); 3226 return intent; 3227 } 3228 3229 /** 3230 * Same as queryIntentActivitiesAsUser, except it makes sure the package is installed, 3231 * and only returns exported activities. 3232 */ 3233 @NonNull 3234 @VisibleForTesting 3235 List<ResolveInfo> queryActivities(@NonNull Intent baseIntent, 3236 @NonNull String packageName, @Nullable ComponentName activity, int userId) { 3237 3238 baseIntent.setPackage(Preconditions.checkNotNull(packageName)); 3239 if (activity != null) { 3240 baseIntent.setComponent(activity); 3241 } 3242 return queryActivities(baseIntent, userId, /* exportedOnly =*/ true); 3243 } 3244 3245 @NonNull 3246 List<ResolveInfo> queryActivities(@NonNull Intent intent, int userId, 3247 boolean exportedOnly) { 3248 final List<ResolveInfo> resolved; 3249 final long token = injectClearCallingIdentity(); 3250 try { 3251 resolved = 3252 mContext.getPackageManager().queryIntentActivitiesAsUser( 3253 intent, PACKAGE_MATCH_FLAGS, userId); 3254 } finally { 3255 injectRestoreCallingIdentity(token); 3256 } 3257 if (resolved == null || resolved.size() == 0) { 3258 return EMPTY_RESOLVE_INFO; 3259 } 3260 // Make sure the package is installed. 3261 if (!isInstalled(resolved.get(0).activityInfo)) { 3262 return EMPTY_RESOLVE_INFO; 3263 } 3264 if (exportedOnly) { 3265 resolved.removeIf(ACTIVITY_NOT_EXPORTED); 3266 } 3267 return resolved; 3268 } 3269 3270 /** 3271 * Return the main activity that is enabled and exported. If multiple activities are found, 3272 * return the first one. 3273 */ 3274 @Nullable 3275 ComponentName injectGetDefaultMainActivity(@NonNull String packageName, int userId) { 3276 final long start = injectElapsedRealtime(); 3277 try { 3278 final List<ResolveInfo> resolved = 3279 queryActivities(getMainActivityIntent(), packageName, null, userId); 3280 return resolved.size() == 0 ? null : resolved.get(0).activityInfo.getComponentName(); 3281 } finally { 3282 logDurationStat(Stats.GET_LAUNCHER_ACTIVITY, start); 3283 } 3284 } 3285 3286 /** 3287 * Return whether an activity is enabled, exported and main. 3288 */ 3289 boolean injectIsMainActivity(@NonNull ComponentName activity, int userId) { 3290 final long start = injectElapsedRealtime(); 3291 try { 3292 if (activity == null) { 3293 wtf("null activity detected"); 3294 return false; 3295 } 3296 if (DUMMY_MAIN_ACTIVITY.equals(activity.getClassName())) { 3297 return true; 3298 } 3299 final List<ResolveInfo> resolved = queryActivities( 3300 getMainActivityIntent(), activity.getPackageName(), activity, userId); 3301 return resolved.size() > 0; 3302 } finally { 3303 logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start); 3304 } 3305 } 3306 3307 /** 3308 * Create a dummy "main activity" component name which is used to create a dynamic shortcut 3309 * with no main activity temporarily. 3310 */ 3311 @NonNull 3312 ComponentName getDummyMainActivity(@NonNull String packageName) { 3313 return new ComponentName(packageName, DUMMY_MAIN_ACTIVITY); 3314 } 3315 3316 boolean isDummyMainActivity(@Nullable ComponentName name) { 3317 return name != null && DUMMY_MAIN_ACTIVITY.equals(name.getClassName()); 3318 } 3319 3320 /** 3321 * Return all the enabled, exported and main activities from a package. 3322 */ 3323 @NonNull 3324 List<ResolveInfo> injectGetMainActivities(@NonNull String packageName, int userId) { 3325 final long start = injectElapsedRealtime(); 3326 try { 3327 return queryActivities(getMainActivityIntent(), packageName, null, userId); 3328 } finally { 3329 logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start); 3330 } 3331 } 3332 3333 /** 3334 * Return whether an activity is enabled and exported. 3335 */ 3336 @VisibleForTesting 3337 boolean injectIsActivityEnabledAndExported( 3338 @NonNull ComponentName activity, @UserIdInt int userId) { 3339 final long start = injectElapsedRealtime(); 3340 try { 3341 return queryActivities(new Intent(), activity.getPackageName(), activity, userId) 3342 .size() > 0; 3343 } finally { 3344 logDurationStat(Stats.IS_ACTIVITY_ENABLED, start); 3345 } 3346 } 3347 3348 /** 3349 * Get the {@link LauncherApps#ACTION_CONFIRM_PIN_SHORTCUT} or 3350 * {@link LauncherApps#ACTION_CONFIRM_PIN_APPWIDGET} activity in a given package depending on 3351 * the requestType. 3352 */ 3353 @Nullable 3354 ComponentName injectGetPinConfirmationActivity(@NonNull String launcherPackageName, 3355 int launcherUserId, int requestType) { 3356 Preconditions.checkNotNull(launcherPackageName); 3357 String action = requestType == LauncherApps.PinItemRequest.REQUEST_TYPE_SHORTCUT ? 3358 LauncherApps.ACTION_CONFIRM_PIN_SHORTCUT : 3359 LauncherApps.ACTION_CONFIRM_PIN_APPWIDGET; 3360 3361 final Intent confirmIntent = new Intent(action).setPackage(launcherPackageName); 3362 final List<ResolveInfo> candidates = queryActivities( 3363 confirmIntent, launcherUserId, /* exportedOnly =*/ false); 3364 for (ResolveInfo ri : candidates) { 3365 return ri.activityInfo.getComponentName(); 3366 } 3367 return null; 3368 } 3369 3370 boolean injectIsSafeModeEnabled() { 3371 final long token = injectClearCallingIdentity(); 3372 try { 3373 return IWindowManager.Stub 3374 .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE)) 3375 .isSafeModeEnabled(); 3376 } catch (RemoteException e) { 3377 return false; // Shouldn't happen though. 3378 } finally { 3379 injectRestoreCallingIdentity(token); 3380 } 3381 } 3382 3383 /** 3384 * If {@code userId} is of a managed profile, return the parent user ID. Otherwise return 3385 * itself. 3386 */ 3387 int getParentOrSelfUserId(int userId) { 3388 final long token = injectClearCallingIdentity(); 3389 try { 3390 final UserInfo parent = mUserManager.getProfileParent(userId); 3391 return (parent != null) ? parent.id : userId; 3392 } finally { 3393 injectRestoreCallingIdentity(token); 3394 } 3395 } 3396 3397 void injectSendIntentSender(IntentSender intentSender, Intent extras) { 3398 if (intentSender == null) { 3399 return; 3400 } 3401 try { 3402 intentSender.sendIntent(mContext, /* code= */ 0, extras, 3403 /* onFinished=*/ null, /* handler= */ null); 3404 } catch (SendIntentException e) { 3405 Slog.w(TAG, "sendIntent failed().", e); 3406 } 3407 } 3408 3409 // === Backup & restore === 3410 3411 boolean shouldBackupApp(String packageName, int userId) { 3412 return isApplicationFlagSet(packageName, userId, ApplicationInfo.FLAG_ALLOW_BACKUP); 3413 } 3414 3415 static boolean shouldBackupApp(PackageInfo pi) { 3416 return (pi.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0; 3417 } 3418 3419 @Override 3420 public byte[] getBackupPayload(@UserIdInt int userId) { 3421 enforceSystem(); 3422 if (DEBUG) { 3423 Slog.d(TAG, "Backing up user " + userId); 3424 } 3425 synchronized (mLock) { 3426 if (!isUserUnlockedL(userId)) { 3427 wtf("Can't backup: user " + userId + " is locked or not running"); 3428 return null; 3429 } 3430 3431 final ShortcutUser user = getUserShortcutsLocked(userId); 3432 if (user == null) { 3433 wtf("Can't backup: user not found: id=" + userId); 3434 return null; 3435 } 3436 3437 // Update the signatures for all packages. 3438 user.forAllPackageItems(spi -> spi.refreshPackageSignatureAndSave()); 3439 3440 // Set the version code for the launchers. 3441 // We shouldn't do this for publisher packages, because we don't want to update the 3442 // version code without rescanning the manifest. 3443 user.forAllLaunchers(launcher -> launcher.ensurePackageInfo()); 3444 3445 // Save to the filesystem. 3446 scheduleSaveUser(userId); 3447 saveDirtyInfo(); 3448 3449 // Note, in case of backup, we don't have to wait on bitmap saving, because we don't 3450 // back up bitmaps anyway. 3451 3452 // Then create the backup payload. 3453 final ByteArrayOutputStream os = new ByteArrayOutputStream(32 * 1024); 3454 try { 3455 saveUserInternalLocked(userId, os, /* forBackup */ true); 3456 } catch (XmlPullParserException | IOException e) { 3457 // Shouldn't happen. 3458 Slog.w(TAG, "Backup failed.", e); 3459 return null; 3460 } 3461 return os.toByteArray(); 3462 } 3463 } 3464 3465 @Override 3466 public void applyRestore(byte[] payload, @UserIdInt int userId) { 3467 enforceSystem(); 3468 if (DEBUG) { 3469 Slog.d(TAG, "Restoring user " + userId); 3470 } 3471 synchronized (mLock) { 3472 if (!isUserUnlockedL(userId)) { 3473 wtf("Can't restore: user " + userId + " is locked or not running"); 3474 return; 3475 } 3476 3477 // Note we print the file timestamps in dumpsys too, but also printing the timestamp 3478 // in the files anyway. 3479 mShortcutDumpFiles.save("restore-0-start.txt", pw -> { 3480 pw.print("Start time: "); 3481 dumpCurrentTime(pw); 3482 pw.println(); 3483 }); 3484 mShortcutDumpFiles.save("restore-1-payload.xml", payload); 3485 3486 // Actually do restore. 3487 final ShortcutUser restored; 3488 final ByteArrayInputStream is = new ByteArrayInputStream(payload); 3489 try { 3490 restored = loadUserInternal(userId, is, /* fromBackup */ true); 3491 } catch (XmlPullParserException | IOException | InvalidFileFormatException e) { 3492 Slog.w(TAG, "Restoration failed.", e); 3493 return; 3494 } 3495 mShortcutDumpFiles.save("restore-2.txt", this::dumpInner); 3496 3497 getUserShortcutsLocked(userId).mergeRestoredFile(restored); 3498 3499 mShortcutDumpFiles.save("restore-3.txt", this::dumpInner); 3500 3501 // Rescan all packages to re-publish manifest shortcuts and do other checks. 3502 rescanUpdatedPackagesLocked(userId, 3503 0 // lastScanTime = 0; rescan all packages. 3504 ); 3505 3506 mShortcutDumpFiles.save("restore-4.txt", this::dumpInner); 3507 3508 mShortcutDumpFiles.save("restore-5-finish.txt", pw -> { 3509 pw.print("Finish time: "); 3510 dumpCurrentTime(pw); 3511 pw.println(); 3512 }); 3513 3514 saveUserLocked(userId); 3515 } 3516 } 3517 3518 // === Dump === 3519 3520 @Override 3521 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 3522 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return; 3523 dumpNoCheck(fd, pw, args); 3524 } 3525 3526 @VisibleForTesting 3527 void dumpNoCheck(FileDescriptor fd, PrintWriter pw, String[] args) { 3528 final DumpFilter filter = parseDumpArgs(args); 3529 3530 if (filter.shouldDumpCheckIn()) { 3531 // Other flags are not supported for checkin. 3532 dumpCheckin(pw, filter.shouldCheckInClear()); 3533 } else { 3534 if (filter.shouldDumpMain()) { 3535 dumpInner(pw, filter); 3536 pw.println(); 3537 } 3538 if (filter.shouldDumpUid()) { 3539 dumpUid(pw); 3540 pw.println(); 3541 } 3542 if (filter.shouldDumpFiles()) { 3543 dumpDumpFiles(pw); 3544 pw.println(); 3545 } 3546 } 3547 } 3548 3549 private static DumpFilter parseDumpArgs(String[] args) { 3550 final DumpFilter filter = new DumpFilter(); 3551 if (args == null) { 3552 return filter; 3553 } 3554 3555 int argIndex = 0; 3556 while (argIndex < args.length) { 3557 final String arg = args[argIndex++]; 3558 3559 if ("-c".equals(arg)) { 3560 filter.setDumpCheckIn(true); 3561 continue; 3562 } 3563 if ("--checkin".equals(arg)) { 3564 filter.setDumpCheckIn(true); 3565 filter.setCheckInClear(true); 3566 continue; 3567 } 3568 if ("-a".equals(arg) || "--all".equals(arg)) { 3569 filter.setDumpUid(true); 3570 filter.setDumpFiles(true); 3571 continue; 3572 } 3573 if ("-u".equals(arg) || "--uid".equals(arg)) { 3574 filter.setDumpUid(true); 3575 continue; 3576 } 3577 if ("-f".equals(arg) || "--files".equals(arg)) { 3578 filter.setDumpFiles(true); 3579 continue; 3580 } 3581 if ("-n".equals(arg) || "--no-main".equals(arg)) { 3582 filter.setDumpMain(false); 3583 continue; 3584 } 3585 if ("--user".equals(arg)) { 3586 if (argIndex >= args.length) { 3587 throw new IllegalArgumentException("Missing user ID for --user"); 3588 } 3589 try { 3590 filter.addUser(Integer.parseInt(args[argIndex++])); 3591 } catch (NumberFormatException e) { 3592 throw new IllegalArgumentException("Invalid user ID", e); 3593 } 3594 continue; 3595 } 3596 if ("-p".equals(arg) || "--package".equals(arg)) { 3597 if (argIndex >= args.length) { 3598 throw new IllegalArgumentException("Missing package name for --package"); 3599 } 3600 filter.addPackageRegex(args[argIndex++]); 3601 filter.setDumpDetails(false); 3602 continue; 3603 } 3604 if (arg.startsWith("-")) { 3605 throw new IllegalArgumentException("Unknown option " + arg); 3606 } 3607 break; 3608 } 3609 while (argIndex < args.length) { 3610 filter.addPackage(args[argIndex++]); 3611 } 3612 return filter; 3613 } 3614 3615 static class DumpFilter { 3616 private boolean mDumpCheckIn = false; 3617 private boolean mCheckInClear = false; 3618 3619 private boolean mDumpMain = true; 3620 private boolean mDumpUid = false; 3621 private boolean mDumpFiles = false; 3622 3623 private boolean mDumpDetails = true; 3624 private List<Pattern> mPackagePatterns = new ArrayList<>(); 3625 private List<Integer> mUsers = new ArrayList<>(); 3626 3627 void addPackageRegex(String regex) { 3628 mPackagePatterns.add(Pattern.compile(regex)); 3629 } 3630 3631 public void addPackage(String packageName) { 3632 addPackageRegex(Pattern.quote(packageName)); 3633 } 3634 3635 void addUser(int userId) { 3636 mUsers.add(userId); 3637 } 3638 3639 boolean isPackageMatch(String packageName) { 3640 if (mPackagePatterns.size() == 0) { 3641 return true; 3642 } 3643 for (int i = 0; i < mPackagePatterns.size(); i++) { 3644 if (mPackagePatterns.get(i).matcher(packageName).find()) { 3645 return true; 3646 } 3647 } 3648 return false; 3649 } 3650 3651 boolean isUserMatch(int userId) { 3652 if (mUsers.size() == 0) { 3653 return true; 3654 } 3655 for (int i = 0; i < mUsers.size(); i++) { 3656 if (mUsers.get(i) == userId) { 3657 return true; 3658 } 3659 } 3660 return false; 3661 } 3662 3663 public boolean shouldDumpCheckIn() { 3664 return mDumpCheckIn; 3665 } 3666 3667 public void setDumpCheckIn(boolean dumpCheckIn) { 3668 mDumpCheckIn = dumpCheckIn; 3669 } 3670 3671 public boolean shouldCheckInClear() { 3672 return mCheckInClear; 3673 } 3674 3675 public void setCheckInClear(boolean checkInClear) { 3676 mCheckInClear = checkInClear; 3677 } 3678 3679 public boolean shouldDumpMain() { 3680 return mDumpMain; 3681 } 3682 3683 public void setDumpMain(boolean dumpMain) { 3684 mDumpMain = dumpMain; 3685 } 3686 3687 public boolean shouldDumpUid() { 3688 return mDumpUid; 3689 } 3690 3691 public void setDumpUid(boolean dumpUid) { 3692 mDumpUid = dumpUid; 3693 } 3694 3695 public boolean shouldDumpFiles() { 3696 return mDumpFiles; 3697 } 3698 3699 public void setDumpFiles(boolean dumpFiles) { 3700 mDumpFiles = dumpFiles; 3701 } 3702 3703 public boolean shouldDumpDetails() { 3704 return mDumpDetails; 3705 } 3706 3707 public void setDumpDetails(boolean dumpDetails) { 3708 mDumpDetails = dumpDetails; 3709 } 3710 } 3711 3712 private void dumpInner(PrintWriter pw) { 3713 dumpInner(pw, new DumpFilter()); 3714 } 3715 3716 private void dumpInner(PrintWriter pw, DumpFilter filter) { 3717 synchronized (mLock) { 3718 if (filter.shouldDumpDetails()) { 3719 final long now = injectCurrentTimeMillis(); 3720 pw.print("Now: ["); 3721 pw.print(now); 3722 pw.print("] "); 3723 pw.print(formatTime(now)); 3724 3725 pw.print(" Raw last reset: ["); 3726 pw.print(mRawLastResetTime); 3727 pw.print("] "); 3728 pw.print(formatTime(mRawLastResetTime)); 3729 3730 final long last = getLastResetTimeLocked(); 3731 pw.print(" Last reset: ["); 3732 pw.print(last); 3733 pw.print("] "); 3734 pw.print(formatTime(last)); 3735 3736 final long next = getNextResetTimeLocked(); 3737 pw.print(" Next reset: ["); 3738 pw.print(next); 3739 pw.print("] "); 3740 pw.print(formatTime(next)); 3741 3742 pw.print(" Config:"); 3743 pw.print(" Max icon dim: "); 3744 pw.println(mMaxIconDimension); 3745 pw.print(" Icon format: "); 3746 pw.println(mIconPersistFormat); 3747 pw.print(" Icon quality: "); 3748 pw.println(mIconPersistQuality); 3749 pw.print(" saveDelayMillis: "); 3750 pw.println(mSaveDelayMillis); 3751 pw.print(" resetInterval: "); 3752 pw.println(mResetInterval); 3753 pw.print(" maxUpdatesPerInterval: "); 3754 pw.println(mMaxUpdatesPerInterval); 3755 pw.print(" maxShortcutsPerActivity: "); 3756 pw.println(mMaxShortcuts); 3757 pw.println(); 3758 3759 pw.println(" Stats:"); 3760 synchronized (mStatLock) { 3761 for (int i = 0; i < Stats.COUNT; i++) { 3762 dumpStatLS(pw, " ", i); 3763 } 3764 } 3765 3766 pw.println(); 3767 pw.print(" #Failures: "); 3768 pw.println(mWtfCount); 3769 3770 if (mLastWtfStacktrace != null) { 3771 pw.print(" Last failure stack trace: "); 3772 pw.println(Log.getStackTraceString(mLastWtfStacktrace)); 3773 } 3774 3775 pw.println(); 3776 mShortcutBitmapSaver.dumpLocked(pw, " "); 3777 3778 pw.println(); 3779 } 3780 3781 for (int i = 0; i < mUsers.size(); i++) { 3782 final ShortcutUser user = mUsers.valueAt(i); 3783 if (filter.isUserMatch(user.getUserId())) { 3784 user.dump(pw, " ", filter); 3785 pw.println(); 3786 } 3787 } 3788 } 3789 } 3790 3791 private void dumpUid(PrintWriter pw) { 3792 synchronized (mLock) { 3793 pw.println("** SHORTCUT MANAGER UID STATES (dumpsys shortcut -n -u)"); 3794 3795 for (int i = 0; i < mUidState.size(); i++) { 3796 final int uid = mUidState.keyAt(i); 3797 final int state = mUidState.valueAt(i); 3798 pw.print(" UID="); 3799 pw.print(uid); 3800 pw.print(" state="); 3801 pw.print(state); 3802 if (isProcessStateForeground(state)) { 3803 pw.print(" [FG]"); 3804 } 3805 pw.print(" last FG="); 3806 pw.print(mUidLastForegroundElapsedTime.get(uid)); 3807 pw.println(); 3808 } 3809 } 3810 } 3811 3812 static String formatTime(long time) { 3813 Time tobj = new Time(); 3814 tobj.set(time); 3815 return tobj.format("%Y-%m-%d %H:%M:%S"); 3816 } 3817 3818 private void dumpCurrentTime(PrintWriter pw) { 3819 pw.print(formatTime(injectCurrentTimeMillis())); 3820 } 3821 3822 private void dumpStatLS(PrintWriter pw, String prefix, int statId) { 3823 pw.print(prefix); 3824 final int count = mCountStats[statId]; 3825 final long dur = mDurationStats[statId]; 3826 pw.println(String.format("%s: count=%d, total=%dms, avg=%.1fms", 3827 STAT_LABELS[statId], count, dur, 3828 (count == 0 ? 0 : ((double) dur) / count))); 3829 } 3830 3831 /** 3832 * Dumpsys for checkin. 3833 * 3834 * @param clear if true, clear the history information. Some other system services have this 3835 * behavior but shortcut service doesn't for now. 3836 */ 3837 private void dumpCheckin(PrintWriter pw, boolean clear) { 3838 synchronized (mLock) { 3839 try { 3840 final JSONArray users = new JSONArray(); 3841 3842 for (int i = 0; i < mUsers.size(); i++) { 3843 users.put(mUsers.valueAt(i).dumpCheckin(clear)); 3844 } 3845 3846 final JSONObject result = new JSONObject(); 3847 3848 result.put(KEY_SHORTCUT, users); 3849 result.put(KEY_LOW_RAM, injectIsLowRamDevice()); 3850 result.put(KEY_ICON_SIZE, mMaxIconDimension); 3851 3852 pw.println(result.toString(1)); 3853 } catch (JSONException e) { 3854 Slog.e(TAG, "Unable to write in json", e); 3855 } 3856 } 3857 } 3858 3859 private void dumpDumpFiles(PrintWriter pw) { 3860 synchronized (mLock) { 3861 pw.println("** SHORTCUT MANAGER FILES (dumpsys shortcut -n -f)"); 3862 mShortcutDumpFiles.dumpAll(pw); 3863 } 3864 } 3865 3866 // === Shell support === 3867 3868 @Override 3869 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err, 3870 String[] args, ShellCallback callback, ResultReceiver resultReceiver) { 3871 3872 enforceShell(); 3873 3874 final long token = injectClearCallingIdentity(); 3875 try { 3876 final int status = (new MyShellCommand()).exec(this, in, out, err, args, callback, 3877 resultReceiver); 3878 resultReceiver.send(status, null); 3879 } finally { 3880 injectRestoreCallingIdentity(token); 3881 } 3882 } 3883 3884 static class CommandException extends Exception { 3885 public CommandException(String message) { 3886 super(message); 3887 } 3888 } 3889 3890 /** 3891 * Handle "adb shell cmd". 3892 */ 3893 private class MyShellCommand extends ShellCommand { 3894 3895 private int mUserId = UserHandle.USER_SYSTEM; 3896 3897 private void parseOptionsLocked(boolean takeUser) 3898 throws CommandException { 3899 String opt; 3900 while ((opt = getNextOption()) != null) { 3901 switch (opt) { 3902 case "--user": 3903 if (takeUser) { 3904 mUserId = UserHandle.parseUserArg(getNextArgRequired()); 3905 if (!isUserUnlockedL(mUserId)) { 3906 throw new CommandException( 3907 "User " + mUserId + " is not running or locked"); 3908 } 3909 break; 3910 } 3911 // fallthrough 3912 default: 3913 throw new CommandException("Unknown option: " + opt); 3914 } 3915 } 3916 } 3917 3918 @Override 3919 public int onCommand(String cmd) { 3920 if (cmd == null) { 3921 return handleDefaultCommands(cmd); 3922 } 3923 final PrintWriter pw = getOutPrintWriter(); 3924 try { 3925 switch (cmd) { 3926 case "reset-throttling": 3927 handleResetThrottling(); 3928 break; 3929 case "reset-all-throttling": 3930 handleResetAllThrottling(); 3931 break; 3932 case "override-config": 3933 handleOverrideConfig(); 3934 break; 3935 case "reset-config": 3936 handleResetConfig(); 3937 break; 3938 case "clear-default-launcher": 3939 handleClearDefaultLauncher(); 3940 break; 3941 case "get-default-launcher": 3942 handleGetDefaultLauncher(); 3943 break; 3944 case "unload-user": 3945 handleUnloadUser(); 3946 break; 3947 case "clear-shortcuts": 3948 handleClearShortcuts(); 3949 break; 3950 case "verify-states": // hidden command to verify various internal states. 3951 handleVerifyStates(); 3952 break; 3953 default: 3954 return handleDefaultCommands(cmd); 3955 } 3956 } catch (CommandException e) { 3957 pw.println("Error: " + e.getMessage()); 3958 return 1; 3959 } 3960 pw.println("Success"); 3961 return 0; 3962 } 3963 3964 @Override 3965 public void onHelp() { 3966 final PrintWriter pw = getOutPrintWriter(); 3967 pw.println("Usage: cmd shortcut COMMAND [options ...]"); 3968 pw.println(); 3969 pw.println("cmd shortcut reset-throttling [--user USER_ID]"); 3970 pw.println(" Reset throttling for all packages and users"); 3971 pw.println(); 3972 pw.println("cmd shortcut reset-all-throttling"); 3973 pw.println(" Reset the throttling state for all users"); 3974 pw.println(); 3975 pw.println("cmd shortcut override-config CONFIG"); 3976 pw.println(" Override the configuration for testing (will last until reboot)"); 3977 pw.println(); 3978 pw.println("cmd shortcut reset-config"); 3979 pw.println(" Reset the configuration set with \"update-config\""); 3980 pw.println(); 3981 pw.println("cmd shortcut clear-default-launcher [--user USER_ID]"); 3982 pw.println(" Clear the cached default launcher"); 3983 pw.println(); 3984 pw.println("cmd shortcut get-default-launcher [--user USER_ID]"); 3985 pw.println(" Show the default launcher"); 3986 pw.println(); 3987 pw.println("cmd shortcut unload-user [--user USER_ID]"); 3988 pw.println(" Unload a user from the memory"); 3989 pw.println(" (This should not affect any observable behavior)"); 3990 pw.println(); 3991 pw.println("cmd shortcut clear-shortcuts [--user USER_ID] PACKAGE"); 3992 pw.println(" Remove all shortcuts from a package, including pinned shortcuts"); 3993 pw.println(); 3994 } 3995 3996 private void handleResetThrottling() throws CommandException { 3997 synchronized (mLock) { 3998 parseOptionsLocked(/* takeUser =*/ true); 3999 4000 Slog.i(TAG, "cmd: handleResetThrottling: user=" + mUserId); 4001 4002 resetThrottlingInner(mUserId); 4003 } 4004 } 4005 4006 private void handleResetAllThrottling() { 4007 Slog.i(TAG, "cmd: handleResetAllThrottling"); 4008 4009 resetAllThrottlingInner(); 4010 } 4011 4012 private void handleOverrideConfig() throws CommandException { 4013 final String config = getNextArgRequired(); 4014 4015 Slog.i(TAG, "cmd: handleOverrideConfig: " + config); 4016 4017 synchronized (mLock) { 4018 if (!updateConfigurationLocked(config)) { 4019 throw new CommandException("override-config failed. See logcat for details."); 4020 } 4021 } 4022 } 4023 4024 private void handleResetConfig() { 4025 Slog.i(TAG, "cmd: handleResetConfig"); 4026 4027 synchronized (mLock) { 4028 loadConfigurationLocked(); 4029 } 4030 } 4031 4032 private void clearLauncher() { 4033 synchronized (mLock) { 4034 getUserShortcutsLocked(mUserId).forceClearLauncher(); 4035 } 4036 } 4037 4038 private void showLauncher() { 4039 synchronized (mLock) { 4040 // This ensures to set the cached launcher. Package name doesn't matter. 4041 hasShortcutHostPermissionInner("-", mUserId); 4042 4043 getOutPrintWriter().println("Launcher: " 4044 + getUserShortcutsLocked(mUserId).getLastKnownLauncher()); 4045 } 4046 } 4047 4048 private void handleClearDefaultLauncher() throws CommandException { 4049 synchronized (mLock) { 4050 parseOptionsLocked(/* takeUser =*/ true); 4051 4052 clearLauncher(); 4053 } 4054 } 4055 4056 private void handleGetDefaultLauncher() throws CommandException { 4057 synchronized (mLock) { 4058 parseOptionsLocked(/* takeUser =*/ true); 4059 4060 clearLauncher(); 4061 showLauncher(); 4062 } 4063 } 4064 4065 private void handleUnloadUser() throws CommandException { 4066 synchronized (mLock) { 4067 parseOptionsLocked(/* takeUser =*/ true); 4068 4069 Slog.i(TAG, "cmd: handleUnloadUser: user=" + mUserId); 4070 4071 ShortcutService.this.handleStopUser(mUserId); 4072 } 4073 } 4074 4075 private void handleClearShortcuts() throws CommandException { 4076 synchronized (mLock) { 4077 parseOptionsLocked(/* takeUser =*/ true); 4078 final String packageName = getNextArgRequired(); 4079 4080 Slog.i(TAG, "cmd: handleClearShortcuts: user" + mUserId + ", " + packageName); 4081 4082 ShortcutService.this.cleanUpPackageForAllLoadedUsers(packageName, mUserId, 4083 /* appStillExists = */ true); 4084 } 4085 } 4086 4087 private void handleVerifyStates() throws CommandException { 4088 try { 4089 verifyStatesForce(); // This will throw when there's an issue. 4090 } catch (Throwable th) { 4091 throw new CommandException(th.getMessage() + "\n" + Log.getStackTraceString(th)); 4092 } 4093 } 4094 } 4095 4096 // === Unit test support === 4097 4098 // Injection point. 4099 @VisibleForTesting 4100 long injectCurrentTimeMillis() { 4101 return System.currentTimeMillis(); 4102 } 4103 4104 @VisibleForTesting 4105 long injectElapsedRealtime() { 4106 return SystemClock.elapsedRealtime(); 4107 } 4108 4109 @VisibleForTesting 4110 long injectUptimeMillis() { 4111 return SystemClock.uptimeMillis(); 4112 } 4113 4114 // Injection point. 4115 @VisibleForTesting 4116 int injectBinderCallingUid() { 4117 return getCallingUid(); 4118 } 4119 4120 private int getCallingUserId() { 4121 return UserHandle.getUserId(injectBinderCallingUid()); 4122 } 4123 4124 // Injection point. 4125 @VisibleForTesting 4126 long injectClearCallingIdentity() { 4127 return Binder.clearCallingIdentity(); 4128 } 4129 4130 // Injection point. 4131 @VisibleForTesting 4132 void injectRestoreCallingIdentity(long token) { 4133 Binder.restoreCallingIdentity(token); 4134 } 4135 4136 // Injection point. 4137 @VisibleForTesting 4138 String injectBuildFingerprint() { 4139 return Build.FINGERPRINT; 4140 } 4141 4142 final void wtf(String message) { 4143 wtf(message, /* exception= */ null); 4144 } 4145 4146 // Injection point. 4147 void wtf(String message, Throwable e) { 4148 if (e == null) { 4149 e = new RuntimeException("Stacktrace"); 4150 } 4151 synchronized (mLock) { 4152 mWtfCount++; 4153 mLastWtfStacktrace = new Exception("Last failure was logged here:"); 4154 } 4155 Slog.wtf(TAG, message, e); 4156 } 4157 4158 @VisibleForTesting 4159 File injectSystemDataPath() { 4160 return Environment.getDataSystemDirectory(); 4161 } 4162 4163 @VisibleForTesting 4164 File injectUserDataPath(@UserIdInt int userId) { 4165 return new File(Environment.getDataSystemCeDirectory(userId), DIRECTORY_PER_USER); 4166 } 4167 4168 public File getDumpPath() { 4169 return new File(injectUserDataPath(UserHandle.USER_SYSTEM), DIRECTORY_DUMP); 4170 } 4171 4172 @VisibleForTesting 4173 boolean injectIsLowRamDevice() { 4174 return ActivityManager.isLowRamDeviceStatic(); 4175 } 4176 4177 @VisibleForTesting 4178 void injectRegisterUidObserver(IUidObserver observer, int which) { 4179 try { 4180 ActivityManager.getService().registerUidObserver(observer, which, 4181 ActivityManager.PROCESS_STATE_UNKNOWN, null); 4182 } catch (RemoteException shouldntHappen) { 4183 } 4184 } 4185 4186 File getUserBitmapFilePath(@UserIdInt int userId) { 4187 return new File(injectUserDataPath(userId), DIRECTORY_BITMAPS); 4188 } 4189 4190 @VisibleForTesting 4191 SparseArray<ShortcutUser> getShortcutsForTest() { 4192 return mUsers; 4193 } 4194 4195 @VisibleForTesting 4196 int getMaxShortcutsForTest() { 4197 return mMaxShortcuts; 4198 } 4199 4200 @VisibleForTesting 4201 int getMaxUpdatesPerIntervalForTest() { 4202 return mMaxUpdatesPerInterval; 4203 } 4204 4205 @VisibleForTesting 4206 long getResetIntervalForTest() { 4207 return mResetInterval; 4208 } 4209 4210 @VisibleForTesting 4211 int getMaxIconDimensionForTest() { 4212 return mMaxIconDimension; 4213 } 4214 4215 @VisibleForTesting 4216 CompressFormat getIconPersistFormatForTest() { 4217 return mIconPersistFormat; 4218 } 4219 4220 @VisibleForTesting 4221 int getIconPersistQualityForTest() { 4222 return mIconPersistQuality; 4223 } 4224 4225 @VisibleForTesting 4226 ShortcutPackage getPackageShortcutForTest(String packageName, int userId) { 4227 synchronized (mLock) { 4228 final ShortcutUser user = mUsers.get(userId); 4229 if (user == null) return null; 4230 4231 return user.getAllPackagesForTest().get(packageName); 4232 } 4233 } 4234 4235 @VisibleForTesting 4236 ShortcutInfo getPackageShortcutForTest(String packageName, String shortcutId, int userId) { 4237 synchronized (mLock) { 4238 final ShortcutPackage pkg = getPackageShortcutForTest(packageName, userId); 4239 if (pkg == null) return null; 4240 4241 return pkg.findShortcutById(shortcutId); 4242 } 4243 } 4244 4245 @VisibleForTesting 4246 ShortcutLauncher getLauncherShortcutForTest(String packageName, int userId) { 4247 synchronized (mLock) { 4248 final ShortcutUser user = mUsers.get(userId); 4249 if (user == null) return null; 4250 4251 return user.getAllLaunchersForTest().get(PackageWithUser.of(userId, packageName)); 4252 } 4253 } 4254 4255 @VisibleForTesting 4256 ShortcutRequestPinProcessor getShortcutRequestPinProcessorForTest() { 4257 return mShortcutRequestPinProcessor; 4258 } 4259 4260 /** 4261 * Control whether {@link #verifyStates} should be performed. We always perform it during unit 4262 * tests. 4263 */ 4264 @VisibleForTesting 4265 boolean injectShouldPerformVerification() { 4266 return DEBUG; 4267 } 4268 4269 /** 4270 * Check various internal states and throws if there's any inconsistency. 4271 * This is normally only enabled during unit tests. 4272 */ 4273 final void verifyStates() { 4274 if (injectShouldPerformVerification()) { 4275 verifyStatesInner(); 4276 } 4277 } 4278 4279 private final void verifyStatesForce() { 4280 verifyStatesInner(); 4281 } 4282 4283 private void verifyStatesInner() { 4284 synchronized (mLock) { 4285 forEachLoadedUserLocked(u -> u.forAllPackageItems(ShortcutPackageItem::verifyStates)); 4286 } 4287 } 4288 4289 @VisibleForTesting 4290 void waitForBitmapSavesForTest() { 4291 synchronized (mLock) { 4292 mShortcutBitmapSaver.waitForAllSavesLocked(); 4293 } 4294 } 4295} 4296