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