blob: ff6d7a888950c8f583e06e33ec04e903931b60ac [file] [log] [blame]
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package com.android.server.pm;
17
Makoto Onuki7d0fa812018-02-21 11:24:43 -080018import android.Manifest.permission;
Makoto Onuki7001a612016-05-27 13:24:28 -070019import android.annotation.IntDef;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080020import android.annotation.NonNull;
21import android.annotation.Nullable;
22import android.annotation.UserIdInt;
Makoto Onuki55046222016-03-08 10:49:47 -080023import android.app.ActivityManager;
Makoto Onuki33525d22016-08-03 15:45:24 -070024import android.app.ActivityManagerInternal;
Makoto Onuki0acbb142016-03-22 17:02:57 -070025import android.app.AppGlobals;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -070026import android.app.IUidObserver;
Makoto Onukiac042502016-05-20 16:39:42 -070027import android.app.usage.UsageStatsManagerInternal;
Sunny Goyal87a563e2017-01-01 19:42:45 -080028import android.appwidget.AppWidgetProviderInfo;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070029import android.content.BroadcastReceiver;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080030import android.content.ComponentName;
31import android.content.Context;
32import android.content.Intent;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070033import android.content.IntentFilter;
Makoto Onuki2d895c32016-12-02 15:48:40 -080034import android.content.IntentSender;
35import android.content.IntentSender.SendIntentException;
Makoto Onuki22fcc682016-05-17 14:52:19 -070036import android.content.pm.ActivityInfo;
Makoto Onuki0acbb142016-03-22 17:02:57 -070037import android.content.pm.ApplicationInfo;
38import android.content.pm.IPackageManager;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080039import android.content.pm.IShortcutService;
40import android.content.pm.LauncherApps;
41import android.content.pm.LauncherApps.ShortcutQuery;
Makoto Onuki0acbb142016-03-22 17:02:57 -070042import android.content.pm.PackageInfo;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080043import android.content.pm.PackageManager;
Todd Kennedy0eb97382017-10-03 16:57:22 -070044import android.content.pm.PackageManager.NameNotFoundException;
Mehdi Alizadeh32774622018-11-05 17:32:01 -080045import android.content.pm.PackageManagerInternal;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080046import android.content.pm.ParceledListSlice;
Makoto Onuki2d5b4652016-03-11 16:09:54 -080047import android.content.pm.ResolveInfo;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080048import android.content.pm.ShortcutInfo;
Mehdi Alizadeh406e8b32018-12-11 18:21:49 -080049import android.content.pm.ShortcutManager;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080050import android.content.pm.ShortcutServiceInternal;
51import android.content.pm.ShortcutServiceInternal.ShortcutChangeListener;
Makoto Onuki157b1622016-06-02 16:13:10 -070052import android.content.res.Resources;
Makoto Onuki22fcc682016-05-17 14:52:19 -070053import android.content.res.XmlResourceParser;
Makoto Onuki55046222016-03-08 10:49:47 -080054import android.graphics.Bitmap;
55import android.graphics.Bitmap.CompressFormat;
Makoto Onuki55046222016-03-08 10:49:47 -080056import android.graphics.Canvas;
57import android.graphics.RectF;
Hyunyoung Song47037462017-05-08 16:51:43 -070058import android.graphics.drawable.AdaptiveIconDrawable;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080059import android.graphics.drawable.Icon;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070060import android.net.Uri;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080061import android.os.Binder;
Makoto Onuki33663282016-08-22 16:19:04 -070062import android.os.Build;
Sunny Goyal4ad6b572017-02-28 11:11:51 -080063import android.os.Bundle;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080064import android.os.Environment;
Makoto Onuki2e210c42016-03-30 08:30:36 -070065import android.os.FileUtils;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080066import android.os.Handler;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070067import android.os.LocaleList;
Makoto Onukiaa8b94a2016-03-17 13:14:05 -070068import android.os.Looper;
Makoto Onuki55046222016-03-08 10:49:47 -080069import android.os.ParcelFileDescriptor;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080070import android.os.PersistableBundle;
71import android.os.Process;
72import android.os.RemoteException;
73import android.os.ResultReceiver;
Makoto Onuki55046222016-03-08 10:49:47 -080074import android.os.SELinux;
Makoto Onukib08790c2016-06-23 14:05:46 -070075import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070076import android.os.ShellCallback;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080077import android.os.ShellCommand;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -070078import android.os.SystemClock;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080079import android.os.UserHandle;
Sunny Goyal145c8f82018-02-15 14:27:09 -080080import android.os.UserManagerInternal;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080081import android.text.TextUtils;
82import android.text.format.Time;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080083import android.util.ArraySet;
84import android.util.AtomicFile;
Makoto Onuki4362a662016-03-08 18:59:09 -080085import android.util.KeyValueListParser;
Makoto Onukiac042502016-05-20 16:39:42 -070086import android.util.Log;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080087import android.util.Slog;
88import android.util.SparseArray;
Makoto Onuki02f338e2016-07-29 09:40:40 -070089import android.util.SparseBooleanArray;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -070090import android.util.SparseIntArray;
91import android.util.SparseLongArray;
Makoto Onuki55046222016-03-08 10:49:47 -080092import android.util.TypedValue;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080093import android.util.Xml;
Makoto Onukib08790c2016-06-23 14:05:46 -070094import android.view.IWindowManager;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080095
96import com.android.internal.annotations.GuardedBy;
97import com.android.internal.annotations.VisibleForTesting;
98import com.android.internal.os.BackgroundThread;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060099import com.android.internal.util.DumpUtils;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800100import com.android.internal.util.FastXmlSerializer;
101import com.android.internal.util.Preconditions;
Makoto Onuki49392d32018-04-11 13:51:02 -0700102import com.android.internal.util.StatLogger;
Mehdi Alizadeh32774622018-11-05 17:32:01 -0800103import com.android.server.LocalServices;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800104import com.android.server.SystemService;
Makoto Onukid99c6f02016-03-28 11:02:54 -0700105import com.android.server.pm.ShortcutUser.PackageWithUser;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800106
107import libcore.io.IoUtils;
108
Makoto Onuki76269922016-07-15 14:58:54 -0700109import org.json.JSONArray;
110import org.json.JSONException;
111import org.json.JSONObject;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800112import org.xmlpull.v1.XmlPullParser;
113import org.xmlpull.v1.XmlPullParserException;
114import org.xmlpull.v1.XmlSerializer;
115
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700116import java.io.BufferedInputStream;
117import java.io.BufferedOutputStream;
118import java.io.ByteArrayInputStream;
119import java.io.ByteArrayOutputStream;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800120import java.io.File;
121import java.io.FileDescriptor;
122import java.io.FileInputStream;
123import java.io.FileNotFoundException;
124import java.io.FileOutputStream;
125import java.io.IOException;
Makoto Onuki55046222016-03-08 10:49:47 -0800126import java.io.InputStream;
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700127import java.io.OutputStream;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800128import java.io.PrintWriter;
Makoto Onuki7001a612016-05-27 13:24:28 -0700129import java.lang.annotation.Retention;
130import java.lang.annotation.RetentionPolicy;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800131import java.net.URISyntaxException;
132import java.nio.charset.StandardCharsets;
133import java.util.ArrayList;
Makoto Onuki22fcc682016-05-17 14:52:19 -0700134import java.util.Collections;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800135import java.util.List;
Makoto Onukia19fb232018-06-12 13:01:42 -0700136import java.util.Objects;
Makoto Onukic51b2872016-05-04 15:24:50 -0700137import java.util.concurrent.atomic.AtomicBoolean;
Makoto Onuki2e210c42016-03-30 08:30:36 -0700138import java.util.function.Consumer;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800139import java.util.function.Predicate;
Makoto Onuki20b82212017-10-04 15:03:50 -0700140import java.util.regex.Pattern;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800141
142/**
143 * TODO:
Makoto Onuki22fcc682016-05-17 14:52:19 -0700144 * - getIconMaxWidth()/getIconMaxHeight() should use xdpi and ydpi.
Makoto Onukib5a012f2016-06-21 11:13:53 -0700145 * -> But TypedValue.applyDimension() doesn't differentiate x and y..?
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800146 *
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700147 * - Detect when already registered instances are passed to APIs again, which might break
Makoto Onukib08790c2016-06-23 14:05:46 -0700148 * internal bitmap handling.
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800149 */
150public class ShortcutService extends IShortcutService.Stub {
Makoto Onuki55046222016-03-08 10:49:47 -0800151 static final String TAG = "ShortcutService";
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800152
Makoto Onuki7001a612016-05-27 13:24:28 -0700153 static final boolean DEBUG = false; // STOPSHIP if true
Makoto Onuki41066a62016-03-09 16:18:44 -0800154 static final boolean DEBUG_LOAD = false; // STOPSHIP if true
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700155 static final boolean DEBUG_PROCSTATE = false; // STOPSHIP if true
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800156
Makoto Onuki4362a662016-03-08 18:59:09 -0800157 @VisibleForTesting
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700158 static final long DEFAULT_RESET_INTERVAL_SEC = 24 * 60 * 60; // 1 day
Makoto Onuki4362a662016-03-08 18:59:09 -0800159
160 @VisibleForTesting
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700161 static final int DEFAULT_MAX_UPDATES_PER_INTERVAL = 10;
Makoto Onuki4362a662016-03-08 18:59:09 -0800162
163 @VisibleForTesting
164 static final int DEFAULT_MAX_SHORTCUTS_PER_APP = 5;
165
166 @VisibleForTesting
167 static final int DEFAULT_MAX_ICON_DIMENSION_DP = 96;
168
169 @VisibleForTesting
170 static final int DEFAULT_MAX_ICON_DIMENSION_LOWRAM_DP = 48;
171
172 @VisibleForTesting
173 static final String DEFAULT_ICON_PERSIST_FORMAT = CompressFormat.PNG.name();
174
175 @VisibleForTesting
176 static final int DEFAULT_ICON_PERSIST_QUALITY = 100;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800177
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700178 @VisibleForTesting
179 static final int DEFAULT_SAVE_DELAY_MS = 3000;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800180
181 @VisibleForTesting
182 static final String FILENAME_BASE_STATE = "shortcut_service.xml";
183
184 @VisibleForTesting
185 static final String DIRECTORY_PER_USER = "shortcut_service";
186
187 @VisibleForTesting
Makoto Onuki50a320e2017-05-31 14:38:42 -0700188 static final String DIRECTORY_DUMP = "shortcut_dump";
189
190 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800191 static final String FILENAME_USER_PACKAGES = "shortcuts.xml";
192
Makoto Onuki55046222016-03-08 10:49:47 -0800193 static final String DIRECTORY_BITMAPS = "bitmaps";
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800194
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700195 private static final String TAG_ROOT = "root";
196 private static final String TAG_LAST_RESET_TIME = "last_reset_time";
Makoto Onuki55046222016-03-08 10:49:47 -0800197
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700198 private static final String ATTR_VALUE = "value";
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800199
Makoto Onukib08790c2016-06-23 14:05:46 -0700200 private static final String LAUNCHER_INTENT_CATEGORY = Intent.CATEGORY_LAUNCHER;
201
Makoto Onuki76269922016-07-15 14:58:54 -0700202 private static final String KEY_SHORTCUT = "shortcut";
203 private static final String KEY_LOW_RAM = "lowRam";
204 private static final String KEY_ICON_SIZE = "iconSize";
205
Makoto Onuki2d895c32016-12-02 15:48:40 -0800206 private static final String DUMMY_MAIN_ACTIVITY = "android.__dummy__";
207
Makoto Onuki4362a662016-03-08 18:59:09 -0800208 @VisibleForTesting
209 interface ConfigConstants {
210 /**
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700211 * Key name for the save delay, in milliseconds. (int)
212 */
213 String KEY_SAVE_DELAY_MILLIS = "save_delay_ms";
214
215 /**
Makoto Onuki4362a662016-03-08 18:59:09 -0800216 * Key name for the throttling reset interval, in seconds. (long)
217 */
218 String KEY_RESET_INTERVAL_SEC = "reset_interval_sec";
219
220 /**
221 * Key name for the max number of modifying API calls per app for every interval. (int)
222 */
Makoto Onukib6d35232016-04-04 15:57:17 -0700223 String KEY_MAX_UPDATES_PER_INTERVAL = "max_updates_per_interval";
Makoto Onuki4362a662016-03-08 18:59:09 -0800224
225 /**
226 * Key name for the max icon dimensions in DP, for non-low-memory devices.
227 */
228 String KEY_MAX_ICON_DIMENSION_DP = "max_icon_dimension_dp";
229
230 /**
231 * Key name for the max icon dimensions in DP, for low-memory devices.
232 */
233 String KEY_MAX_ICON_DIMENSION_DP_LOWRAM = "max_icon_dimension_dp_lowram";
234
235 /**
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700236 * Key name for the max dynamic shortcuts per activity. (int)
Makoto Onuki4362a662016-03-08 18:59:09 -0800237 */
238 String KEY_MAX_SHORTCUTS = "max_shortcuts";
239
240 /**
Makoto Onuki41066a62016-03-09 16:18:44 -0800241 * Key name for icon compression quality, 0-100.
Makoto Onuki4362a662016-03-08 18:59:09 -0800242 */
243 String KEY_ICON_QUALITY = "icon_quality";
244
245 /**
246 * Key name for icon compression format: "PNG", "JPEG" or "WEBP"
247 */
248 String KEY_ICON_FORMAT = "icon_format";
249 }
250
Makoto Onuki41066a62016-03-09 16:18:44 -0800251 final Context mContext;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800252
253 private final Object mLock = new Object();
254
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700255 private static List<ResolveInfo> EMPTY_RESOLVE_INFO = new ArrayList<>(0);
256
Mark Renoufe065f7c2016-11-01 11:48:24 -0400257 // Temporarily reverted to anonymous inner class form due to: b/32554459
258 private static Predicate<ResolveInfo> ACTIVITY_NOT_EXPORTED = new Predicate<ResolveInfo>() {
259 public boolean test(ResolveInfo ri) {
260 return !ri.activityInfo.exported;
261 }
262 };
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700263
Mark Renoufe065f7c2016-11-01 11:48:24 -0400264 // Temporarily reverted to anonymous inner class form due to: b/32554459
265 private static Predicate<PackageInfo> PACKAGE_NOT_INSTALLED = new Predicate<PackageInfo>() {
266 public boolean test(PackageInfo pi) {
267 return !isInstalled(pi);
268 }
269 };
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700270
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800271 private final Handler mHandler;
272
273 @GuardedBy("mLock")
274 private final ArrayList<ShortcutChangeListener> mListeners = new ArrayList<>(1);
275
276 @GuardedBy("mLock")
277 private long mRawLastResetTime;
278
279 /**
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -0800280 * User ID -> UserShortcuts
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800281 */
282 @GuardedBy("mLock")
Makoto Onuki31459242016-03-22 11:12:18 -0700283 private final SparseArray<ShortcutUser> mUsers = new SparseArray<>();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800284
285 /**
Makoto Onuki708703b2017-12-11 16:38:11 -0800286 * User ID -> ShortcutNonPersistentUser
287 */
288 @GuardedBy("mLock")
289 private final SparseArray<ShortcutNonPersistentUser> mShortcutNonPersistentUsers =
290 new SparseArray<>();
291
292 /**
Makoto Onukib5a012f2016-06-21 11:13:53 -0700293 * Max number of dynamic + manifest shortcuts that each application can have at a time.
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800294 */
Makoto Onukib5a012f2016-06-21 11:13:53 -0700295 private int mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800296
297 /**
Makoto Onukib6d35232016-04-04 15:57:17 -0700298 * Max number of updating API calls that each application can make during the interval.
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800299 */
Makoto Onukib6d35232016-04-04 15:57:17 -0700300 int mMaxUpdatesPerInterval;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800301
302 /**
303 * Actual throttling-reset interval. By default it's a day.
304 */
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800305 private long mResetInterval;
306
Makoto Onuki55046222016-03-08 10:49:47 -0800307 /**
308 * Icon max width/height in pixels.
309 */
310 private int mMaxIconDimension;
311
Makoto Onuki4362a662016-03-08 18:59:09 -0800312 private CompressFormat mIconPersistFormat;
313 private int mIconPersistQuality;
Makoto Onuki55046222016-03-08 10:49:47 -0800314
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700315 private int mSaveDelayMillis;
316
Makoto Onuki0acbb142016-03-22 17:02:57 -0700317 private final IPackageManager mIPackageManager;
Makoto Onuki2d5b4652016-03-11 16:09:54 -0800318 private final PackageManagerInternal mPackageManagerInternal;
Sunny Goyal145c8f82018-02-15 14:27:09 -0800319 private final UserManagerInternal mUserManagerInternal;
Makoto Onukiac042502016-05-20 16:39:42 -0700320 private final UsageStatsManagerInternal mUsageStatsManagerInternal;
Makoto Onuki33525d22016-08-03 15:45:24 -0700321 private final ActivityManagerInternal mActivityManagerInternal;
Makoto Onuki2d5b4652016-03-11 16:09:54 -0800322
Makoto Onuki2d895c32016-12-02 15:48:40 -0800323 private final ShortcutRequestPinProcessor mShortcutRequestPinProcessor;
Makoto Onuki475c3652017-05-08 14:29:03 -0700324 private final ShortcutBitmapSaver mShortcutBitmapSaver;
Makoto Onuki50a320e2017-05-31 14:38:42 -0700325 private final ShortcutDumpFiles mShortcutDumpFiles;
Makoto Onuki2d895c32016-12-02 15:48:40 -0800326
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700327 @GuardedBy("mLock")
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700328 final SparseIntArray mUidState = new SparseIntArray();
329
330 @GuardedBy("mLock")
331 final SparseLongArray mUidLastForegroundElapsedTime = new SparseLongArray();
332
333 @GuardedBy("mLock")
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700334 private List<Integer> mDirtyUserIds = new ArrayList<>();
335
Makoto Onukic51b2872016-05-04 15:24:50 -0700336 private final AtomicBoolean mBootCompleted = new AtomicBoolean();
337
Makoto Onuki905e8852016-03-28 10:40:58 -0700338 private static final int PACKAGE_MATCH_FLAGS =
339 PackageManager.MATCH_DIRECT_BOOT_AWARE
Makoto Onukib08790c2016-06-23 14:05:46 -0700340 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE
341 | PackageManager.MATCH_UNINSTALLED_PACKAGES;
Makoto Onuki905e8852016-03-28 10:40:58 -0700342
Makoto Onukie63b04a2017-12-11 14:47:19 -0800343 /**
344 * Note we use a fine-grained lock for {@link #mUnlockedUsers} due to b/64303666.
345 */
346 @GuardedBy("mUnlockedUsers")
Makoto Onuki02f338e2016-07-29 09:40:40 -0700347 final SparseBooleanArray mUnlockedUsers = new SparseBooleanArray();
348
Makoto Onuki2e210c42016-03-30 08:30:36 -0700349 // Stats
350 @VisibleForTesting
351 interface Stats {
352 int GET_DEFAULT_HOME = 0;
353 int GET_PACKAGE_INFO = 1;
354 int GET_PACKAGE_INFO_WITH_SIG = 2;
355 int GET_APPLICATION_INFO = 3;
356 int LAUNCHER_PERMISSION_CHECK = 4;
Makoto Onuki6c1dbd52016-05-02 15:19:32 -0700357 int CLEANUP_DANGLING_BITMAPS = 5;
Makoto Onukib08790c2016-06-23 14:05:46 -0700358 int GET_ACTIVITY_WITH_METADATA = 6;
Makoto Onuki6dd9fb72016-06-01 13:55:54 -0700359 int GET_INSTALLED_PACKAGES = 7;
Makoto Onuki22fcc682016-05-17 14:52:19 -0700360 int CHECK_PACKAGE_CHANGES = 8;
Makoto Onuki157b1622016-06-02 16:13:10 -0700361 int GET_APPLICATION_RESOURCES = 9;
362 int RESOURCE_NAME_LOOKUP = 10;
Makoto Onukib08790c2016-06-23 14:05:46 -0700363 int GET_LAUNCHER_ACTIVITY = 11;
364 int CHECK_LAUNCHER_ACTIVITY = 12;
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700365 int IS_ACTIVITY_ENABLED = 13;
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700366 int PACKAGE_UPDATE_CHECK = 14;
Makoto Onuki085a05c2016-08-19 11:39:29 -0700367 int ASYNC_PRELOAD_USER_DELAY = 15;
Makoto Onuki2d895c32016-12-02 15:48:40 -0800368 int GET_DEFAULT_LAUNCHER = 16;
Makoto Onuki2e210c42016-03-30 08:30:36 -0700369
Makoto Onuki2d895c32016-12-02 15:48:40 -0800370 int COUNT = GET_DEFAULT_LAUNCHER + 1;
Makoto Onuki2e210c42016-03-30 08:30:36 -0700371 }
372
Makoto Onuki84d59342018-02-02 09:22:38 -0800373 private final StatLogger mStatLogger = new StatLogger(new String[] {
Makoto Onuki085a05c2016-08-19 11:39:29 -0700374 "getHomeActivities()",
375 "Launcher permission check",
376 "getPackageInfo()",
377 "getPackageInfo(SIG)",
378 "getApplicationInfo",
379 "cleanupDanglingBitmaps",
380 "getActivity+metadata",
381 "getInstalledPackages",
382 "checkPackageChanges",
383 "getApplicationResources",
384 "resourceNameLookup",
385 "getLauncherActivity",
386 "checkLauncherActivity",
387 "isActivityEnabled",
388 "packageUpdateCheck",
Makoto Onuki2d895c32016-12-02 15:48:40 -0800389 "asyncPreloadUserDelay",
390 "getDefaultLauncher()"
Makoto Onuki84d59342018-02-02 09:22:38 -0800391 });
Makoto Onuki2e210c42016-03-30 08:30:36 -0700392
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700393 private static final int PROCESS_STATE_FOREGROUND_THRESHOLD =
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -0800394 ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700395
Makoto Onuki7001a612016-05-27 13:24:28 -0700396 static final int OPERATION_SET = 0;
397 static final int OPERATION_ADD = 1;
398 static final int OPERATION_UPDATE = 2;
399
400 /** @hide */
401 @IntDef(value = {
402 OPERATION_SET,
403 OPERATION_ADD,
404 OPERATION_UPDATE
Makoto Onukib08790c2016-06-23 14:05:46 -0700405 })
Makoto Onuki7001a612016-05-27 13:24:28 -0700406 @Retention(RetentionPolicy.SOURCE)
Makoto Onukib08790c2016-06-23 14:05:46 -0700407 @interface ShortcutOperation {
408 }
Makoto Onuki7001a612016-05-27 13:24:28 -0700409
Makoto Onukia2241832016-07-06 13:28:37 -0700410 @GuardedBy("mLock")
411 private int mWtfCount = 0;
412
413 @GuardedBy("mLock")
414 private Exception mLastWtfStacktrace;
415
Makoto Onukifc4cf2d2016-08-24 11:10:26 -0700416 static class InvalidFileFormatException extends Exception {
417 public InvalidFileFormatException(String message, Throwable cause) {
418 super(message, cause);
419 }
420 }
421
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800422 public ShortcutService(Context context) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700423 this(context, BackgroundThread.get().getLooper(), /*onyForPackgeManagerApis*/ false);
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700424 }
425
426 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700427 ShortcutService(Context context, Looper looper, boolean onlyForPackageManagerApis) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800428 mContext = Preconditions.checkNotNull(context);
429 LocalServices.addService(ShortcutServiceInternal.class, new LocalService());
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700430 mHandler = new Handler(looper);
Makoto Onuki0acbb142016-03-22 17:02:57 -0700431 mIPackageManager = AppGlobals.getPackageManager();
Makoto Onukiac042502016-05-20 16:39:42 -0700432 mPackageManagerInternal = Preconditions.checkNotNull(
433 LocalServices.getService(PackageManagerInternal.class));
Sunny Goyal145c8f82018-02-15 14:27:09 -0800434 mUserManagerInternal = Preconditions.checkNotNull(
435 LocalServices.getService(UserManagerInternal.class));
Makoto Onukiac042502016-05-20 16:39:42 -0700436 mUsageStatsManagerInternal = Preconditions.checkNotNull(
437 LocalServices.getService(UsageStatsManagerInternal.class));
Makoto Onuki33525d22016-08-03 15:45:24 -0700438 mActivityManagerInternal = Preconditions.checkNotNull(
439 LocalServices.getService(ActivityManagerInternal.class));
Makoto Onukicdc78f72016-03-21 15:47:52 -0700440
Makoto Onuki2d895c32016-12-02 15:48:40 -0800441 mShortcutRequestPinProcessor = new ShortcutRequestPinProcessor(this, mLock);
Makoto Onuki475c3652017-05-08 14:29:03 -0700442 mShortcutBitmapSaver = new ShortcutBitmapSaver(this);
Makoto Onuki50a320e2017-05-31 14:38:42 -0700443 mShortcutDumpFiles = new ShortcutDumpFiles(this);
Makoto Onuki2d895c32016-12-02 15:48:40 -0800444
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700445 if (onlyForPackageManagerApis) {
446 return; // Don't do anything further. For unit tests only.
447 }
448
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700449 // Register receivers.
450
451 // We need to set a priority, so let's just not use PackageMonitor for now.
452 // TODO Refactor PackageMonitor to support priorities.
453 final IntentFilter packageFilter = new IntentFilter();
454 packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
455 packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
456 packageFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
457 packageFilter.addAction(Intent.ACTION_PACKAGE_DATA_CLEARED);
458 packageFilter.addDataScheme("package");
459 packageFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
460 mContext.registerReceiverAsUser(mPackageMonitor, UserHandle.ALL,
461 packageFilter, null, mHandler);
462
Makoto Onuki10305202016-07-14 18:14:08 -0700463 final IntentFilter preferedActivityFilter = new IntentFilter();
464 preferedActivityFilter.addAction(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
465 preferedActivityFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
466 mContext.registerReceiverAsUser(mPackageMonitor, UserHandle.ALL,
467 preferedActivityFilter, null, mHandler);
468
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700469 final IntentFilter localeFilter = new IntentFilter();
470 localeFilter.addAction(Intent.ACTION_LOCALE_CHANGED);
471 localeFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
472 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL,
473 localeFilter, null, mHandler);
Makoto Onukif34c3082016-07-13 10:25:25 -0700474
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700475 injectRegisterUidObserver(mUidObserver, ActivityManager.UID_OBSERVER_PROCSTATE
476 | ActivityManager.UID_OBSERVER_GONE);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800477 }
478
Makoto Onuki84d59342018-02-02 09:22:38 -0800479 long getStatStartTime() {
480 return mStatLogger.getTime();
481 }
482
Makoto Onuki2e210c42016-03-30 08:30:36 -0700483 void logDurationStat(int statId, long start) {
Makoto Onuki84d59342018-02-02 09:22:38 -0800484 mStatLogger.logDurationStat(statId, start);
Makoto Onuki2e210c42016-03-30 08:30:36 -0700485 }
486
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700487 public String injectGetLocaleTagsForUser(@UserIdInt int userId) {
488 // TODO This should get the per-user locale. b/30123329 b/30119489
489 return LocaleList.getDefault().toLanguageTags();
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700490 }
491
492 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Makoto Onukib08790c2016-06-23 14:05:46 -0700493 @Override
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700494 public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onukidc3f6d12017-09-22 17:22:50 -0700495 injectPostToHandler(() -> handleOnUidStateChanged(uid, procState));
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700496 }
497
Makoto Onukib08790c2016-06-23 14:05:46 -0700498 @Override
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700499 public void onUidGone(int uid, boolean disabled) {
Makoto Onukidc3f6d12017-09-22 17:22:50 -0700500 injectPostToHandler(() ->
501 handleOnUidStateChanged(uid, ActivityManager.PROCESS_STATE_NONEXISTENT));
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700502 }
503
Makoto Onukib08790c2016-06-23 14:05:46 -0700504 @Override
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700505 public void onUidActive(int uid) {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700506 }
507
Makoto Onukib08790c2016-06-23 14:05:46 -0700508 @Override
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700509 public void onUidIdle(int uid, boolean disabled) {
510 }
511
512 @Override public void onUidCachedChanged(int uid, boolean cached) {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700513 }
514 };
515
516 void handleOnUidStateChanged(int uid, int procState) {
517 if (DEBUG_PROCSTATE) {
518 Slog.d(TAG, "onUidStateChanged: uid=" + uid + " state=" + procState);
519 }
520 synchronized (mLock) {
521 mUidState.put(uid, procState);
522
523 // We need to keep track of last time an app comes to foreground.
524 // See ShortcutPackage.getApiCallCount() for how it's used.
525 // It doesn't have to be persisted, but it needs to be the elapsed time.
526 if (isProcessStateForeground(procState)) {
527 mUidLastForegroundElapsedTime.put(uid, injectElapsedRealtime());
528 }
529 }
530 }
531
532 private boolean isProcessStateForeground(int processState) {
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800533 return processState <= PROCESS_STATE_FOREGROUND_THRESHOLD;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700534 }
535
Andreas Gampea36dc622018-02-05 17:19:22 -0800536 @GuardedBy("mLock")
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700537 boolean isUidForegroundLocked(int uid) {
538 if (uid == Process.SYSTEM_UID) {
539 // IUidObserver doesn't report the state of SYSTEM, but it always has bound services,
540 // so it's foreground anyway.
541 return true;
542 }
Makoto Onuki33525d22016-08-03 15:45:24 -0700543 // First, check with the local cache.
544 if (isProcessStateForeground(mUidState.get(uid, ActivityManager.MAX_PROCESS_STATE))) {
545 return true;
546 }
547 // If the cache says background, reach out to AM. Since it'll internally need to hold
548 // the AM lock, we use it as a last resort.
549 return isProcessStateForeground(mActivityManagerInternal.getUidProcessState(uid));
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700550 }
551
Andreas Gampea36dc622018-02-05 17:19:22 -0800552 @GuardedBy("mLock")
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700553 long getUidLastForegroundElapsedTimeLocked(int uid) {
554 return mUidLastForegroundElapsedTime.get(uid);
555 }
556
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800557 /**
558 * System service lifecycle.
559 */
560 public static final class Lifecycle extends SystemService {
561 final ShortcutService mService;
562
563 public Lifecycle(Context context) {
564 super(context);
Makoto Onukia4f89b12017-10-05 10:37:55 -0700565 if (DEBUG) {
566 Binder.LOG_RUNTIME_EXCEPTION = true;
567 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800568 mService = new ShortcutService(context);
569 }
570
571 @Override
572 public void onStart() {
573 publishBinderService(Context.SHORTCUT_SERVICE, mService);
574 }
575
576 @Override
577 public void onBootPhase(int phase) {
578 mService.onBootPhase(phase);
579 }
580
581 @Override
Makoto Onuki01ce92b2017-04-28 12:24:16 -0700582 public void onStopUser(int userHandle) {
583 mService.handleStopUser(userHandle);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800584 }
585
586 @Override
Makoto Onukif3a572b2016-03-10 12:28:38 -0800587 public void onUnlockUser(int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -0700588 mService.handleUnlockUser(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800589 }
590 }
591
592 /** lifecycle event */
593 void onBootPhase(int phase) {
594 if (DEBUG) {
595 Slog.d(TAG, "onBootPhase: " + phase);
596 }
597 switch (phase) {
598 case SystemService.PHASE_LOCK_SETTINGS_READY:
599 initialize();
600 break;
Makoto Onukic51b2872016-05-04 15:24:50 -0700601 case SystemService.PHASE_BOOT_COMPLETED:
602 mBootCompleted.set(true);
603 break;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800604 }
605 }
606
607 /** lifecycle event */
Makoto Onukicdc78f72016-03-21 15:47:52 -0700608 void handleUnlockUser(int userId) {
Makoto Onuki22fcc682016-05-17 14:52:19 -0700609 if (DEBUG) {
Makoto Onuki085a05c2016-08-19 11:39:29 -0700610 Slog.d(TAG, "handleUnlockUser: user=" + userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700611 }
Makoto Onukie63b04a2017-12-11 14:47:19 -0800612 synchronized (mUnlockedUsers) {
Makoto Onuki02f338e2016-07-29 09:40:40 -0700613 mUnlockedUsers.put(userId, true);
Makoto Onukicdc78f72016-03-21 15:47:52 -0700614 }
Makoto Onuki085a05c2016-08-19 11:39:29 -0700615
616 // Preload the user data.
617 // Note, we don't use mHandler here but instead just start a new thread.
618 // This is because mHandler (which uses com.android.internal.os.BackgroundThread) is very
619 // busy at this point and this could take hundreds of milliseconds, which would be too
620 // late since the launcher would already have started.
621 // So we just create a new thread. This code runs rarely, so we don't use a thread pool
622 // or anything.
Makoto Onuki84d59342018-02-02 09:22:38 -0800623 final long start = getStatStartTime();
Makoto Onuki085a05c2016-08-19 11:39:29 -0700624 injectRunOnNewThread(() -> {
625 synchronized (mLock) {
626 logDurationStat(Stats.ASYNC_PRELOAD_USER_DELAY, start);
627 getUserShortcutsLocked(userId);
628 }
629 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800630 }
631
632 /** lifecycle event */
Makoto Onuki01ce92b2017-04-28 12:24:16 -0700633 void handleStopUser(int userId) {
Makoto Onuki02f338e2016-07-29 09:40:40 -0700634 if (DEBUG) {
Makoto Onuki01ce92b2017-04-28 12:24:16 -0700635 Slog.d(TAG, "handleStopUser: user=" + userId);
Makoto Onuki02f338e2016-07-29 09:40:40 -0700636 }
Makoto Onukicdc78f72016-03-21 15:47:52 -0700637 synchronized (mLock) {
638 unloadUserLocked(userId);
Makoto Onuki02f338e2016-07-29 09:40:40 -0700639
Makoto Onukie63b04a2017-12-11 14:47:19 -0800640 synchronized (mUnlockedUsers) {
641 mUnlockedUsers.put(userId, false);
642 }
Makoto Onukicdc78f72016-03-21 15:47:52 -0700643 }
644 }
645
Andreas Gampea36dc622018-02-05 17:19:22 -0800646 @GuardedBy("mLock")
Makoto Onukicdc78f72016-03-21 15:47:52 -0700647 private void unloadUserLocked(int userId) {
648 if (DEBUG) {
649 Slog.d(TAG, "unloadUserLocked: user=" + userId);
650 }
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700651 // Save all dirty information.
652 saveDirtyInfo();
653
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800654 // Unload
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -0800655 mUsers.delete(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800656 }
657
658 /** Return the base state file name */
659 private AtomicFile getBaseStateFile() {
660 final File path = new File(injectSystemDataPath(), FILENAME_BASE_STATE);
661 path.mkdirs();
662 return new AtomicFile(path);
663 }
664
665 /**
666 * Init the instance. (load the state file, etc)
667 */
668 private void initialize() {
669 synchronized (mLock) {
Makoto Onuki4362a662016-03-08 18:59:09 -0800670 loadConfigurationLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800671 loadBaseStateLocked();
672 }
673 }
674
Makoto Onuki4362a662016-03-08 18:59:09 -0800675 /**
676 * Load the configuration from Settings.
677 */
678 private void loadConfigurationLocked() {
679 updateConfigurationLocked(injectShortcutManagerConstants());
680 }
Makoto Onuki55046222016-03-08 10:49:47 -0800681
Makoto Onuki4362a662016-03-08 18:59:09 -0800682 /**
683 * Load the configuration from Settings.
684 */
685 @VisibleForTesting
686 boolean updateConfigurationLocked(String config) {
687 boolean result = true;
688
689 final KeyValueListParser parser = new KeyValueListParser(',');
690 try {
691 parser.setString(config);
692 } catch (IllegalArgumentException e) {
693 // Failed to parse the settings string, log this and move on
694 // with defaults.
695 Slog.e(TAG, "Bad shortcut manager settings", e);
696 result = false;
697 }
698
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700699 mSaveDelayMillis = Math.max(0, (int) parser.getLong(ConfigConstants.KEY_SAVE_DELAY_MILLIS,
700 DEFAULT_SAVE_DELAY_MS));
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700701
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700702 mResetInterval = Math.max(1, parser.getLong(
Makoto Onuki4362a662016-03-08 18:59:09 -0800703 ConfigConstants.KEY_RESET_INTERVAL_SEC, DEFAULT_RESET_INTERVAL_SEC)
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700704 * 1000L);
Makoto Onuki4362a662016-03-08 18:59:09 -0800705
Makoto Onukib6d35232016-04-04 15:57:17 -0700706 mMaxUpdatesPerInterval = Math.max(0, (int) parser.getLong(
707 ConfigConstants.KEY_MAX_UPDATES_PER_INTERVAL, DEFAULT_MAX_UPDATES_PER_INTERVAL));
Makoto Onuki4362a662016-03-08 18:59:09 -0800708
Makoto Onukib5a012f2016-06-21 11:13:53 -0700709 mMaxShortcuts = Math.max(0, (int) parser.getLong(
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700710 ConfigConstants.KEY_MAX_SHORTCUTS, DEFAULT_MAX_SHORTCUTS_PER_APP));
Makoto Onuki4362a662016-03-08 18:59:09 -0800711
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700712 final int iconDimensionDp = Math.max(1, injectIsLowRamDevice()
Makoto Onuki4362a662016-03-08 18:59:09 -0800713 ? (int) parser.getLong(
Makoto Onukib08790c2016-06-23 14:05:46 -0700714 ConfigConstants.KEY_MAX_ICON_DIMENSION_DP_LOWRAM,
715 DEFAULT_MAX_ICON_DIMENSION_LOWRAM_DP)
Makoto Onuki4362a662016-03-08 18:59:09 -0800716 : (int) parser.getLong(
Makoto Onukib08790c2016-06-23 14:05:46 -0700717 ConfigConstants.KEY_MAX_ICON_DIMENSION_DP,
718 DEFAULT_MAX_ICON_DIMENSION_DP));
Makoto Onuki4362a662016-03-08 18:59:09 -0800719
720 mMaxIconDimension = injectDipToPixel(iconDimensionDp);
721
722 mIconPersistFormat = CompressFormat.valueOf(
723 parser.getString(ConfigConstants.KEY_ICON_FORMAT, DEFAULT_ICON_PERSIST_FORMAT));
724
725 mIconPersistQuality = (int) parser.getLong(
726 ConfigConstants.KEY_ICON_QUALITY,
727 DEFAULT_ICON_PERSIST_QUALITY);
728
729 return result;
730 }
731
732 @VisibleForTesting
733 String injectShortcutManagerConstants() {
734 return android.provider.Settings.Global.getString(
735 mContext.getContentResolver(),
736 android.provider.Settings.Global.SHORTCUT_MANAGER_CONSTANTS);
737 }
738
739 @VisibleForTesting
740 int injectDipToPixel(int dip) {
741 return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip,
742 mContext.getResources().getDisplayMetrics());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800743 }
744
Makoto Onuki55046222016-03-08 10:49:47 -0800745 // === Persisting ===
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800746
747 @Nullable
Makoto Onuki41066a62016-03-09 16:18:44 -0800748 static String parseStringAttribute(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800749 return parser.getAttributeValue(null, attribute);
750 }
751
Makoto Onuki0acbb142016-03-22 17:02:57 -0700752 static boolean parseBooleanAttribute(XmlPullParser parser, String attribute) {
753 return parseLongAttribute(parser, attribute) == 1;
754 }
755
Makoto Onukia4f89b12017-10-05 10:37:55 -0700756 static boolean parseBooleanAttribute(XmlPullParser parser, String attribute, boolean def) {
757 return parseLongAttribute(parser, attribute, (def ? 1 : 0)) == 1;
758 }
759
Makoto Onuki41066a62016-03-09 16:18:44 -0800760 static int parseIntAttribute(XmlPullParser parser, String attribute) {
761 return (int) parseLongAttribute(parser, attribute);
762 }
763
Makoto Onukid99c6f02016-03-28 11:02:54 -0700764 static int parseIntAttribute(XmlPullParser parser, String attribute, int def) {
765 return (int) parseLongAttribute(parser, attribute, def);
766 }
767
Makoto Onuki41066a62016-03-09 16:18:44 -0800768 static long parseLongAttribute(XmlPullParser parser, String attribute) {
Makoto Onukid99c6f02016-03-28 11:02:54 -0700769 return parseLongAttribute(parser, attribute, 0);
770 }
771
772 static long parseLongAttribute(XmlPullParser parser, String attribute, long def) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800773 final String value = parseStringAttribute(parser, attribute);
774 if (TextUtils.isEmpty(value)) {
Makoto Onukid99c6f02016-03-28 11:02:54 -0700775 return def;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800776 }
777 try {
778 return Long.parseLong(value);
779 } catch (NumberFormatException e) {
780 Slog.e(TAG, "Error parsing long " + value);
Makoto Onukid99c6f02016-03-28 11:02:54 -0700781 return def;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800782 }
783 }
784
785 @Nullable
Makoto Onuki41066a62016-03-09 16:18:44 -0800786 static ComponentName parseComponentNameAttribute(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800787 final String value = parseStringAttribute(parser, attribute);
788 if (TextUtils.isEmpty(value)) {
789 return null;
790 }
791 return ComponentName.unflattenFromString(value);
792 }
793
794 @Nullable
Makoto Onuki440a1ea2016-07-20 14:21:18 -0700795 static Intent parseIntentAttributeNoDefault(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800796 final String value = parseStringAttribute(parser, attribute);
Makoto Onukib5a012f2016-06-21 11:13:53 -0700797 Intent parsed = null;
798 if (!TextUtils.isEmpty(value)) {
799 try {
800 parsed = Intent.parseUri(value, /* flags =*/ 0);
801 } catch (URISyntaxException e) {
802 Slog.e(TAG, "Error parsing intent", e);
803 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800804 }
Makoto Onuki440a1ea2016-07-20 14:21:18 -0700805 return parsed;
806 }
807
808 @Nullable
809 static Intent parseIntentAttribute(XmlPullParser parser, String attribute) {
810 Intent parsed = parseIntentAttributeNoDefault(parser, attribute);
Makoto Onukib5a012f2016-06-21 11:13:53 -0700811 if (parsed == null) {
812 // Default intent.
813 parsed = new Intent(Intent.ACTION_VIEW);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800814 }
Makoto Onukib5a012f2016-06-21 11:13:53 -0700815 return parsed;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800816 }
817
Makoto Onuki41066a62016-03-09 16:18:44 -0800818 static void writeTagValue(XmlSerializer out, String tag, String value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800819 if (TextUtils.isEmpty(value)) return;
820
821 out.startTag(null, tag);
822 out.attribute(null, ATTR_VALUE, value);
823 out.endTag(null, tag);
824 }
825
Makoto Onuki41066a62016-03-09 16:18:44 -0800826 static void writeTagValue(XmlSerializer out, String tag, long value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800827 writeTagValue(out, tag, Long.toString(value));
828 }
829
Makoto Onuki2d5b4652016-03-11 16:09:54 -0800830 static void writeTagValue(XmlSerializer out, String tag, ComponentName name) throws IOException {
831 if (name == null) return;
832 writeTagValue(out, tag, name.flattenToString());
833 }
834
Makoto Onuki41066a62016-03-09 16:18:44 -0800835 static void writeTagExtra(XmlSerializer out, String tag, PersistableBundle bundle)
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800836 throws IOException, XmlPullParserException {
837 if (bundle == null) return;
838
839 out.startTag(null, tag);
840 bundle.saveToXml(out);
841 out.endTag(null, tag);
842 }
843
Makoto Onuki22fcc682016-05-17 14:52:19 -0700844 static void writeAttr(XmlSerializer out, String name, CharSequence value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800845 if (TextUtils.isEmpty(value)) return;
846
Makoto Onuki22fcc682016-05-17 14:52:19 -0700847 out.attribute(null, name, value.toString());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800848 }
849
Makoto Onuki41066a62016-03-09 16:18:44 -0800850 static void writeAttr(XmlSerializer out, String name, long value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800851 writeAttr(out, name, String.valueOf(value));
852 }
853
Makoto Onuki0acbb142016-03-22 17:02:57 -0700854 static void writeAttr(XmlSerializer out, String name, boolean value) throws IOException {
855 if (value) {
856 writeAttr(out, name, "1");
Makoto Onukia4f89b12017-10-05 10:37:55 -0700857 } else {
858 writeAttr(out, name, "0");
Makoto Onuki0acbb142016-03-22 17:02:57 -0700859 }
860 }
861
Makoto Onuki41066a62016-03-09 16:18:44 -0800862 static void writeAttr(XmlSerializer out, String name, ComponentName comp) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800863 if (comp == null) return;
864 writeAttr(out, name, comp.flattenToString());
865 }
866
Makoto Onuki41066a62016-03-09 16:18:44 -0800867 static void writeAttr(XmlSerializer out, String name, Intent intent) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800868 if (intent == null) return;
869
870 writeAttr(out, name, intent.toUri(/* flags =*/ 0));
871 }
872
Andreas Gampea36dc622018-02-05 17:19:22 -0800873 @GuardedBy("mLock")
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800874 @VisibleForTesting
875 void saveBaseStateLocked() {
876 final AtomicFile file = getBaseStateFile();
877 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700878 Slog.d(TAG, "Saving to " + file.getBaseFile());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800879 }
880
881 FileOutputStream outs = null;
882 try {
883 outs = file.startWrite();
884
885 // Write to XML
886 XmlSerializer out = new FastXmlSerializer();
887 out.setOutput(outs, StandardCharsets.UTF_8.name());
888 out.startDocument(null, true);
889 out.startTag(null, TAG_ROOT);
890
891 // Body.
892 writeTagValue(out, TAG_LAST_RESET_TIME, mRawLastResetTime);
893
894 // Epilogue.
895 out.endTag(null, TAG_ROOT);
896 out.endDocument();
897
898 // Close.
899 file.finishWrite(outs);
900 } catch (IOException e) {
901 Slog.e(TAG, "Failed to write to file " + file.getBaseFile(), e);
902 file.failWrite(outs);
903 }
904 }
905
Andreas Gampea36dc622018-02-05 17:19:22 -0800906 @GuardedBy("mLock")
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800907 private void loadBaseStateLocked() {
908 mRawLastResetTime = 0;
909
910 final AtomicFile file = getBaseStateFile();
911 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700912 Slog.d(TAG, "Loading from " + file.getBaseFile());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800913 }
914 try (FileInputStream in = file.openRead()) {
915 XmlPullParser parser = Xml.newPullParser();
916 parser.setInput(in, StandardCharsets.UTF_8.name());
917
918 int type;
919 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
920 if (type != XmlPullParser.START_TAG) {
921 continue;
922 }
923 final int depth = parser.getDepth();
924 // Check the root tag
925 final String tag = parser.getName();
926 if (depth == 1) {
927 if (!TAG_ROOT.equals(tag)) {
928 Slog.e(TAG, "Invalid root tag: " + tag);
929 return;
930 }
931 continue;
932 }
933 // Assume depth == 2
934 switch (tag) {
935 case TAG_LAST_RESET_TIME:
936 mRawLastResetTime = parseLongAttribute(parser, ATTR_VALUE);
937 break;
938 default:
939 Slog.e(TAG, "Invalid tag: " + tag);
940 break;
941 }
942 }
943 } catch (FileNotFoundException e) {
944 // Use the default
Makoto Onukib08790c2016-06-23 14:05:46 -0700945 } catch (IOException | XmlPullParserException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800946 Slog.e(TAG, "Failed to read file " + file.getBaseFile(), e);
947
948 mRawLastResetTime = 0;
949 }
950 // Adjust the last reset time.
951 getLastResetTimeLocked();
952 }
953
Makoto Onuki0eed4412016-07-21 11:21:59 -0700954 @VisibleForTesting
955 final File getUserFile(@UserIdInt int userId) {
956 return new File(injectUserDataPath(userId), FILENAME_USER_PACKAGES);
957 }
958
Andreas Gampea36dc622018-02-05 17:19:22 -0800959 @GuardedBy("mLock")
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800960 private void saveUserLocked(@UserIdInt int userId) {
Makoto Onuki0eed4412016-07-21 11:21:59 -0700961 final File path = getUserFile(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800962 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700963 Slog.d(TAG, "Saving to " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800964 }
Makoto Onuki475c3652017-05-08 14:29:03 -0700965
966 mShortcutBitmapSaver.waitForAllSavesLocked();
967
Makoto Onuki0eed4412016-07-21 11:21:59 -0700968 path.getParentFile().mkdirs();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800969 final AtomicFile file = new AtomicFile(path);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700970 FileOutputStream os = null;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800971 try {
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700972 os = file.startWrite();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800973
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700974 saveUserInternalLocked(userId, os, /* forBackup= */ false);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800975
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700976 file.finishWrite(os);
Makoto Onuki1e173232016-08-10 10:47:13 -0700977
978 // Remove all dangling bitmap files.
979 cleanupDanglingBitmapDirectoriesLocked(userId);
Makoto Onukib08790c2016-06-23 14:05:46 -0700980 } catch (XmlPullParserException | IOException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800981 Slog.e(TAG, "Failed to write to file " + file.getBaseFile(), e);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700982 file.failWrite(os);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800983 }
984 }
985
Andreas Gampea36dc622018-02-05 17:19:22 -0800986 @GuardedBy("mLock")
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700987 private void saveUserInternalLocked(@UserIdInt int userId, OutputStream os,
988 boolean forBackup) throws IOException, XmlPullParserException {
989
990 final BufferedOutputStream bos = new BufferedOutputStream(os);
991
992 // Write to XML
993 XmlSerializer out = new FastXmlSerializer();
994 out.setOutput(bos, StandardCharsets.UTF_8.name());
995 out.startDocument(null, true);
996
Makoto Onukic51b2872016-05-04 15:24:50 -0700997 getUserShortcutsLocked(userId).saveToXml(out, forBackup);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700998
999 out.endDocument();
1000
1001 bos.flush();
1002 os.flush();
1003 }
1004
Makoto Onuki41066a62016-03-09 16:18:44 -08001005 static IOException throwForInvalidTag(int depth, String tag) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001006 throw new IOException(String.format("Invalid tag '%s' found at depth %d", tag, depth));
1007 }
1008
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001009 static void warnForInvalidTag(int depth, String tag) throws IOException {
1010 Slog.w(TAG, String.format("Invalid tag '%s' found at depth %d", tag, depth));
1011 }
1012
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001013 @Nullable
Makoto Onuki31459242016-03-22 11:12:18 -07001014 private ShortcutUser loadUserLocked(@UserIdInt int userId) {
Makoto Onuki0eed4412016-07-21 11:21:59 -07001015 final File path = getUserFile(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001016 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001017 Slog.d(TAG, "Loading from " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001018 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001019 final AtomicFile file = new AtomicFile(path);
1020
1021 final FileInputStream in;
1022 try {
1023 in = file.openRead();
1024 } catch (FileNotFoundException e) {
1025 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001026 Slog.d(TAG, "Not found " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001027 }
1028 return null;
1029 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001030 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07001031 final ShortcutUser ret = loadUserInternal(userId, in, /* forBackup= */ false);
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001032 return ret;
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07001033 } catch (IOException | XmlPullParserException | InvalidFileFormatException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001034 Slog.e(TAG, "Failed to read file " + file.getBaseFile(), e);
1035 return null;
1036 } finally {
1037 IoUtils.closeQuietly(in);
1038 }
1039 }
1040
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001041 private ShortcutUser loadUserInternal(@UserIdInt int userId, InputStream is,
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07001042 boolean fromBackup) throws XmlPullParserException, IOException,
1043 InvalidFileFormatException {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001044
1045 final BufferedInputStream bis = new BufferedInputStream(is);
1046
1047 ShortcutUser ret = null;
1048 XmlPullParser parser = Xml.newPullParser();
1049 parser.setInput(bis, StandardCharsets.UTF_8.name());
1050
1051 int type;
1052 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1053 if (type != XmlPullParser.START_TAG) {
1054 continue;
1055 }
1056 final int depth = parser.getDepth();
1057
1058 final String tag = parser.getName();
1059 if (DEBUG_LOAD) {
1060 Slog.d(TAG, String.format("depth=%d type=%d name=%s",
1061 depth, type, tag));
1062 }
1063 if ((depth == 1) && ShortcutUser.TAG_ROOT.equals(tag)) {
1064 ret = ShortcutUser.loadFromXml(this, parser, userId, fromBackup);
1065 continue;
1066 }
1067 throwForInvalidTag(depth, tag);
1068 }
1069 return ret;
1070 }
1071
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001072 private void scheduleSaveBaseState() {
Makoto Onuki0acbb142016-03-22 17:02:57 -07001073 scheduleSaveInner(UserHandle.USER_NULL); // Special case -- use USER_NULL for base state.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001074 }
1075
Makoto Onuki2d5b4652016-03-11 16:09:54 -08001076 void scheduleSaveUser(@UserIdInt int userId) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07001077 scheduleSaveInner(userId);
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001078 }
1079
1080 // In order to re-schedule, we need to reuse the same instance, so keep it in final.
1081 private final Runnable mSaveDirtyInfoRunner = this::saveDirtyInfo;
1082
Makoto Onuki0acbb142016-03-22 17:02:57 -07001083 private void scheduleSaveInner(@UserIdInt int userId) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001084 if (DEBUG) {
1085 Slog.d(TAG, "Scheduling to save for " + userId);
1086 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001087 synchronized (mLock) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001088 if (!mDirtyUserIds.contains(userId)) {
1089 mDirtyUserIds.add(userId);
1090 }
1091 }
1092 // If already scheduled, remove that and re-schedule in N seconds.
1093 mHandler.removeCallbacks(mSaveDirtyInfoRunner);
1094 mHandler.postDelayed(mSaveDirtyInfoRunner, mSaveDelayMillis);
1095 }
1096
1097 @VisibleForTesting
1098 void saveDirtyInfo() {
1099 if (DEBUG) {
1100 Slog.d(TAG, "saveDirtyInfo");
1101 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001102 try {
1103 synchronized (mLock) {
1104 for (int i = mDirtyUserIds.size() - 1; i >= 0; i--) {
1105 final int userId = mDirtyUserIds.get(i);
1106 if (userId == UserHandle.USER_NULL) { // USER_NULL for base state.
1107 saveBaseStateLocked();
1108 } else {
1109 saveUserLocked(userId);
1110 }
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001111 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001112 mDirtyUserIds.clear();
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001113 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001114 } catch (Exception e) {
1115 wtf("Exception in saveDirtyInfo", e);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001116 }
1117 }
1118
1119 /** Return the last reset time. */
Andreas Gampea36dc622018-02-05 17:19:22 -08001120 @GuardedBy("mLock")
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001121 long getLastResetTimeLocked() {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001122 updateTimesLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001123 return mRawLastResetTime;
1124 }
1125
1126 /** Return the next reset time. */
Andreas Gampea36dc622018-02-05 17:19:22 -08001127 @GuardedBy("mLock")
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001128 long getNextResetTimeLocked() {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001129 updateTimesLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001130 return mRawLastResetTime + mResetInterval;
1131 }
1132
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001133 static boolean isClockValid(long time) {
1134 return time >= 1420070400; // Thu, 01 Jan 2015 00:00:00 GMT
1135 }
1136
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001137 /**
1138 * Update the last reset time.
1139 */
Andreas Gampea36dc622018-02-05 17:19:22 -08001140 @GuardedBy("mLock")
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001141 private void updateTimesLocked() {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001142
1143 final long now = injectCurrentTimeMillis();
1144
1145 final long prevLastResetTime = mRawLastResetTime;
1146
1147 if (mRawLastResetTime == 0) { // first launch.
1148 // TODO Randomize??
1149 mRawLastResetTime = now;
1150 } else if (now < mRawLastResetTime) {
1151 // Clock rewound.
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001152 if (isClockValid(now)) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001153 Slog.w(TAG, "Clock rewound");
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001154 // TODO Randomize??
1155 mRawLastResetTime = now;
1156 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001157 } else {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001158 if ((mRawLastResetTime + mResetInterval) <= now) {
1159 final long offset = mRawLastResetTime % mResetInterval;
1160 mRawLastResetTime = ((now / mResetInterval) * mResetInterval) + offset;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001161 }
1162 }
1163 if (prevLastResetTime != mRawLastResetTime) {
1164 scheduleSaveBaseState();
1165 }
1166 }
1167
Makoto Onuki1e173232016-08-10 10:47:13 -07001168 // Requires mLock held, but "Locked" prefix would look weired so we just say "L".
Makoto Onuki02f338e2016-07-29 09:40:40 -07001169 protected boolean isUserUnlockedL(@UserIdInt int userId) {
Makoto Onuki1e173232016-08-10 10:47:13 -07001170 // First, check the local copy.
Makoto Onukie63b04a2017-12-11 14:47:19 -08001171 synchronized (mUnlockedUsers) {
1172 if (mUnlockedUsers.get(userId)) {
1173 return true;
1174 }
Makoto Onuki1e173232016-08-10 10:47:13 -07001175 }
Mehdi Alizadeh32774622018-11-05 17:32:01 -08001176
Makoto Onuki1e173232016-08-10 10:47:13 -07001177 // If the local copy says the user is locked, check with AM for the actual state, since
1178 // the user might just have been unlocked.
1179 // Note we just don't use isUserUnlockingOrUnlocked() here, because it'll return false
1180 // when the user is STOPPING, which we still want to consider as "unlocked".
Sunny Goyal145c8f82018-02-15 14:27:09 -08001181 return mUserManagerInternal.isUserUnlockingOrUnlocked(userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07001182 }
1183
Makoto Onuki02f338e2016-07-29 09:40:40 -07001184 // Requires mLock held, but "Locked" prefix would look weired so we jsut say "L".
1185 void throwIfUserLockedL(@UserIdInt int userId) {
1186 if (!isUserUnlockedL(userId)) {
Makoto Onuki9c850012016-07-26 15:50:50 -07001187 throw new IllegalStateException("User " + userId + " is locked or not running");
1188 }
1189 }
1190
Makoto Onukicdc78f72016-03-21 15:47:52 -07001191 @GuardedBy("mLock")
1192 @NonNull
Makoto Onuki2e210c42016-03-30 08:30:36 -07001193 private boolean isUserLoadedLocked(@UserIdInt int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07001194 return mUsers.get(userId) != null;
1195 }
1196
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001197 /** Return the per-user state. */
1198 @GuardedBy("mLock")
1199 @NonNull
Makoto Onuki31459242016-03-22 11:12:18 -07001200 ShortcutUser getUserShortcutsLocked(@UserIdInt int userId) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001201 if (!isUserUnlockedL(userId)) {
Makoto Onuki9c850012016-07-26 15:50:50 -07001202 wtf("User still locked");
Makoto Onuki9c850012016-07-26 15:50:50 -07001203 }
1204
Makoto Onuki31459242016-03-22 11:12:18 -07001205 ShortcutUser userPackages = mUsers.get(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001206 if (userPackages == null) {
1207 userPackages = loadUserLocked(userId);
1208 if (userPackages == null) {
Makoto Onukic51b2872016-05-04 15:24:50 -07001209 userPackages = new ShortcutUser(this, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001210 }
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08001211 mUsers.put(userId, userPackages);
Makoto Onuki085a05c2016-08-19 11:39:29 -07001212
1213 // Also when a user's data is first accessed, scan all packages.
1214 checkPackageChanges(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001215 }
1216 return userPackages;
1217 }
1218
Makoto Onuki708703b2017-12-11 16:38:11 -08001219 /** Return the non-persistent per-user state. */
1220 @GuardedBy("mLock")
1221 @NonNull
1222 ShortcutNonPersistentUser getNonPersistentUserLocked(@UserIdInt int userId) {
1223 ShortcutNonPersistentUser ret = mShortcutNonPersistentUsers.get(userId);
1224 if (ret == null) {
1225 ret = new ShortcutNonPersistentUser(this, userId);
1226 mShortcutNonPersistentUsers.put(userId, ret);
1227 }
1228 return ret;
1229 }
1230
Andreas Gampea36dc622018-02-05 17:19:22 -08001231 @GuardedBy("mLock")
Makoto Onuki2e210c42016-03-30 08:30:36 -07001232 void forEachLoadedUserLocked(@NonNull Consumer<ShortcutUser> c) {
1233 for (int i = mUsers.size() - 1; i >= 0; i--) {
1234 c.accept(mUsers.valueAt(i));
1235 }
1236 }
1237
Makoto Onukic8c33292016-09-12 16:36:59 -07001238 /**
1239 * Return the per-user per-package state. If the caller is a publisher, use
1240 * {@link #getPackageShortcutsForPublisherLocked} instead.
1241 */
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001242 @GuardedBy("mLock")
1243 @NonNull
Makoto Onuki31459242016-03-22 11:12:18 -07001244 ShortcutPackage getPackageShortcutsLocked(
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001245 @NonNull String packageName, @UserIdInt int userId) {
Makoto Onukic51b2872016-05-04 15:24:50 -07001246 return getUserShortcutsLocked(userId).getPackageShortcuts(packageName);
Makoto Onukide667372016-03-15 14:29:20 -07001247 }
1248
Makoto Onukic8c33292016-09-12 16:36:59 -07001249 /** Return the per-user per-package state. Use this when the caller is a publisher. */
1250 @GuardedBy("mLock")
1251 @NonNull
1252 ShortcutPackage getPackageShortcutsForPublisherLocked(
1253 @NonNull String packageName, @UserIdInt int userId) {
1254 final ShortcutPackage ret = getUserShortcutsLocked(userId).getPackageShortcuts(packageName);
1255 ret.getUser().onCalledByPublisher(packageName);
1256 return ret;
1257 }
1258
Makoto Onukide667372016-03-15 14:29:20 -07001259 @GuardedBy("mLock")
1260 @NonNull
Makoto Onuki2e210c42016-03-30 08:30:36 -07001261 ShortcutLauncher getLauncherShortcutsLocked(
1262 @NonNull String packageName, @UserIdInt int ownerUserId,
1263 @UserIdInt int launcherUserId) {
1264 return getUserShortcutsLocked(ownerUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07001265 .getLauncherShortcuts(packageName, launcherUserId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001266 }
1267
1268 // === Caller validation ===
1269
Makoto Onuki475c3652017-05-08 14:29:03 -07001270 void removeIconLocked(ShortcutInfo shortcut) {
1271 mShortcutBitmapSaver.removeIcon(shortcut);
Makoto Onuki55046222016-03-08 10:49:47 -08001272 }
1273
Makoto Onuki0033b2a2016-04-14 17:19:16 -07001274 public void cleanupBitmapsForPackage(@UserIdInt int userId, String packageName) {
1275 final File packagePath = new File(getUserBitmapFilePath(userId), packageName);
1276 if (!packagePath.isDirectory()) {
1277 return;
1278 }
1279 if (!(FileUtils.deleteContents(packagePath) && packagePath.delete())) {
1280 Slog.w(TAG, "Unable to remove directory " + packagePath);
1281 }
1282 }
1283
Makoto Onuki475c3652017-05-08 14:29:03 -07001284 /**
1285 * Remove dangling bitmap files for a user.
1286 *
1287 * Note this method must be called with the lock held after calling
1288 * {@link ShortcutBitmapSaver#waitForAllSavesLocked()} to make sure there's no pending bitmap
1289 * saves are going on.
1290 */
Andreas Gampea36dc622018-02-05 17:19:22 -08001291 @GuardedBy("mLock")
Makoto Onuki1e173232016-08-10 10:47:13 -07001292 private void cleanupDanglingBitmapDirectoriesLocked(@UserIdInt int userId) {
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001293 if (DEBUG) {
1294 Slog.d(TAG, "cleanupDanglingBitmaps: userId=" + userId);
1295 }
Makoto Onuki84d59342018-02-02 09:22:38 -08001296 final long start = getStatStartTime();
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001297
Makoto Onuki1e173232016-08-10 10:47:13 -07001298 final ShortcutUser user = getUserShortcutsLocked(userId);
1299
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001300 final File bitmapDir = getUserBitmapFilePath(userId);
1301 final File[] children = bitmapDir.listFiles();
1302 if (children == null) {
1303 return;
1304 }
1305 for (File child : children) {
1306 if (!child.isDirectory()) {
1307 continue;
1308 }
1309 final String packageName = child.getName();
1310 if (DEBUG) {
1311 Slog.d(TAG, "cleanupDanglingBitmaps: Found directory=" + packageName);
1312 }
1313 if (!user.hasPackage(packageName)) {
1314 if (DEBUG) {
1315 Slog.d(TAG, "Removing dangling bitmap directory: " + packageName);
1316 }
1317 cleanupBitmapsForPackage(userId, packageName);
1318 } else {
1319 cleanupDanglingBitmapFilesLocked(userId, user, packageName, child);
1320 }
1321 }
1322 logDurationStat(Stats.CLEANUP_DANGLING_BITMAPS, start);
1323 }
1324
Makoto Onuki475c3652017-05-08 14:29:03 -07001325 /**
1326 * Remove dangling bitmap files for a package.
1327 *
1328 * Note this method must be called with the lock held after calling
1329 * {@link ShortcutBitmapSaver#waitForAllSavesLocked()} to make sure there's no pending bitmap
1330 * saves are going on.
1331 */
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001332 private void cleanupDanglingBitmapFilesLocked(@UserIdInt int userId, @NonNull ShortcutUser user,
1333 @NonNull String packageName, @NonNull File path) {
1334 final ArraySet<String> usedFiles =
Makoto Onukic51b2872016-05-04 15:24:50 -07001335 user.getPackageShortcuts(packageName).getUsedBitmapFiles();
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001336
1337 for (File child : path.listFiles()) {
1338 if (!child.isFile()) {
1339 continue;
1340 }
1341 final String name = child.getName();
1342 if (!usedFiles.contains(name)) {
1343 if (DEBUG) {
1344 Slog.d(TAG, "Removing dangling bitmap file: " + child.getAbsolutePath());
1345 }
1346 child.delete();
1347 }
1348 }
1349 }
1350
Makoto Onuki55046222016-03-08 10:49:47 -08001351 @VisibleForTesting
1352 static class FileOutputStreamWithPath extends FileOutputStream {
1353 private final File mFile;
1354
1355 public FileOutputStreamWithPath(File file) throws FileNotFoundException {
1356 super(file);
1357 mFile = file;
1358 }
1359
1360 public File getFile() {
1361 return mFile;
1362 }
1363 }
1364
1365 /**
1366 * Build the cached bitmap filename for a shortcut icon.
1367 *
1368 * The filename will be based on the ID, except certain characters will be escaped.
1369 */
Makoto Onuki55046222016-03-08 10:49:47 -08001370 FileOutputStreamWithPath openIconFileForWrite(@UserIdInt int userId, ShortcutInfo shortcut)
1371 throws IOException {
1372 final File packagePath = new File(getUserBitmapFilePath(userId),
Makoto Onuki22fcc682016-05-17 14:52:19 -07001373 shortcut.getPackage());
Makoto Onuki55046222016-03-08 10:49:47 -08001374 if (!packagePath.isDirectory()) {
1375 packagePath.mkdirs();
1376 if (!packagePath.isDirectory()) {
1377 throw new IOException("Unable to create directory " + packagePath);
1378 }
1379 SELinux.restorecon(packagePath);
1380 }
1381
1382 final String baseName = String.valueOf(injectCurrentTimeMillis());
Makoto Onukib08790c2016-06-23 14:05:46 -07001383 for (int suffix = 0; ; suffix++) {
Makoto Onuki55046222016-03-08 10:49:47 -08001384 final String filename = (suffix == 0 ? baseName : baseName + "_" + suffix) + ".png";
1385 final File file = new File(packagePath, filename);
1386 if (!file.exists()) {
1387 if (DEBUG) {
1388 Slog.d(TAG, "Saving icon to " + file.getAbsolutePath());
1389 }
1390 return new FileOutputStreamWithPath(file);
1391 }
1392 }
1393 }
1394
Makoto Onuki475c3652017-05-08 14:29:03 -07001395 void saveIconAndFixUpShortcutLocked(ShortcutInfo shortcut) {
Makoto Onuki55046222016-03-08 10:49:47 -08001396 if (shortcut.hasIconFile() || shortcut.hasIconResource()) {
1397 return;
1398 }
1399
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001400 final long token = injectClearCallingIdentity();
Makoto Onuki55046222016-03-08 10:49:47 -08001401 try {
1402 // Clear icon info on the shortcut.
Makoto Onuki475c3652017-05-08 14:29:03 -07001403 removeIconLocked(shortcut);
Makoto Onuki55046222016-03-08 10:49:47 -08001404
1405 final Icon icon = shortcut.getIcon();
1406 if (icon == null) {
1407 return; // has no icon
1408 }
Hyunyoung Song47037462017-05-08 16:51:43 -07001409 int maxIconDimension = mMaxIconDimension;
Makoto Onukiabe84422016-04-07 09:41:19 -07001410 Bitmap bitmap;
Makoto Onuki55046222016-03-08 10:49:47 -08001411 try {
1412 switch (icon.getType()) {
1413 case Icon.TYPE_RESOURCE: {
1414 injectValidateIconResPackage(shortcut, icon);
1415
1416 shortcut.setIconResourceId(icon.getResId());
1417 shortcut.addFlags(ShortcutInfo.FLAG_HAS_ICON_RES);
1418 return;
1419 }
Hyunyoung Songf281e7a2017-02-13 10:57:42 -08001420 case Icon.TYPE_BITMAP:
Makoto Onukiabe84422016-04-07 09:41:19 -07001421 bitmap = icon.getBitmap(); // Don't recycle in this case.
Makoto Onuki55046222016-03-08 10:49:47 -08001422 break;
Hyunyoung Song47037462017-05-08 16:51:43 -07001423 case Icon.TYPE_ADAPTIVE_BITMAP: {
1424 bitmap = icon.getBitmap(); // Don't recycle in this case.
1425 maxIconDimension *= (1 + 2 * AdaptiveIconDrawable.getExtraInsetFraction());
Hyunyoung Song8947f592017-05-15 10:12:11 -07001426 break;
Makoto Onuki55046222016-03-08 10:49:47 -08001427 }
Makoto Onuki55046222016-03-08 10:49:47 -08001428 default:
1429 // This shouldn't happen because we've already validated the icon, but
1430 // just in case.
1431 throw ShortcutInfo.getInvalidIconException();
1432 }
Makoto Onuki475c3652017-05-08 14:29:03 -07001433 mShortcutBitmapSaver.saveBitmapLocked(shortcut,
Hyunyoung Song47037462017-05-08 16:51:43 -07001434 maxIconDimension, mIconPersistFormat, mIconPersistQuality);
Makoto Onuki55046222016-03-08 10:49:47 -08001435 } finally {
Makoto Onuki55046222016-03-08 10:49:47 -08001436 // Once saved, we won't use the original icon information, so null it out.
1437 shortcut.clearIcon();
1438 }
1439 } finally {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001440 injectRestoreCallingIdentity(token);
Makoto Onuki55046222016-03-08 10:49:47 -08001441 }
1442 }
1443
1444 // Unfortunately we can't do this check in unit tests because we fake creator package names,
1445 // so override in unit tests.
1446 // TODO CTS this case.
1447 void injectValidateIconResPackage(ShortcutInfo shortcut, Icon icon) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07001448 if (!shortcut.getPackage().equals(icon.getResPackage())) {
Makoto Onuki55046222016-03-08 10:49:47 -08001449 throw new IllegalArgumentException(
1450 "Icon resource must reside in shortcut owner package");
1451 }
1452 }
1453
Makoto Onuki55046222016-03-08 10:49:47 -08001454 static Bitmap shrinkBitmap(Bitmap in, int maxSize) {
1455 // Original width/height.
1456 final int ow = in.getWidth();
1457 final int oh = in.getHeight();
1458 if ((ow <= maxSize) && (oh <= maxSize)) {
1459 if (DEBUG) {
1460 Slog.d(TAG, String.format("Icon size %dx%d, no need to shrink", ow, oh));
1461 }
1462 return in;
1463 }
1464 final int longerDimension = Math.max(ow, oh);
1465
1466 // New width and height.
1467 final int nw = ow * maxSize / longerDimension;
1468 final int nh = oh * maxSize / longerDimension;
1469 if (DEBUG) {
1470 Slog.d(TAG, String.format("Icon size %dx%d, shrinking to %dx%d",
1471 ow, oh, nw, nh));
1472 }
1473
1474 final Bitmap scaledBitmap = Bitmap.createBitmap(nw, nh, Bitmap.Config.ARGB_8888);
1475 final Canvas c = new Canvas(scaledBitmap);
1476
1477 final RectF dst = new RectF(0, 0, nw, nh);
1478
1479 c.drawBitmap(in, /*src=*/ null, dst, /* paint =*/ null);
1480
Makoto Onuki55046222016-03-08 10:49:47 -08001481 return scaledBitmap;
1482 }
1483
Makoto Onuki157b1622016-06-02 16:13:10 -07001484 /**
1485 * For a shortcut, update all resource names from resource IDs, and also update all
1486 * resource-based strings.
1487 */
1488 void fixUpShortcutResourceNamesAndValues(ShortcutInfo si) {
1489 final Resources publisherRes = injectGetResourcesForApplicationAsUser(
1490 si.getPackage(), si.getUserId());
1491 if (publisherRes != null) {
Makoto Onuki84d59342018-02-02 09:22:38 -08001492 final long start = getStatStartTime();
Makoto Onuki157b1622016-06-02 16:13:10 -07001493 try {
1494 si.lookupAndFillInResourceNames(publisherRes);
1495 } finally {
1496 logDurationStat(Stats.RESOURCE_NAME_LOOKUP, start);
1497 }
1498 si.resolveResourceStrings(publisherRes);
1499 }
1500 }
1501
Makoto Onuki55046222016-03-08 10:49:47 -08001502 // === Caller validation ===
1503
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001504 private boolean isCallerSystem() {
1505 final int callingUid = injectBinderCallingUid();
Makoto Onukib08790c2016-06-23 14:05:46 -07001506 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001507 }
1508
1509 private boolean isCallerShell() {
1510 final int callingUid = injectBinderCallingUid();
1511 return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
1512 }
1513
1514 private void enforceSystemOrShell() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001515 if (!(isCallerSystem() || isCallerShell())) {
1516 throw new SecurityException("Caller must be system or shell");
1517 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001518 }
1519
1520 private void enforceShell() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001521 if (!isCallerShell()) {
1522 throw new SecurityException("Caller must be shell");
1523 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001524 }
1525
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001526 private void enforceSystem() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001527 if (!isCallerSystem()) {
1528 throw new SecurityException("Caller must be system");
1529 }
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001530 }
1531
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001532 private void enforceResetThrottlingPermission() {
1533 if (isCallerSystem()) {
1534 return;
1535 }
Makoto Onuki76269922016-07-15 14:58:54 -07001536 enforceCallingOrSelfPermission(
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001537 android.Manifest.permission.RESET_SHORTCUT_MANAGER_THROTTLING, null);
1538 }
1539
Makoto Onuki76269922016-07-15 14:58:54 -07001540 private void enforceCallingOrSelfPermission(
1541 @NonNull String permission, @Nullable String message) {
1542 if (isCallerSystem()) {
1543 return;
1544 }
1545 injectEnforceCallingPermission(permission, message);
1546 }
1547
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001548 /**
1549 * Somehow overriding ServiceContext.enforceCallingPermission() in the unit tests would confuse
1550 * mockito. So instead we extracted it here and override it in the tests.
1551 */
1552 @VisibleForTesting
1553 void injectEnforceCallingPermission(
1554 @NonNull String permission, @Nullable String message) {
1555 mContext.enforceCallingPermission(permission, message);
1556 }
1557
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001558 private void verifyCaller(@NonNull String packageName, @UserIdInt int userId) {
1559 Preconditions.checkStringNotEmpty(packageName, "packageName");
1560
1561 if (isCallerSystem()) {
1562 return; // no check
1563 }
1564
1565 final int callingUid = injectBinderCallingUid();
1566
1567 // Otherwise, make sure the arguments are valid.
1568 if (UserHandle.getUserId(callingUid) != userId) {
1569 throw new SecurityException("Invalid user-ID");
1570 }
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08001571 if (injectGetPackageUid(packageName, userId) != callingUid) {
1572 throw new SecurityException("Calling package name mismatch");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001573 }
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08001574 Preconditions.checkState(!isEphemeralApp(packageName, userId),
1575 "Ephemeral apps can't use ShortcutManager");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001576 }
1577
Makoto Onukia19fb232018-06-12 13:01:42 -07001578 private void verifyShortcutInfoPackage(String callerPackage, ShortcutInfo si) {
1579 if (si == null) {
1580 return;
1581 }
1582 if (!Objects.equals(callerPackage, si.getPackage())) {
1583 android.util.EventLog.writeEvent(0x534e4554, "109824443", -1, "");
1584 throw new SecurityException("Shortcut package name mismatch");
1585 }
1586 }
1587
1588 private void verifyShortcutInfoPackages(
1589 String callerPackage, List<ShortcutInfo> list) {
1590 final int size = list.size();
1591 for (int i = 0; i < size; i++) {
1592 verifyShortcutInfoPackage(callerPackage, list.get(i));
1593 }
1594 }
1595
Makoto Onuki157b1622016-06-02 16:13:10 -07001596 // Overridden in unit tests to execute r synchronously.
1597 void injectPostToHandler(Runnable r) {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001598 mHandler.post(r);
1599 }
1600
Makoto Onuki085a05c2016-08-19 11:39:29 -07001601 void injectRunOnNewThread(Runnable r) {
1602 new Thread(r).start();
1603 }
1604
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001605 /**
Makoto Onuki7001a612016-05-27 13:24:28 -07001606 * @throws IllegalArgumentException if {@code numShortcuts} is bigger than
Makoto Onukib08790c2016-06-23 14:05:46 -07001607 * {@link #getMaxActivityShortcuts()}.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001608 */
Makoto Onuki7001a612016-05-27 13:24:28 -07001609 void enforceMaxActivityShortcuts(int numShortcuts) {
Makoto Onukib5a012f2016-06-21 11:13:53 -07001610 if (numShortcuts > mMaxShortcuts) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001611 throw new IllegalArgumentException("Max number of dynamic shortcuts exceeded");
1612 }
1613 }
1614
1615 /**
Makoto Onuki7001a612016-05-27 13:24:28 -07001616 * Return the max number of dynamic + manifest shortcuts for each launcher icon.
1617 */
1618 int getMaxActivityShortcuts() {
Makoto Onukib5a012f2016-06-21 11:13:53 -07001619 return mMaxShortcuts;
Makoto Onuki7001a612016-05-27 13:24:28 -07001620 }
1621
1622 /**
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001623 * - Sends a notification to LauncherApps
1624 * - Write to file
1625 */
Makoto Onuki39686e82016-04-13 18:03:00 -07001626 void packageShortcutsChanged(@NonNull String packageName, @UserIdInt int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001627 notifyListeners(packageName, userId);
1628 scheduleSaveUser(userId);
1629 }
1630
1631 private void notifyListeners(@NonNull String packageName, @UserIdInt int userId) {
Makoto Onuki82fb2eb2017-03-31 16:58:26 -07001632 if (DEBUG) {
1633 Slog.d(TAG, String.format(
1634 "Shortcut changes: package=%s, user=%d", packageName, userId));
1635 }
Makoto Onuki157b1622016-06-02 16:13:10 -07001636 injectPostToHandler(() -> {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001637 try {
1638 final ArrayList<ShortcutChangeListener> copy;
1639 synchronized (mLock) {
1640 if (!isUserUnlockedL(userId)) {
1641 return;
1642 }
1643
1644 copy = new ArrayList<>(mListeners);
1645 }
1646 // Note onShortcutChanged() needs to be called with the system service permissions.
1647 for (int i = copy.size() - 1; i >= 0; i--) {
1648 copy.get(i).onShortcutChanged(packageName, userId);
1649 }
1650 } catch (Exception ignore) {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001651 }
1652 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001653 }
1654
1655 /**
1656 * Clean up / validate an incoming shortcut.
1657 * - Make sure all mandatory fields are set.
1658 * - Make sure the intent's extras are persistable, and them to set
Makoto Onuki0eed4412016-07-21 11:21:59 -07001659 * {@link ShortcutInfo#mIntentPersistableExtrases}. Also clear its extras.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001660 * - Clear flags.
1661 */
Makoto Onuki2d895c32016-12-02 15:48:40 -08001662 private void fixUpIncomingShortcutInfo(@NonNull ShortcutInfo shortcut, boolean forUpdate,
1663 boolean forPinRequest) {
Makoto Onukibf563b62017-05-04 10:25:30 -07001664 if (shortcut.isReturnedByServer()) {
1665 Log.w(TAG,
1666 "Re-publishing ShortcutInfo returned by server is not supported."
1667 + " Some information such as icon may lost from shortcut.");
1668 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001669 Preconditions.checkNotNull(shortcut, "Null shortcut detected");
Makoto Onuki255461f2017-01-10 11:47:25 -08001670 if (shortcut.getActivity() != null) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001671 Preconditions.checkState(
Makoto Onuki22fcc682016-05-17 14:52:19 -07001672 shortcut.getPackage().equals(shortcut.getActivity().getPackageName()),
Makoto Onukib08790c2016-06-23 14:05:46 -07001673 "Cannot publish shortcut: activity " + shortcut.getActivity() + " does not"
1674 + " belong to package " + shortcut.getPackage());
Makoto Onuki13260b6ff2016-07-13 18:03:13 -07001675 Preconditions.checkState(
1676 injectIsMainActivity(shortcut.getActivity(), shortcut.getUserId()),
1677 "Cannot publish shortcut: activity " + shortcut.getActivity() + " is not"
1678 + " main activity");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001679 }
1680
Makoto Onuki55046222016-03-08 10:49:47 -08001681 if (!forUpdate) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08001682 shortcut.enforceMandatoryFields(/* forPinned= */ forPinRequest);
1683 if (!forPinRequest) {
Makoto Onuki255461f2017-01-10 11:47:25 -08001684 Preconditions.checkState(shortcut.getActivity() != null,
1685 "Cannot publish shortcut: target activity is not set");
Makoto Onuki2d895c32016-12-02 15:48:40 -08001686 }
Makoto Onuki55046222016-03-08 10:49:47 -08001687 }
1688 if (shortcut.getIcon() != null) {
1689 ShortcutInfo.validateIcon(shortcut.getIcon());
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001690 }
1691
Makoto Onukide667372016-03-15 14:29:20 -07001692 shortcut.replaceFlags(0);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001693 }
1694
Makoto Onuki2d895c32016-12-02 15:48:40 -08001695 private void fixUpIncomingShortcutInfo(@NonNull ShortcutInfo shortcut, boolean forUpdate) {
1696 fixUpIncomingShortcutInfo(shortcut, forUpdate, /*forPinRequest=*/ false);
1697 }
1698
1699 public void validateShortcutForPinRequest(@NonNull ShortcutInfo shortcut) {
1700 fixUpIncomingShortcutInfo(shortcut, /* forUpdate= */ false, /*forPinRequest=*/ true);
1701 }
1702
Makoto Onukib08790c2016-06-23 14:05:46 -07001703 /**
1704 * When a shortcut has no target activity, set the default one from the package.
1705 */
1706 private void fillInDefaultActivity(List<ShortcutInfo> shortcuts) {
Makoto Onukib08790c2016-06-23 14:05:46 -07001707 ComponentName defaultActivity = null;
1708 for (int i = shortcuts.size() - 1; i >= 0; i--) {
1709 final ShortcutInfo si = shortcuts.get(i);
1710 if (si.getActivity() == null) {
1711 if (defaultActivity == null) {
1712 defaultActivity = injectGetDefaultMainActivity(
1713 si.getPackage(), si.getUserId());
1714 Preconditions.checkState(defaultActivity != null,
1715 "Launcher activity not found for package " + si.getPackage());
1716 }
1717 si.setActivity(defaultActivity);
1718 }
1719 }
1720 }
1721
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001722 private void assignImplicitRanks(List<ShortcutInfo> shortcuts) {
1723 for (int i = shortcuts.size() - 1; i >= 0; i--) {
1724 shortcuts.get(i).setImplicitRank(i);
1725 }
1726 }
1727
Makoto Onukibf563b62017-05-04 10:25:30 -07001728 private List<ShortcutInfo> setReturnedByServer(List<ShortcutInfo> shortcuts) {
1729 for (int i = shortcuts.size() - 1; i >= 0; i--) {
1730 shortcuts.get(i).setReturnedByServer();
1731 }
1732 return shortcuts;
1733 }
1734
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001735 // === APIs ===
1736
1737 @Override
1738 public boolean setDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1739 @UserIdInt int userId) {
1740 verifyCaller(packageName, userId);
1741
1742 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
Makoto Onukia19fb232018-06-12 13:01:42 -07001743 verifyShortcutInfoPackages(packageName, newShortcuts);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001744 final int size = newShortcuts.size();
1745
Makoto Onuki7d0fa812018-02-21 11:24:43 -08001746 final boolean unlimited = injectHasUnlimitedShortcutsApiCallsPermission(
1747 injectBinderCallingPid(), injectBinderCallingUid());
1748
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001749 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001750 throwIfUserLockedL(userId);
1751
Makoto Onukic8c33292016-09-12 16:36:59 -07001752 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001753
Makoto Onukia4f89b12017-10-05 10:37:55 -07001754 ps.ensureImmutableShortcutsNotIncluded(newShortcuts, /*ignoreInvisible=*/ true);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001755
Makoto Onukib08790c2016-06-23 14:05:46 -07001756 fillInDefaultActivity(newShortcuts);
1757
Makoto Onuki7001a612016-05-27 13:24:28 -07001758 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_SET);
1759
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001760 // Throttling.
Makoto Onuki7d0fa812018-02-21 11:24:43 -08001761 if (!ps.tryApiCall(unlimited)) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001762 return false;
1763 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001764
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001765 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1766 ps.clearAllImplicitRanks();
1767 assignImplicitRanks(newShortcuts);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001768
Makoto Onukidf6da042016-06-16 09:51:40 -07001769 for (int i = 0; i < size; i++) {
1770 fixUpIncomingShortcutInfo(newShortcuts.get(i), /* forUpdate= */ false);
1771 }
1772
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001773 // First, remove all un-pinned; dynamic shortcuts
Makoto Onukia4f89b12017-10-05 10:37:55 -07001774 ps.deleteAllDynamicShortcuts(/*ignoreInvisible=*/ true);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001775
1776 // Then, add/update all. We need to make sure to take over "pinned" flag.
1777 for (int i = 0; i < size; i++) {
1778 final ShortcutInfo newShortcut = newShortcuts.get(i);
Makoto Onukia4f89b12017-10-05 10:37:55 -07001779 ps.addOrReplaceDynamicShortcut(newShortcut);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001780 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001781
1782 // Lastly, adjust the ranks.
1783 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001784 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001785 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001786
1787 verifyStates();
1788
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001789 return true;
1790 }
1791
1792 @Override
1793 public boolean updateShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1794 @UserIdInt int userId) {
1795 verifyCaller(packageName, userId);
1796
1797 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
Makoto Onukia19fb232018-06-12 13:01:42 -07001798 verifyShortcutInfoPackages(packageName, newShortcuts);
Makoto Onuki55046222016-03-08 10:49:47 -08001799 final int size = newShortcuts.size();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001800
Makoto Onuki7d0fa812018-02-21 11:24:43 -08001801 final boolean unlimited = injectHasUnlimitedShortcutsApiCallsPermission(
1802 injectBinderCallingPid(), injectBinderCallingUid());
1803
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001804 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001805 throwIfUserLockedL(userId);
1806
Makoto Onukic8c33292016-09-12 16:36:59 -07001807 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001808
Makoto Onukia4f89b12017-10-05 10:37:55 -07001809 ps.ensureImmutableShortcutsNotIncluded(newShortcuts, /*ignoreInvisible=*/ true);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001810
Makoto Onukib08790c2016-06-23 14:05:46 -07001811 // For update, don't fill in the default activity. Having null activity means
1812 // "don't update the activity" here.
1813
Makoto Onuki7001a612016-05-27 13:24:28 -07001814 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_UPDATE);
1815
Makoto Onuki55046222016-03-08 10:49:47 -08001816 // Throttling.
Makoto Onuki7d0fa812018-02-21 11:24:43 -08001817 if (!ps.tryApiCall(unlimited)) {
Makoto Onuki55046222016-03-08 10:49:47 -08001818 return false;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001819 }
1820
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001821 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1822 ps.clearAllImplicitRanks();
1823 assignImplicitRanks(newShortcuts);
1824
Makoto Onuki55046222016-03-08 10:49:47 -08001825 for (int i = 0; i < size; i++) {
1826 final ShortcutInfo source = newShortcuts.get(i);
1827 fixUpIncomingShortcutInfo(source, /* forUpdate= */ true);
1828
1829 final ShortcutInfo target = ps.findShortcutById(source.getId());
Makoto Onukia4f89b12017-10-05 10:37:55 -07001830
1831 // Invisible shortcuts can't be updated.
1832 if (target == null || !target.isVisibleToPublisher()) {
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001833 continue;
1834 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07001835
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001836 if (target.isEnabled() != source.isEnabled()) {
1837 Slog.w(TAG,
1838 "ShortcutInfo.enabled cannot be changed with updateShortcuts()");
1839 }
Makoto Onuki55046222016-03-08 10:49:47 -08001840
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001841 // When updating the rank, we need to insert between existing ranks, so set
1842 // this setRankChanged, and also copy the implicit rank fo adjustRanks().
1843 if (source.hasRank()) {
1844 target.setRankChanged();
1845 target.setImplicitRank(source.getImplicitRank());
1846 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07001847
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001848 final boolean replacingIcon = (source.getIcon() != null);
1849 if (replacingIcon) {
Makoto Onuki475c3652017-05-08 14:29:03 -07001850 removeIconLocked(target);
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001851 }
Makoto Onuki55046222016-03-08 10:49:47 -08001852
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001853 // Note copyNonNullFieldsFrom() does the "updatable with?" check too.
1854 target.copyNonNullFieldsFrom(source);
1855 target.setTimestamp(injectCurrentTimeMillis());
1856
1857 if (replacingIcon) {
Makoto Onuki475c3652017-05-08 14:29:03 -07001858 saveIconAndFixUpShortcutLocked(target);
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001859 }
1860
1861 // When we're updating any resource related fields, re-extract the res names and
1862 // the values.
1863 if (replacingIcon || source.hasStringResources()) {
1864 fixUpShortcutResourceNamesAndValues(target);
Makoto Onuki55046222016-03-08 10:49:47 -08001865 }
1866 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001867
1868 // Lastly, adjust the ranks.
1869 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001870 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001871 packageShortcutsChanged(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001872
Makoto Onuki7001a612016-05-27 13:24:28 -07001873 verifyStates();
1874
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001875 return true;
1876 }
1877
1878 @Override
Makoto Onukia4f89b12017-10-05 10:37:55 -07001879 public boolean addDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001880 @UserIdInt int userId) {
1881 verifyCaller(packageName, userId);
1882
Makoto Onukib6d35232016-04-04 15:57:17 -07001883 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
Makoto Onukia19fb232018-06-12 13:01:42 -07001884 verifyShortcutInfoPackages(packageName, newShortcuts);
Makoto Onukib6d35232016-04-04 15:57:17 -07001885 final int size = newShortcuts.size();
1886
Makoto Onuki7d0fa812018-02-21 11:24:43 -08001887 final boolean unlimited = injectHasUnlimitedShortcutsApiCallsPermission(
1888 injectBinderCallingPid(), injectBinderCallingUid());
1889
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001890 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001891 throwIfUserLockedL(userId);
1892
Makoto Onukic8c33292016-09-12 16:36:59 -07001893 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001894
Makoto Onukia4f89b12017-10-05 10:37:55 -07001895 ps.ensureImmutableShortcutsNotIncluded(newShortcuts, /*ignoreInvisible=*/ true);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001896
Makoto Onukib08790c2016-06-23 14:05:46 -07001897 fillInDefaultActivity(newShortcuts);
1898
Makoto Onuki7001a612016-05-27 13:24:28 -07001899 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_ADD);
1900
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001901 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1902 ps.clearAllImplicitRanks();
1903 assignImplicitRanks(newShortcuts);
1904
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001905 // Throttling.
Makoto Onuki7d0fa812018-02-21 11:24:43 -08001906 if (!ps.tryApiCall(unlimited)) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001907 return false;
1908 }
Makoto Onukib6d35232016-04-04 15:57:17 -07001909 for (int i = 0; i < size; i++) {
1910 final ShortcutInfo newShortcut = newShortcuts.get(i);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001911
Makoto Onukib6d35232016-04-04 15:57:17 -07001912 // Validate the shortcut.
1913 fixUpIncomingShortcutInfo(newShortcut, /* forUpdate= */ false);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001914
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001915 // When ranks are changing, we need to insert between ranks, so set the
1916 // "rank changed" flag.
1917 newShortcut.setRankChanged();
1918
Makoto Onukib6d35232016-04-04 15:57:17 -07001919 // Add it.
Makoto Onukia4f89b12017-10-05 10:37:55 -07001920 ps.addOrReplaceDynamicShortcut(newShortcut);
Makoto Onukib6d35232016-04-04 15:57:17 -07001921 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001922
1923 // Lastly, adjust the ranks.
1924 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001925 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001926 packageShortcutsChanged(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001927
Makoto Onuki7001a612016-05-27 13:24:28 -07001928 verifyStates();
1929
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001930 return true;
1931 }
1932
1933 @Override
Makoto Onuki2d895c32016-12-02 15:48:40 -08001934 public boolean requestPinShortcut(String packageName, ShortcutInfo shortcut,
1935 IntentSender resultIntent, int userId) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08001936 Preconditions.checkNotNull(shortcut);
1937 Preconditions.checkArgument(shortcut.isEnabled(), "Shortcut must be enabled");
Sunny Goyal4ad6b572017-02-28 11:11:51 -08001938 return requestPinItem(packageName, userId, shortcut, null, null, resultIntent);
Sunny Goyal87a563e2017-01-01 19:42:45 -08001939 }
1940
Sunny Goyala6be88a2017-01-12 16:27:58 -08001941 @Override
1942 public Intent createShortcutResultIntent(String packageName, ShortcutInfo shortcut, int userId)
1943 throws RemoteException {
1944 Preconditions.checkNotNull(shortcut);
1945 Preconditions.checkArgument(shortcut.isEnabled(), "Shortcut must be enabled");
1946 verifyCaller(packageName, userId);
Makoto Onukia19fb232018-06-12 13:01:42 -07001947 verifyShortcutInfoPackage(packageName, shortcut);
Sunny Goyala6be88a2017-01-12 16:27:58 -08001948
1949 final Intent ret;
1950 synchronized (mLock) {
1951 throwIfUserLockedL(userId);
1952
1953 // Send request to the launcher, if supported.
1954 ret = mShortcutRequestPinProcessor.createShortcutResultIntent(shortcut, userId);
1955 }
1956
1957 verifyStates();
1958 return ret;
1959 }
1960
Sunny Goyal87a563e2017-01-01 19:42:45 -08001961 /**
1962 * Handles {@link #requestPinShortcut} and {@link ShortcutServiceInternal#requestPinAppWidget}.
1963 * After validating the caller, it passes the request to {@link #mShortcutRequestPinProcessor}.
1964 * Either {@param shortcut} or {@param appWidget} should be non-null.
1965 */
Sunny Goyal4ad6b572017-02-28 11:11:51 -08001966 private boolean requestPinItem(String packageName, int userId, ShortcutInfo shortcut,
1967 AppWidgetProviderInfo appWidget, Bundle extras, IntentSender resultIntent) {
Sunny Goyal87a563e2017-01-01 19:42:45 -08001968 verifyCaller(packageName, userId);
Makoto Onukia19fb232018-06-12 13:01:42 -07001969 verifyShortcutInfoPackage(packageName, shortcut);
Makoto Onuki2d895c32016-12-02 15:48:40 -08001970
1971 final boolean ret;
1972 synchronized (mLock) {
1973 throwIfUserLockedL(userId);
1974
Makoto Onukia01f4f02016-12-15 15:58:41 -08001975 Preconditions.checkState(isUidForegroundLocked(injectBinderCallingUid()),
Makoto Onuki255461f2017-01-10 11:47:25 -08001976 "Calling application must have a foreground activity or a foreground service");
Makoto Onuki2d895c32016-12-02 15:48:40 -08001977
Makoto Onukia4f89b12017-10-05 10:37:55 -07001978 // If it's a pin shortcut request, and there's already a shortcut with the same ID
1979 // that's not visible to the caller (i.e. restore-blocked; meaning it's pinned by
1980 // someone already), then we just replace the existing one with this new one,
1981 // and then proceed the rest of the process.
1982 if (shortcut != null) {
1983 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(
1984 packageName, userId);
1985 final String id = shortcut.getId();
1986 if (ps.isShortcutExistsAndInvisibleToPublisher(id)) {
1987
1988 ps.updateInvisibleShortcutForPinRequestWith(shortcut);
1989
1990 packageShortcutsChanged(packageName, userId);
1991 }
1992 }
1993
Makoto Onuki2d895c32016-12-02 15:48:40 -08001994 // Send request to the launcher, if supported.
Sunny Goyal4ad6b572017-02-28 11:11:51 -08001995 ret = mShortcutRequestPinProcessor.requestPinItemLocked(shortcut, appWidget, extras,
1996 userId, resultIntent);
Makoto Onuki2d895c32016-12-02 15:48:40 -08001997 }
1998
1999 verifyStates();
2000
2001 return ret;
2002 }
2003
2004 @Override
Makoto Onuki20c95f82016-05-11 16:51:01 -07002005 public void disableShortcuts(String packageName, List shortcutIds,
Makoto Onukid6880792016-06-29 13:37:43 -07002006 CharSequence disabledMessage, int disabledMessageResId, @UserIdInt int userId) {
Makoto Onuki20c95f82016-05-11 16:51:01 -07002007 verifyCaller(packageName, userId);
2008 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
2009
2010 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002011 throwIfUserLockedL(userId);
2012
Makoto Onukic8c33292016-09-12 16:36:59 -07002013 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002014
Makoto Onukia4f89b12017-10-05 10:37:55 -07002015 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds,
2016 /*ignoreInvisible=*/ true);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002017
Makoto Onukid6880792016-06-29 13:37:43 -07002018 final String disabledMessageString =
2019 (disabledMessage == null) ? null : disabledMessage.toString();
2020
Makoto Onuki22fcc682016-05-17 14:52:19 -07002021 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
Makoto Onukia4f89b12017-10-05 10:37:55 -07002022 final String id = Preconditions.checkStringNotEmpty((String) shortcutIds.get(i));
2023 if (!ps.isShortcutExistsAndVisibleToPublisher(id)) {
2024 continue;
2025 }
2026 ps.disableWithId(id,
Makoto Onukid6880792016-06-29 13:37:43 -07002027 disabledMessageString, disabledMessageResId,
Makoto Onukia4f89b12017-10-05 10:37:55 -07002028 /* overrideImmutable=*/ false, /*ignoreInvisible=*/ true,
2029 ShortcutInfo.DISABLED_REASON_BY_APP);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002030 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002031
2032 // We may have removed dynamic shortcuts which may have left a gap, so adjust the ranks.
2033 ps.adjustRanks();
Makoto Onuki22fcc682016-05-17 14:52:19 -07002034 }
2035 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07002036
2037 verifyStates();
Makoto Onuki22fcc682016-05-17 14:52:19 -07002038 }
2039
2040 @Override
2041 public void enableShortcuts(String packageName, List shortcutIds, @UserIdInt int userId) {
2042 verifyCaller(packageName, userId);
2043 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
2044
2045 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002046 throwIfUserLockedL(userId);
2047
Makoto Onukic8c33292016-09-12 16:36:59 -07002048 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002049
Makoto Onukia4f89b12017-10-05 10:37:55 -07002050 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds,
2051 /*ignoreInvisible=*/ true);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002052
2053 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
Makoto Onukia4f89b12017-10-05 10:37:55 -07002054 final String id = Preconditions.checkStringNotEmpty((String) shortcutIds.get(i));
2055 if (!ps.isShortcutExistsAndVisibleToPublisher(id)) {
2056 continue;
2057 }
2058 ps.enableWithId(id);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002059 }
Makoto Onuki20c95f82016-05-11 16:51:01 -07002060 }
2061 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07002062
2063 verifyStates();
Makoto Onuki20c95f82016-05-11 16:51:01 -07002064 }
2065
2066 @Override
Makoto Onukib6d35232016-04-04 15:57:17 -07002067 public void removeDynamicShortcuts(String packageName, List shortcutIds,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002068 @UserIdInt int userId) {
2069 verifyCaller(packageName, userId);
Makoto Onukib6d35232016-04-04 15:57:17 -07002070 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002071
2072 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002073 throwIfUserLockedL(userId);
2074
Makoto Onukic8c33292016-09-12 16:36:59 -07002075 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002076
Makoto Onukia4f89b12017-10-05 10:37:55 -07002077 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds,
2078 /*ignoreInvisible=*/ true);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002079
Makoto Onukib6d35232016-04-04 15:57:17 -07002080 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
Makoto Onukia4f89b12017-10-05 10:37:55 -07002081 final String id = Preconditions.checkStringNotEmpty((String) shortcutIds.get(i));
2082 if (!ps.isShortcutExistsAndVisibleToPublisher(id)) {
2083 continue;
2084 }
2085 ps.deleteDynamicWithId(id, /*ignoreInvisible=*/ true);
Makoto Onukib6d35232016-04-04 15:57:17 -07002086 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002087
2088 // We may have removed dynamic shortcuts which may have left a gap, so adjust the ranks.
2089 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002090 }
Makoto Onuki39686e82016-04-13 18:03:00 -07002091 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07002092
2093 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002094 }
2095
2096 @Override
Makoto Onukib6d35232016-04-04 15:57:17 -07002097 public void removeAllDynamicShortcuts(String packageName, @UserIdInt int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002098 verifyCaller(packageName, userId);
2099
2100 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002101 throwIfUserLockedL(userId);
2102
Makoto Onukic8c33292016-09-12 16:36:59 -07002103 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onukia4f89b12017-10-05 10:37:55 -07002104 ps.deleteAllDynamicShortcuts(/*ignoreInvisible=*/ true);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002105 }
Makoto Onuki39686e82016-04-13 18:03:00 -07002106 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07002107
2108 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002109 }
2110
2111 @Override
2112 public ParceledListSlice<ShortcutInfo> getDynamicShortcuts(String packageName,
2113 @UserIdInt int userId) {
2114 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002115
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002116 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002117 throwIfUserLockedL(userId);
2118
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002119 return getShortcutsWithQueryLocked(
2120 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
Makoto Onukia4f89b12017-10-05 10:37:55 -07002121 ShortcutInfo::isDynamicVisible);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002122 }
2123 }
2124
2125 @Override
Makoto Onuki22fcc682016-05-17 14:52:19 -07002126 public ParceledListSlice<ShortcutInfo> getManifestShortcuts(String packageName,
2127 @UserIdInt int userId) {
2128 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002129
Makoto Onuki22fcc682016-05-17 14:52:19 -07002130 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002131 throwIfUserLockedL(userId);
2132
Makoto Onuki22fcc682016-05-17 14:52:19 -07002133 return getShortcutsWithQueryLocked(
2134 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
Makoto Onukia4f89b12017-10-05 10:37:55 -07002135 ShortcutInfo::isManifestVisible);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002136 }
2137 }
2138
2139 @Override
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002140 public ParceledListSlice<ShortcutInfo> getPinnedShortcuts(String packageName,
2141 @UserIdInt int userId) {
2142 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002143
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002144 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002145 throwIfUserLockedL(userId);
2146
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002147 return getShortcutsWithQueryLocked(
2148 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
Makoto Onukia4f89b12017-10-05 10:37:55 -07002149 ShortcutInfo::isPinnedVisible);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002150 }
2151 }
2152
Mehdi Alizadeh406e8b32018-12-11 18:21:49 -08002153 @Override
2154 public ParceledListSlice<ShortcutManager.ShareShortcutInfo> getShareTargets(String packageName,
2155 IntentFilter filter, @UserIdInt int userId) {
2156 verifyCaller(packageName, userId);
Mehdi Alizadehc86dd1f2019-01-25 16:59:54 -08002157 enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APP_PREDICTIONS,
2158 "getShareTargets");
Mehdi Alizadeh406e8b32018-12-11 18:21:49 -08002159
2160 synchronized (mLock) {
2161 throwIfUserLockedL(userId);
2162
2163 final List<ShortcutManager.ShareShortcutInfo> shortcutInfoList = new ArrayList<>();
2164
2165 final ShortcutUser user = getUserShortcutsLocked(userId);
2166 user.forAllPackages(p -> shortcutInfoList.addAll(p.getMatchingShareTargets(filter)));
2167
2168 return new ParceledListSlice<>(shortcutInfoList);
2169 }
2170 }
2171
Mehdi Alizadeh85fd3d52019-01-23 12:49:53 -08002172 @Override
2173 public boolean hasShareTargets(String packageName, String packageToCheck,
2174 @UserIdInt int userId) {
2175 verifyCaller(packageName, userId);
2176 enforceSystem();
2177
2178 synchronized (mLock) {
2179 throwIfUserLockedL(userId);
2180
2181 return getPackageShortcutsLocked(packageToCheck, userId).hasShareTargets();
2182 }
2183 }
2184
Andreas Gampea36dc622018-02-05 17:19:22 -08002185 @GuardedBy("mLock")
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002186 private ParceledListSlice<ShortcutInfo> getShortcutsWithQueryLocked(@NonNull String packageName,
2187 @UserIdInt int userId, int cloneFlags, @NonNull Predicate<ShortcutInfo> query) {
2188
2189 final ArrayList<ShortcutInfo> ret = new ArrayList<>();
2190
Makoto Onukic8c33292016-09-12 16:36:59 -07002191 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002192 ps.findAll(ret, query, cloneFlags);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002193
Makoto Onukibf563b62017-05-04 10:25:30 -07002194 return new ParceledListSlice<>(setReturnedByServer(ret));
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002195 }
2196
2197 @Override
Makoto Onukid6880792016-06-29 13:37:43 -07002198 public int getMaxShortcutCountPerActivity(String packageName, @UserIdInt int userId)
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002199 throws RemoteException {
2200 verifyCaller(packageName, userId);
2201
Makoto Onukib5a012f2016-06-21 11:13:53 -07002202 return mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002203 }
2204
2205 @Override
2206 public int getRemainingCallCount(String packageName, @UserIdInt int userId) {
2207 verifyCaller(packageName, userId);
2208
Makoto Onuki7d0fa812018-02-21 11:24:43 -08002209 final boolean unlimited = injectHasUnlimitedShortcutsApiCallsPermission(
2210 injectBinderCallingPid(), injectBinderCallingUid());
2211
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002212 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002213 throwIfUserLockedL(userId);
2214
Makoto Onukic8c33292016-09-12 16:36:59 -07002215 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki7d0fa812018-02-21 11:24:43 -08002216 return mMaxUpdatesPerInterval - ps.getApiCallCount(unlimited);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002217 }
2218 }
2219
2220 @Override
2221 public long getRateLimitResetTime(String packageName, @UserIdInt int userId) {
2222 verifyCaller(packageName, userId);
2223
2224 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002225 throwIfUserLockedL(userId);
2226
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002227 return getNextResetTimeLocked();
2228 }
2229 }
2230
Makoto Onuki55046222016-03-08 10:49:47 -08002231 @Override
Makoto Onuki20c95f82016-05-11 16:51:01 -07002232 public int getIconMaxDimensions(String packageName, int userId) {
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002233 verifyCaller(packageName, userId);
2234
Makoto Onuki55046222016-03-08 10:49:47 -08002235 synchronized (mLock) {
2236 return mMaxIconDimension;
2237 }
2238 }
2239
Makoto Onuki20c95f82016-05-11 16:51:01 -07002240 @Override
2241 public void reportShortcutUsed(String packageName, String shortcutId, int userId) {
2242 verifyCaller(packageName, userId);
2243
Makoto Onukiac042502016-05-20 16:39:42 -07002244 Preconditions.checkNotNull(shortcutId);
2245
2246 if (DEBUG) {
2247 Slog.d(TAG, String.format("reportShortcutUsed: Shortcut %s package %s used on user %d",
2248 shortcutId, packageName, userId));
2249 }
2250
2251 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002252 throwIfUserLockedL(userId);
2253
Makoto Onukic8c33292016-09-12 16:36:59 -07002254 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002255
Makoto Onukiac042502016-05-20 16:39:42 -07002256 if (ps.findShortcutById(shortcutId) == null) {
2257 Log.w(TAG, String.format("reportShortcutUsed: package %s doesn't have shortcut %s",
2258 packageName, shortcutId));
2259 return;
2260 }
2261 }
2262
2263 final long token = injectClearCallingIdentity();
2264 try {
2265 mUsageStatsManagerInternal.reportShortcutUsage(packageName, shortcutId, userId);
2266 } finally {
2267 injectRestoreCallingIdentity(token);
2268 }
Makoto Onuki20c95f82016-05-11 16:51:01 -07002269 }
2270
Makoto Onuki2d895c32016-12-02 15:48:40 -08002271 @Override
Sunny Goyal7f7372a2017-01-24 11:53:54 -08002272 public boolean isRequestPinItemSupported(int callingUserId, int requestType) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08002273 final long token = injectClearCallingIdentity();
2274 try {
Sunny Goyal7f7372a2017-01-24 11:53:54 -08002275 return mShortcutRequestPinProcessor
2276 .isRequestPinItemSupported(callingUserId, requestType);
Makoto Onuki2d895c32016-12-02 15:48:40 -08002277 } finally {
2278 injectRestoreCallingIdentity(token);
2279 }
2280 }
2281
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002282 /**
Makoto Onukib08790c2016-06-23 14:05:46 -07002283 * Reset all throttling, for developer options and command line. Only system/shell can call
2284 * it.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002285 */
2286 @Override
2287 public void resetThrottling() {
2288 enforceSystemOrShell();
2289
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002290 resetThrottlingInner(getCallingUserId());
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002291 }
2292
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002293 void resetThrottlingInner(@UserIdInt int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002294 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002295 if (!isUserUnlockedL(userId)) {
2296 Log.w(TAG, "User " + userId + " is locked or not running");
2297 return;
2298 }
2299
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002300 getUserShortcutsLocked(userId).resetThrottling();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002301 }
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002302 scheduleSaveUser(userId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002303 Slog.i(TAG, "ShortcutManager: throttling counter reset for user " + userId);
2304 }
2305
2306 void resetAllThrottlingInner() {
2307 synchronized (mLock) {
2308 mRawLastResetTime = injectCurrentTimeMillis();
2309 }
2310 scheduleSaveBaseState();
2311 Slog.i(TAG, "ShortcutManager: throttling counter reset for all users");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002312 }
2313
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002314 @Override
2315 public void onApplicationActive(String packageName, int userId) {
2316 if (DEBUG) {
2317 Slog.d(TAG, "onApplicationActive: package=" + packageName + " userid=" + userId);
2318 }
2319 enforceResetThrottlingPermission();
Makoto Onuki02f338e2016-07-29 09:40:40 -07002320
2321 synchronized (mLock) {
2322 if (!isUserUnlockedL(userId)) {
2323 // This is called by system UI, so no need to throw. Just ignore.
2324 return;
2325 }
2326
2327 getPackageShortcutsLocked(packageName, userId)
2328 .resetRateLimitingForCommandLineNoSaving();
2329 saveUserLocked(userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002330 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002331 }
2332
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002333 // We override this method in unit tests to do a simpler check.
Makoto Onuki634cecb2017-10-13 17:10:48 -07002334 boolean hasShortcutHostPermission(@NonNull String callingPackage, int userId,
2335 int callingPid, int callingUid) {
Makoto Onuki35559d62017-11-06 16:26:32 -08002336 if (canSeeAnyPinnedShortcut(callingPackage, userId, callingPid, callingUid)) {
Makoto Onuki634cecb2017-10-13 17:10:48 -07002337 return true;
2338 }
Makoto Onuki84d59342018-02-02 09:22:38 -08002339 final long start = getStatStartTime();
Makoto Onuki10305202016-07-14 18:14:08 -07002340 try {
2341 return hasShortcutHostPermissionInner(callingPackage, userId);
2342 } finally {
2343 logDurationStat(Stats.LAUNCHER_PERMISSION_CHECK, start);
2344 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002345 }
2346
Makoto Onuki35559d62017-11-06 16:26:32 -08002347 boolean canSeeAnyPinnedShortcut(@NonNull String callingPackage, int userId,
2348 int callingPid, int callingUid) {
2349 if (injectHasAccessShortcutsPermission(callingPid, callingUid)) {
2350 return true;
2351 }
2352 synchronized (mLock) {
Makoto Onuki708703b2017-12-11 16:38:11 -08002353 return getNonPersistentUserLocked(userId).hasHostPackage(callingPackage);
Makoto Onuki35559d62017-11-06 16:26:32 -08002354 }
2355 }
2356
Makoto Onuki634cecb2017-10-13 17:10:48 -07002357 /**
2358 * Returns true if the caller has the "ACCESS_SHORTCUTS" permission.
2359 */
Makoto Onuki35559d62017-11-06 16:26:32 -08002360 @VisibleForTesting
2361 boolean injectHasAccessShortcutsPermission(int callingPid, int callingUid) {
Makoto Onuki634cecb2017-10-13 17:10:48 -07002362 return mContext.checkPermission(android.Manifest.permission.ACCESS_SHORTCUTS,
2363 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
2364 }
2365
Makoto Onuki7d0fa812018-02-21 11:24:43 -08002366 /**
2367 * Returns true if the caller has the "UNLIMITED_SHORTCUTS_API_CALLS" permission.
2368 */
2369 @VisibleForTesting
2370 boolean injectHasUnlimitedShortcutsApiCallsPermission(int callingPid, int callingUid) {
2371 return mContext.checkPermission(permission.UNLIMITED_SHORTCUTS_API_CALLS,
2372 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
2373 }
2374
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002375 // This method is extracted so we can directly call this method from unit tests,
2376 // even when hasShortcutPermission() is overridden.
2377 @VisibleForTesting
Makoto Onuki2d895c32016-12-02 15:48:40 -08002378 boolean hasShortcutHostPermissionInner(@NonNull String packageName, int userId) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002379 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002380 throwIfUserLockedL(userId);
2381
Makoto Onuki31459242016-03-22 11:12:18 -07002382 final ShortcutUser user = getUserShortcutsLocked(userId);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002383
Makoto Onuki2d895c32016-12-02 15:48:40 -08002384 // Always trust the cached component.
Makoto Onuki10305202016-07-14 18:14:08 -07002385 final ComponentName cached = user.getCachedLauncher();
2386 if (cached != null) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08002387 if (cached.getPackageName().equals(packageName)) {
Makoto Onuki10305202016-07-14 18:14:08 -07002388 return true;
2389 }
2390 }
2391 // If the cached one doesn't match, then go ahead
2392
Makoto Onuki2d895c32016-12-02 15:48:40 -08002393 final ComponentName detected = getDefaultLauncher(userId);
Makoto Onuki2e210c42016-03-30 08:30:36 -07002394
Makoto Onuki10305202016-07-14 18:14:08 -07002395 // Update the cache.
2396 user.setLauncher(detected);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002397 if (detected != null) {
2398 if (DEBUG) {
2399 Slog.v(TAG, "Detected launcher: " + detected);
2400 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08002401 return detected.getPackageName().equals(packageName);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002402 } else {
2403 // Default launcher not found.
2404 return false;
2405 }
2406 }
2407 }
2408
Makoto Onuki2d895c32016-12-02 15:48:40 -08002409 @Nullable
2410 ComponentName getDefaultLauncher(@UserIdInt int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08002411 final long start = getStatStartTime();
Makoto Onuki2d895c32016-12-02 15:48:40 -08002412 final long token = injectClearCallingIdentity();
2413 try {
2414 synchronized (mLock) {
2415 throwIfUserLockedL(userId);
2416
2417 final ShortcutUser user = getUserShortcutsLocked(userId);
2418
2419 final List<ResolveInfo> allHomeCandidates = new ArrayList<>();
2420
2421 // Default launcher from package manager.
Makoto Onuki84d59342018-02-02 09:22:38 -08002422 final long startGetHomeActivitiesAsUser = getStatStartTime();
Makoto Onuki2d895c32016-12-02 15:48:40 -08002423 final ComponentName defaultLauncher = mPackageManagerInternal
2424 .getHomeActivitiesAsUser(allHomeCandidates, userId);
2425 logDurationStat(Stats.GET_DEFAULT_HOME, startGetHomeActivitiesAsUser);
2426
2427 ComponentName detected = null;
2428 if (defaultLauncher != null) {
2429 detected = defaultLauncher;
2430 if (DEBUG) {
2431 Slog.v(TAG, "Default launcher from PM: " + detected);
2432 }
2433 } else {
2434 detected = user.getLastKnownLauncher();
2435
2436 if (detected != null) {
2437 if (injectIsActivityEnabledAndExported(detected, userId)) {
2438 if (DEBUG) {
2439 Slog.v(TAG, "Cached launcher: " + detected);
2440 }
2441 } else {
2442 Slog.w(TAG, "Cached launcher " + detected + " no longer exists");
2443 detected = null;
2444 user.clearLauncher();
2445 }
2446 }
2447 }
2448
2449 if (detected == null) {
2450 // If we reach here, that means it's the first check since the user was created,
2451 // and there's already multiple launchers and there's no default set.
2452 // Find the system one with the highest priority.
2453 // (We need to check the priority too because of FallbackHome in Settings.)
2454 // If there's no system launcher yet, then no one can access shortcuts, until
2455 // the user explicitly
2456 final int size = allHomeCandidates.size();
2457
2458 int lastPriority = Integer.MIN_VALUE;
2459 for (int i = 0; i < size; i++) {
2460 final ResolveInfo ri = allHomeCandidates.get(i);
2461 if (!ri.activityInfo.applicationInfo.isSystemApp()) {
2462 continue;
2463 }
2464 if (DEBUG) {
2465 Slog.d(TAG, String.format("hasShortcutPermissionInner: pkg=%s prio=%d",
2466 ri.activityInfo.getComponentName(), ri.priority));
2467 }
2468 if (ri.priority < lastPriority) {
2469 continue;
2470 }
2471 detected = ri.activityInfo.getComponentName();
2472 lastPriority = ri.priority;
2473 }
2474 }
2475 return detected;
2476 }
2477 } finally {
2478 injectRestoreCallingIdentity(token);
2479 logDurationStat(Stats.GET_DEFAULT_LAUNCHER, start);
2480 }
2481 }
2482
Dianne Hackbornc160fa42017-11-01 16:14:26 -07002483 public void setShortcutHostPackage(@NonNull String type, @Nullable String packageName,
2484 int userId) {
2485 synchronized (mLock) {
Makoto Onuki708703b2017-12-11 16:38:11 -08002486 getNonPersistentUserLocked(userId).setShortcutHostPackage(type, packageName);
Dianne Hackbornc160fa42017-11-01 16:14:26 -07002487 }
2488 }
2489
Makoto Onukicdc78f72016-03-21 15:47:52 -07002490 // === House keeping ===
2491
Makoto Onukib08790c2016-06-23 14:05:46 -07002492 private void cleanUpPackageForAllLoadedUsers(String packageName, @UserIdInt int packageUserId,
2493 boolean appStillExists) {
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002494 synchronized (mLock) {
2495 forEachLoadedUserLocked(user ->
Makoto Onukib08790c2016-06-23 14:05:46 -07002496 cleanUpPackageLocked(packageName, user.getUserId(), packageUserId,
2497 appStillExists));
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002498 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002499 }
2500
Makoto Onuki2e210c42016-03-30 08:30:36 -07002501 /**
2502 * Remove all the information associated with a package. This will really remove all the
2503 * information, including the restore information (i.e. it'll remove packages even if they're
2504 * shadow).
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002505 *
2506 * This is called when an app is uninstalled, or an app gets "clear data"ed.
Makoto Onuki2e210c42016-03-30 08:30:36 -07002507 */
Andreas Gampea36dc622018-02-05 17:19:22 -08002508 @GuardedBy("mLock")
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002509 @VisibleForTesting
Makoto Onukib08790c2016-06-23 14:05:46 -07002510 void cleanUpPackageLocked(String packageName, int owningUserId, int packageUserId,
2511 boolean appStillExists) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002512 final boolean wasUserLoaded = isUserLoadedLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002513
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002514 final ShortcutUser user = getUserShortcutsLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002515 boolean doNotify = false;
2516
2517 // First, remove the package from the package list (if the package is a publisher).
Makoto Onukid99c6f02016-03-28 11:02:54 -07002518 if (packageUserId == owningUserId) {
Makoto Onukic51b2872016-05-04 15:24:50 -07002519 if (user.removePackage(packageName) != null) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002520 doNotify = true;
2521 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07002522 }
Makoto Onukid99c6f02016-03-28 11:02:54 -07002523
Makoto Onukicdc78f72016-03-21 15:47:52 -07002524 // Also remove from the launcher list (if the package is a launcher).
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002525 user.removeLauncher(packageUserId, packageName);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002526
2527 // Then remove pinned shortcuts from all launchers.
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002528 user.forAllLaunchers(l -> l.cleanUpPackage(packageName, packageUserId));
2529
2530 // Now there may be orphan shortcuts because we removed pinned shortcuts at the previous
Makoto Onukicdc78f72016-03-21 15:47:52 -07002531 // step. Remove them too.
Makoto Onukic51b2872016-05-04 15:24:50 -07002532 user.forAllPackages(p -> p.refreshPinnedFlags());
Makoto Onukicdc78f72016-03-21 15:47:52 -07002533
Makoto Onukid99c6f02016-03-28 11:02:54 -07002534 scheduleSaveUser(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002535
2536 if (doNotify) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002537 notifyListeners(packageName, owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002538 }
2539
Makoto Onukib08790c2016-06-23 14:05:46 -07002540 // If the app still exists (i.e. data cleared), we need to re-publish manifest shortcuts.
2541 if (appStillExists && (packageUserId == owningUserId)) {
2542 // This will do the notification and save when needed, so do it after the above
2543 // notifyListeners.
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002544 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07002545 }
2546
Makoto Onukicdc78f72016-03-21 15:47:52 -07002547 if (!wasUserLoaded) {
2548 // Note this will execute the scheduled save.
Makoto Onukid99c6f02016-03-28 11:02:54 -07002549 unloadUserLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002550 }
2551 }
2552
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002553 /**
2554 * Entry point from {@link LauncherApps}.
2555 */
2556 private class LocalService extends ShortcutServiceInternal {
Makoto Onuki2e210c42016-03-30 08:30:36 -07002557
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002558 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002559 public List<ShortcutInfo> getShortcuts(int launcherUserId,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002560 @NonNull String callingPackage, long changedSince,
Makoto Onukiabe84422016-04-07 09:41:19 -07002561 @Nullable String packageName, @Nullable List<String> shortcutIds,
Makoto Onuki99302b52017-03-29 12:42:26 -07002562 @Nullable ComponentName componentName,
Makoto Onuki634cecb2017-10-13 17:10:48 -07002563 int queryFlags, int userId, int callingPid, int callingUid) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002564 final ArrayList<ShortcutInfo> ret = new ArrayList<>();
Makoto Onuki9c850012016-07-26 15:50:50 -07002565
Makoto Onuki20c95f82016-05-11 16:51:01 -07002566 final boolean cloneKeyFieldOnly =
2567 ((queryFlags & ShortcutQuery.FLAG_GET_KEY_FIELDS_ONLY) != 0);
2568 final int cloneFlag = cloneKeyFieldOnly ? ShortcutInfo.CLONE_REMOVE_NON_KEY_INFO
2569 : ShortcutInfo.CLONE_REMOVE_FOR_LAUNCHER;
Makoto Onukiabe84422016-04-07 09:41:19 -07002570 if (packageName == null) {
2571 shortcutIds = null; // LauncherAppsService already threw for it though.
2572 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002573
2574 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002575 throwIfUserLockedL(userId);
2576 throwIfUserLockedL(launcherUserId);
2577
Makoto Onuki2e210c42016-03-30 08:30:36 -07002578 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002579 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002580
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002581 if (packageName != null) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002582 getShortcutsInnerLocked(launcherUserId,
Makoto Onukiabe84422016-04-07 09:41:19 -07002583 callingPackage, packageName, shortcutIds, changedSince,
Makoto Onuki634cecb2017-10-13 17:10:48 -07002584 componentName, queryFlags, userId, ret, cloneFlag,
2585 callingPid, callingUid);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002586 } else {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002587 final List<String> shortcutIdsF = shortcutIds;
2588 getUserShortcutsLocked(userId).forAllPackages(p -> {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002589 getShortcutsInnerLocked(launcherUserId,
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002590 callingPackage, p.getPackageName(), shortcutIdsF, changedSince,
Makoto Onuki634cecb2017-10-13 17:10:48 -07002591 componentName, queryFlags, userId, ret, cloneFlag,
2592 callingPid, callingUid);
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002593 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002594 }
2595 }
Makoto Onukibf563b62017-05-04 10:25:30 -07002596 return setReturnedByServer(ret);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002597 }
2598
Andreas Gampea36dc622018-02-05 17:19:22 -08002599 @GuardedBy("ShortcutService.this.mLock")
Makoto Onukid99c6f02016-03-28 11:02:54 -07002600 private void getShortcutsInnerLocked(int launcherUserId, @NonNull String callingPackage,
Makoto Onukiabe84422016-04-07 09:41:19 -07002601 @Nullable String packageName, @Nullable List<String> shortcutIds, long changedSince,
Makoto Onuki99302b52017-03-29 12:42:26 -07002602 @Nullable ComponentName componentName, int queryFlags,
Makoto Onuki634cecb2017-10-13 17:10:48 -07002603 int userId, ArrayList<ShortcutInfo> ret, int cloneFlag,
2604 int callingPid, int callingUid) {
Makoto Onukiabe84422016-04-07 09:41:19 -07002605 final ArraySet<String> ids = shortcutIds == null ? null
2606 : new ArraySet<>(shortcutIds);
2607
Makoto Onuki35559d62017-11-06 16:26:32 -08002608 final ShortcutUser user = getUserShortcutsLocked(userId);
2609 final ShortcutPackage p = user.getPackageShortcutsIfExists(packageName);
Makoto Onukic51b2872016-05-04 15:24:50 -07002610 if (p == null) {
2611 return; // No need to instantiate ShortcutPackage.
2612 }
Makoto Onuki634cecb2017-10-13 17:10:48 -07002613 final boolean matchDynamic = (queryFlags & ShortcutQuery.FLAG_MATCH_DYNAMIC) != 0;
2614 final boolean matchPinned = (queryFlags & ShortcutQuery.FLAG_MATCH_PINNED) != 0;
2615 final boolean matchManifest = (queryFlags & ShortcutQuery.FLAG_MATCH_MANIFEST) != 0;
2616
Makoto Onuki35559d62017-11-06 16:26:32 -08002617 final boolean canAccessAllShortcuts =
2618 canSeeAnyPinnedShortcut(callingPackage, launcherUserId, callingPid, callingUid);
2619
Makoto Onuki634cecb2017-10-13 17:10:48 -07002620 final boolean getPinnedByAnyLauncher =
Makoto Onuki35559d62017-11-06 16:26:32 -08002621 canAccessAllShortcuts &&
2622 ((queryFlags & ShortcutQuery.FLAG_MATCH_PINNED_BY_ANY_LAUNCHER) != 0);
Makoto Onukic51b2872016-05-04 15:24:50 -07002623
2624 p.findAll(ret,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002625 (ShortcutInfo si) -> {
2626 if (si.getLastChangedTimestamp() < changedSince) {
2627 return false;
2628 }
Makoto Onukiabe84422016-04-07 09:41:19 -07002629 if (ids != null && !ids.contains(si.getId())) {
2630 return false;
2631 }
Makoto Onuki85694522016-05-04 12:53:37 -07002632 if (componentName != null) {
Makoto Onuki9fd90192017-01-06 18:31:03 +00002633 if (si.getActivity() != null
2634 && !si.getActivity().equals(componentName)) {
Makoto Onuki85694522016-05-04 12:53:37 -07002635 return false;
2636 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002637 }
Makoto Onuki634cecb2017-10-13 17:10:48 -07002638 if (matchDynamic && si.isDynamic()) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002639 return true;
2640 }
Makoto Onuki35559d62017-11-06 16:26:32 -08002641 if ((matchPinned || getPinnedByAnyLauncher) && si.isPinned()) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002642 return true;
2643 }
Makoto Onuki634cecb2017-10-13 17:10:48 -07002644 if (matchManifest && si.isDeclaredInManifest()) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002645 return true;
2646 }
2647 return false;
Makoto Onuki634cecb2017-10-13 17:10:48 -07002648 }, cloneFlag, callingPackage, launcherUserId, getPinnedByAnyLauncher);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002649 }
2650
2651 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002652 public boolean isPinnedByCaller(int launcherUserId, @NonNull String callingPackage,
2653 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2654 Preconditions.checkStringNotEmpty(packageName, "packageName");
2655 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
2656
2657 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002658 throwIfUserLockedL(userId);
2659 throwIfUserLockedL(launcherUserId);
2660
Makoto Onuki2e210c42016-03-30 08:30:36 -07002661 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002662 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002663
Makoto Onukid99c6f02016-03-28 11:02:54 -07002664 final ShortcutInfo si = getShortcutInfoLocked(
Makoto Onuki634cecb2017-10-13 17:10:48 -07002665 launcherUserId, callingPackage, packageName, shortcutId, userId,
2666 /*getPinnedByAnyLauncher=*/ false);
Makoto Onukid99c6f02016-03-28 11:02:54 -07002667 return si != null && si.isPinned();
2668 }
2669 }
2670
Andreas Gampea36dc622018-02-05 17:19:22 -08002671 @GuardedBy("ShortcutService.this.mLock")
Makoto Onuki2e210c42016-03-30 08:30:36 -07002672 private ShortcutInfo getShortcutInfoLocked(
Makoto Onukid99c6f02016-03-28 11:02:54 -07002673 int launcherUserId, @NonNull String callingPackage,
Makoto Onuki634cecb2017-10-13 17:10:48 -07002674 @NonNull String packageName, @NonNull String shortcutId, int userId,
2675 boolean getPinnedByAnyLauncher) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002676 Preconditions.checkStringNotEmpty(packageName, "packageName");
2677 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
2678
Makoto Onuki02f338e2016-07-29 09:40:40 -07002679 throwIfUserLockedL(userId);
2680 throwIfUserLockedL(launcherUserId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002681
Makoto Onukic51b2872016-05-04 15:24:50 -07002682 final ShortcutPackage p = getUserShortcutsLocked(userId)
2683 .getPackageShortcutsIfExists(packageName);
2684 if (p == null) {
2685 return null;
2686 }
2687
Makoto Onukid99c6f02016-03-28 11:02:54 -07002688 final ArrayList<ShortcutInfo> list = new ArrayList<>(1);
Makoto Onukic51b2872016-05-04 15:24:50 -07002689 p.findAll(list,
Makoto Onukid99c6f02016-03-28 11:02:54 -07002690 (ShortcutInfo si) -> shortcutId.equals(si.getId()),
Makoto Onuki634cecb2017-10-13 17:10:48 -07002691 /* clone flags=*/ 0, callingPackage, launcherUserId, getPinnedByAnyLauncher);
Makoto Onukid99c6f02016-03-28 11:02:54 -07002692 return list.size() == 0 ? null : list.get(0);
2693 }
2694
2695 @Override
2696 public void pinShortcuts(int launcherUserId,
2697 @NonNull String callingPackage, @NonNull String packageName,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002698 @NonNull List<String> shortcutIds, int userId) {
2699 // Calling permission must be checked by LauncherAppsImpl.
2700 Preconditions.checkStringNotEmpty(packageName, "packageName");
2701 Preconditions.checkNotNull(shortcutIds, "shortcutIds");
2702
2703 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002704 throwIfUserLockedL(userId);
2705 throwIfUserLockedL(launcherUserId);
2706
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002707 final ShortcutLauncher launcher =
Makoto Onuki2e210c42016-03-30 08:30:36 -07002708 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId);
Makoto Onukic51b2872016-05-04 15:24:50 -07002709 launcher.attemptToRestoreIfNeededAndSave();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002710
Makoto Onukia4f89b12017-10-05 10:37:55 -07002711 launcher.pinShortcuts(userId, packageName, shortcutIds, /*forPinRequest=*/ false);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002712 }
Makoto Onuki39686e82016-04-13 18:03:00 -07002713 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07002714
2715 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002716 }
2717
2718 @Override
Makoto Onuki440a1ea2016-07-20 14:21:18 -07002719 public Intent[] createShortcutIntents(int launcherUserId,
Makoto Onukid99c6f02016-03-28 11:02:54 -07002720 @NonNull String callingPackage,
Makoto Onuki634cecb2017-10-13 17:10:48 -07002721 @NonNull String packageName, @NonNull String shortcutId, int userId,
2722 int callingPid, int callingUid) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002723 // Calling permission must be checked by LauncherAppsImpl.
Makoto Onuki43204b82016-03-08 16:16:44 -08002724 Preconditions.checkStringNotEmpty(packageName, "packageName can't be empty");
2725 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId can't be empty");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002726
2727 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002728 throwIfUserLockedL(userId);
2729 throwIfUserLockedL(launcherUserId);
2730
Makoto Onuki2e210c42016-03-30 08:30:36 -07002731 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002732 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002733
Makoto Onuki634cecb2017-10-13 17:10:48 -07002734 final boolean getPinnedByAnyLauncher =
Makoto Onuki35559d62017-11-06 16:26:32 -08002735 canSeeAnyPinnedShortcut(callingPackage, launcherUserId,
2736 callingPid, callingUid);
Makoto Onuki634cecb2017-10-13 17:10:48 -07002737
Makoto Onukid99c6f02016-03-28 11:02:54 -07002738 // Make sure the shortcut is actually visible to the launcher.
2739 final ShortcutInfo si = getShortcutInfoLocked(
Makoto Onuki634cecb2017-10-13 17:10:48 -07002740 launcherUserId, callingPackage, packageName, shortcutId, userId,
2741 getPinnedByAnyLauncher);
Makoto Onukid99c6f02016-03-28 11:02:54 -07002742 // "si == null" should suffice here, but check the flags too just to make sure.
Makoto Onuki35559d62017-11-06 16:26:32 -08002743 if (si == null || !si.isEnabled() || !(si.isAlive() || getPinnedByAnyLauncher)) {
Makoto Onuki83f6d2d2016-07-11 14:30:19 -07002744 Log.e(TAG, "Shortcut " + shortcutId + " does not exist or disabled");
Makoto Onukid99c6f02016-03-28 11:02:54 -07002745 return null;
2746 }
Makoto Onuki440a1ea2016-07-20 14:21:18 -07002747 return si.getIntents();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002748 }
2749 }
2750
2751 @Override
2752 public void addListener(@NonNull ShortcutChangeListener listener) {
2753 synchronized (mLock) {
2754 mListeners.add(Preconditions.checkNotNull(listener));
2755 }
2756 }
Makoto Onuki55046222016-03-08 10:49:47 -08002757
2758 @Override
Makoto Onukiabe84422016-04-07 09:41:19 -07002759 public int getShortcutIconResId(int launcherUserId, @NonNull String callingPackage,
2760 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2761 Preconditions.checkNotNull(callingPackage, "callingPackage");
2762 Preconditions.checkNotNull(packageName, "packageName");
2763 Preconditions.checkNotNull(shortcutId, "shortcutId");
Makoto Onuki55046222016-03-08 10:49:47 -08002764
2765 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002766 throwIfUserLockedL(userId);
2767 throwIfUserLockedL(launcherUserId);
2768
Makoto Onuki2e210c42016-03-30 08:30:36 -07002769 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002770 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002771
Makoto Onukic51b2872016-05-04 15:24:50 -07002772 final ShortcutPackage p = getUserShortcutsLocked(userId)
2773 .getPackageShortcutsIfExists(packageName);
2774 if (p == null) {
2775 return 0;
2776 }
2777
2778 final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId);
Makoto Onuki55046222016-03-08 10:49:47 -08002779 return (shortcutInfo != null && shortcutInfo.hasIconResource())
2780 ? shortcutInfo.getIconResourceId() : 0;
2781 }
2782 }
2783
2784 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002785 public ParcelFileDescriptor getShortcutIconFd(int launcherUserId,
Makoto Onukiabe84422016-04-07 09:41:19 -07002786 @NonNull String callingPackage, @NonNull String packageName,
2787 @NonNull String shortcutId, int userId) {
2788 Preconditions.checkNotNull(callingPackage, "callingPackage");
2789 Preconditions.checkNotNull(packageName, "packageName");
2790 Preconditions.checkNotNull(shortcutId, "shortcutId");
Makoto Onuki55046222016-03-08 10:49:47 -08002791
2792 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002793 throwIfUserLockedL(userId);
2794 throwIfUserLockedL(launcherUserId);
2795
Makoto Onuki2e210c42016-03-30 08:30:36 -07002796 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002797 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002798
Makoto Onukic51b2872016-05-04 15:24:50 -07002799 final ShortcutPackage p = getUserShortcutsLocked(userId)
2800 .getPackageShortcutsIfExists(packageName);
2801 if (p == null) {
2802 return null;
2803 }
2804
2805 final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId);
Makoto Onuki55046222016-03-08 10:49:47 -08002806 if (shortcutInfo == null || !shortcutInfo.hasIconFile()) {
2807 return null;
2808 }
Makoto Onuki475c3652017-05-08 14:29:03 -07002809 final String path = mShortcutBitmapSaver.getBitmapPathMayWaitLocked(shortcutInfo);
2810 if (path == null) {
2811 Slog.w(TAG, "null bitmap detected in getShortcutIconFd()");
2812 return null;
2813 }
Makoto Onuki55046222016-03-08 10:49:47 -08002814 try {
2815 return ParcelFileDescriptor.open(
Makoto Onuki475c3652017-05-08 14:29:03 -07002816 new File(path),
Makoto Onuki55046222016-03-08 10:49:47 -08002817 ParcelFileDescriptor.MODE_READ_ONLY);
2818 } catch (FileNotFoundException e) {
Makoto Onuki475c3652017-05-08 14:29:03 -07002819 Slog.e(TAG, "Icon file not found: " + path);
Makoto Onuki55046222016-03-08 10:49:47 -08002820 return null;
2821 }
2822 }
2823 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002824
2825 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002826 public boolean hasShortcutHostPermission(int launcherUserId,
Makoto Onuki634cecb2017-10-13 17:10:48 -07002827 @NonNull String callingPackage, int callingPid, int callingUid) {
2828 return ShortcutService.this.hasShortcutHostPermission(callingPackage, launcherUserId,
2829 callingPid, callingUid);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002830 }
Sunny Goyal87a563e2017-01-01 19:42:45 -08002831
2832 @Override
Dianne Hackbornc160fa42017-11-01 16:14:26 -07002833 public void setShortcutHostPackage(@NonNull String type, @Nullable String packageName,
2834 int userId) {
2835 ShortcutService.this.setShortcutHostPackage(type, packageName, userId);
2836 }
2837
2838 @Override
Sunny Goyal87a563e2017-01-01 19:42:45 -08002839 public boolean requestPinAppWidget(@NonNull String callingPackage,
Sunny Goyal4ad6b572017-02-28 11:11:51 -08002840 @NonNull AppWidgetProviderInfo appWidget, @Nullable Bundle extras,
2841 @Nullable IntentSender resultIntent, int userId) {
Sunny Goyal87a563e2017-01-01 19:42:45 -08002842 Preconditions.checkNotNull(appWidget);
Sunny Goyal4ad6b572017-02-28 11:11:51 -08002843 return requestPinItem(callingPackage, userId, null, appWidget, extras, resultIntent);
Sunny Goyal87a563e2017-01-01 19:42:45 -08002844 }
Sunny Goyal7f7372a2017-01-24 11:53:54 -08002845
2846 @Override
2847 public boolean isRequestPinItemSupported(int callingUserId, int requestType) {
2848 return ShortcutService.this.isRequestPinItemSupported(callingUserId, requestType);
2849 }
Tony Maked6ef622017-12-07 16:36:16 +00002850
2851 @Override
2852 public boolean isForegroundDefaultLauncher(@NonNull String callingPackage, int callingUid) {
2853 Preconditions.checkNotNull(callingPackage);
2854
2855 final int userId = UserHandle.getUserId(callingUid);
2856 final ComponentName defaultLauncher = getDefaultLauncher(userId);
2857 if (defaultLauncher == null) {
2858 return false;
2859 }
2860 if (!callingPackage.equals(defaultLauncher.getPackageName())) {
2861 return false;
2862 }
2863 synchronized (mLock) {
2864 if (!isUidForegroundLocked(callingUid)) {
2865 return false;
2866 }
2867 }
2868 return true;
2869 }
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002870 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002871
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002872 final BroadcastReceiver mReceiver = new BroadcastReceiver() {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002873 @Override
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002874 public void onReceive(Context context, Intent intent) {
2875 if (!mBootCompleted.get()) {
2876 return; // Boot not completed, ignore the broadcast.
2877 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07002878 try {
2879 if (Intent.ACTION_LOCALE_CHANGED.equals(intent.getAction())) {
2880 handleLocaleChanged();
2881 }
2882 } catch (Exception e) {
2883 wtf("Exception in mReceiver.onReceive", e);
Makoto Onukic51b2872016-05-04 15:24:50 -07002884 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002885 }
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002886 };
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002887
Makoto Onuki157b1622016-06-02 16:13:10 -07002888 void handleLocaleChanged() {
2889 if (DEBUG) {
2890 Slog.d(TAG, "handleLocaleChanged");
2891 }
2892 scheduleSaveBaseState();
2893
Makoto Onuki02f338e2016-07-29 09:40:40 -07002894 synchronized (mLock) {
2895 final long token = injectClearCallingIdentity();
2896 try {
2897 forEachLoadedUserLocked(user -> user.detectLocaleChange());
2898 } finally {
2899 injectRestoreCallingIdentity(token);
2900 }
Makoto Onuki157b1622016-06-02 16:13:10 -07002901 }
2902 }
2903
Makoto Onukif34c3082016-07-13 10:25:25 -07002904 /**
2905 * Package event callbacks.
2906 */
2907 @VisibleForTesting
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002908 final BroadcastReceiver mPackageMonitor = new BroadcastReceiver() {
Makoto Onukif34c3082016-07-13 10:25:25 -07002909 @Override
2910 public void onReceive(Context context, Intent intent) {
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002911 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
2912 if (userId == UserHandle.USER_NULL) {
2913 Slog.w(TAG, "Intent broadcast does not contain user handle: " + intent);
2914 return;
2915 }
2916
2917 final String action = intent.getAction();
2918
2919 // This is normally called on Handler, so clearCallingIdentity() isn't needed,
2920 // but we still check it in unit tests.
Makoto Onukif34c3082016-07-13 10:25:25 -07002921 final long token = injectClearCallingIdentity();
2922 try {
Makoto Onuki10305202016-07-14 18:14:08 -07002923 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002924 if (!isUserUnlockedL(userId)) {
2925 if (DEBUG) {
2926 Slog.d(TAG, "Ignoring package broadcast " + action
2927 + " for locked/stopped user " + userId);
2928 }
2929 return;
2930 }
2931
2932 // Whenever we get one of those package broadcasts, or get
2933 // ACTION_PREFERRED_ACTIVITY_CHANGED, we purge the default launcher cache.
Makoto Onuki10305202016-07-14 18:14:08 -07002934 final ShortcutUser user = getUserShortcutsLocked(userId);
2935 user.clearLauncher();
2936 }
2937 if (Intent.ACTION_PREFERRED_ACTIVITY_CHANGED.equals(action)) {
2938 // Nothing farther to do.
2939 return;
2940 }
2941
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002942 final Uri intentUri = intent.getData();
2943 final String packageName = (intentUri != null) ? intentUri.getSchemeSpecificPart()
2944 : null;
2945 if (packageName == null) {
2946 Slog.w(TAG, "Intent broadcast does not contain package name: " + intent);
2947 return;
2948 }
2949
2950 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
2951
2952 switch (action) {
2953 case Intent.ACTION_PACKAGE_ADDED:
2954 if (replacing) {
2955 handlePackageUpdateFinished(packageName, userId);
2956 } else {
2957 handlePackageAdded(packageName, userId);
2958 }
2959 break;
2960 case Intent.ACTION_PACKAGE_REMOVED:
2961 if (!replacing) {
2962 handlePackageRemoved(packageName, userId);
2963 }
2964 break;
2965 case Intent.ACTION_PACKAGE_CHANGED:
2966 handlePackageChanged(packageName, userId);
2967
2968 break;
2969 case Intent.ACTION_PACKAGE_DATA_CLEARED:
2970 handlePackageDataCleared(packageName, userId);
2971 break;
2972 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07002973 } catch (Exception e) {
2974 wtf("Exception in mPackageMonitor.onReceive", e);
Makoto Onukif34c3082016-07-13 10:25:25 -07002975 } finally {
2976 injectRestoreCallingIdentity(token);
Makoto Onukia2241832016-07-06 13:28:37 -07002977 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07002978 }
Makoto Onukif34c3082016-07-13 10:25:25 -07002979 };
Makoto Onukicdc78f72016-03-21 15:47:52 -07002980
Makoto Onuki0acbb142016-03-22 17:02:57 -07002981 /**
Makoto Onuki39686e82016-04-13 18:03:00 -07002982 * Called when a user is unlocked.
2983 * - Check all known packages still exist, and otherwise perform cleanup.
2984 * - If a package still exists, check the version code. If it's been updated, may need to
Makoto Onukib08790c2016-06-23 14:05:46 -07002985 * update timestamps of its shortcuts.
Makoto Onuki0acbb142016-03-22 17:02:57 -07002986 */
Makoto Onukid99c6f02016-03-28 11:02:54 -07002987 @VisibleForTesting
Makoto Onuki39686e82016-04-13 18:03:00 -07002988 void checkPackageChanges(@UserIdInt int ownerUserId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07002989 if (DEBUG) {
Makoto Onuki39686e82016-04-13 18:03:00 -07002990 Slog.d(TAG, "checkPackageChanges() ownerUserId=" + ownerUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002991 }
Makoto Onukib08790c2016-06-23 14:05:46 -07002992 if (injectIsSafeModeEnabled()) {
2993 Slog.i(TAG, "Safe mode, skipping checkPackageChanges()");
2994 return;
2995 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07002996
Makoto Onuki84d59342018-02-02 09:22:38 -08002997 final long start = getStatStartTime();
Makoto Onuki22fcc682016-05-17 14:52:19 -07002998 try {
2999 final ArrayList<PackageWithUser> gonePackages = new ArrayList<>();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003000
Makoto Onuki22fcc682016-05-17 14:52:19 -07003001 synchronized (mLock) {
3002 final ShortcutUser user = getUserShortcutsLocked(ownerUserId);
3003
3004 // Find packages that have been uninstalled.
3005 user.forAllPackageItems(spi -> {
3006 if (spi.getPackageInfo().isShadow()) {
3007 return; // Don't delete shadow information.
3008 }
3009 if (!isPackageInstalled(spi.getPackageName(), spi.getPackageUserId())) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003010 if (DEBUG) {
3011 Slog.d(TAG, "Uninstalled: " + spi.getPackageName()
3012 + " user " + spi.getPackageUserId());
3013 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07003014 gonePackages.add(PackageWithUser.of(spi));
3015 }
3016 });
3017 if (gonePackages.size() > 0) {
3018 for (int i = gonePackages.size() - 1; i >= 0; i--) {
3019 final PackageWithUser pu = gonePackages.get(i);
Makoto Onukib08790c2016-06-23 14:05:46 -07003020 cleanUpPackageLocked(pu.packageName, ownerUserId, pu.userId,
3021 /* appStillExists = */ false);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003022 }
Makoto Onukid99c6f02016-03-28 11:02:54 -07003023 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07003024
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003025 rescanUpdatedPackagesLocked(ownerUserId, user.getLastAppScanTime());
Makoto Onuki0acbb142016-03-22 17:02:57 -07003026 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07003027 } finally {
3028 logDurationStat(Stats.CHECK_PACKAGE_CHANGES, start);
Makoto Onuki0acbb142016-03-22 17:02:57 -07003029 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07003030 verifyStates();
Makoto Onukicdc78f72016-03-21 15:47:52 -07003031 }
3032
Andreas Gampea36dc622018-02-05 17:19:22 -08003033 @GuardedBy("mLock")
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003034 private void rescanUpdatedPackagesLocked(@UserIdInt int userId, long lastScanTime) {
Makoto Onuki377b7972016-08-09 14:43:55 -07003035 final ShortcutUser user = getUserShortcutsLocked(userId);
3036
Makoto Onuki33663282016-08-22 16:19:04 -07003037 // Note after each OTA, we'll need to rescan all system apps, as their lastUpdateTime
3038 // is not reliable.
Makoto Onuki377b7972016-08-09 14:43:55 -07003039 final long now = injectCurrentTimeMillis();
Makoto Onuki33663282016-08-22 16:19:04 -07003040 final boolean afterOta =
3041 !injectBuildFingerprint().equals(user.getLastAppScanOsFingerprint());
Makoto Onuki377b7972016-08-09 14:43:55 -07003042
3043 // Then for each installed app, publish manifest shortcuts when needed.
Makoto Onuki33663282016-08-22 16:19:04 -07003044 forUpdatedPackages(userId, lastScanTime, afterOta, ai -> {
Makoto Onuki377b7972016-08-09 14:43:55 -07003045 user.attemptToRestoreIfNeededAndSave(this, ai.packageName, userId);
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003046
3047 user.rescanPackageIfNeeded(ai.packageName, /* forceRescan= */ true);
Makoto Onuki377b7972016-08-09 14:43:55 -07003048 });
3049
3050 // Write the time just before the scan, because there may be apps that have just
3051 // been updated, and we want to catch them in the next time.
3052 user.setLastAppScanTime(now);
Makoto Onuki33663282016-08-22 16:19:04 -07003053 user.setLastAppScanOsFingerprint(injectBuildFingerprint());
Makoto Onuki377b7972016-08-09 14:43:55 -07003054 scheduleSaveUser(userId);
3055 }
3056
Makoto Onuki0acbb142016-03-22 17:02:57 -07003057 private void handlePackageAdded(String packageName, @UserIdInt int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07003058 if (DEBUG) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07003059 Slog.d(TAG, String.format("handlePackageAdded: %s user=%d", packageName, userId));
3060 }
3061 synchronized (mLock) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07003062 final ShortcutUser user = getUserShortcutsLocked(userId);
3063 user.attemptToRestoreIfNeededAndSave(this, packageName, userId);
Makoto Onuki64183d52016-08-08 14:11:34 -07003064 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onuki0acbb142016-03-22 17:02:57 -07003065 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07003066 verifyStates();
Makoto Onuki0acbb142016-03-22 17:02:57 -07003067 }
3068
3069 private void handlePackageUpdateFinished(String packageName, @UserIdInt int userId) {
Makoto Onuki905e8852016-03-28 10:40:58 -07003070 if (DEBUG) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003071 Slog.d(TAG, String.format("handlePackageUpdateFinished: %s user=%d",
3072 packageName, userId));
Makoto Onuki0acbb142016-03-22 17:02:57 -07003073 }
3074 synchronized (mLock) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07003075 final ShortcutUser user = getUserShortcutsLocked(userId);
3076 user.attemptToRestoreIfNeededAndSave(this, packageName, userId);
Makoto Onuki39686e82016-04-13 18:03:00 -07003077
Makoto Onuki22fcc682016-05-17 14:52:19 -07003078 if (isPackageInstalled(packageName, userId)) {
Makoto Onuki64183d52016-08-08 14:11:34 -07003079 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onuki39686e82016-04-13 18:03:00 -07003080 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07003081 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07003082 verifyStates();
Makoto Onuki0acbb142016-03-22 17:02:57 -07003083 }
3084
Makoto Onuki2e210c42016-03-30 08:30:36 -07003085 private void handlePackageRemoved(String packageName, @UserIdInt int packageUserId) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07003086 if (DEBUG) {
Makoto Onuki2e210c42016-03-30 08:30:36 -07003087 Slog.d(TAG, String.format("handlePackageRemoved: %s user=%d", packageName,
3088 packageUserId));
Makoto Onukicdc78f72016-03-21 15:47:52 -07003089 }
Makoto Onukib08790c2016-06-23 14:05:46 -07003090 cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ false);
Makoto Onuki9e1f5592016-06-08 12:30:23 -07003091
3092 verifyStates();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003093 }
3094
Makoto Onuki9ac59d02016-04-26 11:23:14 -07003095 private void handlePackageDataCleared(String packageName, int packageUserId) {
3096 if (DEBUG) {
3097 Slog.d(TAG, String.format("handlePackageDataCleared: %s user=%d", packageName,
3098 packageUserId));
Makoto Onukicdc78f72016-03-21 15:47:52 -07003099 }
Makoto Onukib08790c2016-06-23 14:05:46 -07003100 cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ true);
3101
3102 verifyStates();
3103 }
3104
3105 private void handlePackageChanged(String packageName, int packageUserId) {
Makoto Onuki82fb2eb2017-03-31 16:58:26 -07003106 if (!isPackageInstalled(packageName, packageUserId)) {
3107 // Probably disabled, which is the same thing as uninstalled.
3108 handlePackageRemoved(packageName, packageUserId);
3109 return;
3110 }
Makoto Onukib08790c2016-06-23 14:05:46 -07003111 if (DEBUG) {
3112 Slog.d(TAG, String.format("handlePackageChanged: %s user=%d", packageName,
3113 packageUserId));
3114 }
3115
3116 // Activities may be disabled or enabled. Just rescan the package.
3117 synchronized (mLock) {
3118 final ShortcutUser user = getUserShortcutsLocked(packageUserId);
3119
Makoto Onuki4e6cef42016-07-13 16:14:01 -07003120 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07003121 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07003122
3123 verifyStates();
Makoto Onukicdc78f72016-03-21 15:47:52 -07003124 }
3125
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003126 // === PackageManager interaction ===
Makoto Onuki0acbb142016-03-22 17:02:57 -07003127
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003128 /**
3129 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
3130 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07003131 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003132 final PackageInfo getPackageInfoWithSignatures(String packageName, @UserIdInt int userId) {
3133 return getPackageInfo(packageName, userId, true);
Makoto Onuki0acbb142016-03-22 17:02:57 -07003134 }
3135
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003136 /**
3137 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
3138 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07003139 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003140 final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId) {
3141 return getPackageInfo(packageName, userId, false);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003142 }
3143
Makoto Onuki905e8852016-03-28 10:40:58 -07003144 int injectGetPackageUid(@NonNull String packageName, @UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003145 final long token = injectClearCallingIdentity();
Makoto Onuki905e8852016-03-28 10:40:58 -07003146 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003147 return mIPackageManager.getPackageUid(packageName, PACKAGE_MATCH_FLAGS, userId);
Makoto Onuki905e8852016-03-28 10:40:58 -07003148 } catch (RemoteException e) {
3149 // Shouldn't happen.
3150 Slog.wtf(TAG, "RemoteException", e);
3151 return -1;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003152 } finally {
3153 injectRestoreCallingIdentity(token);
Makoto Onuki905e8852016-03-28 10:40:58 -07003154 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07003155 }
3156
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003157 /**
3158 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
3159 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07003160 @Nullable
Makoto Onuki0acbb142016-03-22 17:02:57 -07003161 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003162 final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId,
3163 boolean getSignatures) {
3164 return isInstalledOrNull(injectPackageInfoWithUninstalled(
3165 packageName, userId, getSignatures));
3166 }
3167
3168 /**
3169 * Do not use directly; this returns uninstalled packages too.
3170 */
3171 @Nullable
3172 @VisibleForTesting
3173 PackageInfo injectPackageInfoWithUninstalled(String packageName, @UserIdInt int userId,
Makoto Onuki0acbb142016-03-22 17:02:57 -07003174 boolean getSignatures) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003175 final long start = getStatStartTime();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003176 final long token = injectClearCallingIdentity();
Makoto Onuki0acbb142016-03-22 17:02:57 -07003177 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003178 return mIPackageManager.getPackageInfo(
3179 packageName, PACKAGE_MATCH_FLAGS
Michal Karpinski528c3e52018-02-07 17:47:10 +00003180 | (getSignatures ? PackageManager.GET_SIGNING_CERTIFICATES : 0),
3181 userId);
Makoto Onuki0acbb142016-03-22 17:02:57 -07003182 } 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(
3190 (getSignatures ? Stats.GET_PACKAGE_INFO_WITH_SIG : Stats.GET_PACKAGE_INFO),
3191 start);
Makoto Onuki0acbb142016-03-22 17:02:57 -07003192 }
3193 }
3194
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003195 /**
3196 * Returns {@link ApplicationInfo} unless it's uninstalled or disabled.
3197 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07003198 @Nullable
Makoto Onuki905e8852016-03-28 10:40:58 -07003199 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003200 final ApplicationInfo getApplicationInfo(String packageName, @UserIdInt int userId) {
3201 return isInstalledOrNull(injectApplicationInfoWithUninstalled(packageName, userId));
3202 }
3203
3204 /**
3205 * Do not use directly; this returns uninstalled packages too.
3206 */
3207 @Nullable
3208 @VisibleForTesting
3209 ApplicationInfo injectApplicationInfoWithUninstalled(
3210 String packageName, @UserIdInt int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003211 final long start = getStatStartTime();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003212 final long token = injectClearCallingIdentity();
Makoto Onuki905e8852016-03-28 10:40:58 -07003213 try {
3214 return mIPackageManager.getApplicationInfo(packageName, PACKAGE_MATCH_FLAGS, userId);
3215 } catch (RemoteException e) {
3216 // Shouldn't happen.
3217 Slog.wtf(TAG, "RemoteException", e);
3218 return null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003219 } finally {
3220 injectRestoreCallingIdentity(token);
Makoto Onuki2e210c42016-03-30 08:30:36 -07003221
3222 logDurationStat(Stats.GET_APPLICATION_INFO, start);
Makoto Onuki905e8852016-03-28 10:40:58 -07003223 }
3224 }
3225
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003226 /**
3227 * Returns {@link ActivityInfo} with its metadata unless it's uninstalled or disabled.
3228 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07003229 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003230 final ActivityInfo getActivityInfoWithMetadata(ComponentName activity, @UserIdInt int userId) {
3231 return isInstalledOrNull(injectGetActivityInfoWithMetadataWithUninstalled(
3232 activity, userId));
3233 }
3234
3235 /**
3236 * Do not use directly; this returns uninstalled packages too.
3237 */
3238 @Nullable
3239 @VisibleForTesting
3240 ActivityInfo injectGetActivityInfoWithMetadataWithUninstalled(
3241 ComponentName activity, @UserIdInt int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003242 final long start = getStatStartTime();
Makoto Onuki22fcc682016-05-17 14:52:19 -07003243 final long token = injectClearCallingIdentity();
3244 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07003245 return mIPackageManager.getActivityInfo(activity,
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003246 (PACKAGE_MATCH_FLAGS | PackageManager.GET_META_DATA), userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003247 } catch (RemoteException e) {
3248 // Shouldn't happen.
3249 Slog.wtf(TAG, "RemoteException", e);
3250 return null;
3251 } finally {
3252 injectRestoreCallingIdentity(token);
3253
Makoto Onukib08790c2016-06-23 14:05:46 -07003254 logDurationStat(Stats.GET_ACTIVITY_WITH_METADATA, start);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003255 }
3256 }
3257
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003258 /**
3259 * Return all installed and enabled packages.
3260 */
3261 @NonNull
Makoto Onuki22fcc682016-05-17 14:52:19 -07003262 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003263 final List<PackageInfo> getInstalledPackages(@UserIdInt int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003264 final long start = getStatStartTime();
Makoto Onuki22fcc682016-05-17 14:52:19 -07003265 final long token = injectClearCallingIdentity();
3266 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003267 final List<PackageInfo> all = injectGetPackagesWithUninstalled(userId);
3268
3269 all.removeIf(PACKAGE_NOT_INSTALLED);
3270
3271 return all;
Makoto Onuki22fcc682016-05-17 14:52:19 -07003272 } catch (RemoteException e) {
3273 // Shouldn't happen.
3274 Slog.wtf(TAG, "RemoteException", e);
3275 return null;
3276 } finally {
3277 injectRestoreCallingIdentity(token);
3278
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003279 logDurationStat(Stats.GET_INSTALLED_PACKAGES, start);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003280 }
3281 }
3282
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003283 /**
3284 * Do not use directly; this returns uninstalled packages too.
3285 */
3286 @NonNull
3287 @VisibleForTesting
3288 List<PackageInfo> injectGetPackagesWithUninstalled(@UserIdInt int userId)
3289 throws RemoteException {
3290 final ParceledListSlice<PackageInfo> parceledList =
3291 mIPackageManager.getInstalledPackages(PACKAGE_MATCH_FLAGS, userId);
3292 if (parceledList == null) {
3293 return Collections.emptyList();
3294 }
3295 return parceledList.getList();
3296 }
3297
Makoto Onuki33663282016-08-22 16:19:04 -07003298 private void forUpdatedPackages(@UserIdInt int userId, long lastScanTime, boolean afterOta,
Makoto Onuki22fcc682016-05-17 14:52:19 -07003299 Consumer<ApplicationInfo> callback) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003300 if (DEBUG) {
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003301 Slog.d(TAG, "forUpdatedPackages for user " + userId + ", lastScanTime=" + lastScanTime
3302 + " afterOta=" + afterOta);
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003303 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003304 final List<PackageInfo> list = getInstalledPackages(userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003305 for (int i = list.size() - 1; i >= 0; i--) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003306 final PackageInfo pi = list.get(i);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003307
Makoto Onuki64183d52016-08-08 14:11:34 -07003308 // If the package has been updated since the last scan time, then scan it.
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003309 // Also if it's right after an OTA, always re-scan all apps anyway, since the
3310 // shortcut parser might have changed.
3311 if (afterOta || (pi.lastUpdateTime >= lastScanTime)) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003312 if (DEBUG) {
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003313 Slog.d(TAG, "Found updated package " + pi.packageName
3314 + " updateTime=" + pi.lastUpdateTime);
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003315 }
3316 callback.accept(pi.applicationInfo);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003317 }
3318 }
3319 }
3320
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003321 private boolean isApplicationFlagSet(@NonNull String packageName, int userId, int flags) {
3322 final ApplicationInfo ai = injectApplicationInfoWithUninstalled(packageName, userId);
Makoto Onuki905e8852016-03-28 10:40:58 -07003323 return (ai != null) && ((ai.flags & flags) == flags);
3324 }
3325
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003326 private static boolean isInstalled(@Nullable ApplicationInfo ai) {
Makoto Onuki82fb2eb2017-03-31 16:58:26 -07003327 return (ai != null) && ai.enabled && (ai.flags & ApplicationInfo.FLAG_INSTALLED) != 0;
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003328 }
3329
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08003330 private static boolean isEphemeralApp(@Nullable ApplicationInfo ai) {
Svetoslav Ganov096d3042017-01-30 16:34:13 -08003331 return (ai != null) && ai.isInstantApp();
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08003332 }
3333
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003334 private static boolean isInstalled(@Nullable PackageInfo pi) {
3335 return (pi != null) && isInstalled(pi.applicationInfo);
3336 }
3337
3338 private static boolean isInstalled(@Nullable ActivityInfo ai) {
3339 return (ai != null) && isInstalled(ai.applicationInfo);
3340 }
3341
3342 private static ApplicationInfo isInstalledOrNull(ApplicationInfo ai) {
3343 return isInstalled(ai) ? ai : null;
3344 }
3345
3346 private static PackageInfo isInstalledOrNull(PackageInfo pi) {
3347 return isInstalled(pi) ? pi : null;
3348 }
3349
3350 private static ActivityInfo isInstalledOrNull(ActivityInfo ai) {
3351 return isInstalled(ai) ? ai : null;
3352 }
3353
Makoto Onuki2e210c42016-03-30 08:30:36 -07003354 boolean isPackageInstalled(String packageName, int userId) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003355 return getApplicationInfo(packageName, userId) != null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003356 }
3357
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08003358 boolean isEphemeralApp(String packageName, int userId) {
3359 return isEphemeralApp(getApplicationInfo(packageName, userId));
3360 }
3361
Makoto Onuki22fcc682016-05-17 14:52:19 -07003362 @Nullable
3363 XmlResourceParser injectXmlMetaData(ActivityInfo activityInfo, String key) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07003364 return activityInfo.loadXmlMetaData(mContext.getPackageManager(), key);
Makoto Onuki39686e82016-04-13 18:03:00 -07003365 }
3366
Makoto Onuki157b1622016-06-02 16:13:10 -07003367 @Nullable
3368 Resources injectGetResourcesForApplicationAsUser(String packageName, int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003369 final long start = getStatStartTime();
Makoto Onuki157b1622016-06-02 16:13:10 -07003370 final long token = injectClearCallingIdentity();
3371 try {
3372 return mContext.getPackageManager().getResourcesForApplicationAsUser(
3373 packageName, userId);
3374 } catch (NameNotFoundException e) {
3375 Slog.e(TAG, "Resources for package " + packageName + " not found");
3376 return null;
3377 } finally {
3378 injectRestoreCallingIdentity(token);
3379
3380 logDurationStat(Stats.GET_APPLICATION_RESOURCES, start);
3381 }
3382 }
3383
Makoto Onukib08790c2016-06-23 14:05:46 -07003384 private Intent getMainActivityIntent() {
3385 final Intent intent = new Intent(Intent.ACTION_MAIN);
3386 intent.addCategory(LAUNCHER_INTENT_CATEGORY);
3387 return intent;
3388 }
3389
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003390 /**
3391 * Same as queryIntentActivitiesAsUser, except it makes sure the package is installed,
3392 * and only returns exported activities.
3393 */
3394 @NonNull
3395 @VisibleForTesting
3396 List<ResolveInfo> queryActivities(@NonNull Intent baseIntent,
3397 @NonNull String packageName, @Nullable ComponentName activity, int userId) {
3398
3399 baseIntent.setPackage(Preconditions.checkNotNull(packageName));
3400 if (activity != null) {
3401 baseIntent.setComponent(activity);
3402 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08003403 return queryActivities(baseIntent, userId, /* exportedOnly =*/ true);
3404 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003405
Makoto Onuki2d895c32016-12-02 15:48:40 -08003406 @NonNull
3407 List<ResolveInfo> queryActivities(@NonNull Intent intent, int userId,
3408 boolean exportedOnly) {
3409 final List<ResolveInfo> resolved;
3410 final long token = injectClearCallingIdentity();
3411 try {
3412 resolved =
3413 mContext.getPackageManager().queryIntentActivitiesAsUser(
3414 intent, PACKAGE_MATCH_FLAGS, userId);
3415 } finally {
3416 injectRestoreCallingIdentity(token);
3417 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003418 if (resolved == null || resolved.size() == 0) {
3419 return EMPTY_RESOLVE_INFO;
3420 }
3421 // Make sure the package is installed.
3422 if (!isInstalled(resolved.get(0).activityInfo)) {
3423 return EMPTY_RESOLVE_INFO;
3424 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08003425 if (exportedOnly) {
3426 resolved.removeIf(ACTIVITY_NOT_EXPORTED);
3427 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003428 return resolved;
3429 }
3430
3431 /**
3432 * Return the main activity that is enabled and exported. If multiple activities are found,
3433 * return the first one.
3434 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003435 @Nullable
3436 ComponentName injectGetDefaultMainActivity(@NonNull String packageName, int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003437 final long start = getStatStartTime();
Makoto Onukib08790c2016-06-23 14:05:46 -07003438 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07003439 final List<ResolveInfo> resolved =
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003440 queryActivities(getMainActivityIntent(), packageName, null, userId);
3441 return resolved.size() == 0 ? null : resolved.get(0).activityInfo.getComponentName();
Makoto Onukib08790c2016-06-23 14:05:46 -07003442 } finally {
Makoto Onukib08790c2016-06-23 14:05:46 -07003443 logDurationStat(Stats.GET_LAUNCHER_ACTIVITY, start);
3444 }
3445 }
3446
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003447 /**
3448 * Return whether an activity is enabled, exported and main.
3449 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003450 boolean injectIsMainActivity(@NonNull ComponentName activity, int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003451 final long start = getStatStartTime();
Makoto Onukib08790c2016-06-23 14:05:46 -07003452 try {
Makoto Onuki34145532017-03-14 17:58:36 -07003453 if (activity == null) {
3454 wtf("null activity detected");
3455 return false;
3456 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08003457 if (DUMMY_MAIN_ACTIVITY.equals(activity.getClassName())) {
3458 return true;
3459 }
3460 final List<ResolveInfo> resolved = queryActivities(
3461 getMainActivityIntent(), activity.getPackageName(), activity, userId);
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003462 return resolved.size() > 0;
Makoto Onukib08790c2016-06-23 14:05:46 -07003463 } finally {
Makoto Onukib08790c2016-06-23 14:05:46 -07003464 logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start);
3465 }
3466 }
3467
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003468 /**
Makoto Onuki2d895c32016-12-02 15:48:40 -08003469 * Create a dummy "main activity" component name which is used to create a dynamic shortcut
3470 * with no main activity temporarily.
3471 */
3472 @NonNull
3473 ComponentName getDummyMainActivity(@NonNull String packageName) {
3474 return new ComponentName(packageName, DUMMY_MAIN_ACTIVITY);
3475 }
3476
Makoto Onuki255461f2017-01-10 11:47:25 -08003477 boolean isDummyMainActivity(@Nullable ComponentName name) {
3478 return name != null && DUMMY_MAIN_ACTIVITY.equals(name.getClassName());
3479 }
3480
Makoto Onuki2d895c32016-12-02 15:48:40 -08003481 /**
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003482 * Return all the enabled, exported and main activities from a package.
3483 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003484 @NonNull
3485 List<ResolveInfo> injectGetMainActivities(@NonNull String packageName, int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003486 final long start = getStatStartTime();
Makoto Onukib08790c2016-06-23 14:05:46 -07003487 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003488 return queryActivities(getMainActivityIntent(), packageName, null, userId);
Makoto Onukib08790c2016-06-23 14:05:46 -07003489 } finally {
Makoto Onukib08790c2016-06-23 14:05:46 -07003490 logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start);
3491 }
3492 }
3493
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003494 /**
3495 * Return whether an activity is enabled and exported.
3496 */
3497 @VisibleForTesting
3498 boolean injectIsActivityEnabledAndExported(
3499 @NonNull ComponentName activity, @UserIdInt int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003500 final long start = getStatStartTime();
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003501 try {
3502 return queryActivities(new Intent(), activity.getPackageName(), activity, userId)
3503 .size() > 0;
3504 } finally {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003505 logDurationStat(Stats.IS_ACTIVITY_ENABLED, start);
3506 }
3507 }
3508
Makoto Onuki2d895c32016-12-02 15:48:40 -08003509 /**
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003510 * Get the {@link LauncherApps#ACTION_CONFIRM_PIN_SHORTCUT} or
3511 * {@link LauncherApps#ACTION_CONFIRM_PIN_APPWIDGET} activity in a given package depending on
3512 * the requestType.
Makoto Onuki2d895c32016-12-02 15:48:40 -08003513 */
3514 @Nullable
3515 ComponentName injectGetPinConfirmationActivity(@NonNull String launcherPackageName,
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003516 int launcherUserId, int requestType) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08003517 Preconditions.checkNotNull(launcherPackageName);
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003518 String action = requestType == LauncherApps.PinItemRequest.REQUEST_TYPE_SHORTCUT ?
3519 LauncherApps.ACTION_CONFIRM_PIN_SHORTCUT :
3520 LauncherApps.ACTION_CONFIRM_PIN_APPWIDGET;
Makoto Onuki2d895c32016-12-02 15:48:40 -08003521
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003522 final Intent confirmIntent = new Intent(action).setPackage(launcherPackageName);
Makoto Onuki2d895c32016-12-02 15:48:40 -08003523 final List<ResolveInfo> candidates = queryActivities(
3524 confirmIntent, launcherUserId, /* exportedOnly =*/ false);
3525 for (ResolveInfo ri : candidates) {
3526 return ri.activityInfo.getComponentName();
3527 }
3528 return null;
3529 }
3530
Makoto Onukib08790c2016-06-23 14:05:46 -07003531 boolean injectIsSafeModeEnabled() {
3532 final long token = injectClearCallingIdentity();
3533 try {
3534 return IWindowManager.Stub
3535 .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE))
3536 .isSafeModeEnabled();
3537 } catch (RemoteException e) {
3538 return false; // Shouldn't happen though.
3539 } finally {
3540 injectRestoreCallingIdentity(token);
3541 }
3542 }
3543
Makoto Onuki2d895c32016-12-02 15:48:40 -08003544 /**
3545 * If {@code userId} is of a managed profile, return the parent user ID. Otherwise return
3546 * itself.
3547 */
3548 int getParentOrSelfUserId(int userId) {
Sunny Goyal145c8f82018-02-15 14:27:09 -08003549 return mUserManagerInternal.getProfileParentId(userId);
Makoto Onuki2d895c32016-12-02 15:48:40 -08003550 }
3551
Sunny Goyal87a563e2017-01-01 19:42:45 -08003552 void injectSendIntentSender(IntentSender intentSender, Intent extras) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08003553 if (intentSender == null) {
3554 return;
3555 }
3556 try {
Sunny Goyal87a563e2017-01-01 19:42:45 -08003557 intentSender.sendIntent(mContext, /* code= */ 0, extras,
Makoto Onuki2d895c32016-12-02 15:48:40 -08003558 /* onFinished=*/ null, /* handler= */ null);
3559 } catch (SendIntentException e) {
3560 Slog.w(TAG, "sendIntent failed().", e);
3561 }
3562 }
3563
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003564 // === Backup & restore ===
3565
Makoto Onuki0acbb142016-03-22 17:02:57 -07003566 boolean shouldBackupApp(String packageName, int userId) {
Makoto Onuki905e8852016-03-28 10:40:58 -07003567 return isApplicationFlagSet(packageName, userId, ApplicationInfo.FLAG_ALLOW_BACKUP);
Makoto Onuki0acbb142016-03-22 17:02:57 -07003568 }
3569
Makoto Onukia4f89b12017-10-05 10:37:55 -07003570 static boolean shouldBackupApp(PackageInfo pi) {
Makoto Onuki2e210c42016-03-30 08:30:36 -07003571 return (pi.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0;
3572 }
3573
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003574 @Override
Makoto Onuki2e210c42016-03-30 08:30:36 -07003575 public byte[] getBackupPayload(@UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003576 enforceSystem();
3577 if (DEBUG) {
3578 Slog.d(TAG, "Backing up user " + userId);
3579 }
3580 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003581 if (!isUserUnlockedL(userId)) {
3582 wtf("Can't backup: user " + userId + " is locked or not running");
3583 return null;
3584 }
3585
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003586 final ShortcutUser user = getUserShortcutsLocked(userId);
3587 if (user == null) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003588 wtf("Can't backup: user not found: id=" + userId);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003589 return null;
3590 }
3591
Makoto Onukic8c33292016-09-12 16:36:59 -07003592 // Update the signatures for all packages.
3593 user.forAllPackageItems(spi -> spi.refreshPackageSignatureAndSave());
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003594
Makoto Onukie3fffa92018-02-28 16:25:40 -08003595 // Rescan all apps; this will also update the version codes and "allow-backup".
3596 user.forAllPackages(pkg -> pkg.rescanPackageIfNeeded(
3597 /*isNewApp=*/ false, /*forceRescan=*/ true));
3598
Makoto Onukic8c33292016-09-12 16:36:59 -07003599 // Set the version code for the launchers.
Makoto Onukia4f89b12017-10-05 10:37:55 -07003600 user.forAllLaunchers(launcher -> launcher.ensurePackageInfo());
Makoto Onukic8c33292016-09-12 16:36:59 -07003601
3602 // Save to the filesystem.
3603 scheduleSaveUser(userId);
3604 saveDirtyInfo();
3605
Makoto Onuki475c3652017-05-08 14:29:03 -07003606 // Note, in case of backup, we don't have to wait on bitmap saving, because we don't
3607 // back up bitmaps anyway.
3608
Makoto Onukic8c33292016-09-12 16:36:59 -07003609 // Then create the backup payload.
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003610 final ByteArrayOutputStream os = new ByteArrayOutputStream(32 * 1024);
3611 try {
3612 saveUserInternalLocked(userId, os, /* forBackup */ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07003613 } catch (XmlPullParserException | IOException e) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003614 // Shouldn't happen.
3615 Slog.w(TAG, "Backup failed.", e);
3616 return null;
3617 }
Makoto Onukie3fffa92018-02-28 16:25:40 -08003618 byte[] payload = os.toByteArray();
3619 mShortcutDumpFiles.save("backup-1-payload.txt", payload);
3620 return payload;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003621 }
3622 }
3623
3624 @Override
Makoto Onuki2e210c42016-03-30 08:30:36 -07003625 public void applyRestore(byte[] payload, @UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003626 enforceSystem();
3627 if (DEBUG) {
3628 Slog.d(TAG, "Restoring user " + userId);
3629 }
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003630 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003631 if (!isUserUnlockedL(userId)) {
3632 wtf("Can't restore: user " + userId + " is locked or not running");
3633 return;
3634 }
Makoto Onuki50a320e2017-05-31 14:38:42 -07003635
3636 // Note we print the file timestamps in dumpsys too, but also printing the timestamp
3637 // in the files anyway.
3638 mShortcutDumpFiles.save("restore-0-start.txt", pw -> {
3639 pw.print("Start time: ");
3640 dumpCurrentTime(pw);
3641 pw.println();
3642 });
3643 mShortcutDumpFiles.save("restore-1-payload.xml", payload);
3644
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003645 // Actually do restore.
3646 final ShortcutUser restored;
Makoto Onuki02f338e2016-07-29 09:40:40 -07003647 final ByteArrayInputStream is = new ByteArrayInputStream(payload);
3648 try {
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003649 restored = loadUserInternal(userId, is, /* fromBackup */ true);
3650 } catch (XmlPullParserException | IOException | InvalidFileFormatException e) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003651 Slog.w(TAG, "Restoration failed.", e);
3652 return;
3653 }
Makoto Onuki50a320e2017-05-31 14:38:42 -07003654 mShortcutDumpFiles.save("restore-2.txt", this::dumpInner);
3655
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003656 getUserShortcutsLocked(userId).mergeRestoredFile(restored);
Makoto Onuki2e210c42016-03-30 08:30:36 -07003657
Makoto Onuki50a320e2017-05-31 14:38:42 -07003658 mShortcutDumpFiles.save("restore-3.txt", this::dumpInner);
3659
Makoto Onuki377b7972016-08-09 14:43:55 -07003660 // Rescan all packages to re-publish manifest shortcuts and do other checks.
3661 rescanUpdatedPackagesLocked(userId,
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003662 0 // lastScanTime = 0; rescan all packages.
3663 );
Makoto Onuki2e210c42016-03-30 08:30:36 -07003664
Makoto Onuki50a320e2017-05-31 14:38:42 -07003665 mShortcutDumpFiles.save("restore-4.txt", this::dumpInner);
3666
3667 mShortcutDumpFiles.save("restore-5-finish.txt", pw -> {
3668 pw.print("Finish time: ");
3669 dumpCurrentTime(pw);
3670 pw.println();
3671 });
3672
Makoto Onuki2e210c42016-03-30 08:30:36 -07003673 saveUserLocked(userId);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003674 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07003675 }
3676
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003677 // === Dump ===
3678
3679 @Override
3680 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06003681 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
Makoto Onukic4361e32017-04-03 11:24:25 -07003682 dumpNoCheck(fd, pw, args);
3683 }
3684
3685 @VisibleForTesting
3686 void dumpNoCheck(FileDescriptor fd, PrintWriter pw, String[] args) {
Makoto Onuki20b82212017-10-04 15:03:50 -07003687 final DumpFilter filter = parseDumpArgs(args);
Makoto Onuki50a320e2017-05-31 14:38:42 -07003688
Makoto Onuki20b82212017-10-04 15:03:50 -07003689 if (filter.shouldDumpCheckIn()) {
Makoto Onuki50a320e2017-05-31 14:38:42 -07003690 // Other flags are not supported for checkin.
Makoto Onuki20b82212017-10-04 15:03:50 -07003691 dumpCheckin(pw, filter.shouldCheckInClear());
Makoto Onuki76269922016-07-15 14:58:54 -07003692 } else {
Makoto Onuki20b82212017-10-04 15:03:50 -07003693 if (filter.shouldDumpMain()) {
3694 dumpInner(pw, filter);
Makoto Onuki50a320e2017-05-31 14:38:42 -07003695 pw.println();
3696 }
Makoto Onuki20b82212017-10-04 15:03:50 -07003697 if (filter.shouldDumpUid()) {
Makoto Onuki50a320e2017-05-31 14:38:42 -07003698 dumpUid(pw);
3699 pw.println();
3700 }
Makoto Onuki20b82212017-10-04 15:03:50 -07003701 if (filter.shouldDumpFiles()) {
Makoto Onuki50a320e2017-05-31 14:38:42 -07003702 dumpDumpFiles(pw);
3703 pw.println();
3704 }
Makoto Onuki76269922016-07-15 14:58:54 -07003705 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003706 }
3707
Makoto Onuki20b82212017-10-04 15:03:50 -07003708 private static DumpFilter parseDumpArgs(String[] args) {
3709 final DumpFilter filter = new DumpFilter();
3710 if (args == null) {
3711 return filter;
3712 }
Makoto Onuki55046222016-03-08 10:49:47 -08003713
Makoto Onuki20b82212017-10-04 15:03:50 -07003714 int argIndex = 0;
3715 while (argIndex < args.length) {
3716 final String arg = args[argIndex++];
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003717
Makoto Onuki20b82212017-10-04 15:03:50 -07003718 if ("-c".equals(arg)) {
3719 filter.setDumpCheckIn(true);
3720 continue;
3721 }
3722 if ("--checkin".equals(arg)) {
3723 filter.setDumpCheckIn(true);
3724 filter.setCheckInClear(true);
3725 continue;
3726 }
3727 if ("-a".equals(arg) || "--all".equals(arg)) {
3728 filter.setDumpUid(true);
3729 filter.setDumpFiles(true);
3730 continue;
3731 }
3732 if ("-u".equals(arg) || "--uid".equals(arg)) {
3733 filter.setDumpUid(true);
3734 continue;
3735 }
3736 if ("-f".equals(arg) || "--files".equals(arg)) {
3737 filter.setDumpFiles(true);
3738 continue;
3739 }
3740 if ("-n".equals(arg) || "--no-main".equals(arg)) {
3741 filter.setDumpMain(false);
3742 continue;
3743 }
3744 if ("--user".equals(arg)) {
3745 if (argIndex >= args.length) {
3746 throw new IllegalArgumentException("Missing user ID for --user");
3747 }
3748 try {
3749 filter.addUser(Integer.parseInt(args[argIndex++]));
3750 } catch (NumberFormatException e) {
3751 throw new IllegalArgumentException("Invalid user ID", e);
3752 }
3753 continue;
3754 }
3755 if ("-p".equals(arg) || "--package".equals(arg)) {
3756 if (argIndex >= args.length) {
3757 throw new IllegalArgumentException("Missing package name for --package");
3758 }
3759 filter.addPackageRegex(args[argIndex++]);
3760 filter.setDumpDetails(false);
3761 continue;
3762 }
3763 if (arg.startsWith("-")) {
3764 throw new IllegalArgumentException("Unknown option " + arg);
3765 }
3766 break;
3767 }
3768 while (argIndex < args.length) {
3769 filter.addPackage(args[argIndex++]);
3770 }
3771 return filter;
3772 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003773
Makoto Onuki20b82212017-10-04 15:03:50 -07003774 static class DumpFilter {
3775 private boolean mDumpCheckIn = false;
3776 private boolean mCheckInClear = false;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003777
Makoto Onuki20b82212017-10-04 15:03:50 -07003778 private boolean mDumpMain = true;
3779 private boolean mDumpUid = false;
3780 private boolean mDumpFiles = false;
Makoto Onuki55046222016-03-08 10:49:47 -08003781
Makoto Onuki20b82212017-10-04 15:03:50 -07003782 private boolean mDumpDetails = true;
3783 private List<Pattern> mPackagePatterns = new ArrayList<>();
3784 private List<Integer> mUsers = new ArrayList<>();
3785
3786 void addPackageRegex(String regex) {
3787 mPackagePatterns.add(Pattern.compile(regex));
3788 }
3789
3790 public void addPackage(String packageName) {
3791 addPackageRegex(Pattern.quote(packageName));
3792 }
3793
3794 void addUser(int userId) {
3795 mUsers.add(userId);
3796 }
3797
3798 boolean isPackageMatch(String packageName) {
3799 if (mPackagePatterns.size() == 0) {
3800 return true;
3801 }
3802 for (int i = 0; i < mPackagePatterns.size(); i++) {
3803 if (mPackagePatterns.get(i).matcher(packageName).find()) {
3804 return true;
Makoto Onuki085a05c2016-08-19 11:39:29 -07003805 }
Makoto Onuki2e210c42016-03-30 08:30:36 -07003806 }
Makoto Onuki20b82212017-10-04 15:03:50 -07003807 return false;
3808 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003809
Makoto Onuki20b82212017-10-04 15:03:50 -07003810 boolean isUserMatch(int userId) {
3811 if (mUsers.size() == 0) {
3812 return true;
3813 }
3814 for (int i = 0; i < mUsers.size(); i++) {
3815 if (mUsers.get(i) == userId) {
3816 return true;
3817 }
3818 }
3819 return false;
3820 }
Makoto Onukia2241832016-07-06 13:28:37 -07003821
Makoto Onuki20b82212017-10-04 15:03:50 -07003822 public boolean shouldDumpCheckIn() {
3823 return mDumpCheckIn;
3824 }
3825
3826 public void setDumpCheckIn(boolean dumpCheckIn) {
3827 mDumpCheckIn = dumpCheckIn;
3828 }
3829
3830 public boolean shouldCheckInClear() {
3831 return mCheckInClear;
3832 }
3833
3834 public void setCheckInClear(boolean checkInClear) {
3835 mCheckInClear = checkInClear;
3836 }
3837
3838 public boolean shouldDumpMain() {
3839 return mDumpMain;
3840 }
3841
3842 public void setDumpMain(boolean dumpMain) {
3843 mDumpMain = dumpMain;
3844 }
3845
3846 public boolean shouldDumpUid() {
3847 return mDumpUid;
3848 }
3849
3850 public void setDumpUid(boolean dumpUid) {
3851 mDumpUid = dumpUid;
3852 }
3853
3854 public boolean shouldDumpFiles() {
3855 return mDumpFiles;
3856 }
3857
3858 public void setDumpFiles(boolean dumpFiles) {
3859 mDumpFiles = dumpFiles;
3860 }
3861
3862 public boolean shouldDumpDetails() {
3863 return mDumpDetails;
3864 }
3865
3866 public void setDumpDetails(boolean dumpDetails) {
3867 mDumpDetails = dumpDetails;
3868 }
3869 }
3870
3871 private void dumpInner(PrintWriter pw) {
3872 dumpInner(pw, new DumpFilter());
3873 }
3874
3875 private void dumpInner(PrintWriter pw, DumpFilter filter) {
3876 synchronized (mLock) {
3877 if (filter.shouldDumpDetails()) {
3878 final long now = injectCurrentTimeMillis();
3879 pw.print("Now: [");
3880 pw.print(now);
3881 pw.print("] ");
3882 pw.print(formatTime(now));
3883
3884 pw.print(" Raw last reset: [");
3885 pw.print(mRawLastResetTime);
3886 pw.print("] ");
3887 pw.print(formatTime(mRawLastResetTime));
3888
3889 final long last = getLastResetTimeLocked();
3890 pw.print(" Last reset: [");
3891 pw.print(last);
3892 pw.print("] ");
3893 pw.print(formatTime(last));
3894
3895 final long next = getNextResetTimeLocked();
3896 pw.print(" Next reset: [");
3897 pw.print(next);
3898 pw.print("] ");
3899 pw.print(formatTime(next));
Makoto Onukie3fffa92018-02-28 16:25:40 -08003900 pw.println();
3901 pw.println();
Makoto Onuki20b82212017-10-04 15:03:50 -07003902
3903 pw.print(" Config:");
3904 pw.print(" Max icon dim: ");
3905 pw.println(mMaxIconDimension);
3906 pw.print(" Icon format: ");
3907 pw.println(mIconPersistFormat);
3908 pw.print(" Icon quality: ");
3909 pw.println(mIconPersistQuality);
3910 pw.print(" saveDelayMillis: ");
3911 pw.println(mSaveDelayMillis);
3912 pw.print(" resetInterval: ");
3913 pw.println(mResetInterval);
3914 pw.print(" maxUpdatesPerInterval: ");
3915 pw.println(mMaxUpdatesPerInterval);
3916 pw.print(" maxShortcutsPerActivity: ");
3917 pw.println(mMaxShortcuts);
3918 pw.println();
3919
Makoto Onuki84d59342018-02-02 09:22:38 -08003920 mStatLogger.dump(pw, " ");
Makoto Onuki20b82212017-10-04 15:03:50 -07003921
3922 pw.println();
3923 pw.print(" #Failures: ");
3924 pw.println(mWtfCount);
3925
3926 if (mLastWtfStacktrace != null) {
3927 pw.print(" Last failure stack trace: ");
3928 pw.println(Log.getStackTraceString(mLastWtfStacktrace));
3929 }
3930
3931 pw.println();
3932 mShortcutBitmapSaver.dumpLocked(pw, " ");
3933
3934 pw.println();
Makoto Onukia2241832016-07-06 13:28:37 -07003935 }
3936
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08003937 for (int i = 0; i < mUsers.size(); i++) {
Makoto Onuki20b82212017-10-04 15:03:50 -07003938 final ShortcutUser user = mUsers.valueAt(i);
3939 if (filter.isUserMatch(user.getUserId())) {
3940 user.dump(pw, " ", filter);
3941 pw.println();
3942 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003943 }
Makoto Onuki708703b2017-12-11 16:38:11 -08003944
3945 for (int i = 0; i < mShortcutNonPersistentUsers.size(); i++) {
3946 final ShortcutNonPersistentUser user = mShortcutNonPersistentUsers.valueAt(i);
3947 if (filter.isUserMatch(user.getUserId())) {
3948 user.dump(pw, " ", filter);
3949 pw.println();
3950 }
3951 }
Makoto Onuki50a320e2017-05-31 14:38:42 -07003952 }
3953 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003954
Makoto Onuki50a320e2017-05-31 14:38:42 -07003955 private void dumpUid(PrintWriter pw) {
3956 synchronized (mLock) {
3957 pw.println("** SHORTCUT MANAGER UID STATES (dumpsys shortcut -n -u)");
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003958
3959 for (int i = 0; i < mUidState.size(); i++) {
3960 final int uid = mUidState.keyAt(i);
3961 final int state = mUidState.valueAt(i);
3962 pw.print(" UID=");
3963 pw.print(uid);
3964 pw.print(" state=");
3965 pw.print(state);
3966 if (isProcessStateForeground(state)) {
3967 pw.print(" [FG]");
3968 }
3969 pw.print(" last FG=");
3970 pw.print(mUidLastForegroundElapsedTime.get(uid));
3971 pw.println();
3972 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003973 }
3974 }
3975
Makoto Onuki41066a62016-03-09 16:18:44 -08003976 static String formatTime(long time) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003977 Time tobj = new Time();
3978 tobj.set(time);
3979 return tobj.format("%Y-%m-%d %H:%M:%S");
3980 }
3981
Makoto Onuki50a320e2017-05-31 14:38:42 -07003982 private void dumpCurrentTime(PrintWriter pw) {
3983 pw.print(formatTime(injectCurrentTimeMillis()));
3984 }
3985
Makoto Onuki76269922016-07-15 14:58:54 -07003986 /**
3987 * Dumpsys for checkin.
3988 *
3989 * @param clear if true, clear the history information. Some other system services have this
3990 * behavior but shortcut service doesn't for now.
3991 */
3992 private void dumpCheckin(PrintWriter pw, boolean clear) {
3993 synchronized (mLock) {
3994 try {
3995 final JSONArray users = new JSONArray();
3996
3997 for (int i = 0; i < mUsers.size(); i++) {
3998 users.put(mUsers.valueAt(i).dumpCheckin(clear));
3999 }
4000
4001 final JSONObject result = new JSONObject();
4002
4003 result.put(KEY_SHORTCUT, users);
4004 result.put(KEY_LOW_RAM, injectIsLowRamDevice());
4005 result.put(KEY_ICON_SIZE, mMaxIconDimension);
4006
4007 pw.println(result.toString(1));
4008 } catch (JSONException e) {
4009 Slog.e(TAG, "Unable to write in json", e);
4010 }
4011 }
4012 }
4013
Makoto Onuki50a320e2017-05-31 14:38:42 -07004014 private void dumpDumpFiles(PrintWriter pw) {
4015 synchronized (mLock) {
4016 pw.println("** SHORTCUT MANAGER FILES (dumpsys shortcut -n -f)");
4017 mShortcutDumpFiles.dumpAll(pw);
4018 }
4019 }
4020
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004021 // === Shell support ===
4022
4023 @Override
4024 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07004025 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004026
4027 enforceShell();
4028
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07004029 final long token = injectClearCallingIdentity();
4030 try {
Dianne Hackborn354736e2016-08-22 17:00:05 -07004031 final int status = (new MyShellCommand()).exec(this, in, out, err, args, callback,
4032 resultReceiver);
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07004033 resultReceiver.send(status, null);
4034 } finally {
4035 injectRestoreCallingIdentity(token);
4036 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004037 }
4038
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004039 static class CommandException extends Exception {
4040 public CommandException(String message) {
4041 super(message);
4042 }
4043 }
4044
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004045 /**
4046 * Handle "adb shell cmd".
4047 */
4048 private class MyShellCommand extends ShellCommand {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004049
4050 private int mUserId = UserHandle.USER_SYSTEM;
4051
Makoto Onuki02f338e2016-07-29 09:40:40 -07004052 private void parseOptionsLocked(boolean takeUser)
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004053 throws CommandException {
4054 String opt;
4055 while ((opt = getNextOption()) != null) {
4056 switch (opt) {
4057 case "--user":
4058 if (takeUser) {
4059 mUserId = UserHandle.parseUserArg(getNextArgRequired());
Makoto Onuki02f338e2016-07-29 09:40:40 -07004060 if (!isUserUnlockedL(mUserId)) {
Makoto Onukif34c3082016-07-13 10:25:25 -07004061 throw new CommandException(
4062 "User " + mUserId + " is not running or locked");
4063 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004064 break;
4065 }
4066 // fallthrough
4067 default:
4068 throw new CommandException("Unknown option: " + opt);
4069 }
4070 }
4071 }
4072
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004073 @Override
4074 public int onCommand(String cmd) {
4075 if (cmd == null) {
4076 return handleDefaultCommands(cmd);
4077 }
4078 final PrintWriter pw = getOutPrintWriter();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004079 try {
4080 switch (cmd) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004081 case "reset-throttling":
4082 handleResetThrottling();
4083 break;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004084 case "reset-all-throttling":
4085 handleResetAllThrottling();
4086 break;
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004087 case "override-config":
4088 handleOverrideConfig();
4089 break;
4090 case "reset-config":
4091 handleResetConfig();
4092 break;
4093 case "clear-default-launcher":
4094 handleClearDefaultLauncher();
4095 break;
4096 case "get-default-launcher":
4097 handleGetDefaultLauncher();
4098 break;
Makoto Onukiac214972016-04-04 10:19:45 -07004099 case "unload-user":
4100 handleUnloadUser();
4101 break;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004102 case "clear-shortcuts":
4103 handleClearShortcuts();
4104 break;
Makoto Onukib08790c2016-06-23 14:05:46 -07004105 case "verify-states": // hidden command to verify various internal states.
4106 handleVerifyStates();
4107 break;
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004108 default:
4109 return handleDefaultCommands(cmd);
4110 }
4111 } catch (CommandException e) {
4112 pw.println("Error: " + e.getMessage());
4113 return 1;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004114 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004115 pw.println("Success");
4116 return 0;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004117 }
4118
4119 @Override
4120 public void onHelp() {
4121 final PrintWriter pw = getOutPrintWriter();
4122 pw.println("Usage: cmd shortcut COMMAND [options ...]");
4123 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004124 pw.println("cmd shortcut reset-throttling [--user USER_ID]");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004125 pw.println(" Reset throttling for all packages and users");
4126 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004127 pw.println("cmd shortcut reset-all-throttling");
4128 pw.println(" Reset the throttling state for all users");
4129 pw.println();
Makoto Onuki4362a662016-03-08 18:59:09 -08004130 pw.println("cmd shortcut override-config CONFIG");
4131 pw.println(" Override the configuration for testing (will last until reboot)");
4132 pw.println();
4133 pw.println("cmd shortcut reset-config");
4134 pw.println(" Reset the configuration set with \"update-config\"");
4135 pw.println();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004136 pw.println("cmd shortcut clear-default-launcher [--user USER_ID]");
4137 pw.println(" Clear the cached default launcher");
4138 pw.println();
4139 pw.println("cmd shortcut get-default-launcher [--user USER_ID]");
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07004140 pw.println(" Show the default launcher");
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004141 pw.println();
Makoto Onukiac214972016-04-04 10:19:45 -07004142 pw.println("cmd shortcut unload-user [--user USER_ID]");
4143 pw.println(" Unload a user from the memory");
4144 pw.println(" (This should not affect any observable behavior)");
4145 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004146 pw.println("cmd shortcut clear-shortcuts [--user USER_ID] PACKAGE");
4147 pw.println(" Remove all shortcuts from a package, including pinned shortcuts");
4148 pw.println();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004149 }
4150
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004151 private void handleResetThrottling() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07004152 synchronized (mLock) {
4153 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki4554d0e2016-03-14 15:51:41 -07004154
Makoto Onuki02f338e2016-07-29 09:40:40 -07004155 Slog.i(TAG, "cmd: handleResetThrottling: user=" + mUserId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004156
Makoto Onuki02f338e2016-07-29 09:40:40 -07004157 resetThrottlingInner(mUserId);
4158 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004159 }
4160
4161 private void handleResetAllThrottling() {
4162 Slog.i(TAG, "cmd: handleResetAllThrottling");
4163
4164 resetAllThrottlingInner();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004165 }
4166
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004167 private void handleOverrideConfig() throws CommandException {
Makoto Onuki4362a662016-03-08 18:59:09 -08004168 final String config = getNextArgRequired();
4169
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004170 Slog.i(TAG, "cmd: handleOverrideConfig: " + config);
4171
Makoto Onuki4362a662016-03-08 18:59:09 -08004172 synchronized (mLock) {
4173 if (!updateConfigurationLocked(config)) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004174 throw new CommandException("override-config failed. See logcat for details.");
Makoto Onuki4362a662016-03-08 18:59:09 -08004175 }
4176 }
Makoto Onuki4362a662016-03-08 18:59:09 -08004177 }
4178
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004179 private void handleResetConfig() {
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004180 Slog.i(TAG, "cmd: handleResetConfig");
4181
Makoto Onuki4362a662016-03-08 18:59:09 -08004182 synchronized (mLock) {
4183 loadConfigurationLocked();
4184 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004185 }
4186
4187 private void clearLauncher() {
4188 synchronized (mLock) {
Makoto Onuki10305202016-07-14 18:14:08 -07004189 getUserShortcutsLocked(mUserId).forceClearLauncher();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004190 }
4191 }
4192
4193 private void showLauncher() {
4194 synchronized (mLock) {
4195 // This ensures to set the cached launcher. Package name doesn't matter.
4196 hasShortcutHostPermissionInner("-", mUserId);
4197
4198 getOutPrintWriter().println("Launcher: "
Makoto Onuki10305202016-07-14 18:14:08 -07004199 + getUserShortcutsLocked(mUserId).getLastKnownLauncher());
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004200 }
4201 }
4202
4203 private void handleClearDefaultLauncher() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07004204 synchronized (mLock) {
4205 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004206
Makoto Onuki02f338e2016-07-29 09:40:40 -07004207 clearLauncher();
4208 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004209 }
4210
4211 private void handleGetDefaultLauncher() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07004212 synchronized (mLock) {
4213 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004214
Makoto Onuki02f338e2016-07-29 09:40:40 -07004215 clearLauncher();
4216 showLauncher();
4217 }
Makoto Onuki4362a662016-03-08 18:59:09 -08004218 }
Makoto Onukiac214972016-04-04 10:19:45 -07004219
4220 private void handleUnloadUser() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07004221 synchronized (mLock) {
4222 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onukiac214972016-04-04 10:19:45 -07004223
Makoto Onuki02f338e2016-07-29 09:40:40 -07004224 Slog.i(TAG, "cmd: handleUnloadUser: user=" + mUserId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004225
Makoto Onuki01ce92b2017-04-28 12:24:16 -07004226 ShortcutService.this.handleStopUser(mUserId);
Makoto Onuki02f338e2016-07-29 09:40:40 -07004227 }
Makoto Onukiac214972016-04-04 10:19:45 -07004228 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004229
4230 private void handleClearShortcuts() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07004231 synchronized (mLock) {
4232 parseOptionsLocked(/* takeUser =*/ true);
4233 final String packageName = getNextArgRequired();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004234
Makoto Onuki02f338e2016-07-29 09:40:40 -07004235 Slog.i(TAG, "cmd: handleClearShortcuts: user" + mUserId + ", " + packageName);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004236
Makoto Onuki02f338e2016-07-29 09:40:40 -07004237 ShortcutService.this.cleanUpPackageForAllLoadedUsers(packageName, mUserId,
4238 /* appStillExists = */ true);
4239 }
Makoto Onukib08790c2016-06-23 14:05:46 -07004240 }
4241
4242 private void handleVerifyStates() throws CommandException {
4243 try {
4244 verifyStatesForce(); // This will throw when there's an issue.
4245 } catch (Throwable th) {
4246 throw new CommandException(th.getMessage() + "\n" + Log.getStackTraceString(th));
4247 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004248 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004249 }
4250
4251 // === Unit test support ===
4252
4253 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07004254 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004255 long injectCurrentTimeMillis() {
4256 return System.currentTimeMillis();
4257 }
4258
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07004259 @VisibleForTesting
4260 long injectElapsedRealtime() {
4261 return SystemClock.elapsedRealtime();
4262 }
4263
Makoto Onuki475c3652017-05-08 14:29:03 -07004264 @VisibleForTesting
4265 long injectUptimeMillis() {
4266 return SystemClock.uptimeMillis();
4267 }
4268
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004269 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07004270 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004271 int injectBinderCallingUid() {
4272 return getCallingUid();
4273 }
4274
Makoto Onuki7d0fa812018-02-21 11:24:43 -08004275 @VisibleForTesting
4276 int injectBinderCallingPid() {
4277 return getCallingPid();
4278 }
4279
Makoto Onuki31459242016-03-22 11:12:18 -07004280 private int getCallingUserId() {
Makoto Onuki4554d0e2016-03-14 15:51:41 -07004281 return UserHandle.getUserId(injectBinderCallingUid());
4282 }
4283
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07004284 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07004285 @VisibleForTesting
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07004286 long injectClearCallingIdentity() {
4287 return Binder.clearCallingIdentity();
4288 }
4289
4290 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07004291 @VisibleForTesting
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07004292 void injectRestoreCallingIdentity(long token) {
4293 Binder.restoreCallingIdentity(token);
4294 }
4295
Makoto Onuki33663282016-08-22 16:19:04 -07004296 // Injection point.
Makoto Onuki33663282016-08-22 16:19:04 -07004297 String injectBuildFingerprint() {
4298 return Build.FINGERPRINT;
4299 }
4300
Makoto Onukide667372016-03-15 14:29:20 -07004301 final void wtf(String message) {
Makoto Onukib08790c2016-06-23 14:05:46 -07004302 wtf(message, /* exception= */ null);
Makoto Onukide667372016-03-15 14:29:20 -07004303 }
4304
Makoto Onuki2e210c42016-03-30 08:30:36 -07004305 // Injection point.
Makoto Onukia2241832016-07-06 13:28:37 -07004306 void wtf(String message, Throwable e) {
4307 if (e == null) {
4308 e = new RuntimeException("Stacktrace");
4309 }
4310 synchronized (mLock) {
4311 mWtfCount++;
4312 mLastWtfStacktrace = new Exception("Last failure was logged here:");
4313 }
Makoto Onukide667372016-03-15 14:29:20 -07004314 Slog.wtf(TAG, message, e);
4315 }
4316
Makoto Onuki31459242016-03-22 11:12:18 -07004317 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004318 File injectSystemDataPath() {
4319 return Environment.getDataSystemDirectory();
4320 }
4321
Makoto Onuki31459242016-03-22 11:12:18 -07004322 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004323 File injectUserDataPath(@UserIdInt int userId) {
Makoto Onuki55046222016-03-08 10:49:47 -08004324 return new File(Environment.getDataSystemCeDirectory(userId), DIRECTORY_PER_USER);
4325 }
4326
Makoto Onuki50a320e2017-05-31 14:38:42 -07004327 public File getDumpPath() {
4328 return new File(injectUserDataPath(UserHandle.USER_SYSTEM), DIRECTORY_DUMP);
4329 }
4330
Makoto Onuki4362a662016-03-08 18:59:09 -08004331 @VisibleForTesting
Makoto Onuki55046222016-03-08 10:49:47 -08004332 boolean injectIsLowRamDevice() {
4333 return ActivityManager.isLowRamDeviceStatic();
4334 }
4335
Makoto Onuki31459242016-03-22 11:12:18 -07004336 @VisibleForTesting
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07004337 void injectRegisterUidObserver(IUidObserver observer, int which) {
4338 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004339 ActivityManager.getService().registerUidObserver(observer, which,
Dianne Hackborn5614bf52016-11-07 17:26:41 -08004340 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07004341 } catch (RemoteException shouldntHappen) {
4342 }
4343 }
4344
Makoto Onuki55046222016-03-08 10:49:47 -08004345 File getUserBitmapFilePath(@UserIdInt int userId) {
4346 return new File(injectUserDataPath(userId), DIRECTORY_BITMAPS);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004347 }
4348
4349 @VisibleForTesting
Makoto Onuki31459242016-03-22 11:12:18 -07004350 SparseArray<ShortcutUser> getShortcutsForTest() {
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08004351 return mUsers;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004352 }
4353
4354 @VisibleForTesting
Makoto Onukib5a012f2016-06-21 11:13:53 -07004355 int getMaxShortcutsForTest() {
4356 return mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004357 }
4358
4359 @VisibleForTesting
Makoto Onukib6d35232016-04-04 15:57:17 -07004360 int getMaxUpdatesPerIntervalForTest() {
4361 return mMaxUpdatesPerInterval;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004362 }
4363
4364 @VisibleForTesting
Makoto Onuki4362a662016-03-08 18:59:09 -08004365 long getResetIntervalForTest() {
4366 return mResetInterval;
Makoto Onuki55046222016-03-08 10:49:47 -08004367 }
4368
4369 @VisibleForTesting
Makoto Onuki4362a662016-03-08 18:59:09 -08004370 int getMaxIconDimensionForTest() {
4371 return mMaxIconDimension;
4372 }
4373
4374 @VisibleForTesting
4375 CompressFormat getIconPersistFormatForTest() {
4376 return mIconPersistFormat;
4377 }
4378
4379 @VisibleForTesting
4380 int getIconPersistQualityForTest() {
4381 return mIconPersistQuality;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004382 }
Makoto Onuki41066a62016-03-09 16:18:44 -08004383
4384 @VisibleForTesting
Makoto Onuki22fcc682016-05-17 14:52:19 -07004385 ShortcutPackage getPackageShortcutForTest(String packageName, int userId) {
Makoto Onuki41066a62016-03-09 16:18:44 -08004386 synchronized (mLock) {
Makoto Onuki31459242016-03-22 11:12:18 -07004387 final ShortcutUser user = mUsers.get(userId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07004388 if (user == null) return null;
4389
Makoto Onuki22fcc682016-05-17 14:52:19 -07004390 return user.getAllPackagesForTest().get(packageName);
4391 }
4392 }
4393
4394 @VisibleForTesting
4395 ShortcutInfo getPackageShortcutForTest(String packageName, String shortcutId, int userId) {
4396 synchronized (mLock) {
Makoto Onukif34c3082016-07-13 10:25:25 -07004397 final ShortcutPackage pkg = getPackageShortcutForTest(packageName, userId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07004398 if (pkg == null) return null;
4399
4400 return pkg.findShortcutById(shortcutId);
Makoto Onuki41066a62016-03-09 16:18:44 -08004401 }
4402 }
Makoto Onuki7001a612016-05-27 13:24:28 -07004403
Makoto Onukifac592f2016-11-21 13:41:32 -08004404 @VisibleForTesting
4405 ShortcutLauncher getLauncherShortcutForTest(String packageName, int userId) {
4406 synchronized (mLock) {
4407 final ShortcutUser user = mUsers.get(userId);
4408 if (user == null) return null;
4409
4410 return user.getAllLaunchersForTest().get(PackageWithUser.of(userId, packageName));
4411 }
4412 }
4413
Makoto Onuki2d895c32016-12-02 15:48:40 -08004414 @VisibleForTesting
4415 ShortcutRequestPinProcessor getShortcutRequestPinProcessorForTest() {
4416 return mShortcutRequestPinProcessor;
4417 }
4418
Makoto Onuki7001a612016-05-27 13:24:28 -07004419 /**
4420 * Control whether {@link #verifyStates} should be performed. We always perform it during unit
4421 * tests.
4422 */
4423 @VisibleForTesting
4424 boolean injectShouldPerformVerification() {
4425 return DEBUG;
4426 }
4427
4428 /**
4429 * Check various internal states and throws if there's any inconsistency.
4430 * This is normally only enabled during unit tests.
4431 */
4432 final void verifyStates() {
4433 if (injectShouldPerformVerification()) {
4434 verifyStatesInner();
4435 }
4436 }
4437
Makoto Onukib08790c2016-06-23 14:05:46 -07004438 private final void verifyStatesForce() {
4439 verifyStatesInner();
4440 }
4441
Makoto Onuki7001a612016-05-27 13:24:28 -07004442 private void verifyStatesInner() {
Makoto Onuki10305202016-07-14 18:14:08 -07004443 synchronized (mLock) {
Makoto Onuki7001a612016-05-27 13:24:28 -07004444 forEachLoadedUserLocked(u -> u.forAllPackageItems(ShortcutPackageItem::verifyStates));
4445 }
4446 }
Makoto Onuki475c3652017-05-08 14:29:03 -07004447
4448 @VisibleForTesting
4449 void waitForBitmapSavesForTest() {
4450 synchronized (mLock) {
4451 mShortcutBitmapSaver.waitForAllSavesLocked();
4452 }
4453 }
Makoto Onuki41066a62016-03-09 16:18:44 -08004454}