blob: 599e5a573437ddfd1337a931fb69dbc94b2ecd7f [file] [log] [blame]
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package com.android.server.pm;
17
Makoto Onuki7d0fa812018-02-21 11:24:43 -080018import android.Manifest.permission;
Makoto Onuki7001a612016-05-27 13:24:28 -070019import android.annotation.IntDef;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080020import android.annotation.NonNull;
21import android.annotation.Nullable;
22import android.annotation.UserIdInt;
Makoto Onuki55046222016-03-08 10:49:47 -080023import android.app.ActivityManager;
Makoto Onuki33525d22016-08-03 15:45:24 -070024import android.app.ActivityManagerInternal;
Makoto Onuki0acbb142016-03-22 17:02:57 -070025import android.app.AppGlobals;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -070026import android.app.IUidObserver;
Makoto Onukiac042502016-05-20 16:39:42 -070027import android.app.usage.UsageStatsManagerInternal;
Sunny Goyal87a563e2017-01-01 19:42:45 -080028import android.appwidget.AppWidgetProviderInfo;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070029import android.content.BroadcastReceiver;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080030import android.content.ComponentName;
31import android.content.Context;
32import android.content.Intent;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070033import android.content.IntentFilter;
Makoto Onuki2d895c32016-12-02 15:48:40 -080034import android.content.IntentSender;
35import android.content.IntentSender.SendIntentException;
Makoto Onuki22fcc682016-05-17 14:52:19 -070036import android.content.pm.ActivityInfo;
Makoto Onuki0acbb142016-03-22 17:02:57 -070037import android.content.pm.ApplicationInfo;
38import android.content.pm.IPackageManager;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080039import android.content.pm.IShortcutService;
40import android.content.pm.LauncherApps;
41import android.content.pm.LauncherApps.ShortcutQuery;
Makoto Onuki0acbb142016-03-22 17:02:57 -070042import android.content.pm.PackageInfo;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080043import android.content.pm.PackageManager;
Makoto Onuki2d5b4652016-03-11 16:09:54 -080044import android.content.pm.PackageManagerInternal;
Todd Kennedy0eb97382017-10-03 16:57:22 -070045import android.content.pm.PackageManager.NameNotFoundException;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080046import android.content.pm.ParceledListSlice;
Makoto Onuki2d5b4652016-03-11 16:09:54 -080047import android.content.pm.ResolveInfo;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080048import android.content.pm.ShortcutInfo;
49import android.content.pm.ShortcutServiceInternal;
50import android.content.pm.ShortcutServiceInternal.ShortcutChangeListener;
Makoto Onuki157b1622016-06-02 16:13:10 -070051import android.content.res.Resources;
Makoto Onuki22fcc682016-05-17 14:52:19 -070052import android.content.res.XmlResourceParser;
Makoto Onuki55046222016-03-08 10:49:47 -080053import android.graphics.Bitmap;
54import android.graphics.Bitmap.CompressFormat;
Makoto Onuki55046222016-03-08 10:49:47 -080055import android.graphics.Canvas;
56import android.graphics.RectF;
Hyunyoung Song47037462017-05-08 16:51:43 -070057import android.graphics.drawable.AdaptiveIconDrawable;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080058import android.graphics.drawable.Icon;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070059import android.net.Uri;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080060import android.os.Binder;
Makoto Onuki33663282016-08-22 16:19:04 -070061import android.os.Build;
Sunny Goyal4ad6b572017-02-28 11:11:51 -080062import android.os.Bundle;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080063import android.os.Environment;
Makoto Onuki2e210c42016-03-30 08:30:36 -070064import android.os.FileUtils;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080065import android.os.Handler;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070066import android.os.LocaleList;
Makoto Onukiaa8b94a2016-03-17 13:14:05 -070067import android.os.Looper;
Makoto Onuki55046222016-03-08 10:49:47 -080068import android.os.ParcelFileDescriptor;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080069import android.os.PersistableBundle;
70import android.os.Process;
71import android.os.RemoteException;
72import android.os.ResultReceiver;
Makoto Onuki55046222016-03-08 10:49:47 -080073import android.os.SELinux;
Makoto Onukib08790c2016-06-23 14:05:46 -070074import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070075import android.os.ShellCallback;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080076import android.os.ShellCommand;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -070077import android.os.SystemClock;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080078import android.os.UserHandle;
Sunny Goyal145c8f82018-02-15 14:27:09 -080079import android.os.UserManagerInternal;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080080import android.text.TextUtils;
81import android.text.format.Time;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080082import android.util.ArraySet;
83import android.util.AtomicFile;
Makoto Onuki4362a662016-03-08 18:59:09 -080084import android.util.KeyValueListParser;
Makoto Onukiac042502016-05-20 16:39:42 -070085import android.util.Log;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080086import android.util.Slog;
87import android.util.SparseArray;
Makoto Onuki02f338e2016-07-29 09:40:40 -070088import android.util.SparseBooleanArray;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -070089import android.util.SparseIntArray;
90import android.util.SparseLongArray;
Makoto Onuki55046222016-03-08 10:49:47 -080091import android.util.TypedValue;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080092import android.util.Xml;
Makoto Onukib08790c2016-06-23 14:05:46 -070093import android.view.IWindowManager;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080094
95import com.android.internal.annotations.GuardedBy;
96import com.android.internal.annotations.VisibleForTesting;
97import com.android.internal.os.BackgroundThread;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060098import com.android.internal.util.DumpUtils;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080099import com.android.internal.util.FastXmlSerializer;
100import com.android.internal.util.Preconditions;
101import com.android.server.LocalServices;
Makoto Onuki49392d32018-04-11 13:51:02 -0700102import com.android.internal.util.StatLogger;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800103import com.android.server.SystemService;
Makoto Onukid99c6f02016-03-28 11:02:54 -0700104import com.android.server.pm.ShortcutUser.PackageWithUser;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800105
106import libcore.io.IoUtils;
107
Makoto Onuki76269922016-07-15 14:58:54 -0700108import org.json.JSONArray;
109import org.json.JSONException;
110import org.json.JSONObject;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800111import org.xmlpull.v1.XmlPullParser;
112import org.xmlpull.v1.XmlPullParserException;
113import org.xmlpull.v1.XmlSerializer;
114
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700115import java.io.BufferedInputStream;
116import java.io.BufferedOutputStream;
117import java.io.ByteArrayInputStream;
118import java.io.ByteArrayOutputStream;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800119import java.io.File;
120import java.io.FileDescriptor;
121import java.io.FileInputStream;
122import java.io.FileNotFoundException;
123import java.io.FileOutputStream;
124import java.io.IOException;
Makoto Onuki55046222016-03-08 10:49:47 -0800125import java.io.InputStream;
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700126import java.io.OutputStream;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800127import java.io.PrintWriter;
Makoto Onuki7001a612016-05-27 13:24:28 -0700128import java.lang.annotation.Retention;
129import java.lang.annotation.RetentionPolicy;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800130import java.net.URISyntaxException;
131import java.nio.charset.StandardCharsets;
132import java.util.ArrayList;
Makoto Onuki22fcc682016-05-17 14:52:19 -0700133import java.util.Collections;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800134import java.util.List;
Makoto Onukic51b2872016-05-04 15:24:50 -0700135import java.util.concurrent.atomic.AtomicBoolean;
Makoto Onuki2e210c42016-03-30 08:30:36 -0700136import java.util.function.Consumer;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800137import java.util.function.Predicate;
Makoto Onuki20b82212017-10-04 15:03:50 -0700138import java.util.regex.Pattern;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800139
140/**
141 * TODO:
Makoto Onuki22fcc682016-05-17 14:52:19 -0700142 * - getIconMaxWidth()/getIconMaxHeight() should use xdpi and ydpi.
Makoto Onukib5a012f2016-06-21 11:13:53 -0700143 * -> But TypedValue.applyDimension() doesn't differentiate x and y..?
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800144 *
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700145 * - Detect when already registered instances are passed to APIs again, which might break
Makoto Onukib08790c2016-06-23 14:05:46 -0700146 * internal bitmap handling.
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800147 */
148public class ShortcutService extends IShortcutService.Stub {
Makoto Onuki55046222016-03-08 10:49:47 -0800149 static final String TAG = "ShortcutService";
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800150
Makoto Onuki7001a612016-05-27 13:24:28 -0700151 static final boolean DEBUG = false; // STOPSHIP if true
Makoto Onuki41066a62016-03-09 16:18:44 -0800152 static final boolean DEBUG_LOAD = false; // STOPSHIP if true
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700153 static final boolean DEBUG_PROCSTATE = false; // STOPSHIP if true
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800154
Makoto Onuki4362a662016-03-08 18:59:09 -0800155 @VisibleForTesting
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700156 static final long DEFAULT_RESET_INTERVAL_SEC = 24 * 60 * 60; // 1 day
Makoto Onuki4362a662016-03-08 18:59:09 -0800157
158 @VisibleForTesting
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700159 static final int DEFAULT_MAX_UPDATES_PER_INTERVAL = 10;
Makoto Onuki4362a662016-03-08 18:59:09 -0800160
161 @VisibleForTesting
162 static final int DEFAULT_MAX_SHORTCUTS_PER_APP = 5;
163
164 @VisibleForTesting
165 static final int DEFAULT_MAX_ICON_DIMENSION_DP = 96;
166
167 @VisibleForTesting
168 static final int DEFAULT_MAX_ICON_DIMENSION_LOWRAM_DP = 48;
169
170 @VisibleForTesting
171 static final String DEFAULT_ICON_PERSIST_FORMAT = CompressFormat.PNG.name();
172
173 @VisibleForTesting
174 static final int DEFAULT_ICON_PERSIST_QUALITY = 100;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800175
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700176 @VisibleForTesting
177 static final int DEFAULT_SAVE_DELAY_MS = 3000;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800178
179 @VisibleForTesting
180 static final String FILENAME_BASE_STATE = "shortcut_service.xml";
181
182 @VisibleForTesting
183 static final String DIRECTORY_PER_USER = "shortcut_service";
184
185 @VisibleForTesting
Makoto Onuki50a320e2017-05-31 14:38:42 -0700186 static final String DIRECTORY_DUMP = "shortcut_dump";
187
188 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800189 static final String FILENAME_USER_PACKAGES = "shortcuts.xml";
190
Makoto Onuki55046222016-03-08 10:49:47 -0800191 static final String DIRECTORY_BITMAPS = "bitmaps";
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800192
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700193 private static final String TAG_ROOT = "root";
194 private static final String TAG_LAST_RESET_TIME = "last_reset_time";
Makoto Onuki55046222016-03-08 10:49:47 -0800195
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700196 private static final String ATTR_VALUE = "value";
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800197
Makoto Onukib08790c2016-06-23 14:05:46 -0700198 private static final String LAUNCHER_INTENT_CATEGORY = Intent.CATEGORY_LAUNCHER;
199
Makoto Onuki76269922016-07-15 14:58:54 -0700200 private static final String KEY_SHORTCUT = "shortcut";
201 private static final String KEY_LOW_RAM = "lowRam";
202 private static final String KEY_ICON_SIZE = "iconSize";
203
Makoto Onuki2d895c32016-12-02 15:48:40 -0800204 private static final String DUMMY_MAIN_ACTIVITY = "android.__dummy__";
205
Makoto Onuki4362a662016-03-08 18:59:09 -0800206 @VisibleForTesting
207 interface ConfigConstants {
208 /**
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700209 * Key name for the save delay, in milliseconds. (int)
210 */
211 String KEY_SAVE_DELAY_MILLIS = "save_delay_ms";
212
213 /**
Makoto Onuki4362a662016-03-08 18:59:09 -0800214 * Key name for the throttling reset interval, in seconds. (long)
215 */
216 String KEY_RESET_INTERVAL_SEC = "reset_interval_sec";
217
218 /**
219 * Key name for the max number of modifying API calls per app for every interval. (int)
220 */
Makoto Onukib6d35232016-04-04 15:57:17 -0700221 String KEY_MAX_UPDATES_PER_INTERVAL = "max_updates_per_interval";
Makoto Onuki4362a662016-03-08 18:59:09 -0800222
223 /**
224 * Key name for the max icon dimensions in DP, for non-low-memory devices.
225 */
226 String KEY_MAX_ICON_DIMENSION_DP = "max_icon_dimension_dp";
227
228 /**
229 * Key name for the max icon dimensions in DP, for low-memory devices.
230 */
231 String KEY_MAX_ICON_DIMENSION_DP_LOWRAM = "max_icon_dimension_dp_lowram";
232
233 /**
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700234 * Key name for the max dynamic shortcuts per activity. (int)
Makoto Onuki4362a662016-03-08 18:59:09 -0800235 */
236 String KEY_MAX_SHORTCUTS = "max_shortcuts";
237
238 /**
Makoto Onuki41066a62016-03-09 16:18:44 -0800239 * Key name for icon compression quality, 0-100.
Makoto Onuki4362a662016-03-08 18:59:09 -0800240 */
241 String KEY_ICON_QUALITY = "icon_quality";
242
243 /**
244 * Key name for icon compression format: "PNG", "JPEG" or "WEBP"
245 */
246 String KEY_ICON_FORMAT = "icon_format";
247 }
248
Makoto Onuki41066a62016-03-09 16:18:44 -0800249 final Context mContext;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800250
251 private final Object mLock = new Object();
252
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700253 private static List<ResolveInfo> EMPTY_RESOLVE_INFO = new ArrayList<>(0);
254
Mark Renoufe065f7c2016-11-01 11:48:24 -0400255 // Temporarily reverted to anonymous inner class form due to: b/32554459
256 private static Predicate<ResolveInfo> ACTIVITY_NOT_EXPORTED = new Predicate<ResolveInfo>() {
257 public boolean test(ResolveInfo ri) {
258 return !ri.activityInfo.exported;
259 }
260 };
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700261
Mark Renoufe065f7c2016-11-01 11:48:24 -0400262 // Temporarily reverted to anonymous inner class form due to: b/32554459
263 private static Predicate<PackageInfo> PACKAGE_NOT_INSTALLED = new Predicate<PackageInfo>() {
264 public boolean test(PackageInfo pi) {
265 return !isInstalled(pi);
266 }
267 };
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700268
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800269 private final Handler mHandler;
270
271 @GuardedBy("mLock")
272 private final ArrayList<ShortcutChangeListener> mListeners = new ArrayList<>(1);
273
274 @GuardedBy("mLock")
275 private long mRawLastResetTime;
276
277 /**
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -0800278 * User ID -> UserShortcuts
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800279 */
280 @GuardedBy("mLock")
Makoto Onuki31459242016-03-22 11:12:18 -0700281 private final SparseArray<ShortcutUser> mUsers = new SparseArray<>();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800282
283 /**
Makoto Onuki708703b2017-12-11 16:38:11 -0800284 * User ID -> ShortcutNonPersistentUser
285 */
286 @GuardedBy("mLock")
287 private final SparseArray<ShortcutNonPersistentUser> mShortcutNonPersistentUsers =
288 new SparseArray<>();
289
290 /**
Makoto Onukib5a012f2016-06-21 11:13:53 -0700291 * Max number of dynamic + manifest shortcuts that each application can have at a time.
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800292 */
Makoto Onukib5a012f2016-06-21 11:13:53 -0700293 private int mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800294
295 /**
Makoto Onukib6d35232016-04-04 15:57:17 -0700296 * Max number of updating API calls that each application can make during the interval.
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800297 */
Makoto Onukib6d35232016-04-04 15:57:17 -0700298 int mMaxUpdatesPerInterval;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800299
300 /**
301 * Actual throttling-reset interval. By default it's a day.
302 */
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800303 private long mResetInterval;
304
Makoto Onuki55046222016-03-08 10:49:47 -0800305 /**
306 * Icon max width/height in pixels.
307 */
308 private int mMaxIconDimension;
309
Makoto Onuki4362a662016-03-08 18:59:09 -0800310 private CompressFormat mIconPersistFormat;
311 private int mIconPersistQuality;
Makoto Onuki55046222016-03-08 10:49:47 -0800312
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700313 private int mSaveDelayMillis;
314
Makoto Onuki0acbb142016-03-22 17:02:57 -0700315 private final IPackageManager mIPackageManager;
Makoto Onuki2d5b4652016-03-11 16:09:54 -0800316 private final PackageManagerInternal mPackageManagerInternal;
Sunny Goyal145c8f82018-02-15 14:27:09 -0800317 private final UserManagerInternal mUserManagerInternal;
Makoto Onukiac042502016-05-20 16:39:42 -0700318 private final UsageStatsManagerInternal mUsageStatsManagerInternal;
Makoto Onuki33525d22016-08-03 15:45:24 -0700319 private final ActivityManagerInternal mActivityManagerInternal;
Makoto Onuki2d5b4652016-03-11 16:09:54 -0800320
Makoto Onuki2d895c32016-12-02 15:48:40 -0800321 private final ShortcutRequestPinProcessor mShortcutRequestPinProcessor;
Makoto Onuki475c3652017-05-08 14:29:03 -0700322 private final ShortcutBitmapSaver mShortcutBitmapSaver;
Makoto Onuki50a320e2017-05-31 14:38:42 -0700323 private final ShortcutDumpFiles mShortcutDumpFiles;
Makoto Onuki2d895c32016-12-02 15:48:40 -0800324
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700325 @GuardedBy("mLock")
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700326 final SparseIntArray mUidState = new SparseIntArray();
327
328 @GuardedBy("mLock")
329 final SparseLongArray mUidLastForegroundElapsedTime = new SparseLongArray();
330
331 @GuardedBy("mLock")
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700332 private List<Integer> mDirtyUserIds = new ArrayList<>();
333
Makoto Onukic51b2872016-05-04 15:24:50 -0700334 private final AtomicBoolean mBootCompleted = new AtomicBoolean();
335
Makoto Onuki905e8852016-03-28 10:40:58 -0700336 private static final int PACKAGE_MATCH_FLAGS =
337 PackageManager.MATCH_DIRECT_BOOT_AWARE
Makoto Onukib08790c2016-06-23 14:05:46 -0700338 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE
339 | PackageManager.MATCH_UNINSTALLED_PACKAGES;
Makoto Onuki905e8852016-03-28 10:40:58 -0700340
Makoto Onukie63b04a2017-12-11 14:47:19 -0800341 /**
342 * Note we use a fine-grained lock for {@link #mUnlockedUsers} due to b/64303666.
343 */
344 @GuardedBy("mUnlockedUsers")
Makoto Onuki02f338e2016-07-29 09:40:40 -0700345 final SparseBooleanArray mUnlockedUsers = new SparseBooleanArray();
346
Makoto Onuki2e210c42016-03-30 08:30:36 -0700347 // Stats
348 @VisibleForTesting
349 interface Stats {
350 int GET_DEFAULT_HOME = 0;
351 int GET_PACKAGE_INFO = 1;
352 int GET_PACKAGE_INFO_WITH_SIG = 2;
353 int GET_APPLICATION_INFO = 3;
354 int LAUNCHER_PERMISSION_CHECK = 4;
Makoto Onuki6c1dbd52016-05-02 15:19:32 -0700355 int CLEANUP_DANGLING_BITMAPS = 5;
Makoto Onukib08790c2016-06-23 14:05:46 -0700356 int GET_ACTIVITY_WITH_METADATA = 6;
Makoto Onuki6dd9fb72016-06-01 13:55:54 -0700357 int GET_INSTALLED_PACKAGES = 7;
Makoto Onuki22fcc682016-05-17 14:52:19 -0700358 int CHECK_PACKAGE_CHANGES = 8;
Makoto Onuki157b1622016-06-02 16:13:10 -0700359 int GET_APPLICATION_RESOURCES = 9;
360 int RESOURCE_NAME_LOOKUP = 10;
Makoto Onukib08790c2016-06-23 14:05:46 -0700361 int GET_LAUNCHER_ACTIVITY = 11;
362 int CHECK_LAUNCHER_ACTIVITY = 12;
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700363 int IS_ACTIVITY_ENABLED = 13;
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700364 int PACKAGE_UPDATE_CHECK = 14;
Makoto Onuki085a05c2016-08-19 11:39:29 -0700365 int ASYNC_PRELOAD_USER_DELAY = 15;
Makoto Onuki2d895c32016-12-02 15:48:40 -0800366 int GET_DEFAULT_LAUNCHER = 16;
Makoto Onuki2e210c42016-03-30 08:30:36 -0700367
Makoto Onuki2d895c32016-12-02 15:48:40 -0800368 int COUNT = GET_DEFAULT_LAUNCHER + 1;
Makoto Onuki2e210c42016-03-30 08:30:36 -0700369 }
370
Makoto Onuki84d59342018-02-02 09:22:38 -0800371 private final StatLogger mStatLogger = new StatLogger(new String[] {
Makoto Onuki085a05c2016-08-19 11:39:29 -0700372 "getHomeActivities()",
373 "Launcher permission check",
374 "getPackageInfo()",
375 "getPackageInfo(SIG)",
376 "getApplicationInfo",
377 "cleanupDanglingBitmaps",
378 "getActivity+metadata",
379 "getInstalledPackages",
380 "checkPackageChanges",
381 "getApplicationResources",
382 "resourceNameLookup",
383 "getLauncherActivity",
384 "checkLauncherActivity",
385 "isActivityEnabled",
386 "packageUpdateCheck",
Makoto Onuki2d895c32016-12-02 15:48:40 -0800387 "asyncPreloadUserDelay",
388 "getDefaultLauncher()"
Makoto Onuki84d59342018-02-02 09:22:38 -0800389 });
Makoto Onuki2e210c42016-03-30 08:30:36 -0700390
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700391 private static final int PROCESS_STATE_FOREGROUND_THRESHOLD =
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -0800392 ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700393
Makoto Onuki7001a612016-05-27 13:24:28 -0700394 static final int OPERATION_SET = 0;
395 static final int OPERATION_ADD = 1;
396 static final int OPERATION_UPDATE = 2;
397
398 /** @hide */
399 @IntDef(value = {
400 OPERATION_SET,
401 OPERATION_ADD,
402 OPERATION_UPDATE
Makoto Onukib08790c2016-06-23 14:05:46 -0700403 })
Makoto Onuki7001a612016-05-27 13:24:28 -0700404 @Retention(RetentionPolicy.SOURCE)
Makoto Onukib08790c2016-06-23 14:05:46 -0700405 @interface ShortcutOperation {
406 }
Makoto Onuki7001a612016-05-27 13:24:28 -0700407
Makoto Onukia2241832016-07-06 13:28:37 -0700408 @GuardedBy("mLock")
409 private int mWtfCount = 0;
410
411 @GuardedBy("mLock")
412 private Exception mLastWtfStacktrace;
413
Makoto Onukifc4cf2d2016-08-24 11:10:26 -0700414 static class InvalidFileFormatException extends Exception {
415 public InvalidFileFormatException(String message, Throwable cause) {
416 super(message, cause);
417 }
418 }
419
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800420 public ShortcutService(Context context) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700421 this(context, BackgroundThread.get().getLooper(), /*onyForPackgeManagerApis*/ false);
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700422 }
423
424 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700425 ShortcutService(Context context, Looper looper, boolean onlyForPackageManagerApis) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800426 mContext = Preconditions.checkNotNull(context);
427 LocalServices.addService(ShortcutServiceInternal.class, new LocalService());
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700428 mHandler = new Handler(looper);
Makoto Onuki0acbb142016-03-22 17:02:57 -0700429 mIPackageManager = AppGlobals.getPackageManager();
Makoto Onukiac042502016-05-20 16:39:42 -0700430 mPackageManagerInternal = Preconditions.checkNotNull(
431 LocalServices.getService(PackageManagerInternal.class));
Sunny Goyal145c8f82018-02-15 14:27:09 -0800432 mUserManagerInternal = Preconditions.checkNotNull(
433 LocalServices.getService(UserManagerInternal.class));
Makoto Onukiac042502016-05-20 16:39:42 -0700434 mUsageStatsManagerInternal = Preconditions.checkNotNull(
435 LocalServices.getService(UsageStatsManagerInternal.class));
Makoto Onuki33525d22016-08-03 15:45:24 -0700436 mActivityManagerInternal = Preconditions.checkNotNull(
437 LocalServices.getService(ActivityManagerInternal.class));
Makoto Onukicdc78f72016-03-21 15:47:52 -0700438
Makoto Onuki2d895c32016-12-02 15:48:40 -0800439 mShortcutRequestPinProcessor = new ShortcutRequestPinProcessor(this, mLock);
Makoto Onuki475c3652017-05-08 14:29:03 -0700440 mShortcutBitmapSaver = new ShortcutBitmapSaver(this);
Makoto Onuki50a320e2017-05-31 14:38:42 -0700441 mShortcutDumpFiles = new ShortcutDumpFiles(this);
Makoto Onuki2d895c32016-12-02 15:48:40 -0800442
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700443 if (onlyForPackageManagerApis) {
444 return; // Don't do anything further. For unit tests only.
445 }
446
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700447 // Register receivers.
448
449 // We need to set a priority, so let's just not use PackageMonitor for now.
450 // TODO Refactor PackageMonitor to support priorities.
451 final IntentFilter packageFilter = new IntentFilter();
452 packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
453 packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
454 packageFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
455 packageFilter.addAction(Intent.ACTION_PACKAGE_DATA_CLEARED);
456 packageFilter.addDataScheme("package");
457 packageFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
458 mContext.registerReceiverAsUser(mPackageMonitor, UserHandle.ALL,
459 packageFilter, null, mHandler);
460
Makoto Onuki10305202016-07-14 18:14:08 -0700461 final IntentFilter preferedActivityFilter = new IntentFilter();
462 preferedActivityFilter.addAction(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
463 preferedActivityFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
464 mContext.registerReceiverAsUser(mPackageMonitor, UserHandle.ALL,
465 preferedActivityFilter, null, mHandler);
466
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700467 final IntentFilter localeFilter = new IntentFilter();
468 localeFilter.addAction(Intent.ACTION_LOCALE_CHANGED);
469 localeFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
470 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL,
471 localeFilter, null, mHandler);
Makoto Onukif34c3082016-07-13 10:25:25 -0700472
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700473 injectRegisterUidObserver(mUidObserver, ActivityManager.UID_OBSERVER_PROCSTATE
474 | ActivityManager.UID_OBSERVER_GONE);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800475 }
476
Makoto Onuki84d59342018-02-02 09:22:38 -0800477 long getStatStartTime() {
478 return mStatLogger.getTime();
479 }
480
Makoto Onuki2e210c42016-03-30 08:30:36 -0700481 void logDurationStat(int statId, long start) {
Makoto Onuki84d59342018-02-02 09:22:38 -0800482 mStatLogger.logDurationStat(statId, start);
Makoto Onuki2e210c42016-03-30 08:30:36 -0700483 }
484
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700485 public String injectGetLocaleTagsForUser(@UserIdInt int userId) {
486 // TODO This should get the per-user locale. b/30123329 b/30119489
487 return LocaleList.getDefault().toLanguageTags();
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700488 }
489
490 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Makoto Onukib08790c2016-06-23 14:05:46 -0700491 @Override
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700492 public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onukidc3f6d12017-09-22 17:22:50 -0700493 injectPostToHandler(() -> handleOnUidStateChanged(uid, procState));
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700494 }
495
Makoto Onukib08790c2016-06-23 14:05:46 -0700496 @Override
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700497 public void onUidGone(int uid, boolean disabled) {
Makoto Onukidc3f6d12017-09-22 17:22:50 -0700498 injectPostToHandler(() ->
499 handleOnUidStateChanged(uid, ActivityManager.PROCESS_STATE_NONEXISTENT));
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700500 }
501
Makoto Onukib08790c2016-06-23 14:05:46 -0700502 @Override
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700503 public void onUidActive(int uid) {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700504 }
505
Makoto Onukib08790c2016-06-23 14:05:46 -0700506 @Override
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700507 public void onUidIdle(int uid, boolean disabled) {
508 }
509
510 @Override public void onUidCachedChanged(int uid, boolean cached) {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700511 }
512 };
513
514 void handleOnUidStateChanged(int uid, int procState) {
515 if (DEBUG_PROCSTATE) {
516 Slog.d(TAG, "onUidStateChanged: uid=" + uid + " state=" + procState);
517 }
518 synchronized (mLock) {
519 mUidState.put(uid, procState);
520
521 // We need to keep track of last time an app comes to foreground.
522 // See ShortcutPackage.getApiCallCount() for how it's used.
523 // It doesn't have to be persisted, but it needs to be the elapsed time.
524 if (isProcessStateForeground(procState)) {
525 mUidLastForegroundElapsedTime.put(uid, injectElapsedRealtime());
526 }
527 }
528 }
529
530 private boolean isProcessStateForeground(int processState) {
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800531 return processState <= PROCESS_STATE_FOREGROUND_THRESHOLD;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700532 }
533
Andreas Gampea36dc622018-02-05 17:19:22 -0800534 @GuardedBy("mLock")
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700535 boolean isUidForegroundLocked(int uid) {
536 if (uid == Process.SYSTEM_UID) {
537 // IUidObserver doesn't report the state of SYSTEM, but it always has bound services,
538 // so it's foreground anyway.
539 return true;
540 }
Makoto Onuki33525d22016-08-03 15:45:24 -0700541 // First, check with the local cache.
542 if (isProcessStateForeground(mUidState.get(uid, ActivityManager.MAX_PROCESS_STATE))) {
543 return true;
544 }
545 // If the cache says background, reach out to AM. Since it'll internally need to hold
546 // the AM lock, we use it as a last resort.
547 return isProcessStateForeground(mActivityManagerInternal.getUidProcessState(uid));
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700548 }
549
Andreas Gampea36dc622018-02-05 17:19:22 -0800550 @GuardedBy("mLock")
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700551 long getUidLastForegroundElapsedTimeLocked(int uid) {
552 return mUidLastForegroundElapsedTime.get(uid);
553 }
554
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800555 /**
556 * System service lifecycle.
557 */
558 public static final class Lifecycle extends SystemService {
559 final ShortcutService mService;
560
561 public Lifecycle(Context context) {
562 super(context);
Makoto Onukia4f89b12017-10-05 10:37:55 -0700563 if (DEBUG) {
564 Binder.LOG_RUNTIME_EXCEPTION = true;
565 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800566 mService = new ShortcutService(context);
567 }
568
569 @Override
570 public void onStart() {
571 publishBinderService(Context.SHORTCUT_SERVICE, mService);
572 }
573
574 @Override
575 public void onBootPhase(int phase) {
576 mService.onBootPhase(phase);
577 }
578
579 @Override
Makoto Onuki01ce92b2017-04-28 12:24:16 -0700580 public void onStopUser(int userHandle) {
581 mService.handleStopUser(userHandle);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800582 }
583
584 @Override
Makoto Onukif3a572b2016-03-10 12:28:38 -0800585 public void onUnlockUser(int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -0700586 mService.handleUnlockUser(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800587 }
588 }
589
590 /** lifecycle event */
591 void onBootPhase(int phase) {
592 if (DEBUG) {
593 Slog.d(TAG, "onBootPhase: " + phase);
594 }
595 switch (phase) {
596 case SystemService.PHASE_LOCK_SETTINGS_READY:
597 initialize();
598 break;
Makoto Onukic51b2872016-05-04 15:24:50 -0700599 case SystemService.PHASE_BOOT_COMPLETED:
600 mBootCompleted.set(true);
601 break;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800602 }
603 }
604
605 /** lifecycle event */
Makoto Onukicdc78f72016-03-21 15:47:52 -0700606 void handleUnlockUser(int userId) {
Makoto Onuki22fcc682016-05-17 14:52:19 -0700607 if (DEBUG) {
Makoto Onuki085a05c2016-08-19 11:39:29 -0700608 Slog.d(TAG, "handleUnlockUser: user=" + userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700609 }
Makoto Onukie63b04a2017-12-11 14:47:19 -0800610 synchronized (mUnlockedUsers) {
Makoto Onuki02f338e2016-07-29 09:40:40 -0700611 mUnlockedUsers.put(userId, true);
Makoto Onukicdc78f72016-03-21 15:47:52 -0700612 }
Makoto Onuki085a05c2016-08-19 11:39:29 -0700613
614 // Preload the user data.
615 // Note, we don't use mHandler here but instead just start a new thread.
616 // This is because mHandler (which uses com.android.internal.os.BackgroundThread) is very
617 // busy at this point and this could take hundreds of milliseconds, which would be too
618 // late since the launcher would already have started.
619 // So we just create a new thread. This code runs rarely, so we don't use a thread pool
620 // or anything.
Makoto Onuki84d59342018-02-02 09:22:38 -0800621 final long start = getStatStartTime();
Makoto Onuki085a05c2016-08-19 11:39:29 -0700622 injectRunOnNewThread(() -> {
623 synchronized (mLock) {
624 logDurationStat(Stats.ASYNC_PRELOAD_USER_DELAY, start);
625 getUserShortcutsLocked(userId);
626 }
627 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800628 }
629
630 /** lifecycle event */
Makoto Onuki01ce92b2017-04-28 12:24:16 -0700631 void handleStopUser(int userId) {
Makoto Onuki02f338e2016-07-29 09:40:40 -0700632 if (DEBUG) {
Makoto Onuki01ce92b2017-04-28 12:24:16 -0700633 Slog.d(TAG, "handleStopUser: user=" + userId);
Makoto Onuki02f338e2016-07-29 09:40:40 -0700634 }
Makoto Onukicdc78f72016-03-21 15:47:52 -0700635 synchronized (mLock) {
636 unloadUserLocked(userId);
Makoto Onuki02f338e2016-07-29 09:40:40 -0700637
Makoto Onukie63b04a2017-12-11 14:47:19 -0800638 synchronized (mUnlockedUsers) {
639 mUnlockedUsers.put(userId, false);
640 }
Makoto Onukicdc78f72016-03-21 15:47:52 -0700641 }
642 }
643
Andreas Gampea36dc622018-02-05 17:19:22 -0800644 @GuardedBy("mLock")
Makoto Onukicdc78f72016-03-21 15:47:52 -0700645 private void unloadUserLocked(int userId) {
646 if (DEBUG) {
647 Slog.d(TAG, "unloadUserLocked: user=" + userId);
648 }
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700649 // Save all dirty information.
650 saveDirtyInfo();
651
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800652 // Unload
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -0800653 mUsers.delete(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800654 }
655
656 /** Return the base state file name */
657 private AtomicFile getBaseStateFile() {
658 final File path = new File(injectSystemDataPath(), FILENAME_BASE_STATE);
659 path.mkdirs();
660 return new AtomicFile(path);
661 }
662
663 /**
664 * Init the instance. (load the state file, etc)
665 */
666 private void initialize() {
667 synchronized (mLock) {
Makoto Onuki4362a662016-03-08 18:59:09 -0800668 loadConfigurationLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800669 loadBaseStateLocked();
670 }
671 }
672
Makoto Onuki4362a662016-03-08 18:59:09 -0800673 /**
674 * Load the configuration from Settings.
675 */
676 private void loadConfigurationLocked() {
677 updateConfigurationLocked(injectShortcutManagerConstants());
678 }
Makoto Onuki55046222016-03-08 10:49:47 -0800679
Makoto Onuki4362a662016-03-08 18:59:09 -0800680 /**
681 * Load the configuration from Settings.
682 */
683 @VisibleForTesting
684 boolean updateConfigurationLocked(String config) {
685 boolean result = true;
686
687 final KeyValueListParser parser = new KeyValueListParser(',');
688 try {
689 parser.setString(config);
690 } catch (IllegalArgumentException e) {
691 // Failed to parse the settings string, log this and move on
692 // with defaults.
693 Slog.e(TAG, "Bad shortcut manager settings", e);
694 result = false;
695 }
696
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700697 mSaveDelayMillis = Math.max(0, (int) parser.getLong(ConfigConstants.KEY_SAVE_DELAY_MILLIS,
698 DEFAULT_SAVE_DELAY_MS));
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700699
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700700 mResetInterval = Math.max(1, parser.getLong(
Makoto Onuki4362a662016-03-08 18:59:09 -0800701 ConfigConstants.KEY_RESET_INTERVAL_SEC, DEFAULT_RESET_INTERVAL_SEC)
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700702 * 1000L);
Makoto Onuki4362a662016-03-08 18:59:09 -0800703
Makoto Onukib6d35232016-04-04 15:57:17 -0700704 mMaxUpdatesPerInterval = Math.max(0, (int) parser.getLong(
705 ConfigConstants.KEY_MAX_UPDATES_PER_INTERVAL, DEFAULT_MAX_UPDATES_PER_INTERVAL));
Makoto Onuki4362a662016-03-08 18:59:09 -0800706
Makoto Onukib5a012f2016-06-21 11:13:53 -0700707 mMaxShortcuts = Math.max(0, (int) parser.getLong(
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700708 ConfigConstants.KEY_MAX_SHORTCUTS, DEFAULT_MAX_SHORTCUTS_PER_APP));
Makoto Onuki4362a662016-03-08 18:59:09 -0800709
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700710 final int iconDimensionDp = Math.max(1, injectIsLowRamDevice()
Makoto Onuki4362a662016-03-08 18:59:09 -0800711 ? (int) parser.getLong(
Makoto Onukib08790c2016-06-23 14:05:46 -0700712 ConfigConstants.KEY_MAX_ICON_DIMENSION_DP_LOWRAM,
713 DEFAULT_MAX_ICON_DIMENSION_LOWRAM_DP)
Makoto Onuki4362a662016-03-08 18:59:09 -0800714 : (int) parser.getLong(
Makoto Onukib08790c2016-06-23 14:05:46 -0700715 ConfigConstants.KEY_MAX_ICON_DIMENSION_DP,
716 DEFAULT_MAX_ICON_DIMENSION_DP));
Makoto Onuki4362a662016-03-08 18:59:09 -0800717
718 mMaxIconDimension = injectDipToPixel(iconDimensionDp);
719
720 mIconPersistFormat = CompressFormat.valueOf(
721 parser.getString(ConfigConstants.KEY_ICON_FORMAT, DEFAULT_ICON_PERSIST_FORMAT));
722
723 mIconPersistQuality = (int) parser.getLong(
724 ConfigConstants.KEY_ICON_QUALITY,
725 DEFAULT_ICON_PERSIST_QUALITY);
726
727 return result;
728 }
729
730 @VisibleForTesting
731 String injectShortcutManagerConstants() {
732 return android.provider.Settings.Global.getString(
733 mContext.getContentResolver(),
734 android.provider.Settings.Global.SHORTCUT_MANAGER_CONSTANTS);
735 }
736
737 @VisibleForTesting
738 int injectDipToPixel(int dip) {
739 return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip,
740 mContext.getResources().getDisplayMetrics());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800741 }
742
Makoto Onuki55046222016-03-08 10:49:47 -0800743 // === Persisting ===
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800744
745 @Nullable
Makoto Onuki41066a62016-03-09 16:18:44 -0800746 static String parseStringAttribute(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800747 return parser.getAttributeValue(null, attribute);
748 }
749
Makoto Onuki0acbb142016-03-22 17:02:57 -0700750 static boolean parseBooleanAttribute(XmlPullParser parser, String attribute) {
751 return parseLongAttribute(parser, attribute) == 1;
752 }
753
Makoto Onukia4f89b12017-10-05 10:37:55 -0700754 static boolean parseBooleanAttribute(XmlPullParser parser, String attribute, boolean def) {
755 return parseLongAttribute(parser, attribute, (def ? 1 : 0)) == 1;
756 }
757
Makoto Onuki41066a62016-03-09 16:18:44 -0800758 static int parseIntAttribute(XmlPullParser parser, String attribute) {
759 return (int) parseLongAttribute(parser, attribute);
760 }
761
Makoto Onukid99c6f02016-03-28 11:02:54 -0700762 static int parseIntAttribute(XmlPullParser parser, String attribute, int def) {
763 return (int) parseLongAttribute(parser, attribute, def);
764 }
765
Makoto Onuki41066a62016-03-09 16:18:44 -0800766 static long parseLongAttribute(XmlPullParser parser, String attribute) {
Makoto Onukid99c6f02016-03-28 11:02:54 -0700767 return parseLongAttribute(parser, attribute, 0);
768 }
769
770 static long parseLongAttribute(XmlPullParser parser, String attribute, long def) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800771 final String value = parseStringAttribute(parser, attribute);
772 if (TextUtils.isEmpty(value)) {
Makoto Onukid99c6f02016-03-28 11:02:54 -0700773 return def;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800774 }
775 try {
776 return Long.parseLong(value);
777 } catch (NumberFormatException e) {
778 Slog.e(TAG, "Error parsing long " + value);
Makoto Onukid99c6f02016-03-28 11:02:54 -0700779 return def;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800780 }
781 }
782
783 @Nullable
Makoto Onuki41066a62016-03-09 16:18:44 -0800784 static ComponentName parseComponentNameAttribute(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800785 final String value = parseStringAttribute(parser, attribute);
786 if (TextUtils.isEmpty(value)) {
787 return null;
788 }
789 return ComponentName.unflattenFromString(value);
790 }
791
792 @Nullable
Makoto Onuki440a1ea2016-07-20 14:21:18 -0700793 static Intent parseIntentAttributeNoDefault(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800794 final String value = parseStringAttribute(parser, attribute);
Makoto Onukib5a012f2016-06-21 11:13:53 -0700795 Intent parsed = null;
796 if (!TextUtils.isEmpty(value)) {
797 try {
798 parsed = Intent.parseUri(value, /* flags =*/ 0);
799 } catch (URISyntaxException e) {
800 Slog.e(TAG, "Error parsing intent", e);
801 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800802 }
Makoto Onuki440a1ea2016-07-20 14:21:18 -0700803 return parsed;
804 }
805
806 @Nullable
807 static Intent parseIntentAttribute(XmlPullParser parser, String attribute) {
808 Intent parsed = parseIntentAttributeNoDefault(parser, attribute);
Makoto Onukib5a012f2016-06-21 11:13:53 -0700809 if (parsed == null) {
810 // Default intent.
811 parsed = new Intent(Intent.ACTION_VIEW);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800812 }
Makoto Onukib5a012f2016-06-21 11:13:53 -0700813 return parsed;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800814 }
815
Makoto Onuki41066a62016-03-09 16:18:44 -0800816 static void writeTagValue(XmlSerializer out, String tag, String value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800817 if (TextUtils.isEmpty(value)) return;
818
819 out.startTag(null, tag);
820 out.attribute(null, ATTR_VALUE, value);
821 out.endTag(null, tag);
822 }
823
Makoto Onuki41066a62016-03-09 16:18:44 -0800824 static void writeTagValue(XmlSerializer out, String tag, long value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800825 writeTagValue(out, tag, Long.toString(value));
826 }
827
Makoto Onuki2d5b4652016-03-11 16:09:54 -0800828 static void writeTagValue(XmlSerializer out, String tag, ComponentName name) throws IOException {
829 if (name == null) return;
830 writeTagValue(out, tag, name.flattenToString());
831 }
832
Makoto Onuki41066a62016-03-09 16:18:44 -0800833 static void writeTagExtra(XmlSerializer out, String tag, PersistableBundle bundle)
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800834 throws IOException, XmlPullParserException {
835 if (bundle == null) return;
836
837 out.startTag(null, tag);
838 bundle.saveToXml(out);
839 out.endTag(null, tag);
840 }
841
Makoto Onuki22fcc682016-05-17 14:52:19 -0700842 static void writeAttr(XmlSerializer out, String name, CharSequence value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800843 if (TextUtils.isEmpty(value)) return;
844
Makoto Onuki22fcc682016-05-17 14:52:19 -0700845 out.attribute(null, name, value.toString());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800846 }
847
Makoto Onuki41066a62016-03-09 16:18:44 -0800848 static void writeAttr(XmlSerializer out, String name, long value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800849 writeAttr(out, name, String.valueOf(value));
850 }
851
Makoto Onuki0acbb142016-03-22 17:02:57 -0700852 static void writeAttr(XmlSerializer out, String name, boolean value) throws IOException {
853 if (value) {
854 writeAttr(out, name, "1");
Makoto Onukia4f89b12017-10-05 10:37:55 -0700855 } else {
856 writeAttr(out, name, "0");
Makoto Onuki0acbb142016-03-22 17:02:57 -0700857 }
858 }
859
Makoto Onuki41066a62016-03-09 16:18:44 -0800860 static void writeAttr(XmlSerializer out, String name, ComponentName comp) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800861 if (comp == null) return;
862 writeAttr(out, name, comp.flattenToString());
863 }
864
Makoto Onuki41066a62016-03-09 16:18:44 -0800865 static void writeAttr(XmlSerializer out, String name, Intent intent) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800866 if (intent == null) return;
867
868 writeAttr(out, name, intent.toUri(/* flags =*/ 0));
869 }
870
Andreas Gampea36dc622018-02-05 17:19:22 -0800871 @GuardedBy("mLock")
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800872 @VisibleForTesting
873 void saveBaseStateLocked() {
874 final AtomicFile file = getBaseStateFile();
875 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700876 Slog.d(TAG, "Saving to " + file.getBaseFile());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800877 }
878
879 FileOutputStream outs = null;
880 try {
881 outs = file.startWrite();
882
883 // Write to XML
884 XmlSerializer out = new FastXmlSerializer();
885 out.setOutput(outs, StandardCharsets.UTF_8.name());
886 out.startDocument(null, true);
887 out.startTag(null, TAG_ROOT);
888
889 // Body.
890 writeTagValue(out, TAG_LAST_RESET_TIME, mRawLastResetTime);
891
892 // Epilogue.
893 out.endTag(null, TAG_ROOT);
894 out.endDocument();
895
896 // Close.
897 file.finishWrite(outs);
898 } catch (IOException e) {
899 Slog.e(TAG, "Failed to write to file " + file.getBaseFile(), e);
900 file.failWrite(outs);
901 }
902 }
903
Andreas Gampea36dc622018-02-05 17:19:22 -0800904 @GuardedBy("mLock")
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800905 private void loadBaseStateLocked() {
906 mRawLastResetTime = 0;
907
908 final AtomicFile file = getBaseStateFile();
909 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700910 Slog.d(TAG, "Loading from " + file.getBaseFile());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800911 }
912 try (FileInputStream in = file.openRead()) {
913 XmlPullParser parser = Xml.newPullParser();
914 parser.setInput(in, StandardCharsets.UTF_8.name());
915
916 int type;
917 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
918 if (type != XmlPullParser.START_TAG) {
919 continue;
920 }
921 final int depth = parser.getDepth();
922 // Check the root tag
923 final String tag = parser.getName();
924 if (depth == 1) {
925 if (!TAG_ROOT.equals(tag)) {
926 Slog.e(TAG, "Invalid root tag: " + tag);
927 return;
928 }
929 continue;
930 }
931 // Assume depth == 2
932 switch (tag) {
933 case TAG_LAST_RESET_TIME:
934 mRawLastResetTime = parseLongAttribute(parser, ATTR_VALUE);
935 break;
936 default:
937 Slog.e(TAG, "Invalid tag: " + tag);
938 break;
939 }
940 }
941 } catch (FileNotFoundException e) {
942 // Use the default
Makoto Onukib08790c2016-06-23 14:05:46 -0700943 } catch (IOException | XmlPullParserException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800944 Slog.e(TAG, "Failed to read file " + file.getBaseFile(), e);
945
946 mRawLastResetTime = 0;
947 }
948 // Adjust the last reset time.
949 getLastResetTimeLocked();
950 }
951
Makoto Onuki0eed4412016-07-21 11:21:59 -0700952 @VisibleForTesting
953 final File getUserFile(@UserIdInt int userId) {
954 return new File(injectUserDataPath(userId), FILENAME_USER_PACKAGES);
955 }
956
Andreas Gampea36dc622018-02-05 17:19:22 -0800957 @GuardedBy("mLock")
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800958 private void saveUserLocked(@UserIdInt int userId) {
Makoto Onuki0eed4412016-07-21 11:21:59 -0700959 final File path = getUserFile(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800960 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700961 Slog.d(TAG, "Saving to " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800962 }
Makoto Onuki475c3652017-05-08 14:29:03 -0700963
964 mShortcutBitmapSaver.waitForAllSavesLocked();
965
Makoto Onuki0eed4412016-07-21 11:21:59 -0700966 path.getParentFile().mkdirs();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800967 final AtomicFile file = new AtomicFile(path);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700968 FileOutputStream os = null;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800969 try {
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700970 os = file.startWrite();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800971
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700972 saveUserInternalLocked(userId, os, /* forBackup= */ false);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800973
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700974 file.finishWrite(os);
Makoto Onuki1e173232016-08-10 10:47:13 -0700975
976 // Remove all dangling bitmap files.
977 cleanupDanglingBitmapDirectoriesLocked(userId);
Makoto Onukib08790c2016-06-23 14:05:46 -0700978 } catch (XmlPullParserException | IOException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800979 Slog.e(TAG, "Failed to write to file " + file.getBaseFile(), e);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700980 file.failWrite(os);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800981 }
982 }
983
Andreas Gampea36dc622018-02-05 17:19:22 -0800984 @GuardedBy("mLock")
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700985 private void saveUserInternalLocked(@UserIdInt int userId, OutputStream os,
986 boolean forBackup) throws IOException, XmlPullParserException {
987
988 final BufferedOutputStream bos = new BufferedOutputStream(os);
989
990 // Write to XML
991 XmlSerializer out = new FastXmlSerializer();
992 out.setOutput(bos, StandardCharsets.UTF_8.name());
993 out.startDocument(null, true);
994
Makoto Onukic51b2872016-05-04 15:24:50 -0700995 getUserShortcutsLocked(userId).saveToXml(out, forBackup);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700996
997 out.endDocument();
998
999 bos.flush();
1000 os.flush();
1001 }
1002
Makoto Onuki41066a62016-03-09 16:18:44 -08001003 static IOException throwForInvalidTag(int depth, String tag) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001004 throw new IOException(String.format("Invalid tag '%s' found at depth %d", tag, depth));
1005 }
1006
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001007 static void warnForInvalidTag(int depth, String tag) throws IOException {
1008 Slog.w(TAG, String.format("Invalid tag '%s' found at depth %d", tag, depth));
1009 }
1010
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001011 @Nullable
Makoto Onuki31459242016-03-22 11:12:18 -07001012 private ShortcutUser loadUserLocked(@UserIdInt int userId) {
Makoto Onuki0eed4412016-07-21 11:21:59 -07001013 final File path = getUserFile(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001014 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001015 Slog.d(TAG, "Loading from " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001016 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001017 final AtomicFile file = new AtomicFile(path);
1018
1019 final FileInputStream in;
1020 try {
1021 in = file.openRead();
1022 } catch (FileNotFoundException e) {
1023 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001024 Slog.d(TAG, "Not found " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001025 }
1026 return null;
1027 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001028 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07001029 final ShortcutUser ret = loadUserInternal(userId, in, /* forBackup= */ false);
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001030 return ret;
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07001031 } catch (IOException | XmlPullParserException | InvalidFileFormatException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001032 Slog.e(TAG, "Failed to read file " + file.getBaseFile(), e);
1033 return null;
1034 } finally {
1035 IoUtils.closeQuietly(in);
1036 }
1037 }
1038
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001039 private ShortcutUser loadUserInternal(@UserIdInt int userId, InputStream is,
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07001040 boolean fromBackup) throws XmlPullParserException, IOException,
1041 InvalidFileFormatException {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001042
1043 final BufferedInputStream bis = new BufferedInputStream(is);
1044
1045 ShortcutUser ret = null;
1046 XmlPullParser parser = Xml.newPullParser();
1047 parser.setInput(bis, StandardCharsets.UTF_8.name());
1048
1049 int type;
1050 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1051 if (type != XmlPullParser.START_TAG) {
1052 continue;
1053 }
1054 final int depth = parser.getDepth();
1055
1056 final String tag = parser.getName();
1057 if (DEBUG_LOAD) {
1058 Slog.d(TAG, String.format("depth=%d type=%d name=%s",
1059 depth, type, tag));
1060 }
1061 if ((depth == 1) && ShortcutUser.TAG_ROOT.equals(tag)) {
1062 ret = ShortcutUser.loadFromXml(this, parser, userId, fromBackup);
1063 continue;
1064 }
1065 throwForInvalidTag(depth, tag);
1066 }
1067 return ret;
1068 }
1069
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001070 private void scheduleSaveBaseState() {
Makoto Onuki0acbb142016-03-22 17:02:57 -07001071 scheduleSaveInner(UserHandle.USER_NULL); // Special case -- use USER_NULL for base state.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001072 }
1073
Makoto Onuki2d5b4652016-03-11 16:09:54 -08001074 void scheduleSaveUser(@UserIdInt int userId) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07001075 scheduleSaveInner(userId);
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001076 }
1077
1078 // In order to re-schedule, we need to reuse the same instance, so keep it in final.
1079 private final Runnable mSaveDirtyInfoRunner = this::saveDirtyInfo;
1080
Makoto Onuki0acbb142016-03-22 17:02:57 -07001081 private void scheduleSaveInner(@UserIdInt int userId) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001082 if (DEBUG) {
1083 Slog.d(TAG, "Scheduling to save for " + userId);
1084 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001085 synchronized (mLock) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001086 if (!mDirtyUserIds.contains(userId)) {
1087 mDirtyUserIds.add(userId);
1088 }
1089 }
1090 // If already scheduled, remove that and re-schedule in N seconds.
1091 mHandler.removeCallbacks(mSaveDirtyInfoRunner);
1092 mHandler.postDelayed(mSaveDirtyInfoRunner, mSaveDelayMillis);
1093 }
1094
1095 @VisibleForTesting
1096 void saveDirtyInfo() {
1097 if (DEBUG) {
1098 Slog.d(TAG, "saveDirtyInfo");
1099 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001100 try {
1101 synchronized (mLock) {
1102 for (int i = mDirtyUserIds.size() - 1; i >= 0; i--) {
1103 final int userId = mDirtyUserIds.get(i);
1104 if (userId == UserHandle.USER_NULL) { // USER_NULL for base state.
1105 saveBaseStateLocked();
1106 } else {
1107 saveUserLocked(userId);
1108 }
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001109 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001110 mDirtyUserIds.clear();
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001111 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001112 } catch (Exception e) {
1113 wtf("Exception in saveDirtyInfo", e);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001114 }
1115 }
1116
1117 /** Return the last reset time. */
Andreas Gampea36dc622018-02-05 17:19:22 -08001118 @GuardedBy("mLock")
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001119 long getLastResetTimeLocked() {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001120 updateTimesLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001121 return mRawLastResetTime;
1122 }
1123
1124 /** Return the next reset time. */
Andreas Gampea36dc622018-02-05 17:19:22 -08001125 @GuardedBy("mLock")
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001126 long getNextResetTimeLocked() {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001127 updateTimesLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001128 return mRawLastResetTime + mResetInterval;
1129 }
1130
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001131 static boolean isClockValid(long time) {
1132 return time >= 1420070400; // Thu, 01 Jan 2015 00:00:00 GMT
1133 }
1134
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001135 /**
1136 * Update the last reset time.
1137 */
Andreas Gampea36dc622018-02-05 17:19:22 -08001138 @GuardedBy("mLock")
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001139 private void updateTimesLocked() {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001140
1141 final long now = injectCurrentTimeMillis();
1142
1143 final long prevLastResetTime = mRawLastResetTime;
1144
1145 if (mRawLastResetTime == 0) { // first launch.
1146 // TODO Randomize??
1147 mRawLastResetTime = now;
1148 } else if (now < mRawLastResetTime) {
1149 // Clock rewound.
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001150 if (isClockValid(now)) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001151 Slog.w(TAG, "Clock rewound");
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001152 // TODO Randomize??
1153 mRawLastResetTime = now;
1154 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001155 } else {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001156 if ((mRawLastResetTime + mResetInterval) <= now) {
1157 final long offset = mRawLastResetTime % mResetInterval;
1158 mRawLastResetTime = ((now / mResetInterval) * mResetInterval) + offset;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001159 }
1160 }
1161 if (prevLastResetTime != mRawLastResetTime) {
1162 scheduleSaveBaseState();
1163 }
1164 }
1165
Makoto Onuki1e173232016-08-10 10:47:13 -07001166 // Requires mLock held, but "Locked" prefix would look weired so we just say "L".
Makoto Onuki02f338e2016-07-29 09:40:40 -07001167 protected boolean isUserUnlockedL(@UserIdInt int userId) {
Makoto Onuki1e173232016-08-10 10:47:13 -07001168 // First, check the local copy.
Makoto Onukie63b04a2017-12-11 14:47:19 -08001169 synchronized (mUnlockedUsers) {
1170 if (mUnlockedUsers.get(userId)) {
1171 return true;
1172 }
Makoto Onuki1e173232016-08-10 10:47:13 -07001173 }
Makoto Onukie63b04a2017-12-11 14:47:19 -08001174
Makoto Onuki1e173232016-08-10 10:47:13 -07001175 // If the local copy says the user is locked, check with AM for the actual state, since
1176 // the user might just have been unlocked.
1177 // Note we just don't use isUserUnlockingOrUnlocked() here, because it'll return false
1178 // when the user is STOPPING, which we still want to consider as "unlocked".
Sunny Goyal145c8f82018-02-15 14:27:09 -08001179 return mUserManagerInternal.isUserUnlockingOrUnlocked(userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07001180 }
1181
Makoto Onuki02f338e2016-07-29 09:40:40 -07001182 // Requires mLock held, but "Locked" prefix would look weired so we jsut say "L".
1183 void throwIfUserLockedL(@UserIdInt int userId) {
1184 if (!isUserUnlockedL(userId)) {
Makoto Onuki9c850012016-07-26 15:50:50 -07001185 throw new IllegalStateException("User " + userId + " is locked or not running");
1186 }
1187 }
1188
Makoto Onukicdc78f72016-03-21 15:47:52 -07001189 @GuardedBy("mLock")
1190 @NonNull
Makoto Onuki2e210c42016-03-30 08:30:36 -07001191 private boolean isUserLoadedLocked(@UserIdInt int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07001192 return mUsers.get(userId) != null;
1193 }
1194
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001195 /** Return the per-user state. */
1196 @GuardedBy("mLock")
1197 @NonNull
Makoto Onuki31459242016-03-22 11:12:18 -07001198 ShortcutUser getUserShortcutsLocked(@UserIdInt int userId) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001199 if (!isUserUnlockedL(userId)) {
Makoto Onuki9c850012016-07-26 15:50:50 -07001200 wtf("User still locked");
Makoto Onuki9c850012016-07-26 15:50:50 -07001201 }
1202
Makoto Onuki31459242016-03-22 11:12:18 -07001203 ShortcutUser userPackages = mUsers.get(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001204 if (userPackages == null) {
1205 userPackages = loadUserLocked(userId);
1206 if (userPackages == null) {
Makoto Onukic51b2872016-05-04 15:24:50 -07001207 userPackages = new ShortcutUser(this, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001208 }
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08001209 mUsers.put(userId, userPackages);
Makoto Onuki085a05c2016-08-19 11:39:29 -07001210
1211 // Also when a user's data is first accessed, scan all packages.
1212 checkPackageChanges(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001213 }
1214 return userPackages;
1215 }
1216
Makoto Onuki708703b2017-12-11 16:38:11 -08001217 /** Return the non-persistent per-user state. */
1218 @GuardedBy("mLock")
1219 @NonNull
1220 ShortcutNonPersistentUser getNonPersistentUserLocked(@UserIdInt int userId) {
1221 ShortcutNonPersistentUser ret = mShortcutNonPersistentUsers.get(userId);
1222 if (ret == null) {
1223 ret = new ShortcutNonPersistentUser(this, userId);
1224 mShortcutNonPersistentUsers.put(userId, ret);
1225 }
1226 return ret;
1227 }
1228
Andreas Gampea36dc622018-02-05 17:19:22 -08001229 @GuardedBy("mLock")
Makoto Onuki2e210c42016-03-30 08:30:36 -07001230 void forEachLoadedUserLocked(@NonNull Consumer<ShortcutUser> c) {
1231 for (int i = mUsers.size() - 1; i >= 0; i--) {
1232 c.accept(mUsers.valueAt(i));
1233 }
1234 }
1235
Makoto Onukic8c33292016-09-12 16:36:59 -07001236 /**
1237 * Return the per-user per-package state. If the caller is a publisher, use
1238 * {@link #getPackageShortcutsForPublisherLocked} instead.
1239 */
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001240 @GuardedBy("mLock")
1241 @NonNull
Makoto Onuki31459242016-03-22 11:12:18 -07001242 ShortcutPackage getPackageShortcutsLocked(
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001243 @NonNull String packageName, @UserIdInt int userId) {
Makoto Onukic51b2872016-05-04 15:24:50 -07001244 return getUserShortcutsLocked(userId).getPackageShortcuts(packageName);
Makoto Onukide667372016-03-15 14:29:20 -07001245 }
1246
Makoto Onukic8c33292016-09-12 16:36:59 -07001247 /** Return the per-user per-package state. Use this when the caller is a publisher. */
1248 @GuardedBy("mLock")
1249 @NonNull
1250 ShortcutPackage getPackageShortcutsForPublisherLocked(
1251 @NonNull String packageName, @UserIdInt int userId) {
1252 final ShortcutPackage ret = getUserShortcutsLocked(userId).getPackageShortcuts(packageName);
1253 ret.getUser().onCalledByPublisher(packageName);
1254 return ret;
1255 }
1256
Makoto Onukide667372016-03-15 14:29:20 -07001257 @GuardedBy("mLock")
1258 @NonNull
Makoto Onuki2e210c42016-03-30 08:30:36 -07001259 ShortcutLauncher getLauncherShortcutsLocked(
1260 @NonNull String packageName, @UserIdInt int ownerUserId,
1261 @UserIdInt int launcherUserId) {
1262 return getUserShortcutsLocked(ownerUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07001263 .getLauncherShortcuts(packageName, launcherUserId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001264 }
1265
1266 // === Caller validation ===
1267
Makoto Onuki475c3652017-05-08 14:29:03 -07001268 void removeIconLocked(ShortcutInfo shortcut) {
1269 mShortcutBitmapSaver.removeIcon(shortcut);
Makoto Onuki55046222016-03-08 10:49:47 -08001270 }
1271
Makoto Onuki0033b2a2016-04-14 17:19:16 -07001272 public void cleanupBitmapsForPackage(@UserIdInt int userId, String packageName) {
1273 final File packagePath = new File(getUserBitmapFilePath(userId), packageName);
1274 if (!packagePath.isDirectory()) {
1275 return;
1276 }
1277 if (!(FileUtils.deleteContents(packagePath) && packagePath.delete())) {
1278 Slog.w(TAG, "Unable to remove directory " + packagePath);
1279 }
1280 }
1281
Makoto Onuki475c3652017-05-08 14:29:03 -07001282 /**
1283 * Remove dangling bitmap files for a user.
1284 *
1285 * Note this method must be called with the lock held after calling
1286 * {@link ShortcutBitmapSaver#waitForAllSavesLocked()} to make sure there's no pending bitmap
1287 * saves are going on.
1288 */
Andreas Gampea36dc622018-02-05 17:19:22 -08001289 @GuardedBy("mLock")
Makoto Onuki1e173232016-08-10 10:47:13 -07001290 private void cleanupDanglingBitmapDirectoriesLocked(@UserIdInt int userId) {
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001291 if (DEBUG) {
1292 Slog.d(TAG, "cleanupDanglingBitmaps: userId=" + userId);
1293 }
Makoto Onuki84d59342018-02-02 09:22:38 -08001294 final long start = getStatStartTime();
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001295
Makoto Onuki1e173232016-08-10 10:47:13 -07001296 final ShortcutUser user = getUserShortcutsLocked(userId);
1297
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001298 final File bitmapDir = getUserBitmapFilePath(userId);
1299 final File[] children = bitmapDir.listFiles();
1300 if (children == null) {
1301 return;
1302 }
1303 for (File child : children) {
1304 if (!child.isDirectory()) {
1305 continue;
1306 }
1307 final String packageName = child.getName();
1308 if (DEBUG) {
1309 Slog.d(TAG, "cleanupDanglingBitmaps: Found directory=" + packageName);
1310 }
1311 if (!user.hasPackage(packageName)) {
1312 if (DEBUG) {
1313 Slog.d(TAG, "Removing dangling bitmap directory: " + packageName);
1314 }
1315 cleanupBitmapsForPackage(userId, packageName);
1316 } else {
1317 cleanupDanglingBitmapFilesLocked(userId, user, packageName, child);
1318 }
1319 }
1320 logDurationStat(Stats.CLEANUP_DANGLING_BITMAPS, start);
1321 }
1322
Makoto Onuki475c3652017-05-08 14:29:03 -07001323 /**
1324 * Remove dangling bitmap files for a package.
1325 *
1326 * Note this method must be called with the lock held after calling
1327 * {@link ShortcutBitmapSaver#waitForAllSavesLocked()} to make sure there's no pending bitmap
1328 * saves are going on.
1329 */
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001330 private void cleanupDanglingBitmapFilesLocked(@UserIdInt int userId, @NonNull ShortcutUser user,
1331 @NonNull String packageName, @NonNull File path) {
1332 final ArraySet<String> usedFiles =
Makoto Onukic51b2872016-05-04 15:24:50 -07001333 user.getPackageShortcuts(packageName).getUsedBitmapFiles();
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001334
1335 for (File child : path.listFiles()) {
1336 if (!child.isFile()) {
1337 continue;
1338 }
1339 final String name = child.getName();
1340 if (!usedFiles.contains(name)) {
1341 if (DEBUG) {
1342 Slog.d(TAG, "Removing dangling bitmap file: " + child.getAbsolutePath());
1343 }
1344 child.delete();
1345 }
1346 }
1347 }
1348
Makoto Onuki55046222016-03-08 10:49:47 -08001349 @VisibleForTesting
1350 static class FileOutputStreamWithPath extends FileOutputStream {
1351 private final File mFile;
1352
1353 public FileOutputStreamWithPath(File file) throws FileNotFoundException {
1354 super(file);
1355 mFile = file;
1356 }
1357
1358 public File getFile() {
1359 return mFile;
1360 }
1361 }
1362
1363 /**
1364 * Build the cached bitmap filename for a shortcut icon.
1365 *
1366 * The filename will be based on the ID, except certain characters will be escaped.
1367 */
Makoto Onuki55046222016-03-08 10:49:47 -08001368 FileOutputStreamWithPath openIconFileForWrite(@UserIdInt int userId, ShortcutInfo shortcut)
1369 throws IOException {
1370 final File packagePath = new File(getUserBitmapFilePath(userId),
Makoto Onuki22fcc682016-05-17 14:52:19 -07001371 shortcut.getPackage());
Makoto Onuki55046222016-03-08 10:49:47 -08001372 if (!packagePath.isDirectory()) {
1373 packagePath.mkdirs();
1374 if (!packagePath.isDirectory()) {
1375 throw new IOException("Unable to create directory " + packagePath);
1376 }
1377 SELinux.restorecon(packagePath);
1378 }
1379
1380 final String baseName = String.valueOf(injectCurrentTimeMillis());
Makoto Onukib08790c2016-06-23 14:05:46 -07001381 for (int suffix = 0; ; suffix++) {
Makoto Onuki55046222016-03-08 10:49:47 -08001382 final String filename = (suffix == 0 ? baseName : baseName + "_" + suffix) + ".png";
1383 final File file = new File(packagePath, filename);
1384 if (!file.exists()) {
1385 if (DEBUG) {
1386 Slog.d(TAG, "Saving icon to " + file.getAbsolutePath());
1387 }
1388 return new FileOutputStreamWithPath(file);
1389 }
1390 }
1391 }
1392
Makoto Onuki475c3652017-05-08 14:29:03 -07001393 void saveIconAndFixUpShortcutLocked(ShortcutInfo shortcut) {
Makoto Onuki55046222016-03-08 10:49:47 -08001394 if (shortcut.hasIconFile() || shortcut.hasIconResource()) {
1395 return;
1396 }
1397
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001398 final long token = injectClearCallingIdentity();
Makoto Onuki55046222016-03-08 10:49:47 -08001399 try {
1400 // Clear icon info on the shortcut.
Makoto Onuki475c3652017-05-08 14:29:03 -07001401 removeIconLocked(shortcut);
Makoto Onuki55046222016-03-08 10:49:47 -08001402
1403 final Icon icon = shortcut.getIcon();
1404 if (icon == null) {
1405 return; // has no icon
1406 }
Hyunyoung Song47037462017-05-08 16:51:43 -07001407 int maxIconDimension = mMaxIconDimension;
Makoto Onukiabe84422016-04-07 09:41:19 -07001408 Bitmap bitmap;
Makoto Onuki55046222016-03-08 10:49:47 -08001409 try {
1410 switch (icon.getType()) {
1411 case Icon.TYPE_RESOURCE: {
1412 injectValidateIconResPackage(shortcut, icon);
1413
1414 shortcut.setIconResourceId(icon.getResId());
1415 shortcut.addFlags(ShortcutInfo.FLAG_HAS_ICON_RES);
1416 return;
1417 }
Hyunyoung Songf281e7a2017-02-13 10:57:42 -08001418 case Icon.TYPE_BITMAP:
Makoto Onukiabe84422016-04-07 09:41:19 -07001419 bitmap = icon.getBitmap(); // Don't recycle in this case.
Makoto Onuki55046222016-03-08 10:49:47 -08001420 break;
Hyunyoung Song47037462017-05-08 16:51:43 -07001421 case Icon.TYPE_ADAPTIVE_BITMAP: {
1422 bitmap = icon.getBitmap(); // Don't recycle in this case.
1423 maxIconDimension *= (1 + 2 * AdaptiveIconDrawable.getExtraInsetFraction());
Hyunyoung Song8947f592017-05-15 10:12:11 -07001424 break;
Makoto Onuki55046222016-03-08 10:49:47 -08001425 }
Makoto Onuki55046222016-03-08 10:49:47 -08001426 default:
1427 // This shouldn't happen because we've already validated the icon, but
1428 // just in case.
1429 throw ShortcutInfo.getInvalidIconException();
1430 }
Makoto Onuki475c3652017-05-08 14:29:03 -07001431 mShortcutBitmapSaver.saveBitmapLocked(shortcut,
Hyunyoung Song47037462017-05-08 16:51:43 -07001432 maxIconDimension, mIconPersistFormat, mIconPersistQuality);
Makoto Onuki55046222016-03-08 10:49:47 -08001433 } finally {
Makoto Onuki55046222016-03-08 10:49:47 -08001434 // Once saved, we won't use the original icon information, so null it out.
1435 shortcut.clearIcon();
1436 }
1437 } finally {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001438 injectRestoreCallingIdentity(token);
Makoto Onuki55046222016-03-08 10:49:47 -08001439 }
1440 }
1441
1442 // Unfortunately we can't do this check in unit tests because we fake creator package names,
1443 // so override in unit tests.
1444 // TODO CTS this case.
1445 void injectValidateIconResPackage(ShortcutInfo shortcut, Icon icon) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07001446 if (!shortcut.getPackage().equals(icon.getResPackage())) {
Makoto Onuki55046222016-03-08 10:49:47 -08001447 throw new IllegalArgumentException(
1448 "Icon resource must reside in shortcut owner package");
1449 }
1450 }
1451
Makoto Onuki55046222016-03-08 10:49:47 -08001452 static Bitmap shrinkBitmap(Bitmap in, int maxSize) {
1453 // Original width/height.
1454 final int ow = in.getWidth();
1455 final int oh = in.getHeight();
1456 if ((ow <= maxSize) && (oh <= maxSize)) {
1457 if (DEBUG) {
1458 Slog.d(TAG, String.format("Icon size %dx%d, no need to shrink", ow, oh));
1459 }
1460 return in;
1461 }
1462 final int longerDimension = Math.max(ow, oh);
1463
1464 // New width and height.
1465 final int nw = ow * maxSize / longerDimension;
1466 final int nh = oh * maxSize / longerDimension;
1467 if (DEBUG) {
1468 Slog.d(TAG, String.format("Icon size %dx%d, shrinking to %dx%d",
1469 ow, oh, nw, nh));
1470 }
1471
1472 final Bitmap scaledBitmap = Bitmap.createBitmap(nw, nh, Bitmap.Config.ARGB_8888);
1473 final Canvas c = new Canvas(scaledBitmap);
1474
1475 final RectF dst = new RectF(0, 0, nw, nh);
1476
1477 c.drawBitmap(in, /*src=*/ null, dst, /* paint =*/ null);
1478
Makoto Onuki55046222016-03-08 10:49:47 -08001479 return scaledBitmap;
1480 }
1481
Makoto Onuki157b1622016-06-02 16:13:10 -07001482 /**
1483 * For a shortcut, update all resource names from resource IDs, and also update all
1484 * resource-based strings.
1485 */
1486 void fixUpShortcutResourceNamesAndValues(ShortcutInfo si) {
1487 final Resources publisherRes = injectGetResourcesForApplicationAsUser(
1488 si.getPackage(), si.getUserId());
1489 if (publisherRes != null) {
Makoto Onuki84d59342018-02-02 09:22:38 -08001490 final long start = getStatStartTime();
Makoto Onuki157b1622016-06-02 16:13:10 -07001491 try {
1492 si.lookupAndFillInResourceNames(publisherRes);
1493 } finally {
1494 logDurationStat(Stats.RESOURCE_NAME_LOOKUP, start);
1495 }
1496 si.resolveResourceStrings(publisherRes);
1497 }
1498 }
1499
Makoto Onuki55046222016-03-08 10:49:47 -08001500 // === Caller validation ===
1501
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001502 private boolean isCallerSystem() {
1503 final int callingUid = injectBinderCallingUid();
Makoto Onukib08790c2016-06-23 14:05:46 -07001504 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001505 }
1506
1507 private boolean isCallerShell() {
1508 final int callingUid = injectBinderCallingUid();
1509 return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
1510 }
1511
1512 private void enforceSystemOrShell() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001513 if (!(isCallerSystem() || isCallerShell())) {
1514 throw new SecurityException("Caller must be system or shell");
1515 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001516 }
1517
1518 private void enforceShell() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001519 if (!isCallerShell()) {
1520 throw new SecurityException("Caller must be shell");
1521 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001522 }
1523
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001524 private void enforceSystem() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001525 if (!isCallerSystem()) {
1526 throw new SecurityException("Caller must be system");
1527 }
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001528 }
1529
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001530 private void enforceResetThrottlingPermission() {
1531 if (isCallerSystem()) {
1532 return;
1533 }
Makoto Onuki76269922016-07-15 14:58:54 -07001534 enforceCallingOrSelfPermission(
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001535 android.Manifest.permission.RESET_SHORTCUT_MANAGER_THROTTLING, null);
1536 }
1537
Makoto Onuki76269922016-07-15 14:58:54 -07001538 private void enforceCallingOrSelfPermission(
1539 @NonNull String permission, @Nullable String message) {
1540 if (isCallerSystem()) {
1541 return;
1542 }
1543 injectEnforceCallingPermission(permission, message);
1544 }
1545
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001546 /**
1547 * Somehow overriding ServiceContext.enforceCallingPermission() in the unit tests would confuse
1548 * mockito. So instead we extracted it here and override it in the tests.
1549 */
1550 @VisibleForTesting
1551 void injectEnforceCallingPermission(
1552 @NonNull String permission, @Nullable String message) {
1553 mContext.enforceCallingPermission(permission, message);
1554 }
1555
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001556 private void verifyCaller(@NonNull String packageName, @UserIdInt int userId) {
1557 Preconditions.checkStringNotEmpty(packageName, "packageName");
1558
1559 if (isCallerSystem()) {
1560 return; // no check
1561 }
1562
1563 final int callingUid = injectBinderCallingUid();
1564
1565 // Otherwise, make sure the arguments are valid.
1566 if (UserHandle.getUserId(callingUid) != userId) {
1567 throw new SecurityException("Invalid user-ID");
1568 }
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08001569 if (injectGetPackageUid(packageName, userId) != callingUid) {
1570 throw new SecurityException("Calling package name mismatch");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001571 }
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08001572 Preconditions.checkState(!isEphemeralApp(packageName, userId),
1573 "Ephemeral apps can't use ShortcutManager");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001574 }
1575
Makoto Onuki157b1622016-06-02 16:13:10 -07001576 // Overridden in unit tests to execute r synchronously.
1577 void injectPostToHandler(Runnable r) {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001578 mHandler.post(r);
1579 }
1580
Makoto Onuki085a05c2016-08-19 11:39:29 -07001581 void injectRunOnNewThread(Runnable r) {
1582 new Thread(r).start();
1583 }
1584
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001585 /**
Makoto Onuki7001a612016-05-27 13:24:28 -07001586 * @throws IllegalArgumentException if {@code numShortcuts} is bigger than
Makoto Onukib08790c2016-06-23 14:05:46 -07001587 * {@link #getMaxActivityShortcuts()}.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001588 */
Makoto Onuki7001a612016-05-27 13:24:28 -07001589 void enforceMaxActivityShortcuts(int numShortcuts) {
Makoto Onukib5a012f2016-06-21 11:13:53 -07001590 if (numShortcuts > mMaxShortcuts) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001591 throw new IllegalArgumentException("Max number of dynamic shortcuts exceeded");
1592 }
1593 }
1594
1595 /**
Makoto Onuki7001a612016-05-27 13:24:28 -07001596 * Return the max number of dynamic + manifest shortcuts for each launcher icon.
1597 */
1598 int getMaxActivityShortcuts() {
Makoto Onukib5a012f2016-06-21 11:13:53 -07001599 return mMaxShortcuts;
Makoto Onuki7001a612016-05-27 13:24:28 -07001600 }
1601
1602 /**
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001603 * - Sends a notification to LauncherApps
1604 * - Write to file
1605 */
Makoto Onuki39686e82016-04-13 18:03:00 -07001606 void packageShortcutsChanged(@NonNull String packageName, @UserIdInt int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001607 notifyListeners(packageName, userId);
1608 scheduleSaveUser(userId);
1609 }
1610
1611 private void notifyListeners(@NonNull String packageName, @UserIdInt int userId) {
Makoto Onuki82fb2eb2017-03-31 16:58:26 -07001612 if (DEBUG) {
1613 Slog.d(TAG, String.format(
1614 "Shortcut changes: package=%s, user=%d", packageName, userId));
1615 }
Makoto Onuki157b1622016-06-02 16:13:10 -07001616 injectPostToHandler(() -> {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001617 try {
1618 final ArrayList<ShortcutChangeListener> copy;
1619 synchronized (mLock) {
1620 if (!isUserUnlockedL(userId)) {
1621 return;
1622 }
1623
1624 copy = new ArrayList<>(mListeners);
1625 }
1626 // Note onShortcutChanged() needs to be called with the system service permissions.
1627 for (int i = copy.size() - 1; i >= 0; i--) {
1628 copy.get(i).onShortcutChanged(packageName, userId);
1629 }
1630 } catch (Exception ignore) {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001631 }
1632 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001633 }
1634
1635 /**
1636 * Clean up / validate an incoming shortcut.
1637 * - Make sure all mandatory fields are set.
1638 * - Make sure the intent's extras are persistable, and them to set
Makoto Onuki0eed4412016-07-21 11:21:59 -07001639 * {@link ShortcutInfo#mIntentPersistableExtrases}. Also clear its extras.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001640 * - Clear flags.
1641 */
Makoto Onuki2d895c32016-12-02 15:48:40 -08001642 private void fixUpIncomingShortcutInfo(@NonNull ShortcutInfo shortcut, boolean forUpdate,
1643 boolean forPinRequest) {
Makoto Onukibf563b62017-05-04 10:25:30 -07001644 if (shortcut.isReturnedByServer()) {
1645 Log.w(TAG,
1646 "Re-publishing ShortcutInfo returned by server is not supported."
1647 + " Some information such as icon may lost from shortcut.");
1648 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001649 Preconditions.checkNotNull(shortcut, "Null shortcut detected");
Makoto Onuki255461f2017-01-10 11:47:25 -08001650 if (shortcut.getActivity() != null) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001651 Preconditions.checkState(
Makoto Onuki22fcc682016-05-17 14:52:19 -07001652 shortcut.getPackage().equals(shortcut.getActivity().getPackageName()),
Makoto Onukib08790c2016-06-23 14:05:46 -07001653 "Cannot publish shortcut: activity " + shortcut.getActivity() + " does not"
1654 + " belong to package " + shortcut.getPackage());
Makoto Onuki13260b6ff2016-07-13 18:03:13 -07001655 Preconditions.checkState(
1656 injectIsMainActivity(shortcut.getActivity(), shortcut.getUserId()),
1657 "Cannot publish shortcut: activity " + shortcut.getActivity() + " is not"
1658 + " main activity");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001659 }
1660
Makoto Onuki55046222016-03-08 10:49:47 -08001661 if (!forUpdate) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08001662 shortcut.enforceMandatoryFields(/* forPinned= */ forPinRequest);
1663 if (!forPinRequest) {
Makoto Onuki255461f2017-01-10 11:47:25 -08001664 Preconditions.checkState(shortcut.getActivity() != null,
1665 "Cannot publish shortcut: target activity is not set");
Makoto Onuki2d895c32016-12-02 15:48:40 -08001666 }
Makoto Onuki55046222016-03-08 10:49:47 -08001667 }
1668 if (shortcut.getIcon() != null) {
1669 ShortcutInfo.validateIcon(shortcut.getIcon());
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001670 }
1671
Makoto Onukide667372016-03-15 14:29:20 -07001672 shortcut.replaceFlags(0);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001673 }
1674
Makoto Onuki2d895c32016-12-02 15:48:40 -08001675 private void fixUpIncomingShortcutInfo(@NonNull ShortcutInfo shortcut, boolean forUpdate) {
1676 fixUpIncomingShortcutInfo(shortcut, forUpdate, /*forPinRequest=*/ false);
1677 }
1678
1679 public void validateShortcutForPinRequest(@NonNull ShortcutInfo shortcut) {
1680 fixUpIncomingShortcutInfo(shortcut, /* forUpdate= */ false, /*forPinRequest=*/ true);
1681 }
1682
Makoto Onukib08790c2016-06-23 14:05:46 -07001683 /**
1684 * When a shortcut has no target activity, set the default one from the package.
1685 */
1686 private void fillInDefaultActivity(List<ShortcutInfo> shortcuts) {
Makoto Onukib08790c2016-06-23 14:05:46 -07001687 ComponentName defaultActivity = null;
1688 for (int i = shortcuts.size() - 1; i >= 0; i--) {
1689 final ShortcutInfo si = shortcuts.get(i);
1690 if (si.getActivity() == null) {
1691 if (defaultActivity == null) {
1692 defaultActivity = injectGetDefaultMainActivity(
1693 si.getPackage(), si.getUserId());
1694 Preconditions.checkState(defaultActivity != null,
1695 "Launcher activity not found for package " + si.getPackage());
1696 }
1697 si.setActivity(defaultActivity);
1698 }
1699 }
1700 }
1701
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001702 private void assignImplicitRanks(List<ShortcutInfo> shortcuts) {
1703 for (int i = shortcuts.size() - 1; i >= 0; i--) {
1704 shortcuts.get(i).setImplicitRank(i);
1705 }
1706 }
1707
Makoto Onukibf563b62017-05-04 10:25:30 -07001708 private List<ShortcutInfo> setReturnedByServer(List<ShortcutInfo> shortcuts) {
1709 for (int i = shortcuts.size() - 1; i >= 0; i--) {
1710 shortcuts.get(i).setReturnedByServer();
1711 }
1712 return shortcuts;
1713 }
1714
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001715 // === APIs ===
1716
1717 @Override
1718 public boolean setDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1719 @UserIdInt int userId) {
1720 verifyCaller(packageName, userId);
1721
1722 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
1723 final int size = newShortcuts.size();
1724
Makoto Onuki7d0fa812018-02-21 11:24:43 -08001725 final boolean unlimited = injectHasUnlimitedShortcutsApiCallsPermission(
1726 injectBinderCallingPid(), injectBinderCallingUid());
1727
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001728 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001729 throwIfUserLockedL(userId);
1730
Makoto Onukic8c33292016-09-12 16:36:59 -07001731 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001732
Makoto Onukia4f89b12017-10-05 10:37:55 -07001733 ps.ensureImmutableShortcutsNotIncluded(newShortcuts, /*ignoreInvisible=*/ true);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001734
Makoto Onukib08790c2016-06-23 14:05:46 -07001735 fillInDefaultActivity(newShortcuts);
1736
Makoto Onuki7001a612016-05-27 13:24:28 -07001737 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_SET);
1738
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001739 // Throttling.
Makoto Onuki7d0fa812018-02-21 11:24:43 -08001740 if (!ps.tryApiCall(unlimited)) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001741 return false;
1742 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001743
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001744 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1745 ps.clearAllImplicitRanks();
1746 assignImplicitRanks(newShortcuts);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001747
Makoto Onukidf6da042016-06-16 09:51:40 -07001748 for (int i = 0; i < size; i++) {
1749 fixUpIncomingShortcutInfo(newShortcuts.get(i), /* forUpdate= */ false);
1750 }
1751
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001752 // First, remove all un-pinned; dynamic shortcuts
Makoto Onukia4f89b12017-10-05 10:37:55 -07001753 ps.deleteAllDynamicShortcuts(/*ignoreInvisible=*/ true);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001754
1755 // Then, add/update all. We need to make sure to take over "pinned" flag.
1756 for (int i = 0; i < size; i++) {
1757 final ShortcutInfo newShortcut = newShortcuts.get(i);
Makoto Onukia4f89b12017-10-05 10:37:55 -07001758 ps.addOrReplaceDynamicShortcut(newShortcut);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001759 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001760
1761 // Lastly, adjust the ranks.
1762 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001763 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001764 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001765
1766 verifyStates();
1767
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001768 return true;
1769 }
1770
1771 @Override
1772 public boolean updateShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1773 @UserIdInt int userId) {
1774 verifyCaller(packageName, userId);
1775
1776 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
Makoto Onuki55046222016-03-08 10:49:47 -08001777 final int size = newShortcuts.size();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001778
Makoto Onuki7d0fa812018-02-21 11:24:43 -08001779 final boolean unlimited = injectHasUnlimitedShortcutsApiCallsPermission(
1780 injectBinderCallingPid(), injectBinderCallingUid());
1781
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001782 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001783 throwIfUserLockedL(userId);
1784
Makoto Onukic8c33292016-09-12 16:36:59 -07001785 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001786
Makoto Onukia4f89b12017-10-05 10:37:55 -07001787 ps.ensureImmutableShortcutsNotIncluded(newShortcuts, /*ignoreInvisible=*/ true);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001788
Makoto Onukib08790c2016-06-23 14:05:46 -07001789 // For update, don't fill in the default activity. Having null activity means
1790 // "don't update the activity" here.
1791
Makoto Onuki7001a612016-05-27 13:24:28 -07001792 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_UPDATE);
1793
Makoto Onuki55046222016-03-08 10:49:47 -08001794 // Throttling.
Makoto Onuki7d0fa812018-02-21 11:24:43 -08001795 if (!ps.tryApiCall(unlimited)) {
Makoto Onuki55046222016-03-08 10:49:47 -08001796 return false;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001797 }
1798
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001799 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1800 ps.clearAllImplicitRanks();
1801 assignImplicitRanks(newShortcuts);
1802
Makoto Onuki55046222016-03-08 10:49:47 -08001803 for (int i = 0; i < size; i++) {
1804 final ShortcutInfo source = newShortcuts.get(i);
1805 fixUpIncomingShortcutInfo(source, /* forUpdate= */ true);
1806
1807 final ShortcutInfo target = ps.findShortcutById(source.getId());
Makoto Onukia4f89b12017-10-05 10:37:55 -07001808
1809 // Invisible shortcuts can't be updated.
1810 if (target == null || !target.isVisibleToPublisher()) {
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001811 continue;
1812 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07001813
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001814 if (target.isEnabled() != source.isEnabled()) {
1815 Slog.w(TAG,
1816 "ShortcutInfo.enabled cannot be changed with updateShortcuts()");
1817 }
Makoto Onuki55046222016-03-08 10:49:47 -08001818
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001819 // When updating the rank, we need to insert between existing ranks, so set
1820 // this setRankChanged, and also copy the implicit rank fo adjustRanks().
1821 if (source.hasRank()) {
1822 target.setRankChanged();
1823 target.setImplicitRank(source.getImplicitRank());
1824 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07001825
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001826 final boolean replacingIcon = (source.getIcon() != null);
1827 if (replacingIcon) {
Makoto Onuki475c3652017-05-08 14:29:03 -07001828 removeIconLocked(target);
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001829 }
Makoto Onuki55046222016-03-08 10:49:47 -08001830
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001831 // Note copyNonNullFieldsFrom() does the "updatable with?" check too.
1832 target.copyNonNullFieldsFrom(source);
1833 target.setTimestamp(injectCurrentTimeMillis());
1834
1835 if (replacingIcon) {
Makoto Onuki475c3652017-05-08 14:29:03 -07001836 saveIconAndFixUpShortcutLocked(target);
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001837 }
1838
1839 // When we're updating any resource related fields, re-extract the res names and
1840 // the values.
1841 if (replacingIcon || source.hasStringResources()) {
1842 fixUpShortcutResourceNamesAndValues(target);
Makoto Onuki55046222016-03-08 10:49:47 -08001843 }
1844 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001845
1846 // Lastly, adjust the ranks.
1847 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001848 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001849 packageShortcutsChanged(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001850
Makoto Onuki7001a612016-05-27 13:24:28 -07001851 verifyStates();
1852
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001853 return true;
1854 }
1855
1856 @Override
Makoto Onukia4f89b12017-10-05 10:37:55 -07001857 public boolean addDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001858 @UserIdInt int userId) {
1859 verifyCaller(packageName, userId);
1860
Makoto Onukib6d35232016-04-04 15:57:17 -07001861 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
1862 final int size = newShortcuts.size();
1863
Makoto Onuki7d0fa812018-02-21 11:24:43 -08001864 final boolean unlimited = injectHasUnlimitedShortcutsApiCallsPermission(
1865 injectBinderCallingPid(), injectBinderCallingUid());
1866
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001867 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001868 throwIfUserLockedL(userId);
1869
Makoto Onukic8c33292016-09-12 16:36:59 -07001870 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001871
Makoto Onukia4f89b12017-10-05 10:37:55 -07001872 ps.ensureImmutableShortcutsNotIncluded(newShortcuts, /*ignoreInvisible=*/ true);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001873
Makoto Onukib08790c2016-06-23 14:05:46 -07001874 fillInDefaultActivity(newShortcuts);
1875
Makoto Onuki7001a612016-05-27 13:24:28 -07001876 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_ADD);
1877
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001878 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1879 ps.clearAllImplicitRanks();
1880 assignImplicitRanks(newShortcuts);
1881
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001882 // Throttling.
Makoto Onuki7d0fa812018-02-21 11:24:43 -08001883 if (!ps.tryApiCall(unlimited)) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001884 return false;
1885 }
Makoto Onukib6d35232016-04-04 15:57:17 -07001886 for (int i = 0; i < size; i++) {
1887 final ShortcutInfo newShortcut = newShortcuts.get(i);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001888
Makoto Onukib6d35232016-04-04 15:57:17 -07001889 // Validate the shortcut.
1890 fixUpIncomingShortcutInfo(newShortcut, /* forUpdate= */ false);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001891
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001892 // When ranks are changing, we need to insert between ranks, so set the
1893 // "rank changed" flag.
1894 newShortcut.setRankChanged();
1895
Makoto Onukib6d35232016-04-04 15:57:17 -07001896 // Add it.
Makoto Onukia4f89b12017-10-05 10:37:55 -07001897 ps.addOrReplaceDynamicShortcut(newShortcut);
Makoto Onukib6d35232016-04-04 15:57:17 -07001898 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001899
1900 // Lastly, adjust the ranks.
1901 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001902 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001903 packageShortcutsChanged(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001904
Makoto Onuki7001a612016-05-27 13:24:28 -07001905 verifyStates();
1906
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001907 return true;
1908 }
1909
1910 @Override
Makoto Onuki2d895c32016-12-02 15:48:40 -08001911 public boolean requestPinShortcut(String packageName, ShortcutInfo shortcut,
1912 IntentSender resultIntent, int userId) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08001913 Preconditions.checkNotNull(shortcut);
1914 Preconditions.checkArgument(shortcut.isEnabled(), "Shortcut must be enabled");
Sunny Goyal4ad6b572017-02-28 11:11:51 -08001915 return requestPinItem(packageName, userId, shortcut, null, null, resultIntent);
Sunny Goyal87a563e2017-01-01 19:42:45 -08001916 }
1917
Sunny Goyala6be88a2017-01-12 16:27:58 -08001918 @Override
1919 public Intent createShortcutResultIntent(String packageName, ShortcutInfo shortcut, int userId)
1920 throws RemoteException {
1921 Preconditions.checkNotNull(shortcut);
1922 Preconditions.checkArgument(shortcut.isEnabled(), "Shortcut must be enabled");
1923 verifyCaller(packageName, userId);
1924
1925 final Intent ret;
1926 synchronized (mLock) {
1927 throwIfUserLockedL(userId);
1928
1929 // Send request to the launcher, if supported.
1930 ret = mShortcutRequestPinProcessor.createShortcutResultIntent(shortcut, userId);
1931 }
1932
1933 verifyStates();
1934 return ret;
1935 }
1936
Sunny Goyal87a563e2017-01-01 19:42:45 -08001937 /**
1938 * Handles {@link #requestPinShortcut} and {@link ShortcutServiceInternal#requestPinAppWidget}.
1939 * After validating the caller, it passes the request to {@link #mShortcutRequestPinProcessor}.
1940 * Either {@param shortcut} or {@param appWidget} should be non-null.
1941 */
Sunny Goyal4ad6b572017-02-28 11:11:51 -08001942 private boolean requestPinItem(String packageName, int userId, ShortcutInfo shortcut,
1943 AppWidgetProviderInfo appWidget, Bundle extras, IntentSender resultIntent) {
Sunny Goyal87a563e2017-01-01 19:42:45 -08001944 verifyCaller(packageName, userId);
Makoto Onuki2d895c32016-12-02 15:48:40 -08001945
1946 final boolean ret;
1947 synchronized (mLock) {
1948 throwIfUserLockedL(userId);
1949
Makoto Onukia01f4f02016-12-15 15:58:41 -08001950 Preconditions.checkState(isUidForegroundLocked(injectBinderCallingUid()),
Makoto Onuki255461f2017-01-10 11:47:25 -08001951 "Calling application must have a foreground activity or a foreground service");
Makoto Onuki2d895c32016-12-02 15:48:40 -08001952
Makoto Onukia4f89b12017-10-05 10:37:55 -07001953 // If it's a pin shortcut request, and there's already a shortcut with the same ID
1954 // that's not visible to the caller (i.e. restore-blocked; meaning it's pinned by
1955 // someone already), then we just replace the existing one with this new one,
1956 // and then proceed the rest of the process.
1957 if (shortcut != null) {
1958 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(
1959 packageName, userId);
1960 final String id = shortcut.getId();
1961 if (ps.isShortcutExistsAndInvisibleToPublisher(id)) {
1962
1963 ps.updateInvisibleShortcutForPinRequestWith(shortcut);
1964
1965 packageShortcutsChanged(packageName, userId);
1966 }
1967 }
1968
Makoto Onuki2d895c32016-12-02 15:48:40 -08001969 // Send request to the launcher, if supported.
Sunny Goyal4ad6b572017-02-28 11:11:51 -08001970 ret = mShortcutRequestPinProcessor.requestPinItemLocked(shortcut, appWidget, extras,
1971 userId, resultIntent);
Makoto Onuki2d895c32016-12-02 15:48:40 -08001972 }
1973
1974 verifyStates();
1975
1976 return ret;
1977 }
1978
1979 @Override
Makoto Onuki20c95f82016-05-11 16:51:01 -07001980 public void disableShortcuts(String packageName, List shortcutIds,
Makoto Onukid6880792016-06-29 13:37:43 -07001981 CharSequence disabledMessage, int disabledMessageResId, @UserIdInt int userId) {
Makoto Onuki20c95f82016-05-11 16:51:01 -07001982 verifyCaller(packageName, userId);
1983 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
1984
1985 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001986 throwIfUserLockedL(userId);
1987
Makoto Onukic8c33292016-09-12 16:36:59 -07001988 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001989
Makoto Onukia4f89b12017-10-05 10:37:55 -07001990 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds,
1991 /*ignoreInvisible=*/ true);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001992
Makoto Onukid6880792016-06-29 13:37:43 -07001993 final String disabledMessageString =
1994 (disabledMessage == null) ? null : disabledMessage.toString();
1995
Makoto Onuki22fcc682016-05-17 14:52:19 -07001996 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
Makoto Onukia4f89b12017-10-05 10:37:55 -07001997 final String id = Preconditions.checkStringNotEmpty((String) shortcutIds.get(i));
1998 if (!ps.isShortcutExistsAndVisibleToPublisher(id)) {
1999 continue;
2000 }
2001 ps.disableWithId(id,
Makoto Onukid6880792016-06-29 13:37:43 -07002002 disabledMessageString, disabledMessageResId,
Makoto Onukia4f89b12017-10-05 10:37:55 -07002003 /* overrideImmutable=*/ false, /*ignoreInvisible=*/ true,
2004 ShortcutInfo.DISABLED_REASON_BY_APP);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002005 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002006
2007 // We may have removed dynamic shortcuts which may have left a gap, so adjust the ranks.
2008 ps.adjustRanks();
Makoto Onuki22fcc682016-05-17 14:52:19 -07002009 }
2010 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07002011
2012 verifyStates();
Makoto Onuki22fcc682016-05-17 14:52:19 -07002013 }
2014
2015 @Override
2016 public void enableShortcuts(String packageName, List shortcutIds, @UserIdInt int userId) {
2017 verifyCaller(packageName, userId);
2018 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
2019
2020 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002021 throwIfUserLockedL(userId);
2022
Makoto Onukic8c33292016-09-12 16:36:59 -07002023 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002024
Makoto Onukia4f89b12017-10-05 10:37:55 -07002025 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds,
2026 /*ignoreInvisible=*/ true);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002027
2028 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
Makoto Onukia4f89b12017-10-05 10:37:55 -07002029 final String id = Preconditions.checkStringNotEmpty((String) shortcutIds.get(i));
2030 if (!ps.isShortcutExistsAndVisibleToPublisher(id)) {
2031 continue;
2032 }
2033 ps.enableWithId(id);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002034 }
Makoto Onuki20c95f82016-05-11 16:51:01 -07002035 }
2036 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07002037
2038 verifyStates();
Makoto Onuki20c95f82016-05-11 16:51:01 -07002039 }
2040
2041 @Override
Makoto Onukib6d35232016-04-04 15:57:17 -07002042 public void removeDynamicShortcuts(String packageName, List shortcutIds,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002043 @UserIdInt int userId) {
2044 verifyCaller(packageName, userId);
Makoto Onukib6d35232016-04-04 15:57:17 -07002045 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002046
2047 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002048 throwIfUserLockedL(userId);
2049
Makoto Onukic8c33292016-09-12 16:36:59 -07002050 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002051
Makoto Onukia4f89b12017-10-05 10:37:55 -07002052 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds,
2053 /*ignoreInvisible=*/ true);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002054
Makoto Onukib6d35232016-04-04 15:57:17 -07002055 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
Makoto Onukia4f89b12017-10-05 10:37:55 -07002056 final String id = Preconditions.checkStringNotEmpty((String) shortcutIds.get(i));
2057 if (!ps.isShortcutExistsAndVisibleToPublisher(id)) {
2058 continue;
2059 }
2060 ps.deleteDynamicWithId(id, /*ignoreInvisible=*/ true);
Makoto Onukib6d35232016-04-04 15:57:17 -07002061 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002062
2063 // We may have removed dynamic shortcuts which may have left a gap, so adjust the ranks.
2064 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002065 }
Makoto Onuki39686e82016-04-13 18:03:00 -07002066 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07002067
2068 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002069 }
2070
2071 @Override
Makoto Onukib6d35232016-04-04 15:57:17 -07002072 public void removeAllDynamicShortcuts(String packageName, @UserIdInt int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002073 verifyCaller(packageName, userId);
2074
2075 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002076 throwIfUserLockedL(userId);
2077
Makoto Onukic8c33292016-09-12 16:36:59 -07002078 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onukia4f89b12017-10-05 10:37:55 -07002079 ps.deleteAllDynamicShortcuts(/*ignoreInvisible=*/ true);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002080 }
Makoto Onuki39686e82016-04-13 18:03:00 -07002081 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07002082
2083 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002084 }
2085
2086 @Override
2087 public ParceledListSlice<ShortcutInfo> getDynamicShortcuts(String packageName,
2088 @UserIdInt int userId) {
2089 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002090
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002091 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002092 throwIfUserLockedL(userId);
2093
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002094 return getShortcutsWithQueryLocked(
2095 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
Makoto Onukia4f89b12017-10-05 10:37:55 -07002096 ShortcutInfo::isDynamicVisible);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002097 }
2098 }
2099
2100 @Override
Makoto Onuki22fcc682016-05-17 14:52:19 -07002101 public ParceledListSlice<ShortcutInfo> getManifestShortcuts(String packageName,
2102 @UserIdInt int userId) {
2103 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002104
Makoto Onuki22fcc682016-05-17 14:52:19 -07002105 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002106 throwIfUserLockedL(userId);
2107
Makoto Onuki22fcc682016-05-17 14:52:19 -07002108 return getShortcutsWithQueryLocked(
2109 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
Makoto Onukia4f89b12017-10-05 10:37:55 -07002110 ShortcutInfo::isManifestVisible);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002111 }
2112 }
2113
2114 @Override
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002115 public ParceledListSlice<ShortcutInfo> getPinnedShortcuts(String packageName,
2116 @UserIdInt int userId) {
2117 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002118
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002119 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002120 throwIfUserLockedL(userId);
2121
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002122 return getShortcutsWithQueryLocked(
2123 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
Makoto Onukia4f89b12017-10-05 10:37:55 -07002124 ShortcutInfo::isPinnedVisible);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002125 }
2126 }
2127
Andreas Gampea36dc622018-02-05 17:19:22 -08002128 @GuardedBy("mLock")
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002129 private ParceledListSlice<ShortcutInfo> getShortcutsWithQueryLocked(@NonNull String packageName,
2130 @UserIdInt int userId, int cloneFlags, @NonNull Predicate<ShortcutInfo> query) {
2131
2132 final ArrayList<ShortcutInfo> ret = new ArrayList<>();
2133
Makoto Onukic8c33292016-09-12 16:36:59 -07002134 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002135 ps.findAll(ret, query, cloneFlags);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002136
Makoto Onukibf563b62017-05-04 10:25:30 -07002137 return new ParceledListSlice<>(setReturnedByServer(ret));
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002138 }
2139
2140 @Override
Makoto Onukid6880792016-06-29 13:37:43 -07002141 public int getMaxShortcutCountPerActivity(String packageName, @UserIdInt int userId)
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002142 throws RemoteException {
2143 verifyCaller(packageName, userId);
2144
Makoto Onukib5a012f2016-06-21 11:13:53 -07002145 return mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002146 }
2147
2148 @Override
2149 public int getRemainingCallCount(String packageName, @UserIdInt int userId) {
2150 verifyCaller(packageName, userId);
2151
Makoto Onuki7d0fa812018-02-21 11:24:43 -08002152 final boolean unlimited = injectHasUnlimitedShortcutsApiCallsPermission(
2153 injectBinderCallingPid(), injectBinderCallingUid());
2154
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002155 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002156 throwIfUserLockedL(userId);
2157
Makoto Onukic8c33292016-09-12 16:36:59 -07002158 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki7d0fa812018-02-21 11:24:43 -08002159 return mMaxUpdatesPerInterval - ps.getApiCallCount(unlimited);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002160 }
2161 }
2162
2163 @Override
2164 public long getRateLimitResetTime(String packageName, @UserIdInt int userId) {
2165 verifyCaller(packageName, userId);
2166
2167 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002168 throwIfUserLockedL(userId);
2169
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002170 return getNextResetTimeLocked();
2171 }
2172 }
2173
Makoto Onuki55046222016-03-08 10:49:47 -08002174 @Override
Makoto Onuki20c95f82016-05-11 16:51:01 -07002175 public int getIconMaxDimensions(String packageName, int userId) {
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002176 verifyCaller(packageName, userId);
2177
Makoto Onuki55046222016-03-08 10:49:47 -08002178 synchronized (mLock) {
2179 return mMaxIconDimension;
2180 }
2181 }
2182
Makoto Onuki20c95f82016-05-11 16:51:01 -07002183 @Override
2184 public void reportShortcutUsed(String packageName, String shortcutId, int userId) {
2185 verifyCaller(packageName, userId);
2186
Makoto Onukiac042502016-05-20 16:39:42 -07002187 Preconditions.checkNotNull(shortcutId);
2188
2189 if (DEBUG) {
2190 Slog.d(TAG, String.format("reportShortcutUsed: Shortcut %s package %s used on user %d",
2191 shortcutId, packageName, userId));
2192 }
2193
2194 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002195 throwIfUserLockedL(userId);
2196
Makoto Onukic8c33292016-09-12 16:36:59 -07002197 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002198
Makoto Onukiac042502016-05-20 16:39:42 -07002199 if (ps.findShortcutById(shortcutId) == null) {
2200 Log.w(TAG, String.format("reportShortcutUsed: package %s doesn't have shortcut %s",
2201 packageName, shortcutId));
2202 return;
2203 }
2204 }
2205
2206 final long token = injectClearCallingIdentity();
2207 try {
2208 mUsageStatsManagerInternal.reportShortcutUsage(packageName, shortcutId, userId);
2209 } finally {
2210 injectRestoreCallingIdentity(token);
2211 }
Makoto Onuki20c95f82016-05-11 16:51:01 -07002212 }
2213
Makoto Onuki2d895c32016-12-02 15:48:40 -08002214 @Override
Sunny Goyal7f7372a2017-01-24 11:53:54 -08002215 public boolean isRequestPinItemSupported(int callingUserId, int requestType) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08002216 final long token = injectClearCallingIdentity();
2217 try {
Sunny Goyal7f7372a2017-01-24 11:53:54 -08002218 return mShortcutRequestPinProcessor
2219 .isRequestPinItemSupported(callingUserId, requestType);
Makoto Onuki2d895c32016-12-02 15:48:40 -08002220 } finally {
2221 injectRestoreCallingIdentity(token);
2222 }
2223 }
2224
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002225 /**
Makoto Onukib08790c2016-06-23 14:05:46 -07002226 * Reset all throttling, for developer options and command line. Only system/shell can call
2227 * it.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002228 */
2229 @Override
2230 public void resetThrottling() {
2231 enforceSystemOrShell();
2232
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002233 resetThrottlingInner(getCallingUserId());
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002234 }
2235
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002236 void resetThrottlingInner(@UserIdInt int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002237 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002238 if (!isUserUnlockedL(userId)) {
2239 Log.w(TAG, "User " + userId + " is locked or not running");
2240 return;
2241 }
2242
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002243 getUserShortcutsLocked(userId).resetThrottling();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002244 }
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002245 scheduleSaveUser(userId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002246 Slog.i(TAG, "ShortcutManager: throttling counter reset for user " + userId);
2247 }
2248
2249 void resetAllThrottlingInner() {
2250 synchronized (mLock) {
2251 mRawLastResetTime = injectCurrentTimeMillis();
2252 }
2253 scheduleSaveBaseState();
2254 Slog.i(TAG, "ShortcutManager: throttling counter reset for all users");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002255 }
2256
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002257 @Override
2258 public void onApplicationActive(String packageName, int userId) {
2259 if (DEBUG) {
2260 Slog.d(TAG, "onApplicationActive: package=" + packageName + " userid=" + userId);
2261 }
2262 enforceResetThrottlingPermission();
Makoto Onuki02f338e2016-07-29 09:40:40 -07002263
2264 synchronized (mLock) {
2265 if (!isUserUnlockedL(userId)) {
2266 // This is called by system UI, so no need to throw. Just ignore.
2267 return;
2268 }
2269
2270 getPackageShortcutsLocked(packageName, userId)
2271 .resetRateLimitingForCommandLineNoSaving();
2272 saveUserLocked(userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002273 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002274 }
2275
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002276 // We override this method in unit tests to do a simpler check.
Makoto Onuki634cecb2017-10-13 17:10:48 -07002277 boolean hasShortcutHostPermission(@NonNull String callingPackage, int userId,
2278 int callingPid, int callingUid) {
Makoto Onuki35559d62017-11-06 16:26:32 -08002279 if (canSeeAnyPinnedShortcut(callingPackage, userId, callingPid, callingUid)) {
Makoto Onuki634cecb2017-10-13 17:10:48 -07002280 return true;
2281 }
Makoto Onuki84d59342018-02-02 09:22:38 -08002282 final long start = getStatStartTime();
Makoto Onuki10305202016-07-14 18:14:08 -07002283 try {
2284 return hasShortcutHostPermissionInner(callingPackage, userId);
2285 } finally {
2286 logDurationStat(Stats.LAUNCHER_PERMISSION_CHECK, start);
2287 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002288 }
2289
Makoto Onuki35559d62017-11-06 16:26:32 -08002290 boolean canSeeAnyPinnedShortcut(@NonNull String callingPackage, int userId,
2291 int callingPid, int callingUid) {
2292 if (injectHasAccessShortcutsPermission(callingPid, callingUid)) {
2293 return true;
2294 }
2295 synchronized (mLock) {
Makoto Onuki708703b2017-12-11 16:38:11 -08002296 return getNonPersistentUserLocked(userId).hasHostPackage(callingPackage);
Makoto Onuki35559d62017-11-06 16:26:32 -08002297 }
2298 }
2299
Makoto Onuki634cecb2017-10-13 17:10:48 -07002300 /**
2301 * Returns true if the caller has the "ACCESS_SHORTCUTS" permission.
2302 */
Makoto Onuki35559d62017-11-06 16:26:32 -08002303 @VisibleForTesting
2304 boolean injectHasAccessShortcutsPermission(int callingPid, int callingUid) {
Makoto Onuki634cecb2017-10-13 17:10:48 -07002305 return mContext.checkPermission(android.Manifest.permission.ACCESS_SHORTCUTS,
2306 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
2307 }
2308
Makoto Onuki7d0fa812018-02-21 11:24:43 -08002309 /**
2310 * Returns true if the caller has the "UNLIMITED_SHORTCUTS_API_CALLS" permission.
2311 */
2312 @VisibleForTesting
2313 boolean injectHasUnlimitedShortcutsApiCallsPermission(int callingPid, int callingUid) {
2314 return mContext.checkPermission(permission.UNLIMITED_SHORTCUTS_API_CALLS,
2315 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
2316 }
2317
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002318 // This method is extracted so we can directly call this method from unit tests,
2319 // even when hasShortcutPermission() is overridden.
2320 @VisibleForTesting
Makoto Onuki2d895c32016-12-02 15:48:40 -08002321 boolean hasShortcutHostPermissionInner(@NonNull String packageName, int userId) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002322 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002323 throwIfUserLockedL(userId);
2324
Makoto Onuki31459242016-03-22 11:12:18 -07002325 final ShortcutUser user = getUserShortcutsLocked(userId);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002326
Makoto Onuki2d895c32016-12-02 15:48:40 -08002327 // Always trust the cached component.
Makoto Onuki10305202016-07-14 18:14:08 -07002328 final ComponentName cached = user.getCachedLauncher();
2329 if (cached != null) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08002330 if (cached.getPackageName().equals(packageName)) {
Makoto Onuki10305202016-07-14 18:14:08 -07002331 return true;
2332 }
2333 }
2334 // If the cached one doesn't match, then go ahead
2335
Makoto Onuki2d895c32016-12-02 15:48:40 -08002336 final ComponentName detected = getDefaultLauncher(userId);
Makoto Onuki2e210c42016-03-30 08:30:36 -07002337
Makoto Onuki10305202016-07-14 18:14:08 -07002338 // Update the cache.
2339 user.setLauncher(detected);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002340 if (detected != null) {
2341 if (DEBUG) {
2342 Slog.v(TAG, "Detected launcher: " + detected);
2343 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08002344 return detected.getPackageName().equals(packageName);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002345 } else {
2346 // Default launcher not found.
2347 return false;
2348 }
2349 }
2350 }
2351
Makoto Onuki2d895c32016-12-02 15:48:40 -08002352 @Nullable
2353 ComponentName getDefaultLauncher(@UserIdInt int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08002354 final long start = getStatStartTime();
Makoto Onuki2d895c32016-12-02 15:48:40 -08002355 final long token = injectClearCallingIdentity();
2356 try {
2357 synchronized (mLock) {
2358 throwIfUserLockedL(userId);
2359
2360 final ShortcutUser user = getUserShortcutsLocked(userId);
2361
2362 final List<ResolveInfo> allHomeCandidates = new ArrayList<>();
2363
2364 // Default launcher from package manager.
Makoto Onuki84d59342018-02-02 09:22:38 -08002365 final long startGetHomeActivitiesAsUser = getStatStartTime();
Makoto Onuki2d895c32016-12-02 15:48:40 -08002366 final ComponentName defaultLauncher = mPackageManagerInternal
2367 .getHomeActivitiesAsUser(allHomeCandidates, userId);
2368 logDurationStat(Stats.GET_DEFAULT_HOME, startGetHomeActivitiesAsUser);
2369
2370 ComponentName detected = null;
2371 if (defaultLauncher != null) {
2372 detected = defaultLauncher;
2373 if (DEBUG) {
2374 Slog.v(TAG, "Default launcher from PM: " + detected);
2375 }
2376 } else {
2377 detected = user.getLastKnownLauncher();
2378
2379 if (detected != null) {
2380 if (injectIsActivityEnabledAndExported(detected, userId)) {
2381 if (DEBUG) {
2382 Slog.v(TAG, "Cached launcher: " + detected);
2383 }
2384 } else {
2385 Slog.w(TAG, "Cached launcher " + detected + " no longer exists");
2386 detected = null;
2387 user.clearLauncher();
2388 }
2389 }
2390 }
2391
2392 if (detected == null) {
2393 // If we reach here, that means it's the first check since the user was created,
2394 // and there's already multiple launchers and there's no default set.
2395 // Find the system one with the highest priority.
2396 // (We need to check the priority too because of FallbackHome in Settings.)
2397 // If there's no system launcher yet, then no one can access shortcuts, until
2398 // the user explicitly
2399 final int size = allHomeCandidates.size();
2400
2401 int lastPriority = Integer.MIN_VALUE;
2402 for (int i = 0; i < size; i++) {
2403 final ResolveInfo ri = allHomeCandidates.get(i);
2404 if (!ri.activityInfo.applicationInfo.isSystemApp()) {
2405 continue;
2406 }
2407 if (DEBUG) {
2408 Slog.d(TAG, String.format("hasShortcutPermissionInner: pkg=%s prio=%d",
2409 ri.activityInfo.getComponentName(), ri.priority));
2410 }
2411 if (ri.priority < lastPriority) {
2412 continue;
2413 }
2414 detected = ri.activityInfo.getComponentName();
2415 lastPriority = ri.priority;
2416 }
2417 }
2418 return detected;
2419 }
2420 } finally {
2421 injectRestoreCallingIdentity(token);
2422 logDurationStat(Stats.GET_DEFAULT_LAUNCHER, start);
2423 }
2424 }
2425
Dianne Hackbornc160fa42017-11-01 16:14:26 -07002426 public void setShortcutHostPackage(@NonNull String type, @Nullable String packageName,
2427 int userId) {
2428 synchronized (mLock) {
Makoto Onuki708703b2017-12-11 16:38:11 -08002429 getNonPersistentUserLocked(userId).setShortcutHostPackage(type, packageName);
Dianne Hackbornc160fa42017-11-01 16:14:26 -07002430 }
2431 }
2432
Makoto Onukicdc78f72016-03-21 15:47:52 -07002433 // === House keeping ===
2434
Makoto Onukib08790c2016-06-23 14:05:46 -07002435 private void cleanUpPackageForAllLoadedUsers(String packageName, @UserIdInt int packageUserId,
2436 boolean appStillExists) {
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002437 synchronized (mLock) {
2438 forEachLoadedUserLocked(user ->
Makoto Onukib08790c2016-06-23 14:05:46 -07002439 cleanUpPackageLocked(packageName, user.getUserId(), packageUserId,
2440 appStillExists));
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002441 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002442 }
2443
Makoto Onuki2e210c42016-03-30 08:30:36 -07002444 /**
2445 * Remove all the information associated with a package. This will really remove all the
2446 * information, including the restore information (i.e. it'll remove packages even if they're
2447 * shadow).
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002448 *
2449 * This is called when an app is uninstalled, or an app gets "clear data"ed.
Makoto Onuki2e210c42016-03-30 08:30:36 -07002450 */
Andreas Gampea36dc622018-02-05 17:19:22 -08002451 @GuardedBy("mLock")
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002452 @VisibleForTesting
Makoto Onukib08790c2016-06-23 14:05:46 -07002453 void cleanUpPackageLocked(String packageName, int owningUserId, int packageUserId,
2454 boolean appStillExists) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002455 final boolean wasUserLoaded = isUserLoadedLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002456
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002457 final ShortcutUser user = getUserShortcutsLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002458 boolean doNotify = false;
2459
2460 // First, remove the package from the package list (if the package is a publisher).
Makoto Onukid99c6f02016-03-28 11:02:54 -07002461 if (packageUserId == owningUserId) {
Makoto Onukic51b2872016-05-04 15:24:50 -07002462 if (user.removePackage(packageName) != null) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002463 doNotify = true;
2464 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07002465 }
Makoto Onukid99c6f02016-03-28 11:02:54 -07002466
Makoto Onukicdc78f72016-03-21 15:47:52 -07002467 // Also remove from the launcher list (if the package is a launcher).
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002468 user.removeLauncher(packageUserId, packageName);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002469
2470 // Then remove pinned shortcuts from all launchers.
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002471 user.forAllLaunchers(l -> l.cleanUpPackage(packageName, packageUserId));
2472
2473 // Now there may be orphan shortcuts because we removed pinned shortcuts at the previous
Makoto Onukicdc78f72016-03-21 15:47:52 -07002474 // step. Remove them too.
Makoto Onukic51b2872016-05-04 15:24:50 -07002475 user.forAllPackages(p -> p.refreshPinnedFlags());
Makoto Onukicdc78f72016-03-21 15:47:52 -07002476
Makoto Onukid99c6f02016-03-28 11:02:54 -07002477 scheduleSaveUser(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002478
2479 if (doNotify) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002480 notifyListeners(packageName, owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002481 }
2482
Makoto Onukib08790c2016-06-23 14:05:46 -07002483 // If the app still exists (i.e. data cleared), we need to re-publish manifest shortcuts.
2484 if (appStillExists && (packageUserId == owningUserId)) {
2485 // This will do the notification and save when needed, so do it after the above
2486 // notifyListeners.
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002487 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07002488 }
2489
Makoto Onukicdc78f72016-03-21 15:47:52 -07002490 if (!wasUserLoaded) {
2491 // Note this will execute the scheduled save.
Makoto Onukid99c6f02016-03-28 11:02:54 -07002492 unloadUserLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002493 }
2494 }
2495
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002496 /**
2497 * Entry point from {@link LauncherApps}.
2498 */
2499 private class LocalService extends ShortcutServiceInternal {
Makoto Onuki2e210c42016-03-30 08:30:36 -07002500
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002501 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002502 public List<ShortcutInfo> getShortcuts(int launcherUserId,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002503 @NonNull String callingPackage, long changedSince,
Makoto Onukiabe84422016-04-07 09:41:19 -07002504 @Nullable String packageName, @Nullable List<String> shortcutIds,
Makoto Onuki99302b52017-03-29 12:42:26 -07002505 @Nullable ComponentName componentName,
Makoto Onuki634cecb2017-10-13 17:10:48 -07002506 int queryFlags, int userId, int callingPid, int callingUid) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002507 final ArrayList<ShortcutInfo> ret = new ArrayList<>();
Makoto Onuki9c850012016-07-26 15:50:50 -07002508
Makoto Onuki20c95f82016-05-11 16:51:01 -07002509 final boolean cloneKeyFieldOnly =
2510 ((queryFlags & ShortcutQuery.FLAG_GET_KEY_FIELDS_ONLY) != 0);
2511 final int cloneFlag = cloneKeyFieldOnly ? ShortcutInfo.CLONE_REMOVE_NON_KEY_INFO
2512 : ShortcutInfo.CLONE_REMOVE_FOR_LAUNCHER;
Makoto Onukiabe84422016-04-07 09:41:19 -07002513 if (packageName == null) {
2514 shortcutIds = null; // LauncherAppsService already threw for it though.
2515 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002516
2517 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002518 throwIfUserLockedL(userId);
2519 throwIfUserLockedL(launcherUserId);
2520
Makoto Onuki2e210c42016-03-30 08:30:36 -07002521 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002522 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002523
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002524 if (packageName != null) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002525 getShortcutsInnerLocked(launcherUserId,
Makoto Onukiabe84422016-04-07 09:41:19 -07002526 callingPackage, packageName, shortcutIds, changedSince,
Makoto Onuki634cecb2017-10-13 17:10:48 -07002527 componentName, queryFlags, userId, ret, cloneFlag,
2528 callingPid, callingUid);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002529 } else {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002530 final List<String> shortcutIdsF = shortcutIds;
2531 getUserShortcutsLocked(userId).forAllPackages(p -> {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002532 getShortcutsInnerLocked(launcherUserId,
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002533 callingPackage, p.getPackageName(), shortcutIdsF, changedSince,
Makoto Onuki634cecb2017-10-13 17:10:48 -07002534 componentName, queryFlags, userId, ret, cloneFlag,
2535 callingPid, callingUid);
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002536 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002537 }
2538 }
Makoto Onukibf563b62017-05-04 10:25:30 -07002539 return setReturnedByServer(ret);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002540 }
2541
Andreas Gampea36dc622018-02-05 17:19:22 -08002542 @GuardedBy("ShortcutService.this.mLock")
Makoto Onukid99c6f02016-03-28 11:02:54 -07002543 private void getShortcutsInnerLocked(int launcherUserId, @NonNull String callingPackage,
Makoto Onukiabe84422016-04-07 09:41:19 -07002544 @Nullable String packageName, @Nullable List<String> shortcutIds, long changedSince,
Makoto Onuki99302b52017-03-29 12:42:26 -07002545 @Nullable ComponentName componentName, int queryFlags,
Makoto Onuki634cecb2017-10-13 17:10:48 -07002546 int userId, ArrayList<ShortcutInfo> ret, int cloneFlag,
2547 int callingPid, int callingUid) {
Makoto Onukiabe84422016-04-07 09:41:19 -07002548 final ArraySet<String> ids = shortcutIds == null ? null
2549 : new ArraySet<>(shortcutIds);
2550
Makoto Onuki35559d62017-11-06 16:26:32 -08002551 final ShortcutUser user = getUserShortcutsLocked(userId);
2552 final ShortcutPackage p = user.getPackageShortcutsIfExists(packageName);
Makoto Onukic51b2872016-05-04 15:24:50 -07002553 if (p == null) {
2554 return; // No need to instantiate ShortcutPackage.
2555 }
Makoto Onuki634cecb2017-10-13 17:10:48 -07002556 final boolean matchDynamic = (queryFlags & ShortcutQuery.FLAG_MATCH_DYNAMIC) != 0;
2557 final boolean matchPinned = (queryFlags & ShortcutQuery.FLAG_MATCH_PINNED) != 0;
2558 final boolean matchManifest = (queryFlags & ShortcutQuery.FLAG_MATCH_MANIFEST) != 0;
2559
Makoto Onuki35559d62017-11-06 16:26:32 -08002560 final boolean canAccessAllShortcuts =
2561 canSeeAnyPinnedShortcut(callingPackage, launcherUserId, callingPid, callingUid);
2562
Makoto Onuki634cecb2017-10-13 17:10:48 -07002563 final boolean getPinnedByAnyLauncher =
Makoto Onuki35559d62017-11-06 16:26:32 -08002564 canAccessAllShortcuts &&
2565 ((queryFlags & ShortcutQuery.FLAG_MATCH_PINNED_BY_ANY_LAUNCHER) != 0);
Makoto Onukic51b2872016-05-04 15:24:50 -07002566
2567 p.findAll(ret,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002568 (ShortcutInfo si) -> {
2569 if (si.getLastChangedTimestamp() < changedSince) {
2570 return false;
2571 }
Makoto Onukiabe84422016-04-07 09:41:19 -07002572 if (ids != null && !ids.contains(si.getId())) {
2573 return false;
2574 }
Makoto Onuki85694522016-05-04 12:53:37 -07002575 if (componentName != null) {
Makoto Onuki9fd90192017-01-06 18:31:03 +00002576 if (si.getActivity() != null
2577 && !si.getActivity().equals(componentName)) {
Makoto Onuki85694522016-05-04 12:53:37 -07002578 return false;
2579 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002580 }
Makoto Onuki634cecb2017-10-13 17:10:48 -07002581 if (matchDynamic && si.isDynamic()) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002582 return true;
2583 }
Makoto Onuki35559d62017-11-06 16:26:32 -08002584 if ((matchPinned || getPinnedByAnyLauncher) && si.isPinned()) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002585 return true;
2586 }
Makoto Onuki634cecb2017-10-13 17:10:48 -07002587 if (matchManifest && si.isDeclaredInManifest()) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002588 return true;
2589 }
2590 return false;
Makoto Onuki634cecb2017-10-13 17:10:48 -07002591 }, cloneFlag, callingPackage, launcherUserId, getPinnedByAnyLauncher);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002592 }
2593
2594 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002595 public boolean isPinnedByCaller(int launcherUserId, @NonNull String callingPackage,
2596 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2597 Preconditions.checkStringNotEmpty(packageName, "packageName");
2598 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
2599
2600 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002601 throwIfUserLockedL(userId);
2602 throwIfUserLockedL(launcherUserId);
2603
Makoto Onuki2e210c42016-03-30 08:30:36 -07002604 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002605 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002606
Makoto Onukid99c6f02016-03-28 11:02:54 -07002607 final ShortcutInfo si = getShortcutInfoLocked(
Makoto Onuki634cecb2017-10-13 17:10:48 -07002608 launcherUserId, callingPackage, packageName, shortcutId, userId,
2609 /*getPinnedByAnyLauncher=*/ false);
Makoto Onukid99c6f02016-03-28 11:02:54 -07002610 return si != null && si.isPinned();
2611 }
2612 }
2613
Andreas Gampea36dc622018-02-05 17:19:22 -08002614 @GuardedBy("ShortcutService.this.mLock")
Makoto Onuki2e210c42016-03-30 08:30:36 -07002615 private ShortcutInfo getShortcutInfoLocked(
Makoto Onukid99c6f02016-03-28 11:02:54 -07002616 int launcherUserId, @NonNull String callingPackage,
Makoto Onuki634cecb2017-10-13 17:10:48 -07002617 @NonNull String packageName, @NonNull String shortcutId, int userId,
2618 boolean getPinnedByAnyLauncher) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002619 Preconditions.checkStringNotEmpty(packageName, "packageName");
2620 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
2621
Makoto Onuki02f338e2016-07-29 09:40:40 -07002622 throwIfUserLockedL(userId);
2623 throwIfUserLockedL(launcherUserId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002624
Makoto Onukic51b2872016-05-04 15:24:50 -07002625 final ShortcutPackage p = getUserShortcutsLocked(userId)
2626 .getPackageShortcutsIfExists(packageName);
2627 if (p == null) {
2628 return null;
2629 }
2630
Makoto Onukid99c6f02016-03-28 11:02:54 -07002631 final ArrayList<ShortcutInfo> list = new ArrayList<>(1);
Makoto Onukic51b2872016-05-04 15:24:50 -07002632 p.findAll(list,
Makoto Onukid99c6f02016-03-28 11:02:54 -07002633 (ShortcutInfo si) -> shortcutId.equals(si.getId()),
Makoto Onuki634cecb2017-10-13 17:10:48 -07002634 /* clone flags=*/ 0, callingPackage, launcherUserId, getPinnedByAnyLauncher);
Makoto Onukid99c6f02016-03-28 11:02:54 -07002635 return list.size() == 0 ? null : list.get(0);
2636 }
2637
2638 @Override
2639 public void pinShortcuts(int launcherUserId,
2640 @NonNull String callingPackage, @NonNull String packageName,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002641 @NonNull List<String> shortcutIds, int userId) {
2642 // Calling permission must be checked by LauncherAppsImpl.
2643 Preconditions.checkStringNotEmpty(packageName, "packageName");
2644 Preconditions.checkNotNull(shortcutIds, "shortcutIds");
2645
2646 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002647 throwIfUserLockedL(userId);
2648 throwIfUserLockedL(launcherUserId);
2649
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002650 final ShortcutLauncher launcher =
Makoto Onuki2e210c42016-03-30 08:30:36 -07002651 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId);
Makoto Onukic51b2872016-05-04 15:24:50 -07002652 launcher.attemptToRestoreIfNeededAndSave();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002653
Makoto Onukia4f89b12017-10-05 10:37:55 -07002654 launcher.pinShortcuts(userId, packageName, shortcutIds, /*forPinRequest=*/ false);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002655 }
Makoto Onuki39686e82016-04-13 18:03:00 -07002656 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07002657
2658 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002659 }
2660
2661 @Override
Makoto Onuki440a1ea2016-07-20 14:21:18 -07002662 public Intent[] createShortcutIntents(int launcherUserId,
Makoto Onukid99c6f02016-03-28 11:02:54 -07002663 @NonNull String callingPackage,
Makoto Onuki634cecb2017-10-13 17:10:48 -07002664 @NonNull String packageName, @NonNull String shortcutId, int userId,
2665 int callingPid, int callingUid) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002666 // Calling permission must be checked by LauncherAppsImpl.
Makoto Onuki43204b82016-03-08 16:16:44 -08002667 Preconditions.checkStringNotEmpty(packageName, "packageName can't be empty");
2668 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId can't be empty");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002669
2670 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002671 throwIfUserLockedL(userId);
2672 throwIfUserLockedL(launcherUserId);
2673
Makoto Onuki2e210c42016-03-30 08:30:36 -07002674 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002675 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002676
Makoto Onuki634cecb2017-10-13 17:10:48 -07002677 final boolean getPinnedByAnyLauncher =
Makoto Onuki35559d62017-11-06 16:26:32 -08002678 canSeeAnyPinnedShortcut(callingPackage, launcherUserId,
2679 callingPid, callingUid);
Makoto Onuki634cecb2017-10-13 17:10:48 -07002680
Makoto Onukid99c6f02016-03-28 11:02:54 -07002681 // Make sure the shortcut is actually visible to the launcher.
2682 final ShortcutInfo si = getShortcutInfoLocked(
Makoto Onuki634cecb2017-10-13 17:10:48 -07002683 launcherUserId, callingPackage, packageName, shortcutId, userId,
2684 getPinnedByAnyLauncher);
Makoto Onukid99c6f02016-03-28 11:02:54 -07002685 // "si == null" should suffice here, but check the flags too just to make sure.
Makoto Onuki35559d62017-11-06 16:26:32 -08002686 if (si == null || !si.isEnabled() || !(si.isAlive() || getPinnedByAnyLauncher)) {
Makoto Onuki83f6d2d2016-07-11 14:30:19 -07002687 Log.e(TAG, "Shortcut " + shortcutId + " does not exist or disabled");
Makoto Onukid99c6f02016-03-28 11:02:54 -07002688 return null;
2689 }
Makoto Onuki440a1ea2016-07-20 14:21:18 -07002690 return si.getIntents();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002691 }
2692 }
2693
2694 @Override
2695 public void addListener(@NonNull ShortcutChangeListener listener) {
2696 synchronized (mLock) {
2697 mListeners.add(Preconditions.checkNotNull(listener));
2698 }
2699 }
Makoto Onuki55046222016-03-08 10:49:47 -08002700
2701 @Override
Makoto Onukiabe84422016-04-07 09:41:19 -07002702 public int getShortcutIconResId(int launcherUserId, @NonNull String callingPackage,
2703 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2704 Preconditions.checkNotNull(callingPackage, "callingPackage");
2705 Preconditions.checkNotNull(packageName, "packageName");
2706 Preconditions.checkNotNull(shortcutId, "shortcutId");
Makoto Onuki55046222016-03-08 10:49:47 -08002707
2708 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002709 throwIfUserLockedL(userId);
2710 throwIfUserLockedL(launcherUserId);
2711
Makoto Onuki2e210c42016-03-30 08:30:36 -07002712 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002713 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002714
Makoto Onukic51b2872016-05-04 15:24:50 -07002715 final ShortcutPackage p = getUserShortcutsLocked(userId)
2716 .getPackageShortcutsIfExists(packageName);
2717 if (p == null) {
2718 return 0;
2719 }
2720
2721 final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId);
Makoto Onuki55046222016-03-08 10:49:47 -08002722 return (shortcutInfo != null && shortcutInfo.hasIconResource())
2723 ? shortcutInfo.getIconResourceId() : 0;
2724 }
2725 }
2726
2727 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002728 public ParcelFileDescriptor getShortcutIconFd(int launcherUserId,
Makoto Onukiabe84422016-04-07 09:41:19 -07002729 @NonNull String callingPackage, @NonNull String packageName,
2730 @NonNull String shortcutId, int userId) {
2731 Preconditions.checkNotNull(callingPackage, "callingPackage");
2732 Preconditions.checkNotNull(packageName, "packageName");
2733 Preconditions.checkNotNull(shortcutId, "shortcutId");
Makoto Onuki55046222016-03-08 10:49:47 -08002734
2735 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002736 throwIfUserLockedL(userId);
2737 throwIfUserLockedL(launcherUserId);
2738
Makoto Onuki2e210c42016-03-30 08:30:36 -07002739 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002740 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002741
Makoto Onukic51b2872016-05-04 15:24:50 -07002742 final ShortcutPackage p = getUserShortcutsLocked(userId)
2743 .getPackageShortcutsIfExists(packageName);
2744 if (p == null) {
2745 return null;
2746 }
2747
2748 final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId);
Makoto Onuki55046222016-03-08 10:49:47 -08002749 if (shortcutInfo == null || !shortcutInfo.hasIconFile()) {
2750 return null;
2751 }
Makoto Onuki475c3652017-05-08 14:29:03 -07002752 final String path = mShortcutBitmapSaver.getBitmapPathMayWaitLocked(shortcutInfo);
2753 if (path == null) {
2754 Slog.w(TAG, "null bitmap detected in getShortcutIconFd()");
2755 return null;
2756 }
Makoto Onuki55046222016-03-08 10:49:47 -08002757 try {
2758 return ParcelFileDescriptor.open(
Makoto Onuki475c3652017-05-08 14:29:03 -07002759 new File(path),
Makoto Onuki55046222016-03-08 10:49:47 -08002760 ParcelFileDescriptor.MODE_READ_ONLY);
2761 } catch (FileNotFoundException e) {
Makoto Onuki475c3652017-05-08 14:29:03 -07002762 Slog.e(TAG, "Icon file not found: " + path);
Makoto Onuki55046222016-03-08 10:49:47 -08002763 return null;
2764 }
2765 }
2766 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002767
2768 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002769 public boolean hasShortcutHostPermission(int launcherUserId,
Makoto Onuki634cecb2017-10-13 17:10:48 -07002770 @NonNull String callingPackage, int callingPid, int callingUid) {
2771 return ShortcutService.this.hasShortcutHostPermission(callingPackage, launcherUserId,
2772 callingPid, callingUid);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002773 }
Sunny Goyal87a563e2017-01-01 19:42:45 -08002774
2775 @Override
Dianne Hackbornc160fa42017-11-01 16:14:26 -07002776 public void setShortcutHostPackage(@NonNull String type, @Nullable String packageName,
2777 int userId) {
2778 ShortcutService.this.setShortcutHostPackage(type, packageName, userId);
2779 }
2780
2781 @Override
Sunny Goyal87a563e2017-01-01 19:42:45 -08002782 public boolean requestPinAppWidget(@NonNull String callingPackage,
Sunny Goyal4ad6b572017-02-28 11:11:51 -08002783 @NonNull AppWidgetProviderInfo appWidget, @Nullable Bundle extras,
2784 @Nullable IntentSender resultIntent, int userId) {
Sunny Goyal87a563e2017-01-01 19:42:45 -08002785 Preconditions.checkNotNull(appWidget);
Sunny Goyal4ad6b572017-02-28 11:11:51 -08002786 return requestPinItem(callingPackage, userId, null, appWidget, extras, resultIntent);
Sunny Goyal87a563e2017-01-01 19:42:45 -08002787 }
Sunny Goyal7f7372a2017-01-24 11:53:54 -08002788
2789 @Override
2790 public boolean isRequestPinItemSupported(int callingUserId, int requestType) {
2791 return ShortcutService.this.isRequestPinItemSupported(callingUserId, requestType);
2792 }
Tony Maked6ef622017-12-07 16:36:16 +00002793
2794 @Override
2795 public boolean isForegroundDefaultLauncher(@NonNull String callingPackage, int callingUid) {
2796 Preconditions.checkNotNull(callingPackage);
2797
2798 final int userId = UserHandle.getUserId(callingUid);
2799 final ComponentName defaultLauncher = getDefaultLauncher(userId);
2800 if (defaultLauncher == null) {
2801 return false;
2802 }
2803 if (!callingPackage.equals(defaultLauncher.getPackageName())) {
2804 return false;
2805 }
2806 synchronized (mLock) {
2807 if (!isUidForegroundLocked(callingUid)) {
2808 return false;
2809 }
2810 }
2811 return true;
2812 }
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002813 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002814
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002815 final BroadcastReceiver mReceiver = new BroadcastReceiver() {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002816 @Override
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002817 public void onReceive(Context context, Intent intent) {
2818 if (!mBootCompleted.get()) {
2819 return; // Boot not completed, ignore the broadcast.
2820 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07002821 try {
2822 if (Intent.ACTION_LOCALE_CHANGED.equals(intent.getAction())) {
2823 handleLocaleChanged();
2824 }
2825 } catch (Exception e) {
2826 wtf("Exception in mReceiver.onReceive", e);
Makoto Onukic51b2872016-05-04 15:24:50 -07002827 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002828 }
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002829 };
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002830
Makoto Onuki157b1622016-06-02 16:13:10 -07002831 void handleLocaleChanged() {
2832 if (DEBUG) {
2833 Slog.d(TAG, "handleLocaleChanged");
2834 }
2835 scheduleSaveBaseState();
2836
Makoto Onuki02f338e2016-07-29 09:40:40 -07002837 synchronized (mLock) {
2838 final long token = injectClearCallingIdentity();
2839 try {
2840 forEachLoadedUserLocked(user -> user.detectLocaleChange());
2841 } finally {
2842 injectRestoreCallingIdentity(token);
2843 }
Makoto Onuki157b1622016-06-02 16:13:10 -07002844 }
2845 }
2846
Makoto Onukif34c3082016-07-13 10:25:25 -07002847 /**
2848 * Package event callbacks.
2849 */
2850 @VisibleForTesting
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002851 final BroadcastReceiver mPackageMonitor = new BroadcastReceiver() {
Makoto Onukif34c3082016-07-13 10:25:25 -07002852 @Override
2853 public void onReceive(Context context, Intent intent) {
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002854 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
2855 if (userId == UserHandle.USER_NULL) {
2856 Slog.w(TAG, "Intent broadcast does not contain user handle: " + intent);
2857 return;
2858 }
2859
2860 final String action = intent.getAction();
2861
2862 // This is normally called on Handler, so clearCallingIdentity() isn't needed,
2863 // but we still check it in unit tests.
Makoto Onukif34c3082016-07-13 10:25:25 -07002864 final long token = injectClearCallingIdentity();
2865 try {
Makoto Onuki10305202016-07-14 18:14:08 -07002866 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002867 if (!isUserUnlockedL(userId)) {
2868 if (DEBUG) {
2869 Slog.d(TAG, "Ignoring package broadcast " + action
2870 + " for locked/stopped user " + userId);
2871 }
2872 return;
2873 }
2874
2875 // Whenever we get one of those package broadcasts, or get
2876 // ACTION_PREFERRED_ACTIVITY_CHANGED, we purge the default launcher cache.
Makoto Onuki10305202016-07-14 18:14:08 -07002877 final ShortcutUser user = getUserShortcutsLocked(userId);
2878 user.clearLauncher();
2879 }
2880 if (Intent.ACTION_PREFERRED_ACTIVITY_CHANGED.equals(action)) {
2881 // Nothing farther to do.
2882 return;
2883 }
2884
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002885 final Uri intentUri = intent.getData();
2886 final String packageName = (intentUri != null) ? intentUri.getSchemeSpecificPart()
2887 : null;
2888 if (packageName == null) {
2889 Slog.w(TAG, "Intent broadcast does not contain package name: " + intent);
2890 return;
2891 }
2892
2893 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
2894
2895 switch (action) {
2896 case Intent.ACTION_PACKAGE_ADDED:
2897 if (replacing) {
2898 handlePackageUpdateFinished(packageName, userId);
2899 } else {
2900 handlePackageAdded(packageName, userId);
2901 }
2902 break;
2903 case Intent.ACTION_PACKAGE_REMOVED:
2904 if (!replacing) {
2905 handlePackageRemoved(packageName, userId);
2906 }
2907 break;
2908 case Intent.ACTION_PACKAGE_CHANGED:
2909 handlePackageChanged(packageName, userId);
2910
2911 break;
2912 case Intent.ACTION_PACKAGE_DATA_CLEARED:
2913 handlePackageDataCleared(packageName, userId);
2914 break;
2915 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07002916 } catch (Exception e) {
2917 wtf("Exception in mPackageMonitor.onReceive", e);
Makoto Onukif34c3082016-07-13 10:25:25 -07002918 } finally {
2919 injectRestoreCallingIdentity(token);
Makoto Onukia2241832016-07-06 13:28:37 -07002920 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07002921 }
Makoto Onukif34c3082016-07-13 10:25:25 -07002922 };
Makoto Onukicdc78f72016-03-21 15:47:52 -07002923
Makoto Onuki0acbb142016-03-22 17:02:57 -07002924 /**
Makoto Onuki39686e82016-04-13 18:03:00 -07002925 * Called when a user is unlocked.
2926 * - Check all known packages still exist, and otherwise perform cleanup.
2927 * - If a package still exists, check the version code. If it's been updated, may need to
Makoto Onukib08790c2016-06-23 14:05:46 -07002928 * update timestamps of its shortcuts.
Makoto Onuki0acbb142016-03-22 17:02:57 -07002929 */
Makoto Onukid99c6f02016-03-28 11:02:54 -07002930 @VisibleForTesting
Makoto Onuki39686e82016-04-13 18:03:00 -07002931 void checkPackageChanges(@UserIdInt int ownerUserId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07002932 if (DEBUG) {
Makoto Onuki39686e82016-04-13 18:03:00 -07002933 Slog.d(TAG, "checkPackageChanges() ownerUserId=" + ownerUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002934 }
Makoto Onukib08790c2016-06-23 14:05:46 -07002935 if (injectIsSafeModeEnabled()) {
2936 Slog.i(TAG, "Safe mode, skipping checkPackageChanges()");
2937 return;
2938 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07002939
Makoto Onuki84d59342018-02-02 09:22:38 -08002940 final long start = getStatStartTime();
Makoto Onuki22fcc682016-05-17 14:52:19 -07002941 try {
2942 final ArrayList<PackageWithUser> gonePackages = new ArrayList<>();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002943
Makoto Onuki22fcc682016-05-17 14:52:19 -07002944 synchronized (mLock) {
2945 final ShortcutUser user = getUserShortcutsLocked(ownerUserId);
2946
2947 // Find packages that have been uninstalled.
2948 user.forAllPackageItems(spi -> {
2949 if (spi.getPackageInfo().isShadow()) {
2950 return; // Don't delete shadow information.
2951 }
2952 if (!isPackageInstalled(spi.getPackageName(), spi.getPackageUserId())) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002953 if (DEBUG) {
2954 Slog.d(TAG, "Uninstalled: " + spi.getPackageName()
2955 + " user " + spi.getPackageUserId());
2956 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002957 gonePackages.add(PackageWithUser.of(spi));
2958 }
2959 });
2960 if (gonePackages.size() > 0) {
2961 for (int i = gonePackages.size() - 1; i >= 0; i--) {
2962 final PackageWithUser pu = gonePackages.get(i);
Makoto Onukib08790c2016-06-23 14:05:46 -07002963 cleanUpPackageLocked(pu.packageName, ownerUserId, pu.userId,
2964 /* appStillExists = */ false);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002965 }
Makoto Onukid99c6f02016-03-28 11:02:54 -07002966 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002967
Makoto Onuki248a0ef2016-11-03 15:59:01 -07002968 rescanUpdatedPackagesLocked(ownerUserId, user.getLastAppScanTime());
Makoto Onuki0acbb142016-03-22 17:02:57 -07002969 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002970 } finally {
2971 logDurationStat(Stats.CHECK_PACKAGE_CHANGES, start);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002972 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002973 verifyStates();
Makoto Onukicdc78f72016-03-21 15:47:52 -07002974 }
2975
Andreas Gampea36dc622018-02-05 17:19:22 -08002976 @GuardedBy("mLock")
Makoto Onuki248a0ef2016-11-03 15:59:01 -07002977 private void rescanUpdatedPackagesLocked(@UserIdInt int userId, long lastScanTime) {
Makoto Onuki377b7972016-08-09 14:43:55 -07002978 final ShortcutUser user = getUserShortcutsLocked(userId);
2979
Makoto Onuki33663282016-08-22 16:19:04 -07002980 // Note after each OTA, we'll need to rescan all system apps, as their lastUpdateTime
2981 // is not reliable.
Makoto Onuki377b7972016-08-09 14:43:55 -07002982 final long now = injectCurrentTimeMillis();
Makoto Onuki33663282016-08-22 16:19:04 -07002983 final boolean afterOta =
2984 !injectBuildFingerprint().equals(user.getLastAppScanOsFingerprint());
Makoto Onuki377b7972016-08-09 14:43:55 -07002985
2986 // Then for each installed app, publish manifest shortcuts when needed.
Makoto Onuki33663282016-08-22 16:19:04 -07002987 forUpdatedPackages(userId, lastScanTime, afterOta, ai -> {
Makoto Onuki377b7972016-08-09 14:43:55 -07002988 user.attemptToRestoreIfNeededAndSave(this, ai.packageName, userId);
Makoto Onuki248a0ef2016-11-03 15:59:01 -07002989
2990 user.rescanPackageIfNeeded(ai.packageName, /* forceRescan= */ true);
Makoto Onuki377b7972016-08-09 14:43:55 -07002991 });
2992
2993 // Write the time just before the scan, because there may be apps that have just
2994 // been updated, and we want to catch them in the next time.
2995 user.setLastAppScanTime(now);
Makoto Onuki33663282016-08-22 16:19:04 -07002996 user.setLastAppScanOsFingerprint(injectBuildFingerprint());
Makoto Onuki377b7972016-08-09 14:43:55 -07002997 scheduleSaveUser(userId);
2998 }
2999
Makoto Onuki0acbb142016-03-22 17:02:57 -07003000 private void handlePackageAdded(String packageName, @UserIdInt int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07003001 if (DEBUG) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07003002 Slog.d(TAG, String.format("handlePackageAdded: %s user=%d", packageName, userId));
3003 }
3004 synchronized (mLock) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07003005 final ShortcutUser user = getUserShortcutsLocked(userId);
3006 user.attemptToRestoreIfNeededAndSave(this, packageName, userId);
Makoto Onuki64183d52016-08-08 14:11:34 -07003007 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onuki0acbb142016-03-22 17:02:57 -07003008 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07003009 verifyStates();
Makoto Onuki0acbb142016-03-22 17:02:57 -07003010 }
3011
3012 private void handlePackageUpdateFinished(String packageName, @UserIdInt int userId) {
Makoto Onuki905e8852016-03-28 10:40:58 -07003013 if (DEBUG) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003014 Slog.d(TAG, String.format("handlePackageUpdateFinished: %s user=%d",
3015 packageName, userId));
Makoto Onuki0acbb142016-03-22 17:02:57 -07003016 }
3017 synchronized (mLock) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07003018 final ShortcutUser user = getUserShortcutsLocked(userId);
3019 user.attemptToRestoreIfNeededAndSave(this, packageName, userId);
Makoto Onuki39686e82016-04-13 18:03:00 -07003020
Makoto Onuki22fcc682016-05-17 14:52:19 -07003021 if (isPackageInstalled(packageName, userId)) {
Makoto Onuki64183d52016-08-08 14:11:34 -07003022 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onuki39686e82016-04-13 18:03:00 -07003023 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07003024 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07003025 verifyStates();
Makoto Onuki0acbb142016-03-22 17:02:57 -07003026 }
3027
Makoto Onuki2e210c42016-03-30 08:30:36 -07003028 private void handlePackageRemoved(String packageName, @UserIdInt int packageUserId) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07003029 if (DEBUG) {
Makoto Onuki2e210c42016-03-30 08:30:36 -07003030 Slog.d(TAG, String.format("handlePackageRemoved: %s user=%d", packageName,
3031 packageUserId));
Makoto Onukicdc78f72016-03-21 15:47:52 -07003032 }
Makoto Onukib08790c2016-06-23 14:05:46 -07003033 cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ false);
Makoto Onuki9e1f5592016-06-08 12:30:23 -07003034
3035 verifyStates();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003036 }
3037
Makoto Onuki9ac59d02016-04-26 11:23:14 -07003038 private void handlePackageDataCleared(String packageName, int packageUserId) {
3039 if (DEBUG) {
3040 Slog.d(TAG, String.format("handlePackageDataCleared: %s user=%d", packageName,
3041 packageUserId));
Makoto Onukicdc78f72016-03-21 15:47:52 -07003042 }
Makoto Onukib08790c2016-06-23 14:05:46 -07003043 cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ true);
3044
3045 verifyStates();
3046 }
3047
3048 private void handlePackageChanged(String packageName, int packageUserId) {
Makoto Onuki82fb2eb2017-03-31 16:58:26 -07003049 if (!isPackageInstalled(packageName, packageUserId)) {
3050 // Probably disabled, which is the same thing as uninstalled.
3051 handlePackageRemoved(packageName, packageUserId);
3052 return;
3053 }
Makoto Onukib08790c2016-06-23 14:05:46 -07003054 if (DEBUG) {
3055 Slog.d(TAG, String.format("handlePackageChanged: %s user=%d", packageName,
3056 packageUserId));
3057 }
3058
3059 // Activities may be disabled or enabled. Just rescan the package.
3060 synchronized (mLock) {
3061 final ShortcutUser user = getUserShortcutsLocked(packageUserId);
3062
Makoto Onuki4e6cef42016-07-13 16:14:01 -07003063 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07003064 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07003065
3066 verifyStates();
Makoto Onukicdc78f72016-03-21 15:47:52 -07003067 }
3068
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003069 // === PackageManager interaction ===
Makoto Onuki0acbb142016-03-22 17:02:57 -07003070
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003071 /**
3072 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
3073 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07003074 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003075 final PackageInfo getPackageInfoWithSignatures(String packageName, @UserIdInt int userId) {
3076 return getPackageInfo(packageName, userId, true);
Makoto Onuki0acbb142016-03-22 17:02:57 -07003077 }
3078
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003079 /**
3080 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
3081 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07003082 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003083 final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId) {
3084 return getPackageInfo(packageName, userId, false);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003085 }
3086
Makoto Onuki905e8852016-03-28 10:40:58 -07003087 int injectGetPackageUid(@NonNull String packageName, @UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003088 final long token = injectClearCallingIdentity();
Makoto Onuki905e8852016-03-28 10:40:58 -07003089 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003090 return mIPackageManager.getPackageUid(packageName, PACKAGE_MATCH_FLAGS, userId);
Makoto Onuki905e8852016-03-28 10:40:58 -07003091 } catch (RemoteException e) {
3092 // Shouldn't happen.
3093 Slog.wtf(TAG, "RemoteException", e);
3094 return -1;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003095 } finally {
3096 injectRestoreCallingIdentity(token);
Makoto Onuki905e8852016-03-28 10:40:58 -07003097 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07003098 }
3099
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003100 /**
3101 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
3102 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07003103 @Nullable
Makoto Onuki0acbb142016-03-22 17:02:57 -07003104 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003105 final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId,
3106 boolean getSignatures) {
3107 return isInstalledOrNull(injectPackageInfoWithUninstalled(
3108 packageName, userId, getSignatures));
3109 }
3110
3111 /**
3112 * Do not use directly; this returns uninstalled packages too.
3113 */
3114 @Nullable
3115 @VisibleForTesting
3116 PackageInfo injectPackageInfoWithUninstalled(String packageName, @UserIdInt int userId,
Makoto Onuki0acbb142016-03-22 17:02:57 -07003117 boolean getSignatures) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003118 final long start = getStatStartTime();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003119 final long token = injectClearCallingIdentity();
Makoto Onuki0acbb142016-03-22 17:02:57 -07003120 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003121 return mIPackageManager.getPackageInfo(
3122 packageName, PACKAGE_MATCH_FLAGS
Michal Karpinski528c3e52018-02-07 17:47:10 +00003123 | (getSignatures ? PackageManager.GET_SIGNING_CERTIFICATES : 0),
3124 userId);
Makoto Onuki0acbb142016-03-22 17:02:57 -07003125 } catch (RemoteException e) {
3126 // Shouldn't happen.
3127 Slog.wtf(TAG, "RemoteException", e);
3128 return null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003129 } finally {
3130 injectRestoreCallingIdentity(token);
Makoto Onuki2e210c42016-03-30 08:30:36 -07003131
3132 logDurationStat(
3133 (getSignatures ? Stats.GET_PACKAGE_INFO_WITH_SIG : Stats.GET_PACKAGE_INFO),
3134 start);
Makoto Onuki0acbb142016-03-22 17:02:57 -07003135 }
3136 }
3137
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003138 /**
3139 * Returns {@link ApplicationInfo} unless it's uninstalled or disabled.
3140 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07003141 @Nullable
Makoto Onuki905e8852016-03-28 10:40:58 -07003142 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003143 final ApplicationInfo getApplicationInfo(String packageName, @UserIdInt int userId) {
3144 return isInstalledOrNull(injectApplicationInfoWithUninstalled(packageName, userId));
3145 }
3146
3147 /**
3148 * Do not use directly; this returns uninstalled packages too.
3149 */
3150 @Nullable
3151 @VisibleForTesting
3152 ApplicationInfo injectApplicationInfoWithUninstalled(
3153 String packageName, @UserIdInt int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003154 final long start = getStatStartTime();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003155 final long token = injectClearCallingIdentity();
Makoto Onuki905e8852016-03-28 10:40:58 -07003156 try {
3157 return mIPackageManager.getApplicationInfo(packageName, PACKAGE_MATCH_FLAGS, userId);
3158 } catch (RemoteException e) {
3159 // Shouldn't happen.
3160 Slog.wtf(TAG, "RemoteException", e);
3161 return null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003162 } finally {
3163 injectRestoreCallingIdentity(token);
Makoto Onuki2e210c42016-03-30 08:30:36 -07003164
3165 logDurationStat(Stats.GET_APPLICATION_INFO, start);
Makoto Onuki905e8852016-03-28 10:40:58 -07003166 }
3167 }
3168
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003169 /**
3170 * Returns {@link ActivityInfo} with its metadata unless it's uninstalled or disabled.
3171 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07003172 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003173 final ActivityInfo getActivityInfoWithMetadata(ComponentName activity, @UserIdInt int userId) {
3174 return isInstalledOrNull(injectGetActivityInfoWithMetadataWithUninstalled(
3175 activity, userId));
3176 }
3177
3178 /**
3179 * Do not use directly; this returns uninstalled packages too.
3180 */
3181 @Nullable
3182 @VisibleForTesting
3183 ActivityInfo injectGetActivityInfoWithMetadataWithUninstalled(
3184 ComponentName activity, @UserIdInt int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003185 final long start = getStatStartTime();
Makoto Onuki22fcc682016-05-17 14:52:19 -07003186 final long token = injectClearCallingIdentity();
3187 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07003188 return mIPackageManager.getActivityInfo(activity,
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003189 (PACKAGE_MATCH_FLAGS | PackageManager.GET_META_DATA), userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003190 } catch (RemoteException e) {
3191 // Shouldn't happen.
3192 Slog.wtf(TAG, "RemoteException", e);
3193 return null;
3194 } finally {
3195 injectRestoreCallingIdentity(token);
3196
Makoto Onukib08790c2016-06-23 14:05:46 -07003197 logDurationStat(Stats.GET_ACTIVITY_WITH_METADATA, start);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003198 }
3199 }
3200
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003201 /**
3202 * Return all installed and enabled packages.
3203 */
3204 @NonNull
Makoto Onuki22fcc682016-05-17 14:52:19 -07003205 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003206 final List<PackageInfo> getInstalledPackages(@UserIdInt int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003207 final long start = getStatStartTime();
Makoto Onuki22fcc682016-05-17 14:52:19 -07003208 final long token = injectClearCallingIdentity();
3209 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003210 final List<PackageInfo> all = injectGetPackagesWithUninstalled(userId);
3211
3212 all.removeIf(PACKAGE_NOT_INSTALLED);
3213
3214 return all;
Makoto Onuki22fcc682016-05-17 14:52:19 -07003215 } catch (RemoteException e) {
3216 // Shouldn't happen.
3217 Slog.wtf(TAG, "RemoteException", e);
3218 return null;
3219 } finally {
3220 injectRestoreCallingIdentity(token);
3221
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003222 logDurationStat(Stats.GET_INSTALLED_PACKAGES, start);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003223 }
3224 }
3225
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003226 /**
3227 * Do not use directly; this returns uninstalled packages too.
3228 */
3229 @NonNull
3230 @VisibleForTesting
3231 List<PackageInfo> injectGetPackagesWithUninstalled(@UserIdInt int userId)
3232 throws RemoteException {
3233 final ParceledListSlice<PackageInfo> parceledList =
3234 mIPackageManager.getInstalledPackages(PACKAGE_MATCH_FLAGS, userId);
3235 if (parceledList == null) {
3236 return Collections.emptyList();
3237 }
3238 return parceledList.getList();
3239 }
3240
Makoto Onuki33663282016-08-22 16:19:04 -07003241 private void forUpdatedPackages(@UserIdInt int userId, long lastScanTime, boolean afterOta,
Makoto Onuki22fcc682016-05-17 14:52:19 -07003242 Consumer<ApplicationInfo> callback) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003243 if (DEBUG) {
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003244 Slog.d(TAG, "forUpdatedPackages for user " + userId + ", lastScanTime=" + lastScanTime
3245 + " afterOta=" + afterOta);
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003246 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003247 final List<PackageInfo> list = getInstalledPackages(userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003248 for (int i = list.size() - 1; i >= 0; i--) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003249 final PackageInfo pi = list.get(i);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003250
Makoto Onuki64183d52016-08-08 14:11:34 -07003251 // If the package has been updated since the last scan time, then scan it.
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003252 // Also if it's right after an OTA, always re-scan all apps anyway, since the
3253 // shortcut parser might have changed.
3254 if (afterOta || (pi.lastUpdateTime >= lastScanTime)) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003255 if (DEBUG) {
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003256 Slog.d(TAG, "Found updated package " + pi.packageName
3257 + " updateTime=" + pi.lastUpdateTime);
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003258 }
3259 callback.accept(pi.applicationInfo);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003260 }
3261 }
3262 }
3263
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003264 private boolean isApplicationFlagSet(@NonNull String packageName, int userId, int flags) {
3265 final ApplicationInfo ai = injectApplicationInfoWithUninstalled(packageName, userId);
Makoto Onuki905e8852016-03-28 10:40:58 -07003266 return (ai != null) && ((ai.flags & flags) == flags);
3267 }
3268
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003269 private static boolean isInstalled(@Nullable ApplicationInfo ai) {
Makoto Onuki82fb2eb2017-03-31 16:58:26 -07003270 return (ai != null) && ai.enabled && (ai.flags & ApplicationInfo.FLAG_INSTALLED) != 0;
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003271 }
3272
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08003273 private static boolean isEphemeralApp(@Nullable ApplicationInfo ai) {
Svetoslav Ganov096d3042017-01-30 16:34:13 -08003274 return (ai != null) && ai.isInstantApp();
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08003275 }
3276
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003277 private static boolean isInstalled(@Nullable PackageInfo pi) {
3278 return (pi != null) && isInstalled(pi.applicationInfo);
3279 }
3280
3281 private static boolean isInstalled(@Nullable ActivityInfo ai) {
3282 return (ai != null) && isInstalled(ai.applicationInfo);
3283 }
3284
3285 private static ApplicationInfo isInstalledOrNull(ApplicationInfo ai) {
3286 return isInstalled(ai) ? ai : null;
3287 }
3288
3289 private static PackageInfo isInstalledOrNull(PackageInfo pi) {
3290 return isInstalled(pi) ? pi : null;
3291 }
3292
3293 private static ActivityInfo isInstalledOrNull(ActivityInfo ai) {
3294 return isInstalled(ai) ? ai : null;
3295 }
3296
Makoto Onuki2e210c42016-03-30 08:30:36 -07003297 boolean isPackageInstalled(String packageName, int userId) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003298 return getApplicationInfo(packageName, userId) != null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003299 }
3300
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08003301 boolean isEphemeralApp(String packageName, int userId) {
3302 return isEphemeralApp(getApplicationInfo(packageName, userId));
3303 }
3304
Makoto Onuki22fcc682016-05-17 14:52:19 -07003305 @Nullable
3306 XmlResourceParser injectXmlMetaData(ActivityInfo activityInfo, String key) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07003307 return activityInfo.loadXmlMetaData(mContext.getPackageManager(), key);
Makoto Onuki39686e82016-04-13 18:03:00 -07003308 }
3309
Makoto Onuki157b1622016-06-02 16:13:10 -07003310 @Nullable
3311 Resources injectGetResourcesForApplicationAsUser(String packageName, int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003312 final long start = getStatStartTime();
Makoto Onuki157b1622016-06-02 16:13:10 -07003313 final long token = injectClearCallingIdentity();
3314 try {
3315 return mContext.getPackageManager().getResourcesForApplicationAsUser(
3316 packageName, userId);
3317 } catch (NameNotFoundException e) {
3318 Slog.e(TAG, "Resources for package " + packageName + " not found");
3319 return null;
3320 } finally {
3321 injectRestoreCallingIdentity(token);
3322
3323 logDurationStat(Stats.GET_APPLICATION_RESOURCES, start);
3324 }
3325 }
3326
Makoto Onukib08790c2016-06-23 14:05:46 -07003327 private Intent getMainActivityIntent() {
3328 final Intent intent = new Intent(Intent.ACTION_MAIN);
3329 intent.addCategory(LAUNCHER_INTENT_CATEGORY);
3330 return intent;
3331 }
3332
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003333 /**
3334 * Same as queryIntentActivitiesAsUser, except it makes sure the package is installed,
3335 * and only returns exported activities.
3336 */
3337 @NonNull
3338 @VisibleForTesting
3339 List<ResolveInfo> queryActivities(@NonNull Intent baseIntent,
3340 @NonNull String packageName, @Nullable ComponentName activity, int userId) {
3341
3342 baseIntent.setPackage(Preconditions.checkNotNull(packageName));
3343 if (activity != null) {
3344 baseIntent.setComponent(activity);
3345 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08003346 return queryActivities(baseIntent, userId, /* exportedOnly =*/ true);
3347 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003348
Makoto Onuki2d895c32016-12-02 15:48:40 -08003349 @NonNull
3350 List<ResolveInfo> queryActivities(@NonNull Intent intent, int userId,
3351 boolean exportedOnly) {
3352 final List<ResolveInfo> resolved;
3353 final long token = injectClearCallingIdentity();
3354 try {
3355 resolved =
3356 mContext.getPackageManager().queryIntentActivitiesAsUser(
3357 intent, PACKAGE_MATCH_FLAGS, userId);
3358 } finally {
3359 injectRestoreCallingIdentity(token);
3360 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003361 if (resolved == null || resolved.size() == 0) {
3362 return EMPTY_RESOLVE_INFO;
3363 }
3364 // Make sure the package is installed.
3365 if (!isInstalled(resolved.get(0).activityInfo)) {
3366 return EMPTY_RESOLVE_INFO;
3367 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08003368 if (exportedOnly) {
3369 resolved.removeIf(ACTIVITY_NOT_EXPORTED);
3370 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003371 return resolved;
3372 }
3373
3374 /**
3375 * Return the main activity that is enabled and exported. If multiple activities are found,
3376 * return the first one.
3377 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003378 @Nullable
3379 ComponentName injectGetDefaultMainActivity(@NonNull String packageName, int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003380 final long start = getStatStartTime();
Makoto Onukib08790c2016-06-23 14:05:46 -07003381 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07003382 final List<ResolveInfo> resolved =
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003383 queryActivities(getMainActivityIntent(), packageName, null, userId);
3384 return resolved.size() == 0 ? null : resolved.get(0).activityInfo.getComponentName();
Makoto Onukib08790c2016-06-23 14:05:46 -07003385 } finally {
Makoto Onukib08790c2016-06-23 14:05:46 -07003386 logDurationStat(Stats.GET_LAUNCHER_ACTIVITY, start);
3387 }
3388 }
3389
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003390 /**
3391 * Return whether an activity is enabled, exported and main.
3392 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003393 boolean injectIsMainActivity(@NonNull ComponentName activity, int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003394 final long start = getStatStartTime();
Makoto Onukib08790c2016-06-23 14:05:46 -07003395 try {
Makoto Onuki34145532017-03-14 17:58:36 -07003396 if (activity == null) {
3397 wtf("null activity detected");
3398 return false;
3399 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08003400 if (DUMMY_MAIN_ACTIVITY.equals(activity.getClassName())) {
3401 return true;
3402 }
3403 final List<ResolveInfo> resolved = queryActivities(
3404 getMainActivityIntent(), activity.getPackageName(), activity, userId);
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003405 return resolved.size() > 0;
Makoto Onukib08790c2016-06-23 14:05:46 -07003406 } finally {
Makoto Onukib08790c2016-06-23 14:05:46 -07003407 logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start);
3408 }
3409 }
3410
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003411 /**
Makoto Onuki2d895c32016-12-02 15:48:40 -08003412 * Create a dummy "main activity" component name which is used to create a dynamic shortcut
3413 * with no main activity temporarily.
3414 */
3415 @NonNull
3416 ComponentName getDummyMainActivity(@NonNull String packageName) {
3417 return new ComponentName(packageName, DUMMY_MAIN_ACTIVITY);
3418 }
3419
Makoto Onuki255461f2017-01-10 11:47:25 -08003420 boolean isDummyMainActivity(@Nullable ComponentName name) {
3421 return name != null && DUMMY_MAIN_ACTIVITY.equals(name.getClassName());
3422 }
3423
Makoto Onuki2d895c32016-12-02 15:48:40 -08003424 /**
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003425 * Return all the enabled, exported and main activities from a package.
3426 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003427 @NonNull
3428 List<ResolveInfo> injectGetMainActivities(@NonNull String packageName, int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003429 final long start = getStatStartTime();
Makoto Onukib08790c2016-06-23 14:05:46 -07003430 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003431 return queryActivities(getMainActivityIntent(), packageName, null, userId);
Makoto Onukib08790c2016-06-23 14:05:46 -07003432 } finally {
Makoto Onukib08790c2016-06-23 14:05:46 -07003433 logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start);
3434 }
3435 }
3436
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003437 /**
3438 * Return whether an activity is enabled and exported.
3439 */
3440 @VisibleForTesting
3441 boolean injectIsActivityEnabledAndExported(
3442 @NonNull ComponentName activity, @UserIdInt int userId) {
Makoto Onuki84d59342018-02-02 09:22:38 -08003443 final long start = getStatStartTime();
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003444 try {
3445 return queryActivities(new Intent(), activity.getPackageName(), activity, userId)
3446 .size() > 0;
3447 } finally {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003448 logDurationStat(Stats.IS_ACTIVITY_ENABLED, start);
3449 }
3450 }
3451
Makoto Onuki2d895c32016-12-02 15:48:40 -08003452 /**
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003453 * Get the {@link LauncherApps#ACTION_CONFIRM_PIN_SHORTCUT} or
3454 * {@link LauncherApps#ACTION_CONFIRM_PIN_APPWIDGET} activity in a given package depending on
3455 * the requestType.
Makoto Onuki2d895c32016-12-02 15:48:40 -08003456 */
3457 @Nullable
3458 ComponentName injectGetPinConfirmationActivity(@NonNull String launcherPackageName,
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003459 int launcherUserId, int requestType) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08003460 Preconditions.checkNotNull(launcherPackageName);
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003461 String action = requestType == LauncherApps.PinItemRequest.REQUEST_TYPE_SHORTCUT ?
3462 LauncherApps.ACTION_CONFIRM_PIN_SHORTCUT :
3463 LauncherApps.ACTION_CONFIRM_PIN_APPWIDGET;
Makoto Onuki2d895c32016-12-02 15:48:40 -08003464
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003465 final Intent confirmIntent = new Intent(action).setPackage(launcherPackageName);
Makoto Onuki2d895c32016-12-02 15:48:40 -08003466 final List<ResolveInfo> candidates = queryActivities(
3467 confirmIntent, launcherUserId, /* exportedOnly =*/ false);
3468 for (ResolveInfo ri : candidates) {
3469 return ri.activityInfo.getComponentName();
3470 }
3471 return null;
3472 }
3473
Makoto Onukib08790c2016-06-23 14:05:46 -07003474 boolean injectIsSafeModeEnabled() {
3475 final long token = injectClearCallingIdentity();
3476 try {
3477 return IWindowManager.Stub
3478 .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE))
3479 .isSafeModeEnabled();
3480 } catch (RemoteException e) {
3481 return false; // Shouldn't happen though.
3482 } finally {
3483 injectRestoreCallingIdentity(token);
3484 }
3485 }
3486
Makoto Onuki2d895c32016-12-02 15:48:40 -08003487 /**
3488 * If {@code userId} is of a managed profile, return the parent user ID. Otherwise return
3489 * itself.
3490 */
3491 int getParentOrSelfUserId(int userId) {
Sunny Goyal145c8f82018-02-15 14:27:09 -08003492 return mUserManagerInternal.getProfileParentId(userId);
Makoto Onuki2d895c32016-12-02 15:48:40 -08003493 }
3494
Sunny Goyal87a563e2017-01-01 19:42:45 -08003495 void injectSendIntentSender(IntentSender intentSender, Intent extras) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08003496 if (intentSender == null) {
3497 return;
3498 }
3499 try {
Sunny Goyal87a563e2017-01-01 19:42:45 -08003500 intentSender.sendIntent(mContext, /* code= */ 0, extras,
Makoto Onuki2d895c32016-12-02 15:48:40 -08003501 /* onFinished=*/ null, /* handler= */ null);
3502 } catch (SendIntentException e) {
3503 Slog.w(TAG, "sendIntent failed().", e);
3504 }
3505 }
3506
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003507 // === Backup & restore ===
3508
Makoto Onuki0acbb142016-03-22 17:02:57 -07003509 boolean shouldBackupApp(String packageName, int userId) {
Makoto Onuki905e8852016-03-28 10:40:58 -07003510 return isApplicationFlagSet(packageName, userId, ApplicationInfo.FLAG_ALLOW_BACKUP);
Makoto Onuki0acbb142016-03-22 17:02:57 -07003511 }
3512
Makoto Onukia4f89b12017-10-05 10:37:55 -07003513 static boolean shouldBackupApp(PackageInfo pi) {
Makoto Onuki2e210c42016-03-30 08:30:36 -07003514 return (pi.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0;
3515 }
3516
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003517 @Override
Makoto Onuki2e210c42016-03-30 08:30:36 -07003518 public byte[] getBackupPayload(@UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003519 enforceSystem();
3520 if (DEBUG) {
3521 Slog.d(TAG, "Backing up user " + userId);
3522 }
3523 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003524 if (!isUserUnlockedL(userId)) {
3525 wtf("Can't backup: user " + userId + " is locked or not running");
3526 return null;
3527 }
3528
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003529 final ShortcutUser user = getUserShortcutsLocked(userId);
3530 if (user == null) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003531 wtf("Can't backup: user not found: id=" + userId);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003532 return null;
3533 }
3534
Makoto Onukic8c33292016-09-12 16:36:59 -07003535 // Update the signatures for all packages.
3536 user.forAllPackageItems(spi -> spi.refreshPackageSignatureAndSave());
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003537
Makoto Onukie3fffa92018-02-28 16:25:40 -08003538 // Rescan all apps; this will also update the version codes and "allow-backup".
3539 user.forAllPackages(pkg -> pkg.rescanPackageIfNeeded(
3540 /*isNewApp=*/ false, /*forceRescan=*/ true));
3541
Makoto Onukic8c33292016-09-12 16:36:59 -07003542 // Set the version code for the launchers.
Makoto Onukia4f89b12017-10-05 10:37:55 -07003543 user.forAllLaunchers(launcher -> launcher.ensurePackageInfo());
Makoto Onukic8c33292016-09-12 16:36:59 -07003544
3545 // Save to the filesystem.
3546 scheduleSaveUser(userId);
3547 saveDirtyInfo();
3548
Makoto Onuki475c3652017-05-08 14:29:03 -07003549 // Note, in case of backup, we don't have to wait on bitmap saving, because we don't
3550 // back up bitmaps anyway.
3551
Makoto Onukic8c33292016-09-12 16:36:59 -07003552 // Then create the backup payload.
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003553 final ByteArrayOutputStream os = new ByteArrayOutputStream(32 * 1024);
3554 try {
3555 saveUserInternalLocked(userId, os, /* forBackup */ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07003556 } catch (XmlPullParserException | IOException e) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003557 // Shouldn't happen.
3558 Slog.w(TAG, "Backup failed.", e);
3559 return null;
3560 }
Makoto Onukie3fffa92018-02-28 16:25:40 -08003561 byte[] payload = os.toByteArray();
3562 mShortcutDumpFiles.save("backup-1-payload.txt", payload);
3563 return payload;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003564 }
3565 }
3566
3567 @Override
Makoto Onuki2e210c42016-03-30 08:30:36 -07003568 public void applyRestore(byte[] payload, @UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003569 enforceSystem();
3570 if (DEBUG) {
3571 Slog.d(TAG, "Restoring user " + userId);
3572 }
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003573 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003574 if (!isUserUnlockedL(userId)) {
3575 wtf("Can't restore: user " + userId + " is locked or not running");
3576 return;
3577 }
Makoto Onuki50a320e2017-05-31 14:38:42 -07003578
3579 // Note we print the file timestamps in dumpsys too, but also printing the timestamp
3580 // in the files anyway.
3581 mShortcutDumpFiles.save("restore-0-start.txt", pw -> {
3582 pw.print("Start time: ");
3583 dumpCurrentTime(pw);
3584 pw.println();
3585 });
3586 mShortcutDumpFiles.save("restore-1-payload.xml", payload);
3587
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003588 // Actually do restore.
3589 final ShortcutUser restored;
Makoto Onuki02f338e2016-07-29 09:40:40 -07003590 final ByteArrayInputStream is = new ByteArrayInputStream(payload);
3591 try {
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003592 restored = loadUserInternal(userId, is, /* fromBackup */ true);
3593 } catch (XmlPullParserException | IOException | InvalidFileFormatException e) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003594 Slog.w(TAG, "Restoration failed.", e);
3595 return;
3596 }
Makoto Onuki50a320e2017-05-31 14:38:42 -07003597 mShortcutDumpFiles.save("restore-2.txt", this::dumpInner);
3598
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003599 getUserShortcutsLocked(userId).mergeRestoredFile(restored);
Makoto Onuki2e210c42016-03-30 08:30:36 -07003600
Makoto Onuki50a320e2017-05-31 14:38:42 -07003601 mShortcutDumpFiles.save("restore-3.txt", this::dumpInner);
3602
Makoto Onuki377b7972016-08-09 14:43:55 -07003603 // Rescan all packages to re-publish manifest shortcuts and do other checks.
3604 rescanUpdatedPackagesLocked(userId,
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003605 0 // lastScanTime = 0; rescan all packages.
3606 );
Makoto Onuki2e210c42016-03-30 08:30:36 -07003607
Makoto Onuki50a320e2017-05-31 14:38:42 -07003608 mShortcutDumpFiles.save("restore-4.txt", this::dumpInner);
3609
3610 mShortcutDumpFiles.save("restore-5-finish.txt", pw -> {
3611 pw.print("Finish time: ");
3612 dumpCurrentTime(pw);
3613 pw.println();
3614 });
3615
Makoto Onuki2e210c42016-03-30 08:30:36 -07003616 saveUserLocked(userId);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003617 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07003618 }
3619
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003620 // === Dump ===
3621
3622 @Override
3623 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06003624 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
Makoto Onukic4361e32017-04-03 11:24:25 -07003625 dumpNoCheck(fd, pw, args);
3626 }
3627
3628 @VisibleForTesting
3629 void dumpNoCheck(FileDescriptor fd, PrintWriter pw, String[] args) {
Makoto Onuki20b82212017-10-04 15:03:50 -07003630 final DumpFilter filter = parseDumpArgs(args);
Makoto Onuki50a320e2017-05-31 14:38:42 -07003631
Makoto Onuki20b82212017-10-04 15:03:50 -07003632 if (filter.shouldDumpCheckIn()) {
Makoto Onuki50a320e2017-05-31 14:38:42 -07003633 // Other flags are not supported for checkin.
Makoto Onuki20b82212017-10-04 15:03:50 -07003634 dumpCheckin(pw, filter.shouldCheckInClear());
Makoto Onuki76269922016-07-15 14:58:54 -07003635 } else {
Makoto Onuki20b82212017-10-04 15:03:50 -07003636 if (filter.shouldDumpMain()) {
3637 dumpInner(pw, filter);
Makoto Onuki50a320e2017-05-31 14:38:42 -07003638 pw.println();
3639 }
Makoto Onuki20b82212017-10-04 15:03:50 -07003640 if (filter.shouldDumpUid()) {
Makoto Onuki50a320e2017-05-31 14:38:42 -07003641 dumpUid(pw);
3642 pw.println();
3643 }
Makoto Onuki20b82212017-10-04 15:03:50 -07003644 if (filter.shouldDumpFiles()) {
Makoto Onuki50a320e2017-05-31 14:38:42 -07003645 dumpDumpFiles(pw);
3646 pw.println();
3647 }
Makoto Onuki76269922016-07-15 14:58:54 -07003648 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003649 }
3650
Makoto Onuki20b82212017-10-04 15:03:50 -07003651 private static DumpFilter parseDumpArgs(String[] args) {
3652 final DumpFilter filter = new DumpFilter();
3653 if (args == null) {
3654 return filter;
3655 }
Makoto Onuki55046222016-03-08 10:49:47 -08003656
Makoto Onuki20b82212017-10-04 15:03:50 -07003657 int argIndex = 0;
3658 while (argIndex < args.length) {
3659 final String arg = args[argIndex++];
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003660
Makoto Onuki20b82212017-10-04 15:03:50 -07003661 if ("-c".equals(arg)) {
3662 filter.setDumpCheckIn(true);
3663 continue;
3664 }
3665 if ("--checkin".equals(arg)) {
3666 filter.setDumpCheckIn(true);
3667 filter.setCheckInClear(true);
3668 continue;
3669 }
3670 if ("-a".equals(arg) || "--all".equals(arg)) {
3671 filter.setDumpUid(true);
3672 filter.setDumpFiles(true);
3673 continue;
3674 }
3675 if ("-u".equals(arg) || "--uid".equals(arg)) {
3676 filter.setDumpUid(true);
3677 continue;
3678 }
3679 if ("-f".equals(arg) || "--files".equals(arg)) {
3680 filter.setDumpFiles(true);
3681 continue;
3682 }
3683 if ("-n".equals(arg) || "--no-main".equals(arg)) {
3684 filter.setDumpMain(false);
3685 continue;
3686 }
3687 if ("--user".equals(arg)) {
3688 if (argIndex >= args.length) {
3689 throw new IllegalArgumentException("Missing user ID for --user");
3690 }
3691 try {
3692 filter.addUser(Integer.parseInt(args[argIndex++]));
3693 } catch (NumberFormatException e) {
3694 throw new IllegalArgumentException("Invalid user ID", e);
3695 }
3696 continue;
3697 }
3698 if ("-p".equals(arg) || "--package".equals(arg)) {
3699 if (argIndex >= args.length) {
3700 throw new IllegalArgumentException("Missing package name for --package");
3701 }
3702 filter.addPackageRegex(args[argIndex++]);
3703 filter.setDumpDetails(false);
3704 continue;
3705 }
3706 if (arg.startsWith("-")) {
3707 throw new IllegalArgumentException("Unknown option " + arg);
3708 }
3709 break;
3710 }
3711 while (argIndex < args.length) {
3712 filter.addPackage(args[argIndex++]);
3713 }
3714 return filter;
3715 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003716
Makoto Onuki20b82212017-10-04 15:03:50 -07003717 static class DumpFilter {
3718 private boolean mDumpCheckIn = false;
3719 private boolean mCheckInClear = false;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003720
Makoto Onuki20b82212017-10-04 15:03:50 -07003721 private boolean mDumpMain = true;
3722 private boolean mDumpUid = false;
3723 private boolean mDumpFiles = false;
Makoto Onuki55046222016-03-08 10:49:47 -08003724
Makoto Onuki20b82212017-10-04 15:03:50 -07003725 private boolean mDumpDetails = true;
3726 private List<Pattern> mPackagePatterns = new ArrayList<>();
3727 private List<Integer> mUsers = new ArrayList<>();
3728
3729 void addPackageRegex(String regex) {
3730 mPackagePatterns.add(Pattern.compile(regex));
3731 }
3732
3733 public void addPackage(String packageName) {
3734 addPackageRegex(Pattern.quote(packageName));
3735 }
3736
3737 void addUser(int userId) {
3738 mUsers.add(userId);
3739 }
3740
3741 boolean isPackageMatch(String packageName) {
3742 if (mPackagePatterns.size() == 0) {
3743 return true;
3744 }
3745 for (int i = 0; i < mPackagePatterns.size(); i++) {
3746 if (mPackagePatterns.get(i).matcher(packageName).find()) {
3747 return true;
Makoto Onuki085a05c2016-08-19 11:39:29 -07003748 }
Makoto Onuki2e210c42016-03-30 08:30:36 -07003749 }
Makoto Onuki20b82212017-10-04 15:03:50 -07003750 return false;
3751 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003752
Makoto Onuki20b82212017-10-04 15:03:50 -07003753 boolean isUserMatch(int userId) {
3754 if (mUsers.size() == 0) {
3755 return true;
3756 }
3757 for (int i = 0; i < mUsers.size(); i++) {
3758 if (mUsers.get(i) == userId) {
3759 return true;
3760 }
3761 }
3762 return false;
3763 }
Makoto Onukia2241832016-07-06 13:28:37 -07003764
Makoto Onuki20b82212017-10-04 15:03:50 -07003765 public boolean shouldDumpCheckIn() {
3766 return mDumpCheckIn;
3767 }
3768
3769 public void setDumpCheckIn(boolean dumpCheckIn) {
3770 mDumpCheckIn = dumpCheckIn;
3771 }
3772
3773 public boolean shouldCheckInClear() {
3774 return mCheckInClear;
3775 }
3776
3777 public void setCheckInClear(boolean checkInClear) {
3778 mCheckInClear = checkInClear;
3779 }
3780
3781 public boolean shouldDumpMain() {
3782 return mDumpMain;
3783 }
3784
3785 public void setDumpMain(boolean dumpMain) {
3786 mDumpMain = dumpMain;
3787 }
3788
3789 public boolean shouldDumpUid() {
3790 return mDumpUid;
3791 }
3792
3793 public void setDumpUid(boolean dumpUid) {
3794 mDumpUid = dumpUid;
3795 }
3796
3797 public boolean shouldDumpFiles() {
3798 return mDumpFiles;
3799 }
3800
3801 public void setDumpFiles(boolean dumpFiles) {
3802 mDumpFiles = dumpFiles;
3803 }
3804
3805 public boolean shouldDumpDetails() {
3806 return mDumpDetails;
3807 }
3808
3809 public void setDumpDetails(boolean dumpDetails) {
3810 mDumpDetails = dumpDetails;
3811 }
3812 }
3813
3814 private void dumpInner(PrintWriter pw) {
3815 dumpInner(pw, new DumpFilter());
3816 }
3817
3818 private void dumpInner(PrintWriter pw, DumpFilter filter) {
3819 synchronized (mLock) {
3820 if (filter.shouldDumpDetails()) {
3821 final long now = injectCurrentTimeMillis();
3822 pw.print("Now: [");
3823 pw.print(now);
3824 pw.print("] ");
3825 pw.print(formatTime(now));
3826
3827 pw.print(" Raw last reset: [");
3828 pw.print(mRawLastResetTime);
3829 pw.print("] ");
3830 pw.print(formatTime(mRawLastResetTime));
3831
3832 final long last = getLastResetTimeLocked();
3833 pw.print(" Last reset: [");
3834 pw.print(last);
3835 pw.print("] ");
3836 pw.print(formatTime(last));
3837
3838 final long next = getNextResetTimeLocked();
3839 pw.print(" Next reset: [");
3840 pw.print(next);
3841 pw.print("] ");
3842 pw.print(formatTime(next));
Makoto Onukie3fffa92018-02-28 16:25:40 -08003843 pw.println();
3844 pw.println();
Makoto Onuki20b82212017-10-04 15:03:50 -07003845
3846 pw.print(" Config:");
3847 pw.print(" Max icon dim: ");
3848 pw.println(mMaxIconDimension);
3849 pw.print(" Icon format: ");
3850 pw.println(mIconPersistFormat);
3851 pw.print(" Icon quality: ");
3852 pw.println(mIconPersistQuality);
3853 pw.print(" saveDelayMillis: ");
3854 pw.println(mSaveDelayMillis);
3855 pw.print(" resetInterval: ");
3856 pw.println(mResetInterval);
3857 pw.print(" maxUpdatesPerInterval: ");
3858 pw.println(mMaxUpdatesPerInterval);
3859 pw.print(" maxShortcutsPerActivity: ");
3860 pw.println(mMaxShortcuts);
3861 pw.println();
3862
Makoto Onuki84d59342018-02-02 09:22:38 -08003863 mStatLogger.dump(pw, " ");
Makoto Onuki20b82212017-10-04 15:03:50 -07003864
3865 pw.println();
3866 pw.print(" #Failures: ");
3867 pw.println(mWtfCount);
3868
3869 if (mLastWtfStacktrace != null) {
3870 pw.print(" Last failure stack trace: ");
3871 pw.println(Log.getStackTraceString(mLastWtfStacktrace));
3872 }
3873
3874 pw.println();
3875 mShortcutBitmapSaver.dumpLocked(pw, " ");
3876
3877 pw.println();
Makoto Onukia2241832016-07-06 13:28:37 -07003878 }
3879
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08003880 for (int i = 0; i < mUsers.size(); i++) {
Makoto Onuki20b82212017-10-04 15:03:50 -07003881 final ShortcutUser user = mUsers.valueAt(i);
3882 if (filter.isUserMatch(user.getUserId())) {
3883 user.dump(pw, " ", filter);
3884 pw.println();
3885 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003886 }
Makoto Onuki708703b2017-12-11 16:38:11 -08003887
3888 for (int i = 0; i < mShortcutNonPersistentUsers.size(); i++) {
3889 final ShortcutNonPersistentUser user = mShortcutNonPersistentUsers.valueAt(i);
3890 if (filter.isUserMatch(user.getUserId())) {
3891 user.dump(pw, " ", filter);
3892 pw.println();
3893 }
3894 }
Makoto Onuki50a320e2017-05-31 14:38:42 -07003895 }
3896 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003897
Makoto Onuki50a320e2017-05-31 14:38:42 -07003898 private void dumpUid(PrintWriter pw) {
3899 synchronized (mLock) {
3900 pw.println("** SHORTCUT MANAGER UID STATES (dumpsys shortcut -n -u)");
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003901
3902 for (int i = 0; i < mUidState.size(); i++) {
3903 final int uid = mUidState.keyAt(i);
3904 final int state = mUidState.valueAt(i);
3905 pw.print(" UID=");
3906 pw.print(uid);
3907 pw.print(" state=");
3908 pw.print(state);
3909 if (isProcessStateForeground(state)) {
3910 pw.print(" [FG]");
3911 }
3912 pw.print(" last FG=");
3913 pw.print(mUidLastForegroundElapsedTime.get(uid));
3914 pw.println();
3915 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003916 }
3917 }
3918
Makoto Onuki41066a62016-03-09 16:18:44 -08003919 static String formatTime(long time) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003920 Time tobj = new Time();
3921 tobj.set(time);
3922 return tobj.format("%Y-%m-%d %H:%M:%S");
3923 }
3924
Makoto Onuki50a320e2017-05-31 14:38:42 -07003925 private void dumpCurrentTime(PrintWriter pw) {
3926 pw.print(formatTime(injectCurrentTimeMillis()));
3927 }
3928
Makoto Onuki76269922016-07-15 14:58:54 -07003929 /**
3930 * Dumpsys for checkin.
3931 *
3932 * @param clear if true, clear the history information. Some other system services have this
3933 * behavior but shortcut service doesn't for now.
3934 */
3935 private void dumpCheckin(PrintWriter pw, boolean clear) {
3936 synchronized (mLock) {
3937 try {
3938 final JSONArray users = new JSONArray();
3939
3940 for (int i = 0; i < mUsers.size(); i++) {
3941 users.put(mUsers.valueAt(i).dumpCheckin(clear));
3942 }
3943
3944 final JSONObject result = new JSONObject();
3945
3946 result.put(KEY_SHORTCUT, users);
3947 result.put(KEY_LOW_RAM, injectIsLowRamDevice());
3948 result.put(KEY_ICON_SIZE, mMaxIconDimension);
3949
3950 pw.println(result.toString(1));
3951 } catch (JSONException e) {
3952 Slog.e(TAG, "Unable to write in json", e);
3953 }
3954 }
3955 }
3956
Makoto Onuki50a320e2017-05-31 14:38:42 -07003957 private void dumpDumpFiles(PrintWriter pw) {
3958 synchronized (mLock) {
3959 pw.println("** SHORTCUT MANAGER FILES (dumpsys shortcut -n -f)");
3960 mShortcutDumpFiles.dumpAll(pw);
3961 }
3962 }
3963
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003964 // === Shell support ===
3965
3966 @Override
3967 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003968 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003969
3970 enforceShell();
3971
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07003972 final long token = injectClearCallingIdentity();
3973 try {
Dianne Hackborn354736e2016-08-22 17:00:05 -07003974 final int status = (new MyShellCommand()).exec(this, in, out, err, args, callback,
3975 resultReceiver);
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07003976 resultReceiver.send(status, null);
3977 } finally {
3978 injectRestoreCallingIdentity(token);
3979 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003980 }
3981
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003982 static class CommandException extends Exception {
3983 public CommandException(String message) {
3984 super(message);
3985 }
3986 }
3987
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003988 /**
3989 * Handle "adb shell cmd".
3990 */
3991 private class MyShellCommand extends ShellCommand {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003992
3993 private int mUserId = UserHandle.USER_SYSTEM;
3994
Makoto Onuki02f338e2016-07-29 09:40:40 -07003995 private void parseOptionsLocked(boolean takeUser)
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003996 throws CommandException {
3997 String opt;
3998 while ((opt = getNextOption()) != null) {
3999 switch (opt) {
4000 case "--user":
4001 if (takeUser) {
4002 mUserId = UserHandle.parseUserArg(getNextArgRequired());
Makoto Onuki02f338e2016-07-29 09:40:40 -07004003 if (!isUserUnlockedL(mUserId)) {
Makoto Onukif34c3082016-07-13 10:25:25 -07004004 throw new CommandException(
4005 "User " + mUserId + " is not running or locked");
4006 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004007 break;
4008 }
4009 // fallthrough
4010 default:
4011 throw new CommandException("Unknown option: " + opt);
4012 }
4013 }
4014 }
4015
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004016 @Override
4017 public int onCommand(String cmd) {
4018 if (cmd == null) {
4019 return handleDefaultCommands(cmd);
4020 }
4021 final PrintWriter pw = getOutPrintWriter();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004022 try {
4023 switch (cmd) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004024 case "reset-throttling":
4025 handleResetThrottling();
4026 break;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004027 case "reset-all-throttling":
4028 handleResetAllThrottling();
4029 break;
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004030 case "override-config":
4031 handleOverrideConfig();
4032 break;
4033 case "reset-config":
4034 handleResetConfig();
4035 break;
4036 case "clear-default-launcher":
4037 handleClearDefaultLauncher();
4038 break;
4039 case "get-default-launcher":
4040 handleGetDefaultLauncher();
4041 break;
Makoto Onukiac214972016-04-04 10:19:45 -07004042 case "unload-user":
4043 handleUnloadUser();
4044 break;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004045 case "clear-shortcuts":
4046 handleClearShortcuts();
4047 break;
Makoto Onukib08790c2016-06-23 14:05:46 -07004048 case "verify-states": // hidden command to verify various internal states.
4049 handleVerifyStates();
4050 break;
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004051 default:
4052 return handleDefaultCommands(cmd);
4053 }
4054 } catch (CommandException e) {
4055 pw.println("Error: " + e.getMessage());
4056 return 1;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004057 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004058 pw.println("Success");
4059 return 0;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004060 }
4061
4062 @Override
4063 public void onHelp() {
4064 final PrintWriter pw = getOutPrintWriter();
4065 pw.println("Usage: cmd shortcut COMMAND [options ...]");
4066 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004067 pw.println("cmd shortcut reset-throttling [--user USER_ID]");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004068 pw.println(" Reset throttling for all packages and users");
4069 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004070 pw.println("cmd shortcut reset-all-throttling");
4071 pw.println(" Reset the throttling state for all users");
4072 pw.println();
Makoto Onuki4362a662016-03-08 18:59:09 -08004073 pw.println("cmd shortcut override-config CONFIG");
4074 pw.println(" Override the configuration for testing (will last until reboot)");
4075 pw.println();
4076 pw.println("cmd shortcut reset-config");
4077 pw.println(" Reset the configuration set with \"update-config\"");
4078 pw.println();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004079 pw.println("cmd shortcut clear-default-launcher [--user USER_ID]");
4080 pw.println(" Clear the cached default launcher");
4081 pw.println();
4082 pw.println("cmd shortcut get-default-launcher [--user USER_ID]");
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07004083 pw.println(" Show the default launcher");
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004084 pw.println();
Makoto Onukiac214972016-04-04 10:19:45 -07004085 pw.println("cmd shortcut unload-user [--user USER_ID]");
4086 pw.println(" Unload a user from the memory");
4087 pw.println(" (This should not affect any observable behavior)");
4088 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004089 pw.println("cmd shortcut clear-shortcuts [--user USER_ID] PACKAGE");
4090 pw.println(" Remove all shortcuts from a package, including pinned shortcuts");
4091 pw.println();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004092 }
4093
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004094 private void handleResetThrottling() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07004095 synchronized (mLock) {
4096 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki4554d0e2016-03-14 15:51:41 -07004097
Makoto Onuki02f338e2016-07-29 09:40:40 -07004098 Slog.i(TAG, "cmd: handleResetThrottling: user=" + mUserId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004099
Makoto Onuki02f338e2016-07-29 09:40:40 -07004100 resetThrottlingInner(mUserId);
4101 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004102 }
4103
4104 private void handleResetAllThrottling() {
4105 Slog.i(TAG, "cmd: handleResetAllThrottling");
4106
4107 resetAllThrottlingInner();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004108 }
4109
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004110 private void handleOverrideConfig() throws CommandException {
Makoto Onuki4362a662016-03-08 18:59:09 -08004111 final String config = getNextArgRequired();
4112
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004113 Slog.i(TAG, "cmd: handleOverrideConfig: " + config);
4114
Makoto Onuki4362a662016-03-08 18:59:09 -08004115 synchronized (mLock) {
4116 if (!updateConfigurationLocked(config)) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004117 throw new CommandException("override-config failed. See logcat for details.");
Makoto Onuki4362a662016-03-08 18:59:09 -08004118 }
4119 }
Makoto Onuki4362a662016-03-08 18:59:09 -08004120 }
4121
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004122 private void handleResetConfig() {
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004123 Slog.i(TAG, "cmd: handleResetConfig");
4124
Makoto Onuki4362a662016-03-08 18:59:09 -08004125 synchronized (mLock) {
4126 loadConfigurationLocked();
4127 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004128 }
4129
4130 private void clearLauncher() {
4131 synchronized (mLock) {
Makoto Onuki10305202016-07-14 18:14:08 -07004132 getUserShortcutsLocked(mUserId).forceClearLauncher();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004133 }
4134 }
4135
4136 private void showLauncher() {
4137 synchronized (mLock) {
4138 // This ensures to set the cached launcher. Package name doesn't matter.
4139 hasShortcutHostPermissionInner("-", mUserId);
4140
4141 getOutPrintWriter().println("Launcher: "
Makoto Onuki10305202016-07-14 18:14:08 -07004142 + getUserShortcutsLocked(mUserId).getLastKnownLauncher());
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004143 }
4144 }
4145
4146 private void handleClearDefaultLauncher() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07004147 synchronized (mLock) {
4148 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004149
Makoto Onuki02f338e2016-07-29 09:40:40 -07004150 clearLauncher();
4151 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004152 }
4153
4154 private void handleGetDefaultLauncher() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07004155 synchronized (mLock) {
4156 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08004157
Makoto Onuki02f338e2016-07-29 09:40:40 -07004158 clearLauncher();
4159 showLauncher();
4160 }
Makoto Onuki4362a662016-03-08 18:59:09 -08004161 }
Makoto Onukiac214972016-04-04 10:19:45 -07004162
4163 private void handleUnloadUser() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07004164 synchronized (mLock) {
4165 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onukiac214972016-04-04 10:19:45 -07004166
Makoto Onuki02f338e2016-07-29 09:40:40 -07004167 Slog.i(TAG, "cmd: handleUnloadUser: user=" + mUserId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004168
Makoto Onuki01ce92b2017-04-28 12:24:16 -07004169 ShortcutService.this.handleStopUser(mUserId);
Makoto Onuki02f338e2016-07-29 09:40:40 -07004170 }
Makoto Onukiac214972016-04-04 10:19:45 -07004171 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004172
4173 private void handleClearShortcuts() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07004174 synchronized (mLock) {
4175 parseOptionsLocked(/* takeUser =*/ true);
4176 final String packageName = getNextArgRequired();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004177
Makoto Onuki02f338e2016-07-29 09:40:40 -07004178 Slog.i(TAG, "cmd: handleClearShortcuts: user" + mUserId + ", " + packageName);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004179
Makoto Onuki02f338e2016-07-29 09:40:40 -07004180 ShortcutService.this.cleanUpPackageForAllLoadedUsers(packageName, mUserId,
4181 /* appStillExists = */ true);
4182 }
Makoto Onukib08790c2016-06-23 14:05:46 -07004183 }
4184
4185 private void handleVerifyStates() throws CommandException {
4186 try {
4187 verifyStatesForce(); // This will throw when there's an issue.
4188 } catch (Throwable th) {
4189 throw new CommandException(th.getMessage() + "\n" + Log.getStackTraceString(th));
4190 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07004191 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004192 }
4193
4194 // === Unit test support ===
4195
4196 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07004197 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004198 long injectCurrentTimeMillis() {
4199 return System.currentTimeMillis();
4200 }
4201
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07004202 @VisibleForTesting
4203 long injectElapsedRealtime() {
4204 return SystemClock.elapsedRealtime();
4205 }
4206
Makoto Onuki475c3652017-05-08 14:29:03 -07004207 @VisibleForTesting
4208 long injectUptimeMillis() {
4209 return SystemClock.uptimeMillis();
4210 }
4211
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004212 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07004213 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004214 int injectBinderCallingUid() {
4215 return getCallingUid();
4216 }
4217
Makoto Onuki7d0fa812018-02-21 11:24:43 -08004218 @VisibleForTesting
4219 int injectBinderCallingPid() {
4220 return getCallingPid();
4221 }
4222
Makoto Onuki31459242016-03-22 11:12:18 -07004223 private int getCallingUserId() {
Makoto Onuki4554d0e2016-03-14 15:51:41 -07004224 return UserHandle.getUserId(injectBinderCallingUid());
4225 }
4226
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07004227 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07004228 @VisibleForTesting
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07004229 long injectClearCallingIdentity() {
4230 return Binder.clearCallingIdentity();
4231 }
4232
4233 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07004234 @VisibleForTesting
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07004235 void injectRestoreCallingIdentity(long token) {
4236 Binder.restoreCallingIdentity(token);
4237 }
4238
Makoto Onuki33663282016-08-22 16:19:04 -07004239 // Injection point.
Makoto Onuki33663282016-08-22 16:19:04 -07004240 String injectBuildFingerprint() {
4241 return Build.FINGERPRINT;
4242 }
4243
Makoto Onukide667372016-03-15 14:29:20 -07004244 final void wtf(String message) {
Makoto Onukib08790c2016-06-23 14:05:46 -07004245 wtf(message, /* exception= */ null);
Makoto Onukide667372016-03-15 14:29:20 -07004246 }
4247
Makoto Onuki2e210c42016-03-30 08:30:36 -07004248 // Injection point.
Makoto Onukia2241832016-07-06 13:28:37 -07004249 void wtf(String message, Throwable e) {
4250 if (e == null) {
4251 e = new RuntimeException("Stacktrace");
4252 }
4253 synchronized (mLock) {
4254 mWtfCount++;
4255 mLastWtfStacktrace = new Exception("Last failure was logged here:");
4256 }
Makoto Onukide667372016-03-15 14:29:20 -07004257 Slog.wtf(TAG, message, e);
4258 }
4259
Makoto Onuki31459242016-03-22 11:12:18 -07004260 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004261 File injectSystemDataPath() {
4262 return Environment.getDataSystemDirectory();
4263 }
4264
Makoto Onuki31459242016-03-22 11:12:18 -07004265 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004266 File injectUserDataPath(@UserIdInt int userId) {
Makoto Onuki55046222016-03-08 10:49:47 -08004267 return new File(Environment.getDataSystemCeDirectory(userId), DIRECTORY_PER_USER);
4268 }
4269
Makoto Onuki50a320e2017-05-31 14:38:42 -07004270 public File getDumpPath() {
4271 return new File(injectUserDataPath(UserHandle.USER_SYSTEM), DIRECTORY_DUMP);
4272 }
4273
Makoto Onuki4362a662016-03-08 18:59:09 -08004274 @VisibleForTesting
Makoto Onuki55046222016-03-08 10:49:47 -08004275 boolean injectIsLowRamDevice() {
4276 return ActivityManager.isLowRamDeviceStatic();
4277 }
4278
Makoto Onuki31459242016-03-22 11:12:18 -07004279 @VisibleForTesting
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07004280 void injectRegisterUidObserver(IUidObserver observer, int which) {
4281 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004282 ActivityManager.getService().registerUidObserver(observer, which,
Dianne Hackborn5614bf52016-11-07 17:26:41 -08004283 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07004284 } catch (RemoteException shouldntHappen) {
4285 }
4286 }
4287
Makoto Onuki55046222016-03-08 10:49:47 -08004288 File getUserBitmapFilePath(@UserIdInt int userId) {
4289 return new File(injectUserDataPath(userId), DIRECTORY_BITMAPS);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004290 }
4291
4292 @VisibleForTesting
Makoto Onuki31459242016-03-22 11:12:18 -07004293 SparseArray<ShortcutUser> getShortcutsForTest() {
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08004294 return mUsers;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004295 }
4296
4297 @VisibleForTesting
Makoto Onukib5a012f2016-06-21 11:13:53 -07004298 int getMaxShortcutsForTest() {
4299 return mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004300 }
4301
4302 @VisibleForTesting
Makoto Onukib6d35232016-04-04 15:57:17 -07004303 int getMaxUpdatesPerIntervalForTest() {
4304 return mMaxUpdatesPerInterval;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004305 }
4306
4307 @VisibleForTesting
Makoto Onuki4362a662016-03-08 18:59:09 -08004308 long getResetIntervalForTest() {
4309 return mResetInterval;
Makoto Onuki55046222016-03-08 10:49:47 -08004310 }
4311
4312 @VisibleForTesting
Makoto Onuki4362a662016-03-08 18:59:09 -08004313 int getMaxIconDimensionForTest() {
4314 return mMaxIconDimension;
4315 }
4316
4317 @VisibleForTesting
4318 CompressFormat getIconPersistFormatForTest() {
4319 return mIconPersistFormat;
4320 }
4321
4322 @VisibleForTesting
4323 int getIconPersistQualityForTest() {
4324 return mIconPersistQuality;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004325 }
Makoto Onuki41066a62016-03-09 16:18:44 -08004326
4327 @VisibleForTesting
Makoto Onuki22fcc682016-05-17 14:52:19 -07004328 ShortcutPackage getPackageShortcutForTest(String packageName, int userId) {
Makoto Onuki41066a62016-03-09 16:18:44 -08004329 synchronized (mLock) {
Makoto Onuki31459242016-03-22 11:12:18 -07004330 final ShortcutUser user = mUsers.get(userId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07004331 if (user == null) return null;
4332
Makoto Onuki22fcc682016-05-17 14:52:19 -07004333 return user.getAllPackagesForTest().get(packageName);
4334 }
4335 }
4336
4337 @VisibleForTesting
4338 ShortcutInfo getPackageShortcutForTest(String packageName, String shortcutId, int userId) {
4339 synchronized (mLock) {
Makoto Onukif34c3082016-07-13 10:25:25 -07004340 final ShortcutPackage pkg = getPackageShortcutForTest(packageName, userId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07004341 if (pkg == null) return null;
4342
4343 return pkg.findShortcutById(shortcutId);
Makoto Onuki41066a62016-03-09 16:18:44 -08004344 }
4345 }
Makoto Onuki7001a612016-05-27 13:24:28 -07004346
Makoto Onukifac592f2016-11-21 13:41:32 -08004347 @VisibleForTesting
4348 ShortcutLauncher getLauncherShortcutForTest(String packageName, int userId) {
4349 synchronized (mLock) {
4350 final ShortcutUser user = mUsers.get(userId);
4351 if (user == null) return null;
4352
4353 return user.getAllLaunchersForTest().get(PackageWithUser.of(userId, packageName));
4354 }
4355 }
4356
Makoto Onuki2d895c32016-12-02 15:48:40 -08004357 @VisibleForTesting
4358 ShortcutRequestPinProcessor getShortcutRequestPinProcessorForTest() {
4359 return mShortcutRequestPinProcessor;
4360 }
4361
Makoto Onuki7001a612016-05-27 13:24:28 -07004362 /**
4363 * Control whether {@link #verifyStates} should be performed. We always perform it during unit
4364 * tests.
4365 */
4366 @VisibleForTesting
4367 boolean injectShouldPerformVerification() {
4368 return DEBUG;
4369 }
4370
4371 /**
4372 * Check various internal states and throws if there's any inconsistency.
4373 * This is normally only enabled during unit tests.
4374 */
4375 final void verifyStates() {
4376 if (injectShouldPerformVerification()) {
4377 verifyStatesInner();
4378 }
4379 }
4380
Makoto Onukib08790c2016-06-23 14:05:46 -07004381 private final void verifyStatesForce() {
4382 verifyStatesInner();
4383 }
4384
Makoto Onuki7001a612016-05-27 13:24:28 -07004385 private void verifyStatesInner() {
Makoto Onuki10305202016-07-14 18:14:08 -07004386 synchronized (mLock) {
Makoto Onuki7001a612016-05-27 13:24:28 -07004387 forEachLoadedUserLocked(u -> u.forAllPackageItems(ShortcutPackageItem::verifyStates));
4388 }
4389 }
Makoto Onuki475c3652017-05-08 14:29:03 -07004390
4391 @VisibleForTesting
4392 void waitForBitmapSavesForTest() {
4393 synchronized (mLock) {
4394 mShortcutBitmapSaver.waitForAllSavesLocked();
4395 }
4396 }
Makoto Onuki41066a62016-03-09 16:18:44 -08004397}