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