blob: 74eb340b23e3ce50c450d9b6198786b7c0a6076e [file] [log] [blame]
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package com.android.server.pm;
17
Makoto Onuki7001a612016-05-27 13:24:28 -070018import android.annotation.IntDef;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080019import android.annotation.NonNull;
20import android.annotation.Nullable;
21import android.annotation.UserIdInt;
Makoto Onuki55046222016-03-08 10:49:47 -080022import android.app.ActivityManager;
Makoto Onuki33525d22016-08-03 15:45:24 -070023import android.app.ActivityManagerInternal;
Makoto Onuki0acbb142016-03-22 17:02:57 -070024import android.app.AppGlobals;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -070025import android.app.IUidObserver;
Makoto Onukiac042502016-05-20 16:39:42 -070026import android.app.usage.UsageStatsManagerInternal;
Sunny Goyal87a563e2017-01-01 19:42:45 -080027import android.appwidget.AppWidgetProviderInfo;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070028import android.content.BroadcastReceiver;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080029import android.content.ComponentName;
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -080030import android.content.ContentResolver;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080031import 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 Onuki20c95f82016-05-11 16:51:01 -070044import android.content.pm.PackageManager.NameNotFoundException;
Makoto Onuki2d5b4652016-03-11 16:09:54 -080045import android.content.pm.PackageManagerInternal;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080046import android.content.pm.ParceledListSlice;
Makoto Onuki2d5b4652016-03-11 16:09:54 -080047import android.content.pm.ResolveInfo;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080048import android.content.pm.ShortcutInfo;
Makoto Onuki2d895c32016-12-02 15:48:40 -080049import android.content.pm.ShortcutManager;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080050import android.content.pm.ShortcutServiceInternal;
51import android.content.pm.ShortcutServiceInternal.ShortcutChangeListener;
Makoto Onuki2d895c32016-12-02 15:48:40 -080052import android.content.pm.UserInfo;
Makoto Onuki157b1622016-06-02 16:13:10 -070053import android.content.res.Resources;
Makoto Onuki22fcc682016-05-17 14:52:19 -070054import android.content.res.XmlResourceParser;
Makoto Onuki55046222016-03-08 10:49:47 -080055import android.graphics.Bitmap;
56import android.graphics.Bitmap.CompressFormat;
Makoto Onuki55046222016-03-08 10:49:47 -080057import android.graphics.Canvas;
58import android.graphics.RectF;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080059import android.graphics.drawable.Icon;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070060import android.net.Uri;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080061import android.os.Binder;
Makoto Onuki33663282016-08-22 16:19:04 -070062import android.os.Build;
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;
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -080068import android.os.Parcel;
Makoto Onuki55046222016-03-08 10:49:47 -080069import android.os.ParcelFileDescriptor;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080070import android.os.PersistableBundle;
71import android.os.Process;
72import android.os.RemoteException;
73import android.os.ResultReceiver;
Makoto Onuki55046222016-03-08 10:49:47 -080074import android.os.SELinux;
Makoto Onukib08790c2016-06-23 14:05:46 -070075import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070076import android.os.ShellCallback;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080077import android.os.ShellCommand;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -070078import android.os.SystemClock;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080079import android.os.UserHandle;
Makoto Onukicdc78f72016-03-21 15:47:52 -070080import android.os.UserManager;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080081import android.text.TextUtils;
82import android.text.format.Time;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080083import android.util.ArraySet;
84import android.util.AtomicFile;
Makoto Onuki4362a662016-03-08 18:59:09 -080085import android.util.KeyValueListParser;
Makoto Onukiac042502016-05-20 16:39:42 -070086import android.util.Log;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080087import android.util.Slog;
88import android.util.SparseArray;
Makoto Onuki02f338e2016-07-29 09:40:40 -070089import android.util.SparseBooleanArray;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -070090import android.util.SparseIntArray;
91import android.util.SparseLongArray;
Makoto Onuki55046222016-03-08 10:49:47 -080092import android.util.TypedValue;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080093import android.util.Xml;
Makoto Onukib08790c2016-06-23 14:05:46 -070094import android.view.IWindowManager;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080095
96import com.android.internal.annotations.GuardedBy;
97import com.android.internal.annotations.VisibleForTesting;
98import com.android.internal.os.BackgroundThread;
99import com.android.internal.util.FastXmlSerializer;
100import com.android.internal.util.Preconditions;
101import com.android.server.LocalServices;
102import com.android.server.SystemService;
Makoto Onukid99c6f02016-03-28 11:02:54 -0700103import com.android.server.pm.ShortcutUser.PackageWithUser;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800104
105import libcore.io.IoUtils;
106
Makoto Onuki76269922016-07-15 14:58:54 -0700107import org.json.JSONArray;
108import org.json.JSONException;
109import org.json.JSONObject;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800110import org.xmlpull.v1.XmlPullParser;
111import org.xmlpull.v1.XmlPullParserException;
112import org.xmlpull.v1.XmlSerializer;
113
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700114import java.io.BufferedInputStream;
115import java.io.BufferedOutputStream;
116import java.io.ByteArrayInputStream;
117import java.io.ByteArrayOutputStream;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800118import java.io.File;
119import java.io.FileDescriptor;
120import java.io.FileInputStream;
121import java.io.FileNotFoundException;
122import java.io.FileOutputStream;
123import java.io.IOException;
Makoto Onuki55046222016-03-08 10:49:47 -0800124import java.io.InputStream;
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700125import java.io.OutputStream;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800126import java.io.PrintWriter;
Makoto Onuki7001a612016-05-27 13:24:28 -0700127import java.lang.annotation.Retention;
128import java.lang.annotation.RetentionPolicy;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800129import java.net.URISyntaxException;
130import java.nio.charset.StandardCharsets;
131import java.util.ArrayList;
Makoto Onuki22fcc682016-05-17 14:52:19 -0700132import java.util.Collections;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800133import java.util.List;
Makoto Onukic51b2872016-05-04 15:24:50 -0700134import java.util.concurrent.atomic.AtomicBoolean;
Makoto Onuki2e210c42016-03-30 08:30:36 -0700135import java.util.function.Consumer;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800136import java.util.function.Predicate;
137
138/**
139 * TODO:
Makoto Onuki22fcc682016-05-17 14:52:19 -0700140 * - getIconMaxWidth()/getIconMaxHeight() should use xdpi and ydpi.
Makoto Onukib5a012f2016-06-21 11:13:53 -0700141 * -> But TypedValue.applyDimension() doesn't differentiate x and y..?
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800142 *
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700143 * - Detect when already registered instances are passed to APIs again, which might break
Makoto Onukib08790c2016-06-23 14:05:46 -0700144 * internal bitmap handling.
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800145 */
146public class ShortcutService extends IShortcutService.Stub {
Makoto Onuki55046222016-03-08 10:49:47 -0800147 static final String TAG = "ShortcutService";
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800148
Makoto Onuki7001a612016-05-27 13:24:28 -0700149 static final boolean DEBUG = false; // STOPSHIP if true
Makoto Onuki41066a62016-03-09 16:18:44 -0800150 static final boolean DEBUG_LOAD = false; // STOPSHIP if true
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700151 static final boolean DEBUG_PROCSTATE = false; // STOPSHIP if true
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800152
Makoto Onuki4362a662016-03-08 18:59:09 -0800153 @VisibleForTesting
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700154 static final long DEFAULT_RESET_INTERVAL_SEC = 24 * 60 * 60; // 1 day
Makoto Onuki4362a662016-03-08 18:59:09 -0800155
156 @VisibleForTesting
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700157 static final int DEFAULT_MAX_UPDATES_PER_INTERVAL = 10;
Makoto Onuki4362a662016-03-08 18:59:09 -0800158
159 @VisibleForTesting
160 static final int DEFAULT_MAX_SHORTCUTS_PER_APP = 5;
161
162 @VisibleForTesting
163 static final int DEFAULT_MAX_ICON_DIMENSION_DP = 96;
164
165 @VisibleForTesting
166 static final int DEFAULT_MAX_ICON_DIMENSION_LOWRAM_DP = 48;
167
168 @VisibleForTesting
169 static final String DEFAULT_ICON_PERSIST_FORMAT = CompressFormat.PNG.name();
170
171 @VisibleForTesting
172 static final int DEFAULT_ICON_PERSIST_QUALITY = 100;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800173
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700174 @VisibleForTesting
175 static final int DEFAULT_SAVE_DELAY_MS = 3000;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800176
177 @VisibleForTesting
178 static final String FILENAME_BASE_STATE = "shortcut_service.xml";
179
180 @VisibleForTesting
181 static final String DIRECTORY_PER_USER = "shortcut_service";
182
183 @VisibleForTesting
184 static final String FILENAME_USER_PACKAGES = "shortcuts.xml";
185
Makoto Onuki55046222016-03-08 10:49:47 -0800186 static final String DIRECTORY_BITMAPS = "bitmaps";
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800187
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700188 private static final String TAG_ROOT = "root";
189 private static final String TAG_LAST_RESET_TIME = "last_reset_time";
Makoto Onuki55046222016-03-08 10:49:47 -0800190
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700191 private static final String ATTR_VALUE = "value";
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800192
Makoto Onukib08790c2016-06-23 14:05:46 -0700193 private static final String LAUNCHER_INTENT_CATEGORY = Intent.CATEGORY_LAUNCHER;
194
Makoto Onuki76269922016-07-15 14:58:54 -0700195 private static final String KEY_SHORTCUT = "shortcut";
196 private static final String KEY_LOW_RAM = "lowRam";
197 private static final String KEY_ICON_SIZE = "iconSize";
198
Makoto Onuki2d895c32016-12-02 15:48:40 -0800199 private static final String DUMMY_MAIN_ACTIVITY = "android.__dummy__";
200
Makoto Onuki4362a662016-03-08 18:59:09 -0800201 @VisibleForTesting
202 interface ConfigConstants {
203 /**
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700204 * Key name for the save delay, in milliseconds. (int)
205 */
206 String KEY_SAVE_DELAY_MILLIS = "save_delay_ms";
207
208 /**
Makoto Onuki4362a662016-03-08 18:59:09 -0800209 * Key name for the throttling reset interval, in seconds. (long)
210 */
211 String KEY_RESET_INTERVAL_SEC = "reset_interval_sec";
212
213 /**
214 * Key name for the max number of modifying API calls per app for every interval. (int)
215 */
Makoto Onukib6d35232016-04-04 15:57:17 -0700216 String KEY_MAX_UPDATES_PER_INTERVAL = "max_updates_per_interval";
Makoto Onuki4362a662016-03-08 18:59:09 -0800217
218 /**
219 * Key name for the max icon dimensions in DP, for non-low-memory devices.
220 */
221 String KEY_MAX_ICON_DIMENSION_DP = "max_icon_dimension_dp";
222
223 /**
224 * Key name for the max icon dimensions in DP, for low-memory devices.
225 */
226 String KEY_MAX_ICON_DIMENSION_DP_LOWRAM = "max_icon_dimension_dp_lowram";
227
228 /**
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700229 * Key name for the max dynamic shortcuts per activity. (int)
Makoto Onuki4362a662016-03-08 18:59:09 -0800230 */
231 String KEY_MAX_SHORTCUTS = "max_shortcuts";
232
233 /**
Makoto Onuki41066a62016-03-09 16:18:44 -0800234 * Key name for icon compression quality, 0-100.
Makoto Onuki4362a662016-03-08 18:59:09 -0800235 */
236 String KEY_ICON_QUALITY = "icon_quality";
237
238 /**
239 * Key name for icon compression format: "PNG", "JPEG" or "WEBP"
240 */
241 String KEY_ICON_FORMAT = "icon_format";
242 }
243
Makoto Onuki41066a62016-03-09 16:18:44 -0800244 final Context mContext;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800245
246 private final Object mLock = new Object();
247
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700248 private static List<ResolveInfo> EMPTY_RESOLVE_INFO = new ArrayList<>(0);
249
Mark Renoufe065f7c2016-11-01 11:48:24 -0400250 // Temporarily reverted to anonymous inner class form due to: b/32554459
251 private static Predicate<ResolveInfo> ACTIVITY_NOT_EXPORTED = new Predicate<ResolveInfo>() {
252 public boolean test(ResolveInfo ri) {
253 return !ri.activityInfo.exported;
254 }
255 };
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700256
Mark Renoufe065f7c2016-11-01 11:48:24 -0400257 // Temporarily reverted to anonymous inner class form due to: b/32554459
258 private static Predicate<PackageInfo> PACKAGE_NOT_INSTALLED = new Predicate<PackageInfo>() {
259 public boolean test(PackageInfo pi) {
260 return !isInstalled(pi);
261 }
262 };
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700263
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800264 private final Handler mHandler;
265
266 @GuardedBy("mLock")
267 private final ArrayList<ShortcutChangeListener> mListeners = new ArrayList<>(1);
268
269 @GuardedBy("mLock")
270 private long mRawLastResetTime;
271
272 /**
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -0800273 * User ID -> UserShortcuts
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800274 */
275 @GuardedBy("mLock")
Makoto Onuki31459242016-03-22 11:12:18 -0700276 private final SparseArray<ShortcutUser> mUsers = new SparseArray<>();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800277
278 /**
Makoto Onukib5a012f2016-06-21 11:13:53 -0700279 * Max number of dynamic + manifest shortcuts that each application can have at a time.
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800280 */
Makoto Onukib5a012f2016-06-21 11:13:53 -0700281 private int mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800282
283 /**
Makoto Onukib6d35232016-04-04 15:57:17 -0700284 * Max number of updating API calls that each application can make during the interval.
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800285 */
Makoto Onukib6d35232016-04-04 15:57:17 -0700286 int mMaxUpdatesPerInterval;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800287
288 /**
289 * Actual throttling-reset interval. By default it's a day.
290 */
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800291 private long mResetInterval;
292
Makoto Onuki55046222016-03-08 10:49:47 -0800293 /**
294 * Icon max width/height in pixels.
295 */
296 private int mMaxIconDimension;
297
Makoto Onuki4362a662016-03-08 18:59:09 -0800298 private CompressFormat mIconPersistFormat;
299 private int mIconPersistQuality;
Makoto Onuki55046222016-03-08 10:49:47 -0800300
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700301 private int mSaveDelayMillis;
302
Makoto Onuki0acbb142016-03-22 17:02:57 -0700303 private final IPackageManager mIPackageManager;
Makoto Onuki2d5b4652016-03-11 16:09:54 -0800304 private final PackageManagerInternal mPackageManagerInternal;
Makoto Onukicdc78f72016-03-21 15:47:52 -0700305 private final UserManager mUserManager;
Makoto Onukiac042502016-05-20 16:39:42 -0700306 private final UsageStatsManagerInternal mUsageStatsManagerInternal;
Makoto Onuki33525d22016-08-03 15:45:24 -0700307 private final ActivityManagerInternal mActivityManagerInternal;
Makoto Onuki2d5b4652016-03-11 16:09:54 -0800308
Makoto Onuki2d895c32016-12-02 15:48:40 -0800309 private final ShortcutRequestPinProcessor mShortcutRequestPinProcessor;
310
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700311 @GuardedBy("mLock")
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700312 final SparseIntArray mUidState = new SparseIntArray();
313
314 @GuardedBy("mLock")
315 final SparseLongArray mUidLastForegroundElapsedTime = new SparseLongArray();
316
317 @GuardedBy("mLock")
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700318 private List<Integer> mDirtyUserIds = new ArrayList<>();
319
Makoto Onukic51b2872016-05-04 15:24:50 -0700320 private final AtomicBoolean mBootCompleted = new AtomicBoolean();
321
Makoto Onuki905e8852016-03-28 10:40:58 -0700322 private static final int PACKAGE_MATCH_FLAGS =
323 PackageManager.MATCH_DIRECT_BOOT_AWARE
Makoto Onukib08790c2016-06-23 14:05:46 -0700324 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE
325 | PackageManager.MATCH_UNINSTALLED_PACKAGES;
Makoto Onuki905e8852016-03-28 10:40:58 -0700326
Makoto Onuki02f338e2016-07-29 09:40:40 -0700327 @GuardedBy("mLock")
328 final SparseBooleanArray mUnlockedUsers = new SparseBooleanArray();
329
Makoto Onuki2e210c42016-03-30 08:30:36 -0700330 // Stats
331 @VisibleForTesting
332 interface Stats {
333 int GET_DEFAULT_HOME = 0;
334 int GET_PACKAGE_INFO = 1;
335 int GET_PACKAGE_INFO_WITH_SIG = 2;
336 int GET_APPLICATION_INFO = 3;
337 int LAUNCHER_PERMISSION_CHECK = 4;
Makoto Onuki6c1dbd52016-05-02 15:19:32 -0700338 int CLEANUP_DANGLING_BITMAPS = 5;
Makoto Onukib08790c2016-06-23 14:05:46 -0700339 int GET_ACTIVITY_WITH_METADATA = 6;
Makoto Onuki6dd9fb72016-06-01 13:55:54 -0700340 int GET_INSTALLED_PACKAGES = 7;
Makoto Onuki22fcc682016-05-17 14:52:19 -0700341 int CHECK_PACKAGE_CHANGES = 8;
Makoto Onuki157b1622016-06-02 16:13:10 -0700342 int GET_APPLICATION_RESOURCES = 9;
343 int RESOURCE_NAME_LOOKUP = 10;
Makoto Onukib08790c2016-06-23 14:05:46 -0700344 int GET_LAUNCHER_ACTIVITY = 11;
345 int CHECK_LAUNCHER_ACTIVITY = 12;
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700346 int IS_ACTIVITY_ENABLED = 13;
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700347 int PACKAGE_UPDATE_CHECK = 14;
Makoto Onuki085a05c2016-08-19 11:39:29 -0700348 int ASYNC_PRELOAD_USER_DELAY = 15;
Makoto Onuki2d895c32016-12-02 15:48:40 -0800349 int GET_DEFAULT_LAUNCHER = 16;
Makoto Onuki2e210c42016-03-30 08:30:36 -0700350
Makoto Onuki2d895c32016-12-02 15:48:40 -0800351 int COUNT = GET_DEFAULT_LAUNCHER + 1;
Makoto Onuki2e210c42016-03-30 08:30:36 -0700352 }
353
Makoto Onuki085a05c2016-08-19 11:39:29 -0700354 private static final String[] STAT_LABELS = {
355 "getHomeActivities()",
356 "Launcher permission check",
357 "getPackageInfo()",
358 "getPackageInfo(SIG)",
359 "getApplicationInfo",
360 "cleanupDanglingBitmaps",
361 "getActivity+metadata",
362 "getInstalledPackages",
363 "checkPackageChanges",
364 "getApplicationResources",
365 "resourceNameLookup",
366 "getLauncherActivity",
367 "checkLauncherActivity",
368 "isActivityEnabled",
369 "packageUpdateCheck",
Makoto Onuki2d895c32016-12-02 15:48:40 -0800370 "asyncPreloadUserDelay",
371 "getDefaultLauncher()"
Makoto Onuki085a05c2016-08-19 11:39:29 -0700372 };
373
Makoto Onuki2e210c42016-03-30 08:30:36 -0700374 final Object mStatLock = new Object();
375
376 @GuardedBy("mStatLock")
377 private final int[] mCountStats = new int[Stats.COUNT];
378
379 @GuardedBy("mStatLock")
380 private final long[] mDurationStats = new long[Stats.COUNT];
381
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700382 private static final int PROCESS_STATE_FOREGROUND_THRESHOLD =
383 ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
384
Makoto Onuki7001a612016-05-27 13:24:28 -0700385 static final int OPERATION_SET = 0;
386 static final int OPERATION_ADD = 1;
387 static final int OPERATION_UPDATE = 2;
388
389 /** @hide */
390 @IntDef(value = {
391 OPERATION_SET,
392 OPERATION_ADD,
393 OPERATION_UPDATE
Makoto Onukib08790c2016-06-23 14:05:46 -0700394 })
Makoto Onuki7001a612016-05-27 13:24:28 -0700395 @Retention(RetentionPolicy.SOURCE)
Makoto Onukib08790c2016-06-23 14:05:46 -0700396 @interface ShortcutOperation {
397 }
Makoto Onuki7001a612016-05-27 13:24:28 -0700398
Makoto Onukia2241832016-07-06 13:28:37 -0700399 @GuardedBy("mLock")
400 private int mWtfCount = 0;
401
402 @GuardedBy("mLock")
403 private Exception mLastWtfStacktrace;
404
Makoto Onukifc4cf2d2016-08-24 11:10:26 -0700405 static class InvalidFileFormatException extends Exception {
406 public InvalidFileFormatException(String message, Throwable cause) {
407 super(message, cause);
408 }
409 }
410
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800411 public ShortcutService(Context context) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700412 this(context, BackgroundThread.get().getLooper(), /*onyForPackgeManagerApis*/ false);
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700413 }
414
415 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700416 ShortcutService(Context context, Looper looper, boolean onlyForPackageManagerApis) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800417 mContext = Preconditions.checkNotNull(context);
418 LocalServices.addService(ShortcutServiceInternal.class, new LocalService());
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700419 mHandler = new Handler(looper);
Makoto Onuki0acbb142016-03-22 17:02:57 -0700420 mIPackageManager = AppGlobals.getPackageManager();
Makoto Onukiac042502016-05-20 16:39:42 -0700421 mPackageManagerInternal = Preconditions.checkNotNull(
422 LocalServices.getService(PackageManagerInternal.class));
423 mUserManager = Preconditions.checkNotNull(context.getSystemService(UserManager.class));
424 mUsageStatsManagerInternal = Preconditions.checkNotNull(
425 LocalServices.getService(UsageStatsManagerInternal.class));
Makoto Onuki33525d22016-08-03 15:45:24 -0700426 mActivityManagerInternal = Preconditions.checkNotNull(
427 LocalServices.getService(ActivityManagerInternal.class));
Makoto Onukicdc78f72016-03-21 15:47:52 -0700428
Makoto Onuki2d895c32016-12-02 15:48:40 -0800429 mShortcutRequestPinProcessor = new ShortcutRequestPinProcessor(this, mLock);
430
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700431 if (onlyForPackageManagerApis) {
432 return; // Don't do anything further. For unit tests only.
433 }
434
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700435 // Register receivers.
436
437 // We need to set a priority, so let's just not use PackageMonitor for now.
438 // TODO Refactor PackageMonitor to support priorities.
439 final IntentFilter packageFilter = new IntentFilter();
440 packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
441 packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
442 packageFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
443 packageFilter.addAction(Intent.ACTION_PACKAGE_DATA_CLEARED);
444 packageFilter.addDataScheme("package");
445 packageFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
446 mContext.registerReceiverAsUser(mPackageMonitor, UserHandle.ALL,
447 packageFilter, null, mHandler);
448
Makoto Onuki10305202016-07-14 18:14:08 -0700449 final IntentFilter preferedActivityFilter = new IntentFilter();
450 preferedActivityFilter.addAction(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
451 preferedActivityFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
452 mContext.registerReceiverAsUser(mPackageMonitor, UserHandle.ALL,
453 preferedActivityFilter, null, mHandler);
454
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700455 final IntentFilter localeFilter = new IntentFilter();
456 localeFilter.addAction(Intent.ACTION_LOCALE_CHANGED);
457 localeFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
458 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL,
459 localeFilter, null, mHandler);
Makoto Onukif34c3082016-07-13 10:25:25 -0700460
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700461 injectRegisterUidObserver(mUidObserver, ActivityManager.UID_OBSERVER_PROCSTATE
462 | ActivityManager.UID_OBSERVER_GONE);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800463 }
464
Makoto Onuki2e210c42016-03-30 08:30:36 -0700465 void logDurationStat(int statId, long start) {
466 synchronized (mStatLock) {
467 mCountStats[statId]++;
Makoto Onuki6c1dbd52016-05-02 15:19:32 -0700468 mDurationStats[statId] += (injectElapsedRealtime() - start);
Makoto Onuki2e210c42016-03-30 08:30:36 -0700469 }
470 }
471
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700472 public String injectGetLocaleTagsForUser(@UserIdInt int userId) {
473 // TODO This should get the per-user locale. b/30123329 b/30119489
474 return LocaleList.getDefault().toLanguageTags();
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700475 }
476
477 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Makoto Onukib08790c2016-06-23 14:05:46 -0700478 @Override
479 public void onUidStateChanged(int uid, int procState) throws RemoteException {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700480 handleOnUidStateChanged(uid, procState);
481 }
482
Makoto Onukib08790c2016-06-23 14:05:46 -0700483 @Override
Dianne Hackborne07641d2016-11-09 15:07:23 -0800484 public void onUidGone(int uid, boolean disabled) throws RemoteException {
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800485 handleOnUidStateChanged(uid, ActivityManager.PROCESS_STATE_NONEXISTENT);
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700486 }
487
Makoto Onukib08790c2016-06-23 14:05:46 -0700488 @Override
489 public void onUidActive(int uid) throws RemoteException {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700490 }
491
Makoto Onukib08790c2016-06-23 14:05:46 -0700492 @Override
Dianne Hackborne07641d2016-11-09 15:07:23 -0800493 public void onUidIdle(int uid, boolean disabled) throws RemoteException {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700494 }
495 };
496
497 void handleOnUidStateChanged(int uid, int procState) {
498 if (DEBUG_PROCSTATE) {
499 Slog.d(TAG, "onUidStateChanged: uid=" + uid + " state=" + procState);
500 }
501 synchronized (mLock) {
502 mUidState.put(uid, procState);
503
504 // We need to keep track of last time an app comes to foreground.
505 // See ShortcutPackage.getApiCallCount() for how it's used.
506 // It doesn't have to be persisted, but it needs to be the elapsed time.
507 if (isProcessStateForeground(procState)) {
508 mUidLastForegroundElapsedTime.put(uid, injectElapsedRealtime());
509 }
510 }
511 }
512
513 private boolean isProcessStateForeground(int processState) {
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800514 return processState <= PROCESS_STATE_FOREGROUND_THRESHOLD;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700515 }
516
517 boolean isUidForegroundLocked(int uid) {
518 if (uid == Process.SYSTEM_UID) {
519 // IUidObserver doesn't report the state of SYSTEM, but it always has bound services,
520 // so it's foreground anyway.
521 return true;
522 }
Makoto Onuki33525d22016-08-03 15:45:24 -0700523 // First, check with the local cache.
524 if (isProcessStateForeground(mUidState.get(uid, ActivityManager.MAX_PROCESS_STATE))) {
525 return true;
526 }
527 // If the cache says background, reach out to AM. Since it'll internally need to hold
528 // the AM lock, we use it as a last resort.
529 return isProcessStateForeground(mActivityManagerInternal.getUidProcessState(uid));
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700530 }
531
532 long getUidLastForegroundElapsedTimeLocked(int uid) {
533 return mUidLastForegroundElapsedTime.get(uid);
534 }
535
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800536 /**
537 * System service lifecycle.
538 */
539 public static final class Lifecycle extends SystemService {
540 final ShortcutService mService;
541
542 public Lifecycle(Context context) {
543 super(context);
544 mService = new ShortcutService(context);
545 }
546
547 @Override
548 public void onStart() {
549 publishBinderService(Context.SHORTCUT_SERVICE, mService);
550 }
551
552 @Override
553 public void onBootPhase(int phase) {
554 mService.onBootPhase(phase);
555 }
556
557 @Override
558 public void onCleanupUser(int userHandle) {
Makoto Onukicdc78f72016-03-21 15:47:52 -0700559 mService.handleCleanupUser(userHandle);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800560 }
561
562 @Override
Makoto Onukif3a572b2016-03-10 12:28:38 -0800563 public void onUnlockUser(int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -0700564 mService.handleUnlockUser(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800565 }
566 }
567
568 /** lifecycle event */
569 void onBootPhase(int phase) {
570 if (DEBUG) {
571 Slog.d(TAG, "onBootPhase: " + phase);
572 }
573 switch (phase) {
574 case SystemService.PHASE_LOCK_SETTINGS_READY:
575 initialize();
576 break;
Makoto Onukic51b2872016-05-04 15:24:50 -0700577 case SystemService.PHASE_BOOT_COMPLETED:
578 mBootCompleted.set(true);
579 break;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800580 }
581 }
582
583 /** lifecycle event */
Makoto Onukicdc78f72016-03-21 15:47:52 -0700584 void handleUnlockUser(int userId) {
Makoto Onuki22fcc682016-05-17 14:52:19 -0700585 if (DEBUG) {
Makoto Onuki085a05c2016-08-19 11:39:29 -0700586 Slog.d(TAG, "handleUnlockUser: user=" + userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700587 }
Makoto Onukicdc78f72016-03-21 15:47:52 -0700588 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -0700589 mUnlockedUsers.put(userId, true);
Makoto Onukicdc78f72016-03-21 15:47:52 -0700590 }
Makoto Onuki085a05c2016-08-19 11:39:29 -0700591
592 // Preload the user data.
593 // Note, we don't use mHandler here but instead just start a new thread.
594 // This is because mHandler (which uses com.android.internal.os.BackgroundThread) is very
595 // busy at this point and this could take hundreds of milliseconds, which would be too
596 // late since the launcher would already have started.
597 // So we just create a new thread. This code runs rarely, so we don't use a thread pool
598 // or anything.
599 final long start = injectElapsedRealtime();
600 injectRunOnNewThread(() -> {
601 synchronized (mLock) {
602 logDurationStat(Stats.ASYNC_PRELOAD_USER_DELAY, start);
603 getUserShortcutsLocked(userId);
604 }
605 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800606 }
607
608 /** lifecycle event */
Makoto Onukicdc78f72016-03-21 15:47:52 -0700609 void handleCleanupUser(int userId) {
Makoto Onuki02f338e2016-07-29 09:40:40 -0700610 if (DEBUG) {
611 Slog.d(TAG, "handleCleanupUser: user=" + userId);
612 }
Makoto Onukicdc78f72016-03-21 15:47:52 -0700613 synchronized (mLock) {
614 unloadUserLocked(userId);
Makoto Onuki02f338e2016-07-29 09:40:40 -0700615
616 mUnlockedUsers.put(userId, false);
Makoto Onukicdc78f72016-03-21 15:47:52 -0700617 }
618 }
619
620 private void unloadUserLocked(int userId) {
621 if (DEBUG) {
622 Slog.d(TAG, "unloadUserLocked: user=" + userId);
623 }
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700624 // Save all dirty information.
625 saveDirtyInfo();
626
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800627 // Unload
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -0800628 mUsers.delete(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800629 }
630
631 /** Return the base state file name */
632 private AtomicFile getBaseStateFile() {
633 final File path = new File(injectSystemDataPath(), FILENAME_BASE_STATE);
634 path.mkdirs();
635 return new AtomicFile(path);
636 }
637
638 /**
639 * Init the instance. (load the state file, etc)
640 */
641 private void initialize() {
642 synchronized (mLock) {
Makoto Onuki4362a662016-03-08 18:59:09 -0800643 loadConfigurationLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800644 loadBaseStateLocked();
645 }
646 }
647
Makoto Onuki4362a662016-03-08 18:59:09 -0800648 /**
649 * Load the configuration from Settings.
650 */
651 private void loadConfigurationLocked() {
652 updateConfigurationLocked(injectShortcutManagerConstants());
653 }
Makoto Onuki55046222016-03-08 10:49:47 -0800654
Makoto Onuki4362a662016-03-08 18:59:09 -0800655 /**
656 * Load the configuration from Settings.
657 */
658 @VisibleForTesting
659 boolean updateConfigurationLocked(String config) {
660 boolean result = true;
661
662 final KeyValueListParser parser = new KeyValueListParser(',');
663 try {
664 parser.setString(config);
665 } catch (IllegalArgumentException e) {
666 // Failed to parse the settings string, log this and move on
667 // with defaults.
668 Slog.e(TAG, "Bad shortcut manager settings", e);
669 result = false;
670 }
671
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700672 mSaveDelayMillis = Math.max(0, (int) parser.getLong(ConfigConstants.KEY_SAVE_DELAY_MILLIS,
673 DEFAULT_SAVE_DELAY_MS));
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700674
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700675 mResetInterval = Math.max(1, parser.getLong(
Makoto Onuki4362a662016-03-08 18:59:09 -0800676 ConfigConstants.KEY_RESET_INTERVAL_SEC, DEFAULT_RESET_INTERVAL_SEC)
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700677 * 1000L);
Makoto Onuki4362a662016-03-08 18:59:09 -0800678
Makoto Onukib6d35232016-04-04 15:57:17 -0700679 mMaxUpdatesPerInterval = Math.max(0, (int) parser.getLong(
680 ConfigConstants.KEY_MAX_UPDATES_PER_INTERVAL, DEFAULT_MAX_UPDATES_PER_INTERVAL));
Makoto Onuki4362a662016-03-08 18:59:09 -0800681
Makoto Onukib5a012f2016-06-21 11:13:53 -0700682 mMaxShortcuts = Math.max(0, (int) parser.getLong(
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700683 ConfigConstants.KEY_MAX_SHORTCUTS, DEFAULT_MAX_SHORTCUTS_PER_APP));
Makoto Onuki4362a662016-03-08 18:59:09 -0800684
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700685 final int iconDimensionDp = Math.max(1, injectIsLowRamDevice()
Makoto Onuki4362a662016-03-08 18:59:09 -0800686 ? (int) parser.getLong(
Makoto Onukib08790c2016-06-23 14:05:46 -0700687 ConfigConstants.KEY_MAX_ICON_DIMENSION_DP_LOWRAM,
688 DEFAULT_MAX_ICON_DIMENSION_LOWRAM_DP)
Makoto Onuki4362a662016-03-08 18:59:09 -0800689 : (int) parser.getLong(
Makoto Onukib08790c2016-06-23 14:05:46 -0700690 ConfigConstants.KEY_MAX_ICON_DIMENSION_DP,
691 DEFAULT_MAX_ICON_DIMENSION_DP));
Makoto Onuki4362a662016-03-08 18:59:09 -0800692
693 mMaxIconDimension = injectDipToPixel(iconDimensionDp);
694
695 mIconPersistFormat = CompressFormat.valueOf(
696 parser.getString(ConfigConstants.KEY_ICON_FORMAT, DEFAULT_ICON_PERSIST_FORMAT));
697
698 mIconPersistQuality = (int) parser.getLong(
699 ConfigConstants.KEY_ICON_QUALITY,
700 DEFAULT_ICON_PERSIST_QUALITY);
701
702 return result;
703 }
704
705 @VisibleForTesting
706 String injectShortcutManagerConstants() {
707 return android.provider.Settings.Global.getString(
708 mContext.getContentResolver(),
709 android.provider.Settings.Global.SHORTCUT_MANAGER_CONSTANTS);
710 }
711
712 @VisibleForTesting
713 int injectDipToPixel(int dip) {
714 return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip,
715 mContext.getResources().getDisplayMetrics());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800716 }
717
Makoto Onuki55046222016-03-08 10:49:47 -0800718 // === Persisting ===
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800719
720 @Nullable
Makoto Onuki41066a62016-03-09 16:18:44 -0800721 static String parseStringAttribute(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800722 return parser.getAttributeValue(null, attribute);
723 }
724
Makoto Onuki0acbb142016-03-22 17:02:57 -0700725 static boolean parseBooleanAttribute(XmlPullParser parser, String attribute) {
726 return parseLongAttribute(parser, attribute) == 1;
727 }
728
Makoto Onuki41066a62016-03-09 16:18:44 -0800729 static int parseIntAttribute(XmlPullParser parser, String attribute) {
730 return (int) parseLongAttribute(parser, attribute);
731 }
732
Makoto Onukid99c6f02016-03-28 11:02:54 -0700733 static int parseIntAttribute(XmlPullParser parser, String attribute, int def) {
734 return (int) parseLongAttribute(parser, attribute, def);
735 }
736
Makoto Onuki41066a62016-03-09 16:18:44 -0800737 static long parseLongAttribute(XmlPullParser parser, String attribute) {
Makoto Onukid99c6f02016-03-28 11:02:54 -0700738 return parseLongAttribute(parser, attribute, 0);
739 }
740
741 static long parseLongAttribute(XmlPullParser parser, String attribute, long def) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800742 final String value = parseStringAttribute(parser, attribute);
743 if (TextUtils.isEmpty(value)) {
Makoto Onukid99c6f02016-03-28 11:02:54 -0700744 return def;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800745 }
746 try {
747 return Long.parseLong(value);
748 } catch (NumberFormatException e) {
749 Slog.e(TAG, "Error parsing long " + value);
Makoto Onukid99c6f02016-03-28 11:02:54 -0700750 return def;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800751 }
752 }
753
754 @Nullable
Makoto Onuki41066a62016-03-09 16:18:44 -0800755 static ComponentName parseComponentNameAttribute(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800756 final String value = parseStringAttribute(parser, attribute);
757 if (TextUtils.isEmpty(value)) {
758 return null;
759 }
760 return ComponentName.unflattenFromString(value);
761 }
762
763 @Nullable
Makoto Onuki440a1ea2016-07-20 14:21:18 -0700764 static Intent parseIntentAttributeNoDefault(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800765 final String value = parseStringAttribute(parser, attribute);
Makoto Onukib5a012f2016-06-21 11:13:53 -0700766 Intent parsed = null;
767 if (!TextUtils.isEmpty(value)) {
768 try {
769 parsed = Intent.parseUri(value, /* flags =*/ 0);
770 } catch (URISyntaxException e) {
771 Slog.e(TAG, "Error parsing intent", e);
772 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800773 }
Makoto Onuki440a1ea2016-07-20 14:21:18 -0700774 return parsed;
775 }
776
777 @Nullable
778 static Intent parseIntentAttribute(XmlPullParser parser, String attribute) {
779 Intent parsed = parseIntentAttributeNoDefault(parser, attribute);
Makoto Onukib5a012f2016-06-21 11:13:53 -0700780 if (parsed == null) {
781 // Default intent.
782 parsed = new Intent(Intent.ACTION_VIEW);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800783 }
Makoto Onukib5a012f2016-06-21 11:13:53 -0700784 return parsed;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800785 }
786
Makoto Onuki41066a62016-03-09 16:18:44 -0800787 static void writeTagValue(XmlSerializer out, String tag, String value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800788 if (TextUtils.isEmpty(value)) return;
789
790 out.startTag(null, tag);
791 out.attribute(null, ATTR_VALUE, value);
792 out.endTag(null, tag);
793 }
794
Makoto Onuki41066a62016-03-09 16:18:44 -0800795 static void writeTagValue(XmlSerializer out, String tag, long value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800796 writeTagValue(out, tag, Long.toString(value));
797 }
798
Makoto Onuki2d5b4652016-03-11 16:09:54 -0800799 static void writeTagValue(XmlSerializer out, String tag, ComponentName name) throws IOException {
800 if (name == null) return;
801 writeTagValue(out, tag, name.flattenToString());
802 }
803
Makoto Onuki41066a62016-03-09 16:18:44 -0800804 static void writeTagExtra(XmlSerializer out, String tag, PersistableBundle bundle)
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800805 throws IOException, XmlPullParserException {
806 if (bundle == null) return;
807
808 out.startTag(null, tag);
809 bundle.saveToXml(out);
810 out.endTag(null, tag);
811 }
812
Makoto Onuki22fcc682016-05-17 14:52:19 -0700813 static void writeAttr(XmlSerializer out, String name, CharSequence value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800814 if (TextUtils.isEmpty(value)) return;
815
Makoto Onuki22fcc682016-05-17 14:52:19 -0700816 out.attribute(null, name, value.toString());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800817 }
818
Makoto Onuki41066a62016-03-09 16:18:44 -0800819 static void writeAttr(XmlSerializer out, String name, long value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800820 writeAttr(out, name, String.valueOf(value));
821 }
822
Makoto Onuki0acbb142016-03-22 17:02:57 -0700823 static void writeAttr(XmlSerializer out, String name, boolean value) throws IOException {
824 if (value) {
825 writeAttr(out, name, "1");
826 }
827 }
828
Makoto Onuki41066a62016-03-09 16:18:44 -0800829 static void writeAttr(XmlSerializer out, String name, ComponentName comp) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800830 if (comp == null) return;
831 writeAttr(out, name, comp.flattenToString());
832 }
833
Makoto Onuki41066a62016-03-09 16:18:44 -0800834 static void writeAttr(XmlSerializer out, String name, Intent intent) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800835 if (intent == null) return;
836
837 writeAttr(out, name, intent.toUri(/* flags =*/ 0));
838 }
839
840 @VisibleForTesting
841 void saveBaseStateLocked() {
842 final AtomicFile file = getBaseStateFile();
843 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700844 Slog.d(TAG, "Saving to " + file.getBaseFile());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800845 }
846
847 FileOutputStream outs = null;
848 try {
849 outs = file.startWrite();
850
851 // Write to XML
852 XmlSerializer out = new FastXmlSerializer();
853 out.setOutput(outs, StandardCharsets.UTF_8.name());
854 out.startDocument(null, true);
855 out.startTag(null, TAG_ROOT);
856
857 // Body.
858 writeTagValue(out, TAG_LAST_RESET_TIME, mRawLastResetTime);
859
860 // Epilogue.
861 out.endTag(null, TAG_ROOT);
862 out.endDocument();
863
864 // Close.
865 file.finishWrite(outs);
866 } catch (IOException e) {
867 Slog.e(TAG, "Failed to write to file " + file.getBaseFile(), e);
868 file.failWrite(outs);
869 }
870 }
871
872 private void loadBaseStateLocked() {
873 mRawLastResetTime = 0;
874
875 final AtomicFile file = getBaseStateFile();
876 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700877 Slog.d(TAG, "Loading from " + file.getBaseFile());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800878 }
879 try (FileInputStream in = file.openRead()) {
880 XmlPullParser parser = Xml.newPullParser();
881 parser.setInput(in, StandardCharsets.UTF_8.name());
882
883 int type;
884 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
885 if (type != XmlPullParser.START_TAG) {
886 continue;
887 }
888 final int depth = parser.getDepth();
889 // Check the root tag
890 final String tag = parser.getName();
891 if (depth == 1) {
892 if (!TAG_ROOT.equals(tag)) {
893 Slog.e(TAG, "Invalid root tag: " + tag);
894 return;
895 }
896 continue;
897 }
898 // Assume depth == 2
899 switch (tag) {
900 case TAG_LAST_RESET_TIME:
901 mRawLastResetTime = parseLongAttribute(parser, ATTR_VALUE);
902 break;
903 default:
904 Slog.e(TAG, "Invalid tag: " + tag);
905 break;
906 }
907 }
908 } catch (FileNotFoundException e) {
909 // Use the default
Makoto Onukib08790c2016-06-23 14:05:46 -0700910 } catch (IOException | XmlPullParserException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800911 Slog.e(TAG, "Failed to read file " + file.getBaseFile(), e);
912
913 mRawLastResetTime = 0;
914 }
915 // Adjust the last reset time.
916 getLastResetTimeLocked();
917 }
918
Makoto Onuki0eed4412016-07-21 11:21:59 -0700919 @VisibleForTesting
920 final File getUserFile(@UserIdInt int userId) {
921 return new File(injectUserDataPath(userId), FILENAME_USER_PACKAGES);
922 }
923
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800924 private void saveUserLocked(@UserIdInt int userId) {
Makoto Onuki0eed4412016-07-21 11:21:59 -0700925 final File path = getUserFile(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800926 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700927 Slog.d(TAG, "Saving to " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800928 }
Makoto Onuki0eed4412016-07-21 11:21:59 -0700929 path.getParentFile().mkdirs();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800930 final AtomicFile file = new AtomicFile(path);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700931 FileOutputStream os = null;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800932 try {
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700933 os = file.startWrite();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800934
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700935 saveUserInternalLocked(userId, os, /* forBackup= */ false);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800936
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700937 file.finishWrite(os);
Makoto Onuki1e173232016-08-10 10:47:13 -0700938
939 // Remove all dangling bitmap files.
940 cleanupDanglingBitmapDirectoriesLocked(userId);
Makoto Onukib08790c2016-06-23 14:05:46 -0700941 } catch (XmlPullParserException | IOException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800942 Slog.e(TAG, "Failed to write to file " + file.getBaseFile(), e);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700943 file.failWrite(os);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800944 }
945 }
946
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700947 private void saveUserInternalLocked(@UserIdInt int userId, OutputStream os,
948 boolean forBackup) throws IOException, XmlPullParserException {
949
950 final BufferedOutputStream bos = new BufferedOutputStream(os);
951
952 // Write to XML
953 XmlSerializer out = new FastXmlSerializer();
954 out.setOutput(bos, StandardCharsets.UTF_8.name());
955 out.startDocument(null, true);
956
Makoto Onukic51b2872016-05-04 15:24:50 -0700957 getUserShortcutsLocked(userId).saveToXml(out, forBackup);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700958
959 out.endDocument();
960
961 bos.flush();
962 os.flush();
963 }
964
Makoto Onuki41066a62016-03-09 16:18:44 -0800965 static IOException throwForInvalidTag(int depth, String tag) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800966 throw new IOException(String.format("Invalid tag '%s' found at depth %d", tag, depth));
967 }
968
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700969 static void warnForInvalidTag(int depth, String tag) throws IOException {
970 Slog.w(TAG, String.format("Invalid tag '%s' found at depth %d", tag, depth));
971 }
972
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800973 @Nullable
Makoto Onuki31459242016-03-22 11:12:18 -0700974 private ShortcutUser loadUserLocked(@UserIdInt int userId) {
Makoto Onuki0eed4412016-07-21 11:21:59 -0700975 final File path = getUserFile(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800976 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700977 Slog.d(TAG, "Loading from " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800978 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800979 final AtomicFile file = new AtomicFile(path);
980
981 final FileInputStream in;
982 try {
983 in = file.openRead();
984 } catch (FileNotFoundException e) {
985 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700986 Slog.d(TAG, "Not found " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800987 }
988 return null;
989 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800990 try {
Makoto Onukib08790c2016-06-23 14:05:46 -0700991 final ShortcutUser ret = loadUserInternal(userId, in, /* forBackup= */ false);
Makoto Onuki6c1dbd52016-05-02 15:19:32 -0700992 return ret;
Makoto Onukifc4cf2d2016-08-24 11:10:26 -0700993 } catch (IOException | XmlPullParserException | InvalidFileFormatException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800994 Slog.e(TAG, "Failed to read file " + file.getBaseFile(), e);
995 return null;
996 } finally {
997 IoUtils.closeQuietly(in);
998 }
999 }
1000
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001001 private ShortcutUser loadUserInternal(@UserIdInt int userId, InputStream is,
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07001002 boolean fromBackup) throws XmlPullParserException, IOException,
1003 InvalidFileFormatException {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001004
1005 final BufferedInputStream bis = new BufferedInputStream(is);
1006
1007 ShortcutUser ret = null;
1008 XmlPullParser parser = Xml.newPullParser();
1009 parser.setInput(bis, StandardCharsets.UTF_8.name());
1010
1011 int type;
1012 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1013 if (type != XmlPullParser.START_TAG) {
1014 continue;
1015 }
1016 final int depth = parser.getDepth();
1017
1018 final String tag = parser.getName();
1019 if (DEBUG_LOAD) {
1020 Slog.d(TAG, String.format("depth=%d type=%d name=%s",
1021 depth, type, tag));
1022 }
1023 if ((depth == 1) && ShortcutUser.TAG_ROOT.equals(tag)) {
1024 ret = ShortcutUser.loadFromXml(this, parser, userId, fromBackup);
1025 continue;
1026 }
1027 throwForInvalidTag(depth, tag);
1028 }
1029 return ret;
1030 }
1031
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001032 private void scheduleSaveBaseState() {
Makoto Onuki0acbb142016-03-22 17:02:57 -07001033 scheduleSaveInner(UserHandle.USER_NULL); // Special case -- use USER_NULL for base state.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001034 }
1035
Makoto Onuki2d5b4652016-03-11 16:09:54 -08001036 void scheduleSaveUser(@UserIdInt int userId) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07001037 scheduleSaveInner(userId);
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001038 }
1039
1040 // In order to re-schedule, we need to reuse the same instance, so keep it in final.
1041 private final Runnable mSaveDirtyInfoRunner = this::saveDirtyInfo;
1042
Makoto Onuki0acbb142016-03-22 17:02:57 -07001043 private void scheduleSaveInner(@UserIdInt int userId) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001044 if (DEBUG) {
1045 Slog.d(TAG, "Scheduling to save for " + userId);
1046 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001047 synchronized (mLock) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001048 if (!mDirtyUserIds.contains(userId)) {
1049 mDirtyUserIds.add(userId);
1050 }
1051 }
1052 // If already scheduled, remove that and re-schedule in N seconds.
1053 mHandler.removeCallbacks(mSaveDirtyInfoRunner);
1054 mHandler.postDelayed(mSaveDirtyInfoRunner, mSaveDelayMillis);
1055 }
1056
1057 @VisibleForTesting
1058 void saveDirtyInfo() {
1059 if (DEBUG) {
1060 Slog.d(TAG, "saveDirtyInfo");
1061 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001062 try {
1063 synchronized (mLock) {
1064 for (int i = mDirtyUserIds.size() - 1; i >= 0; i--) {
1065 final int userId = mDirtyUserIds.get(i);
1066 if (userId == UserHandle.USER_NULL) { // USER_NULL for base state.
1067 saveBaseStateLocked();
1068 } else {
1069 saveUserLocked(userId);
1070 }
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001071 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001072 mDirtyUserIds.clear();
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001073 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001074 } catch (Exception e) {
1075 wtf("Exception in saveDirtyInfo", e);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001076 }
1077 }
1078
1079 /** Return the last reset time. */
1080 long getLastResetTimeLocked() {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001081 updateTimesLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001082 return mRawLastResetTime;
1083 }
1084
1085 /** Return the next reset time. */
1086 long getNextResetTimeLocked() {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001087 updateTimesLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001088 return mRawLastResetTime + mResetInterval;
1089 }
1090
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001091 static boolean isClockValid(long time) {
1092 return time >= 1420070400; // Thu, 01 Jan 2015 00:00:00 GMT
1093 }
1094
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001095 /**
1096 * Update the last reset time.
1097 */
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001098 private void updateTimesLocked() {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001099
1100 final long now = injectCurrentTimeMillis();
1101
1102 final long prevLastResetTime = mRawLastResetTime;
1103
1104 if (mRawLastResetTime == 0) { // first launch.
1105 // TODO Randomize??
1106 mRawLastResetTime = now;
1107 } else if (now < mRawLastResetTime) {
1108 // Clock rewound.
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001109 if (isClockValid(now)) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001110 Slog.w(TAG, "Clock rewound");
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001111 // TODO Randomize??
1112 mRawLastResetTime = now;
1113 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001114 } else {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001115 if ((mRawLastResetTime + mResetInterval) <= now) {
1116 final long offset = mRawLastResetTime % mResetInterval;
1117 mRawLastResetTime = ((now / mResetInterval) * mResetInterval) + offset;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001118 }
1119 }
1120 if (prevLastResetTime != mRawLastResetTime) {
1121 scheduleSaveBaseState();
1122 }
1123 }
1124
Makoto Onuki1e173232016-08-10 10:47:13 -07001125 // Requires mLock held, but "Locked" prefix would look weired so we just say "L".
Makoto Onuki02f338e2016-07-29 09:40:40 -07001126 protected boolean isUserUnlockedL(@UserIdInt int userId) {
Makoto Onuki1e173232016-08-10 10:47:13 -07001127 // First, check the local copy.
1128 if (mUnlockedUsers.get(userId)) {
1129 return true;
1130 }
1131 // If the local copy says the user is locked, check with AM for the actual state, since
1132 // the user might just have been unlocked.
1133 // Note we just don't use isUserUnlockingOrUnlocked() here, because it'll return false
1134 // when the user is STOPPING, which we still want to consider as "unlocked".
1135 final long token = injectClearCallingIdentity();
1136 try {
1137 return mUserManager.isUserUnlockingOrUnlocked(userId);
1138 } finally {
1139 injectRestoreCallingIdentity(token);
1140 }
Makoto Onuki9c850012016-07-26 15:50:50 -07001141 }
1142
Makoto Onuki02f338e2016-07-29 09:40:40 -07001143 // Requires mLock held, but "Locked" prefix would look weired so we jsut say "L".
1144 void throwIfUserLockedL(@UserIdInt int userId) {
1145 if (!isUserUnlockedL(userId)) {
Makoto Onuki9c850012016-07-26 15:50:50 -07001146 throw new IllegalStateException("User " + userId + " is locked or not running");
1147 }
1148 }
1149
Makoto Onukicdc78f72016-03-21 15:47:52 -07001150 @GuardedBy("mLock")
1151 @NonNull
Makoto Onuki2e210c42016-03-30 08:30:36 -07001152 private boolean isUserLoadedLocked(@UserIdInt int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07001153 return mUsers.get(userId) != null;
1154 }
1155
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001156 /** Return the per-user state. */
1157 @GuardedBy("mLock")
1158 @NonNull
Makoto Onuki31459242016-03-22 11:12:18 -07001159 ShortcutUser getUserShortcutsLocked(@UserIdInt int userId) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001160 if (!isUserUnlockedL(userId)) {
Makoto Onuki9c850012016-07-26 15:50:50 -07001161 wtf("User still locked");
Makoto Onuki9c850012016-07-26 15:50:50 -07001162 }
1163
Makoto Onuki31459242016-03-22 11:12:18 -07001164 ShortcutUser userPackages = mUsers.get(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001165 if (userPackages == null) {
1166 userPackages = loadUserLocked(userId);
1167 if (userPackages == null) {
Makoto Onukic51b2872016-05-04 15:24:50 -07001168 userPackages = new ShortcutUser(this, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001169 }
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08001170 mUsers.put(userId, userPackages);
Makoto Onuki085a05c2016-08-19 11:39:29 -07001171
1172 // Also when a user's data is first accessed, scan all packages.
1173 checkPackageChanges(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001174 }
1175 return userPackages;
1176 }
1177
Makoto Onuki2e210c42016-03-30 08:30:36 -07001178 void forEachLoadedUserLocked(@NonNull Consumer<ShortcutUser> c) {
1179 for (int i = mUsers.size() - 1; i >= 0; i--) {
1180 c.accept(mUsers.valueAt(i));
1181 }
1182 }
1183
Makoto Onukic8c33292016-09-12 16:36:59 -07001184 /**
1185 * Return the per-user per-package state. If the caller is a publisher, use
1186 * {@link #getPackageShortcutsForPublisherLocked} instead.
1187 */
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001188 @GuardedBy("mLock")
1189 @NonNull
Makoto Onuki31459242016-03-22 11:12:18 -07001190 ShortcutPackage getPackageShortcutsLocked(
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001191 @NonNull String packageName, @UserIdInt int userId) {
Makoto Onukic51b2872016-05-04 15:24:50 -07001192 return getUserShortcutsLocked(userId).getPackageShortcuts(packageName);
Makoto Onukide667372016-03-15 14:29:20 -07001193 }
1194
Makoto Onukic8c33292016-09-12 16:36:59 -07001195 /** Return the per-user per-package state. Use this when the caller is a publisher. */
1196 @GuardedBy("mLock")
1197 @NonNull
1198 ShortcutPackage getPackageShortcutsForPublisherLocked(
1199 @NonNull String packageName, @UserIdInt int userId) {
1200 final ShortcutPackage ret = getUserShortcutsLocked(userId).getPackageShortcuts(packageName);
1201 ret.getUser().onCalledByPublisher(packageName);
1202 return ret;
1203 }
1204
Makoto Onukide667372016-03-15 14:29:20 -07001205 @GuardedBy("mLock")
1206 @NonNull
Makoto Onuki2e210c42016-03-30 08:30:36 -07001207 ShortcutLauncher getLauncherShortcutsLocked(
1208 @NonNull String packageName, @UserIdInt int ownerUserId,
1209 @UserIdInt int launcherUserId) {
1210 return getUserShortcutsLocked(ownerUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07001211 .getLauncherShortcuts(packageName, launcherUserId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001212 }
1213
1214 // === Caller validation ===
1215
Makoto Onuki55046222016-03-08 10:49:47 -08001216 void removeIcon(@UserIdInt int userId, ShortcutInfo shortcut) {
Makoto Onuki1e173232016-08-10 10:47:13 -07001217 // Do not remove the actual bitmap file yet, because if the device crashes before saving
1218 // he XML we'd lose the icon. We just remove all dangling files after saving the XML.
Makoto Onukidd097812016-06-29 13:10:09 -07001219 shortcut.setIconResourceId(0);
1220 shortcut.setIconResName(null);
Hyunyoung Songf281e7a2017-02-13 10:57:42 -08001221 shortcut.clearFlags(ShortcutInfo.FLAG_HAS_ICON_FILE |
1222 ShortcutInfo.FLAG_MASKABLE_BITMAP | ShortcutInfo.FLAG_HAS_ICON_RES);
Makoto Onuki55046222016-03-08 10:49:47 -08001223 }
1224
Makoto Onuki0033b2a2016-04-14 17:19:16 -07001225 public void cleanupBitmapsForPackage(@UserIdInt int userId, String packageName) {
1226 final File packagePath = new File(getUserBitmapFilePath(userId), packageName);
1227 if (!packagePath.isDirectory()) {
1228 return;
1229 }
1230 if (!(FileUtils.deleteContents(packagePath) && packagePath.delete())) {
1231 Slog.w(TAG, "Unable to remove directory " + packagePath);
1232 }
1233 }
1234
Makoto Onuki1e173232016-08-10 10:47:13 -07001235 private void cleanupDanglingBitmapDirectoriesLocked(@UserIdInt int userId) {
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001236 if (DEBUG) {
1237 Slog.d(TAG, "cleanupDanglingBitmaps: userId=" + userId);
1238 }
1239 final long start = injectElapsedRealtime();
1240
Makoto Onuki1e173232016-08-10 10:47:13 -07001241 final ShortcutUser user = getUserShortcutsLocked(userId);
1242
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001243 final File bitmapDir = getUserBitmapFilePath(userId);
1244 final File[] children = bitmapDir.listFiles();
1245 if (children == null) {
1246 return;
1247 }
1248 for (File child : children) {
1249 if (!child.isDirectory()) {
1250 continue;
1251 }
1252 final String packageName = child.getName();
1253 if (DEBUG) {
1254 Slog.d(TAG, "cleanupDanglingBitmaps: Found directory=" + packageName);
1255 }
1256 if (!user.hasPackage(packageName)) {
1257 if (DEBUG) {
1258 Slog.d(TAG, "Removing dangling bitmap directory: " + packageName);
1259 }
1260 cleanupBitmapsForPackage(userId, packageName);
1261 } else {
1262 cleanupDanglingBitmapFilesLocked(userId, user, packageName, child);
1263 }
1264 }
1265 logDurationStat(Stats.CLEANUP_DANGLING_BITMAPS, start);
1266 }
1267
1268 private void cleanupDanglingBitmapFilesLocked(@UserIdInt int userId, @NonNull ShortcutUser user,
1269 @NonNull String packageName, @NonNull File path) {
1270 final ArraySet<String> usedFiles =
Makoto Onukic51b2872016-05-04 15:24:50 -07001271 user.getPackageShortcuts(packageName).getUsedBitmapFiles();
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001272
1273 for (File child : path.listFiles()) {
1274 if (!child.isFile()) {
1275 continue;
1276 }
1277 final String name = child.getName();
1278 if (!usedFiles.contains(name)) {
1279 if (DEBUG) {
1280 Slog.d(TAG, "Removing dangling bitmap file: " + child.getAbsolutePath());
1281 }
1282 child.delete();
1283 }
1284 }
1285 }
1286
Makoto Onuki55046222016-03-08 10:49:47 -08001287 @VisibleForTesting
1288 static class FileOutputStreamWithPath extends FileOutputStream {
1289 private final File mFile;
1290
1291 public FileOutputStreamWithPath(File file) throws FileNotFoundException {
1292 super(file);
1293 mFile = file;
1294 }
1295
1296 public File getFile() {
1297 return mFile;
1298 }
1299 }
1300
1301 /**
1302 * Build the cached bitmap filename for a shortcut icon.
1303 *
1304 * The filename will be based on the ID, except certain characters will be escaped.
1305 */
1306 @VisibleForTesting
1307 FileOutputStreamWithPath openIconFileForWrite(@UserIdInt int userId, ShortcutInfo shortcut)
1308 throws IOException {
1309 final File packagePath = new File(getUserBitmapFilePath(userId),
Makoto Onuki22fcc682016-05-17 14:52:19 -07001310 shortcut.getPackage());
Makoto Onuki55046222016-03-08 10:49:47 -08001311 if (!packagePath.isDirectory()) {
1312 packagePath.mkdirs();
1313 if (!packagePath.isDirectory()) {
1314 throw new IOException("Unable to create directory " + packagePath);
1315 }
1316 SELinux.restorecon(packagePath);
1317 }
1318
1319 final String baseName = String.valueOf(injectCurrentTimeMillis());
Makoto Onukib08790c2016-06-23 14:05:46 -07001320 for (int suffix = 0; ; suffix++) {
Makoto Onuki55046222016-03-08 10:49:47 -08001321 final String filename = (suffix == 0 ? baseName : baseName + "_" + suffix) + ".png";
1322 final File file = new File(packagePath, filename);
1323 if (!file.exists()) {
1324 if (DEBUG) {
1325 Slog.d(TAG, "Saving icon to " + file.getAbsolutePath());
1326 }
1327 return new FileOutputStreamWithPath(file);
1328 }
1329 }
1330 }
1331
1332 void saveIconAndFixUpShortcut(@UserIdInt int userId, ShortcutInfo shortcut) {
1333 if (shortcut.hasIconFile() || shortcut.hasIconResource()) {
1334 return;
1335 }
1336
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001337 final long token = injectClearCallingIdentity();
Makoto Onuki55046222016-03-08 10:49:47 -08001338 try {
1339 // Clear icon info on the shortcut.
Makoto Onukidd097812016-06-29 13:10:09 -07001340 removeIcon(userId, shortcut);
Makoto Onuki55046222016-03-08 10:49:47 -08001341
1342 final Icon icon = shortcut.getIcon();
1343 if (icon == null) {
1344 return; // has no icon
1345 }
1346
Makoto Onukiabe84422016-04-07 09:41:19 -07001347 Bitmap bitmap;
Makoto Onuki55046222016-03-08 10:49:47 -08001348 try {
1349 switch (icon.getType()) {
1350 case Icon.TYPE_RESOURCE: {
1351 injectValidateIconResPackage(shortcut, icon);
1352
1353 shortcut.setIconResourceId(icon.getResId());
1354 shortcut.addFlags(ShortcutInfo.FLAG_HAS_ICON_RES);
1355 return;
1356 }
Hyunyoung Songf281e7a2017-02-13 10:57:42 -08001357 case Icon.TYPE_BITMAP:
1358 case Icon.TYPE_BITMAP_MASKABLE: {
Makoto Onukiabe84422016-04-07 09:41:19 -07001359 bitmap = icon.getBitmap(); // Don't recycle in this case.
Makoto Onuki55046222016-03-08 10:49:47 -08001360 break;
1361 }
Makoto Onuki55046222016-03-08 10:49:47 -08001362 default:
1363 // This shouldn't happen because we've already validated the icon, but
1364 // just in case.
1365 throw ShortcutInfo.getInvalidIconException();
1366 }
1367 if (bitmap == null) {
1368 Slog.e(TAG, "Null bitmap detected");
1369 return;
1370 }
1371 // Shrink and write to the file.
1372 File path = null;
1373 try {
1374 final FileOutputStreamWithPath out = openIconFileForWrite(userId, shortcut);
1375 try {
1376 path = out.getFile();
1377
Makoto Onukiabe84422016-04-07 09:41:19 -07001378 Bitmap shrunk = shrinkBitmap(bitmap, mMaxIconDimension);
1379 try {
1380 shrunk.compress(mIconPersistFormat, mIconPersistQuality, out);
1381 } finally {
1382 if (bitmap != shrunk) {
1383 shrunk.recycle();
1384 }
1385 }
Makoto Onuki55046222016-03-08 10:49:47 -08001386
1387 shortcut.setBitmapPath(out.getFile().getAbsolutePath());
1388 shortcut.addFlags(ShortcutInfo.FLAG_HAS_ICON_FILE);
Hyunyoung Songf281e7a2017-02-13 10:57:42 -08001389 if (icon.getType() == Icon.TYPE_BITMAP_MASKABLE) {
1390 shortcut.addFlags(ShortcutInfo.FLAG_MASKABLE_BITMAP);
1391 }
Makoto Onuki55046222016-03-08 10:49:47 -08001392 } finally {
1393 IoUtils.closeQuietly(out);
1394 }
Makoto Onukib08790c2016-06-23 14:05:46 -07001395 } catch (IOException | RuntimeException e) {
Makoto Onuki55046222016-03-08 10:49:47 -08001396 // STOPSHIP Change wtf to e
1397 Slog.wtf(ShortcutService.TAG, "Unable to write bitmap to file", e);
1398 if (path != null && path.exists()) {
1399 path.delete();
1400 }
1401 }
1402 } finally {
Makoto Onuki55046222016-03-08 10:49:47 -08001403 // Once saved, we won't use the original icon information, so null it out.
1404 shortcut.clearIcon();
1405 }
1406 } finally {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001407 injectRestoreCallingIdentity(token);
Makoto Onuki55046222016-03-08 10:49:47 -08001408 }
1409 }
1410
1411 // Unfortunately we can't do this check in unit tests because we fake creator package names,
1412 // so override in unit tests.
1413 // TODO CTS this case.
1414 void injectValidateIconResPackage(ShortcutInfo shortcut, Icon icon) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07001415 if (!shortcut.getPackage().equals(icon.getResPackage())) {
Makoto Onuki55046222016-03-08 10:49:47 -08001416 throw new IllegalArgumentException(
1417 "Icon resource must reside in shortcut owner package");
1418 }
1419 }
1420
1421 @VisibleForTesting
1422 static Bitmap shrinkBitmap(Bitmap in, int maxSize) {
1423 // Original width/height.
1424 final int ow = in.getWidth();
1425 final int oh = in.getHeight();
1426 if ((ow <= maxSize) && (oh <= maxSize)) {
1427 if (DEBUG) {
1428 Slog.d(TAG, String.format("Icon size %dx%d, no need to shrink", ow, oh));
1429 }
1430 return in;
1431 }
1432 final int longerDimension = Math.max(ow, oh);
1433
1434 // New width and height.
1435 final int nw = ow * maxSize / longerDimension;
1436 final int nh = oh * maxSize / longerDimension;
1437 if (DEBUG) {
1438 Slog.d(TAG, String.format("Icon size %dx%d, shrinking to %dx%d",
1439 ow, oh, nw, nh));
1440 }
1441
1442 final Bitmap scaledBitmap = Bitmap.createBitmap(nw, nh, Bitmap.Config.ARGB_8888);
1443 final Canvas c = new Canvas(scaledBitmap);
1444
1445 final RectF dst = new RectF(0, 0, nw, nh);
1446
1447 c.drawBitmap(in, /*src=*/ null, dst, /* paint =*/ null);
1448
Makoto Onuki55046222016-03-08 10:49:47 -08001449 return scaledBitmap;
1450 }
1451
Makoto Onuki157b1622016-06-02 16:13:10 -07001452 /**
1453 * For a shortcut, update all resource names from resource IDs, and also update all
1454 * resource-based strings.
1455 */
1456 void fixUpShortcutResourceNamesAndValues(ShortcutInfo si) {
1457 final Resources publisherRes = injectGetResourcesForApplicationAsUser(
1458 si.getPackage(), si.getUserId());
1459 if (publisherRes != null) {
1460 final long start = injectElapsedRealtime();
1461 try {
1462 si.lookupAndFillInResourceNames(publisherRes);
1463 } finally {
1464 logDurationStat(Stats.RESOURCE_NAME_LOOKUP, start);
1465 }
1466 si.resolveResourceStrings(publisherRes);
1467 }
1468 }
1469
Makoto Onuki55046222016-03-08 10:49:47 -08001470 // === Caller validation ===
1471
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001472 private boolean isCallerSystem() {
1473 final int callingUid = injectBinderCallingUid();
Makoto Onukib08790c2016-06-23 14:05:46 -07001474 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001475 }
1476
1477 private boolean isCallerShell() {
1478 final int callingUid = injectBinderCallingUid();
1479 return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
1480 }
1481
1482 private void enforceSystemOrShell() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001483 if (!(isCallerSystem() || isCallerShell())) {
1484 throw new SecurityException("Caller must be system or shell");
1485 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001486 }
1487
1488 private void enforceShell() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001489 if (!isCallerShell()) {
1490 throw new SecurityException("Caller must be shell");
1491 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001492 }
1493
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001494 private void enforceSystem() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001495 if (!isCallerSystem()) {
1496 throw new SecurityException("Caller must be system");
1497 }
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001498 }
1499
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001500 private void enforceResetThrottlingPermission() {
1501 if (isCallerSystem()) {
1502 return;
1503 }
Makoto Onuki76269922016-07-15 14:58:54 -07001504 enforceCallingOrSelfPermission(
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001505 android.Manifest.permission.RESET_SHORTCUT_MANAGER_THROTTLING, null);
1506 }
1507
Makoto Onuki76269922016-07-15 14:58:54 -07001508 private void enforceCallingOrSelfPermission(
1509 @NonNull String permission, @Nullable String message) {
1510 if (isCallerSystem()) {
1511 return;
1512 }
1513 injectEnforceCallingPermission(permission, message);
1514 }
1515
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001516 /**
1517 * Somehow overriding ServiceContext.enforceCallingPermission() in the unit tests would confuse
1518 * mockito. So instead we extracted it here and override it in the tests.
1519 */
1520 @VisibleForTesting
1521 void injectEnforceCallingPermission(
1522 @NonNull String permission, @Nullable String message) {
1523 mContext.enforceCallingPermission(permission, message);
1524 }
1525
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001526 private void verifyCaller(@NonNull String packageName, @UserIdInt int userId) {
1527 Preconditions.checkStringNotEmpty(packageName, "packageName");
1528
1529 if (isCallerSystem()) {
1530 return; // no check
1531 }
1532
1533 final int callingUid = injectBinderCallingUid();
1534
1535 // Otherwise, make sure the arguments are valid.
1536 if (UserHandle.getUserId(callingUid) != userId) {
1537 throw new SecurityException("Invalid user-ID");
1538 }
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08001539 if (injectGetPackageUid(packageName, userId) != callingUid) {
1540 throw new SecurityException("Calling package name mismatch");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001541 }
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08001542 Preconditions.checkState(!isEphemeralApp(packageName, userId),
1543 "Ephemeral apps can't use ShortcutManager");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001544 }
1545
Makoto Onuki157b1622016-06-02 16:13:10 -07001546 // Overridden in unit tests to execute r synchronously.
1547 void injectPostToHandler(Runnable r) {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001548 mHandler.post(r);
1549 }
1550
Makoto Onuki085a05c2016-08-19 11:39:29 -07001551 void injectRunOnNewThread(Runnable r) {
1552 new Thread(r).start();
1553 }
1554
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001555 /**
Makoto Onuki7001a612016-05-27 13:24:28 -07001556 * @throws IllegalArgumentException if {@code numShortcuts} is bigger than
Makoto Onukib08790c2016-06-23 14:05:46 -07001557 * {@link #getMaxActivityShortcuts()}.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001558 */
Makoto Onuki7001a612016-05-27 13:24:28 -07001559 void enforceMaxActivityShortcuts(int numShortcuts) {
Makoto Onukib5a012f2016-06-21 11:13:53 -07001560 if (numShortcuts > mMaxShortcuts) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001561 throw new IllegalArgumentException("Max number of dynamic shortcuts exceeded");
1562 }
1563 }
1564
1565 /**
Makoto Onuki7001a612016-05-27 13:24:28 -07001566 * Return the max number of dynamic + manifest shortcuts for each launcher icon.
1567 */
1568 int getMaxActivityShortcuts() {
Makoto Onukib5a012f2016-06-21 11:13:53 -07001569 return mMaxShortcuts;
Makoto Onuki7001a612016-05-27 13:24:28 -07001570 }
1571
1572 /**
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001573 * - Sends a notification to LauncherApps
1574 * - Write to file
1575 */
Makoto Onuki39686e82016-04-13 18:03:00 -07001576 void packageShortcutsChanged(@NonNull String packageName, @UserIdInt int userId) {
1577 if (DEBUG) {
1578 Slog.d(TAG, String.format(
1579 "Shortcut changes: package=%s, user=%d", packageName, userId));
1580 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001581 notifyListeners(packageName, userId);
1582 scheduleSaveUser(userId);
1583 }
1584
1585 private void notifyListeners(@NonNull String packageName, @UserIdInt int userId) {
Makoto Onuki157b1622016-06-02 16:13:10 -07001586 injectPostToHandler(() -> {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001587 try {
1588 final ArrayList<ShortcutChangeListener> copy;
1589 synchronized (mLock) {
1590 if (!isUserUnlockedL(userId)) {
1591 return;
1592 }
1593
1594 copy = new ArrayList<>(mListeners);
1595 }
1596 // Note onShortcutChanged() needs to be called with the system service permissions.
1597 for (int i = copy.size() - 1; i >= 0; i--) {
1598 copy.get(i).onShortcutChanged(packageName, userId);
1599 }
1600 } catch (Exception ignore) {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001601 }
1602 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001603 }
1604
1605 /**
1606 * Clean up / validate an incoming shortcut.
1607 * - Make sure all mandatory fields are set.
1608 * - Make sure the intent's extras are persistable, and them to set
Makoto Onuki0eed4412016-07-21 11:21:59 -07001609 * {@link ShortcutInfo#mIntentPersistableExtrases}. Also clear its extras.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001610 * - Clear flags.
1611 */
Makoto Onuki2d895c32016-12-02 15:48:40 -08001612 private void fixUpIncomingShortcutInfo(@NonNull ShortcutInfo shortcut, boolean forUpdate,
1613 boolean forPinRequest) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001614 Preconditions.checkNotNull(shortcut, "Null shortcut detected");
Makoto Onuki255461f2017-01-10 11:47:25 -08001615 if (shortcut.getActivity() != null) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001616 Preconditions.checkState(
Makoto Onuki22fcc682016-05-17 14:52:19 -07001617 shortcut.getPackage().equals(shortcut.getActivity().getPackageName()),
Makoto Onukib08790c2016-06-23 14:05:46 -07001618 "Cannot publish shortcut: activity " + shortcut.getActivity() + " does not"
1619 + " belong to package " + shortcut.getPackage());
Makoto Onuki13260b6ff2016-07-13 18:03:13 -07001620 Preconditions.checkState(
1621 injectIsMainActivity(shortcut.getActivity(), shortcut.getUserId()),
1622 "Cannot publish shortcut: activity " + shortcut.getActivity() + " is not"
1623 + " main activity");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001624 }
1625
Makoto Onuki55046222016-03-08 10:49:47 -08001626 if (!forUpdate) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08001627 shortcut.enforceMandatoryFields(/* forPinned= */ forPinRequest);
1628 if (!forPinRequest) {
Makoto Onuki255461f2017-01-10 11:47:25 -08001629 Preconditions.checkState(shortcut.getActivity() != null,
1630 "Cannot publish shortcut: target activity is not set");
Makoto Onuki2d895c32016-12-02 15:48:40 -08001631 }
Makoto Onuki55046222016-03-08 10:49:47 -08001632 }
1633 if (shortcut.getIcon() != null) {
1634 ShortcutInfo.validateIcon(shortcut.getIcon());
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001635 }
1636
Makoto Onukide667372016-03-15 14:29:20 -07001637 shortcut.replaceFlags(0);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001638 }
1639
Makoto Onuki2d895c32016-12-02 15:48:40 -08001640 private void fixUpIncomingShortcutInfo(@NonNull ShortcutInfo shortcut, boolean forUpdate) {
1641 fixUpIncomingShortcutInfo(shortcut, forUpdate, /*forPinRequest=*/ false);
1642 }
1643
1644 public void validateShortcutForPinRequest(@NonNull ShortcutInfo shortcut) {
1645 fixUpIncomingShortcutInfo(shortcut, /* forUpdate= */ false, /*forPinRequest=*/ true);
1646 }
1647
Makoto Onukib08790c2016-06-23 14:05:46 -07001648 /**
1649 * When a shortcut has no target activity, set the default one from the package.
1650 */
1651 private void fillInDefaultActivity(List<ShortcutInfo> shortcuts) {
Makoto Onukib08790c2016-06-23 14:05:46 -07001652 ComponentName defaultActivity = null;
1653 for (int i = shortcuts.size() - 1; i >= 0; i--) {
1654 final ShortcutInfo si = shortcuts.get(i);
1655 if (si.getActivity() == null) {
1656 if (defaultActivity == null) {
1657 defaultActivity = injectGetDefaultMainActivity(
1658 si.getPackage(), si.getUserId());
1659 Preconditions.checkState(defaultActivity != null,
1660 "Launcher activity not found for package " + si.getPackage());
1661 }
1662 si.setActivity(defaultActivity);
1663 }
1664 }
1665 }
1666
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001667 private void assignImplicitRanks(List<ShortcutInfo> shortcuts) {
1668 for (int i = shortcuts.size() - 1; i >= 0; i--) {
1669 shortcuts.get(i).setImplicitRank(i);
1670 }
1671 }
1672
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001673 // === APIs ===
1674
1675 @Override
1676 public boolean setDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1677 @UserIdInt int userId) {
1678 verifyCaller(packageName, userId);
1679
1680 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
1681 final int size = newShortcuts.size();
1682
1683 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001684 throwIfUserLockedL(userId);
1685
Makoto Onukic8c33292016-09-12 16:36:59 -07001686 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001687
Makoto Onuki22fcc682016-05-17 14:52:19 -07001688 ps.ensureImmutableShortcutsNotIncluded(newShortcuts);
1689
Makoto Onukib08790c2016-06-23 14:05:46 -07001690 fillInDefaultActivity(newShortcuts);
1691
Makoto Onuki7001a612016-05-27 13:24:28 -07001692 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_SET);
1693
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001694 // Throttling.
Makoto Onukic51b2872016-05-04 15:24:50 -07001695 if (!ps.tryApiCall()) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001696 return false;
1697 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001698
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001699 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1700 ps.clearAllImplicitRanks();
1701 assignImplicitRanks(newShortcuts);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001702
Makoto Onukidf6da042016-06-16 09:51:40 -07001703 for (int i = 0; i < size; i++) {
1704 fixUpIncomingShortcutInfo(newShortcuts.get(i), /* forUpdate= */ false);
1705 }
1706
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001707 // First, remove all un-pinned; dynamic shortcuts
Makoto Onukic51b2872016-05-04 15:24:50 -07001708 ps.deleteAllDynamicShortcuts();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001709
1710 // Then, add/update all. We need to make sure to take over "pinned" flag.
1711 for (int i = 0; i < size; i++) {
1712 final ShortcutInfo newShortcut = newShortcuts.get(i);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001713 ps.addOrUpdateDynamicShortcut(newShortcut);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001714 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001715
1716 // Lastly, adjust the ranks.
1717 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001718 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001719 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001720
1721 verifyStates();
1722
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001723 return true;
1724 }
1725
1726 @Override
1727 public boolean updateShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1728 @UserIdInt int userId) {
1729 verifyCaller(packageName, userId);
1730
1731 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
Makoto Onuki55046222016-03-08 10:49:47 -08001732 final int size = newShortcuts.size();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001733
1734 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001735 throwIfUserLockedL(userId);
1736
Makoto Onukic8c33292016-09-12 16:36:59 -07001737 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001738
Makoto Onuki22fcc682016-05-17 14:52:19 -07001739 ps.ensureImmutableShortcutsNotIncluded(newShortcuts);
1740
Makoto Onukib08790c2016-06-23 14:05:46 -07001741 // For update, don't fill in the default activity. Having null activity means
1742 // "don't update the activity" here.
1743
Makoto Onuki7001a612016-05-27 13:24:28 -07001744 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_UPDATE);
1745
Makoto Onuki55046222016-03-08 10:49:47 -08001746 // Throttling.
Makoto Onukic51b2872016-05-04 15:24:50 -07001747 if (!ps.tryApiCall()) {
Makoto Onuki55046222016-03-08 10:49:47 -08001748 return false;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001749 }
1750
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001751 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1752 ps.clearAllImplicitRanks();
1753 assignImplicitRanks(newShortcuts);
1754
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -08001755 // TODO: Consider removing Chooser fields. If so, the FLAG_CHOOSER should be removed
Makoto Onuki55046222016-03-08 10:49:47 -08001756 for (int i = 0; i < size; i++) {
1757 final ShortcutInfo source = newShortcuts.get(i);
1758 fixUpIncomingShortcutInfo(source, /* forUpdate= */ true);
1759
1760 final ShortcutInfo target = ps.findShortcutById(source.getId());
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001761 if (target == null) {
1762 continue;
1763 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07001764
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001765 if (target.isEnabled() != source.isEnabled()) {
1766 Slog.w(TAG,
1767 "ShortcutInfo.enabled cannot be changed with updateShortcuts()");
1768 }
Makoto Onuki55046222016-03-08 10:49:47 -08001769
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001770 // When updating the rank, we need to insert between existing ranks, so set
1771 // this setRankChanged, and also copy the implicit rank fo adjustRanks().
1772 if (source.hasRank()) {
1773 target.setRankChanged();
1774 target.setImplicitRank(source.getImplicitRank());
1775 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07001776
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001777 final boolean replacingIcon = (source.getIcon() != null);
1778 if (replacingIcon) {
1779 removeIcon(userId, target);
1780 }
Makoto Onuki55046222016-03-08 10:49:47 -08001781
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001782 // Note copyNonNullFieldsFrom() does the "updatable with?" check too.
1783 target.copyNonNullFieldsFrom(source);
1784 target.setTimestamp(injectCurrentTimeMillis());
1785
1786 if (replacingIcon) {
1787 saveIconAndFixUpShortcut(userId, target);
1788 }
1789
1790 // When we're updating any resource related fields, re-extract the res names and
1791 // the values.
1792 if (replacingIcon || source.hasStringResources()) {
1793 fixUpShortcutResourceNamesAndValues(target);
Makoto Onuki55046222016-03-08 10:49:47 -08001794 }
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -08001795
1796 // While updating, we keep the dynamic flag as it previously was, but refresh the
1797 // chooser flag.
1798 // TODO: If we support clearing Chooser fields, we should also remove the flag.
1799 if (target.getChooserIntentFilters() != null) {
1800 target.addFlags(ShortcutInfo.FLAG_CHOOSER);
1801 }
Makoto Onuki55046222016-03-08 10:49:47 -08001802 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001803
1804 // Lastly, adjust the ranks.
1805 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001806 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001807 packageShortcutsChanged(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001808
Makoto Onuki7001a612016-05-27 13:24:28 -07001809 verifyStates();
1810
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001811 return true;
1812 }
1813
1814 @Override
Makoto Onukib6d35232016-04-04 15:57:17 -07001815 public boolean addDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001816 @UserIdInt int userId) {
1817 verifyCaller(packageName, userId);
1818
Makoto Onukib6d35232016-04-04 15:57:17 -07001819 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
1820 final int size = newShortcuts.size();
1821
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001822 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001823 throwIfUserLockedL(userId);
1824
Makoto Onukic8c33292016-09-12 16:36:59 -07001825 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001826
Makoto Onuki22fcc682016-05-17 14:52:19 -07001827 ps.ensureImmutableShortcutsNotIncluded(newShortcuts);
1828
Makoto Onukib08790c2016-06-23 14:05:46 -07001829 fillInDefaultActivity(newShortcuts);
1830
Makoto Onuki7001a612016-05-27 13:24:28 -07001831 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_ADD);
1832
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001833 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1834 ps.clearAllImplicitRanks();
1835 assignImplicitRanks(newShortcuts);
1836
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001837 // Throttling.
Makoto Onukic51b2872016-05-04 15:24:50 -07001838 if (!ps.tryApiCall()) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001839 return false;
1840 }
Makoto Onukib6d35232016-04-04 15:57:17 -07001841 for (int i = 0; i < size; i++) {
1842 final ShortcutInfo newShortcut = newShortcuts.get(i);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001843
Makoto Onukib6d35232016-04-04 15:57:17 -07001844 // Validate the shortcut.
1845 fixUpIncomingShortcutInfo(newShortcut, /* forUpdate= */ false);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001846
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001847 // When ranks are changing, we need to insert between ranks, so set the
1848 // "rank changed" flag.
1849 newShortcut.setRankChanged();
1850
Makoto Onukib6d35232016-04-04 15:57:17 -07001851 // Add it.
Makoto Onuki22fcc682016-05-17 14:52:19 -07001852 ps.addOrUpdateDynamicShortcut(newShortcut);
Makoto Onukib6d35232016-04-04 15:57:17 -07001853 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001854
1855 // Lastly, adjust the ranks.
1856 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001857 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001858 packageShortcutsChanged(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001859
Makoto Onuki7001a612016-05-27 13:24:28 -07001860 verifyStates();
1861
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001862 return true;
1863 }
1864
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -08001865 // TODO: Ensure non-launchable shortcuts can not be pinned
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001866 @Override
Makoto Onuki2d895c32016-12-02 15:48:40 -08001867 public boolean requestPinShortcut(String packageName, ShortcutInfo shortcut,
1868 IntentSender resultIntent, int userId) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08001869 Preconditions.checkNotNull(shortcut);
1870 Preconditions.checkArgument(shortcut.isEnabled(), "Shortcut must be enabled");
Sunny Goyal87a563e2017-01-01 19:42:45 -08001871 return requestPinItem(packageName, userId, shortcut, null, resultIntent);
1872 }
1873
Sunny Goyala6be88a2017-01-12 16:27:58 -08001874 @Override
1875 public Intent createShortcutResultIntent(String packageName, ShortcutInfo shortcut, int userId)
1876 throws RemoteException {
1877 Preconditions.checkNotNull(shortcut);
1878 Preconditions.checkArgument(shortcut.isEnabled(), "Shortcut must be enabled");
1879 verifyCaller(packageName, userId);
1880
1881 final Intent ret;
1882 synchronized (mLock) {
1883 throwIfUserLockedL(userId);
1884
1885 // Send request to the launcher, if supported.
1886 ret = mShortcutRequestPinProcessor.createShortcutResultIntent(shortcut, userId);
1887 }
1888
1889 verifyStates();
1890 return ret;
1891 }
1892
Sunny Goyal87a563e2017-01-01 19:42:45 -08001893 /**
1894 * Handles {@link #requestPinShortcut} and {@link ShortcutServiceInternal#requestPinAppWidget}.
1895 * After validating the caller, it passes the request to {@link #mShortcutRequestPinProcessor}.
1896 * Either {@param shortcut} or {@param appWidget} should be non-null.
1897 */
1898 private boolean requestPinItem(String packageName, int userId,
1899 ShortcutInfo shortcut, AppWidgetProviderInfo appWidget, IntentSender resultIntent) {
1900 verifyCaller(packageName, userId);
Makoto Onuki2d895c32016-12-02 15:48:40 -08001901
1902 final boolean ret;
1903 synchronized (mLock) {
1904 throwIfUserLockedL(userId);
1905
Makoto Onukia01f4f02016-12-15 15:58:41 -08001906 Preconditions.checkState(isUidForegroundLocked(injectBinderCallingUid()),
Makoto Onuki255461f2017-01-10 11:47:25 -08001907 "Calling application must have a foreground activity or a foreground service");
Makoto Onuki2d895c32016-12-02 15:48:40 -08001908
1909 // Send request to the launcher, if supported.
Sunny Goyal87a563e2017-01-01 19:42:45 -08001910 ret = mShortcutRequestPinProcessor.requestPinItemLocked(shortcut, appWidget, userId,
1911 resultIntent);
Makoto Onuki2d895c32016-12-02 15:48:40 -08001912 }
1913
1914 verifyStates();
1915
1916 return ret;
1917 }
1918
1919 @Override
Makoto Onuki20c95f82016-05-11 16:51:01 -07001920 public void disableShortcuts(String packageName, List shortcutIds,
Makoto Onukid6880792016-06-29 13:37:43 -07001921 CharSequence disabledMessage, int disabledMessageResId, @UserIdInt int userId) {
Makoto Onuki20c95f82016-05-11 16:51:01 -07001922 verifyCaller(packageName, userId);
1923 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
1924
1925 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001926 throwIfUserLockedL(userId);
1927
Makoto Onukic8c33292016-09-12 16:36:59 -07001928 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001929
1930 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds);
1931
Makoto Onukid6880792016-06-29 13:37:43 -07001932 final String disabledMessageString =
1933 (disabledMessage == null) ? null : disabledMessage.toString();
1934
Makoto Onuki22fcc682016-05-17 14:52:19 -07001935 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
1936 ps.disableWithId(Preconditions.checkStringNotEmpty((String) shortcutIds.get(i)),
Makoto Onukid6880792016-06-29 13:37:43 -07001937 disabledMessageString, disabledMessageResId,
Makoto Onuki22fcc682016-05-17 14:52:19 -07001938 /* overrideImmutable=*/ false);
1939 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001940
1941 // We may have removed dynamic shortcuts which may have left a gap, so adjust the ranks.
1942 ps.adjustRanks();
Makoto Onuki22fcc682016-05-17 14:52:19 -07001943 }
1944 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001945
1946 verifyStates();
Makoto Onuki22fcc682016-05-17 14:52:19 -07001947 }
1948
1949 @Override
1950 public void enableShortcuts(String packageName, List shortcutIds, @UserIdInt int userId) {
1951 verifyCaller(packageName, userId);
1952 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
1953
1954 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001955 throwIfUserLockedL(userId);
1956
Makoto Onukic8c33292016-09-12 16:36:59 -07001957 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001958
1959 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds);
1960
1961 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
1962 ps.enableWithId((String) shortcutIds.get(i));
1963 }
Makoto Onuki20c95f82016-05-11 16:51:01 -07001964 }
1965 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001966
1967 verifyStates();
Makoto Onuki20c95f82016-05-11 16:51:01 -07001968 }
1969
1970 @Override
Makoto Onukib6d35232016-04-04 15:57:17 -07001971 public void removeDynamicShortcuts(String packageName, List shortcutIds,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001972 @UserIdInt int userId) {
1973 verifyCaller(packageName, userId);
Makoto Onukib6d35232016-04-04 15:57:17 -07001974 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001975
1976 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001977 throwIfUserLockedL(userId);
1978
Makoto Onukic8c33292016-09-12 16:36:59 -07001979 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001980
1981 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds);
1982
Makoto Onukib6d35232016-04-04 15:57:17 -07001983 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07001984 ps.deleteDynamicWithId(
Makoto Onukib6d35232016-04-04 15:57:17 -07001985 Preconditions.checkStringNotEmpty((String) shortcutIds.get(i)));
1986 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001987
1988 // We may have removed dynamic shortcuts which may have left a gap, so adjust the ranks.
1989 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001990 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001991 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001992
1993 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001994 }
1995
1996 @Override
Makoto Onukib6d35232016-04-04 15:57:17 -07001997 public void removeAllDynamicShortcuts(String packageName, @UserIdInt int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001998 verifyCaller(packageName, userId);
1999
2000 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002001 throwIfUserLockedL(userId);
2002
Makoto Onukic8c33292016-09-12 16:36:59 -07002003 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002004 ps.deleteAllDynamicShortcuts();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002005 }
Makoto Onuki39686e82016-04-13 18:03:00 -07002006 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07002007
2008 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002009 }
2010
2011 @Override
2012 public ParceledListSlice<ShortcutInfo> getDynamicShortcuts(String packageName,
2013 @UserIdInt int userId) {
2014 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002015
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002016 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002017 throwIfUserLockedL(userId);
2018
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002019 return getShortcutsWithQueryLocked(
2020 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -08002021 ShortcutInfo::isDynamicOrChooser);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002022 }
2023 }
2024
2025 @Override
Makoto Onuki22fcc682016-05-17 14:52:19 -07002026 public ParceledListSlice<ShortcutInfo> getManifestShortcuts(String packageName,
2027 @UserIdInt int userId) {
2028 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002029
Makoto Onuki22fcc682016-05-17 14:52:19 -07002030 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002031 throwIfUserLockedL(userId);
2032
Makoto Onuki22fcc682016-05-17 14:52:19 -07002033 return getShortcutsWithQueryLocked(
2034 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
2035 ShortcutInfo::isManifestShortcut);
2036 }
2037 }
2038
2039 @Override
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002040 public ParceledListSlice<ShortcutInfo> getPinnedShortcuts(String packageName,
2041 @UserIdInt int userId) {
2042 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002043
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002044 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002045 throwIfUserLockedL(userId);
2046
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002047 return getShortcutsWithQueryLocked(
2048 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
2049 ShortcutInfo::isPinned);
2050 }
2051 }
2052
2053 private ParceledListSlice<ShortcutInfo> getShortcutsWithQueryLocked(@NonNull String packageName,
2054 @UserIdInt int userId, int cloneFlags, @NonNull Predicate<ShortcutInfo> query) {
2055
2056 final ArrayList<ShortcutInfo> ret = new ArrayList<>();
2057
Makoto Onukic8c33292016-09-12 16:36:59 -07002058 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002059 ps.findAll(ret, query, cloneFlags);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002060
2061 return new ParceledListSlice<>(ret);
2062 }
2063
2064 @Override
Makoto Onukid6880792016-06-29 13:37:43 -07002065 public int getMaxShortcutCountPerActivity(String packageName, @UserIdInt int userId)
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002066 throws RemoteException {
2067 verifyCaller(packageName, userId);
2068
Makoto Onukib5a012f2016-06-21 11:13:53 -07002069 return mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002070 }
2071
2072 @Override
2073 public int getRemainingCallCount(String packageName, @UserIdInt int userId) {
2074 verifyCaller(packageName, userId);
2075
2076 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002077 throwIfUserLockedL(userId);
2078
Makoto Onukic8c33292016-09-12 16:36:59 -07002079 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002080 return mMaxUpdatesPerInterval - ps.getApiCallCount();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002081 }
2082 }
2083
2084 @Override
2085 public long getRateLimitResetTime(String packageName, @UserIdInt int userId) {
2086 verifyCaller(packageName, userId);
2087
2088 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002089 throwIfUserLockedL(userId);
2090
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002091 return getNextResetTimeLocked();
2092 }
2093 }
2094
Makoto Onuki55046222016-03-08 10:49:47 -08002095 @Override
Makoto Onuki20c95f82016-05-11 16:51:01 -07002096 public int getIconMaxDimensions(String packageName, int userId) {
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002097 verifyCaller(packageName, userId);
2098
Makoto Onuki55046222016-03-08 10:49:47 -08002099 synchronized (mLock) {
2100 return mMaxIconDimension;
2101 }
2102 }
2103
Makoto Onuki20c95f82016-05-11 16:51:01 -07002104 @Override
2105 public void reportShortcutUsed(String packageName, String shortcutId, int userId) {
2106 verifyCaller(packageName, userId);
2107
Makoto Onukiac042502016-05-20 16:39:42 -07002108 Preconditions.checkNotNull(shortcutId);
2109
2110 if (DEBUG) {
2111 Slog.d(TAG, String.format("reportShortcutUsed: Shortcut %s package %s used on user %d",
2112 shortcutId, packageName, userId));
2113 }
2114
2115 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002116 throwIfUserLockedL(userId);
2117
Makoto Onukic8c33292016-09-12 16:36:59 -07002118 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002119
Makoto Onukiac042502016-05-20 16:39:42 -07002120 if (ps.findShortcutById(shortcutId) == null) {
2121 Log.w(TAG, String.format("reportShortcutUsed: package %s doesn't have shortcut %s",
2122 packageName, shortcutId));
2123 return;
2124 }
2125 }
2126
2127 final long token = injectClearCallingIdentity();
2128 try {
2129 mUsageStatsManagerInternal.reportShortcutUsage(packageName, shortcutId, userId);
2130 } finally {
2131 injectRestoreCallingIdentity(token);
2132 }
Makoto Onuki20c95f82016-05-11 16:51:01 -07002133 }
2134
Makoto Onuki2d895c32016-12-02 15:48:40 -08002135 @Override
Sunny Goyal7f7372a2017-01-24 11:53:54 -08002136 public boolean isRequestPinItemSupported(int callingUserId, int requestType) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08002137 final long token = injectClearCallingIdentity();
2138 try {
Sunny Goyal7f7372a2017-01-24 11:53:54 -08002139 return mShortcutRequestPinProcessor
2140 .isRequestPinItemSupported(callingUserId, requestType);
Makoto Onuki2d895c32016-12-02 15:48:40 -08002141 } finally {
2142 injectRestoreCallingIdentity(token);
2143 }
2144 }
2145
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002146 /**
Makoto Onukib08790c2016-06-23 14:05:46 -07002147 * Reset all throttling, for developer options and command line. Only system/shell can call
2148 * it.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002149 */
2150 @Override
2151 public void resetThrottling() {
2152 enforceSystemOrShell();
2153
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002154 resetThrottlingInner(getCallingUserId());
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002155 }
2156
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002157 void resetThrottlingInner(@UserIdInt int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002158 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002159 if (!isUserUnlockedL(userId)) {
2160 Log.w(TAG, "User " + userId + " is locked or not running");
2161 return;
2162 }
2163
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002164 getUserShortcutsLocked(userId).resetThrottling();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002165 }
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002166 scheduleSaveUser(userId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002167 Slog.i(TAG, "ShortcutManager: throttling counter reset for user " + userId);
2168 }
2169
2170 void resetAllThrottlingInner() {
2171 synchronized (mLock) {
2172 mRawLastResetTime = injectCurrentTimeMillis();
2173 }
2174 scheduleSaveBaseState();
2175 Slog.i(TAG, "ShortcutManager: throttling counter reset for all users");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002176 }
2177
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002178 @Override
2179 public void onApplicationActive(String packageName, int userId) {
2180 if (DEBUG) {
2181 Slog.d(TAG, "onApplicationActive: package=" + packageName + " userid=" + userId);
2182 }
2183 enforceResetThrottlingPermission();
Makoto Onuki02f338e2016-07-29 09:40:40 -07002184
2185 synchronized (mLock) {
2186 if (!isUserUnlockedL(userId)) {
2187 // This is called by system UI, so no need to throw. Just ignore.
2188 return;
2189 }
2190
2191 getPackageShortcutsLocked(packageName, userId)
2192 .resetRateLimitingForCommandLineNoSaving();
2193 saveUserLocked(userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002194 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002195 }
2196
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002197 // We override this method in unit tests to do a simpler check.
2198 boolean hasShortcutHostPermission(@NonNull String callingPackage, int userId) {
Makoto Onuki10305202016-07-14 18:14:08 -07002199 final long start = injectElapsedRealtime();
2200 try {
2201 return hasShortcutHostPermissionInner(callingPackage, userId);
2202 } finally {
2203 logDurationStat(Stats.LAUNCHER_PERMISSION_CHECK, start);
2204 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002205 }
2206
2207 // This method is extracted so we can directly call this method from unit tests,
2208 // even when hasShortcutPermission() is overridden.
2209 @VisibleForTesting
Makoto Onuki2d895c32016-12-02 15:48:40 -08002210 boolean hasShortcutHostPermissionInner(@NonNull String packageName, int userId) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002211 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002212 throwIfUserLockedL(userId);
2213
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -08002214 // For the chooser, we just check is the system is calling.
2215 // STOPSHIP: We need to implement a new permission here rather than this terrible check.
2216 // The packageName check is to try to distinguish between when an actual
2217 // launcher is making the call, and when it's the system.
2218 if (isCallerSystem() && packageName.equals("android")) {
2219 return true;
2220 }
2221
Makoto Onuki31459242016-03-22 11:12:18 -07002222 final ShortcutUser user = getUserShortcutsLocked(userId);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002223
Makoto Onuki2d895c32016-12-02 15:48:40 -08002224 // Always trust the cached component.
Makoto Onuki10305202016-07-14 18:14:08 -07002225 final ComponentName cached = user.getCachedLauncher();
2226 if (cached != null) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08002227 if (cached.getPackageName().equals(packageName)) {
Makoto Onuki10305202016-07-14 18:14:08 -07002228 return true;
2229 }
2230 }
2231 // If the cached one doesn't match, then go ahead
2232
Makoto Onuki2d895c32016-12-02 15:48:40 -08002233 final ComponentName detected = getDefaultLauncher(userId);
Makoto Onuki2e210c42016-03-30 08:30:36 -07002234
Makoto Onuki10305202016-07-14 18:14:08 -07002235 // Update the cache.
2236 user.setLauncher(detected);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002237 if (detected != null) {
2238 if (DEBUG) {
2239 Slog.v(TAG, "Detected launcher: " + detected);
2240 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08002241 return detected.getPackageName().equals(packageName);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002242 } else {
2243 // Default launcher not found.
2244 return false;
2245 }
2246 }
2247 }
2248
Makoto Onuki2d895c32016-12-02 15:48:40 -08002249 @Nullable
2250 ComponentName getDefaultLauncher(@UserIdInt int userId) {
2251 final long start = injectElapsedRealtime();
2252 final long token = injectClearCallingIdentity();
2253 try {
2254 synchronized (mLock) {
2255 throwIfUserLockedL(userId);
2256
2257 final ShortcutUser user = getUserShortcutsLocked(userId);
2258
2259 final List<ResolveInfo> allHomeCandidates = new ArrayList<>();
2260
2261 // Default launcher from package manager.
2262 final long startGetHomeActivitiesAsUser = injectElapsedRealtime();
2263 final ComponentName defaultLauncher = mPackageManagerInternal
2264 .getHomeActivitiesAsUser(allHomeCandidates, userId);
2265 logDurationStat(Stats.GET_DEFAULT_HOME, startGetHomeActivitiesAsUser);
2266
2267 ComponentName detected = null;
2268 if (defaultLauncher != null) {
2269 detected = defaultLauncher;
2270 if (DEBUG) {
2271 Slog.v(TAG, "Default launcher from PM: " + detected);
2272 }
2273 } else {
2274 detected = user.getLastKnownLauncher();
2275
2276 if (detected != null) {
2277 if (injectIsActivityEnabledAndExported(detected, userId)) {
2278 if (DEBUG) {
2279 Slog.v(TAG, "Cached launcher: " + detected);
2280 }
2281 } else {
2282 Slog.w(TAG, "Cached launcher " + detected + " no longer exists");
2283 detected = null;
2284 user.clearLauncher();
2285 }
2286 }
2287 }
2288
2289 if (detected == null) {
2290 // If we reach here, that means it's the first check since the user was created,
2291 // and there's already multiple launchers and there's no default set.
2292 // Find the system one with the highest priority.
2293 // (We need to check the priority too because of FallbackHome in Settings.)
2294 // If there's no system launcher yet, then no one can access shortcuts, until
2295 // the user explicitly
2296 final int size = allHomeCandidates.size();
2297
2298 int lastPriority = Integer.MIN_VALUE;
2299 for (int i = 0; i < size; i++) {
2300 final ResolveInfo ri = allHomeCandidates.get(i);
2301 if (!ri.activityInfo.applicationInfo.isSystemApp()) {
2302 continue;
2303 }
2304 if (DEBUG) {
2305 Slog.d(TAG, String.format("hasShortcutPermissionInner: pkg=%s prio=%d",
2306 ri.activityInfo.getComponentName(), ri.priority));
2307 }
2308 if (ri.priority < lastPriority) {
2309 continue;
2310 }
2311 detected = ri.activityInfo.getComponentName();
2312 lastPriority = ri.priority;
2313 }
2314 }
2315 return detected;
2316 }
2317 } finally {
2318 injectRestoreCallingIdentity(token);
2319 logDurationStat(Stats.GET_DEFAULT_LAUNCHER, start);
2320 }
2321 }
2322
Makoto Onukicdc78f72016-03-21 15:47:52 -07002323 // === House keeping ===
2324
Makoto Onukib08790c2016-06-23 14:05:46 -07002325 private void cleanUpPackageForAllLoadedUsers(String packageName, @UserIdInt int packageUserId,
2326 boolean appStillExists) {
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002327 synchronized (mLock) {
2328 forEachLoadedUserLocked(user ->
Makoto Onukib08790c2016-06-23 14:05:46 -07002329 cleanUpPackageLocked(packageName, user.getUserId(), packageUserId,
2330 appStillExists));
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002331 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002332 }
2333
Makoto Onuki2e210c42016-03-30 08:30:36 -07002334 /**
2335 * Remove all the information associated with a package. This will really remove all the
2336 * information, including the restore information (i.e. it'll remove packages even if they're
2337 * shadow).
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002338 *
2339 * This is called when an app is uninstalled, or an app gets "clear data"ed.
Makoto Onuki2e210c42016-03-30 08:30:36 -07002340 */
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002341 @VisibleForTesting
Makoto Onukib08790c2016-06-23 14:05:46 -07002342 void cleanUpPackageLocked(String packageName, int owningUserId, int packageUserId,
2343 boolean appStillExists) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002344 final boolean wasUserLoaded = isUserLoadedLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002345
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002346 final ShortcutUser user = getUserShortcutsLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002347 boolean doNotify = false;
2348
2349 // First, remove the package from the package list (if the package is a publisher).
Makoto Onukid99c6f02016-03-28 11:02:54 -07002350 if (packageUserId == owningUserId) {
Makoto Onukic51b2872016-05-04 15:24:50 -07002351 if (user.removePackage(packageName) != null) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002352 doNotify = true;
2353 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07002354 }
Makoto Onukid99c6f02016-03-28 11:02:54 -07002355
Makoto Onukicdc78f72016-03-21 15:47:52 -07002356 // Also remove from the launcher list (if the package is a launcher).
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002357 user.removeLauncher(packageUserId, packageName);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002358
2359 // Then remove pinned shortcuts from all launchers.
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002360 user.forAllLaunchers(l -> l.cleanUpPackage(packageName, packageUserId));
2361
2362 // Now there may be orphan shortcuts because we removed pinned shortcuts at the previous
Makoto Onukicdc78f72016-03-21 15:47:52 -07002363 // step. Remove them too.
Makoto Onukic51b2872016-05-04 15:24:50 -07002364 user.forAllPackages(p -> p.refreshPinnedFlags());
Makoto Onukicdc78f72016-03-21 15:47:52 -07002365
Makoto Onukid99c6f02016-03-28 11:02:54 -07002366 scheduleSaveUser(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002367
2368 if (doNotify) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002369 notifyListeners(packageName, owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002370 }
2371
Makoto Onukib08790c2016-06-23 14:05:46 -07002372 // If the app still exists (i.e. data cleared), we need to re-publish manifest shortcuts.
2373 if (appStillExists && (packageUserId == owningUserId)) {
2374 // This will do the notification and save when needed, so do it after the above
2375 // notifyListeners.
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002376 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07002377 }
2378
Makoto Onukicdc78f72016-03-21 15:47:52 -07002379 if (!wasUserLoaded) {
2380 // Note this will execute the scheduled save.
Makoto Onukid99c6f02016-03-28 11:02:54 -07002381 unloadUserLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002382 }
2383 }
2384
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002385 /**
2386 * Entry point from {@link LauncherApps}.
2387 */
2388 private class LocalService extends ShortcutServiceInternal {
Makoto Onuki2e210c42016-03-30 08:30:36 -07002389
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002390 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002391 public List<ShortcutInfo> getShortcuts(int launcherUserId,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002392 @NonNull String callingPackage, long changedSince,
Makoto Onukiabe84422016-04-07 09:41:19 -07002393 @Nullable String packageName, @Nullable List<String> shortcutIds,
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -08002394 @Nullable ComponentName componentName, @Nullable Intent intent,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002395 int queryFlags, int userId) {
2396 final ArrayList<ShortcutInfo> ret = new ArrayList<>();
Makoto Onuki9c850012016-07-26 15:50:50 -07002397
Makoto Onuki20c95f82016-05-11 16:51:01 -07002398 final boolean cloneKeyFieldOnly =
2399 ((queryFlags & ShortcutQuery.FLAG_GET_KEY_FIELDS_ONLY) != 0);
2400 final int cloneFlag = cloneKeyFieldOnly ? ShortcutInfo.CLONE_REMOVE_NON_KEY_INFO
2401 : ShortcutInfo.CLONE_REMOVE_FOR_LAUNCHER;
Makoto Onukiabe84422016-04-07 09:41:19 -07002402 if (packageName == null) {
2403 shortcutIds = null; // LauncherAppsService already threw for it though.
2404 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002405
2406 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002407 throwIfUserLockedL(userId);
2408 throwIfUserLockedL(launcherUserId);
2409
Makoto Onuki2e210c42016-03-30 08:30:36 -07002410 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002411 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002412
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002413 if (packageName != null) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002414 getShortcutsInnerLocked(launcherUserId,
Makoto Onukiabe84422016-04-07 09:41:19 -07002415 callingPackage, packageName, shortcutIds, changedSince,
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -08002416 componentName, intent, queryFlags, userId, ret, cloneFlag);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002417 } else {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002418 final List<String> shortcutIdsF = shortcutIds;
2419 getUserShortcutsLocked(userId).forAllPackages(p -> {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002420 getShortcutsInnerLocked(launcherUserId,
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002421 callingPackage, p.getPackageName(), shortcutIdsF, changedSince,
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -08002422 componentName, intent, queryFlags, userId, ret, cloneFlag);
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002423 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002424 }
2425 }
2426 return ret;
2427 }
2428
Makoto Onukid99c6f02016-03-28 11:02:54 -07002429 private void getShortcutsInnerLocked(int launcherUserId, @NonNull String callingPackage,
Makoto Onukiabe84422016-04-07 09:41:19 -07002430 @Nullable String packageName, @Nullable List<String> shortcutIds, long changedSince,
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -08002431 @Nullable ComponentName componentName, Intent intent, int queryFlags,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002432 int userId, ArrayList<ShortcutInfo> ret, int cloneFlag) {
Makoto Onukiabe84422016-04-07 09:41:19 -07002433 final ArraySet<String> ids = shortcutIds == null ? null
2434 : new ArraySet<>(shortcutIds);
2435
Makoto Onukic51b2872016-05-04 15:24:50 -07002436 final ShortcutPackage p = getUserShortcutsLocked(userId)
2437 .getPackageShortcutsIfExists(packageName);
2438 if (p == null) {
2439 return; // No need to instantiate ShortcutPackage.
2440 }
2441
2442 p.findAll(ret,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002443 (ShortcutInfo si) -> {
2444 if (si.getLastChangedTimestamp() < changedSince) {
2445 return false;
2446 }
Makoto Onukiabe84422016-04-07 09:41:19 -07002447 if (ids != null && !ids.contains(si.getId())) {
2448 return false;
2449 }
Makoto Onuki85694522016-05-04 12:53:37 -07002450 if (componentName != null) {
Makoto Onuki9fd90192017-01-06 18:31:03 +00002451 if (si.getActivity() != null
2452 && !si.getActivity().equals(componentName)) {
Makoto Onuki85694522016-05-04 12:53:37 -07002453 return false;
2454 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002455 }
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -08002456 if (intent != null
2457 && !si.hasMatchingFilter(mContext.getContentResolver(), intent)) {
2458 return false;
2459 }
2460
2461 if (((queryFlags & ShortcutQuery.FLAG_MATCH_CHOOSER) != 0)
2462 && si.isChooser()) {
2463 return true;
2464 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002465 if (((queryFlags & ShortcutQuery.FLAG_GET_DYNAMIC) != 0)
2466 && si.isDynamic()) {
2467 return true;
2468 }
2469 if (((queryFlags & ShortcutQuery.FLAG_GET_PINNED) != 0)
2470 && si.isPinned()) {
2471 return true;
2472 }
2473 if (((queryFlags & ShortcutQuery.FLAG_GET_MANIFEST) != 0)
2474 && si.isManifestShortcut()) {
2475 return true;
2476 }
2477 return false;
Makoto Onukid99c6f02016-03-28 11:02:54 -07002478 }, cloneFlag, callingPackage, launcherUserId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002479 }
2480
2481 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002482 public boolean isPinnedByCaller(int launcherUserId, @NonNull String callingPackage,
2483 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2484 Preconditions.checkStringNotEmpty(packageName, "packageName");
2485 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
2486
2487 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002488 throwIfUserLockedL(userId);
2489 throwIfUserLockedL(launcherUserId);
2490
Makoto Onuki2e210c42016-03-30 08:30:36 -07002491 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002492 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002493
Makoto Onukid99c6f02016-03-28 11:02:54 -07002494 final ShortcutInfo si = getShortcutInfoLocked(
2495 launcherUserId, callingPackage, packageName, shortcutId, userId);
2496 return si != null && si.isPinned();
2497 }
2498 }
2499
Makoto Onuki2e210c42016-03-30 08:30:36 -07002500 private ShortcutInfo getShortcutInfoLocked(
Makoto Onukid99c6f02016-03-28 11:02:54 -07002501 int launcherUserId, @NonNull String callingPackage,
2502 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2503 Preconditions.checkStringNotEmpty(packageName, "packageName");
2504 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
2505
Makoto Onuki02f338e2016-07-29 09:40:40 -07002506 throwIfUserLockedL(userId);
2507 throwIfUserLockedL(launcherUserId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002508
Makoto Onukic51b2872016-05-04 15:24:50 -07002509 final ShortcutPackage p = getUserShortcutsLocked(userId)
2510 .getPackageShortcutsIfExists(packageName);
2511 if (p == null) {
2512 return null;
2513 }
2514
Makoto Onukid99c6f02016-03-28 11:02:54 -07002515 final ArrayList<ShortcutInfo> list = new ArrayList<>(1);
Makoto Onukic51b2872016-05-04 15:24:50 -07002516 p.findAll(list,
Makoto Onukid99c6f02016-03-28 11:02:54 -07002517 (ShortcutInfo si) -> shortcutId.equals(si.getId()),
2518 /* clone flags=*/ 0, callingPackage, launcherUserId);
2519 return list.size() == 0 ? null : list.get(0);
2520 }
2521
2522 @Override
2523 public void pinShortcuts(int launcherUserId,
2524 @NonNull String callingPackage, @NonNull String packageName,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002525 @NonNull List<String> shortcutIds, int userId) {
2526 // Calling permission must be checked by LauncherAppsImpl.
2527 Preconditions.checkStringNotEmpty(packageName, "packageName");
2528 Preconditions.checkNotNull(shortcutIds, "shortcutIds");
2529
2530 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002531 throwIfUserLockedL(userId);
2532 throwIfUserLockedL(launcherUserId);
2533
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002534 final ShortcutLauncher launcher =
Makoto Onuki2e210c42016-03-30 08:30:36 -07002535 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId);
Makoto Onukic51b2872016-05-04 15:24:50 -07002536 launcher.attemptToRestoreIfNeededAndSave();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002537
Makoto Onukic51b2872016-05-04 15:24:50 -07002538 launcher.pinShortcuts(userId, packageName, shortcutIds);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002539 }
Makoto Onuki39686e82016-04-13 18:03:00 -07002540 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07002541
2542 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002543 }
2544
2545 @Override
Makoto Onuki440a1ea2016-07-20 14:21:18 -07002546 public Intent[] createShortcutIntents(int launcherUserId,
Makoto Onukid99c6f02016-03-28 11:02:54 -07002547 @NonNull String callingPackage,
Makoto Onuki43204b82016-03-08 16:16:44 -08002548 @NonNull String packageName, @NonNull String shortcutId, int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002549 // Calling permission must be checked by LauncherAppsImpl.
Makoto Onuki43204b82016-03-08 16:16:44 -08002550 Preconditions.checkStringNotEmpty(packageName, "packageName can't be empty");
2551 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId can't be empty");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002552
2553 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002554 throwIfUserLockedL(userId);
2555 throwIfUserLockedL(launcherUserId);
2556
Makoto Onuki2e210c42016-03-30 08:30:36 -07002557 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002558 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002559
Makoto Onukid99c6f02016-03-28 11:02:54 -07002560 // Make sure the shortcut is actually visible to the launcher.
2561 final ShortcutInfo si = getShortcutInfoLocked(
2562 launcherUserId, callingPackage, packageName, shortcutId, userId);
2563 // "si == null" should suffice here, but check the flags too just to make sure.
Makoto Onuki22fcc682016-05-17 14:52:19 -07002564 if (si == null || !si.isEnabled() || !si.isAlive()) {
Makoto Onuki83f6d2d2016-07-11 14:30:19 -07002565 Log.e(TAG, "Shortcut " + shortcutId + " does not exist or disabled");
Makoto Onukid99c6f02016-03-28 11:02:54 -07002566 return null;
2567 }
Makoto Onuki440a1ea2016-07-20 14:21:18 -07002568 return si.getIntents();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002569 }
2570 }
2571
2572 @Override
2573 public void addListener(@NonNull ShortcutChangeListener listener) {
2574 synchronized (mLock) {
2575 mListeners.add(Preconditions.checkNotNull(listener));
2576 }
2577 }
Makoto Onuki55046222016-03-08 10:49:47 -08002578
2579 @Override
Makoto Onukiabe84422016-04-07 09:41:19 -07002580 public int getShortcutIconResId(int launcherUserId, @NonNull String callingPackage,
2581 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2582 Preconditions.checkNotNull(callingPackage, "callingPackage");
2583 Preconditions.checkNotNull(packageName, "packageName");
2584 Preconditions.checkNotNull(shortcutId, "shortcutId");
Makoto Onuki55046222016-03-08 10:49:47 -08002585
2586 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002587 throwIfUserLockedL(userId);
2588 throwIfUserLockedL(launcherUserId);
2589
Makoto Onuki2e210c42016-03-30 08:30:36 -07002590 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002591 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002592
Makoto Onukic51b2872016-05-04 15:24:50 -07002593 final ShortcutPackage p = getUserShortcutsLocked(userId)
2594 .getPackageShortcutsIfExists(packageName);
2595 if (p == null) {
2596 return 0;
2597 }
2598
2599 final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId);
Makoto Onuki55046222016-03-08 10:49:47 -08002600 return (shortcutInfo != null && shortcutInfo.hasIconResource())
2601 ? shortcutInfo.getIconResourceId() : 0;
2602 }
2603 }
2604
2605 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002606 public ParcelFileDescriptor getShortcutIconFd(int launcherUserId,
Makoto Onukiabe84422016-04-07 09:41:19 -07002607 @NonNull String callingPackage, @NonNull String packageName,
2608 @NonNull String shortcutId, int userId) {
2609 Preconditions.checkNotNull(callingPackage, "callingPackage");
2610 Preconditions.checkNotNull(packageName, "packageName");
2611 Preconditions.checkNotNull(shortcutId, "shortcutId");
Makoto Onuki55046222016-03-08 10:49:47 -08002612
2613 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002614 throwIfUserLockedL(userId);
2615 throwIfUserLockedL(launcherUserId);
2616
Makoto Onuki2e210c42016-03-30 08:30:36 -07002617 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002618 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002619
Makoto Onukic51b2872016-05-04 15:24:50 -07002620 final ShortcutPackage p = getUserShortcutsLocked(userId)
2621 .getPackageShortcutsIfExists(packageName);
2622 if (p == null) {
2623 return null;
2624 }
2625
2626 final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId);
Makoto Onuki55046222016-03-08 10:49:47 -08002627 if (shortcutInfo == null || !shortcutInfo.hasIconFile()) {
2628 return null;
2629 }
2630 try {
Makoto Onuki34d1c912016-03-10 14:24:58 -08002631 if (shortcutInfo.getBitmapPath() == null) {
2632 Slog.w(TAG, "null bitmap detected in getShortcutIconFd()");
2633 return null;
2634 }
Makoto Onuki55046222016-03-08 10:49:47 -08002635 return ParcelFileDescriptor.open(
2636 new File(shortcutInfo.getBitmapPath()),
2637 ParcelFileDescriptor.MODE_READ_ONLY);
2638 } catch (FileNotFoundException e) {
2639 Slog.e(TAG, "Icon file not found: " + shortcutInfo.getBitmapPath());
2640 return null;
2641 }
2642 }
2643 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002644
2645 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002646 public boolean hasShortcutHostPermission(int launcherUserId,
2647 @NonNull String callingPackage) {
2648 return ShortcutService.this.hasShortcutHostPermission(callingPackage, launcherUserId);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002649 }
Sunny Goyal87a563e2017-01-01 19:42:45 -08002650
2651 @Override
2652 public boolean requestPinAppWidget(@NonNull String callingPackage,
2653 @NonNull AppWidgetProviderInfo appWidget, @Nullable IntentSender resultIntent,
2654 int userId) {
2655 Preconditions.checkNotNull(appWidget);
2656 return requestPinItem(callingPackage, userId, null, appWidget, resultIntent);
2657 }
Sunny Goyal7f7372a2017-01-24 11:53:54 -08002658
2659 @Override
2660 public boolean isRequestPinItemSupported(int callingUserId, int requestType) {
2661 return ShortcutService.this.isRequestPinItemSupported(callingUserId, requestType);
2662 }
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002663 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002664
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002665 final BroadcastReceiver mReceiver = new BroadcastReceiver() {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002666 @Override
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002667 public void onReceive(Context context, Intent intent) {
2668 if (!mBootCompleted.get()) {
2669 return; // Boot not completed, ignore the broadcast.
2670 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07002671 try {
2672 if (Intent.ACTION_LOCALE_CHANGED.equals(intent.getAction())) {
2673 handleLocaleChanged();
2674 }
2675 } catch (Exception e) {
2676 wtf("Exception in mReceiver.onReceive", e);
Makoto Onukic51b2872016-05-04 15:24:50 -07002677 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002678 }
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002679 };
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002680
Makoto Onuki157b1622016-06-02 16:13:10 -07002681 void handleLocaleChanged() {
2682 if (DEBUG) {
2683 Slog.d(TAG, "handleLocaleChanged");
2684 }
2685 scheduleSaveBaseState();
2686
Makoto Onuki02f338e2016-07-29 09:40:40 -07002687 synchronized (mLock) {
2688 final long token = injectClearCallingIdentity();
2689 try {
2690 forEachLoadedUserLocked(user -> user.detectLocaleChange());
2691 } finally {
2692 injectRestoreCallingIdentity(token);
2693 }
Makoto Onuki157b1622016-06-02 16:13:10 -07002694 }
2695 }
2696
Makoto Onukif34c3082016-07-13 10:25:25 -07002697 /**
2698 * Package event callbacks.
2699 */
2700 @VisibleForTesting
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002701 final BroadcastReceiver mPackageMonitor = new BroadcastReceiver() {
Makoto Onukif34c3082016-07-13 10:25:25 -07002702 @Override
2703 public void onReceive(Context context, Intent intent) {
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002704 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
2705 if (userId == UserHandle.USER_NULL) {
2706 Slog.w(TAG, "Intent broadcast does not contain user handle: " + intent);
2707 return;
2708 }
2709
2710 final String action = intent.getAction();
2711
2712 // This is normally called on Handler, so clearCallingIdentity() isn't needed,
2713 // but we still check it in unit tests.
Makoto Onukif34c3082016-07-13 10:25:25 -07002714 final long token = injectClearCallingIdentity();
2715 try {
Makoto Onuki10305202016-07-14 18:14:08 -07002716 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002717 if (!isUserUnlockedL(userId)) {
2718 if (DEBUG) {
2719 Slog.d(TAG, "Ignoring package broadcast " + action
2720 + " for locked/stopped user " + userId);
2721 }
2722 return;
2723 }
2724
2725 // Whenever we get one of those package broadcasts, or get
2726 // ACTION_PREFERRED_ACTIVITY_CHANGED, we purge the default launcher cache.
Makoto Onuki10305202016-07-14 18:14:08 -07002727 final ShortcutUser user = getUserShortcutsLocked(userId);
2728 user.clearLauncher();
2729 }
2730 if (Intent.ACTION_PREFERRED_ACTIVITY_CHANGED.equals(action)) {
2731 // Nothing farther to do.
2732 return;
2733 }
2734
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002735 final Uri intentUri = intent.getData();
2736 final String packageName = (intentUri != null) ? intentUri.getSchemeSpecificPart()
2737 : null;
2738 if (packageName == null) {
2739 Slog.w(TAG, "Intent broadcast does not contain package name: " + intent);
2740 return;
2741 }
2742
2743 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
2744
2745 switch (action) {
2746 case Intent.ACTION_PACKAGE_ADDED:
2747 if (replacing) {
2748 handlePackageUpdateFinished(packageName, userId);
2749 } else {
2750 handlePackageAdded(packageName, userId);
2751 }
2752 break;
2753 case Intent.ACTION_PACKAGE_REMOVED:
2754 if (!replacing) {
2755 handlePackageRemoved(packageName, userId);
2756 }
2757 break;
2758 case Intent.ACTION_PACKAGE_CHANGED:
2759 handlePackageChanged(packageName, userId);
2760
2761 break;
2762 case Intent.ACTION_PACKAGE_DATA_CLEARED:
2763 handlePackageDataCleared(packageName, userId);
2764 break;
2765 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07002766 } catch (Exception e) {
2767 wtf("Exception in mPackageMonitor.onReceive", e);
Makoto Onukif34c3082016-07-13 10:25:25 -07002768 } finally {
2769 injectRestoreCallingIdentity(token);
Makoto Onukia2241832016-07-06 13:28:37 -07002770 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07002771 }
Makoto Onukif34c3082016-07-13 10:25:25 -07002772 };
Makoto Onukicdc78f72016-03-21 15:47:52 -07002773
Makoto Onuki0acbb142016-03-22 17:02:57 -07002774 /**
Makoto Onuki39686e82016-04-13 18:03:00 -07002775 * Called when a user is unlocked.
2776 * - Check all known packages still exist, and otherwise perform cleanup.
2777 * - If a package still exists, check the version code. If it's been updated, may need to
Makoto Onukib08790c2016-06-23 14:05:46 -07002778 * update timestamps of its shortcuts.
Makoto Onuki0acbb142016-03-22 17:02:57 -07002779 */
Makoto Onukid99c6f02016-03-28 11:02:54 -07002780 @VisibleForTesting
Makoto Onuki39686e82016-04-13 18:03:00 -07002781 void checkPackageChanges(@UserIdInt int ownerUserId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07002782 if (DEBUG) {
Makoto Onuki39686e82016-04-13 18:03:00 -07002783 Slog.d(TAG, "checkPackageChanges() ownerUserId=" + ownerUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002784 }
Makoto Onukib08790c2016-06-23 14:05:46 -07002785 if (injectIsSafeModeEnabled()) {
2786 Slog.i(TAG, "Safe mode, skipping checkPackageChanges()");
2787 return;
2788 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07002789
Makoto Onuki22fcc682016-05-17 14:52:19 -07002790 final long start = injectElapsedRealtime();
2791 try {
2792 final ArrayList<PackageWithUser> gonePackages = new ArrayList<>();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002793
Makoto Onuki22fcc682016-05-17 14:52:19 -07002794 synchronized (mLock) {
2795 final ShortcutUser user = getUserShortcutsLocked(ownerUserId);
2796
2797 // Find packages that have been uninstalled.
2798 user.forAllPackageItems(spi -> {
2799 if (spi.getPackageInfo().isShadow()) {
2800 return; // Don't delete shadow information.
2801 }
2802 if (!isPackageInstalled(spi.getPackageName(), spi.getPackageUserId())) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002803 if (DEBUG) {
2804 Slog.d(TAG, "Uninstalled: " + spi.getPackageName()
2805 + " user " + spi.getPackageUserId());
2806 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002807 gonePackages.add(PackageWithUser.of(spi));
2808 }
2809 });
2810 if (gonePackages.size() > 0) {
2811 for (int i = gonePackages.size() - 1; i >= 0; i--) {
2812 final PackageWithUser pu = gonePackages.get(i);
Makoto Onukib08790c2016-06-23 14:05:46 -07002813 cleanUpPackageLocked(pu.packageName, ownerUserId, pu.userId,
2814 /* appStillExists = */ false);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002815 }
Makoto Onukid99c6f02016-03-28 11:02:54 -07002816 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002817
Makoto Onuki248a0ef2016-11-03 15:59:01 -07002818 rescanUpdatedPackagesLocked(ownerUserId, user.getLastAppScanTime());
Makoto Onuki0acbb142016-03-22 17:02:57 -07002819 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002820 } finally {
2821 logDurationStat(Stats.CHECK_PACKAGE_CHANGES, start);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002822 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002823 verifyStates();
Makoto Onukicdc78f72016-03-21 15:47:52 -07002824 }
2825
Makoto Onuki248a0ef2016-11-03 15:59:01 -07002826 private void rescanUpdatedPackagesLocked(@UserIdInt int userId, long lastScanTime) {
Makoto Onuki377b7972016-08-09 14:43:55 -07002827 final ShortcutUser user = getUserShortcutsLocked(userId);
2828
Makoto Onuki33663282016-08-22 16:19:04 -07002829 // Note after each OTA, we'll need to rescan all system apps, as their lastUpdateTime
2830 // is not reliable.
Makoto Onuki377b7972016-08-09 14:43:55 -07002831 final long now = injectCurrentTimeMillis();
Makoto Onuki33663282016-08-22 16:19:04 -07002832 final boolean afterOta =
2833 !injectBuildFingerprint().equals(user.getLastAppScanOsFingerprint());
Makoto Onuki377b7972016-08-09 14:43:55 -07002834
2835 // Then for each installed app, publish manifest shortcuts when needed.
Makoto Onuki33663282016-08-22 16:19:04 -07002836 forUpdatedPackages(userId, lastScanTime, afterOta, ai -> {
Makoto Onuki377b7972016-08-09 14:43:55 -07002837 user.attemptToRestoreIfNeededAndSave(this, ai.packageName, userId);
Makoto Onuki248a0ef2016-11-03 15:59:01 -07002838
2839 user.rescanPackageIfNeeded(ai.packageName, /* forceRescan= */ true);
Makoto Onuki377b7972016-08-09 14:43:55 -07002840 });
2841
2842 // Write the time just before the scan, because there may be apps that have just
2843 // been updated, and we want to catch them in the next time.
2844 user.setLastAppScanTime(now);
Makoto Onuki33663282016-08-22 16:19:04 -07002845 user.setLastAppScanOsFingerprint(injectBuildFingerprint());
Makoto Onuki377b7972016-08-09 14:43:55 -07002846 scheduleSaveUser(userId);
2847 }
2848
Makoto Onuki0acbb142016-03-22 17:02:57 -07002849 private void handlePackageAdded(String packageName, @UserIdInt int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07002850 if (DEBUG) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07002851 Slog.d(TAG, String.format("handlePackageAdded: %s user=%d", packageName, userId));
2852 }
2853 synchronized (mLock) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002854 final ShortcutUser user = getUserShortcutsLocked(userId);
2855 user.attemptToRestoreIfNeededAndSave(this, packageName, userId);
Makoto Onuki64183d52016-08-08 14:11:34 -07002856 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002857 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002858 verifyStates();
Makoto Onuki0acbb142016-03-22 17:02:57 -07002859 }
2860
2861 private void handlePackageUpdateFinished(String packageName, @UserIdInt int userId) {
Makoto Onuki905e8852016-03-28 10:40:58 -07002862 if (DEBUG) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002863 Slog.d(TAG, String.format("handlePackageUpdateFinished: %s user=%d",
2864 packageName, userId));
Makoto Onuki0acbb142016-03-22 17:02:57 -07002865 }
2866 synchronized (mLock) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002867 final ShortcutUser user = getUserShortcutsLocked(userId);
2868 user.attemptToRestoreIfNeededAndSave(this, packageName, userId);
Makoto Onuki39686e82016-04-13 18:03:00 -07002869
Makoto Onuki22fcc682016-05-17 14:52:19 -07002870 if (isPackageInstalled(packageName, userId)) {
Makoto Onuki64183d52016-08-08 14:11:34 -07002871 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onuki39686e82016-04-13 18:03:00 -07002872 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07002873 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002874 verifyStates();
Makoto Onuki0acbb142016-03-22 17:02:57 -07002875 }
2876
Makoto Onuki2e210c42016-03-30 08:30:36 -07002877 private void handlePackageRemoved(String packageName, @UserIdInt int packageUserId) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07002878 if (DEBUG) {
Makoto Onuki2e210c42016-03-30 08:30:36 -07002879 Slog.d(TAG, String.format("handlePackageRemoved: %s user=%d", packageName,
2880 packageUserId));
Makoto Onukicdc78f72016-03-21 15:47:52 -07002881 }
Makoto Onukib08790c2016-06-23 14:05:46 -07002882 cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ false);
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002883
2884 verifyStates();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002885 }
2886
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002887 private void handlePackageDataCleared(String packageName, int packageUserId) {
2888 if (DEBUG) {
2889 Slog.d(TAG, String.format("handlePackageDataCleared: %s user=%d", packageName,
2890 packageUserId));
Makoto Onukicdc78f72016-03-21 15:47:52 -07002891 }
Makoto Onukib08790c2016-06-23 14:05:46 -07002892 cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ true);
2893
2894 verifyStates();
2895 }
2896
2897 private void handlePackageChanged(String packageName, int packageUserId) {
2898 if (DEBUG) {
2899 Slog.d(TAG, String.format("handlePackageChanged: %s user=%d", packageName,
2900 packageUserId));
2901 }
2902
2903 // Activities may be disabled or enabled. Just rescan the package.
2904 synchronized (mLock) {
2905 final ShortcutUser user = getUserShortcutsLocked(packageUserId);
2906
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002907 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07002908 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002909
2910 verifyStates();
Makoto Onukicdc78f72016-03-21 15:47:52 -07002911 }
2912
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002913 // === PackageManager interaction ===
Makoto Onuki0acbb142016-03-22 17:02:57 -07002914
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002915 /**
2916 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
2917 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002918 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002919 final PackageInfo getPackageInfoWithSignatures(String packageName, @UserIdInt int userId) {
2920 return getPackageInfo(packageName, userId, true);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002921 }
2922
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002923 /**
2924 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
2925 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002926 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002927 final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId) {
2928 return getPackageInfo(packageName, userId, false);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002929 }
2930
Makoto Onuki905e8852016-03-28 10:40:58 -07002931 int injectGetPackageUid(@NonNull String packageName, @UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002932 final long token = injectClearCallingIdentity();
Makoto Onuki905e8852016-03-28 10:40:58 -07002933 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002934 return mIPackageManager.getPackageUid(packageName, PACKAGE_MATCH_FLAGS, userId);
Makoto Onuki905e8852016-03-28 10:40:58 -07002935 } catch (RemoteException e) {
2936 // Shouldn't happen.
2937 Slog.wtf(TAG, "RemoteException", e);
2938 return -1;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002939 } finally {
2940 injectRestoreCallingIdentity(token);
Makoto Onuki905e8852016-03-28 10:40:58 -07002941 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07002942 }
2943
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002944 /**
2945 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
2946 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002947 @Nullable
Makoto Onuki0acbb142016-03-22 17:02:57 -07002948 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002949 final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId,
2950 boolean getSignatures) {
2951 return isInstalledOrNull(injectPackageInfoWithUninstalled(
2952 packageName, userId, getSignatures));
2953 }
2954
2955 /**
2956 * Do not use directly; this returns uninstalled packages too.
2957 */
2958 @Nullable
2959 @VisibleForTesting
2960 PackageInfo injectPackageInfoWithUninstalled(String packageName, @UserIdInt int userId,
Makoto Onuki0acbb142016-03-22 17:02:57 -07002961 boolean getSignatures) {
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07002962 final long start = injectElapsedRealtime();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002963 final long token = injectClearCallingIdentity();
Makoto Onuki0acbb142016-03-22 17:02:57 -07002964 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002965 return mIPackageManager.getPackageInfo(
2966 packageName, PACKAGE_MATCH_FLAGS
2967 | (getSignatures ? PackageManager.GET_SIGNATURES : 0), userId);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002968 } catch (RemoteException e) {
2969 // Shouldn't happen.
2970 Slog.wtf(TAG, "RemoteException", e);
2971 return null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002972 } finally {
2973 injectRestoreCallingIdentity(token);
Makoto Onuki2e210c42016-03-30 08:30:36 -07002974
2975 logDurationStat(
2976 (getSignatures ? Stats.GET_PACKAGE_INFO_WITH_SIG : Stats.GET_PACKAGE_INFO),
2977 start);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002978 }
2979 }
2980
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002981 /**
2982 * Returns {@link ApplicationInfo} unless it's uninstalled or disabled.
2983 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002984 @Nullable
Makoto Onuki905e8852016-03-28 10:40:58 -07002985 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002986 final ApplicationInfo getApplicationInfo(String packageName, @UserIdInt int userId) {
2987 return isInstalledOrNull(injectApplicationInfoWithUninstalled(packageName, userId));
2988 }
2989
2990 /**
2991 * Do not use directly; this returns uninstalled packages too.
2992 */
2993 @Nullable
2994 @VisibleForTesting
2995 ApplicationInfo injectApplicationInfoWithUninstalled(
2996 String packageName, @UserIdInt int userId) {
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07002997 final long start = injectElapsedRealtime();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002998 final long token = injectClearCallingIdentity();
Makoto Onuki905e8852016-03-28 10:40:58 -07002999 try {
3000 return mIPackageManager.getApplicationInfo(packageName, PACKAGE_MATCH_FLAGS, userId);
3001 } catch (RemoteException e) {
3002 // Shouldn't happen.
3003 Slog.wtf(TAG, "RemoteException", e);
3004 return null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003005 } finally {
3006 injectRestoreCallingIdentity(token);
Makoto Onuki2e210c42016-03-30 08:30:36 -07003007
3008 logDurationStat(Stats.GET_APPLICATION_INFO, start);
Makoto Onuki905e8852016-03-28 10:40:58 -07003009 }
3010 }
3011
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003012 /**
3013 * Returns {@link ActivityInfo} with its metadata unless it's uninstalled or disabled.
3014 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07003015 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003016 final ActivityInfo getActivityInfoWithMetadata(ComponentName activity, @UserIdInt int userId) {
3017 return isInstalledOrNull(injectGetActivityInfoWithMetadataWithUninstalled(
3018 activity, userId));
3019 }
3020
3021 /**
3022 * Do not use directly; this returns uninstalled packages too.
3023 */
3024 @Nullable
3025 @VisibleForTesting
3026 ActivityInfo injectGetActivityInfoWithMetadataWithUninstalled(
3027 ComponentName activity, @UserIdInt int userId) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07003028 final long start = injectElapsedRealtime();
3029 final long token = injectClearCallingIdentity();
3030 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07003031 return mIPackageManager.getActivityInfo(activity,
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003032 (PACKAGE_MATCH_FLAGS | PackageManager.GET_META_DATA), userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003033 } catch (RemoteException e) {
3034 // Shouldn't happen.
3035 Slog.wtf(TAG, "RemoteException", e);
3036 return null;
3037 } finally {
3038 injectRestoreCallingIdentity(token);
3039
Makoto Onukib08790c2016-06-23 14:05:46 -07003040 logDurationStat(Stats.GET_ACTIVITY_WITH_METADATA, start);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003041 }
3042 }
3043
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003044 /**
3045 * Return all installed and enabled packages.
3046 */
3047 @NonNull
Makoto Onuki22fcc682016-05-17 14:52:19 -07003048 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003049 final List<PackageInfo> getInstalledPackages(@UserIdInt int userId) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07003050 final long start = injectElapsedRealtime();
3051 final long token = injectClearCallingIdentity();
3052 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003053 final List<PackageInfo> all = injectGetPackagesWithUninstalled(userId);
3054
3055 all.removeIf(PACKAGE_NOT_INSTALLED);
3056
3057 return all;
Makoto Onuki22fcc682016-05-17 14:52:19 -07003058 } catch (RemoteException e) {
3059 // Shouldn't happen.
3060 Slog.wtf(TAG, "RemoteException", e);
3061 return null;
3062 } finally {
3063 injectRestoreCallingIdentity(token);
3064
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003065 logDurationStat(Stats.GET_INSTALLED_PACKAGES, start);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003066 }
3067 }
3068
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003069 /**
3070 * Do not use directly; this returns uninstalled packages too.
3071 */
3072 @NonNull
3073 @VisibleForTesting
3074 List<PackageInfo> injectGetPackagesWithUninstalled(@UserIdInt int userId)
3075 throws RemoteException {
3076 final ParceledListSlice<PackageInfo> parceledList =
3077 mIPackageManager.getInstalledPackages(PACKAGE_MATCH_FLAGS, userId);
3078 if (parceledList == null) {
3079 return Collections.emptyList();
3080 }
3081 return parceledList.getList();
3082 }
3083
Makoto Onuki33663282016-08-22 16:19:04 -07003084 private void forUpdatedPackages(@UserIdInt int userId, long lastScanTime, boolean afterOta,
Makoto Onuki22fcc682016-05-17 14:52:19 -07003085 Consumer<ApplicationInfo> callback) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003086 if (DEBUG) {
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003087 Slog.d(TAG, "forUpdatedPackages for user " + userId + ", lastScanTime=" + lastScanTime
3088 + " afterOta=" + afterOta);
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003089 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003090 final List<PackageInfo> list = getInstalledPackages(userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003091 for (int i = list.size() - 1; i >= 0; i--) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003092 final PackageInfo pi = list.get(i);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003093
Makoto Onuki64183d52016-08-08 14:11:34 -07003094 // If the package has been updated since the last scan time, then scan it.
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003095 // Also if it's right after an OTA, always re-scan all apps anyway, since the
3096 // shortcut parser might have changed.
3097 if (afterOta || (pi.lastUpdateTime >= lastScanTime)) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003098 if (DEBUG) {
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003099 Slog.d(TAG, "Found updated package " + pi.packageName
3100 + " updateTime=" + pi.lastUpdateTime);
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003101 }
3102 callback.accept(pi.applicationInfo);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003103 }
3104 }
3105 }
3106
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003107 private boolean isApplicationFlagSet(@NonNull String packageName, int userId, int flags) {
3108 final ApplicationInfo ai = injectApplicationInfoWithUninstalled(packageName, userId);
Makoto Onuki905e8852016-03-28 10:40:58 -07003109 return (ai != null) && ((ai.flags & flags) == flags);
3110 }
3111
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003112 private static boolean isInstalled(@Nullable ApplicationInfo ai) {
3113 return (ai != null) && (ai.flags & ApplicationInfo.FLAG_INSTALLED) != 0;
3114 }
3115
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08003116 private static boolean isEphemeralApp(@Nullable ApplicationInfo ai) {
Svetoslav Ganov096d3042017-01-30 16:34:13 -08003117 return (ai != null) && ai.isInstantApp();
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08003118 }
3119
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003120 private static boolean isInstalled(@Nullable PackageInfo pi) {
3121 return (pi != null) && isInstalled(pi.applicationInfo);
3122 }
3123
3124 private static boolean isInstalled(@Nullable ActivityInfo ai) {
3125 return (ai != null) && isInstalled(ai.applicationInfo);
3126 }
3127
3128 private static ApplicationInfo isInstalledOrNull(ApplicationInfo ai) {
3129 return isInstalled(ai) ? ai : null;
3130 }
3131
3132 private static PackageInfo isInstalledOrNull(PackageInfo pi) {
3133 return isInstalled(pi) ? pi : null;
3134 }
3135
3136 private static ActivityInfo isInstalledOrNull(ActivityInfo ai) {
3137 return isInstalled(ai) ? ai : null;
3138 }
3139
Makoto Onuki2e210c42016-03-30 08:30:36 -07003140 boolean isPackageInstalled(String packageName, int userId) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003141 return getApplicationInfo(packageName, userId) != null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003142 }
3143
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08003144 boolean isEphemeralApp(String packageName, int userId) {
3145 return isEphemeralApp(getApplicationInfo(packageName, userId));
3146 }
3147
Makoto Onuki22fcc682016-05-17 14:52:19 -07003148 @Nullable
3149 XmlResourceParser injectXmlMetaData(ActivityInfo activityInfo, String key) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07003150 return activityInfo.loadXmlMetaData(mContext.getPackageManager(), key);
Makoto Onuki39686e82016-04-13 18:03:00 -07003151 }
3152
Makoto Onuki157b1622016-06-02 16:13:10 -07003153 @Nullable
3154 Resources injectGetResourcesForApplicationAsUser(String packageName, int userId) {
3155 final long start = injectElapsedRealtime();
3156 final long token = injectClearCallingIdentity();
3157 try {
3158 return mContext.getPackageManager().getResourcesForApplicationAsUser(
3159 packageName, userId);
3160 } catch (NameNotFoundException e) {
3161 Slog.e(TAG, "Resources for package " + packageName + " not found");
3162 return null;
3163 } finally {
3164 injectRestoreCallingIdentity(token);
3165
3166 logDurationStat(Stats.GET_APPLICATION_RESOURCES, start);
3167 }
3168 }
3169
Makoto Onukib08790c2016-06-23 14:05:46 -07003170 private Intent getMainActivityIntent() {
3171 final Intent intent = new Intent(Intent.ACTION_MAIN);
3172 intent.addCategory(LAUNCHER_INTENT_CATEGORY);
3173 return intent;
3174 }
3175
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003176 /**
3177 * Same as queryIntentActivitiesAsUser, except it makes sure the package is installed,
3178 * and only returns exported activities.
3179 */
3180 @NonNull
3181 @VisibleForTesting
3182 List<ResolveInfo> queryActivities(@NonNull Intent baseIntent,
3183 @NonNull String packageName, @Nullable ComponentName activity, int userId) {
3184
3185 baseIntent.setPackage(Preconditions.checkNotNull(packageName));
3186 if (activity != null) {
3187 baseIntent.setComponent(activity);
3188 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08003189 return queryActivities(baseIntent, userId, /* exportedOnly =*/ true);
3190 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003191
Makoto Onuki2d895c32016-12-02 15:48:40 -08003192 @NonNull
3193 List<ResolveInfo> queryActivities(@NonNull Intent intent, int userId,
3194 boolean exportedOnly) {
3195 final List<ResolveInfo> resolved;
3196 final long token = injectClearCallingIdentity();
3197 try {
3198 resolved =
3199 mContext.getPackageManager().queryIntentActivitiesAsUser(
3200 intent, PACKAGE_MATCH_FLAGS, userId);
3201 } finally {
3202 injectRestoreCallingIdentity(token);
3203 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003204 if (resolved == null || resolved.size() == 0) {
3205 return EMPTY_RESOLVE_INFO;
3206 }
3207 // Make sure the package is installed.
3208 if (!isInstalled(resolved.get(0).activityInfo)) {
3209 return EMPTY_RESOLVE_INFO;
3210 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08003211 if (exportedOnly) {
3212 resolved.removeIf(ACTIVITY_NOT_EXPORTED);
3213 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003214 return resolved;
3215 }
3216
3217 /**
3218 * Return the main activity that is enabled and exported. If multiple activities are found,
3219 * return the first one.
3220 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003221 @Nullable
3222 ComponentName injectGetDefaultMainActivity(@NonNull String packageName, int userId) {
3223 final long start = injectElapsedRealtime();
Makoto Onukib08790c2016-06-23 14:05:46 -07003224 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07003225 final List<ResolveInfo> resolved =
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003226 queryActivities(getMainActivityIntent(), packageName, null, userId);
3227 return resolved.size() == 0 ? null : resolved.get(0).activityInfo.getComponentName();
Makoto Onukib08790c2016-06-23 14:05:46 -07003228 } finally {
Makoto Onukib08790c2016-06-23 14:05:46 -07003229 logDurationStat(Stats.GET_LAUNCHER_ACTIVITY, start);
3230 }
3231 }
3232
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003233 /**
3234 * Return whether an activity is enabled, exported and main.
3235 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003236 boolean injectIsMainActivity(@NonNull ComponentName activity, int userId) {
3237 final long start = injectElapsedRealtime();
Makoto Onukib08790c2016-06-23 14:05:46 -07003238 try {
Makoto Onuki2d895c32016-12-02 15:48:40 -08003239 if (DUMMY_MAIN_ACTIVITY.equals(activity.getClassName())) {
3240 return true;
3241 }
3242 final List<ResolveInfo> resolved = queryActivities(
3243 getMainActivityIntent(), activity.getPackageName(), activity, userId);
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003244 return resolved.size() > 0;
Makoto Onukib08790c2016-06-23 14:05:46 -07003245 } finally {
Makoto Onukib08790c2016-06-23 14:05:46 -07003246 logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start);
3247 }
3248 }
3249
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003250 /**
Makoto Onuki2d895c32016-12-02 15:48:40 -08003251 * Create a dummy "main activity" component name which is used to create a dynamic shortcut
3252 * with no main activity temporarily.
3253 */
3254 @NonNull
3255 ComponentName getDummyMainActivity(@NonNull String packageName) {
3256 return new ComponentName(packageName, DUMMY_MAIN_ACTIVITY);
3257 }
3258
Makoto Onuki255461f2017-01-10 11:47:25 -08003259 boolean isDummyMainActivity(@Nullable ComponentName name) {
3260 return name != null && DUMMY_MAIN_ACTIVITY.equals(name.getClassName());
3261 }
3262
Makoto Onuki2d895c32016-12-02 15:48:40 -08003263 /**
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003264 * Return all the enabled, exported and main activities from a package.
3265 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003266 @NonNull
3267 List<ResolveInfo> injectGetMainActivities(@NonNull String packageName, int userId) {
3268 final long start = injectElapsedRealtime();
Makoto Onukib08790c2016-06-23 14:05:46 -07003269 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003270 return queryActivities(getMainActivityIntent(), packageName, null, userId);
Makoto Onukib08790c2016-06-23 14:05:46 -07003271 } finally {
Makoto Onukib08790c2016-06-23 14:05:46 -07003272 logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start);
3273 }
3274 }
3275
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003276 /**
3277 * Return whether an activity is enabled and exported.
3278 */
3279 @VisibleForTesting
3280 boolean injectIsActivityEnabledAndExported(
3281 @NonNull ComponentName activity, @UserIdInt int userId) {
3282 final long start = injectElapsedRealtime();
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003283 try {
3284 return queryActivities(new Intent(), activity.getPackageName(), activity, userId)
3285 .size() > 0;
3286 } finally {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003287 logDurationStat(Stats.IS_ACTIVITY_ENABLED, start);
3288 }
3289 }
3290
Makoto Onuki2d895c32016-12-02 15:48:40 -08003291 /**
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003292 * Get the {@link LauncherApps#ACTION_CONFIRM_PIN_SHORTCUT} or
3293 * {@link LauncherApps#ACTION_CONFIRM_PIN_APPWIDGET} activity in a given package depending on
3294 * the requestType.
Makoto Onuki2d895c32016-12-02 15:48:40 -08003295 */
3296 @Nullable
3297 ComponentName injectGetPinConfirmationActivity(@NonNull String launcherPackageName,
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003298 int launcherUserId, int requestType) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08003299 Preconditions.checkNotNull(launcherPackageName);
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003300 String action = requestType == LauncherApps.PinItemRequest.REQUEST_TYPE_SHORTCUT ?
3301 LauncherApps.ACTION_CONFIRM_PIN_SHORTCUT :
3302 LauncherApps.ACTION_CONFIRM_PIN_APPWIDGET;
Makoto Onuki2d895c32016-12-02 15:48:40 -08003303
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003304 final Intent confirmIntent = new Intent(action).setPackage(launcherPackageName);
Makoto Onuki2d895c32016-12-02 15:48:40 -08003305 final List<ResolveInfo> candidates = queryActivities(
3306 confirmIntent, launcherUserId, /* exportedOnly =*/ false);
3307 for (ResolveInfo ri : candidates) {
3308 return ri.activityInfo.getComponentName();
3309 }
3310 return null;
3311 }
3312
Makoto Onukib08790c2016-06-23 14:05:46 -07003313 boolean injectIsSafeModeEnabled() {
3314 final long token = injectClearCallingIdentity();
3315 try {
3316 return IWindowManager.Stub
3317 .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE))
3318 .isSafeModeEnabled();
3319 } catch (RemoteException e) {
3320 return false; // Shouldn't happen though.
3321 } finally {
3322 injectRestoreCallingIdentity(token);
3323 }
3324 }
3325
Makoto Onuki2d895c32016-12-02 15:48:40 -08003326 /**
3327 * If {@code userId} is of a managed profile, return the parent user ID. Otherwise return
3328 * itself.
3329 */
3330 int getParentOrSelfUserId(int userId) {
3331 final long token = injectClearCallingIdentity();
3332 try {
3333 final UserInfo parent = mUserManager.getProfileParent(userId);
3334 return (parent != null) ? parent.id : userId;
3335 } finally {
3336 injectRestoreCallingIdentity(token);
3337 }
3338 }
3339
Sunny Goyal87a563e2017-01-01 19:42:45 -08003340 void injectSendIntentSender(IntentSender intentSender, Intent extras) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08003341 if (intentSender == null) {
3342 return;
3343 }
3344 try {
Sunny Goyal87a563e2017-01-01 19:42:45 -08003345 intentSender.sendIntent(mContext, /* code= */ 0, extras,
Makoto Onuki2d895c32016-12-02 15:48:40 -08003346 /* onFinished=*/ null, /* handler= */ null);
3347 } catch (SendIntentException e) {
3348 Slog.w(TAG, "sendIntent failed().", e);
3349 }
3350 }
3351
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003352 // === Backup & restore ===
3353
Makoto Onuki0acbb142016-03-22 17:02:57 -07003354 boolean shouldBackupApp(String packageName, int userId) {
Makoto Onuki905e8852016-03-28 10:40:58 -07003355 return isApplicationFlagSet(packageName, userId, ApplicationInfo.FLAG_ALLOW_BACKUP);
Makoto Onuki0acbb142016-03-22 17:02:57 -07003356 }
3357
Makoto Onuki2e210c42016-03-30 08:30:36 -07003358 boolean shouldBackupApp(PackageInfo pi) {
3359 return (pi.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0;
3360 }
3361
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003362 @Override
Makoto Onuki2e210c42016-03-30 08:30:36 -07003363 public byte[] getBackupPayload(@UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003364 enforceSystem();
3365 if (DEBUG) {
3366 Slog.d(TAG, "Backing up user " + userId);
3367 }
3368 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003369 if (!isUserUnlockedL(userId)) {
3370 wtf("Can't backup: user " + userId + " is locked or not running");
3371 return null;
3372 }
3373
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003374 final ShortcutUser user = getUserShortcutsLocked(userId);
3375 if (user == null) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003376 wtf("Can't backup: user not found: id=" + userId);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003377 return null;
3378 }
3379
Makoto Onukic8c33292016-09-12 16:36:59 -07003380 // Update the signatures for all packages.
3381 user.forAllPackageItems(spi -> spi.refreshPackageSignatureAndSave());
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003382
Makoto Onukic8c33292016-09-12 16:36:59 -07003383 // Set the version code for the launchers.
3384 // We shouldn't do this for publisher packages, because we don't want to update the
3385 // version code without rescanning the manifest.
3386 user.forAllLaunchers(launcher -> launcher.ensureVersionInfo());
3387
3388 // Save to the filesystem.
3389 scheduleSaveUser(userId);
3390 saveDirtyInfo();
3391
3392 // Then create the backup payload.
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003393 final ByteArrayOutputStream os = new ByteArrayOutputStream(32 * 1024);
3394 try {
3395 saveUserInternalLocked(userId, os, /* forBackup */ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07003396 } catch (XmlPullParserException | IOException e) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003397 // Shouldn't happen.
3398 Slog.w(TAG, "Backup failed.", e);
3399 return null;
3400 }
3401 return os.toByteArray();
3402 }
3403 }
3404
3405 @Override
Makoto Onuki2e210c42016-03-30 08:30:36 -07003406 public void applyRestore(byte[] payload, @UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003407 enforceSystem();
3408 if (DEBUG) {
3409 Slog.d(TAG, "Restoring user " + userId);
3410 }
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003411 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003412 if (!isUserUnlockedL(userId)) {
3413 wtf("Can't restore: user " + userId + " is locked or not running");
3414 return;
3415 }
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003416 // Actually do restore.
3417 final ShortcutUser restored;
Makoto Onuki02f338e2016-07-29 09:40:40 -07003418 final ByteArrayInputStream is = new ByteArrayInputStream(payload);
3419 try {
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003420 restored = loadUserInternal(userId, is, /* fromBackup */ true);
3421 } catch (XmlPullParserException | IOException | InvalidFileFormatException e) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003422 Slog.w(TAG, "Restoration failed.", e);
3423 return;
3424 }
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003425 getUserShortcutsLocked(userId).mergeRestoredFile(restored);
Makoto Onuki2e210c42016-03-30 08:30:36 -07003426
Makoto Onuki377b7972016-08-09 14:43:55 -07003427 // Rescan all packages to re-publish manifest shortcuts and do other checks.
3428 rescanUpdatedPackagesLocked(userId,
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003429 0 // lastScanTime = 0; rescan all packages.
3430 );
Makoto Onuki2e210c42016-03-30 08:30:36 -07003431
3432 saveUserLocked(userId);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003433 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07003434 }
3435
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003436 // === Dump ===
3437
3438 @Override
3439 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Makoto Onuki76269922016-07-15 14:58:54 -07003440 enforceCallingOrSelfPermission(android.Manifest.permission.DUMP,
3441 "can't dump by this caller");
3442 boolean checkin = false;
3443 boolean clear = false;
3444 if (args != null) {
3445 for (String arg : args) {
3446 if ("-c".equals(arg)) {
3447 checkin = true;
3448 } else if ("--checkin".equals(arg)) {
3449 checkin = true;
3450 clear = true;
3451 }
3452 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003453 }
Makoto Onuki76269922016-07-15 14:58:54 -07003454
3455 if (checkin) {
3456 dumpCheckin(pw, clear);
3457 } else {
3458 dumpInner(pw);
3459 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003460 }
3461
Makoto Onuki76269922016-07-15 14:58:54 -07003462 private void dumpInner(PrintWriter pw) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003463 synchronized (mLock) {
3464 final long now = injectCurrentTimeMillis();
3465 pw.print("Now: [");
3466 pw.print(now);
3467 pw.print("] ");
3468 pw.print(formatTime(now));
Makoto Onuki55046222016-03-08 10:49:47 -08003469
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003470 pw.print(" Raw last reset: [");
3471 pw.print(mRawLastResetTime);
3472 pw.print("] ");
3473 pw.print(formatTime(mRawLastResetTime));
3474
3475 final long last = getLastResetTimeLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003476 pw.print(" Last reset: [");
3477 pw.print(last);
3478 pw.print("] ");
3479 pw.print(formatTime(last));
3480
Makoto Onuki55046222016-03-08 10:49:47 -08003481 final long next = getNextResetTimeLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003482 pw.print(" Next reset: [");
3483 pw.print(next);
3484 pw.print("] ");
3485 pw.print(formatTime(next));
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003486
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003487 pw.print(" Config:");
3488 pw.print(" Max icon dim: ");
3489 pw.println(mMaxIconDimension);
3490 pw.print(" Icon format: ");
3491 pw.println(mIconPersistFormat);
3492 pw.print(" Icon quality: ");
Makoto Onuki2e210c42016-03-30 08:30:36 -07003493 pw.println(mIconPersistQuality);
Makoto Onuki0033b2a2016-04-14 17:19:16 -07003494 pw.print(" saveDelayMillis: ");
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003495 pw.println(mSaveDelayMillis);
Makoto Onuki0033b2a2016-04-14 17:19:16 -07003496 pw.print(" resetInterval: ");
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003497 pw.println(mResetInterval);
Makoto Onuki0033b2a2016-04-14 17:19:16 -07003498 pw.print(" maxUpdatesPerInterval: ");
Makoto Onukib6d35232016-04-04 15:57:17 -07003499 pw.println(mMaxUpdatesPerInterval);
Makoto Onukib08790c2016-06-23 14:05:46 -07003500 pw.print(" maxShortcutsPerActivity: ");
Makoto Onukib5a012f2016-06-21 11:13:53 -07003501 pw.println(mMaxShortcuts);
Makoto Onuki55046222016-03-08 10:49:47 -08003502 pw.println();
3503
Makoto Onuki2e210c42016-03-30 08:30:36 -07003504 pw.println(" Stats:");
3505 synchronized (mStatLock) {
Makoto Onuki085a05c2016-08-19 11:39:29 -07003506 for (int i = 0; i < Stats.COUNT; i++) {
3507 dumpStatLS(pw, " ", i);
3508 }
Makoto Onuki2e210c42016-03-30 08:30:36 -07003509 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003510
Makoto Onukia2241832016-07-06 13:28:37 -07003511 pw.println();
3512 pw.print(" #Failures: ");
3513 pw.println(mWtfCount);
3514
3515 if (mLastWtfStacktrace != null) {
3516 pw.print(" Last failure stack trace: ");
3517 pw.println(Log.getStackTraceString(mLastWtfStacktrace));
3518 }
3519
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08003520 for (int i = 0; i < mUsers.size(); i++) {
3521 pw.println();
Makoto Onukic51b2872016-05-04 15:24:50 -07003522 mUsers.valueAt(i).dump(pw, " ");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003523 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003524
3525 pw.println();
3526 pw.println(" UID state:");
3527
3528 for (int i = 0; i < mUidState.size(); i++) {
3529 final int uid = mUidState.keyAt(i);
3530 final int state = mUidState.valueAt(i);
3531 pw.print(" UID=");
3532 pw.print(uid);
3533 pw.print(" state=");
3534 pw.print(state);
3535 if (isProcessStateForeground(state)) {
3536 pw.print(" [FG]");
3537 }
3538 pw.print(" last FG=");
3539 pw.print(mUidLastForegroundElapsedTime.get(uid));
3540 pw.println();
3541 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003542 }
3543 }
3544
Makoto Onuki41066a62016-03-09 16:18:44 -08003545 static String formatTime(long time) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003546 Time tobj = new Time();
3547 tobj.set(time);
3548 return tobj.format("%Y-%m-%d %H:%M:%S");
3549 }
3550
Makoto Onuki085a05c2016-08-19 11:39:29 -07003551 private void dumpStatLS(PrintWriter pw, String prefix, int statId) {
Makoto Onuki2e210c42016-03-30 08:30:36 -07003552 pw.print(prefix);
3553 final int count = mCountStats[statId];
3554 final long dur = mDurationStats[statId];
3555 pw.println(String.format("%s: count=%d, total=%dms, avg=%.1fms",
Makoto Onuki085a05c2016-08-19 11:39:29 -07003556 STAT_LABELS[statId], count, dur,
Makoto Onuki2e210c42016-03-30 08:30:36 -07003557 (count == 0 ? 0 : ((double) dur) / count)));
3558 }
3559
Makoto Onuki76269922016-07-15 14:58:54 -07003560 /**
3561 * Dumpsys for checkin.
3562 *
3563 * @param clear if true, clear the history information. Some other system services have this
3564 * behavior but shortcut service doesn't for now.
3565 */
3566 private void dumpCheckin(PrintWriter pw, boolean clear) {
3567 synchronized (mLock) {
3568 try {
3569 final JSONArray users = new JSONArray();
3570
3571 for (int i = 0; i < mUsers.size(); i++) {
3572 users.put(mUsers.valueAt(i).dumpCheckin(clear));
3573 }
3574
3575 final JSONObject result = new JSONObject();
3576
3577 result.put(KEY_SHORTCUT, users);
3578 result.put(KEY_LOW_RAM, injectIsLowRamDevice());
3579 result.put(KEY_ICON_SIZE, mMaxIconDimension);
3580
3581 pw.println(result.toString(1));
3582 } catch (JSONException e) {
3583 Slog.e(TAG, "Unable to write in json", e);
3584 }
3585 }
3586 }
3587
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003588 // === Shell support ===
3589
3590 @Override
3591 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003592 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003593
3594 enforceShell();
3595
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07003596 final long token = injectClearCallingIdentity();
3597 try {
Dianne Hackborn354736e2016-08-22 17:00:05 -07003598 final int status = (new MyShellCommand()).exec(this, in, out, err, args, callback,
3599 resultReceiver);
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07003600 resultReceiver.send(status, null);
3601 } finally {
3602 injectRestoreCallingIdentity(token);
3603 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003604 }
3605
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003606 static class CommandException extends Exception {
3607 public CommandException(String message) {
3608 super(message);
3609 }
3610 }
3611
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003612 /**
3613 * Handle "adb shell cmd".
3614 */
3615 private class MyShellCommand extends ShellCommand {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003616
3617 private int mUserId = UserHandle.USER_SYSTEM;
3618
Makoto Onuki02f338e2016-07-29 09:40:40 -07003619 private void parseOptionsLocked(boolean takeUser)
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003620 throws CommandException {
3621 String opt;
3622 while ((opt = getNextOption()) != null) {
3623 switch (opt) {
3624 case "--user":
3625 if (takeUser) {
3626 mUserId = UserHandle.parseUserArg(getNextArgRequired());
Makoto Onuki02f338e2016-07-29 09:40:40 -07003627 if (!isUserUnlockedL(mUserId)) {
Makoto Onukif34c3082016-07-13 10:25:25 -07003628 throw new CommandException(
3629 "User " + mUserId + " is not running or locked");
3630 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003631 break;
3632 }
3633 // fallthrough
3634 default:
3635 throw new CommandException("Unknown option: " + opt);
3636 }
3637 }
3638 }
3639
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003640 @Override
3641 public int onCommand(String cmd) {
3642 if (cmd == null) {
3643 return handleDefaultCommands(cmd);
3644 }
3645 final PrintWriter pw = getOutPrintWriter();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003646 try {
3647 switch (cmd) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003648 case "reset-throttling":
3649 handleResetThrottling();
3650 break;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003651 case "reset-all-throttling":
3652 handleResetAllThrottling();
3653 break;
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003654 case "override-config":
3655 handleOverrideConfig();
3656 break;
3657 case "reset-config":
3658 handleResetConfig();
3659 break;
3660 case "clear-default-launcher":
3661 handleClearDefaultLauncher();
3662 break;
3663 case "get-default-launcher":
3664 handleGetDefaultLauncher();
3665 break;
Makoto Onukiac214972016-04-04 10:19:45 -07003666 case "unload-user":
3667 handleUnloadUser();
3668 break;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003669 case "clear-shortcuts":
3670 handleClearShortcuts();
3671 break;
Makoto Onukib08790c2016-06-23 14:05:46 -07003672 case "verify-states": // hidden command to verify various internal states.
3673 handleVerifyStates();
3674 break;
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003675 default:
3676 return handleDefaultCommands(cmd);
3677 }
3678 } catch (CommandException e) {
3679 pw.println("Error: " + e.getMessage());
3680 return 1;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003681 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003682 pw.println("Success");
3683 return 0;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003684 }
3685
3686 @Override
3687 public void onHelp() {
3688 final PrintWriter pw = getOutPrintWriter();
3689 pw.println("Usage: cmd shortcut COMMAND [options ...]");
3690 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003691 pw.println("cmd shortcut reset-throttling [--user USER_ID]");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003692 pw.println(" Reset throttling for all packages and users");
3693 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003694 pw.println("cmd shortcut reset-all-throttling");
3695 pw.println(" Reset the throttling state for all users");
3696 pw.println();
Makoto Onuki4362a662016-03-08 18:59:09 -08003697 pw.println("cmd shortcut override-config CONFIG");
3698 pw.println(" Override the configuration for testing (will last until reboot)");
3699 pw.println();
3700 pw.println("cmd shortcut reset-config");
3701 pw.println(" Reset the configuration set with \"update-config\"");
3702 pw.println();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003703 pw.println("cmd shortcut clear-default-launcher [--user USER_ID]");
3704 pw.println(" Clear the cached default launcher");
3705 pw.println();
3706 pw.println("cmd shortcut get-default-launcher [--user USER_ID]");
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07003707 pw.println(" Show the default launcher");
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003708 pw.println();
Makoto Onukiac214972016-04-04 10:19:45 -07003709 pw.println("cmd shortcut unload-user [--user USER_ID]");
3710 pw.println(" Unload a user from the memory");
3711 pw.println(" (This should not affect any observable behavior)");
3712 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003713 pw.println("cmd shortcut clear-shortcuts [--user USER_ID] PACKAGE");
3714 pw.println(" Remove all shortcuts from a package, including pinned shortcuts");
3715 pw.println();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003716 }
3717
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003718 private void handleResetThrottling() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003719 synchronized (mLock) {
3720 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki4554d0e2016-03-14 15:51:41 -07003721
Makoto Onuki02f338e2016-07-29 09:40:40 -07003722 Slog.i(TAG, "cmd: handleResetThrottling: user=" + mUserId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003723
Makoto Onuki02f338e2016-07-29 09:40:40 -07003724 resetThrottlingInner(mUserId);
3725 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003726 }
3727
3728 private void handleResetAllThrottling() {
3729 Slog.i(TAG, "cmd: handleResetAllThrottling");
3730
3731 resetAllThrottlingInner();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003732 }
3733
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003734 private void handleOverrideConfig() throws CommandException {
Makoto Onuki4362a662016-03-08 18:59:09 -08003735 final String config = getNextArgRequired();
3736
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003737 Slog.i(TAG, "cmd: handleOverrideConfig: " + config);
3738
Makoto Onuki4362a662016-03-08 18:59:09 -08003739 synchronized (mLock) {
3740 if (!updateConfigurationLocked(config)) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003741 throw new CommandException("override-config failed. See logcat for details.");
Makoto Onuki4362a662016-03-08 18:59:09 -08003742 }
3743 }
Makoto Onuki4362a662016-03-08 18:59:09 -08003744 }
3745
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003746 private void handleResetConfig() {
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003747 Slog.i(TAG, "cmd: handleResetConfig");
3748
Makoto Onuki4362a662016-03-08 18:59:09 -08003749 synchronized (mLock) {
3750 loadConfigurationLocked();
3751 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003752 }
3753
3754 private void clearLauncher() {
3755 synchronized (mLock) {
Makoto Onuki10305202016-07-14 18:14:08 -07003756 getUserShortcutsLocked(mUserId).forceClearLauncher();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003757 }
3758 }
3759
3760 private void showLauncher() {
3761 synchronized (mLock) {
3762 // This ensures to set the cached launcher. Package name doesn't matter.
3763 hasShortcutHostPermissionInner("-", mUserId);
3764
3765 getOutPrintWriter().println("Launcher: "
Makoto Onuki10305202016-07-14 18:14:08 -07003766 + getUserShortcutsLocked(mUserId).getLastKnownLauncher());
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003767 }
3768 }
3769
3770 private void handleClearDefaultLauncher() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003771 synchronized (mLock) {
3772 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003773
Makoto Onuki02f338e2016-07-29 09:40:40 -07003774 clearLauncher();
3775 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003776 }
3777
3778 private void handleGetDefaultLauncher() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003779 synchronized (mLock) {
3780 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003781
Makoto Onuki02f338e2016-07-29 09:40:40 -07003782 clearLauncher();
3783 showLauncher();
3784 }
Makoto Onuki4362a662016-03-08 18:59:09 -08003785 }
Makoto Onukiac214972016-04-04 10:19:45 -07003786
3787 private void handleUnloadUser() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003788 synchronized (mLock) {
3789 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onukiac214972016-04-04 10:19:45 -07003790
Makoto Onuki02f338e2016-07-29 09:40:40 -07003791 Slog.i(TAG, "cmd: handleUnloadUser: user=" + mUserId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003792
Makoto Onuki02f338e2016-07-29 09:40:40 -07003793 ShortcutService.this.handleCleanupUser(mUserId);
3794 }
Makoto Onukiac214972016-04-04 10:19:45 -07003795 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003796
3797 private void handleClearShortcuts() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003798 synchronized (mLock) {
3799 parseOptionsLocked(/* takeUser =*/ true);
3800 final String packageName = getNextArgRequired();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003801
Makoto Onuki02f338e2016-07-29 09:40:40 -07003802 Slog.i(TAG, "cmd: handleClearShortcuts: user" + mUserId + ", " + packageName);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003803
Makoto Onuki02f338e2016-07-29 09:40:40 -07003804 ShortcutService.this.cleanUpPackageForAllLoadedUsers(packageName, mUserId,
3805 /* appStillExists = */ true);
3806 }
Makoto Onukib08790c2016-06-23 14:05:46 -07003807 }
3808
3809 private void handleVerifyStates() throws CommandException {
3810 try {
3811 verifyStatesForce(); // This will throw when there's an issue.
3812 } catch (Throwable th) {
3813 throw new CommandException(th.getMessage() + "\n" + Log.getStackTraceString(th));
3814 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003815 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003816 }
3817
3818 // === Unit test support ===
3819
3820 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07003821 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003822 long injectCurrentTimeMillis() {
3823 return System.currentTimeMillis();
3824 }
3825
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003826 @VisibleForTesting
3827 long injectElapsedRealtime() {
3828 return SystemClock.elapsedRealtime();
3829 }
3830
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003831 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07003832 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003833 int injectBinderCallingUid() {
3834 return getCallingUid();
3835 }
3836
Makoto Onuki31459242016-03-22 11:12:18 -07003837 private int getCallingUserId() {
Makoto Onuki4554d0e2016-03-14 15:51:41 -07003838 return UserHandle.getUserId(injectBinderCallingUid());
3839 }
3840
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07003841 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07003842 @VisibleForTesting
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07003843 long injectClearCallingIdentity() {
3844 return Binder.clearCallingIdentity();
3845 }
3846
3847 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07003848 @VisibleForTesting
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07003849 void injectRestoreCallingIdentity(long token) {
3850 Binder.restoreCallingIdentity(token);
3851 }
3852
Makoto Onuki33663282016-08-22 16:19:04 -07003853 // Injection point.
3854 @VisibleForTesting
3855 String injectBuildFingerprint() {
3856 return Build.FINGERPRINT;
3857 }
3858
Makoto Onukide667372016-03-15 14:29:20 -07003859 final void wtf(String message) {
Makoto Onukib08790c2016-06-23 14:05:46 -07003860 wtf(message, /* exception= */ null);
Makoto Onukide667372016-03-15 14:29:20 -07003861 }
3862
Makoto Onuki2e210c42016-03-30 08:30:36 -07003863 // Injection point.
Makoto Onukia2241832016-07-06 13:28:37 -07003864 void wtf(String message, Throwable e) {
3865 if (e == null) {
3866 e = new RuntimeException("Stacktrace");
3867 }
3868 synchronized (mLock) {
3869 mWtfCount++;
3870 mLastWtfStacktrace = new Exception("Last failure was logged here:");
3871 }
Makoto Onukide667372016-03-15 14:29:20 -07003872 Slog.wtf(TAG, message, e);
3873 }
3874
Makoto Onuki31459242016-03-22 11:12:18 -07003875 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003876 File injectSystemDataPath() {
3877 return Environment.getDataSystemDirectory();
3878 }
3879
Makoto Onuki31459242016-03-22 11:12:18 -07003880 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003881 File injectUserDataPath(@UserIdInt int userId) {
Makoto Onuki55046222016-03-08 10:49:47 -08003882 return new File(Environment.getDataSystemCeDirectory(userId), DIRECTORY_PER_USER);
3883 }
3884
Makoto Onuki4362a662016-03-08 18:59:09 -08003885 @VisibleForTesting
Makoto Onuki55046222016-03-08 10:49:47 -08003886 boolean injectIsLowRamDevice() {
3887 return ActivityManager.isLowRamDeviceStatic();
3888 }
3889
Makoto Onuki31459242016-03-22 11:12:18 -07003890 @VisibleForTesting
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003891 void injectRegisterUidObserver(IUidObserver observer, int which) {
3892 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003893 ActivityManager.getService().registerUidObserver(observer, which,
Dianne Hackborn5614bf52016-11-07 17:26:41 -08003894 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003895 } catch (RemoteException shouldntHappen) {
3896 }
3897 }
3898
Makoto Onuki55046222016-03-08 10:49:47 -08003899 File getUserBitmapFilePath(@UserIdInt int userId) {
3900 return new File(injectUserDataPath(userId), DIRECTORY_BITMAPS);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003901 }
3902
3903 @VisibleForTesting
Makoto Onuki31459242016-03-22 11:12:18 -07003904 SparseArray<ShortcutUser> getShortcutsForTest() {
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08003905 return mUsers;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003906 }
3907
3908 @VisibleForTesting
Makoto Onukib5a012f2016-06-21 11:13:53 -07003909 int getMaxShortcutsForTest() {
3910 return mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003911 }
3912
3913 @VisibleForTesting
Makoto Onukib6d35232016-04-04 15:57:17 -07003914 int getMaxUpdatesPerIntervalForTest() {
3915 return mMaxUpdatesPerInterval;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003916 }
3917
3918 @VisibleForTesting
Makoto Onuki4362a662016-03-08 18:59:09 -08003919 long getResetIntervalForTest() {
3920 return mResetInterval;
Makoto Onuki55046222016-03-08 10:49:47 -08003921 }
3922
3923 @VisibleForTesting
Makoto Onuki4362a662016-03-08 18:59:09 -08003924 int getMaxIconDimensionForTest() {
3925 return mMaxIconDimension;
3926 }
3927
3928 @VisibleForTesting
3929 CompressFormat getIconPersistFormatForTest() {
3930 return mIconPersistFormat;
3931 }
3932
3933 @VisibleForTesting
3934 int getIconPersistQualityForTest() {
3935 return mIconPersistQuality;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003936 }
Makoto Onuki41066a62016-03-09 16:18:44 -08003937
3938 @VisibleForTesting
Makoto Onuki22fcc682016-05-17 14:52:19 -07003939 ShortcutPackage getPackageShortcutForTest(String packageName, int userId) {
Makoto Onuki41066a62016-03-09 16:18:44 -08003940 synchronized (mLock) {
Makoto Onuki31459242016-03-22 11:12:18 -07003941 final ShortcutUser user = mUsers.get(userId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07003942 if (user == null) return null;
3943
Makoto Onuki22fcc682016-05-17 14:52:19 -07003944 return user.getAllPackagesForTest().get(packageName);
3945 }
3946 }
3947
3948 @VisibleForTesting
3949 ShortcutInfo getPackageShortcutForTest(String packageName, String shortcutId, int userId) {
3950 synchronized (mLock) {
Makoto Onukif34c3082016-07-13 10:25:25 -07003951 final ShortcutPackage pkg = getPackageShortcutForTest(packageName, userId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07003952 if (pkg == null) return null;
3953
3954 return pkg.findShortcutById(shortcutId);
Makoto Onuki41066a62016-03-09 16:18:44 -08003955 }
3956 }
Makoto Onuki7001a612016-05-27 13:24:28 -07003957
Makoto Onukifac592f2016-11-21 13:41:32 -08003958 @VisibleForTesting
3959 ShortcutLauncher getLauncherShortcutForTest(String packageName, int userId) {
3960 synchronized (mLock) {
3961 final ShortcutUser user = mUsers.get(userId);
3962 if (user == null) return null;
3963
3964 return user.getAllLaunchersForTest().get(PackageWithUser.of(userId, packageName));
3965 }
3966 }
3967
Makoto Onuki2d895c32016-12-02 15:48:40 -08003968 @VisibleForTesting
3969 ShortcutRequestPinProcessor getShortcutRequestPinProcessorForTest() {
3970 return mShortcutRequestPinProcessor;
3971 }
3972
Makoto Onuki7001a612016-05-27 13:24:28 -07003973 /**
3974 * Control whether {@link #verifyStates} should be performed. We always perform it during unit
3975 * tests.
3976 */
3977 @VisibleForTesting
3978 boolean injectShouldPerformVerification() {
3979 return DEBUG;
3980 }
3981
3982 /**
3983 * Check various internal states and throws if there's any inconsistency.
3984 * This is normally only enabled during unit tests.
3985 */
3986 final void verifyStates() {
3987 if (injectShouldPerformVerification()) {
3988 verifyStatesInner();
3989 }
3990 }
3991
Makoto Onukib08790c2016-06-23 14:05:46 -07003992 private final void verifyStatesForce() {
3993 verifyStatesInner();
3994 }
3995
Makoto Onuki7001a612016-05-27 13:24:28 -07003996 private void verifyStatesInner() {
Makoto Onuki10305202016-07-14 18:14:08 -07003997 synchronized (mLock) {
Makoto Onuki7001a612016-05-27 13:24:28 -07003998 forEachLoadedUserLocked(u -> u.forAllPackageItems(ShortcutPackageItem::verifyStates));
3999 }
4000 }
Makoto Onuki41066a62016-03-09 16:18:44 -08004001}