blob: d8857b77d9618d40650a35bc8fff5cdc81f44e23 [file] [log] [blame]
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package com.android.server.pm;
17
Makoto Onuki7001a612016-05-27 13:24:28 -070018import android.annotation.IntDef;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080019import android.annotation.NonNull;
20import android.annotation.Nullable;
21import android.annotation.UserIdInt;
Makoto Onuki55046222016-03-08 10:49:47 -080022import android.app.ActivityManager;
Makoto Onuki33525d22016-08-03 15:45:24 -070023import android.app.ActivityManagerInternal;
Makoto Onuki0acbb142016-03-22 17:02:57 -070024import android.app.AppGlobals;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -070025import android.app.IUidObserver;
Makoto Onukiac042502016-05-20 16:39:42 -070026import android.app.usage.UsageStatsManagerInternal;
Sunny Goyal87a563e2017-01-01 19:42:45 -080027import android.appwidget.AppWidgetProviderInfo;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070028import android.content.BroadcastReceiver;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080029import android.content.ComponentName;
30import android.content.Context;
31import android.content.Intent;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070032import android.content.IntentFilter;
Makoto Onuki2d895c32016-12-02 15:48:40 -080033import android.content.IntentSender;
34import android.content.IntentSender.SendIntentException;
Makoto Onuki22fcc682016-05-17 14:52:19 -070035import android.content.pm.ActivityInfo;
Makoto Onuki0acbb142016-03-22 17:02:57 -070036import android.content.pm.ApplicationInfo;
37import android.content.pm.IPackageManager;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080038import android.content.pm.IShortcutService;
39import android.content.pm.LauncherApps;
40import android.content.pm.LauncherApps.ShortcutQuery;
Makoto Onuki0acbb142016-03-22 17:02:57 -070041import android.content.pm.PackageInfo;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080042import android.content.pm.PackageManager;
Makoto Onuki20c95f82016-05-11 16:51:01 -070043import android.content.pm.PackageManager.NameNotFoundException;
Makoto Onuki2d5b4652016-03-11 16:09:54 -080044import android.content.pm.PackageManagerInternal;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080045import android.content.pm.ParceledListSlice;
Makoto Onuki2d5b4652016-03-11 16:09:54 -080046import android.content.pm.ResolveInfo;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080047import android.content.pm.ShortcutInfo;
Makoto Onuki2d895c32016-12-02 15:48:40 -080048import android.content.pm.ShortcutManager;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080049import android.content.pm.ShortcutServiceInternal;
50import android.content.pm.ShortcutServiceInternal.ShortcutChangeListener;
Makoto Onuki2d895c32016-12-02 15:48:40 -080051import android.content.pm.UserInfo;
Makoto Onuki157b1622016-06-02 16:13:10 -070052import android.content.res.Resources;
Makoto Onuki22fcc682016-05-17 14:52:19 -070053import android.content.res.XmlResourceParser;
Makoto Onuki55046222016-03-08 10:49:47 -080054import android.graphics.Bitmap;
55import android.graphics.Bitmap.CompressFormat;
Makoto Onuki55046222016-03-08 10:49:47 -080056import android.graphics.Canvas;
57import android.graphics.RectF;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080058import android.graphics.drawable.Icon;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070059import android.net.Uri;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080060import android.os.Binder;
Makoto Onuki33663282016-08-22 16:19:04 -070061import android.os.Build;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080062import android.os.Environment;
Makoto Onuki2e210c42016-03-30 08:30:36 -070063import android.os.FileUtils;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080064import android.os.Handler;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070065import android.os.LocaleList;
Makoto Onukiaa8b94a2016-03-17 13:14:05 -070066import android.os.Looper;
Makoto Onuki55046222016-03-08 10:49:47 -080067import android.os.ParcelFileDescriptor;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080068import android.os.PersistableBundle;
69import android.os.Process;
70import android.os.RemoteException;
71import android.os.ResultReceiver;
Makoto Onuki55046222016-03-08 10:49:47 -080072import android.os.SELinux;
Makoto Onukib08790c2016-06-23 14:05:46 -070073import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070074import android.os.ShellCallback;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080075import android.os.ShellCommand;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -070076import android.os.SystemClock;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080077import android.os.UserHandle;
Makoto Onukicdc78f72016-03-21 15:47:52 -070078import android.os.UserManager;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080079import android.text.TextUtils;
80import android.text.format.Time;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080081import android.util.ArraySet;
82import android.util.AtomicFile;
Makoto Onuki4362a662016-03-08 18:59:09 -080083import android.util.KeyValueListParser;
Makoto Onukiac042502016-05-20 16:39:42 -070084import android.util.Log;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080085import android.util.Slog;
86import android.util.SparseArray;
Makoto Onuki02f338e2016-07-29 09:40:40 -070087import android.util.SparseBooleanArray;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -070088import android.util.SparseIntArray;
89import android.util.SparseLongArray;
Makoto Onuki55046222016-03-08 10:49:47 -080090import android.util.TypedValue;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080091import android.util.Xml;
Makoto Onukib08790c2016-06-23 14:05:46 -070092import android.view.IWindowManager;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080093
94import com.android.internal.annotations.GuardedBy;
95import com.android.internal.annotations.VisibleForTesting;
96import com.android.internal.os.BackgroundThread;
97import com.android.internal.util.FastXmlSerializer;
98import com.android.internal.util.Preconditions;
99import com.android.server.LocalServices;
100import com.android.server.SystemService;
Makoto Onukid99c6f02016-03-28 11:02:54 -0700101import com.android.server.pm.ShortcutUser.PackageWithUser;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800102
103import libcore.io.IoUtils;
104
Makoto Onuki76269922016-07-15 14:58:54 -0700105import org.json.JSONArray;
106import org.json.JSONException;
107import org.json.JSONObject;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800108import org.xmlpull.v1.XmlPullParser;
109import org.xmlpull.v1.XmlPullParserException;
110import org.xmlpull.v1.XmlSerializer;
111
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700112import java.io.BufferedInputStream;
113import java.io.BufferedOutputStream;
114import java.io.ByteArrayInputStream;
115import java.io.ByteArrayOutputStream;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800116import java.io.File;
117import java.io.FileDescriptor;
118import java.io.FileInputStream;
119import java.io.FileNotFoundException;
120import java.io.FileOutputStream;
121import java.io.IOException;
Makoto Onuki55046222016-03-08 10:49:47 -0800122import java.io.InputStream;
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700123import java.io.OutputStream;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800124import java.io.PrintWriter;
Makoto Onuki7001a612016-05-27 13:24:28 -0700125import java.lang.annotation.Retention;
126import java.lang.annotation.RetentionPolicy;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800127import java.net.URISyntaxException;
128import java.nio.charset.StandardCharsets;
129import java.util.ArrayList;
Makoto Onuki22fcc682016-05-17 14:52:19 -0700130import java.util.Collections;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800131import java.util.List;
Makoto Onukic51b2872016-05-04 15:24:50 -0700132import java.util.concurrent.atomic.AtomicBoolean;
Makoto Onuki2e210c42016-03-30 08:30:36 -0700133import java.util.function.Consumer;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800134import java.util.function.Predicate;
135
136/**
137 * TODO:
Makoto Onuki22fcc682016-05-17 14:52:19 -0700138 * - getIconMaxWidth()/getIconMaxHeight() should use xdpi and ydpi.
Makoto Onukib5a012f2016-06-21 11:13:53 -0700139 * -> But TypedValue.applyDimension() doesn't differentiate x and y..?
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800140 *
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700141 * - Detect when already registered instances are passed to APIs again, which might break
Makoto Onukib08790c2016-06-23 14:05:46 -0700142 * internal bitmap handling.
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800143 */
144public class ShortcutService extends IShortcutService.Stub {
Makoto Onuki55046222016-03-08 10:49:47 -0800145 static final String TAG = "ShortcutService";
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800146
Makoto Onuki7001a612016-05-27 13:24:28 -0700147 static final boolean DEBUG = false; // STOPSHIP if true
Makoto Onuki41066a62016-03-09 16:18:44 -0800148 static final boolean DEBUG_LOAD = false; // STOPSHIP if true
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700149 static final boolean DEBUG_PROCSTATE = false; // STOPSHIP if true
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800150
Makoto Onuki4362a662016-03-08 18:59:09 -0800151 @VisibleForTesting
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700152 static final long DEFAULT_RESET_INTERVAL_SEC = 24 * 60 * 60; // 1 day
Makoto Onuki4362a662016-03-08 18:59:09 -0800153
154 @VisibleForTesting
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700155 static final int DEFAULT_MAX_UPDATES_PER_INTERVAL = 10;
Makoto Onuki4362a662016-03-08 18:59:09 -0800156
157 @VisibleForTesting
158 static final int DEFAULT_MAX_SHORTCUTS_PER_APP = 5;
159
160 @VisibleForTesting
161 static final int DEFAULT_MAX_ICON_DIMENSION_DP = 96;
162
163 @VisibleForTesting
164 static final int DEFAULT_MAX_ICON_DIMENSION_LOWRAM_DP = 48;
165
166 @VisibleForTesting
167 static final String DEFAULT_ICON_PERSIST_FORMAT = CompressFormat.PNG.name();
168
169 @VisibleForTesting
170 static final int DEFAULT_ICON_PERSIST_QUALITY = 100;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800171
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700172 @VisibleForTesting
173 static final int DEFAULT_SAVE_DELAY_MS = 3000;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800174
175 @VisibleForTesting
176 static final String FILENAME_BASE_STATE = "shortcut_service.xml";
177
178 @VisibleForTesting
179 static final String DIRECTORY_PER_USER = "shortcut_service";
180
181 @VisibleForTesting
182 static final String FILENAME_USER_PACKAGES = "shortcuts.xml";
183
Makoto Onuki55046222016-03-08 10:49:47 -0800184 static final String DIRECTORY_BITMAPS = "bitmaps";
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800185
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700186 private static final String TAG_ROOT = "root";
187 private static final String TAG_LAST_RESET_TIME = "last_reset_time";
Makoto Onuki55046222016-03-08 10:49:47 -0800188
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700189 private static final String ATTR_VALUE = "value";
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800190
Makoto Onukib08790c2016-06-23 14:05:46 -0700191 private static final String LAUNCHER_INTENT_CATEGORY = Intent.CATEGORY_LAUNCHER;
192
Makoto Onuki76269922016-07-15 14:58:54 -0700193 private static final String KEY_SHORTCUT = "shortcut";
194 private static final String KEY_LOW_RAM = "lowRam";
195 private static final String KEY_ICON_SIZE = "iconSize";
196
Makoto Onuki2d895c32016-12-02 15:48:40 -0800197 private static final String DUMMY_MAIN_ACTIVITY = "android.__dummy__";
198
Makoto Onuki4362a662016-03-08 18:59:09 -0800199 @VisibleForTesting
200 interface ConfigConstants {
201 /**
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700202 * Key name for the save delay, in milliseconds. (int)
203 */
204 String KEY_SAVE_DELAY_MILLIS = "save_delay_ms";
205
206 /**
Makoto Onuki4362a662016-03-08 18:59:09 -0800207 * Key name for the throttling reset interval, in seconds. (long)
208 */
209 String KEY_RESET_INTERVAL_SEC = "reset_interval_sec";
210
211 /**
212 * Key name for the max number of modifying API calls per app for every interval. (int)
213 */
Makoto Onukib6d35232016-04-04 15:57:17 -0700214 String KEY_MAX_UPDATES_PER_INTERVAL = "max_updates_per_interval";
Makoto Onuki4362a662016-03-08 18:59:09 -0800215
216 /**
217 * Key name for the max icon dimensions in DP, for non-low-memory devices.
218 */
219 String KEY_MAX_ICON_DIMENSION_DP = "max_icon_dimension_dp";
220
221 /**
222 * Key name for the max icon dimensions in DP, for low-memory devices.
223 */
224 String KEY_MAX_ICON_DIMENSION_DP_LOWRAM = "max_icon_dimension_dp_lowram";
225
226 /**
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700227 * Key name for the max dynamic shortcuts per activity. (int)
Makoto Onuki4362a662016-03-08 18:59:09 -0800228 */
229 String KEY_MAX_SHORTCUTS = "max_shortcuts";
230
231 /**
Makoto Onuki41066a62016-03-09 16:18:44 -0800232 * Key name for icon compression quality, 0-100.
Makoto Onuki4362a662016-03-08 18:59:09 -0800233 */
234 String KEY_ICON_QUALITY = "icon_quality";
235
236 /**
237 * Key name for icon compression format: "PNG", "JPEG" or "WEBP"
238 */
239 String KEY_ICON_FORMAT = "icon_format";
240 }
241
Makoto Onuki41066a62016-03-09 16:18:44 -0800242 final Context mContext;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800243
244 private final Object mLock = new Object();
245
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700246 private static List<ResolveInfo> EMPTY_RESOLVE_INFO = new ArrayList<>(0);
247
Mark Renoufe065f7c2016-11-01 11:48:24 -0400248 // Temporarily reverted to anonymous inner class form due to: b/32554459
249 private static Predicate<ResolveInfo> ACTIVITY_NOT_EXPORTED = new Predicate<ResolveInfo>() {
250 public boolean test(ResolveInfo ri) {
251 return !ri.activityInfo.exported;
252 }
253 };
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700254
Mark Renoufe065f7c2016-11-01 11:48:24 -0400255 // Temporarily reverted to anonymous inner class form due to: b/32554459
256 private static Predicate<PackageInfo> PACKAGE_NOT_INSTALLED = new Predicate<PackageInfo>() {
257 public boolean test(PackageInfo pi) {
258 return !isInstalled(pi);
259 }
260 };
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700261
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800262 private final Handler mHandler;
263
264 @GuardedBy("mLock")
265 private final ArrayList<ShortcutChangeListener> mListeners = new ArrayList<>(1);
266
267 @GuardedBy("mLock")
268 private long mRawLastResetTime;
269
270 /**
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -0800271 * User ID -> UserShortcuts
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800272 */
273 @GuardedBy("mLock")
Makoto Onuki31459242016-03-22 11:12:18 -0700274 private final SparseArray<ShortcutUser> mUsers = new SparseArray<>();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800275
276 /**
Makoto Onukib5a012f2016-06-21 11:13:53 -0700277 * Max number of dynamic + manifest shortcuts that each application can have at a time.
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800278 */
Makoto Onukib5a012f2016-06-21 11:13:53 -0700279 private int mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800280
281 /**
Makoto Onukib6d35232016-04-04 15:57:17 -0700282 * Max number of updating API calls that each application can make during the interval.
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800283 */
Makoto Onukib6d35232016-04-04 15:57:17 -0700284 int mMaxUpdatesPerInterval;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800285
286 /**
287 * Actual throttling-reset interval. By default it's a day.
288 */
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800289 private long mResetInterval;
290
Makoto Onuki55046222016-03-08 10:49:47 -0800291 /**
292 * Icon max width/height in pixels.
293 */
294 private int mMaxIconDimension;
295
Makoto Onuki4362a662016-03-08 18:59:09 -0800296 private CompressFormat mIconPersistFormat;
297 private int mIconPersistQuality;
Makoto Onuki55046222016-03-08 10:49:47 -0800298
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700299 private int mSaveDelayMillis;
300
Makoto Onuki0acbb142016-03-22 17:02:57 -0700301 private final IPackageManager mIPackageManager;
Makoto Onuki2d5b4652016-03-11 16:09:54 -0800302 private final PackageManagerInternal mPackageManagerInternal;
Makoto Onukicdc78f72016-03-21 15:47:52 -0700303 private final UserManager mUserManager;
Makoto Onukiac042502016-05-20 16:39:42 -0700304 private final UsageStatsManagerInternal mUsageStatsManagerInternal;
Makoto Onuki33525d22016-08-03 15:45:24 -0700305 private final ActivityManagerInternal mActivityManagerInternal;
Makoto Onuki2d5b4652016-03-11 16:09:54 -0800306
Makoto Onuki2d895c32016-12-02 15:48:40 -0800307 private final ShortcutRequestPinProcessor mShortcutRequestPinProcessor;
308
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700309 @GuardedBy("mLock")
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700310 final SparseIntArray mUidState = new SparseIntArray();
311
312 @GuardedBy("mLock")
313 final SparseLongArray mUidLastForegroundElapsedTime = new SparseLongArray();
314
315 @GuardedBy("mLock")
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700316 private List<Integer> mDirtyUserIds = new ArrayList<>();
317
Makoto Onukic51b2872016-05-04 15:24:50 -0700318 private final AtomicBoolean mBootCompleted = new AtomicBoolean();
319
Makoto Onuki905e8852016-03-28 10:40:58 -0700320 private static final int PACKAGE_MATCH_FLAGS =
321 PackageManager.MATCH_DIRECT_BOOT_AWARE
Makoto Onukib08790c2016-06-23 14:05:46 -0700322 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE
323 | PackageManager.MATCH_UNINSTALLED_PACKAGES;
Makoto Onuki905e8852016-03-28 10:40:58 -0700324
Makoto Onuki02f338e2016-07-29 09:40:40 -0700325 @GuardedBy("mLock")
326 final SparseBooleanArray mUnlockedUsers = new SparseBooleanArray();
327
Makoto Onuki2e210c42016-03-30 08:30:36 -0700328 // Stats
329 @VisibleForTesting
330 interface Stats {
331 int GET_DEFAULT_HOME = 0;
332 int GET_PACKAGE_INFO = 1;
333 int GET_PACKAGE_INFO_WITH_SIG = 2;
334 int GET_APPLICATION_INFO = 3;
335 int LAUNCHER_PERMISSION_CHECK = 4;
Makoto Onuki6c1dbd52016-05-02 15:19:32 -0700336 int CLEANUP_DANGLING_BITMAPS = 5;
Makoto Onukib08790c2016-06-23 14:05:46 -0700337 int GET_ACTIVITY_WITH_METADATA = 6;
Makoto Onuki6dd9fb72016-06-01 13:55:54 -0700338 int GET_INSTALLED_PACKAGES = 7;
Makoto Onuki22fcc682016-05-17 14:52:19 -0700339 int CHECK_PACKAGE_CHANGES = 8;
Makoto Onuki157b1622016-06-02 16:13:10 -0700340 int GET_APPLICATION_RESOURCES = 9;
341 int RESOURCE_NAME_LOOKUP = 10;
Makoto Onukib08790c2016-06-23 14:05:46 -0700342 int GET_LAUNCHER_ACTIVITY = 11;
343 int CHECK_LAUNCHER_ACTIVITY = 12;
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700344 int IS_ACTIVITY_ENABLED = 13;
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700345 int PACKAGE_UPDATE_CHECK = 14;
Makoto Onuki085a05c2016-08-19 11:39:29 -0700346 int ASYNC_PRELOAD_USER_DELAY = 15;
Makoto Onuki2d895c32016-12-02 15:48:40 -0800347 int GET_DEFAULT_LAUNCHER = 16;
Makoto Onuki2e210c42016-03-30 08:30:36 -0700348
Makoto Onuki2d895c32016-12-02 15:48:40 -0800349 int COUNT = GET_DEFAULT_LAUNCHER + 1;
Makoto Onuki2e210c42016-03-30 08:30:36 -0700350 }
351
Makoto Onuki085a05c2016-08-19 11:39:29 -0700352 private static final String[] STAT_LABELS = {
353 "getHomeActivities()",
354 "Launcher permission check",
355 "getPackageInfo()",
356 "getPackageInfo(SIG)",
357 "getApplicationInfo",
358 "cleanupDanglingBitmaps",
359 "getActivity+metadata",
360 "getInstalledPackages",
361 "checkPackageChanges",
362 "getApplicationResources",
363 "resourceNameLookup",
364 "getLauncherActivity",
365 "checkLauncherActivity",
366 "isActivityEnabled",
367 "packageUpdateCheck",
Makoto Onuki2d895c32016-12-02 15:48:40 -0800368 "asyncPreloadUserDelay",
369 "getDefaultLauncher()"
Makoto Onuki085a05c2016-08-19 11:39:29 -0700370 };
371
Makoto Onuki2e210c42016-03-30 08:30:36 -0700372 final Object mStatLock = new Object();
373
374 @GuardedBy("mStatLock")
375 private final int[] mCountStats = new int[Stats.COUNT];
376
377 @GuardedBy("mStatLock")
378 private final long[] mDurationStats = new long[Stats.COUNT];
379
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700380 private static final int PROCESS_STATE_FOREGROUND_THRESHOLD =
381 ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
382
Makoto Onuki7001a612016-05-27 13:24:28 -0700383 static final int OPERATION_SET = 0;
384 static final int OPERATION_ADD = 1;
385 static final int OPERATION_UPDATE = 2;
386
387 /** @hide */
388 @IntDef(value = {
389 OPERATION_SET,
390 OPERATION_ADD,
391 OPERATION_UPDATE
Makoto Onukib08790c2016-06-23 14:05:46 -0700392 })
Makoto Onuki7001a612016-05-27 13:24:28 -0700393 @Retention(RetentionPolicy.SOURCE)
Makoto Onukib08790c2016-06-23 14:05:46 -0700394 @interface ShortcutOperation {
395 }
Makoto Onuki7001a612016-05-27 13:24:28 -0700396
Makoto Onukia2241832016-07-06 13:28:37 -0700397 @GuardedBy("mLock")
398 private int mWtfCount = 0;
399
400 @GuardedBy("mLock")
401 private Exception mLastWtfStacktrace;
402
Makoto Onukifc4cf2d2016-08-24 11:10:26 -0700403 static class InvalidFileFormatException extends Exception {
404 public InvalidFileFormatException(String message, Throwable cause) {
405 super(message, cause);
406 }
407 }
408
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800409 public ShortcutService(Context context) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700410 this(context, BackgroundThread.get().getLooper(), /*onyForPackgeManagerApis*/ false);
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700411 }
412
413 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700414 ShortcutService(Context context, Looper looper, boolean onlyForPackageManagerApis) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800415 mContext = Preconditions.checkNotNull(context);
416 LocalServices.addService(ShortcutServiceInternal.class, new LocalService());
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700417 mHandler = new Handler(looper);
Makoto Onuki0acbb142016-03-22 17:02:57 -0700418 mIPackageManager = AppGlobals.getPackageManager();
Makoto Onukiac042502016-05-20 16:39:42 -0700419 mPackageManagerInternal = Preconditions.checkNotNull(
420 LocalServices.getService(PackageManagerInternal.class));
421 mUserManager = Preconditions.checkNotNull(context.getSystemService(UserManager.class));
422 mUsageStatsManagerInternal = Preconditions.checkNotNull(
423 LocalServices.getService(UsageStatsManagerInternal.class));
Makoto Onuki33525d22016-08-03 15:45:24 -0700424 mActivityManagerInternal = Preconditions.checkNotNull(
425 LocalServices.getService(ActivityManagerInternal.class));
Makoto Onukicdc78f72016-03-21 15:47:52 -0700426
Makoto Onuki2d895c32016-12-02 15:48:40 -0800427 mShortcutRequestPinProcessor = new ShortcutRequestPinProcessor(this, mLock);
428
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700429 if (onlyForPackageManagerApis) {
430 return; // Don't do anything further. For unit tests only.
431 }
432
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700433 // Register receivers.
434
435 // We need to set a priority, so let's just not use PackageMonitor for now.
436 // TODO Refactor PackageMonitor to support priorities.
437 final IntentFilter packageFilter = new IntentFilter();
438 packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
439 packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
440 packageFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
441 packageFilter.addAction(Intent.ACTION_PACKAGE_DATA_CLEARED);
442 packageFilter.addDataScheme("package");
443 packageFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
444 mContext.registerReceiverAsUser(mPackageMonitor, UserHandle.ALL,
445 packageFilter, null, mHandler);
446
Makoto Onuki10305202016-07-14 18:14:08 -0700447 final IntentFilter preferedActivityFilter = new IntentFilter();
448 preferedActivityFilter.addAction(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
449 preferedActivityFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
450 mContext.registerReceiverAsUser(mPackageMonitor, UserHandle.ALL,
451 preferedActivityFilter, null, mHandler);
452
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700453 final IntentFilter localeFilter = new IntentFilter();
454 localeFilter.addAction(Intent.ACTION_LOCALE_CHANGED);
455 localeFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
456 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL,
457 localeFilter, null, mHandler);
Makoto Onukif34c3082016-07-13 10:25:25 -0700458
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700459 injectRegisterUidObserver(mUidObserver, ActivityManager.UID_OBSERVER_PROCSTATE
460 | ActivityManager.UID_OBSERVER_GONE);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800461 }
462
Makoto Onuki2e210c42016-03-30 08:30:36 -0700463 void logDurationStat(int statId, long start) {
464 synchronized (mStatLock) {
465 mCountStats[statId]++;
Makoto Onuki6c1dbd52016-05-02 15:19:32 -0700466 mDurationStats[statId] += (injectElapsedRealtime() - start);
Makoto Onuki2e210c42016-03-30 08:30:36 -0700467 }
468 }
469
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700470 public String injectGetLocaleTagsForUser(@UserIdInt int userId) {
471 // TODO This should get the per-user locale. b/30123329 b/30119489
472 return LocaleList.getDefault().toLanguageTags();
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700473 }
474
475 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Makoto Onukib08790c2016-06-23 14:05:46 -0700476 @Override
477 public void onUidStateChanged(int uid, int procState) throws RemoteException {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700478 handleOnUidStateChanged(uid, procState);
479 }
480
Makoto Onukib08790c2016-06-23 14:05:46 -0700481 @Override
Dianne Hackborne07641d2016-11-09 15:07:23 -0800482 public void onUidGone(int uid, boolean disabled) throws RemoteException {
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800483 handleOnUidStateChanged(uid, ActivityManager.PROCESS_STATE_NONEXISTENT);
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700484 }
485
Makoto Onukib08790c2016-06-23 14:05:46 -0700486 @Override
487 public void onUidActive(int uid) throws RemoteException {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700488 }
489
Makoto Onukib08790c2016-06-23 14:05:46 -0700490 @Override
Dianne Hackborne07641d2016-11-09 15:07:23 -0800491 public void onUidIdle(int uid, boolean disabled) throws RemoteException {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700492 }
493 };
494
495 void handleOnUidStateChanged(int uid, int procState) {
496 if (DEBUG_PROCSTATE) {
497 Slog.d(TAG, "onUidStateChanged: uid=" + uid + " state=" + procState);
498 }
499 synchronized (mLock) {
500 mUidState.put(uid, procState);
501
502 // We need to keep track of last time an app comes to foreground.
503 // See ShortcutPackage.getApiCallCount() for how it's used.
504 // It doesn't have to be persisted, but it needs to be the elapsed time.
505 if (isProcessStateForeground(procState)) {
506 mUidLastForegroundElapsedTime.put(uid, injectElapsedRealtime());
507 }
508 }
509 }
510
511 private boolean isProcessStateForeground(int processState) {
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800512 return processState <= PROCESS_STATE_FOREGROUND_THRESHOLD;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700513 }
514
515 boolean isUidForegroundLocked(int uid) {
516 if (uid == Process.SYSTEM_UID) {
517 // IUidObserver doesn't report the state of SYSTEM, but it always has bound services,
518 // so it's foreground anyway.
519 return true;
520 }
Makoto Onuki33525d22016-08-03 15:45:24 -0700521 // First, check with the local cache.
522 if (isProcessStateForeground(mUidState.get(uid, ActivityManager.MAX_PROCESS_STATE))) {
523 return true;
524 }
525 // If the cache says background, reach out to AM. Since it'll internally need to hold
526 // the AM lock, we use it as a last resort.
527 return isProcessStateForeground(mActivityManagerInternal.getUidProcessState(uid));
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700528 }
529
530 long getUidLastForegroundElapsedTimeLocked(int uid) {
531 return mUidLastForegroundElapsedTime.get(uid);
532 }
533
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800534 /**
535 * System service lifecycle.
536 */
537 public static final class Lifecycle extends SystemService {
538 final ShortcutService mService;
539
540 public Lifecycle(Context context) {
541 super(context);
542 mService = new ShortcutService(context);
543 }
544
545 @Override
546 public void onStart() {
547 publishBinderService(Context.SHORTCUT_SERVICE, mService);
548 }
549
550 @Override
551 public void onBootPhase(int phase) {
552 mService.onBootPhase(phase);
553 }
554
555 @Override
556 public void onCleanupUser(int userHandle) {
Makoto Onukicdc78f72016-03-21 15:47:52 -0700557 mService.handleCleanupUser(userHandle);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800558 }
559
560 @Override
Makoto Onukif3a572b2016-03-10 12:28:38 -0800561 public void onUnlockUser(int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -0700562 mService.handleUnlockUser(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800563 }
564 }
565
566 /** lifecycle event */
567 void onBootPhase(int phase) {
568 if (DEBUG) {
569 Slog.d(TAG, "onBootPhase: " + phase);
570 }
571 switch (phase) {
572 case SystemService.PHASE_LOCK_SETTINGS_READY:
573 initialize();
574 break;
Makoto Onukic51b2872016-05-04 15:24:50 -0700575 case SystemService.PHASE_BOOT_COMPLETED:
576 mBootCompleted.set(true);
577 break;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800578 }
579 }
580
581 /** lifecycle event */
Makoto Onukicdc78f72016-03-21 15:47:52 -0700582 void handleUnlockUser(int userId) {
Makoto Onuki22fcc682016-05-17 14:52:19 -0700583 if (DEBUG) {
Makoto Onuki085a05c2016-08-19 11:39:29 -0700584 Slog.d(TAG, "handleUnlockUser: user=" + userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700585 }
Makoto Onukicdc78f72016-03-21 15:47:52 -0700586 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -0700587 mUnlockedUsers.put(userId, true);
Makoto Onukicdc78f72016-03-21 15:47:52 -0700588 }
Makoto Onuki085a05c2016-08-19 11:39:29 -0700589
590 // Preload the user data.
591 // Note, we don't use mHandler here but instead just start a new thread.
592 // This is because mHandler (which uses com.android.internal.os.BackgroundThread) is very
593 // busy at this point and this could take hundreds of milliseconds, which would be too
594 // late since the launcher would already have started.
595 // So we just create a new thread. This code runs rarely, so we don't use a thread pool
596 // or anything.
597 final long start = injectElapsedRealtime();
598 injectRunOnNewThread(() -> {
599 synchronized (mLock) {
600 logDurationStat(Stats.ASYNC_PRELOAD_USER_DELAY, start);
601 getUserShortcutsLocked(userId);
602 }
603 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800604 }
605
606 /** lifecycle event */
Makoto Onukicdc78f72016-03-21 15:47:52 -0700607 void handleCleanupUser(int userId) {
Makoto Onuki02f338e2016-07-29 09:40:40 -0700608 if (DEBUG) {
609 Slog.d(TAG, "handleCleanupUser: user=" + userId);
610 }
Makoto Onukicdc78f72016-03-21 15:47:52 -0700611 synchronized (mLock) {
612 unloadUserLocked(userId);
Makoto Onuki02f338e2016-07-29 09:40:40 -0700613
614 mUnlockedUsers.put(userId, false);
Makoto Onukicdc78f72016-03-21 15:47:52 -0700615 }
616 }
617
618 private void unloadUserLocked(int userId) {
619 if (DEBUG) {
620 Slog.d(TAG, "unloadUserLocked: user=" + userId);
621 }
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700622 // Save all dirty information.
623 saveDirtyInfo();
624
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800625 // Unload
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -0800626 mUsers.delete(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800627 }
628
629 /** Return the base state file name */
630 private AtomicFile getBaseStateFile() {
631 final File path = new File(injectSystemDataPath(), FILENAME_BASE_STATE);
632 path.mkdirs();
633 return new AtomicFile(path);
634 }
635
636 /**
637 * Init the instance. (load the state file, etc)
638 */
639 private void initialize() {
640 synchronized (mLock) {
Makoto Onuki4362a662016-03-08 18:59:09 -0800641 loadConfigurationLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800642 loadBaseStateLocked();
643 }
644 }
645
Makoto Onuki4362a662016-03-08 18:59:09 -0800646 /**
647 * Load the configuration from Settings.
648 */
649 private void loadConfigurationLocked() {
650 updateConfigurationLocked(injectShortcutManagerConstants());
651 }
Makoto Onuki55046222016-03-08 10:49:47 -0800652
Makoto Onuki4362a662016-03-08 18:59:09 -0800653 /**
654 * Load the configuration from Settings.
655 */
656 @VisibleForTesting
657 boolean updateConfigurationLocked(String config) {
658 boolean result = true;
659
660 final KeyValueListParser parser = new KeyValueListParser(',');
661 try {
662 parser.setString(config);
663 } catch (IllegalArgumentException e) {
664 // Failed to parse the settings string, log this and move on
665 // with defaults.
666 Slog.e(TAG, "Bad shortcut manager settings", e);
667 result = false;
668 }
669
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700670 mSaveDelayMillis = Math.max(0, (int) parser.getLong(ConfigConstants.KEY_SAVE_DELAY_MILLIS,
671 DEFAULT_SAVE_DELAY_MS));
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700672
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700673 mResetInterval = Math.max(1, parser.getLong(
Makoto Onuki4362a662016-03-08 18:59:09 -0800674 ConfigConstants.KEY_RESET_INTERVAL_SEC, DEFAULT_RESET_INTERVAL_SEC)
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700675 * 1000L);
Makoto Onuki4362a662016-03-08 18:59:09 -0800676
Makoto Onukib6d35232016-04-04 15:57:17 -0700677 mMaxUpdatesPerInterval = Math.max(0, (int) parser.getLong(
678 ConfigConstants.KEY_MAX_UPDATES_PER_INTERVAL, DEFAULT_MAX_UPDATES_PER_INTERVAL));
Makoto Onuki4362a662016-03-08 18:59:09 -0800679
Makoto Onukib5a012f2016-06-21 11:13:53 -0700680 mMaxShortcuts = Math.max(0, (int) parser.getLong(
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700681 ConfigConstants.KEY_MAX_SHORTCUTS, DEFAULT_MAX_SHORTCUTS_PER_APP));
Makoto Onuki4362a662016-03-08 18:59:09 -0800682
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700683 final int iconDimensionDp = Math.max(1, injectIsLowRamDevice()
Makoto Onuki4362a662016-03-08 18:59:09 -0800684 ? (int) parser.getLong(
Makoto Onukib08790c2016-06-23 14:05:46 -0700685 ConfigConstants.KEY_MAX_ICON_DIMENSION_DP_LOWRAM,
686 DEFAULT_MAX_ICON_DIMENSION_LOWRAM_DP)
Makoto Onuki4362a662016-03-08 18:59:09 -0800687 : (int) parser.getLong(
Makoto Onukib08790c2016-06-23 14:05:46 -0700688 ConfigConstants.KEY_MAX_ICON_DIMENSION_DP,
689 DEFAULT_MAX_ICON_DIMENSION_DP));
Makoto Onuki4362a662016-03-08 18:59:09 -0800690
691 mMaxIconDimension = injectDipToPixel(iconDimensionDp);
692
693 mIconPersistFormat = CompressFormat.valueOf(
694 parser.getString(ConfigConstants.KEY_ICON_FORMAT, DEFAULT_ICON_PERSIST_FORMAT));
695
696 mIconPersistQuality = (int) parser.getLong(
697 ConfigConstants.KEY_ICON_QUALITY,
698 DEFAULT_ICON_PERSIST_QUALITY);
699
700 return result;
701 }
702
703 @VisibleForTesting
704 String injectShortcutManagerConstants() {
705 return android.provider.Settings.Global.getString(
706 mContext.getContentResolver(),
707 android.provider.Settings.Global.SHORTCUT_MANAGER_CONSTANTS);
708 }
709
710 @VisibleForTesting
711 int injectDipToPixel(int dip) {
712 return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip,
713 mContext.getResources().getDisplayMetrics());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800714 }
715
Makoto Onuki55046222016-03-08 10:49:47 -0800716 // === Persisting ===
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800717
718 @Nullable
Makoto Onuki41066a62016-03-09 16:18:44 -0800719 static String parseStringAttribute(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800720 return parser.getAttributeValue(null, attribute);
721 }
722
Makoto Onuki0acbb142016-03-22 17:02:57 -0700723 static boolean parseBooleanAttribute(XmlPullParser parser, String attribute) {
724 return parseLongAttribute(parser, attribute) == 1;
725 }
726
Makoto Onuki41066a62016-03-09 16:18:44 -0800727 static int parseIntAttribute(XmlPullParser parser, String attribute) {
728 return (int) parseLongAttribute(parser, attribute);
729 }
730
Makoto Onukid99c6f02016-03-28 11:02:54 -0700731 static int parseIntAttribute(XmlPullParser parser, String attribute, int def) {
732 return (int) parseLongAttribute(parser, attribute, def);
733 }
734
Makoto Onuki41066a62016-03-09 16:18:44 -0800735 static long parseLongAttribute(XmlPullParser parser, String attribute) {
Makoto Onukid99c6f02016-03-28 11:02:54 -0700736 return parseLongAttribute(parser, attribute, 0);
737 }
738
739 static long parseLongAttribute(XmlPullParser parser, String attribute, long def) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800740 final String value = parseStringAttribute(parser, attribute);
741 if (TextUtils.isEmpty(value)) {
Makoto Onukid99c6f02016-03-28 11:02:54 -0700742 return def;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800743 }
744 try {
745 return Long.parseLong(value);
746 } catch (NumberFormatException e) {
747 Slog.e(TAG, "Error parsing long " + value);
Makoto Onukid99c6f02016-03-28 11:02:54 -0700748 return def;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800749 }
750 }
751
752 @Nullable
Makoto Onuki41066a62016-03-09 16:18:44 -0800753 static ComponentName parseComponentNameAttribute(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800754 final String value = parseStringAttribute(parser, attribute);
755 if (TextUtils.isEmpty(value)) {
756 return null;
757 }
758 return ComponentName.unflattenFromString(value);
759 }
760
761 @Nullable
Makoto Onuki440a1ea2016-07-20 14:21:18 -0700762 static Intent parseIntentAttributeNoDefault(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800763 final String value = parseStringAttribute(parser, attribute);
Makoto Onukib5a012f2016-06-21 11:13:53 -0700764 Intent parsed = null;
765 if (!TextUtils.isEmpty(value)) {
766 try {
767 parsed = Intent.parseUri(value, /* flags =*/ 0);
768 } catch (URISyntaxException e) {
769 Slog.e(TAG, "Error parsing intent", e);
770 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800771 }
Makoto Onuki440a1ea2016-07-20 14:21:18 -0700772 return parsed;
773 }
774
775 @Nullable
776 static Intent parseIntentAttribute(XmlPullParser parser, String attribute) {
777 Intent parsed = parseIntentAttributeNoDefault(parser, attribute);
Makoto Onukib5a012f2016-06-21 11:13:53 -0700778 if (parsed == null) {
779 // Default intent.
780 parsed = new Intent(Intent.ACTION_VIEW);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800781 }
Makoto Onukib5a012f2016-06-21 11:13:53 -0700782 return parsed;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800783 }
784
Makoto Onuki41066a62016-03-09 16:18:44 -0800785 static void writeTagValue(XmlSerializer out, String tag, String value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800786 if (TextUtils.isEmpty(value)) return;
787
788 out.startTag(null, tag);
789 out.attribute(null, ATTR_VALUE, value);
790 out.endTag(null, tag);
791 }
792
Makoto Onuki41066a62016-03-09 16:18:44 -0800793 static void writeTagValue(XmlSerializer out, String tag, long value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800794 writeTagValue(out, tag, Long.toString(value));
795 }
796
Makoto Onuki2d5b4652016-03-11 16:09:54 -0800797 static void writeTagValue(XmlSerializer out, String tag, ComponentName name) throws IOException {
798 if (name == null) return;
799 writeTagValue(out, tag, name.flattenToString());
800 }
801
Makoto Onuki41066a62016-03-09 16:18:44 -0800802 static void writeTagExtra(XmlSerializer out, String tag, PersistableBundle bundle)
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800803 throws IOException, XmlPullParserException {
804 if (bundle == null) return;
805
806 out.startTag(null, tag);
807 bundle.saveToXml(out);
808 out.endTag(null, tag);
809 }
810
Makoto Onuki22fcc682016-05-17 14:52:19 -0700811 static void writeAttr(XmlSerializer out, String name, CharSequence value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800812 if (TextUtils.isEmpty(value)) return;
813
Makoto Onuki22fcc682016-05-17 14:52:19 -0700814 out.attribute(null, name, value.toString());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800815 }
816
Makoto Onuki41066a62016-03-09 16:18:44 -0800817 static void writeAttr(XmlSerializer out, String name, long value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800818 writeAttr(out, name, String.valueOf(value));
819 }
820
Makoto Onuki0acbb142016-03-22 17:02:57 -0700821 static void writeAttr(XmlSerializer out, String name, boolean value) throws IOException {
822 if (value) {
823 writeAttr(out, name, "1");
824 }
825 }
826
Makoto Onuki41066a62016-03-09 16:18:44 -0800827 static void writeAttr(XmlSerializer out, String name, ComponentName comp) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800828 if (comp == null) return;
829 writeAttr(out, name, comp.flattenToString());
830 }
831
Makoto Onuki41066a62016-03-09 16:18:44 -0800832 static void writeAttr(XmlSerializer out, String name, Intent intent) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800833 if (intent == null) return;
834
835 writeAttr(out, name, intent.toUri(/* flags =*/ 0));
836 }
837
838 @VisibleForTesting
839 void saveBaseStateLocked() {
840 final AtomicFile file = getBaseStateFile();
841 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700842 Slog.d(TAG, "Saving to " + file.getBaseFile());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800843 }
844
845 FileOutputStream outs = null;
846 try {
847 outs = file.startWrite();
848
849 // Write to XML
850 XmlSerializer out = new FastXmlSerializer();
851 out.setOutput(outs, StandardCharsets.UTF_8.name());
852 out.startDocument(null, true);
853 out.startTag(null, TAG_ROOT);
854
855 // Body.
856 writeTagValue(out, TAG_LAST_RESET_TIME, mRawLastResetTime);
857
858 // Epilogue.
859 out.endTag(null, TAG_ROOT);
860 out.endDocument();
861
862 // Close.
863 file.finishWrite(outs);
864 } catch (IOException e) {
865 Slog.e(TAG, "Failed to write to file " + file.getBaseFile(), e);
866 file.failWrite(outs);
867 }
868 }
869
870 private void loadBaseStateLocked() {
871 mRawLastResetTime = 0;
872
873 final AtomicFile file = getBaseStateFile();
874 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700875 Slog.d(TAG, "Loading from " + file.getBaseFile());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800876 }
877 try (FileInputStream in = file.openRead()) {
878 XmlPullParser parser = Xml.newPullParser();
879 parser.setInput(in, StandardCharsets.UTF_8.name());
880
881 int type;
882 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
883 if (type != XmlPullParser.START_TAG) {
884 continue;
885 }
886 final int depth = parser.getDepth();
887 // Check the root tag
888 final String tag = parser.getName();
889 if (depth == 1) {
890 if (!TAG_ROOT.equals(tag)) {
891 Slog.e(TAG, "Invalid root tag: " + tag);
892 return;
893 }
894 continue;
895 }
896 // Assume depth == 2
897 switch (tag) {
898 case TAG_LAST_RESET_TIME:
899 mRawLastResetTime = parseLongAttribute(parser, ATTR_VALUE);
900 break;
901 default:
902 Slog.e(TAG, "Invalid tag: " + tag);
903 break;
904 }
905 }
906 } catch (FileNotFoundException e) {
907 // Use the default
Makoto Onukib08790c2016-06-23 14:05:46 -0700908 } catch (IOException | XmlPullParserException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800909 Slog.e(TAG, "Failed to read file " + file.getBaseFile(), e);
910
911 mRawLastResetTime = 0;
912 }
913 // Adjust the last reset time.
914 getLastResetTimeLocked();
915 }
916
Makoto Onuki0eed4412016-07-21 11:21:59 -0700917 @VisibleForTesting
918 final File getUserFile(@UserIdInt int userId) {
919 return new File(injectUserDataPath(userId), FILENAME_USER_PACKAGES);
920 }
921
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800922 private void saveUserLocked(@UserIdInt int userId) {
Makoto Onuki0eed4412016-07-21 11:21:59 -0700923 final File path = getUserFile(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800924 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700925 Slog.d(TAG, "Saving to " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800926 }
Makoto Onuki0eed4412016-07-21 11:21:59 -0700927 path.getParentFile().mkdirs();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800928 final AtomicFile file = new AtomicFile(path);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700929 FileOutputStream os = null;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800930 try {
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700931 os = file.startWrite();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800932
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700933 saveUserInternalLocked(userId, os, /* forBackup= */ false);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800934
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700935 file.finishWrite(os);
Makoto Onuki1e173232016-08-10 10:47:13 -0700936
937 // Remove all dangling bitmap files.
938 cleanupDanglingBitmapDirectoriesLocked(userId);
Makoto Onukib08790c2016-06-23 14:05:46 -0700939 } catch (XmlPullParserException | IOException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800940 Slog.e(TAG, "Failed to write to file " + file.getBaseFile(), e);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700941 file.failWrite(os);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800942 }
943 }
944
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700945 private void saveUserInternalLocked(@UserIdInt int userId, OutputStream os,
946 boolean forBackup) throws IOException, XmlPullParserException {
947
948 final BufferedOutputStream bos = new BufferedOutputStream(os);
949
950 // Write to XML
951 XmlSerializer out = new FastXmlSerializer();
952 out.setOutput(bos, StandardCharsets.UTF_8.name());
953 out.startDocument(null, true);
954
Makoto Onukic51b2872016-05-04 15:24:50 -0700955 getUserShortcutsLocked(userId).saveToXml(out, forBackup);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700956
957 out.endDocument();
958
959 bos.flush();
960 os.flush();
961 }
962
Makoto Onuki41066a62016-03-09 16:18:44 -0800963 static IOException throwForInvalidTag(int depth, String tag) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800964 throw new IOException(String.format("Invalid tag '%s' found at depth %d", tag, depth));
965 }
966
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700967 static void warnForInvalidTag(int depth, String tag) throws IOException {
968 Slog.w(TAG, String.format("Invalid tag '%s' found at depth %d", tag, depth));
969 }
970
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800971 @Nullable
Makoto Onuki31459242016-03-22 11:12:18 -0700972 private ShortcutUser loadUserLocked(@UserIdInt int userId) {
Makoto Onuki0eed4412016-07-21 11:21:59 -0700973 final File path = getUserFile(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800974 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700975 Slog.d(TAG, "Loading from " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800976 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800977 final AtomicFile file = new AtomicFile(path);
978
979 final FileInputStream in;
980 try {
981 in = file.openRead();
982 } catch (FileNotFoundException e) {
983 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700984 Slog.d(TAG, "Not found " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800985 }
986 return null;
987 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800988 try {
Makoto Onukib08790c2016-06-23 14:05:46 -0700989 final ShortcutUser ret = loadUserInternal(userId, in, /* forBackup= */ false);
Makoto Onuki6c1dbd52016-05-02 15:19:32 -0700990 return ret;
Makoto Onukifc4cf2d2016-08-24 11:10:26 -0700991 } catch (IOException | XmlPullParserException | InvalidFileFormatException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800992 Slog.e(TAG, "Failed to read file " + file.getBaseFile(), e);
993 return null;
994 } finally {
995 IoUtils.closeQuietly(in);
996 }
997 }
998
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700999 private ShortcutUser loadUserInternal(@UserIdInt int userId, InputStream is,
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07001000 boolean fromBackup) throws XmlPullParserException, IOException,
1001 InvalidFileFormatException {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001002
1003 final BufferedInputStream bis = new BufferedInputStream(is);
1004
1005 ShortcutUser ret = null;
1006 XmlPullParser parser = Xml.newPullParser();
1007 parser.setInput(bis, StandardCharsets.UTF_8.name());
1008
1009 int type;
1010 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1011 if (type != XmlPullParser.START_TAG) {
1012 continue;
1013 }
1014 final int depth = parser.getDepth();
1015
1016 final String tag = parser.getName();
1017 if (DEBUG_LOAD) {
1018 Slog.d(TAG, String.format("depth=%d type=%d name=%s",
1019 depth, type, tag));
1020 }
1021 if ((depth == 1) && ShortcutUser.TAG_ROOT.equals(tag)) {
1022 ret = ShortcutUser.loadFromXml(this, parser, userId, fromBackup);
1023 continue;
1024 }
1025 throwForInvalidTag(depth, tag);
1026 }
1027 return ret;
1028 }
1029
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001030 private void scheduleSaveBaseState() {
Makoto Onuki0acbb142016-03-22 17:02:57 -07001031 scheduleSaveInner(UserHandle.USER_NULL); // Special case -- use USER_NULL for base state.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001032 }
1033
Makoto Onuki2d5b4652016-03-11 16:09:54 -08001034 void scheduleSaveUser(@UserIdInt int userId) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07001035 scheduleSaveInner(userId);
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001036 }
1037
1038 // In order to re-schedule, we need to reuse the same instance, so keep it in final.
1039 private final Runnable mSaveDirtyInfoRunner = this::saveDirtyInfo;
1040
Makoto Onuki0acbb142016-03-22 17:02:57 -07001041 private void scheduleSaveInner(@UserIdInt int userId) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001042 if (DEBUG) {
1043 Slog.d(TAG, "Scheduling to save for " + userId);
1044 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001045 synchronized (mLock) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001046 if (!mDirtyUserIds.contains(userId)) {
1047 mDirtyUserIds.add(userId);
1048 }
1049 }
1050 // If already scheduled, remove that and re-schedule in N seconds.
1051 mHandler.removeCallbacks(mSaveDirtyInfoRunner);
1052 mHandler.postDelayed(mSaveDirtyInfoRunner, mSaveDelayMillis);
1053 }
1054
1055 @VisibleForTesting
1056 void saveDirtyInfo() {
1057 if (DEBUG) {
1058 Slog.d(TAG, "saveDirtyInfo");
1059 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001060 try {
1061 synchronized (mLock) {
1062 for (int i = mDirtyUserIds.size() - 1; i >= 0; i--) {
1063 final int userId = mDirtyUserIds.get(i);
1064 if (userId == UserHandle.USER_NULL) { // USER_NULL for base state.
1065 saveBaseStateLocked();
1066 } else {
1067 saveUserLocked(userId);
1068 }
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001069 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001070 mDirtyUserIds.clear();
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001071 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001072 } catch (Exception e) {
1073 wtf("Exception in saveDirtyInfo", e);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001074 }
1075 }
1076
1077 /** Return the last reset time. */
1078 long getLastResetTimeLocked() {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001079 updateTimesLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001080 return mRawLastResetTime;
1081 }
1082
1083 /** Return the next reset time. */
1084 long getNextResetTimeLocked() {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001085 updateTimesLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001086 return mRawLastResetTime + mResetInterval;
1087 }
1088
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001089 static boolean isClockValid(long time) {
1090 return time >= 1420070400; // Thu, 01 Jan 2015 00:00:00 GMT
1091 }
1092
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001093 /**
1094 * Update the last reset time.
1095 */
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001096 private void updateTimesLocked() {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001097
1098 final long now = injectCurrentTimeMillis();
1099
1100 final long prevLastResetTime = mRawLastResetTime;
1101
1102 if (mRawLastResetTime == 0) { // first launch.
1103 // TODO Randomize??
1104 mRawLastResetTime = now;
1105 } else if (now < mRawLastResetTime) {
1106 // Clock rewound.
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001107 if (isClockValid(now)) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001108 Slog.w(TAG, "Clock rewound");
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001109 // TODO Randomize??
1110 mRawLastResetTime = now;
1111 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001112 } else {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001113 if ((mRawLastResetTime + mResetInterval) <= now) {
1114 final long offset = mRawLastResetTime % mResetInterval;
1115 mRawLastResetTime = ((now / mResetInterval) * mResetInterval) + offset;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001116 }
1117 }
1118 if (prevLastResetTime != mRawLastResetTime) {
1119 scheduleSaveBaseState();
1120 }
1121 }
1122
Makoto Onuki1e173232016-08-10 10:47:13 -07001123 // Requires mLock held, but "Locked" prefix would look weired so we just say "L".
Makoto Onuki02f338e2016-07-29 09:40:40 -07001124 protected boolean isUserUnlockedL(@UserIdInt int userId) {
Makoto Onuki1e173232016-08-10 10:47:13 -07001125 // First, check the local copy.
1126 if (mUnlockedUsers.get(userId)) {
1127 return true;
1128 }
1129 // If the local copy says the user is locked, check with AM for the actual state, since
1130 // the user might just have been unlocked.
1131 // Note we just don't use isUserUnlockingOrUnlocked() here, because it'll return false
1132 // when the user is STOPPING, which we still want to consider as "unlocked".
1133 final long token = injectClearCallingIdentity();
1134 try {
1135 return mUserManager.isUserUnlockingOrUnlocked(userId);
1136 } finally {
1137 injectRestoreCallingIdentity(token);
1138 }
Makoto Onuki9c850012016-07-26 15:50:50 -07001139 }
1140
Makoto Onuki02f338e2016-07-29 09:40:40 -07001141 // Requires mLock held, but "Locked" prefix would look weired so we jsut say "L".
1142 void throwIfUserLockedL(@UserIdInt int userId) {
1143 if (!isUserUnlockedL(userId)) {
Makoto Onuki9c850012016-07-26 15:50:50 -07001144 throw new IllegalStateException("User " + userId + " is locked or not running");
1145 }
1146 }
1147
Makoto Onukicdc78f72016-03-21 15:47:52 -07001148 @GuardedBy("mLock")
1149 @NonNull
Makoto Onuki2e210c42016-03-30 08:30:36 -07001150 private boolean isUserLoadedLocked(@UserIdInt int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07001151 return mUsers.get(userId) != null;
1152 }
1153
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001154 /** Return the per-user state. */
1155 @GuardedBy("mLock")
1156 @NonNull
Makoto Onuki31459242016-03-22 11:12:18 -07001157 ShortcutUser getUserShortcutsLocked(@UserIdInt int userId) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001158 if (!isUserUnlockedL(userId)) {
Makoto Onuki9c850012016-07-26 15:50:50 -07001159 wtf("User still locked");
Makoto Onuki9c850012016-07-26 15:50:50 -07001160 }
1161
Makoto Onuki31459242016-03-22 11:12:18 -07001162 ShortcutUser userPackages = mUsers.get(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001163 if (userPackages == null) {
1164 userPackages = loadUserLocked(userId);
1165 if (userPackages == null) {
Makoto Onukic51b2872016-05-04 15:24:50 -07001166 userPackages = new ShortcutUser(this, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001167 }
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08001168 mUsers.put(userId, userPackages);
Makoto Onuki085a05c2016-08-19 11:39:29 -07001169
1170 // Also when a user's data is first accessed, scan all packages.
1171 checkPackageChanges(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001172 }
1173 return userPackages;
1174 }
1175
Makoto Onuki2e210c42016-03-30 08:30:36 -07001176 void forEachLoadedUserLocked(@NonNull Consumer<ShortcutUser> c) {
1177 for (int i = mUsers.size() - 1; i >= 0; i--) {
1178 c.accept(mUsers.valueAt(i));
1179 }
1180 }
1181
Makoto Onukic8c33292016-09-12 16:36:59 -07001182 /**
1183 * Return the per-user per-package state. If the caller is a publisher, use
1184 * {@link #getPackageShortcutsForPublisherLocked} instead.
1185 */
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001186 @GuardedBy("mLock")
1187 @NonNull
Makoto Onuki31459242016-03-22 11:12:18 -07001188 ShortcutPackage getPackageShortcutsLocked(
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001189 @NonNull String packageName, @UserIdInt int userId) {
Makoto Onukic51b2872016-05-04 15:24:50 -07001190 return getUserShortcutsLocked(userId).getPackageShortcuts(packageName);
Makoto Onukide667372016-03-15 14:29:20 -07001191 }
1192
Makoto Onukic8c33292016-09-12 16:36:59 -07001193 /** Return the per-user per-package state. Use this when the caller is a publisher. */
1194 @GuardedBy("mLock")
1195 @NonNull
1196 ShortcutPackage getPackageShortcutsForPublisherLocked(
1197 @NonNull String packageName, @UserIdInt int userId) {
1198 final ShortcutPackage ret = getUserShortcutsLocked(userId).getPackageShortcuts(packageName);
1199 ret.getUser().onCalledByPublisher(packageName);
1200 return ret;
1201 }
1202
Makoto Onukide667372016-03-15 14:29:20 -07001203 @GuardedBy("mLock")
1204 @NonNull
Makoto Onuki2e210c42016-03-30 08:30:36 -07001205 ShortcutLauncher getLauncherShortcutsLocked(
1206 @NonNull String packageName, @UserIdInt int ownerUserId,
1207 @UserIdInt int launcherUserId) {
1208 return getUserShortcutsLocked(ownerUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07001209 .getLauncherShortcuts(packageName, launcherUserId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001210 }
1211
1212 // === Caller validation ===
1213
Makoto Onuki55046222016-03-08 10:49:47 -08001214 void removeIcon(@UserIdInt int userId, ShortcutInfo shortcut) {
Makoto Onuki1e173232016-08-10 10:47:13 -07001215 // Do not remove the actual bitmap file yet, because if the device crashes before saving
1216 // he XML we'd lose the icon. We just remove all dangling files after saving the XML.
Makoto Onukidd097812016-06-29 13:10:09 -07001217 shortcut.setIconResourceId(0);
1218 shortcut.setIconResName(null);
1219 shortcut.clearFlags(ShortcutInfo.FLAG_HAS_ICON_FILE | ShortcutInfo.FLAG_HAS_ICON_RES);
Makoto Onuki55046222016-03-08 10:49:47 -08001220 }
1221
Makoto Onuki0033b2a2016-04-14 17:19:16 -07001222 public void cleanupBitmapsForPackage(@UserIdInt int userId, String packageName) {
1223 final File packagePath = new File(getUserBitmapFilePath(userId), packageName);
1224 if (!packagePath.isDirectory()) {
1225 return;
1226 }
1227 if (!(FileUtils.deleteContents(packagePath) && packagePath.delete())) {
1228 Slog.w(TAG, "Unable to remove directory " + packagePath);
1229 }
1230 }
1231
Makoto Onuki1e173232016-08-10 10:47:13 -07001232 private void cleanupDanglingBitmapDirectoriesLocked(@UserIdInt int userId) {
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001233 if (DEBUG) {
1234 Slog.d(TAG, "cleanupDanglingBitmaps: userId=" + userId);
1235 }
1236 final long start = injectElapsedRealtime();
1237
Makoto Onuki1e173232016-08-10 10:47:13 -07001238 final ShortcutUser user = getUserShortcutsLocked(userId);
1239
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001240 final File bitmapDir = getUserBitmapFilePath(userId);
1241 final File[] children = bitmapDir.listFiles();
1242 if (children == null) {
1243 return;
1244 }
1245 for (File child : children) {
1246 if (!child.isDirectory()) {
1247 continue;
1248 }
1249 final String packageName = child.getName();
1250 if (DEBUG) {
1251 Slog.d(TAG, "cleanupDanglingBitmaps: Found directory=" + packageName);
1252 }
1253 if (!user.hasPackage(packageName)) {
1254 if (DEBUG) {
1255 Slog.d(TAG, "Removing dangling bitmap directory: " + packageName);
1256 }
1257 cleanupBitmapsForPackage(userId, packageName);
1258 } else {
1259 cleanupDanglingBitmapFilesLocked(userId, user, packageName, child);
1260 }
1261 }
1262 logDurationStat(Stats.CLEANUP_DANGLING_BITMAPS, start);
1263 }
1264
1265 private void cleanupDanglingBitmapFilesLocked(@UserIdInt int userId, @NonNull ShortcutUser user,
1266 @NonNull String packageName, @NonNull File path) {
1267 final ArraySet<String> usedFiles =
Makoto Onukic51b2872016-05-04 15:24:50 -07001268 user.getPackageShortcuts(packageName).getUsedBitmapFiles();
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001269
1270 for (File child : path.listFiles()) {
1271 if (!child.isFile()) {
1272 continue;
1273 }
1274 final String name = child.getName();
1275 if (!usedFiles.contains(name)) {
1276 if (DEBUG) {
1277 Slog.d(TAG, "Removing dangling bitmap file: " + child.getAbsolutePath());
1278 }
1279 child.delete();
1280 }
1281 }
1282 }
1283
Makoto Onuki55046222016-03-08 10:49:47 -08001284 @VisibleForTesting
1285 static class FileOutputStreamWithPath extends FileOutputStream {
1286 private final File mFile;
1287
1288 public FileOutputStreamWithPath(File file) throws FileNotFoundException {
1289 super(file);
1290 mFile = file;
1291 }
1292
1293 public File getFile() {
1294 return mFile;
1295 }
1296 }
1297
1298 /**
1299 * Build the cached bitmap filename for a shortcut icon.
1300 *
1301 * The filename will be based on the ID, except certain characters will be escaped.
1302 */
1303 @VisibleForTesting
1304 FileOutputStreamWithPath openIconFileForWrite(@UserIdInt int userId, ShortcutInfo shortcut)
1305 throws IOException {
1306 final File packagePath = new File(getUserBitmapFilePath(userId),
Makoto Onuki22fcc682016-05-17 14:52:19 -07001307 shortcut.getPackage());
Makoto Onuki55046222016-03-08 10:49:47 -08001308 if (!packagePath.isDirectory()) {
1309 packagePath.mkdirs();
1310 if (!packagePath.isDirectory()) {
1311 throw new IOException("Unable to create directory " + packagePath);
1312 }
1313 SELinux.restorecon(packagePath);
1314 }
1315
1316 final String baseName = String.valueOf(injectCurrentTimeMillis());
Makoto Onukib08790c2016-06-23 14:05:46 -07001317 for (int suffix = 0; ; suffix++) {
Makoto Onuki55046222016-03-08 10:49:47 -08001318 final String filename = (suffix == 0 ? baseName : baseName + "_" + suffix) + ".png";
1319 final File file = new File(packagePath, filename);
1320 if (!file.exists()) {
1321 if (DEBUG) {
1322 Slog.d(TAG, "Saving icon to " + file.getAbsolutePath());
1323 }
1324 return new FileOutputStreamWithPath(file);
1325 }
1326 }
1327 }
1328
1329 void saveIconAndFixUpShortcut(@UserIdInt int userId, ShortcutInfo shortcut) {
1330 if (shortcut.hasIconFile() || shortcut.hasIconResource()) {
1331 return;
1332 }
1333
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001334 final long token = injectClearCallingIdentity();
Makoto Onuki55046222016-03-08 10:49:47 -08001335 try {
1336 // Clear icon info on the shortcut.
Makoto Onukidd097812016-06-29 13:10:09 -07001337 removeIcon(userId, shortcut);
Makoto Onuki55046222016-03-08 10:49:47 -08001338
1339 final Icon icon = shortcut.getIcon();
1340 if (icon == null) {
1341 return; // has no icon
1342 }
1343
Makoto Onukiabe84422016-04-07 09:41:19 -07001344 Bitmap bitmap;
Makoto Onuki55046222016-03-08 10:49:47 -08001345 try {
1346 switch (icon.getType()) {
1347 case Icon.TYPE_RESOURCE: {
1348 injectValidateIconResPackage(shortcut, icon);
1349
1350 shortcut.setIconResourceId(icon.getResId());
1351 shortcut.addFlags(ShortcutInfo.FLAG_HAS_ICON_RES);
1352 return;
1353 }
1354 case Icon.TYPE_BITMAP: {
Makoto Onukiabe84422016-04-07 09:41:19 -07001355 bitmap = icon.getBitmap(); // Don't recycle in this case.
Makoto Onuki55046222016-03-08 10:49:47 -08001356 break;
1357 }
Makoto Onuki55046222016-03-08 10:49:47 -08001358 default:
1359 // This shouldn't happen because we've already validated the icon, but
1360 // just in case.
1361 throw ShortcutInfo.getInvalidIconException();
1362 }
1363 if (bitmap == null) {
1364 Slog.e(TAG, "Null bitmap detected");
1365 return;
1366 }
1367 // Shrink and write to the file.
1368 File path = null;
1369 try {
1370 final FileOutputStreamWithPath out = openIconFileForWrite(userId, shortcut);
1371 try {
1372 path = out.getFile();
1373
Makoto Onukiabe84422016-04-07 09:41:19 -07001374 Bitmap shrunk = shrinkBitmap(bitmap, mMaxIconDimension);
1375 try {
1376 shrunk.compress(mIconPersistFormat, mIconPersistQuality, out);
1377 } finally {
1378 if (bitmap != shrunk) {
1379 shrunk.recycle();
1380 }
1381 }
Makoto Onuki55046222016-03-08 10:49:47 -08001382
1383 shortcut.setBitmapPath(out.getFile().getAbsolutePath());
1384 shortcut.addFlags(ShortcutInfo.FLAG_HAS_ICON_FILE);
1385 } finally {
1386 IoUtils.closeQuietly(out);
1387 }
Makoto Onukib08790c2016-06-23 14:05:46 -07001388 } catch (IOException | RuntimeException e) {
Makoto Onuki55046222016-03-08 10:49:47 -08001389 // STOPSHIP Change wtf to e
1390 Slog.wtf(ShortcutService.TAG, "Unable to write bitmap to file", e);
1391 if (path != null && path.exists()) {
1392 path.delete();
1393 }
1394 }
1395 } finally {
Makoto Onuki55046222016-03-08 10:49:47 -08001396 // Once saved, we won't use the original icon information, so null it out.
1397 shortcut.clearIcon();
1398 }
1399 } finally {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001400 injectRestoreCallingIdentity(token);
Makoto Onuki55046222016-03-08 10:49:47 -08001401 }
1402 }
1403
1404 // Unfortunately we can't do this check in unit tests because we fake creator package names,
1405 // so override in unit tests.
1406 // TODO CTS this case.
1407 void injectValidateIconResPackage(ShortcutInfo shortcut, Icon icon) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07001408 if (!shortcut.getPackage().equals(icon.getResPackage())) {
Makoto Onuki55046222016-03-08 10:49:47 -08001409 throw new IllegalArgumentException(
1410 "Icon resource must reside in shortcut owner package");
1411 }
1412 }
1413
1414 @VisibleForTesting
1415 static Bitmap shrinkBitmap(Bitmap in, int maxSize) {
1416 // Original width/height.
1417 final int ow = in.getWidth();
1418 final int oh = in.getHeight();
1419 if ((ow <= maxSize) && (oh <= maxSize)) {
1420 if (DEBUG) {
1421 Slog.d(TAG, String.format("Icon size %dx%d, no need to shrink", ow, oh));
1422 }
1423 return in;
1424 }
1425 final int longerDimension = Math.max(ow, oh);
1426
1427 // New width and height.
1428 final int nw = ow * maxSize / longerDimension;
1429 final int nh = oh * maxSize / longerDimension;
1430 if (DEBUG) {
1431 Slog.d(TAG, String.format("Icon size %dx%d, shrinking to %dx%d",
1432 ow, oh, nw, nh));
1433 }
1434
1435 final Bitmap scaledBitmap = Bitmap.createBitmap(nw, nh, Bitmap.Config.ARGB_8888);
1436 final Canvas c = new Canvas(scaledBitmap);
1437
1438 final RectF dst = new RectF(0, 0, nw, nh);
1439
1440 c.drawBitmap(in, /*src=*/ null, dst, /* paint =*/ null);
1441
Makoto Onuki55046222016-03-08 10:49:47 -08001442 return scaledBitmap;
1443 }
1444
Makoto Onuki157b1622016-06-02 16:13:10 -07001445 /**
1446 * For a shortcut, update all resource names from resource IDs, and also update all
1447 * resource-based strings.
1448 */
1449 void fixUpShortcutResourceNamesAndValues(ShortcutInfo si) {
1450 final Resources publisherRes = injectGetResourcesForApplicationAsUser(
1451 si.getPackage(), si.getUserId());
1452 if (publisherRes != null) {
1453 final long start = injectElapsedRealtime();
1454 try {
1455 si.lookupAndFillInResourceNames(publisherRes);
1456 } finally {
1457 logDurationStat(Stats.RESOURCE_NAME_LOOKUP, start);
1458 }
1459 si.resolveResourceStrings(publisherRes);
1460 }
1461 }
1462
Makoto Onuki55046222016-03-08 10:49:47 -08001463 // === Caller validation ===
1464
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001465 private boolean isCallerSystem() {
1466 final int callingUid = injectBinderCallingUid();
Makoto Onukib08790c2016-06-23 14:05:46 -07001467 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001468 }
1469
1470 private boolean isCallerShell() {
1471 final int callingUid = injectBinderCallingUid();
1472 return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
1473 }
1474
1475 private void enforceSystemOrShell() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001476 if (!(isCallerSystem() || isCallerShell())) {
1477 throw new SecurityException("Caller must be system or shell");
1478 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001479 }
1480
1481 private void enforceShell() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001482 if (!isCallerShell()) {
1483 throw new SecurityException("Caller must be shell");
1484 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001485 }
1486
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001487 private void enforceSystem() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001488 if (!isCallerSystem()) {
1489 throw new SecurityException("Caller must be system");
1490 }
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001491 }
1492
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001493 private void enforceResetThrottlingPermission() {
1494 if (isCallerSystem()) {
1495 return;
1496 }
Makoto Onuki76269922016-07-15 14:58:54 -07001497 enforceCallingOrSelfPermission(
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001498 android.Manifest.permission.RESET_SHORTCUT_MANAGER_THROTTLING, null);
1499 }
1500
Makoto Onuki76269922016-07-15 14:58:54 -07001501 private void enforceCallingOrSelfPermission(
1502 @NonNull String permission, @Nullable String message) {
1503 if (isCallerSystem()) {
1504 return;
1505 }
1506 injectEnforceCallingPermission(permission, message);
1507 }
1508
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001509 /**
1510 * Somehow overriding ServiceContext.enforceCallingPermission() in the unit tests would confuse
1511 * mockito. So instead we extracted it here and override it in the tests.
1512 */
1513 @VisibleForTesting
1514 void injectEnforceCallingPermission(
1515 @NonNull String permission, @Nullable String message) {
1516 mContext.enforceCallingPermission(permission, message);
1517 }
1518
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001519 private void verifyCaller(@NonNull String packageName, @UserIdInt int userId) {
1520 Preconditions.checkStringNotEmpty(packageName, "packageName");
1521
1522 if (isCallerSystem()) {
1523 return; // no check
1524 }
1525
1526 final int callingUid = injectBinderCallingUid();
1527
1528 // Otherwise, make sure the arguments are valid.
1529 if (UserHandle.getUserId(callingUid) != userId) {
1530 throw new SecurityException("Invalid user-ID");
1531 }
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08001532 if (injectGetPackageUid(packageName, userId) != callingUid) {
1533 throw new SecurityException("Calling package name mismatch");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001534 }
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08001535 Preconditions.checkState(!isEphemeralApp(packageName, userId),
1536 "Ephemeral apps can't use ShortcutManager");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001537 }
1538
Makoto Onuki157b1622016-06-02 16:13:10 -07001539 // Overridden in unit tests to execute r synchronously.
1540 void injectPostToHandler(Runnable r) {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001541 mHandler.post(r);
1542 }
1543
Makoto Onuki085a05c2016-08-19 11:39:29 -07001544 void injectRunOnNewThread(Runnable r) {
1545 new Thread(r).start();
1546 }
1547
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001548 /**
Makoto Onuki7001a612016-05-27 13:24:28 -07001549 * @throws IllegalArgumentException if {@code numShortcuts} is bigger than
Makoto Onukib08790c2016-06-23 14:05:46 -07001550 * {@link #getMaxActivityShortcuts()}.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001551 */
Makoto Onuki7001a612016-05-27 13:24:28 -07001552 void enforceMaxActivityShortcuts(int numShortcuts) {
Makoto Onukib5a012f2016-06-21 11:13:53 -07001553 if (numShortcuts > mMaxShortcuts) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001554 throw new IllegalArgumentException("Max number of dynamic shortcuts exceeded");
1555 }
1556 }
1557
1558 /**
Makoto Onuki7001a612016-05-27 13:24:28 -07001559 * Return the max number of dynamic + manifest shortcuts for each launcher icon.
1560 */
1561 int getMaxActivityShortcuts() {
Makoto Onukib5a012f2016-06-21 11:13:53 -07001562 return mMaxShortcuts;
Makoto Onuki7001a612016-05-27 13:24:28 -07001563 }
1564
1565 /**
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001566 * - Sends a notification to LauncherApps
1567 * - Write to file
1568 */
Makoto Onuki39686e82016-04-13 18:03:00 -07001569 void packageShortcutsChanged(@NonNull String packageName, @UserIdInt int userId) {
1570 if (DEBUG) {
1571 Slog.d(TAG, String.format(
1572 "Shortcut changes: package=%s, user=%d", packageName, userId));
1573 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001574 notifyListeners(packageName, userId);
1575 scheduleSaveUser(userId);
1576 }
1577
1578 private void notifyListeners(@NonNull String packageName, @UserIdInt int userId) {
Makoto Onuki157b1622016-06-02 16:13:10 -07001579 injectPostToHandler(() -> {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001580 try {
1581 final ArrayList<ShortcutChangeListener> copy;
1582 synchronized (mLock) {
1583 if (!isUserUnlockedL(userId)) {
1584 return;
1585 }
1586
1587 copy = new ArrayList<>(mListeners);
1588 }
1589 // Note onShortcutChanged() needs to be called with the system service permissions.
1590 for (int i = copy.size() - 1; i >= 0; i--) {
1591 copy.get(i).onShortcutChanged(packageName, userId);
1592 }
1593 } catch (Exception ignore) {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001594 }
1595 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001596 }
1597
1598 /**
1599 * Clean up / validate an incoming shortcut.
1600 * - Make sure all mandatory fields are set.
1601 * - Make sure the intent's extras are persistable, and them to set
Makoto Onuki0eed4412016-07-21 11:21:59 -07001602 * {@link ShortcutInfo#mIntentPersistableExtrases}. Also clear its extras.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001603 * - Clear flags.
1604 */
Makoto Onuki2d895c32016-12-02 15:48:40 -08001605 private void fixUpIncomingShortcutInfo(@NonNull ShortcutInfo shortcut, boolean forUpdate,
1606 boolean forPinRequest) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001607 Preconditions.checkNotNull(shortcut, "Null shortcut detected");
Makoto Onuki255461f2017-01-10 11:47:25 -08001608 if (shortcut.getActivity() != null) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001609 Preconditions.checkState(
Makoto Onuki22fcc682016-05-17 14:52:19 -07001610 shortcut.getPackage().equals(shortcut.getActivity().getPackageName()),
Makoto Onukib08790c2016-06-23 14:05:46 -07001611 "Cannot publish shortcut: activity " + shortcut.getActivity() + " does not"
1612 + " belong to package " + shortcut.getPackage());
Makoto Onuki13260b6ff2016-07-13 18:03:13 -07001613 Preconditions.checkState(
1614 injectIsMainActivity(shortcut.getActivity(), shortcut.getUserId()),
1615 "Cannot publish shortcut: activity " + shortcut.getActivity() + " is not"
1616 + " main activity");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001617 }
1618
Makoto Onuki55046222016-03-08 10:49:47 -08001619 if (!forUpdate) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08001620 shortcut.enforceMandatoryFields(/* forPinned= */ forPinRequest);
1621 if (!forPinRequest) {
Makoto Onuki255461f2017-01-10 11:47:25 -08001622 Preconditions.checkState(shortcut.getActivity() != null,
1623 "Cannot publish shortcut: target activity is not set");
Makoto Onuki2d895c32016-12-02 15:48:40 -08001624 }
Makoto Onuki55046222016-03-08 10:49:47 -08001625 }
1626 if (shortcut.getIcon() != null) {
1627 ShortcutInfo.validateIcon(shortcut.getIcon());
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001628 }
1629
Makoto Onukide667372016-03-15 14:29:20 -07001630 shortcut.replaceFlags(0);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001631 }
1632
Makoto Onuki2d895c32016-12-02 15:48:40 -08001633 private void fixUpIncomingShortcutInfo(@NonNull ShortcutInfo shortcut, boolean forUpdate) {
1634 fixUpIncomingShortcutInfo(shortcut, forUpdate, /*forPinRequest=*/ false);
1635 }
1636
1637 public void validateShortcutForPinRequest(@NonNull ShortcutInfo shortcut) {
1638 fixUpIncomingShortcutInfo(shortcut, /* forUpdate= */ false, /*forPinRequest=*/ true);
1639 }
1640
Makoto Onukib08790c2016-06-23 14:05:46 -07001641 /**
1642 * When a shortcut has no target activity, set the default one from the package.
1643 */
1644 private void fillInDefaultActivity(List<ShortcutInfo> shortcuts) {
Makoto Onukib08790c2016-06-23 14:05:46 -07001645 ComponentName defaultActivity = null;
1646 for (int i = shortcuts.size() - 1; i >= 0; i--) {
1647 final ShortcutInfo si = shortcuts.get(i);
1648 if (si.getActivity() == null) {
1649 if (defaultActivity == null) {
1650 defaultActivity = injectGetDefaultMainActivity(
1651 si.getPackage(), si.getUserId());
1652 Preconditions.checkState(defaultActivity != null,
1653 "Launcher activity not found for package " + si.getPackage());
1654 }
1655 si.setActivity(defaultActivity);
1656 }
1657 }
1658 }
1659
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001660 private void assignImplicitRanks(List<ShortcutInfo> shortcuts) {
1661 for (int i = shortcuts.size() - 1; i >= 0; i--) {
1662 shortcuts.get(i).setImplicitRank(i);
1663 }
1664 }
1665
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001666 // === APIs ===
1667
1668 @Override
1669 public boolean setDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1670 @UserIdInt int userId) {
1671 verifyCaller(packageName, userId);
1672
1673 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
1674 final int size = newShortcuts.size();
1675
1676 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001677 throwIfUserLockedL(userId);
1678
Makoto Onukic8c33292016-09-12 16:36:59 -07001679 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001680
Makoto Onuki22fcc682016-05-17 14:52:19 -07001681 ps.ensureImmutableShortcutsNotIncluded(newShortcuts);
1682
Makoto Onukib08790c2016-06-23 14:05:46 -07001683 fillInDefaultActivity(newShortcuts);
1684
Makoto Onuki7001a612016-05-27 13:24:28 -07001685 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_SET);
1686
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001687 // Throttling.
Makoto Onukic51b2872016-05-04 15:24:50 -07001688 if (!ps.tryApiCall()) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001689 return false;
1690 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001691
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001692 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1693 ps.clearAllImplicitRanks();
1694 assignImplicitRanks(newShortcuts);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001695
Makoto Onukidf6da042016-06-16 09:51:40 -07001696 for (int i = 0; i < size; i++) {
1697 fixUpIncomingShortcutInfo(newShortcuts.get(i), /* forUpdate= */ false);
1698 }
1699
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001700 // First, remove all un-pinned; dynamic shortcuts
Makoto Onukic51b2872016-05-04 15:24:50 -07001701 ps.deleteAllDynamicShortcuts();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001702
1703 // Then, add/update all. We need to make sure to take over "pinned" flag.
1704 for (int i = 0; i < size; i++) {
1705 final ShortcutInfo newShortcut = newShortcuts.get(i);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001706 ps.addOrUpdateDynamicShortcut(newShortcut);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001707 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001708
1709 // Lastly, adjust the ranks.
1710 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001711 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001712 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001713
1714 verifyStates();
1715
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001716 return true;
1717 }
1718
1719 @Override
1720 public boolean updateShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1721 @UserIdInt int userId) {
1722 verifyCaller(packageName, userId);
1723
1724 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
Makoto Onuki55046222016-03-08 10:49:47 -08001725 final int size = newShortcuts.size();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001726
1727 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001728 throwIfUserLockedL(userId);
1729
Makoto Onukic8c33292016-09-12 16:36:59 -07001730 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001731
Makoto Onuki22fcc682016-05-17 14:52:19 -07001732 ps.ensureImmutableShortcutsNotIncluded(newShortcuts);
1733
Makoto Onukib08790c2016-06-23 14:05:46 -07001734 // For update, don't fill in the default activity. Having null activity means
1735 // "don't update the activity" here.
1736
Makoto Onuki7001a612016-05-27 13:24:28 -07001737 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_UPDATE);
1738
Makoto Onuki55046222016-03-08 10:49:47 -08001739 // Throttling.
Makoto Onukic51b2872016-05-04 15:24:50 -07001740 if (!ps.tryApiCall()) {
Makoto Onuki55046222016-03-08 10:49:47 -08001741 return false;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001742 }
1743
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001744 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1745 ps.clearAllImplicitRanks();
1746 assignImplicitRanks(newShortcuts);
1747
Makoto Onuki55046222016-03-08 10:49:47 -08001748 for (int i = 0; i < size; i++) {
1749 final ShortcutInfo source = newShortcuts.get(i);
1750 fixUpIncomingShortcutInfo(source, /* forUpdate= */ true);
1751
1752 final ShortcutInfo target = ps.findShortcutById(source.getId());
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001753 if (target == null) {
1754 continue;
1755 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07001756
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001757 if (target.isEnabled() != source.isEnabled()) {
1758 Slog.w(TAG,
1759 "ShortcutInfo.enabled cannot be changed with updateShortcuts()");
1760 }
Makoto Onuki55046222016-03-08 10:49:47 -08001761
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001762 // When updating the rank, we need to insert between existing ranks, so set
1763 // this setRankChanged, and also copy the implicit rank fo adjustRanks().
1764 if (source.hasRank()) {
1765 target.setRankChanged();
1766 target.setImplicitRank(source.getImplicitRank());
1767 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07001768
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001769 final boolean replacingIcon = (source.getIcon() != null);
1770 if (replacingIcon) {
1771 removeIcon(userId, target);
1772 }
Makoto Onuki55046222016-03-08 10:49:47 -08001773
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001774 // Note copyNonNullFieldsFrom() does the "updatable with?" check too.
1775 target.copyNonNullFieldsFrom(source);
1776 target.setTimestamp(injectCurrentTimeMillis());
1777
1778 if (replacingIcon) {
1779 saveIconAndFixUpShortcut(userId, target);
1780 }
1781
1782 // When we're updating any resource related fields, re-extract the res names and
1783 // the values.
1784 if (replacingIcon || source.hasStringResources()) {
1785 fixUpShortcutResourceNamesAndValues(target);
Makoto Onuki55046222016-03-08 10:49:47 -08001786 }
1787 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001788
1789 // Lastly, adjust the ranks.
1790 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001791 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001792 packageShortcutsChanged(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001793
Makoto Onuki7001a612016-05-27 13:24:28 -07001794 verifyStates();
1795
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001796 return true;
1797 }
1798
1799 @Override
Makoto Onukib6d35232016-04-04 15:57:17 -07001800 public boolean addDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001801 @UserIdInt int userId) {
1802 verifyCaller(packageName, userId);
1803
Makoto Onukib6d35232016-04-04 15:57:17 -07001804 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
1805 final int size = newShortcuts.size();
1806
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001807 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001808 throwIfUserLockedL(userId);
1809
Makoto Onukic8c33292016-09-12 16:36:59 -07001810 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001811
Makoto Onuki22fcc682016-05-17 14:52:19 -07001812 ps.ensureImmutableShortcutsNotIncluded(newShortcuts);
1813
Makoto Onukib08790c2016-06-23 14:05:46 -07001814 fillInDefaultActivity(newShortcuts);
1815
Makoto Onuki7001a612016-05-27 13:24:28 -07001816 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_ADD);
1817
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001818 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1819 ps.clearAllImplicitRanks();
1820 assignImplicitRanks(newShortcuts);
1821
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001822 // Throttling.
Makoto Onukic51b2872016-05-04 15:24:50 -07001823 if (!ps.tryApiCall()) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001824 return false;
1825 }
Makoto Onukib6d35232016-04-04 15:57:17 -07001826 for (int i = 0; i < size; i++) {
1827 final ShortcutInfo newShortcut = newShortcuts.get(i);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001828
Makoto Onukib6d35232016-04-04 15:57:17 -07001829 // Validate the shortcut.
1830 fixUpIncomingShortcutInfo(newShortcut, /* forUpdate= */ false);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001831
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001832 // When ranks are changing, we need to insert between ranks, so set the
1833 // "rank changed" flag.
1834 newShortcut.setRankChanged();
1835
Makoto Onukib6d35232016-04-04 15:57:17 -07001836 // Add it.
Makoto Onuki22fcc682016-05-17 14:52:19 -07001837 ps.addOrUpdateDynamicShortcut(newShortcut);
Makoto Onukib6d35232016-04-04 15:57:17 -07001838 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001839
1840 // Lastly, adjust the ranks.
1841 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001842 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001843 packageShortcutsChanged(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001844
Makoto Onuki7001a612016-05-27 13:24:28 -07001845 verifyStates();
1846
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001847 return true;
1848 }
1849
1850 @Override
Makoto Onuki2d895c32016-12-02 15:48:40 -08001851 public boolean requestPinShortcut(String packageName, ShortcutInfo shortcut,
1852 IntentSender resultIntent, int userId) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08001853 Preconditions.checkNotNull(shortcut);
1854 Preconditions.checkArgument(shortcut.isEnabled(), "Shortcut must be enabled");
Sunny Goyal87a563e2017-01-01 19:42:45 -08001855 return requestPinItem(packageName, userId, shortcut, null, resultIntent);
1856 }
1857
Sunny Goyala6be88a2017-01-12 16:27:58 -08001858 @Override
1859 public Intent createShortcutResultIntent(String packageName, ShortcutInfo shortcut, int userId)
1860 throws RemoteException {
1861 Preconditions.checkNotNull(shortcut);
1862 Preconditions.checkArgument(shortcut.isEnabled(), "Shortcut must be enabled");
1863 verifyCaller(packageName, userId);
1864
1865 final Intent ret;
1866 synchronized (mLock) {
1867 throwIfUserLockedL(userId);
1868
1869 // Send request to the launcher, if supported.
1870 ret = mShortcutRequestPinProcessor.createShortcutResultIntent(shortcut, userId);
1871 }
1872
1873 verifyStates();
1874 return ret;
1875 }
1876
Sunny Goyal87a563e2017-01-01 19:42:45 -08001877 /**
1878 * Handles {@link #requestPinShortcut} and {@link ShortcutServiceInternal#requestPinAppWidget}.
1879 * After validating the caller, it passes the request to {@link #mShortcutRequestPinProcessor}.
1880 * Either {@param shortcut} or {@param appWidget} should be non-null.
1881 */
1882 private boolean requestPinItem(String packageName, int userId,
1883 ShortcutInfo shortcut, AppWidgetProviderInfo appWidget, IntentSender resultIntent) {
1884 verifyCaller(packageName, userId);
Makoto Onuki2d895c32016-12-02 15:48:40 -08001885
1886 final boolean ret;
1887 synchronized (mLock) {
1888 throwIfUserLockedL(userId);
1889
Makoto Onukia01f4f02016-12-15 15:58:41 -08001890 Preconditions.checkState(isUidForegroundLocked(injectBinderCallingUid()),
Makoto Onuki255461f2017-01-10 11:47:25 -08001891 "Calling application must have a foreground activity or a foreground service");
Makoto Onuki2d895c32016-12-02 15:48:40 -08001892
1893 // Send request to the launcher, if supported.
Sunny Goyal87a563e2017-01-01 19:42:45 -08001894 ret = mShortcutRequestPinProcessor.requestPinItemLocked(shortcut, appWidget, userId,
1895 resultIntent);
Makoto Onuki2d895c32016-12-02 15:48:40 -08001896 }
1897
1898 verifyStates();
1899
1900 return ret;
1901 }
1902
1903 @Override
Makoto Onuki20c95f82016-05-11 16:51:01 -07001904 public void disableShortcuts(String packageName, List shortcutIds,
Makoto Onukid6880792016-06-29 13:37:43 -07001905 CharSequence disabledMessage, int disabledMessageResId, @UserIdInt int userId) {
Makoto Onuki20c95f82016-05-11 16:51:01 -07001906 verifyCaller(packageName, userId);
1907 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
1908
1909 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001910 throwIfUserLockedL(userId);
1911
Makoto Onukic8c33292016-09-12 16:36:59 -07001912 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001913
1914 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds);
1915
Makoto Onukid6880792016-06-29 13:37:43 -07001916 final String disabledMessageString =
1917 (disabledMessage == null) ? null : disabledMessage.toString();
1918
Makoto Onuki22fcc682016-05-17 14:52:19 -07001919 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
1920 ps.disableWithId(Preconditions.checkStringNotEmpty((String) shortcutIds.get(i)),
Makoto Onukid6880792016-06-29 13:37:43 -07001921 disabledMessageString, disabledMessageResId,
Makoto Onuki22fcc682016-05-17 14:52:19 -07001922 /* overrideImmutable=*/ false);
1923 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001924
1925 // We may have removed dynamic shortcuts which may have left a gap, so adjust the ranks.
1926 ps.adjustRanks();
Makoto Onuki22fcc682016-05-17 14:52:19 -07001927 }
1928 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001929
1930 verifyStates();
Makoto Onuki22fcc682016-05-17 14:52:19 -07001931 }
1932
1933 @Override
1934 public void enableShortcuts(String packageName, List shortcutIds, @UserIdInt int userId) {
1935 verifyCaller(packageName, userId);
1936 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
1937
1938 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001939 throwIfUserLockedL(userId);
1940
Makoto Onukic8c33292016-09-12 16:36:59 -07001941 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001942
1943 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds);
1944
1945 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
1946 ps.enableWithId((String) shortcutIds.get(i));
1947 }
Makoto Onuki20c95f82016-05-11 16:51:01 -07001948 }
1949 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001950
1951 verifyStates();
Makoto Onuki20c95f82016-05-11 16:51:01 -07001952 }
1953
1954 @Override
Makoto Onukib6d35232016-04-04 15:57:17 -07001955 public void removeDynamicShortcuts(String packageName, List shortcutIds,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001956 @UserIdInt int userId) {
1957 verifyCaller(packageName, userId);
Makoto Onukib6d35232016-04-04 15:57:17 -07001958 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001959
1960 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001961 throwIfUserLockedL(userId);
1962
Makoto Onukic8c33292016-09-12 16:36:59 -07001963 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001964
1965 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds);
1966
Makoto Onukib6d35232016-04-04 15:57:17 -07001967 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07001968 ps.deleteDynamicWithId(
Makoto Onukib6d35232016-04-04 15:57:17 -07001969 Preconditions.checkStringNotEmpty((String) shortcutIds.get(i)));
1970 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001971
1972 // We may have removed dynamic shortcuts which may have left a gap, so adjust the ranks.
1973 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001974 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001975 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001976
1977 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001978 }
1979
1980 @Override
Makoto Onukib6d35232016-04-04 15:57:17 -07001981 public void removeAllDynamicShortcuts(String packageName, @UserIdInt int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001982 verifyCaller(packageName, userId);
1983
1984 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001985 throwIfUserLockedL(userId);
1986
Makoto Onukic8c33292016-09-12 16:36:59 -07001987 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07001988 ps.deleteAllDynamicShortcuts();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001989 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001990 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001991
1992 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001993 }
1994
1995 @Override
1996 public ParceledListSlice<ShortcutInfo> getDynamicShortcuts(String packageName,
1997 @UserIdInt int userId) {
1998 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07001999
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002000 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002001 throwIfUserLockedL(userId);
2002
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002003 return getShortcutsWithQueryLocked(
2004 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
2005 ShortcutInfo::isDynamic);
2006 }
2007 }
2008
2009 @Override
Makoto Onuki22fcc682016-05-17 14:52:19 -07002010 public ParceledListSlice<ShortcutInfo> getManifestShortcuts(String packageName,
2011 @UserIdInt int userId) {
2012 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002013
Makoto Onuki22fcc682016-05-17 14:52:19 -07002014 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002015 throwIfUserLockedL(userId);
2016
Makoto Onuki22fcc682016-05-17 14:52:19 -07002017 return getShortcutsWithQueryLocked(
2018 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
2019 ShortcutInfo::isManifestShortcut);
2020 }
2021 }
2022
2023 @Override
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002024 public ParceledListSlice<ShortcutInfo> getPinnedShortcuts(String packageName,
2025 @UserIdInt int userId) {
2026 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002027
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002028 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002029 throwIfUserLockedL(userId);
2030
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002031 return getShortcutsWithQueryLocked(
2032 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
2033 ShortcutInfo::isPinned);
2034 }
2035 }
2036
2037 private ParceledListSlice<ShortcutInfo> getShortcutsWithQueryLocked(@NonNull String packageName,
2038 @UserIdInt int userId, int cloneFlags, @NonNull Predicate<ShortcutInfo> query) {
2039
2040 final ArrayList<ShortcutInfo> ret = new ArrayList<>();
2041
Makoto Onukic8c33292016-09-12 16:36:59 -07002042 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002043 ps.findAll(ret, query, cloneFlags);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002044
2045 return new ParceledListSlice<>(ret);
2046 }
2047
2048 @Override
Makoto Onukid6880792016-06-29 13:37:43 -07002049 public int getMaxShortcutCountPerActivity(String packageName, @UserIdInt int userId)
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002050 throws RemoteException {
2051 verifyCaller(packageName, userId);
2052
Makoto Onukib5a012f2016-06-21 11:13:53 -07002053 return mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002054 }
2055
2056 @Override
2057 public int getRemainingCallCount(String packageName, @UserIdInt int userId) {
2058 verifyCaller(packageName, userId);
2059
2060 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002061 throwIfUserLockedL(userId);
2062
Makoto Onukic8c33292016-09-12 16:36:59 -07002063 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002064 return mMaxUpdatesPerInterval - ps.getApiCallCount();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002065 }
2066 }
2067
2068 @Override
2069 public long getRateLimitResetTime(String packageName, @UserIdInt int userId) {
2070 verifyCaller(packageName, userId);
2071
2072 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002073 throwIfUserLockedL(userId);
2074
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002075 return getNextResetTimeLocked();
2076 }
2077 }
2078
Makoto Onuki55046222016-03-08 10:49:47 -08002079 @Override
Makoto Onuki20c95f82016-05-11 16:51:01 -07002080 public int getIconMaxDimensions(String packageName, int userId) {
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002081 verifyCaller(packageName, userId);
2082
Makoto Onuki55046222016-03-08 10:49:47 -08002083 synchronized (mLock) {
2084 return mMaxIconDimension;
2085 }
2086 }
2087
Makoto Onuki20c95f82016-05-11 16:51:01 -07002088 @Override
2089 public void reportShortcutUsed(String packageName, String shortcutId, int userId) {
2090 verifyCaller(packageName, userId);
2091
Makoto Onukiac042502016-05-20 16:39:42 -07002092 Preconditions.checkNotNull(shortcutId);
2093
2094 if (DEBUG) {
2095 Slog.d(TAG, String.format("reportShortcutUsed: Shortcut %s package %s used on user %d",
2096 shortcutId, packageName, userId));
2097 }
2098
2099 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002100 throwIfUserLockedL(userId);
2101
Makoto Onukic8c33292016-09-12 16:36:59 -07002102 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002103
Makoto Onukiac042502016-05-20 16:39:42 -07002104 if (ps.findShortcutById(shortcutId) == null) {
2105 Log.w(TAG, String.format("reportShortcutUsed: package %s doesn't have shortcut %s",
2106 packageName, shortcutId));
2107 return;
2108 }
2109 }
2110
2111 final long token = injectClearCallingIdentity();
2112 try {
2113 mUsageStatsManagerInternal.reportShortcutUsage(packageName, shortcutId, userId);
2114 } finally {
2115 injectRestoreCallingIdentity(token);
2116 }
Makoto Onuki20c95f82016-05-11 16:51:01 -07002117 }
2118
Makoto Onuki2d895c32016-12-02 15:48:40 -08002119 @Override
Sunny Goyal7f7372a2017-01-24 11:53:54 -08002120 public boolean isRequestPinItemSupported(int callingUserId, int requestType) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08002121 final long token = injectClearCallingIdentity();
2122 try {
Sunny Goyal7f7372a2017-01-24 11:53:54 -08002123 return mShortcutRequestPinProcessor
2124 .isRequestPinItemSupported(callingUserId, requestType);
Makoto Onuki2d895c32016-12-02 15:48:40 -08002125 } finally {
2126 injectRestoreCallingIdentity(token);
2127 }
2128 }
2129
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002130 /**
Makoto Onukib08790c2016-06-23 14:05:46 -07002131 * Reset all throttling, for developer options and command line. Only system/shell can call
2132 * it.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002133 */
2134 @Override
2135 public void resetThrottling() {
2136 enforceSystemOrShell();
2137
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002138 resetThrottlingInner(getCallingUserId());
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002139 }
2140
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002141 void resetThrottlingInner(@UserIdInt int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002142 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002143 if (!isUserUnlockedL(userId)) {
2144 Log.w(TAG, "User " + userId + " is locked or not running");
2145 return;
2146 }
2147
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002148 getUserShortcutsLocked(userId).resetThrottling();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002149 }
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002150 scheduleSaveUser(userId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002151 Slog.i(TAG, "ShortcutManager: throttling counter reset for user " + userId);
2152 }
2153
2154 void resetAllThrottlingInner() {
2155 synchronized (mLock) {
2156 mRawLastResetTime = injectCurrentTimeMillis();
2157 }
2158 scheduleSaveBaseState();
2159 Slog.i(TAG, "ShortcutManager: throttling counter reset for all users");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002160 }
2161
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002162 @Override
2163 public void onApplicationActive(String packageName, int userId) {
2164 if (DEBUG) {
2165 Slog.d(TAG, "onApplicationActive: package=" + packageName + " userid=" + userId);
2166 }
2167 enforceResetThrottlingPermission();
Makoto Onuki02f338e2016-07-29 09:40:40 -07002168
2169 synchronized (mLock) {
2170 if (!isUserUnlockedL(userId)) {
2171 // This is called by system UI, so no need to throw. Just ignore.
2172 return;
2173 }
2174
2175 getPackageShortcutsLocked(packageName, userId)
2176 .resetRateLimitingForCommandLineNoSaving();
2177 saveUserLocked(userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002178 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002179 }
2180
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002181 // We override this method in unit tests to do a simpler check.
2182 boolean hasShortcutHostPermission(@NonNull String callingPackage, int userId) {
Makoto Onuki10305202016-07-14 18:14:08 -07002183 final long start = injectElapsedRealtime();
2184 try {
2185 return hasShortcutHostPermissionInner(callingPackage, userId);
2186 } finally {
2187 logDurationStat(Stats.LAUNCHER_PERMISSION_CHECK, start);
2188 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002189 }
2190
2191 // This method is extracted so we can directly call this method from unit tests,
2192 // even when hasShortcutPermission() is overridden.
2193 @VisibleForTesting
Makoto Onuki2d895c32016-12-02 15:48:40 -08002194 boolean hasShortcutHostPermissionInner(@NonNull String packageName, int userId) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002195 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002196 throwIfUserLockedL(userId);
2197
Makoto Onuki31459242016-03-22 11:12:18 -07002198 final ShortcutUser user = getUserShortcutsLocked(userId);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002199
Makoto Onuki2d895c32016-12-02 15:48:40 -08002200 // Always trust the cached component.
Makoto Onuki10305202016-07-14 18:14:08 -07002201 final ComponentName cached = user.getCachedLauncher();
2202 if (cached != null) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08002203 if (cached.getPackageName().equals(packageName)) {
Makoto Onuki10305202016-07-14 18:14:08 -07002204 return true;
2205 }
2206 }
2207 // If the cached one doesn't match, then go ahead
2208
Makoto Onuki2d895c32016-12-02 15:48:40 -08002209 final ComponentName detected = getDefaultLauncher(userId);
Makoto Onuki2e210c42016-03-30 08:30:36 -07002210
Makoto Onuki10305202016-07-14 18:14:08 -07002211 // Update the cache.
2212 user.setLauncher(detected);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002213 if (detected != null) {
2214 if (DEBUG) {
2215 Slog.v(TAG, "Detected launcher: " + detected);
2216 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08002217 return detected.getPackageName().equals(packageName);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002218 } else {
2219 // Default launcher not found.
2220 return false;
2221 }
2222 }
2223 }
2224
Makoto Onuki2d895c32016-12-02 15:48:40 -08002225 @Nullable
2226 ComponentName getDefaultLauncher(@UserIdInt int userId) {
2227 final long start = injectElapsedRealtime();
2228 final long token = injectClearCallingIdentity();
2229 try {
2230 synchronized (mLock) {
2231 throwIfUserLockedL(userId);
2232
2233 final ShortcutUser user = getUserShortcutsLocked(userId);
2234
2235 final List<ResolveInfo> allHomeCandidates = new ArrayList<>();
2236
2237 // Default launcher from package manager.
2238 final long startGetHomeActivitiesAsUser = injectElapsedRealtime();
2239 final ComponentName defaultLauncher = mPackageManagerInternal
2240 .getHomeActivitiesAsUser(allHomeCandidates, userId);
2241 logDurationStat(Stats.GET_DEFAULT_HOME, startGetHomeActivitiesAsUser);
2242
2243 ComponentName detected = null;
2244 if (defaultLauncher != null) {
2245 detected = defaultLauncher;
2246 if (DEBUG) {
2247 Slog.v(TAG, "Default launcher from PM: " + detected);
2248 }
2249 } else {
2250 detected = user.getLastKnownLauncher();
2251
2252 if (detected != null) {
2253 if (injectIsActivityEnabledAndExported(detected, userId)) {
2254 if (DEBUG) {
2255 Slog.v(TAG, "Cached launcher: " + detected);
2256 }
2257 } else {
2258 Slog.w(TAG, "Cached launcher " + detected + " no longer exists");
2259 detected = null;
2260 user.clearLauncher();
2261 }
2262 }
2263 }
2264
2265 if (detected == null) {
2266 // If we reach here, that means it's the first check since the user was created,
2267 // and there's already multiple launchers and there's no default set.
2268 // Find the system one with the highest priority.
2269 // (We need to check the priority too because of FallbackHome in Settings.)
2270 // If there's no system launcher yet, then no one can access shortcuts, until
2271 // the user explicitly
2272 final int size = allHomeCandidates.size();
2273
2274 int lastPriority = Integer.MIN_VALUE;
2275 for (int i = 0; i < size; i++) {
2276 final ResolveInfo ri = allHomeCandidates.get(i);
2277 if (!ri.activityInfo.applicationInfo.isSystemApp()) {
2278 continue;
2279 }
2280 if (DEBUG) {
2281 Slog.d(TAG, String.format("hasShortcutPermissionInner: pkg=%s prio=%d",
2282 ri.activityInfo.getComponentName(), ri.priority));
2283 }
2284 if (ri.priority < lastPriority) {
2285 continue;
2286 }
2287 detected = ri.activityInfo.getComponentName();
2288 lastPriority = ri.priority;
2289 }
2290 }
2291 return detected;
2292 }
2293 } finally {
2294 injectRestoreCallingIdentity(token);
2295 logDurationStat(Stats.GET_DEFAULT_LAUNCHER, start);
2296 }
2297 }
2298
Makoto Onukicdc78f72016-03-21 15:47:52 -07002299 // === House keeping ===
2300
Makoto Onukib08790c2016-06-23 14:05:46 -07002301 private void cleanUpPackageForAllLoadedUsers(String packageName, @UserIdInt int packageUserId,
2302 boolean appStillExists) {
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002303 synchronized (mLock) {
2304 forEachLoadedUserLocked(user ->
Makoto Onukib08790c2016-06-23 14:05:46 -07002305 cleanUpPackageLocked(packageName, user.getUserId(), packageUserId,
2306 appStillExists));
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002307 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002308 }
2309
Makoto Onuki2e210c42016-03-30 08:30:36 -07002310 /**
2311 * Remove all the information associated with a package. This will really remove all the
2312 * information, including the restore information (i.e. it'll remove packages even if they're
2313 * shadow).
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002314 *
2315 * This is called when an app is uninstalled, or an app gets "clear data"ed.
Makoto Onuki2e210c42016-03-30 08:30:36 -07002316 */
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002317 @VisibleForTesting
Makoto Onukib08790c2016-06-23 14:05:46 -07002318 void cleanUpPackageLocked(String packageName, int owningUserId, int packageUserId,
2319 boolean appStillExists) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002320 final boolean wasUserLoaded = isUserLoadedLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002321
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002322 final ShortcutUser user = getUserShortcutsLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002323 boolean doNotify = false;
2324
2325 // First, remove the package from the package list (if the package is a publisher).
Makoto Onukid99c6f02016-03-28 11:02:54 -07002326 if (packageUserId == owningUserId) {
Makoto Onukic51b2872016-05-04 15:24:50 -07002327 if (user.removePackage(packageName) != null) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002328 doNotify = true;
2329 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07002330 }
Makoto Onukid99c6f02016-03-28 11:02:54 -07002331
Makoto Onukicdc78f72016-03-21 15:47:52 -07002332 // Also remove from the launcher list (if the package is a launcher).
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002333 user.removeLauncher(packageUserId, packageName);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002334
2335 // Then remove pinned shortcuts from all launchers.
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002336 user.forAllLaunchers(l -> l.cleanUpPackage(packageName, packageUserId));
2337
2338 // Now there may be orphan shortcuts because we removed pinned shortcuts at the previous
Makoto Onukicdc78f72016-03-21 15:47:52 -07002339 // step. Remove them too.
Makoto Onukic51b2872016-05-04 15:24:50 -07002340 user.forAllPackages(p -> p.refreshPinnedFlags());
Makoto Onukicdc78f72016-03-21 15:47:52 -07002341
Makoto Onukid99c6f02016-03-28 11:02:54 -07002342 scheduleSaveUser(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002343
2344 if (doNotify) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002345 notifyListeners(packageName, owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002346 }
2347
Makoto Onukib08790c2016-06-23 14:05:46 -07002348 // If the app still exists (i.e. data cleared), we need to re-publish manifest shortcuts.
2349 if (appStillExists && (packageUserId == owningUserId)) {
2350 // This will do the notification and save when needed, so do it after the above
2351 // notifyListeners.
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002352 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07002353 }
2354
Makoto Onukicdc78f72016-03-21 15:47:52 -07002355 if (!wasUserLoaded) {
2356 // Note this will execute the scheduled save.
Makoto Onukid99c6f02016-03-28 11:02:54 -07002357 unloadUserLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002358 }
2359 }
2360
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002361 /**
2362 * Entry point from {@link LauncherApps}.
2363 */
2364 private class LocalService extends ShortcutServiceInternal {
Makoto Onuki2e210c42016-03-30 08:30:36 -07002365
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002366 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002367 public List<ShortcutInfo> getShortcuts(int launcherUserId,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002368 @NonNull String callingPackage, long changedSince,
Makoto Onukiabe84422016-04-07 09:41:19 -07002369 @Nullable String packageName, @Nullable List<String> shortcutIds,
2370 @Nullable ComponentName componentName,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002371 int queryFlags, int userId) {
2372 final ArrayList<ShortcutInfo> ret = new ArrayList<>();
Makoto Onuki9c850012016-07-26 15:50:50 -07002373
Makoto Onuki20c95f82016-05-11 16:51:01 -07002374 final boolean cloneKeyFieldOnly =
2375 ((queryFlags & ShortcutQuery.FLAG_GET_KEY_FIELDS_ONLY) != 0);
2376 final int cloneFlag = cloneKeyFieldOnly ? ShortcutInfo.CLONE_REMOVE_NON_KEY_INFO
2377 : ShortcutInfo.CLONE_REMOVE_FOR_LAUNCHER;
Makoto Onukiabe84422016-04-07 09:41:19 -07002378 if (packageName == null) {
2379 shortcutIds = null; // LauncherAppsService already threw for it though.
2380 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002381
2382 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002383 throwIfUserLockedL(userId);
2384 throwIfUserLockedL(launcherUserId);
2385
Makoto Onuki2e210c42016-03-30 08:30:36 -07002386 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002387 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002388
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002389 if (packageName != null) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002390 getShortcutsInnerLocked(launcherUserId,
Makoto Onukiabe84422016-04-07 09:41:19 -07002391 callingPackage, packageName, shortcutIds, changedSince,
Makoto Onukide667372016-03-15 14:29:20 -07002392 componentName, queryFlags, userId, ret, cloneFlag);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002393 } else {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002394 final List<String> shortcutIdsF = shortcutIds;
2395 getUserShortcutsLocked(userId).forAllPackages(p -> {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002396 getShortcutsInnerLocked(launcherUserId,
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002397 callingPackage, p.getPackageName(), shortcutIdsF, changedSince,
Makoto Onukide667372016-03-15 14:29:20 -07002398 componentName, queryFlags, userId, ret, cloneFlag);
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002399 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002400 }
2401 }
2402 return ret;
2403 }
2404
Makoto Onukid99c6f02016-03-28 11:02:54 -07002405 private void getShortcutsInnerLocked(int launcherUserId, @NonNull String callingPackage,
Makoto Onukiabe84422016-04-07 09:41:19 -07002406 @Nullable String packageName, @Nullable List<String> shortcutIds, long changedSince,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002407 @Nullable ComponentName componentName, int queryFlags,
2408 int userId, ArrayList<ShortcutInfo> ret, int cloneFlag) {
Makoto Onukiabe84422016-04-07 09:41:19 -07002409 final ArraySet<String> ids = shortcutIds == null ? null
2410 : new ArraySet<>(shortcutIds);
2411
Makoto Onukic51b2872016-05-04 15:24:50 -07002412 final ShortcutPackage p = getUserShortcutsLocked(userId)
2413 .getPackageShortcutsIfExists(packageName);
2414 if (p == null) {
2415 return; // No need to instantiate ShortcutPackage.
2416 }
2417
2418 p.findAll(ret,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002419 (ShortcutInfo si) -> {
2420 if (si.getLastChangedTimestamp() < changedSince) {
2421 return false;
2422 }
Makoto Onukiabe84422016-04-07 09:41:19 -07002423 if (ids != null && !ids.contains(si.getId())) {
2424 return false;
2425 }
Makoto Onuki85694522016-05-04 12:53:37 -07002426 if (componentName != null) {
Makoto Onuki9fd90192017-01-06 18:31:03 +00002427 if (si.getActivity() != null
2428 && !si.getActivity().equals(componentName)) {
Makoto Onuki85694522016-05-04 12:53:37 -07002429 return false;
2430 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002431 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002432 if (((queryFlags & ShortcutQuery.FLAG_GET_DYNAMIC) != 0)
2433 && si.isDynamic()) {
2434 return true;
2435 }
2436 if (((queryFlags & ShortcutQuery.FLAG_GET_PINNED) != 0)
2437 && si.isPinned()) {
2438 return true;
2439 }
2440 if (((queryFlags & ShortcutQuery.FLAG_GET_MANIFEST) != 0)
2441 && si.isManifestShortcut()) {
2442 return true;
2443 }
2444 return false;
Makoto Onukid99c6f02016-03-28 11:02:54 -07002445 }, cloneFlag, callingPackage, launcherUserId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002446 }
2447
2448 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002449 public boolean isPinnedByCaller(int launcherUserId, @NonNull String callingPackage,
2450 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2451 Preconditions.checkStringNotEmpty(packageName, "packageName");
2452 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
2453
2454 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002455 throwIfUserLockedL(userId);
2456 throwIfUserLockedL(launcherUserId);
2457
Makoto Onuki2e210c42016-03-30 08:30:36 -07002458 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002459 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002460
Makoto Onukid99c6f02016-03-28 11:02:54 -07002461 final ShortcutInfo si = getShortcutInfoLocked(
2462 launcherUserId, callingPackage, packageName, shortcutId, userId);
2463 return si != null && si.isPinned();
2464 }
2465 }
2466
Makoto Onuki2e210c42016-03-30 08:30:36 -07002467 private ShortcutInfo getShortcutInfoLocked(
Makoto Onukid99c6f02016-03-28 11:02:54 -07002468 int launcherUserId, @NonNull String callingPackage,
2469 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2470 Preconditions.checkStringNotEmpty(packageName, "packageName");
2471 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
2472
Makoto Onuki02f338e2016-07-29 09:40:40 -07002473 throwIfUserLockedL(userId);
2474 throwIfUserLockedL(launcherUserId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002475
Makoto Onukic51b2872016-05-04 15:24:50 -07002476 final ShortcutPackage p = getUserShortcutsLocked(userId)
2477 .getPackageShortcutsIfExists(packageName);
2478 if (p == null) {
2479 return null;
2480 }
2481
Makoto Onukid99c6f02016-03-28 11:02:54 -07002482 final ArrayList<ShortcutInfo> list = new ArrayList<>(1);
Makoto Onukic51b2872016-05-04 15:24:50 -07002483 p.findAll(list,
Makoto Onukid99c6f02016-03-28 11:02:54 -07002484 (ShortcutInfo si) -> shortcutId.equals(si.getId()),
2485 /* clone flags=*/ 0, callingPackage, launcherUserId);
2486 return list.size() == 0 ? null : list.get(0);
2487 }
2488
2489 @Override
2490 public void pinShortcuts(int launcherUserId,
2491 @NonNull String callingPackage, @NonNull String packageName,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002492 @NonNull List<String> shortcutIds, int userId) {
2493 // Calling permission must be checked by LauncherAppsImpl.
2494 Preconditions.checkStringNotEmpty(packageName, "packageName");
2495 Preconditions.checkNotNull(shortcutIds, "shortcutIds");
2496
2497 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002498 throwIfUserLockedL(userId);
2499 throwIfUserLockedL(launcherUserId);
2500
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002501 final ShortcutLauncher launcher =
Makoto Onuki2e210c42016-03-30 08:30:36 -07002502 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId);
Makoto Onukic51b2872016-05-04 15:24:50 -07002503 launcher.attemptToRestoreIfNeededAndSave();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002504
Makoto Onukic51b2872016-05-04 15:24:50 -07002505 launcher.pinShortcuts(userId, packageName, shortcutIds);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002506 }
Makoto Onuki39686e82016-04-13 18:03:00 -07002507 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07002508
2509 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002510 }
2511
2512 @Override
Makoto Onuki440a1ea2016-07-20 14:21:18 -07002513 public Intent[] createShortcutIntents(int launcherUserId,
Makoto Onukid99c6f02016-03-28 11:02:54 -07002514 @NonNull String callingPackage,
Makoto Onuki43204b82016-03-08 16:16:44 -08002515 @NonNull String packageName, @NonNull String shortcutId, int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002516 // Calling permission must be checked by LauncherAppsImpl.
Makoto Onuki43204b82016-03-08 16:16:44 -08002517 Preconditions.checkStringNotEmpty(packageName, "packageName can't be empty");
2518 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId can't be empty");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002519
2520 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002521 throwIfUserLockedL(userId);
2522 throwIfUserLockedL(launcherUserId);
2523
Makoto Onuki2e210c42016-03-30 08:30:36 -07002524 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002525 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002526
Makoto Onukid99c6f02016-03-28 11:02:54 -07002527 // Make sure the shortcut is actually visible to the launcher.
2528 final ShortcutInfo si = getShortcutInfoLocked(
2529 launcherUserId, callingPackage, packageName, shortcutId, userId);
2530 // "si == null" should suffice here, but check the flags too just to make sure.
Makoto Onuki22fcc682016-05-17 14:52:19 -07002531 if (si == null || !si.isEnabled() || !si.isAlive()) {
Makoto Onuki83f6d2d2016-07-11 14:30:19 -07002532 Log.e(TAG, "Shortcut " + shortcutId + " does not exist or disabled");
Makoto Onukid99c6f02016-03-28 11:02:54 -07002533 return null;
2534 }
Makoto Onuki440a1ea2016-07-20 14:21:18 -07002535 return si.getIntents();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002536 }
2537 }
2538
2539 @Override
2540 public void addListener(@NonNull ShortcutChangeListener listener) {
2541 synchronized (mLock) {
2542 mListeners.add(Preconditions.checkNotNull(listener));
2543 }
2544 }
Makoto Onuki55046222016-03-08 10:49:47 -08002545
2546 @Override
Makoto Onukiabe84422016-04-07 09:41:19 -07002547 public int getShortcutIconResId(int launcherUserId, @NonNull String callingPackage,
2548 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2549 Preconditions.checkNotNull(callingPackage, "callingPackage");
2550 Preconditions.checkNotNull(packageName, "packageName");
2551 Preconditions.checkNotNull(shortcutId, "shortcutId");
Makoto Onuki55046222016-03-08 10:49:47 -08002552
2553 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002554 throwIfUserLockedL(userId);
2555 throwIfUserLockedL(launcherUserId);
2556
Makoto Onuki2e210c42016-03-30 08:30:36 -07002557 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002558 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002559
Makoto Onukic51b2872016-05-04 15:24:50 -07002560 final ShortcutPackage p = getUserShortcutsLocked(userId)
2561 .getPackageShortcutsIfExists(packageName);
2562 if (p == null) {
2563 return 0;
2564 }
2565
2566 final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId);
Makoto Onuki55046222016-03-08 10:49:47 -08002567 return (shortcutInfo != null && shortcutInfo.hasIconResource())
2568 ? shortcutInfo.getIconResourceId() : 0;
2569 }
2570 }
2571
2572 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002573 public ParcelFileDescriptor getShortcutIconFd(int launcherUserId,
Makoto Onukiabe84422016-04-07 09:41:19 -07002574 @NonNull String callingPackage, @NonNull String packageName,
2575 @NonNull String shortcutId, int userId) {
2576 Preconditions.checkNotNull(callingPackage, "callingPackage");
2577 Preconditions.checkNotNull(packageName, "packageName");
2578 Preconditions.checkNotNull(shortcutId, "shortcutId");
Makoto Onuki55046222016-03-08 10:49:47 -08002579
2580 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002581 throwIfUserLockedL(userId);
2582 throwIfUserLockedL(launcherUserId);
2583
Makoto Onuki2e210c42016-03-30 08:30:36 -07002584 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002585 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002586
Makoto Onukic51b2872016-05-04 15:24:50 -07002587 final ShortcutPackage p = getUserShortcutsLocked(userId)
2588 .getPackageShortcutsIfExists(packageName);
2589 if (p == null) {
2590 return null;
2591 }
2592
2593 final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId);
Makoto Onuki55046222016-03-08 10:49:47 -08002594 if (shortcutInfo == null || !shortcutInfo.hasIconFile()) {
2595 return null;
2596 }
2597 try {
Makoto Onuki34d1c912016-03-10 14:24:58 -08002598 if (shortcutInfo.getBitmapPath() == null) {
2599 Slog.w(TAG, "null bitmap detected in getShortcutIconFd()");
2600 return null;
2601 }
Makoto Onuki55046222016-03-08 10:49:47 -08002602 return ParcelFileDescriptor.open(
2603 new File(shortcutInfo.getBitmapPath()),
2604 ParcelFileDescriptor.MODE_READ_ONLY);
2605 } catch (FileNotFoundException e) {
2606 Slog.e(TAG, "Icon file not found: " + shortcutInfo.getBitmapPath());
2607 return null;
2608 }
2609 }
2610 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002611
2612 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002613 public boolean hasShortcutHostPermission(int launcherUserId,
2614 @NonNull String callingPackage) {
2615 return ShortcutService.this.hasShortcutHostPermission(callingPackage, launcherUserId);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002616 }
Sunny Goyal87a563e2017-01-01 19:42:45 -08002617
2618 @Override
2619 public boolean requestPinAppWidget(@NonNull String callingPackage,
2620 @NonNull AppWidgetProviderInfo appWidget, @Nullable IntentSender resultIntent,
2621 int userId) {
2622 Preconditions.checkNotNull(appWidget);
2623 return requestPinItem(callingPackage, userId, null, appWidget, resultIntent);
2624 }
Sunny Goyal7f7372a2017-01-24 11:53:54 -08002625
2626 @Override
2627 public boolean isRequestPinItemSupported(int callingUserId, int requestType) {
2628 return ShortcutService.this.isRequestPinItemSupported(callingUserId, requestType);
2629 }
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002630 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002631
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002632 final BroadcastReceiver mReceiver = new BroadcastReceiver() {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002633 @Override
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002634 public void onReceive(Context context, Intent intent) {
2635 if (!mBootCompleted.get()) {
2636 return; // Boot not completed, ignore the broadcast.
2637 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07002638 try {
2639 if (Intent.ACTION_LOCALE_CHANGED.equals(intent.getAction())) {
2640 handleLocaleChanged();
2641 }
2642 } catch (Exception e) {
2643 wtf("Exception in mReceiver.onReceive", e);
Makoto Onukic51b2872016-05-04 15:24:50 -07002644 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002645 }
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002646 };
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002647
Makoto Onuki157b1622016-06-02 16:13:10 -07002648 void handleLocaleChanged() {
2649 if (DEBUG) {
2650 Slog.d(TAG, "handleLocaleChanged");
2651 }
2652 scheduleSaveBaseState();
2653
Makoto Onuki02f338e2016-07-29 09:40:40 -07002654 synchronized (mLock) {
2655 final long token = injectClearCallingIdentity();
2656 try {
2657 forEachLoadedUserLocked(user -> user.detectLocaleChange());
2658 } finally {
2659 injectRestoreCallingIdentity(token);
2660 }
Makoto Onuki157b1622016-06-02 16:13:10 -07002661 }
2662 }
2663
Makoto Onukif34c3082016-07-13 10:25:25 -07002664 /**
2665 * Package event callbacks.
2666 */
2667 @VisibleForTesting
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002668 final BroadcastReceiver mPackageMonitor = new BroadcastReceiver() {
Makoto Onukif34c3082016-07-13 10:25:25 -07002669 @Override
2670 public void onReceive(Context context, Intent intent) {
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002671 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
2672 if (userId == UserHandle.USER_NULL) {
2673 Slog.w(TAG, "Intent broadcast does not contain user handle: " + intent);
2674 return;
2675 }
2676
2677 final String action = intent.getAction();
2678
2679 // This is normally called on Handler, so clearCallingIdentity() isn't needed,
2680 // but we still check it in unit tests.
Makoto Onukif34c3082016-07-13 10:25:25 -07002681 final long token = injectClearCallingIdentity();
2682 try {
Makoto Onuki10305202016-07-14 18:14:08 -07002683 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002684 if (!isUserUnlockedL(userId)) {
2685 if (DEBUG) {
2686 Slog.d(TAG, "Ignoring package broadcast " + action
2687 + " for locked/stopped user " + userId);
2688 }
2689 return;
2690 }
2691
2692 // Whenever we get one of those package broadcasts, or get
2693 // ACTION_PREFERRED_ACTIVITY_CHANGED, we purge the default launcher cache.
Makoto Onuki10305202016-07-14 18:14:08 -07002694 final ShortcutUser user = getUserShortcutsLocked(userId);
2695 user.clearLauncher();
2696 }
2697 if (Intent.ACTION_PREFERRED_ACTIVITY_CHANGED.equals(action)) {
2698 // Nothing farther to do.
2699 return;
2700 }
2701
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002702 final Uri intentUri = intent.getData();
2703 final String packageName = (intentUri != null) ? intentUri.getSchemeSpecificPart()
2704 : null;
2705 if (packageName == null) {
2706 Slog.w(TAG, "Intent broadcast does not contain package name: " + intent);
2707 return;
2708 }
2709
2710 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
2711
2712 switch (action) {
2713 case Intent.ACTION_PACKAGE_ADDED:
2714 if (replacing) {
2715 handlePackageUpdateFinished(packageName, userId);
2716 } else {
2717 handlePackageAdded(packageName, userId);
2718 }
2719 break;
2720 case Intent.ACTION_PACKAGE_REMOVED:
2721 if (!replacing) {
2722 handlePackageRemoved(packageName, userId);
2723 }
2724 break;
2725 case Intent.ACTION_PACKAGE_CHANGED:
2726 handlePackageChanged(packageName, userId);
2727
2728 break;
2729 case Intent.ACTION_PACKAGE_DATA_CLEARED:
2730 handlePackageDataCleared(packageName, userId);
2731 break;
2732 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07002733 } catch (Exception e) {
2734 wtf("Exception in mPackageMonitor.onReceive", e);
Makoto Onukif34c3082016-07-13 10:25:25 -07002735 } finally {
2736 injectRestoreCallingIdentity(token);
Makoto Onukia2241832016-07-06 13:28:37 -07002737 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07002738 }
Makoto Onukif34c3082016-07-13 10:25:25 -07002739 };
Makoto Onukicdc78f72016-03-21 15:47:52 -07002740
Makoto Onuki0acbb142016-03-22 17:02:57 -07002741 /**
Makoto Onuki39686e82016-04-13 18:03:00 -07002742 * Called when a user is unlocked.
2743 * - Check all known packages still exist, and otherwise perform cleanup.
2744 * - If a package still exists, check the version code. If it's been updated, may need to
Makoto Onukib08790c2016-06-23 14:05:46 -07002745 * update timestamps of its shortcuts.
Makoto Onuki0acbb142016-03-22 17:02:57 -07002746 */
Makoto Onukid99c6f02016-03-28 11:02:54 -07002747 @VisibleForTesting
Makoto Onuki39686e82016-04-13 18:03:00 -07002748 void checkPackageChanges(@UserIdInt int ownerUserId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07002749 if (DEBUG) {
Makoto Onuki39686e82016-04-13 18:03:00 -07002750 Slog.d(TAG, "checkPackageChanges() ownerUserId=" + ownerUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002751 }
Makoto Onukib08790c2016-06-23 14:05:46 -07002752 if (injectIsSafeModeEnabled()) {
2753 Slog.i(TAG, "Safe mode, skipping checkPackageChanges()");
2754 return;
2755 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07002756
Makoto Onuki22fcc682016-05-17 14:52:19 -07002757 final long start = injectElapsedRealtime();
2758 try {
2759 final ArrayList<PackageWithUser> gonePackages = new ArrayList<>();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002760
Makoto Onuki22fcc682016-05-17 14:52:19 -07002761 synchronized (mLock) {
2762 final ShortcutUser user = getUserShortcutsLocked(ownerUserId);
2763
2764 // Find packages that have been uninstalled.
2765 user.forAllPackageItems(spi -> {
2766 if (spi.getPackageInfo().isShadow()) {
2767 return; // Don't delete shadow information.
2768 }
2769 if (!isPackageInstalled(spi.getPackageName(), spi.getPackageUserId())) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002770 if (DEBUG) {
2771 Slog.d(TAG, "Uninstalled: " + spi.getPackageName()
2772 + " user " + spi.getPackageUserId());
2773 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002774 gonePackages.add(PackageWithUser.of(spi));
2775 }
2776 });
2777 if (gonePackages.size() > 0) {
2778 for (int i = gonePackages.size() - 1; i >= 0; i--) {
2779 final PackageWithUser pu = gonePackages.get(i);
Makoto Onukib08790c2016-06-23 14:05:46 -07002780 cleanUpPackageLocked(pu.packageName, ownerUserId, pu.userId,
2781 /* appStillExists = */ false);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002782 }
Makoto Onukid99c6f02016-03-28 11:02:54 -07002783 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002784
Makoto Onuki248a0ef2016-11-03 15:59:01 -07002785 rescanUpdatedPackagesLocked(ownerUserId, user.getLastAppScanTime());
Makoto Onuki0acbb142016-03-22 17:02:57 -07002786 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002787 } finally {
2788 logDurationStat(Stats.CHECK_PACKAGE_CHANGES, start);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002789 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002790 verifyStates();
Makoto Onukicdc78f72016-03-21 15:47:52 -07002791 }
2792
Makoto Onuki248a0ef2016-11-03 15:59:01 -07002793 private void rescanUpdatedPackagesLocked(@UserIdInt int userId, long lastScanTime) {
Makoto Onuki377b7972016-08-09 14:43:55 -07002794 final ShortcutUser user = getUserShortcutsLocked(userId);
2795
Makoto Onuki33663282016-08-22 16:19:04 -07002796 // Note after each OTA, we'll need to rescan all system apps, as their lastUpdateTime
2797 // is not reliable.
Makoto Onuki377b7972016-08-09 14:43:55 -07002798 final long now = injectCurrentTimeMillis();
Makoto Onuki33663282016-08-22 16:19:04 -07002799 final boolean afterOta =
2800 !injectBuildFingerprint().equals(user.getLastAppScanOsFingerprint());
Makoto Onuki377b7972016-08-09 14:43:55 -07002801
2802 // Then for each installed app, publish manifest shortcuts when needed.
Makoto Onuki33663282016-08-22 16:19:04 -07002803 forUpdatedPackages(userId, lastScanTime, afterOta, ai -> {
Makoto Onuki377b7972016-08-09 14:43:55 -07002804 user.attemptToRestoreIfNeededAndSave(this, ai.packageName, userId);
Makoto Onuki248a0ef2016-11-03 15:59:01 -07002805
2806 user.rescanPackageIfNeeded(ai.packageName, /* forceRescan= */ true);
Makoto Onuki377b7972016-08-09 14:43:55 -07002807 });
2808
2809 // Write the time just before the scan, because there may be apps that have just
2810 // been updated, and we want to catch them in the next time.
2811 user.setLastAppScanTime(now);
Makoto Onuki33663282016-08-22 16:19:04 -07002812 user.setLastAppScanOsFingerprint(injectBuildFingerprint());
Makoto Onuki377b7972016-08-09 14:43:55 -07002813 scheduleSaveUser(userId);
2814 }
2815
Makoto Onuki0acbb142016-03-22 17:02:57 -07002816 private void handlePackageAdded(String packageName, @UserIdInt int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07002817 if (DEBUG) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07002818 Slog.d(TAG, String.format("handlePackageAdded: %s user=%d", packageName, userId));
2819 }
2820 synchronized (mLock) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002821 final ShortcutUser user = getUserShortcutsLocked(userId);
2822 user.attemptToRestoreIfNeededAndSave(this, packageName, userId);
Makoto Onuki64183d52016-08-08 14:11:34 -07002823 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002824 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002825 verifyStates();
Makoto Onuki0acbb142016-03-22 17:02:57 -07002826 }
2827
2828 private void handlePackageUpdateFinished(String packageName, @UserIdInt int userId) {
Makoto Onuki905e8852016-03-28 10:40:58 -07002829 if (DEBUG) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002830 Slog.d(TAG, String.format("handlePackageUpdateFinished: %s user=%d",
2831 packageName, userId));
Makoto Onuki0acbb142016-03-22 17:02:57 -07002832 }
2833 synchronized (mLock) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002834 final ShortcutUser user = getUserShortcutsLocked(userId);
2835 user.attemptToRestoreIfNeededAndSave(this, packageName, userId);
Makoto Onuki39686e82016-04-13 18:03:00 -07002836
Makoto Onuki22fcc682016-05-17 14:52:19 -07002837 if (isPackageInstalled(packageName, userId)) {
Makoto Onuki64183d52016-08-08 14:11:34 -07002838 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onuki39686e82016-04-13 18:03:00 -07002839 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07002840 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002841 verifyStates();
Makoto Onuki0acbb142016-03-22 17:02:57 -07002842 }
2843
Makoto Onuki2e210c42016-03-30 08:30:36 -07002844 private void handlePackageRemoved(String packageName, @UserIdInt int packageUserId) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07002845 if (DEBUG) {
Makoto Onuki2e210c42016-03-30 08:30:36 -07002846 Slog.d(TAG, String.format("handlePackageRemoved: %s user=%d", packageName,
2847 packageUserId));
Makoto Onukicdc78f72016-03-21 15:47:52 -07002848 }
Makoto Onukib08790c2016-06-23 14:05:46 -07002849 cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ false);
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002850
2851 verifyStates();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002852 }
2853
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002854 private void handlePackageDataCleared(String packageName, int packageUserId) {
2855 if (DEBUG) {
2856 Slog.d(TAG, String.format("handlePackageDataCleared: %s user=%d", packageName,
2857 packageUserId));
Makoto Onukicdc78f72016-03-21 15:47:52 -07002858 }
Makoto Onukib08790c2016-06-23 14:05:46 -07002859 cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ true);
2860
2861 verifyStates();
2862 }
2863
2864 private void handlePackageChanged(String packageName, int packageUserId) {
2865 if (DEBUG) {
2866 Slog.d(TAG, String.format("handlePackageChanged: %s user=%d", packageName,
2867 packageUserId));
2868 }
2869
2870 // Activities may be disabled or enabled. Just rescan the package.
2871 synchronized (mLock) {
2872 final ShortcutUser user = getUserShortcutsLocked(packageUserId);
2873
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002874 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07002875 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002876
2877 verifyStates();
Makoto Onukicdc78f72016-03-21 15:47:52 -07002878 }
2879
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002880 // === PackageManager interaction ===
Makoto Onuki0acbb142016-03-22 17:02:57 -07002881
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002882 /**
2883 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
2884 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002885 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002886 final PackageInfo getPackageInfoWithSignatures(String packageName, @UserIdInt int userId) {
2887 return getPackageInfo(packageName, userId, true);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002888 }
2889
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002890 /**
2891 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
2892 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002893 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002894 final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId) {
2895 return getPackageInfo(packageName, userId, false);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002896 }
2897
Makoto Onuki905e8852016-03-28 10:40:58 -07002898 int injectGetPackageUid(@NonNull String packageName, @UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002899 final long token = injectClearCallingIdentity();
Makoto Onuki905e8852016-03-28 10:40:58 -07002900 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002901 return mIPackageManager.getPackageUid(packageName, PACKAGE_MATCH_FLAGS, userId);
Makoto Onuki905e8852016-03-28 10:40:58 -07002902 } catch (RemoteException e) {
2903 // Shouldn't happen.
2904 Slog.wtf(TAG, "RemoteException", e);
2905 return -1;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002906 } finally {
2907 injectRestoreCallingIdentity(token);
Makoto Onuki905e8852016-03-28 10:40:58 -07002908 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07002909 }
2910
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002911 /**
2912 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
2913 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002914 @Nullable
Makoto Onuki0acbb142016-03-22 17:02:57 -07002915 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002916 final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId,
2917 boolean getSignatures) {
2918 return isInstalledOrNull(injectPackageInfoWithUninstalled(
2919 packageName, userId, getSignatures));
2920 }
2921
2922 /**
2923 * Do not use directly; this returns uninstalled packages too.
2924 */
2925 @Nullable
2926 @VisibleForTesting
2927 PackageInfo injectPackageInfoWithUninstalled(String packageName, @UserIdInt int userId,
Makoto Onuki0acbb142016-03-22 17:02:57 -07002928 boolean getSignatures) {
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07002929 final long start = injectElapsedRealtime();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002930 final long token = injectClearCallingIdentity();
Makoto Onuki0acbb142016-03-22 17:02:57 -07002931 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002932 return mIPackageManager.getPackageInfo(
2933 packageName, PACKAGE_MATCH_FLAGS
2934 | (getSignatures ? PackageManager.GET_SIGNATURES : 0), userId);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002935 } catch (RemoteException e) {
2936 // Shouldn't happen.
2937 Slog.wtf(TAG, "RemoteException", e);
2938 return null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002939 } finally {
2940 injectRestoreCallingIdentity(token);
Makoto Onuki2e210c42016-03-30 08:30:36 -07002941
2942 logDurationStat(
2943 (getSignatures ? Stats.GET_PACKAGE_INFO_WITH_SIG : Stats.GET_PACKAGE_INFO),
2944 start);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002945 }
2946 }
2947
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002948 /**
2949 * Returns {@link ApplicationInfo} unless it's uninstalled or disabled.
2950 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002951 @Nullable
Makoto Onuki905e8852016-03-28 10:40:58 -07002952 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002953 final ApplicationInfo getApplicationInfo(String packageName, @UserIdInt int userId) {
2954 return isInstalledOrNull(injectApplicationInfoWithUninstalled(packageName, userId));
2955 }
2956
2957 /**
2958 * Do not use directly; this returns uninstalled packages too.
2959 */
2960 @Nullable
2961 @VisibleForTesting
2962 ApplicationInfo injectApplicationInfoWithUninstalled(
2963 String packageName, @UserIdInt int userId) {
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07002964 final long start = injectElapsedRealtime();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002965 final long token = injectClearCallingIdentity();
Makoto Onuki905e8852016-03-28 10:40:58 -07002966 try {
2967 return mIPackageManager.getApplicationInfo(packageName, PACKAGE_MATCH_FLAGS, userId);
2968 } catch (RemoteException e) {
2969 // Shouldn't happen.
2970 Slog.wtf(TAG, "RemoteException", e);
2971 return null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002972 } finally {
2973 injectRestoreCallingIdentity(token);
Makoto Onuki2e210c42016-03-30 08:30:36 -07002974
2975 logDurationStat(Stats.GET_APPLICATION_INFO, start);
Makoto Onuki905e8852016-03-28 10:40:58 -07002976 }
2977 }
2978
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002979 /**
2980 * Returns {@link ActivityInfo} with its metadata unless it's uninstalled or disabled.
2981 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002982 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002983 final ActivityInfo getActivityInfoWithMetadata(ComponentName activity, @UserIdInt int userId) {
2984 return isInstalledOrNull(injectGetActivityInfoWithMetadataWithUninstalled(
2985 activity, userId));
2986 }
2987
2988 /**
2989 * Do not use directly; this returns uninstalled packages too.
2990 */
2991 @Nullable
2992 @VisibleForTesting
2993 ActivityInfo injectGetActivityInfoWithMetadataWithUninstalled(
2994 ComponentName activity, @UserIdInt int userId) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002995 final long start = injectElapsedRealtime();
2996 final long token = injectClearCallingIdentity();
2997 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07002998 return mIPackageManager.getActivityInfo(activity,
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002999 (PACKAGE_MATCH_FLAGS | PackageManager.GET_META_DATA), userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003000 } catch (RemoteException e) {
3001 // Shouldn't happen.
3002 Slog.wtf(TAG, "RemoteException", e);
3003 return null;
3004 } finally {
3005 injectRestoreCallingIdentity(token);
3006
Makoto Onukib08790c2016-06-23 14:05:46 -07003007 logDurationStat(Stats.GET_ACTIVITY_WITH_METADATA, start);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003008 }
3009 }
3010
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003011 /**
3012 * Return all installed and enabled packages.
3013 */
3014 @NonNull
Makoto Onuki22fcc682016-05-17 14:52:19 -07003015 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003016 final List<PackageInfo> getInstalledPackages(@UserIdInt int userId) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07003017 final long start = injectElapsedRealtime();
3018 final long token = injectClearCallingIdentity();
3019 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003020 final List<PackageInfo> all = injectGetPackagesWithUninstalled(userId);
3021
3022 all.removeIf(PACKAGE_NOT_INSTALLED);
3023
3024 return all;
Makoto Onuki22fcc682016-05-17 14:52:19 -07003025 } catch (RemoteException e) {
3026 // Shouldn't happen.
3027 Slog.wtf(TAG, "RemoteException", e);
3028 return null;
3029 } finally {
3030 injectRestoreCallingIdentity(token);
3031
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003032 logDurationStat(Stats.GET_INSTALLED_PACKAGES, start);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003033 }
3034 }
3035
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003036 /**
3037 * Do not use directly; this returns uninstalled packages too.
3038 */
3039 @NonNull
3040 @VisibleForTesting
3041 List<PackageInfo> injectGetPackagesWithUninstalled(@UserIdInt int userId)
3042 throws RemoteException {
3043 final ParceledListSlice<PackageInfo> parceledList =
3044 mIPackageManager.getInstalledPackages(PACKAGE_MATCH_FLAGS, userId);
3045 if (parceledList == null) {
3046 return Collections.emptyList();
3047 }
3048 return parceledList.getList();
3049 }
3050
Makoto Onuki33663282016-08-22 16:19:04 -07003051 private void forUpdatedPackages(@UserIdInt int userId, long lastScanTime, boolean afterOta,
Makoto Onuki22fcc682016-05-17 14:52:19 -07003052 Consumer<ApplicationInfo> callback) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003053 if (DEBUG) {
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003054 Slog.d(TAG, "forUpdatedPackages for user " + userId + ", lastScanTime=" + lastScanTime
3055 + " afterOta=" + afterOta);
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003056 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003057 final List<PackageInfo> list = getInstalledPackages(userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003058 for (int i = list.size() - 1; i >= 0; i--) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003059 final PackageInfo pi = list.get(i);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003060
Makoto Onuki64183d52016-08-08 14:11:34 -07003061 // If the package has been updated since the last scan time, then scan it.
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003062 // Also if it's right after an OTA, always re-scan all apps anyway, since the
3063 // shortcut parser might have changed.
3064 if (afterOta || (pi.lastUpdateTime >= lastScanTime)) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003065 if (DEBUG) {
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003066 Slog.d(TAG, "Found updated package " + pi.packageName
3067 + " updateTime=" + pi.lastUpdateTime);
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003068 }
3069 callback.accept(pi.applicationInfo);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003070 }
3071 }
3072 }
3073
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003074 private boolean isApplicationFlagSet(@NonNull String packageName, int userId, int flags) {
3075 final ApplicationInfo ai = injectApplicationInfoWithUninstalled(packageName, userId);
Makoto Onuki905e8852016-03-28 10:40:58 -07003076 return (ai != null) && ((ai.flags & flags) == flags);
3077 }
3078
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003079 private static boolean isInstalled(@Nullable ApplicationInfo ai) {
3080 return (ai != null) && (ai.flags & ApplicationInfo.FLAG_INSTALLED) != 0;
3081 }
3082
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08003083 private static boolean isEphemeralApp(@Nullable ApplicationInfo ai) {
Svetoslav Ganov096d3042017-01-30 16:34:13 -08003084 return (ai != null) && ai.isInstantApp();
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08003085 }
3086
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003087 private static boolean isInstalled(@Nullable PackageInfo pi) {
3088 return (pi != null) && isInstalled(pi.applicationInfo);
3089 }
3090
3091 private static boolean isInstalled(@Nullable ActivityInfo ai) {
3092 return (ai != null) && isInstalled(ai.applicationInfo);
3093 }
3094
3095 private static ApplicationInfo isInstalledOrNull(ApplicationInfo ai) {
3096 return isInstalled(ai) ? ai : null;
3097 }
3098
3099 private static PackageInfo isInstalledOrNull(PackageInfo pi) {
3100 return isInstalled(pi) ? pi : null;
3101 }
3102
3103 private static ActivityInfo isInstalledOrNull(ActivityInfo ai) {
3104 return isInstalled(ai) ? ai : null;
3105 }
3106
Makoto Onuki2e210c42016-03-30 08:30:36 -07003107 boolean isPackageInstalled(String packageName, int userId) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003108 return getApplicationInfo(packageName, userId) != null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003109 }
3110
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08003111 boolean isEphemeralApp(String packageName, int userId) {
3112 return isEphemeralApp(getApplicationInfo(packageName, userId));
3113 }
3114
Makoto Onuki22fcc682016-05-17 14:52:19 -07003115 @Nullable
3116 XmlResourceParser injectXmlMetaData(ActivityInfo activityInfo, String key) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07003117 return activityInfo.loadXmlMetaData(mContext.getPackageManager(), key);
Makoto Onuki39686e82016-04-13 18:03:00 -07003118 }
3119
Makoto Onuki157b1622016-06-02 16:13:10 -07003120 @Nullable
3121 Resources injectGetResourcesForApplicationAsUser(String packageName, int userId) {
3122 final long start = injectElapsedRealtime();
3123 final long token = injectClearCallingIdentity();
3124 try {
3125 return mContext.getPackageManager().getResourcesForApplicationAsUser(
3126 packageName, userId);
3127 } catch (NameNotFoundException e) {
3128 Slog.e(TAG, "Resources for package " + packageName + " not found");
3129 return null;
3130 } finally {
3131 injectRestoreCallingIdentity(token);
3132
3133 logDurationStat(Stats.GET_APPLICATION_RESOURCES, start);
3134 }
3135 }
3136
Makoto Onukib08790c2016-06-23 14:05:46 -07003137 private Intent getMainActivityIntent() {
3138 final Intent intent = new Intent(Intent.ACTION_MAIN);
3139 intent.addCategory(LAUNCHER_INTENT_CATEGORY);
3140 return intent;
3141 }
3142
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003143 /**
3144 * Same as queryIntentActivitiesAsUser, except it makes sure the package is installed,
3145 * and only returns exported activities.
3146 */
3147 @NonNull
3148 @VisibleForTesting
3149 List<ResolveInfo> queryActivities(@NonNull Intent baseIntent,
3150 @NonNull String packageName, @Nullable ComponentName activity, int userId) {
3151
3152 baseIntent.setPackage(Preconditions.checkNotNull(packageName));
3153 if (activity != null) {
3154 baseIntent.setComponent(activity);
3155 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08003156 return queryActivities(baseIntent, userId, /* exportedOnly =*/ true);
3157 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003158
Makoto Onuki2d895c32016-12-02 15:48:40 -08003159 @NonNull
3160 List<ResolveInfo> queryActivities(@NonNull Intent intent, int userId,
3161 boolean exportedOnly) {
3162 final List<ResolveInfo> resolved;
3163 final long token = injectClearCallingIdentity();
3164 try {
3165 resolved =
3166 mContext.getPackageManager().queryIntentActivitiesAsUser(
3167 intent, PACKAGE_MATCH_FLAGS, userId);
3168 } finally {
3169 injectRestoreCallingIdentity(token);
3170 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003171 if (resolved == null || resolved.size() == 0) {
3172 return EMPTY_RESOLVE_INFO;
3173 }
3174 // Make sure the package is installed.
3175 if (!isInstalled(resolved.get(0).activityInfo)) {
3176 return EMPTY_RESOLVE_INFO;
3177 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08003178 if (exportedOnly) {
3179 resolved.removeIf(ACTIVITY_NOT_EXPORTED);
3180 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003181 return resolved;
3182 }
3183
3184 /**
3185 * Return the main activity that is enabled and exported. If multiple activities are found,
3186 * return the first one.
3187 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003188 @Nullable
3189 ComponentName injectGetDefaultMainActivity(@NonNull String packageName, int userId) {
3190 final long start = injectElapsedRealtime();
Makoto Onukib08790c2016-06-23 14:05:46 -07003191 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07003192 final List<ResolveInfo> resolved =
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003193 queryActivities(getMainActivityIntent(), packageName, null, userId);
3194 return resolved.size() == 0 ? null : resolved.get(0).activityInfo.getComponentName();
Makoto Onukib08790c2016-06-23 14:05:46 -07003195 } finally {
Makoto Onukib08790c2016-06-23 14:05:46 -07003196 logDurationStat(Stats.GET_LAUNCHER_ACTIVITY, start);
3197 }
3198 }
3199
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003200 /**
3201 * Return whether an activity is enabled, exported and main.
3202 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003203 boolean injectIsMainActivity(@NonNull ComponentName activity, int userId) {
3204 final long start = injectElapsedRealtime();
Makoto Onukib08790c2016-06-23 14:05:46 -07003205 try {
Makoto Onuki2d895c32016-12-02 15:48:40 -08003206 if (DUMMY_MAIN_ACTIVITY.equals(activity.getClassName())) {
3207 return true;
3208 }
3209 final List<ResolveInfo> resolved = queryActivities(
3210 getMainActivityIntent(), activity.getPackageName(), activity, userId);
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003211 return resolved.size() > 0;
Makoto Onukib08790c2016-06-23 14:05:46 -07003212 } finally {
Makoto Onukib08790c2016-06-23 14:05:46 -07003213 logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start);
3214 }
3215 }
3216
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003217 /**
Makoto Onuki2d895c32016-12-02 15:48:40 -08003218 * Create a dummy "main activity" component name which is used to create a dynamic shortcut
3219 * with no main activity temporarily.
3220 */
3221 @NonNull
3222 ComponentName getDummyMainActivity(@NonNull String packageName) {
3223 return new ComponentName(packageName, DUMMY_MAIN_ACTIVITY);
3224 }
3225
Makoto Onuki255461f2017-01-10 11:47:25 -08003226 boolean isDummyMainActivity(@Nullable ComponentName name) {
3227 return name != null && DUMMY_MAIN_ACTIVITY.equals(name.getClassName());
3228 }
3229
Makoto Onuki2d895c32016-12-02 15:48:40 -08003230 /**
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003231 * Return all the enabled, exported and main activities from a package.
3232 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003233 @NonNull
3234 List<ResolveInfo> injectGetMainActivities(@NonNull String packageName, int userId) {
3235 final long start = injectElapsedRealtime();
Makoto Onukib08790c2016-06-23 14:05:46 -07003236 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003237 return queryActivities(getMainActivityIntent(), packageName, null, userId);
Makoto Onukib08790c2016-06-23 14:05:46 -07003238 } finally {
Makoto Onukib08790c2016-06-23 14:05:46 -07003239 logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start);
3240 }
3241 }
3242
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003243 /**
3244 * Return whether an activity is enabled and exported.
3245 */
3246 @VisibleForTesting
3247 boolean injectIsActivityEnabledAndExported(
3248 @NonNull ComponentName activity, @UserIdInt int userId) {
3249 final long start = injectElapsedRealtime();
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003250 try {
3251 return queryActivities(new Intent(), activity.getPackageName(), activity, userId)
3252 .size() > 0;
3253 } finally {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003254 logDurationStat(Stats.IS_ACTIVITY_ENABLED, start);
3255 }
3256 }
3257
Makoto Onuki2d895c32016-12-02 15:48:40 -08003258 /**
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003259 * Get the {@link LauncherApps#ACTION_CONFIRM_PIN_SHORTCUT} or
3260 * {@link LauncherApps#ACTION_CONFIRM_PIN_APPWIDGET} activity in a given package depending on
3261 * the requestType.
Makoto Onuki2d895c32016-12-02 15:48:40 -08003262 */
3263 @Nullable
3264 ComponentName injectGetPinConfirmationActivity(@NonNull String launcherPackageName,
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003265 int launcherUserId, int requestType) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08003266 Preconditions.checkNotNull(launcherPackageName);
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003267 String action = requestType == LauncherApps.PinItemRequest.REQUEST_TYPE_SHORTCUT ?
3268 LauncherApps.ACTION_CONFIRM_PIN_SHORTCUT :
3269 LauncherApps.ACTION_CONFIRM_PIN_APPWIDGET;
Makoto Onuki2d895c32016-12-02 15:48:40 -08003270
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003271 final Intent confirmIntent = new Intent(action).setPackage(launcherPackageName);
Makoto Onuki2d895c32016-12-02 15:48:40 -08003272 final List<ResolveInfo> candidates = queryActivities(
3273 confirmIntent, launcherUserId, /* exportedOnly =*/ false);
3274 for (ResolveInfo ri : candidates) {
3275 return ri.activityInfo.getComponentName();
3276 }
3277 return null;
3278 }
3279
Makoto Onukib08790c2016-06-23 14:05:46 -07003280 boolean injectIsSafeModeEnabled() {
3281 final long token = injectClearCallingIdentity();
3282 try {
3283 return IWindowManager.Stub
3284 .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE))
3285 .isSafeModeEnabled();
3286 } catch (RemoteException e) {
3287 return false; // Shouldn't happen though.
3288 } finally {
3289 injectRestoreCallingIdentity(token);
3290 }
3291 }
3292
Makoto Onuki2d895c32016-12-02 15:48:40 -08003293 /**
3294 * If {@code userId} is of a managed profile, return the parent user ID. Otherwise return
3295 * itself.
3296 */
3297 int getParentOrSelfUserId(int userId) {
3298 final long token = injectClearCallingIdentity();
3299 try {
3300 final UserInfo parent = mUserManager.getProfileParent(userId);
3301 return (parent != null) ? parent.id : userId;
3302 } finally {
3303 injectRestoreCallingIdentity(token);
3304 }
3305 }
3306
Sunny Goyal87a563e2017-01-01 19:42:45 -08003307 void injectSendIntentSender(IntentSender intentSender, Intent extras) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08003308 if (intentSender == null) {
3309 return;
3310 }
3311 try {
Sunny Goyal87a563e2017-01-01 19:42:45 -08003312 intentSender.sendIntent(mContext, /* code= */ 0, extras,
Makoto Onuki2d895c32016-12-02 15:48:40 -08003313 /* onFinished=*/ null, /* handler= */ null);
3314 } catch (SendIntentException e) {
3315 Slog.w(TAG, "sendIntent failed().", e);
3316 }
3317 }
3318
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003319 // === Backup & restore ===
3320
Makoto Onuki0acbb142016-03-22 17:02:57 -07003321 boolean shouldBackupApp(String packageName, int userId) {
Makoto Onuki905e8852016-03-28 10:40:58 -07003322 return isApplicationFlagSet(packageName, userId, ApplicationInfo.FLAG_ALLOW_BACKUP);
Makoto Onuki0acbb142016-03-22 17:02:57 -07003323 }
3324
Makoto Onuki2e210c42016-03-30 08:30:36 -07003325 boolean shouldBackupApp(PackageInfo pi) {
3326 return (pi.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0;
3327 }
3328
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003329 @Override
Makoto Onuki2e210c42016-03-30 08:30:36 -07003330 public byte[] getBackupPayload(@UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003331 enforceSystem();
3332 if (DEBUG) {
3333 Slog.d(TAG, "Backing up user " + userId);
3334 }
3335 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003336 if (!isUserUnlockedL(userId)) {
3337 wtf("Can't backup: user " + userId + " is locked or not running");
3338 return null;
3339 }
3340
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003341 final ShortcutUser user = getUserShortcutsLocked(userId);
3342 if (user == null) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003343 wtf("Can't backup: user not found: id=" + userId);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003344 return null;
3345 }
3346
Makoto Onukic8c33292016-09-12 16:36:59 -07003347 // Update the signatures for all packages.
3348 user.forAllPackageItems(spi -> spi.refreshPackageSignatureAndSave());
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003349
Makoto Onukic8c33292016-09-12 16:36:59 -07003350 // Set the version code for the launchers.
3351 // We shouldn't do this for publisher packages, because we don't want to update the
3352 // version code without rescanning the manifest.
3353 user.forAllLaunchers(launcher -> launcher.ensureVersionInfo());
3354
3355 // Save to the filesystem.
3356 scheduleSaveUser(userId);
3357 saveDirtyInfo();
3358
3359 // Then create the backup payload.
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003360 final ByteArrayOutputStream os = new ByteArrayOutputStream(32 * 1024);
3361 try {
3362 saveUserInternalLocked(userId, os, /* forBackup */ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07003363 } catch (XmlPullParserException | IOException e) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003364 // Shouldn't happen.
3365 Slog.w(TAG, "Backup failed.", e);
3366 return null;
3367 }
3368 return os.toByteArray();
3369 }
3370 }
3371
3372 @Override
Makoto Onuki2e210c42016-03-30 08:30:36 -07003373 public void applyRestore(byte[] payload, @UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003374 enforceSystem();
3375 if (DEBUG) {
3376 Slog.d(TAG, "Restoring user " + userId);
3377 }
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003378 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003379 if (!isUserUnlockedL(userId)) {
3380 wtf("Can't restore: user " + userId + " is locked or not running");
3381 return;
3382 }
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003383 // Actually do restore.
3384 final ShortcutUser restored;
Makoto Onuki02f338e2016-07-29 09:40:40 -07003385 final ByteArrayInputStream is = new ByteArrayInputStream(payload);
3386 try {
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003387 restored = loadUserInternal(userId, is, /* fromBackup */ true);
3388 } catch (XmlPullParserException | IOException | InvalidFileFormatException e) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003389 Slog.w(TAG, "Restoration failed.", e);
3390 return;
3391 }
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003392 getUserShortcutsLocked(userId).mergeRestoredFile(restored);
Makoto Onuki2e210c42016-03-30 08:30:36 -07003393
Makoto Onuki377b7972016-08-09 14:43:55 -07003394 // Rescan all packages to re-publish manifest shortcuts and do other checks.
3395 rescanUpdatedPackagesLocked(userId,
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003396 0 // lastScanTime = 0; rescan all packages.
3397 );
Makoto Onuki2e210c42016-03-30 08:30:36 -07003398
3399 saveUserLocked(userId);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003400 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07003401 }
3402
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003403 // === Dump ===
3404
3405 @Override
3406 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Makoto Onuki76269922016-07-15 14:58:54 -07003407 enforceCallingOrSelfPermission(android.Manifest.permission.DUMP,
3408 "can't dump by this caller");
3409 boolean checkin = false;
3410 boolean clear = false;
3411 if (args != null) {
3412 for (String arg : args) {
3413 if ("-c".equals(arg)) {
3414 checkin = true;
3415 } else if ("--checkin".equals(arg)) {
3416 checkin = true;
3417 clear = true;
3418 }
3419 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003420 }
Makoto Onuki76269922016-07-15 14:58:54 -07003421
3422 if (checkin) {
3423 dumpCheckin(pw, clear);
3424 } else {
3425 dumpInner(pw);
3426 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003427 }
3428
Makoto Onuki76269922016-07-15 14:58:54 -07003429 private void dumpInner(PrintWriter pw) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003430 synchronized (mLock) {
3431 final long now = injectCurrentTimeMillis();
3432 pw.print("Now: [");
3433 pw.print(now);
3434 pw.print("] ");
3435 pw.print(formatTime(now));
Makoto Onuki55046222016-03-08 10:49:47 -08003436
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003437 pw.print(" Raw last reset: [");
3438 pw.print(mRawLastResetTime);
3439 pw.print("] ");
3440 pw.print(formatTime(mRawLastResetTime));
3441
3442 final long last = getLastResetTimeLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003443 pw.print(" Last reset: [");
3444 pw.print(last);
3445 pw.print("] ");
3446 pw.print(formatTime(last));
3447
Makoto Onuki55046222016-03-08 10:49:47 -08003448 final long next = getNextResetTimeLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003449 pw.print(" Next reset: [");
3450 pw.print(next);
3451 pw.print("] ");
3452 pw.print(formatTime(next));
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003453
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003454 pw.print(" Config:");
3455 pw.print(" Max icon dim: ");
3456 pw.println(mMaxIconDimension);
3457 pw.print(" Icon format: ");
3458 pw.println(mIconPersistFormat);
3459 pw.print(" Icon quality: ");
Makoto Onuki2e210c42016-03-30 08:30:36 -07003460 pw.println(mIconPersistQuality);
Makoto Onuki0033b2a2016-04-14 17:19:16 -07003461 pw.print(" saveDelayMillis: ");
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003462 pw.println(mSaveDelayMillis);
Makoto Onuki0033b2a2016-04-14 17:19:16 -07003463 pw.print(" resetInterval: ");
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003464 pw.println(mResetInterval);
Makoto Onuki0033b2a2016-04-14 17:19:16 -07003465 pw.print(" maxUpdatesPerInterval: ");
Makoto Onukib6d35232016-04-04 15:57:17 -07003466 pw.println(mMaxUpdatesPerInterval);
Makoto Onukib08790c2016-06-23 14:05:46 -07003467 pw.print(" maxShortcutsPerActivity: ");
Makoto Onukib5a012f2016-06-21 11:13:53 -07003468 pw.println(mMaxShortcuts);
Makoto Onuki55046222016-03-08 10:49:47 -08003469 pw.println();
3470
Makoto Onuki2e210c42016-03-30 08:30:36 -07003471 pw.println(" Stats:");
3472 synchronized (mStatLock) {
Makoto Onuki085a05c2016-08-19 11:39:29 -07003473 for (int i = 0; i < Stats.COUNT; i++) {
3474 dumpStatLS(pw, " ", i);
3475 }
Makoto Onuki2e210c42016-03-30 08:30:36 -07003476 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003477
Makoto Onukia2241832016-07-06 13:28:37 -07003478 pw.println();
3479 pw.print(" #Failures: ");
3480 pw.println(mWtfCount);
3481
3482 if (mLastWtfStacktrace != null) {
3483 pw.print(" Last failure stack trace: ");
3484 pw.println(Log.getStackTraceString(mLastWtfStacktrace));
3485 }
3486
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08003487 for (int i = 0; i < mUsers.size(); i++) {
3488 pw.println();
Makoto Onukic51b2872016-05-04 15:24:50 -07003489 mUsers.valueAt(i).dump(pw, " ");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003490 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003491
3492 pw.println();
3493 pw.println(" UID state:");
3494
3495 for (int i = 0; i < mUidState.size(); i++) {
3496 final int uid = mUidState.keyAt(i);
3497 final int state = mUidState.valueAt(i);
3498 pw.print(" UID=");
3499 pw.print(uid);
3500 pw.print(" state=");
3501 pw.print(state);
3502 if (isProcessStateForeground(state)) {
3503 pw.print(" [FG]");
3504 }
3505 pw.print(" last FG=");
3506 pw.print(mUidLastForegroundElapsedTime.get(uid));
3507 pw.println();
3508 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003509 }
3510 }
3511
Makoto Onuki41066a62016-03-09 16:18:44 -08003512 static String formatTime(long time) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003513 Time tobj = new Time();
3514 tobj.set(time);
3515 return tobj.format("%Y-%m-%d %H:%M:%S");
3516 }
3517
Makoto Onuki085a05c2016-08-19 11:39:29 -07003518 private void dumpStatLS(PrintWriter pw, String prefix, int statId) {
Makoto Onuki2e210c42016-03-30 08:30:36 -07003519 pw.print(prefix);
3520 final int count = mCountStats[statId];
3521 final long dur = mDurationStats[statId];
3522 pw.println(String.format("%s: count=%d, total=%dms, avg=%.1fms",
Makoto Onuki085a05c2016-08-19 11:39:29 -07003523 STAT_LABELS[statId], count, dur,
Makoto Onuki2e210c42016-03-30 08:30:36 -07003524 (count == 0 ? 0 : ((double) dur) / count)));
3525 }
3526
Makoto Onuki76269922016-07-15 14:58:54 -07003527 /**
3528 * Dumpsys for checkin.
3529 *
3530 * @param clear if true, clear the history information. Some other system services have this
3531 * behavior but shortcut service doesn't for now.
3532 */
3533 private void dumpCheckin(PrintWriter pw, boolean clear) {
3534 synchronized (mLock) {
3535 try {
3536 final JSONArray users = new JSONArray();
3537
3538 for (int i = 0; i < mUsers.size(); i++) {
3539 users.put(mUsers.valueAt(i).dumpCheckin(clear));
3540 }
3541
3542 final JSONObject result = new JSONObject();
3543
3544 result.put(KEY_SHORTCUT, users);
3545 result.put(KEY_LOW_RAM, injectIsLowRamDevice());
3546 result.put(KEY_ICON_SIZE, mMaxIconDimension);
3547
3548 pw.println(result.toString(1));
3549 } catch (JSONException e) {
3550 Slog.e(TAG, "Unable to write in json", e);
3551 }
3552 }
3553 }
3554
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003555 // === Shell support ===
3556
3557 @Override
3558 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003559 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003560
3561 enforceShell();
3562
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07003563 final long token = injectClearCallingIdentity();
3564 try {
Dianne Hackborn354736e2016-08-22 17:00:05 -07003565 final int status = (new MyShellCommand()).exec(this, in, out, err, args, callback,
3566 resultReceiver);
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07003567 resultReceiver.send(status, null);
3568 } finally {
3569 injectRestoreCallingIdentity(token);
3570 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003571 }
3572
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003573 static class CommandException extends Exception {
3574 public CommandException(String message) {
3575 super(message);
3576 }
3577 }
3578
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003579 /**
3580 * Handle "adb shell cmd".
3581 */
3582 private class MyShellCommand extends ShellCommand {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003583
3584 private int mUserId = UserHandle.USER_SYSTEM;
3585
Makoto Onuki02f338e2016-07-29 09:40:40 -07003586 private void parseOptionsLocked(boolean takeUser)
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003587 throws CommandException {
3588 String opt;
3589 while ((opt = getNextOption()) != null) {
3590 switch (opt) {
3591 case "--user":
3592 if (takeUser) {
3593 mUserId = UserHandle.parseUserArg(getNextArgRequired());
Makoto Onuki02f338e2016-07-29 09:40:40 -07003594 if (!isUserUnlockedL(mUserId)) {
Makoto Onukif34c3082016-07-13 10:25:25 -07003595 throw new CommandException(
3596 "User " + mUserId + " is not running or locked");
3597 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003598 break;
3599 }
3600 // fallthrough
3601 default:
3602 throw new CommandException("Unknown option: " + opt);
3603 }
3604 }
3605 }
3606
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003607 @Override
3608 public int onCommand(String cmd) {
3609 if (cmd == null) {
3610 return handleDefaultCommands(cmd);
3611 }
3612 final PrintWriter pw = getOutPrintWriter();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003613 try {
3614 switch (cmd) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003615 case "reset-throttling":
3616 handleResetThrottling();
3617 break;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003618 case "reset-all-throttling":
3619 handleResetAllThrottling();
3620 break;
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003621 case "override-config":
3622 handleOverrideConfig();
3623 break;
3624 case "reset-config":
3625 handleResetConfig();
3626 break;
3627 case "clear-default-launcher":
3628 handleClearDefaultLauncher();
3629 break;
3630 case "get-default-launcher":
3631 handleGetDefaultLauncher();
3632 break;
Makoto Onukiac214972016-04-04 10:19:45 -07003633 case "unload-user":
3634 handleUnloadUser();
3635 break;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003636 case "clear-shortcuts":
3637 handleClearShortcuts();
3638 break;
Makoto Onukib08790c2016-06-23 14:05:46 -07003639 case "verify-states": // hidden command to verify various internal states.
3640 handleVerifyStates();
3641 break;
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003642 default:
3643 return handleDefaultCommands(cmd);
3644 }
3645 } catch (CommandException e) {
3646 pw.println("Error: " + e.getMessage());
3647 return 1;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003648 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003649 pw.println("Success");
3650 return 0;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003651 }
3652
3653 @Override
3654 public void onHelp() {
3655 final PrintWriter pw = getOutPrintWriter();
3656 pw.println("Usage: cmd shortcut COMMAND [options ...]");
3657 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003658 pw.println("cmd shortcut reset-throttling [--user USER_ID]");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003659 pw.println(" Reset throttling for all packages and users");
3660 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003661 pw.println("cmd shortcut reset-all-throttling");
3662 pw.println(" Reset the throttling state for all users");
3663 pw.println();
Makoto Onuki4362a662016-03-08 18:59:09 -08003664 pw.println("cmd shortcut override-config CONFIG");
3665 pw.println(" Override the configuration for testing (will last until reboot)");
3666 pw.println();
3667 pw.println("cmd shortcut reset-config");
3668 pw.println(" Reset the configuration set with \"update-config\"");
3669 pw.println();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003670 pw.println("cmd shortcut clear-default-launcher [--user USER_ID]");
3671 pw.println(" Clear the cached default launcher");
3672 pw.println();
3673 pw.println("cmd shortcut get-default-launcher [--user USER_ID]");
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07003674 pw.println(" Show the default launcher");
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003675 pw.println();
Makoto Onukiac214972016-04-04 10:19:45 -07003676 pw.println("cmd shortcut unload-user [--user USER_ID]");
3677 pw.println(" Unload a user from the memory");
3678 pw.println(" (This should not affect any observable behavior)");
3679 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003680 pw.println("cmd shortcut clear-shortcuts [--user USER_ID] PACKAGE");
3681 pw.println(" Remove all shortcuts from a package, including pinned shortcuts");
3682 pw.println();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003683 }
3684
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003685 private void handleResetThrottling() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003686 synchronized (mLock) {
3687 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki4554d0e2016-03-14 15:51:41 -07003688
Makoto Onuki02f338e2016-07-29 09:40:40 -07003689 Slog.i(TAG, "cmd: handleResetThrottling: user=" + mUserId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003690
Makoto Onuki02f338e2016-07-29 09:40:40 -07003691 resetThrottlingInner(mUserId);
3692 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003693 }
3694
3695 private void handleResetAllThrottling() {
3696 Slog.i(TAG, "cmd: handleResetAllThrottling");
3697
3698 resetAllThrottlingInner();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003699 }
3700
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003701 private void handleOverrideConfig() throws CommandException {
Makoto Onuki4362a662016-03-08 18:59:09 -08003702 final String config = getNextArgRequired();
3703
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003704 Slog.i(TAG, "cmd: handleOverrideConfig: " + config);
3705
Makoto Onuki4362a662016-03-08 18:59:09 -08003706 synchronized (mLock) {
3707 if (!updateConfigurationLocked(config)) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003708 throw new CommandException("override-config failed. See logcat for details.");
Makoto Onuki4362a662016-03-08 18:59:09 -08003709 }
3710 }
Makoto Onuki4362a662016-03-08 18:59:09 -08003711 }
3712
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003713 private void handleResetConfig() {
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003714 Slog.i(TAG, "cmd: handleResetConfig");
3715
Makoto Onuki4362a662016-03-08 18:59:09 -08003716 synchronized (mLock) {
3717 loadConfigurationLocked();
3718 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003719 }
3720
3721 private void clearLauncher() {
3722 synchronized (mLock) {
Makoto Onuki10305202016-07-14 18:14:08 -07003723 getUserShortcutsLocked(mUserId).forceClearLauncher();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003724 }
3725 }
3726
3727 private void showLauncher() {
3728 synchronized (mLock) {
3729 // This ensures to set the cached launcher. Package name doesn't matter.
3730 hasShortcutHostPermissionInner("-", mUserId);
3731
3732 getOutPrintWriter().println("Launcher: "
Makoto Onuki10305202016-07-14 18:14:08 -07003733 + getUserShortcutsLocked(mUserId).getLastKnownLauncher());
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003734 }
3735 }
3736
3737 private void handleClearDefaultLauncher() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003738 synchronized (mLock) {
3739 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003740
Makoto Onuki02f338e2016-07-29 09:40:40 -07003741 clearLauncher();
3742 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003743 }
3744
3745 private void handleGetDefaultLauncher() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003746 synchronized (mLock) {
3747 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003748
Makoto Onuki02f338e2016-07-29 09:40:40 -07003749 clearLauncher();
3750 showLauncher();
3751 }
Makoto Onuki4362a662016-03-08 18:59:09 -08003752 }
Makoto Onukiac214972016-04-04 10:19:45 -07003753
3754 private void handleUnloadUser() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003755 synchronized (mLock) {
3756 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onukiac214972016-04-04 10:19:45 -07003757
Makoto Onuki02f338e2016-07-29 09:40:40 -07003758 Slog.i(TAG, "cmd: handleUnloadUser: user=" + mUserId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003759
Makoto Onuki02f338e2016-07-29 09:40:40 -07003760 ShortcutService.this.handleCleanupUser(mUserId);
3761 }
Makoto Onukiac214972016-04-04 10:19:45 -07003762 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003763
3764 private void handleClearShortcuts() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003765 synchronized (mLock) {
3766 parseOptionsLocked(/* takeUser =*/ true);
3767 final String packageName = getNextArgRequired();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003768
Makoto Onuki02f338e2016-07-29 09:40:40 -07003769 Slog.i(TAG, "cmd: handleClearShortcuts: user" + mUserId + ", " + packageName);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003770
Makoto Onuki02f338e2016-07-29 09:40:40 -07003771 ShortcutService.this.cleanUpPackageForAllLoadedUsers(packageName, mUserId,
3772 /* appStillExists = */ true);
3773 }
Makoto Onukib08790c2016-06-23 14:05:46 -07003774 }
3775
3776 private void handleVerifyStates() throws CommandException {
3777 try {
3778 verifyStatesForce(); // This will throw when there's an issue.
3779 } catch (Throwable th) {
3780 throw new CommandException(th.getMessage() + "\n" + Log.getStackTraceString(th));
3781 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003782 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003783 }
3784
3785 // === Unit test support ===
3786
3787 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07003788 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003789 long injectCurrentTimeMillis() {
3790 return System.currentTimeMillis();
3791 }
3792
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003793 @VisibleForTesting
3794 long injectElapsedRealtime() {
3795 return SystemClock.elapsedRealtime();
3796 }
3797
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003798 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07003799 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003800 int injectBinderCallingUid() {
3801 return getCallingUid();
3802 }
3803
Makoto Onuki31459242016-03-22 11:12:18 -07003804 private int getCallingUserId() {
Makoto Onuki4554d0e2016-03-14 15:51:41 -07003805 return UserHandle.getUserId(injectBinderCallingUid());
3806 }
3807
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07003808 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07003809 @VisibleForTesting
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07003810 long injectClearCallingIdentity() {
3811 return Binder.clearCallingIdentity();
3812 }
3813
3814 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07003815 @VisibleForTesting
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07003816 void injectRestoreCallingIdentity(long token) {
3817 Binder.restoreCallingIdentity(token);
3818 }
3819
Makoto Onuki33663282016-08-22 16:19:04 -07003820 // Injection point.
3821 @VisibleForTesting
3822 String injectBuildFingerprint() {
3823 return Build.FINGERPRINT;
3824 }
3825
Makoto Onukide667372016-03-15 14:29:20 -07003826 final void wtf(String message) {
Makoto Onukib08790c2016-06-23 14:05:46 -07003827 wtf(message, /* exception= */ null);
Makoto Onukide667372016-03-15 14:29:20 -07003828 }
3829
Makoto Onuki2e210c42016-03-30 08:30:36 -07003830 // Injection point.
Makoto Onukia2241832016-07-06 13:28:37 -07003831 void wtf(String message, Throwable e) {
3832 if (e == null) {
3833 e = new RuntimeException("Stacktrace");
3834 }
3835 synchronized (mLock) {
3836 mWtfCount++;
3837 mLastWtfStacktrace = new Exception("Last failure was logged here:");
3838 }
Makoto Onukide667372016-03-15 14:29:20 -07003839 Slog.wtf(TAG, message, e);
3840 }
3841
Makoto Onuki31459242016-03-22 11:12:18 -07003842 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003843 File injectSystemDataPath() {
3844 return Environment.getDataSystemDirectory();
3845 }
3846
Makoto Onuki31459242016-03-22 11:12:18 -07003847 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003848 File injectUserDataPath(@UserIdInt int userId) {
Makoto Onuki55046222016-03-08 10:49:47 -08003849 return new File(Environment.getDataSystemCeDirectory(userId), DIRECTORY_PER_USER);
3850 }
3851
Makoto Onuki4362a662016-03-08 18:59:09 -08003852 @VisibleForTesting
Makoto Onuki55046222016-03-08 10:49:47 -08003853 boolean injectIsLowRamDevice() {
3854 return ActivityManager.isLowRamDeviceStatic();
3855 }
3856
Makoto Onuki31459242016-03-22 11:12:18 -07003857 @VisibleForTesting
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003858 void injectRegisterUidObserver(IUidObserver observer, int which) {
3859 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003860 ActivityManager.getService().registerUidObserver(observer, which,
Dianne Hackborn5614bf52016-11-07 17:26:41 -08003861 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003862 } catch (RemoteException shouldntHappen) {
3863 }
3864 }
3865
Makoto Onuki55046222016-03-08 10:49:47 -08003866 File getUserBitmapFilePath(@UserIdInt int userId) {
3867 return new File(injectUserDataPath(userId), DIRECTORY_BITMAPS);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003868 }
3869
3870 @VisibleForTesting
Makoto Onuki31459242016-03-22 11:12:18 -07003871 SparseArray<ShortcutUser> getShortcutsForTest() {
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08003872 return mUsers;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003873 }
3874
3875 @VisibleForTesting
Makoto Onukib5a012f2016-06-21 11:13:53 -07003876 int getMaxShortcutsForTest() {
3877 return mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003878 }
3879
3880 @VisibleForTesting
Makoto Onukib6d35232016-04-04 15:57:17 -07003881 int getMaxUpdatesPerIntervalForTest() {
3882 return mMaxUpdatesPerInterval;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003883 }
3884
3885 @VisibleForTesting
Makoto Onuki4362a662016-03-08 18:59:09 -08003886 long getResetIntervalForTest() {
3887 return mResetInterval;
Makoto Onuki55046222016-03-08 10:49:47 -08003888 }
3889
3890 @VisibleForTesting
Makoto Onuki4362a662016-03-08 18:59:09 -08003891 int getMaxIconDimensionForTest() {
3892 return mMaxIconDimension;
3893 }
3894
3895 @VisibleForTesting
3896 CompressFormat getIconPersistFormatForTest() {
3897 return mIconPersistFormat;
3898 }
3899
3900 @VisibleForTesting
3901 int getIconPersistQualityForTest() {
3902 return mIconPersistQuality;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003903 }
Makoto Onuki41066a62016-03-09 16:18:44 -08003904
3905 @VisibleForTesting
Makoto Onuki22fcc682016-05-17 14:52:19 -07003906 ShortcutPackage getPackageShortcutForTest(String packageName, int userId) {
Makoto Onuki41066a62016-03-09 16:18:44 -08003907 synchronized (mLock) {
Makoto Onuki31459242016-03-22 11:12:18 -07003908 final ShortcutUser user = mUsers.get(userId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07003909 if (user == null) return null;
3910
Makoto Onuki22fcc682016-05-17 14:52:19 -07003911 return user.getAllPackagesForTest().get(packageName);
3912 }
3913 }
3914
3915 @VisibleForTesting
3916 ShortcutInfo getPackageShortcutForTest(String packageName, String shortcutId, int userId) {
3917 synchronized (mLock) {
Makoto Onukif34c3082016-07-13 10:25:25 -07003918 final ShortcutPackage pkg = getPackageShortcutForTest(packageName, userId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07003919 if (pkg == null) return null;
3920
3921 return pkg.findShortcutById(shortcutId);
Makoto Onuki41066a62016-03-09 16:18:44 -08003922 }
3923 }
Makoto Onuki7001a612016-05-27 13:24:28 -07003924
Makoto Onukifac592f2016-11-21 13:41:32 -08003925 @VisibleForTesting
3926 ShortcutLauncher getLauncherShortcutForTest(String packageName, int userId) {
3927 synchronized (mLock) {
3928 final ShortcutUser user = mUsers.get(userId);
3929 if (user == null) return null;
3930
3931 return user.getAllLaunchersForTest().get(PackageWithUser.of(userId, packageName));
3932 }
3933 }
3934
Makoto Onuki2d895c32016-12-02 15:48:40 -08003935 @VisibleForTesting
3936 ShortcutRequestPinProcessor getShortcutRequestPinProcessorForTest() {
3937 return mShortcutRequestPinProcessor;
3938 }
3939
Makoto Onuki7001a612016-05-27 13:24:28 -07003940 /**
3941 * Control whether {@link #verifyStates} should be performed. We always perform it during unit
3942 * tests.
3943 */
3944 @VisibleForTesting
3945 boolean injectShouldPerformVerification() {
3946 return DEBUG;
3947 }
3948
3949 /**
3950 * Check various internal states and throws if there's any inconsistency.
3951 * This is normally only enabled during unit tests.
3952 */
3953 final void verifyStates() {
3954 if (injectShouldPerformVerification()) {
3955 verifyStatesInner();
3956 }
3957 }
3958
Makoto Onukib08790c2016-06-23 14:05:46 -07003959 private final void verifyStatesForce() {
3960 verifyStatesInner();
3961 }
3962
Makoto Onuki7001a612016-05-27 13:24:28 -07003963 private void verifyStatesInner() {
Makoto Onuki10305202016-07-14 18:14:08 -07003964 synchronized (mLock) {
Makoto Onuki7001a612016-05-27 13:24:28 -07003965 forEachLoadedUserLocked(u -> u.forAllPackageItems(ShortcutPackageItem::verifyStates));
3966 }
3967 }
Makoto Onuki41066a62016-03-09 16:18:44 -08003968}