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