ShortcutService.java revision 66e4a2b801fe0ff2ee1db5e0578a3e7cb6e1f6d6
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 | ShortcutInfo.FLAG_HAS_ICON_RES);
1220    }
1221
1222    public void cleanupBitmapsForPackage(@UserIdInt int userId, String packageName) {
1223        final File packagePath = new File(getUserBitmapFilePath(userId), packageName);
1224        if (!packagePath.isDirectory()) {
1225            return;
1226        }
1227        if (!(FileUtils.deleteContents(packagePath) && packagePath.delete())) {
1228            Slog.w(TAG, "Unable to remove directory " + packagePath);
1229        }
1230    }
1231
1232    private void cleanupDanglingBitmapDirectoriesLocked(@UserIdInt int userId) {
1233        if (DEBUG) {
1234            Slog.d(TAG, "cleanupDanglingBitmaps: userId=" + userId);
1235        }
1236        final long start = injectElapsedRealtime();
1237
1238        final ShortcutUser user = getUserShortcutsLocked(userId);
1239
1240        final File bitmapDir = getUserBitmapFilePath(userId);
1241        final File[] children = bitmapDir.listFiles();
1242        if (children == null) {
1243            return;
1244        }
1245        for (File child : children) {
1246            if (!child.isDirectory()) {
1247                continue;
1248            }
1249            final String packageName = child.getName();
1250            if (DEBUG) {
1251                Slog.d(TAG, "cleanupDanglingBitmaps: Found directory=" + packageName);
1252            }
1253            if (!user.hasPackage(packageName)) {
1254                if (DEBUG) {
1255                    Slog.d(TAG, "Removing dangling bitmap directory: " + packageName);
1256                }
1257                cleanupBitmapsForPackage(userId, packageName);
1258            } else {
1259                cleanupDanglingBitmapFilesLocked(userId, user, packageName, child);
1260            }
1261        }
1262        logDurationStat(Stats.CLEANUP_DANGLING_BITMAPS, start);
1263    }
1264
1265    private void cleanupDanglingBitmapFilesLocked(@UserIdInt int userId, @NonNull ShortcutUser user,
1266            @NonNull String packageName, @NonNull File path) {
1267        final ArraySet<String> usedFiles =
1268                user.getPackageShortcuts(packageName).getUsedBitmapFiles();
1269
1270        for (File child : path.listFiles()) {
1271            if (!child.isFile()) {
1272                continue;
1273            }
1274            final String name = child.getName();
1275            if (!usedFiles.contains(name)) {
1276                if (DEBUG) {
1277                    Slog.d(TAG, "Removing dangling bitmap file: " + child.getAbsolutePath());
1278                }
1279                child.delete();
1280            }
1281        }
1282    }
1283
1284    @VisibleForTesting
1285    static class FileOutputStreamWithPath extends FileOutputStream {
1286        private final File mFile;
1287
1288        public FileOutputStreamWithPath(File file) throws FileNotFoundException {
1289            super(file);
1290            mFile = file;
1291        }
1292
1293        public File getFile() {
1294            return mFile;
1295        }
1296    }
1297
1298    /**
1299     * Build the cached bitmap filename for a shortcut icon.
1300     *
1301     * The filename will be based on the ID, except certain characters will be escaped.
1302     */
1303    @VisibleForTesting
1304    FileOutputStreamWithPath openIconFileForWrite(@UserIdInt int userId, ShortcutInfo shortcut)
1305            throws IOException {
1306        final File packagePath = new File(getUserBitmapFilePath(userId),
1307                shortcut.getPackage());
1308        if (!packagePath.isDirectory()) {
1309            packagePath.mkdirs();
1310            if (!packagePath.isDirectory()) {
1311                throw new IOException("Unable to create directory " + packagePath);
1312            }
1313            SELinux.restorecon(packagePath);
1314        }
1315
1316        final String baseName = String.valueOf(injectCurrentTimeMillis());
1317        for (int suffix = 0; ; suffix++) {
1318            final String filename = (suffix == 0 ? baseName : baseName + "_" + suffix) + ".png";
1319            final File file = new File(packagePath, filename);
1320            if (!file.exists()) {
1321                if (DEBUG) {
1322                    Slog.d(TAG, "Saving icon to " + file.getAbsolutePath());
1323                }
1324                return new FileOutputStreamWithPath(file);
1325            }
1326        }
1327    }
1328
1329    void saveIconAndFixUpShortcut(@UserIdInt int userId, ShortcutInfo shortcut) {
1330        if (shortcut.hasIconFile() || shortcut.hasIconResource()) {
1331            return;
1332        }
1333
1334        final long token = injectClearCallingIdentity();
1335        try {
1336            // Clear icon info on the shortcut.
1337            removeIcon(userId, shortcut);
1338
1339            final Icon icon = shortcut.getIcon();
1340            if (icon == null) {
1341                return; // has no icon
1342            }
1343
1344            Bitmap bitmap;
1345            try {
1346                switch (icon.getType()) {
1347                    case Icon.TYPE_RESOURCE: {
1348                        injectValidateIconResPackage(shortcut, icon);
1349
1350                        shortcut.setIconResourceId(icon.getResId());
1351                        shortcut.addFlags(ShortcutInfo.FLAG_HAS_ICON_RES);
1352                        return;
1353                    }
1354                    case Icon.TYPE_BITMAP: {
1355                        bitmap = icon.getBitmap(); // Don't recycle in this case.
1356                        break;
1357                    }
1358                    default:
1359                        // This shouldn't happen because we've already validated the icon, but
1360                        // just in case.
1361                        throw ShortcutInfo.getInvalidIconException();
1362                }
1363                if (bitmap == null) {
1364                    Slog.e(TAG, "Null bitmap detected");
1365                    return;
1366                }
1367                // Shrink and write to the file.
1368                File path = null;
1369                try {
1370                    final FileOutputStreamWithPath out = openIconFileForWrite(userId, shortcut);
1371                    try {
1372                        path = out.getFile();
1373
1374                        Bitmap shrunk = shrinkBitmap(bitmap, mMaxIconDimension);
1375                        try {
1376                            shrunk.compress(mIconPersistFormat, mIconPersistQuality, out);
1377                        } finally {
1378                            if (bitmap != shrunk) {
1379                                shrunk.recycle();
1380                            }
1381                        }
1382
1383                        shortcut.setBitmapPath(out.getFile().getAbsolutePath());
1384                        shortcut.addFlags(ShortcutInfo.FLAG_HAS_ICON_FILE);
1385                    } finally {
1386                        IoUtils.closeQuietly(out);
1387                    }
1388                } catch (IOException | RuntimeException e) {
1389                    // STOPSHIP Change wtf to e
1390                    Slog.wtf(ShortcutService.TAG, "Unable to write bitmap to file", e);
1391                    if (path != null && path.exists()) {
1392                        path.delete();
1393                    }
1394                }
1395            } finally {
1396                // Once saved, we won't use the original icon information, so null it out.
1397                shortcut.clearIcon();
1398            }
1399        } finally {
1400            injectRestoreCallingIdentity(token);
1401        }
1402    }
1403
1404    // Unfortunately we can't do this check in unit tests because we fake creator package names,
1405    // so override in unit tests.
1406    // TODO CTS this case.
1407    void injectValidateIconResPackage(ShortcutInfo shortcut, Icon icon) {
1408        if (!shortcut.getPackage().equals(icon.getResPackage())) {
1409            throw new IllegalArgumentException(
1410                    "Icon resource must reside in shortcut owner package");
1411        }
1412    }
1413
1414    @VisibleForTesting
1415    static Bitmap shrinkBitmap(Bitmap in, int maxSize) {
1416        // Original width/height.
1417        final int ow = in.getWidth();
1418        final int oh = in.getHeight();
1419        if ((ow <= maxSize) && (oh <= maxSize)) {
1420            if (DEBUG) {
1421                Slog.d(TAG, String.format("Icon size %dx%d, no need to shrink", ow, oh));
1422            }
1423            return in;
1424        }
1425        final int longerDimension = Math.max(ow, oh);
1426
1427        // New width and height.
1428        final int nw = ow * maxSize / longerDimension;
1429        final int nh = oh * maxSize / longerDimension;
1430        if (DEBUG) {
1431            Slog.d(TAG, String.format("Icon size %dx%d, shrinking to %dx%d",
1432                    ow, oh, nw, nh));
1433        }
1434
1435        final Bitmap scaledBitmap = Bitmap.createBitmap(nw, nh, Bitmap.Config.ARGB_8888);
1436        final Canvas c = new Canvas(scaledBitmap);
1437
1438        final RectF dst = new RectF(0, 0, nw, nh);
1439
1440        c.drawBitmap(in, /*src=*/ null, dst, /* paint =*/ null);
1441
1442        return scaledBitmap;
1443    }
1444
1445    /**
1446     * For a shortcut, update all resource names from resource IDs, and also update all
1447     * resource-based strings.
1448     */
1449    void fixUpShortcutResourceNamesAndValues(ShortcutInfo si) {
1450        final Resources publisherRes = injectGetResourcesForApplicationAsUser(
1451                si.getPackage(), si.getUserId());
1452        if (publisherRes != null) {
1453            final long start = injectElapsedRealtime();
1454            try {
1455                si.lookupAndFillInResourceNames(publisherRes);
1456            } finally {
1457                logDurationStat(Stats.RESOURCE_NAME_LOOKUP, start);
1458            }
1459            si.resolveResourceStrings(publisherRes);
1460        }
1461    }
1462
1463    // === Caller validation ===
1464
1465    private boolean isCallerSystem() {
1466        final int callingUid = injectBinderCallingUid();
1467        return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID);
1468    }
1469
1470    private boolean isCallerShell() {
1471        final int callingUid = injectBinderCallingUid();
1472        return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
1473    }
1474
1475    private void enforceSystemOrShell() {
1476        if (!(isCallerSystem() || isCallerShell())) {
1477            throw new SecurityException("Caller must be system or shell");
1478        }
1479    }
1480
1481    private void enforceShell() {
1482        if (!isCallerShell()) {
1483            throw new SecurityException("Caller must be shell");
1484        }
1485    }
1486
1487    private void enforceSystem() {
1488        if (!isCallerSystem()) {
1489            throw new SecurityException("Caller must be system");
1490        }
1491    }
1492
1493    private void enforceResetThrottlingPermission() {
1494        if (isCallerSystem()) {
1495            return;
1496        }
1497        enforceCallingOrSelfPermission(
1498                android.Manifest.permission.RESET_SHORTCUT_MANAGER_THROTTLING, null);
1499    }
1500
1501    private void enforceCallingOrSelfPermission(
1502            @NonNull String permission, @Nullable String message) {
1503        if (isCallerSystem()) {
1504            return;
1505        }
1506        injectEnforceCallingPermission(permission, message);
1507    }
1508
1509    /**
1510     * Somehow overriding ServiceContext.enforceCallingPermission() in the unit tests would confuse
1511     * mockito.  So instead we extracted it here and override it in the tests.
1512     */
1513    @VisibleForTesting
1514    void injectEnforceCallingPermission(
1515            @NonNull String permission, @Nullable String message) {
1516        mContext.enforceCallingPermission(permission, message);
1517    }
1518
1519    private void verifyCaller(@NonNull String packageName, @UserIdInt int userId) {
1520        Preconditions.checkStringNotEmpty(packageName, "packageName");
1521
1522        if (isCallerSystem()) {
1523            return; // no check
1524        }
1525
1526        final int callingUid = injectBinderCallingUid();
1527
1528        // Otherwise, make sure the arguments are valid.
1529        if (UserHandle.getUserId(callingUid) != userId) {
1530            throw new SecurityException("Invalid user-ID");
1531        }
1532        if (injectGetPackageUid(packageName, userId) != callingUid) {
1533            throw new SecurityException("Calling package name mismatch");
1534        }
1535        Preconditions.checkState(!isEphemeralApp(packageName, userId),
1536                "Ephemeral apps can't use ShortcutManager");
1537    }
1538
1539    // Overridden in unit tests to execute r synchronously.
1540    void injectPostToHandler(Runnable r) {
1541        mHandler.post(r);
1542    }
1543
1544    void injectRunOnNewThread(Runnable r) {
1545        new Thread(r).start();
1546    }
1547
1548    /**
1549     * @throws IllegalArgumentException if {@code numShortcuts} is bigger than
1550     *                                  {@link #getMaxActivityShortcuts()}.
1551     */
1552    void enforceMaxActivityShortcuts(int numShortcuts) {
1553        if (numShortcuts > mMaxShortcuts) {
1554            throw new IllegalArgumentException("Max number of dynamic shortcuts exceeded");
1555        }
1556    }
1557
1558    /**
1559     * Return the max number of dynamic + manifest shortcuts for each launcher icon.
1560     */
1561    int getMaxActivityShortcuts() {
1562        return mMaxShortcuts;
1563    }
1564
1565    /**
1566     * - Sends a notification to LauncherApps
1567     * - Write to file
1568     */
1569    void packageShortcutsChanged(@NonNull String packageName, @UserIdInt int userId) {
1570        if (DEBUG) {
1571            Slog.d(TAG, String.format(
1572                    "Shortcut changes: package=%s, user=%d", packageName, userId));
1573        }
1574        notifyListeners(packageName, userId);
1575        scheduleSaveUser(userId);
1576    }
1577
1578    private void notifyListeners(@NonNull String packageName, @UserIdInt int userId) {
1579        injectPostToHandler(() -> {
1580            try {
1581                final ArrayList<ShortcutChangeListener> copy;
1582                synchronized (mLock) {
1583                    if (!isUserUnlockedL(userId)) {
1584                        return;
1585                    }
1586
1587                    copy = new ArrayList<>(mListeners);
1588                }
1589                // Note onShortcutChanged() needs to be called with the system service permissions.
1590                for (int i = copy.size() - 1; i >= 0; i--) {
1591                    copy.get(i).onShortcutChanged(packageName, userId);
1592                }
1593            } catch (Exception ignore) {
1594            }
1595        });
1596    }
1597
1598    /**
1599     * Clean up / validate an incoming shortcut.
1600     * - Make sure all mandatory fields are set.
1601     * - Make sure the intent's extras are persistable, and them to set
1602     * {@link ShortcutInfo#mIntentPersistableExtrases}.  Also clear its extras.
1603     * - Clear flags.
1604     */
1605    private void fixUpIncomingShortcutInfo(@NonNull ShortcutInfo shortcut, boolean forUpdate,
1606            boolean forPinRequest) {
1607        Preconditions.checkNotNull(shortcut, "Null shortcut detected");
1608        if (shortcut.getActivity() != null) {
1609            Preconditions.checkState(
1610                    shortcut.getPackage().equals(shortcut.getActivity().getPackageName()),
1611                    "Cannot publish shortcut: activity " + shortcut.getActivity() + " does not"
1612                    + " belong to package " + shortcut.getPackage());
1613            Preconditions.checkState(
1614                    injectIsMainActivity(shortcut.getActivity(), shortcut.getUserId()),
1615                    "Cannot publish shortcut: activity " + shortcut.getActivity() + " is not"
1616                            + " main activity");
1617        }
1618
1619        if (!forUpdate) {
1620            shortcut.enforceMandatoryFields(/* forPinned= */ forPinRequest);
1621            if (!forPinRequest) {
1622                Preconditions.checkState(shortcut.getActivity() != null,
1623                        "Cannot publish shortcut: target activity is not set");
1624            }
1625        }
1626        if (shortcut.getIcon() != null) {
1627            ShortcutInfo.validateIcon(shortcut.getIcon());
1628        }
1629
1630        shortcut.replaceFlags(0);
1631    }
1632
1633    private void fixUpIncomingShortcutInfo(@NonNull ShortcutInfo shortcut, boolean forUpdate) {
1634        fixUpIncomingShortcutInfo(shortcut, forUpdate, /*forPinRequest=*/ false);
1635    }
1636
1637    public void validateShortcutForPinRequest(@NonNull ShortcutInfo shortcut) {
1638        fixUpIncomingShortcutInfo(shortcut, /* forUpdate= */ false, /*forPinRequest=*/ true);
1639    }
1640
1641    /**
1642     * When a shortcut has no target activity, set the default one from the package.
1643     */
1644    private void fillInDefaultActivity(List<ShortcutInfo> shortcuts) {
1645        ComponentName defaultActivity = null;
1646        for (int i = shortcuts.size() - 1; i >= 0; i--) {
1647            final ShortcutInfo si = shortcuts.get(i);
1648            if (si.getActivity() == null) {
1649                if (defaultActivity == null) {
1650                    defaultActivity = injectGetDefaultMainActivity(
1651                            si.getPackage(), si.getUserId());
1652                    Preconditions.checkState(defaultActivity != null,
1653                            "Launcher activity not found for package " + si.getPackage());
1654                }
1655                si.setActivity(defaultActivity);
1656            }
1657        }
1658    }
1659
1660    private void assignImplicitRanks(List<ShortcutInfo> shortcuts) {
1661        for (int i = shortcuts.size() - 1; i >= 0; i--) {
1662            shortcuts.get(i).setImplicitRank(i);
1663        }
1664    }
1665
1666    // === APIs ===
1667
1668    @Override
1669    public boolean setDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1670            @UserIdInt int userId) {
1671        verifyCaller(packageName, userId);
1672
1673        final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
1674        final int size = newShortcuts.size();
1675
1676        synchronized (mLock) {
1677            throwIfUserLockedL(userId);
1678
1679            final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
1680
1681            ps.ensureImmutableShortcutsNotIncluded(newShortcuts);
1682
1683            fillInDefaultActivity(newShortcuts);
1684
1685            ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_SET);
1686
1687            // Throttling.
1688            if (!ps.tryApiCall()) {
1689                return false;
1690            }
1691
1692            // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1693            ps.clearAllImplicitRanks();
1694            assignImplicitRanks(newShortcuts);
1695
1696            for (int i = 0; i < size; i++) {
1697                fixUpIncomingShortcutInfo(newShortcuts.get(i), /* forUpdate= */ false);
1698            }
1699
1700            // First, remove all un-pinned; dynamic shortcuts
1701            ps.deleteAllDynamicShortcuts();
1702
1703            // Then, add/update all.  We need to make sure to take over "pinned" flag.
1704            for (int i = 0; i < size; i++) {
1705                final ShortcutInfo newShortcut = newShortcuts.get(i);
1706                ps.addOrUpdateDynamicShortcut(newShortcut);
1707            }
1708
1709            // Lastly, adjust the ranks.
1710            ps.adjustRanks();
1711        }
1712        packageShortcutsChanged(packageName, userId);
1713
1714        verifyStates();
1715
1716        return true;
1717    }
1718
1719    @Override
1720    public boolean updateShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1721            @UserIdInt int userId) {
1722        verifyCaller(packageName, userId);
1723
1724        final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
1725        final int size = newShortcuts.size();
1726
1727        synchronized (mLock) {
1728            throwIfUserLockedL(userId);
1729
1730            final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
1731
1732            ps.ensureImmutableShortcutsNotIncluded(newShortcuts);
1733
1734            // For update, don't fill in the default activity.  Having null activity means
1735            // "don't update the activity" here.
1736
1737            ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_UPDATE);
1738
1739            // Throttling.
1740            if (!ps.tryApiCall()) {
1741                return false;
1742            }
1743
1744            // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1745            ps.clearAllImplicitRanks();
1746            assignImplicitRanks(newShortcuts);
1747
1748            for (int i = 0; i < size; i++) {
1749                final ShortcutInfo source = newShortcuts.get(i);
1750                fixUpIncomingShortcutInfo(source, /* forUpdate= */ true);
1751
1752                final ShortcutInfo target = ps.findShortcutById(source.getId());
1753                if (target == null) {
1754                    continue;
1755                }
1756
1757                if (target.isEnabled() != source.isEnabled()) {
1758                    Slog.w(TAG,
1759                            "ShortcutInfo.enabled cannot be changed with updateShortcuts()");
1760                }
1761
1762                // When updating the rank, we need to insert between existing ranks, so set
1763                // this setRankChanged, and also copy the implicit rank fo adjustRanks().
1764                if (source.hasRank()) {
1765                    target.setRankChanged();
1766                    target.setImplicitRank(source.getImplicitRank());
1767                }
1768
1769                final boolean replacingIcon = (source.getIcon() != null);
1770                if (replacingIcon) {
1771                    removeIcon(userId, target);
1772                }
1773
1774                // Note copyNonNullFieldsFrom() does the "updatable with?" check too.
1775                target.copyNonNullFieldsFrom(source);
1776                target.setTimestamp(injectCurrentTimeMillis());
1777
1778                if (replacingIcon) {
1779                    saveIconAndFixUpShortcut(userId, target);
1780                }
1781
1782                // When we're updating any resource related fields, re-extract the res names and
1783                // the values.
1784                if (replacingIcon || source.hasStringResources()) {
1785                    fixUpShortcutResourceNamesAndValues(target);
1786                }
1787            }
1788
1789            // Lastly, adjust the ranks.
1790            ps.adjustRanks();
1791        }
1792        packageShortcutsChanged(packageName, userId);
1793
1794        verifyStates();
1795
1796        return true;
1797    }
1798
1799    @Override
1800    public boolean addDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1801            @UserIdInt int userId) {
1802        verifyCaller(packageName, userId);
1803
1804        final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
1805        final int size = newShortcuts.size();
1806
1807        synchronized (mLock) {
1808            throwIfUserLockedL(userId);
1809
1810            final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
1811
1812            ps.ensureImmutableShortcutsNotIncluded(newShortcuts);
1813
1814            fillInDefaultActivity(newShortcuts);
1815
1816            ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_ADD);
1817
1818            // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1819            ps.clearAllImplicitRanks();
1820            assignImplicitRanks(newShortcuts);
1821
1822            // Throttling.
1823            if (!ps.tryApiCall()) {
1824                return false;
1825            }
1826            for (int i = 0; i < size; i++) {
1827                final ShortcutInfo newShortcut = newShortcuts.get(i);
1828
1829                // Validate the shortcut.
1830                fixUpIncomingShortcutInfo(newShortcut, /* forUpdate= */ false);
1831
1832                // When ranks are changing, we need to insert between ranks, so set the
1833                // "rank changed" flag.
1834                newShortcut.setRankChanged();
1835
1836                // Add it.
1837                ps.addOrUpdateDynamicShortcut(newShortcut);
1838            }
1839
1840            // Lastly, adjust the ranks.
1841            ps.adjustRanks();
1842        }
1843        packageShortcutsChanged(packageName, userId);
1844
1845        verifyStates();
1846
1847        return true;
1848    }
1849
1850    @Override
1851    public boolean requestPinShortcut(String packageName, ShortcutInfo shortcut,
1852            IntentSender resultIntent, int userId) {
1853        Preconditions.checkNotNull(shortcut);
1854        Preconditions.checkArgument(shortcut.isEnabled(), "Shortcut must be enabled");
1855        return requestPinItem(packageName, userId, shortcut, null, resultIntent);
1856    }
1857
1858    @Override
1859    public Intent createShortcutResultIntent(String packageName, ShortcutInfo shortcut, int userId)
1860            throws RemoteException {
1861        Preconditions.checkNotNull(shortcut);
1862        Preconditions.checkArgument(shortcut.isEnabled(), "Shortcut must be enabled");
1863        verifyCaller(packageName, userId);
1864
1865        final Intent ret;
1866        synchronized (mLock) {
1867            throwIfUserLockedL(userId);
1868
1869            // Send request to the launcher, if supported.
1870            ret = mShortcutRequestPinProcessor.createShortcutResultIntent(shortcut, userId);
1871        }
1872
1873        verifyStates();
1874        return ret;
1875    }
1876
1877    /**
1878     * Handles {@link #requestPinShortcut} and {@link ShortcutServiceInternal#requestPinAppWidget}.
1879     * After validating the caller, it passes the request to {@link #mShortcutRequestPinProcessor}.
1880     * Either {@param shortcut} or {@param appWidget} should be non-null.
1881     */
1882    private boolean requestPinItem(String packageName, int userId,
1883            ShortcutInfo shortcut, AppWidgetProviderInfo appWidget, IntentSender resultIntent) {
1884        verifyCaller(packageName, userId);
1885
1886        final boolean ret;
1887        synchronized (mLock) {
1888            throwIfUserLockedL(userId);
1889
1890            Preconditions.checkState(isUidForegroundLocked(injectBinderCallingUid()),
1891                    "Calling application must have a foreground activity or a foreground service");
1892
1893            // Send request to the launcher, if supported.
1894            ret = mShortcutRequestPinProcessor.requestPinItemLocked(shortcut, appWidget, userId,
1895                    resultIntent);
1896        }
1897
1898        verifyStates();
1899
1900        return ret;
1901    }
1902
1903    @Override
1904    public void disableShortcuts(String packageName, List shortcutIds,
1905            CharSequence disabledMessage, int disabledMessageResId, @UserIdInt int userId) {
1906        verifyCaller(packageName, userId);
1907        Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
1908
1909        synchronized (mLock) {
1910            throwIfUserLockedL(userId);
1911
1912            final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
1913
1914            ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds);
1915
1916            final String disabledMessageString =
1917                    (disabledMessage == null) ? null : disabledMessage.toString();
1918
1919            for (int i = shortcutIds.size() - 1; i >= 0; i--) {
1920                ps.disableWithId(Preconditions.checkStringNotEmpty((String) shortcutIds.get(i)),
1921                        disabledMessageString, disabledMessageResId,
1922                        /* overrideImmutable=*/ false);
1923            }
1924
1925            // We may have removed dynamic shortcuts which may have left a gap, so adjust the ranks.
1926            ps.adjustRanks();
1927        }
1928        packageShortcutsChanged(packageName, userId);
1929
1930        verifyStates();
1931    }
1932
1933    @Override
1934    public void enableShortcuts(String packageName, List shortcutIds, @UserIdInt int userId) {
1935        verifyCaller(packageName, userId);
1936        Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
1937
1938        synchronized (mLock) {
1939            throwIfUserLockedL(userId);
1940
1941            final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
1942
1943            ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds);
1944
1945            for (int i = shortcutIds.size() - 1; i >= 0; i--) {
1946                ps.enableWithId((String) shortcutIds.get(i));
1947            }
1948        }
1949        packageShortcutsChanged(packageName, userId);
1950
1951        verifyStates();
1952    }
1953
1954    @Override
1955    public void removeDynamicShortcuts(String packageName, List shortcutIds,
1956            @UserIdInt int userId) {
1957        verifyCaller(packageName, userId);
1958        Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
1959
1960        synchronized (mLock) {
1961            throwIfUserLockedL(userId);
1962
1963            final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
1964
1965            ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds);
1966
1967            for (int i = shortcutIds.size() - 1; i >= 0; i--) {
1968                ps.deleteDynamicWithId(
1969                        Preconditions.checkStringNotEmpty((String) shortcutIds.get(i)));
1970            }
1971
1972            // We may have removed dynamic shortcuts which may have left a gap, so adjust the ranks.
1973            ps.adjustRanks();
1974        }
1975        packageShortcutsChanged(packageName, userId);
1976
1977        verifyStates();
1978    }
1979
1980    @Override
1981    public void removeAllDynamicShortcuts(String packageName, @UserIdInt int userId) {
1982        verifyCaller(packageName, userId);
1983
1984        synchronized (mLock) {
1985            throwIfUserLockedL(userId);
1986
1987            final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
1988            ps.deleteAllDynamicShortcuts();
1989        }
1990        packageShortcutsChanged(packageName, userId);
1991
1992        verifyStates();
1993    }
1994
1995    @Override
1996    public ParceledListSlice<ShortcutInfo> getDynamicShortcuts(String packageName,
1997            @UserIdInt int userId) {
1998        verifyCaller(packageName, userId);
1999
2000        synchronized (mLock) {
2001            throwIfUserLockedL(userId);
2002
2003            return getShortcutsWithQueryLocked(
2004                    packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
2005                    ShortcutInfo::isDynamic);
2006        }
2007    }
2008
2009    @Override
2010    public ParceledListSlice<ShortcutInfo> getManifestShortcuts(String packageName,
2011            @UserIdInt int userId) {
2012        verifyCaller(packageName, userId);
2013
2014        synchronized (mLock) {
2015            throwIfUserLockedL(userId);
2016
2017            return getShortcutsWithQueryLocked(
2018                    packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
2019                    ShortcutInfo::isManifestShortcut);
2020        }
2021    }
2022
2023    @Override
2024    public ParceledListSlice<ShortcutInfo> getPinnedShortcuts(String packageName,
2025            @UserIdInt int userId) {
2026        verifyCaller(packageName, userId);
2027
2028        synchronized (mLock) {
2029            throwIfUserLockedL(userId);
2030
2031            return getShortcutsWithQueryLocked(
2032                    packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
2033                    ShortcutInfo::isPinned);
2034        }
2035    }
2036
2037    private ParceledListSlice<ShortcutInfo> getShortcutsWithQueryLocked(@NonNull String packageName,
2038            @UserIdInt int userId, int cloneFlags, @NonNull Predicate<ShortcutInfo> query) {
2039
2040        final ArrayList<ShortcutInfo> ret = new ArrayList<>();
2041
2042        final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
2043        ps.findAll(ret, query, cloneFlags);
2044
2045        return new ParceledListSlice<>(ret);
2046    }
2047
2048    @Override
2049    public int getMaxShortcutCountPerActivity(String packageName, @UserIdInt int userId)
2050            throws RemoteException {
2051        verifyCaller(packageName, userId);
2052
2053        return mMaxShortcuts;
2054    }
2055
2056    @Override
2057    public int getRemainingCallCount(String packageName, @UserIdInt int userId) {
2058        verifyCaller(packageName, userId);
2059
2060        synchronized (mLock) {
2061            throwIfUserLockedL(userId);
2062
2063            final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
2064            return mMaxUpdatesPerInterval - ps.getApiCallCount();
2065        }
2066    }
2067
2068    @Override
2069    public long getRateLimitResetTime(String packageName, @UserIdInt int userId) {
2070        verifyCaller(packageName, userId);
2071
2072        synchronized (mLock) {
2073            throwIfUserLockedL(userId);
2074
2075            return getNextResetTimeLocked();
2076        }
2077    }
2078
2079    @Override
2080    public int getIconMaxDimensions(String packageName, int userId) {
2081        verifyCaller(packageName, userId);
2082
2083        synchronized (mLock) {
2084            return mMaxIconDimension;
2085        }
2086    }
2087
2088    @Override
2089    public void reportShortcutUsed(String packageName, String shortcutId, int userId) {
2090        verifyCaller(packageName, userId);
2091
2092        Preconditions.checkNotNull(shortcutId);
2093
2094        if (DEBUG) {
2095            Slog.d(TAG, String.format("reportShortcutUsed: Shortcut %s package %s used on user %d",
2096                    shortcutId, packageName, userId));
2097        }
2098
2099        synchronized (mLock) {
2100            throwIfUserLockedL(userId);
2101
2102            final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
2103
2104            if (ps.findShortcutById(shortcutId) == null) {
2105                Log.w(TAG, String.format("reportShortcutUsed: package %s doesn't have shortcut %s",
2106                        packageName, shortcutId));
2107                return;
2108            }
2109        }
2110
2111        final long token = injectClearCallingIdentity();
2112        try {
2113            mUsageStatsManagerInternal.reportShortcutUsage(packageName, shortcutId, userId);
2114        } finally {
2115            injectRestoreCallingIdentity(token);
2116        }
2117    }
2118
2119    @Override
2120    public boolean isRequestPinShortcutSupported(int callingUserId) {
2121        final long token = injectClearCallingIdentity();
2122        try {
2123            return mShortcutRequestPinProcessor.isRequestPinnedShortcutSupported(callingUserId);
2124        } finally {
2125            injectRestoreCallingIdentity(token);
2126        }
2127    }
2128
2129    /**
2130     * Reset all throttling, for developer options and command line.  Only system/shell can call
2131     * it.
2132     */
2133    @Override
2134    public void resetThrottling() {
2135        enforceSystemOrShell();
2136
2137        resetThrottlingInner(getCallingUserId());
2138    }
2139
2140    void resetThrottlingInner(@UserIdInt int userId) {
2141        synchronized (mLock) {
2142            if (!isUserUnlockedL(userId)) {
2143                Log.w(TAG, "User " + userId + " is locked or not running");
2144                return;
2145            }
2146
2147            getUserShortcutsLocked(userId).resetThrottling();
2148        }
2149        scheduleSaveUser(userId);
2150        Slog.i(TAG, "ShortcutManager: throttling counter reset for user " + userId);
2151    }
2152
2153    void resetAllThrottlingInner() {
2154        synchronized (mLock) {
2155            mRawLastResetTime = injectCurrentTimeMillis();
2156        }
2157        scheduleSaveBaseState();
2158        Slog.i(TAG, "ShortcutManager: throttling counter reset for all users");
2159    }
2160
2161    @Override
2162    public void onApplicationActive(String packageName, int userId) {
2163        if (DEBUG) {
2164            Slog.d(TAG, "onApplicationActive: package=" + packageName + "  userid=" + userId);
2165        }
2166        enforceResetThrottlingPermission();
2167
2168        synchronized (mLock) {
2169            if (!isUserUnlockedL(userId)) {
2170                // This is called by system UI, so no need to throw.  Just ignore.
2171                return;
2172            }
2173
2174            getPackageShortcutsLocked(packageName, userId)
2175                    .resetRateLimitingForCommandLineNoSaving();
2176            saveUserLocked(userId);
2177        }
2178    }
2179
2180    // We override this method in unit tests to do a simpler check.
2181    boolean hasShortcutHostPermission(@NonNull String callingPackage, int userId) {
2182        final long start = injectElapsedRealtime();
2183        try {
2184            return hasShortcutHostPermissionInner(callingPackage, userId);
2185        } finally {
2186            logDurationStat(Stats.LAUNCHER_PERMISSION_CHECK, start);
2187        }
2188    }
2189
2190    // This method is extracted so we can directly call this method from unit tests,
2191    // even when hasShortcutPermission() is overridden.
2192    @VisibleForTesting
2193    boolean hasShortcutHostPermissionInner(@NonNull String packageName, int userId) {
2194        synchronized (mLock) {
2195            throwIfUserLockedL(userId);
2196
2197            final ShortcutUser user = getUserShortcutsLocked(userId);
2198
2199            // Always trust the cached component.
2200            final ComponentName cached = user.getCachedLauncher();
2201            if (cached != null) {
2202                if (cached.getPackageName().equals(packageName)) {
2203                    return true;
2204                }
2205            }
2206            // If the cached one doesn't match, then go ahead
2207
2208            final ComponentName detected = getDefaultLauncher(userId);
2209
2210            // Update the cache.
2211            user.setLauncher(detected);
2212            if (detected != null) {
2213                if (DEBUG) {
2214                    Slog.v(TAG, "Detected launcher: " + detected);
2215                }
2216                return detected.getPackageName().equals(packageName);
2217            } else {
2218                // Default launcher not found.
2219                return false;
2220            }
2221        }
2222    }
2223
2224    @Nullable
2225    ComponentName getDefaultLauncher(@UserIdInt int userId) {
2226        final long start = injectElapsedRealtime();
2227        final long token = injectClearCallingIdentity();
2228        try {
2229            synchronized (mLock) {
2230                throwIfUserLockedL(userId);
2231
2232                final ShortcutUser user = getUserShortcutsLocked(userId);
2233
2234                final List<ResolveInfo> allHomeCandidates = new ArrayList<>();
2235
2236                // Default launcher from package manager.
2237                final long startGetHomeActivitiesAsUser = injectElapsedRealtime();
2238                final ComponentName defaultLauncher = mPackageManagerInternal
2239                        .getHomeActivitiesAsUser(allHomeCandidates, userId);
2240                logDurationStat(Stats.GET_DEFAULT_HOME, startGetHomeActivitiesAsUser);
2241
2242                ComponentName detected = null;
2243                if (defaultLauncher != null) {
2244                    detected = defaultLauncher;
2245                    if (DEBUG) {
2246                        Slog.v(TAG, "Default launcher from PM: " + detected);
2247                    }
2248                } else {
2249                    detected = user.getLastKnownLauncher();
2250
2251                    if (detected != null) {
2252                        if (injectIsActivityEnabledAndExported(detected, userId)) {
2253                            if (DEBUG) {
2254                                Slog.v(TAG, "Cached launcher: " + detected);
2255                            }
2256                        } else {
2257                            Slog.w(TAG, "Cached launcher " + detected + " no longer exists");
2258                            detected = null;
2259                            user.clearLauncher();
2260                        }
2261                    }
2262                }
2263
2264                if (detected == null) {
2265                    // If we reach here, that means it's the first check since the user was created,
2266                    // and there's already multiple launchers and there's no default set.
2267                    // Find the system one with the highest priority.
2268                    // (We need to check the priority too because of FallbackHome in Settings.)
2269                    // If there's no system launcher yet, then no one can access shortcuts, until
2270                    // the user explicitly
2271                    final int size = allHomeCandidates.size();
2272
2273                    int lastPriority = Integer.MIN_VALUE;
2274                    for (int i = 0; i < size; i++) {
2275                        final ResolveInfo ri = allHomeCandidates.get(i);
2276                        if (!ri.activityInfo.applicationInfo.isSystemApp()) {
2277                            continue;
2278                        }
2279                        if (DEBUG) {
2280                            Slog.d(TAG, String.format("hasShortcutPermissionInner: pkg=%s prio=%d",
2281                                    ri.activityInfo.getComponentName(), ri.priority));
2282                        }
2283                        if (ri.priority < lastPriority) {
2284                            continue;
2285                        }
2286                        detected = ri.activityInfo.getComponentName();
2287                        lastPriority = ri.priority;
2288                    }
2289                }
2290                return detected;
2291            }
2292        } finally {
2293            injectRestoreCallingIdentity(token);
2294            logDurationStat(Stats.GET_DEFAULT_LAUNCHER, start);
2295        }
2296    }
2297
2298    // === House keeping ===
2299
2300    private void cleanUpPackageForAllLoadedUsers(String packageName, @UserIdInt int packageUserId,
2301            boolean appStillExists) {
2302        synchronized (mLock) {
2303            forEachLoadedUserLocked(user ->
2304                    cleanUpPackageLocked(packageName, user.getUserId(), packageUserId,
2305                            appStillExists));
2306        }
2307    }
2308
2309    /**
2310     * Remove all the information associated with a package.  This will really remove all the
2311     * information, including the restore information (i.e. it'll remove packages even if they're
2312     * shadow).
2313     *
2314     * This is called when an app is uninstalled, or an app gets "clear data"ed.
2315     */
2316    @VisibleForTesting
2317    void cleanUpPackageLocked(String packageName, int owningUserId, int packageUserId,
2318            boolean appStillExists) {
2319        final boolean wasUserLoaded = isUserLoadedLocked(owningUserId);
2320
2321        final ShortcutUser user = getUserShortcutsLocked(owningUserId);
2322        boolean doNotify = false;
2323
2324        // First, remove the package from the package list (if the package is a publisher).
2325        if (packageUserId == owningUserId) {
2326            if (user.removePackage(packageName) != null) {
2327                doNotify = true;
2328            }
2329        }
2330
2331        // Also remove from the launcher list (if the package is a launcher).
2332        user.removeLauncher(packageUserId, packageName);
2333
2334        // Then remove pinned shortcuts from all launchers.
2335        user.forAllLaunchers(l -> l.cleanUpPackage(packageName, packageUserId));
2336
2337        // Now there may be orphan shortcuts because we removed pinned shortcuts at the previous
2338        // step.  Remove them too.
2339        user.forAllPackages(p -> p.refreshPinnedFlags());
2340
2341        scheduleSaveUser(owningUserId);
2342
2343        if (doNotify) {
2344            notifyListeners(packageName, owningUserId);
2345        }
2346
2347        // If the app still exists (i.e. data cleared), we need to re-publish manifest shortcuts.
2348        if (appStillExists && (packageUserId == owningUserId)) {
2349            // This will do the notification and save when needed, so do it after the above
2350            // notifyListeners.
2351            user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
2352        }
2353
2354        if (!wasUserLoaded) {
2355            // Note this will execute the scheduled save.
2356            unloadUserLocked(owningUserId);
2357        }
2358    }
2359
2360    /**
2361     * Entry point from {@link LauncherApps}.
2362     */
2363    private class LocalService extends ShortcutServiceInternal {
2364
2365        @Override
2366        public List<ShortcutInfo> getShortcuts(int launcherUserId,
2367                @NonNull String callingPackage, long changedSince,
2368                @Nullable String packageName, @Nullable List<String> shortcutIds,
2369                @Nullable ComponentName componentName,
2370                int queryFlags, int userId) {
2371            final ArrayList<ShortcutInfo> ret = new ArrayList<>();
2372
2373            final boolean cloneKeyFieldOnly =
2374                    ((queryFlags & ShortcutQuery.FLAG_GET_KEY_FIELDS_ONLY) != 0);
2375            final int cloneFlag = cloneKeyFieldOnly ? ShortcutInfo.CLONE_REMOVE_NON_KEY_INFO
2376                    : ShortcutInfo.CLONE_REMOVE_FOR_LAUNCHER;
2377            if (packageName == null) {
2378                shortcutIds = null; // LauncherAppsService already threw for it though.
2379            }
2380
2381            synchronized (mLock) {
2382                throwIfUserLockedL(userId);
2383                throwIfUserLockedL(launcherUserId);
2384
2385                getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
2386                        .attemptToRestoreIfNeededAndSave();
2387
2388                if (packageName != null) {
2389                    getShortcutsInnerLocked(launcherUserId,
2390                            callingPackage, packageName, shortcutIds, changedSince,
2391                            componentName, queryFlags, userId, ret, cloneFlag);
2392                } else {
2393                    final List<String> shortcutIdsF = shortcutIds;
2394                    getUserShortcutsLocked(userId).forAllPackages(p -> {
2395                        getShortcutsInnerLocked(launcherUserId,
2396                                callingPackage, p.getPackageName(), shortcutIdsF, changedSince,
2397                                componentName, queryFlags, userId, ret, cloneFlag);
2398                    });
2399                }
2400            }
2401            return ret;
2402        }
2403
2404        private void getShortcutsInnerLocked(int launcherUserId, @NonNull String callingPackage,
2405                @Nullable String packageName, @Nullable List<String> shortcutIds, long changedSince,
2406                @Nullable ComponentName componentName, int queryFlags,
2407                int userId, ArrayList<ShortcutInfo> ret, int cloneFlag) {
2408            final ArraySet<String> ids = shortcutIds == null ? null
2409                    : new ArraySet<>(shortcutIds);
2410
2411            final ShortcutPackage p = getUserShortcutsLocked(userId)
2412                    .getPackageShortcutsIfExists(packageName);
2413            if (p == null) {
2414                return; // No need to instantiate ShortcutPackage.
2415            }
2416
2417            p.findAll(ret,
2418                    (ShortcutInfo si) -> {
2419                        if (si.getLastChangedTimestamp() < changedSince) {
2420                            return false;
2421                        }
2422                        if (ids != null && !ids.contains(si.getId())) {
2423                            return false;
2424                        }
2425                        if (componentName != null) {
2426                            if (si.getActivity() != null
2427                                    && !si.getActivity().equals(componentName)) {
2428                                return false;
2429                            }
2430                        }
2431                        if (((queryFlags & ShortcutQuery.FLAG_GET_DYNAMIC) != 0)
2432                                && si.isDynamic()) {
2433                            return true;
2434                        }
2435                        if (((queryFlags & ShortcutQuery.FLAG_GET_PINNED) != 0)
2436                                && si.isPinned()) {
2437                            return true;
2438                        }
2439                        if (((queryFlags & ShortcutQuery.FLAG_GET_MANIFEST) != 0)
2440                                && si.isManifestShortcut()) {
2441                            return true;
2442                        }
2443                        return false;
2444                    }, cloneFlag, callingPackage, launcherUserId);
2445        }
2446
2447        @Override
2448        public boolean isPinnedByCaller(int launcherUserId, @NonNull String callingPackage,
2449                @NonNull String packageName, @NonNull String shortcutId, int userId) {
2450            Preconditions.checkStringNotEmpty(packageName, "packageName");
2451            Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
2452
2453            synchronized (mLock) {
2454                throwIfUserLockedL(userId);
2455                throwIfUserLockedL(launcherUserId);
2456
2457                getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
2458                        .attemptToRestoreIfNeededAndSave();
2459
2460                final ShortcutInfo si = getShortcutInfoLocked(
2461                        launcherUserId, callingPackage, packageName, shortcutId, userId);
2462                return si != null && si.isPinned();
2463            }
2464        }
2465
2466        private ShortcutInfo getShortcutInfoLocked(
2467                int launcherUserId, @NonNull String callingPackage,
2468                @NonNull String packageName, @NonNull String shortcutId, int userId) {
2469            Preconditions.checkStringNotEmpty(packageName, "packageName");
2470            Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
2471
2472            throwIfUserLockedL(userId);
2473            throwIfUserLockedL(launcherUserId);
2474
2475            final ShortcutPackage p = getUserShortcutsLocked(userId)
2476                    .getPackageShortcutsIfExists(packageName);
2477            if (p == null) {
2478                return null;
2479            }
2480
2481            final ArrayList<ShortcutInfo> list = new ArrayList<>(1);
2482            p.findAll(list,
2483                    (ShortcutInfo si) -> shortcutId.equals(si.getId()),
2484                    /* clone flags=*/ 0, callingPackage, launcherUserId);
2485            return list.size() == 0 ? null : list.get(0);
2486        }
2487
2488        @Override
2489        public void pinShortcuts(int launcherUserId,
2490                @NonNull String callingPackage, @NonNull String packageName,
2491                @NonNull List<String> shortcutIds, int userId) {
2492            // Calling permission must be checked by LauncherAppsImpl.
2493            Preconditions.checkStringNotEmpty(packageName, "packageName");
2494            Preconditions.checkNotNull(shortcutIds, "shortcutIds");
2495
2496            synchronized (mLock) {
2497                throwIfUserLockedL(userId);
2498                throwIfUserLockedL(launcherUserId);
2499
2500                final ShortcutLauncher launcher =
2501                        getLauncherShortcutsLocked(callingPackage, userId, launcherUserId);
2502                launcher.attemptToRestoreIfNeededAndSave();
2503
2504                launcher.pinShortcuts(userId, packageName, shortcutIds);
2505            }
2506            packageShortcutsChanged(packageName, userId);
2507
2508            verifyStates();
2509        }
2510
2511        @Override
2512        public Intent[] createShortcutIntents(int launcherUserId,
2513                @NonNull String callingPackage,
2514                @NonNull String packageName, @NonNull String shortcutId, int userId) {
2515            // Calling permission must be checked by LauncherAppsImpl.
2516            Preconditions.checkStringNotEmpty(packageName, "packageName can't be empty");
2517            Preconditions.checkStringNotEmpty(shortcutId, "shortcutId can't be empty");
2518
2519            synchronized (mLock) {
2520                throwIfUserLockedL(userId);
2521                throwIfUserLockedL(launcherUserId);
2522
2523                getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
2524                        .attemptToRestoreIfNeededAndSave();
2525
2526                // Make sure the shortcut is actually visible to the launcher.
2527                final ShortcutInfo si = getShortcutInfoLocked(
2528                        launcherUserId, callingPackage, packageName, shortcutId, userId);
2529                // "si == null" should suffice here, but check the flags too just to make sure.
2530                if (si == null || !si.isEnabled() || !si.isAlive()) {
2531                    Log.e(TAG, "Shortcut " + shortcutId + " does not exist or disabled");
2532                    return null;
2533                }
2534                return si.getIntents();
2535            }
2536        }
2537
2538        @Override
2539        public void addListener(@NonNull ShortcutChangeListener listener) {
2540            synchronized (mLock) {
2541                mListeners.add(Preconditions.checkNotNull(listener));
2542            }
2543        }
2544
2545        @Override
2546        public int getShortcutIconResId(int launcherUserId, @NonNull String callingPackage,
2547                @NonNull String packageName, @NonNull String shortcutId, int userId) {
2548            Preconditions.checkNotNull(callingPackage, "callingPackage");
2549            Preconditions.checkNotNull(packageName, "packageName");
2550            Preconditions.checkNotNull(shortcutId, "shortcutId");
2551
2552            synchronized (mLock) {
2553                throwIfUserLockedL(userId);
2554                throwIfUserLockedL(launcherUserId);
2555
2556                getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
2557                        .attemptToRestoreIfNeededAndSave();
2558
2559                final ShortcutPackage p = getUserShortcutsLocked(userId)
2560                        .getPackageShortcutsIfExists(packageName);
2561                if (p == null) {
2562                    return 0;
2563                }
2564
2565                final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId);
2566                return (shortcutInfo != null && shortcutInfo.hasIconResource())
2567                        ? shortcutInfo.getIconResourceId() : 0;
2568            }
2569        }
2570
2571        @Override
2572        public ParcelFileDescriptor getShortcutIconFd(int launcherUserId,
2573                @NonNull String callingPackage, @NonNull String packageName,
2574                @NonNull String shortcutId, int userId) {
2575            Preconditions.checkNotNull(callingPackage, "callingPackage");
2576            Preconditions.checkNotNull(packageName, "packageName");
2577            Preconditions.checkNotNull(shortcutId, "shortcutId");
2578
2579            synchronized (mLock) {
2580                throwIfUserLockedL(userId);
2581                throwIfUserLockedL(launcherUserId);
2582
2583                getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
2584                        .attemptToRestoreIfNeededAndSave();
2585
2586                final ShortcutPackage p = getUserShortcutsLocked(userId)
2587                        .getPackageShortcutsIfExists(packageName);
2588                if (p == null) {
2589                    return null;
2590                }
2591
2592                final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId);
2593                if (shortcutInfo == null || !shortcutInfo.hasIconFile()) {
2594                    return null;
2595                }
2596                try {
2597                    if (shortcutInfo.getBitmapPath() == null) {
2598                        Slog.w(TAG, "null bitmap detected in getShortcutIconFd()");
2599                        return null;
2600                    }
2601                    return ParcelFileDescriptor.open(
2602                            new File(shortcutInfo.getBitmapPath()),
2603                            ParcelFileDescriptor.MODE_READ_ONLY);
2604                } catch (FileNotFoundException e) {
2605                    Slog.e(TAG, "Icon file not found: " + shortcutInfo.getBitmapPath());
2606                    return null;
2607                }
2608            }
2609        }
2610
2611        @Override
2612        public boolean hasShortcutHostPermission(int launcherUserId,
2613                @NonNull String callingPackage) {
2614            return ShortcutService.this.hasShortcutHostPermission(callingPackage, launcherUserId);
2615        }
2616
2617        @Override
2618        public boolean requestPinAppWidget(@NonNull String callingPackage,
2619                @NonNull AppWidgetProviderInfo appWidget, @Nullable IntentSender resultIntent,
2620                int userId) {
2621            Preconditions.checkNotNull(appWidget);
2622            return requestPinItem(callingPackage, userId, null, appWidget, resultIntent);
2623        }
2624    }
2625
2626    final BroadcastReceiver mReceiver = new BroadcastReceiver() {
2627        @Override
2628        public void onReceive(Context context, Intent intent) {
2629            if (!mBootCompleted.get()) {
2630                return; // Boot not completed, ignore the broadcast.
2631            }
2632            try {
2633                if (Intent.ACTION_LOCALE_CHANGED.equals(intent.getAction())) {
2634                    handleLocaleChanged();
2635                }
2636            } catch (Exception e) {
2637                wtf("Exception in mReceiver.onReceive", e);
2638            }
2639        }
2640    };
2641
2642    void handleLocaleChanged() {
2643        if (DEBUG) {
2644            Slog.d(TAG, "handleLocaleChanged");
2645        }
2646        scheduleSaveBaseState();
2647
2648        synchronized (mLock) {
2649            final long token = injectClearCallingIdentity();
2650            try {
2651                forEachLoadedUserLocked(user -> user.detectLocaleChange());
2652            } finally {
2653                injectRestoreCallingIdentity(token);
2654            }
2655        }
2656    }
2657
2658    /**
2659     * Package event callbacks.
2660     */
2661    @VisibleForTesting
2662    final BroadcastReceiver mPackageMonitor = new BroadcastReceiver() {
2663        @Override
2664        public void onReceive(Context context, Intent intent) {
2665            final int userId  = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
2666            if (userId == UserHandle.USER_NULL) {
2667                Slog.w(TAG, "Intent broadcast does not contain user handle: " + intent);
2668                return;
2669            }
2670
2671            final String action = intent.getAction();
2672
2673            // This is normally called on Handler, so clearCallingIdentity() isn't needed,
2674            // but we still check it in unit tests.
2675            final long token = injectClearCallingIdentity();
2676            try {
2677                synchronized (mLock) {
2678                    if (!isUserUnlockedL(userId)) {
2679                        if (DEBUG) {
2680                            Slog.d(TAG, "Ignoring package broadcast " + action
2681                                    + " for locked/stopped user " + userId);
2682                        }
2683                        return;
2684                    }
2685
2686                    // Whenever we get one of those package broadcasts, or get
2687                    // ACTION_PREFERRED_ACTIVITY_CHANGED, we purge the default launcher cache.
2688                    final ShortcutUser user = getUserShortcutsLocked(userId);
2689                    user.clearLauncher();
2690                }
2691                if (Intent.ACTION_PREFERRED_ACTIVITY_CHANGED.equals(action)) {
2692                    // Nothing farther to do.
2693                    return;
2694                }
2695
2696                final Uri intentUri = intent.getData();
2697                final String packageName = (intentUri != null) ? intentUri.getSchemeSpecificPart()
2698                        : null;
2699                if (packageName == null) {
2700                    Slog.w(TAG, "Intent broadcast does not contain package name: " + intent);
2701                    return;
2702                }
2703
2704                final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
2705
2706                switch (action) {
2707                    case Intent.ACTION_PACKAGE_ADDED:
2708                        if (replacing) {
2709                            handlePackageUpdateFinished(packageName, userId);
2710                        } else {
2711                            handlePackageAdded(packageName, userId);
2712                        }
2713                        break;
2714                    case Intent.ACTION_PACKAGE_REMOVED:
2715                        if (!replacing) {
2716                            handlePackageRemoved(packageName, userId);
2717                        }
2718                        break;
2719                    case Intent.ACTION_PACKAGE_CHANGED:
2720                        handlePackageChanged(packageName, userId);
2721
2722                        break;
2723                    case Intent.ACTION_PACKAGE_DATA_CLEARED:
2724                        handlePackageDataCleared(packageName, userId);
2725                        break;
2726                }
2727            } catch (Exception e) {
2728                wtf("Exception in mPackageMonitor.onReceive", e);
2729            } finally {
2730                injectRestoreCallingIdentity(token);
2731            }
2732        }
2733    };
2734
2735    /**
2736     * Called when a user is unlocked.
2737     * - Check all known packages still exist, and otherwise perform cleanup.
2738     * - If a package still exists, check the version code.  If it's been updated, may need to
2739     * update timestamps of its shortcuts.
2740     */
2741    @VisibleForTesting
2742    void checkPackageChanges(@UserIdInt int ownerUserId) {
2743        if (DEBUG) {
2744            Slog.d(TAG, "checkPackageChanges() ownerUserId=" + ownerUserId);
2745        }
2746        if (injectIsSafeModeEnabled()) {
2747            Slog.i(TAG, "Safe mode, skipping checkPackageChanges()");
2748            return;
2749        }
2750
2751        final long start = injectElapsedRealtime();
2752        try {
2753            final ArrayList<PackageWithUser> gonePackages = new ArrayList<>();
2754
2755            synchronized (mLock) {
2756                final ShortcutUser user = getUserShortcutsLocked(ownerUserId);
2757
2758                // Find packages that have been uninstalled.
2759                user.forAllPackageItems(spi -> {
2760                    if (spi.getPackageInfo().isShadow()) {
2761                        return; // Don't delete shadow information.
2762                    }
2763                    if (!isPackageInstalled(spi.getPackageName(), spi.getPackageUserId())) {
2764                        if (DEBUG) {
2765                            Slog.d(TAG, "Uninstalled: " + spi.getPackageName()
2766                                    + " user " + spi.getPackageUserId());
2767                        }
2768                        gonePackages.add(PackageWithUser.of(spi));
2769                    }
2770                });
2771                if (gonePackages.size() > 0) {
2772                    for (int i = gonePackages.size() - 1; i >= 0; i--) {
2773                        final PackageWithUser pu = gonePackages.get(i);
2774                        cleanUpPackageLocked(pu.packageName, ownerUserId, pu.userId,
2775                                /* appStillExists = */ false);
2776                    }
2777                }
2778
2779                rescanUpdatedPackagesLocked(ownerUserId, user.getLastAppScanTime());
2780            }
2781        } finally {
2782            logDurationStat(Stats.CHECK_PACKAGE_CHANGES, start);
2783        }
2784        verifyStates();
2785    }
2786
2787    private void rescanUpdatedPackagesLocked(@UserIdInt int userId, long lastScanTime) {
2788        final ShortcutUser user = getUserShortcutsLocked(userId);
2789
2790        // Note after each OTA, we'll need to rescan all system apps, as their lastUpdateTime
2791        // is not reliable.
2792        final long now = injectCurrentTimeMillis();
2793        final boolean afterOta =
2794                !injectBuildFingerprint().equals(user.getLastAppScanOsFingerprint());
2795
2796        // Then for each installed app, publish manifest shortcuts when needed.
2797        forUpdatedPackages(userId, lastScanTime, afterOta, ai -> {
2798            user.attemptToRestoreIfNeededAndSave(this, ai.packageName, userId);
2799
2800            user.rescanPackageIfNeeded(ai.packageName, /* forceRescan= */ true);
2801        });
2802
2803        // Write the time just before the scan, because there may be apps that have just
2804        // been updated, and we want to catch them in the next time.
2805        user.setLastAppScanTime(now);
2806        user.setLastAppScanOsFingerprint(injectBuildFingerprint());
2807        scheduleSaveUser(userId);
2808    }
2809
2810    private void handlePackageAdded(String packageName, @UserIdInt int userId) {
2811        if (DEBUG) {
2812            Slog.d(TAG, String.format("handlePackageAdded: %s user=%d", packageName, userId));
2813        }
2814        synchronized (mLock) {
2815            final ShortcutUser user = getUserShortcutsLocked(userId);
2816            user.attemptToRestoreIfNeededAndSave(this, packageName, userId);
2817            user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
2818        }
2819        verifyStates();
2820    }
2821
2822    private void handlePackageUpdateFinished(String packageName, @UserIdInt int userId) {
2823        if (DEBUG) {
2824            Slog.d(TAG, String.format("handlePackageUpdateFinished: %s user=%d",
2825                    packageName, userId));
2826        }
2827        synchronized (mLock) {
2828            final ShortcutUser user = getUserShortcutsLocked(userId);
2829            user.attemptToRestoreIfNeededAndSave(this, packageName, userId);
2830
2831            if (isPackageInstalled(packageName, userId)) {
2832                user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
2833            }
2834        }
2835        verifyStates();
2836    }
2837
2838    private void handlePackageRemoved(String packageName, @UserIdInt int packageUserId) {
2839        if (DEBUG) {
2840            Slog.d(TAG, String.format("handlePackageRemoved: %s user=%d", packageName,
2841                    packageUserId));
2842        }
2843        cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ false);
2844
2845        verifyStates();
2846    }
2847
2848    private void handlePackageDataCleared(String packageName, int packageUserId) {
2849        if (DEBUG) {
2850            Slog.d(TAG, String.format("handlePackageDataCleared: %s user=%d", packageName,
2851                    packageUserId));
2852        }
2853        cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ true);
2854
2855        verifyStates();
2856    }
2857
2858    private void handlePackageChanged(String packageName, int packageUserId) {
2859        if (DEBUG) {
2860            Slog.d(TAG, String.format("handlePackageChanged: %s user=%d", packageName,
2861                    packageUserId));
2862        }
2863
2864        // Activities may be disabled or enabled.  Just rescan the package.
2865        synchronized (mLock) {
2866            final ShortcutUser user = getUserShortcutsLocked(packageUserId);
2867
2868            user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
2869        }
2870
2871        verifyStates();
2872    }
2873
2874    // === PackageManager interaction ===
2875
2876    /**
2877     * Returns {@link PackageInfo} unless it's uninstalled or disabled.
2878     */
2879    @Nullable
2880    final PackageInfo getPackageInfoWithSignatures(String packageName, @UserIdInt int userId) {
2881        return getPackageInfo(packageName, userId, true);
2882    }
2883
2884    /**
2885     * Returns {@link PackageInfo} unless it's uninstalled or disabled.
2886     */
2887    @Nullable
2888    final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId) {
2889        return getPackageInfo(packageName, userId, false);
2890    }
2891
2892    int injectGetPackageUid(@NonNull String packageName, @UserIdInt int userId) {
2893        final long token = injectClearCallingIdentity();
2894        try {
2895            return mIPackageManager.getPackageUid(packageName, PACKAGE_MATCH_FLAGS, userId);
2896        } catch (RemoteException e) {
2897            // Shouldn't happen.
2898            Slog.wtf(TAG, "RemoteException", e);
2899            return -1;
2900        } finally {
2901            injectRestoreCallingIdentity(token);
2902        }
2903    }
2904
2905    /**
2906     * Returns {@link PackageInfo} unless it's uninstalled or disabled.
2907     */
2908    @Nullable
2909    @VisibleForTesting
2910    final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId,
2911            boolean getSignatures) {
2912        return isInstalledOrNull(injectPackageInfoWithUninstalled(
2913                packageName, userId, getSignatures));
2914    }
2915
2916    /**
2917     * Do not use directly; this returns uninstalled packages too.
2918     */
2919    @Nullable
2920    @VisibleForTesting
2921    PackageInfo injectPackageInfoWithUninstalled(String packageName, @UserIdInt int userId,
2922            boolean getSignatures) {
2923        final long start = injectElapsedRealtime();
2924        final long token = injectClearCallingIdentity();
2925        try {
2926            return mIPackageManager.getPackageInfo(
2927                    packageName, PACKAGE_MATCH_FLAGS
2928                            | (getSignatures ? PackageManager.GET_SIGNATURES : 0), userId);
2929        } catch (RemoteException e) {
2930            // Shouldn't happen.
2931            Slog.wtf(TAG, "RemoteException", e);
2932            return null;
2933        } finally {
2934            injectRestoreCallingIdentity(token);
2935
2936            logDurationStat(
2937                    (getSignatures ? Stats.GET_PACKAGE_INFO_WITH_SIG : Stats.GET_PACKAGE_INFO),
2938                    start);
2939        }
2940    }
2941
2942    /**
2943     * Returns {@link ApplicationInfo} unless it's uninstalled or disabled.
2944     */
2945    @Nullable
2946    @VisibleForTesting
2947    final ApplicationInfo getApplicationInfo(String packageName, @UserIdInt int userId) {
2948        return isInstalledOrNull(injectApplicationInfoWithUninstalled(packageName, userId));
2949    }
2950
2951    /**
2952     * Do not use directly; this returns uninstalled packages too.
2953     */
2954    @Nullable
2955    @VisibleForTesting
2956    ApplicationInfo injectApplicationInfoWithUninstalled(
2957            String packageName, @UserIdInt int userId) {
2958        final long start = injectElapsedRealtime();
2959        final long token = injectClearCallingIdentity();
2960        try {
2961            return mIPackageManager.getApplicationInfo(packageName, PACKAGE_MATCH_FLAGS, userId);
2962        } catch (RemoteException e) {
2963            // Shouldn't happen.
2964            Slog.wtf(TAG, "RemoteException", e);
2965            return null;
2966        } finally {
2967            injectRestoreCallingIdentity(token);
2968
2969            logDurationStat(Stats.GET_APPLICATION_INFO, start);
2970        }
2971    }
2972
2973    /**
2974     * Returns {@link ActivityInfo} with its metadata unless it's uninstalled or disabled.
2975     */
2976    @Nullable
2977    final ActivityInfo getActivityInfoWithMetadata(ComponentName activity, @UserIdInt int userId) {
2978        return isInstalledOrNull(injectGetActivityInfoWithMetadataWithUninstalled(
2979                activity, userId));
2980    }
2981
2982    /**
2983     * Do not use directly; this returns uninstalled packages too.
2984     */
2985    @Nullable
2986    @VisibleForTesting
2987    ActivityInfo injectGetActivityInfoWithMetadataWithUninstalled(
2988            ComponentName activity, @UserIdInt int userId) {
2989        final long start = injectElapsedRealtime();
2990        final long token = injectClearCallingIdentity();
2991        try {
2992            return mIPackageManager.getActivityInfo(activity,
2993                    (PACKAGE_MATCH_FLAGS | PackageManager.GET_META_DATA), userId);
2994        } catch (RemoteException e) {
2995            // Shouldn't happen.
2996            Slog.wtf(TAG, "RemoteException", e);
2997            return null;
2998        } finally {
2999            injectRestoreCallingIdentity(token);
3000
3001            logDurationStat(Stats.GET_ACTIVITY_WITH_METADATA, start);
3002        }
3003    }
3004
3005    /**
3006     * Return all installed and enabled packages.
3007     */
3008    @NonNull
3009    @VisibleForTesting
3010    final List<PackageInfo> getInstalledPackages(@UserIdInt int userId) {
3011        final long start = injectElapsedRealtime();
3012        final long token = injectClearCallingIdentity();
3013        try {
3014            final List<PackageInfo> all = injectGetPackagesWithUninstalled(userId);
3015
3016            all.removeIf(PACKAGE_NOT_INSTALLED);
3017
3018            return all;
3019        } catch (RemoteException e) {
3020            // Shouldn't happen.
3021            Slog.wtf(TAG, "RemoteException", e);
3022            return null;
3023        } finally {
3024            injectRestoreCallingIdentity(token);
3025
3026            logDurationStat(Stats.GET_INSTALLED_PACKAGES, start);
3027        }
3028    }
3029
3030    /**
3031     * Do not use directly; this returns uninstalled packages too.
3032     */
3033    @NonNull
3034    @VisibleForTesting
3035    List<PackageInfo> injectGetPackagesWithUninstalled(@UserIdInt int userId)
3036            throws RemoteException {
3037        final ParceledListSlice<PackageInfo> parceledList =
3038                mIPackageManager.getInstalledPackages(PACKAGE_MATCH_FLAGS, userId);
3039        if (parceledList == null) {
3040            return Collections.emptyList();
3041        }
3042        return parceledList.getList();
3043    }
3044
3045    private void forUpdatedPackages(@UserIdInt int userId, long lastScanTime, boolean afterOta,
3046            Consumer<ApplicationInfo> callback) {
3047        if (DEBUG) {
3048            Slog.d(TAG, "forUpdatedPackages for user " + userId + ", lastScanTime=" + lastScanTime
3049                    + " afterOta=" + afterOta);
3050        }
3051        final List<PackageInfo> list = getInstalledPackages(userId);
3052        for (int i = list.size() - 1; i >= 0; i--) {
3053            final PackageInfo pi = list.get(i);
3054
3055            // If the package has been updated since the last scan time, then scan it.
3056            // Also if it's right after an OTA, always re-scan all apps anyway, since the
3057            // shortcut parser might have changed.
3058            if (afterOta || (pi.lastUpdateTime >= lastScanTime)) {
3059                if (DEBUG) {
3060                    Slog.d(TAG, "Found updated package " + pi.packageName
3061                            + " updateTime=" + pi.lastUpdateTime);
3062                }
3063                callback.accept(pi.applicationInfo);
3064            }
3065        }
3066    }
3067
3068    private boolean isApplicationFlagSet(@NonNull String packageName, int userId, int flags) {
3069        final ApplicationInfo ai = injectApplicationInfoWithUninstalled(packageName, userId);
3070        return (ai != null) && ((ai.flags & flags) == flags);
3071    }
3072
3073    private static boolean isInstalled(@Nullable ApplicationInfo ai) {
3074        return (ai != null) && (ai.flags & ApplicationInfo.FLAG_INSTALLED) != 0;
3075    }
3076
3077    private static boolean isEphemeralApp(@Nullable ApplicationInfo ai) {
3078        return (ai != null) && ai.isEphemeralApp();
3079    }
3080
3081    private static boolean isInstalled(@Nullable PackageInfo pi) {
3082        return (pi != null) && isInstalled(pi.applicationInfo);
3083    }
3084
3085    private static boolean isInstalled(@Nullable ActivityInfo ai) {
3086        return (ai != null) && isInstalled(ai.applicationInfo);
3087    }
3088
3089    private static ApplicationInfo isInstalledOrNull(ApplicationInfo ai) {
3090        return isInstalled(ai) ? ai : null;
3091    }
3092
3093    private static PackageInfo isInstalledOrNull(PackageInfo pi) {
3094        return isInstalled(pi) ? pi : null;
3095    }
3096
3097    private static ActivityInfo isInstalledOrNull(ActivityInfo ai) {
3098        return isInstalled(ai) ? ai : null;
3099    }
3100
3101    boolean isPackageInstalled(String packageName, int userId) {
3102        return getApplicationInfo(packageName, userId) != null;
3103    }
3104
3105    boolean isEphemeralApp(String packageName, int userId) {
3106        return isEphemeralApp(getApplicationInfo(packageName, userId));
3107    }
3108
3109    @Nullable
3110    XmlResourceParser injectXmlMetaData(ActivityInfo activityInfo, String key) {
3111        return activityInfo.loadXmlMetaData(mContext.getPackageManager(), key);
3112    }
3113
3114    @Nullable
3115    Resources injectGetResourcesForApplicationAsUser(String packageName, int userId) {
3116        final long start = injectElapsedRealtime();
3117        final long token = injectClearCallingIdentity();
3118        try {
3119            return mContext.getPackageManager().getResourcesForApplicationAsUser(
3120                    packageName, userId);
3121        } catch (NameNotFoundException e) {
3122            Slog.e(TAG, "Resources for package " + packageName + " not found");
3123            return null;
3124        } finally {
3125            injectRestoreCallingIdentity(token);
3126
3127            logDurationStat(Stats.GET_APPLICATION_RESOURCES, start);
3128        }
3129    }
3130
3131    private Intent getMainActivityIntent() {
3132        final Intent intent = new Intent(Intent.ACTION_MAIN);
3133        intent.addCategory(LAUNCHER_INTENT_CATEGORY);
3134        return intent;
3135    }
3136
3137    /**
3138     * Same as queryIntentActivitiesAsUser, except it makes sure the package is installed,
3139     * and only returns exported activities.
3140     */
3141    @NonNull
3142    @VisibleForTesting
3143    List<ResolveInfo> queryActivities(@NonNull Intent baseIntent,
3144            @NonNull String packageName, @Nullable ComponentName activity, int userId) {
3145
3146        baseIntent.setPackage(Preconditions.checkNotNull(packageName));
3147        if (activity != null) {
3148            baseIntent.setComponent(activity);
3149        }
3150        return queryActivities(baseIntent, userId, /* exportedOnly =*/ true);
3151    }
3152
3153    @NonNull
3154    List<ResolveInfo> queryActivities(@NonNull Intent intent, int userId,
3155            boolean exportedOnly) {
3156        final List<ResolveInfo> resolved;
3157        final long token = injectClearCallingIdentity();
3158        try {
3159            resolved =
3160                    mContext.getPackageManager().queryIntentActivitiesAsUser(
3161                            intent, PACKAGE_MATCH_FLAGS, userId);
3162        } finally {
3163            injectRestoreCallingIdentity(token);
3164        }
3165        if (resolved == null || resolved.size() == 0) {
3166            return EMPTY_RESOLVE_INFO;
3167        }
3168        // Make sure the package is installed.
3169        if (!isInstalled(resolved.get(0).activityInfo)) {
3170            return EMPTY_RESOLVE_INFO;
3171        }
3172        if (exportedOnly) {
3173            resolved.removeIf(ACTIVITY_NOT_EXPORTED);
3174        }
3175        return resolved;
3176    }
3177
3178    /**
3179     * Return the main activity that is enabled and exported.  If multiple activities are found,
3180     * return the first one.
3181     */
3182    @Nullable
3183    ComponentName injectGetDefaultMainActivity(@NonNull String packageName, int userId) {
3184        final long start = injectElapsedRealtime();
3185        try {
3186            final List<ResolveInfo> resolved =
3187                    queryActivities(getMainActivityIntent(), packageName, null, userId);
3188            return resolved.size() == 0 ? null : resolved.get(0).activityInfo.getComponentName();
3189        } finally {
3190            logDurationStat(Stats.GET_LAUNCHER_ACTIVITY, start);
3191        }
3192    }
3193
3194    /**
3195     * Return whether an activity is enabled, exported and main.
3196     */
3197    boolean injectIsMainActivity(@NonNull ComponentName activity, int userId) {
3198        final long start = injectElapsedRealtime();
3199        try {
3200            if (DUMMY_MAIN_ACTIVITY.equals(activity.getClassName())) {
3201                return true;
3202            }
3203            final List<ResolveInfo> resolved = queryActivities(
3204                    getMainActivityIntent(), activity.getPackageName(), activity, userId);
3205            return resolved.size() > 0;
3206        } finally {
3207            logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start);
3208        }
3209    }
3210
3211    /**
3212     * Create a dummy "main activity" component name which is used to create a dynamic shortcut
3213     * with no main activity temporarily.
3214     */
3215    @NonNull
3216    ComponentName getDummyMainActivity(@NonNull String packageName) {
3217        return new ComponentName(packageName, DUMMY_MAIN_ACTIVITY);
3218    }
3219
3220    boolean isDummyMainActivity(@Nullable ComponentName name) {
3221        return name != null && DUMMY_MAIN_ACTIVITY.equals(name.getClassName());
3222    }
3223
3224    /**
3225     * Return all the enabled, exported and main activities from a package.
3226     */
3227    @NonNull
3228    List<ResolveInfo> injectGetMainActivities(@NonNull String packageName, int userId) {
3229        final long start = injectElapsedRealtime();
3230        try {
3231            return queryActivities(getMainActivityIntent(), packageName, null, userId);
3232        } finally {
3233            logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start);
3234        }
3235    }
3236
3237    /**
3238     * Return whether an activity is enabled and exported.
3239     */
3240    @VisibleForTesting
3241    boolean injectIsActivityEnabledAndExported(
3242            @NonNull ComponentName activity, @UserIdInt int userId) {
3243        final long start = injectElapsedRealtime();
3244        try {
3245            return queryActivities(new Intent(), activity.getPackageName(), activity, userId)
3246                    .size() > 0;
3247        } finally {
3248            logDurationStat(Stats.IS_ACTIVITY_ENABLED, start);
3249        }
3250    }
3251
3252    /**
3253     * Get the {@link LauncherApps#ACTION_CONFIRM_PIN_ITEM} activity in a given package.
3254     */
3255    @Nullable
3256    ComponentName injectGetPinConfirmationActivity(@NonNull String launcherPackageName,
3257            int launcherUserId) {
3258        Preconditions.checkNotNull(launcherPackageName);
3259
3260        final Intent confirmIntent = new Intent(LauncherApps.ACTION_CONFIRM_PIN_ITEM);
3261        confirmIntent.setPackage(launcherPackageName);
3262
3263        final List<ResolveInfo> candidates = queryActivities(
3264                confirmIntent, launcherUserId, /* exportedOnly =*/ false);
3265        for (ResolveInfo ri : candidates) {
3266            return ri.activityInfo.getComponentName();
3267        }
3268        return null;
3269    }
3270
3271    boolean injectIsSafeModeEnabled() {
3272        final long token = injectClearCallingIdentity();
3273        try {
3274            return IWindowManager.Stub
3275                    .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE))
3276                    .isSafeModeEnabled();
3277        } catch (RemoteException e) {
3278            return false; // Shouldn't happen though.
3279        } finally {
3280            injectRestoreCallingIdentity(token);
3281        }
3282    }
3283
3284    /**
3285     * If {@code userId} is of a managed profile, return the parent user ID.  Otherwise return
3286     * itself.
3287     */
3288    int getParentOrSelfUserId(int userId) {
3289        final long token = injectClearCallingIdentity();
3290        try {
3291            final UserInfo parent = mUserManager.getProfileParent(userId);
3292            return (parent != null) ? parent.id : userId;
3293        } finally {
3294            injectRestoreCallingIdentity(token);
3295        }
3296    }
3297
3298    void injectSendIntentSender(IntentSender intentSender, Intent extras) {
3299        if (intentSender == null) {
3300            return;
3301        }
3302        try {
3303            intentSender.sendIntent(mContext, /* code= */ 0, extras,
3304                    /* onFinished=*/ null, /* handler= */ null);
3305        } catch (SendIntentException e) {
3306            Slog.w(TAG, "sendIntent failed().", e);
3307        }
3308    }
3309
3310    // === Backup & restore ===
3311
3312    boolean shouldBackupApp(String packageName, int userId) {
3313        return isApplicationFlagSet(packageName, userId, ApplicationInfo.FLAG_ALLOW_BACKUP);
3314    }
3315
3316    boolean shouldBackupApp(PackageInfo pi) {
3317        return (pi.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0;
3318    }
3319
3320    @Override
3321    public byte[] getBackupPayload(@UserIdInt int userId) {
3322        enforceSystem();
3323        if (DEBUG) {
3324            Slog.d(TAG, "Backing up user " + userId);
3325        }
3326        synchronized (mLock) {
3327            if (!isUserUnlockedL(userId)) {
3328                wtf("Can't backup: user " + userId + " is locked or not running");
3329                return null;
3330            }
3331
3332            final ShortcutUser user = getUserShortcutsLocked(userId);
3333            if (user == null) {
3334                wtf("Can't backup: user not found: id=" + userId);
3335                return null;
3336            }
3337
3338            // Update the signatures for all packages.
3339            user.forAllPackageItems(spi -> spi.refreshPackageSignatureAndSave());
3340
3341            // Set the version code for the launchers.
3342            // We shouldn't do this for publisher packages, because we don't want to update the
3343            // version code without rescanning the manifest.
3344            user.forAllLaunchers(launcher -> launcher.ensureVersionInfo());
3345
3346            // Save to the filesystem.
3347            scheduleSaveUser(userId);
3348            saveDirtyInfo();
3349
3350            // Then create the backup payload.
3351            final ByteArrayOutputStream os = new ByteArrayOutputStream(32 * 1024);
3352            try {
3353                saveUserInternalLocked(userId, os, /* forBackup */ true);
3354            } catch (XmlPullParserException | IOException e) {
3355                // Shouldn't happen.
3356                Slog.w(TAG, "Backup failed.", e);
3357                return null;
3358            }
3359            return os.toByteArray();
3360        }
3361    }
3362
3363    @Override
3364    public void applyRestore(byte[] payload, @UserIdInt int userId) {
3365        enforceSystem();
3366        if (DEBUG) {
3367            Slog.d(TAG, "Restoring user " + userId);
3368        }
3369        synchronized (mLock) {
3370            if (!isUserUnlockedL(userId)) {
3371                wtf("Can't restore: user " + userId + " is locked or not running");
3372                return;
3373            }
3374            // Actually do restore.
3375            final ShortcutUser restored;
3376            final ByteArrayInputStream is = new ByteArrayInputStream(payload);
3377            try {
3378                restored = loadUserInternal(userId, is, /* fromBackup */ true);
3379            } catch (XmlPullParserException | IOException | InvalidFileFormatException e) {
3380                Slog.w(TAG, "Restoration failed.", e);
3381                return;
3382            }
3383            getUserShortcutsLocked(userId).mergeRestoredFile(restored);
3384
3385            // Rescan all packages to re-publish manifest shortcuts and do other checks.
3386            rescanUpdatedPackagesLocked(userId,
3387                    0 // lastScanTime = 0; rescan all packages.
3388                    );
3389
3390            saveUserLocked(userId);
3391        }
3392    }
3393
3394    // === Dump ===
3395
3396    @Override
3397    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
3398        enforceCallingOrSelfPermission(android.Manifest.permission.DUMP,
3399                "can't dump by this caller");
3400        boolean checkin = false;
3401        boolean clear = false;
3402        if (args != null) {
3403            for (String arg : args) {
3404                if ("-c".equals(arg)) {
3405                    checkin = true;
3406                } else if ("--checkin".equals(arg)) {
3407                    checkin = true;
3408                    clear = true;
3409                }
3410            }
3411        }
3412
3413        if (checkin) {
3414            dumpCheckin(pw, clear);
3415        } else {
3416            dumpInner(pw);
3417        }
3418    }
3419
3420    private void dumpInner(PrintWriter pw) {
3421        synchronized (mLock) {
3422            final long now = injectCurrentTimeMillis();
3423            pw.print("Now: [");
3424            pw.print(now);
3425            pw.print("] ");
3426            pw.print(formatTime(now));
3427
3428            pw.print("  Raw last reset: [");
3429            pw.print(mRawLastResetTime);
3430            pw.print("] ");
3431            pw.print(formatTime(mRawLastResetTime));
3432
3433            final long last = getLastResetTimeLocked();
3434            pw.print("  Last reset: [");
3435            pw.print(last);
3436            pw.print("] ");
3437            pw.print(formatTime(last));
3438
3439            final long next = getNextResetTimeLocked();
3440            pw.print("  Next reset: [");
3441            pw.print(next);
3442            pw.print("] ");
3443            pw.print(formatTime(next));
3444
3445            pw.print("  Config:");
3446            pw.print("    Max icon dim: ");
3447            pw.println(mMaxIconDimension);
3448            pw.print("    Icon format: ");
3449            pw.println(mIconPersistFormat);
3450            pw.print("    Icon quality: ");
3451            pw.println(mIconPersistQuality);
3452            pw.print("    saveDelayMillis: ");
3453            pw.println(mSaveDelayMillis);
3454            pw.print("    resetInterval: ");
3455            pw.println(mResetInterval);
3456            pw.print("    maxUpdatesPerInterval: ");
3457            pw.println(mMaxUpdatesPerInterval);
3458            pw.print("    maxShortcutsPerActivity: ");
3459            pw.println(mMaxShortcuts);
3460            pw.println();
3461
3462            pw.println("  Stats:");
3463            synchronized (mStatLock) {
3464                for (int i = 0; i < Stats.COUNT; i++) {
3465                    dumpStatLS(pw, "    ", i);
3466                }
3467            }
3468
3469            pw.println();
3470            pw.print("  #Failures: ");
3471            pw.println(mWtfCount);
3472
3473            if (mLastWtfStacktrace != null) {
3474                pw.print("  Last failure stack trace: ");
3475                pw.println(Log.getStackTraceString(mLastWtfStacktrace));
3476            }
3477
3478            for (int i = 0; i < mUsers.size(); i++) {
3479                pw.println();
3480                mUsers.valueAt(i).dump(pw, "  ");
3481            }
3482
3483            pw.println();
3484            pw.println("  UID state:");
3485
3486            for (int i = 0; i < mUidState.size(); i++) {
3487                final int uid = mUidState.keyAt(i);
3488                final int state = mUidState.valueAt(i);
3489                pw.print("    UID=");
3490                pw.print(uid);
3491                pw.print(" state=");
3492                pw.print(state);
3493                if (isProcessStateForeground(state)) {
3494                    pw.print("  [FG]");
3495                }
3496                pw.print("  last FG=");
3497                pw.print(mUidLastForegroundElapsedTime.get(uid));
3498                pw.println();
3499            }
3500        }
3501    }
3502
3503    static String formatTime(long time) {
3504        Time tobj = new Time();
3505        tobj.set(time);
3506        return tobj.format("%Y-%m-%d %H:%M:%S");
3507    }
3508
3509    private void dumpStatLS(PrintWriter pw, String prefix, int statId) {
3510        pw.print(prefix);
3511        final int count = mCountStats[statId];
3512        final long dur = mDurationStats[statId];
3513        pw.println(String.format("%s: count=%d, total=%dms, avg=%.1fms",
3514                STAT_LABELS[statId], count, dur,
3515                (count == 0 ? 0 : ((double) dur) / count)));
3516    }
3517
3518    /**
3519     * Dumpsys for checkin.
3520     *
3521     * @param clear if true, clear the history information.  Some other system services have this
3522     * behavior but shortcut service doesn't for now.
3523     */
3524    private  void dumpCheckin(PrintWriter pw, boolean clear) {
3525        synchronized (mLock) {
3526            try {
3527                final JSONArray users = new JSONArray();
3528
3529                for (int i = 0; i < mUsers.size(); i++) {
3530                    users.put(mUsers.valueAt(i).dumpCheckin(clear));
3531                }
3532
3533                final JSONObject result = new JSONObject();
3534
3535                result.put(KEY_SHORTCUT, users);
3536                result.put(KEY_LOW_RAM, injectIsLowRamDevice());
3537                result.put(KEY_ICON_SIZE, mMaxIconDimension);
3538
3539                pw.println(result.toString(1));
3540            } catch (JSONException e) {
3541                Slog.e(TAG, "Unable to write in json", e);
3542            }
3543        }
3544    }
3545
3546    // === Shell support ===
3547
3548    @Override
3549    public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
3550            String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
3551
3552        enforceShell();
3553
3554        final long token = injectClearCallingIdentity();
3555        try {
3556            final int status = (new MyShellCommand()).exec(this, in, out, err, args, callback,
3557                    resultReceiver);
3558            resultReceiver.send(status, null);
3559        } finally {
3560            injectRestoreCallingIdentity(token);
3561        }
3562    }
3563
3564    static class CommandException extends Exception {
3565        public CommandException(String message) {
3566            super(message);
3567        }
3568    }
3569
3570    /**
3571     * Handle "adb shell cmd".
3572     */
3573    private class MyShellCommand extends ShellCommand {
3574
3575        private int mUserId = UserHandle.USER_SYSTEM;
3576
3577        private void parseOptionsLocked(boolean takeUser)
3578                throws CommandException {
3579            String opt;
3580            while ((opt = getNextOption()) != null) {
3581                switch (opt) {
3582                    case "--user":
3583                        if (takeUser) {
3584                            mUserId = UserHandle.parseUserArg(getNextArgRequired());
3585                            if (!isUserUnlockedL(mUserId)) {
3586                                throw new CommandException(
3587                                        "User " + mUserId + " is not running or locked");
3588                            }
3589                            break;
3590                        }
3591                        // fallthrough
3592                    default:
3593                        throw new CommandException("Unknown option: " + opt);
3594                }
3595            }
3596        }
3597
3598        @Override
3599        public int onCommand(String cmd) {
3600            if (cmd == null) {
3601                return handleDefaultCommands(cmd);
3602            }
3603            final PrintWriter pw = getOutPrintWriter();
3604            try {
3605                switch (cmd) {
3606                    case "reset-throttling":
3607                        handleResetThrottling();
3608                        break;
3609                    case "reset-all-throttling":
3610                        handleResetAllThrottling();
3611                        break;
3612                    case "override-config":
3613                        handleOverrideConfig();
3614                        break;
3615                    case "reset-config":
3616                        handleResetConfig();
3617                        break;
3618                    case "clear-default-launcher":
3619                        handleClearDefaultLauncher();
3620                        break;
3621                    case "get-default-launcher":
3622                        handleGetDefaultLauncher();
3623                        break;
3624                    case "unload-user":
3625                        handleUnloadUser();
3626                        break;
3627                    case "clear-shortcuts":
3628                        handleClearShortcuts();
3629                        break;
3630                    case "verify-states": // hidden command to verify various internal states.
3631                        handleVerifyStates();
3632                        break;
3633                    default:
3634                        return handleDefaultCommands(cmd);
3635                }
3636            } catch (CommandException e) {
3637                pw.println("Error: " + e.getMessage());
3638                return 1;
3639            }
3640            pw.println("Success");
3641            return 0;
3642        }
3643
3644        @Override
3645        public void onHelp() {
3646            final PrintWriter pw = getOutPrintWriter();
3647            pw.println("Usage: cmd shortcut COMMAND [options ...]");
3648            pw.println();
3649            pw.println("cmd shortcut reset-throttling [--user USER_ID]");
3650            pw.println("    Reset throttling for all packages and users");
3651            pw.println();
3652            pw.println("cmd shortcut reset-all-throttling");
3653            pw.println("    Reset the throttling state for all users");
3654            pw.println();
3655            pw.println("cmd shortcut override-config CONFIG");
3656            pw.println("    Override the configuration for testing (will last until reboot)");
3657            pw.println();
3658            pw.println("cmd shortcut reset-config");
3659            pw.println("    Reset the configuration set with \"update-config\"");
3660            pw.println();
3661            pw.println("cmd shortcut clear-default-launcher [--user USER_ID]");
3662            pw.println("    Clear the cached default launcher");
3663            pw.println();
3664            pw.println("cmd shortcut get-default-launcher [--user USER_ID]");
3665            pw.println("    Show the default launcher");
3666            pw.println();
3667            pw.println("cmd shortcut unload-user [--user USER_ID]");
3668            pw.println("    Unload a user from the memory");
3669            pw.println("    (This should not affect any observable behavior)");
3670            pw.println();
3671            pw.println("cmd shortcut clear-shortcuts [--user USER_ID] PACKAGE");
3672            pw.println("    Remove all shortcuts from a package, including pinned shortcuts");
3673            pw.println();
3674        }
3675
3676        private void handleResetThrottling() throws CommandException {
3677            synchronized (mLock) {
3678                parseOptionsLocked(/* takeUser =*/ true);
3679
3680                Slog.i(TAG, "cmd: handleResetThrottling: user=" + mUserId);
3681
3682                resetThrottlingInner(mUserId);
3683            }
3684        }
3685
3686        private void handleResetAllThrottling() {
3687            Slog.i(TAG, "cmd: handleResetAllThrottling");
3688
3689            resetAllThrottlingInner();
3690        }
3691
3692        private void handleOverrideConfig() throws CommandException {
3693            final String config = getNextArgRequired();
3694
3695            Slog.i(TAG, "cmd: handleOverrideConfig: " + config);
3696
3697            synchronized (mLock) {
3698                if (!updateConfigurationLocked(config)) {
3699                    throw new CommandException("override-config failed.  See logcat for details.");
3700                }
3701            }
3702        }
3703
3704        private void handleResetConfig() {
3705            Slog.i(TAG, "cmd: handleResetConfig");
3706
3707            synchronized (mLock) {
3708                loadConfigurationLocked();
3709            }
3710        }
3711
3712        private void clearLauncher() {
3713            synchronized (mLock) {
3714                getUserShortcutsLocked(mUserId).forceClearLauncher();
3715            }
3716        }
3717
3718        private void showLauncher() {
3719            synchronized (mLock) {
3720                // This ensures to set the cached launcher.  Package name doesn't matter.
3721                hasShortcutHostPermissionInner("-", mUserId);
3722
3723                getOutPrintWriter().println("Launcher: "
3724                        + getUserShortcutsLocked(mUserId).getLastKnownLauncher());
3725            }
3726        }
3727
3728        private void handleClearDefaultLauncher() throws CommandException {
3729            synchronized (mLock) {
3730                parseOptionsLocked(/* takeUser =*/ true);
3731
3732                clearLauncher();
3733            }
3734        }
3735
3736        private void handleGetDefaultLauncher() throws CommandException {
3737            synchronized (mLock) {
3738                parseOptionsLocked(/* takeUser =*/ true);
3739
3740                clearLauncher();
3741                showLauncher();
3742            }
3743        }
3744
3745        private void handleUnloadUser() throws CommandException {
3746            synchronized (mLock) {
3747                parseOptionsLocked(/* takeUser =*/ true);
3748
3749                Slog.i(TAG, "cmd: handleUnloadUser: user=" + mUserId);
3750
3751                ShortcutService.this.handleCleanupUser(mUserId);
3752            }
3753        }
3754
3755        private void handleClearShortcuts() throws CommandException {
3756            synchronized (mLock) {
3757                parseOptionsLocked(/* takeUser =*/ true);
3758                final String packageName = getNextArgRequired();
3759
3760                Slog.i(TAG, "cmd: handleClearShortcuts: user" + mUserId + ", " + packageName);
3761
3762                ShortcutService.this.cleanUpPackageForAllLoadedUsers(packageName, mUserId,
3763                        /* appStillExists = */ true);
3764            }
3765        }
3766
3767        private void handleVerifyStates() throws CommandException {
3768            try {
3769                verifyStatesForce(); // This will throw when there's an issue.
3770            } catch (Throwable th) {
3771                throw new CommandException(th.getMessage() + "\n" + Log.getStackTraceString(th));
3772            }
3773        }
3774    }
3775
3776    // === Unit test support ===
3777
3778    // Injection point.
3779    @VisibleForTesting
3780    long injectCurrentTimeMillis() {
3781        return System.currentTimeMillis();
3782    }
3783
3784    @VisibleForTesting
3785    long injectElapsedRealtime() {
3786        return SystemClock.elapsedRealtime();
3787    }
3788
3789    // Injection point.
3790    @VisibleForTesting
3791    int injectBinderCallingUid() {
3792        return getCallingUid();
3793    }
3794
3795    private int getCallingUserId() {
3796        return UserHandle.getUserId(injectBinderCallingUid());
3797    }
3798
3799    // Injection point.
3800    @VisibleForTesting
3801    long injectClearCallingIdentity() {
3802        return Binder.clearCallingIdentity();
3803    }
3804
3805    // Injection point.
3806    @VisibleForTesting
3807    void injectRestoreCallingIdentity(long token) {
3808        Binder.restoreCallingIdentity(token);
3809    }
3810
3811    // Injection point.
3812    @VisibleForTesting
3813    String injectBuildFingerprint() {
3814        return Build.FINGERPRINT;
3815    }
3816
3817    final void wtf(String message) {
3818        wtf(message, /* exception= */ null);
3819    }
3820
3821    // Injection point.
3822    void wtf(String message, Throwable e) {
3823        if (e == null) {
3824            e = new RuntimeException("Stacktrace");
3825        }
3826        synchronized (mLock) {
3827            mWtfCount++;
3828            mLastWtfStacktrace = new Exception("Last failure was logged here:");
3829        }
3830        Slog.wtf(TAG, message, e);
3831    }
3832
3833    @VisibleForTesting
3834    File injectSystemDataPath() {
3835        return Environment.getDataSystemDirectory();
3836    }
3837
3838    @VisibleForTesting
3839    File injectUserDataPath(@UserIdInt int userId) {
3840        return new File(Environment.getDataSystemCeDirectory(userId), DIRECTORY_PER_USER);
3841    }
3842
3843    @VisibleForTesting
3844    boolean injectIsLowRamDevice() {
3845        return ActivityManager.isLowRamDeviceStatic();
3846    }
3847
3848    @VisibleForTesting
3849    void injectRegisterUidObserver(IUidObserver observer, int which) {
3850        try {
3851            ActivityManager.getService().registerUidObserver(observer, which,
3852                    ActivityManager.PROCESS_STATE_UNKNOWN, null);
3853        } catch (RemoteException shouldntHappen) {
3854        }
3855    }
3856
3857    File getUserBitmapFilePath(@UserIdInt int userId) {
3858        return new File(injectUserDataPath(userId), DIRECTORY_BITMAPS);
3859    }
3860
3861    @VisibleForTesting
3862    SparseArray<ShortcutUser> getShortcutsForTest() {
3863        return mUsers;
3864    }
3865
3866    @VisibleForTesting
3867    int getMaxShortcutsForTest() {
3868        return mMaxShortcuts;
3869    }
3870
3871    @VisibleForTesting
3872    int getMaxUpdatesPerIntervalForTest() {
3873        return mMaxUpdatesPerInterval;
3874    }
3875
3876    @VisibleForTesting
3877    long getResetIntervalForTest() {
3878        return mResetInterval;
3879    }
3880
3881    @VisibleForTesting
3882    int getMaxIconDimensionForTest() {
3883        return mMaxIconDimension;
3884    }
3885
3886    @VisibleForTesting
3887    CompressFormat getIconPersistFormatForTest() {
3888        return mIconPersistFormat;
3889    }
3890
3891    @VisibleForTesting
3892    int getIconPersistQualityForTest() {
3893        return mIconPersistQuality;
3894    }
3895
3896    @VisibleForTesting
3897    ShortcutPackage getPackageShortcutForTest(String packageName, int userId) {
3898        synchronized (mLock) {
3899            final ShortcutUser user = mUsers.get(userId);
3900            if (user == null) return null;
3901
3902            return user.getAllPackagesForTest().get(packageName);
3903        }
3904    }
3905
3906    @VisibleForTesting
3907    ShortcutInfo getPackageShortcutForTest(String packageName, String shortcutId, int userId) {
3908        synchronized (mLock) {
3909            final ShortcutPackage pkg = getPackageShortcutForTest(packageName, userId);
3910            if (pkg == null) return null;
3911
3912            return pkg.findShortcutById(shortcutId);
3913        }
3914    }
3915
3916    @VisibleForTesting
3917    ShortcutLauncher getLauncherShortcutForTest(String packageName, int userId) {
3918        synchronized (mLock) {
3919            final ShortcutUser user = mUsers.get(userId);
3920            if (user == null) return null;
3921
3922            return user.getAllLaunchersForTest().get(PackageWithUser.of(userId, packageName));
3923        }
3924    }
3925
3926    @VisibleForTesting
3927    ShortcutRequestPinProcessor getShortcutRequestPinProcessorForTest() {
3928        return mShortcutRequestPinProcessor;
3929    }
3930
3931    /**
3932     * Control whether {@link #verifyStates} should be performed.  We always perform it during unit
3933     * tests.
3934     */
3935    @VisibleForTesting
3936    boolean injectShouldPerformVerification() {
3937        return DEBUG;
3938    }
3939
3940    /**
3941     * Check various internal states and throws if there's any inconsistency.
3942     * This is normally only enabled during unit tests.
3943     */
3944    final void verifyStates() {
3945        if (injectShouldPerformVerification()) {
3946            verifyStatesInner();
3947        }
3948    }
3949
3950    private final void verifyStatesForce() {
3951        verifyStatesInner();
3952    }
3953
3954    private void verifyStatesInner() {
3955        synchronized (mLock) {
3956            forEachLoadedUserLocked(u -> u.forAllPackageItems(ShortcutPackageItem::verifyStates));
3957        }
3958    }
3959}
3960