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