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