blob: 15d20716a322383d4d61dda53121c0e55df11c26 [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 Onukidc3f6d12017-09-22 17:22:50 -0700487 injectPostToHandler(() -> handleOnUidStateChanged(uid, procState));
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700488 }
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) {
Makoto Onukidc3f6d12017-09-22 17:22:50 -0700492 injectPostToHandler(() ->
493 handleOnUidStateChanged(uid, ActivityManager.PROCESS_STATE_NONEXISTENT));
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700494 }
495
Makoto Onukib08790c2016-06-23 14:05:46 -0700496 @Override
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700497 public void onUidActive(int uid) {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700498 }
499
Makoto Onukib08790c2016-06-23 14:05:46 -0700500 @Override
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700501 public void onUidIdle(int uid, boolean disabled) {
502 }
503
504 @Override public void onUidCachedChanged(int uid, boolean cached) {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700505 }
506 };
507
508 void handleOnUidStateChanged(int uid, int procState) {
509 if (DEBUG_PROCSTATE) {
510 Slog.d(TAG, "onUidStateChanged: uid=" + uid + " state=" + procState);
511 }
512 synchronized (mLock) {
513 mUidState.put(uid, procState);
514
515 // We need to keep track of last time an app comes to foreground.
516 // See ShortcutPackage.getApiCallCount() for how it's used.
517 // It doesn't have to be persisted, but it needs to be the elapsed time.
518 if (isProcessStateForeground(procState)) {
519 mUidLastForegroundElapsedTime.put(uid, injectElapsedRealtime());
520 }
521 }
522 }
523
524 private boolean isProcessStateForeground(int processState) {
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800525 return processState <= PROCESS_STATE_FOREGROUND_THRESHOLD;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700526 }
527
528 boolean isUidForegroundLocked(int uid) {
529 if (uid == Process.SYSTEM_UID) {
530 // IUidObserver doesn't report the state of SYSTEM, but it always has bound services,
531 // so it's foreground anyway.
532 return true;
533 }
Makoto Onuki33525d22016-08-03 15:45:24 -0700534 // First, check with the local cache.
535 if (isProcessStateForeground(mUidState.get(uid, ActivityManager.MAX_PROCESS_STATE))) {
536 return true;
537 }
538 // If the cache says background, reach out to AM. Since it'll internally need to hold
539 // the AM lock, we use it as a last resort.
540 return isProcessStateForeground(mActivityManagerInternal.getUidProcessState(uid));
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700541 }
542
543 long getUidLastForegroundElapsedTimeLocked(int uid) {
544 return mUidLastForegroundElapsedTime.get(uid);
545 }
546
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800547 /**
548 * System service lifecycle.
549 */
550 public static final class Lifecycle extends SystemService {
551 final ShortcutService mService;
552
553 public Lifecycle(Context context) {
554 super(context);
555 mService = new ShortcutService(context);
556 }
557
558 @Override
559 public void onStart() {
560 publishBinderService(Context.SHORTCUT_SERVICE, mService);
561 }
562
563 @Override
564 public void onBootPhase(int phase) {
565 mService.onBootPhase(phase);
566 }
567
568 @Override
Makoto Onuki01ce92b2017-04-28 12:24:16 -0700569 public void onStopUser(int userHandle) {
570 mService.handleStopUser(userHandle);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800571 }
572
573 @Override
Makoto Onukif3a572b2016-03-10 12:28:38 -0800574 public void onUnlockUser(int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -0700575 mService.handleUnlockUser(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800576 }
577 }
578
579 /** lifecycle event */
580 void onBootPhase(int phase) {
581 if (DEBUG) {
582 Slog.d(TAG, "onBootPhase: " + phase);
583 }
584 switch (phase) {
585 case SystemService.PHASE_LOCK_SETTINGS_READY:
586 initialize();
587 break;
Makoto Onukic51b2872016-05-04 15:24:50 -0700588 case SystemService.PHASE_BOOT_COMPLETED:
589 mBootCompleted.set(true);
590 break;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800591 }
592 }
593
594 /** lifecycle event */
Makoto Onukicdc78f72016-03-21 15:47:52 -0700595 void handleUnlockUser(int userId) {
Makoto Onuki22fcc682016-05-17 14:52:19 -0700596 if (DEBUG) {
Makoto Onuki085a05c2016-08-19 11:39:29 -0700597 Slog.d(TAG, "handleUnlockUser: user=" + userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700598 }
Makoto Onukicdc78f72016-03-21 15:47:52 -0700599 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -0700600 mUnlockedUsers.put(userId, true);
Makoto Onukicdc78f72016-03-21 15:47:52 -0700601 }
Makoto Onuki085a05c2016-08-19 11:39:29 -0700602
603 // Preload the user data.
604 // Note, we don't use mHandler here but instead just start a new thread.
605 // This is because mHandler (which uses com.android.internal.os.BackgroundThread) is very
606 // busy at this point and this could take hundreds of milliseconds, which would be too
607 // late since the launcher would already have started.
608 // So we just create a new thread. This code runs rarely, so we don't use a thread pool
609 // or anything.
610 final long start = injectElapsedRealtime();
611 injectRunOnNewThread(() -> {
612 synchronized (mLock) {
613 logDurationStat(Stats.ASYNC_PRELOAD_USER_DELAY, start);
614 getUserShortcutsLocked(userId);
615 }
616 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800617 }
618
619 /** lifecycle event */
Makoto Onuki01ce92b2017-04-28 12:24:16 -0700620 void handleStopUser(int userId) {
Makoto Onuki02f338e2016-07-29 09:40:40 -0700621 if (DEBUG) {
Makoto Onuki01ce92b2017-04-28 12:24:16 -0700622 Slog.d(TAG, "handleStopUser: user=" + userId);
Makoto Onuki02f338e2016-07-29 09:40:40 -0700623 }
Makoto Onukicdc78f72016-03-21 15:47:52 -0700624 synchronized (mLock) {
625 unloadUserLocked(userId);
Makoto Onuki02f338e2016-07-29 09:40:40 -0700626
627 mUnlockedUsers.put(userId, false);
Makoto Onukicdc78f72016-03-21 15:47:52 -0700628 }
629 }
630
631 private void unloadUserLocked(int userId) {
632 if (DEBUG) {
633 Slog.d(TAG, "unloadUserLocked: user=" + userId);
634 }
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700635 // Save all dirty information.
636 saveDirtyInfo();
637
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800638 // Unload
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -0800639 mUsers.delete(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800640 }
641
642 /** Return the base state file name */
643 private AtomicFile getBaseStateFile() {
644 final File path = new File(injectSystemDataPath(), FILENAME_BASE_STATE);
645 path.mkdirs();
646 return new AtomicFile(path);
647 }
648
649 /**
650 * Init the instance. (load the state file, etc)
651 */
652 private void initialize() {
653 synchronized (mLock) {
Makoto Onuki4362a662016-03-08 18:59:09 -0800654 loadConfigurationLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800655 loadBaseStateLocked();
656 }
657 }
658
Makoto Onuki4362a662016-03-08 18:59:09 -0800659 /**
660 * Load the configuration from Settings.
661 */
662 private void loadConfigurationLocked() {
663 updateConfigurationLocked(injectShortcutManagerConstants());
664 }
Makoto Onuki55046222016-03-08 10:49:47 -0800665
Makoto Onuki4362a662016-03-08 18:59:09 -0800666 /**
667 * Load the configuration from Settings.
668 */
669 @VisibleForTesting
670 boolean updateConfigurationLocked(String config) {
671 boolean result = true;
672
673 final KeyValueListParser parser = new KeyValueListParser(',');
674 try {
675 parser.setString(config);
676 } catch (IllegalArgumentException e) {
677 // Failed to parse the settings string, log this and move on
678 // with defaults.
679 Slog.e(TAG, "Bad shortcut manager settings", e);
680 result = false;
681 }
682
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700683 mSaveDelayMillis = Math.max(0, (int) parser.getLong(ConfigConstants.KEY_SAVE_DELAY_MILLIS,
684 DEFAULT_SAVE_DELAY_MS));
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700685
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700686 mResetInterval = Math.max(1, parser.getLong(
Makoto Onuki4362a662016-03-08 18:59:09 -0800687 ConfigConstants.KEY_RESET_INTERVAL_SEC, DEFAULT_RESET_INTERVAL_SEC)
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700688 * 1000L);
Makoto Onuki4362a662016-03-08 18:59:09 -0800689
Makoto Onukib6d35232016-04-04 15:57:17 -0700690 mMaxUpdatesPerInterval = Math.max(0, (int) parser.getLong(
691 ConfigConstants.KEY_MAX_UPDATES_PER_INTERVAL, DEFAULT_MAX_UPDATES_PER_INTERVAL));
Makoto Onuki4362a662016-03-08 18:59:09 -0800692
Makoto Onukib5a012f2016-06-21 11:13:53 -0700693 mMaxShortcuts = Math.max(0, (int) parser.getLong(
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700694 ConfigConstants.KEY_MAX_SHORTCUTS, DEFAULT_MAX_SHORTCUTS_PER_APP));
Makoto Onuki4362a662016-03-08 18:59:09 -0800695
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700696 final int iconDimensionDp = Math.max(1, injectIsLowRamDevice()
Makoto Onuki4362a662016-03-08 18:59:09 -0800697 ? (int) parser.getLong(
Makoto Onukib08790c2016-06-23 14:05:46 -0700698 ConfigConstants.KEY_MAX_ICON_DIMENSION_DP_LOWRAM,
699 DEFAULT_MAX_ICON_DIMENSION_LOWRAM_DP)
Makoto Onuki4362a662016-03-08 18:59:09 -0800700 : (int) parser.getLong(
Makoto Onukib08790c2016-06-23 14:05:46 -0700701 ConfigConstants.KEY_MAX_ICON_DIMENSION_DP,
702 DEFAULT_MAX_ICON_DIMENSION_DP));
Makoto Onuki4362a662016-03-08 18:59:09 -0800703
704 mMaxIconDimension = injectDipToPixel(iconDimensionDp);
705
706 mIconPersistFormat = CompressFormat.valueOf(
707 parser.getString(ConfigConstants.KEY_ICON_FORMAT, DEFAULT_ICON_PERSIST_FORMAT));
708
709 mIconPersistQuality = (int) parser.getLong(
710 ConfigConstants.KEY_ICON_QUALITY,
711 DEFAULT_ICON_PERSIST_QUALITY);
712
713 return result;
714 }
715
716 @VisibleForTesting
717 String injectShortcutManagerConstants() {
718 return android.provider.Settings.Global.getString(
719 mContext.getContentResolver(),
720 android.provider.Settings.Global.SHORTCUT_MANAGER_CONSTANTS);
721 }
722
723 @VisibleForTesting
724 int injectDipToPixel(int dip) {
725 return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip,
726 mContext.getResources().getDisplayMetrics());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800727 }
728
Makoto Onuki55046222016-03-08 10:49:47 -0800729 // === Persisting ===
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800730
731 @Nullable
Makoto Onuki41066a62016-03-09 16:18:44 -0800732 static String parseStringAttribute(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800733 return parser.getAttributeValue(null, attribute);
734 }
735
Makoto Onuki0acbb142016-03-22 17:02:57 -0700736 static boolean parseBooleanAttribute(XmlPullParser parser, String attribute) {
737 return parseLongAttribute(parser, attribute) == 1;
738 }
739
Makoto Onuki41066a62016-03-09 16:18:44 -0800740 static int parseIntAttribute(XmlPullParser parser, String attribute) {
741 return (int) parseLongAttribute(parser, attribute);
742 }
743
Makoto Onukid99c6f02016-03-28 11:02:54 -0700744 static int parseIntAttribute(XmlPullParser parser, String attribute, int def) {
745 return (int) parseLongAttribute(parser, attribute, def);
746 }
747
Makoto Onuki41066a62016-03-09 16:18:44 -0800748 static long parseLongAttribute(XmlPullParser parser, String attribute) {
Makoto Onukid99c6f02016-03-28 11:02:54 -0700749 return parseLongAttribute(parser, attribute, 0);
750 }
751
752 static long parseLongAttribute(XmlPullParser parser, String attribute, long def) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800753 final String value = parseStringAttribute(parser, attribute);
754 if (TextUtils.isEmpty(value)) {
Makoto Onukid99c6f02016-03-28 11:02:54 -0700755 return def;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800756 }
757 try {
758 return Long.parseLong(value);
759 } catch (NumberFormatException e) {
760 Slog.e(TAG, "Error parsing long " + value);
Makoto Onukid99c6f02016-03-28 11:02:54 -0700761 return def;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800762 }
763 }
764
765 @Nullable
Makoto Onuki41066a62016-03-09 16:18:44 -0800766 static ComponentName parseComponentNameAttribute(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800767 final String value = parseStringAttribute(parser, attribute);
768 if (TextUtils.isEmpty(value)) {
769 return null;
770 }
771 return ComponentName.unflattenFromString(value);
772 }
773
774 @Nullable
Makoto Onuki440a1ea2016-07-20 14:21:18 -0700775 static Intent parseIntentAttributeNoDefault(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800776 final String value = parseStringAttribute(parser, attribute);
Makoto Onukib5a012f2016-06-21 11:13:53 -0700777 Intent parsed = null;
778 if (!TextUtils.isEmpty(value)) {
779 try {
780 parsed = Intent.parseUri(value, /* flags =*/ 0);
781 } catch (URISyntaxException e) {
782 Slog.e(TAG, "Error parsing intent", e);
783 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800784 }
Makoto Onuki440a1ea2016-07-20 14:21:18 -0700785 return parsed;
786 }
787
788 @Nullable
789 static Intent parseIntentAttribute(XmlPullParser parser, String attribute) {
790 Intent parsed = parseIntentAttributeNoDefault(parser, attribute);
Makoto Onukib5a012f2016-06-21 11:13:53 -0700791 if (parsed == null) {
792 // Default intent.
793 parsed = new Intent(Intent.ACTION_VIEW);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800794 }
Makoto Onukib5a012f2016-06-21 11:13:53 -0700795 return parsed;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800796 }
797
Makoto Onuki41066a62016-03-09 16:18:44 -0800798 static void writeTagValue(XmlSerializer out, String tag, String value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800799 if (TextUtils.isEmpty(value)) return;
800
801 out.startTag(null, tag);
802 out.attribute(null, ATTR_VALUE, value);
803 out.endTag(null, tag);
804 }
805
Makoto Onuki41066a62016-03-09 16:18:44 -0800806 static void writeTagValue(XmlSerializer out, String tag, long value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800807 writeTagValue(out, tag, Long.toString(value));
808 }
809
Makoto Onuki2d5b4652016-03-11 16:09:54 -0800810 static void writeTagValue(XmlSerializer out, String tag, ComponentName name) throws IOException {
811 if (name == null) return;
812 writeTagValue(out, tag, name.flattenToString());
813 }
814
Makoto Onuki41066a62016-03-09 16:18:44 -0800815 static void writeTagExtra(XmlSerializer out, String tag, PersistableBundle bundle)
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800816 throws IOException, XmlPullParserException {
817 if (bundle == null) return;
818
819 out.startTag(null, tag);
820 bundle.saveToXml(out);
821 out.endTag(null, tag);
822 }
823
Makoto Onuki22fcc682016-05-17 14:52:19 -0700824 static void writeAttr(XmlSerializer out, String name, CharSequence value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800825 if (TextUtils.isEmpty(value)) return;
826
Makoto Onuki22fcc682016-05-17 14:52:19 -0700827 out.attribute(null, name, value.toString());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800828 }
829
Makoto Onuki41066a62016-03-09 16:18:44 -0800830 static void writeAttr(XmlSerializer out, String name, long value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800831 writeAttr(out, name, String.valueOf(value));
832 }
833
Makoto Onuki0acbb142016-03-22 17:02:57 -0700834 static void writeAttr(XmlSerializer out, String name, boolean value) throws IOException {
835 if (value) {
836 writeAttr(out, name, "1");
837 }
838 }
839
Makoto Onuki41066a62016-03-09 16:18:44 -0800840 static void writeAttr(XmlSerializer out, String name, ComponentName comp) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800841 if (comp == null) return;
842 writeAttr(out, name, comp.flattenToString());
843 }
844
Makoto Onuki41066a62016-03-09 16:18:44 -0800845 static void writeAttr(XmlSerializer out, String name, Intent intent) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800846 if (intent == null) return;
847
848 writeAttr(out, name, intent.toUri(/* flags =*/ 0));
849 }
850
851 @VisibleForTesting
852 void saveBaseStateLocked() {
853 final AtomicFile file = getBaseStateFile();
854 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700855 Slog.d(TAG, "Saving to " + file.getBaseFile());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800856 }
857
858 FileOutputStream outs = null;
859 try {
860 outs = file.startWrite();
861
862 // Write to XML
863 XmlSerializer out = new FastXmlSerializer();
864 out.setOutput(outs, StandardCharsets.UTF_8.name());
865 out.startDocument(null, true);
866 out.startTag(null, TAG_ROOT);
867
868 // Body.
869 writeTagValue(out, TAG_LAST_RESET_TIME, mRawLastResetTime);
870
871 // Epilogue.
872 out.endTag(null, TAG_ROOT);
873 out.endDocument();
874
875 // Close.
876 file.finishWrite(outs);
877 } catch (IOException e) {
878 Slog.e(TAG, "Failed to write to file " + file.getBaseFile(), e);
879 file.failWrite(outs);
880 }
881 }
882
883 private void loadBaseStateLocked() {
884 mRawLastResetTime = 0;
885
886 final AtomicFile file = getBaseStateFile();
887 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700888 Slog.d(TAG, "Loading from " + file.getBaseFile());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800889 }
890 try (FileInputStream in = file.openRead()) {
891 XmlPullParser parser = Xml.newPullParser();
892 parser.setInput(in, StandardCharsets.UTF_8.name());
893
894 int type;
895 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
896 if (type != XmlPullParser.START_TAG) {
897 continue;
898 }
899 final int depth = parser.getDepth();
900 // Check the root tag
901 final String tag = parser.getName();
902 if (depth == 1) {
903 if (!TAG_ROOT.equals(tag)) {
904 Slog.e(TAG, "Invalid root tag: " + tag);
905 return;
906 }
907 continue;
908 }
909 // Assume depth == 2
910 switch (tag) {
911 case TAG_LAST_RESET_TIME:
912 mRawLastResetTime = parseLongAttribute(parser, ATTR_VALUE);
913 break;
914 default:
915 Slog.e(TAG, "Invalid tag: " + tag);
916 break;
917 }
918 }
919 } catch (FileNotFoundException e) {
920 // Use the default
Makoto Onukib08790c2016-06-23 14:05:46 -0700921 } catch (IOException | XmlPullParserException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800922 Slog.e(TAG, "Failed to read file " + file.getBaseFile(), e);
923
924 mRawLastResetTime = 0;
925 }
926 // Adjust the last reset time.
927 getLastResetTimeLocked();
928 }
929
Makoto Onuki0eed4412016-07-21 11:21:59 -0700930 @VisibleForTesting
931 final File getUserFile(@UserIdInt int userId) {
932 return new File(injectUserDataPath(userId), FILENAME_USER_PACKAGES);
933 }
934
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800935 private void saveUserLocked(@UserIdInt int userId) {
Makoto Onuki0eed4412016-07-21 11:21:59 -0700936 final File path = getUserFile(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800937 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700938 Slog.d(TAG, "Saving to " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800939 }
Makoto Onuki475c3652017-05-08 14:29:03 -0700940
941 mShortcutBitmapSaver.waitForAllSavesLocked();
942
Makoto Onuki0eed4412016-07-21 11:21:59 -0700943 path.getParentFile().mkdirs();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800944 final AtomicFile file = new AtomicFile(path);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700945 FileOutputStream os = null;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800946 try {
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700947 os = file.startWrite();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800948
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700949 saveUserInternalLocked(userId, os, /* forBackup= */ false);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800950
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700951 file.finishWrite(os);
Makoto Onuki1e173232016-08-10 10:47:13 -0700952
953 // Remove all dangling bitmap files.
954 cleanupDanglingBitmapDirectoriesLocked(userId);
Makoto Onukib08790c2016-06-23 14:05:46 -0700955 } catch (XmlPullParserException | IOException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800956 Slog.e(TAG, "Failed to write to file " + file.getBaseFile(), e);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700957 file.failWrite(os);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800958 }
959 }
960
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700961 private void saveUserInternalLocked(@UserIdInt int userId, OutputStream os,
962 boolean forBackup) throws IOException, XmlPullParserException {
963
964 final BufferedOutputStream bos = new BufferedOutputStream(os);
965
966 // Write to XML
967 XmlSerializer out = new FastXmlSerializer();
968 out.setOutput(bos, StandardCharsets.UTF_8.name());
969 out.startDocument(null, true);
970
Makoto Onukic51b2872016-05-04 15:24:50 -0700971 getUserShortcutsLocked(userId).saveToXml(out, forBackup);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700972
973 out.endDocument();
974
975 bos.flush();
976 os.flush();
977 }
978
Makoto Onuki41066a62016-03-09 16:18:44 -0800979 static IOException throwForInvalidTag(int depth, String tag) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800980 throw new IOException(String.format("Invalid tag '%s' found at depth %d", tag, depth));
981 }
982
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700983 static void warnForInvalidTag(int depth, String tag) throws IOException {
984 Slog.w(TAG, String.format("Invalid tag '%s' found at depth %d", tag, depth));
985 }
986
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800987 @Nullable
Makoto Onuki31459242016-03-22 11:12:18 -0700988 private ShortcutUser loadUserLocked(@UserIdInt int userId) {
Makoto Onuki0eed4412016-07-21 11:21:59 -0700989 final File path = getUserFile(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800990 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700991 Slog.d(TAG, "Loading from " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800992 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800993 final AtomicFile file = new AtomicFile(path);
994
995 final FileInputStream in;
996 try {
997 in = file.openRead();
998 } catch (FileNotFoundException e) {
999 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001000 Slog.d(TAG, "Not found " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001001 }
1002 return null;
1003 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001004 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07001005 final ShortcutUser ret = loadUserInternal(userId, in, /* forBackup= */ false);
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001006 return ret;
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07001007 } catch (IOException | XmlPullParserException | InvalidFileFormatException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001008 Slog.e(TAG, "Failed to read file " + file.getBaseFile(), e);
1009 return null;
1010 } finally {
1011 IoUtils.closeQuietly(in);
1012 }
1013 }
1014
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001015 private ShortcutUser loadUserInternal(@UserIdInt int userId, InputStream is,
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07001016 boolean fromBackup) throws XmlPullParserException, IOException,
1017 InvalidFileFormatException {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001018
1019 final BufferedInputStream bis = new BufferedInputStream(is);
1020
1021 ShortcutUser ret = null;
1022 XmlPullParser parser = Xml.newPullParser();
1023 parser.setInput(bis, StandardCharsets.UTF_8.name());
1024
1025 int type;
1026 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1027 if (type != XmlPullParser.START_TAG) {
1028 continue;
1029 }
1030 final int depth = parser.getDepth();
1031
1032 final String tag = parser.getName();
1033 if (DEBUG_LOAD) {
1034 Slog.d(TAG, String.format("depth=%d type=%d name=%s",
1035 depth, type, tag));
1036 }
1037 if ((depth == 1) && ShortcutUser.TAG_ROOT.equals(tag)) {
1038 ret = ShortcutUser.loadFromXml(this, parser, userId, fromBackup);
1039 continue;
1040 }
1041 throwForInvalidTag(depth, tag);
1042 }
1043 return ret;
1044 }
1045
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001046 private void scheduleSaveBaseState() {
Makoto Onuki0acbb142016-03-22 17:02:57 -07001047 scheduleSaveInner(UserHandle.USER_NULL); // Special case -- use USER_NULL for base state.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001048 }
1049
Makoto Onuki2d5b4652016-03-11 16:09:54 -08001050 void scheduleSaveUser(@UserIdInt int userId) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07001051 scheduleSaveInner(userId);
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001052 }
1053
1054 // In order to re-schedule, we need to reuse the same instance, so keep it in final.
1055 private final Runnable mSaveDirtyInfoRunner = this::saveDirtyInfo;
1056
Makoto Onuki0acbb142016-03-22 17:02:57 -07001057 private void scheduleSaveInner(@UserIdInt int userId) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001058 if (DEBUG) {
1059 Slog.d(TAG, "Scheduling to save for " + userId);
1060 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001061 synchronized (mLock) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001062 if (!mDirtyUserIds.contains(userId)) {
1063 mDirtyUserIds.add(userId);
1064 }
1065 }
1066 // If already scheduled, remove that and re-schedule in N seconds.
1067 mHandler.removeCallbacks(mSaveDirtyInfoRunner);
1068 mHandler.postDelayed(mSaveDirtyInfoRunner, mSaveDelayMillis);
1069 }
1070
1071 @VisibleForTesting
1072 void saveDirtyInfo() {
1073 if (DEBUG) {
1074 Slog.d(TAG, "saveDirtyInfo");
1075 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001076 try {
1077 synchronized (mLock) {
1078 for (int i = mDirtyUserIds.size() - 1; i >= 0; i--) {
1079 final int userId = mDirtyUserIds.get(i);
1080 if (userId == UserHandle.USER_NULL) { // USER_NULL for base state.
1081 saveBaseStateLocked();
1082 } else {
1083 saveUserLocked(userId);
1084 }
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001085 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001086 mDirtyUserIds.clear();
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001087 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001088 } catch (Exception e) {
1089 wtf("Exception in saveDirtyInfo", e);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001090 }
1091 }
1092
1093 /** Return the last reset time. */
1094 long getLastResetTimeLocked() {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001095 updateTimesLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001096 return mRawLastResetTime;
1097 }
1098
1099 /** Return the next reset time. */
1100 long getNextResetTimeLocked() {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001101 updateTimesLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001102 return mRawLastResetTime + mResetInterval;
1103 }
1104
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001105 static boolean isClockValid(long time) {
1106 return time >= 1420070400; // Thu, 01 Jan 2015 00:00:00 GMT
1107 }
1108
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001109 /**
1110 * Update the last reset time.
1111 */
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001112 private void updateTimesLocked() {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001113
1114 final long now = injectCurrentTimeMillis();
1115
1116 final long prevLastResetTime = mRawLastResetTime;
1117
1118 if (mRawLastResetTime == 0) { // first launch.
1119 // TODO Randomize??
1120 mRawLastResetTime = now;
1121 } else if (now < mRawLastResetTime) {
1122 // Clock rewound.
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001123 if (isClockValid(now)) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001124 Slog.w(TAG, "Clock rewound");
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001125 // TODO Randomize??
1126 mRawLastResetTime = now;
1127 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001128 } else {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001129 if ((mRawLastResetTime + mResetInterval) <= now) {
1130 final long offset = mRawLastResetTime % mResetInterval;
1131 mRawLastResetTime = ((now / mResetInterval) * mResetInterval) + offset;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001132 }
1133 }
1134 if (prevLastResetTime != mRawLastResetTime) {
1135 scheduleSaveBaseState();
1136 }
1137 }
1138
Makoto Onuki1e173232016-08-10 10:47:13 -07001139 // Requires mLock held, but "Locked" prefix would look weired so we just say "L".
Makoto Onuki02f338e2016-07-29 09:40:40 -07001140 protected boolean isUserUnlockedL(@UserIdInt int userId) {
Makoto Onuki1e173232016-08-10 10:47:13 -07001141 // First, check the local copy.
1142 if (mUnlockedUsers.get(userId)) {
1143 return true;
1144 }
1145 // If the local copy says the user is locked, check with AM for the actual state, since
1146 // the user might just have been unlocked.
1147 // Note we just don't use isUserUnlockingOrUnlocked() here, because it'll return false
1148 // when the user is STOPPING, which we still want to consider as "unlocked".
1149 final long token = injectClearCallingIdentity();
1150 try {
1151 return mUserManager.isUserUnlockingOrUnlocked(userId);
1152 } finally {
1153 injectRestoreCallingIdentity(token);
1154 }
Makoto Onuki9c850012016-07-26 15:50:50 -07001155 }
1156
Makoto Onuki02f338e2016-07-29 09:40:40 -07001157 // Requires mLock held, but "Locked" prefix would look weired so we jsut say "L".
1158 void throwIfUserLockedL(@UserIdInt int userId) {
1159 if (!isUserUnlockedL(userId)) {
Makoto Onuki9c850012016-07-26 15:50:50 -07001160 throw new IllegalStateException("User " + userId + " is locked or not running");
1161 }
1162 }
1163
Makoto Onukicdc78f72016-03-21 15:47:52 -07001164 @GuardedBy("mLock")
1165 @NonNull
Makoto Onuki2e210c42016-03-30 08:30:36 -07001166 private boolean isUserLoadedLocked(@UserIdInt int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07001167 return mUsers.get(userId) != null;
1168 }
1169
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001170 /** Return the per-user state. */
1171 @GuardedBy("mLock")
1172 @NonNull
Makoto Onuki31459242016-03-22 11:12:18 -07001173 ShortcutUser getUserShortcutsLocked(@UserIdInt int userId) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001174 if (!isUserUnlockedL(userId)) {
Makoto Onuki9c850012016-07-26 15:50:50 -07001175 wtf("User still locked");
Makoto Onuki9c850012016-07-26 15:50:50 -07001176 }
1177
Makoto Onuki31459242016-03-22 11:12:18 -07001178 ShortcutUser userPackages = mUsers.get(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001179 if (userPackages == null) {
1180 userPackages = loadUserLocked(userId);
1181 if (userPackages == null) {
Makoto Onukic51b2872016-05-04 15:24:50 -07001182 userPackages = new ShortcutUser(this, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001183 }
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08001184 mUsers.put(userId, userPackages);
Makoto Onuki085a05c2016-08-19 11:39:29 -07001185
1186 // Also when a user's data is first accessed, scan all packages.
1187 checkPackageChanges(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001188 }
1189 return userPackages;
1190 }
1191
Makoto Onuki2e210c42016-03-30 08:30:36 -07001192 void forEachLoadedUserLocked(@NonNull Consumer<ShortcutUser> c) {
1193 for (int i = mUsers.size() - 1; i >= 0; i--) {
1194 c.accept(mUsers.valueAt(i));
1195 }
1196 }
1197
Makoto Onukic8c33292016-09-12 16:36:59 -07001198 /**
1199 * Return the per-user per-package state. If the caller is a publisher, use
1200 * {@link #getPackageShortcutsForPublisherLocked} instead.
1201 */
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001202 @GuardedBy("mLock")
1203 @NonNull
Makoto Onuki31459242016-03-22 11:12:18 -07001204 ShortcutPackage getPackageShortcutsLocked(
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001205 @NonNull String packageName, @UserIdInt int userId) {
Makoto Onukic51b2872016-05-04 15:24:50 -07001206 return getUserShortcutsLocked(userId).getPackageShortcuts(packageName);
Makoto Onukide667372016-03-15 14:29:20 -07001207 }
1208
Makoto Onukic8c33292016-09-12 16:36:59 -07001209 /** Return the per-user per-package state. Use this when the caller is a publisher. */
1210 @GuardedBy("mLock")
1211 @NonNull
1212 ShortcutPackage getPackageShortcutsForPublisherLocked(
1213 @NonNull String packageName, @UserIdInt int userId) {
1214 final ShortcutPackage ret = getUserShortcutsLocked(userId).getPackageShortcuts(packageName);
1215 ret.getUser().onCalledByPublisher(packageName);
1216 return ret;
1217 }
1218
Makoto Onukide667372016-03-15 14:29:20 -07001219 @GuardedBy("mLock")
1220 @NonNull
Makoto Onuki2e210c42016-03-30 08:30:36 -07001221 ShortcutLauncher getLauncherShortcutsLocked(
1222 @NonNull String packageName, @UserIdInt int ownerUserId,
1223 @UserIdInt int launcherUserId) {
1224 return getUserShortcutsLocked(ownerUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07001225 .getLauncherShortcuts(packageName, launcherUserId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001226 }
1227
1228 // === Caller validation ===
1229
Makoto Onuki475c3652017-05-08 14:29:03 -07001230 void removeIconLocked(ShortcutInfo shortcut) {
1231 mShortcutBitmapSaver.removeIcon(shortcut);
Makoto Onuki55046222016-03-08 10:49:47 -08001232 }
1233
Makoto Onuki0033b2a2016-04-14 17:19:16 -07001234 public void cleanupBitmapsForPackage(@UserIdInt int userId, String packageName) {
1235 final File packagePath = new File(getUserBitmapFilePath(userId), packageName);
1236 if (!packagePath.isDirectory()) {
1237 return;
1238 }
1239 if (!(FileUtils.deleteContents(packagePath) && packagePath.delete())) {
1240 Slog.w(TAG, "Unable to remove directory " + packagePath);
1241 }
1242 }
1243
Makoto Onuki475c3652017-05-08 14:29:03 -07001244 /**
1245 * Remove dangling bitmap files for a user.
1246 *
1247 * Note this method must be called with the lock held after calling
1248 * {@link ShortcutBitmapSaver#waitForAllSavesLocked()} to make sure there's no pending bitmap
1249 * saves are going on.
1250 */
Makoto Onuki1e173232016-08-10 10:47:13 -07001251 private void cleanupDanglingBitmapDirectoriesLocked(@UserIdInt int userId) {
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001252 if (DEBUG) {
1253 Slog.d(TAG, "cleanupDanglingBitmaps: userId=" + userId);
1254 }
1255 final long start = injectElapsedRealtime();
1256
Makoto Onuki1e173232016-08-10 10:47:13 -07001257 final ShortcutUser user = getUserShortcutsLocked(userId);
1258
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001259 final File bitmapDir = getUserBitmapFilePath(userId);
1260 final File[] children = bitmapDir.listFiles();
1261 if (children == null) {
1262 return;
1263 }
1264 for (File child : children) {
1265 if (!child.isDirectory()) {
1266 continue;
1267 }
1268 final String packageName = child.getName();
1269 if (DEBUG) {
1270 Slog.d(TAG, "cleanupDanglingBitmaps: Found directory=" + packageName);
1271 }
1272 if (!user.hasPackage(packageName)) {
1273 if (DEBUG) {
1274 Slog.d(TAG, "Removing dangling bitmap directory: " + packageName);
1275 }
1276 cleanupBitmapsForPackage(userId, packageName);
1277 } else {
1278 cleanupDanglingBitmapFilesLocked(userId, user, packageName, child);
1279 }
1280 }
1281 logDurationStat(Stats.CLEANUP_DANGLING_BITMAPS, start);
1282 }
1283
Makoto Onuki475c3652017-05-08 14:29:03 -07001284 /**
1285 * Remove dangling bitmap files for a package.
1286 *
1287 * Note this method must be called with the lock held after calling
1288 * {@link ShortcutBitmapSaver#waitForAllSavesLocked()} to make sure there's no pending bitmap
1289 * saves are going on.
1290 */
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001291 private void cleanupDanglingBitmapFilesLocked(@UserIdInt int userId, @NonNull ShortcutUser user,
1292 @NonNull String packageName, @NonNull File path) {
1293 final ArraySet<String> usedFiles =
Makoto Onukic51b2872016-05-04 15:24:50 -07001294 user.getPackageShortcuts(packageName).getUsedBitmapFiles();
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001295
1296 for (File child : path.listFiles()) {
1297 if (!child.isFile()) {
1298 continue;
1299 }
1300 final String name = child.getName();
1301 if (!usedFiles.contains(name)) {
1302 if (DEBUG) {
1303 Slog.d(TAG, "Removing dangling bitmap file: " + child.getAbsolutePath());
1304 }
1305 child.delete();
1306 }
1307 }
1308 }
1309
Makoto Onuki55046222016-03-08 10:49:47 -08001310 @VisibleForTesting
1311 static class FileOutputStreamWithPath extends FileOutputStream {
1312 private final File mFile;
1313
1314 public FileOutputStreamWithPath(File file) throws FileNotFoundException {
1315 super(file);
1316 mFile = file;
1317 }
1318
1319 public File getFile() {
1320 return mFile;
1321 }
1322 }
1323
1324 /**
1325 * Build the cached bitmap filename for a shortcut icon.
1326 *
1327 * The filename will be based on the ID, except certain characters will be escaped.
1328 */
Makoto Onuki55046222016-03-08 10:49:47 -08001329 FileOutputStreamWithPath openIconFileForWrite(@UserIdInt int userId, ShortcutInfo shortcut)
1330 throws IOException {
1331 final File packagePath = new File(getUserBitmapFilePath(userId),
Makoto Onuki22fcc682016-05-17 14:52:19 -07001332 shortcut.getPackage());
Makoto Onuki55046222016-03-08 10:49:47 -08001333 if (!packagePath.isDirectory()) {
1334 packagePath.mkdirs();
1335 if (!packagePath.isDirectory()) {
1336 throw new IOException("Unable to create directory " + packagePath);
1337 }
1338 SELinux.restorecon(packagePath);
1339 }
1340
1341 final String baseName = String.valueOf(injectCurrentTimeMillis());
Makoto Onukib08790c2016-06-23 14:05:46 -07001342 for (int suffix = 0; ; suffix++) {
Makoto Onuki55046222016-03-08 10:49:47 -08001343 final String filename = (suffix == 0 ? baseName : baseName + "_" + suffix) + ".png";
1344 final File file = new File(packagePath, filename);
1345 if (!file.exists()) {
1346 if (DEBUG) {
1347 Slog.d(TAG, "Saving icon to " + file.getAbsolutePath());
1348 }
1349 return new FileOutputStreamWithPath(file);
1350 }
1351 }
1352 }
1353
Makoto Onuki475c3652017-05-08 14:29:03 -07001354 void saveIconAndFixUpShortcutLocked(ShortcutInfo shortcut) {
Makoto Onuki55046222016-03-08 10:49:47 -08001355 if (shortcut.hasIconFile() || shortcut.hasIconResource()) {
1356 return;
1357 }
1358
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001359 final long token = injectClearCallingIdentity();
Makoto Onuki55046222016-03-08 10:49:47 -08001360 try {
1361 // Clear icon info on the shortcut.
Makoto Onuki475c3652017-05-08 14:29:03 -07001362 removeIconLocked(shortcut);
Makoto Onuki55046222016-03-08 10:49:47 -08001363
1364 final Icon icon = shortcut.getIcon();
1365 if (icon == null) {
1366 return; // has no icon
1367 }
Hyunyoung Song47037462017-05-08 16:51:43 -07001368 int maxIconDimension = mMaxIconDimension;
Makoto Onukiabe84422016-04-07 09:41:19 -07001369 Bitmap bitmap;
Makoto Onuki55046222016-03-08 10:49:47 -08001370 try {
1371 switch (icon.getType()) {
1372 case Icon.TYPE_RESOURCE: {
1373 injectValidateIconResPackage(shortcut, icon);
1374
1375 shortcut.setIconResourceId(icon.getResId());
1376 shortcut.addFlags(ShortcutInfo.FLAG_HAS_ICON_RES);
1377 return;
1378 }
Hyunyoung Songf281e7a2017-02-13 10:57:42 -08001379 case Icon.TYPE_BITMAP:
Makoto Onukiabe84422016-04-07 09:41:19 -07001380 bitmap = icon.getBitmap(); // Don't recycle in this case.
Makoto Onuki55046222016-03-08 10:49:47 -08001381 break;
Hyunyoung Song47037462017-05-08 16:51:43 -07001382 case Icon.TYPE_ADAPTIVE_BITMAP: {
1383 bitmap = icon.getBitmap(); // Don't recycle in this case.
1384 maxIconDimension *= (1 + 2 * AdaptiveIconDrawable.getExtraInsetFraction());
Hyunyoung Song8947f592017-05-15 10:12:11 -07001385 break;
Makoto Onuki55046222016-03-08 10:49:47 -08001386 }
Makoto Onuki55046222016-03-08 10:49:47 -08001387 default:
1388 // This shouldn't happen because we've already validated the icon, but
1389 // just in case.
1390 throw ShortcutInfo.getInvalidIconException();
1391 }
Makoto Onuki475c3652017-05-08 14:29:03 -07001392 mShortcutBitmapSaver.saveBitmapLocked(shortcut,
Hyunyoung Song47037462017-05-08 16:51:43 -07001393 maxIconDimension, mIconPersistFormat, mIconPersistQuality);
Makoto Onuki55046222016-03-08 10:49:47 -08001394 } finally {
Makoto Onuki55046222016-03-08 10:49:47 -08001395 // Once saved, we won't use the original icon information, so null it out.
1396 shortcut.clearIcon();
1397 }
1398 } finally {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001399 injectRestoreCallingIdentity(token);
Makoto Onuki55046222016-03-08 10:49:47 -08001400 }
1401 }
1402
1403 // Unfortunately we can't do this check in unit tests because we fake creator package names,
1404 // so override in unit tests.
1405 // TODO CTS this case.
1406 void injectValidateIconResPackage(ShortcutInfo shortcut, Icon icon) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07001407 if (!shortcut.getPackage().equals(icon.getResPackage())) {
Makoto Onuki55046222016-03-08 10:49:47 -08001408 throw new IllegalArgumentException(
1409 "Icon resource must reside in shortcut owner package");
1410 }
1411 }
1412
Makoto Onuki55046222016-03-08 10:49:47 -08001413 static Bitmap shrinkBitmap(Bitmap in, int maxSize) {
1414 // Original width/height.
1415 final int ow = in.getWidth();
1416 final int oh = in.getHeight();
1417 if ((ow <= maxSize) && (oh <= maxSize)) {
1418 if (DEBUG) {
1419 Slog.d(TAG, String.format("Icon size %dx%d, no need to shrink", ow, oh));
1420 }
1421 return in;
1422 }
1423 final int longerDimension = Math.max(ow, oh);
1424
1425 // New width and height.
1426 final int nw = ow * maxSize / longerDimension;
1427 final int nh = oh * maxSize / longerDimension;
1428 if (DEBUG) {
1429 Slog.d(TAG, String.format("Icon size %dx%d, shrinking to %dx%d",
1430 ow, oh, nw, nh));
1431 }
1432
1433 final Bitmap scaledBitmap = Bitmap.createBitmap(nw, nh, Bitmap.Config.ARGB_8888);
1434 final Canvas c = new Canvas(scaledBitmap);
1435
1436 final RectF dst = new RectF(0, 0, nw, nh);
1437
1438 c.drawBitmap(in, /*src=*/ null, dst, /* paint =*/ null);
1439
Makoto Onuki55046222016-03-08 10:49:47 -08001440 return scaledBitmap;
1441 }
1442
Makoto Onuki157b1622016-06-02 16:13:10 -07001443 /**
1444 * For a shortcut, update all resource names from resource IDs, and also update all
1445 * resource-based strings.
1446 */
1447 void fixUpShortcutResourceNamesAndValues(ShortcutInfo si) {
1448 final Resources publisherRes = injectGetResourcesForApplicationAsUser(
1449 si.getPackage(), si.getUserId());
1450 if (publisherRes != null) {
1451 final long start = injectElapsedRealtime();
1452 try {
1453 si.lookupAndFillInResourceNames(publisherRes);
1454 } finally {
1455 logDurationStat(Stats.RESOURCE_NAME_LOOKUP, start);
1456 }
1457 si.resolveResourceStrings(publisherRes);
1458 }
1459 }
1460
Makoto Onuki55046222016-03-08 10:49:47 -08001461 // === Caller validation ===
1462
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001463 private boolean isCallerSystem() {
1464 final int callingUid = injectBinderCallingUid();
Makoto Onukib08790c2016-06-23 14:05:46 -07001465 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001466 }
1467
1468 private boolean isCallerShell() {
1469 final int callingUid = injectBinderCallingUid();
1470 return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
1471 }
1472
1473 private void enforceSystemOrShell() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001474 if (!(isCallerSystem() || isCallerShell())) {
1475 throw new SecurityException("Caller must be system or shell");
1476 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001477 }
1478
1479 private void enforceShell() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001480 if (!isCallerShell()) {
1481 throw new SecurityException("Caller must be shell");
1482 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001483 }
1484
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001485 private void enforceSystem() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001486 if (!isCallerSystem()) {
1487 throw new SecurityException("Caller must be system");
1488 }
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001489 }
1490
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001491 private void enforceResetThrottlingPermission() {
1492 if (isCallerSystem()) {
1493 return;
1494 }
Makoto Onuki76269922016-07-15 14:58:54 -07001495 enforceCallingOrSelfPermission(
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001496 android.Manifest.permission.RESET_SHORTCUT_MANAGER_THROTTLING, null);
1497 }
1498
Makoto Onuki76269922016-07-15 14:58:54 -07001499 private void enforceCallingOrSelfPermission(
1500 @NonNull String permission, @Nullable String message) {
1501 if (isCallerSystem()) {
1502 return;
1503 }
1504 injectEnforceCallingPermission(permission, message);
1505 }
1506
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001507 /**
1508 * Somehow overriding ServiceContext.enforceCallingPermission() in the unit tests would confuse
1509 * mockito. So instead we extracted it here and override it in the tests.
1510 */
1511 @VisibleForTesting
1512 void injectEnforceCallingPermission(
1513 @NonNull String permission, @Nullable String message) {
1514 mContext.enforceCallingPermission(permission, message);
1515 }
1516
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001517 private void verifyCaller(@NonNull String packageName, @UserIdInt int userId) {
1518 Preconditions.checkStringNotEmpty(packageName, "packageName");
1519
1520 if (isCallerSystem()) {
1521 return; // no check
1522 }
1523
1524 final int callingUid = injectBinderCallingUid();
1525
1526 // Otherwise, make sure the arguments are valid.
1527 if (UserHandle.getUserId(callingUid) != userId) {
1528 throw new SecurityException("Invalid user-ID");
1529 }
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08001530 if (injectGetPackageUid(packageName, userId) != callingUid) {
1531 throw new SecurityException("Calling package name mismatch");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001532 }
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08001533 Preconditions.checkState(!isEphemeralApp(packageName, userId),
1534 "Ephemeral apps can't use ShortcutManager");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001535 }
1536
Makoto Onuki157b1622016-06-02 16:13:10 -07001537 // Overridden in unit tests to execute r synchronously.
1538 void injectPostToHandler(Runnable r) {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001539 mHandler.post(r);
1540 }
1541
Makoto Onuki085a05c2016-08-19 11:39:29 -07001542 void injectRunOnNewThread(Runnable r) {
1543 new Thread(r).start();
1544 }
1545
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001546 /**
Makoto Onuki7001a612016-05-27 13:24:28 -07001547 * @throws IllegalArgumentException if {@code numShortcuts} is bigger than
Makoto Onukib08790c2016-06-23 14:05:46 -07001548 * {@link #getMaxActivityShortcuts()}.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001549 */
Makoto Onuki7001a612016-05-27 13:24:28 -07001550 void enforceMaxActivityShortcuts(int numShortcuts) {
Makoto Onukib5a012f2016-06-21 11:13:53 -07001551 if (numShortcuts > mMaxShortcuts) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001552 throw new IllegalArgumentException("Max number of dynamic shortcuts exceeded");
1553 }
1554 }
1555
1556 /**
Makoto Onuki7001a612016-05-27 13:24:28 -07001557 * Return the max number of dynamic + manifest shortcuts for each launcher icon.
1558 */
1559 int getMaxActivityShortcuts() {
Makoto Onukib5a012f2016-06-21 11:13:53 -07001560 return mMaxShortcuts;
Makoto Onuki7001a612016-05-27 13:24:28 -07001561 }
1562
1563 /**
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001564 * - Sends a notification to LauncherApps
1565 * - Write to file
1566 */
Makoto Onuki39686e82016-04-13 18:03:00 -07001567 void packageShortcutsChanged(@NonNull String packageName, @UserIdInt int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001568 notifyListeners(packageName, userId);
1569 scheduleSaveUser(userId);
1570 }
1571
1572 private void notifyListeners(@NonNull String packageName, @UserIdInt int userId) {
Makoto Onuki82fb2eb2017-03-31 16:58:26 -07001573 if (DEBUG) {
1574 Slog.d(TAG, String.format(
1575 "Shortcut changes: package=%s, user=%d", packageName, userId));
1576 }
Makoto Onuki157b1622016-06-02 16:13:10 -07001577 injectPostToHandler(() -> {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001578 try {
1579 final ArrayList<ShortcutChangeListener> copy;
1580 synchronized (mLock) {
1581 if (!isUserUnlockedL(userId)) {
1582 return;
1583 }
1584
1585 copy = new ArrayList<>(mListeners);
1586 }
1587 // Note onShortcutChanged() needs to be called with the system service permissions.
1588 for (int i = copy.size() - 1; i >= 0; i--) {
1589 copy.get(i).onShortcutChanged(packageName, userId);
1590 }
1591 } catch (Exception ignore) {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001592 }
1593 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001594 }
1595
1596 /**
1597 * Clean up / validate an incoming shortcut.
1598 * - Make sure all mandatory fields are set.
1599 * - Make sure the intent's extras are persistable, and them to set
Makoto Onuki0eed4412016-07-21 11:21:59 -07001600 * {@link ShortcutInfo#mIntentPersistableExtrases}. Also clear its extras.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001601 * - Clear flags.
1602 */
Makoto Onuki2d895c32016-12-02 15:48:40 -08001603 private void fixUpIncomingShortcutInfo(@NonNull ShortcutInfo shortcut, boolean forUpdate,
1604 boolean forPinRequest) {
Makoto Onukibf563b62017-05-04 10:25:30 -07001605 if (shortcut.isReturnedByServer()) {
1606 Log.w(TAG,
1607 "Re-publishing ShortcutInfo returned by server is not supported."
1608 + " Some information such as icon may lost from shortcut.");
1609 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001610 Preconditions.checkNotNull(shortcut, "Null shortcut detected");
Makoto Onuki255461f2017-01-10 11:47:25 -08001611 if (shortcut.getActivity() != null) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001612 Preconditions.checkState(
Makoto Onuki22fcc682016-05-17 14:52:19 -07001613 shortcut.getPackage().equals(shortcut.getActivity().getPackageName()),
Makoto Onukib08790c2016-06-23 14:05:46 -07001614 "Cannot publish shortcut: activity " + shortcut.getActivity() + " does not"
1615 + " belong to package " + shortcut.getPackage());
Makoto Onuki13260b6ff2016-07-13 18:03:13 -07001616 Preconditions.checkState(
1617 injectIsMainActivity(shortcut.getActivity(), shortcut.getUserId()),
1618 "Cannot publish shortcut: activity " + shortcut.getActivity() + " is not"
1619 + " main activity");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001620 }
1621
Makoto Onuki55046222016-03-08 10:49:47 -08001622 if (!forUpdate) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08001623 shortcut.enforceMandatoryFields(/* forPinned= */ forPinRequest);
1624 if (!forPinRequest) {
Makoto Onuki255461f2017-01-10 11:47:25 -08001625 Preconditions.checkState(shortcut.getActivity() != null,
1626 "Cannot publish shortcut: target activity is not set");
Makoto Onuki2d895c32016-12-02 15:48:40 -08001627 }
Makoto Onuki55046222016-03-08 10:49:47 -08001628 }
1629 if (shortcut.getIcon() != null) {
1630 ShortcutInfo.validateIcon(shortcut.getIcon());
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001631 }
1632
Makoto Onukide667372016-03-15 14:29:20 -07001633 shortcut.replaceFlags(0);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001634 }
1635
Makoto Onuki2d895c32016-12-02 15:48:40 -08001636 private void fixUpIncomingShortcutInfo(@NonNull ShortcutInfo shortcut, boolean forUpdate) {
1637 fixUpIncomingShortcutInfo(shortcut, forUpdate, /*forPinRequest=*/ false);
1638 }
1639
1640 public void validateShortcutForPinRequest(@NonNull ShortcutInfo shortcut) {
1641 fixUpIncomingShortcutInfo(shortcut, /* forUpdate= */ false, /*forPinRequest=*/ true);
1642 }
1643
Makoto Onukib08790c2016-06-23 14:05:46 -07001644 /**
1645 * When a shortcut has no target activity, set the default one from the package.
1646 */
1647 private void fillInDefaultActivity(List<ShortcutInfo> shortcuts) {
Makoto Onukib08790c2016-06-23 14:05:46 -07001648 ComponentName defaultActivity = null;
1649 for (int i = shortcuts.size() - 1; i >= 0; i--) {
1650 final ShortcutInfo si = shortcuts.get(i);
1651 if (si.getActivity() == null) {
1652 if (defaultActivity == null) {
1653 defaultActivity = injectGetDefaultMainActivity(
1654 si.getPackage(), si.getUserId());
1655 Preconditions.checkState(defaultActivity != null,
1656 "Launcher activity not found for package " + si.getPackage());
1657 }
1658 si.setActivity(defaultActivity);
1659 }
1660 }
1661 }
1662
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001663 private void assignImplicitRanks(List<ShortcutInfo> shortcuts) {
1664 for (int i = shortcuts.size() - 1; i >= 0; i--) {
1665 shortcuts.get(i).setImplicitRank(i);
1666 }
1667 }
1668
Makoto Onukibf563b62017-05-04 10:25:30 -07001669 private List<ShortcutInfo> setReturnedByServer(List<ShortcutInfo> shortcuts) {
1670 for (int i = shortcuts.size() - 1; i >= 0; i--) {
1671 shortcuts.get(i).setReturnedByServer();
1672 }
1673 return shortcuts;
1674 }
1675
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001676 // === APIs ===
1677
1678 @Override
1679 public boolean setDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1680 @UserIdInt int userId) {
1681 verifyCaller(packageName, userId);
1682
1683 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
1684 final int size = newShortcuts.size();
1685
1686 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001687 throwIfUserLockedL(userId);
1688
Makoto Onukic8c33292016-09-12 16:36:59 -07001689 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001690
Makoto Onuki22fcc682016-05-17 14:52:19 -07001691 ps.ensureImmutableShortcutsNotIncluded(newShortcuts);
1692
Makoto Onukib08790c2016-06-23 14:05:46 -07001693 fillInDefaultActivity(newShortcuts);
1694
Makoto Onuki7001a612016-05-27 13:24:28 -07001695 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_SET);
1696
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001697 // Throttling.
Makoto Onukic51b2872016-05-04 15:24:50 -07001698 if (!ps.tryApiCall()) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001699 return false;
1700 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001701
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001702 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1703 ps.clearAllImplicitRanks();
1704 assignImplicitRanks(newShortcuts);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001705
Makoto Onukidf6da042016-06-16 09:51:40 -07001706 for (int i = 0; i < size; i++) {
1707 fixUpIncomingShortcutInfo(newShortcuts.get(i), /* forUpdate= */ false);
1708 }
1709
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001710 // First, remove all un-pinned; dynamic shortcuts
Makoto Onukic51b2872016-05-04 15:24:50 -07001711 ps.deleteAllDynamicShortcuts();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001712
1713 // Then, add/update all. We need to make sure to take over "pinned" flag.
1714 for (int i = 0; i < size; i++) {
1715 final ShortcutInfo newShortcut = newShortcuts.get(i);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001716 ps.addOrUpdateDynamicShortcut(newShortcut);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001717 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001718
1719 // Lastly, adjust the ranks.
1720 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001721 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001722 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001723
1724 verifyStates();
1725
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001726 return true;
1727 }
1728
1729 @Override
1730 public boolean updateShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1731 @UserIdInt int userId) {
1732 verifyCaller(packageName, userId);
1733
1734 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
Makoto Onuki55046222016-03-08 10:49:47 -08001735 final int size = newShortcuts.size();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001736
1737 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001738 throwIfUserLockedL(userId);
1739
Makoto Onukic8c33292016-09-12 16:36:59 -07001740 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001741
Makoto Onuki22fcc682016-05-17 14:52:19 -07001742 ps.ensureImmutableShortcutsNotIncluded(newShortcuts);
1743
Makoto Onukib08790c2016-06-23 14:05:46 -07001744 // For update, don't fill in the default activity. Having null activity means
1745 // "don't update the activity" here.
1746
Makoto Onuki7001a612016-05-27 13:24:28 -07001747 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_UPDATE);
1748
Makoto Onuki55046222016-03-08 10:49:47 -08001749 // Throttling.
Makoto Onukic51b2872016-05-04 15:24:50 -07001750 if (!ps.tryApiCall()) {
Makoto Onuki55046222016-03-08 10:49:47 -08001751 return false;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001752 }
1753
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001754 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1755 ps.clearAllImplicitRanks();
1756 assignImplicitRanks(newShortcuts);
1757
Makoto Onuki55046222016-03-08 10:49:47 -08001758 for (int i = 0; i < size; i++) {
1759 final ShortcutInfo source = newShortcuts.get(i);
1760 fixUpIncomingShortcutInfo(source, /* forUpdate= */ true);
1761
1762 final ShortcutInfo target = ps.findShortcutById(source.getId());
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001763 if (target == null) {
1764 continue;
1765 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07001766
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001767 if (target.isEnabled() != source.isEnabled()) {
1768 Slog.w(TAG,
1769 "ShortcutInfo.enabled cannot be changed with updateShortcuts()");
1770 }
Makoto Onuki55046222016-03-08 10:49:47 -08001771
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001772 // When updating the rank, we need to insert between existing ranks, so set
1773 // this setRankChanged, and also copy the implicit rank fo adjustRanks().
1774 if (source.hasRank()) {
1775 target.setRankChanged();
1776 target.setImplicitRank(source.getImplicitRank());
1777 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07001778
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001779 final boolean replacingIcon = (source.getIcon() != null);
1780 if (replacingIcon) {
Makoto Onuki475c3652017-05-08 14:29:03 -07001781 removeIconLocked(target);
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001782 }
Makoto Onuki55046222016-03-08 10:49:47 -08001783
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001784 // Note copyNonNullFieldsFrom() does the "updatable with?" check too.
1785 target.copyNonNullFieldsFrom(source);
1786 target.setTimestamp(injectCurrentTimeMillis());
1787
1788 if (replacingIcon) {
Makoto Onuki475c3652017-05-08 14:29:03 -07001789 saveIconAndFixUpShortcutLocked(target);
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001790 }
1791
1792 // When we're updating any resource related fields, re-extract the res names and
1793 // the values.
1794 if (replacingIcon || source.hasStringResources()) {
1795 fixUpShortcutResourceNamesAndValues(target);
Makoto Onuki55046222016-03-08 10:49:47 -08001796 }
1797 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001798
1799 // Lastly, adjust the ranks.
1800 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001801 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001802 packageShortcutsChanged(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001803
Makoto Onuki7001a612016-05-27 13:24:28 -07001804 verifyStates();
1805
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001806 return true;
1807 }
1808
1809 @Override
Makoto Onukib6d35232016-04-04 15:57:17 -07001810 public boolean addDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001811 @UserIdInt int userId) {
1812 verifyCaller(packageName, userId);
1813
Makoto Onukib6d35232016-04-04 15:57:17 -07001814 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
1815 final int size = newShortcuts.size();
1816
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001817 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001818 throwIfUserLockedL(userId);
1819
Makoto Onukic8c33292016-09-12 16:36:59 -07001820 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001821
Makoto Onuki22fcc682016-05-17 14:52:19 -07001822 ps.ensureImmutableShortcutsNotIncluded(newShortcuts);
1823
Makoto Onukib08790c2016-06-23 14:05:46 -07001824 fillInDefaultActivity(newShortcuts);
1825
Makoto Onuki7001a612016-05-27 13:24:28 -07001826 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_ADD);
1827
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001828 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1829 ps.clearAllImplicitRanks();
1830 assignImplicitRanks(newShortcuts);
1831
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001832 // Throttling.
Makoto Onukic51b2872016-05-04 15:24:50 -07001833 if (!ps.tryApiCall()) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001834 return false;
1835 }
Makoto Onukib6d35232016-04-04 15:57:17 -07001836 for (int i = 0; i < size; i++) {
1837 final ShortcutInfo newShortcut = newShortcuts.get(i);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001838
Makoto Onukib6d35232016-04-04 15:57:17 -07001839 // Validate the shortcut.
1840 fixUpIncomingShortcutInfo(newShortcut, /* forUpdate= */ false);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001841
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001842 // When ranks are changing, we need to insert between ranks, so set the
1843 // "rank changed" flag.
1844 newShortcut.setRankChanged();
1845
Makoto Onukib6d35232016-04-04 15:57:17 -07001846 // Add it.
Makoto Onuki22fcc682016-05-17 14:52:19 -07001847 ps.addOrUpdateDynamicShortcut(newShortcut);
Makoto Onukib6d35232016-04-04 15:57:17 -07001848 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001849
1850 // Lastly, adjust the ranks.
1851 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001852 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001853 packageShortcutsChanged(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001854
Makoto Onuki7001a612016-05-27 13:24:28 -07001855 verifyStates();
1856
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001857 return true;
1858 }
1859
1860 @Override
Makoto Onuki2d895c32016-12-02 15:48:40 -08001861 public boolean requestPinShortcut(String packageName, ShortcutInfo shortcut,
1862 IntentSender resultIntent, int userId) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08001863 Preconditions.checkNotNull(shortcut);
1864 Preconditions.checkArgument(shortcut.isEnabled(), "Shortcut must be enabled");
Sunny Goyal4ad6b572017-02-28 11:11:51 -08001865 return requestPinItem(packageName, userId, shortcut, null, null, resultIntent);
Sunny Goyal87a563e2017-01-01 19:42:45 -08001866 }
1867
Sunny Goyala6be88a2017-01-12 16:27:58 -08001868 @Override
1869 public Intent createShortcutResultIntent(String packageName, ShortcutInfo shortcut, int userId)
1870 throws RemoteException {
1871 Preconditions.checkNotNull(shortcut);
1872 Preconditions.checkArgument(shortcut.isEnabled(), "Shortcut must be enabled");
1873 verifyCaller(packageName, userId);
1874
1875 final Intent ret;
1876 synchronized (mLock) {
1877 throwIfUserLockedL(userId);
1878
1879 // Send request to the launcher, if supported.
1880 ret = mShortcutRequestPinProcessor.createShortcutResultIntent(shortcut, userId);
1881 }
1882
1883 verifyStates();
1884 return ret;
1885 }
1886
Sunny Goyal87a563e2017-01-01 19:42:45 -08001887 /**
1888 * Handles {@link #requestPinShortcut} and {@link ShortcutServiceInternal#requestPinAppWidget}.
1889 * After validating the caller, it passes the request to {@link #mShortcutRequestPinProcessor}.
1890 * Either {@param shortcut} or {@param appWidget} should be non-null.
1891 */
Sunny Goyal4ad6b572017-02-28 11:11:51 -08001892 private boolean requestPinItem(String packageName, int userId, ShortcutInfo shortcut,
1893 AppWidgetProviderInfo appWidget, Bundle extras, IntentSender resultIntent) {
Sunny Goyal87a563e2017-01-01 19:42:45 -08001894 verifyCaller(packageName, userId);
Makoto Onuki2d895c32016-12-02 15:48:40 -08001895
1896 final boolean ret;
1897 synchronized (mLock) {
1898 throwIfUserLockedL(userId);
1899
Makoto Onukia01f4f02016-12-15 15:58:41 -08001900 Preconditions.checkState(isUidForegroundLocked(injectBinderCallingUid()),
Makoto Onuki255461f2017-01-10 11:47:25 -08001901 "Calling application must have a foreground activity or a foreground service");
Makoto Onuki2d895c32016-12-02 15:48:40 -08001902
1903 // Send request to the launcher, if supported.
Sunny Goyal4ad6b572017-02-28 11:11:51 -08001904 ret = mShortcutRequestPinProcessor.requestPinItemLocked(shortcut, appWidget, extras,
1905 userId, resultIntent);
Makoto Onuki2d895c32016-12-02 15:48:40 -08001906 }
1907
1908 verifyStates();
1909
1910 return ret;
1911 }
1912
1913 @Override
Makoto Onuki20c95f82016-05-11 16:51:01 -07001914 public void disableShortcuts(String packageName, List shortcutIds,
Makoto Onukid6880792016-06-29 13:37:43 -07001915 CharSequence disabledMessage, int disabledMessageResId, @UserIdInt int userId) {
Makoto Onuki20c95f82016-05-11 16:51:01 -07001916 verifyCaller(packageName, userId);
1917 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
1918
1919 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001920 throwIfUserLockedL(userId);
1921
Makoto Onukic8c33292016-09-12 16:36:59 -07001922 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001923
1924 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds);
1925
Makoto Onukid6880792016-06-29 13:37:43 -07001926 final String disabledMessageString =
1927 (disabledMessage == null) ? null : disabledMessage.toString();
1928
Makoto Onuki22fcc682016-05-17 14:52:19 -07001929 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
1930 ps.disableWithId(Preconditions.checkStringNotEmpty((String) shortcutIds.get(i)),
Makoto Onukid6880792016-06-29 13:37:43 -07001931 disabledMessageString, disabledMessageResId,
Makoto Onuki22fcc682016-05-17 14:52:19 -07001932 /* overrideImmutable=*/ false);
1933 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001934
1935 // We may have removed dynamic shortcuts which may have left a gap, so adjust the ranks.
1936 ps.adjustRanks();
Makoto Onuki22fcc682016-05-17 14:52:19 -07001937 }
1938 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001939
1940 verifyStates();
Makoto Onuki22fcc682016-05-17 14:52:19 -07001941 }
1942
1943 @Override
1944 public void enableShortcuts(String packageName, List shortcutIds, @UserIdInt int userId) {
1945 verifyCaller(packageName, userId);
1946 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
1947
1948 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001949 throwIfUserLockedL(userId);
1950
Makoto Onukic8c33292016-09-12 16:36:59 -07001951 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001952
1953 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds);
1954
1955 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
1956 ps.enableWithId((String) shortcutIds.get(i));
1957 }
Makoto Onuki20c95f82016-05-11 16:51:01 -07001958 }
1959 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001960
1961 verifyStates();
Makoto Onuki20c95f82016-05-11 16:51:01 -07001962 }
1963
1964 @Override
Makoto Onukib6d35232016-04-04 15:57:17 -07001965 public void removeDynamicShortcuts(String packageName, List shortcutIds,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001966 @UserIdInt int userId) {
1967 verifyCaller(packageName, userId);
Makoto Onukib6d35232016-04-04 15:57:17 -07001968 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001969
1970 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001971 throwIfUserLockedL(userId);
1972
Makoto Onukic8c33292016-09-12 16:36:59 -07001973 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001974
1975 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds);
1976
Makoto Onukib6d35232016-04-04 15:57:17 -07001977 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07001978 ps.deleteDynamicWithId(
Makoto Onukib6d35232016-04-04 15:57:17 -07001979 Preconditions.checkStringNotEmpty((String) shortcutIds.get(i)));
1980 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001981
1982 // We may have removed dynamic shortcuts which may have left a gap, so adjust the ranks.
1983 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001984 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001985 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001986
1987 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001988 }
1989
1990 @Override
Makoto Onukib6d35232016-04-04 15:57:17 -07001991 public void removeAllDynamicShortcuts(String packageName, @UserIdInt int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001992 verifyCaller(packageName, userId);
1993
1994 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001995 throwIfUserLockedL(userId);
1996
Makoto Onukic8c33292016-09-12 16:36:59 -07001997 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07001998 ps.deleteAllDynamicShortcuts();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001999 }
Makoto Onuki39686e82016-04-13 18:03:00 -07002000 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07002001
2002 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002003 }
2004
2005 @Override
2006 public ParceledListSlice<ShortcutInfo> getDynamicShortcuts(String packageName,
2007 @UserIdInt int userId) {
2008 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002009
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002010 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002011 throwIfUserLockedL(userId);
2012
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002013 return getShortcutsWithQueryLocked(
2014 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
Makoto Onuki99302b52017-03-29 12:42:26 -07002015 ShortcutInfo::isDynamic);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002016 }
2017 }
2018
2019 @Override
Makoto Onuki22fcc682016-05-17 14:52:19 -07002020 public ParceledListSlice<ShortcutInfo> getManifestShortcuts(String packageName,
2021 @UserIdInt int userId) {
2022 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002023
Makoto Onuki22fcc682016-05-17 14:52:19 -07002024 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002025 throwIfUserLockedL(userId);
2026
Makoto Onuki22fcc682016-05-17 14:52:19 -07002027 return getShortcutsWithQueryLocked(
2028 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
2029 ShortcutInfo::isManifestShortcut);
2030 }
2031 }
2032
2033 @Override
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002034 public ParceledListSlice<ShortcutInfo> getPinnedShortcuts(String packageName,
2035 @UserIdInt int userId) {
2036 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002037
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002038 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002039 throwIfUserLockedL(userId);
2040
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002041 return getShortcutsWithQueryLocked(
2042 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
2043 ShortcutInfo::isPinned);
2044 }
2045 }
2046
2047 private ParceledListSlice<ShortcutInfo> getShortcutsWithQueryLocked(@NonNull String packageName,
2048 @UserIdInt int userId, int cloneFlags, @NonNull Predicate<ShortcutInfo> query) {
2049
2050 final ArrayList<ShortcutInfo> ret = new ArrayList<>();
2051
Makoto Onukic8c33292016-09-12 16:36:59 -07002052 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002053 ps.findAll(ret, query, cloneFlags);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002054
Makoto Onukibf563b62017-05-04 10:25:30 -07002055 return new ParceledListSlice<>(setReturnedByServer(ret));
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002056 }
2057
2058 @Override
Makoto Onukid6880792016-06-29 13:37:43 -07002059 public int getMaxShortcutCountPerActivity(String packageName, @UserIdInt int userId)
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002060 throws RemoteException {
2061 verifyCaller(packageName, userId);
2062
Makoto Onukib5a012f2016-06-21 11:13:53 -07002063 return mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002064 }
2065
2066 @Override
2067 public int getRemainingCallCount(String packageName, @UserIdInt int userId) {
2068 verifyCaller(packageName, userId);
2069
2070 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002071 throwIfUserLockedL(userId);
2072
Makoto Onukic8c33292016-09-12 16:36:59 -07002073 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002074 return mMaxUpdatesPerInterval - ps.getApiCallCount();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002075 }
2076 }
2077
2078 @Override
2079 public long getRateLimitResetTime(String packageName, @UserIdInt int userId) {
2080 verifyCaller(packageName, userId);
2081
2082 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002083 throwIfUserLockedL(userId);
2084
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002085 return getNextResetTimeLocked();
2086 }
2087 }
2088
Makoto Onuki55046222016-03-08 10:49:47 -08002089 @Override
Makoto Onuki20c95f82016-05-11 16:51:01 -07002090 public int getIconMaxDimensions(String packageName, int userId) {
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002091 verifyCaller(packageName, userId);
2092
Makoto Onuki55046222016-03-08 10:49:47 -08002093 synchronized (mLock) {
2094 return mMaxIconDimension;
2095 }
2096 }
2097
Makoto Onuki20c95f82016-05-11 16:51:01 -07002098 @Override
2099 public void reportShortcutUsed(String packageName, String shortcutId, int userId) {
2100 verifyCaller(packageName, userId);
2101
Makoto Onukiac042502016-05-20 16:39:42 -07002102 Preconditions.checkNotNull(shortcutId);
2103
2104 if (DEBUG) {
2105 Slog.d(TAG, String.format("reportShortcutUsed: Shortcut %s package %s used on user %d",
2106 shortcutId, packageName, userId));
2107 }
2108
2109 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002110 throwIfUserLockedL(userId);
2111
Makoto Onukic8c33292016-09-12 16:36:59 -07002112 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002113
Makoto Onukiac042502016-05-20 16:39:42 -07002114 if (ps.findShortcutById(shortcutId) == null) {
2115 Log.w(TAG, String.format("reportShortcutUsed: package %s doesn't have shortcut %s",
2116 packageName, shortcutId));
2117 return;
2118 }
2119 }
2120
2121 final long token = injectClearCallingIdentity();
2122 try {
2123 mUsageStatsManagerInternal.reportShortcutUsage(packageName, shortcutId, userId);
2124 } finally {
2125 injectRestoreCallingIdentity(token);
2126 }
Makoto Onuki20c95f82016-05-11 16:51:01 -07002127 }
2128
Makoto Onuki2d895c32016-12-02 15:48:40 -08002129 @Override
Sunny Goyal7f7372a2017-01-24 11:53:54 -08002130 public boolean isRequestPinItemSupported(int callingUserId, int requestType) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08002131 final long token = injectClearCallingIdentity();
2132 try {
Sunny Goyal7f7372a2017-01-24 11:53:54 -08002133 return mShortcutRequestPinProcessor
2134 .isRequestPinItemSupported(callingUserId, requestType);
Makoto Onuki2d895c32016-12-02 15:48:40 -08002135 } finally {
2136 injectRestoreCallingIdentity(token);
2137 }
2138 }
2139
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002140 /**
Makoto Onukib08790c2016-06-23 14:05:46 -07002141 * Reset all throttling, for developer options and command line. Only system/shell can call
2142 * it.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002143 */
2144 @Override
2145 public void resetThrottling() {
2146 enforceSystemOrShell();
2147
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002148 resetThrottlingInner(getCallingUserId());
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002149 }
2150
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002151 void resetThrottlingInner(@UserIdInt int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002152 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002153 if (!isUserUnlockedL(userId)) {
2154 Log.w(TAG, "User " + userId + " is locked or not running");
2155 return;
2156 }
2157
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002158 getUserShortcutsLocked(userId).resetThrottling();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002159 }
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002160 scheduleSaveUser(userId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002161 Slog.i(TAG, "ShortcutManager: throttling counter reset for user " + userId);
2162 }
2163
2164 void resetAllThrottlingInner() {
2165 synchronized (mLock) {
2166 mRawLastResetTime = injectCurrentTimeMillis();
2167 }
2168 scheduleSaveBaseState();
2169 Slog.i(TAG, "ShortcutManager: throttling counter reset for all users");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002170 }
2171
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002172 @Override
2173 public void onApplicationActive(String packageName, int userId) {
2174 if (DEBUG) {
2175 Slog.d(TAG, "onApplicationActive: package=" + packageName + " userid=" + userId);
2176 }
2177 enforceResetThrottlingPermission();
Makoto Onuki02f338e2016-07-29 09:40:40 -07002178
2179 synchronized (mLock) {
2180 if (!isUserUnlockedL(userId)) {
2181 // This is called by system UI, so no need to throw. Just ignore.
2182 return;
2183 }
2184
2185 getPackageShortcutsLocked(packageName, userId)
2186 .resetRateLimitingForCommandLineNoSaving();
2187 saveUserLocked(userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002188 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002189 }
2190
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002191 // We override this method in unit tests to do a simpler check.
2192 boolean hasShortcutHostPermission(@NonNull String callingPackage, int userId) {
Makoto Onuki10305202016-07-14 18:14:08 -07002193 final long start = injectElapsedRealtime();
2194 try {
2195 return hasShortcutHostPermissionInner(callingPackage, userId);
2196 } finally {
2197 logDurationStat(Stats.LAUNCHER_PERMISSION_CHECK, start);
2198 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002199 }
2200
2201 // This method is extracted so we can directly call this method from unit tests,
2202 // even when hasShortcutPermission() is overridden.
2203 @VisibleForTesting
Makoto Onuki2d895c32016-12-02 15:48:40 -08002204 boolean hasShortcutHostPermissionInner(@NonNull String packageName, int userId) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002205 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002206 throwIfUserLockedL(userId);
2207
Makoto Onuki31459242016-03-22 11:12:18 -07002208 final ShortcutUser user = getUserShortcutsLocked(userId);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002209
Makoto Onuki2d895c32016-12-02 15:48:40 -08002210 // Always trust the cached component.
Makoto Onuki10305202016-07-14 18:14:08 -07002211 final ComponentName cached = user.getCachedLauncher();
2212 if (cached != null) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08002213 if (cached.getPackageName().equals(packageName)) {
Makoto Onuki10305202016-07-14 18:14:08 -07002214 return true;
2215 }
2216 }
2217 // If the cached one doesn't match, then go ahead
2218
Makoto Onuki2d895c32016-12-02 15:48:40 -08002219 final ComponentName detected = getDefaultLauncher(userId);
Makoto Onuki2e210c42016-03-30 08:30:36 -07002220
Makoto Onuki10305202016-07-14 18:14:08 -07002221 // Update the cache.
2222 user.setLauncher(detected);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002223 if (detected != null) {
2224 if (DEBUG) {
2225 Slog.v(TAG, "Detected launcher: " + detected);
2226 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08002227 return detected.getPackageName().equals(packageName);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002228 } else {
2229 // Default launcher not found.
2230 return false;
2231 }
2232 }
2233 }
2234
Makoto Onuki2d895c32016-12-02 15:48:40 -08002235 @Nullable
2236 ComponentName getDefaultLauncher(@UserIdInt int userId) {
2237 final long start = injectElapsedRealtime();
2238 final long token = injectClearCallingIdentity();
2239 try {
2240 synchronized (mLock) {
2241 throwIfUserLockedL(userId);
2242
2243 final ShortcutUser user = getUserShortcutsLocked(userId);
2244
2245 final List<ResolveInfo> allHomeCandidates = new ArrayList<>();
2246
2247 // Default launcher from package manager.
2248 final long startGetHomeActivitiesAsUser = injectElapsedRealtime();
2249 final ComponentName defaultLauncher = mPackageManagerInternal
2250 .getHomeActivitiesAsUser(allHomeCandidates, userId);
2251 logDurationStat(Stats.GET_DEFAULT_HOME, startGetHomeActivitiesAsUser);
2252
2253 ComponentName detected = null;
2254 if (defaultLauncher != null) {
2255 detected = defaultLauncher;
2256 if (DEBUG) {
2257 Slog.v(TAG, "Default launcher from PM: " + detected);
2258 }
2259 } else {
2260 detected = user.getLastKnownLauncher();
2261
2262 if (detected != null) {
2263 if (injectIsActivityEnabledAndExported(detected, userId)) {
2264 if (DEBUG) {
2265 Slog.v(TAG, "Cached launcher: " + detected);
2266 }
2267 } else {
2268 Slog.w(TAG, "Cached launcher " + detected + " no longer exists");
2269 detected = null;
2270 user.clearLauncher();
2271 }
2272 }
2273 }
2274
2275 if (detected == null) {
2276 // If we reach here, that means it's the first check since the user was created,
2277 // and there's already multiple launchers and there's no default set.
2278 // Find the system one with the highest priority.
2279 // (We need to check the priority too because of FallbackHome in Settings.)
2280 // If there's no system launcher yet, then no one can access shortcuts, until
2281 // the user explicitly
2282 final int size = allHomeCandidates.size();
2283
2284 int lastPriority = Integer.MIN_VALUE;
2285 for (int i = 0; i < size; i++) {
2286 final ResolveInfo ri = allHomeCandidates.get(i);
2287 if (!ri.activityInfo.applicationInfo.isSystemApp()) {
2288 continue;
2289 }
2290 if (DEBUG) {
2291 Slog.d(TAG, String.format("hasShortcutPermissionInner: pkg=%s prio=%d",
2292 ri.activityInfo.getComponentName(), ri.priority));
2293 }
2294 if (ri.priority < lastPriority) {
2295 continue;
2296 }
2297 detected = ri.activityInfo.getComponentName();
2298 lastPriority = ri.priority;
2299 }
2300 }
2301 return detected;
2302 }
2303 } finally {
2304 injectRestoreCallingIdentity(token);
2305 logDurationStat(Stats.GET_DEFAULT_LAUNCHER, start);
2306 }
2307 }
2308
Makoto Onukicdc78f72016-03-21 15:47:52 -07002309 // === House keeping ===
2310
Makoto Onukib08790c2016-06-23 14:05:46 -07002311 private void cleanUpPackageForAllLoadedUsers(String packageName, @UserIdInt int packageUserId,
2312 boolean appStillExists) {
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002313 synchronized (mLock) {
2314 forEachLoadedUserLocked(user ->
Makoto Onukib08790c2016-06-23 14:05:46 -07002315 cleanUpPackageLocked(packageName, user.getUserId(), packageUserId,
2316 appStillExists));
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002317 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002318 }
2319
Makoto Onuki2e210c42016-03-30 08:30:36 -07002320 /**
2321 * Remove all the information associated with a package. This will really remove all the
2322 * information, including the restore information (i.e. it'll remove packages even if they're
2323 * shadow).
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002324 *
2325 * This is called when an app is uninstalled, or an app gets "clear data"ed.
Makoto Onuki2e210c42016-03-30 08:30:36 -07002326 */
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002327 @VisibleForTesting
Makoto Onukib08790c2016-06-23 14:05:46 -07002328 void cleanUpPackageLocked(String packageName, int owningUserId, int packageUserId,
2329 boolean appStillExists) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002330 final boolean wasUserLoaded = isUserLoadedLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002331
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002332 final ShortcutUser user = getUserShortcutsLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002333 boolean doNotify = false;
2334
2335 // First, remove the package from the package list (if the package is a publisher).
Makoto Onukid99c6f02016-03-28 11:02:54 -07002336 if (packageUserId == owningUserId) {
Makoto Onukic51b2872016-05-04 15:24:50 -07002337 if (user.removePackage(packageName) != null) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002338 doNotify = true;
2339 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07002340 }
Makoto Onukid99c6f02016-03-28 11:02:54 -07002341
Makoto Onukicdc78f72016-03-21 15:47:52 -07002342 // Also remove from the launcher list (if the package is a launcher).
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002343 user.removeLauncher(packageUserId, packageName);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002344
2345 // Then remove pinned shortcuts from all launchers.
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002346 user.forAllLaunchers(l -> l.cleanUpPackage(packageName, packageUserId));
2347
2348 // Now there may be orphan shortcuts because we removed pinned shortcuts at the previous
Makoto Onukicdc78f72016-03-21 15:47:52 -07002349 // step. Remove them too.
Makoto Onukic51b2872016-05-04 15:24:50 -07002350 user.forAllPackages(p -> p.refreshPinnedFlags());
Makoto Onukicdc78f72016-03-21 15:47:52 -07002351
Makoto Onukid99c6f02016-03-28 11:02:54 -07002352 scheduleSaveUser(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002353
2354 if (doNotify) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002355 notifyListeners(packageName, owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002356 }
2357
Makoto Onukib08790c2016-06-23 14:05:46 -07002358 // If the app still exists (i.e. data cleared), we need to re-publish manifest shortcuts.
2359 if (appStillExists && (packageUserId == owningUserId)) {
2360 // This will do the notification and save when needed, so do it after the above
2361 // notifyListeners.
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002362 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07002363 }
2364
Makoto Onukicdc78f72016-03-21 15:47:52 -07002365 if (!wasUserLoaded) {
2366 // Note this will execute the scheduled save.
Makoto Onukid99c6f02016-03-28 11:02:54 -07002367 unloadUserLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002368 }
2369 }
2370
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002371 /**
2372 * Entry point from {@link LauncherApps}.
2373 */
2374 private class LocalService extends ShortcutServiceInternal {
Makoto Onuki2e210c42016-03-30 08:30:36 -07002375
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002376 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002377 public List<ShortcutInfo> getShortcuts(int launcherUserId,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002378 @NonNull String callingPackage, long changedSince,
Makoto Onukiabe84422016-04-07 09:41:19 -07002379 @Nullable String packageName, @Nullable List<String> shortcutIds,
Makoto Onuki99302b52017-03-29 12:42:26 -07002380 @Nullable ComponentName componentName,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002381 int queryFlags, int userId) {
2382 final ArrayList<ShortcutInfo> ret = new ArrayList<>();
Makoto Onuki9c850012016-07-26 15:50:50 -07002383
Makoto Onuki20c95f82016-05-11 16:51:01 -07002384 final boolean cloneKeyFieldOnly =
2385 ((queryFlags & ShortcutQuery.FLAG_GET_KEY_FIELDS_ONLY) != 0);
2386 final int cloneFlag = cloneKeyFieldOnly ? ShortcutInfo.CLONE_REMOVE_NON_KEY_INFO
2387 : ShortcutInfo.CLONE_REMOVE_FOR_LAUNCHER;
Makoto Onukiabe84422016-04-07 09:41:19 -07002388 if (packageName == null) {
2389 shortcutIds = null; // LauncherAppsService already threw for it though.
2390 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002391
2392 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002393 throwIfUserLockedL(userId);
2394 throwIfUserLockedL(launcherUserId);
2395
Makoto Onuki2e210c42016-03-30 08:30:36 -07002396 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002397 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002398
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002399 if (packageName != null) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002400 getShortcutsInnerLocked(launcherUserId,
Makoto Onukiabe84422016-04-07 09:41:19 -07002401 callingPackage, packageName, shortcutIds, changedSince,
Makoto Onuki99302b52017-03-29 12:42:26 -07002402 componentName, queryFlags, userId, ret, cloneFlag);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002403 } else {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002404 final List<String> shortcutIdsF = shortcutIds;
2405 getUserShortcutsLocked(userId).forAllPackages(p -> {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002406 getShortcutsInnerLocked(launcherUserId,
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002407 callingPackage, p.getPackageName(), shortcutIdsF, changedSince,
Makoto Onuki99302b52017-03-29 12:42:26 -07002408 componentName, queryFlags, userId, ret, cloneFlag);
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002409 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002410 }
2411 }
Makoto Onukibf563b62017-05-04 10:25:30 -07002412 return setReturnedByServer(ret);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002413 }
2414
Makoto Onukid99c6f02016-03-28 11:02:54 -07002415 private void getShortcutsInnerLocked(int launcherUserId, @NonNull String callingPackage,
Makoto Onukiabe84422016-04-07 09:41:19 -07002416 @Nullable String packageName, @Nullable List<String> shortcutIds, long changedSince,
Makoto Onuki99302b52017-03-29 12:42:26 -07002417 @Nullable ComponentName componentName, int queryFlags,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002418 int userId, ArrayList<ShortcutInfo> ret, int cloneFlag) {
Makoto Onukiabe84422016-04-07 09:41:19 -07002419 final ArraySet<String> ids = shortcutIds == null ? null
2420 : new ArraySet<>(shortcutIds);
2421
Makoto Onukic51b2872016-05-04 15:24:50 -07002422 final ShortcutPackage p = getUserShortcutsLocked(userId)
2423 .getPackageShortcutsIfExists(packageName);
2424 if (p == null) {
2425 return; // No need to instantiate ShortcutPackage.
2426 }
2427
2428 p.findAll(ret,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002429 (ShortcutInfo si) -> {
2430 if (si.getLastChangedTimestamp() < changedSince) {
2431 return false;
2432 }
Makoto Onukiabe84422016-04-07 09:41:19 -07002433 if (ids != null && !ids.contains(si.getId())) {
2434 return false;
2435 }
Makoto Onuki85694522016-05-04 12:53:37 -07002436 if (componentName != null) {
Makoto Onuki9fd90192017-01-06 18:31:03 +00002437 if (si.getActivity() != null
2438 && !si.getActivity().equals(componentName)) {
Makoto Onuki85694522016-05-04 12:53:37 -07002439 return false;
2440 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002441 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002442 if (((queryFlags & ShortcutQuery.FLAG_GET_DYNAMIC) != 0)
2443 && si.isDynamic()) {
2444 return true;
2445 }
2446 if (((queryFlags & ShortcutQuery.FLAG_GET_PINNED) != 0)
2447 && si.isPinned()) {
2448 return true;
2449 }
2450 if (((queryFlags & ShortcutQuery.FLAG_GET_MANIFEST) != 0)
2451 && si.isManifestShortcut()) {
2452 return true;
2453 }
2454 return false;
Makoto Onukid99c6f02016-03-28 11:02:54 -07002455 }, cloneFlag, callingPackage, launcherUserId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002456 }
2457
2458 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002459 public boolean isPinnedByCaller(int launcherUserId, @NonNull String callingPackage,
2460 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2461 Preconditions.checkStringNotEmpty(packageName, "packageName");
2462 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
2463
2464 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002465 throwIfUserLockedL(userId);
2466 throwIfUserLockedL(launcherUserId);
2467
Makoto Onuki2e210c42016-03-30 08:30:36 -07002468 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002469 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002470
Makoto Onukid99c6f02016-03-28 11:02:54 -07002471 final ShortcutInfo si = getShortcutInfoLocked(
2472 launcherUserId, callingPackage, packageName, shortcutId, userId);
2473 return si != null && si.isPinned();
2474 }
2475 }
2476
Makoto Onuki2e210c42016-03-30 08:30:36 -07002477 private ShortcutInfo getShortcutInfoLocked(
Makoto Onukid99c6f02016-03-28 11:02:54 -07002478 int launcherUserId, @NonNull String callingPackage,
2479 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2480 Preconditions.checkStringNotEmpty(packageName, "packageName");
2481 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
2482
Makoto Onuki02f338e2016-07-29 09:40:40 -07002483 throwIfUserLockedL(userId);
2484 throwIfUserLockedL(launcherUserId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002485
Makoto Onukic51b2872016-05-04 15:24:50 -07002486 final ShortcutPackage p = getUserShortcutsLocked(userId)
2487 .getPackageShortcutsIfExists(packageName);
2488 if (p == null) {
2489 return null;
2490 }
2491
Makoto Onukid99c6f02016-03-28 11:02:54 -07002492 final ArrayList<ShortcutInfo> list = new ArrayList<>(1);
Makoto Onukic51b2872016-05-04 15:24:50 -07002493 p.findAll(list,
Makoto Onukid99c6f02016-03-28 11:02:54 -07002494 (ShortcutInfo si) -> shortcutId.equals(si.getId()),
2495 /* clone flags=*/ 0, callingPackage, launcherUserId);
2496 return list.size() == 0 ? null : list.get(0);
2497 }
2498
2499 @Override
2500 public void pinShortcuts(int launcherUserId,
2501 @NonNull String callingPackage, @NonNull String packageName,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002502 @NonNull List<String> shortcutIds, int userId) {
2503 // Calling permission must be checked by LauncherAppsImpl.
2504 Preconditions.checkStringNotEmpty(packageName, "packageName");
2505 Preconditions.checkNotNull(shortcutIds, "shortcutIds");
2506
2507 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002508 throwIfUserLockedL(userId);
2509 throwIfUserLockedL(launcherUserId);
2510
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002511 final ShortcutLauncher launcher =
Makoto Onuki2e210c42016-03-30 08:30:36 -07002512 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId);
Makoto Onukic51b2872016-05-04 15:24:50 -07002513 launcher.attemptToRestoreIfNeededAndSave();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002514
Makoto Onukic51b2872016-05-04 15:24:50 -07002515 launcher.pinShortcuts(userId, packageName, shortcutIds);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002516 }
Makoto Onuki39686e82016-04-13 18:03:00 -07002517 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07002518
2519 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002520 }
2521
2522 @Override
Makoto Onuki440a1ea2016-07-20 14:21:18 -07002523 public Intent[] createShortcutIntents(int launcherUserId,
Makoto Onukid99c6f02016-03-28 11:02:54 -07002524 @NonNull String callingPackage,
Makoto Onuki43204b82016-03-08 16:16:44 -08002525 @NonNull String packageName, @NonNull String shortcutId, int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002526 // Calling permission must be checked by LauncherAppsImpl.
Makoto Onuki43204b82016-03-08 16:16:44 -08002527 Preconditions.checkStringNotEmpty(packageName, "packageName can't be empty");
2528 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId can't be empty");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002529
2530 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002531 throwIfUserLockedL(userId);
2532 throwIfUserLockedL(launcherUserId);
2533
Makoto Onuki2e210c42016-03-30 08:30:36 -07002534 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002535 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002536
Makoto Onukid99c6f02016-03-28 11:02:54 -07002537 // Make sure the shortcut is actually visible to the launcher.
2538 final ShortcutInfo si = getShortcutInfoLocked(
2539 launcherUserId, callingPackage, packageName, shortcutId, userId);
2540 // "si == null" should suffice here, but check the flags too just to make sure.
Makoto Onuki22fcc682016-05-17 14:52:19 -07002541 if (si == null || !si.isEnabled() || !si.isAlive()) {
Makoto Onuki83f6d2d2016-07-11 14:30:19 -07002542 Log.e(TAG, "Shortcut " + shortcutId + " does not exist or disabled");
Makoto Onukid99c6f02016-03-28 11:02:54 -07002543 return null;
2544 }
Makoto Onuki440a1ea2016-07-20 14:21:18 -07002545 return si.getIntents();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002546 }
2547 }
2548
2549 @Override
2550 public void addListener(@NonNull ShortcutChangeListener listener) {
2551 synchronized (mLock) {
2552 mListeners.add(Preconditions.checkNotNull(listener));
2553 }
2554 }
Makoto Onuki55046222016-03-08 10:49:47 -08002555
2556 @Override
Makoto Onukiabe84422016-04-07 09:41:19 -07002557 public int getShortcutIconResId(int launcherUserId, @NonNull String callingPackage,
2558 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2559 Preconditions.checkNotNull(callingPackage, "callingPackage");
2560 Preconditions.checkNotNull(packageName, "packageName");
2561 Preconditions.checkNotNull(shortcutId, "shortcutId");
Makoto Onuki55046222016-03-08 10:49:47 -08002562
2563 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002564 throwIfUserLockedL(userId);
2565 throwIfUserLockedL(launcherUserId);
2566
Makoto Onuki2e210c42016-03-30 08:30:36 -07002567 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002568 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002569
Makoto Onukic51b2872016-05-04 15:24:50 -07002570 final ShortcutPackage p = getUserShortcutsLocked(userId)
2571 .getPackageShortcutsIfExists(packageName);
2572 if (p == null) {
2573 return 0;
2574 }
2575
2576 final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId);
Makoto Onuki55046222016-03-08 10:49:47 -08002577 return (shortcutInfo != null && shortcutInfo.hasIconResource())
2578 ? shortcutInfo.getIconResourceId() : 0;
2579 }
2580 }
2581
2582 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002583 public ParcelFileDescriptor getShortcutIconFd(int launcherUserId,
Makoto Onukiabe84422016-04-07 09:41:19 -07002584 @NonNull String callingPackage, @NonNull String packageName,
2585 @NonNull String shortcutId, int userId) {
2586 Preconditions.checkNotNull(callingPackage, "callingPackage");
2587 Preconditions.checkNotNull(packageName, "packageName");
2588 Preconditions.checkNotNull(shortcutId, "shortcutId");
Makoto Onuki55046222016-03-08 10:49:47 -08002589
2590 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002591 throwIfUserLockedL(userId);
2592 throwIfUserLockedL(launcherUserId);
2593
Makoto Onuki2e210c42016-03-30 08:30:36 -07002594 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002595 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002596
Makoto Onukic51b2872016-05-04 15:24:50 -07002597 final ShortcutPackage p = getUserShortcutsLocked(userId)
2598 .getPackageShortcutsIfExists(packageName);
2599 if (p == null) {
2600 return null;
2601 }
2602
2603 final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId);
Makoto Onuki55046222016-03-08 10:49:47 -08002604 if (shortcutInfo == null || !shortcutInfo.hasIconFile()) {
2605 return null;
2606 }
Makoto Onuki475c3652017-05-08 14:29:03 -07002607 final String path = mShortcutBitmapSaver.getBitmapPathMayWaitLocked(shortcutInfo);
2608 if (path == null) {
2609 Slog.w(TAG, "null bitmap detected in getShortcutIconFd()");
2610 return null;
2611 }
Makoto Onuki55046222016-03-08 10:49:47 -08002612 try {
2613 return ParcelFileDescriptor.open(
Makoto Onuki475c3652017-05-08 14:29:03 -07002614 new File(path),
Makoto Onuki55046222016-03-08 10:49:47 -08002615 ParcelFileDescriptor.MODE_READ_ONLY);
2616 } catch (FileNotFoundException e) {
Makoto Onuki475c3652017-05-08 14:29:03 -07002617 Slog.e(TAG, "Icon file not found: " + path);
Makoto Onuki55046222016-03-08 10:49:47 -08002618 return null;
2619 }
2620 }
2621 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002622
2623 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002624 public boolean hasShortcutHostPermission(int launcherUserId,
2625 @NonNull String callingPackage) {
2626 return ShortcutService.this.hasShortcutHostPermission(callingPackage, launcherUserId);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002627 }
Sunny Goyal87a563e2017-01-01 19:42:45 -08002628
2629 @Override
2630 public boolean requestPinAppWidget(@NonNull String callingPackage,
Sunny Goyal4ad6b572017-02-28 11:11:51 -08002631 @NonNull AppWidgetProviderInfo appWidget, @Nullable Bundle extras,
2632 @Nullable IntentSender resultIntent, int userId) {
Sunny Goyal87a563e2017-01-01 19:42:45 -08002633 Preconditions.checkNotNull(appWidget);
Sunny Goyal4ad6b572017-02-28 11:11:51 -08002634 return requestPinItem(callingPackage, userId, null, appWidget, extras, resultIntent);
Sunny Goyal87a563e2017-01-01 19:42:45 -08002635 }
Sunny Goyal7f7372a2017-01-24 11:53:54 -08002636
2637 @Override
2638 public boolean isRequestPinItemSupported(int callingUserId, int requestType) {
2639 return ShortcutService.this.isRequestPinItemSupported(callingUserId, requestType);
2640 }
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002641 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002642
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002643 final BroadcastReceiver mReceiver = new BroadcastReceiver() {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002644 @Override
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002645 public void onReceive(Context context, Intent intent) {
2646 if (!mBootCompleted.get()) {
2647 return; // Boot not completed, ignore the broadcast.
2648 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07002649 try {
2650 if (Intent.ACTION_LOCALE_CHANGED.equals(intent.getAction())) {
2651 handleLocaleChanged();
2652 }
2653 } catch (Exception e) {
2654 wtf("Exception in mReceiver.onReceive", e);
Makoto Onukic51b2872016-05-04 15:24:50 -07002655 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002656 }
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002657 };
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002658
Makoto Onuki157b1622016-06-02 16:13:10 -07002659 void handleLocaleChanged() {
2660 if (DEBUG) {
2661 Slog.d(TAG, "handleLocaleChanged");
2662 }
2663 scheduleSaveBaseState();
2664
Makoto Onuki02f338e2016-07-29 09:40:40 -07002665 synchronized (mLock) {
2666 final long token = injectClearCallingIdentity();
2667 try {
2668 forEachLoadedUserLocked(user -> user.detectLocaleChange());
2669 } finally {
2670 injectRestoreCallingIdentity(token);
2671 }
Makoto Onuki157b1622016-06-02 16:13:10 -07002672 }
2673 }
2674
Makoto Onukif34c3082016-07-13 10:25:25 -07002675 /**
2676 * Package event callbacks.
2677 */
2678 @VisibleForTesting
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002679 final BroadcastReceiver mPackageMonitor = new BroadcastReceiver() {
Makoto Onukif34c3082016-07-13 10:25:25 -07002680 @Override
2681 public void onReceive(Context context, Intent intent) {
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002682 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
2683 if (userId == UserHandle.USER_NULL) {
2684 Slog.w(TAG, "Intent broadcast does not contain user handle: " + intent);
2685 return;
2686 }
2687
2688 final String action = intent.getAction();
2689
2690 // This is normally called on Handler, so clearCallingIdentity() isn't needed,
2691 // but we still check it in unit tests.
Makoto Onukif34c3082016-07-13 10:25:25 -07002692 final long token = injectClearCallingIdentity();
2693 try {
Makoto Onuki10305202016-07-14 18:14:08 -07002694 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002695 if (!isUserUnlockedL(userId)) {
2696 if (DEBUG) {
2697 Slog.d(TAG, "Ignoring package broadcast " + action
2698 + " for locked/stopped user " + userId);
2699 }
2700 return;
2701 }
2702
2703 // Whenever we get one of those package broadcasts, or get
2704 // ACTION_PREFERRED_ACTIVITY_CHANGED, we purge the default launcher cache.
Makoto Onuki10305202016-07-14 18:14:08 -07002705 final ShortcutUser user = getUserShortcutsLocked(userId);
2706 user.clearLauncher();
2707 }
2708 if (Intent.ACTION_PREFERRED_ACTIVITY_CHANGED.equals(action)) {
2709 // Nothing farther to do.
2710 return;
2711 }
2712
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002713 final Uri intentUri = intent.getData();
2714 final String packageName = (intentUri != null) ? intentUri.getSchemeSpecificPart()
2715 : null;
2716 if (packageName == null) {
2717 Slog.w(TAG, "Intent broadcast does not contain package name: " + intent);
2718 return;
2719 }
2720
2721 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
2722
2723 switch (action) {
2724 case Intent.ACTION_PACKAGE_ADDED:
2725 if (replacing) {
2726 handlePackageUpdateFinished(packageName, userId);
2727 } else {
2728 handlePackageAdded(packageName, userId);
2729 }
2730 break;
2731 case Intent.ACTION_PACKAGE_REMOVED:
2732 if (!replacing) {
2733 handlePackageRemoved(packageName, userId);
2734 }
2735 break;
2736 case Intent.ACTION_PACKAGE_CHANGED:
2737 handlePackageChanged(packageName, userId);
2738
2739 break;
2740 case Intent.ACTION_PACKAGE_DATA_CLEARED:
2741 handlePackageDataCleared(packageName, userId);
2742 break;
2743 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07002744 } catch (Exception e) {
2745 wtf("Exception in mPackageMonitor.onReceive", e);
Makoto Onukif34c3082016-07-13 10:25:25 -07002746 } finally {
2747 injectRestoreCallingIdentity(token);
Makoto Onukia2241832016-07-06 13:28:37 -07002748 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07002749 }
Makoto Onukif34c3082016-07-13 10:25:25 -07002750 };
Makoto Onukicdc78f72016-03-21 15:47:52 -07002751
Makoto Onuki0acbb142016-03-22 17:02:57 -07002752 /**
Makoto Onuki39686e82016-04-13 18:03:00 -07002753 * Called when a user is unlocked.
2754 * - Check all known packages still exist, and otherwise perform cleanup.
2755 * - If a package still exists, check the version code. If it's been updated, may need to
Makoto Onukib08790c2016-06-23 14:05:46 -07002756 * update timestamps of its shortcuts.
Makoto Onuki0acbb142016-03-22 17:02:57 -07002757 */
Makoto Onukid99c6f02016-03-28 11:02:54 -07002758 @VisibleForTesting
Makoto Onuki39686e82016-04-13 18:03:00 -07002759 void checkPackageChanges(@UserIdInt int ownerUserId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07002760 if (DEBUG) {
Makoto Onuki39686e82016-04-13 18:03:00 -07002761 Slog.d(TAG, "checkPackageChanges() ownerUserId=" + ownerUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002762 }
Makoto Onukib08790c2016-06-23 14:05:46 -07002763 if (injectIsSafeModeEnabled()) {
2764 Slog.i(TAG, "Safe mode, skipping checkPackageChanges()");
2765 return;
2766 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07002767
Makoto Onuki22fcc682016-05-17 14:52:19 -07002768 final long start = injectElapsedRealtime();
2769 try {
2770 final ArrayList<PackageWithUser> gonePackages = new ArrayList<>();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002771
Makoto Onuki22fcc682016-05-17 14:52:19 -07002772 synchronized (mLock) {
2773 final ShortcutUser user = getUserShortcutsLocked(ownerUserId);
2774
2775 // Find packages that have been uninstalled.
2776 user.forAllPackageItems(spi -> {
2777 if (spi.getPackageInfo().isShadow()) {
2778 return; // Don't delete shadow information.
2779 }
2780 if (!isPackageInstalled(spi.getPackageName(), spi.getPackageUserId())) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002781 if (DEBUG) {
2782 Slog.d(TAG, "Uninstalled: " + spi.getPackageName()
2783 + " user " + spi.getPackageUserId());
2784 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002785 gonePackages.add(PackageWithUser.of(spi));
2786 }
2787 });
2788 if (gonePackages.size() > 0) {
2789 for (int i = gonePackages.size() - 1; i >= 0; i--) {
2790 final PackageWithUser pu = gonePackages.get(i);
Makoto Onukib08790c2016-06-23 14:05:46 -07002791 cleanUpPackageLocked(pu.packageName, ownerUserId, pu.userId,
2792 /* appStillExists = */ false);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002793 }
Makoto Onukid99c6f02016-03-28 11:02:54 -07002794 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002795
Makoto Onuki248a0ef2016-11-03 15:59:01 -07002796 rescanUpdatedPackagesLocked(ownerUserId, user.getLastAppScanTime());
Makoto Onuki0acbb142016-03-22 17:02:57 -07002797 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002798 } finally {
2799 logDurationStat(Stats.CHECK_PACKAGE_CHANGES, start);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002800 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002801 verifyStates();
Makoto Onukicdc78f72016-03-21 15:47:52 -07002802 }
2803
Makoto Onuki248a0ef2016-11-03 15:59:01 -07002804 private void rescanUpdatedPackagesLocked(@UserIdInt int userId, long lastScanTime) {
Makoto Onuki377b7972016-08-09 14:43:55 -07002805 final ShortcutUser user = getUserShortcutsLocked(userId);
2806
Makoto Onuki33663282016-08-22 16:19:04 -07002807 // Note after each OTA, we'll need to rescan all system apps, as their lastUpdateTime
2808 // is not reliable.
Makoto Onuki377b7972016-08-09 14:43:55 -07002809 final long now = injectCurrentTimeMillis();
Makoto Onuki33663282016-08-22 16:19:04 -07002810 final boolean afterOta =
2811 !injectBuildFingerprint().equals(user.getLastAppScanOsFingerprint());
Makoto Onuki377b7972016-08-09 14:43:55 -07002812
2813 // Then for each installed app, publish manifest shortcuts when needed.
Makoto Onuki33663282016-08-22 16:19:04 -07002814 forUpdatedPackages(userId, lastScanTime, afterOta, ai -> {
Makoto Onuki377b7972016-08-09 14:43:55 -07002815 user.attemptToRestoreIfNeededAndSave(this, ai.packageName, userId);
Makoto Onuki248a0ef2016-11-03 15:59:01 -07002816
2817 user.rescanPackageIfNeeded(ai.packageName, /* forceRescan= */ true);
Makoto Onuki377b7972016-08-09 14:43:55 -07002818 });
2819
2820 // Write the time just before the scan, because there may be apps that have just
2821 // been updated, and we want to catch them in the next time.
2822 user.setLastAppScanTime(now);
Makoto Onuki33663282016-08-22 16:19:04 -07002823 user.setLastAppScanOsFingerprint(injectBuildFingerprint());
Makoto Onuki377b7972016-08-09 14:43:55 -07002824 scheduleSaveUser(userId);
2825 }
2826
Makoto Onuki0acbb142016-03-22 17:02:57 -07002827 private void handlePackageAdded(String packageName, @UserIdInt int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07002828 if (DEBUG) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07002829 Slog.d(TAG, String.format("handlePackageAdded: %s user=%d", packageName, userId));
2830 }
2831 synchronized (mLock) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002832 final ShortcutUser user = getUserShortcutsLocked(userId);
2833 user.attemptToRestoreIfNeededAndSave(this, packageName, userId);
Makoto Onuki64183d52016-08-08 14:11:34 -07002834 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002835 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002836 verifyStates();
Makoto Onuki0acbb142016-03-22 17:02:57 -07002837 }
2838
2839 private void handlePackageUpdateFinished(String packageName, @UserIdInt int userId) {
Makoto Onuki905e8852016-03-28 10:40:58 -07002840 if (DEBUG) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002841 Slog.d(TAG, String.format("handlePackageUpdateFinished: %s user=%d",
2842 packageName, userId));
Makoto Onuki0acbb142016-03-22 17:02:57 -07002843 }
2844 synchronized (mLock) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002845 final ShortcutUser user = getUserShortcutsLocked(userId);
2846 user.attemptToRestoreIfNeededAndSave(this, packageName, userId);
Makoto Onuki39686e82016-04-13 18:03:00 -07002847
Makoto Onuki22fcc682016-05-17 14:52:19 -07002848 if (isPackageInstalled(packageName, userId)) {
Makoto Onuki64183d52016-08-08 14:11:34 -07002849 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onuki39686e82016-04-13 18:03:00 -07002850 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07002851 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002852 verifyStates();
Makoto Onuki0acbb142016-03-22 17:02:57 -07002853 }
2854
Makoto Onuki2e210c42016-03-30 08:30:36 -07002855 private void handlePackageRemoved(String packageName, @UserIdInt int packageUserId) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07002856 if (DEBUG) {
Makoto Onuki2e210c42016-03-30 08:30:36 -07002857 Slog.d(TAG, String.format("handlePackageRemoved: %s user=%d", packageName,
2858 packageUserId));
Makoto Onukicdc78f72016-03-21 15:47:52 -07002859 }
Makoto Onukib08790c2016-06-23 14:05:46 -07002860 cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ false);
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002861
2862 verifyStates();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002863 }
2864
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002865 private void handlePackageDataCleared(String packageName, int packageUserId) {
2866 if (DEBUG) {
2867 Slog.d(TAG, String.format("handlePackageDataCleared: %s user=%d", packageName,
2868 packageUserId));
Makoto Onukicdc78f72016-03-21 15:47:52 -07002869 }
Makoto Onukib08790c2016-06-23 14:05:46 -07002870 cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ true);
2871
2872 verifyStates();
2873 }
2874
2875 private void handlePackageChanged(String packageName, int packageUserId) {
Makoto Onuki82fb2eb2017-03-31 16:58:26 -07002876 if (!isPackageInstalled(packageName, packageUserId)) {
2877 // Probably disabled, which is the same thing as uninstalled.
2878 handlePackageRemoved(packageName, packageUserId);
2879 return;
2880 }
Makoto Onukib08790c2016-06-23 14:05:46 -07002881 if (DEBUG) {
2882 Slog.d(TAG, String.format("handlePackageChanged: %s user=%d", packageName,
2883 packageUserId));
2884 }
2885
2886 // Activities may be disabled or enabled. Just rescan the package.
2887 synchronized (mLock) {
2888 final ShortcutUser user = getUserShortcutsLocked(packageUserId);
2889
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002890 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07002891 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002892
2893 verifyStates();
Makoto Onukicdc78f72016-03-21 15:47:52 -07002894 }
2895
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002896 // === PackageManager interaction ===
Makoto Onuki0acbb142016-03-22 17:02:57 -07002897
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002898 /**
2899 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
2900 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002901 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002902 final PackageInfo getPackageInfoWithSignatures(String packageName, @UserIdInt int userId) {
2903 return getPackageInfo(packageName, userId, true);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002904 }
2905
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002906 /**
2907 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
2908 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002909 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002910 final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId) {
2911 return getPackageInfo(packageName, userId, false);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002912 }
2913
Makoto Onuki905e8852016-03-28 10:40:58 -07002914 int injectGetPackageUid(@NonNull String packageName, @UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002915 final long token = injectClearCallingIdentity();
Makoto Onuki905e8852016-03-28 10:40:58 -07002916 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002917 return mIPackageManager.getPackageUid(packageName, PACKAGE_MATCH_FLAGS, userId);
Makoto Onuki905e8852016-03-28 10:40:58 -07002918 } catch (RemoteException e) {
2919 // Shouldn't happen.
2920 Slog.wtf(TAG, "RemoteException", e);
2921 return -1;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002922 } finally {
2923 injectRestoreCallingIdentity(token);
Makoto Onuki905e8852016-03-28 10:40:58 -07002924 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07002925 }
2926
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002927 /**
2928 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
2929 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002930 @Nullable
Makoto Onuki0acbb142016-03-22 17:02:57 -07002931 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002932 final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId,
2933 boolean getSignatures) {
2934 return isInstalledOrNull(injectPackageInfoWithUninstalled(
2935 packageName, userId, getSignatures));
2936 }
2937
2938 /**
2939 * Do not use directly; this returns uninstalled packages too.
2940 */
2941 @Nullable
2942 @VisibleForTesting
2943 PackageInfo injectPackageInfoWithUninstalled(String packageName, @UserIdInt int userId,
Makoto Onuki0acbb142016-03-22 17:02:57 -07002944 boolean getSignatures) {
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07002945 final long start = injectElapsedRealtime();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002946 final long token = injectClearCallingIdentity();
Makoto Onuki0acbb142016-03-22 17:02:57 -07002947 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002948 return mIPackageManager.getPackageInfo(
2949 packageName, PACKAGE_MATCH_FLAGS
2950 | (getSignatures ? PackageManager.GET_SIGNATURES : 0), userId);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002951 } catch (RemoteException e) {
2952 // Shouldn't happen.
2953 Slog.wtf(TAG, "RemoteException", e);
2954 return null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002955 } finally {
2956 injectRestoreCallingIdentity(token);
Makoto Onuki2e210c42016-03-30 08:30:36 -07002957
2958 logDurationStat(
2959 (getSignatures ? Stats.GET_PACKAGE_INFO_WITH_SIG : Stats.GET_PACKAGE_INFO),
2960 start);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002961 }
2962 }
2963
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002964 /**
2965 * Returns {@link ApplicationInfo} unless it's uninstalled or disabled.
2966 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002967 @Nullable
Makoto Onuki905e8852016-03-28 10:40:58 -07002968 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002969 final ApplicationInfo getApplicationInfo(String packageName, @UserIdInt int userId) {
2970 return isInstalledOrNull(injectApplicationInfoWithUninstalled(packageName, userId));
2971 }
2972
2973 /**
2974 * Do not use directly; this returns uninstalled packages too.
2975 */
2976 @Nullable
2977 @VisibleForTesting
2978 ApplicationInfo injectApplicationInfoWithUninstalled(
2979 String packageName, @UserIdInt int userId) {
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07002980 final long start = injectElapsedRealtime();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002981 final long token = injectClearCallingIdentity();
Makoto Onuki905e8852016-03-28 10:40:58 -07002982 try {
2983 return mIPackageManager.getApplicationInfo(packageName, PACKAGE_MATCH_FLAGS, userId);
2984 } catch (RemoteException e) {
2985 // Shouldn't happen.
2986 Slog.wtf(TAG, "RemoteException", e);
2987 return null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002988 } finally {
2989 injectRestoreCallingIdentity(token);
Makoto Onuki2e210c42016-03-30 08:30:36 -07002990
2991 logDurationStat(Stats.GET_APPLICATION_INFO, start);
Makoto Onuki905e8852016-03-28 10:40:58 -07002992 }
2993 }
2994
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002995 /**
2996 * Returns {@link ActivityInfo} with its metadata unless it's uninstalled or disabled.
2997 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002998 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002999 final ActivityInfo getActivityInfoWithMetadata(ComponentName activity, @UserIdInt int userId) {
3000 return isInstalledOrNull(injectGetActivityInfoWithMetadataWithUninstalled(
3001 activity, userId));
3002 }
3003
3004 /**
3005 * Do not use directly; this returns uninstalled packages too.
3006 */
3007 @Nullable
3008 @VisibleForTesting
3009 ActivityInfo injectGetActivityInfoWithMetadataWithUninstalled(
3010 ComponentName activity, @UserIdInt int userId) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07003011 final long start = injectElapsedRealtime();
3012 final long token = injectClearCallingIdentity();
3013 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07003014 return mIPackageManager.getActivityInfo(activity,
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003015 (PACKAGE_MATCH_FLAGS | PackageManager.GET_META_DATA), userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003016 } catch (RemoteException e) {
3017 // Shouldn't happen.
3018 Slog.wtf(TAG, "RemoteException", e);
3019 return null;
3020 } finally {
3021 injectRestoreCallingIdentity(token);
3022
Makoto Onukib08790c2016-06-23 14:05:46 -07003023 logDurationStat(Stats.GET_ACTIVITY_WITH_METADATA, start);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003024 }
3025 }
3026
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003027 /**
3028 * Return all installed and enabled packages.
3029 */
3030 @NonNull
Makoto Onuki22fcc682016-05-17 14:52:19 -07003031 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003032 final List<PackageInfo> getInstalledPackages(@UserIdInt int userId) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07003033 final long start = injectElapsedRealtime();
3034 final long token = injectClearCallingIdentity();
3035 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003036 final List<PackageInfo> all = injectGetPackagesWithUninstalled(userId);
3037
3038 all.removeIf(PACKAGE_NOT_INSTALLED);
3039
3040 return all;
Makoto Onuki22fcc682016-05-17 14:52:19 -07003041 } catch (RemoteException e) {
3042 // Shouldn't happen.
3043 Slog.wtf(TAG, "RemoteException", e);
3044 return null;
3045 } finally {
3046 injectRestoreCallingIdentity(token);
3047
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003048 logDurationStat(Stats.GET_INSTALLED_PACKAGES, start);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003049 }
3050 }
3051
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003052 /**
3053 * Do not use directly; this returns uninstalled packages too.
3054 */
3055 @NonNull
3056 @VisibleForTesting
3057 List<PackageInfo> injectGetPackagesWithUninstalled(@UserIdInt int userId)
3058 throws RemoteException {
3059 final ParceledListSlice<PackageInfo> parceledList =
3060 mIPackageManager.getInstalledPackages(PACKAGE_MATCH_FLAGS, userId);
3061 if (parceledList == null) {
3062 return Collections.emptyList();
3063 }
3064 return parceledList.getList();
3065 }
3066
Makoto Onuki33663282016-08-22 16:19:04 -07003067 private void forUpdatedPackages(@UserIdInt int userId, long lastScanTime, boolean afterOta,
Makoto Onuki22fcc682016-05-17 14:52:19 -07003068 Consumer<ApplicationInfo> callback) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003069 if (DEBUG) {
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003070 Slog.d(TAG, "forUpdatedPackages for user " + userId + ", lastScanTime=" + lastScanTime
3071 + " afterOta=" + afterOta);
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003072 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003073 final List<PackageInfo> list = getInstalledPackages(userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003074 for (int i = list.size() - 1; i >= 0; i--) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003075 final PackageInfo pi = list.get(i);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003076
Makoto Onuki64183d52016-08-08 14:11:34 -07003077 // If the package has been updated since the last scan time, then scan it.
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003078 // Also if it's right after an OTA, always re-scan all apps anyway, since the
3079 // shortcut parser might have changed.
3080 if (afterOta || (pi.lastUpdateTime >= lastScanTime)) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003081 if (DEBUG) {
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003082 Slog.d(TAG, "Found updated package " + pi.packageName
3083 + " updateTime=" + pi.lastUpdateTime);
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003084 }
3085 callback.accept(pi.applicationInfo);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003086 }
3087 }
3088 }
3089
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003090 private boolean isApplicationFlagSet(@NonNull String packageName, int userId, int flags) {
3091 final ApplicationInfo ai = injectApplicationInfoWithUninstalled(packageName, userId);
Makoto Onuki905e8852016-03-28 10:40:58 -07003092 return (ai != null) && ((ai.flags & flags) == flags);
3093 }
3094
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003095 private static boolean isInstalled(@Nullable ApplicationInfo ai) {
Makoto Onuki82fb2eb2017-03-31 16:58:26 -07003096 return (ai != null) && ai.enabled && (ai.flags & ApplicationInfo.FLAG_INSTALLED) != 0;
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003097 }
3098
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08003099 private static boolean isEphemeralApp(@Nullable ApplicationInfo ai) {
Svetoslav Ganov096d3042017-01-30 16:34:13 -08003100 return (ai != null) && ai.isInstantApp();
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08003101 }
3102
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003103 private static boolean isInstalled(@Nullable PackageInfo pi) {
3104 return (pi != null) && isInstalled(pi.applicationInfo);
3105 }
3106
3107 private static boolean isInstalled(@Nullable ActivityInfo ai) {
3108 return (ai != null) && isInstalled(ai.applicationInfo);
3109 }
3110
3111 private static ApplicationInfo isInstalledOrNull(ApplicationInfo ai) {
3112 return isInstalled(ai) ? ai : null;
3113 }
3114
3115 private static PackageInfo isInstalledOrNull(PackageInfo pi) {
3116 return isInstalled(pi) ? pi : null;
3117 }
3118
3119 private static ActivityInfo isInstalledOrNull(ActivityInfo ai) {
3120 return isInstalled(ai) ? ai : null;
3121 }
3122
Makoto Onuki2e210c42016-03-30 08:30:36 -07003123 boolean isPackageInstalled(String packageName, int userId) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003124 return getApplicationInfo(packageName, userId) != null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003125 }
3126
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08003127 boolean isEphemeralApp(String packageName, int userId) {
3128 return isEphemeralApp(getApplicationInfo(packageName, userId));
3129 }
3130
Makoto Onuki22fcc682016-05-17 14:52:19 -07003131 @Nullable
3132 XmlResourceParser injectXmlMetaData(ActivityInfo activityInfo, String key) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07003133 return activityInfo.loadXmlMetaData(mContext.getPackageManager(), key);
Makoto Onuki39686e82016-04-13 18:03:00 -07003134 }
3135
Makoto Onuki157b1622016-06-02 16:13:10 -07003136 @Nullable
3137 Resources injectGetResourcesForApplicationAsUser(String packageName, int userId) {
3138 final long start = injectElapsedRealtime();
3139 final long token = injectClearCallingIdentity();
3140 try {
3141 return mContext.getPackageManager().getResourcesForApplicationAsUser(
3142 packageName, userId);
3143 } catch (NameNotFoundException e) {
3144 Slog.e(TAG, "Resources for package " + packageName + " not found");
3145 return null;
3146 } finally {
3147 injectRestoreCallingIdentity(token);
3148
3149 logDurationStat(Stats.GET_APPLICATION_RESOURCES, start);
3150 }
3151 }
3152
Makoto Onukib08790c2016-06-23 14:05:46 -07003153 private Intent getMainActivityIntent() {
3154 final Intent intent = new Intent(Intent.ACTION_MAIN);
3155 intent.addCategory(LAUNCHER_INTENT_CATEGORY);
3156 return intent;
3157 }
3158
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003159 /**
3160 * Same as queryIntentActivitiesAsUser, except it makes sure the package is installed,
3161 * and only returns exported activities.
3162 */
3163 @NonNull
3164 @VisibleForTesting
3165 List<ResolveInfo> queryActivities(@NonNull Intent baseIntent,
3166 @NonNull String packageName, @Nullable ComponentName activity, int userId) {
3167
3168 baseIntent.setPackage(Preconditions.checkNotNull(packageName));
3169 if (activity != null) {
3170 baseIntent.setComponent(activity);
3171 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08003172 return queryActivities(baseIntent, userId, /* exportedOnly =*/ true);
3173 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003174
Makoto Onuki2d895c32016-12-02 15:48:40 -08003175 @NonNull
3176 List<ResolveInfo> queryActivities(@NonNull Intent intent, int userId,
3177 boolean exportedOnly) {
3178 final List<ResolveInfo> resolved;
3179 final long token = injectClearCallingIdentity();
3180 try {
3181 resolved =
3182 mContext.getPackageManager().queryIntentActivitiesAsUser(
3183 intent, PACKAGE_MATCH_FLAGS, userId);
3184 } finally {
3185 injectRestoreCallingIdentity(token);
3186 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003187 if (resolved == null || resolved.size() == 0) {
3188 return EMPTY_RESOLVE_INFO;
3189 }
3190 // Make sure the package is installed.
3191 if (!isInstalled(resolved.get(0).activityInfo)) {
3192 return EMPTY_RESOLVE_INFO;
3193 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08003194 if (exportedOnly) {
3195 resolved.removeIf(ACTIVITY_NOT_EXPORTED);
3196 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003197 return resolved;
3198 }
3199
3200 /**
3201 * Return the main activity that is enabled and exported. If multiple activities are found,
3202 * return the first one.
3203 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003204 @Nullable
3205 ComponentName injectGetDefaultMainActivity(@NonNull String packageName, int userId) {
3206 final long start = injectElapsedRealtime();
Makoto Onukib08790c2016-06-23 14:05:46 -07003207 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07003208 final List<ResolveInfo> resolved =
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003209 queryActivities(getMainActivityIntent(), packageName, null, userId);
3210 return resolved.size() == 0 ? null : resolved.get(0).activityInfo.getComponentName();
Makoto Onukib08790c2016-06-23 14:05:46 -07003211 } finally {
Makoto Onukib08790c2016-06-23 14:05:46 -07003212 logDurationStat(Stats.GET_LAUNCHER_ACTIVITY, start);
3213 }
3214 }
3215
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003216 /**
3217 * Return whether an activity is enabled, exported and main.
3218 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003219 boolean injectIsMainActivity(@NonNull ComponentName activity, int userId) {
3220 final long start = injectElapsedRealtime();
Makoto Onukib08790c2016-06-23 14:05:46 -07003221 try {
Makoto Onuki34145532017-03-14 17:58:36 -07003222 if (activity == null) {
3223 wtf("null activity detected");
3224 return false;
3225 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08003226 if (DUMMY_MAIN_ACTIVITY.equals(activity.getClassName())) {
3227 return true;
3228 }
3229 final List<ResolveInfo> resolved = queryActivities(
3230 getMainActivityIntent(), activity.getPackageName(), activity, userId);
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003231 return resolved.size() > 0;
Makoto Onukib08790c2016-06-23 14:05:46 -07003232 } finally {
Makoto Onukib08790c2016-06-23 14:05:46 -07003233 logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start);
3234 }
3235 }
3236
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003237 /**
Makoto Onuki2d895c32016-12-02 15:48:40 -08003238 * Create a dummy "main activity" component name which is used to create a dynamic shortcut
3239 * with no main activity temporarily.
3240 */
3241 @NonNull
3242 ComponentName getDummyMainActivity(@NonNull String packageName) {
3243 return new ComponentName(packageName, DUMMY_MAIN_ACTIVITY);
3244 }
3245
Makoto Onuki255461f2017-01-10 11:47:25 -08003246 boolean isDummyMainActivity(@Nullable ComponentName name) {
3247 return name != null && DUMMY_MAIN_ACTIVITY.equals(name.getClassName());
3248 }
3249
Makoto Onuki2d895c32016-12-02 15:48:40 -08003250 /**
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003251 * Return all the enabled, exported and main activities from a package.
3252 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003253 @NonNull
3254 List<ResolveInfo> injectGetMainActivities(@NonNull String packageName, int userId) {
3255 final long start = injectElapsedRealtime();
Makoto Onukib08790c2016-06-23 14:05:46 -07003256 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003257 return queryActivities(getMainActivityIntent(), packageName, null, userId);
Makoto Onukib08790c2016-06-23 14:05:46 -07003258 } finally {
Makoto Onukib08790c2016-06-23 14:05:46 -07003259 logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start);
3260 }
3261 }
3262
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003263 /**
3264 * Return whether an activity is enabled and exported.
3265 */
3266 @VisibleForTesting
3267 boolean injectIsActivityEnabledAndExported(
3268 @NonNull ComponentName activity, @UserIdInt int userId) {
3269 final long start = injectElapsedRealtime();
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003270 try {
3271 return queryActivities(new Intent(), activity.getPackageName(), activity, userId)
3272 .size() > 0;
3273 } finally {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003274 logDurationStat(Stats.IS_ACTIVITY_ENABLED, start);
3275 }
3276 }
3277
Makoto Onuki2d895c32016-12-02 15:48:40 -08003278 /**
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003279 * Get the {@link LauncherApps#ACTION_CONFIRM_PIN_SHORTCUT} or
3280 * {@link LauncherApps#ACTION_CONFIRM_PIN_APPWIDGET} activity in a given package depending on
3281 * the requestType.
Makoto Onuki2d895c32016-12-02 15:48:40 -08003282 */
3283 @Nullable
3284 ComponentName injectGetPinConfirmationActivity(@NonNull String launcherPackageName,
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003285 int launcherUserId, int requestType) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08003286 Preconditions.checkNotNull(launcherPackageName);
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003287 String action = requestType == LauncherApps.PinItemRequest.REQUEST_TYPE_SHORTCUT ?
3288 LauncherApps.ACTION_CONFIRM_PIN_SHORTCUT :
3289 LauncherApps.ACTION_CONFIRM_PIN_APPWIDGET;
Makoto Onuki2d895c32016-12-02 15:48:40 -08003290
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003291 final Intent confirmIntent = new Intent(action).setPackage(launcherPackageName);
Makoto Onuki2d895c32016-12-02 15:48:40 -08003292 final List<ResolveInfo> candidates = queryActivities(
3293 confirmIntent, launcherUserId, /* exportedOnly =*/ false);
3294 for (ResolveInfo ri : candidates) {
3295 return ri.activityInfo.getComponentName();
3296 }
3297 return null;
3298 }
3299
Makoto Onukib08790c2016-06-23 14:05:46 -07003300 boolean injectIsSafeModeEnabled() {
3301 final long token = injectClearCallingIdentity();
3302 try {
3303 return IWindowManager.Stub
3304 .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE))
3305 .isSafeModeEnabled();
3306 } catch (RemoteException e) {
3307 return false; // Shouldn't happen though.
3308 } finally {
3309 injectRestoreCallingIdentity(token);
3310 }
3311 }
3312
Makoto Onuki2d895c32016-12-02 15:48:40 -08003313 /**
3314 * If {@code userId} is of a managed profile, return the parent user ID. Otherwise return
3315 * itself.
3316 */
3317 int getParentOrSelfUserId(int userId) {
3318 final long token = injectClearCallingIdentity();
3319 try {
3320 final UserInfo parent = mUserManager.getProfileParent(userId);
3321 return (parent != null) ? parent.id : userId;
3322 } finally {
3323 injectRestoreCallingIdentity(token);
3324 }
3325 }
3326
Sunny Goyal87a563e2017-01-01 19:42:45 -08003327 void injectSendIntentSender(IntentSender intentSender, Intent extras) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08003328 if (intentSender == null) {
3329 return;
3330 }
3331 try {
Sunny Goyal87a563e2017-01-01 19:42:45 -08003332 intentSender.sendIntent(mContext, /* code= */ 0, extras,
Makoto Onuki2d895c32016-12-02 15:48:40 -08003333 /* onFinished=*/ null, /* handler= */ null);
3334 } catch (SendIntentException e) {
3335 Slog.w(TAG, "sendIntent failed().", e);
3336 }
3337 }
3338
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003339 // === Backup & restore ===
3340
Makoto Onuki0acbb142016-03-22 17:02:57 -07003341 boolean shouldBackupApp(String packageName, int userId) {
Makoto Onuki905e8852016-03-28 10:40:58 -07003342 return isApplicationFlagSet(packageName, userId, ApplicationInfo.FLAG_ALLOW_BACKUP);
Makoto Onuki0acbb142016-03-22 17:02:57 -07003343 }
3344
Makoto Onuki2e210c42016-03-30 08:30:36 -07003345 boolean shouldBackupApp(PackageInfo pi) {
3346 return (pi.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0;
3347 }
3348
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003349 @Override
Makoto Onuki2e210c42016-03-30 08:30:36 -07003350 public byte[] getBackupPayload(@UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003351 enforceSystem();
3352 if (DEBUG) {
3353 Slog.d(TAG, "Backing up user " + userId);
3354 }
3355 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003356 if (!isUserUnlockedL(userId)) {
3357 wtf("Can't backup: user " + userId + " is locked or not running");
3358 return null;
3359 }
3360
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003361 final ShortcutUser user = getUserShortcutsLocked(userId);
3362 if (user == null) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003363 wtf("Can't backup: user not found: id=" + userId);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003364 return null;
3365 }
3366
Makoto Onukic8c33292016-09-12 16:36:59 -07003367 // Update the signatures for all packages.
3368 user.forAllPackageItems(spi -> spi.refreshPackageSignatureAndSave());
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003369
Makoto Onukic8c33292016-09-12 16:36:59 -07003370 // Set the version code for the launchers.
3371 // We shouldn't do this for publisher packages, because we don't want to update the
3372 // version code without rescanning the manifest.
3373 user.forAllLaunchers(launcher -> launcher.ensureVersionInfo());
3374
3375 // Save to the filesystem.
3376 scheduleSaveUser(userId);
3377 saveDirtyInfo();
3378
Makoto Onuki475c3652017-05-08 14:29:03 -07003379 // Note, in case of backup, we don't have to wait on bitmap saving, because we don't
3380 // back up bitmaps anyway.
3381
Makoto Onukic8c33292016-09-12 16:36:59 -07003382 // Then create the backup payload.
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003383 final ByteArrayOutputStream os = new ByteArrayOutputStream(32 * 1024);
3384 try {
3385 saveUserInternalLocked(userId, os, /* forBackup */ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07003386 } catch (XmlPullParserException | IOException e) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003387 // Shouldn't happen.
3388 Slog.w(TAG, "Backup failed.", e);
3389 return null;
3390 }
3391 return os.toByteArray();
3392 }
3393 }
3394
3395 @Override
Makoto Onuki2e210c42016-03-30 08:30:36 -07003396 public void applyRestore(byte[] payload, @UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003397 enforceSystem();
3398 if (DEBUG) {
3399 Slog.d(TAG, "Restoring user " + userId);
3400 }
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003401 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003402 if (!isUserUnlockedL(userId)) {
3403 wtf("Can't restore: user " + userId + " is locked or not running");
3404 return;
3405 }
Makoto Onuki50a320e2017-05-31 14:38:42 -07003406
3407 // Note we print the file timestamps in dumpsys too, but also printing the timestamp
3408 // in the files anyway.
3409 mShortcutDumpFiles.save("restore-0-start.txt", pw -> {
3410 pw.print("Start time: ");
3411 dumpCurrentTime(pw);
3412 pw.println();
3413 });
3414 mShortcutDumpFiles.save("restore-1-payload.xml", payload);
3415
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003416 // Actually do restore.
3417 final ShortcutUser restored;
Makoto Onuki02f338e2016-07-29 09:40:40 -07003418 final ByteArrayInputStream is = new ByteArrayInputStream(payload);
3419 try {
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003420 restored = loadUserInternal(userId, is, /* fromBackup */ true);
3421 } catch (XmlPullParserException | IOException | InvalidFileFormatException e) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003422 Slog.w(TAG, "Restoration failed.", e);
3423 return;
3424 }
Makoto Onuki50a320e2017-05-31 14:38:42 -07003425 mShortcutDumpFiles.save("restore-2.txt", this::dumpInner);
3426
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003427 getUserShortcutsLocked(userId).mergeRestoredFile(restored);
Makoto Onuki2e210c42016-03-30 08:30:36 -07003428
Makoto Onuki50a320e2017-05-31 14:38:42 -07003429 mShortcutDumpFiles.save("restore-3.txt", this::dumpInner);
3430
Makoto Onuki377b7972016-08-09 14:43:55 -07003431 // Rescan all packages to re-publish manifest shortcuts and do other checks.
3432 rescanUpdatedPackagesLocked(userId,
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003433 0 // lastScanTime = 0; rescan all packages.
3434 );
Makoto Onuki2e210c42016-03-30 08:30:36 -07003435
Makoto Onuki50a320e2017-05-31 14:38:42 -07003436 mShortcutDumpFiles.save("restore-4.txt", this::dumpInner);
3437
3438 mShortcutDumpFiles.save("restore-5-finish.txt", pw -> {
3439 pw.print("Finish time: ");
3440 dumpCurrentTime(pw);
3441 pw.println();
3442 });
3443
Makoto Onuki2e210c42016-03-30 08:30:36 -07003444 saveUserLocked(userId);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003445 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07003446 }
3447
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003448 // === Dump ===
3449
3450 @Override
3451 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06003452 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
Makoto Onukic4361e32017-04-03 11:24:25 -07003453 dumpNoCheck(fd, pw, args);
3454 }
3455
3456 @VisibleForTesting
3457 void dumpNoCheck(FileDescriptor fd, PrintWriter pw, String[] args) {
Makoto Onuki50a320e2017-05-31 14:38:42 -07003458
3459 boolean dumpMain = true;
Makoto Onuki76269922016-07-15 14:58:54 -07003460 boolean checkin = false;
3461 boolean clear = false;
Makoto Onuki50a320e2017-05-31 14:38:42 -07003462 boolean dumpUid = false;
3463 boolean dumpFiles = false;
3464
Makoto Onuki76269922016-07-15 14:58:54 -07003465 if (args != null) {
3466 for (String arg : args) {
3467 if ("-c".equals(arg)) {
3468 checkin = true;
Makoto Onuki50a320e2017-05-31 14:38:42 -07003469
Makoto Onuki76269922016-07-15 14:58:54 -07003470 } else if ("--checkin".equals(arg)) {
3471 checkin = true;
3472 clear = true;
Makoto Onuki50a320e2017-05-31 14:38:42 -07003473
3474 } else if ("-a".equals(arg) || "--all".equals(arg)) {
3475 dumpUid = true;
3476 dumpFiles = true;
3477
3478 } else if ("-u".equals(arg) || "--uid".equals(arg)) {
3479 dumpUid = true;
3480
3481 } else if ("-f".equals(arg) || "--files".equals(arg)) {
3482 dumpFiles = true;
3483
3484 } else if ("-n".equals(arg) || "--no-main".equals(arg)) {
3485 dumpMain = false;
Makoto Onuki76269922016-07-15 14:58:54 -07003486 }
3487 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003488 }
Makoto Onuki76269922016-07-15 14:58:54 -07003489
3490 if (checkin) {
Makoto Onuki50a320e2017-05-31 14:38:42 -07003491 // Other flags are not supported for checkin.
Makoto Onuki76269922016-07-15 14:58:54 -07003492 dumpCheckin(pw, clear);
3493 } else {
Makoto Onuki50a320e2017-05-31 14:38:42 -07003494 if (dumpMain) {
3495 dumpInner(pw);
3496 pw.println();
3497 }
3498 if (dumpUid) {
3499 dumpUid(pw);
3500 pw.println();
3501 }
3502 if (dumpFiles) {
3503 dumpDumpFiles(pw);
3504 pw.println();
3505 }
Makoto Onuki76269922016-07-15 14:58:54 -07003506 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003507 }
3508
Makoto Onuki76269922016-07-15 14:58:54 -07003509 private void dumpInner(PrintWriter pw) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003510 synchronized (mLock) {
3511 final long now = injectCurrentTimeMillis();
3512 pw.print("Now: [");
3513 pw.print(now);
3514 pw.print("] ");
3515 pw.print(formatTime(now));
Makoto Onuki55046222016-03-08 10:49:47 -08003516
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003517 pw.print(" Raw last reset: [");
3518 pw.print(mRawLastResetTime);
3519 pw.print("] ");
3520 pw.print(formatTime(mRawLastResetTime));
3521
3522 final long last = getLastResetTimeLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003523 pw.print(" Last reset: [");
3524 pw.print(last);
3525 pw.print("] ");
3526 pw.print(formatTime(last));
3527
Makoto Onuki55046222016-03-08 10:49:47 -08003528 final long next = getNextResetTimeLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003529 pw.print(" Next reset: [");
3530 pw.print(next);
3531 pw.print("] ");
3532 pw.print(formatTime(next));
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003533
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003534 pw.print(" Config:");
3535 pw.print(" Max icon dim: ");
3536 pw.println(mMaxIconDimension);
3537 pw.print(" Icon format: ");
3538 pw.println(mIconPersistFormat);
3539 pw.print(" Icon quality: ");
Makoto Onuki2e210c42016-03-30 08:30:36 -07003540 pw.println(mIconPersistQuality);
Makoto Onuki0033b2a2016-04-14 17:19:16 -07003541 pw.print(" saveDelayMillis: ");
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003542 pw.println(mSaveDelayMillis);
Makoto Onuki0033b2a2016-04-14 17:19:16 -07003543 pw.print(" resetInterval: ");
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003544 pw.println(mResetInterval);
Makoto Onuki0033b2a2016-04-14 17:19:16 -07003545 pw.print(" maxUpdatesPerInterval: ");
Makoto Onukib6d35232016-04-04 15:57:17 -07003546 pw.println(mMaxUpdatesPerInterval);
Makoto Onukib08790c2016-06-23 14:05:46 -07003547 pw.print(" maxShortcutsPerActivity: ");
Makoto Onukib5a012f2016-06-21 11:13:53 -07003548 pw.println(mMaxShortcuts);
Makoto Onuki55046222016-03-08 10:49:47 -08003549 pw.println();
3550
Makoto Onuki2e210c42016-03-30 08:30:36 -07003551 pw.println(" Stats:");
3552 synchronized (mStatLock) {
Makoto Onuki085a05c2016-08-19 11:39:29 -07003553 for (int i = 0; i < Stats.COUNT; i++) {
3554 dumpStatLS(pw, " ", i);
3555 }
Makoto Onuki2e210c42016-03-30 08:30:36 -07003556 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003557
Makoto Onukia2241832016-07-06 13:28:37 -07003558 pw.println();
3559 pw.print(" #Failures: ");
3560 pw.println(mWtfCount);
3561
3562 if (mLastWtfStacktrace != null) {
3563 pw.print(" Last failure stack trace: ");
3564 pw.println(Log.getStackTraceString(mLastWtfStacktrace));
3565 }
3566
Makoto Onuki475c3652017-05-08 14:29:03 -07003567 pw.println();
3568 mShortcutBitmapSaver.dumpLocked(pw, " ");
3569
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08003570 for (int i = 0; i < mUsers.size(); i++) {
3571 pw.println();
Makoto Onukic51b2872016-05-04 15:24:50 -07003572 mUsers.valueAt(i).dump(pw, " ");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003573 }
Makoto Onuki50a320e2017-05-31 14:38:42 -07003574 }
3575 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003576
Makoto Onuki50a320e2017-05-31 14:38:42 -07003577 private void dumpUid(PrintWriter pw) {
3578 synchronized (mLock) {
3579 pw.println("** SHORTCUT MANAGER UID STATES (dumpsys shortcut -n -u)");
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003580
3581 for (int i = 0; i < mUidState.size(); i++) {
3582 final int uid = mUidState.keyAt(i);
3583 final int state = mUidState.valueAt(i);
3584 pw.print(" UID=");
3585 pw.print(uid);
3586 pw.print(" state=");
3587 pw.print(state);
3588 if (isProcessStateForeground(state)) {
3589 pw.print(" [FG]");
3590 }
3591 pw.print(" last FG=");
3592 pw.print(mUidLastForegroundElapsedTime.get(uid));
3593 pw.println();
3594 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003595 }
3596 }
3597
Makoto Onuki41066a62016-03-09 16:18:44 -08003598 static String formatTime(long time) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003599 Time tobj = new Time();
3600 tobj.set(time);
3601 return tobj.format("%Y-%m-%d %H:%M:%S");
3602 }
3603
Makoto Onuki50a320e2017-05-31 14:38:42 -07003604 private void dumpCurrentTime(PrintWriter pw) {
3605 pw.print(formatTime(injectCurrentTimeMillis()));
3606 }
3607
Makoto Onuki085a05c2016-08-19 11:39:29 -07003608 private void dumpStatLS(PrintWriter pw, String prefix, int statId) {
Makoto Onuki2e210c42016-03-30 08:30:36 -07003609 pw.print(prefix);
3610 final int count = mCountStats[statId];
3611 final long dur = mDurationStats[statId];
3612 pw.println(String.format("%s: count=%d, total=%dms, avg=%.1fms",
Makoto Onuki085a05c2016-08-19 11:39:29 -07003613 STAT_LABELS[statId], count, dur,
Makoto Onuki2e210c42016-03-30 08:30:36 -07003614 (count == 0 ? 0 : ((double) dur) / count)));
3615 }
3616
Makoto Onuki76269922016-07-15 14:58:54 -07003617 /**
3618 * Dumpsys for checkin.
3619 *
3620 * @param clear if true, clear the history information. Some other system services have this
3621 * behavior but shortcut service doesn't for now.
3622 */
3623 private void dumpCheckin(PrintWriter pw, boolean clear) {
3624 synchronized (mLock) {
3625 try {
3626 final JSONArray users = new JSONArray();
3627
3628 for (int i = 0; i < mUsers.size(); i++) {
3629 users.put(mUsers.valueAt(i).dumpCheckin(clear));
3630 }
3631
3632 final JSONObject result = new JSONObject();
3633
3634 result.put(KEY_SHORTCUT, users);
3635 result.put(KEY_LOW_RAM, injectIsLowRamDevice());
3636 result.put(KEY_ICON_SIZE, mMaxIconDimension);
3637
3638 pw.println(result.toString(1));
3639 } catch (JSONException e) {
3640 Slog.e(TAG, "Unable to write in json", e);
3641 }
3642 }
3643 }
3644
Makoto Onuki50a320e2017-05-31 14:38:42 -07003645 private void dumpDumpFiles(PrintWriter pw) {
3646 synchronized (mLock) {
3647 pw.println("** SHORTCUT MANAGER FILES (dumpsys shortcut -n -f)");
3648 mShortcutDumpFiles.dumpAll(pw);
3649 }
3650 }
3651
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003652 // === Shell support ===
3653
3654 @Override
3655 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003656 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003657
3658 enforceShell();
3659
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07003660 final long token = injectClearCallingIdentity();
3661 try {
Dianne Hackborn354736e2016-08-22 17:00:05 -07003662 final int status = (new MyShellCommand()).exec(this, in, out, err, args, callback,
3663 resultReceiver);
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07003664 resultReceiver.send(status, null);
3665 } finally {
3666 injectRestoreCallingIdentity(token);
3667 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003668 }
3669
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003670 static class CommandException extends Exception {
3671 public CommandException(String message) {
3672 super(message);
3673 }
3674 }
3675
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003676 /**
3677 * Handle "adb shell cmd".
3678 */
3679 private class MyShellCommand extends ShellCommand {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003680
3681 private int mUserId = UserHandle.USER_SYSTEM;
3682
Makoto Onuki02f338e2016-07-29 09:40:40 -07003683 private void parseOptionsLocked(boolean takeUser)
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003684 throws CommandException {
3685 String opt;
3686 while ((opt = getNextOption()) != null) {
3687 switch (opt) {
3688 case "--user":
3689 if (takeUser) {
3690 mUserId = UserHandle.parseUserArg(getNextArgRequired());
Makoto Onuki02f338e2016-07-29 09:40:40 -07003691 if (!isUserUnlockedL(mUserId)) {
Makoto Onukif34c3082016-07-13 10:25:25 -07003692 throw new CommandException(
3693 "User " + mUserId + " is not running or locked");
3694 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003695 break;
3696 }
3697 // fallthrough
3698 default:
3699 throw new CommandException("Unknown option: " + opt);
3700 }
3701 }
3702 }
3703
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003704 @Override
3705 public int onCommand(String cmd) {
3706 if (cmd == null) {
3707 return handleDefaultCommands(cmd);
3708 }
3709 final PrintWriter pw = getOutPrintWriter();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003710 try {
3711 switch (cmd) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003712 case "reset-throttling":
3713 handleResetThrottling();
3714 break;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003715 case "reset-all-throttling":
3716 handleResetAllThrottling();
3717 break;
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003718 case "override-config":
3719 handleOverrideConfig();
3720 break;
3721 case "reset-config":
3722 handleResetConfig();
3723 break;
3724 case "clear-default-launcher":
3725 handleClearDefaultLauncher();
3726 break;
3727 case "get-default-launcher":
3728 handleGetDefaultLauncher();
3729 break;
Makoto Onukiac214972016-04-04 10:19:45 -07003730 case "unload-user":
3731 handleUnloadUser();
3732 break;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003733 case "clear-shortcuts":
3734 handleClearShortcuts();
3735 break;
Makoto Onukib08790c2016-06-23 14:05:46 -07003736 case "verify-states": // hidden command to verify various internal states.
3737 handleVerifyStates();
3738 break;
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003739 default:
3740 return handleDefaultCommands(cmd);
3741 }
3742 } catch (CommandException e) {
3743 pw.println("Error: " + e.getMessage());
3744 return 1;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003745 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003746 pw.println("Success");
3747 return 0;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003748 }
3749
3750 @Override
3751 public void onHelp() {
3752 final PrintWriter pw = getOutPrintWriter();
3753 pw.println("Usage: cmd shortcut COMMAND [options ...]");
3754 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003755 pw.println("cmd shortcut reset-throttling [--user USER_ID]");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003756 pw.println(" Reset throttling for all packages and users");
3757 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003758 pw.println("cmd shortcut reset-all-throttling");
3759 pw.println(" Reset the throttling state for all users");
3760 pw.println();
Makoto Onuki4362a662016-03-08 18:59:09 -08003761 pw.println("cmd shortcut override-config CONFIG");
3762 pw.println(" Override the configuration for testing (will last until reboot)");
3763 pw.println();
3764 pw.println("cmd shortcut reset-config");
3765 pw.println(" Reset the configuration set with \"update-config\"");
3766 pw.println();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003767 pw.println("cmd shortcut clear-default-launcher [--user USER_ID]");
3768 pw.println(" Clear the cached default launcher");
3769 pw.println();
3770 pw.println("cmd shortcut get-default-launcher [--user USER_ID]");
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07003771 pw.println(" Show the default launcher");
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003772 pw.println();
Makoto Onukiac214972016-04-04 10:19:45 -07003773 pw.println("cmd shortcut unload-user [--user USER_ID]");
3774 pw.println(" Unload a user from the memory");
3775 pw.println(" (This should not affect any observable behavior)");
3776 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003777 pw.println("cmd shortcut clear-shortcuts [--user USER_ID] PACKAGE");
3778 pw.println(" Remove all shortcuts from a package, including pinned shortcuts");
3779 pw.println();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003780 }
3781
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003782 private void handleResetThrottling() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003783 synchronized (mLock) {
3784 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki4554d0e2016-03-14 15:51:41 -07003785
Makoto Onuki02f338e2016-07-29 09:40:40 -07003786 Slog.i(TAG, "cmd: handleResetThrottling: user=" + mUserId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003787
Makoto Onuki02f338e2016-07-29 09:40:40 -07003788 resetThrottlingInner(mUserId);
3789 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003790 }
3791
3792 private void handleResetAllThrottling() {
3793 Slog.i(TAG, "cmd: handleResetAllThrottling");
3794
3795 resetAllThrottlingInner();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003796 }
3797
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003798 private void handleOverrideConfig() throws CommandException {
Makoto Onuki4362a662016-03-08 18:59:09 -08003799 final String config = getNextArgRequired();
3800
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003801 Slog.i(TAG, "cmd: handleOverrideConfig: " + config);
3802
Makoto Onuki4362a662016-03-08 18:59:09 -08003803 synchronized (mLock) {
3804 if (!updateConfigurationLocked(config)) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003805 throw new CommandException("override-config failed. See logcat for details.");
Makoto Onuki4362a662016-03-08 18:59:09 -08003806 }
3807 }
Makoto Onuki4362a662016-03-08 18:59:09 -08003808 }
3809
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003810 private void handleResetConfig() {
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003811 Slog.i(TAG, "cmd: handleResetConfig");
3812
Makoto Onuki4362a662016-03-08 18:59:09 -08003813 synchronized (mLock) {
3814 loadConfigurationLocked();
3815 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003816 }
3817
3818 private void clearLauncher() {
3819 synchronized (mLock) {
Makoto Onuki10305202016-07-14 18:14:08 -07003820 getUserShortcutsLocked(mUserId).forceClearLauncher();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003821 }
3822 }
3823
3824 private void showLauncher() {
3825 synchronized (mLock) {
3826 // This ensures to set the cached launcher. Package name doesn't matter.
3827 hasShortcutHostPermissionInner("-", mUserId);
3828
3829 getOutPrintWriter().println("Launcher: "
Makoto Onuki10305202016-07-14 18:14:08 -07003830 + getUserShortcutsLocked(mUserId).getLastKnownLauncher());
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003831 }
3832 }
3833
3834 private void handleClearDefaultLauncher() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003835 synchronized (mLock) {
3836 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003837
Makoto Onuki02f338e2016-07-29 09:40:40 -07003838 clearLauncher();
3839 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003840 }
3841
3842 private void handleGetDefaultLauncher() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003843 synchronized (mLock) {
3844 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003845
Makoto Onuki02f338e2016-07-29 09:40:40 -07003846 clearLauncher();
3847 showLauncher();
3848 }
Makoto Onuki4362a662016-03-08 18:59:09 -08003849 }
Makoto Onukiac214972016-04-04 10:19:45 -07003850
3851 private void handleUnloadUser() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003852 synchronized (mLock) {
3853 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onukiac214972016-04-04 10:19:45 -07003854
Makoto Onuki02f338e2016-07-29 09:40:40 -07003855 Slog.i(TAG, "cmd: handleUnloadUser: user=" + mUserId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003856
Makoto Onuki01ce92b2017-04-28 12:24:16 -07003857 ShortcutService.this.handleStopUser(mUserId);
Makoto Onuki02f338e2016-07-29 09:40:40 -07003858 }
Makoto Onukiac214972016-04-04 10:19:45 -07003859 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003860
3861 private void handleClearShortcuts() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003862 synchronized (mLock) {
3863 parseOptionsLocked(/* takeUser =*/ true);
3864 final String packageName = getNextArgRequired();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003865
Makoto Onuki02f338e2016-07-29 09:40:40 -07003866 Slog.i(TAG, "cmd: handleClearShortcuts: user" + mUserId + ", " + packageName);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003867
Makoto Onuki02f338e2016-07-29 09:40:40 -07003868 ShortcutService.this.cleanUpPackageForAllLoadedUsers(packageName, mUserId,
3869 /* appStillExists = */ true);
3870 }
Makoto Onukib08790c2016-06-23 14:05:46 -07003871 }
3872
3873 private void handleVerifyStates() throws CommandException {
3874 try {
3875 verifyStatesForce(); // This will throw when there's an issue.
3876 } catch (Throwable th) {
3877 throw new CommandException(th.getMessage() + "\n" + Log.getStackTraceString(th));
3878 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003879 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003880 }
3881
3882 // === Unit test support ===
3883
3884 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07003885 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003886 long injectCurrentTimeMillis() {
3887 return System.currentTimeMillis();
3888 }
3889
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003890 @VisibleForTesting
3891 long injectElapsedRealtime() {
3892 return SystemClock.elapsedRealtime();
3893 }
3894
Makoto Onuki475c3652017-05-08 14:29:03 -07003895 @VisibleForTesting
3896 long injectUptimeMillis() {
3897 return SystemClock.uptimeMillis();
3898 }
3899
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003900 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07003901 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003902 int injectBinderCallingUid() {
3903 return getCallingUid();
3904 }
3905
Makoto Onuki31459242016-03-22 11:12:18 -07003906 private int getCallingUserId() {
Makoto Onuki4554d0e2016-03-14 15:51:41 -07003907 return UserHandle.getUserId(injectBinderCallingUid());
3908 }
3909
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07003910 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07003911 @VisibleForTesting
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07003912 long injectClearCallingIdentity() {
3913 return Binder.clearCallingIdentity();
3914 }
3915
3916 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07003917 @VisibleForTesting
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07003918 void injectRestoreCallingIdentity(long token) {
3919 Binder.restoreCallingIdentity(token);
3920 }
3921
Makoto Onuki33663282016-08-22 16:19:04 -07003922 // Injection point.
3923 @VisibleForTesting
3924 String injectBuildFingerprint() {
3925 return Build.FINGERPRINT;
3926 }
3927
Makoto Onukide667372016-03-15 14:29:20 -07003928 final void wtf(String message) {
Makoto Onukib08790c2016-06-23 14:05:46 -07003929 wtf(message, /* exception= */ null);
Makoto Onukide667372016-03-15 14:29:20 -07003930 }
3931
Makoto Onuki2e210c42016-03-30 08:30:36 -07003932 // Injection point.
Makoto Onukia2241832016-07-06 13:28:37 -07003933 void wtf(String message, Throwable e) {
3934 if (e == null) {
3935 e = new RuntimeException("Stacktrace");
3936 }
3937 synchronized (mLock) {
3938 mWtfCount++;
3939 mLastWtfStacktrace = new Exception("Last failure was logged here:");
3940 }
Makoto Onukide667372016-03-15 14:29:20 -07003941 Slog.wtf(TAG, message, e);
3942 }
3943
Makoto Onuki31459242016-03-22 11:12:18 -07003944 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003945 File injectSystemDataPath() {
3946 return Environment.getDataSystemDirectory();
3947 }
3948
Makoto Onuki31459242016-03-22 11:12:18 -07003949 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003950 File injectUserDataPath(@UserIdInt int userId) {
Makoto Onuki55046222016-03-08 10:49:47 -08003951 return new File(Environment.getDataSystemCeDirectory(userId), DIRECTORY_PER_USER);
3952 }
3953
Makoto Onuki50a320e2017-05-31 14:38:42 -07003954 public File getDumpPath() {
3955 return new File(injectUserDataPath(UserHandle.USER_SYSTEM), DIRECTORY_DUMP);
3956 }
3957
Makoto Onuki4362a662016-03-08 18:59:09 -08003958 @VisibleForTesting
Makoto Onuki55046222016-03-08 10:49:47 -08003959 boolean injectIsLowRamDevice() {
3960 return ActivityManager.isLowRamDeviceStatic();
3961 }
3962
Makoto Onuki31459242016-03-22 11:12:18 -07003963 @VisibleForTesting
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003964 void injectRegisterUidObserver(IUidObserver observer, int which) {
3965 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003966 ActivityManager.getService().registerUidObserver(observer, which,
Dianne Hackborn5614bf52016-11-07 17:26:41 -08003967 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003968 } catch (RemoteException shouldntHappen) {
3969 }
3970 }
3971
Makoto Onuki55046222016-03-08 10:49:47 -08003972 File getUserBitmapFilePath(@UserIdInt int userId) {
3973 return new File(injectUserDataPath(userId), DIRECTORY_BITMAPS);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003974 }
3975
3976 @VisibleForTesting
Makoto Onuki31459242016-03-22 11:12:18 -07003977 SparseArray<ShortcutUser> getShortcutsForTest() {
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08003978 return mUsers;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003979 }
3980
3981 @VisibleForTesting
Makoto Onukib5a012f2016-06-21 11:13:53 -07003982 int getMaxShortcutsForTest() {
3983 return mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003984 }
3985
3986 @VisibleForTesting
Makoto Onukib6d35232016-04-04 15:57:17 -07003987 int getMaxUpdatesPerIntervalForTest() {
3988 return mMaxUpdatesPerInterval;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003989 }
3990
3991 @VisibleForTesting
Makoto Onuki4362a662016-03-08 18:59:09 -08003992 long getResetIntervalForTest() {
3993 return mResetInterval;
Makoto Onuki55046222016-03-08 10:49:47 -08003994 }
3995
3996 @VisibleForTesting
Makoto Onuki4362a662016-03-08 18:59:09 -08003997 int getMaxIconDimensionForTest() {
3998 return mMaxIconDimension;
3999 }
4000
4001 @VisibleForTesting
4002 CompressFormat getIconPersistFormatForTest() {
4003 return mIconPersistFormat;
4004 }
4005
4006 @VisibleForTesting
4007 int getIconPersistQualityForTest() {
4008 return mIconPersistQuality;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08004009 }
Makoto Onuki41066a62016-03-09 16:18:44 -08004010
4011 @VisibleForTesting
Makoto Onuki22fcc682016-05-17 14:52:19 -07004012 ShortcutPackage getPackageShortcutForTest(String packageName, int userId) {
Makoto Onuki41066a62016-03-09 16:18:44 -08004013 synchronized (mLock) {
Makoto Onuki31459242016-03-22 11:12:18 -07004014 final ShortcutUser user = mUsers.get(userId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07004015 if (user == null) return null;
4016
Makoto Onuki22fcc682016-05-17 14:52:19 -07004017 return user.getAllPackagesForTest().get(packageName);
4018 }
4019 }
4020
4021 @VisibleForTesting
4022 ShortcutInfo getPackageShortcutForTest(String packageName, String shortcutId, int userId) {
4023 synchronized (mLock) {
Makoto Onukif34c3082016-07-13 10:25:25 -07004024 final ShortcutPackage pkg = getPackageShortcutForTest(packageName, userId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07004025 if (pkg == null) return null;
4026
4027 return pkg.findShortcutById(shortcutId);
Makoto Onuki41066a62016-03-09 16:18:44 -08004028 }
4029 }
Makoto Onuki7001a612016-05-27 13:24:28 -07004030
Makoto Onukifac592f2016-11-21 13:41:32 -08004031 @VisibleForTesting
4032 ShortcutLauncher getLauncherShortcutForTest(String packageName, int userId) {
4033 synchronized (mLock) {
4034 final ShortcutUser user = mUsers.get(userId);
4035 if (user == null) return null;
4036
4037 return user.getAllLaunchersForTest().get(PackageWithUser.of(userId, packageName));
4038 }
4039 }
4040
Makoto Onuki2d895c32016-12-02 15:48:40 -08004041 @VisibleForTesting
4042 ShortcutRequestPinProcessor getShortcutRequestPinProcessorForTest() {
4043 return mShortcutRequestPinProcessor;
4044 }
4045
Makoto Onuki7001a612016-05-27 13:24:28 -07004046 /**
4047 * Control whether {@link #verifyStates} should be performed. We always perform it during unit
4048 * tests.
4049 */
4050 @VisibleForTesting
4051 boolean injectShouldPerformVerification() {
4052 return DEBUG;
4053 }
4054
4055 /**
4056 * Check various internal states and throws if there's any inconsistency.
4057 * This is normally only enabled during unit tests.
4058 */
4059 final void verifyStates() {
4060 if (injectShouldPerformVerification()) {
4061 verifyStatesInner();
4062 }
4063 }
4064
Makoto Onukib08790c2016-06-23 14:05:46 -07004065 private final void verifyStatesForce() {
4066 verifyStatesInner();
4067 }
4068
Makoto Onuki7001a612016-05-27 13:24:28 -07004069 private void verifyStatesInner() {
Makoto Onuki10305202016-07-14 18:14:08 -07004070 synchronized (mLock) {
Makoto Onuki7001a612016-05-27 13:24:28 -07004071 forEachLoadedUserLocked(u -> u.forAllPackageItems(ShortcutPackageItem::verifyStates));
4072 }
4073 }
Makoto Onuki475c3652017-05-08 14:29:03 -07004074
4075 @VisibleForTesting
4076 void waitForBitmapSavesForTest() {
4077 synchronized (mLock) {
4078 mShortcutBitmapSaver.waitForAllSavesLocked();
4079 }
4080 }
Makoto Onuki41066a62016-03-09 16:18:44 -08004081}