blob: 057e781e76dd43af782cf2eb23a24b045010a1b8 [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;
Makoto Onuki2d895c32016-12-02 15:48:40 -080048import android.content.pm.ShortcutManager;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080049import android.content.pm.ShortcutServiceInternal;
50import android.content.pm.ShortcutServiceInternal.ShortcutChangeListener;
Makoto Onuki2d895c32016-12-02 15:48:40 -080051import android.content.pm.UserInfo;
Makoto Onuki157b1622016-06-02 16:13:10 -070052import android.content.res.Resources;
Makoto Onuki22fcc682016-05-17 14:52:19 -070053import android.content.res.XmlResourceParser;
Makoto Onuki55046222016-03-08 10:49:47 -080054import android.graphics.Bitmap;
55import android.graphics.Bitmap.CompressFormat;
Makoto Onuki55046222016-03-08 10:49:47 -080056import android.graphics.Canvas;
57import android.graphics.RectF;
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;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080062import android.os.Environment;
Makoto Onuki2e210c42016-03-30 08:30:36 -070063import android.os.FileUtils;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080064import android.os.Handler;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070065import android.os.LocaleList;
Makoto Onukiaa8b94a2016-03-17 13:14:05 -070066import android.os.Looper;
Makoto Onuki55046222016-03-08 10:49:47 -080067import android.os.ParcelFileDescriptor;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080068import android.os.PersistableBundle;
69import android.os.Process;
70import android.os.RemoteException;
71import android.os.ResultReceiver;
Makoto Onuki55046222016-03-08 10:49:47 -080072import android.os.SELinux;
Makoto Onukib08790c2016-06-23 14:05:46 -070073import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070074import android.os.ShellCallback;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080075import android.os.ShellCommand;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -070076import android.os.SystemClock;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080077import android.os.UserHandle;
Makoto Onukicdc78f72016-03-21 15:47:52 -070078import android.os.UserManager;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080079import android.text.TextUtils;
80import android.text.format.Time;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080081import android.util.ArraySet;
82import android.util.AtomicFile;
Makoto Onuki4362a662016-03-08 18:59:09 -080083import android.util.KeyValueListParser;
Makoto Onukiac042502016-05-20 16:39:42 -070084import android.util.Log;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080085import android.util.Slog;
86import android.util.SparseArray;
Makoto Onuki02f338e2016-07-29 09:40:40 -070087import android.util.SparseBooleanArray;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -070088import android.util.SparseIntArray;
89import android.util.SparseLongArray;
Makoto Onuki55046222016-03-08 10:49:47 -080090import android.util.TypedValue;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080091import android.util.Xml;
Makoto Onukib08790c2016-06-23 14:05:46 -070092import android.view.IWindowManager;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080093
94import com.android.internal.annotations.GuardedBy;
95import com.android.internal.annotations.VisibleForTesting;
96import com.android.internal.os.BackgroundThread;
97import com.android.internal.util.FastXmlSerializer;
98import com.android.internal.util.Preconditions;
99import com.android.server.LocalServices;
100import com.android.server.SystemService;
Makoto Onukid99c6f02016-03-28 11:02:54 -0700101import com.android.server.pm.ShortcutUser.PackageWithUser;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800102
103import libcore.io.IoUtils;
104
Makoto Onuki76269922016-07-15 14:58:54 -0700105import org.json.JSONArray;
106import org.json.JSONException;
107import org.json.JSONObject;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800108import org.xmlpull.v1.XmlPullParser;
109import org.xmlpull.v1.XmlPullParserException;
110import org.xmlpull.v1.XmlSerializer;
111
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700112import java.io.BufferedInputStream;
113import java.io.BufferedOutputStream;
114import java.io.ByteArrayInputStream;
115import java.io.ByteArrayOutputStream;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800116import java.io.File;
117import java.io.FileDescriptor;
118import java.io.FileInputStream;
119import java.io.FileNotFoundException;
120import java.io.FileOutputStream;
121import java.io.IOException;
Makoto Onuki55046222016-03-08 10:49:47 -0800122import java.io.InputStream;
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700123import java.io.OutputStream;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800124import java.io.PrintWriter;
Makoto Onuki7001a612016-05-27 13:24:28 -0700125import java.lang.annotation.Retention;
126import java.lang.annotation.RetentionPolicy;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800127import java.net.URISyntaxException;
128import java.nio.charset.StandardCharsets;
129import java.util.ArrayList;
Makoto Onuki22fcc682016-05-17 14:52:19 -0700130import java.util.Collections;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800131import java.util.List;
Makoto Onukic51b2872016-05-04 15:24:50 -0700132import java.util.concurrent.atomic.AtomicBoolean;
Makoto Onuki2e210c42016-03-30 08:30:36 -0700133import java.util.function.Consumer;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800134import java.util.function.Predicate;
135
136/**
137 * TODO:
Makoto Onuki22fcc682016-05-17 14:52:19 -0700138 * - getIconMaxWidth()/getIconMaxHeight() should use xdpi and ydpi.
Makoto Onukib5a012f2016-06-21 11:13:53 -0700139 * -> But TypedValue.applyDimension() doesn't differentiate x and y..?
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800140 *
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700141 * - Detect when already registered instances are passed to APIs again, which might break
Makoto Onukib08790c2016-06-23 14:05:46 -0700142 * internal bitmap handling.
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800143 */
144public class ShortcutService extends IShortcutService.Stub {
Makoto Onuki55046222016-03-08 10:49:47 -0800145 static final String TAG = "ShortcutService";
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800146
Makoto Onuki7001a612016-05-27 13:24:28 -0700147 static final boolean DEBUG = false; // STOPSHIP if true
Makoto Onuki41066a62016-03-09 16:18:44 -0800148 static final boolean DEBUG_LOAD = false; // STOPSHIP if true
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700149 static final boolean DEBUG_PROCSTATE = false; // STOPSHIP if true
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800150
Makoto Onuki4362a662016-03-08 18:59:09 -0800151 @VisibleForTesting
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700152 static final long DEFAULT_RESET_INTERVAL_SEC = 24 * 60 * 60; // 1 day
Makoto Onuki4362a662016-03-08 18:59:09 -0800153
154 @VisibleForTesting
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700155 static final int DEFAULT_MAX_UPDATES_PER_INTERVAL = 10;
Makoto Onuki4362a662016-03-08 18:59:09 -0800156
157 @VisibleForTesting
158 static final int DEFAULT_MAX_SHORTCUTS_PER_APP = 5;
159
160 @VisibleForTesting
161 static final int DEFAULT_MAX_ICON_DIMENSION_DP = 96;
162
163 @VisibleForTesting
164 static final int DEFAULT_MAX_ICON_DIMENSION_LOWRAM_DP = 48;
165
166 @VisibleForTesting
167 static final String DEFAULT_ICON_PERSIST_FORMAT = CompressFormat.PNG.name();
168
169 @VisibleForTesting
170 static final int DEFAULT_ICON_PERSIST_QUALITY = 100;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800171
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700172 @VisibleForTesting
173 static final int DEFAULT_SAVE_DELAY_MS = 3000;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800174
175 @VisibleForTesting
176 static final String FILENAME_BASE_STATE = "shortcut_service.xml";
177
178 @VisibleForTesting
179 static final String DIRECTORY_PER_USER = "shortcut_service";
180
181 @VisibleForTesting
182 static final String FILENAME_USER_PACKAGES = "shortcuts.xml";
183
Makoto Onuki55046222016-03-08 10:49:47 -0800184 static final String DIRECTORY_BITMAPS = "bitmaps";
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800185
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700186 private static final String TAG_ROOT = "root";
187 private static final String TAG_LAST_RESET_TIME = "last_reset_time";
Makoto Onuki55046222016-03-08 10:49:47 -0800188
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700189 private static final String ATTR_VALUE = "value";
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800190
Makoto Onukib08790c2016-06-23 14:05:46 -0700191 private static final String LAUNCHER_INTENT_CATEGORY = Intent.CATEGORY_LAUNCHER;
192
Makoto Onuki76269922016-07-15 14:58:54 -0700193 private static final String KEY_SHORTCUT = "shortcut";
194 private static final String KEY_LOW_RAM = "lowRam";
195 private static final String KEY_ICON_SIZE = "iconSize";
196
Makoto Onuki2d895c32016-12-02 15:48:40 -0800197 private static final String DUMMY_MAIN_ACTIVITY = "android.__dummy__";
198
Makoto Onuki4362a662016-03-08 18:59:09 -0800199 @VisibleForTesting
200 interface ConfigConstants {
201 /**
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700202 * Key name for the save delay, in milliseconds. (int)
203 */
204 String KEY_SAVE_DELAY_MILLIS = "save_delay_ms";
205
206 /**
Makoto Onuki4362a662016-03-08 18:59:09 -0800207 * Key name for the throttling reset interval, in seconds. (long)
208 */
209 String KEY_RESET_INTERVAL_SEC = "reset_interval_sec";
210
211 /**
212 * Key name for the max number of modifying API calls per app for every interval. (int)
213 */
Makoto Onukib6d35232016-04-04 15:57:17 -0700214 String KEY_MAX_UPDATES_PER_INTERVAL = "max_updates_per_interval";
Makoto Onuki4362a662016-03-08 18:59:09 -0800215
216 /**
217 * Key name for the max icon dimensions in DP, for non-low-memory devices.
218 */
219 String KEY_MAX_ICON_DIMENSION_DP = "max_icon_dimension_dp";
220
221 /**
222 * Key name for the max icon dimensions in DP, for low-memory devices.
223 */
224 String KEY_MAX_ICON_DIMENSION_DP_LOWRAM = "max_icon_dimension_dp_lowram";
225
226 /**
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700227 * Key name for the max dynamic shortcuts per activity. (int)
Makoto Onuki4362a662016-03-08 18:59:09 -0800228 */
229 String KEY_MAX_SHORTCUTS = "max_shortcuts";
230
231 /**
Makoto Onuki41066a62016-03-09 16:18:44 -0800232 * Key name for icon compression quality, 0-100.
Makoto Onuki4362a662016-03-08 18:59:09 -0800233 */
234 String KEY_ICON_QUALITY = "icon_quality";
235
236 /**
237 * Key name for icon compression format: "PNG", "JPEG" or "WEBP"
238 */
239 String KEY_ICON_FORMAT = "icon_format";
240 }
241
Makoto Onuki41066a62016-03-09 16:18:44 -0800242 final Context mContext;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800243
244 private final Object mLock = new Object();
245
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700246 private static List<ResolveInfo> EMPTY_RESOLVE_INFO = new ArrayList<>(0);
247
Mark Renoufe065f7c2016-11-01 11:48:24 -0400248 // Temporarily reverted to anonymous inner class form due to: b/32554459
249 private static Predicate<ResolveInfo> ACTIVITY_NOT_EXPORTED = new Predicate<ResolveInfo>() {
250 public boolean test(ResolveInfo ri) {
251 return !ri.activityInfo.exported;
252 }
253 };
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700254
Mark Renoufe065f7c2016-11-01 11:48:24 -0400255 // Temporarily reverted to anonymous inner class form due to: b/32554459
256 private static Predicate<PackageInfo> PACKAGE_NOT_INSTALLED = new Predicate<PackageInfo>() {
257 public boolean test(PackageInfo pi) {
258 return !isInstalled(pi);
259 }
260 };
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700261
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800262 private final Handler mHandler;
263
264 @GuardedBy("mLock")
265 private final ArrayList<ShortcutChangeListener> mListeners = new ArrayList<>(1);
266
267 @GuardedBy("mLock")
268 private long mRawLastResetTime;
269
270 /**
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -0800271 * User ID -> UserShortcuts
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800272 */
273 @GuardedBy("mLock")
Makoto Onuki31459242016-03-22 11:12:18 -0700274 private final SparseArray<ShortcutUser> mUsers = new SparseArray<>();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800275
276 /**
Makoto Onukib5a012f2016-06-21 11:13:53 -0700277 * Max number of dynamic + manifest shortcuts that each application can have at a time.
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800278 */
Makoto Onukib5a012f2016-06-21 11:13:53 -0700279 private int mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800280
281 /**
Makoto Onukib6d35232016-04-04 15:57:17 -0700282 * Max number of updating API calls that each application can make during the interval.
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800283 */
Makoto Onukib6d35232016-04-04 15:57:17 -0700284 int mMaxUpdatesPerInterval;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800285
286 /**
287 * Actual throttling-reset interval. By default it's a day.
288 */
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800289 private long mResetInterval;
290
Makoto Onuki55046222016-03-08 10:49:47 -0800291 /**
292 * Icon max width/height in pixels.
293 */
294 private int mMaxIconDimension;
295
Makoto Onuki4362a662016-03-08 18:59:09 -0800296 private CompressFormat mIconPersistFormat;
297 private int mIconPersistQuality;
Makoto Onuki55046222016-03-08 10:49:47 -0800298
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700299 private int mSaveDelayMillis;
300
Makoto Onuki0acbb142016-03-22 17:02:57 -0700301 private final IPackageManager mIPackageManager;
Makoto Onuki2d5b4652016-03-11 16:09:54 -0800302 private final PackageManagerInternal mPackageManagerInternal;
Makoto Onukicdc78f72016-03-21 15:47:52 -0700303 private final UserManager mUserManager;
Makoto Onukiac042502016-05-20 16:39:42 -0700304 private final UsageStatsManagerInternal mUsageStatsManagerInternal;
Makoto Onuki33525d22016-08-03 15:45:24 -0700305 private final ActivityManagerInternal mActivityManagerInternal;
Makoto Onuki2d5b4652016-03-11 16:09:54 -0800306
Makoto Onuki2d895c32016-12-02 15:48:40 -0800307 private final ShortcutRequestPinProcessor mShortcutRequestPinProcessor;
308
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700309 @GuardedBy("mLock")
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700310 final SparseIntArray mUidState = new SparseIntArray();
311
312 @GuardedBy("mLock")
313 final SparseLongArray mUidLastForegroundElapsedTime = new SparseLongArray();
314
315 @GuardedBy("mLock")
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700316 private List<Integer> mDirtyUserIds = new ArrayList<>();
317
Makoto Onukic51b2872016-05-04 15:24:50 -0700318 private final AtomicBoolean mBootCompleted = new AtomicBoolean();
319
Makoto Onuki905e8852016-03-28 10:40:58 -0700320 private static final int PACKAGE_MATCH_FLAGS =
321 PackageManager.MATCH_DIRECT_BOOT_AWARE
Makoto Onukib08790c2016-06-23 14:05:46 -0700322 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE
323 | PackageManager.MATCH_UNINSTALLED_PACKAGES;
Makoto Onuki905e8852016-03-28 10:40:58 -0700324
Makoto Onuki02f338e2016-07-29 09:40:40 -0700325 @GuardedBy("mLock")
326 final SparseBooleanArray mUnlockedUsers = new SparseBooleanArray();
327
Makoto Onuki2e210c42016-03-30 08:30:36 -0700328 // Stats
329 @VisibleForTesting
330 interface Stats {
331 int GET_DEFAULT_HOME = 0;
332 int GET_PACKAGE_INFO = 1;
333 int GET_PACKAGE_INFO_WITH_SIG = 2;
334 int GET_APPLICATION_INFO = 3;
335 int LAUNCHER_PERMISSION_CHECK = 4;
Makoto Onuki6c1dbd52016-05-02 15:19:32 -0700336 int CLEANUP_DANGLING_BITMAPS = 5;
Makoto Onukib08790c2016-06-23 14:05:46 -0700337 int GET_ACTIVITY_WITH_METADATA = 6;
Makoto Onuki6dd9fb72016-06-01 13:55:54 -0700338 int GET_INSTALLED_PACKAGES = 7;
Makoto Onuki22fcc682016-05-17 14:52:19 -0700339 int CHECK_PACKAGE_CHANGES = 8;
Makoto Onuki157b1622016-06-02 16:13:10 -0700340 int GET_APPLICATION_RESOURCES = 9;
341 int RESOURCE_NAME_LOOKUP = 10;
Makoto Onukib08790c2016-06-23 14:05:46 -0700342 int GET_LAUNCHER_ACTIVITY = 11;
343 int CHECK_LAUNCHER_ACTIVITY = 12;
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700344 int IS_ACTIVITY_ENABLED = 13;
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700345 int PACKAGE_UPDATE_CHECK = 14;
Makoto Onuki085a05c2016-08-19 11:39:29 -0700346 int ASYNC_PRELOAD_USER_DELAY = 15;
Makoto Onuki2d895c32016-12-02 15:48:40 -0800347 int GET_DEFAULT_LAUNCHER = 16;
Makoto Onuki2e210c42016-03-30 08:30:36 -0700348
Makoto Onuki2d895c32016-12-02 15:48:40 -0800349 int COUNT = GET_DEFAULT_LAUNCHER + 1;
Makoto Onuki2e210c42016-03-30 08:30:36 -0700350 }
351
Makoto Onuki085a05c2016-08-19 11:39:29 -0700352 private static final String[] STAT_LABELS = {
353 "getHomeActivities()",
354 "Launcher permission check",
355 "getPackageInfo()",
356 "getPackageInfo(SIG)",
357 "getApplicationInfo",
358 "cleanupDanglingBitmaps",
359 "getActivity+metadata",
360 "getInstalledPackages",
361 "checkPackageChanges",
362 "getApplicationResources",
363 "resourceNameLookup",
364 "getLauncherActivity",
365 "checkLauncherActivity",
366 "isActivityEnabled",
367 "packageUpdateCheck",
Makoto Onuki2d895c32016-12-02 15:48:40 -0800368 "asyncPreloadUserDelay",
369 "getDefaultLauncher()"
Makoto Onuki085a05c2016-08-19 11:39:29 -0700370 };
371
Makoto Onuki2e210c42016-03-30 08:30:36 -0700372 final Object mStatLock = new Object();
373
374 @GuardedBy("mStatLock")
375 private final int[] mCountStats = new int[Stats.COUNT];
376
377 @GuardedBy("mStatLock")
378 private final long[] mDurationStats = new long[Stats.COUNT];
379
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700380 private static final int PROCESS_STATE_FOREGROUND_THRESHOLD =
381 ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
382
Makoto Onuki7001a612016-05-27 13:24:28 -0700383 static final int OPERATION_SET = 0;
384 static final int OPERATION_ADD = 1;
385 static final int OPERATION_UPDATE = 2;
386
387 /** @hide */
388 @IntDef(value = {
389 OPERATION_SET,
390 OPERATION_ADD,
391 OPERATION_UPDATE
Makoto Onukib08790c2016-06-23 14:05:46 -0700392 })
Makoto Onuki7001a612016-05-27 13:24:28 -0700393 @Retention(RetentionPolicy.SOURCE)
Makoto Onukib08790c2016-06-23 14:05:46 -0700394 @interface ShortcutOperation {
395 }
Makoto Onuki7001a612016-05-27 13:24:28 -0700396
Makoto Onukia2241832016-07-06 13:28:37 -0700397 @GuardedBy("mLock")
398 private int mWtfCount = 0;
399
400 @GuardedBy("mLock")
401 private Exception mLastWtfStacktrace;
402
Makoto Onukifc4cf2d2016-08-24 11:10:26 -0700403 static class InvalidFileFormatException extends Exception {
404 public InvalidFileFormatException(String message, Throwable cause) {
405 super(message, cause);
406 }
407 }
408
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800409 public ShortcutService(Context context) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700410 this(context, BackgroundThread.get().getLooper(), /*onyForPackgeManagerApis*/ false);
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700411 }
412
413 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700414 ShortcutService(Context context, Looper looper, boolean onlyForPackageManagerApis) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800415 mContext = Preconditions.checkNotNull(context);
416 LocalServices.addService(ShortcutServiceInternal.class, new LocalService());
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700417 mHandler = new Handler(looper);
Makoto Onuki0acbb142016-03-22 17:02:57 -0700418 mIPackageManager = AppGlobals.getPackageManager();
Makoto Onukiac042502016-05-20 16:39:42 -0700419 mPackageManagerInternal = Preconditions.checkNotNull(
420 LocalServices.getService(PackageManagerInternal.class));
421 mUserManager = Preconditions.checkNotNull(context.getSystemService(UserManager.class));
422 mUsageStatsManagerInternal = Preconditions.checkNotNull(
423 LocalServices.getService(UsageStatsManagerInternal.class));
Makoto Onuki33525d22016-08-03 15:45:24 -0700424 mActivityManagerInternal = Preconditions.checkNotNull(
425 LocalServices.getService(ActivityManagerInternal.class));
Makoto Onukicdc78f72016-03-21 15:47:52 -0700426
Makoto Onuki2d895c32016-12-02 15:48:40 -0800427 mShortcutRequestPinProcessor = new ShortcutRequestPinProcessor(this, mLock);
428
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700429 if (onlyForPackageManagerApis) {
430 return; // Don't do anything further. For unit tests only.
431 }
432
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700433 // Register receivers.
434
435 // We need to set a priority, so let's just not use PackageMonitor for now.
436 // TODO Refactor PackageMonitor to support priorities.
437 final IntentFilter packageFilter = new IntentFilter();
438 packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
439 packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
440 packageFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
441 packageFilter.addAction(Intent.ACTION_PACKAGE_DATA_CLEARED);
442 packageFilter.addDataScheme("package");
443 packageFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
444 mContext.registerReceiverAsUser(mPackageMonitor, UserHandle.ALL,
445 packageFilter, null, mHandler);
446
Makoto Onuki10305202016-07-14 18:14:08 -0700447 final IntentFilter preferedActivityFilter = new IntentFilter();
448 preferedActivityFilter.addAction(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
449 preferedActivityFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
450 mContext.registerReceiverAsUser(mPackageMonitor, UserHandle.ALL,
451 preferedActivityFilter, null, mHandler);
452
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700453 final IntentFilter localeFilter = new IntentFilter();
454 localeFilter.addAction(Intent.ACTION_LOCALE_CHANGED);
455 localeFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
456 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL,
457 localeFilter, null, mHandler);
Makoto Onukif34c3082016-07-13 10:25:25 -0700458
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700459 injectRegisterUidObserver(mUidObserver, ActivityManager.UID_OBSERVER_PROCSTATE
460 | ActivityManager.UID_OBSERVER_GONE);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800461 }
462
Makoto Onuki2e210c42016-03-30 08:30:36 -0700463 void logDurationStat(int statId, long start) {
464 synchronized (mStatLock) {
465 mCountStats[statId]++;
Makoto Onuki6c1dbd52016-05-02 15:19:32 -0700466 mDurationStats[statId] += (injectElapsedRealtime() - start);
Makoto Onuki2e210c42016-03-30 08:30:36 -0700467 }
468 }
469
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700470 public String injectGetLocaleTagsForUser(@UserIdInt int userId) {
471 // TODO This should get the per-user locale. b/30123329 b/30119489
472 return LocaleList.getDefault().toLanguageTags();
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700473 }
474
475 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Makoto Onukib08790c2016-06-23 14:05:46 -0700476 @Override
477 public void onUidStateChanged(int uid, int procState) throws RemoteException {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700478 handleOnUidStateChanged(uid, procState);
479 }
480
Makoto Onukib08790c2016-06-23 14:05:46 -0700481 @Override
Dianne Hackborne07641d2016-11-09 15:07:23 -0800482 public void onUidGone(int uid, boolean disabled) throws RemoteException {
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800483 handleOnUidStateChanged(uid, ActivityManager.PROCESS_STATE_NONEXISTENT);
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700484 }
485
Makoto Onukib08790c2016-06-23 14:05:46 -0700486 @Override
487 public void onUidActive(int uid) throws RemoteException {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700488 }
489
Makoto Onukib08790c2016-06-23 14:05:46 -0700490 @Override
Dianne Hackborne07641d2016-11-09 15:07:23 -0800491 public void onUidIdle(int uid, boolean disabled) throws RemoteException {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700492 }
493 };
494
495 void handleOnUidStateChanged(int uid, int procState) {
496 if (DEBUG_PROCSTATE) {
497 Slog.d(TAG, "onUidStateChanged: uid=" + uid + " state=" + procState);
498 }
499 synchronized (mLock) {
500 mUidState.put(uid, procState);
501
502 // We need to keep track of last time an app comes to foreground.
503 // See ShortcutPackage.getApiCallCount() for how it's used.
504 // It doesn't have to be persisted, but it needs to be the elapsed time.
505 if (isProcessStateForeground(procState)) {
506 mUidLastForegroundElapsedTime.put(uid, injectElapsedRealtime());
507 }
508 }
509 }
510
511 private boolean isProcessStateForeground(int processState) {
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800512 return processState <= PROCESS_STATE_FOREGROUND_THRESHOLD;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700513 }
514
515 boolean isUidForegroundLocked(int uid) {
516 if (uid == Process.SYSTEM_UID) {
517 // IUidObserver doesn't report the state of SYSTEM, but it always has bound services,
518 // so it's foreground anyway.
519 return true;
520 }
Makoto Onuki33525d22016-08-03 15:45:24 -0700521 // First, check with the local cache.
522 if (isProcessStateForeground(mUidState.get(uid, ActivityManager.MAX_PROCESS_STATE))) {
523 return true;
524 }
525 // If the cache says background, reach out to AM. Since it'll internally need to hold
526 // the AM lock, we use it as a last resort.
527 return isProcessStateForeground(mActivityManagerInternal.getUidProcessState(uid));
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700528 }
529
530 long getUidLastForegroundElapsedTimeLocked(int uid) {
531 return mUidLastForegroundElapsedTime.get(uid);
532 }
533
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800534 /**
535 * System service lifecycle.
536 */
537 public static final class Lifecycle extends SystemService {
538 final ShortcutService mService;
539
540 public Lifecycle(Context context) {
541 super(context);
542 mService = new ShortcutService(context);
543 }
544
545 @Override
546 public void onStart() {
547 publishBinderService(Context.SHORTCUT_SERVICE, mService);
548 }
549
550 @Override
551 public void onBootPhase(int phase) {
552 mService.onBootPhase(phase);
553 }
554
555 @Override
556 public void onCleanupUser(int userHandle) {
Makoto Onukicdc78f72016-03-21 15:47:52 -0700557 mService.handleCleanupUser(userHandle);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800558 }
559
560 @Override
Makoto Onukif3a572b2016-03-10 12:28:38 -0800561 public void onUnlockUser(int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -0700562 mService.handleUnlockUser(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800563 }
564 }
565
566 /** lifecycle event */
567 void onBootPhase(int phase) {
568 if (DEBUG) {
569 Slog.d(TAG, "onBootPhase: " + phase);
570 }
571 switch (phase) {
572 case SystemService.PHASE_LOCK_SETTINGS_READY:
573 initialize();
574 break;
Makoto Onukic51b2872016-05-04 15:24:50 -0700575 case SystemService.PHASE_BOOT_COMPLETED:
576 mBootCompleted.set(true);
577 break;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800578 }
579 }
580
581 /** lifecycle event */
Makoto Onukicdc78f72016-03-21 15:47:52 -0700582 void handleUnlockUser(int userId) {
Makoto Onuki22fcc682016-05-17 14:52:19 -0700583 if (DEBUG) {
Makoto Onuki085a05c2016-08-19 11:39:29 -0700584 Slog.d(TAG, "handleUnlockUser: user=" + userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700585 }
Makoto Onukicdc78f72016-03-21 15:47:52 -0700586 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -0700587 mUnlockedUsers.put(userId, true);
Makoto Onukicdc78f72016-03-21 15:47:52 -0700588 }
Makoto Onuki085a05c2016-08-19 11:39:29 -0700589
590 // Preload the user data.
591 // Note, we don't use mHandler here but instead just start a new thread.
592 // This is because mHandler (which uses com.android.internal.os.BackgroundThread) is very
593 // busy at this point and this could take hundreds of milliseconds, which would be too
594 // late since the launcher would already have started.
595 // So we just create a new thread. This code runs rarely, so we don't use a thread pool
596 // or anything.
597 final long start = injectElapsedRealtime();
598 injectRunOnNewThread(() -> {
599 synchronized (mLock) {
600 logDurationStat(Stats.ASYNC_PRELOAD_USER_DELAY, start);
601 getUserShortcutsLocked(userId);
602 }
603 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800604 }
605
606 /** lifecycle event */
Makoto Onukicdc78f72016-03-21 15:47:52 -0700607 void handleCleanupUser(int userId) {
Makoto Onuki02f338e2016-07-29 09:40:40 -0700608 if (DEBUG) {
609 Slog.d(TAG, "handleCleanupUser: user=" + userId);
610 }
Makoto Onukicdc78f72016-03-21 15:47:52 -0700611 synchronized (mLock) {
612 unloadUserLocked(userId);
Makoto Onuki02f338e2016-07-29 09:40:40 -0700613
614 mUnlockedUsers.put(userId, false);
Makoto Onukicdc78f72016-03-21 15:47:52 -0700615 }
616 }
617
618 private void unloadUserLocked(int userId) {
619 if (DEBUG) {
620 Slog.d(TAG, "unloadUserLocked: user=" + userId);
621 }
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700622 // Save all dirty information.
623 saveDirtyInfo();
624
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800625 // Unload
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -0800626 mUsers.delete(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800627 }
628
629 /** Return the base state file name */
630 private AtomicFile getBaseStateFile() {
631 final File path = new File(injectSystemDataPath(), FILENAME_BASE_STATE);
632 path.mkdirs();
633 return new AtomicFile(path);
634 }
635
636 /**
637 * Init the instance. (load the state file, etc)
638 */
639 private void initialize() {
640 synchronized (mLock) {
Makoto Onuki4362a662016-03-08 18:59:09 -0800641 loadConfigurationLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800642 loadBaseStateLocked();
643 }
644 }
645
Makoto Onuki4362a662016-03-08 18:59:09 -0800646 /**
647 * Load the configuration from Settings.
648 */
649 private void loadConfigurationLocked() {
650 updateConfigurationLocked(injectShortcutManagerConstants());
651 }
Makoto Onuki55046222016-03-08 10:49:47 -0800652
Makoto Onuki4362a662016-03-08 18:59:09 -0800653 /**
654 * Load the configuration from Settings.
655 */
656 @VisibleForTesting
657 boolean updateConfigurationLocked(String config) {
658 boolean result = true;
659
660 final KeyValueListParser parser = new KeyValueListParser(',');
661 try {
662 parser.setString(config);
663 } catch (IllegalArgumentException e) {
664 // Failed to parse the settings string, log this and move on
665 // with defaults.
666 Slog.e(TAG, "Bad shortcut manager settings", e);
667 result = false;
668 }
669
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700670 mSaveDelayMillis = Math.max(0, (int) parser.getLong(ConfigConstants.KEY_SAVE_DELAY_MILLIS,
671 DEFAULT_SAVE_DELAY_MS));
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700672
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700673 mResetInterval = Math.max(1, parser.getLong(
Makoto Onuki4362a662016-03-08 18:59:09 -0800674 ConfigConstants.KEY_RESET_INTERVAL_SEC, DEFAULT_RESET_INTERVAL_SEC)
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700675 * 1000L);
Makoto Onuki4362a662016-03-08 18:59:09 -0800676
Makoto Onukib6d35232016-04-04 15:57:17 -0700677 mMaxUpdatesPerInterval = Math.max(0, (int) parser.getLong(
678 ConfigConstants.KEY_MAX_UPDATES_PER_INTERVAL, DEFAULT_MAX_UPDATES_PER_INTERVAL));
Makoto Onuki4362a662016-03-08 18:59:09 -0800679
Makoto Onukib5a012f2016-06-21 11:13:53 -0700680 mMaxShortcuts = Math.max(0, (int) parser.getLong(
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700681 ConfigConstants.KEY_MAX_SHORTCUTS, DEFAULT_MAX_SHORTCUTS_PER_APP));
Makoto Onuki4362a662016-03-08 18:59:09 -0800682
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700683 final int iconDimensionDp = Math.max(1, injectIsLowRamDevice()
Makoto Onuki4362a662016-03-08 18:59:09 -0800684 ? (int) parser.getLong(
Makoto Onukib08790c2016-06-23 14:05:46 -0700685 ConfigConstants.KEY_MAX_ICON_DIMENSION_DP_LOWRAM,
686 DEFAULT_MAX_ICON_DIMENSION_LOWRAM_DP)
Makoto Onuki4362a662016-03-08 18:59:09 -0800687 : (int) parser.getLong(
Makoto Onukib08790c2016-06-23 14:05:46 -0700688 ConfigConstants.KEY_MAX_ICON_DIMENSION_DP,
689 DEFAULT_MAX_ICON_DIMENSION_DP));
Makoto Onuki4362a662016-03-08 18:59:09 -0800690
691 mMaxIconDimension = injectDipToPixel(iconDimensionDp);
692
693 mIconPersistFormat = CompressFormat.valueOf(
694 parser.getString(ConfigConstants.KEY_ICON_FORMAT, DEFAULT_ICON_PERSIST_FORMAT));
695
696 mIconPersistQuality = (int) parser.getLong(
697 ConfigConstants.KEY_ICON_QUALITY,
698 DEFAULT_ICON_PERSIST_QUALITY);
699
700 return result;
701 }
702
703 @VisibleForTesting
704 String injectShortcutManagerConstants() {
705 return android.provider.Settings.Global.getString(
706 mContext.getContentResolver(),
707 android.provider.Settings.Global.SHORTCUT_MANAGER_CONSTANTS);
708 }
709
710 @VisibleForTesting
711 int injectDipToPixel(int dip) {
712 return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip,
713 mContext.getResources().getDisplayMetrics());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800714 }
715
Makoto Onuki55046222016-03-08 10:49:47 -0800716 // === Persisting ===
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800717
718 @Nullable
Makoto Onuki41066a62016-03-09 16:18:44 -0800719 static String parseStringAttribute(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800720 return parser.getAttributeValue(null, attribute);
721 }
722
Makoto Onuki0acbb142016-03-22 17:02:57 -0700723 static boolean parseBooleanAttribute(XmlPullParser parser, String attribute) {
724 return parseLongAttribute(parser, attribute) == 1;
725 }
726
Makoto Onuki41066a62016-03-09 16:18:44 -0800727 static int parseIntAttribute(XmlPullParser parser, String attribute) {
728 return (int) parseLongAttribute(parser, attribute);
729 }
730
Makoto Onukid99c6f02016-03-28 11:02:54 -0700731 static int parseIntAttribute(XmlPullParser parser, String attribute, int def) {
732 return (int) parseLongAttribute(parser, attribute, def);
733 }
734
Makoto Onuki41066a62016-03-09 16:18:44 -0800735 static long parseLongAttribute(XmlPullParser parser, String attribute) {
Makoto Onukid99c6f02016-03-28 11:02:54 -0700736 return parseLongAttribute(parser, attribute, 0);
737 }
738
739 static long parseLongAttribute(XmlPullParser parser, String attribute, long def) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800740 final String value = parseStringAttribute(parser, attribute);
741 if (TextUtils.isEmpty(value)) {
Makoto Onukid99c6f02016-03-28 11:02:54 -0700742 return def;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800743 }
744 try {
745 return Long.parseLong(value);
746 } catch (NumberFormatException e) {
747 Slog.e(TAG, "Error parsing long " + value);
Makoto Onukid99c6f02016-03-28 11:02:54 -0700748 return def;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800749 }
750 }
751
752 @Nullable
Makoto Onuki41066a62016-03-09 16:18:44 -0800753 static ComponentName parseComponentNameAttribute(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800754 final String value = parseStringAttribute(parser, attribute);
755 if (TextUtils.isEmpty(value)) {
756 return null;
757 }
758 return ComponentName.unflattenFromString(value);
759 }
760
761 @Nullable
Makoto Onuki440a1ea2016-07-20 14:21:18 -0700762 static Intent parseIntentAttributeNoDefault(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800763 final String value = parseStringAttribute(parser, attribute);
Makoto Onukib5a012f2016-06-21 11:13:53 -0700764 Intent parsed = null;
765 if (!TextUtils.isEmpty(value)) {
766 try {
767 parsed = Intent.parseUri(value, /* flags =*/ 0);
768 } catch (URISyntaxException e) {
769 Slog.e(TAG, "Error parsing intent", e);
770 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800771 }
Makoto Onuki440a1ea2016-07-20 14:21:18 -0700772 return parsed;
773 }
774
775 @Nullable
776 static Intent parseIntentAttribute(XmlPullParser parser, String attribute) {
777 Intent parsed = parseIntentAttributeNoDefault(parser, attribute);
Makoto Onukib5a012f2016-06-21 11:13:53 -0700778 if (parsed == null) {
779 // Default intent.
780 parsed = new Intent(Intent.ACTION_VIEW);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800781 }
Makoto Onukib5a012f2016-06-21 11:13:53 -0700782 return parsed;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800783 }
784
Makoto Onuki41066a62016-03-09 16:18:44 -0800785 static void writeTagValue(XmlSerializer out, String tag, String value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800786 if (TextUtils.isEmpty(value)) return;
787
788 out.startTag(null, tag);
789 out.attribute(null, ATTR_VALUE, value);
790 out.endTag(null, tag);
791 }
792
Makoto Onuki41066a62016-03-09 16:18:44 -0800793 static void writeTagValue(XmlSerializer out, String tag, long value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800794 writeTagValue(out, tag, Long.toString(value));
795 }
796
Makoto Onuki2d5b4652016-03-11 16:09:54 -0800797 static void writeTagValue(XmlSerializer out, String tag, ComponentName name) throws IOException {
798 if (name == null) return;
799 writeTagValue(out, tag, name.flattenToString());
800 }
801
Makoto Onuki41066a62016-03-09 16:18:44 -0800802 static void writeTagExtra(XmlSerializer out, String tag, PersistableBundle bundle)
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800803 throws IOException, XmlPullParserException {
804 if (bundle == null) return;
805
806 out.startTag(null, tag);
807 bundle.saveToXml(out);
808 out.endTag(null, tag);
809 }
810
Makoto Onuki22fcc682016-05-17 14:52:19 -0700811 static void writeAttr(XmlSerializer out, String name, CharSequence value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800812 if (TextUtils.isEmpty(value)) return;
813
Makoto Onuki22fcc682016-05-17 14:52:19 -0700814 out.attribute(null, name, value.toString());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800815 }
816
Makoto Onuki41066a62016-03-09 16:18:44 -0800817 static void writeAttr(XmlSerializer out, String name, long value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800818 writeAttr(out, name, String.valueOf(value));
819 }
820
Makoto Onuki0acbb142016-03-22 17:02:57 -0700821 static void writeAttr(XmlSerializer out, String name, boolean value) throws IOException {
822 if (value) {
823 writeAttr(out, name, "1");
824 }
825 }
826
Makoto Onuki41066a62016-03-09 16:18:44 -0800827 static void writeAttr(XmlSerializer out, String name, ComponentName comp) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800828 if (comp == null) return;
829 writeAttr(out, name, comp.flattenToString());
830 }
831
Makoto Onuki41066a62016-03-09 16:18:44 -0800832 static void writeAttr(XmlSerializer out, String name, Intent intent) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800833 if (intent == null) return;
834
835 writeAttr(out, name, intent.toUri(/* flags =*/ 0));
836 }
837
838 @VisibleForTesting
839 void saveBaseStateLocked() {
840 final AtomicFile file = getBaseStateFile();
841 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700842 Slog.d(TAG, "Saving to " + file.getBaseFile());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800843 }
844
845 FileOutputStream outs = null;
846 try {
847 outs = file.startWrite();
848
849 // Write to XML
850 XmlSerializer out = new FastXmlSerializer();
851 out.setOutput(outs, StandardCharsets.UTF_8.name());
852 out.startDocument(null, true);
853 out.startTag(null, TAG_ROOT);
854
855 // Body.
856 writeTagValue(out, TAG_LAST_RESET_TIME, mRawLastResetTime);
857
858 // Epilogue.
859 out.endTag(null, TAG_ROOT);
860 out.endDocument();
861
862 // Close.
863 file.finishWrite(outs);
864 } catch (IOException e) {
865 Slog.e(TAG, "Failed to write to file " + file.getBaseFile(), e);
866 file.failWrite(outs);
867 }
868 }
869
870 private void loadBaseStateLocked() {
871 mRawLastResetTime = 0;
872
873 final AtomicFile file = getBaseStateFile();
874 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700875 Slog.d(TAG, "Loading from " + file.getBaseFile());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800876 }
877 try (FileInputStream in = file.openRead()) {
878 XmlPullParser parser = Xml.newPullParser();
879 parser.setInput(in, StandardCharsets.UTF_8.name());
880
881 int type;
882 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
883 if (type != XmlPullParser.START_TAG) {
884 continue;
885 }
886 final int depth = parser.getDepth();
887 // Check the root tag
888 final String tag = parser.getName();
889 if (depth == 1) {
890 if (!TAG_ROOT.equals(tag)) {
891 Slog.e(TAG, "Invalid root tag: " + tag);
892 return;
893 }
894 continue;
895 }
896 // Assume depth == 2
897 switch (tag) {
898 case TAG_LAST_RESET_TIME:
899 mRawLastResetTime = parseLongAttribute(parser, ATTR_VALUE);
900 break;
901 default:
902 Slog.e(TAG, "Invalid tag: " + tag);
903 break;
904 }
905 }
906 } catch (FileNotFoundException e) {
907 // Use the default
Makoto Onukib08790c2016-06-23 14:05:46 -0700908 } catch (IOException | XmlPullParserException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800909 Slog.e(TAG, "Failed to read file " + file.getBaseFile(), e);
910
911 mRawLastResetTime = 0;
912 }
913 // Adjust the last reset time.
914 getLastResetTimeLocked();
915 }
916
Makoto Onuki0eed4412016-07-21 11:21:59 -0700917 @VisibleForTesting
918 final File getUserFile(@UserIdInt int userId) {
919 return new File(injectUserDataPath(userId), FILENAME_USER_PACKAGES);
920 }
921
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800922 private void saveUserLocked(@UserIdInt int userId) {
Makoto Onuki0eed4412016-07-21 11:21:59 -0700923 final File path = getUserFile(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800924 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700925 Slog.d(TAG, "Saving to " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800926 }
Makoto Onuki0eed4412016-07-21 11:21:59 -0700927 path.getParentFile().mkdirs();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800928 final AtomicFile file = new AtomicFile(path);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700929 FileOutputStream os = null;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800930 try {
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700931 os = file.startWrite();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800932
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700933 saveUserInternalLocked(userId, os, /* forBackup= */ false);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800934
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700935 file.finishWrite(os);
Makoto Onuki1e173232016-08-10 10:47:13 -0700936
937 // Remove all dangling bitmap files.
938 cleanupDanglingBitmapDirectoriesLocked(userId);
Makoto Onukib08790c2016-06-23 14:05:46 -0700939 } catch (XmlPullParserException | IOException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800940 Slog.e(TAG, "Failed to write to file " + file.getBaseFile(), e);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700941 file.failWrite(os);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800942 }
943 }
944
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700945 private void saveUserInternalLocked(@UserIdInt int userId, OutputStream os,
946 boolean forBackup) throws IOException, XmlPullParserException {
947
948 final BufferedOutputStream bos = new BufferedOutputStream(os);
949
950 // Write to XML
951 XmlSerializer out = new FastXmlSerializer();
952 out.setOutput(bos, StandardCharsets.UTF_8.name());
953 out.startDocument(null, true);
954
Makoto Onukic51b2872016-05-04 15:24:50 -0700955 getUserShortcutsLocked(userId).saveToXml(out, forBackup);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700956
957 out.endDocument();
958
959 bos.flush();
960 os.flush();
961 }
962
Makoto Onuki41066a62016-03-09 16:18:44 -0800963 static IOException throwForInvalidTag(int depth, String tag) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800964 throw new IOException(String.format("Invalid tag '%s' found at depth %d", tag, depth));
965 }
966
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700967 static void warnForInvalidTag(int depth, String tag) throws IOException {
968 Slog.w(TAG, String.format("Invalid tag '%s' found at depth %d", tag, depth));
969 }
970
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800971 @Nullable
Makoto Onuki31459242016-03-22 11:12:18 -0700972 private ShortcutUser loadUserLocked(@UserIdInt int userId) {
Makoto Onuki0eed4412016-07-21 11:21:59 -0700973 final File path = getUserFile(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800974 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700975 Slog.d(TAG, "Loading from " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800976 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800977 final AtomicFile file = new AtomicFile(path);
978
979 final FileInputStream in;
980 try {
981 in = file.openRead();
982 } catch (FileNotFoundException e) {
983 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700984 Slog.d(TAG, "Not found " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800985 }
986 return null;
987 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800988 try {
Makoto Onukib08790c2016-06-23 14:05:46 -0700989 final ShortcutUser ret = loadUserInternal(userId, in, /* forBackup= */ false);
Makoto Onuki6c1dbd52016-05-02 15:19:32 -0700990 return ret;
Makoto Onukifc4cf2d2016-08-24 11:10:26 -0700991 } catch (IOException | XmlPullParserException | InvalidFileFormatException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800992 Slog.e(TAG, "Failed to read file " + file.getBaseFile(), e);
993 return null;
994 } finally {
995 IoUtils.closeQuietly(in);
996 }
997 }
998
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700999 private ShortcutUser loadUserInternal(@UserIdInt int userId, InputStream is,
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07001000 boolean fromBackup) throws XmlPullParserException, IOException,
1001 InvalidFileFormatException {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001002
1003 final BufferedInputStream bis = new BufferedInputStream(is);
1004
1005 ShortcutUser ret = null;
1006 XmlPullParser parser = Xml.newPullParser();
1007 parser.setInput(bis, StandardCharsets.UTF_8.name());
1008
1009 int type;
1010 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1011 if (type != XmlPullParser.START_TAG) {
1012 continue;
1013 }
1014 final int depth = parser.getDepth();
1015
1016 final String tag = parser.getName();
1017 if (DEBUG_LOAD) {
1018 Slog.d(TAG, String.format("depth=%d type=%d name=%s",
1019 depth, type, tag));
1020 }
1021 if ((depth == 1) && ShortcutUser.TAG_ROOT.equals(tag)) {
1022 ret = ShortcutUser.loadFromXml(this, parser, userId, fromBackup);
1023 continue;
1024 }
1025 throwForInvalidTag(depth, tag);
1026 }
1027 return ret;
1028 }
1029
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001030 private void scheduleSaveBaseState() {
Makoto Onuki0acbb142016-03-22 17:02:57 -07001031 scheduleSaveInner(UserHandle.USER_NULL); // Special case -- use USER_NULL for base state.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001032 }
1033
Makoto Onuki2d5b4652016-03-11 16:09:54 -08001034 void scheduleSaveUser(@UserIdInt int userId) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07001035 scheduleSaveInner(userId);
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001036 }
1037
1038 // In order to re-schedule, we need to reuse the same instance, so keep it in final.
1039 private final Runnable mSaveDirtyInfoRunner = this::saveDirtyInfo;
1040
Makoto Onuki0acbb142016-03-22 17:02:57 -07001041 private void scheduleSaveInner(@UserIdInt int userId) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001042 if (DEBUG) {
1043 Slog.d(TAG, "Scheduling to save for " + userId);
1044 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001045 synchronized (mLock) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001046 if (!mDirtyUserIds.contains(userId)) {
1047 mDirtyUserIds.add(userId);
1048 }
1049 }
1050 // If already scheduled, remove that and re-schedule in N seconds.
1051 mHandler.removeCallbacks(mSaveDirtyInfoRunner);
1052 mHandler.postDelayed(mSaveDirtyInfoRunner, mSaveDelayMillis);
1053 }
1054
1055 @VisibleForTesting
1056 void saveDirtyInfo() {
1057 if (DEBUG) {
1058 Slog.d(TAG, "saveDirtyInfo");
1059 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001060 try {
1061 synchronized (mLock) {
1062 for (int i = mDirtyUserIds.size() - 1; i >= 0; i--) {
1063 final int userId = mDirtyUserIds.get(i);
1064 if (userId == UserHandle.USER_NULL) { // USER_NULL for base state.
1065 saveBaseStateLocked();
1066 } else {
1067 saveUserLocked(userId);
1068 }
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001069 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001070 mDirtyUserIds.clear();
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001071 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001072 } catch (Exception e) {
1073 wtf("Exception in saveDirtyInfo", e);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001074 }
1075 }
1076
1077 /** Return the last reset time. */
1078 long getLastResetTimeLocked() {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001079 updateTimesLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001080 return mRawLastResetTime;
1081 }
1082
1083 /** Return the next reset time. */
1084 long getNextResetTimeLocked() {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001085 updateTimesLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001086 return mRawLastResetTime + mResetInterval;
1087 }
1088
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001089 static boolean isClockValid(long time) {
1090 return time >= 1420070400; // Thu, 01 Jan 2015 00:00:00 GMT
1091 }
1092
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001093 /**
1094 * Update the last reset time.
1095 */
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001096 private void updateTimesLocked() {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001097
1098 final long now = injectCurrentTimeMillis();
1099
1100 final long prevLastResetTime = mRawLastResetTime;
1101
1102 if (mRawLastResetTime == 0) { // first launch.
1103 // TODO Randomize??
1104 mRawLastResetTime = now;
1105 } else if (now < mRawLastResetTime) {
1106 // Clock rewound.
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001107 if (isClockValid(now)) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001108 Slog.w(TAG, "Clock rewound");
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001109 // TODO Randomize??
1110 mRawLastResetTime = now;
1111 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001112 } else {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001113 if ((mRawLastResetTime + mResetInterval) <= now) {
1114 final long offset = mRawLastResetTime % mResetInterval;
1115 mRawLastResetTime = ((now / mResetInterval) * mResetInterval) + offset;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001116 }
1117 }
1118 if (prevLastResetTime != mRawLastResetTime) {
1119 scheduleSaveBaseState();
1120 }
1121 }
1122
Makoto Onuki1e173232016-08-10 10:47:13 -07001123 // Requires mLock held, but "Locked" prefix would look weired so we just say "L".
Makoto Onuki02f338e2016-07-29 09:40:40 -07001124 protected boolean isUserUnlockedL(@UserIdInt int userId) {
Makoto Onuki1e173232016-08-10 10:47:13 -07001125 // First, check the local copy.
1126 if (mUnlockedUsers.get(userId)) {
1127 return true;
1128 }
1129 // If the local copy says the user is locked, check with AM for the actual state, since
1130 // the user might just have been unlocked.
1131 // Note we just don't use isUserUnlockingOrUnlocked() here, because it'll return false
1132 // when the user is STOPPING, which we still want to consider as "unlocked".
1133 final long token = injectClearCallingIdentity();
1134 try {
1135 return mUserManager.isUserUnlockingOrUnlocked(userId);
1136 } finally {
1137 injectRestoreCallingIdentity(token);
1138 }
Makoto Onuki9c850012016-07-26 15:50:50 -07001139 }
1140
Makoto Onuki02f338e2016-07-29 09:40:40 -07001141 // Requires mLock held, but "Locked" prefix would look weired so we jsut say "L".
1142 void throwIfUserLockedL(@UserIdInt int userId) {
1143 if (!isUserUnlockedL(userId)) {
Makoto Onuki9c850012016-07-26 15:50:50 -07001144 throw new IllegalStateException("User " + userId + " is locked or not running");
1145 }
1146 }
1147
Makoto Onukicdc78f72016-03-21 15:47:52 -07001148 @GuardedBy("mLock")
1149 @NonNull
Makoto Onuki2e210c42016-03-30 08:30:36 -07001150 private boolean isUserLoadedLocked(@UserIdInt int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07001151 return mUsers.get(userId) != null;
1152 }
1153
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001154 /** Return the per-user state. */
1155 @GuardedBy("mLock")
1156 @NonNull
Makoto Onuki31459242016-03-22 11:12:18 -07001157 ShortcutUser getUserShortcutsLocked(@UserIdInt int userId) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001158 if (!isUserUnlockedL(userId)) {
Makoto Onuki9c850012016-07-26 15:50:50 -07001159 wtf("User still locked");
Makoto Onuki9c850012016-07-26 15:50:50 -07001160 }
1161
Makoto Onuki31459242016-03-22 11:12:18 -07001162 ShortcutUser userPackages = mUsers.get(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001163 if (userPackages == null) {
1164 userPackages = loadUserLocked(userId);
1165 if (userPackages == null) {
Makoto Onukic51b2872016-05-04 15:24:50 -07001166 userPackages = new ShortcutUser(this, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001167 }
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08001168 mUsers.put(userId, userPackages);
Makoto Onuki085a05c2016-08-19 11:39:29 -07001169
1170 // Also when a user's data is first accessed, scan all packages.
1171 checkPackageChanges(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001172 }
1173 return userPackages;
1174 }
1175
Makoto Onuki2e210c42016-03-30 08:30:36 -07001176 void forEachLoadedUserLocked(@NonNull Consumer<ShortcutUser> c) {
1177 for (int i = mUsers.size() - 1; i >= 0; i--) {
1178 c.accept(mUsers.valueAt(i));
1179 }
1180 }
1181
Makoto Onukic8c33292016-09-12 16:36:59 -07001182 /**
1183 * Return the per-user per-package state. If the caller is a publisher, use
1184 * {@link #getPackageShortcutsForPublisherLocked} instead.
1185 */
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001186 @GuardedBy("mLock")
1187 @NonNull
Makoto Onuki31459242016-03-22 11:12:18 -07001188 ShortcutPackage getPackageShortcutsLocked(
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001189 @NonNull String packageName, @UserIdInt int userId) {
Makoto Onukic51b2872016-05-04 15:24:50 -07001190 return getUserShortcutsLocked(userId).getPackageShortcuts(packageName);
Makoto Onukide667372016-03-15 14:29:20 -07001191 }
1192
Makoto Onukic8c33292016-09-12 16:36:59 -07001193 /** Return the per-user per-package state. Use this when the caller is a publisher. */
1194 @GuardedBy("mLock")
1195 @NonNull
1196 ShortcutPackage getPackageShortcutsForPublisherLocked(
1197 @NonNull String packageName, @UserIdInt int userId) {
1198 final ShortcutPackage ret = getUserShortcutsLocked(userId).getPackageShortcuts(packageName);
1199 ret.getUser().onCalledByPublisher(packageName);
1200 return ret;
1201 }
1202
Makoto Onukide667372016-03-15 14:29:20 -07001203 @GuardedBy("mLock")
1204 @NonNull
Makoto Onuki2e210c42016-03-30 08:30:36 -07001205 ShortcutLauncher getLauncherShortcutsLocked(
1206 @NonNull String packageName, @UserIdInt int ownerUserId,
1207 @UserIdInt int launcherUserId) {
1208 return getUserShortcutsLocked(ownerUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07001209 .getLauncherShortcuts(packageName, launcherUserId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001210 }
1211
1212 // === Caller validation ===
1213
Makoto Onuki55046222016-03-08 10:49:47 -08001214 void removeIcon(@UserIdInt int userId, ShortcutInfo shortcut) {
Makoto Onuki1e173232016-08-10 10:47:13 -07001215 // Do not remove the actual bitmap file yet, because if the device crashes before saving
1216 // he XML we'd lose the icon. We just remove all dangling files after saving the XML.
Makoto Onukidd097812016-06-29 13:10:09 -07001217 shortcut.setIconResourceId(0);
1218 shortcut.setIconResName(null);
Hyunyoung Songf281e7a2017-02-13 10:57:42 -08001219 shortcut.clearFlags(ShortcutInfo.FLAG_HAS_ICON_FILE |
1220 ShortcutInfo.FLAG_MASKABLE_BITMAP | ShortcutInfo.FLAG_HAS_ICON_RES);
Makoto Onuki55046222016-03-08 10:49:47 -08001221 }
1222
Makoto Onuki0033b2a2016-04-14 17:19:16 -07001223 public void cleanupBitmapsForPackage(@UserIdInt int userId, String packageName) {
1224 final File packagePath = new File(getUserBitmapFilePath(userId), packageName);
1225 if (!packagePath.isDirectory()) {
1226 return;
1227 }
1228 if (!(FileUtils.deleteContents(packagePath) && packagePath.delete())) {
1229 Slog.w(TAG, "Unable to remove directory " + packagePath);
1230 }
1231 }
1232
Makoto Onuki1e173232016-08-10 10:47:13 -07001233 private void cleanupDanglingBitmapDirectoriesLocked(@UserIdInt int userId) {
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001234 if (DEBUG) {
1235 Slog.d(TAG, "cleanupDanglingBitmaps: userId=" + userId);
1236 }
1237 final long start = injectElapsedRealtime();
1238
Makoto Onuki1e173232016-08-10 10:47:13 -07001239 final ShortcutUser user = getUserShortcutsLocked(userId);
1240
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001241 final File bitmapDir = getUserBitmapFilePath(userId);
1242 final File[] children = bitmapDir.listFiles();
1243 if (children == null) {
1244 return;
1245 }
1246 for (File child : children) {
1247 if (!child.isDirectory()) {
1248 continue;
1249 }
1250 final String packageName = child.getName();
1251 if (DEBUG) {
1252 Slog.d(TAG, "cleanupDanglingBitmaps: Found directory=" + packageName);
1253 }
1254 if (!user.hasPackage(packageName)) {
1255 if (DEBUG) {
1256 Slog.d(TAG, "Removing dangling bitmap directory: " + packageName);
1257 }
1258 cleanupBitmapsForPackage(userId, packageName);
1259 } else {
1260 cleanupDanglingBitmapFilesLocked(userId, user, packageName, child);
1261 }
1262 }
1263 logDurationStat(Stats.CLEANUP_DANGLING_BITMAPS, start);
1264 }
1265
1266 private void cleanupDanglingBitmapFilesLocked(@UserIdInt int userId, @NonNull ShortcutUser user,
1267 @NonNull String packageName, @NonNull File path) {
1268 final ArraySet<String> usedFiles =
Makoto Onukic51b2872016-05-04 15:24:50 -07001269 user.getPackageShortcuts(packageName).getUsedBitmapFiles();
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001270
1271 for (File child : path.listFiles()) {
1272 if (!child.isFile()) {
1273 continue;
1274 }
1275 final String name = child.getName();
1276 if (!usedFiles.contains(name)) {
1277 if (DEBUG) {
1278 Slog.d(TAG, "Removing dangling bitmap file: " + child.getAbsolutePath());
1279 }
1280 child.delete();
1281 }
1282 }
1283 }
1284
Makoto Onuki55046222016-03-08 10:49:47 -08001285 @VisibleForTesting
1286 static class FileOutputStreamWithPath extends FileOutputStream {
1287 private final File mFile;
1288
1289 public FileOutputStreamWithPath(File file) throws FileNotFoundException {
1290 super(file);
1291 mFile = file;
1292 }
1293
1294 public File getFile() {
1295 return mFile;
1296 }
1297 }
1298
1299 /**
1300 * Build the cached bitmap filename for a shortcut icon.
1301 *
1302 * The filename will be based on the ID, except certain characters will be escaped.
1303 */
1304 @VisibleForTesting
1305 FileOutputStreamWithPath openIconFileForWrite(@UserIdInt int userId, ShortcutInfo shortcut)
1306 throws IOException {
1307 final File packagePath = new File(getUserBitmapFilePath(userId),
Makoto Onuki22fcc682016-05-17 14:52:19 -07001308 shortcut.getPackage());
Makoto Onuki55046222016-03-08 10:49:47 -08001309 if (!packagePath.isDirectory()) {
1310 packagePath.mkdirs();
1311 if (!packagePath.isDirectory()) {
1312 throw new IOException("Unable to create directory " + packagePath);
1313 }
1314 SELinux.restorecon(packagePath);
1315 }
1316
1317 final String baseName = String.valueOf(injectCurrentTimeMillis());
Makoto Onukib08790c2016-06-23 14:05:46 -07001318 for (int suffix = 0; ; suffix++) {
Makoto Onuki55046222016-03-08 10:49:47 -08001319 final String filename = (suffix == 0 ? baseName : baseName + "_" + suffix) + ".png";
1320 final File file = new File(packagePath, filename);
1321 if (!file.exists()) {
1322 if (DEBUG) {
1323 Slog.d(TAG, "Saving icon to " + file.getAbsolutePath());
1324 }
1325 return new FileOutputStreamWithPath(file);
1326 }
1327 }
1328 }
1329
1330 void saveIconAndFixUpShortcut(@UserIdInt int userId, ShortcutInfo shortcut) {
1331 if (shortcut.hasIconFile() || shortcut.hasIconResource()) {
1332 return;
1333 }
1334
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001335 final long token = injectClearCallingIdentity();
Makoto Onuki55046222016-03-08 10:49:47 -08001336 try {
1337 // Clear icon info on the shortcut.
Makoto Onukidd097812016-06-29 13:10:09 -07001338 removeIcon(userId, shortcut);
Makoto Onuki55046222016-03-08 10:49:47 -08001339
1340 final Icon icon = shortcut.getIcon();
1341 if (icon == null) {
1342 return; // has no icon
1343 }
1344
Makoto Onukiabe84422016-04-07 09:41:19 -07001345 Bitmap bitmap;
Makoto Onuki55046222016-03-08 10:49:47 -08001346 try {
1347 switch (icon.getType()) {
1348 case Icon.TYPE_RESOURCE: {
1349 injectValidateIconResPackage(shortcut, icon);
1350
1351 shortcut.setIconResourceId(icon.getResId());
1352 shortcut.addFlags(ShortcutInfo.FLAG_HAS_ICON_RES);
1353 return;
1354 }
Hyunyoung Songf281e7a2017-02-13 10:57:42 -08001355 case Icon.TYPE_BITMAP:
1356 case Icon.TYPE_BITMAP_MASKABLE: {
Makoto Onukiabe84422016-04-07 09:41:19 -07001357 bitmap = icon.getBitmap(); // Don't recycle in this case.
Makoto Onuki55046222016-03-08 10:49:47 -08001358 break;
1359 }
Makoto Onuki55046222016-03-08 10:49:47 -08001360 default:
1361 // This shouldn't happen because we've already validated the icon, but
1362 // just in case.
1363 throw ShortcutInfo.getInvalidIconException();
1364 }
1365 if (bitmap == null) {
1366 Slog.e(TAG, "Null bitmap detected");
1367 return;
1368 }
1369 // Shrink and write to the file.
1370 File path = null;
1371 try {
1372 final FileOutputStreamWithPath out = openIconFileForWrite(userId, shortcut);
1373 try {
1374 path = out.getFile();
1375
Makoto Onukiabe84422016-04-07 09:41:19 -07001376 Bitmap shrunk = shrinkBitmap(bitmap, mMaxIconDimension);
1377 try {
1378 shrunk.compress(mIconPersistFormat, mIconPersistQuality, out);
1379 } finally {
1380 if (bitmap != shrunk) {
1381 shrunk.recycle();
1382 }
1383 }
Makoto Onuki55046222016-03-08 10:49:47 -08001384
1385 shortcut.setBitmapPath(out.getFile().getAbsolutePath());
1386 shortcut.addFlags(ShortcutInfo.FLAG_HAS_ICON_FILE);
Hyunyoung Songf281e7a2017-02-13 10:57:42 -08001387 if (icon.getType() == Icon.TYPE_BITMAP_MASKABLE) {
1388 shortcut.addFlags(ShortcutInfo.FLAG_MASKABLE_BITMAP);
1389 }
Makoto Onuki55046222016-03-08 10:49:47 -08001390 } finally {
1391 IoUtils.closeQuietly(out);
1392 }
Makoto Onukib08790c2016-06-23 14:05:46 -07001393 } catch (IOException | RuntimeException e) {
Makoto Onuki55046222016-03-08 10:49:47 -08001394 // STOPSHIP Change wtf to e
1395 Slog.wtf(ShortcutService.TAG, "Unable to write bitmap to file", e);
1396 if (path != null && path.exists()) {
1397 path.delete();
1398 }
1399 }
1400 } finally {
Makoto Onuki55046222016-03-08 10:49:47 -08001401 // Once saved, we won't use the original icon information, so null it out.
1402 shortcut.clearIcon();
1403 }
1404 } finally {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001405 injectRestoreCallingIdentity(token);
Makoto Onuki55046222016-03-08 10:49:47 -08001406 }
1407 }
1408
1409 // Unfortunately we can't do this check in unit tests because we fake creator package names,
1410 // so override in unit tests.
1411 // TODO CTS this case.
1412 void injectValidateIconResPackage(ShortcutInfo shortcut, Icon icon) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07001413 if (!shortcut.getPackage().equals(icon.getResPackage())) {
Makoto Onuki55046222016-03-08 10:49:47 -08001414 throw new IllegalArgumentException(
1415 "Icon resource must reside in shortcut owner package");
1416 }
1417 }
1418
1419 @VisibleForTesting
1420 static Bitmap shrinkBitmap(Bitmap in, int maxSize) {
1421 // Original width/height.
1422 final int ow = in.getWidth();
1423 final int oh = in.getHeight();
1424 if ((ow <= maxSize) && (oh <= maxSize)) {
1425 if (DEBUG) {
1426 Slog.d(TAG, String.format("Icon size %dx%d, no need to shrink", ow, oh));
1427 }
1428 return in;
1429 }
1430 final int longerDimension = Math.max(ow, oh);
1431
1432 // New width and height.
1433 final int nw = ow * maxSize / longerDimension;
1434 final int nh = oh * maxSize / longerDimension;
1435 if (DEBUG) {
1436 Slog.d(TAG, String.format("Icon size %dx%d, shrinking to %dx%d",
1437 ow, oh, nw, nh));
1438 }
1439
1440 final Bitmap scaledBitmap = Bitmap.createBitmap(nw, nh, Bitmap.Config.ARGB_8888);
1441 final Canvas c = new Canvas(scaledBitmap);
1442
1443 final RectF dst = new RectF(0, 0, nw, nh);
1444
1445 c.drawBitmap(in, /*src=*/ null, dst, /* paint =*/ null);
1446
Makoto Onuki55046222016-03-08 10:49:47 -08001447 return scaledBitmap;
1448 }
1449
Makoto Onuki157b1622016-06-02 16:13:10 -07001450 /**
1451 * For a shortcut, update all resource names from resource IDs, and also update all
1452 * resource-based strings.
1453 */
1454 void fixUpShortcutResourceNamesAndValues(ShortcutInfo si) {
1455 final Resources publisherRes = injectGetResourcesForApplicationAsUser(
1456 si.getPackage(), si.getUserId());
1457 if (publisherRes != null) {
1458 final long start = injectElapsedRealtime();
1459 try {
1460 si.lookupAndFillInResourceNames(publisherRes);
1461 } finally {
1462 logDurationStat(Stats.RESOURCE_NAME_LOOKUP, start);
1463 }
1464 si.resolveResourceStrings(publisherRes);
1465 }
1466 }
1467
Makoto Onuki55046222016-03-08 10:49:47 -08001468 // === Caller validation ===
1469
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001470 private boolean isCallerSystem() {
1471 final int callingUid = injectBinderCallingUid();
Makoto Onukib08790c2016-06-23 14:05:46 -07001472 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001473 }
1474
1475 private boolean isCallerShell() {
1476 final int callingUid = injectBinderCallingUid();
1477 return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
1478 }
1479
1480 private void enforceSystemOrShell() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001481 if (!(isCallerSystem() || isCallerShell())) {
1482 throw new SecurityException("Caller must be system or shell");
1483 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001484 }
1485
1486 private void enforceShell() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001487 if (!isCallerShell()) {
1488 throw new SecurityException("Caller must be shell");
1489 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001490 }
1491
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001492 private void enforceSystem() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001493 if (!isCallerSystem()) {
1494 throw new SecurityException("Caller must be system");
1495 }
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001496 }
1497
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001498 private void enforceResetThrottlingPermission() {
1499 if (isCallerSystem()) {
1500 return;
1501 }
Makoto Onuki76269922016-07-15 14:58:54 -07001502 enforceCallingOrSelfPermission(
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001503 android.Manifest.permission.RESET_SHORTCUT_MANAGER_THROTTLING, null);
1504 }
1505
Makoto Onuki76269922016-07-15 14:58:54 -07001506 private void enforceCallingOrSelfPermission(
1507 @NonNull String permission, @Nullable String message) {
1508 if (isCallerSystem()) {
1509 return;
1510 }
1511 injectEnforceCallingPermission(permission, message);
1512 }
1513
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001514 /**
1515 * Somehow overriding ServiceContext.enforceCallingPermission() in the unit tests would confuse
1516 * mockito. So instead we extracted it here and override it in the tests.
1517 */
1518 @VisibleForTesting
1519 void injectEnforceCallingPermission(
1520 @NonNull String permission, @Nullable String message) {
1521 mContext.enforceCallingPermission(permission, message);
1522 }
1523
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001524 private void verifyCaller(@NonNull String packageName, @UserIdInt int userId) {
1525 Preconditions.checkStringNotEmpty(packageName, "packageName");
1526
1527 if (isCallerSystem()) {
1528 return; // no check
1529 }
1530
1531 final int callingUid = injectBinderCallingUid();
1532
1533 // Otherwise, make sure the arguments are valid.
1534 if (UserHandle.getUserId(callingUid) != userId) {
1535 throw new SecurityException("Invalid user-ID");
1536 }
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08001537 if (injectGetPackageUid(packageName, userId) != callingUid) {
1538 throw new SecurityException("Calling package name mismatch");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001539 }
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08001540 Preconditions.checkState(!isEphemeralApp(packageName, userId),
1541 "Ephemeral apps can't use ShortcutManager");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001542 }
1543
Makoto Onuki157b1622016-06-02 16:13:10 -07001544 // Overridden in unit tests to execute r synchronously.
1545 void injectPostToHandler(Runnable r) {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001546 mHandler.post(r);
1547 }
1548
Makoto Onuki085a05c2016-08-19 11:39:29 -07001549 void injectRunOnNewThread(Runnable r) {
1550 new Thread(r).start();
1551 }
1552
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001553 /**
Makoto Onuki7001a612016-05-27 13:24:28 -07001554 * @throws IllegalArgumentException if {@code numShortcuts} is bigger than
Makoto Onukib08790c2016-06-23 14:05:46 -07001555 * {@link #getMaxActivityShortcuts()}.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001556 */
Makoto Onuki7001a612016-05-27 13:24:28 -07001557 void enforceMaxActivityShortcuts(int numShortcuts) {
Makoto Onukib5a012f2016-06-21 11:13:53 -07001558 if (numShortcuts > mMaxShortcuts) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001559 throw new IllegalArgumentException("Max number of dynamic shortcuts exceeded");
1560 }
1561 }
1562
1563 /**
Makoto Onuki7001a612016-05-27 13:24:28 -07001564 * Return the max number of dynamic + manifest shortcuts for each launcher icon.
1565 */
1566 int getMaxActivityShortcuts() {
Makoto Onukib5a012f2016-06-21 11:13:53 -07001567 return mMaxShortcuts;
Makoto Onuki7001a612016-05-27 13:24:28 -07001568 }
1569
1570 /**
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001571 * - Sends a notification to LauncherApps
1572 * - Write to file
1573 */
Makoto Onuki39686e82016-04-13 18:03:00 -07001574 void packageShortcutsChanged(@NonNull String packageName, @UserIdInt int userId) {
1575 if (DEBUG) {
1576 Slog.d(TAG, String.format(
1577 "Shortcut changes: package=%s, user=%d", packageName, userId));
1578 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001579 notifyListeners(packageName, userId);
1580 scheduleSaveUser(userId);
1581 }
1582
1583 private void notifyListeners(@NonNull String packageName, @UserIdInt int userId) {
Makoto Onuki157b1622016-06-02 16:13:10 -07001584 injectPostToHandler(() -> {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001585 try {
1586 final ArrayList<ShortcutChangeListener> copy;
1587 synchronized (mLock) {
1588 if (!isUserUnlockedL(userId)) {
1589 return;
1590 }
1591
1592 copy = new ArrayList<>(mListeners);
1593 }
1594 // Note onShortcutChanged() needs to be called with the system service permissions.
1595 for (int i = copy.size() - 1; i >= 0; i--) {
1596 copy.get(i).onShortcutChanged(packageName, userId);
1597 }
1598 } catch (Exception ignore) {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001599 }
1600 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001601 }
1602
1603 /**
1604 * Clean up / validate an incoming shortcut.
1605 * - Make sure all mandatory fields are set.
1606 * - Make sure the intent's extras are persistable, and them to set
Makoto Onuki0eed4412016-07-21 11:21:59 -07001607 * {@link ShortcutInfo#mIntentPersistableExtrases}. Also clear its extras.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001608 * - Clear flags.
1609 */
Makoto Onuki2d895c32016-12-02 15:48:40 -08001610 private void fixUpIncomingShortcutInfo(@NonNull ShortcutInfo shortcut, boolean forUpdate,
1611 boolean forPinRequest) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001612 Preconditions.checkNotNull(shortcut, "Null shortcut detected");
Makoto Onuki255461f2017-01-10 11:47:25 -08001613 if (shortcut.getActivity() != null) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001614 Preconditions.checkState(
Makoto Onuki22fcc682016-05-17 14:52:19 -07001615 shortcut.getPackage().equals(shortcut.getActivity().getPackageName()),
Makoto Onukib08790c2016-06-23 14:05:46 -07001616 "Cannot publish shortcut: activity " + shortcut.getActivity() + " does not"
1617 + " belong to package " + shortcut.getPackage());
Makoto Onuki13260b6ff2016-07-13 18:03:13 -07001618 Preconditions.checkState(
1619 injectIsMainActivity(shortcut.getActivity(), shortcut.getUserId()),
1620 "Cannot publish shortcut: activity " + shortcut.getActivity() + " is not"
1621 + " main activity");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001622 }
1623
Makoto Onuki55046222016-03-08 10:49:47 -08001624 if (!forUpdate) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08001625 shortcut.enforceMandatoryFields(/* forPinned= */ forPinRequest);
1626 if (!forPinRequest) {
Makoto Onuki255461f2017-01-10 11:47:25 -08001627 Preconditions.checkState(shortcut.getActivity() != null,
1628 "Cannot publish shortcut: target activity is not set");
Makoto Onuki2d895c32016-12-02 15:48:40 -08001629 }
Makoto Onuki55046222016-03-08 10:49:47 -08001630 }
1631 if (shortcut.getIcon() != null) {
1632 ShortcutInfo.validateIcon(shortcut.getIcon());
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001633 }
1634
Makoto Onukide667372016-03-15 14:29:20 -07001635 shortcut.replaceFlags(0);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001636 }
1637
Makoto Onuki2d895c32016-12-02 15:48:40 -08001638 private void fixUpIncomingShortcutInfo(@NonNull ShortcutInfo shortcut, boolean forUpdate) {
1639 fixUpIncomingShortcutInfo(shortcut, forUpdate, /*forPinRequest=*/ false);
1640 }
1641
1642 public void validateShortcutForPinRequest(@NonNull ShortcutInfo shortcut) {
1643 fixUpIncomingShortcutInfo(shortcut, /* forUpdate= */ false, /*forPinRequest=*/ true);
1644 }
1645
Makoto Onukib08790c2016-06-23 14:05:46 -07001646 /**
1647 * When a shortcut has no target activity, set the default one from the package.
1648 */
1649 private void fillInDefaultActivity(List<ShortcutInfo> shortcuts) {
Makoto Onukib08790c2016-06-23 14:05:46 -07001650 ComponentName defaultActivity = null;
1651 for (int i = shortcuts.size() - 1; i >= 0; i--) {
1652 final ShortcutInfo si = shortcuts.get(i);
1653 if (si.getActivity() == null) {
1654 if (defaultActivity == null) {
1655 defaultActivity = injectGetDefaultMainActivity(
1656 si.getPackage(), si.getUserId());
1657 Preconditions.checkState(defaultActivity != null,
1658 "Launcher activity not found for package " + si.getPackage());
1659 }
1660 si.setActivity(defaultActivity);
1661 }
1662 }
1663 }
1664
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001665 private void assignImplicitRanks(List<ShortcutInfo> shortcuts) {
1666 for (int i = shortcuts.size() - 1; i >= 0; i--) {
1667 shortcuts.get(i).setImplicitRank(i);
1668 }
1669 }
1670
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001671 // === APIs ===
1672
1673 @Override
1674 public boolean setDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1675 @UserIdInt int userId) {
1676 verifyCaller(packageName, userId);
1677
1678 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
1679 final int size = newShortcuts.size();
1680
1681 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001682 throwIfUserLockedL(userId);
1683
Makoto Onukic8c33292016-09-12 16:36:59 -07001684 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001685
Makoto Onuki22fcc682016-05-17 14:52:19 -07001686 ps.ensureImmutableShortcutsNotIncluded(newShortcuts);
1687
Makoto Onukib08790c2016-06-23 14:05:46 -07001688 fillInDefaultActivity(newShortcuts);
1689
Makoto Onuki7001a612016-05-27 13:24:28 -07001690 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_SET);
1691
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001692 // Throttling.
Makoto Onukic51b2872016-05-04 15:24:50 -07001693 if (!ps.tryApiCall()) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001694 return false;
1695 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001696
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001697 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1698 ps.clearAllImplicitRanks();
1699 assignImplicitRanks(newShortcuts);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001700
Makoto Onukidf6da042016-06-16 09:51:40 -07001701 for (int i = 0; i < size; i++) {
1702 fixUpIncomingShortcutInfo(newShortcuts.get(i), /* forUpdate= */ false);
1703 }
1704
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001705 // First, remove all un-pinned; dynamic shortcuts
Makoto Onukic51b2872016-05-04 15:24:50 -07001706 ps.deleteAllDynamicShortcuts();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001707
1708 // Then, add/update all. We need to make sure to take over "pinned" flag.
1709 for (int i = 0; i < size; i++) {
1710 final ShortcutInfo newShortcut = newShortcuts.get(i);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001711 ps.addOrUpdateDynamicShortcut(newShortcut);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001712 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001713
1714 // Lastly, adjust the ranks.
1715 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001716 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001717 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001718
1719 verifyStates();
1720
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001721 return true;
1722 }
1723
1724 @Override
1725 public boolean updateShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1726 @UserIdInt int userId) {
1727 verifyCaller(packageName, userId);
1728
1729 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
Makoto Onuki55046222016-03-08 10:49:47 -08001730 final int size = newShortcuts.size();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001731
1732 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001733 throwIfUserLockedL(userId);
1734
Makoto Onukic8c33292016-09-12 16:36:59 -07001735 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001736
Makoto Onuki22fcc682016-05-17 14:52:19 -07001737 ps.ensureImmutableShortcutsNotIncluded(newShortcuts);
1738
Makoto Onukib08790c2016-06-23 14:05:46 -07001739 // For update, don't fill in the default activity. Having null activity means
1740 // "don't update the activity" here.
1741
Makoto Onuki7001a612016-05-27 13:24:28 -07001742 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_UPDATE);
1743
Makoto Onuki55046222016-03-08 10:49:47 -08001744 // Throttling.
Makoto Onukic51b2872016-05-04 15:24:50 -07001745 if (!ps.tryApiCall()) {
Makoto Onuki55046222016-03-08 10:49:47 -08001746 return false;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001747 }
1748
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001749 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1750 ps.clearAllImplicitRanks();
1751 assignImplicitRanks(newShortcuts);
1752
Makoto Onuki55046222016-03-08 10:49:47 -08001753 for (int i = 0; i < size; i++) {
1754 final ShortcutInfo source = newShortcuts.get(i);
1755 fixUpIncomingShortcutInfo(source, /* forUpdate= */ true);
1756
1757 final ShortcutInfo target = ps.findShortcutById(source.getId());
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001758 if (target == null) {
1759 continue;
1760 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07001761
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001762 if (target.isEnabled() != source.isEnabled()) {
1763 Slog.w(TAG,
1764 "ShortcutInfo.enabled cannot be changed with updateShortcuts()");
1765 }
Makoto Onuki55046222016-03-08 10:49:47 -08001766
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001767 // When updating the rank, we need to insert between existing ranks, so set
1768 // this setRankChanged, and also copy the implicit rank fo adjustRanks().
1769 if (source.hasRank()) {
1770 target.setRankChanged();
1771 target.setImplicitRank(source.getImplicitRank());
1772 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07001773
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001774 final boolean replacingIcon = (source.getIcon() != null);
1775 if (replacingIcon) {
1776 removeIcon(userId, target);
1777 }
Makoto Onuki55046222016-03-08 10:49:47 -08001778
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001779 // Note copyNonNullFieldsFrom() does the "updatable with?" check too.
1780 target.copyNonNullFieldsFrom(source);
1781 target.setTimestamp(injectCurrentTimeMillis());
1782
1783 if (replacingIcon) {
1784 saveIconAndFixUpShortcut(userId, target);
1785 }
1786
1787 // When we're updating any resource related fields, re-extract the res names and
1788 // the values.
1789 if (replacingIcon || source.hasStringResources()) {
1790 fixUpShortcutResourceNamesAndValues(target);
Makoto Onuki55046222016-03-08 10:49:47 -08001791 }
1792 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001793
1794 // Lastly, adjust the ranks.
1795 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001796 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001797 packageShortcutsChanged(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001798
Makoto Onuki7001a612016-05-27 13:24:28 -07001799 verifyStates();
1800
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001801 return true;
1802 }
1803
1804 @Override
Makoto Onukib6d35232016-04-04 15:57:17 -07001805 public boolean addDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001806 @UserIdInt int userId) {
1807 verifyCaller(packageName, userId);
1808
Makoto Onukib6d35232016-04-04 15:57:17 -07001809 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
1810 final int size = newShortcuts.size();
1811
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001812 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001813 throwIfUserLockedL(userId);
1814
Makoto Onukic8c33292016-09-12 16:36:59 -07001815 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001816
Makoto Onuki22fcc682016-05-17 14:52:19 -07001817 ps.ensureImmutableShortcutsNotIncluded(newShortcuts);
1818
Makoto Onukib08790c2016-06-23 14:05:46 -07001819 fillInDefaultActivity(newShortcuts);
1820
Makoto Onuki7001a612016-05-27 13:24:28 -07001821 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_ADD);
1822
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001823 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1824 ps.clearAllImplicitRanks();
1825 assignImplicitRanks(newShortcuts);
1826
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001827 // Throttling.
Makoto Onukic51b2872016-05-04 15:24:50 -07001828 if (!ps.tryApiCall()) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001829 return false;
1830 }
Makoto Onukib6d35232016-04-04 15:57:17 -07001831 for (int i = 0; i < size; i++) {
1832 final ShortcutInfo newShortcut = newShortcuts.get(i);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001833
Makoto Onukib6d35232016-04-04 15:57:17 -07001834 // Validate the shortcut.
1835 fixUpIncomingShortcutInfo(newShortcut, /* forUpdate= */ false);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001836
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001837 // When ranks are changing, we need to insert between ranks, so set the
1838 // "rank changed" flag.
1839 newShortcut.setRankChanged();
1840
Makoto Onukib6d35232016-04-04 15:57:17 -07001841 // Add it.
Makoto Onuki22fcc682016-05-17 14:52:19 -07001842 ps.addOrUpdateDynamicShortcut(newShortcut);
Makoto Onukib6d35232016-04-04 15:57:17 -07001843 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001844
1845 // Lastly, adjust the ranks.
1846 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001847 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001848 packageShortcutsChanged(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001849
Makoto Onuki7001a612016-05-27 13:24:28 -07001850 verifyStates();
1851
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001852 return true;
1853 }
1854
1855 @Override
Makoto Onuki2d895c32016-12-02 15:48:40 -08001856 public boolean requestPinShortcut(String packageName, ShortcutInfo shortcut,
1857 IntentSender resultIntent, int userId) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08001858 Preconditions.checkNotNull(shortcut);
1859 Preconditions.checkArgument(shortcut.isEnabled(), "Shortcut must be enabled");
Sunny Goyal87a563e2017-01-01 19:42:45 -08001860 return requestPinItem(packageName, userId, shortcut, null, resultIntent);
1861 }
1862
Sunny Goyala6be88a2017-01-12 16:27:58 -08001863 @Override
1864 public Intent createShortcutResultIntent(String packageName, ShortcutInfo shortcut, int userId)
1865 throws RemoteException {
1866 Preconditions.checkNotNull(shortcut);
1867 Preconditions.checkArgument(shortcut.isEnabled(), "Shortcut must be enabled");
1868 verifyCaller(packageName, userId);
1869
1870 final Intent ret;
1871 synchronized (mLock) {
1872 throwIfUserLockedL(userId);
1873
1874 // Send request to the launcher, if supported.
1875 ret = mShortcutRequestPinProcessor.createShortcutResultIntent(shortcut, userId);
1876 }
1877
1878 verifyStates();
1879 return ret;
1880 }
1881
Sunny Goyal87a563e2017-01-01 19:42:45 -08001882 /**
1883 * Handles {@link #requestPinShortcut} and {@link ShortcutServiceInternal#requestPinAppWidget}.
1884 * After validating the caller, it passes the request to {@link #mShortcutRequestPinProcessor}.
1885 * Either {@param shortcut} or {@param appWidget} should be non-null.
1886 */
1887 private boolean requestPinItem(String packageName, int userId,
1888 ShortcutInfo shortcut, AppWidgetProviderInfo appWidget, IntentSender resultIntent) {
1889 verifyCaller(packageName, userId);
Makoto Onuki2d895c32016-12-02 15:48:40 -08001890
1891 final boolean ret;
1892 synchronized (mLock) {
1893 throwIfUserLockedL(userId);
1894
Makoto Onukia01f4f02016-12-15 15:58:41 -08001895 Preconditions.checkState(isUidForegroundLocked(injectBinderCallingUid()),
Makoto Onuki255461f2017-01-10 11:47:25 -08001896 "Calling application must have a foreground activity or a foreground service");
Makoto Onuki2d895c32016-12-02 15:48:40 -08001897
1898 // Send request to the launcher, if supported.
Sunny Goyal87a563e2017-01-01 19:42:45 -08001899 ret = mShortcutRequestPinProcessor.requestPinItemLocked(shortcut, appWidget, userId,
1900 resultIntent);
Makoto Onuki2d895c32016-12-02 15:48:40 -08001901 }
1902
1903 verifyStates();
1904
1905 return ret;
1906 }
1907
1908 @Override
Makoto Onuki20c95f82016-05-11 16:51:01 -07001909 public void disableShortcuts(String packageName, List shortcutIds,
Makoto Onukid6880792016-06-29 13:37:43 -07001910 CharSequence disabledMessage, int disabledMessageResId, @UserIdInt int userId) {
Makoto Onuki20c95f82016-05-11 16:51:01 -07001911 verifyCaller(packageName, userId);
1912 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
1913
1914 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001915 throwIfUserLockedL(userId);
1916
Makoto Onukic8c33292016-09-12 16:36:59 -07001917 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001918
1919 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds);
1920
Makoto Onukid6880792016-06-29 13:37:43 -07001921 final String disabledMessageString =
1922 (disabledMessage == null) ? null : disabledMessage.toString();
1923
Makoto Onuki22fcc682016-05-17 14:52:19 -07001924 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
1925 ps.disableWithId(Preconditions.checkStringNotEmpty((String) shortcutIds.get(i)),
Makoto Onukid6880792016-06-29 13:37:43 -07001926 disabledMessageString, disabledMessageResId,
Makoto Onuki22fcc682016-05-17 14:52:19 -07001927 /* overrideImmutable=*/ false);
1928 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001929
1930 // We may have removed dynamic shortcuts which may have left a gap, so adjust the ranks.
1931 ps.adjustRanks();
Makoto Onuki22fcc682016-05-17 14:52:19 -07001932 }
1933 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001934
1935 verifyStates();
Makoto Onuki22fcc682016-05-17 14:52:19 -07001936 }
1937
1938 @Override
1939 public void enableShortcuts(String packageName, List shortcutIds, @UserIdInt int userId) {
1940 verifyCaller(packageName, userId);
1941 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
1942
1943 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001944 throwIfUserLockedL(userId);
1945
Makoto Onukic8c33292016-09-12 16:36:59 -07001946 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001947
1948 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds);
1949
1950 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
1951 ps.enableWithId((String) shortcutIds.get(i));
1952 }
Makoto Onuki20c95f82016-05-11 16:51:01 -07001953 }
1954 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001955
1956 verifyStates();
Makoto Onuki20c95f82016-05-11 16:51:01 -07001957 }
1958
1959 @Override
Makoto Onukib6d35232016-04-04 15:57:17 -07001960 public void removeDynamicShortcuts(String packageName, List shortcutIds,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001961 @UserIdInt int userId) {
1962 verifyCaller(packageName, userId);
Makoto Onukib6d35232016-04-04 15:57:17 -07001963 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001964
1965 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001966 throwIfUserLockedL(userId);
1967
Makoto Onukic8c33292016-09-12 16:36:59 -07001968 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001969
1970 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds);
1971
Makoto Onukib6d35232016-04-04 15:57:17 -07001972 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07001973 ps.deleteDynamicWithId(
Makoto Onukib6d35232016-04-04 15:57:17 -07001974 Preconditions.checkStringNotEmpty((String) shortcutIds.get(i)));
1975 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001976
1977 // We may have removed dynamic shortcuts which may have left a gap, so adjust the ranks.
1978 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001979 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001980 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001981
1982 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001983 }
1984
1985 @Override
Makoto Onukib6d35232016-04-04 15:57:17 -07001986 public void removeAllDynamicShortcuts(String packageName, @UserIdInt int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001987 verifyCaller(packageName, userId);
1988
1989 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001990 throwIfUserLockedL(userId);
1991
Makoto Onukic8c33292016-09-12 16:36:59 -07001992 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07001993 ps.deleteAllDynamicShortcuts();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001994 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001995 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001996
1997 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001998 }
1999
2000 @Override
2001 public ParceledListSlice<ShortcutInfo> getDynamicShortcuts(String packageName,
2002 @UserIdInt int userId) {
2003 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002004
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002005 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002006 throwIfUserLockedL(userId);
2007
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002008 return getShortcutsWithQueryLocked(
2009 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
2010 ShortcutInfo::isDynamic);
2011 }
2012 }
2013
2014 @Override
Makoto Onuki22fcc682016-05-17 14:52:19 -07002015 public ParceledListSlice<ShortcutInfo> getManifestShortcuts(String packageName,
2016 @UserIdInt int userId) {
2017 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002018
Makoto Onuki22fcc682016-05-17 14:52:19 -07002019 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002020 throwIfUserLockedL(userId);
2021
Makoto Onuki22fcc682016-05-17 14:52:19 -07002022 return getShortcutsWithQueryLocked(
2023 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
2024 ShortcutInfo::isManifestShortcut);
2025 }
2026 }
2027
2028 @Override
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002029 public ParceledListSlice<ShortcutInfo> getPinnedShortcuts(String packageName,
2030 @UserIdInt int userId) {
2031 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002032
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002033 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002034 throwIfUserLockedL(userId);
2035
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002036 return getShortcutsWithQueryLocked(
2037 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
2038 ShortcutInfo::isPinned);
2039 }
2040 }
2041
2042 private ParceledListSlice<ShortcutInfo> getShortcutsWithQueryLocked(@NonNull String packageName,
2043 @UserIdInt int userId, int cloneFlags, @NonNull Predicate<ShortcutInfo> query) {
2044
2045 final ArrayList<ShortcutInfo> ret = new ArrayList<>();
2046
Makoto Onukic8c33292016-09-12 16:36:59 -07002047 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002048 ps.findAll(ret, query, cloneFlags);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002049
2050 return new ParceledListSlice<>(ret);
2051 }
2052
2053 @Override
Makoto Onukid6880792016-06-29 13:37:43 -07002054 public int getMaxShortcutCountPerActivity(String packageName, @UserIdInt int userId)
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002055 throws RemoteException {
2056 verifyCaller(packageName, userId);
2057
Makoto Onukib5a012f2016-06-21 11:13:53 -07002058 return mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002059 }
2060
2061 @Override
2062 public int getRemainingCallCount(String packageName, @UserIdInt int userId) {
2063 verifyCaller(packageName, userId);
2064
2065 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002066 throwIfUserLockedL(userId);
2067
Makoto Onukic8c33292016-09-12 16:36:59 -07002068 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002069 return mMaxUpdatesPerInterval - ps.getApiCallCount();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002070 }
2071 }
2072
2073 @Override
2074 public long getRateLimitResetTime(String packageName, @UserIdInt int userId) {
2075 verifyCaller(packageName, userId);
2076
2077 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002078 throwIfUserLockedL(userId);
2079
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002080 return getNextResetTimeLocked();
2081 }
2082 }
2083
Makoto Onuki55046222016-03-08 10:49:47 -08002084 @Override
Makoto Onuki20c95f82016-05-11 16:51:01 -07002085 public int getIconMaxDimensions(String packageName, int userId) {
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002086 verifyCaller(packageName, userId);
2087
Makoto Onuki55046222016-03-08 10:49:47 -08002088 synchronized (mLock) {
2089 return mMaxIconDimension;
2090 }
2091 }
2092
Makoto Onuki20c95f82016-05-11 16:51:01 -07002093 @Override
2094 public void reportShortcutUsed(String packageName, String shortcutId, int userId) {
2095 verifyCaller(packageName, userId);
2096
Makoto Onukiac042502016-05-20 16:39:42 -07002097 Preconditions.checkNotNull(shortcutId);
2098
2099 if (DEBUG) {
2100 Slog.d(TAG, String.format("reportShortcutUsed: Shortcut %s package %s used on user %d",
2101 shortcutId, packageName, userId));
2102 }
2103
2104 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002105 throwIfUserLockedL(userId);
2106
Makoto Onukic8c33292016-09-12 16:36:59 -07002107 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002108
Makoto Onukiac042502016-05-20 16:39:42 -07002109 if (ps.findShortcutById(shortcutId) == null) {
2110 Log.w(TAG, String.format("reportShortcutUsed: package %s doesn't have shortcut %s",
2111 packageName, shortcutId));
2112 return;
2113 }
2114 }
2115
2116 final long token = injectClearCallingIdentity();
2117 try {
2118 mUsageStatsManagerInternal.reportShortcutUsage(packageName, shortcutId, userId);
2119 } finally {
2120 injectRestoreCallingIdentity(token);
2121 }
Makoto Onuki20c95f82016-05-11 16:51:01 -07002122 }
2123
Makoto Onuki2d895c32016-12-02 15:48:40 -08002124 @Override
Sunny Goyal7f7372a2017-01-24 11:53:54 -08002125 public boolean isRequestPinItemSupported(int callingUserId, int requestType) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08002126 final long token = injectClearCallingIdentity();
2127 try {
Sunny Goyal7f7372a2017-01-24 11:53:54 -08002128 return mShortcutRequestPinProcessor
2129 .isRequestPinItemSupported(callingUserId, requestType);
Makoto Onuki2d895c32016-12-02 15:48:40 -08002130 } finally {
2131 injectRestoreCallingIdentity(token);
2132 }
2133 }
2134
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002135 /**
Makoto Onukib08790c2016-06-23 14:05:46 -07002136 * Reset all throttling, for developer options and command line. Only system/shell can call
2137 * it.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002138 */
2139 @Override
2140 public void resetThrottling() {
2141 enforceSystemOrShell();
2142
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002143 resetThrottlingInner(getCallingUserId());
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002144 }
2145
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002146 void resetThrottlingInner(@UserIdInt int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002147 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002148 if (!isUserUnlockedL(userId)) {
2149 Log.w(TAG, "User " + userId + " is locked or not running");
2150 return;
2151 }
2152
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002153 getUserShortcutsLocked(userId).resetThrottling();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002154 }
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002155 scheduleSaveUser(userId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002156 Slog.i(TAG, "ShortcutManager: throttling counter reset for user " + userId);
2157 }
2158
2159 void resetAllThrottlingInner() {
2160 synchronized (mLock) {
2161 mRawLastResetTime = injectCurrentTimeMillis();
2162 }
2163 scheduleSaveBaseState();
2164 Slog.i(TAG, "ShortcutManager: throttling counter reset for all users");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002165 }
2166
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002167 @Override
2168 public void onApplicationActive(String packageName, int userId) {
2169 if (DEBUG) {
2170 Slog.d(TAG, "onApplicationActive: package=" + packageName + " userid=" + userId);
2171 }
2172 enforceResetThrottlingPermission();
Makoto Onuki02f338e2016-07-29 09:40:40 -07002173
2174 synchronized (mLock) {
2175 if (!isUserUnlockedL(userId)) {
2176 // This is called by system UI, so no need to throw. Just ignore.
2177 return;
2178 }
2179
2180 getPackageShortcutsLocked(packageName, userId)
2181 .resetRateLimitingForCommandLineNoSaving();
2182 saveUserLocked(userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002183 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002184 }
2185
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002186 // We override this method in unit tests to do a simpler check.
2187 boolean hasShortcutHostPermission(@NonNull String callingPackage, int userId) {
Makoto Onuki10305202016-07-14 18:14:08 -07002188 final long start = injectElapsedRealtime();
2189 try {
2190 return hasShortcutHostPermissionInner(callingPackage, userId);
2191 } finally {
2192 logDurationStat(Stats.LAUNCHER_PERMISSION_CHECK, start);
2193 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002194 }
2195
2196 // This method is extracted so we can directly call this method from unit tests,
2197 // even when hasShortcutPermission() is overridden.
2198 @VisibleForTesting
Makoto Onuki2d895c32016-12-02 15:48:40 -08002199 boolean hasShortcutHostPermissionInner(@NonNull String packageName, int userId) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002200 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002201 throwIfUserLockedL(userId);
2202
Makoto Onuki31459242016-03-22 11:12:18 -07002203 final ShortcutUser user = getUserShortcutsLocked(userId);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002204
Makoto Onuki2d895c32016-12-02 15:48:40 -08002205 // Always trust the cached component.
Makoto Onuki10305202016-07-14 18:14:08 -07002206 final ComponentName cached = user.getCachedLauncher();
2207 if (cached != null) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08002208 if (cached.getPackageName().equals(packageName)) {
Makoto Onuki10305202016-07-14 18:14:08 -07002209 return true;
2210 }
2211 }
2212 // If the cached one doesn't match, then go ahead
2213
Makoto Onuki2d895c32016-12-02 15:48:40 -08002214 final ComponentName detected = getDefaultLauncher(userId);
Makoto Onuki2e210c42016-03-30 08:30:36 -07002215
Makoto Onuki10305202016-07-14 18:14:08 -07002216 // Update the cache.
2217 user.setLauncher(detected);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002218 if (detected != null) {
2219 if (DEBUG) {
2220 Slog.v(TAG, "Detected launcher: " + detected);
2221 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08002222 return detected.getPackageName().equals(packageName);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002223 } else {
2224 // Default launcher not found.
2225 return false;
2226 }
2227 }
2228 }
2229
Makoto Onuki2d895c32016-12-02 15:48:40 -08002230 @Nullable
2231 ComponentName getDefaultLauncher(@UserIdInt int userId) {
2232 final long start = injectElapsedRealtime();
2233 final long token = injectClearCallingIdentity();
2234 try {
2235 synchronized (mLock) {
2236 throwIfUserLockedL(userId);
2237
2238 final ShortcutUser user = getUserShortcutsLocked(userId);
2239
2240 final List<ResolveInfo> allHomeCandidates = new ArrayList<>();
2241
2242 // Default launcher from package manager.
2243 final long startGetHomeActivitiesAsUser = injectElapsedRealtime();
2244 final ComponentName defaultLauncher = mPackageManagerInternal
2245 .getHomeActivitiesAsUser(allHomeCandidates, userId);
2246 logDurationStat(Stats.GET_DEFAULT_HOME, startGetHomeActivitiesAsUser);
2247
2248 ComponentName detected = null;
2249 if (defaultLauncher != null) {
2250 detected = defaultLauncher;
2251 if (DEBUG) {
2252 Slog.v(TAG, "Default launcher from PM: " + detected);
2253 }
2254 } else {
2255 detected = user.getLastKnownLauncher();
2256
2257 if (detected != null) {
2258 if (injectIsActivityEnabledAndExported(detected, userId)) {
2259 if (DEBUG) {
2260 Slog.v(TAG, "Cached launcher: " + detected);
2261 }
2262 } else {
2263 Slog.w(TAG, "Cached launcher " + detected + " no longer exists");
2264 detected = null;
2265 user.clearLauncher();
2266 }
2267 }
2268 }
2269
2270 if (detected == null) {
2271 // If we reach here, that means it's the first check since the user was created,
2272 // and there's already multiple launchers and there's no default set.
2273 // Find the system one with the highest priority.
2274 // (We need to check the priority too because of FallbackHome in Settings.)
2275 // If there's no system launcher yet, then no one can access shortcuts, until
2276 // the user explicitly
2277 final int size = allHomeCandidates.size();
2278
2279 int lastPriority = Integer.MIN_VALUE;
2280 for (int i = 0; i < size; i++) {
2281 final ResolveInfo ri = allHomeCandidates.get(i);
2282 if (!ri.activityInfo.applicationInfo.isSystemApp()) {
2283 continue;
2284 }
2285 if (DEBUG) {
2286 Slog.d(TAG, String.format("hasShortcutPermissionInner: pkg=%s prio=%d",
2287 ri.activityInfo.getComponentName(), ri.priority));
2288 }
2289 if (ri.priority < lastPriority) {
2290 continue;
2291 }
2292 detected = ri.activityInfo.getComponentName();
2293 lastPriority = ri.priority;
2294 }
2295 }
2296 return detected;
2297 }
2298 } finally {
2299 injectRestoreCallingIdentity(token);
2300 logDurationStat(Stats.GET_DEFAULT_LAUNCHER, start);
2301 }
2302 }
2303
Makoto Onukicdc78f72016-03-21 15:47:52 -07002304 // === House keeping ===
2305
Makoto Onukib08790c2016-06-23 14:05:46 -07002306 private void cleanUpPackageForAllLoadedUsers(String packageName, @UserIdInt int packageUserId,
2307 boolean appStillExists) {
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002308 synchronized (mLock) {
2309 forEachLoadedUserLocked(user ->
Makoto Onukib08790c2016-06-23 14:05:46 -07002310 cleanUpPackageLocked(packageName, user.getUserId(), packageUserId,
2311 appStillExists));
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002312 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002313 }
2314
Makoto Onuki2e210c42016-03-30 08:30:36 -07002315 /**
2316 * Remove all the information associated with a package. This will really remove all the
2317 * information, including the restore information (i.e. it'll remove packages even if they're
2318 * shadow).
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002319 *
2320 * This is called when an app is uninstalled, or an app gets "clear data"ed.
Makoto Onuki2e210c42016-03-30 08:30:36 -07002321 */
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002322 @VisibleForTesting
Makoto Onukib08790c2016-06-23 14:05:46 -07002323 void cleanUpPackageLocked(String packageName, int owningUserId, int packageUserId,
2324 boolean appStillExists) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002325 final boolean wasUserLoaded = isUserLoadedLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002326
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002327 final ShortcutUser user = getUserShortcutsLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002328 boolean doNotify = false;
2329
2330 // First, remove the package from the package list (if the package is a publisher).
Makoto Onukid99c6f02016-03-28 11:02:54 -07002331 if (packageUserId == owningUserId) {
Makoto Onukic51b2872016-05-04 15:24:50 -07002332 if (user.removePackage(packageName) != null) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002333 doNotify = true;
2334 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07002335 }
Makoto Onukid99c6f02016-03-28 11:02:54 -07002336
Makoto Onukicdc78f72016-03-21 15:47:52 -07002337 // Also remove from the launcher list (if the package is a launcher).
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002338 user.removeLauncher(packageUserId, packageName);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002339
2340 // Then remove pinned shortcuts from all launchers.
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002341 user.forAllLaunchers(l -> l.cleanUpPackage(packageName, packageUserId));
2342
2343 // Now there may be orphan shortcuts because we removed pinned shortcuts at the previous
Makoto Onukicdc78f72016-03-21 15:47:52 -07002344 // step. Remove them too.
Makoto Onukic51b2872016-05-04 15:24:50 -07002345 user.forAllPackages(p -> p.refreshPinnedFlags());
Makoto Onukicdc78f72016-03-21 15:47:52 -07002346
Makoto Onukid99c6f02016-03-28 11:02:54 -07002347 scheduleSaveUser(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002348
2349 if (doNotify) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002350 notifyListeners(packageName, owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002351 }
2352
Makoto Onukib08790c2016-06-23 14:05:46 -07002353 // If the app still exists (i.e. data cleared), we need to re-publish manifest shortcuts.
2354 if (appStillExists && (packageUserId == owningUserId)) {
2355 // This will do the notification and save when needed, so do it after the above
2356 // notifyListeners.
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002357 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07002358 }
2359
Makoto Onukicdc78f72016-03-21 15:47:52 -07002360 if (!wasUserLoaded) {
2361 // Note this will execute the scheduled save.
Makoto Onukid99c6f02016-03-28 11:02:54 -07002362 unloadUserLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002363 }
2364 }
2365
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002366 /**
2367 * Entry point from {@link LauncherApps}.
2368 */
2369 private class LocalService extends ShortcutServiceInternal {
Makoto Onuki2e210c42016-03-30 08:30:36 -07002370
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002371 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002372 public List<ShortcutInfo> getShortcuts(int launcherUserId,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002373 @NonNull String callingPackage, long changedSince,
Makoto Onukiabe84422016-04-07 09:41:19 -07002374 @Nullable String packageName, @Nullable List<String> shortcutIds,
2375 @Nullable ComponentName componentName,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002376 int queryFlags, int userId) {
2377 final ArrayList<ShortcutInfo> ret = new ArrayList<>();
Makoto Onuki9c850012016-07-26 15:50:50 -07002378
Makoto Onuki20c95f82016-05-11 16:51:01 -07002379 final boolean cloneKeyFieldOnly =
2380 ((queryFlags & ShortcutQuery.FLAG_GET_KEY_FIELDS_ONLY) != 0);
2381 final int cloneFlag = cloneKeyFieldOnly ? ShortcutInfo.CLONE_REMOVE_NON_KEY_INFO
2382 : ShortcutInfo.CLONE_REMOVE_FOR_LAUNCHER;
Makoto Onukiabe84422016-04-07 09:41:19 -07002383 if (packageName == null) {
2384 shortcutIds = null; // LauncherAppsService already threw for it though.
2385 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002386
2387 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002388 throwIfUserLockedL(userId);
2389 throwIfUserLockedL(launcherUserId);
2390
Makoto Onuki2e210c42016-03-30 08:30:36 -07002391 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002392 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002393
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002394 if (packageName != null) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002395 getShortcutsInnerLocked(launcherUserId,
Makoto Onukiabe84422016-04-07 09:41:19 -07002396 callingPackage, packageName, shortcutIds, changedSince,
Makoto Onukide667372016-03-15 14:29:20 -07002397 componentName, queryFlags, userId, ret, cloneFlag);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002398 } else {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002399 final List<String> shortcutIdsF = shortcutIds;
2400 getUserShortcutsLocked(userId).forAllPackages(p -> {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002401 getShortcutsInnerLocked(launcherUserId,
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002402 callingPackage, p.getPackageName(), shortcutIdsF, changedSince,
Makoto Onukide667372016-03-15 14:29:20 -07002403 componentName, queryFlags, userId, ret, cloneFlag);
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002404 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002405 }
2406 }
2407 return ret;
2408 }
2409
Makoto Onukid99c6f02016-03-28 11:02:54 -07002410 private void getShortcutsInnerLocked(int launcherUserId, @NonNull String callingPackage,
Makoto Onukiabe84422016-04-07 09:41:19 -07002411 @Nullable String packageName, @Nullable List<String> shortcutIds, long changedSince,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002412 @Nullable ComponentName componentName, int queryFlags,
2413 int userId, ArrayList<ShortcutInfo> ret, int cloneFlag) {
Makoto Onukiabe84422016-04-07 09:41:19 -07002414 final ArraySet<String> ids = shortcutIds == null ? null
2415 : new ArraySet<>(shortcutIds);
2416
Makoto Onukic51b2872016-05-04 15:24:50 -07002417 final ShortcutPackage p = getUserShortcutsLocked(userId)
2418 .getPackageShortcutsIfExists(packageName);
2419 if (p == null) {
2420 return; // No need to instantiate ShortcutPackage.
2421 }
2422
2423 p.findAll(ret,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002424 (ShortcutInfo si) -> {
2425 if (si.getLastChangedTimestamp() < changedSince) {
2426 return false;
2427 }
Makoto Onukiabe84422016-04-07 09:41:19 -07002428 if (ids != null && !ids.contains(si.getId())) {
2429 return false;
2430 }
Makoto Onuki85694522016-05-04 12:53:37 -07002431 if (componentName != null) {
Makoto Onuki9fd90192017-01-06 18:31:03 +00002432 if (si.getActivity() != null
2433 && !si.getActivity().equals(componentName)) {
Makoto Onuki85694522016-05-04 12:53:37 -07002434 return false;
2435 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002436 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002437 if (((queryFlags & ShortcutQuery.FLAG_GET_DYNAMIC) != 0)
2438 && si.isDynamic()) {
2439 return true;
2440 }
2441 if (((queryFlags & ShortcutQuery.FLAG_GET_PINNED) != 0)
2442 && si.isPinned()) {
2443 return true;
2444 }
2445 if (((queryFlags & ShortcutQuery.FLAG_GET_MANIFEST) != 0)
2446 && si.isManifestShortcut()) {
2447 return true;
2448 }
2449 return false;
Makoto Onukid99c6f02016-03-28 11:02:54 -07002450 }, cloneFlag, callingPackage, launcherUserId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002451 }
2452
2453 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002454 public boolean isPinnedByCaller(int launcherUserId, @NonNull String callingPackage,
2455 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2456 Preconditions.checkStringNotEmpty(packageName, "packageName");
2457 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
2458
2459 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002460 throwIfUserLockedL(userId);
2461 throwIfUserLockedL(launcherUserId);
2462
Makoto Onuki2e210c42016-03-30 08:30:36 -07002463 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002464 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002465
Makoto Onukid99c6f02016-03-28 11:02:54 -07002466 final ShortcutInfo si = getShortcutInfoLocked(
2467 launcherUserId, callingPackage, packageName, shortcutId, userId);
2468 return si != null && si.isPinned();
2469 }
2470 }
2471
Makoto Onuki2e210c42016-03-30 08:30:36 -07002472 private ShortcutInfo getShortcutInfoLocked(
Makoto Onukid99c6f02016-03-28 11:02:54 -07002473 int launcherUserId, @NonNull String callingPackage,
2474 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2475 Preconditions.checkStringNotEmpty(packageName, "packageName");
2476 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
2477
Makoto Onuki02f338e2016-07-29 09:40:40 -07002478 throwIfUserLockedL(userId);
2479 throwIfUserLockedL(launcherUserId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002480
Makoto Onukic51b2872016-05-04 15:24:50 -07002481 final ShortcutPackage p = getUserShortcutsLocked(userId)
2482 .getPackageShortcutsIfExists(packageName);
2483 if (p == null) {
2484 return null;
2485 }
2486
Makoto Onukid99c6f02016-03-28 11:02:54 -07002487 final ArrayList<ShortcutInfo> list = new ArrayList<>(1);
Makoto Onukic51b2872016-05-04 15:24:50 -07002488 p.findAll(list,
Makoto Onukid99c6f02016-03-28 11:02:54 -07002489 (ShortcutInfo si) -> shortcutId.equals(si.getId()),
2490 /* clone flags=*/ 0, callingPackage, launcherUserId);
2491 return list.size() == 0 ? null : list.get(0);
2492 }
2493
2494 @Override
2495 public void pinShortcuts(int launcherUserId,
2496 @NonNull String callingPackage, @NonNull String packageName,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002497 @NonNull List<String> shortcutIds, int userId) {
2498 // Calling permission must be checked by LauncherAppsImpl.
2499 Preconditions.checkStringNotEmpty(packageName, "packageName");
2500 Preconditions.checkNotNull(shortcutIds, "shortcutIds");
2501
2502 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002503 throwIfUserLockedL(userId);
2504 throwIfUserLockedL(launcherUserId);
2505
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002506 final ShortcutLauncher launcher =
Makoto Onuki2e210c42016-03-30 08:30:36 -07002507 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId);
Makoto Onukic51b2872016-05-04 15:24:50 -07002508 launcher.attemptToRestoreIfNeededAndSave();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002509
Makoto Onukic51b2872016-05-04 15:24:50 -07002510 launcher.pinShortcuts(userId, packageName, shortcutIds);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002511 }
Makoto Onuki39686e82016-04-13 18:03:00 -07002512 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07002513
2514 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002515 }
2516
2517 @Override
Makoto Onuki440a1ea2016-07-20 14:21:18 -07002518 public Intent[] createShortcutIntents(int launcherUserId,
Makoto Onukid99c6f02016-03-28 11:02:54 -07002519 @NonNull String callingPackage,
Makoto Onuki43204b82016-03-08 16:16:44 -08002520 @NonNull String packageName, @NonNull String shortcutId, int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002521 // Calling permission must be checked by LauncherAppsImpl.
Makoto Onuki43204b82016-03-08 16:16:44 -08002522 Preconditions.checkStringNotEmpty(packageName, "packageName can't be empty");
2523 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId can't be empty");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002524
2525 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002526 throwIfUserLockedL(userId);
2527 throwIfUserLockedL(launcherUserId);
2528
Makoto Onuki2e210c42016-03-30 08:30:36 -07002529 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002530 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002531
Makoto Onukid99c6f02016-03-28 11:02:54 -07002532 // Make sure the shortcut is actually visible to the launcher.
2533 final ShortcutInfo si = getShortcutInfoLocked(
2534 launcherUserId, callingPackage, packageName, shortcutId, userId);
2535 // "si == null" should suffice here, but check the flags too just to make sure.
Makoto Onuki22fcc682016-05-17 14:52:19 -07002536 if (si == null || !si.isEnabled() || !si.isAlive()) {
Makoto Onuki83f6d2d2016-07-11 14:30:19 -07002537 Log.e(TAG, "Shortcut " + shortcutId + " does not exist or disabled");
Makoto Onukid99c6f02016-03-28 11:02:54 -07002538 return null;
2539 }
Makoto Onuki440a1ea2016-07-20 14:21:18 -07002540 return si.getIntents();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002541 }
2542 }
2543
2544 @Override
2545 public void addListener(@NonNull ShortcutChangeListener listener) {
2546 synchronized (mLock) {
2547 mListeners.add(Preconditions.checkNotNull(listener));
2548 }
2549 }
Makoto Onuki55046222016-03-08 10:49:47 -08002550
2551 @Override
Makoto Onukiabe84422016-04-07 09:41:19 -07002552 public int getShortcutIconResId(int launcherUserId, @NonNull String callingPackage,
2553 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2554 Preconditions.checkNotNull(callingPackage, "callingPackage");
2555 Preconditions.checkNotNull(packageName, "packageName");
2556 Preconditions.checkNotNull(shortcutId, "shortcutId");
Makoto Onuki55046222016-03-08 10:49:47 -08002557
2558 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002559 throwIfUserLockedL(userId);
2560 throwIfUserLockedL(launcherUserId);
2561
Makoto Onuki2e210c42016-03-30 08:30:36 -07002562 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002563 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002564
Makoto Onukic51b2872016-05-04 15:24:50 -07002565 final ShortcutPackage p = getUserShortcutsLocked(userId)
2566 .getPackageShortcutsIfExists(packageName);
2567 if (p == null) {
2568 return 0;
2569 }
2570
2571 final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId);
Makoto Onuki55046222016-03-08 10:49:47 -08002572 return (shortcutInfo != null && shortcutInfo.hasIconResource())
2573 ? shortcutInfo.getIconResourceId() : 0;
2574 }
2575 }
2576
2577 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002578 public ParcelFileDescriptor getShortcutIconFd(int launcherUserId,
Makoto Onukiabe84422016-04-07 09:41:19 -07002579 @NonNull String callingPackage, @NonNull String packageName,
2580 @NonNull String shortcutId, int userId) {
2581 Preconditions.checkNotNull(callingPackage, "callingPackage");
2582 Preconditions.checkNotNull(packageName, "packageName");
2583 Preconditions.checkNotNull(shortcutId, "shortcutId");
Makoto Onuki55046222016-03-08 10:49:47 -08002584
2585 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002586 throwIfUserLockedL(userId);
2587 throwIfUserLockedL(launcherUserId);
2588
Makoto Onuki2e210c42016-03-30 08:30:36 -07002589 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002590 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002591
Makoto Onukic51b2872016-05-04 15:24:50 -07002592 final ShortcutPackage p = getUserShortcutsLocked(userId)
2593 .getPackageShortcutsIfExists(packageName);
2594 if (p == null) {
2595 return null;
2596 }
2597
2598 final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId);
Makoto Onuki55046222016-03-08 10:49:47 -08002599 if (shortcutInfo == null || !shortcutInfo.hasIconFile()) {
2600 return null;
2601 }
2602 try {
Makoto Onuki34d1c912016-03-10 14:24:58 -08002603 if (shortcutInfo.getBitmapPath() == null) {
2604 Slog.w(TAG, "null bitmap detected in getShortcutIconFd()");
2605 return null;
2606 }
Makoto Onuki55046222016-03-08 10:49:47 -08002607 return ParcelFileDescriptor.open(
2608 new File(shortcutInfo.getBitmapPath()),
2609 ParcelFileDescriptor.MODE_READ_ONLY);
2610 } catch (FileNotFoundException e) {
2611 Slog.e(TAG, "Icon file not found: " + shortcutInfo.getBitmapPath());
2612 return null;
2613 }
2614 }
2615 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002616
2617 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002618 public boolean hasShortcutHostPermission(int launcherUserId,
2619 @NonNull String callingPackage) {
2620 return ShortcutService.this.hasShortcutHostPermission(callingPackage, launcherUserId);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002621 }
Sunny Goyal87a563e2017-01-01 19:42:45 -08002622
2623 @Override
2624 public boolean requestPinAppWidget(@NonNull String callingPackage,
2625 @NonNull AppWidgetProviderInfo appWidget, @Nullable IntentSender resultIntent,
2626 int userId) {
2627 Preconditions.checkNotNull(appWidget);
2628 return requestPinItem(callingPackage, userId, null, appWidget, resultIntent);
2629 }
Sunny Goyal7f7372a2017-01-24 11:53:54 -08002630
2631 @Override
2632 public boolean isRequestPinItemSupported(int callingUserId, int requestType) {
2633 return ShortcutService.this.isRequestPinItemSupported(callingUserId, requestType);
2634 }
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002635 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002636
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002637 final BroadcastReceiver mReceiver = new BroadcastReceiver() {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002638 @Override
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002639 public void onReceive(Context context, Intent intent) {
2640 if (!mBootCompleted.get()) {
2641 return; // Boot not completed, ignore the broadcast.
2642 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07002643 try {
2644 if (Intent.ACTION_LOCALE_CHANGED.equals(intent.getAction())) {
2645 handleLocaleChanged();
2646 }
2647 } catch (Exception e) {
2648 wtf("Exception in mReceiver.onReceive", e);
Makoto Onukic51b2872016-05-04 15:24:50 -07002649 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002650 }
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002651 };
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002652
Makoto Onuki157b1622016-06-02 16:13:10 -07002653 void handleLocaleChanged() {
2654 if (DEBUG) {
2655 Slog.d(TAG, "handleLocaleChanged");
2656 }
2657 scheduleSaveBaseState();
2658
Makoto Onuki02f338e2016-07-29 09:40:40 -07002659 synchronized (mLock) {
2660 final long token = injectClearCallingIdentity();
2661 try {
2662 forEachLoadedUserLocked(user -> user.detectLocaleChange());
2663 } finally {
2664 injectRestoreCallingIdentity(token);
2665 }
Makoto Onuki157b1622016-06-02 16:13:10 -07002666 }
2667 }
2668
Makoto Onukif34c3082016-07-13 10:25:25 -07002669 /**
2670 * Package event callbacks.
2671 */
2672 @VisibleForTesting
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002673 final BroadcastReceiver mPackageMonitor = new BroadcastReceiver() {
Makoto Onukif34c3082016-07-13 10:25:25 -07002674 @Override
2675 public void onReceive(Context context, Intent intent) {
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002676 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
2677 if (userId == UserHandle.USER_NULL) {
2678 Slog.w(TAG, "Intent broadcast does not contain user handle: " + intent);
2679 return;
2680 }
2681
2682 final String action = intent.getAction();
2683
2684 // This is normally called on Handler, so clearCallingIdentity() isn't needed,
2685 // but we still check it in unit tests.
Makoto Onukif34c3082016-07-13 10:25:25 -07002686 final long token = injectClearCallingIdentity();
2687 try {
Makoto Onuki10305202016-07-14 18:14:08 -07002688 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002689 if (!isUserUnlockedL(userId)) {
2690 if (DEBUG) {
2691 Slog.d(TAG, "Ignoring package broadcast " + action
2692 + " for locked/stopped user " + userId);
2693 }
2694 return;
2695 }
2696
2697 // Whenever we get one of those package broadcasts, or get
2698 // ACTION_PREFERRED_ACTIVITY_CHANGED, we purge the default launcher cache.
Makoto Onuki10305202016-07-14 18:14:08 -07002699 final ShortcutUser user = getUserShortcutsLocked(userId);
2700 user.clearLauncher();
2701 }
2702 if (Intent.ACTION_PREFERRED_ACTIVITY_CHANGED.equals(action)) {
2703 // Nothing farther to do.
2704 return;
2705 }
2706
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002707 final Uri intentUri = intent.getData();
2708 final String packageName = (intentUri != null) ? intentUri.getSchemeSpecificPart()
2709 : null;
2710 if (packageName == null) {
2711 Slog.w(TAG, "Intent broadcast does not contain package name: " + intent);
2712 return;
2713 }
2714
2715 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
2716
2717 switch (action) {
2718 case Intent.ACTION_PACKAGE_ADDED:
2719 if (replacing) {
2720 handlePackageUpdateFinished(packageName, userId);
2721 } else {
2722 handlePackageAdded(packageName, userId);
2723 }
2724 break;
2725 case Intent.ACTION_PACKAGE_REMOVED:
2726 if (!replacing) {
2727 handlePackageRemoved(packageName, userId);
2728 }
2729 break;
2730 case Intent.ACTION_PACKAGE_CHANGED:
2731 handlePackageChanged(packageName, userId);
2732
2733 break;
2734 case Intent.ACTION_PACKAGE_DATA_CLEARED:
2735 handlePackageDataCleared(packageName, userId);
2736 break;
2737 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07002738 } catch (Exception e) {
2739 wtf("Exception in mPackageMonitor.onReceive", e);
Makoto Onukif34c3082016-07-13 10:25:25 -07002740 } finally {
2741 injectRestoreCallingIdentity(token);
Makoto Onukia2241832016-07-06 13:28:37 -07002742 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07002743 }
Makoto Onukif34c3082016-07-13 10:25:25 -07002744 };
Makoto Onukicdc78f72016-03-21 15:47:52 -07002745
Makoto Onuki0acbb142016-03-22 17:02:57 -07002746 /**
Makoto Onuki39686e82016-04-13 18:03:00 -07002747 * Called when a user is unlocked.
2748 * - Check all known packages still exist, and otherwise perform cleanup.
2749 * - If a package still exists, check the version code. If it's been updated, may need to
Makoto Onukib08790c2016-06-23 14:05:46 -07002750 * update timestamps of its shortcuts.
Makoto Onuki0acbb142016-03-22 17:02:57 -07002751 */
Makoto Onukid99c6f02016-03-28 11:02:54 -07002752 @VisibleForTesting
Makoto Onuki39686e82016-04-13 18:03:00 -07002753 void checkPackageChanges(@UserIdInt int ownerUserId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07002754 if (DEBUG) {
Makoto Onuki39686e82016-04-13 18:03:00 -07002755 Slog.d(TAG, "checkPackageChanges() ownerUserId=" + ownerUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002756 }
Makoto Onukib08790c2016-06-23 14:05:46 -07002757 if (injectIsSafeModeEnabled()) {
2758 Slog.i(TAG, "Safe mode, skipping checkPackageChanges()");
2759 return;
2760 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07002761
Makoto Onuki22fcc682016-05-17 14:52:19 -07002762 final long start = injectElapsedRealtime();
2763 try {
2764 final ArrayList<PackageWithUser> gonePackages = new ArrayList<>();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002765
Makoto Onuki22fcc682016-05-17 14:52:19 -07002766 synchronized (mLock) {
2767 final ShortcutUser user = getUserShortcutsLocked(ownerUserId);
2768
2769 // Find packages that have been uninstalled.
2770 user.forAllPackageItems(spi -> {
2771 if (spi.getPackageInfo().isShadow()) {
2772 return; // Don't delete shadow information.
2773 }
2774 if (!isPackageInstalled(spi.getPackageName(), spi.getPackageUserId())) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002775 if (DEBUG) {
2776 Slog.d(TAG, "Uninstalled: " + spi.getPackageName()
2777 + " user " + spi.getPackageUserId());
2778 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002779 gonePackages.add(PackageWithUser.of(spi));
2780 }
2781 });
2782 if (gonePackages.size() > 0) {
2783 for (int i = gonePackages.size() - 1; i >= 0; i--) {
2784 final PackageWithUser pu = gonePackages.get(i);
Makoto Onukib08790c2016-06-23 14:05:46 -07002785 cleanUpPackageLocked(pu.packageName, ownerUserId, pu.userId,
2786 /* appStillExists = */ false);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002787 }
Makoto Onukid99c6f02016-03-28 11:02:54 -07002788 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002789
Makoto Onuki248a0ef2016-11-03 15:59:01 -07002790 rescanUpdatedPackagesLocked(ownerUserId, user.getLastAppScanTime());
Makoto Onuki0acbb142016-03-22 17:02:57 -07002791 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002792 } finally {
2793 logDurationStat(Stats.CHECK_PACKAGE_CHANGES, start);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002794 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002795 verifyStates();
Makoto Onukicdc78f72016-03-21 15:47:52 -07002796 }
2797
Makoto Onuki248a0ef2016-11-03 15:59:01 -07002798 private void rescanUpdatedPackagesLocked(@UserIdInt int userId, long lastScanTime) {
Makoto Onuki377b7972016-08-09 14:43:55 -07002799 final ShortcutUser user = getUserShortcutsLocked(userId);
2800
Makoto Onuki33663282016-08-22 16:19:04 -07002801 // Note after each OTA, we'll need to rescan all system apps, as their lastUpdateTime
2802 // is not reliable.
Makoto Onuki377b7972016-08-09 14:43:55 -07002803 final long now = injectCurrentTimeMillis();
Makoto Onuki33663282016-08-22 16:19:04 -07002804 final boolean afterOta =
2805 !injectBuildFingerprint().equals(user.getLastAppScanOsFingerprint());
Makoto Onuki377b7972016-08-09 14:43:55 -07002806
2807 // Then for each installed app, publish manifest shortcuts when needed.
Makoto Onuki33663282016-08-22 16:19:04 -07002808 forUpdatedPackages(userId, lastScanTime, afterOta, ai -> {
Makoto Onuki377b7972016-08-09 14:43:55 -07002809 user.attemptToRestoreIfNeededAndSave(this, ai.packageName, userId);
Makoto Onuki248a0ef2016-11-03 15:59:01 -07002810
2811 user.rescanPackageIfNeeded(ai.packageName, /* forceRescan= */ true);
Makoto Onuki377b7972016-08-09 14:43:55 -07002812 });
2813
2814 // Write the time just before the scan, because there may be apps that have just
2815 // been updated, and we want to catch them in the next time.
2816 user.setLastAppScanTime(now);
Makoto Onuki33663282016-08-22 16:19:04 -07002817 user.setLastAppScanOsFingerprint(injectBuildFingerprint());
Makoto Onuki377b7972016-08-09 14:43:55 -07002818 scheduleSaveUser(userId);
2819 }
2820
Makoto Onuki0acbb142016-03-22 17:02:57 -07002821 private void handlePackageAdded(String packageName, @UserIdInt int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07002822 if (DEBUG) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07002823 Slog.d(TAG, String.format("handlePackageAdded: %s user=%d", packageName, userId));
2824 }
2825 synchronized (mLock) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002826 final ShortcutUser user = getUserShortcutsLocked(userId);
2827 user.attemptToRestoreIfNeededAndSave(this, packageName, userId);
Makoto Onuki64183d52016-08-08 14:11:34 -07002828 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002829 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002830 verifyStates();
Makoto Onuki0acbb142016-03-22 17:02:57 -07002831 }
2832
2833 private void handlePackageUpdateFinished(String packageName, @UserIdInt int userId) {
Makoto Onuki905e8852016-03-28 10:40:58 -07002834 if (DEBUG) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002835 Slog.d(TAG, String.format("handlePackageUpdateFinished: %s user=%d",
2836 packageName, userId));
Makoto Onuki0acbb142016-03-22 17:02:57 -07002837 }
2838 synchronized (mLock) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002839 final ShortcutUser user = getUserShortcutsLocked(userId);
2840 user.attemptToRestoreIfNeededAndSave(this, packageName, userId);
Makoto Onuki39686e82016-04-13 18:03:00 -07002841
Makoto Onuki22fcc682016-05-17 14:52:19 -07002842 if (isPackageInstalled(packageName, userId)) {
Makoto Onuki64183d52016-08-08 14:11:34 -07002843 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onuki39686e82016-04-13 18:03:00 -07002844 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07002845 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002846 verifyStates();
Makoto Onuki0acbb142016-03-22 17:02:57 -07002847 }
2848
Makoto Onuki2e210c42016-03-30 08:30:36 -07002849 private void handlePackageRemoved(String packageName, @UserIdInt int packageUserId) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07002850 if (DEBUG) {
Makoto Onuki2e210c42016-03-30 08:30:36 -07002851 Slog.d(TAG, String.format("handlePackageRemoved: %s user=%d", packageName,
2852 packageUserId));
Makoto Onukicdc78f72016-03-21 15:47:52 -07002853 }
Makoto Onukib08790c2016-06-23 14:05:46 -07002854 cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ false);
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002855
2856 verifyStates();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002857 }
2858
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002859 private void handlePackageDataCleared(String packageName, int packageUserId) {
2860 if (DEBUG) {
2861 Slog.d(TAG, String.format("handlePackageDataCleared: %s user=%d", packageName,
2862 packageUserId));
Makoto Onukicdc78f72016-03-21 15:47:52 -07002863 }
Makoto Onukib08790c2016-06-23 14:05:46 -07002864 cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ true);
2865
2866 verifyStates();
2867 }
2868
2869 private void handlePackageChanged(String packageName, int packageUserId) {
2870 if (DEBUG) {
2871 Slog.d(TAG, String.format("handlePackageChanged: %s user=%d", packageName,
2872 packageUserId));
2873 }
2874
2875 // Activities may be disabled or enabled. Just rescan the package.
2876 synchronized (mLock) {
2877 final ShortcutUser user = getUserShortcutsLocked(packageUserId);
2878
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002879 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07002880 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002881
2882 verifyStates();
Makoto Onukicdc78f72016-03-21 15:47:52 -07002883 }
2884
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002885 // === PackageManager interaction ===
Makoto Onuki0acbb142016-03-22 17:02:57 -07002886
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002887 /**
2888 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
2889 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002890 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002891 final PackageInfo getPackageInfoWithSignatures(String packageName, @UserIdInt int userId) {
2892 return getPackageInfo(packageName, userId, true);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002893 }
2894
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002895 /**
2896 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
2897 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002898 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002899 final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId) {
2900 return getPackageInfo(packageName, userId, false);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002901 }
2902
Makoto Onuki905e8852016-03-28 10:40:58 -07002903 int injectGetPackageUid(@NonNull String packageName, @UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002904 final long token = injectClearCallingIdentity();
Makoto Onuki905e8852016-03-28 10:40:58 -07002905 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002906 return mIPackageManager.getPackageUid(packageName, PACKAGE_MATCH_FLAGS, userId);
Makoto Onuki905e8852016-03-28 10:40:58 -07002907 } catch (RemoteException e) {
2908 // Shouldn't happen.
2909 Slog.wtf(TAG, "RemoteException", e);
2910 return -1;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002911 } finally {
2912 injectRestoreCallingIdentity(token);
Makoto Onuki905e8852016-03-28 10:40:58 -07002913 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07002914 }
2915
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002916 /**
2917 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
2918 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002919 @Nullable
Makoto Onuki0acbb142016-03-22 17:02:57 -07002920 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002921 final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId,
2922 boolean getSignatures) {
2923 return isInstalledOrNull(injectPackageInfoWithUninstalled(
2924 packageName, userId, getSignatures));
2925 }
2926
2927 /**
2928 * Do not use directly; this returns uninstalled packages too.
2929 */
2930 @Nullable
2931 @VisibleForTesting
2932 PackageInfo injectPackageInfoWithUninstalled(String packageName, @UserIdInt int userId,
Makoto Onuki0acbb142016-03-22 17:02:57 -07002933 boolean getSignatures) {
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07002934 final long start = injectElapsedRealtime();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002935 final long token = injectClearCallingIdentity();
Makoto Onuki0acbb142016-03-22 17:02:57 -07002936 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002937 return mIPackageManager.getPackageInfo(
2938 packageName, PACKAGE_MATCH_FLAGS
2939 | (getSignatures ? PackageManager.GET_SIGNATURES : 0), userId);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002940 } catch (RemoteException e) {
2941 // Shouldn't happen.
2942 Slog.wtf(TAG, "RemoteException", e);
2943 return null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002944 } finally {
2945 injectRestoreCallingIdentity(token);
Makoto Onuki2e210c42016-03-30 08:30:36 -07002946
2947 logDurationStat(
2948 (getSignatures ? Stats.GET_PACKAGE_INFO_WITH_SIG : Stats.GET_PACKAGE_INFO),
2949 start);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002950 }
2951 }
2952
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002953 /**
2954 * Returns {@link ApplicationInfo} unless it's uninstalled or disabled.
2955 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002956 @Nullable
Makoto Onuki905e8852016-03-28 10:40:58 -07002957 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002958 final ApplicationInfo getApplicationInfo(String packageName, @UserIdInt int userId) {
2959 return isInstalledOrNull(injectApplicationInfoWithUninstalled(packageName, userId));
2960 }
2961
2962 /**
2963 * Do not use directly; this returns uninstalled packages too.
2964 */
2965 @Nullable
2966 @VisibleForTesting
2967 ApplicationInfo injectApplicationInfoWithUninstalled(
2968 String packageName, @UserIdInt int userId) {
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07002969 final long start = injectElapsedRealtime();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002970 final long token = injectClearCallingIdentity();
Makoto Onuki905e8852016-03-28 10:40:58 -07002971 try {
2972 return mIPackageManager.getApplicationInfo(packageName, PACKAGE_MATCH_FLAGS, userId);
2973 } catch (RemoteException e) {
2974 // Shouldn't happen.
2975 Slog.wtf(TAG, "RemoteException", e);
2976 return null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002977 } finally {
2978 injectRestoreCallingIdentity(token);
Makoto Onuki2e210c42016-03-30 08:30:36 -07002979
2980 logDurationStat(Stats.GET_APPLICATION_INFO, start);
Makoto Onuki905e8852016-03-28 10:40:58 -07002981 }
2982 }
2983
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002984 /**
2985 * Returns {@link ActivityInfo} with its metadata unless it's uninstalled or disabled.
2986 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002987 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002988 final ActivityInfo getActivityInfoWithMetadata(ComponentName activity, @UserIdInt int userId) {
2989 return isInstalledOrNull(injectGetActivityInfoWithMetadataWithUninstalled(
2990 activity, userId));
2991 }
2992
2993 /**
2994 * Do not use directly; this returns uninstalled packages too.
2995 */
2996 @Nullable
2997 @VisibleForTesting
2998 ActivityInfo injectGetActivityInfoWithMetadataWithUninstalled(
2999 ComponentName activity, @UserIdInt int userId) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07003000 final long start = injectElapsedRealtime();
3001 final long token = injectClearCallingIdentity();
3002 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07003003 return mIPackageManager.getActivityInfo(activity,
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003004 (PACKAGE_MATCH_FLAGS | PackageManager.GET_META_DATA), userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003005 } catch (RemoteException e) {
3006 // Shouldn't happen.
3007 Slog.wtf(TAG, "RemoteException", e);
3008 return null;
3009 } finally {
3010 injectRestoreCallingIdentity(token);
3011
Makoto Onukib08790c2016-06-23 14:05:46 -07003012 logDurationStat(Stats.GET_ACTIVITY_WITH_METADATA, start);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003013 }
3014 }
3015
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003016 /**
3017 * Return all installed and enabled packages.
3018 */
3019 @NonNull
Makoto Onuki22fcc682016-05-17 14:52:19 -07003020 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003021 final List<PackageInfo> getInstalledPackages(@UserIdInt int userId) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07003022 final long start = injectElapsedRealtime();
3023 final long token = injectClearCallingIdentity();
3024 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003025 final List<PackageInfo> all = injectGetPackagesWithUninstalled(userId);
3026
3027 all.removeIf(PACKAGE_NOT_INSTALLED);
3028
3029 return all;
Makoto Onuki22fcc682016-05-17 14:52:19 -07003030 } catch (RemoteException e) {
3031 // Shouldn't happen.
3032 Slog.wtf(TAG, "RemoteException", e);
3033 return null;
3034 } finally {
3035 injectRestoreCallingIdentity(token);
3036
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003037 logDurationStat(Stats.GET_INSTALLED_PACKAGES, start);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003038 }
3039 }
3040
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003041 /**
3042 * Do not use directly; this returns uninstalled packages too.
3043 */
3044 @NonNull
3045 @VisibleForTesting
3046 List<PackageInfo> injectGetPackagesWithUninstalled(@UserIdInt int userId)
3047 throws RemoteException {
3048 final ParceledListSlice<PackageInfo> parceledList =
3049 mIPackageManager.getInstalledPackages(PACKAGE_MATCH_FLAGS, userId);
3050 if (parceledList == null) {
3051 return Collections.emptyList();
3052 }
3053 return parceledList.getList();
3054 }
3055
Makoto Onuki33663282016-08-22 16:19:04 -07003056 private void forUpdatedPackages(@UserIdInt int userId, long lastScanTime, boolean afterOta,
Makoto Onuki22fcc682016-05-17 14:52:19 -07003057 Consumer<ApplicationInfo> callback) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003058 if (DEBUG) {
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003059 Slog.d(TAG, "forUpdatedPackages for user " + userId + ", lastScanTime=" + lastScanTime
3060 + " afterOta=" + afterOta);
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003061 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003062 final List<PackageInfo> list = getInstalledPackages(userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003063 for (int i = list.size() - 1; i >= 0; i--) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003064 final PackageInfo pi = list.get(i);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003065
Makoto Onuki64183d52016-08-08 14:11:34 -07003066 // If the package has been updated since the last scan time, then scan it.
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003067 // Also if it's right after an OTA, always re-scan all apps anyway, since the
3068 // shortcut parser might have changed.
3069 if (afterOta || (pi.lastUpdateTime >= lastScanTime)) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003070 if (DEBUG) {
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003071 Slog.d(TAG, "Found updated package " + pi.packageName
3072 + " updateTime=" + pi.lastUpdateTime);
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003073 }
3074 callback.accept(pi.applicationInfo);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003075 }
3076 }
3077 }
3078
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003079 private boolean isApplicationFlagSet(@NonNull String packageName, int userId, int flags) {
3080 final ApplicationInfo ai = injectApplicationInfoWithUninstalled(packageName, userId);
Makoto Onuki905e8852016-03-28 10:40:58 -07003081 return (ai != null) && ((ai.flags & flags) == flags);
3082 }
3083
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003084 private static boolean isInstalled(@Nullable ApplicationInfo ai) {
3085 return (ai != null) && (ai.flags & ApplicationInfo.FLAG_INSTALLED) != 0;
3086 }
3087
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08003088 private static boolean isEphemeralApp(@Nullable ApplicationInfo ai) {
Svetoslav Ganov096d3042017-01-30 16:34:13 -08003089 return (ai != null) && ai.isInstantApp();
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08003090 }
3091
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003092 private static boolean isInstalled(@Nullable PackageInfo pi) {
3093 return (pi != null) && isInstalled(pi.applicationInfo);
3094 }
3095
3096 private static boolean isInstalled(@Nullable ActivityInfo ai) {
3097 return (ai != null) && isInstalled(ai.applicationInfo);
3098 }
3099
3100 private static ApplicationInfo isInstalledOrNull(ApplicationInfo ai) {
3101 return isInstalled(ai) ? ai : null;
3102 }
3103
3104 private static PackageInfo isInstalledOrNull(PackageInfo pi) {
3105 return isInstalled(pi) ? pi : null;
3106 }
3107
3108 private static ActivityInfo isInstalledOrNull(ActivityInfo ai) {
3109 return isInstalled(ai) ? ai : null;
3110 }
3111
Makoto Onuki2e210c42016-03-30 08:30:36 -07003112 boolean isPackageInstalled(String packageName, int userId) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003113 return getApplicationInfo(packageName, userId) != null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003114 }
3115
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08003116 boolean isEphemeralApp(String packageName, int userId) {
3117 return isEphemeralApp(getApplicationInfo(packageName, userId));
3118 }
3119
Makoto Onuki22fcc682016-05-17 14:52:19 -07003120 @Nullable
3121 XmlResourceParser injectXmlMetaData(ActivityInfo activityInfo, String key) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07003122 return activityInfo.loadXmlMetaData(mContext.getPackageManager(), key);
Makoto Onuki39686e82016-04-13 18:03:00 -07003123 }
3124
Makoto Onuki157b1622016-06-02 16:13:10 -07003125 @Nullable
3126 Resources injectGetResourcesForApplicationAsUser(String packageName, int userId) {
3127 final long start = injectElapsedRealtime();
3128 final long token = injectClearCallingIdentity();
3129 try {
3130 return mContext.getPackageManager().getResourcesForApplicationAsUser(
3131 packageName, userId);
3132 } catch (NameNotFoundException e) {
3133 Slog.e(TAG, "Resources for package " + packageName + " not found");
3134 return null;
3135 } finally {
3136 injectRestoreCallingIdentity(token);
3137
3138 logDurationStat(Stats.GET_APPLICATION_RESOURCES, start);
3139 }
3140 }
3141
Makoto Onukib08790c2016-06-23 14:05:46 -07003142 private Intent getMainActivityIntent() {
3143 final Intent intent = new Intent(Intent.ACTION_MAIN);
3144 intent.addCategory(LAUNCHER_INTENT_CATEGORY);
3145 return intent;
3146 }
3147
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003148 /**
3149 * Same as queryIntentActivitiesAsUser, except it makes sure the package is installed,
3150 * and only returns exported activities.
3151 */
3152 @NonNull
3153 @VisibleForTesting
3154 List<ResolveInfo> queryActivities(@NonNull Intent baseIntent,
3155 @NonNull String packageName, @Nullable ComponentName activity, int userId) {
3156
3157 baseIntent.setPackage(Preconditions.checkNotNull(packageName));
3158 if (activity != null) {
3159 baseIntent.setComponent(activity);
3160 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08003161 return queryActivities(baseIntent, userId, /* exportedOnly =*/ true);
3162 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003163
Makoto Onuki2d895c32016-12-02 15:48:40 -08003164 @NonNull
3165 List<ResolveInfo> queryActivities(@NonNull Intent intent, int userId,
3166 boolean exportedOnly) {
3167 final List<ResolveInfo> resolved;
3168 final long token = injectClearCallingIdentity();
3169 try {
3170 resolved =
3171 mContext.getPackageManager().queryIntentActivitiesAsUser(
3172 intent, PACKAGE_MATCH_FLAGS, userId);
3173 } finally {
3174 injectRestoreCallingIdentity(token);
3175 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003176 if (resolved == null || resolved.size() == 0) {
3177 return EMPTY_RESOLVE_INFO;
3178 }
3179 // Make sure the package is installed.
3180 if (!isInstalled(resolved.get(0).activityInfo)) {
3181 return EMPTY_RESOLVE_INFO;
3182 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08003183 if (exportedOnly) {
3184 resolved.removeIf(ACTIVITY_NOT_EXPORTED);
3185 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003186 return resolved;
3187 }
3188
3189 /**
3190 * Return the main activity that is enabled and exported. If multiple activities are found,
3191 * return the first one.
3192 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003193 @Nullable
3194 ComponentName injectGetDefaultMainActivity(@NonNull String packageName, int userId) {
3195 final long start = injectElapsedRealtime();
Makoto Onukib08790c2016-06-23 14:05:46 -07003196 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07003197 final List<ResolveInfo> resolved =
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003198 queryActivities(getMainActivityIntent(), packageName, null, userId);
3199 return resolved.size() == 0 ? null : resolved.get(0).activityInfo.getComponentName();
Makoto Onukib08790c2016-06-23 14:05:46 -07003200 } finally {
Makoto Onukib08790c2016-06-23 14:05:46 -07003201 logDurationStat(Stats.GET_LAUNCHER_ACTIVITY, start);
3202 }
3203 }
3204
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003205 /**
3206 * Return whether an activity is enabled, exported and main.
3207 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003208 boolean injectIsMainActivity(@NonNull ComponentName activity, int userId) {
3209 final long start = injectElapsedRealtime();
Makoto Onukib08790c2016-06-23 14:05:46 -07003210 try {
Makoto Onuki2d895c32016-12-02 15:48:40 -08003211 if (DUMMY_MAIN_ACTIVITY.equals(activity.getClassName())) {
3212 return true;
3213 }
3214 final List<ResolveInfo> resolved = queryActivities(
3215 getMainActivityIntent(), activity.getPackageName(), activity, userId);
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003216 return resolved.size() > 0;
Makoto Onukib08790c2016-06-23 14:05:46 -07003217 } finally {
Makoto Onukib08790c2016-06-23 14:05:46 -07003218 logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start);
3219 }
3220 }
3221
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003222 /**
Makoto Onuki2d895c32016-12-02 15:48:40 -08003223 * Create a dummy "main activity" component name which is used to create a dynamic shortcut
3224 * with no main activity temporarily.
3225 */
3226 @NonNull
3227 ComponentName getDummyMainActivity(@NonNull String packageName) {
3228 return new ComponentName(packageName, DUMMY_MAIN_ACTIVITY);
3229 }
3230
Makoto Onuki255461f2017-01-10 11:47:25 -08003231 boolean isDummyMainActivity(@Nullable ComponentName name) {
3232 return name != null && DUMMY_MAIN_ACTIVITY.equals(name.getClassName());
3233 }
3234
Makoto Onuki2d895c32016-12-02 15:48:40 -08003235 /**
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003236 * Return all the enabled, exported and main activities from a package.
3237 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003238 @NonNull
3239 List<ResolveInfo> injectGetMainActivities(@NonNull String packageName, int userId) {
3240 final long start = injectElapsedRealtime();
Makoto Onukib08790c2016-06-23 14:05:46 -07003241 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003242 return queryActivities(getMainActivityIntent(), packageName, null, userId);
Makoto Onukib08790c2016-06-23 14:05:46 -07003243 } finally {
Makoto Onukib08790c2016-06-23 14:05:46 -07003244 logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start);
3245 }
3246 }
3247
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003248 /**
3249 * Return whether an activity is enabled and exported.
3250 */
3251 @VisibleForTesting
3252 boolean injectIsActivityEnabledAndExported(
3253 @NonNull ComponentName activity, @UserIdInt int userId) {
3254 final long start = injectElapsedRealtime();
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003255 try {
3256 return queryActivities(new Intent(), activity.getPackageName(), activity, userId)
3257 .size() > 0;
3258 } finally {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003259 logDurationStat(Stats.IS_ACTIVITY_ENABLED, start);
3260 }
3261 }
3262
Makoto Onuki2d895c32016-12-02 15:48:40 -08003263 /**
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003264 * Get the {@link LauncherApps#ACTION_CONFIRM_PIN_SHORTCUT} or
3265 * {@link LauncherApps#ACTION_CONFIRM_PIN_APPWIDGET} activity in a given package depending on
3266 * the requestType.
Makoto Onuki2d895c32016-12-02 15:48:40 -08003267 */
3268 @Nullable
3269 ComponentName injectGetPinConfirmationActivity(@NonNull String launcherPackageName,
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003270 int launcherUserId, int requestType) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08003271 Preconditions.checkNotNull(launcherPackageName);
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003272 String action = requestType == LauncherApps.PinItemRequest.REQUEST_TYPE_SHORTCUT ?
3273 LauncherApps.ACTION_CONFIRM_PIN_SHORTCUT :
3274 LauncherApps.ACTION_CONFIRM_PIN_APPWIDGET;
Makoto Onuki2d895c32016-12-02 15:48:40 -08003275
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003276 final Intent confirmIntent = new Intent(action).setPackage(launcherPackageName);
Makoto Onuki2d895c32016-12-02 15:48:40 -08003277 final List<ResolveInfo> candidates = queryActivities(
3278 confirmIntent, launcherUserId, /* exportedOnly =*/ false);
3279 for (ResolveInfo ri : candidates) {
3280 return ri.activityInfo.getComponentName();
3281 }
3282 return null;
3283 }
3284
Makoto Onukib08790c2016-06-23 14:05:46 -07003285 boolean injectIsSafeModeEnabled() {
3286 final long token = injectClearCallingIdentity();
3287 try {
3288 return IWindowManager.Stub
3289 .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE))
3290 .isSafeModeEnabled();
3291 } catch (RemoteException e) {
3292 return false; // Shouldn't happen though.
3293 } finally {
3294 injectRestoreCallingIdentity(token);
3295 }
3296 }
3297
Makoto Onuki2d895c32016-12-02 15:48:40 -08003298 /**
3299 * If {@code userId} is of a managed profile, return the parent user ID. Otherwise return
3300 * itself.
3301 */
3302 int getParentOrSelfUserId(int userId) {
3303 final long token = injectClearCallingIdentity();
3304 try {
3305 final UserInfo parent = mUserManager.getProfileParent(userId);
3306 return (parent != null) ? parent.id : userId;
3307 } finally {
3308 injectRestoreCallingIdentity(token);
3309 }
3310 }
3311
Sunny Goyal87a563e2017-01-01 19:42:45 -08003312 void injectSendIntentSender(IntentSender intentSender, Intent extras) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08003313 if (intentSender == null) {
3314 return;
3315 }
3316 try {
Sunny Goyal87a563e2017-01-01 19:42:45 -08003317 intentSender.sendIntent(mContext, /* code= */ 0, extras,
Makoto Onuki2d895c32016-12-02 15:48:40 -08003318 /* onFinished=*/ null, /* handler= */ null);
3319 } catch (SendIntentException e) {
3320 Slog.w(TAG, "sendIntent failed().", e);
3321 }
3322 }
3323
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003324 // === Backup & restore ===
3325
Makoto Onuki0acbb142016-03-22 17:02:57 -07003326 boolean shouldBackupApp(String packageName, int userId) {
Makoto Onuki905e8852016-03-28 10:40:58 -07003327 return isApplicationFlagSet(packageName, userId, ApplicationInfo.FLAG_ALLOW_BACKUP);
Makoto Onuki0acbb142016-03-22 17:02:57 -07003328 }
3329
Makoto Onuki2e210c42016-03-30 08:30:36 -07003330 boolean shouldBackupApp(PackageInfo pi) {
3331 return (pi.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0;
3332 }
3333
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003334 @Override
Makoto Onuki2e210c42016-03-30 08:30:36 -07003335 public byte[] getBackupPayload(@UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003336 enforceSystem();
3337 if (DEBUG) {
3338 Slog.d(TAG, "Backing up user " + userId);
3339 }
3340 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003341 if (!isUserUnlockedL(userId)) {
3342 wtf("Can't backup: user " + userId + " is locked or not running");
3343 return null;
3344 }
3345
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003346 final ShortcutUser user = getUserShortcutsLocked(userId);
3347 if (user == null) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003348 wtf("Can't backup: user not found: id=" + userId);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003349 return null;
3350 }
3351
Makoto Onukic8c33292016-09-12 16:36:59 -07003352 // Update the signatures for all packages.
3353 user.forAllPackageItems(spi -> spi.refreshPackageSignatureAndSave());
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003354
Makoto Onukic8c33292016-09-12 16:36:59 -07003355 // Set the version code for the launchers.
3356 // We shouldn't do this for publisher packages, because we don't want to update the
3357 // version code without rescanning the manifest.
3358 user.forAllLaunchers(launcher -> launcher.ensureVersionInfo());
3359
3360 // Save to the filesystem.
3361 scheduleSaveUser(userId);
3362 saveDirtyInfo();
3363
3364 // Then create the backup payload.
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003365 final ByteArrayOutputStream os = new ByteArrayOutputStream(32 * 1024);
3366 try {
3367 saveUserInternalLocked(userId, os, /* forBackup */ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07003368 } catch (XmlPullParserException | IOException e) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003369 // Shouldn't happen.
3370 Slog.w(TAG, "Backup failed.", e);
3371 return null;
3372 }
3373 return os.toByteArray();
3374 }
3375 }
3376
3377 @Override
Makoto Onuki2e210c42016-03-30 08:30:36 -07003378 public void applyRestore(byte[] payload, @UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003379 enforceSystem();
3380 if (DEBUG) {
3381 Slog.d(TAG, "Restoring user " + userId);
3382 }
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003383 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003384 if (!isUserUnlockedL(userId)) {
3385 wtf("Can't restore: user " + userId + " is locked or not running");
3386 return;
3387 }
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003388 // Actually do restore.
3389 final ShortcutUser restored;
Makoto Onuki02f338e2016-07-29 09:40:40 -07003390 final ByteArrayInputStream is = new ByteArrayInputStream(payload);
3391 try {
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003392 restored = loadUserInternal(userId, is, /* fromBackup */ true);
3393 } catch (XmlPullParserException | IOException | InvalidFileFormatException e) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003394 Slog.w(TAG, "Restoration failed.", e);
3395 return;
3396 }
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003397 getUserShortcutsLocked(userId).mergeRestoredFile(restored);
Makoto Onuki2e210c42016-03-30 08:30:36 -07003398
Makoto Onuki377b7972016-08-09 14:43:55 -07003399 // Rescan all packages to re-publish manifest shortcuts and do other checks.
3400 rescanUpdatedPackagesLocked(userId,
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003401 0 // lastScanTime = 0; rescan all packages.
3402 );
Makoto Onuki2e210c42016-03-30 08:30:36 -07003403
3404 saveUserLocked(userId);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003405 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07003406 }
3407
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003408 // === Dump ===
3409
3410 @Override
3411 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Makoto Onuki76269922016-07-15 14:58:54 -07003412 enforceCallingOrSelfPermission(android.Manifest.permission.DUMP,
3413 "can't dump by this caller");
3414 boolean checkin = false;
3415 boolean clear = false;
3416 if (args != null) {
3417 for (String arg : args) {
3418 if ("-c".equals(arg)) {
3419 checkin = true;
3420 } else if ("--checkin".equals(arg)) {
3421 checkin = true;
3422 clear = true;
3423 }
3424 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003425 }
Makoto Onuki76269922016-07-15 14:58:54 -07003426
3427 if (checkin) {
3428 dumpCheckin(pw, clear);
3429 } else {
3430 dumpInner(pw);
3431 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003432 }
3433
Makoto Onuki76269922016-07-15 14:58:54 -07003434 private void dumpInner(PrintWriter pw) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003435 synchronized (mLock) {
3436 final long now = injectCurrentTimeMillis();
3437 pw.print("Now: [");
3438 pw.print(now);
3439 pw.print("] ");
3440 pw.print(formatTime(now));
Makoto Onuki55046222016-03-08 10:49:47 -08003441
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003442 pw.print(" Raw last reset: [");
3443 pw.print(mRawLastResetTime);
3444 pw.print("] ");
3445 pw.print(formatTime(mRawLastResetTime));
3446
3447 final long last = getLastResetTimeLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003448 pw.print(" Last reset: [");
3449 pw.print(last);
3450 pw.print("] ");
3451 pw.print(formatTime(last));
3452
Makoto Onuki55046222016-03-08 10:49:47 -08003453 final long next = getNextResetTimeLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003454 pw.print(" Next reset: [");
3455 pw.print(next);
3456 pw.print("] ");
3457 pw.print(formatTime(next));
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003458
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003459 pw.print(" Config:");
3460 pw.print(" Max icon dim: ");
3461 pw.println(mMaxIconDimension);
3462 pw.print(" Icon format: ");
3463 pw.println(mIconPersistFormat);
3464 pw.print(" Icon quality: ");
Makoto Onuki2e210c42016-03-30 08:30:36 -07003465 pw.println(mIconPersistQuality);
Makoto Onuki0033b2a2016-04-14 17:19:16 -07003466 pw.print(" saveDelayMillis: ");
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003467 pw.println(mSaveDelayMillis);
Makoto Onuki0033b2a2016-04-14 17:19:16 -07003468 pw.print(" resetInterval: ");
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003469 pw.println(mResetInterval);
Makoto Onuki0033b2a2016-04-14 17:19:16 -07003470 pw.print(" maxUpdatesPerInterval: ");
Makoto Onukib6d35232016-04-04 15:57:17 -07003471 pw.println(mMaxUpdatesPerInterval);
Makoto Onukib08790c2016-06-23 14:05:46 -07003472 pw.print(" maxShortcutsPerActivity: ");
Makoto Onukib5a012f2016-06-21 11:13:53 -07003473 pw.println(mMaxShortcuts);
Makoto Onuki55046222016-03-08 10:49:47 -08003474 pw.println();
3475
Makoto Onuki2e210c42016-03-30 08:30:36 -07003476 pw.println(" Stats:");
3477 synchronized (mStatLock) {
Makoto Onuki085a05c2016-08-19 11:39:29 -07003478 for (int i = 0; i < Stats.COUNT; i++) {
3479 dumpStatLS(pw, " ", i);
3480 }
Makoto Onuki2e210c42016-03-30 08:30:36 -07003481 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003482
Makoto Onukia2241832016-07-06 13:28:37 -07003483 pw.println();
3484 pw.print(" #Failures: ");
3485 pw.println(mWtfCount);
3486
3487 if (mLastWtfStacktrace != null) {
3488 pw.print(" Last failure stack trace: ");
3489 pw.println(Log.getStackTraceString(mLastWtfStacktrace));
3490 }
3491
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08003492 for (int i = 0; i < mUsers.size(); i++) {
3493 pw.println();
Makoto Onukic51b2872016-05-04 15:24:50 -07003494 mUsers.valueAt(i).dump(pw, " ");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003495 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003496
3497 pw.println();
3498 pw.println(" UID state:");
3499
3500 for (int i = 0; i < mUidState.size(); i++) {
3501 final int uid = mUidState.keyAt(i);
3502 final int state = mUidState.valueAt(i);
3503 pw.print(" UID=");
3504 pw.print(uid);
3505 pw.print(" state=");
3506 pw.print(state);
3507 if (isProcessStateForeground(state)) {
3508 pw.print(" [FG]");
3509 }
3510 pw.print(" last FG=");
3511 pw.print(mUidLastForegroundElapsedTime.get(uid));
3512 pw.println();
3513 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003514 }
3515 }
3516
Makoto Onuki41066a62016-03-09 16:18:44 -08003517 static String formatTime(long time) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003518 Time tobj = new Time();
3519 tobj.set(time);
3520 return tobj.format("%Y-%m-%d %H:%M:%S");
3521 }
3522
Makoto Onuki085a05c2016-08-19 11:39:29 -07003523 private void dumpStatLS(PrintWriter pw, String prefix, int statId) {
Makoto Onuki2e210c42016-03-30 08:30:36 -07003524 pw.print(prefix);
3525 final int count = mCountStats[statId];
3526 final long dur = mDurationStats[statId];
3527 pw.println(String.format("%s: count=%d, total=%dms, avg=%.1fms",
Makoto Onuki085a05c2016-08-19 11:39:29 -07003528 STAT_LABELS[statId], count, dur,
Makoto Onuki2e210c42016-03-30 08:30:36 -07003529 (count == 0 ? 0 : ((double) dur) / count)));
3530 }
3531
Makoto Onuki76269922016-07-15 14:58:54 -07003532 /**
3533 * Dumpsys for checkin.
3534 *
3535 * @param clear if true, clear the history information. Some other system services have this
3536 * behavior but shortcut service doesn't for now.
3537 */
3538 private void dumpCheckin(PrintWriter pw, boolean clear) {
3539 synchronized (mLock) {
3540 try {
3541 final JSONArray users = new JSONArray();
3542
3543 for (int i = 0; i < mUsers.size(); i++) {
3544 users.put(mUsers.valueAt(i).dumpCheckin(clear));
3545 }
3546
3547 final JSONObject result = new JSONObject();
3548
3549 result.put(KEY_SHORTCUT, users);
3550 result.put(KEY_LOW_RAM, injectIsLowRamDevice());
3551 result.put(KEY_ICON_SIZE, mMaxIconDimension);
3552
3553 pw.println(result.toString(1));
3554 } catch (JSONException e) {
3555 Slog.e(TAG, "Unable to write in json", e);
3556 }
3557 }
3558 }
3559
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003560 // === Shell support ===
3561
3562 @Override
3563 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003564 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003565
3566 enforceShell();
3567
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07003568 final long token = injectClearCallingIdentity();
3569 try {
Dianne Hackborn354736e2016-08-22 17:00:05 -07003570 final int status = (new MyShellCommand()).exec(this, in, out, err, args, callback,
3571 resultReceiver);
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07003572 resultReceiver.send(status, null);
3573 } finally {
3574 injectRestoreCallingIdentity(token);
3575 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003576 }
3577
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003578 static class CommandException extends Exception {
3579 public CommandException(String message) {
3580 super(message);
3581 }
3582 }
3583
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003584 /**
3585 * Handle "adb shell cmd".
3586 */
3587 private class MyShellCommand extends ShellCommand {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003588
3589 private int mUserId = UserHandle.USER_SYSTEM;
3590
Makoto Onuki02f338e2016-07-29 09:40:40 -07003591 private void parseOptionsLocked(boolean takeUser)
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003592 throws CommandException {
3593 String opt;
3594 while ((opt = getNextOption()) != null) {
3595 switch (opt) {
3596 case "--user":
3597 if (takeUser) {
3598 mUserId = UserHandle.parseUserArg(getNextArgRequired());
Makoto Onuki02f338e2016-07-29 09:40:40 -07003599 if (!isUserUnlockedL(mUserId)) {
Makoto Onukif34c3082016-07-13 10:25:25 -07003600 throw new CommandException(
3601 "User " + mUserId + " is not running or locked");
3602 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003603 break;
3604 }
3605 // fallthrough
3606 default:
3607 throw new CommandException("Unknown option: " + opt);
3608 }
3609 }
3610 }
3611
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003612 @Override
3613 public int onCommand(String cmd) {
3614 if (cmd == null) {
3615 return handleDefaultCommands(cmd);
3616 }
3617 final PrintWriter pw = getOutPrintWriter();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003618 try {
3619 switch (cmd) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003620 case "reset-throttling":
3621 handleResetThrottling();
3622 break;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003623 case "reset-all-throttling":
3624 handleResetAllThrottling();
3625 break;
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003626 case "override-config":
3627 handleOverrideConfig();
3628 break;
3629 case "reset-config":
3630 handleResetConfig();
3631 break;
3632 case "clear-default-launcher":
3633 handleClearDefaultLauncher();
3634 break;
3635 case "get-default-launcher":
3636 handleGetDefaultLauncher();
3637 break;
Makoto Onukiac214972016-04-04 10:19:45 -07003638 case "unload-user":
3639 handleUnloadUser();
3640 break;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003641 case "clear-shortcuts":
3642 handleClearShortcuts();
3643 break;
Makoto Onukib08790c2016-06-23 14:05:46 -07003644 case "verify-states": // hidden command to verify various internal states.
3645 handleVerifyStates();
3646 break;
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003647 default:
3648 return handleDefaultCommands(cmd);
3649 }
3650 } catch (CommandException e) {
3651 pw.println("Error: " + e.getMessage());
3652 return 1;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003653 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003654 pw.println("Success");
3655 return 0;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003656 }
3657
3658 @Override
3659 public void onHelp() {
3660 final PrintWriter pw = getOutPrintWriter();
3661 pw.println("Usage: cmd shortcut COMMAND [options ...]");
3662 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003663 pw.println("cmd shortcut reset-throttling [--user USER_ID]");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003664 pw.println(" Reset throttling for all packages and users");
3665 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003666 pw.println("cmd shortcut reset-all-throttling");
3667 pw.println(" Reset the throttling state for all users");
3668 pw.println();
Makoto Onuki4362a662016-03-08 18:59:09 -08003669 pw.println("cmd shortcut override-config CONFIG");
3670 pw.println(" Override the configuration for testing (will last until reboot)");
3671 pw.println();
3672 pw.println("cmd shortcut reset-config");
3673 pw.println(" Reset the configuration set with \"update-config\"");
3674 pw.println();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003675 pw.println("cmd shortcut clear-default-launcher [--user USER_ID]");
3676 pw.println(" Clear the cached default launcher");
3677 pw.println();
3678 pw.println("cmd shortcut get-default-launcher [--user USER_ID]");
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07003679 pw.println(" Show the default launcher");
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003680 pw.println();
Makoto Onukiac214972016-04-04 10:19:45 -07003681 pw.println("cmd shortcut unload-user [--user USER_ID]");
3682 pw.println(" Unload a user from the memory");
3683 pw.println(" (This should not affect any observable behavior)");
3684 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003685 pw.println("cmd shortcut clear-shortcuts [--user USER_ID] PACKAGE");
3686 pw.println(" Remove all shortcuts from a package, including pinned shortcuts");
3687 pw.println();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003688 }
3689
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003690 private void handleResetThrottling() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003691 synchronized (mLock) {
3692 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki4554d0e2016-03-14 15:51:41 -07003693
Makoto Onuki02f338e2016-07-29 09:40:40 -07003694 Slog.i(TAG, "cmd: handleResetThrottling: user=" + mUserId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003695
Makoto Onuki02f338e2016-07-29 09:40:40 -07003696 resetThrottlingInner(mUserId);
3697 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003698 }
3699
3700 private void handleResetAllThrottling() {
3701 Slog.i(TAG, "cmd: handleResetAllThrottling");
3702
3703 resetAllThrottlingInner();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003704 }
3705
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003706 private void handleOverrideConfig() throws CommandException {
Makoto Onuki4362a662016-03-08 18:59:09 -08003707 final String config = getNextArgRequired();
3708
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003709 Slog.i(TAG, "cmd: handleOverrideConfig: " + config);
3710
Makoto Onuki4362a662016-03-08 18:59:09 -08003711 synchronized (mLock) {
3712 if (!updateConfigurationLocked(config)) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003713 throw new CommandException("override-config failed. See logcat for details.");
Makoto Onuki4362a662016-03-08 18:59:09 -08003714 }
3715 }
Makoto Onuki4362a662016-03-08 18:59:09 -08003716 }
3717
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003718 private void handleResetConfig() {
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003719 Slog.i(TAG, "cmd: handleResetConfig");
3720
Makoto Onuki4362a662016-03-08 18:59:09 -08003721 synchronized (mLock) {
3722 loadConfigurationLocked();
3723 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003724 }
3725
3726 private void clearLauncher() {
3727 synchronized (mLock) {
Makoto Onuki10305202016-07-14 18:14:08 -07003728 getUserShortcutsLocked(mUserId).forceClearLauncher();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003729 }
3730 }
3731
3732 private void showLauncher() {
3733 synchronized (mLock) {
3734 // This ensures to set the cached launcher. Package name doesn't matter.
3735 hasShortcutHostPermissionInner("-", mUserId);
3736
3737 getOutPrintWriter().println("Launcher: "
Makoto Onuki10305202016-07-14 18:14:08 -07003738 + getUserShortcutsLocked(mUserId).getLastKnownLauncher());
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003739 }
3740 }
3741
3742 private void handleClearDefaultLauncher() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003743 synchronized (mLock) {
3744 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003745
Makoto Onuki02f338e2016-07-29 09:40:40 -07003746 clearLauncher();
3747 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003748 }
3749
3750 private void handleGetDefaultLauncher() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003751 synchronized (mLock) {
3752 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003753
Makoto Onuki02f338e2016-07-29 09:40:40 -07003754 clearLauncher();
3755 showLauncher();
3756 }
Makoto Onuki4362a662016-03-08 18:59:09 -08003757 }
Makoto Onukiac214972016-04-04 10:19:45 -07003758
3759 private void handleUnloadUser() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003760 synchronized (mLock) {
3761 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onukiac214972016-04-04 10:19:45 -07003762
Makoto Onuki02f338e2016-07-29 09:40:40 -07003763 Slog.i(TAG, "cmd: handleUnloadUser: user=" + mUserId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003764
Makoto Onuki02f338e2016-07-29 09:40:40 -07003765 ShortcutService.this.handleCleanupUser(mUserId);
3766 }
Makoto Onukiac214972016-04-04 10:19:45 -07003767 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003768
3769 private void handleClearShortcuts() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003770 synchronized (mLock) {
3771 parseOptionsLocked(/* takeUser =*/ true);
3772 final String packageName = getNextArgRequired();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003773
Makoto Onuki02f338e2016-07-29 09:40:40 -07003774 Slog.i(TAG, "cmd: handleClearShortcuts: user" + mUserId + ", " + packageName);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003775
Makoto Onuki02f338e2016-07-29 09:40:40 -07003776 ShortcutService.this.cleanUpPackageForAllLoadedUsers(packageName, mUserId,
3777 /* appStillExists = */ true);
3778 }
Makoto Onukib08790c2016-06-23 14:05:46 -07003779 }
3780
3781 private void handleVerifyStates() throws CommandException {
3782 try {
3783 verifyStatesForce(); // This will throw when there's an issue.
3784 } catch (Throwable th) {
3785 throw new CommandException(th.getMessage() + "\n" + Log.getStackTraceString(th));
3786 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003787 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003788 }
3789
3790 // === Unit test support ===
3791
3792 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07003793 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003794 long injectCurrentTimeMillis() {
3795 return System.currentTimeMillis();
3796 }
3797
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003798 @VisibleForTesting
3799 long injectElapsedRealtime() {
3800 return SystemClock.elapsedRealtime();
3801 }
3802
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003803 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07003804 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003805 int injectBinderCallingUid() {
3806 return getCallingUid();
3807 }
3808
Makoto Onuki31459242016-03-22 11:12:18 -07003809 private int getCallingUserId() {
Makoto Onuki4554d0e2016-03-14 15:51:41 -07003810 return UserHandle.getUserId(injectBinderCallingUid());
3811 }
3812
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07003813 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07003814 @VisibleForTesting
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07003815 long injectClearCallingIdentity() {
3816 return Binder.clearCallingIdentity();
3817 }
3818
3819 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07003820 @VisibleForTesting
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07003821 void injectRestoreCallingIdentity(long token) {
3822 Binder.restoreCallingIdentity(token);
3823 }
3824
Makoto Onuki33663282016-08-22 16:19:04 -07003825 // Injection point.
3826 @VisibleForTesting
3827 String injectBuildFingerprint() {
3828 return Build.FINGERPRINT;
3829 }
3830
Makoto Onukide667372016-03-15 14:29:20 -07003831 final void wtf(String message) {
Makoto Onukib08790c2016-06-23 14:05:46 -07003832 wtf(message, /* exception= */ null);
Makoto Onukide667372016-03-15 14:29:20 -07003833 }
3834
Makoto Onuki2e210c42016-03-30 08:30:36 -07003835 // Injection point.
Makoto Onukia2241832016-07-06 13:28:37 -07003836 void wtf(String message, Throwable e) {
3837 if (e == null) {
3838 e = new RuntimeException("Stacktrace");
3839 }
3840 synchronized (mLock) {
3841 mWtfCount++;
3842 mLastWtfStacktrace = new Exception("Last failure was logged here:");
3843 }
Makoto Onukide667372016-03-15 14:29:20 -07003844 Slog.wtf(TAG, message, e);
3845 }
3846
Makoto Onuki31459242016-03-22 11:12:18 -07003847 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003848 File injectSystemDataPath() {
3849 return Environment.getDataSystemDirectory();
3850 }
3851
Makoto Onuki31459242016-03-22 11:12:18 -07003852 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003853 File injectUserDataPath(@UserIdInt int userId) {
Makoto Onuki55046222016-03-08 10:49:47 -08003854 return new File(Environment.getDataSystemCeDirectory(userId), DIRECTORY_PER_USER);
3855 }
3856
Makoto Onuki4362a662016-03-08 18:59:09 -08003857 @VisibleForTesting
Makoto Onuki55046222016-03-08 10:49:47 -08003858 boolean injectIsLowRamDevice() {
3859 return ActivityManager.isLowRamDeviceStatic();
3860 }
3861
Makoto Onuki31459242016-03-22 11:12:18 -07003862 @VisibleForTesting
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003863 void injectRegisterUidObserver(IUidObserver observer, int which) {
3864 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003865 ActivityManager.getService().registerUidObserver(observer, which,
Dianne Hackborn5614bf52016-11-07 17:26:41 -08003866 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003867 } catch (RemoteException shouldntHappen) {
3868 }
3869 }
3870
Makoto Onuki55046222016-03-08 10:49:47 -08003871 File getUserBitmapFilePath(@UserIdInt int userId) {
3872 return new File(injectUserDataPath(userId), DIRECTORY_BITMAPS);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003873 }
3874
3875 @VisibleForTesting
Makoto Onuki31459242016-03-22 11:12:18 -07003876 SparseArray<ShortcutUser> getShortcutsForTest() {
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08003877 return mUsers;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003878 }
3879
3880 @VisibleForTesting
Makoto Onukib5a012f2016-06-21 11:13:53 -07003881 int getMaxShortcutsForTest() {
3882 return mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003883 }
3884
3885 @VisibleForTesting
Makoto Onukib6d35232016-04-04 15:57:17 -07003886 int getMaxUpdatesPerIntervalForTest() {
3887 return mMaxUpdatesPerInterval;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003888 }
3889
3890 @VisibleForTesting
Makoto Onuki4362a662016-03-08 18:59:09 -08003891 long getResetIntervalForTest() {
3892 return mResetInterval;
Makoto Onuki55046222016-03-08 10:49:47 -08003893 }
3894
3895 @VisibleForTesting
Makoto Onuki4362a662016-03-08 18:59:09 -08003896 int getMaxIconDimensionForTest() {
3897 return mMaxIconDimension;
3898 }
3899
3900 @VisibleForTesting
3901 CompressFormat getIconPersistFormatForTest() {
3902 return mIconPersistFormat;
3903 }
3904
3905 @VisibleForTesting
3906 int getIconPersistQualityForTest() {
3907 return mIconPersistQuality;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003908 }
Makoto Onuki41066a62016-03-09 16:18:44 -08003909
3910 @VisibleForTesting
Makoto Onuki22fcc682016-05-17 14:52:19 -07003911 ShortcutPackage getPackageShortcutForTest(String packageName, int userId) {
Makoto Onuki41066a62016-03-09 16:18:44 -08003912 synchronized (mLock) {
Makoto Onuki31459242016-03-22 11:12:18 -07003913 final ShortcutUser user = mUsers.get(userId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07003914 if (user == null) return null;
3915
Makoto Onuki22fcc682016-05-17 14:52:19 -07003916 return user.getAllPackagesForTest().get(packageName);
3917 }
3918 }
3919
3920 @VisibleForTesting
3921 ShortcutInfo getPackageShortcutForTest(String packageName, String shortcutId, int userId) {
3922 synchronized (mLock) {
Makoto Onukif34c3082016-07-13 10:25:25 -07003923 final ShortcutPackage pkg = getPackageShortcutForTest(packageName, userId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07003924 if (pkg == null) return null;
3925
3926 return pkg.findShortcutById(shortcutId);
Makoto Onuki41066a62016-03-09 16:18:44 -08003927 }
3928 }
Makoto Onuki7001a612016-05-27 13:24:28 -07003929
Makoto Onukifac592f2016-11-21 13:41:32 -08003930 @VisibleForTesting
3931 ShortcutLauncher getLauncherShortcutForTest(String packageName, int userId) {
3932 synchronized (mLock) {
3933 final ShortcutUser user = mUsers.get(userId);
3934 if (user == null) return null;
3935
3936 return user.getAllLaunchersForTest().get(PackageWithUser.of(userId, packageName));
3937 }
3938 }
3939
Makoto Onuki2d895c32016-12-02 15:48:40 -08003940 @VisibleForTesting
3941 ShortcutRequestPinProcessor getShortcutRequestPinProcessorForTest() {
3942 return mShortcutRequestPinProcessor;
3943 }
3944
Makoto Onuki7001a612016-05-27 13:24:28 -07003945 /**
3946 * Control whether {@link #verifyStates} should be performed. We always perform it during unit
3947 * tests.
3948 */
3949 @VisibleForTesting
3950 boolean injectShouldPerformVerification() {
3951 return DEBUG;
3952 }
3953
3954 /**
3955 * Check various internal states and throws if there's any inconsistency.
3956 * This is normally only enabled during unit tests.
3957 */
3958 final void verifyStates() {
3959 if (injectShouldPerformVerification()) {
3960 verifyStatesInner();
3961 }
3962 }
3963
Makoto Onukib08790c2016-06-23 14:05:46 -07003964 private final void verifyStatesForce() {
3965 verifyStatesInner();
3966 }
3967
Makoto Onuki7001a612016-05-27 13:24:28 -07003968 private void verifyStatesInner() {
Makoto Onuki10305202016-07-14 18:14:08 -07003969 synchronized (mLock) {
Makoto Onuki7001a612016-05-27 13:24:28 -07003970 forEachLoadedUserLocked(u -> u.forAllPackageItems(ShortcutPackageItem::verifyStates));
3971 }
3972 }
Makoto Onuki41066a62016-03-09 16:18:44 -08003973}