blob: dc29404f5aae970a3423ff9d2f2bb2b8def7e9c6 [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;
Sunny Goyal87a563e2017-01-01 19:42:45 -080027import android.appwidget.AppWidgetProviderInfo;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070028import android.content.BroadcastReceiver;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080029import android.content.ComponentName;
30import android.content.Context;
31import android.content.Intent;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070032import android.content.IntentFilter;
Makoto Onuki2d895c32016-12-02 15:48:40 -080033import android.content.IntentSender;
34import android.content.IntentSender.SendIntentException;
Makoto Onuki22fcc682016-05-17 14:52:19 -070035import android.content.pm.ActivityInfo;
Makoto Onuki0acbb142016-03-22 17:02:57 -070036import android.content.pm.ApplicationInfo;
37import android.content.pm.IPackageManager;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080038import android.content.pm.IShortcutService;
39import android.content.pm.LauncherApps;
40import android.content.pm.LauncherApps.ShortcutQuery;
Makoto Onuki0acbb142016-03-22 17:02:57 -070041import android.content.pm.PackageInfo;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080042import android.content.pm.PackageManager;
Makoto Onuki20c95f82016-05-11 16:51:01 -070043import android.content.pm.PackageManager.NameNotFoundException;
Makoto Onuki2d5b4652016-03-11 16:09:54 -080044import android.content.pm.PackageManagerInternal;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080045import android.content.pm.ParceledListSlice;
Makoto Onuki2d5b4652016-03-11 16:09:54 -080046import android.content.pm.ResolveInfo;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080047import android.content.pm.ShortcutInfo;
48import android.content.pm.ShortcutServiceInternal;
49import android.content.pm.ShortcutServiceInternal.ShortcutChangeListener;
Makoto Onuki2d895c32016-12-02 15:48:40 -080050import android.content.pm.UserInfo;
Makoto Onuki157b1622016-06-02 16:13:10 -070051import android.content.res.Resources;
Makoto Onuki22fcc682016-05-17 14:52:19 -070052import android.content.res.XmlResourceParser;
Makoto Onuki55046222016-03-08 10:49:47 -080053import android.graphics.Bitmap;
54import android.graphics.Bitmap.CompressFormat;
Makoto Onuki55046222016-03-08 10:49:47 -080055import android.graphics.Canvas;
56import android.graphics.RectF;
Hyunyoung Song47037462017-05-08 16:51:43 -070057import android.graphics.drawable.AdaptiveIconDrawable;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080058import android.graphics.drawable.Icon;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070059import android.net.Uri;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080060import android.os.Binder;
Makoto Onuki33663282016-08-22 16:19:04 -070061import android.os.Build;
Sunny Goyal4ad6b572017-02-28 11:11:51 -080062import android.os.Bundle;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080063import android.os.Environment;
Makoto Onuki2e210c42016-03-30 08:30:36 -070064import android.os.FileUtils;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080065import android.os.Handler;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070066import android.os.LocaleList;
Makoto Onukiaa8b94a2016-03-17 13:14:05 -070067import android.os.Looper;
Makoto Onuki55046222016-03-08 10:49:47 -080068import android.os.ParcelFileDescriptor;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080069import android.os.PersistableBundle;
70import android.os.Process;
71import android.os.RemoteException;
72import android.os.ResultReceiver;
Makoto Onuki55046222016-03-08 10:49:47 -080073import android.os.SELinux;
Makoto Onukib08790c2016-06-23 14:05:46 -070074import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070075import android.os.ShellCallback;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080076import android.os.ShellCommand;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -070077import android.os.SystemClock;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080078import android.os.UserHandle;
Makoto Onukicdc78f72016-03-21 15:47:52 -070079import android.os.UserManager;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080080import android.text.TextUtils;
81import android.text.format.Time;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080082import android.util.ArraySet;
83import android.util.AtomicFile;
Makoto Onuki4362a662016-03-08 18:59:09 -080084import android.util.KeyValueListParser;
Makoto Onukiac042502016-05-20 16:39:42 -070085import android.util.Log;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080086import android.util.Slog;
87import android.util.SparseArray;
Makoto Onuki02f338e2016-07-29 09:40:40 -070088import android.util.SparseBooleanArray;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -070089import android.util.SparseIntArray;
90import android.util.SparseLongArray;
Makoto Onuki55046222016-03-08 10:49:47 -080091import android.util.TypedValue;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080092import android.util.Xml;
Makoto Onukib08790c2016-06-23 14:05:46 -070093import android.view.IWindowManager;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080094
95import com.android.internal.annotations.GuardedBy;
96import com.android.internal.annotations.VisibleForTesting;
97import com.android.internal.os.BackgroundThread;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060098import com.android.internal.util.DumpUtils;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080099import com.android.internal.util.FastXmlSerializer;
100import com.android.internal.util.Preconditions;
101import com.android.server.LocalServices;
102import com.android.server.SystemService;
Makoto Onukid99c6f02016-03-28 11:02:54 -0700103import com.android.server.pm.ShortcutUser.PackageWithUser;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800104
105import libcore.io.IoUtils;
106
Makoto Onuki76269922016-07-15 14:58:54 -0700107import org.json.JSONArray;
108import org.json.JSONException;
109import org.json.JSONObject;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800110import org.xmlpull.v1.XmlPullParser;
111import org.xmlpull.v1.XmlPullParserException;
112import org.xmlpull.v1.XmlSerializer;
113
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700114import java.io.BufferedInputStream;
115import java.io.BufferedOutputStream;
116import java.io.ByteArrayInputStream;
117import java.io.ByteArrayOutputStream;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800118import java.io.File;
119import java.io.FileDescriptor;
120import java.io.FileInputStream;
121import java.io.FileNotFoundException;
122import java.io.FileOutputStream;
123import java.io.IOException;
Makoto Onuki55046222016-03-08 10:49:47 -0800124import java.io.InputStream;
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700125import java.io.OutputStream;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800126import java.io.PrintWriter;
Makoto Onuki7001a612016-05-27 13:24:28 -0700127import java.lang.annotation.Retention;
128import java.lang.annotation.RetentionPolicy;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800129import java.net.URISyntaxException;
130import java.nio.charset.StandardCharsets;
131import java.util.ArrayList;
Makoto Onuki22fcc682016-05-17 14:52:19 -0700132import java.util.Collections;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800133import java.util.List;
Makoto Onukic51b2872016-05-04 15:24:50 -0700134import java.util.concurrent.atomic.AtomicBoolean;
Makoto Onuki2e210c42016-03-30 08:30:36 -0700135import java.util.function.Consumer;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800136import java.util.function.Predicate;
Makoto Onuki20b82212017-10-04 15:03:50 -0700137import java.util.regex.Pattern;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800138
139/**
140 * TODO:
Makoto Onuki22fcc682016-05-17 14:52:19 -0700141 * - getIconMaxWidth()/getIconMaxHeight() should use xdpi and ydpi.
Makoto Onukib5a012f2016-06-21 11:13:53 -0700142 * -> But TypedValue.applyDimension() doesn't differentiate x and y..?
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800143 *
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700144 * - Detect when already registered instances are passed to APIs again, which might break
Makoto Onukib08790c2016-06-23 14:05:46 -0700145 * internal bitmap handling.
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800146 */
147public class ShortcutService extends IShortcutService.Stub {
Makoto Onuki55046222016-03-08 10:49:47 -0800148 static final String TAG = "ShortcutService";
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800149
Makoto Onuki7001a612016-05-27 13:24:28 -0700150 static final boolean DEBUG = false; // STOPSHIP if true
Makoto Onuki41066a62016-03-09 16:18:44 -0800151 static final boolean DEBUG_LOAD = false; // STOPSHIP if true
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700152 static final boolean DEBUG_PROCSTATE = false; // STOPSHIP if true
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800153
Makoto Onuki4362a662016-03-08 18:59:09 -0800154 @VisibleForTesting
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700155 static final long DEFAULT_RESET_INTERVAL_SEC = 24 * 60 * 60; // 1 day
Makoto Onuki4362a662016-03-08 18:59:09 -0800156
157 @VisibleForTesting
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700158 static final int DEFAULT_MAX_UPDATES_PER_INTERVAL = 10;
Makoto Onuki4362a662016-03-08 18:59:09 -0800159
160 @VisibleForTesting
161 static final int DEFAULT_MAX_SHORTCUTS_PER_APP = 5;
162
163 @VisibleForTesting
164 static final int DEFAULT_MAX_ICON_DIMENSION_DP = 96;
165
166 @VisibleForTesting
167 static final int DEFAULT_MAX_ICON_DIMENSION_LOWRAM_DP = 48;
168
169 @VisibleForTesting
170 static final String DEFAULT_ICON_PERSIST_FORMAT = CompressFormat.PNG.name();
171
172 @VisibleForTesting
173 static final int DEFAULT_ICON_PERSIST_QUALITY = 100;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800174
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700175 @VisibleForTesting
176 static final int DEFAULT_SAVE_DELAY_MS = 3000;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800177
178 @VisibleForTesting
179 static final String FILENAME_BASE_STATE = "shortcut_service.xml";
180
181 @VisibleForTesting
182 static final String DIRECTORY_PER_USER = "shortcut_service";
183
184 @VisibleForTesting
Makoto Onuki50a320e2017-05-31 14:38:42 -0700185 static final String DIRECTORY_DUMP = "shortcut_dump";
186
187 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800188 static final String FILENAME_USER_PACKAGES = "shortcuts.xml";
189
Makoto Onuki55046222016-03-08 10:49:47 -0800190 static final String DIRECTORY_BITMAPS = "bitmaps";
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800191
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700192 private static final String TAG_ROOT = "root";
193 private static final String TAG_LAST_RESET_TIME = "last_reset_time";
Makoto Onuki55046222016-03-08 10:49:47 -0800194
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700195 private static final String ATTR_VALUE = "value";
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800196
Makoto Onukib08790c2016-06-23 14:05:46 -0700197 private static final String LAUNCHER_INTENT_CATEGORY = Intent.CATEGORY_LAUNCHER;
198
Makoto Onuki76269922016-07-15 14:58:54 -0700199 private static final String KEY_SHORTCUT = "shortcut";
200 private static final String KEY_LOW_RAM = "lowRam";
201 private static final String KEY_ICON_SIZE = "iconSize";
202
Makoto Onuki2d895c32016-12-02 15:48:40 -0800203 private static final String DUMMY_MAIN_ACTIVITY = "android.__dummy__";
204
Makoto Onuki4362a662016-03-08 18:59:09 -0800205 @VisibleForTesting
206 interface ConfigConstants {
207 /**
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700208 * Key name for the save delay, in milliseconds. (int)
209 */
210 String KEY_SAVE_DELAY_MILLIS = "save_delay_ms";
211
212 /**
Makoto Onuki4362a662016-03-08 18:59:09 -0800213 * Key name for the throttling reset interval, in seconds. (long)
214 */
215 String KEY_RESET_INTERVAL_SEC = "reset_interval_sec";
216
217 /**
218 * Key name for the max number of modifying API calls per app for every interval. (int)
219 */
Makoto Onukib6d35232016-04-04 15:57:17 -0700220 String KEY_MAX_UPDATES_PER_INTERVAL = "max_updates_per_interval";
Makoto Onuki4362a662016-03-08 18:59:09 -0800221
222 /**
223 * Key name for the max icon dimensions in DP, for non-low-memory devices.
224 */
225 String KEY_MAX_ICON_DIMENSION_DP = "max_icon_dimension_dp";
226
227 /**
228 * Key name for the max icon dimensions in DP, for low-memory devices.
229 */
230 String KEY_MAX_ICON_DIMENSION_DP_LOWRAM = "max_icon_dimension_dp_lowram";
231
232 /**
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700233 * Key name for the max dynamic shortcuts per activity. (int)
Makoto Onuki4362a662016-03-08 18:59:09 -0800234 */
235 String KEY_MAX_SHORTCUTS = "max_shortcuts";
236
237 /**
Makoto Onuki41066a62016-03-09 16:18:44 -0800238 * Key name for icon compression quality, 0-100.
Makoto Onuki4362a662016-03-08 18:59:09 -0800239 */
240 String KEY_ICON_QUALITY = "icon_quality";
241
242 /**
243 * Key name for icon compression format: "PNG", "JPEG" or "WEBP"
244 */
245 String KEY_ICON_FORMAT = "icon_format";
246 }
247
Makoto Onuki41066a62016-03-09 16:18:44 -0800248 final Context mContext;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800249
250 private final Object mLock = new Object();
251
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700252 private static List<ResolveInfo> EMPTY_RESOLVE_INFO = new ArrayList<>(0);
253
Mark Renoufe065f7c2016-11-01 11:48:24 -0400254 // Temporarily reverted to anonymous inner class form due to: b/32554459
255 private static Predicate<ResolveInfo> ACTIVITY_NOT_EXPORTED = new Predicate<ResolveInfo>() {
256 public boolean test(ResolveInfo ri) {
257 return !ri.activityInfo.exported;
258 }
259 };
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700260
Mark Renoufe065f7c2016-11-01 11:48:24 -0400261 // Temporarily reverted to anonymous inner class form due to: b/32554459
262 private static Predicate<PackageInfo> PACKAGE_NOT_INSTALLED = new Predicate<PackageInfo>() {
263 public boolean test(PackageInfo pi) {
264 return !isInstalled(pi);
265 }
266 };
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700267
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800268 private final Handler mHandler;
269
270 @GuardedBy("mLock")
271 private final ArrayList<ShortcutChangeListener> mListeners = new ArrayList<>(1);
272
273 @GuardedBy("mLock")
274 private long mRawLastResetTime;
275
276 /**
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -0800277 * User ID -> UserShortcuts
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800278 */
279 @GuardedBy("mLock")
Makoto Onuki31459242016-03-22 11:12:18 -0700280 private final SparseArray<ShortcutUser> mUsers = new SparseArray<>();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800281
282 /**
Makoto Onukib5a012f2016-06-21 11:13:53 -0700283 * Max number of dynamic + manifest shortcuts that each application can have at a time.
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800284 */
Makoto Onukib5a012f2016-06-21 11:13:53 -0700285 private int mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800286
287 /**
Makoto Onukib6d35232016-04-04 15:57:17 -0700288 * Max number of updating API calls that each application can make during the interval.
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800289 */
Makoto Onukib6d35232016-04-04 15:57:17 -0700290 int mMaxUpdatesPerInterval;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800291
292 /**
293 * Actual throttling-reset interval. By default it's a day.
294 */
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800295 private long mResetInterval;
296
Makoto Onuki55046222016-03-08 10:49:47 -0800297 /**
298 * Icon max width/height in pixels.
299 */
300 private int mMaxIconDimension;
301
Makoto Onuki4362a662016-03-08 18:59:09 -0800302 private CompressFormat mIconPersistFormat;
303 private int mIconPersistQuality;
Makoto Onuki55046222016-03-08 10:49:47 -0800304
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700305 private int mSaveDelayMillis;
306
Makoto Onuki0acbb142016-03-22 17:02:57 -0700307 private final IPackageManager mIPackageManager;
Makoto Onuki2d5b4652016-03-11 16:09:54 -0800308 private final PackageManagerInternal mPackageManagerInternal;
Makoto Onukicdc78f72016-03-21 15:47:52 -0700309 private final UserManager mUserManager;
Makoto Onukiac042502016-05-20 16:39:42 -0700310 private final UsageStatsManagerInternal mUsageStatsManagerInternal;
Makoto Onuki33525d22016-08-03 15:45:24 -0700311 private final ActivityManagerInternal mActivityManagerInternal;
Makoto Onuki2d5b4652016-03-11 16:09:54 -0800312
Makoto Onuki2d895c32016-12-02 15:48:40 -0800313 private final ShortcutRequestPinProcessor mShortcutRequestPinProcessor;
Makoto Onuki475c3652017-05-08 14:29:03 -0700314 private final ShortcutBitmapSaver mShortcutBitmapSaver;
Makoto Onuki50a320e2017-05-31 14:38:42 -0700315 private final ShortcutDumpFiles mShortcutDumpFiles;
Makoto Onuki2d895c32016-12-02 15:48:40 -0800316
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700317 @GuardedBy("mLock")
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700318 final SparseIntArray mUidState = new SparseIntArray();
319
320 @GuardedBy("mLock")
321 final SparseLongArray mUidLastForegroundElapsedTime = new SparseLongArray();
322
323 @GuardedBy("mLock")
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700324 private List<Integer> mDirtyUserIds = new ArrayList<>();
325
Makoto Onukic51b2872016-05-04 15:24:50 -0700326 private final AtomicBoolean mBootCompleted = new AtomicBoolean();
327
Makoto Onuki905e8852016-03-28 10:40:58 -0700328 private static final int PACKAGE_MATCH_FLAGS =
329 PackageManager.MATCH_DIRECT_BOOT_AWARE
Makoto Onukib08790c2016-06-23 14:05:46 -0700330 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE
331 | PackageManager.MATCH_UNINSTALLED_PACKAGES;
Makoto Onuki905e8852016-03-28 10:40:58 -0700332
Makoto Onuki02f338e2016-07-29 09:40:40 -0700333 @GuardedBy("mLock")
334 final SparseBooleanArray mUnlockedUsers = new SparseBooleanArray();
335
Makoto Onuki2e210c42016-03-30 08:30:36 -0700336 // Stats
337 @VisibleForTesting
338 interface Stats {
339 int GET_DEFAULT_HOME = 0;
340 int GET_PACKAGE_INFO = 1;
341 int GET_PACKAGE_INFO_WITH_SIG = 2;
342 int GET_APPLICATION_INFO = 3;
343 int LAUNCHER_PERMISSION_CHECK = 4;
Makoto Onuki6c1dbd52016-05-02 15:19:32 -0700344 int CLEANUP_DANGLING_BITMAPS = 5;
Makoto Onukib08790c2016-06-23 14:05:46 -0700345 int GET_ACTIVITY_WITH_METADATA = 6;
Makoto Onuki6dd9fb72016-06-01 13:55:54 -0700346 int GET_INSTALLED_PACKAGES = 7;
Makoto Onuki22fcc682016-05-17 14:52:19 -0700347 int CHECK_PACKAGE_CHANGES = 8;
Makoto Onuki157b1622016-06-02 16:13:10 -0700348 int GET_APPLICATION_RESOURCES = 9;
349 int RESOURCE_NAME_LOOKUP = 10;
Makoto Onukib08790c2016-06-23 14:05:46 -0700350 int GET_LAUNCHER_ACTIVITY = 11;
351 int CHECK_LAUNCHER_ACTIVITY = 12;
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700352 int IS_ACTIVITY_ENABLED = 13;
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700353 int PACKAGE_UPDATE_CHECK = 14;
Makoto Onuki085a05c2016-08-19 11:39:29 -0700354 int ASYNC_PRELOAD_USER_DELAY = 15;
Makoto Onuki2d895c32016-12-02 15:48:40 -0800355 int GET_DEFAULT_LAUNCHER = 16;
Makoto Onuki2e210c42016-03-30 08:30:36 -0700356
Makoto Onuki2d895c32016-12-02 15:48:40 -0800357 int COUNT = GET_DEFAULT_LAUNCHER + 1;
Makoto Onuki2e210c42016-03-30 08:30:36 -0700358 }
359
Makoto Onuki085a05c2016-08-19 11:39:29 -0700360 private static final String[] STAT_LABELS = {
361 "getHomeActivities()",
362 "Launcher permission check",
363 "getPackageInfo()",
364 "getPackageInfo(SIG)",
365 "getApplicationInfo",
366 "cleanupDanglingBitmaps",
367 "getActivity+metadata",
368 "getInstalledPackages",
369 "checkPackageChanges",
370 "getApplicationResources",
371 "resourceNameLookup",
372 "getLauncherActivity",
373 "checkLauncherActivity",
374 "isActivityEnabled",
375 "packageUpdateCheck",
Makoto Onuki2d895c32016-12-02 15:48:40 -0800376 "asyncPreloadUserDelay",
377 "getDefaultLauncher()"
Makoto Onuki085a05c2016-08-19 11:39:29 -0700378 };
379
Makoto Onuki2e210c42016-03-30 08:30:36 -0700380 final Object mStatLock = new Object();
381
382 @GuardedBy("mStatLock")
383 private final int[] mCountStats = new int[Stats.COUNT];
384
385 @GuardedBy("mStatLock")
386 private final long[] mDurationStats = new long[Stats.COUNT];
387
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700388 private static final int PROCESS_STATE_FOREGROUND_THRESHOLD =
389 ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
390
Makoto Onuki7001a612016-05-27 13:24:28 -0700391 static final int OPERATION_SET = 0;
392 static final int OPERATION_ADD = 1;
393 static final int OPERATION_UPDATE = 2;
394
395 /** @hide */
396 @IntDef(value = {
397 OPERATION_SET,
398 OPERATION_ADD,
399 OPERATION_UPDATE
Makoto Onukib08790c2016-06-23 14:05:46 -0700400 })
Makoto Onuki7001a612016-05-27 13:24:28 -0700401 @Retention(RetentionPolicy.SOURCE)
Makoto Onukib08790c2016-06-23 14:05:46 -0700402 @interface ShortcutOperation {
403 }
Makoto Onuki7001a612016-05-27 13:24:28 -0700404
Makoto Onukia2241832016-07-06 13:28:37 -0700405 @GuardedBy("mLock")
406 private int mWtfCount = 0;
407
408 @GuardedBy("mLock")
409 private Exception mLastWtfStacktrace;
410
Makoto Onukifc4cf2d2016-08-24 11:10:26 -0700411 static class InvalidFileFormatException extends Exception {
412 public InvalidFileFormatException(String message, Throwable cause) {
413 super(message, cause);
414 }
415 }
416
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800417 public ShortcutService(Context context) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700418 this(context, BackgroundThread.get().getLooper(), /*onyForPackgeManagerApis*/ false);
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700419 }
420
421 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700422 ShortcutService(Context context, Looper looper, boolean onlyForPackageManagerApis) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800423 mContext = Preconditions.checkNotNull(context);
424 LocalServices.addService(ShortcutServiceInternal.class, new LocalService());
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700425 mHandler = new Handler(looper);
Makoto Onuki0acbb142016-03-22 17:02:57 -0700426 mIPackageManager = AppGlobals.getPackageManager();
Makoto Onukiac042502016-05-20 16:39:42 -0700427 mPackageManagerInternal = Preconditions.checkNotNull(
428 LocalServices.getService(PackageManagerInternal.class));
429 mUserManager = Preconditions.checkNotNull(context.getSystemService(UserManager.class));
430 mUsageStatsManagerInternal = Preconditions.checkNotNull(
431 LocalServices.getService(UsageStatsManagerInternal.class));
Makoto Onuki33525d22016-08-03 15:45:24 -0700432 mActivityManagerInternal = Preconditions.checkNotNull(
433 LocalServices.getService(ActivityManagerInternal.class));
Makoto Onukicdc78f72016-03-21 15:47:52 -0700434
Makoto Onuki2d895c32016-12-02 15:48:40 -0800435 mShortcutRequestPinProcessor = new ShortcutRequestPinProcessor(this, mLock);
Makoto Onuki475c3652017-05-08 14:29:03 -0700436 mShortcutBitmapSaver = new ShortcutBitmapSaver(this);
Makoto Onuki50a320e2017-05-31 14:38:42 -0700437 mShortcutDumpFiles = new ShortcutDumpFiles(this);
Makoto Onuki2d895c32016-12-02 15:48:40 -0800438
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700439 if (onlyForPackageManagerApis) {
440 return; // Don't do anything further. For unit tests only.
441 }
442
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700443 // Register receivers.
444
445 // We need to set a priority, so let's just not use PackageMonitor for now.
446 // TODO Refactor PackageMonitor to support priorities.
447 final IntentFilter packageFilter = new IntentFilter();
448 packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
449 packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
450 packageFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
451 packageFilter.addAction(Intent.ACTION_PACKAGE_DATA_CLEARED);
452 packageFilter.addDataScheme("package");
453 packageFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
454 mContext.registerReceiverAsUser(mPackageMonitor, UserHandle.ALL,
455 packageFilter, null, mHandler);
456
Makoto Onuki10305202016-07-14 18:14:08 -0700457 final IntentFilter preferedActivityFilter = new IntentFilter();
458 preferedActivityFilter.addAction(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
459 preferedActivityFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
460 mContext.registerReceiverAsUser(mPackageMonitor, UserHandle.ALL,
461 preferedActivityFilter, null, mHandler);
462
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700463 final IntentFilter localeFilter = new IntentFilter();
464 localeFilter.addAction(Intent.ACTION_LOCALE_CHANGED);
465 localeFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
466 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL,
467 localeFilter, null, mHandler);
Makoto Onukif34c3082016-07-13 10:25:25 -0700468
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700469 injectRegisterUidObserver(mUidObserver, ActivityManager.UID_OBSERVER_PROCSTATE
470 | ActivityManager.UID_OBSERVER_GONE);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800471 }
472
Makoto Onuki2e210c42016-03-30 08:30:36 -0700473 void logDurationStat(int statId, long start) {
474 synchronized (mStatLock) {
475 mCountStats[statId]++;
Makoto Onuki6c1dbd52016-05-02 15:19:32 -0700476 mDurationStats[statId] += (injectElapsedRealtime() - start);
Makoto Onuki2e210c42016-03-30 08:30:36 -0700477 }
478 }
479
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700480 public String injectGetLocaleTagsForUser(@UserIdInt int userId) {
481 // TODO This should get the per-user locale. b/30123329 b/30119489
482 return LocaleList.getDefault().toLanguageTags();
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700483 }
484
485 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Makoto Onukib08790c2016-06-23 14:05:46 -0700486 @Override
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700487 public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onukidc3f6d12017-09-22 17:22:50 -0700488 injectPostToHandler(() -> handleOnUidStateChanged(uid, procState));
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700489 }
490
Makoto Onukib08790c2016-06-23 14:05:46 -0700491 @Override
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700492 public void onUidGone(int uid, boolean disabled) {
Makoto Onukidc3f6d12017-09-22 17:22:50 -0700493 injectPostToHandler(() ->
494 handleOnUidStateChanged(uid, ActivityManager.PROCESS_STATE_NONEXISTENT));
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700495 }
496
Makoto Onukib08790c2016-06-23 14:05:46 -0700497 @Override
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700498 public void onUidActive(int uid) {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700499 }
500
Makoto Onukib08790c2016-06-23 14:05:46 -0700501 @Override
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700502 public void onUidIdle(int uid, boolean disabled) {
503 }
504
505 @Override public void onUidCachedChanged(int uid, boolean cached) {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700506 }
507 };
508
509 void handleOnUidStateChanged(int uid, int procState) {
510 if (DEBUG_PROCSTATE) {
511 Slog.d(TAG, "onUidStateChanged: uid=" + uid + " state=" + procState);
512 }
513 synchronized (mLock) {
514 mUidState.put(uid, procState);
515
516 // We need to keep track of last time an app comes to foreground.
517 // See ShortcutPackage.getApiCallCount() for how it's used.
518 // It doesn't have to be persisted, but it needs to be the elapsed time.
519 if (isProcessStateForeground(procState)) {
520 mUidLastForegroundElapsedTime.put(uid, injectElapsedRealtime());
521 }
522 }
523 }
524
525 private boolean isProcessStateForeground(int processState) {
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800526 return processState <= PROCESS_STATE_FOREGROUND_THRESHOLD;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700527 }
528
529 boolean isUidForegroundLocked(int uid) {
530 if (uid == Process.SYSTEM_UID) {
531 // IUidObserver doesn't report the state of SYSTEM, but it always has bound services,
532 // so it's foreground anyway.
533 return true;
534 }
Makoto Onuki33525d22016-08-03 15:45:24 -0700535 // First, check with the local cache.
536 if (isProcessStateForeground(mUidState.get(uid, ActivityManager.MAX_PROCESS_STATE))) {
537 return true;
538 }
539 // If the cache says background, reach out to AM. Since it'll internally need to hold
540 // the AM lock, we use it as a last resort.
541 return isProcessStateForeground(mActivityManagerInternal.getUidProcessState(uid));
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700542 }
543
544 long getUidLastForegroundElapsedTimeLocked(int uid) {
545 return mUidLastForegroundElapsedTime.get(uid);
546 }
547
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800548 /**
549 * System service lifecycle.
550 */
551 public static final class Lifecycle extends SystemService {
552 final ShortcutService mService;
553
554 public Lifecycle(Context context) {
555 super(context);
556 mService = new ShortcutService(context);
557 }
558
559 @Override
560 public void onStart() {
561 publishBinderService(Context.SHORTCUT_SERVICE, mService);
562 }
563
564 @Override
565 public void onBootPhase(int phase) {
566 mService.onBootPhase(phase);
567 }
568
569 @Override
Makoto Onuki01ce92b2017-04-28 12:24:16 -0700570 public void onStopUser(int userHandle) {
571 mService.handleStopUser(userHandle);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800572 }
573
574 @Override
Makoto Onukif3a572b2016-03-10 12:28:38 -0800575 public void onUnlockUser(int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -0700576 mService.handleUnlockUser(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800577 }
578 }
579
580 /** lifecycle event */
581 void onBootPhase(int phase) {
582 if (DEBUG) {
583 Slog.d(TAG, "onBootPhase: " + phase);
584 }
585 switch (phase) {
586 case SystemService.PHASE_LOCK_SETTINGS_READY:
587 initialize();
588 break;
Makoto Onukic51b2872016-05-04 15:24:50 -0700589 case SystemService.PHASE_BOOT_COMPLETED:
590 mBootCompleted.set(true);
591 break;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800592 }
593 }
594
595 /** lifecycle event */
Makoto Onukicdc78f72016-03-21 15:47:52 -0700596 void handleUnlockUser(int userId) {
Makoto Onuki22fcc682016-05-17 14:52:19 -0700597 if (DEBUG) {
Makoto Onuki085a05c2016-08-19 11:39:29 -0700598 Slog.d(TAG, "handleUnlockUser: user=" + userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700599 }
Makoto Onukicdc78f72016-03-21 15:47:52 -0700600 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -0700601 mUnlockedUsers.put(userId, true);
Makoto Onukicdc78f72016-03-21 15:47:52 -0700602 }
Makoto Onuki085a05c2016-08-19 11:39:29 -0700603
604 // Preload the user data.
605 // Note, we don't use mHandler here but instead just start a new thread.
606 // This is because mHandler (which uses com.android.internal.os.BackgroundThread) is very
607 // busy at this point and this could take hundreds of milliseconds, which would be too
608 // late since the launcher would already have started.
609 // So we just create a new thread. This code runs rarely, so we don't use a thread pool
610 // or anything.
611 final long start = injectElapsedRealtime();
612 injectRunOnNewThread(() -> {
613 synchronized (mLock) {
614 logDurationStat(Stats.ASYNC_PRELOAD_USER_DELAY, start);
615 getUserShortcutsLocked(userId);
616 }
617 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800618 }
619
620 /** lifecycle event */
Makoto Onuki01ce92b2017-04-28 12:24:16 -0700621 void handleStopUser(int userId) {
Makoto Onuki02f338e2016-07-29 09:40:40 -0700622 if (DEBUG) {
Makoto Onuki01ce92b2017-04-28 12:24:16 -0700623 Slog.d(TAG, "handleStopUser: user=" + userId);
Makoto Onuki02f338e2016-07-29 09:40:40 -0700624 }
Makoto Onukicdc78f72016-03-21 15:47:52 -0700625 synchronized (mLock) {
626 unloadUserLocked(userId);
Makoto Onuki02f338e2016-07-29 09:40:40 -0700627
628 mUnlockedUsers.put(userId, false);
Makoto Onukicdc78f72016-03-21 15:47:52 -0700629 }
630 }
631
632 private void unloadUserLocked(int userId) {
633 if (DEBUG) {
634 Slog.d(TAG, "unloadUserLocked: user=" + userId);
635 }
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700636 // Save all dirty information.
637 saveDirtyInfo();
638
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800639 // Unload
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -0800640 mUsers.delete(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800641 }
642
643 /** Return the base state file name */
644 private AtomicFile getBaseStateFile() {
645 final File path = new File(injectSystemDataPath(), FILENAME_BASE_STATE);
646 path.mkdirs();
647 return new AtomicFile(path);
648 }
649
650 /**
651 * Init the instance. (load the state file, etc)
652 */
653 private void initialize() {
654 synchronized (mLock) {
Makoto Onuki4362a662016-03-08 18:59:09 -0800655 loadConfigurationLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800656 loadBaseStateLocked();
657 }
658 }
659
Makoto Onuki4362a662016-03-08 18:59:09 -0800660 /**
661 * Load the configuration from Settings.
662 */
663 private void loadConfigurationLocked() {
664 updateConfigurationLocked(injectShortcutManagerConstants());
665 }
Makoto Onuki55046222016-03-08 10:49:47 -0800666
Makoto Onuki4362a662016-03-08 18:59:09 -0800667 /**
668 * Load the configuration from Settings.
669 */
670 @VisibleForTesting
671 boolean updateConfigurationLocked(String config) {
672 boolean result = true;
673
674 final KeyValueListParser parser = new KeyValueListParser(',');
675 try {
676 parser.setString(config);
677 } catch (IllegalArgumentException e) {
678 // Failed to parse the settings string, log this and move on
679 // with defaults.
680 Slog.e(TAG, "Bad shortcut manager settings", e);
681 result = false;
682 }
683
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700684 mSaveDelayMillis = Math.max(0, (int) parser.getLong(ConfigConstants.KEY_SAVE_DELAY_MILLIS,
685 DEFAULT_SAVE_DELAY_MS));
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700686
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700687 mResetInterval = Math.max(1, parser.getLong(
Makoto Onuki4362a662016-03-08 18:59:09 -0800688 ConfigConstants.KEY_RESET_INTERVAL_SEC, DEFAULT_RESET_INTERVAL_SEC)
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700689 * 1000L);
Makoto Onuki4362a662016-03-08 18:59:09 -0800690
Makoto Onukib6d35232016-04-04 15:57:17 -0700691 mMaxUpdatesPerInterval = Math.max(0, (int) parser.getLong(
692 ConfigConstants.KEY_MAX_UPDATES_PER_INTERVAL, DEFAULT_MAX_UPDATES_PER_INTERVAL));
Makoto Onuki4362a662016-03-08 18:59:09 -0800693
Makoto Onukib5a012f2016-06-21 11:13:53 -0700694 mMaxShortcuts = Math.max(0, (int) parser.getLong(
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700695 ConfigConstants.KEY_MAX_SHORTCUTS, DEFAULT_MAX_SHORTCUTS_PER_APP));
Makoto Onuki4362a662016-03-08 18:59:09 -0800696
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700697 final int iconDimensionDp = Math.max(1, injectIsLowRamDevice()
Makoto Onuki4362a662016-03-08 18:59:09 -0800698 ? (int) parser.getLong(
Makoto Onukib08790c2016-06-23 14:05:46 -0700699 ConfigConstants.KEY_MAX_ICON_DIMENSION_DP_LOWRAM,
700 DEFAULT_MAX_ICON_DIMENSION_LOWRAM_DP)
Makoto Onuki4362a662016-03-08 18:59:09 -0800701 : (int) parser.getLong(
Makoto Onukib08790c2016-06-23 14:05:46 -0700702 ConfigConstants.KEY_MAX_ICON_DIMENSION_DP,
703 DEFAULT_MAX_ICON_DIMENSION_DP));
Makoto Onuki4362a662016-03-08 18:59:09 -0800704
705 mMaxIconDimension = injectDipToPixel(iconDimensionDp);
706
707 mIconPersistFormat = CompressFormat.valueOf(
708 parser.getString(ConfigConstants.KEY_ICON_FORMAT, DEFAULT_ICON_PERSIST_FORMAT));
709
710 mIconPersistQuality = (int) parser.getLong(
711 ConfigConstants.KEY_ICON_QUALITY,
712 DEFAULT_ICON_PERSIST_QUALITY);
713
714 return result;
715 }
716
717 @VisibleForTesting
718 String injectShortcutManagerConstants() {
719 return android.provider.Settings.Global.getString(
720 mContext.getContentResolver(),
721 android.provider.Settings.Global.SHORTCUT_MANAGER_CONSTANTS);
722 }
723
724 @VisibleForTesting
725 int injectDipToPixel(int dip) {
726 return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip,
727 mContext.getResources().getDisplayMetrics());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800728 }
729
Makoto Onuki55046222016-03-08 10:49:47 -0800730 // === Persisting ===
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800731
732 @Nullable
Makoto Onuki41066a62016-03-09 16:18:44 -0800733 static String parseStringAttribute(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800734 return parser.getAttributeValue(null, attribute);
735 }
736
Makoto Onuki0acbb142016-03-22 17:02:57 -0700737 static boolean parseBooleanAttribute(XmlPullParser parser, String attribute) {
738 return parseLongAttribute(parser, attribute) == 1;
739 }
740
Makoto Onuki41066a62016-03-09 16:18:44 -0800741 static int parseIntAttribute(XmlPullParser parser, String attribute) {
742 return (int) parseLongAttribute(parser, attribute);
743 }
744
Makoto Onukid99c6f02016-03-28 11:02:54 -0700745 static int parseIntAttribute(XmlPullParser parser, String attribute, int def) {
746 return (int) parseLongAttribute(parser, attribute, def);
747 }
748
Makoto Onuki41066a62016-03-09 16:18:44 -0800749 static long parseLongAttribute(XmlPullParser parser, String attribute) {
Makoto Onukid99c6f02016-03-28 11:02:54 -0700750 return parseLongAttribute(parser, attribute, 0);
751 }
752
753 static long parseLongAttribute(XmlPullParser parser, String attribute, long def) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800754 final String value = parseStringAttribute(parser, attribute);
755 if (TextUtils.isEmpty(value)) {
Makoto Onukid99c6f02016-03-28 11:02:54 -0700756 return def;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800757 }
758 try {
759 return Long.parseLong(value);
760 } catch (NumberFormatException e) {
761 Slog.e(TAG, "Error parsing long " + value);
Makoto Onukid99c6f02016-03-28 11:02:54 -0700762 return def;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800763 }
764 }
765
766 @Nullable
Makoto Onuki41066a62016-03-09 16:18:44 -0800767 static ComponentName parseComponentNameAttribute(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800768 final String value = parseStringAttribute(parser, attribute);
769 if (TextUtils.isEmpty(value)) {
770 return null;
771 }
772 return ComponentName.unflattenFromString(value);
773 }
774
775 @Nullable
Makoto Onuki440a1ea2016-07-20 14:21:18 -0700776 static Intent parseIntentAttributeNoDefault(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800777 final String value = parseStringAttribute(parser, attribute);
Makoto Onukib5a012f2016-06-21 11:13:53 -0700778 Intent parsed = null;
779 if (!TextUtils.isEmpty(value)) {
780 try {
781 parsed = Intent.parseUri(value, /* flags =*/ 0);
782 } catch (URISyntaxException e) {
783 Slog.e(TAG, "Error parsing intent", e);
784 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800785 }
Makoto Onuki440a1ea2016-07-20 14:21:18 -0700786 return parsed;
787 }
788
789 @Nullable
790 static Intent parseIntentAttribute(XmlPullParser parser, String attribute) {
791 Intent parsed = parseIntentAttributeNoDefault(parser, attribute);
Makoto Onukib5a012f2016-06-21 11:13:53 -0700792 if (parsed == null) {
793 // Default intent.
794 parsed = new Intent(Intent.ACTION_VIEW);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800795 }
Makoto Onukib5a012f2016-06-21 11:13:53 -0700796 return parsed;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800797 }
798
Makoto Onuki41066a62016-03-09 16:18:44 -0800799 static void writeTagValue(XmlSerializer out, String tag, String value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800800 if (TextUtils.isEmpty(value)) return;
801
802 out.startTag(null, tag);
803 out.attribute(null, ATTR_VALUE, value);
804 out.endTag(null, tag);
805 }
806
Makoto Onuki41066a62016-03-09 16:18:44 -0800807 static void writeTagValue(XmlSerializer out, String tag, long value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800808 writeTagValue(out, tag, Long.toString(value));
809 }
810
Makoto Onuki2d5b4652016-03-11 16:09:54 -0800811 static void writeTagValue(XmlSerializer out, String tag, ComponentName name) throws IOException {
812 if (name == null) return;
813 writeTagValue(out, tag, name.flattenToString());
814 }
815
Makoto Onuki41066a62016-03-09 16:18:44 -0800816 static void writeTagExtra(XmlSerializer out, String tag, PersistableBundle bundle)
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800817 throws IOException, XmlPullParserException {
818 if (bundle == null) return;
819
820 out.startTag(null, tag);
821 bundle.saveToXml(out);
822 out.endTag(null, tag);
823 }
824
Makoto Onuki22fcc682016-05-17 14:52:19 -0700825 static void writeAttr(XmlSerializer out, String name, CharSequence value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800826 if (TextUtils.isEmpty(value)) return;
827
Makoto Onuki22fcc682016-05-17 14:52:19 -0700828 out.attribute(null, name, value.toString());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800829 }
830
Makoto Onuki41066a62016-03-09 16:18:44 -0800831 static void writeAttr(XmlSerializer out, String name, long value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800832 writeAttr(out, name, String.valueOf(value));
833 }
834
Makoto Onuki0acbb142016-03-22 17:02:57 -0700835 static void writeAttr(XmlSerializer out, String name, boolean value) throws IOException {
836 if (value) {
837 writeAttr(out, name, "1");
838 }
839 }
840
Makoto Onuki41066a62016-03-09 16:18:44 -0800841 static void writeAttr(XmlSerializer out, String name, ComponentName comp) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800842 if (comp == null) return;
843 writeAttr(out, name, comp.flattenToString());
844 }
845
Makoto Onuki41066a62016-03-09 16:18:44 -0800846 static void writeAttr(XmlSerializer out, String name, Intent intent) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800847 if (intent == null) return;
848
849 writeAttr(out, name, intent.toUri(/* flags =*/ 0));
850 }
851
852 @VisibleForTesting
853 void saveBaseStateLocked() {
854 final AtomicFile file = getBaseStateFile();
855 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700856 Slog.d(TAG, "Saving to " + file.getBaseFile());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800857 }
858
859 FileOutputStream outs = null;
860 try {
861 outs = file.startWrite();
862
863 // Write to XML
864 XmlSerializer out = new FastXmlSerializer();
865 out.setOutput(outs, StandardCharsets.UTF_8.name());
866 out.startDocument(null, true);
867 out.startTag(null, TAG_ROOT);
868
869 // Body.
870 writeTagValue(out, TAG_LAST_RESET_TIME, mRawLastResetTime);
871
872 // Epilogue.
873 out.endTag(null, TAG_ROOT);
874 out.endDocument();
875
876 // Close.
877 file.finishWrite(outs);
878 } catch (IOException e) {
879 Slog.e(TAG, "Failed to write to file " + file.getBaseFile(), e);
880 file.failWrite(outs);
881 }
882 }
883
884 private void loadBaseStateLocked() {
885 mRawLastResetTime = 0;
886
887 final AtomicFile file = getBaseStateFile();
888 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700889 Slog.d(TAG, "Loading from " + file.getBaseFile());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800890 }
891 try (FileInputStream in = file.openRead()) {
892 XmlPullParser parser = Xml.newPullParser();
893 parser.setInput(in, StandardCharsets.UTF_8.name());
894
895 int type;
896 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
897 if (type != XmlPullParser.START_TAG) {
898 continue;
899 }
900 final int depth = parser.getDepth();
901 // Check the root tag
902 final String tag = parser.getName();
903 if (depth == 1) {
904 if (!TAG_ROOT.equals(tag)) {
905 Slog.e(TAG, "Invalid root tag: " + tag);
906 return;
907 }
908 continue;
909 }
910 // Assume depth == 2
911 switch (tag) {
912 case TAG_LAST_RESET_TIME:
913 mRawLastResetTime = parseLongAttribute(parser, ATTR_VALUE);
914 break;
915 default:
916 Slog.e(TAG, "Invalid tag: " + tag);
917 break;
918 }
919 }
920 } catch (FileNotFoundException e) {
921 // Use the default
Makoto Onukib08790c2016-06-23 14:05:46 -0700922 } catch (IOException | XmlPullParserException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800923 Slog.e(TAG, "Failed to read file " + file.getBaseFile(), e);
924
925 mRawLastResetTime = 0;
926 }
927 // Adjust the last reset time.
928 getLastResetTimeLocked();
929 }
930
Makoto Onuki0eed4412016-07-21 11:21:59 -0700931 @VisibleForTesting
932 final File getUserFile(@UserIdInt int userId) {
933 return new File(injectUserDataPath(userId), FILENAME_USER_PACKAGES);
934 }
935
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800936 private void saveUserLocked(@UserIdInt int userId) {
Makoto Onuki0eed4412016-07-21 11:21:59 -0700937 final File path = getUserFile(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800938 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700939 Slog.d(TAG, "Saving to " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800940 }
Makoto Onuki475c3652017-05-08 14:29:03 -0700941
942 mShortcutBitmapSaver.waitForAllSavesLocked();
943
Makoto Onuki0eed4412016-07-21 11:21:59 -0700944 path.getParentFile().mkdirs();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800945 final AtomicFile file = new AtomicFile(path);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700946 FileOutputStream os = null;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800947 try {
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700948 os = file.startWrite();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800949
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700950 saveUserInternalLocked(userId, os, /* forBackup= */ false);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800951
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700952 file.finishWrite(os);
Makoto Onuki1e173232016-08-10 10:47:13 -0700953
954 // Remove all dangling bitmap files.
955 cleanupDanglingBitmapDirectoriesLocked(userId);
Makoto Onukib08790c2016-06-23 14:05:46 -0700956 } catch (XmlPullParserException | IOException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800957 Slog.e(TAG, "Failed to write to file " + file.getBaseFile(), e);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700958 file.failWrite(os);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800959 }
960 }
961
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700962 private void saveUserInternalLocked(@UserIdInt int userId, OutputStream os,
963 boolean forBackup) throws IOException, XmlPullParserException {
964
965 final BufferedOutputStream bos = new BufferedOutputStream(os);
966
967 // Write to XML
968 XmlSerializer out = new FastXmlSerializer();
969 out.setOutput(bos, StandardCharsets.UTF_8.name());
970 out.startDocument(null, true);
971
Makoto Onukic51b2872016-05-04 15:24:50 -0700972 getUserShortcutsLocked(userId).saveToXml(out, forBackup);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700973
974 out.endDocument();
975
976 bos.flush();
977 os.flush();
978 }
979
Makoto Onuki41066a62016-03-09 16:18:44 -0800980 static IOException throwForInvalidTag(int depth, String tag) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800981 throw new IOException(String.format("Invalid tag '%s' found at depth %d", tag, depth));
982 }
983
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700984 static void warnForInvalidTag(int depth, String tag) throws IOException {
985 Slog.w(TAG, String.format("Invalid tag '%s' found at depth %d", tag, depth));
986 }
987
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800988 @Nullable
Makoto Onuki31459242016-03-22 11:12:18 -0700989 private ShortcutUser loadUserLocked(@UserIdInt int userId) {
Makoto Onuki0eed4412016-07-21 11:21:59 -0700990 final File path = getUserFile(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800991 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700992 Slog.d(TAG, "Loading from " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800993 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800994 final AtomicFile file = new AtomicFile(path);
995
996 final FileInputStream in;
997 try {
998 in = file.openRead();
999 } catch (FileNotFoundException e) {
1000 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001001 Slog.d(TAG, "Not found " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001002 }
1003 return null;
1004 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001005 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07001006 final ShortcutUser ret = loadUserInternal(userId, in, /* forBackup= */ false);
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001007 return ret;
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07001008 } catch (IOException | XmlPullParserException | InvalidFileFormatException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001009 Slog.e(TAG, "Failed to read file " + file.getBaseFile(), e);
1010 return null;
1011 } finally {
1012 IoUtils.closeQuietly(in);
1013 }
1014 }
1015
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001016 private ShortcutUser loadUserInternal(@UserIdInt int userId, InputStream is,
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07001017 boolean fromBackup) throws XmlPullParserException, IOException,
1018 InvalidFileFormatException {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001019
1020 final BufferedInputStream bis = new BufferedInputStream(is);
1021
1022 ShortcutUser ret = null;
1023 XmlPullParser parser = Xml.newPullParser();
1024 parser.setInput(bis, StandardCharsets.UTF_8.name());
1025
1026 int type;
1027 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1028 if (type != XmlPullParser.START_TAG) {
1029 continue;
1030 }
1031 final int depth = parser.getDepth();
1032
1033 final String tag = parser.getName();
1034 if (DEBUG_LOAD) {
1035 Slog.d(TAG, String.format("depth=%d type=%d name=%s",
1036 depth, type, tag));
1037 }
1038 if ((depth == 1) && ShortcutUser.TAG_ROOT.equals(tag)) {
1039 ret = ShortcutUser.loadFromXml(this, parser, userId, fromBackup);
1040 continue;
1041 }
1042 throwForInvalidTag(depth, tag);
1043 }
1044 return ret;
1045 }
1046
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001047 private void scheduleSaveBaseState() {
Makoto Onuki0acbb142016-03-22 17:02:57 -07001048 scheduleSaveInner(UserHandle.USER_NULL); // Special case -- use USER_NULL for base state.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001049 }
1050
Makoto Onuki2d5b4652016-03-11 16:09:54 -08001051 void scheduleSaveUser(@UserIdInt int userId) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07001052 scheduleSaveInner(userId);
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001053 }
1054
1055 // In order to re-schedule, we need to reuse the same instance, so keep it in final.
1056 private final Runnable mSaveDirtyInfoRunner = this::saveDirtyInfo;
1057
Makoto Onuki0acbb142016-03-22 17:02:57 -07001058 private void scheduleSaveInner(@UserIdInt int userId) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001059 if (DEBUG) {
1060 Slog.d(TAG, "Scheduling to save for " + userId);
1061 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001062 synchronized (mLock) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001063 if (!mDirtyUserIds.contains(userId)) {
1064 mDirtyUserIds.add(userId);
1065 }
1066 }
1067 // If already scheduled, remove that and re-schedule in N seconds.
1068 mHandler.removeCallbacks(mSaveDirtyInfoRunner);
1069 mHandler.postDelayed(mSaveDirtyInfoRunner, mSaveDelayMillis);
1070 }
1071
1072 @VisibleForTesting
1073 void saveDirtyInfo() {
1074 if (DEBUG) {
1075 Slog.d(TAG, "saveDirtyInfo");
1076 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001077 try {
1078 synchronized (mLock) {
1079 for (int i = mDirtyUserIds.size() - 1; i >= 0; i--) {
1080 final int userId = mDirtyUserIds.get(i);
1081 if (userId == UserHandle.USER_NULL) { // USER_NULL for base state.
1082 saveBaseStateLocked();
1083 } else {
1084 saveUserLocked(userId);
1085 }
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001086 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001087 mDirtyUserIds.clear();
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001088 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001089 } catch (Exception e) {
1090 wtf("Exception in saveDirtyInfo", e);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001091 }
1092 }
1093
1094 /** Return the last reset time. */
1095 long getLastResetTimeLocked() {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001096 updateTimesLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001097 return mRawLastResetTime;
1098 }
1099
1100 /** Return the next reset time. */
1101 long getNextResetTimeLocked() {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001102 updateTimesLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001103 return mRawLastResetTime + mResetInterval;
1104 }
1105
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001106 static boolean isClockValid(long time) {
1107 return time >= 1420070400; // Thu, 01 Jan 2015 00:00:00 GMT
1108 }
1109
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001110 /**
1111 * Update the last reset time.
1112 */
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001113 private void updateTimesLocked() {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001114
1115 final long now = injectCurrentTimeMillis();
1116
1117 final long prevLastResetTime = mRawLastResetTime;
1118
1119 if (mRawLastResetTime == 0) { // first launch.
1120 // TODO Randomize??
1121 mRawLastResetTime = now;
1122 } else if (now < mRawLastResetTime) {
1123 // Clock rewound.
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001124 if (isClockValid(now)) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001125 Slog.w(TAG, "Clock rewound");
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001126 // TODO Randomize??
1127 mRawLastResetTime = now;
1128 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001129 } else {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001130 if ((mRawLastResetTime + mResetInterval) <= now) {
1131 final long offset = mRawLastResetTime % mResetInterval;
1132 mRawLastResetTime = ((now / mResetInterval) * mResetInterval) + offset;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001133 }
1134 }
1135 if (prevLastResetTime != mRawLastResetTime) {
1136 scheduleSaveBaseState();
1137 }
1138 }
1139
Makoto Onuki1e173232016-08-10 10:47:13 -07001140 // Requires mLock held, but "Locked" prefix would look weired so we just say "L".
Makoto Onuki02f338e2016-07-29 09:40:40 -07001141 protected boolean isUserUnlockedL(@UserIdInt int userId) {
Makoto Onuki1e173232016-08-10 10:47:13 -07001142 // First, check the local copy.
1143 if (mUnlockedUsers.get(userId)) {
1144 return true;
1145 }
1146 // If the local copy says the user is locked, check with AM for the actual state, since
1147 // the user might just have been unlocked.
1148 // Note we just don't use isUserUnlockingOrUnlocked() here, because it'll return false
1149 // when the user is STOPPING, which we still want to consider as "unlocked".
1150 final long token = injectClearCallingIdentity();
1151 try {
1152 return mUserManager.isUserUnlockingOrUnlocked(userId);
1153 } finally {
1154 injectRestoreCallingIdentity(token);
1155 }
Makoto Onuki9c850012016-07-26 15:50:50 -07001156 }
1157
Makoto Onuki02f338e2016-07-29 09:40:40 -07001158 // Requires mLock held, but "Locked" prefix would look weired so we jsut say "L".
1159 void throwIfUserLockedL(@UserIdInt int userId) {
1160 if (!isUserUnlockedL(userId)) {
Makoto Onuki9c850012016-07-26 15:50:50 -07001161 throw new IllegalStateException("User " + userId + " is locked or not running");
1162 }
1163 }
1164
Makoto Onukicdc78f72016-03-21 15:47:52 -07001165 @GuardedBy("mLock")
1166 @NonNull
Makoto Onuki2e210c42016-03-30 08:30:36 -07001167 private boolean isUserLoadedLocked(@UserIdInt int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07001168 return mUsers.get(userId) != null;
1169 }
1170
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001171 /** Return the per-user state. */
1172 @GuardedBy("mLock")
1173 @NonNull
Makoto Onuki31459242016-03-22 11:12:18 -07001174 ShortcutUser getUserShortcutsLocked(@UserIdInt int userId) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001175 if (!isUserUnlockedL(userId)) {
Makoto Onuki9c850012016-07-26 15:50:50 -07001176 wtf("User still locked");
Makoto Onuki9c850012016-07-26 15:50:50 -07001177 }
1178
Makoto Onuki31459242016-03-22 11:12:18 -07001179 ShortcutUser userPackages = mUsers.get(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001180 if (userPackages == null) {
1181 userPackages = loadUserLocked(userId);
1182 if (userPackages == null) {
Makoto Onukic51b2872016-05-04 15:24:50 -07001183 userPackages = new ShortcutUser(this, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001184 }
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08001185 mUsers.put(userId, userPackages);
Makoto Onuki085a05c2016-08-19 11:39:29 -07001186
1187 // Also when a user's data is first accessed, scan all packages.
1188 checkPackageChanges(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001189 }
1190 return userPackages;
1191 }
1192
Makoto Onuki2e210c42016-03-30 08:30:36 -07001193 void forEachLoadedUserLocked(@NonNull Consumer<ShortcutUser> c) {
1194 for (int i = mUsers.size() - 1; i >= 0; i--) {
1195 c.accept(mUsers.valueAt(i));
1196 }
1197 }
1198
Makoto Onukic8c33292016-09-12 16:36:59 -07001199 /**
1200 * Return the per-user per-package state. If the caller is a publisher, use
1201 * {@link #getPackageShortcutsForPublisherLocked} instead.
1202 */
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001203 @GuardedBy("mLock")
1204 @NonNull
Makoto Onuki31459242016-03-22 11:12:18 -07001205 ShortcutPackage getPackageShortcutsLocked(
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001206 @NonNull String packageName, @UserIdInt int userId) {
Makoto Onukic51b2872016-05-04 15:24:50 -07001207 return getUserShortcutsLocked(userId).getPackageShortcuts(packageName);
Makoto Onukide667372016-03-15 14:29:20 -07001208 }
1209
Makoto Onukic8c33292016-09-12 16:36:59 -07001210 /** Return the per-user per-package state. Use this when the caller is a publisher. */
1211 @GuardedBy("mLock")
1212 @NonNull
1213 ShortcutPackage getPackageShortcutsForPublisherLocked(
1214 @NonNull String packageName, @UserIdInt int userId) {
1215 final ShortcutPackage ret = getUserShortcutsLocked(userId).getPackageShortcuts(packageName);
1216 ret.getUser().onCalledByPublisher(packageName);
1217 return ret;
1218 }
1219
Makoto Onukide667372016-03-15 14:29:20 -07001220 @GuardedBy("mLock")
1221 @NonNull
Makoto Onuki2e210c42016-03-30 08:30:36 -07001222 ShortcutLauncher getLauncherShortcutsLocked(
1223 @NonNull String packageName, @UserIdInt int ownerUserId,
1224 @UserIdInt int launcherUserId) {
1225 return getUserShortcutsLocked(ownerUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07001226 .getLauncherShortcuts(packageName, launcherUserId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001227 }
1228
1229 // === Caller validation ===
1230
Makoto Onuki475c3652017-05-08 14:29:03 -07001231 void removeIconLocked(ShortcutInfo shortcut) {
1232 mShortcutBitmapSaver.removeIcon(shortcut);
Makoto Onuki55046222016-03-08 10:49:47 -08001233 }
1234
Makoto Onuki0033b2a2016-04-14 17:19:16 -07001235 public void cleanupBitmapsForPackage(@UserIdInt int userId, String packageName) {
1236 final File packagePath = new File(getUserBitmapFilePath(userId), packageName);
1237 if (!packagePath.isDirectory()) {
1238 return;
1239 }
1240 if (!(FileUtils.deleteContents(packagePath) && packagePath.delete())) {
1241 Slog.w(TAG, "Unable to remove directory " + packagePath);
1242 }
1243 }
1244
Makoto Onuki475c3652017-05-08 14:29:03 -07001245 /**
1246 * Remove dangling bitmap files for a user.
1247 *
1248 * Note this method must be called with the lock held after calling
1249 * {@link ShortcutBitmapSaver#waitForAllSavesLocked()} to make sure there's no pending bitmap
1250 * saves are going on.
1251 */
Makoto Onuki1e173232016-08-10 10:47:13 -07001252 private void cleanupDanglingBitmapDirectoriesLocked(@UserIdInt int userId) {
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001253 if (DEBUG) {
1254 Slog.d(TAG, "cleanupDanglingBitmaps: userId=" + userId);
1255 }
1256 final long start = injectElapsedRealtime();
1257
Makoto Onuki1e173232016-08-10 10:47:13 -07001258 final ShortcutUser user = getUserShortcutsLocked(userId);
1259
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001260 final File bitmapDir = getUserBitmapFilePath(userId);
1261 final File[] children = bitmapDir.listFiles();
1262 if (children == null) {
1263 return;
1264 }
1265 for (File child : children) {
1266 if (!child.isDirectory()) {
1267 continue;
1268 }
1269 final String packageName = child.getName();
1270 if (DEBUG) {
1271 Slog.d(TAG, "cleanupDanglingBitmaps: Found directory=" + packageName);
1272 }
1273 if (!user.hasPackage(packageName)) {
1274 if (DEBUG) {
1275 Slog.d(TAG, "Removing dangling bitmap directory: " + packageName);
1276 }
1277 cleanupBitmapsForPackage(userId, packageName);
1278 } else {
1279 cleanupDanglingBitmapFilesLocked(userId, user, packageName, child);
1280 }
1281 }
1282 logDurationStat(Stats.CLEANUP_DANGLING_BITMAPS, start);
1283 }
1284
Makoto Onuki475c3652017-05-08 14:29:03 -07001285 /**
1286 * Remove dangling bitmap files for a package.
1287 *
1288 * Note this method must be called with the lock held after calling
1289 * {@link ShortcutBitmapSaver#waitForAllSavesLocked()} to make sure there's no pending bitmap
1290 * saves are going on.
1291 */
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001292 private void cleanupDanglingBitmapFilesLocked(@UserIdInt int userId, @NonNull ShortcutUser user,
1293 @NonNull String packageName, @NonNull File path) {
1294 final ArraySet<String> usedFiles =
Makoto Onukic51b2872016-05-04 15:24:50 -07001295 user.getPackageShortcuts(packageName).getUsedBitmapFiles();
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001296
1297 for (File child : path.listFiles()) {
1298 if (!child.isFile()) {
1299 continue;
1300 }
1301 final String name = child.getName();
1302 if (!usedFiles.contains(name)) {
1303 if (DEBUG) {
1304 Slog.d(TAG, "Removing dangling bitmap file: " + child.getAbsolutePath());
1305 }
1306 child.delete();
1307 }
1308 }
1309 }
1310
Makoto Onuki55046222016-03-08 10:49:47 -08001311 @VisibleForTesting
1312 static class FileOutputStreamWithPath extends FileOutputStream {
1313 private final File mFile;
1314
1315 public FileOutputStreamWithPath(File file) throws FileNotFoundException {
1316 super(file);
1317 mFile = file;
1318 }
1319
1320 public File getFile() {
1321 return mFile;
1322 }
1323 }
1324
1325 /**
1326 * Build the cached bitmap filename for a shortcut icon.
1327 *
1328 * The filename will be based on the ID, except certain characters will be escaped.
1329 */
Makoto Onuki55046222016-03-08 10:49:47 -08001330 FileOutputStreamWithPath openIconFileForWrite(@UserIdInt int userId, ShortcutInfo shortcut)
1331 throws IOException {
1332 final File packagePath = new File(getUserBitmapFilePath(userId),
Makoto Onuki22fcc682016-05-17 14:52:19 -07001333 shortcut.getPackage());
Makoto Onuki55046222016-03-08 10:49:47 -08001334 if (!packagePath.isDirectory()) {
1335 packagePath.mkdirs();
1336 if (!packagePath.isDirectory()) {
1337 throw new IOException("Unable to create directory " + packagePath);
1338 }
1339 SELinux.restorecon(packagePath);
1340 }
1341
1342 final String baseName = String.valueOf(injectCurrentTimeMillis());
Makoto Onukib08790c2016-06-23 14:05:46 -07001343 for (int suffix = 0; ; suffix++) {
Makoto Onuki55046222016-03-08 10:49:47 -08001344 final String filename = (suffix == 0 ? baseName : baseName + "_" + suffix) + ".png";
1345 final File file = new File(packagePath, filename);
1346 if (!file.exists()) {
1347 if (DEBUG) {
1348 Slog.d(TAG, "Saving icon to " + file.getAbsolutePath());
1349 }
1350 return new FileOutputStreamWithPath(file);
1351 }
1352 }
1353 }
1354
Makoto Onuki475c3652017-05-08 14:29:03 -07001355 void saveIconAndFixUpShortcutLocked(ShortcutInfo shortcut) {
Makoto Onuki55046222016-03-08 10:49:47 -08001356 if (shortcut.hasIconFile() || shortcut.hasIconResource()) {
1357 return;
1358 }
1359
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001360 final long token = injectClearCallingIdentity();
Makoto Onuki55046222016-03-08 10:49:47 -08001361 try {
1362 // Clear icon info on the shortcut.
Makoto Onuki475c3652017-05-08 14:29:03 -07001363 removeIconLocked(shortcut);
Makoto Onuki55046222016-03-08 10:49:47 -08001364
1365 final Icon icon = shortcut.getIcon();
1366 if (icon == null) {
1367 return; // has no icon
1368 }
Hyunyoung Song47037462017-05-08 16:51:43 -07001369 int maxIconDimension = mMaxIconDimension;
Makoto Onukiabe84422016-04-07 09:41:19 -07001370 Bitmap bitmap;
Makoto Onuki55046222016-03-08 10:49:47 -08001371 try {
1372 switch (icon.getType()) {
1373 case Icon.TYPE_RESOURCE: {
1374 injectValidateIconResPackage(shortcut, icon);
1375
1376 shortcut.setIconResourceId(icon.getResId());
1377 shortcut.addFlags(ShortcutInfo.FLAG_HAS_ICON_RES);
1378 return;
1379 }
Hyunyoung Songf281e7a2017-02-13 10:57:42 -08001380 case Icon.TYPE_BITMAP:
Makoto Onukiabe84422016-04-07 09:41:19 -07001381 bitmap = icon.getBitmap(); // Don't recycle in this case.
Makoto Onuki55046222016-03-08 10:49:47 -08001382 break;
Hyunyoung Song47037462017-05-08 16:51:43 -07001383 case Icon.TYPE_ADAPTIVE_BITMAP: {
1384 bitmap = icon.getBitmap(); // Don't recycle in this case.
1385 maxIconDimension *= (1 + 2 * AdaptiveIconDrawable.getExtraInsetFraction());
Hyunyoung Song8947f592017-05-15 10:12:11 -07001386 break;
Makoto Onuki55046222016-03-08 10:49:47 -08001387 }
Makoto Onuki55046222016-03-08 10:49:47 -08001388 default:
1389 // This shouldn't happen because we've already validated the icon, but
1390 // just in case.
1391 throw ShortcutInfo.getInvalidIconException();
1392 }
Makoto Onuki475c3652017-05-08 14:29:03 -07001393 mShortcutBitmapSaver.saveBitmapLocked(shortcut,
Hyunyoung Song47037462017-05-08 16:51:43 -07001394 maxIconDimension, mIconPersistFormat, mIconPersistQuality);
Makoto Onuki55046222016-03-08 10:49:47 -08001395 } finally {
Makoto Onuki55046222016-03-08 10:49:47 -08001396 // Once saved, we won't use the original icon information, so null it out.
1397 shortcut.clearIcon();
1398 }
1399 } finally {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001400 injectRestoreCallingIdentity(token);
Makoto Onuki55046222016-03-08 10:49:47 -08001401 }
1402 }
1403
1404 // Unfortunately we can't do this check in unit tests because we fake creator package names,
1405 // so override in unit tests.
1406 // TODO CTS this case.
1407 void injectValidateIconResPackage(ShortcutInfo shortcut, Icon icon) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07001408 if (!shortcut.getPackage().equals(icon.getResPackage())) {
Makoto Onuki55046222016-03-08 10:49:47 -08001409 throw new IllegalArgumentException(
1410 "Icon resource must reside in shortcut owner package");
1411 }
1412 }
1413
Makoto Onuki55046222016-03-08 10:49:47 -08001414 static Bitmap shrinkBitmap(Bitmap in, int maxSize) {
1415 // Original width/height.
1416 final int ow = in.getWidth();
1417 final int oh = in.getHeight();
1418 if ((ow <= maxSize) && (oh <= maxSize)) {
1419 if (DEBUG) {
1420 Slog.d(TAG, String.format("Icon size %dx%d, no need to shrink", ow, oh));
1421 }
1422 return in;
1423 }
1424 final int longerDimension = Math.max(ow, oh);
1425
1426 // New width and height.
1427 final int nw = ow * maxSize / longerDimension;
1428 final int nh = oh * maxSize / longerDimension;
1429 if (DEBUG) {
1430 Slog.d(TAG, String.format("Icon size %dx%d, shrinking to %dx%d",
1431 ow, oh, nw, nh));
1432 }
1433
1434 final Bitmap scaledBitmap = Bitmap.createBitmap(nw, nh, Bitmap.Config.ARGB_8888);
1435 final Canvas c = new Canvas(scaledBitmap);
1436
1437 final RectF dst = new RectF(0, 0, nw, nh);
1438
1439 c.drawBitmap(in, /*src=*/ null, dst, /* paint =*/ null);
1440
Makoto Onuki55046222016-03-08 10:49:47 -08001441 return scaledBitmap;
1442 }
1443
Makoto Onuki157b1622016-06-02 16:13:10 -07001444 /**
1445 * For a shortcut, update all resource names from resource IDs, and also update all
1446 * resource-based strings.
1447 */
1448 void fixUpShortcutResourceNamesAndValues(ShortcutInfo si) {
1449 final Resources publisherRes = injectGetResourcesForApplicationAsUser(
1450 si.getPackage(), si.getUserId());
1451 if (publisherRes != null) {
1452 final long start = injectElapsedRealtime();
1453 try {
1454 si.lookupAndFillInResourceNames(publisherRes);
1455 } finally {
1456 logDurationStat(Stats.RESOURCE_NAME_LOOKUP, start);
1457 }
1458 si.resolveResourceStrings(publisherRes);
1459 }
1460 }
1461
Makoto Onuki55046222016-03-08 10:49:47 -08001462 // === Caller validation ===
1463
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001464 private boolean isCallerSystem() {
1465 final int callingUid = injectBinderCallingUid();
Makoto Onukib08790c2016-06-23 14:05:46 -07001466 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001467 }
1468
1469 private boolean isCallerShell() {
1470 final int callingUid = injectBinderCallingUid();
1471 return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
1472 }
1473
1474 private void enforceSystemOrShell() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001475 if (!(isCallerSystem() || isCallerShell())) {
1476 throw new SecurityException("Caller must be system or shell");
1477 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001478 }
1479
1480 private void enforceShell() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001481 if (!isCallerShell()) {
1482 throw new SecurityException("Caller must be shell");
1483 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001484 }
1485
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001486 private void enforceSystem() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001487 if (!isCallerSystem()) {
1488 throw new SecurityException("Caller must be system");
1489 }
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001490 }
1491
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001492 private void enforceResetThrottlingPermission() {
1493 if (isCallerSystem()) {
1494 return;
1495 }
Makoto Onuki76269922016-07-15 14:58:54 -07001496 enforceCallingOrSelfPermission(
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001497 android.Manifest.permission.RESET_SHORTCUT_MANAGER_THROTTLING, null);
1498 }
1499
Makoto Onuki76269922016-07-15 14:58:54 -07001500 private void enforceCallingOrSelfPermission(
1501 @NonNull String permission, @Nullable String message) {
1502 if (isCallerSystem()) {
1503 return;
1504 }
1505 injectEnforceCallingPermission(permission, message);
1506 }
1507
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001508 /**
1509 * Somehow overriding ServiceContext.enforceCallingPermission() in the unit tests would confuse
1510 * mockito. So instead we extracted it here and override it in the tests.
1511 */
1512 @VisibleForTesting
1513 void injectEnforceCallingPermission(
1514 @NonNull String permission, @Nullable String message) {
1515 mContext.enforceCallingPermission(permission, message);
1516 }
1517
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001518 private void verifyCaller(@NonNull String packageName, @UserIdInt int userId) {
1519 Preconditions.checkStringNotEmpty(packageName, "packageName");
1520
1521 if (isCallerSystem()) {
1522 return; // no check
1523 }
1524
1525 final int callingUid = injectBinderCallingUid();
1526
1527 // Otherwise, make sure the arguments are valid.
1528 if (UserHandle.getUserId(callingUid) != userId) {
1529 throw new SecurityException("Invalid user-ID");
1530 }
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08001531 if (injectGetPackageUid(packageName, userId) != callingUid) {
1532 throw new SecurityException("Calling package name mismatch");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001533 }
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08001534 Preconditions.checkState(!isEphemeralApp(packageName, userId),
1535 "Ephemeral apps can't use ShortcutManager");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001536 }
1537
Makoto Onuki157b1622016-06-02 16:13:10 -07001538 // Overridden in unit tests to execute r synchronously.
1539 void injectPostToHandler(Runnable r) {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001540 mHandler.post(r);
1541 }
1542
Makoto Onuki085a05c2016-08-19 11:39:29 -07001543 void injectRunOnNewThread(Runnable r) {
1544 new Thread(r).start();
1545 }
1546
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001547 /**
Makoto Onuki7001a612016-05-27 13:24:28 -07001548 * @throws IllegalArgumentException if {@code numShortcuts} is bigger than
Makoto Onukib08790c2016-06-23 14:05:46 -07001549 * {@link #getMaxActivityShortcuts()}.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001550 */
Makoto Onuki7001a612016-05-27 13:24:28 -07001551 void enforceMaxActivityShortcuts(int numShortcuts) {
Makoto Onukib5a012f2016-06-21 11:13:53 -07001552 if (numShortcuts > mMaxShortcuts) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001553 throw new IllegalArgumentException("Max number of dynamic shortcuts exceeded");
1554 }
1555 }
1556
1557 /**
Makoto Onuki7001a612016-05-27 13:24:28 -07001558 * Return the max number of dynamic + manifest shortcuts for each launcher icon.
1559 */
1560 int getMaxActivityShortcuts() {
Makoto Onukib5a012f2016-06-21 11:13:53 -07001561 return mMaxShortcuts;
Makoto Onuki7001a612016-05-27 13:24:28 -07001562 }
1563
1564 /**
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001565 * - Sends a notification to LauncherApps
1566 * - Write to file
1567 */
Makoto Onuki39686e82016-04-13 18:03:00 -07001568 void packageShortcutsChanged(@NonNull String packageName, @UserIdInt int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001569 notifyListeners(packageName, userId);
1570 scheduleSaveUser(userId);
1571 }
1572
1573 private void notifyListeners(@NonNull String packageName, @UserIdInt int userId) {
Makoto Onuki82fb2eb2017-03-31 16:58:26 -07001574 if (DEBUG) {
1575 Slog.d(TAG, String.format(
1576 "Shortcut changes: package=%s, user=%d", packageName, userId));
1577 }
Makoto Onuki157b1622016-06-02 16:13:10 -07001578 injectPostToHandler(() -> {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001579 try {
1580 final ArrayList<ShortcutChangeListener> copy;
1581 synchronized (mLock) {
1582 if (!isUserUnlockedL(userId)) {
1583 return;
1584 }
1585
1586 copy = new ArrayList<>(mListeners);
1587 }
1588 // Note onShortcutChanged() needs to be called with the system service permissions.
1589 for (int i = copy.size() - 1; i >= 0; i--) {
1590 copy.get(i).onShortcutChanged(packageName, userId);
1591 }
1592 } catch (Exception ignore) {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001593 }
1594 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001595 }
1596
1597 /**
1598 * Clean up / validate an incoming shortcut.
1599 * - Make sure all mandatory fields are set.
1600 * - Make sure the intent's extras are persistable, and them to set
Makoto Onuki0eed4412016-07-21 11:21:59 -07001601 * {@link ShortcutInfo#mIntentPersistableExtrases}. Also clear its extras.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001602 * - Clear flags.
1603 */
Makoto Onuki2d895c32016-12-02 15:48:40 -08001604 private void fixUpIncomingShortcutInfo(@NonNull ShortcutInfo shortcut, boolean forUpdate,
1605 boolean forPinRequest) {
Makoto Onukibf563b62017-05-04 10:25:30 -07001606 if (shortcut.isReturnedByServer()) {
1607 Log.w(TAG,
1608 "Re-publishing ShortcutInfo returned by server is not supported."
1609 + " Some information such as icon may lost from shortcut.");
1610 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001611 Preconditions.checkNotNull(shortcut, "Null shortcut detected");
Makoto Onuki255461f2017-01-10 11:47:25 -08001612 if (shortcut.getActivity() != null) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001613 Preconditions.checkState(
Makoto Onuki22fcc682016-05-17 14:52:19 -07001614 shortcut.getPackage().equals(shortcut.getActivity().getPackageName()),
Makoto Onukib08790c2016-06-23 14:05:46 -07001615 "Cannot publish shortcut: activity " + shortcut.getActivity() + " does not"
1616 + " belong to package " + shortcut.getPackage());
Makoto Onuki13260b6ff2016-07-13 18:03:13 -07001617 Preconditions.checkState(
1618 injectIsMainActivity(shortcut.getActivity(), shortcut.getUserId()),
1619 "Cannot publish shortcut: activity " + shortcut.getActivity() + " is not"
1620 + " main activity");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001621 }
1622
Makoto Onuki55046222016-03-08 10:49:47 -08001623 if (!forUpdate) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08001624 shortcut.enforceMandatoryFields(/* forPinned= */ forPinRequest);
1625 if (!forPinRequest) {
Makoto Onuki255461f2017-01-10 11:47:25 -08001626 Preconditions.checkState(shortcut.getActivity() != null,
1627 "Cannot publish shortcut: target activity is not set");
Makoto Onuki2d895c32016-12-02 15:48:40 -08001628 }
Makoto Onuki55046222016-03-08 10:49:47 -08001629 }
1630 if (shortcut.getIcon() != null) {
1631 ShortcutInfo.validateIcon(shortcut.getIcon());
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001632 }
1633
Makoto Onukide667372016-03-15 14:29:20 -07001634 shortcut.replaceFlags(0);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001635 }
1636
Makoto Onuki2d895c32016-12-02 15:48:40 -08001637 private void fixUpIncomingShortcutInfo(@NonNull ShortcutInfo shortcut, boolean forUpdate) {
1638 fixUpIncomingShortcutInfo(shortcut, forUpdate, /*forPinRequest=*/ false);
1639 }
1640
1641 public void validateShortcutForPinRequest(@NonNull ShortcutInfo shortcut) {
1642 fixUpIncomingShortcutInfo(shortcut, /* forUpdate= */ false, /*forPinRequest=*/ true);
1643 }
1644
Makoto Onukib08790c2016-06-23 14:05:46 -07001645 /**
1646 * When a shortcut has no target activity, set the default one from the package.
1647 */
1648 private void fillInDefaultActivity(List<ShortcutInfo> shortcuts) {
Makoto Onukib08790c2016-06-23 14:05:46 -07001649 ComponentName defaultActivity = null;
1650 for (int i = shortcuts.size() - 1; i >= 0; i--) {
1651 final ShortcutInfo si = shortcuts.get(i);
1652 if (si.getActivity() == null) {
1653 if (defaultActivity == null) {
1654 defaultActivity = injectGetDefaultMainActivity(
1655 si.getPackage(), si.getUserId());
1656 Preconditions.checkState(defaultActivity != null,
1657 "Launcher activity not found for package " + si.getPackage());
1658 }
1659 si.setActivity(defaultActivity);
1660 }
1661 }
1662 }
1663
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001664 private void assignImplicitRanks(List<ShortcutInfo> shortcuts) {
1665 for (int i = shortcuts.size() - 1; i >= 0; i--) {
1666 shortcuts.get(i).setImplicitRank(i);
1667 }
1668 }
1669
Makoto Onukibf563b62017-05-04 10:25:30 -07001670 private List<ShortcutInfo> setReturnedByServer(List<ShortcutInfo> shortcuts) {
1671 for (int i = shortcuts.size() - 1; i >= 0; i--) {
1672 shortcuts.get(i).setReturnedByServer();
1673 }
1674 return shortcuts;
1675 }
1676
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001677 // === APIs ===
1678
1679 @Override
1680 public boolean setDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1681 @UserIdInt int userId) {
1682 verifyCaller(packageName, userId);
1683
1684 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
1685 final int size = newShortcuts.size();
1686
1687 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001688 throwIfUserLockedL(userId);
1689
Makoto Onukic8c33292016-09-12 16:36:59 -07001690 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001691
Makoto Onuki22fcc682016-05-17 14:52:19 -07001692 ps.ensureImmutableShortcutsNotIncluded(newShortcuts);
1693
Makoto Onukib08790c2016-06-23 14:05:46 -07001694 fillInDefaultActivity(newShortcuts);
1695
Makoto Onuki7001a612016-05-27 13:24:28 -07001696 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_SET);
1697
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001698 // Throttling.
Makoto Onukic51b2872016-05-04 15:24:50 -07001699 if (!ps.tryApiCall()) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001700 return false;
1701 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001702
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001703 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1704 ps.clearAllImplicitRanks();
1705 assignImplicitRanks(newShortcuts);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001706
Makoto Onukidf6da042016-06-16 09:51:40 -07001707 for (int i = 0; i < size; i++) {
1708 fixUpIncomingShortcutInfo(newShortcuts.get(i), /* forUpdate= */ false);
1709 }
1710
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001711 // First, remove all un-pinned; dynamic shortcuts
Makoto Onukic51b2872016-05-04 15:24:50 -07001712 ps.deleteAllDynamicShortcuts();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001713
1714 // Then, add/update all. We need to make sure to take over "pinned" flag.
1715 for (int i = 0; i < size; i++) {
1716 final ShortcutInfo newShortcut = newShortcuts.get(i);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001717 ps.addOrUpdateDynamicShortcut(newShortcut);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001718 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001719
1720 // Lastly, adjust the ranks.
1721 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001722 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001723 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001724
1725 verifyStates();
1726
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001727 return true;
1728 }
1729
1730 @Override
1731 public boolean updateShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1732 @UserIdInt int userId) {
1733 verifyCaller(packageName, userId);
1734
1735 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
Makoto Onuki55046222016-03-08 10:49:47 -08001736 final int size = newShortcuts.size();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001737
1738 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001739 throwIfUserLockedL(userId);
1740
Makoto Onukic8c33292016-09-12 16:36:59 -07001741 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001742
Makoto Onuki22fcc682016-05-17 14:52:19 -07001743 ps.ensureImmutableShortcutsNotIncluded(newShortcuts);
1744
Makoto Onukib08790c2016-06-23 14:05:46 -07001745 // For update, don't fill in the default activity. Having null activity means
1746 // "don't update the activity" here.
1747
Makoto Onuki7001a612016-05-27 13:24:28 -07001748 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_UPDATE);
1749
Makoto Onuki55046222016-03-08 10:49:47 -08001750 // Throttling.
Makoto Onukic51b2872016-05-04 15:24:50 -07001751 if (!ps.tryApiCall()) {
Makoto Onuki55046222016-03-08 10:49:47 -08001752 return false;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001753 }
1754
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001755 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1756 ps.clearAllImplicitRanks();
1757 assignImplicitRanks(newShortcuts);
1758
Makoto Onuki55046222016-03-08 10:49:47 -08001759 for (int i = 0; i < size; i++) {
1760 final ShortcutInfo source = newShortcuts.get(i);
1761 fixUpIncomingShortcutInfo(source, /* forUpdate= */ true);
1762
1763 final ShortcutInfo target = ps.findShortcutById(source.getId());
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001764 if (target == null) {
1765 continue;
1766 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07001767
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001768 if (target.isEnabled() != source.isEnabled()) {
1769 Slog.w(TAG,
1770 "ShortcutInfo.enabled cannot be changed with updateShortcuts()");
1771 }
Makoto Onuki55046222016-03-08 10:49:47 -08001772
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001773 // When updating the rank, we need to insert between existing ranks, so set
1774 // this setRankChanged, and also copy the implicit rank fo adjustRanks().
1775 if (source.hasRank()) {
1776 target.setRankChanged();
1777 target.setImplicitRank(source.getImplicitRank());
1778 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07001779
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001780 final boolean replacingIcon = (source.getIcon() != null);
1781 if (replacingIcon) {
Makoto Onuki475c3652017-05-08 14:29:03 -07001782 removeIconLocked(target);
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001783 }
Makoto Onuki55046222016-03-08 10:49:47 -08001784
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001785 // Note copyNonNullFieldsFrom() does the "updatable with?" check too.
1786 target.copyNonNullFieldsFrom(source);
1787 target.setTimestamp(injectCurrentTimeMillis());
1788
1789 if (replacingIcon) {
Makoto Onuki475c3652017-05-08 14:29:03 -07001790 saveIconAndFixUpShortcutLocked(target);
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001791 }
1792
1793 // When we're updating any resource related fields, re-extract the res names and
1794 // the values.
1795 if (replacingIcon || source.hasStringResources()) {
1796 fixUpShortcutResourceNamesAndValues(target);
Makoto Onuki55046222016-03-08 10:49:47 -08001797 }
1798 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001799
1800 // Lastly, adjust the ranks.
1801 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001802 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001803 packageShortcutsChanged(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001804
Makoto Onuki7001a612016-05-27 13:24:28 -07001805 verifyStates();
1806
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001807 return true;
1808 }
1809
1810 @Override
Makoto Onukib6d35232016-04-04 15:57:17 -07001811 public boolean addDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001812 @UserIdInt int userId) {
1813 verifyCaller(packageName, userId);
1814
Makoto Onukib6d35232016-04-04 15:57:17 -07001815 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
1816 final int size = newShortcuts.size();
1817
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001818 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001819 throwIfUserLockedL(userId);
1820
Makoto Onukic8c33292016-09-12 16:36:59 -07001821 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001822
Makoto Onuki22fcc682016-05-17 14:52:19 -07001823 ps.ensureImmutableShortcutsNotIncluded(newShortcuts);
1824
Makoto Onukib08790c2016-06-23 14:05:46 -07001825 fillInDefaultActivity(newShortcuts);
1826
Makoto Onuki7001a612016-05-27 13:24:28 -07001827 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_ADD);
1828
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001829 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1830 ps.clearAllImplicitRanks();
1831 assignImplicitRanks(newShortcuts);
1832
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001833 // Throttling.
Makoto Onukic51b2872016-05-04 15:24:50 -07001834 if (!ps.tryApiCall()) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001835 return false;
1836 }
Makoto Onukib6d35232016-04-04 15:57:17 -07001837 for (int i = 0; i < size; i++) {
1838 final ShortcutInfo newShortcut = newShortcuts.get(i);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001839
Makoto Onukib6d35232016-04-04 15:57:17 -07001840 // Validate the shortcut.
1841 fixUpIncomingShortcutInfo(newShortcut, /* forUpdate= */ false);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001842
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001843 // When ranks are changing, we need to insert between ranks, so set the
1844 // "rank changed" flag.
1845 newShortcut.setRankChanged();
1846
Makoto Onukib6d35232016-04-04 15:57:17 -07001847 // Add it.
Makoto Onuki22fcc682016-05-17 14:52:19 -07001848 ps.addOrUpdateDynamicShortcut(newShortcut);
Makoto Onukib6d35232016-04-04 15:57:17 -07001849 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001850
1851 // Lastly, adjust the ranks.
1852 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001853 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001854 packageShortcutsChanged(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001855
Makoto Onuki7001a612016-05-27 13:24:28 -07001856 verifyStates();
1857
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001858 return true;
1859 }
1860
1861 @Override
Makoto Onuki2d895c32016-12-02 15:48:40 -08001862 public boolean requestPinShortcut(String packageName, ShortcutInfo shortcut,
1863 IntentSender resultIntent, int userId) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08001864 Preconditions.checkNotNull(shortcut);
1865 Preconditions.checkArgument(shortcut.isEnabled(), "Shortcut must be enabled");
Sunny Goyal4ad6b572017-02-28 11:11:51 -08001866 return requestPinItem(packageName, userId, shortcut, null, null, resultIntent);
Sunny Goyal87a563e2017-01-01 19:42:45 -08001867 }
1868
Sunny Goyala6be88a2017-01-12 16:27:58 -08001869 @Override
1870 public Intent createShortcutResultIntent(String packageName, ShortcutInfo shortcut, int userId)
1871 throws RemoteException {
1872 Preconditions.checkNotNull(shortcut);
1873 Preconditions.checkArgument(shortcut.isEnabled(), "Shortcut must be enabled");
1874 verifyCaller(packageName, userId);
1875
1876 final Intent ret;
1877 synchronized (mLock) {
1878 throwIfUserLockedL(userId);
1879
1880 // Send request to the launcher, if supported.
1881 ret = mShortcutRequestPinProcessor.createShortcutResultIntent(shortcut, userId);
1882 }
1883
1884 verifyStates();
1885 return ret;
1886 }
1887
Sunny Goyal87a563e2017-01-01 19:42:45 -08001888 /**
1889 * Handles {@link #requestPinShortcut} and {@link ShortcutServiceInternal#requestPinAppWidget}.
1890 * After validating the caller, it passes the request to {@link #mShortcutRequestPinProcessor}.
1891 * Either {@param shortcut} or {@param appWidget} should be non-null.
1892 */
Sunny Goyal4ad6b572017-02-28 11:11:51 -08001893 private boolean requestPinItem(String packageName, int userId, ShortcutInfo shortcut,
1894 AppWidgetProviderInfo appWidget, Bundle extras, IntentSender resultIntent) {
Sunny Goyal87a563e2017-01-01 19:42:45 -08001895 verifyCaller(packageName, userId);
Makoto Onuki2d895c32016-12-02 15:48:40 -08001896
1897 final boolean ret;
1898 synchronized (mLock) {
1899 throwIfUserLockedL(userId);
1900
Makoto Onukia01f4f02016-12-15 15:58:41 -08001901 Preconditions.checkState(isUidForegroundLocked(injectBinderCallingUid()),
Makoto Onuki255461f2017-01-10 11:47:25 -08001902 "Calling application must have a foreground activity or a foreground service");
Makoto Onuki2d895c32016-12-02 15:48:40 -08001903
1904 // Send request to the launcher, if supported.
Sunny Goyal4ad6b572017-02-28 11:11:51 -08001905 ret = mShortcutRequestPinProcessor.requestPinItemLocked(shortcut, appWidget, extras,
1906 userId, resultIntent);
Makoto Onuki2d895c32016-12-02 15:48:40 -08001907 }
1908
1909 verifyStates();
1910
1911 return ret;
1912 }
1913
1914 @Override
Makoto Onuki20c95f82016-05-11 16:51:01 -07001915 public void disableShortcuts(String packageName, List shortcutIds,
Makoto Onukid6880792016-06-29 13:37:43 -07001916 CharSequence disabledMessage, int disabledMessageResId, @UserIdInt int userId) {
Makoto Onuki20c95f82016-05-11 16:51:01 -07001917 verifyCaller(packageName, userId);
1918 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
1919
1920 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001921 throwIfUserLockedL(userId);
1922
Makoto Onukic8c33292016-09-12 16:36:59 -07001923 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001924
1925 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds);
1926
Makoto Onukid6880792016-06-29 13:37:43 -07001927 final String disabledMessageString =
1928 (disabledMessage == null) ? null : disabledMessage.toString();
1929
Makoto Onuki22fcc682016-05-17 14:52:19 -07001930 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
1931 ps.disableWithId(Preconditions.checkStringNotEmpty((String) shortcutIds.get(i)),
Makoto Onukid6880792016-06-29 13:37:43 -07001932 disabledMessageString, disabledMessageResId,
Makoto Onuki22fcc682016-05-17 14:52:19 -07001933 /* overrideImmutable=*/ false);
1934 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001935
1936 // We may have removed dynamic shortcuts which may have left a gap, so adjust the ranks.
1937 ps.adjustRanks();
Makoto Onuki22fcc682016-05-17 14:52:19 -07001938 }
1939 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001940
1941 verifyStates();
Makoto Onuki22fcc682016-05-17 14:52:19 -07001942 }
1943
1944 @Override
1945 public void enableShortcuts(String packageName, List shortcutIds, @UserIdInt int userId) {
1946 verifyCaller(packageName, userId);
1947 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
1948
1949 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001950 throwIfUserLockedL(userId);
1951
Makoto Onukic8c33292016-09-12 16:36:59 -07001952 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001953
1954 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds);
1955
1956 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
1957 ps.enableWithId((String) shortcutIds.get(i));
1958 }
Makoto Onuki20c95f82016-05-11 16:51:01 -07001959 }
1960 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001961
1962 verifyStates();
Makoto Onuki20c95f82016-05-11 16:51:01 -07001963 }
1964
1965 @Override
Makoto Onukib6d35232016-04-04 15:57:17 -07001966 public void removeDynamicShortcuts(String packageName, List shortcutIds,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001967 @UserIdInt int userId) {
1968 verifyCaller(packageName, userId);
Makoto Onukib6d35232016-04-04 15:57:17 -07001969 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001970
1971 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001972 throwIfUserLockedL(userId);
1973
Makoto Onukic8c33292016-09-12 16:36:59 -07001974 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001975
1976 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds);
1977
Makoto Onukib6d35232016-04-04 15:57:17 -07001978 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07001979 ps.deleteDynamicWithId(
Makoto Onukib6d35232016-04-04 15:57:17 -07001980 Preconditions.checkStringNotEmpty((String) shortcutIds.get(i)));
1981 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001982
1983 // We may have removed dynamic shortcuts which may have left a gap, so adjust the ranks.
1984 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001985 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001986 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001987
1988 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001989 }
1990
1991 @Override
Makoto Onukib6d35232016-04-04 15:57:17 -07001992 public void removeAllDynamicShortcuts(String packageName, @UserIdInt int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001993 verifyCaller(packageName, userId);
1994
1995 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001996 throwIfUserLockedL(userId);
1997
Makoto Onukic8c33292016-09-12 16:36:59 -07001998 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07001999 ps.deleteAllDynamicShortcuts();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002000 }
Makoto Onuki39686e82016-04-13 18:03:00 -07002001 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07002002
2003 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002004 }
2005
2006 @Override
2007 public ParceledListSlice<ShortcutInfo> getDynamicShortcuts(String packageName,
2008 @UserIdInt int userId) {
2009 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002010
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002011 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002012 throwIfUserLockedL(userId);
2013
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002014 return getShortcutsWithQueryLocked(
2015 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
Makoto Onuki99302b52017-03-29 12:42:26 -07002016 ShortcutInfo::isDynamic);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002017 }
2018 }
2019
2020 @Override
Makoto Onuki22fcc682016-05-17 14:52:19 -07002021 public ParceledListSlice<ShortcutInfo> getManifestShortcuts(String packageName,
2022 @UserIdInt int userId) {
2023 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002024
Makoto Onuki22fcc682016-05-17 14:52:19 -07002025 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002026 throwIfUserLockedL(userId);
2027
Makoto Onuki22fcc682016-05-17 14:52:19 -07002028 return getShortcutsWithQueryLocked(
2029 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
2030 ShortcutInfo::isManifestShortcut);
2031 }
2032 }
2033
2034 @Override
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002035 public ParceledListSlice<ShortcutInfo> getPinnedShortcuts(String packageName,
2036 @UserIdInt int userId) {
2037 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002038
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002039 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002040 throwIfUserLockedL(userId);
2041
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002042 return getShortcutsWithQueryLocked(
2043 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
2044 ShortcutInfo::isPinned);
2045 }
2046 }
2047
2048 private ParceledListSlice<ShortcutInfo> getShortcutsWithQueryLocked(@NonNull String packageName,
2049 @UserIdInt int userId, int cloneFlags, @NonNull Predicate<ShortcutInfo> query) {
2050
2051 final ArrayList<ShortcutInfo> ret = new ArrayList<>();
2052
Makoto Onukic8c33292016-09-12 16:36:59 -07002053 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002054 ps.findAll(ret, query, cloneFlags);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002055
Makoto Onukibf563b62017-05-04 10:25:30 -07002056 return new ParceledListSlice<>(setReturnedByServer(ret));
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002057 }
2058
2059 @Override
Makoto Onukid6880792016-06-29 13:37:43 -07002060 public int getMaxShortcutCountPerActivity(String packageName, @UserIdInt int userId)
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002061 throws RemoteException {
2062 verifyCaller(packageName, userId);
2063
Makoto Onukib5a012f2016-06-21 11:13:53 -07002064 return mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002065 }
2066
2067 @Override
2068 public int getRemainingCallCount(String packageName, @UserIdInt int userId) {
2069 verifyCaller(packageName, userId);
2070
2071 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002072 throwIfUserLockedL(userId);
2073
Makoto Onukic8c33292016-09-12 16:36:59 -07002074 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002075 return mMaxUpdatesPerInterval - ps.getApiCallCount();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002076 }
2077 }
2078
2079 @Override
2080 public long getRateLimitResetTime(String packageName, @UserIdInt int userId) {
2081 verifyCaller(packageName, userId);
2082
2083 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002084 throwIfUserLockedL(userId);
2085
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002086 return getNextResetTimeLocked();
2087 }
2088 }
2089
Makoto Onuki55046222016-03-08 10:49:47 -08002090 @Override
Makoto Onuki20c95f82016-05-11 16:51:01 -07002091 public int getIconMaxDimensions(String packageName, int userId) {
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002092 verifyCaller(packageName, userId);
2093
Makoto Onuki55046222016-03-08 10:49:47 -08002094 synchronized (mLock) {
2095 return mMaxIconDimension;
2096 }
2097 }
2098
Makoto Onuki20c95f82016-05-11 16:51:01 -07002099 @Override
2100 public void reportShortcutUsed(String packageName, String shortcutId, int userId) {
2101 verifyCaller(packageName, userId);
2102
Makoto Onukiac042502016-05-20 16:39:42 -07002103 Preconditions.checkNotNull(shortcutId);
2104
2105 if (DEBUG) {
2106 Slog.d(TAG, String.format("reportShortcutUsed: Shortcut %s package %s used on user %d",
2107 shortcutId, packageName, userId));
2108 }
2109
2110 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002111 throwIfUserLockedL(userId);
2112
Makoto Onukic8c33292016-09-12 16:36:59 -07002113 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002114
Makoto Onukiac042502016-05-20 16:39:42 -07002115 if (ps.findShortcutById(shortcutId) == null) {
2116 Log.w(TAG, String.format("reportShortcutUsed: package %s doesn't have shortcut %s",
2117 packageName, shortcutId));
2118 return;
2119 }
2120 }
2121
2122 final long token = injectClearCallingIdentity();
2123 try {
2124 mUsageStatsManagerInternal.reportShortcutUsage(packageName, shortcutId, userId);
2125 } finally {
2126 injectRestoreCallingIdentity(token);
2127 }
Makoto Onuki20c95f82016-05-11 16:51:01 -07002128 }
2129
Makoto Onuki2d895c32016-12-02 15:48:40 -08002130 @Override
Sunny Goyal7f7372a2017-01-24 11:53:54 -08002131 public boolean isRequestPinItemSupported(int callingUserId, int requestType) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08002132 final long token = injectClearCallingIdentity();
2133 try {
Sunny Goyal7f7372a2017-01-24 11:53:54 -08002134 return mShortcutRequestPinProcessor
2135 .isRequestPinItemSupported(callingUserId, requestType);
Makoto Onuki2d895c32016-12-02 15:48:40 -08002136 } finally {
2137 injectRestoreCallingIdentity(token);
2138 }
2139 }
2140
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002141 /**
Makoto Onukib08790c2016-06-23 14:05:46 -07002142 * Reset all throttling, for developer options and command line. Only system/shell can call
2143 * it.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002144 */
2145 @Override
2146 public void resetThrottling() {
2147 enforceSystemOrShell();
2148
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002149 resetThrottlingInner(getCallingUserId());
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002150 }
2151
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002152 void resetThrottlingInner(@UserIdInt int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002153 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002154 if (!isUserUnlockedL(userId)) {
2155 Log.w(TAG, "User " + userId + " is locked or not running");
2156 return;
2157 }
2158
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002159 getUserShortcutsLocked(userId).resetThrottling();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002160 }
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002161 scheduleSaveUser(userId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002162 Slog.i(TAG, "ShortcutManager: throttling counter reset for user " + userId);
2163 }
2164
2165 void resetAllThrottlingInner() {
2166 synchronized (mLock) {
2167 mRawLastResetTime = injectCurrentTimeMillis();
2168 }
2169 scheduleSaveBaseState();
2170 Slog.i(TAG, "ShortcutManager: throttling counter reset for all users");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002171 }
2172
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002173 @Override
2174 public void onApplicationActive(String packageName, int userId) {
2175 if (DEBUG) {
2176 Slog.d(TAG, "onApplicationActive: package=" + packageName + " userid=" + userId);
2177 }
2178 enforceResetThrottlingPermission();
Makoto Onuki02f338e2016-07-29 09:40:40 -07002179
2180 synchronized (mLock) {
2181 if (!isUserUnlockedL(userId)) {
2182 // This is called by system UI, so no need to throw. Just ignore.
2183 return;
2184 }
2185
2186 getPackageShortcutsLocked(packageName, userId)
2187 .resetRateLimitingForCommandLineNoSaving();
2188 saveUserLocked(userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002189 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002190 }
2191
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002192 // We override this method in unit tests to do a simpler check.
2193 boolean hasShortcutHostPermission(@NonNull String callingPackage, int userId) {
Makoto Onuki10305202016-07-14 18:14:08 -07002194 final long start = injectElapsedRealtime();
2195 try {
2196 return hasShortcutHostPermissionInner(callingPackage, userId);
2197 } finally {
2198 logDurationStat(Stats.LAUNCHER_PERMISSION_CHECK, start);
2199 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002200 }
2201
2202 // This method is extracted so we can directly call this method from unit tests,
2203 // even when hasShortcutPermission() is overridden.
2204 @VisibleForTesting
Makoto Onuki2d895c32016-12-02 15:48:40 -08002205 boolean hasShortcutHostPermissionInner(@NonNull String packageName, int userId) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002206 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002207 throwIfUserLockedL(userId);
2208
Makoto Onuki31459242016-03-22 11:12:18 -07002209 final ShortcutUser user = getUserShortcutsLocked(userId);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002210
Makoto Onuki2d895c32016-12-02 15:48:40 -08002211 // Always trust the cached component.
Makoto Onuki10305202016-07-14 18:14:08 -07002212 final ComponentName cached = user.getCachedLauncher();
2213 if (cached != null) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08002214 if (cached.getPackageName().equals(packageName)) {
Makoto Onuki10305202016-07-14 18:14:08 -07002215 return true;
2216 }
2217 }
2218 // If the cached one doesn't match, then go ahead
2219
Makoto Onuki2d895c32016-12-02 15:48:40 -08002220 final ComponentName detected = getDefaultLauncher(userId);
Makoto Onuki2e210c42016-03-30 08:30:36 -07002221
Makoto Onuki10305202016-07-14 18:14:08 -07002222 // Update the cache.
2223 user.setLauncher(detected);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002224 if (detected != null) {
2225 if (DEBUG) {
2226 Slog.v(TAG, "Detected launcher: " + detected);
2227 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08002228 return detected.getPackageName().equals(packageName);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002229 } else {
2230 // Default launcher not found.
2231 return false;
2232 }
2233 }
2234 }
2235
Makoto Onuki2d895c32016-12-02 15:48:40 -08002236 @Nullable
2237 ComponentName getDefaultLauncher(@UserIdInt int userId) {
2238 final long start = injectElapsedRealtime();
2239 final long token = injectClearCallingIdentity();
2240 try {
2241 synchronized (mLock) {
2242 throwIfUserLockedL(userId);
2243
2244 final ShortcutUser user = getUserShortcutsLocked(userId);
2245
2246 final List<ResolveInfo> allHomeCandidates = new ArrayList<>();
2247
2248 // Default launcher from package manager.
2249 final long startGetHomeActivitiesAsUser = injectElapsedRealtime();
2250 final ComponentName defaultLauncher = mPackageManagerInternal
2251 .getHomeActivitiesAsUser(allHomeCandidates, userId);
2252 logDurationStat(Stats.GET_DEFAULT_HOME, startGetHomeActivitiesAsUser);
2253
2254 ComponentName detected = null;
2255 if (defaultLauncher != null) {
2256 detected = defaultLauncher;
2257 if (DEBUG) {
2258 Slog.v(TAG, "Default launcher from PM: " + detected);
2259 }
2260 } else {
2261 detected = user.getLastKnownLauncher();
2262
2263 if (detected != null) {
2264 if (injectIsActivityEnabledAndExported(detected, userId)) {
2265 if (DEBUG) {
2266 Slog.v(TAG, "Cached launcher: " + detected);
2267 }
2268 } else {
2269 Slog.w(TAG, "Cached launcher " + detected + " no longer exists");
2270 detected = null;
2271 user.clearLauncher();
2272 }
2273 }
2274 }
2275
2276 if (detected == null) {
2277 // If we reach here, that means it's the first check since the user was created,
2278 // and there's already multiple launchers and there's no default set.
2279 // Find the system one with the highest priority.
2280 // (We need to check the priority too because of FallbackHome in Settings.)
2281 // If there's no system launcher yet, then no one can access shortcuts, until
2282 // the user explicitly
2283 final int size = allHomeCandidates.size();
2284
2285 int lastPriority = Integer.MIN_VALUE;
2286 for (int i = 0; i < size; i++) {
2287 final ResolveInfo ri = allHomeCandidates.get(i);
2288 if (!ri.activityInfo.applicationInfo.isSystemApp()) {
2289 continue;
2290 }
2291 if (DEBUG) {
2292 Slog.d(TAG, String.format("hasShortcutPermissionInner: pkg=%s prio=%d",
2293 ri.activityInfo.getComponentName(), ri.priority));
2294 }
2295 if (ri.priority < lastPriority) {
2296 continue;
2297 }
2298 detected = ri.activityInfo.getComponentName();
2299 lastPriority = ri.priority;
2300 }
2301 }
2302 return detected;
2303 }
2304 } finally {
2305 injectRestoreCallingIdentity(token);
2306 logDurationStat(Stats.GET_DEFAULT_LAUNCHER, start);
2307 }
2308 }
2309
Makoto Onukicdc78f72016-03-21 15:47:52 -07002310 // === House keeping ===
2311
Makoto Onukib08790c2016-06-23 14:05:46 -07002312 private void cleanUpPackageForAllLoadedUsers(String packageName, @UserIdInt int packageUserId,
2313 boolean appStillExists) {
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002314 synchronized (mLock) {
2315 forEachLoadedUserLocked(user ->
Makoto Onukib08790c2016-06-23 14:05:46 -07002316 cleanUpPackageLocked(packageName, user.getUserId(), packageUserId,
2317 appStillExists));
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002318 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002319 }
2320
Makoto Onuki2e210c42016-03-30 08:30:36 -07002321 /**
2322 * Remove all the information associated with a package. This will really remove all the
2323 * information, including the restore information (i.e. it'll remove packages even if they're
2324 * shadow).
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002325 *
2326 * This is called when an app is uninstalled, or an app gets "clear data"ed.
Makoto Onuki2e210c42016-03-30 08:30:36 -07002327 */
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002328 @VisibleForTesting
Makoto Onukib08790c2016-06-23 14:05:46 -07002329 void cleanUpPackageLocked(String packageName, int owningUserId, int packageUserId,
2330 boolean appStillExists) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002331 final boolean wasUserLoaded = isUserLoadedLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002332
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002333 final ShortcutUser user = getUserShortcutsLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002334 boolean doNotify = false;
2335
2336 // First, remove the package from the package list (if the package is a publisher).
Makoto Onukid99c6f02016-03-28 11:02:54 -07002337 if (packageUserId == owningUserId) {
Makoto Onukic51b2872016-05-04 15:24:50 -07002338 if (user.removePackage(packageName) != null) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002339 doNotify = true;
2340 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07002341 }
Makoto Onukid99c6f02016-03-28 11:02:54 -07002342
Makoto Onukicdc78f72016-03-21 15:47:52 -07002343 // Also remove from the launcher list (if the package is a launcher).
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002344 user.removeLauncher(packageUserId, packageName);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002345
2346 // Then remove pinned shortcuts from all launchers.
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002347 user.forAllLaunchers(l -> l.cleanUpPackage(packageName, packageUserId));
2348
2349 // Now there may be orphan shortcuts because we removed pinned shortcuts at the previous
Makoto Onukicdc78f72016-03-21 15:47:52 -07002350 // step. Remove them too.
Makoto Onukic51b2872016-05-04 15:24:50 -07002351 user.forAllPackages(p -> p.refreshPinnedFlags());
Makoto Onukicdc78f72016-03-21 15:47:52 -07002352
Makoto Onukid99c6f02016-03-28 11:02:54 -07002353 scheduleSaveUser(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002354
2355 if (doNotify) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002356 notifyListeners(packageName, owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002357 }
2358
Makoto Onukib08790c2016-06-23 14:05:46 -07002359 // If the app still exists (i.e. data cleared), we need to re-publish manifest shortcuts.
2360 if (appStillExists && (packageUserId == owningUserId)) {
2361 // This will do the notification and save when needed, so do it after the above
2362 // notifyListeners.
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002363 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07002364 }
2365
Makoto Onukicdc78f72016-03-21 15:47:52 -07002366 if (!wasUserLoaded) {
2367 // Note this will execute the scheduled save.
Makoto Onukid99c6f02016-03-28 11:02:54 -07002368 unloadUserLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002369 }
2370 }
2371
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002372 /**
2373 * Entry point from {@link LauncherApps}.
2374 */
2375 private class LocalService extends ShortcutServiceInternal {
Makoto Onuki2e210c42016-03-30 08:30:36 -07002376
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002377 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002378 public List<ShortcutInfo> getShortcuts(int launcherUserId,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002379 @NonNull String callingPackage, long changedSince,
Makoto Onukiabe84422016-04-07 09:41:19 -07002380 @Nullable String packageName, @Nullable List<String> shortcutIds,
Makoto Onuki99302b52017-03-29 12:42:26 -07002381 @Nullable ComponentName componentName,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002382 int queryFlags, int userId) {
2383 final ArrayList<ShortcutInfo> ret = new ArrayList<>();
Makoto Onuki9c850012016-07-26 15:50:50 -07002384
Makoto Onuki20c95f82016-05-11 16:51:01 -07002385 final boolean cloneKeyFieldOnly =
2386 ((queryFlags & ShortcutQuery.FLAG_GET_KEY_FIELDS_ONLY) != 0);
2387 final int cloneFlag = cloneKeyFieldOnly ? ShortcutInfo.CLONE_REMOVE_NON_KEY_INFO
2388 : ShortcutInfo.CLONE_REMOVE_FOR_LAUNCHER;
Makoto Onukiabe84422016-04-07 09:41:19 -07002389 if (packageName == null) {
2390 shortcutIds = null; // LauncherAppsService already threw for it though.
2391 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002392
2393 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002394 throwIfUserLockedL(userId);
2395 throwIfUserLockedL(launcherUserId);
2396
Makoto Onuki2e210c42016-03-30 08:30:36 -07002397 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002398 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002399
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002400 if (packageName != null) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002401 getShortcutsInnerLocked(launcherUserId,
Makoto Onukiabe84422016-04-07 09:41:19 -07002402 callingPackage, packageName, shortcutIds, changedSince,
Makoto Onuki99302b52017-03-29 12:42:26 -07002403 componentName, queryFlags, userId, ret, cloneFlag);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002404 } else {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002405 final List<String> shortcutIdsF = shortcutIds;
2406 getUserShortcutsLocked(userId).forAllPackages(p -> {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002407 getShortcutsInnerLocked(launcherUserId,
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002408 callingPackage, p.getPackageName(), shortcutIdsF, changedSince,
Makoto Onuki99302b52017-03-29 12:42:26 -07002409 componentName, queryFlags, userId, ret, cloneFlag);
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002410 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002411 }
2412 }
Makoto Onukibf563b62017-05-04 10:25:30 -07002413 return setReturnedByServer(ret);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002414 }
2415
Makoto Onukid99c6f02016-03-28 11:02:54 -07002416 private void getShortcutsInnerLocked(int launcherUserId, @NonNull String callingPackage,
Makoto Onukiabe84422016-04-07 09:41:19 -07002417 @Nullable String packageName, @Nullable List<String> shortcutIds, long changedSince,
Makoto Onuki99302b52017-03-29 12:42:26 -07002418 @Nullable ComponentName componentName, int queryFlags,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002419 int userId, ArrayList<ShortcutInfo> ret, int cloneFlag) {
Makoto Onukiabe84422016-04-07 09:41:19 -07002420 final ArraySet<String> ids = shortcutIds == null ? null
2421 : new ArraySet<>(shortcutIds);
2422
Makoto Onukic51b2872016-05-04 15:24:50 -07002423 final ShortcutPackage p = getUserShortcutsLocked(userId)
2424 .getPackageShortcutsIfExists(packageName);
2425 if (p == null) {
2426 return; // No need to instantiate ShortcutPackage.
2427 }
2428
2429 p.findAll(ret,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002430 (ShortcutInfo si) -> {
2431 if (si.getLastChangedTimestamp() < changedSince) {
2432 return false;
2433 }
Makoto Onukiabe84422016-04-07 09:41:19 -07002434 if (ids != null && !ids.contains(si.getId())) {
2435 return false;
2436 }
Makoto Onuki85694522016-05-04 12:53:37 -07002437 if (componentName != null) {
Makoto Onuki9fd90192017-01-06 18:31:03 +00002438 if (si.getActivity() != null
2439 && !si.getActivity().equals(componentName)) {
Makoto Onuki85694522016-05-04 12:53:37 -07002440 return false;
2441 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002442 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002443 if (((queryFlags & ShortcutQuery.FLAG_GET_DYNAMIC) != 0)
2444 && si.isDynamic()) {
2445 return true;
2446 }
2447 if (((queryFlags & ShortcutQuery.FLAG_GET_PINNED) != 0)
2448 && si.isPinned()) {
2449 return true;
2450 }
2451 if (((queryFlags & ShortcutQuery.FLAG_GET_MANIFEST) != 0)
2452 && si.isManifestShortcut()) {
2453 return true;
2454 }
2455 return false;
Makoto Onukid99c6f02016-03-28 11:02:54 -07002456 }, cloneFlag, callingPackage, launcherUserId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002457 }
2458
2459 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002460 public boolean isPinnedByCaller(int launcherUserId, @NonNull String callingPackage,
2461 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2462 Preconditions.checkStringNotEmpty(packageName, "packageName");
2463 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
2464
2465 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002466 throwIfUserLockedL(userId);
2467 throwIfUserLockedL(launcherUserId);
2468
Makoto Onuki2e210c42016-03-30 08:30:36 -07002469 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002470 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002471
Makoto Onukid99c6f02016-03-28 11:02:54 -07002472 final ShortcutInfo si = getShortcutInfoLocked(
2473 launcherUserId, callingPackage, packageName, shortcutId, userId);
2474 return si != null && si.isPinned();
2475 }
2476 }
2477
Makoto Onuki2e210c42016-03-30 08:30:36 -07002478 private ShortcutInfo getShortcutInfoLocked(
Makoto Onukid99c6f02016-03-28 11:02:54 -07002479 int launcherUserId, @NonNull String callingPackage,
2480 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2481 Preconditions.checkStringNotEmpty(packageName, "packageName");
2482 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
2483
Makoto Onuki02f338e2016-07-29 09:40:40 -07002484 throwIfUserLockedL(userId);
2485 throwIfUserLockedL(launcherUserId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002486
Makoto Onukic51b2872016-05-04 15:24:50 -07002487 final ShortcutPackage p = getUserShortcutsLocked(userId)
2488 .getPackageShortcutsIfExists(packageName);
2489 if (p == null) {
2490 return null;
2491 }
2492
Makoto Onukid99c6f02016-03-28 11:02:54 -07002493 final ArrayList<ShortcutInfo> list = new ArrayList<>(1);
Makoto Onukic51b2872016-05-04 15:24:50 -07002494 p.findAll(list,
Makoto Onukid99c6f02016-03-28 11:02:54 -07002495 (ShortcutInfo si) -> shortcutId.equals(si.getId()),
2496 /* clone flags=*/ 0, callingPackage, launcherUserId);
2497 return list.size() == 0 ? null : list.get(0);
2498 }
2499
2500 @Override
2501 public void pinShortcuts(int launcherUserId,
2502 @NonNull String callingPackage, @NonNull String packageName,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002503 @NonNull List<String> shortcutIds, int userId) {
2504 // Calling permission must be checked by LauncherAppsImpl.
2505 Preconditions.checkStringNotEmpty(packageName, "packageName");
2506 Preconditions.checkNotNull(shortcutIds, "shortcutIds");
2507
2508 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002509 throwIfUserLockedL(userId);
2510 throwIfUserLockedL(launcherUserId);
2511
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002512 final ShortcutLauncher launcher =
Makoto Onuki2e210c42016-03-30 08:30:36 -07002513 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId);
Makoto Onukic51b2872016-05-04 15:24:50 -07002514 launcher.attemptToRestoreIfNeededAndSave();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002515
Makoto Onukic51b2872016-05-04 15:24:50 -07002516 launcher.pinShortcuts(userId, packageName, shortcutIds);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002517 }
Makoto Onuki39686e82016-04-13 18:03:00 -07002518 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07002519
2520 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002521 }
2522
2523 @Override
Makoto Onuki440a1ea2016-07-20 14:21:18 -07002524 public Intent[] createShortcutIntents(int launcherUserId,
Makoto Onukid99c6f02016-03-28 11:02:54 -07002525 @NonNull String callingPackage,
Makoto Onuki43204b82016-03-08 16:16:44 -08002526 @NonNull String packageName, @NonNull String shortcutId, int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002527 // Calling permission must be checked by LauncherAppsImpl.
Makoto Onuki43204b82016-03-08 16:16:44 -08002528 Preconditions.checkStringNotEmpty(packageName, "packageName can't be empty");
2529 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId can't be empty");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002530
2531 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002532 throwIfUserLockedL(userId);
2533 throwIfUserLockedL(launcherUserId);
2534
Makoto Onuki2e210c42016-03-30 08:30:36 -07002535 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002536 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002537
Makoto Onukid99c6f02016-03-28 11:02:54 -07002538 // Make sure the shortcut is actually visible to the launcher.
2539 final ShortcutInfo si = getShortcutInfoLocked(
2540 launcherUserId, callingPackage, packageName, shortcutId, userId);
2541 // "si == null" should suffice here, but check the flags too just to make sure.
Makoto Onuki22fcc682016-05-17 14:52:19 -07002542 if (si == null || !si.isEnabled() || !si.isAlive()) {
Makoto Onuki83f6d2d2016-07-11 14:30:19 -07002543 Log.e(TAG, "Shortcut " + shortcutId + " does not exist or disabled");
Makoto Onukid99c6f02016-03-28 11:02:54 -07002544 return null;
2545 }
Makoto Onuki440a1ea2016-07-20 14:21:18 -07002546 return si.getIntents();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002547 }
2548 }
2549
2550 @Override
2551 public void addListener(@NonNull ShortcutChangeListener listener) {
2552 synchronized (mLock) {
2553 mListeners.add(Preconditions.checkNotNull(listener));
2554 }
2555 }
Makoto Onuki55046222016-03-08 10:49:47 -08002556
2557 @Override
Makoto Onukiabe84422016-04-07 09:41:19 -07002558 public int getShortcutIconResId(int launcherUserId, @NonNull String callingPackage,
2559 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2560 Preconditions.checkNotNull(callingPackage, "callingPackage");
2561 Preconditions.checkNotNull(packageName, "packageName");
2562 Preconditions.checkNotNull(shortcutId, "shortcutId");
Makoto Onuki55046222016-03-08 10:49:47 -08002563
2564 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002565 throwIfUserLockedL(userId);
2566 throwIfUserLockedL(launcherUserId);
2567
Makoto Onuki2e210c42016-03-30 08:30:36 -07002568 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002569 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002570
Makoto Onukic51b2872016-05-04 15:24:50 -07002571 final ShortcutPackage p = getUserShortcutsLocked(userId)
2572 .getPackageShortcutsIfExists(packageName);
2573 if (p == null) {
2574 return 0;
2575 }
2576
2577 final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId);
Makoto Onuki55046222016-03-08 10:49:47 -08002578 return (shortcutInfo != null && shortcutInfo.hasIconResource())
2579 ? shortcutInfo.getIconResourceId() : 0;
2580 }
2581 }
2582
2583 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002584 public ParcelFileDescriptor getShortcutIconFd(int launcherUserId,
Makoto Onukiabe84422016-04-07 09:41:19 -07002585 @NonNull String callingPackage, @NonNull String packageName,
2586 @NonNull String shortcutId, int userId) {
2587 Preconditions.checkNotNull(callingPackage, "callingPackage");
2588 Preconditions.checkNotNull(packageName, "packageName");
2589 Preconditions.checkNotNull(shortcutId, "shortcutId");
Makoto Onuki55046222016-03-08 10:49:47 -08002590
2591 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002592 throwIfUserLockedL(userId);
2593 throwIfUserLockedL(launcherUserId);
2594
Makoto Onuki2e210c42016-03-30 08:30:36 -07002595 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002596 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002597
Makoto Onukic51b2872016-05-04 15:24:50 -07002598 final ShortcutPackage p = getUserShortcutsLocked(userId)
2599 .getPackageShortcutsIfExists(packageName);
2600 if (p == null) {
2601 return null;
2602 }
2603
2604 final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId);
Makoto Onuki55046222016-03-08 10:49:47 -08002605 if (shortcutInfo == null || !shortcutInfo.hasIconFile()) {
2606 return null;
2607 }
Makoto Onuki475c3652017-05-08 14:29:03 -07002608 final String path = mShortcutBitmapSaver.getBitmapPathMayWaitLocked(shortcutInfo);
2609 if (path == null) {
2610 Slog.w(TAG, "null bitmap detected in getShortcutIconFd()");
2611 return null;
2612 }
Makoto Onuki55046222016-03-08 10:49:47 -08002613 try {
2614 return ParcelFileDescriptor.open(
Makoto Onuki475c3652017-05-08 14:29:03 -07002615 new File(path),
Makoto Onuki55046222016-03-08 10:49:47 -08002616 ParcelFileDescriptor.MODE_READ_ONLY);
2617 } catch (FileNotFoundException e) {
Makoto Onuki475c3652017-05-08 14:29:03 -07002618 Slog.e(TAG, "Icon file not found: " + path);
Makoto Onuki55046222016-03-08 10:49:47 -08002619 return null;
2620 }
2621 }
2622 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002623
2624 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002625 public boolean hasShortcutHostPermission(int launcherUserId,
2626 @NonNull String callingPackage) {
2627 return ShortcutService.this.hasShortcutHostPermission(callingPackage, launcherUserId);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002628 }
Sunny Goyal87a563e2017-01-01 19:42:45 -08002629
2630 @Override
2631 public boolean requestPinAppWidget(@NonNull String callingPackage,
Sunny Goyal4ad6b572017-02-28 11:11:51 -08002632 @NonNull AppWidgetProviderInfo appWidget, @Nullable Bundle extras,
2633 @Nullable IntentSender resultIntent, int userId) {
Sunny Goyal87a563e2017-01-01 19:42:45 -08002634 Preconditions.checkNotNull(appWidget);
Sunny Goyal4ad6b572017-02-28 11:11:51 -08002635 return requestPinItem(callingPackage, userId, null, appWidget, extras, resultIntent);
Sunny Goyal87a563e2017-01-01 19:42:45 -08002636 }
Sunny Goyal7f7372a2017-01-24 11:53:54 -08002637
2638 @Override
2639 public boolean isRequestPinItemSupported(int callingUserId, int requestType) {
2640 return ShortcutService.this.isRequestPinItemSupported(callingUserId, requestType);
2641 }
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002642 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002643
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002644 final BroadcastReceiver mReceiver = new BroadcastReceiver() {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002645 @Override
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002646 public void onReceive(Context context, Intent intent) {
2647 if (!mBootCompleted.get()) {
2648 return; // Boot not completed, ignore the broadcast.
2649 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07002650 try {
2651 if (Intent.ACTION_LOCALE_CHANGED.equals(intent.getAction())) {
2652 handleLocaleChanged();
2653 }
2654 } catch (Exception e) {
2655 wtf("Exception in mReceiver.onReceive", e);
Makoto Onukic51b2872016-05-04 15:24:50 -07002656 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002657 }
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002658 };
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002659
Makoto Onuki157b1622016-06-02 16:13:10 -07002660 void handleLocaleChanged() {
2661 if (DEBUG) {
2662 Slog.d(TAG, "handleLocaleChanged");
2663 }
2664 scheduleSaveBaseState();
2665
Makoto Onuki02f338e2016-07-29 09:40:40 -07002666 synchronized (mLock) {
2667 final long token = injectClearCallingIdentity();
2668 try {
2669 forEachLoadedUserLocked(user -> user.detectLocaleChange());
2670 } finally {
2671 injectRestoreCallingIdentity(token);
2672 }
Makoto Onuki157b1622016-06-02 16:13:10 -07002673 }
2674 }
2675
Makoto Onukif34c3082016-07-13 10:25:25 -07002676 /**
2677 * Package event callbacks.
2678 */
2679 @VisibleForTesting
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002680 final BroadcastReceiver mPackageMonitor = new BroadcastReceiver() {
Makoto Onukif34c3082016-07-13 10:25:25 -07002681 @Override
2682 public void onReceive(Context context, Intent intent) {
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002683 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
2684 if (userId == UserHandle.USER_NULL) {
2685 Slog.w(TAG, "Intent broadcast does not contain user handle: " + intent);
2686 return;
2687 }
2688
2689 final String action = intent.getAction();
2690
2691 // This is normally called on Handler, so clearCallingIdentity() isn't needed,
2692 // but we still check it in unit tests.
Makoto Onukif34c3082016-07-13 10:25:25 -07002693 final long token = injectClearCallingIdentity();
2694 try {
Makoto Onuki10305202016-07-14 18:14:08 -07002695 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002696 if (!isUserUnlockedL(userId)) {
2697 if (DEBUG) {
2698 Slog.d(TAG, "Ignoring package broadcast " + action
2699 + " for locked/stopped user " + userId);
2700 }
2701 return;
2702 }
2703
2704 // Whenever we get one of those package broadcasts, or get
2705 // ACTION_PREFERRED_ACTIVITY_CHANGED, we purge the default launcher cache.
Makoto Onuki10305202016-07-14 18:14:08 -07002706 final ShortcutUser user = getUserShortcutsLocked(userId);
2707 user.clearLauncher();
2708 }
2709 if (Intent.ACTION_PREFERRED_ACTIVITY_CHANGED.equals(action)) {
2710 // Nothing farther to do.
2711 return;
2712 }
2713
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002714 final Uri intentUri = intent.getData();
2715 final String packageName = (intentUri != null) ? intentUri.getSchemeSpecificPart()
2716 : null;
2717 if (packageName == null) {
2718 Slog.w(TAG, "Intent broadcast does not contain package name: " + intent);
2719 return;
2720 }
2721
2722 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
2723
2724 switch (action) {
2725 case Intent.ACTION_PACKAGE_ADDED:
2726 if (replacing) {
2727 handlePackageUpdateFinished(packageName, userId);
2728 } else {
2729 handlePackageAdded(packageName, userId);
2730 }
2731 break;
2732 case Intent.ACTION_PACKAGE_REMOVED:
2733 if (!replacing) {
2734 handlePackageRemoved(packageName, userId);
2735 }
2736 break;
2737 case Intent.ACTION_PACKAGE_CHANGED:
2738 handlePackageChanged(packageName, userId);
2739
2740 break;
2741 case Intent.ACTION_PACKAGE_DATA_CLEARED:
2742 handlePackageDataCleared(packageName, userId);
2743 break;
2744 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07002745 } catch (Exception e) {
2746 wtf("Exception in mPackageMonitor.onReceive", e);
Makoto Onukif34c3082016-07-13 10:25:25 -07002747 } finally {
2748 injectRestoreCallingIdentity(token);
Makoto Onukia2241832016-07-06 13:28:37 -07002749 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07002750 }
Makoto Onukif34c3082016-07-13 10:25:25 -07002751 };
Makoto Onukicdc78f72016-03-21 15:47:52 -07002752
Makoto Onuki0acbb142016-03-22 17:02:57 -07002753 /**
Makoto Onuki39686e82016-04-13 18:03:00 -07002754 * Called when a user is unlocked.
2755 * - Check all known packages still exist, and otherwise perform cleanup.
2756 * - If a package still exists, check the version code. If it's been updated, may need to
Makoto Onukib08790c2016-06-23 14:05:46 -07002757 * update timestamps of its shortcuts.
Makoto Onuki0acbb142016-03-22 17:02:57 -07002758 */
Makoto Onukid99c6f02016-03-28 11:02:54 -07002759 @VisibleForTesting
Makoto Onuki39686e82016-04-13 18:03:00 -07002760 void checkPackageChanges(@UserIdInt int ownerUserId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07002761 if (DEBUG) {
Makoto Onuki39686e82016-04-13 18:03:00 -07002762 Slog.d(TAG, "checkPackageChanges() ownerUserId=" + ownerUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002763 }
Makoto Onukib08790c2016-06-23 14:05:46 -07002764 if (injectIsSafeModeEnabled()) {
2765 Slog.i(TAG, "Safe mode, skipping checkPackageChanges()");
2766 return;
2767 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07002768
Makoto Onuki22fcc682016-05-17 14:52:19 -07002769 final long start = injectElapsedRealtime();
2770 try {
2771 final ArrayList<PackageWithUser> gonePackages = new ArrayList<>();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002772
Makoto Onuki22fcc682016-05-17 14:52:19 -07002773 synchronized (mLock) {
2774 final ShortcutUser user = getUserShortcutsLocked(ownerUserId);
2775
2776 // Find packages that have been uninstalled.
2777 user.forAllPackageItems(spi -> {
2778 if (spi.getPackageInfo().isShadow()) {
2779 return; // Don't delete shadow information.
2780 }
2781 if (!isPackageInstalled(spi.getPackageName(), spi.getPackageUserId())) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002782 if (DEBUG) {
2783 Slog.d(TAG, "Uninstalled: " + spi.getPackageName()
2784 + " user " + spi.getPackageUserId());
2785 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002786 gonePackages.add(PackageWithUser.of(spi));
2787 }
2788 });
2789 if (gonePackages.size() > 0) {
2790 for (int i = gonePackages.size() - 1; i >= 0; i--) {
2791 final PackageWithUser pu = gonePackages.get(i);
Makoto Onukib08790c2016-06-23 14:05:46 -07002792 cleanUpPackageLocked(pu.packageName, ownerUserId, pu.userId,
2793 /* appStillExists = */ false);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002794 }
Makoto Onukid99c6f02016-03-28 11:02:54 -07002795 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002796
Makoto Onuki248a0ef2016-11-03 15:59:01 -07002797 rescanUpdatedPackagesLocked(ownerUserId, user.getLastAppScanTime());
Makoto Onuki0acbb142016-03-22 17:02:57 -07002798 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002799 } finally {
2800 logDurationStat(Stats.CHECK_PACKAGE_CHANGES, start);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002801 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002802 verifyStates();
Makoto Onukicdc78f72016-03-21 15:47:52 -07002803 }
2804
Makoto Onuki248a0ef2016-11-03 15:59:01 -07002805 private void rescanUpdatedPackagesLocked(@UserIdInt int userId, long lastScanTime) {
Makoto Onuki377b7972016-08-09 14:43:55 -07002806 final ShortcutUser user = getUserShortcutsLocked(userId);
2807
Makoto Onuki33663282016-08-22 16:19:04 -07002808 // Note after each OTA, we'll need to rescan all system apps, as their lastUpdateTime
2809 // is not reliable.
Makoto Onuki377b7972016-08-09 14:43:55 -07002810 final long now = injectCurrentTimeMillis();
Makoto Onuki33663282016-08-22 16:19:04 -07002811 final boolean afterOta =
2812 !injectBuildFingerprint().equals(user.getLastAppScanOsFingerprint());
Makoto Onuki377b7972016-08-09 14:43:55 -07002813
2814 // Then for each installed app, publish manifest shortcuts when needed.
Makoto Onuki33663282016-08-22 16:19:04 -07002815 forUpdatedPackages(userId, lastScanTime, afterOta, ai -> {
Makoto Onuki377b7972016-08-09 14:43:55 -07002816 user.attemptToRestoreIfNeededAndSave(this, ai.packageName, userId);
Makoto Onuki248a0ef2016-11-03 15:59:01 -07002817
2818 user.rescanPackageIfNeeded(ai.packageName, /* forceRescan= */ true);
Makoto Onuki377b7972016-08-09 14:43:55 -07002819 });
2820
2821 // Write the time just before the scan, because there may be apps that have just
2822 // been updated, and we want to catch them in the next time.
2823 user.setLastAppScanTime(now);
Makoto Onuki33663282016-08-22 16:19:04 -07002824 user.setLastAppScanOsFingerprint(injectBuildFingerprint());
Makoto Onuki377b7972016-08-09 14:43:55 -07002825 scheduleSaveUser(userId);
2826 }
2827
Makoto Onuki0acbb142016-03-22 17:02:57 -07002828 private void handlePackageAdded(String packageName, @UserIdInt int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07002829 if (DEBUG) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07002830 Slog.d(TAG, String.format("handlePackageAdded: %s user=%d", packageName, userId));
2831 }
2832 synchronized (mLock) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002833 final ShortcutUser user = getUserShortcutsLocked(userId);
2834 user.attemptToRestoreIfNeededAndSave(this, packageName, userId);
Makoto Onuki64183d52016-08-08 14:11:34 -07002835 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002836 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002837 verifyStates();
Makoto Onuki0acbb142016-03-22 17:02:57 -07002838 }
2839
2840 private void handlePackageUpdateFinished(String packageName, @UserIdInt int userId) {
Makoto Onuki905e8852016-03-28 10:40:58 -07002841 if (DEBUG) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002842 Slog.d(TAG, String.format("handlePackageUpdateFinished: %s user=%d",
2843 packageName, userId));
Makoto Onuki0acbb142016-03-22 17:02:57 -07002844 }
2845 synchronized (mLock) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002846 final ShortcutUser user = getUserShortcutsLocked(userId);
2847 user.attemptToRestoreIfNeededAndSave(this, packageName, userId);
Makoto Onuki39686e82016-04-13 18:03:00 -07002848
Makoto Onuki22fcc682016-05-17 14:52:19 -07002849 if (isPackageInstalled(packageName, userId)) {
Makoto Onuki64183d52016-08-08 14:11:34 -07002850 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onuki39686e82016-04-13 18:03:00 -07002851 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07002852 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002853 verifyStates();
Makoto Onuki0acbb142016-03-22 17:02:57 -07002854 }
2855
Makoto Onuki2e210c42016-03-30 08:30:36 -07002856 private void handlePackageRemoved(String packageName, @UserIdInt int packageUserId) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07002857 if (DEBUG) {
Makoto Onuki2e210c42016-03-30 08:30:36 -07002858 Slog.d(TAG, String.format("handlePackageRemoved: %s user=%d", packageName,
2859 packageUserId));
Makoto Onukicdc78f72016-03-21 15:47:52 -07002860 }
Makoto Onukib08790c2016-06-23 14:05:46 -07002861 cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ false);
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002862
2863 verifyStates();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002864 }
2865
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002866 private void handlePackageDataCleared(String packageName, int packageUserId) {
2867 if (DEBUG) {
2868 Slog.d(TAG, String.format("handlePackageDataCleared: %s user=%d", packageName,
2869 packageUserId));
Makoto Onukicdc78f72016-03-21 15:47:52 -07002870 }
Makoto Onukib08790c2016-06-23 14:05:46 -07002871 cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ true);
2872
2873 verifyStates();
2874 }
2875
2876 private void handlePackageChanged(String packageName, int packageUserId) {
Makoto Onuki82fb2eb2017-03-31 16:58:26 -07002877 if (!isPackageInstalled(packageName, packageUserId)) {
2878 // Probably disabled, which is the same thing as uninstalled.
2879 handlePackageRemoved(packageName, packageUserId);
2880 return;
2881 }
Makoto Onukib08790c2016-06-23 14:05:46 -07002882 if (DEBUG) {
2883 Slog.d(TAG, String.format("handlePackageChanged: %s user=%d", packageName,
2884 packageUserId));
2885 }
2886
2887 // Activities may be disabled or enabled. Just rescan the package.
2888 synchronized (mLock) {
2889 final ShortcutUser user = getUserShortcutsLocked(packageUserId);
2890
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002891 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07002892 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002893
2894 verifyStates();
Makoto Onukicdc78f72016-03-21 15:47:52 -07002895 }
2896
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002897 // === PackageManager interaction ===
Makoto Onuki0acbb142016-03-22 17:02:57 -07002898
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002899 /**
2900 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
2901 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002902 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002903 final PackageInfo getPackageInfoWithSignatures(String packageName, @UserIdInt int userId) {
2904 return getPackageInfo(packageName, userId, true);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002905 }
2906
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002907 /**
2908 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
2909 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002910 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002911 final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId) {
2912 return getPackageInfo(packageName, userId, false);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002913 }
2914
Makoto Onuki905e8852016-03-28 10:40:58 -07002915 int injectGetPackageUid(@NonNull String packageName, @UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002916 final long token = injectClearCallingIdentity();
Makoto Onuki905e8852016-03-28 10:40:58 -07002917 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002918 return mIPackageManager.getPackageUid(packageName, PACKAGE_MATCH_FLAGS, userId);
Makoto Onuki905e8852016-03-28 10:40:58 -07002919 } catch (RemoteException e) {
2920 // Shouldn't happen.
2921 Slog.wtf(TAG, "RemoteException", e);
2922 return -1;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002923 } finally {
2924 injectRestoreCallingIdentity(token);
Makoto Onuki905e8852016-03-28 10:40:58 -07002925 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07002926 }
2927
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002928 /**
2929 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
2930 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002931 @Nullable
Makoto Onuki0acbb142016-03-22 17:02:57 -07002932 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002933 final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId,
2934 boolean getSignatures) {
2935 return isInstalledOrNull(injectPackageInfoWithUninstalled(
2936 packageName, userId, getSignatures));
2937 }
2938
2939 /**
2940 * Do not use directly; this returns uninstalled packages too.
2941 */
2942 @Nullable
2943 @VisibleForTesting
2944 PackageInfo injectPackageInfoWithUninstalled(String packageName, @UserIdInt int userId,
Makoto Onuki0acbb142016-03-22 17:02:57 -07002945 boolean getSignatures) {
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07002946 final long start = injectElapsedRealtime();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002947 final long token = injectClearCallingIdentity();
Makoto Onuki0acbb142016-03-22 17:02:57 -07002948 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002949 return mIPackageManager.getPackageInfo(
2950 packageName, PACKAGE_MATCH_FLAGS
2951 | (getSignatures ? PackageManager.GET_SIGNATURES : 0), userId);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002952 } catch (RemoteException e) {
2953 // Shouldn't happen.
2954 Slog.wtf(TAG, "RemoteException", e);
2955 return null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002956 } finally {
2957 injectRestoreCallingIdentity(token);
Makoto Onuki2e210c42016-03-30 08:30:36 -07002958
2959 logDurationStat(
2960 (getSignatures ? Stats.GET_PACKAGE_INFO_WITH_SIG : Stats.GET_PACKAGE_INFO),
2961 start);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002962 }
2963 }
2964
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002965 /**
2966 * Returns {@link ApplicationInfo} unless it's uninstalled or disabled.
2967 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002968 @Nullable
Makoto Onuki905e8852016-03-28 10:40:58 -07002969 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002970 final ApplicationInfo getApplicationInfo(String packageName, @UserIdInt int userId) {
2971 return isInstalledOrNull(injectApplicationInfoWithUninstalled(packageName, userId));
2972 }
2973
2974 /**
2975 * Do not use directly; this returns uninstalled packages too.
2976 */
2977 @Nullable
2978 @VisibleForTesting
2979 ApplicationInfo injectApplicationInfoWithUninstalled(
2980 String packageName, @UserIdInt int userId) {
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07002981 final long start = injectElapsedRealtime();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002982 final long token = injectClearCallingIdentity();
Makoto Onuki905e8852016-03-28 10:40:58 -07002983 try {
2984 return mIPackageManager.getApplicationInfo(packageName, PACKAGE_MATCH_FLAGS, userId);
2985 } catch (RemoteException e) {
2986 // Shouldn't happen.
2987 Slog.wtf(TAG, "RemoteException", e);
2988 return null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002989 } finally {
2990 injectRestoreCallingIdentity(token);
Makoto Onuki2e210c42016-03-30 08:30:36 -07002991
2992 logDurationStat(Stats.GET_APPLICATION_INFO, start);
Makoto Onuki905e8852016-03-28 10:40:58 -07002993 }
2994 }
2995
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002996 /**
2997 * Returns {@link ActivityInfo} with its metadata unless it's uninstalled or disabled.
2998 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002999 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003000 final ActivityInfo getActivityInfoWithMetadata(ComponentName activity, @UserIdInt int userId) {
3001 return isInstalledOrNull(injectGetActivityInfoWithMetadataWithUninstalled(
3002 activity, userId));
3003 }
3004
3005 /**
3006 * Do not use directly; this returns uninstalled packages too.
3007 */
3008 @Nullable
3009 @VisibleForTesting
3010 ActivityInfo injectGetActivityInfoWithMetadataWithUninstalled(
3011 ComponentName activity, @UserIdInt int userId) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07003012 final long start = injectElapsedRealtime();
3013 final long token = injectClearCallingIdentity();
3014 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07003015 return mIPackageManager.getActivityInfo(activity,
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003016 (PACKAGE_MATCH_FLAGS | PackageManager.GET_META_DATA), userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003017 } catch (RemoteException e) {
3018 // Shouldn't happen.
3019 Slog.wtf(TAG, "RemoteException", e);
3020 return null;
3021 } finally {
3022 injectRestoreCallingIdentity(token);
3023
Makoto Onukib08790c2016-06-23 14:05:46 -07003024 logDurationStat(Stats.GET_ACTIVITY_WITH_METADATA, start);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003025 }
3026 }
3027
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003028 /**
3029 * Return all installed and enabled packages.
3030 */
3031 @NonNull
Makoto Onuki22fcc682016-05-17 14:52:19 -07003032 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003033 final List<PackageInfo> getInstalledPackages(@UserIdInt int userId) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07003034 final long start = injectElapsedRealtime();
3035 final long token = injectClearCallingIdentity();
3036 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003037 final List<PackageInfo> all = injectGetPackagesWithUninstalled(userId);
3038
3039 all.removeIf(PACKAGE_NOT_INSTALLED);
3040
3041 return all;
Makoto Onuki22fcc682016-05-17 14:52:19 -07003042 } catch (RemoteException e) {
3043 // Shouldn't happen.
3044 Slog.wtf(TAG, "RemoteException", e);
3045 return null;
3046 } finally {
3047 injectRestoreCallingIdentity(token);
3048
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003049 logDurationStat(Stats.GET_INSTALLED_PACKAGES, start);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003050 }
3051 }
3052
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003053 /**
3054 * Do not use directly; this returns uninstalled packages too.
3055 */
3056 @NonNull
3057 @VisibleForTesting
3058 List<PackageInfo> injectGetPackagesWithUninstalled(@UserIdInt int userId)
3059 throws RemoteException {
3060 final ParceledListSlice<PackageInfo> parceledList =
3061 mIPackageManager.getInstalledPackages(PACKAGE_MATCH_FLAGS, userId);
3062 if (parceledList == null) {
3063 return Collections.emptyList();
3064 }
3065 return parceledList.getList();
3066 }
3067
Makoto Onuki33663282016-08-22 16:19:04 -07003068 private void forUpdatedPackages(@UserIdInt int userId, long lastScanTime, boolean afterOta,
Makoto Onuki22fcc682016-05-17 14:52:19 -07003069 Consumer<ApplicationInfo> callback) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003070 if (DEBUG) {
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003071 Slog.d(TAG, "forUpdatedPackages for user " + userId + ", lastScanTime=" + lastScanTime
3072 + " afterOta=" + afterOta);
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003073 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003074 final List<PackageInfo> list = getInstalledPackages(userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003075 for (int i = list.size() - 1; i >= 0; i--) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003076 final PackageInfo pi = list.get(i);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003077
Makoto Onuki64183d52016-08-08 14:11:34 -07003078 // If the package has been updated since the last scan time, then scan it.
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003079 // Also if it's right after an OTA, always re-scan all apps anyway, since the
3080 // shortcut parser might have changed.
3081 if (afterOta || (pi.lastUpdateTime >= lastScanTime)) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003082 if (DEBUG) {
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003083 Slog.d(TAG, "Found updated package " + pi.packageName
3084 + " updateTime=" + pi.lastUpdateTime);
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003085 }
3086 callback.accept(pi.applicationInfo);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003087 }
3088 }
3089 }
3090
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003091 private boolean isApplicationFlagSet(@NonNull String packageName, int userId, int flags) {
3092 final ApplicationInfo ai = injectApplicationInfoWithUninstalled(packageName, userId);
Makoto Onuki905e8852016-03-28 10:40:58 -07003093 return (ai != null) && ((ai.flags & flags) == flags);
3094 }
3095
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003096 private static boolean isInstalled(@Nullable ApplicationInfo ai) {
Makoto Onuki82fb2eb2017-03-31 16:58:26 -07003097 return (ai != null) && ai.enabled && (ai.flags & ApplicationInfo.FLAG_INSTALLED) != 0;
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003098 }
3099
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08003100 private static boolean isEphemeralApp(@Nullable ApplicationInfo ai) {
Svetoslav Ganov096d3042017-01-30 16:34:13 -08003101 return (ai != null) && ai.isInstantApp();
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08003102 }
3103
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003104 private static boolean isInstalled(@Nullable PackageInfo pi) {
3105 return (pi != null) && isInstalled(pi.applicationInfo);
3106 }
3107
3108 private static boolean isInstalled(@Nullable ActivityInfo ai) {
3109 return (ai != null) && isInstalled(ai.applicationInfo);
3110 }
3111
3112 private static ApplicationInfo isInstalledOrNull(ApplicationInfo ai) {
3113 return isInstalled(ai) ? ai : null;
3114 }
3115
3116 private static PackageInfo isInstalledOrNull(PackageInfo pi) {
3117 return isInstalled(pi) ? pi : null;
3118 }
3119
3120 private static ActivityInfo isInstalledOrNull(ActivityInfo ai) {
3121 return isInstalled(ai) ? ai : null;
3122 }
3123
Makoto Onuki2e210c42016-03-30 08:30:36 -07003124 boolean isPackageInstalled(String packageName, int userId) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003125 return getApplicationInfo(packageName, userId) != null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003126 }
3127
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08003128 boolean isEphemeralApp(String packageName, int userId) {
3129 return isEphemeralApp(getApplicationInfo(packageName, userId));
3130 }
3131
Makoto Onuki22fcc682016-05-17 14:52:19 -07003132 @Nullable
3133 XmlResourceParser injectXmlMetaData(ActivityInfo activityInfo, String key) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07003134 return activityInfo.loadXmlMetaData(mContext.getPackageManager(), key);
Makoto Onuki39686e82016-04-13 18:03:00 -07003135 }
3136
Makoto Onuki157b1622016-06-02 16:13:10 -07003137 @Nullable
3138 Resources injectGetResourcesForApplicationAsUser(String packageName, int userId) {
3139 final long start = injectElapsedRealtime();
3140 final long token = injectClearCallingIdentity();
3141 try {
3142 return mContext.getPackageManager().getResourcesForApplicationAsUser(
3143 packageName, userId);
3144 } catch (NameNotFoundException e) {
3145 Slog.e(TAG, "Resources for package " + packageName + " not found");
3146 return null;
3147 } finally {
3148 injectRestoreCallingIdentity(token);
3149
3150 logDurationStat(Stats.GET_APPLICATION_RESOURCES, start);
3151 }
3152 }
3153
Makoto Onukib08790c2016-06-23 14:05:46 -07003154 private Intent getMainActivityIntent() {
3155 final Intent intent = new Intent(Intent.ACTION_MAIN);
3156 intent.addCategory(LAUNCHER_INTENT_CATEGORY);
3157 return intent;
3158 }
3159
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003160 /**
3161 * Same as queryIntentActivitiesAsUser, except it makes sure the package is installed,
3162 * and only returns exported activities.
3163 */
3164 @NonNull
3165 @VisibleForTesting
3166 List<ResolveInfo> queryActivities(@NonNull Intent baseIntent,
3167 @NonNull String packageName, @Nullable ComponentName activity, int userId) {
3168
3169 baseIntent.setPackage(Preconditions.checkNotNull(packageName));
3170 if (activity != null) {
3171 baseIntent.setComponent(activity);
3172 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08003173 return queryActivities(baseIntent, userId, /* exportedOnly =*/ true);
3174 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003175
Makoto Onuki2d895c32016-12-02 15:48:40 -08003176 @NonNull
3177 List<ResolveInfo> queryActivities(@NonNull Intent intent, int userId,
3178 boolean exportedOnly) {
3179 final List<ResolveInfo> resolved;
3180 final long token = injectClearCallingIdentity();
3181 try {
3182 resolved =
3183 mContext.getPackageManager().queryIntentActivitiesAsUser(
3184 intent, PACKAGE_MATCH_FLAGS, userId);
3185 } finally {
3186 injectRestoreCallingIdentity(token);
3187 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003188 if (resolved == null || resolved.size() == 0) {
3189 return EMPTY_RESOLVE_INFO;
3190 }
3191 // Make sure the package is installed.
3192 if (!isInstalled(resolved.get(0).activityInfo)) {
3193 return EMPTY_RESOLVE_INFO;
3194 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08003195 if (exportedOnly) {
3196 resolved.removeIf(ACTIVITY_NOT_EXPORTED);
3197 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003198 return resolved;
3199 }
3200
3201 /**
3202 * Return the main activity that is enabled and exported. If multiple activities are found,
3203 * return the first one.
3204 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003205 @Nullable
3206 ComponentName injectGetDefaultMainActivity(@NonNull String packageName, int userId) {
3207 final long start = injectElapsedRealtime();
Makoto Onukib08790c2016-06-23 14:05:46 -07003208 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07003209 final List<ResolveInfo> resolved =
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003210 queryActivities(getMainActivityIntent(), packageName, null, userId);
3211 return resolved.size() == 0 ? null : resolved.get(0).activityInfo.getComponentName();
Makoto Onukib08790c2016-06-23 14:05:46 -07003212 } finally {
Makoto Onukib08790c2016-06-23 14:05:46 -07003213 logDurationStat(Stats.GET_LAUNCHER_ACTIVITY, start);
3214 }
3215 }
3216
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003217 /**
3218 * Return whether an activity is enabled, exported and main.
3219 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003220 boolean injectIsMainActivity(@NonNull ComponentName activity, int userId) {
3221 final long start = injectElapsedRealtime();
Makoto Onukib08790c2016-06-23 14:05:46 -07003222 try {
Makoto Onuki34145532017-03-14 17:58:36 -07003223 if (activity == null) {
3224 wtf("null activity detected");
3225 return false;
3226 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08003227 if (DUMMY_MAIN_ACTIVITY.equals(activity.getClassName())) {
3228 return true;
3229 }
3230 final List<ResolveInfo> resolved = queryActivities(
3231 getMainActivityIntent(), activity.getPackageName(), activity, userId);
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003232 return resolved.size() > 0;
Makoto Onukib08790c2016-06-23 14:05:46 -07003233 } finally {
Makoto Onukib08790c2016-06-23 14:05:46 -07003234 logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start);
3235 }
3236 }
3237
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003238 /**
Makoto Onuki2d895c32016-12-02 15:48:40 -08003239 * Create a dummy "main activity" component name which is used to create a dynamic shortcut
3240 * with no main activity temporarily.
3241 */
3242 @NonNull
3243 ComponentName getDummyMainActivity(@NonNull String packageName) {
3244 return new ComponentName(packageName, DUMMY_MAIN_ACTIVITY);
3245 }
3246
Makoto Onuki255461f2017-01-10 11:47:25 -08003247 boolean isDummyMainActivity(@Nullable ComponentName name) {
3248 return name != null && DUMMY_MAIN_ACTIVITY.equals(name.getClassName());
3249 }
3250
Makoto Onuki2d895c32016-12-02 15:48:40 -08003251 /**
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003252 * Return all the enabled, exported and main activities from a package.
3253 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003254 @NonNull
3255 List<ResolveInfo> injectGetMainActivities(@NonNull String packageName, int userId) {
3256 final long start = injectElapsedRealtime();
Makoto Onukib08790c2016-06-23 14:05:46 -07003257 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003258 return queryActivities(getMainActivityIntent(), packageName, null, userId);
Makoto Onukib08790c2016-06-23 14:05:46 -07003259 } finally {
Makoto Onukib08790c2016-06-23 14:05:46 -07003260 logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start);
3261 }
3262 }
3263
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003264 /**
3265 * Return whether an activity is enabled and exported.
3266 */
3267 @VisibleForTesting
3268 boolean injectIsActivityEnabledAndExported(
3269 @NonNull ComponentName activity, @UserIdInt int userId) {
3270 final long start = injectElapsedRealtime();
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003271 try {
3272 return queryActivities(new Intent(), activity.getPackageName(), activity, userId)
3273 .size() > 0;
3274 } finally {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003275 logDurationStat(Stats.IS_ACTIVITY_ENABLED, start);
3276 }
3277 }
3278
Makoto Onuki2d895c32016-12-02 15:48:40 -08003279 /**
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003280 * Get the {@link LauncherApps#ACTION_CONFIRM_PIN_SHORTCUT} or
3281 * {@link LauncherApps#ACTION_CONFIRM_PIN_APPWIDGET} activity in a given package depending on
3282 * the requestType.
Makoto Onuki2d895c32016-12-02 15:48:40 -08003283 */
3284 @Nullable
3285 ComponentName injectGetPinConfirmationActivity(@NonNull String launcherPackageName,
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003286 int launcherUserId, int requestType) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08003287 Preconditions.checkNotNull(launcherPackageName);
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003288 String action = requestType == LauncherApps.PinItemRequest.REQUEST_TYPE_SHORTCUT ?
3289 LauncherApps.ACTION_CONFIRM_PIN_SHORTCUT :
3290 LauncherApps.ACTION_CONFIRM_PIN_APPWIDGET;
Makoto Onuki2d895c32016-12-02 15:48:40 -08003291
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003292 final Intent confirmIntent = new Intent(action).setPackage(launcherPackageName);
Makoto Onuki2d895c32016-12-02 15:48:40 -08003293 final List<ResolveInfo> candidates = queryActivities(
3294 confirmIntent, launcherUserId, /* exportedOnly =*/ false);
3295 for (ResolveInfo ri : candidates) {
3296 return ri.activityInfo.getComponentName();
3297 }
3298 return null;
3299 }
3300
Makoto Onukib08790c2016-06-23 14:05:46 -07003301 boolean injectIsSafeModeEnabled() {
3302 final long token = injectClearCallingIdentity();
3303 try {
3304 return IWindowManager.Stub
3305 .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE))
3306 .isSafeModeEnabled();
3307 } catch (RemoteException e) {
3308 return false; // Shouldn't happen though.
3309 } finally {
3310 injectRestoreCallingIdentity(token);
3311 }
3312 }
3313
Makoto Onuki2d895c32016-12-02 15:48:40 -08003314 /**
3315 * If {@code userId} is of a managed profile, return the parent user ID. Otherwise return
3316 * itself.
3317 */
3318 int getParentOrSelfUserId(int userId) {
3319 final long token = injectClearCallingIdentity();
3320 try {
3321 final UserInfo parent = mUserManager.getProfileParent(userId);
3322 return (parent != null) ? parent.id : userId;
3323 } finally {
3324 injectRestoreCallingIdentity(token);
3325 }
3326 }
3327
Sunny Goyal87a563e2017-01-01 19:42:45 -08003328 void injectSendIntentSender(IntentSender intentSender, Intent extras) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08003329 if (intentSender == null) {
3330 return;
3331 }
3332 try {
Sunny Goyal87a563e2017-01-01 19:42:45 -08003333 intentSender.sendIntent(mContext, /* code= */ 0, extras,
Makoto Onuki2d895c32016-12-02 15:48:40 -08003334 /* onFinished=*/ null, /* handler= */ null);
3335 } catch (SendIntentException e) {
3336 Slog.w(TAG, "sendIntent failed().", e);
3337 }
3338 }
3339
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003340 // === Backup & restore ===
3341
Makoto Onuki0acbb142016-03-22 17:02:57 -07003342 boolean shouldBackupApp(String packageName, int userId) {
Makoto Onuki905e8852016-03-28 10:40:58 -07003343 return isApplicationFlagSet(packageName, userId, ApplicationInfo.FLAG_ALLOW_BACKUP);
Makoto Onuki0acbb142016-03-22 17:02:57 -07003344 }
3345
Makoto Onuki2e210c42016-03-30 08:30:36 -07003346 boolean shouldBackupApp(PackageInfo pi) {
3347 return (pi.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0;
3348 }
3349
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003350 @Override
Makoto Onuki2e210c42016-03-30 08:30:36 -07003351 public byte[] getBackupPayload(@UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003352 enforceSystem();
3353 if (DEBUG) {
3354 Slog.d(TAG, "Backing up user " + userId);
3355 }
3356 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003357 if (!isUserUnlockedL(userId)) {
3358 wtf("Can't backup: user " + userId + " is locked or not running");
3359 return null;
3360 }
3361
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003362 final ShortcutUser user = getUserShortcutsLocked(userId);
3363 if (user == null) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003364 wtf("Can't backup: user not found: id=" + userId);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003365 return null;
3366 }
3367
Makoto Onukic8c33292016-09-12 16:36:59 -07003368 // Update the signatures for all packages.
3369 user.forAllPackageItems(spi -> spi.refreshPackageSignatureAndSave());
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003370
Makoto Onukic8c33292016-09-12 16:36:59 -07003371 // Set the version code for the launchers.
3372 // We shouldn't do this for publisher packages, because we don't want to update the
3373 // version code without rescanning the manifest.
3374 user.forAllLaunchers(launcher -> launcher.ensureVersionInfo());
3375
3376 // Save to the filesystem.
3377 scheduleSaveUser(userId);
3378 saveDirtyInfo();
3379
Makoto Onuki475c3652017-05-08 14:29:03 -07003380 // Note, in case of backup, we don't have to wait on bitmap saving, because we don't
3381 // back up bitmaps anyway.
3382
Makoto Onukic8c33292016-09-12 16:36:59 -07003383 // Then create the backup payload.
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003384 final ByteArrayOutputStream os = new ByteArrayOutputStream(32 * 1024);
3385 try {
3386 saveUserInternalLocked(userId, os, /* forBackup */ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07003387 } catch (XmlPullParserException | IOException e) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003388 // Shouldn't happen.
3389 Slog.w(TAG, "Backup failed.", e);
3390 return null;
3391 }
3392 return os.toByteArray();
3393 }
3394 }
3395
3396 @Override
Makoto Onuki2e210c42016-03-30 08:30:36 -07003397 public void applyRestore(byte[] payload, @UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003398 enforceSystem();
3399 if (DEBUG) {
3400 Slog.d(TAG, "Restoring user " + userId);
3401 }
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003402 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003403 if (!isUserUnlockedL(userId)) {
3404 wtf("Can't restore: user " + userId + " is locked or not running");
3405 return;
3406 }
Makoto Onuki50a320e2017-05-31 14:38:42 -07003407
3408 // Note we print the file timestamps in dumpsys too, but also printing the timestamp
3409 // in the files anyway.
3410 mShortcutDumpFiles.save("restore-0-start.txt", pw -> {
3411 pw.print("Start time: ");
3412 dumpCurrentTime(pw);
3413 pw.println();
3414 });
3415 mShortcutDumpFiles.save("restore-1-payload.xml", payload);
3416
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003417 // Actually do restore.
3418 final ShortcutUser restored;
Makoto Onuki02f338e2016-07-29 09:40:40 -07003419 final ByteArrayInputStream is = new ByteArrayInputStream(payload);
3420 try {
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003421 restored = loadUserInternal(userId, is, /* fromBackup */ true);
3422 } catch (XmlPullParserException | IOException | InvalidFileFormatException e) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003423 Slog.w(TAG, "Restoration failed.", e);
3424 return;
3425 }
Makoto Onuki50a320e2017-05-31 14:38:42 -07003426 mShortcutDumpFiles.save("restore-2.txt", this::dumpInner);
3427
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003428 getUserShortcutsLocked(userId).mergeRestoredFile(restored);
Makoto Onuki2e210c42016-03-30 08:30:36 -07003429
Makoto Onuki50a320e2017-05-31 14:38:42 -07003430 mShortcutDumpFiles.save("restore-3.txt", this::dumpInner);
3431
Makoto Onuki377b7972016-08-09 14:43:55 -07003432 // Rescan all packages to re-publish manifest shortcuts and do other checks.
3433 rescanUpdatedPackagesLocked(userId,
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003434 0 // lastScanTime = 0; rescan all packages.
3435 );
Makoto Onuki2e210c42016-03-30 08:30:36 -07003436
Makoto Onuki50a320e2017-05-31 14:38:42 -07003437 mShortcutDumpFiles.save("restore-4.txt", this::dumpInner);
3438
3439 mShortcutDumpFiles.save("restore-5-finish.txt", pw -> {
3440 pw.print("Finish time: ");
3441 dumpCurrentTime(pw);
3442 pw.println();
3443 });
3444
Makoto Onuki2e210c42016-03-30 08:30:36 -07003445 saveUserLocked(userId);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003446 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07003447 }
3448
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003449 // === Dump ===
3450
3451 @Override
3452 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06003453 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
Makoto Onukic4361e32017-04-03 11:24:25 -07003454 dumpNoCheck(fd, pw, args);
3455 }
3456
3457 @VisibleForTesting
3458 void dumpNoCheck(FileDescriptor fd, PrintWriter pw, String[] args) {
Makoto Onuki20b82212017-10-04 15:03:50 -07003459 final DumpFilter filter = parseDumpArgs(args);
Makoto Onuki50a320e2017-05-31 14:38:42 -07003460
Makoto Onuki20b82212017-10-04 15:03:50 -07003461 if (filter.shouldDumpCheckIn()) {
Makoto Onuki50a320e2017-05-31 14:38:42 -07003462 // Other flags are not supported for checkin.
Makoto Onuki20b82212017-10-04 15:03:50 -07003463 dumpCheckin(pw, filter.shouldCheckInClear());
Makoto Onuki76269922016-07-15 14:58:54 -07003464 } else {
Makoto Onuki20b82212017-10-04 15:03:50 -07003465 if (filter.shouldDumpMain()) {
3466 dumpInner(pw, filter);
Makoto Onuki50a320e2017-05-31 14:38:42 -07003467 pw.println();
3468 }
Makoto Onuki20b82212017-10-04 15:03:50 -07003469 if (filter.shouldDumpUid()) {
Makoto Onuki50a320e2017-05-31 14:38:42 -07003470 dumpUid(pw);
3471 pw.println();
3472 }
Makoto Onuki20b82212017-10-04 15:03:50 -07003473 if (filter.shouldDumpFiles()) {
Makoto Onuki50a320e2017-05-31 14:38:42 -07003474 dumpDumpFiles(pw);
3475 pw.println();
3476 }
Makoto Onuki76269922016-07-15 14:58:54 -07003477 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003478 }
3479
Makoto Onuki20b82212017-10-04 15:03:50 -07003480 private static DumpFilter parseDumpArgs(String[] args) {
3481 final DumpFilter filter = new DumpFilter();
3482 if (args == null) {
3483 return filter;
3484 }
Makoto Onuki55046222016-03-08 10:49:47 -08003485
Makoto Onuki20b82212017-10-04 15:03:50 -07003486 int argIndex = 0;
3487 while (argIndex < args.length) {
3488 final String arg = args[argIndex++];
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003489
Makoto Onuki20b82212017-10-04 15:03:50 -07003490 if ("-c".equals(arg)) {
3491 filter.setDumpCheckIn(true);
3492 continue;
3493 }
3494 if ("--checkin".equals(arg)) {
3495 filter.setDumpCheckIn(true);
3496 filter.setCheckInClear(true);
3497 continue;
3498 }
3499 if ("-a".equals(arg) || "--all".equals(arg)) {
3500 filter.setDumpUid(true);
3501 filter.setDumpFiles(true);
3502 continue;
3503 }
3504 if ("-u".equals(arg) || "--uid".equals(arg)) {
3505 filter.setDumpUid(true);
3506 continue;
3507 }
3508 if ("-f".equals(arg) || "--files".equals(arg)) {
3509 filter.setDumpFiles(true);
3510 continue;
3511 }
3512 if ("-n".equals(arg) || "--no-main".equals(arg)) {
3513 filter.setDumpMain(false);
3514 continue;
3515 }
3516 if ("--user".equals(arg)) {
3517 if (argIndex >= args.length) {
3518 throw new IllegalArgumentException("Missing user ID for --user");
3519 }
3520 try {
3521 filter.addUser(Integer.parseInt(args[argIndex++]));
3522 } catch (NumberFormatException e) {
3523 throw new IllegalArgumentException("Invalid user ID", e);
3524 }
3525 continue;
3526 }
3527 if ("-p".equals(arg) || "--package".equals(arg)) {
3528 if (argIndex >= args.length) {
3529 throw new IllegalArgumentException("Missing package name for --package");
3530 }
3531 filter.addPackageRegex(args[argIndex++]);
3532 filter.setDumpDetails(false);
3533 continue;
3534 }
3535 if (arg.startsWith("-")) {
3536 throw new IllegalArgumentException("Unknown option " + arg);
3537 }
3538 break;
3539 }
3540 while (argIndex < args.length) {
3541 filter.addPackage(args[argIndex++]);
3542 }
3543 return filter;
3544 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003545
Makoto Onuki20b82212017-10-04 15:03:50 -07003546 static class DumpFilter {
3547 private boolean mDumpCheckIn = false;
3548 private boolean mCheckInClear = false;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003549
Makoto Onuki20b82212017-10-04 15:03:50 -07003550 private boolean mDumpMain = true;
3551 private boolean mDumpUid = false;
3552 private boolean mDumpFiles = false;
Makoto Onuki55046222016-03-08 10:49:47 -08003553
Makoto Onuki20b82212017-10-04 15:03:50 -07003554 private boolean mDumpDetails = true;
3555 private List<Pattern> mPackagePatterns = new ArrayList<>();
3556 private List<Integer> mUsers = new ArrayList<>();
3557
3558 void addPackageRegex(String regex) {
3559 mPackagePatterns.add(Pattern.compile(regex));
3560 }
3561
3562 public void addPackage(String packageName) {
3563 addPackageRegex(Pattern.quote(packageName));
3564 }
3565
3566 void addUser(int userId) {
3567 mUsers.add(userId);
3568 }
3569
3570 boolean isPackageMatch(String packageName) {
3571 if (mPackagePatterns.size() == 0) {
3572 return true;
3573 }
3574 for (int i = 0; i < mPackagePatterns.size(); i++) {
3575 if (mPackagePatterns.get(i).matcher(packageName).find()) {
3576 return true;
Makoto Onuki085a05c2016-08-19 11:39:29 -07003577 }
Makoto Onuki2e210c42016-03-30 08:30:36 -07003578 }
Makoto Onuki20b82212017-10-04 15:03:50 -07003579 return false;
3580 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003581
Makoto Onuki20b82212017-10-04 15:03:50 -07003582 boolean isUserMatch(int userId) {
3583 if (mUsers.size() == 0) {
3584 return true;
3585 }
3586 for (int i = 0; i < mUsers.size(); i++) {
3587 if (mUsers.get(i) == userId) {
3588 return true;
3589 }
3590 }
3591 return false;
3592 }
Makoto Onukia2241832016-07-06 13:28:37 -07003593
Makoto Onuki20b82212017-10-04 15:03:50 -07003594 public boolean shouldDumpCheckIn() {
3595 return mDumpCheckIn;
3596 }
3597
3598 public void setDumpCheckIn(boolean dumpCheckIn) {
3599 mDumpCheckIn = dumpCheckIn;
3600 }
3601
3602 public boolean shouldCheckInClear() {
3603 return mCheckInClear;
3604 }
3605
3606 public void setCheckInClear(boolean checkInClear) {
3607 mCheckInClear = checkInClear;
3608 }
3609
3610 public boolean shouldDumpMain() {
3611 return mDumpMain;
3612 }
3613
3614 public void setDumpMain(boolean dumpMain) {
3615 mDumpMain = dumpMain;
3616 }
3617
3618 public boolean shouldDumpUid() {
3619 return mDumpUid;
3620 }
3621
3622 public void setDumpUid(boolean dumpUid) {
3623 mDumpUid = dumpUid;
3624 }
3625
3626 public boolean shouldDumpFiles() {
3627 return mDumpFiles;
3628 }
3629
3630 public void setDumpFiles(boolean dumpFiles) {
3631 mDumpFiles = dumpFiles;
3632 }
3633
3634 public boolean shouldDumpDetails() {
3635 return mDumpDetails;
3636 }
3637
3638 public void setDumpDetails(boolean dumpDetails) {
3639 mDumpDetails = dumpDetails;
3640 }
3641 }
3642
3643 private void dumpInner(PrintWriter pw) {
3644 dumpInner(pw, new DumpFilter());
3645 }
3646
3647 private void dumpInner(PrintWriter pw, DumpFilter filter) {
3648 synchronized (mLock) {
3649 if (filter.shouldDumpDetails()) {
3650 final long now = injectCurrentTimeMillis();
3651 pw.print("Now: [");
3652 pw.print(now);
3653 pw.print("] ");
3654 pw.print(formatTime(now));
3655
3656 pw.print(" Raw last reset: [");
3657 pw.print(mRawLastResetTime);
3658 pw.print("] ");
3659 pw.print(formatTime(mRawLastResetTime));
3660
3661 final long last = getLastResetTimeLocked();
3662 pw.print(" Last reset: [");
3663 pw.print(last);
3664 pw.print("] ");
3665 pw.print(formatTime(last));
3666
3667 final long next = getNextResetTimeLocked();
3668 pw.print(" Next reset: [");
3669 pw.print(next);
3670 pw.print("] ");
3671 pw.print(formatTime(next));
3672
3673 pw.print(" Config:");
3674 pw.print(" Max icon dim: ");
3675 pw.println(mMaxIconDimension);
3676 pw.print(" Icon format: ");
3677 pw.println(mIconPersistFormat);
3678 pw.print(" Icon quality: ");
3679 pw.println(mIconPersistQuality);
3680 pw.print(" saveDelayMillis: ");
3681 pw.println(mSaveDelayMillis);
3682 pw.print(" resetInterval: ");
3683 pw.println(mResetInterval);
3684 pw.print(" maxUpdatesPerInterval: ");
3685 pw.println(mMaxUpdatesPerInterval);
3686 pw.print(" maxShortcutsPerActivity: ");
3687 pw.println(mMaxShortcuts);
3688 pw.println();
3689
3690 pw.println(" Stats:");
3691 synchronized (mStatLock) {
3692 for (int i = 0; i < Stats.COUNT; i++) {
3693 dumpStatLS(pw, " ", i);
3694 }
3695 }
3696
3697 pw.println();
3698 pw.print(" #Failures: ");
3699 pw.println(mWtfCount);
3700
3701 if (mLastWtfStacktrace != null) {
3702 pw.print(" Last failure stack trace: ");
3703 pw.println(Log.getStackTraceString(mLastWtfStacktrace));
3704 }
3705
3706 pw.println();
3707 mShortcutBitmapSaver.dumpLocked(pw, " ");
3708
3709 pw.println();
Makoto Onukia2241832016-07-06 13:28:37 -07003710 }
3711
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08003712 for (int i = 0; i < mUsers.size(); i++) {
Makoto Onuki20b82212017-10-04 15:03:50 -07003713 final ShortcutUser user = mUsers.valueAt(i);
3714 if (filter.isUserMatch(user.getUserId())) {
3715 user.dump(pw, " ", filter);
3716 pw.println();
3717 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003718 }
Makoto Onuki50a320e2017-05-31 14:38:42 -07003719 }
3720 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003721
Makoto Onuki50a320e2017-05-31 14:38:42 -07003722 private void dumpUid(PrintWriter pw) {
3723 synchronized (mLock) {
3724 pw.println("** SHORTCUT MANAGER UID STATES (dumpsys shortcut -n -u)");
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003725
3726 for (int i = 0; i < mUidState.size(); i++) {
3727 final int uid = mUidState.keyAt(i);
3728 final int state = mUidState.valueAt(i);
3729 pw.print(" UID=");
3730 pw.print(uid);
3731 pw.print(" state=");
3732 pw.print(state);
3733 if (isProcessStateForeground(state)) {
3734 pw.print(" [FG]");
3735 }
3736 pw.print(" last FG=");
3737 pw.print(mUidLastForegroundElapsedTime.get(uid));
3738 pw.println();
3739 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003740 }
3741 }
3742
Makoto Onuki41066a62016-03-09 16:18:44 -08003743 static String formatTime(long time) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003744 Time tobj = new Time();
3745 tobj.set(time);
3746 return tobj.format("%Y-%m-%d %H:%M:%S");
3747 }
3748
Makoto Onuki50a320e2017-05-31 14:38:42 -07003749 private void dumpCurrentTime(PrintWriter pw) {
3750 pw.print(formatTime(injectCurrentTimeMillis()));
3751 }
3752
Makoto Onuki085a05c2016-08-19 11:39:29 -07003753 private void dumpStatLS(PrintWriter pw, String prefix, int statId) {
Makoto Onuki2e210c42016-03-30 08:30:36 -07003754 pw.print(prefix);
3755 final int count = mCountStats[statId];
3756 final long dur = mDurationStats[statId];
3757 pw.println(String.format("%s: count=%d, total=%dms, avg=%.1fms",
Makoto Onuki085a05c2016-08-19 11:39:29 -07003758 STAT_LABELS[statId], count, dur,
Makoto Onuki2e210c42016-03-30 08:30:36 -07003759 (count == 0 ? 0 : ((double) dur) / count)));
3760 }
3761
Makoto Onuki76269922016-07-15 14:58:54 -07003762 /**
3763 * Dumpsys for checkin.
3764 *
3765 * @param clear if true, clear the history information. Some other system services have this
3766 * behavior but shortcut service doesn't for now.
3767 */
3768 private void dumpCheckin(PrintWriter pw, boolean clear) {
3769 synchronized (mLock) {
3770 try {
3771 final JSONArray users = new JSONArray();
3772
3773 for (int i = 0; i < mUsers.size(); i++) {
3774 users.put(mUsers.valueAt(i).dumpCheckin(clear));
3775 }
3776
3777 final JSONObject result = new JSONObject();
3778
3779 result.put(KEY_SHORTCUT, users);
3780 result.put(KEY_LOW_RAM, injectIsLowRamDevice());
3781 result.put(KEY_ICON_SIZE, mMaxIconDimension);
3782
3783 pw.println(result.toString(1));
3784 } catch (JSONException e) {
3785 Slog.e(TAG, "Unable to write in json", e);
3786 }
3787 }
3788 }
3789
Makoto Onuki50a320e2017-05-31 14:38:42 -07003790 private void dumpDumpFiles(PrintWriter pw) {
3791 synchronized (mLock) {
3792 pw.println("** SHORTCUT MANAGER FILES (dumpsys shortcut -n -f)");
3793 mShortcutDumpFiles.dumpAll(pw);
3794 }
3795 }
3796
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003797 // === Shell support ===
3798
3799 @Override
3800 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003801 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003802
3803 enforceShell();
3804
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07003805 final long token = injectClearCallingIdentity();
3806 try {
Dianne Hackborn354736e2016-08-22 17:00:05 -07003807 final int status = (new MyShellCommand()).exec(this, in, out, err, args, callback,
3808 resultReceiver);
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07003809 resultReceiver.send(status, null);
3810 } finally {
3811 injectRestoreCallingIdentity(token);
3812 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003813 }
3814
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003815 static class CommandException extends Exception {
3816 public CommandException(String message) {
3817 super(message);
3818 }
3819 }
3820
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003821 /**
3822 * Handle "adb shell cmd".
3823 */
3824 private class MyShellCommand extends ShellCommand {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003825
3826 private int mUserId = UserHandle.USER_SYSTEM;
3827
Makoto Onuki02f338e2016-07-29 09:40:40 -07003828 private void parseOptionsLocked(boolean takeUser)
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003829 throws CommandException {
3830 String opt;
3831 while ((opt = getNextOption()) != null) {
3832 switch (opt) {
3833 case "--user":
3834 if (takeUser) {
3835 mUserId = UserHandle.parseUserArg(getNextArgRequired());
Makoto Onuki02f338e2016-07-29 09:40:40 -07003836 if (!isUserUnlockedL(mUserId)) {
Makoto Onukif34c3082016-07-13 10:25:25 -07003837 throw new CommandException(
3838 "User " + mUserId + " is not running or locked");
3839 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003840 break;
3841 }
3842 // fallthrough
3843 default:
3844 throw new CommandException("Unknown option: " + opt);
3845 }
3846 }
3847 }
3848
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003849 @Override
3850 public int onCommand(String cmd) {
3851 if (cmd == null) {
3852 return handleDefaultCommands(cmd);
3853 }
3854 final PrintWriter pw = getOutPrintWriter();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003855 try {
3856 switch (cmd) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003857 case "reset-throttling":
3858 handleResetThrottling();
3859 break;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003860 case "reset-all-throttling":
3861 handleResetAllThrottling();
3862 break;
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003863 case "override-config":
3864 handleOverrideConfig();
3865 break;
3866 case "reset-config":
3867 handleResetConfig();
3868 break;
3869 case "clear-default-launcher":
3870 handleClearDefaultLauncher();
3871 break;
3872 case "get-default-launcher":
3873 handleGetDefaultLauncher();
3874 break;
Makoto Onukiac214972016-04-04 10:19:45 -07003875 case "unload-user":
3876 handleUnloadUser();
3877 break;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003878 case "clear-shortcuts":
3879 handleClearShortcuts();
3880 break;
Makoto Onukib08790c2016-06-23 14:05:46 -07003881 case "verify-states": // hidden command to verify various internal states.
3882 handleVerifyStates();
3883 break;
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003884 default:
3885 return handleDefaultCommands(cmd);
3886 }
3887 } catch (CommandException e) {
3888 pw.println("Error: " + e.getMessage());
3889 return 1;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003890 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003891 pw.println("Success");
3892 return 0;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003893 }
3894
3895 @Override
3896 public void onHelp() {
3897 final PrintWriter pw = getOutPrintWriter();
3898 pw.println("Usage: cmd shortcut COMMAND [options ...]");
3899 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003900 pw.println("cmd shortcut reset-throttling [--user USER_ID]");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003901 pw.println(" Reset throttling for all packages and users");
3902 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003903 pw.println("cmd shortcut reset-all-throttling");
3904 pw.println(" Reset the throttling state for all users");
3905 pw.println();
Makoto Onuki4362a662016-03-08 18:59:09 -08003906 pw.println("cmd shortcut override-config CONFIG");
3907 pw.println(" Override the configuration for testing (will last until reboot)");
3908 pw.println();
3909 pw.println("cmd shortcut reset-config");
3910 pw.println(" Reset the configuration set with \"update-config\"");
3911 pw.println();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003912 pw.println("cmd shortcut clear-default-launcher [--user USER_ID]");
3913 pw.println(" Clear the cached default launcher");
3914 pw.println();
3915 pw.println("cmd shortcut get-default-launcher [--user USER_ID]");
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07003916 pw.println(" Show the default launcher");
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003917 pw.println();
Makoto Onukiac214972016-04-04 10:19:45 -07003918 pw.println("cmd shortcut unload-user [--user USER_ID]");
3919 pw.println(" Unload a user from the memory");
3920 pw.println(" (This should not affect any observable behavior)");
3921 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003922 pw.println("cmd shortcut clear-shortcuts [--user USER_ID] PACKAGE");
3923 pw.println(" Remove all shortcuts from a package, including pinned shortcuts");
3924 pw.println();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003925 }
3926
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003927 private void handleResetThrottling() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003928 synchronized (mLock) {
3929 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki4554d0e2016-03-14 15:51:41 -07003930
Makoto Onuki02f338e2016-07-29 09:40:40 -07003931 Slog.i(TAG, "cmd: handleResetThrottling: user=" + mUserId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003932
Makoto Onuki02f338e2016-07-29 09:40:40 -07003933 resetThrottlingInner(mUserId);
3934 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003935 }
3936
3937 private void handleResetAllThrottling() {
3938 Slog.i(TAG, "cmd: handleResetAllThrottling");
3939
3940 resetAllThrottlingInner();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003941 }
3942
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003943 private void handleOverrideConfig() throws CommandException {
Makoto Onuki4362a662016-03-08 18:59:09 -08003944 final String config = getNextArgRequired();
3945
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003946 Slog.i(TAG, "cmd: handleOverrideConfig: " + config);
3947
Makoto Onuki4362a662016-03-08 18:59:09 -08003948 synchronized (mLock) {
3949 if (!updateConfigurationLocked(config)) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003950 throw new CommandException("override-config failed. See logcat for details.");
Makoto Onuki4362a662016-03-08 18:59:09 -08003951 }
3952 }
Makoto Onuki4362a662016-03-08 18:59:09 -08003953 }
3954
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003955 private void handleResetConfig() {
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003956 Slog.i(TAG, "cmd: handleResetConfig");
3957
Makoto Onuki4362a662016-03-08 18:59:09 -08003958 synchronized (mLock) {
3959 loadConfigurationLocked();
3960 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003961 }
3962
3963 private void clearLauncher() {
3964 synchronized (mLock) {
Makoto Onuki10305202016-07-14 18:14:08 -07003965 getUserShortcutsLocked(mUserId).forceClearLauncher();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003966 }
3967 }
3968
3969 private void showLauncher() {
3970 synchronized (mLock) {
3971 // This ensures to set the cached launcher. Package name doesn't matter.
3972 hasShortcutHostPermissionInner("-", mUserId);
3973
3974 getOutPrintWriter().println("Launcher: "
Makoto Onuki10305202016-07-14 18:14:08 -07003975 + getUserShortcutsLocked(mUserId).getLastKnownLauncher());
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003976 }
3977 }
3978
3979 private void handleClearDefaultLauncher() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003980 synchronized (mLock) {
3981 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003982
Makoto Onuki02f338e2016-07-29 09:40:40 -07003983 clearLauncher();
3984 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003985 }
3986
3987 private void handleGetDefaultLauncher() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003988 synchronized (mLock) {
3989 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003990
Makoto Onuki02f338e2016-07-29 09:40:40 -07003991 clearLauncher();
3992 showLauncher();
3993 }
Makoto Onuki4362a662016-03-08 18:59:09 -08003994 }
Makoto Onukiac214972016-04-04 10:19:45 -07003995
3996 private void handleUnloadUser() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003997 synchronized (mLock) {
3998 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onukiac214972016-04-04 10:19:45 -07003999
Makoto Onuki02f338e2016-07-29 09:40:40 -07004000 Slog.i(TAG, "cmd: handleUnloadUser: user=" + mUserId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004001
Makoto Onuki01ce92b2017-04-28 12:24:16 -07004002 ShortcutService.this.handleStopUser(mUserId);
Makoto Onuki02f338e2016-07-29 09:40:40 -07004003 }
Makoto Onukiac214972016-04-04 10:19:45 -07004004 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004005
4006 private void handleClearShortcuts() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07004007 synchronized (mLock) {
4008 parseOptionsLocked(/* takeUser =*/ true);
4009 final String packageName = getNextArgRequired();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004010
Makoto Onuki02f338e2016-07-29 09:40:40 -07004011 Slog.i(TAG, "cmd: handleClearShortcuts: user" + mUserId + ", " + packageName);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004012
Makoto Onuki02f338e2016-07-29 09:40:40 -07004013 ShortcutService.this.cleanUpPackageForAllLoadedUsers(packageName, mUserId,
4014 /* appStillExists = */ true);
4015 }
Makoto Onukib08790c2016-06-23 14:05:46 -07004016 }
4017
4018 private void handleVerifyStates() throws CommandException {
4019 try {
4020 verifyStatesForce(); // This will throw when there's an issue.
4021 } catch (Throwable th) {
4022 throw new CommandException(th.getMessage() + "\n" + Log.getStackTraceString(th));
4023 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004024 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004025 }
4026
4027 // === Unit test support ===
4028
4029 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07004030 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004031 long injectCurrentTimeMillis() {
4032 return System.currentTimeMillis();
4033 }
4034
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07004035 @VisibleForTesting
4036 long injectElapsedRealtime() {
4037 return SystemClock.elapsedRealtime();
4038 }
4039
Makoto Onuki475c3652017-05-08 14:29:03 -07004040 @VisibleForTesting
4041 long injectUptimeMillis() {
4042 return SystemClock.uptimeMillis();
4043 }
4044
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004045 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07004046 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004047 int injectBinderCallingUid() {
4048 return getCallingUid();
4049 }
4050
Makoto Onuki31459242016-03-22 11:12:18 -07004051 private int getCallingUserId() {
Makoto Onuki4554d0e2016-03-14 15:51:41 -07004052 return UserHandle.getUserId(injectBinderCallingUid());
4053 }
4054
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07004055 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07004056 @VisibleForTesting
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07004057 long injectClearCallingIdentity() {
4058 return Binder.clearCallingIdentity();
4059 }
4060
4061 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07004062 @VisibleForTesting
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07004063 void injectRestoreCallingIdentity(long token) {
4064 Binder.restoreCallingIdentity(token);
4065 }
4066
Makoto Onuki33663282016-08-22 16:19:04 -07004067 // Injection point.
4068 @VisibleForTesting
4069 String injectBuildFingerprint() {
4070 return Build.FINGERPRINT;
4071 }
4072
Makoto Onukide667372016-03-15 14:29:20 -07004073 final void wtf(String message) {
Makoto Onukib08790c2016-06-23 14:05:46 -07004074 wtf(message, /* exception= */ null);
Makoto Onukide667372016-03-15 14:29:20 -07004075 }
4076
Makoto Onuki2e210c42016-03-30 08:30:36 -07004077 // Injection point.
Makoto Onukia2241832016-07-06 13:28:37 -07004078 void wtf(String message, Throwable e) {
4079 if (e == null) {
4080 e = new RuntimeException("Stacktrace");
4081 }
4082 synchronized (mLock) {
4083 mWtfCount++;
4084 mLastWtfStacktrace = new Exception("Last failure was logged here:");
4085 }
Makoto Onukide667372016-03-15 14:29:20 -07004086 Slog.wtf(TAG, message, e);
4087 }
4088
Makoto Onuki31459242016-03-22 11:12:18 -07004089 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004090 File injectSystemDataPath() {
4091 return Environment.getDataSystemDirectory();
4092 }
4093
Makoto Onuki31459242016-03-22 11:12:18 -07004094 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004095 File injectUserDataPath(@UserIdInt int userId) {
Makoto Onuki55046222016-03-08 10:49:47 -08004096 return new File(Environment.getDataSystemCeDirectory(userId), DIRECTORY_PER_USER);
4097 }
4098
Makoto Onuki50a320e2017-05-31 14:38:42 -07004099 public File getDumpPath() {
4100 return new File(injectUserDataPath(UserHandle.USER_SYSTEM), DIRECTORY_DUMP);
4101 }
4102
Makoto Onuki4362a662016-03-08 18:59:09 -08004103 @VisibleForTesting
Makoto Onuki55046222016-03-08 10:49:47 -08004104 boolean injectIsLowRamDevice() {
4105 return ActivityManager.isLowRamDeviceStatic();
4106 }
4107
Makoto Onuki31459242016-03-22 11:12:18 -07004108 @VisibleForTesting
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07004109 void injectRegisterUidObserver(IUidObserver observer, int which) {
4110 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004111 ActivityManager.getService().registerUidObserver(observer, which,
Dianne Hackborn5614bf52016-11-07 17:26:41 -08004112 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07004113 } catch (RemoteException shouldntHappen) {
4114 }
4115 }
4116
Makoto Onuki55046222016-03-08 10:49:47 -08004117 File getUserBitmapFilePath(@UserIdInt int userId) {
4118 return new File(injectUserDataPath(userId), DIRECTORY_BITMAPS);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004119 }
4120
4121 @VisibleForTesting
Makoto Onuki31459242016-03-22 11:12:18 -07004122 SparseArray<ShortcutUser> getShortcutsForTest() {
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08004123 return mUsers;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004124 }
4125
4126 @VisibleForTesting
Makoto Onukib5a012f2016-06-21 11:13:53 -07004127 int getMaxShortcutsForTest() {
4128 return mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004129 }
4130
4131 @VisibleForTesting
Makoto Onukib6d35232016-04-04 15:57:17 -07004132 int getMaxUpdatesPerIntervalForTest() {
4133 return mMaxUpdatesPerInterval;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004134 }
4135
4136 @VisibleForTesting
Makoto Onuki4362a662016-03-08 18:59:09 -08004137 long getResetIntervalForTest() {
4138 return mResetInterval;
Makoto Onuki55046222016-03-08 10:49:47 -08004139 }
4140
4141 @VisibleForTesting
Makoto Onuki4362a662016-03-08 18:59:09 -08004142 int getMaxIconDimensionForTest() {
4143 return mMaxIconDimension;
4144 }
4145
4146 @VisibleForTesting
4147 CompressFormat getIconPersistFormatForTest() {
4148 return mIconPersistFormat;
4149 }
4150
4151 @VisibleForTesting
4152 int getIconPersistQualityForTest() {
4153 return mIconPersistQuality;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004154 }
Makoto Onuki41066a62016-03-09 16:18:44 -08004155
4156 @VisibleForTesting
Makoto Onuki22fcc682016-05-17 14:52:19 -07004157 ShortcutPackage getPackageShortcutForTest(String packageName, int userId) {
Makoto Onuki41066a62016-03-09 16:18:44 -08004158 synchronized (mLock) {
Makoto Onuki31459242016-03-22 11:12:18 -07004159 final ShortcutUser user = mUsers.get(userId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07004160 if (user == null) return null;
4161
Makoto Onuki22fcc682016-05-17 14:52:19 -07004162 return user.getAllPackagesForTest().get(packageName);
4163 }
4164 }
4165
4166 @VisibleForTesting
4167 ShortcutInfo getPackageShortcutForTest(String packageName, String shortcutId, int userId) {
4168 synchronized (mLock) {
Makoto Onukif34c3082016-07-13 10:25:25 -07004169 final ShortcutPackage pkg = getPackageShortcutForTest(packageName, userId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07004170 if (pkg == null) return null;
4171
4172 return pkg.findShortcutById(shortcutId);
Makoto Onuki41066a62016-03-09 16:18:44 -08004173 }
4174 }
Makoto Onuki7001a612016-05-27 13:24:28 -07004175
Makoto Onukifac592f2016-11-21 13:41:32 -08004176 @VisibleForTesting
4177 ShortcutLauncher getLauncherShortcutForTest(String packageName, int userId) {
4178 synchronized (mLock) {
4179 final ShortcutUser user = mUsers.get(userId);
4180 if (user == null) return null;
4181
4182 return user.getAllLaunchersForTest().get(PackageWithUser.of(userId, packageName));
4183 }
4184 }
4185
Makoto Onuki2d895c32016-12-02 15:48:40 -08004186 @VisibleForTesting
4187 ShortcutRequestPinProcessor getShortcutRequestPinProcessorForTest() {
4188 return mShortcutRequestPinProcessor;
4189 }
4190
Makoto Onuki7001a612016-05-27 13:24:28 -07004191 /**
4192 * Control whether {@link #verifyStates} should be performed. We always perform it during unit
4193 * tests.
4194 */
4195 @VisibleForTesting
4196 boolean injectShouldPerformVerification() {
4197 return DEBUG;
4198 }
4199
4200 /**
4201 * Check various internal states and throws if there's any inconsistency.
4202 * This is normally only enabled during unit tests.
4203 */
4204 final void verifyStates() {
4205 if (injectShouldPerformVerification()) {
4206 verifyStatesInner();
4207 }
4208 }
4209
Makoto Onukib08790c2016-06-23 14:05:46 -07004210 private final void verifyStatesForce() {
4211 verifyStatesInner();
4212 }
4213
Makoto Onuki7001a612016-05-27 13:24:28 -07004214 private void verifyStatesInner() {
Makoto Onuki10305202016-07-14 18:14:08 -07004215 synchronized (mLock) {
Makoto Onuki7001a612016-05-27 13:24:28 -07004216 forEachLoadedUserLocked(u -> u.forAllPackageItems(ShortcutPackageItem::verifyStates));
4217 }
4218 }
Makoto Onuki475c3652017-05-08 14:29:03 -07004219
4220 @VisibleForTesting
4221 void waitForBitmapSavesForTest() {
4222 synchronized (mLock) {
4223 mShortcutBitmapSaver.waitForAllSavesLocked();
4224 }
4225 }
Makoto Onuki41066a62016-03-09 16:18:44 -08004226}