blob: 5a0bee1e049b2540573119b3122de7b3c0e477b9 [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 Onuki4d36b3a2016-04-27 12:00:17 -070024import android.app.ActivityManagerNative;
Makoto Onuki0acbb142016-03-22 17:02:57 -070025import android.app.AppGlobals;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -070026import android.app.IUidObserver;
Makoto Onukiac042502016-05-20 16:39:42 -070027import android.app.usage.UsageStatsManagerInternal;
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 Onuki22fcc682016-05-17 14:52:19 -070033import android.content.pm.ActivityInfo;
Makoto Onuki0acbb142016-03-22 17:02:57 -070034import android.content.pm.ApplicationInfo;
35import android.content.pm.IPackageManager;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080036import android.content.pm.IShortcutService;
37import android.content.pm.LauncherApps;
38import android.content.pm.LauncherApps.ShortcutQuery;
Makoto Onuki0acbb142016-03-22 17:02:57 -070039import android.content.pm.PackageInfo;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080040import android.content.pm.PackageManager;
Makoto Onuki20c95f82016-05-11 16:51:01 -070041import android.content.pm.PackageManager.NameNotFoundException;
Makoto Onuki2d5b4652016-03-11 16:09:54 -080042import android.content.pm.PackageManagerInternal;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080043import android.content.pm.ParceledListSlice;
Makoto Onuki2d5b4652016-03-11 16:09:54 -080044import android.content.pm.ResolveInfo;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080045import android.content.pm.ShortcutInfo;
46import android.content.pm.ShortcutServiceInternal;
47import android.content.pm.ShortcutServiceInternal.ShortcutChangeListener;
Makoto Onuki157b1622016-06-02 16:13:10 -070048import android.content.res.Resources;
Makoto Onuki22fcc682016-05-17 14:52:19 -070049import android.content.res.XmlResourceParser;
Makoto Onuki55046222016-03-08 10:49:47 -080050import android.graphics.Bitmap;
51import android.graphics.Bitmap.CompressFormat;
Makoto Onuki55046222016-03-08 10:49:47 -080052import android.graphics.Canvas;
53import android.graphics.RectF;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080054import android.graphics.drawable.Icon;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070055import android.net.Uri;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080056import android.os.Binder;
Makoto Onuki33663282016-08-22 16:19:04 -070057import android.os.Build;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080058import android.os.Environment;
Makoto Onuki2e210c42016-03-30 08:30:36 -070059import android.os.FileUtils;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080060import android.os.Handler;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070061import android.os.LocaleList;
Makoto Onukiaa8b94a2016-03-17 13:14:05 -070062import android.os.Looper;
Makoto Onuki55046222016-03-08 10:49:47 -080063import android.os.ParcelFileDescriptor;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080064import android.os.PersistableBundle;
65import android.os.Process;
66import android.os.RemoteException;
67import android.os.ResultReceiver;
Makoto Onuki55046222016-03-08 10:49:47 -080068import android.os.SELinux;
Makoto Onukib08790c2016-06-23 14:05:46 -070069import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070070import android.os.ShellCallback;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080071import android.os.ShellCommand;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -070072import android.os.SystemClock;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080073import android.os.UserHandle;
Makoto Onukicdc78f72016-03-21 15:47:52 -070074import android.os.UserManager;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080075import android.text.TextUtils;
76import android.text.format.Time;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080077import android.util.ArraySet;
78import android.util.AtomicFile;
Makoto Onuki4362a662016-03-08 18:59:09 -080079import android.util.KeyValueListParser;
Makoto Onukiac042502016-05-20 16:39:42 -070080import android.util.Log;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080081import android.util.Slog;
82import android.util.SparseArray;
Makoto Onuki02f338e2016-07-29 09:40:40 -070083import android.util.SparseBooleanArray;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -070084import android.util.SparseIntArray;
85import android.util.SparseLongArray;
Makoto Onuki55046222016-03-08 10:49:47 -080086import android.util.TypedValue;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080087import android.util.Xml;
Makoto Onukib08790c2016-06-23 14:05:46 -070088import android.view.IWindowManager;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080089
90import com.android.internal.annotations.GuardedBy;
91import com.android.internal.annotations.VisibleForTesting;
92import com.android.internal.os.BackgroundThread;
93import com.android.internal.util.FastXmlSerializer;
94import com.android.internal.util.Preconditions;
95import com.android.server.LocalServices;
96import com.android.server.SystemService;
Makoto Onukid99c6f02016-03-28 11:02:54 -070097import com.android.server.pm.ShortcutUser.PackageWithUser;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080098
99import libcore.io.IoUtils;
100
Makoto Onuki76269922016-07-15 14:58:54 -0700101import org.json.JSONArray;
102import org.json.JSONException;
103import org.json.JSONObject;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800104import org.xmlpull.v1.XmlPullParser;
105import org.xmlpull.v1.XmlPullParserException;
106import org.xmlpull.v1.XmlSerializer;
107
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700108import java.io.BufferedInputStream;
109import java.io.BufferedOutputStream;
110import java.io.ByteArrayInputStream;
111import java.io.ByteArrayOutputStream;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800112import java.io.File;
113import java.io.FileDescriptor;
114import java.io.FileInputStream;
115import java.io.FileNotFoundException;
116import java.io.FileOutputStream;
117import java.io.IOException;
Makoto Onuki55046222016-03-08 10:49:47 -0800118import java.io.InputStream;
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700119import java.io.OutputStream;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800120import java.io.PrintWriter;
Makoto Onuki7001a612016-05-27 13:24:28 -0700121import java.lang.annotation.Retention;
122import java.lang.annotation.RetentionPolicy;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800123import java.net.URISyntaxException;
124import java.nio.charset.StandardCharsets;
125import java.util.ArrayList;
Makoto Onuki22fcc682016-05-17 14:52:19 -0700126import java.util.Collections;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800127import java.util.List;
Makoto Onukic51b2872016-05-04 15:24:50 -0700128import java.util.concurrent.atomic.AtomicBoolean;
Makoto Onuki2e210c42016-03-30 08:30:36 -0700129import java.util.function.Consumer;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800130import java.util.function.Predicate;
131
132/**
133 * TODO:
Makoto Onuki22fcc682016-05-17 14:52:19 -0700134 * - getIconMaxWidth()/getIconMaxHeight() should use xdpi and ydpi.
Makoto Onukib5a012f2016-06-21 11:13:53 -0700135 * -> But TypedValue.applyDimension() doesn't differentiate x and y..?
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800136 *
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700137 * - Detect when already registered instances are passed to APIs again, which might break
Makoto Onukib08790c2016-06-23 14:05:46 -0700138 * internal bitmap handling.
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800139 */
140public class ShortcutService extends IShortcutService.Stub {
Makoto Onuki55046222016-03-08 10:49:47 -0800141 static final String TAG = "ShortcutService";
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800142
Makoto Onuki7001a612016-05-27 13:24:28 -0700143 static final boolean DEBUG = false; // STOPSHIP if true
Makoto Onuki41066a62016-03-09 16:18:44 -0800144 static final boolean DEBUG_LOAD = false; // STOPSHIP if true
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700145 static final boolean DEBUG_PROCSTATE = false; // STOPSHIP if true
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800146
Makoto Onuki4362a662016-03-08 18:59:09 -0800147 @VisibleForTesting
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700148 static final long DEFAULT_RESET_INTERVAL_SEC = 24 * 60 * 60; // 1 day
Makoto Onuki4362a662016-03-08 18:59:09 -0800149
150 @VisibleForTesting
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700151 static final int DEFAULT_MAX_UPDATES_PER_INTERVAL = 10;
Makoto Onuki4362a662016-03-08 18:59:09 -0800152
153 @VisibleForTesting
154 static final int DEFAULT_MAX_SHORTCUTS_PER_APP = 5;
155
156 @VisibleForTesting
157 static final int DEFAULT_MAX_ICON_DIMENSION_DP = 96;
158
159 @VisibleForTesting
160 static final int DEFAULT_MAX_ICON_DIMENSION_LOWRAM_DP = 48;
161
162 @VisibleForTesting
163 static final String DEFAULT_ICON_PERSIST_FORMAT = CompressFormat.PNG.name();
164
165 @VisibleForTesting
166 static final int DEFAULT_ICON_PERSIST_QUALITY = 100;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800167
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700168 @VisibleForTesting
169 static final int DEFAULT_SAVE_DELAY_MS = 3000;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800170
171 @VisibleForTesting
172 static final String FILENAME_BASE_STATE = "shortcut_service.xml";
173
174 @VisibleForTesting
175 static final String DIRECTORY_PER_USER = "shortcut_service";
176
177 @VisibleForTesting
178 static final String FILENAME_USER_PACKAGES = "shortcuts.xml";
179
Makoto Onuki55046222016-03-08 10:49:47 -0800180 static final String DIRECTORY_BITMAPS = "bitmaps";
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800181
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700182 private static final String TAG_ROOT = "root";
183 private static final String TAG_LAST_RESET_TIME = "last_reset_time";
Makoto Onuki55046222016-03-08 10:49:47 -0800184
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700185 private static final String ATTR_VALUE = "value";
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800186
Makoto Onukib08790c2016-06-23 14:05:46 -0700187 private static final String LAUNCHER_INTENT_CATEGORY = Intent.CATEGORY_LAUNCHER;
188
Makoto Onuki76269922016-07-15 14:58:54 -0700189 private static final String KEY_SHORTCUT = "shortcut";
190 private static final String KEY_LOW_RAM = "lowRam";
191 private static final String KEY_ICON_SIZE = "iconSize";
192
Makoto Onuki4362a662016-03-08 18:59:09 -0800193 @VisibleForTesting
194 interface ConfigConstants {
195 /**
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700196 * Key name for the save delay, in milliseconds. (int)
197 */
198 String KEY_SAVE_DELAY_MILLIS = "save_delay_ms";
199
200 /**
Makoto Onuki4362a662016-03-08 18:59:09 -0800201 * Key name for the throttling reset interval, in seconds. (long)
202 */
203 String KEY_RESET_INTERVAL_SEC = "reset_interval_sec";
204
205 /**
206 * Key name for the max number of modifying API calls per app for every interval. (int)
207 */
Makoto Onukib6d35232016-04-04 15:57:17 -0700208 String KEY_MAX_UPDATES_PER_INTERVAL = "max_updates_per_interval";
Makoto Onuki4362a662016-03-08 18:59:09 -0800209
210 /**
211 * Key name for the max icon dimensions in DP, for non-low-memory devices.
212 */
213 String KEY_MAX_ICON_DIMENSION_DP = "max_icon_dimension_dp";
214
215 /**
216 * Key name for the max icon dimensions in DP, for low-memory devices.
217 */
218 String KEY_MAX_ICON_DIMENSION_DP_LOWRAM = "max_icon_dimension_dp_lowram";
219
220 /**
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700221 * Key name for the max dynamic shortcuts per activity. (int)
Makoto Onuki4362a662016-03-08 18:59:09 -0800222 */
223 String KEY_MAX_SHORTCUTS = "max_shortcuts";
224
225 /**
Makoto Onuki41066a62016-03-09 16:18:44 -0800226 * Key name for icon compression quality, 0-100.
Makoto Onuki4362a662016-03-08 18:59:09 -0800227 */
228 String KEY_ICON_QUALITY = "icon_quality";
229
230 /**
231 * Key name for icon compression format: "PNG", "JPEG" or "WEBP"
232 */
233 String KEY_ICON_FORMAT = "icon_format";
234 }
235
Makoto Onuki41066a62016-03-09 16:18:44 -0800236 final Context mContext;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800237
238 private final Object mLock = new Object();
239
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700240 private static List<ResolveInfo> EMPTY_RESOLVE_INFO = new ArrayList<>(0);
241
Mark Renoufe065f7c2016-11-01 11:48:24 -0400242 // Temporarily reverted to anonymous inner class form due to: b/32554459
243 private static Predicate<ResolveInfo> ACTIVITY_NOT_EXPORTED = new Predicate<ResolveInfo>() {
244 public boolean test(ResolveInfo ri) {
245 return !ri.activityInfo.exported;
246 }
247 };
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700248
Mark Renoufe065f7c2016-11-01 11:48:24 -0400249 // Temporarily reverted to anonymous inner class form due to: b/32554459
250 private static Predicate<PackageInfo> PACKAGE_NOT_INSTALLED = new Predicate<PackageInfo>() {
251 public boolean test(PackageInfo pi) {
252 return !isInstalled(pi);
253 }
254 };
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700255
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800256 private final Handler mHandler;
257
258 @GuardedBy("mLock")
259 private final ArrayList<ShortcutChangeListener> mListeners = new ArrayList<>(1);
260
261 @GuardedBy("mLock")
262 private long mRawLastResetTime;
263
264 /**
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -0800265 * User ID -> UserShortcuts
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800266 */
267 @GuardedBy("mLock")
Makoto Onuki31459242016-03-22 11:12:18 -0700268 private final SparseArray<ShortcutUser> mUsers = new SparseArray<>();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800269
270 /**
Makoto Onukib5a012f2016-06-21 11:13:53 -0700271 * Max number of dynamic + manifest shortcuts that each application can have at a time.
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800272 */
Makoto Onukib5a012f2016-06-21 11:13:53 -0700273 private int mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800274
275 /**
Makoto Onukib6d35232016-04-04 15:57:17 -0700276 * Max number of updating API calls that each application can make during the interval.
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800277 */
Makoto Onukib6d35232016-04-04 15:57:17 -0700278 int mMaxUpdatesPerInterval;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800279
280 /**
281 * Actual throttling-reset interval. By default it's a day.
282 */
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800283 private long mResetInterval;
284
Makoto Onuki55046222016-03-08 10:49:47 -0800285 /**
286 * Icon max width/height in pixels.
287 */
288 private int mMaxIconDimension;
289
Makoto Onuki4362a662016-03-08 18:59:09 -0800290 private CompressFormat mIconPersistFormat;
291 private int mIconPersistQuality;
Makoto Onuki55046222016-03-08 10:49:47 -0800292
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700293 private int mSaveDelayMillis;
294
Makoto Onuki0acbb142016-03-22 17:02:57 -0700295 private final IPackageManager mIPackageManager;
Makoto Onuki2d5b4652016-03-11 16:09:54 -0800296 private final PackageManagerInternal mPackageManagerInternal;
Makoto Onukicdc78f72016-03-21 15:47:52 -0700297 private final UserManager mUserManager;
Makoto Onukiac042502016-05-20 16:39:42 -0700298 private final UsageStatsManagerInternal mUsageStatsManagerInternal;
Makoto Onuki33525d22016-08-03 15:45:24 -0700299 private final ActivityManagerInternal mActivityManagerInternal;
Makoto Onuki2d5b4652016-03-11 16:09:54 -0800300
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700301 @GuardedBy("mLock")
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700302 final SparseIntArray mUidState = new SparseIntArray();
303
304 @GuardedBy("mLock")
305 final SparseLongArray mUidLastForegroundElapsedTime = new SparseLongArray();
306
307 @GuardedBy("mLock")
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700308 private List<Integer> mDirtyUserIds = new ArrayList<>();
309
Makoto Onukic51b2872016-05-04 15:24:50 -0700310 private final AtomicBoolean mBootCompleted = new AtomicBoolean();
311
Makoto Onuki905e8852016-03-28 10:40:58 -0700312 private static final int PACKAGE_MATCH_FLAGS =
313 PackageManager.MATCH_DIRECT_BOOT_AWARE
Makoto Onukib08790c2016-06-23 14:05:46 -0700314 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE
315 | PackageManager.MATCH_UNINSTALLED_PACKAGES;
Makoto Onuki905e8852016-03-28 10:40:58 -0700316
Makoto Onuki02f338e2016-07-29 09:40:40 -0700317 @GuardedBy("mLock")
318 final SparseBooleanArray mUnlockedUsers = new SparseBooleanArray();
319
Makoto Onuki2e210c42016-03-30 08:30:36 -0700320 // Stats
321 @VisibleForTesting
322 interface Stats {
323 int GET_DEFAULT_HOME = 0;
324 int GET_PACKAGE_INFO = 1;
325 int GET_PACKAGE_INFO_WITH_SIG = 2;
326 int GET_APPLICATION_INFO = 3;
327 int LAUNCHER_PERMISSION_CHECK = 4;
Makoto Onuki6c1dbd52016-05-02 15:19:32 -0700328 int CLEANUP_DANGLING_BITMAPS = 5;
Makoto Onukib08790c2016-06-23 14:05:46 -0700329 int GET_ACTIVITY_WITH_METADATA = 6;
Makoto Onuki6dd9fb72016-06-01 13:55:54 -0700330 int GET_INSTALLED_PACKAGES = 7;
Makoto Onuki22fcc682016-05-17 14:52:19 -0700331 int CHECK_PACKAGE_CHANGES = 8;
Makoto Onuki157b1622016-06-02 16:13:10 -0700332 int GET_APPLICATION_RESOURCES = 9;
333 int RESOURCE_NAME_LOOKUP = 10;
Makoto Onukib08790c2016-06-23 14:05:46 -0700334 int GET_LAUNCHER_ACTIVITY = 11;
335 int CHECK_LAUNCHER_ACTIVITY = 12;
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700336 int IS_ACTIVITY_ENABLED = 13;
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700337 int PACKAGE_UPDATE_CHECK = 14;
Makoto Onuki085a05c2016-08-19 11:39:29 -0700338 int ASYNC_PRELOAD_USER_DELAY = 15;
Makoto Onuki2e210c42016-03-30 08:30:36 -0700339
Makoto Onuki085a05c2016-08-19 11:39:29 -0700340 int COUNT = ASYNC_PRELOAD_USER_DELAY + 1;
Makoto Onuki2e210c42016-03-30 08:30:36 -0700341 }
342
Makoto Onuki085a05c2016-08-19 11:39:29 -0700343 private static final String[] STAT_LABELS = {
344 "getHomeActivities()",
345 "Launcher permission check",
346 "getPackageInfo()",
347 "getPackageInfo(SIG)",
348 "getApplicationInfo",
349 "cleanupDanglingBitmaps",
350 "getActivity+metadata",
351 "getInstalledPackages",
352 "checkPackageChanges",
353 "getApplicationResources",
354 "resourceNameLookup",
355 "getLauncherActivity",
356 "checkLauncherActivity",
357 "isActivityEnabled",
358 "packageUpdateCheck",
359 "asyncPreloadUserDelay"
360 };
361
Makoto Onuki2e210c42016-03-30 08:30:36 -0700362 final Object mStatLock = new Object();
363
364 @GuardedBy("mStatLock")
365 private final int[] mCountStats = new int[Stats.COUNT];
366
367 @GuardedBy("mStatLock")
368 private final long[] mDurationStats = new long[Stats.COUNT];
369
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700370 private static final int PROCESS_STATE_FOREGROUND_THRESHOLD =
371 ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
372
Makoto Onuki7001a612016-05-27 13:24:28 -0700373 static final int OPERATION_SET = 0;
374 static final int OPERATION_ADD = 1;
375 static final int OPERATION_UPDATE = 2;
376
377 /** @hide */
378 @IntDef(value = {
379 OPERATION_SET,
380 OPERATION_ADD,
381 OPERATION_UPDATE
Makoto Onukib08790c2016-06-23 14:05:46 -0700382 })
Makoto Onuki7001a612016-05-27 13:24:28 -0700383 @Retention(RetentionPolicy.SOURCE)
Makoto Onukib08790c2016-06-23 14:05:46 -0700384 @interface ShortcutOperation {
385 }
Makoto Onuki7001a612016-05-27 13:24:28 -0700386
Makoto Onukia2241832016-07-06 13:28:37 -0700387 @GuardedBy("mLock")
388 private int mWtfCount = 0;
389
390 @GuardedBy("mLock")
391 private Exception mLastWtfStacktrace;
392
Makoto Onukifc4cf2d2016-08-24 11:10:26 -0700393 static class InvalidFileFormatException extends Exception {
394 public InvalidFileFormatException(String message, Throwable cause) {
395 super(message, cause);
396 }
397 }
398
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800399 public ShortcutService(Context context) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700400 this(context, BackgroundThread.get().getLooper(), /*onyForPackgeManagerApis*/ false);
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700401 }
402
403 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700404 ShortcutService(Context context, Looper looper, boolean onlyForPackageManagerApis) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800405 mContext = Preconditions.checkNotNull(context);
406 LocalServices.addService(ShortcutServiceInternal.class, new LocalService());
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700407 mHandler = new Handler(looper);
Makoto Onuki0acbb142016-03-22 17:02:57 -0700408 mIPackageManager = AppGlobals.getPackageManager();
Makoto Onukiac042502016-05-20 16:39:42 -0700409 mPackageManagerInternal = Preconditions.checkNotNull(
410 LocalServices.getService(PackageManagerInternal.class));
411 mUserManager = Preconditions.checkNotNull(context.getSystemService(UserManager.class));
412 mUsageStatsManagerInternal = Preconditions.checkNotNull(
413 LocalServices.getService(UsageStatsManagerInternal.class));
Makoto Onuki33525d22016-08-03 15:45:24 -0700414 mActivityManagerInternal = Preconditions.checkNotNull(
415 LocalServices.getService(ActivityManagerInternal.class));
Makoto Onukicdc78f72016-03-21 15:47:52 -0700416
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700417 if (onlyForPackageManagerApis) {
418 return; // Don't do anything further. For unit tests only.
419 }
420
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700421 // Register receivers.
422
423 // We need to set a priority, so let's just not use PackageMonitor for now.
424 // TODO Refactor PackageMonitor to support priorities.
425 final IntentFilter packageFilter = new IntentFilter();
426 packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
427 packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
428 packageFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
429 packageFilter.addAction(Intent.ACTION_PACKAGE_DATA_CLEARED);
430 packageFilter.addDataScheme("package");
431 packageFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
432 mContext.registerReceiverAsUser(mPackageMonitor, UserHandle.ALL,
433 packageFilter, null, mHandler);
434
Makoto Onuki10305202016-07-14 18:14:08 -0700435 final IntentFilter preferedActivityFilter = new IntentFilter();
436 preferedActivityFilter.addAction(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
437 preferedActivityFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
438 mContext.registerReceiverAsUser(mPackageMonitor, UserHandle.ALL,
439 preferedActivityFilter, null, mHandler);
440
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700441 final IntentFilter localeFilter = new IntentFilter();
442 localeFilter.addAction(Intent.ACTION_LOCALE_CHANGED);
443 localeFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
444 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL,
445 localeFilter, null, mHandler);
Makoto Onukif34c3082016-07-13 10:25:25 -0700446
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700447 injectRegisterUidObserver(mUidObserver, ActivityManager.UID_OBSERVER_PROCSTATE
448 | ActivityManager.UID_OBSERVER_GONE);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800449 }
450
Makoto Onuki2e210c42016-03-30 08:30:36 -0700451 void logDurationStat(int statId, long start) {
452 synchronized (mStatLock) {
453 mCountStats[statId]++;
Makoto Onuki6c1dbd52016-05-02 15:19:32 -0700454 mDurationStats[statId] += (injectElapsedRealtime() - start);
Makoto Onuki2e210c42016-03-30 08:30:36 -0700455 }
456 }
457
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700458 public String injectGetLocaleTagsForUser(@UserIdInt int userId) {
459 // TODO This should get the per-user locale. b/30123329 b/30119489
460 return LocaleList.getDefault().toLanguageTags();
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700461 }
462
463 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Makoto Onukib08790c2016-06-23 14:05:46 -0700464 @Override
465 public void onUidStateChanged(int uid, int procState) throws RemoteException {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700466 handleOnUidStateChanged(uid, procState);
467 }
468
Makoto Onukib08790c2016-06-23 14:05:46 -0700469 @Override
Dianne Hackborne07641d2016-11-09 15:07:23 -0800470 public void onUidGone(int uid, boolean disabled) throws RemoteException {
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800471 handleOnUidStateChanged(uid, ActivityManager.PROCESS_STATE_NONEXISTENT);
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700472 }
473
Makoto Onukib08790c2016-06-23 14:05:46 -0700474 @Override
475 public void onUidActive(int uid) throws RemoteException {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700476 }
477
Makoto Onukib08790c2016-06-23 14:05:46 -0700478 @Override
Dianne Hackborne07641d2016-11-09 15:07:23 -0800479 public void onUidIdle(int uid, boolean disabled) throws RemoteException {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700480 }
481 };
482
483 void handleOnUidStateChanged(int uid, int procState) {
484 if (DEBUG_PROCSTATE) {
485 Slog.d(TAG, "onUidStateChanged: uid=" + uid + " state=" + procState);
486 }
487 synchronized (mLock) {
488 mUidState.put(uid, procState);
489
490 // We need to keep track of last time an app comes to foreground.
491 // See ShortcutPackage.getApiCallCount() for how it's used.
492 // It doesn't have to be persisted, but it needs to be the elapsed time.
493 if (isProcessStateForeground(procState)) {
494 mUidLastForegroundElapsedTime.put(uid, injectElapsedRealtime());
495 }
496 }
497 }
498
499 private boolean isProcessStateForeground(int processState) {
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800500 return processState <= PROCESS_STATE_FOREGROUND_THRESHOLD;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700501 }
502
503 boolean isUidForegroundLocked(int uid) {
504 if (uid == Process.SYSTEM_UID) {
505 // IUidObserver doesn't report the state of SYSTEM, but it always has bound services,
506 // so it's foreground anyway.
507 return true;
508 }
Makoto Onuki33525d22016-08-03 15:45:24 -0700509 // First, check with the local cache.
510 if (isProcessStateForeground(mUidState.get(uid, ActivityManager.MAX_PROCESS_STATE))) {
511 return true;
512 }
513 // If the cache says background, reach out to AM. Since it'll internally need to hold
514 // the AM lock, we use it as a last resort.
515 return isProcessStateForeground(mActivityManagerInternal.getUidProcessState(uid));
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700516 }
517
518 long getUidLastForegroundElapsedTimeLocked(int uid) {
519 return mUidLastForegroundElapsedTime.get(uid);
520 }
521
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800522 /**
523 * System service lifecycle.
524 */
525 public static final class Lifecycle extends SystemService {
526 final ShortcutService mService;
527
528 public Lifecycle(Context context) {
529 super(context);
530 mService = new ShortcutService(context);
531 }
532
533 @Override
534 public void onStart() {
535 publishBinderService(Context.SHORTCUT_SERVICE, mService);
536 }
537
538 @Override
539 public void onBootPhase(int phase) {
540 mService.onBootPhase(phase);
541 }
542
543 @Override
544 public void onCleanupUser(int userHandle) {
Makoto Onukicdc78f72016-03-21 15:47:52 -0700545 mService.handleCleanupUser(userHandle);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800546 }
547
548 @Override
Makoto Onukif3a572b2016-03-10 12:28:38 -0800549 public void onUnlockUser(int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -0700550 mService.handleUnlockUser(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800551 }
552 }
553
554 /** lifecycle event */
555 void onBootPhase(int phase) {
556 if (DEBUG) {
557 Slog.d(TAG, "onBootPhase: " + phase);
558 }
559 switch (phase) {
560 case SystemService.PHASE_LOCK_SETTINGS_READY:
561 initialize();
562 break;
Makoto Onukic51b2872016-05-04 15:24:50 -0700563 case SystemService.PHASE_BOOT_COMPLETED:
564 mBootCompleted.set(true);
565 break;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800566 }
567 }
568
569 /** lifecycle event */
Makoto Onukicdc78f72016-03-21 15:47:52 -0700570 void handleUnlockUser(int userId) {
Makoto Onuki22fcc682016-05-17 14:52:19 -0700571 if (DEBUG) {
Makoto Onuki085a05c2016-08-19 11:39:29 -0700572 Slog.d(TAG, "handleUnlockUser: user=" + userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700573 }
Makoto Onukicdc78f72016-03-21 15:47:52 -0700574 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -0700575 mUnlockedUsers.put(userId, true);
Makoto Onukicdc78f72016-03-21 15:47:52 -0700576 }
Makoto Onuki085a05c2016-08-19 11:39:29 -0700577
578 // Preload the user data.
579 // Note, we don't use mHandler here but instead just start a new thread.
580 // This is because mHandler (which uses com.android.internal.os.BackgroundThread) is very
581 // busy at this point and this could take hundreds of milliseconds, which would be too
582 // late since the launcher would already have started.
583 // So we just create a new thread. This code runs rarely, so we don't use a thread pool
584 // or anything.
585 final long start = injectElapsedRealtime();
586 injectRunOnNewThread(() -> {
587 synchronized (mLock) {
588 logDurationStat(Stats.ASYNC_PRELOAD_USER_DELAY, start);
589 getUserShortcutsLocked(userId);
590 }
591 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800592 }
593
594 /** lifecycle event */
Makoto Onukicdc78f72016-03-21 15:47:52 -0700595 void handleCleanupUser(int userId) {
Makoto Onuki02f338e2016-07-29 09:40:40 -0700596 if (DEBUG) {
597 Slog.d(TAG, "handleCleanupUser: user=" + userId);
598 }
Makoto Onukicdc78f72016-03-21 15:47:52 -0700599 synchronized (mLock) {
600 unloadUserLocked(userId);
Makoto Onuki02f338e2016-07-29 09:40:40 -0700601
602 mUnlockedUsers.put(userId, false);
Makoto Onukicdc78f72016-03-21 15:47:52 -0700603 }
604 }
605
606 private void unloadUserLocked(int userId) {
607 if (DEBUG) {
608 Slog.d(TAG, "unloadUserLocked: user=" + userId);
609 }
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700610 // Save all dirty information.
611 saveDirtyInfo();
612
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800613 // Unload
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -0800614 mUsers.delete(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800615 }
616
617 /** Return the base state file name */
618 private AtomicFile getBaseStateFile() {
619 final File path = new File(injectSystemDataPath(), FILENAME_BASE_STATE);
620 path.mkdirs();
621 return new AtomicFile(path);
622 }
623
624 /**
625 * Init the instance. (load the state file, etc)
626 */
627 private void initialize() {
628 synchronized (mLock) {
Makoto Onuki4362a662016-03-08 18:59:09 -0800629 loadConfigurationLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800630 loadBaseStateLocked();
631 }
632 }
633
Makoto Onuki4362a662016-03-08 18:59:09 -0800634 /**
635 * Load the configuration from Settings.
636 */
637 private void loadConfigurationLocked() {
638 updateConfigurationLocked(injectShortcutManagerConstants());
639 }
Makoto Onuki55046222016-03-08 10:49:47 -0800640
Makoto Onuki4362a662016-03-08 18:59:09 -0800641 /**
642 * Load the configuration from Settings.
643 */
644 @VisibleForTesting
645 boolean updateConfigurationLocked(String config) {
646 boolean result = true;
647
648 final KeyValueListParser parser = new KeyValueListParser(',');
649 try {
650 parser.setString(config);
651 } catch (IllegalArgumentException e) {
652 // Failed to parse the settings string, log this and move on
653 // with defaults.
654 Slog.e(TAG, "Bad shortcut manager settings", e);
655 result = false;
656 }
657
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700658 mSaveDelayMillis = Math.max(0, (int) parser.getLong(ConfigConstants.KEY_SAVE_DELAY_MILLIS,
659 DEFAULT_SAVE_DELAY_MS));
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700660
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700661 mResetInterval = Math.max(1, parser.getLong(
Makoto Onuki4362a662016-03-08 18:59:09 -0800662 ConfigConstants.KEY_RESET_INTERVAL_SEC, DEFAULT_RESET_INTERVAL_SEC)
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700663 * 1000L);
Makoto Onuki4362a662016-03-08 18:59:09 -0800664
Makoto Onukib6d35232016-04-04 15:57:17 -0700665 mMaxUpdatesPerInterval = Math.max(0, (int) parser.getLong(
666 ConfigConstants.KEY_MAX_UPDATES_PER_INTERVAL, DEFAULT_MAX_UPDATES_PER_INTERVAL));
Makoto Onuki4362a662016-03-08 18:59:09 -0800667
Makoto Onukib5a012f2016-06-21 11:13:53 -0700668 mMaxShortcuts = Math.max(0, (int) parser.getLong(
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700669 ConfigConstants.KEY_MAX_SHORTCUTS, DEFAULT_MAX_SHORTCUTS_PER_APP));
Makoto Onuki4362a662016-03-08 18:59:09 -0800670
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700671 final int iconDimensionDp = Math.max(1, injectIsLowRamDevice()
Makoto Onuki4362a662016-03-08 18:59:09 -0800672 ? (int) parser.getLong(
Makoto Onukib08790c2016-06-23 14:05:46 -0700673 ConfigConstants.KEY_MAX_ICON_DIMENSION_DP_LOWRAM,
674 DEFAULT_MAX_ICON_DIMENSION_LOWRAM_DP)
Makoto Onuki4362a662016-03-08 18:59:09 -0800675 : (int) parser.getLong(
Makoto Onukib08790c2016-06-23 14:05:46 -0700676 ConfigConstants.KEY_MAX_ICON_DIMENSION_DP,
677 DEFAULT_MAX_ICON_DIMENSION_DP));
Makoto Onuki4362a662016-03-08 18:59:09 -0800678
679 mMaxIconDimension = injectDipToPixel(iconDimensionDp);
680
681 mIconPersistFormat = CompressFormat.valueOf(
682 parser.getString(ConfigConstants.KEY_ICON_FORMAT, DEFAULT_ICON_PERSIST_FORMAT));
683
684 mIconPersistQuality = (int) parser.getLong(
685 ConfigConstants.KEY_ICON_QUALITY,
686 DEFAULT_ICON_PERSIST_QUALITY);
687
688 return result;
689 }
690
691 @VisibleForTesting
692 String injectShortcutManagerConstants() {
693 return android.provider.Settings.Global.getString(
694 mContext.getContentResolver(),
695 android.provider.Settings.Global.SHORTCUT_MANAGER_CONSTANTS);
696 }
697
698 @VisibleForTesting
699 int injectDipToPixel(int dip) {
700 return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip,
701 mContext.getResources().getDisplayMetrics());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800702 }
703
Makoto Onuki55046222016-03-08 10:49:47 -0800704 // === Persisting ===
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800705
706 @Nullable
Makoto Onuki41066a62016-03-09 16:18:44 -0800707 static String parseStringAttribute(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800708 return parser.getAttributeValue(null, attribute);
709 }
710
Makoto Onuki0acbb142016-03-22 17:02:57 -0700711 static boolean parseBooleanAttribute(XmlPullParser parser, String attribute) {
712 return parseLongAttribute(parser, attribute) == 1;
713 }
714
Makoto Onuki41066a62016-03-09 16:18:44 -0800715 static int parseIntAttribute(XmlPullParser parser, String attribute) {
716 return (int) parseLongAttribute(parser, attribute);
717 }
718
Makoto Onukid99c6f02016-03-28 11:02:54 -0700719 static int parseIntAttribute(XmlPullParser parser, String attribute, int def) {
720 return (int) parseLongAttribute(parser, attribute, def);
721 }
722
Makoto Onuki41066a62016-03-09 16:18:44 -0800723 static long parseLongAttribute(XmlPullParser parser, String attribute) {
Makoto Onukid99c6f02016-03-28 11:02:54 -0700724 return parseLongAttribute(parser, attribute, 0);
725 }
726
727 static long parseLongAttribute(XmlPullParser parser, String attribute, long def) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800728 final String value = parseStringAttribute(parser, attribute);
729 if (TextUtils.isEmpty(value)) {
Makoto Onukid99c6f02016-03-28 11:02:54 -0700730 return def;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800731 }
732 try {
733 return Long.parseLong(value);
734 } catch (NumberFormatException e) {
735 Slog.e(TAG, "Error parsing long " + value);
Makoto Onukid99c6f02016-03-28 11:02:54 -0700736 return def;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800737 }
738 }
739
740 @Nullable
Makoto Onuki41066a62016-03-09 16:18:44 -0800741 static ComponentName parseComponentNameAttribute(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800742 final String value = parseStringAttribute(parser, attribute);
743 if (TextUtils.isEmpty(value)) {
744 return null;
745 }
746 return ComponentName.unflattenFromString(value);
747 }
748
749 @Nullable
Makoto Onuki440a1ea2016-07-20 14:21:18 -0700750 static Intent parseIntentAttributeNoDefault(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800751 final String value = parseStringAttribute(parser, attribute);
Makoto Onukib5a012f2016-06-21 11:13:53 -0700752 Intent parsed = null;
753 if (!TextUtils.isEmpty(value)) {
754 try {
755 parsed = Intent.parseUri(value, /* flags =*/ 0);
756 } catch (URISyntaxException e) {
757 Slog.e(TAG, "Error parsing intent", e);
758 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800759 }
Makoto Onuki440a1ea2016-07-20 14:21:18 -0700760 return parsed;
761 }
762
763 @Nullable
764 static Intent parseIntentAttribute(XmlPullParser parser, String attribute) {
765 Intent parsed = parseIntentAttributeNoDefault(parser, attribute);
Makoto Onukib5a012f2016-06-21 11:13:53 -0700766 if (parsed == null) {
767 // Default intent.
768 parsed = new Intent(Intent.ACTION_VIEW);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800769 }
Makoto Onukib5a012f2016-06-21 11:13:53 -0700770 return parsed;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800771 }
772
Makoto Onuki41066a62016-03-09 16:18:44 -0800773 static void writeTagValue(XmlSerializer out, String tag, String value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800774 if (TextUtils.isEmpty(value)) return;
775
776 out.startTag(null, tag);
777 out.attribute(null, ATTR_VALUE, value);
778 out.endTag(null, tag);
779 }
780
Makoto Onuki41066a62016-03-09 16:18:44 -0800781 static void writeTagValue(XmlSerializer out, String tag, long value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800782 writeTagValue(out, tag, Long.toString(value));
783 }
784
Makoto Onuki2d5b4652016-03-11 16:09:54 -0800785 static void writeTagValue(XmlSerializer out, String tag, ComponentName name) throws IOException {
786 if (name == null) return;
787 writeTagValue(out, tag, name.flattenToString());
788 }
789
Makoto Onuki41066a62016-03-09 16:18:44 -0800790 static void writeTagExtra(XmlSerializer out, String tag, PersistableBundle bundle)
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800791 throws IOException, XmlPullParserException {
792 if (bundle == null) return;
793
794 out.startTag(null, tag);
795 bundle.saveToXml(out);
796 out.endTag(null, tag);
797 }
798
Makoto Onuki22fcc682016-05-17 14:52:19 -0700799 static void writeAttr(XmlSerializer out, String name, CharSequence value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800800 if (TextUtils.isEmpty(value)) return;
801
Makoto Onuki22fcc682016-05-17 14:52:19 -0700802 out.attribute(null, name, value.toString());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800803 }
804
Makoto Onuki41066a62016-03-09 16:18:44 -0800805 static void writeAttr(XmlSerializer out, String name, long value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800806 writeAttr(out, name, String.valueOf(value));
807 }
808
Makoto Onuki0acbb142016-03-22 17:02:57 -0700809 static void writeAttr(XmlSerializer out, String name, boolean value) throws IOException {
810 if (value) {
811 writeAttr(out, name, "1");
812 }
813 }
814
Makoto Onuki41066a62016-03-09 16:18:44 -0800815 static void writeAttr(XmlSerializer out, String name, ComponentName comp) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800816 if (comp == null) return;
817 writeAttr(out, name, comp.flattenToString());
818 }
819
Makoto Onuki41066a62016-03-09 16:18:44 -0800820 static void writeAttr(XmlSerializer out, String name, Intent intent) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800821 if (intent == null) return;
822
823 writeAttr(out, name, intent.toUri(/* flags =*/ 0));
824 }
825
826 @VisibleForTesting
827 void saveBaseStateLocked() {
828 final AtomicFile file = getBaseStateFile();
829 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700830 Slog.d(TAG, "Saving to " + file.getBaseFile());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800831 }
832
833 FileOutputStream outs = null;
834 try {
835 outs = file.startWrite();
836
837 // Write to XML
838 XmlSerializer out = new FastXmlSerializer();
839 out.setOutput(outs, StandardCharsets.UTF_8.name());
840 out.startDocument(null, true);
841 out.startTag(null, TAG_ROOT);
842
843 // Body.
844 writeTagValue(out, TAG_LAST_RESET_TIME, mRawLastResetTime);
845
846 // Epilogue.
847 out.endTag(null, TAG_ROOT);
848 out.endDocument();
849
850 // Close.
851 file.finishWrite(outs);
852 } catch (IOException e) {
853 Slog.e(TAG, "Failed to write to file " + file.getBaseFile(), e);
854 file.failWrite(outs);
855 }
856 }
857
858 private void loadBaseStateLocked() {
859 mRawLastResetTime = 0;
860
861 final AtomicFile file = getBaseStateFile();
862 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700863 Slog.d(TAG, "Loading from " + file.getBaseFile());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800864 }
865 try (FileInputStream in = file.openRead()) {
866 XmlPullParser parser = Xml.newPullParser();
867 parser.setInput(in, StandardCharsets.UTF_8.name());
868
869 int type;
870 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
871 if (type != XmlPullParser.START_TAG) {
872 continue;
873 }
874 final int depth = parser.getDepth();
875 // Check the root tag
876 final String tag = parser.getName();
877 if (depth == 1) {
878 if (!TAG_ROOT.equals(tag)) {
879 Slog.e(TAG, "Invalid root tag: " + tag);
880 return;
881 }
882 continue;
883 }
884 // Assume depth == 2
885 switch (tag) {
886 case TAG_LAST_RESET_TIME:
887 mRawLastResetTime = parseLongAttribute(parser, ATTR_VALUE);
888 break;
889 default:
890 Slog.e(TAG, "Invalid tag: " + tag);
891 break;
892 }
893 }
894 } catch (FileNotFoundException e) {
895 // Use the default
Makoto Onukib08790c2016-06-23 14:05:46 -0700896 } catch (IOException | XmlPullParserException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800897 Slog.e(TAG, "Failed to read file " + file.getBaseFile(), e);
898
899 mRawLastResetTime = 0;
900 }
901 // Adjust the last reset time.
902 getLastResetTimeLocked();
903 }
904
Makoto Onuki0eed4412016-07-21 11:21:59 -0700905 @VisibleForTesting
906 final File getUserFile(@UserIdInt int userId) {
907 return new File(injectUserDataPath(userId), FILENAME_USER_PACKAGES);
908 }
909
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800910 private void saveUserLocked(@UserIdInt int userId) {
Makoto Onuki0eed4412016-07-21 11:21:59 -0700911 final File path = getUserFile(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800912 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700913 Slog.d(TAG, "Saving to " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800914 }
Makoto Onuki0eed4412016-07-21 11:21:59 -0700915 path.getParentFile().mkdirs();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800916 final AtomicFile file = new AtomicFile(path);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700917 FileOutputStream os = null;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800918 try {
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700919 os = file.startWrite();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800920
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700921 saveUserInternalLocked(userId, os, /* forBackup= */ false);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800922
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700923 file.finishWrite(os);
Makoto Onuki1e173232016-08-10 10:47:13 -0700924
925 // Remove all dangling bitmap files.
926 cleanupDanglingBitmapDirectoriesLocked(userId);
Makoto Onukib08790c2016-06-23 14:05:46 -0700927 } catch (XmlPullParserException | IOException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800928 Slog.e(TAG, "Failed to write to file " + file.getBaseFile(), e);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700929 file.failWrite(os);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800930 }
931 }
932
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700933 private void saveUserInternalLocked(@UserIdInt int userId, OutputStream os,
934 boolean forBackup) throws IOException, XmlPullParserException {
935
936 final BufferedOutputStream bos = new BufferedOutputStream(os);
937
938 // Write to XML
939 XmlSerializer out = new FastXmlSerializer();
940 out.setOutput(bos, StandardCharsets.UTF_8.name());
941 out.startDocument(null, true);
942
Makoto Onukic51b2872016-05-04 15:24:50 -0700943 getUserShortcutsLocked(userId).saveToXml(out, forBackup);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700944
945 out.endDocument();
946
947 bos.flush();
948 os.flush();
949 }
950
Makoto Onuki41066a62016-03-09 16:18:44 -0800951 static IOException throwForInvalidTag(int depth, String tag) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800952 throw new IOException(String.format("Invalid tag '%s' found at depth %d", tag, depth));
953 }
954
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700955 static void warnForInvalidTag(int depth, String tag) throws IOException {
956 Slog.w(TAG, String.format("Invalid tag '%s' found at depth %d", tag, depth));
957 }
958
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800959 @Nullable
Makoto Onuki31459242016-03-22 11:12:18 -0700960 private ShortcutUser loadUserLocked(@UserIdInt int userId) {
Makoto Onuki0eed4412016-07-21 11:21:59 -0700961 final File path = getUserFile(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800962 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700963 Slog.d(TAG, "Loading from " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800964 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800965 final AtomicFile file = new AtomicFile(path);
966
967 final FileInputStream in;
968 try {
969 in = file.openRead();
970 } catch (FileNotFoundException e) {
971 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700972 Slog.d(TAG, "Not found " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800973 }
974 return null;
975 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800976 try {
Makoto Onukib08790c2016-06-23 14:05:46 -0700977 final ShortcutUser ret = loadUserInternal(userId, in, /* forBackup= */ false);
Makoto Onuki6c1dbd52016-05-02 15:19:32 -0700978 return ret;
Makoto Onukifc4cf2d2016-08-24 11:10:26 -0700979 } catch (IOException | XmlPullParserException | InvalidFileFormatException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800980 Slog.e(TAG, "Failed to read file " + file.getBaseFile(), e);
981 return null;
982 } finally {
983 IoUtils.closeQuietly(in);
984 }
985 }
986
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700987 private ShortcutUser loadUserInternal(@UserIdInt int userId, InputStream is,
Makoto Onukifc4cf2d2016-08-24 11:10:26 -0700988 boolean fromBackup) throws XmlPullParserException, IOException,
989 InvalidFileFormatException {
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700990
991 final BufferedInputStream bis = new BufferedInputStream(is);
992
993 ShortcutUser ret = null;
994 XmlPullParser parser = Xml.newPullParser();
995 parser.setInput(bis, StandardCharsets.UTF_8.name());
996
997 int type;
998 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
999 if (type != XmlPullParser.START_TAG) {
1000 continue;
1001 }
1002 final int depth = parser.getDepth();
1003
1004 final String tag = parser.getName();
1005 if (DEBUG_LOAD) {
1006 Slog.d(TAG, String.format("depth=%d type=%d name=%s",
1007 depth, type, tag));
1008 }
1009 if ((depth == 1) && ShortcutUser.TAG_ROOT.equals(tag)) {
1010 ret = ShortcutUser.loadFromXml(this, parser, userId, fromBackup);
1011 continue;
1012 }
1013 throwForInvalidTag(depth, tag);
1014 }
1015 return ret;
1016 }
1017
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001018 private void scheduleSaveBaseState() {
Makoto Onuki0acbb142016-03-22 17:02:57 -07001019 scheduleSaveInner(UserHandle.USER_NULL); // Special case -- use USER_NULL for base state.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001020 }
1021
Makoto Onuki2d5b4652016-03-11 16:09:54 -08001022 void scheduleSaveUser(@UserIdInt int userId) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07001023 scheduleSaveInner(userId);
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001024 }
1025
1026 // In order to re-schedule, we need to reuse the same instance, so keep it in final.
1027 private final Runnable mSaveDirtyInfoRunner = this::saveDirtyInfo;
1028
Makoto Onuki0acbb142016-03-22 17:02:57 -07001029 private void scheduleSaveInner(@UserIdInt int userId) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001030 if (DEBUG) {
1031 Slog.d(TAG, "Scheduling to save for " + userId);
1032 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001033 synchronized (mLock) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001034 if (!mDirtyUserIds.contains(userId)) {
1035 mDirtyUserIds.add(userId);
1036 }
1037 }
1038 // If already scheduled, remove that and re-schedule in N seconds.
1039 mHandler.removeCallbacks(mSaveDirtyInfoRunner);
1040 mHandler.postDelayed(mSaveDirtyInfoRunner, mSaveDelayMillis);
1041 }
1042
1043 @VisibleForTesting
1044 void saveDirtyInfo() {
1045 if (DEBUG) {
1046 Slog.d(TAG, "saveDirtyInfo");
1047 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001048 try {
1049 synchronized (mLock) {
1050 for (int i = mDirtyUserIds.size() - 1; i >= 0; i--) {
1051 final int userId = mDirtyUserIds.get(i);
1052 if (userId == UserHandle.USER_NULL) { // USER_NULL for base state.
1053 saveBaseStateLocked();
1054 } else {
1055 saveUserLocked(userId);
1056 }
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001057 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001058 mDirtyUserIds.clear();
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001059 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001060 } catch (Exception e) {
1061 wtf("Exception in saveDirtyInfo", e);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001062 }
1063 }
1064
1065 /** Return the last reset time. */
1066 long getLastResetTimeLocked() {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001067 updateTimesLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001068 return mRawLastResetTime;
1069 }
1070
1071 /** Return the next reset time. */
1072 long getNextResetTimeLocked() {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001073 updateTimesLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001074 return mRawLastResetTime + mResetInterval;
1075 }
1076
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001077 static boolean isClockValid(long time) {
1078 return time >= 1420070400; // Thu, 01 Jan 2015 00:00:00 GMT
1079 }
1080
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001081 /**
1082 * Update the last reset time.
1083 */
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001084 private void updateTimesLocked() {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001085
1086 final long now = injectCurrentTimeMillis();
1087
1088 final long prevLastResetTime = mRawLastResetTime;
1089
1090 if (mRawLastResetTime == 0) { // first launch.
1091 // TODO Randomize??
1092 mRawLastResetTime = now;
1093 } else if (now < mRawLastResetTime) {
1094 // Clock rewound.
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001095 if (isClockValid(now)) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001096 Slog.w(TAG, "Clock rewound");
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001097 // TODO Randomize??
1098 mRawLastResetTime = now;
1099 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001100 } else {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001101 if ((mRawLastResetTime + mResetInterval) <= now) {
1102 final long offset = mRawLastResetTime % mResetInterval;
1103 mRawLastResetTime = ((now / mResetInterval) * mResetInterval) + offset;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001104 }
1105 }
1106 if (prevLastResetTime != mRawLastResetTime) {
1107 scheduleSaveBaseState();
1108 }
1109 }
1110
Makoto Onuki1e173232016-08-10 10:47:13 -07001111 // Requires mLock held, but "Locked" prefix would look weired so we just say "L".
Makoto Onuki02f338e2016-07-29 09:40:40 -07001112 protected boolean isUserUnlockedL(@UserIdInt int userId) {
Makoto Onuki1e173232016-08-10 10:47:13 -07001113 // First, check the local copy.
1114 if (mUnlockedUsers.get(userId)) {
1115 return true;
1116 }
1117 // If the local copy says the user is locked, check with AM for the actual state, since
1118 // the user might just have been unlocked.
1119 // Note we just don't use isUserUnlockingOrUnlocked() here, because it'll return false
1120 // when the user is STOPPING, which we still want to consider as "unlocked".
1121 final long token = injectClearCallingIdentity();
1122 try {
1123 return mUserManager.isUserUnlockingOrUnlocked(userId);
1124 } finally {
1125 injectRestoreCallingIdentity(token);
1126 }
Makoto Onuki9c850012016-07-26 15:50:50 -07001127 }
1128
Makoto Onuki02f338e2016-07-29 09:40:40 -07001129 // Requires mLock held, but "Locked" prefix would look weired so we jsut say "L".
1130 void throwIfUserLockedL(@UserIdInt int userId) {
1131 if (!isUserUnlockedL(userId)) {
Makoto Onuki9c850012016-07-26 15:50:50 -07001132 throw new IllegalStateException("User " + userId + " is locked or not running");
1133 }
1134 }
1135
Makoto Onukicdc78f72016-03-21 15:47:52 -07001136 @GuardedBy("mLock")
1137 @NonNull
Makoto Onuki2e210c42016-03-30 08:30:36 -07001138 private boolean isUserLoadedLocked(@UserIdInt int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07001139 return mUsers.get(userId) != null;
1140 }
1141
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001142 /** Return the per-user state. */
1143 @GuardedBy("mLock")
1144 @NonNull
Makoto Onuki31459242016-03-22 11:12:18 -07001145 ShortcutUser getUserShortcutsLocked(@UserIdInt int userId) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001146 if (!isUserUnlockedL(userId)) {
Makoto Onuki9c850012016-07-26 15:50:50 -07001147 wtf("User still locked");
Makoto Onuki9c850012016-07-26 15:50:50 -07001148 }
1149
Makoto Onuki31459242016-03-22 11:12:18 -07001150 ShortcutUser userPackages = mUsers.get(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001151 if (userPackages == null) {
1152 userPackages = loadUserLocked(userId);
1153 if (userPackages == null) {
Makoto Onukic51b2872016-05-04 15:24:50 -07001154 userPackages = new ShortcutUser(this, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001155 }
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08001156 mUsers.put(userId, userPackages);
Makoto Onuki085a05c2016-08-19 11:39:29 -07001157
1158 // Also when a user's data is first accessed, scan all packages.
1159 checkPackageChanges(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001160 }
1161 return userPackages;
1162 }
1163
Makoto Onuki2e210c42016-03-30 08:30:36 -07001164 void forEachLoadedUserLocked(@NonNull Consumer<ShortcutUser> c) {
1165 for (int i = mUsers.size() - 1; i >= 0; i--) {
1166 c.accept(mUsers.valueAt(i));
1167 }
1168 }
1169
Makoto Onukic8c33292016-09-12 16:36:59 -07001170 /**
1171 * Return the per-user per-package state. If the caller is a publisher, use
1172 * {@link #getPackageShortcutsForPublisherLocked} instead.
1173 */
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001174 @GuardedBy("mLock")
1175 @NonNull
Makoto Onuki31459242016-03-22 11:12:18 -07001176 ShortcutPackage getPackageShortcutsLocked(
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001177 @NonNull String packageName, @UserIdInt int userId) {
Makoto Onukic51b2872016-05-04 15:24:50 -07001178 return getUserShortcutsLocked(userId).getPackageShortcuts(packageName);
Makoto Onukide667372016-03-15 14:29:20 -07001179 }
1180
Makoto Onukic8c33292016-09-12 16:36:59 -07001181 /** Return the per-user per-package state. Use this when the caller is a publisher. */
1182 @GuardedBy("mLock")
1183 @NonNull
1184 ShortcutPackage getPackageShortcutsForPublisherLocked(
1185 @NonNull String packageName, @UserIdInt int userId) {
1186 final ShortcutPackage ret = getUserShortcutsLocked(userId).getPackageShortcuts(packageName);
1187 ret.getUser().onCalledByPublisher(packageName);
1188 return ret;
1189 }
1190
Makoto Onukide667372016-03-15 14:29:20 -07001191 @GuardedBy("mLock")
1192 @NonNull
Makoto Onuki2e210c42016-03-30 08:30:36 -07001193 ShortcutLauncher getLauncherShortcutsLocked(
1194 @NonNull String packageName, @UserIdInt int ownerUserId,
1195 @UserIdInt int launcherUserId) {
1196 return getUserShortcutsLocked(ownerUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07001197 .getLauncherShortcuts(packageName, launcherUserId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001198 }
1199
1200 // === Caller validation ===
1201
Makoto Onuki55046222016-03-08 10:49:47 -08001202 void removeIcon(@UserIdInt int userId, ShortcutInfo shortcut) {
Makoto Onuki1e173232016-08-10 10:47:13 -07001203 // Do not remove the actual bitmap file yet, because if the device crashes before saving
1204 // he XML we'd lose the icon. We just remove all dangling files after saving the XML.
Makoto Onukidd097812016-06-29 13:10:09 -07001205 shortcut.setIconResourceId(0);
1206 shortcut.setIconResName(null);
1207 shortcut.clearFlags(ShortcutInfo.FLAG_HAS_ICON_FILE | ShortcutInfo.FLAG_HAS_ICON_RES);
Makoto Onuki55046222016-03-08 10:49:47 -08001208 }
1209
Makoto Onuki0033b2a2016-04-14 17:19:16 -07001210 public void cleanupBitmapsForPackage(@UserIdInt int userId, String packageName) {
1211 final File packagePath = new File(getUserBitmapFilePath(userId), packageName);
1212 if (!packagePath.isDirectory()) {
1213 return;
1214 }
1215 if (!(FileUtils.deleteContents(packagePath) && packagePath.delete())) {
1216 Slog.w(TAG, "Unable to remove directory " + packagePath);
1217 }
1218 }
1219
Makoto Onuki1e173232016-08-10 10:47:13 -07001220 private void cleanupDanglingBitmapDirectoriesLocked(@UserIdInt int userId) {
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001221 if (DEBUG) {
1222 Slog.d(TAG, "cleanupDanglingBitmaps: userId=" + userId);
1223 }
1224 final long start = injectElapsedRealtime();
1225
Makoto Onuki1e173232016-08-10 10:47:13 -07001226 final ShortcutUser user = getUserShortcutsLocked(userId);
1227
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001228 final File bitmapDir = getUserBitmapFilePath(userId);
1229 final File[] children = bitmapDir.listFiles();
1230 if (children == null) {
1231 return;
1232 }
1233 for (File child : children) {
1234 if (!child.isDirectory()) {
1235 continue;
1236 }
1237 final String packageName = child.getName();
1238 if (DEBUG) {
1239 Slog.d(TAG, "cleanupDanglingBitmaps: Found directory=" + packageName);
1240 }
1241 if (!user.hasPackage(packageName)) {
1242 if (DEBUG) {
1243 Slog.d(TAG, "Removing dangling bitmap directory: " + packageName);
1244 }
1245 cleanupBitmapsForPackage(userId, packageName);
1246 } else {
1247 cleanupDanglingBitmapFilesLocked(userId, user, packageName, child);
1248 }
1249 }
1250 logDurationStat(Stats.CLEANUP_DANGLING_BITMAPS, start);
1251 }
1252
1253 private void cleanupDanglingBitmapFilesLocked(@UserIdInt int userId, @NonNull ShortcutUser user,
1254 @NonNull String packageName, @NonNull File path) {
1255 final ArraySet<String> usedFiles =
Makoto Onukic51b2872016-05-04 15:24:50 -07001256 user.getPackageShortcuts(packageName).getUsedBitmapFiles();
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001257
1258 for (File child : path.listFiles()) {
1259 if (!child.isFile()) {
1260 continue;
1261 }
1262 final String name = child.getName();
1263 if (!usedFiles.contains(name)) {
1264 if (DEBUG) {
1265 Slog.d(TAG, "Removing dangling bitmap file: " + child.getAbsolutePath());
1266 }
1267 child.delete();
1268 }
1269 }
1270 }
1271
Makoto Onuki55046222016-03-08 10:49:47 -08001272 @VisibleForTesting
1273 static class FileOutputStreamWithPath extends FileOutputStream {
1274 private final File mFile;
1275
1276 public FileOutputStreamWithPath(File file) throws FileNotFoundException {
1277 super(file);
1278 mFile = file;
1279 }
1280
1281 public File getFile() {
1282 return mFile;
1283 }
1284 }
1285
1286 /**
1287 * Build the cached bitmap filename for a shortcut icon.
1288 *
1289 * The filename will be based on the ID, except certain characters will be escaped.
1290 */
1291 @VisibleForTesting
1292 FileOutputStreamWithPath openIconFileForWrite(@UserIdInt int userId, ShortcutInfo shortcut)
1293 throws IOException {
1294 final File packagePath = new File(getUserBitmapFilePath(userId),
Makoto Onuki22fcc682016-05-17 14:52:19 -07001295 shortcut.getPackage());
Makoto Onuki55046222016-03-08 10:49:47 -08001296 if (!packagePath.isDirectory()) {
1297 packagePath.mkdirs();
1298 if (!packagePath.isDirectory()) {
1299 throw new IOException("Unable to create directory " + packagePath);
1300 }
1301 SELinux.restorecon(packagePath);
1302 }
1303
1304 final String baseName = String.valueOf(injectCurrentTimeMillis());
Makoto Onukib08790c2016-06-23 14:05:46 -07001305 for (int suffix = 0; ; suffix++) {
Makoto Onuki55046222016-03-08 10:49:47 -08001306 final String filename = (suffix == 0 ? baseName : baseName + "_" + suffix) + ".png";
1307 final File file = new File(packagePath, filename);
1308 if (!file.exists()) {
1309 if (DEBUG) {
1310 Slog.d(TAG, "Saving icon to " + file.getAbsolutePath());
1311 }
1312 return new FileOutputStreamWithPath(file);
1313 }
1314 }
1315 }
1316
1317 void saveIconAndFixUpShortcut(@UserIdInt int userId, ShortcutInfo shortcut) {
1318 if (shortcut.hasIconFile() || shortcut.hasIconResource()) {
1319 return;
1320 }
1321
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001322 final long token = injectClearCallingIdentity();
Makoto Onuki55046222016-03-08 10:49:47 -08001323 try {
1324 // Clear icon info on the shortcut.
Makoto Onukidd097812016-06-29 13:10:09 -07001325 removeIcon(userId, shortcut);
Makoto Onuki55046222016-03-08 10:49:47 -08001326
1327 final Icon icon = shortcut.getIcon();
1328 if (icon == null) {
1329 return; // has no icon
1330 }
1331
Makoto Onukiabe84422016-04-07 09:41:19 -07001332 Bitmap bitmap;
Makoto Onuki55046222016-03-08 10:49:47 -08001333 try {
1334 switch (icon.getType()) {
1335 case Icon.TYPE_RESOURCE: {
1336 injectValidateIconResPackage(shortcut, icon);
1337
1338 shortcut.setIconResourceId(icon.getResId());
1339 shortcut.addFlags(ShortcutInfo.FLAG_HAS_ICON_RES);
1340 return;
1341 }
1342 case Icon.TYPE_BITMAP: {
Makoto Onukiabe84422016-04-07 09:41:19 -07001343 bitmap = icon.getBitmap(); // Don't recycle in this case.
Makoto Onuki55046222016-03-08 10:49:47 -08001344 break;
1345 }
Makoto Onuki55046222016-03-08 10:49:47 -08001346 default:
1347 // This shouldn't happen because we've already validated the icon, but
1348 // just in case.
1349 throw ShortcutInfo.getInvalidIconException();
1350 }
1351 if (bitmap == null) {
1352 Slog.e(TAG, "Null bitmap detected");
1353 return;
1354 }
1355 // Shrink and write to the file.
1356 File path = null;
1357 try {
1358 final FileOutputStreamWithPath out = openIconFileForWrite(userId, shortcut);
1359 try {
1360 path = out.getFile();
1361
Makoto Onukiabe84422016-04-07 09:41:19 -07001362 Bitmap shrunk = shrinkBitmap(bitmap, mMaxIconDimension);
1363 try {
1364 shrunk.compress(mIconPersistFormat, mIconPersistQuality, out);
1365 } finally {
1366 if (bitmap != shrunk) {
1367 shrunk.recycle();
1368 }
1369 }
Makoto Onuki55046222016-03-08 10:49:47 -08001370
1371 shortcut.setBitmapPath(out.getFile().getAbsolutePath());
1372 shortcut.addFlags(ShortcutInfo.FLAG_HAS_ICON_FILE);
1373 } finally {
1374 IoUtils.closeQuietly(out);
1375 }
Makoto Onukib08790c2016-06-23 14:05:46 -07001376 } catch (IOException | RuntimeException e) {
Makoto Onuki55046222016-03-08 10:49:47 -08001377 // STOPSHIP Change wtf to e
1378 Slog.wtf(ShortcutService.TAG, "Unable to write bitmap to file", e);
1379 if (path != null && path.exists()) {
1380 path.delete();
1381 }
1382 }
1383 } finally {
Makoto Onuki55046222016-03-08 10:49:47 -08001384 // Once saved, we won't use the original icon information, so null it out.
1385 shortcut.clearIcon();
1386 }
1387 } finally {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001388 injectRestoreCallingIdentity(token);
Makoto Onuki55046222016-03-08 10:49:47 -08001389 }
1390 }
1391
1392 // Unfortunately we can't do this check in unit tests because we fake creator package names,
1393 // so override in unit tests.
1394 // TODO CTS this case.
1395 void injectValidateIconResPackage(ShortcutInfo shortcut, Icon icon) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07001396 if (!shortcut.getPackage().equals(icon.getResPackage())) {
Makoto Onuki55046222016-03-08 10:49:47 -08001397 throw new IllegalArgumentException(
1398 "Icon resource must reside in shortcut owner package");
1399 }
1400 }
1401
1402 @VisibleForTesting
1403 static Bitmap shrinkBitmap(Bitmap in, int maxSize) {
1404 // Original width/height.
1405 final int ow = in.getWidth();
1406 final int oh = in.getHeight();
1407 if ((ow <= maxSize) && (oh <= maxSize)) {
1408 if (DEBUG) {
1409 Slog.d(TAG, String.format("Icon size %dx%d, no need to shrink", ow, oh));
1410 }
1411 return in;
1412 }
1413 final int longerDimension = Math.max(ow, oh);
1414
1415 // New width and height.
1416 final int nw = ow * maxSize / longerDimension;
1417 final int nh = oh * maxSize / longerDimension;
1418 if (DEBUG) {
1419 Slog.d(TAG, String.format("Icon size %dx%d, shrinking to %dx%d",
1420 ow, oh, nw, nh));
1421 }
1422
1423 final Bitmap scaledBitmap = Bitmap.createBitmap(nw, nh, Bitmap.Config.ARGB_8888);
1424 final Canvas c = new Canvas(scaledBitmap);
1425
1426 final RectF dst = new RectF(0, 0, nw, nh);
1427
1428 c.drawBitmap(in, /*src=*/ null, dst, /* paint =*/ null);
1429
Makoto Onuki55046222016-03-08 10:49:47 -08001430 return scaledBitmap;
1431 }
1432
Makoto Onuki157b1622016-06-02 16:13:10 -07001433 /**
1434 * For a shortcut, update all resource names from resource IDs, and also update all
1435 * resource-based strings.
1436 */
1437 void fixUpShortcutResourceNamesAndValues(ShortcutInfo si) {
1438 final Resources publisherRes = injectGetResourcesForApplicationAsUser(
1439 si.getPackage(), si.getUserId());
1440 if (publisherRes != null) {
1441 final long start = injectElapsedRealtime();
1442 try {
1443 si.lookupAndFillInResourceNames(publisherRes);
1444 } finally {
1445 logDurationStat(Stats.RESOURCE_NAME_LOOKUP, start);
1446 }
1447 si.resolveResourceStrings(publisherRes);
1448 }
1449 }
1450
Makoto Onuki55046222016-03-08 10:49:47 -08001451 // === Caller validation ===
1452
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001453 private boolean isCallerSystem() {
1454 final int callingUid = injectBinderCallingUid();
Makoto Onukib08790c2016-06-23 14:05:46 -07001455 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001456 }
1457
1458 private boolean isCallerShell() {
1459 final int callingUid = injectBinderCallingUid();
1460 return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
1461 }
1462
1463 private void enforceSystemOrShell() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001464 if (!(isCallerSystem() || isCallerShell())) {
1465 throw new SecurityException("Caller must be system or shell");
1466 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001467 }
1468
1469 private void enforceShell() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001470 if (!isCallerShell()) {
1471 throw new SecurityException("Caller must be shell");
1472 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001473 }
1474
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001475 private void enforceSystem() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001476 if (!isCallerSystem()) {
1477 throw new SecurityException("Caller must be system");
1478 }
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001479 }
1480
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001481 private void enforceResetThrottlingPermission() {
1482 if (isCallerSystem()) {
1483 return;
1484 }
Makoto Onuki76269922016-07-15 14:58:54 -07001485 enforceCallingOrSelfPermission(
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001486 android.Manifest.permission.RESET_SHORTCUT_MANAGER_THROTTLING, null);
1487 }
1488
Makoto Onuki76269922016-07-15 14:58:54 -07001489 private void enforceCallingOrSelfPermission(
1490 @NonNull String permission, @Nullable String message) {
1491 if (isCallerSystem()) {
1492 return;
1493 }
1494 injectEnforceCallingPermission(permission, message);
1495 }
1496
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001497 /**
1498 * Somehow overriding ServiceContext.enforceCallingPermission() in the unit tests would confuse
1499 * mockito. So instead we extracted it here and override it in the tests.
1500 */
1501 @VisibleForTesting
1502 void injectEnforceCallingPermission(
1503 @NonNull String permission, @Nullable String message) {
1504 mContext.enforceCallingPermission(permission, message);
1505 }
1506
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001507 private void verifyCaller(@NonNull String packageName, @UserIdInt int userId) {
1508 Preconditions.checkStringNotEmpty(packageName, "packageName");
1509
1510 if (isCallerSystem()) {
1511 return; // no check
1512 }
1513
1514 final int callingUid = injectBinderCallingUid();
1515
1516 // Otherwise, make sure the arguments are valid.
1517 if (UserHandle.getUserId(callingUid) != userId) {
1518 throw new SecurityException("Invalid user-ID");
1519 }
Makoto Onuki55046222016-03-08 10:49:47 -08001520 if (injectGetPackageUid(packageName, userId) == injectBinderCallingUid()) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001521 return; // Caller is valid.
1522 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07001523 throw new SecurityException("Calling package name mismatch");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001524 }
1525
Makoto Onuki157b1622016-06-02 16:13:10 -07001526 // Overridden in unit tests to execute r synchronously.
1527 void injectPostToHandler(Runnable r) {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001528 mHandler.post(r);
1529 }
1530
Makoto Onuki085a05c2016-08-19 11:39:29 -07001531 void injectRunOnNewThread(Runnable r) {
1532 new Thread(r).start();
1533 }
1534
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001535 /**
Makoto Onuki7001a612016-05-27 13:24:28 -07001536 * @throws IllegalArgumentException if {@code numShortcuts} is bigger than
Makoto Onukib08790c2016-06-23 14:05:46 -07001537 * {@link #getMaxActivityShortcuts()}.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001538 */
Makoto Onuki7001a612016-05-27 13:24:28 -07001539 void enforceMaxActivityShortcuts(int numShortcuts) {
Makoto Onukib5a012f2016-06-21 11:13:53 -07001540 if (numShortcuts > mMaxShortcuts) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001541 throw new IllegalArgumentException("Max number of dynamic shortcuts exceeded");
1542 }
1543 }
1544
1545 /**
Makoto Onuki7001a612016-05-27 13:24:28 -07001546 * Return the max number of dynamic + manifest shortcuts for each launcher icon.
1547 */
1548 int getMaxActivityShortcuts() {
Makoto Onukib5a012f2016-06-21 11:13:53 -07001549 return mMaxShortcuts;
Makoto Onuki7001a612016-05-27 13:24:28 -07001550 }
1551
1552 /**
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001553 * - Sends a notification to LauncherApps
1554 * - Write to file
1555 */
Makoto Onuki39686e82016-04-13 18:03:00 -07001556 void packageShortcutsChanged(@NonNull String packageName, @UserIdInt int userId) {
1557 if (DEBUG) {
1558 Slog.d(TAG, String.format(
1559 "Shortcut changes: package=%s, user=%d", packageName, userId));
1560 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001561 notifyListeners(packageName, userId);
1562 scheduleSaveUser(userId);
1563 }
1564
1565 private void notifyListeners(@NonNull String packageName, @UserIdInt int userId) {
Makoto Onuki157b1622016-06-02 16:13:10 -07001566 injectPostToHandler(() -> {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001567 try {
1568 final ArrayList<ShortcutChangeListener> copy;
1569 synchronized (mLock) {
1570 if (!isUserUnlockedL(userId)) {
1571 return;
1572 }
1573
1574 copy = new ArrayList<>(mListeners);
1575 }
1576 // Note onShortcutChanged() needs to be called with the system service permissions.
1577 for (int i = copy.size() - 1; i >= 0; i--) {
1578 copy.get(i).onShortcutChanged(packageName, userId);
1579 }
1580 } catch (Exception ignore) {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001581 }
1582 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001583 }
1584
1585 /**
1586 * Clean up / validate an incoming shortcut.
1587 * - Make sure all mandatory fields are set.
1588 * - Make sure the intent's extras are persistable, and them to set
Makoto Onuki0eed4412016-07-21 11:21:59 -07001589 * {@link ShortcutInfo#mIntentPersistableExtrases}. Also clear its extras.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001590 * - Clear flags.
Makoto Onuki55046222016-03-08 10:49:47 -08001591 *
1592 * TODO Detailed unit tests
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001593 */
Makoto Onuki55046222016-03-08 10:49:47 -08001594 private void fixUpIncomingShortcutInfo(@NonNull ShortcutInfo shortcut, boolean forUpdate) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001595 Preconditions.checkNotNull(shortcut, "Null shortcut detected");
Makoto Onuki22fcc682016-05-17 14:52:19 -07001596 if (shortcut.getActivity() != null) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001597 Preconditions.checkState(
Makoto Onuki22fcc682016-05-17 14:52:19 -07001598 shortcut.getPackage().equals(shortcut.getActivity().getPackageName()),
Makoto Onukib08790c2016-06-23 14:05:46 -07001599 "Cannot publish shortcut: activity " + shortcut.getActivity() + " does not"
1600 + " belong to package " + shortcut.getPackage());
Makoto Onuki13260b6ff2016-07-13 18:03:13 -07001601 Preconditions.checkState(
1602 injectIsMainActivity(shortcut.getActivity(), shortcut.getUserId()),
1603 "Cannot publish shortcut: activity " + shortcut.getActivity() + " is not"
1604 + " main activity");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001605 }
1606
Makoto Onuki55046222016-03-08 10:49:47 -08001607 if (!forUpdate) {
1608 shortcut.enforceMandatoryFields();
Makoto Onukib08790c2016-06-23 14:05:46 -07001609 Preconditions.checkArgument(
1610 injectIsMainActivity(shortcut.getActivity(), shortcut.getUserId()),
1611 "Cannot publish shortcut: " + shortcut.getActivity() + " is not main activity");
Makoto Onuki55046222016-03-08 10:49:47 -08001612 }
1613 if (shortcut.getIcon() != null) {
1614 ShortcutInfo.validateIcon(shortcut.getIcon());
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001615 }
1616
Makoto Onukide667372016-03-15 14:29:20 -07001617 shortcut.replaceFlags(0);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001618 }
1619
Makoto Onukib08790c2016-06-23 14:05:46 -07001620 /**
1621 * When a shortcut has no target activity, set the default one from the package.
1622 */
1623 private void fillInDefaultActivity(List<ShortcutInfo> shortcuts) {
1624
1625 ComponentName defaultActivity = null;
1626 for (int i = shortcuts.size() - 1; i >= 0; i--) {
1627 final ShortcutInfo si = shortcuts.get(i);
1628 if (si.getActivity() == null) {
1629 if (defaultActivity == null) {
1630 defaultActivity = injectGetDefaultMainActivity(
1631 si.getPackage(), si.getUserId());
1632 Preconditions.checkState(defaultActivity != null,
1633 "Launcher activity not found for package " + si.getPackage());
1634 }
1635 si.setActivity(defaultActivity);
1636 }
1637 }
1638 }
1639
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001640 private void assignImplicitRanks(List<ShortcutInfo> shortcuts) {
1641 for (int i = shortcuts.size() - 1; i >= 0; i--) {
1642 shortcuts.get(i).setImplicitRank(i);
1643 }
1644 }
1645
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001646 // === APIs ===
1647
1648 @Override
1649 public boolean setDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1650 @UserIdInt int userId) {
1651 verifyCaller(packageName, userId);
1652
1653 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
1654 final int size = newShortcuts.size();
1655
1656 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001657 throwIfUserLockedL(userId);
1658
Makoto Onukic8c33292016-09-12 16:36:59 -07001659 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001660
Makoto Onuki22fcc682016-05-17 14:52:19 -07001661 ps.ensureImmutableShortcutsNotIncluded(newShortcuts);
1662
Makoto Onukib08790c2016-06-23 14:05:46 -07001663 fillInDefaultActivity(newShortcuts);
1664
Makoto Onuki7001a612016-05-27 13:24:28 -07001665 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_SET);
1666
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001667 // Throttling.
Makoto Onukic51b2872016-05-04 15:24:50 -07001668 if (!ps.tryApiCall()) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001669 return false;
1670 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001671
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001672 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1673 ps.clearAllImplicitRanks();
1674 assignImplicitRanks(newShortcuts);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001675
Makoto Onukidf6da042016-06-16 09:51:40 -07001676 for (int i = 0; i < size; i++) {
1677 fixUpIncomingShortcutInfo(newShortcuts.get(i), /* forUpdate= */ false);
1678 }
1679
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001680 // First, remove all un-pinned; dynamic shortcuts
Makoto Onukic51b2872016-05-04 15:24:50 -07001681 ps.deleteAllDynamicShortcuts();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001682
1683 // Then, add/update all. We need to make sure to take over "pinned" flag.
1684 for (int i = 0; i < size; i++) {
1685 final ShortcutInfo newShortcut = newShortcuts.get(i);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001686 ps.addOrUpdateDynamicShortcut(newShortcut);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001687 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001688
1689 // Lastly, adjust the ranks.
1690 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001691 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001692 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001693
1694 verifyStates();
1695
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001696 return true;
1697 }
1698
1699 @Override
1700 public boolean updateShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1701 @UserIdInt int userId) {
1702 verifyCaller(packageName, userId);
1703
1704 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
Makoto Onuki55046222016-03-08 10:49:47 -08001705 final int size = newShortcuts.size();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001706
1707 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001708 throwIfUserLockedL(userId);
1709
Makoto Onukic8c33292016-09-12 16:36:59 -07001710 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001711
Makoto Onuki22fcc682016-05-17 14:52:19 -07001712 ps.ensureImmutableShortcutsNotIncluded(newShortcuts);
1713
Makoto Onukib08790c2016-06-23 14:05:46 -07001714 // For update, don't fill in the default activity. Having null activity means
1715 // "don't update the activity" here.
1716
Makoto Onuki7001a612016-05-27 13:24:28 -07001717 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_UPDATE);
1718
Makoto Onuki55046222016-03-08 10:49:47 -08001719 // Throttling.
Makoto Onukic51b2872016-05-04 15:24:50 -07001720 if (!ps.tryApiCall()) {
Makoto Onuki55046222016-03-08 10:49:47 -08001721 return false;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001722 }
1723
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001724 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1725 ps.clearAllImplicitRanks();
1726 assignImplicitRanks(newShortcuts);
1727
Makoto Onuki55046222016-03-08 10:49:47 -08001728 for (int i = 0; i < size; i++) {
1729 final ShortcutInfo source = newShortcuts.get(i);
1730 fixUpIncomingShortcutInfo(source, /* forUpdate= */ true);
1731
1732 final ShortcutInfo target = ps.findShortcutById(source.getId());
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001733 if (target == null) {
1734 continue;
1735 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07001736
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001737 if (target.isEnabled() != source.isEnabled()) {
1738 Slog.w(TAG,
1739 "ShortcutInfo.enabled cannot be changed with updateShortcuts()");
1740 }
Makoto Onuki55046222016-03-08 10:49:47 -08001741
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001742 // When updating the rank, we need to insert between existing ranks, so set
1743 // this setRankChanged, and also copy the implicit rank fo adjustRanks().
1744 if (source.hasRank()) {
1745 target.setRankChanged();
1746 target.setImplicitRank(source.getImplicitRank());
1747 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07001748
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001749 final boolean replacingIcon = (source.getIcon() != null);
1750 if (replacingIcon) {
1751 removeIcon(userId, target);
1752 }
Makoto Onuki55046222016-03-08 10:49:47 -08001753
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001754 // Note copyNonNullFieldsFrom() does the "updatable with?" check too.
1755 target.copyNonNullFieldsFrom(source);
1756 target.setTimestamp(injectCurrentTimeMillis());
1757
1758 if (replacingIcon) {
1759 saveIconAndFixUpShortcut(userId, target);
1760 }
1761
1762 // When we're updating any resource related fields, re-extract the res names and
1763 // the values.
1764 if (replacingIcon || source.hasStringResources()) {
1765 fixUpShortcutResourceNamesAndValues(target);
Makoto Onuki55046222016-03-08 10:49:47 -08001766 }
1767 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001768
1769 // Lastly, adjust the ranks.
1770 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001771 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001772 packageShortcutsChanged(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001773
Makoto Onuki7001a612016-05-27 13:24:28 -07001774 verifyStates();
1775
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001776 return true;
1777 }
1778
1779 @Override
Makoto Onukib6d35232016-04-04 15:57:17 -07001780 public boolean addDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001781 @UserIdInt int userId) {
1782 verifyCaller(packageName, userId);
1783
Makoto Onukib6d35232016-04-04 15:57:17 -07001784 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
1785 final int size = newShortcuts.size();
1786
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001787 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001788 throwIfUserLockedL(userId);
1789
Makoto Onukic8c33292016-09-12 16:36:59 -07001790 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001791
Makoto Onuki22fcc682016-05-17 14:52:19 -07001792 ps.ensureImmutableShortcutsNotIncluded(newShortcuts);
1793
Makoto Onukib08790c2016-06-23 14:05:46 -07001794 fillInDefaultActivity(newShortcuts);
1795
Makoto Onuki7001a612016-05-27 13:24:28 -07001796 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_ADD);
1797
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001798 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1799 ps.clearAllImplicitRanks();
1800 assignImplicitRanks(newShortcuts);
1801
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001802 // Throttling.
Makoto Onukic51b2872016-05-04 15:24:50 -07001803 if (!ps.tryApiCall()) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001804 return false;
1805 }
Makoto Onukib6d35232016-04-04 15:57:17 -07001806 for (int i = 0; i < size; i++) {
1807 final ShortcutInfo newShortcut = newShortcuts.get(i);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001808
Makoto Onukib6d35232016-04-04 15:57:17 -07001809 // Validate the shortcut.
1810 fixUpIncomingShortcutInfo(newShortcut, /* forUpdate= */ false);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001811
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001812 // When ranks are changing, we need to insert between ranks, so set the
1813 // "rank changed" flag.
1814 newShortcut.setRankChanged();
1815
Makoto Onukib6d35232016-04-04 15:57:17 -07001816 // Add it.
Makoto Onuki22fcc682016-05-17 14:52:19 -07001817 ps.addOrUpdateDynamicShortcut(newShortcut);
Makoto Onukib6d35232016-04-04 15:57:17 -07001818 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001819
1820 // Lastly, adjust the ranks.
1821 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001822 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001823 packageShortcutsChanged(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001824
Makoto Onuki7001a612016-05-27 13:24:28 -07001825 verifyStates();
1826
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001827 return true;
1828 }
1829
1830 @Override
Makoto Onuki20c95f82016-05-11 16:51:01 -07001831 public void disableShortcuts(String packageName, List shortcutIds,
Makoto Onukid6880792016-06-29 13:37:43 -07001832 CharSequence disabledMessage, int disabledMessageResId, @UserIdInt int userId) {
Makoto Onuki20c95f82016-05-11 16:51:01 -07001833 verifyCaller(packageName, userId);
1834 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
1835
1836 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001837 throwIfUserLockedL(userId);
1838
Makoto Onukic8c33292016-09-12 16:36:59 -07001839 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001840
1841 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds);
1842
Makoto Onukid6880792016-06-29 13:37:43 -07001843 final String disabledMessageString =
1844 (disabledMessage == null) ? null : disabledMessage.toString();
1845
Makoto Onuki22fcc682016-05-17 14:52:19 -07001846 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
1847 ps.disableWithId(Preconditions.checkStringNotEmpty((String) shortcutIds.get(i)),
Makoto Onukid6880792016-06-29 13:37:43 -07001848 disabledMessageString, disabledMessageResId,
Makoto Onuki22fcc682016-05-17 14:52:19 -07001849 /* overrideImmutable=*/ false);
1850 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001851
1852 // We may have removed dynamic shortcuts which may have left a gap, so adjust the ranks.
1853 ps.adjustRanks();
Makoto Onuki22fcc682016-05-17 14:52:19 -07001854 }
1855 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001856
1857 verifyStates();
Makoto Onuki22fcc682016-05-17 14:52:19 -07001858 }
1859
1860 @Override
1861 public void enableShortcuts(String packageName, List shortcutIds, @UserIdInt int userId) {
1862 verifyCaller(packageName, userId);
1863 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
1864
1865 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001866 throwIfUserLockedL(userId);
1867
Makoto Onukic8c33292016-09-12 16:36:59 -07001868 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001869
1870 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds);
1871
1872 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
1873 ps.enableWithId((String) shortcutIds.get(i));
1874 }
Makoto Onuki20c95f82016-05-11 16:51:01 -07001875 }
1876 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001877
1878 verifyStates();
Makoto Onuki20c95f82016-05-11 16:51:01 -07001879 }
1880
1881 @Override
Makoto Onukib6d35232016-04-04 15:57:17 -07001882 public void removeDynamicShortcuts(String packageName, List shortcutIds,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001883 @UserIdInt int userId) {
1884 verifyCaller(packageName, userId);
Makoto Onukib6d35232016-04-04 15:57:17 -07001885 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001886
1887 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001888 throwIfUserLockedL(userId);
1889
Makoto Onukic8c33292016-09-12 16:36:59 -07001890 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001891
1892 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds);
1893
Makoto Onukib6d35232016-04-04 15:57:17 -07001894 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07001895 ps.deleteDynamicWithId(
Makoto Onukib6d35232016-04-04 15:57:17 -07001896 Preconditions.checkStringNotEmpty((String) shortcutIds.get(i)));
1897 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001898
1899 // We may have removed dynamic shortcuts which may have left a gap, so adjust the ranks.
1900 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001901 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001902 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001903
1904 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001905 }
1906
1907 @Override
Makoto Onukib6d35232016-04-04 15:57:17 -07001908 public void removeAllDynamicShortcuts(String packageName, @UserIdInt int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001909 verifyCaller(packageName, userId);
1910
1911 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001912 throwIfUserLockedL(userId);
1913
Makoto Onukic8c33292016-09-12 16:36:59 -07001914 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07001915 ps.deleteAllDynamicShortcuts();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001916 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001917 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001918
1919 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001920 }
1921
1922 @Override
1923 public ParceledListSlice<ShortcutInfo> getDynamicShortcuts(String packageName,
1924 @UserIdInt int userId) {
1925 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07001926
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001927 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001928 throwIfUserLockedL(userId);
1929
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001930 return getShortcutsWithQueryLocked(
1931 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
1932 ShortcutInfo::isDynamic);
1933 }
1934 }
1935
1936 @Override
Makoto Onuki22fcc682016-05-17 14:52:19 -07001937 public ParceledListSlice<ShortcutInfo> getManifestShortcuts(String packageName,
1938 @UserIdInt int userId) {
1939 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07001940
Makoto Onuki22fcc682016-05-17 14:52:19 -07001941 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001942 throwIfUserLockedL(userId);
1943
Makoto Onuki22fcc682016-05-17 14:52:19 -07001944 return getShortcutsWithQueryLocked(
1945 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
1946 ShortcutInfo::isManifestShortcut);
1947 }
1948 }
1949
1950 @Override
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001951 public ParceledListSlice<ShortcutInfo> getPinnedShortcuts(String packageName,
1952 @UserIdInt int userId) {
1953 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07001954
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001955 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001956 throwIfUserLockedL(userId);
1957
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001958 return getShortcutsWithQueryLocked(
1959 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
1960 ShortcutInfo::isPinned);
1961 }
1962 }
1963
1964 private ParceledListSlice<ShortcutInfo> getShortcutsWithQueryLocked(@NonNull String packageName,
1965 @UserIdInt int userId, int cloneFlags, @NonNull Predicate<ShortcutInfo> query) {
1966
1967 final ArrayList<ShortcutInfo> ret = new ArrayList<>();
1968
Makoto Onukic8c33292016-09-12 16:36:59 -07001969 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07001970 ps.findAll(ret, query, cloneFlags);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001971
1972 return new ParceledListSlice<>(ret);
1973 }
1974
1975 @Override
Makoto Onukid6880792016-06-29 13:37:43 -07001976 public int getMaxShortcutCountPerActivity(String packageName, @UserIdInt int userId)
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001977 throws RemoteException {
1978 verifyCaller(packageName, userId);
1979
Makoto Onukib5a012f2016-06-21 11:13:53 -07001980 return mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001981 }
1982
1983 @Override
1984 public int getRemainingCallCount(String packageName, @UserIdInt int userId) {
1985 verifyCaller(packageName, userId);
1986
1987 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001988 throwIfUserLockedL(userId);
1989
Makoto Onukic8c33292016-09-12 16:36:59 -07001990 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07001991 return mMaxUpdatesPerInterval - ps.getApiCallCount();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001992 }
1993 }
1994
1995 @Override
1996 public long getRateLimitResetTime(String packageName, @UserIdInt int userId) {
1997 verifyCaller(packageName, userId);
1998
1999 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002000 throwIfUserLockedL(userId);
2001
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002002 return getNextResetTimeLocked();
2003 }
2004 }
2005
Makoto Onuki55046222016-03-08 10:49:47 -08002006 @Override
Makoto Onuki20c95f82016-05-11 16:51:01 -07002007 public int getIconMaxDimensions(String packageName, int userId) {
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002008 verifyCaller(packageName, userId);
2009
Makoto Onuki55046222016-03-08 10:49:47 -08002010 synchronized (mLock) {
2011 return mMaxIconDimension;
2012 }
2013 }
2014
Makoto Onuki20c95f82016-05-11 16:51:01 -07002015 @Override
2016 public void reportShortcutUsed(String packageName, String shortcutId, int userId) {
2017 verifyCaller(packageName, userId);
2018
Makoto Onukiac042502016-05-20 16:39:42 -07002019 Preconditions.checkNotNull(shortcutId);
2020
2021 if (DEBUG) {
2022 Slog.d(TAG, String.format("reportShortcutUsed: Shortcut %s package %s used on user %d",
2023 shortcutId, packageName, userId));
2024 }
2025
2026 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002027 throwIfUserLockedL(userId);
2028
Makoto Onukic8c33292016-09-12 16:36:59 -07002029 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002030
Makoto Onukiac042502016-05-20 16:39:42 -07002031 if (ps.findShortcutById(shortcutId) == null) {
2032 Log.w(TAG, String.format("reportShortcutUsed: package %s doesn't have shortcut %s",
2033 packageName, shortcutId));
2034 return;
2035 }
2036 }
2037
2038 final long token = injectClearCallingIdentity();
2039 try {
2040 mUsageStatsManagerInternal.reportShortcutUsage(packageName, shortcutId, userId);
2041 } finally {
2042 injectRestoreCallingIdentity(token);
2043 }
Makoto Onuki20c95f82016-05-11 16:51:01 -07002044 }
2045
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002046 /**
Makoto Onukib08790c2016-06-23 14:05:46 -07002047 * Reset all throttling, for developer options and command line. Only system/shell can call
2048 * it.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002049 */
2050 @Override
2051 public void resetThrottling() {
2052 enforceSystemOrShell();
2053
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002054 resetThrottlingInner(getCallingUserId());
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002055 }
2056
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002057 void resetThrottlingInner(@UserIdInt int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002058 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002059 if (!isUserUnlockedL(userId)) {
2060 Log.w(TAG, "User " + userId + " is locked or not running");
2061 return;
2062 }
2063
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002064 getUserShortcutsLocked(userId).resetThrottling();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002065 }
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002066 scheduleSaveUser(userId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002067 Slog.i(TAG, "ShortcutManager: throttling counter reset for user " + userId);
2068 }
2069
2070 void resetAllThrottlingInner() {
2071 synchronized (mLock) {
2072 mRawLastResetTime = injectCurrentTimeMillis();
2073 }
2074 scheduleSaveBaseState();
2075 Slog.i(TAG, "ShortcutManager: throttling counter reset for all users");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002076 }
2077
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002078 @Override
2079 public void onApplicationActive(String packageName, int userId) {
2080 if (DEBUG) {
2081 Slog.d(TAG, "onApplicationActive: package=" + packageName + " userid=" + userId);
2082 }
2083 enforceResetThrottlingPermission();
Makoto Onuki02f338e2016-07-29 09:40:40 -07002084
2085 synchronized (mLock) {
2086 if (!isUserUnlockedL(userId)) {
2087 // This is called by system UI, so no need to throw. Just ignore.
2088 return;
2089 }
2090
2091 getPackageShortcutsLocked(packageName, userId)
2092 .resetRateLimitingForCommandLineNoSaving();
2093 saveUserLocked(userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002094 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002095 }
2096
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002097 // We override this method in unit tests to do a simpler check.
2098 boolean hasShortcutHostPermission(@NonNull String callingPackage, int userId) {
Makoto Onuki10305202016-07-14 18:14:08 -07002099 final long start = injectElapsedRealtime();
2100 try {
2101 return hasShortcutHostPermissionInner(callingPackage, userId);
2102 } finally {
2103 logDurationStat(Stats.LAUNCHER_PERMISSION_CHECK, start);
2104 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002105 }
2106
2107 // This method is extracted so we can directly call this method from unit tests,
2108 // even when hasShortcutPermission() is overridden.
2109 @VisibleForTesting
2110 boolean hasShortcutHostPermissionInner(@NonNull String callingPackage, int userId) {
2111 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002112 throwIfUserLockedL(userId);
2113
Makoto Onuki31459242016-03-22 11:12:18 -07002114 final ShortcutUser user = getUserShortcutsLocked(userId);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002115
Makoto Onuki10305202016-07-14 18:14:08 -07002116 // Always trust the in-memory cache.
2117 final ComponentName cached = user.getCachedLauncher();
2118 if (cached != null) {
2119 if (cached.getPackageName().equals(callingPackage)) {
2120 return true;
2121 }
2122 }
2123 // If the cached one doesn't match, then go ahead
2124
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002125 final List<ResolveInfo> allHomeCandidates = new ArrayList<>();
2126
2127 // Default launcher from package manager.
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07002128 final long startGetHomeActivitiesAsUser = injectElapsedRealtime();
Makoto Onuki10305202016-07-14 18:14:08 -07002129 final ComponentName defaultLauncher = mPackageManagerInternal
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002130 .getHomeActivitiesAsUser(allHomeCandidates, userId);
Makoto Onuki2e210c42016-03-30 08:30:36 -07002131 logDurationStat(Stats.GET_DEFAULT_HOME, startGetHomeActivitiesAsUser);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002132
2133 ComponentName detected;
2134 if (defaultLauncher != null) {
2135 detected = defaultLauncher;
2136 if (DEBUG) {
2137 Slog.v(TAG, "Default launcher from PM: " + detected);
2138 }
2139 } else {
Makoto Onuki10305202016-07-14 18:14:08 -07002140 detected = user.getLastKnownLauncher();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002141
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002142 if (detected != null) {
2143 if (injectIsActivityEnabledAndExported(detected, userId)) {
2144 if (DEBUG) {
2145 Slog.v(TAG, "Cached launcher: " + detected);
2146 }
2147 } else {
2148 Slog.w(TAG, "Cached launcher " + detected + " no longer exists");
2149 detected = null;
Makoto Onuki10305202016-07-14 18:14:08 -07002150 user.clearLauncher();
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002151 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002152 }
2153 }
2154
2155 if (detected == null) {
2156 // If we reach here, that means it's the first check since the user was created,
2157 // and there's already multiple launchers and there's no default set.
2158 // Find the system one with the highest priority.
2159 // (We need to check the priority too because of FallbackHome in Settings.)
2160 // If there's no system launcher yet, then no one can access shortcuts, until
2161 // the user explicitly
2162 final int size = allHomeCandidates.size();
2163
2164 int lastPriority = Integer.MIN_VALUE;
2165 for (int i = 0; i < size; i++) {
2166 final ResolveInfo ri = allHomeCandidates.get(i);
2167 if (!ri.activityInfo.applicationInfo.isSystemApp()) {
2168 continue;
2169 }
2170 if (DEBUG) {
2171 Slog.d(TAG, String.format("hasShortcutPermissionInner: pkg=%s prio=%d",
2172 ri.activityInfo.getComponentName(), ri.priority));
2173 }
2174 if (ri.priority < lastPriority) {
2175 continue;
2176 }
2177 detected = ri.activityInfo.getComponentName();
2178 lastPriority = ri.priority;
2179 }
2180 }
Makoto Onuki2e210c42016-03-30 08:30:36 -07002181
Makoto Onuki10305202016-07-14 18:14:08 -07002182 // Update the cache.
2183 user.setLauncher(detected);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002184 if (detected != null) {
2185 if (DEBUG) {
2186 Slog.v(TAG, "Detected launcher: " + detected);
2187 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002188 return detected.getPackageName().equals(callingPackage);
2189 } else {
2190 // Default launcher not found.
2191 return false;
2192 }
2193 }
2194 }
2195
Makoto Onukicdc78f72016-03-21 15:47:52 -07002196 // === House keeping ===
2197
Makoto Onukib08790c2016-06-23 14:05:46 -07002198 private void cleanUpPackageForAllLoadedUsers(String packageName, @UserIdInt int packageUserId,
2199 boolean appStillExists) {
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002200 synchronized (mLock) {
2201 forEachLoadedUserLocked(user ->
Makoto Onukib08790c2016-06-23 14:05:46 -07002202 cleanUpPackageLocked(packageName, user.getUserId(), packageUserId,
2203 appStillExists));
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002204 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002205 }
2206
Makoto Onuki2e210c42016-03-30 08:30:36 -07002207 /**
2208 * Remove all the information associated with a package. This will really remove all the
2209 * information, including the restore information (i.e. it'll remove packages even if they're
2210 * shadow).
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002211 *
2212 * This is called when an app is uninstalled, or an app gets "clear data"ed.
Makoto Onuki2e210c42016-03-30 08:30:36 -07002213 */
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002214 @VisibleForTesting
Makoto Onukib08790c2016-06-23 14:05:46 -07002215 void cleanUpPackageLocked(String packageName, int owningUserId, int packageUserId,
2216 boolean appStillExists) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002217 final boolean wasUserLoaded = isUserLoadedLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002218
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002219 final ShortcutUser user = getUserShortcutsLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002220 boolean doNotify = false;
2221
2222 // First, remove the package from the package list (if the package is a publisher).
Makoto Onukid99c6f02016-03-28 11:02:54 -07002223 if (packageUserId == owningUserId) {
Makoto Onukic51b2872016-05-04 15:24:50 -07002224 if (user.removePackage(packageName) != null) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002225 doNotify = true;
2226 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07002227 }
Makoto Onukid99c6f02016-03-28 11:02:54 -07002228
Makoto Onukicdc78f72016-03-21 15:47:52 -07002229 // Also remove from the launcher list (if the package is a launcher).
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002230 user.removeLauncher(packageUserId, packageName);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002231
2232 // Then remove pinned shortcuts from all launchers.
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002233 user.forAllLaunchers(l -> l.cleanUpPackage(packageName, packageUserId));
2234
2235 // Now there may be orphan shortcuts because we removed pinned shortcuts at the previous
Makoto Onukicdc78f72016-03-21 15:47:52 -07002236 // step. Remove them too.
Makoto Onukic51b2872016-05-04 15:24:50 -07002237 user.forAllPackages(p -> p.refreshPinnedFlags());
Makoto Onukicdc78f72016-03-21 15:47:52 -07002238
Makoto Onukid99c6f02016-03-28 11:02:54 -07002239 scheduleSaveUser(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002240
2241 if (doNotify) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002242 notifyListeners(packageName, owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002243 }
2244
Makoto Onukib08790c2016-06-23 14:05:46 -07002245 // If the app still exists (i.e. data cleared), we need to re-publish manifest shortcuts.
2246 if (appStillExists && (packageUserId == owningUserId)) {
2247 // This will do the notification and save when needed, so do it after the above
2248 // notifyListeners.
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002249 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07002250 }
2251
Makoto Onukicdc78f72016-03-21 15:47:52 -07002252 if (!wasUserLoaded) {
2253 // Note this will execute the scheduled save.
Makoto Onukid99c6f02016-03-28 11:02:54 -07002254 unloadUserLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002255 }
2256 }
2257
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002258 /**
2259 * Entry point from {@link LauncherApps}.
2260 */
2261 private class LocalService extends ShortcutServiceInternal {
Makoto Onuki2e210c42016-03-30 08:30:36 -07002262
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002263 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002264 public List<ShortcutInfo> getShortcuts(int launcherUserId,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002265 @NonNull String callingPackage, long changedSince,
Makoto Onukiabe84422016-04-07 09:41:19 -07002266 @Nullable String packageName, @Nullable List<String> shortcutIds,
2267 @Nullable ComponentName componentName,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002268 int queryFlags, int userId) {
2269 final ArrayList<ShortcutInfo> ret = new ArrayList<>();
Makoto Onuki9c850012016-07-26 15:50:50 -07002270
Makoto Onuki20c95f82016-05-11 16:51:01 -07002271 final boolean cloneKeyFieldOnly =
2272 ((queryFlags & ShortcutQuery.FLAG_GET_KEY_FIELDS_ONLY) != 0);
2273 final int cloneFlag = cloneKeyFieldOnly ? ShortcutInfo.CLONE_REMOVE_NON_KEY_INFO
2274 : ShortcutInfo.CLONE_REMOVE_FOR_LAUNCHER;
Makoto Onukiabe84422016-04-07 09:41:19 -07002275 if (packageName == null) {
2276 shortcutIds = null; // LauncherAppsService already threw for it though.
2277 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002278
2279 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002280 throwIfUserLockedL(userId);
2281 throwIfUserLockedL(launcherUserId);
2282
Makoto Onuki2e210c42016-03-30 08:30:36 -07002283 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002284 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002285
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002286 if (packageName != null) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002287 getShortcutsInnerLocked(launcherUserId,
Makoto Onukiabe84422016-04-07 09:41:19 -07002288 callingPackage, packageName, shortcutIds, changedSince,
Makoto Onukide667372016-03-15 14:29:20 -07002289 componentName, queryFlags, userId, ret, cloneFlag);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002290 } else {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002291 final List<String> shortcutIdsF = shortcutIds;
2292 getUserShortcutsLocked(userId).forAllPackages(p -> {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002293 getShortcutsInnerLocked(launcherUserId,
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002294 callingPackage, p.getPackageName(), shortcutIdsF, changedSince,
Makoto Onukide667372016-03-15 14:29:20 -07002295 componentName, queryFlags, userId, ret, cloneFlag);
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002296 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002297 }
2298 }
2299 return ret;
2300 }
2301
Makoto Onukid99c6f02016-03-28 11:02:54 -07002302 private void getShortcutsInnerLocked(int launcherUserId, @NonNull String callingPackage,
Makoto Onukiabe84422016-04-07 09:41:19 -07002303 @Nullable String packageName, @Nullable List<String> shortcutIds, long changedSince,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002304 @Nullable ComponentName componentName, int queryFlags,
2305 int userId, ArrayList<ShortcutInfo> ret, int cloneFlag) {
Makoto Onukiabe84422016-04-07 09:41:19 -07002306 final ArraySet<String> ids = shortcutIds == null ? null
2307 : new ArraySet<>(shortcutIds);
2308
Makoto Onukic51b2872016-05-04 15:24:50 -07002309 final ShortcutPackage p = getUserShortcutsLocked(userId)
2310 .getPackageShortcutsIfExists(packageName);
2311 if (p == null) {
2312 return; // No need to instantiate ShortcutPackage.
2313 }
2314
2315 p.findAll(ret,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002316 (ShortcutInfo si) -> {
2317 if (si.getLastChangedTimestamp() < changedSince) {
2318 return false;
2319 }
Makoto Onukiabe84422016-04-07 09:41:19 -07002320 if (ids != null && !ids.contains(si.getId())) {
2321 return false;
2322 }
Makoto Onuki85694522016-05-04 12:53:37 -07002323 if (componentName != null) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002324 if (si.getActivity() != null
2325 && !si.getActivity().equals(componentName)) {
Makoto Onuki85694522016-05-04 12:53:37 -07002326 return false;
2327 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002328 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002329 if (((queryFlags & ShortcutQuery.FLAG_GET_DYNAMIC) != 0)
2330 && si.isDynamic()) {
2331 return true;
2332 }
2333 if (((queryFlags & ShortcutQuery.FLAG_GET_PINNED) != 0)
2334 && si.isPinned()) {
2335 return true;
2336 }
2337 if (((queryFlags & ShortcutQuery.FLAG_GET_MANIFEST) != 0)
2338 && si.isManifestShortcut()) {
2339 return true;
2340 }
2341 return false;
Makoto Onukid99c6f02016-03-28 11:02:54 -07002342 }, cloneFlag, callingPackage, launcherUserId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002343 }
2344
2345 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002346 public boolean isPinnedByCaller(int launcherUserId, @NonNull String callingPackage,
2347 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2348 Preconditions.checkStringNotEmpty(packageName, "packageName");
2349 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
2350
2351 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002352 throwIfUserLockedL(userId);
2353 throwIfUserLockedL(launcherUserId);
2354
Makoto Onuki2e210c42016-03-30 08:30:36 -07002355 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002356 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002357
Makoto Onukid99c6f02016-03-28 11:02:54 -07002358 final ShortcutInfo si = getShortcutInfoLocked(
2359 launcherUserId, callingPackage, packageName, shortcutId, userId);
2360 return si != null && si.isPinned();
2361 }
2362 }
2363
Makoto Onuki2e210c42016-03-30 08:30:36 -07002364 private ShortcutInfo getShortcutInfoLocked(
Makoto Onukid99c6f02016-03-28 11:02:54 -07002365 int launcherUserId, @NonNull String callingPackage,
2366 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2367 Preconditions.checkStringNotEmpty(packageName, "packageName");
2368 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
2369
Makoto Onuki02f338e2016-07-29 09:40:40 -07002370 throwIfUserLockedL(userId);
2371 throwIfUserLockedL(launcherUserId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002372
Makoto Onukic51b2872016-05-04 15:24:50 -07002373 final ShortcutPackage p = getUserShortcutsLocked(userId)
2374 .getPackageShortcutsIfExists(packageName);
2375 if (p == null) {
2376 return null;
2377 }
2378
Makoto Onukid99c6f02016-03-28 11:02:54 -07002379 final ArrayList<ShortcutInfo> list = new ArrayList<>(1);
Makoto Onukic51b2872016-05-04 15:24:50 -07002380 p.findAll(list,
Makoto Onukid99c6f02016-03-28 11:02:54 -07002381 (ShortcutInfo si) -> shortcutId.equals(si.getId()),
2382 /* clone flags=*/ 0, callingPackage, launcherUserId);
2383 return list.size() == 0 ? null : list.get(0);
2384 }
2385
2386 @Override
2387 public void pinShortcuts(int launcherUserId,
2388 @NonNull String callingPackage, @NonNull String packageName,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002389 @NonNull List<String> shortcutIds, int userId) {
2390 // Calling permission must be checked by LauncherAppsImpl.
2391 Preconditions.checkStringNotEmpty(packageName, "packageName");
2392 Preconditions.checkNotNull(shortcutIds, "shortcutIds");
2393
2394 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002395 throwIfUserLockedL(userId);
2396 throwIfUserLockedL(launcherUserId);
2397
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002398 final ShortcutLauncher launcher =
Makoto Onuki2e210c42016-03-30 08:30:36 -07002399 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId);
Makoto Onukic51b2872016-05-04 15:24:50 -07002400 launcher.attemptToRestoreIfNeededAndSave();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002401
Makoto Onukic51b2872016-05-04 15:24:50 -07002402 launcher.pinShortcuts(userId, packageName, shortcutIds);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002403 }
Makoto Onuki39686e82016-04-13 18:03:00 -07002404 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07002405
2406 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002407 }
2408
2409 @Override
Makoto Onuki440a1ea2016-07-20 14:21:18 -07002410 public Intent[] createShortcutIntents(int launcherUserId,
Makoto Onukid99c6f02016-03-28 11:02:54 -07002411 @NonNull String callingPackage,
Makoto Onuki43204b82016-03-08 16:16:44 -08002412 @NonNull String packageName, @NonNull String shortcutId, int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002413 // Calling permission must be checked by LauncherAppsImpl.
Makoto Onuki43204b82016-03-08 16:16:44 -08002414 Preconditions.checkStringNotEmpty(packageName, "packageName can't be empty");
2415 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId can't be empty");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002416
2417 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002418 throwIfUserLockedL(userId);
2419 throwIfUserLockedL(launcherUserId);
2420
Makoto Onuki2e210c42016-03-30 08:30:36 -07002421 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002422 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002423
Makoto Onukid99c6f02016-03-28 11:02:54 -07002424 // Make sure the shortcut is actually visible to the launcher.
2425 final ShortcutInfo si = getShortcutInfoLocked(
2426 launcherUserId, callingPackage, packageName, shortcutId, userId);
2427 // "si == null" should suffice here, but check the flags too just to make sure.
Makoto Onuki22fcc682016-05-17 14:52:19 -07002428 if (si == null || !si.isEnabled() || !si.isAlive()) {
Makoto Onuki83f6d2d2016-07-11 14:30:19 -07002429 Log.e(TAG, "Shortcut " + shortcutId + " does not exist or disabled");
Makoto Onukid99c6f02016-03-28 11:02:54 -07002430 return null;
2431 }
Makoto Onuki440a1ea2016-07-20 14:21:18 -07002432 return si.getIntents();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002433 }
2434 }
2435
2436 @Override
2437 public void addListener(@NonNull ShortcutChangeListener listener) {
2438 synchronized (mLock) {
2439 mListeners.add(Preconditions.checkNotNull(listener));
2440 }
2441 }
Makoto Onuki55046222016-03-08 10:49:47 -08002442
2443 @Override
Makoto Onukiabe84422016-04-07 09:41:19 -07002444 public int getShortcutIconResId(int launcherUserId, @NonNull String callingPackage,
2445 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2446 Preconditions.checkNotNull(callingPackage, "callingPackage");
2447 Preconditions.checkNotNull(packageName, "packageName");
2448 Preconditions.checkNotNull(shortcutId, "shortcutId");
Makoto Onuki55046222016-03-08 10:49:47 -08002449
2450 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002451 throwIfUserLockedL(userId);
2452 throwIfUserLockedL(launcherUserId);
2453
Makoto Onuki2e210c42016-03-30 08:30:36 -07002454 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002455 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002456
Makoto Onukic51b2872016-05-04 15:24:50 -07002457 final ShortcutPackage p = getUserShortcutsLocked(userId)
2458 .getPackageShortcutsIfExists(packageName);
2459 if (p == null) {
2460 return 0;
2461 }
2462
2463 final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId);
Makoto Onuki55046222016-03-08 10:49:47 -08002464 return (shortcutInfo != null && shortcutInfo.hasIconResource())
2465 ? shortcutInfo.getIconResourceId() : 0;
2466 }
2467 }
2468
2469 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002470 public ParcelFileDescriptor getShortcutIconFd(int launcherUserId,
Makoto Onukiabe84422016-04-07 09:41:19 -07002471 @NonNull String callingPackage, @NonNull String packageName,
2472 @NonNull String shortcutId, int userId) {
2473 Preconditions.checkNotNull(callingPackage, "callingPackage");
2474 Preconditions.checkNotNull(packageName, "packageName");
2475 Preconditions.checkNotNull(shortcutId, "shortcutId");
Makoto Onuki55046222016-03-08 10:49:47 -08002476
2477 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002478 throwIfUserLockedL(userId);
2479 throwIfUserLockedL(launcherUserId);
2480
Makoto Onuki2e210c42016-03-30 08:30:36 -07002481 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002482 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002483
Makoto Onukic51b2872016-05-04 15:24:50 -07002484 final ShortcutPackage p = getUserShortcutsLocked(userId)
2485 .getPackageShortcutsIfExists(packageName);
2486 if (p == null) {
2487 return null;
2488 }
2489
2490 final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId);
Makoto Onuki55046222016-03-08 10:49:47 -08002491 if (shortcutInfo == null || !shortcutInfo.hasIconFile()) {
2492 return null;
2493 }
2494 try {
Makoto Onuki34d1c912016-03-10 14:24:58 -08002495 if (shortcutInfo.getBitmapPath() == null) {
2496 Slog.w(TAG, "null bitmap detected in getShortcutIconFd()");
2497 return null;
2498 }
Makoto Onuki55046222016-03-08 10:49:47 -08002499 return ParcelFileDescriptor.open(
2500 new File(shortcutInfo.getBitmapPath()),
2501 ParcelFileDescriptor.MODE_READ_ONLY);
2502 } catch (FileNotFoundException e) {
2503 Slog.e(TAG, "Icon file not found: " + shortcutInfo.getBitmapPath());
2504 return null;
2505 }
2506 }
2507 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002508
2509 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002510 public boolean hasShortcutHostPermission(int launcherUserId,
2511 @NonNull String callingPackage) {
2512 return ShortcutService.this.hasShortcutHostPermission(callingPackage, launcherUserId);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002513 }
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002514 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002515
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002516 final BroadcastReceiver mReceiver = new BroadcastReceiver() {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002517 @Override
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002518 public void onReceive(Context context, Intent intent) {
2519 if (!mBootCompleted.get()) {
2520 return; // Boot not completed, ignore the broadcast.
2521 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07002522 try {
2523 if (Intent.ACTION_LOCALE_CHANGED.equals(intent.getAction())) {
2524 handleLocaleChanged();
2525 }
2526 } catch (Exception e) {
2527 wtf("Exception in mReceiver.onReceive", e);
Makoto Onukic51b2872016-05-04 15:24:50 -07002528 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002529 }
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002530 };
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002531
Makoto Onuki157b1622016-06-02 16:13:10 -07002532 void handleLocaleChanged() {
2533 if (DEBUG) {
2534 Slog.d(TAG, "handleLocaleChanged");
2535 }
2536 scheduleSaveBaseState();
2537
Makoto Onuki02f338e2016-07-29 09:40:40 -07002538 synchronized (mLock) {
2539 final long token = injectClearCallingIdentity();
2540 try {
2541 forEachLoadedUserLocked(user -> user.detectLocaleChange());
2542 } finally {
2543 injectRestoreCallingIdentity(token);
2544 }
Makoto Onuki157b1622016-06-02 16:13:10 -07002545 }
2546 }
2547
Makoto Onukif34c3082016-07-13 10:25:25 -07002548 /**
2549 * Package event callbacks.
2550 */
2551 @VisibleForTesting
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002552 final BroadcastReceiver mPackageMonitor = new BroadcastReceiver() {
Makoto Onukif34c3082016-07-13 10:25:25 -07002553 @Override
2554 public void onReceive(Context context, Intent intent) {
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002555 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
2556 if (userId == UserHandle.USER_NULL) {
2557 Slog.w(TAG, "Intent broadcast does not contain user handle: " + intent);
2558 return;
2559 }
2560
2561 final String action = intent.getAction();
2562
2563 // This is normally called on Handler, so clearCallingIdentity() isn't needed,
2564 // but we still check it in unit tests.
Makoto Onukif34c3082016-07-13 10:25:25 -07002565 final long token = injectClearCallingIdentity();
2566 try {
Makoto Onuki10305202016-07-14 18:14:08 -07002567 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002568 if (!isUserUnlockedL(userId)) {
2569 if (DEBUG) {
2570 Slog.d(TAG, "Ignoring package broadcast " + action
2571 + " for locked/stopped user " + userId);
2572 }
2573 return;
2574 }
2575
2576 // Whenever we get one of those package broadcasts, or get
2577 // ACTION_PREFERRED_ACTIVITY_CHANGED, we purge the default launcher cache.
Makoto Onuki10305202016-07-14 18:14:08 -07002578 final ShortcutUser user = getUserShortcutsLocked(userId);
2579 user.clearLauncher();
2580 }
2581 if (Intent.ACTION_PREFERRED_ACTIVITY_CHANGED.equals(action)) {
2582 // Nothing farther to do.
2583 return;
2584 }
2585
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002586 final Uri intentUri = intent.getData();
2587 final String packageName = (intentUri != null) ? intentUri.getSchemeSpecificPart()
2588 : null;
2589 if (packageName == null) {
2590 Slog.w(TAG, "Intent broadcast does not contain package name: " + intent);
2591 return;
2592 }
2593
2594 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
2595
2596 switch (action) {
2597 case Intent.ACTION_PACKAGE_ADDED:
2598 if (replacing) {
2599 handlePackageUpdateFinished(packageName, userId);
2600 } else {
2601 handlePackageAdded(packageName, userId);
2602 }
2603 break;
2604 case Intent.ACTION_PACKAGE_REMOVED:
2605 if (!replacing) {
2606 handlePackageRemoved(packageName, userId);
2607 }
2608 break;
2609 case Intent.ACTION_PACKAGE_CHANGED:
2610 handlePackageChanged(packageName, userId);
2611
2612 break;
2613 case Intent.ACTION_PACKAGE_DATA_CLEARED:
2614 handlePackageDataCleared(packageName, userId);
2615 break;
2616 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07002617 } catch (Exception e) {
2618 wtf("Exception in mPackageMonitor.onReceive", e);
Makoto Onukif34c3082016-07-13 10:25:25 -07002619 } finally {
2620 injectRestoreCallingIdentity(token);
Makoto Onukia2241832016-07-06 13:28:37 -07002621 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07002622 }
Makoto Onukif34c3082016-07-13 10:25:25 -07002623 };
Makoto Onukicdc78f72016-03-21 15:47:52 -07002624
Makoto Onuki0acbb142016-03-22 17:02:57 -07002625 /**
Makoto Onuki39686e82016-04-13 18:03:00 -07002626 * Called when a user is unlocked.
2627 * - Check all known packages still exist, and otherwise perform cleanup.
2628 * - If a package still exists, check the version code. If it's been updated, may need to
Makoto Onukib08790c2016-06-23 14:05:46 -07002629 * update timestamps of its shortcuts.
Makoto Onuki0acbb142016-03-22 17:02:57 -07002630 */
Makoto Onukid99c6f02016-03-28 11:02:54 -07002631 @VisibleForTesting
Makoto Onuki39686e82016-04-13 18:03:00 -07002632 void checkPackageChanges(@UserIdInt int ownerUserId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07002633 if (DEBUG) {
Makoto Onuki39686e82016-04-13 18:03:00 -07002634 Slog.d(TAG, "checkPackageChanges() ownerUserId=" + ownerUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002635 }
Makoto Onukib08790c2016-06-23 14:05:46 -07002636 if (injectIsSafeModeEnabled()) {
2637 Slog.i(TAG, "Safe mode, skipping checkPackageChanges()");
2638 return;
2639 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07002640
Makoto Onuki22fcc682016-05-17 14:52:19 -07002641 final long start = injectElapsedRealtime();
2642 try {
2643 final ArrayList<PackageWithUser> gonePackages = new ArrayList<>();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002644
Makoto Onuki22fcc682016-05-17 14:52:19 -07002645 synchronized (mLock) {
2646 final ShortcutUser user = getUserShortcutsLocked(ownerUserId);
2647
2648 // Find packages that have been uninstalled.
2649 user.forAllPackageItems(spi -> {
2650 if (spi.getPackageInfo().isShadow()) {
2651 return; // Don't delete shadow information.
2652 }
2653 if (!isPackageInstalled(spi.getPackageName(), spi.getPackageUserId())) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002654 if (DEBUG) {
2655 Slog.d(TAG, "Uninstalled: " + spi.getPackageName()
2656 + " user " + spi.getPackageUserId());
2657 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002658 gonePackages.add(PackageWithUser.of(spi));
2659 }
2660 });
2661 if (gonePackages.size() > 0) {
2662 for (int i = gonePackages.size() - 1; i >= 0; i--) {
2663 final PackageWithUser pu = gonePackages.get(i);
Makoto Onukib08790c2016-06-23 14:05:46 -07002664 cleanUpPackageLocked(pu.packageName, ownerUserId, pu.userId,
2665 /* appStillExists = */ false);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002666 }
Makoto Onukid99c6f02016-03-28 11:02:54 -07002667 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002668
Makoto Onuki248a0ef2016-11-03 15:59:01 -07002669 rescanUpdatedPackagesLocked(ownerUserId, user.getLastAppScanTime());
Makoto Onuki0acbb142016-03-22 17:02:57 -07002670 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002671 } finally {
2672 logDurationStat(Stats.CHECK_PACKAGE_CHANGES, start);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002673 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002674 verifyStates();
Makoto Onukicdc78f72016-03-21 15:47:52 -07002675 }
2676
Makoto Onuki248a0ef2016-11-03 15:59:01 -07002677 private void rescanUpdatedPackagesLocked(@UserIdInt int userId, long lastScanTime) {
Makoto Onuki377b7972016-08-09 14:43:55 -07002678 final ShortcutUser user = getUserShortcutsLocked(userId);
2679
Makoto Onuki33663282016-08-22 16:19:04 -07002680 // Note after each OTA, we'll need to rescan all system apps, as their lastUpdateTime
2681 // is not reliable.
Makoto Onuki377b7972016-08-09 14:43:55 -07002682 final long now = injectCurrentTimeMillis();
Makoto Onuki33663282016-08-22 16:19:04 -07002683 final boolean afterOta =
2684 !injectBuildFingerprint().equals(user.getLastAppScanOsFingerprint());
Makoto Onuki377b7972016-08-09 14:43:55 -07002685
2686 // Then for each installed app, publish manifest shortcuts when needed.
Makoto Onuki33663282016-08-22 16:19:04 -07002687 forUpdatedPackages(userId, lastScanTime, afterOta, ai -> {
Makoto Onuki377b7972016-08-09 14:43:55 -07002688 user.attemptToRestoreIfNeededAndSave(this, ai.packageName, userId);
Makoto Onuki248a0ef2016-11-03 15:59:01 -07002689
2690 user.rescanPackageIfNeeded(ai.packageName, /* forceRescan= */ true);
Makoto Onuki377b7972016-08-09 14:43:55 -07002691 });
2692
2693 // Write the time just before the scan, because there may be apps that have just
2694 // been updated, and we want to catch them in the next time.
2695 user.setLastAppScanTime(now);
Makoto Onuki33663282016-08-22 16:19:04 -07002696 user.setLastAppScanOsFingerprint(injectBuildFingerprint());
Makoto Onuki377b7972016-08-09 14:43:55 -07002697 scheduleSaveUser(userId);
2698 }
2699
Makoto Onuki0acbb142016-03-22 17:02:57 -07002700 private void handlePackageAdded(String packageName, @UserIdInt int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07002701 if (DEBUG) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07002702 Slog.d(TAG, String.format("handlePackageAdded: %s user=%d", packageName, userId));
2703 }
2704 synchronized (mLock) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002705 final ShortcutUser user = getUserShortcutsLocked(userId);
2706 user.attemptToRestoreIfNeededAndSave(this, packageName, userId);
Makoto Onuki64183d52016-08-08 14:11:34 -07002707 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002708 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002709 verifyStates();
Makoto Onuki0acbb142016-03-22 17:02:57 -07002710 }
2711
2712 private void handlePackageUpdateFinished(String packageName, @UserIdInt int userId) {
Makoto Onuki905e8852016-03-28 10:40:58 -07002713 if (DEBUG) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002714 Slog.d(TAG, String.format("handlePackageUpdateFinished: %s user=%d",
2715 packageName, userId));
Makoto Onuki0acbb142016-03-22 17:02:57 -07002716 }
2717 synchronized (mLock) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002718 final ShortcutUser user = getUserShortcutsLocked(userId);
2719 user.attemptToRestoreIfNeededAndSave(this, packageName, userId);
Makoto Onuki39686e82016-04-13 18:03:00 -07002720
Makoto Onuki22fcc682016-05-17 14:52:19 -07002721 if (isPackageInstalled(packageName, userId)) {
Makoto Onuki64183d52016-08-08 14:11:34 -07002722 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onuki39686e82016-04-13 18:03:00 -07002723 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07002724 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002725 verifyStates();
Makoto Onuki0acbb142016-03-22 17:02:57 -07002726 }
2727
Makoto Onuki2e210c42016-03-30 08:30:36 -07002728 private void handlePackageRemoved(String packageName, @UserIdInt int packageUserId) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07002729 if (DEBUG) {
Makoto Onuki2e210c42016-03-30 08:30:36 -07002730 Slog.d(TAG, String.format("handlePackageRemoved: %s user=%d", packageName,
2731 packageUserId));
Makoto Onukicdc78f72016-03-21 15:47:52 -07002732 }
Makoto Onukib08790c2016-06-23 14:05:46 -07002733 cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ false);
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002734
2735 verifyStates();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002736 }
2737
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002738 private void handlePackageDataCleared(String packageName, int packageUserId) {
2739 if (DEBUG) {
2740 Slog.d(TAG, String.format("handlePackageDataCleared: %s user=%d", packageName,
2741 packageUserId));
Makoto Onukicdc78f72016-03-21 15:47:52 -07002742 }
Makoto Onukib08790c2016-06-23 14:05:46 -07002743 cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ true);
2744
2745 verifyStates();
2746 }
2747
2748 private void handlePackageChanged(String packageName, int packageUserId) {
2749 if (DEBUG) {
2750 Slog.d(TAG, String.format("handlePackageChanged: %s user=%d", packageName,
2751 packageUserId));
2752 }
2753
2754 // Activities may be disabled or enabled. Just rescan the package.
2755 synchronized (mLock) {
2756 final ShortcutUser user = getUserShortcutsLocked(packageUserId);
2757
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002758 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07002759 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002760
2761 verifyStates();
Makoto Onukicdc78f72016-03-21 15:47:52 -07002762 }
2763
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002764 // === PackageManager interaction ===
Makoto Onuki0acbb142016-03-22 17:02:57 -07002765
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002766 /**
2767 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
2768 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002769 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002770 final PackageInfo getPackageInfoWithSignatures(String packageName, @UserIdInt int userId) {
2771 return getPackageInfo(packageName, userId, true);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002772 }
2773
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002774 /**
2775 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
2776 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002777 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002778 final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId) {
2779 return getPackageInfo(packageName, userId, false);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002780 }
2781
Makoto Onuki905e8852016-03-28 10:40:58 -07002782 int injectGetPackageUid(@NonNull String packageName, @UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002783 final long token = injectClearCallingIdentity();
Makoto Onuki905e8852016-03-28 10:40:58 -07002784 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002785 return mIPackageManager.getPackageUid(packageName, PACKAGE_MATCH_FLAGS, userId);
Makoto Onuki905e8852016-03-28 10:40:58 -07002786 } catch (RemoteException e) {
2787 // Shouldn't happen.
2788 Slog.wtf(TAG, "RemoteException", e);
2789 return -1;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002790 } finally {
2791 injectRestoreCallingIdentity(token);
Makoto Onuki905e8852016-03-28 10:40:58 -07002792 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07002793 }
2794
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002795 /**
2796 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
2797 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002798 @Nullable
Makoto Onuki0acbb142016-03-22 17:02:57 -07002799 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002800 final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId,
2801 boolean getSignatures) {
2802 return isInstalledOrNull(injectPackageInfoWithUninstalled(
2803 packageName, userId, getSignatures));
2804 }
2805
2806 /**
2807 * Do not use directly; this returns uninstalled packages too.
2808 */
2809 @Nullable
2810 @VisibleForTesting
2811 PackageInfo injectPackageInfoWithUninstalled(String packageName, @UserIdInt int userId,
Makoto Onuki0acbb142016-03-22 17:02:57 -07002812 boolean getSignatures) {
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07002813 final long start = injectElapsedRealtime();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002814 final long token = injectClearCallingIdentity();
Makoto Onuki0acbb142016-03-22 17:02:57 -07002815 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002816 return mIPackageManager.getPackageInfo(
2817 packageName, PACKAGE_MATCH_FLAGS
2818 | (getSignatures ? PackageManager.GET_SIGNATURES : 0), userId);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002819 } catch (RemoteException e) {
2820 // Shouldn't happen.
2821 Slog.wtf(TAG, "RemoteException", e);
2822 return null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002823 } finally {
2824 injectRestoreCallingIdentity(token);
Makoto Onuki2e210c42016-03-30 08:30:36 -07002825
2826 logDurationStat(
2827 (getSignatures ? Stats.GET_PACKAGE_INFO_WITH_SIG : Stats.GET_PACKAGE_INFO),
2828 start);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002829 }
2830 }
2831
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002832 /**
2833 * Returns {@link ApplicationInfo} unless it's uninstalled or disabled.
2834 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002835 @Nullable
Makoto Onuki905e8852016-03-28 10:40:58 -07002836 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002837 final ApplicationInfo getApplicationInfo(String packageName, @UserIdInt int userId) {
2838 return isInstalledOrNull(injectApplicationInfoWithUninstalled(packageName, userId));
2839 }
2840
2841 /**
2842 * Do not use directly; this returns uninstalled packages too.
2843 */
2844 @Nullable
2845 @VisibleForTesting
2846 ApplicationInfo injectApplicationInfoWithUninstalled(
2847 String packageName, @UserIdInt int userId) {
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07002848 final long start = injectElapsedRealtime();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002849 final long token = injectClearCallingIdentity();
Makoto Onuki905e8852016-03-28 10:40:58 -07002850 try {
2851 return mIPackageManager.getApplicationInfo(packageName, PACKAGE_MATCH_FLAGS, userId);
2852 } catch (RemoteException e) {
2853 // Shouldn't happen.
2854 Slog.wtf(TAG, "RemoteException", e);
2855 return null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002856 } finally {
2857 injectRestoreCallingIdentity(token);
Makoto Onuki2e210c42016-03-30 08:30:36 -07002858
2859 logDurationStat(Stats.GET_APPLICATION_INFO, start);
Makoto Onuki905e8852016-03-28 10:40:58 -07002860 }
2861 }
2862
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002863 /**
2864 * Returns {@link ActivityInfo} with its metadata unless it's uninstalled or disabled.
2865 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002866 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002867 final ActivityInfo getActivityInfoWithMetadata(ComponentName activity, @UserIdInt int userId) {
2868 return isInstalledOrNull(injectGetActivityInfoWithMetadataWithUninstalled(
2869 activity, userId));
2870 }
2871
2872 /**
2873 * Do not use directly; this returns uninstalled packages too.
2874 */
2875 @Nullable
2876 @VisibleForTesting
2877 ActivityInfo injectGetActivityInfoWithMetadataWithUninstalled(
2878 ComponentName activity, @UserIdInt int userId) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002879 final long start = injectElapsedRealtime();
2880 final long token = injectClearCallingIdentity();
2881 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07002882 return mIPackageManager.getActivityInfo(activity,
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002883 (PACKAGE_MATCH_FLAGS | PackageManager.GET_META_DATA), userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002884 } catch (RemoteException e) {
2885 // Shouldn't happen.
2886 Slog.wtf(TAG, "RemoteException", e);
2887 return null;
2888 } finally {
2889 injectRestoreCallingIdentity(token);
2890
Makoto Onukib08790c2016-06-23 14:05:46 -07002891 logDurationStat(Stats.GET_ACTIVITY_WITH_METADATA, start);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002892 }
2893 }
2894
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002895 /**
2896 * Return all installed and enabled packages.
2897 */
2898 @NonNull
Makoto Onuki22fcc682016-05-17 14:52:19 -07002899 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002900 final List<PackageInfo> getInstalledPackages(@UserIdInt int userId) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002901 final long start = injectElapsedRealtime();
2902 final long token = injectClearCallingIdentity();
2903 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002904 final List<PackageInfo> all = injectGetPackagesWithUninstalled(userId);
2905
2906 all.removeIf(PACKAGE_NOT_INSTALLED);
2907
2908 return all;
Makoto Onuki22fcc682016-05-17 14:52:19 -07002909 } catch (RemoteException e) {
2910 // Shouldn't happen.
2911 Slog.wtf(TAG, "RemoteException", e);
2912 return null;
2913 } finally {
2914 injectRestoreCallingIdentity(token);
2915
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07002916 logDurationStat(Stats.GET_INSTALLED_PACKAGES, start);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002917 }
2918 }
2919
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002920 /**
2921 * Do not use directly; this returns uninstalled packages too.
2922 */
2923 @NonNull
2924 @VisibleForTesting
2925 List<PackageInfo> injectGetPackagesWithUninstalled(@UserIdInt int userId)
2926 throws RemoteException {
2927 final ParceledListSlice<PackageInfo> parceledList =
2928 mIPackageManager.getInstalledPackages(PACKAGE_MATCH_FLAGS, userId);
2929 if (parceledList == null) {
2930 return Collections.emptyList();
2931 }
2932 return parceledList.getList();
2933 }
2934
Makoto Onuki33663282016-08-22 16:19:04 -07002935 private void forUpdatedPackages(@UserIdInt int userId, long lastScanTime, boolean afterOta,
Makoto Onuki22fcc682016-05-17 14:52:19 -07002936 Consumer<ApplicationInfo> callback) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07002937 if (DEBUG) {
Makoto Onuki248a0ef2016-11-03 15:59:01 -07002938 Slog.d(TAG, "forUpdatedPackages for user " + userId + ", lastScanTime=" + lastScanTime
2939 + " afterOta=" + afterOta);
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07002940 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002941 final List<PackageInfo> list = getInstalledPackages(userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002942 for (int i = list.size() - 1; i >= 0; i--) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07002943 final PackageInfo pi = list.get(i);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002944
Makoto Onuki64183d52016-08-08 14:11:34 -07002945 // If the package has been updated since the last scan time, then scan it.
Makoto Onuki248a0ef2016-11-03 15:59:01 -07002946 // Also if it's right after an OTA, always re-scan all apps anyway, since the
2947 // shortcut parser might have changed.
2948 if (afterOta || (pi.lastUpdateTime >= lastScanTime)) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07002949 if (DEBUG) {
Makoto Onuki248a0ef2016-11-03 15:59:01 -07002950 Slog.d(TAG, "Found updated package " + pi.packageName
2951 + " updateTime=" + pi.lastUpdateTime);
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07002952 }
2953 callback.accept(pi.applicationInfo);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002954 }
2955 }
2956 }
2957
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002958 private boolean isApplicationFlagSet(@NonNull String packageName, int userId, int flags) {
2959 final ApplicationInfo ai = injectApplicationInfoWithUninstalled(packageName, userId);
Makoto Onuki905e8852016-03-28 10:40:58 -07002960 return (ai != null) && ((ai.flags & flags) == flags);
2961 }
2962
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002963 private static boolean isInstalled(@Nullable ApplicationInfo ai) {
2964 return (ai != null) && (ai.flags & ApplicationInfo.FLAG_INSTALLED) != 0;
2965 }
2966
2967 private static boolean isInstalled(@Nullable PackageInfo pi) {
2968 return (pi != null) && isInstalled(pi.applicationInfo);
2969 }
2970
2971 private static boolean isInstalled(@Nullable ActivityInfo ai) {
2972 return (ai != null) && isInstalled(ai.applicationInfo);
2973 }
2974
2975 private static ApplicationInfo isInstalledOrNull(ApplicationInfo ai) {
2976 return isInstalled(ai) ? ai : null;
2977 }
2978
2979 private static PackageInfo isInstalledOrNull(PackageInfo pi) {
2980 return isInstalled(pi) ? pi : null;
2981 }
2982
2983 private static ActivityInfo isInstalledOrNull(ActivityInfo ai) {
2984 return isInstalled(ai) ? ai : null;
2985 }
2986
Makoto Onuki2e210c42016-03-30 08:30:36 -07002987 boolean isPackageInstalled(String packageName, int userId) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002988 return getApplicationInfo(packageName, userId) != null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002989 }
2990
Makoto Onuki22fcc682016-05-17 14:52:19 -07002991 @Nullable
2992 XmlResourceParser injectXmlMetaData(ActivityInfo activityInfo, String key) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002993 return activityInfo.loadXmlMetaData(mContext.getPackageManager(), key);
Makoto Onuki39686e82016-04-13 18:03:00 -07002994 }
2995
Makoto Onuki157b1622016-06-02 16:13:10 -07002996 @Nullable
2997 Resources injectGetResourcesForApplicationAsUser(String packageName, int userId) {
2998 final long start = injectElapsedRealtime();
2999 final long token = injectClearCallingIdentity();
3000 try {
3001 return mContext.getPackageManager().getResourcesForApplicationAsUser(
3002 packageName, userId);
3003 } catch (NameNotFoundException e) {
3004 Slog.e(TAG, "Resources for package " + packageName + " not found");
3005 return null;
3006 } finally {
3007 injectRestoreCallingIdentity(token);
3008
3009 logDurationStat(Stats.GET_APPLICATION_RESOURCES, start);
3010 }
3011 }
3012
Makoto Onukib08790c2016-06-23 14:05:46 -07003013 private Intent getMainActivityIntent() {
3014 final Intent intent = new Intent(Intent.ACTION_MAIN);
3015 intent.addCategory(LAUNCHER_INTENT_CATEGORY);
3016 return intent;
3017 }
3018
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003019 /**
3020 * Same as queryIntentActivitiesAsUser, except it makes sure the package is installed,
3021 * and only returns exported activities.
3022 */
3023 @NonNull
3024 @VisibleForTesting
3025 List<ResolveInfo> queryActivities(@NonNull Intent baseIntent,
3026 @NonNull String packageName, @Nullable ComponentName activity, int userId) {
3027
3028 baseIntent.setPackage(Preconditions.checkNotNull(packageName));
3029 if (activity != null) {
3030 baseIntent.setComponent(activity);
3031 }
3032
3033 final List<ResolveInfo> resolved =
3034 mContext.getPackageManager().queryIntentActivitiesAsUser(
3035 baseIntent, PACKAGE_MATCH_FLAGS, userId);
3036 if (resolved == null || resolved.size() == 0) {
3037 return EMPTY_RESOLVE_INFO;
3038 }
3039 // Make sure the package is installed.
3040 if (!isInstalled(resolved.get(0).activityInfo)) {
3041 return EMPTY_RESOLVE_INFO;
3042 }
3043 resolved.removeIf(ACTIVITY_NOT_EXPORTED);
3044 return resolved;
3045 }
3046
3047 /**
3048 * Return the main activity that is enabled and exported. If multiple activities are found,
3049 * return the first one.
3050 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003051 @Nullable
3052 ComponentName injectGetDefaultMainActivity(@NonNull String packageName, int userId) {
3053 final long start = injectElapsedRealtime();
3054 final long token = injectClearCallingIdentity();
3055 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07003056 final List<ResolveInfo> resolved =
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003057 queryActivities(getMainActivityIntent(), packageName, null, userId);
3058 return resolved.size() == 0 ? null : resolved.get(0).activityInfo.getComponentName();
Makoto Onukib08790c2016-06-23 14:05:46 -07003059 } finally {
3060 injectRestoreCallingIdentity(token);
3061
3062 logDurationStat(Stats.GET_LAUNCHER_ACTIVITY, start);
3063 }
3064 }
3065
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003066 /**
3067 * Return whether an activity is enabled, exported and main.
3068 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003069 boolean injectIsMainActivity(@NonNull ComponentName activity, int userId) {
3070 final long start = injectElapsedRealtime();
3071 final long token = injectClearCallingIdentity();
3072 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07003073 final List<ResolveInfo> resolved =
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003074 queryActivities(getMainActivityIntent(), activity.getPackageName(),
3075 activity, userId);
3076 return resolved.size() > 0;
Makoto Onukib08790c2016-06-23 14:05:46 -07003077 } finally {
3078 injectRestoreCallingIdentity(token);
3079
3080 logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start);
3081 }
3082 }
3083
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003084 /**
3085 * Return all the enabled, exported and main activities from a package.
3086 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003087 @NonNull
3088 List<ResolveInfo> injectGetMainActivities(@NonNull String packageName, int userId) {
3089 final long start = injectElapsedRealtime();
3090 final long token = injectClearCallingIdentity();
3091 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003092 return queryActivities(getMainActivityIntent(), packageName, null, userId);
Makoto Onukib08790c2016-06-23 14:05:46 -07003093 } finally {
3094 injectRestoreCallingIdentity(token);
3095
3096 logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start);
3097 }
3098 }
3099
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003100 /**
3101 * Return whether an activity is enabled and exported.
3102 */
3103 @VisibleForTesting
3104 boolean injectIsActivityEnabledAndExported(
3105 @NonNull ComponentName activity, @UserIdInt int userId) {
3106 final long start = injectElapsedRealtime();
3107 final long token = injectClearCallingIdentity();
3108 try {
3109 return queryActivities(new Intent(), activity.getPackageName(), activity, userId)
3110 .size() > 0;
3111 } finally {
3112 injectRestoreCallingIdentity(token);
3113
3114 logDurationStat(Stats.IS_ACTIVITY_ENABLED, start);
3115 }
3116 }
3117
Makoto Onukib08790c2016-06-23 14:05:46 -07003118 boolean injectIsSafeModeEnabled() {
3119 final long token = injectClearCallingIdentity();
3120 try {
3121 return IWindowManager.Stub
3122 .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE))
3123 .isSafeModeEnabled();
3124 } catch (RemoteException e) {
3125 return false; // Shouldn't happen though.
3126 } finally {
3127 injectRestoreCallingIdentity(token);
3128 }
3129 }
3130
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003131 // === Backup & restore ===
3132
Makoto Onuki0acbb142016-03-22 17:02:57 -07003133 boolean shouldBackupApp(String packageName, int userId) {
Makoto Onuki905e8852016-03-28 10:40:58 -07003134 return isApplicationFlagSet(packageName, userId, ApplicationInfo.FLAG_ALLOW_BACKUP);
Makoto Onuki0acbb142016-03-22 17:02:57 -07003135 }
3136
Makoto Onuki2e210c42016-03-30 08:30:36 -07003137 boolean shouldBackupApp(PackageInfo pi) {
3138 return (pi.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0;
3139 }
3140
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003141 @Override
Makoto Onuki2e210c42016-03-30 08:30:36 -07003142 public byte[] getBackupPayload(@UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003143 enforceSystem();
3144 if (DEBUG) {
3145 Slog.d(TAG, "Backing up user " + userId);
3146 }
3147 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003148 if (!isUserUnlockedL(userId)) {
3149 wtf("Can't backup: user " + userId + " is locked or not running");
3150 return null;
3151 }
3152
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003153 final ShortcutUser user = getUserShortcutsLocked(userId);
3154 if (user == null) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003155 wtf("Can't backup: user not found: id=" + userId);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003156 return null;
3157 }
3158
Makoto Onukic8c33292016-09-12 16:36:59 -07003159 // Update the signatures for all packages.
3160 user.forAllPackageItems(spi -> spi.refreshPackageSignatureAndSave());
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003161
Makoto Onukic8c33292016-09-12 16:36:59 -07003162 // Set the version code for the launchers.
3163 // We shouldn't do this for publisher packages, because we don't want to update the
3164 // version code without rescanning the manifest.
3165 user.forAllLaunchers(launcher -> launcher.ensureVersionInfo());
3166
3167 // Save to the filesystem.
3168 scheduleSaveUser(userId);
3169 saveDirtyInfo();
3170
3171 // Then create the backup payload.
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003172 final ByteArrayOutputStream os = new ByteArrayOutputStream(32 * 1024);
3173 try {
3174 saveUserInternalLocked(userId, os, /* forBackup */ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07003175 } catch (XmlPullParserException | IOException e) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003176 // Shouldn't happen.
3177 Slog.w(TAG, "Backup failed.", e);
3178 return null;
3179 }
3180 return os.toByteArray();
3181 }
3182 }
3183
3184 @Override
Makoto Onuki2e210c42016-03-30 08:30:36 -07003185 public void applyRestore(byte[] payload, @UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003186 enforceSystem();
3187 if (DEBUG) {
3188 Slog.d(TAG, "Restoring user " + userId);
3189 }
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003190 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003191 if (!isUserUnlockedL(userId)) {
3192 wtf("Can't restore: user " + userId + " is locked or not running");
3193 return;
3194 }
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003195 // Actually do restore.
3196 final ShortcutUser restored;
Makoto Onuki02f338e2016-07-29 09:40:40 -07003197 final ByteArrayInputStream is = new ByteArrayInputStream(payload);
3198 try {
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003199 restored = loadUserInternal(userId, is, /* fromBackup */ true);
3200 } catch (XmlPullParserException | IOException | InvalidFileFormatException e) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003201 Slog.w(TAG, "Restoration failed.", e);
3202 return;
3203 }
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003204 getUserShortcutsLocked(userId).mergeRestoredFile(restored);
Makoto Onuki2e210c42016-03-30 08:30:36 -07003205
Makoto Onuki377b7972016-08-09 14:43:55 -07003206 // Rescan all packages to re-publish manifest shortcuts and do other checks.
3207 rescanUpdatedPackagesLocked(userId,
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003208 0 // lastScanTime = 0; rescan all packages.
3209 );
Makoto Onuki2e210c42016-03-30 08:30:36 -07003210
3211 saveUserLocked(userId);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003212 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07003213 }
3214
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003215 // === Dump ===
3216
3217 @Override
3218 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Makoto Onuki76269922016-07-15 14:58:54 -07003219 enforceCallingOrSelfPermission(android.Manifest.permission.DUMP,
3220 "can't dump by this caller");
3221 boolean checkin = false;
3222 boolean clear = false;
3223 if (args != null) {
3224 for (String arg : args) {
3225 if ("-c".equals(arg)) {
3226 checkin = true;
3227 } else if ("--checkin".equals(arg)) {
3228 checkin = true;
3229 clear = true;
3230 }
3231 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003232 }
Makoto Onuki76269922016-07-15 14:58:54 -07003233
3234 if (checkin) {
3235 dumpCheckin(pw, clear);
3236 } else {
3237 dumpInner(pw);
3238 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003239 }
3240
Makoto Onuki76269922016-07-15 14:58:54 -07003241 private void dumpInner(PrintWriter pw) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003242 synchronized (mLock) {
3243 final long now = injectCurrentTimeMillis();
3244 pw.print("Now: [");
3245 pw.print(now);
3246 pw.print("] ");
3247 pw.print(formatTime(now));
Makoto Onuki55046222016-03-08 10:49:47 -08003248
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003249 pw.print(" Raw last reset: [");
3250 pw.print(mRawLastResetTime);
3251 pw.print("] ");
3252 pw.print(formatTime(mRawLastResetTime));
3253
3254 final long last = getLastResetTimeLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003255 pw.print(" Last reset: [");
3256 pw.print(last);
3257 pw.print("] ");
3258 pw.print(formatTime(last));
3259
Makoto Onuki55046222016-03-08 10:49:47 -08003260 final long next = getNextResetTimeLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003261 pw.print(" Next reset: [");
3262 pw.print(next);
3263 pw.print("] ");
3264 pw.print(formatTime(next));
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003265
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003266 pw.print(" Config:");
3267 pw.print(" Max icon dim: ");
3268 pw.println(mMaxIconDimension);
3269 pw.print(" Icon format: ");
3270 pw.println(mIconPersistFormat);
3271 pw.print(" Icon quality: ");
Makoto Onuki2e210c42016-03-30 08:30:36 -07003272 pw.println(mIconPersistQuality);
Makoto Onuki0033b2a2016-04-14 17:19:16 -07003273 pw.print(" saveDelayMillis: ");
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003274 pw.println(mSaveDelayMillis);
Makoto Onuki0033b2a2016-04-14 17:19:16 -07003275 pw.print(" resetInterval: ");
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003276 pw.println(mResetInterval);
Makoto Onuki0033b2a2016-04-14 17:19:16 -07003277 pw.print(" maxUpdatesPerInterval: ");
Makoto Onukib6d35232016-04-04 15:57:17 -07003278 pw.println(mMaxUpdatesPerInterval);
Makoto Onukib08790c2016-06-23 14:05:46 -07003279 pw.print(" maxShortcutsPerActivity: ");
Makoto Onukib5a012f2016-06-21 11:13:53 -07003280 pw.println(mMaxShortcuts);
Makoto Onuki55046222016-03-08 10:49:47 -08003281 pw.println();
3282
Makoto Onuki2e210c42016-03-30 08:30:36 -07003283 pw.println(" Stats:");
3284 synchronized (mStatLock) {
Makoto Onuki085a05c2016-08-19 11:39:29 -07003285 for (int i = 0; i < Stats.COUNT; i++) {
3286 dumpStatLS(pw, " ", i);
3287 }
Makoto Onuki2e210c42016-03-30 08:30:36 -07003288 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003289
Makoto Onukia2241832016-07-06 13:28:37 -07003290 pw.println();
3291 pw.print(" #Failures: ");
3292 pw.println(mWtfCount);
3293
3294 if (mLastWtfStacktrace != null) {
3295 pw.print(" Last failure stack trace: ");
3296 pw.println(Log.getStackTraceString(mLastWtfStacktrace));
3297 }
3298
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08003299 for (int i = 0; i < mUsers.size(); i++) {
3300 pw.println();
Makoto Onukic51b2872016-05-04 15:24:50 -07003301 mUsers.valueAt(i).dump(pw, " ");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003302 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003303
3304 pw.println();
3305 pw.println(" UID state:");
3306
3307 for (int i = 0; i < mUidState.size(); i++) {
3308 final int uid = mUidState.keyAt(i);
3309 final int state = mUidState.valueAt(i);
3310 pw.print(" UID=");
3311 pw.print(uid);
3312 pw.print(" state=");
3313 pw.print(state);
3314 if (isProcessStateForeground(state)) {
3315 pw.print(" [FG]");
3316 }
3317 pw.print(" last FG=");
3318 pw.print(mUidLastForegroundElapsedTime.get(uid));
3319 pw.println();
3320 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003321 }
3322 }
3323
Makoto Onuki41066a62016-03-09 16:18:44 -08003324 static String formatTime(long time) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003325 Time tobj = new Time();
3326 tobj.set(time);
3327 return tobj.format("%Y-%m-%d %H:%M:%S");
3328 }
3329
Makoto Onuki085a05c2016-08-19 11:39:29 -07003330 private void dumpStatLS(PrintWriter pw, String prefix, int statId) {
Makoto Onuki2e210c42016-03-30 08:30:36 -07003331 pw.print(prefix);
3332 final int count = mCountStats[statId];
3333 final long dur = mDurationStats[statId];
3334 pw.println(String.format("%s: count=%d, total=%dms, avg=%.1fms",
Makoto Onuki085a05c2016-08-19 11:39:29 -07003335 STAT_LABELS[statId], count, dur,
Makoto Onuki2e210c42016-03-30 08:30:36 -07003336 (count == 0 ? 0 : ((double) dur) / count)));
3337 }
3338
Makoto Onuki76269922016-07-15 14:58:54 -07003339 /**
3340 * Dumpsys for checkin.
3341 *
3342 * @param clear if true, clear the history information. Some other system services have this
3343 * behavior but shortcut service doesn't for now.
3344 */
3345 private void dumpCheckin(PrintWriter pw, boolean clear) {
3346 synchronized (mLock) {
3347 try {
3348 final JSONArray users = new JSONArray();
3349
3350 for (int i = 0; i < mUsers.size(); i++) {
3351 users.put(mUsers.valueAt(i).dumpCheckin(clear));
3352 }
3353
3354 final JSONObject result = new JSONObject();
3355
3356 result.put(KEY_SHORTCUT, users);
3357 result.put(KEY_LOW_RAM, injectIsLowRamDevice());
3358 result.put(KEY_ICON_SIZE, mMaxIconDimension);
3359
3360 pw.println(result.toString(1));
3361 } catch (JSONException e) {
3362 Slog.e(TAG, "Unable to write in json", e);
3363 }
3364 }
3365 }
3366
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003367 // === Shell support ===
3368
3369 @Override
3370 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003371 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003372
3373 enforceShell();
3374
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07003375 final long token = injectClearCallingIdentity();
3376 try {
Dianne Hackborn354736e2016-08-22 17:00:05 -07003377 final int status = (new MyShellCommand()).exec(this, in, out, err, args, callback,
3378 resultReceiver);
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07003379 resultReceiver.send(status, null);
3380 } finally {
3381 injectRestoreCallingIdentity(token);
3382 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003383 }
3384
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003385 static class CommandException extends Exception {
3386 public CommandException(String message) {
3387 super(message);
3388 }
3389 }
3390
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003391 /**
3392 * Handle "adb shell cmd".
3393 */
3394 private class MyShellCommand extends ShellCommand {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003395
3396 private int mUserId = UserHandle.USER_SYSTEM;
3397
Makoto Onuki02f338e2016-07-29 09:40:40 -07003398 private void parseOptionsLocked(boolean takeUser)
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003399 throws CommandException {
3400 String opt;
3401 while ((opt = getNextOption()) != null) {
3402 switch (opt) {
3403 case "--user":
3404 if (takeUser) {
3405 mUserId = UserHandle.parseUserArg(getNextArgRequired());
Makoto Onuki02f338e2016-07-29 09:40:40 -07003406 if (!isUserUnlockedL(mUserId)) {
Makoto Onukif34c3082016-07-13 10:25:25 -07003407 throw new CommandException(
3408 "User " + mUserId + " is not running or locked");
3409 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003410 break;
3411 }
3412 // fallthrough
3413 default:
3414 throw new CommandException("Unknown option: " + opt);
3415 }
3416 }
3417 }
3418
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003419 @Override
3420 public int onCommand(String cmd) {
3421 if (cmd == null) {
3422 return handleDefaultCommands(cmd);
3423 }
3424 final PrintWriter pw = getOutPrintWriter();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003425 try {
3426 switch (cmd) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003427 case "reset-throttling":
3428 handleResetThrottling();
3429 break;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003430 case "reset-all-throttling":
3431 handleResetAllThrottling();
3432 break;
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003433 case "override-config":
3434 handleOverrideConfig();
3435 break;
3436 case "reset-config":
3437 handleResetConfig();
3438 break;
3439 case "clear-default-launcher":
3440 handleClearDefaultLauncher();
3441 break;
3442 case "get-default-launcher":
3443 handleGetDefaultLauncher();
3444 break;
Makoto Onukiac214972016-04-04 10:19:45 -07003445 case "unload-user":
3446 handleUnloadUser();
3447 break;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003448 case "clear-shortcuts":
3449 handleClearShortcuts();
3450 break;
Makoto Onukib08790c2016-06-23 14:05:46 -07003451 case "verify-states": // hidden command to verify various internal states.
3452 handleVerifyStates();
3453 break;
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003454 default:
3455 return handleDefaultCommands(cmd);
3456 }
3457 } catch (CommandException e) {
3458 pw.println("Error: " + e.getMessage());
3459 return 1;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003460 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003461 pw.println("Success");
3462 return 0;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003463 }
3464
3465 @Override
3466 public void onHelp() {
3467 final PrintWriter pw = getOutPrintWriter();
3468 pw.println("Usage: cmd shortcut COMMAND [options ...]");
3469 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003470 pw.println("cmd shortcut reset-throttling [--user USER_ID]");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003471 pw.println(" Reset throttling for all packages and users");
3472 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003473 pw.println("cmd shortcut reset-all-throttling");
3474 pw.println(" Reset the throttling state for all users");
3475 pw.println();
Makoto Onuki4362a662016-03-08 18:59:09 -08003476 pw.println("cmd shortcut override-config CONFIG");
3477 pw.println(" Override the configuration for testing (will last until reboot)");
3478 pw.println();
3479 pw.println("cmd shortcut reset-config");
3480 pw.println(" Reset the configuration set with \"update-config\"");
3481 pw.println();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003482 pw.println("cmd shortcut clear-default-launcher [--user USER_ID]");
3483 pw.println(" Clear the cached default launcher");
3484 pw.println();
3485 pw.println("cmd shortcut get-default-launcher [--user USER_ID]");
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07003486 pw.println(" Show the default launcher");
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003487 pw.println();
Makoto Onukiac214972016-04-04 10:19:45 -07003488 pw.println("cmd shortcut unload-user [--user USER_ID]");
3489 pw.println(" Unload a user from the memory");
3490 pw.println(" (This should not affect any observable behavior)");
3491 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003492 pw.println("cmd shortcut clear-shortcuts [--user USER_ID] PACKAGE");
3493 pw.println(" Remove all shortcuts from a package, including pinned shortcuts");
3494 pw.println();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003495 }
3496
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003497 private void handleResetThrottling() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003498 synchronized (mLock) {
3499 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki4554d0e2016-03-14 15:51:41 -07003500
Makoto Onuki02f338e2016-07-29 09:40:40 -07003501 Slog.i(TAG, "cmd: handleResetThrottling: user=" + mUserId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003502
Makoto Onuki02f338e2016-07-29 09:40:40 -07003503 resetThrottlingInner(mUserId);
3504 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003505 }
3506
3507 private void handleResetAllThrottling() {
3508 Slog.i(TAG, "cmd: handleResetAllThrottling");
3509
3510 resetAllThrottlingInner();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003511 }
3512
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003513 private void handleOverrideConfig() throws CommandException {
Makoto Onuki4362a662016-03-08 18:59:09 -08003514 final String config = getNextArgRequired();
3515
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003516 Slog.i(TAG, "cmd: handleOverrideConfig: " + config);
3517
Makoto Onuki4362a662016-03-08 18:59:09 -08003518 synchronized (mLock) {
3519 if (!updateConfigurationLocked(config)) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003520 throw new CommandException("override-config failed. See logcat for details.");
Makoto Onuki4362a662016-03-08 18:59:09 -08003521 }
3522 }
Makoto Onuki4362a662016-03-08 18:59:09 -08003523 }
3524
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003525 private void handleResetConfig() {
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003526 Slog.i(TAG, "cmd: handleResetConfig");
3527
Makoto Onuki4362a662016-03-08 18:59:09 -08003528 synchronized (mLock) {
3529 loadConfigurationLocked();
3530 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003531 }
3532
3533 private void clearLauncher() {
3534 synchronized (mLock) {
Makoto Onuki10305202016-07-14 18:14:08 -07003535 getUserShortcutsLocked(mUserId).forceClearLauncher();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003536 }
3537 }
3538
3539 private void showLauncher() {
3540 synchronized (mLock) {
3541 // This ensures to set the cached launcher. Package name doesn't matter.
3542 hasShortcutHostPermissionInner("-", mUserId);
3543
3544 getOutPrintWriter().println("Launcher: "
Makoto Onuki10305202016-07-14 18:14:08 -07003545 + getUserShortcutsLocked(mUserId).getLastKnownLauncher());
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003546 }
3547 }
3548
3549 private void handleClearDefaultLauncher() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003550 synchronized (mLock) {
3551 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003552
Makoto Onuki02f338e2016-07-29 09:40:40 -07003553 clearLauncher();
3554 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003555 }
3556
3557 private void handleGetDefaultLauncher() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003558 synchronized (mLock) {
3559 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003560
Makoto Onuki02f338e2016-07-29 09:40:40 -07003561 clearLauncher();
3562 showLauncher();
3563 }
Makoto Onuki4362a662016-03-08 18:59:09 -08003564 }
Makoto Onukiac214972016-04-04 10:19:45 -07003565
3566 private void handleUnloadUser() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003567 synchronized (mLock) {
3568 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onukiac214972016-04-04 10:19:45 -07003569
Makoto Onuki02f338e2016-07-29 09:40:40 -07003570 Slog.i(TAG, "cmd: handleUnloadUser: user=" + mUserId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003571
Makoto Onuki02f338e2016-07-29 09:40:40 -07003572 ShortcutService.this.handleCleanupUser(mUserId);
3573 }
Makoto Onukiac214972016-04-04 10:19:45 -07003574 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003575
3576 private void handleClearShortcuts() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003577 synchronized (mLock) {
3578 parseOptionsLocked(/* takeUser =*/ true);
3579 final String packageName = getNextArgRequired();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003580
Makoto Onuki02f338e2016-07-29 09:40:40 -07003581 Slog.i(TAG, "cmd: handleClearShortcuts: user" + mUserId + ", " + packageName);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003582
Makoto Onuki02f338e2016-07-29 09:40:40 -07003583 ShortcutService.this.cleanUpPackageForAllLoadedUsers(packageName, mUserId,
3584 /* appStillExists = */ true);
3585 }
Makoto Onukib08790c2016-06-23 14:05:46 -07003586 }
3587
3588 private void handleVerifyStates() throws CommandException {
3589 try {
3590 verifyStatesForce(); // This will throw when there's an issue.
3591 } catch (Throwable th) {
3592 throw new CommandException(th.getMessage() + "\n" + Log.getStackTraceString(th));
3593 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003594 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003595 }
3596
3597 // === Unit test support ===
3598
3599 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07003600 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003601 long injectCurrentTimeMillis() {
3602 return System.currentTimeMillis();
3603 }
3604
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003605 @VisibleForTesting
3606 long injectElapsedRealtime() {
3607 return SystemClock.elapsedRealtime();
3608 }
3609
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003610 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07003611 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003612 int injectBinderCallingUid() {
3613 return getCallingUid();
3614 }
3615
Makoto Onuki31459242016-03-22 11:12:18 -07003616 private int getCallingUserId() {
Makoto Onuki4554d0e2016-03-14 15:51:41 -07003617 return UserHandle.getUserId(injectBinderCallingUid());
3618 }
3619
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07003620 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07003621 @VisibleForTesting
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07003622 long injectClearCallingIdentity() {
3623 return Binder.clearCallingIdentity();
3624 }
3625
3626 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07003627 @VisibleForTesting
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07003628 void injectRestoreCallingIdentity(long token) {
3629 Binder.restoreCallingIdentity(token);
3630 }
3631
Makoto Onuki33663282016-08-22 16:19:04 -07003632 // Injection point.
3633 @VisibleForTesting
3634 String injectBuildFingerprint() {
3635 return Build.FINGERPRINT;
3636 }
3637
Makoto Onukide667372016-03-15 14:29:20 -07003638 final void wtf(String message) {
Makoto Onukib08790c2016-06-23 14:05:46 -07003639 wtf(message, /* exception= */ null);
Makoto Onukide667372016-03-15 14:29:20 -07003640 }
3641
Makoto Onuki2e210c42016-03-30 08:30:36 -07003642 // Injection point.
Makoto Onukia2241832016-07-06 13:28:37 -07003643 void wtf(String message, Throwable e) {
3644 if (e == null) {
3645 e = new RuntimeException("Stacktrace");
3646 }
3647 synchronized (mLock) {
3648 mWtfCount++;
3649 mLastWtfStacktrace = new Exception("Last failure was logged here:");
3650 }
Makoto Onukide667372016-03-15 14:29:20 -07003651 Slog.wtf(TAG, message, e);
3652 }
3653
Makoto Onuki31459242016-03-22 11:12:18 -07003654 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003655 File injectSystemDataPath() {
3656 return Environment.getDataSystemDirectory();
3657 }
3658
Makoto Onuki31459242016-03-22 11:12:18 -07003659 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003660 File injectUserDataPath(@UserIdInt int userId) {
Makoto Onuki55046222016-03-08 10:49:47 -08003661 return new File(Environment.getDataSystemCeDirectory(userId), DIRECTORY_PER_USER);
3662 }
3663
Makoto Onuki4362a662016-03-08 18:59:09 -08003664 @VisibleForTesting
Makoto Onuki55046222016-03-08 10:49:47 -08003665 boolean injectIsLowRamDevice() {
3666 return ActivityManager.isLowRamDeviceStatic();
3667 }
3668
Makoto Onuki31459242016-03-22 11:12:18 -07003669 @VisibleForTesting
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003670 void injectRegisterUidObserver(IUidObserver observer, int which) {
3671 try {
Dianne Hackborn5614bf52016-11-07 17:26:41 -08003672 ActivityManagerNative.getDefault().registerUidObserver(observer, which,
3673 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003674 } catch (RemoteException shouldntHappen) {
3675 }
3676 }
3677
Makoto Onuki55046222016-03-08 10:49:47 -08003678 File getUserBitmapFilePath(@UserIdInt int userId) {
3679 return new File(injectUserDataPath(userId), DIRECTORY_BITMAPS);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003680 }
3681
3682 @VisibleForTesting
Makoto Onuki31459242016-03-22 11:12:18 -07003683 SparseArray<ShortcutUser> getShortcutsForTest() {
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08003684 return mUsers;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003685 }
3686
3687 @VisibleForTesting
Makoto Onukib5a012f2016-06-21 11:13:53 -07003688 int getMaxShortcutsForTest() {
3689 return mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003690 }
3691
3692 @VisibleForTesting
Makoto Onukib6d35232016-04-04 15:57:17 -07003693 int getMaxUpdatesPerIntervalForTest() {
3694 return mMaxUpdatesPerInterval;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003695 }
3696
3697 @VisibleForTesting
Makoto Onuki4362a662016-03-08 18:59:09 -08003698 long getResetIntervalForTest() {
3699 return mResetInterval;
Makoto Onuki55046222016-03-08 10:49:47 -08003700 }
3701
3702 @VisibleForTesting
Makoto Onuki4362a662016-03-08 18:59:09 -08003703 int getMaxIconDimensionForTest() {
3704 return mMaxIconDimension;
3705 }
3706
3707 @VisibleForTesting
3708 CompressFormat getIconPersistFormatForTest() {
3709 return mIconPersistFormat;
3710 }
3711
3712 @VisibleForTesting
3713 int getIconPersistQualityForTest() {
3714 return mIconPersistQuality;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003715 }
Makoto Onuki41066a62016-03-09 16:18:44 -08003716
3717 @VisibleForTesting
Makoto Onuki22fcc682016-05-17 14:52:19 -07003718 ShortcutPackage getPackageShortcutForTest(String packageName, int userId) {
Makoto Onuki41066a62016-03-09 16:18:44 -08003719 synchronized (mLock) {
Makoto Onuki31459242016-03-22 11:12:18 -07003720 final ShortcutUser user = mUsers.get(userId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07003721 if (user == null) return null;
3722
Makoto Onuki22fcc682016-05-17 14:52:19 -07003723 return user.getAllPackagesForTest().get(packageName);
3724 }
3725 }
3726
3727 @VisibleForTesting
3728 ShortcutInfo getPackageShortcutForTest(String packageName, String shortcutId, int userId) {
3729 synchronized (mLock) {
Makoto Onukif34c3082016-07-13 10:25:25 -07003730 final ShortcutPackage pkg = getPackageShortcutForTest(packageName, userId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07003731 if (pkg == null) return null;
3732
3733 return pkg.findShortcutById(shortcutId);
Makoto Onuki41066a62016-03-09 16:18:44 -08003734 }
3735 }
Makoto Onuki7001a612016-05-27 13:24:28 -07003736
3737 /**
3738 * Control whether {@link #verifyStates} should be performed. We always perform it during unit
3739 * tests.
3740 */
3741 @VisibleForTesting
3742 boolean injectShouldPerformVerification() {
3743 return DEBUG;
3744 }
3745
3746 /**
3747 * Check various internal states and throws if there's any inconsistency.
3748 * This is normally only enabled during unit tests.
3749 */
3750 final void verifyStates() {
3751 if (injectShouldPerformVerification()) {
3752 verifyStatesInner();
3753 }
3754 }
3755
Makoto Onukib08790c2016-06-23 14:05:46 -07003756 private final void verifyStatesForce() {
3757 verifyStatesInner();
3758 }
3759
Makoto Onuki7001a612016-05-27 13:24:28 -07003760 private void verifyStatesInner() {
Makoto Onuki10305202016-07-14 18:14:08 -07003761 synchronized (mLock) {
Makoto Onuki7001a612016-05-27 13:24:28 -07003762 forEachLoadedUserLocked(u -> u.forAllPackageItems(ShortcutPackageItem::verifyStates));
3763 }
3764 }
Makoto Onuki41066a62016-03-09 16:18:44 -08003765}