blob: ee2f3742c811eba7ccee721cc6cb8e3352e95e33 [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 Onuki2d5b4652016-03-11 16:09:54 -080043import android.content.pm.PackageManagerInternal;
Todd Kennedy0eb97382017-10-03 16:57:22 -070044import android.content.pm.PackageManager.NameNotFoundException;
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);
Makoto Onukia4f89b12017-10-05 10:37:55 -0700556 if (DEBUG) {
557 Binder.LOG_RUNTIME_EXCEPTION = true;
558 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800559 mService = new ShortcutService(context);
560 }
561
562 @Override
563 public void onStart() {
564 publishBinderService(Context.SHORTCUT_SERVICE, mService);
565 }
566
567 @Override
568 public void onBootPhase(int phase) {
569 mService.onBootPhase(phase);
570 }
571
572 @Override
Makoto Onuki01ce92b2017-04-28 12:24:16 -0700573 public void onStopUser(int userHandle) {
574 mService.handleStopUser(userHandle);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800575 }
576
577 @Override
Makoto Onukif3a572b2016-03-10 12:28:38 -0800578 public void onUnlockUser(int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -0700579 mService.handleUnlockUser(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800580 }
581 }
582
583 /** lifecycle event */
584 void onBootPhase(int phase) {
585 if (DEBUG) {
586 Slog.d(TAG, "onBootPhase: " + phase);
587 }
588 switch (phase) {
589 case SystemService.PHASE_LOCK_SETTINGS_READY:
590 initialize();
591 break;
Makoto Onukic51b2872016-05-04 15:24:50 -0700592 case SystemService.PHASE_BOOT_COMPLETED:
593 mBootCompleted.set(true);
594 break;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800595 }
596 }
597
598 /** lifecycle event */
Makoto Onukicdc78f72016-03-21 15:47:52 -0700599 void handleUnlockUser(int userId) {
Makoto Onuki22fcc682016-05-17 14:52:19 -0700600 if (DEBUG) {
Makoto Onuki085a05c2016-08-19 11:39:29 -0700601 Slog.d(TAG, "handleUnlockUser: user=" + userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700602 }
Makoto Onukicdc78f72016-03-21 15:47:52 -0700603 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -0700604 mUnlockedUsers.put(userId, true);
Makoto Onukicdc78f72016-03-21 15:47:52 -0700605 }
Makoto Onuki085a05c2016-08-19 11:39:29 -0700606
607 // Preload the user data.
608 // Note, we don't use mHandler here but instead just start a new thread.
609 // This is because mHandler (which uses com.android.internal.os.BackgroundThread) is very
610 // busy at this point and this could take hundreds of milliseconds, which would be too
611 // late since the launcher would already have started.
612 // So we just create a new thread. This code runs rarely, so we don't use a thread pool
613 // or anything.
614 final long start = injectElapsedRealtime();
615 injectRunOnNewThread(() -> {
616 synchronized (mLock) {
617 logDurationStat(Stats.ASYNC_PRELOAD_USER_DELAY, start);
618 getUserShortcutsLocked(userId);
619 }
620 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800621 }
622
623 /** lifecycle event */
Makoto Onuki01ce92b2017-04-28 12:24:16 -0700624 void handleStopUser(int userId) {
Makoto Onuki02f338e2016-07-29 09:40:40 -0700625 if (DEBUG) {
Makoto Onuki01ce92b2017-04-28 12:24:16 -0700626 Slog.d(TAG, "handleStopUser: user=" + userId);
Makoto Onuki02f338e2016-07-29 09:40:40 -0700627 }
Makoto Onukicdc78f72016-03-21 15:47:52 -0700628 synchronized (mLock) {
629 unloadUserLocked(userId);
Makoto Onuki02f338e2016-07-29 09:40:40 -0700630
631 mUnlockedUsers.put(userId, false);
Makoto Onukicdc78f72016-03-21 15:47:52 -0700632 }
633 }
634
635 private void unloadUserLocked(int userId) {
636 if (DEBUG) {
637 Slog.d(TAG, "unloadUserLocked: user=" + userId);
638 }
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700639 // Save all dirty information.
640 saveDirtyInfo();
641
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800642 // Unload
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -0800643 mUsers.delete(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800644 }
645
646 /** Return the base state file name */
647 private AtomicFile getBaseStateFile() {
648 final File path = new File(injectSystemDataPath(), FILENAME_BASE_STATE);
649 path.mkdirs();
650 return new AtomicFile(path);
651 }
652
653 /**
654 * Init the instance. (load the state file, etc)
655 */
656 private void initialize() {
657 synchronized (mLock) {
Makoto Onuki4362a662016-03-08 18:59:09 -0800658 loadConfigurationLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800659 loadBaseStateLocked();
660 }
661 }
662
Makoto Onuki4362a662016-03-08 18:59:09 -0800663 /**
664 * Load the configuration from Settings.
665 */
666 private void loadConfigurationLocked() {
667 updateConfigurationLocked(injectShortcutManagerConstants());
668 }
Makoto Onuki55046222016-03-08 10:49:47 -0800669
Makoto Onuki4362a662016-03-08 18:59:09 -0800670 /**
671 * Load the configuration from Settings.
672 */
673 @VisibleForTesting
674 boolean updateConfigurationLocked(String config) {
675 boolean result = true;
676
677 final KeyValueListParser parser = new KeyValueListParser(',');
678 try {
679 parser.setString(config);
680 } catch (IllegalArgumentException e) {
681 // Failed to parse the settings string, log this and move on
682 // with defaults.
683 Slog.e(TAG, "Bad shortcut manager settings", e);
684 result = false;
685 }
686
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700687 mSaveDelayMillis = Math.max(0, (int) parser.getLong(ConfigConstants.KEY_SAVE_DELAY_MILLIS,
688 DEFAULT_SAVE_DELAY_MS));
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700689
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700690 mResetInterval = Math.max(1, parser.getLong(
Makoto Onuki4362a662016-03-08 18:59:09 -0800691 ConfigConstants.KEY_RESET_INTERVAL_SEC, DEFAULT_RESET_INTERVAL_SEC)
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700692 * 1000L);
Makoto Onuki4362a662016-03-08 18:59:09 -0800693
Makoto Onukib6d35232016-04-04 15:57:17 -0700694 mMaxUpdatesPerInterval = Math.max(0, (int) parser.getLong(
695 ConfigConstants.KEY_MAX_UPDATES_PER_INTERVAL, DEFAULT_MAX_UPDATES_PER_INTERVAL));
Makoto Onuki4362a662016-03-08 18:59:09 -0800696
Makoto Onukib5a012f2016-06-21 11:13:53 -0700697 mMaxShortcuts = Math.max(0, (int) parser.getLong(
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700698 ConfigConstants.KEY_MAX_SHORTCUTS, DEFAULT_MAX_SHORTCUTS_PER_APP));
Makoto Onuki4362a662016-03-08 18:59:09 -0800699
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700700 final int iconDimensionDp = Math.max(1, injectIsLowRamDevice()
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_LOWRAM,
703 DEFAULT_MAX_ICON_DIMENSION_LOWRAM_DP)
Makoto Onuki4362a662016-03-08 18:59:09 -0800704 : (int) parser.getLong(
Makoto Onukib08790c2016-06-23 14:05:46 -0700705 ConfigConstants.KEY_MAX_ICON_DIMENSION_DP,
706 DEFAULT_MAX_ICON_DIMENSION_DP));
Makoto Onuki4362a662016-03-08 18:59:09 -0800707
708 mMaxIconDimension = injectDipToPixel(iconDimensionDp);
709
710 mIconPersistFormat = CompressFormat.valueOf(
711 parser.getString(ConfigConstants.KEY_ICON_FORMAT, DEFAULT_ICON_PERSIST_FORMAT));
712
713 mIconPersistQuality = (int) parser.getLong(
714 ConfigConstants.KEY_ICON_QUALITY,
715 DEFAULT_ICON_PERSIST_QUALITY);
716
717 return result;
718 }
719
720 @VisibleForTesting
721 String injectShortcutManagerConstants() {
722 return android.provider.Settings.Global.getString(
723 mContext.getContentResolver(),
724 android.provider.Settings.Global.SHORTCUT_MANAGER_CONSTANTS);
725 }
726
727 @VisibleForTesting
728 int injectDipToPixel(int dip) {
729 return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip,
730 mContext.getResources().getDisplayMetrics());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800731 }
732
Makoto Onuki55046222016-03-08 10:49:47 -0800733 // === Persisting ===
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800734
735 @Nullable
Makoto Onuki41066a62016-03-09 16:18:44 -0800736 static String parseStringAttribute(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800737 return parser.getAttributeValue(null, attribute);
738 }
739
Makoto Onuki0acbb142016-03-22 17:02:57 -0700740 static boolean parseBooleanAttribute(XmlPullParser parser, String attribute) {
741 return parseLongAttribute(parser, attribute) == 1;
742 }
743
Makoto Onukia4f89b12017-10-05 10:37:55 -0700744 static boolean parseBooleanAttribute(XmlPullParser parser, String attribute, boolean def) {
745 return parseLongAttribute(parser, attribute, (def ? 1 : 0)) == 1;
746 }
747
Makoto Onuki41066a62016-03-09 16:18:44 -0800748 static int parseIntAttribute(XmlPullParser parser, String attribute) {
749 return (int) parseLongAttribute(parser, attribute);
750 }
751
Makoto Onukid99c6f02016-03-28 11:02:54 -0700752 static int parseIntAttribute(XmlPullParser parser, String attribute, int def) {
753 return (int) parseLongAttribute(parser, attribute, def);
754 }
755
Makoto Onuki41066a62016-03-09 16:18:44 -0800756 static long parseLongAttribute(XmlPullParser parser, String attribute) {
Makoto Onukid99c6f02016-03-28 11:02:54 -0700757 return parseLongAttribute(parser, attribute, 0);
758 }
759
760 static long parseLongAttribute(XmlPullParser parser, String attribute, long def) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800761 final String value = parseStringAttribute(parser, attribute);
762 if (TextUtils.isEmpty(value)) {
Makoto Onukid99c6f02016-03-28 11:02:54 -0700763 return def;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800764 }
765 try {
766 return Long.parseLong(value);
767 } catch (NumberFormatException e) {
768 Slog.e(TAG, "Error parsing long " + value);
Makoto Onukid99c6f02016-03-28 11:02:54 -0700769 return def;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800770 }
771 }
772
773 @Nullable
Makoto Onuki41066a62016-03-09 16:18:44 -0800774 static ComponentName parseComponentNameAttribute(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800775 final String value = parseStringAttribute(parser, attribute);
776 if (TextUtils.isEmpty(value)) {
777 return null;
778 }
779 return ComponentName.unflattenFromString(value);
780 }
781
782 @Nullable
Makoto Onuki440a1ea2016-07-20 14:21:18 -0700783 static Intent parseIntentAttributeNoDefault(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800784 final String value = parseStringAttribute(parser, attribute);
Makoto Onukib5a012f2016-06-21 11:13:53 -0700785 Intent parsed = null;
786 if (!TextUtils.isEmpty(value)) {
787 try {
788 parsed = Intent.parseUri(value, /* flags =*/ 0);
789 } catch (URISyntaxException e) {
790 Slog.e(TAG, "Error parsing intent", e);
791 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800792 }
Makoto Onuki440a1ea2016-07-20 14:21:18 -0700793 return parsed;
794 }
795
796 @Nullable
797 static Intent parseIntentAttribute(XmlPullParser parser, String attribute) {
798 Intent parsed = parseIntentAttributeNoDefault(parser, attribute);
Makoto Onukib5a012f2016-06-21 11:13:53 -0700799 if (parsed == null) {
800 // Default intent.
801 parsed = new Intent(Intent.ACTION_VIEW);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800802 }
Makoto Onukib5a012f2016-06-21 11:13:53 -0700803 return parsed;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800804 }
805
Makoto Onuki41066a62016-03-09 16:18:44 -0800806 static void writeTagValue(XmlSerializer out, String tag, String value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800807 if (TextUtils.isEmpty(value)) return;
808
809 out.startTag(null, tag);
810 out.attribute(null, ATTR_VALUE, value);
811 out.endTag(null, tag);
812 }
813
Makoto Onuki41066a62016-03-09 16:18:44 -0800814 static void writeTagValue(XmlSerializer out, String tag, long value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800815 writeTagValue(out, tag, Long.toString(value));
816 }
817
Makoto Onuki2d5b4652016-03-11 16:09:54 -0800818 static void writeTagValue(XmlSerializer out, String tag, ComponentName name) throws IOException {
819 if (name == null) return;
820 writeTagValue(out, tag, name.flattenToString());
821 }
822
Makoto Onuki41066a62016-03-09 16:18:44 -0800823 static void writeTagExtra(XmlSerializer out, String tag, PersistableBundle bundle)
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800824 throws IOException, XmlPullParserException {
825 if (bundle == null) return;
826
827 out.startTag(null, tag);
828 bundle.saveToXml(out);
829 out.endTag(null, tag);
830 }
831
Makoto Onuki22fcc682016-05-17 14:52:19 -0700832 static void writeAttr(XmlSerializer out, String name, CharSequence value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800833 if (TextUtils.isEmpty(value)) return;
834
Makoto Onuki22fcc682016-05-17 14:52:19 -0700835 out.attribute(null, name, value.toString());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800836 }
837
Makoto Onuki41066a62016-03-09 16:18:44 -0800838 static void writeAttr(XmlSerializer out, String name, long value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800839 writeAttr(out, name, String.valueOf(value));
840 }
841
Makoto Onuki0acbb142016-03-22 17:02:57 -0700842 static void writeAttr(XmlSerializer out, String name, boolean value) throws IOException {
843 if (value) {
844 writeAttr(out, name, "1");
Makoto Onukia4f89b12017-10-05 10:37:55 -0700845 } else {
846 writeAttr(out, name, "0");
Makoto Onuki0acbb142016-03-22 17:02:57 -0700847 }
848 }
849
Makoto Onuki41066a62016-03-09 16:18:44 -0800850 static void writeAttr(XmlSerializer out, String name, ComponentName comp) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800851 if (comp == null) return;
852 writeAttr(out, name, comp.flattenToString());
853 }
854
Makoto Onuki41066a62016-03-09 16:18:44 -0800855 static void writeAttr(XmlSerializer out, String name, Intent intent) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800856 if (intent == null) return;
857
858 writeAttr(out, name, intent.toUri(/* flags =*/ 0));
859 }
860
861 @VisibleForTesting
862 void saveBaseStateLocked() {
863 final AtomicFile file = getBaseStateFile();
864 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700865 Slog.d(TAG, "Saving to " + file.getBaseFile());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800866 }
867
868 FileOutputStream outs = null;
869 try {
870 outs = file.startWrite();
871
872 // Write to XML
873 XmlSerializer out = new FastXmlSerializer();
874 out.setOutput(outs, StandardCharsets.UTF_8.name());
875 out.startDocument(null, true);
876 out.startTag(null, TAG_ROOT);
877
878 // Body.
879 writeTagValue(out, TAG_LAST_RESET_TIME, mRawLastResetTime);
880
881 // Epilogue.
882 out.endTag(null, TAG_ROOT);
883 out.endDocument();
884
885 // Close.
886 file.finishWrite(outs);
887 } catch (IOException e) {
888 Slog.e(TAG, "Failed to write to file " + file.getBaseFile(), e);
889 file.failWrite(outs);
890 }
891 }
892
893 private void loadBaseStateLocked() {
894 mRawLastResetTime = 0;
895
896 final AtomicFile file = getBaseStateFile();
897 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700898 Slog.d(TAG, "Loading from " + file.getBaseFile());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800899 }
900 try (FileInputStream in = file.openRead()) {
901 XmlPullParser parser = Xml.newPullParser();
902 parser.setInput(in, StandardCharsets.UTF_8.name());
903
904 int type;
905 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
906 if (type != XmlPullParser.START_TAG) {
907 continue;
908 }
909 final int depth = parser.getDepth();
910 // Check the root tag
911 final String tag = parser.getName();
912 if (depth == 1) {
913 if (!TAG_ROOT.equals(tag)) {
914 Slog.e(TAG, "Invalid root tag: " + tag);
915 return;
916 }
917 continue;
918 }
919 // Assume depth == 2
920 switch (tag) {
921 case TAG_LAST_RESET_TIME:
922 mRawLastResetTime = parseLongAttribute(parser, ATTR_VALUE);
923 break;
924 default:
925 Slog.e(TAG, "Invalid tag: " + tag);
926 break;
927 }
928 }
929 } catch (FileNotFoundException e) {
930 // Use the default
Makoto Onukib08790c2016-06-23 14:05:46 -0700931 } catch (IOException | XmlPullParserException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800932 Slog.e(TAG, "Failed to read file " + file.getBaseFile(), e);
933
934 mRawLastResetTime = 0;
935 }
936 // Adjust the last reset time.
937 getLastResetTimeLocked();
938 }
939
Makoto Onuki0eed4412016-07-21 11:21:59 -0700940 @VisibleForTesting
941 final File getUserFile(@UserIdInt int userId) {
942 return new File(injectUserDataPath(userId), FILENAME_USER_PACKAGES);
943 }
944
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800945 private void saveUserLocked(@UserIdInt int userId) {
Makoto Onuki0eed4412016-07-21 11:21:59 -0700946 final File path = getUserFile(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800947 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700948 Slog.d(TAG, "Saving to " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800949 }
Makoto Onuki475c3652017-05-08 14:29:03 -0700950
951 mShortcutBitmapSaver.waitForAllSavesLocked();
952
Makoto Onuki0eed4412016-07-21 11:21:59 -0700953 path.getParentFile().mkdirs();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800954 final AtomicFile file = new AtomicFile(path);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700955 FileOutputStream os = null;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800956 try {
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700957 os = file.startWrite();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800958
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700959 saveUserInternalLocked(userId, os, /* forBackup= */ false);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800960
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700961 file.finishWrite(os);
Makoto Onuki1e173232016-08-10 10:47:13 -0700962
963 // Remove all dangling bitmap files.
964 cleanupDanglingBitmapDirectoriesLocked(userId);
Makoto Onukib08790c2016-06-23 14:05:46 -0700965 } catch (XmlPullParserException | IOException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800966 Slog.e(TAG, "Failed to write to file " + file.getBaseFile(), e);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700967 file.failWrite(os);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800968 }
969 }
970
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700971 private void saveUserInternalLocked(@UserIdInt int userId, OutputStream os,
972 boolean forBackup) throws IOException, XmlPullParserException {
973
974 final BufferedOutputStream bos = new BufferedOutputStream(os);
975
976 // Write to XML
977 XmlSerializer out = new FastXmlSerializer();
978 out.setOutput(bos, StandardCharsets.UTF_8.name());
979 out.startDocument(null, true);
980
Makoto Onukic51b2872016-05-04 15:24:50 -0700981 getUserShortcutsLocked(userId).saveToXml(out, forBackup);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700982
983 out.endDocument();
984
985 bos.flush();
986 os.flush();
987 }
988
Makoto Onuki41066a62016-03-09 16:18:44 -0800989 static IOException throwForInvalidTag(int depth, String tag) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800990 throw new IOException(String.format("Invalid tag '%s' found at depth %d", tag, depth));
991 }
992
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700993 static void warnForInvalidTag(int depth, String tag) throws IOException {
994 Slog.w(TAG, String.format("Invalid tag '%s' found at depth %d", tag, depth));
995 }
996
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800997 @Nullable
Makoto Onuki31459242016-03-22 11:12:18 -0700998 private ShortcutUser loadUserLocked(@UserIdInt int userId) {
Makoto Onuki0eed4412016-07-21 11:21:59 -0700999 final File path = getUserFile(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001000 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001001 Slog.d(TAG, "Loading from " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001002 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001003 final AtomicFile file = new AtomicFile(path);
1004
1005 final FileInputStream in;
1006 try {
1007 in = file.openRead();
1008 } catch (FileNotFoundException e) {
1009 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001010 Slog.d(TAG, "Not found " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001011 }
1012 return null;
1013 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001014 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07001015 final ShortcutUser ret = loadUserInternal(userId, in, /* forBackup= */ false);
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001016 return ret;
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07001017 } catch (IOException | XmlPullParserException | InvalidFileFormatException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001018 Slog.e(TAG, "Failed to read file " + file.getBaseFile(), e);
1019 return null;
1020 } finally {
1021 IoUtils.closeQuietly(in);
1022 }
1023 }
1024
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001025 private ShortcutUser loadUserInternal(@UserIdInt int userId, InputStream is,
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07001026 boolean fromBackup) throws XmlPullParserException, IOException,
1027 InvalidFileFormatException {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001028
1029 final BufferedInputStream bis = new BufferedInputStream(is);
1030
1031 ShortcutUser ret = null;
1032 XmlPullParser parser = Xml.newPullParser();
1033 parser.setInput(bis, StandardCharsets.UTF_8.name());
1034
1035 int type;
1036 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1037 if (type != XmlPullParser.START_TAG) {
1038 continue;
1039 }
1040 final int depth = parser.getDepth();
1041
1042 final String tag = parser.getName();
1043 if (DEBUG_LOAD) {
1044 Slog.d(TAG, String.format("depth=%d type=%d name=%s",
1045 depth, type, tag));
1046 }
1047 if ((depth == 1) && ShortcutUser.TAG_ROOT.equals(tag)) {
1048 ret = ShortcutUser.loadFromXml(this, parser, userId, fromBackup);
1049 continue;
1050 }
1051 throwForInvalidTag(depth, tag);
1052 }
1053 return ret;
1054 }
1055
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001056 private void scheduleSaveBaseState() {
Makoto Onuki0acbb142016-03-22 17:02:57 -07001057 scheduleSaveInner(UserHandle.USER_NULL); // Special case -- use USER_NULL for base state.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001058 }
1059
Makoto Onuki2d5b4652016-03-11 16:09:54 -08001060 void scheduleSaveUser(@UserIdInt int userId) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07001061 scheduleSaveInner(userId);
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001062 }
1063
1064 // In order to re-schedule, we need to reuse the same instance, so keep it in final.
1065 private final Runnable mSaveDirtyInfoRunner = this::saveDirtyInfo;
1066
Makoto Onuki0acbb142016-03-22 17:02:57 -07001067 private void scheduleSaveInner(@UserIdInt int userId) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001068 if (DEBUG) {
1069 Slog.d(TAG, "Scheduling to save for " + userId);
1070 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001071 synchronized (mLock) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001072 if (!mDirtyUserIds.contains(userId)) {
1073 mDirtyUserIds.add(userId);
1074 }
1075 }
1076 // If already scheduled, remove that and re-schedule in N seconds.
1077 mHandler.removeCallbacks(mSaveDirtyInfoRunner);
1078 mHandler.postDelayed(mSaveDirtyInfoRunner, mSaveDelayMillis);
1079 }
1080
1081 @VisibleForTesting
1082 void saveDirtyInfo() {
1083 if (DEBUG) {
1084 Slog.d(TAG, "saveDirtyInfo");
1085 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001086 try {
1087 synchronized (mLock) {
1088 for (int i = mDirtyUserIds.size() - 1; i >= 0; i--) {
1089 final int userId = mDirtyUserIds.get(i);
1090 if (userId == UserHandle.USER_NULL) { // USER_NULL for base state.
1091 saveBaseStateLocked();
1092 } else {
1093 saveUserLocked(userId);
1094 }
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001095 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001096 mDirtyUserIds.clear();
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001097 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001098 } catch (Exception e) {
1099 wtf("Exception in saveDirtyInfo", e);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001100 }
1101 }
1102
1103 /** Return the last reset time. */
1104 long getLastResetTimeLocked() {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001105 updateTimesLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001106 return mRawLastResetTime;
1107 }
1108
1109 /** Return the next reset time. */
1110 long getNextResetTimeLocked() {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001111 updateTimesLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001112 return mRawLastResetTime + mResetInterval;
1113 }
1114
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001115 static boolean isClockValid(long time) {
1116 return time >= 1420070400; // Thu, 01 Jan 2015 00:00:00 GMT
1117 }
1118
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001119 /**
1120 * Update the last reset time.
1121 */
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001122 private void updateTimesLocked() {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001123
1124 final long now = injectCurrentTimeMillis();
1125
1126 final long prevLastResetTime = mRawLastResetTime;
1127
1128 if (mRawLastResetTime == 0) { // first launch.
1129 // TODO Randomize??
1130 mRawLastResetTime = now;
1131 } else if (now < mRawLastResetTime) {
1132 // Clock rewound.
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001133 if (isClockValid(now)) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001134 Slog.w(TAG, "Clock rewound");
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001135 // TODO Randomize??
1136 mRawLastResetTime = now;
1137 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001138 } else {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001139 if ((mRawLastResetTime + mResetInterval) <= now) {
1140 final long offset = mRawLastResetTime % mResetInterval;
1141 mRawLastResetTime = ((now / mResetInterval) * mResetInterval) + offset;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001142 }
1143 }
1144 if (prevLastResetTime != mRawLastResetTime) {
1145 scheduleSaveBaseState();
1146 }
1147 }
1148
Makoto Onuki1e173232016-08-10 10:47:13 -07001149 // Requires mLock held, but "Locked" prefix would look weired so we just say "L".
Makoto Onuki02f338e2016-07-29 09:40:40 -07001150 protected boolean isUserUnlockedL(@UserIdInt int userId) {
Makoto Onuki1e173232016-08-10 10:47:13 -07001151 // First, check the local copy.
1152 if (mUnlockedUsers.get(userId)) {
1153 return true;
1154 }
1155 // If the local copy says the user is locked, check with AM for the actual state, since
1156 // the user might just have been unlocked.
1157 // Note we just don't use isUserUnlockingOrUnlocked() here, because it'll return false
1158 // when the user is STOPPING, which we still want to consider as "unlocked".
1159 final long token = injectClearCallingIdentity();
1160 try {
1161 return mUserManager.isUserUnlockingOrUnlocked(userId);
1162 } finally {
1163 injectRestoreCallingIdentity(token);
1164 }
Makoto Onuki9c850012016-07-26 15:50:50 -07001165 }
1166
Makoto Onuki02f338e2016-07-29 09:40:40 -07001167 // Requires mLock held, but "Locked" prefix would look weired so we jsut say "L".
1168 void throwIfUserLockedL(@UserIdInt int userId) {
1169 if (!isUserUnlockedL(userId)) {
Makoto Onuki9c850012016-07-26 15:50:50 -07001170 throw new IllegalStateException("User " + userId + " is locked or not running");
1171 }
1172 }
1173
Makoto Onukicdc78f72016-03-21 15:47:52 -07001174 @GuardedBy("mLock")
1175 @NonNull
Makoto Onuki2e210c42016-03-30 08:30:36 -07001176 private boolean isUserLoadedLocked(@UserIdInt int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07001177 return mUsers.get(userId) != null;
1178 }
1179
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001180 /** Return the per-user state. */
1181 @GuardedBy("mLock")
1182 @NonNull
Makoto Onuki31459242016-03-22 11:12:18 -07001183 ShortcutUser getUserShortcutsLocked(@UserIdInt int userId) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001184 if (!isUserUnlockedL(userId)) {
Makoto Onuki9c850012016-07-26 15:50:50 -07001185 wtf("User still locked");
Makoto Onuki9c850012016-07-26 15:50:50 -07001186 }
1187
Makoto Onuki31459242016-03-22 11:12:18 -07001188 ShortcutUser userPackages = mUsers.get(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001189 if (userPackages == null) {
1190 userPackages = loadUserLocked(userId);
1191 if (userPackages == null) {
Makoto Onukic51b2872016-05-04 15:24:50 -07001192 userPackages = new ShortcutUser(this, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001193 }
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08001194 mUsers.put(userId, userPackages);
Makoto Onuki085a05c2016-08-19 11:39:29 -07001195
1196 // Also when a user's data is first accessed, scan all packages.
1197 checkPackageChanges(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001198 }
1199 return userPackages;
1200 }
1201
Makoto Onuki2e210c42016-03-30 08:30:36 -07001202 void forEachLoadedUserLocked(@NonNull Consumer<ShortcutUser> c) {
1203 for (int i = mUsers.size() - 1; i >= 0; i--) {
1204 c.accept(mUsers.valueAt(i));
1205 }
1206 }
1207
Makoto Onukic8c33292016-09-12 16:36:59 -07001208 /**
1209 * Return the per-user per-package state. If the caller is a publisher, use
1210 * {@link #getPackageShortcutsForPublisherLocked} instead.
1211 */
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001212 @GuardedBy("mLock")
1213 @NonNull
Makoto Onuki31459242016-03-22 11:12:18 -07001214 ShortcutPackage getPackageShortcutsLocked(
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001215 @NonNull String packageName, @UserIdInt int userId) {
Makoto Onukic51b2872016-05-04 15:24:50 -07001216 return getUserShortcutsLocked(userId).getPackageShortcuts(packageName);
Makoto Onukide667372016-03-15 14:29:20 -07001217 }
1218
Makoto Onukic8c33292016-09-12 16:36:59 -07001219 /** Return the per-user per-package state. Use this when the caller is a publisher. */
1220 @GuardedBy("mLock")
1221 @NonNull
1222 ShortcutPackage getPackageShortcutsForPublisherLocked(
1223 @NonNull String packageName, @UserIdInt int userId) {
1224 final ShortcutPackage ret = getUserShortcutsLocked(userId).getPackageShortcuts(packageName);
1225 ret.getUser().onCalledByPublisher(packageName);
1226 return ret;
1227 }
1228
Makoto Onukide667372016-03-15 14:29:20 -07001229 @GuardedBy("mLock")
1230 @NonNull
Makoto Onuki2e210c42016-03-30 08:30:36 -07001231 ShortcutLauncher getLauncherShortcutsLocked(
1232 @NonNull String packageName, @UserIdInt int ownerUserId,
1233 @UserIdInt int launcherUserId) {
1234 return getUserShortcutsLocked(ownerUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07001235 .getLauncherShortcuts(packageName, launcherUserId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001236 }
1237
1238 // === Caller validation ===
1239
Makoto Onuki475c3652017-05-08 14:29:03 -07001240 void removeIconLocked(ShortcutInfo shortcut) {
1241 mShortcutBitmapSaver.removeIcon(shortcut);
Makoto Onuki55046222016-03-08 10:49:47 -08001242 }
1243
Makoto Onuki0033b2a2016-04-14 17:19:16 -07001244 public void cleanupBitmapsForPackage(@UserIdInt int userId, String packageName) {
1245 final File packagePath = new File(getUserBitmapFilePath(userId), packageName);
1246 if (!packagePath.isDirectory()) {
1247 return;
1248 }
1249 if (!(FileUtils.deleteContents(packagePath) && packagePath.delete())) {
1250 Slog.w(TAG, "Unable to remove directory " + packagePath);
1251 }
1252 }
1253
Makoto Onuki475c3652017-05-08 14:29:03 -07001254 /**
1255 * Remove dangling bitmap files for a user.
1256 *
1257 * Note this method must be called with the lock held after calling
1258 * {@link ShortcutBitmapSaver#waitForAllSavesLocked()} to make sure there's no pending bitmap
1259 * saves are going on.
1260 */
Makoto Onuki1e173232016-08-10 10:47:13 -07001261 private void cleanupDanglingBitmapDirectoriesLocked(@UserIdInt int userId) {
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001262 if (DEBUG) {
1263 Slog.d(TAG, "cleanupDanglingBitmaps: userId=" + userId);
1264 }
1265 final long start = injectElapsedRealtime();
1266
Makoto Onuki1e173232016-08-10 10:47:13 -07001267 final ShortcutUser user = getUserShortcutsLocked(userId);
1268
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001269 final File bitmapDir = getUserBitmapFilePath(userId);
1270 final File[] children = bitmapDir.listFiles();
1271 if (children == null) {
1272 return;
1273 }
1274 for (File child : children) {
1275 if (!child.isDirectory()) {
1276 continue;
1277 }
1278 final String packageName = child.getName();
1279 if (DEBUG) {
1280 Slog.d(TAG, "cleanupDanglingBitmaps: Found directory=" + packageName);
1281 }
1282 if (!user.hasPackage(packageName)) {
1283 if (DEBUG) {
1284 Slog.d(TAG, "Removing dangling bitmap directory: " + packageName);
1285 }
1286 cleanupBitmapsForPackage(userId, packageName);
1287 } else {
1288 cleanupDanglingBitmapFilesLocked(userId, user, packageName, child);
1289 }
1290 }
1291 logDurationStat(Stats.CLEANUP_DANGLING_BITMAPS, start);
1292 }
1293
Makoto Onuki475c3652017-05-08 14:29:03 -07001294 /**
1295 * Remove dangling bitmap files for a package.
1296 *
1297 * Note this method must be called with the lock held after calling
1298 * {@link ShortcutBitmapSaver#waitForAllSavesLocked()} to make sure there's no pending bitmap
1299 * saves are going on.
1300 */
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001301 private void cleanupDanglingBitmapFilesLocked(@UserIdInt int userId, @NonNull ShortcutUser user,
1302 @NonNull String packageName, @NonNull File path) {
1303 final ArraySet<String> usedFiles =
Makoto Onukic51b2872016-05-04 15:24:50 -07001304 user.getPackageShortcuts(packageName).getUsedBitmapFiles();
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001305
1306 for (File child : path.listFiles()) {
1307 if (!child.isFile()) {
1308 continue;
1309 }
1310 final String name = child.getName();
1311 if (!usedFiles.contains(name)) {
1312 if (DEBUG) {
1313 Slog.d(TAG, "Removing dangling bitmap file: " + child.getAbsolutePath());
1314 }
1315 child.delete();
1316 }
1317 }
1318 }
1319
Makoto Onuki55046222016-03-08 10:49:47 -08001320 @VisibleForTesting
1321 static class FileOutputStreamWithPath extends FileOutputStream {
1322 private final File mFile;
1323
1324 public FileOutputStreamWithPath(File file) throws FileNotFoundException {
1325 super(file);
1326 mFile = file;
1327 }
1328
1329 public File getFile() {
1330 return mFile;
1331 }
1332 }
1333
1334 /**
1335 * Build the cached bitmap filename for a shortcut icon.
1336 *
1337 * The filename will be based on the ID, except certain characters will be escaped.
1338 */
Makoto Onuki55046222016-03-08 10:49:47 -08001339 FileOutputStreamWithPath openIconFileForWrite(@UserIdInt int userId, ShortcutInfo shortcut)
1340 throws IOException {
1341 final File packagePath = new File(getUserBitmapFilePath(userId),
Makoto Onuki22fcc682016-05-17 14:52:19 -07001342 shortcut.getPackage());
Makoto Onuki55046222016-03-08 10:49:47 -08001343 if (!packagePath.isDirectory()) {
1344 packagePath.mkdirs();
1345 if (!packagePath.isDirectory()) {
1346 throw new IOException("Unable to create directory " + packagePath);
1347 }
1348 SELinux.restorecon(packagePath);
1349 }
1350
1351 final String baseName = String.valueOf(injectCurrentTimeMillis());
Makoto Onukib08790c2016-06-23 14:05:46 -07001352 for (int suffix = 0; ; suffix++) {
Makoto Onuki55046222016-03-08 10:49:47 -08001353 final String filename = (suffix == 0 ? baseName : baseName + "_" + suffix) + ".png";
1354 final File file = new File(packagePath, filename);
1355 if (!file.exists()) {
1356 if (DEBUG) {
1357 Slog.d(TAG, "Saving icon to " + file.getAbsolutePath());
1358 }
1359 return new FileOutputStreamWithPath(file);
1360 }
1361 }
1362 }
1363
Makoto Onuki475c3652017-05-08 14:29:03 -07001364 void saveIconAndFixUpShortcutLocked(ShortcutInfo shortcut) {
Makoto Onuki55046222016-03-08 10:49:47 -08001365 if (shortcut.hasIconFile() || shortcut.hasIconResource()) {
1366 return;
1367 }
1368
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001369 final long token = injectClearCallingIdentity();
Makoto Onuki55046222016-03-08 10:49:47 -08001370 try {
1371 // Clear icon info on the shortcut.
Makoto Onuki475c3652017-05-08 14:29:03 -07001372 removeIconLocked(shortcut);
Makoto Onuki55046222016-03-08 10:49:47 -08001373
1374 final Icon icon = shortcut.getIcon();
1375 if (icon == null) {
1376 return; // has no icon
1377 }
Hyunyoung Song47037462017-05-08 16:51:43 -07001378 int maxIconDimension = mMaxIconDimension;
Makoto Onukiabe84422016-04-07 09:41:19 -07001379 Bitmap bitmap;
Makoto Onuki55046222016-03-08 10:49:47 -08001380 try {
1381 switch (icon.getType()) {
1382 case Icon.TYPE_RESOURCE: {
1383 injectValidateIconResPackage(shortcut, icon);
1384
1385 shortcut.setIconResourceId(icon.getResId());
1386 shortcut.addFlags(ShortcutInfo.FLAG_HAS_ICON_RES);
1387 return;
1388 }
Hyunyoung Songf281e7a2017-02-13 10:57:42 -08001389 case Icon.TYPE_BITMAP:
Makoto Onukiabe84422016-04-07 09:41:19 -07001390 bitmap = icon.getBitmap(); // Don't recycle in this case.
Makoto Onuki55046222016-03-08 10:49:47 -08001391 break;
Hyunyoung Song47037462017-05-08 16:51:43 -07001392 case Icon.TYPE_ADAPTIVE_BITMAP: {
1393 bitmap = icon.getBitmap(); // Don't recycle in this case.
1394 maxIconDimension *= (1 + 2 * AdaptiveIconDrawable.getExtraInsetFraction());
Hyunyoung Song8947f592017-05-15 10:12:11 -07001395 break;
Makoto Onuki55046222016-03-08 10:49:47 -08001396 }
Makoto Onuki55046222016-03-08 10:49:47 -08001397 default:
1398 // This shouldn't happen because we've already validated the icon, but
1399 // just in case.
1400 throw ShortcutInfo.getInvalidIconException();
1401 }
Makoto Onuki475c3652017-05-08 14:29:03 -07001402 mShortcutBitmapSaver.saveBitmapLocked(shortcut,
Hyunyoung Song47037462017-05-08 16:51:43 -07001403 maxIconDimension, mIconPersistFormat, mIconPersistQuality);
Makoto Onuki55046222016-03-08 10:49:47 -08001404 } finally {
Makoto Onuki55046222016-03-08 10:49:47 -08001405 // Once saved, we won't use the original icon information, so null it out.
1406 shortcut.clearIcon();
1407 }
1408 } finally {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001409 injectRestoreCallingIdentity(token);
Makoto Onuki55046222016-03-08 10:49:47 -08001410 }
1411 }
1412
1413 // Unfortunately we can't do this check in unit tests because we fake creator package names,
1414 // so override in unit tests.
1415 // TODO CTS this case.
1416 void injectValidateIconResPackage(ShortcutInfo shortcut, Icon icon) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07001417 if (!shortcut.getPackage().equals(icon.getResPackage())) {
Makoto Onuki55046222016-03-08 10:49:47 -08001418 throw new IllegalArgumentException(
1419 "Icon resource must reside in shortcut owner package");
1420 }
1421 }
1422
Makoto Onuki55046222016-03-08 10:49:47 -08001423 static Bitmap shrinkBitmap(Bitmap in, int maxSize) {
1424 // Original width/height.
1425 final int ow = in.getWidth();
1426 final int oh = in.getHeight();
1427 if ((ow <= maxSize) && (oh <= maxSize)) {
1428 if (DEBUG) {
1429 Slog.d(TAG, String.format("Icon size %dx%d, no need to shrink", ow, oh));
1430 }
1431 return in;
1432 }
1433 final int longerDimension = Math.max(ow, oh);
1434
1435 // New width and height.
1436 final int nw = ow * maxSize / longerDimension;
1437 final int nh = oh * maxSize / longerDimension;
1438 if (DEBUG) {
1439 Slog.d(TAG, String.format("Icon size %dx%d, shrinking to %dx%d",
1440 ow, oh, nw, nh));
1441 }
1442
1443 final Bitmap scaledBitmap = Bitmap.createBitmap(nw, nh, Bitmap.Config.ARGB_8888);
1444 final Canvas c = new Canvas(scaledBitmap);
1445
1446 final RectF dst = new RectF(0, 0, nw, nh);
1447
1448 c.drawBitmap(in, /*src=*/ null, dst, /* paint =*/ null);
1449
Makoto Onuki55046222016-03-08 10:49:47 -08001450 return scaledBitmap;
1451 }
1452
Makoto Onuki157b1622016-06-02 16:13:10 -07001453 /**
1454 * For a shortcut, update all resource names from resource IDs, and also update all
1455 * resource-based strings.
1456 */
1457 void fixUpShortcutResourceNamesAndValues(ShortcutInfo si) {
1458 final Resources publisherRes = injectGetResourcesForApplicationAsUser(
1459 si.getPackage(), si.getUserId());
1460 if (publisherRes != null) {
1461 final long start = injectElapsedRealtime();
1462 try {
1463 si.lookupAndFillInResourceNames(publisherRes);
1464 } finally {
1465 logDurationStat(Stats.RESOURCE_NAME_LOOKUP, start);
1466 }
1467 si.resolveResourceStrings(publisherRes);
1468 }
1469 }
1470
Makoto Onuki55046222016-03-08 10:49:47 -08001471 // === Caller validation ===
1472
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001473 private boolean isCallerSystem() {
1474 final int callingUid = injectBinderCallingUid();
Makoto Onukib08790c2016-06-23 14:05:46 -07001475 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001476 }
1477
1478 private boolean isCallerShell() {
1479 final int callingUid = injectBinderCallingUid();
1480 return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
1481 }
1482
1483 private void enforceSystemOrShell() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001484 if (!(isCallerSystem() || isCallerShell())) {
1485 throw new SecurityException("Caller must be system or shell");
1486 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001487 }
1488
1489 private void enforceShell() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001490 if (!isCallerShell()) {
1491 throw new SecurityException("Caller must be shell");
1492 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001493 }
1494
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001495 private void enforceSystem() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001496 if (!isCallerSystem()) {
1497 throw new SecurityException("Caller must be system");
1498 }
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001499 }
1500
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001501 private void enforceResetThrottlingPermission() {
1502 if (isCallerSystem()) {
1503 return;
1504 }
Makoto Onuki76269922016-07-15 14:58:54 -07001505 enforceCallingOrSelfPermission(
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001506 android.Manifest.permission.RESET_SHORTCUT_MANAGER_THROTTLING, null);
1507 }
1508
Makoto Onuki76269922016-07-15 14:58:54 -07001509 private void enforceCallingOrSelfPermission(
1510 @NonNull String permission, @Nullable String message) {
1511 if (isCallerSystem()) {
1512 return;
1513 }
1514 injectEnforceCallingPermission(permission, message);
1515 }
1516
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001517 /**
1518 * Somehow overriding ServiceContext.enforceCallingPermission() in the unit tests would confuse
1519 * mockito. So instead we extracted it here and override it in the tests.
1520 */
1521 @VisibleForTesting
1522 void injectEnforceCallingPermission(
1523 @NonNull String permission, @Nullable String message) {
1524 mContext.enforceCallingPermission(permission, message);
1525 }
1526
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001527 private void verifyCaller(@NonNull String packageName, @UserIdInt int userId) {
1528 Preconditions.checkStringNotEmpty(packageName, "packageName");
1529
1530 if (isCallerSystem()) {
1531 return; // no check
1532 }
1533
1534 final int callingUid = injectBinderCallingUid();
1535
1536 // Otherwise, make sure the arguments are valid.
1537 if (UserHandle.getUserId(callingUid) != userId) {
1538 throw new SecurityException("Invalid user-ID");
1539 }
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08001540 if (injectGetPackageUid(packageName, userId) != callingUid) {
1541 throw new SecurityException("Calling package name mismatch");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001542 }
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08001543 Preconditions.checkState(!isEphemeralApp(packageName, userId),
1544 "Ephemeral apps can't use ShortcutManager");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001545 }
1546
Makoto Onuki157b1622016-06-02 16:13:10 -07001547 // Overridden in unit tests to execute r synchronously.
1548 void injectPostToHandler(Runnable r) {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001549 mHandler.post(r);
1550 }
1551
Makoto Onuki085a05c2016-08-19 11:39:29 -07001552 void injectRunOnNewThread(Runnable r) {
1553 new Thread(r).start();
1554 }
1555
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001556 /**
Makoto Onuki7001a612016-05-27 13:24:28 -07001557 * @throws IllegalArgumentException if {@code numShortcuts} is bigger than
Makoto Onukib08790c2016-06-23 14:05:46 -07001558 * {@link #getMaxActivityShortcuts()}.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001559 */
Makoto Onuki7001a612016-05-27 13:24:28 -07001560 void enforceMaxActivityShortcuts(int numShortcuts) {
Makoto Onukib5a012f2016-06-21 11:13:53 -07001561 if (numShortcuts > mMaxShortcuts) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001562 throw new IllegalArgumentException("Max number of dynamic shortcuts exceeded");
1563 }
1564 }
1565
1566 /**
Makoto Onuki7001a612016-05-27 13:24:28 -07001567 * Return the max number of dynamic + manifest shortcuts for each launcher icon.
1568 */
1569 int getMaxActivityShortcuts() {
Makoto Onukib5a012f2016-06-21 11:13:53 -07001570 return mMaxShortcuts;
Makoto Onuki7001a612016-05-27 13:24:28 -07001571 }
1572
1573 /**
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001574 * - Sends a notification to LauncherApps
1575 * - Write to file
1576 */
Makoto Onuki39686e82016-04-13 18:03:00 -07001577 void packageShortcutsChanged(@NonNull String packageName, @UserIdInt int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001578 notifyListeners(packageName, userId);
1579 scheduleSaveUser(userId);
1580 }
1581
1582 private void notifyListeners(@NonNull String packageName, @UserIdInt int userId) {
Makoto Onuki82fb2eb2017-03-31 16:58:26 -07001583 if (DEBUG) {
1584 Slog.d(TAG, String.format(
1585 "Shortcut changes: package=%s, user=%d", packageName, userId));
1586 }
Makoto Onuki157b1622016-06-02 16:13:10 -07001587 injectPostToHandler(() -> {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001588 try {
1589 final ArrayList<ShortcutChangeListener> copy;
1590 synchronized (mLock) {
1591 if (!isUserUnlockedL(userId)) {
1592 return;
1593 }
1594
1595 copy = new ArrayList<>(mListeners);
1596 }
1597 // Note onShortcutChanged() needs to be called with the system service permissions.
1598 for (int i = copy.size() - 1; i >= 0; i--) {
1599 copy.get(i).onShortcutChanged(packageName, userId);
1600 }
1601 } catch (Exception ignore) {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001602 }
1603 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001604 }
1605
1606 /**
1607 * Clean up / validate an incoming shortcut.
1608 * - Make sure all mandatory fields are set.
1609 * - Make sure the intent's extras are persistable, and them to set
Makoto Onuki0eed4412016-07-21 11:21:59 -07001610 * {@link ShortcutInfo#mIntentPersistableExtrases}. Also clear its extras.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001611 * - Clear flags.
1612 */
Makoto Onuki2d895c32016-12-02 15:48:40 -08001613 private void fixUpIncomingShortcutInfo(@NonNull ShortcutInfo shortcut, boolean forUpdate,
1614 boolean forPinRequest) {
Makoto Onukibf563b62017-05-04 10:25:30 -07001615 if (shortcut.isReturnedByServer()) {
1616 Log.w(TAG,
1617 "Re-publishing ShortcutInfo returned by server is not supported."
1618 + " Some information such as icon may lost from shortcut.");
1619 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001620 Preconditions.checkNotNull(shortcut, "Null shortcut detected");
Makoto Onuki255461f2017-01-10 11:47:25 -08001621 if (shortcut.getActivity() != null) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001622 Preconditions.checkState(
Makoto Onuki22fcc682016-05-17 14:52:19 -07001623 shortcut.getPackage().equals(shortcut.getActivity().getPackageName()),
Makoto Onukib08790c2016-06-23 14:05:46 -07001624 "Cannot publish shortcut: activity " + shortcut.getActivity() + " does not"
1625 + " belong to package " + shortcut.getPackage());
Makoto Onuki13260b6ff2016-07-13 18:03:13 -07001626 Preconditions.checkState(
1627 injectIsMainActivity(shortcut.getActivity(), shortcut.getUserId()),
1628 "Cannot publish shortcut: activity " + shortcut.getActivity() + " is not"
1629 + " main activity");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001630 }
1631
Makoto Onuki55046222016-03-08 10:49:47 -08001632 if (!forUpdate) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08001633 shortcut.enforceMandatoryFields(/* forPinned= */ forPinRequest);
1634 if (!forPinRequest) {
Makoto Onuki255461f2017-01-10 11:47:25 -08001635 Preconditions.checkState(shortcut.getActivity() != null,
1636 "Cannot publish shortcut: target activity is not set");
Makoto Onuki2d895c32016-12-02 15:48:40 -08001637 }
Makoto Onuki55046222016-03-08 10:49:47 -08001638 }
1639 if (shortcut.getIcon() != null) {
1640 ShortcutInfo.validateIcon(shortcut.getIcon());
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001641 }
1642
Makoto Onukide667372016-03-15 14:29:20 -07001643 shortcut.replaceFlags(0);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001644 }
1645
Makoto Onuki2d895c32016-12-02 15:48:40 -08001646 private void fixUpIncomingShortcutInfo(@NonNull ShortcutInfo shortcut, boolean forUpdate) {
1647 fixUpIncomingShortcutInfo(shortcut, forUpdate, /*forPinRequest=*/ false);
1648 }
1649
1650 public void validateShortcutForPinRequest(@NonNull ShortcutInfo shortcut) {
1651 fixUpIncomingShortcutInfo(shortcut, /* forUpdate= */ false, /*forPinRequest=*/ true);
1652 }
1653
Makoto Onukib08790c2016-06-23 14:05:46 -07001654 /**
1655 * When a shortcut has no target activity, set the default one from the package.
1656 */
1657 private void fillInDefaultActivity(List<ShortcutInfo> shortcuts) {
Makoto Onukib08790c2016-06-23 14:05:46 -07001658 ComponentName defaultActivity = null;
1659 for (int i = shortcuts.size() - 1; i >= 0; i--) {
1660 final ShortcutInfo si = shortcuts.get(i);
1661 if (si.getActivity() == null) {
1662 if (defaultActivity == null) {
1663 defaultActivity = injectGetDefaultMainActivity(
1664 si.getPackage(), si.getUserId());
1665 Preconditions.checkState(defaultActivity != null,
1666 "Launcher activity not found for package " + si.getPackage());
1667 }
1668 si.setActivity(defaultActivity);
1669 }
1670 }
1671 }
1672
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001673 private void assignImplicitRanks(List<ShortcutInfo> shortcuts) {
1674 for (int i = shortcuts.size() - 1; i >= 0; i--) {
1675 shortcuts.get(i).setImplicitRank(i);
1676 }
1677 }
1678
Makoto Onukibf563b62017-05-04 10:25:30 -07001679 private List<ShortcutInfo> setReturnedByServer(List<ShortcutInfo> shortcuts) {
1680 for (int i = shortcuts.size() - 1; i >= 0; i--) {
1681 shortcuts.get(i).setReturnedByServer();
1682 }
1683 return shortcuts;
1684 }
1685
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001686 // === APIs ===
1687
1688 @Override
1689 public boolean setDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1690 @UserIdInt int userId) {
1691 verifyCaller(packageName, userId);
1692
1693 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
1694 final int size = newShortcuts.size();
1695
1696 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001697 throwIfUserLockedL(userId);
1698
Makoto Onukic8c33292016-09-12 16:36:59 -07001699 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001700
Makoto Onukia4f89b12017-10-05 10:37:55 -07001701 ps.ensureImmutableShortcutsNotIncluded(newShortcuts, /*ignoreInvisible=*/ true);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001702
Makoto Onukib08790c2016-06-23 14:05:46 -07001703 fillInDefaultActivity(newShortcuts);
1704
Makoto Onuki7001a612016-05-27 13:24:28 -07001705 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_SET);
1706
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001707 // Throttling.
Makoto Onukic51b2872016-05-04 15:24:50 -07001708 if (!ps.tryApiCall()) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001709 return false;
1710 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001711
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001712 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1713 ps.clearAllImplicitRanks();
1714 assignImplicitRanks(newShortcuts);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001715
Makoto Onukidf6da042016-06-16 09:51:40 -07001716 for (int i = 0; i < size; i++) {
1717 fixUpIncomingShortcutInfo(newShortcuts.get(i), /* forUpdate= */ false);
1718 }
1719
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001720 // First, remove all un-pinned; dynamic shortcuts
Makoto Onukia4f89b12017-10-05 10:37:55 -07001721 ps.deleteAllDynamicShortcuts(/*ignoreInvisible=*/ true);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001722
1723 // Then, add/update all. We need to make sure to take over "pinned" flag.
1724 for (int i = 0; i < size; i++) {
1725 final ShortcutInfo newShortcut = newShortcuts.get(i);
Makoto Onukia4f89b12017-10-05 10:37:55 -07001726 ps.addOrReplaceDynamicShortcut(newShortcut);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001727 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001728
1729 // Lastly, adjust the ranks.
1730 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001731 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001732 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001733
1734 verifyStates();
1735
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001736 return true;
1737 }
1738
1739 @Override
1740 public boolean updateShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1741 @UserIdInt int userId) {
1742 verifyCaller(packageName, userId);
1743
1744 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
Makoto Onuki55046222016-03-08 10:49:47 -08001745 final int size = newShortcuts.size();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001746
1747 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001748 throwIfUserLockedL(userId);
1749
Makoto Onukic8c33292016-09-12 16:36:59 -07001750 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001751
Makoto Onukia4f89b12017-10-05 10:37:55 -07001752 ps.ensureImmutableShortcutsNotIncluded(newShortcuts, /*ignoreInvisible=*/ true);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001753
Makoto Onukib08790c2016-06-23 14:05:46 -07001754 // For update, don't fill in the default activity. Having null activity means
1755 // "don't update the activity" here.
1756
Makoto Onuki7001a612016-05-27 13:24:28 -07001757 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_UPDATE);
1758
Makoto Onuki55046222016-03-08 10:49:47 -08001759 // Throttling.
Makoto Onukic51b2872016-05-04 15:24:50 -07001760 if (!ps.tryApiCall()) {
Makoto Onuki55046222016-03-08 10:49:47 -08001761 return false;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001762 }
1763
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001764 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1765 ps.clearAllImplicitRanks();
1766 assignImplicitRanks(newShortcuts);
1767
Makoto Onuki55046222016-03-08 10:49:47 -08001768 for (int i = 0; i < size; i++) {
1769 final ShortcutInfo source = newShortcuts.get(i);
1770 fixUpIncomingShortcutInfo(source, /* forUpdate= */ true);
1771
1772 final ShortcutInfo target = ps.findShortcutById(source.getId());
Makoto Onukia4f89b12017-10-05 10:37:55 -07001773
1774 // Invisible shortcuts can't be updated.
1775 if (target == null || !target.isVisibleToPublisher()) {
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001776 continue;
1777 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07001778
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001779 if (target.isEnabled() != source.isEnabled()) {
1780 Slog.w(TAG,
1781 "ShortcutInfo.enabled cannot be changed with updateShortcuts()");
1782 }
Makoto Onuki55046222016-03-08 10:49:47 -08001783
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001784 // When updating the rank, we need to insert between existing ranks, so set
1785 // this setRankChanged, and also copy the implicit rank fo adjustRanks().
1786 if (source.hasRank()) {
1787 target.setRankChanged();
1788 target.setImplicitRank(source.getImplicitRank());
1789 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07001790
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001791 final boolean replacingIcon = (source.getIcon() != null);
1792 if (replacingIcon) {
Makoto Onuki475c3652017-05-08 14:29:03 -07001793 removeIconLocked(target);
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001794 }
Makoto Onuki55046222016-03-08 10:49:47 -08001795
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001796 // Note copyNonNullFieldsFrom() does the "updatable with?" check too.
1797 target.copyNonNullFieldsFrom(source);
1798 target.setTimestamp(injectCurrentTimeMillis());
1799
1800 if (replacingIcon) {
Makoto Onuki475c3652017-05-08 14:29:03 -07001801 saveIconAndFixUpShortcutLocked(target);
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001802 }
1803
1804 // When we're updating any resource related fields, re-extract the res names and
1805 // the values.
1806 if (replacingIcon || source.hasStringResources()) {
1807 fixUpShortcutResourceNamesAndValues(target);
Makoto Onuki55046222016-03-08 10:49:47 -08001808 }
1809 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001810
1811 // Lastly, adjust the ranks.
1812 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001813 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001814 packageShortcutsChanged(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001815
Makoto Onuki7001a612016-05-27 13:24:28 -07001816 verifyStates();
1817
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001818 return true;
1819 }
1820
1821 @Override
Makoto Onukia4f89b12017-10-05 10:37:55 -07001822 public boolean addDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001823 @UserIdInt int userId) {
1824 verifyCaller(packageName, userId);
1825
Makoto Onukib6d35232016-04-04 15:57:17 -07001826 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
1827 final int size = newShortcuts.size();
1828
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001829 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001830 throwIfUserLockedL(userId);
1831
Makoto Onukic8c33292016-09-12 16:36:59 -07001832 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001833
Makoto Onukia4f89b12017-10-05 10:37:55 -07001834 ps.ensureImmutableShortcutsNotIncluded(newShortcuts, /*ignoreInvisible=*/ true);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001835
Makoto Onukib08790c2016-06-23 14:05:46 -07001836 fillInDefaultActivity(newShortcuts);
1837
Makoto Onuki7001a612016-05-27 13:24:28 -07001838 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_ADD);
1839
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001840 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1841 ps.clearAllImplicitRanks();
1842 assignImplicitRanks(newShortcuts);
1843
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001844 // Throttling.
Makoto Onukic51b2872016-05-04 15:24:50 -07001845 if (!ps.tryApiCall()) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001846 return false;
1847 }
Makoto Onukib6d35232016-04-04 15:57:17 -07001848 for (int i = 0; i < size; i++) {
1849 final ShortcutInfo newShortcut = newShortcuts.get(i);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001850
Makoto Onukib6d35232016-04-04 15:57:17 -07001851 // Validate the shortcut.
1852 fixUpIncomingShortcutInfo(newShortcut, /* forUpdate= */ false);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001853
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001854 // When ranks are changing, we need to insert between ranks, so set the
1855 // "rank changed" flag.
1856 newShortcut.setRankChanged();
1857
Makoto Onukib6d35232016-04-04 15:57:17 -07001858 // Add it.
Makoto Onukia4f89b12017-10-05 10:37:55 -07001859 ps.addOrReplaceDynamicShortcut(newShortcut);
Makoto Onukib6d35232016-04-04 15:57:17 -07001860 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001861
1862 // Lastly, adjust the ranks.
1863 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001864 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001865 packageShortcutsChanged(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001866
Makoto Onuki7001a612016-05-27 13:24:28 -07001867 verifyStates();
1868
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001869 return true;
1870 }
1871
1872 @Override
Makoto Onuki2d895c32016-12-02 15:48:40 -08001873 public boolean requestPinShortcut(String packageName, ShortcutInfo shortcut,
1874 IntentSender resultIntent, int userId) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08001875 Preconditions.checkNotNull(shortcut);
1876 Preconditions.checkArgument(shortcut.isEnabled(), "Shortcut must be enabled");
Sunny Goyal4ad6b572017-02-28 11:11:51 -08001877 return requestPinItem(packageName, userId, shortcut, null, null, resultIntent);
Sunny Goyal87a563e2017-01-01 19:42:45 -08001878 }
1879
Sunny Goyala6be88a2017-01-12 16:27:58 -08001880 @Override
1881 public Intent createShortcutResultIntent(String packageName, ShortcutInfo shortcut, int userId)
1882 throws RemoteException {
1883 Preconditions.checkNotNull(shortcut);
1884 Preconditions.checkArgument(shortcut.isEnabled(), "Shortcut must be enabled");
1885 verifyCaller(packageName, userId);
1886
1887 final Intent ret;
1888 synchronized (mLock) {
1889 throwIfUserLockedL(userId);
1890
1891 // Send request to the launcher, if supported.
1892 ret = mShortcutRequestPinProcessor.createShortcutResultIntent(shortcut, userId);
1893 }
1894
1895 verifyStates();
1896 return ret;
1897 }
1898
Sunny Goyal87a563e2017-01-01 19:42:45 -08001899 /**
1900 * Handles {@link #requestPinShortcut} and {@link ShortcutServiceInternal#requestPinAppWidget}.
1901 * After validating the caller, it passes the request to {@link #mShortcutRequestPinProcessor}.
1902 * Either {@param shortcut} or {@param appWidget} should be non-null.
1903 */
Sunny Goyal4ad6b572017-02-28 11:11:51 -08001904 private boolean requestPinItem(String packageName, int userId, ShortcutInfo shortcut,
1905 AppWidgetProviderInfo appWidget, Bundle extras, IntentSender resultIntent) {
Sunny Goyal87a563e2017-01-01 19:42:45 -08001906 verifyCaller(packageName, userId);
Makoto Onuki2d895c32016-12-02 15:48:40 -08001907
1908 final boolean ret;
1909 synchronized (mLock) {
1910 throwIfUserLockedL(userId);
1911
Makoto Onukia01f4f02016-12-15 15:58:41 -08001912 Preconditions.checkState(isUidForegroundLocked(injectBinderCallingUid()),
Makoto Onuki255461f2017-01-10 11:47:25 -08001913 "Calling application must have a foreground activity or a foreground service");
Makoto Onuki2d895c32016-12-02 15:48:40 -08001914
Makoto Onukia4f89b12017-10-05 10:37:55 -07001915 // If it's a pin shortcut request, and there's already a shortcut with the same ID
1916 // that's not visible to the caller (i.e. restore-blocked; meaning it's pinned by
1917 // someone already), then we just replace the existing one with this new one,
1918 // and then proceed the rest of the process.
1919 if (shortcut != null) {
1920 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(
1921 packageName, userId);
1922 final String id = shortcut.getId();
1923 if (ps.isShortcutExistsAndInvisibleToPublisher(id)) {
1924
1925 ps.updateInvisibleShortcutForPinRequestWith(shortcut);
1926
1927 packageShortcutsChanged(packageName, userId);
1928 }
1929 }
1930
Makoto Onuki2d895c32016-12-02 15:48:40 -08001931 // Send request to the launcher, if supported.
Sunny Goyal4ad6b572017-02-28 11:11:51 -08001932 ret = mShortcutRequestPinProcessor.requestPinItemLocked(shortcut, appWidget, extras,
1933 userId, resultIntent);
Makoto Onuki2d895c32016-12-02 15:48:40 -08001934 }
1935
1936 verifyStates();
1937
1938 return ret;
1939 }
1940
1941 @Override
Makoto Onuki20c95f82016-05-11 16:51:01 -07001942 public void disableShortcuts(String packageName, List shortcutIds,
Makoto Onukid6880792016-06-29 13:37:43 -07001943 CharSequence disabledMessage, int disabledMessageResId, @UserIdInt int userId) {
Makoto Onuki20c95f82016-05-11 16:51:01 -07001944 verifyCaller(packageName, userId);
1945 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
1946
1947 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001948 throwIfUserLockedL(userId);
1949
Makoto Onukic8c33292016-09-12 16:36:59 -07001950 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001951
Makoto Onukia4f89b12017-10-05 10:37:55 -07001952 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds,
1953 /*ignoreInvisible=*/ true);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001954
Makoto Onukid6880792016-06-29 13:37:43 -07001955 final String disabledMessageString =
1956 (disabledMessage == null) ? null : disabledMessage.toString();
1957
Makoto Onuki22fcc682016-05-17 14:52:19 -07001958 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
Makoto Onukia4f89b12017-10-05 10:37:55 -07001959 final String id = Preconditions.checkStringNotEmpty((String) shortcutIds.get(i));
1960 if (!ps.isShortcutExistsAndVisibleToPublisher(id)) {
1961 continue;
1962 }
1963 ps.disableWithId(id,
Makoto Onukid6880792016-06-29 13:37:43 -07001964 disabledMessageString, disabledMessageResId,
Makoto Onukia4f89b12017-10-05 10:37:55 -07001965 /* overrideImmutable=*/ false, /*ignoreInvisible=*/ true,
1966 ShortcutInfo.DISABLED_REASON_BY_APP);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001967 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001968
1969 // We may have removed dynamic shortcuts which may have left a gap, so adjust the ranks.
1970 ps.adjustRanks();
Makoto Onuki22fcc682016-05-17 14:52:19 -07001971 }
1972 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001973
1974 verifyStates();
Makoto Onuki22fcc682016-05-17 14:52:19 -07001975 }
1976
1977 @Override
1978 public void enableShortcuts(String packageName, List shortcutIds, @UserIdInt int userId) {
1979 verifyCaller(packageName, userId);
1980 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
1981
1982 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001983 throwIfUserLockedL(userId);
1984
Makoto Onukic8c33292016-09-12 16:36:59 -07001985 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001986
Makoto Onukia4f89b12017-10-05 10:37:55 -07001987 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds,
1988 /*ignoreInvisible=*/ true);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001989
1990 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
Makoto Onukia4f89b12017-10-05 10:37:55 -07001991 final String id = Preconditions.checkStringNotEmpty((String) shortcutIds.get(i));
1992 if (!ps.isShortcutExistsAndVisibleToPublisher(id)) {
1993 continue;
1994 }
1995 ps.enableWithId(id);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001996 }
Makoto Onuki20c95f82016-05-11 16:51:01 -07001997 }
1998 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001999
2000 verifyStates();
Makoto Onuki20c95f82016-05-11 16:51:01 -07002001 }
2002
2003 @Override
Makoto Onukib6d35232016-04-04 15:57:17 -07002004 public void removeDynamicShortcuts(String packageName, List shortcutIds,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002005 @UserIdInt int userId) {
2006 verifyCaller(packageName, userId);
Makoto Onukib6d35232016-04-04 15:57:17 -07002007 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002008
2009 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002010 throwIfUserLockedL(userId);
2011
Makoto Onukic8c33292016-09-12 16:36:59 -07002012 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002013
Makoto Onukia4f89b12017-10-05 10:37:55 -07002014 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds,
2015 /*ignoreInvisible=*/ true);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002016
Makoto Onukib6d35232016-04-04 15:57:17 -07002017 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
Makoto Onukia4f89b12017-10-05 10:37:55 -07002018 final String id = Preconditions.checkStringNotEmpty((String) shortcutIds.get(i));
2019 if (!ps.isShortcutExistsAndVisibleToPublisher(id)) {
2020 continue;
2021 }
2022 ps.deleteDynamicWithId(id, /*ignoreInvisible=*/ true);
Makoto Onukib6d35232016-04-04 15:57:17 -07002023 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002024
2025 // We may have removed dynamic shortcuts which may have left a gap, so adjust the ranks.
2026 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002027 }
Makoto Onuki39686e82016-04-13 18:03:00 -07002028 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07002029
2030 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002031 }
2032
2033 @Override
Makoto Onukib6d35232016-04-04 15:57:17 -07002034 public void removeAllDynamicShortcuts(String packageName, @UserIdInt int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002035 verifyCaller(packageName, userId);
2036
2037 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002038 throwIfUserLockedL(userId);
2039
Makoto Onukic8c33292016-09-12 16:36:59 -07002040 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onukia4f89b12017-10-05 10:37:55 -07002041 ps.deleteAllDynamicShortcuts(/*ignoreInvisible=*/ true);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002042 }
Makoto Onuki39686e82016-04-13 18:03:00 -07002043 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07002044
2045 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002046 }
2047
2048 @Override
2049 public ParceledListSlice<ShortcutInfo> getDynamicShortcuts(String packageName,
2050 @UserIdInt int userId) {
2051 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002052
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002053 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002054 throwIfUserLockedL(userId);
2055
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002056 return getShortcutsWithQueryLocked(
2057 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
Makoto Onukia4f89b12017-10-05 10:37:55 -07002058 ShortcutInfo::isDynamicVisible);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002059 }
2060 }
2061
2062 @Override
Makoto Onuki22fcc682016-05-17 14:52:19 -07002063 public ParceledListSlice<ShortcutInfo> getManifestShortcuts(String packageName,
2064 @UserIdInt int userId) {
2065 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002066
Makoto Onuki22fcc682016-05-17 14:52:19 -07002067 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002068 throwIfUserLockedL(userId);
2069
Makoto Onuki22fcc682016-05-17 14:52:19 -07002070 return getShortcutsWithQueryLocked(
2071 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
Makoto Onukia4f89b12017-10-05 10:37:55 -07002072 ShortcutInfo::isManifestVisible);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002073 }
2074 }
2075
2076 @Override
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002077 public ParceledListSlice<ShortcutInfo> getPinnedShortcuts(String packageName,
2078 @UserIdInt int userId) {
2079 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002080
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002081 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002082 throwIfUserLockedL(userId);
2083
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002084 return getShortcutsWithQueryLocked(
2085 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
Makoto Onukia4f89b12017-10-05 10:37:55 -07002086 ShortcutInfo::isPinnedVisible);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002087 }
2088 }
2089
2090 private ParceledListSlice<ShortcutInfo> getShortcutsWithQueryLocked(@NonNull String packageName,
2091 @UserIdInt int userId, int cloneFlags, @NonNull Predicate<ShortcutInfo> query) {
2092
2093 final ArrayList<ShortcutInfo> ret = new ArrayList<>();
2094
Makoto Onukic8c33292016-09-12 16:36:59 -07002095 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002096 ps.findAll(ret, query, cloneFlags);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002097
Makoto Onukibf563b62017-05-04 10:25:30 -07002098 return new ParceledListSlice<>(setReturnedByServer(ret));
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002099 }
2100
2101 @Override
Makoto Onukid6880792016-06-29 13:37:43 -07002102 public int getMaxShortcutCountPerActivity(String packageName, @UserIdInt int userId)
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002103 throws RemoteException {
2104 verifyCaller(packageName, userId);
2105
Makoto Onukib5a012f2016-06-21 11:13:53 -07002106 return mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002107 }
2108
2109 @Override
2110 public int getRemainingCallCount(String packageName, @UserIdInt int userId) {
2111 verifyCaller(packageName, userId);
2112
2113 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002114 throwIfUserLockedL(userId);
2115
Makoto Onukic8c33292016-09-12 16:36:59 -07002116 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002117 return mMaxUpdatesPerInterval - ps.getApiCallCount();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002118 }
2119 }
2120
2121 @Override
2122 public long getRateLimitResetTime(String packageName, @UserIdInt int userId) {
2123 verifyCaller(packageName, userId);
2124
2125 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002126 throwIfUserLockedL(userId);
2127
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002128 return getNextResetTimeLocked();
2129 }
2130 }
2131
Makoto Onuki55046222016-03-08 10:49:47 -08002132 @Override
Makoto Onuki20c95f82016-05-11 16:51:01 -07002133 public int getIconMaxDimensions(String packageName, int userId) {
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002134 verifyCaller(packageName, userId);
2135
Makoto Onuki55046222016-03-08 10:49:47 -08002136 synchronized (mLock) {
2137 return mMaxIconDimension;
2138 }
2139 }
2140
Makoto Onuki20c95f82016-05-11 16:51:01 -07002141 @Override
2142 public void reportShortcutUsed(String packageName, String shortcutId, int userId) {
2143 verifyCaller(packageName, userId);
2144
Makoto Onukiac042502016-05-20 16:39:42 -07002145 Preconditions.checkNotNull(shortcutId);
2146
2147 if (DEBUG) {
2148 Slog.d(TAG, String.format("reportShortcutUsed: Shortcut %s package %s used on user %d",
2149 shortcutId, packageName, userId));
2150 }
2151
2152 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002153 throwIfUserLockedL(userId);
2154
Makoto Onukic8c33292016-09-12 16:36:59 -07002155 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002156
Makoto Onukiac042502016-05-20 16:39:42 -07002157 if (ps.findShortcutById(shortcutId) == null) {
2158 Log.w(TAG, String.format("reportShortcutUsed: package %s doesn't have shortcut %s",
2159 packageName, shortcutId));
2160 return;
2161 }
2162 }
2163
2164 final long token = injectClearCallingIdentity();
2165 try {
2166 mUsageStatsManagerInternal.reportShortcutUsage(packageName, shortcutId, userId);
2167 } finally {
2168 injectRestoreCallingIdentity(token);
2169 }
Makoto Onuki20c95f82016-05-11 16:51:01 -07002170 }
2171
Makoto Onuki2d895c32016-12-02 15:48:40 -08002172 @Override
Sunny Goyal7f7372a2017-01-24 11:53:54 -08002173 public boolean isRequestPinItemSupported(int callingUserId, int requestType) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08002174 final long token = injectClearCallingIdentity();
2175 try {
Sunny Goyal7f7372a2017-01-24 11:53:54 -08002176 return mShortcutRequestPinProcessor
2177 .isRequestPinItemSupported(callingUserId, requestType);
Makoto Onuki2d895c32016-12-02 15:48:40 -08002178 } finally {
2179 injectRestoreCallingIdentity(token);
2180 }
2181 }
2182
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002183 /**
Makoto Onukib08790c2016-06-23 14:05:46 -07002184 * Reset all throttling, for developer options and command line. Only system/shell can call
2185 * it.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002186 */
2187 @Override
2188 public void resetThrottling() {
2189 enforceSystemOrShell();
2190
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002191 resetThrottlingInner(getCallingUserId());
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002192 }
2193
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002194 void resetThrottlingInner(@UserIdInt int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002195 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002196 if (!isUserUnlockedL(userId)) {
2197 Log.w(TAG, "User " + userId + " is locked or not running");
2198 return;
2199 }
2200
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002201 getUserShortcutsLocked(userId).resetThrottling();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002202 }
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002203 scheduleSaveUser(userId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002204 Slog.i(TAG, "ShortcutManager: throttling counter reset for user " + userId);
2205 }
2206
2207 void resetAllThrottlingInner() {
2208 synchronized (mLock) {
2209 mRawLastResetTime = injectCurrentTimeMillis();
2210 }
2211 scheduleSaveBaseState();
2212 Slog.i(TAG, "ShortcutManager: throttling counter reset for all users");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002213 }
2214
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002215 @Override
2216 public void onApplicationActive(String packageName, int userId) {
2217 if (DEBUG) {
2218 Slog.d(TAG, "onApplicationActive: package=" + packageName + " userid=" + userId);
2219 }
2220 enforceResetThrottlingPermission();
Makoto Onuki02f338e2016-07-29 09:40:40 -07002221
2222 synchronized (mLock) {
2223 if (!isUserUnlockedL(userId)) {
2224 // This is called by system UI, so no need to throw. Just ignore.
2225 return;
2226 }
2227
2228 getPackageShortcutsLocked(packageName, userId)
2229 .resetRateLimitingForCommandLineNoSaving();
2230 saveUserLocked(userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002231 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002232 }
2233
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002234 // We override this method in unit tests to do a simpler check.
Makoto Onuki634cecb2017-10-13 17:10:48 -07002235 boolean hasShortcutHostPermission(@NonNull String callingPackage, int userId,
2236 int callingPid, int callingUid) {
Makoto Onuki35559d62017-11-06 16:26:32 -08002237 if (canSeeAnyPinnedShortcut(callingPackage, userId, callingPid, callingUid)) {
Makoto Onuki634cecb2017-10-13 17:10:48 -07002238 return true;
2239 }
Makoto Onuki10305202016-07-14 18:14:08 -07002240 final long start = injectElapsedRealtime();
2241 try {
2242 return hasShortcutHostPermissionInner(callingPackage, userId);
2243 } finally {
2244 logDurationStat(Stats.LAUNCHER_PERMISSION_CHECK, start);
2245 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002246 }
2247
Makoto Onuki35559d62017-11-06 16:26:32 -08002248 boolean canSeeAnyPinnedShortcut(@NonNull String callingPackage, int userId,
2249 int callingPid, int callingUid) {
2250 if (injectHasAccessShortcutsPermission(callingPid, callingUid)) {
2251 return true;
2252 }
2253 synchronized (mLock) {
2254 return getUserShortcutsLocked(userId).hasHostPackage(callingPackage);
2255 }
2256 }
2257
Makoto Onuki634cecb2017-10-13 17:10:48 -07002258 /**
2259 * Returns true if the caller has the "ACCESS_SHORTCUTS" permission.
2260 */
Makoto Onuki35559d62017-11-06 16:26:32 -08002261 @VisibleForTesting
2262 boolean injectHasAccessShortcutsPermission(int callingPid, int callingUid) {
Makoto Onuki634cecb2017-10-13 17:10:48 -07002263 return mContext.checkPermission(android.Manifest.permission.ACCESS_SHORTCUTS,
2264 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
2265 }
2266
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002267 // This method is extracted so we can directly call this method from unit tests,
2268 // even when hasShortcutPermission() is overridden.
2269 @VisibleForTesting
Makoto Onuki2d895c32016-12-02 15:48:40 -08002270 boolean hasShortcutHostPermissionInner(@NonNull String packageName, int userId) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002271 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002272 throwIfUserLockedL(userId);
2273
Makoto Onuki31459242016-03-22 11:12:18 -07002274 final ShortcutUser user = getUserShortcutsLocked(userId);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002275
Makoto Onuki2d895c32016-12-02 15:48:40 -08002276 // Always trust the cached component.
Makoto Onuki10305202016-07-14 18:14:08 -07002277 final ComponentName cached = user.getCachedLauncher();
2278 if (cached != null) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08002279 if (cached.getPackageName().equals(packageName)) {
Makoto Onuki10305202016-07-14 18:14:08 -07002280 return true;
2281 }
2282 }
2283 // If the cached one doesn't match, then go ahead
2284
Makoto Onuki2d895c32016-12-02 15:48:40 -08002285 final ComponentName detected = getDefaultLauncher(userId);
Makoto Onuki2e210c42016-03-30 08:30:36 -07002286
Makoto Onuki10305202016-07-14 18:14:08 -07002287 // Update the cache.
2288 user.setLauncher(detected);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002289 if (detected != null) {
2290 if (DEBUG) {
2291 Slog.v(TAG, "Detected launcher: " + detected);
2292 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08002293 return detected.getPackageName().equals(packageName);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002294 } else {
2295 // Default launcher not found.
2296 return false;
2297 }
2298 }
2299 }
2300
Makoto Onuki2d895c32016-12-02 15:48:40 -08002301 @Nullable
2302 ComponentName getDefaultLauncher(@UserIdInt int userId) {
2303 final long start = injectElapsedRealtime();
2304 final long token = injectClearCallingIdentity();
2305 try {
2306 synchronized (mLock) {
2307 throwIfUserLockedL(userId);
2308
2309 final ShortcutUser user = getUserShortcutsLocked(userId);
2310
2311 final List<ResolveInfo> allHomeCandidates = new ArrayList<>();
2312
2313 // Default launcher from package manager.
2314 final long startGetHomeActivitiesAsUser = injectElapsedRealtime();
2315 final ComponentName defaultLauncher = mPackageManagerInternal
2316 .getHomeActivitiesAsUser(allHomeCandidates, userId);
2317 logDurationStat(Stats.GET_DEFAULT_HOME, startGetHomeActivitiesAsUser);
2318
2319 ComponentName detected = null;
2320 if (defaultLauncher != null) {
2321 detected = defaultLauncher;
2322 if (DEBUG) {
2323 Slog.v(TAG, "Default launcher from PM: " + detected);
2324 }
2325 } else {
2326 detected = user.getLastKnownLauncher();
2327
2328 if (detected != null) {
2329 if (injectIsActivityEnabledAndExported(detected, userId)) {
2330 if (DEBUG) {
2331 Slog.v(TAG, "Cached launcher: " + detected);
2332 }
2333 } else {
2334 Slog.w(TAG, "Cached launcher " + detected + " no longer exists");
2335 detected = null;
2336 user.clearLauncher();
2337 }
2338 }
2339 }
2340
2341 if (detected == null) {
2342 // If we reach here, that means it's the first check since the user was created,
2343 // and there's already multiple launchers and there's no default set.
2344 // Find the system one with the highest priority.
2345 // (We need to check the priority too because of FallbackHome in Settings.)
2346 // If there's no system launcher yet, then no one can access shortcuts, until
2347 // the user explicitly
2348 final int size = allHomeCandidates.size();
2349
2350 int lastPriority = Integer.MIN_VALUE;
2351 for (int i = 0; i < size; i++) {
2352 final ResolveInfo ri = allHomeCandidates.get(i);
2353 if (!ri.activityInfo.applicationInfo.isSystemApp()) {
2354 continue;
2355 }
2356 if (DEBUG) {
2357 Slog.d(TAG, String.format("hasShortcutPermissionInner: pkg=%s prio=%d",
2358 ri.activityInfo.getComponentName(), ri.priority));
2359 }
2360 if (ri.priority < lastPriority) {
2361 continue;
2362 }
2363 detected = ri.activityInfo.getComponentName();
2364 lastPriority = ri.priority;
2365 }
2366 }
2367 return detected;
2368 }
2369 } finally {
2370 injectRestoreCallingIdentity(token);
2371 logDurationStat(Stats.GET_DEFAULT_LAUNCHER, start);
2372 }
2373 }
2374
Dianne Hackbornc160fa42017-11-01 16:14:26 -07002375 public void setShortcutHostPackage(@NonNull String type, @Nullable String packageName,
2376 int userId) {
2377 synchronized (mLock) {
2378 throwIfUserLockedL(userId);
2379
2380 final ShortcutUser user = getUserShortcutsLocked(userId);
2381 user.setShortcutHostPackage(type, packageName);
2382 }
2383 }
2384
Makoto Onukicdc78f72016-03-21 15:47:52 -07002385 // === House keeping ===
2386
Makoto Onukib08790c2016-06-23 14:05:46 -07002387 private void cleanUpPackageForAllLoadedUsers(String packageName, @UserIdInt int packageUserId,
2388 boolean appStillExists) {
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002389 synchronized (mLock) {
2390 forEachLoadedUserLocked(user ->
Makoto Onukib08790c2016-06-23 14:05:46 -07002391 cleanUpPackageLocked(packageName, user.getUserId(), packageUserId,
2392 appStillExists));
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002393 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002394 }
2395
Makoto Onuki2e210c42016-03-30 08:30:36 -07002396 /**
2397 * Remove all the information associated with a package. This will really remove all the
2398 * information, including the restore information (i.e. it'll remove packages even if they're
2399 * shadow).
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002400 *
2401 * This is called when an app is uninstalled, or an app gets "clear data"ed.
Makoto Onuki2e210c42016-03-30 08:30:36 -07002402 */
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002403 @VisibleForTesting
Makoto Onukib08790c2016-06-23 14:05:46 -07002404 void cleanUpPackageLocked(String packageName, int owningUserId, int packageUserId,
2405 boolean appStillExists) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002406 final boolean wasUserLoaded = isUserLoadedLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002407
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002408 final ShortcutUser user = getUserShortcutsLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002409 boolean doNotify = false;
2410
2411 // First, remove the package from the package list (if the package is a publisher).
Makoto Onukid99c6f02016-03-28 11:02:54 -07002412 if (packageUserId == owningUserId) {
Makoto Onukic51b2872016-05-04 15:24:50 -07002413 if (user.removePackage(packageName) != null) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002414 doNotify = true;
2415 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07002416 }
Makoto Onukid99c6f02016-03-28 11:02:54 -07002417
Makoto Onukicdc78f72016-03-21 15:47:52 -07002418 // Also remove from the launcher list (if the package is a launcher).
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002419 user.removeLauncher(packageUserId, packageName);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002420
2421 // Then remove pinned shortcuts from all launchers.
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002422 user.forAllLaunchers(l -> l.cleanUpPackage(packageName, packageUserId));
2423
2424 // Now there may be orphan shortcuts because we removed pinned shortcuts at the previous
Makoto Onukicdc78f72016-03-21 15:47:52 -07002425 // step. Remove them too.
Makoto Onukic51b2872016-05-04 15:24:50 -07002426 user.forAllPackages(p -> p.refreshPinnedFlags());
Makoto Onukicdc78f72016-03-21 15:47:52 -07002427
Makoto Onukid99c6f02016-03-28 11:02:54 -07002428 scheduleSaveUser(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002429
2430 if (doNotify) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002431 notifyListeners(packageName, owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002432 }
2433
Makoto Onukib08790c2016-06-23 14:05:46 -07002434 // If the app still exists (i.e. data cleared), we need to re-publish manifest shortcuts.
2435 if (appStillExists && (packageUserId == owningUserId)) {
2436 // This will do the notification and save when needed, so do it after the above
2437 // notifyListeners.
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002438 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07002439 }
2440
Makoto Onukicdc78f72016-03-21 15:47:52 -07002441 if (!wasUserLoaded) {
2442 // Note this will execute the scheduled save.
Makoto Onukid99c6f02016-03-28 11:02:54 -07002443 unloadUserLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002444 }
2445 }
2446
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002447 /**
2448 * Entry point from {@link LauncherApps}.
2449 */
2450 private class LocalService extends ShortcutServiceInternal {
Makoto Onuki2e210c42016-03-30 08:30:36 -07002451
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002452 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002453 public List<ShortcutInfo> getShortcuts(int launcherUserId,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002454 @NonNull String callingPackage, long changedSince,
Makoto Onukiabe84422016-04-07 09:41:19 -07002455 @Nullable String packageName, @Nullable List<String> shortcutIds,
Makoto Onuki99302b52017-03-29 12:42:26 -07002456 @Nullable ComponentName componentName,
Makoto Onuki634cecb2017-10-13 17:10:48 -07002457 int queryFlags, int userId, int callingPid, int callingUid) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002458 final ArrayList<ShortcutInfo> ret = new ArrayList<>();
Makoto Onuki9c850012016-07-26 15:50:50 -07002459
Makoto Onuki20c95f82016-05-11 16:51:01 -07002460 final boolean cloneKeyFieldOnly =
2461 ((queryFlags & ShortcutQuery.FLAG_GET_KEY_FIELDS_ONLY) != 0);
2462 final int cloneFlag = cloneKeyFieldOnly ? ShortcutInfo.CLONE_REMOVE_NON_KEY_INFO
2463 : ShortcutInfo.CLONE_REMOVE_FOR_LAUNCHER;
Makoto Onukiabe84422016-04-07 09:41:19 -07002464 if (packageName == null) {
2465 shortcutIds = null; // LauncherAppsService already threw for it though.
2466 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002467
2468 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002469 throwIfUserLockedL(userId);
2470 throwIfUserLockedL(launcherUserId);
2471
Makoto Onuki2e210c42016-03-30 08:30:36 -07002472 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002473 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002474
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002475 if (packageName != null) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002476 getShortcutsInnerLocked(launcherUserId,
Makoto Onukiabe84422016-04-07 09:41:19 -07002477 callingPackage, packageName, shortcutIds, changedSince,
Makoto Onuki634cecb2017-10-13 17:10:48 -07002478 componentName, queryFlags, userId, ret, cloneFlag,
2479 callingPid, callingUid);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002480 } else {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002481 final List<String> shortcutIdsF = shortcutIds;
2482 getUserShortcutsLocked(userId).forAllPackages(p -> {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002483 getShortcutsInnerLocked(launcherUserId,
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002484 callingPackage, p.getPackageName(), shortcutIdsF, changedSince,
Makoto Onuki634cecb2017-10-13 17:10:48 -07002485 componentName, queryFlags, userId, ret, cloneFlag,
2486 callingPid, callingUid);
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002487 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002488 }
2489 }
Makoto Onukibf563b62017-05-04 10:25:30 -07002490 return setReturnedByServer(ret);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002491 }
2492
Makoto Onukid99c6f02016-03-28 11:02:54 -07002493 private void getShortcutsInnerLocked(int launcherUserId, @NonNull String callingPackage,
Makoto Onukiabe84422016-04-07 09:41:19 -07002494 @Nullable String packageName, @Nullable List<String> shortcutIds, long changedSince,
Makoto Onuki99302b52017-03-29 12:42:26 -07002495 @Nullable ComponentName componentName, int queryFlags,
Makoto Onuki634cecb2017-10-13 17:10:48 -07002496 int userId, ArrayList<ShortcutInfo> ret, int cloneFlag,
2497 int callingPid, int callingUid) {
Makoto Onukiabe84422016-04-07 09:41:19 -07002498 final ArraySet<String> ids = shortcutIds == null ? null
2499 : new ArraySet<>(shortcutIds);
2500
Makoto Onuki35559d62017-11-06 16:26:32 -08002501 final ShortcutUser user = getUserShortcutsLocked(userId);
2502 final ShortcutPackage p = user.getPackageShortcutsIfExists(packageName);
Makoto Onukic51b2872016-05-04 15:24:50 -07002503 if (p == null) {
2504 return; // No need to instantiate ShortcutPackage.
2505 }
Makoto Onuki634cecb2017-10-13 17:10:48 -07002506 final boolean matchDynamic = (queryFlags & ShortcutQuery.FLAG_MATCH_DYNAMIC) != 0;
2507 final boolean matchPinned = (queryFlags & ShortcutQuery.FLAG_MATCH_PINNED) != 0;
2508 final boolean matchManifest = (queryFlags & ShortcutQuery.FLAG_MATCH_MANIFEST) != 0;
2509
Makoto Onuki35559d62017-11-06 16:26:32 -08002510 final boolean canAccessAllShortcuts =
2511 canSeeAnyPinnedShortcut(callingPackage, launcherUserId, callingPid, callingUid);
2512
Makoto Onuki634cecb2017-10-13 17:10:48 -07002513 final boolean getPinnedByAnyLauncher =
Makoto Onuki35559d62017-11-06 16:26:32 -08002514 canAccessAllShortcuts &&
2515 ((queryFlags & ShortcutQuery.FLAG_MATCH_PINNED_BY_ANY_LAUNCHER) != 0);
Makoto Onukic51b2872016-05-04 15:24:50 -07002516
2517 p.findAll(ret,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002518 (ShortcutInfo si) -> {
2519 if (si.getLastChangedTimestamp() < changedSince) {
2520 return false;
2521 }
Makoto Onukiabe84422016-04-07 09:41:19 -07002522 if (ids != null && !ids.contains(si.getId())) {
2523 return false;
2524 }
Makoto Onuki85694522016-05-04 12:53:37 -07002525 if (componentName != null) {
Makoto Onuki9fd90192017-01-06 18:31:03 +00002526 if (si.getActivity() != null
2527 && !si.getActivity().equals(componentName)) {
Makoto Onuki85694522016-05-04 12:53:37 -07002528 return false;
2529 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002530 }
Makoto Onuki634cecb2017-10-13 17:10:48 -07002531 if (matchDynamic && si.isDynamic()) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002532 return true;
2533 }
Makoto Onuki35559d62017-11-06 16:26:32 -08002534 if ((matchPinned || getPinnedByAnyLauncher) && si.isPinned()) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002535 return true;
2536 }
Makoto Onuki634cecb2017-10-13 17:10:48 -07002537 if (matchManifest && si.isDeclaredInManifest()) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002538 return true;
2539 }
2540 return false;
Makoto Onuki634cecb2017-10-13 17:10:48 -07002541 }, cloneFlag, callingPackage, launcherUserId, getPinnedByAnyLauncher);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002542 }
2543
2544 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002545 public boolean isPinnedByCaller(int launcherUserId, @NonNull String callingPackage,
2546 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2547 Preconditions.checkStringNotEmpty(packageName, "packageName");
2548 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
2549
2550 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002551 throwIfUserLockedL(userId);
2552 throwIfUserLockedL(launcherUserId);
2553
Makoto Onuki2e210c42016-03-30 08:30:36 -07002554 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002555 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002556
Makoto Onukid99c6f02016-03-28 11:02:54 -07002557 final ShortcutInfo si = getShortcutInfoLocked(
Makoto Onuki634cecb2017-10-13 17:10:48 -07002558 launcherUserId, callingPackage, packageName, shortcutId, userId,
2559 /*getPinnedByAnyLauncher=*/ false);
Makoto Onukid99c6f02016-03-28 11:02:54 -07002560 return si != null && si.isPinned();
2561 }
2562 }
2563
Makoto Onuki2e210c42016-03-30 08:30:36 -07002564 private ShortcutInfo getShortcutInfoLocked(
Makoto Onukid99c6f02016-03-28 11:02:54 -07002565 int launcherUserId, @NonNull String callingPackage,
Makoto Onuki634cecb2017-10-13 17:10:48 -07002566 @NonNull String packageName, @NonNull String shortcutId, int userId,
2567 boolean getPinnedByAnyLauncher) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002568 Preconditions.checkStringNotEmpty(packageName, "packageName");
2569 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
2570
Makoto Onuki02f338e2016-07-29 09:40:40 -07002571 throwIfUserLockedL(userId);
2572 throwIfUserLockedL(launcherUserId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002573
Makoto Onukic51b2872016-05-04 15:24:50 -07002574 final ShortcutPackage p = getUserShortcutsLocked(userId)
2575 .getPackageShortcutsIfExists(packageName);
2576 if (p == null) {
2577 return null;
2578 }
2579
Makoto Onukid99c6f02016-03-28 11:02:54 -07002580 final ArrayList<ShortcutInfo> list = new ArrayList<>(1);
Makoto Onukic51b2872016-05-04 15:24:50 -07002581 p.findAll(list,
Makoto Onukid99c6f02016-03-28 11:02:54 -07002582 (ShortcutInfo si) -> shortcutId.equals(si.getId()),
Makoto Onuki634cecb2017-10-13 17:10:48 -07002583 /* clone flags=*/ 0, callingPackage, launcherUserId, getPinnedByAnyLauncher);
Makoto Onukid99c6f02016-03-28 11:02:54 -07002584 return list.size() == 0 ? null : list.get(0);
2585 }
2586
2587 @Override
2588 public void pinShortcuts(int launcherUserId,
2589 @NonNull String callingPackage, @NonNull String packageName,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002590 @NonNull List<String> shortcutIds, int userId) {
2591 // Calling permission must be checked by LauncherAppsImpl.
2592 Preconditions.checkStringNotEmpty(packageName, "packageName");
2593 Preconditions.checkNotNull(shortcutIds, "shortcutIds");
2594
2595 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002596 throwIfUserLockedL(userId);
2597 throwIfUserLockedL(launcherUserId);
2598
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002599 final ShortcutLauncher launcher =
Makoto Onuki2e210c42016-03-30 08:30:36 -07002600 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId);
Makoto Onukic51b2872016-05-04 15:24:50 -07002601 launcher.attemptToRestoreIfNeededAndSave();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002602
Makoto Onukia4f89b12017-10-05 10:37:55 -07002603 launcher.pinShortcuts(userId, packageName, shortcutIds, /*forPinRequest=*/ false);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002604 }
Makoto Onuki39686e82016-04-13 18:03:00 -07002605 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07002606
2607 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002608 }
2609
2610 @Override
Makoto Onuki440a1ea2016-07-20 14:21:18 -07002611 public Intent[] createShortcutIntents(int launcherUserId,
Makoto Onukid99c6f02016-03-28 11:02:54 -07002612 @NonNull String callingPackage,
Makoto Onuki634cecb2017-10-13 17:10:48 -07002613 @NonNull String packageName, @NonNull String shortcutId, int userId,
2614 int callingPid, int callingUid) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002615 // Calling permission must be checked by LauncherAppsImpl.
Makoto Onuki43204b82016-03-08 16:16:44 -08002616 Preconditions.checkStringNotEmpty(packageName, "packageName can't be empty");
2617 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId can't be empty");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002618
2619 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002620 throwIfUserLockedL(userId);
2621 throwIfUserLockedL(launcherUserId);
2622
Makoto Onuki2e210c42016-03-30 08:30:36 -07002623 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002624 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002625
Makoto Onuki634cecb2017-10-13 17:10:48 -07002626 final boolean getPinnedByAnyLauncher =
Makoto Onuki35559d62017-11-06 16:26:32 -08002627 canSeeAnyPinnedShortcut(callingPackage, launcherUserId,
2628 callingPid, callingUid);
Makoto Onuki634cecb2017-10-13 17:10:48 -07002629
Makoto Onukid99c6f02016-03-28 11:02:54 -07002630 // Make sure the shortcut is actually visible to the launcher.
2631 final ShortcutInfo si = getShortcutInfoLocked(
Makoto Onuki634cecb2017-10-13 17:10:48 -07002632 launcherUserId, callingPackage, packageName, shortcutId, userId,
2633 getPinnedByAnyLauncher);
Makoto Onukid99c6f02016-03-28 11:02:54 -07002634 // "si == null" should suffice here, but check the flags too just to make sure.
Makoto Onuki35559d62017-11-06 16:26:32 -08002635 if (si == null || !si.isEnabled() || !(si.isAlive() || getPinnedByAnyLauncher)) {
Makoto Onuki83f6d2d2016-07-11 14:30:19 -07002636 Log.e(TAG, "Shortcut " + shortcutId + " does not exist or disabled");
Makoto Onukid99c6f02016-03-28 11:02:54 -07002637 return null;
2638 }
Makoto Onuki440a1ea2016-07-20 14:21:18 -07002639 return si.getIntents();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002640 }
2641 }
2642
2643 @Override
2644 public void addListener(@NonNull ShortcutChangeListener listener) {
2645 synchronized (mLock) {
2646 mListeners.add(Preconditions.checkNotNull(listener));
2647 }
2648 }
Makoto Onuki55046222016-03-08 10:49:47 -08002649
2650 @Override
Makoto Onukiabe84422016-04-07 09:41:19 -07002651 public int getShortcutIconResId(int launcherUserId, @NonNull String callingPackage,
2652 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2653 Preconditions.checkNotNull(callingPackage, "callingPackage");
2654 Preconditions.checkNotNull(packageName, "packageName");
2655 Preconditions.checkNotNull(shortcutId, "shortcutId");
Makoto Onuki55046222016-03-08 10:49:47 -08002656
2657 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002658 throwIfUserLockedL(userId);
2659 throwIfUserLockedL(launcherUserId);
2660
Makoto Onuki2e210c42016-03-30 08:30:36 -07002661 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002662 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002663
Makoto Onukic51b2872016-05-04 15:24:50 -07002664 final ShortcutPackage p = getUserShortcutsLocked(userId)
2665 .getPackageShortcutsIfExists(packageName);
2666 if (p == null) {
2667 return 0;
2668 }
2669
2670 final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId);
Makoto Onuki55046222016-03-08 10:49:47 -08002671 return (shortcutInfo != null && shortcutInfo.hasIconResource())
2672 ? shortcutInfo.getIconResourceId() : 0;
2673 }
2674 }
2675
2676 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002677 public ParcelFileDescriptor getShortcutIconFd(int launcherUserId,
Makoto Onukiabe84422016-04-07 09:41:19 -07002678 @NonNull String callingPackage, @NonNull String packageName,
2679 @NonNull String shortcutId, int userId) {
2680 Preconditions.checkNotNull(callingPackage, "callingPackage");
2681 Preconditions.checkNotNull(packageName, "packageName");
2682 Preconditions.checkNotNull(shortcutId, "shortcutId");
Makoto Onuki55046222016-03-08 10:49:47 -08002683
2684 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002685 throwIfUserLockedL(userId);
2686 throwIfUserLockedL(launcherUserId);
2687
Makoto Onuki2e210c42016-03-30 08:30:36 -07002688 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002689 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002690
Makoto Onukic51b2872016-05-04 15:24:50 -07002691 final ShortcutPackage p = getUserShortcutsLocked(userId)
2692 .getPackageShortcutsIfExists(packageName);
2693 if (p == null) {
2694 return null;
2695 }
2696
2697 final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId);
Makoto Onuki55046222016-03-08 10:49:47 -08002698 if (shortcutInfo == null || !shortcutInfo.hasIconFile()) {
2699 return null;
2700 }
Makoto Onuki475c3652017-05-08 14:29:03 -07002701 final String path = mShortcutBitmapSaver.getBitmapPathMayWaitLocked(shortcutInfo);
2702 if (path == null) {
2703 Slog.w(TAG, "null bitmap detected in getShortcutIconFd()");
2704 return null;
2705 }
Makoto Onuki55046222016-03-08 10:49:47 -08002706 try {
2707 return ParcelFileDescriptor.open(
Makoto Onuki475c3652017-05-08 14:29:03 -07002708 new File(path),
Makoto Onuki55046222016-03-08 10:49:47 -08002709 ParcelFileDescriptor.MODE_READ_ONLY);
2710 } catch (FileNotFoundException e) {
Makoto Onuki475c3652017-05-08 14:29:03 -07002711 Slog.e(TAG, "Icon file not found: " + path);
Makoto Onuki55046222016-03-08 10:49:47 -08002712 return null;
2713 }
2714 }
2715 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002716
2717 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002718 public boolean hasShortcutHostPermission(int launcherUserId,
Makoto Onuki634cecb2017-10-13 17:10:48 -07002719 @NonNull String callingPackage, int callingPid, int callingUid) {
2720 return ShortcutService.this.hasShortcutHostPermission(callingPackage, launcherUserId,
2721 callingPid, callingUid);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002722 }
Sunny Goyal87a563e2017-01-01 19:42:45 -08002723
2724 @Override
Dianne Hackbornc160fa42017-11-01 16:14:26 -07002725 public void setShortcutHostPackage(@NonNull String type, @Nullable String packageName,
2726 int userId) {
2727 ShortcutService.this.setShortcutHostPackage(type, packageName, userId);
2728 }
2729
2730 @Override
Sunny Goyal87a563e2017-01-01 19:42:45 -08002731 public boolean requestPinAppWidget(@NonNull String callingPackage,
Sunny Goyal4ad6b572017-02-28 11:11:51 -08002732 @NonNull AppWidgetProviderInfo appWidget, @Nullable Bundle extras,
2733 @Nullable IntentSender resultIntent, int userId) {
Sunny Goyal87a563e2017-01-01 19:42:45 -08002734 Preconditions.checkNotNull(appWidget);
Sunny Goyal4ad6b572017-02-28 11:11:51 -08002735 return requestPinItem(callingPackage, userId, null, appWidget, extras, resultIntent);
Sunny Goyal87a563e2017-01-01 19:42:45 -08002736 }
Sunny Goyal7f7372a2017-01-24 11:53:54 -08002737
2738 @Override
2739 public boolean isRequestPinItemSupported(int callingUserId, int requestType) {
2740 return ShortcutService.this.isRequestPinItemSupported(callingUserId, requestType);
2741 }
Tony Maked6ef622017-12-07 16:36:16 +00002742
2743 @Override
2744 public boolean isForegroundDefaultLauncher(@NonNull String callingPackage, int callingUid) {
2745 Preconditions.checkNotNull(callingPackage);
2746
2747 final int userId = UserHandle.getUserId(callingUid);
2748 final ComponentName defaultLauncher = getDefaultLauncher(userId);
2749 if (defaultLauncher == null) {
2750 return false;
2751 }
2752 if (!callingPackage.equals(defaultLauncher.getPackageName())) {
2753 return false;
2754 }
2755 synchronized (mLock) {
2756 if (!isUidForegroundLocked(callingUid)) {
2757 return false;
2758 }
2759 }
2760 return true;
2761 }
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002762 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002763
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002764 final BroadcastReceiver mReceiver = new BroadcastReceiver() {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002765 @Override
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002766 public void onReceive(Context context, Intent intent) {
2767 if (!mBootCompleted.get()) {
2768 return; // Boot not completed, ignore the broadcast.
2769 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07002770 try {
2771 if (Intent.ACTION_LOCALE_CHANGED.equals(intent.getAction())) {
2772 handleLocaleChanged();
2773 }
2774 } catch (Exception e) {
2775 wtf("Exception in mReceiver.onReceive", e);
Makoto Onukic51b2872016-05-04 15:24:50 -07002776 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002777 }
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002778 };
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002779
Makoto Onuki157b1622016-06-02 16:13:10 -07002780 void handleLocaleChanged() {
2781 if (DEBUG) {
2782 Slog.d(TAG, "handleLocaleChanged");
2783 }
2784 scheduleSaveBaseState();
2785
Makoto Onuki02f338e2016-07-29 09:40:40 -07002786 synchronized (mLock) {
2787 final long token = injectClearCallingIdentity();
2788 try {
2789 forEachLoadedUserLocked(user -> user.detectLocaleChange());
2790 } finally {
2791 injectRestoreCallingIdentity(token);
2792 }
Makoto Onuki157b1622016-06-02 16:13:10 -07002793 }
2794 }
2795
Makoto Onukif34c3082016-07-13 10:25:25 -07002796 /**
2797 * Package event callbacks.
2798 */
2799 @VisibleForTesting
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002800 final BroadcastReceiver mPackageMonitor = new BroadcastReceiver() {
Makoto Onukif34c3082016-07-13 10:25:25 -07002801 @Override
2802 public void onReceive(Context context, Intent intent) {
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002803 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
2804 if (userId == UserHandle.USER_NULL) {
2805 Slog.w(TAG, "Intent broadcast does not contain user handle: " + intent);
2806 return;
2807 }
2808
2809 final String action = intent.getAction();
2810
2811 // This is normally called on Handler, so clearCallingIdentity() isn't needed,
2812 // but we still check it in unit tests.
Makoto Onukif34c3082016-07-13 10:25:25 -07002813 final long token = injectClearCallingIdentity();
2814 try {
Makoto Onuki10305202016-07-14 18:14:08 -07002815 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002816 if (!isUserUnlockedL(userId)) {
2817 if (DEBUG) {
2818 Slog.d(TAG, "Ignoring package broadcast " + action
2819 + " for locked/stopped user " + userId);
2820 }
2821 return;
2822 }
2823
2824 // Whenever we get one of those package broadcasts, or get
2825 // ACTION_PREFERRED_ACTIVITY_CHANGED, we purge the default launcher cache.
Makoto Onuki10305202016-07-14 18:14:08 -07002826 final ShortcutUser user = getUserShortcutsLocked(userId);
2827 user.clearLauncher();
2828 }
2829 if (Intent.ACTION_PREFERRED_ACTIVITY_CHANGED.equals(action)) {
2830 // Nothing farther to do.
2831 return;
2832 }
2833
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002834 final Uri intentUri = intent.getData();
2835 final String packageName = (intentUri != null) ? intentUri.getSchemeSpecificPart()
2836 : null;
2837 if (packageName == null) {
2838 Slog.w(TAG, "Intent broadcast does not contain package name: " + intent);
2839 return;
2840 }
2841
2842 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
2843
2844 switch (action) {
2845 case Intent.ACTION_PACKAGE_ADDED:
2846 if (replacing) {
2847 handlePackageUpdateFinished(packageName, userId);
2848 } else {
2849 handlePackageAdded(packageName, userId);
2850 }
2851 break;
2852 case Intent.ACTION_PACKAGE_REMOVED:
2853 if (!replacing) {
2854 handlePackageRemoved(packageName, userId);
2855 }
2856 break;
2857 case Intent.ACTION_PACKAGE_CHANGED:
2858 handlePackageChanged(packageName, userId);
2859
2860 break;
2861 case Intent.ACTION_PACKAGE_DATA_CLEARED:
2862 handlePackageDataCleared(packageName, userId);
2863 break;
2864 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07002865 } catch (Exception e) {
2866 wtf("Exception in mPackageMonitor.onReceive", e);
Makoto Onukif34c3082016-07-13 10:25:25 -07002867 } finally {
2868 injectRestoreCallingIdentity(token);
Makoto Onukia2241832016-07-06 13:28:37 -07002869 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07002870 }
Makoto Onukif34c3082016-07-13 10:25:25 -07002871 };
Makoto Onukicdc78f72016-03-21 15:47:52 -07002872
Makoto Onuki0acbb142016-03-22 17:02:57 -07002873 /**
Makoto Onuki39686e82016-04-13 18:03:00 -07002874 * Called when a user is unlocked.
2875 * - Check all known packages still exist, and otherwise perform cleanup.
2876 * - If a package still exists, check the version code. If it's been updated, may need to
Makoto Onukib08790c2016-06-23 14:05:46 -07002877 * update timestamps of its shortcuts.
Makoto Onuki0acbb142016-03-22 17:02:57 -07002878 */
Makoto Onukid99c6f02016-03-28 11:02:54 -07002879 @VisibleForTesting
Makoto Onuki39686e82016-04-13 18:03:00 -07002880 void checkPackageChanges(@UserIdInt int ownerUserId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07002881 if (DEBUG) {
Makoto Onuki39686e82016-04-13 18:03:00 -07002882 Slog.d(TAG, "checkPackageChanges() ownerUserId=" + ownerUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002883 }
Makoto Onukib08790c2016-06-23 14:05:46 -07002884 if (injectIsSafeModeEnabled()) {
2885 Slog.i(TAG, "Safe mode, skipping checkPackageChanges()");
2886 return;
2887 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07002888
Makoto Onuki22fcc682016-05-17 14:52:19 -07002889 final long start = injectElapsedRealtime();
2890 try {
2891 final ArrayList<PackageWithUser> gonePackages = new ArrayList<>();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002892
Makoto Onuki22fcc682016-05-17 14:52:19 -07002893 synchronized (mLock) {
2894 final ShortcutUser user = getUserShortcutsLocked(ownerUserId);
2895
2896 // Find packages that have been uninstalled.
2897 user.forAllPackageItems(spi -> {
2898 if (spi.getPackageInfo().isShadow()) {
2899 return; // Don't delete shadow information.
2900 }
2901 if (!isPackageInstalled(spi.getPackageName(), spi.getPackageUserId())) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002902 if (DEBUG) {
2903 Slog.d(TAG, "Uninstalled: " + spi.getPackageName()
2904 + " user " + spi.getPackageUserId());
2905 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002906 gonePackages.add(PackageWithUser.of(spi));
2907 }
2908 });
2909 if (gonePackages.size() > 0) {
2910 for (int i = gonePackages.size() - 1; i >= 0; i--) {
2911 final PackageWithUser pu = gonePackages.get(i);
Makoto Onukib08790c2016-06-23 14:05:46 -07002912 cleanUpPackageLocked(pu.packageName, ownerUserId, pu.userId,
2913 /* appStillExists = */ false);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002914 }
Makoto Onukid99c6f02016-03-28 11:02:54 -07002915 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002916
Makoto Onuki248a0ef2016-11-03 15:59:01 -07002917 rescanUpdatedPackagesLocked(ownerUserId, user.getLastAppScanTime());
Makoto Onuki0acbb142016-03-22 17:02:57 -07002918 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002919 } finally {
2920 logDurationStat(Stats.CHECK_PACKAGE_CHANGES, start);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002921 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002922 verifyStates();
Makoto Onukicdc78f72016-03-21 15:47:52 -07002923 }
2924
Makoto Onuki248a0ef2016-11-03 15:59:01 -07002925 private void rescanUpdatedPackagesLocked(@UserIdInt int userId, long lastScanTime) {
Makoto Onuki377b7972016-08-09 14:43:55 -07002926 final ShortcutUser user = getUserShortcutsLocked(userId);
2927
Makoto Onuki33663282016-08-22 16:19:04 -07002928 // Note after each OTA, we'll need to rescan all system apps, as their lastUpdateTime
2929 // is not reliable.
Makoto Onuki377b7972016-08-09 14:43:55 -07002930 final long now = injectCurrentTimeMillis();
Makoto Onuki33663282016-08-22 16:19:04 -07002931 final boolean afterOta =
2932 !injectBuildFingerprint().equals(user.getLastAppScanOsFingerprint());
Makoto Onuki377b7972016-08-09 14:43:55 -07002933
2934 // Then for each installed app, publish manifest shortcuts when needed.
Makoto Onuki33663282016-08-22 16:19:04 -07002935 forUpdatedPackages(userId, lastScanTime, afterOta, ai -> {
Makoto Onuki377b7972016-08-09 14:43:55 -07002936 user.attemptToRestoreIfNeededAndSave(this, ai.packageName, userId);
Makoto Onuki248a0ef2016-11-03 15:59:01 -07002937
2938 user.rescanPackageIfNeeded(ai.packageName, /* forceRescan= */ true);
Makoto Onuki377b7972016-08-09 14:43:55 -07002939 });
2940
2941 // Write the time just before the scan, because there may be apps that have just
2942 // been updated, and we want to catch them in the next time.
2943 user.setLastAppScanTime(now);
Makoto Onuki33663282016-08-22 16:19:04 -07002944 user.setLastAppScanOsFingerprint(injectBuildFingerprint());
Makoto Onuki377b7972016-08-09 14:43:55 -07002945 scheduleSaveUser(userId);
2946 }
2947
Makoto Onuki0acbb142016-03-22 17:02:57 -07002948 private void handlePackageAdded(String packageName, @UserIdInt int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07002949 if (DEBUG) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07002950 Slog.d(TAG, String.format("handlePackageAdded: %s user=%d", packageName, userId));
2951 }
2952 synchronized (mLock) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002953 final ShortcutUser user = getUserShortcutsLocked(userId);
2954 user.attemptToRestoreIfNeededAndSave(this, packageName, userId);
Makoto Onuki64183d52016-08-08 14:11:34 -07002955 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002956 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002957 verifyStates();
Makoto Onuki0acbb142016-03-22 17:02:57 -07002958 }
2959
2960 private void handlePackageUpdateFinished(String packageName, @UserIdInt int userId) {
Makoto Onuki905e8852016-03-28 10:40:58 -07002961 if (DEBUG) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002962 Slog.d(TAG, String.format("handlePackageUpdateFinished: %s user=%d",
2963 packageName, userId));
Makoto Onuki0acbb142016-03-22 17:02:57 -07002964 }
2965 synchronized (mLock) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002966 final ShortcutUser user = getUserShortcutsLocked(userId);
2967 user.attemptToRestoreIfNeededAndSave(this, packageName, userId);
Makoto Onuki39686e82016-04-13 18:03:00 -07002968
Makoto Onuki22fcc682016-05-17 14:52:19 -07002969 if (isPackageInstalled(packageName, userId)) {
Makoto Onuki64183d52016-08-08 14:11:34 -07002970 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onuki39686e82016-04-13 18:03:00 -07002971 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07002972 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002973 verifyStates();
Makoto Onuki0acbb142016-03-22 17:02:57 -07002974 }
2975
Makoto Onuki2e210c42016-03-30 08:30:36 -07002976 private void handlePackageRemoved(String packageName, @UserIdInt int packageUserId) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07002977 if (DEBUG) {
Makoto Onuki2e210c42016-03-30 08:30:36 -07002978 Slog.d(TAG, String.format("handlePackageRemoved: %s user=%d", packageName,
2979 packageUserId));
Makoto Onukicdc78f72016-03-21 15:47:52 -07002980 }
Makoto Onukib08790c2016-06-23 14:05:46 -07002981 cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ false);
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002982
2983 verifyStates();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002984 }
2985
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002986 private void handlePackageDataCleared(String packageName, int packageUserId) {
2987 if (DEBUG) {
2988 Slog.d(TAG, String.format("handlePackageDataCleared: %s user=%d", packageName,
2989 packageUserId));
Makoto Onukicdc78f72016-03-21 15:47:52 -07002990 }
Makoto Onukib08790c2016-06-23 14:05:46 -07002991 cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ true);
2992
2993 verifyStates();
2994 }
2995
2996 private void handlePackageChanged(String packageName, int packageUserId) {
Makoto Onuki82fb2eb2017-03-31 16:58:26 -07002997 if (!isPackageInstalled(packageName, packageUserId)) {
2998 // Probably disabled, which is the same thing as uninstalled.
2999 handlePackageRemoved(packageName, packageUserId);
3000 return;
3001 }
Makoto Onukib08790c2016-06-23 14:05:46 -07003002 if (DEBUG) {
3003 Slog.d(TAG, String.format("handlePackageChanged: %s user=%d", packageName,
3004 packageUserId));
3005 }
3006
3007 // Activities may be disabled or enabled. Just rescan the package.
3008 synchronized (mLock) {
3009 final ShortcutUser user = getUserShortcutsLocked(packageUserId);
3010
Makoto Onuki4e6cef42016-07-13 16:14:01 -07003011 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07003012 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07003013
3014 verifyStates();
Makoto Onukicdc78f72016-03-21 15:47:52 -07003015 }
3016
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003017 // === PackageManager interaction ===
Makoto Onuki0acbb142016-03-22 17:02:57 -07003018
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003019 /**
3020 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
3021 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07003022 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003023 final PackageInfo getPackageInfoWithSignatures(String packageName, @UserIdInt int userId) {
3024 return getPackageInfo(packageName, userId, true);
Makoto Onuki0acbb142016-03-22 17:02:57 -07003025 }
3026
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003027 /**
3028 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
3029 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07003030 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003031 final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId) {
3032 return getPackageInfo(packageName, userId, false);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003033 }
3034
Makoto Onuki905e8852016-03-28 10:40:58 -07003035 int injectGetPackageUid(@NonNull String packageName, @UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003036 final long token = injectClearCallingIdentity();
Makoto Onuki905e8852016-03-28 10:40:58 -07003037 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003038 return mIPackageManager.getPackageUid(packageName, PACKAGE_MATCH_FLAGS, userId);
Makoto Onuki905e8852016-03-28 10:40:58 -07003039 } catch (RemoteException e) {
3040 // Shouldn't happen.
3041 Slog.wtf(TAG, "RemoteException", e);
3042 return -1;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003043 } finally {
3044 injectRestoreCallingIdentity(token);
Makoto Onuki905e8852016-03-28 10:40:58 -07003045 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07003046 }
3047
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003048 /**
3049 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
3050 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07003051 @Nullable
Makoto Onuki0acbb142016-03-22 17:02:57 -07003052 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003053 final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId,
3054 boolean getSignatures) {
3055 return isInstalledOrNull(injectPackageInfoWithUninstalled(
3056 packageName, userId, getSignatures));
3057 }
3058
3059 /**
3060 * Do not use directly; this returns uninstalled packages too.
3061 */
3062 @Nullable
3063 @VisibleForTesting
3064 PackageInfo injectPackageInfoWithUninstalled(String packageName, @UserIdInt int userId,
Makoto Onuki0acbb142016-03-22 17:02:57 -07003065 boolean getSignatures) {
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07003066 final long start = injectElapsedRealtime();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003067 final long token = injectClearCallingIdentity();
Makoto Onuki0acbb142016-03-22 17:02:57 -07003068 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003069 return mIPackageManager.getPackageInfo(
3070 packageName, PACKAGE_MATCH_FLAGS
3071 | (getSignatures ? PackageManager.GET_SIGNATURES : 0), userId);
Makoto Onuki0acbb142016-03-22 17:02:57 -07003072 } catch (RemoteException e) {
3073 // Shouldn't happen.
3074 Slog.wtf(TAG, "RemoteException", e);
3075 return null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003076 } finally {
3077 injectRestoreCallingIdentity(token);
Makoto Onuki2e210c42016-03-30 08:30:36 -07003078
3079 logDurationStat(
3080 (getSignatures ? Stats.GET_PACKAGE_INFO_WITH_SIG : Stats.GET_PACKAGE_INFO),
3081 start);
Makoto Onuki0acbb142016-03-22 17:02:57 -07003082 }
3083 }
3084
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003085 /**
3086 * Returns {@link ApplicationInfo} unless it's uninstalled or disabled.
3087 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07003088 @Nullable
Makoto Onuki905e8852016-03-28 10:40:58 -07003089 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003090 final ApplicationInfo getApplicationInfo(String packageName, @UserIdInt int userId) {
3091 return isInstalledOrNull(injectApplicationInfoWithUninstalled(packageName, userId));
3092 }
3093
3094 /**
3095 * Do not use directly; this returns uninstalled packages too.
3096 */
3097 @Nullable
3098 @VisibleForTesting
3099 ApplicationInfo injectApplicationInfoWithUninstalled(
3100 String packageName, @UserIdInt int userId) {
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07003101 final long start = injectElapsedRealtime();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003102 final long token = injectClearCallingIdentity();
Makoto Onuki905e8852016-03-28 10:40:58 -07003103 try {
3104 return mIPackageManager.getApplicationInfo(packageName, PACKAGE_MATCH_FLAGS, userId);
3105 } catch (RemoteException e) {
3106 // Shouldn't happen.
3107 Slog.wtf(TAG, "RemoteException", e);
3108 return null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003109 } finally {
3110 injectRestoreCallingIdentity(token);
Makoto Onuki2e210c42016-03-30 08:30:36 -07003111
3112 logDurationStat(Stats.GET_APPLICATION_INFO, start);
Makoto Onuki905e8852016-03-28 10:40:58 -07003113 }
3114 }
3115
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003116 /**
3117 * Returns {@link ActivityInfo} with its metadata unless it's uninstalled or disabled.
3118 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07003119 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003120 final ActivityInfo getActivityInfoWithMetadata(ComponentName activity, @UserIdInt int userId) {
3121 return isInstalledOrNull(injectGetActivityInfoWithMetadataWithUninstalled(
3122 activity, userId));
3123 }
3124
3125 /**
3126 * Do not use directly; this returns uninstalled packages too.
3127 */
3128 @Nullable
3129 @VisibleForTesting
3130 ActivityInfo injectGetActivityInfoWithMetadataWithUninstalled(
3131 ComponentName activity, @UserIdInt int userId) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07003132 final long start = injectElapsedRealtime();
3133 final long token = injectClearCallingIdentity();
3134 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07003135 return mIPackageManager.getActivityInfo(activity,
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003136 (PACKAGE_MATCH_FLAGS | PackageManager.GET_META_DATA), userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003137 } catch (RemoteException e) {
3138 // Shouldn't happen.
3139 Slog.wtf(TAG, "RemoteException", e);
3140 return null;
3141 } finally {
3142 injectRestoreCallingIdentity(token);
3143
Makoto Onukib08790c2016-06-23 14:05:46 -07003144 logDurationStat(Stats.GET_ACTIVITY_WITH_METADATA, start);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003145 }
3146 }
3147
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003148 /**
3149 * Return all installed and enabled packages.
3150 */
3151 @NonNull
Makoto Onuki22fcc682016-05-17 14:52:19 -07003152 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003153 final List<PackageInfo> getInstalledPackages(@UserIdInt int userId) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07003154 final long start = injectElapsedRealtime();
3155 final long token = injectClearCallingIdentity();
3156 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003157 final List<PackageInfo> all = injectGetPackagesWithUninstalled(userId);
3158
3159 all.removeIf(PACKAGE_NOT_INSTALLED);
3160
3161 return all;
Makoto Onuki22fcc682016-05-17 14:52:19 -07003162 } catch (RemoteException e) {
3163 // Shouldn't happen.
3164 Slog.wtf(TAG, "RemoteException", e);
3165 return null;
3166 } finally {
3167 injectRestoreCallingIdentity(token);
3168
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003169 logDurationStat(Stats.GET_INSTALLED_PACKAGES, start);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003170 }
3171 }
3172
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003173 /**
3174 * Do not use directly; this returns uninstalled packages too.
3175 */
3176 @NonNull
3177 @VisibleForTesting
3178 List<PackageInfo> injectGetPackagesWithUninstalled(@UserIdInt int userId)
3179 throws RemoteException {
3180 final ParceledListSlice<PackageInfo> parceledList =
3181 mIPackageManager.getInstalledPackages(PACKAGE_MATCH_FLAGS, userId);
3182 if (parceledList == null) {
3183 return Collections.emptyList();
3184 }
3185 return parceledList.getList();
3186 }
3187
Makoto Onuki33663282016-08-22 16:19:04 -07003188 private void forUpdatedPackages(@UserIdInt int userId, long lastScanTime, boolean afterOta,
Makoto Onuki22fcc682016-05-17 14:52:19 -07003189 Consumer<ApplicationInfo> callback) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003190 if (DEBUG) {
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003191 Slog.d(TAG, "forUpdatedPackages for user " + userId + ", lastScanTime=" + lastScanTime
3192 + " afterOta=" + afterOta);
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003193 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003194 final List<PackageInfo> list = getInstalledPackages(userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003195 for (int i = list.size() - 1; i >= 0; i--) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003196 final PackageInfo pi = list.get(i);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003197
Makoto Onuki64183d52016-08-08 14:11:34 -07003198 // If the package has been updated since the last scan time, then scan it.
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003199 // Also if it's right after an OTA, always re-scan all apps anyway, since the
3200 // shortcut parser might have changed.
3201 if (afterOta || (pi.lastUpdateTime >= lastScanTime)) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003202 if (DEBUG) {
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003203 Slog.d(TAG, "Found updated package " + pi.packageName
3204 + " updateTime=" + pi.lastUpdateTime);
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003205 }
3206 callback.accept(pi.applicationInfo);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003207 }
3208 }
3209 }
3210
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003211 private boolean isApplicationFlagSet(@NonNull String packageName, int userId, int flags) {
3212 final ApplicationInfo ai = injectApplicationInfoWithUninstalled(packageName, userId);
Makoto Onuki905e8852016-03-28 10:40:58 -07003213 return (ai != null) && ((ai.flags & flags) == flags);
3214 }
3215
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003216 private static boolean isInstalled(@Nullable ApplicationInfo ai) {
Makoto Onuki82fb2eb2017-03-31 16:58:26 -07003217 return (ai != null) && ai.enabled && (ai.flags & ApplicationInfo.FLAG_INSTALLED) != 0;
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003218 }
3219
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08003220 private static boolean isEphemeralApp(@Nullable ApplicationInfo ai) {
Svetoslav Ganov096d3042017-01-30 16:34:13 -08003221 return (ai != null) && ai.isInstantApp();
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08003222 }
3223
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003224 private static boolean isInstalled(@Nullable PackageInfo pi) {
3225 return (pi != null) && isInstalled(pi.applicationInfo);
3226 }
3227
3228 private static boolean isInstalled(@Nullable ActivityInfo ai) {
3229 return (ai != null) && isInstalled(ai.applicationInfo);
3230 }
3231
3232 private static ApplicationInfo isInstalledOrNull(ApplicationInfo ai) {
3233 return isInstalled(ai) ? ai : null;
3234 }
3235
3236 private static PackageInfo isInstalledOrNull(PackageInfo pi) {
3237 return isInstalled(pi) ? pi : null;
3238 }
3239
3240 private static ActivityInfo isInstalledOrNull(ActivityInfo ai) {
3241 return isInstalled(ai) ? ai : null;
3242 }
3243
Makoto Onuki2e210c42016-03-30 08:30:36 -07003244 boolean isPackageInstalled(String packageName, int userId) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003245 return getApplicationInfo(packageName, userId) != null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003246 }
3247
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08003248 boolean isEphemeralApp(String packageName, int userId) {
3249 return isEphemeralApp(getApplicationInfo(packageName, userId));
3250 }
3251
Makoto Onuki22fcc682016-05-17 14:52:19 -07003252 @Nullable
3253 XmlResourceParser injectXmlMetaData(ActivityInfo activityInfo, String key) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07003254 return activityInfo.loadXmlMetaData(mContext.getPackageManager(), key);
Makoto Onuki39686e82016-04-13 18:03:00 -07003255 }
3256
Makoto Onuki157b1622016-06-02 16:13:10 -07003257 @Nullable
3258 Resources injectGetResourcesForApplicationAsUser(String packageName, int userId) {
3259 final long start = injectElapsedRealtime();
3260 final long token = injectClearCallingIdentity();
3261 try {
3262 return mContext.getPackageManager().getResourcesForApplicationAsUser(
3263 packageName, userId);
3264 } catch (NameNotFoundException e) {
3265 Slog.e(TAG, "Resources for package " + packageName + " not found");
3266 return null;
3267 } finally {
3268 injectRestoreCallingIdentity(token);
3269
3270 logDurationStat(Stats.GET_APPLICATION_RESOURCES, start);
3271 }
3272 }
3273
Makoto Onukib08790c2016-06-23 14:05:46 -07003274 private Intent getMainActivityIntent() {
3275 final Intent intent = new Intent(Intent.ACTION_MAIN);
3276 intent.addCategory(LAUNCHER_INTENT_CATEGORY);
3277 return intent;
3278 }
3279
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003280 /**
3281 * Same as queryIntentActivitiesAsUser, except it makes sure the package is installed,
3282 * and only returns exported activities.
3283 */
3284 @NonNull
3285 @VisibleForTesting
3286 List<ResolveInfo> queryActivities(@NonNull Intent baseIntent,
3287 @NonNull String packageName, @Nullable ComponentName activity, int userId) {
3288
3289 baseIntent.setPackage(Preconditions.checkNotNull(packageName));
3290 if (activity != null) {
3291 baseIntent.setComponent(activity);
3292 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08003293 return queryActivities(baseIntent, userId, /* exportedOnly =*/ true);
3294 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003295
Makoto Onuki2d895c32016-12-02 15:48:40 -08003296 @NonNull
3297 List<ResolveInfo> queryActivities(@NonNull Intent intent, int userId,
3298 boolean exportedOnly) {
3299 final List<ResolveInfo> resolved;
3300 final long token = injectClearCallingIdentity();
3301 try {
3302 resolved =
3303 mContext.getPackageManager().queryIntentActivitiesAsUser(
3304 intent, PACKAGE_MATCH_FLAGS, userId);
3305 } finally {
3306 injectRestoreCallingIdentity(token);
3307 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003308 if (resolved == null || resolved.size() == 0) {
3309 return EMPTY_RESOLVE_INFO;
3310 }
3311 // Make sure the package is installed.
3312 if (!isInstalled(resolved.get(0).activityInfo)) {
3313 return EMPTY_RESOLVE_INFO;
3314 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08003315 if (exportedOnly) {
3316 resolved.removeIf(ACTIVITY_NOT_EXPORTED);
3317 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003318 return resolved;
3319 }
3320
3321 /**
3322 * Return the main activity that is enabled and exported. If multiple activities are found,
3323 * return the first one.
3324 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003325 @Nullable
3326 ComponentName injectGetDefaultMainActivity(@NonNull String packageName, int userId) {
3327 final long start = injectElapsedRealtime();
Makoto Onukib08790c2016-06-23 14:05:46 -07003328 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07003329 final List<ResolveInfo> resolved =
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003330 queryActivities(getMainActivityIntent(), packageName, null, userId);
3331 return resolved.size() == 0 ? null : resolved.get(0).activityInfo.getComponentName();
Makoto Onukib08790c2016-06-23 14:05:46 -07003332 } finally {
Makoto Onukib08790c2016-06-23 14:05:46 -07003333 logDurationStat(Stats.GET_LAUNCHER_ACTIVITY, start);
3334 }
3335 }
3336
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003337 /**
3338 * Return whether an activity is enabled, exported and main.
3339 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003340 boolean injectIsMainActivity(@NonNull ComponentName activity, int userId) {
3341 final long start = injectElapsedRealtime();
Makoto Onukib08790c2016-06-23 14:05:46 -07003342 try {
Makoto Onuki34145532017-03-14 17:58:36 -07003343 if (activity == null) {
3344 wtf("null activity detected");
3345 return false;
3346 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08003347 if (DUMMY_MAIN_ACTIVITY.equals(activity.getClassName())) {
3348 return true;
3349 }
3350 final List<ResolveInfo> resolved = queryActivities(
3351 getMainActivityIntent(), activity.getPackageName(), activity, userId);
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003352 return resolved.size() > 0;
Makoto Onukib08790c2016-06-23 14:05:46 -07003353 } finally {
Makoto Onukib08790c2016-06-23 14:05:46 -07003354 logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start);
3355 }
3356 }
3357
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003358 /**
Makoto Onuki2d895c32016-12-02 15:48:40 -08003359 * Create a dummy "main activity" component name which is used to create a dynamic shortcut
3360 * with no main activity temporarily.
3361 */
3362 @NonNull
3363 ComponentName getDummyMainActivity(@NonNull String packageName) {
3364 return new ComponentName(packageName, DUMMY_MAIN_ACTIVITY);
3365 }
3366
Makoto Onuki255461f2017-01-10 11:47:25 -08003367 boolean isDummyMainActivity(@Nullable ComponentName name) {
3368 return name != null && DUMMY_MAIN_ACTIVITY.equals(name.getClassName());
3369 }
3370
Makoto Onuki2d895c32016-12-02 15:48:40 -08003371 /**
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003372 * Return all the enabled, exported and main activities from a package.
3373 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003374 @NonNull
3375 List<ResolveInfo> injectGetMainActivities(@NonNull String packageName, int userId) {
3376 final long start = injectElapsedRealtime();
Makoto Onukib08790c2016-06-23 14:05:46 -07003377 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003378 return queryActivities(getMainActivityIntent(), packageName, null, userId);
Makoto Onukib08790c2016-06-23 14:05:46 -07003379 } finally {
Makoto Onukib08790c2016-06-23 14:05:46 -07003380 logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start);
3381 }
3382 }
3383
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003384 /**
3385 * Return whether an activity is enabled and exported.
3386 */
3387 @VisibleForTesting
3388 boolean injectIsActivityEnabledAndExported(
3389 @NonNull ComponentName activity, @UserIdInt int userId) {
3390 final long start = injectElapsedRealtime();
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003391 try {
3392 return queryActivities(new Intent(), activity.getPackageName(), activity, userId)
3393 .size() > 0;
3394 } finally {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003395 logDurationStat(Stats.IS_ACTIVITY_ENABLED, start);
3396 }
3397 }
3398
Makoto Onuki2d895c32016-12-02 15:48:40 -08003399 /**
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003400 * Get the {@link LauncherApps#ACTION_CONFIRM_PIN_SHORTCUT} or
3401 * {@link LauncherApps#ACTION_CONFIRM_PIN_APPWIDGET} activity in a given package depending on
3402 * the requestType.
Makoto Onuki2d895c32016-12-02 15:48:40 -08003403 */
3404 @Nullable
3405 ComponentName injectGetPinConfirmationActivity(@NonNull String launcherPackageName,
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003406 int launcherUserId, int requestType) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08003407 Preconditions.checkNotNull(launcherPackageName);
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003408 String action = requestType == LauncherApps.PinItemRequest.REQUEST_TYPE_SHORTCUT ?
3409 LauncherApps.ACTION_CONFIRM_PIN_SHORTCUT :
3410 LauncherApps.ACTION_CONFIRM_PIN_APPWIDGET;
Makoto Onuki2d895c32016-12-02 15:48:40 -08003411
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003412 final Intent confirmIntent = new Intent(action).setPackage(launcherPackageName);
Makoto Onuki2d895c32016-12-02 15:48:40 -08003413 final List<ResolveInfo> candidates = queryActivities(
3414 confirmIntent, launcherUserId, /* exportedOnly =*/ false);
3415 for (ResolveInfo ri : candidates) {
3416 return ri.activityInfo.getComponentName();
3417 }
3418 return null;
3419 }
3420
Makoto Onukib08790c2016-06-23 14:05:46 -07003421 boolean injectIsSafeModeEnabled() {
3422 final long token = injectClearCallingIdentity();
3423 try {
3424 return IWindowManager.Stub
3425 .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE))
3426 .isSafeModeEnabled();
3427 } catch (RemoteException e) {
3428 return false; // Shouldn't happen though.
3429 } finally {
3430 injectRestoreCallingIdentity(token);
3431 }
3432 }
3433
Makoto Onuki2d895c32016-12-02 15:48:40 -08003434 /**
3435 * If {@code userId} is of a managed profile, return the parent user ID. Otherwise return
3436 * itself.
3437 */
3438 int getParentOrSelfUserId(int userId) {
3439 final long token = injectClearCallingIdentity();
3440 try {
3441 final UserInfo parent = mUserManager.getProfileParent(userId);
3442 return (parent != null) ? parent.id : userId;
3443 } finally {
3444 injectRestoreCallingIdentity(token);
3445 }
3446 }
3447
Sunny Goyal87a563e2017-01-01 19:42:45 -08003448 void injectSendIntentSender(IntentSender intentSender, Intent extras) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08003449 if (intentSender == null) {
3450 return;
3451 }
3452 try {
Sunny Goyal87a563e2017-01-01 19:42:45 -08003453 intentSender.sendIntent(mContext, /* code= */ 0, extras,
Makoto Onuki2d895c32016-12-02 15:48:40 -08003454 /* onFinished=*/ null, /* handler= */ null);
3455 } catch (SendIntentException e) {
3456 Slog.w(TAG, "sendIntent failed().", e);
3457 }
3458 }
3459
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003460 // === Backup & restore ===
3461
Makoto Onuki0acbb142016-03-22 17:02:57 -07003462 boolean shouldBackupApp(String packageName, int userId) {
Makoto Onuki905e8852016-03-28 10:40:58 -07003463 return isApplicationFlagSet(packageName, userId, ApplicationInfo.FLAG_ALLOW_BACKUP);
Makoto Onuki0acbb142016-03-22 17:02:57 -07003464 }
3465
Makoto Onukia4f89b12017-10-05 10:37:55 -07003466 static boolean shouldBackupApp(PackageInfo pi) {
Makoto Onuki2e210c42016-03-30 08:30:36 -07003467 return (pi.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0;
3468 }
3469
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003470 @Override
Makoto Onuki2e210c42016-03-30 08:30:36 -07003471 public byte[] getBackupPayload(@UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003472 enforceSystem();
3473 if (DEBUG) {
3474 Slog.d(TAG, "Backing up user " + userId);
3475 }
3476 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003477 if (!isUserUnlockedL(userId)) {
3478 wtf("Can't backup: user " + userId + " is locked or not running");
3479 return null;
3480 }
3481
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003482 final ShortcutUser user = getUserShortcutsLocked(userId);
3483 if (user == null) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003484 wtf("Can't backup: user not found: id=" + userId);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003485 return null;
3486 }
3487
Makoto Onukic8c33292016-09-12 16:36:59 -07003488 // Update the signatures for all packages.
3489 user.forAllPackageItems(spi -> spi.refreshPackageSignatureAndSave());
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003490
Makoto Onukic8c33292016-09-12 16:36:59 -07003491 // Set the version code for the launchers.
3492 // We shouldn't do this for publisher packages, because we don't want to update the
3493 // version code without rescanning the manifest.
Makoto Onukia4f89b12017-10-05 10:37:55 -07003494 user.forAllLaunchers(launcher -> launcher.ensurePackageInfo());
Makoto Onukic8c33292016-09-12 16:36:59 -07003495
3496 // Save to the filesystem.
3497 scheduleSaveUser(userId);
3498 saveDirtyInfo();
3499
Makoto Onuki475c3652017-05-08 14:29:03 -07003500 // Note, in case of backup, we don't have to wait on bitmap saving, because we don't
3501 // back up bitmaps anyway.
3502
Makoto Onukic8c33292016-09-12 16:36:59 -07003503 // Then create the backup payload.
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003504 final ByteArrayOutputStream os = new ByteArrayOutputStream(32 * 1024);
3505 try {
3506 saveUserInternalLocked(userId, os, /* forBackup */ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07003507 } catch (XmlPullParserException | IOException e) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003508 // Shouldn't happen.
3509 Slog.w(TAG, "Backup failed.", e);
3510 return null;
3511 }
3512 return os.toByteArray();
3513 }
3514 }
3515
3516 @Override
Makoto Onuki2e210c42016-03-30 08:30:36 -07003517 public void applyRestore(byte[] payload, @UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003518 enforceSystem();
3519 if (DEBUG) {
3520 Slog.d(TAG, "Restoring user " + userId);
3521 }
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003522 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003523 if (!isUserUnlockedL(userId)) {
3524 wtf("Can't restore: user " + userId + " is locked or not running");
3525 return;
3526 }
Makoto Onuki50a320e2017-05-31 14:38:42 -07003527
3528 // Note we print the file timestamps in dumpsys too, but also printing the timestamp
3529 // in the files anyway.
3530 mShortcutDumpFiles.save("restore-0-start.txt", pw -> {
3531 pw.print("Start time: ");
3532 dumpCurrentTime(pw);
3533 pw.println();
3534 });
3535 mShortcutDumpFiles.save("restore-1-payload.xml", payload);
3536
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003537 // Actually do restore.
3538 final ShortcutUser restored;
Makoto Onuki02f338e2016-07-29 09:40:40 -07003539 final ByteArrayInputStream is = new ByteArrayInputStream(payload);
3540 try {
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003541 restored = loadUserInternal(userId, is, /* fromBackup */ true);
3542 } catch (XmlPullParserException | IOException | InvalidFileFormatException e) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003543 Slog.w(TAG, "Restoration failed.", e);
3544 return;
3545 }
Makoto Onuki50a320e2017-05-31 14:38:42 -07003546 mShortcutDumpFiles.save("restore-2.txt", this::dumpInner);
3547
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003548 getUserShortcutsLocked(userId).mergeRestoredFile(restored);
Makoto Onuki2e210c42016-03-30 08:30:36 -07003549
Makoto Onuki50a320e2017-05-31 14:38:42 -07003550 mShortcutDumpFiles.save("restore-3.txt", this::dumpInner);
3551
Makoto Onuki377b7972016-08-09 14:43:55 -07003552 // Rescan all packages to re-publish manifest shortcuts and do other checks.
3553 rescanUpdatedPackagesLocked(userId,
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003554 0 // lastScanTime = 0; rescan all packages.
3555 );
Makoto Onuki2e210c42016-03-30 08:30:36 -07003556
Makoto Onuki50a320e2017-05-31 14:38:42 -07003557 mShortcutDumpFiles.save("restore-4.txt", this::dumpInner);
3558
3559 mShortcutDumpFiles.save("restore-5-finish.txt", pw -> {
3560 pw.print("Finish time: ");
3561 dumpCurrentTime(pw);
3562 pw.println();
3563 });
3564
Makoto Onuki2e210c42016-03-30 08:30:36 -07003565 saveUserLocked(userId);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003566 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07003567 }
3568
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003569 // === Dump ===
3570
3571 @Override
3572 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06003573 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
Makoto Onukic4361e32017-04-03 11:24:25 -07003574 dumpNoCheck(fd, pw, args);
3575 }
3576
3577 @VisibleForTesting
3578 void dumpNoCheck(FileDescriptor fd, PrintWriter pw, String[] args) {
Makoto Onuki20b82212017-10-04 15:03:50 -07003579 final DumpFilter filter = parseDumpArgs(args);
Makoto Onuki50a320e2017-05-31 14:38:42 -07003580
Makoto Onuki20b82212017-10-04 15:03:50 -07003581 if (filter.shouldDumpCheckIn()) {
Makoto Onuki50a320e2017-05-31 14:38:42 -07003582 // Other flags are not supported for checkin.
Makoto Onuki20b82212017-10-04 15:03:50 -07003583 dumpCheckin(pw, filter.shouldCheckInClear());
Makoto Onuki76269922016-07-15 14:58:54 -07003584 } else {
Makoto Onuki20b82212017-10-04 15:03:50 -07003585 if (filter.shouldDumpMain()) {
3586 dumpInner(pw, filter);
Makoto Onuki50a320e2017-05-31 14:38:42 -07003587 pw.println();
3588 }
Makoto Onuki20b82212017-10-04 15:03:50 -07003589 if (filter.shouldDumpUid()) {
Makoto Onuki50a320e2017-05-31 14:38:42 -07003590 dumpUid(pw);
3591 pw.println();
3592 }
Makoto Onuki20b82212017-10-04 15:03:50 -07003593 if (filter.shouldDumpFiles()) {
Makoto Onuki50a320e2017-05-31 14:38:42 -07003594 dumpDumpFiles(pw);
3595 pw.println();
3596 }
Makoto Onuki76269922016-07-15 14:58:54 -07003597 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003598 }
3599
Makoto Onuki20b82212017-10-04 15:03:50 -07003600 private static DumpFilter parseDumpArgs(String[] args) {
3601 final DumpFilter filter = new DumpFilter();
3602 if (args == null) {
3603 return filter;
3604 }
Makoto Onuki55046222016-03-08 10:49:47 -08003605
Makoto Onuki20b82212017-10-04 15:03:50 -07003606 int argIndex = 0;
3607 while (argIndex < args.length) {
3608 final String arg = args[argIndex++];
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003609
Makoto Onuki20b82212017-10-04 15:03:50 -07003610 if ("-c".equals(arg)) {
3611 filter.setDumpCheckIn(true);
3612 continue;
3613 }
3614 if ("--checkin".equals(arg)) {
3615 filter.setDumpCheckIn(true);
3616 filter.setCheckInClear(true);
3617 continue;
3618 }
3619 if ("-a".equals(arg) || "--all".equals(arg)) {
3620 filter.setDumpUid(true);
3621 filter.setDumpFiles(true);
3622 continue;
3623 }
3624 if ("-u".equals(arg) || "--uid".equals(arg)) {
3625 filter.setDumpUid(true);
3626 continue;
3627 }
3628 if ("-f".equals(arg) || "--files".equals(arg)) {
3629 filter.setDumpFiles(true);
3630 continue;
3631 }
3632 if ("-n".equals(arg) || "--no-main".equals(arg)) {
3633 filter.setDumpMain(false);
3634 continue;
3635 }
3636 if ("--user".equals(arg)) {
3637 if (argIndex >= args.length) {
3638 throw new IllegalArgumentException("Missing user ID for --user");
3639 }
3640 try {
3641 filter.addUser(Integer.parseInt(args[argIndex++]));
3642 } catch (NumberFormatException e) {
3643 throw new IllegalArgumentException("Invalid user ID", e);
3644 }
3645 continue;
3646 }
3647 if ("-p".equals(arg) || "--package".equals(arg)) {
3648 if (argIndex >= args.length) {
3649 throw new IllegalArgumentException("Missing package name for --package");
3650 }
3651 filter.addPackageRegex(args[argIndex++]);
3652 filter.setDumpDetails(false);
3653 continue;
3654 }
3655 if (arg.startsWith("-")) {
3656 throw new IllegalArgumentException("Unknown option " + arg);
3657 }
3658 break;
3659 }
3660 while (argIndex < args.length) {
3661 filter.addPackage(args[argIndex++]);
3662 }
3663 return filter;
3664 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003665
Makoto Onuki20b82212017-10-04 15:03:50 -07003666 static class DumpFilter {
3667 private boolean mDumpCheckIn = false;
3668 private boolean mCheckInClear = false;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003669
Makoto Onuki20b82212017-10-04 15:03:50 -07003670 private boolean mDumpMain = true;
3671 private boolean mDumpUid = false;
3672 private boolean mDumpFiles = false;
Makoto Onuki55046222016-03-08 10:49:47 -08003673
Makoto Onuki20b82212017-10-04 15:03:50 -07003674 private boolean mDumpDetails = true;
3675 private List<Pattern> mPackagePatterns = new ArrayList<>();
3676 private List<Integer> mUsers = new ArrayList<>();
3677
3678 void addPackageRegex(String regex) {
3679 mPackagePatterns.add(Pattern.compile(regex));
3680 }
3681
3682 public void addPackage(String packageName) {
3683 addPackageRegex(Pattern.quote(packageName));
3684 }
3685
3686 void addUser(int userId) {
3687 mUsers.add(userId);
3688 }
3689
3690 boolean isPackageMatch(String packageName) {
3691 if (mPackagePatterns.size() == 0) {
3692 return true;
3693 }
3694 for (int i = 0; i < mPackagePatterns.size(); i++) {
3695 if (mPackagePatterns.get(i).matcher(packageName).find()) {
3696 return true;
Makoto Onuki085a05c2016-08-19 11:39:29 -07003697 }
Makoto Onuki2e210c42016-03-30 08:30:36 -07003698 }
Makoto Onuki20b82212017-10-04 15:03:50 -07003699 return false;
3700 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003701
Makoto Onuki20b82212017-10-04 15:03:50 -07003702 boolean isUserMatch(int userId) {
3703 if (mUsers.size() == 0) {
3704 return true;
3705 }
3706 for (int i = 0; i < mUsers.size(); i++) {
3707 if (mUsers.get(i) == userId) {
3708 return true;
3709 }
3710 }
3711 return false;
3712 }
Makoto Onukia2241832016-07-06 13:28:37 -07003713
Makoto Onuki20b82212017-10-04 15:03:50 -07003714 public boolean shouldDumpCheckIn() {
3715 return mDumpCheckIn;
3716 }
3717
3718 public void setDumpCheckIn(boolean dumpCheckIn) {
3719 mDumpCheckIn = dumpCheckIn;
3720 }
3721
3722 public boolean shouldCheckInClear() {
3723 return mCheckInClear;
3724 }
3725
3726 public void setCheckInClear(boolean checkInClear) {
3727 mCheckInClear = checkInClear;
3728 }
3729
3730 public boolean shouldDumpMain() {
3731 return mDumpMain;
3732 }
3733
3734 public void setDumpMain(boolean dumpMain) {
3735 mDumpMain = dumpMain;
3736 }
3737
3738 public boolean shouldDumpUid() {
3739 return mDumpUid;
3740 }
3741
3742 public void setDumpUid(boolean dumpUid) {
3743 mDumpUid = dumpUid;
3744 }
3745
3746 public boolean shouldDumpFiles() {
3747 return mDumpFiles;
3748 }
3749
3750 public void setDumpFiles(boolean dumpFiles) {
3751 mDumpFiles = dumpFiles;
3752 }
3753
3754 public boolean shouldDumpDetails() {
3755 return mDumpDetails;
3756 }
3757
3758 public void setDumpDetails(boolean dumpDetails) {
3759 mDumpDetails = dumpDetails;
3760 }
3761 }
3762
3763 private void dumpInner(PrintWriter pw) {
3764 dumpInner(pw, new DumpFilter());
3765 }
3766
3767 private void dumpInner(PrintWriter pw, DumpFilter filter) {
3768 synchronized (mLock) {
3769 if (filter.shouldDumpDetails()) {
3770 final long now = injectCurrentTimeMillis();
3771 pw.print("Now: [");
3772 pw.print(now);
3773 pw.print("] ");
3774 pw.print(formatTime(now));
3775
3776 pw.print(" Raw last reset: [");
3777 pw.print(mRawLastResetTime);
3778 pw.print("] ");
3779 pw.print(formatTime(mRawLastResetTime));
3780
3781 final long last = getLastResetTimeLocked();
3782 pw.print(" Last reset: [");
3783 pw.print(last);
3784 pw.print("] ");
3785 pw.print(formatTime(last));
3786
3787 final long next = getNextResetTimeLocked();
3788 pw.print(" Next reset: [");
3789 pw.print(next);
3790 pw.print("] ");
3791 pw.print(formatTime(next));
3792
3793 pw.print(" Config:");
3794 pw.print(" Max icon dim: ");
3795 pw.println(mMaxIconDimension);
3796 pw.print(" Icon format: ");
3797 pw.println(mIconPersistFormat);
3798 pw.print(" Icon quality: ");
3799 pw.println(mIconPersistQuality);
3800 pw.print(" saveDelayMillis: ");
3801 pw.println(mSaveDelayMillis);
3802 pw.print(" resetInterval: ");
3803 pw.println(mResetInterval);
3804 pw.print(" maxUpdatesPerInterval: ");
3805 pw.println(mMaxUpdatesPerInterval);
3806 pw.print(" maxShortcutsPerActivity: ");
3807 pw.println(mMaxShortcuts);
3808 pw.println();
3809
3810 pw.println(" Stats:");
3811 synchronized (mStatLock) {
3812 for (int i = 0; i < Stats.COUNT; i++) {
3813 dumpStatLS(pw, " ", i);
3814 }
3815 }
3816
3817 pw.println();
3818 pw.print(" #Failures: ");
3819 pw.println(mWtfCount);
3820
3821 if (mLastWtfStacktrace != null) {
3822 pw.print(" Last failure stack trace: ");
3823 pw.println(Log.getStackTraceString(mLastWtfStacktrace));
3824 }
3825
3826 pw.println();
3827 mShortcutBitmapSaver.dumpLocked(pw, " ");
3828
3829 pw.println();
Makoto Onukia2241832016-07-06 13:28:37 -07003830 }
3831
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08003832 for (int i = 0; i < mUsers.size(); i++) {
Makoto Onuki20b82212017-10-04 15:03:50 -07003833 final ShortcutUser user = mUsers.valueAt(i);
3834 if (filter.isUserMatch(user.getUserId())) {
3835 user.dump(pw, " ", filter);
3836 pw.println();
3837 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003838 }
Makoto Onuki50a320e2017-05-31 14:38:42 -07003839 }
3840 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003841
Makoto Onuki50a320e2017-05-31 14:38:42 -07003842 private void dumpUid(PrintWriter pw) {
3843 synchronized (mLock) {
3844 pw.println("** SHORTCUT MANAGER UID STATES (dumpsys shortcut -n -u)");
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003845
3846 for (int i = 0; i < mUidState.size(); i++) {
3847 final int uid = mUidState.keyAt(i);
3848 final int state = mUidState.valueAt(i);
3849 pw.print(" UID=");
3850 pw.print(uid);
3851 pw.print(" state=");
3852 pw.print(state);
3853 if (isProcessStateForeground(state)) {
3854 pw.print(" [FG]");
3855 }
3856 pw.print(" last FG=");
3857 pw.print(mUidLastForegroundElapsedTime.get(uid));
3858 pw.println();
3859 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003860 }
3861 }
3862
Makoto Onuki41066a62016-03-09 16:18:44 -08003863 static String formatTime(long time) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003864 Time tobj = new Time();
3865 tobj.set(time);
3866 return tobj.format("%Y-%m-%d %H:%M:%S");
3867 }
3868
Makoto Onuki50a320e2017-05-31 14:38:42 -07003869 private void dumpCurrentTime(PrintWriter pw) {
3870 pw.print(formatTime(injectCurrentTimeMillis()));
3871 }
3872
Makoto Onuki085a05c2016-08-19 11:39:29 -07003873 private void dumpStatLS(PrintWriter pw, String prefix, int statId) {
Makoto Onuki2e210c42016-03-30 08:30:36 -07003874 pw.print(prefix);
3875 final int count = mCountStats[statId];
3876 final long dur = mDurationStats[statId];
3877 pw.println(String.format("%s: count=%d, total=%dms, avg=%.1fms",
Makoto Onuki085a05c2016-08-19 11:39:29 -07003878 STAT_LABELS[statId], count, dur,
Makoto Onuki2e210c42016-03-30 08:30:36 -07003879 (count == 0 ? 0 : ((double) dur) / count)));
3880 }
3881
Makoto Onuki76269922016-07-15 14:58:54 -07003882 /**
3883 * Dumpsys for checkin.
3884 *
3885 * @param clear if true, clear the history information. Some other system services have this
3886 * behavior but shortcut service doesn't for now.
3887 */
3888 private void dumpCheckin(PrintWriter pw, boolean clear) {
3889 synchronized (mLock) {
3890 try {
3891 final JSONArray users = new JSONArray();
3892
3893 for (int i = 0; i < mUsers.size(); i++) {
3894 users.put(mUsers.valueAt(i).dumpCheckin(clear));
3895 }
3896
3897 final JSONObject result = new JSONObject();
3898
3899 result.put(KEY_SHORTCUT, users);
3900 result.put(KEY_LOW_RAM, injectIsLowRamDevice());
3901 result.put(KEY_ICON_SIZE, mMaxIconDimension);
3902
3903 pw.println(result.toString(1));
3904 } catch (JSONException e) {
3905 Slog.e(TAG, "Unable to write in json", e);
3906 }
3907 }
3908 }
3909
Makoto Onuki50a320e2017-05-31 14:38:42 -07003910 private void dumpDumpFiles(PrintWriter pw) {
3911 synchronized (mLock) {
3912 pw.println("** SHORTCUT MANAGER FILES (dumpsys shortcut -n -f)");
3913 mShortcutDumpFiles.dumpAll(pw);
3914 }
3915 }
3916
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003917 // === Shell support ===
3918
3919 @Override
3920 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003921 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003922
3923 enforceShell();
3924
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07003925 final long token = injectClearCallingIdentity();
3926 try {
Dianne Hackborn354736e2016-08-22 17:00:05 -07003927 final int status = (new MyShellCommand()).exec(this, in, out, err, args, callback,
3928 resultReceiver);
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07003929 resultReceiver.send(status, null);
3930 } finally {
3931 injectRestoreCallingIdentity(token);
3932 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003933 }
3934
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003935 static class CommandException extends Exception {
3936 public CommandException(String message) {
3937 super(message);
3938 }
3939 }
3940
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003941 /**
3942 * Handle "adb shell cmd".
3943 */
3944 private class MyShellCommand extends ShellCommand {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003945
3946 private int mUserId = UserHandle.USER_SYSTEM;
3947
Makoto Onuki02f338e2016-07-29 09:40:40 -07003948 private void parseOptionsLocked(boolean takeUser)
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003949 throws CommandException {
3950 String opt;
3951 while ((opt = getNextOption()) != null) {
3952 switch (opt) {
3953 case "--user":
3954 if (takeUser) {
3955 mUserId = UserHandle.parseUserArg(getNextArgRequired());
Makoto Onuki02f338e2016-07-29 09:40:40 -07003956 if (!isUserUnlockedL(mUserId)) {
Makoto Onukif34c3082016-07-13 10:25:25 -07003957 throw new CommandException(
3958 "User " + mUserId + " is not running or locked");
3959 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003960 break;
3961 }
3962 // fallthrough
3963 default:
3964 throw new CommandException("Unknown option: " + opt);
3965 }
3966 }
3967 }
3968
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003969 @Override
3970 public int onCommand(String cmd) {
3971 if (cmd == null) {
3972 return handleDefaultCommands(cmd);
3973 }
3974 final PrintWriter pw = getOutPrintWriter();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003975 try {
3976 switch (cmd) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003977 case "reset-throttling":
3978 handleResetThrottling();
3979 break;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003980 case "reset-all-throttling":
3981 handleResetAllThrottling();
3982 break;
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003983 case "override-config":
3984 handleOverrideConfig();
3985 break;
3986 case "reset-config":
3987 handleResetConfig();
3988 break;
3989 case "clear-default-launcher":
3990 handleClearDefaultLauncher();
3991 break;
3992 case "get-default-launcher":
3993 handleGetDefaultLauncher();
3994 break;
Makoto Onukiac214972016-04-04 10:19:45 -07003995 case "unload-user":
3996 handleUnloadUser();
3997 break;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003998 case "clear-shortcuts":
3999 handleClearShortcuts();
4000 break;
Makoto Onukib08790c2016-06-23 14:05:46 -07004001 case "verify-states": // hidden command to verify various internal states.
4002 handleVerifyStates();
4003 break;
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004004 default:
4005 return handleDefaultCommands(cmd);
4006 }
4007 } catch (CommandException e) {
4008 pw.println("Error: " + e.getMessage());
4009 return 1;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004010 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004011 pw.println("Success");
4012 return 0;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004013 }
4014
4015 @Override
4016 public void onHelp() {
4017 final PrintWriter pw = getOutPrintWriter();
4018 pw.println("Usage: cmd shortcut COMMAND [options ...]");
4019 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004020 pw.println("cmd shortcut reset-throttling [--user USER_ID]");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004021 pw.println(" Reset throttling for all packages and users");
4022 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004023 pw.println("cmd shortcut reset-all-throttling");
4024 pw.println(" Reset the throttling state for all users");
4025 pw.println();
Makoto Onuki4362a662016-03-08 18:59:09 -08004026 pw.println("cmd shortcut override-config CONFIG");
4027 pw.println(" Override the configuration for testing (will last until reboot)");
4028 pw.println();
4029 pw.println("cmd shortcut reset-config");
4030 pw.println(" Reset the configuration set with \"update-config\"");
4031 pw.println();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004032 pw.println("cmd shortcut clear-default-launcher [--user USER_ID]");
4033 pw.println(" Clear the cached default launcher");
4034 pw.println();
4035 pw.println("cmd shortcut get-default-launcher [--user USER_ID]");
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07004036 pw.println(" Show the default launcher");
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004037 pw.println();
Makoto Onukiac214972016-04-04 10:19:45 -07004038 pw.println("cmd shortcut unload-user [--user USER_ID]");
4039 pw.println(" Unload a user from the memory");
4040 pw.println(" (This should not affect any observable behavior)");
4041 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004042 pw.println("cmd shortcut clear-shortcuts [--user USER_ID] PACKAGE");
4043 pw.println(" Remove all shortcuts from a package, including pinned shortcuts");
4044 pw.println();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004045 }
4046
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004047 private void handleResetThrottling() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07004048 synchronized (mLock) {
4049 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki4554d0e2016-03-14 15:51:41 -07004050
Makoto Onuki02f338e2016-07-29 09:40:40 -07004051 Slog.i(TAG, "cmd: handleResetThrottling: user=" + mUserId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004052
Makoto Onuki02f338e2016-07-29 09:40:40 -07004053 resetThrottlingInner(mUserId);
4054 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004055 }
4056
4057 private void handleResetAllThrottling() {
4058 Slog.i(TAG, "cmd: handleResetAllThrottling");
4059
4060 resetAllThrottlingInner();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004061 }
4062
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004063 private void handleOverrideConfig() throws CommandException {
Makoto Onuki4362a662016-03-08 18:59:09 -08004064 final String config = getNextArgRequired();
4065
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004066 Slog.i(TAG, "cmd: handleOverrideConfig: " + config);
4067
Makoto Onuki4362a662016-03-08 18:59:09 -08004068 synchronized (mLock) {
4069 if (!updateConfigurationLocked(config)) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004070 throw new CommandException("override-config failed. See logcat for details.");
Makoto Onuki4362a662016-03-08 18:59:09 -08004071 }
4072 }
Makoto Onuki4362a662016-03-08 18:59:09 -08004073 }
4074
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004075 private void handleResetConfig() {
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004076 Slog.i(TAG, "cmd: handleResetConfig");
4077
Makoto Onuki4362a662016-03-08 18:59:09 -08004078 synchronized (mLock) {
4079 loadConfigurationLocked();
4080 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004081 }
4082
4083 private void clearLauncher() {
4084 synchronized (mLock) {
Makoto Onuki10305202016-07-14 18:14:08 -07004085 getUserShortcutsLocked(mUserId).forceClearLauncher();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004086 }
4087 }
4088
4089 private void showLauncher() {
4090 synchronized (mLock) {
4091 // This ensures to set the cached launcher. Package name doesn't matter.
4092 hasShortcutHostPermissionInner("-", mUserId);
4093
4094 getOutPrintWriter().println("Launcher: "
Makoto Onuki10305202016-07-14 18:14:08 -07004095 + getUserShortcutsLocked(mUserId).getLastKnownLauncher());
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004096 }
4097 }
4098
4099 private void handleClearDefaultLauncher() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07004100 synchronized (mLock) {
4101 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004102
Makoto Onuki02f338e2016-07-29 09:40:40 -07004103 clearLauncher();
4104 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004105 }
4106
4107 private void handleGetDefaultLauncher() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07004108 synchronized (mLock) {
4109 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004110
Makoto Onuki02f338e2016-07-29 09:40:40 -07004111 clearLauncher();
4112 showLauncher();
4113 }
Makoto Onuki4362a662016-03-08 18:59:09 -08004114 }
Makoto Onukiac214972016-04-04 10:19:45 -07004115
4116 private void handleUnloadUser() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07004117 synchronized (mLock) {
4118 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onukiac214972016-04-04 10:19:45 -07004119
Makoto Onuki02f338e2016-07-29 09:40:40 -07004120 Slog.i(TAG, "cmd: handleUnloadUser: user=" + mUserId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004121
Makoto Onuki01ce92b2017-04-28 12:24:16 -07004122 ShortcutService.this.handleStopUser(mUserId);
Makoto Onuki02f338e2016-07-29 09:40:40 -07004123 }
Makoto Onukiac214972016-04-04 10:19:45 -07004124 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004125
4126 private void handleClearShortcuts() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07004127 synchronized (mLock) {
4128 parseOptionsLocked(/* takeUser =*/ true);
4129 final String packageName = getNextArgRequired();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004130
Makoto Onuki02f338e2016-07-29 09:40:40 -07004131 Slog.i(TAG, "cmd: handleClearShortcuts: user" + mUserId + ", " + packageName);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004132
Makoto Onuki02f338e2016-07-29 09:40:40 -07004133 ShortcutService.this.cleanUpPackageForAllLoadedUsers(packageName, mUserId,
4134 /* appStillExists = */ true);
4135 }
Makoto Onukib08790c2016-06-23 14:05:46 -07004136 }
4137
4138 private void handleVerifyStates() throws CommandException {
4139 try {
4140 verifyStatesForce(); // This will throw when there's an issue.
4141 } catch (Throwable th) {
4142 throw new CommandException(th.getMessage() + "\n" + Log.getStackTraceString(th));
4143 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004144 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004145 }
4146
4147 // === Unit test support ===
4148
4149 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07004150 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004151 long injectCurrentTimeMillis() {
4152 return System.currentTimeMillis();
4153 }
4154
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07004155 @VisibleForTesting
4156 long injectElapsedRealtime() {
4157 return SystemClock.elapsedRealtime();
4158 }
4159
Makoto Onuki475c3652017-05-08 14:29:03 -07004160 @VisibleForTesting
4161 long injectUptimeMillis() {
4162 return SystemClock.uptimeMillis();
4163 }
4164
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004165 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07004166 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004167 int injectBinderCallingUid() {
4168 return getCallingUid();
4169 }
4170
Makoto Onuki31459242016-03-22 11:12:18 -07004171 private int getCallingUserId() {
Makoto Onuki4554d0e2016-03-14 15:51:41 -07004172 return UserHandle.getUserId(injectBinderCallingUid());
4173 }
4174
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07004175 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07004176 @VisibleForTesting
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07004177 long injectClearCallingIdentity() {
4178 return Binder.clearCallingIdentity();
4179 }
4180
4181 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07004182 @VisibleForTesting
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07004183 void injectRestoreCallingIdentity(long token) {
4184 Binder.restoreCallingIdentity(token);
4185 }
4186
Makoto Onuki33663282016-08-22 16:19:04 -07004187 // Injection point.
4188 @VisibleForTesting
4189 String injectBuildFingerprint() {
4190 return Build.FINGERPRINT;
4191 }
4192
Makoto Onukide667372016-03-15 14:29:20 -07004193 final void wtf(String message) {
Makoto Onukib08790c2016-06-23 14:05:46 -07004194 wtf(message, /* exception= */ null);
Makoto Onukide667372016-03-15 14:29:20 -07004195 }
4196
Makoto Onuki2e210c42016-03-30 08:30:36 -07004197 // Injection point.
Makoto Onukia2241832016-07-06 13:28:37 -07004198 void wtf(String message, Throwable e) {
4199 if (e == null) {
4200 e = new RuntimeException("Stacktrace");
4201 }
4202 synchronized (mLock) {
4203 mWtfCount++;
4204 mLastWtfStacktrace = new Exception("Last failure was logged here:");
4205 }
Makoto Onukide667372016-03-15 14:29:20 -07004206 Slog.wtf(TAG, message, e);
4207 }
4208
Makoto Onuki31459242016-03-22 11:12:18 -07004209 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004210 File injectSystemDataPath() {
4211 return Environment.getDataSystemDirectory();
4212 }
4213
Makoto Onuki31459242016-03-22 11:12:18 -07004214 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004215 File injectUserDataPath(@UserIdInt int userId) {
Makoto Onuki55046222016-03-08 10:49:47 -08004216 return new File(Environment.getDataSystemCeDirectory(userId), DIRECTORY_PER_USER);
4217 }
4218
Makoto Onuki50a320e2017-05-31 14:38:42 -07004219 public File getDumpPath() {
4220 return new File(injectUserDataPath(UserHandle.USER_SYSTEM), DIRECTORY_DUMP);
4221 }
4222
Makoto Onuki4362a662016-03-08 18:59:09 -08004223 @VisibleForTesting
Makoto Onuki55046222016-03-08 10:49:47 -08004224 boolean injectIsLowRamDevice() {
4225 return ActivityManager.isLowRamDeviceStatic();
4226 }
4227
Makoto Onuki31459242016-03-22 11:12:18 -07004228 @VisibleForTesting
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07004229 void injectRegisterUidObserver(IUidObserver observer, int which) {
4230 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004231 ActivityManager.getService().registerUidObserver(observer, which,
Dianne Hackborn5614bf52016-11-07 17:26:41 -08004232 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07004233 } catch (RemoteException shouldntHappen) {
4234 }
4235 }
4236
Makoto Onuki55046222016-03-08 10:49:47 -08004237 File getUserBitmapFilePath(@UserIdInt int userId) {
4238 return new File(injectUserDataPath(userId), DIRECTORY_BITMAPS);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004239 }
4240
4241 @VisibleForTesting
Makoto Onuki31459242016-03-22 11:12:18 -07004242 SparseArray<ShortcutUser> getShortcutsForTest() {
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08004243 return mUsers;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004244 }
4245
4246 @VisibleForTesting
Makoto Onukib5a012f2016-06-21 11:13:53 -07004247 int getMaxShortcutsForTest() {
4248 return mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004249 }
4250
4251 @VisibleForTesting
Makoto Onukib6d35232016-04-04 15:57:17 -07004252 int getMaxUpdatesPerIntervalForTest() {
4253 return mMaxUpdatesPerInterval;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004254 }
4255
4256 @VisibleForTesting
Makoto Onuki4362a662016-03-08 18:59:09 -08004257 long getResetIntervalForTest() {
4258 return mResetInterval;
Makoto Onuki55046222016-03-08 10:49:47 -08004259 }
4260
4261 @VisibleForTesting
Makoto Onuki4362a662016-03-08 18:59:09 -08004262 int getMaxIconDimensionForTest() {
4263 return mMaxIconDimension;
4264 }
4265
4266 @VisibleForTesting
4267 CompressFormat getIconPersistFormatForTest() {
4268 return mIconPersistFormat;
4269 }
4270
4271 @VisibleForTesting
4272 int getIconPersistQualityForTest() {
4273 return mIconPersistQuality;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004274 }
Makoto Onuki41066a62016-03-09 16:18:44 -08004275
4276 @VisibleForTesting
Makoto Onuki22fcc682016-05-17 14:52:19 -07004277 ShortcutPackage getPackageShortcutForTest(String packageName, int userId) {
Makoto Onuki41066a62016-03-09 16:18:44 -08004278 synchronized (mLock) {
Makoto Onuki31459242016-03-22 11:12:18 -07004279 final ShortcutUser user = mUsers.get(userId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07004280 if (user == null) return null;
4281
Makoto Onuki22fcc682016-05-17 14:52:19 -07004282 return user.getAllPackagesForTest().get(packageName);
4283 }
4284 }
4285
4286 @VisibleForTesting
4287 ShortcutInfo getPackageShortcutForTest(String packageName, String shortcutId, int userId) {
4288 synchronized (mLock) {
Makoto Onukif34c3082016-07-13 10:25:25 -07004289 final ShortcutPackage pkg = getPackageShortcutForTest(packageName, userId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07004290 if (pkg == null) return null;
4291
4292 return pkg.findShortcutById(shortcutId);
Makoto Onuki41066a62016-03-09 16:18:44 -08004293 }
4294 }
Makoto Onuki7001a612016-05-27 13:24:28 -07004295
Makoto Onukifac592f2016-11-21 13:41:32 -08004296 @VisibleForTesting
4297 ShortcutLauncher getLauncherShortcutForTest(String packageName, int userId) {
4298 synchronized (mLock) {
4299 final ShortcutUser user = mUsers.get(userId);
4300 if (user == null) return null;
4301
4302 return user.getAllLaunchersForTest().get(PackageWithUser.of(userId, packageName));
4303 }
4304 }
4305
Makoto Onuki2d895c32016-12-02 15:48:40 -08004306 @VisibleForTesting
4307 ShortcutRequestPinProcessor getShortcutRequestPinProcessorForTest() {
4308 return mShortcutRequestPinProcessor;
4309 }
4310
Makoto Onuki7001a612016-05-27 13:24:28 -07004311 /**
4312 * Control whether {@link #verifyStates} should be performed. We always perform it during unit
4313 * tests.
4314 */
4315 @VisibleForTesting
4316 boolean injectShouldPerformVerification() {
4317 return DEBUG;
4318 }
4319
4320 /**
4321 * Check various internal states and throws if there's any inconsistency.
4322 * This is normally only enabled during unit tests.
4323 */
4324 final void verifyStates() {
4325 if (injectShouldPerformVerification()) {
4326 verifyStatesInner();
4327 }
4328 }
4329
Makoto Onukib08790c2016-06-23 14:05:46 -07004330 private final void verifyStatesForce() {
4331 verifyStatesInner();
4332 }
4333
Makoto Onuki7001a612016-05-27 13:24:28 -07004334 private void verifyStatesInner() {
Makoto Onuki10305202016-07-14 18:14:08 -07004335 synchronized (mLock) {
Makoto Onuki7001a612016-05-27 13:24:28 -07004336 forEachLoadedUserLocked(u -> u.forAllPackageItems(ShortcutPackageItem::verifyStates));
4337 }
4338 }
Makoto Onuki475c3652017-05-08 14:29:03 -07004339
4340 @VisibleForTesting
4341 void waitForBitmapSavesForTest() {
4342 synchronized (mLock) {
4343 mShortcutBitmapSaver.waitForAllSavesLocked();
4344 }
4345 }
Makoto Onuki41066a62016-03-09 16:18:44 -08004346}