blob: f368666a06ba699d0573c495810e3470e208b86c [file] [log] [blame]
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001/*
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
Makoto Onuki7d0fa812018-02-21 11:24:43 -080018import android.Manifest.permission;
Makoto Onuki7001a612016-05-27 13:24:28 -070019import android.annotation.IntDef;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080020import android.annotation.NonNull;
21import android.annotation.Nullable;
22import android.annotation.UserIdInt;
Makoto Onuki55046222016-03-08 10:49:47 -080023import android.app.ActivityManager;
Makoto Onuki33525d22016-08-03 15:45:24 -070024import android.app.ActivityManagerInternal;
Makoto Onuki0acbb142016-03-22 17:02:57 -070025import android.app.AppGlobals;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -070026import android.app.IUidObserver;
Makoto Onukiac042502016-05-20 16:39:42 -070027import android.app.usage.UsageStatsManagerInternal;
Sunny Goyal87a563e2017-01-01 19:42:45 -080028import android.appwidget.AppWidgetProviderInfo;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070029import android.content.BroadcastReceiver;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080030import android.content.ComponentName;
31import android.content.Context;
32import android.content.Intent;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070033import android.content.IntentFilter;
Makoto Onuki2d895c32016-12-02 15:48:40 -080034import android.content.IntentSender;
35import android.content.IntentSender.SendIntentException;
Makoto Onuki22fcc682016-05-17 14:52:19 -070036import android.content.pm.ActivityInfo;
Makoto Onuki0acbb142016-03-22 17:02:57 -070037import android.content.pm.ApplicationInfo;
38import android.content.pm.IPackageManager;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080039import android.content.pm.IShortcutService;
40import android.content.pm.LauncherApps;
41import android.content.pm.LauncherApps.ShortcutQuery;
Makoto Onuki0acbb142016-03-22 17:02:57 -070042import android.content.pm.PackageInfo;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080043import android.content.pm.PackageManager;
Todd Kennedy0eb97382017-10-03 16:57:22 -070044import android.content.pm.PackageManager.NameNotFoundException;
Mehdi Alizadeh32774622018-11-05 17:32:01 -080045import android.content.pm.PackageManagerInternal;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080046import android.content.pm.ParceledListSlice;
Makoto Onuki2d5b4652016-03-11 16:09:54 -080047import android.content.pm.ResolveInfo;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080048import android.content.pm.ShortcutInfo;
Mehdi Alizadeh406e8b32018-12-11 18:21:49 -080049import android.content.pm.ShortcutManager;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080050import android.content.pm.ShortcutServiceInternal;
51import android.content.pm.ShortcutServiceInternal.ShortcutChangeListener;
Makoto Onuki157b1622016-06-02 16:13:10 -070052import android.content.res.Resources;
Makoto Onuki22fcc682016-05-17 14:52:19 -070053import android.content.res.XmlResourceParser;
Makoto Onuki55046222016-03-08 10:49:47 -080054import android.graphics.Bitmap;
55import android.graphics.Bitmap.CompressFormat;
Makoto Onuki55046222016-03-08 10:49:47 -080056import android.graphics.Canvas;
57import android.graphics.RectF;
Hyunyoung Song47037462017-05-08 16:51:43 -070058import android.graphics.drawable.AdaptiveIconDrawable;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080059import android.graphics.drawable.Icon;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070060import android.net.Uri;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080061import android.os.Binder;
Makoto Onuki33663282016-08-22 16:19:04 -070062import android.os.Build;
Sunny Goyal4ad6b572017-02-28 11:11:51 -080063import android.os.Bundle;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080064import android.os.Environment;
Makoto Onuki2e210c42016-03-30 08:30:36 -070065import android.os.FileUtils;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080066import android.os.Handler;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070067import android.os.LocaleList;
Makoto Onukiaa8b94a2016-03-17 13:14:05 -070068import android.os.Looper;
Makoto Onuki55046222016-03-08 10:49:47 -080069import android.os.ParcelFileDescriptor;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080070import android.os.PersistableBundle;
71import android.os.Process;
72import android.os.RemoteException;
73import android.os.ResultReceiver;
Makoto Onuki55046222016-03-08 10:49:47 -080074import android.os.SELinux;
Makoto Onukib08790c2016-06-23 14:05:46 -070075import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070076import android.os.ShellCallback;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080077import android.os.ShellCommand;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -070078import android.os.SystemClock;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080079import android.os.UserHandle;
Sunny Goyal145c8f82018-02-15 14:27:09 -080080import android.os.UserManagerInternal;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080081import android.text.TextUtils;
Neil Fuller9aa7b742019-06-17 11:40:35 +010082import android.text.format.TimeMigrationUtils;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080083import android.util.ArraySet;
84import android.util.AtomicFile;
Makoto Onuki4362a662016-03-08 18:59:09 -080085import android.util.KeyValueListParser;
Makoto Onukiac042502016-05-20 16:39:42 -070086import android.util.Log;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080087import android.util.Slog;
88import android.util.SparseArray;
Makoto Onuki02f338e2016-07-29 09:40:40 -070089import android.util.SparseBooleanArray;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -070090import android.util.SparseIntArray;
91import android.util.SparseLongArray;
Makoto Onuki55046222016-03-08 10:49:47 -080092import android.util.TypedValue;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080093import android.util.Xml;
Makoto Onukib08790c2016-06-23 14:05:46 -070094import android.view.IWindowManager;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080095
96import com.android.internal.annotations.GuardedBy;
97import com.android.internal.annotations.VisibleForTesting;
Mehdi Alizadeha20781c2019-04-25 14:52:02 -070098import com.android.internal.logging.MetricsLogger;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080099import com.android.internal.os.BackgroundThread;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600100import com.android.internal.util.DumpUtils;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800101import com.android.internal.util.FastXmlSerializer;
102import com.android.internal.util.Preconditions;
Makoto Onuki49392d32018-04-11 13:51:02 -0700103import com.android.internal.util.StatLogger;
Mehdi Alizadeh32774622018-11-05 17:32:01 -0800104import com.android.server.LocalServices;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800105import com.android.server.SystemService;
Makoto Onukid99c6f02016-03-28 11:02:54 -0700106import com.android.server.pm.ShortcutUser.PackageWithUser;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800107
108import libcore.io.IoUtils;
109
Makoto Onuki76269922016-07-15 14:58:54 -0700110import org.json.JSONArray;
111import org.json.JSONException;
112import org.json.JSONObject;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800113import org.xmlpull.v1.XmlPullParser;
114import org.xmlpull.v1.XmlPullParserException;
115import org.xmlpull.v1.XmlSerializer;
116
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700117import java.io.BufferedInputStream;
118import java.io.BufferedOutputStream;
119import java.io.ByteArrayInputStream;
120import java.io.ByteArrayOutputStream;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800121import java.io.File;
122import java.io.FileDescriptor;
123import java.io.FileInputStream;
124import java.io.FileNotFoundException;
125import java.io.FileOutputStream;
126import java.io.IOException;
Makoto Onuki55046222016-03-08 10:49:47 -0800127import java.io.InputStream;
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700128import java.io.OutputStream;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800129import java.io.PrintWriter;
Makoto Onuki7001a612016-05-27 13:24:28 -0700130import java.lang.annotation.Retention;
131import java.lang.annotation.RetentionPolicy;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800132import java.net.URISyntaxException;
133import java.nio.charset.StandardCharsets;
134import java.util.ArrayList;
Makoto Onuki22fcc682016-05-17 14:52:19 -0700135import java.util.Collections;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800136import java.util.List;
Makoto Onukia19fb232018-06-12 13:01:42 -0700137import java.util.Objects;
Makoto Onukic51b2872016-05-04 15:24:50 -0700138import java.util.concurrent.atomic.AtomicBoolean;
Makoto Onuki2e210c42016-03-30 08:30:36 -0700139import java.util.function.Consumer;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800140import java.util.function.Predicate;
Makoto Onuki20b82212017-10-04 15:03:50 -0700141import java.util.regex.Pattern;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800142
143/**
144 * TODO:
Makoto Onuki22fcc682016-05-17 14:52:19 -0700145 * - getIconMaxWidth()/getIconMaxHeight() should use xdpi and ydpi.
Makoto Onukib5a012f2016-06-21 11:13:53 -0700146 * -> But TypedValue.applyDimension() doesn't differentiate x and y..?
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800147 *
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700148 * - Detect when already registered instances are passed to APIs again, which might break
Makoto Onukib08790c2016-06-23 14:05:46 -0700149 * internal bitmap handling.
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800150 */
151public class ShortcutService extends IShortcutService.Stub {
Makoto Onuki55046222016-03-08 10:49:47 -0800152 static final String TAG = "ShortcutService";
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800153
Makoto Onuki7001a612016-05-27 13:24:28 -0700154 static final boolean DEBUG = false; // STOPSHIP if true
Makoto Onuki41066a62016-03-09 16:18:44 -0800155 static final boolean DEBUG_LOAD = false; // STOPSHIP if true
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700156 static final boolean DEBUG_PROCSTATE = false; // STOPSHIP if true
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800157
Makoto Onuki4362a662016-03-08 18:59:09 -0800158 @VisibleForTesting
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700159 static final long DEFAULT_RESET_INTERVAL_SEC = 24 * 60 * 60; // 1 day
Makoto Onuki4362a662016-03-08 18:59:09 -0800160
161 @VisibleForTesting
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700162 static final int DEFAULT_MAX_UPDATES_PER_INTERVAL = 10;
Makoto Onuki4362a662016-03-08 18:59:09 -0800163
164 @VisibleForTesting
Mehdi Alizadehbebfc0b32019-04-25 17:05:52 -0700165 static final int DEFAULT_MAX_SHORTCUTS_PER_APP = 10;
Makoto Onuki4362a662016-03-08 18:59:09 -0800166
167 @VisibleForTesting
168 static final int DEFAULT_MAX_ICON_DIMENSION_DP = 96;
169
170 @VisibleForTesting
171 static final int DEFAULT_MAX_ICON_DIMENSION_LOWRAM_DP = 48;
172
173 @VisibleForTesting
174 static final String DEFAULT_ICON_PERSIST_FORMAT = CompressFormat.PNG.name();
175
176 @VisibleForTesting
177 static final int DEFAULT_ICON_PERSIST_QUALITY = 100;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800178
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700179 @VisibleForTesting
180 static final int DEFAULT_SAVE_DELAY_MS = 3000;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800181
182 @VisibleForTesting
183 static final String FILENAME_BASE_STATE = "shortcut_service.xml";
184
185 @VisibleForTesting
186 static final String DIRECTORY_PER_USER = "shortcut_service";
187
188 @VisibleForTesting
Makoto Onuki50a320e2017-05-31 14:38:42 -0700189 static final String DIRECTORY_DUMP = "shortcut_dump";
190
191 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800192 static final String FILENAME_USER_PACKAGES = "shortcuts.xml";
193
Makoto Onuki55046222016-03-08 10:49:47 -0800194 static final String DIRECTORY_BITMAPS = "bitmaps";
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800195
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700196 private static final String TAG_ROOT = "root";
197 private static final String TAG_LAST_RESET_TIME = "last_reset_time";
Makoto Onuki55046222016-03-08 10:49:47 -0800198
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700199 private static final String ATTR_VALUE = "value";
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800200
Makoto Onukib08790c2016-06-23 14:05:46 -0700201 private static final String LAUNCHER_INTENT_CATEGORY = Intent.CATEGORY_LAUNCHER;
202
Makoto Onuki76269922016-07-15 14:58:54 -0700203 private static final String KEY_SHORTCUT = "shortcut";
204 private static final String KEY_LOW_RAM = "lowRam";
205 private static final String KEY_ICON_SIZE = "iconSize";
206
Makoto Onuki2d895c32016-12-02 15:48:40 -0800207 private static final String DUMMY_MAIN_ACTIVITY = "android.__dummy__";
208
Makoto Onuki4362a662016-03-08 18:59:09 -0800209 @VisibleForTesting
210 interface ConfigConstants {
211 /**
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700212 * Key name for the save delay, in milliseconds. (int)
213 */
214 String KEY_SAVE_DELAY_MILLIS = "save_delay_ms";
215
216 /**
Makoto Onuki4362a662016-03-08 18:59:09 -0800217 * Key name for the throttling reset interval, in seconds. (long)
218 */
219 String KEY_RESET_INTERVAL_SEC = "reset_interval_sec";
220
221 /**
222 * Key name for the max number of modifying API calls per app for every interval. (int)
223 */
Makoto Onukib6d35232016-04-04 15:57:17 -0700224 String KEY_MAX_UPDATES_PER_INTERVAL = "max_updates_per_interval";
Makoto Onuki4362a662016-03-08 18:59:09 -0800225
226 /**
227 * Key name for the max icon dimensions in DP, for non-low-memory devices.
228 */
229 String KEY_MAX_ICON_DIMENSION_DP = "max_icon_dimension_dp";
230
231 /**
232 * Key name for the max icon dimensions in DP, for low-memory devices.
233 */
234 String KEY_MAX_ICON_DIMENSION_DP_LOWRAM = "max_icon_dimension_dp_lowram";
235
236 /**
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700237 * Key name for the max dynamic shortcuts per activity. (int)
Makoto Onuki4362a662016-03-08 18:59:09 -0800238 */
239 String KEY_MAX_SHORTCUTS = "max_shortcuts";
240
241 /**
Makoto Onuki41066a62016-03-09 16:18:44 -0800242 * Key name for icon compression quality, 0-100.
Makoto Onuki4362a662016-03-08 18:59:09 -0800243 */
244 String KEY_ICON_QUALITY = "icon_quality";
245
246 /**
247 * Key name for icon compression format: "PNG", "JPEG" or "WEBP"
248 */
249 String KEY_ICON_FORMAT = "icon_format";
250 }
251
Makoto Onuki41066a62016-03-09 16:18:44 -0800252 final Context mContext;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800253
254 private final Object mLock = new Object();
255
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700256 private static List<ResolveInfo> EMPTY_RESOLVE_INFO = new ArrayList<>(0);
257
Mark Renoufe065f7c2016-11-01 11:48:24 -0400258 // Temporarily reverted to anonymous inner class form due to: b/32554459
259 private static Predicate<ResolveInfo> ACTIVITY_NOT_EXPORTED = new Predicate<ResolveInfo>() {
260 public boolean test(ResolveInfo ri) {
261 return !ri.activityInfo.exported;
262 }
263 };
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700264
Mark Renoufe065f7c2016-11-01 11:48:24 -0400265 // Temporarily reverted to anonymous inner class form due to: b/32554459
266 private static Predicate<PackageInfo> PACKAGE_NOT_INSTALLED = new Predicate<PackageInfo>() {
267 public boolean test(PackageInfo pi) {
268 return !isInstalled(pi);
269 }
270 };
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700271
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800272 private final Handler mHandler;
273
274 @GuardedBy("mLock")
275 private final ArrayList<ShortcutChangeListener> mListeners = new ArrayList<>(1);
276
277 @GuardedBy("mLock")
278 private long mRawLastResetTime;
279
280 /**
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -0800281 * User ID -> UserShortcuts
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800282 */
283 @GuardedBy("mLock")
Makoto Onuki31459242016-03-22 11:12:18 -0700284 private final SparseArray<ShortcutUser> mUsers = new SparseArray<>();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800285
286 /**
Makoto Onuki708703b2017-12-11 16:38:11 -0800287 * User ID -> ShortcutNonPersistentUser
288 */
289 @GuardedBy("mLock")
290 private final SparseArray<ShortcutNonPersistentUser> mShortcutNonPersistentUsers =
291 new SparseArray<>();
292
293 /**
Makoto Onukib5a012f2016-06-21 11:13:53 -0700294 * Max number of dynamic + manifest shortcuts that each application can have at a time.
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800295 */
Makoto Onukib5a012f2016-06-21 11:13:53 -0700296 private int mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800297
298 /**
Makoto Onukib6d35232016-04-04 15:57:17 -0700299 * Max number of updating API calls that each application can make during the interval.
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800300 */
Makoto Onukib6d35232016-04-04 15:57:17 -0700301 int mMaxUpdatesPerInterval;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800302
303 /**
304 * Actual throttling-reset interval. By default it's a day.
305 */
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800306 private long mResetInterval;
307
Makoto Onuki55046222016-03-08 10:49:47 -0800308 /**
309 * Icon max width/height in pixels.
310 */
311 private int mMaxIconDimension;
312
Makoto Onuki4362a662016-03-08 18:59:09 -0800313 private CompressFormat mIconPersistFormat;
314 private int mIconPersistQuality;
Makoto Onuki55046222016-03-08 10:49:47 -0800315
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700316 private int mSaveDelayMillis;
317
Makoto Onuki0acbb142016-03-22 17:02:57 -0700318 private final IPackageManager mIPackageManager;
Makoto Onuki2d5b4652016-03-11 16:09:54 -0800319 private final PackageManagerInternal mPackageManagerInternal;
Sunny Goyal145c8f82018-02-15 14:27:09 -0800320 private final UserManagerInternal mUserManagerInternal;
Makoto Onukiac042502016-05-20 16:39:42 -0700321 private final UsageStatsManagerInternal mUsageStatsManagerInternal;
Makoto Onuki33525d22016-08-03 15:45:24 -0700322 private final ActivityManagerInternal mActivityManagerInternal;
Makoto Onuki2d5b4652016-03-11 16:09:54 -0800323
Makoto Onuki2d895c32016-12-02 15:48:40 -0800324 private final ShortcutRequestPinProcessor mShortcutRequestPinProcessor;
Makoto Onuki475c3652017-05-08 14:29:03 -0700325 private final ShortcutBitmapSaver mShortcutBitmapSaver;
Makoto Onuki50a320e2017-05-31 14:38:42 -0700326 private final ShortcutDumpFiles mShortcutDumpFiles;
Makoto Onuki2d895c32016-12-02 15:48:40 -0800327
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700328 @GuardedBy("mLock")
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700329 final SparseIntArray mUidState = new SparseIntArray();
330
331 @GuardedBy("mLock")
332 final SparseLongArray mUidLastForegroundElapsedTime = new SparseLongArray();
333
334 @GuardedBy("mLock")
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700335 private List<Integer> mDirtyUserIds = new ArrayList<>();
336
Makoto Onukic51b2872016-05-04 15:24:50 -0700337 private final AtomicBoolean mBootCompleted = new AtomicBoolean();
338
Makoto Onuki905e8852016-03-28 10:40:58 -0700339 private static final int PACKAGE_MATCH_FLAGS =
340 PackageManager.MATCH_DIRECT_BOOT_AWARE
Makoto Onukib08790c2016-06-23 14:05:46 -0700341 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE
342 | PackageManager.MATCH_UNINSTALLED_PACKAGES;
Makoto Onuki905e8852016-03-28 10:40:58 -0700343
Makoto Onukie63b04a2017-12-11 14:47:19 -0800344 /**
345 * Note we use a fine-grained lock for {@link #mUnlockedUsers} due to b/64303666.
346 */
347 @GuardedBy("mUnlockedUsers")
Makoto Onuki02f338e2016-07-29 09:40:40 -0700348 final SparseBooleanArray mUnlockedUsers = new SparseBooleanArray();
349
Makoto Onuki2e210c42016-03-30 08:30:36 -0700350 // Stats
351 @VisibleForTesting
352 interface Stats {
353 int GET_DEFAULT_HOME = 0;
354 int GET_PACKAGE_INFO = 1;
355 int GET_PACKAGE_INFO_WITH_SIG = 2;
356 int GET_APPLICATION_INFO = 3;
357 int LAUNCHER_PERMISSION_CHECK = 4;
Makoto Onuki6c1dbd52016-05-02 15:19:32 -0700358 int CLEANUP_DANGLING_BITMAPS = 5;
Makoto Onukib08790c2016-06-23 14:05:46 -0700359 int GET_ACTIVITY_WITH_METADATA = 6;
Makoto Onuki6dd9fb72016-06-01 13:55:54 -0700360 int GET_INSTALLED_PACKAGES = 7;
Makoto Onuki22fcc682016-05-17 14:52:19 -0700361 int CHECK_PACKAGE_CHANGES = 8;
Makoto Onuki157b1622016-06-02 16:13:10 -0700362 int GET_APPLICATION_RESOURCES = 9;
363 int RESOURCE_NAME_LOOKUP = 10;
Makoto Onukib08790c2016-06-23 14:05:46 -0700364 int GET_LAUNCHER_ACTIVITY = 11;
365 int CHECK_LAUNCHER_ACTIVITY = 12;
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700366 int IS_ACTIVITY_ENABLED = 13;
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700367 int PACKAGE_UPDATE_CHECK = 14;
Makoto Onuki085a05c2016-08-19 11:39:29 -0700368 int ASYNC_PRELOAD_USER_DELAY = 15;
Makoto Onuki2d895c32016-12-02 15:48:40 -0800369 int GET_DEFAULT_LAUNCHER = 16;
Makoto Onuki2e210c42016-03-30 08:30:36 -0700370
Makoto Onuki2d895c32016-12-02 15:48:40 -0800371 int COUNT = GET_DEFAULT_LAUNCHER + 1;
Makoto Onuki2e210c42016-03-30 08:30:36 -0700372 }
373
Makoto Onuki84d59342018-02-02 09:22:38 -0800374 private final StatLogger mStatLogger = new StatLogger(new String[] {
Makoto Onuki085a05c2016-08-19 11:39:29 -0700375 "getHomeActivities()",
376 "Launcher permission check",
377 "getPackageInfo()",
378 "getPackageInfo(SIG)",
379 "getApplicationInfo",
380 "cleanupDanglingBitmaps",
381 "getActivity+metadata",
382 "getInstalledPackages",
383 "checkPackageChanges",
384 "getApplicationResources",
385 "resourceNameLookup",
386 "getLauncherActivity",
387 "checkLauncherActivity",
388 "isActivityEnabled",
389 "packageUpdateCheck",
Makoto Onuki2d895c32016-12-02 15:48:40 -0800390 "asyncPreloadUserDelay",
391 "getDefaultLauncher()"
Makoto Onuki84d59342018-02-02 09:22:38 -0800392 });
Makoto Onuki2e210c42016-03-30 08:30:36 -0700393
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700394 private static final int PROCESS_STATE_FOREGROUND_THRESHOLD =
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -0800395 ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700396
Makoto Onuki7001a612016-05-27 13:24:28 -0700397 static final int OPERATION_SET = 0;
398 static final int OPERATION_ADD = 1;
399 static final int OPERATION_UPDATE = 2;
400
401 /** @hide */
402 @IntDef(value = {
403 OPERATION_SET,
404 OPERATION_ADD,
405 OPERATION_UPDATE
Makoto Onukib08790c2016-06-23 14:05:46 -0700406 })
Makoto Onuki7001a612016-05-27 13:24:28 -0700407 @Retention(RetentionPolicy.SOURCE)
Makoto Onukib08790c2016-06-23 14:05:46 -0700408 @interface ShortcutOperation {
409 }
Makoto Onuki7001a612016-05-27 13:24:28 -0700410
Makoto Onukia2241832016-07-06 13:28:37 -0700411 @GuardedBy("mLock")
412 private int mWtfCount = 0;
413
414 @GuardedBy("mLock")
415 private Exception mLastWtfStacktrace;
416
Mehdi Alizadeha20781c2019-04-25 14:52:02 -0700417 @GuardedBy("mLock")
418 private final MetricsLogger mMetricsLogger = new MetricsLogger();
419
Makoto Onukifc4cf2d2016-08-24 11:10:26 -0700420 static class InvalidFileFormatException extends Exception {
421 public InvalidFileFormatException(String message, Throwable cause) {
422 super(message, cause);
423 }
424 }
425
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800426 public ShortcutService(Context context) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700427 this(context, BackgroundThread.get().getLooper(), /*onyForPackgeManagerApis*/ false);
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700428 }
429
430 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700431 ShortcutService(Context context, Looper looper, boolean onlyForPackageManagerApis) {
Daulet Zhanguzin82adfcb2020-01-02 17:31:40 +0000432 mContext = Objects.requireNonNull(context);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800433 LocalServices.addService(ShortcutServiceInternal.class, new LocalService());
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700434 mHandler = new Handler(looper);
Makoto Onuki0acbb142016-03-22 17:02:57 -0700435 mIPackageManager = AppGlobals.getPackageManager();
Daulet Zhanguzin82adfcb2020-01-02 17:31:40 +0000436 mPackageManagerInternal = Objects.requireNonNull(
Makoto Onukiac042502016-05-20 16:39:42 -0700437 LocalServices.getService(PackageManagerInternal.class));
Daulet Zhanguzin82adfcb2020-01-02 17:31:40 +0000438 mUserManagerInternal = Objects.requireNonNull(
Sunny Goyal145c8f82018-02-15 14:27:09 -0800439 LocalServices.getService(UserManagerInternal.class));
Daulet Zhanguzin82adfcb2020-01-02 17:31:40 +0000440 mUsageStatsManagerInternal = Objects.requireNonNull(
Makoto Onukiac042502016-05-20 16:39:42 -0700441 LocalServices.getService(UsageStatsManagerInternal.class));
Daulet Zhanguzin82adfcb2020-01-02 17:31:40 +0000442 mActivityManagerInternal = Objects.requireNonNull(
Makoto Onuki33525d22016-08-03 15:45:24 -0700443 LocalServices.getService(ActivityManagerInternal.class));
Makoto Onukicdc78f72016-03-21 15:47:52 -0700444
Makoto Onuki2d895c32016-12-02 15:48:40 -0800445 mShortcutRequestPinProcessor = new ShortcutRequestPinProcessor(this, mLock);
Makoto Onuki475c3652017-05-08 14:29:03 -0700446 mShortcutBitmapSaver = new ShortcutBitmapSaver(this);
Makoto Onuki50a320e2017-05-31 14:38:42 -0700447 mShortcutDumpFiles = new ShortcutDumpFiles(this);
Makoto Onuki2d895c32016-12-02 15:48:40 -0800448
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700449 if (onlyForPackageManagerApis) {
450 return; // Don't do anything further. For unit tests only.
451 }
452
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700453 // Register receivers.
454
455 // We need to set a priority, so let's just not use PackageMonitor for now.
456 // TODO Refactor PackageMonitor to support priorities.
457 final IntentFilter packageFilter = new IntentFilter();
458 packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
459 packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
460 packageFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
461 packageFilter.addAction(Intent.ACTION_PACKAGE_DATA_CLEARED);
462 packageFilter.addDataScheme("package");
463 packageFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
464 mContext.registerReceiverAsUser(mPackageMonitor, UserHandle.ALL,
465 packageFilter, null, mHandler);
466
Makoto Onuki10305202016-07-14 18:14:08 -0700467 final IntentFilter preferedActivityFilter = new IntentFilter();
468 preferedActivityFilter.addAction(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
469 preferedActivityFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
470 mContext.registerReceiverAsUser(mPackageMonitor, UserHandle.ALL,
471 preferedActivityFilter, null, mHandler);
472
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700473 final IntentFilter localeFilter = new IntentFilter();
474 localeFilter.addAction(Intent.ACTION_LOCALE_CHANGED);
475 localeFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
476 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL,
477 localeFilter, null, mHandler);
Makoto Onukif34c3082016-07-13 10:25:25 -0700478
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700479 injectRegisterUidObserver(mUidObserver, ActivityManager.UID_OBSERVER_PROCSTATE
480 | ActivityManager.UID_OBSERVER_GONE);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800481 }
482
Makoto Onuki84d59342018-02-02 09:22:38 -0800483 long getStatStartTime() {
484 return mStatLogger.getTime();
485 }
486
Makoto Onuki2e210c42016-03-30 08:30:36 -0700487 void logDurationStat(int statId, long start) {
Makoto Onuki84d59342018-02-02 09:22:38 -0800488 mStatLogger.logDurationStat(statId, start);
Makoto Onuki2e210c42016-03-30 08:30:36 -0700489 }
490
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700491 public String injectGetLocaleTagsForUser(@UserIdInt int userId) {
492 // TODO This should get the per-user locale. b/30123329 b/30119489
493 return LocaleList.getDefault().toLanguageTags();
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700494 }
495
496 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Makoto Onukib08790c2016-06-23 14:05:46 -0700497 @Override
Hui Yu26969322019-08-21 14:56:35 -0700498 public void onUidStateChanged(int uid, int procState, long procStateSeq, int capability) {
Makoto Onukidc3f6d12017-09-22 17:22:50 -0700499 injectPostToHandler(() -> handleOnUidStateChanged(uid, procState));
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700500 }
501
Makoto Onukib08790c2016-06-23 14:05:46 -0700502 @Override
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700503 public void onUidGone(int uid, boolean disabled) {
Makoto Onukidc3f6d12017-09-22 17:22:50 -0700504 injectPostToHandler(() ->
505 handleOnUidStateChanged(uid, ActivityManager.PROCESS_STATE_NONEXISTENT));
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700506 }
507
Makoto Onukib08790c2016-06-23 14:05:46 -0700508 @Override
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700509 public void onUidActive(int uid) {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700510 }
511
Makoto Onukib08790c2016-06-23 14:05:46 -0700512 @Override
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700513 public void onUidIdle(int uid, boolean disabled) {
514 }
515
516 @Override public void onUidCachedChanged(int uid, boolean cached) {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700517 }
518 };
519
520 void handleOnUidStateChanged(int uid, int procState) {
521 if (DEBUG_PROCSTATE) {
522 Slog.d(TAG, "onUidStateChanged: uid=" + uid + " state=" + procState);
523 }
524 synchronized (mLock) {
525 mUidState.put(uid, procState);
526
527 // We need to keep track of last time an app comes to foreground.
528 // See ShortcutPackage.getApiCallCount() for how it's used.
529 // It doesn't have to be persisted, but it needs to be the elapsed time.
530 if (isProcessStateForeground(procState)) {
531 mUidLastForegroundElapsedTime.put(uid, injectElapsedRealtime());
532 }
533 }
534 }
535
536 private boolean isProcessStateForeground(int processState) {
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800537 return processState <= PROCESS_STATE_FOREGROUND_THRESHOLD;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700538 }
539
Andreas Gampea36dc622018-02-05 17:19:22 -0800540 @GuardedBy("mLock")
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700541 boolean isUidForegroundLocked(int uid) {
542 if (uid == Process.SYSTEM_UID) {
543 // IUidObserver doesn't report the state of SYSTEM, but it always has bound services,
544 // so it's foreground anyway.
545 return true;
546 }
Makoto Onuki33525d22016-08-03 15:45:24 -0700547 // First, check with the local cache.
548 if (isProcessStateForeground(mUidState.get(uid, ActivityManager.MAX_PROCESS_STATE))) {
549 return true;
550 }
551 // If the cache says background, reach out to AM. Since it'll internally need to hold
552 // the AM lock, we use it as a last resort.
553 return isProcessStateForeground(mActivityManagerInternal.getUidProcessState(uid));
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700554 }
555
Andreas Gampea36dc622018-02-05 17:19:22 -0800556 @GuardedBy("mLock")
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700557 long getUidLastForegroundElapsedTimeLocked(int uid) {
558 return mUidLastForegroundElapsedTime.get(uid);
559 }
560
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800561 /**
562 * System service lifecycle.
563 */
564 public static final class Lifecycle extends SystemService {
565 final ShortcutService mService;
566
567 public Lifecycle(Context context) {
568 super(context);
Makoto Onukia4f89b12017-10-05 10:37:55 -0700569 if (DEBUG) {
570 Binder.LOG_RUNTIME_EXCEPTION = true;
571 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800572 mService = new ShortcutService(context);
573 }
574
575 @Override
576 public void onStart() {
577 publishBinderService(Context.SHORTCUT_SERVICE, mService);
578 }
579
580 @Override
581 public void onBootPhase(int phase) {
582 mService.onBootPhase(phase);
583 }
584
585 @Override
Makoto Onuki01ce92b2017-04-28 12:24:16 -0700586 public void onStopUser(int userHandle) {
587 mService.handleStopUser(userHandle);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800588 }
589
590 @Override
Makoto Onukif3a572b2016-03-10 12:28:38 -0800591 public void onUnlockUser(int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -0700592 mService.handleUnlockUser(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800593 }
594 }
595
596 /** lifecycle event */
597 void onBootPhase(int phase) {
598 if (DEBUG) {
599 Slog.d(TAG, "onBootPhase: " + phase);
600 }
601 switch (phase) {
602 case SystemService.PHASE_LOCK_SETTINGS_READY:
603 initialize();
604 break;
Makoto Onukic51b2872016-05-04 15:24:50 -0700605 case SystemService.PHASE_BOOT_COMPLETED:
606 mBootCompleted.set(true);
607 break;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800608 }
609 }
610
611 /** lifecycle event */
Makoto Onukicdc78f72016-03-21 15:47:52 -0700612 void handleUnlockUser(int userId) {
Makoto Onuki22fcc682016-05-17 14:52:19 -0700613 if (DEBUG) {
Makoto Onuki085a05c2016-08-19 11:39:29 -0700614 Slog.d(TAG, "handleUnlockUser: user=" + userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700615 }
Makoto Onukie63b04a2017-12-11 14:47:19 -0800616 synchronized (mUnlockedUsers) {
Makoto Onuki02f338e2016-07-29 09:40:40 -0700617 mUnlockedUsers.put(userId, true);
Makoto Onukicdc78f72016-03-21 15:47:52 -0700618 }
Makoto Onuki085a05c2016-08-19 11:39:29 -0700619
620 // Preload the user data.
621 // Note, we don't use mHandler here but instead just start a new thread.
622 // This is because mHandler (which uses com.android.internal.os.BackgroundThread) is very
623 // busy at this point and this could take hundreds of milliseconds, which would be too
624 // late since the launcher would already have started.
625 // So we just create a new thread. This code runs rarely, so we don't use a thread pool
626 // or anything.
Makoto Onuki84d59342018-02-02 09:22:38 -0800627 final long start = getStatStartTime();
Makoto Onuki085a05c2016-08-19 11:39:29 -0700628 injectRunOnNewThread(() -> {
629 synchronized (mLock) {
630 logDurationStat(Stats.ASYNC_PRELOAD_USER_DELAY, start);
631 getUserShortcutsLocked(userId);
632 }
633 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800634 }
635
636 /** lifecycle event */
Makoto Onuki01ce92b2017-04-28 12:24:16 -0700637 void handleStopUser(int userId) {
Makoto Onuki02f338e2016-07-29 09:40:40 -0700638 if (DEBUG) {
Makoto Onuki01ce92b2017-04-28 12:24:16 -0700639 Slog.d(TAG, "handleStopUser: user=" + userId);
Makoto Onuki02f338e2016-07-29 09:40:40 -0700640 }
Makoto Onukicdc78f72016-03-21 15:47:52 -0700641 synchronized (mLock) {
642 unloadUserLocked(userId);
Makoto Onuki02f338e2016-07-29 09:40:40 -0700643
Makoto Onukie63b04a2017-12-11 14:47:19 -0800644 synchronized (mUnlockedUsers) {
645 mUnlockedUsers.put(userId, false);
646 }
Makoto Onukicdc78f72016-03-21 15:47:52 -0700647 }
648 }
649
Andreas Gampea36dc622018-02-05 17:19:22 -0800650 @GuardedBy("mLock")
Makoto Onukicdc78f72016-03-21 15:47:52 -0700651 private void unloadUserLocked(int userId) {
652 if (DEBUG) {
653 Slog.d(TAG, "unloadUserLocked: user=" + userId);
654 }
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700655 // Save all dirty information.
656 saveDirtyInfo();
657
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800658 // Unload
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -0800659 mUsers.delete(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800660 }
661
662 /** Return the base state file name */
663 private AtomicFile getBaseStateFile() {
664 final File path = new File(injectSystemDataPath(), FILENAME_BASE_STATE);
665 path.mkdirs();
666 return new AtomicFile(path);
667 }
668
669 /**
670 * Init the instance. (load the state file, etc)
671 */
672 private void initialize() {
673 synchronized (mLock) {
Makoto Onuki4362a662016-03-08 18:59:09 -0800674 loadConfigurationLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800675 loadBaseStateLocked();
676 }
677 }
678
Makoto Onuki4362a662016-03-08 18:59:09 -0800679 /**
680 * Load the configuration from Settings.
681 */
682 private void loadConfigurationLocked() {
683 updateConfigurationLocked(injectShortcutManagerConstants());
684 }
Makoto Onuki55046222016-03-08 10:49:47 -0800685
Makoto Onuki4362a662016-03-08 18:59:09 -0800686 /**
687 * Load the configuration from Settings.
688 */
689 @VisibleForTesting
690 boolean updateConfigurationLocked(String config) {
691 boolean result = true;
692
693 final KeyValueListParser parser = new KeyValueListParser(',');
694 try {
695 parser.setString(config);
696 } catch (IllegalArgumentException e) {
697 // Failed to parse the settings string, log this and move on
698 // with defaults.
699 Slog.e(TAG, "Bad shortcut manager settings", e);
700 result = false;
701 }
702
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700703 mSaveDelayMillis = Math.max(0, (int) parser.getLong(ConfigConstants.KEY_SAVE_DELAY_MILLIS,
704 DEFAULT_SAVE_DELAY_MS));
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700705
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700706 mResetInterval = Math.max(1, parser.getLong(
Makoto Onuki4362a662016-03-08 18:59:09 -0800707 ConfigConstants.KEY_RESET_INTERVAL_SEC, DEFAULT_RESET_INTERVAL_SEC)
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700708 * 1000L);
Makoto Onuki4362a662016-03-08 18:59:09 -0800709
Makoto Onukib6d35232016-04-04 15:57:17 -0700710 mMaxUpdatesPerInterval = Math.max(0, (int) parser.getLong(
711 ConfigConstants.KEY_MAX_UPDATES_PER_INTERVAL, DEFAULT_MAX_UPDATES_PER_INTERVAL));
Makoto Onuki4362a662016-03-08 18:59:09 -0800712
Makoto Onukib5a012f2016-06-21 11:13:53 -0700713 mMaxShortcuts = Math.max(0, (int) parser.getLong(
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700714 ConfigConstants.KEY_MAX_SHORTCUTS, DEFAULT_MAX_SHORTCUTS_PER_APP));
Makoto Onuki4362a662016-03-08 18:59:09 -0800715
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700716 final int iconDimensionDp = Math.max(1, injectIsLowRamDevice()
Makoto Onuki4362a662016-03-08 18:59:09 -0800717 ? (int) parser.getLong(
Makoto Onukib08790c2016-06-23 14:05:46 -0700718 ConfigConstants.KEY_MAX_ICON_DIMENSION_DP_LOWRAM,
719 DEFAULT_MAX_ICON_DIMENSION_LOWRAM_DP)
Makoto Onuki4362a662016-03-08 18:59:09 -0800720 : (int) parser.getLong(
Makoto Onukib08790c2016-06-23 14:05:46 -0700721 ConfigConstants.KEY_MAX_ICON_DIMENSION_DP,
722 DEFAULT_MAX_ICON_DIMENSION_DP));
Makoto Onuki4362a662016-03-08 18:59:09 -0800723
724 mMaxIconDimension = injectDipToPixel(iconDimensionDp);
725
726 mIconPersistFormat = CompressFormat.valueOf(
727 parser.getString(ConfigConstants.KEY_ICON_FORMAT, DEFAULT_ICON_PERSIST_FORMAT));
728
729 mIconPersistQuality = (int) parser.getLong(
730 ConfigConstants.KEY_ICON_QUALITY,
731 DEFAULT_ICON_PERSIST_QUALITY);
732
733 return result;
734 }
735
736 @VisibleForTesting
737 String injectShortcutManagerConstants() {
738 return android.provider.Settings.Global.getString(
739 mContext.getContentResolver(),
740 android.provider.Settings.Global.SHORTCUT_MANAGER_CONSTANTS);
741 }
742
743 @VisibleForTesting
744 int injectDipToPixel(int dip) {
745 return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip,
746 mContext.getResources().getDisplayMetrics());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800747 }
748
Makoto Onuki55046222016-03-08 10:49:47 -0800749 // === Persisting ===
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800750
751 @Nullable
Makoto Onuki41066a62016-03-09 16:18:44 -0800752 static String parseStringAttribute(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800753 return parser.getAttributeValue(null, attribute);
754 }
755
Makoto Onuki0acbb142016-03-22 17:02:57 -0700756 static boolean parseBooleanAttribute(XmlPullParser parser, String attribute) {
757 return parseLongAttribute(parser, attribute) == 1;
758 }
759
Makoto Onukia4f89b12017-10-05 10:37:55 -0700760 static boolean parseBooleanAttribute(XmlPullParser parser, String attribute, boolean def) {
761 return parseLongAttribute(parser, attribute, (def ? 1 : 0)) == 1;
762 }
763
Makoto Onuki41066a62016-03-09 16:18:44 -0800764 static int parseIntAttribute(XmlPullParser parser, String attribute) {
765 return (int) parseLongAttribute(parser, attribute);
766 }
767
Makoto Onukid99c6f02016-03-28 11:02:54 -0700768 static int parseIntAttribute(XmlPullParser parser, String attribute, int def) {
769 return (int) parseLongAttribute(parser, attribute, def);
770 }
771
Makoto Onuki41066a62016-03-09 16:18:44 -0800772 static long parseLongAttribute(XmlPullParser parser, String attribute) {
Makoto Onukid99c6f02016-03-28 11:02:54 -0700773 return parseLongAttribute(parser, attribute, 0);
774 }
775
776 static long parseLongAttribute(XmlPullParser parser, String attribute, long def) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800777 final String value = parseStringAttribute(parser, attribute);
778 if (TextUtils.isEmpty(value)) {
Makoto Onukid99c6f02016-03-28 11:02:54 -0700779 return def;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800780 }
781 try {
782 return Long.parseLong(value);
783 } catch (NumberFormatException e) {
784 Slog.e(TAG, "Error parsing long " + value);
Makoto Onukid99c6f02016-03-28 11:02:54 -0700785 return def;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800786 }
787 }
788
789 @Nullable
Makoto Onuki41066a62016-03-09 16:18:44 -0800790 static ComponentName parseComponentNameAttribute(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800791 final String value = parseStringAttribute(parser, attribute);
792 if (TextUtils.isEmpty(value)) {
793 return null;
794 }
795 return ComponentName.unflattenFromString(value);
796 }
797
798 @Nullable
Makoto Onuki440a1ea2016-07-20 14:21:18 -0700799 static Intent parseIntentAttributeNoDefault(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800800 final String value = parseStringAttribute(parser, attribute);
Makoto Onukib5a012f2016-06-21 11:13:53 -0700801 Intent parsed = null;
802 if (!TextUtils.isEmpty(value)) {
803 try {
804 parsed = Intent.parseUri(value, /* flags =*/ 0);
805 } catch (URISyntaxException e) {
806 Slog.e(TAG, "Error parsing intent", e);
807 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800808 }
Makoto Onuki440a1ea2016-07-20 14:21:18 -0700809 return parsed;
810 }
811
812 @Nullable
813 static Intent parseIntentAttribute(XmlPullParser parser, String attribute) {
814 Intent parsed = parseIntentAttributeNoDefault(parser, attribute);
Makoto Onukib5a012f2016-06-21 11:13:53 -0700815 if (parsed == null) {
816 // Default intent.
817 parsed = new Intent(Intent.ACTION_VIEW);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800818 }
Makoto Onukib5a012f2016-06-21 11:13:53 -0700819 return parsed;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800820 }
821
Makoto Onuki41066a62016-03-09 16:18:44 -0800822 static void writeTagValue(XmlSerializer out, String tag, String value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800823 if (TextUtils.isEmpty(value)) return;
824
825 out.startTag(null, tag);
826 out.attribute(null, ATTR_VALUE, value);
827 out.endTag(null, tag);
828 }
829
Makoto Onuki41066a62016-03-09 16:18:44 -0800830 static void writeTagValue(XmlSerializer out, String tag, long value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800831 writeTagValue(out, tag, Long.toString(value));
832 }
833
Makoto Onuki2d5b4652016-03-11 16:09:54 -0800834 static void writeTagValue(XmlSerializer out, String tag, ComponentName name) throws IOException {
835 if (name == null) return;
836 writeTagValue(out, tag, name.flattenToString());
837 }
838
Makoto Onuki41066a62016-03-09 16:18:44 -0800839 static void writeTagExtra(XmlSerializer out, String tag, PersistableBundle bundle)
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800840 throws IOException, XmlPullParserException {
841 if (bundle == null) return;
842
843 out.startTag(null, tag);
844 bundle.saveToXml(out);
845 out.endTag(null, tag);
846 }
847
Makoto Onuki22fcc682016-05-17 14:52:19 -0700848 static void writeAttr(XmlSerializer out, String name, CharSequence value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800849 if (TextUtils.isEmpty(value)) return;
850
Makoto Onuki22fcc682016-05-17 14:52:19 -0700851 out.attribute(null, name, value.toString());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800852 }
853
Makoto Onuki41066a62016-03-09 16:18:44 -0800854 static void writeAttr(XmlSerializer out, String name, long value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800855 writeAttr(out, name, String.valueOf(value));
856 }
857
Makoto Onuki0acbb142016-03-22 17:02:57 -0700858 static void writeAttr(XmlSerializer out, String name, boolean value) throws IOException {
859 if (value) {
860 writeAttr(out, name, "1");
Makoto Onukia4f89b12017-10-05 10:37:55 -0700861 } else {
862 writeAttr(out, name, "0");
Makoto Onuki0acbb142016-03-22 17:02:57 -0700863 }
864 }
865
Makoto Onuki41066a62016-03-09 16:18:44 -0800866 static void writeAttr(XmlSerializer out, String name, ComponentName comp) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800867 if (comp == null) return;
868 writeAttr(out, name, comp.flattenToString());
869 }
870
Makoto Onuki41066a62016-03-09 16:18:44 -0800871 static void writeAttr(XmlSerializer out, String name, Intent intent) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800872 if (intent == null) return;
873
874 writeAttr(out, name, intent.toUri(/* flags =*/ 0));
875 }
876
Andreas Gampea36dc622018-02-05 17:19:22 -0800877 @GuardedBy("mLock")
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800878 @VisibleForTesting
879 void saveBaseStateLocked() {
880 final AtomicFile file = getBaseStateFile();
881 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700882 Slog.d(TAG, "Saving to " + file.getBaseFile());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800883 }
884
885 FileOutputStream outs = null;
886 try {
887 outs = file.startWrite();
888
889 // Write to XML
890 XmlSerializer out = new FastXmlSerializer();
891 out.setOutput(outs, StandardCharsets.UTF_8.name());
892 out.startDocument(null, true);
893 out.startTag(null, TAG_ROOT);
894
895 // Body.
896 writeTagValue(out, TAG_LAST_RESET_TIME, mRawLastResetTime);
897
898 // Epilogue.
899 out.endTag(null, TAG_ROOT);
900 out.endDocument();
901
902 // Close.
903 file.finishWrite(outs);
904 } catch (IOException e) {
905 Slog.e(TAG, "Failed to write to file " + file.getBaseFile(), e);
906 file.failWrite(outs);
907 }
908 }
909
Andreas Gampea36dc622018-02-05 17:19:22 -0800910 @GuardedBy("mLock")
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800911 private void loadBaseStateLocked() {
912 mRawLastResetTime = 0;
913
914 final AtomicFile file = getBaseStateFile();
915 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700916 Slog.d(TAG, "Loading from " + file.getBaseFile());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800917 }
918 try (FileInputStream in = file.openRead()) {
919 XmlPullParser parser = Xml.newPullParser();
920 parser.setInput(in, StandardCharsets.UTF_8.name());
921
922 int type;
923 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
924 if (type != XmlPullParser.START_TAG) {
925 continue;
926 }
927 final int depth = parser.getDepth();
928 // Check the root tag
929 final String tag = parser.getName();
930 if (depth == 1) {
931 if (!TAG_ROOT.equals(tag)) {
932 Slog.e(TAG, "Invalid root tag: " + tag);
933 return;
934 }
935 continue;
936 }
937 // Assume depth == 2
938 switch (tag) {
939 case TAG_LAST_RESET_TIME:
940 mRawLastResetTime = parseLongAttribute(parser, ATTR_VALUE);
941 break;
942 default:
943 Slog.e(TAG, "Invalid tag: " + tag);
944 break;
945 }
946 }
947 } catch (FileNotFoundException e) {
948 // Use the default
Makoto Onukib08790c2016-06-23 14:05:46 -0700949 } catch (IOException | XmlPullParserException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800950 Slog.e(TAG, "Failed to read file " + file.getBaseFile(), e);
951
952 mRawLastResetTime = 0;
953 }
954 // Adjust the last reset time.
955 getLastResetTimeLocked();
956 }
957
Makoto Onuki0eed4412016-07-21 11:21:59 -0700958 @VisibleForTesting
959 final File getUserFile(@UserIdInt int userId) {
960 return new File(injectUserDataPath(userId), FILENAME_USER_PACKAGES);
961 }
962
Andreas Gampea36dc622018-02-05 17:19:22 -0800963 @GuardedBy("mLock")
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800964 private void saveUserLocked(@UserIdInt int userId) {
Makoto Onuki0eed4412016-07-21 11:21:59 -0700965 final File path = getUserFile(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800966 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700967 Slog.d(TAG, "Saving to " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800968 }
Makoto Onuki475c3652017-05-08 14:29:03 -0700969
970 mShortcutBitmapSaver.waitForAllSavesLocked();
971
Makoto Onuki0eed4412016-07-21 11:21:59 -0700972 path.getParentFile().mkdirs();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800973 final AtomicFile file = new AtomicFile(path);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700974 FileOutputStream os = null;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800975 try {
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700976 os = file.startWrite();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800977
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700978 saveUserInternalLocked(userId, os, /* forBackup= */ false);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800979
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700980 file.finishWrite(os);
Makoto Onuki1e173232016-08-10 10:47:13 -0700981
982 // Remove all dangling bitmap files.
983 cleanupDanglingBitmapDirectoriesLocked(userId);
Makoto Onukib08790c2016-06-23 14:05:46 -0700984 } catch (XmlPullParserException | IOException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800985 Slog.e(TAG, "Failed to write to file " + file.getBaseFile(), e);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700986 file.failWrite(os);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800987 }
Mehdi Alizadeha20781c2019-04-25 14:52:02 -0700988
989 getUserShortcutsLocked(userId).logSharingShortcutStats(mMetricsLogger);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800990 }
991
Andreas Gampea36dc622018-02-05 17:19:22 -0800992 @GuardedBy("mLock")
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700993 private void saveUserInternalLocked(@UserIdInt int userId, OutputStream os,
994 boolean forBackup) throws IOException, XmlPullParserException {
995
996 final BufferedOutputStream bos = new BufferedOutputStream(os);
997
998 // Write to XML
999 XmlSerializer out = new FastXmlSerializer();
1000 out.setOutput(bos, StandardCharsets.UTF_8.name());
1001 out.startDocument(null, true);
1002
Makoto Onukic51b2872016-05-04 15:24:50 -07001003 getUserShortcutsLocked(userId).saveToXml(out, forBackup);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001004
1005 out.endDocument();
1006
1007 bos.flush();
1008 os.flush();
1009 }
1010
Makoto Onuki41066a62016-03-09 16:18:44 -08001011 static IOException throwForInvalidTag(int depth, String tag) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001012 throw new IOException(String.format("Invalid tag '%s' found at depth %d", tag, depth));
1013 }
1014
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001015 static void warnForInvalidTag(int depth, String tag) throws IOException {
1016 Slog.w(TAG, String.format("Invalid tag '%s' found at depth %d", tag, depth));
1017 }
1018
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001019 @Nullable
Makoto Onuki31459242016-03-22 11:12:18 -07001020 private ShortcutUser loadUserLocked(@UserIdInt int userId) {
Makoto Onuki0eed4412016-07-21 11:21:59 -07001021 final File path = getUserFile(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001022 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001023 Slog.d(TAG, "Loading from " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001024 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001025 final AtomicFile file = new AtomicFile(path);
1026
1027 final FileInputStream in;
1028 try {
1029 in = file.openRead();
1030 } catch (FileNotFoundException e) {
1031 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001032 Slog.d(TAG, "Not found " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001033 }
1034 return null;
1035 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001036 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07001037 final ShortcutUser ret = loadUserInternal(userId, in, /* forBackup= */ false);
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001038 return ret;
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07001039 } catch (IOException | XmlPullParserException | InvalidFileFormatException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001040 Slog.e(TAG, "Failed to read file " + file.getBaseFile(), e);
1041 return null;
1042 } finally {
1043 IoUtils.closeQuietly(in);
1044 }
1045 }
1046
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001047 private ShortcutUser loadUserInternal(@UserIdInt int userId, InputStream is,
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07001048 boolean fromBackup) throws XmlPullParserException, IOException,
1049 InvalidFileFormatException {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001050
1051 final BufferedInputStream bis = new BufferedInputStream(is);
1052
1053 ShortcutUser ret = null;
1054 XmlPullParser parser = Xml.newPullParser();
1055 parser.setInput(bis, StandardCharsets.UTF_8.name());
1056
1057 int type;
1058 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1059 if (type != XmlPullParser.START_TAG) {
1060 continue;
1061 }
1062 final int depth = parser.getDepth();
1063
1064 final String tag = parser.getName();
1065 if (DEBUG_LOAD) {
1066 Slog.d(TAG, String.format("depth=%d type=%d name=%s",
1067 depth, type, tag));
1068 }
1069 if ((depth == 1) && ShortcutUser.TAG_ROOT.equals(tag)) {
1070 ret = ShortcutUser.loadFromXml(this, parser, userId, fromBackup);
1071 continue;
1072 }
1073 throwForInvalidTag(depth, tag);
1074 }
1075 return ret;
1076 }
1077
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001078 private void scheduleSaveBaseState() {
Makoto Onuki0acbb142016-03-22 17:02:57 -07001079 scheduleSaveInner(UserHandle.USER_NULL); // Special case -- use USER_NULL for base state.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001080 }
1081
Makoto Onuki2d5b4652016-03-11 16:09:54 -08001082 void scheduleSaveUser(@UserIdInt int userId) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07001083 scheduleSaveInner(userId);
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001084 }
1085
1086 // In order to re-schedule, we need to reuse the same instance, so keep it in final.
1087 private final Runnable mSaveDirtyInfoRunner = this::saveDirtyInfo;
1088
Makoto Onuki0acbb142016-03-22 17:02:57 -07001089 private void scheduleSaveInner(@UserIdInt int userId) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001090 if (DEBUG) {
1091 Slog.d(TAG, "Scheduling to save for " + userId);
1092 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001093 synchronized (mLock) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001094 if (!mDirtyUserIds.contains(userId)) {
1095 mDirtyUserIds.add(userId);
1096 }
1097 }
1098 // If already scheduled, remove that and re-schedule in N seconds.
1099 mHandler.removeCallbacks(mSaveDirtyInfoRunner);
1100 mHandler.postDelayed(mSaveDirtyInfoRunner, mSaveDelayMillis);
1101 }
1102
1103 @VisibleForTesting
1104 void saveDirtyInfo() {
1105 if (DEBUG) {
1106 Slog.d(TAG, "saveDirtyInfo");
1107 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001108 try {
1109 synchronized (mLock) {
1110 for (int i = mDirtyUserIds.size() - 1; i >= 0; i--) {
1111 final int userId = mDirtyUserIds.get(i);
1112 if (userId == UserHandle.USER_NULL) { // USER_NULL for base state.
1113 saveBaseStateLocked();
1114 } else {
1115 saveUserLocked(userId);
1116 }
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001117 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001118 mDirtyUserIds.clear();
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001119 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001120 } catch (Exception e) {
1121 wtf("Exception in saveDirtyInfo", e);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001122 }
1123 }
1124
1125 /** Return the last reset time. */
Andreas Gampea36dc622018-02-05 17:19:22 -08001126 @GuardedBy("mLock")
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001127 long getLastResetTimeLocked() {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001128 updateTimesLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001129 return mRawLastResetTime;
1130 }
1131
1132 /** Return the next reset time. */
Andreas Gampea36dc622018-02-05 17:19:22 -08001133 @GuardedBy("mLock")
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001134 long getNextResetTimeLocked() {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001135 updateTimesLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001136 return mRawLastResetTime + mResetInterval;
1137 }
1138
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001139 static boolean isClockValid(long time) {
1140 return time >= 1420070400; // Thu, 01 Jan 2015 00:00:00 GMT
1141 }
1142
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001143 /**
1144 * Update the last reset time.
1145 */
Andreas Gampea36dc622018-02-05 17:19:22 -08001146 @GuardedBy("mLock")
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001147 private void updateTimesLocked() {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001148
1149 final long now = injectCurrentTimeMillis();
1150
1151 final long prevLastResetTime = mRawLastResetTime;
1152
1153 if (mRawLastResetTime == 0) { // first launch.
1154 // TODO Randomize??
1155 mRawLastResetTime = now;
1156 } else if (now < mRawLastResetTime) {
1157 // Clock rewound.
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001158 if (isClockValid(now)) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001159 Slog.w(TAG, "Clock rewound");
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001160 // TODO Randomize??
1161 mRawLastResetTime = now;
1162 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001163 } else {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001164 if ((mRawLastResetTime + mResetInterval) <= now) {
1165 final long offset = mRawLastResetTime % mResetInterval;
1166 mRawLastResetTime = ((now / mResetInterval) * mResetInterval) + offset;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001167 }
1168 }
1169 if (prevLastResetTime != mRawLastResetTime) {
1170 scheduleSaveBaseState();
1171 }
1172 }
1173
Makoto Onuki1e173232016-08-10 10:47:13 -07001174 // Requires mLock held, but "Locked" prefix would look weired so we just say "L".
Makoto Onuki02f338e2016-07-29 09:40:40 -07001175 protected boolean isUserUnlockedL(@UserIdInt int userId) {
Makoto Onuki1e173232016-08-10 10:47:13 -07001176 // First, check the local copy.
Makoto Onukie63b04a2017-12-11 14:47:19 -08001177 synchronized (mUnlockedUsers) {
1178 if (mUnlockedUsers.get(userId)) {
1179 return true;
1180 }
Makoto Onuki1e173232016-08-10 10:47:13 -07001181 }
Mehdi Alizadeh32774622018-11-05 17:32:01 -08001182
Makoto Onuki1e173232016-08-10 10:47:13 -07001183 // If the local copy says the user is locked, check with AM for the actual state, since
1184 // the user might just have been unlocked.
1185 // Note we just don't use isUserUnlockingOrUnlocked() here, because it'll return false
1186 // when the user is STOPPING, which we still want to consider as "unlocked".
Sunny Goyal145c8f82018-02-15 14:27:09 -08001187 return mUserManagerInternal.isUserUnlockingOrUnlocked(userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07001188 }
1189
Makoto Onuki02f338e2016-07-29 09:40:40 -07001190 // Requires mLock held, but "Locked" prefix would look weired so we jsut say "L".
1191 void throwIfUserLockedL(@UserIdInt int userId) {
1192 if (!isUserUnlockedL(userId)) {
Makoto Onuki9c850012016-07-26 15:50:50 -07001193 throw new IllegalStateException("User " + userId + " is locked or not running");
1194 }
1195 }
1196
Makoto Onukicdc78f72016-03-21 15:47:52 -07001197 @GuardedBy("mLock")
1198 @NonNull
Makoto Onuki2e210c42016-03-30 08:30:36 -07001199 private boolean isUserLoadedLocked(@UserIdInt int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07001200 return mUsers.get(userId) != null;
1201 }
1202
Makoto Onukidc801c82019-10-08 13:56:10 -07001203 private int mLastLockedUser = -1;
1204
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001205 /** Return the per-user state. */
1206 @GuardedBy("mLock")
1207 @NonNull
Makoto Onuki31459242016-03-22 11:12:18 -07001208 ShortcutUser getUserShortcutsLocked(@UserIdInt int userId) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001209 if (!isUserUnlockedL(userId)) {
Makoto Onukidc801c82019-10-08 13:56:10 -07001210 // Only do wtf once for each user. (until the user is unlocked)
1211 if (userId != mLastLockedUser) {
1212 wtf("User still locked");
1213 mLastLockedUser = userId;
1214 }
1215 } else {
1216 mLastLockedUser = -1;
Makoto Onuki9c850012016-07-26 15:50:50 -07001217 }
1218
Makoto Onuki31459242016-03-22 11:12:18 -07001219 ShortcutUser userPackages = mUsers.get(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001220 if (userPackages == null) {
1221 userPackages = loadUserLocked(userId);
1222 if (userPackages == null) {
Makoto Onukic51b2872016-05-04 15:24:50 -07001223 userPackages = new ShortcutUser(this, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001224 }
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08001225 mUsers.put(userId, userPackages);
Makoto Onuki085a05c2016-08-19 11:39:29 -07001226
1227 // Also when a user's data is first accessed, scan all packages.
1228 checkPackageChanges(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001229 }
1230 return userPackages;
1231 }
1232
Makoto Onuki708703b2017-12-11 16:38:11 -08001233 /** Return the non-persistent per-user state. */
1234 @GuardedBy("mLock")
1235 @NonNull
1236 ShortcutNonPersistentUser getNonPersistentUserLocked(@UserIdInt int userId) {
1237 ShortcutNonPersistentUser ret = mShortcutNonPersistentUsers.get(userId);
1238 if (ret == null) {
1239 ret = new ShortcutNonPersistentUser(this, userId);
1240 mShortcutNonPersistentUsers.put(userId, ret);
1241 }
1242 return ret;
1243 }
1244
Andreas Gampea36dc622018-02-05 17:19:22 -08001245 @GuardedBy("mLock")
Makoto Onuki2e210c42016-03-30 08:30:36 -07001246 void forEachLoadedUserLocked(@NonNull Consumer<ShortcutUser> c) {
1247 for (int i = mUsers.size() - 1; i >= 0; i--) {
1248 c.accept(mUsers.valueAt(i));
1249 }
1250 }
1251
Makoto Onukic8c33292016-09-12 16:36:59 -07001252 /**
1253 * Return the per-user per-package state. If the caller is a publisher, use
1254 * {@link #getPackageShortcutsForPublisherLocked} instead.
1255 */
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001256 @GuardedBy("mLock")
1257 @NonNull
Makoto Onuki31459242016-03-22 11:12:18 -07001258 ShortcutPackage getPackageShortcutsLocked(
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001259 @NonNull String packageName, @UserIdInt int userId) {
Makoto Onukic51b2872016-05-04 15:24:50 -07001260 return getUserShortcutsLocked(userId).getPackageShortcuts(packageName);
Makoto Onukide667372016-03-15 14:29:20 -07001261 }
1262
Makoto Onukic8c33292016-09-12 16:36:59 -07001263 /** Return the per-user per-package state. Use this when the caller is a publisher. */
1264 @GuardedBy("mLock")
1265 @NonNull
1266 ShortcutPackage getPackageShortcutsForPublisherLocked(
1267 @NonNull String packageName, @UserIdInt int userId) {
1268 final ShortcutPackage ret = getUserShortcutsLocked(userId).getPackageShortcuts(packageName);
1269 ret.getUser().onCalledByPublisher(packageName);
1270 return ret;
1271 }
1272
Makoto Onukide667372016-03-15 14:29:20 -07001273 @GuardedBy("mLock")
1274 @NonNull
Makoto Onuki2e210c42016-03-30 08:30:36 -07001275 ShortcutLauncher getLauncherShortcutsLocked(
1276 @NonNull String packageName, @UserIdInt int ownerUserId,
1277 @UserIdInt int launcherUserId) {
1278 return getUserShortcutsLocked(ownerUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07001279 .getLauncherShortcuts(packageName, launcherUserId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001280 }
1281
1282 // === Caller validation ===
1283
Makoto Onuki475c3652017-05-08 14:29:03 -07001284 void removeIconLocked(ShortcutInfo shortcut) {
1285 mShortcutBitmapSaver.removeIcon(shortcut);
Makoto Onuki55046222016-03-08 10:49:47 -08001286 }
1287
Makoto Onuki0033b2a2016-04-14 17:19:16 -07001288 public void cleanupBitmapsForPackage(@UserIdInt int userId, String packageName) {
1289 final File packagePath = new File(getUserBitmapFilePath(userId), packageName);
1290 if (!packagePath.isDirectory()) {
1291 return;
1292 }
1293 if (!(FileUtils.deleteContents(packagePath) && packagePath.delete())) {
1294 Slog.w(TAG, "Unable to remove directory " + packagePath);
1295 }
1296 }
1297
Makoto Onuki475c3652017-05-08 14:29:03 -07001298 /**
1299 * Remove dangling bitmap files for a user.
1300 *
1301 * Note this method must be called with the lock held after calling
1302 * {@link ShortcutBitmapSaver#waitForAllSavesLocked()} to make sure there's no pending bitmap
1303 * saves are going on.
1304 */
Andreas Gampea36dc622018-02-05 17:19:22 -08001305 @GuardedBy("mLock")
Makoto Onuki1e173232016-08-10 10:47:13 -07001306 private void cleanupDanglingBitmapDirectoriesLocked(@UserIdInt int userId) {
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001307 if (DEBUG) {
1308 Slog.d(TAG, "cleanupDanglingBitmaps: userId=" + userId);
1309 }
Makoto Onuki84d59342018-02-02 09:22:38 -08001310 final long start = getStatStartTime();
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001311
Makoto Onuki1e173232016-08-10 10:47:13 -07001312 final ShortcutUser user = getUserShortcutsLocked(userId);
1313
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001314 final File bitmapDir = getUserBitmapFilePath(userId);
1315 final File[] children = bitmapDir.listFiles();
1316 if (children == null) {
1317 return;
1318 }
1319 for (File child : children) {
1320 if (!child.isDirectory()) {
1321 continue;
1322 }
1323 final String packageName = child.getName();
1324 if (DEBUG) {
1325 Slog.d(TAG, "cleanupDanglingBitmaps: Found directory=" + packageName);
1326 }
1327 if (!user.hasPackage(packageName)) {
1328 if (DEBUG) {
1329 Slog.d(TAG, "Removing dangling bitmap directory: " + packageName);
1330 }
1331 cleanupBitmapsForPackage(userId, packageName);
1332 } else {
1333 cleanupDanglingBitmapFilesLocked(userId, user, packageName, child);
1334 }
1335 }
1336 logDurationStat(Stats.CLEANUP_DANGLING_BITMAPS, start);
1337 }
1338
Makoto Onuki475c3652017-05-08 14:29:03 -07001339 /**
1340 * Remove dangling bitmap files for a package.
1341 *
1342 * Note this method must be called with the lock held after calling
1343 * {@link ShortcutBitmapSaver#waitForAllSavesLocked()} to make sure there's no pending bitmap
1344 * saves are going on.
1345 */
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001346 private void cleanupDanglingBitmapFilesLocked(@UserIdInt int userId, @NonNull ShortcutUser user,
1347 @NonNull String packageName, @NonNull File path) {
1348 final ArraySet<String> usedFiles =
Makoto Onukic51b2872016-05-04 15:24:50 -07001349 user.getPackageShortcuts(packageName).getUsedBitmapFiles();
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001350
1351 for (File child : path.listFiles()) {
1352 if (!child.isFile()) {
1353 continue;
1354 }
1355 final String name = child.getName();
1356 if (!usedFiles.contains(name)) {
1357 if (DEBUG) {
1358 Slog.d(TAG, "Removing dangling bitmap file: " + child.getAbsolutePath());
1359 }
1360 child.delete();
1361 }
1362 }
1363 }
1364
Makoto Onuki55046222016-03-08 10:49:47 -08001365 @VisibleForTesting
1366 static class FileOutputStreamWithPath extends FileOutputStream {
1367 private final File mFile;
1368
1369 public FileOutputStreamWithPath(File file) throws FileNotFoundException {
1370 super(file);
1371 mFile = file;
1372 }
1373
1374 public File getFile() {
1375 return mFile;
1376 }
1377 }
1378
1379 /**
1380 * Build the cached bitmap filename for a shortcut icon.
1381 *
1382 * The filename will be based on the ID, except certain characters will be escaped.
1383 */
Makoto Onuki55046222016-03-08 10:49:47 -08001384 FileOutputStreamWithPath openIconFileForWrite(@UserIdInt int userId, ShortcutInfo shortcut)
1385 throws IOException {
1386 final File packagePath = new File(getUserBitmapFilePath(userId),
Makoto Onuki22fcc682016-05-17 14:52:19 -07001387 shortcut.getPackage());
Makoto Onuki55046222016-03-08 10:49:47 -08001388 if (!packagePath.isDirectory()) {
1389 packagePath.mkdirs();
1390 if (!packagePath.isDirectory()) {
1391 throw new IOException("Unable to create directory " + packagePath);
1392 }
1393 SELinux.restorecon(packagePath);
1394 }
1395
1396 final String baseName = String.valueOf(injectCurrentTimeMillis());
Makoto Onukib08790c2016-06-23 14:05:46 -07001397 for (int suffix = 0; ; suffix++) {
Makoto Onuki55046222016-03-08 10:49:47 -08001398 final String filename = (suffix == 0 ? baseName : baseName + "_" + suffix) + ".png";
1399 final File file = new File(packagePath, filename);
1400 if (!file.exists()) {
1401 if (DEBUG) {
1402 Slog.d(TAG, "Saving icon to " + file.getAbsolutePath());
1403 }
1404 return new FileOutputStreamWithPath(file);
1405 }
1406 }
1407 }
1408
Makoto Onuki475c3652017-05-08 14:29:03 -07001409 void saveIconAndFixUpShortcutLocked(ShortcutInfo shortcut) {
Makoto Onuki55046222016-03-08 10:49:47 -08001410 if (shortcut.hasIconFile() || shortcut.hasIconResource()) {
1411 return;
1412 }
1413
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001414 final long token = injectClearCallingIdentity();
Makoto Onuki55046222016-03-08 10:49:47 -08001415 try {
1416 // Clear icon info on the shortcut.
Makoto Onuki475c3652017-05-08 14:29:03 -07001417 removeIconLocked(shortcut);
Makoto Onuki55046222016-03-08 10:49:47 -08001418
1419 final Icon icon = shortcut.getIcon();
1420 if (icon == null) {
1421 return; // has no icon
1422 }
Hyunyoung Song47037462017-05-08 16:51:43 -07001423 int maxIconDimension = mMaxIconDimension;
Makoto Onukiabe84422016-04-07 09:41:19 -07001424 Bitmap bitmap;
Makoto Onuki55046222016-03-08 10:49:47 -08001425 try {
1426 switch (icon.getType()) {
1427 case Icon.TYPE_RESOURCE: {
1428 injectValidateIconResPackage(shortcut, icon);
1429
1430 shortcut.setIconResourceId(icon.getResId());
1431 shortcut.addFlags(ShortcutInfo.FLAG_HAS_ICON_RES);
1432 return;
1433 }
Hyunyoung Songf281e7a2017-02-13 10:57:42 -08001434 case Icon.TYPE_BITMAP:
Makoto Onukiabe84422016-04-07 09:41:19 -07001435 bitmap = icon.getBitmap(); // Don't recycle in this case.
Makoto Onuki55046222016-03-08 10:49:47 -08001436 break;
Hyunyoung Song47037462017-05-08 16:51:43 -07001437 case Icon.TYPE_ADAPTIVE_BITMAP: {
1438 bitmap = icon.getBitmap(); // Don't recycle in this case.
1439 maxIconDimension *= (1 + 2 * AdaptiveIconDrawable.getExtraInsetFraction());
Hyunyoung Song8947f592017-05-15 10:12:11 -07001440 break;
Makoto Onuki55046222016-03-08 10:49:47 -08001441 }
Makoto Onuki55046222016-03-08 10:49:47 -08001442 default:
1443 // This shouldn't happen because we've already validated the icon, but
1444 // just in case.
1445 throw ShortcutInfo.getInvalidIconException();
1446 }
Makoto Onuki475c3652017-05-08 14:29:03 -07001447 mShortcutBitmapSaver.saveBitmapLocked(shortcut,
Hyunyoung Song47037462017-05-08 16:51:43 -07001448 maxIconDimension, mIconPersistFormat, mIconPersistQuality);
Makoto Onuki55046222016-03-08 10:49:47 -08001449 } finally {
Makoto Onuki55046222016-03-08 10:49:47 -08001450 // Once saved, we won't use the original icon information, so null it out.
1451 shortcut.clearIcon();
1452 }
1453 } finally {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001454 injectRestoreCallingIdentity(token);
Makoto Onuki55046222016-03-08 10:49:47 -08001455 }
1456 }
1457
1458 // Unfortunately we can't do this check in unit tests because we fake creator package names,
1459 // so override in unit tests.
1460 // TODO CTS this case.
1461 void injectValidateIconResPackage(ShortcutInfo shortcut, Icon icon) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07001462 if (!shortcut.getPackage().equals(icon.getResPackage())) {
Makoto Onuki55046222016-03-08 10:49:47 -08001463 throw new IllegalArgumentException(
1464 "Icon resource must reside in shortcut owner package");
1465 }
1466 }
1467
Makoto Onuki55046222016-03-08 10:49:47 -08001468 static Bitmap shrinkBitmap(Bitmap in, int maxSize) {
1469 // Original width/height.
1470 final int ow = in.getWidth();
1471 final int oh = in.getHeight();
1472 if ((ow <= maxSize) && (oh <= maxSize)) {
1473 if (DEBUG) {
1474 Slog.d(TAG, String.format("Icon size %dx%d, no need to shrink", ow, oh));
1475 }
1476 return in;
1477 }
1478 final int longerDimension = Math.max(ow, oh);
1479
1480 // New width and height.
1481 final int nw = ow * maxSize / longerDimension;
1482 final int nh = oh * maxSize / longerDimension;
1483 if (DEBUG) {
1484 Slog.d(TAG, String.format("Icon size %dx%d, shrinking to %dx%d",
1485 ow, oh, nw, nh));
1486 }
1487
1488 final Bitmap scaledBitmap = Bitmap.createBitmap(nw, nh, Bitmap.Config.ARGB_8888);
1489 final Canvas c = new Canvas(scaledBitmap);
1490
1491 final RectF dst = new RectF(0, 0, nw, nh);
1492
1493 c.drawBitmap(in, /*src=*/ null, dst, /* paint =*/ null);
1494
Makoto Onuki55046222016-03-08 10:49:47 -08001495 return scaledBitmap;
1496 }
1497
Makoto Onuki157b1622016-06-02 16:13:10 -07001498 /**
1499 * For a shortcut, update all resource names from resource IDs, and also update all
1500 * resource-based strings.
1501 */
1502 void fixUpShortcutResourceNamesAndValues(ShortcutInfo si) {
1503 final Resources publisherRes = injectGetResourcesForApplicationAsUser(
1504 si.getPackage(), si.getUserId());
1505 if (publisherRes != null) {
Makoto Onuki84d59342018-02-02 09:22:38 -08001506 final long start = getStatStartTime();
Makoto Onuki157b1622016-06-02 16:13:10 -07001507 try {
1508 si.lookupAndFillInResourceNames(publisherRes);
1509 } finally {
1510 logDurationStat(Stats.RESOURCE_NAME_LOOKUP, start);
1511 }
1512 si.resolveResourceStrings(publisherRes);
1513 }
1514 }
1515
Makoto Onuki55046222016-03-08 10:49:47 -08001516 // === Caller validation ===
1517
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001518 private boolean isCallerSystem() {
1519 final int callingUid = injectBinderCallingUid();
Makoto Onukib08790c2016-06-23 14:05:46 -07001520 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001521 }
1522
1523 private boolean isCallerShell() {
1524 final int callingUid = injectBinderCallingUid();
1525 return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
1526 }
1527
1528 private void enforceSystemOrShell() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001529 if (!(isCallerSystem() || isCallerShell())) {
1530 throw new SecurityException("Caller must be system or shell");
1531 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001532 }
1533
1534 private void enforceShell() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001535 if (!isCallerShell()) {
1536 throw new SecurityException("Caller must be shell");
1537 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001538 }
1539
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001540 private void enforceSystem() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001541 if (!isCallerSystem()) {
1542 throw new SecurityException("Caller must be system");
1543 }
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001544 }
1545
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001546 private void enforceResetThrottlingPermission() {
1547 if (isCallerSystem()) {
1548 return;
1549 }
Makoto Onuki76269922016-07-15 14:58:54 -07001550 enforceCallingOrSelfPermission(
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001551 android.Manifest.permission.RESET_SHORTCUT_MANAGER_THROTTLING, null);
1552 }
1553
Makoto Onuki76269922016-07-15 14:58:54 -07001554 private void enforceCallingOrSelfPermission(
1555 @NonNull String permission, @Nullable String message) {
1556 if (isCallerSystem()) {
1557 return;
1558 }
1559 injectEnforceCallingPermission(permission, message);
1560 }
1561
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001562 /**
1563 * Somehow overriding ServiceContext.enforceCallingPermission() in the unit tests would confuse
1564 * mockito. So instead we extracted it here and override it in the tests.
1565 */
1566 @VisibleForTesting
1567 void injectEnforceCallingPermission(
1568 @NonNull String permission, @Nullable String message) {
1569 mContext.enforceCallingPermission(permission, message);
1570 }
1571
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001572 private void verifyCaller(@NonNull String packageName, @UserIdInt int userId) {
1573 Preconditions.checkStringNotEmpty(packageName, "packageName");
1574
1575 if (isCallerSystem()) {
1576 return; // no check
1577 }
1578
1579 final int callingUid = injectBinderCallingUid();
1580
1581 // Otherwise, make sure the arguments are valid.
1582 if (UserHandle.getUserId(callingUid) != userId) {
1583 throw new SecurityException("Invalid user-ID");
1584 }
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08001585 if (injectGetPackageUid(packageName, userId) != callingUid) {
1586 throw new SecurityException("Calling package name mismatch");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001587 }
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08001588 Preconditions.checkState(!isEphemeralApp(packageName, userId),
1589 "Ephemeral apps can't use ShortcutManager");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001590 }
1591
Makoto Onukia19fb232018-06-12 13:01:42 -07001592 private void verifyShortcutInfoPackage(String callerPackage, ShortcutInfo si) {
1593 if (si == null) {
1594 return;
1595 }
1596 if (!Objects.equals(callerPackage, si.getPackage())) {
1597 android.util.EventLog.writeEvent(0x534e4554, "109824443", -1, "");
1598 throw new SecurityException("Shortcut package name mismatch");
1599 }
1600 }
1601
1602 private void verifyShortcutInfoPackages(
1603 String callerPackage, List<ShortcutInfo> list) {
1604 final int size = list.size();
1605 for (int i = 0; i < size; i++) {
1606 verifyShortcutInfoPackage(callerPackage, list.get(i));
1607 }
1608 }
1609
Makoto Onuki157b1622016-06-02 16:13:10 -07001610 // Overridden in unit tests to execute r synchronously.
1611 void injectPostToHandler(Runnable r) {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001612 mHandler.post(r);
1613 }
1614
Makoto Onuki085a05c2016-08-19 11:39:29 -07001615 void injectRunOnNewThread(Runnable r) {
1616 new Thread(r).start();
1617 }
1618
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001619 /**
Makoto Onuki7001a612016-05-27 13:24:28 -07001620 * @throws IllegalArgumentException if {@code numShortcuts} is bigger than
Makoto Onukib08790c2016-06-23 14:05:46 -07001621 * {@link #getMaxActivityShortcuts()}.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001622 */
Makoto Onuki7001a612016-05-27 13:24:28 -07001623 void enforceMaxActivityShortcuts(int numShortcuts) {
Makoto Onukib5a012f2016-06-21 11:13:53 -07001624 if (numShortcuts > mMaxShortcuts) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001625 throw new IllegalArgumentException("Max number of dynamic shortcuts exceeded");
1626 }
1627 }
1628
1629 /**
Makoto Onuki7001a612016-05-27 13:24:28 -07001630 * Return the max number of dynamic + manifest shortcuts for each launcher icon.
1631 */
1632 int getMaxActivityShortcuts() {
Makoto Onukib5a012f2016-06-21 11:13:53 -07001633 return mMaxShortcuts;
Makoto Onuki7001a612016-05-27 13:24:28 -07001634 }
1635
1636 /**
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001637 * - Sends a notification to LauncherApps
1638 * - Write to file
1639 */
Makoto Onuki39686e82016-04-13 18:03:00 -07001640 void packageShortcutsChanged(@NonNull String packageName, @UserIdInt int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001641 notifyListeners(packageName, userId);
1642 scheduleSaveUser(userId);
1643 }
1644
1645 private void notifyListeners(@NonNull String packageName, @UserIdInt int userId) {
Makoto Onuki82fb2eb2017-03-31 16:58:26 -07001646 if (DEBUG) {
1647 Slog.d(TAG, String.format(
1648 "Shortcut changes: package=%s, user=%d", packageName, userId));
1649 }
Makoto Onuki157b1622016-06-02 16:13:10 -07001650 injectPostToHandler(() -> {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001651 try {
1652 final ArrayList<ShortcutChangeListener> copy;
1653 synchronized (mLock) {
1654 if (!isUserUnlockedL(userId)) {
1655 return;
1656 }
1657
1658 copy = new ArrayList<>(mListeners);
1659 }
1660 // Note onShortcutChanged() needs to be called with the system service permissions.
1661 for (int i = copy.size() - 1; i >= 0; i--) {
1662 copy.get(i).onShortcutChanged(packageName, userId);
1663 }
1664 } catch (Exception ignore) {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001665 }
1666 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001667 }
1668
1669 /**
1670 * Clean up / validate an incoming shortcut.
1671 * - Make sure all mandatory fields are set.
1672 * - Make sure the intent's extras are persistable, and them to set
Makoto Onuki0eed4412016-07-21 11:21:59 -07001673 * {@link ShortcutInfo#mIntentPersistableExtrases}. Also clear its extras.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001674 * - Clear flags.
1675 */
Makoto Onuki2d895c32016-12-02 15:48:40 -08001676 private void fixUpIncomingShortcutInfo(@NonNull ShortcutInfo shortcut, boolean forUpdate,
1677 boolean forPinRequest) {
Makoto Onukibf563b62017-05-04 10:25:30 -07001678 if (shortcut.isReturnedByServer()) {
1679 Log.w(TAG,
1680 "Re-publishing ShortcutInfo returned by server is not supported."
1681 + " Some information such as icon may lost from shortcut.");
1682 }
Daulet Zhanguzin82adfcb2020-01-02 17:31:40 +00001683 Objects.requireNonNull(shortcut, "Null shortcut detected");
Makoto Onuki255461f2017-01-10 11:47:25 -08001684 if (shortcut.getActivity() != null) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001685 Preconditions.checkState(
Makoto Onuki22fcc682016-05-17 14:52:19 -07001686 shortcut.getPackage().equals(shortcut.getActivity().getPackageName()),
Makoto Onukib08790c2016-06-23 14:05:46 -07001687 "Cannot publish shortcut: activity " + shortcut.getActivity() + " does not"
1688 + " belong to package " + shortcut.getPackage());
Makoto Onuki13260b6ff2016-07-13 18:03:13 -07001689 Preconditions.checkState(
1690 injectIsMainActivity(shortcut.getActivity(), shortcut.getUserId()),
1691 "Cannot publish shortcut: activity " + shortcut.getActivity() + " is not"
1692 + " main activity");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001693 }
1694
Makoto Onuki55046222016-03-08 10:49:47 -08001695 if (!forUpdate) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08001696 shortcut.enforceMandatoryFields(/* forPinned= */ forPinRequest);
1697 if (!forPinRequest) {
Makoto Onuki255461f2017-01-10 11:47:25 -08001698 Preconditions.checkState(shortcut.getActivity() != null,
1699 "Cannot publish shortcut: target activity is not set");
Makoto Onuki2d895c32016-12-02 15:48:40 -08001700 }
Makoto Onuki55046222016-03-08 10:49:47 -08001701 }
1702 if (shortcut.getIcon() != null) {
1703 ShortcutInfo.validateIcon(shortcut.getIcon());
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001704 }
1705
Makoto Onukide667372016-03-15 14:29:20 -07001706 shortcut.replaceFlags(0);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001707 }
1708
Makoto Onuki2d895c32016-12-02 15:48:40 -08001709 private void fixUpIncomingShortcutInfo(@NonNull ShortcutInfo shortcut, boolean forUpdate) {
1710 fixUpIncomingShortcutInfo(shortcut, forUpdate, /*forPinRequest=*/ false);
1711 }
1712
1713 public void validateShortcutForPinRequest(@NonNull ShortcutInfo shortcut) {
1714 fixUpIncomingShortcutInfo(shortcut, /* forUpdate= */ false, /*forPinRequest=*/ true);
1715 }
1716
Makoto Onukib08790c2016-06-23 14:05:46 -07001717 /**
1718 * When a shortcut has no target activity, set the default one from the package.
1719 */
1720 private void fillInDefaultActivity(List<ShortcutInfo> shortcuts) {
Makoto Onukib08790c2016-06-23 14:05:46 -07001721 ComponentName defaultActivity = null;
1722 for (int i = shortcuts.size() - 1; i >= 0; i--) {
1723 final ShortcutInfo si = shortcuts.get(i);
1724 if (si.getActivity() == null) {
1725 if (defaultActivity == null) {
1726 defaultActivity = injectGetDefaultMainActivity(
1727 si.getPackage(), si.getUserId());
1728 Preconditions.checkState(defaultActivity != null,
1729 "Launcher activity not found for package " + si.getPackage());
1730 }
1731 si.setActivity(defaultActivity);
1732 }
1733 }
1734 }
1735
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001736 private void assignImplicitRanks(List<ShortcutInfo> shortcuts) {
1737 for (int i = shortcuts.size() - 1; i >= 0; i--) {
1738 shortcuts.get(i).setImplicitRank(i);
1739 }
1740 }
1741
Makoto Onukibf563b62017-05-04 10:25:30 -07001742 private List<ShortcutInfo> setReturnedByServer(List<ShortcutInfo> shortcuts) {
1743 for (int i = shortcuts.size() - 1; i >= 0; i--) {
1744 shortcuts.get(i).setReturnedByServer();
1745 }
1746 return shortcuts;
1747 }
1748
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001749 // === APIs ===
1750
1751 @Override
1752 public boolean setDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1753 @UserIdInt int userId) {
1754 verifyCaller(packageName, userId);
1755
1756 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
Makoto Onukia19fb232018-06-12 13:01:42 -07001757 verifyShortcutInfoPackages(packageName, newShortcuts);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001758 final int size = newShortcuts.size();
1759
Makoto Onuki7d0fa812018-02-21 11:24:43 -08001760 final boolean unlimited = injectHasUnlimitedShortcutsApiCallsPermission(
1761 injectBinderCallingPid(), injectBinderCallingUid());
1762
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001763 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001764 throwIfUserLockedL(userId);
1765
Makoto Onukic8c33292016-09-12 16:36:59 -07001766 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001767
Makoto Onukia4f89b12017-10-05 10:37:55 -07001768 ps.ensureImmutableShortcutsNotIncluded(newShortcuts, /*ignoreInvisible=*/ true);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001769
Makoto Onukib08790c2016-06-23 14:05:46 -07001770 fillInDefaultActivity(newShortcuts);
1771
Makoto Onuki7001a612016-05-27 13:24:28 -07001772 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_SET);
1773
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001774 // Throttling.
Makoto Onuki7d0fa812018-02-21 11:24:43 -08001775 if (!ps.tryApiCall(unlimited)) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001776 return false;
1777 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001778
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001779 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1780 ps.clearAllImplicitRanks();
1781 assignImplicitRanks(newShortcuts);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001782
Makoto Onukidf6da042016-06-16 09:51:40 -07001783 for (int i = 0; i < size; i++) {
1784 fixUpIncomingShortcutInfo(newShortcuts.get(i), /* forUpdate= */ false);
1785 }
1786
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001787 // First, remove all un-pinned; dynamic shortcuts
Makoto Onukia4f89b12017-10-05 10:37:55 -07001788 ps.deleteAllDynamicShortcuts(/*ignoreInvisible=*/ true);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001789
1790 // Then, add/update all. We need to make sure to take over "pinned" flag.
1791 for (int i = 0; i < size; i++) {
1792 final ShortcutInfo newShortcut = newShortcuts.get(i);
Makoto Onukia4f89b12017-10-05 10:37:55 -07001793 ps.addOrReplaceDynamicShortcut(newShortcut);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001794 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001795
1796 // Lastly, adjust the ranks.
1797 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001798 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001799 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001800
1801 verifyStates();
1802
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001803 return true;
1804 }
1805
1806 @Override
1807 public boolean updateShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1808 @UserIdInt int userId) {
1809 verifyCaller(packageName, userId);
1810
1811 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
Makoto Onukia19fb232018-06-12 13:01:42 -07001812 verifyShortcutInfoPackages(packageName, newShortcuts);
Makoto Onuki55046222016-03-08 10:49:47 -08001813 final int size = newShortcuts.size();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001814
Makoto Onuki7d0fa812018-02-21 11:24:43 -08001815 final boolean unlimited = injectHasUnlimitedShortcutsApiCallsPermission(
1816 injectBinderCallingPid(), injectBinderCallingUid());
1817
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001818 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001819 throwIfUserLockedL(userId);
1820
Makoto Onukic8c33292016-09-12 16:36:59 -07001821 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001822
Makoto Onukia4f89b12017-10-05 10:37:55 -07001823 ps.ensureImmutableShortcutsNotIncluded(newShortcuts, /*ignoreInvisible=*/ true);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001824
Makoto Onukib08790c2016-06-23 14:05:46 -07001825 // For update, don't fill in the default activity. Having null activity means
1826 // "don't update the activity" here.
1827
Makoto Onuki7001a612016-05-27 13:24:28 -07001828 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_UPDATE);
1829
Makoto Onuki55046222016-03-08 10:49:47 -08001830 // Throttling.
Makoto Onuki7d0fa812018-02-21 11:24:43 -08001831 if (!ps.tryApiCall(unlimited)) {
Makoto Onuki55046222016-03-08 10:49:47 -08001832 return false;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001833 }
1834
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001835 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1836 ps.clearAllImplicitRanks();
1837 assignImplicitRanks(newShortcuts);
1838
Makoto Onuki55046222016-03-08 10:49:47 -08001839 for (int i = 0; i < size; i++) {
1840 final ShortcutInfo source = newShortcuts.get(i);
1841 fixUpIncomingShortcutInfo(source, /* forUpdate= */ true);
1842
1843 final ShortcutInfo target = ps.findShortcutById(source.getId());
Makoto Onukia4f89b12017-10-05 10:37:55 -07001844
1845 // Invisible shortcuts can't be updated.
1846 if (target == null || !target.isVisibleToPublisher()) {
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001847 continue;
1848 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07001849
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001850 if (target.isEnabled() != source.isEnabled()) {
1851 Slog.w(TAG,
1852 "ShortcutInfo.enabled cannot be changed with updateShortcuts()");
1853 }
Makoto Onuki55046222016-03-08 10:49:47 -08001854
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001855 // When updating the rank, we need to insert between existing ranks, so set
1856 // this setRankChanged, and also copy the implicit rank fo adjustRanks().
1857 if (source.hasRank()) {
1858 target.setRankChanged();
1859 target.setImplicitRank(source.getImplicitRank());
1860 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07001861
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001862 final boolean replacingIcon = (source.getIcon() != null);
1863 if (replacingIcon) {
Makoto Onuki475c3652017-05-08 14:29:03 -07001864 removeIconLocked(target);
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001865 }
Makoto Onuki55046222016-03-08 10:49:47 -08001866
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001867 // Note copyNonNullFieldsFrom() does the "updatable with?" check too.
1868 target.copyNonNullFieldsFrom(source);
1869 target.setTimestamp(injectCurrentTimeMillis());
1870
1871 if (replacingIcon) {
Makoto Onuki475c3652017-05-08 14:29:03 -07001872 saveIconAndFixUpShortcutLocked(target);
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001873 }
1874
1875 // When we're updating any resource related fields, re-extract the res names and
1876 // the values.
1877 if (replacingIcon || source.hasStringResources()) {
1878 fixUpShortcutResourceNamesAndValues(target);
Makoto Onuki55046222016-03-08 10:49:47 -08001879 }
1880 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001881
1882 // Lastly, adjust the ranks.
1883 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001884 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001885 packageShortcutsChanged(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001886
Makoto Onuki7001a612016-05-27 13:24:28 -07001887 verifyStates();
1888
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001889 return true;
1890 }
1891
1892 @Override
Makoto Onukia4f89b12017-10-05 10:37:55 -07001893 public boolean addDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001894 @UserIdInt int userId) {
1895 verifyCaller(packageName, userId);
1896
Makoto Onukib6d35232016-04-04 15:57:17 -07001897 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
Makoto Onukia19fb232018-06-12 13:01:42 -07001898 verifyShortcutInfoPackages(packageName, newShortcuts);
Makoto Onukib6d35232016-04-04 15:57:17 -07001899 final int size = newShortcuts.size();
1900
Makoto Onuki7d0fa812018-02-21 11:24:43 -08001901 final boolean unlimited = injectHasUnlimitedShortcutsApiCallsPermission(
1902 injectBinderCallingPid(), injectBinderCallingUid());
1903
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001904 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001905 throwIfUserLockedL(userId);
1906
Makoto Onukic8c33292016-09-12 16:36:59 -07001907 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001908
Makoto Onukia4f89b12017-10-05 10:37:55 -07001909 ps.ensureImmutableShortcutsNotIncluded(newShortcuts, /*ignoreInvisible=*/ true);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001910
Makoto Onukib08790c2016-06-23 14:05:46 -07001911 fillInDefaultActivity(newShortcuts);
1912
Makoto Onuki7001a612016-05-27 13:24:28 -07001913 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_ADD);
1914
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001915 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1916 ps.clearAllImplicitRanks();
1917 assignImplicitRanks(newShortcuts);
1918
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001919 // Throttling.
Makoto Onuki7d0fa812018-02-21 11:24:43 -08001920 if (!ps.tryApiCall(unlimited)) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001921 return false;
1922 }
Makoto Onukib6d35232016-04-04 15:57:17 -07001923 for (int i = 0; i < size; i++) {
1924 final ShortcutInfo newShortcut = newShortcuts.get(i);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001925
Makoto Onukib6d35232016-04-04 15:57:17 -07001926 // Validate the shortcut.
1927 fixUpIncomingShortcutInfo(newShortcut, /* forUpdate= */ false);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001928
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001929 // When ranks are changing, we need to insert between ranks, so set the
1930 // "rank changed" flag.
1931 newShortcut.setRankChanged();
1932
Makoto Onukib6d35232016-04-04 15:57:17 -07001933 // Add it.
Makoto Onukia4f89b12017-10-05 10:37:55 -07001934 ps.addOrReplaceDynamicShortcut(newShortcut);
Makoto Onukib6d35232016-04-04 15:57:17 -07001935 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001936
1937 // Lastly, adjust the ranks.
1938 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001939 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001940 packageShortcutsChanged(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001941
Makoto Onuki7001a612016-05-27 13:24:28 -07001942 verifyStates();
1943
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001944 return true;
1945 }
1946
1947 @Override
Makoto Onuki2d895c32016-12-02 15:48:40 -08001948 public boolean requestPinShortcut(String packageName, ShortcutInfo shortcut,
1949 IntentSender resultIntent, int userId) {
Daulet Zhanguzin82adfcb2020-01-02 17:31:40 +00001950 Objects.requireNonNull(shortcut);
Makoto Onuki2d895c32016-12-02 15:48:40 -08001951 Preconditions.checkArgument(shortcut.isEnabled(), "Shortcut must be enabled");
Sunny Goyal4ad6b572017-02-28 11:11:51 -08001952 return requestPinItem(packageName, userId, shortcut, null, null, resultIntent);
Sunny Goyal87a563e2017-01-01 19:42:45 -08001953 }
1954
Sunny Goyala6be88a2017-01-12 16:27:58 -08001955 @Override
1956 public Intent createShortcutResultIntent(String packageName, ShortcutInfo shortcut, int userId)
1957 throws RemoteException {
Daulet Zhanguzin82adfcb2020-01-02 17:31:40 +00001958 Objects.requireNonNull(shortcut);
Sunny Goyala6be88a2017-01-12 16:27:58 -08001959 Preconditions.checkArgument(shortcut.isEnabled(), "Shortcut must be enabled");
1960 verifyCaller(packageName, userId);
Makoto Onukia19fb232018-06-12 13:01:42 -07001961 verifyShortcutInfoPackage(packageName, shortcut);
Sunny Goyala6be88a2017-01-12 16:27:58 -08001962
1963 final Intent ret;
1964 synchronized (mLock) {
1965 throwIfUserLockedL(userId);
1966
1967 // Send request to the launcher, if supported.
1968 ret = mShortcutRequestPinProcessor.createShortcutResultIntent(shortcut, userId);
1969 }
1970
1971 verifyStates();
1972 return ret;
1973 }
1974
Sunny Goyal87a563e2017-01-01 19:42:45 -08001975 /**
1976 * Handles {@link #requestPinShortcut} and {@link ShortcutServiceInternal#requestPinAppWidget}.
1977 * After validating the caller, it passes the request to {@link #mShortcutRequestPinProcessor}.
1978 * Either {@param shortcut} or {@param appWidget} should be non-null.
1979 */
Sunny Goyal4ad6b572017-02-28 11:11:51 -08001980 private boolean requestPinItem(String packageName, int userId, ShortcutInfo shortcut,
1981 AppWidgetProviderInfo appWidget, Bundle extras, IntentSender resultIntent) {
Sunny Goyal87a563e2017-01-01 19:42:45 -08001982 verifyCaller(packageName, userId);
Makoto Onukia19fb232018-06-12 13:01:42 -07001983 verifyShortcutInfoPackage(packageName, shortcut);
Makoto Onuki2d895c32016-12-02 15:48:40 -08001984
1985 final boolean ret;
1986 synchronized (mLock) {
1987 throwIfUserLockedL(userId);
1988
Makoto Onukia01f4f02016-12-15 15:58:41 -08001989 Preconditions.checkState(isUidForegroundLocked(injectBinderCallingUid()),
Makoto Onuki255461f2017-01-10 11:47:25 -08001990 "Calling application must have a foreground activity or a foreground service");
Makoto Onuki2d895c32016-12-02 15:48:40 -08001991
Makoto Onukia4f89b12017-10-05 10:37:55 -07001992 // If it's a pin shortcut request, and there's already a shortcut with the same ID
1993 // that's not visible to the caller (i.e. restore-blocked; meaning it's pinned by
1994 // someone already), then we just replace the existing one with this new one,
1995 // and then proceed the rest of the process.
1996 if (shortcut != null) {
1997 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(
1998 packageName, userId);
1999 final String id = shortcut.getId();
2000 if (ps.isShortcutExistsAndInvisibleToPublisher(id)) {
2001
2002 ps.updateInvisibleShortcutForPinRequestWith(shortcut);
2003
2004 packageShortcutsChanged(packageName, userId);
2005 }
2006 }
2007
Makoto Onuki2d895c32016-12-02 15:48:40 -08002008 // Send request to the launcher, if supported.
Sunny Goyal4ad6b572017-02-28 11:11:51 -08002009 ret = mShortcutRequestPinProcessor.requestPinItemLocked(shortcut, appWidget, extras,
2010 userId, resultIntent);
Makoto Onuki2d895c32016-12-02 15:48:40 -08002011 }
2012
2013 verifyStates();
2014
2015 return ret;
2016 }
2017
2018 @Override
Makoto Onuki20c95f82016-05-11 16:51:01 -07002019 public void disableShortcuts(String packageName, List shortcutIds,
Makoto Onukid6880792016-06-29 13:37:43 -07002020 CharSequence disabledMessage, int disabledMessageResId, @UserIdInt int userId) {
Makoto Onuki20c95f82016-05-11 16:51:01 -07002021 verifyCaller(packageName, userId);
Daulet Zhanguzin82adfcb2020-01-02 17:31:40 +00002022 Objects.requireNonNull(shortcutIds, "shortcutIds must be provided");
Makoto Onuki20c95f82016-05-11 16:51:01 -07002023
2024 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002025 throwIfUserLockedL(userId);
2026
Makoto Onukic8c33292016-09-12 16:36:59 -07002027 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002028
Makoto Onukia4f89b12017-10-05 10:37:55 -07002029 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds,
2030 /*ignoreInvisible=*/ true);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002031
Makoto Onukid6880792016-06-29 13:37:43 -07002032 final String disabledMessageString =
2033 (disabledMessage == null) ? null : disabledMessage.toString();
2034
Makoto Onuki22fcc682016-05-17 14:52:19 -07002035 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
Makoto Onukia4f89b12017-10-05 10:37:55 -07002036 final String id = Preconditions.checkStringNotEmpty((String) shortcutIds.get(i));
2037 if (!ps.isShortcutExistsAndVisibleToPublisher(id)) {
2038 continue;
2039 }
2040 ps.disableWithId(id,
Makoto Onukid6880792016-06-29 13:37:43 -07002041 disabledMessageString, disabledMessageResId,
Makoto Onukia4f89b12017-10-05 10:37:55 -07002042 /* overrideImmutable=*/ false, /*ignoreInvisible=*/ true,
2043 ShortcutInfo.DISABLED_REASON_BY_APP);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002044 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002045
2046 // We may have removed dynamic shortcuts which may have left a gap, so adjust the ranks.
2047 ps.adjustRanks();
Makoto Onuki22fcc682016-05-17 14:52:19 -07002048 }
2049 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07002050
2051 verifyStates();
Makoto Onuki22fcc682016-05-17 14:52:19 -07002052 }
2053
2054 @Override
2055 public void enableShortcuts(String packageName, List shortcutIds, @UserIdInt int userId) {
2056 verifyCaller(packageName, userId);
Daulet Zhanguzin82adfcb2020-01-02 17:31:40 +00002057 Objects.requireNonNull(shortcutIds, "shortcutIds must be provided");
Makoto Onuki22fcc682016-05-17 14:52:19 -07002058
2059 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002060 throwIfUserLockedL(userId);
2061
Makoto Onukic8c33292016-09-12 16:36:59 -07002062 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002063
Makoto Onukia4f89b12017-10-05 10:37:55 -07002064 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds,
2065 /*ignoreInvisible=*/ true);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002066
2067 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
Makoto Onukia4f89b12017-10-05 10:37:55 -07002068 final String id = Preconditions.checkStringNotEmpty((String) shortcutIds.get(i));
2069 if (!ps.isShortcutExistsAndVisibleToPublisher(id)) {
2070 continue;
2071 }
2072 ps.enableWithId(id);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002073 }
Makoto Onuki20c95f82016-05-11 16:51:01 -07002074 }
2075 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07002076
2077 verifyStates();
Makoto Onuki20c95f82016-05-11 16:51:01 -07002078 }
2079
2080 @Override
Makoto Onukib6d35232016-04-04 15:57:17 -07002081 public void removeDynamicShortcuts(String packageName, List shortcutIds,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002082 @UserIdInt int userId) {
2083 verifyCaller(packageName, userId);
Daulet Zhanguzin82adfcb2020-01-02 17:31:40 +00002084 Objects.requireNonNull(shortcutIds, "shortcutIds must be provided");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002085
2086 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002087 throwIfUserLockedL(userId);
2088
Makoto Onukic8c33292016-09-12 16:36:59 -07002089 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002090
Makoto Onukia4f89b12017-10-05 10:37:55 -07002091 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds,
2092 /*ignoreInvisible=*/ true);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002093
Makoto Onukib6d35232016-04-04 15:57:17 -07002094 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
Makoto Onukia4f89b12017-10-05 10:37:55 -07002095 final String id = Preconditions.checkStringNotEmpty((String) shortcutIds.get(i));
2096 if (!ps.isShortcutExistsAndVisibleToPublisher(id)) {
2097 continue;
2098 }
2099 ps.deleteDynamicWithId(id, /*ignoreInvisible=*/ true);
Makoto Onukib6d35232016-04-04 15:57:17 -07002100 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002101
2102 // We may have removed dynamic shortcuts which may have left a gap, so adjust the ranks.
2103 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002104 }
Makoto Onuki39686e82016-04-13 18:03:00 -07002105 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07002106
2107 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002108 }
2109
2110 @Override
Makoto Onukib6d35232016-04-04 15:57:17 -07002111 public void removeAllDynamicShortcuts(String packageName, @UserIdInt int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002112 verifyCaller(packageName, userId);
2113
2114 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002115 throwIfUserLockedL(userId);
2116
Makoto Onukic8c33292016-09-12 16:36:59 -07002117 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onukia4f89b12017-10-05 10:37:55 -07002118 ps.deleteAllDynamicShortcuts(/*ignoreInvisible=*/ true);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002119 }
Makoto Onuki39686e82016-04-13 18:03:00 -07002120 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07002121
2122 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002123 }
2124
2125 @Override
Mehdi Alizadeh505fb762020-01-21 17:26:24 -08002126 public void removeLongLivedShortcuts(String packageName, List shortcutIds,
2127 @UserIdInt int userId) {
2128 verifyCaller(packageName, userId);
2129 Objects.requireNonNull(shortcutIds, "shortcutIds must be provided");
2130
2131 synchronized (mLock) {
2132 throwIfUserLockedL(userId);
2133
2134 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
2135
2136 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds,
2137 /*ignoreInvisible=*/ true);
2138
2139 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
2140 final String id = Preconditions.checkStringNotEmpty((String) shortcutIds.get(i));
2141 ps.deleteLongLivedWithId(id, /*ignoreInvisible=*/ true);
2142 }
2143
2144 // We may have removed dynamic shortcuts which may have left a gap, so adjust the ranks.
2145 ps.adjustRanks();
2146 }
2147 packageShortcutsChanged(packageName, userId);
2148
2149 verifyStates();
2150 }
2151
2152 @Override
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002153 public ParceledListSlice<ShortcutInfo> getDynamicShortcuts(String packageName,
2154 @UserIdInt int userId) {
2155 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002156
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002157 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002158 throwIfUserLockedL(userId);
2159
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002160 return getShortcutsWithQueryLocked(
2161 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
Makoto Onukia4f89b12017-10-05 10:37:55 -07002162 ShortcutInfo::isDynamicVisible);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002163 }
2164 }
2165
2166 @Override
Makoto Onuki22fcc682016-05-17 14:52:19 -07002167 public ParceledListSlice<ShortcutInfo> getManifestShortcuts(String packageName,
2168 @UserIdInt int userId) {
2169 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002170
Makoto Onuki22fcc682016-05-17 14:52:19 -07002171 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002172 throwIfUserLockedL(userId);
2173
Makoto Onuki22fcc682016-05-17 14:52:19 -07002174 return getShortcutsWithQueryLocked(
2175 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
Makoto Onukia4f89b12017-10-05 10:37:55 -07002176 ShortcutInfo::isManifestVisible);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002177 }
2178 }
2179
2180 @Override
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002181 public ParceledListSlice<ShortcutInfo> getPinnedShortcuts(String packageName,
2182 @UserIdInt int userId) {
2183 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002184
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002185 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002186 throwIfUserLockedL(userId);
2187
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002188 return getShortcutsWithQueryLocked(
2189 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
Makoto Onukia4f89b12017-10-05 10:37:55 -07002190 ShortcutInfo::isPinnedVisible);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002191 }
2192 }
2193
Mehdi Alizadeh406e8b32018-12-11 18:21:49 -08002194 @Override
Mehdi Alizadeh505fb762020-01-21 17:26:24 -08002195 public ParceledListSlice<ShortcutInfo> getShortcuts(String packageName,
2196 @ShortcutManager.ShortcutMatchFlags int matchFlags, @UserIdInt int userId) {
2197 verifyCaller(packageName, userId);
2198
2199 synchronized (mLock) {
2200 throwIfUserLockedL(userId);
2201
2202 final boolean matchDynamic = (matchFlags & ShortcutManager.FLAG_MATCH_DYNAMIC) != 0;
2203 final boolean matchPinned = (matchFlags & ShortcutManager.FLAG_MATCH_PINNED) != 0;
2204 final boolean matchManifest = (matchFlags & ShortcutManager.FLAG_MATCH_MANIFEST) != 0;
2205 final boolean matchCached = (matchFlags & ShortcutManager.FLAG_MATCH_CACHED) != 0;
2206
2207 final int shortcutFlags = (matchDynamic ? ShortcutInfo.FLAG_DYNAMIC : 0)
2208 | (matchPinned ? ShortcutInfo.FLAG_PINNED : 0)
2209 | (matchManifest ? ShortcutInfo.FLAG_MANIFEST : 0)
2210 | (matchCached ? ShortcutInfo.FLAG_CACHED : 0);
2211
2212 return getShortcutsWithQueryLocked(
2213 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
2214 (ShortcutInfo si) ->
2215 si.isVisibleToPublisher() && (si.getFlags() & shortcutFlags) != 0);
2216 }
2217 }
2218
2219 @Override
Mehdi Alizadeh406e8b32018-12-11 18:21:49 -08002220 public ParceledListSlice<ShortcutManager.ShareShortcutInfo> getShareTargets(String packageName,
2221 IntentFilter filter, @UserIdInt int userId) {
2222 verifyCaller(packageName, userId);
Mehdi Alizadehc86dd1f2019-01-25 16:59:54 -08002223 enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APP_PREDICTIONS,
2224 "getShareTargets");
Mehdi Alizadeh406e8b32018-12-11 18:21:49 -08002225
2226 synchronized (mLock) {
2227 throwIfUserLockedL(userId);
2228
2229 final List<ShortcutManager.ShareShortcutInfo> shortcutInfoList = new ArrayList<>();
2230
2231 final ShortcutUser user = getUserShortcutsLocked(userId);
2232 user.forAllPackages(p -> shortcutInfoList.addAll(p.getMatchingShareTargets(filter)));
2233
2234 return new ParceledListSlice<>(shortcutInfoList);
2235 }
2236 }
2237
Mehdi Alizadeh85fd3d52019-01-23 12:49:53 -08002238 @Override
2239 public boolean hasShareTargets(String packageName, String packageToCheck,
2240 @UserIdInt int userId) {
2241 verifyCaller(packageName, userId);
Mehdi Alizadeh627d4db2019-02-04 13:52:03 -08002242 enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APP_PREDICTIONS,
2243 "hasShareTargets");
Mehdi Alizadeh85fd3d52019-01-23 12:49:53 -08002244
2245 synchronized (mLock) {
2246 throwIfUserLockedL(userId);
2247
2248 return getPackageShortcutsLocked(packageToCheck, userId).hasShareTargets();
2249 }
2250 }
2251
Andreas Gampea36dc622018-02-05 17:19:22 -08002252 @GuardedBy("mLock")
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002253 private ParceledListSlice<ShortcutInfo> getShortcutsWithQueryLocked(@NonNull String packageName,
2254 @UserIdInt int userId, int cloneFlags, @NonNull Predicate<ShortcutInfo> query) {
2255
2256 final ArrayList<ShortcutInfo> ret = new ArrayList<>();
2257
Makoto Onukic8c33292016-09-12 16:36:59 -07002258 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002259 ps.findAll(ret, query, cloneFlags);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002260
Makoto Onukibf563b62017-05-04 10:25:30 -07002261 return new ParceledListSlice<>(setReturnedByServer(ret));
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002262 }
2263
2264 @Override
Makoto Onukid6880792016-06-29 13:37:43 -07002265 public int getMaxShortcutCountPerActivity(String packageName, @UserIdInt int userId)
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002266 throws RemoteException {
2267 verifyCaller(packageName, userId);
2268
Makoto Onukib5a012f2016-06-21 11:13:53 -07002269 return mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002270 }
2271
2272 @Override
2273 public int getRemainingCallCount(String packageName, @UserIdInt int userId) {
2274 verifyCaller(packageName, userId);
2275
Makoto Onuki7d0fa812018-02-21 11:24:43 -08002276 final boolean unlimited = injectHasUnlimitedShortcutsApiCallsPermission(
2277 injectBinderCallingPid(), injectBinderCallingUid());
2278
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002279 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002280 throwIfUserLockedL(userId);
2281
Makoto Onukic8c33292016-09-12 16:36:59 -07002282 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki7d0fa812018-02-21 11:24:43 -08002283 return mMaxUpdatesPerInterval - ps.getApiCallCount(unlimited);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002284 }
2285 }
2286
2287 @Override
2288 public long getRateLimitResetTime(String packageName, @UserIdInt int userId) {
2289 verifyCaller(packageName, userId);
2290
2291 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002292 throwIfUserLockedL(userId);
2293
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002294 return getNextResetTimeLocked();
2295 }
2296 }
2297
Makoto Onuki55046222016-03-08 10:49:47 -08002298 @Override
Makoto Onuki20c95f82016-05-11 16:51:01 -07002299 public int getIconMaxDimensions(String packageName, int userId) {
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002300 verifyCaller(packageName, userId);
2301
Makoto Onuki55046222016-03-08 10:49:47 -08002302 synchronized (mLock) {
2303 return mMaxIconDimension;
2304 }
2305 }
2306
Makoto Onuki20c95f82016-05-11 16:51:01 -07002307 @Override
2308 public void reportShortcutUsed(String packageName, String shortcutId, int userId) {
2309 verifyCaller(packageName, userId);
2310
Daulet Zhanguzin82adfcb2020-01-02 17:31:40 +00002311 Objects.requireNonNull(shortcutId);
Makoto Onukiac042502016-05-20 16:39:42 -07002312
2313 if (DEBUG) {
2314 Slog.d(TAG, String.format("reportShortcutUsed: Shortcut %s package %s used on user %d",
2315 shortcutId, packageName, userId));
2316 }
2317
2318 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002319 throwIfUserLockedL(userId);
2320
Makoto Onukic8c33292016-09-12 16:36:59 -07002321 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002322
Makoto Onukiac042502016-05-20 16:39:42 -07002323 if (ps.findShortcutById(shortcutId) == null) {
2324 Log.w(TAG, String.format("reportShortcutUsed: package %s doesn't have shortcut %s",
2325 packageName, shortcutId));
2326 return;
2327 }
2328 }
2329
2330 final long token = injectClearCallingIdentity();
2331 try {
2332 mUsageStatsManagerInternal.reportShortcutUsage(packageName, shortcutId, userId);
2333 } finally {
2334 injectRestoreCallingIdentity(token);
2335 }
Makoto Onuki20c95f82016-05-11 16:51:01 -07002336 }
2337
Makoto Onuki2d895c32016-12-02 15:48:40 -08002338 @Override
Sunny Goyal7f7372a2017-01-24 11:53:54 -08002339 public boolean isRequestPinItemSupported(int callingUserId, int requestType) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08002340 final long token = injectClearCallingIdentity();
2341 try {
Sunny Goyal7f7372a2017-01-24 11:53:54 -08002342 return mShortcutRequestPinProcessor
2343 .isRequestPinItemSupported(callingUserId, requestType);
Makoto Onuki2d895c32016-12-02 15:48:40 -08002344 } finally {
2345 injectRestoreCallingIdentity(token);
2346 }
2347 }
2348
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002349 /**
Makoto Onukib08790c2016-06-23 14:05:46 -07002350 * Reset all throttling, for developer options and command line. Only system/shell can call
2351 * it.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002352 */
2353 @Override
2354 public void resetThrottling() {
2355 enforceSystemOrShell();
2356
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002357 resetThrottlingInner(getCallingUserId());
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002358 }
2359
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002360 void resetThrottlingInner(@UserIdInt int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002361 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002362 if (!isUserUnlockedL(userId)) {
2363 Log.w(TAG, "User " + userId + " is locked or not running");
2364 return;
2365 }
2366
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002367 getUserShortcutsLocked(userId).resetThrottling();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002368 }
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002369 scheduleSaveUser(userId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002370 Slog.i(TAG, "ShortcutManager: throttling counter reset for user " + userId);
2371 }
2372
2373 void resetAllThrottlingInner() {
2374 synchronized (mLock) {
2375 mRawLastResetTime = injectCurrentTimeMillis();
2376 }
2377 scheduleSaveBaseState();
2378 Slog.i(TAG, "ShortcutManager: throttling counter reset for all users");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002379 }
2380
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002381 @Override
2382 public void onApplicationActive(String packageName, int userId) {
2383 if (DEBUG) {
2384 Slog.d(TAG, "onApplicationActive: package=" + packageName + " userid=" + userId);
2385 }
2386 enforceResetThrottlingPermission();
Makoto Onuki02f338e2016-07-29 09:40:40 -07002387
2388 synchronized (mLock) {
2389 if (!isUserUnlockedL(userId)) {
2390 // This is called by system UI, so no need to throw. Just ignore.
2391 return;
2392 }
2393
2394 getPackageShortcutsLocked(packageName, userId)
2395 .resetRateLimitingForCommandLineNoSaving();
2396 saveUserLocked(userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002397 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002398 }
2399
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002400 // We override this method in unit tests to do a simpler check.
Makoto Onuki634cecb2017-10-13 17:10:48 -07002401 boolean hasShortcutHostPermission(@NonNull String callingPackage, int userId,
2402 int callingPid, int callingUid) {
Makoto Onuki35559d62017-11-06 16:26:32 -08002403 if (canSeeAnyPinnedShortcut(callingPackage, userId, callingPid, callingUid)) {
Makoto Onuki634cecb2017-10-13 17:10:48 -07002404 return true;
2405 }
Makoto Onuki84d59342018-02-02 09:22:38 -08002406 final long start = getStatStartTime();
Makoto Onuki10305202016-07-14 18:14:08 -07002407 try {
2408 return hasShortcutHostPermissionInner(callingPackage, userId);
2409 } finally {
2410 logDurationStat(Stats.LAUNCHER_PERMISSION_CHECK, start);
2411 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002412 }
2413
Makoto Onuki35559d62017-11-06 16:26:32 -08002414 boolean canSeeAnyPinnedShortcut(@NonNull String callingPackage, int userId,
2415 int callingPid, int callingUid) {
2416 if (injectHasAccessShortcutsPermission(callingPid, callingUid)) {
2417 return true;
2418 }
2419 synchronized (mLock) {
Makoto Onuki708703b2017-12-11 16:38:11 -08002420 return getNonPersistentUserLocked(userId).hasHostPackage(callingPackage);
Makoto Onuki35559d62017-11-06 16:26:32 -08002421 }
2422 }
2423
Makoto Onuki634cecb2017-10-13 17:10:48 -07002424 /**
2425 * Returns true if the caller has the "ACCESS_SHORTCUTS" permission.
2426 */
Makoto Onuki35559d62017-11-06 16:26:32 -08002427 @VisibleForTesting
2428 boolean injectHasAccessShortcutsPermission(int callingPid, int callingUid) {
Makoto Onuki634cecb2017-10-13 17:10:48 -07002429 return mContext.checkPermission(android.Manifest.permission.ACCESS_SHORTCUTS,
2430 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
2431 }
2432
Makoto Onuki7d0fa812018-02-21 11:24:43 -08002433 /**
2434 * Returns true if the caller has the "UNLIMITED_SHORTCUTS_API_CALLS" permission.
2435 */
2436 @VisibleForTesting
2437 boolean injectHasUnlimitedShortcutsApiCallsPermission(int callingPid, int callingUid) {
2438 return mContext.checkPermission(permission.UNLIMITED_SHORTCUTS_API_CALLS,
2439 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
2440 }
2441
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002442 // This method is extracted so we can directly call this method from unit tests,
2443 // even when hasShortcutPermission() is overridden.
2444 @VisibleForTesting
Makoto Onuki2d895c32016-12-02 15:48:40 -08002445 boolean hasShortcutHostPermissionInner(@NonNull String packageName, int userId) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002446 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002447 throwIfUserLockedL(userId);
2448
Makoto Onuki31459242016-03-22 11:12:18 -07002449 final ShortcutUser user = getUserShortcutsLocked(userId);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002450
Makoto Onuki2d895c32016-12-02 15:48:40 -08002451 // Always trust the cached component.
Makoto Onuki10305202016-07-14 18:14:08 -07002452 final ComponentName cached = user.getCachedLauncher();
2453 if (cached != null) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08002454 if (cached.getPackageName().equals(packageName)) {
Makoto Onuki10305202016-07-14 18:14:08 -07002455 return true;
2456 }
2457 }
2458 // If the cached one doesn't match, then go ahead
2459
Makoto Onuki2d895c32016-12-02 15:48:40 -08002460 final ComponentName detected = getDefaultLauncher(userId);
Makoto Onuki2e210c42016-03-30 08:30:36 -07002461
Makoto Onuki10305202016-07-14 18:14:08 -07002462 // Update the cache.
2463 user.setLauncher(detected);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002464 if (detected != null) {
2465 if (DEBUG) {
2466 Slog.v(TAG, "Detected launcher: " + detected);
2467 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08002468 return detected.getPackageName().equals(packageName);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002469 } else {
2470 // Default launcher not found.
2471 return false;
2472 }
2473 }
2474 }
2475
Makoto Onuki2d895c32016-12-02 15:48:40 -08002476 @Nullable
2477 ComponentName getDefaultLauncher(@UserIdInt int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08002478 final long start = getStatStartTime();
Makoto Onuki2d895c32016-12-02 15:48:40 -08002479 final long token = injectClearCallingIdentity();
2480 try {
2481 synchronized (mLock) {
2482 throwIfUserLockedL(userId);
2483
2484 final ShortcutUser user = getUserShortcutsLocked(userId);
2485
2486 final List<ResolveInfo> allHomeCandidates = new ArrayList<>();
2487
2488 // Default launcher from package manager.
Makoto Onuki84d59342018-02-02 09:22:38 -08002489 final long startGetHomeActivitiesAsUser = getStatStartTime();
Makoto Onuki2d895c32016-12-02 15:48:40 -08002490 final ComponentName defaultLauncher = mPackageManagerInternal
2491 .getHomeActivitiesAsUser(allHomeCandidates, userId);
2492 logDurationStat(Stats.GET_DEFAULT_HOME, startGetHomeActivitiesAsUser);
2493
2494 ComponentName detected = null;
2495 if (defaultLauncher != null) {
2496 detected = defaultLauncher;
2497 if (DEBUG) {
2498 Slog.v(TAG, "Default launcher from PM: " + detected);
2499 }
2500 } else {
2501 detected = user.getLastKnownLauncher();
2502
2503 if (detected != null) {
2504 if (injectIsActivityEnabledAndExported(detected, userId)) {
2505 if (DEBUG) {
2506 Slog.v(TAG, "Cached launcher: " + detected);
2507 }
2508 } else {
2509 Slog.w(TAG, "Cached launcher " + detected + " no longer exists");
2510 detected = null;
2511 user.clearLauncher();
2512 }
2513 }
2514 }
2515
2516 if (detected == null) {
2517 // If we reach here, that means it's the first check since the user was created,
2518 // and there's already multiple launchers and there's no default set.
2519 // Find the system one with the highest priority.
2520 // (We need to check the priority too because of FallbackHome in Settings.)
2521 // If there's no system launcher yet, then no one can access shortcuts, until
2522 // the user explicitly
2523 final int size = allHomeCandidates.size();
2524
2525 int lastPriority = Integer.MIN_VALUE;
2526 for (int i = 0; i < size; i++) {
2527 final ResolveInfo ri = allHomeCandidates.get(i);
2528 if (!ri.activityInfo.applicationInfo.isSystemApp()) {
2529 continue;
2530 }
2531 if (DEBUG) {
2532 Slog.d(TAG, String.format("hasShortcutPermissionInner: pkg=%s prio=%d",
2533 ri.activityInfo.getComponentName(), ri.priority));
2534 }
2535 if (ri.priority < lastPriority) {
2536 continue;
2537 }
2538 detected = ri.activityInfo.getComponentName();
2539 lastPriority = ri.priority;
2540 }
2541 }
2542 return detected;
2543 }
2544 } finally {
2545 injectRestoreCallingIdentity(token);
2546 logDurationStat(Stats.GET_DEFAULT_LAUNCHER, start);
2547 }
2548 }
2549
Dianne Hackbornc160fa42017-11-01 16:14:26 -07002550 public void setShortcutHostPackage(@NonNull String type, @Nullable String packageName,
2551 int userId) {
2552 synchronized (mLock) {
Makoto Onuki708703b2017-12-11 16:38:11 -08002553 getNonPersistentUserLocked(userId).setShortcutHostPackage(type, packageName);
Dianne Hackbornc160fa42017-11-01 16:14:26 -07002554 }
2555 }
2556
Makoto Onukicdc78f72016-03-21 15:47:52 -07002557 // === House keeping ===
2558
Makoto Onukib08790c2016-06-23 14:05:46 -07002559 private void cleanUpPackageForAllLoadedUsers(String packageName, @UserIdInt int packageUserId,
2560 boolean appStillExists) {
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002561 synchronized (mLock) {
2562 forEachLoadedUserLocked(user ->
Makoto Onukib08790c2016-06-23 14:05:46 -07002563 cleanUpPackageLocked(packageName, user.getUserId(), packageUserId,
2564 appStillExists));
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002565 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002566 }
2567
Makoto Onuki2e210c42016-03-30 08:30:36 -07002568 /**
2569 * Remove all the information associated with a package. This will really remove all the
2570 * information, including the restore information (i.e. it'll remove packages even if they're
2571 * shadow).
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002572 *
2573 * This is called when an app is uninstalled, or an app gets "clear data"ed.
Makoto Onuki2e210c42016-03-30 08:30:36 -07002574 */
Andreas Gampea36dc622018-02-05 17:19:22 -08002575 @GuardedBy("mLock")
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002576 @VisibleForTesting
Makoto Onukib08790c2016-06-23 14:05:46 -07002577 void cleanUpPackageLocked(String packageName, int owningUserId, int packageUserId,
2578 boolean appStillExists) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002579 final boolean wasUserLoaded = isUserLoadedLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002580
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002581 final ShortcutUser user = getUserShortcutsLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002582 boolean doNotify = false;
2583
2584 // First, remove the package from the package list (if the package is a publisher).
Makoto Onukid99c6f02016-03-28 11:02:54 -07002585 if (packageUserId == owningUserId) {
Makoto Onukic51b2872016-05-04 15:24:50 -07002586 if (user.removePackage(packageName) != null) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002587 doNotify = true;
2588 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07002589 }
Makoto Onukid99c6f02016-03-28 11:02:54 -07002590
Makoto Onukicdc78f72016-03-21 15:47:52 -07002591 // Also remove from the launcher list (if the package is a launcher).
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002592 user.removeLauncher(packageUserId, packageName);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002593
2594 // Then remove pinned shortcuts from all launchers.
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002595 user.forAllLaunchers(l -> l.cleanUpPackage(packageName, packageUserId));
2596
2597 // Now there may be orphan shortcuts because we removed pinned shortcuts at the previous
Makoto Onukicdc78f72016-03-21 15:47:52 -07002598 // step. Remove them too.
Makoto Onukic51b2872016-05-04 15:24:50 -07002599 user.forAllPackages(p -> p.refreshPinnedFlags());
Makoto Onukicdc78f72016-03-21 15:47:52 -07002600
Makoto Onukid99c6f02016-03-28 11:02:54 -07002601 scheduleSaveUser(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002602
2603 if (doNotify) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002604 notifyListeners(packageName, owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002605 }
2606
Makoto Onukib08790c2016-06-23 14:05:46 -07002607 // If the app still exists (i.e. data cleared), we need to re-publish manifest shortcuts.
2608 if (appStillExists && (packageUserId == owningUserId)) {
2609 // This will do the notification and save when needed, so do it after the above
2610 // notifyListeners.
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002611 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07002612 }
2613
Makoto Onukicdc78f72016-03-21 15:47:52 -07002614 if (!wasUserLoaded) {
2615 // Note this will execute the scheduled save.
Makoto Onukid99c6f02016-03-28 11:02:54 -07002616 unloadUserLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002617 }
2618 }
2619
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002620 /**
2621 * Entry point from {@link LauncherApps}.
2622 */
2623 private class LocalService extends ShortcutServiceInternal {
Makoto Onuki2e210c42016-03-30 08:30:36 -07002624
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002625 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002626 public List<ShortcutInfo> getShortcuts(int launcherUserId,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002627 @NonNull String callingPackage, long changedSince,
Makoto Onukiabe84422016-04-07 09:41:19 -07002628 @Nullable String packageName, @Nullable List<String> shortcutIds,
Makoto Onuki99302b52017-03-29 12:42:26 -07002629 @Nullable ComponentName componentName,
Makoto Onuki634cecb2017-10-13 17:10:48 -07002630 int queryFlags, int userId, int callingPid, int callingUid) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002631 final ArrayList<ShortcutInfo> ret = new ArrayList<>();
Makoto Onuki9c850012016-07-26 15:50:50 -07002632
Makoto Onuki20c95f82016-05-11 16:51:01 -07002633 final boolean cloneKeyFieldOnly =
2634 ((queryFlags & ShortcutQuery.FLAG_GET_KEY_FIELDS_ONLY) != 0);
2635 final int cloneFlag = cloneKeyFieldOnly ? ShortcutInfo.CLONE_REMOVE_NON_KEY_INFO
2636 : ShortcutInfo.CLONE_REMOVE_FOR_LAUNCHER;
Makoto Onukiabe84422016-04-07 09:41:19 -07002637 if (packageName == null) {
2638 shortcutIds = null; // LauncherAppsService already threw for it though.
2639 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002640
2641 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002642 throwIfUserLockedL(userId);
2643 throwIfUserLockedL(launcherUserId);
2644
Makoto Onuki2e210c42016-03-30 08:30:36 -07002645 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002646 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002647
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002648 if (packageName != null) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002649 getShortcutsInnerLocked(launcherUserId,
Makoto Onukiabe84422016-04-07 09:41:19 -07002650 callingPackage, packageName, shortcutIds, changedSince,
Makoto Onuki634cecb2017-10-13 17:10:48 -07002651 componentName, queryFlags, userId, ret, cloneFlag,
2652 callingPid, callingUid);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002653 } else {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002654 final List<String> shortcutIdsF = shortcutIds;
2655 getUserShortcutsLocked(userId).forAllPackages(p -> {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002656 getShortcutsInnerLocked(launcherUserId,
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002657 callingPackage, p.getPackageName(), shortcutIdsF, changedSince,
Makoto Onuki634cecb2017-10-13 17:10:48 -07002658 componentName, queryFlags, userId, ret, cloneFlag,
2659 callingPid, callingUid);
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002660 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002661 }
2662 }
Makoto Onukibf563b62017-05-04 10:25:30 -07002663 return setReturnedByServer(ret);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002664 }
2665
Andreas Gampea36dc622018-02-05 17:19:22 -08002666 @GuardedBy("ShortcutService.this.mLock")
Makoto Onukid99c6f02016-03-28 11:02:54 -07002667 private void getShortcutsInnerLocked(int launcherUserId, @NonNull String callingPackage,
Makoto Onukiabe84422016-04-07 09:41:19 -07002668 @Nullable String packageName, @Nullable List<String> shortcutIds, long changedSince,
Makoto Onuki99302b52017-03-29 12:42:26 -07002669 @Nullable ComponentName componentName, int queryFlags,
Makoto Onuki634cecb2017-10-13 17:10:48 -07002670 int userId, ArrayList<ShortcutInfo> ret, int cloneFlag,
2671 int callingPid, int callingUid) {
Makoto Onukiabe84422016-04-07 09:41:19 -07002672 final ArraySet<String> ids = shortcutIds == null ? null
2673 : new ArraySet<>(shortcutIds);
2674
Makoto Onuki35559d62017-11-06 16:26:32 -08002675 final ShortcutUser user = getUserShortcutsLocked(userId);
2676 final ShortcutPackage p = user.getPackageShortcutsIfExists(packageName);
Makoto Onukic51b2872016-05-04 15:24:50 -07002677 if (p == null) {
2678 return; // No need to instantiate ShortcutPackage.
2679 }
Makoto Onuki634cecb2017-10-13 17:10:48 -07002680 final boolean matchDynamic = (queryFlags & ShortcutQuery.FLAG_MATCH_DYNAMIC) != 0;
2681 final boolean matchPinned = (queryFlags & ShortcutQuery.FLAG_MATCH_PINNED) != 0;
2682 final boolean matchManifest = (queryFlags & ShortcutQuery.FLAG_MATCH_MANIFEST) != 0;
Mehdi Alizadeh505fb762020-01-21 17:26:24 -08002683 final boolean matchCached = (queryFlags & ShortcutQuery.FLAG_MATCH_CACHED) != 0;
Makoto Onuki634cecb2017-10-13 17:10:48 -07002684
Makoto Onuki35559d62017-11-06 16:26:32 -08002685 final boolean canAccessAllShortcuts =
2686 canSeeAnyPinnedShortcut(callingPackage, launcherUserId, callingPid, callingUid);
2687
Makoto Onuki634cecb2017-10-13 17:10:48 -07002688 final boolean getPinnedByAnyLauncher =
Makoto Onuki35559d62017-11-06 16:26:32 -08002689 canAccessAllShortcuts &&
2690 ((queryFlags & ShortcutQuery.FLAG_MATCH_PINNED_BY_ANY_LAUNCHER) != 0);
Makoto Onukic51b2872016-05-04 15:24:50 -07002691
2692 p.findAll(ret,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002693 (ShortcutInfo si) -> {
2694 if (si.getLastChangedTimestamp() < changedSince) {
2695 return false;
2696 }
Makoto Onukiabe84422016-04-07 09:41:19 -07002697 if (ids != null && !ids.contains(si.getId())) {
2698 return false;
2699 }
Makoto Onuki85694522016-05-04 12:53:37 -07002700 if (componentName != null) {
Makoto Onuki9fd90192017-01-06 18:31:03 +00002701 if (si.getActivity() != null
2702 && !si.getActivity().equals(componentName)) {
Makoto Onuki85694522016-05-04 12:53:37 -07002703 return false;
2704 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002705 }
Makoto Onuki634cecb2017-10-13 17:10:48 -07002706 if (matchDynamic && si.isDynamic()) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002707 return true;
2708 }
Makoto Onuki35559d62017-11-06 16:26:32 -08002709 if ((matchPinned || getPinnedByAnyLauncher) && si.isPinned()) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002710 return true;
2711 }
Makoto Onuki634cecb2017-10-13 17:10:48 -07002712 if (matchManifest && si.isDeclaredInManifest()) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002713 return true;
2714 }
Mehdi Alizadeh505fb762020-01-21 17:26:24 -08002715 if (matchCached && si.isCached()) {
2716 return true;
2717 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002718 return false;
Makoto Onuki634cecb2017-10-13 17:10:48 -07002719 }, cloneFlag, callingPackage, launcherUserId, getPinnedByAnyLauncher);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002720 }
2721
2722 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002723 public boolean isPinnedByCaller(int launcherUserId, @NonNull String callingPackage,
2724 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2725 Preconditions.checkStringNotEmpty(packageName, "packageName");
2726 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
2727
2728 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002729 throwIfUserLockedL(userId);
2730 throwIfUserLockedL(launcherUserId);
2731
Makoto Onuki2e210c42016-03-30 08:30:36 -07002732 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002733 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002734
Makoto Onukid99c6f02016-03-28 11:02:54 -07002735 final ShortcutInfo si = getShortcutInfoLocked(
Makoto Onuki634cecb2017-10-13 17:10:48 -07002736 launcherUserId, callingPackage, packageName, shortcutId, userId,
2737 /*getPinnedByAnyLauncher=*/ false);
Makoto Onukid99c6f02016-03-28 11:02:54 -07002738 return si != null && si.isPinned();
2739 }
2740 }
2741
Andreas Gampea36dc622018-02-05 17:19:22 -08002742 @GuardedBy("ShortcutService.this.mLock")
Makoto Onuki2e210c42016-03-30 08:30:36 -07002743 private ShortcutInfo getShortcutInfoLocked(
Makoto Onukid99c6f02016-03-28 11:02:54 -07002744 int launcherUserId, @NonNull String callingPackage,
Makoto Onuki634cecb2017-10-13 17:10:48 -07002745 @NonNull String packageName, @NonNull String shortcutId, int userId,
2746 boolean getPinnedByAnyLauncher) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002747 Preconditions.checkStringNotEmpty(packageName, "packageName");
2748 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
2749
Makoto Onuki02f338e2016-07-29 09:40:40 -07002750 throwIfUserLockedL(userId);
2751 throwIfUserLockedL(launcherUserId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002752
Makoto Onukic51b2872016-05-04 15:24:50 -07002753 final ShortcutPackage p = getUserShortcutsLocked(userId)
2754 .getPackageShortcutsIfExists(packageName);
2755 if (p == null) {
2756 return null;
2757 }
2758
Makoto Onukid99c6f02016-03-28 11:02:54 -07002759 final ArrayList<ShortcutInfo> list = new ArrayList<>(1);
Makoto Onukic51b2872016-05-04 15:24:50 -07002760 p.findAll(list,
Makoto Onukid99c6f02016-03-28 11:02:54 -07002761 (ShortcutInfo si) -> shortcutId.equals(si.getId()),
Makoto Onuki634cecb2017-10-13 17:10:48 -07002762 /* clone flags=*/ 0, callingPackage, launcherUserId, getPinnedByAnyLauncher);
Makoto Onukid99c6f02016-03-28 11:02:54 -07002763 return list.size() == 0 ? null : list.get(0);
2764 }
2765
2766 @Override
2767 public void pinShortcuts(int launcherUserId,
2768 @NonNull String callingPackage, @NonNull String packageName,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002769 @NonNull List<String> shortcutIds, int userId) {
2770 // Calling permission must be checked by LauncherAppsImpl.
2771 Preconditions.checkStringNotEmpty(packageName, "packageName");
Daulet Zhanguzin82adfcb2020-01-02 17:31:40 +00002772 Objects.requireNonNull(shortcutIds, "shortcutIds");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002773
2774 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002775 throwIfUserLockedL(userId);
2776 throwIfUserLockedL(launcherUserId);
2777
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002778 final ShortcutLauncher launcher =
Makoto Onuki2e210c42016-03-30 08:30:36 -07002779 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId);
Makoto Onukic51b2872016-05-04 15:24:50 -07002780 launcher.attemptToRestoreIfNeededAndSave();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002781
Makoto Onukia4f89b12017-10-05 10:37:55 -07002782 launcher.pinShortcuts(userId, packageName, shortcutIds, /*forPinRequest=*/ false);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002783 }
Makoto Onuki39686e82016-04-13 18:03:00 -07002784 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07002785
2786 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002787 }
2788
2789 @Override
Makoto Onuki440a1ea2016-07-20 14:21:18 -07002790 public Intent[] createShortcutIntents(int launcherUserId,
Makoto Onukid99c6f02016-03-28 11:02:54 -07002791 @NonNull String callingPackage,
Makoto Onuki634cecb2017-10-13 17:10:48 -07002792 @NonNull String packageName, @NonNull String shortcutId, int userId,
2793 int callingPid, int callingUid) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002794 // Calling permission must be checked by LauncherAppsImpl.
Makoto Onuki43204b82016-03-08 16:16:44 -08002795 Preconditions.checkStringNotEmpty(packageName, "packageName can't be empty");
2796 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId can't be empty");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002797
2798 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002799 throwIfUserLockedL(userId);
2800 throwIfUserLockedL(launcherUserId);
2801
Makoto Onuki2e210c42016-03-30 08:30:36 -07002802 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002803 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002804
Makoto Onuki634cecb2017-10-13 17:10:48 -07002805 final boolean getPinnedByAnyLauncher =
Makoto Onuki35559d62017-11-06 16:26:32 -08002806 canSeeAnyPinnedShortcut(callingPackage, launcherUserId,
2807 callingPid, callingUid);
Makoto Onuki634cecb2017-10-13 17:10:48 -07002808
Makoto Onukid99c6f02016-03-28 11:02:54 -07002809 // Make sure the shortcut is actually visible to the launcher.
2810 final ShortcutInfo si = getShortcutInfoLocked(
Makoto Onuki634cecb2017-10-13 17:10:48 -07002811 launcherUserId, callingPackage, packageName, shortcutId, userId,
2812 getPinnedByAnyLauncher);
Makoto Onukid99c6f02016-03-28 11:02:54 -07002813 // "si == null" should suffice here, but check the flags too just to make sure.
Makoto Onuki35559d62017-11-06 16:26:32 -08002814 if (si == null || !si.isEnabled() || !(si.isAlive() || getPinnedByAnyLauncher)) {
Makoto Onuki83f6d2d2016-07-11 14:30:19 -07002815 Log.e(TAG, "Shortcut " + shortcutId + " does not exist or disabled");
Makoto Onukid99c6f02016-03-28 11:02:54 -07002816 return null;
2817 }
Makoto Onuki440a1ea2016-07-20 14:21:18 -07002818 return si.getIntents();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002819 }
2820 }
2821
2822 @Override
2823 public void addListener(@NonNull ShortcutChangeListener listener) {
2824 synchronized (mLock) {
Daulet Zhanguzin82adfcb2020-01-02 17:31:40 +00002825 mListeners.add(Objects.requireNonNull(listener));
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002826 }
2827 }
Makoto Onuki55046222016-03-08 10:49:47 -08002828
2829 @Override
Makoto Onukiabe84422016-04-07 09:41:19 -07002830 public int getShortcutIconResId(int launcherUserId, @NonNull String callingPackage,
2831 @NonNull String packageName, @NonNull String shortcutId, int userId) {
Daulet Zhanguzin82adfcb2020-01-02 17:31:40 +00002832 Objects.requireNonNull(callingPackage, "callingPackage");
2833 Objects.requireNonNull(packageName, "packageName");
2834 Objects.requireNonNull(shortcutId, "shortcutId");
Makoto Onuki55046222016-03-08 10:49:47 -08002835
2836 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002837 throwIfUserLockedL(userId);
2838 throwIfUserLockedL(launcherUserId);
2839
Makoto Onuki2e210c42016-03-30 08:30:36 -07002840 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002841 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002842
Makoto Onukic51b2872016-05-04 15:24:50 -07002843 final ShortcutPackage p = getUserShortcutsLocked(userId)
2844 .getPackageShortcutsIfExists(packageName);
2845 if (p == null) {
2846 return 0;
2847 }
2848
2849 final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId);
Makoto Onuki55046222016-03-08 10:49:47 -08002850 return (shortcutInfo != null && shortcutInfo.hasIconResource())
2851 ? shortcutInfo.getIconResourceId() : 0;
2852 }
2853 }
2854
2855 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002856 public ParcelFileDescriptor getShortcutIconFd(int launcherUserId,
Makoto Onukiabe84422016-04-07 09:41:19 -07002857 @NonNull String callingPackage, @NonNull String packageName,
2858 @NonNull String shortcutId, int userId) {
Daulet Zhanguzin82adfcb2020-01-02 17:31:40 +00002859 Objects.requireNonNull(callingPackage, "callingPackage");
2860 Objects.requireNonNull(packageName, "packageName");
2861 Objects.requireNonNull(shortcutId, "shortcutId");
Makoto Onuki55046222016-03-08 10:49:47 -08002862
2863 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002864 throwIfUserLockedL(userId);
2865 throwIfUserLockedL(launcherUserId);
2866
Makoto Onuki2e210c42016-03-30 08:30:36 -07002867 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002868 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002869
Makoto Onukic51b2872016-05-04 15:24:50 -07002870 final ShortcutPackage p = getUserShortcutsLocked(userId)
2871 .getPackageShortcutsIfExists(packageName);
2872 if (p == null) {
2873 return null;
2874 }
2875
2876 final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId);
Makoto Onuki55046222016-03-08 10:49:47 -08002877 if (shortcutInfo == null || !shortcutInfo.hasIconFile()) {
2878 return null;
2879 }
Makoto Onuki475c3652017-05-08 14:29:03 -07002880 final String path = mShortcutBitmapSaver.getBitmapPathMayWaitLocked(shortcutInfo);
2881 if (path == null) {
2882 Slog.w(TAG, "null bitmap detected in getShortcutIconFd()");
2883 return null;
2884 }
Makoto Onuki55046222016-03-08 10:49:47 -08002885 try {
2886 return ParcelFileDescriptor.open(
Makoto Onuki475c3652017-05-08 14:29:03 -07002887 new File(path),
Makoto Onuki55046222016-03-08 10:49:47 -08002888 ParcelFileDescriptor.MODE_READ_ONLY);
2889 } catch (FileNotFoundException e) {
Makoto Onuki475c3652017-05-08 14:29:03 -07002890 Slog.e(TAG, "Icon file not found: " + path);
Makoto Onuki55046222016-03-08 10:49:47 -08002891 return null;
2892 }
2893 }
2894 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002895
2896 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002897 public boolean hasShortcutHostPermission(int launcherUserId,
Makoto Onuki634cecb2017-10-13 17:10:48 -07002898 @NonNull String callingPackage, int callingPid, int callingUid) {
2899 return ShortcutService.this.hasShortcutHostPermission(callingPackage, launcherUserId,
2900 callingPid, callingUid);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002901 }
Sunny Goyal87a563e2017-01-01 19:42:45 -08002902
2903 @Override
Dianne Hackbornc160fa42017-11-01 16:14:26 -07002904 public void setShortcutHostPackage(@NonNull String type, @Nullable String packageName,
2905 int userId) {
2906 ShortcutService.this.setShortcutHostPackage(type, packageName, userId);
2907 }
2908
2909 @Override
Sunny Goyal87a563e2017-01-01 19:42:45 -08002910 public boolean requestPinAppWidget(@NonNull String callingPackage,
Sunny Goyal4ad6b572017-02-28 11:11:51 -08002911 @NonNull AppWidgetProviderInfo appWidget, @Nullable Bundle extras,
2912 @Nullable IntentSender resultIntent, int userId) {
Daulet Zhanguzin82adfcb2020-01-02 17:31:40 +00002913 Objects.requireNonNull(appWidget);
Sunny Goyal4ad6b572017-02-28 11:11:51 -08002914 return requestPinItem(callingPackage, userId, null, appWidget, extras, resultIntent);
Sunny Goyal87a563e2017-01-01 19:42:45 -08002915 }
Sunny Goyal7f7372a2017-01-24 11:53:54 -08002916
2917 @Override
2918 public boolean isRequestPinItemSupported(int callingUserId, int requestType) {
2919 return ShortcutService.this.isRequestPinItemSupported(callingUserId, requestType);
2920 }
Tony Maked6ef622017-12-07 16:36:16 +00002921
2922 @Override
2923 public boolean isForegroundDefaultLauncher(@NonNull String callingPackage, int callingUid) {
Daulet Zhanguzin82adfcb2020-01-02 17:31:40 +00002924 Objects.requireNonNull(callingPackage);
Tony Maked6ef622017-12-07 16:36:16 +00002925
2926 final int userId = UserHandle.getUserId(callingUid);
2927 final ComponentName defaultLauncher = getDefaultLauncher(userId);
2928 if (defaultLauncher == null) {
2929 return false;
2930 }
2931 if (!callingPackage.equals(defaultLauncher.getPackageName())) {
2932 return false;
2933 }
2934 synchronized (mLock) {
2935 if (!isUidForegroundLocked(callingUid)) {
2936 return false;
2937 }
2938 }
2939 return true;
2940 }
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002941 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002942
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002943 final BroadcastReceiver mReceiver = new BroadcastReceiver() {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002944 @Override
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002945 public void onReceive(Context context, Intent intent) {
2946 if (!mBootCompleted.get()) {
2947 return; // Boot not completed, ignore the broadcast.
2948 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07002949 try {
2950 if (Intent.ACTION_LOCALE_CHANGED.equals(intent.getAction())) {
2951 handleLocaleChanged();
2952 }
2953 } catch (Exception e) {
2954 wtf("Exception in mReceiver.onReceive", e);
Makoto Onukic51b2872016-05-04 15:24:50 -07002955 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002956 }
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002957 };
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002958
Makoto Onuki157b1622016-06-02 16:13:10 -07002959 void handleLocaleChanged() {
2960 if (DEBUG) {
2961 Slog.d(TAG, "handleLocaleChanged");
2962 }
2963 scheduleSaveBaseState();
2964
Makoto Onuki02f338e2016-07-29 09:40:40 -07002965 synchronized (mLock) {
2966 final long token = injectClearCallingIdentity();
2967 try {
2968 forEachLoadedUserLocked(user -> user.detectLocaleChange());
2969 } finally {
2970 injectRestoreCallingIdentity(token);
2971 }
Makoto Onuki157b1622016-06-02 16:13:10 -07002972 }
2973 }
2974
Makoto Onukif34c3082016-07-13 10:25:25 -07002975 /**
2976 * Package event callbacks.
2977 */
2978 @VisibleForTesting
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002979 final BroadcastReceiver mPackageMonitor = new BroadcastReceiver() {
Makoto Onukif34c3082016-07-13 10:25:25 -07002980 @Override
2981 public void onReceive(Context context, Intent intent) {
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002982 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
2983 if (userId == UserHandle.USER_NULL) {
2984 Slog.w(TAG, "Intent broadcast does not contain user handle: " + intent);
2985 return;
2986 }
2987
2988 final String action = intent.getAction();
2989
2990 // This is normally called on Handler, so clearCallingIdentity() isn't needed,
2991 // but we still check it in unit tests.
Makoto Onukif34c3082016-07-13 10:25:25 -07002992 final long token = injectClearCallingIdentity();
2993 try {
Makoto Onuki10305202016-07-14 18:14:08 -07002994 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002995 if (!isUserUnlockedL(userId)) {
2996 if (DEBUG) {
2997 Slog.d(TAG, "Ignoring package broadcast " + action
2998 + " for locked/stopped user " + userId);
2999 }
3000 return;
3001 }
3002
3003 // Whenever we get one of those package broadcasts, or get
3004 // ACTION_PREFERRED_ACTIVITY_CHANGED, we purge the default launcher cache.
Makoto Onuki10305202016-07-14 18:14:08 -07003005 final ShortcutUser user = getUserShortcutsLocked(userId);
3006 user.clearLauncher();
3007 }
3008 if (Intent.ACTION_PREFERRED_ACTIVITY_CHANGED.equals(action)) {
3009 // Nothing farther to do.
3010 return;
3011 }
3012
Makoto Onuki4e6cef42016-07-13 16:14:01 -07003013 final Uri intentUri = intent.getData();
3014 final String packageName = (intentUri != null) ? intentUri.getSchemeSpecificPart()
3015 : null;
3016 if (packageName == null) {
3017 Slog.w(TAG, "Intent broadcast does not contain package name: " + intent);
3018 return;
3019 }
3020
3021 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
3022
3023 switch (action) {
3024 case Intent.ACTION_PACKAGE_ADDED:
3025 if (replacing) {
3026 handlePackageUpdateFinished(packageName, userId);
3027 } else {
3028 handlePackageAdded(packageName, userId);
3029 }
3030 break;
3031 case Intent.ACTION_PACKAGE_REMOVED:
3032 if (!replacing) {
3033 handlePackageRemoved(packageName, userId);
3034 }
3035 break;
3036 case Intent.ACTION_PACKAGE_CHANGED:
3037 handlePackageChanged(packageName, userId);
3038
3039 break;
3040 case Intent.ACTION_PACKAGE_DATA_CLEARED:
3041 handlePackageDataCleared(packageName, userId);
3042 break;
3043 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07003044 } catch (Exception e) {
3045 wtf("Exception in mPackageMonitor.onReceive", e);
Makoto Onukif34c3082016-07-13 10:25:25 -07003046 } finally {
3047 injectRestoreCallingIdentity(token);
Makoto Onukia2241832016-07-06 13:28:37 -07003048 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07003049 }
Makoto Onukif34c3082016-07-13 10:25:25 -07003050 };
Makoto Onukicdc78f72016-03-21 15:47:52 -07003051
Makoto Onuki0acbb142016-03-22 17:02:57 -07003052 /**
Makoto Onuki39686e82016-04-13 18:03:00 -07003053 * Called when a user is unlocked.
3054 * - Check all known packages still exist, and otherwise perform cleanup.
3055 * - If a package still exists, check the version code. If it's been updated, may need to
Makoto Onukib08790c2016-06-23 14:05:46 -07003056 * update timestamps of its shortcuts.
Makoto Onuki0acbb142016-03-22 17:02:57 -07003057 */
Makoto Onukid99c6f02016-03-28 11:02:54 -07003058 @VisibleForTesting
Makoto Onuki39686e82016-04-13 18:03:00 -07003059 void checkPackageChanges(@UserIdInt int ownerUserId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07003060 if (DEBUG) {
Makoto Onuki39686e82016-04-13 18:03:00 -07003061 Slog.d(TAG, "checkPackageChanges() ownerUserId=" + ownerUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07003062 }
Makoto Onukib08790c2016-06-23 14:05:46 -07003063 if (injectIsSafeModeEnabled()) {
3064 Slog.i(TAG, "Safe mode, skipping checkPackageChanges()");
3065 return;
3066 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07003067
Makoto Onuki84d59342018-02-02 09:22:38 -08003068 final long start = getStatStartTime();
Makoto Onuki22fcc682016-05-17 14:52:19 -07003069 try {
3070 final ArrayList<PackageWithUser> gonePackages = new ArrayList<>();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003071
Makoto Onuki22fcc682016-05-17 14:52:19 -07003072 synchronized (mLock) {
3073 final ShortcutUser user = getUserShortcutsLocked(ownerUserId);
3074
3075 // Find packages that have been uninstalled.
3076 user.forAllPackageItems(spi -> {
3077 if (spi.getPackageInfo().isShadow()) {
3078 return; // Don't delete shadow information.
3079 }
3080 if (!isPackageInstalled(spi.getPackageName(), spi.getPackageUserId())) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003081 if (DEBUG) {
3082 Slog.d(TAG, "Uninstalled: " + spi.getPackageName()
3083 + " user " + spi.getPackageUserId());
3084 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07003085 gonePackages.add(PackageWithUser.of(spi));
3086 }
3087 });
3088 if (gonePackages.size() > 0) {
3089 for (int i = gonePackages.size() - 1; i >= 0; i--) {
3090 final PackageWithUser pu = gonePackages.get(i);
Makoto Onukib08790c2016-06-23 14:05:46 -07003091 cleanUpPackageLocked(pu.packageName, ownerUserId, pu.userId,
3092 /* appStillExists = */ false);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003093 }
Makoto Onukid99c6f02016-03-28 11:02:54 -07003094 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07003095
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003096 rescanUpdatedPackagesLocked(ownerUserId, user.getLastAppScanTime());
Makoto Onuki0acbb142016-03-22 17:02:57 -07003097 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07003098 } finally {
3099 logDurationStat(Stats.CHECK_PACKAGE_CHANGES, start);
Makoto Onuki0acbb142016-03-22 17:02:57 -07003100 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07003101 verifyStates();
Makoto Onukicdc78f72016-03-21 15:47:52 -07003102 }
3103
Andreas Gampea36dc622018-02-05 17:19:22 -08003104 @GuardedBy("mLock")
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003105 private void rescanUpdatedPackagesLocked(@UserIdInt int userId, long lastScanTime) {
Makoto Onuki377b7972016-08-09 14:43:55 -07003106 final ShortcutUser user = getUserShortcutsLocked(userId);
3107
Makoto Onuki33663282016-08-22 16:19:04 -07003108 // Note after each OTA, we'll need to rescan all system apps, as their lastUpdateTime
3109 // is not reliable.
Makoto Onuki377b7972016-08-09 14:43:55 -07003110 final long now = injectCurrentTimeMillis();
Makoto Onuki33663282016-08-22 16:19:04 -07003111 final boolean afterOta =
3112 !injectBuildFingerprint().equals(user.getLastAppScanOsFingerprint());
Makoto Onuki377b7972016-08-09 14:43:55 -07003113
3114 // Then for each installed app, publish manifest shortcuts when needed.
Makoto Onuki33663282016-08-22 16:19:04 -07003115 forUpdatedPackages(userId, lastScanTime, afterOta, ai -> {
Makoto Onuki377b7972016-08-09 14:43:55 -07003116 user.attemptToRestoreIfNeededAndSave(this, ai.packageName, userId);
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003117
3118 user.rescanPackageIfNeeded(ai.packageName, /* forceRescan= */ true);
Makoto Onuki377b7972016-08-09 14:43:55 -07003119 });
3120
3121 // Write the time just before the scan, because there may be apps that have just
3122 // been updated, and we want to catch them in the next time.
3123 user.setLastAppScanTime(now);
Makoto Onuki33663282016-08-22 16:19:04 -07003124 user.setLastAppScanOsFingerprint(injectBuildFingerprint());
Makoto Onuki377b7972016-08-09 14:43:55 -07003125 scheduleSaveUser(userId);
3126 }
3127
Makoto Onuki0acbb142016-03-22 17:02:57 -07003128 private void handlePackageAdded(String packageName, @UserIdInt int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07003129 if (DEBUG) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07003130 Slog.d(TAG, String.format("handlePackageAdded: %s user=%d", packageName, userId));
3131 }
3132 synchronized (mLock) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07003133 final ShortcutUser user = getUserShortcutsLocked(userId);
3134 user.attemptToRestoreIfNeededAndSave(this, packageName, userId);
Makoto Onuki64183d52016-08-08 14:11:34 -07003135 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onuki0acbb142016-03-22 17:02:57 -07003136 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07003137 verifyStates();
Makoto Onuki0acbb142016-03-22 17:02:57 -07003138 }
3139
3140 private void handlePackageUpdateFinished(String packageName, @UserIdInt int userId) {
Makoto Onuki905e8852016-03-28 10:40:58 -07003141 if (DEBUG) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003142 Slog.d(TAG, String.format("handlePackageUpdateFinished: %s user=%d",
3143 packageName, userId));
Makoto Onuki0acbb142016-03-22 17:02:57 -07003144 }
3145 synchronized (mLock) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07003146 final ShortcutUser user = getUserShortcutsLocked(userId);
3147 user.attemptToRestoreIfNeededAndSave(this, packageName, userId);
Makoto Onuki39686e82016-04-13 18:03:00 -07003148
Makoto Onuki22fcc682016-05-17 14:52:19 -07003149 if (isPackageInstalled(packageName, userId)) {
Makoto Onuki64183d52016-08-08 14:11:34 -07003150 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onuki39686e82016-04-13 18:03:00 -07003151 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07003152 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07003153 verifyStates();
Makoto Onuki0acbb142016-03-22 17:02:57 -07003154 }
3155
Makoto Onuki2e210c42016-03-30 08:30:36 -07003156 private void handlePackageRemoved(String packageName, @UserIdInt int packageUserId) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07003157 if (DEBUG) {
Makoto Onuki2e210c42016-03-30 08:30:36 -07003158 Slog.d(TAG, String.format("handlePackageRemoved: %s user=%d", packageName,
3159 packageUserId));
Makoto Onukicdc78f72016-03-21 15:47:52 -07003160 }
Makoto Onukib08790c2016-06-23 14:05:46 -07003161 cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ false);
Makoto Onuki9e1f5592016-06-08 12:30:23 -07003162
3163 verifyStates();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003164 }
3165
Makoto Onuki9ac59d02016-04-26 11:23:14 -07003166 private void handlePackageDataCleared(String packageName, int packageUserId) {
3167 if (DEBUG) {
3168 Slog.d(TAG, String.format("handlePackageDataCleared: %s user=%d", packageName,
3169 packageUserId));
Makoto Onukicdc78f72016-03-21 15:47:52 -07003170 }
Makoto Onukib08790c2016-06-23 14:05:46 -07003171 cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ true);
3172
3173 verifyStates();
3174 }
3175
3176 private void handlePackageChanged(String packageName, int packageUserId) {
Makoto Onuki82fb2eb2017-03-31 16:58:26 -07003177 if (!isPackageInstalled(packageName, packageUserId)) {
3178 // Probably disabled, which is the same thing as uninstalled.
3179 handlePackageRemoved(packageName, packageUserId);
3180 return;
3181 }
Makoto Onukib08790c2016-06-23 14:05:46 -07003182 if (DEBUG) {
3183 Slog.d(TAG, String.format("handlePackageChanged: %s user=%d", packageName,
3184 packageUserId));
3185 }
3186
3187 // Activities may be disabled or enabled. Just rescan the package.
3188 synchronized (mLock) {
3189 final ShortcutUser user = getUserShortcutsLocked(packageUserId);
3190
Makoto Onuki4e6cef42016-07-13 16:14:01 -07003191 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07003192 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07003193
3194 verifyStates();
Makoto Onukicdc78f72016-03-21 15:47:52 -07003195 }
3196
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003197 // === PackageManager interaction ===
Makoto Onuki0acbb142016-03-22 17:02:57 -07003198
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003199 /**
3200 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
3201 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07003202 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003203 final PackageInfo getPackageInfoWithSignatures(String packageName, @UserIdInt int userId) {
3204 return getPackageInfo(packageName, userId, true);
Makoto Onuki0acbb142016-03-22 17:02:57 -07003205 }
3206
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003207 /**
3208 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
3209 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07003210 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003211 final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId) {
3212 return getPackageInfo(packageName, userId, false);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003213 }
3214
Makoto Onuki905e8852016-03-28 10:40:58 -07003215 int injectGetPackageUid(@NonNull String packageName, @UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003216 final long token = injectClearCallingIdentity();
Makoto Onuki905e8852016-03-28 10:40:58 -07003217 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003218 return mIPackageManager.getPackageUid(packageName, PACKAGE_MATCH_FLAGS, userId);
Makoto Onuki905e8852016-03-28 10:40:58 -07003219 } catch (RemoteException e) {
3220 // Shouldn't happen.
3221 Slog.wtf(TAG, "RemoteException", e);
3222 return -1;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003223 } finally {
3224 injectRestoreCallingIdentity(token);
Makoto Onuki905e8852016-03-28 10:40:58 -07003225 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07003226 }
3227
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003228 /**
3229 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
3230 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07003231 @Nullable
Makoto Onuki0acbb142016-03-22 17:02:57 -07003232 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003233 final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId,
3234 boolean getSignatures) {
3235 return isInstalledOrNull(injectPackageInfoWithUninstalled(
3236 packageName, userId, getSignatures));
3237 }
3238
3239 /**
3240 * Do not use directly; this returns uninstalled packages too.
3241 */
3242 @Nullable
3243 @VisibleForTesting
3244 PackageInfo injectPackageInfoWithUninstalled(String packageName, @UserIdInt int userId,
Makoto Onuki0acbb142016-03-22 17:02:57 -07003245 boolean getSignatures) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003246 final long start = getStatStartTime();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003247 final long token = injectClearCallingIdentity();
Makoto Onuki0acbb142016-03-22 17:02:57 -07003248 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003249 return mIPackageManager.getPackageInfo(
3250 packageName, PACKAGE_MATCH_FLAGS
Michal Karpinski528c3e52018-02-07 17:47:10 +00003251 | (getSignatures ? PackageManager.GET_SIGNING_CERTIFICATES : 0),
3252 userId);
Makoto Onuki0acbb142016-03-22 17:02:57 -07003253 } catch (RemoteException e) {
3254 // Shouldn't happen.
3255 Slog.wtf(TAG, "RemoteException", e);
3256 return null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003257 } finally {
3258 injectRestoreCallingIdentity(token);
Makoto Onuki2e210c42016-03-30 08:30:36 -07003259
3260 logDurationStat(
3261 (getSignatures ? Stats.GET_PACKAGE_INFO_WITH_SIG : Stats.GET_PACKAGE_INFO),
3262 start);
Makoto Onuki0acbb142016-03-22 17:02:57 -07003263 }
3264 }
3265
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003266 /**
3267 * Returns {@link ApplicationInfo} unless it's uninstalled or disabled.
3268 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07003269 @Nullable
Makoto Onuki905e8852016-03-28 10:40:58 -07003270 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003271 final ApplicationInfo getApplicationInfo(String packageName, @UserIdInt int userId) {
3272 return isInstalledOrNull(injectApplicationInfoWithUninstalled(packageName, userId));
3273 }
3274
3275 /**
3276 * Do not use directly; this returns uninstalled packages too.
3277 */
3278 @Nullable
3279 @VisibleForTesting
3280 ApplicationInfo injectApplicationInfoWithUninstalled(
3281 String packageName, @UserIdInt int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003282 final long start = getStatStartTime();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003283 final long token = injectClearCallingIdentity();
Makoto Onuki905e8852016-03-28 10:40:58 -07003284 try {
3285 return mIPackageManager.getApplicationInfo(packageName, PACKAGE_MATCH_FLAGS, userId);
3286 } catch (RemoteException e) {
3287 // Shouldn't happen.
3288 Slog.wtf(TAG, "RemoteException", e);
3289 return null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003290 } finally {
3291 injectRestoreCallingIdentity(token);
Makoto Onuki2e210c42016-03-30 08:30:36 -07003292
3293 logDurationStat(Stats.GET_APPLICATION_INFO, start);
Makoto Onuki905e8852016-03-28 10:40:58 -07003294 }
3295 }
3296
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003297 /**
3298 * Returns {@link ActivityInfo} with its metadata unless it's uninstalled or disabled.
3299 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07003300 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003301 final ActivityInfo getActivityInfoWithMetadata(ComponentName activity, @UserIdInt int userId) {
3302 return isInstalledOrNull(injectGetActivityInfoWithMetadataWithUninstalled(
3303 activity, userId));
3304 }
3305
3306 /**
3307 * Do not use directly; this returns uninstalled packages too.
3308 */
3309 @Nullable
3310 @VisibleForTesting
3311 ActivityInfo injectGetActivityInfoWithMetadataWithUninstalled(
3312 ComponentName activity, @UserIdInt int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003313 final long start = getStatStartTime();
Makoto Onuki22fcc682016-05-17 14:52:19 -07003314 final long token = injectClearCallingIdentity();
3315 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07003316 return mIPackageManager.getActivityInfo(activity,
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003317 (PACKAGE_MATCH_FLAGS | PackageManager.GET_META_DATA), userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003318 } catch (RemoteException e) {
3319 // Shouldn't happen.
3320 Slog.wtf(TAG, "RemoteException", e);
3321 return null;
3322 } finally {
3323 injectRestoreCallingIdentity(token);
3324
Makoto Onukib08790c2016-06-23 14:05:46 -07003325 logDurationStat(Stats.GET_ACTIVITY_WITH_METADATA, start);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003326 }
3327 }
3328
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003329 /**
3330 * Return all installed and enabled packages.
3331 */
3332 @NonNull
Makoto Onuki22fcc682016-05-17 14:52:19 -07003333 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003334 final List<PackageInfo> getInstalledPackages(@UserIdInt int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003335 final long start = getStatStartTime();
Makoto Onuki22fcc682016-05-17 14:52:19 -07003336 final long token = injectClearCallingIdentity();
3337 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003338 final List<PackageInfo> all = injectGetPackagesWithUninstalled(userId);
3339
3340 all.removeIf(PACKAGE_NOT_INSTALLED);
3341
3342 return all;
Makoto Onuki22fcc682016-05-17 14:52:19 -07003343 } catch (RemoteException e) {
3344 // Shouldn't happen.
3345 Slog.wtf(TAG, "RemoteException", e);
3346 return null;
3347 } finally {
3348 injectRestoreCallingIdentity(token);
3349
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003350 logDurationStat(Stats.GET_INSTALLED_PACKAGES, start);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003351 }
3352 }
3353
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003354 /**
3355 * Do not use directly; this returns uninstalled packages too.
3356 */
3357 @NonNull
3358 @VisibleForTesting
3359 List<PackageInfo> injectGetPackagesWithUninstalled(@UserIdInt int userId)
3360 throws RemoteException {
3361 final ParceledListSlice<PackageInfo> parceledList =
3362 mIPackageManager.getInstalledPackages(PACKAGE_MATCH_FLAGS, userId);
3363 if (parceledList == null) {
3364 return Collections.emptyList();
3365 }
3366 return parceledList.getList();
3367 }
3368
Makoto Onuki33663282016-08-22 16:19:04 -07003369 private void forUpdatedPackages(@UserIdInt int userId, long lastScanTime, boolean afterOta,
Makoto Onuki22fcc682016-05-17 14:52:19 -07003370 Consumer<ApplicationInfo> callback) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003371 if (DEBUG) {
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003372 Slog.d(TAG, "forUpdatedPackages for user " + userId + ", lastScanTime=" + lastScanTime
3373 + " afterOta=" + afterOta);
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003374 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003375 final List<PackageInfo> list = getInstalledPackages(userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003376 for (int i = list.size() - 1; i >= 0; i--) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003377 final PackageInfo pi = list.get(i);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003378
Makoto Onuki64183d52016-08-08 14:11:34 -07003379 // If the package has been updated since the last scan time, then scan it.
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003380 // Also if it's right after an OTA, always re-scan all apps anyway, since the
3381 // shortcut parser might have changed.
3382 if (afterOta || (pi.lastUpdateTime >= lastScanTime)) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003383 if (DEBUG) {
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003384 Slog.d(TAG, "Found updated package " + pi.packageName
3385 + " updateTime=" + pi.lastUpdateTime);
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003386 }
3387 callback.accept(pi.applicationInfo);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003388 }
3389 }
3390 }
3391
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003392 private boolean isApplicationFlagSet(@NonNull String packageName, int userId, int flags) {
3393 final ApplicationInfo ai = injectApplicationInfoWithUninstalled(packageName, userId);
Makoto Onuki905e8852016-03-28 10:40:58 -07003394 return (ai != null) && ((ai.flags & flags) == flags);
3395 }
3396
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003397 private static boolean isInstalled(@Nullable ApplicationInfo ai) {
Makoto Onuki82fb2eb2017-03-31 16:58:26 -07003398 return (ai != null) && ai.enabled && (ai.flags & ApplicationInfo.FLAG_INSTALLED) != 0;
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003399 }
3400
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08003401 private static boolean isEphemeralApp(@Nullable ApplicationInfo ai) {
Svetoslav Ganov096d3042017-01-30 16:34:13 -08003402 return (ai != null) && ai.isInstantApp();
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08003403 }
3404
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003405 private static boolean isInstalled(@Nullable PackageInfo pi) {
3406 return (pi != null) && isInstalled(pi.applicationInfo);
3407 }
3408
3409 private static boolean isInstalled(@Nullable ActivityInfo ai) {
3410 return (ai != null) && isInstalled(ai.applicationInfo);
3411 }
3412
3413 private static ApplicationInfo isInstalledOrNull(ApplicationInfo ai) {
3414 return isInstalled(ai) ? ai : null;
3415 }
3416
3417 private static PackageInfo isInstalledOrNull(PackageInfo pi) {
3418 return isInstalled(pi) ? pi : null;
3419 }
3420
3421 private static ActivityInfo isInstalledOrNull(ActivityInfo ai) {
3422 return isInstalled(ai) ? ai : null;
3423 }
3424
Makoto Onuki2e210c42016-03-30 08:30:36 -07003425 boolean isPackageInstalled(String packageName, int userId) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003426 return getApplicationInfo(packageName, userId) != null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003427 }
3428
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08003429 boolean isEphemeralApp(String packageName, int userId) {
3430 return isEphemeralApp(getApplicationInfo(packageName, userId));
3431 }
3432
Makoto Onuki22fcc682016-05-17 14:52:19 -07003433 @Nullable
3434 XmlResourceParser injectXmlMetaData(ActivityInfo activityInfo, String key) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07003435 return activityInfo.loadXmlMetaData(mContext.getPackageManager(), key);
Makoto Onuki39686e82016-04-13 18:03:00 -07003436 }
3437
Makoto Onuki157b1622016-06-02 16:13:10 -07003438 @Nullable
3439 Resources injectGetResourcesForApplicationAsUser(String packageName, int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003440 final long start = getStatStartTime();
Makoto Onuki157b1622016-06-02 16:13:10 -07003441 final long token = injectClearCallingIdentity();
3442 try {
3443 return mContext.getPackageManager().getResourcesForApplicationAsUser(
3444 packageName, userId);
3445 } catch (NameNotFoundException e) {
3446 Slog.e(TAG, "Resources for package " + packageName + " not found");
3447 return null;
3448 } finally {
3449 injectRestoreCallingIdentity(token);
3450
3451 logDurationStat(Stats.GET_APPLICATION_RESOURCES, start);
3452 }
3453 }
3454
Makoto Onukib08790c2016-06-23 14:05:46 -07003455 private Intent getMainActivityIntent() {
3456 final Intent intent = new Intent(Intent.ACTION_MAIN);
3457 intent.addCategory(LAUNCHER_INTENT_CATEGORY);
3458 return intent;
3459 }
3460
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003461 /**
3462 * Same as queryIntentActivitiesAsUser, except it makes sure the package is installed,
3463 * and only returns exported activities.
3464 */
3465 @NonNull
3466 @VisibleForTesting
3467 List<ResolveInfo> queryActivities(@NonNull Intent baseIntent,
3468 @NonNull String packageName, @Nullable ComponentName activity, int userId) {
3469
Daulet Zhanguzin82adfcb2020-01-02 17:31:40 +00003470 baseIntent.setPackage(Objects.requireNonNull(packageName));
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003471 if (activity != null) {
3472 baseIntent.setComponent(activity);
3473 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08003474 return queryActivities(baseIntent, userId, /* exportedOnly =*/ true);
3475 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003476
Makoto Onuki2d895c32016-12-02 15:48:40 -08003477 @NonNull
3478 List<ResolveInfo> queryActivities(@NonNull Intent intent, int userId,
3479 boolean exportedOnly) {
3480 final List<ResolveInfo> resolved;
3481 final long token = injectClearCallingIdentity();
3482 try {
3483 resolved =
3484 mContext.getPackageManager().queryIntentActivitiesAsUser(
3485 intent, PACKAGE_MATCH_FLAGS, userId);
3486 } finally {
3487 injectRestoreCallingIdentity(token);
3488 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003489 if (resolved == null || resolved.size() == 0) {
3490 return EMPTY_RESOLVE_INFO;
3491 }
3492 // Make sure the package is installed.
3493 if (!isInstalled(resolved.get(0).activityInfo)) {
3494 return EMPTY_RESOLVE_INFO;
3495 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08003496 if (exportedOnly) {
3497 resolved.removeIf(ACTIVITY_NOT_EXPORTED);
3498 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003499 return resolved;
3500 }
3501
3502 /**
3503 * Return the main activity that is enabled and exported. If multiple activities are found,
3504 * return the first one.
3505 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003506 @Nullable
3507 ComponentName injectGetDefaultMainActivity(@NonNull String packageName, int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003508 final long start = getStatStartTime();
Makoto Onukib08790c2016-06-23 14:05:46 -07003509 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07003510 final List<ResolveInfo> resolved =
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003511 queryActivities(getMainActivityIntent(), packageName, null, userId);
3512 return resolved.size() == 0 ? null : resolved.get(0).activityInfo.getComponentName();
Makoto Onukib08790c2016-06-23 14:05:46 -07003513 } finally {
Makoto Onukib08790c2016-06-23 14:05:46 -07003514 logDurationStat(Stats.GET_LAUNCHER_ACTIVITY, start);
3515 }
3516 }
3517
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003518 /**
3519 * Return whether an activity is enabled, exported and main.
3520 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003521 boolean injectIsMainActivity(@NonNull ComponentName activity, int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003522 final long start = getStatStartTime();
Makoto Onukib08790c2016-06-23 14:05:46 -07003523 try {
Makoto Onuki34145532017-03-14 17:58:36 -07003524 if (activity == null) {
3525 wtf("null activity detected");
3526 return false;
3527 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08003528 if (DUMMY_MAIN_ACTIVITY.equals(activity.getClassName())) {
3529 return true;
3530 }
3531 final List<ResolveInfo> resolved = queryActivities(
3532 getMainActivityIntent(), activity.getPackageName(), activity, userId);
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003533 return resolved.size() > 0;
Makoto Onukib08790c2016-06-23 14:05:46 -07003534 } finally {
Makoto Onukib08790c2016-06-23 14:05:46 -07003535 logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start);
3536 }
3537 }
3538
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003539 /**
Makoto Onuki2d895c32016-12-02 15:48:40 -08003540 * Create a dummy "main activity" component name which is used to create a dynamic shortcut
3541 * with no main activity temporarily.
3542 */
3543 @NonNull
3544 ComponentName getDummyMainActivity(@NonNull String packageName) {
3545 return new ComponentName(packageName, DUMMY_MAIN_ACTIVITY);
3546 }
3547
Makoto Onuki255461f2017-01-10 11:47:25 -08003548 boolean isDummyMainActivity(@Nullable ComponentName name) {
3549 return name != null && DUMMY_MAIN_ACTIVITY.equals(name.getClassName());
3550 }
3551
Makoto Onuki2d895c32016-12-02 15:48:40 -08003552 /**
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003553 * Return all the enabled, exported and main activities from a package.
3554 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003555 @NonNull
3556 List<ResolveInfo> injectGetMainActivities(@NonNull String packageName, int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003557 final long start = getStatStartTime();
Makoto Onukib08790c2016-06-23 14:05:46 -07003558 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003559 return queryActivities(getMainActivityIntent(), packageName, null, userId);
Makoto Onukib08790c2016-06-23 14:05:46 -07003560 } finally {
Makoto Onukib08790c2016-06-23 14:05:46 -07003561 logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start);
3562 }
3563 }
3564
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003565 /**
3566 * Return whether an activity is enabled and exported.
3567 */
3568 @VisibleForTesting
3569 boolean injectIsActivityEnabledAndExported(
3570 @NonNull ComponentName activity, @UserIdInt int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003571 final long start = getStatStartTime();
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003572 try {
3573 return queryActivities(new Intent(), activity.getPackageName(), activity, userId)
3574 .size() > 0;
3575 } finally {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003576 logDurationStat(Stats.IS_ACTIVITY_ENABLED, start);
3577 }
3578 }
3579
Makoto Onuki2d895c32016-12-02 15:48:40 -08003580 /**
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003581 * Get the {@link LauncherApps#ACTION_CONFIRM_PIN_SHORTCUT} or
3582 * {@link LauncherApps#ACTION_CONFIRM_PIN_APPWIDGET} activity in a given package depending on
3583 * the requestType.
Makoto Onuki2d895c32016-12-02 15:48:40 -08003584 */
3585 @Nullable
3586 ComponentName injectGetPinConfirmationActivity(@NonNull String launcherPackageName,
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003587 int launcherUserId, int requestType) {
Daulet Zhanguzin82adfcb2020-01-02 17:31:40 +00003588 Objects.requireNonNull(launcherPackageName);
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003589 String action = requestType == LauncherApps.PinItemRequest.REQUEST_TYPE_SHORTCUT ?
3590 LauncherApps.ACTION_CONFIRM_PIN_SHORTCUT :
3591 LauncherApps.ACTION_CONFIRM_PIN_APPWIDGET;
Makoto Onuki2d895c32016-12-02 15:48:40 -08003592
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003593 final Intent confirmIntent = new Intent(action).setPackage(launcherPackageName);
Makoto Onuki2d895c32016-12-02 15:48:40 -08003594 final List<ResolveInfo> candidates = queryActivities(
3595 confirmIntent, launcherUserId, /* exportedOnly =*/ false);
3596 for (ResolveInfo ri : candidates) {
3597 return ri.activityInfo.getComponentName();
3598 }
3599 return null;
3600 }
3601
Makoto Onukib08790c2016-06-23 14:05:46 -07003602 boolean injectIsSafeModeEnabled() {
3603 final long token = injectClearCallingIdentity();
3604 try {
3605 return IWindowManager.Stub
3606 .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE))
3607 .isSafeModeEnabled();
3608 } catch (RemoteException e) {
3609 return false; // Shouldn't happen though.
3610 } finally {
3611 injectRestoreCallingIdentity(token);
3612 }
3613 }
3614
Makoto Onuki2d895c32016-12-02 15:48:40 -08003615 /**
3616 * If {@code userId} is of a managed profile, return the parent user ID. Otherwise return
3617 * itself.
3618 */
3619 int getParentOrSelfUserId(int userId) {
Sunny Goyal145c8f82018-02-15 14:27:09 -08003620 return mUserManagerInternal.getProfileParentId(userId);
Makoto Onuki2d895c32016-12-02 15:48:40 -08003621 }
3622
Sunny Goyal87a563e2017-01-01 19:42:45 -08003623 void injectSendIntentSender(IntentSender intentSender, Intent extras) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08003624 if (intentSender == null) {
3625 return;
3626 }
3627 try {
Sunny Goyal87a563e2017-01-01 19:42:45 -08003628 intentSender.sendIntent(mContext, /* code= */ 0, extras,
Makoto Onuki2d895c32016-12-02 15:48:40 -08003629 /* onFinished=*/ null, /* handler= */ null);
3630 } catch (SendIntentException e) {
3631 Slog.w(TAG, "sendIntent failed().", e);
3632 }
3633 }
3634
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003635 // === Backup & restore ===
3636
Makoto Onuki0acbb142016-03-22 17:02:57 -07003637 boolean shouldBackupApp(String packageName, int userId) {
Makoto Onuki905e8852016-03-28 10:40:58 -07003638 return isApplicationFlagSet(packageName, userId, ApplicationInfo.FLAG_ALLOW_BACKUP);
Makoto Onuki0acbb142016-03-22 17:02:57 -07003639 }
3640
Makoto Onukia4f89b12017-10-05 10:37:55 -07003641 static boolean shouldBackupApp(PackageInfo pi) {
Makoto Onuki2e210c42016-03-30 08:30:36 -07003642 return (pi.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0;
3643 }
3644
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003645 @Override
Makoto Onuki2e210c42016-03-30 08:30:36 -07003646 public byte[] getBackupPayload(@UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003647 enforceSystem();
3648 if (DEBUG) {
3649 Slog.d(TAG, "Backing up user " + userId);
3650 }
3651 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003652 if (!isUserUnlockedL(userId)) {
3653 wtf("Can't backup: user " + userId + " is locked or not running");
3654 return null;
3655 }
3656
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003657 final ShortcutUser user = getUserShortcutsLocked(userId);
3658 if (user == null) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003659 wtf("Can't backup: user not found: id=" + userId);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003660 return null;
3661 }
3662
Makoto Onukic8c33292016-09-12 16:36:59 -07003663 // Update the signatures for all packages.
3664 user.forAllPackageItems(spi -> spi.refreshPackageSignatureAndSave());
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003665
Makoto Onukie3fffa92018-02-28 16:25:40 -08003666 // Rescan all apps; this will also update the version codes and "allow-backup".
3667 user.forAllPackages(pkg -> pkg.rescanPackageIfNeeded(
3668 /*isNewApp=*/ false, /*forceRescan=*/ true));
3669
Makoto Onukic8c33292016-09-12 16:36:59 -07003670 // Set the version code for the launchers.
Makoto Onukia4f89b12017-10-05 10:37:55 -07003671 user.forAllLaunchers(launcher -> launcher.ensurePackageInfo());
Makoto Onukic8c33292016-09-12 16:36:59 -07003672
3673 // Save to the filesystem.
3674 scheduleSaveUser(userId);
3675 saveDirtyInfo();
3676
Makoto Onuki475c3652017-05-08 14:29:03 -07003677 // Note, in case of backup, we don't have to wait on bitmap saving, because we don't
3678 // back up bitmaps anyway.
3679
Makoto Onukic8c33292016-09-12 16:36:59 -07003680 // Then create the backup payload.
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003681 final ByteArrayOutputStream os = new ByteArrayOutputStream(32 * 1024);
3682 try {
3683 saveUserInternalLocked(userId, os, /* forBackup */ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07003684 } catch (XmlPullParserException | IOException e) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003685 // Shouldn't happen.
3686 Slog.w(TAG, "Backup failed.", e);
3687 return null;
3688 }
Makoto Onukie3fffa92018-02-28 16:25:40 -08003689 byte[] payload = os.toByteArray();
3690 mShortcutDumpFiles.save("backup-1-payload.txt", payload);
3691 return payload;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003692 }
3693 }
3694
3695 @Override
Makoto Onuki2e210c42016-03-30 08:30:36 -07003696 public void applyRestore(byte[] payload, @UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003697 enforceSystem();
3698 if (DEBUG) {
3699 Slog.d(TAG, "Restoring user " + userId);
3700 }
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003701 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003702 if (!isUserUnlockedL(userId)) {
3703 wtf("Can't restore: user " + userId + " is locked or not running");
3704 return;
3705 }
Makoto Onuki50a320e2017-05-31 14:38:42 -07003706
3707 // Note we print the file timestamps in dumpsys too, but also printing the timestamp
3708 // in the files anyway.
3709 mShortcutDumpFiles.save("restore-0-start.txt", pw -> {
3710 pw.print("Start time: ");
3711 dumpCurrentTime(pw);
3712 pw.println();
3713 });
3714 mShortcutDumpFiles.save("restore-1-payload.xml", payload);
3715
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003716 // Actually do restore.
3717 final ShortcutUser restored;
Makoto Onuki02f338e2016-07-29 09:40:40 -07003718 final ByteArrayInputStream is = new ByteArrayInputStream(payload);
3719 try {
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003720 restored = loadUserInternal(userId, is, /* fromBackup */ true);
3721 } catch (XmlPullParserException | IOException | InvalidFileFormatException e) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003722 Slog.w(TAG, "Restoration failed.", e);
3723 return;
3724 }
Makoto Onuki50a320e2017-05-31 14:38:42 -07003725 mShortcutDumpFiles.save("restore-2.txt", this::dumpInner);
3726
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003727 getUserShortcutsLocked(userId).mergeRestoredFile(restored);
Makoto Onuki2e210c42016-03-30 08:30:36 -07003728
Makoto Onuki50a320e2017-05-31 14:38:42 -07003729 mShortcutDumpFiles.save("restore-3.txt", this::dumpInner);
3730
Makoto Onuki377b7972016-08-09 14:43:55 -07003731 // Rescan all packages to re-publish manifest shortcuts and do other checks.
3732 rescanUpdatedPackagesLocked(userId,
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003733 0 // lastScanTime = 0; rescan all packages.
3734 );
Makoto Onuki2e210c42016-03-30 08:30:36 -07003735
Makoto Onuki50a320e2017-05-31 14:38:42 -07003736 mShortcutDumpFiles.save("restore-4.txt", this::dumpInner);
3737
3738 mShortcutDumpFiles.save("restore-5-finish.txt", pw -> {
3739 pw.print("Finish time: ");
3740 dumpCurrentTime(pw);
3741 pw.println();
3742 });
3743
Makoto Onuki2e210c42016-03-30 08:30:36 -07003744 saveUserLocked(userId);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003745 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07003746 }
3747
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003748 // === Dump ===
3749
3750 @Override
3751 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06003752 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
Makoto Onukic4361e32017-04-03 11:24:25 -07003753 dumpNoCheck(fd, pw, args);
3754 }
3755
3756 @VisibleForTesting
3757 void dumpNoCheck(FileDescriptor fd, PrintWriter pw, String[] args) {
Makoto Onuki20b82212017-10-04 15:03:50 -07003758 final DumpFilter filter = parseDumpArgs(args);
Makoto Onuki50a320e2017-05-31 14:38:42 -07003759
Makoto Onuki20b82212017-10-04 15:03:50 -07003760 if (filter.shouldDumpCheckIn()) {
Makoto Onuki50a320e2017-05-31 14:38:42 -07003761 // Other flags are not supported for checkin.
Makoto Onuki20b82212017-10-04 15:03:50 -07003762 dumpCheckin(pw, filter.shouldCheckInClear());
Makoto Onuki76269922016-07-15 14:58:54 -07003763 } else {
Makoto Onuki20b82212017-10-04 15:03:50 -07003764 if (filter.shouldDumpMain()) {
3765 dumpInner(pw, filter);
Makoto Onuki50a320e2017-05-31 14:38:42 -07003766 pw.println();
3767 }
Makoto Onuki20b82212017-10-04 15:03:50 -07003768 if (filter.shouldDumpUid()) {
Makoto Onuki50a320e2017-05-31 14:38:42 -07003769 dumpUid(pw);
3770 pw.println();
3771 }
Makoto Onuki20b82212017-10-04 15:03:50 -07003772 if (filter.shouldDumpFiles()) {
Makoto Onuki50a320e2017-05-31 14:38:42 -07003773 dumpDumpFiles(pw);
3774 pw.println();
3775 }
Makoto Onuki76269922016-07-15 14:58:54 -07003776 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003777 }
3778
Makoto Onuki20b82212017-10-04 15:03:50 -07003779 private static DumpFilter parseDumpArgs(String[] args) {
3780 final DumpFilter filter = new DumpFilter();
3781 if (args == null) {
3782 return filter;
3783 }
Makoto Onuki55046222016-03-08 10:49:47 -08003784
Makoto Onuki20b82212017-10-04 15:03:50 -07003785 int argIndex = 0;
3786 while (argIndex < args.length) {
3787 final String arg = args[argIndex++];
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003788
Makoto Onuki20b82212017-10-04 15:03:50 -07003789 if ("-c".equals(arg)) {
3790 filter.setDumpCheckIn(true);
3791 continue;
3792 }
3793 if ("--checkin".equals(arg)) {
3794 filter.setDumpCheckIn(true);
3795 filter.setCheckInClear(true);
3796 continue;
3797 }
3798 if ("-a".equals(arg) || "--all".equals(arg)) {
3799 filter.setDumpUid(true);
3800 filter.setDumpFiles(true);
3801 continue;
3802 }
3803 if ("-u".equals(arg) || "--uid".equals(arg)) {
3804 filter.setDumpUid(true);
3805 continue;
3806 }
3807 if ("-f".equals(arg) || "--files".equals(arg)) {
3808 filter.setDumpFiles(true);
3809 continue;
3810 }
3811 if ("-n".equals(arg) || "--no-main".equals(arg)) {
3812 filter.setDumpMain(false);
3813 continue;
3814 }
3815 if ("--user".equals(arg)) {
3816 if (argIndex >= args.length) {
3817 throw new IllegalArgumentException("Missing user ID for --user");
3818 }
3819 try {
3820 filter.addUser(Integer.parseInt(args[argIndex++]));
3821 } catch (NumberFormatException e) {
3822 throw new IllegalArgumentException("Invalid user ID", e);
3823 }
3824 continue;
3825 }
3826 if ("-p".equals(arg) || "--package".equals(arg)) {
3827 if (argIndex >= args.length) {
3828 throw new IllegalArgumentException("Missing package name for --package");
3829 }
3830 filter.addPackageRegex(args[argIndex++]);
3831 filter.setDumpDetails(false);
3832 continue;
3833 }
3834 if (arg.startsWith("-")) {
3835 throw new IllegalArgumentException("Unknown option " + arg);
3836 }
3837 break;
3838 }
3839 while (argIndex < args.length) {
3840 filter.addPackage(args[argIndex++]);
3841 }
3842 return filter;
3843 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003844
Makoto Onuki20b82212017-10-04 15:03:50 -07003845 static class DumpFilter {
3846 private boolean mDumpCheckIn = false;
3847 private boolean mCheckInClear = false;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003848
Makoto Onuki20b82212017-10-04 15:03:50 -07003849 private boolean mDumpMain = true;
3850 private boolean mDumpUid = false;
3851 private boolean mDumpFiles = false;
Makoto Onuki55046222016-03-08 10:49:47 -08003852
Makoto Onuki20b82212017-10-04 15:03:50 -07003853 private boolean mDumpDetails = true;
3854 private List<Pattern> mPackagePatterns = new ArrayList<>();
3855 private List<Integer> mUsers = new ArrayList<>();
3856
3857 void addPackageRegex(String regex) {
3858 mPackagePatterns.add(Pattern.compile(regex));
3859 }
3860
3861 public void addPackage(String packageName) {
3862 addPackageRegex(Pattern.quote(packageName));
3863 }
3864
3865 void addUser(int userId) {
3866 mUsers.add(userId);
3867 }
3868
3869 boolean isPackageMatch(String packageName) {
3870 if (mPackagePatterns.size() == 0) {
3871 return true;
3872 }
3873 for (int i = 0; i < mPackagePatterns.size(); i++) {
3874 if (mPackagePatterns.get(i).matcher(packageName).find()) {
3875 return true;
Makoto Onuki085a05c2016-08-19 11:39:29 -07003876 }
Makoto Onuki2e210c42016-03-30 08:30:36 -07003877 }
Makoto Onuki20b82212017-10-04 15:03:50 -07003878 return false;
3879 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003880
Makoto Onuki20b82212017-10-04 15:03:50 -07003881 boolean isUserMatch(int userId) {
3882 if (mUsers.size() == 0) {
3883 return true;
3884 }
3885 for (int i = 0; i < mUsers.size(); i++) {
3886 if (mUsers.get(i) == userId) {
3887 return true;
3888 }
3889 }
3890 return false;
3891 }
Makoto Onukia2241832016-07-06 13:28:37 -07003892
Makoto Onuki20b82212017-10-04 15:03:50 -07003893 public boolean shouldDumpCheckIn() {
3894 return mDumpCheckIn;
3895 }
3896
3897 public void setDumpCheckIn(boolean dumpCheckIn) {
3898 mDumpCheckIn = dumpCheckIn;
3899 }
3900
3901 public boolean shouldCheckInClear() {
3902 return mCheckInClear;
3903 }
3904
3905 public void setCheckInClear(boolean checkInClear) {
3906 mCheckInClear = checkInClear;
3907 }
3908
3909 public boolean shouldDumpMain() {
3910 return mDumpMain;
3911 }
3912
3913 public void setDumpMain(boolean dumpMain) {
3914 mDumpMain = dumpMain;
3915 }
3916
3917 public boolean shouldDumpUid() {
3918 return mDumpUid;
3919 }
3920
3921 public void setDumpUid(boolean dumpUid) {
3922 mDumpUid = dumpUid;
3923 }
3924
3925 public boolean shouldDumpFiles() {
3926 return mDumpFiles;
3927 }
3928
3929 public void setDumpFiles(boolean dumpFiles) {
3930 mDumpFiles = dumpFiles;
3931 }
3932
3933 public boolean shouldDumpDetails() {
3934 return mDumpDetails;
3935 }
3936
3937 public void setDumpDetails(boolean dumpDetails) {
3938 mDumpDetails = dumpDetails;
3939 }
3940 }
3941
3942 private void dumpInner(PrintWriter pw) {
3943 dumpInner(pw, new DumpFilter());
3944 }
3945
3946 private void dumpInner(PrintWriter pw, DumpFilter filter) {
3947 synchronized (mLock) {
3948 if (filter.shouldDumpDetails()) {
3949 final long now = injectCurrentTimeMillis();
3950 pw.print("Now: [");
3951 pw.print(now);
3952 pw.print("] ");
3953 pw.print(formatTime(now));
3954
3955 pw.print(" Raw last reset: [");
3956 pw.print(mRawLastResetTime);
3957 pw.print("] ");
3958 pw.print(formatTime(mRawLastResetTime));
3959
3960 final long last = getLastResetTimeLocked();
3961 pw.print(" Last reset: [");
3962 pw.print(last);
3963 pw.print("] ");
3964 pw.print(formatTime(last));
3965
3966 final long next = getNextResetTimeLocked();
3967 pw.print(" Next reset: [");
3968 pw.print(next);
3969 pw.print("] ");
3970 pw.print(formatTime(next));
Makoto Onukie3fffa92018-02-28 16:25:40 -08003971 pw.println();
3972 pw.println();
Makoto Onuki20b82212017-10-04 15:03:50 -07003973
3974 pw.print(" Config:");
3975 pw.print(" Max icon dim: ");
3976 pw.println(mMaxIconDimension);
3977 pw.print(" Icon format: ");
3978 pw.println(mIconPersistFormat);
3979 pw.print(" Icon quality: ");
3980 pw.println(mIconPersistQuality);
3981 pw.print(" saveDelayMillis: ");
3982 pw.println(mSaveDelayMillis);
3983 pw.print(" resetInterval: ");
3984 pw.println(mResetInterval);
3985 pw.print(" maxUpdatesPerInterval: ");
3986 pw.println(mMaxUpdatesPerInterval);
3987 pw.print(" maxShortcutsPerActivity: ");
3988 pw.println(mMaxShortcuts);
3989 pw.println();
3990
Makoto Onuki84d59342018-02-02 09:22:38 -08003991 mStatLogger.dump(pw, " ");
Makoto Onuki20b82212017-10-04 15:03:50 -07003992
3993 pw.println();
3994 pw.print(" #Failures: ");
3995 pw.println(mWtfCount);
3996
3997 if (mLastWtfStacktrace != null) {
3998 pw.print(" Last failure stack trace: ");
3999 pw.println(Log.getStackTraceString(mLastWtfStacktrace));
4000 }
4001
4002 pw.println();
4003 mShortcutBitmapSaver.dumpLocked(pw, " ");
4004
4005 pw.println();
Makoto Onukia2241832016-07-06 13:28:37 -07004006 }
4007
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08004008 for (int i = 0; i < mUsers.size(); i++) {
Makoto Onuki20b82212017-10-04 15:03:50 -07004009 final ShortcutUser user = mUsers.valueAt(i);
4010 if (filter.isUserMatch(user.getUserId())) {
4011 user.dump(pw, " ", filter);
4012 pw.println();
4013 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004014 }
Makoto Onuki708703b2017-12-11 16:38:11 -08004015
4016 for (int i = 0; i < mShortcutNonPersistentUsers.size(); i++) {
4017 final ShortcutNonPersistentUser user = mShortcutNonPersistentUsers.valueAt(i);
4018 if (filter.isUserMatch(user.getUserId())) {
4019 user.dump(pw, " ", filter);
4020 pw.println();
4021 }
4022 }
Makoto Onuki50a320e2017-05-31 14:38:42 -07004023 }
4024 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07004025
Makoto Onuki50a320e2017-05-31 14:38:42 -07004026 private void dumpUid(PrintWriter pw) {
4027 synchronized (mLock) {
4028 pw.println("** SHORTCUT MANAGER UID STATES (dumpsys shortcut -n -u)");
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07004029
4030 for (int i = 0; i < mUidState.size(); i++) {
4031 final int uid = mUidState.keyAt(i);
4032 final int state = mUidState.valueAt(i);
4033 pw.print(" UID=");
4034 pw.print(uid);
4035 pw.print(" state=");
4036 pw.print(state);
4037 if (isProcessStateForeground(state)) {
4038 pw.print(" [FG]");
4039 }
4040 pw.print(" last FG=");
4041 pw.print(mUidLastForegroundElapsedTime.get(uid));
4042 pw.println();
4043 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004044 }
4045 }
4046
Makoto Onuki41066a62016-03-09 16:18:44 -08004047 static String formatTime(long time) {
Neil Fuller9aa7b742019-06-17 11:40:35 +01004048 return TimeMigrationUtils.formatMillisWithFixedFormat(time);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004049 }
4050
Makoto Onuki50a320e2017-05-31 14:38:42 -07004051 private void dumpCurrentTime(PrintWriter pw) {
4052 pw.print(formatTime(injectCurrentTimeMillis()));
4053 }
4054
Makoto Onuki76269922016-07-15 14:58:54 -07004055 /**
4056 * Dumpsys for checkin.
4057 *
4058 * @param clear if true, clear the history information. Some other system services have this
4059 * behavior but shortcut service doesn't for now.
4060 */
4061 private void dumpCheckin(PrintWriter pw, boolean clear) {
4062 synchronized (mLock) {
4063 try {
4064 final JSONArray users = new JSONArray();
4065
4066 for (int i = 0; i < mUsers.size(); i++) {
4067 users.put(mUsers.valueAt(i).dumpCheckin(clear));
4068 }
4069
4070 final JSONObject result = new JSONObject();
4071
4072 result.put(KEY_SHORTCUT, users);
4073 result.put(KEY_LOW_RAM, injectIsLowRamDevice());
4074 result.put(KEY_ICON_SIZE, mMaxIconDimension);
4075
4076 pw.println(result.toString(1));
4077 } catch (JSONException e) {
4078 Slog.e(TAG, "Unable to write in json", e);
4079 }
4080 }
4081 }
4082
Makoto Onuki50a320e2017-05-31 14:38:42 -07004083 private void dumpDumpFiles(PrintWriter pw) {
4084 synchronized (mLock) {
4085 pw.println("** SHORTCUT MANAGER FILES (dumpsys shortcut -n -f)");
4086 mShortcutDumpFiles.dumpAll(pw);
4087 }
4088 }
4089
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004090 // === Shell support ===
4091
4092 @Override
4093 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07004094 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004095
4096 enforceShell();
4097
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07004098 final long token = injectClearCallingIdentity();
4099 try {
Dianne Hackborn354736e2016-08-22 17:00:05 -07004100 final int status = (new MyShellCommand()).exec(this, in, out, err, args, callback,
4101 resultReceiver);
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07004102 resultReceiver.send(status, null);
4103 } finally {
4104 injectRestoreCallingIdentity(token);
4105 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004106 }
4107
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004108 static class CommandException extends Exception {
4109 public CommandException(String message) {
4110 super(message);
4111 }
4112 }
4113
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004114 /**
4115 * Handle "adb shell cmd".
4116 */
4117 private class MyShellCommand extends ShellCommand {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004118
4119 private int mUserId = UserHandle.USER_SYSTEM;
4120
Makoto Onuki02f338e2016-07-29 09:40:40 -07004121 private void parseOptionsLocked(boolean takeUser)
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004122 throws CommandException {
4123 String opt;
4124 while ((opt = getNextOption()) != null) {
4125 switch (opt) {
4126 case "--user":
4127 if (takeUser) {
4128 mUserId = UserHandle.parseUserArg(getNextArgRequired());
Makoto Onuki02f338e2016-07-29 09:40:40 -07004129 if (!isUserUnlockedL(mUserId)) {
Makoto Onukif34c3082016-07-13 10:25:25 -07004130 throw new CommandException(
4131 "User " + mUserId + " is not running or locked");
4132 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004133 break;
4134 }
4135 // fallthrough
4136 default:
4137 throw new CommandException("Unknown option: " + opt);
4138 }
4139 }
4140 }
4141
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004142 @Override
4143 public int onCommand(String cmd) {
4144 if (cmd == null) {
4145 return handleDefaultCommands(cmd);
4146 }
4147 final PrintWriter pw = getOutPrintWriter();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004148 try {
4149 switch (cmd) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004150 case "reset-throttling":
4151 handleResetThrottling();
4152 break;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004153 case "reset-all-throttling":
4154 handleResetAllThrottling();
4155 break;
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004156 case "override-config":
4157 handleOverrideConfig();
4158 break;
4159 case "reset-config":
4160 handleResetConfig();
4161 break;
4162 case "clear-default-launcher":
4163 handleClearDefaultLauncher();
4164 break;
4165 case "get-default-launcher":
4166 handleGetDefaultLauncher();
4167 break;
Makoto Onukiac214972016-04-04 10:19:45 -07004168 case "unload-user":
4169 handleUnloadUser();
4170 break;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004171 case "clear-shortcuts":
4172 handleClearShortcuts();
4173 break;
Makoto Onukib08790c2016-06-23 14:05:46 -07004174 case "verify-states": // hidden command to verify various internal states.
4175 handleVerifyStates();
4176 break;
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004177 default:
4178 return handleDefaultCommands(cmd);
4179 }
4180 } catch (CommandException e) {
4181 pw.println("Error: " + e.getMessage());
4182 return 1;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004183 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004184 pw.println("Success");
4185 return 0;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004186 }
4187
4188 @Override
4189 public void onHelp() {
4190 final PrintWriter pw = getOutPrintWriter();
4191 pw.println("Usage: cmd shortcut COMMAND [options ...]");
4192 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004193 pw.println("cmd shortcut reset-throttling [--user USER_ID]");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004194 pw.println(" Reset throttling for all packages and users");
4195 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004196 pw.println("cmd shortcut reset-all-throttling");
4197 pw.println(" Reset the throttling state for all users");
4198 pw.println();
Makoto Onuki4362a662016-03-08 18:59:09 -08004199 pw.println("cmd shortcut override-config CONFIG");
4200 pw.println(" Override the configuration for testing (will last until reboot)");
4201 pw.println();
4202 pw.println("cmd shortcut reset-config");
4203 pw.println(" Reset the configuration set with \"update-config\"");
4204 pw.println();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004205 pw.println("cmd shortcut clear-default-launcher [--user USER_ID]");
4206 pw.println(" Clear the cached default launcher");
4207 pw.println();
4208 pw.println("cmd shortcut get-default-launcher [--user USER_ID]");
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07004209 pw.println(" Show the default launcher");
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004210 pw.println();
Makoto Onukiac214972016-04-04 10:19:45 -07004211 pw.println("cmd shortcut unload-user [--user USER_ID]");
4212 pw.println(" Unload a user from the memory");
4213 pw.println(" (This should not affect any observable behavior)");
4214 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004215 pw.println("cmd shortcut clear-shortcuts [--user USER_ID] PACKAGE");
4216 pw.println(" Remove all shortcuts from a package, including pinned shortcuts");
4217 pw.println();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004218 }
4219
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004220 private void handleResetThrottling() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07004221 synchronized (mLock) {
4222 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki4554d0e2016-03-14 15:51:41 -07004223
Makoto Onuki02f338e2016-07-29 09:40:40 -07004224 Slog.i(TAG, "cmd: handleResetThrottling: user=" + mUserId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004225
Makoto Onuki02f338e2016-07-29 09:40:40 -07004226 resetThrottlingInner(mUserId);
4227 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004228 }
4229
4230 private void handleResetAllThrottling() {
4231 Slog.i(TAG, "cmd: handleResetAllThrottling");
4232
4233 resetAllThrottlingInner();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004234 }
4235
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004236 private void handleOverrideConfig() throws CommandException {
Makoto Onuki4362a662016-03-08 18:59:09 -08004237 final String config = getNextArgRequired();
4238
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004239 Slog.i(TAG, "cmd: handleOverrideConfig: " + config);
4240
Makoto Onuki4362a662016-03-08 18:59:09 -08004241 synchronized (mLock) {
4242 if (!updateConfigurationLocked(config)) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004243 throw new CommandException("override-config failed. See logcat for details.");
Makoto Onuki4362a662016-03-08 18:59:09 -08004244 }
4245 }
Makoto Onuki4362a662016-03-08 18:59:09 -08004246 }
4247
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004248 private void handleResetConfig() {
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004249 Slog.i(TAG, "cmd: handleResetConfig");
4250
Makoto Onuki4362a662016-03-08 18:59:09 -08004251 synchronized (mLock) {
4252 loadConfigurationLocked();
4253 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004254 }
4255
4256 private void clearLauncher() {
4257 synchronized (mLock) {
Makoto Onuki10305202016-07-14 18:14:08 -07004258 getUserShortcutsLocked(mUserId).forceClearLauncher();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004259 }
4260 }
4261
4262 private void showLauncher() {
4263 synchronized (mLock) {
4264 // This ensures to set the cached launcher. Package name doesn't matter.
4265 hasShortcutHostPermissionInner("-", mUserId);
4266
4267 getOutPrintWriter().println("Launcher: "
Makoto Onuki10305202016-07-14 18:14:08 -07004268 + getUserShortcutsLocked(mUserId).getLastKnownLauncher());
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004269 }
4270 }
4271
4272 private void handleClearDefaultLauncher() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07004273 synchronized (mLock) {
4274 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004275
Makoto Onuki02f338e2016-07-29 09:40:40 -07004276 clearLauncher();
4277 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004278 }
4279
4280 private void handleGetDefaultLauncher() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07004281 synchronized (mLock) {
4282 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004283
Makoto Onuki02f338e2016-07-29 09:40:40 -07004284 clearLauncher();
4285 showLauncher();
4286 }
Makoto Onuki4362a662016-03-08 18:59:09 -08004287 }
Makoto Onukiac214972016-04-04 10:19:45 -07004288
4289 private void handleUnloadUser() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07004290 synchronized (mLock) {
4291 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onukiac214972016-04-04 10:19:45 -07004292
Makoto Onuki02f338e2016-07-29 09:40:40 -07004293 Slog.i(TAG, "cmd: handleUnloadUser: user=" + mUserId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004294
Makoto Onuki01ce92b2017-04-28 12:24:16 -07004295 ShortcutService.this.handleStopUser(mUserId);
Makoto Onuki02f338e2016-07-29 09:40:40 -07004296 }
Makoto Onukiac214972016-04-04 10:19:45 -07004297 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004298
4299 private void handleClearShortcuts() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07004300 synchronized (mLock) {
4301 parseOptionsLocked(/* takeUser =*/ true);
4302 final String packageName = getNextArgRequired();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004303
Makoto Onuki02f338e2016-07-29 09:40:40 -07004304 Slog.i(TAG, "cmd: handleClearShortcuts: user" + mUserId + ", " + packageName);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004305
Makoto Onuki02f338e2016-07-29 09:40:40 -07004306 ShortcutService.this.cleanUpPackageForAllLoadedUsers(packageName, mUserId,
4307 /* appStillExists = */ true);
4308 }
Makoto Onukib08790c2016-06-23 14:05:46 -07004309 }
4310
4311 private void handleVerifyStates() throws CommandException {
4312 try {
4313 verifyStatesForce(); // This will throw when there's an issue.
4314 } catch (Throwable th) {
4315 throw new CommandException(th.getMessage() + "\n" + Log.getStackTraceString(th));
4316 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004317 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004318 }
4319
4320 // === Unit test support ===
4321
4322 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07004323 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004324 long injectCurrentTimeMillis() {
4325 return System.currentTimeMillis();
4326 }
4327
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07004328 @VisibleForTesting
4329 long injectElapsedRealtime() {
4330 return SystemClock.elapsedRealtime();
4331 }
4332
Makoto Onuki475c3652017-05-08 14:29:03 -07004333 @VisibleForTesting
4334 long injectUptimeMillis() {
4335 return SystemClock.uptimeMillis();
4336 }
4337
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004338 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07004339 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004340 int injectBinderCallingUid() {
4341 return getCallingUid();
4342 }
4343
Makoto Onuki7d0fa812018-02-21 11:24:43 -08004344 @VisibleForTesting
4345 int injectBinderCallingPid() {
4346 return getCallingPid();
4347 }
4348
Makoto Onuki31459242016-03-22 11:12:18 -07004349 private int getCallingUserId() {
Makoto Onuki4554d0e2016-03-14 15:51:41 -07004350 return UserHandle.getUserId(injectBinderCallingUid());
4351 }
4352
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07004353 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07004354 @VisibleForTesting
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07004355 long injectClearCallingIdentity() {
4356 return Binder.clearCallingIdentity();
4357 }
4358
4359 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07004360 @VisibleForTesting
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07004361 void injectRestoreCallingIdentity(long token) {
4362 Binder.restoreCallingIdentity(token);
4363 }
4364
Makoto Onuki33663282016-08-22 16:19:04 -07004365 // Injection point.
Makoto Onuki33663282016-08-22 16:19:04 -07004366 String injectBuildFingerprint() {
4367 return Build.FINGERPRINT;
4368 }
4369
Makoto Onukide667372016-03-15 14:29:20 -07004370 final void wtf(String message) {
Makoto Onukib08790c2016-06-23 14:05:46 -07004371 wtf(message, /* exception= */ null);
Makoto Onukide667372016-03-15 14:29:20 -07004372 }
4373
Makoto Onuki2e210c42016-03-30 08:30:36 -07004374 // Injection point.
Makoto Onukia2241832016-07-06 13:28:37 -07004375 void wtf(String message, Throwable e) {
4376 if (e == null) {
4377 e = new RuntimeException("Stacktrace");
4378 }
4379 synchronized (mLock) {
4380 mWtfCount++;
4381 mLastWtfStacktrace = new Exception("Last failure was logged here:");
4382 }
Makoto Onukide667372016-03-15 14:29:20 -07004383 Slog.wtf(TAG, message, e);
4384 }
4385
Makoto Onuki31459242016-03-22 11:12:18 -07004386 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004387 File injectSystemDataPath() {
4388 return Environment.getDataSystemDirectory();
4389 }
4390
Makoto Onuki31459242016-03-22 11:12:18 -07004391 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004392 File injectUserDataPath(@UserIdInt int userId) {
Makoto Onuki55046222016-03-08 10:49:47 -08004393 return new File(Environment.getDataSystemCeDirectory(userId), DIRECTORY_PER_USER);
4394 }
4395
Makoto Onuki50a320e2017-05-31 14:38:42 -07004396 public File getDumpPath() {
4397 return new File(injectUserDataPath(UserHandle.USER_SYSTEM), DIRECTORY_DUMP);
4398 }
4399
Makoto Onuki4362a662016-03-08 18:59:09 -08004400 @VisibleForTesting
Makoto Onuki55046222016-03-08 10:49:47 -08004401 boolean injectIsLowRamDevice() {
4402 return ActivityManager.isLowRamDeviceStatic();
4403 }
4404
Makoto Onuki31459242016-03-22 11:12:18 -07004405 @VisibleForTesting
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07004406 void injectRegisterUidObserver(IUidObserver observer, int which) {
4407 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004408 ActivityManager.getService().registerUidObserver(observer, which,
Dianne Hackborn5614bf52016-11-07 17:26:41 -08004409 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07004410 } catch (RemoteException shouldntHappen) {
4411 }
4412 }
4413
Makoto Onuki55046222016-03-08 10:49:47 -08004414 File getUserBitmapFilePath(@UserIdInt int userId) {
4415 return new File(injectUserDataPath(userId), DIRECTORY_BITMAPS);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004416 }
4417
4418 @VisibleForTesting
Makoto Onuki31459242016-03-22 11:12:18 -07004419 SparseArray<ShortcutUser> getShortcutsForTest() {
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08004420 return mUsers;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004421 }
4422
4423 @VisibleForTesting
Makoto Onukib5a012f2016-06-21 11:13:53 -07004424 int getMaxShortcutsForTest() {
4425 return mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004426 }
4427
4428 @VisibleForTesting
Makoto Onukib6d35232016-04-04 15:57:17 -07004429 int getMaxUpdatesPerIntervalForTest() {
4430 return mMaxUpdatesPerInterval;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004431 }
4432
4433 @VisibleForTesting
Makoto Onuki4362a662016-03-08 18:59:09 -08004434 long getResetIntervalForTest() {
4435 return mResetInterval;
Makoto Onuki55046222016-03-08 10:49:47 -08004436 }
4437
4438 @VisibleForTesting
Makoto Onuki4362a662016-03-08 18:59:09 -08004439 int getMaxIconDimensionForTest() {
4440 return mMaxIconDimension;
4441 }
4442
4443 @VisibleForTesting
4444 CompressFormat getIconPersistFormatForTest() {
4445 return mIconPersistFormat;
4446 }
4447
4448 @VisibleForTesting
4449 int getIconPersistQualityForTest() {
4450 return mIconPersistQuality;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004451 }
Makoto Onuki41066a62016-03-09 16:18:44 -08004452
4453 @VisibleForTesting
Makoto Onuki22fcc682016-05-17 14:52:19 -07004454 ShortcutPackage getPackageShortcutForTest(String packageName, int userId) {
Makoto Onuki41066a62016-03-09 16:18:44 -08004455 synchronized (mLock) {
Makoto Onuki31459242016-03-22 11:12:18 -07004456 final ShortcutUser user = mUsers.get(userId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07004457 if (user == null) return null;
4458
Makoto Onuki22fcc682016-05-17 14:52:19 -07004459 return user.getAllPackagesForTest().get(packageName);
4460 }
4461 }
4462
4463 @VisibleForTesting
4464 ShortcutInfo getPackageShortcutForTest(String packageName, String shortcutId, int userId) {
4465 synchronized (mLock) {
Makoto Onukif34c3082016-07-13 10:25:25 -07004466 final ShortcutPackage pkg = getPackageShortcutForTest(packageName, userId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07004467 if (pkg == null) return null;
4468
4469 return pkg.findShortcutById(shortcutId);
Makoto Onuki41066a62016-03-09 16:18:44 -08004470 }
4471 }
Makoto Onuki7001a612016-05-27 13:24:28 -07004472
Makoto Onukifac592f2016-11-21 13:41:32 -08004473 @VisibleForTesting
4474 ShortcutLauncher getLauncherShortcutForTest(String packageName, int userId) {
4475 synchronized (mLock) {
4476 final ShortcutUser user = mUsers.get(userId);
4477 if (user == null) return null;
4478
4479 return user.getAllLaunchersForTest().get(PackageWithUser.of(userId, packageName));
4480 }
4481 }
4482
Makoto Onuki2d895c32016-12-02 15:48:40 -08004483 @VisibleForTesting
4484 ShortcutRequestPinProcessor getShortcutRequestPinProcessorForTest() {
4485 return mShortcutRequestPinProcessor;
4486 }
4487
Makoto Onuki7001a612016-05-27 13:24:28 -07004488 /**
4489 * Control whether {@link #verifyStates} should be performed. We always perform it during unit
4490 * tests.
4491 */
4492 @VisibleForTesting
4493 boolean injectShouldPerformVerification() {
4494 return DEBUG;
4495 }
4496
4497 /**
4498 * Check various internal states and throws if there's any inconsistency.
4499 * This is normally only enabled during unit tests.
4500 */
4501 final void verifyStates() {
4502 if (injectShouldPerformVerification()) {
4503 verifyStatesInner();
4504 }
4505 }
4506
Makoto Onukib08790c2016-06-23 14:05:46 -07004507 private final void verifyStatesForce() {
4508 verifyStatesInner();
4509 }
4510
Makoto Onuki7001a612016-05-27 13:24:28 -07004511 private void verifyStatesInner() {
Makoto Onuki10305202016-07-14 18:14:08 -07004512 synchronized (mLock) {
Makoto Onuki7001a612016-05-27 13:24:28 -07004513 forEachLoadedUserLocked(u -> u.forAllPackageItems(ShortcutPackageItem::verifyStates));
4514 }
4515 }
Makoto Onuki475c3652017-05-08 14:29:03 -07004516
4517 @VisibleForTesting
4518 void waitForBitmapSavesForTest() {
4519 synchronized (mLock) {
4520 mShortcutBitmapSaver.waitForAllSavesLocked();
4521 }
4522 }
Makoto Onuki41066a62016-03-09 16:18:44 -08004523}