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