blob: c5c1c0cac43cf7ff5c9e82751471eaa3df49b4f7 [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 Onuki7001a612016-05-27 13:24:28 -070018import android.annotation.IntDef;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080019import android.annotation.NonNull;
20import android.annotation.Nullable;
21import android.annotation.UserIdInt;
Makoto Onuki55046222016-03-08 10:49:47 -080022import android.app.ActivityManager;
Makoto Onuki33525d22016-08-03 15:45:24 -070023import android.app.ActivityManagerInternal;
Makoto Onuki0acbb142016-03-22 17:02:57 -070024import android.app.AppGlobals;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -070025import android.app.IUidObserver;
Makoto Onukiac042502016-05-20 16:39:42 -070026import android.app.usage.UsageStatsManagerInternal;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070027import android.content.BroadcastReceiver;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080028import android.content.ComponentName;
29import android.content.Context;
30import android.content.Intent;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070031import android.content.IntentFilter;
Makoto Onuki22fcc682016-05-17 14:52:19 -070032import android.content.pm.ActivityInfo;
Makoto Onuki0acbb142016-03-22 17:02:57 -070033import android.content.pm.ApplicationInfo;
34import android.content.pm.IPackageManager;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080035import android.content.pm.IShortcutService;
36import android.content.pm.LauncherApps;
37import android.content.pm.LauncherApps.ShortcutQuery;
Makoto Onuki0acbb142016-03-22 17:02:57 -070038import android.content.pm.PackageInfo;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080039import android.content.pm.PackageManager;
Makoto Onuki20c95f82016-05-11 16:51:01 -070040import android.content.pm.PackageManager.NameNotFoundException;
Makoto Onuki2d5b4652016-03-11 16:09:54 -080041import android.content.pm.PackageManagerInternal;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080042import android.content.pm.ParceledListSlice;
Makoto Onuki2d5b4652016-03-11 16:09:54 -080043import android.content.pm.ResolveInfo;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080044import android.content.pm.ShortcutInfo;
45import android.content.pm.ShortcutServiceInternal;
46import android.content.pm.ShortcutServiceInternal.ShortcutChangeListener;
Makoto Onuki157b1622016-06-02 16:13:10 -070047import android.content.res.Resources;
Makoto Onuki22fcc682016-05-17 14:52:19 -070048import android.content.res.XmlResourceParser;
Makoto Onuki55046222016-03-08 10:49:47 -080049import android.graphics.Bitmap;
50import android.graphics.Bitmap.CompressFormat;
Makoto Onuki55046222016-03-08 10:49:47 -080051import android.graphics.Canvas;
52import android.graphics.RectF;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080053import android.graphics.drawable.Icon;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070054import android.net.Uri;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080055import android.os.Binder;
Makoto Onuki33663282016-08-22 16:19:04 -070056import android.os.Build;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080057import android.os.Environment;
Makoto Onuki2e210c42016-03-30 08:30:36 -070058import android.os.FileUtils;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080059import android.os.Handler;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070060import android.os.LocaleList;
Makoto Onukiaa8b94a2016-03-17 13:14:05 -070061import android.os.Looper;
Makoto Onuki55046222016-03-08 10:49:47 -080062import android.os.ParcelFileDescriptor;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080063import android.os.PersistableBundle;
64import android.os.Process;
65import android.os.RemoteException;
66import android.os.ResultReceiver;
Makoto Onuki55046222016-03-08 10:49:47 -080067import android.os.SELinux;
Makoto Onukib08790c2016-06-23 14:05:46 -070068import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070069import android.os.ShellCallback;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080070import android.os.ShellCommand;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -070071import android.os.SystemClock;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080072import android.os.UserHandle;
Makoto Onukicdc78f72016-03-21 15:47:52 -070073import android.os.UserManager;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080074import android.text.TextUtils;
75import android.text.format.Time;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080076import android.util.ArraySet;
77import android.util.AtomicFile;
Makoto Onuki4362a662016-03-08 18:59:09 -080078import android.util.KeyValueListParser;
Makoto Onukiac042502016-05-20 16:39:42 -070079import android.util.Log;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080080import android.util.Slog;
81import android.util.SparseArray;
Makoto Onuki02f338e2016-07-29 09:40:40 -070082import android.util.SparseBooleanArray;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -070083import android.util.SparseIntArray;
84import android.util.SparseLongArray;
Makoto Onuki55046222016-03-08 10:49:47 -080085import android.util.TypedValue;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080086import android.util.Xml;
Makoto Onukib08790c2016-06-23 14:05:46 -070087import android.view.IWindowManager;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080088
89import com.android.internal.annotations.GuardedBy;
90import com.android.internal.annotations.VisibleForTesting;
91import com.android.internal.os.BackgroundThread;
92import com.android.internal.util.FastXmlSerializer;
93import com.android.internal.util.Preconditions;
94import com.android.server.LocalServices;
95import com.android.server.SystemService;
Makoto Onukid99c6f02016-03-28 11:02:54 -070096import com.android.server.pm.ShortcutUser.PackageWithUser;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080097
98import libcore.io.IoUtils;
99
Makoto Onuki76269922016-07-15 14:58:54 -0700100import org.json.JSONArray;
101import org.json.JSONException;
102import org.json.JSONObject;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800103import org.xmlpull.v1.XmlPullParser;
104import org.xmlpull.v1.XmlPullParserException;
105import org.xmlpull.v1.XmlSerializer;
106
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700107import java.io.BufferedInputStream;
108import java.io.BufferedOutputStream;
109import java.io.ByteArrayInputStream;
110import java.io.ByteArrayOutputStream;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800111import java.io.File;
112import java.io.FileDescriptor;
113import java.io.FileInputStream;
114import java.io.FileNotFoundException;
115import java.io.FileOutputStream;
116import java.io.IOException;
Makoto Onuki55046222016-03-08 10:49:47 -0800117import java.io.InputStream;
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700118import java.io.OutputStream;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800119import java.io.PrintWriter;
Makoto Onuki7001a612016-05-27 13:24:28 -0700120import java.lang.annotation.Retention;
121import java.lang.annotation.RetentionPolicy;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800122import java.net.URISyntaxException;
123import java.nio.charset.StandardCharsets;
124import java.util.ArrayList;
Makoto Onuki22fcc682016-05-17 14:52:19 -0700125import java.util.Collections;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800126import java.util.List;
Makoto Onuki106ff7a2016-12-01 10:17:57 -0800127import java.util.Objects;
Makoto Onukic51b2872016-05-04 15:24:50 -0700128import java.util.concurrent.atomic.AtomicBoolean;
Makoto Onuki2e210c42016-03-30 08:30:36 -0700129import java.util.function.Consumer;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800130import java.util.function.Predicate;
131
132/**
133 * TODO:
Makoto Onuki22fcc682016-05-17 14:52:19 -0700134 * - getIconMaxWidth()/getIconMaxHeight() should use xdpi and ydpi.
Makoto Onukib5a012f2016-06-21 11:13:53 -0700135 * -> But TypedValue.applyDimension() doesn't differentiate x and y..?
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800136 *
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700137 * - Detect when already registered instances are passed to APIs again, which might break
Makoto Onukib08790c2016-06-23 14:05:46 -0700138 * internal bitmap handling.
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800139 */
140public class ShortcutService extends IShortcutService.Stub {
Makoto Onuki55046222016-03-08 10:49:47 -0800141 static final String TAG = "ShortcutService";
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800142
Makoto Onuki7001a612016-05-27 13:24:28 -0700143 static final boolean DEBUG = false; // STOPSHIP if true
Makoto Onuki41066a62016-03-09 16:18:44 -0800144 static final boolean DEBUG_LOAD = false; // STOPSHIP if true
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700145 static final boolean DEBUG_PROCSTATE = false; // STOPSHIP if true
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800146
Makoto Onuki4362a662016-03-08 18:59:09 -0800147 @VisibleForTesting
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700148 static final long DEFAULT_RESET_INTERVAL_SEC = 24 * 60 * 60; // 1 day
Makoto Onuki4362a662016-03-08 18:59:09 -0800149
150 @VisibleForTesting
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700151 static final int DEFAULT_MAX_UPDATES_PER_INTERVAL = 10;
Makoto Onuki4362a662016-03-08 18:59:09 -0800152
153 @VisibleForTesting
154 static final int DEFAULT_MAX_SHORTCUTS_PER_APP = 5;
155
156 @VisibleForTesting
157 static final int DEFAULT_MAX_ICON_DIMENSION_DP = 96;
158
159 @VisibleForTesting
160 static final int DEFAULT_MAX_ICON_DIMENSION_LOWRAM_DP = 48;
161
162 @VisibleForTesting
163 static final String DEFAULT_ICON_PERSIST_FORMAT = CompressFormat.PNG.name();
164
165 @VisibleForTesting
166 static final int DEFAULT_ICON_PERSIST_QUALITY = 100;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800167
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700168 @VisibleForTesting
169 static final int DEFAULT_SAVE_DELAY_MS = 3000;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800170
171 @VisibleForTesting
172 static final String FILENAME_BASE_STATE = "shortcut_service.xml";
173
174 @VisibleForTesting
175 static final String DIRECTORY_PER_USER = "shortcut_service";
176
177 @VisibleForTesting
178 static final String FILENAME_USER_PACKAGES = "shortcuts.xml";
179
Makoto Onuki55046222016-03-08 10:49:47 -0800180 static final String DIRECTORY_BITMAPS = "bitmaps";
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800181
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700182 private static final String TAG_ROOT = "root";
183 private static final String TAG_LAST_RESET_TIME = "last_reset_time";
Makoto Onuki55046222016-03-08 10:49:47 -0800184
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700185 private static final String ATTR_VALUE = "value";
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800186
Makoto Onukib08790c2016-06-23 14:05:46 -0700187 private static final String LAUNCHER_INTENT_CATEGORY = Intent.CATEGORY_LAUNCHER;
188
Makoto Onuki76269922016-07-15 14:58:54 -0700189 private static final String KEY_SHORTCUT = "shortcut";
190 private static final String KEY_LOW_RAM = "lowRam";
191 private static final String KEY_ICON_SIZE = "iconSize";
192
Makoto Onuki4362a662016-03-08 18:59:09 -0800193 @VisibleForTesting
194 interface ConfigConstants {
195 /**
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700196 * Key name for the save delay, in milliseconds. (int)
197 */
198 String KEY_SAVE_DELAY_MILLIS = "save_delay_ms";
199
200 /**
Makoto Onuki4362a662016-03-08 18:59:09 -0800201 * Key name for the throttling reset interval, in seconds. (long)
202 */
203 String KEY_RESET_INTERVAL_SEC = "reset_interval_sec";
204
205 /**
206 * Key name for the max number of modifying API calls per app for every interval. (int)
207 */
Makoto Onukib6d35232016-04-04 15:57:17 -0700208 String KEY_MAX_UPDATES_PER_INTERVAL = "max_updates_per_interval";
Makoto Onuki4362a662016-03-08 18:59:09 -0800209
210 /**
211 * Key name for the max icon dimensions in DP, for non-low-memory devices.
212 */
213 String KEY_MAX_ICON_DIMENSION_DP = "max_icon_dimension_dp";
214
215 /**
216 * Key name for the max icon dimensions in DP, for low-memory devices.
217 */
218 String KEY_MAX_ICON_DIMENSION_DP_LOWRAM = "max_icon_dimension_dp_lowram";
219
220 /**
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700221 * Key name for the max dynamic shortcuts per activity. (int)
Makoto Onuki4362a662016-03-08 18:59:09 -0800222 */
223 String KEY_MAX_SHORTCUTS = "max_shortcuts";
224
225 /**
Makoto Onuki41066a62016-03-09 16:18:44 -0800226 * Key name for icon compression quality, 0-100.
Makoto Onuki4362a662016-03-08 18:59:09 -0800227 */
228 String KEY_ICON_QUALITY = "icon_quality";
229
230 /**
231 * Key name for icon compression format: "PNG", "JPEG" or "WEBP"
232 */
233 String KEY_ICON_FORMAT = "icon_format";
234 }
235
Makoto Onuki41066a62016-03-09 16:18:44 -0800236 final Context mContext;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800237
238 private final Object mLock = new Object();
239
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700240 private static List<ResolveInfo> EMPTY_RESOLVE_INFO = new ArrayList<>(0);
241
Mark Renoufe065f7c2016-11-01 11:48:24 -0400242 // Temporarily reverted to anonymous inner class form due to: b/32554459
243 private static Predicate<ResolveInfo> ACTIVITY_NOT_EXPORTED = new Predicate<ResolveInfo>() {
244 public boolean test(ResolveInfo ri) {
245 return !ri.activityInfo.exported;
246 }
247 };
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700248
Mark Renoufe065f7c2016-11-01 11:48:24 -0400249 // Temporarily reverted to anonymous inner class form due to: b/32554459
250 private static Predicate<PackageInfo> PACKAGE_NOT_INSTALLED = new Predicate<PackageInfo>() {
251 public boolean test(PackageInfo pi) {
252 return !isInstalled(pi);
253 }
254 };
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700255
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800256 private final Handler mHandler;
257
258 @GuardedBy("mLock")
259 private final ArrayList<ShortcutChangeListener> mListeners = new ArrayList<>(1);
260
261 @GuardedBy("mLock")
262 private long mRawLastResetTime;
263
264 /**
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -0800265 * User ID -> UserShortcuts
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800266 */
267 @GuardedBy("mLock")
Makoto Onuki31459242016-03-22 11:12:18 -0700268 private final SparseArray<ShortcutUser> mUsers = new SparseArray<>();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800269
270 /**
Makoto Onukib5a012f2016-06-21 11:13:53 -0700271 * Max number of dynamic + manifest shortcuts that each application can have at a time.
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800272 */
Makoto Onukib5a012f2016-06-21 11:13:53 -0700273 private int mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800274
275 /**
Makoto Onukib6d35232016-04-04 15:57:17 -0700276 * Max number of updating API calls that each application can make during the interval.
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800277 */
Makoto Onukib6d35232016-04-04 15:57:17 -0700278 int mMaxUpdatesPerInterval;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800279
280 /**
281 * Actual throttling-reset interval. By default it's a day.
282 */
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800283 private long mResetInterval;
284
Makoto Onuki55046222016-03-08 10:49:47 -0800285 /**
286 * Icon max width/height in pixels.
287 */
288 private int mMaxIconDimension;
289
Makoto Onuki4362a662016-03-08 18:59:09 -0800290 private CompressFormat mIconPersistFormat;
291 private int mIconPersistQuality;
Makoto Onuki55046222016-03-08 10:49:47 -0800292
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700293 private int mSaveDelayMillis;
294
Makoto Onuki0acbb142016-03-22 17:02:57 -0700295 private final IPackageManager mIPackageManager;
Makoto Onuki2d5b4652016-03-11 16:09:54 -0800296 private final PackageManagerInternal mPackageManagerInternal;
Makoto Onukicdc78f72016-03-21 15:47:52 -0700297 private final UserManager mUserManager;
Makoto Onukiac042502016-05-20 16:39:42 -0700298 private final UsageStatsManagerInternal mUsageStatsManagerInternal;
Makoto Onuki33525d22016-08-03 15:45:24 -0700299 private final ActivityManagerInternal mActivityManagerInternal;
Makoto Onuki2d5b4652016-03-11 16:09:54 -0800300
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700301 @GuardedBy("mLock")
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700302 final SparseIntArray mUidState = new SparseIntArray();
303
304 @GuardedBy("mLock")
305 final SparseLongArray mUidLastForegroundElapsedTime = new SparseLongArray();
306
307 @GuardedBy("mLock")
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700308 private List<Integer> mDirtyUserIds = new ArrayList<>();
309
Makoto Onukic51b2872016-05-04 15:24:50 -0700310 private final AtomicBoolean mBootCompleted = new AtomicBoolean();
311
Makoto Onuki905e8852016-03-28 10:40:58 -0700312 private static final int PACKAGE_MATCH_FLAGS =
313 PackageManager.MATCH_DIRECT_BOOT_AWARE
Makoto Onukib08790c2016-06-23 14:05:46 -0700314 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE
315 | PackageManager.MATCH_UNINSTALLED_PACKAGES;
Makoto Onuki905e8852016-03-28 10:40:58 -0700316
Makoto Onuki02f338e2016-07-29 09:40:40 -0700317 @GuardedBy("mLock")
318 final SparseBooleanArray mUnlockedUsers = new SparseBooleanArray();
319
Makoto Onuki2e210c42016-03-30 08:30:36 -0700320 // Stats
321 @VisibleForTesting
322 interface Stats {
323 int GET_DEFAULT_HOME = 0;
324 int GET_PACKAGE_INFO = 1;
325 int GET_PACKAGE_INFO_WITH_SIG = 2;
326 int GET_APPLICATION_INFO = 3;
327 int LAUNCHER_PERMISSION_CHECK = 4;
Makoto Onuki6c1dbd52016-05-02 15:19:32 -0700328 int CLEANUP_DANGLING_BITMAPS = 5;
Makoto Onukib08790c2016-06-23 14:05:46 -0700329 int GET_ACTIVITY_WITH_METADATA = 6;
Makoto Onuki6dd9fb72016-06-01 13:55:54 -0700330 int GET_INSTALLED_PACKAGES = 7;
Makoto Onuki22fcc682016-05-17 14:52:19 -0700331 int CHECK_PACKAGE_CHANGES = 8;
Makoto Onuki157b1622016-06-02 16:13:10 -0700332 int GET_APPLICATION_RESOURCES = 9;
333 int RESOURCE_NAME_LOOKUP = 10;
Makoto Onukib08790c2016-06-23 14:05:46 -0700334 int GET_LAUNCHER_ACTIVITY = 11;
335 int CHECK_LAUNCHER_ACTIVITY = 12;
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700336 int IS_ACTIVITY_ENABLED = 13;
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700337 int PACKAGE_UPDATE_CHECK = 14;
Makoto Onuki085a05c2016-08-19 11:39:29 -0700338 int ASYNC_PRELOAD_USER_DELAY = 15;
Makoto Onuki2e210c42016-03-30 08:30:36 -0700339
Makoto Onuki085a05c2016-08-19 11:39:29 -0700340 int COUNT = ASYNC_PRELOAD_USER_DELAY + 1;
Makoto Onuki2e210c42016-03-30 08:30:36 -0700341 }
342
Makoto Onuki085a05c2016-08-19 11:39:29 -0700343 private static final String[] STAT_LABELS = {
344 "getHomeActivities()",
345 "Launcher permission check",
346 "getPackageInfo()",
347 "getPackageInfo(SIG)",
348 "getApplicationInfo",
349 "cleanupDanglingBitmaps",
350 "getActivity+metadata",
351 "getInstalledPackages",
352 "checkPackageChanges",
353 "getApplicationResources",
354 "resourceNameLookup",
355 "getLauncherActivity",
356 "checkLauncherActivity",
357 "isActivityEnabled",
358 "packageUpdateCheck",
359 "asyncPreloadUserDelay"
360 };
361
Makoto Onuki2e210c42016-03-30 08:30:36 -0700362 final Object mStatLock = new Object();
363
364 @GuardedBy("mStatLock")
365 private final int[] mCountStats = new int[Stats.COUNT];
366
367 @GuardedBy("mStatLock")
368 private final long[] mDurationStats = new long[Stats.COUNT];
369
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700370 private static final int PROCESS_STATE_FOREGROUND_THRESHOLD =
371 ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
372
Makoto Onuki7001a612016-05-27 13:24:28 -0700373 static final int OPERATION_SET = 0;
374 static final int OPERATION_ADD = 1;
375 static final int OPERATION_UPDATE = 2;
376
377 /** @hide */
378 @IntDef(value = {
379 OPERATION_SET,
380 OPERATION_ADD,
381 OPERATION_UPDATE
Makoto Onukib08790c2016-06-23 14:05:46 -0700382 })
Makoto Onuki7001a612016-05-27 13:24:28 -0700383 @Retention(RetentionPolicy.SOURCE)
Makoto Onukib08790c2016-06-23 14:05:46 -0700384 @interface ShortcutOperation {
385 }
Makoto Onuki7001a612016-05-27 13:24:28 -0700386
Makoto Onukia2241832016-07-06 13:28:37 -0700387 @GuardedBy("mLock")
388 private int mWtfCount = 0;
389
390 @GuardedBy("mLock")
391 private Exception mLastWtfStacktrace;
392
Makoto Onukifc4cf2d2016-08-24 11:10:26 -0700393 static class InvalidFileFormatException extends Exception {
394 public InvalidFileFormatException(String message, Throwable cause) {
395 super(message, cause);
396 }
397 }
398
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800399 public ShortcutService(Context context) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700400 this(context, BackgroundThread.get().getLooper(), /*onyForPackgeManagerApis*/ false);
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700401 }
402
403 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700404 ShortcutService(Context context, Looper looper, boolean onlyForPackageManagerApis) {
Makoto Onuki106ff7a2016-12-01 10:17:57 -0800405 if (DEBUG) {
406 Binder.LOG_RUNTIME_EXCEPTION = true;
407 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800408 mContext = Preconditions.checkNotNull(context);
409 LocalServices.addService(ShortcutServiceInternal.class, new LocalService());
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700410 mHandler = new Handler(looper);
Makoto Onuki0acbb142016-03-22 17:02:57 -0700411 mIPackageManager = AppGlobals.getPackageManager();
Makoto Onukiac042502016-05-20 16:39:42 -0700412 mPackageManagerInternal = Preconditions.checkNotNull(
413 LocalServices.getService(PackageManagerInternal.class));
414 mUserManager = Preconditions.checkNotNull(context.getSystemService(UserManager.class));
415 mUsageStatsManagerInternal = Preconditions.checkNotNull(
416 LocalServices.getService(UsageStatsManagerInternal.class));
Makoto Onuki33525d22016-08-03 15:45:24 -0700417 mActivityManagerInternal = Preconditions.checkNotNull(
418 LocalServices.getService(ActivityManagerInternal.class));
Makoto Onukicdc78f72016-03-21 15:47:52 -0700419
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700420 if (onlyForPackageManagerApis) {
421 return; // Don't do anything further. For unit tests only.
422 }
423
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700424 // Register receivers.
425
426 // We need to set a priority, so let's just not use PackageMonitor for now.
427 // TODO Refactor PackageMonitor to support priorities.
428 final IntentFilter packageFilter = new IntentFilter();
429 packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
430 packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
431 packageFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
432 packageFilter.addAction(Intent.ACTION_PACKAGE_DATA_CLEARED);
433 packageFilter.addDataScheme("package");
434 packageFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
435 mContext.registerReceiverAsUser(mPackageMonitor, UserHandle.ALL,
436 packageFilter, null, mHandler);
437
Makoto Onuki10305202016-07-14 18:14:08 -0700438 final IntentFilter preferedActivityFilter = new IntentFilter();
439 preferedActivityFilter.addAction(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
440 preferedActivityFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
441 mContext.registerReceiverAsUser(mPackageMonitor, UserHandle.ALL,
442 preferedActivityFilter, null, mHandler);
443
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700444 final IntentFilter localeFilter = new IntentFilter();
445 localeFilter.addAction(Intent.ACTION_LOCALE_CHANGED);
446 localeFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
447 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL,
448 localeFilter, null, mHandler);
Makoto Onukif34c3082016-07-13 10:25:25 -0700449
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700450 injectRegisterUidObserver(mUidObserver, ActivityManager.UID_OBSERVER_PROCSTATE
451 | ActivityManager.UID_OBSERVER_GONE);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800452 }
453
Makoto Onuki2e210c42016-03-30 08:30:36 -0700454 void logDurationStat(int statId, long start) {
455 synchronized (mStatLock) {
456 mCountStats[statId]++;
Makoto Onuki6c1dbd52016-05-02 15:19:32 -0700457 mDurationStats[statId] += (injectElapsedRealtime() - start);
Makoto Onuki2e210c42016-03-30 08:30:36 -0700458 }
459 }
460
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700461 public String injectGetLocaleTagsForUser(@UserIdInt int userId) {
462 // TODO This should get the per-user locale. b/30123329 b/30119489
463 return LocaleList.getDefault().toLanguageTags();
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700464 }
465
466 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Makoto Onukib08790c2016-06-23 14:05:46 -0700467 @Override
468 public void onUidStateChanged(int uid, int procState) throws RemoteException {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700469 handleOnUidStateChanged(uid, procState);
470 }
471
Makoto Onukib08790c2016-06-23 14:05:46 -0700472 @Override
Dianne Hackborne07641d2016-11-09 15:07:23 -0800473 public void onUidGone(int uid, boolean disabled) throws RemoteException {
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800474 handleOnUidStateChanged(uid, ActivityManager.PROCESS_STATE_NONEXISTENT);
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700475 }
476
Makoto Onukib08790c2016-06-23 14:05:46 -0700477 @Override
478 public void onUidActive(int uid) throws RemoteException {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700479 }
480
Makoto Onukib08790c2016-06-23 14:05:46 -0700481 @Override
Dianne Hackborne07641d2016-11-09 15:07:23 -0800482 public void onUidIdle(int uid, boolean disabled) throws RemoteException {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700483 }
484 };
485
486 void handleOnUidStateChanged(int uid, int procState) {
487 if (DEBUG_PROCSTATE) {
488 Slog.d(TAG, "onUidStateChanged: uid=" + uid + " state=" + procState);
489 }
490 synchronized (mLock) {
491 mUidState.put(uid, procState);
492
493 // We need to keep track of last time an app comes to foreground.
494 // See ShortcutPackage.getApiCallCount() for how it's used.
495 // It doesn't have to be persisted, but it needs to be the elapsed time.
496 if (isProcessStateForeground(procState)) {
497 mUidLastForegroundElapsedTime.put(uid, injectElapsedRealtime());
498 }
499 }
500 }
501
502 private boolean isProcessStateForeground(int processState) {
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800503 return processState <= PROCESS_STATE_FOREGROUND_THRESHOLD;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700504 }
505
506 boolean isUidForegroundLocked(int uid) {
507 if (uid == Process.SYSTEM_UID) {
508 // IUidObserver doesn't report the state of SYSTEM, but it always has bound services,
509 // so it's foreground anyway.
510 return true;
511 }
Makoto Onuki33525d22016-08-03 15:45:24 -0700512 // First, check with the local cache.
513 if (isProcessStateForeground(mUidState.get(uid, ActivityManager.MAX_PROCESS_STATE))) {
514 return true;
515 }
516 // If the cache says background, reach out to AM. Since it'll internally need to hold
517 // the AM lock, we use it as a last resort.
518 return isProcessStateForeground(mActivityManagerInternal.getUidProcessState(uid));
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700519 }
520
521 long getUidLastForegroundElapsedTimeLocked(int uid) {
522 return mUidLastForegroundElapsedTime.get(uid);
523 }
524
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800525 /**
526 * System service lifecycle.
527 */
528 public static final class Lifecycle extends SystemService {
529 final ShortcutService mService;
530
531 public Lifecycle(Context context) {
532 super(context);
533 mService = new ShortcutService(context);
534 }
535
536 @Override
537 public void onStart() {
538 publishBinderService(Context.SHORTCUT_SERVICE, mService);
539 }
540
541 @Override
542 public void onBootPhase(int phase) {
543 mService.onBootPhase(phase);
544 }
545
546 @Override
547 public void onCleanupUser(int userHandle) {
Makoto Onukicdc78f72016-03-21 15:47:52 -0700548 mService.handleCleanupUser(userHandle);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800549 }
550
551 @Override
Makoto Onukif3a572b2016-03-10 12:28:38 -0800552 public void onUnlockUser(int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -0700553 mService.handleUnlockUser(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800554 }
555 }
556
557 /** lifecycle event */
558 void onBootPhase(int phase) {
559 if (DEBUG) {
560 Slog.d(TAG, "onBootPhase: " + phase);
561 }
562 switch (phase) {
563 case SystemService.PHASE_LOCK_SETTINGS_READY:
564 initialize();
565 break;
Makoto Onukic51b2872016-05-04 15:24:50 -0700566 case SystemService.PHASE_BOOT_COMPLETED:
567 mBootCompleted.set(true);
568 break;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800569 }
570 }
571
572 /** lifecycle event */
Makoto Onukicdc78f72016-03-21 15:47:52 -0700573 void handleUnlockUser(int userId) {
Makoto Onuki22fcc682016-05-17 14:52:19 -0700574 if (DEBUG) {
Makoto Onuki085a05c2016-08-19 11:39:29 -0700575 Slog.d(TAG, "handleUnlockUser: user=" + userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700576 }
Makoto Onukicdc78f72016-03-21 15:47:52 -0700577 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -0700578 mUnlockedUsers.put(userId, true);
Makoto Onukicdc78f72016-03-21 15:47:52 -0700579 }
Makoto Onuki085a05c2016-08-19 11:39:29 -0700580
581 // Preload the user data.
582 // Note, we don't use mHandler here but instead just start a new thread.
583 // This is because mHandler (which uses com.android.internal.os.BackgroundThread) is very
584 // busy at this point and this could take hundreds of milliseconds, which would be too
585 // late since the launcher would already have started.
586 // So we just create a new thread. This code runs rarely, so we don't use a thread pool
587 // or anything.
588 final long start = injectElapsedRealtime();
589 injectRunOnNewThread(() -> {
590 synchronized (mLock) {
591 logDurationStat(Stats.ASYNC_PRELOAD_USER_DELAY, start);
592 getUserShortcutsLocked(userId);
593 }
594 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800595 }
596
597 /** lifecycle event */
Makoto Onukicdc78f72016-03-21 15:47:52 -0700598 void handleCleanupUser(int userId) {
Makoto Onuki02f338e2016-07-29 09:40:40 -0700599 if (DEBUG) {
600 Slog.d(TAG, "handleCleanupUser: user=" + userId);
601 }
Makoto Onukicdc78f72016-03-21 15:47:52 -0700602 synchronized (mLock) {
603 unloadUserLocked(userId);
Makoto Onuki02f338e2016-07-29 09:40:40 -0700604
605 mUnlockedUsers.put(userId, false);
Makoto Onukicdc78f72016-03-21 15:47:52 -0700606 }
607 }
608
609 private void unloadUserLocked(int userId) {
610 if (DEBUG) {
611 Slog.d(TAG, "unloadUserLocked: user=" + userId);
612 }
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700613 // Save all dirty information.
614 saveDirtyInfo();
615
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800616 // Unload
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -0800617 mUsers.delete(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800618 }
619
620 /** Return the base state file name */
621 private AtomicFile getBaseStateFile() {
622 final File path = new File(injectSystemDataPath(), FILENAME_BASE_STATE);
623 path.mkdirs();
624 return new AtomicFile(path);
625 }
626
627 /**
628 * Init the instance. (load the state file, etc)
629 */
630 private void initialize() {
631 synchronized (mLock) {
Makoto Onuki4362a662016-03-08 18:59:09 -0800632 loadConfigurationLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800633 loadBaseStateLocked();
634 }
635 }
636
Makoto Onuki4362a662016-03-08 18:59:09 -0800637 /**
638 * Load the configuration from Settings.
639 */
640 private void loadConfigurationLocked() {
641 updateConfigurationLocked(injectShortcutManagerConstants());
642 }
Makoto Onuki55046222016-03-08 10:49:47 -0800643
Makoto Onuki4362a662016-03-08 18:59:09 -0800644 /**
645 * Load the configuration from Settings.
646 */
647 @VisibleForTesting
648 boolean updateConfigurationLocked(String config) {
649 boolean result = true;
650
651 final KeyValueListParser parser = new KeyValueListParser(',');
652 try {
653 parser.setString(config);
654 } catch (IllegalArgumentException e) {
655 // Failed to parse the settings string, log this and move on
656 // with defaults.
657 Slog.e(TAG, "Bad shortcut manager settings", e);
658 result = false;
659 }
660
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700661 mSaveDelayMillis = Math.max(0, (int) parser.getLong(ConfigConstants.KEY_SAVE_DELAY_MILLIS,
662 DEFAULT_SAVE_DELAY_MS));
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700663
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700664 mResetInterval = Math.max(1, parser.getLong(
Makoto Onuki4362a662016-03-08 18:59:09 -0800665 ConfigConstants.KEY_RESET_INTERVAL_SEC, DEFAULT_RESET_INTERVAL_SEC)
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700666 * 1000L);
Makoto Onuki4362a662016-03-08 18:59:09 -0800667
Makoto Onukib6d35232016-04-04 15:57:17 -0700668 mMaxUpdatesPerInterval = Math.max(0, (int) parser.getLong(
669 ConfigConstants.KEY_MAX_UPDATES_PER_INTERVAL, DEFAULT_MAX_UPDATES_PER_INTERVAL));
Makoto Onuki4362a662016-03-08 18:59:09 -0800670
Makoto Onukib5a012f2016-06-21 11:13:53 -0700671 mMaxShortcuts = Math.max(0, (int) parser.getLong(
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700672 ConfigConstants.KEY_MAX_SHORTCUTS, DEFAULT_MAX_SHORTCUTS_PER_APP));
Makoto Onuki4362a662016-03-08 18:59:09 -0800673
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700674 final int iconDimensionDp = Math.max(1, injectIsLowRamDevice()
Makoto Onuki4362a662016-03-08 18:59:09 -0800675 ? (int) parser.getLong(
Makoto Onukib08790c2016-06-23 14:05:46 -0700676 ConfigConstants.KEY_MAX_ICON_DIMENSION_DP_LOWRAM,
677 DEFAULT_MAX_ICON_DIMENSION_LOWRAM_DP)
Makoto Onuki4362a662016-03-08 18:59:09 -0800678 : (int) parser.getLong(
Makoto Onukib08790c2016-06-23 14:05:46 -0700679 ConfigConstants.KEY_MAX_ICON_DIMENSION_DP,
680 DEFAULT_MAX_ICON_DIMENSION_DP));
Makoto Onuki4362a662016-03-08 18:59:09 -0800681
682 mMaxIconDimension = injectDipToPixel(iconDimensionDp);
683
684 mIconPersistFormat = CompressFormat.valueOf(
685 parser.getString(ConfigConstants.KEY_ICON_FORMAT, DEFAULT_ICON_PERSIST_FORMAT));
686
687 mIconPersistQuality = (int) parser.getLong(
688 ConfigConstants.KEY_ICON_QUALITY,
689 DEFAULT_ICON_PERSIST_QUALITY);
690
691 return result;
692 }
693
694 @VisibleForTesting
695 String injectShortcutManagerConstants() {
696 return android.provider.Settings.Global.getString(
697 mContext.getContentResolver(),
698 android.provider.Settings.Global.SHORTCUT_MANAGER_CONSTANTS);
699 }
700
701 @VisibleForTesting
702 int injectDipToPixel(int dip) {
703 return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip,
704 mContext.getResources().getDisplayMetrics());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800705 }
706
Makoto Onuki55046222016-03-08 10:49:47 -0800707 // === Persisting ===
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800708
709 @Nullable
Makoto Onuki41066a62016-03-09 16:18:44 -0800710 static String parseStringAttribute(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800711 return parser.getAttributeValue(null, attribute);
712 }
713
Makoto Onuki0acbb142016-03-22 17:02:57 -0700714 static boolean parseBooleanAttribute(XmlPullParser parser, String attribute) {
715 return parseLongAttribute(parser, attribute) == 1;
716 }
717
Makoto Onuki41066a62016-03-09 16:18:44 -0800718 static int parseIntAttribute(XmlPullParser parser, String attribute) {
719 return (int) parseLongAttribute(parser, attribute);
720 }
721
Makoto Onukid99c6f02016-03-28 11:02:54 -0700722 static int parseIntAttribute(XmlPullParser parser, String attribute, int def) {
723 return (int) parseLongAttribute(parser, attribute, def);
724 }
725
Makoto Onuki41066a62016-03-09 16:18:44 -0800726 static long parseLongAttribute(XmlPullParser parser, String attribute) {
Makoto Onukid99c6f02016-03-28 11:02:54 -0700727 return parseLongAttribute(parser, attribute, 0);
728 }
729
730 static long parseLongAttribute(XmlPullParser parser, String attribute, long def) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800731 final String value = parseStringAttribute(parser, attribute);
732 if (TextUtils.isEmpty(value)) {
Makoto Onukid99c6f02016-03-28 11:02:54 -0700733 return def;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800734 }
735 try {
736 return Long.parseLong(value);
737 } catch (NumberFormatException e) {
738 Slog.e(TAG, "Error parsing long " + value);
Makoto Onukid99c6f02016-03-28 11:02:54 -0700739 return def;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800740 }
741 }
742
743 @Nullable
Makoto Onuki41066a62016-03-09 16:18:44 -0800744 static ComponentName parseComponentNameAttribute(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800745 final String value = parseStringAttribute(parser, attribute);
746 if (TextUtils.isEmpty(value)) {
747 return null;
748 }
749 return ComponentName.unflattenFromString(value);
750 }
751
752 @Nullable
Makoto Onuki440a1ea2016-07-20 14:21:18 -0700753 static Intent parseIntentAttributeNoDefault(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800754 final String value = parseStringAttribute(parser, attribute);
Makoto Onukib5a012f2016-06-21 11:13:53 -0700755 Intent parsed = null;
756 if (!TextUtils.isEmpty(value)) {
757 try {
758 parsed = Intent.parseUri(value, /* flags =*/ 0);
759 } catch (URISyntaxException e) {
760 Slog.e(TAG, "Error parsing intent", e);
761 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800762 }
Makoto Onuki440a1ea2016-07-20 14:21:18 -0700763 return parsed;
764 }
765
766 @Nullable
767 static Intent parseIntentAttribute(XmlPullParser parser, String attribute) {
768 Intent parsed = parseIntentAttributeNoDefault(parser, attribute);
Makoto Onukib5a012f2016-06-21 11:13:53 -0700769 if (parsed == null) {
770 // Default intent.
771 parsed = new Intent(Intent.ACTION_VIEW);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800772 }
Makoto Onukib5a012f2016-06-21 11:13:53 -0700773 return parsed;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800774 }
775
Makoto Onuki41066a62016-03-09 16:18:44 -0800776 static void writeTagValue(XmlSerializer out, String tag, String value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800777 if (TextUtils.isEmpty(value)) return;
778
779 out.startTag(null, tag);
780 out.attribute(null, ATTR_VALUE, value);
781 out.endTag(null, tag);
782 }
783
Makoto Onuki41066a62016-03-09 16:18:44 -0800784 static void writeTagValue(XmlSerializer out, String tag, long value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800785 writeTagValue(out, tag, Long.toString(value));
786 }
787
Makoto Onuki2d5b4652016-03-11 16:09:54 -0800788 static void writeTagValue(XmlSerializer out, String tag, ComponentName name) throws IOException {
789 if (name == null) return;
790 writeTagValue(out, tag, name.flattenToString());
791 }
792
Makoto Onuki41066a62016-03-09 16:18:44 -0800793 static void writeTagExtra(XmlSerializer out, String tag, PersistableBundle bundle)
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800794 throws IOException, XmlPullParserException {
795 if (bundle == null) return;
796
797 out.startTag(null, tag);
798 bundle.saveToXml(out);
799 out.endTag(null, tag);
800 }
801
Makoto Onuki22fcc682016-05-17 14:52:19 -0700802 static void writeAttr(XmlSerializer out, String name, CharSequence value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800803 if (TextUtils.isEmpty(value)) return;
804
Makoto Onuki22fcc682016-05-17 14:52:19 -0700805 out.attribute(null, name, value.toString());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800806 }
807
Makoto Onuki41066a62016-03-09 16:18:44 -0800808 static void writeAttr(XmlSerializer out, String name, long value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800809 writeAttr(out, name, String.valueOf(value));
810 }
811
Makoto Onuki0acbb142016-03-22 17:02:57 -0700812 static void writeAttr(XmlSerializer out, String name, boolean value) throws IOException {
813 if (value) {
814 writeAttr(out, name, "1");
815 }
816 }
817
Makoto Onuki41066a62016-03-09 16:18:44 -0800818 static void writeAttr(XmlSerializer out, String name, ComponentName comp) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800819 if (comp == null) return;
820 writeAttr(out, name, comp.flattenToString());
821 }
822
Makoto Onuki41066a62016-03-09 16:18:44 -0800823 static void writeAttr(XmlSerializer out, String name, Intent intent) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800824 if (intent == null) return;
825
826 writeAttr(out, name, intent.toUri(/* flags =*/ 0));
827 }
828
829 @VisibleForTesting
830 void saveBaseStateLocked() {
831 final AtomicFile file = getBaseStateFile();
832 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700833 Slog.d(TAG, "Saving to " + file.getBaseFile());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800834 }
835
836 FileOutputStream outs = null;
837 try {
838 outs = file.startWrite();
839
840 // Write to XML
841 XmlSerializer out = new FastXmlSerializer();
842 out.setOutput(outs, StandardCharsets.UTF_8.name());
843 out.startDocument(null, true);
844 out.startTag(null, TAG_ROOT);
845
846 // Body.
847 writeTagValue(out, TAG_LAST_RESET_TIME, mRawLastResetTime);
848
849 // Epilogue.
850 out.endTag(null, TAG_ROOT);
851 out.endDocument();
852
853 // Close.
854 file.finishWrite(outs);
855 } catch (IOException e) {
856 Slog.e(TAG, "Failed to write to file " + file.getBaseFile(), e);
857 file.failWrite(outs);
858 }
859 }
860
861 private void loadBaseStateLocked() {
862 mRawLastResetTime = 0;
863
864 final AtomicFile file = getBaseStateFile();
865 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700866 Slog.d(TAG, "Loading from " + file.getBaseFile());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800867 }
868 try (FileInputStream in = file.openRead()) {
869 XmlPullParser parser = Xml.newPullParser();
870 parser.setInput(in, StandardCharsets.UTF_8.name());
871
872 int type;
873 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
874 if (type != XmlPullParser.START_TAG) {
875 continue;
876 }
877 final int depth = parser.getDepth();
878 // Check the root tag
879 final String tag = parser.getName();
880 if (depth == 1) {
881 if (!TAG_ROOT.equals(tag)) {
882 Slog.e(TAG, "Invalid root tag: " + tag);
883 return;
884 }
885 continue;
886 }
887 // Assume depth == 2
888 switch (tag) {
889 case TAG_LAST_RESET_TIME:
890 mRawLastResetTime = parseLongAttribute(parser, ATTR_VALUE);
891 break;
892 default:
893 Slog.e(TAG, "Invalid tag: " + tag);
894 break;
895 }
896 }
897 } catch (FileNotFoundException e) {
898 // Use the default
Makoto Onukib08790c2016-06-23 14:05:46 -0700899 } catch (IOException | XmlPullParserException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800900 Slog.e(TAG, "Failed to read file " + file.getBaseFile(), e);
901
902 mRawLastResetTime = 0;
903 }
904 // Adjust the last reset time.
905 getLastResetTimeLocked();
906 }
907
Makoto Onuki0eed4412016-07-21 11:21:59 -0700908 @VisibleForTesting
909 final File getUserFile(@UserIdInt int userId) {
910 return new File(injectUserDataPath(userId), FILENAME_USER_PACKAGES);
911 }
912
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800913 private void saveUserLocked(@UserIdInt int userId) {
Makoto Onuki0eed4412016-07-21 11:21:59 -0700914 final File path = getUserFile(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800915 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700916 Slog.d(TAG, "Saving to " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800917 }
Makoto Onuki0eed4412016-07-21 11:21:59 -0700918 path.getParentFile().mkdirs();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800919 final AtomicFile file = new AtomicFile(path);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700920 FileOutputStream os = null;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800921 try {
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700922 os = file.startWrite();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800923
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700924 saveUserInternalLocked(userId, os, /* forBackup= */ false);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800925
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700926 file.finishWrite(os);
Makoto Onuki1e173232016-08-10 10:47:13 -0700927
928 // Remove all dangling bitmap files.
929 cleanupDanglingBitmapDirectoriesLocked(userId);
Makoto Onukib08790c2016-06-23 14:05:46 -0700930 } catch (XmlPullParserException | IOException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800931 Slog.e(TAG, "Failed to write to file " + file.getBaseFile(), e);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700932 file.failWrite(os);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800933 }
934 }
935
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700936 private void saveUserInternalLocked(@UserIdInt int userId, OutputStream os,
937 boolean forBackup) throws IOException, XmlPullParserException {
938
939 final BufferedOutputStream bos = new BufferedOutputStream(os);
940
941 // Write to XML
942 XmlSerializer out = new FastXmlSerializer();
943 out.setOutput(bos, StandardCharsets.UTF_8.name());
944 out.startDocument(null, true);
945
Makoto Onukic51b2872016-05-04 15:24:50 -0700946 getUserShortcutsLocked(userId).saveToXml(out, forBackup);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700947
948 out.endDocument();
949
950 bos.flush();
951 os.flush();
952 }
953
Makoto Onuki41066a62016-03-09 16:18:44 -0800954 static IOException throwForInvalidTag(int depth, String tag) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800955 throw new IOException(String.format("Invalid tag '%s' found at depth %d", tag, depth));
956 }
957
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700958 static void warnForInvalidTag(int depth, String tag) throws IOException {
959 Slog.w(TAG, String.format("Invalid tag '%s' found at depth %d", tag, depth));
960 }
961
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800962 @Nullable
Makoto Onuki31459242016-03-22 11:12:18 -0700963 private ShortcutUser loadUserLocked(@UserIdInt int userId) {
Makoto Onuki0eed4412016-07-21 11:21:59 -0700964 final File path = getUserFile(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800965 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700966 Slog.d(TAG, "Loading from " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800967 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800968 final AtomicFile file = new AtomicFile(path);
969
970 final FileInputStream in;
971 try {
972 in = file.openRead();
973 } catch (FileNotFoundException e) {
974 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700975 Slog.d(TAG, "Not found " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800976 }
977 return null;
978 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800979 try {
Makoto Onukib08790c2016-06-23 14:05:46 -0700980 final ShortcutUser ret = loadUserInternal(userId, in, /* forBackup= */ false);
Makoto Onuki6c1dbd52016-05-02 15:19:32 -0700981 return ret;
Makoto Onukifc4cf2d2016-08-24 11:10:26 -0700982 } catch (IOException | XmlPullParserException | InvalidFileFormatException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800983 Slog.e(TAG, "Failed to read file " + file.getBaseFile(), e);
984 return null;
985 } finally {
986 IoUtils.closeQuietly(in);
987 }
988 }
989
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700990 private ShortcutUser loadUserInternal(@UserIdInt int userId, InputStream is,
Makoto Onukifc4cf2d2016-08-24 11:10:26 -0700991 boolean fromBackup) throws XmlPullParserException, IOException,
992 InvalidFileFormatException {
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700993
994 final BufferedInputStream bis = new BufferedInputStream(is);
995
996 ShortcutUser ret = null;
997 XmlPullParser parser = Xml.newPullParser();
998 parser.setInput(bis, StandardCharsets.UTF_8.name());
999
1000 int type;
1001 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1002 if (type != XmlPullParser.START_TAG) {
1003 continue;
1004 }
1005 final int depth = parser.getDepth();
1006
1007 final String tag = parser.getName();
1008 if (DEBUG_LOAD) {
1009 Slog.d(TAG, String.format("depth=%d type=%d name=%s",
1010 depth, type, tag));
1011 }
1012 if ((depth == 1) && ShortcutUser.TAG_ROOT.equals(tag)) {
1013 ret = ShortcutUser.loadFromXml(this, parser, userId, fromBackup);
1014 continue;
1015 }
1016 throwForInvalidTag(depth, tag);
1017 }
1018 return ret;
1019 }
1020
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001021 private void scheduleSaveBaseState() {
Makoto Onuki0acbb142016-03-22 17:02:57 -07001022 scheduleSaveInner(UserHandle.USER_NULL); // Special case -- use USER_NULL for base state.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001023 }
1024
Makoto Onuki2d5b4652016-03-11 16:09:54 -08001025 void scheduleSaveUser(@UserIdInt int userId) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07001026 scheduleSaveInner(userId);
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001027 }
1028
1029 // In order to re-schedule, we need to reuse the same instance, so keep it in final.
1030 private final Runnable mSaveDirtyInfoRunner = this::saveDirtyInfo;
1031
Makoto Onuki0acbb142016-03-22 17:02:57 -07001032 private void scheduleSaveInner(@UserIdInt int userId) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001033 if (DEBUG) {
1034 Slog.d(TAG, "Scheduling to save for " + userId);
1035 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001036 synchronized (mLock) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001037 if (!mDirtyUserIds.contains(userId)) {
1038 mDirtyUserIds.add(userId);
1039 }
1040 }
1041 // If already scheduled, remove that and re-schedule in N seconds.
1042 mHandler.removeCallbacks(mSaveDirtyInfoRunner);
1043 mHandler.postDelayed(mSaveDirtyInfoRunner, mSaveDelayMillis);
1044 }
1045
1046 @VisibleForTesting
1047 void saveDirtyInfo() {
1048 if (DEBUG) {
1049 Slog.d(TAG, "saveDirtyInfo");
1050 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001051 try {
1052 synchronized (mLock) {
1053 for (int i = mDirtyUserIds.size() - 1; i >= 0; i--) {
1054 final int userId = mDirtyUserIds.get(i);
1055 if (userId == UserHandle.USER_NULL) { // USER_NULL for base state.
1056 saveBaseStateLocked();
1057 } else {
1058 saveUserLocked(userId);
1059 }
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001060 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001061 mDirtyUserIds.clear();
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001062 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001063 } catch (Exception e) {
1064 wtf("Exception in saveDirtyInfo", e);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001065 }
1066 }
1067
1068 /** Return the last reset time. */
1069 long getLastResetTimeLocked() {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001070 updateTimesLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001071 return mRawLastResetTime;
1072 }
1073
1074 /** Return the next reset time. */
1075 long getNextResetTimeLocked() {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001076 updateTimesLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001077 return mRawLastResetTime + mResetInterval;
1078 }
1079
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001080 static boolean isClockValid(long time) {
1081 return time >= 1420070400; // Thu, 01 Jan 2015 00:00:00 GMT
1082 }
1083
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001084 /**
1085 * Update the last reset time.
1086 */
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001087 private void updateTimesLocked() {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001088
1089 final long now = injectCurrentTimeMillis();
1090
1091 final long prevLastResetTime = mRawLastResetTime;
1092
1093 if (mRawLastResetTime == 0) { // first launch.
1094 // TODO Randomize??
1095 mRawLastResetTime = now;
1096 } else if (now < mRawLastResetTime) {
1097 // Clock rewound.
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001098 if (isClockValid(now)) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001099 Slog.w(TAG, "Clock rewound");
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001100 // TODO Randomize??
1101 mRawLastResetTime = now;
1102 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001103 } else {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001104 if ((mRawLastResetTime + mResetInterval) <= now) {
1105 final long offset = mRawLastResetTime % mResetInterval;
1106 mRawLastResetTime = ((now / mResetInterval) * mResetInterval) + offset;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001107 }
1108 }
1109 if (prevLastResetTime != mRawLastResetTime) {
1110 scheduleSaveBaseState();
1111 }
1112 }
1113
Makoto Onuki1e173232016-08-10 10:47:13 -07001114 // Requires mLock held, but "Locked" prefix would look weired so we just say "L".
Makoto Onuki02f338e2016-07-29 09:40:40 -07001115 protected boolean isUserUnlockedL(@UserIdInt int userId) {
Makoto Onuki1e173232016-08-10 10:47:13 -07001116 // First, check the local copy.
1117 if (mUnlockedUsers.get(userId)) {
1118 return true;
1119 }
1120 // If the local copy says the user is locked, check with AM for the actual state, since
1121 // the user might just have been unlocked.
1122 // Note we just don't use isUserUnlockingOrUnlocked() here, because it'll return false
1123 // when the user is STOPPING, which we still want to consider as "unlocked".
1124 final long token = injectClearCallingIdentity();
1125 try {
1126 return mUserManager.isUserUnlockingOrUnlocked(userId);
1127 } finally {
1128 injectRestoreCallingIdentity(token);
1129 }
Makoto Onuki9c850012016-07-26 15:50:50 -07001130 }
1131
Makoto Onuki02f338e2016-07-29 09:40:40 -07001132 // Requires mLock held, but "Locked" prefix would look weired so we jsut say "L".
1133 void throwIfUserLockedL(@UserIdInt int userId) {
1134 if (!isUserUnlockedL(userId)) {
Makoto Onuki9c850012016-07-26 15:50:50 -07001135 throw new IllegalStateException("User " + userId + " is locked or not running");
1136 }
1137 }
1138
Makoto Onukicdc78f72016-03-21 15:47:52 -07001139 @GuardedBy("mLock")
1140 @NonNull
Makoto Onuki2e210c42016-03-30 08:30:36 -07001141 private boolean isUserLoadedLocked(@UserIdInt int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07001142 return mUsers.get(userId) != null;
1143 }
1144
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001145 /** Return the per-user state. */
1146 @GuardedBy("mLock")
1147 @NonNull
Makoto Onuki31459242016-03-22 11:12:18 -07001148 ShortcutUser getUserShortcutsLocked(@UserIdInt int userId) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001149 if (!isUserUnlockedL(userId)) {
Makoto Onuki9c850012016-07-26 15:50:50 -07001150 wtf("User still locked");
Makoto Onuki9c850012016-07-26 15:50:50 -07001151 }
1152
Makoto Onuki31459242016-03-22 11:12:18 -07001153 ShortcutUser userPackages = mUsers.get(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001154 if (userPackages == null) {
1155 userPackages = loadUserLocked(userId);
1156 if (userPackages == null) {
Makoto Onukic51b2872016-05-04 15:24:50 -07001157 userPackages = new ShortcutUser(this, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001158 }
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08001159 mUsers.put(userId, userPackages);
Makoto Onuki085a05c2016-08-19 11:39:29 -07001160
1161 // Also when a user's data is first accessed, scan all packages.
1162 checkPackageChanges(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001163 }
1164 return userPackages;
1165 }
1166
Makoto Onuki2e210c42016-03-30 08:30:36 -07001167 void forEachLoadedUserLocked(@NonNull Consumer<ShortcutUser> c) {
1168 for (int i = mUsers.size() - 1; i >= 0; i--) {
1169 c.accept(mUsers.valueAt(i));
1170 }
1171 }
1172
Makoto Onukic8c33292016-09-12 16:36:59 -07001173 /**
1174 * Return the per-user per-package state. If the caller is a publisher, use
1175 * {@link #getPackageShortcutsForPublisherLocked} instead.
1176 */
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001177 @GuardedBy("mLock")
1178 @NonNull
Makoto Onuki31459242016-03-22 11:12:18 -07001179 ShortcutPackage getPackageShortcutsLocked(
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001180 @NonNull String packageName, @UserIdInt int userId) {
Makoto Onukic51b2872016-05-04 15:24:50 -07001181 return getUserShortcutsLocked(userId).getPackageShortcuts(packageName);
Makoto Onukide667372016-03-15 14:29:20 -07001182 }
1183
Makoto Onukic8c33292016-09-12 16:36:59 -07001184 /** Return the per-user per-package state. Use this when the caller is a publisher. */
1185 @GuardedBy("mLock")
1186 @NonNull
1187 ShortcutPackage getPackageShortcutsForPublisherLocked(
1188 @NonNull String packageName, @UserIdInt int userId) {
1189 final ShortcutPackage ret = getUserShortcutsLocked(userId).getPackageShortcuts(packageName);
1190 ret.getUser().onCalledByPublisher(packageName);
1191 return ret;
1192 }
1193
Makoto Onukide667372016-03-15 14:29:20 -07001194 @GuardedBy("mLock")
1195 @NonNull
Makoto Onuki2e210c42016-03-30 08:30:36 -07001196 ShortcutLauncher getLauncherShortcutsLocked(
1197 @NonNull String packageName, @UserIdInt int ownerUserId,
1198 @UserIdInt int launcherUserId) {
1199 return getUserShortcutsLocked(ownerUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07001200 .getLauncherShortcuts(packageName, launcherUserId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001201 }
1202
1203 // === Caller validation ===
1204
Makoto Onuki55046222016-03-08 10:49:47 -08001205 void removeIcon(@UserIdInt int userId, ShortcutInfo shortcut) {
Makoto Onuki1e173232016-08-10 10:47:13 -07001206 // Do not remove the actual bitmap file yet, because if the device crashes before saving
1207 // he XML we'd lose the icon. We just remove all dangling files after saving the XML.
Makoto Onukidd097812016-06-29 13:10:09 -07001208 shortcut.setIconResourceId(0);
1209 shortcut.setIconResName(null);
1210 shortcut.clearFlags(ShortcutInfo.FLAG_HAS_ICON_FILE | ShortcutInfo.FLAG_HAS_ICON_RES);
Makoto Onuki55046222016-03-08 10:49:47 -08001211 }
1212
Makoto Onuki0033b2a2016-04-14 17:19:16 -07001213 public void cleanupBitmapsForPackage(@UserIdInt int userId, String packageName) {
1214 final File packagePath = new File(getUserBitmapFilePath(userId), packageName);
1215 if (!packagePath.isDirectory()) {
1216 return;
1217 }
1218 if (!(FileUtils.deleteContents(packagePath) && packagePath.delete())) {
1219 Slog.w(TAG, "Unable to remove directory " + packagePath);
1220 }
1221 }
1222
Makoto Onuki1e173232016-08-10 10:47:13 -07001223 private void cleanupDanglingBitmapDirectoriesLocked(@UserIdInt int userId) {
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001224 if (DEBUG) {
1225 Slog.d(TAG, "cleanupDanglingBitmaps: userId=" + userId);
1226 }
1227 final long start = injectElapsedRealtime();
1228
Makoto Onuki1e173232016-08-10 10:47:13 -07001229 final ShortcutUser user = getUserShortcutsLocked(userId);
1230
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001231 final File bitmapDir = getUserBitmapFilePath(userId);
1232 final File[] children = bitmapDir.listFiles();
1233 if (children == null) {
1234 return;
1235 }
1236 for (File child : children) {
1237 if (!child.isDirectory()) {
1238 continue;
1239 }
1240 final String packageName = child.getName();
1241 if (DEBUG) {
1242 Slog.d(TAG, "cleanupDanglingBitmaps: Found directory=" + packageName);
1243 }
1244 if (!user.hasPackage(packageName)) {
1245 if (DEBUG) {
1246 Slog.d(TAG, "Removing dangling bitmap directory: " + packageName);
1247 }
1248 cleanupBitmapsForPackage(userId, packageName);
1249 } else {
1250 cleanupDanglingBitmapFilesLocked(userId, user, packageName, child);
1251 }
1252 }
1253 logDurationStat(Stats.CLEANUP_DANGLING_BITMAPS, start);
1254 }
1255
1256 private void cleanupDanglingBitmapFilesLocked(@UserIdInt int userId, @NonNull ShortcutUser user,
1257 @NonNull String packageName, @NonNull File path) {
1258 final ArraySet<String> usedFiles =
Makoto Onukic51b2872016-05-04 15:24:50 -07001259 user.getPackageShortcuts(packageName).getUsedBitmapFiles();
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001260
1261 for (File child : path.listFiles()) {
1262 if (!child.isFile()) {
1263 continue;
1264 }
1265 final String name = child.getName();
1266 if (!usedFiles.contains(name)) {
1267 if (DEBUG) {
1268 Slog.d(TAG, "Removing dangling bitmap file: " + child.getAbsolutePath());
1269 }
1270 child.delete();
1271 }
1272 }
1273 }
1274
Makoto Onuki55046222016-03-08 10:49:47 -08001275 @VisibleForTesting
1276 static class FileOutputStreamWithPath extends FileOutputStream {
1277 private final File mFile;
1278
1279 public FileOutputStreamWithPath(File file) throws FileNotFoundException {
1280 super(file);
1281 mFile = file;
1282 }
1283
1284 public File getFile() {
1285 return mFile;
1286 }
1287 }
1288
1289 /**
1290 * Build the cached bitmap filename for a shortcut icon.
1291 *
1292 * The filename will be based on the ID, except certain characters will be escaped.
1293 */
1294 @VisibleForTesting
1295 FileOutputStreamWithPath openIconFileForWrite(@UserIdInt int userId, ShortcutInfo shortcut)
1296 throws IOException {
1297 final File packagePath = new File(getUserBitmapFilePath(userId),
Makoto Onuki22fcc682016-05-17 14:52:19 -07001298 shortcut.getPackage());
Makoto Onuki55046222016-03-08 10:49:47 -08001299 if (!packagePath.isDirectory()) {
1300 packagePath.mkdirs();
1301 if (!packagePath.isDirectory()) {
1302 throw new IOException("Unable to create directory " + packagePath);
1303 }
1304 SELinux.restorecon(packagePath);
1305 }
1306
1307 final String baseName = String.valueOf(injectCurrentTimeMillis());
Makoto Onukib08790c2016-06-23 14:05:46 -07001308 for (int suffix = 0; ; suffix++) {
Makoto Onuki55046222016-03-08 10:49:47 -08001309 final String filename = (suffix == 0 ? baseName : baseName + "_" + suffix) + ".png";
1310 final File file = new File(packagePath, filename);
1311 if (!file.exists()) {
1312 if (DEBUG) {
1313 Slog.d(TAG, "Saving icon to " + file.getAbsolutePath());
1314 }
1315 return new FileOutputStreamWithPath(file);
1316 }
1317 }
1318 }
1319
1320 void saveIconAndFixUpShortcut(@UserIdInt int userId, ShortcutInfo shortcut) {
1321 if (shortcut.hasIconFile() || shortcut.hasIconResource()) {
1322 return;
1323 }
1324
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001325 final long token = injectClearCallingIdentity();
Makoto Onuki55046222016-03-08 10:49:47 -08001326 try {
1327 // Clear icon info on the shortcut.
Makoto Onukidd097812016-06-29 13:10:09 -07001328 removeIcon(userId, shortcut);
Makoto Onuki55046222016-03-08 10:49:47 -08001329
1330 final Icon icon = shortcut.getIcon();
1331 if (icon == null) {
1332 return; // has no icon
1333 }
1334
Makoto Onukiabe84422016-04-07 09:41:19 -07001335 Bitmap bitmap;
Makoto Onuki55046222016-03-08 10:49:47 -08001336 try {
1337 switch (icon.getType()) {
1338 case Icon.TYPE_RESOURCE: {
1339 injectValidateIconResPackage(shortcut, icon);
1340
1341 shortcut.setIconResourceId(icon.getResId());
1342 shortcut.addFlags(ShortcutInfo.FLAG_HAS_ICON_RES);
1343 return;
1344 }
1345 case Icon.TYPE_BITMAP: {
Makoto Onukiabe84422016-04-07 09:41:19 -07001346 bitmap = icon.getBitmap(); // Don't recycle in this case.
Makoto Onuki55046222016-03-08 10:49:47 -08001347 break;
1348 }
Makoto Onuki55046222016-03-08 10:49:47 -08001349 default:
1350 // This shouldn't happen because we've already validated the icon, but
1351 // just in case.
1352 throw ShortcutInfo.getInvalidIconException();
1353 }
1354 if (bitmap == null) {
1355 Slog.e(TAG, "Null bitmap detected");
1356 return;
1357 }
1358 // Shrink and write to the file.
1359 File path = null;
1360 try {
1361 final FileOutputStreamWithPath out = openIconFileForWrite(userId, shortcut);
1362 try {
1363 path = out.getFile();
1364
Makoto Onukiabe84422016-04-07 09:41:19 -07001365 Bitmap shrunk = shrinkBitmap(bitmap, mMaxIconDimension);
1366 try {
1367 shrunk.compress(mIconPersistFormat, mIconPersistQuality, out);
1368 } finally {
1369 if (bitmap != shrunk) {
1370 shrunk.recycle();
1371 }
1372 }
Makoto Onuki55046222016-03-08 10:49:47 -08001373
1374 shortcut.setBitmapPath(out.getFile().getAbsolutePath());
1375 shortcut.addFlags(ShortcutInfo.FLAG_HAS_ICON_FILE);
1376 } finally {
1377 IoUtils.closeQuietly(out);
1378 }
Makoto Onukib08790c2016-06-23 14:05:46 -07001379 } catch (IOException | RuntimeException e) {
Makoto Onuki55046222016-03-08 10:49:47 -08001380 // STOPSHIP Change wtf to e
1381 Slog.wtf(ShortcutService.TAG, "Unable to write bitmap to file", e);
1382 if (path != null && path.exists()) {
1383 path.delete();
1384 }
1385 }
1386 } finally {
Makoto Onuki55046222016-03-08 10:49:47 -08001387 // Once saved, we won't use the original icon information, so null it out.
1388 shortcut.clearIcon();
1389 }
1390 } finally {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001391 injectRestoreCallingIdentity(token);
Makoto Onuki55046222016-03-08 10:49:47 -08001392 }
1393 }
1394
1395 // Unfortunately we can't do this check in unit tests because we fake creator package names,
1396 // so override in unit tests.
1397 // TODO CTS this case.
1398 void injectValidateIconResPackage(ShortcutInfo shortcut, Icon icon) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07001399 if (!shortcut.getPackage().equals(icon.getResPackage())) {
Makoto Onuki55046222016-03-08 10:49:47 -08001400 throw new IllegalArgumentException(
1401 "Icon resource must reside in shortcut owner package");
1402 }
1403 }
1404
1405 @VisibleForTesting
1406 static Bitmap shrinkBitmap(Bitmap in, int maxSize) {
1407 // Original width/height.
1408 final int ow = in.getWidth();
1409 final int oh = in.getHeight();
1410 if ((ow <= maxSize) && (oh <= maxSize)) {
1411 if (DEBUG) {
1412 Slog.d(TAG, String.format("Icon size %dx%d, no need to shrink", ow, oh));
1413 }
1414 return in;
1415 }
1416 final int longerDimension = Math.max(ow, oh);
1417
1418 // New width and height.
1419 final int nw = ow * maxSize / longerDimension;
1420 final int nh = oh * maxSize / longerDimension;
1421 if (DEBUG) {
1422 Slog.d(TAG, String.format("Icon size %dx%d, shrinking to %dx%d",
1423 ow, oh, nw, nh));
1424 }
1425
1426 final Bitmap scaledBitmap = Bitmap.createBitmap(nw, nh, Bitmap.Config.ARGB_8888);
1427 final Canvas c = new Canvas(scaledBitmap);
1428
1429 final RectF dst = new RectF(0, 0, nw, nh);
1430
1431 c.drawBitmap(in, /*src=*/ null, dst, /* paint =*/ null);
1432
Makoto Onuki55046222016-03-08 10:49:47 -08001433 return scaledBitmap;
1434 }
1435
Makoto Onuki157b1622016-06-02 16:13:10 -07001436 /**
1437 * For a shortcut, update all resource names from resource IDs, and also update all
1438 * resource-based strings.
1439 */
1440 void fixUpShortcutResourceNamesAndValues(ShortcutInfo si) {
1441 final Resources publisherRes = injectGetResourcesForApplicationAsUser(
1442 si.getPackage(), si.getUserId());
1443 if (publisherRes != null) {
1444 final long start = injectElapsedRealtime();
1445 try {
1446 si.lookupAndFillInResourceNames(publisherRes);
1447 } finally {
1448 logDurationStat(Stats.RESOURCE_NAME_LOOKUP, start);
1449 }
1450 si.resolveResourceStrings(publisherRes);
1451 }
1452 }
1453
Makoto Onuki55046222016-03-08 10:49:47 -08001454 // === Caller validation ===
1455
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001456 private boolean isCallerSystem() {
1457 final int callingUid = injectBinderCallingUid();
Makoto Onukib08790c2016-06-23 14:05:46 -07001458 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001459 }
1460
1461 private boolean isCallerShell() {
1462 final int callingUid = injectBinderCallingUid();
1463 return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
1464 }
1465
1466 private void enforceSystemOrShell() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001467 if (!(isCallerSystem() || isCallerShell())) {
1468 throw new SecurityException("Caller must be system or shell");
1469 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001470 }
1471
1472 private void enforceShell() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001473 if (!isCallerShell()) {
1474 throw new SecurityException("Caller must be shell");
1475 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001476 }
1477
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001478 private void enforceSystem() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001479 if (!isCallerSystem()) {
1480 throw new SecurityException("Caller must be system");
1481 }
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001482 }
1483
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001484 private void enforceResetThrottlingPermission() {
1485 if (isCallerSystem()) {
1486 return;
1487 }
Makoto Onuki76269922016-07-15 14:58:54 -07001488 enforceCallingOrSelfPermission(
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001489 android.Manifest.permission.RESET_SHORTCUT_MANAGER_THROTTLING, null);
1490 }
1491
Makoto Onuki76269922016-07-15 14:58:54 -07001492 private void enforceCallingOrSelfPermission(
1493 @NonNull String permission, @Nullable String message) {
1494 if (isCallerSystem()) {
1495 return;
1496 }
1497 injectEnforceCallingPermission(permission, message);
1498 }
1499
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001500 /**
1501 * Somehow overriding ServiceContext.enforceCallingPermission() in the unit tests would confuse
1502 * mockito. So instead we extracted it here and override it in the tests.
1503 */
1504 @VisibleForTesting
1505 void injectEnforceCallingPermission(
1506 @NonNull String permission, @Nullable String message) {
1507 mContext.enforceCallingPermission(permission, message);
1508 }
1509
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001510 private void verifyCaller(@NonNull String packageName, @UserIdInt int userId) {
1511 Preconditions.checkStringNotEmpty(packageName, "packageName");
1512
1513 if (isCallerSystem()) {
1514 return; // no check
1515 }
1516
1517 final int callingUid = injectBinderCallingUid();
1518
1519 // Otherwise, make sure the arguments are valid.
1520 if (UserHandle.getUserId(callingUid) != userId) {
1521 throw new SecurityException("Invalid user-ID");
1522 }
Makoto Onuki55046222016-03-08 10:49:47 -08001523 if (injectGetPackageUid(packageName, userId) == injectBinderCallingUid()) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001524 return; // Caller is valid.
1525 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07001526 throw new SecurityException("Calling package name mismatch");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001527 }
1528
Makoto Onuki157b1622016-06-02 16:13:10 -07001529 // Overridden in unit tests to execute r synchronously.
1530 void injectPostToHandler(Runnable r) {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001531 mHandler.post(r);
1532 }
1533
Makoto Onuki085a05c2016-08-19 11:39:29 -07001534 void injectRunOnNewThread(Runnable r) {
1535 new Thread(r).start();
1536 }
1537
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001538 /**
Makoto Onuki7001a612016-05-27 13:24:28 -07001539 * @throws IllegalArgumentException if {@code numShortcuts} is bigger than
Makoto Onukib08790c2016-06-23 14:05:46 -07001540 * {@link #getMaxActivityShortcuts()}.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001541 */
Makoto Onuki7001a612016-05-27 13:24:28 -07001542 void enforceMaxActivityShortcuts(int numShortcuts) {
Makoto Onukib5a012f2016-06-21 11:13:53 -07001543 if (numShortcuts > mMaxShortcuts) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001544 throw new IllegalArgumentException("Max number of dynamic shortcuts exceeded");
1545 }
1546 }
1547
1548 /**
Makoto Onuki7001a612016-05-27 13:24:28 -07001549 * Return the max number of dynamic + manifest shortcuts for each launcher icon.
1550 */
1551 int getMaxActivityShortcuts() {
Makoto Onukib5a012f2016-06-21 11:13:53 -07001552 return mMaxShortcuts;
Makoto Onuki7001a612016-05-27 13:24:28 -07001553 }
1554
1555 /**
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001556 * - Sends a notification to LauncherApps
1557 * - Write to file
1558 */
Makoto Onuki39686e82016-04-13 18:03:00 -07001559 void packageShortcutsChanged(@NonNull String packageName, @UserIdInt int userId) {
1560 if (DEBUG) {
1561 Slog.d(TAG, String.format(
1562 "Shortcut changes: package=%s, user=%d", packageName, userId));
1563 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001564 notifyListeners(packageName, userId);
1565 scheduleSaveUser(userId);
1566 }
1567
1568 private void notifyListeners(@NonNull String packageName, @UserIdInt int userId) {
Makoto Onuki157b1622016-06-02 16:13:10 -07001569 injectPostToHandler(() -> {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001570 try {
1571 final ArrayList<ShortcutChangeListener> copy;
1572 synchronized (mLock) {
1573 if (!isUserUnlockedL(userId)) {
1574 return;
1575 }
1576
1577 copy = new ArrayList<>(mListeners);
1578 }
1579 // Note onShortcutChanged() needs to be called with the system service permissions.
1580 for (int i = copy.size() - 1; i >= 0; i--) {
1581 copy.get(i).onShortcutChanged(packageName, userId);
1582 }
1583 } catch (Exception ignore) {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001584 }
1585 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001586 }
1587
1588 /**
1589 * Clean up / validate an incoming shortcut.
1590 * - Make sure all mandatory fields are set.
1591 * - Make sure the intent's extras are persistable, and them to set
Makoto Onuki0eed4412016-07-21 11:21:59 -07001592 * {@link ShortcutInfo#mIntentPersistableExtrases}. Also clear its extras.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001593 * - Clear flags.
Makoto Onuki55046222016-03-08 10:49:47 -08001594 *
1595 * TODO Detailed unit tests
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001596 */
Makoto Onuki55046222016-03-08 10:49:47 -08001597 private void fixUpIncomingShortcutInfo(@NonNull ShortcutInfo shortcut, boolean forUpdate) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001598 Preconditions.checkNotNull(shortcut, "Null shortcut detected");
Makoto Onuki22fcc682016-05-17 14:52:19 -07001599 if (shortcut.getActivity() != null) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001600 Preconditions.checkState(
Makoto Onuki22fcc682016-05-17 14:52:19 -07001601 shortcut.getPackage().equals(shortcut.getActivity().getPackageName()),
Makoto Onukib08790c2016-06-23 14:05:46 -07001602 "Cannot publish shortcut: activity " + shortcut.getActivity() + " does not"
1603 + " belong to package " + shortcut.getPackage());
Makoto Onuki13260b6ff2016-07-13 18:03:13 -07001604 Preconditions.checkState(
1605 injectIsMainActivity(shortcut.getActivity(), shortcut.getUserId()),
1606 "Cannot publish shortcut: activity " + shortcut.getActivity() + " is not"
1607 + " main activity");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001608 }
1609
Makoto Onuki55046222016-03-08 10:49:47 -08001610 if (!forUpdate) {
Makoto Onuki106ff7a2016-12-01 10:17:57 -08001611 shortcut.enforceMandatoryFields(/* forPinned= */ false);
Makoto Onukib08790c2016-06-23 14:05:46 -07001612 Preconditions.checkArgument(
1613 injectIsMainActivity(shortcut.getActivity(), shortcut.getUserId()),
1614 "Cannot publish shortcut: " + shortcut.getActivity() + " is not main activity");
Makoto Onuki55046222016-03-08 10:49:47 -08001615 }
1616 if (shortcut.getIcon() != null) {
1617 ShortcutInfo.validateIcon(shortcut.getIcon());
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001618 }
1619
Makoto Onukide667372016-03-15 14:29:20 -07001620 shortcut.replaceFlags(0);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001621 }
1622
Makoto Onukib08790c2016-06-23 14:05:46 -07001623 /**
1624 * When a shortcut has no target activity, set the default one from the package.
1625 */
1626 private void fillInDefaultActivity(List<ShortcutInfo> shortcuts) {
1627
1628 ComponentName defaultActivity = null;
1629 for (int i = shortcuts.size() - 1; i >= 0; i--) {
1630 final ShortcutInfo si = shortcuts.get(i);
1631 if (si.getActivity() == null) {
1632 if (defaultActivity == null) {
1633 defaultActivity = injectGetDefaultMainActivity(
1634 si.getPackage(), si.getUserId());
1635 Preconditions.checkState(defaultActivity != null,
1636 "Launcher activity not found for package " + si.getPackage());
1637 }
1638 si.setActivity(defaultActivity);
1639 }
1640 }
1641 }
1642
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001643 private void assignImplicitRanks(List<ShortcutInfo> shortcuts) {
1644 for (int i = shortcuts.size() - 1; i >= 0; i--) {
1645 shortcuts.get(i).setImplicitRank(i);
1646 }
1647 }
1648
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001649 // === APIs ===
1650
1651 @Override
1652 public boolean setDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1653 @UserIdInt int userId) {
1654 verifyCaller(packageName, userId);
1655
1656 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
1657 final int size = newShortcuts.size();
1658
1659 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001660 throwIfUserLockedL(userId);
1661
Makoto Onukic8c33292016-09-12 16:36:59 -07001662 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001663
Makoto Onuki22fcc682016-05-17 14:52:19 -07001664 ps.ensureImmutableShortcutsNotIncluded(newShortcuts);
1665
Makoto Onukib08790c2016-06-23 14:05:46 -07001666 fillInDefaultActivity(newShortcuts);
1667
Makoto Onuki7001a612016-05-27 13:24:28 -07001668 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_SET);
1669
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001670 // Throttling.
Makoto Onukic51b2872016-05-04 15:24:50 -07001671 if (!ps.tryApiCall()) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001672 return false;
1673 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001674
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001675 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1676 ps.clearAllImplicitRanks();
1677 assignImplicitRanks(newShortcuts);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001678
Makoto Onukidf6da042016-06-16 09:51:40 -07001679 for (int i = 0; i < size; i++) {
1680 fixUpIncomingShortcutInfo(newShortcuts.get(i), /* forUpdate= */ false);
1681 }
1682
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001683 // First, remove all un-pinned; dynamic shortcuts
Makoto Onukic51b2872016-05-04 15:24:50 -07001684 ps.deleteAllDynamicShortcuts();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001685
1686 // Then, add/update all. We need to make sure to take over "pinned" flag.
1687 for (int i = 0; i < size; i++) {
1688 final ShortcutInfo newShortcut = newShortcuts.get(i);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001689 ps.addOrUpdateDynamicShortcut(newShortcut);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001690 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001691
1692 // Lastly, adjust the ranks.
1693 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001694 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001695 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001696
1697 verifyStates();
1698
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001699 return true;
1700 }
1701
1702 @Override
1703 public boolean updateShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1704 @UserIdInt int userId) {
1705 verifyCaller(packageName, userId);
1706
1707 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
Makoto Onuki55046222016-03-08 10:49:47 -08001708 final int size = newShortcuts.size();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001709
1710 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001711 throwIfUserLockedL(userId);
1712
Makoto Onukic8c33292016-09-12 16:36:59 -07001713 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001714
Makoto Onuki22fcc682016-05-17 14:52:19 -07001715 ps.ensureImmutableShortcutsNotIncluded(newShortcuts);
1716
Makoto Onukib08790c2016-06-23 14:05:46 -07001717 // For update, don't fill in the default activity. Having null activity means
1718 // "don't update the activity" here.
1719
Makoto Onuki7001a612016-05-27 13:24:28 -07001720 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_UPDATE);
1721
Makoto Onuki55046222016-03-08 10:49:47 -08001722 // Throttling.
Makoto Onukic51b2872016-05-04 15:24:50 -07001723 if (!ps.tryApiCall()) {
Makoto Onuki55046222016-03-08 10:49:47 -08001724 return false;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001725 }
1726
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001727 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1728 ps.clearAllImplicitRanks();
1729 assignImplicitRanks(newShortcuts);
1730
Makoto Onuki55046222016-03-08 10:49:47 -08001731 for (int i = 0; i < size; i++) {
1732 final ShortcutInfo source = newShortcuts.get(i);
1733 fixUpIncomingShortcutInfo(source, /* forUpdate= */ true);
1734
1735 final ShortcutInfo target = ps.findShortcutById(source.getId());
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001736 if (target == null) {
1737 continue;
1738 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07001739
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001740 if (target.isEnabled() != source.isEnabled()) {
1741 Slog.w(TAG,
1742 "ShortcutInfo.enabled cannot be changed with updateShortcuts()");
1743 }
Makoto Onuki55046222016-03-08 10:49:47 -08001744
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001745 // When updating the rank, we need to insert between existing ranks, so set
1746 // this setRankChanged, and also copy the implicit rank fo adjustRanks().
1747 if (source.hasRank()) {
1748 target.setRankChanged();
1749 target.setImplicitRank(source.getImplicitRank());
1750 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07001751
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001752 final boolean replacingIcon = (source.getIcon() != null);
1753 if (replacingIcon) {
1754 removeIcon(userId, target);
1755 }
Makoto Onuki55046222016-03-08 10:49:47 -08001756
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001757 // Note copyNonNullFieldsFrom() does the "updatable with?" check too.
1758 target.copyNonNullFieldsFrom(source);
Makoto Onuki106ff7a2016-12-01 10:17:57 -08001759 if (target.isFloating()) {
1760 target.setActivity(null);
1761 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001762 target.setTimestamp(injectCurrentTimeMillis());
1763
1764 if (replacingIcon) {
1765 saveIconAndFixUpShortcut(userId, target);
1766 }
1767
1768 // When we're updating any resource related fields, re-extract the res names and
1769 // the values.
1770 if (replacingIcon || source.hasStringResources()) {
1771 fixUpShortcutResourceNamesAndValues(target);
Makoto Onuki55046222016-03-08 10:49:47 -08001772 }
1773 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001774
1775 // Lastly, adjust the ranks.
1776 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001777 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001778 packageShortcutsChanged(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001779
Makoto Onuki7001a612016-05-27 13:24:28 -07001780 verifyStates();
1781
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001782 return true;
1783 }
1784
1785 @Override
Makoto Onukib6d35232016-04-04 15:57:17 -07001786 public boolean addDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001787 @UserIdInt int userId) {
1788 verifyCaller(packageName, userId);
1789
Makoto Onukib6d35232016-04-04 15:57:17 -07001790 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
1791 final int size = newShortcuts.size();
1792
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001793 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001794 throwIfUserLockedL(userId);
1795
Makoto Onukic8c33292016-09-12 16:36:59 -07001796 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001797
Makoto Onuki22fcc682016-05-17 14:52:19 -07001798 ps.ensureImmutableShortcutsNotIncluded(newShortcuts);
1799
Makoto Onukib08790c2016-06-23 14:05:46 -07001800 fillInDefaultActivity(newShortcuts);
1801
Makoto Onuki7001a612016-05-27 13:24:28 -07001802 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_ADD);
1803
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001804 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1805 ps.clearAllImplicitRanks();
1806 assignImplicitRanks(newShortcuts);
1807
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001808 // Throttling.
Makoto Onukic51b2872016-05-04 15:24:50 -07001809 if (!ps.tryApiCall()) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001810 return false;
1811 }
Makoto Onukib6d35232016-04-04 15:57:17 -07001812 for (int i = 0; i < size; i++) {
1813 final ShortcutInfo newShortcut = newShortcuts.get(i);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001814
Makoto Onukib6d35232016-04-04 15:57:17 -07001815 // Validate the shortcut.
1816 fixUpIncomingShortcutInfo(newShortcut, /* forUpdate= */ false);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001817
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001818 // When ranks are changing, we need to insert between ranks, so set the
1819 // "rank changed" flag.
1820 newShortcut.setRankChanged();
1821
Makoto Onukib6d35232016-04-04 15:57:17 -07001822 // Add it.
Makoto Onuki22fcc682016-05-17 14:52:19 -07001823 ps.addOrUpdateDynamicShortcut(newShortcut);
Makoto Onukib6d35232016-04-04 15:57:17 -07001824 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001825
1826 // Lastly, adjust the ranks.
1827 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001828 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001829 packageShortcutsChanged(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001830
Makoto Onuki7001a612016-05-27 13:24:28 -07001831 verifyStates();
1832
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001833 return true;
1834 }
1835
1836 @Override
Makoto Onuki20c95f82016-05-11 16:51:01 -07001837 public void disableShortcuts(String packageName, List shortcutIds,
Makoto Onukid6880792016-06-29 13:37:43 -07001838 CharSequence disabledMessage, int disabledMessageResId, @UserIdInt int userId) {
Makoto Onuki20c95f82016-05-11 16:51:01 -07001839 verifyCaller(packageName, userId);
1840 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
1841
1842 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001843 throwIfUserLockedL(userId);
1844
Makoto Onukic8c33292016-09-12 16:36:59 -07001845 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001846
1847 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds);
1848
Makoto Onukid6880792016-06-29 13:37:43 -07001849 final String disabledMessageString =
1850 (disabledMessage == null) ? null : disabledMessage.toString();
1851
Makoto Onuki22fcc682016-05-17 14:52:19 -07001852 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
1853 ps.disableWithId(Preconditions.checkStringNotEmpty((String) shortcutIds.get(i)),
Makoto Onukid6880792016-06-29 13:37:43 -07001854 disabledMessageString, disabledMessageResId,
Makoto Onuki22fcc682016-05-17 14:52:19 -07001855 /* overrideImmutable=*/ false);
1856 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001857
1858 // We may have removed dynamic shortcuts which may have left a gap, so adjust the ranks.
1859 ps.adjustRanks();
Makoto Onuki22fcc682016-05-17 14:52:19 -07001860 }
1861 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001862
1863 verifyStates();
Makoto Onuki22fcc682016-05-17 14:52:19 -07001864 }
1865
1866 @Override
1867 public void enableShortcuts(String packageName, List shortcutIds, @UserIdInt int userId) {
1868 verifyCaller(packageName, userId);
1869 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
1870
1871 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001872 throwIfUserLockedL(userId);
1873
Makoto Onukic8c33292016-09-12 16:36:59 -07001874 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001875
1876 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds);
1877
1878 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
1879 ps.enableWithId((String) shortcutIds.get(i));
1880 }
Makoto Onuki20c95f82016-05-11 16:51:01 -07001881 }
1882 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001883
1884 verifyStates();
Makoto Onuki20c95f82016-05-11 16:51:01 -07001885 }
1886
1887 @Override
Makoto Onukib6d35232016-04-04 15:57:17 -07001888 public void removeDynamicShortcuts(String packageName, List shortcutIds,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001889 @UserIdInt int userId) {
1890 verifyCaller(packageName, userId);
Makoto Onukib6d35232016-04-04 15:57:17 -07001891 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001892
1893 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001894 throwIfUserLockedL(userId);
1895
Makoto Onukic8c33292016-09-12 16:36:59 -07001896 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001897
1898 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds);
1899
Makoto Onukib6d35232016-04-04 15:57:17 -07001900 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07001901 ps.deleteDynamicWithId(
Makoto Onukib6d35232016-04-04 15:57:17 -07001902 Preconditions.checkStringNotEmpty((String) shortcutIds.get(i)));
1903 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001904
1905 // We may have removed dynamic shortcuts which may have left a gap, so adjust the ranks.
1906 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001907 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001908 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001909
1910 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001911 }
1912
1913 @Override
Makoto Onukib6d35232016-04-04 15:57:17 -07001914 public void removeAllDynamicShortcuts(String packageName, @UserIdInt int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001915 verifyCaller(packageName, userId);
1916
1917 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001918 throwIfUserLockedL(userId);
1919
Makoto Onukic8c33292016-09-12 16:36:59 -07001920 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07001921 ps.deleteAllDynamicShortcuts();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001922 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001923 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001924
1925 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001926 }
1927
1928 @Override
1929 public ParceledListSlice<ShortcutInfo> getDynamicShortcuts(String packageName,
1930 @UserIdInt int userId) {
1931 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07001932
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001933 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001934 throwIfUserLockedL(userId);
1935
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001936 return getShortcutsWithQueryLocked(
1937 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
1938 ShortcutInfo::isDynamic);
1939 }
1940 }
1941
1942 @Override
Makoto Onuki22fcc682016-05-17 14:52:19 -07001943 public ParceledListSlice<ShortcutInfo> getManifestShortcuts(String packageName,
1944 @UserIdInt int userId) {
1945 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07001946
Makoto Onuki22fcc682016-05-17 14:52:19 -07001947 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001948 throwIfUserLockedL(userId);
1949
Makoto Onuki22fcc682016-05-17 14:52:19 -07001950 return getShortcutsWithQueryLocked(
1951 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
1952 ShortcutInfo::isManifestShortcut);
1953 }
1954 }
1955
1956 @Override
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001957 public ParceledListSlice<ShortcutInfo> getPinnedShortcuts(String packageName,
1958 @UserIdInt int userId) {
1959 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07001960
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001961 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001962 throwIfUserLockedL(userId);
1963
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001964 return getShortcutsWithQueryLocked(
1965 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
1966 ShortcutInfo::isPinned);
1967 }
1968 }
1969
1970 private ParceledListSlice<ShortcutInfo> getShortcutsWithQueryLocked(@NonNull String packageName,
1971 @UserIdInt int userId, int cloneFlags, @NonNull Predicate<ShortcutInfo> query) {
1972
1973 final ArrayList<ShortcutInfo> ret = new ArrayList<>();
1974
Makoto Onukic8c33292016-09-12 16:36:59 -07001975 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07001976 ps.findAll(ret, query, cloneFlags);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001977
1978 return new ParceledListSlice<>(ret);
1979 }
1980
1981 @Override
Makoto Onukid6880792016-06-29 13:37:43 -07001982 public int getMaxShortcutCountPerActivity(String packageName, @UserIdInt int userId)
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001983 throws RemoteException {
1984 verifyCaller(packageName, userId);
1985
Makoto Onukib5a012f2016-06-21 11:13:53 -07001986 return mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001987 }
1988
1989 @Override
1990 public int getRemainingCallCount(String packageName, @UserIdInt int userId) {
1991 verifyCaller(packageName, userId);
1992
1993 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001994 throwIfUserLockedL(userId);
1995
Makoto Onukic8c33292016-09-12 16:36:59 -07001996 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07001997 return mMaxUpdatesPerInterval - ps.getApiCallCount();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001998 }
1999 }
2000
2001 @Override
2002 public long getRateLimitResetTime(String packageName, @UserIdInt int userId) {
2003 verifyCaller(packageName, userId);
2004
2005 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002006 throwIfUserLockedL(userId);
2007
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002008 return getNextResetTimeLocked();
2009 }
2010 }
2011
Makoto Onuki55046222016-03-08 10:49:47 -08002012 @Override
Makoto Onuki20c95f82016-05-11 16:51:01 -07002013 public int getIconMaxDimensions(String packageName, int userId) {
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002014 verifyCaller(packageName, userId);
2015
Makoto Onuki55046222016-03-08 10:49:47 -08002016 synchronized (mLock) {
2017 return mMaxIconDimension;
2018 }
2019 }
2020
Makoto Onuki20c95f82016-05-11 16:51:01 -07002021 @Override
2022 public void reportShortcutUsed(String packageName, String shortcutId, int userId) {
2023 verifyCaller(packageName, userId);
2024
Makoto Onukiac042502016-05-20 16:39:42 -07002025 Preconditions.checkNotNull(shortcutId);
2026
2027 if (DEBUG) {
2028 Slog.d(TAG, String.format("reportShortcutUsed: Shortcut %s package %s used on user %d",
2029 shortcutId, packageName, userId));
2030 }
2031
2032 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002033 throwIfUserLockedL(userId);
2034
Makoto Onukic8c33292016-09-12 16:36:59 -07002035 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002036
Makoto Onukiac042502016-05-20 16:39:42 -07002037 if (ps.findShortcutById(shortcutId) == null) {
2038 Log.w(TAG, String.format("reportShortcutUsed: package %s doesn't have shortcut %s",
2039 packageName, shortcutId));
2040 return;
2041 }
2042 }
2043
2044 final long token = injectClearCallingIdentity();
2045 try {
2046 mUsageStatsManagerInternal.reportShortcutUsage(packageName, shortcutId, userId);
2047 } finally {
2048 injectRestoreCallingIdentity(token);
2049 }
Makoto Onuki20c95f82016-05-11 16:51:01 -07002050 }
2051
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002052 /**
Makoto Onukib08790c2016-06-23 14:05:46 -07002053 * Reset all throttling, for developer options and command line. Only system/shell can call
2054 * it.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002055 */
2056 @Override
2057 public void resetThrottling() {
2058 enforceSystemOrShell();
2059
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002060 resetThrottlingInner(getCallingUserId());
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002061 }
2062
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002063 void resetThrottlingInner(@UserIdInt int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002064 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002065 if (!isUserUnlockedL(userId)) {
2066 Log.w(TAG, "User " + userId + " is locked or not running");
2067 return;
2068 }
2069
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002070 getUserShortcutsLocked(userId).resetThrottling();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002071 }
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002072 scheduleSaveUser(userId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002073 Slog.i(TAG, "ShortcutManager: throttling counter reset for user " + userId);
2074 }
2075
2076 void resetAllThrottlingInner() {
2077 synchronized (mLock) {
2078 mRawLastResetTime = injectCurrentTimeMillis();
2079 }
2080 scheduleSaveBaseState();
2081 Slog.i(TAG, "ShortcutManager: throttling counter reset for all users");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002082 }
2083
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002084 @Override
2085 public void onApplicationActive(String packageName, int userId) {
2086 if (DEBUG) {
2087 Slog.d(TAG, "onApplicationActive: package=" + packageName + " userid=" + userId);
2088 }
2089 enforceResetThrottlingPermission();
Makoto Onuki02f338e2016-07-29 09:40:40 -07002090
2091 synchronized (mLock) {
2092 if (!isUserUnlockedL(userId)) {
2093 // This is called by system UI, so no need to throw. Just ignore.
2094 return;
2095 }
2096
2097 getPackageShortcutsLocked(packageName, userId)
2098 .resetRateLimitingForCommandLineNoSaving();
2099 saveUserLocked(userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002100 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002101 }
2102
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002103 // We override this method in unit tests to do a simpler check.
2104 boolean hasShortcutHostPermission(@NonNull String callingPackage, int userId) {
Makoto Onuki10305202016-07-14 18:14:08 -07002105 final long start = injectElapsedRealtime();
2106 try {
2107 return hasShortcutHostPermissionInner(callingPackage, userId);
2108 } finally {
2109 logDurationStat(Stats.LAUNCHER_PERMISSION_CHECK, start);
2110 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002111 }
2112
2113 // This method is extracted so we can directly call this method from unit tests,
2114 // even when hasShortcutPermission() is overridden.
2115 @VisibleForTesting
2116 boolean hasShortcutHostPermissionInner(@NonNull String callingPackage, int userId) {
2117 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002118 throwIfUserLockedL(userId);
2119
Makoto Onuki31459242016-03-22 11:12:18 -07002120 final ShortcutUser user = getUserShortcutsLocked(userId);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002121
Makoto Onuki10305202016-07-14 18:14:08 -07002122 // Always trust the in-memory cache.
2123 final ComponentName cached = user.getCachedLauncher();
2124 if (cached != null) {
2125 if (cached.getPackageName().equals(callingPackage)) {
2126 return true;
2127 }
2128 }
2129 // If the cached one doesn't match, then go ahead
2130
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002131 final List<ResolveInfo> allHomeCandidates = new ArrayList<>();
2132
2133 // Default launcher from package manager.
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07002134 final long startGetHomeActivitiesAsUser = injectElapsedRealtime();
Makoto Onuki10305202016-07-14 18:14:08 -07002135 final ComponentName defaultLauncher = mPackageManagerInternal
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002136 .getHomeActivitiesAsUser(allHomeCandidates, userId);
Makoto Onuki2e210c42016-03-30 08:30:36 -07002137 logDurationStat(Stats.GET_DEFAULT_HOME, startGetHomeActivitiesAsUser);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002138
2139 ComponentName detected;
2140 if (defaultLauncher != null) {
2141 detected = defaultLauncher;
2142 if (DEBUG) {
2143 Slog.v(TAG, "Default launcher from PM: " + detected);
2144 }
2145 } else {
Makoto Onuki10305202016-07-14 18:14:08 -07002146 detected = user.getLastKnownLauncher();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002147
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002148 if (detected != null) {
2149 if (injectIsActivityEnabledAndExported(detected, userId)) {
2150 if (DEBUG) {
2151 Slog.v(TAG, "Cached launcher: " + detected);
2152 }
2153 } else {
2154 Slog.w(TAG, "Cached launcher " + detected + " no longer exists");
2155 detected = null;
Makoto Onuki10305202016-07-14 18:14:08 -07002156 user.clearLauncher();
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002157 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002158 }
2159 }
2160
2161 if (detected == null) {
2162 // If we reach here, that means it's the first check since the user was created,
2163 // and there's already multiple launchers and there's no default set.
2164 // Find the system one with the highest priority.
2165 // (We need to check the priority too because of FallbackHome in Settings.)
2166 // If there's no system launcher yet, then no one can access shortcuts, until
2167 // the user explicitly
2168 final int size = allHomeCandidates.size();
2169
2170 int lastPriority = Integer.MIN_VALUE;
2171 for (int i = 0; i < size; i++) {
2172 final ResolveInfo ri = allHomeCandidates.get(i);
2173 if (!ri.activityInfo.applicationInfo.isSystemApp()) {
2174 continue;
2175 }
2176 if (DEBUG) {
2177 Slog.d(TAG, String.format("hasShortcutPermissionInner: pkg=%s prio=%d",
2178 ri.activityInfo.getComponentName(), ri.priority));
2179 }
2180 if (ri.priority < lastPriority) {
2181 continue;
2182 }
2183 detected = ri.activityInfo.getComponentName();
2184 lastPriority = ri.priority;
2185 }
2186 }
Makoto Onuki2e210c42016-03-30 08:30:36 -07002187
Makoto Onuki10305202016-07-14 18:14:08 -07002188 // Update the cache.
2189 user.setLauncher(detected);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002190 if (detected != null) {
2191 if (DEBUG) {
2192 Slog.v(TAG, "Detected launcher: " + detected);
2193 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002194 return detected.getPackageName().equals(callingPackage);
2195 } else {
2196 // Default launcher not found.
2197 return false;
2198 }
2199 }
2200 }
2201
Makoto Onukicdc78f72016-03-21 15:47:52 -07002202 // === House keeping ===
2203
Makoto Onukib08790c2016-06-23 14:05:46 -07002204 private void cleanUpPackageForAllLoadedUsers(String packageName, @UserIdInt int packageUserId,
2205 boolean appStillExists) {
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002206 synchronized (mLock) {
2207 forEachLoadedUserLocked(user ->
Makoto Onukib08790c2016-06-23 14:05:46 -07002208 cleanUpPackageLocked(packageName, user.getUserId(), packageUserId,
2209 appStillExists));
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002210 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002211 }
2212
Makoto Onuki2e210c42016-03-30 08:30:36 -07002213 /**
2214 * Remove all the information associated with a package. This will really remove all the
2215 * information, including the restore information (i.e. it'll remove packages even if they're
2216 * shadow).
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002217 *
2218 * This is called when an app is uninstalled, or an app gets "clear data"ed.
Makoto Onuki2e210c42016-03-30 08:30:36 -07002219 */
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002220 @VisibleForTesting
Makoto Onukib08790c2016-06-23 14:05:46 -07002221 void cleanUpPackageLocked(String packageName, int owningUserId, int packageUserId,
2222 boolean appStillExists) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002223 final boolean wasUserLoaded = isUserLoadedLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002224
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002225 final ShortcutUser user = getUserShortcutsLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002226 boolean doNotify = false;
2227
2228 // First, remove the package from the package list (if the package is a publisher).
Makoto Onukid99c6f02016-03-28 11:02:54 -07002229 if (packageUserId == owningUserId) {
Makoto Onukic51b2872016-05-04 15:24:50 -07002230 if (user.removePackage(packageName) != null) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002231 doNotify = true;
2232 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07002233 }
Makoto Onukid99c6f02016-03-28 11:02:54 -07002234
Makoto Onukicdc78f72016-03-21 15:47:52 -07002235 // Also remove from the launcher list (if the package is a launcher).
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002236 user.removeLauncher(packageUserId, packageName);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002237
2238 // Then remove pinned shortcuts from all launchers.
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002239 user.forAllLaunchers(l -> l.cleanUpPackage(packageName, packageUserId));
2240
2241 // Now there may be orphan shortcuts because we removed pinned shortcuts at the previous
Makoto Onukicdc78f72016-03-21 15:47:52 -07002242 // step. Remove them too.
Makoto Onukic51b2872016-05-04 15:24:50 -07002243 user.forAllPackages(p -> p.refreshPinnedFlags());
Makoto Onukicdc78f72016-03-21 15:47:52 -07002244
Makoto Onukid99c6f02016-03-28 11:02:54 -07002245 scheduleSaveUser(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002246
2247 if (doNotify) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002248 notifyListeners(packageName, owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002249 }
2250
Makoto Onukib08790c2016-06-23 14:05:46 -07002251 // If the app still exists (i.e. data cleared), we need to re-publish manifest shortcuts.
2252 if (appStillExists && (packageUserId == owningUserId)) {
2253 // This will do the notification and save when needed, so do it after the above
2254 // notifyListeners.
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002255 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07002256 }
2257
Makoto Onukicdc78f72016-03-21 15:47:52 -07002258 if (!wasUserLoaded) {
2259 // Note this will execute the scheduled save.
Makoto Onukid99c6f02016-03-28 11:02:54 -07002260 unloadUserLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002261 }
2262 }
2263
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002264 /**
2265 * Entry point from {@link LauncherApps}.
2266 */
2267 private class LocalService extends ShortcutServiceInternal {
Makoto Onuki2e210c42016-03-30 08:30:36 -07002268
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002269 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002270 public List<ShortcutInfo> getShortcuts(int launcherUserId,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002271 @NonNull String callingPackage, long changedSince,
Makoto Onukiabe84422016-04-07 09:41:19 -07002272 @Nullable String packageName, @Nullable List<String> shortcutIds,
2273 @Nullable ComponentName componentName,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002274 int queryFlags, int userId) {
2275 final ArrayList<ShortcutInfo> ret = new ArrayList<>();
Makoto Onuki9c850012016-07-26 15:50:50 -07002276
Makoto Onuki20c95f82016-05-11 16:51:01 -07002277 final boolean cloneKeyFieldOnly =
2278 ((queryFlags & ShortcutQuery.FLAG_GET_KEY_FIELDS_ONLY) != 0);
2279 final int cloneFlag = cloneKeyFieldOnly ? ShortcutInfo.CLONE_REMOVE_NON_KEY_INFO
2280 : ShortcutInfo.CLONE_REMOVE_FOR_LAUNCHER;
Makoto Onukiabe84422016-04-07 09:41:19 -07002281 if (packageName == null) {
2282 shortcutIds = null; // LauncherAppsService already threw for it though.
2283 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002284
2285 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002286 throwIfUserLockedL(userId);
2287 throwIfUserLockedL(launcherUserId);
2288
Makoto Onuki2e210c42016-03-30 08:30:36 -07002289 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002290 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002291
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002292 if (packageName != null) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002293 getShortcutsInnerLocked(launcherUserId,
Makoto Onukiabe84422016-04-07 09:41:19 -07002294 callingPackage, packageName, shortcutIds, changedSince,
Makoto Onukide667372016-03-15 14:29:20 -07002295 componentName, queryFlags, userId, ret, cloneFlag);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002296 } else {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002297 final List<String> shortcutIdsF = shortcutIds;
2298 getUserShortcutsLocked(userId).forAllPackages(p -> {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002299 getShortcutsInnerLocked(launcherUserId,
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002300 callingPackage, p.getPackageName(), shortcutIdsF, changedSince,
Makoto Onukide667372016-03-15 14:29:20 -07002301 componentName, queryFlags, userId, ret, cloneFlag);
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002302 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002303 }
2304 }
2305 return ret;
2306 }
2307
Makoto Onukid99c6f02016-03-28 11:02:54 -07002308 private void getShortcutsInnerLocked(int launcherUserId, @NonNull String callingPackage,
Makoto Onukiabe84422016-04-07 09:41:19 -07002309 @Nullable String packageName, @Nullable List<String> shortcutIds, long changedSince,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002310 @Nullable ComponentName componentName, int queryFlags,
2311 int userId, ArrayList<ShortcutInfo> ret, int cloneFlag) {
Makoto Onukiabe84422016-04-07 09:41:19 -07002312 final ArraySet<String> ids = shortcutIds == null ? null
2313 : new ArraySet<>(shortcutIds);
2314
Makoto Onukic51b2872016-05-04 15:24:50 -07002315 final ShortcutPackage p = getUserShortcutsLocked(userId)
2316 .getPackageShortcutsIfExists(packageName);
2317 if (p == null) {
2318 return; // No need to instantiate ShortcutPackage.
2319 }
2320
2321 p.findAll(ret,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002322 (ShortcutInfo si) -> {
2323 if (si.getLastChangedTimestamp() < changedSince) {
2324 return false;
2325 }
Makoto Onukiabe84422016-04-07 09:41:19 -07002326 if (ids != null && !ids.contains(si.getId())) {
2327 return false;
2328 }
Makoto Onuki85694522016-05-04 12:53:37 -07002329 if (componentName != null) {
Makoto Onuki106ff7a2016-12-01 10:17:57 -08002330 if (!Objects.equals(componentName, si.getActivity())) {
Makoto Onuki85694522016-05-04 12:53:37 -07002331 return false;
2332 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002333 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002334 if (((queryFlags & ShortcutQuery.FLAG_GET_DYNAMIC) != 0)
2335 && si.isDynamic()) {
2336 return true;
2337 }
2338 if (((queryFlags & ShortcutQuery.FLAG_GET_PINNED) != 0)
2339 && si.isPinned()) {
2340 return true;
2341 }
2342 if (((queryFlags & ShortcutQuery.FLAG_GET_MANIFEST) != 0)
2343 && si.isManifestShortcut()) {
2344 return true;
2345 }
2346 return false;
Makoto Onukid99c6f02016-03-28 11:02:54 -07002347 }, cloneFlag, callingPackage, launcherUserId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002348 }
2349
2350 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002351 public boolean isPinnedByCaller(int launcherUserId, @NonNull String callingPackage,
2352 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2353 Preconditions.checkStringNotEmpty(packageName, "packageName");
2354 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
2355
2356 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002357 throwIfUserLockedL(userId);
2358 throwIfUserLockedL(launcherUserId);
2359
Makoto Onuki2e210c42016-03-30 08:30:36 -07002360 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002361 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002362
Makoto Onukid99c6f02016-03-28 11:02:54 -07002363 final ShortcutInfo si = getShortcutInfoLocked(
2364 launcherUserId, callingPackage, packageName, shortcutId, userId);
2365 return si != null && si.isPinned();
2366 }
2367 }
2368
Makoto Onuki2e210c42016-03-30 08:30:36 -07002369 private ShortcutInfo getShortcutInfoLocked(
Makoto Onukid99c6f02016-03-28 11:02:54 -07002370 int launcherUserId, @NonNull String callingPackage,
2371 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2372 Preconditions.checkStringNotEmpty(packageName, "packageName");
2373 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
2374
Makoto Onuki02f338e2016-07-29 09:40:40 -07002375 throwIfUserLockedL(userId);
2376 throwIfUserLockedL(launcherUserId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002377
Makoto Onukic51b2872016-05-04 15:24:50 -07002378 final ShortcutPackage p = getUserShortcutsLocked(userId)
2379 .getPackageShortcutsIfExists(packageName);
2380 if (p == null) {
2381 return null;
2382 }
2383
Makoto Onukid99c6f02016-03-28 11:02:54 -07002384 final ArrayList<ShortcutInfo> list = new ArrayList<>(1);
Makoto Onukic51b2872016-05-04 15:24:50 -07002385 p.findAll(list,
Makoto Onukid99c6f02016-03-28 11:02:54 -07002386 (ShortcutInfo si) -> shortcutId.equals(si.getId()),
2387 /* clone flags=*/ 0, callingPackage, launcherUserId);
2388 return list.size() == 0 ? null : list.get(0);
2389 }
2390
2391 @Override
2392 public void pinShortcuts(int launcherUserId,
2393 @NonNull String callingPackage, @NonNull String packageName,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002394 @NonNull List<String> shortcutIds, int userId) {
2395 // Calling permission must be checked by LauncherAppsImpl.
2396 Preconditions.checkStringNotEmpty(packageName, "packageName");
2397 Preconditions.checkNotNull(shortcutIds, "shortcutIds");
2398
2399 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002400 throwIfUserLockedL(userId);
2401 throwIfUserLockedL(launcherUserId);
2402
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002403 final ShortcutLauncher launcher =
Makoto Onuki2e210c42016-03-30 08:30:36 -07002404 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId);
Makoto Onukic51b2872016-05-04 15:24:50 -07002405 launcher.attemptToRestoreIfNeededAndSave();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002406
Makoto Onukic51b2872016-05-04 15:24:50 -07002407 launcher.pinShortcuts(userId, packageName, shortcutIds);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002408 }
Makoto Onuki39686e82016-04-13 18:03:00 -07002409 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07002410
2411 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002412 }
2413
2414 @Override
Makoto Onuki440a1ea2016-07-20 14:21:18 -07002415 public Intent[] createShortcutIntents(int launcherUserId,
Makoto Onukid99c6f02016-03-28 11:02:54 -07002416 @NonNull String callingPackage,
Makoto Onuki43204b82016-03-08 16:16:44 -08002417 @NonNull String packageName, @NonNull String shortcutId, int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002418 // Calling permission must be checked by LauncherAppsImpl.
Makoto Onuki43204b82016-03-08 16:16:44 -08002419 Preconditions.checkStringNotEmpty(packageName, "packageName can't be empty");
2420 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId can't be empty");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002421
2422 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002423 throwIfUserLockedL(userId);
2424 throwIfUserLockedL(launcherUserId);
2425
Makoto Onuki2e210c42016-03-30 08:30:36 -07002426 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002427 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002428
Makoto Onukid99c6f02016-03-28 11:02:54 -07002429 // Make sure the shortcut is actually visible to the launcher.
2430 final ShortcutInfo si = getShortcutInfoLocked(
2431 launcherUserId, callingPackage, packageName, shortcutId, userId);
2432 // "si == null" should suffice here, but check the flags too just to make sure.
Makoto Onuki22fcc682016-05-17 14:52:19 -07002433 if (si == null || !si.isEnabled() || !si.isAlive()) {
Makoto Onuki83f6d2d2016-07-11 14:30:19 -07002434 Log.e(TAG, "Shortcut " + shortcutId + " does not exist or disabled");
Makoto Onukid99c6f02016-03-28 11:02:54 -07002435 return null;
2436 }
Makoto Onuki440a1ea2016-07-20 14:21:18 -07002437 return si.getIntents();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002438 }
2439 }
2440
2441 @Override
2442 public void addListener(@NonNull ShortcutChangeListener listener) {
2443 synchronized (mLock) {
2444 mListeners.add(Preconditions.checkNotNull(listener));
2445 }
2446 }
Makoto Onuki55046222016-03-08 10:49:47 -08002447
2448 @Override
Makoto Onukiabe84422016-04-07 09:41:19 -07002449 public int getShortcutIconResId(int launcherUserId, @NonNull String callingPackage,
2450 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2451 Preconditions.checkNotNull(callingPackage, "callingPackage");
2452 Preconditions.checkNotNull(packageName, "packageName");
2453 Preconditions.checkNotNull(shortcutId, "shortcutId");
Makoto Onuki55046222016-03-08 10:49:47 -08002454
2455 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002456 throwIfUserLockedL(userId);
2457 throwIfUserLockedL(launcherUserId);
2458
Makoto Onuki2e210c42016-03-30 08:30:36 -07002459 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002460 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002461
Makoto Onukic51b2872016-05-04 15:24:50 -07002462 final ShortcutPackage p = getUserShortcutsLocked(userId)
2463 .getPackageShortcutsIfExists(packageName);
2464 if (p == null) {
2465 return 0;
2466 }
2467
2468 final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId);
Makoto Onuki55046222016-03-08 10:49:47 -08002469 return (shortcutInfo != null && shortcutInfo.hasIconResource())
2470 ? shortcutInfo.getIconResourceId() : 0;
2471 }
2472 }
2473
2474 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002475 public ParcelFileDescriptor getShortcutIconFd(int launcherUserId,
Makoto Onukiabe84422016-04-07 09:41:19 -07002476 @NonNull String callingPackage, @NonNull String packageName,
2477 @NonNull String shortcutId, int userId) {
2478 Preconditions.checkNotNull(callingPackage, "callingPackage");
2479 Preconditions.checkNotNull(packageName, "packageName");
2480 Preconditions.checkNotNull(shortcutId, "shortcutId");
Makoto Onuki55046222016-03-08 10:49:47 -08002481
2482 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002483 throwIfUserLockedL(userId);
2484 throwIfUserLockedL(launcherUserId);
2485
Makoto Onuki2e210c42016-03-30 08:30:36 -07002486 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002487 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002488
Makoto Onukic51b2872016-05-04 15:24:50 -07002489 final ShortcutPackage p = getUserShortcutsLocked(userId)
2490 .getPackageShortcutsIfExists(packageName);
2491 if (p == null) {
2492 return null;
2493 }
2494
2495 final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId);
Makoto Onuki55046222016-03-08 10:49:47 -08002496 if (shortcutInfo == null || !shortcutInfo.hasIconFile()) {
2497 return null;
2498 }
2499 try {
Makoto Onuki34d1c912016-03-10 14:24:58 -08002500 if (shortcutInfo.getBitmapPath() == null) {
2501 Slog.w(TAG, "null bitmap detected in getShortcutIconFd()");
2502 return null;
2503 }
Makoto Onuki55046222016-03-08 10:49:47 -08002504 return ParcelFileDescriptor.open(
2505 new File(shortcutInfo.getBitmapPath()),
2506 ParcelFileDescriptor.MODE_READ_ONLY);
2507 } catch (FileNotFoundException e) {
2508 Slog.e(TAG, "Icon file not found: " + shortcutInfo.getBitmapPath());
2509 return null;
2510 }
2511 }
2512 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002513
2514 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002515 public boolean hasShortcutHostPermission(int launcherUserId,
2516 @NonNull String callingPackage) {
2517 return ShortcutService.this.hasShortcutHostPermission(callingPackage, launcherUserId);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002518 }
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002519 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002520
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002521 final BroadcastReceiver mReceiver = new BroadcastReceiver() {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002522 @Override
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002523 public void onReceive(Context context, Intent intent) {
2524 if (!mBootCompleted.get()) {
2525 return; // Boot not completed, ignore the broadcast.
2526 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07002527 try {
2528 if (Intent.ACTION_LOCALE_CHANGED.equals(intent.getAction())) {
2529 handleLocaleChanged();
2530 }
2531 } catch (Exception e) {
2532 wtf("Exception in mReceiver.onReceive", e);
Makoto Onukic51b2872016-05-04 15:24:50 -07002533 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002534 }
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002535 };
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002536
Makoto Onuki157b1622016-06-02 16:13:10 -07002537 void handleLocaleChanged() {
2538 if (DEBUG) {
2539 Slog.d(TAG, "handleLocaleChanged");
2540 }
2541 scheduleSaveBaseState();
2542
Makoto Onuki02f338e2016-07-29 09:40:40 -07002543 synchronized (mLock) {
2544 final long token = injectClearCallingIdentity();
2545 try {
2546 forEachLoadedUserLocked(user -> user.detectLocaleChange());
2547 } finally {
2548 injectRestoreCallingIdentity(token);
2549 }
Makoto Onuki157b1622016-06-02 16:13:10 -07002550 }
2551 }
2552
Makoto Onukif34c3082016-07-13 10:25:25 -07002553 /**
2554 * Package event callbacks.
2555 */
2556 @VisibleForTesting
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002557 final BroadcastReceiver mPackageMonitor = new BroadcastReceiver() {
Makoto Onukif34c3082016-07-13 10:25:25 -07002558 @Override
2559 public void onReceive(Context context, Intent intent) {
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002560 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
2561 if (userId == UserHandle.USER_NULL) {
2562 Slog.w(TAG, "Intent broadcast does not contain user handle: " + intent);
2563 return;
2564 }
2565
2566 final String action = intent.getAction();
2567
2568 // This is normally called on Handler, so clearCallingIdentity() isn't needed,
2569 // but we still check it in unit tests.
Makoto Onukif34c3082016-07-13 10:25:25 -07002570 final long token = injectClearCallingIdentity();
2571 try {
Makoto Onuki10305202016-07-14 18:14:08 -07002572 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002573 if (!isUserUnlockedL(userId)) {
2574 if (DEBUG) {
2575 Slog.d(TAG, "Ignoring package broadcast " + action
2576 + " for locked/stopped user " + userId);
2577 }
2578 return;
2579 }
2580
2581 // Whenever we get one of those package broadcasts, or get
2582 // ACTION_PREFERRED_ACTIVITY_CHANGED, we purge the default launcher cache.
Makoto Onuki10305202016-07-14 18:14:08 -07002583 final ShortcutUser user = getUserShortcutsLocked(userId);
2584 user.clearLauncher();
2585 }
2586 if (Intent.ACTION_PREFERRED_ACTIVITY_CHANGED.equals(action)) {
2587 // Nothing farther to do.
2588 return;
2589 }
2590
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002591 final Uri intentUri = intent.getData();
2592 final String packageName = (intentUri != null) ? intentUri.getSchemeSpecificPart()
2593 : null;
2594 if (packageName == null) {
2595 Slog.w(TAG, "Intent broadcast does not contain package name: " + intent);
2596 return;
2597 }
2598
2599 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
2600
2601 switch (action) {
2602 case Intent.ACTION_PACKAGE_ADDED:
2603 if (replacing) {
2604 handlePackageUpdateFinished(packageName, userId);
2605 } else {
2606 handlePackageAdded(packageName, userId);
2607 }
2608 break;
2609 case Intent.ACTION_PACKAGE_REMOVED:
2610 if (!replacing) {
2611 handlePackageRemoved(packageName, userId);
2612 }
2613 break;
2614 case Intent.ACTION_PACKAGE_CHANGED:
2615 handlePackageChanged(packageName, userId);
2616
2617 break;
2618 case Intent.ACTION_PACKAGE_DATA_CLEARED:
2619 handlePackageDataCleared(packageName, userId);
2620 break;
2621 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07002622 } catch (Exception e) {
2623 wtf("Exception in mPackageMonitor.onReceive", e);
Makoto Onukif34c3082016-07-13 10:25:25 -07002624 } finally {
2625 injectRestoreCallingIdentity(token);
Makoto Onukia2241832016-07-06 13:28:37 -07002626 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07002627 }
Makoto Onukif34c3082016-07-13 10:25:25 -07002628 };
Makoto Onukicdc78f72016-03-21 15:47:52 -07002629
Makoto Onuki0acbb142016-03-22 17:02:57 -07002630 /**
Makoto Onuki39686e82016-04-13 18:03:00 -07002631 * Called when a user is unlocked.
2632 * - Check all known packages still exist, and otherwise perform cleanup.
2633 * - If a package still exists, check the version code. If it's been updated, may need to
Makoto Onukib08790c2016-06-23 14:05:46 -07002634 * update timestamps of its shortcuts.
Makoto Onuki0acbb142016-03-22 17:02:57 -07002635 */
Makoto Onukid99c6f02016-03-28 11:02:54 -07002636 @VisibleForTesting
Makoto Onuki39686e82016-04-13 18:03:00 -07002637 void checkPackageChanges(@UserIdInt int ownerUserId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07002638 if (DEBUG) {
Makoto Onuki39686e82016-04-13 18:03:00 -07002639 Slog.d(TAG, "checkPackageChanges() ownerUserId=" + ownerUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002640 }
Makoto Onukib08790c2016-06-23 14:05:46 -07002641 if (injectIsSafeModeEnabled()) {
2642 Slog.i(TAG, "Safe mode, skipping checkPackageChanges()");
2643 return;
2644 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07002645
Makoto Onuki22fcc682016-05-17 14:52:19 -07002646 final long start = injectElapsedRealtime();
2647 try {
2648 final ArrayList<PackageWithUser> gonePackages = new ArrayList<>();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002649
Makoto Onuki22fcc682016-05-17 14:52:19 -07002650 synchronized (mLock) {
2651 final ShortcutUser user = getUserShortcutsLocked(ownerUserId);
2652
2653 // Find packages that have been uninstalled.
2654 user.forAllPackageItems(spi -> {
2655 if (spi.getPackageInfo().isShadow()) {
2656 return; // Don't delete shadow information.
2657 }
2658 if (!isPackageInstalled(spi.getPackageName(), spi.getPackageUserId())) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002659 if (DEBUG) {
2660 Slog.d(TAG, "Uninstalled: " + spi.getPackageName()
2661 + " user " + spi.getPackageUserId());
2662 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002663 gonePackages.add(PackageWithUser.of(spi));
2664 }
2665 });
2666 if (gonePackages.size() > 0) {
2667 for (int i = gonePackages.size() - 1; i >= 0; i--) {
2668 final PackageWithUser pu = gonePackages.get(i);
Makoto Onukib08790c2016-06-23 14:05:46 -07002669 cleanUpPackageLocked(pu.packageName, ownerUserId, pu.userId,
2670 /* appStillExists = */ false);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002671 }
Makoto Onukid99c6f02016-03-28 11:02:54 -07002672 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002673
Makoto Onuki248a0ef2016-11-03 15:59:01 -07002674 rescanUpdatedPackagesLocked(ownerUserId, user.getLastAppScanTime());
Makoto Onuki0acbb142016-03-22 17:02:57 -07002675 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002676 } finally {
2677 logDurationStat(Stats.CHECK_PACKAGE_CHANGES, start);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002678 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002679 verifyStates();
Makoto Onukicdc78f72016-03-21 15:47:52 -07002680 }
2681
Makoto Onuki248a0ef2016-11-03 15:59:01 -07002682 private void rescanUpdatedPackagesLocked(@UserIdInt int userId, long lastScanTime) {
Makoto Onuki377b7972016-08-09 14:43:55 -07002683 final ShortcutUser user = getUserShortcutsLocked(userId);
2684
Makoto Onuki33663282016-08-22 16:19:04 -07002685 // Note after each OTA, we'll need to rescan all system apps, as their lastUpdateTime
2686 // is not reliable.
Makoto Onuki377b7972016-08-09 14:43:55 -07002687 final long now = injectCurrentTimeMillis();
Makoto Onuki33663282016-08-22 16:19:04 -07002688 final boolean afterOta =
2689 !injectBuildFingerprint().equals(user.getLastAppScanOsFingerprint());
Makoto Onuki377b7972016-08-09 14:43:55 -07002690
2691 // Then for each installed app, publish manifest shortcuts when needed.
Makoto Onuki33663282016-08-22 16:19:04 -07002692 forUpdatedPackages(userId, lastScanTime, afterOta, ai -> {
Makoto Onuki377b7972016-08-09 14:43:55 -07002693 user.attemptToRestoreIfNeededAndSave(this, ai.packageName, userId);
Makoto Onuki248a0ef2016-11-03 15:59:01 -07002694
2695 user.rescanPackageIfNeeded(ai.packageName, /* forceRescan= */ true);
Makoto Onuki377b7972016-08-09 14:43:55 -07002696 });
2697
2698 // Write the time just before the scan, because there may be apps that have just
2699 // been updated, and we want to catch them in the next time.
2700 user.setLastAppScanTime(now);
Makoto Onuki33663282016-08-22 16:19:04 -07002701 user.setLastAppScanOsFingerprint(injectBuildFingerprint());
Makoto Onuki377b7972016-08-09 14:43:55 -07002702 scheduleSaveUser(userId);
2703 }
2704
Makoto Onuki0acbb142016-03-22 17:02:57 -07002705 private void handlePackageAdded(String packageName, @UserIdInt int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07002706 if (DEBUG) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07002707 Slog.d(TAG, String.format("handlePackageAdded: %s user=%d", packageName, userId));
2708 }
2709 synchronized (mLock) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002710 final ShortcutUser user = getUserShortcutsLocked(userId);
2711 user.attemptToRestoreIfNeededAndSave(this, packageName, userId);
Makoto Onuki64183d52016-08-08 14:11:34 -07002712 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002713 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002714 verifyStates();
Makoto Onuki0acbb142016-03-22 17:02:57 -07002715 }
2716
2717 private void handlePackageUpdateFinished(String packageName, @UserIdInt int userId) {
Makoto Onuki905e8852016-03-28 10:40:58 -07002718 if (DEBUG) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002719 Slog.d(TAG, String.format("handlePackageUpdateFinished: %s user=%d",
2720 packageName, userId));
Makoto Onuki0acbb142016-03-22 17:02:57 -07002721 }
2722 synchronized (mLock) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002723 final ShortcutUser user = getUserShortcutsLocked(userId);
2724 user.attemptToRestoreIfNeededAndSave(this, packageName, userId);
Makoto Onuki39686e82016-04-13 18:03:00 -07002725
Makoto Onuki22fcc682016-05-17 14:52:19 -07002726 if (isPackageInstalled(packageName, userId)) {
Makoto Onuki64183d52016-08-08 14:11:34 -07002727 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onuki39686e82016-04-13 18:03:00 -07002728 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07002729 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002730 verifyStates();
Makoto Onuki0acbb142016-03-22 17:02:57 -07002731 }
2732
Makoto Onuki2e210c42016-03-30 08:30:36 -07002733 private void handlePackageRemoved(String packageName, @UserIdInt int packageUserId) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07002734 if (DEBUG) {
Makoto Onuki2e210c42016-03-30 08:30:36 -07002735 Slog.d(TAG, String.format("handlePackageRemoved: %s user=%d", packageName,
2736 packageUserId));
Makoto Onukicdc78f72016-03-21 15:47:52 -07002737 }
Makoto Onukib08790c2016-06-23 14:05:46 -07002738 cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ false);
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002739
2740 verifyStates();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002741 }
2742
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002743 private void handlePackageDataCleared(String packageName, int packageUserId) {
2744 if (DEBUG) {
2745 Slog.d(TAG, String.format("handlePackageDataCleared: %s user=%d", packageName,
2746 packageUserId));
Makoto Onukicdc78f72016-03-21 15:47:52 -07002747 }
Makoto Onukib08790c2016-06-23 14:05:46 -07002748 cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ true);
2749
2750 verifyStates();
2751 }
2752
2753 private void handlePackageChanged(String packageName, int packageUserId) {
2754 if (DEBUG) {
2755 Slog.d(TAG, String.format("handlePackageChanged: %s user=%d", packageName,
2756 packageUserId));
2757 }
2758
2759 // Activities may be disabled or enabled. Just rescan the package.
2760 synchronized (mLock) {
2761 final ShortcutUser user = getUserShortcutsLocked(packageUserId);
2762
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002763 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07002764 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002765
2766 verifyStates();
Makoto Onukicdc78f72016-03-21 15:47:52 -07002767 }
2768
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002769 // === PackageManager interaction ===
Makoto Onuki0acbb142016-03-22 17:02:57 -07002770
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002771 /**
2772 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
2773 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002774 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002775 final PackageInfo getPackageInfoWithSignatures(String packageName, @UserIdInt int userId) {
2776 return getPackageInfo(packageName, userId, true);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002777 }
2778
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002779 /**
2780 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
2781 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002782 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002783 final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId) {
2784 return getPackageInfo(packageName, userId, false);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002785 }
2786
Makoto Onuki905e8852016-03-28 10:40:58 -07002787 int injectGetPackageUid(@NonNull String packageName, @UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002788 final long token = injectClearCallingIdentity();
Makoto Onuki905e8852016-03-28 10:40:58 -07002789 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002790 return mIPackageManager.getPackageUid(packageName, PACKAGE_MATCH_FLAGS, userId);
Makoto Onuki905e8852016-03-28 10:40:58 -07002791 } catch (RemoteException e) {
2792 // Shouldn't happen.
2793 Slog.wtf(TAG, "RemoteException", e);
2794 return -1;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002795 } finally {
2796 injectRestoreCallingIdentity(token);
Makoto Onuki905e8852016-03-28 10:40:58 -07002797 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07002798 }
2799
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002800 /**
2801 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
2802 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002803 @Nullable
Makoto Onuki0acbb142016-03-22 17:02:57 -07002804 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002805 final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId,
2806 boolean getSignatures) {
2807 return isInstalledOrNull(injectPackageInfoWithUninstalled(
2808 packageName, userId, getSignatures));
2809 }
2810
2811 /**
2812 * Do not use directly; this returns uninstalled packages too.
2813 */
2814 @Nullable
2815 @VisibleForTesting
2816 PackageInfo injectPackageInfoWithUninstalled(String packageName, @UserIdInt int userId,
Makoto Onuki0acbb142016-03-22 17:02:57 -07002817 boolean getSignatures) {
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07002818 final long start = injectElapsedRealtime();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002819 final long token = injectClearCallingIdentity();
Makoto Onuki0acbb142016-03-22 17:02:57 -07002820 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002821 return mIPackageManager.getPackageInfo(
2822 packageName, PACKAGE_MATCH_FLAGS
2823 | (getSignatures ? PackageManager.GET_SIGNATURES : 0), userId);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002824 } catch (RemoteException e) {
2825 // Shouldn't happen.
2826 Slog.wtf(TAG, "RemoteException", e);
2827 return null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002828 } finally {
2829 injectRestoreCallingIdentity(token);
Makoto Onuki2e210c42016-03-30 08:30:36 -07002830
2831 logDurationStat(
2832 (getSignatures ? Stats.GET_PACKAGE_INFO_WITH_SIG : Stats.GET_PACKAGE_INFO),
2833 start);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002834 }
2835 }
2836
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002837 /**
2838 * Returns {@link ApplicationInfo} unless it's uninstalled or disabled.
2839 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002840 @Nullable
Makoto Onuki905e8852016-03-28 10:40:58 -07002841 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002842 final ApplicationInfo getApplicationInfo(String packageName, @UserIdInt int userId) {
2843 return isInstalledOrNull(injectApplicationInfoWithUninstalled(packageName, userId));
2844 }
2845
2846 /**
2847 * Do not use directly; this returns uninstalled packages too.
2848 */
2849 @Nullable
2850 @VisibleForTesting
2851 ApplicationInfo injectApplicationInfoWithUninstalled(
2852 String packageName, @UserIdInt int userId) {
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07002853 final long start = injectElapsedRealtime();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002854 final long token = injectClearCallingIdentity();
Makoto Onuki905e8852016-03-28 10:40:58 -07002855 try {
2856 return mIPackageManager.getApplicationInfo(packageName, PACKAGE_MATCH_FLAGS, userId);
2857 } catch (RemoteException e) {
2858 // Shouldn't happen.
2859 Slog.wtf(TAG, "RemoteException", e);
2860 return null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002861 } finally {
2862 injectRestoreCallingIdentity(token);
Makoto Onuki2e210c42016-03-30 08:30:36 -07002863
2864 logDurationStat(Stats.GET_APPLICATION_INFO, start);
Makoto Onuki905e8852016-03-28 10:40:58 -07002865 }
2866 }
2867
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002868 /**
2869 * Returns {@link ActivityInfo} with its metadata unless it's uninstalled or disabled.
2870 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002871 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002872 final ActivityInfo getActivityInfoWithMetadata(ComponentName activity, @UserIdInt int userId) {
2873 return isInstalledOrNull(injectGetActivityInfoWithMetadataWithUninstalled(
2874 activity, userId));
2875 }
2876
2877 /**
2878 * Do not use directly; this returns uninstalled packages too.
2879 */
2880 @Nullable
2881 @VisibleForTesting
2882 ActivityInfo injectGetActivityInfoWithMetadataWithUninstalled(
2883 ComponentName activity, @UserIdInt int userId) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002884 final long start = injectElapsedRealtime();
2885 final long token = injectClearCallingIdentity();
2886 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07002887 return mIPackageManager.getActivityInfo(activity,
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002888 (PACKAGE_MATCH_FLAGS | PackageManager.GET_META_DATA), userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002889 } catch (RemoteException e) {
2890 // Shouldn't happen.
2891 Slog.wtf(TAG, "RemoteException", e);
2892 return null;
2893 } finally {
2894 injectRestoreCallingIdentity(token);
2895
Makoto Onukib08790c2016-06-23 14:05:46 -07002896 logDurationStat(Stats.GET_ACTIVITY_WITH_METADATA, start);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002897 }
2898 }
2899
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002900 /**
2901 * Return all installed and enabled packages.
2902 */
2903 @NonNull
Makoto Onuki22fcc682016-05-17 14:52:19 -07002904 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002905 final List<PackageInfo> getInstalledPackages(@UserIdInt int userId) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002906 final long start = injectElapsedRealtime();
2907 final long token = injectClearCallingIdentity();
2908 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002909 final List<PackageInfo> all = injectGetPackagesWithUninstalled(userId);
2910
2911 all.removeIf(PACKAGE_NOT_INSTALLED);
2912
2913 return all;
Makoto Onuki22fcc682016-05-17 14:52:19 -07002914 } catch (RemoteException e) {
2915 // Shouldn't happen.
2916 Slog.wtf(TAG, "RemoteException", e);
2917 return null;
2918 } finally {
2919 injectRestoreCallingIdentity(token);
2920
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07002921 logDurationStat(Stats.GET_INSTALLED_PACKAGES, start);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002922 }
2923 }
2924
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002925 /**
2926 * Do not use directly; this returns uninstalled packages too.
2927 */
2928 @NonNull
2929 @VisibleForTesting
2930 List<PackageInfo> injectGetPackagesWithUninstalled(@UserIdInt int userId)
2931 throws RemoteException {
2932 final ParceledListSlice<PackageInfo> parceledList =
2933 mIPackageManager.getInstalledPackages(PACKAGE_MATCH_FLAGS, userId);
2934 if (parceledList == null) {
2935 return Collections.emptyList();
2936 }
2937 return parceledList.getList();
2938 }
2939
Makoto Onuki33663282016-08-22 16:19:04 -07002940 private void forUpdatedPackages(@UserIdInt int userId, long lastScanTime, boolean afterOta,
Makoto Onuki22fcc682016-05-17 14:52:19 -07002941 Consumer<ApplicationInfo> callback) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07002942 if (DEBUG) {
Makoto Onuki248a0ef2016-11-03 15:59:01 -07002943 Slog.d(TAG, "forUpdatedPackages for user " + userId + ", lastScanTime=" + lastScanTime
2944 + " afterOta=" + afterOta);
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07002945 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002946 final List<PackageInfo> list = getInstalledPackages(userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002947 for (int i = list.size() - 1; i >= 0; i--) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07002948 final PackageInfo pi = list.get(i);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002949
Makoto Onuki64183d52016-08-08 14:11:34 -07002950 // If the package has been updated since the last scan time, then scan it.
Makoto Onuki248a0ef2016-11-03 15:59:01 -07002951 // Also if it's right after an OTA, always re-scan all apps anyway, since the
2952 // shortcut parser might have changed.
2953 if (afterOta || (pi.lastUpdateTime >= lastScanTime)) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07002954 if (DEBUG) {
Makoto Onuki248a0ef2016-11-03 15:59:01 -07002955 Slog.d(TAG, "Found updated package " + pi.packageName
2956 + " updateTime=" + pi.lastUpdateTime);
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07002957 }
2958 callback.accept(pi.applicationInfo);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002959 }
2960 }
2961 }
2962
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002963 private boolean isApplicationFlagSet(@NonNull String packageName, int userId, int flags) {
2964 final ApplicationInfo ai = injectApplicationInfoWithUninstalled(packageName, userId);
Makoto Onuki905e8852016-03-28 10:40:58 -07002965 return (ai != null) && ((ai.flags & flags) == flags);
2966 }
2967
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002968 private static boolean isInstalled(@Nullable ApplicationInfo ai) {
2969 return (ai != null) && (ai.flags & ApplicationInfo.FLAG_INSTALLED) != 0;
2970 }
2971
2972 private static boolean isInstalled(@Nullable PackageInfo pi) {
2973 return (pi != null) && isInstalled(pi.applicationInfo);
2974 }
2975
2976 private static boolean isInstalled(@Nullable ActivityInfo ai) {
2977 return (ai != null) && isInstalled(ai.applicationInfo);
2978 }
2979
2980 private static ApplicationInfo isInstalledOrNull(ApplicationInfo ai) {
2981 return isInstalled(ai) ? ai : null;
2982 }
2983
2984 private static PackageInfo isInstalledOrNull(PackageInfo pi) {
2985 return isInstalled(pi) ? pi : null;
2986 }
2987
2988 private static ActivityInfo isInstalledOrNull(ActivityInfo ai) {
2989 return isInstalled(ai) ? ai : null;
2990 }
2991
Makoto Onuki2e210c42016-03-30 08:30:36 -07002992 boolean isPackageInstalled(String packageName, int userId) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002993 return getApplicationInfo(packageName, userId) != null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002994 }
2995
Makoto Onuki22fcc682016-05-17 14:52:19 -07002996 @Nullable
2997 XmlResourceParser injectXmlMetaData(ActivityInfo activityInfo, String key) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002998 return activityInfo.loadXmlMetaData(mContext.getPackageManager(), key);
Makoto Onuki39686e82016-04-13 18:03:00 -07002999 }
3000
Makoto Onuki157b1622016-06-02 16:13:10 -07003001 @Nullable
3002 Resources injectGetResourcesForApplicationAsUser(String packageName, int userId) {
3003 final long start = injectElapsedRealtime();
3004 final long token = injectClearCallingIdentity();
3005 try {
3006 return mContext.getPackageManager().getResourcesForApplicationAsUser(
3007 packageName, userId);
3008 } catch (NameNotFoundException e) {
3009 Slog.e(TAG, "Resources for package " + packageName + " not found");
3010 return null;
3011 } finally {
3012 injectRestoreCallingIdentity(token);
3013
3014 logDurationStat(Stats.GET_APPLICATION_RESOURCES, start);
3015 }
3016 }
3017
Makoto Onukib08790c2016-06-23 14:05:46 -07003018 private Intent getMainActivityIntent() {
3019 final Intent intent = new Intent(Intent.ACTION_MAIN);
3020 intent.addCategory(LAUNCHER_INTENT_CATEGORY);
3021 return intent;
3022 }
3023
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003024 /**
3025 * Same as queryIntentActivitiesAsUser, except it makes sure the package is installed,
3026 * and only returns exported activities.
3027 */
3028 @NonNull
3029 @VisibleForTesting
3030 List<ResolveInfo> queryActivities(@NonNull Intent baseIntent,
3031 @NonNull String packageName, @Nullable ComponentName activity, int userId) {
3032
3033 baseIntent.setPackage(Preconditions.checkNotNull(packageName));
3034 if (activity != null) {
3035 baseIntent.setComponent(activity);
3036 }
3037
3038 final List<ResolveInfo> resolved =
3039 mContext.getPackageManager().queryIntentActivitiesAsUser(
3040 baseIntent, PACKAGE_MATCH_FLAGS, userId);
3041 if (resolved == null || resolved.size() == 0) {
3042 return EMPTY_RESOLVE_INFO;
3043 }
3044 // Make sure the package is installed.
3045 if (!isInstalled(resolved.get(0).activityInfo)) {
3046 return EMPTY_RESOLVE_INFO;
3047 }
3048 resolved.removeIf(ACTIVITY_NOT_EXPORTED);
3049 return resolved;
3050 }
3051
3052 /**
3053 * Return the main activity that is enabled and exported. If multiple activities are found,
3054 * return the first one.
3055 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003056 @Nullable
3057 ComponentName injectGetDefaultMainActivity(@NonNull String packageName, int userId) {
3058 final long start = injectElapsedRealtime();
3059 final long token = injectClearCallingIdentity();
3060 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07003061 final List<ResolveInfo> resolved =
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003062 queryActivities(getMainActivityIntent(), packageName, null, userId);
3063 return resolved.size() == 0 ? null : resolved.get(0).activityInfo.getComponentName();
Makoto Onukib08790c2016-06-23 14:05:46 -07003064 } finally {
3065 injectRestoreCallingIdentity(token);
3066
3067 logDurationStat(Stats.GET_LAUNCHER_ACTIVITY, start);
3068 }
3069 }
3070
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003071 /**
3072 * Return whether an activity is enabled, exported and main.
3073 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003074 boolean injectIsMainActivity(@NonNull ComponentName activity, int userId) {
3075 final long start = injectElapsedRealtime();
3076 final long token = injectClearCallingIdentity();
3077 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07003078 final List<ResolveInfo> resolved =
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003079 queryActivities(getMainActivityIntent(), activity.getPackageName(),
3080 activity, userId);
3081 return resolved.size() > 0;
Makoto Onukib08790c2016-06-23 14:05:46 -07003082 } finally {
3083 injectRestoreCallingIdentity(token);
3084
3085 logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start);
3086 }
3087 }
3088
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003089 /**
3090 * Return all the enabled, exported and main activities from a package.
3091 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003092 @NonNull
3093 List<ResolveInfo> injectGetMainActivities(@NonNull String packageName, int userId) {
3094 final long start = injectElapsedRealtime();
3095 final long token = injectClearCallingIdentity();
3096 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003097 return queryActivities(getMainActivityIntent(), packageName, null, userId);
Makoto Onukib08790c2016-06-23 14:05:46 -07003098 } finally {
3099 injectRestoreCallingIdentity(token);
3100
3101 logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start);
3102 }
3103 }
3104
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003105 /**
3106 * Return whether an activity is enabled and exported.
3107 */
3108 @VisibleForTesting
3109 boolean injectIsActivityEnabledAndExported(
3110 @NonNull ComponentName activity, @UserIdInt int userId) {
3111 final long start = injectElapsedRealtime();
3112 final long token = injectClearCallingIdentity();
3113 try {
3114 return queryActivities(new Intent(), activity.getPackageName(), activity, userId)
3115 .size() > 0;
3116 } finally {
3117 injectRestoreCallingIdentity(token);
3118
3119 logDurationStat(Stats.IS_ACTIVITY_ENABLED, start);
3120 }
3121 }
3122
Makoto Onukib08790c2016-06-23 14:05:46 -07003123 boolean injectIsSafeModeEnabled() {
3124 final long token = injectClearCallingIdentity();
3125 try {
3126 return IWindowManager.Stub
3127 .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE))
3128 .isSafeModeEnabled();
3129 } catch (RemoteException e) {
3130 return false; // Shouldn't happen though.
3131 } finally {
3132 injectRestoreCallingIdentity(token);
3133 }
3134 }
3135
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003136 // === Backup & restore ===
3137
Makoto Onuki0acbb142016-03-22 17:02:57 -07003138 boolean shouldBackupApp(String packageName, int userId) {
Makoto Onuki905e8852016-03-28 10:40:58 -07003139 return isApplicationFlagSet(packageName, userId, ApplicationInfo.FLAG_ALLOW_BACKUP);
Makoto Onuki0acbb142016-03-22 17:02:57 -07003140 }
3141
Makoto Onuki2e210c42016-03-30 08:30:36 -07003142 boolean shouldBackupApp(PackageInfo pi) {
3143 return (pi.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0;
3144 }
3145
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003146 @Override
Makoto Onuki2e210c42016-03-30 08:30:36 -07003147 public byte[] getBackupPayload(@UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003148 enforceSystem();
3149 if (DEBUG) {
3150 Slog.d(TAG, "Backing up user " + userId);
3151 }
3152 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003153 if (!isUserUnlockedL(userId)) {
3154 wtf("Can't backup: user " + userId + " is locked or not running");
3155 return null;
3156 }
3157
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003158 final ShortcutUser user = getUserShortcutsLocked(userId);
3159 if (user == null) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003160 wtf("Can't backup: user not found: id=" + userId);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003161 return null;
3162 }
3163
Makoto Onukic8c33292016-09-12 16:36:59 -07003164 // Update the signatures for all packages.
3165 user.forAllPackageItems(spi -> spi.refreshPackageSignatureAndSave());
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003166
Makoto Onukic8c33292016-09-12 16:36:59 -07003167 // Set the version code for the launchers.
3168 // We shouldn't do this for publisher packages, because we don't want to update the
3169 // version code without rescanning the manifest.
3170 user.forAllLaunchers(launcher -> launcher.ensureVersionInfo());
3171
3172 // Save to the filesystem.
3173 scheduleSaveUser(userId);
3174 saveDirtyInfo();
3175
3176 // Then create the backup payload.
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003177 final ByteArrayOutputStream os = new ByteArrayOutputStream(32 * 1024);
3178 try {
3179 saveUserInternalLocked(userId, os, /* forBackup */ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07003180 } catch (XmlPullParserException | IOException e) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003181 // Shouldn't happen.
3182 Slog.w(TAG, "Backup failed.", e);
3183 return null;
3184 }
3185 return os.toByteArray();
3186 }
3187 }
3188
3189 @Override
Makoto Onuki2e210c42016-03-30 08:30:36 -07003190 public void applyRestore(byte[] payload, @UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003191 enforceSystem();
3192 if (DEBUG) {
3193 Slog.d(TAG, "Restoring user " + userId);
3194 }
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003195 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003196 if (!isUserUnlockedL(userId)) {
3197 wtf("Can't restore: user " + userId + " is locked or not running");
3198 return;
3199 }
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003200 // Actually do restore.
3201 final ShortcutUser restored;
Makoto Onuki02f338e2016-07-29 09:40:40 -07003202 final ByteArrayInputStream is = new ByteArrayInputStream(payload);
3203 try {
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003204 restored = loadUserInternal(userId, is, /* fromBackup */ true);
3205 } catch (XmlPullParserException | IOException | InvalidFileFormatException e) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003206 Slog.w(TAG, "Restoration failed.", e);
3207 return;
3208 }
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003209 getUserShortcutsLocked(userId).mergeRestoredFile(restored);
Makoto Onuki2e210c42016-03-30 08:30:36 -07003210
Makoto Onuki377b7972016-08-09 14:43:55 -07003211 // Rescan all packages to re-publish manifest shortcuts and do other checks.
3212 rescanUpdatedPackagesLocked(userId,
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003213 0 // lastScanTime = 0; rescan all packages.
3214 );
Makoto Onuki2e210c42016-03-30 08:30:36 -07003215
3216 saveUserLocked(userId);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003217 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07003218 }
3219
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003220 // === Dump ===
3221
3222 @Override
3223 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Makoto Onuki76269922016-07-15 14:58:54 -07003224 enforceCallingOrSelfPermission(android.Manifest.permission.DUMP,
3225 "can't dump by this caller");
3226 boolean checkin = false;
3227 boolean clear = false;
3228 if (args != null) {
3229 for (String arg : args) {
3230 if ("-c".equals(arg)) {
3231 checkin = true;
3232 } else if ("--checkin".equals(arg)) {
3233 checkin = true;
3234 clear = true;
3235 }
3236 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003237 }
Makoto Onuki76269922016-07-15 14:58:54 -07003238
3239 if (checkin) {
3240 dumpCheckin(pw, clear);
3241 } else {
3242 dumpInner(pw);
3243 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003244 }
3245
Makoto Onuki76269922016-07-15 14:58:54 -07003246 private void dumpInner(PrintWriter pw) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003247 synchronized (mLock) {
3248 final long now = injectCurrentTimeMillis();
3249 pw.print("Now: [");
3250 pw.print(now);
3251 pw.print("] ");
3252 pw.print(formatTime(now));
Makoto Onuki55046222016-03-08 10:49:47 -08003253
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003254 pw.print(" Raw last reset: [");
3255 pw.print(mRawLastResetTime);
3256 pw.print("] ");
3257 pw.print(formatTime(mRawLastResetTime));
3258
3259 final long last = getLastResetTimeLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003260 pw.print(" Last reset: [");
3261 pw.print(last);
3262 pw.print("] ");
3263 pw.print(formatTime(last));
3264
Makoto Onuki55046222016-03-08 10:49:47 -08003265 final long next = getNextResetTimeLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003266 pw.print(" Next reset: [");
3267 pw.print(next);
3268 pw.print("] ");
3269 pw.print(formatTime(next));
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003270
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003271 pw.print(" Config:");
3272 pw.print(" Max icon dim: ");
3273 pw.println(mMaxIconDimension);
3274 pw.print(" Icon format: ");
3275 pw.println(mIconPersistFormat);
3276 pw.print(" Icon quality: ");
Makoto Onuki2e210c42016-03-30 08:30:36 -07003277 pw.println(mIconPersistQuality);
Makoto Onuki0033b2a2016-04-14 17:19:16 -07003278 pw.print(" saveDelayMillis: ");
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003279 pw.println(mSaveDelayMillis);
Makoto Onuki0033b2a2016-04-14 17:19:16 -07003280 pw.print(" resetInterval: ");
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003281 pw.println(mResetInterval);
Makoto Onuki0033b2a2016-04-14 17:19:16 -07003282 pw.print(" maxUpdatesPerInterval: ");
Makoto Onukib6d35232016-04-04 15:57:17 -07003283 pw.println(mMaxUpdatesPerInterval);
Makoto Onukib08790c2016-06-23 14:05:46 -07003284 pw.print(" maxShortcutsPerActivity: ");
Makoto Onukib5a012f2016-06-21 11:13:53 -07003285 pw.println(mMaxShortcuts);
Makoto Onuki55046222016-03-08 10:49:47 -08003286 pw.println();
3287
Makoto Onuki2e210c42016-03-30 08:30:36 -07003288 pw.println(" Stats:");
3289 synchronized (mStatLock) {
Makoto Onuki085a05c2016-08-19 11:39:29 -07003290 for (int i = 0; i < Stats.COUNT; i++) {
3291 dumpStatLS(pw, " ", i);
3292 }
Makoto Onuki2e210c42016-03-30 08:30:36 -07003293 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003294
Makoto Onukia2241832016-07-06 13:28:37 -07003295 pw.println();
3296 pw.print(" #Failures: ");
3297 pw.println(mWtfCount);
3298
3299 if (mLastWtfStacktrace != null) {
3300 pw.print(" Last failure stack trace: ");
3301 pw.println(Log.getStackTraceString(mLastWtfStacktrace));
3302 }
3303
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08003304 for (int i = 0; i < mUsers.size(); i++) {
3305 pw.println();
Makoto Onukic51b2872016-05-04 15:24:50 -07003306 mUsers.valueAt(i).dump(pw, " ");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003307 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003308
3309 pw.println();
3310 pw.println(" UID state:");
3311
3312 for (int i = 0; i < mUidState.size(); i++) {
3313 final int uid = mUidState.keyAt(i);
3314 final int state = mUidState.valueAt(i);
3315 pw.print(" UID=");
3316 pw.print(uid);
3317 pw.print(" state=");
3318 pw.print(state);
3319 if (isProcessStateForeground(state)) {
3320 pw.print(" [FG]");
3321 }
3322 pw.print(" last FG=");
3323 pw.print(mUidLastForegroundElapsedTime.get(uid));
3324 pw.println();
3325 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003326 }
3327 }
3328
Makoto Onuki41066a62016-03-09 16:18:44 -08003329 static String formatTime(long time) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003330 Time tobj = new Time();
3331 tobj.set(time);
3332 return tobj.format("%Y-%m-%d %H:%M:%S");
3333 }
3334
Makoto Onuki085a05c2016-08-19 11:39:29 -07003335 private void dumpStatLS(PrintWriter pw, String prefix, int statId) {
Makoto Onuki2e210c42016-03-30 08:30:36 -07003336 pw.print(prefix);
3337 final int count = mCountStats[statId];
3338 final long dur = mDurationStats[statId];
3339 pw.println(String.format("%s: count=%d, total=%dms, avg=%.1fms",
Makoto Onuki085a05c2016-08-19 11:39:29 -07003340 STAT_LABELS[statId], count, dur,
Makoto Onuki2e210c42016-03-30 08:30:36 -07003341 (count == 0 ? 0 : ((double) dur) / count)));
3342 }
3343
Makoto Onuki76269922016-07-15 14:58:54 -07003344 /**
3345 * Dumpsys for checkin.
3346 *
3347 * @param clear if true, clear the history information. Some other system services have this
3348 * behavior but shortcut service doesn't for now.
3349 */
3350 private void dumpCheckin(PrintWriter pw, boolean clear) {
3351 synchronized (mLock) {
3352 try {
3353 final JSONArray users = new JSONArray();
3354
3355 for (int i = 0; i < mUsers.size(); i++) {
3356 users.put(mUsers.valueAt(i).dumpCheckin(clear));
3357 }
3358
3359 final JSONObject result = new JSONObject();
3360
3361 result.put(KEY_SHORTCUT, users);
3362 result.put(KEY_LOW_RAM, injectIsLowRamDevice());
3363 result.put(KEY_ICON_SIZE, mMaxIconDimension);
3364
3365 pw.println(result.toString(1));
3366 } catch (JSONException e) {
3367 Slog.e(TAG, "Unable to write in json", e);
3368 }
3369 }
3370 }
3371
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003372 // === Shell support ===
3373
3374 @Override
3375 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003376 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003377
3378 enforceShell();
3379
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07003380 final long token = injectClearCallingIdentity();
3381 try {
Dianne Hackborn354736e2016-08-22 17:00:05 -07003382 final int status = (new MyShellCommand()).exec(this, in, out, err, args, callback,
3383 resultReceiver);
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07003384 resultReceiver.send(status, null);
3385 } finally {
3386 injectRestoreCallingIdentity(token);
3387 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003388 }
3389
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003390 static class CommandException extends Exception {
3391 public CommandException(String message) {
3392 super(message);
3393 }
3394 }
3395
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003396 /**
3397 * Handle "adb shell cmd".
3398 */
3399 private class MyShellCommand extends ShellCommand {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003400
3401 private int mUserId = UserHandle.USER_SYSTEM;
3402
Makoto Onuki02f338e2016-07-29 09:40:40 -07003403 private void parseOptionsLocked(boolean takeUser)
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003404 throws CommandException {
3405 String opt;
3406 while ((opt = getNextOption()) != null) {
3407 switch (opt) {
3408 case "--user":
3409 if (takeUser) {
3410 mUserId = UserHandle.parseUserArg(getNextArgRequired());
Makoto Onuki02f338e2016-07-29 09:40:40 -07003411 if (!isUserUnlockedL(mUserId)) {
Makoto Onukif34c3082016-07-13 10:25:25 -07003412 throw new CommandException(
3413 "User " + mUserId + " is not running or locked");
3414 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003415 break;
3416 }
3417 // fallthrough
3418 default:
3419 throw new CommandException("Unknown option: " + opt);
3420 }
3421 }
3422 }
3423
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003424 @Override
3425 public int onCommand(String cmd) {
3426 if (cmd == null) {
3427 return handleDefaultCommands(cmd);
3428 }
3429 final PrintWriter pw = getOutPrintWriter();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003430 try {
3431 switch (cmd) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003432 case "reset-throttling":
3433 handleResetThrottling();
3434 break;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003435 case "reset-all-throttling":
3436 handleResetAllThrottling();
3437 break;
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003438 case "override-config":
3439 handleOverrideConfig();
3440 break;
3441 case "reset-config":
3442 handleResetConfig();
3443 break;
3444 case "clear-default-launcher":
3445 handleClearDefaultLauncher();
3446 break;
3447 case "get-default-launcher":
3448 handleGetDefaultLauncher();
3449 break;
Makoto Onukiac214972016-04-04 10:19:45 -07003450 case "unload-user":
3451 handleUnloadUser();
3452 break;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003453 case "clear-shortcuts":
3454 handleClearShortcuts();
3455 break;
Makoto Onukib08790c2016-06-23 14:05:46 -07003456 case "verify-states": // hidden command to verify various internal states.
3457 handleVerifyStates();
3458 break;
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003459 default:
3460 return handleDefaultCommands(cmd);
3461 }
3462 } catch (CommandException e) {
3463 pw.println("Error: " + e.getMessage());
3464 return 1;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003465 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003466 pw.println("Success");
3467 return 0;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003468 }
3469
3470 @Override
3471 public void onHelp() {
3472 final PrintWriter pw = getOutPrintWriter();
3473 pw.println("Usage: cmd shortcut COMMAND [options ...]");
3474 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003475 pw.println("cmd shortcut reset-throttling [--user USER_ID]");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003476 pw.println(" Reset throttling for all packages and users");
3477 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003478 pw.println("cmd shortcut reset-all-throttling");
3479 pw.println(" Reset the throttling state for all users");
3480 pw.println();
Makoto Onuki4362a662016-03-08 18:59:09 -08003481 pw.println("cmd shortcut override-config CONFIG");
3482 pw.println(" Override the configuration for testing (will last until reboot)");
3483 pw.println();
3484 pw.println("cmd shortcut reset-config");
3485 pw.println(" Reset the configuration set with \"update-config\"");
3486 pw.println();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003487 pw.println("cmd shortcut clear-default-launcher [--user USER_ID]");
3488 pw.println(" Clear the cached default launcher");
3489 pw.println();
3490 pw.println("cmd shortcut get-default-launcher [--user USER_ID]");
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07003491 pw.println(" Show the default launcher");
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003492 pw.println();
Makoto Onukiac214972016-04-04 10:19:45 -07003493 pw.println("cmd shortcut unload-user [--user USER_ID]");
3494 pw.println(" Unload a user from the memory");
3495 pw.println(" (This should not affect any observable behavior)");
3496 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003497 pw.println("cmd shortcut clear-shortcuts [--user USER_ID] PACKAGE");
3498 pw.println(" Remove all shortcuts from a package, including pinned shortcuts");
3499 pw.println();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003500 }
3501
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003502 private void handleResetThrottling() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003503 synchronized (mLock) {
3504 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki4554d0e2016-03-14 15:51:41 -07003505
Makoto Onuki02f338e2016-07-29 09:40:40 -07003506 Slog.i(TAG, "cmd: handleResetThrottling: user=" + mUserId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003507
Makoto Onuki02f338e2016-07-29 09:40:40 -07003508 resetThrottlingInner(mUserId);
3509 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003510 }
3511
3512 private void handleResetAllThrottling() {
3513 Slog.i(TAG, "cmd: handleResetAllThrottling");
3514
3515 resetAllThrottlingInner();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003516 }
3517
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003518 private void handleOverrideConfig() throws CommandException {
Makoto Onuki4362a662016-03-08 18:59:09 -08003519 final String config = getNextArgRequired();
3520
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003521 Slog.i(TAG, "cmd: handleOverrideConfig: " + config);
3522
Makoto Onuki4362a662016-03-08 18:59:09 -08003523 synchronized (mLock) {
3524 if (!updateConfigurationLocked(config)) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003525 throw new CommandException("override-config failed. See logcat for details.");
Makoto Onuki4362a662016-03-08 18:59:09 -08003526 }
3527 }
Makoto Onuki4362a662016-03-08 18:59:09 -08003528 }
3529
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003530 private void handleResetConfig() {
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003531 Slog.i(TAG, "cmd: handleResetConfig");
3532
Makoto Onuki4362a662016-03-08 18:59:09 -08003533 synchronized (mLock) {
3534 loadConfigurationLocked();
3535 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003536 }
3537
3538 private void clearLauncher() {
3539 synchronized (mLock) {
Makoto Onuki10305202016-07-14 18:14:08 -07003540 getUserShortcutsLocked(mUserId).forceClearLauncher();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003541 }
3542 }
3543
3544 private void showLauncher() {
3545 synchronized (mLock) {
3546 // This ensures to set the cached launcher. Package name doesn't matter.
3547 hasShortcutHostPermissionInner("-", mUserId);
3548
3549 getOutPrintWriter().println("Launcher: "
Makoto Onuki10305202016-07-14 18:14:08 -07003550 + getUserShortcutsLocked(mUserId).getLastKnownLauncher());
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003551 }
3552 }
3553
3554 private void handleClearDefaultLauncher() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003555 synchronized (mLock) {
3556 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003557
Makoto Onuki02f338e2016-07-29 09:40:40 -07003558 clearLauncher();
3559 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003560 }
3561
3562 private void handleGetDefaultLauncher() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003563 synchronized (mLock) {
3564 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003565
Makoto Onuki02f338e2016-07-29 09:40:40 -07003566 clearLauncher();
3567 showLauncher();
3568 }
Makoto Onuki4362a662016-03-08 18:59:09 -08003569 }
Makoto Onukiac214972016-04-04 10:19:45 -07003570
3571 private void handleUnloadUser() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003572 synchronized (mLock) {
3573 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onukiac214972016-04-04 10:19:45 -07003574
Makoto Onuki02f338e2016-07-29 09:40:40 -07003575 Slog.i(TAG, "cmd: handleUnloadUser: user=" + mUserId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003576
Makoto Onuki02f338e2016-07-29 09:40:40 -07003577 ShortcutService.this.handleCleanupUser(mUserId);
3578 }
Makoto Onukiac214972016-04-04 10:19:45 -07003579 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003580
3581 private void handleClearShortcuts() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003582 synchronized (mLock) {
3583 parseOptionsLocked(/* takeUser =*/ true);
3584 final String packageName = getNextArgRequired();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003585
Makoto Onuki02f338e2016-07-29 09:40:40 -07003586 Slog.i(TAG, "cmd: handleClearShortcuts: user" + mUserId + ", " + packageName);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003587
Makoto Onuki02f338e2016-07-29 09:40:40 -07003588 ShortcutService.this.cleanUpPackageForAllLoadedUsers(packageName, mUserId,
3589 /* appStillExists = */ true);
3590 }
Makoto Onukib08790c2016-06-23 14:05:46 -07003591 }
3592
3593 private void handleVerifyStates() throws CommandException {
3594 try {
3595 verifyStatesForce(); // This will throw when there's an issue.
3596 } catch (Throwable th) {
3597 throw new CommandException(th.getMessage() + "\n" + Log.getStackTraceString(th));
3598 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003599 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003600 }
3601
3602 // === Unit test support ===
3603
3604 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07003605 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003606 long injectCurrentTimeMillis() {
3607 return System.currentTimeMillis();
3608 }
3609
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003610 @VisibleForTesting
3611 long injectElapsedRealtime() {
3612 return SystemClock.elapsedRealtime();
3613 }
3614
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003615 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07003616 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003617 int injectBinderCallingUid() {
3618 return getCallingUid();
3619 }
3620
Makoto Onuki31459242016-03-22 11:12:18 -07003621 private int getCallingUserId() {
Makoto Onuki4554d0e2016-03-14 15:51:41 -07003622 return UserHandle.getUserId(injectBinderCallingUid());
3623 }
3624
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07003625 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07003626 @VisibleForTesting
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07003627 long injectClearCallingIdentity() {
3628 return Binder.clearCallingIdentity();
3629 }
3630
3631 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07003632 @VisibleForTesting
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07003633 void injectRestoreCallingIdentity(long token) {
3634 Binder.restoreCallingIdentity(token);
3635 }
3636
Makoto Onuki33663282016-08-22 16:19:04 -07003637 // Injection point.
3638 @VisibleForTesting
3639 String injectBuildFingerprint() {
3640 return Build.FINGERPRINT;
3641 }
3642
Makoto Onukide667372016-03-15 14:29:20 -07003643 final void wtf(String message) {
Makoto Onukib08790c2016-06-23 14:05:46 -07003644 wtf(message, /* exception= */ null);
Makoto Onukide667372016-03-15 14:29:20 -07003645 }
3646
Makoto Onuki2e210c42016-03-30 08:30:36 -07003647 // Injection point.
Makoto Onukia2241832016-07-06 13:28:37 -07003648 void wtf(String message, Throwable e) {
3649 if (e == null) {
3650 e = new RuntimeException("Stacktrace");
3651 }
3652 synchronized (mLock) {
3653 mWtfCount++;
3654 mLastWtfStacktrace = new Exception("Last failure was logged here:");
3655 }
Makoto Onukide667372016-03-15 14:29:20 -07003656 Slog.wtf(TAG, message, e);
3657 }
3658
Makoto Onuki31459242016-03-22 11:12:18 -07003659 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003660 File injectSystemDataPath() {
3661 return Environment.getDataSystemDirectory();
3662 }
3663
Makoto Onuki31459242016-03-22 11:12:18 -07003664 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003665 File injectUserDataPath(@UserIdInt int userId) {
Makoto Onuki55046222016-03-08 10:49:47 -08003666 return new File(Environment.getDataSystemCeDirectory(userId), DIRECTORY_PER_USER);
3667 }
3668
Makoto Onuki4362a662016-03-08 18:59:09 -08003669 @VisibleForTesting
Makoto Onuki55046222016-03-08 10:49:47 -08003670 boolean injectIsLowRamDevice() {
3671 return ActivityManager.isLowRamDeviceStatic();
3672 }
3673
Makoto Onuki31459242016-03-22 11:12:18 -07003674 @VisibleForTesting
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003675 void injectRegisterUidObserver(IUidObserver observer, int which) {
3676 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003677 ActivityManager.getService().registerUidObserver(observer, which,
Dianne Hackborn5614bf52016-11-07 17:26:41 -08003678 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003679 } catch (RemoteException shouldntHappen) {
3680 }
3681 }
3682
Makoto Onuki55046222016-03-08 10:49:47 -08003683 File getUserBitmapFilePath(@UserIdInt int userId) {
3684 return new File(injectUserDataPath(userId), DIRECTORY_BITMAPS);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003685 }
3686
3687 @VisibleForTesting
Makoto Onuki31459242016-03-22 11:12:18 -07003688 SparseArray<ShortcutUser> getShortcutsForTest() {
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08003689 return mUsers;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003690 }
3691
3692 @VisibleForTesting
Makoto Onukib5a012f2016-06-21 11:13:53 -07003693 int getMaxShortcutsForTest() {
3694 return mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003695 }
3696
3697 @VisibleForTesting
Makoto Onukib6d35232016-04-04 15:57:17 -07003698 int getMaxUpdatesPerIntervalForTest() {
3699 return mMaxUpdatesPerInterval;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003700 }
3701
3702 @VisibleForTesting
Makoto Onuki4362a662016-03-08 18:59:09 -08003703 long getResetIntervalForTest() {
3704 return mResetInterval;
Makoto Onuki55046222016-03-08 10:49:47 -08003705 }
3706
3707 @VisibleForTesting
Makoto Onuki4362a662016-03-08 18:59:09 -08003708 int getMaxIconDimensionForTest() {
3709 return mMaxIconDimension;
3710 }
3711
3712 @VisibleForTesting
3713 CompressFormat getIconPersistFormatForTest() {
3714 return mIconPersistFormat;
3715 }
3716
3717 @VisibleForTesting
3718 int getIconPersistQualityForTest() {
3719 return mIconPersistQuality;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003720 }
Makoto Onuki41066a62016-03-09 16:18:44 -08003721
3722 @VisibleForTesting
Makoto Onuki22fcc682016-05-17 14:52:19 -07003723 ShortcutPackage getPackageShortcutForTest(String packageName, int userId) {
Makoto Onuki41066a62016-03-09 16:18:44 -08003724 synchronized (mLock) {
Makoto Onuki31459242016-03-22 11:12:18 -07003725 final ShortcutUser user = mUsers.get(userId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07003726 if (user == null) return null;
3727
Makoto Onuki22fcc682016-05-17 14:52:19 -07003728 return user.getAllPackagesForTest().get(packageName);
3729 }
3730 }
3731
3732 @VisibleForTesting
3733 ShortcutInfo getPackageShortcutForTest(String packageName, String shortcutId, int userId) {
3734 synchronized (mLock) {
Makoto Onukif34c3082016-07-13 10:25:25 -07003735 final ShortcutPackage pkg = getPackageShortcutForTest(packageName, userId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07003736 if (pkg == null) return null;
3737
3738 return pkg.findShortcutById(shortcutId);
Makoto Onuki41066a62016-03-09 16:18:44 -08003739 }
3740 }
Makoto Onuki7001a612016-05-27 13:24:28 -07003741
Makoto Onukifac592f2016-11-21 13:41:32 -08003742 @VisibleForTesting
3743 ShortcutLauncher getLauncherShortcutForTest(String packageName, int userId) {
3744 synchronized (mLock) {
3745 final ShortcutUser user = mUsers.get(userId);
3746 if (user == null) return null;
3747
3748 return user.getAllLaunchersForTest().get(PackageWithUser.of(userId, packageName));
3749 }
3750 }
3751
Makoto Onuki7001a612016-05-27 13:24:28 -07003752 /**
3753 * Control whether {@link #verifyStates} should be performed. We always perform it during unit
3754 * tests.
3755 */
3756 @VisibleForTesting
3757 boolean injectShouldPerformVerification() {
3758 return DEBUG;
3759 }
3760
3761 /**
3762 * Check various internal states and throws if there's any inconsistency.
3763 * This is normally only enabled during unit tests.
3764 */
3765 final void verifyStates() {
3766 if (injectShouldPerformVerification()) {
3767 verifyStatesInner();
3768 }
3769 }
3770
Makoto Onukib08790c2016-06-23 14:05:46 -07003771 private final void verifyStatesForce() {
3772 verifyStatesInner();
3773 }
3774
Makoto Onuki7001a612016-05-27 13:24:28 -07003775 private void verifyStatesInner() {
Makoto Onuki10305202016-07-14 18:14:08 -07003776 synchronized (mLock) {
Makoto Onuki7001a612016-05-27 13:24:28 -07003777 forEachLoadedUserLocked(u -> u.forAllPackageItems(ShortcutPackageItem::verifyStates));
3778 }
3779 }
Makoto Onuki106ff7a2016-12-01 10:17:57 -08003780
3781 void verifyError() {
3782 Slog.e(TAG, "See logcat for errors");
3783 }
Makoto Onuki41066a62016-03-09 16:18:44 -08003784}