blob: 9deea9ec86222e0c2aaeca373fe24a091b732b55 [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);
Mehdi Alizadeh627d4db2019-02-04 13:52:03 -08002176 enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_APP_PREDICTIONS,
2177 "hasShareTargets");
Mehdi Alizadeh85fd3d52019-01-23 12:49:53 -08002178
2179 synchronized (mLock) {
2180 throwIfUserLockedL(userId);
2181
2182 return getPackageShortcutsLocked(packageToCheck, userId).hasShareTargets();
2183 }
2184 }
2185
Andreas Gampea36dc622018-02-05 17:19:22 -08002186 @GuardedBy("mLock")
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002187 private ParceledListSlice<ShortcutInfo> getShortcutsWithQueryLocked(@NonNull String packageName,
2188 @UserIdInt int userId, int cloneFlags, @NonNull Predicate<ShortcutInfo> query) {
2189
2190 final ArrayList<ShortcutInfo> ret = new ArrayList<>();
2191
Makoto Onukic8c33292016-09-12 16:36:59 -07002192 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002193 ps.findAll(ret, query, cloneFlags);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002194
Makoto Onukibf563b62017-05-04 10:25:30 -07002195 return new ParceledListSlice<>(setReturnedByServer(ret));
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002196 }
2197
2198 @Override
Makoto Onukid6880792016-06-29 13:37:43 -07002199 public int getMaxShortcutCountPerActivity(String packageName, @UserIdInt int userId)
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002200 throws RemoteException {
2201 verifyCaller(packageName, userId);
2202
Makoto Onukib5a012f2016-06-21 11:13:53 -07002203 return mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002204 }
2205
2206 @Override
2207 public int getRemainingCallCount(String packageName, @UserIdInt int userId) {
2208 verifyCaller(packageName, userId);
2209
Makoto Onuki7d0fa812018-02-21 11:24:43 -08002210 final boolean unlimited = injectHasUnlimitedShortcutsApiCallsPermission(
2211 injectBinderCallingPid(), injectBinderCallingUid());
2212
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002213 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002214 throwIfUserLockedL(userId);
2215
Makoto Onukic8c33292016-09-12 16:36:59 -07002216 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki7d0fa812018-02-21 11:24:43 -08002217 return mMaxUpdatesPerInterval - ps.getApiCallCount(unlimited);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002218 }
2219 }
2220
2221 @Override
2222 public long getRateLimitResetTime(String packageName, @UserIdInt int userId) {
2223 verifyCaller(packageName, userId);
2224
2225 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002226 throwIfUserLockedL(userId);
2227
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002228 return getNextResetTimeLocked();
2229 }
2230 }
2231
Makoto Onuki55046222016-03-08 10:49:47 -08002232 @Override
Makoto Onuki20c95f82016-05-11 16:51:01 -07002233 public int getIconMaxDimensions(String packageName, int userId) {
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002234 verifyCaller(packageName, userId);
2235
Makoto Onuki55046222016-03-08 10:49:47 -08002236 synchronized (mLock) {
2237 return mMaxIconDimension;
2238 }
2239 }
2240
Makoto Onuki20c95f82016-05-11 16:51:01 -07002241 @Override
2242 public void reportShortcutUsed(String packageName, String shortcutId, int userId) {
2243 verifyCaller(packageName, userId);
2244
Makoto Onukiac042502016-05-20 16:39:42 -07002245 Preconditions.checkNotNull(shortcutId);
2246
2247 if (DEBUG) {
2248 Slog.d(TAG, String.format("reportShortcutUsed: Shortcut %s package %s used on user %d",
2249 shortcutId, packageName, userId));
2250 }
2251
2252 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002253 throwIfUserLockedL(userId);
2254
Makoto Onukic8c33292016-09-12 16:36:59 -07002255 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002256
Makoto Onukiac042502016-05-20 16:39:42 -07002257 if (ps.findShortcutById(shortcutId) == null) {
2258 Log.w(TAG, String.format("reportShortcutUsed: package %s doesn't have shortcut %s",
2259 packageName, shortcutId));
2260 return;
2261 }
2262 }
2263
2264 final long token = injectClearCallingIdentity();
2265 try {
2266 mUsageStatsManagerInternal.reportShortcutUsage(packageName, shortcutId, userId);
2267 } finally {
2268 injectRestoreCallingIdentity(token);
2269 }
Makoto Onuki20c95f82016-05-11 16:51:01 -07002270 }
2271
Makoto Onuki2d895c32016-12-02 15:48:40 -08002272 @Override
Sunny Goyal7f7372a2017-01-24 11:53:54 -08002273 public boolean isRequestPinItemSupported(int callingUserId, int requestType) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08002274 final long token = injectClearCallingIdentity();
2275 try {
Sunny Goyal7f7372a2017-01-24 11:53:54 -08002276 return mShortcutRequestPinProcessor
2277 .isRequestPinItemSupported(callingUserId, requestType);
Makoto Onuki2d895c32016-12-02 15:48:40 -08002278 } finally {
2279 injectRestoreCallingIdentity(token);
2280 }
2281 }
2282
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002283 /**
Makoto Onukib08790c2016-06-23 14:05:46 -07002284 * Reset all throttling, for developer options and command line. Only system/shell can call
2285 * it.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002286 */
2287 @Override
2288 public void resetThrottling() {
2289 enforceSystemOrShell();
2290
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002291 resetThrottlingInner(getCallingUserId());
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002292 }
2293
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002294 void resetThrottlingInner(@UserIdInt int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002295 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002296 if (!isUserUnlockedL(userId)) {
2297 Log.w(TAG, "User " + userId + " is locked or not running");
2298 return;
2299 }
2300
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002301 getUserShortcutsLocked(userId).resetThrottling();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002302 }
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002303 scheduleSaveUser(userId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002304 Slog.i(TAG, "ShortcutManager: throttling counter reset for user " + userId);
2305 }
2306
2307 void resetAllThrottlingInner() {
2308 synchronized (mLock) {
2309 mRawLastResetTime = injectCurrentTimeMillis();
2310 }
2311 scheduleSaveBaseState();
2312 Slog.i(TAG, "ShortcutManager: throttling counter reset for all users");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002313 }
2314
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002315 @Override
2316 public void onApplicationActive(String packageName, int userId) {
2317 if (DEBUG) {
2318 Slog.d(TAG, "onApplicationActive: package=" + packageName + " userid=" + userId);
2319 }
2320 enforceResetThrottlingPermission();
Makoto Onuki02f338e2016-07-29 09:40:40 -07002321
2322 synchronized (mLock) {
2323 if (!isUserUnlockedL(userId)) {
2324 // This is called by system UI, so no need to throw. Just ignore.
2325 return;
2326 }
2327
2328 getPackageShortcutsLocked(packageName, userId)
2329 .resetRateLimitingForCommandLineNoSaving();
2330 saveUserLocked(userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002331 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002332 }
2333
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002334 // We override this method in unit tests to do a simpler check.
Makoto Onuki634cecb2017-10-13 17:10:48 -07002335 boolean hasShortcutHostPermission(@NonNull String callingPackage, int userId,
2336 int callingPid, int callingUid) {
Makoto Onuki35559d62017-11-06 16:26:32 -08002337 if (canSeeAnyPinnedShortcut(callingPackage, userId, callingPid, callingUid)) {
Makoto Onuki634cecb2017-10-13 17:10:48 -07002338 return true;
2339 }
Makoto Onuki84d59342018-02-02 09:22:38 -08002340 final long start = getStatStartTime();
Makoto Onuki10305202016-07-14 18:14:08 -07002341 try {
2342 return hasShortcutHostPermissionInner(callingPackage, userId);
2343 } finally {
2344 logDurationStat(Stats.LAUNCHER_PERMISSION_CHECK, start);
2345 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002346 }
2347
Makoto Onuki35559d62017-11-06 16:26:32 -08002348 boolean canSeeAnyPinnedShortcut(@NonNull String callingPackage, int userId,
2349 int callingPid, int callingUid) {
2350 if (injectHasAccessShortcutsPermission(callingPid, callingUid)) {
2351 return true;
2352 }
2353 synchronized (mLock) {
Makoto Onuki708703b2017-12-11 16:38:11 -08002354 return getNonPersistentUserLocked(userId).hasHostPackage(callingPackage);
Makoto Onuki35559d62017-11-06 16:26:32 -08002355 }
2356 }
2357
Makoto Onuki634cecb2017-10-13 17:10:48 -07002358 /**
2359 * Returns true if the caller has the "ACCESS_SHORTCUTS" permission.
2360 */
Makoto Onuki35559d62017-11-06 16:26:32 -08002361 @VisibleForTesting
2362 boolean injectHasAccessShortcutsPermission(int callingPid, int callingUid) {
Makoto Onuki634cecb2017-10-13 17:10:48 -07002363 return mContext.checkPermission(android.Manifest.permission.ACCESS_SHORTCUTS,
2364 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
2365 }
2366
Makoto Onuki7d0fa812018-02-21 11:24:43 -08002367 /**
2368 * Returns true if the caller has the "UNLIMITED_SHORTCUTS_API_CALLS" permission.
2369 */
2370 @VisibleForTesting
2371 boolean injectHasUnlimitedShortcutsApiCallsPermission(int callingPid, int callingUid) {
2372 return mContext.checkPermission(permission.UNLIMITED_SHORTCUTS_API_CALLS,
2373 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
2374 }
2375
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002376 // This method is extracted so we can directly call this method from unit tests,
2377 // even when hasShortcutPermission() is overridden.
2378 @VisibleForTesting
Makoto Onuki2d895c32016-12-02 15:48:40 -08002379 boolean hasShortcutHostPermissionInner(@NonNull String packageName, int userId) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002380 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002381 throwIfUserLockedL(userId);
2382
Makoto Onuki31459242016-03-22 11:12:18 -07002383 final ShortcutUser user = getUserShortcutsLocked(userId);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002384
Makoto Onuki2d895c32016-12-02 15:48:40 -08002385 // Always trust the cached component.
Makoto Onuki10305202016-07-14 18:14:08 -07002386 final ComponentName cached = user.getCachedLauncher();
2387 if (cached != null) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08002388 if (cached.getPackageName().equals(packageName)) {
Makoto Onuki10305202016-07-14 18:14:08 -07002389 return true;
2390 }
2391 }
2392 // If the cached one doesn't match, then go ahead
2393
Makoto Onuki2d895c32016-12-02 15:48:40 -08002394 final ComponentName detected = getDefaultLauncher(userId);
Makoto Onuki2e210c42016-03-30 08:30:36 -07002395
Makoto Onuki10305202016-07-14 18:14:08 -07002396 // Update the cache.
2397 user.setLauncher(detected);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002398 if (detected != null) {
2399 if (DEBUG) {
2400 Slog.v(TAG, "Detected launcher: " + detected);
2401 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08002402 return detected.getPackageName().equals(packageName);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002403 } else {
2404 // Default launcher not found.
2405 return false;
2406 }
2407 }
2408 }
2409
Makoto Onuki2d895c32016-12-02 15:48:40 -08002410 @Nullable
2411 ComponentName getDefaultLauncher(@UserIdInt int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08002412 final long start = getStatStartTime();
Makoto Onuki2d895c32016-12-02 15:48:40 -08002413 final long token = injectClearCallingIdentity();
2414 try {
2415 synchronized (mLock) {
2416 throwIfUserLockedL(userId);
2417
2418 final ShortcutUser user = getUserShortcutsLocked(userId);
2419
2420 final List<ResolveInfo> allHomeCandidates = new ArrayList<>();
2421
2422 // Default launcher from package manager.
Makoto Onuki84d59342018-02-02 09:22:38 -08002423 final long startGetHomeActivitiesAsUser = getStatStartTime();
Makoto Onuki2d895c32016-12-02 15:48:40 -08002424 final ComponentName defaultLauncher = mPackageManagerInternal
2425 .getHomeActivitiesAsUser(allHomeCandidates, userId);
2426 logDurationStat(Stats.GET_DEFAULT_HOME, startGetHomeActivitiesAsUser);
2427
2428 ComponentName detected = null;
2429 if (defaultLauncher != null) {
2430 detected = defaultLauncher;
2431 if (DEBUG) {
2432 Slog.v(TAG, "Default launcher from PM: " + detected);
2433 }
2434 } else {
2435 detected = user.getLastKnownLauncher();
2436
2437 if (detected != null) {
2438 if (injectIsActivityEnabledAndExported(detected, userId)) {
2439 if (DEBUG) {
2440 Slog.v(TAG, "Cached launcher: " + detected);
2441 }
2442 } else {
2443 Slog.w(TAG, "Cached launcher " + detected + " no longer exists");
2444 detected = null;
2445 user.clearLauncher();
2446 }
2447 }
2448 }
2449
2450 if (detected == null) {
2451 // If we reach here, that means it's the first check since the user was created,
2452 // and there's already multiple launchers and there's no default set.
2453 // Find the system one with the highest priority.
2454 // (We need to check the priority too because of FallbackHome in Settings.)
2455 // If there's no system launcher yet, then no one can access shortcuts, until
2456 // the user explicitly
2457 final int size = allHomeCandidates.size();
2458
2459 int lastPriority = Integer.MIN_VALUE;
2460 for (int i = 0; i < size; i++) {
2461 final ResolveInfo ri = allHomeCandidates.get(i);
2462 if (!ri.activityInfo.applicationInfo.isSystemApp()) {
2463 continue;
2464 }
2465 if (DEBUG) {
2466 Slog.d(TAG, String.format("hasShortcutPermissionInner: pkg=%s prio=%d",
2467 ri.activityInfo.getComponentName(), ri.priority));
2468 }
2469 if (ri.priority < lastPriority) {
2470 continue;
2471 }
2472 detected = ri.activityInfo.getComponentName();
2473 lastPriority = ri.priority;
2474 }
2475 }
2476 return detected;
2477 }
2478 } finally {
2479 injectRestoreCallingIdentity(token);
2480 logDurationStat(Stats.GET_DEFAULT_LAUNCHER, start);
2481 }
2482 }
2483
Dianne Hackbornc160fa42017-11-01 16:14:26 -07002484 public void setShortcutHostPackage(@NonNull String type, @Nullable String packageName,
2485 int userId) {
2486 synchronized (mLock) {
Makoto Onuki708703b2017-12-11 16:38:11 -08002487 getNonPersistentUserLocked(userId).setShortcutHostPackage(type, packageName);
Dianne Hackbornc160fa42017-11-01 16:14:26 -07002488 }
2489 }
2490
Makoto Onukicdc78f72016-03-21 15:47:52 -07002491 // === House keeping ===
2492
Makoto Onukib08790c2016-06-23 14:05:46 -07002493 private void cleanUpPackageForAllLoadedUsers(String packageName, @UserIdInt int packageUserId,
2494 boolean appStillExists) {
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002495 synchronized (mLock) {
2496 forEachLoadedUserLocked(user ->
Makoto Onukib08790c2016-06-23 14:05:46 -07002497 cleanUpPackageLocked(packageName, user.getUserId(), packageUserId,
2498 appStillExists));
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002499 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002500 }
2501
Makoto Onuki2e210c42016-03-30 08:30:36 -07002502 /**
2503 * Remove all the information associated with a package. This will really remove all the
2504 * information, including the restore information (i.e. it'll remove packages even if they're
2505 * shadow).
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002506 *
2507 * This is called when an app is uninstalled, or an app gets "clear data"ed.
Makoto Onuki2e210c42016-03-30 08:30:36 -07002508 */
Andreas Gampea36dc622018-02-05 17:19:22 -08002509 @GuardedBy("mLock")
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002510 @VisibleForTesting
Makoto Onukib08790c2016-06-23 14:05:46 -07002511 void cleanUpPackageLocked(String packageName, int owningUserId, int packageUserId,
2512 boolean appStillExists) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002513 final boolean wasUserLoaded = isUserLoadedLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002514
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002515 final ShortcutUser user = getUserShortcutsLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002516 boolean doNotify = false;
2517
2518 // First, remove the package from the package list (if the package is a publisher).
Makoto Onukid99c6f02016-03-28 11:02:54 -07002519 if (packageUserId == owningUserId) {
Makoto Onukic51b2872016-05-04 15:24:50 -07002520 if (user.removePackage(packageName) != null) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002521 doNotify = true;
2522 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07002523 }
Makoto Onukid99c6f02016-03-28 11:02:54 -07002524
Makoto Onukicdc78f72016-03-21 15:47:52 -07002525 // Also remove from the launcher list (if the package is a launcher).
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002526 user.removeLauncher(packageUserId, packageName);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002527
2528 // Then remove pinned shortcuts from all launchers.
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002529 user.forAllLaunchers(l -> l.cleanUpPackage(packageName, packageUserId));
2530
2531 // Now there may be orphan shortcuts because we removed pinned shortcuts at the previous
Makoto Onukicdc78f72016-03-21 15:47:52 -07002532 // step. Remove them too.
Makoto Onukic51b2872016-05-04 15:24:50 -07002533 user.forAllPackages(p -> p.refreshPinnedFlags());
Makoto Onukicdc78f72016-03-21 15:47:52 -07002534
Makoto Onukid99c6f02016-03-28 11:02:54 -07002535 scheduleSaveUser(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002536
2537 if (doNotify) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002538 notifyListeners(packageName, owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002539 }
2540
Makoto Onukib08790c2016-06-23 14:05:46 -07002541 // If the app still exists (i.e. data cleared), we need to re-publish manifest shortcuts.
2542 if (appStillExists && (packageUserId == owningUserId)) {
2543 // This will do the notification and save when needed, so do it after the above
2544 // notifyListeners.
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002545 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07002546 }
2547
Makoto Onukicdc78f72016-03-21 15:47:52 -07002548 if (!wasUserLoaded) {
2549 // Note this will execute the scheduled save.
Makoto Onukid99c6f02016-03-28 11:02:54 -07002550 unloadUserLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002551 }
2552 }
2553
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002554 /**
2555 * Entry point from {@link LauncherApps}.
2556 */
2557 private class LocalService extends ShortcutServiceInternal {
Makoto Onuki2e210c42016-03-30 08:30:36 -07002558
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002559 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002560 public List<ShortcutInfo> getShortcuts(int launcherUserId,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002561 @NonNull String callingPackage, long changedSince,
Makoto Onukiabe84422016-04-07 09:41:19 -07002562 @Nullable String packageName, @Nullable List<String> shortcutIds,
Makoto Onuki99302b52017-03-29 12:42:26 -07002563 @Nullable ComponentName componentName,
Makoto Onuki634cecb2017-10-13 17:10:48 -07002564 int queryFlags, int userId, int callingPid, int callingUid) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002565 final ArrayList<ShortcutInfo> ret = new ArrayList<>();
Makoto Onuki9c850012016-07-26 15:50:50 -07002566
Makoto Onuki20c95f82016-05-11 16:51:01 -07002567 final boolean cloneKeyFieldOnly =
2568 ((queryFlags & ShortcutQuery.FLAG_GET_KEY_FIELDS_ONLY) != 0);
2569 final int cloneFlag = cloneKeyFieldOnly ? ShortcutInfo.CLONE_REMOVE_NON_KEY_INFO
2570 : ShortcutInfo.CLONE_REMOVE_FOR_LAUNCHER;
Makoto Onukiabe84422016-04-07 09:41:19 -07002571 if (packageName == null) {
2572 shortcutIds = null; // LauncherAppsService already threw for it though.
2573 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002574
2575 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002576 throwIfUserLockedL(userId);
2577 throwIfUserLockedL(launcherUserId);
2578
Makoto Onuki2e210c42016-03-30 08:30:36 -07002579 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002580 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002581
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002582 if (packageName != null) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002583 getShortcutsInnerLocked(launcherUserId,
Makoto Onukiabe84422016-04-07 09:41:19 -07002584 callingPackage, packageName, shortcutIds, changedSince,
Makoto Onuki634cecb2017-10-13 17:10:48 -07002585 componentName, queryFlags, userId, ret, cloneFlag,
2586 callingPid, callingUid);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002587 } else {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002588 final List<String> shortcutIdsF = shortcutIds;
2589 getUserShortcutsLocked(userId).forAllPackages(p -> {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002590 getShortcutsInnerLocked(launcherUserId,
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002591 callingPackage, p.getPackageName(), shortcutIdsF, changedSince,
Makoto Onuki634cecb2017-10-13 17:10:48 -07002592 componentName, queryFlags, userId, ret, cloneFlag,
2593 callingPid, callingUid);
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002594 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002595 }
2596 }
Makoto Onukibf563b62017-05-04 10:25:30 -07002597 return setReturnedByServer(ret);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002598 }
2599
Andreas Gampea36dc622018-02-05 17:19:22 -08002600 @GuardedBy("ShortcutService.this.mLock")
Makoto Onukid99c6f02016-03-28 11:02:54 -07002601 private void getShortcutsInnerLocked(int launcherUserId, @NonNull String callingPackage,
Makoto Onukiabe84422016-04-07 09:41:19 -07002602 @Nullable String packageName, @Nullable List<String> shortcutIds, long changedSince,
Makoto Onuki99302b52017-03-29 12:42:26 -07002603 @Nullable ComponentName componentName, int queryFlags,
Makoto Onuki634cecb2017-10-13 17:10:48 -07002604 int userId, ArrayList<ShortcutInfo> ret, int cloneFlag,
2605 int callingPid, int callingUid) {
Makoto Onukiabe84422016-04-07 09:41:19 -07002606 final ArraySet<String> ids = shortcutIds == null ? null
2607 : new ArraySet<>(shortcutIds);
2608
Makoto Onuki35559d62017-11-06 16:26:32 -08002609 final ShortcutUser user = getUserShortcutsLocked(userId);
2610 final ShortcutPackage p = user.getPackageShortcutsIfExists(packageName);
Makoto Onukic51b2872016-05-04 15:24:50 -07002611 if (p == null) {
2612 return; // No need to instantiate ShortcutPackage.
2613 }
Makoto Onuki634cecb2017-10-13 17:10:48 -07002614 final boolean matchDynamic = (queryFlags & ShortcutQuery.FLAG_MATCH_DYNAMIC) != 0;
2615 final boolean matchPinned = (queryFlags & ShortcutQuery.FLAG_MATCH_PINNED) != 0;
2616 final boolean matchManifest = (queryFlags & ShortcutQuery.FLAG_MATCH_MANIFEST) != 0;
2617
Makoto Onuki35559d62017-11-06 16:26:32 -08002618 final boolean canAccessAllShortcuts =
2619 canSeeAnyPinnedShortcut(callingPackage, launcherUserId, callingPid, callingUid);
2620
Makoto Onuki634cecb2017-10-13 17:10:48 -07002621 final boolean getPinnedByAnyLauncher =
Makoto Onuki35559d62017-11-06 16:26:32 -08002622 canAccessAllShortcuts &&
2623 ((queryFlags & ShortcutQuery.FLAG_MATCH_PINNED_BY_ANY_LAUNCHER) != 0);
Makoto Onukic51b2872016-05-04 15:24:50 -07002624
2625 p.findAll(ret,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002626 (ShortcutInfo si) -> {
2627 if (si.getLastChangedTimestamp() < changedSince) {
2628 return false;
2629 }
Makoto Onukiabe84422016-04-07 09:41:19 -07002630 if (ids != null && !ids.contains(si.getId())) {
2631 return false;
2632 }
Makoto Onuki85694522016-05-04 12:53:37 -07002633 if (componentName != null) {
Makoto Onuki9fd90192017-01-06 18:31:03 +00002634 if (si.getActivity() != null
2635 && !si.getActivity().equals(componentName)) {
Makoto Onuki85694522016-05-04 12:53:37 -07002636 return false;
2637 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002638 }
Makoto Onuki634cecb2017-10-13 17:10:48 -07002639 if (matchDynamic && si.isDynamic()) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002640 return true;
2641 }
Makoto Onuki35559d62017-11-06 16:26:32 -08002642 if ((matchPinned || getPinnedByAnyLauncher) && si.isPinned()) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002643 return true;
2644 }
Makoto Onuki634cecb2017-10-13 17:10:48 -07002645 if (matchManifest && si.isDeclaredInManifest()) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002646 return true;
2647 }
2648 return false;
Makoto Onuki634cecb2017-10-13 17:10:48 -07002649 }, cloneFlag, callingPackage, launcherUserId, getPinnedByAnyLauncher);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002650 }
2651
2652 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002653 public boolean isPinnedByCaller(int launcherUserId, @NonNull String callingPackage,
2654 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2655 Preconditions.checkStringNotEmpty(packageName, "packageName");
2656 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
2657
2658 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002659 throwIfUserLockedL(userId);
2660 throwIfUserLockedL(launcherUserId);
2661
Makoto Onuki2e210c42016-03-30 08:30:36 -07002662 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002663 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002664
Makoto Onukid99c6f02016-03-28 11:02:54 -07002665 final ShortcutInfo si = getShortcutInfoLocked(
Makoto Onuki634cecb2017-10-13 17:10:48 -07002666 launcherUserId, callingPackage, packageName, shortcutId, userId,
2667 /*getPinnedByAnyLauncher=*/ false);
Makoto Onukid99c6f02016-03-28 11:02:54 -07002668 return si != null && si.isPinned();
2669 }
2670 }
2671
Andreas Gampea36dc622018-02-05 17:19:22 -08002672 @GuardedBy("ShortcutService.this.mLock")
Makoto Onuki2e210c42016-03-30 08:30:36 -07002673 private ShortcutInfo getShortcutInfoLocked(
Makoto Onukid99c6f02016-03-28 11:02:54 -07002674 int launcherUserId, @NonNull String callingPackage,
Makoto Onuki634cecb2017-10-13 17:10:48 -07002675 @NonNull String packageName, @NonNull String shortcutId, int userId,
2676 boolean getPinnedByAnyLauncher) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002677 Preconditions.checkStringNotEmpty(packageName, "packageName");
2678 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
2679
Makoto Onuki02f338e2016-07-29 09:40:40 -07002680 throwIfUserLockedL(userId);
2681 throwIfUserLockedL(launcherUserId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002682
Makoto Onukic51b2872016-05-04 15:24:50 -07002683 final ShortcutPackage p = getUserShortcutsLocked(userId)
2684 .getPackageShortcutsIfExists(packageName);
2685 if (p == null) {
2686 return null;
2687 }
2688
Makoto Onukid99c6f02016-03-28 11:02:54 -07002689 final ArrayList<ShortcutInfo> list = new ArrayList<>(1);
Makoto Onukic51b2872016-05-04 15:24:50 -07002690 p.findAll(list,
Makoto Onukid99c6f02016-03-28 11:02:54 -07002691 (ShortcutInfo si) -> shortcutId.equals(si.getId()),
Makoto Onuki634cecb2017-10-13 17:10:48 -07002692 /* clone flags=*/ 0, callingPackage, launcherUserId, getPinnedByAnyLauncher);
Makoto Onukid99c6f02016-03-28 11:02:54 -07002693 return list.size() == 0 ? null : list.get(0);
2694 }
2695
2696 @Override
2697 public void pinShortcuts(int launcherUserId,
2698 @NonNull String callingPackage, @NonNull String packageName,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002699 @NonNull List<String> shortcutIds, int userId) {
2700 // Calling permission must be checked by LauncherAppsImpl.
2701 Preconditions.checkStringNotEmpty(packageName, "packageName");
2702 Preconditions.checkNotNull(shortcutIds, "shortcutIds");
2703
2704 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002705 throwIfUserLockedL(userId);
2706 throwIfUserLockedL(launcherUserId);
2707
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002708 final ShortcutLauncher launcher =
Makoto Onuki2e210c42016-03-30 08:30:36 -07002709 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId);
Makoto Onukic51b2872016-05-04 15:24:50 -07002710 launcher.attemptToRestoreIfNeededAndSave();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002711
Makoto Onukia4f89b12017-10-05 10:37:55 -07002712 launcher.pinShortcuts(userId, packageName, shortcutIds, /*forPinRequest=*/ false);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002713 }
Makoto Onuki39686e82016-04-13 18:03:00 -07002714 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07002715
2716 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002717 }
2718
2719 @Override
Makoto Onuki440a1ea2016-07-20 14:21:18 -07002720 public Intent[] createShortcutIntents(int launcherUserId,
Makoto Onukid99c6f02016-03-28 11:02:54 -07002721 @NonNull String callingPackage,
Makoto Onuki634cecb2017-10-13 17:10:48 -07002722 @NonNull String packageName, @NonNull String shortcutId, int userId,
2723 int callingPid, int callingUid) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002724 // Calling permission must be checked by LauncherAppsImpl.
Makoto Onuki43204b82016-03-08 16:16:44 -08002725 Preconditions.checkStringNotEmpty(packageName, "packageName can't be empty");
2726 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId can't be empty");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002727
2728 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002729 throwIfUserLockedL(userId);
2730 throwIfUserLockedL(launcherUserId);
2731
Makoto Onuki2e210c42016-03-30 08:30:36 -07002732 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002733 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002734
Makoto Onuki634cecb2017-10-13 17:10:48 -07002735 final boolean getPinnedByAnyLauncher =
Makoto Onuki35559d62017-11-06 16:26:32 -08002736 canSeeAnyPinnedShortcut(callingPackage, launcherUserId,
2737 callingPid, callingUid);
Makoto Onuki634cecb2017-10-13 17:10:48 -07002738
Makoto Onukid99c6f02016-03-28 11:02:54 -07002739 // Make sure the shortcut is actually visible to the launcher.
2740 final ShortcutInfo si = getShortcutInfoLocked(
Makoto Onuki634cecb2017-10-13 17:10:48 -07002741 launcherUserId, callingPackage, packageName, shortcutId, userId,
2742 getPinnedByAnyLauncher);
Makoto Onukid99c6f02016-03-28 11:02:54 -07002743 // "si == null" should suffice here, but check the flags too just to make sure.
Makoto Onuki35559d62017-11-06 16:26:32 -08002744 if (si == null || !si.isEnabled() || !(si.isAlive() || getPinnedByAnyLauncher)) {
Makoto Onuki83f6d2d2016-07-11 14:30:19 -07002745 Log.e(TAG, "Shortcut " + shortcutId + " does not exist or disabled");
Makoto Onukid99c6f02016-03-28 11:02:54 -07002746 return null;
2747 }
Makoto Onuki440a1ea2016-07-20 14:21:18 -07002748 return si.getIntents();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002749 }
2750 }
2751
2752 @Override
2753 public void addListener(@NonNull ShortcutChangeListener listener) {
2754 synchronized (mLock) {
2755 mListeners.add(Preconditions.checkNotNull(listener));
2756 }
2757 }
Makoto Onuki55046222016-03-08 10:49:47 -08002758
2759 @Override
Makoto Onukiabe84422016-04-07 09:41:19 -07002760 public int getShortcutIconResId(int launcherUserId, @NonNull String callingPackage,
2761 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2762 Preconditions.checkNotNull(callingPackage, "callingPackage");
2763 Preconditions.checkNotNull(packageName, "packageName");
2764 Preconditions.checkNotNull(shortcutId, "shortcutId");
Makoto Onuki55046222016-03-08 10:49:47 -08002765
2766 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002767 throwIfUserLockedL(userId);
2768 throwIfUserLockedL(launcherUserId);
2769
Makoto Onuki2e210c42016-03-30 08:30:36 -07002770 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002771 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002772
Makoto Onukic51b2872016-05-04 15:24:50 -07002773 final ShortcutPackage p = getUserShortcutsLocked(userId)
2774 .getPackageShortcutsIfExists(packageName);
2775 if (p == null) {
2776 return 0;
2777 }
2778
2779 final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId);
Makoto Onuki55046222016-03-08 10:49:47 -08002780 return (shortcutInfo != null && shortcutInfo.hasIconResource())
2781 ? shortcutInfo.getIconResourceId() : 0;
2782 }
2783 }
2784
2785 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002786 public ParcelFileDescriptor getShortcutIconFd(int launcherUserId,
Makoto Onukiabe84422016-04-07 09:41:19 -07002787 @NonNull String callingPackage, @NonNull String packageName,
2788 @NonNull String shortcutId, int userId) {
2789 Preconditions.checkNotNull(callingPackage, "callingPackage");
2790 Preconditions.checkNotNull(packageName, "packageName");
2791 Preconditions.checkNotNull(shortcutId, "shortcutId");
Makoto Onuki55046222016-03-08 10:49:47 -08002792
2793 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002794 throwIfUserLockedL(userId);
2795 throwIfUserLockedL(launcherUserId);
2796
Makoto Onuki2e210c42016-03-30 08:30:36 -07002797 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002798 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002799
Makoto Onukic51b2872016-05-04 15:24:50 -07002800 final ShortcutPackage p = getUserShortcutsLocked(userId)
2801 .getPackageShortcutsIfExists(packageName);
2802 if (p == null) {
2803 return null;
2804 }
2805
2806 final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId);
Makoto Onuki55046222016-03-08 10:49:47 -08002807 if (shortcutInfo == null || !shortcutInfo.hasIconFile()) {
2808 return null;
2809 }
Makoto Onuki475c3652017-05-08 14:29:03 -07002810 final String path = mShortcutBitmapSaver.getBitmapPathMayWaitLocked(shortcutInfo);
2811 if (path == null) {
2812 Slog.w(TAG, "null bitmap detected in getShortcutIconFd()");
2813 return null;
2814 }
Makoto Onuki55046222016-03-08 10:49:47 -08002815 try {
2816 return ParcelFileDescriptor.open(
Makoto Onuki475c3652017-05-08 14:29:03 -07002817 new File(path),
Makoto Onuki55046222016-03-08 10:49:47 -08002818 ParcelFileDescriptor.MODE_READ_ONLY);
2819 } catch (FileNotFoundException e) {
Makoto Onuki475c3652017-05-08 14:29:03 -07002820 Slog.e(TAG, "Icon file not found: " + path);
Makoto Onuki55046222016-03-08 10:49:47 -08002821 return null;
2822 }
2823 }
2824 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002825
2826 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002827 public boolean hasShortcutHostPermission(int launcherUserId,
Makoto Onuki634cecb2017-10-13 17:10:48 -07002828 @NonNull String callingPackage, int callingPid, int callingUid) {
2829 return ShortcutService.this.hasShortcutHostPermission(callingPackage, launcherUserId,
2830 callingPid, callingUid);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002831 }
Sunny Goyal87a563e2017-01-01 19:42:45 -08002832
2833 @Override
Dianne Hackbornc160fa42017-11-01 16:14:26 -07002834 public void setShortcutHostPackage(@NonNull String type, @Nullable String packageName,
2835 int userId) {
2836 ShortcutService.this.setShortcutHostPackage(type, packageName, userId);
2837 }
2838
2839 @Override
Sunny Goyal87a563e2017-01-01 19:42:45 -08002840 public boolean requestPinAppWidget(@NonNull String callingPackage,
Sunny Goyal4ad6b572017-02-28 11:11:51 -08002841 @NonNull AppWidgetProviderInfo appWidget, @Nullable Bundle extras,
2842 @Nullable IntentSender resultIntent, int userId) {
Sunny Goyal87a563e2017-01-01 19:42:45 -08002843 Preconditions.checkNotNull(appWidget);
Sunny Goyal4ad6b572017-02-28 11:11:51 -08002844 return requestPinItem(callingPackage, userId, null, appWidget, extras, resultIntent);
Sunny Goyal87a563e2017-01-01 19:42:45 -08002845 }
Sunny Goyal7f7372a2017-01-24 11:53:54 -08002846
2847 @Override
2848 public boolean isRequestPinItemSupported(int callingUserId, int requestType) {
2849 return ShortcutService.this.isRequestPinItemSupported(callingUserId, requestType);
2850 }
Tony Maked6ef622017-12-07 16:36:16 +00002851
2852 @Override
2853 public boolean isForegroundDefaultLauncher(@NonNull String callingPackage, int callingUid) {
2854 Preconditions.checkNotNull(callingPackage);
2855
2856 final int userId = UserHandle.getUserId(callingUid);
2857 final ComponentName defaultLauncher = getDefaultLauncher(userId);
2858 if (defaultLauncher == null) {
2859 return false;
2860 }
2861 if (!callingPackage.equals(defaultLauncher.getPackageName())) {
2862 return false;
2863 }
2864 synchronized (mLock) {
2865 if (!isUidForegroundLocked(callingUid)) {
2866 return false;
2867 }
2868 }
2869 return true;
2870 }
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002871 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002872
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002873 final BroadcastReceiver mReceiver = new BroadcastReceiver() {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002874 @Override
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002875 public void onReceive(Context context, Intent intent) {
2876 if (!mBootCompleted.get()) {
2877 return; // Boot not completed, ignore the broadcast.
2878 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07002879 try {
2880 if (Intent.ACTION_LOCALE_CHANGED.equals(intent.getAction())) {
2881 handleLocaleChanged();
2882 }
2883 } catch (Exception e) {
2884 wtf("Exception in mReceiver.onReceive", e);
Makoto Onukic51b2872016-05-04 15:24:50 -07002885 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002886 }
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002887 };
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002888
Makoto Onuki157b1622016-06-02 16:13:10 -07002889 void handleLocaleChanged() {
2890 if (DEBUG) {
2891 Slog.d(TAG, "handleLocaleChanged");
2892 }
2893 scheduleSaveBaseState();
2894
Makoto Onuki02f338e2016-07-29 09:40:40 -07002895 synchronized (mLock) {
2896 final long token = injectClearCallingIdentity();
2897 try {
2898 forEachLoadedUserLocked(user -> user.detectLocaleChange());
2899 } finally {
2900 injectRestoreCallingIdentity(token);
2901 }
Makoto Onuki157b1622016-06-02 16:13:10 -07002902 }
2903 }
2904
Makoto Onukif34c3082016-07-13 10:25:25 -07002905 /**
2906 * Package event callbacks.
2907 */
2908 @VisibleForTesting
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002909 final BroadcastReceiver mPackageMonitor = new BroadcastReceiver() {
Makoto Onukif34c3082016-07-13 10:25:25 -07002910 @Override
2911 public void onReceive(Context context, Intent intent) {
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002912 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
2913 if (userId == UserHandle.USER_NULL) {
2914 Slog.w(TAG, "Intent broadcast does not contain user handle: " + intent);
2915 return;
2916 }
2917
2918 final String action = intent.getAction();
2919
2920 // This is normally called on Handler, so clearCallingIdentity() isn't needed,
2921 // but we still check it in unit tests.
Makoto Onukif34c3082016-07-13 10:25:25 -07002922 final long token = injectClearCallingIdentity();
2923 try {
Makoto Onuki10305202016-07-14 18:14:08 -07002924 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002925 if (!isUserUnlockedL(userId)) {
2926 if (DEBUG) {
2927 Slog.d(TAG, "Ignoring package broadcast " + action
2928 + " for locked/stopped user " + userId);
2929 }
2930 return;
2931 }
2932
2933 // Whenever we get one of those package broadcasts, or get
2934 // ACTION_PREFERRED_ACTIVITY_CHANGED, we purge the default launcher cache.
Makoto Onuki10305202016-07-14 18:14:08 -07002935 final ShortcutUser user = getUserShortcutsLocked(userId);
2936 user.clearLauncher();
2937 }
2938 if (Intent.ACTION_PREFERRED_ACTIVITY_CHANGED.equals(action)) {
2939 // Nothing farther to do.
2940 return;
2941 }
2942
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002943 final Uri intentUri = intent.getData();
2944 final String packageName = (intentUri != null) ? intentUri.getSchemeSpecificPart()
2945 : null;
2946 if (packageName == null) {
2947 Slog.w(TAG, "Intent broadcast does not contain package name: " + intent);
2948 return;
2949 }
2950
2951 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
2952
2953 switch (action) {
2954 case Intent.ACTION_PACKAGE_ADDED:
2955 if (replacing) {
2956 handlePackageUpdateFinished(packageName, userId);
2957 } else {
2958 handlePackageAdded(packageName, userId);
2959 }
2960 break;
2961 case Intent.ACTION_PACKAGE_REMOVED:
2962 if (!replacing) {
2963 handlePackageRemoved(packageName, userId);
2964 }
2965 break;
2966 case Intent.ACTION_PACKAGE_CHANGED:
2967 handlePackageChanged(packageName, userId);
2968
2969 break;
2970 case Intent.ACTION_PACKAGE_DATA_CLEARED:
2971 handlePackageDataCleared(packageName, userId);
2972 break;
2973 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07002974 } catch (Exception e) {
2975 wtf("Exception in mPackageMonitor.onReceive", e);
Makoto Onukif34c3082016-07-13 10:25:25 -07002976 } finally {
2977 injectRestoreCallingIdentity(token);
Makoto Onukia2241832016-07-06 13:28:37 -07002978 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07002979 }
Makoto Onukif34c3082016-07-13 10:25:25 -07002980 };
Makoto Onukicdc78f72016-03-21 15:47:52 -07002981
Makoto Onuki0acbb142016-03-22 17:02:57 -07002982 /**
Makoto Onuki39686e82016-04-13 18:03:00 -07002983 * Called when a user is unlocked.
2984 * - Check all known packages still exist, and otherwise perform cleanup.
2985 * - If a package still exists, check the version code. If it's been updated, may need to
Makoto Onukib08790c2016-06-23 14:05:46 -07002986 * update timestamps of its shortcuts.
Makoto Onuki0acbb142016-03-22 17:02:57 -07002987 */
Makoto Onukid99c6f02016-03-28 11:02:54 -07002988 @VisibleForTesting
Makoto Onuki39686e82016-04-13 18:03:00 -07002989 void checkPackageChanges(@UserIdInt int ownerUserId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07002990 if (DEBUG) {
Makoto Onuki39686e82016-04-13 18:03:00 -07002991 Slog.d(TAG, "checkPackageChanges() ownerUserId=" + ownerUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002992 }
Makoto Onukib08790c2016-06-23 14:05:46 -07002993 if (injectIsSafeModeEnabled()) {
2994 Slog.i(TAG, "Safe mode, skipping checkPackageChanges()");
2995 return;
2996 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07002997
Makoto Onuki84d59342018-02-02 09:22:38 -08002998 final long start = getStatStartTime();
Makoto Onuki22fcc682016-05-17 14:52:19 -07002999 try {
3000 final ArrayList<PackageWithUser> gonePackages = new ArrayList<>();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003001
Makoto Onuki22fcc682016-05-17 14:52:19 -07003002 synchronized (mLock) {
3003 final ShortcutUser user = getUserShortcutsLocked(ownerUserId);
3004
3005 // Find packages that have been uninstalled.
3006 user.forAllPackageItems(spi -> {
3007 if (spi.getPackageInfo().isShadow()) {
3008 return; // Don't delete shadow information.
3009 }
3010 if (!isPackageInstalled(spi.getPackageName(), spi.getPackageUserId())) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003011 if (DEBUG) {
3012 Slog.d(TAG, "Uninstalled: " + spi.getPackageName()
3013 + " user " + spi.getPackageUserId());
3014 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07003015 gonePackages.add(PackageWithUser.of(spi));
3016 }
3017 });
3018 if (gonePackages.size() > 0) {
3019 for (int i = gonePackages.size() - 1; i >= 0; i--) {
3020 final PackageWithUser pu = gonePackages.get(i);
Makoto Onukib08790c2016-06-23 14:05:46 -07003021 cleanUpPackageLocked(pu.packageName, ownerUserId, pu.userId,
3022 /* appStillExists = */ false);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003023 }
Makoto Onukid99c6f02016-03-28 11:02:54 -07003024 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07003025
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003026 rescanUpdatedPackagesLocked(ownerUserId, user.getLastAppScanTime());
Makoto Onuki0acbb142016-03-22 17:02:57 -07003027 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07003028 } finally {
3029 logDurationStat(Stats.CHECK_PACKAGE_CHANGES, start);
Makoto Onuki0acbb142016-03-22 17:02:57 -07003030 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07003031 verifyStates();
Makoto Onukicdc78f72016-03-21 15:47:52 -07003032 }
3033
Andreas Gampea36dc622018-02-05 17:19:22 -08003034 @GuardedBy("mLock")
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003035 private void rescanUpdatedPackagesLocked(@UserIdInt int userId, long lastScanTime) {
Makoto Onuki377b7972016-08-09 14:43:55 -07003036 final ShortcutUser user = getUserShortcutsLocked(userId);
3037
Makoto Onuki33663282016-08-22 16:19:04 -07003038 // Note after each OTA, we'll need to rescan all system apps, as their lastUpdateTime
3039 // is not reliable.
Makoto Onuki377b7972016-08-09 14:43:55 -07003040 final long now = injectCurrentTimeMillis();
Makoto Onuki33663282016-08-22 16:19:04 -07003041 final boolean afterOta =
3042 !injectBuildFingerprint().equals(user.getLastAppScanOsFingerprint());
Makoto Onuki377b7972016-08-09 14:43:55 -07003043
3044 // Then for each installed app, publish manifest shortcuts when needed.
Makoto Onuki33663282016-08-22 16:19:04 -07003045 forUpdatedPackages(userId, lastScanTime, afterOta, ai -> {
Makoto Onuki377b7972016-08-09 14:43:55 -07003046 user.attemptToRestoreIfNeededAndSave(this, ai.packageName, userId);
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003047
3048 user.rescanPackageIfNeeded(ai.packageName, /* forceRescan= */ true);
Makoto Onuki377b7972016-08-09 14:43:55 -07003049 });
3050
3051 // Write the time just before the scan, because there may be apps that have just
3052 // been updated, and we want to catch them in the next time.
3053 user.setLastAppScanTime(now);
Makoto Onuki33663282016-08-22 16:19:04 -07003054 user.setLastAppScanOsFingerprint(injectBuildFingerprint());
Makoto Onuki377b7972016-08-09 14:43:55 -07003055 scheduleSaveUser(userId);
3056 }
3057
Makoto Onuki0acbb142016-03-22 17:02:57 -07003058 private void handlePackageAdded(String packageName, @UserIdInt int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07003059 if (DEBUG) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07003060 Slog.d(TAG, String.format("handlePackageAdded: %s user=%d", packageName, userId));
3061 }
3062 synchronized (mLock) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07003063 final ShortcutUser user = getUserShortcutsLocked(userId);
3064 user.attemptToRestoreIfNeededAndSave(this, packageName, userId);
Makoto Onuki64183d52016-08-08 14:11:34 -07003065 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onuki0acbb142016-03-22 17:02:57 -07003066 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07003067 verifyStates();
Makoto Onuki0acbb142016-03-22 17:02:57 -07003068 }
3069
3070 private void handlePackageUpdateFinished(String packageName, @UserIdInt int userId) {
Makoto Onuki905e8852016-03-28 10:40:58 -07003071 if (DEBUG) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003072 Slog.d(TAG, String.format("handlePackageUpdateFinished: %s user=%d",
3073 packageName, userId));
Makoto Onuki0acbb142016-03-22 17:02:57 -07003074 }
3075 synchronized (mLock) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07003076 final ShortcutUser user = getUserShortcutsLocked(userId);
3077 user.attemptToRestoreIfNeededAndSave(this, packageName, userId);
Makoto Onuki39686e82016-04-13 18:03:00 -07003078
Makoto Onuki22fcc682016-05-17 14:52:19 -07003079 if (isPackageInstalled(packageName, userId)) {
Makoto Onuki64183d52016-08-08 14:11:34 -07003080 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onuki39686e82016-04-13 18:03:00 -07003081 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07003082 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07003083 verifyStates();
Makoto Onuki0acbb142016-03-22 17:02:57 -07003084 }
3085
Makoto Onuki2e210c42016-03-30 08:30:36 -07003086 private void handlePackageRemoved(String packageName, @UserIdInt int packageUserId) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07003087 if (DEBUG) {
Makoto Onuki2e210c42016-03-30 08:30:36 -07003088 Slog.d(TAG, String.format("handlePackageRemoved: %s user=%d", packageName,
3089 packageUserId));
Makoto Onukicdc78f72016-03-21 15:47:52 -07003090 }
Makoto Onukib08790c2016-06-23 14:05:46 -07003091 cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ false);
Makoto Onuki9e1f5592016-06-08 12:30:23 -07003092
3093 verifyStates();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003094 }
3095
Makoto Onuki9ac59d02016-04-26 11:23:14 -07003096 private void handlePackageDataCleared(String packageName, int packageUserId) {
3097 if (DEBUG) {
3098 Slog.d(TAG, String.format("handlePackageDataCleared: %s user=%d", packageName,
3099 packageUserId));
Makoto Onukicdc78f72016-03-21 15:47:52 -07003100 }
Makoto Onukib08790c2016-06-23 14:05:46 -07003101 cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ true);
3102
3103 verifyStates();
3104 }
3105
3106 private void handlePackageChanged(String packageName, int packageUserId) {
Makoto Onuki82fb2eb2017-03-31 16:58:26 -07003107 if (!isPackageInstalled(packageName, packageUserId)) {
3108 // Probably disabled, which is the same thing as uninstalled.
3109 handlePackageRemoved(packageName, packageUserId);
3110 return;
3111 }
Makoto Onukib08790c2016-06-23 14:05:46 -07003112 if (DEBUG) {
3113 Slog.d(TAG, String.format("handlePackageChanged: %s user=%d", packageName,
3114 packageUserId));
3115 }
3116
3117 // Activities may be disabled or enabled. Just rescan the package.
3118 synchronized (mLock) {
3119 final ShortcutUser user = getUserShortcutsLocked(packageUserId);
3120
Makoto Onuki4e6cef42016-07-13 16:14:01 -07003121 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07003122 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07003123
3124 verifyStates();
Makoto Onukicdc78f72016-03-21 15:47:52 -07003125 }
3126
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003127 // === PackageManager interaction ===
Makoto Onuki0acbb142016-03-22 17:02:57 -07003128
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003129 /**
3130 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
3131 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07003132 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003133 final PackageInfo getPackageInfoWithSignatures(String packageName, @UserIdInt int userId) {
3134 return getPackageInfo(packageName, userId, true);
Makoto Onuki0acbb142016-03-22 17:02:57 -07003135 }
3136
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003137 /**
3138 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
3139 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07003140 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003141 final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId) {
3142 return getPackageInfo(packageName, userId, false);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003143 }
3144
Makoto Onuki905e8852016-03-28 10:40:58 -07003145 int injectGetPackageUid(@NonNull String packageName, @UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003146 final long token = injectClearCallingIdentity();
Makoto Onuki905e8852016-03-28 10:40:58 -07003147 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003148 return mIPackageManager.getPackageUid(packageName, PACKAGE_MATCH_FLAGS, userId);
Makoto Onuki905e8852016-03-28 10:40:58 -07003149 } catch (RemoteException e) {
3150 // Shouldn't happen.
3151 Slog.wtf(TAG, "RemoteException", e);
3152 return -1;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003153 } finally {
3154 injectRestoreCallingIdentity(token);
Makoto Onuki905e8852016-03-28 10:40:58 -07003155 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07003156 }
3157
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003158 /**
3159 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
3160 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07003161 @Nullable
Makoto Onuki0acbb142016-03-22 17:02:57 -07003162 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003163 final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId,
3164 boolean getSignatures) {
3165 return isInstalledOrNull(injectPackageInfoWithUninstalled(
3166 packageName, userId, getSignatures));
3167 }
3168
3169 /**
3170 * Do not use directly; this returns uninstalled packages too.
3171 */
3172 @Nullable
3173 @VisibleForTesting
3174 PackageInfo injectPackageInfoWithUninstalled(String packageName, @UserIdInt int userId,
Makoto Onuki0acbb142016-03-22 17:02:57 -07003175 boolean getSignatures) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003176 final long start = getStatStartTime();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003177 final long token = injectClearCallingIdentity();
Makoto Onuki0acbb142016-03-22 17:02:57 -07003178 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003179 return mIPackageManager.getPackageInfo(
3180 packageName, PACKAGE_MATCH_FLAGS
Michal Karpinski528c3e52018-02-07 17:47:10 +00003181 | (getSignatures ? PackageManager.GET_SIGNING_CERTIFICATES : 0),
3182 userId);
Makoto Onuki0acbb142016-03-22 17:02:57 -07003183 } catch (RemoteException e) {
3184 // Shouldn't happen.
3185 Slog.wtf(TAG, "RemoteException", e);
3186 return null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003187 } finally {
3188 injectRestoreCallingIdentity(token);
Makoto Onuki2e210c42016-03-30 08:30:36 -07003189
3190 logDurationStat(
3191 (getSignatures ? Stats.GET_PACKAGE_INFO_WITH_SIG : Stats.GET_PACKAGE_INFO),
3192 start);
Makoto Onuki0acbb142016-03-22 17:02:57 -07003193 }
3194 }
3195
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003196 /**
3197 * Returns {@link ApplicationInfo} unless it's uninstalled or disabled.
3198 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07003199 @Nullable
Makoto Onuki905e8852016-03-28 10:40:58 -07003200 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003201 final ApplicationInfo getApplicationInfo(String packageName, @UserIdInt int userId) {
3202 return isInstalledOrNull(injectApplicationInfoWithUninstalled(packageName, userId));
3203 }
3204
3205 /**
3206 * Do not use directly; this returns uninstalled packages too.
3207 */
3208 @Nullable
3209 @VisibleForTesting
3210 ApplicationInfo injectApplicationInfoWithUninstalled(
3211 String packageName, @UserIdInt int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003212 final long start = getStatStartTime();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003213 final long token = injectClearCallingIdentity();
Makoto Onuki905e8852016-03-28 10:40:58 -07003214 try {
3215 return mIPackageManager.getApplicationInfo(packageName, PACKAGE_MATCH_FLAGS, userId);
3216 } catch (RemoteException e) {
3217 // Shouldn't happen.
3218 Slog.wtf(TAG, "RemoteException", e);
3219 return null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003220 } finally {
3221 injectRestoreCallingIdentity(token);
Makoto Onuki2e210c42016-03-30 08:30:36 -07003222
3223 logDurationStat(Stats.GET_APPLICATION_INFO, start);
Makoto Onuki905e8852016-03-28 10:40:58 -07003224 }
3225 }
3226
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003227 /**
3228 * Returns {@link ActivityInfo} with its metadata unless it's uninstalled or disabled.
3229 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07003230 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003231 final ActivityInfo getActivityInfoWithMetadata(ComponentName activity, @UserIdInt int userId) {
3232 return isInstalledOrNull(injectGetActivityInfoWithMetadataWithUninstalled(
3233 activity, userId));
3234 }
3235
3236 /**
3237 * Do not use directly; this returns uninstalled packages too.
3238 */
3239 @Nullable
3240 @VisibleForTesting
3241 ActivityInfo injectGetActivityInfoWithMetadataWithUninstalled(
3242 ComponentName activity, @UserIdInt int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003243 final long start = getStatStartTime();
Makoto Onuki22fcc682016-05-17 14:52:19 -07003244 final long token = injectClearCallingIdentity();
3245 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07003246 return mIPackageManager.getActivityInfo(activity,
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003247 (PACKAGE_MATCH_FLAGS | PackageManager.GET_META_DATA), userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003248 } catch (RemoteException e) {
3249 // Shouldn't happen.
3250 Slog.wtf(TAG, "RemoteException", e);
3251 return null;
3252 } finally {
3253 injectRestoreCallingIdentity(token);
3254
Makoto Onukib08790c2016-06-23 14:05:46 -07003255 logDurationStat(Stats.GET_ACTIVITY_WITH_METADATA, start);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003256 }
3257 }
3258
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003259 /**
3260 * Return all installed and enabled packages.
3261 */
3262 @NonNull
Makoto Onuki22fcc682016-05-17 14:52:19 -07003263 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003264 final List<PackageInfo> getInstalledPackages(@UserIdInt int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003265 final long start = getStatStartTime();
Makoto Onuki22fcc682016-05-17 14:52:19 -07003266 final long token = injectClearCallingIdentity();
3267 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003268 final List<PackageInfo> all = injectGetPackagesWithUninstalled(userId);
3269
3270 all.removeIf(PACKAGE_NOT_INSTALLED);
3271
3272 return all;
Makoto Onuki22fcc682016-05-17 14:52:19 -07003273 } catch (RemoteException e) {
3274 // Shouldn't happen.
3275 Slog.wtf(TAG, "RemoteException", e);
3276 return null;
3277 } finally {
3278 injectRestoreCallingIdentity(token);
3279
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003280 logDurationStat(Stats.GET_INSTALLED_PACKAGES, start);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003281 }
3282 }
3283
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003284 /**
3285 * Do not use directly; this returns uninstalled packages too.
3286 */
3287 @NonNull
3288 @VisibleForTesting
3289 List<PackageInfo> injectGetPackagesWithUninstalled(@UserIdInt int userId)
3290 throws RemoteException {
3291 final ParceledListSlice<PackageInfo> parceledList =
3292 mIPackageManager.getInstalledPackages(PACKAGE_MATCH_FLAGS, userId);
3293 if (parceledList == null) {
3294 return Collections.emptyList();
3295 }
3296 return parceledList.getList();
3297 }
3298
Makoto Onuki33663282016-08-22 16:19:04 -07003299 private void forUpdatedPackages(@UserIdInt int userId, long lastScanTime, boolean afterOta,
Makoto Onuki22fcc682016-05-17 14:52:19 -07003300 Consumer<ApplicationInfo> callback) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003301 if (DEBUG) {
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003302 Slog.d(TAG, "forUpdatedPackages for user " + userId + ", lastScanTime=" + lastScanTime
3303 + " afterOta=" + afterOta);
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003304 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003305 final List<PackageInfo> list = getInstalledPackages(userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003306 for (int i = list.size() - 1; i >= 0; i--) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003307 final PackageInfo pi = list.get(i);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003308
Makoto Onuki64183d52016-08-08 14:11:34 -07003309 // If the package has been updated since the last scan time, then scan it.
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003310 // Also if it's right after an OTA, always re-scan all apps anyway, since the
3311 // shortcut parser might have changed.
3312 if (afterOta || (pi.lastUpdateTime >= lastScanTime)) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003313 if (DEBUG) {
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003314 Slog.d(TAG, "Found updated package " + pi.packageName
3315 + " updateTime=" + pi.lastUpdateTime);
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003316 }
3317 callback.accept(pi.applicationInfo);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003318 }
3319 }
3320 }
3321
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003322 private boolean isApplicationFlagSet(@NonNull String packageName, int userId, int flags) {
3323 final ApplicationInfo ai = injectApplicationInfoWithUninstalled(packageName, userId);
Makoto Onuki905e8852016-03-28 10:40:58 -07003324 return (ai != null) && ((ai.flags & flags) == flags);
3325 }
3326
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003327 private static boolean isInstalled(@Nullable ApplicationInfo ai) {
Makoto Onuki82fb2eb2017-03-31 16:58:26 -07003328 return (ai != null) && ai.enabled && (ai.flags & ApplicationInfo.FLAG_INSTALLED) != 0;
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003329 }
3330
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08003331 private static boolean isEphemeralApp(@Nullable ApplicationInfo ai) {
Svetoslav Ganov096d3042017-01-30 16:34:13 -08003332 return (ai != null) && ai.isInstantApp();
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08003333 }
3334
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003335 private static boolean isInstalled(@Nullable PackageInfo pi) {
3336 return (pi != null) && isInstalled(pi.applicationInfo);
3337 }
3338
3339 private static boolean isInstalled(@Nullable ActivityInfo ai) {
3340 return (ai != null) && isInstalled(ai.applicationInfo);
3341 }
3342
3343 private static ApplicationInfo isInstalledOrNull(ApplicationInfo ai) {
3344 return isInstalled(ai) ? ai : null;
3345 }
3346
3347 private static PackageInfo isInstalledOrNull(PackageInfo pi) {
3348 return isInstalled(pi) ? pi : null;
3349 }
3350
3351 private static ActivityInfo isInstalledOrNull(ActivityInfo ai) {
3352 return isInstalled(ai) ? ai : null;
3353 }
3354
Makoto Onuki2e210c42016-03-30 08:30:36 -07003355 boolean isPackageInstalled(String packageName, int userId) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003356 return getApplicationInfo(packageName, userId) != null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003357 }
3358
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08003359 boolean isEphemeralApp(String packageName, int userId) {
3360 return isEphemeralApp(getApplicationInfo(packageName, userId));
3361 }
3362
Makoto Onuki22fcc682016-05-17 14:52:19 -07003363 @Nullable
3364 XmlResourceParser injectXmlMetaData(ActivityInfo activityInfo, String key) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07003365 return activityInfo.loadXmlMetaData(mContext.getPackageManager(), key);
Makoto Onuki39686e82016-04-13 18:03:00 -07003366 }
3367
Makoto Onuki157b1622016-06-02 16:13:10 -07003368 @Nullable
3369 Resources injectGetResourcesForApplicationAsUser(String packageName, int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003370 final long start = getStatStartTime();
Makoto Onuki157b1622016-06-02 16:13:10 -07003371 final long token = injectClearCallingIdentity();
3372 try {
3373 return mContext.getPackageManager().getResourcesForApplicationAsUser(
3374 packageName, userId);
3375 } catch (NameNotFoundException e) {
3376 Slog.e(TAG, "Resources for package " + packageName + " not found");
3377 return null;
3378 } finally {
3379 injectRestoreCallingIdentity(token);
3380
3381 logDurationStat(Stats.GET_APPLICATION_RESOURCES, start);
3382 }
3383 }
3384
Makoto Onukib08790c2016-06-23 14:05:46 -07003385 private Intent getMainActivityIntent() {
3386 final Intent intent = new Intent(Intent.ACTION_MAIN);
3387 intent.addCategory(LAUNCHER_INTENT_CATEGORY);
3388 return intent;
3389 }
3390
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003391 /**
3392 * Same as queryIntentActivitiesAsUser, except it makes sure the package is installed,
3393 * and only returns exported activities.
3394 */
3395 @NonNull
3396 @VisibleForTesting
3397 List<ResolveInfo> queryActivities(@NonNull Intent baseIntent,
3398 @NonNull String packageName, @Nullable ComponentName activity, int userId) {
3399
3400 baseIntent.setPackage(Preconditions.checkNotNull(packageName));
3401 if (activity != null) {
3402 baseIntent.setComponent(activity);
3403 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08003404 return queryActivities(baseIntent, userId, /* exportedOnly =*/ true);
3405 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003406
Makoto Onuki2d895c32016-12-02 15:48:40 -08003407 @NonNull
3408 List<ResolveInfo> queryActivities(@NonNull Intent intent, int userId,
3409 boolean exportedOnly) {
3410 final List<ResolveInfo> resolved;
3411 final long token = injectClearCallingIdentity();
3412 try {
3413 resolved =
3414 mContext.getPackageManager().queryIntentActivitiesAsUser(
3415 intent, PACKAGE_MATCH_FLAGS, userId);
3416 } finally {
3417 injectRestoreCallingIdentity(token);
3418 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003419 if (resolved == null || resolved.size() == 0) {
3420 return EMPTY_RESOLVE_INFO;
3421 }
3422 // Make sure the package is installed.
3423 if (!isInstalled(resolved.get(0).activityInfo)) {
3424 return EMPTY_RESOLVE_INFO;
3425 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08003426 if (exportedOnly) {
3427 resolved.removeIf(ACTIVITY_NOT_EXPORTED);
3428 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003429 return resolved;
3430 }
3431
3432 /**
3433 * Return the main activity that is enabled and exported. If multiple activities are found,
3434 * return the first one.
3435 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003436 @Nullable
3437 ComponentName injectGetDefaultMainActivity(@NonNull String packageName, int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003438 final long start = getStatStartTime();
Makoto Onukib08790c2016-06-23 14:05:46 -07003439 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07003440 final List<ResolveInfo> resolved =
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003441 queryActivities(getMainActivityIntent(), packageName, null, userId);
3442 return resolved.size() == 0 ? null : resolved.get(0).activityInfo.getComponentName();
Makoto Onukib08790c2016-06-23 14:05:46 -07003443 } finally {
Makoto Onukib08790c2016-06-23 14:05:46 -07003444 logDurationStat(Stats.GET_LAUNCHER_ACTIVITY, start);
3445 }
3446 }
3447
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003448 /**
3449 * Return whether an activity is enabled, exported and main.
3450 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003451 boolean injectIsMainActivity(@NonNull ComponentName activity, int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003452 final long start = getStatStartTime();
Makoto Onukib08790c2016-06-23 14:05:46 -07003453 try {
Makoto Onuki34145532017-03-14 17:58:36 -07003454 if (activity == null) {
3455 wtf("null activity detected");
3456 return false;
3457 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08003458 if (DUMMY_MAIN_ACTIVITY.equals(activity.getClassName())) {
3459 return true;
3460 }
3461 final List<ResolveInfo> resolved = queryActivities(
3462 getMainActivityIntent(), activity.getPackageName(), activity, userId);
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003463 return resolved.size() > 0;
Makoto Onukib08790c2016-06-23 14:05:46 -07003464 } finally {
Makoto Onukib08790c2016-06-23 14:05:46 -07003465 logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start);
3466 }
3467 }
3468
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003469 /**
Makoto Onuki2d895c32016-12-02 15:48:40 -08003470 * Create a dummy "main activity" component name which is used to create a dynamic shortcut
3471 * with no main activity temporarily.
3472 */
3473 @NonNull
3474 ComponentName getDummyMainActivity(@NonNull String packageName) {
3475 return new ComponentName(packageName, DUMMY_MAIN_ACTIVITY);
3476 }
3477
Makoto Onuki255461f2017-01-10 11:47:25 -08003478 boolean isDummyMainActivity(@Nullable ComponentName name) {
3479 return name != null && DUMMY_MAIN_ACTIVITY.equals(name.getClassName());
3480 }
3481
Makoto Onuki2d895c32016-12-02 15:48:40 -08003482 /**
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003483 * Return all the enabled, exported and main activities from a package.
3484 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003485 @NonNull
3486 List<ResolveInfo> injectGetMainActivities(@NonNull String packageName, int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003487 final long start = getStatStartTime();
Makoto Onukib08790c2016-06-23 14:05:46 -07003488 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003489 return queryActivities(getMainActivityIntent(), packageName, null, userId);
Makoto Onukib08790c2016-06-23 14:05:46 -07003490 } finally {
Makoto Onukib08790c2016-06-23 14:05:46 -07003491 logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start);
3492 }
3493 }
3494
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003495 /**
3496 * Return whether an activity is enabled and exported.
3497 */
3498 @VisibleForTesting
3499 boolean injectIsActivityEnabledAndExported(
3500 @NonNull ComponentName activity, @UserIdInt int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003501 final long start = getStatStartTime();
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003502 try {
3503 return queryActivities(new Intent(), activity.getPackageName(), activity, userId)
3504 .size() > 0;
3505 } finally {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003506 logDurationStat(Stats.IS_ACTIVITY_ENABLED, start);
3507 }
3508 }
3509
Makoto Onuki2d895c32016-12-02 15:48:40 -08003510 /**
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003511 * Get the {@link LauncherApps#ACTION_CONFIRM_PIN_SHORTCUT} or
3512 * {@link LauncherApps#ACTION_CONFIRM_PIN_APPWIDGET} activity in a given package depending on
3513 * the requestType.
Makoto Onuki2d895c32016-12-02 15:48:40 -08003514 */
3515 @Nullable
3516 ComponentName injectGetPinConfirmationActivity(@NonNull String launcherPackageName,
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003517 int launcherUserId, int requestType) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08003518 Preconditions.checkNotNull(launcherPackageName);
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003519 String action = requestType == LauncherApps.PinItemRequest.REQUEST_TYPE_SHORTCUT ?
3520 LauncherApps.ACTION_CONFIRM_PIN_SHORTCUT :
3521 LauncherApps.ACTION_CONFIRM_PIN_APPWIDGET;
Makoto Onuki2d895c32016-12-02 15:48:40 -08003522
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003523 final Intent confirmIntent = new Intent(action).setPackage(launcherPackageName);
Makoto Onuki2d895c32016-12-02 15:48:40 -08003524 final List<ResolveInfo> candidates = queryActivities(
3525 confirmIntent, launcherUserId, /* exportedOnly =*/ false);
3526 for (ResolveInfo ri : candidates) {
3527 return ri.activityInfo.getComponentName();
3528 }
3529 return null;
3530 }
3531
Makoto Onukib08790c2016-06-23 14:05:46 -07003532 boolean injectIsSafeModeEnabled() {
3533 final long token = injectClearCallingIdentity();
3534 try {
3535 return IWindowManager.Stub
3536 .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE))
3537 .isSafeModeEnabled();
3538 } catch (RemoteException e) {
3539 return false; // Shouldn't happen though.
3540 } finally {
3541 injectRestoreCallingIdentity(token);
3542 }
3543 }
3544
Makoto Onuki2d895c32016-12-02 15:48:40 -08003545 /**
3546 * If {@code userId} is of a managed profile, return the parent user ID. Otherwise return
3547 * itself.
3548 */
3549 int getParentOrSelfUserId(int userId) {
Sunny Goyal145c8f82018-02-15 14:27:09 -08003550 return mUserManagerInternal.getProfileParentId(userId);
Makoto Onuki2d895c32016-12-02 15:48:40 -08003551 }
3552
Sunny Goyal87a563e2017-01-01 19:42:45 -08003553 void injectSendIntentSender(IntentSender intentSender, Intent extras) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08003554 if (intentSender == null) {
3555 return;
3556 }
3557 try {
Sunny Goyal87a563e2017-01-01 19:42:45 -08003558 intentSender.sendIntent(mContext, /* code= */ 0, extras,
Makoto Onuki2d895c32016-12-02 15:48:40 -08003559 /* onFinished=*/ null, /* handler= */ null);
3560 } catch (SendIntentException e) {
3561 Slog.w(TAG, "sendIntent failed().", e);
3562 }
3563 }
3564
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003565 // === Backup & restore ===
3566
Makoto Onuki0acbb142016-03-22 17:02:57 -07003567 boolean shouldBackupApp(String packageName, int userId) {
Makoto Onuki905e8852016-03-28 10:40:58 -07003568 return isApplicationFlagSet(packageName, userId, ApplicationInfo.FLAG_ALLOW_BACKUP);
Makoto Onuki0acbb142016-03-22 17:02:57 -07003569 }
3570
Makoto Onukia4f89b12017-10-05 10:37:55 -07003571 static boolean shouldBackupApp(PackageInfo pi) {
Makoto Onuki2e210c42016-03-30 08:30:36 -07003572 return (pi.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0;
3573 }
3574
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003575 @Override
Makoto Onuki2e210c42016-03-30 08:30:36 -07003576 public byte[] getBackupPayload(@UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003577 enforceSystem();
3578 if (DEBUG) {
3579 Slog.d(TAG, "Backing up user " + userId);
3580 }
3581 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003582 if (!isUserUnlockedL(userId)) {
3583 wtf("Can't backup: user " + userId + " is locked or not running");
3584 return null;
3585 }
3586
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003587 final ShortcutUser user = getUserShortcutsLocked(userId);
3588 if (user == null) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003589 wtf("Can't backup: user not found: id=" + userId);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003590 return null;
3591 }
3592
Makoto Onukic8c33292016-09-12 16:36:59 -07003593 // Update the signatures for all packages.
3594 user.forAllPackageItems(spi -> spi.refreshPackageSignatureAndSave());
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003595
Makoto Onukie3fffa92018-02-28 16:25:40 -08003596 // Rescan all apps; this will also update the version codes and "allow-backup".
3597 user.forAllPackages(pkg -> pkg.rescanPackageIfNeeded(
3598 /*isNewApp=*/ false, /*forceRescan=*/ true));
3599
Makoto Onukic8c33292016-09-12 16:36:59 -07003600 // Set the version code for the launchers.
Makoto Onukia4f89b12017-10-05 10:37:55 -07003601 user.forAllLaunchers(launcher -> launcher.ensurePackageInfo());
Makoto Onukic8c33292016-09-12 16:36:59 -07003602
3603 // Save to the filesystem.
3604 scheduleSaveUser(userId);
3605 saveDirtyInfo();
3606
Makoto Onuki475c3652017-05-08 14:29:03 -07003607 // Note, in case of backup, we don't have to wait on bitmap saving, because we don't
3608 // back up bitmaps anyway.
3609
Makoto Onukic8c33292016-09-12 16:36:59 -07003610 // Then create the backup payload.
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003611 final ByteArrayOutputStream os = new ByteArrayOutputStream(32 * 1024);
3612 try {
3613 saveUserInternalLocked(userId, os, /* forBackup */ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07003614 } catch (XmlPullParserException | IOException e) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003615 // Shouldn't happen.
3616 Slog.w(TAG, "Backup failed.", e);
3617 return null;
3618 }
Makoto Onukie3fffa92018-02-28 16:25:40 -08003619 byte[] payload = os.toByteArray();
3620 mShortcutDumpFiles.save("backup-1-payload.txt", payload);
3621 return payload;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003622 }
3623 }
3624
3625 @Override
Makoto Onuki2e210c42016-03-30 08:30:36 -07003626 public void applyRestore(byte[] payload, @UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003627 enforceSystem();
3628 if (DEBUG) {
3629 Slog.d(TAG, "Restoring user " + userId);
3630 }
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003631 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003632 if (!isUserUnlockedL(userId)) {
3633 wtf("Can't restore: user " + userId + " is locked or not running");
3634 return;
3635 }
Makoto Onuki50a320e2017-05-31 14:38:42 -07003636
3637 // Note we print the file timestamps in dumpsys too, but also printing the timestamp
3638 // in the files anyway.
3639 mShortcutDumpFiles.save("restore-0-start.txt", pw -> {
3640 pw.print("Start time: ");
3641 dumpCurrentTime(pw);
3642 pw.println();
3643 });
3644 mShortcutDumpFiles.save("restore-1-payload.xml", payload);
3645
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003646 // Actually do restore.
3647 final ShortcutUser restored;
Makoto Onuki02f338e2016-07-29 09:40:40 -07003648 final ByteArrayInputStream is = new ByteArrayInputStream(payload);
3649 try {
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003650 restored = loadUserInternal(userId, is, /* fromBackup */ true);
3651 } catch (XmlPullParserException | IOException | InvalidFileFormatException e) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003652 Slog.w(TAG, "Restoration failed.", e);
3653 return;
3654 }
Makoto Onuki50a320e2017-05-31 14:38:42 -07003655 mShortcutDumpFiles.save("restore-2.txt", this::dumpInner);
3656
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003657 getUserShortcutsLocked(userId).mergeRestoredFile(restored);
Makoto Onuki2e210c42016-03-30 08:30:36 -07003658
Makoto Onuki50a320e2017-05-31 14:38:42 -07003659 mShortcutDumpFiles.save("restore-3.txt", this::dumpInner);
3660
Makoto Onuki377b7972016-08-09 14:43:55 -07003661 // Rescan all packages to re-publish manifest shortcuts and do other checks.
3662 rescanUpdatedPackagesLocked(userId,
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003663 0 // lastScanTime = 0; rescan all packages.
3664 );
Makoto Onuki2e210c42016-03-30 08:30:36 -07003665
Makoto Onuki50a320e2017-05-31 14:38:42 -07003666 mShortcutDumpFiles.save("restore-4.txt", this::dumpInner);
3667
3668 mShortcutDumpFiles.save("restore-5-finish.txt", pw -> {
3669 pw.print("Finish time: ");
3670 dumpCurrentTime(pw);
3671 pw.println();
3672 });
3673
Makoto Onuki2e210c42016-03-30 08:30:36 -07003674 saveUserLocked(userId);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003675 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07003676 }
3677
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003678 // === Dump ===
3679
3680 @Override
3681 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06003682 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
Makoto Onukic4361e32017-04-03 11:24:25 -07003683 dumpNoCheck(fd, pw, args);
3684 }
3685
3686 @VisibleForTesting
3687 void dumpNoCheck(FileDescriptor fd, PrintWriter pw, String[] args) {
Makoto Onuki20b82212017-10-04 15:03:50 -07003688 final DumpFilter filter = parseDumpArgs(args);
Makoto Onuki50a320e2017-05-31 14:38:42 -07003689
Makoto Onuki20b82212017-10-04 15:03:50 -07003690 if (filter.shouldDumpCheckIn()) {
Makoto Onuki50a320e2017-05-31 14:38:42 -07003691 // Other flags are not supported for checkin.
Makoto Onuki20b82212017-10-04 15:03:50 -07003692 dumpCheckin(pw, filter.shouldCheckInClear());
Makoto Onuki76269922016-07-15 14:58:54 -07003693 } else {
Makoto Onuki20b82212017-10-04 15:03:50 -07003694 if (filter.shouldDumpMain()) {
3695 dumpInner(pw, filter);
Makoto Onuki50a320e2017-05-31 14:38:42 -07003696 pw.println();
3697 }
Makoto Onuki20b82212017-10-04 15:03:50 -07003698 if (filter.shouldDumpUid()) {
Makoto Onuki50a320e2017-05-31 14:38:42 -07003699 dumpUid(pw);
3700 pw.println();
3701 }
Makoto Onuki20b82212017-10-04 15:03:50 -07003702 if (filter.shouldDumpFiles()) {
Makoto Onuki50a320e2017-05-31 14:38:42 -07003703 dumpDumpFiles(pw);
3704 pw.println();
3705 }
Makoto Onuki76269922016-07-15 14:58:54 -07003706 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003707 }
3708
Makoto Onuki20b82212017-10-04 15:03:50 -07003709 private static DumpFilter parseDumpArgs(String[] args) {
3710 final DumpFilter filter = new DumpFilter();
3711 if (args == null) {
3712 return filter;
3713 }
Makoto Onuki55046222016-03-08 10:49:47 -08003714
Makoto Onuki20b82212017-10-04 15:03:50 -07003715 int argIndex = 0;
3716 while (argIndex < args.length) {
3717 final String arg = args[argIndex++];
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003718
Makoto Onuki20b82212017-10-04 15:03:50 -07003719 if ("-c".equals(arg)) {
3720 filter.setDumpCheckIn(true);
3721 continue;
3722 }
3723 if ("--checkin".equals(arg)) {
3724 filter.setDumpCheckIn(true);
3725 filter.setCheckInClear(true);
3726 continue;
3727 }
3728 if ("-a".equals(arg) || "--all".equals(arg)) {
3729 filter.setDumpUid(true);
3730 filter.setDumpFiles(true);
3731 continue;
3732 }
3733 if ("-u".equals(arg) || "--uid".equals(arg)) {
3734 filter.setDumpUid(true);
3735 continue;
3736 }
3737 if ("-f".equals(arg) || "--files".equals(arg)) {
3738 filter.setDumpFiles(true);
3739 continue;
3740 }
3741 if ("-n".equals(arg) || "--no-main".equals(arg)) {
3742 filter.setDumpMain(false);
3743 continue;
3744 }
3745 if ("--user".equals(arg)) {
3746 if (argIndex >= args.length) {
3747 throw new IllegalArgumentException("Missing user ID for --user");
3748 }
3749 try {
3750 filter.addUser(Integer.parseInt(args[argIndex++]));
3751 } catch (NumberFormatException e) {
3752 throw new IllegalArgumentException("Invalid user ID", e);
3753 }
3754 continue;
3755 }
3756 if ("-p".equals(arg) || "--package".equals(arg)) {
3757 if (argIndex >= args.length) {
3758 throw new IllegalArgumentException("Missing package name for --package");
3759 }
3760 filter.addPackageRegex(args[argIndex++]);
3761 filter.setDumpDetails(false);
3762 continue;
3763 }
3764 if (arg.startsWith("-")) {
3765 throw new IllegalArgumentException("Unknown option " + arg);
3766 }
3767 break;
3768 }
3769 while (argIndex < args.length) {
3770 filter.addPackage(args[argIndex++]);
3771 }
3772 return filter;
3773 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003774
Makoto Onuki20b82212017-10-04 15:03:50 -07003775 static class DumpFilter {
3776 private boolean mDumpCheckIn = false;
3777 private boolean mCheckInClear = false;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003778
Makoto Onuki20b82212017-10-04 15:03:50 -07003779 private boolean mDumpMain = true;
3780 private boolean mDumpUid = false;
3781 private boolean mDumpFiles = false;
Makoto Onuki55046222016-03-08 10:49:47 -08003782
Makoto Onuki20b82212017-10-04 15:03:50 -07003783 private boolean mDumpDetails = true;
3784 private List<Pattern> mPackagePatterns = new ArrayList<>();
3785 private List<Integer> mUsers = new ArrayList<>();
3786
3787 void addPackageRegex(String regex) {
3788 mPackagePatterns.add(Pattern.compile(regex));
3789 }
3790
3791 public void addPackage(String packageName) {
3792 addPackageRegex(Pattern.quote(packageName));
3793 }
3794
3795 void addUser(int userId) {
3796 mUsers.add(userId);
3797 }
3798
3799 boolean isPackageMatch(String packageName) {
3800 if (mPackagePatterns.size() == 0) {
3801 return true;
3802 }
3803 for (int i = 0; i < mPackagePatterns.size(); i++) {
3804 if (mPackagePatterns.get(i).matcher(packageName).find()) {
3805 return true;
Makoto Onuki085a05c2016-08-19 11:39:29 -07003806 }
Makoto Onuki2e210c42016-03-30 08:30:36 -07003807 }
Makoto Onuki20b82212017-10-04 15:03:50 -07003808 return false;
3809 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003810
Makoto Onuki20b82212017-10-04 15:03:50 -07003811 boolean isUserMatch(int userId) {
3812 if (mUsers.size() == 0) {
3813 return true;
3814 }
3815 for (int i = 0; i < mUsers.size(); i++) {
3816 if (mUsers.get(i) == userId) {
3817 return true;
3818 }
3819 }
3820 return false;
3821 }
Makoto Onukia2241832016-07-06 13:28:37 -07003822
Makoto Onuki20b82212017-10-04 15:03:50 -07003823 public boolean shouldDumpCheckIn() {
3824 return mDumpCheckIn;
3825 }
3826
3827 public void setDumpCheckIn(boolean dumpCheckIn) {
3828 mDumpCheckIn = dumpCheckIn;
3829 }
3830
3831 public boolean shouldCheckInClear() {
3832 return mCheckInClear;
3833 }
3834
3835 public void setCheckInClear(boolean checkInClear) {
3836 mCheckInClear = checkInClear;
3837 }
3838
3839 public boolean shouldDumpMain() {
3840 return mDumpMain;
3841 }
3842
3843 public void setDumpMain(boolean dumpMain) {
3844 mDumpMain = dumpMain;
3845 }
3846
3847 public boolean shouldDumpUid() {
3848 return mDumpUid;
3849 }
3850
3851 public void setDumpUid(boolean dumpUid) {
3852 mDumpUid = dumpUid;
3853 }
3854
3855 public boolean shouldDumpFiles() {
3856 return mDumpFiles;
3857 }
3858
3859 public void setDumpFiles(boolean dumpFiles) {
3860 mDumpFiles = dumpFiles;
3861 }
3862
3863 public boolean shouldDumpDetails() {
3864 return mDumpDetails;
3865 }
3866
3867 public void setDumpDetails(boolean dumpDetails) {
3868 mDumpDetails = dumpDetails;
3869 }
3870 }
3871
3872 private void dumpInner(PrintWriter pw) {
3873 dumpInner(pw, new DumpFilter());
3874 }
3875
3876 private void dumpInner(PrintWriter pw, DumpFilter filter) {
3877 synchronized (mLock) {
3878 if (filter.shouldDumpDetails()) {
3879 final long now = injectCurrentTimeMillis();
3880 pw.print("Now: [");
3881 pw.print(now);
3882 pw.print("] ");
3883 pw.print(formatTime(now));
3884
3885 pw.print(" Raw last reset: [");
3886 pw.print(mRawLastResetTime);
3887 pw.print("] ");
3888 pw.print(formatTime(mRawLastResetTime));
3889
3890 final long last = getLastResetTimeLocked();
3891 pw.print(" Last reset: [");
3892 pw.print(last);
3893 pw.print("] ");
3894 pw.print(formatTime(last));
3895
3896 final long next = getNextResetTimeLocked();
3897 pw.print(" Next reset: [");
3898 pw.print(next);
3899 pw.print("] ");
3900 pw.print(formatTime(next));
Makoto Onukie3fffa92018-02-28 16:25:40 -08003901 pw.println();
3902 pw.println();
Makoto Onuki20b82212017-10-04 15:03:50 -07003903
3904 pw.print(" Config:");
3905 pw.print(" Max icon dim: ");
3906 pw.println(mMaxIconDimension);
3907 pw.print(" Icon format: ");
3908 pw.println(mIconPersistFormat);
3909 pw.print(" Icon quality: ");
3910 pw.println(mIconPersistQuality);
3911 pw.print(" saveDelayMillis: ");
3912 pw.println(mSaveDelayMillis);
3913 pw.print(" resetInterval: ");
3914 pw.println(mResetInterval);
3915 pw.print(" maxUpdatesPerInterval: ");
3916 pw.println(mMaxUpdatesPerInterval);
3917 pw.print(" maxShortcutsPerActivity: ");
3918 pw.println(mMaxShortcuts);
3919 pw.println();
3920
Makoto Onuki84d59342018-02-02 09:22:38 -08003921 mStatLogger.dump(pw, " ");
Makoto Onuki20b82212017-10-04 15:03:50 -07003922
3923 pw.println();
3924 pw.print(" #Failures: ");
3925 pw.println(mWtfCount);
3926
3927 if (mLastWtfStacktrace != null) {
3928 pw.print(" Last failure stack trace: ");
3929 pw.println(Log.getStackTraceString(mLastWtfStacktrace));
3930 }
3931
3932 pw.println();
3933 mShortcutBitmapSaver.dumpLocked(pw, " ");
3934
3935 pw.println();
Makoto Onukia2241832016-07-06 13:28:37 -07003936 }
3937
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08003938 for (int i = 0; i < mUsers.size(); i++) {
Makoto Onuki20b82212017-10-04 15:03:50 -07003939 final ShortcutUser user = mUsers.valueAt(i);
3940 if (filter.isUserMatch(user.getUserId())) {
3941 user.dump(pw, " ", filter);
3942 pw.println();
3943 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003944 }
Makoto Onuki708703b2017-12-11 16:38:11 -08003945
3946 for (int i = 0; i < mShortcutNonPersistentUsers.size(); i++) {
3947 final ShortcutNonPersistentUser user = mShortcutNonPersistentUsers.valueAt(i);
3948 if (filter.isUserMatch(user.getUserId())) {
3949 user.dump(pw, " ", filter);
3950 pw.println();
3951 }
3952 }
Makoto Onuki50a320e2017-05-31 14:38:42 -07003953 }
3954 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003955
Makoto Onuki50a320e2017-05-31 14:38:42 -07003956 private void dumpUid(PrintWriter pw) {
3957 synchronized (mLock) {
3958 pw.println("** SHORTCUT MANAGER UID STATES (dumpsys shortcut -n -u)");
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003959
3960 for (int i = 0; i < mUidState.size(); i++) {
3961 final int uid = mUidState.keyAt(i);
3962 final int state = mUidState.valueAt(i);
3963 pw.print(" UID=");
3964 pw.print(uid);
3965 pw.print(" state=");
3966 pw.print(state);
3967 if (isProcessStateForeground(state)) {
3968 pw.print(" [FG]");
3969 }
3970 pw.print(" last FG=");
3971 pw.print(mUidLastForegroundElapsedTime.get(uid));
3972 pw.println();
3973 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003974 }
3975 }
3976
Makoto Onuki41066a62016-03-09 16:18:44 -08003977 static String formatTime(long time) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003978 Time tobj = new Time();
3979 tobj.set(time);
3980 return tobj.format("%Y-%m-%d %H:%M:%S");
3981 }
3982
Makoto Onuki50a320e2017-05-31 14:38:42 -07003983 private void dumpCurrentTime(PrintWriter pw) {
3984 pw.print(formatTime(injectCurrentTimeMillis()));
3985 }
3986
Makoto Onuki76269922016-07-15 14:58:54 -07003987 /**
3988 * Dumpsys for checkin.
3989 *
3990 * @param clear if true, clear the history information. Some other system services have this
3991 * behavior but shortcut service doesn't for now.
3992 */
3993 private void dumpCheckin(PrintWriter pw, boolean clear) {
3994 synchronized (mLock) {
3995 try {
3996 final JSONArray users = new JSONArray();
3997
3998 for (int i = 0; i < mUsers.size(); i++) {
3999 users.put(mUsers.valueAt(i).dumpCheckin(clear));
4000 }
4001
4002 final JSONObject result = new JSONObject();
4003
4004 result.put(KEY_SHORTCUT, users);
4005 result.put(KEY_LOW_RAM, injectIsLowRamDevice());
4006 result.put(KEY_ICON_SIZE, mMaxIconDimension);
4007
4008 pw.println(result.toString(1));
4009 } catch (JSONException e) {
4010 Slog.e(TAG, "Unable to write in json", e);
4011 }
4012 }
4013 }
4014
Makoto Onuki50a320e2017-05-31 14:38:42 -07004015 private void dumpDumpFiles(PrintWriter pw) {
4016 synchronized (mLock) {
4017 pw.println("** SHORTCUT MANAGER FILES (dumpsys shortcut -n -f)");
4018 mShortcutDumpFiles.dumpAll(pw);
4019 }
4020 }
4021
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004022 // === Shell support ===
4023
4024 @Override
4025 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07004026 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004027
4028 enforceShell();
4029
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07004030 final long token = injectClearCallingIdentity();
4031 try {
Dianne Hackborn354736e2016-08-22 17:00:05 -07004032 final int status = (new MyShellCommand()).exec(this, in, out, err, args, callback,
4033 resultReceiver);
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07004034 resultReceiver.send(status, null);
4035 } finally {
4036 injectRestoreCallingIdentity(token);
4037 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004038 }
4039
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004040 static class CommandException extends Exception {
4041 public CommandException(String message) {
4042 super(message);
4043 }
4044 }
4045
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004046 /**
4047 * Handle "adb shell cmd".
4048 */
4049 private class MyShellCommand extends ShellCommand {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004050
4051 private int mUserId = UserHandle.USER_SYSTEM;
4052
Makoto Onuki02f338e2016-07-29 09:40:40 -07004053 private void parseOptionsLocked(boolean takeUser)
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004054 throws CommandException {
4055 String opt;
4056 while ((opt = getNextOption()) != null) {
4057 switch (opt) {
4058 case "--user":
4059 if (takeUser) {
4060 mUserId = UserHandle.parseUserArg(getNextArgRequired());
Makoto Onuki02f338e2016-07-29 09:40:40 -07004061 if (!isUserUnlockedL(mUserId)) {
Makoto Onukif34c3082016-07-13 10:25:25 -07004062 throw new CommandException(
4063 "User " + mUserId + " is not running or locked");
4064 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004065 break;
4066 }
4067 // fallthrough
4068 default:
4069 throw new CommandException("Unknown option: " + opt);
4070 }
4071 }
4072 }
4073
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004074 @Override
4075 public int onCommand(String cmd) {
4076 if (cmd == null) {
4077 return handleDefaultCommands(cmd);
4078 }
4079 final PrintWriter pw = getOutPrintWriter();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004080 try {
4081 switch (cmd) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004082 case "reset-throttling":
4083 handleResetThrottling();
4084 break;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004085 case "reset-all-throttling":
4086 handleResetAllThrottling();
4087 break;
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004088 case "override-config":
4089 handleOverrideConfig();
4090 break;
4091 case "reset-config":
4092 handleResetConfig();
4093 break;
4094 case "clear-default-launcher":
4095 handleClearDefaultLauncher();
4096 break;
4097 case "get-default-launcher":
4098 handleGetDefaultLauncher();
4099 break;
Makoto Onukiac214972016-04-04 10:19:45 -07004100 case "unload-user":
4101 handleUnloadUser();
4102 break;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004103 case "clear-shortcuts":
4104 handleClearShortcuts();
4105 break;
Makoto Onukib08790c2016-06-23 14:05:46 -07004106 case "verify-states": // hidden command to verify various internal states.
4107 handleVerifyStates();
4108 break;
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004109 default:
4110 return handleDefaultCommands(cmd);
4111 }
4112 } catch (CommandException e) {
4113 pw.println("Error: " + e.getMessage());
4114 return 1;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004115 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004116 pw.println("Success");
4117 return 0;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004118 }
4119
4120 @Override
4121 public void onHelp() {
4122 final PrintWriter pw = getOutPrintWriter();
4123 pw.println("Usage: cmd shortcut COMMAND [options ...]");
4124 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004125 pw.println("cmd shortcut reset-throttling [--user USER_ID]");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004126 pw.println(" Reset throttling for all packages and users");
4127 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004128 pw.println("cmd shortcut reset-all-throttling");
4129 pw.println(" Reset the throttling state for all users");
4130 pw.println();
Makoto Onuki4362a662016-03-08 18:59:09 -08004131 pw.println("cmd shortcut override-config CONFIG");
4132 pw.println(" Override the configuration for testing (will last until reboot)");
4133 pw.println();
4134 pw.println("cmd shortcut reset-config");
4135 pw.println(" Reset the configuration set with \"update-config\"");
4136 pw.println();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004137 pw.println("cmd shortcut clear-default-launcher [--user USER_ID]");
4138 pw.println(" Clear the cached default launcher");
4139 pw.println();
4140 pw.println("cmd shortcut get-default-launcher [--user USER_ID]");
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07004141 pw.println(" Show the default launcher");
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004142 pw.println();
Makoto Onukiac214972016-04-04 10:19:45 -07004143 pw.println("cmd shortcut unload-user [--user USER_ID]");
4144 pw.println(" Unload a user from the memory");
4145 pw.println(" (This should not affect any observable behavior)");
4146 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004147 pw.println("cmd shortcut clear-shortcuts [--user USER_ID] PACKAGE");
4148 pw.println(" Remove all shortcuts from a package, including pinned shortcuts");
4149 pw.println();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004150 }
4151
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004152 private void handleResetThrottling() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07004153 synchronized (mLock) {
4154 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki4554d0e2016-03-14 15:51:41 -07004155
Makoto Onuki02f338e2016-07-29 09:40:40 -07004156 Slog.i(TAG, "cmd: handleResetThrottling: user=" + mUserId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004157
Makoto Onuki02f338e2016-07-29 09:40:40 -07004158 resetThrottlingInner(mUserId);
4159 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004160 }
4161
4162 private void handleResetAllThrottling() {
4163 Slog.i(TAG, "cmd: handleResetAllThrottling");
4164
4165 resetAllThrottlingInner();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004166 }
4167
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004168 private void handleOverrideConfig() throws CommandException {
Makoto Onuki4362a662016-03-08 18:59:09 -08004169 final String config = getNextArgRequired();
4170
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004171 Slog.i(TAG, "cmd: handleOverrideConfig: " + config);
4172
Makoto Onuki4362a662016-03-08 18:59:09 -08004173 synchronized (mLock) {
4174 if (!updateConfigurationLocked(config)) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004175 throw new CommandException("override-config failed. See logcat for details.");
Makoto Onuki4362a662016-03-08 18:59:09 -08004176 }
4177 }
Makoto Onuki4362a662016-03-08 18:59:09 -08004178 }
4179
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004180 private void handleResetConfig() {
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004181 Slog.i(TAG, "cmd: handleResetConfig");
4182
Makoto Onuki4362a662016-03-08 18:59:09 -08004183 synchronized (mLock) {
4184 loadConfigurationLocked();
4185 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004186 }
4187
4188 private void clearLauncher() {
4189 synchronized (mLock) {
Makoto Onuki10305202016-07-14 18:14:08 -07004190 getUserShortcutsLocked(mUserId).forceClearLauncher();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004191 }
4192 }
4193
4194 private void showLauncher() {
4195 synchronized (mLock) {
4196 // This ensures to set the cached launcher. Package name doesn't matter.
4197 hasShortcutHostPermissionInner("-", mUserId);
4198
4199 getOutPrintWriter().println("Launcher: "
Makoto Onuki10305202016-07-14 18:14:08 -07004200 + getUserShortcutsLocked(mUserId).getLastKnownLauncher());
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004201 }
4202 }
4203
4204 private void handleClearDefaultLauncher() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07004205 synchronized (mLock) {
4206 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004207
Makoto Onuki02f338e2016-07-29 09:40:40 -07004208 clearLauncher();
4209 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004210 }
4211
4212 private void handleGetDefaultLauncher() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07004213 synchronized (mLock) {
4214 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004215
Makoto Onuki02f338e2016-07-29 09:40:40 -07004216 clearLauncher();
4217 showLauncher();
4218 }
Makoto Onuki4362a662016-03-08 18:59:09 -08004219 }
Makoto Onukiac214972016-04-04 10:19:45 -07004220
4221 private void handleUnloadUser() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07004222 synchronized (mLock) {
4223 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onukiac214972016-04-04 10:19:45 -07004224
Makoto Onuki02f338e2016-07-29 09:40:40 -07004225 Slog.i(TAG, "cmd: handleUnloadUser: user=" + mUserId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004226
Makoto Onuki01ce92b2017-04-28 12:24:16 -07004227 ShortcutService.this.handleStopUser(mUserId);
Makoto Onuki02f338e2016-07-29 09:40:40 -07004228 }
Makoto Onukiac214972016-04-04 10:19:45 -07004229 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004230
4231 private void handleClearShortcuts() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07004232 synchronized (mLock) {
4233 parseOptionsLocked(/* takeUser =*/ true);
4234 final String packageName = getNextArgRequired();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004235
Makoto Onuki02f338e2016-07-29 09:40:40 -07004236 Slog.i(TAG, "cmd: handleClearShortcuts: user" + mUserId + ", " + packageName);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004237
Makoto Onuki02f338e2016-07-29 09:40:40 -07004238 ShortcutService.this.cleanUpPackageForAllLoadedUsers(packageName, mUserId,
4239 /* appStillExists = */ true);
4240 }
Makoto Onukib08790c2016-06-23 14:05:46 -07004241 }
4242
4243 private void handleVerifyStates() throws CommandException {
4244 try {
4245 verifyStatesForce(); // This will throw when there's an issue.
4246 } catch (Throwable th) {
4247 throw new CommandException(th.getMessage() + "\n" + Log.getStackTraceString(th));
4248 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004249 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004250 }
4251
4252 // === Unit test support ===
4253
4254 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07004255 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004256 long injectCurrentTimeMillis() {
4257 return System.currentTimeMillis();
4258 }
4259
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07004260 @VisibleForTesting
4261 long injectElapsedRealtime() {
4262 return SystemClock.elapsedRealtime();
4263 }
4264
Makoto Onuki475c3652017-05-08 14:29:03 -07004265 @VisibleForTesting
4266 long injectUptimeMillis() {
4267 return SystemClock.uptimeMillis();
4268 }
4269
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004270 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07004271 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004272 int injectBinderCallingUid() {
4273 return getCallingUid();
4274 }
4275
Makoto Onuki7d0fa812018-02-21 11:24:43 -08004276 @VisibleForTesting
4277 int injectBinderCallingPid() {
4278 return getCallingPid();
4279 }
4280
Makoto Onuki31459242016-03-22 11:12:18 -07004281 private int getCallingUserId() {
Makoto Onuki4554d0e2016-03-14 15:51:41 -07004282 return UserHandle.getUserId(injectBinderCallingUid());
4283 }
4284
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07004285 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07004286 @VisibleForTesting
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07004287 long injectClearCallingIdentity() {
4288 return Binder.clearCallingIdentity();
4289 }
4290
4291 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07004292 @VisibleForTesting
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07004293 void injectRestoreCallingIdentity(long token) {
4294 Binder.restoreCallingIdentity(token);
4295 }
4296
Makoto Onuki33663282016-08-22 16:19:04 -07004297 // Injection point.
Makoto Onuki33663282016-08-22 16:19:04 -07004298 String injectBuildFingerprint() {
4299 return Build.FINGERPRINT;
4300 }
4301
Makoto Onukide667372016-03-15 14:29:20 -07004302 final void wtf(String message) {
Makoto Onukib08790c2016-06-23 14:05:46 -07004303 wtf(message, /* exception= */ null);
Makoto Onukide667372016-03-15 14:29:20 -07004304 }
4305
Makoto Onuki2e210c42016-03-30 08:30:36 -07004306 // Injection point.
Makoto Onukia2241832016-07-06 13:28:37 -07004307 void wtf(String message, Throwable e) {
4308 if (e == null) {
4309 e = new RuntimeException("Stacktrace");
4310 }
4311 synchronized (mLock) {
4312 mWtfCount++;
4313 mLastWtfStacktrace = new Exception("Last failure was logged here:");
4314 }
Makoto Onukide667372016-03-15 14:29:20 -07004315 Slog.wtf(TAG, message, e);
4316 }
4317
Makoto Onuki31459242016-03-22 11:12:18 -07004318 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004319 File injectSystemDataPath() {
4320 return Environment.getDataSystemDirectory();
4321 }
4322
Makoto Onuki31459242016-03-22 11:12:18 -07004323 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004324 File injectUserDataPath(@UserIdInt int userId) {
Makoto Onuki55046222016-03-08 10:49:47 -08004325 return new File(Environment.getDataSystemCeDirectory(userId), DIRECTORY_PER_USER);
4326 }
4327
Makoto Onuki50a320e2017-05-31 14:38:42 -07004328 public File getDumpPath() {
4329 return new File(injectUserDataPath(UserHandle.USER_SYSTEM), DIRECTORY_DUMP);
4330 }
4331
Makoto Onuki4362a662016-03-08 18:59:09 -08004332 @VisibleForTesting
Makoto Onuki55046222016-03-08 10:49:47 -08004333 boolean injectIsLowRamDevice() {
4334 return ActivityManager.isLowRamDeviceStatic();
4335 }
4336
Makoto Onuki31459242016-03-22 11:12:18 -07004337 @VisibleForTesting
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07004338 void injectRegisterUidObserver(IUidObserver observer, int which) {
4339 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004340 ActivityManager.getService().registerUidObserver(observer, which,
Dianne Hackborn5614bf52016-11-07 17:26:41 -08004341 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07004342 } catch (RemoteException shouldntHappen) {
4343 }
4344 }
4345
Makoto Onuki55046222016-03-08 10:49:47 -08004346 File getUserBitmapFilePath(@UserIdInt int userId) {
4347 return new File(injectUserDataPath(userId), DIRECTORY_BITMAPS);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004348 }
4349
4350 @VisibleForTesting
Makoto Onuki31459242016-03-22 11:12:18 -07004351 SparseArray<ShortcutUser> getShortcutsForTest() {
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08004352 return mUsers;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004353 }
4354
4355 @VisibleForTesting
Makoto Onukib5a012f2016-06-21 11:13:53 -07004356 int getMaxShortcutsForTest() {
4357 return mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004358 }
4359
4360 @VisibleForTesting
Makoto Onukib6d35232016-04-04 15:57:17 -07004361 int getMaxUpdatesPerIntervalForTest() {
4362 return mMaxUpdatesPerInterval;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004363 }
4364
4365 @VisibleForTesting
Makoto Onuki4362a662016-03-08 18:59:09 -08004366 long getResetIntervalForTest() {
4367 return mResetInterval;
Makoto Onuki55046222016-03-08 10:49:47 -08004368 }
4369
4370 @VisibleForTesting
Makoto Onuki4362a662016-03-08 18:59:09 -08004371 int getMaxIconDimensionForTest() {
4372 return mMaxIconDimension;
4373 }
4374
4375 @VisibleForTesting
4376 CompressFormat getIconPersistFormatForTest() {
4377 return mIconPersistFormat;
4378 }
4379
4380 @VisibleForTesting
4381 int getIconPersistQualityForTest() {
4382 return mIconPersistQuality;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004383 }
Makoto Onuki41066a62016-03-09 16:18:44 -08004384
4385 @VisibleForTesting
Makoto Onuki22fcc682016-05-17 14:52:19 -07004386 ShortcutPackage getPackageShortcutForTest(String packageName, int userId) {
Makoto Onuki41066a62016-03-09 16:18:44 -08004387 synchronized (mLock) {
Makoto Onuki31459242016-03-22 11:12:18 -07004388 final ShortcutUser user = mUsers.get(userId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07004389 if (user == null) return null;
4390
Makoto Onuki22fcc682016-05-17 14:52:19 -07004391 return user.getAllPackagesForTest().get(packageName);
4392 }
4393 }
4394
4395 @VisibleForTesting
4396 ShortcutInfo getPackageShortcutForTest(String packageName, String shortcutId, int userId) {
4397 synchronized (mLock) {
Makoto Onukif34c3082016-07-13 10:25:25 -07004398 final ShortcutPackage pkg = getPackageShortcutForTest(packageName, userId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07004399 if (pkg == null) return null;
4400
4401 return pkg.findShortcutById(shortcutId);
Makoto Onuki41066a62016-03-09 16:18:44 -08004402 }
4403 }
Makoto Onuki7001a612016-05-27 13:24:28 -07004404
Makoto Onukifac592f2016-11-21 13:41:32 -08004405 @VisibleForTesting
4406 ShortcutLauncher getLauncherShortcutForTest(String packageName, int userId) {
4407 synchronized (mLock) {
4408 final ShortcutUser user = mUsers.get(userId);
4409 if (user == null) return null;
4410
4411 return user.getAllLaunchersForTest().get(PackageWithUser.of(userId, packageName));
4412 }
4413 }
4414
Makoto Onuki2d895c32016-12-02 15:48:40 -08004415 @VisibleForTesting
4416 ShortcutRequestPinProcessor getShortcutRequestPinProcessorForTest() {
4417 return mShortcutRequestPinProcessor;
4418 }
4419
Makoto Onuki7001a612016-05-27 13:24:28 -07004420 /**
4421 * Control whether {@link #verifyStates} should be performed. We always perform it during unit
4422 * tests.
4423 */
4424 @VisibleForTesting
4425 boolean injectShouldPerformVerification() {
4426 return DEBUG;
4427 }
4428
4429 /**
4430 * Check various internal states and throws if there's any inconsistency.
4431 * This is normally only enabled during unit tests.
4432 */
4433 final void verifyStates() {
4434 if (injectShouldPerformVerification()) {
4435 verifyStatesInner();
4436 }
4437 }
4438
Makoto Onukib08790c2016-06-23 14:05:46 -07004439 private final void verifyStatesForce() {
4440 verifyStatesInner();
4441 }
4442
Makoto Onuki7001a612016-05-27 13:24:28 -07004443 private void verifyStatesInner() {
Makoto Onuki10305202016-07-14 18:14:08 -07004444 synchronized (mLock) {
Makoto Onuki7001a612016-05-27 13:24:28 -07004445 forEachLoadedUserLocked(u -> u.forAllPackageItems(ShortcutPackageItem::verifyStates));
4446 }
4447 }
Makoto Onuki475c3652017-05-08 14:29:03 -07004448
4449 @VisibleForTesting
4450 void waitForBitmapSavesForTest() {
4451 synchronized (mLock) {
4452 mShortcutBitmapSaver.waitForAllSavesLocked();
4453 }
4454 }
Makoto Onuki41066a62016-03-09 16:18:44 -08004455}