blob: 0e572d8215722ce4fb1873d8ac9ba376b6fb7d70 [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;
30import android.content.Context;
31import android.content.Intent;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070032import android.content.IntentFilter;
Makoto Onuki2d895c32016-12-02 15:48:40 -080033import android.content.IntentSender;
34import android.content.IntentSender.SendIntentException;
Makoto Onuki22fcc682016-05-17 14:52:19 -070035import android.content.pm.ActivityInfo;
Makoto Onuki0acbb142016-03-22 17:02:57 -070036import android.content.pm.ApplicationInfo;
37import android.content.pm.IPackageManager;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080038import android.content.pm.IShortcutService;
39import android.content.pm.LauncherApps;
40import android.content.pm.LauncherApps.ShortcutQuery;
Makoto Onuki0acbb142016-03-22 17:02:57 -070041import android.content.pm.PackageInfo;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080042import android.content.pm.PackageManager;
Makoto Onuki20c95f82016-05-11 16:51:01 -070043import android.content.pm.PackageManager.NameNotFoundException;
Makoto Onuki2d5b4652016-03-11 16:09:54 -080044import android.content.pm.PackageManagerInternal;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080045import android.content.pm.ParceledListSlice;
Makoto Onuki2d5b4652016-03-11 16:09:54 -080046import android.content.pm.ResolveInfo;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080047import android.content.pm.ShortcutInfo;
48import android.content.pm.ShortcutServiceInternal;
49import android.content.pm.ShortcutServiceInternal.ShortcutChangeListener;
Makoto Onuki2d895c32016-12-02 15:48:40 -080050import android.content.pm.UserInfo;
Makoto Onuki157b1622016-06-02 16:13:10 -070051import android.content.res.Resources;
Makoto Onuki22fcc682016-05-17 14:52:19 -070052import android.content.res.XmlResourceParser;
Makoto Onuki55046222016-03-08 10:49:47 -080053import android.graphics.Bitmap;
54import android.graphics.Bitmap.CompressFormat;
Makoto Onuki55046222016-03-08 10:49:47 -080055import android.graphics.Canvas;
56import android.graphics.RectF;
Hyunyoung Song47037462017-05-08 16:51:43 -070057import android.graphics.drawable.AdaptiveIconDrawable;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080058import android.graphics.drawable.Icon;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070059import android.net.Uri;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080060import android.os.Binder;
Makoto Onuki33663282016-08-22 16:19:04 -070061import android.os.Build;
Sunny Goyal4ad6b572017-02-28 11:11:51 -080062import android.os.Bundle;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080063import android.os.Environment;
Makoto Onuki2e210c42016-03-30 08:30:36 -070064import android.os.FileUtils;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080065import android.os.Handler;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070066import android.os.LocaleList;
Makoto Onukiaa8b94a2016-03-17 13:14:05 -070067import android.os.Looper;
Makoto Onuki55046222016-03-08 10:49:47 -080068import android.os.ParcelFileDescriptor;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080069import android.os.PersistableBundle;
70import android.os.Process;
71import android.os.RemoteException;
72import android.os.ResultReceiver;
Makoto Onuki55046222016-03-08 10:49:47 -080073import android.os.SELinux;
Makoto Onukib08790c2016-06-23 14:05:46 -070074import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070075import android.os.ShellCallback;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080076import android.os.ShellCommand;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -070077import android.os.SystemClock;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080078import android.os.UserHandle;
Makoto Onukicdc78f72016-03-21 15:47:52 -070079import android.os.UserManager;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080080import android.text.TextUtils;
81import android.text.format.Time;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080082import android.util.ArraySet;
83import android.util.AtomicFile;
Makoto Onuki4362a662016-03-08 18:59:09 -080084import android.util.KeyValueListParser;
Makoto Onukiac042502016-05-20 16:39:42 -070085import android.util.Log;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080086import android.util.Slog;
87import android.util.SparseArray;
Makoto Onuki02f338e2016-07-29 09:40:40 -070088import android.util.SparseBooleanArray;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -070089import android.util.SparseIntArray;
90import android.util.SparseLongArray;
Makoto Onuki55046222016-03-08 10:49:47 -080091import android.util.TypedValue;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080092import android.util.Xml;
Makoto Onukib08790c2016-06-23 14:05:46 -070093import android.view.IWindowManager;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080094
95import com.android.internal.annotations.GuardedBy;
96import com.android.internal.annotations.VisibleForTesting;
97import com.android.internal.os.BackgroundThread;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060098import com.android.internal.util.DumpUtils;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080099import com.android.internal.util.FastXmlSerializer;
100import com.android.internal.util.Preconditions;
101import com.android.server.LocalServices;
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
Makoto Onuki50a320e2017-05-31 14:38:42 -0700184 static final String DIRECTORY_DUMP = "shortcut_dump";
185
186 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800187 static final String FILENAME_USER_PACKAGES = "shortcuts.xml";
188
Makoto Onuki55046222016-03-08 10:49:47 -0800189 static final String DIRECTORY_BITMAPS = "bitmaps";
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800190
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700191 private static final String TAG_ROOT = "root";
192 private static final String TAG_LAST_RESET_TIME = "last_reset_time";
Makoto Onuki55046222016-03-08 10:49:47 -0800193
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700194 private static final String ATTR_VALUE = "value";
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800195
Makoto Onukib08790c2016-06-23 14:05:46 -0700196 private static final String LAUNCHER_INTENT_CATEGORY = Intent.CATEGORY_LAUNCHER;
197
Makoto Onuki76269922016-07-15 14:58:54 -0700198 private static final String KEY_SHORTCUT = "shortcut";
199 private static final String KEY_LOW_RAM = "lowRam";
200 private static final String KEY_ICON_SIZE = "iconSize";
201
Makoto Onuki2d895c32016-12-02 15:48:40 -0800202 private static final String DUMMY_MAIN_ACTIVITY = "android.__dummy__";
203
Makoto Onuki4362a662016-03-08 18:59:09 -0800204 @VisibleForTesting
205 interface ConfigConstants {
206 /**
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700207 * Key name for the save delay, in milliseconds. (int)
208 */
209 String KEY_SAVE_DELAY_MILLIS = "save_delay_ms";
210
211 /**
Makoto Onuki4362a662016-03-08 18:59:09 -0800212 * Key name for the throttling reset interval, in seconds. (long)
213 */
214 String KEY_RESET_INTERVAL_SEC = "reset_interval_sec";
215
216 /**
217 * Key name for the max number of modifying API calls per app for every interval. (int)
218 */
Makoto Onukib6d35232016-04-04 15:57:17 -0700219 String KEY_MAX_UPDATES_PER_INTERVAL = "max_updates_per_interval";
Makoto Onuki4362a662016-03-08 18:59:09 -0800220
221 /**
222 * Key name for the max icon dimensions in DP, for non-low-memory devices.
223 */
224 String KEY_MAX_ICON_DIMENSION_DP = "max_icon_dimension_dp";
225
226 /**
227 * Key name for the max icon dimensions in DP, for low-memory devices.
228 */
229 String KEY_MAX_ICON_DIMENSION_DP_LOWRAM = "max_icon_dimension_dp_lowram";
230
231 /**
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700232 * Key name for the max dynamic shortcuts per activity. (int)
Makoto Onuki4362a662016-03-08 18:59:09 -0800233 */
234 String KEY_MAX_SHORTCUTS = "max_shortcuts";
235
236 /**
Makoto Onuki41066a62016-03-09 16:18:44 -0800237 * Key name for icon compression quality, 0-100.
Makoto Onuki4362a662016-03-08 18:59:09 -0800238 */
239 String KEY_ICON_QUALITY = "icon_quality";
240
241 /**
242 * Key name for icon compression format: "PNG", "JPEG" or "WEBP"
243 */
244 String KEY_ICON_FORMAT = "icon_format";
245 }
246
Makoto Onuki41066a62016-03-09 16:18:44 -0800247 final Context mContext;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800248
249 private final Object mLock = new Object();
250
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700251 private static List<ResolveInfo> EMPTY_RESOLVE_INFO = new ArrayList<>(0);
252
Mark Renoufe065f7c2016-11-01 11:48:24 -0400253 // Temporarily reverted to anonymous inner class form due to: b/32554459
254 private static Predicate<ResolveInfo> ACTIVITY_NOT_EXPORTED = new Predicate<ResolveInfo>() {
255 public boolean test(ResolveInfo ri) {
256 return !ri.activityInfo.exported;
257 }
258 };
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700259
Mark Renoufe065f7c2016-11-01 11:48:24 -0400260 // Temporarily reverted to anonymous inner class form due to: b/32554459
261 private static Predicate<PackageInfo> PACKAGE_NOT_INSTALLED = new Predicate<PackageInfo>() {
262 public boolean test(PackageInfo pi) {
263 return !isInstalled(pi);
264 }
265 };
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700266
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800267 private final Handler mHandler;
268
269 @GuardedBy("mLock")
270 private final ArrayList<ShortcutChangeListener> mListeners = new ArrayList<>(1);
271
272 @GuardedBy("mLock")
273 private long mRawLastResetTime;
274
275 /**
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -0800276 * User ID -> UserShortcuts
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800277 */
278 @GuardedBy("mLock")
Makoto Onuki31459242016-03-22 11:12:18 -0700279 private final SparseArray<ShortcutUser> mUsers = new SparseArray<>();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800280
281 /**
Makoto Onukib5a012f2016-06-21 11:13:53 -0700282 * Max number of dynamic + manifest shortcuts that each application can have at a time.
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800283 */
Makoto Onukib5a012f2016-06-21 11:13:53 -0700284 private int mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800285
286 /**
Makoto Onukib6d35232016-04-04 15:57:17 -0700287 * Max number of updating API calls that each application can make during the interval.
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800288 */
Makoto Onukib6d35232016-04-04 15:57:17 -0700289 int mMaxUpdatesPerInterval;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800290
291 /**
292 * Actual throttling-reset interval. By default it's a day.
293 */
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800294 private long mResetInterval;
295
Makoto Onuki55046222016-03-08 10:49:47 -0800296 /**
297 * Icon max width/height in pixels.
298 */
299 private int mMaxIconDimension;
300
Makoto Onuki4362a662016-03-08 18:59:09 -0800301 private CompressFormat mIconPersistFormat;
302 private int mIconPersistQuality;
Makoto Onuki55046222016-03-08 10:49:47 -0800303
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700304 private int mSaveDelayMillis;
305
Makoto Onuki0acbb142016-03-22 17:02:57 -0700306 private final IPackageManager mIPackageManager;
Makoto Onuki2d5b4652016-03-11 16:09:54 -0800307 private final PackageManagerInternal mPackageManagerInternal;
Makoto Onukicdc78f72016-03-21 15:47:52 -0700308 private final UserManager mUserManager;
Makoto Onukiac042502016-05-20 16:39:42 -0700309 private final UsageStatsManagerInternal mUsageStatsManagerInternal;
Makoto Onuki33525d22016-08-03 15:45:24 -0700310 private final ActivityManagerInternal mActivityManagerInternal;
Makoto Onuki2d5b4652016-03-11 16:09:54 -0800311
Makoto Onuki2d895c32016-12-02 15:48:40 -0800312 private final ShortcutRequestPinProcessor mShortcutRequestPinProcessor;
Makoto Onuki475c3652017-05-08 14:29:03 -0700313 private final ShortcutBitmapSaver mShortcutBitmapSaver;
Makoto Onuki50a320e2017-05-31 14:38:42 -0700314 private final ShortcutDumpFiles mShortcutDumpFiles;
Makoto Onuki2d895c32016-12-02 15:48:40 -0800315
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700316 @GuardedBy("mLock")
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700317 final SparseIntArray mUidState = new SparseIntArray();
318
319 @GuardedBy("mLock")
320 final SparseLongArray mUidLastForegroundElapsedTime = new SparseLongArray();
321
322 @GuardedBy("mLock")
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700323 private List<Integer> mDirtyUserIds = new ArrayList<>();
324
Makoto Onukic51b2872016-05-04 15:24:50 -0700325 private final AtomicBoolean mBootCompleted = new AtomicBoolean();
326
Makoto Onuki905e8852016-03-28 10:40:58 -0700327 private static final int PACKAGE_MATCH_FLAGS =
328 PackageManager.MATCH_DIRECT_BOOT_AWARE
Makoto Onukib08790c2016-06-23 14:05:46 -0700329 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE
330 | PackageManager.MATCH_UNINSTALLED_PACKAGES;
Makoto Onuki905e8852016-03-28 10:40:58 -0700331
Makoto Onuki02f338e2016-07-29 09:40:40 -0700332 @GuardedBy("mLock")
333 final SparseBooleanArray mUnlockedUsers = new SparseBooleanArray();
334
Makoto Onuki2e210c42016-03-30 08:30:36 -0700335 // Stats
336 @VisibleForTesting
337 interface Stats {
338 int GET_DEFAULT_HOME = 0;
339 int GET_PACKAGE_INFO = 1;
340 int GET_PACKAGE_INFO_WITH_SIG = 2;
341 int GET_APPLICATION_INFO = 3;
342 int LAUNCHER_PERMISSION_CHECK = 4;
Makoto Onuki6c1dbd52016-05-02 15:19:32 -0700343 int CLEANUP_DANGLING_BITMAPS = 5;
Makoto Onukib08790c2016-06-23 14:05:46 -0700344 int GET_ACTIVITY_WITH_METADATA = 6;
Makoto Onuki6dd9fb72016-06-01 13:55:54 -0700345 int GET_INSTALLED_PACKAGES = 7;
Makoto Onuki22fcc682016-05-17 14:52:19 -0700346 int CHECK_PACKAGE_CHANGES = 8;
Makoto Onuki157b1622016-06-02 16:13:10 -0700347 int GET_APPLICATION_RESOURCES = 9;
348 int RESOURCE_NAME_LOOKUP = 10;
Makoto Onukib08790c2016-06-23 14:05:46 -0700349 int GET_LAUNCHER_ACTIVITY = 11;
350 int CHECK_LAUNCHER_ACTIVITY = 12;
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700351 int IS_ACTIVITY_ENABLED = 13;
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700352 int PACKAGE_UPDATE_CHECK = 14;
Makoto Onuki085a05c2016-08-19 11:39:29 -0700353 int ASYNC_PRELOAD_USER_DELAY = 15;
Makoto Onuki2d895c32016-12-02 15:48:40 -0800354 int GET_DEFAULT_LAUNCHER = 16;
Makoto Onuki2e210c42016-03-30 08:30:36 -0700355
Makoto Onuki2d895c32016-12-02 15:48:40 -0800356 int COUNT = GET_DEFAULT_LAUNCHER + 1;
Makoto Onuki2e210c42016-03-30 08:30:36 -0700357 }
358
Makoto Onuki085a05c2016-08-19 11:39:29 -0700359 private static final String[] STAT_LABELS = {
360 "getHomeActivities()",
361 "Launcher permission check",
362 "getPackageInfo()",
363 "getPackageInfo(SIG)",
364 "getApplicationInfo",
365 "cleanupDanglingBitmaps",
366 "getActivity+metadata",
367 "getInstalledPackages",
368 "checkPackageChanges",
369 "getApplicationResources",
370 "resourceNameLookup",
371 "getLauncherActivity",
372 "checkLauncherActivity",
373 "isActivityEnabled",
374 "packageUpdateCheck",
Makoto Onuki2d895c32016-12-02 15:48:40 -0800375 "asyncPreloadUserDelay",
376 "getDefaultLauncher()"
Makoto Onuki085a05c2016-08-19 11:39:29 -0700377 };
378
Makoto Onuki2e210c42016-03-30 08:30:36 -0700379 final Object mStatLock = new Object();
380
381 @GuardedBy("mStatLock")
382 private final int[] mCountStats = new int[Stats.COUNT];
383
384 @GuardedBy("mStatLock")
385 private final long[] mDurationStats = new long[Stats.COUNT];
386
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700387 private static final int PROCESS_STATE_FOREGROUND_THRESHOLD =
388 ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
389
Makoto Onuki7001a612016-05-27 13:24:28 -0700390 static final int OPERATION_SET = 0;
391 static final int OPERATION_ADD = 1;
392 static final int OPERATION_UPDATE = 2;
393
394 /** @hide */
395 @IntDef(value = {
396 OPERATION_SET,
397 OPERATION_ADD,
398 OPERATION_UPDATE
Makoto Onukib08790c2016-06-23 14:05:46 -0700399 })
Makoto Onuki7001a612016-05-27 13:24:28 -0700400 @Retention(RetentionPolicy.SOURCE)
Makoto Onukib08790c2016-06-23 14:05:46 -0700401 @interface ShortcutOperation {
402 }
Makoto Onuki7001a612016-05-27 13:24:28 -0700403
Makoto Onukia2241832016-07-06 13:28:37 -0700404 @GuardedBy("mLock")
405 private int mWtfCount = 0;
406
407 @GuardedBy("mLock")
408 private Exception mLastWtfStacktrace;
409
Makoto Onukifc4cf2d2016-08-24 11:10:26 -0700410 static class InvalidFileFormatException extends Exception {
411 public InvalidFileFormatException(String message, Throwable cause) {
412 super(message, cause);
413 }
414 }
415
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800416 public ShortcutService(Context context) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700417 this(context, BackgroundThread.get().getLooper(), /*onyForPackgeManagerApis*/ false);
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700418 }
419
420 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700421 ShortcutService(Context context, Looper looper, boolean onlyForPackageManagerApis) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800422 mContext = Preconditions.checkNotNull(context);
423 LocalServices.addService(ShortcutServiceInternal.class, new LocalService());
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700424 mHandler = new Handler(looper);
Makoto Onuki0acbb142016-03-22 17:02:57 -0700425 mIPackageManager = AppGlobals.getPackageManager();
Makoto Onukiac042502016-05-20 16:39:42 -0700426 mPackageManagerInternal = Preconditions.checkNotNull(
427 LocalServices.getService(PackageManagerInternal.class));
428 mUserManager = Preconditions.checkNotNull(context.getSystemService(UserManager.class));
429 mUsageStatsManagerInternal = Preconditions.checkNotNull(
430 LocalServices.getService(UsageStatsManagerInternal.class));
Makoto Onuki33525d22016-08-03 15:45:24 -0700431 mActivityManagerInternal = Preconditions.checkNotNull(
432 LocalServices.getService(ActivityManagerInternal.class));
Makoto Onukicdc78f72016-03-21 15:47:52 -0700433
Makoto Onuki2d895c32016-12-02 15:48:40 -0800434 mShortcutRequestPinProcessor = new ShortcutRequestPinProcessor(this, mLock);
Makoto Onuki475c3652017-05-08 14:29:03 -0700435 mShortcutBitmapSaver = new ShortcutBitmapSaver(this);
Makoto Onuki50a320e2017-05-31 14:38:42 -0700436 mShortcutDumpFiles = new ShortcutDumpFiles(this);
Makoto Onuki2d895c32016-12-02 15:48:40 -0800437
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700438 if (onlyForPackageManagerApis) {
439 return; // Don't do anything further. For unit tests only.
440 }
441
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700442 // Register receivers.
443
444 // We need to set a priority, so let's just not use PackageMonitor for now.
445 // TODO Refactor PackageMonitor to support priorities.
446 final IntentFilter packageFilter = new IntentFilter();
447 packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
448 packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
449 packageFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
450 packageFilter.addAction(Intent.ACTION_PACKAGE_DATA_CLEARED);
451 packageFilter.addDataScheme("package");
452 packageFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
453 mContext.registerReceiverAsUser(mPackageMonitor, UserHandle.ALL,
454 packageFilter, null, mHandler);
455
Makoto Onuki10305202016-07-14 18:14:08 -0700456 final IntentFilter preferedActivityFilter = new IntentFilter();
457 preferedActivityFilter.addAction(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
458 preferedActivityFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
459 mContext.registerReceiverAsUser(mPackageMonitor, UserHandle.ALL,
460 preferedActivityFilter, null, mHandler);
461
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700462 final IntentFilter localeFilter = new IntentFilter();
463 localeFilter.addAction(Intent.ACTION_LOCALE_CHANGED);
464 localeFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
465 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL,
466 localeFilter, null, mHandler);
Makoto Onukif34c3082016-07-13 10:25:25 -0700467
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700468 injectRegisterUidObserver(mUidObserver, ActivityManager.UID_OBSERVER_PROCSTATE
469 | ActivityManager.UID_OBSERVER_GONE);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800470 }
471
Makoto Onuki2e210c42016-03-30 08:30:36 -0700472 void logDurationStat(int statId, long start) {
473 synchronized (mStatLock) {
474 mCountStats[statId]++;
Makoto Onuki6c1dbd52016-05-02 15:19:32 -0700475 mDurationStats[statId] += (injectElapsedRealtime() - start);
Makoto Onuki2e210c42016-03-30 08:30:36 -0700476 }
477 }
478
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700479 public String injectGetLocaleTagsForUser(@UserIdInt int userId) {
480 // TODO This should get the per-user locale. b/30123329 b/30119489
481 return LocaleList.getDefault().toLanguageTags();
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700482 }
483
484 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Makoto Onukib08790c2016-06-23 14:05:46 -0700485 @Override
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700486 public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700487 handleOnUidStateChanged(uid, procState);
488 }
489
Makoto Onukib08790c2016-06-23 14:05:46 -0700490 @Override
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700491 public void onUidGone(int uid, boolean disabled) {
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800492 handleOnUidStateChanged(uid, ActivityManager.PROCESS_STATE_NONEXISTENT);
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700493 }
494
Makoto Onukib08790c2016-06-23 14:05:46 -0700495 @Override
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700496 public void onUidActive(int uid) {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700497 }
498
Makoto Onukib08790c2016-06-23 14:05:46 -0700499 @Override
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700500 public void onUidIdle(int uid, boolean disabled) {
501 }
502
503 @Override public void onUidCachedChanged(int uid, boolean cached) {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700504 }
505 };
506
507 void handleOnUidStateChanged(int uid, int procState) {
508 if (DEBUG_PROCSTATE) {
509 Slog.d(TAG, "onUidStateChanged: uid=" + uid + " state=" + procState);
510 }
511 synchronized (mLock) {
512 mUidState.put(uid, procState);
513
514 // We need to keep track of last time an app comes to foreground.
515 // See ShortcutPackage.getApiCallCount() for how it's used.
516 // It doesn't have to be persisted, but it needs to be the elapsed time.
517 if (isProcessStateForeground(procState)) {
518 mUidLastForegroundElapsedTime.put(uid, injectElapsedRealtime());
519 }
520 }
521 }
522
523 private boolean isProcessStateForeground(int processState) {
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800524 return processState <= PROCESS_STATE_FOREGROUND_THRESHOLD;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700525 }
526
527 boolean isUidForegroundLocked(int uid) {
528 if (uid == Process.SYSTEM_UID) {
529 // IUidObserver doesn't report the state of SYSTEM, but it always has bound services,
530 // so it's foreground anyway.
531 return true;
532 }
Makoto Onuki33525d22016-08-03 15:45:24 -0700533 // First, check with the local cache.
534 if (isProcessStateForeground(mUidState.get(uid, ActivityManager.MAX_PROCESS_STATE))) {
535 return true;
536 }
537 // If the cache says background, reach out to AM. Since it'll internally need to hold
538 // the AM lock, we use it as a last resort.
539 return isProcessStateForeground(mActivityManagerInternal.getUidProcessState(uid));
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700540 }
541
542 long getUidLastForegroundElapsedTimeLocked(int uid) {
543 return mUidLastForegroundElapsedTime.get(uid);
544 }
545
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800546 /**
547 * System service lifecycle.
548 */
549 public static final class Lifecycle extends SystemService {
550 final ShortcutService mService;
551
552 public Lifecycle(Context context) {
553 super(context);
554 mService = new ShortcutService(context);
555 }
556
557 @Override
558 public void onStart() {
559 publishBinderService(Context.SHORTCUT_SERVICE, mService);
560 }
561
562 @Override
563 public void onBootPhase(int phase) {
564 mService.onBootPhase(phase);
565 }
566
567 @Override
Makoto Onuki01ce92b2017-04-28 12:24:16 -0700568 public void onStopUser(int userHandle) {
569 mService.handleStopUser(userHandle);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800570 }
571
572 @Override
Makoto Onukif3a572b2016-03-10 12:28:38 -0800573 public void onUnlockUser(int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -0700574 mService.handleUnlockUser(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800575 }
576 }
577
578 /** lifecycle event */
579 void onBootPhase(int phase) {
580 if (DEBUG) {
581 Slog.d(TAG, "onBootPhase: " + phase);
582 }
583 switch (phase) {
584 case SystemService.PHASE_LOCK_SETTINGS_READY:
585 initialize();
586 break;
Makoto Onukic51b2872016-05-04 15:24:50 -0700587 case SystemService.PHASE_BOOT_COMPLETED:
588 mBootCompleted.set(true);
589 break;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800590 }
591 }
592
593 /** lifecycle event */
Makoto Onukicdc78f72016-03-21 15:47:52 -0700594 void handleUnlockUser(int userId) {
Makoto Onuki22fcc682016-05-17 14:52:19 -0700595 if (DEBUG) {
Makoto Onuki085a05c2016-08-19 11:39:29 -0700596 Slog.d(TAG, "handleUnlockUser: user=" + userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700597 }
Makoto Onukicdc78f72016-03-21 15:47:52 -0700598 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -0700599 mUnlockedUsers.put(userId, true);
Makoto Onukicdc78f72016-03-21 15:47:52 -0700600 }
Makoto Onuki085a05c2016-08-19 11:39:29 -0700601
602 // Preload the user data.
603 // Note, we don't use mHandler here but instead just start a new thread.
604 // This is because mHandler (which uses com.android.internal.os.BackgroundThread) is very
605 // busy at this point and this could take hundreds of milliseconds, which would be too
606 // late since the launcher would already have started.
607 // So we just create a new thread. This code runs rarely, so we don't use a thread pool
608 // or anything.
609 final long start = injectElapsedRealtime();
610 injectRunOnNewThread(() -> {
611 synchronized (mLock) {
612 logDurationStat(Stats.ASYNC_PRELOAD_USER_DELAY, start);
613 getUserShortcutsLocked(userId);
614 }
615 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800616 }
617
618 /** lifecycle event */
Makoto Onuki01ce92b2017-04-28 12:24:16 -0700619 void handleStopUser(int userId) {
Makoto Onuki02f338e2016-07-29 09:40:40 -0700620 if (DEBUG) {
Makoto Onuki01ce92b2017-04-28 12:24:16 -0700621 Slog.d(TAG, "handleStopUser: user=" + userId);
Makoto Onuki02f338e2016-07-29 09:40:40 -0700622 }
Makoto Onukicdc78f72016-03-21 15:47:52 -0700623 synchronized (mLock) {
624 unloadUserLocked(userId);
Makoto Onuki02f338e2016-07-29 09:40:40 -0700625
626 mUnlockedUsers.put(userId, false);
Makoto Onukicdc78f72016-03-21 15:47:52 -0700627 }
628 }
629
630 private void unloadUserLocked(int userId) {
631 if (DEBUG) {
632 Slog.d(TAG, "unloadUserLocked: user=" + userId);
633 }
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700634 // Save all dirty information.
635 saveDirtyInfo();
636
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800637 // Unload
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -0800638 mUsers.delete(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800639 }
640
641 /** Return the base state file name */
642 private AtomicFile getBaseStateFile() {
643 final File path = new File(injectSystemDataPath(), FILENAME_BASE_STATE);
644 path.mkdirs();
645 return new AtomicFile(path);
646 }
647
648 /**
649 * Init the instance. (load the state file, etc)
650 */
651 private void initialize() {
652 synchronized (mLock) {
Makoto Onuki4362a662016-03-08 18:59:09 -0800653 loadConfigurationLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800654 loadBaseStateLocked();
655 }
656 }
657
Makoto Onuki4362a662016-03-08 18:59:09 -0800658 /**
659 * Load the configuration from Settings.
660 */
661 private void loadConfigurationLocked() {
662 updateConfigurationLocked(injectShortcutManagerConstants());
663 }
Makoto Onuki55046222016-03-08 10:49:47 -0800664
Makoto Onuki4362a662016-03-08 18:59:09 -0800665 /**
666 * Load the configuration from Settings.
667 */
668 @VisibleForTesting
669 boolean updateConfigurationLocked(String config) {
670 boolean result = true;
671
672 final KeyValueListParser parser = new KeyValueListParser(',');
673 try {
674 parser.setString(config);
675 } catch (IllegalArgumentException e) {
676 // Failed to parse the settings string, log this and move on
677 // with defaults.
678 Slog.e(TAG, "Bad shortcut manager settings", e);
679 result = false;
680 }
681
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700682 mSaveDelayMillis = Math.max(0, (int) parser.getLong(ConfigConstants.KEY_SAVE_DELAY_MILLIS,
683 DEFAULT_SAVE_DELAY_MS));
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700684
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700685 mResetInterval = Math.max(1, parser.getLong(
Makoto Onuki4362a662016-03-08 18:59:09 -0800686 ConfigConstants.KEY_RESET_INTERVAL_SEC, DEFAULT_RESET_INTERVAL_SEC)
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700687 * 1000L);
Makoto Onuki4362a662016-03-08 18:59:09 -0800688
Makoto Onukib6d35232016-04-04 15:57:17 -0700689 mMaxUpdatesPerInterval = Math.max(0, (int) parser.getLong(
690 ConfigConstants.KEY_MAX_UPDATES_PER_INTERVAL, DEFAULT_MAX_UPDATES_PER_INTERVAL));
Makoto Onuki4362a662016-03-08 18:59:09 -0800691
Makoto Onukib5a012f2016-06-21 11:13:53 -0700692 mMaxShortcuts = Math.max(0, (int) parser.getLong(
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700693 ConfigConstants.KEY_MAX_SHORTCUTS, DEFAULT_MAX_SHORTCUTS_PER_APP));
Makoto Onuki4362a662016-03-08 18:59:09 -0800694
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700695 final int iconDimensionDp = Math.max(1, injectIsLowRamDevice()
Makoto Onuki4362a662016-03-08 18:59:09 -0800696 ? (int) parser.getLong(
Makoto Onukib08790c2016-06-23 14:05:46 -0700697 ConfigConstants.KEY_MAX_ICON_DIMENSION_DP_LOWRAM,
698 DEFAULT_MAX_ICON_DIMENSION_LOWRAM_DP)
Makoto Onuki4362a662016-03-08 18:59:09 -0800699 : (int) parser.getLong(
Makoto Onukib08790c2016-06-23 14:05:46 -0700700 ConfigConstants.KEY_MAX_ICON_DIMENSION_DP,
701 DEFAULT_MAX_ICON_DIMENSION_DP));
Makoto Onuki4362a662016-03-08 18:59:09 -0800702
703 mMaxIconDimension = injectDipToPixel(iconDimensionDp);
704
705 mIconPersistFormat = CompressFormat.valueOf(
706 parser.getString(ConfigConstants.KEY_ICON_FORMAT, DEFAULT_ICON_PERSIST_FORMAT));
707
708 mIconPersistQuality = (int) parser.getLong(
709 ConfigConstants.KEY_ICON_QUALITY,
710 DEFAULT_ICON_PERSIST_QUALITY);
711
712 return result;
713 }
714
715 @VisibleForTesting
716 String injectShortcutManagerConstants() {
717 return android.provider.Settings.Global.getString(
718 mContext.getContentResolver(),
719 android.provider.Settings.Global.SHORTCUT_MANAGER_CONSTANTS);
720 }
721
722 @VisibleForTesting
723 int injectDipToPixel(int dip) {
724 return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip,
725 mContext.getResources().getDisplayMetrics());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800726 }
727
Makoto Onuki55046222016-03-08 10:49:47 -0800728 // === Persisting ===
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800729
730 @Nullable
Makoto Onuki41066a62016-03-09 16:18:44 -0800731 static String parseStringAttribute(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800732 return parser.getAttributeValue(null, attribute);
733 }
734
Makoto Onuki0acbb142016-03-22 17:02:57 -0700735 static boolean parseBooleanAttribute(XmlPullParser parser, String attribute) {
736 return parseLongAttribute(parser, attribute) == 1;
737 }
738
Makoto Onuki41066a62016-03-09 16:18:44 -0800739 static int parseIntAttribute(XmlPullParser parser, String attribute) {
740 return (int) parseLongAttribute(parser, attribute);
741 }
742
Makoto Onukid99c6f02016-03-28 11:02:54 -0700743 static int parseIntAttribute(XmlPullParser parser, String attribute, int def) {
744 return (int) parseLongAttribute(parser, attribute, def);
745 }
746
Makoto Onuki41066a62016-03-09 16:18:44 -0800747 static long parseLongAttribute(XmlPullParser parser, String attribute) {
Makoto Onukid99c6f02016-03-28 11:02:54 -0700748 return parseLongAttribute(parser, attribute, 0);
749 }
750
751 static long parseLongAttribute(XmlPullParser parser, String attribute, long def) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800752 final String value = parseStringAttribute(parser, attribute);
753 if (TextUtils.isEmpty(value)) {
Makoto Onukid99c6f02016-03-28 11:02:54 -0700754 return def;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800755 }
756 try {
757 return Long.parseLong(value);
758 } catch (NumberFormatException e) {
759 Slog.e(TAG, "Error parsing long " + value);
Makoto Onukid99c6f02016-03-28 11:02:54 -0700760 return def;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800761 }
762 }
763
764 @Nullable
Makoto Onuki41066a62016-03-09 16:18:44 -0800765 static ComponentName parseComponentNameAttribute(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800766 final String value = parseStringAttribute(parser, attribute);
767 if (TextUtils.isEmpty(value)) {
768 return null;
769 }
770 return ComponentName.unflattenFromString(value);
771 }
772
773 @Nullable
Makoto Onuki440a1ea2016-07-20 14:21:18 -0700774 static Intent parseIntentAttributeNoDefault(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800775 final String value = parseStringAttribute(parser, attribute);
Makoto Onukib5a012f2016-06-21 11:13:53 -0700776 Intent parsed = null;
777 if (!TextUtils.isEmpty(value)) {
778 try {
779 parsed = Intent.parseUri(value, /* flags =*/ 0);
780 } catch (URISyntaxException e) {
781 Slog.e(TAG, "Error parsing intent", e);
782 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800783 }
Makoto Onuki440a1ea2016-07-20 14:21:18 -0700784 return parsed;
785 }
786
787 @Nullable
788 static Intent parseIntentAttribute(XmlPullParser parser, String attribute) {
789 Intent parsed = parseIntentAttributeNoDefault(parser, attribute);
Makoto Onukib5a012f2016-06-21 11:13:53 -0700790 if (parsed == null) {
791 // Default intent.
792 parsed = new Intent(Intent.ACTION_VIEW);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800793 }
Makoto Onukib5a012f2016-06-21 11:13:53 -0700794 return parsed;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800795 }
796
Makoto Onuki41066a62016-03-09 16:18:44 -0800797 static void writeTagValue(XmlSerializer out, String tag, String value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800798 if (TextUtils.isEmpty(value)) return;
799
800 out.startTag(null, tag);
801 out.attribute(null, ATTR_VALUE, value);
802 out.endTag(null, tag);
803 }
804
Makoto Onuki41066a62016-03-09 16:18:44 -0800805 static void writeTagValue(XmlSerializer out, String tag, long value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800806 writeTagValue(out, tag, Long.toString(value));
807 }
808
Makoto Onuki2d5b4652016-03-11 16:09:54 -0800809 static void writeTagValue(XmlSerializer out, String tag, ComponentName name) throws IOException {
810 if (name == null) return;
811 writeTagValue(out, tag, name.flattenToString());
812 }
813
Makoto Onuki41066a62016-03-09 16:18:44 -0800814 static void writeTagExtra(XmlSerializer out, String tag, PersistableBundle bundle)
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800815 throws IOException, XmlPullParserException {
816 if (bundle == null) return;
817
818 out.startTag(null, tag);
819 bundle.saveToXml(out);
820 out.endTag(null, tag);
821 }
822
Makoto Onuki22fcc682016-05-17 14:52:19 -0700823 static void writeAttr(XmlSerializer out, String name, CharSequence value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800824 if (TextUtils.isEmpty(value)) return;
825
Makoto Onuki22fcc682016-05-17 14:52:19 -0700826 out.attribute(null, name, value.toString());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800827 }
828
Makoto Onuki41066a62016-03-09 16:18:44 -0800829 static void writeAttr(XmlSerializer out, String name, long value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800830 writeAttr(out, name, String.valueOf(value));
831 }
832
Makoto Onuki0acbb142016-03-22 17:02:57 -0700833 static void writeAttr(XmlSerializer out, String name, boolean value) throws IOException {
834 if (value) {
835 writeAttr(out, name, "1");
836 }
837 }
838
Makoto Onuki41066a62016-03-09 16:18:44 -0800839 static void writeAttr(XmlSerializer out, String name, ComponentName comp) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800840 if (comp == null) return;
841 writeAttr(out, name, comp.flattenToString());
842 }
843
Makoto Onuki41066a62016-03-09 16:18:44 -0800844 static void writeAttr(XmlSerializer out, String name, Intent intent) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800845 if (intent == null) return;
846
847 writeAttr(out, name, intent.toUri(/* flags =*/ 0));
848 }
849
850 @VisibleForTesting
851 void saveBaseStateLocked() {
852 final AtomicFile file = getBaseStateFile();
853 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700854 Slog.d(TAG, "Saving to " + file.getBaseFile());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800855 }
856
857 FileOutputStream outs = null;
858 try {
859 outs = file.startWrite();
860
861 // Write to XML
862 XmlSerializer out = new FastXmlSerializer();
863 out.setOutput(outs, StandardCharsets.UTF_8.name());
864 out.startDocument(null, true);
865 out.startTag(null, TAG_ROOT);
866
867 // Body.
868 writeTagValue(out, TAG_LAST_RESET_TIME, mRawLastResetTime);
869
870 // Epilogue.
871 out.endTag(null, TAG_ROOT);
872 out.endDocument();
873
874 // Close.
875 file.finishWrite(outs);
876 } catch (IOException e) {
877 Slog.e(TAG, "Failed to write to file " + file.getBaseFile(), e);
878 file.failWrite(outs);
879 }
880 }
881
882 private void loadBaseStateLocked() {
883 mRawLastResetTime = 0;
884
885 final AtomicFile file = getBaseStateFile();
886 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700887 Slog.d(TAG, "Loading from " + file.getBaseFile());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800888 }
889 try (FileInputStream in = file.openRead()) {
890 XmlPullParser parser = Xml.newPullParser();
891 parser.setInput(in, StandardCharsets.UTF_8.name());
892
893 int type;
894 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
895 if (type != XmlPullParser.START_TAG) {
896 continue;
897 }
898 final int depth = parser.getDepth();
899 // Check the root tag
900 final String tag = parser.getName();
901 if (depth == 1) {
902 if (!TAG_ROOT.equals(tag)) {
903 Slog.e(TAG, "Invalid root tag: " + tag);
904 return;
905 }
906 continue;
907 }
908 // Assume depth == 2
909 switch (tag) {
910 case TAG_LAST_RESET_TIME:
911 mRawLastResetTime = parseLongAttribute(parser, ATTR_VALUE);
912 break;
913 default:
914 Slog.e(TAG, "Invalid tag: " + tag);
915 break;
916 }
917 }
918 } catch (FileNotFoundException e) {
919 // Use the default
Makoto Onukib08790c2016-06-23 14:05:46 -0700920 } catch (IOException | XmlPullParserException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800921 Slog.e(TAG, "Failed to read file " + file.getBaseFile(), e);
922
923 mRawLastResetTime = 0;
924 }
925 // Adjust the last reset time.
926 getLastResetTimeLocked();
927 }
928
Makoto Onuki0eed4412016-07-21 11:21:59 -0700929 @VisibleForTesting
930 final File getUserFile(@UserIdInt int userId) {
931 return new File(injectUserDataPath(userId), FILENAME_USER_PACKAGES);
932 }
933
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800934 private void saveUserLocked(@UserIdInt int userId) {
Makoto Onuki0eed4412016-07-21 11:21:59 -0700935 final File path = getUserFile(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800936 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700937 Slog.d(TAG, "Saving to " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800938 }
Makoto Onuki475c3652017-05-08 14:29:03 -0700939
940 mShortcutBitmapSaver.waitForAllSavesLocked();
941
Makoto Onuki0eed4412016-07-21 11:21:59 -0700942 path.getParentFile().mkdirs();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800943 final AtomicFile file = new AtomicFile(path);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700944 FileOutputStream os = null;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800945 try {
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700946 os = file.startWrite();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800947
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700948 saveUserInternalLocked(userId, os, /* forBackup= */ false);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800949
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700950 file.finishWrite(os);
Makoto Onuki1e173232016-08-10 10:47:13 -0700951
952 // Remove all dangling bitmap files.
953 cleanupDanglingBitmapDirectoriesLocked(userId);
Makoto Onukib08790c2016-06-23 14:05:46 -0700954 } catch (XmlPullParserException | IOException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800955 Slog.e(TAG, "Failed to write to file " + file.getBaseFile(), e);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700956 file.failWrite(os);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800957 }
958 }
959
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700960 private void saveUserInternalLocked(@UserIdInt int userId, OutputStream os,
961 boolean forBackup) throws IOException, XmlPullParserException {
962
963 final BufferedOutputStream bos = new BufferedOutputStream(os);
964
965 // Write to XML
966 XmlSerializer out = new FastXmlSerializer();
967 out.setOutput(bos, StandardCharsets.UTF_8.name());
968 out.startDocument(null, true);
969
Makoto Onukic51b2872016-05-04 15:24:50 -0700970 getUserShortcutsLocked(userId).saveToXml(out, forBackup);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700971
972 out.endDocument();
973
974 bos.flush();
975 os.flush();
976 }
977
Makoto Onuki41066a62016-03-09 16:18:44 -0800978 static IOException throwForInvalidTag(int depth, String tag) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800979 throw new IOException(String.format("Invalid tag '%s' found at depth %d", tag, depth));
980 }
981
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700982 static void warnForInvalidTag(int depth, String tag) throws IOException {
983 Slog.w(TAG, String.format("Invalid tag '%s' found at depth %d", tag, depth));
984 }
985
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800986 @Nullable
Makoto Onuki31459242016-03-22 11:12:18 -0700987 private ShortcutUser loadUserLocked(@UserIdInt int userId) {
Makoto Onuki0eed4412016-07-21 11:21:59 -0700988 final File path = getUserFile(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800989 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700990 Slog.d(TAG, "Loading from " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800991 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800992 final AtomicFile file = new AtomicFile(path);
993
994 final FileInputStream in;
995 try {
996 in = file.openRead();
997 } catch (FileNotFoundException e) {
998 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700999 Slog.d(TAG, "Not found " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001000 }
1001 return null;
1002 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001003 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07001004 final ShortcutUser ret = loadUserInternal(userId, in, /* forBackup= */ false);
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001005 return ret;
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07001006 } catch (IOException | XmlPullParserException | InvalidFileFormatException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001007 Slog.e(TAG, "Failed to read file " + file.getBaseFile(), e);
1008 return null;
1009 } finally {
1010 IoUtils.closeQuietly(in);
1011 }
1012 }
1013
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001014 private ShortcutUser loadUserInternal(@UserIdInt int userId, InputStream is,
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07001015 boolean fromBackup) throws XmlPullParserException, IOException,
1016 InvalidFileFormatException {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001017
1018 final BufferedInputStream bis = new BufferedInputStream(is);
1019
1020 ShortcutUser ret = null;
1021 XmlPullParser parser = Xml.newPullParser();
1022 parser.setInput(bis, StandardCharsets.UTF_8.name());
1023
1024 int type;
1025 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1026 if (type != XmlPullParser.START_TAG) {
1027 continue;
1028 }
1029 final int depth = parser.getDepth();
1030
1031 final String tag = parser.getName();
1032 if (DEBUG_LOAD) {
1033 Slog.d(TAG, String.format("depth=%d type=%d name=%s",
1034 depth, type, tag));
1035 }
1036 if ((depth == 1) && ShortcutUser.TAG_ROOT.equals(tag)) {
1037 ret = ShortcutUser.loadFromXml(this, parser, userId, fromBackup);
1038 continue;
1039 }
1040 throwForInvalidTag(depth, tag);
1041 }
1042 return ret;
1043 }
1044
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001045 private void scheduleSaveBaseState() {
Makoto Onuki0acbb142016-03-22 17:02:57 -07001046 scheduleSaveInner(UserHandle.USER_NULL); // Special case -- use USER_NULL for base state.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001047 }
1048
Makoto Onuki2d5b4652016-03-11 16:09:54 -08001049 void scheduleSaveUser(@UserIdInt int userId) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07001050 scheduleSaveInner(userId);
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001051 }
1052
1053 // In order to re-schedule, we need to reuse the same instance, so keep it in final.
1054 private final Runnable mSaveDirtyInfoRunner = this::saveDirtyInfo;
1055
Makoto Onuki0acbb142016-03-22 17:02:57 -07001056 private void scheduleSaveInner(@UserIdInt int userId) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001057 if (DEBUG) {
1058 Slog.d(TAG, "Scheduling to save for " + userId);
1059 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001060 synchronized (mLock) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001061 if (!mDirtyUserIds.contains(userId)) {
1062 mDirtyUserIds.add(userId);
1063 }
1064 }
1065 // If already scheduled, remove that and re-schedule in N seconds.
1066 mHandler.removeCallbacks(mSaveDirtyInfoRunner);
1067 mHandler.postDelayed(mSaveDirtyInfoRunner, mSaveDelayMillis);
1068 }
1069
1070 @VisibleForTesting
1071 void saveDirtyInfo() {
1072 if (DEBUG) {
1073 Slog.d(TAG, "saveDirtyInfo");
1074 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001075 try {
1076 synchronized (mLock) {
1077 for (int i = mDirtyUserIds.size() - 1; i >= 0; i--) {
1078 final int userId = mDirtyUserIds.get(i);
1079 if (userId == UserHandle.USER_NULL) { // USER_NULL for base state.
1080 saveBaseStateLocked();
1081 } else {
1082 saveUserLocked(userId);
1083 }
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001084 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001085 mDirtyUserIds.clear();
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001086 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001087 } catch (Exception e) {
1088 wtf("Exception in saveDirtyInfo", e);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001089 }
1090 }
1091
1092 /** Return the last reset time. */
1093 long getLastResetTimeLocked() {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001094 updateTimesLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001095 return mRawLastResetTime;
1096 }
1097
1098 /** Return the next reset time. */
1099 long getNextResetTimeLocked() {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001100 updateTimesLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001101 return mRawLastResetTime + mResetInterval;
1102 }
1103
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001104 static boolean isClockValid(long time) {
1105 return time >= 1420070400; // Thu, 01 Jan 2015 00:00:00 GMT
1106 }
1107
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001108 /**
1109 * Update the last reset time.
1110 */
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001111 private void updateTimesLocked() {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001112
1113 final long now = injectCurrentTimeMillis();
1114
1115 final long prevLastResetTime = mRawLastResetTime;
1116
1117 if (mRawLastResetTime == 0) { // first launch.
1118 // TODO Randomize??
1119 mRawLastResetTime = now;
1120 } else if (now < mRawLastResetTime) {
1121 // Clock rewound.
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001122 if (isClockValid(now)) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001123 Slog.w(TAG, "Clock rewound");
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001124 // TODO Randomize??
1125 mRawLastResetTime = now;
1126 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001127 } else {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001128 if ((mRawLastResetTime + mResetInterval) <= now) {
1129 final long offset = mRawLastResetTime % mResetInterval;
1130 mRawLastResetTime = ((now / mResetInterval) * mResetInterval) + offset;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001131 }
1132 }
1133 if (prevLastResetTime != mRawLastResetTime) {
1134 scheduleSaveBaseState();
1135 }
1136 }
1137
Makoto Onuki1e173232016-08-10 10:47:13 -07001138 // Requires mLock held, but "Locked" prefix would look weired so we just say "L".
Makoto Onuki02f338e2016-07-29 09:40:40 -07001139 protected boolean isUserUnlockedL(@UserIdInt int userId) {
Makoto Onuki1e173232016-08-10 10:47:13 -07001140 // First, check the local copy.
1141 if (mUnlockedUsers.get(userId)) {
1142 return true;
1143 }
1144 // If the local copy says the user is locked, check with AM for the actual state, since
1145 // the user might just have been unlocked.
1146 // Note we just don't use isUserUnlockingOrUnlocked() here, because it'll return false
1147 // when the user is STOPPING, which we still want to consider as "unlocked".
1148 final long token = injectClearCallingIdentity();
1149 try {
1150 return mUserManager.isUserUnlockingOrUnlocked(userId);
1151 } finally {
1152 injectRestoreCallingIdentity(token);
1153 }
Makoto Onuki9c850012016-07-26 15:50:50 -07001154 }
1155
Makoto Onuki02f338e2016-07-29 09:40:40 -07001156 // Requires mLock held, but "Locked" prefix would look weired so we jsut say "L".
1157 void throwIfUserLockedL(@UserIdInt int userId) {
1158 if (!isUserUnlockedL(userId)) {
Makoto Onuki9c850012016-07-26 15:50:50 -07001159 throw new IllegalStateException("User " + userId + " is locked or not running");
1160 }
1161 }
1162
Makoto Onukicdc78f72016-03-21 15:47:52 -07001163 @GuardedBy("mLock")
1164 @NonNull
Makoto Onuki2e210c42016-03-30 08:30:36 -07001165 private boolean isUserLoadedLocked(@UserIdInt int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07001166 return mUsers.get(userId) != null;
1167 }
1168
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001169 /** Return the per-user state. */
1170 @GuardedBy("mLock")
1171 @NonNull
Makoto Onuki31459242016-03-22 11:12:18 -07001172 ShortcutUser getUserShortcutsLocked(@UserIdInt int userId) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001173 if (!isUserUnlockedL(userId)) {
Makoto Onuki9c850012016-07-26 15:50:50 -07001174 wtf("User still locked");
Makoto Onuki9c850012016-07-26 15:50:50 -07001175 }
1176
Makoto Onuki31459242016-03-22 11:12:18 -07001177 ShortcutUser userPackages = mUsers.get(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001178 if (userPackages == null) {
1179 userPackages = loadUserLocked(userId);
1180 if (userPackages == null) {
Makoto Onukic51b2872016-05-04 15:24:50 -07001181 userPackages = new ShortcutUser(this, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001182 }
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08001183 mUsers.put(userId, userPackages);
Makoto Onuki085a05c2016-08-19 11:39:29 -07001184
1185 // Also when a user's data is first accessed, scan all packages.
1186 checkPackageChanges(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001187 }
1188 return userPackages;
1189 }
1190
Makoto Onuki2e210c42016-03-30 08:30:36 -07001191 void forEachLoadedUserLocked(@NonNull Consumer<ShortcutUser> c) {
1192 for (int i = mUsers.size() - 1; i >= 0; i--) {
1193 c.accept(mUsers.valueAt(i));
1194 }
1195 }
1196
Makoto Onukic8c33292016-09-12 16:36:59 -07001197 /**
1198 * Return the per-user per-package state. If the caller is a publisher, use
1199 * {@link #getPackageShortcutsForPublisherLocked} instead.
1200 */
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001201 @GuardedBy("mLock")
1202 @NonNull
Makoto Onuki31459242016-03-22 11:12:18 -07001203 ShortcutPackage getPackageShortcutsLocked(
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001204 @NonNull String packageName, @UserIdInt int userId) {
Makoto Onukic51b2872016-05-04 15:24:50 -07001205 return getUserShortcutsLocked(userId).getPackageShortcuts(packageName);
Makoto Onukide667372016-03-15 14:29:20 -07001206 }
1207
Makoto Onukic8c33292016-09-12 16:36:59 -07001208 /** Return the per-user per-package state. Use this when the caller is a publisher. */
1209 @GuardedBy("mLock")
1210 @NonNull
1211 ShortcutPackage getPackageShortcutsForPublisherLocked(
1212 @NonNull String packageName, @UserIdInt int userId) {
1213 final ShortcutPackage ret = getUserShortcutsLocked(userId).getPackageShortcuts(packageName);
1214 ret.getUser().onCalledByPublisher(packageName);
1215 return ret;
1216 }
1217
Makoto Onukide667372016-03-15 14:29:20 -07001218 @GuardedBy("mLock")
1219 @NonNull
Makoto Onuki2e210c42016-03-30 08:30:36 -07001220 ShortcutLauncher getLauncherShortcutsLocked(
1221 @NonNull String packageName, @UserIdInt int ownerUserId,
1222 @UserIdInt int launcherUserId) {
1223 return getUserShortcutsLocked(ownerUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07001224 .getLauncherShortcuts(packageName, launcherUserId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001225 }
1226
1227 // === Caller validation ===
1228
Makoto Onuki475c3652017-05-08 14:29:03 -07001229 void removeIconLocked(ShortcutInfo shortcut) {
1230 mShortcutBitmapSaver.removeIcon(shortcut);
Makoto Onuki55046222016-03-08 10:49:47 -08001231 }
1232
Makoto Onuki0033b2a2016-04-14 17:19:16 -07001233 public void cleanupBitmapsForPackage(@UserIdInt int userId, String packageName) {
1234 final File packagePath = new File(getUserBitmapFilePath(userId), packageName);
1235 if (!packagePath.isDirectory()) {
1236 return;
1237 }
1238 if (!(FileUtils.deleteContents(packagePath) && packagePath.delete())) {
1239 Slog.w(TAG, "Unable to remove directory " + packagePath);
1240 }
1241 }
1242
Makoto Onuki475c3652017-05-08 14:29:03 -07001243 /**
1244 * Remove dangling bitmap files for a user.
1245 *
1246 * Note this method must be called with the lock held after calling
1247 * {@link ShortcutBitmapSaver#waitForAllSavesLocked()} to make sure there's no pending bitmap
1248 * saves are going on.
1249 */
Makoto Onuki1e173232016-08-10 10:47:13 -07001250 private void cleanupDanglingBitmapDirectoriesLocked(@UserIdInt int userId) {
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001251 if (DEBUG) {
1252 Slog.d(TAG, "cleanupDanglingBitmaps: userId=" + userId);
1253 }
1254 final long start = injectElapsedRealtime();
1255
Makoto Onuki1e173232016-08-10 10:47:13 -07001256 final ShortcutUser user = getUserShortcutsLocked(userId);
1257
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001258 final File bitmapDir = getUserBitmapFilePath(userId);
1259 final File[] children = bitmapDir.listFiles();
1260 if (children == null) {
1261 return;
1262 }
1263 for (File child : children) {
1264 if (!child.isDirectory()) {
1265 continue;
1266 }
1267 final String packageName = child.getName();
1268 if (DEBUG) {
1269 Slog.d(TAG, "cleanupDanglingBitmaps: Found directory=" + packageName);
1270 }
1271 if (!user.hasPackage(packageName)) {
1272 if (DEBUG) {
1273 Slog.d(TAG, "Removing dangling bitmap directory: " + packageName);
1274 }
1275 cleanupBitmapsForPackage(userId, packageName);
1276 } else {
1277 cleanupDanglingBitmapFilesLocked(userId, user, packageName, child);
1278 }
1279 }
1280 logDurationStat(Stats.CLEANUP_DANGLING_BITMAPS, start);
1281 }
1282
Makoto Onuki475c3652017-05-08 14:29:03 -07001283 /**
1284 * Remove dangling bitmap files for a package.
1285 *
1286 * Note this method must be called with the lock held after calling
1287 * {@link ShortcutBitmapSaver#waitForAllSavesLocked()} to make sure there's no pending bitmap
1288 * saves are going on.
1289 */
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001290 private void cleanupDanglingBitmapFilesLocked(@UserIdInt int userId, @NonNull ShortcutUser user,
1291 @NonNull String packageName, @NonNull File path) {
1292 final ArraySet<String> usedFiles =
Makoto Onukic51b2872016-05-04 15:24:50 -07001293 user.getPackageShortcuts(packageName).getUsedBitmapFiles();
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001294
1295 for (File child : path.listFiles()) {
1296 if (!child.isFile()) {
1297 continue;
1298 }
1299 final String name = child.getName();
1300 if (!usedFiles.contains(name)) {
1301 if (DEBUG) {
1302 Slog.d(TAG, "Removing dangling bitmap file: " + child.getAbsolutePath());
1303 }
1304 child.delete();
1305 }
1306 }
1307 }
1308
Makoto Onuki55046222016-03-08 10:49:47 -08001309 @VisibleForTesting
1310 static class FileOutputStreamWithPath extends FileOutputStream {
1311 private final File mFile;
1312
1313 public FileOutputStreamWithPath(File file) throws FileNotFoundException {
1314 super(file);
1315 mFile = file;
1316 }
1317
1318 public File getFile() {
1319 return mFile;
1320 }
1321 }
1322
1323 /**
1324 * Build the cached bitmap filename for a shortcut icon.
1325 *
1326 * The filename will be based on the ID, except certain characters will be escaped.
1327 */
Makoto Onuki55046222016-03-08 10:49:47 -08001328 FileOutputStreamWithPath openIconFileForWrite(@UserIdInt int userId, ShortcutInfo shortcut)
1329 throws IOException {
1330 final File packagePath = new File(getUserBitmapFilePath(userId),
Makoto Onuki22fcc682016-05-17 14:52:19 -07001331 shortcut.getPackage());
Makoto Onuki55046222016-03-08 10:49:47 -08001332 if (!packagePath.isDirectory()) {
1333 packagePath.mkdirs();
1334 if (!packagePath.isDirectory()) {
1335 throw new IOException("Unable to create directory " + packagePath);
1336 }
1337 SELinux.restorecon(packagePath);
1338 }
1339
1340 final String baseName = String.valueOf(injectCurrentTimeMillis());
Makoto Onukib08790c2016-06-23 14:05:46 -07001341 for (int suffix = 0; ; suffix++) {
Makoto Onuki55046222016-03-08 10:49:47 -08001342 final String filename = (suffix == 0 ? baseName : baseName + "_" + suffix) + ".png";
1343 final File file = new File(packagePath, filename);
1344 if (!file.exists()) {
1345 if (DEBUG) {
1346 Slog.d(TAG, "Saving icon to " + file.getAbsolutePath());
1347 }
1348 return new FileOutputStreamWithPath(file);
1349 }
1350 }
1351 }
1352
Makoto Onuki475c3652017-05-08 14:29:03 -07001353 void saveIconAndFixUpShortcutLocked(ShortcutInfo shortcut) {
Makoto Onuki55046222016-03-08 10:49:47 -08001354 if (shortcut.hasIconFile() || shortcut.hasIconResource()) {
1355 return;
1356 }
1357
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001358 final long token = injectClearCallingIdentity();
Makoto Onuki55046222016-03-08 10:49:47 -08001359 try {
1360 // Clear icon info on the shortcut.
Makoto Onuki475c3652017-05-08 14:29:03 -07001361 removeIconLocked(shortcut);
Makoto Onuki55046222016-03-08 10:49:47 -08001362
1363 final Icon icon = shortcut.getIcon();
1364 if (icon == null) {
1365 return; // has no icon
1366 }
Hyunyoung Song47037462017-05-08 16:51:43 -07001367 int maxIconDimension = mMaxIconDimension;
Makoto Onukiabe84422016-04-07 09:41:19 -07001368 Bitmap bitmap;
Makoto Onuki55046222016-03-08 10:49:47 -08001369 try {
1370 switch (icon.getType()) {
1371 case Icon.TYPE_RESOURCE: {
1372 injectValidateIconResPackage(shortcut, icon);
1373
1374 shortcut.setIconResourceId(icon.getResId());
1375 shortcut.addFlags(ShortcutInfo.FLAG_HAS_ICON_RES);
1376 return;
1377 }
Hyunyoung Songf281e7a2017-02-13 10:57:42 -08001378 case Icon.TYPE_BITMAP:
Makoto Onukiabe84422016-04-07 09:41:19 -07001379 bitmap = icon.getBitmap(); // Don't recycle in this case.
Makoto Onuki55046222016-03-08 10:49:47 -08001380 break;
Hyunyoung Song47037462017-05-08 16:51:43 -07001381 case Icon.TYPE_ADAPTIVE_BITMAP: {
1382 bitmap = icon.getBitmap(); // Don't recycle in this case.
1383 maxIconDimension *= (1 + 2 * AdaptiveIconDrawable.getExtraInsetFraction());
Hyunyoung Song8947f592017-05-15 10:12:11 -07001384 break;
Makoto Onuki55046222016-03-08 10:49:47 -08001385 }
Makoto Onuki55046222016-03-08 10:49:47 -08001386 default:
1387 // This shouldn't happen because we've already validated the icon, but
1388 // just in case.
1389 throw ShortcutInfo.getInvalidIconException();
1390 }
Makoto Onuki475c3652017-05-08 14:29:03 -07001391 mShortcutBitmapSaver.saveBitmapLocked(shortcut,
Hyunyoung Song47037462017-05-08 16:51:43 -07001392 maxIconDimension, mIconPersistFormat, mIconPersistQuality);
Makoto Onuki55046222016-03-08 10:49:47 -08001393 } finally {
Makoto Onuki55046222016-03-08 10:49:47 -08001394 // Once saved, we won't use the original icon information, so null it out.
1395 shortcut.clearIcon();
1396 }
1397 } finally {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001398 injectRestoreCallingIdentity(token);
Makoto Onuki55046222016-03-08 10:49:47 -08001399 }
1400 }
1401
1402 // Unfortunately we can't do this check in unit tests because we fake creator package names,
1403 // so override in unit tests.
1404 // TODO CTS this case.
1405 void injectValidateIconResPackage(ShortcutInfo shortcut, Icon icon) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07001406 if (!shortcut.getPackage().equals(icon.getResPackage())) {
Makoto Onuki55046222016-03-08 10:49:47 -08001407 throw new IllegalArgumentException(
1408 "Icon resource must reside in shortcut owner package");
1409 }
1410 }
1411
Makoto Onuki55046222016-03-08 10:49:47 -08001412 static Bitmap shrinkBitmap(Bitmap in, int maxSize) {
1413 // Original width/height.
1414 final int ow = in.getWidth();
1415 final int oh = in.getHeight();
1416 if ((ow <= maxSize) && (oh <= maxSize)) {
1417 if (DEBUG) {
1418 Slog.d(TAG, String.format("Icon size %dx%d, no need to shrink", ow, oh));
1419 }
1420 return in;
1421 }
1422 final int longerDimension = Math.max(ow, oh);
1423
1424 // New width and height.
1425 final int nw = ow * maxSize / longerDimension;
1426 final int nh = oh * maxSize / longerDimension;
1427 if (DEBUG) {
1428 Slog.d(TAG, String.format("Icon size %dx%d, shrinking to %dx%d",
1429 ow, oh, nw, nh));
1430 }
1431
1432 final Bitmap scaledBitmap = Bitmap.createBitmap(nw, nh, Bitmap.Config.ARGB_8888);
1433 final Canvas c = new Canvas(scaledBitmap);
1434
1435 final RectF dst = new RectF(0, 0, nw, nh);
1436
1437 c.drawBitmap(in, /*src=*/ null, dst, /* paint =*/ null);
1438
Makoto Onuki55046222016-03-08 10:49:47 -08001439 return scaledBitmap;
1440 }
1441
Makoto Onuki157b1622016-06-02 16:13:10 -07001442 /**
1443 * For a shortcut, update all resource names from resource IDs, and also update all
1444 * resource-based strings.
1445 */
1446 void fixUpShortcutResourceNamesAndValues(ShortcutInfo si) {
1447 final Resources publisherRes = injectGetResourcesForApplicationAsUser(
1448 si.getPackage(), si.getUserId());
1449 if (publisherRes != null) {
1450 final long start = injectElapsedRealtime();
1451 try {
1452 si.lookupAndFillInResourceNames(publisherRes);
1453 } finally {
1454 logDurationStat(Stats.RESOURCE_NAME_LOOKUP, start);
1455 }
1456 si.resolveResourceStrings(publisherRes);
1457 }
1458 }
1459
Makoto Onuki55046222016-03-08 10:49:47 -08001460 // === Caller validation ===
1461
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001462 private boolean isCallerSystem() {
1463 final int callingUid = injectBinderCallingUid();
Makoto Onukib08790c2016-06-23 14:05:46 -07001464 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001465 }
1466
1467 private boolean isCallerShell() {
1468 final int callingUid = injectBinderCallingUid();
1469 return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
1470 }
1471
1472 private void enforceSystemOrShell() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001473 if (!(isCallerSystem() || isCallerShell())) {
1474 throw new SecurityException("Caller must be system or shell");
1475 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001476 }
1477
1478 private void enforceShell() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001479 if (!isCallerShell()) {
1480 throw new SecurityException("Caller must be shell");
1481 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001482 }
1483
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001484 private void enforceSystem() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001485 if (!isCallerSystem()) {
1486 throw new SecurityException("Caller must be system");
1487 }
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001488 }
1489
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001490 private void enforceResetThrottlingPermission() {
1491 if (isCallerSystem()) {
1492 return;
1493 }
Makoto Onuki76269922016-07-15 14:58:54 -07001494 enforceCallingOrSelfPermission(
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001495 android.Manifest.permission.RESET_SHORTCUT_MANAGER_THROTTLING, null);
1496 }
1497
Makoto Onuki76269922016-07-15 14:58:54 -07001498 private void enforceCallingOrSelfPermission(
1499 @NonNull String permission, @Nullable String message) {
1500 if (isCallerSystem()) {
1501 return;
1502 }
1503 injectEnforceCallingPermission(permission, message);
1504 }
1505
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001506 /**
1507 * Somehow overriding ServiceContext.enforceCallingPermission() in the unit tests would confuse
1508 * mockito. So instead we extracted it here and override it in the tests.
1509 */
1510 @VisibleForTesting
1511 void injectEnforceCallingPermission(
1512 @NonNull String permission, @Nullable String message) {
1513 mContext.enforceCallingPermission(permission, message);
1514 }
1515
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001516 private void verifyCaller(@NonNull String packageName, @UserIdInt int userId) {
1517 Preconditions.checkStringNotEmpty(packageName, "packageName");
1518
1519 if (isCallerSystem()) {
1520 return; // no check
1521 }
1522
1523 final int callingUid = injectBinderCallingUid();
1524
1525 // Otherwise, make sure the arguments are valid.
1526 if (UserHandle.getUserId(callingUid) != userId) {
1527 throw new SecurityException("Invalid user-ID");
1528 }
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08001529 if (injectGetPackageUid(packageName, userId) != callingUid) {
1530 throw new SecurityException("Calling package name mismatch");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001531 }
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08001532 Preconditions.checkState(!isEphemeralApp(packageName, userId),
1533 "Ephemeral apps can't use ShortcutManager");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001534 }
1535
Makoto Onuki157b1622016-06-02 16:13:10 -07001536 // Overridden in unit tests to execute r synchronously.
1537 void injectPostToHandler(Runnable r) {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001538 mHandler.post(r);
1539 }
1540
Makoto Onuki085a05c2016-08-19 11:39:29 -07001541 void injectRunOnNewThread(Runnable r) {
1542 new Thread(r).start();
1543 }
1544
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001545 /**
Makoto Onuki7001a612016-05-27 13:24:28 -07001546 * @throws IllegalArgumentException if {@code numShortcuts} is bigger than
Makoto Onukib08790c2016-06-23 14:05:46 -07001547 * {@link #getMaxActivityShortcuts()}.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001548 */
Makoto Onuki7001a612016-05-27 13:24:28 -07001549 void enforceMaxActivityShortcuts(int numShortcuts) {
Makoto Onukib5a012f2016-06-21 11:13:53 -07001550 if (numShortcuts > mMaxShortcuts) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001551 throw new IllegalArgumentException("Max number of dynamic shortcuts exceeded");
1552 }
1553 }
1554
1555 /**
Makoto Onuki7001a612016-05-27 13:24:28 -07001556 * Return the max number of dynamic + manifest shortcuts for each launcher icon.
1557 */
1558 int getMaxActivityShortcuts() {
Makoto Onukib5a012f2016-06-21 11:13:53 -07001559 return mMaxShortcuts;
Makoto Onuki7001a612016-05-27 13:24:28 -07001560 }
1561
1562 /**
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001563 * - Sends a notification to LauncherApps
1564 * - Write to file
1565 */
Makoto Onuki39686e82016-04-13 18:03:00 -07001566 void packageShortcutsChanged(@NonNull String packageName, @UserIdInt int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001567 notifyListeners(packageName, userId);
1568 scheduleSaveUser(userId);
1569 }
1570
1571 private void notifyListeners(@NonNull String packageName, @UserIdInt int userId) {
Makoto Onuki82fb2eb2017-03-31 16:58:26 -07001572 if (DEBUG) {
1573 Slog.d(TAG, String.format(
1574 "Shortcut changes: package=%s, user=%d", packageName, userId));
1575 }
Makoto Onuki157b1622016-06-02 16:13:10 -07001576 injectPostToHandler(() -> {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001577 try {
1578 final ArrayList<ShortcutChangeListener> copy;
1579 synchronized (mLock) {
1580 if (!isUserUnlockedL(userId)) {
1581 return;
1582 }
1583
1584 copy = new ArrayList<>(mListeners);
1585 }
1586 // Note onShortcutChanged() needs to be called with the system service permissions.
1587 for (int i = copy.size() - 1; i >= 0; i--) {
1588 copy.get(i).onShortcutChanged(packageName, userId);
1589 }
1590 } catch (Exception ignore) {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001591 }
1592 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001593 }
1594
1595 /**
1596 * Clean up / validate an incoming shortcut.
1597 * - Make sure all mandatory fields are set.
1598 * - Make sure the intent's extras are persistable, and them to set
Makoto Onuki0eed4412016-07-21 11:21:59 -07001599 * {@link ShortcutInfo#mIntentPersistableExtrases}. Also clear its extras.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001600 * - Clear flags.
1601 */
Makoto Onuki2d895c32016-12-02 15:48:40 -08001602 private void fixUpIncomingShortcutInfo(@NonNull ShortcutInfo shortcut, boolean forUpdate,
1603 boolean forPinRequest) {
Makoto Onukibf563b62017-05-04 10:25:30 -07001604 if (shortcut.isReturnedByServer()) {
1605 Log.w(TAG,
1606 "Re-publishing ShortcutInfo returned by server is not supported."
1607 + " Some information such as icon may lost from shortcut.");
1608 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001609 Preconditions.checkNotNull(shortcut, "Null shortcut detected");
Makoto Onuki255461f2017-01-10 11:47:25 -08001610 if (shortcut.getActivity() != null) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001611 Preconditions.checkState(
Makoto Onuki22fcc682016-05-17 14:52:19 -07001612 shortcut.getPackage().equals(shortcut.getActivity().getPackageName()),
Makoto Onukib08790c2016-06-23 14:05:46 -07001613 "Cannot publish shortcut: activity " + shortcut.getActivity() + " does not"
1614 + " belong to package " + shortcut.getPackage());
Makoto Onuki13260b6ff2016-07-13 18:03:13 -07001615 Preconditions.checkState(
1616 injectIsMainActivity(shortcut.getActivity(), shortcut.getUserId()),
1617 "Cannot publish shortcut: activity " + shortcut.getActivity() + " is not"
1618 + " main activity");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001619 }
1620
Makoto Onuki55046222016-03-08 10:49:47 -08001621 if (!forUpdate) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08001622 shortcut.enforceMandatoryFields(/* forPinned= */ forPinRequest);
1623 if (!forPinRequest) {
Makoto Onuki255461f2017-01-10 11:47:25 -08001624 Preconditions.checkState(shortcut.getActivity() != null,
1625 "Cannot publish shortcut: target activity is not set");
Makoto Onuki2d895c32016-12-02 15:48:40 -08001626 }
Makoto Onuki55046222016-03-08 10:49:47 -08001627 }
1628 if (shortcut.getIcon() != null) {
1629 ShortcutInfo.validateIcon(shortcut.getIcon());
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001630 }
1631
Makoto Onukide667372016-03-15 14:29:20 -07001632 shortcut.replaceFlags(0);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001633 }
1634
Makoto Onuki2d895c32016-12-02 15:48:40 -08001635 private void fixUpIncomingShortcutInfo(@NonNull ShortcutInfo shortcut, boolean forUpdate) {
1636 fixUpIncomingShortcutInfo(shortcut, forUpdate, /*forPinRequest=*/ false);
1637 }
1638
1639 public void validateShortcutForPinRequest(@NonNull ShortcutInfo shortcut) {
1640 fixUpIncomingShortcutInfo(shortcut, /* forUpdate= */ false, /*forPinRequest=*/ true);
1641 }
1642
Makoto Onukib08790c2016-06-23 14:05:46 -07001643 /**
1644 * When a shortcut has no target activity, set the default one from the package.
1645 */
1646 private void fillInDefaultActivity(List<ShortcutInfo> shortcuts) {
Makoto Onukib08790c2016-06-23 14:05:46 -07001647 ComponentName defaultActivity = null;
1648 for (int i = shortcuts.size() - 1; i >= 0; i--) {
1649 final ShortcutInfo si = shortcuts.get(i);
1650 if (si.getActivity() == null) {
1651 if (defaultActivity == null) {
1652 defaultActivity = injectGetDefaultMainActivity(
1653 si.getPackage(), si.getUserId());
1654 Preconditions.checkState(defaultActivity != null,
1655 "Launcher activity not found for package " + si.getPackage());
1656 }
1657 si.setActivity(defaultActivity);
1658 }
1659 }
1660 }
1661
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001662 private void assignImplicitRanks(List<ShortcutInfo> shortcuts) {
1663 for (int i = shortcuts.size() - 1; i >= 0; i--) {
1664 shortcuts.get(i).setImplicitRank(i);
1665 }
1666 }
1667
Makoto Onukibf563b62017-05-04 10:25:30 -07001668 private List<ShortcutInfo> setReturnedByServer(List<ShortcutInfo> shortcuts) {
1669 for (int i = shortcuts.size() - 1; i >= 0; i--) {
1670 shortcuts.get(i).setReturnedByServer();
1671 }
1672 return shortcuts;
1673 }
1674
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001675 // === APIs ===
1676
1677 @Override
1678 public boolean setDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1679 @UserIdInt int userId) {
1680 verifyCaller(packageName, userId);
1681
1682 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
1683 final int size = newShortcuts.size();
1684
1685 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001686 throwIfUserLockedL(userId);
1687
Makoto Onukic8c33292016-09-12 16:36:59 -07001688 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001689
Makoto Onuki22fcc682016-05-17 14:52:19 -07001690 ps.ensureImmutableShortcutsNotIncluded(newShortcuts);
1691
Makoto Onukib08790c2016-06-23 14:05:46 -07001692 fillInDefaultActivity(newShortcuts);
1693
Makoto Onuki7001a612016-05-27 13:24:28 -07001694 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_SET);
1695
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001696 // Throttling.
Makoto Onukic51b2872016-05-04 15:24:50 -07001697 if (!ps.tryApiCall()) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001698 return false;
1699 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001700
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001701 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1702 ps.clearAllImplicitRanks();
1703 assignImplicitRanks(newShortcuts);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001704
Makoto Onukidf6da042016-06-16 09:51:40 -07001705 for (int i = 0; i < size; i++) {
1706 fixUpIncomingShortcutInfo(newShortcuts.get(i), /* forUpdate= */ false);
1707 }
1708
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001709 // First, remove all un-pinned; dynamic shortcuts
Makoto Onukic51b2872016-05-04 15:24:50 -07001710 ps.deleteAllDynamicShortcuts();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001711
1712 // Then, add/update all. We need to make sure to take over "pinned" flag.
1713 for (int i = 0; i < size; i++) {
1714 final ShortcutInfo newShortcut = newShortcuts.get(i);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001715 ps.addOrUpdateDynamicShortcut(newShortcut);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001716 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001717
1718 // Lastly, adjust the ranks.
1719 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001720 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001721 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001722
1723 verifyStates();
1724
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001725 return true;
1726 }
1727
1728 @Override
1729 public boolean updateShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1730 @UserIdInt int userId) {
1731 verifyCaller(packageName, userId);
1732
1733 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
Makoto Onuki55046222016-03-08 10:49:47 -08001734 final int size = newShortcuts.size();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001735
1736 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001737 throwIfUserLockedL(userId);
1738
Makoto Onukic8c33292016-09-12 16:36:59 -07001739 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001740
Makoto Onuki22fcc682016-05-17 14:52:19 -07001741 ps.ensureImmutableShortcutsNotIncluded(newShortcuts);
1742
Makoto Onukib08790c2016-06-23 14:05:46 -07001743 // For update, don't fill in the default activity. Having null activity means
1744 // "don't update the activity" here.
1745
Makoto Onuki7001a612016-05-27 13:24:28 -07001746 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_UPDATE);
1747
Makoto Onuki55046222016-03-08 10:49:47 -08001748 // Throttling.
Makoto Onukic51b2872016-05-04 15:24:50 -07001749 if (!ps.tryApiCall()) {
Makoto Onuki55046222016-03-08 10:49:47 -08001750 return false;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001751 }
1752
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001753 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1754 ps.clearAllImplicitRanks();
1755 assignImplicitRanks(newShortcuts);
1756
Makoto Onuki55046222016-03-08 10:49:47 -08001757 for (int i = 0; i < size; i++) {
1758 final ShortcutInfo source = newShortcuts.get(i);
1759 fixUpIncomingShortcutInfo(source, /* forUpdate= */ true);
1760
1761 final ShortcutInfo target = ps.findShortcutById(source.getId());
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001762 if (target == null) {
1763 continue;
1764 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07001765
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001766 if (target.isEnabled() != source.isEnabled()) {
1767 Slog.w(TAG,
1768 "ShortcutInfo.enabled cannot be changed with updateShortcuts()");
1769 }
Makoto Onuki55046222016-03-08 10:49:47 -08001770
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001771 // When updating the rank, we need to insert between existing ranks, so set
1772 // this setRankChanged, and also copy the implicit rank fo adjustRanks().
1773 if (source.hasRank()) {
1774 target.setRankChanged();
1775 target.setImplicitRank(source.getImplicitRank());
1776 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07001777
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001778 final boolean replacingIcon = (source.getIcon() != null);
1779 if (replacingIcon) {
Makoto Onuki475c3652017-05-08 14:29:03 -07001780 removeIconLocked(target);
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001781 }
Makoto Onuki55046222016-03-08 10:49:47 -08001782
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001783 // Note copyNonNullFieldsFrom() does the "updatable with?" check too.
1784 target.copyNonNullFieldsFrom(source);
1785 target.setTimestamp(injectCurrentTimeMillis());
1786
1787 if (replacingIcon) {
Makoto Onuki475c3652017-05-08 14:29:03 -07001788 saveIconAndFixUpShortcutLocked(target);
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001789 }
1790
1791 // When we're updating any resource related fields, re-extract the res names and
1792 // the values.
1793 if (replacingIcon || source.hasStringResources()) {
1794 fixUpShortcutResourceNamesAndValues(target);
Makoto Onuki55046222016-03-08 10:49:47 -08001795 }
1796 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001797
1798 // Lastly, adjust the ranks.
1799 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001800 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001801 packageShortcutsChanged(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001802
Makoto Onuki7001a612016-05-27 13:24:28 -07001803 verifyStates();
1804
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001805 return true;
1806 }
1807
1808 @Override
Makoto Onukib6d35232016-04-04 15:57:17 -07001809 public boolean addDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001810 @UserIdInt int userId) {
1811 verifyCaller(packageName, userId);
1812
Makoto Onukib6d35232016-04-04 15:57:17 -07001813 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
1814 final int size = newShortcuts.size();
1815
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001816 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001817 throwIfUserLockedL(userId);
1818
Makoto Onukic8c33292016-09-12 16:36:59 -07001819 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001820
Makoto Onuki22fcc682016-05-17 14:52:19 -07001821 ps.ensureImmutableShortcutsNotIncluded(newShortcuts);
1822
Makoto Onukib08790c2016-06-23 14:05:46 -07001823 fillInDefaultActivity(newShortcuts);
1824
Makoto Onuki7001a612016-05-27 13:24:28 -07001825 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_ADD);
1826
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001827 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1828 ps.clearAllImplicitRanks();
1829 assignImplicitRanks(newShortcuts);
1830
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001831 // Throttling.
Makoto Onukic51b2872016-05-04 15:24:50 -07001832 if (!ps.tryApiCall()) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001833 return false;
1834 }
Makoto Onukib6d35232016-04-04 15:57:17 -07001835 for (int i = 0; i < size; i++) {
1836 final ShortcutInfo newShortcut = newShortcuts.get(i);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001837
Makoto Onukib6d35232016-04-04 15:57:17 -07001838 // Validate the shortcut.
1839 fixUpIncomingShortcutInfo(newShortcut, /* forUpdate= */ false);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001840
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001841 // When ranks are changing, we need to insert between ranks, so set the
1842 // "rank changed" flag.
1843 newShortcut.setRankChanged();
1844
Makoto Onukib6d35232016-04-04 15:57:17 -07001845 // Add it.
Makoto Onuki22fcc682016-05-17 14:52:19 -07001846 ps.addOrUpdateDynamicShortcut(newShortcut);
Makoto Onukib6d35232016-04-04 15:57:17 -07001847 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001848
1849 // Lastly, adjust the ranks.
1850 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001851 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001852 packageShortcutsChanged(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001853
Makoto Onuki7001a612016-05-27 13:24:28 -07001854 verifyStates();
1855
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001856 return true;
1857 }
1858
1859 @Override
Makoto Onuki2d895c32016-12-02 15:48:40 -08001860 public boolean requestPinShortcut(String packageName, ShortcutInfo shortcut,
1861 IntentSender resultIntent, int userId) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08001862 Preconditions.checkNotNull(shortcut);
1863 Preconditions.checkArgument(shortcut.isEnabled(), "Shortcut must be enabled");
Sunny Goyal4ad6b572017-02-28 11:11:51 -08001864 return requestPinItem(packageName, userId, shortcut, null, null, resultIntent);
Sunny Goyal87a563e2017-01-01 19:42:45 -08001865 }
1866
Sunny Goyala6be88a2017-01-12 16:27:58 -08001867 @Override
1868 public Intent createShortcutResultIntent(String packageName, ShortcutInfo shortcut, int userId)
1869 throws RemoteException {
1870 Preconditions.checkNotNull(shortcut);
1871 Preconditions.checkArgument(shortcut.isEnabled(), "Shortcut must be enabled");
1872 verifyCaller(packageName, userId);
1873
1874 final Intent ret;
1875 synchronized (mLock) {
1876 throwIfUserLockedL(userId);
1877
1878 // Send request to the launcher, if supported.
1879 ret = mShortcutRequestPinProcessor.createShortcutResultIntent(shortcut, userId);
1880 }
1881
1882 verifyStates();
1883 return ret;
1884 }
1885
Sunny Goyal87a563e2017-01-01 19:42:45 -08001886 /**
1887 * Handles {@link #requestPinShortcut} and {@link ShortcutServiceInternal#requestPinAppWidget}.
1888 * After validating the caller, it passes the request to {@link #mShortcutRequestPinProcessor}.
1889 * Either {@param shortcut} or {@param appWidget} should be non-null.
1890 */
Sunny Goyal4ad6b572017-02-28 11:11:51 -08001891 private boolean requestPinItem(String packageName, int userId, ShortcutInfo shortcut,
1892 AppWidgetProviderInfo appWidget, Bundle extras, IntentSender resultIntent) {
Sunny Goyal87a563e2017-01-01 19:42:45 -08001893 verifyCaller(packageName, userId);
Makoto Onuki2d895c32016-12-02 15:48:40 -08001894
1895 final boolean ret;
1896 synchronized (mLock) {
1897 throwIfUserLockedL(userId);
1898
Makoto Onukia01f4f02016-12-15 15:58:41 -08001899 Preconditions.checkState(isUidForegroundLocked(injectBinderCallingUid()),
Makoto Onuki255461f2017-01-10 11:47:25 -08001900 "Calling application must have a foreground activity or a foreground service");
Makoto Onuki2d895c32016-12-02 15:48:40 -08001901
1902 // Send request to the launcher, if supported.
Sunny Goyal4ad6b572017-02-28 11:11:51 -08001903 ret = mShortcutRequestPinProcessor.requestPinItemLocked(shortcut, appWidget, extras,
1904 userId, resultIntent);
Makoto Onuki2d895c32016-12-02 15:48:40 -08001905 }
1906
1907 verifyStates();
1908
1909 return ret;
1910 }
1911
1912 @Override
Makoto Onuki20c95f82016-05-11 16:51:01 -07001913 public void disableShortcuts(String packageName, List shortcutIds,
Makoto Onukid6880792016-06-29 13:37:43 -07001914 CharSequence disabledMessage, int disabledMessageResId, @UserIdInt int userId) {
Makoto Onuki20c95f82016-05-11 16:51:01 -07001915 verifyCaller(packageName, userId);
1916 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
1917
1918 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001919 throwIfUserLockedL(userId);
1920
Makoto Onukic8c33292016-09-12 16:36:59 -07001921 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001922
1923 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds);
1924
Makoto Onukid6880792016-06-29 13:37:43 -07001925 final String disabledMessageString =
1926 (disabledMessage == null) ? null : disabledMessage.toString();
1927
Makoto Onuki22fcc682016-05-17 14:52:19 -07001928 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
1929 ps.disableWithId(Preconditions.checkStringNotEmpty((String) shortcutIds.get(i)),
Makoto Onukid6880792016-06-29 13:37:43 -07001930 disabledMessageString, disabledMessageResId,
Makoto Onuki22fcc682016-05-17 14:52:19 -07001931 /* overrideImmutable=*/ false);
1932 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001933
1934 // We may have removed dynamic shortcuts which may have left a gap, so adjust the ranks.
1935 ps.adjustRanks();
Makoto Onuki22fcc682016-05-17 14:52:19 -07001936 }
1937 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001938
1939 verifyStates();
Makoto Onuki22fcc682016-05-17 14:52:19 -07001940 }
1941
1942 @Override
1943 public void enableShortcuts(String packageName, List shortcutIds, @UserIdInt int userId) {
1944 verifyCaller(packageName, userId);
1945 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
1946
1947 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001948 throwIfUserLockedL(userId);
1949
Makoto Onukic8c33292016-09-12 16:36:59 -07001950 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001951
1952 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds);
1953
1954 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
1955 ps.enableWithId((String) shortcutIds.get(i));
1956 }
Makoto Onuki20c95f82016-05-11 16:51:01 -07001957 }
1958 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001959
1960 verifyStates();
Makoto Onuki20c95f82016-05-11 16:51:01 -07001961 }
1962
1963 @Override
Makoto Onukib6d35232016-04-04 15:57:17 -07001964 public void removeDynamicShortcuts(String packageName, List shortcutIds,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001965 @UserIdInt int userId) {
1966 verifyCaller(packageName, userId);
Makoto Onukib6d35232016-04-04 15:57:17 -07001967 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001968
1969 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001970 throwIfUserLockedL(userId);
1971
Makoto Onukic8c33292016-09-12 16:36:59 -07001972 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001973
1974 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds);
1975
Makoto Onukib6d35232016-04-04 15:57:17 -07001976 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07001977 ps.deleteDynamicWithId(
Makoto Onukib6d35232016-04-04 15:57:17 -07001978 Preconditions.checkStringNotEmpty((String) shortcutIds.get(i)));
1979 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001980
1981 // We may have removed dynamic shortcuts which may have left a gap, so adjust the ranks.
1982 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001983 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001984 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001985
1986 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001987 }
1988
1989 @Override
Makoto Onukib6d35232016-04-04 15:57:17 -07001990 public void removeAllDynamicShortcuts(String packageName, @UserIdInt int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001991 verifyCaller(packageName, userId);
1992
1993 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001994 throwIfUserLockedL(userId);
1995
Makoto Onukic8c33292016-09-12 16:36:59 -07001996 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07001997 ps.deleteAllDynamicShortcuts();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001998 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001999 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07002000
2001 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002002 }
2003
2004 @Override
2005 public ParceledListSlice<ShortcutInfo> getDynamicShortcuts(String packageName,
2006 @UserIdInt int userId) {
2007 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002008
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002009 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002010 throwIfUserLockedL(userId);
2011
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002012 return getShortcutsWithQueryLocked(
2013 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
Makoto Onuki99302b52017-03-29 12:42:26 -07002014 ShortcutInfo::isDynamic);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002015 }
2016 }
2017
2018 @Override
Makoto Onuki22fcc682016-05-17 14:52:19 -07002019 public ParceledListSlice<ShortcutInfo> getManifestShortcuts(String packageName,
2020 @UserIdInt int userId) {
2021 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002022
Makoto Onuki22fcc682016-05-17 14:52:19 -07002023 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002024 throwIfUserLockedL(userId);
2025
Makoto Onuki22fcc682016-05-17 14:52:19 -07002026 return getShortcutsWithQueryLocked(
2027 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
2028 ShortcutInfo::isManifestShortcut);
2029 }
2030 }
2031
2032 @Override
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002033 public ParceledListSlice<ShortcutInfo> getPinnedShortcuts(String packageName,
2034 @UserIdInt int userId) {
2035 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002036
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002037 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002038 throwIfUserLockedL(userId);
2039
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002040 return getShortcutsWithQueryLocked(
2041 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
2042 ShortcutInfo::isPinned);
2043 }
2044 }
2045
2046 private ParceledListSlice<ShortcutInfo> getShortcutsWithQueryLocked(@NonNull String packageName,
2047 @UserIdInt int userId, int cloneFlags, @NonNull Predicate<ShortcutInfo> query) {
2048
2049 final ArrayList<ShortcutInfo> ret = new ArrayList<>();
2050
Makoto Onukic8c33292016-09-12 16:36:59 -07002051 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002052 ps.findAll(ret, query, cloneFlags);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002053
Makoto Onukibf563b62017-05-04 10:25:30 -07002054 return new ParceledListSlice<>(setReturnedByServer(ret));
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002055 }
2056
2057 @Override
Makoto Onukid6880792016-06-29 13:37:43 -07002058 public int getMaxShortcutCountPerActivity(String packageName, @UserIdInt int userId)
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002059 throws RemoteException {
2060 verifyCaller(packageName, userId);
2061
Makoto Onukib5a012f2016-06-21 11:13:53 -07002062 return mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002063 }
2064
2065 @Override
2066 public int getRemainingCallCount(String packageName, @UserIdInt int userId) {
2067 verifyCaller(packageName, userId);
2068
2069 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002070 throwIfUserLockedL(userId);
2071
Makoto Onukic8c33292016-09-12 16:36:59 -07002072 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002073 return mMaxUpdatesPerInterval - ps.getApiCallCount();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002074 }
2075 }
2076
2077 @Override
2078 public long getRateLimitResetTime(String packageName, @UserIdInt int userId) {
2079 verifyCaller(packageName, userId);
2080
2081 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002082 throwIfUserLockedL(userId);
2083
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002084 return getNextResetTimeLocked();
2085 }
2086 }
2087
Makoto Onuki55046222016-03-08 10:49:47 -08002088 @Override
Makoto Onuki20c95f82016-05-11 16:51:01 -07002089 public int getIconMaxDimensions(String packageName, int userId) {
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002090 verifyCaller(packageName, userId);
2091
Makoto Onuki55046222016-03-08 10:49:47 -08002092 synchronized (mLock) {
2093 return mMaxIconDimension;
2094 }
2095 }
2096
Makoto Onuki20c95f82016-05-11 16:51:01 -07002097 @Override
2098 public void reportShortcutUsed(String packageName, String shortcutId, int userId) {
2099 verifyCaller(packageName, userId);
2100
Makoto Onukiac042502016-05-20 16:39:42 -07002101 Preconditions.checkNotNull(shortcutId);
2102
2103 if (DEBUG) {
2104 Slog.d(TAG, String.format("reportShortcutUsed: Shortcut %s package %s used on user %d",
2105 shortcutId, packageName, userId));
2106 }
2107
2108 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002109 throwIfUserLockedL(userId);
2110
Makoto Onukic8c33292016-09-12 16:36:59 -07002111 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002112
Makoto Onukiac042502016-05-20 16:39:42 -07002113 if (ps.findShortcutById(shortcutId) == null) {
2114 Log.w(TAG, String.format("reportShortcutUsed: package %s doesn't have shortcut %s",
2115 packageName, shortcutId));
2116 return;
2117 }
2118 }
2119
2120 final long token = injectClearCallingIdentity();
2121 try {
2122 mUsageStatsManagerInternal.reportShortcutUsage(packageName, shortcutId, userId);
2123 } finally {
2124 injectRestoreCallingIdentity(token);
2125 }
Makoto Onuki20c95f82016-05-11 16:51:01 -07002126 }
2127
Makoto Onuki2d895c32016-12-02 15:48:40 -08002128 @Override
Sunny Goyal7f7372a2017-01-24 11:53:54 -08002129 public boolean isRequestPinItemSupported(int callingUserId, int requestType) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08002130 final long token = injectClearCallingIdentity();
2131 try {
Sunny Goyal7f7372a2017-01-24 11:53:54 -08002132 return mShortcutRequestPinProcessor
2133 .isRequestPinItemSupported(callingUserId, requestType);
Makoto Onuki2d895c32016-12-02 15:48:40 -08002134 } finally {
2135 injectRestoreCallingIdentity(token);
2136 }
2137 }
2138
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002139 /**
Makoto Onukib08790c2016-06-23 14:05:46 -07002140 * Reset all throttling, for developer options and command line. Only system/shell can call
2141 * it.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002142 */
2143 @Override
2144 public void resetThrottling() {
2145 enforceSystemOrShell();
2146
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002147 resetThrottlingInner(getCallingUserId());
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002148 }
2149
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002150 void resetThrottlingInner(@UserIdInt int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002151 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002152 if (!isUserUnlockedL(userId)) {
2153 Log.w(TAG, "User " + userId + " is locked or not running");
2154 return;
2155 }
2156
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002157 getUserShortcutsLocked(userId).resetThrottling();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002158 }
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002159 scheduleSaveUser(userId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002160 Slog.i(TAG, "ShortcutManager: throttling counter reset for user " + userId);
2161 }
2162
2163 void resetAllThrottlingInner() {
2164 synchronized (mLock) {
2165 mRawLastResetTime = injectCurrentTimeMillis();
2166 }
2167 scheduleSaveBaseState();
2168 Slog.i(TAG, "ShortcutManager: throttling counter reset for all users");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002169 }
2170
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002171 @Override
2172 public void onApplicationActive(String packageName, int userId) {
2173 if (DEBUG) {
2174 Slog.d(TAG, "onApplicationActive: package=" + packageName + " userid=" + userId);
2175 }
2176 enforceResetThrottlingPermission();
Makoto Onuki02f338e2016-07-29 09:40:40 -07002177
2178 synchronized (mLock) {
2179 if (!isUserUnlockedL(userId)) {
2180 // This is called by system UI, so no need to throw. Just ignore.
2181 return;
2182 }
2183
2184 getPackageShortcutsLocked(packageName, userId)
2185 .resetRateLimitingForCommandLineNoSaving();
2186 saveUserLocked(userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002187 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002188 }
2189
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002190 // We override this method in unit tests to do a simpler check.
2191 boolean hasShortcutHostPermission(@NonNull String callingPackage, int userId) {
Makoto Onuki10305202016-07-14 18:14:08 -07002192 final long start = injectElapsedRealtime();
2193 try {
2194 return hasShortcutHostPermissionInner(callingPackage, userId);
2195 } finally {
2196 logDurationStat(Stats.LAUNCHER_PERMISSION_CHECK, start);
2197 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002198 }
2199
2200 // This method is extracted so we can directly call this method from unit tests,
2201 // even when hasShortcutPermission() is overridden.
2202 @VisibleForTesting
Makoto Onuki2d895c32016-12-02 15:48:40 -08002203 boolean hasShortcutHostPermissionInner(@NonNull String packageName, int userId) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002204 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002205 throwIfUserLockedL(userId);
2206
Makoto Onuki31459242016-03-22 11:12:18 -07002207 final ShortcutUser user = getUserShortcutsLocked(userId);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002208
Makoto Onuki2d895c32016-12-02 15:48:40 -08002209 // Always trust the cached component.
Makoto Onuki10305202016-07-14 18:14:08 -07002210 final ComponentName cached = user.getCachedLauncher();
2211 if (cached != null) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08002212 if (cached.getPackageName().equals(packageName)) {
Makoto Onuki10305202016-07-14 18:14:08 -07002213 return true;
2214 }
2215 }
2216 // If the cached one doesn't match, then go ahead
2217
Makoto Onuki2d895c32016-12-02 15:48:40 -08002218 final ComponentName detected = getDefaultLauncher(userId);
Makoto Onuki2e210c42016-03-30 08:30:36 -07002219
Makoto Onuki10305202016-07-14 18:14:08 -07002220 // Update the cache.
2221 user.setLauncher(detected);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002222 if (detected != null) {
2223 if (DEBUG) {
2224 Slog.v(TAG, "Detected launcher: " + detected);
2225 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08002226 return detected.getPackageName().equals(packageName);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002227 } else {
2228 // Default launcher not found.
2229 return false;
2230 }
2231 }
2232 }
2233
Makoto Onuki2d895c32016-12-02 15:48:40 -08002234 @Nullable
2235 ComponentName getDefaultLauncher(@UserIdInt int userId) {
2236 final long start = injectElapsedRealtime();
2237 final long token = injectClearCallingIdentity();
2238 try {
2239 synchronized (mLock) {
2240 throwIfUserLockedL(userId);
2241
2242 final ShortcutUser user = getUserShortcutsLocked(userId);
2243
2244 final List<ResolveInfo> allHomeCandidates = new ArrayList<>();
2245
2246 // Default launcher from package manager.
2247 final long startGetHomeActivitiesAsUser = injectElapsedRealtime();
2248 final ComponentName defaultLauncher = mPackageManagerInternal
2249 .getHomeActivitiesAsUser(allHomeCandidates, userId);
2250 logDurationStat(Stats.GET_DEFAULT_HOME, startGetHomeActivitiesAsUser);
2251
2252 ComponentName detected = null;
2253 if (defaultLauncher != null) {
2254 detected = defaultLauncher;
2255 if (DEBUG) {
2256 Slog.v(TAG, "Default launcher from PM: " + detected);
2257 }
2258 } else {
2259 detected = user.getLastKnownLauncher();
2260
2261 if (detected != null) {
2262 if (injectIsActivityEnabledAndExported(detected, userId)) {
2263 if (DEBUG) {
2264 Slog.v(TAG, "Cached launcher: " + detected);
2265 }
2266 } else {
2267 Slog.w(TAG, "Cached launcher " + detected + " no longer exists");
2268 detected = null;
2269 user.clearLauncher();
2270 }
2271 }
2272 }
2273
2274 if (detected == null) {
2275 // If we reach here, that means it's the first check since the user was created,
2276 // and there's already multiple launchers and there's no default set.
2277 // Find the system one with the highest priority.
2278 // (We need to check the priority too because of FallbackHome in Settings.)
2279 // If there's no system launcher yet, then no one can access shortcuts, until
2280 // the user explicitly
2281 final int size = allHomeCandidates.size();
2282
2283 int lastPriority = Integer.MIN_VALUE;
2284 for (int i = 0; i < size; i++) {
2285 final ResolveInfo ri = allHomeCandidates.get(i);
2286 if (!ri.activityInfo.applicationInfo.isSystemApp()) {
2287 continue;
2288 }
2289 if (DEBUG) {
2290 Slog.d(TAG, String.format("hasShortcutPermissionInner: pkg=%s prio=%d",
2291 ri.activityInfo.getComponentName(), ri.priority));
2292 }
2293 if (ri.priority < lastPriority) {
2294 continue;
2295 }
2296 detected = ri.activityInfo.getComponentName();
2297 lastPriority = ri.priority;
2298 }
2299 }
2300 return detected;
2301 }
2302 } finally {
2303 injectRestoreCallingIdentity(token);
2304 logDurationStat(Stats.GET_DEFAULT_LAUNCHER, start);
2305 }
2306 }
2307
Makoto Onukicdc78f72016-03-21 15:47:52 -07002308 // === House keeping ===
2309
Makoto Onukib08790c2016-06-23 14:05:46 -07002310 private void cleanUpPackageForAllLoadedUsers(String packageName, @UserIdInt int packageUserId,
2311 boolean appStillExists) {
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002312 synchronized (mLock) {
2313 forEachLoadedUserLocked(user ->
Makoto Onukib08790c2016-06-23 14:05:46 -07002314 cleanUpPackageLocked(packageName, user.getUserId(), packageUserId,
2315 appStillExists));
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002316 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002317 }
2318
Makoto Onuki2e210c42016-03-30 08:30:36 -07002319 /**
2320 * Remove all the information associated with a package. This will really remove all the
2321 * information, including the restore information (i.e. it'll remove packages even if they're
2322 * shadow).
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002323 *
2324 * This is called when an app is uninstalled, or an app gets "clear data"ed.
Makoto Onuki2e210c42016-03-30 08:30:36 -07002325 */
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002326 @VisibleForTesting
Makoto Onukib08790c2016-06-23 14:05:46 -07002327 void cleanUpPackageLocked(String packageName, int owningUserId, int packageUserId,
2328 boolean appStillExists) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002329 final boolean wasUserLoaded = isUserLoadedLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002330
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002331 final ShortcutUser user = getUserShortcutsLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002332 boolean doNotify = false;
2333
2334 // First, remove the package from the package list (if the package is a publisher).
Makoto Onukid99c6f02016-03-28 11:02:54 -07002335 if (packageUserId == owningUserId) {
Makoto Onukic51b2872016-05-04 15:24:50 -07002336 if (user.removePackage(packageName) != null) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002337 doNotify = true;
2338 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07002339 }
Makoto Onukid99c6f02016-03-28 11:02:54 -07002340
Makoto Onukicdc78f72016-03-21 15:47:52 -07002341 // Also remove from the launcher list (if the package is a launcher).
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002342 user.removeLauncher(packageUserId, packageName);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002343
2344 // Then remove pinned shortcuts from all launchers.
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002345 user.forAllLaunchers(l -> l.cleanUpPackage(packageName, packageUserId));
2346
2347 // Now there may be orphan shortcuts because we removed pinned shortcuts at the previous
Makoto Onukicdc78f72016-03-21 15:47:52 -07002348 // step. Remove them too.
Makoto Onukic51b2872016-05-04 15:24:50 -07002349 user.forAllPackages(p -> p.refreshPinnedFlags());
Makoto Onukicdc78f72016-03-21 15:47:52 -07002350
Makoto Onukid99c6f02016-03-28 11:02:54 -07002351 scheduleSaveUser(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002352
2353 if (doNotify) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002354 notifyListeners(packageName, owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002355 }
2356
Makoto Onukib08790c2016-06-23 14:05:46 -07002357 // If the app still exists (i.e. data cleared), we need to re-publish manifest shortcuts.
2358 if (appStillExists && (packageUserId == owningUserId)) {
2359 // This will do the notification and save when needed, so do it after the above
2360 // notifyListeners.
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002361 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07002362 }
2363
Makoto Onukicdc78f72016-03-21 15:47:52 -07002364 if (!wasUserLoaded) {
2365 // Note this will execute the scheduled save.
Makoto Onukid99c6f02016-03-28 11:02:54 -07002366 unloadUserLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002367 }
2368 }
2369
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002370 /**
2371 * Entry point from {@link LauncherApps}.
2372 */
2373 private class LocalService extends ShortcutServiceInternal {
Makoto Onuki2e210c42016-03-30 08:30:36 -07002374
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002375 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002376 public List<ShortcutInfo> getShortcuts(int launcherUserId,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002377 @NonNull String callingPackage, long changedSince,
Makoto Onukiabe84422016-04-07 09:41:19 -07002378 @Nullable String packageName, @Nullable List<String> shortcutIds,
Makoto Onuki99302b52017-03-29 12:42:26 -07002379 @Nullable ComponentName componentName,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002380 int queryFlags, int userId) {
2381 final ArrayList<ShortcutInfo> ret = new ArrayList<>();
Makoto Onuki9c850012016-07-26 15:50:50 -07002382
Makoto Onuki20c95f82016-05-11 16:51:01 -07002383 final boolean cloneKeyFieldOnly =
2384 ((queryFlags & ShortcutQuery.FLAG_GET_KEY_FIELDS_ONLY) != 0);
2385 final int cloneFlag = cloneKeyFieldOnly ? ShortcutInfo.CLONE_REMOVE_NON_KEY_INFO
2386 : ShortcutInfo.CLONE_REMOVE_FOR_LAUNCHER;
Makoto Onukiabe84422016-04-07 09:41:19 -07002387 if (packageName == null) {
2388 shortcutIds = null; // LauncherAppsService already threw for it though.
2389 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002390
2391 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002392 throwIfUserLockedL(userId);
2393 throwIfUserLockedL(launcherUserId);
2394
Makoto Onuki2e210c42016-03-30 08:30:36 -07002395 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002396 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002397
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002398 if (packageName != null) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002399 getShortcutsInnerLocked(launcherUserId,
Makoto Onukiabe84422016-04-07 09:41:19 -07002400 callingPackage, packageName, shortcutIds, changedSince,
Makoto Onuki99302b52017-03-29 12:42:26 -07002401 componentName, queryFlags, userId, ret, cloneFlag);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002402 } else {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002403 final List<String> shortcutIdsF = shortcutIds;
2404 getUserShortcutsLocked(userId).forAllPackages(p -> {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002405 getShortcutsInnerLocked(launcherUserId,
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002406 callingPackage, p.getPackageName(), shortcutIdsF, changedSince,
Makoto Onuki99302b52017-03-29 12:42:26 -07002407 componentName, queryFlags, userId, ret, cloneFlag);
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002408 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002409 }
2410 }
Makoto Onukibf563b62017-05-04 10:25:30 -07002411 return setReturnedByServer(ret);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002412 }
2413
Makoto Onukid99c6f02016-03-28 11:02:54 -07002414 private void getShortcutsInnerLocked(int launcherUserId, @NonNull String callingPackage,
Makoto Onukiabe84422016-04-07 09:41:19 -07002415 @Nullable String packageName, @Nullable List<String> shortcutIds, long changedSince,
Makoto Onuki99302b52017-03-29 12:42:26 -07002416 @Nullable ComponentName componentName, int queryFlags,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002417 int userId, ArrayList<ShortcutInfo> ret, int cloneFlag) {
Makoto Onukiabe84422016-04-07 09:41:19 -07002418 final ArraySet<String> ids = shortcutIds == null ? null
2419 : new ArraySet<>(shortcutIds);
2420
Makoto Onukic51b2872016-05-04 15:24:50 -07002421 final ShortcutPackage p = getUserShortcutsLocked(userId)
2422 .getPackageShortcutsIfExists(packageName);
2423 if (p == null) {
2424 return; // No need to instantiate ShortcutPackage.
2425 }
2426
2427 p.findAll(ret,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002428 (ShortcutInfo si) -> {
2429 if (si.getLastChangedTimestamp() < changedSince) {
2430 return false;
2431 }
Makoto Onukiabe84422016-04-07 09:41:19 -07002432 if (ids != null && !ids.contains(si.getId())) {
2433 return false;
2434 }
Makoto Onuki85694522016-05-04 12:53:37 -07002435 if (componentName != null) {
Makoto Onuki9fd90192017-01-06 18:31:03 +00002436 if (si.getActivity() != null
2437 && !si.getActivity().equals(componentName)) {
Makoto Onuki85694522016-05-04 12:53:37 -07002438 return false;
2439 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002440 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002441 if (((queryFlags & ShortcutQuery.FLAG_GET_DYNAMIC) != 0)
2442 && si.isDynamic()) {
2443 return true;
2444 }
2445 if (((queryFlags & ShortcutQuery.FLAG_GET_PINNED) != 0)
2446 && si.isPinned()) {
2447 return true;
2448 }
2449 if (((queryFlags & ShortcutQuery.FLAG_GET_MANIFEST) != 0)
2450 && si.isManifestShortcut()) {
2451 return true;
2452 }
2453 return false;
Makoto Onukid99c6f02016-03-28 11:02:54 -07002454 }, cloneFlag, callingPackage, launcherUserId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002455 }
2456
2457 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002458 public boolean isPinnedByCaller(int launcherUserId, @NonNull String callingPackage,
2459 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2460 Preconditions.checkStringNotEmpty(packageName, "packageName");
2461 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
2462
2463 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002464 throwIfUserLockedL(userId);
2465 throwIfUserLockedL(launcherUserId);
2466
Makoto Onuki2e210c42016-03-30 08:30:36 -07002467 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002468 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002469
Makoto Onukid99c6f02016-03-28 11:02:54 -07002470 final ShortcutInfo si = getShortcutInfoLocked(
2471 launcherUserId, callingPackage, packageName, shortcutId, userId);
2472 return si != null && si.isPinned();
2473 }
2474 }
2475
Makoto Onuki2e210c42016-03-30 08:30:36 -07002476 private ShortcutInfo getShortcutInfoLocked(
Makoto Onukid99c6f02016-03-28 11:02:54 -07002477 int launcherUserId, @NonNull String callingPackage,
2478 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2479 Preconditions.checkStringNotEmpty(packageName, "packageName");
2480 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
2481
Makoto Onuki02f338e2016-07-29 09:40:40 -07002482 throwIfUserLockedL(userId);
2483 throwIfUserLockedL(launcherUserId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002484
Makoto Onukic51b2872016-05-04 15:24:50 -07002485 final ShortcutPackage p = getUserShortcutsLocked(userId)
2486 .getPackageShortcutsIfExists(packageName);
2487 if (p == null) {
2488 return null;
2489 }
2490
Makoto Onukid99c6f02016-03-28 11:02:54 -07002491 final ArrayList<ShortcutInfo> list = new ArrayList<>(1);
Makoto Onukic51b2872016-05-04 15:24:50 -07002492 p.findAll(list,
Makoto Onukid99c6f02016-03-28 11:02:54 -07002493 (ShortcutInfo si) -> shortcutId.equals(si.getId()),
2494 /* clone flags=*/ 0, callingPackage, launcherUserId);
2495 return list.size() == 0 ? null : list.get(0);
2496 }
2497
2498 @Override
2499 public void pinShortcuts(int launcherUserId,
2500 @NonNull String callingPackage, @NonNull String packageName,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002501 @NonNull List<String> shortcutIds, int userId) {
2502 // Calling permission must be checked by LauncherAppsImpl.
2503 Preconditions.checkStringNotEmpty(packageName, "packageName");
2504 Preconditions.checkNotNull(shortcutIds, "shortcutIds");
2505
2506 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002507 throwIfUserLockedL(userId);
2508 throwIfUserLockedL(launcherUserId);
2509
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002510 final ShortcutLauncher launcher =
Makoto Onuki2e210c42016-03-30 08:30:36 -07002511 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId);
Makoto Onukic51b2872016-05-04 15:24:50 -07002512 launcher.attemptToRestoreIfNeededAndSave();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002513
Makoto Onukic51b2872016-05-04 15:24:50 -07002514 launcher.pinShortcuts(userId, packageName, shortcutIds);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002515 }
Makoto Onuki39686e82016-04-13 18:03:00 -07002516 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07002517
2518 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002519 }
2520
2521 @Override
Makoto Onuki440a1ea2016-07-20 14:21:18 -07002522 public Intent[] createShortcutIntents(int launcherUserId,
Makoto Onukid99c6f02016-03-28 11:02:54 -07002523 @NonNull String callingPackage,
Makoto Onuki43204b82016-03-08 16:16:44 -08002524 @NonNull String packageName, @NonNull String shortcutId, int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002525 // Calling permission must be checked by LauncherAppsImpl.
Makoto Onuki43204b82016-03-08 16:16:44 -08002526 Preconditions.checkStringNotEmpty(packageName, "packageName can't be empty");
2527 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId can't be empty");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002528
2529 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002530 throwIfUserLockedL(userId);
2531 throwIfUserLockedL(launcherUserId);
2532
Makoto Onuki2e210c42016-03-30 08:30:36 -07002533 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002534 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002535
Makoto Onukid99c6f02016-03-28 11:02:54 -07002536 // Make sure the shortcut is actually visible to the launcher.
2537 final ShortcutInfo si = getShortcutInfoLocked(
2538 launcherUserId, callingPackage, packageName, shortcutId, userId);
2539 // "si == null" should suffice here, but check the flags too just to make sure.
Makoto Onuki22fcc682016-05-17 14:52:19 -07002540 if (si == null || !si.isEnabled() || !si.isAlive()) {
Makoto Onuki83f6d2d2016-07-11 14:30:19 -07002541 Log.e(TAG, "Shortcut " + shortcutId + " does not exist or disabled");
Makoto Onukid99c6f02016-03-28 11:02:54 -07002542 return null;
2543 }
Makoto Onuki440a1ea2016-07-20 14:21:18 -07002544 return si.getIntents();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002545 }
2546 }
2547
2548 @Override
2549 public void addListener(@NonNull ShortcutChangeListener listener) {
2550 synchronized (mLock) {
2551 mListeners.add(Preconditions.checkNotNull(listener));
2552 }
2553 }
Makoto Onuki55046222016-03-08 10:49:47 -08002554
2555 @Override
Makoto Onukiabe84422016-04-07 09:41:19 -07002556 public int getShortcutIconResId(int launcherUserId, @NonNull String callingPackage,
2557 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2558 Preconditions.checkNotNull(callingPackage, "callingPackage");
2559 Preconditions.checkNotNull(packageName, "packageName");
2560 Preconditions.checkNotNull(shortcutId, "shortcutId");
Makoto Onuki55046222016-03-08 10:49:47 -08002561
2562 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002563 throwIfUserLockedL(userId);
2564 throwIfUserLockedL(launcherUserId);
2565
Makoto Onuki2e210c42016-03-30 08:30:36 -07002566 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002567 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002568
Makoto Onukic51b2872016-05-04 15:24:50 -07002569 final ShortcutPackage p = getUserShortcutsLocked(userId)
2570 .getPackageShortcutsIfExists(packageName);
2571 if (p == null) {
2572 return 0;
2573 }
2574
2575 final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId);
Makoto Onuki55046222016-03-08 10:49:47 -08002576 return (shortcutInfo != null && shortcutInfo.hasIconResource())
2577 ? shortcutInfo.getIconResourceId() : 0;
2578 }
2579 }
2580
2581 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002582 public ParcelFileDescriptor getShortcutIconFd(int launcherUserId,
Makoto Onukiabe84422016-04-07 09:41:19 -07002583 @NonNull String callingPackage, @NonNull String packageName,
2584 @NonNull String shortcutId, int userId) {
2585 Preconditions.checkNotNull(callingPackage, "callingPackage");
2586 Preconditions.checkNotNull(packageName, "packageName");
2587 Preconditions.checkNotNull(shortcutId, "shortcutId");
Makoto Onuki55046222016-03-08 10:49:47 -08002588
2589 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002590 throwIfUserLockedL(userId);
2591 throwIfUserLockedL(launcherUserId);
2592
Makoto Onuki2e210c42016-03-30 08:30:36 -07002593 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002594 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002595
Makoto Onukic51b2872016-05-04 15:24:50 -07002596 final ShortcutPackage p = getUserShortcutsLocked(userId)
2597 .getPackageShortcutsIfExists(packageName);
2598 if (p == null) {
2599 return null;
2600 }
2601
2602 final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId);
Makoto Onuki55046222016-03-08 10:49:47 -08002603 if (shortcutInfo == null || !shortcutInfo.hasIconFile()) {
2604 return null;
2605 }
Makoto Onuki475c3652017-05-08 14:29:03 -07002606 final String path = mShortcutBitmapSaver.getBitmapPathMayWaitLocked(shortcutInfo);
2607 if (path == null) {
2608 Slog.w(TAG, "null bitmap detected in getShortcutIconFd()");
2609 return null;
2610 }
Makoto Onuki55046222016-03-08 10:49:47 -08002611 try {
2612 return ParcelFileDescriptor.open(
Makoto Onuki475c3652017-05-08 14:29:03 -07002613 new File(path),
Makoto Onuki55046222016-03-08 10:49:47 -08002614 ParcelFileDescriptor.MODE_READ_ONLY);
2615 } catch (FileNotFoundException e) {
Makoto Onuki475c3652017-05-08 14:29:03 -07002616 Slog.e(TAG, "Icon file not found: " + path);
Makoto Onuki55046222016-03-08 10:49:47 -08002617 return null;
2618 }
2619 }
2620 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002621
2622 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002623 public boolean hasShortcutHostPermission(int launcherUserId,
2624 @NonNull String callingPackage) {
2625 return ShortcutService.this.hasShortcutHostPermission(callingPackage, launcherUserId);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002626 }
Sunny Goyal87a563e2017-01-01 19:42:45 -08002627
2628 @Override
2629 public boolean requestPinAppWidget(@NonNull String callingPackage,
Sunny Goyal4ad6b572017-02-28 11:11:51 -08002630 @NonNull AppWidgetProviderInfo appWidget, @Nullable Bundle extras,
2631 @Nullable IntentSender resultIntent, int userId) {
Sunny Goyal87a563e2017-01-01 19:42:45 -08002632 Preconditions.checkNotNull(appWidget);
Sunny Goyal4ad6b572017-02-28 11:11:51 -08002633 return requestPinItem(callingPackage, userId, null, appWidget, extras, resultIntent);
Sunny Goyal87a563e2017-01-01 19:42:45 -08002634 }
Sunny Goyal7f7372a2017-01-24 11:53:54 -08002635
2636 @Override
2637 public boolean isRequestPinItemSupported(int callingUserId, int requestType) {
2638 return ShortcutService.this.isRequestPinItemSupported(callingUserId, requestType);
2639 }
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002640 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002641
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002642 final BroadcastReceiver mReceiver = new BroadcastReceiver() {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002643 @Override
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002644 public void onReceive(Context context, Intent intent) {
2645 if (!mBootCompleted.get()) {
2646 return; // Boot not completed, ignore the broadcast.
2647 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07002648 try {
2649 if (Intent.ACTION_LOCALE_CHANGED.equals(intent.getAction())) {
2650 handleLocaleChanged();
2651 }
2652 } catch (Exception e) {
2653 wtf("Exception in mReceiver.onReceive", e);
Makoto Onukic51b2872016-05-04 15:24:50 -07002654 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002655 }
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002656 };
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002657
Makoto Onuki157b1622016-06-02 16:13:10 -07002658 void handleLocaleChanged() {
2659 if (DEBUG) {
2660 Slog.d(TAG, "handleLocaleChanged");
2661 }
2662 scheduleSaveBaseState();
2663
Makoto Onuki02f338e2016-07-29 09:40:40 -07002664 synchronized (mLock) {
2665 final long token = injectClearCallingIdentity();
2666 try {
2667 forEachLoadedUserLocked(user -> user.detectLocaleChange());
2668 } finally {
2669 injectRestoreCallingIdentity(token);
2670 }
Makoto Onuki157b1622016-06-02 16:13:10 -07002671 }
2672 }
2673
Makoto Onukif34c3082016-07-13 10:25:25 -07002674 /**
2675 * Package event callbacks.
2676 */
2677 @VisibleForTesting
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002678 final BroadcastReceiver mPackageMonitor = new BroadcastReceiver() {
Makoto Onukif34c3082016-07-13 10:25:25 -07002679 @Override
2680 public void onReceive(Context context, Intent intent) {
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002681 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
2682 if (userId == UserHandle.USER_NULL) {
2683 Slog.w(TAG, "Intent broadcast does not contain user handle: " + intent);
2684 return;
2685 }
2686
2687 final String action = intent.getAction();
2688
2689 // This is normally called on Handler, so clearCallingIdentity() isn't needed,
2690 // but we still check it in unit tests.
Makoto Onukif34c3082016-07-13 10:25:25 -07002691 final long token = injectClearCallingIdentity();
2692 try {
Makoto Onuki10305202016-07-14 18:14:08 -07002693 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002694 if (!isUserUnlockedL(userId)) {
2695 if (DEBUG) {
2696 Slog.d(TAG, "Ignoring package broadcast " + action
2697 + " for locked/stopped user " + userId);
2698 }
2699 return;
2700 }
2701
2702 // Whenever we get one of those package broadcasts, or get
2703 // ACTION_PREFERRED_ACTIVITY_CHANGED, we purge the default launcher cache.
Makoto Onuki10305202016-07-14 18:14:08 -07002704 final ShortcutUser user = getUserShortcutsLocked(userId);
2705 user.clearLauncher();
2706 }
2707 if (Intent.ACTION_PREFERRED_ACTIVITY_CHANGED.equals(action)) {
2708 // Nothing farther to do.
2709 return;
2710 }
2711
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002712 final Uri intentUri = intent.getData();
2713 final String packageName = (intentUri != null) ? intentUri.getSchemeSpecificPart()
2714 : null;
2715 if (packageName == null) {
2716 Slog.w(TAG, "Intent broadcast does not contain package name: " + intent);
2717 return;
2718 }
2719
2720 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
2721
2722 switch (action) {
2723 case Intent.ACTION_PACKAGE_ADDED:
2724 if (replacing) {
2725 handlePackageUpdateFinished(packageName, userId);
2726 } else {
2727 handlePackageAdded(packageName, userId);
2728 }
2729 break;
2730 case Intent.ACTION_PACKAGE_REMOVED:
2731 if (!replacing) {
2732 handlePackageRemoved(packageName, userId);
2733 }
2734 break;
2735 case Intent.ACTION_PACKAGE_CHANGED:
2736 handlePackageChanged(packageName, userId);
2737
2738 break;
2739 case Intent.ACTION_PACKAGE_DATA_CLEARED:
2740 handlePackageDataCleared(packageName, userId);
2741 break;
2742 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07002743 } catch (Exception e) {
2744 wtf("Exception in mPackageMonitor.onReceive", e);
Makoto Onukif34c3082016-07-13 10:25:25 -07002745 } finally {
2746 injectRestoreCallingIdentity(token);
Makoto Onukia2241832016-07-06 13:28:37 -07002747 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07002748 }
Makoto Onukif34c3082016-07-13 10:25:25 -07002749 };
Makoto Onukicdc78f72016-03-21 15:47:52 -07002750
Makoto Onuki0acbb142016-03-22 17:02:57 -07002751 /**
Makoto Onuki39686e82016-04-13 18:03:00 -07002752 * Called when a user is unlocked.
2753 * - Check all known packages still exist, and otherwise perform cleanup.
2754 * - If a package still exists, check the version code. If it's been updated, may need to
Makoto Onukib08790c2016-06-23 14:05:46 -07002755 * update timestamps of its shortcuts.
Makoto Onuki0acbb142016-03-22 17:02:57 -07002756 */
Makoto Onukid99c6f02016-03-28 11:02:54 -07002757 @VisibleForTesting
Makoto Onuki39686e82016-04-13 18:03:00 -07002758 void checkPackageChanges(@UserIdInt int ownerUserId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07002759 if (DEBUG) {
Makoto Onuki39686e82016-04-13 18:03:00 -07002760 Slog.d(TAG, "checkPackageChanges() ownerUserId=" + ownerUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002761 }
Makoto Onukib08790c2016-06-23 14:05:46 -07002762 if (injectIsSafeModeEnabled()) {
2763 Slog.i(TAG, "Safe mode, skipping checkPackageChanges()");
2764 return;
2765 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07002766
Makoto Onuki22fcc682016-05-17 14:52:19 -07002767 final long start = injectElapsedRealtime();
2768 try {
2769 final ArrayList<PackageWithUser> gonePackages = new ArrayList<>();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002770
Makoto Onuki22fcc682016-05-17 14:52:19 -07002771 synchronized (mLock) {
2772 final ShortcutUser user = getUserShortcutsLocked(ownerUserId);
2773
2774 // Find packages that have been uninstalled.
2775 user.forAllPackageItems(spi -> {
2776 if (spi.getPackageInfo().isShadow()) {
2777 return; // Don't delete shadow information.
2778 }
2779 if (!isPackageInstalled(spi.getPackageName(), spi.getPackageUserId())) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002780 if (DEBUG) {
2781 Slog.d(TAG, "Uninstalled: " + spi.getPackageName()
2782 + " user " + spi.getPackageUserId());
2783 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002784 gonePackages.add(PackageWithUser.of(spi));
2785 }
2786 });
2787 if (gonePackages.size() > 0) {
2788 for (int i = gonePackages.size() - 1; i >= 0; i--) {
2789 final PackageWithUser pu = gonePackages.get(i);
Makoto Onukib08790c2016-06-23 14:05:46 -07002790 cleanUpPackageLocked(pu.packageName, ownerUserId, pu.userId,
2791 /* appStillExists = */ false);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002792 }
Makoto Onukid99c6f02016-03-28 11:02:54 -07002793 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002794
Makoto Onuki248a0ef2016-11-03 15:59:01 -07002795 rescanUpdatedPackagesLocked(ownerUserId, user.getLastAppScanTime());
Makoto Onuki0acbb142016-03-22 17:02:57 -07002796 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002797 } finally {
2798 logDurationStat(Stats.CHECK_PACKAGE_CHANGES, start);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002799 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002800 verifyStates();
Makoto Onukicdc78f72016-03-21 15:47:52 -07002801 }
2802
Makoto Onuki248a0ef2016-11-03 15:59:01 -07002803 private void rescanUpdatedPackagesLocked(@UserIdInt int userId, long lastScanTime) {
Makoto Onuki377b7972016-08-09 14:43:55 -07002804 final ShortcutUser user = getUserShortcutsLocked(userId);
2805
Makoto Onuki33663282016-08-22 16:19:04 -07002806 // Note after each OTA, we'll need to rescan all system apps, as their lastUpdateTime
2807 // is not reliable.
Makoto Onuki377b7972016-08-09 14:43:55 -07002808 final long now = injectCurrentTimeMillis();
Makoto Onuki33663282016-08-22 16:19:04 -07002809 final boolean afterOta =
2810 !injectBuildFingerprint().equals(user.getLastAppScanOsFingerprint());
Makoto Onuki377b7972016-08-09 14:43:55 -07002811
2812 // Then for each installed app, publish manifest shortcuts when needed.
Makoto Onuki33663282016-08-22 16:19:04 -07002813 forUpdatedPackages(userId, lastScanTime, afterOta, ai -> {
Makoto Onuki377b7972016-08-09 14:43:55 -07002814 user.attemptToRestoreIfNeededAndSave(this, ai.packageName, userId);
Makoto Onuki248a0ef2016-11-03 15:59:01 -07002815
2816 user.rescanPackageIfNeeded(ai.packageName, /* forceRescan= */ true);
Makoto Onuki377b7972016-08-09 14:43:55 -07002817 });
2818
2819 // Write the time just before the scan, because there may be apps that have just
2820 // been updated, and we want to catch them in the next time.
2821 user.setLastAppScanTime(now);
Makoto Onuki33663282016-08-22 16:19:04 -07002822 user.setLastAppScanOsFingerprint(injectBuildFingerprint());
Makoto Onuki377b7972016-08-09 14:43:55 -07002823 scheduleSaveUser(userId);
2824 }
2825
Makoto Onuki0acbb142016-03-22 17:02:57 -07002826 private void handlePackageAdded(String packageName, @UserIdInt int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07002827 if (DEBUG) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07002828 Slog.d(TAG, String.format("handlePackageAdded: %s user=%d", packageName, userId));
2829 }
2830 synchronized (mLock) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002831 final ShortcutUser user = getUserShortcutsLocked(userId);
2832 user.attemptToRestoreIfNeededAndSave(this, packageName, userId);
Makoto Onuki64183d52016-08-08 14:11:34 -07002833 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002834 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002835 verifyStates();
Makoto Onuki0acbb142016-03-22 17:02:57 -07002836 }
2837
2838 private void handlePackageUpdateFinished(String packageName, @UserIdInt int userId) {
Makoto Onuki905e8852016-03-28 10:40:58 -07002839 if (DEBUG) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002840 Slog.d(TAG, String.format("handlePackageUpdateFinished: %s user=%d",
2841 packageName, userId));
Makoto Onuki0acbb142016-03-22 17:02:57 -07002842 }
2843 synchronized (mLock) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002844 final ShortcutUser user = getUserShortcutsLocked(userId);
2845 user.attemptToRestoreIfNeededAndSave(this, packageName, userId);
Makoto Onuki39686e82016-04-13 18:03:00 -07002846
Makoto Onuki22fcc682016-05-17 14:52:19 -07002847 if (isPackageInstalled(packageName, userId)) {
Makoto Onuki64183d52016-08-08 14:11:34 -07002848 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onuki39686e82016-04-13 18:03:00 -07002849 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07002850 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002851 verifyStates();
Makoto Onuki0acbb142016-03-22 17:02:57 -07002852 }
2853
Makoto Onuki2e210c42016-03-30 08:30:36 -07002854 private void handlePackageRemoved(String packageName, @UserIdInt int packageUserId) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07002855 if (DEBUG) {
Makoto Onuki2e210c42016-03-30 08:30:36 -07002856 Slog.d(TAG, String.format("handlePackageRemoved: %s user=%d", packageName,
2857 packageUserId));
Makoto Onukicdc78f72016-03-21 15:47:52 -07002858 }
Makoto Onukib08790c2016-06-23 14:05:46 -07002859 cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ false);
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002860
2861 verifyStates();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002862 }
2863
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002864 private void handlePackageDataCleared(String packageName, int packageUserId) {
2865 if (DEBUG) {
2866 Slog.d(TAG, String.format("handlePackageDataCleared: %s user=%d", packageName,
2867 packageUserId));
Makoto Onukicdc78f72016-03-21 15:47:52 -07002868 }
Makoto Onukib08790c2016-06-23 14:05:46 -07002869 cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ true);
2870
2871 verifyStates();
2872 }
2873
2874 private void handlePackageChanged(String packageName, int packageUserId) {
Makoto Onuki82fb2eb2017-03-31 16:58:26 -07002875 if (!isPackageInstalled(packageName, packageUserId)) {
2876 // Probably disabled, which is the same thing as uninstalled.
2877 handlePackageRemoved(packageName, packageUserId);
2878 return;
2879 }
Makoto Onukib08790c2016-06-23 14:05:46 -07002880 if (DEBUG) {
2881 Slog.d(TAG, String.format("handlePackageChanged: %s user=%d", packageName,
2882 packageUserId));
2883 }
2884
2885 // Activities may be disabled or enabled. Just rescan the package.
2886 synchronized (mLock) {
2887 final ShortcutUser user = getUserShortcutsLocked(packageUserId);
2888
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002889 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07002890 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002891
2892 verifyStates();
Makoto Onukicdc78f72016-03-21 15:47:52 -07002893 }
2894
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002895 // === PackageManager interaction ===
Makoto Onuki0acbb142016-03-22 17:02:57 -07002896
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002897 /**
2898 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
2899 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002900 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002901 final PackageInfo getPackageInfoWithSignatures(String packageName, @UserIdInt int userId) {
2902 return getPackageInfo(packageName, userId, true);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002903 }
2904
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002905 /**
2906 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
2907 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002908 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002909 final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId) {
2910 return getPackageInfo(packageName, userId, false);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002911 }
2912
Makoto Onuki905e8852016-03-28 10:40:58 -07002913 int injectGetPackageUid(@NonNull String packageName, @UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002914 final long token = injectClearCallingIdentity();
Makoto Onuki905e8852016-03-28 10:40:58 -07002915 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002916 return mIPackageManager.getPackageUid(packageName, PACKAGE_MATCH_FLAGS, userId);
Makoto Onuki905e8852016-03-28 10:40:58 -07002917 } catch (RemoteException e) {
2918 // Shouldn't happen.
2919 Slog.wtf(TAG, "RemoteException", e);
2920 return -1;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002921 } finally {
2922 injectRestoreCallingIdentity(token);
Makoto Onuki905e8852016-03-28 10:40:58 -07002923 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07002924 }
2925
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002926 /**
2927 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
2928 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002929 @Nullable
Makoto Onuki0acbb142016-03-22 17:02:57 -07002930 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002931 final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId,
2932 boolean getSignatures) {
2933 return isInstalledOrNull(injectPackageInfoWithUninstalled(
2934 packageName, userId, getSignatures));
2935 }
2936
2937 /**
2938 * Do not use directly; this returns uninstalled packages too.
2939 */
2940 @Nullable
2941 @VisibleForTesting
2942 PackageInfo injectPackageInfoWithUninstalled(String packageName, @UserIdInt int userId,
Makoto Onuki0acbb142016-03-22 17:02:57 -07002943 boolean getSignatures) {
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07002944 final long start = injectElapsedRealtime();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002945 final long token = injectClearCallingIdentity();
Makoto Onuki0acbb142016-03-22 17:02:57 -07002946 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002947 return mIPackageManager.getPackageInfo(
2948 packageName, PACKAGE_MATCH_FLAGS
2949 | (getSignatures ? PackageManager.GET_SIGNATURES : 0), userId);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002950 } catch (RemoteException e) {
2951 // Shouldn't happen.
2952 Slog.wtf(TAG, "RemoteException", e);
2953 return null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002954 } finally {
2955 injectRestoreCallingIdentity(token);
Makoto Onuki2e210c42016-03-30 08:30:36 -07002956
2957 logDurationStat(
2958 (getSignatures ? Stats.GET_PACKAGE_INFO_WITH_SIG : Stats.GET_PACKAGE_INFO),
2959 start);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002960 }
2961 }
2962
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002963 /**
2964 * Returns {@link ApplicationInfo} unless it's uninstalled or disabled.
2965 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002966 @Nullable
Makoto Onuki905e8852016-03-28 10:40:58 -07002967 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002968 final ApplicationInfo getApplicationInfo(String packageName, @UserIdInt int userId) {
2969 return isInstalledOrNull(injectApplicationInfoWithUninstalled(packageName, userId));
2970 }
2971
2972 /**
2973 * Do not use directly; this returns uninstalled packages too.
2974 */
2975 @Nullable
2976 @VisibleForTesting
2977 ApplicationInfo injectApplicationInfoWithUninstalled(
2978 String packageName, @UserIdInt int userId) {
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07002979 final long start = injectElapsedRealtime();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002980 final long token = injectClearCallingIdentity();
Makoto Onuki905e8852016-03-28 10:40:58 -07002981 try {
2982 return mIPackageManager.getApplicationInfo(packageName, PACKAGE_MATCH_FLAGS, userId);
2983 } catch (RemoteException e) {
2984 // Shouldn't happen.
2985 Slog.wtf(TAG, "RemoteException", e);
2986 return null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002987 } finally {
2988 injectRestoreCallingIdentity(token);
Makoto Onuki2e210c42016-03-30 08:30:36 -07002989
2990 logDurationStat(Stats.GET_APPLICATION_INFO, start);
Makoto Onuki905e8852016-03-28 10:40:58 -07002991 }
2992 }
2993
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002994 /**
2995 * Returns {@link ActivityInfo} with its metadata unless it's uninstalled or disabled.
2996 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002997 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002998 final ActivityInfo getActivityInfoWithMetadata(ComponentName activity, @UserIdInt int userId) {
2999 return isInstalledOrNull(injectGetActivityInfoWithMetadataWithUninstalled(
3000 activity, userId));
3001 }
3002
3003 /**
3004 * Do not use directly; this returns uninstalled packages too.
3005 */
3006 @Nullable
3007 @VisibleForTesting
3008 ActivityInfo injectGetActivityInfoWithMetadataWithUninstalled(
3009 ComponentName activity, @UserIdInt int userId) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07003010 final long start = injectElapsedRealtime();
3011 final long token = injectClearCallingIdentity();
3012 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07003013 return mIPackageManager.getActivityInfo(activity,
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003014 (PACKAGE_MATCH_FLAGS | PackageManager.GET_META_DATA), userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003015 } catch (RemoteException e) {
3016 // Shouldn't happen.
3017 Slog.wtf(TAG, "RemoteException", e);
3018 return null;
3019 } finally {
3020 injectRestoreCallingIdentity(token);
3021
Makoto Onukib08790c2016-06-23 14:05:46 -07003022 logDurationStat(Stats.GET_ACTIVITY_WITH_METADATA, start);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003023 }
3024 }
3025
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003026 /**
3027 * Return all installed and enabled packages.
3028 */
3029 @NonNull
Makoto Onuki22fcc682016-05-17 14:52:19 -07003030 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003031 final List<PackageInfo> getInstalledPackages(@UserIdInt int userId) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07003032 final long start = injectElapsedRealtime();
3033 final long token = injectClearCallingIdentity();
3034 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003035 final List<PackageInfo> all = injectGetPackagesWithUninstalled(userId);
3036
3037 all.removeIf(PACKAGE_NOT_INSTALLED);
3038
3039 return all;
Makoto Onuki22fcc682016-05-17 14:52:19 -07003040 } catch (RemoteException e) {
3041 // Shouldn't happen.
3042 Slog.wtf(TAG, "RemoteException", e);
3043 return null;
3044 } finally {
3045 injectRestoreCallingIdentity(token);
3046
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003047 logDurationStat(Stats.GET_INSTALLED_PACKAGES, start);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003048 }
3049 }
3050
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003051 /**
3052 * Do not use directly; this returns uninstalled packages too.
3053 */
3054 @NonNull
3055 @VisibleForTesting
3056 List<PackageInfo> injectGetPackagesWithUninstalled(@UserIdInt int userId)
3057 throws RemoteException {
3058 final ParceledListSlice<PackageInfo> parceledList =
3059 mIPackageManager.getInstalledPackages(PACKAGE_MATCH_FLAGS, userId);
3060 if (parceledList == null) {
3061 return Collections.emptyList();
3062 }
3063 return parceledList.getList();
3064 }
3065
Makoto Onuki33663282016-08-22 16:19:04 -07003066 private void forUpdatedPackages(@UserIdInt int userId, long lastScanTime, boolean afterOta,
Makoto Onuki22fcc682016-05-17 14:52:19 -07003067 Consumer<ApplicationInfo> callback) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003068 if (DEBUG) {
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003069 Slog.d(TAG, "forUpdatedPackages for user " + userId + ", lastScanTime=" + lastScanTime
3070 + " afterOta=" + afterOta);
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003071 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003072 final List<PackageInfo> list = getInstalledPackages(userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003073 for (int i = list.size() - 1; i >= 0; i--) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003074 final PackageInfo pi = list.get(i);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003075
Makoto Onuki64183d52016-08-08 14:11:34 -07003076 // If the package has been updated since the last scan time, then scan it.
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003077 // Also if it's right after an OTA, always re-scan all apps anyway, since the
3078 // shortcut parser might have changed.
3079 if (afterOta || (pi.lastUpdateTime >= lastScanTime)) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003080 if (DEBUG) {
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003081 Slog.d(TAG, "Found updated package " + pi.packageName
3082 + " updateTime=" + pi.lastUpdateTime);
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003083 }
3084 callback.accept(pi.applicationInfo);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003085 }
3086 }
3087 }
3088
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003089 private boolean isApplicationFlagSet(@NonNull String packageName, int userId, int flags) {
3090 final ApplicationInfo ai = injectApplicationInfoWithUninstalled(packageName, userId);
Makoto Onuki905e8852016-03-28 10:40:58 -07003091 return (ai != null) && ((ai.flags & flags) == flags);
3092 }
3093
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003094 private static boolean isInstalled(@Nullable ApplicationInfo ai) {
Makoto Onuki82fb2eb2017-03-31 16:58:26 -07003095 return (ai != null) && ai.enabled && (ai.flags & ApplicationInfo.FLAG_INSTALLED) != 0;
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003096 }
3097
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08003098 private static boolean isEphemeralApp(@Nullable ApplicationInfo ai) {
Svetoslav Ganov096d3042017-01-30 16:34:13 -08003099 return (ai != null) && ai.isInstantApp();
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08003100 }
3101
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003102 private static boolean isInstalled(@Nullable PackageInfo pi) {
3103 return (pi != null) && isInstalled(pi.applicationInfo);
3104 }
3105
3106 private static boolean isInstalled(@Nullable ActivityInfo ai) {
3107 return (ai != null) && isInstalled(ai.applicationInfo);
3108 }
3109
3110 private static ApplicationInfo isInstalledOrNull(ApplicationInfo ai) {
3111 return isInstalled(ai) ? ai : null;
3112 }
3113
3114 private static PackageInfo isInstalledOrNull(PackageInfo pi) {
3115 return isInstalled(pi) ? pi : null;
3116 }
3117
3118 private static ActivityInfo isInstalledOrNull(ActivityInfo ai) {
3119 return isInstalled(ai) ? ai : null;
3120 }
3121
Makoto Onuki2e210c42016-03-30 08:30:36 -07003122 boolean isPackageInstalled(String packageName, int userId) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003123 return getApplicationInfo(packageName, userId) != null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003124 }
3125
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08003126 boolean isEphemeralApp(String packageName, int userId) {
3127 return isEphemeralApp(getApplicationInfo(packageName, userId));
3128 }
3129
Makoto Onuki22fcc682016-05-17 14:52:19 -07003130 @Nullable
3131 XmlResourceParser injectXmlMetaData(ActivityInfo activityInfo, String key) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07003132 return activityInfo.loadXmlMetaData(mContext.getPackageManager(), key);
Makoto Onuki39686e82016-04-13 18:03:00 -07003133 }
3134
Makoto Onuki157b1622016-06-02 16:13:10 -07003135 @Nullable
3136 Resources injectGetResourcesForApplicationAsUser(String packageName, int userId) {
3137 final long start = injectElapsedRealtime();
3138 final long token = injectClearCallingIdentity();
3139 try {
3140 return mContext.getPackageManager().getResourcesForApplicationAsUser(
3141 packageName, userId);
3142 } catch (NameNotFoundException e) {
3143 Slog.e(TAG, "Resources for package " + packageName + " not found");
3144 return null;
3145 } finally {
3146 injectRestoreCallingIdentity(token);
3147
3148 logDurationStat(Stats.GET_APPLICATION_RESOURCES, start);
3149 }
3150 }
3151
Makoto Onukib08790c2016-06-23 14:05:46 -07003152 private Intent getMainActivityIntent() {
3153 final Intent intent = new Intent(Intent.ACTION_MAIN);
3154 intent.addCategory(LAUNCHER_INTENT_CATEGORY);
3155 return intent;
3156 }
3157
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003158 /**
3159 * Same as queryIntentActivitiesAsUser, except it makes sure the package is installed,
3160 * and only returns exported activities.
3161 */
3162 @NonNull
3163 @VisibleForTesting
3164 List<ResolveInfo> queryActivities(@NonNull Intent baseIntent,
3165 @NonNull String packageName, @Nullable ComponentName activity, int userId) {
3166
3167 baseIntent.setPackage(Preconditions.checkNotNull(packageName));
3168 if (activity != null) {
3169 baseIntent.setComponent(activity);
3170 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08003171 return queryActivities(baseIntent, userId, /* exportedOnly =*/ true);
3172 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003173
Makoto Onuki2d895c32016-12-02 15:48:40 -08003174 @NonNull
3175 List<ResolveInfo> queryActivities(@NonNull Intent intent, int userId,
3176 boolean exportedOnly) {
3177 final List<ResolveInfo> resolved;
3178 final long token = injectClearCallingIdentity();
3179 try {
3180 resolved =
3181 mContext.getPackageManager().queryIntentActivitiesAsUser(
3182 intent, PACKAGE_MATCH_FLAGS, userId);
3183 } finally {
3184 injectRestoreCallingIdentity(token);
3185 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003186 if (resolved == null || resolved.size() == 0) {
3187 return EMPTY_RESOLVE_INFO;
3188 }
3189 // Make sure the package is installed.
3190 if (!isInstalled(resolved.get(0).activityInfo)) {
3191 return EMPTY_RESOLVE_INFO;
3192 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08003193 if (exportedOnly) {
3194 resolved.removeIf(ACTIVITY_NOT_EXPORTED);
3195 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003196 return resolved;
3197 }
3198
3199 /**
3200 * Return the main activity that is enabled and exported. If multiple activities are found,
3201 * return the first one.
3202 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003203 @Nullable
3204 ComponentName injectGetDefaultMainActivity(@NonNull String packageName, int userId) {
3205 final long start = injectElapsedRealtime();
Makoto Onukib08790c2016-06-23 14:05:46 -07003206 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07003207 final List<ResolveInfo> resolved =
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003208 queryActivities(getMainActivityIntent(), packageName, null, userId);
3209 return resolved.size() == 0 ? null : resolved.get(0).activityInfo.getComponentName();
Makoto Onukib08790c2016-06-23 14:05:46 -07003210 } finally {
Makoto Onukib08790c2016-06-23 14:05:46 -07003211 logDurationStat(Stats.GET_LAUNCHER_ACTIVITY, start);
3212 }
3213 }
3214
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003215 /**
3216 * Return whether an activity is enabled, exported and main.
3217 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003218 boolean injectIsMainActivity(@NonNull ComponentName activity, int userId) {
3219 final long start = injectElapsedRealtime();
Makoto Onukib08790c2016-06-23 14:05:46 -07003220 try {
Makoto Onuki34145532017-03-14 17:58:36 -07003221 if (activity == null) {
3222 wtf("null activity detected");
3223 return false;
3224 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08003225 if (DUMMY_MAIN_ACTIVITY.equals(activity.getClassName())) {
3226 return true;
3227 }
3228 final List<ResolveInfo> resolved = queryActivities(
3229 getMainActivityIntent(), activity.getPackageName(), activity, userId);
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003230 return resolved.size() > 0;
Makoto Onukib08790c2016-06-23 14:05:46 -07003231 } finally {
Makoto Onukib08790c2016-06-23 14:05:46 -07003232 logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start);
3233 }
3234 }
3235
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003236 /**
Makoto Onuki2d895c32016-12-02 15:48:40 -08003237 * Create a dummy "main activity" component name which is used to create a dynamic shortcut
3238 * with no main activity temporarily.
3239 */
3240 @NonNull
3241 ComponentName getDummyMainActivity(@NonNull String packageName) {
3242 return new ComponentName(packageName, DUMMY_MAIN_ACTIVITY);
3243 }
3244
Makoto Onuki255461f2017-01-10 11:47:25 -08003245 boolean isDummyMainActivity(@Nullable ComponentName name) {
3246 return name != null && DUMMY_MAIN_ACTIVITY.equals(name.getClassName());
3247 }
3248
Makoto Onuki2d895c32016-12-02 15:48:40 -08003249 /**
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003250 * Return all the enabled, exported and main activities from a package.
3251 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003252 @NonNull
3253 List<ResolveInfo> injectGetMainActivities(@NonNull String packageName, int userId) {
3254 final long start = injectElapsedRealtime();
Makoto Onukib08790c2016-06-23 14:05:46 -07003255 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003256 return queryActivities(getMainActivityIntent(), packageName, null, userId);
Makoto Onukib08790c2016-06-23 14:05:46 -07003257 } finally {
Makoto Onukib08790c2016-06-23 14:05:46 -07003258 logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start);
3259 }
3260 }
3261
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003262 /**
3263 * Return whether an activity is enabled and exported.
3264 */
3265 @VisibleForTesting
3266 boolean injectIsActivityEnabledAndExported(
3267 @NonNull ComponentName activity, @UserIdInt int userId) {
3268 final long start = injectElapsedRealtime();
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003269 try {
3270 return queryActivities(new Intent(), activity.getPackageName(), activity, userId)
3271 .size() > 0;
3272 } finally {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003273 logDurationStat(Stats.IS_ACTIVITY_ENABLED, start);
3274 }
3275 }
3276
Makoto Onuki2d895c32016-12-02 15:48:40 -08003277 /**
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003278 * Get the {@link LauncherApps#ACTION_CONFIRM_PIN_SHORTCUT} or
3279 * {@link LauncherApps#ACTION_CONFIRM_PIN_APPWIDGET} activity in a given package depending on
3280 * the requestType.
Makoto Onuki2d895c32016-12-02 15:48:40 -08003281 */
3282 @Nullable
3283 ComponentName injectGetPinConfirmationActivity(@NonNull String launcherPackageName,
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003284 int launcherUserId, int requestType) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08003285 Preconditions.checkNotNull(launcherPackageName);
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003286 String action = requestType == LauncherApps.PinItemRequest.REQUEST_TYPE_SHORTCUT ?
3287 LauncherApps.ACTION_CONFIRM_PIN_SHORTCUT :
3288 LauncherApps.ACTION_CONFIRM_PIN_APPWIDGET;
Makoto Onuki2d895c32016-12-02 15:48:40 -08003289
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003290 final Intent confirmIntent = new Intent(action).setPackage(launcherPackageName);
Makoto Onuki2d895c32016-12-02 15:48:40 -08003291 final List<ResolveInfo> candidates = queryActivities(
3292 confirmIntent, launcherUserId, /* exportedOnly =*/ false);
3293 for (ResolveInfo ri : candidates) {
3294 return ri.activityInfo.getComponentName();
3295 }
3296 return null;
3297 }
3298
Makoto Onukib08790c2016-06-23 14:05:46 -07003299 boolean injectIsSafeModeEnabled() {
3300 final long token = injectClearCallingIdentity();
3301 try {
3302 return IWindowManager.Stub
3303 .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE))
3304 .isSafeModeEnabled();
3305 } catch (RemoteException e) {
3306 return false; // Shouldn't happen though.
3307 } finally {
3308 injectRestoreCallingIdentity(token);
3309 }
3310 }
3311
Makoto Onuki2d895c32016-12-02 15:48:40 -08003312 /**
3313 * If {@code userId} is of a managed profile, return the parent user ID. Otherwise return
3314 * itself.
3315 */
3316 int getParentOrSelfUserId(int userId) {
3317 final long token = injectClearCallingIdentity();
3318 try {
3319 final UserInfo parent = mUserManager.getProfileParent(userId);
3320 return (parent != null) ? parent.id : userId;
3321 } finally {
3322 injectRestoreCallingIdentity(token);
3323 }
3324 }
3325
Sunny Goyal87a563e2017-01-01 19:42:45 -08003326 void injectSendIntentSender(IntentSender intentSender, Intent extras) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08003327 if (intentSender == null) {
3328 return;
3329 }
3330 try {
Sunny Goyal87a563e2017-01-01 19:42:45 -08003331 intentSender.sendIntent(mContext, /* code= */ 0, extras,
Makoto Onuki2d895c32016-12-02 15:48:40 -08003332 /* onFinished=*/ null, /* handler= */ null);
3333 } catch (SendIntentException e) {
3334 Slog.w(TAG, "sendIntent failed().", e);
3335 }
3336 }
3337
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003338 // === Backup & restore ===
3339
Makoto Onuki0acbb142016-03-22 17:02:57 -07003340 boolean shouldBackupApp(String packageName, int userId) {
Makoto Onuki905e8852016-03-28 10:40:58 -07003341 return isApplicationFlagSet(packageName, userId, ApplicationInfo.FLAG_ALLOW_BACKUP);
Makoto Onuki0acbb142016-03-22 17:02:57 -07003342 }
3343
Makoto Onuki2e210c42016-03-30 08:30:36 -07003344 boolean shouldBackupApp(PackageInfo pi) {
3345 return (pi.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0;
3346 }
3347
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003348 @Override
Makoto Onuki2e210c42016-03-30 08:30:36 -07003349 public byte[] getBackupPayload(@UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003350 enforceSystem();
3351 if (DEBUG) {
3352 Slog.d(TAG, "Backing up user " + userId);
3353 }
3354 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003355 if (!isUserUnlockedL(userId)) {
3356 wtf("Can't backup: user " + userId + " is locked or not running");
3357 return null;
3358 }
3359
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003360 final ShortcutUser user = getUserShortcutsLocked(userId);
3361 if (user == null) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003362 wtf("Can't backup: user not found: id=" + userId);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003363 return null;
3364 }
3365
Makoto Onukic8c33292016-09-12 16:36:59 -07003366 // Update the signatures for all packages.
3367 user.forAllPackageItems(spi -> spi.refreshPackageSignatureAndSave());
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003368
Makoto Onukic8c33292016-09-12 16:36:59 -07003369 // Set the version code for the launchers.
3370 // We shouldn't do this for publisher packages, because we don't want to update the
3371 // version code without rescanning the manifest.
3372 user.forAllLaunchers(launcher -> launcher.ensureVersionInfo());
3373
3374 // Save to the filesystem.
3375 scheduleSaveUser(userId);
3376 saveDirtyInfo();
3377
Makoto Onuki475c3652017-05-08 14:29:03 -07003378 // Note, in case of backup, we don't have to wait on bitmap saving, because we don't
3379 // back up bitmaps anyway.
3380
Makoto Onukic8c33292016-09-12 16:36:59 -07003381 // Then create the backup payload.
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003382 final ByteArrayOutputStream os = new ByteArrayOutputStream(32 * 1024);
3383 try {
3384 saveUserInternalLocked(userId, os, /* forBackup */ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07003385 } catch (XmlPullParserException | IOException e) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003386 // Shouldn't happen.
3387 Slog.w(TAG, "Backup failed.", e);
3388 return null;
3389 }
3390 return os.toByteArray();
3391 }
3392 }
3393
3394 @Override
Makoto Onuki2e210c42016-03-30 08:30:36 -07003395 public void applyRestore(byte[] payload, @UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003396 enforceSystem();
3397 if (DEBUG) {
3398 Slog.d(TAG, "Restoring user " + userId);
3399 }
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003400 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003401 if (!isUserUnlockedL(userId)) {
3402 wtf("Can't restore: user " + userId + " is locked or not running");
3403 return;
3404 }
Makoto Onuki50a320e2017-05-31 14:38:42 -07003405
3406 // Note we print the file timestamps in dumpsys too, but also printing the timestamp
3407 // in the files anyway.
3408 mShortcutDumpFiles.save("restore-0-start.txt", pw -> {
3409 pw.print("Start time: ");
3410 dumpCurrentTime(pw);
3411 pw.println();
3412 });
3413 mShortcutDumpFiles.save("restore-1-payload.xml", payload);
3414
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003415 // Actually do restore.
3416 final ShortcutUser restored;
Makoto Onuki02f338e2016-07-29 09:40:40 -07003417 final ByteArrayInputStream is = new ByteArrayInputStream(payload);
3418 try {
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003419 restored = loadUserInternal(userId, is, /* fromBackup */ true);
3420 } catch (XmlPullParserException | IOException | InvalidFileFormatException e) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003421 Slog.w(TAG, "Restoration failed.", e);
3422 return;
3423 }
Makoto Onuki50a320e2017-05-31 14:38:42 -07003424 mShortcutDumpFiles.save("restore-2.txt", this::dumpInner);
3425
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003426 getUserShortcutsLocked(userId).mergeRestoredFile(restored);
Makoto Onuki2e210c42016-03-30 08:30:36 -07003427
Makoto Onuki50a320e2017-05-31 14:38:42 -07003428 mShortcutDumpFiles.save("restore-3.txt", this::dumpInner);
3429
Makoto Onuki377b7972016-08-09 14:43:55 -07003430 // Rescan all packages to re-publish manifest shortcuts and do other checks.
3431 rescanUpdatedPackagesLocked(userId,
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003432 0 // lastScanTime = 0; rescan all packages.
3433 );
Makoto Onuki2e210c42016-03-30 08:30:36 -07003434
Makoto Onuki50a320e2017-05-31 14:38:42 -07003435 mShortcutDumpFiles.save("restore-4.txt", this::dumpInner);
3436
3437 mShortcutDumpFiles.save("restore-5-finish.txt", pw -> {
3438 pw.print("Finish time: ");
3439 dumpCurrentTime(pw);
3440 pw.println();
3441 });
3442
Makoto Onuki2e210c42016-03-30 08:30:36 -07003443 saveUserLocked(userId);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003444 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07003445 }
3446
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003447 // === Dump ===
3448
3449 @Override
3450 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06003451 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
Makoto Onukic4361e32017-04-03 11:24:25 -07003452 dumpNoCheck(fd, pw, args);
3453 }
3454
3455 @VisibleForTesting
3456 void dumpNoCheck(FileDescriptor fd, PrintWriter pw, String[] args) {
Makoto Onuki50a320e2017-05-31 14:38:42 -07003457
3458 boolean dumpMain = true;
Makoto Onuki76269922016-07-15 14:58:54 -07003459 boolean checkin = false;
3460 boolean clear = false;
Makoto Onuki50a320e2017-05-31 14:38:42 -07003461 boolean dumpUid = false;
3462 boolean dumpFiles = false;
3463
Makoto Onuki76269922016-07-15 14:58:54 -07003464 if (args != null) {
3465 for (String arg : args) {
3466 if ("-c".equals(arg)) {
3467 checkin = true;
Makoto Onuki50a320e2017-05-31 14:38:42 -07003468
Makoto Onuki76269922016-07-15 14:58:54 -07003469 } else if ("--checkin".equals(arg)) {
3470 checkin = true;
3471 clear = true;
Makoto Onuki50a320e2017-05-31 14:38:42 -07003472
3473 } else if ("-a".equals(arg) || "--all".equals(arg)) {
3474 dumpUid = true;
3475 dumpFiles = true;
3476
3477 } else if ("-u".equals(arg) || "--uid".equals(arg)) {
3478 dumpUid = true;
3479
3480 } else if ("-f".equals(arg) || "--files".equals(arg)) {
3481 dumpFiles = true;
3482
3483 } else if ("-n".equals(arg) || "--no-main".equals(arg)) {
3484 dumpMain = false;
Makoto Onuki76269922016-07-15 14:58:54 -07003485 }
3486 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003487 }
Makoto Onuki76269922016-07-15 14:58:54 -07003488
3489 if (checkin) {
Makoto Onuki50a320e2017-05-31 14:38:42 -07003490 // Other flags are not supported for checkin.
Makoto Onuki76269922016-07-15 14:58:54 -07003491 dumpCheckin(pw, clear);
3492 } else {
Makoto Onuki50a320e2017-05-31 14:38:42 -07003493 if (dumpMain) {
3494 dumpInner(pw);
3495 pw.println();
3496 }
3497 if (dumpUid) {
3498 dumpUid(pw);
3499 pw.println();
3500 }
3501 if (dumpFiles) {
3502 dumpDumpFiles(pw);
3503 pw.println();
3504 }
Makoto Onuki76269922016-07-15 14:58:54 -07003505 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003506 }
3507
Makoto Onuki76269922016-07-15 14:58:54 -07003508 private void dumpInner(PrintWriter pw) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003509 synchronized (mLock) {
3510 final long now = injectCurrentTimeMillis();
3511 pw.print("Now: [");
3512 pw.print(now);
3513 pw.print("] ");
3514 pw.print(formatTime(now));
Makoto Onuki55046222016-03-08 10:49:47 -08003515
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003516 pw.print(" Raw last reset: [");
3517 pw.print(mRawLastResetTime);
3518 pw.print("] ");
3519 pw.print(formatTime(mRawLastResetTime));
3520
3521 final long last = getLastResetTimeLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003522 pw.print(" Last reset: [");
3523 pw.print(last);
3524 pw.print("] ");
3525 pw.print(formatTime(last));
3526
Makoto Onuki55046222016-03-08 10:49:47 -08003527 final long next = getNextResetTimeLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003528 pw.print(" Next reset: [");
3529 pw.print(next);
3530 pw.print("] ");
3531 pw.print(formatTime(next));
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003532
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003533 pw.print(" Config:");
3534 pw.print(" Max icon dim: ");
3535 pw.println(mMaxIconDimension);
3536 pw.print(" Icon format: ");
3537 pw.println(mIconPersistFormat);
3538 pw.print(" Icon quality: ");
Makoto Onuki2e210c42016-03-30 08:30:36 -07003539 pw.println(mIconPersistQuality);
Makoto Onuki0033b2a2016-04-14 17:19:16 -07003540 pw.print(" saveDelayMillis: ");
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003541 pw.println(mSaveDelayMillis);
Makoto Onuki0033b2a2016-04-14 17:19:16 -07003542 pw.print(" resetInterval: ");
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003543 pw.println(mResetInterval);
Makoto Onuki0033b2a2016-04-14 17:19:16 -07003544 pw.print(" maxUpdatesPerInterval: ");
Makoto Onukib6d35232016-04-04 15:57:17 -07003545 pw.println(mMaxUpdatesPerInterval);
Makoto Onukib08790c2016-06-23 14:05:46 -07003546 pw.print(" maxShortcutsPerActivity: ");
Makoto Onukib5a012f2016-06-21 11:13:53 -07003547 pw.println(mMaxShortcuts);
Makoto Onuki55046222016-03-08 10:49:47 -08003548 pw.println();
3549
Makoto Onuki2e210c42016-03-30 08:30:36 -07003550 pw.println(" Stats:");
3551 synchronized (mStatLock) {
Makoto Onuki085a05c2016-08-19 11:39:29 -07003552 for (int i = 0; i < Stats.COUNT; i++) {
3553 dumpStatLS(pw, " ", i);
3554 }
Makoto Onuki2e210c42016-03-30 08:30:36 -07003555 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003556
Makoto Onukia2241832016-07-06 13:28:37 -07003557 pw.println();
3558 pw.print(" #Failures: ");
3559 pw.println(mWtfCount);
3560
3561 if (mLastWtfStacktrace != null) {
3562 pw.print(" Last failure stack trace: ");
3563 pw.println(Log.getStackTraceString(mLastWtfStacktrace));
3564 }
3565
Makoto Onuki475c3652017-05-08 14:29:03 -07003566 pw.println();
3567 mShortcutBitmapSaver.dumpLocked(pw, " ");
3568
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08003569 for (int i = 0; i < mUsers.size(); i++) {
3570 pw.println();
Makoto Onukic51b2872016-05-04 15:24:50 -07003571 mUsers.valueAt(i).dump(pw, " ");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003572 }
Makoto Onuki50a320e2017-05-31 14:38:42 -07003573 }
3574 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003575
Makoto Onuki50a320e2017-05-31 14:38:42 -07003576 private void dumpUid(PrintWriter pw) {
3577 synchronized (mLock) {
3578 pw.println("** SHORTCUT MANAGER UID STATES (dumpsys shortcut -n -u)");
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003579
3580 for (int i = 0; i < mUidState.size(); i++) {
3581 final int uid = mUidState.keyAt(i);
3582 final int state = mUidState.valueAt(i);
3583 pw.print(" UID=");
3584 pw.print(uid);
3585 pw.print(" state=");
3586 pw.print(state);
3587 if (isProcessStateForeground(state)) {
3588 pw.print(" [FG]");
3589 }
3590 pw.print(" last FG=");
3591 pw.print(mUidLastForegroundElapsedTime.get(uid));
3592 pw.println();
3593 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003594 }
3595 }
3596
Makoto Onuki41066a62016-03-09 16:18:44 -08003597 static String formatTime(long time) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003598 Time tobj = new Time();
3599 tobj.set(time);
3600 return tobj.format("%Y-%m-%d %H:%M:%S");
3601 }
3602
Makoto Onuki50a320e2017-05-31 14:38:42 -07003603 private void dumpCurrentTime(PrintWriter pw) {
3604 pw.print(formatTime(injectCurrentTimeMillis()));
3605 }
3606
Makoto Onuki085a05c2016-08-19 11:39:29 -07003607 private void dumpStatLS(PrintWriter pw, String prefix, int statId) {
Makoto Onuki2e210c42016-03-30 08:30:36 -07003608 pw.print(prefix);
3609 final int count = mCountStats[statId];
3610 final long dur = mDurationStats[statId];
3611 pw.println(String.format("%s: count=%d, total=%dms, avg=%.1fms",
Makoto Onuki085a05c2016-08-19 11:39:29 -07003612 STAT_LABELS[statId], count, dur,
Makoto Onuki2e210c42016-03-30 08:30:36 -07003613 (count == 0 ? 0 : ((double) dur) / count)));
3614 }
3615
Makoto Onuki76269922016-07-15 14:58:54 -07003616 /**
3617 * Dumpsys for checkin.
3618 *
3619 * @param clear if true, clear the history information. Some other system services have this
3620 * behavior but shortcut service doesn't for now.
3621 */
3622 private void dumpCheckin(PrintWriter pw, boolean clear) {
3623 synchronized (mLock) {
3624 try {
3625 final JSONArray users = new JSONArray();
3626
3627 for (int i = 0; i < mUsers.size(); i++) {
3628 users.put(mUsers.valueAt(i).dumpCheckin(clear));
3629 }
3630
3631 final JSONObject result = new JSONObject();
3632
3633 result.put(KEY_SHORTCUT, users);
3634 result.put(KEY_LOW_RAM, injectIsLowRamDevice());
3635 result.put(KEY_ICON_SIZE, mMaxIconDimension);
3636
3637 pw.println(result.toString(1));
3638 } catch (JSONException e) {
3639 Slog.e(TAG, "Unable to write in json", e);
3640 }
3641 }
3642 }
3643
Makoto Onuki50a320e2017-05-31 14:38:42 -07003644 private void dumpDumpFiles(PrintWriter pw) {
3645 synchronized (mLock) {
3646 pw.println("** SHORTCUT MANAGER FILES (dumpsys shortcut -n -f)");
3647 mShortcutDumpFiles.dumpAll(pw);
3648 }
3649 }
3650
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003651 // === Shell support ===
3652
3653 @Override
3654 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003655 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003656
3657 enforceShell();
3658
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07003659 final long token = injectClearCallingIdentity();
3660 try {
Dianne Hackborn354736e2016-08-22 17:00:05 -07003661 final int status = (new MyShellCommand()).exec(this, in, out, err, args, callback,
3662 resultReceiver);
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07003663 resultReceiver.send(status, null);
3664 } finally {
3665 injectRestoreCallingIdentity(token);
3666 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003667 }
3668
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003669 static class CommandException extends Exception {
3670 public CommandException(String message) {
3671 super(message);
3672 }
3673 }
3674
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003675 /**
3676 * Handle "adb shell cmd".
3677 */
3678 private class MyShellCommand extends ShellCommand {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003679
3680 private int mUserId = UserHandle.USER_SYSTEM;
3681
Makoto Onuki02f338e2016-07-29 09:40:40 -07003682 private void parseOptionsLocked(boolean takeUser)
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003683 throws CommandException {
3684 String opt;
3685 while ((opt = getNextOption()) != null) {
3686 switch (opt) {
3687 case "--user":
3688 if (takeUser) {
3689 mUserId = UserHandle.parseUserArg(getNextArgRequired());
Makoto Onuki02f338e2016-07-29 09:40:40 -07003690 if (!isUserUnlockedL(mUserId)) {
Makoto Onukif34c3082016-07-13 10:25:25 -07003691 throw new CommandException(
3692 "User " + mUserId + " is not running or locked");
3693 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003694 break;
3695 }
3696 // fallthrough
3697 default:
3698 throw new CommandException("Unknown option: " + opt);
3699 }
3700 }
3701 }
3702
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003703 @Override
3704 public int onCommand(String cmd) {
3705 if (cmd == null) {
3706 return handleDefaultCommands(cmd);
3707 }
3708 final PrintWriter pw = getOutPrintWriter();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003709 try {
3710 switch (cmd) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003711 case "reset-throttling":
3712 handleResetThrottling();
3713 break;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003714 case "reset-all-throttling":
3715 handleResetAllThrottling();
3716 break;
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003717 case "override-config":
3718 handleOverrideConfig();
3719 break;
3720 case "reset-config":
3721 handleResetConfig();
3722 break;
3723 case "clear-default-launcher":
3724 handleClearDefaultLauncher();
3725 break;
3726 case "get-default-launcher":
3727 handleGetDefaultLauncher();
3728 break;
Makoto Onukiac214972016-04-04 10:19:45 -07003729 case "unload-user":
3730 handleUnloadUser();
3731 break;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003732 case "clear-shortcuts":
3733 handleClearShortcuts();
3734 break;
Makoto Onukib08790c2016-06-23 14:05:46 -07003735 case "verify-states": // hidden command to verify various internal states.
3736 handleVerifyStates();
3737 break;
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003738 default:
3739 return handleDefaultCommands(cmd);
3740 }
3741 } catch (CommandException e) {
3742 pw.println("Error: " + e.getMessage());
3743 return 1;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003744 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003745 pw.println("Success");
3746 return 0;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003747 }
3748
3749 @Override
3750 public void onHelp() {
3751 final PrintWriter pw = getOutPrintWriter();
3752 pw.println("Usage: cmd shortcut COMMAND [options ...]");
3753 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003754 pw.println("cmd shortcut reset-throttling [--user USER_ID]");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003755 pw.println(" Reset throttling for all packages and users");
3756 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003757 pw.println("cmd shortcut reset-all-throttling");
3758 pw.println(" Reset the throttling state for all users");
3759 pw.println();
Makoto Onuki4362a662016-03-08 18:59:09 -08003760 pw.println("cmd shortcut override-config CONFIG");
3761 pw.println(" Override the configuration for testing (will last until reboot)");
3762 pw.println();
3763 pw.println("cmd shortcut reset-config");
3764 pw.println(" Reset the configuration set with \"update-config\"");
3765 pw.println();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003766 pw.println("cmd shortcut clear-default-launcher [--user USER_ID]");
3767 pw.println(" Clear the cached default launcher");
3768 pw.println();
3769 pw.println("cmd shortcut get-default-launcher [--user USER_ID]");
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07003770 pw.println(" Show the default launcher");
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003771 pw.println();
Makoto Onukiac214972016-04-04 10:19:45 -07003772 pw.println("cmd shortcut unload-user [--user USER_ID]");
3773 pw.println(" Unload a user from the memory");
3774 pw.println(" (This should not affect any observable behavior)");
3775 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003776 pw.println("cmd shortcut clear-shortcuts [--user USER_ID] PACKAGE");
3777 pw.println(" Remove all shortcuts from a package, including pinned shortcuts");
3778 pw.println();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003779 }
3780
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003781 private void handleResetThrottling() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003782 synchronized (mLock) {
3783 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki4554d0e2016-03-14 15:51:41 -07003784
Makoto Onuki02f338e2016-07-29 09:40:40 -07003785 Slog.i(TAG, "cmd: handleResetThrottling: user=" + mUserId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003786
Makoto Onuki02f338e2016-07-29 09:40:40 -07003787 resetThrottlingInner(mUserId);
3788 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003789 }
3790
3791 private void handleResetAllThrottling() {
3792 Slog.i(TAG, "cmd: handleResetAllThrottling");
3793
3794 resetAllThrottlingInner();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003795 }
3796
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003797 private void handleOverrideConfig() throws CommandException {
Makoto Onuki4362a662016-03-08 18:59:09 -08003798 final String config = getNextArgRequired();
3799
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003800 Slog.i(TAG, "cmd: handleOverrideConfig: " + config);
3801
Makoto Onuki4362a662016-03-08 18:59:09 -08003802 synchronized (mLock) {
3803 if (!updateConfigurationLocked(config)) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003804 throw new CommandException("override-config failed. See logcat for details.");
Makoto Onuki4362a662016-03-08 18:59:09 -08003805 }
3806 }
Makoto Onuki4362a662016-03-08 18:59:09 -08003807 }
3808
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003809 private void handleResetConfig() {
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003810 Slog.i(TAG, "cmd: handleResetConfig");
3811
Makoto Onuki4362a662016-03-08 18:59:09 -08003812 synchronized (mLock) {
3813 loadConfigurationLocked();
3814 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003815 }
3816
3817 private void clearLauncher() {
3818 synchronized (mLock) {
Makoto Onuki10305202016-07-14 18:14:08 -07003819 getUserShortcutsLocked(mUserId).forceClearLauncher();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003820 }
3821 }
3822
3823 private void showLauncher() {
3824 synchronized (mLock) {
3825 // This ensures to set the cached launcher. Package name doesn't matter.
3826 hasShortcutHostPermissionInner("-", mUserId);
3827
3828 getOutPrintWriter().println("Launcher: "
Makoto Onuki10305202016-07-14 18:14:08 -07003829 + getUserShortcutsLocked(mUserId).getLastKnownLauncher());
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003830 }
3831 }
3832
3833 private void handleClearDefaultLauncher() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003834 synchronized (mLock) {
3835 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003836
Makoto Onuki02f338e2016-07-29 09:40:40 -07003837 clearLauncher();
3838 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003839 }
3840
3841 private void handleGetDefaultLauncher() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003842 synchronized (mLock) {
3843 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003844
Makoto Onuki02f338e2016-07-29 09:40:40 -07003845 clearLauncher();
3846 showLauncher();
3847 }
Makoto Onuki4362a662016-03-08 18:59:09 -08003848 }
Makoto Onukiac214972016-04-04 10:19:45 -07003849
3850 private void handleUnloadUser() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003851 synchronized (mLock) {
3852 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onukiac214972016-04-04 10:19:45 -07003853
Makoto Onuki02f338e2016-07-29 09:40:40 -07003854 Slog.i(TAG, "cmd: handleUnloadUser: user=" + mUserId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003855
Makoto Onuki01ce92b2017-04-28 12:24:16 -07003856 ShortcutService.this.handleStopUser(mUserId);
Makoto Onuki02f338e2016-07-29 09:40:40 -07003857 }
Makoto Onukiac214972016-04-04 10:19:45 -07003858 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003859
3860 private void handleClearShortcuts() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003861 synchronized (mLock) {
3862 parseOptionsLocked(/* takeUser =*/ true);
3863 final String packageName = getNextArgRequired();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003864
Makoto Onuki02f338e2016-07-29 09:40:40 -07003865 Slog.i(TAG, "cmd: handleClearShortcuts: user" + mUserId + ", " + packageName);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003866
Makoto Onuki02f338e2016-07-29 09:40:40 -07003867 ShortcutService.this.cleanUpPackageForAllLoadedUsers(packageName, mUserId,
3868 /* appStillExists = */ true);
3869 }
Makoto Onukib08790c2016-06-23 14:05:46 -07003870 }
3871
3872 private void handleVerifyStates() throws CommandException {
3873 try {
3874 verifyStatesForce(); // This will throw when there's an issue.
3875 } catch (Throwable th) {
3876 throw new CommandException(th.getMessage() + "\n" + Log.getStackTraceString(th));
3877 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003878 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003879 }
3880
3881 // === Unit test support ===
3882
3883 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07003884 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003885 long injectCurrentTimeMillis() {
3886 return System.currentTimeMillis();
3887 }
3888
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003889 @VisibleForTesting
3890 long injectElapsedRealtime() {
3891 return SystemClock.elapsedRealtime();
3892 }
3893
Makoto Onuki475c3652017-05-08 14:29:03 -07003894 @VisibleForTesting
3895 long injectUptimeMillis() {
3896 return SystemClock.uptimeMillis();
3897 }
3898
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003899 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07003900 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003901 int injectBinderCallingUid() {
3902 return getCallingUid();
3903 }
3904
Makoto Onuki31459242016-03-22 11:12:18 -07003905 private int getCallingUserId() {
Makoto Onuki4554d0e2016-03-14 15:51:41 -07003906 return UserHandle.getUserId(injectBinderCallingUid());
3907 }
3908
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07003909 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07003910 @VisibleForTesting
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07003911 long injectClearCallingIdentity() {
3912 return Binder.clearCallingIdentity();
3913 }
3914
3915 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07003916 @VisibleForTesting
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07003917 void injectRestoreCallingIdentity(long token) {
3918 Binder.restoreCallingIdentity(token);
3919 }
3920
Makoto Onuki33663282016-08-22 16:19:04 -07003921 // Injection point.
3922 @VisibleForTesting
3923 String injectBuildFingerprint() {
3924 return Build.FINGERPRINT;
3925 }
3926
Makoto Onukide667372016-03-15 14:29:20 -07003927 final void wtf(String message) {
Makoto Onukib08790c2016-06-23 14:05:46 -07003928 wtf(message, /* exception= */ null);
Makoto Onukide667372016-03-15 14:29:20 -07003929 }
3930
Makoto Onuki2e210c42016-03-30 08:30:36 -07003931 // Injection point.
Makoto Onukia2241832016-07-06 13:28:37 -07003932 void wtf(String message, Throwable e) {
3933 if (e == null) {
3934 e = new RuntimeException("Stacktrace");
3935 }
3936 synchronized (mLock) {
3937 mWtfCount++;
3938 mLastWtfStacktrace = new Exception("Last failure was logged here:");
3939 }
Makoto Onukide667372016-03-15 14:29:20 -07003940 Slog.wtf(TAG, message, e);
3941 }
3942
Makoto Onuki31459242016-03-22 11:12:18 -07003943 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003944 File injectSystemDataPath() {
3945 return Environment.getDataSystemDirectory();
3946 }
3947
Makoto Onuki31459242016-03-22 11:12:18 -07003948 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003949 File injectUserDataPath(@UserIdInt int userId) {
Makoto Onuki55046222016-03-08 10:49:47 -08003950 return new File(Environment.getDataSystemCeDirectory(userId), DIRECTORY_PER_USER);
3951 }
3952
Makoto Onuki50a320e2017-05-31 14:38:42 -07003953 public File getDumpPath() {
3954 return new File(injectUserDataPath(UserHandle.USER_SYSTEM), DIRECTORY_DUMP);
3955 }
3956
Makoto Onuki4362a662016-03-08 18:59:09 -08003957 @VisibleForTesting
Makoto Onuki55046222016-03-08 10:49:47 -08003958 boolean injectIsLowRamDevice() {
3959 return ActivityManager.isLowRamDeviceStatic();
3960 }
3961
Makoto Onuki31459242016-03-22 11:12:18 -07003962 @VisibleForTesting
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003963 void injectRegisterUidObserver(IUidObserver observer, int which) {
3964 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003965 ActivityManager.getService().registerUidObserver(observer, which,
Dianne Hackborn5614bf52016-11-07 17:26:41 -08003966 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003967 } catch (RemoteException shouldntHappen) {
3968 }
3969 }
3970
Makoto Onuki55046222016-03-08 10:49:47 -08003971 File getUserBitmapFilePath(@UserIdInt int userId) {
3972 return new File(injectUserDataPath(userId), DIRECTORY_BITMAPS);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003973 }
3974
3975 @VisibleForTesting
Makoto Onuki31459242016-03-22 11:12:18 -07003976 SparseArray<ShortcutUser> getShortcutsForTest() {
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08003977 return mUsers;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003978 }
3979
3980 @VisibleForTesting
Makoto Onukib5a012f2016-06-21 11:13:53 -07003981 int getMaxShortcutsForTest() {
3982 return mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003983 }
3984
3985 @VisibleForTesting
Makoto Onukib6d35232016-04-04 15:57:17 -07003986 int getMaxUpdatesPerIntervalForTest() {
3987 return mMaxUpdatesPerInterval;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003988 }
3989
3990 @VisibleForTesting
Makoto Onuki4362a662016-03-08 18:59:09 -08003991 long getResetIntervalForTest() {
3992 return mResetInterval;
Makoto Onuki55046222016-03-08 10:49:47 -08003993 }
3994
3995 @VisibleForTesting
Makoto Onuki4362a662016-03-08 18:59:09 -08003996 int getMaxIconDimensionForTest() {
3997 return mMaxIconDimension;
3998 }
3999
4000 @VisibleForTesting
4001 CompressFormat getIconPersistFormatForTest() {
4002 return mIconPersistFormat;
4003 }
4004
4005 @VisibleForTesting
4006 int getIconPersistQualityForTest() {
4007 return mIconPersistQuality;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004008 }
Makoto Onuki41066a62016-03-09 16:18:44 -08004009
4010 @VisibleForTesting
Makoto Onuki22fcc682016-05-17 14:52:19 -07004011 ShortcutPackage getPackageShortcutForTest(String packageName, int userId) {
Makoto Onuki41066a62016-03-09 16:18:44 -08004012 synchronized (mLock) {
Makoto Onuki31459242016-03-22 11:12:18 -07004013 final ShortcutUser user = mUsers.get(userId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07004014 if (user == null) return null;
4015
Makoto Onuki22fcc682016-05-17 14:52:19 -07004016 return user.getAllPackagesForTest().get(packageName);
4017 }
4018 }
4019
4020 @VisibleForTesting
4021 ShortcutInfo getPackageShortcutForTest(String packageName, String shortcutId, int userId) {
4022 synchronized (mLock) {
Makoto Onukif34c3082016-07-13 10:25:25 -07004023 final ShortcutPackage pkg = getPackageShortcutForTest(packageName, userId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07004024 if (pkg == null) return null;
4025
4026 return pkg.findShortcutById(shortcutId);
Makoto Onuki41066a62016-03-09 16:18:44 -08004027 }
4028 }
Makoto Onuki7001a612016-05-27 13:24:28 -07004029
Makoto Onukifac592f2016-11-21 13:41:32 -08004030 @VisibleForTesting
4031 ShortcutLauncher getLauncherShortcutForTest(String packageName, int userId) {
4032 synchronized (mLock) {
4033 final ShortcutUser user = mUsers.get(userId);
4034 if (user == null) return null;
4035
4036 return user.getAllLaunchersForTest().get(PackageWithUser.of(userId, packageName));
4037 }
4038 }
4039
Makoto Onuki2d895c32016-12-02 15:48:40 -08004040 @VisibleForTesting
4041 ShortcutRequestPinProcessor getShortcutRequestPinProcessorForTest() {
4042 return mShortcutRequestPinProcessor;
4043 }
4044
Makoto Onuki7001a612016-05-27 13:24:28 -07004045 /**
4046 * Control whether {@link #verifyStates} should be performed. We always perform it during unit
4047 * tests.
4048 */
4049 @VisibleForTesting
4050 boolean injectShouldPerformVerification() {
4051 return DEBUG;
4052 }
4053
4054 /**
4055 * Check various internal states and throws if there's any inconsistency.
4056 * This is normally only enabled during unit tests.
4057 */
4058 final void verifyStates() {
4059 if (injectShouldPerformVerification()) {
4060 verifyStatesInner();
4061 }
4062 }
4063
Makoto Onukib08790c2016-06-23 14:05:46 -07004064 private final void verifyStatesForce() {
4065 verifyStatesInner();
4066 }
4067
Makoto Onuki7001a612016-05-27 13:24:28 -07004068 private void verifyStatesInner() {
Makoto Onuki10305202016-07-14 18:14:08 -07004069 synchronized (mLock) {
Makoto Onuki7001a612016-05-27 13:24:28 -07004070 forEachLoadedUserLocked(u -> u.forAllPackageItems(ShortcutPackageItem::verifyStates));
4071 }
4072 }
Makoto Onuki475c3652017-05-08 14:29:03 -07004073
4074 @VisibleForTesting
4075 void waitForBitmapSavesForTest() {
4076 synchronized (mLock) {
4077 mShortcutBitmapSaver.waitForAllSavesLocked();
4078 }
4079 }
Makoto Onuki41066a62016-03-09 16:18:44 -08004080}