blob: b9c304890420f0efb6e54c692c812cf93cf0d425 [file] [log] [blame]
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package com.android.server.pm;
17
Makoto Onuki7d0fa812018-02-21 11:24:43 -080018import android.Manifest.permission;
Makoto Onuki7001a612016-05-27 13:24:28 -070019import android.annotation.IntDef;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080020import android.annotation.NonNull;
21import android.annotation.Nullable;
22import android.annotation.UserIdInt;
Makoto Onuki55046222016-03-08 10:49:47 -080023import android.app.ActivityManager;
Makoto Onuki33525d22016-08-03 15:45:24 -070024import android.app.ActivityManagerInternal;
Makoto Onuki0acbb142016-03-22 17:02:57 -070025import android.app.AppGlobals;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -070026import android.app.IUidObserver;
Makoto Onukiac042502016-05-20 16:39:42 -070027import android.app.usage.UsageStatsManagerInternal;
Sunny Goyal87a563e2017-01-01 19:42:45 -080028import android.appwidget.AppWidgetProviderInfo;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070029import android.content.BroadcastReceiver;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080030import android.content.ComponentName;
31import android.content.Context;
32import android.content.Intent;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070033import android.content.IntentFilter;
Makoto Onuki2d895c32016-12-02 15:48:40 -080034import android.content.IntentSender;
35import android.content.IntentSender.SendIntentException;
Makoto Onuki22fcc682016-05-17 14:52:19 -070036import android.content.pm.ActivityInfo;
Makoto Onuki0acbb142016-03-22 17:02:57 -070037import android.content.pm.ApplicationInfo;
38import android.content.pm.IPackageManager;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080039import android.content.pm.IShortcutService;
40import android.content.pm.LauncherApps;
41import android.content.pm.LauncherApps.ShortcutQuery;
Makoto Onuki0acbb142016-03-22 17:02:57 -070042import android.content.pm.PackageInfo;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080043import android.content.pm.PackageManager;
Makoto Onuki2d5b4652016-03-11 16:09:54 -080044import android.content.pm.PackageManagerInternal;
Todd Kennedy0eb97382017-10-03 16:57:22 -070045import android.content.pm.PackageManager.NameNotFoundException;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080046import android.content.pm.ParceledListSlice;
Makoto Onuki2d5b4652016-03-11 16:09:54 -080047import android.content.pm.ResolveInfo;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080048import android.content.pm.ShortcutInfo;
49import android.content.pm.ShortcutServiceInternal;
50import android.content.pm.ShortcutServiceInternal.ShortcutChangeListener;
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;
Sunny Goyal145c8f82018-02-15 14:27:09 -080079import android.os.UserManagerInternal;
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;
Makoto Onuki49392d32018-04-11 13:51:02 -0700102import com.android.internal.util.StatLogger;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800103import com.android.server.SystemService;
Makoto Onukid99c6f02016-03-28 11:02:54 -0700104import com.android.server.pm.ShortcutUser.PackageWithUser;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800105
106import libcore.io.IoUtils;
107
Makoto Onuki76269922016-07-15 14:58:54 -0700108import org.json.JSONArray;
109import org.json.JSONException;
110import org.json.JSONObject;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800111import org.xmlpull.v1.XmlPullParser;
112import org.xmlpull.v1.XmlPullParserException;
113import org.xmlpull.v1.XmlSerializer;
114
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700115import java.io.BufferedInputStream;
116import java.io.BufferedOutputStream;
117import java.io.ByteArrayInputStream;
118import java.io.ByteArrayOutputStream;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800119import java.io.File;
120import java.io.FileDescriptor;
121import java.io.FileInputStream;
122import java.io.FileNotFoundException;
123import java.io.FileOutputStream;
124import java.io.IOException;
Makoto Onuki55046222016-03-08 10:49:47 -0800125import java.io.InputStream;
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700126import java.io.OutputStream;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800127import java.io.PrintWriter;
Makoto Onuki7001a612016-05-27 13:24:28 -0700128import java.lang.annotation.Retention;
129import java.lang.annotation.RetentionPolicy;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800130import java.net.URISyntaxException;
131import java.nio.charset.StandardCharsets;
132import java.util.ArrayList;
Makoto Onuki22fcc682016-05-17 14:52:19 -0700133import java.util.Collections;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800134import java.util.List;
Makoto Onuki9e215792018-06-12 13:01:42 -0700135import java.util.Objects;
Makoto Onukic51b2872016-05-04 15:24:50 -0700136import java.util.concurrent.atomic.AtomicBoolean;
Makoto Onuki2e210c42016-03-30 08:30:36 -0700137import java.util.function.Consumer;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800138import java.util.function.Predicate;
Makoto Onuki20b82212017-10-04 15:03:50 -0700139import java.util.regex.Pattern;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800140
141/**
142 * TODO:
Makoto Onuki22fcc682016-05-17 14:52:19 -0700143 * - getIconMaxWidth()/getIconMaxHeight() should use xdpi and ydpi.
Makoto Onukib5a012f2016-06-21 11:13:53 -0700144 * -> But TypedValue.applyDimension() doesn't differentiate x and y..?
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800145 *
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700146 * - Detect when already registered instances are passed to APIs again, which might break
Makoto Onukib08790c2016-06-23 14:05:46 -0700147 * internal bitmap handling.
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800148 */
149public class ShortcutService extends IShortcutService.Stub {
Makoto Onuki55046222016-03-08 10:49:47 -0800150 static final String TAG = "ShortcutService";
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800151
Makoto Onuki7001a612016-05-27 13:24:28 -0700152 static final boolean DEBUG = false; // STOPSHIP if true
Makoto Onuki41066a62016-03-09 16:18:44 -0800153 static final boolean DEBUG_LOAD = false; // STOPSHIP if true
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700154 static final boolean DEBUG_PROCSTATE = false; // STOPSHIP if true
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800155
Makoto Onuki4362a662016-03-08 18:59:09 -0800156 @VisibleForTesting
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700157 static final long DEFAULT_RESET_INTERVAL_SEC = 24 * 60 * 60; // 1 day
Makoto Onuki4362a662016-03-08 18:59:09 -0800158
159 @VisibleForTesting
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700160 static final int DEFAULT_MAX_UPDATES_PER_INTERVAL = 10;
Makoto Onuki4362a662016-03-08 18:59:09 -0800161
162 @VisibleForTesting
163 static final int DEFAULT_MAX_SHORTCUTS_PER_APP = 5;
164
165 @VisibleForTesting
166 static final int DEFAULT_MAX_ICON_DIMENSION_DP = 96;
167
168 @VisibleForTesting
169 static final int DEFAULT_MAX_ICON_DIMENSION_LOWRAM_DP = 48;
170
171 @VisibleForTesting
172 static final String DEFAULT_ICON_PERSIST_FORMAT = CompressFormat.PNG.name();
173
174 @VisibleForTesting
175 static final int DEFAULT_ICON_PERSIST_QUALITY = 100;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800176
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700177 @VisibleForTesting
178 static final int DEFAULT_SAVE_DELAY_MS = 3000;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800179
180 @VisibleForTesting
181 static final String FILENAME_BASE_STATE = "shortcut_service.xml";
182
183 @VisibleForTesting
184 static final String DIRECTORY_PER_USER = "shortcut_service";
185
186 @VisibleForTesting
Makoto Onuki50a320e2017-05-31 14:38:42 -0700187 static final String DIRECTORY_DUMP = "shortcut_dump";
188
189 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800190 static final String FILENAME_USER_PACKAGES = "shortcuts.xml";
191
Makoto Onuki55046222016-03-08 10:49:47 -0800192 static final String DIRECTORY_BITMAPS = "bitmaps";
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800193
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700194 private static final String TAG_ROOT = "root";
195 private static final String TAG_LAST_RESET_TIME = "last_reset_time";
Makoto Onuki55046222016-03-08 10:49:47 -0800196
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700197 private static final String ATTR_VALUE = "value";
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800198
Makoto Onukib08790c2016-06-23 14:05:46 -0700199 private static final String LAUNCHER_INTENT_CATEGORY = Intent.CATEGORY_LAUNCHER;
200
Makoto Onuki76269922016-07-15 14:58:54 -0700201 private static final String KEY_SHORTCUT = "shortcut";
202 private static final String KEY_LOW_RAM = "lowRam";
203 private static final String KEY_ICON_SIZE = "iconSize";
204
Makoto Onuki2d895c32016-12-02 15:48:40 -0800205 private static final String DUMMY_MAIN_ACTIVITY = "android.__dummy__";
206
Makoto Onuki4362a662016-03-08 18:59:09 -0800207 @VisibleForTesting
208 interface ConfigConstants {
209 /**
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700210 * Key name for the save delay, in milliseconds. (int)
211 */
212 String KEY_SAVE_DELAY_MILLIS = "save_delay_ms";
213
214 /**
Makoto Onuki4362a662016-03-08 18:59:09 -0800215 * Key name for the throttling reset interval, in seconds. (long)
216 */
217 String KEY_RESET_INTERVAL_SEC = "reset_interval_sec";
218
219 /**
220 * Key name for the max number of modifying API calls per app for every interval. (int)
221 */
Makoto Onukib6d35232016-04-04 15:57:17 -0700222 String KEY_MAX_UPDATES_PER_INTERVAL = "max_updates_per_interval";
Makoto Onuki4362a662016-03-08 18:59:09 -0800223
224 /**
225 * Key name for the max icon dimensions in DP, for non-low-memory devices.
226 */
227 String KEY_MAX_ICON_DIMENSION_DP = "max_icon_dimension_dp";
228
229 /**
230 * Key name for the max icon dimensions in DP, for low-memory devices.
231 */
232 String KEY_MAX_ICON_DIMENSION_DP_LOWRAM = "max_icon_dimension_dp_lowram";
233
234 /**
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700235 * Key name for the max dynamic shortcuts per activity. (int)
Makoto Onuki4362a662016-03-08 18:59:09 -0800236 */
237 String KEY_MAX_SHORTCUTS = "max_shortcuts";
238
239 /**
Makoto Onuki41066a62016-03-09 16:18:44 -0800240 * Key name for icon compression quality, 0-100.
Makoto Onuki4362a662016-03-08 18:59:09 -0800241 */
242 String KEY_ICON_QUALITY = "icon_quality";
243
244 /**
245 * Key name for icon compression format: "PNG", "JPEG" or "WEBP"
246 */
247 String KEY_ICON_FORMAT = "icon_format";
248 }
249
Makoto Onuki41066a62016-03-09 16:18:44 -0800250 final Context mContext;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800251
252 private final Object mLock = new Object();
253
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700254 private static List<ResolveInfo> EMPTY_RESOLVE_INFO = new ArrayList<>(0);
255
Mark Renoufe065f7c2016-11-01 11:48:24 -0400256 // Temporarily reverted to anonymous inner class form due to: b/32554459
257 private static Predicate<ResolveInfo> ACTIVITY_NOT_EXPORTED = new Predicate<ResolveInfo>() {
258 public boolean test(ResolveInfo ri) {
259 return !ri.activityInfo.exported;
260 }
261 };
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700262
Mark Renoufe065f7c2016-11-01 11:48:24 -0400263 // Temporarily reverted to anonymous inner class form due to: b/32554459
264 private static Predicate<PackageInfo> PACKAGE_NOT_INSTALLED = new Predicate<PackageInfo>() {
265 public boolean test(PackageInfo pi) {
266 return !isInstalled(pi);
267 }
268 };
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700269
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800270 private final Handler mHandler;
271
272 @GuardedBy("mLock")
273 private final ArrayList<ShortcutChangeListener> mListeners = new ArrayList<>(1);
274
275 @GuardedBy("mLock")
276 private long mRawLastResetTime;
277
278 /**
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -0800279 * User ID -> UserShortcuts
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800280 */
281 @GuardedBy("mLock")
Makoto Onuki31459242016-03-22 11:12:18 -0700282 private final SparseArray<ShortcutUser> mUsers = new SparseArray<>();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800283
284 /**
Makoto Onuki708703b2017-12-11 16:38:11 -0800285 * User ID -> ShortcutNonPersistentUser
286 */
287 @GuardedBy("mLock")
288 private final SparseArray<ShortcutNonPersistentUser> mShortcutNonPersistentUsers =
289 new SparseArray<>();
290
291 /**
Makoto Onukib5a012f2016-06-21 11:13:53 -0700292 * Max number of dynamic + manifest shortcuts that each application can have at a time.
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800293 */
Makoto Onukib5a012f2016-06-21 11:13:53 -0700294 private int mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800295
296 /**
Makoto Onukib6d35232016-04-04 15:57:17 -0700297 * Max number of updating API calls that each application can make during the interval.
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800298 */
Makoto Onukib6d35232016-04-04 15:57:17 -0700299 int mMaxUpdatesPerInterval;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800300
301 /**
302 * Actual throttling-reset interval. By default it's a day.
303 */
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800304 private long mResetInterval;
305
Makoto Onuki55046222016-03-08 10:49:47 -0800306 /**
307 * Icon max width/height in pixels.
308 */
309 private int mMaxIconDimension;
310
Makoto Onuki4362a662016-03-08 18:59:09 -0800311 private CompressFormat mIconPersistFormat;
312 private int mIconPersistQuality;
Makoto Onuki55046222016-03-08 10:49:47 -0800313
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700314 private int mSaveDelayMillis;
315
Makoto Onuki0acbb142016-03-22 17:02:57 -0700316 private final IPackageManager mIPackageManager;
Makoto Onuki2d5b4652016-03-11 16:09:54 -0800317 private final PackageManagerInternal mPackageManagerInternal;
Sunny Goyal145c8f82018-02-15 14:27:09 -0800318 private final UserManagerInternal mUserManagerInternal;
Makoto Onukiac042502016-05-20 16:39:42 -0700319 private final UsageStatsManagerInternal mUsageStatsManagerInternal;
Makoto Onuki33525d22016-08-03 15:45:24 -0700320 private final ActivityManagerInternal mActivityManagerInternal;
Makoto Onuki2d5b4652016-03-11 16:09:54 -0800321
Makoto Onuki2d895c32016-12-02 15:48:40 -0800322 private final ShortcutRequestPinProcessor mShortcutRequestPinProcessor;
Makoto Onuki475c3652017-05-08 14:29:03 -0700323 private final ShortcutBitmapSaver mShortcutBitmapSaver;
Makoto Onuki50a320e2017-05-31 14:38:42 -0700324 private final ShortcutDumpFiles mShortcutDumpFiles;
Makoto Onuki2d895c32016-12-02 15:48:40 -0800325
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700326 @GuardedBy("mLock")
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700327 final SparseIntArray mUidState = new SparseIntArray();
328
329 @GuardedBy("mLock")
330 final SparseLongArray mUidLastForegroundElapsedTime = new SparseLongArray();
331
332 @GuardedBy("mLock")
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700333 private List<Integer> mDirtyUserIds = new ArrayList<>();
334
Makoto Onukic51b2872016-05-04 15:24:50 -0700335 private final AtomicBoolean mBootCompleted = new AtomicBoolean();
336
Makoto Onuki905e8852016-03-28 10:40:58 -0700337 private static final int PACKAGE_MATCH_FLAGS =
338 PackageManager.MATCH_DIRECT_BOOT_AWARE
Makoto Onukib08790c2016-06-23 14:05:46 -0700339 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE
340 | PackageManager.MATCH_UNINSTALLED_PACKAGES;
Makoto Onuki905e8852016-03-28 10:40:58 -0700341
Makoto Onukie63b04a2017-12-11 14:47:19 -0800342 /**
343 * Note we use a fine-grained lock for {@link #mUnlockedUsers} due to b/64303666.
344 */
345 @GuardedBy("mUnlockedUsers")
Makoto Onuki02f338e2016-07-29 09:40:40 -0700346 final SparseBooleanArray mUnlockedUsers = new SparseBooleanArray();
347
Makoto Onuki2e210c42016-03-30 08:30:36 -0700348 // Stats
349 @VisibleForTesting
350 interface Stats {
351 int GET_DEFAULT_HOME = 0;
352 int GET_PACKAGE_INFO = 1;
353 int GET_PACKAGE_INFO_WITH_SIG = 2;
354 int GET_APPLICATION_INFO = 3;
355 int LAUNCHER_PERMISSION_CHECK = 4;
Makoto Onuki6c1dbd52016-05-02 15:19:32 -0700356 int CLEANUP_DANGLING_BITMAPS = 5;
Makoto Onukib08790c2016-06-23 14:05:46 -0700357 int GET_ACTIVITY_WITH_METADATA = 6;
Makoto Onuki6dd9fb72016-06-01 13:55:54 -0700358 int GET_INSTALLED_PACKAGES = 7;
Makoto Onuki22fcc682016-05-17 14:52:19 -0700359 int CHECK_PACKAGE_CHANGES = 8;
Makoto Onuki157b1622016-06-02 16:13:10 -0700360 int GET_APPLICATION_RESOURCES = 9;
361 int RESOURCE_NAME_LOOKUP = 10;
Makoto Onukib08790c2016-06-23 14:05:46 -0700362 int GET_LAUNCHER_ACTIVITY = 11;
363 int CHECK_LAUNCHER_ACTIVITY = 12;
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700364 int IS_ACTIVITY_ENABLED = 13;
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700365 int PACKAGE_UPDATE_CHECK = 14;
Makoto Onuki085a05c2016-08-19 11:39:29 -0700366 int ASYNC_PRELOAD_USER_DELAY = 15;
Makoto Onuki2d895c32016-12-02 15:48:40 -0800367 int GET_DEFAULT_LAUNCHER = 16;
Makoto Onuki2e210c42016-03-30 08:30:36 -0700368
Makoto Onuki2d895c32016-12-02 15:48:40 -0800369 int COUNT = GET_DEFAULT_LAUNCHER + 1;
Makoto Onuki2e210c42016-03-30 08:30:36 -0700370 }
371
Makoto Onuki84d59342018-02-02 09:22:38 -0800372 private final StatLogger mStatLogger = new StatLogger(new String[] {
Makoto Onuki085a05c2016-08-19 11:39:29 -0700373 "getHomeActivities()",
374 "Launcher permission check",
375 "getPackageInfo()",
376 "getPackageInfo(SIG)",
377 "getApplicationInfo",
378 "cleanupDanglingBitmaps",
379 "getActivity+metadata",
380 "getInstalledPackages",
381 "checkPackageChanges",
382 "getApplicationResources",
383 "resourceNameLookup",
384 "getLauncherActivity",
385 "checkLauncherActivity",
386 "isActivityEnabled",
387 "packageUpdateCheck",
Makoto Onuki2d895c32016-12-02 15:48:40 -0800388 "asyncPreloadUserDelay",
389 "getDefaultLauncher()"
Makoto Onuki84d59342018-02-02 09:22:38 -0800390 });
Makoto Onuki2e210c42016-03-30 08:30:36 -0700391
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700392 private static final int PROCESS_STATE_FOREGROUND_THRESHOLD =
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -0800393 ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700394
Makoto Onuki7001a612016-05-27 13:24:28 -0700395 static final int OPERATION_SET = 0;
396 static final int OPERATION_ADD = 1;
397 static final int OPERATION_UPDATE = 2;
398
399 /** @hide */
400 @IntDef(value = {
401 OPERATION_SET,
402 OPERATION_ADD,
403 OPERATION_UPDATE
Makoto Onukib08790c2016-06-23 14:05:46 -0700404 })
Makoto Onuki7001a612016-05-27 13:24:28 -0700405 @Retention(RetentionPolicy.SOURCE)
Makoto Onukib08790c2016-06-23 14:05:46 -0700406 @interface ShortcutOperation {
407 }
Makoto Onuki7001a612016-05-27 13:24:28 -0700408
Makoto Onukia2241832016-07-06 13:28:37 -0700409 @GuardedBy("mLock")
410 private int mWtfCount = 0;
411
412 @GuardedBy("mLock")
413 private Exception mLastWtfStacktrace;
414
Makoto Onukifc4cf2d2016-08-24 11:10:26 -0700415 static class InvalidFileFormatException extends Exception {
416 public InvalidFileFormatException(String message, Throwable cause) {
417 super(message, cause);
418 }
419 }
420
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800421 public ShortcutService(Context context) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700422 this(context, BackgroundThread.get().getLooper(), /*onyForPackgeManagerApis*/ false);
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700423 }
424
425 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700426 ShortcutService(Context context, Looper looper, boolean onlyForPackageManagerApis) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800427 mContext = Preconditions.checkNotNull(context);
428 LocalServices.addService(ShortcutServiceInternal.class, new LocalService());
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700429 mHandler = new Handler(looper);
Makoto Onuki0acbb142016-03-22 17:02:57 -0700430 mIPackageManager = AppGlobals.getPackageManager();
Makoto Onukiac042502016-05-20 16:39:42 -0700431 mPackageManagerInternal = Preconditions.checkNotNull(
432 LocalServices.getService(PackageManagerInternal.class));
Sunny Goyal145c8f82018-02-15 14:27:09 -0800433 mUserManagerInternal = Preconditions.checkNotNull(
434 LocalServices.getService(UserManagerInternal.class));
Makoto Onukiac042502016-05-20 16:39:42 -0700435 mUsageStatsManagerInternal = Preconditions.checkNotNull(
436 LocalServices.getService(UsageStatsManagerInternal.class));
Makoto Onuki33525d22016-08-03 15:45:24 -0700437 mActivityManagerInternal = Preconditions.checkNotNull(
438 LocalServices.getService(ActivityManagerInternal.class));
Makoto Onukicdc78f72016-03-21 15:47:52 -0700439
Makoto Onuki2d895c32016-12-02 15:48:40 -0800440 mShortcutRequestPinProcessor = new ShortcutRequestPinProcessor(this, mLock);
Makoto Onuki475c3652017-05-08 14:29:03 -0700441 mShortcutBitmapSaver = new ShortcutBitmapSaver(this);
Makoto Onuki50a320e2017-05-31 14:38:42 -0700442 mShortcutDumpFiles = new ShortcutDumpFiles(this);
Makoto Onuki2d895c32016-12-02 15:48:40 -0800443
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700444 if (onlyForPackageManagerApis) {
445 return; // Don't do anything further. For unit tests only.
446 }
447
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700448 // Register receivers.
449
450 // We need to set a priority, so let's just not use PackageMonitor for now.
451 // TODO Refactor PackageMonitor to support priorities.
452 final IntentFilter packageFilter = new IntentFilter();
453 packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
454 packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
455 packageFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
456 packageFilter.addAction(Intent.ACTION_PACKAGE_DATA_CLEARED);
457 packageFilter.addDataScheme("package");
458 packageFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
459 mContext.registerReceiverAsUser(mPackageMonitor, UserHandle.ALL,
460 packageFilter, null, mHandler);
461
Makoto Onuki10305202016-07-14 18:14:08 -0700462 final IntentFilter preferedActivityFilter = new IntentFilter();
463 preferedActivityFilter.addAction(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
464 preferedActivityFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
465 mContext.registerReceiverAsUser(mPackageMonitor, UserHandle.ALL,
466 preferedActivityFilter, null, mHandler);
467
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700468 final IntentFilter localeFilter = new IntentFilter();
469 localeFilter.addAction(Intent.ACTION_LOCALE_CHANGED);
470 localeFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
471 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL,
472 localeFilter, null, mHandler);
Makoto Onukif34c3082016-07-13 10:25:25 -0700473
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700474 injectRegisterUidObserver(mUidObserver, ActivityManager.UID_OBSERVER_PROCSTATE
475 | ActivityManager.UID_OBSERVER_GONE);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800476 }
477
Makoto Onuki84d59342018-02-02 09:22:38 -0800478 long getStatStartTime() {
479 return mStatLogger.getTime();
480 }
481
Makoto Onuki2e210c42016-03-30 08:30:36 -0700482 void logDurationStat(int statId, long start) {
Makoto Onuki84d59342018-02-02 09:22:38 -0800483 mStatLogger.logDurationStat(statId, start);
Makoto Onuki2e210c42016-03-30 08:30:36 -0700484 }
485
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700486 public String injectGetLocaleTagsForUser(@UserIdInt int userId) {
487 // TODO This should get the per-user locale. b/30123329 b/30119489
488 return LocaleList.getDefault().toLanguageTags();
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700489 }
490
491 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Makoto Onukib08790c2016-06-23 14:05:46 -0700492 @Override
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700493 public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onukidc3f6d12017-09-22 17:22:50 -0700494 injectPostToHandler(() -> handleOnUidStateChanged(uid, procState));
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 onUidGone(int uid, boolean disabled) {
Makoto Onukidc3f6d12017-09-22 17:22:50 -0700499 injectPostToHandler(() ->
500 handleOnUidStateChanged(uid, ActivityManager.PROCESS_STATE_NONEXISTENT));
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700501 }
502
Makoto Onukib08790c2016-06-23 14:05:46 -0700503 @Override
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700504 public void onUidActive(int uid) {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700505 }
506
Makoto Onukib08790c2016-06-23 14:05:46 -0700507 @Override
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700508 public void onUidIdle(int uid, boolean disabled) {
509 }
510
511 @Override public void onUidCachedChanged(int uid, boolean cached) {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700512 }
513 };
514
515 void handleOnUidStateChanged(int uid, int procState) {
516 if (DEBUG_PROCSTATE) {
517 Slog.d(TAG, "onUidStateChanged: uid=" + uid + " state=" + procState);
518 }
519 synchronized (mLock) {
520 mUidState.put(uid, procState);
521
522 // We need to keep track of last time an app comes to foreground.
523 // See ShortcutPackage.getApiCallCount() for how it's used.
524 // It doesn't have to be persisted, but it needs to be the elapsed time.
525 if (isProcessStateForeground(procState)) {
526 mUidLastForegroundElapsedTime.put(uid, injectElapsedRealtime());
527 }
528 }
529 }
530
531 private boolean isProcessStateForeground(int processState) {
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800532 return processState <= PROCESS_STATE_FOREGROUND_THRESHOLD;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700533 }
534
Andreas Gampea36dc622018-02-05 17:19:22 -0800535 @GuardedBy("mLock")
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700536 boolean isUidForegroundLocked(int uid) {
537 if (uid == Process.SYSTEM_UID) {
538 // IUidObserver doesn't report the state of SYSTEM, but it always has bound services,
539 // so it's foreground anyway.
540 return true;
541 }
Makoto Onuki33525d22016-08-03 15:45:24 -0700542 // First, check with the local cache.
543 if (isProcessStateForeground(mUidState.get(uid, ActivityManager.MAX_PROCESS_STATE))) {
544 return true;
545 }
546 // If the cache says background, reach out to AM. Since it'll internally need to hold
547 // the AM lock, we use it as a last resort.
548 return isProcessStateForeground(mActivityManagerInternal.getUidProcessState(uid));
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700549 }
550
Andreas Gampea36dc622018-02-05 17:19:22 -0800551 @GuardedBy("mLock")
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700552 long getUidLastForegroundElapsedTimeLocked(int uid) {
553 return mUidLastForegroundElapsedTime.get(uid);
554 }
555
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800556 /**
557 * System service lifecycle.
558 */
559 public static final class Lifecycle extends SystemService {
560 final ShortcutService mService;
561
562 public Lifecycle(Context context) {
563 super(context);
Makoto Onukia4f89b12017-10-05 10:37:55 -0700564 if (DEBUG) {
565 Binder.LOG_RUNTIME_EXCEPTION = true;
566 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800567 mService = new ShortcutService(context);
568 }
569
570 @Override
571 public void onStart() {
572 publishBinderService(Context.SHORTCUT_SERVICE, mService);
573 }
574
575 @Override
576 public void onBootPhase(int phase) {
577 mService.onBootPhase(phase);
578 }
579
580 @Override
Makoto Onuki01ce92b2017-04-28 12:24:16 -0700581 public void onStopUser(int userHandle) {
582 mService.handleStopUser(userHandle);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800583 }
584
585 @Override
Makoto Onukif3a572b2016-03-10 12:28:38 -0800586 public void onUnlockUser(int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -0700587 mService.handleUnlockUser(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800588 }
589 }
590
591 /** lifecycle event */
592 void onBootPhase(int phase) {
593 if (DEBUG) {
594 Slog.d(TAG, "onBootPhase: " + phase);
595 }
596 switch (phase) {
597 case SystemService.PHASE_LOCK_SETTINGS_READY:
598 initialize();
599 break;
Makoto Onukic51b2872016-05-04 15:24:50 -0700600 case SystemService.PHASE_BOOT_COMPLETED:
601 mBootCompleted.set(true);
602 break;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800603 }
604 }
605
606 /** lifecycle event */
Makoto Onukicdc78f72016-03-21 15:47:52 -0700607 void handleUnlockUser(int userId) {
Makoto Onuki22fcc682016-05-17 14:52:19 -0700608 if (DEBUG) {
Makoto Onuki085a05c2016-08-19 11:39:29 -0700609 Slog.d(TAG, "handleUnlockUser: user=" + userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700610 }
Makoto Onukie63b04a2017-12-11 14:47:19 -0800611 synchronized (mUnlockedUsers) {
Makoto Onuki02f338e2016-07-29 09:40:40 -0700612 mUnlockedUsers.put(userId, true);
Makoto Onukicdc78f72016-03-21 15:47:52 -0700613 }
Makoto Onuki085a05c2016-08-19 11:39:29 -0700614
615 // Preload the user data.
616 // Note, we don't use mHandler here but instead just start a new thread.
617 // This is because mHandler (which uses com.android.internal.os.BackgroundThread) is very
618 // busy at this point and this could take hundreds of milliseconds, which would be too
619 // late since the launcher would already have started.
620 // So we just create a new thread. This code runs rarely, so we don't use a thread pool
621 // or anything.
Makoto Onuki84d59342018-02-02 09:22:38 -0800622 final long start = getStatStartTime();
Makoto Onuki085a05c2016-08-19 11:39:29 -0700623 injectRunOnNewThread(() -> {
624 synchronized (mLock) {
625 logDurationStat(Stats.ASYNC_PRELOAD_USER_DELAY, start);
626 getUserShortcutsLocked(userId);
627 }
628 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800629 }
630
631 /** lifecycle event */
Makoto Onuki01ce92b2017-04-28 12:24:16 -0700632 void handleStopUser(int userId) {
Makoto Onuki02f338e2016-07-29 09:40:40 -0700633 if (DEBUG) {
Makoto Onuki01ce92b2017-04-28 12:24:16 -0700634 Slog.d(TAG, "handleStopUser: user=" + userId);
Makoto Onuki02f338e2016-07-29 09:40:40 -0700635 }
Makoto Onukicdc78f72016-03-21 15:47:52 -0700636 synchronized (mLock) {
637 unloadUserLocked(userId);
Makoto Onuki02f338e2016-07-29 09:40:40 -0700638
Makoto Onukie63b04a2017-12-11 14:47:19 -0800639 synchronized (mUnlockedUsers) {
640 mUnlockedUsers.put(userId, false);
641 }
Makoto Onukicdc78f72016-03-21 15:47:52 -0700642 }
643 }
644
Andreas Gampea36dc622018-02-05 17:19:22 -0800645 @GuardedBy("mLock")
Makoto Onukicdc78f72016-03-21 15:47:52 -0700646 private void unloadUserLocked(int userId) {
647 if (DEBUG) {
648 Slog.d(TAG, "unloadUserLocked: user=" + userId);
649 }
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700650 // Save all dirty information.
651 saveDirtyInfo();
652
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800653 // Unload
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -0800654 mUsers.delete(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800655 }
656
657 /** Return the base state file name */
658 private AtomicFile getBaseStateFile() {
659 final File path = new File(injectSystemDataPath(), FILENAME_BASE_STATE);
660 path.mkdirs();
661 return new AtomicFile(path);
662 }
663
664 /**
665 * Init the instance. (load the state file, etc)
666 */
667 private void initialize() {
668 synchronized (mLock) {
Makoto Onuki4362a662016-03-08 18:59:09 -0800669 loadConfigurationLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800670 loadBaseStateLocked();
671 }
672 }
673
Makoto Onuki4362a662016-03-08 18:59:09 -0800674 /**
675 * Load the configuration from Settings.
676 */
677 private void loadConfigurationLocked() {
678 updateConfigurationLocked(injectShortcutManagerConstants());
679 }
Makoto Onuki55046222016-03-08 10:49:47 -0800680
Makoto Onuki4362a662016-03-08 18:59:09 -0800681 /**
682 * Load the configuration from Settings.
683 */
684 @VisibleForTesting
685 boolean updateConfigurationLocked(String config) {
686 boolean result = true;
687
688 final KeyValueListParser parser = new KeyValueListParser(',');
689 try {
690 parser.setString(config);
691 } catch (IllegalArgumentException e) {
692 // Failed to parse the settings string, log this and move on
693 // with defaults.
694 Slog.e(TAG, "Bad shortcut manager settings", e);
695 result = false;
696 }
697
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700698 mSaveDelayMillis = Math.max(0, (int) parser.getLong(ConfigConstants.KEY_SAVE_DELAY_MILLIS,
699 DEFAULT_SAVE_DELAY_MS));
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700700
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700701 mResetInterval = Math.max(1, parser.getLong(
Makoto Onuki4362a662016-03-08 18:59:09 -0800702 ConfigConstants.KEY_RESET_INTERVAL_SEC, DEFAULT_RESET_INTERVAL_SEC)
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700703 * 1000L);
Makoto Onuki4362a662016-03-08 18:59:09 -0800704
Makoto Onukib6d35232016-04-04 15:57:17 -0700705 mMaxUpdatesPerInterval = Math.max(0, (int) parser.getLong(
706 ConfigConstants.KEY_MAX_UPDATES_PER_INTERVAL, DEFAULT_MAX_UPDATES_PER_INTERVAL));
Makoto Onuki4362a662016-03-08 18:59:09 -0800707
Makoto Onukib5a012f2016-06-21 11:13:53 -0700708 mMaxShortcuts = Math.max(0, (int) parser.getLong(
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700709 ConfigConstants.KEY_MAX_SHORTCUTS, DEFAULT_MAX_SHORTCUTS_PER_APP));
Makoto Onuki4362a662016-03-08 18:59:09 -0800710
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700711 final int iconDimensionDp = Math.max(1, injectIsLowRamDevice()
Makoto Onuki4362a662016-03-08 18:59:09 -0800712 ? (int) parser.getLong(
Makoto Onukib08790c2016-06-23 14:05:46 -0700713 ConfigConstants.KEY_MAX_ICON_DIMENSION_DP_LOWRAM,
714 DEFAULT_MAX_ICON_DIMENSION_LOWRAM_DP)
Makoto Onuki4362a662016-03-08 18:59:09 -0800715 : (int) parser.getLong(
Makoto Onukib08790c2016-06-23 14:05:46 -0700716 ConfigConstants.KEY_MAX_ICON_DIMENSION_DP,
717 DEFAULT_MAX_ICON_DIMENSION_DP));
Makoto Onuki4362a662016-03-08 18:59:09 -0800718
719 mMaxIconDimension = injectDipToPixel(iconDimensionDp);
720
721 mIconPersistFormat = CompressFormat.valueOf(
722 parser.getString(ConfigConstants.KEY_ICON_FORMAT, DEFAULT_ICON_PERSIST_FORMAT));
723
724 mIconPersistQuality = (int) parser.getLong(
725 ConfigConstants.KEY_ICON_QUALITY,
726 DEFAULT_ICON_PERSIST_QUALITY);
727
728 return result;
729 }
730
731 @VisibleForTesting
732 String injectShortcutManagerConstants() {
733 return android.provider.Settings.Global.getString(
734 mContext.getContentResolver(),
735 android.provider.Settings.Global.SHORTCUT_MANAGER_CONSTANTS);
736 }
737
738 @VisibleForTesting
739 int injectDipToPixel(int dip) {
740 return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip,
741 mContext.getResources().getDisplayMetrics());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800742 }
743
Makoto Onuki55046222016-03-08 10:49:47 -0800744 // === Persisting ===
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800745
746 @Nullable
Makoto Onuki41066a62016-03-09 16:18:44 -0800747 static String parseStringAttribute(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800748 return parser.getAttributeValue(null, attribute);
749 }
750
Makoto Onuki0acbb142016-03-22 17:02:57 -0700751 static boolean parseBooleanAttribute(XmlPullParser parser, String attribute) {
752 return parseLongAttribute(parser, attribute) == 1;
753 }
754
Makoto Onukia4f89b12017-10-05 10:37:55 -0700755 static boolean parseBooleanAttribute(XmlPullParser parser, String attribute, boolean def) {
756 return parseLongAttribute(parser, attribute, (def ? 1 : 0)) == 1;
757 }
758
Makoto Onuki41066a62016-03-09 16:18:44 -0800759 static int parseIntAttribute(XmlPullParser parser, String attribute) {
760 return (int) parseLongAttribute(parser, attribute);
761 }
762
Makoto Onukid99c6f02016-03-28 11:02:54 -0700763 static int parseIntAttribute(XmlPullParser parser, String attribute, int def) {
764 return (int) parseLongAttribute(parser, attribute, def);
765 }
766
Makoto Onuki41066a62016-03-09 16:18:44 -0800767 static long parseLongAttribute(XmlPullParser parser, String attribute) {
Makoto Onukid99c6f02016-03-28 11:02:54 -0700768 return parseLongAttribute(parser, attribute, 0);
769 }
770
771 static long parseLongAttribute(XmlPullParser parser, String attribute, long def) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800772 final String value = parseStringAttribute(parser, attribute);
773 if (TextUtils.isEmpty(value)) {
Makoto Onukid99c6f02016-03-28 11:02:54 -0700774 return def;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800775 }
776 try {
777 return Long.parseLong(value);
778 } catch (NumberFormatException e) {
779 Slog.e(TAG, "Error parsing long " + value);
Makoto Onukid99c6f02016-03-28 11:02:54 -0700780 return def;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800781 }
782 }
783
784 @Nullable
Makoto Onuki41066a62016-03-09 16:18:44 -0800785 static ComponentName parseComponentNameAttribute(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800786 final String value = parseStringAttribute(parser, attribute);
787 if (TextUtils.isEmpty(value)) {
788 return null;
789 }
790 return ComponentName.unflattenFromString(value);
791 }
792
793 @Nullable
Makoto Onuki440a1ea2016-07-20 14:21:18 -0700794 static Intent parseIntentAttributeNoDefault(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800795 final String value = parseStringAttribute(parser, attribute);
Makoto Onukib5a012f2016-06-21 11:13:53 -0700796 Intent parsed = null;
797 if (!TextUtils.isEmpty(value)) {
798 try {
799 parsed = Intent.parseUri(value, /* flags =*/ 0);
800 } catch (URISyntaxException e) {
801 Slog.e(TAG, "Error parsing intent", e);
802 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800803 }
Makoto Onuki440a1ea2016-07-20 14:21:18 -0700804 return parsed;
805 }
806
807 @Nullable
808 static Intent parseIntentAttribute(XmlPullParser parser, String attribute) {
809 Intent parsed = parseIntentAttributeNoDefault(parser, attribute);
Makoto Onukib5a012f2016-06-21 11:13:53 -0700810 if (parsed == null) {
811 // Default intent.
812 parsed = new Intent(Intent.ACTION_VIEW);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800813 }
Makoto Onukib5a012f2016-06-21 11:13:53 -0700814 return parsed;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800815 }
816
Makoto Onuki41066a62016-03-09 16:18:44 -0800817 static void writeTagValue(XmlSerializer out, String tag, String value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800818 if (TextUtils.isEmpty(value)) return;
819
820 out.startTag(null, tag);
821 out.attribute(null, ATTR_VALUE, value);
822 out.endTag(null, tag);
823 }
824
Makoto Onuki41066a62016-03-09 16:18:44 -0800825 static void writeTagValue(XmlSerializer out, String tag, long value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800826 writeTagValue(out, tag, Long.toString(value));
827 }
828
Makoto Onuki2d5b4652016-03-11 16:09:54 -0800829 static void writeTagValue(XmlSerializer out, String tag, ComponentName name) throws IOException {
830 if (name == null) return;
831 writeTagValue(out, tag, name.flattenToString());
832 }
833
Makoto Onuki41066a62016-03-09 16:18:44 -0800834 static void writeTagExtra(XmlSerializer out, String tag, PersistableBundle bundle)
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800835 throws IOException, XmlPullParserException {
836 if (bundle == null) return;
837
838 out.startTag(null, tag);
839 bundle.saveToXml(out);
840 out.endTag(null, tag);
841 }
842
Makoto Onuki22fcc682016-05-17 14:52:19 -0700843 static void writeAttr(XmlSerializer out, String name, CharSequence value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800844 if (TextUtils.isEmpty(value)) return;
845
Makoto Onuki22fcc682016-05-17 14:52:19 -0700846 out.attribute(null, name, value.toString());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800847 }
848
Makoto Onuki41066a62016-03-09 16:18:44 -0800849 static void writeAttr(XmlSerializer out, String name, long value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800850 writeAttr(out, name, String.valueOf(value));
851 }
852
Makoto Onuki0acbb142016-03-22 17:02:57 -0700853 static void writeAttr(XmlSerializer out, String name, boolean value) throws IOException {
854 if (value) {
855 writeAttr(out, name, "1");
Makoto Onukia4f89b12017-10-05 10:37:55 -0700856 } else {
857 writeAttr(out, name, "0");
Makoto Onuki0acbb142016-03-22 17:02:57 -0700858 }
859 }
860
Makoto Onuki41066a62016-03-09 16:18:44 -0800861 static void writeAttr(XmlSerializer out, String name, ComponentName comp) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800862 if (comp == null) return;
863 writeAttr(out, name, comp.flattenToString());
864 }
865
Makoto Onuki41066a62016-03-09 16:18:44 -0800866 static void writeAttr(XmlSerializer out, String name, Intent intent) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800867 if (intent == null) return;
868
869 writeAttr(out, name, intent.toUri(/* flags =*/ 0));
870 }
871
Andreas Gampea36dc622018-02-05 17:19:22 -0800872 @GuardedBy("mLock")
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800873 @VisibleForTesting
874 void saveBaseStateLocked() {
875 final AtomicFile file = getBaseStateFile();
876 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700877 Slog.d(TAG, "Saving to " + file.getBaseFile());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800878 }
879
880 FileOutputStream outs = null;
881 try {
882 outs = file.startWrite();
883
884 // Write to XML
885 XmlSerializer out = new FastXmlSerializer();
886 out.setOutput(outs, StandardCharsets.UTF_8.name());
887 out.startDocument(null, true);
888 out.startTag(null, TAG_ROOT);
889
890 // Body.
891 writeTagValue(out, TAG_LAST_RESET_TIME, mRawLastResetTime);
892
893 // Epilogue.
894 out.endTag(null, TAG_ROOT);
895 out.endDocument();
896
897 // Close.
898 file.finishWrite(outs);
899 } catch (IOException e) {
900 Slog.e(TAG, "Failed to write to file " + file.getBaseFile(), e);
901 file.failWrite(outs);
902 }
903 }
904
Andreas Gampea36dc622018-02-05 17:19:22 -0800905 @GuardedBy("mLock")
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800906 private void loadBaseStateLocked() {
907 mRawLastResetTime = 0;
908
909 final AtomicFile file = getBaseStateFile();
910 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700911 Slog.d(TAG, "Loading from " + file.getBaseFile());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800912 }
913 try (FileInputStream in = file.openRead()) {
914 XmlPullParser parser = Xml.newPullParser();
915 parser.setInput(in, StandardCharsets.UTF_8.name());
916
917 int type;
918 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
919 if (type != XmlPullParser.START_TAG) {
920 continue;
921 }
922 final int depth = parser.getDepth();
923 // Check the root tag
924 final String tag = parser.getName();
925 if (depth == 1) {
926 if (!TAG_ROOT.equals(tag)) {
927 Slog.e(TAG, "Invalid root tag: " + tag);
928 return;
929 }
930 continue;
931 }
932 // Assume depth == 2
933 switch (tag) {
934 case TAG_LAST_RESET_TIME:
935 mRawLastResetTime = parseLongAttribute(parser, ATTR_VALUE);
936 break;
937 default:
938 Slog.e(TAG, "Invalid tag: " + tag);
939 break;
940 }
941 }
942 } catch (FileNotFoundException e) {
943 // Use the default
Makoto Onukib08790c2016-06-23 14:05:46 -0700944 } catch (IOException | XmlPullParserException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800945 Slog.e(TAG, "Failed to read file " + file.getBaseFile(), e);
946
947 mRawLastResetTime = 0;
948 }
949 // Adjust the last reset time.
950 getLastResetTimeLocked();
951 }
952
Makoto Onuki0eed4412016-07-21 11:21:59 -0700953 @VisibleForTesting
954 final File getUserFile(@UserIdInt int userId) {
955 return new File(injectUserDataPath(userId), FILENAME_USER_PACKAGES);
956 }
957
Andreas Gampea36dc622018-02-05 17:19:22 -0800958 @GuardedBy("mLock")
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800959 private void saveUserLocked(@UserIdInt int userId) {
Makoto Onuki0eed4412016-07-21 11:21:59 -0700960 final File path = getUserFile(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800961 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700962 Slog.d(TAG, "Saving to " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800963 }
Makoto Onuki475c3652017-05-08 14:29:03 -0700964
965 mShortcutBitmapSaver.waitForAllSavesLocked();
966
Makoto Onuki0eed4412016-07-21 11:21:59 -0700967 path.getParentFile().mkdirs();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800968 final AtomicFile file = new AtomicFile(path);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700969 FileOutputStream os = null;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800970 try {
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700971 os = file.startWrite();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800972
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700973 saveUserInternalLocked(userId, os, /* forBackup= */ false);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800974
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700975 file.finishWrite(os);
Makoto Onuki1e173232016-08-10 10:47:13 -0700976
977 // Remove all dangling bitmap files.
978 cleanupDanglingBitmapDirectoriesLocked(userId);
Makoto Onukib08790c2016-06-23 14:05:46 -0700979 } catch (XmlPullParserException | IOException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800980 Slog.e(TAG, "Failed to write to file " + file.getBaseFile(), e);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700981 file.failWrite(os);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800982 }
983 }
984
Andreas Gampea36dc622018-02-05 17:19:22 -0800985 @GuardedBy("mLock")
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700986 private void saveUserInternalLocked(@UserIdInt int userId, OutputStream os,
987 boolean forBackup) throws IOException, XmlPullParserException {
988
989 final BufferedOutputStream bos = new BufferedOutputStream(os);
990
991 // Write to XML
992 XmlSerializer out = new FastXmlSerializer();
993 out.setOutput(bos, StandardCharsets.UTF_8.name());
994 out.startDocument(null, true);
995
Makoto Onukic51b2872016-05-04 15:24:50 -0700996 getUserShortcutsLocked(userId).saveToXml(out, forBackup);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700997
998 out.endDocument();
999
1000 bos.flush();
1001 os.flush();
1002 }
1003
Makoto Onuki41066a62016-03-09 16:18:44 -08001004 static IOException throwForInvalidTag(int depth, String tag) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001005 throw new IOException(String.format("Invalid tag '%s' found at depth %d", tag, depth));
1006 }
1007
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001008 static void warnForInvalidTag(int depth, String tag) throws IOException {
1009 Slog.w(TAG, String.format("Invalid tag '%s' found at depth %d", tag, depth));
1010 }
1011
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001012 @Nullable
Makoto Onuki31459242016-03-22 11:12:18 -07001013 private ShortcutUser loadUserLocked(@UserIdInt int userId) {
Makoto Onuki0eed4412016-07-21 11:21:59 -07001014 final File path = getUserFile(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001015 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001016 Slog.d(TAG, "Loading from " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001017 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001018 final AtomicFile file = new AtomicFile(path);
1019
1020 final FileInputStream in;
1021 try {
1022 in = file.openRead();
1023 } catch (FileNotFoundException e) {
1024 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001025 Slog.d(TAG, "Not found " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001026 }
1027 return null;
1028 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001029 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07001030 final ShortcutUser ret = loadUserInternal(userId, in, /* forBackup= */ false);
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001031 return ret;
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07001032 } catch (IOException | XmlPullParserException | InvalidFileFormatException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001033 Slog.e(TAG, "Failed to read file " + file.getBaseFile(), e);
1034 return null;
1035 } finally {
1036 IoUtils.closeQuietly(in);
1037 }
1038 }
1039
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001040 private ShortcutUser loadUserInternal(@UserIdInt int userId, InputStream is,
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07001041 boolean fromBackup) throws XmlPullParserException, IOException,
1042 InvalidFileFormatException {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001043
1044 final BufferedInputStream bis = new BufferedInputStream(is);
1045
1046 ShortcutUser ret = null;
1047 XmlPullParser parser = Xml.newPullParser();
1048 parser.setInput(bis, StandardCharsets.UTF_8.name());
1049
1050 int type;
1051 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1052 if (type != XmlPullParser.START_TAG) {
1053 continue;
1054 }
1055 final int depth = parser.getDepth();
1056
1057 final String tag = parser.getName();
1058 if (DEBUG_LOAD) {
1059 Slog.d(TAG, String.format("depth=%d type=%d name=%s",
1060 depth, type, tag));
1061 }
1062 if ((depth == 1) && ShortcutUser.TAG_ROOT.equals(tag)) {
1063 ret = ShortcutUser.loadFromXml(this, parser, userId, fromBackup);
1064 continue;
1065 }
1066 throwForInvalidTag(depth, tag);
1067 }
1068 return ret;
1069 }
1070
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001071 private void scheduleSaveBaseState() {
Makoto Onuki0acbb142016-03-22 17:02:57 -07001072 scheduleSaveInner(UserHandle.USER_NULL); // Special case -- use USER_NULL for base state.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001073 }
1074
Makoto Onuki2d5b4652016-03-11 16:09:54 -08001075 void scheduleSaveUser(@UserIdInt int userId) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07001076 scheduleSaveInner(userId);
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001077 }
1078
1079 // In order to re-schedule, we need to reuse the same instance, so keep it in final.
1080 private final Runnable mSaveDirtyInfoRunner = this::saveDirtyInfo;
1081
Makoto Onuki0acbb142016-03-22 17:02:57 -07001082 private void scheduleSaveInner(@UserIdInt int userId) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001083 if (DEBUG) {
1084 Slog.d(TAG, "Scheduling to save for " + userId);
1085 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001086 synchronized (mLock) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001087 if (!mDirtyUserIds.contains(userId)) {
1088 mDirtyUserIds.add(userId);
1089 }
1090 }
1091 // If already scheduled, remove that and re-schedule in N seconds.
1092 mHandler.removeCallbacks(mSaveDirtyInfoRunner);
1093 mHandler.postDelayed(mSaveDirtyInfoRunner, mSaveDelayMillis);
1094 }
1095
1096 @VisibleForTesting
1097 void saveDirtyInfo() {
1098 if (DEBUG) {
1099 Slog.d(TAG, "saveDirtyInfo");
1100 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001101 try {
1102 synchronized (mLock) {
1103 for (int i = mDirtyUserIds.size() - 1; i >= 0; i--) {
1104 final int userId = mDirtyUserIds.get(i);
1105 if (userId == UserHandle.USER_NULL) { // USER_NULL for base state.
1106 saveBaseStateLocked();
1107 } else {
1108 saveUserLocked(userId);
1109 }
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001110 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001111 mDirtyUserIds.clear();
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001112 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001113 } catch (Exception e) {
1114 wtf("Exception in saveDirtyInfo", e);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001115 }
1116 }
1117
1118 /** Return the last reset time. */
Andreas Gampea36dc622018-02-05 17:19:22 -08001119 @GuardedBy("mLock")
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001120 long getLastResetTimeLocked() {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001121 updateTimesLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001122 return mRawLastResetTime;
1123 }
1124
1125 /** Return the next reset time. */
Andreas Gampea36dc622018-02-05 17:19:22 -08001126 @GuardedBy("mLock")
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001127 long getNextResetTimeLocked() {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001128 updateTimesLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001129 return mRawLastResetTime + mResetInterval;
1130 }
1131
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001132 static boolean isClockValid(long time) {
1133 return time >= 1420070400; // Thu, 01 Jan 2015 00:00:00 GMT
1134 }
1135
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001136 /**
1137 * Update the last reset time.
1138 */
Andreas Gampea36dc622018-02-05 17:19:22 -08001139 @GuardedBy("mLock")
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001140 private void updateTimesLocked() {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001141
1142 final long now = injectCurrentTimeMillis();
1143
1144 final long prevLastResetTime = mRawLastResetTime;
1145
1146 if (mRawLastResetTime == 0) { // first launch.
1147 // TODO Randomize??
1148 mRawLastResetTime = now;
1149 } else if (now < mRawLastResetTime) {
1150 // Clock rewound.
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001151 if (isClockValid(now)) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001152 Slog.w(TAG, "Clock rewound");
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001153 // TODO Randomize??
1154 mRawLastResetTime = now;
1155 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001156 } else {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001157 if ((mRawLastResetTime + mResetInterval) <= now) {
1158 final long offset = mRawLastResetTime % mResetInterval;
1159 mRawLastResetTime = ((now / mResetInterval) * mResetInterval) + offset;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001160 }
1161 }
1162 if (prevLastResetTime != mRawLastResetTime) {
1163 scheduleSaveBaseState();
1164 }
1165 }
1166
Makoto Onuki1e173232016-08-10 10:47:13 -07001167 // Requires mLock held, but "Locked" prefix would look weired so we just say "L".
Makoto Onuki02f338e2016-07-29 09:40:40 -07001168 protected boolean isUserUnlockedL(@UserIdInt int userId) {
Makoto Onuki1e173232016-08-10 10:47:13 -07001169 // First, check the local copy.
Makoto Onukie63b04a2017-12-11 14:47:19 -08001170 synchronized (mUnlockedUsers) {
1171 if (mUnlockedUsers.get(userId)) {
1172 return true;
1173 }
Makoto Onuki1e173232016-08-10 10:47:13 -07001174 }
Makoto Onukie63b04a2017-12-11 14:47:19 -08001175
Makoto Onuki1e173232016-08-10 10:47:13 -07001176 // If the local copy says the user is locked, check with AM for the actual state, since
1177 // the user might just have been unlocked.
1178 // Note we just don't use isUserUnlockingOrUnlocked() here, because it'll return false
1179 // when the user is STOPPING, which we still want to consider as "unlocked".
Sunny Goyal145c8f82018-02-15 14:27:09 -08001180 return mUserManagerInternal.isUserUnlockingOrUnlocked(userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07001181 }
1182
Makoto Onuki02f338e2016-07-29 09:40:40 -07001183 // Requires mLock held, but "Locked" prefix would look weired so we jsut say "L".
1184 void throwIfUserLockedL(@UserIdInt int userId) {
1185 if (!isUserUnlockedL(userId)) {
Makoto Onuki9c850012016-07-26 15:50:50 -07001186 throw new IllegalStateException("User " + userId + " is locked or not running");
1187 }
1188 }
1189
Makoto Onukicdc78f72016-03-21 15:47:52 -07001190 @GuardedBy("mLock")
1191 @NonNull
Makoto Onuki2e210c42016-03-30 08:30:36 -07001192 private boolean isUserLoadedLocked(@UserIdInt int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07001193 return mUsers.get(userId) != null;
1194 }
1195
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001196 /** Return the per-user state. */
1197 @GuardedBy("mLock")
1198 @NonNull
Makoto Onuki31459242016-03-22 11:12:18 -07001199 ShortcutUser getUserShortcutsLocked(@UserIdInt int userId) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001200 if (!isUserUnlockedL(userId)) {
Makoto Onuki9c850012016-07-26 15:50:50 -07001201 wtf("User still locked");
Makoto Onuki9c850012016-07-26 15:50:50 -07001202 }
1203
Makoto Onuki31459242016-03-22 11:12:18 -07001204 ShortcutUser userPackages = mUsers.get(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001205 if (userPackages == null) {
1206 userPackages = loadUserLocked(userId);
1207 if (userPackages == null) {
Makoto Onukic51b2872016-05-04 15:24:50 -07001208 userPackages = new ShortcutUser(this, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001209 }
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08001210 mUsers.put(userId, userPackages);
Makoto Onuki085a05c2016-08-19 11:39:29 -07001211
1212 // Also when a user's data is first accessed, scan all packages.
1213 checkPackageChanges(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001214 }
1215 return userPackages;
1216 }
1217
Makoto Onuki708703b2017-12-11 16:38:11 -08001218 /** Return the non-persistent per-user state. */
1219 @GuardedBy("mLock")
1220 @NonNull
1221 ShortcutNonPersistentUser getNonPersistentUserLocked(@UserIdInt int userId) {
1222 ShortcutNonPersistentUser ret = mShortcutNonPersistentUsers.get(userId);
1223 if (ret == null) {
1224 ret = new ShortcutNonPersistentUser(this, userId);
1225 mShortcutNonPersistentUsers.put(userId, ret);
1226 }
1227 return ret;
1228 }
1229
Andreas Gampea36dc622018-02-05 17:19:22 -08001230 @GuardedBy("mLock")
Makoto Onuki2e210c42016-03-30 08:30:36 -07001231 void forEachLoadedUserLocked(@NonNull Consumer<ShortcutUser> c) {
1232 for (int i = mUsers.size() - 1; i >= 0; i--) {
1233 c.accept(mUsers.valueAt(i));
1234 }
1235 }
1236
Makoto Onukic8c33292016-09-12 16:36:59 -07001237 /**
1238 * Return the per-user per-package state. If the caller is a publisher, use
1239 * {@link #getPackageShortcutsForPublisherLocked} instead.
1240 */
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001241 @GuardedBy("mLock")
1242 @NonNull
Makoto Onuki31459242016-03-22 11:12:18 -07001243 ShortcutPackage getPackageShortcutsLocked(
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001244 @NonNull String packageName, @UserIdInt int userId) {
Makoto Onukic51b2872016-05-04 15:24:50 -07001245 return getUserShortcutsLocked(userId).getPackageShortcuts(packageName);
Makoto Onukide667372016-03-15 14:29:20 -07001246 }
1247
Makoto Onukic8c33292016-09-12 16:36:59 -07001248 /** Return the per-user per-package state. Use this when the caller is a publisher. */
1249 @GuardedBy("mLock")
1250 @NonNull
1251 ShortcutPackage getPackageShortcutsForPublisherLocked(
1252 @NonNull String packageName, @UserIdInt int userId) {
1253 final ShortcutPackage ret = getUserShortcutsLocked(userId).getPackageShortcuts(packageName);
1254 ret.getUser().onCalledByPublisher(packageName);
1255 return ret;
1256 }
1257
Makoto Onukide667372016-03-15 14:29:20 -07001258 @GuardedBy("mLock")
1259 @NonNull
Makoto Onuki2e210c42016-03-30 08:30:36 -07001260 ShortcutLauncher getLauncherShortcutsLocked(
1261 @NonNull String packageName, @UserIdInt int ownerUserId,
1262 @UserIdInt int launcherUserId) {
1263 return getUserShortcutsLocked(ownerUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07001264 .getLauncherShortcuts(packageName, launcherUserId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001265 }
1266
1267 // === Caller validation ===
1268
Makoto Onuki475c3652017-05-08 14:29:03 -07001269 void removeIconLocked(ShortcutInfo shortcut) {
1270 mShortcutBitmapSaver.removeIcon(shortcut);
Makoto Onuki55046222016-03-08 10:49:47 -08001271 }
1272
Makoto Onuki0033b2a2016-04-14 17:19:16 -07001273 public void cleanupBitmapsForPackage(@UserIdInt int userId, String packageName) {
1274 final File packagePath = new File(getUserBitmapFilePath(userId), packageName);
1275 if (!packagePath.isDirectory()) {
1276 return;
1277 }
1278 if (!(FileUtils.deleteContents(packagePath) && packagePath.delete())) {
1279 Slog.w(TAG, "Unable to remove directory " + packagePath);
1280 }
1281 }
1282
Makoto Onuki475c3652017-05-08 14:29:03 -07001283 /**
1284 * Remove dangling bitmap files for a user.
1285 *
1286 * Note this method must be called with the lock held after calling
1287 * {@link ShortcutBitmapSaver#waitForAllSavesLocked()} to make sure there's no pending bitmap
1288 * saves are going on.
1289 */
Andreas Gampea36dc622018-02-05 17:19:22 -08001290 @GuardedBy("mLock")
Makoto Onuki1e173232016-08-10 10:47:13 -07001291 private void cleanupDanglingBitmapDirectoriesLocked(@UserIdInt int userId) {
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001292 if (DEBUG) {
1293 Slog.d(TAG, "cleanupDanglingBitmaps: userId=" + userId);
1294 }
Makoto Onuki84d59342018-02-02 09:22:38 -08001295 final long start = getStatStartTime();
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001296
Makoto Onuki1e173232016-08-10 10:47:13 -07001297 final ShortcutUser user = getUserShortcutsLocked(userId);
1298
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001299 final File bitmapDir = getUserBitmapFilePath(userId);
1300 final File[] children = bitmapDir.listFiles();
1301 if (children == null) {
1302 return;
1303 }
1304 for (File child : children) {
1305 if (!child.isDirectory()) {
1306 continue;
1307 }
1308 final String packageName = child.getName();
1309 if (DEBUG) {
1310 Slog.d(TAG, "cleanupDanglingBitmaps: Found directory=" + packageName);
1311 }
1312 if (!user.hasPackage(packageName)) {
1313 if (DEBUG) {
1314 Slog.d(TAG, "Removing dangling bitmap directory: " + packageName);
1315 }
1316 cleanupBitmapsForPackage(userId, packageName);
1317 } else {
1318 cleanupDanglingBitmapFilesLocked(userId, user, packageName, child);
1319 }
1320 }
1321 logDurationStat(Stats.CLEANUP_DANGLING_BITMAPS, start);
1322 }
1323
Makoto Onuki475c3652017-05-08 14:29:03 -07001324 /**
1325 * Remove dangling bitmap files for a package.
1326 *
1327 * Note this method must be called with the lock held after calling
1328 * {@link ShortcutBitmapSaver#waitForAllSavesLocked()} to make sure there's no pending bitmap
1329 * saves are going on.
1330 */
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001331 private void cleanupDanglingBitmapFilesLocked(@UserIdInt int userId, @NonNull ShortcutUser user,
1332 @NonNull String packageName, @NonNull File path) {
1333 final ArraySet<String> usedFiles =
Makoto Onukic51b2872016-05-04 15:24:50 -07001334 user.getPackageShortcuts(packageName).getUsedBitmapFiles();
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001335
1336 for (File child : path.listFiles()) {
1337 if (!child.isFile()) {
1338 continue;
1339 }
1340 final String name = child.getName();
1341 if (!usedFiles.contains(name)) {
1342 if (DEBUG) {
1343 Slog.d(TAG, "Removing dangling bitmap file: " + child.getAbsolutePath());
1344 }
1345 child.delete();
1346 }
1347 }
1348 }
1349
Makoto Onuki55046222016-03-08 10:49:47 -08001350 @VisibleForTesting
1351 static class FileOutputStreamWithPath extends FileOutputStream {
1352 private final File mFile;
1353
1354 public FileOutputStreamWithPath(File file) throws FileNotFoundException {
1355 super(file);
1356 mFile = file;
1357 }
1358
1359 public File getFile() {
1360 return mFile;
1361 }
1362 }
1363
1364 /**
1365 * Build the cached bitmap filename for a shortcut icon.
1366 *
1367 * The filename will be based on the ID, except certain characters will be escaped.
1368 */
Makoto Onuki55046222016-03-08 10:49:47 -08001369 FileOutputStreamWithPath openIconFileForWrite(@UserIdInt int userId, ShortcutInfo shortcut)
1370 throws IOException {
1371 final File packagePath = new File(getUserBitmapFilePath(userId),
Makoto Onuki22fcc682016-05-17 14:52:19 -07001372 shortcut.getPackage());
Makoto Onuki55046222016-03-08 10:49:47 -08001373 if (!packagePath.isDirectory()) {
1374 packagePath.mkdirs();
1375 if (!packagePath.isDirectory()) {
1376 throw new IOException("Unable to create directory " + packagePath);
1377 }
1378 SELinux.restorecon(packagePath);
1379 }
1380
1381 final String baseName = String.valueOf(injectCurrentTimeMillis());
Makoto Onukib08790c2016-06-23 14:05:46 -07001382 for (int suffix = 0; ; suffix++) {
Makoto Onuki55046222016-03-08 10:49:47 -08001383 final String filename = (suffix == 0 ? baseName : baseName + "_" + suffix) + ".png";
1384 final File file = new File(packagePath, filename);
1385 if (!file.exists()) {
1386 if (DEBUG) {
1387 Slog.d(TAG, "Saving icon to " + file.getAbsolutePath());
1388 }
1389 return new FileOutputStreamWithPath(file);
1390 }
1391 }
1392 }
1393
Makoto Onuki475c3652017-05-08 14:29:03 -07001394 void saveIconAndFixUpShortcutLocked(ShortcutInfo shortcut) {
Makoto Onuki55046222016-03-08 10:49:47 -08001395 if (shortcut.hasIconFile() || shortcut.hasIconResource()) {
1396 return;
1397 }
1398
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001399 final long token = injectClearCallingIdentity();
Makoto Onuki55046222016-03-08 10:49:47 -08001400 try {
1401 // Clear icon info on the shortcut.
Makoto Onuki475c3652017-05-08 14:29:03 -07001402 removeIconLocked(shortcut);
Makoto Onuki55046222016-03-08 10:49:47 -08001403
1404 final Icon icon = shortcut.getIcon();
1405 if (icon == null) {
1406 return; // has no icon
1407 }
Hyunyoung Song47037462017-05-08 16:51:43 -07001408 int maxIconDimension = mMaxIconDimension;
Makoto Onukiabe84422016-04-07 09:41:19 -07001409 Bitmap bitmap;
Makoto Onuki55046222016-03-08 10:49:47 -08001410 try {
1411 switch (icon.getType()) {
1412 case Icon.TYPE_RESOURCE: {
1413 injectValidateIconResPackage(shortcut, icon);
1414
1415 shortcut.setIconResourceId(icon.getResId());
1416 shortcut.addFlags(ShortcutInfo.FLAG_HAS_ICON_RES);
1417 return;
1418 }
Hyunyoung Songf281e7a2017-02-13 10:57:42 -08001419 case Icon.TYPE_BITMAP:
Makoto Onukiabe84422016-04-07 09:41:19 -07001420 bitmap = icon.getBitmap(); // Don't recycle in this case.
Makoto Onuki55046222016-03-08 10:49:47 -08001421 break;
Hyunyoung Song47037462017-05-08 16:51:43 -07001422 case Icon.TYPE_ADAPTIVE_BITMAP: {
1423 bitmap = icon.getBitmap(); // Don't recycle in this case.
1424 maxIconDimension *= (1 + 2 * AdaptiveIconDrawable.getExtraInsetFraction());
Hyunyoung Song8947f592017-05-15 10:12:11 -07001425 break;
Makoto Onuki55046222016-03-08 10:49:47 -08001426 }
Makoto Onuki55046222016-03-08 10:49:47 -08001427 default:
1428 // This shouldn't happen because we've already validated the icon, but
1429 // just in case.
1430 throw ShortcutInfo.getInvalidIconException();
1431 }
Makoto Onuki475c3652017-05-08 14:29:03 -07001432 mShortcutBitmapSaver.saveBitmapLocked(shortcut,
Hyunyoung Song47037462017-05-08 16:51:43 -07001433 maxIconDimension, mIconPersistFormat, mIconPersistQuality);
Makoto Onuki55046222016-03-08 10:49:47 -08001434 } finally {
Makoto Onuki55046222016-03-08 10:49:47 -08001435 // Once saved, we won't use the original icon information, so null it out.
1436 shortcut.clearIcon();
1437 }
1438 } finally {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001439 injectRestoreCallingIdentity(token);
Makoto Onuki55046222016-03-08 10:49:47 -08001440 }
1441 }
1442
1443 // Unfortunately we can't do this check in unit tests because we fake creator package names,
1444 // so override in unit tests.
1445 // TODO CTS this case.
1446 void injectValidateIconResPackage(ShortcutInfo shortcut, Icon icon) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07001447 if (!shortcut.getPackage().equals(icon.getResPackage())) {
Makoto Onuki55046222016-03-08 10:49:47 -08001448 throw new IllegalArgumentException(
1449 "Icon resource must reside in shortcut owner package");
1450 }
1451 }
1452
Makoto Onuki55046222016-03-08 10:49:47 -08001453 static Bitmap shrinkBitmap(Bitmap in, int maxSize) {
1454 // Original width/height.
1455 final int ow = in.getWidth();
1456 final int oh = in.getHeight();
1457 if ((ow <= maxSize) && (oh <= maxSize)) {
1458 if (DEBUG) {
1459 Slog.d(TAG, String.format("Icon size %dx%d, no need to shrink", ow, oh));
1460 }
1461 return in;
1462 }
1463 final int longerDimension = Math.max(ow, oh);
1464
1465 // New width and height.
1466 final int nw = ow * maxSize / longerDimension;
1467 final int nh = oh * maxSize / longerDimension;
1468 if (DEBUG) {
1469 Slog.d(TAG, String.format("Icon size %dx%d, shrinking to %dx%d",
1470 ow, oh, nw, nh));
1471 }
1472
1473 final Bitmap scaledBitmap = Bitmap.createBitmap(nw, nh, Bitmap.Config.ARGB_8888);
1474 final Canvas c = new Canvas(scaledBitmap);
1475
1476 final RectF dst = new RectF(0, 0, nw, nh);
1477
1478 c.drawBitmap(in, /*src=*/ null, dst, /* paint =*/ null);
1479
Makoto Onuki55046222016-03-08 10:49:47 -08001480 return scaledBitmap;
1481 }
1482
Makoto Onuki157b1622016-06-02 16:13:10 -07001483 /**
1484 * For a shortcut, update all resource names from resource IDs, and also update all
1485 * resource-based strings.
1486 */
1487 void fixUpShortcutResourceNamesAndValues(ShortcutInfo si) {
1488 final Resources publisherRes = injectGetResourcesForApplicationAsUser(
1489 si.getPackage(), si.getUserId());
1490 if (publisherRes != null) {
Makoto Onuki84d59342018-02-02 09:22:38 -08001491 final long start = getStatStartTime();
Makoto Onuki157b1622016-06-02 16:13:10 -07001492 try {
1493 si.lookupAndFillInResourceNames(publisherRes);
1494 } finally {
1495 logDurationStat(Stats.RESOURCE_NAME_LOOKUP, start);
1496 }
1497 si.resolveResourceStrings(publisherRes);
1498 }
1499 }
1500
Makoto Onuki55046222016-03-08 10:49:47 -08001501 // === Caller validation ===
1502
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001503 private boolean isCallerSystem() {
1504 final int callingUid = injectBinderCallingUid();
Makoto Onukib08790c2016-06-23 14:05:46 -07001505 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001506 }
1507
1508 private boolean isCallerShell() {
1509 final int callingUid = injectBinderCallingUid();
1510 return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
1511 }
1512
1513 private void enforceSystemOrShell() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001514 if (!(isCallerSystem() || isCallerShell())) {
1515 throw new SecurityException("Caller must be system or shell");
1516 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001517 }
1518
1519 private void enforceShell() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001520 if (!isCallerShell()) {
1521 throw new SecurityException("Caller must be shell");
1522 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001523 }
1524
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001525 private void enforceSystem() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001526 if (!isCallerSystem()) {
1527 throw new SecurityException("Caller must be system");
1528 }
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001529 }
1530
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001531 private void enforceResetThrottlingPermission() {
1532 if (isCallerSystem()) {
1533 return;
1534 }
Makoto Onuki76269922016-07-15 14:58:54 -07001535 enforceCallingOrSelfPermission(
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001536 android.Manifest.permission.RESET_SHORTCUT_MANAGER_THROTTLING, null);
1537 }
1538
Makoto Onuki76269922016-07-15 14:58:54 -07001539 private void enforceCallingOrSelfPermission(
1540 @NonNull String permission, @Nullable String message) {
1541 if (isCallerSystem()) {
1542 return;
1543 }
1544 injectEnforceCallingPermission(permission, message);
1545 }
1546
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001547 /**
1548 * Somehow overriding ServiceContext.enforceCallingPermission() in the unit tests would confuse
1549 * mockito. So instead we extracted it here and override it in the tests.
1550 */
1551 @VisibleForTesting
1552 void injectEnforceCallingPermission(
1553 @NonNull String permission, @Nullable String message) {
1554 mContext.enforceCallingPermission(permission, message);
1555 }
1556
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001557 private void verifyCaller(@NonNull String packageName, @UserIdInt int userId) {
1558 Preconditions.checkStringNotEmpty(packageName, "packageName");
1559
1560 if (isCallerSystem()) {
1561 return; // no check
1562 }
1563
1564 final int callingUid = injectBinderCallingUid();
1565
1566 // Otherwise, make sure the arguments are valid.
1567 if (UserHandle.getUserId(callingUid) != userId) {
1568 throw new SecurityException("Invalid user-ID");
1569 }
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08001570 if (injectGetPackageUid(packageName, userId) != callingUid) {
1571 throw new SecurityException("Calling package name mismatch");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001572 }
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08001573 Preconditions.checkState(!isEphemeralApp(packageName, userId),
1574 "Ephemeral apps can't use ShortcutManager");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001575 }
1576
Makoto Onuki9e215792018-06-12 13:01:42 -07001577 private void verifyShortcutInfoPackage(String callerPackage, ShortcutInfo si) {
1578 if (si == null) {
1579 return;
1580 }
1581 if (!Objects.equals(callerPackage, si.getPackage())) {
1582 android.util.EventLog.writeEvent(0x534e4554, "109824443", -1, "");
1583 throw new SecurityException("Shortcut package name mismatch");
1584 }
1585 }
1586
1587 private void verifyShortcutInfoPackages(
1588 String callerPackage, List<ShortcutInfo> list) {
1589 final int size = list.size();
1590 for (int i = 0; i < size; i++) {
1591 verifyShortcutInfoPackage(callerPackage, list.get(i));
1592 }
1593 }
1594
Makoto Onuki157b1622016-06-02 16:13:10 -07001595 // Overridden in unit tests to execute r synchronously.
1596 void injectPostToHandler(Runnable r) {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001597 mHandler.post(r);
1598 }
1599
Makoto Onuki085a05c2016-08-19 11:39:29 -07001600 void injectRunOnNewThread(Runnable r) {
1601 new Thread(r).start();
1602 }
1603
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001604 /**
Makoto Onuki7001a612016-05-27 13:24:28 -07001605 * @throws IllegalArgumentException if {@code numShortcuts} is bigger than
Makoto Onukib08790c2016-06-23 14:05:46 -07001606 * {@link #getMaxActivityShortcuts()}.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001607 */
Makoto Onuki7001a612016-05-27 13:24:28 -07001608 void enforceMaxActivityShortcuts(int numShortcuts) {
Makoto Onukib5a012f2016-06-21 11:13:53 -07001609 if (numShortcuts > mMaxShortcuts) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001610 throw new IllegalArgumentException("Max number of dynamic shortcuts exceeded");
1611 }
1612 }
1613
1614 /**
Makoto Onuki7001a612016-05-27 13:24:28 -07001615 * Return the max number of dynamic + manifest shortcuts for each launcher icon.
1616 */
1617 int getMaxActivityShortcuts() {
Makoto Onukib5a012f2016-06-21 11:13:53 -07001618 return mMaxShortcuts;
Makoto Onuki7001a612016-05-27 13:24:28 -07001619 }
1620
1621 /**
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001622 * - Sends a notification to LauncherApps
1623 * - Write to file
1624 */
Makoto Onuki39686e82016-04-13 18:03:00 -07001625 void packageShortcutsChanged(@NonNull String packageName, @UserIdInt int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001626 notifyListeners(packageName, userId);
1627 scheduleSaveUser(userId);
1628 }
1629
1630 private void notifyListeners(@NonNull String packageName, @UserIdInt int userId) {
Makoto Onuki82fb2eb2017-03-31 16:58:26 -07001631 if (DEBUG) {
1632 Slog.d(TAG, String.format(
1633 "Shortcut changes: package=%s, user=%d", packageName, userId));
1634 }
Makoto Onuki157b1622016-06-02 16:13:10 -07001635 injectPostToHandler(() -> {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001636 try {
1637 final ArrayList<ShortcutChangeListener> copy;
1638 synchronized (mLock) {
1639 if (!isUserUnlockedL(userId)) {
1640 return;
1641 }
1642
1643 copy = new ArrayList<>(mListeners);
1644 }
1645 // Note onShortcutChanged() needs to be called with the system service permissions.
1646 for (int i = copy.size() - 1; i >= 0; i--) {
1647 copy.get(i).onShortcutChanged(packageName, userId);
1648 }
1649 } catch (Exception ignore) {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001650 }
1651 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001652 }
1653
1654 /**
1655 * Clean up / validate an incoming shortcut.
1656 * - Make sure all mandatory fields are set.
1657 * - Make sure the intent's extras are persistable, and them to set
Makoto Onuki0eed4412016-07-21 11:21:59 -07001658 * {@link ShortcutInfo#mIntentPersistableExtrases}. Also clear its extras.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001659 * - Clear flags.
1660 */
Makoto Onuki2d895c32016-12-02 15:48:40 -08001661 private void fixUpIncomingShortcutInfo(@NonNull ShortcutInfo shortcut, boolean forUpdate,
1662 boolean forPinRequest) {
Makoto Onukibf563b62017-05-04 10:25:30 -07001663 if (shortcut.isReturnedByServer()) {
1664 Log.w(TAG,
1665 "Re-publishing ShortcutInfo returned by server is not supported."
1666 + " Some information such as icon may lost from shortcut.");
1667 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001668 Preconditions.checkNotNull(shortcut, "Null shortcut detected");
Makoto Onuki255461f2017-01-10 11:47:25 -08001669 if (shortcut.getActivity() != null) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001670 Preconditions.checkState(
Makoto Onuki22fcc682016-05-17 14:52:19 -07001671 shortcut.getPackage().equals(shortcut.getActivity().getPackageName()),
Makoto Onukib08790c2016-06-23 14:05:46 -07001672 "Cannot publish shortcut: activity " + shortcut.getActivity() + " does not"
1673 + " belong to package " + shortcut.getPackage());
Makoto Onuki13260b6ff2016-07-13 18:03:13 -07001674 Preconditions.checkState(
1675 injectIsMainActivity(shortcut.getActivity(), shortcut.getUserId()),
1676 "Cannot publish shortcut: activity " + shortcut.getActivity() + " is not"
1677 + " main activity");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001678 }
1679
Makoto Onuki55046222016-03-08 10:49:47 -08001680 if (!forUpdate) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08001681 shortcut.enforceMandatoryFields(/* forPinned= */ forPinRequest);
1682 if (!forPinRequest) {
Makoto Onuki255461f2017-01-10 11:47:25 -08001683 Preconditions.checkState(shortcut.getActivity() != null,
1684 "Cannot publish shortcut: target activity is not set");
Makoto Onuki2d895c32016-12-02 15:48:40 -08001685 }
Makoto Onuki55046222016-03-08 10:49:47 -08001686 }
1687 if (shortcut.getIcon() != null) {
1688 ShortcutInfo.validateIcon(shortcut.getIcon());
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001689 }
1690
Makoto Onukide667372016-03-15 14:29:20 -07001691 shortcut.replaceFlags(0);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001692 }
1693
Makoto Onuki2d895c32016-12-02 15:48:40 -08001694 private void fixUpIncomingShortcutInfo(@NonNull ShortcutInfo shortcut, boolean forUpdate) {
1695 fixUpIncomingShortcutInfo(shortcut, forUpdate, /*forPinRequest=*/ false);
1696 }
1697
1698 public void validateShortcutForPinRequest(@NonNull ShortcutInfo shortcut) {
1699 fixUpIncomingShortcutInfo(shortcut, /* forUpdate= */ false, /*forPinRequest=*/ true);
1700 }
1701
Makoto Onukib08790c2016-06-23 14:05:46 -07001702 /**
1703 * When a shortcut has no target activity, set the default one from the package.
1704 */
1705 private void fillInDefaultActivity(List<ShortcutInfo> shortcuts) {
Makoto Onukib08790c2016-06-23 14:05:46 -07001706 ComponentName defaultActivity = null;
1707 for (int i = shortcuts.size() - 1; i >= 0; i--) {
1708 final ShortcutInfo si = shortcuts.get(i);
1709 if (si.getActivity() == null) {
1710 if (defaultActivity == null) {
1711 defaultActivity = injectGetDefaultMainActivity(
1712 si.getPackage(), si.getUserId());
1713 Preconditions.checkState(defaultActivity != null,
1714 "Launcher activity not found for package " + si.getPackage());
1715 }
1716 si.setActivity(defaultActivity);
1717 }
1718 }
1719 }
1720
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001721 private void assignImplicitRanks(List<ShortcutInfo> shortcuts) {
1722 for (int i = shortcuts.size() - 1; i >= 0; i--) {
1723 shortcuts.get(i).setImplicitRank(i);
1724 }
1725 }
1726
Makoto Onukibf563b62017-05-04 10:25:30 -07001727 private List<ShortcutInfo> setReturnedByServer(List<ShortcutInfo> shortcuts) {
1728 for (int i = shortcuts.size() - 1; i >= 0; i--) {
1729 shortcuts.get(i).setReturnedByServer();
1730 }
1731 return shortcuts;
1732 }
1733
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001734 // === APIs ===
1735
1736 @Override
1737 public boolean setDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1738 @UserIdInt int userId) {
1739 verifyCaller(packageName, userId);
1740
1741 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
Makoto Onuki9e215792018-06-12 13:01:42 -07001742 verifyShortcutInfoPackages(packageName, newShortcuts);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001743 final int size = newShortcuts.size();
1744
Makoto Onuki7d0fa812018-02-21 11:24:43 -08001745 final boolean unlimited = injectHasUnlimitedShortcutsApiCallsPermission(
1746 injectBinderCallingPid(), injectBinderCallingUid());
1747
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001748 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001749 throwIfUserLockedL(userId);
1750
Makoto Onukic8c33292016-09-12 16:36:59 -07001751 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001752
Makoto Onukia4f89b12017-10-05 10:37:55 -07001753 ps.ensureImmutableShortcutsNotIncluded(newShortcuts, /*ignoreInvisible=*/ true);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001754
Makoto Onukib08790c2016-06-23 14:05:46 -07001755 fillInDefaultActivity(newShortcuts);
1756
Makoto Onuki7001a612016-05-27 13:24:28 -07001757 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_SET);
1758
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001759 // Throttling.
Makoto Onuki7d0fa812018-02-21 11:24:43 -08001760 if (!ps.tryApiCall(unlimited)) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001761 return false;
1762 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001763
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001764 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1765 ps.clearAllImplicitRanks();
1766 assignImplicitRanks(newShortcuts);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001767
Makoto Onukidf6da042016-06-16 09:51:40 -07001768 for (int i = 0; i < size; i++) {
1769 fixUpIncomingShortcutInfo(newShortcuts.get(i), /* forUpdate= */ false);
1770 }
1771
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001772 // First, remove all un-pinned; dynamic shortcuts
Makoto Onukia4f89b12017-10-05 10:37:55 -07001773 ps.deleteAllDynamicShortcuts(/*ignoreInvisible=*/ true);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001774
1775 // Then, add/update all. We need to make sure to take over "pinned" flag.
1776 for (int i = 0; i < size; i++) {
1777 final ShortcutInfo newShortcut = newShortcuts.get(i);
Makoto Onukia4f89b12017-10-05 10:37:55 -07001778 ps.addOrReplaceDynamicShortcut(newShortcut);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001779 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001780
1781 // Lastly, adjust the ranks.
1782 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001783 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001784 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001785
1786 verifyStates();
1787
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001788 return true;
1789 }
1790
1791 @Override
1792 public boolean updateShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1793 @UserIdInt int userId) {
1794 verifyCaller(packageName, userId);
1795
1796 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
Makoto Onuki9e215792018-06-12 13:01:42 -07001797 verifyShortcutInfoPackages(packageName, newShortcuts);
Makoto Onuki55046222016-03-08 10:49:47 -08001798 final int size = newShortcuts.size();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001799
Makoto Onuki7d0fa812018-02-21 11:24:43 -08001800 final boolean unlimited = injectHasUnlimitedShortcutsApiCallsPermission(
1801 injectBinderCallingPid(), injectBinderCallingUid());
1802
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001803 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001804 throwIfUserLockedL(userId);
1805
Makoto Onukic8c33292016-09-12 16:36:59 -07001806 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001807
Makoto Onukia4f89b12017-10-05 10:37:55 -07001808 ps.ensureImmutableShortcutsNotIncluded(newShortcuts, /*ignoreInvisible=*/ true);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001809
Makoto Onukib08790c2016-06-23 14:05:46 -07001810 // For update, don't fill in the default activity. Having null activity means
1811 // "don't update the activity" here.
1812
Makoto Onuki7001a612016-05-27 13:24:28 -07001813 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_UPDATE);
1814
Makoto Onuki55046222016-03-08 10:49:47 -08001815 // Throttling.
Makoto Onuki7d0fa812018-02-21 11:24:43 -08001816 if (!ps.tryApiCall(unlimited)) {
Makoto Onuki55046222016-03-08 10:49:47 -08001817 return false;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001818 }
1819
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001820 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1821 ps.clearAllImplicitRanks();
1822 assignImplicitRanks(newShortcuts);
1823
Makoto Onuki55046222016-03-08 10:49:47 -08001824 for (int i = 0; i < size; i++) {
1825 final ShortcutInfo source = newShortcuts.get(i);
1826 fixUpIncomingShortcutInfo(source, /* forUpdate= */ true);
1827
1828 final ShortcutInfo target = ps.findShortcutById(source.getId());
Makoto Onukia4f89b12017-10-05 10:37:55 -07001829
1830 // Invisible shortcuts can't be updated.
1831 if (target == null || !target.isVisibleToPublisher()) {
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001832 continue;
1833 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07001834
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001835 if (target.isEnabled() != source.isEnabled()) {
1836 Slog.w(TAG,
1837 "ShortcutInfo.enabled cannot be changed with updateShortcuts()");
1838 }
Makoto Onuki55046222016-03-08 10:49:47 -08001839
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001840 // When updating the rank, we need to insert between existing ranks, so set
1841 // this setRankChanged, and also copy the implicit rank fo adjustRanks().
1842 if (source.hasRank()) {
1843 target.setRankChanged();
1844 target.setImplicitRank(source.getImplicitRank());
1845 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07001846
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001847 final boolean replacingIcon = (source.getIcon() != null);
1848 if (replacingIcon) {
Makoto Onuki475c3652017-05-08 14:29:03 -07001849 removeIconLocked(target);
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001850 }
Makoto Onuki55046222016-03-08 10:49:47 -08001851
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001852 // Note copyNonNullFieldsFrom() does the "updatable with?" check too.
1853 target.copyNonNullFieldsFrom(source);
1854 target.setTimestamp(injectCurrentTimeMillis());
1855
1856 if (replacingIcon) {
Makoto Onuki475c3652017-05-08 14:29:03 -07001857 saveIconAndFixUpShortcutLocked(target);
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001858 }
1859
1860 // When we're updating any resource related fields, re-extract the res names and
1861 // the values.
1862 if (replacingIcon || source.hasStringResources()) {
1863 fixUpShortcutResourceNamesAndValues(target);
Makoto Onuki55046222016-03-08 10:49:47 -08001864 }
1865 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001866
1867 // Lastly, adjust the ranks.
1868 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001869 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001870 packageShortcutsChanged(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001871
Makoto Onuki7001a612016-05-27 13:24:28 -07001872 verifyStates();
1873
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001874 return true;
1875 }
1876
1877 @Override
Makoto Onukia4f89b12017-10-05 10:37:55 -07001878 public boolean addDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001879 @UserIdInt int userId) {
1880 verifyCaller(packageName, userId);
1881
Makoto Onukib6d35232016-04-04 15:57:17 -07001882 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
Makoto Onuki9e215792018-06-12 13:01:42 -07001883 verifyShortcutInfoPackages(packageName, newShortcuts);
Makoto Onukib6d35232016-04-04 15:57:17 -07001884 final int size = newShortcuts.size();
1885
Makoto Onuki7d0fa812018-02-21 11:24:43 -08001886 final boolean unlimited = injectHasUnlimitedShortcutsApiCallsPermission(
1887 injectBinderCallingPid(), injectBinderCallingUid());
1888
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001889 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001890 throwIfUserLockedL(userId);
1891
Makoto Onukic8c33292016-09-12 16:36:59 -07001892 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001893
Makoto Onukia4f89b12017-10-05 10:37:55 -07001894 ps.ensureImmutableShortcutsNotIncluded(newShortcuts, /*ignoreInvisible=*/ true);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001895
Makoto Onukib08790c2016-06-23 14:05:46 -07001896 fillInDefaultActivity(newShortcuts);
1897
Makoto Onuki7001a612016-05-27 13:24:28 -07001898 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_ADD);
1899
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001900 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1901 ps.clearAllImplicitRanks();
1902 assignImplicitRanks(newShortcuts);
1903
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001904 // Throttling.
Makoto Onuki7d0fa812018-02-21 11:24:43 -08001905 if (!ps.tryApiCall(unlimited)) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001906 return false;
1907 }
Makoto Onukib6d35232016-04-04 15:57:17 -07001908 for (int i = 0; i < size; i++) {
1909 final ShortcutInfo newShortcut = newShortcuts.get(i);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001910
Makoto Onukib6d35232016-04-04 15:57:17 -07001911 // Validate the shortcut.
1912 fixUpIncomingShortcutInfo(newShortcut, /* forUpdate= */ false);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001913
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001914 // When ranks are changing, we need to insert between ranks, so set the
1915 // "rank changed" flag.
1916 newShortcut.setRankChanged();
1917
Makoto Onukib6d35232016-04-04 15:57:17 -07001918 // Add it.
Makoto Onukia4f89b12017-10-05 10:37:55 -07001919 ps.addOrReplaceDynamicShortcut(newShortcut);
Makoto Onukib6d35232016-04-04 15:57:17 -07001920 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001921
1922 // Lastly, adjust the ranks.
1923 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001924 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001925 packageShortcutsChanged(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001926
Makoto Onuki7001a612016-05-27 13:24:28 -07001927 verifyStates();
1928
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001929 return true;
1930 }
1931
1932 @Override
Makoto Onuki2d895c32016-12-02 15:48:40 -08001933 public boolean requestPinShortcut(String packageName, ShortcutInfo shortcut,
1934 IntentSender resultIntent, int userId) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08001935 Preconditions.checkNotNull(shortcut);
1936 Preconditions.checkArgument(shortcut.isEnabled(), "Shortcut must be enabled");
Sunny Goyal4ad6b572017-02-28 11:11:51 -08001937 return requestPinItem(packageName, userId, shortcut, null, null, resultIntent);
Sunny Goyal87a563e2017-01-01 19:42:45 -08001938 }
1939
Sunny Goyala6be88a2017-01-12 16:27:58 -08001940 @Override
1941 public Intent createShortcutResultIntent(String packageName, ShortcutInfo shortcut, int userId)
1942 throws RemoteException {
1943 Preconditions.checkNotNull(shortcut);
1944 Preconditions.checkArgument(shortcut.isEnabled(), "Shortcut must be enabled");
1945 verifyCaller(packageName, userId);
Makoto Onuki9e215792018-06-12 13:01:42 -07001946 verifyShortcutInfoPackage(packageName, shortcut);
Sunny Goyala6be88a2017-01-12 16:27:58 -08001947
1948 final Intent ret;
1949 synchronized (mLock) {
1950 throwIfUserLockedL(userId);
1951
1952 // Send request to the launcher, if supported.
1953 ret = mShortcutRequestPinProcessor.createShortcutResultIntent(shortcut, userId);
1954 }
1955
1956 verifyStates();
1957 return ret;
1958 }
1959
Sunny Goyal87a563e2017-01-01 19:42:45 -08001960 /**
1961 * Handles {@link #requestPinShortcut} and {@link ShortcutServiceInternal#requestPinAppWidget}.
1962 * After validating the caller, it passes the request to {@link #mShortcutRequestPinProcessor}.
1963 * Either {@param shortcut} or {@param appWidget} should be non-null.
1964 */
Sunny Goyal4ad6b572017-02-28 11:11:51 -08001965 private boolean requestPinItem(String packageName, int userId, ShortcutInfo shortcut,
1966 AppWidgetProviderInfo appWidget, Bundle extras, IntentSender resultIntent) {
Sunny Goyal87a563e2017-01-01 19:42:45 -08001967 verifyCaller(packageName, userId);
Makoto Onuki9e215792018-06-12 13:01:42 -07001968 verifyShortcutInfoPackage(packageName, shortcut);
Makoto Onuki2d895c32016-12-02 15:48:40 -08001969
1970 final boolean ret;
1971 synchronized (mLock) {
1972 throwIfUserLockedL(userId);
1973
Makoto Onukia01f4f02016-12-15 15:58:41 -08001974 Preconditions.checkState(isUidForegroundLocked(injectBinderCallingUid()),
Makoto Onuki255461f2017-01-10 11:47:25 -08001975 "Calling application must have a foreground activity or a foreground service");
Makoto Onuki2d895c32016-12-02 15:48:40 -08001976
Makoto Onukia4f89b12017-10-05 10:37:55 -07001977 // If it's a pin shortcut request, and there's already a shortcut with the same ID
1978 // that's not visible to the caller (i.e. restore-blocked; meaning it's pinned by
1979 // someone already), then we just replace the existing one with this new one,
1980 // and then proceed the rest of the process.
1981 if (shortcut != null) {
1982 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(
1983 packageName, userId);
1984 final String id = shortcut.getId();
1985 if (ps.isShortcutExistsAndInvisibleToPublisher(id)) {
1986
1987 ps.updateInvisibleShortcutForPinRequestWith(shortcut);
1988
1989 packageShortcutsChanged(packageName, userId);
1990 }
1991 }
1992
Makoto Onuki2d895c32016-12-02 15:48:40 -08001993 // Send request to the launcher, if supported.
Sunny Goyal4ad6b572017-02-28 11:11:51 -08001994 ret = mShortcutRequestPinProcessor.requestPinItemLocked(shortcut, appWidget, extras,
1995 userId, resultIntent);
Makoto Onuki2d895c32016-12-02 15:48:40 -08001996 }
1997
1998 verifyStates();
1999
2000 return ret;
2001 }
2002
2003 @Override
Makoto Onuki20c95f82016-05-11 16:51:01 -07002004 public void disableShortcuts(String packageName, List shortcutIds,
Makoto Onukid6880792016-06-29 13:37:43 -07002005 CharSequence disabledMessage, int disabledMessageResId, @UserIdInt int userId) {
Makoto Onuki20c95f82016-05-11 16:51:01 -07002006 verifyCaller(packageName, userId);
2007 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
2008
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 Onukid6880792016-06-29 13:37:43 -07002017 final String disabledMessageString =
2018 (disabledMessage == null) ? null : disabledMessage.toString();
2019
Makoto Onuki22fcc682016-05-17 14:52:19 -07002020 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
Makoto Onukia4f89b12017-10-05 10:37:55 -07002021 final String id = Preconditions.checkStringNotEmpty((String) shortcutIds.get(i));
2022 if (!ps.isShortcutExistsAndVisibleToPublisher(id)) {
2023 continue;
2024 }
2025 ps.disableWithId(id,
Makoto Onukid6880792016-06-29 13:37:43 -07002026 disabledMessageString, disabledMessageResId,
Makoto Onukia4f89b12017-10-05 10:37:55 -07002027 /* overrideImmutable=*/ false, /*ignoreInvisible=*/ true,
2028 ShortcutInfo.DISABLED_REASON_BY_APP);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002029 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002030
2031 // We may have removed dynamic shortcuts which may have left a gap, so adjust the ranks.
2032 ps.adjustRanks();
Makoto Onuki22fcc682016-05-17 14:52:19 -07002033 }
2034 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07002035
2036 verifyStates();
Makoto Onuki22fcc682016-05-17 14:52:19 -07002037 }
2038
2039 @Override
2040 public void enableShortcuts(String packageName, List shortcutIds, @UserIdInt int userId) {
2041 verifyCaller(packageName, userId);
2042 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
2043
2044 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002045 throwIfUserLockedL(userId);
2046
Makoto Onukic8c33292016-09-12 16:36:59 -07002047 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002048
Makoto Onukia4f89b12017-10-05 10:37:55 -07002049 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds,
2050 /*ignoreInvisible=*/ true);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002051
2052 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
Makoto Onukia4f89b12017-10-05 10:37:55 -07002053 final String id = Preconditions.checkStringNotEmpty((String) shortcutIds.get(i));
2054 if (!ps.isShortcutExistsAndVisibleToPublisher(id)) {
2055 continue;
2056 }
2057 ps.enableWithId(id);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002058 }
Makoto Onuki20c95f82016-05-11 16:51:01 -07002059 }
2060 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07002061
2062 verifyStates();
Makoto Onuki20c95f82016-05-11 16:51:01 -07002063 }
2064
2065 @Override
Makoto Onukib6d35232016-04-04 15:57:17 -07002066 public void removeDynamicShortcuts(String packageName, List shortcutIds,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002067 @UserIdInt int userId) {
2068 verifyCaller(packageName, userId);
Makoto Onukib6d35232016-04-04 15:57:17 -07002069 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002070
2071 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002072 throwIfUserLockedL(userId);
2073
Makoto Onukic8c33292016-09-12 16:36:59 -07002074 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002075
Makoto Onukia4f89b12017-10-05 10:37:55 -07002076 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds,
2077 /*ignoreInvisible=*/ true);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002078
Makoto Onukib6d35232016-04-04 15:57:17 -07002079 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
Makoto Onukia4f89b12017-10-05 10:37:55 -07002080 final String id = Preconditions.checkStringNotEmpty((String) shortcutIds.get(i));
2081 if (!ps.isShortcutExistsAndVisibleToPublisher(id)) {
2082 continue;
2083 }
2084 ps.deleteDynamicWithId(id, /*ignoreInvisible=*/ true);
Makoto Onukib6d35232016-04-04 15:57:17 -07002085 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002086
2087 // We may have removed dynamic shortcuts which may have left a gap, so adjust the ranks.
2088 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002089 }
Makoto Onuki39686e82016-04-13 18:03:00 -07002090 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07002091
2092 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002093 }
2094
2095 @Override
Makoto Onukib6d35232016-04-04 15:57:17 -07002096 public void removeAllDynamicShortcuts(String packageName, @UserIdInt int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002097 verifyCaller(packageName, userId);
2098
2099 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002100 throwIfUserLockedL(userId);
2101
Makoto Onukic8c33292016-09-12 16:36:59 -07002102 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onukia4f89b12017-10-05 10:37:55 -07002103 ps.deleteAllDynamicShortcuts(/*ignoreInvisible=*/ true);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002104 }
Makoto Onuki39686e82016-04-13 18:03:00 -07002105 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07002106
2107 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002108 }
2109
2110 @Override
2111 public ParceledListSlice<ShortcutInfo> getDynamicShortcuts(String packageName,
2112 @UserIdInt int userId) {
2113 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002114
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002115 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002116 throwIfUserLockedL(userId);
2117
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002118 return getShortcutsWithQueryLocked(
2119 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
Makoto Onukia4f89b12017-10-05 10:37:55 -07002120 ShortcutInfo::isDynamicVisible);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002121 }
2122 }
2123
2124 @Override
Makoto Onuki22fcc682016-05-17 14:52:19 -07002125 public ParceledListSlice<ShortcutInfo> getManifestShortcuts(String packageName,
2126 @UserIdInt int userId) {
2127 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002128
Makoto Onuki22fcc682016-05-17 14:52:19 -07002129 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002130 throwIfUserLockedL(userId);
2131
Makoto Onuki22fcc682016-05-17 14:52:19 -07002132 return getShortcutsWithQueryLocked(
2133 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
Makoto Onukia4f89b12017-10-05 10:37:55 -07002134 ShortcutInfo::isManifestVisible);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002135 }
2136 }
2137
2138 @Override
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002139 public ParceledListSlice<ShortcutInfo> getPinnedShortcuts(String packageName,
2140 @UserIdInt int userId) {
2141 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002142
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002143 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002144 throwIfUserLockedL(userId);
2145
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002146 return getShortcutsWithQueryLocked(
2147 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
Makoto Onukia4f89b12017-10-05 10:37:55 -07002148 ShortcutInfo::isPinnedVisible);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002149 }
2150 }
2151
Andreas Gampea36dc622018-02-05 17:19:22 -08002152 @GuardedBy("mLock")
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002153 private ParceledListSlice<ShortcutInfo> getShortcutsWithQueryLocked(@NonNull String packageName,
2154 @UserIdInt int userId, int cloneFlags, @NonNull Predicate<ShortcutInfo> query) {
2155
2156 final ArrayList<ShortcutInfo> ret = new ArrayList<>();
2157
Makoto Onukic8c33292016-09-12 16:36:59 -07002158 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002159 ps.findAll(ret, query, cloneFlags);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002160
Makoto Onukibf563b62017-05-04 10:25:30 -07002161 return new ParceledListSlice<>(setReturnedByServer(ret));
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002162 }
2163
2164 @Override
Makoto Onukid6880792016-06-29 13:37:43 -07002165 public int getMaxShortcutCountPerActivity(String packageName, @UserIdInt int userId)
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002166 throws RemoteException {
2167 verifyCaller(packageName, userId);
2168
Makoto Onukib5a012f2016-06-21 11:13:53 -07002169 return mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002170 }
2171
2172 @Override
2173 public int getRemainingCallCount(String packageName, @UserIdInt int userId) {
2174 verifyCaller(packageName, userId);
2175
Makoto Onuki7d0fa812018-02-21 11:24:43 -08002176 final boolean unlimited = injectHasUnlimitedShortcutsApiCallsPermission(
2177 injectBinderCallingPid(), injectBinderCallingUid());
2178
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002179 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002180 throwIfUserLockedL(userId);
2181
Makoto Onukic8c33292016-09-12 16:36:59 -07002182 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki7d0fa812018-02-21 11:24:43 -08002183 return mMaxUpdatesPerInterval - ps.getApiCallCount(unlimited);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002184 }
2185 }
2186
2187 @Override
2188 public long getRateLimitResetTime(String packageName, @UserIdInt int userId) {
2189 verifyCaller(packageName, userId);
2190
2191 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002192 throwIfUserLockedL(userId);
2193
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002194 return getNextResetTimeLocked();
2195 }
2196 }
2197
Makoto Onuki55046222016-03-08 10:49:47 -08002198 @Override
Makoto Onuki20c95f82016-05-11 16:51:01 -07002199 public int getIconMaxDimensions(String packageName, int userId) {
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002200 verifyCaller(packageName, userId);
2201
Makoto Onuki55046222016-03-08 10:49:47 -08002202 synchronized (mLock) {
2203 return mMaxIconDimension;
2204 }
2205 }
2206
Makoto Onuki20c95f82016-05-11 16:51:01 -07002207 @Override
2208 public void reportShortcutUsed(String packageName, String shortcutId, int userId) {
2209 verifyCaller(packageName, userId);
2210
Makoto Onukiac042502016-05-20 16:39:42 -07002211 Preconditions.checkNotNull(shortcutId);
2212
2213 if (DEBUG) {
2214 Slog.d(TAG, String.format("reportShortcutUsed: Shortcut %s package %s used on user %d",
2215 shortcutId, packageName, userId));
2216 }
2217
2218 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002219 throwIfUserLockedL(userId);
2220
Makoto Onukic8c33292016-09-12 16:36:59 -07002221 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002222
Makoto Onukiac042502016-05-20 16:39:42 -07002223 if (ps.findShortcutById(shortcutId) == null) {
2224 Log.w(TAG, String.format("reportShortcutUsed: package %s doesn't have shortcut %s",
2225 packageName, shortcutId));
2226 return;
2227 }
2228 }
2229
2230 final long token = injectClearCallingIdentity();
2231 try {
2232 mUsageStatsManagerInternal.reportShortcutUsage(packageName, shortcutId, userId);
2233 } finally {
2234 injectRestoreCallingIdentity(token);
2235 }
Makoto Onuki20c95f82016-05-11 16:51:01 -07002236 }
2237
Makoto Onuki2d895c32016-12-02 15:48:40 -08002238 @Override
Sunny Goyal7f7372a2017-01-24 11:53:54 -08002239 public boolean isRequestPinItemSupported(int callingUserId, int requestType) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08002240 final long token = injectClearCallingIdentity();
2241 try {
Sunny Goyal7f7372a2017-01-24 11:53:54 -08002242 return mShortcutRequestPinProcessor
2243 .isRequestPinItemSupported(callingUserId, requestType);
Makoto Onuki2d895c32016-12-02 15:48:40 -08002244 } finally {
2245 injectRestoreCallingIdentity(token);
2246 }
2247 }
2248
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002249 /**
Makoto Onukib08790c2016-06-23 14:05:46 -07002250 * Reset all throttling, for developer options and command line. Only system/shell can call
2251 * it.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002252 */
2253 @Override
2254 public void resetThrottling() {
2255 enforceSystemOrShell();
2256
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002257 resetThrottlingInner(getCallingUserId());
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002258 }
2259
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002260 void resetThrottlingInner(@UserIdInt int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002261 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002262 if (!isUserUnlockedL(userId)) {
2263 Log.w(TAG, "User " + userId + " is locked or not running");
2264 return;
2265 }
2266
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002267 getUserShortcutsLocked(userId).resetThrottling();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002268 }
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002269 scheduleSaveUser(userId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002270 Slog.i(TAG, "ShortcutManager: throttling counter reset for user " + userId);
2271 }
2272
2273 void resetAllThrottlingInner() {
2274 synchronized (mLock) {
2275 mRawLastResetTime = injectCurrentTimeMillis();
2276 }
2277 scheduleSaveBaseState();
2278 Slog.i(TAG, "ShortcutManager: throttling counter reset for all users");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002279 }
2280
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002281 @Override
2282 public void onApplicationActive(String packageName, int userId) {
2283 if (DEBUG) {
2284 Slog.d(TAG, "onApplicationActive: package=" + packageName + " userid=" + userId);
2285 }
2286 enforceResetThrottlingPermission();
Makoto Onuki02f338e2016-07-29 09:40:40 -07002287
2288 synchronized (mLock) {
2289 if (!isUserUnlockedL(userId)) {
2290 // This is called by system UI, so no need to throw. Just ignore.
2291 return;
2292 }
2293
2294 getPackageShortcutsLocked(packageName, userId)
2295 .resetRateLimitingForCommandLineNoSaving();
2296 saveUserLocked(userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002297 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002298 }
2299
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002300 // We override this method in unit tests to do a simpler check.
Makoto Onuki634cecb2017-10-13 17:10:48 -07002301 boolean hasShortcutHostPermission(@NonNull String callingPackage, int userId,
2302 int callingPid, int callingUid) {
Makoto Onuki35559d62017-11-06 16:26:32 -08002303 if (canSeeAnyPinnedShortcut(callingPackage, userId, callingPid, callingUid)) {
Makoto Onuki634cecb2017-10-13 17:10:48 -07002304 return true;
2305 }
Makoto Onuki84d59342018-02-02 09:22:38 -08002306 final long start = getStatStartTime();
Makoto Onuki10305202016-07-14 18:14:08 -07002307 try {
2308 return hasShortcutHostPermissionInner(callingPackage, userId);
2309 } finally {
2310 logDurationStat(Stats.LAUNCHER_PERMISSION_CHECK, start);
2311 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002312 }
2313
Makoto Onuki35559d62017-11-06 16:26:32 -08002314 boolean canSeeAnyPinnedShortcut(@NonNull String callingPackage, int userId,
2315 int callingPid, int callingUid) {
2316 if (injectHasAccessShortcutsPermission(callingPid, callingUid)) {
2317 return true;
2318 }
2319 synchronized (mLock) {
Makoto Onuki708703b2017-12-11 16:38:11 -08002320 return getNonPersistentUserLocked(userId).hasHostPackage(callingPackage);
Makoto Onuki35559d62017-11-06 16:26:32 -08002321 }
2322 }
2323
Makoto Onuki634cecb2017-10-13 17:10:48 -07002324 /**
2325 * Returns true if the caller has the "ACCESS_SHORTCUTS" permission.
2326 */
Makoto Onuki35559d62017-11-06 16:26:32 -08002327 @VisibleForTesting
2328 boolean injectHasAccessShortcutsPermission(int callingPid, int callingUid) {
Makoto Onuki634cecb2017-10-13 17:10:48 -07002329 return mContext.checkPermission(android.Manifest.permission.ACCESS_SHORTCUTS,
2330 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
2331 }
2332
Makoto Onuki7d0fa812018-02-21 11:24:43 -08002333 /**
2334 * Returns true if the caller has the "UNLIMITED_SHORTCUTS_API_CALLS" permission.
2335 */
2336 @VisibleForTesting
2337 boolean injectHasUnlimitedShortcutsApiCallsPermission(int callingPid, int callingUid) {
2338 return mContext.checkPermission(permission.UNLIMITED_SHORTCUTS_API_CALLS,
2339 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
2340 }
2341
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002342 // This method is extracted so we can directly call this method from unit tests,
2343 // even when hasShortcutPermission() is overridden.
2344 @VisibleForTesting
Makoto Onuki2d895c32016-12-02 15:48:40 -08002345 boolean hasShortcutHostPermissionInner(@NonNull String packageName, int userId) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002346 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002347 throwIfUserLockedL(userId);
2348
Makoto Onuki31459242016-03-22 11:12:18 -07002349 final ShortcutUser user = getUserShortcutsLocked(userId);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002350
Makoto Onuki2d895c32016-12-02 15:48:40 -08002351 // Always trust the cached component.
Makoto Onuki10305202016-07-14 18:14:08 -07002352 final ComponentName cached = user.getCachedLauncher();
2353 if (cached != null) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08002354 if (cached.getPackageName().equals(packageName)) {
Makoto Onuki10305202016-07-14 18:14:08 -07002355 return true;
2356 }
2357 }
2358 // If the cached one doesn't match, then go ahead
2359
Makoto Onuki2d895c32016-12-02 15:48:40 -08002360 final ComponentName detected = getDefaultLauncher(userId);
Makoto Onuki2e210c42016-03-30 08:30:36 -07002361
Makoto Onuki10305202016-07-14 18:14:08 -07002362 // Update the cache.
2363 user.setLauncher(detected);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002364 if (detected != null) {
2365 if (DEBUG) {
2366 Slog.v(TAG, "Detected launcher: " + detected);
2367 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08002368 return detected.getPackageName().equals(packageName);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002369 } else {
2370 // Default launcher not found.
2371 return false;
2372 }
2373 }
2374 }
2375
Makoto Onuki2d895c32016-12-02 15:48:40 -08002376 @Nullable
2377 ComponentName getDefaultLauncher(@UserIdInt int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08002378 final long start = getStatStartTime();
Makoto Onuki2d895c32016-12-02 15:48:40 -08002379 final long token = injectClearCallingIdentity();
2380 try {
2381 synchronized (mLock) {
2382 throwIfUserLockedL(userId);
2383
2384 final ShortcutUser user = getUserShortcutsLocked(userId);
2385
2386 final List<ResolveInfo> allHomeCandidates = new ArrayList<>();
2387
2388 // Default launcher from package manager.
Makoto Onuki84d59342018-02-02 09:22:38 -08002389 final long startGetHomeActivitiesAsUser = getStatStartTime();
Makoto Onuki2d895c32016-12-02 15:48:40 -08002390 final ComponentName defaultLauncher = mPackageManagerInternal
2391 .getHomeActivitiesAsUser(allHomeCandidates, userId);
2392 logDurationStat(Stats.GET_DEFAULT_HOME, startGetHomeActivitiesAsUser);
2393
2394 ComponentName detected = null;
2395 if (defaultLauncher != null) {
2396 detected = defaultLauncher;
2397 if (DEBUG) {
2398 Slog.v(TAG, "Default launcher from PM: " + detected);
2399 }
2400 } else {
2401 detected = user.getLastKnownLauncher();
2402
2403 if (detected != null) {
2404 if (injectIsActivityEnabledAndExported(detected, userId)) {
2405 if (DEBUG) {
2406 Slog.v(TAG, "Cached launcher: " + detected);
2407 }
2408 } else {
2409 Slog.w(TAG, "Cached launcher " + detected + " no longer exists");
2410 detected = null;
2411 user.clearLauncher();
2412 }
2413 }
2414 }
2415
2416 if (detected == null) {
2417 // If we reach here, that means it's the first check since the user was created,
2418 // and there's already multiple launchers and there's no default set.
2419 // Find the system one with the highest priority.
2420 // (We need to check the priority too because of FallbackHome in Settings.)
2421 // If there's no system launcher yet, then no one can access shortcuts, until
2422 // the user explicitly
2423 final int size = allHomeCandidates.size();
2424
2425 int lastPriority = Integer.MIN_VALUE;
2426 for (int i = 0; i < size; i++) {
2427 final ResolveInfo ri = allHomeCandidates.get(i);
2428 if (!ri.activityInfo.applicationInfo.isSystemApp()) {
2429 continue;
2430 }
2431 if (DEBUG) {
2432 Slog.d(TAG, String.format("hasShortcutPermissionInner: pkg=%s prio=%d",
2433 ri.activityInfo.getComponentName(), ri.priority));
2434 }
2435 if (ri.priority < lastPriority) {
2436 continue;
2437 }
2438 detected = ri.activityInfo.getComponentName();
2439 lastPriority = ri.priority;
2440 }
2441 }
2442 return detected;
2443 }
2444 } finally {
2445 injectRestoreCallingIdentity(token);
2446 logDurationStat(Stats.GET_DEFAULT_LAUNCHER, start);
2447 }
2448 }
2449
Dianne Hackbornc160fa42017-11-01 16:14:26 -07002450 public void setShortcutHostPackage(@NonNull String type, @Nullable String packageName,
2451 int userId) {
2452 synchronized (mLock) {
Makoto Onuki708703b2017-12-11 16:38:11 -08002453 getNonPersistentUserLocked(userId).setShortcutHostPackage(type, packageName);
Dianne Hackbornc160fa42017-11-01 16:14:26 -07002454 }
2455 }
2456
Makoto Onukicdc78f72016-03-21 15:47:52 -07002457 // === House keeping ===
2458
Makoto Onukib08790c2016-06-23 14:05:46 -07002459 private void cleanUpPackageForAllLoadedUsers(String packageName, @UserIdInt int packageUserId,
2460 boolean appStillExists) {
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002461 synchronized (mLock) {
2462 forEachLoadedUserLocked(user ->
Makoto Onukib08790c2016-06-23 14:05:46 -07002463 cleanUpPackageLocked(packageName, user.getUserId(), packageUserId,
2464 appStillExists));
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002465 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002466 }
2467
Makoto Onuki2e210c42016-03-30 08:30:36 -07002468 /**
2469 * Remove all the information associated with a package. This will really remove all the
2470 * information, including the restore information (i.e. it'll remove packages even if they're
2471 * shadow).
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002472 *
2473 * This is called when an app is uninstalled, or an app gets "clear data"ed.
Makoto Onuki2e210c42016-03-30 08:30:36 -07002474 */
Andreas Gampea36dc622018-02-05 17:19:22 -08002475 @GuardedBy("mLock")
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002476 @VisibleForTesting
Makoto Onukib08790c2016-06-23 14:05:46 -07002477 void cleanUpPackageLocked(String packageName, int owningUserId, int packageUserId,
2478 boolean appStillExists) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002479 final boolean wasUserLoaded = isUserLoadedLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002480
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002481 final ShortcutUser user = getUserShortcutsLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002482 boolean doNotify = false;
2483
2484 // First, remove the package from the package list (if the package is a publisher).
Makoto Onukid99c6f02016-03-28 11:02:54 -07002485 if (packageUserId == owningUserId) {
Makoto Onukic51b2872016-05-04 15:24:50 -07002486 if (user.removePackage(packageName) != null) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002487 doNotify = true;
2488 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07002489 }
Makoto Onukid99c6f02016-03-28 11:02:54 -07002490
Makoto Onukicdc78f72016-03-21 15:47:52 -07002491 // Also remove from the launcher list (if the package is a launcher).
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002492 user.removeLauncher(packageUserId, packageName);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002493
2494 // Then remove pinned shortcuts from all launchers.
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002495 user.forAllLaunchers(l -> l.cleanUpPackage(packageName, packageUserId));
2496
2497 // Now there may be orphan shortcuts because we removed pinned shortcuts at the previous
Makoto Onukicdc78f72016-03-21 15:47:52 -07002498 // step. Remove them too.
Makoto Onukic51b2872016-05-04 15:24:50 -07002499 user.forAllPackages(p -> p.refreshPinnedFlags());
Makoto Onukicdc78f72016-03-21 15:47:52 -07002500
Makoto Onukid99c6f02016-03-28 11:02:54 -07002501 scheduleSaveUser(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002502
2503 if (doNotify) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002504 notifyListeners(packageName, owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002505 }
2506
Makoto Onukib08790c2016-06-23 14:05:46 -07002507 // If the app still exists (i.e. data cleared), we need to re-publish manifest shortcuts.
2508 if (appStillExists && (packageUserId == owningUserId)) {
2509 // This will do the notification and save when needed, so do it after the above
2510 // notifyListeners.
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002511 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07002512 }
2513
Makoto Onukicdc78f72016-03-21 15:47:52 -07002514 if (!wasUserLoaded) {
2515 // Note this will execute the scheduled save.
Makoto Onukid99c6f02016-03-28 11:02:54 -07002516 unloadUserLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002517 }
2518 }
2519
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002520 /**
2521 * Entry point from {@link LauncherApps}.
2522 */
2523 private class LocalService extends ShortcutServiceInternal {
Makoto Onuki2e210c42016-03-30 08:30:36 -07002524
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002525 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002526 public List<ShortcutInfo> getShortcuts(int launcherUserId,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002527 @NonNull String callingPackage, long changedSince,
Makoto Onukiabe84422016-04-07 09:41:19 -07002528 @Nullable String packageName, @Nullable List<String> shortcutIds,
Makoto Onuki99302b52017-03-29 12:42:26 -07002529 @Nullable ComponentName componentName,
Makoto Onuki634cecb2017-10-13 17:10:48 -07002530 int queryFlags, int userId, int callingPid, int callingUid) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002531 final ArrayList<ShortcutInfo> ret = new ArrayList<>();
Makoto Onuki9c850012016-07-26 15:50:50 -07002532
Makoto Onuki20c95f82016-05-11 16:51:01 -07002533 final boolean cloneKeyFieldOnly =
2534 ((queryFlags & ShortcutQuery.FLAG_GET_KEY_FIELDS_ONLY) != 0);
2535 final int cloneFlag = cloneKeyFieldOnly ? ShortcutInfo.CLONE_REMOVE_NON_KEY_INFO
2536 : ShortcutInfo.CLONE_REMOVE_FOR_LAUNCHER;
Makoto Onukiabe84422016-04-07 09:41:19 -07002537 if (packageName == null) {
2538 shortcutIds = null; // LauncherAppsService already threw for it though.
2539 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002540
2541 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002542 throwIfUserLockedL(userId);
2543 throwIfUserLockedL(launcherUserId);
2544
Makoto Onuki2e210c42016-03-30 08:30:36 -07002545 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002546 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002547
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002548 if (packageName != null) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002549 getShortcutsInnerLocked(launcherUserId,
Makoto Onukiabe84422016-04-07 09:41:19 -07002550 callingPackage, packageName, shortcutIds, changedSince,
Makoto Onuki634cecb2017-10-13 17:10:48 -07002551 componentName, queryFlags, userId, ret, cloneFlag,
2552 callingPid, callingUid);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002553 } else {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002554 final List<String> shortcutIdsF = shortcutIds;
2555 getUserShortcutsLocked(userId).forAllPackages(p -> {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002556 getShortcutsInnerLocked(launcherUserId,
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002557 callingPackage, p.getPackageName(), shortcutIdsF, changedSince,
Makoto Onuki634cecb2017-10-13 17:10:48 -07002558 componentName, queryFlags, userId, ret, cloneFlag,
2559 callingPid, callingUid);
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002560 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002561 }
2562 }
Makoto Onukibf563b62017-05-04 10:25:30 -07002563 return setReturnedByServer(ret);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002564 }
2565
Andreas Gampea36dc622018-02-05 17:19:22 -08002566 @GuardedBy("ShortcutService.this.mLock")
Makoto Onukid99c6f02016-03-28 11:02:54 -07002567 private void getShortcutsInnerLocked(int launcherUserId, @NonNull String callingPackage,
Makoto Onukiabe84422016-04-07 09:41:19 -07002568 @Nullable String packageName, @Nullable List<String> shortcutIds, long changedSince,
Makoto Onuki99302b52017-03-29 12:42:26 -07002569 @Nullable ComponentName componentName, int queryFlags,
Makoto Onuki634cecb2017-10-13 17:10:48 -07002570 int userId, ArrayList<ShortcutInfo> ret, int cloneFlag,
2571 int callingPid, int callingUid) {
Makoto Onukiabe84422016-04-07 09:41:19 -07002572 final ArraySet<String> ids = shortcutIds == null ? null
2573 : new ArraySet<>(shortcutIds);
2574
Makoto Onuki35559d62017-11-06 16:26:32 -08002575 final ShortcutUser user = getUserShortcutsLocked(userId);
2576 final ShortcutPackage p = user.getPackageShortcutsIfExists(packageName);
Makoto Onukic51b2872016-05-04 15:24:50 -07002577 if (p == null) {
2578 return; // No need to instantiate ShortcutPackage.
2579 }
Makoto Onuki634cecb2017-10-13 17:10:48 -07002580 final boolean matchDynamic = (queryFlags & ShortcutQuery.FLAG_MATCH_DYNAMIC) != 0;
2581 final boolean matchPinned = (queryFlags & ShortcutQuery.FLAG_MATCH_PINNED) != 0;
2582 final boolean matchManifest = (queryFlags & ShortcutQuery.FLAG_MATCH_MANIFEST) != 0;
2583
Makoto Onuki35559d62017-11-06 16:26:32 -08002584 final boolean canAccessAllShortcuts =
2585 canSeeAnyPinnedShortcut(callingPackage, launcherUserId, callingPid, callingUid);
2586
Makoto Onuki634cecb2017-10-13 17:10:48 -07002587 final boolean getPinnedByAnyLauncher =
Makoto Onuki35559d62017-11-06 16:26:32 -08002588 canAccessAllShortcuts &&
2589 ((queryFlags & ShortcutQuery.FLAG_MATCH_PINNED_BY_ANY_LAUNCHER) != 0);
Makoto Onukic51b2872016-05-04 15:24:50 -07002590
2591 p.findAll(ret,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002592 (ShortcutInfo si) -> {
2593 if (si.getLastChangedTimestamp() < changedSince) {
2594 return false;
2595 }
Makoto Onukiabe84422016-04-07 09:41:19 -07002596 if (ids != null && !ids.contains(si.getId())) {
2597 return false;
2598 }
Makoto Onuki85694522016-05-04 12:53:37 -07002599 if (componentName != null) {
Makoto Onuki9fd90192017-01-06 18:31:03 +00002600 if (si.getActivity() != null
2601 && !si.getActivity().equals(componentName)) {
Makoto Onuki85694522016-05-04 12:53:37 -07002602 return false;
2603 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002604 }
Makoto Onuki634cecb2017-10-13 17:10:48 -07002605 if (matchDynamic && si.isDynamic()) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002606 return true;
2607 }
Makoto Onuki35559d62017-11-06 16:26:32 -08002608 if ((matchPinned || getPinnedByAnyLauncher) && si.isPinned()) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002609 return true;
2610 }
Makoto Onuki634cecb2017-10-13 17:10:48 -07002611 if (matchManifest && si.isDeclaredInManifest()) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002612 return true;
2613 }
2614 return false;
Makoto Onuki634cecb2017-10-13 17:10:48 -07002615 }, cloneFlag, callingPackage, launcherUserId, getPinnedByAnyLauncher);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002616 }
2617
2618 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002619 public boolean isPinnedByCaller(int launcherUserId, @NonNull String callingPackage,
2620 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2621 Preconditions.checkStringNotEmpty(packageName, "packageName");
2622 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
2623
2624 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002625 throwIfUserLockedL(userId);
2626 throwIfUserLockedL(launcherUserId);
2627
Makoto Onuki2e210c42016-03-30 08:30:36 -07002628 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002629 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002630
Makoto Onukid99c6f02016-03-28 11:02:54 -07002631 final ShortcutInfo si = getShortcutInfoLocked(
Makoto Onuki634cecb2017-10-13 17:10:48 -07002632 launcherUserId, callingPackage, packageName, shortcutId, userId,
2633 /*getPinnedByAnyLauncher=*/ false);
Makoto Onukid99c6f02016-03-28 11:02:54 -07002634 return si != null && si.isPinned();
2635 }
2636 }
2637
Andreas Gampea36dc622018-02-05 17:19:22 -08002638 @GuardedBy("ShortcutService.this.mLock")
Makoto Onuki2e210c42016-03-30 08:30:36 -07002639 private ShortcutInfo getShortcutInfoLocked(
Makoto Onukid99c6f02016-03-28 11:02:54 -07002640 int launcherUserId, @NonNull String callingPackage,
Makoto Onuki634cecb2017-10-13 17:10:48 -07002641 @NonNull String packageName, @NonNull String shortcutId, int userId,
2642 boolean getPinnedByAnyLauncher) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002643 Preconditions.checkStringNotEmpty(packageName, "packageName");
2644 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
2645
Makoto Onuki02f338e2016-07-29 09:40:40 -07002646 throwIfUserLockedL(userId);
2647 throwIfUserLockedL(launcherUserId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002648
Makoto Onukic51b2872016-05-04 15:24:50 -07002649 final ShortcutPackage p = getUserShortcutsLocked(userId)
2650 .getPackageShortcutsIfExists(packageName);
2651 if (p == null) {
2652 return null;
2653 }
2654
Makoto Onukid99c6f02016-03-28 11:02:54 -07002655 final ArrayList<ShortcutInfo> list = new ArrayList<>(1);
Makoto Onukic51b2872016-05-04 15:24:50 -07002656 p.findAll(list,
Makoto Onukid99c6f02016-03-28 11:02:54 -07002657 (ShortcutInfo si) -> shortcutId.equals(si.getId()),
Makoto Onuki634cecb2017-10-13 17:10:48 -07002658 /* clone flags=*/ 0, callingPackage, launcherUserId, getPinnedByAnyLauncher);
Makoto Onukid99c6f02016-03-28 11:02:54 -07002659 return list.size() == 0 ? null : list.get(0);
2660 }
2661
2662 @Override
2663 public void pinShortcuts(int launcherUserId,
2664 @NonNull String callingPackage, @NonNull String packageName,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002665 @NonNull List<String> shortcutIds, int userId) {
2666 // Calling permission must be checked by LauncherAppsImpl.
2667 Preconditions.checkStringNotEmpty(packageName, "packageName");
2668 Preconditions.checkNotNull(shortcutIds, "shortcutIds");
2669
2670 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002671 throwIfUserLockedL(userId);
2672 throwIfUserLockedL(launcherUserId);
2673
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002674 final ShortcutLauncher launcher =
Makoto Onuki2e210c42016-03-30 08:30:36 -07002675 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId);
Makoto Onukic51b2872016-05-04 15:24:50 -07002676 launcher.attemptToRestoreIfNeededAndSave();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002677
Makoto Onukia4f89b12017-10-05 10:37:55 -07002678 launcher.pinShortcuts(userId, packageName, shortcutIds, /*forPinRequest=*/ false);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002679 }
Makoto Onuki39686e82016-04-13 18:03:00 -07002680 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07002681
2682 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002683 }
2684
2685 @Override
Makoto Onuki440a1ea2016-07-20 14:21:18 -07002686 public Intent[] createShortcutIntents(int launcherUserId,
Makoto Onukid99c6f02016-03-28 11:02:54 -07002687 @NonNull String callingPackage,
Makoto Onuki634cecb2017-10-13 17:10:48 -07002688 @NonNull String packageName, @NonNull String shortcutId, int userId,
2689 int callingPid, int callingUid) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002690 // Calling permission must be checked by LauncherAppsImpl.
Makoto Onuki43204b82016-03-08 16:16:44 -08002691 Preconditions.checkStringNotEmpty(packageName, "packageName can't be empty");
2692 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId can't be empty");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002693
2694 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002695 throwIfUserLockedL(userId);
2696 throwIfUserLockedL(launcherUserId);
2697
Makoto Onuki2e210c42016-03-30 08:30:36 -07002698 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002699 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002700
Makoto Onuki634cecb2017-10-13 17:10:48 -07002701 final boolean getPinnedByAnyLauncher =
Makoto Onuki35559d62017-11-06 16:26:32 -08002702 canSeeAnyPinnedShortcut(callingPackage, launcherUserId,
2703 callingPid, callingUid);
Makoto Onuki634cecb2017-10-13 17:10:48 -07002704
Makoto Onukid99c6f02016-03-28 11:02:54 -07002705 // Make sure the shortcut is actually visible to the launcher.
2706 final ShortcutInfo si = getShortcutInfoLocked(
Makoto Onuki634cecb2017-10-13 17:10:48 -07002707 launcherUserId, callingPackage, packageName, shortcutId, userId,
2708 getPinnedByAnyLauncher);
Makoto Onukid99c6f02016-03-28 11:02:54 -07002709 // "si == null" should suffice here, but check the flags too just to make sure.
Makoto Onuki35559d62017-11-06 16:26:32 -08002710 if (si == null || !si.isEnabled() || !(si.isAlive() || getPinnedByAnyLauncher)) {
Makoto Onuki83f6d2d2016-07-11 14:30:19 -07002711 Log.e(TAG, "Shortcut " + shortcutId + " does not exist or disabled");
Makoto Onukid99c6f02016-03-28 11:02:54 -07002712 return null;
2713 }
Makoto Onuki440a1ea2016-07-20 14:21:18 -07002714 return si.getIntents();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002715 }
2716 }
2717
2718 @Override
2719 public void addListener(@NonNull ShortcutChangeListener listener) {
2720 synchronized (mLock) {
2721 mListeners.add(Preconditions.checkNotNull(listener));
2722 }
2723 }
Makoto Onuki55046222016-03-08 10:49:47 -08002724
2725 @Override
Makoto Onukiabe84422016-04-07 09:41:19 -07002726 public int getShortcutIconResId(int launcherUserId, @NonNull String callingPackage,
2727 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2728 Preconditions.checkNotNull(callingPackage, "callingPackage");
2729 Preconditions.checkNotNull(packageName, "packageName");
2730 Preconditions.checkNotNull(shortcutId, "shortcutId");
Makoto Onuki55046222016-03-08 10:49:47 -08002731
2732 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002733 throwIfUserLockedL(userId);
2734 throwIfUserLockedL(launcherUserId);
2735
Makoto Onuki2e210c42016-03-30 08:30:36 -07002736 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002737 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002738
Makoto Onukic51b2872016-05-04 15:24:50 -07002739 final ShortcutPackage p = getUserShortcutsLocked(userId)
2740 .getPackageShortcutsIfExists(packageName);
2741 if (p == null) {
2742 return 0;
2743 }
2744
2745 final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId);
Makoto Onuki55046222016-03-08 10:49:47 -08002746 return (shortcutInfo != null && shortcutInfo.hasIconResource())
2747 ? shortcutInfo.getIconResourceId() : 0;
2748 }
2749 }
2750
2751 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002752 public ParcelFileDescriptor getShortcutIconFd(int launcherUserId,
Makoto Onukiabe84422016-04-07 09:41:19 -07002753 @NonNull String callingPackage, @NonNull String packageName,
2754 @NonNull String shortcutId, int userId) {
2755 Preconditions.checkNotNull(callingPackage, "callingPackage");
2756 Preconditions.checkNotNull(packageName, "packageName");
2757 Preconditions.checkNotNull(shortcutId, "shortcutId");
Makoto Onuki55046222016-03-08 10:49:47 -08002758
2759 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002760 throwIfUserLockedL(userId);
2761 throwIfUserLockedL(launcherUserId);
2762
Makoto Onuki2e210c42016-03-30 08:30:36 -07002763 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002764 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002765
Makoto Onukic51b2872016-05-04 15:24:50 -07002766 final ShortcutPackage p = getUserShortcutsLocked(userId)
2767 .getPackageShortcutsIfExists(packageName);
2768 if (p == null) {
2769 return null;
2770 }
2771
2772 final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId);
Makoto Onuki55046222016-03-08 10:49:47 -08002773 if (shortcutInfo == null || !shortcutInfo.hasIconFile()) {
2774 return null;
2775 }
Makoto Onuki475c3652017-05-08 14:29:03 -07002776 final String path = mShortcutBitmapSaver.getBitmapPathMayWaitLocked(shortcutInfo);
2777 if (path == null) {
2778 Slog.w(TAG, "null bitmap detected in getShortcutIconFd()");
2779 return null;
2780 }
Makoto Onuki55046222016-03-08 10:49:47 -08002781 try {
2782 return ParcelFileDescriptor.open(
Makoto Onuki475c3652017-05-08 14:29:03 -07002783 new File(path),
Makoto Onuki55046222016-03-08 10:49:47 -08002784 ParcelFileDescriptor.MODE_READ_ONLY);
2785 } catch (FileNotFoundException e) {
Makoto Onuki475c3652017-05-08 14:29:03 -07002786 Slog.e(TAG, "Icon file not found: " + path);
Makoto Onuki55046222016-03-08 10:49:47 -08002787 return null;
2788 }
2789 }
2790 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002791
2792 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002793 public boolean hasShortcutHostPermission(int launcherUserId,
Makoto Onuki634cecb2017-10-13 17:10:48 -07002794 @NonNull String callingPackage, int callingPid, int callingUid) {
2795 return ShortcutService.this.hasShortcutHostPermission(callingPackage, launcherUserId,
2796 callingPid, callingUid);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002797 }
Sunny Goyal87a563e2017-01-01 19:42:45 -08002798
2799 @Override
Dianne Hackbornc160fa42017-11-01 16:14:26 -07002800 public void setShortcutHostPackage(@NonNull String type, @Nullable String packageName,
2801 int userId) {
2802 ShortcutService.this.setShortcutHostPackage(type, packageName, userId);
2803 }
2804
2805 @Override
Sunny Goyal87a563e2017-01-01 19:42:45 -08002806 public boolean requestPinAppWidget(@NonNull String callingPackage,
Sunny Goyal4ad6b572017-02-28 11:11:51 -08002807 @NonNull AppWidgetProviderInfo appWidget, @Nullable Bundle extras,
2808 @Nullable IntentSender resultIntent, int userId) {
Sunny Goyal87a563e2017-01-01 19:42:45 -08002809 Preconditions.checkNotNull(appWidget);
Sunny Goyal4ad6b572017-02-28 11:11:51 -08002810 return requestPinItem(callingPackage, userId, null, appWidget, extras, resultIntent);
Sunny Goyal87a563e2017-01-01 19:42:45 -08002811 }
Sunny Goyal7f7372a2017-01-24 11:53:54 -08002812
2813 @Override
2814 public boolean isRequestPinItemSupported(int callingUserId, int requestType) {
2815 return ShortcutService.this.isRequestPinItemSupported(callingUserId, requestType);
2816 }
Tony Maked6ef622017-12-07 16:36:16 +00002817
2818 @Override
2819 public boolean isForegroundDefaultLauncher(@NonNull String callingPackage, int callingUid) {
2820 Preconditions.checkNotNull(callingPackage);
2821
2822 final int userId = UserHandle.getUserId(callingUid);
2823 final ComponentName defaultLauncher = getDefaultLauncher(userId);
2824 if (defaultLauncher == null) {
2825 return false;
2826 }
2827 if (!callingPackage.equals(defaultLauncher.getPackageName())) {
2828 return false;
2829 }
2830 synchronized (mLock) {
2831 if (!isUidForegroundLocked(callingUid)) {
2832 return false;
2833 }
2834 }
2835 return true;
2836 }
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002837 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002838
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002839 final BroadcastReceiver mReceiver = new BroadcastReceiver() {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002840 @Override
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002841 public void onReceive(Context context, Intent intent) {
2842 if (!mBootCompleted.get()) {
2843 return; // Boot not completed, ignore the broadcast.
2844 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07002845 try {
2846 if (Intent.ACTION_LOCALE_CHANGED.equals(intent.getAction())) {
2847 handleLocaleChanged();
2848 }
2849 } catch (Exception e) {
2850 wtf("Exception in mReceiver.onReceive", e);
Makoto Onukic51b2872016-05-04 15:24:50 -07002851 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002852 }
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002853 };
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002854
Makoto Onuki157b1622016-06-02 16:13:10 -07002855 void handleLocaleChanged() {
2856 if (DEBUG) {
2857 Slog.d(TAG, "handleLocaleChanged");
2858 }
2859 scheduleSaveBaseState();
2860
Makoto Onuki02f338e2016-07-29 09:40:40 -07002861 synchronized (mLock) {
2862 final long token = injectClearCallingIdentity();
2863 try {
2864 forEachLoadedUserLocked(user -> user.detectLocaleChange());
2865 } finally {
2866 injectRestoreCallingIdentity(token);
2867 }
Makoto Onuki157b1622016-06-02 16:13:10 -07002868 }
2869 }
2870
Makoto Onukif34c3082016-07-13 10:25:25 -07002871 /**
2872 * Package event callbacks.
2873 */
2874 @VisibleForTesting
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002875 final BroadcastReceiver mPackageMonitor = new BroadcastReceiver() {
Makoto Onukif34c3082016-07-13 10:25:25 -07002876 @Override
2877 public void onReceive(Context context, Intent intent) {
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002878 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
2879 if (userId == UserHandle.USER_NULL) {
2880 Slog.w(TAG, "Intent broadcast does not contain user handle: " + intent);
2881 return;
2882 }
2883
2884 final String action = intent.getAction();
2885
2886 // This is normally called on Handler, so clearCallingIdentity() isn't needed,
2887 // but we still check it in unit tests.
Makoto Onukif34c3082016-07-13 10:25:25 -07002888 final long token = injectClearCallingIdentity();
2889 try {
Makoto Onuki10305202016-07-14 18:14:08 -07002890 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002891 if (!isUserUnlockedL(userId)) {
2892 if (DEBUG) {
2893 Slog.d(TAG, "Ignoring package broadcast " + action
2894 + " for locked/stopped user " + userId);
2895 }
2896 return;
2897 }
2898
2899 // Whenever we get one of those package broadcasts, or get
2900 // ACTION_PREFERRED_ACTIVITY_CHANGED, we purge the default launcher cache.
Makoto Onuki10305202016-07-14 18:14:08 -07002901 final ShortcutUser user = getUserShortcutsLocked(userId);
2902 user.clearLauncher();
2903 }
2904 if (Intent.ACTION_PREFERRED_ACTIVITY_CHANGED.equals(action)) {
2905 // Nothing farther to do.
2906 return;
2907 }
2908
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002909 final Uri intentUri = intent.getData();
2910 final String packageName = (intentUri != null) ? intentUri.getSchemeSpecificPart()
2911 : null;
2912 if (packageName == null) {
2913 Slog.w(TAG, "Intent broadcast does not contain package name: " + intent);
2914 return;
2915 }
2916
2917 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
2918
2919 switch (action) {
2920 case Intent.ACTION_PACKAGE_ADDED:
2921 if (replacing) {
2922 handlePackageUpdateFinished(packageName, userId);
2923 } else {
2924 handlePackageAdded(packageName, userId);
2925 }
2926 break;
2927 case Intent.ACTION_PACKAGE_REMOVED:
2928 if (!replacing) {
2929 handlePackageRemoved(packageName, userId);
2930 }
2931 break;
2932 case Intent.ACTION_PACKAGE_CHANGED:
2933 handlePackageChanged(packageName, userId);
2934
2935 break;
2936 case Intent.ACTION_PACKAGE_DATA_CLEARED:
2937 handlePackageDataCleared(packageName, userId);
2938 break;
2939 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07002940 } catch (Exception e) {
2941 wtf("Exception in mPackageMonitor.onReceive", e);
Makoto Onukif34c3082016-07-13 10:25:25 -07002942 } finally {
2943 injectRestoreCallingIdentity(token);
Makoto Onukia2241832016-07-06 13:28:37 -07002944 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07002945 }
Makoto Onukif34c3082016-07-13 10:25:25 -07002946 };
Makoto Onukicdc78f72016-03-21 15:47:52 -07002947
Makoto Onuki0acbb142016-03-22 17:02:57 -07002948 /**
Makoto Onuki39686e82016-04-13 18:03:00 -07002949 * Called when a user is unlocked.
2950 * - Check all known packages still exist, and otherwise perform cleanup.
2951 * - If a package still exists, check the version code. If it's been updated, may need to
Makoto Onukib08790c2016-06-23 14:05:46 -07002952 * update timestamps of its shortcuts.
Makoto Onuki0acbb142016-03-22 17:02:57 -07002953 */
Makoto Onukid99c6f02016-03-28 11:02:54 -07002954 @VisibleForTesting
Makoto Onuki39686e82016-04-13 18:03:00 -07002955 void checkPackageChanges(@UserIdInt int ownerUserId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07002956 if (DEBUG) {
Makoto Onuki39686e82016-04-13 18:03:00 -07002957 Slog.d(TAG, "checkPackageChanges() ownerUserId=" + ownerUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002958 }
Makoto Onukib08790c2016-06-23 14:05:46 -07002959 if (injectIsSafeModeEnabled()) {
2960 Slog.i(TAG, "Safe mode, skipping checkPackageChanges()");
2961 return;
2962 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07002963
Makoto Onuki84d59342018-02-02 09:22:38 -08002964 final long start = getStatStartTime();
Makoto Onuki22fcc682016-05-17 14:52:19 -07002965 try {
2966 final ArrayList<PackageWithUser> gonePackages = new ArrayList<>();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002967
Makoto Onuki22fcc682016-05-17 14:52:19 -07002968 synchronized (mLock) {
2969 final ShortcutUser user = getUserShortcutsLocked(ownerUserId);
2970
2971 // Find packages that have been uninstalled.
2972 user.forAllPackageItems(spi -> {
2973 if (spi.getPackageInfo().isShadow()) {
2974 return; // Don't delete shadow information.
2975 }
2976 if (!isPackageInstalled(spi.getPackageName(), spi.getPackageUserId())) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002977 if (DEBUG) {
2978 Slog.d(TAG, "Uninstalled: " + spi.getPackageName()
2979 + " user " + spi.getPackageUserId());
2980 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002981 gonePackages.add(PackageWithUser.of(spi));
2982 }
2983 });
2984 if (gonePackages.size() > 0) {
2985 for (int i = gonePackages.size() - 1; i >= 0; i--) {
2986 final PackageWithUser pu = gonePackages.get(i);
Makoto Onukib08790c2016-06-23 14:05:46 -07002987 cleanUpPackageLocked(pu.packageName, ownerUserId, pu.userId,
2988 /* appStillExists = */ false);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002989 }
Makoto Onukid99c6f02016-03-28 11:02:54 -07002990 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002991
Makoto Onuki248a0ef2016-11-03 15:59:01 -07002992 rescanUpdatedPackagesLocked(ownerUserId, user.getLastAppScanTime());
Makoto Onuki0acbb142016-03-22 17:02:57 -07002993 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002994 } finally {
2995 logDurationStat(Stats.CHECK_PACKAGE_CHANGES, start);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002996 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002997 verifyStates();
Makoto Onukicdc78f72016-03-21 15:47:52 -07002998 }
2999
Andreas Gampea36dc622018-02-05 17:19:22 -08003000 @GuardedBy("mLock")
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003001 private void rescanUpdatedPackagesLocked(@UserIdInt int userId, long lastScanTime) {
Makoto Onuki377b7972016-08-09 14:43:55 -07003002 final ShortcutUser user = getUserShortcutsLocked(userId);
3003
Makoto Onuki33663282016-08-22 16:19:04 -07003004 // Note after each OTA, we'll need to rescan all system apps, as their lastUpdateTime
3005 // is not reliable.
Makoto Onuki377b7972016-08-09 14:43:55 -07003006 final long now = injectCurrentTimeMillis();
Makoto Onuki33663282016-08-22 16:19:04 -07003007 final boolean afterOta =
3008 !injectBuildFingerprint().equals(user.getLastAppScanOsFingerprint());
Makoto Onuki377b7972016-08-09 14:43:55 -07003009
3010 // Then for each installed app, publish manifest shortcuts when needed.
Makoto Onuki33663282016-08-22 16:19:04 -07003011 forUpdatedPackages(userId, lastScanTime, afterOta, ai -> {
Makoto Onuki377b7972016-08-09 14:43:55 -07003012 user.attemptToRestoreIfNeededAndSave(this, ai.packageName, userId);
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003013
3014 user.rescanPackageIfNeeded(ai.packageName, /* forceRescan= */ true);
Makoto Onuki377b7972016-08-09 14:43:55 -07003015 });
3016
3017 // Write the time just before the scan, because there may be apps that have just
3018 // been updated, and we want to catch them in the next time.
3019 user.setLastAppScanTime(now);
Makoto Onuki33663282016-08-22 16:19:04 -07003020 user.setLastAppScanOsFingerprint(injectBuildFingerprint());
Makoto Onuki377b7972016-08-09 14:43:55 -07003021 scheduleSaveUser(userId);
3022 }
3023
Makoto Onuki0acbb142016-03-22 17:02:57 -07003024 private void handlePackageAdded(String packageName, @UserIdInt int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07003025 if (DEBUG) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07003026 Slog.d(TAG, String.format("handlePackageAdded: %s user=%d", packageName, userId));
3027 }
3028 synchronized (mLock) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07003029 final ShortcutUser user = getUserShortcutsLocked(userId);
3030 user.attemptToRestoreIfNeededAndSave(this, packageName, userId);
Makoto Onuki64183d52016-08-08 14:11:34 -07003031 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onuki0acbb142016-03-22 17:02:57 -07003032 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07003033 verifyStates();
Makoto Onuki0acbb142016-03-22 17:02:57 -07003034 }
3035
3036 private void handlePackageUpdateFinished(String packageName, @UserIdInt int userId) {
Makoto Onuki905e8852016-03-28 10:40:58 -07003037 if (DEBUG) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003038 Slog.d(TAG, String.format("handlePackageUpdateFinished: %s user=%d",
3039 packageName, userId));
Makoto Onuki0acbb142016-03-22 17:02:57 -07003040 }
3041 synchronized (mLock) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07003042 final ShortcutUser user = getUserShortcutsLocked(userId);
3043 user.attemptToRestoreIfNeededAndSave(this, packageName, userId);
Makoto Onuki39686e82016-04-13 18:03:00 -07003044
Makoto Onuki22fcc682016-05-17 14:52:19 -07003045 if (isPackageInstalled(packageName, userId)) {
Makoto Onuki64183d52016-08-08 14:11:34 -07003046 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onuki39686e82016-04-13 18:03:00 -07003047 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07003048 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07003049 verifyStates();
Makoto Onuki0acbb142016-03-22 17:02:57 -07003050 }
3051
Makoto Onuki2e210c42016-03-30 08:30:36 -07003052 private void handlePackageRemoved(String packageName, @UserIdInt int packageUserId) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07003053 if (DEBUG) {
Makoto Onuki2e210c42016-03-30 08:30:36 -07003054 Slog.d(TAG, String.format("handlePackageRemoved: %s user=%d", packageName,
3055 packageUserId));
Makoto Onukicdc78f72016-03-21 15:47:52 -07003056 }
Makoto Onukib08790c2016-06-23 14:05:46 -07003057 cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ false);
Makoto Onuki9e1f5592016-06-08 12:30:23 -07003058
3059 verifyStates();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003060 }
3061
Makoto Onuki9ac59d02016-04-26 11:23:14 -07003062 private void handlePackageDataCleared(String packageName, int packageUserId) {
3063 if (DEBUG) {
3064 Slog.d(TAG, String.format("handlePackageDataCleared: %s user=%d", packageName,
3065 packageUserId));
Makoto Onukicdc78f72016-03-21 15:47:52 -07003066 }
Makoto Onukib08790c2016-06-23 14:05:46 -07003067 cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ true);
3068
3069 verifyStates();
3070 }
3071
3072 private void handlePackageChanged(String packageName, int packageUserId) {
Makoto Onuki82fb2eb2017-03-31 16:58:26 -07003073 if (!isPackageInstalled(packageName, packageUserId)) {
3074 // Probably disabled, which is the same thing as uninstalled.
3075 handlePackageRemoved(packageName, packageUserId);
3076 return;
3077 }
Makoto Onukib08790c2016-06-23 14:05:46 -07003078 if (DEBUG) {
3079 Slog.d(TAG, String.format("handlePackageChanged: %s user=%d", packageName,
3080 packageUserId));
3081 }
3082
3083 // Activities may be disabled or enabled. Just rescan the package.
3084 synchronized (mLock) {
3085 final ShortcutUser user = getUserShortcutsLocked(packageUserId);
3086
Makoto Onuki4e6cef42016-07-13 16:14:01 -07003087 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07003088 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07003089
3090 verifyStates();
Makoto Onukicdc78f72016-03-21 15:47:52 -07003091 }
3092
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003093 // === PackageManager interaction ===
Makoto Onuki0acbb142016-03-22 17:02:57 -07003094
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003095 /**
3096 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
3097 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07003098 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003099 final PackageInfo getPackageInfoWithSignatures(String packageName, @UserIdInt int userId) {
3100 return getPackageInfo(packageName, userId, true);
Makoto Onuki0acbb142016-03-22 17:02:57 -07003101 }
3102
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003103 /**
3104 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
3105 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07003106 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003107 final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId) {
3108 return getPackageInfo(packageName, userId, false);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003109 }
3110
Makoto Onuki905e8852016-03-28 10:40:58 -07003111 int injectGetPackageUid(@NonNull String packageName, @UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003112 final long token = injectClearCallingIdentity();
Makoto Onuki905e8852016-03-28 10:40:58 -07003113 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003114 return mIPackageManager.getPackageUid(packageName, PACKAGE_MATCH_FLAGS, userId);
Makoto Onuki905e8852016-03-28 10:40:58 -07003115 } catch (RemoteException e) {
3116 // Shouldn't happen.
3117 Slog.wtf(TAG, "RemoteException", e);
3118 return -1;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003119 } finally {
3120 injectRestoreCallingIdentity(token);
Makoto Onuki905e8852016-03-28 10:40:58 -07003121 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07003122 }
3123
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003124 /**
3125 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
3126 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07003127 @Nullable
Makoto Onuki0acbb142016-03-22 17:02:57 -07003128 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003129 final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId,
3130 boolean getSignatures) {
3131 return isInstalledOrNull(injectPackageInfoWithUninstalled(
3132 packageName, userId, getSignatures));
3133 }
3134
3135 /**
3136 * Do not use directly; this returns uninstalled packages too.
3137 */
3138 @Nullable
3139 @VisibleForTesting
3140 PackageInfo injectPackageInfoWithUninstalled(String packageName, @UserIdInt int userId,
Makoto Onuki0acbb142016-03-22 17:02:57 -07003141 boolean getSignatures) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003142 final long start = getStatStartTime();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003143 final long token = injectClearCallingIdentity();
Makoto Onuki0acbb142016-03-22 17:02:57 -07003144 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003145 return mIPackageManager.getPackageInfo(
3146 packageName, PACKAGE_MATCH_FLAGS
Michal Karpinski528c3e52018-02-07 17:47:10 +00003147 | (getSignatures ? PackageManager.GET_SIGNING_CERTIFICATES : 0),
3148 userId);
Makoto Onuki0acbb142016-03-22 17:02:57 -07003149 } catch (RemoteException e) {
3150 // Shouldn't happen.
3151 Slog.wtf(TAG, "RemoteException", e);
3152 return null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003153 } finally {
3154 injectRestoreCallingIdentity(token);
Makoto Onuki2e210c42016-03-30 08:30:36 -07003155
3156 logDurationStat(
3157 (getSignatures ? Stats.GET_PACKAGE_INFO_WITH_SIG : Stats.GET_PACKAGE_INFO),
3158 start);
Makoto Onuki0acbb142016-03-22 17:02:57 -07003159 }
3160 }
3161
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003162 /**
3163 * Returns {@link ApplicationInfo} unless it's uninstalled or disabled.
3164 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07003165 @Nullable
Makoto Onuki905e8852016-03-28 10:40:58 -07003166 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003167 final ApplicationInfo getApplicationInfo(String packageName, @UserIdInt int userId) {
3168 return isInstalledOrNull(injectApplicationInfoWithUninstalled(packageName, userId));
3169 }
3170
3171 /**
3172 * Do not use directly; this returns uninstalled packages too.
3173 */
3174 @Nullable
3175 @VisibleForTesting
3176 ApplicationInfo injectApplicationInfoWithUninstalled(
3177 String packageName, @UserIdInt int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003178 final long start = getStatStartTime();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003179 final long token = injectClearCallingIdentity();
Makoto Onuki905e8852016-03-28 10:40:58 -07003180 try {
3181 return mIPackageManager.getApplicationInfo(packageName, PACKAGE_MATCH_FLAGS, userId);
3182 } catch (RemoteException e) {
3183 // Shouldn't happen.
3184 Slog.wtf(TAG, "RemoteException", e);
3185 return null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003186 } finally {
3187 injectRestoreCallingIdentity(token);
Makoto Onuki2e210c42016-03-30 08:30:36 -07003188
3189 logDurationStat(Stats.GET_APPLICATION_INFO, start);
Makoto Onuki905e8852016-03-28 10:40:58 -07003190 }
3191 }
3192
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003193 /**
3194 * Returns {@link ActivityInfo} with its metadata unless it's uninstalled or disabled.
3195 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07003196 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003197 final ActivityInfo getActivityInfoWithMetadata(ComponentName activity, @UserIdInt int userId) {
3198 return isInstalledOrNull(injectGetActivityInfoWithMetadataWithUninstalled(
3199 activity, userId));
3200 }
3201
3202 /**
3203 * Do not use directly; this returns uninstalled packages too.
3204 */
3205 @Nullable
3206 @VisibleForTesting
3207 ActivityInfo injectGetActivityInfoWithMetadataWithUninstalled(
3208 ComponentName activity, @UserIdInt int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003209 final long start = getStatStartTime();
Makoto Onuki22fcc682016-05-17 14:52:19 -07003210 final long token = injectClearCallingIdentity();
3211 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07003212 return mIPackageManager.getActivityInfo(activity,
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003213 (PACKAGE_MATCH_FLAGS | PackageManager.GET_META_DATA), userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003214 } catch (RemoteException e) {
3215 // Shouldn't happen.
3216 Slog.wtf(TAG, "RemoteException", e);
3217 return null;
3218 } finally {
3219 injectRestoreCallingIdentity(token);
3220
Makoto Onukib08790c2016-06-23 14:05:46 -07003221 logDurationStat(Stats.GET_ACTIVITY_WITH_METADATA, start);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003222 }
3223 }
3224
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003225 /**
3226 * Return all installed and enabled packages.
3227 */
3228 @NonNull
Makoto Onuki22fcc682016-05-17 14:52:19 -07003229 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003230 final List<PackageInfo> getInstalledPackages(@UserIdInt int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003231 final long start = getStatStartTime();
Makoto Onuki22fcc682016-05-17 14:52:19 -07003232 final long token = injectClearCallingIdentity();
3233 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003234 final List<PackageInfo> all = injectGetPackagesWithUninstalled(userId);
3235
3236 all.removeIf(PACKAGE_NOT_INSTALLED);
3237
3238 return all;
Makoto Onuki22fcc682016-05-17 14:52:19 -07003239 } catch (RemoteException e) {
3240 // Shouldn't happen.
3241 Slog.wtf(TAG, "RemoteException", e);
3242 return null;
3243 } finally {
3244 injectRestoreCallingIdentity(token);
3245
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003246 logDurationStat(Stats.GET_INSTALLED_PACKAGES, start);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003247 }
3248 }
3249
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003250 /**
3251 * Do not use directly; this returns uninstalled packages too.
3252 */
3253 @NonNull
3254 @VisibleForTesting
3255 List<PackageInfo> injectGetPackagesWithUninstalled(@UserIdInt int userId)
3256 throws RemoteException {
3257 final ParceledListSlice<PackageInfo> parceledList =
3258 mIPackageManager.getInstalledPackages(PACKAGE_MATCH_FLAGS, userId);
3259 if (parceledList == null) {
3260 return Collections.emptyList();
3261 }
3262 return parceledList.getList();
3263 }
3264
Makoto Onuki33663282016-08-22 16:19:04 -07003265 private void forUpdatedPackages(@UserIdInt int userId, long lastScanTime, boolean afterOta,
Makoto Onuki22fcc682016-05-17 14:52:19 -07003266 Consumer<ApplicationInfo> callback) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003267 if (DEBUG) {
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003268 Slog.d(TAG, "forUpdatedPackages for user " + userId + ", lastScanTime=" + lastScanTime
3269 + " afterOta=" + afterOta);
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003270 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003271 final List<PackageInfo> list = getInstalledPackages(userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003272 for (int i = list.size() - 1; i >= 0; i--) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003273 final PackageInfo pi = list.get(i);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003274
Makoto Onuki64183d52016-08-08 14:11:34 -07003275 // If the package has been updated since the last scan time, then scan it.
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003276 // Also if it's right after an OTA, always re-scan all apps anyway, since the
3277 // shortcut parser might have changed.
3278 if (afterOta || (pi.lastUpdateTime >= lastScanTime)) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003279 if (DEBUG) {
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003280 Slog.d(TAG, "Found updated package " + pi.packageName
3281 + " updateTime=" + pi.lastUpdateTime);
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003282 }
3283 callback.accept(pi.applicationInfo);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003284 }
3285 }
3286 }
3287
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003288 private boolean isApplicationFlagSet(@NonNull String packageName, int userId, int flags) {
3289 final ApplicationInfo ai = injectApplicationInfoWithUninstalled(packageName, userId);
Makoto Onuki905e8852016-03-28 10:40:58 -07003290 return (ai != null) && ((ai.flags & flags) == flags);
3291 }
3292
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003293 private static boolean isInstalled(@Nullable ApplicationInfo ai) {
Makoto Onuki82fb2eb2017-03-31 16:58:26 -07003294 return (ai != null) && ai.enabled && (ai.flags & ApplicationInfo.FLAG_INSTALLED) != 0;
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003295 }
3296
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08003297 private static boolean isEphemeralApp(@Nullable ApplicationInfo ai) {
Svetoslav Ganov096d3042017-01-30 16:34:13 -08003298 return (ai != null) && ai.isInstantApp();
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08003299 }
3300
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003301 private static boolean isInstalled(@Nullable PackageInfo pi) {
3302 return (pi != null) && isInstalled(pi.applicationInfo);
3303 }
3304
3305 private static boolean isInstalled(@Nullable ActivityInfo ai) {
3306 return (ai != null) && isInstalled(ai.applicationInfo);
3307 }
3308
3309 private static ApplicationInfo isInstalledOrNull(ApplicationInfo ai) {
3310 return isInstalled(ai) ? ai : null;
3311 }
3312
3313 private static PackageInfo isInstalledOrNull(PackageInfo pi) {
3314 return isInstalled(pi) ? pi : null;
3315 }
3316
3317 private static ActivityInfo isInstalledOrNull(ActivityInfo ai) {
3318 return isInstalled(ai) ? ai : null;
3319 }
3320
Makoto Onuki2e210c42016-03-30 08:30:36 -07003321 boolean isPackageInstalled(String packageName, int userId) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003322 return getApplicationInfo(packageName, userId) != null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003323 }
3324
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08003325 boolean isEphemeralApp(String packageName, int userId) {
3326 return isEphemeralApp(getApplicationInfo(packageName, userId));
3327 }
3328
Makoto Onuki22fcc682016-05-17 14:52:19 -07003329 @Nullable
3330 XmlResourceParser injectXmlMetaData(ActivityInfo activityInfo, String key) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07003331 return activityInfo.loadXmlMetaData(mContext.getPackageManager(), key);
Makoto Onuki39686e82016-04-13 18:03:00 -07003332 }
3333
Makoto Onuki157b1622016-06-02 16:13:10 -07003334 @Nullable
3335 Resources injectGetResourcesForApplicationAsUser(String packageName, int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003336 final long start = getStatStartTime();
Makoto Onuki157b1622016-06-02 16:13:10 -07003337 final long token = injectClearCallingIdentity();
3338 try {
3339 return mContext.getPackageManager().getResourcesForApplicationAsUser(
3340 packageName, userId);
3341 } catch (NameNotFoundException e) {
3342 Slog.e(TAG, "Resources for package " + packageName + " not found");
3343 return null;
3344 } finally {
3345 injectRestoreCallingIdentity(token);
3346
3347 logDurationStat(Stats.GET_APPLICATION_RESOURCES, start);
3348 }
3349 }
3350
Makoto Onukib08790c2016-06-23 14:05:46 -07003351 private Intent getMainActivityIntent() {
3352 final Intent intent = new Intent(Intent.ACTION_MAIN);
3353 intent.addCategory(LAUNCHER_INTENT_CATEGORY);
3354 return intent;
3355 }
3356
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003357 /**
3358 * Same as queryIntentActivitiesAsUser, except it makes sure the package is installed,
3359 * and only returns exported activities.
3360 */
3361 @NonNull
3362 @VisibleForTesting
3363 List<ResolveInfo> queryActivities(@NonNull Intent baseIntent,
3364 @NonNull String packageName, @Nullable ComponentName activity, int userId) {
3365
3366 baseIntent.setPackage(Preconditions.checkNotNull(packageName));
3367 if (activity != null) {
3368 baseIntent.setComponent(activity);
3369 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08003370 return queryActivities(baseIntent, userId, /* exportedOnly =*/ true);
3371 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003372
Makoto Onuki2d895c32016-12-02 15:48:40 -08003373 @NonNull
3374 List<ResolveInfo> queryActivities(@NonNull Intent intent, int userId,
3375 boolean exportedOnly) {
3376 final List<ResolveInfo> resolved;
3377 final long token = injectClearCallingIdentity();
3378 try {
3379 resolved =
3380 mContext.getPackageManager().queryIntentActivitiesAsUser(
3381 intent, PACKAGE_MATCH_FLAGS, userId);
3382 } finally {
3383 injectRestoreCallingIdentity(token);
3384 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003385 if (resolved == null || resolved.size() == 0) {
3386 return EMPTY_RESOLVE_INFO;
3387 }
3388 // Make sure the package is installed.
3389 if (!isInstalled(resolved.get(0).activityInfo)) {
3390 return EMPTY_RESOLVE_INFO;
3391 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08003392 if (exportedOnly) {
3393 resolved.removeIf(ACTIVITY_NOT_EXPORTED);
3394 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003395 return resolved;
3396 }
3397
3398 /**
3399 * Return the main activity that is enabled and exported. If multiple activities are found,
3400 * return the first one.
3401 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003402 @Nullable
3403 ComponentName injectGetDefaultMainActivity(@NonNull String packageName, int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003404 final long start = getStatStartTime();
Makoto Onukib08790c2016-06-23 14:05:46 -07003405 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07003406 final List<ResolveInfo> resolved =
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003407 queryActivities(getMainActivityIntent(), packageName, null, userId);
3408 return resolved.size() == 0 ? null : resolved.get(0).activityInfo.getComponentName();
Makoto Onukib08790c2016-06-23 14:05:46 -07003409 } finally {
Makoto Onukib08790c2016-06-23 14:05:46 -07003410 logDurationStat(Stats.GET_LAUNCHER_ACTIVITY, start);
3411 }
3412 }
3413
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003414 /**
3415 * Return whether an activity is enabled, exported and main.
3416 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003417 boolean injectIsMainActivity(@NonNull ComponentName activity, int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003418 final long start = getStatStartTime();
Makoto Onukib08790c2016-06-23 14:05:46 -07003419 try {
Makoto Onuki34145532017-03-14 17:58:36 -07003420 if (activity == null) {
3421 wtf("null activity detected");
3422 return false;
3423 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08003424 if (DUMMY_MAIN_ACTIVITY.equals(activity.getClassName())) {
3425 return true;
3426 }
3427 final List<ResolveInfo> resolved = queryActivities(
3428 getMainActivityIntent(), activity.getPackageName(), activity, userId);
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003429 return resolved.size() > 0;
Makoto Onukib08790c2016-06-23 14:05:46 -07003430 } finally {
Makoto Onukib08790c2016-06-23 14:05:46 -07003431 logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start);
3432 }
3433 }
3434
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003435 /**
Makoto Onuki2d895c32016-12-02 15:48:40 -08003436 * Create a dummy "main activity" component name which is used to create a dynamic shortcut
3437 * with no main activity temporarily.
3438 */
3439 @NonNull
3440 ComponentName getDummyMainActivity(@NonNull String packageName) {
3441 return new ComponentName(packageName, DUMMY_MAIN_ACTIVITY);
3442 }
3443
Makoto Onuki255461f2017-01-10 11:47:25 -08003444 boolean isDummyMainActivity(@Nullable ComponentName name) {
3445 return name != null && DUMMY_MAIN_ACTIVITY.equals(name.getClassName());
3446 }
3447
Makoto Onuki2d895c32016-12-02 15:48:40 -08003448 /**
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003449 * Return all the enabled, exported and main activities from a package.
3450 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003451 @NonNull
3452 List<ResolveInfo> injectGetMainActivities(@NonNull String packageName, int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003453 final long start = getStatStartTime();
Makoto Onukib08790c2016-06-23 14:05:46 -07003454 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003455 return queryActivities(getMainActivityIntent(), packageName, null, userId);
Makoto Onukib08790c2016-06-23 14:05:46 -07003456 } finally {
Makoto Onukib08790c2016-06-23 14:05:46 -07003457 logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start);
3458 }
3459 }
3460
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003461 /**
3462 * Return whether an activity is enabled and exported.
3463 */
3464 @VisibleForTesting
3465 boolean injectIsActivityEnabledAndExported(
3466 @NonNull ComponentName activity, @UserIdInt int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003467 final long start = getStatStartTime();
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003468 try {
3469 return queryActivities(new Intent(), activity.getPackageName(), activity, userId)
3470 .size() > 0;
3471 } finally {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003472 logDurationStat(Stats.IS_ACTIVITY_ENABLED, start);
3473 }
3474 }
3475
Makoto Onuki2d895c32016-12-02 15:48:40 -08003476 /**
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003477 * Get the {@link LauncherApps#ACTION_CONFIRM_PIN_SHORTCUT} or
3478 * {@link LauncherApps#ACTION_CONFIRM_PIN_APPWIDGET} activity in a given package depending on
3479 * the requestType.
Makoto Onuki2d895c32016-12-02 15:48:40 -08003480 */
3481 @Nullable
3482 ComponentName injectGetPinConfirmationActivity(@NonNull String launcherPackageName,
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003483 int launcherUserId, int requestType) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08003484 Preconditions.checkNotNull(launcherPackageName);
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003485 String action = requestType == LauncherApps.PinItemRequest.REQUEST_TYPE_SHORTCUT ?
3486 LauncherApps.ACTION_CONFIRM_PIN_SHORTCUT :
3487 LauncherApps.ACTION_CONFIRM_PIN_APPWIDGET;
Makoto Onuki2d895c32016-12-02 15:48:40 -08003488
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003489 final Intent confirmIntent = new Intent(action).setPackage(launcherPackageName);
Makoto Onuki2d895c32016-12-02 15:48:40 -08003490 final List<ResolveInfo> candidates = queryActivities(
3491 confirmIntent, launcherUserId, /* exportedOnly =*/ false);
3492 for (ResolveInfo ri : candidates) {
3493 return ri.activityInfo.getComponentName();
3494 }
3495 return null;
3496 }
3497
Makoto Onukib08790c2016-06-23 14:05:46 -07003498 boolean injectIsSafeModeEnabled() {
3499 final long token = injectClearCallingIdentity();
3500 try {
3501 return IWindowManager.Stub
3502 .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE))
3503 .isSafeModeEnabled();
3504 } catch (RemoteException e) {
3505 return false; // Shouldn't happen though.
3506 } finally {
3507 injectRestoreCallingIdentity(token);
3508 }
3509 }
3510
Makoto Onuki2d895c32016-12-02 15:48:40 -08003511 /**
3512 * If {@code userId} is of a managed profile, return the parent user ID. Otherwise return
3513 * itself.
3514 */
3515 int getParentOrSelfUserId(int userId) {
Sunny Goyal145c8f82018-02-15 14:27:09 -08003516 return mUserManagerInternal.getProfileParentId(userId);
Makoto Onuki2d895c32016-12-02 15:48:40 -08003517 }
3518
Sunny Goyal87a563e2017-01-01 19:42:45 -08003519 void injectSendIntentSender(IntentSender intentSender, Intent extras) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08003520 if (intentSender == null) {
3521 return;
3522 }
3523 try {
Sunny Goyal87a563e2017-01-01 19:42:45 -08003524 intentSender.sendIntent(mContext, /* code= */ 0, extras,
Makoto Onuki2d895c32016-12-02 15:48:40 -08003525 /* onFinished=*/ null, /* handler= */ null);
3526 } catch (SendIntentException e) {
3527 Slog.w(TAG, "sendIntent failed().", e);
3528 }
3529 }
3530
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003531 // === Backup & restore ===
3532
Makoto Onuki0acbb142016-03-22 17:02:57 -07003533 boolean shouldBackupApp(String packageName, int userId) {
Makoto Onuki905e8852016-03-28 10:40:58 -07003534 return isApplicationFlagSet(packageName, userId, ApplicationInfo.FLAG_ALLOW_BACKUP);
Makoto Onuki0acbb142016-03-22 17:02:57 -07003535 }
3536
Makoto Onukia4f89b12017-10-05 10:37:55 -07003537 static boolean shouldBackupApp(PackageInfo pi) {
Makoto Onuki2e210c42016-03-30 08:30:36 -07003538 return (pi.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0;
3539 }
3540
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003541 @Override
Makoto Onuki2e210c42016-03-30 08:30:36 -07003542 public byte[] getBackupPayload(@UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003543 enforceSystem();
3544 if (DEBUG) {
3545 Slog.d(TAG, "Backing up user " + userId);
3546 }
3547 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003548 if (!isUserUnlockedL(userId)) {
3549 wtf("Can't backup: user " + userId + " is locked or not running");
3550 return null;
3551 }
3552
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003553 final ShortcutUser user = getUserShortcutsLocked(userId);
3554 if (user == null) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003555 wtf("Can't backup: user not found: id=" + userId);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003556 return null;
3557 }
3558
Makoto Onukic8c33292016-09-12 16:36:59 -07003559 // Update the signatures for all packages.
3560 user.forAllPackageItems(spi -> spi.refreshPackageSignatureAndSave());
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003561
Makoto Onukie3fffa92018-02-28 16:25:40 -08003562 // Rescan all apps; this will also update the version codes and "allow-backup".
3563 user.forAllPackages(pkg -> pkg.rescanPackageIfNeeded(
3564 /*isNewApp=*/ false, /*forceRescan=*/ true));
3565
Makoto Onukic8c33292016-09-12 16:36:59 -07003566 // Set the version code for the launchers.
Makoto Onukia4f89b12017-10-05 10:37:55 -07003567 user.forAllLaunchers(launcher -> launcher.ensurePackageInfo());
Makoto Onukic8c33292016-09-12 16:36:59 -07003568
3569 // Save to the filesystem.
3570 scheduleSaveUser(userId);
3571 saveDirtyInfo();
3572
Makoto Onuki475c3652017-05-08 14:29:03 -07003573 // Note, in case of backup, we don't have to wait on bitmap saving, because we don't
3574 // back up bitmaps anyway.
3575
Makoto Onukic8c33292016-09-12 16:36:59 -07003576 // Then create the backup payload.
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003577 final ByteArrayOutputStream os = new ByteArrayOutputStream(32 * 1024);
3578 try {
3579 saveUserInternalLocked(userId, os, /* forBackup */ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07003580 } catch (XmlPullParserException | IOException e) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003581 // Shouldn't happen.
3582 Slog.w(TAG, "Backup failed.", e);
3583 return null;
3584 }
Makoto Onukie3fffa92018-02-28 16:25:40 -08003585 byte[] payload = os.toByteArray();
3586 mShortcutDumpFiles.save("backup-1-payload.txt", payload);
3587 return payload;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003588 }
3589 }
3590
3591 @Override
Makoto Onuki2e210c42016-03-30 08:30:36 -07003592 public void applyRestore(byte[] payload, @UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003593 enforceSystem();
3594 if (DEBUG) {
3595 Slog.d(TAG, "Restoring user " + userId);
3596 }
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003597 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003598 if (!isUserUnlockedL(userId)) {
3599 wtf("Can't restore: user " + userId + " is locked or not running");
3600 return;
3601 }
Makoto Onuki50a320e2017-05-31 14:38:42 -07003602
3603 // Note we print the file timestamps in dumpsys too, but also printing the timestamp
3604 // in the files anyway.
3605 mShortcutDumpFiles.save("restore-0-start.txt", pw -> {
3606 pw.print("Start time: ");
3607 dumpCurrentTime(pw);
3608 pw.println();
3609 });
3610 mShortcutDumpFiles.save("restore-1-payload.xml", payload);
3611
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003612 // Actually do restore.
3613 final ShortcutUser restored;
Makoto Onuki02f338e2016-07-29 09:40:40 -07003614 final ByteArrayInputStream is = new ByteArrayInputStream(payload);
3615 try {
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003616 restored = loadUserInternal(userId, is, /* fromBackup */ true);
3617 } catch (XmlPullParserException | IOException | InvalidFileFormatException e) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003618 Slog.w(TAG, "Restoration failed.", e);
3619 return;
3620 }
Makoto Onuki50a320e2017-05-31 14:38:42 -07003621 mShortcutDumpFiles.save("restore-2.txt", this::dumpInner);
3622
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003623 getUserShortcutsLocked(userId).mergeRestoredFile(restored);
Makoto Onuki2e210c42016-03-30 08:30:36 -07003624
Makoto Onuki50a320e2017-05-31 14:38:42 -07003625 mShortcutDumpFiles.save("restore-3.txt", this::dumpInner);
3626
Makoto Onuki377b7972016-08-09 14:43:55 -07003627 // Rescan all packages to re-publish manifest shortcuts and do other checks.
3628 rescanUpdatedPackagesLocked(userId,
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003629 0 // lastScanTime = 0; rescan all packages.
3630 );
Makoto Onuki2e210c42016-03-30 08:30:36 -07003631
Makoto Onuki50a320e2017-05-31 14:38:42 -07003632 mShortcutDumpFiles.save("restore-4.txt", this::dumpInner);
3633
3634 mShortcutDumpFiles.save("restore-5-finish.txt", pw -> {
3635 pw.print("Finish time: ");
3636 dumpCurrentTime(pw);
3637 pw.println();
3638 });
3639
Makoto Onuki2e210c42016-03-30 08:30:36 -07003640 saveUserLocked(userId);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003641 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07003642 }
3643
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003644 // === Dump ===
3645
3646 @Override
3647 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06003648 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
Makoto Onukic4361e32017-04-03 11:24:25 -07003649 dumpNoCheck(fd, pw, args);
3650 }
3651
3652 @VisibleForTesting
3653 void dumpNoCheck(FileDescriptor fd, PrintWriter pw, String[] args) {
Makoto Onuki20b82212017-10-04 15:03:50 -07003654 final DumpFilter filter = parseDumpArgs(args);
Makoto Onuki50a320e2017-05-31 14:38:42 -07003655
Makoto Onuki20b82212017-10-04 15:03:50 -07003656 if (filter.shouldDumpCheckIn()) {
Makoto Onuki50a320e2017-05-31 14:38:42 -07003657 // Other flags are not supported for checkin.
Makoto Onuki20b82212017-10-04 15:03:50 -07003658 dumpCheckin(pw, filter.shouldCheckInClear());
Makoto Onuki76269922016-07-15 14:58:54 -07003659 } else {
Makoto Onuki20b82212017-10-04 15:03:50 -07003660 if (filter.shouldDumpMain()) {
3661 dumpInner(pw, filter);
Makoto Onuki50a320e2017-05-31 14:38:42 -07003662 pw.println();
3663 }
Makoto Onuki20b82212017-10-04 15:03:50 -07003664 if (filter.shouldDumpUid()) {
Makoto Onuki50a320e2017-05-31 14:38:42 -07003665 dumpUid(pw);
3666 pw.println();
3667 }
Makoto Onuki20b82212017-10-04 15:03:50 -07003668 if (filter.shouldDumpFiles()) {
Makoto Onuki50a320e2017-05-31 14:38:42 -07003669 dumpDumpFiles(pw);
3670 pw.println();
3671 }
Makoto Onuki76269922016-07-15 14:58:54 -07003672 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003673 }
3674
Makoto Onuki20b82212017-10-04 15:03:50 -07003675 private static DumpFilter parseDumpArgs(String[] args) {
3676 final DumpFilter filter = new DumpFilter();
3677 if (args == null) {
3678 return filter;
3679 }
Makoto Onuki55046222016-03-08 10:49:47 -08003680
Makoto Onuki20b82212017-10-04 15:03:50 -07003681 int argIndex = 0;
3682 while (argIndex < args.length) {
3683 final String arg = args[argIndex++];
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003684
Makoto Onuki20b82212017-10-04 15:03:50 -07003685 if ("-c".equals(arg)) {
3686 filter.setDumpCheckIn(true);
3687 continue;
3688 }
3689 if ("--checkin".equals(arg)) {
3690 filter.setDumpCheckIn(true);
3691 filter.setCheckInClear(true);
3692 continue;
3693 }
3694 if ("-a".equals(arg) || "--all".equals(arg)) {
3695 filter.setDumpUid(true);
3696 filter.setDumpFiles(true);
3697 continue;
3698 }
3699 if ("-u".equals(arg) || "--uid".equals(arg)) {
3700 filter.setDumpUid(true);
3701 continue;
3702 }
3703 if ("-f".equals(arg) || "--files".equals(arg)) {
3704 filter.setDumpFiles(true);
3705 continue;
3706 }
3707 if ("-n".equals(arg) || "--no-main".equals(arg)) {
3708 filter.setDumpMain(false);
3709 continue;
3710 }
3711 if ("--user".equals(arg)) {
3712 if (argIndex >= args.length) {
3713 throw new IllegalArgumentException("Missing user ID for --user");
3714 }
3715 try {
3716 filter.addUser(Integer.parseInt(args[argIndex++]));
3717 } catch (NumberFormatException e) {
3718 throw new IllegalArgumentException("Invalid user ID", e);
3719 }
3720 continue;
3721 }
3722 if ("-p".equals(arg) || "--package".equals(arg)) {
3723 if (argIndex >= args.length) {
3724 throw new IllegalArgumentException("Missing package name for --package");
3725 }
3726 filter.addPackageRegex(args[argIndex++]);
3727 filter.setDumpDetails(false);
3728 continue;
3729 }
3730 if (arg.startsWith("-")) {
3731 throw new IllegalArgumentException("Unknown option " + arg);
3732 }
3733 break;
3734 }
3735 while (argIndex < args.length) {
3736 filter.addPackage(args[argIndex++]);
3737 }
3738 return filter;
3739 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003740
Makoto Onuki20b82212017-10-04 15:03:50 -07003741 static class DumpFilter {
3742 private boolean mDumpCheckIn = false;
3743 private boolean mCheckInClear = false;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003744
Makoto Onuki20b82212017-10-04 15:03:50 -07003745 private boolean mDumpMain = true;
3746 private boolean mDumpUid = false;
3747 private boolean mDumpFiles = false;
Makoto Onuki55046222016-03-08 10:49:47 -08003748
Makoto Onuki20b82212017-10-04 15:03:50 -07003749 private boolean mDumpDetails = true;
3750 private List<Pattern> mPackagePatterns = new ArrayList<>();
3751 private List<Integer> mUsers = new ArrayList<>();
3752
3753 void addPackageRegex(String regex) {
3754 mPackagePatterns.add(Pattern.compile(regex));
3755 }
3756
3757 public void addPackage(String packageName) {
3758 addPackageRegex(Pattern.quote(packageName));
3759 }
3760
3761 void addUser(int userId) {
3762 mUsers.add(userId);
3763 }
3764
3765 boolean isPackageMatch(String packageName) {
3766 if (mPackagePatterns.size() == 0) {
3767 return true;
3768 }
3769 for (int i = 0; i < mPackagePatterns.size(); i++) {
3770 if (mPackagePatterns.get(i).matcher(packageName).find()) {
3771 return true;
Makoto Onuki085a05c2016-08-19 11:39:29 -07003772 }
Makoto Onuki2e210c42016-03-30 08:30:36 -07003773 }
Makoto Onuki20b82212017-10-04 15:03:50 -07003774 return false;
3775 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003776
Makoto Onuki20b82212017-10-04 15:03:50 -07003777 boolean isUserMatch(int userId) {
3778 if (mUsers.size() == 0) {
3779 return true;
3780 }
3781 for (int i = 0; i < mUsers.size(); i++) {
3782 if (mUsers.get(i) == userId) {
3783 return true;
3784 }
3785 }
3786 return false;
3787 }
Makoto Onukia2241832016-07-06 13:28:37 -07003788
Makoto Onuki20b82212017-10-04 15:03:50 -07003789 public boolean shouldDumpCheckIn() {
3790 return mDumpCheckIn;
3791 }
3792
3793 public void setDumpCheckIn(boolean dumpCheckIn) {
3794 mDumpCheckIn = dumpCheckIn;
3795 }
3796
3797 public boolean shouldCheckInClear() {
3798 return mCheckInClear;
3799 }
3800
3801 public void setCheckInClear(boolean checkInClear) {
3802 mCheckInClear = checkInClear;
3803 }
3804
3805 public boolean shouldDumpMain() {
3806 return mDumpMain;
3807 }
3808
3809 public void setDumpMain(boolean dumpMain) {
3810 mDumpMain = dumpMain;
3811 }
3812
3813 public boolean shouldDumpUid() {
3814 return mDumpUid;
3815 }
3816
3817 public void setDumpUid(boolean dumpUid) {
3818 mDumpUid = dumpUid;
3819 }
3820
3821 public boolean shouldDumpFiles() {
3822 return mDumpFiles;
3823 }
3824
3825 public void setDumpFiles(boolean dumpFiles) {
3826 mDumpFiles = dumpFiles;
3827 }
3828
3829 public boolean shouldDumpDetails() {
3830 return mDumpDetails;
3831 }
3832
3833 public void setDumpDetails(boolean dumpDetails) {
3834 mDumpDetails = dumpDetails;
3835 }
3836 }
3837
3838 private void dumpInner(PrintWriter pw) {
3839 dumpInner(pw, new DumpFilter());
3840 }
3841
3842 private void dumpInner(PrintWriter pw, DumpFilter filter) {
3843 synchronized (mLock) {
3844 if (filter.shouldDumpDetails()) {
3845 final long now = injectCurrentTimeMillis();
3846 pw.print("Now: [");
3847 pw.print(now);
3848 pw.print("] ");
3849 pw.print(formatTime(now));
3850
3851 pw.print(" Raw last reset: [");
3852 pw.print(mRawLastResetTime);
3853 pw.print("] ");
3854 pw.print(formatTime(mRawLastResetTime));
3855
3856 final long last = getLastResetTimeLocked();
3857 pw.print(" Last reset: [");
3858 pw.print(last);
3859 pw.print("] ");
3860 pw.print(formatTime(last));
3861
3862 final long next = getNextResetTimeLocked();
3863 pw.print(" Next reset: [");
3864 pw.print(next);
3865 pw.print("] ");
3866 pw.print(formatTime(next));
Makoto Onukie3fffa92018-02-28 16:25:40 -08003867 pw.println();
3868 pw.println();
Makoto Onuki20b82212017-10-04 15:03:50 -07003869
3870 pw.print(" Config:");
3871 pw.print(" Max icon dim: ");
3872 pw.println(mMaxIconDimension);
3873 pw.print(" Icon format: ");
3874 pw.println(mIconPersistFormat);
3875 pw.print(" Icon quality: ");
3876 pw.println(mIconPersistQuality);
3877 pw.print(" saveDelayMillis: ");
3878 pw.println(mSaveDelayMillis);
3879 pw.print(" resetInterval: ");
3880 pw.println(mResetInterval);
3881 pw.print(" maxUpdatesPerInterval: ");
3882 pw.println(mMaxUpdatesPerInterval);
3883 pw.print(" maxShortcutsPerActivity: ");
3884 pw.println(mMaxShortcuts);
3885 pw.println();
3886
Makoto Onuki84d59342018-02-02 09:22:38 -08003887 mStatLogger.dump(pw, " ");
Makoto Onuki20b82212017-10-04 15:03:50 -07003888
3889 pw.println();
3890 pw.print(" #Failures: ");
3891 pw.println(mWtfCount);
3892
3893 if (mLastWtfStacktrace != null) {
3894 pw.print(" Last failure stack trace: ");
3895 pw.println(Log.getStackTraceString(mLastWtfStacktrace));
3896 }
3897
3898 pw.println();
3899 mShortcutBitmapSaver.dumpLocked(pw, " ");
3900
3901 pw.println();
Makoto Onukia2241832016-07-06 13:28:37 -07003902 }
3903
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08003904 for (int i = 0; i < mUsers.size(); i++) {
Makoto Onuki20b82212017-10-04 15:03:50 -07003905 final ShortcutUser user = mUsers.valueAt(i);
3906 if (filter.isUserMatch(user.getUserId())) {
3907 user.dump(pw, " ", filter);
3908 pw.println();
3909 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003910 }
Makoto Onuki708703b2017-12-11 16:38:11 -08003911
3912 for (int i = 0; i < mShortcutNonPersistentUsers.size(); i++) {
3913 final ShortcutNonPersistentUser user = mShortcutNonPersistentUsers.valueAt(i);
3914 if (filter.isUserMatch(user.getUserId())) {
3915 user.dump(pw, " ", filter);
3916 pw.println();
3917 }
3918 }
Makoto Onuki50a320e2017-05-31 14:38:42 -07003919 }
3920 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003921
Makoto Onuki50a320e2017-05-31 14:38:42 -07003922 private void dumpUid(PrintWriter pw) {
3923 synchronized (mLock) {
3924 pw.println("** SHORTCUT MANAGER UID STATES (dumpsys shortcut -n -u)");
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003925
3926 for (int i = 0; i < mUidState.size(); i++) {
3927 final int uid = mUidState.keyAt(i);
3928 final int state = mUidState.valueAt(i);
3929 pw.print(" UID=");
3930 pw.print(uid);
3931 pw.print(" state=");
3932 pw.print(state);
3933 if (isProcessStateForeground(state)) {
3934 pw.print(" [FG]");
3935 }
3936 pw.print(" last FG=");
3937 pw.print(mUidLastForegroundElapsedTime.get(uid));
3938 pw.println();
3939 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003940 }
3941 }
3942
Makoto Onuki41066a62016-03-09 16:18:44 -08003943 static String formatTime(long time) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003944 Time tobj = new Time();
3945 tobj.set(time);
3946 return tobj.format("%Y-%m-%d %H:%M:%S");
3947 }
3948
Makoto Onuki50a320e2017-05-31 14:38:42 -07003949 private void dumpCurrentTime(PrintWriter pw) {
3950 pw.print(formatTime(injectCurrentTimeMillis()));
3951 }
3952
Makoto Onuki76269922016-07-15 14:58:54 -07003953 /**
3954 * Dumpsys for checkin.
3955 *
3956 * @param clear if true, clear the history information. Some other system services have this
3957 * behavior but shortcut service doesn't for now.
3958 */
3959 private void dumpCheckin(PrintWriter pw, boolean clear) {
3960 synchronized (mLock) {
3961 try {
3962 final JSONArray users = new JSONArray();
3963
3964 for (int i = 0; i < mUsers.size(); i++) {
3965 users.put(mUsers.valueAt(i).dumpCheckin(clear));
3966 }
3967
3968 final JSONObject result = new JSONObject();
3969
3970 result.put(KEY_SHORTCUT, users);
3971 result.put(KEY_LOW_RAM, injectIsLowRamDevice());
3972 result.put(KEY_ICON_SIZE, mMaxIconDimension);
3973
3974 pw.println(result.toString(1));
3975 } catch (JSONException e) {
3976 Slog.e(TAG, "Unable to write in json", e);
3977 }
3978 }
3979 }
3980
Makoto Onuki50a320e2017-05-31 14:38:42 -07003981 private void dumpDumpFiles(PrintWriter pw) {
3982 synchronized (mLock) {
3983 pw.println("** SHORTCUT MANAGER FILES (dumpsys shortcut -n -f)");
3984 mShortcutDumpFiles.dumpAll(pw);
3985 }
3986 }
3987
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003988 // === Shell support ===
3989
3990 @Override
3991 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003992 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003993
3994 enforceShell();
3995
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07003996 final long token = injectClearCallingIdentity();
3997 try {
Dianne Hackborn354736e2016-08-22 17:00:05 -07003998 final int status = (new MyShellCommand()).exec(this, in, out, err, args, callback,
3999 resultReceiver);
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07004000 resultReceiver.send(status, null);
4001 } finally {
4002 injectRestoreCallingIdentity(token);
4003 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004004 }
4005
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004006 static class CommandException extends Exception {
4007 public CommandException(String message) {
4008 super(message);
4009 }
4010 }
4011
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004012 /**
4013 * Handle "adb shell cmd".
4014 */
4015 private class MyShellCommand extends ShellCommand {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004016
4017 private int mUserId = UserHandle.USER_SYSTEM;
4018
Makoto Onuki02f338e2016-07-29 09:40:40 -07004019 private void parseOptionsLocked(boolean takeUser)
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004020 throws CommandException {
4021 String opt;
4022 while ((opt = getNextOption()) != null) {
4023 switch (opt) {
4024 case "--user":
4025 if (takeUser) {
4026 mUserId = UserHandle.parseUserArg(getNextArgRequired());
Makoto Onuki02f338e2016-07-29 09:40:40 -07004027 if (!isUserUnlockedL(mUserId)) {
Makoto Onukif34c3082016-07-13 10:25:25 -07004028 throw new CommandException(
4029 "User " + mUserId + " is not running or locked");
4030 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004031 break;
4032 }
4033 // fallthrough
4034 default:
4035 throw new CommandException("Unknown option: " + opt);
4036 }
4037 }
4038 }
4039
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004040 @Override
4041 public int onCommand(String cmd) {
4042 if (cmd == null) {
4043 return handleDefaultCommands(cmd);
4044 }
4045 final PrintWriter pw = getOutPrintWriter();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004046 try {
4047 switch (cmd) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004048 case "reset-throttling":
4049 handleResetThrottling();
4050 break;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004051 case "reset-all-throttling":
4052 handleResetAllThrottling();
4053 break;
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004054 case "override-config":
4055 handleOverrideConfig();
4056 break;
4057 case "reset-config":
4058 handleResetConfig();
4059 break;
4060 case "clear-default-launcher":
4061 handleClearDefaultLauncher();
4062 break;
4063 case "get-default-launcher":
4064 handleGetDefaultLauncher();
4065 break;
Makoto Onukiac214972016-04-04 10:19:45 -07004066 case "unload-user":
4067 handleUnloadUser();
4068 break;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004069 case "clear-shortcuts":
4070 handleClearShortcuts();
4071 break;
Makoto Onukib08790c2016-06-23 14:05:46 -07004072 case "verify-states": // hidden command to verify various internal states.
4073 handleVerifyStates();
4074 break;
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004075 default:
4076 return handleDefaultCommands(cmd);
4077 }
4078 } catch (CommandException e) {
4079 pw.println("Error: " + e.getMessage());
4080 return 1;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004081 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004082 pw.println("Success");
4083 return 0;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004084 }
4085
4086 @Override
4087 public void onHelp() {
4088 final PrintWriter pw = getOutPrintWriter();
4089 pw.println("Usage: cmd shortcut COMMAND [options ...]");
4090 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004091 pw.println("cmd shortcut reset-throttling [--user USER_ID]");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004092 pw.println(" Reset throttling for all packages and users");
4093 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004094 pw.println("cmd shortcut reset-all-throttling");
4095 pw.println(" Reset the throttling state for all users");
4096 pw.println();
Makoto Onuki4362a662016-03-08 18:59:09 -08004097 pw.println("cmd shortcut override-config CONFIG");
4098 pw.println(" Override the configuration for testing (will last until reboot)");
4099 pw.println();
4100 pw.println("cmd shortcut reset-config");
4101 pw.println(" Reset the configuration set with \"update-config\"");
4102 pw.println();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004103 pw.println("cmd shortcut clear-default-launcher [--user USER_ID]");
4104 pw.println(" Clear the cached default launcher");
4105 pw.println();
4106 pw.println("cmd shortcut get-default-launcher [--user USER_ID]");
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07004107 pw.println(" Show the default launcher");
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004108 pw.println();
Makoto Onukiac214972016-04-04 10:19:45 -07004109 pw.println("cmd shortcut unload-user [--user USER_ID]");
4110 pw.println(" Unload a user from the memory");
4111 pw.println(" (This should not affect any observable behavior)");
4112 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004113 pw.println("cmd shortcut clear-shortcuts [--user USER_ID] PACKAGE");
4114 pw.println(" Remove all shortcuts from a package, including pinned shortcuts");
4115 pw.println();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004116 }
4117
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004118 private void handleResetThrottling() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07004119 synchronized (mLock) {
4120 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki4554d0e2016-03-14 15:51:41 -07004121
Makoto Onuki02f338e2016-07-29 09:40:40 -07004122 Slog.i(TAG, "cmd: handleResetThrottling: user=" + mUserId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004123
Makoto Onuki02f338e2016-07-29 09:40:40 -07004124 resetThrottlingInner(mUserId);
4125 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004126 }
4127
4128 private void handleResetAllThrottling() {
4129 Slog.i(TAG, "cmd: handleResetAllThrottling");
4130
4131 resetAllThrottlingInner();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004132 }
4133
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004134 private void handleOverrideConfig() throws CommandException {
Makoto Onuki4362a662016-03-08 18:59:09 -08004135 final String config = getNextArgRequired();
4136
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004137 Slog.i(TAG, "cmd: handleOverrideConfig: " + config);
4138
Makoto Onuki4362a662016-03-08 18:59:09 -08004139 synchronized (mLock) {
4140 if (!updateConfigurationLocked(config)) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004141 throw new CommandException("override-config failed. See logcat for details.");
Makoto Onuki4362a662016-03-08 18:59:09 -08004142 }
4143 }
Makoto Onuki4362a662016-03-08 18:59:09 -08004144 }
4145
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004146 private void handleResetConfig() {
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004147 Slog.i(TAG, "cmd: handleResetConfig");
4148
Makoto Onuki4362a662016-03-08 18:59:09 -08004149 synchronized (mLock) {
4150 loadConfigurationLocked();
4151 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004152 }
4153
4154 private void clearLauncher() {
4155 synchronized (mLock) {
Makoto Onuki10305202016-07-14 18:14:08 -07004156 getUserShortcutsLocked(mUserId).forceClearLauncher();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004157 }
4158 }
4159
4160 private void showLauncher() {
4161 synchronized (mLock) {
4162 // This ensures to set the cached launcher. Package name doesn't matter.
4163 hasShortcutHostPermissionInner("-", mUserId);
4164
4165 getOutPrintWriter().println("Launcher: "
Makoto Onuki10305202016-07-14 18:14:08 -07004166 + getUserShortcutsLocked(mUserId).getLastKnownLauncher());
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004167 }
4168 }
4169
4170 private void handleClearDefaultLauncher() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07004171 synchronized (mLock) {
4172 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004173
Makoto Onuki02f338e2016-07-29 09:40:40 -07004174 clearLauncher();
4175 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004176 }
4177
4178 private void handleGetDefaultLauncher() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07004179 synchronized (mLock) {
4180 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004181
Makoto Onuki02f338e2016-07-29 09:40:40 -07004182 clearLauncher();
4183 showLauncher();
4184 }
Makoto Onuki4362a662016-03-08 18:59:09 -08004185 }
Makoto Onukiac214972016-04-04 10:19:45 -07004186
4187 private void handleUnloadUser() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07004188 synchronized (mLock) {
4189 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onukiac214972016-04-04 10:19:45 -07004190
Makoto Onuki02f338e2016-07-29 09:40:40 -07004191 Slog.i(TAG, "cmd: handleUnloadUser: user=" + mUserId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004192
Makoto Onuki01ce92b2017-04-28 12:24:16 -07004193 ShortcutService.this.handleStopUser(mUserId);
Makoto Onuki02f338e2016-07-29 09:40:40 -07004194 }
Makoto Onukiac214972016-04-04 10:19:45 -07004195 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004196
4197 private void handleClearShortcuts() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07004198 synchronized (mLock) {
4199 parseOptionsLocked(/* takeUser =*/ true);
4200 final String packageName = getNextArgRequired();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004201
Makoto Onuki02f338e2016-07-29 09:40:40 -07004202 Slog.i(TAG, "cmd: handleClearShortcuts: user" + mUserId + ", " + packageName);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004203
Makoto Onuki02f338e2016-07-29 09:40:40 -07004204 ShortcutService.this.cleanUpPackageForAllLoadedUsers(packageName, mUserId,
4205 /* appStillExists = */ true);
4206 }
Makoto Onukib08790c2016-06-23 14:05:46 -07004207 }
4208
4209 private void handleVerifyStates() throws CommandException {
4210 try {
4211 verifyStatesForce(); // This will throw when there's an issue.
4212 } catch (Throwable th) {
4213 throw new CommandException(th.getMessage() + "\n" + Log.getStackTraceString(th));
4214 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004215 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004216 }
4217
4218 // === Unit test support ===
4219
4220 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07004221 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004222 long injectCurrentTimeMillis() {
4223 return System.currentTimeMillis();
4224 }
4225
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07004226 @VisibleForTesting
4227 long injectElapsedRealtime() {
4228 return SystemClock.elapsedRealtime();
4229 }
4230
Makoto Onuki475c3652017-05-08 14:29:03 -07004231 @VisibleForTesting
4232 long injectUptimeMillis() {
4233 return SystemClock.uptimeMillis();
4234 }
4235
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004236 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07004237 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004238 int injectBinderCallingUid() {
4239 return getCallingUid();
4240 }
4241
Makoto Onuki7d0fa812018-02-21 11:24:43 -08004242 @VisibleForTesting
4243 int injectBinderCallingPid() {
4244 return getCallingPid();
4245 }
4246
Makoto Onuki31459242016-03-22 11:12:18 -07004247 private int getCallingUserId() {
Makoto Onuki4554d0e2016-03-14 15:51:41 -07004248 return UserHandle.getUserId(injectBinderCallingUid());
4249 }
4250
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07004251 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07004252 @VisibleForTesting
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07004253 long injectClearCallingIdentity() {
4254 return Binder.clearCallingIdentity();
4255 }
4256
4257 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07004258 @VisibleForTesting
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07004259 void injectRestoreCallingIdentity(long token) {
4260 Binder.restoreCallingIdentity(token);
4261 }
4262
Makoto Onuki33663282016-08-22 16:19:04 -07004263 // Injection point.
Makoto Onuki33663282016-08-22 16:19:04 -07004264 String injectBuildFingerprint() {
4265 return Build.FINGERPRINT;
4266 }
4267
Makoto Onukide667372016-03-15 14:29:20 -07004268 final void wtf(String message) {
Makoto Onukib08790c2016-06-23 14:05:46 -07004269 wtf(message, /* exception= */ null);
Makoto Onukide667372016-03-15 14:29:20 -07004270 }
4271
Makoto Onuki2e210c42016-03-30 08:30:36 -07004272 // Injection point.
Makoto Onukia2241832016-07-06 13:28:37 -07004273 void wtf(String message, Throwable e) {
4274 if (e == null) {
4275 e = new RuntimeException("Stacktrace");
4276 }
4277 synchronized (mLock) {
4278 mWtfCount++;
4279 mLastWtfStacktrace = new Exception("Last failure was logged here:");
4280 }
Makoto Onukide667372016-03-15 14:29:20 -07004281 Slog.wtf(TAG, message, e);
4282 }
4283
Makoto Onuki31459242016-03-22 11:12:18 -07004284 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004285 File injectSystemDataPath() {
4286 return Environment.getDataSystemDirectory();
4287 }
4288
Makoto Onuki31459242016-03-22 11:12:18 -07004289 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004290 File injectUserDataPath(@UserIdInt int userId) {
Makoto Onuki55046222016-03-08 10:49:47 -08004291 return new File(Environment.getDataSystemCeDirectory(userId), DIRECTORY_PER_USER);
4292 }
4293
Makoto Onuki50a320e2017-05-31 14:38:42 -07004294 public File getDumpPath() {
4295 return new File(injectUserDataPath(UserHandle.USER_SYSTEM), DIRECTORY_DUMP);
4296 }
4297
Makoto Onuki4362a662016-03-08 18:59:09 -08004298 @VisibleForTesting
Makoto Onuki55046222016-03-08 10:49:47 -08004299 boolean injectIsLowRamDevice() {
4300 return ActivityManager.isLowRamDeviceStatic();
4301 }
4302
Makoto Onuki31459242016-03-22 11:12:18 -07004303 @VisibleForTesting
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07004304 void injectRegisterUidObserver(IUidObserver observer, int which) {
4305 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004306 ActivityManager.getService().registerUidObserver(observer, which,
Dianne Hackborn5614bf52016-11-07 17:26:41 -08004307 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07004308 } catch (RemoteException shouldntHappen) {
4309 }
4310 }
4311
Makoto Onuki55046222016-03-08 10:49:47 -08004312 File getUserBitmapFilePath(@UserIdInt int userId) {
4313 return new File(injectUserDataPath(userId), DIRECTORY_BITMAPS);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004314 }
4315
4316 @VisibleForTesting
Makoto Onuki31459242016-03-22 11:12:18 -07004317 SparseArray<ShortcutUser> getShortcutsForTest() {
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08004318 return mUsers;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004319 }
4320
4321 @VisibleForTesting
Makoto Onukib5a012f2016-06-21 11:13:53 -07004322 int getMaxShortcutsForTest() {
4323 return mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004324 }
4325
4326 @VisibleForTesting
Makoto Onukib6d35232016-04-04 15:57:17 -07004327 int getMaxUpdatesPerIntervalForTest() {
4328 return mMaxUpdatesPerInterval;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004329 }
4330
4331 @VisibleForTesting
Makoto Onuki4362a662016-03-08 18:59:09 -08004332 long getResetIntervalForTest() {
4333 return mResetInterval;
Makoto Onuki55046222016-03-08 10:49:47 -08004334 }
4335
4336 @VisibleForTesting
Makoto Onuki4362a662016-03-08 18:59:09 -08004337 int getMaxIconDimensionForTest() {
4338 return mMaxIconDimension;
4339 }
4340
4341 @VisibleForTesting
4342 CompressFormat getIconPersistFormatForTest() {
4343 return mIconPersistFormat;
4344 }
4345
4346 @VisibleForTesting
4347 int getIconPersistQualityForTest() {
4348 return mIconPersistQuality;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004349 }
Makoto Onuki41066a62016-03-09 16:18:44 -08004350
4351 @VisibleForTesting
Makoto Onuki22fcc682016-05-17 14:52:19 -07004352 ShortcutPackage getPackageShortcutForTest(String packageName, int userId) {
Makoto Onuki41066a62016-03-09 16:18:44 -08004353 synchronized (mLock) {
Makoto Onuki31459242016-03-22 11:12:18 -07004354 final ShortcutUser user = mUsers.get(userId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07004355 if (user == null) return null;
4356
Makoto Onuki22fcc682016-05-17 14:52:19 -07004357 return user.getAllPackagesForTest().get(packageName);
4358 }
4359 }
4360
4361 @VisibleForTesting
4362 ShortcutInfo getPackageShortcutForTest(String packageName, String shortcutId, int userId) {
4363 synchronized (mLock) {
Makoto Onukif34c3082016-07-13 10:25:25 -07004364 final ShortcutPackage pkg = getPackageShortcutForTest(packageName, userId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07004365 if (pkg == null) return null;
4366
4367 return pkg.findShortcutById(shortcutId);
Makoto Onuki41066a62016-03-09 16:18:44 -08004368 }
4369 }
Makoto Onuki7001a612016-05-27 13:24:28 -07004370
Makoto Onukifac592f2016-11-21 13:41:32 -08004371 @VisibleForTesting
4372 ShortcutLauncher getLauncherShortcutForTest(String packageName, int userId) {
4373 synchronized (mLock) {
4374 final ShortcutUser user = mUsers.get(userId);
4375 if (user == null) return null;
4376
4377 return user.getAllLaunchersForTest().get(PackageWithUser.of(userId, packageName));
4378 }
4379 }
4380
Makoto Onuki2d895c32016-12-02 15:48:40 -08004381 @VisibleForTesting
4382 ShortcutRequestPinProcessor getShortcutRequestPinProcessorForTest() {
4383 return mShortcutRequestPinProcessor;
4384 }
4385
Makoto Onuki7001a612016-05-27 13:24:28 -07004386 /**
4387 * Control whether {@link #verifyStates} should be performed. We always perform it during unit
4388 * tests.
4389 */
4390 @VisibleForTesting
4391 boolean injectShouldPerformVerification() {
4392 return DEBUG;
4393 }
4394
4395 /**
4396 * Check various internal states and throws if there's any inconsistency.
4397 * This is normally only enabled during unit tests.
4398 */
4399 final void verifyStates() {
4400 if (injectShouldPerformVerification()) {
4401 verifyStatesInner();
4402 }
4403 }
4404
Makoto Onukib08790c2016-06-23 14:05:46 -07004405 private final void verifyStatesForce() {
4406 verifyStatesInner();
4407 }
4408
Makoto Onuki7001a612016-05-27 13:24:28 -07004409 private void verifyStatesInner() {
Makoto Onuki10305202016-07-14 18:14:08 -07004410 synchronized (mLock) {
Makoto Onuki7001a612016-05-27 13:24:28 -07004411 forEachLoadedUserLocked(u -> u.forAllPackageItems(ShortcutPackageItem::verifyStates));
4412 }
4413 }
Makoto Onuki475c3652017-05-08 14:29:03 -07004414
4415 @VisibleForTesting
4416 void waitForBitmapSavesForTest() {
4417 synchronized (mLock) {
4418 mShortcutBitmapSaver.waitForAllSavesLocked();
4419 }
4420 }
Makoto Onuki41066a62016-03-09 16:18:44 -08004421}