blob: 65c6f54c70bb28f47d252e2f9ecf415d043c835b [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;
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -080030import android.content.ContentResolver;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080031import android.content.Context;
32import android.content.Intent;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070033import android.content.IntentFilter;
Makoto Onuki2d895c32016-12-02 15:48:40 -080034import android.content.IntentSender;
35import android.content.IntentSender.SendIntentException;
Makoto Onuki22fcc682016-05-17 14:52:19 -070036import android.content.pm.ActivityInfo;
Makoto Onuki0acbb142016-03-22 17:02:57 -070037import android.content.pm.ApplicationInfo;
38import android.content.pm.IPackageManager;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080039import android.content.pm.IShortcutService;
40import android.content.pm.LauncherApps;
41import android.content.pm.LauncherApps.ShortcutQuery;
Makoto Onuki0acbb142016-03-22 17:02:57 -070042import android.content.pm.PackageInfo;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080043import android.content.pm.PackageManager;
Makoto Onuki20c95f82016-05-11 16:51:01 -070044import android.content.pm.PackageManager.NameNotFoundException;
Makoto Onuki2d5b4652016-03-11 16:09:54 -080045import android.content.pm.PackageManagerInternal;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080046import android.content.pm.ParceledListSlice;
Makoto Onuki2d5b4652016-03-11 16:09:54 -080047import android.content.pm.ResolveInfo;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080048import android.content.pm.ShortcutInfo;
Makoto Onuki2d895c32016-12-02 15:48:40 -080049import android.content.pm.ShortcutManager;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080050import android.content.pm.ShortcutServiceInternal;
51import android.content.pm.ShortcutServiceInternal.ShortcutChangeListener;
Makoto Onuki2d895c32016-12-02 15:48:40 -080052import android.content.pm.UserInfo;
Makoto Onuki157b1622016-06-02 16:13:10 -070053import android.content.res.Resources;
Makoto Onuki22fcc682016-05-17 14:52:19 -070054import android.content.res.XmlResourceParser;
Makoto Onuki55046222016-03-08 10:49:47 -080055import android.graphics.Bitmap;
56import android.graphics.Bitmap.CompressFormat;
Makoto Onuki55046222016-03-08 10:49:47 -080057import android.graphics.Canvas;
58import android.graphics.RectF;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080059import android.graphics.drawable.Icon;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070060import android.net.Uri;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080061import android.os.Binder;
Makoto Onuki33663282016-08-22 16:19:04 -070062import android.os.Build;
Sunny Goyal4ad6b572017-02-28 11:11:51 -080063import android.os.Bundle;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080064import android.os.Environment;
Makoto Onuki2e210c42016-03-30 08:30:36 -070065import android.os.FileUtils;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080066import android.os.Handler;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070067import android.os.LocaleList;
Makoto Onukiaa8b94a2016-03-17 13:14:05 -070068import android.os.Looper;
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -080069import android.os.Parcel;
Makoto Onuki55046222016-03-08 10:49:47 -080070import android.os.ParcelFileDescriptor;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080071import android.os.PersistableBundle;
72import android.os.Process;
73import android.os.RemoteException;
74import android.os.ResultReceiver;
Makoto Onuki55046222016-03-08 10:49:47 -080075import android.os.SELinux;
Makoto Onukib08790c2016-06-23 14:05:46 -070076import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070077import android.os.ShellCallback;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080078import android.os.ShellCommand;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -070079import android.os.SystemClock;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080080import android.os.UserHandle;
Makoto Onukicdc78f72016-03-21 15:47:52 -070081import android.os.UserManager;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080082import android.text.TextUtils;
83import android.text.format.Time;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080084import android.util.ArraySet;
85import android.util.AtomicFile;
Makoto Onuki4362a662016-03-08 18:59:09 -080086import android.util.KeyValueListParser;
Makoto Onukiac042502016-05-20 16:39:42 -070087import android.util.Log;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080088import android.util.Slog;
89import android.util.SparseArray;
Makoto Onuki02f338e2016-07-29 09:40:40 -070090import android.util.SparseBooleanArray;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -070091import android.util.SparseIntArray;
92import android.util.SparseLongArray;
Makoto Onuki55046222016-03-08 10:49:47 -080093import android.util.TypedValue;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080094import android.util.Xml;
Makoto Onukib08790c2016-06-23 14:05:46 -070095import android.view.IWindowManager;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080096
97import com.android.internal.annotations.GuardedBy;
98import com.android.internal.annotations.VisibleForTesting;
99import com.android.internal.os.BackgroundThread;
100import com.android.internal.util.FastXmlSerializer;
101import com.android.internal.util.Preconditions;
102import com.android.server.LocalServices;
103import com.android.server.SystemService;
Makoto Onukid99c6f02016-03-28 11:02:54 -0700104import com.android.server.pm.ShortcutUser.PackageWithUser;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800105
106import libcore.io.IoUtils;
107
Makoto Onuki76269922016-07-15 14:58:54 -0700108import org.json.JSONArray;
109import org.json.JSONException;
110import org.json.JSONObject;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800111import org.xmlpull.v1.XmlPullParser;
112import org.xmlpull.v1.XmlPullParserException;
113import org.xmlpull.v1.XmlSerializer;
114
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700115import java.io.BufferedInputStream;
116import java.io.BufferedOutputStream;
117import java.io.ByteArrayInputStream;
118import java.io.ByteArrayOutputStream;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800119import java.io.File;
120import java.io.FileDescriptor;
121import java.io.FileInputStream;
122import java.io.FileNotFoundException;
123import java.io.FileOutputStream;
124import java.io.IOException;
Makoto Onuki55046222016-03-08 10:49:47 -0800125import java.io.InputStream;
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700126import java.io.OutputStream;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800127import java.io.PrintWriter;
Makoto Onuki7001a612016-05-27 13:24:28 -0700128import java.lang.annotation.Retention;
129import java.lang.annotation.RetentionPolicy;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800130import java.net.URISyntaxException;
131import java.nio.charset.StandardCharsets;
132import java.util.ArrayList;
Makoto Onuki22fcc682016-05-17 14:52:19 -0700133import java.util.Collections;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800134import java.util.List;
Makoto Onukic51b2872016-05-04 15:24:50 -0700135import java.util.concurrent.atomic.AtomicBoolean;
Makoto Onuki2e210c42016-03-30 08:30:36 -0700136import java.util.function.Consumer;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800137import java.util.function.Predicate;
138
139/**
140 * TODO:
Makoto Onuki22fcc682016-05-17 14:52:19 -0700141 * - getIconMaxWidth()/getIconMaxHeight() should use xdpi and ydpi.
Makoto Onukib5a012f2016-06-21 11:13:53 -0700142 * -> But TypedValue.applyDimension() doesn't differentiate x and y..?
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800143 *
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700144 * - Detect when already registered instances are passed to APIs again, which might break
Makoto Onukib08790c2016-06-23 14:05:46 -0700145 * internal bitmap handling.
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800146 */
147public class ShortcutService extends IShortcutService.Stub {
Makoto Onuki55046222016-03-08 10:49:47 -0800148 static final String TAG = "ShortcutService";
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800149
Makoto Onuki7001a612016-05-27 13:24:28 -0700150 static final boolean DEBUG = false; // STOPSHIP if true
Makoto Onuki41066a62016-03-09 16:18:44 -0800151 static final boolean DEBUG_LOAD = false; // STOPSHIP if true
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700152 static final boolean DEBUG_PROCSTATE = false; // STOPSHIP if true
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800153
Makoto Onuki4362a662016-03-08 18:59:09 -0800154 @VisibleForTesting
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700155 static final long DEFAULT_RESET_INTERVAL_SEC = 24 * 60 * 60; // 1 day
Makoto Onuki4362a662016-03-08 18:59:09 -0800156
157 @VisibleForTesting
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700158 static final int DEFAULT_MAX_UPDATES_PER_INTERVAL = 10;
Makoto Onuki4362a662016-03-08 18:59:09 -0800159
160 @VisibleForTesting
161 static final int DEFAULT_MAX_SHORTCUTS_PER_APP = 5;
162
163 @VisibleForTesting
164 static final int DEFAULT_MAX_ICON_DIMENSION_DP = 96;
165
166 @VisibleForTesting
167 static final int DEFAULT_MAX_ICON_DIMENSION_LOWRAM_DP = 48;
168
169 @VisibleForTesting
170 static final String DEFAULT_ICON_PERSIST_FORMAT = CompressFormat.PNG.name();
171
172 @VisibleForTesting
173 static final int DEFAULT_ICON_PERSIST_QUALITY = 100;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800174
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700175 @VisibleForTesting
176 static final int DEFAULT_SAVE_DELAY_MS = 3000;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800177
178 @VisibleForTesting
179 static final String FILENAME_BASE_STATE = "shortcut_service.xml";
180
181 @VisibleForTesting
182 static final String DIRECTORY_PER_USER = "shortcut_service";
183
184 @VisibleForTesting
185 static final String FILENAME_USER_PACKAGES = "shortcuts.xml";
186
Makoto Onuki55046222016-03-08 10:49:47 -0800187 static final String DIRECTORY_BITMAPS = "bitmaps";
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800188
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700189 private static final String TAG_ROOT = "root";
190 private static final String TAG_LAST_RESET_TIME = "last_reset_time";
Makoto Onuki55046222016-03-08 10:49:47 -0800191
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700192 private static final String ATTR_VALUE = "value";
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800193
Makoto Onukib08790c2016-06-23 14:05:46 -0700194 private static final String LAUNCHER_INTENT_CATEGORY = Intent.CATEGORY_LAUNCHER;
195
Makoto Onuki76269922016-07-15 14:58:54 -0700196 private static final String KEY_SHORTCUT = "shortcut";
197 private static final String KEY_LOW_RAM = "lowRam";
198 private static final String KEY_ICON_SIZE = "iconSize";
199
Makoto Onuki2d895c32016-12-02 15:48:40 -0800200 private static final String DUMMY_MAIN_ACTIVITY = "android.__dummy__";
201
Makoto Onuki4362a662016-03-08 18:59:09 -0800202 @VisibleForTesting
203 interface ConfigConstants {
204 /**
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700205 * Key name for the save delay, in milliseconds. (int)
206 */
207 String KEY_SAVE_DELAY_MILLIS = "save_delay_ms";
208
209 /**
Makoto Onuki4362a662016-03-08 18:59:09 -0800210 * Key name for the throttling reset interval, in seconds. (long)
211 */
212 String KEY_RESET_INTERVAL_SEC = "reset_interval_sec";
213
214 /**
215 * Key name for the max number of modifying API calls per app for every interval. (int)
216 */
Makoto Onukib6d35232016-04-04 15:57:17 -0700217 String KEY_MAX_UPDATES_PER_INTERVAL = "max_updates_per_interval";
Makoto Onuki4362a662016-03-08 18:59:09 -0800218
219 /**
220 * Key name for the max icon dimensions in DP, for non-low-memory devices.
221 */
222 String KEY_MAX_ICON_DIMENSION_DP = "max_icon_dimension_dp";
223
224 /**
225 * Key name for the max icon dimensions in DP, for low-memory devices.
226 */
227 String KEY_MAX_ICON_DIMENSION_DP_LOWRAM = "max_icon_dimension_dp_lowram";
228
229 /**
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700230 * Key name for the max dynamic shortcuts per activity. (int)
Makoto Onuki4362a662016-03-08 18:59:09 -0800231 */
232 String KEY_MAX_SHORTCUTS = "max_shortcuts";
233
234 /**
Makoto Onuki41066a62016-03-09 16:18:44 -0800235 * Key name for icon compression quality, 0-100.
Makoto Onuki4362a662016-03-08 18:59:09 -0800236 */
237 String KEY_ICON_QUALITY = "icon_quality";
238
239 /**
240 * Key name for icon compression format: "PNG", "JPEG" or "WEBP"
241 */
242 String KEY_ICON_FORMAT = "icon_format";
243 }
244
Makoto Onuki41066a62016-03-09 16:18:44 -0800245 final Context mContext;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800246
247 private final Object mLock = new Object();
248
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700249 private static List<ResolveInfo> EMPTY_RESOLVE_INFO = new ArrayList<>(0);
250
Mark Renoufe065f7c2016-11-01 11:48:24 -0400251 // Temporarily reverted to anonymous inner class form due to: b/32554459
252 private static Predicate<ResolveInfo> ACTIVITY_NOT_EXPORTED = new Predicate<ResolveInfo>() {
253 public boolean test(ResolveInfo ri) {
254 return !ri.activityInfo.exported;
255 }
256 };
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700257
Mark Renoufe065f7c2016-11-01 11:48:24 -0400258 // Temporarily reverted to anonymous inner class form due to: b/32554459
259 private static Predicate<PackageInfo> PACKAGE_NOT_INSTALLED = new Predicate<PackageInfo>() {
260 public boolean test(PackageInfo pi) {
261 return !isInstalled(pi);
262 }
263 };
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700264
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800265 private final Handler mHandler;
266
267 @GuardedBy("mLock")
268 private final ArrayList<ShortcutChangeListener> mListeners = new ArrayList<>(1);
269
270 @GuardedBy("mLock")
271 private long mRawLastResetTime;
272
273 /**
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -0800274 * User ID -> UserShortcuts
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800275 */
276 @GuardedBy("mLock")
Makoto Onuki31459242016-03-22 11:12:18 -0700277 private final SparseArray<ShortcutUser> mUsers = new SparseArray<>();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800278
279 /**
Makoto Onukib5a012f2016-06-21 11:13:53 -0700280 * Max number of dynamic + manifest shortcuts that each application can have at a time.
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800281 */
Makoto Onukib5a012f2016-06-21 11:13:53 -0700282 private int mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800283
284 /**
Makoto Onukib6d35232016-04-04 15:57:17 -0700285 * Max number of updating API calls that each application can make during the interval.
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800286 */
Makoto Onukib6d35232016-04-04 15:57:17 -0700287 int mMaxUpdatesPerInterval;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800288
289 /**
290 * Actual throttling-reset interval. By default it's a day.
291 */
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800292 private long mResetInterval;
293
Makoto Onuki55046222016-03-08 10:49:47 -0800294 /**
295 * Icon max width/height in pixels.
296 */
297 private int mMaxIconDimension;
298
Makoto Onuki4362a662016-03-08 18:59:09 -0800299 private CompressFormat mIconPersistFormat;
300 private int mIconPersistQuality;
Makoto Onuki55046222016-03-08 10:49:47 -0800301
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700302 private int mSaveDelayMillis;
303
Makoto Onuki0acbb142016-03-22 17:02:57 -0700304 private final IPackageManager mIPackageManager;
Makoto Onuki2d5b4652016-03-11 16:09:54 -0800305 private final PackageManagerInternal mPackageManagerInternal;
Makoto Onukicdc78f72016-03-21 15:47:52 -0700306 private final UserManager mUserManager;
Makoto Onukiac042502016-05-20 16:39:42 -0700307 private final UsageStatsManagerInternal mUsageStatsManagerInternal;
Makoto Onuki33525d22016-08-03 15:45:24 -0700308 private final ActivityManagerInternal mActivityManagerInternal;
Makoto Onuki2d5b4652016-03-11 16:09:54 -0800309
Makoto Onuki2d895c32016-12-02 15:48:40 -0800310 private final ShortcutRequestPinProcessor mShortcutRequestPinProcessor;
311
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700312 @GuardedBy("mLock")
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700313 final SparseIntArray mUidState = new SparseIntArray();
314
315 @GuardedBy("mLock")
316 final SparseLongArray mUidLastForegroundElapsedTime = new SparseLongArray();
317
318 @GuardedBy("mLock")
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700319 private List<Integer> mDirtyUserIds = new ArrayList<>();
320
Makoto Onukic51b2872016-05-04 15:24:50 -0700321 private final AtomicBoolean mBootCompleted = new AtomicBoolean();
322
Makoto Onuki905e8852016-03-28 10:40:58 -0700323 private static final int PACKAGE_MATCH_FLAGS =
324 PackageManager.MATCH_DIRECT_BOOT_AWARE
Makoto Onukib08790c2016-06-23 14:05:46 -0700325 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE
326 | PackageManager.MATCH_UNINSTALLED_PACKAGES;
Makoto Onuki905e8852016-03-28 10:40:58 -0700327
Makoto Onuki02f338e2016-07-29 09:40:40 -0700328 @GuardedBy("mLock")
329 final SparseBooleanArray mUnlockedUsers = new SparseBooleanArray();
330
Makoto Onuki2e210c42016-03-30 08:30:36 -0700331 // Stats
332 @VisibleForTesting
333 interface Stats {
334 int GET_DEFAULT_HOME = 0;
335 int GET_PACKAGE_INFO = 1;
336 int GET_PACKAGE_INFO_WITH_SIG = 2;
337 int GET_APPLICATION_INFO = 3;
338 int LAUNCHER_PERMISSION_CHECK = 4;
Makoto Onuki6c1dbd52016-05-02 15:19:32 -0700339 int CLEANUP_DANGLING_BITMAPS = 5;
Makoto Onukib08790c2016-06-23 14:05:46 -0700340 int GET_ACTIVITY_WITH_METADATA = 6;
Makoto Onuki6dd9fb72016-06-01 13:55:54 -0700341 int GET_INSTALLED_PACKAGES = 7;
Makoto Onuki22fcc682016-05-17 14:52:19 -0700342 int CHECK_PACKAGE_CHANGES = 8;
Makoto Onuki157b1622016-06-02 16:13:10 -0700343 int GET_APPLICATION_RESOURCES = 9;
344 int RESOURCE_NAME_LOOKUP = 10;
Makoto Onukib08790c2016-06-23 14:05:46 -0700345 int GET_LAUNCHER_ACTIVITY = 11;
346 int CHECK_LAUNCHER_ACTIVITY = 12;
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700347 int IS_ACTIVITY_ENABLED = 13;
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700348 int PACKAGE_UPDATE_CHECK = 14;
Makoto Onuki085a05c2016-08-19 11:39:29 -0700349 int ASYNC_PRELOAD_USER_DELAY = 15;
Makoto Onuki2d895c32016-12-02 15:48:40 -0800350 int GET_DEFAULT_LAUNCHER = 16;
Makoto Onuki2e210c42016-03-30 08:30:36 -0700351
Makoto Onuki2d895c32016-12-02 15:48:40 -0800352 int COUNT = GET_DEFAULT_LAUNCHER + 1;
Makoto Onuki2e210c42016-03-30 08:30:36 -0700353 }
354
Makoto Onuki085a05c2016-08-19 11:39:29 -0700355 private static final String[] STAT_LABELS = {
356 "getHomeActivities()",
357 "Launcher permission check",
358 "getPackageInfo()",
359 "getPackageInfo(SIG)",
360 "getApplicationInfo",
361 "cleanupDanglingBitmaps",
362 "getActivity+metadata",
363 "getInstalledPackages",
364 "checkPackageChanges",
365 "getApplicationResources",
366 "resourceNameLookup",
367 "getLauncherActivity",
368 "checkLauncherActivity",
369 "isActivityEnabled",
370 "packageUpdateCheck",
Makoto Onuki2d895c32016-12-02 15:48:40 -0800371 "asyncPreloadUserDelay",
372 "getDefaultLauncher()"
Makoto Onuki085a05c2016-08-19 11:39:29 -0700373 };
374
Makoto Onuki2e210c42016-03-30 08:30:36 -0700375 final Object mStatLock = new Object();
376
377 @GuardedBy("mStatLock")
378 private final int[] mCountStats = new int[Stats.COUNT];
379
380 @GuardedBy("mStatLock")
381 private final long[] mDurationStats = new long[Stats.COUNT];
382
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700383 private static final int PROCESS_STATE_FOREGROUND_THRESHOLD =
384 ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
385
Makoto Onuki7001a612016-05-27 13:24:28 -0700386 static final int OPERATION_SET = 0;
387 static final int OPERATION_ADD = 1;
388 static final int OPERATION_UPDATE = 2;
389
390 /** @hide */
391 @IntDef(value = {
392 OPERATION_SET,
393 OPERATION_ADD,
394 OPERATION_UPDATE
Makoto Onukib08790c2016-06-23 14:05:46 -0700395 })
Makoto Onuki7001a612016-05-27 13:24:28 -0700396 @Retention(RetentionPolicy.SOURCE)
Makoto Onukib08790c2016-06-23 14:05:46 -0700397 @interface ShortcutOperation {
398 }
Makoto Onuki7001a612016-05-27 13:24:28 -0700399
Makoto Onukia2241832016-07-06 13:28:37 -0700400 @GuardedBy("mLock")
401 private int mWtfCount = 0;
402
403 @GuardedBy("mLock")
404 private Exception mLastWtfStacktrace;
405
Makoto Onukifc4cf2d2016-08-24 11:10:26 -0700406 static class InvalidFileFormatException extends Exception {
407 public InvalidFileFormatException(String message, Throwable cause) {
408 super(message, cause);
409 }
410 }
411
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800412 public ShortcutService(Context context) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700413 this(context, BackgroundThread.get().getLooper(), /*onyForPackgeManagerApis*/ false);
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700414 }
415
416 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700417 ShortcutService(Context context, Looper looper, boolean onlyForPackageManagerApis) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800418 mContext = Preconditions.checkNotNull(context);
419 LocalServices.addService(ShortcutServiceInternal.class, new LocalService());
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700420 mHandler = new Handler(looper);
Makoto Onuki0acbb142016-03-22 17:02:57 -0700421 mIPackageManager = AppGlobals.getPackageManager();
Makoto Onukiac042502016-05-20 16:39:42 -0700422 mPackageManagerInternal = Preconditions.checkNotNull(
423 LocalServices.getService(PackageManagerInternal.class));
424 mUserManager = Preconditions.checkNotNull(context.getSystemService(UserManager.class));
425 mUsageStatsManagerInternal = Preconditions.checkNotNull(
426 LocalServices.getService(UsageStatsManagerInternal.class));
Makoto Onuki33525d22016-08-03 15:45:24 -0700427 mActivityManagerInternal = Preconditions.checkNotNull(
428 LocalServices.getService(ActivityManagerInternal.class));
Makoto Onukicdc78f72016-03-21 15:47:52 -0700429
Makoto Onuki2d895c32016-12-02 15:48:40 -0800430 mShortcutRequestPinProcessor = new ShortcutRequestPinProcessor(this, mLock);
431
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700432 if (onlyForPackageManagerApis) {
433 return; // Don't do anything further. For unit tests only.
434 }
435
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700436 // Register receivers.
437
438 // We need to set a priority, so let's just not use PackageMonitor for now.
439 // TODO Refactor PackageMonitor to support priorities.
440 final IntentFilter packageFilter = new IntentFilter();
441 packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
442 packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
443 packageFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
444 packageFilter.addAction(Intent.ACTION_PACKAGE_DATA_CLEARED);
445 packageFilter.addDataScheme("package");
446 packageFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
447 mContext.registerReceiverAsUser(mPackageMonitor, UserHandle.ALL,
448 packageFilter, null, mHandler);
449
Makoto Onuki10305202016-07-14 18:14:08 -0700450 final IntentFilter preferedActivityFilter = new IntentFilter();
451 preferedActivityFilter.addAction(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
452 preferedActivityFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
453 mContext.registerReceiverAsUser(mPackageMonitor, UserHandle.ALL,
454 preferedActivityFilter, null, mHandler);
455
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700456 final IntentFilter localeFilter = new IntentFilter();
457 localeFilter.addAction(Intent.ACTION_LOCALE_CHANGED);
458 localeFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
459 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL,
460 localeFilter, null, mHandler);
Makoto Onukif34c3082016-07-13 10:25:25 -0700461
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700462 injectRegisterUidObserver(mUidObserver, ActivityManager.UID_OBSERVER_PROCSTATE
463 | ActivityManager.UID_OBSERVER_GONE);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800464 }
465
Makoto Onuki2e210c42016-03-30 08:30:36 -0700466 void logDurationStat(int statId, long start) {
467 synchronized (mStatLock) {
468 mCountStats[statId]++;
Makoto Onuki6c1dbd52016-05-02 15:19:32 -0700469 mDurationStats[statId] += (injectElapsedRealtime() - start);
Makoto Onuki2e210c42016-03-30 08:30:36 -0700470 }
471 }
472
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700473 public String injectGetLocaleTagsForUser(@UserIdInt int userId) {
474 // TODO This should get the per-user locale. b/30123329 b/30119489
475 return LocaleList.getDefault().toLanguageTags();
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700476 }
477
478 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Makoto Onukib08790c2016-06-23 14:05:46 -0700479 @Override
480 public void onUidStateChanged(int uid, int procState) throws RemoteException {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700481 handleOnUidStateChanged(uid, procState);
482 }
483
Makoto Onukib08790c2016-06-23 14:05:46 -0700484 @Override
Dianne Hackborne07641d2016-11-09 15:07:23 -0800485 public void onUidGone(int uid, boolean disabled) throws RemoteException {
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800486 handleOnUidStateChanged(uid, ActivityManager.PROCESS_STATE_NONEXISTENT);
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700487 }
488
Makoto Onukib08790c2016-06-23 14:05:46 -0700489 @Override
490 public void onUidActive(int uid) throws RemoteException {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700491 }
492
Makoto Onukib08790c2016-06-23 14:05:46 -0700493 @Override
Dianne Hackborne07641d2016-11-09 15:07:23 -0800494 public void onUidIdle(int uid, boolean disabled) throws RemoteException {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700495 }
496 };
497
498 void handleOnUidStateChanged(int uid, int procState) {
499 if (DEBUG_PROCSTATE) {
500 Slog.d(TAG, "onUidStateChanged: uid=" + uid + " state=" + procState);
501 }
502 synchronized (mLock) {
503 mUidState.put(uid, procState);
504
505 // We need to keep track of last time an app comes to foreground.
506 // See ShortcutPackage.getApiCallCount() for how it's used.
507 // It doesn't have to be persisted, but it needs to be the elapsed time.
508 if (isProcessStateForeground(procState)) {
509 mUidLastForegroundElapsedTime.put(uid, injectElapsedRealtime());
510 }
511 }
512 }
513
514 private boolean isProcessStateForeground(int processState) {
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800515 return processState <= PROCESS_STATE_FOREGROUND_THRESHOLD;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700516 }
517
518 boolean isUidForegroundLocked(int uid) {
519 if (uid == Process.SYSTEM_UID) {
520 // IUidObserver doesn't report the state of SYSTEM, but it always has bound services,
521 // so it's foreground anyway.
522 return true;
523 }
Makoto Onuki33525d22016-08-03 15:45:24 -0700524 // First, check with the local cache.
525 if (isProcessStateForeground(mUidState.get(uid, ActivityManager.MAX_PROCESS_STATE))) {
526 return true;
527 }
528 // If the cache says background, reach out to AM. Since it'll internally need to hold
529 // the AM lock, we use it as a last resort.
530 return isProcessStateForeground(mActivityManagerInternal.getUidProcessState(uid));
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700531 }
532
533 long getUidLastForegroundElapsedTimeLocked(int uid) {
534 return mUidLastForegroundElapsedTime.get(uid);
535 }
536
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800537 /**
538 * System service lifecycle.
539 */
540 public static final class Lifecycle extends SystemService {
541 final ShortcutService mService;
542
543 public Lifecycle(Context context) {
544 super(context);
545 mService = new ShortcutService(context);
546 }
547
548 @Override
549 public void onStart() {
550 publishBinderService(Context.SHORTCUT_SERVICE, mService);
551 }
552
553 @Override
554 public void onBootPhase(int phase) {
555 mService.onBootPhase(phase);
556 }
557
558 @Override
559 public void onCleanupUser(int userHandle) {
Makoto Onukicdc78f72016-03-21 15:47:52 -0700560 mService.handleCleanupUser(userHandle);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800561 }
562
563 @Override
Makoto Onukif3a572b2016-03-10 12:28:38 -0800564 public void onUnlockUser(int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -0700565 mService.handleUnlockUser(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800566 }
567 }
568
569 /** lifecycle event */
570 void onBootPhase(int phase) {
571 if (DEBUG) {
572 Slog.d(TAG, "onBootPhase: " + phase);
573 }
574 switch (phase) {
575 case SystemService.PHASE_LOCK_SETTINGS_READY:
576 initialize();
577 break;
Makoto Onukic51b2872016-05-04 15:24:50 -0700578 case SystemService.PHASE_BOOT_COMPLETED:
579 mBootCompleted.set(true);
580 break;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800581 }
582 }
583
584 /** lifecycle event */
Makoto Onukicdc78f72016-03-21 15:47:52 -0700585 void handleUnlockUser(int userId) {
Makoto Onuki22fcc682016-05-17 14:52:19 -0700586 if (DEBUG) {
Makoto Onuki085a05c2016-08-19 11:39:29 -0700587 Slog.d(TAG, "handleUnlockUser: user=" + userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700588 }
Makoto Onukicdc78f72016-03-21 15:47:52 -0700589 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -0700590 mUnlockedUsers.put(userId, true);
Makoto Onukicdc78f72016-03-21 15:47:52 -0700591 }
Makoto Onuki085a05c2016-08-19 11:39:29 -0700592
593 // Preload the user data.
594 // Note, we don't use mHandler here but instead just start a new thread.
595 // This is because mHandler (which uses com.android.internal.os.BackgroundThread) is very
596 // busy at this point and this could take hundreds of milliseconds, which would be too
597 // late since the launcher would already have started.
598 // So we just create a new thread. This code runs rarely, so we don't use a thread pool
599 // or anything.
600 final long start = injectElapsedRealtime();
601 injectRunOnNewThread(() -> {
602 synchronized (mLock) {
603 logDurationStat(Stats.ASYNC_PRELOAD_USER_DELAY, start);
604 getUserShortcutsLocked(userId);
605 }
606 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800607 }
608
609 /** lifecycle event */
Makoto Onukicdc78f72016-03-21 15:47:52 -0700610 void handleCleanupUser(int userId) {
Makoto Onuki02f338e2016-07-29 09:40:40 -0700611 if (DEBUG) {
612 Slog.d(TAG, "handleCleanupUser: user=" + userId);
613 }
Makoto Onukicdc78f72016-03-21 15:47:52 -0700614 synchronized (mLock) {
615 unloadUserLocked(userId);
Makoto Onuki02f338e2016-07-29 09:40:40 -0700616
617 mUnlockedUsers.put(userId, false);
Makoto Onukicdc78f72016-03-21 15:47:52 -0700618 }
619 }
620
621 private void unloadUserLocked(int userId) {
622 if (DEBUG) {
623 Slog.d(TAG, "unloadUserLocked: user=" + userId);
624 }
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700625 // Save all dirty information.
626 saveDirtyInfo();
627
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800628 // Unload
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -0800629 mUsers.delete(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800630 }
631
632 /** Return the base state file name */
633 private AtomicFile getBaseStateFile() {
634 final File path = new File(injectSystemDataPath(), FILENAME_BASE_STATE);
635 path.mkdirs();
636 return new AtomicFile(path);
637 }
638
639 /**
640 * Init the instance. (load the state file, etc)
641 */
642 private void initialize() {
643 synchronized (mLock) {
Makoto Onuki4362a662016-03-08 18:59:09 -0800644 loadConfigurationLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800645 loadBaseStateLocked();
646 }
647 }
648
Makoto Onuki4362a662016-03-08 18:59:09 -0800649 /**
650 * Load the configuration from Settings.
651 */
652 private void loadConfigurationLocked() {
653 updateConfigurationLocked(injectShortcutManagerConstants());
654 }
Makoto Onuki55046222016-03-08 10:49:47 -0800655
Makoto Onuki4362a662016-03-08 18:59:09 -0800656 /**
657 * Load the configuration from Settings.
658 */
659 @VisibleForTesting
660 boolean updateConfigurationLocked(String config) {
661 boolean result = true;
662
663 final KeyValueListParser parser = new KeyValueListParser(',');
664 try {
665 parser.setString(config);
666 } catch (IllegalArgumentException e) {
667 // Failed to parse the settings string, log this and move on
668 // with defaults.
669 Slog.e(TAG, "Bad shortcut manager settings", e);
670 result = false;
671 }
672
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700673 mSaveDelayMillis = Math.max(0, (int) parser.getLong(ConfigConstants.KEY_SAVE_DELAY_MILLIS,
674 DEFAULT_SAVE_DELAY_MS));
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700675
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700676 mResetInterval = Math.max(1, parser.getLong(
Makoto Onuki4362a662016-03-08 18:59:09 -0800677 ConfigConstants.KEY_RESET_INTERVAL_SEC, DEFAULT_RESET_INTERVAL_SEC)
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700678 * 1000L);
Makoto Onuki4362a662016-03-08 18:59:09 -0800679
Makoto Onukib6d35232016-04-04 15:57:17 -0700680 mMaxUpdatesPerInterval = Math.max(0, (int) parser.getLong(
681 ConfigConstants.KEY_MAX_UPDATES_PER_INTERVAL, DEFAULT_MAX_UPDATES_PER_INTERVAL));
Makoto Onuki4362a662016-03-08 18:59:09 -0800682
Makoto Onukib5a012f2016-06-21 11:13:53 -0700683 mMaxShortcuts = Math.max(0, (int) parser.getLong(
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700684 ConfigConstants.KEY_MAX_SHORTCUTS, DEFAULT_MAX_SHORTCUTS_PER_APP));
Makoto Onuki4362a662016-03-08 18:59:09 -0800685
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700686 final int iconDimensionDp = Math.max(1, injectIsLowRamDevice()
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_LOWRAM,
689 DEFAULT_MAX_ICON_DIMENSION_LOWRAM_DP)
Makoto Onuki4362a662016-03-08 18:59:09 -0800690 : (int) parser.getLong(
Makoto Onukib08790c2016-06-23 14:05:46 -0700691 ConfigConstants.KEY_MAX_ICON_DIMENSION_DP,
692 DEFAULT_MAX_ICON_DIMENSION_DP));
Makoto Onuki4362a662016-03-08 18:59:09 -0800693
694 mMaxIconDimension = injectDipToPixel(iconDimensionDp);
695
696 mIconPersistFormat = CompressFormat.valueOf(
697 parser.getString(ConfigConstants.KEY_ICON_FORMAT, DEFAULT_ICON_PERSIST_FORMAT));
698
699 mIconPersistQuality = (int) parser.getLong(
700 ConfigConstants.KEY_ICON_QUALITY,
701 DEFAULT_ICON_PERSIST_QUALITY);
702
703 return result;
704 }
705
706 @VisibleForTesting
707 String injectShortcutManagerConstants() {
708 return android.provider.Settings.Global.getString(
709 mContext.getContentResolver(),
710 android.provider.Settings.Global.SHORTCUT_MANAGER_CONSTANTS);
711 }
712
713 @VisibleForTesting
714 int injectDipToPixel(int dip) {
715 return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip,
716 mContext.getResources().getDisplayMetrics());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800717 }
718
Makoto Onuki55046222016-03-08 10:49:47 -0800719 // === Persisting ===
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800720
721 @Nullable
Makoto Onuki41066a62016-03-09 16:18:44 -0800722 static String parseStringAttribute(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800723 return parser.getAttributeValue(null, attribute);
724 }
725
Makoto Onuki0acbb142016-03-22 17:02:57 -0700726 static boolean parseBooleanAttribute(XmlPullParser parser, String attribute) {
727 return parseLongAttribute(parser, attribute) == 1;
728 }
729
Makoto Onuki41066a62016-03-09 16:18:44 -0800730 static int parseIntAttribute(XmlPullParser parser, String attribute) {
731 return (int) parseLongAttribute(parser, attribute);
732 }
733
Makoto Onukid99c6f02016-03-28 11:02:54 -0700734 static int parseIntAttribute(XmlPullParser parser, String attribute, int def) {
735 return (int) parseLongAttribute(parser, attribute, def);
736 }
737
Makoto Onuki41066a62016-03-09 16:18:44 -0800738 static long parseLongAttribute(XmlPullParser parser, String attribute) {
Makoto Onukid99c6f02016-03-28 11:02:54 -0700739 return parseLongAttribute(parser, attribute, 0);
740 }
741
742 static long parseLongAttribute(XmlPullParser parser, String attribute, long def) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800743 final String value = parseStringAttribute(parser, attribute);
744 if (TextUtils.isEmpty(value)) {
Makoto Onukid99c6f02016-03-28 11:02:54 -0700745 return def;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800746 }
747 try {
748 return Long.parseLong(value);
749 } catch (NumberFormatException e) {
750 Slog.e(TAG, "Error parsing long " + value);
Makoto Onukid99c6f02016-03-28 11:02:54 -0700751 return def;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800752 }
753 }
754
755 @Nullable
Makoto Onuki41066a62016-03-09 16:18:44 -0800756 static ComponentName parseComponentNameAttribute(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800757 final String value = parseStringAttribute(parser, attribute);
758 if (TextUtils.isEmpty(value)) {
759 return null;
760 }
761 return ComponentName.unflattenFromString(value);
762 }
763
764 @Nullable
Makoto Onuki440a1ea2016-07-20 14:21:18 -0700765 static Intent parseIntentAttributeNoDefault(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800766 final String value = parseStringAttribute(parser, attribute);
Makoto Onukib5a012f2016-06-21 11:13:53 -0700767 Intent parsed = null;
768 if (!TextUtils.isEmpty(value)) {
769 try {
770 parsed = Intent.parseUri(value, /* flags =*/ 0);
771 } catch (URISyntaxException e) {
772 Slog.e(TAG, "Error parsing intent", e);
773 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800774 }
Makoto Onuki440a1ea2016-07-20 14:21:18 -0700775 return parsed;
776 }
777
778 @Nullable
779 static Intent parseIntentAttribute(XmlPullParser parser, String attribute) {
780 Intent parsed = parseIntentAttributeNoDefault(parser, attribute);
Makoto Onukib5a012f2016-06-21 11:13:53 -0700781 if (parsed == null) {
782 // Default intent.
783 parsed = new Intent(Intent.ACTION_VIEW);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800784 }
Makoto Onukib5a012f2016-06-21 11:13:53 -0700785 return parsed;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800786 }
787
Makoto Onuki41066a62016-03-09 16:18:44 -0800788 static void writeTagValue(XmlSerializer out, String tag, String value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800789 if (TextUtils.isEmpty(value)) return;
790
791 out.startTag(null, tag);
792 out.attribute(null, ATTR_VALUE, value);
793 out.endTag(null, tag);
794 }
795
Makoto Onuki41066a62016-03-09 16:18:44 -0800796 static void writeTagValue(XmlSerializer out, String tag, long value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800797 writeTagValue(out, tag, Long.toString(value));
798 }
799
Makoto Onuki2d5b4652016-03-11 16:09:54 -0800800 static void writeTagValue(XmlSerializer out, String tag, ComponentName name) throws IOException {
801 if (name == null) return;
802 writeTagValue(out, tag, name.flattenToString());
803 }
804
Makoto Onuki41066a62016-03-09 16:18:44 -0800805 static void writeTagExtra(XmlSerializer out, String tag, PersistableBundle bundle)
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800806 throws IOException, XmlPullParserException {
807 if (bundle == null) return;
808
809 out.startTag(null, tag);
810 bundle.saveToXml(out);
811 out.endTag(null, tag);
812 }
813
Makoto Onuki22fcc682016-05-17 14:52:19 -0700814 static void writeAttr(XmlSerializer out, String name, CharSequence value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800815 if (TextUtils.isEmpty(value)) return;
816
Makoto Onuki22fcc682016-05-17 14:52:19 -0700817 out.attribute(null, name, value.toString());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800818 }
819
Makoto Onuki41066a62016-03-09 16:18:44 -0800820 static void writeAttr(XmlSerializer out, String name, long value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800821 writeAttr(out, name, String.valueOf(value));
822 }
823
Makoto Onuki0acbb142016-03-22 17:02:57 -0700824 static void writeAttr(XmlSerializer out, String name, boolean value) throws IOException {
825 if (value) {
826 writeAttr(out, name, "1");
827 }
828 }
829
Makoto Onuki41066a62016-03-09 16:18:44 -0800830 static void writeAttr(XmlSerializer out, String name, ComponentName comp) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800831 if (comp == null) return;
832 writeAttr(out, name, comp.flattenToString());
833 }
834
Makoto Onuki41066a62016-03-09 16:18:44 -0800835 static void writeAttr(XmlSerializer out, String name, Intent intent) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800836 if (intent == null) return;
837
838 writeAttr(out, name, intent.toUri(/* flags =*/ 0));
839 }
840
841 @VisibleForTesting
842 void saveBaseStateLocked() {
843 final AtomicFile file = getBaseStateFile();
844 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700845 Slog.d(TAG, "Saving to " + file.getBaseFile());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800846 }
847
848 FileOutputStream outs = null;
849 try {
850 outs = file.startWrite();
851
852 // Write to XML
853 XmlSerializer out = new FastXmlSerializer();
854 out.setOutput(outs, StandardCharsets.UTF_8.name());
855 out.startDocument(null, true);
856 out.startTag(null, TAG_ROOT);
857
858 // Body.
859 writeTagValue(out, TAG_LAST_RESET_TIME, mRawLastResetTime);
860
861 // Epilogue.
862 out.endTag(null, TAG_ROOT);
863 out.endDocument();
864
865 // Close.
866 file.finishWrite(outs);
867 } catch (IOException e) {
868 Slog.e(TAG, "Failed to write to file " + file.getBaseFile(), e);
869 file.failWrite(outs);
870 }
871 }
872
873 private void loadBaseStateLocked() {
874 mRawLastResetTime = 0;
875
876 final AtomicFile file = getBaseStateFile();
877 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700878 Slog.d(TAG, "Loading from " + file.getBaseFile());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800879 }
880 try (FileInputStream in = file.openRead()) {
881 XmlPullParser parser = Xml.newPullParser();
882 parser.setInput(in, StandardCharsets.UTF_8.name());
883
884 int type;
885 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
886 if (type != XmlPullParser.START_TAG) {
887 continue;
888 }
889 final int depth = parser.getDepth();
890 // Check the root tag
891 final String tag = parser.getName();
892 if (depth == 1) {
893 if (!TAG_ROOT.equals(tag)) {
894 Slog.e(TAG, "Invalid root tag: " + tag);
895 return;
896 }
897 continue;
898 }
899 // Assume depth == 2
900 switch (tag) {
901 case TAG_LAST_RESET_TIME:
902 mRawLastResetTime = parseLongAttribute(parser, ATTR_VALUE);
903 break;
904 default:
905 Slog.e(TAG, "Invalid tag: " + tag);
906 break;
907 }
908 }
909 } catch (FileNotFoundException e) {
910 // Use the default
Makoto Onukib08790c2016-06-23 14:05:46 -0700911 } catch (IOException | XmlPullParserException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800912 Slog.e(TAG, "Failed to read file " + file.getBaseFile(), e);
913
914 mRawLastResetTime = 0;
915 }
916 // Adjust the last reset time.
917 getLastResetTimeLocked();
918 }
919
Makoto Onuki0eed4412016-07-21 11:21:59 -0700920 @VisibleForTesting
921 final File getUserFile(@UserIdInt int userId) {
922 return new File(injectUserDataPath(userId), FILENAME_USER_PACKAGES);
923 }
924
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800925 private void saveUserLocked(@UserIdInt int userId) {
Makoto Onuki0eed4412016-07-21 11:21:59 -0700926 final File path = getUserFile(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800927 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700928 Slog.d(TAG, "Saving to " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800929 }
Makoto Onuki0eed4412016-07-21 11:21:59 -0700930 path.getParentFile().mkdirs();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800931 final AtomicFile file = new AtomicFile(path);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700932 FileOutputStream os = null;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800933 try {
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700934 os = file.startWrite();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800935
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700936 saveUserInternalLocked(userId, os, /* forBackup= */ false);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800937
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700938 file.finishWrite(os);
Makoto Onuki1e173232016-08-10 10:47:13 -0700939
940 // Remove all dangling bitmap files.
941 cleanupDanglingBitmapDirectoriesLocked(userId);
Makoto Onukib08790c2016-06-23 14:05:46 -0700942 } catch (XmlPullParserException | IOException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800943 Slog.e(TAG, "Failed to write to file " + file.getBaseFile(), e);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700944 file.failWrite(os);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800945 }
946 }
947
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700948 private void saveUserInternalLocked(@UserIdInt int userId, OutputStream os,
949 boolean forBackup) throws IOException, XmlPullParserException {
950
951 final BufferedOutputStream bos = new BufferedOutputStream(os);
952
953 // Write to XML
954 XmlSerializer out = new FastXmlSerializer();
955 out.setOutput(bos, StandardCharsets.UTF_8.name());
956 out.startDocument(null, true);
957
Makoto Onukic51b2872016-05-04 15:24:50 -0700958 getUserShortcutsLocked(userId).saveToXml(out, forBackup);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700959
960 out.endDocument();
961
962 bos.flush();
963 os.flush();
964 }
965
Makoto Onuki41066a62016-03-09 16:18:44 -0800966 static IOException throwForInvalidTag(int depth, String tag) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800967 throw new IOException(String.format("Invalid tag '%s' found at depth %d", tag, depth));
968 }
969
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700970 static void warnForInvalidTag(int depth, String tag) throws IOException {
971 Slog.w(TAG, String.format("Invalid tag '%s' found at depth %d", tag, depth));
972 }
973
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800974 @Nullable
Makoto Onuki31459242016-03-22 11:12:18 -0700975 private ShortcutUser loadUserLocked(@UserIdInt int userId) {
Makoto Onuki0eed4412016-07-21 11:21:59 -0700976 final File path = getUserFile(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800977 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700978 Slog.d(TAG, "Loading from " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800979 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800980 final AtomicFile file = new AtomicFile(path);
981
982 final FileInputStream in;
983 try {
984 in = file.openRead();
985 } catch (FileNotFoundException e) {
986 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700987 Slog.d(TAG, "Not found " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800988 }
989 return null;
990 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800991 try {
Makoto Onukib08790c2016-06-23 14:05:46 -0700992 final ShortcutUser ret = loadUserInternal(userId, in, /* forBackup= */ false);
Makoto Onuki6c1dbd52016-05-02 15:19:32 -0700993 return ret;
Makoto Onukifc4cf2d2016-08-24 11:10:26 -0700994 } catch (IOException | XmlPullParserException | InvalidFileFormatException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800995 Slog.e(TAG, "Failed to read file " + file.getBaseFile(), e);
996 return null;
997 } finally {
998 IoUtils.closeQuietly(in);
999 }
1000 }
1001
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001002 private ShortcutUser loadUserInternal(@UserIdInt int userId, InputStream is,
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07001003 boolean fromBackup) throws XmlPullParserException, IOException,
1004 InvalidFileFormatException {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001005
1006 final BufferedInputStream bis = new BufferedInputStream(is);
1007
1008 ShortcutUser ret = null;
1009 XmlPullParser parser = Xml.newPullParser();
1010 parser.setInput(bis, StandardCharsets.UTF_8.name());
1011
1012 int type;
1013 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1014 if (type != XmlPullParser.START_TAG) {
1015 continue;
1016 }
1017 final int depth = parser.getDepth();
1018
1019 final String tag = parser.getName();
1020 if (DEBUG_LOAD) {
1021 Slog.d(TAG, String.format("depth=%d type=%d name=%s",
1022 depth, type, tag));
1023 }
1024 if ((depth == 1) && ShortcutUser.TAG_ROOT.equals(tag)) {
1025 ret = ShortcutUser.loadFromXml(this, parser, userId, fromBackup);
1026 continue;
1027 }
1028 throwForInvalidTag(depth, tag);
1029 }
1030 return ret;
1031 }
1032
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001033 private void scheduleSaveBaseState() {
Makoto Onuki0acbb142016-03-22 17:02:57 -07001034 scheduleSaveInner(UserHandle.USER_NULL); // Special case -- use USER_NULL for base state.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001035 }
1036
Makoto Onuki2d5b4652016-03-11 16:09:54 -08001037 void scheduleSaveUser(@UserIdInt int userId) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07001038 scheduleSaveInner(userId);
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001039 }
1040
1041 // In order to re-schedule, we need to reuse the same instance, so keep it in final.
1042 private final Runnable mSaveDirtyInfoRunner = this::saveDirtyInfo;
1043
Makoto Onuki0acbb142016-03-22 17:02:57 -07001044 private void scheduleSaveInner(@UserIdInt int userId) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001045 if (DEBUG) {
1046 Slog.d(TAG, "Scheduling to save for " + userId);
1047 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001048 synchronized (mLock) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001049 if (!mDirtyUserIds.contains(userId)) {
1050 mDirtyUserIds.add(userId);
1051 }
1052 }
1053 // If already scheduled, remove that and re-schedule in N seconds.
1054 mHandler.removeCallbacks(mSaveDirtyInfoRunner);
1055 mHandler.postDelayed(mSaveDirtyInfoRunner, mSaveDelayMillis);
1056 }
1057
1058 @VisibleForTesting
1059 void saveDirtyInfo() {
1060 if (DEBUG) {
1061 Slog.d(TAG, "saveDirtyInfo");
1062 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001063 try {
1064 synchronized (mLock) {
1065 for (int i = mDirtyUserIds.size() - 1; i >= 0; i--) {
1066 final int userId = mDirtyUserIds.get(i);
1067 if (userId == UserHandle.USER_NULL) { // USER_NULL for base state.
1068 saveBaseStateLocked();
1069 } else {
1070 saveUserLocked(userId);
1071 }
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001072 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001073 mDirtyUserIds.clear();
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001074 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001075 } catch (Exception e) {
1076 wtf("Exception in saveDirtyInfo", e);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001077 }
1078 }
1079
1080 /** Return the last reset time. */
1081 long getLastResetTimeLocked() {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001082 updateTimesLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001083 return mRawLastResetTime;
1084 }
1085
1086 /** Return the next reset time. */
1087 long getNextResetTimeLocked() {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001088 updateTimesLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001089 return mRawLastResetTime + mResetInterval;
1090 }
1091
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001092 static boolean isClockValid(long time) {
1093 return time >= 1420070400; // Thu, 01 Jan 2015 00:00:00 GMT
1094 }
1095
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001096 /**
1097 * Update the last reset time.
1098 */
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001099 private void updateTimesLocked() {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001100
1101 final long now = injectCurrentTimeMillis();
1102
1103 final long prevLastResetTime = mRawLastResetTime;
1104
1105 if (mRawLastResetTime == 0) { // first launch.
1106 // TODO Randomize??
1107 mRawLastResetTime = now;
1108 } else if (now < mRawLastResetTime) {
1109 // Clock rewound.
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001110 if (isClockValid(now)) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001111 Slog.w(TAG, "Clock rewound");
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001112 // TODO Randomize??
1113 mRawLastResetTime = now;
1114 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001115 } else {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001116 if ((mRawLastResetTime + mResetInterval) <= now) {
1117 final long offset = mRawLastResetTime % mResetInterval;
1118 mRawLastResetTime = ((now / mResetInterval) * mResetInterval) + offset;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001119 }
1120 }
1121 if (prevLastResetTime != mRawLastResetTime) {
1122 scheduleSaveBaseState();
1123 }
1124 }
1125
Makoto Onuki1e173232016-08-10 10:47:13 -07001126 // Requires mLock held, but "Locked" prefix would look weired so we just say "L".
Makoto Onuki02f338e2016-07-29 09:40:40 -07001127 protected boolean isUserUnlockedL(@UserIdInt int userId) {
Makoto Onuki1e173232016-08-10 10:47:13 -07001128 // First, check the local copy.
1129 if (mUnlockedUsers.get(userId)) {
1130 return true;
1131 }
1132 // If the local copy says the user is locked, check with AM for the actual state, since
1133 // the user might just have been unlocked.
1134 // Note we just don't use isUserUnlockingOrUnlocked() here, because it'll return false
1135 // when the user is STOPPING, which we still want to consider as "unlocked".
1136 final long token = injectClearCallingIdentity();
1137 try {
1138 return mUserManager.isUserUnlockingOrUnlocked(userId);
1139 } finally {
1140 injectRestoreCallingIdentity(token);
1141 }
Makoto Onuki9c850012016-07-26 15:50:50 -07001142 }
1143
Makoto Onuki02f338e2016-07-29 09:40:40 -07001144 // Requires mLock held, but "Locked" prefix would look weired so we jsut say "L".
1145 void throwIfUserLockedL(@UserIdInt int userId) {
1146 if (!isUserUnlockedL(userId)) {
Makoto Onuki9c850012016-07-26 15:50:50 -07001147 throw new IllegalStateException("User " + userId + " is locked or not running");
1148 }
1149 }
1150
Makoto Onukicdc78f72016-03-21 15:47:52 -07001151 @GuardedBy("mLock")
1152 @NonNull
Makoto Onuki2e210c42016-03-30 08:30:36 -07001153 private boolean isUserLoadedLocked(@UserIdInt int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07001154 return mUsers.get(userId) != null;
1155 }
1156
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001157 /** Return the per-user state. */
1158 @GuardedBy("mLock")
1159 @NonNull
Makoto Onuki31459242016-03-22 11:12:18 -07001160 ShortcutUser getUserShortcutsLocked(@UserIdInt int userId) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001161 if (!isUserUnlockedL(userId)) {
Makoto Onuki9c850012016-07-26 15:50:50 -07001162 wtf("User still locked");
Makoto Onuki9c850012016-07-26 15:50:50 -07001163 }
1164
Makoto Onuki31459242016-03-22 11:12:18 -07001165 ShortcutUser userPackages = mUsers.get(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001166 if (userPackages == null) {
1167 userPackages = loadUserLocked(userId);
1168 if (userPackages == null) {
Makoto Onukic51b2872016-05-04 15:24:50 -07001169 userPackages = new ShortcutUser(this, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001170 }
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08001171 mUsers.put(userId, userPackages);
Makoto Onuki085a05c2016-08-19 11:39:29 -07001172
1173 // Also when a user's data is first accessed, scan all packages.
1174 checkPackageChanges(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001175 }
1176 return userPackages;
1177 }
1178
Makoto Onuki2e210c42016-03-30 08:30:36 -07001179 void forEachLoadedUserLocked(@NonNull Consumer<ShortcutUser> c) {
1180 for (int i = mUsers.size() - 1; i >= 0; i--) {
1181 c.accept(mUsers.valueAt(i));
1182 }
1183 }
1184
Makoto Onukic8c33292016-09-12 16:36:59 -07001185 /**
1186 * Return the per-user per-package state. If the caller is a publisher, use
1187 * {@link #getPackageShortcutsForPublisherLocked} instead.
1188 */
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001189 @GuardedBy("mLock")
1190 @NonNull
Makoto Onuki31459242016-03-22 11:12:18 -07001191 ShortcutPackage getPackageShortcutsLocked(
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001192 @NonNull String packageName, @UserIdInt int userId) {
Makoto Onukic51b2872016-05-04 15:24:50 -07001193 return getUserShortcutsLocked(userId).getPackageShortcuts(packageName);
Makoto Onukide667372016-03-15 14:29:20 -07001194 }
1195
Makoto Onukic8c33292016-09-12 16:36:59 -07001196 /** Return the per-user per-package state. Use this when the caller is a publisher. */
1197 @GuardedBy("mLock")
1198 @NonNull
1199 ShortcutPackage getPackageShortcutsForPublisherLocked(
1200 @NonNull String packageName, @UserIdInt int userId) {
1201 final ShortcutPackage ret = getUserShortcutsLocked(userId).getPackageShortcuts(packageName);
1202 ret.getUser().onCalledByPublisher(packageName);
1203 return ret;
1204 }
1205
Makoto Onukide667372016-03-15 14:29:20 -07001206 @GuardedBy("mLock")
1207 @NonNull
Makoto Onuki2e210c42016-03-30 08:30:36 -07001208 ShortcutLauncher getLauncherShortcutsLocked(
1209 @NonNull String packageName, @UserIdInt int ownerUserId,
1210 @UserIdInt int launcherUserId) {
1211 return getUserShortcutsLocked(ownerUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07001212 .getLauncherShortcuts(packageName, launcherUserId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001213 }
1214
1215 // === Caller validation ===
1216
Makoto Onuki55046222016-03-08 10:49:47 -08001217 void removeIcon(@UserIdInt int userId, ShortcutInfo shortcut) {
Makoto Onuki1e173232016-08-10 10:47:13 -07001218 // Do not remove the actual bitmap file yet, because if the device crashes before saving
1219 // he XML we'd lose the icon. We just remove all dangling files after saving the XML.
Makoto Onukidd097812016-06-29 13:10:09 -07001220 shortcut.setIconResourceId(0);
1221 shortcut.setIconResName(null);
Hyunyoung Songf281e7a2017-02-13 10:57:42 -08001222 shortcut.clearFlags(ShortcutInfo.FLAG_HAS_ICON_FILE |
1223 ShortcutInfo.FLAG_MASKABLE_BITMAP | ShortcutInfo.FLAG_HAS_ICON_RES);
Makoto Onuki55046222016-03-08 10:49:47 -08001224 }
1225
Makoto Onuki0033b2a2016-04-14 17:19:16 -07001226 public void cleanupBitmapsForPackage(@UserIdInt int userId, String packageName) {
1227 final File packagePath = new File(getUserBitmapFilePath(userId), packageName);
1228 if (!packagePath.isDirectory()) {
1229 return;
1230 }
1231 if (!(FileUtils.deleteContents(packagePath) && packagePath.delete())) {
1232 Slog.w(TAG, "Unable to remove directory " + packagePath);
1233 }
1234 }
1235
Makoto Onuki1e173232016-08-10 10:47:13 -07001236 private void cleanupDanglingBitmapDirectoriesLocked(@UserIdInt int userId) {
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001237 if (DEBUG) {
1238 Slog.d(TAG, "cleanupDanglingBitmaps: userId=" + userId);
1239 }
1240 final long start = injectElapsedRealtime();
1241
Makoto Onuki1e173232016-08-10 10:47:13 -07001242 final ShortcutUser user = getUserShortcutsLocked(userId);
1243
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001244 final File bitmapDir = getUserBitmapFilePath(userId);
1245 final File[] children = bitmapDir.listFiles();
1246 if (children == null) {
1247 return;
1248 }
1249 for (File child : children) {
1250 if (!child.isDirectory()) {
1251 continue;
1252 }
1253 final String packageName = child.getName();
1254 if (DEBUG) {
1255 Slog.d(TAG, "cleanupDanglingBitmaps: Found directory=" + packageName);
1256 }
1257 if (!user.hasPackage(packageName)) {
1258 if (DEBUG) {
1259 Slog.d(TAG, "Removing dangling bitmap directory: " + packageName);
1260 }
1261 cleanupBitmapsForPackage(userId, packageName);
1262 } else {
1263 cleanupDanglingBitmapFilesLocked(userId, user, packageName, child);
1264 }
1265 }
1266 logDurationStat(Stats.CLEANUP_DANGLING_BITMAPS, start);
1267 }
1268
1269 private void cleanupDanglingBitmapFilesLocked(@UserIdInt int userId, @NonNull ShortcutUser user,
1270 @NonNull String packageName, @NonNull File path) {
1271 final ArraySet<String> usedFiles =
Makoto Onukic51b2872016-05-04 15:24:50 -07001272 user.getPackageShortcuts(packageName).getUsedBitmapFiles();
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001273
1274 for (File child : path.listFiles()) {
1275 if (!child.isFile()) {
1276 continue;
1277 }
1278 final String name = child.getName();
1279 if (!usedFiles.contains(name)) {
1280 if (DEBUG) {
1281 Slog.d(TAG, "Removing dangling bitmap file: " + child.getAbsolutePath());
1282 }
1283 child.delete();
1284 }
1285 }
1286 }
1287
Makoto Onuki55046222016-03-08 10:49:47 -08001288 @VisibleForTesting
1289 static class FileOutputStreamWithPath extends FileOutputStream {
1290 private final File mFile;
1291
1292 public FileOutputStreamWithPath(File file) throws FileNotFoundException {
1293 super(file);
1294 mFile = file;
1295 }
1296
1297 public File getFile() {
1298 return mFile;
1299 }
1300 }
1301
1302 /**
1303 * Build the cached bitmap filename for a shortcut icon.
1304 *
1305 * The filename will be based on the ID, except certain characters will be escaped.
1306 */
1307 @VisibleForTesting
1308 FileOutputStreamWithPath openIconFileForWrite(@UserIdInt int userId, ShortcutInfo shortcut)
1309 throws IOException {
1310 final File packagePath = new File(getUserBitmapFilePath(userId),
Makoto Onuki22fcc682016-05-17 14:52:19 -07001311 shortcut.getPackage());
Makoto Onuki55046222016-03-08 10:49:47 -08001312 if (!packagePath.isDirectory()) {
1313 packagePath.mkdirs();
1314 if (!packagePath.isDirectory()) {
1315 throw new IOException("Unable to create directory " + packagePath);
1316 }
1317 SELinux.restorecon(packagePath);
1318 }
1319
1320 final String baseName = String.valueOf(injectCurrentTimeMillis());
Makoto Onukib08790c2016-06-23 14:05:46 -07001321 for (int suffix = 0; ; suffix++) {
Makoto Onuki55046222016-03-08 10:49:47 -08001322 final String filename = (suffix == 0 ? baseName : baseName + "_" + suffix) + ".png";
1323 final File file = new File(packagePath, filename);
1324 if (!file.exists()) {
1325 if (DEBUG) {
1326 Slog.d(TAG, "Saving icon to " + file.getAbsolutePath());
1327 }
1328 return new FileOutputStreamWithPath(file);
1329 }
1330 }
1331 }
1332
1333 void saveIconAndFixUpShortcut(@UserIdInt int userId, ShortcutInfo shortcut) {
1334 if (shortcut.hasIconFile() || shortcut.hasIconResource()) {
1335 return;
1336 }
1337
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001338 final long token = injectClearCallingIdentity();
Makoto Onuki55046222016-03-08 10:49:47 -08001339 try {
1340 // Clear icon info on the shortcut.
Makoto Onukidd097812016-06-29 13:10:09 -07001341 removeIcon(userId, shortcut);
Makoto Onuki55046222016-03-08 10:49:47 -08001342
1343 final Icon icon = shortcut.getIcon();
1344 if (icon == null) {
1345 return; // has no icon
1346 }
1347
Makoto Onukiabe84422016-04-07 09:41:19 -07001348 Bitmap bitmap;
Makoto Onuki55046222016-03-08 10:49:47 -08001349 try {
1350 switch (icon.getType()) {
1351 case Icon.TYPE_RESOURCE: {
1352 injectValidateIconResPackage(shortcut, icon);
1353
1354 shortcut.setIconResourceId(icon.getResId());
1355 shortcut.addFlags(ShortcutInfo.FLAG_HAS_ICON_RES);
1356 return;
1357 }
Hyunyoung Songf281e7a2017-02-13 10:57:42 -08001358 case Icon.TYPE_BITMAP:
1359 case Icon.TYPE_BITMAP_MASKABLE: {
Makoto Onukiabe84422016-04-07 09:41:19 -07001360 bitmap = icon.getBitmap(); // Don't recycle in this case.
Makoto Onuki55046222016-03-08 10:49:47 -08001361 break;
1362 }
Makoto Onuki55046222016-03-08 10:49:47 -08001363 default:
1364 // This shouldn't happen because we've already validated the icon, but
1365 // just in case.
1366 throw ShortcutInfo.getInvalidIconException();
1367 }
1368 if (bitmap == null) {
1369 Slog.e(TAG, "Null bitmap detected");
1370 return;
1371 }
1372 // Shrink and write to the file.
1373 File path = null;
1374 try {
1375 final FileOutputStreamWithPath out = openIconFileForWrite(userId, shortcut);
1376 try {
1377 path = out.getFile();
1378
Makoto Onukiabe84422016-04-07 09:41:19 -07001379 Bitmap shrunk = shrinkBitmap(bitmap, mMaxIconDimension);
1380 try {
1381 shrunk.compress(mIconPersistFormat, mIconPersistQuality, out);
1382 } finally {
1383 if (bitmap != shrunk) {
1384 shrunk.recycle();
1385 }
1386 }
Makoto Onuki55046222016-03-08 10:49:47 -08001387
1388 shortcut.setBitmapPath(out.getFile().getAbsolutePath());
1389 shortcut.addFlags(ShortcutInfo.FLAG_HAS_ICON_FILE);
Hyunyoung Songf281e7a2017-02-13 10:57:42 -08001390 if (icon.getType() == Icon.TYPE_BITMAP_MASKABLE) {
1391 shortcut.addFlags(ShortcutInfo.FLAG_MASKABLE_BITMAP);
1392 }
Makoto Onuki55046222016-03-08 10:49:47 -08001393 } finally {
1394 IoUtils.closeQuietly(out);
1395 }
Makoto Onukib08790c2016-06-23 14:05:46 -07001396 } catch (IOException | RuntimeException e) {
Makoto Onuki55046222016-03-08 10:49:47 -08001397 // STOPSHIP Change wtf to e
1398 Slog.wtf(ShortcutService.TAG, "Unable to write bitmap to file", e);
1399 if (path != null && path.exists()) {
1400 path.delete();
1401 }
1402 }
1403 } finally {
Makoto Onuki55046222016-03-08 10:49:47 -08001404 // Once saved, we won't use the original icon information, so null it out.
1405 shortcut.clearIcon();
1406 }
1407 } finally {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001408 injectRestoreCallingIdentity(token);
Makoto Onuki55046222016-03-08 10:49:47 -08001409 }
1410 }
1411
1412 // Unfortunately we can't do this check in unit tests because we fake creator package names,
1413 // so override in unit tests.
1414 // TODO CTS this case.
1415 void injectValidateIconResPackage(ShortcutInfo shortcut, Icon icon) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07001416 if (!shortcut.getPackage().equals(icon.getResPackage())) {
Makoto Onuki55046222016-03-08 10:49:47 -08001417 throw new IllegalArgumentException(
1418 "Icon resource must reside in shortcut owner package");
1419 }
1420 }
1421
1422 @VisibleForTesting
1423 static Bitmap shrinkBitmap(Bitmap in, int maxSize) {
1424 // Original width/height.
1425 final int ow = in.getWidth();
1426 final int oh = in.getHeight();
1427 if ((ow <= maxSize) && (oh <= maxSize)) {
1428 if (DEBUG) {
1429 Slog.d(TAG, String.format("Icon size %dx%d, no need to shrink", ow, oh));
1430 }
1431 return in;
1432 }
1433 final int longerDimension = Math.max(ow, oh);
1434
1435 // New width and height.
1436 final int nw = ow * maxSize / longerDimension;
1437 final int nh = oh * maxSize / longerDimension;
1438 if (DEBUG) {
1439 Slog.d(TAG, String.format("Icon size %dx%d, shrinking to %dx%d",
1440 ow, oh, nw, nh));
1441 }
1442
1443 final Bitmap scaledBitmap = Bitmap.createBitmap(nw, nh, Bitmap.Config.ARGB_8888);
1444 final Canvas c = new Canvas(scaledBitmap);
1445
1446 final RectF dst = new RectF(0, 0, nw, nh);
1447
1448 c.drawBitmap(in, /*src=*/ null, dst, /* paint =*/ null);
1449
Makoto Onuki55046222016-03-08 10:49:47 -08001450 return scaledBitmap;
1451 }
1452
Makoto Onuki157b1622016-06-02 16:13:10 -07001453 /**
1454 * For a shortcut, update all resource names from resource IDs, and also update all
1455 * resource-based strings.
1456 */
1457 void fixUpShortcutResourceNamesAndValues(ShortcutInfo si) {
1458 final Resources publisherRes = injectGetResourcesForApplicationAsUser(
1459 si.getPackage(), si.getUserId());
1460 if (publisherRes != null) {
1461 final long start = injectElapsedRealtime();
1462 try {
1463 si.lookupAndFillInResourceNames(publisherRes);
1464 } finally {
1465 logDurationStat(Stats.RESOURCE_NAME_LOOKUP, start);
1466 }
1467 si.resolveResourceStrings(publisherRes);
1468 }
1469 }
1470
Makoto Onuki55046222016-03-08 10:49:47 -08001471 // === Caller validation ===
1472
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001473 private boolean isCallerSystem() {
1474 final int callingUid = injectBinderCallingUid();
Makoto Onukib08790c2016-06-23 14:05:46 -07001475 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001476 }
1477
1478 private boolean isCallerShell() {
1479 final int callingUid = injectBinderCallingUid();
1480 return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
1481 }
1482
1483 private void enforceSystemOrShell() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001484 if (!(isCallerSystem() || isCallerShell())) {
1485 throw new SecurityException("Caller must be system or shell");
1486 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001487 }
1488
1489 private void enforceShell() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001490 if (!isCallerShell()) {
1491 throw new SecurityException("Caller must be shell");
1492 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001493 }
1494
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001495 private void enforceSystem() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001496 if (!isCallerSystem()) {
1497 throw new SecurityException("Caller must be system");
1498 }
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001499 }
1500
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001501 private void enforceResetThrottlingPermission() {
1502 if (isCallerSystem()) {
1503 return;
1504 }
Makoto Onuki76269922016-07-15 14:58:54 -07001505 enforceCallingOrSelfPermission(
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001506 android.Manifest.permission.RESET_SHORTCUT_MANAGER_THROTTLING, null);
1507 }
1508
Makoto Onuki76269922016-07-15 14:58:54 -07001509 private void enforceCallingOrSelfPermission(
1510 @NonNull String permission, @Nullable String message) {
1511 if (isCallerSystem()) {
1512 return;
1513 }
1514 injectEnforceCallingPermission(permission, message);
1515 }
1516
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001517 /**
1518 * Somehow overriding ServiceContext.enforceCallingPermission() in the unit tests would confuse
1519 * mockito. So instead we extracted it here and override it in the tests.
1520 */
1521 @VisibleForTesting
1522 void injectEnforceCallingPermission(
1523 @NonNull String permission, @Nullable String message) {
1524 mContext.enforceCallingPermission(permission, message);
1525 }
1526
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001527 private void verifyCaller(@NonNull String packageName, @UserIdInt int userId) {
1528 Preconditions.checkStringNotEmpty(packageName, "packageName");
1529
1530 if (isCallerSystem()) {
1531 return; // no check
1532 }
1533
1534 final int callingUid = injectBinderCallingUid();
1535
1536 // Otherwise, make sure the arguments are valid.
1537 if (UserHandle.getUserId(callingUid) != userId) {
1538 throw new SecurityException("Invalid user-ID");
1539 }
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08001540 if (injectGetPackageUid(packageName, userId) != callingUid) {
1541 throw new SecurityException("Calling package name mismatch");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001542 }
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08001543 Preconditions.checkState(!isEphemeralApp(packageName, userId),
1544 "Ephemeral apps can't use ShortcutManager");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001545 }
1546
Makoto Onuki157b1622016-06-02 16:13:10 -07001547 // Overridden in unit tests to execute r synchronously.
1548 void injectPostToHandler(Runnable r) {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001549 mHandler.post(r);
1550 }
1551
Makoto Onuki085a05c2016-08-19 11:39:29 -07001552 void injectRunOnNewThread(Runnable r) {
1553 new Thread(r).start();
1554 }
1555
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001556 /**
Makoto Onuki7001a612016-05-27 13:24:28 -07001557 * @throws IllegalArgumentException if {@code numShortcuts} is bigger than
Makoto Onukib08790c2016-06-23 14:05:46 -07001558 * {@link #getMaxActivityShortcuts()}.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001559 */
Makoto Onuki7001a612016-05-27 13:24:28 -07001560 void enforceMaxActivityShortcuts(int numShortcuts) {
Makoto Onukib5a012f2016-06-21 11:13:53 -07001561 if (numShortcuts > mMaxShortcuts) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001562 throw new IllegalArgumentException("Max number of dynamic shortcuts exceeded");
1563 }
1564 }
1565
1566 /**
Makoto Onuki7001a612016-05-27 13:24:28 -07001567 * Return the max number of dynamic + manifest shortcuts for each launcher icon.
1568 */
1569 int getMaxActivityShortcuts() {
Makoto Onukib5a012f2016-06-21 11:13:53 -07001570 return mMaxShortcuts;
Makoto Onuki7001a612016-05-27 13:24:28 -07001571 }
1572
1573 /**
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001574 * - Sends a notification to LauncherApps
1575 * - Write to file
1576 */
Makoto Onuki39686e82016-04-13 18:03:00 -07001577 void packageShortcutsChanged(@NonNull String packageName, @UserIdInt int userId) {
1578 if (DEBUG) {
1579 Slog.d(TAG, String.format(
1580 "Shortcut changes: package=%s, user=%d", packageName, userId));
1581 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001582 notifyListeners(packageName, userId);
1583 scheduleSaveUser(userId);
1584 }
1585
1586 private void notifyListeners(@NonNull String packageName, @UserIdInt int userId) {
Makoto Onuki157b1622016-06-02 16:13:10 -07001587 injectPostToHandler(() -> {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001588 try {
1589 final ArrayList<ShortcutChangeListener> copy;
1590 synchronized (mLock) {
1591 if (!isUserUnlockedL(userId)) {
1592 return;
1593 }
1594
1595 copy = new ArrayList<>(mListeners);
1596 }
1597 // Note onShortcutChanged() needs to be called with the system service permissions.
1598 for (int i = copy.size() - 1; i >= 0; i--) {
1599 copy.get(i).onShortcutChanged(packageName, userId);
1600 }
1601 } catch (Exception ignore) {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001602 }
1603 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001604 }
1605
1606 /**
1607 * Clean up / validate an incoming shortcut.
1608 * - Make sure all mandatory fields are set.
1609 * - Make sure the intent's extras are persistable, and them to set
Makoto Onuki0eed4412016-07-21 11:21:59 -07001610 * {@link ShortcutInfo#mIntentPersistableExtrases}. Also clear its extras.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001611 * - Clear flags.
1612 */
Makoto Onuki2d895c32016-12-02 15:48:40 -08001613 private void fixUpIncomingShortcutInfo(@NonNull ShortcutInfo shortcut, boolean forUpdate,
1614 boolean forPinRequest) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001615 Preconditions.checkNotNull(shortcut, "Null shortcut detected");
Makoto Onuki255461f2017-01-10 11:47:25 -08001616 if (shortcut.getActivity() != null) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001617 Preconditions.checkState(
Makoto Onuki22fcc682016-05-17 14:52:19 -07001618 shortcut.getPackage().equals(shortcut.getActivity().getPackageName()),
Makoto Onukib08790c2016-06-23 14:05:46 -07001619 "Cannot publish shortcut: activity " + shortcut.getActivity() + " does not"
1620 + " belong to package " + shortcut.getPackage());
Makoto Onuki13260b6ff2016-07-13 18:03:13 -07001621 Preconditions.checkState(
1622 injectIsMainActivity(shortcut.getActivity(), shortcut.getUserId()),
1623 "Cannot publish shortcut: activity " + shortcut.getActivity() + " is not"
1624 + " main activity");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001625 }
1626
Makoto Onuki55046222016-03-08 10:49:47 -08001627 if (!forUpdate) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08001628 shortcut.enforceMandatoryFields(/* forPinned= */ forPinRequest);
1629 if (!forPinRequest) {
Makoto Onuki255461f2017-01-10 11:47:25 -08001630 Preconditions.checkState(shortcut.getActivity() != null,
1631 "Cannot publish shortcut: target activity is not set");
Makoto Onuki2d895c32016-12-02 15:48:40 -08001632 }
Makoto Onuki55046222016-03-08 10:49:47 -08001633 }
1634 if (shortcut.getIcon() != null) {
1635 ShortcutInfo.validateIcon(shortcut.getIcon());
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001636 }
1637
Makoto Onukide667372016-03-15 14:29:20 -07001638 shortcut.replaceFlags(0);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001639 }
1640
Makoto Onuki2d895c32016-12-02 15:48:40 -08001641 private void fixUpIncomingShortcutInfo(@NonNull ShortcutInfo shortcut, boolean forUpdate) {
1642 fixUpIncomingShortcutInfo(shortcut, forUpdate, /*forPinRequest=*/ false);
1643 }
1644
1645 public void validateShortcutForPinRequest(@NonNull ShortcutInfo shortcut) {
1646 fixUpIncomingShortcutInfo(shortcut, /* forUpdate= */ false, /*forPinRequest=*/ true);
1647 }
1648
Makoto Onukib08790c2016-06-23 14:05:46 -07001649 /**
1650 * When a shortcut has no target activity, set the default one from the package.
1651 */
1652 private void fillInDefaultActivity(List<ShortcutInfo> shortcuts) {
Makoto Onukib08790c2016-06-23 14:05:46 -07001653 ComponentName defaultActivity = null;
1654 for (int i = shortcuts.size() - 1; i >= 0; i--) {
1655 final ShortcutInfo si = shortcuts.get(i);
1656 if (si.getActivity() == null) {
1657 if (defaultActivity == null) {
1658 defaultActivity = injectGetDefaultMainActivity(
1659 si.getPackage(), si.getUserId());
1660 Preconditions.checkState(defaultActivity != null,
1661 "Launcher activity not found for package " + si.getPackage());
1662 }
1663 si.setActivity(defaultActivity);
1664 }
1665 }
1666 }
1667
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001668 private void assignImplicitRanks(List<ShortcutInfo> shortcuts) {
1669 for (int i = shortcuts.size() - 1; i >= 0; i--) {
1670 shortcuts.get(i).setImplicitRank(i);
1671 }
1672 }
1673
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001674 // === APIs ===
1675
1676 @Override
1677 public boolean setDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1678 @UserIdInt int userId) {
1679 verifyCaller(packageName, userId);
1680
1681 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
1682 final int size = newShortcuts.size();
1683
1684 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001685 throwIfUserLockedL(userId);
1686
Makoto Onukic8c33292016-09-12 16:36:59 -07001687 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001688
Makoto Onuki22fcc682016-05-17 14:52:19 -07001689 ps.ensureImmutableShortcutsNotIncluded(newShortcuts);
1690
Makoto Onukib08790c2016-06-23 14:05:46 -07001691 fillInDefaultActivity(newShortcuts);
1692
Makoto Onuki7001a612016-05-27 13:24:28 -07001693 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_SET);
1694
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001695 // Throttling.
Makoto Onukic51b2872016-05-04 15:24:50 -07001696 if (!ps.tryApiCall()) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001697 return false;
1698 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001699
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001700 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1701 ps.clearAllImplicitRanks();
1702 assignImplicitRanks(newShortcuts);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001703
Makoto Onukidf6da042016-06-16 09:51:40 -07001704 for (int i = 0; i < size; i++) {
1705 fixUpIncomingShortcutInfo(newShortcuts.get(i), /* forUpdate= */ false);
1706 }
1707
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001708 // First, remove all un-pinned; dynamic shortcuts
Makoto Onukic51b2872016-05-04 15:24:50 -07001709 ps.deleteAllDynamicShortcuts();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001710
1711 // Then, add/update all. We need to make sure to take over "pinned" flag.
1712 for (int i = 0; i < size; i++) {
1713 final ShortcutInfo newShortcut = newShortcuts.get(i);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001714 ps.addOrUpdateDynamicShortcut(newShortcut);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001715 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001716
1717 // Lastly, adjust the ranks.
1718 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001719 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001720 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001721
1722 verifyStates();
1723
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001724 return true;
1725 }
1726
1727 @Override
1728 public boolean updateShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1729 @UserIdInt int userId) {
1730 verifyCaller(packageName, userId);
1731
1732 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
Makoto Onuki55046222016-03-08 10:49:47 -08001733 final int size = newShortcuts.size();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001734
1735 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001736 throwIfUserLockedL(userId);
1737
Makoto Onukic8c33292016-09-12 16:36:59 -07001738 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001739
Makoto Onuki22fcc682016-05-17 14:52:19 -07001740 ps.ensureImmutableShortcutsNotIncluded(newShortcuts);
1741
Makoto Onukib08790c2016-06-23 14:05:46 -07001742 // For update, don't fill in the default activity. Having null activity means
1743 // "don't update the activity" here.
1744
Makoto Onuki7001a612016-05-27 13:24:28 -07001745 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_UPDATE);
1746
Makoto Onuki55046222016-03-08 10:49:47 -08001747 // Throttling.
Makoto Onukic51b2872016-05-04 15:24:50 -07001748 if (!ps.tryApiCall()) {
Makoto Onuki55046222016-03-08 10:49:47 -08001749 return false;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001750 }
1751
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001752 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1753 ps.clearAllImplicitRanks();
1754 assignImplicitRanks(newShortcuts);
1755
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -08001756 // TODO: Consider removing Chooser fields. If so, the FLAG_CHOOSER should be removed
Makoto Onuki55046222016-03-08 10:49:47 -08001757 for (int i = 0; i < size; i++) {
1758 final ShortcutInfo source = newShortcuts.get(i);
1759 fixUpIncomingShortcutInfo(source, /* forUpdate= */ true);
1760
1761 final ShortcutInfo target = ps.findShortcutById(source.getId());
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001762 if (target == null) {
1763 continue;
1764 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07001765
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001766 if (target.isEnabled() != source.isEnabled()) {
1767 Slog.w(TAG,
1768 "ShortcutInfo.enabled cannot be changed with updateShortcuts()");
1769 }
Makoto Onuki55046222016-03-08 10:49:47 -08001770
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001771 // When updating the rank, we need to insert between existing ranks, so set
1772 // this setRankChanged, and also copy the implicit rank fo adjustRanks().
1773 if (source.hasRank()) {
1774 target.setRankChanged();
1775 target.setImplicitRank(source.getImplicitRank());
1776 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07001777
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001778 final boolean replacingIcon = (source.getIcon() != null);
1779 if (replacingIcon) {
1780 removeIcon(userId, target);
1781 }
Makoto Onuki55046222016-03-08 10:49:47 -08001782
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001783 // Note copyNonNullFieldsFrom() does the "updatable with?" check too.
1784 target.copyNonNullFieldsFrom(source);
1785 target.setTimestamp(injectCurrentTimeMillis());
1786
1787 if (replacingIcon) {
1788 saveIconAndFixUpShortcut(userId, target);
1789 }
1790
1791 // When we're updating any resource related fields, re-extract the res names and
1792 // the values.
1793 if (replacingIcon || source.hasStringResources()) {
1794 fixUpShortcutResourceNamesAndValues(target);
Makoto Onuki55046222016-03-08 10:49:47 -08001795 }
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -08001796
1797 // While updating, we keep the dynamic flag as it previously was, but refresh the
1798 // chooser flag.
1799 // TODO: If we support clearing Chooser fields, we should also remove the flag.
1800 if (target.getChooserIntentFilters() != null) {
1801 target.addFlags(ShortcutInfo.FLAG_CHOOSER);
1802 }
Makoto Onuki55046222016-03-08 10:49:47 -08001803 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001804
1805 // Lastly, adjust the ranks.
1806 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001807 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001808 packageShortcutsChanged(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001809
Makoto Onuki7001a612016-05-27 13:24:28 -07001810 verifyStates();
1811
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001812 return true;
1813 }
1814
1815 @Override
Makoto Onukib6d35232016-04-04 15:57:17 -07001816 public boolean addDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001817 @UserIdInt int userId) {
1818 verifyCaller(packageName, userId);
1819
Makoto Onukib6d35232016-04-04 15:57:17 -07001820 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
1821 final int size = newShortcuts.size();
1822
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001823 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001824 throwIfUserLockedL(userId);
1825
Makoto Onukic8c33292016-09-12 16:36:59 -07001826 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001827
Makoto Onuki22fcc682016-05-17 14:52:19 -07001828 ps.ensureImmutableShortcutsNotIncluded(newShortcuts);
1829
Makoto Onukib08790c2016-06-23 14:05:46 -07001830 fillInDefaultActivity(newShortcuts);
1831
Makoto Onuki7001a612016-05-27 13:24:28 -07001832 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_ADD);
1833
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001834 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1835 ps.clearAllImplicitRanks();
1836 assignImplicitRanks(newShortcuts);
1837
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001838 // Throttling.
Makoto Onukic51b2872016-05-04 15:24:50 -07001839 if (!ps.tryApiCall()) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001840 return false;
1841 }
Makoto Onukib6d35232016-04-04 15:57:17 -07001842 for (int i = 0; i < size; i++) {
1843 final ShortcutInfo newShortcut = newShortcuts.get(i);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001844
Makoto Onukib6d35232016-04-04 15:57:17 -07001845 // Validate the shortcut.
1846 fixUpIncomingShortcutInfo(newShortcut, /* forUpdate= */ false);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001847
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001848 // When ranks are changing, we need to insert between ranks, so set the
1849 // "rank changed" flag.
1850 newShortcut.setRankChanged();
1851
Makoto Onukib6d35232016-04-04 15:57:17 -07001852 // Add it.
Makoto Onuki22fcc682016-05-17 14:52:19 -07001853 ps.addOrUpdateDynamicShortcut(newShortcut);
Makoto Onukib6d35232016-04-04 15:57:17 -07001854 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001855
1856 // Lastly, adjust the ranks.
1857 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001858 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001859 packageShortcutsChanged(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001860
Makoto Onuki7001a612016-05-27 13:24:28 -07001861 verifyStates();
1862
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001863 return true;
1864 }
1865
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -08001866 // TODO: Ensure non-launchable shortcuts can not be pinned
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001867 @Override
Makoto Onuki2d895c32016-12-02 15:48:40 -08001868 public boolean requestPinShortcut(String packageName, ShortcutInfo shortcut,
1869 IntentSender resultIntent, int userId) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08001870 Preconditions.checkNotNull(shortcut);
1871 Preconditions.checkArgument(shortcut.isEnabled(), "Shortcut must be enabled");
Sunny Goyal4ad6b572017-02-28 11:11:51 -08001872 return requestPinItem(packageName, userId, shortcut, null, null, resultIntent);
Sunny Goyal87a563e2017-01-01 19:42:45 -08001873 }
1874
Sunny Goyala6be88a2017-01-12 16:27:58 -08001875 @Override
1876 public Intent createShortcutResultIntent(String packageName, ShortcutInfo shortcut, int userId)
1877 throws RemoteException {
1878 Preconditions.checkNotNull(shortcut);
1879 Preconditions.checkArgument(shortcut.isEnabled(), "Shortcut must be enabled");
1880 verifyCaller(packageName, userId);
1881
1882 final Intent ret;
1883 synchronized (mLock) {
1884 throwIfUserLockedL(userId);
1885
1886 // Send request to the launcher, if supported.
1887 ret = mShortcutRequestPinProcessor.createShortcutResultIntent(shortcut, userId);
1888 }
1889
1890 verifyStates();
1891 return ret;
1892 }
1893
Sunny Goyal87a563e2017-01-01 19:42:45 -08001894 /**
1895 * Handles {@link #requestPinShortcut} and {@link ShortcutServiceInternal#requestPinAppWidget}.
1896 * After validating the caller, it passes the request to {@link #mShortcutRequestPinProcessor}.
1897 * Either {@param shortcut} or {@param appWidget} should be non-null.
1898 */
Sunny Goyal4ad6b572017-02-28 11:11:51 -08001899 private boolean requestPinItem(String packageName, int userId, ShortcutInfo shortcut,
1900 AppWidgetProviderInfo appWidget, Bundle extras, IntentSender resultIntent) {
Sunny Goyal87a563e2017-01-01 19:42:45 -08001901 verifyCaller(packageName, userId);
Makoto Onuki2d895c32016-12-02 15:48:40 -08001902
1903 final boolean ret;
1904 synchronized (mLock) {
1905 throwIfUserLockedL(userId);
1906
Makoto Onukia01f4f02016-12-15 15:58:41 -08001907 Preconditions.checkState(isUidForegroundLocked(injectBinderCallingUid()),
Makoto Onuki255461f2017-01-10 11:47:25 -08001908 "Calling application must have a foreground activity or a foreground service");
Makoto Onuki2d895c32016-12-02 15:48:40 -08001909
1910 // Send request to the launcher, if supported.
Sunny Goyal4ad6b572017-02-28 11:11:51 -08001911 ret = mShortcutRequestPinProcessor.requestPinItemLocked(shortcut, appWidget, extras,
1912 userId, resultIntent);
Makoto Onuki2d895c32016-12-02 15:48:40 -08001913 }
1914
1915 verifyStates();
1916
1917 return ret;
1918 }
1919
1920 @Override
Makoto Onuki20c95f82016-05-11 16:51:01 -07001921 public void disableShortcuts(String packageName, List shortcutIds,
Makoto Onukid6880792016-06-29 13:37:43 -07001922 CharSequence disabledMessage, int disabledMessageResId, @UserIdInt int userId) {
Makoto Onuki20c95f82016-05-11 16:51:01 -07001923 verifyCaller(packageName, userId);
1924 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
1925
1926 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001927 throwIfUserLockedL(userId);
1928
Makoto Onukic8c33292016-09-12 16:36:59 -07001929 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001930
1931 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds);
1932
Makoto Onukid6880792016-06-29 13:37:43 -07001933 final String disabledMessageString =
1934 (disabledMessage == null) ? null : disabledMessage.toString();
1935
Makoto Onuki22fcc682016-05-17 14:52:19 -07001936 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
1937 ps.disableWithId(Preconditions.checkStringNotEmpty((String) shortcutIds.get(i)),
Makoto Onukid6880792016-06-29 13:37:43 -07001938 disabledMessageString, disabledMessageResId,
Makoto Onuki22fcc682016-05-17 14:52:19 -07001939 /* overrideImmutable=*/ false);
1940 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001941
1942 // We may have removed dynamic shortcuts which may have left a gap, so adjust the ranks.
1943 ps.adjustRanks();
Makoto Onuki22fcc682016-05-17 14:52:19 -07001944 }
1945 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001946
1947 verifyStates();
Makoto Onuki22fcc682016-05-17 14:52:19 -07001948 }
1949
1950 @Override
1951 public void enableShortcuts(String packageName, List shortcutIds, @UserIdInt int userId) {
1952 verifyCaller(packageName, userId);
1953 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
1954
1955 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001956 throwIfUserLockedL(userId);
1957
Makoto Onukic8c33292016-09-12 16:36:59 -07001958 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001959
1960 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds);
1961
1962 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
1963 ps.enableWithId((String) shortcutIds.get(i));
1964 }
Makoto Onuki20c95f82016-05-11 16:51:01 -07001965 }
1966 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001967
1968 verifyStates();
Makoto Onuki20c95f82016-05-11 16:51:01 -07001969 }
1970
1971 @Override
Makoto Onukib6d35232016-04-04 15:57:17 -07001972 public void removeDynamicShortcuts(String packageName, List shortcutIds,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001973 @UserIdInt int userId) {
1974 verifyCaller(packageName, userId);
Makoto Onukib6d35232016-04-04 15:57:17 -07001975 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001976
1977 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001978 throwIfUserLockedL(userId);
1979
Makoto Onukic8c33292016-09-12 16:36:59 -07001980 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001981
1982 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds);
1983
Makoto Onukib6d35232016-04-04 15:57:17 -07001984 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07001985 ps.deleteDynamicWithId(
Makoto Onukib6d35232016-04-04 15:57:17 -07001986 Preconditions.checkStringNotEmpty((String) shortcutIds.get(i)));
1987 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001988
1989 // We may have removed dynamic shortcuts which may have left a gap, so adjust the ranks.
1990 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001991 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001992 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001993
1994 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001995 }
1996
1997 @Override
Makoto Onukib6d35232016-04-04 15:57:17 -07001998 public void removeAllDynamicShortcuts(String packageName, @UserIdInt int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001999 verifyCaller(packageName, userId);
2000
2001 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002002 throwIfUserLockedL(userId);
2003
Makoto Onukic8c33292016-09-12 16:36:59 -07002004 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002005 ps.deleteAllDynamicShortcuts();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002006 }
Makoto Onuki39686e82016-04-13 18:03:00 -07002007 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07002008
2009 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002010 }
2011
2012 @Override
2013 public ParceledListSlice<ShortcutInfo> getDynamicShortcuts(String packageName,
2014 @UserIdInt int userId) {
2015 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002016
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002017 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002018 throwIfUserLockedL(userId);
2019
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002020 return getShortcutsWithQueryLocked(
2021 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -08002022 ShortcutInfo::isDynamicOrChooser);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002023 }
2024 }
2025
2026 @Override
Makoto Onuki22fcc682016-05-17 14:52:19 -07002027 public ParceledListSlice<ShortcutInfo> getManifestShortcuts(String packageName,
2028 @UserIdInt int userId) {
2029 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002030
Makoto Onuki22fcc682016-05-17 14:52:19 -07002031 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002032 throwIfUserLockedL(userId);
2033
Makoto Onuki22fcc682016-05-17 14:52:19 -07002034 return getShortcutsWithQueryLocked(
2035 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
2036 ShortcutInfo::isManifestShortcut);
2037 }
2038 }
2039
2040 @Override
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002041 public ParceledListSlice<ShortcutInfo> getPinnedShortcuts(String packageName,
2042 @UserIdInt int userId) {
2043 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002044
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002045 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002046 throwIfUserLockedL(userId);
2047
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002048 return getShortcutsWithQueryLocked(
2049 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
2050 ShortcutInfo::isPinned);
2051 }
2052 }
2053
2054 private ParceledListSlice<ShortcutInfo> getShortcutsWithQueryLocked(@NonNull String packageName,
2055 @UserIdInt int userId, int cloneFlags, @NonNull Predicate<ShortcutInfo> query) {
2056
2057 final ArrayList<ShortcutInfo> ret = new ArrayList<>();
2058
Makoto Onukic8c33292016-09-12 16:36:59 -07002059 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002060 ps.findAll(ret, query, cloneFlags);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002061
2062 return new ParceledListSlice<>(ret);
2063 }
2064
2065 @Override
Makoto Onukid6880792016-06-29 13:37:43 -07002066 public int getMaxShortcutCountPerActivity(String packageName, @UserIdInt int userId)
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002067 throws RemoteException {
2068 verifyCaller(packageName, userId);
2069
Makoto Onukib5a012f2016-06-21 11:13:53 -07002070 return mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002071 }
2072
2073 @Override
2074 public int getRemainingCallCount(String packageName, @UserIdInt int userId) {
2075 verifyCaller(packageName, userId);
2076
2077 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002078 throwIfUserLockedL(userId);
2079
Makoto Onukic8c33292016-09-12 16:36:59 -07002080 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002081 return mMaxUpdatesPerInterval - ps.getApiCallCount();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002082 }
2083 }
2084
2085 @Override
2086 public long getRateLimitResetTime(String packageName, @UserIdInt int userId) {
2087 verifyCaller(packageName, userId);
2088
2089 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002090 throwIfUserLockedL(userId);
2091
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002092 return getNextResetTimeLocked();
2093 }
2094 }
2095
Makoto Onuki55046222016-03-08 10:49:47 -08002096 @Override
Makoto Onuki20c95f82016-05-11 16:51:01 -07002097 public int getIconMaxDimensions(String packageName, int userId) {
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002098 verifyCaller(packageName, userId);
2099
Makoto Onuki55046222016-03-08 10:49:47 -08002100 synchronized (mLock) {
2101 return mMaxIconDimension;
2102 }
2103 }
2104
Makoto Onuki20c95f82016-05-11 16:51:01 -07002105 @Override
2106 public void reportShortcutUsed(String packageName, String shortcutId, int userId) {
2107 verifyCaller(packageName, userId);
2108
Makoto Onukiac042502016-05-20 16:39:42 -07002109 Preconditions.checkNotNull(shortcutId);
2110
2111 if (DEBUG) {
2112 Slog.d(TAG, String.format("reportShortcutUsed: Shortcut %s package %s used on user %d",
2113 shortcutId, packageName, userId));
2114 }
2115
2116 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002117 throwIfUserLockedL(userId);
2118
Makoto Onukic8c33292016-09-12 16:36:59 -07002119 final ShortcutPackage ps = getPackageShortcutsForPublisherLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002120
Makoto Onukiac042502016-05-20 16:39:42 -07002121 if (ps.findShortcutById(shortcutId) == null) {
2122 Log.w(TAG, String.format("reportShortcutUsed: package %s doesn't have shortcut %s",
2123 packageName, shortcutId));
2124 return;
2125 }
2126 }
2127
2128 final long token = injectClearCallingIdentity();
2129 try {
2130 mUsageStatsManagerInternal.reportShortcutUsage(packageName, shortcutId, userId);
2131 } finally {
2132 injectRestoreCallingIdentity(token);
2133 }
Makoto Onuki20c95f82016-05-11 16:51:01 -07002134 }
2135
Makoto Onuki2d895c32016-12-02 15:48:40 -08002136 @Override
Sunny Goyal7f7372a2017-01-24 11:53:54 -08002137 public boolean isRequestPinItemSupported(int callingUserId, int requestType) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08002138 final long token = injectClearCallingIdentity();
2139 try {
Sunny Goyal7f7372a2017-01-24 11:53:54 -08002140 return mShortcutRequestPinProcessor
2141 .isRequestPinItemSupported(callingUserId, requestType);
Makoto Onuki2d895c32016-12-02 15:48:40 -08002142 } finally {
2143 injectRestoreCallingIdentity(token);
2144 }
2145 }
2146
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002147 /**
Makoto Onukib08790c2016-06-23 14:05:46 -07002148 * Reset all throttling, for developer options and command line. Only system/shell can call
2149 * it.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002150 */
2151 @Override
2152 public void resetThrottling() {
2153 enforceSystemOrShell();
2154
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002155 resetThrottlingInner(getCallingUserId());
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002156 }
2157
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002158 void resetThrottlingInner(@UserIdInt int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002159 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002160 if (!isUserUnlockedL(userId)) {
2161 Log.w(TAG, "User " + userId + " is locked or not running");
2162 return;
2163 }
2164
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002165 getUserShortcutsLocked(userId).resetThrottling();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002166 }
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002167 scheduleSaveUser(userId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002168 Slog.i(TAG, "ShortcutManager: throttling counter reset for user " + userId);
2169 }
2170
2171 void resetAllThrottlingInner() {
2172 synchronized (mLock) {
2173 mRawLastResetTime = injectCurrentTimeMillis();
2174 }
2175 scheduleSaveBaseState();
2176 Slog.i(TAG, "ShortcutManager: throttling counter reset for all users");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002177 }
2178
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002179 @Override
2180 public void onApplicationActive(String packageName, int userId) {
2181 if (DEBUG) {
2182 Slog.d(TAG, "onApplicationActive: package=" + packageName + " userid=" + userId);
2183 }
2184 enforceResetThrottlingPermission();
Makoto Onuki02f338e2016-07-29 09:40:40 -07002185
2186 synchronized (mLock) {
2187 if (!isUserUnlockedL(userId)) {
2188 // This is called by system UI, so no need to throw. Just ignore.
2189 return;
2190 }
2191
2192 getPackageShortcutsLocked(packageName, userId)
2193 .resetRateLimitingForCommandLineNoSaving();
2194 saveUserLocked(userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002195 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002196 }
2197
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002198 // We override this method in unit tests to do a simpler check.
2199 boolean hasShortcutHostPermission(@NonNull String callingPackage, int userId) {
Makoto Onuki10305202016-07-14 18:14:08 -07002200 final long start = injectElapsedRealtime();
2201 try {
2202 return hasShortcutHostPermissionInner(callingPackage, userId);
2203 } finally {
2204 logDurationStat(Stats.LAUNCHER_PERMISSION_CHECK, start);
2205 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002206 }
2207
2208 // This method is extracted so we can directly call this method from unit tests,
2209 // even when hasShortcutPermission() is overridden.
2210 @VisibleForTesting
Makoto Onuki2d895c32016-12-02 15:48:40 -08002211 boolean hasShortcutHostPermissionInner(@NonNull String packageName, int userId) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002212 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002213 throwIfUserLockedL(userId);
2214
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -08002215 // For the chooser, we just check is the system is calling.
2216 // STOPSHIP: We need to implement a new permission here rather than this terrible check.
2217 // The packageName check is to try to distinguish between when an actual
2218 // launcher is making the call, and when it's the system.
2219 if (isCallerSystem() && packageName.equals("android")) {
2220 return true;
2221 }
2222
Makoto Onuki31459242016-03-22 11:12:18 -07002223 final ShortcutUser user = getUserShortcutsLocked(userId);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002224
Makoto Onuki2d895c32016-12-02 15:48:40 -08002225 // Always trust the cached component.
Makoto Onuki10305202016-07-14 18:14:08 -07002226 final ComponentName cached = user.getCachedLauncher();
2227 if (cached != null) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08002228 if (cached.getPackageName().equals(packageName)) {
Makoto Onuki10305202016-07-14 18:14:08 -07002229 return true;
2230 }
2231 }
2232 // If the cached one doesn't match, then go ahead
2233
Makoto Onuki2d895c32016-12-02 15:48:40 -08002234 final ComponentName detected = getDefaultLauncher(userId);
Makoto Onuki2e210c42016-03-30 08:30:36 -07002235
Makoto Onuki10305202016-07-14 18:14:08 -07002236 // Update the cache.
2237 user.setLauncher(detected);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002238 if (detected != null) {
2239 if (DEBUG) {
2240 Slog.v(TAG, "Detected launcher: " + detected);
2241 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08002242 return detected.getPackageName().equals(packageName);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002243 } else {
2244 // Default launcher not found.
2245 return false;
2246 }
2247 }
2248 }
2249
Makoto Onuki2d895c32016-12-02 15:48:40 -08002250 @Nullable
2251 ComponentName getDefaultLauncher(@UserIdInt int userId) {
2252 final long start = injectElapsedRealtime();
2253 final long token = injectClearCallingIdentity();
2254 try {
2255 synchronized (mLock) {
2256 throwIfUserLockedL(userId);
2257
2258 final ShortcutUser user = getUserShortcutsLocked(userId);
2259
2260 final List<ResolveInfo> allHomeCandidates = new ArrayList<>();
2261
2262 // Default launcher from package manager.
2263 final long startGetHomeActivitiesAsUser = injectElapsedRealtime();
2264 final ComponentName defaultLauncher = mPackageManagerInternal
2265 .getHomeActivitiesAsUser(allHomeCandidates, userId);
2266 logDurationStat(Stats.GET_DEFAULT_HOME, startGetHomeActivitiesAsUser);
2267
2268 ComponentName detected = null;
2269 if (defaultLauncher != null) {
2270 detected = defaultLauncher;
2271 if (DEBUG) {
2272 Slog.v(TAG, "Default launcher from PM: " + detected);
2273 }
2274 } else {
2275 detected = user.getLastKnownLauncher();
2276
2277 if (detected != null) {
2278 if (injectIsActivityEnabledAndExported(detected, userId)) {
2279 if (DEBUG) {
2280 Slog.v(TAG, "Cached launcher: " + detected);
2281 }
2282 } else {
2283 Slog.w(TAG, "Cached launcher " + detected + " no longer exists");
2284 detected = null;
2285 user.clearLauncher();
2286 }
2287 }
2288 }
2289
2290 if (detected == null) {
2291 // If we reach here, that means it's the first check since the user was created,
2292 // and there's already multiple launchers and there's no default set.
2293 // Find the system one with the highest priority.
2294 // (We need to check the priority too because of FallbackHome in Settings.)
2295 // If there's no system launcher yet, then no one can access shortcuts, until
2296 // the user explicitly
2297 final int size = allHomeCandidates.size();
2298
2299 int lastPriority = Integer.MIN_VALUE;
2300 for (int i = 0; i < size; i++) {
2301 final ResolveInfo ri = allHomeCandidates.get(i);
2302 if (!ri.activityInfo.applicationInfo.isSystemApp()) {
2303 continue;
2304 }
2305 if (DEBUG) {
2306 Slog.d(TAG, String.format("hasShortcutPermissionInner: pkg=%s prio=%d",
2307 ri.activityInfo.getComponentName(), ri.priority));
2308 }
2309 if (ri.priority < lastPriority) {
2310 continue;
2311 }
2312 detected = ri.activityInfo.getComponentName();
2313 lastPriority = ri.priority;
2314 }
2315 }
2316 return detected;
2317 }
2318 } finally {
2319 injectRestoreCallingIdentity(token);
2320 logDurationStat(Stats.GET_DEFAULT_LAUNCHER, start);
2321 }
2322 }
2323
Makoto Onukicdc78f72016-03-21 15:47:52 -07002324 // === House keeping ===
2325
Makoto Onukib08790c2016-06-23 14:05:46 -07002326 private void cleanUpPackageForAllLoadedUsers(String packageName, @UserIdInt int packageUserId,
2327 boolean appStillExists) {
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002328 synchronized (mLock) {
2329 forEachLoadedUserLocked(user ->
Makoto Onukib08790c2016-06-23 14:05:46 -07002330 cleanUpPackageLocked(packageName, user.getUserId(), packageUserId,
2331 appStillExists));
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002332 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002333 }
2334
Makoto Onuki2e210c42016-03-30 08:30:36 -07002335 /**
2336 * Remove all the information associated with a package. This will really remove all the
2337 * information, including the restore information (i.e. it'll remove packages even if they're
2338 * shadow).
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002339 *
2340 * This is called when an app is uninstalled, or an app gets "clear data"ed.
Makoto Onuki2e210c42016-03-30 08:30:36 -07002341 */
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002342 @VisibleForTesting
Makoto Onukib08790c2016-06-23 14:05:46 -07002343 void cleanUpPackageLocked(String packageName, int owningUserId, int packageUserId,
2344 boolean appStillExists) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002345 final boolean wasUserLoaded = isUserLoadedLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002346
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002347 final ShortcutUser user = getUserShortcutsLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002348 boolean doNotify = false;
2349
2350 // First, remove the package from the package list (if the package is a publisher).
Makoto Onukid99c6f02016-03-28 11:02:54 -07002351 if (packageUserId == owningUserId) {
Makoto Onukic51b2872016-05-04 15:24:50 -07002352 if (user.removePackage(packageName) != null) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002353 doNotify = true;
2354 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07002355 }
Makoto Onukid99c6f02016-03-28 11:02:54 -07002356
Makoto Onukicdc78f72016-03-21 15:47:52 -07002357 // Also remove from the launcher list (if the package is a launcher).
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002358 user.removeLauncher(packageUserId, packageName);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002359
2360 // Then remove pinned shortcuts from all launchers.
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002361 user.forAllLaunchers(l -> l.cleanUpPackage(packageName, packageUserId));
2362
2363 // Now there may be orphan shortcuts because we removed pinned shortcuts at the previous
Makoto Onukicdc78f72016-03-21 15:47:52 -07002364 // step. Remove them too.
Makoto Onukic51b2872016-05-04 15:24:50 -07002365 user.forAllPackages(p -> p.refreshPinnedFlags());
Makoto Onukicdc78f72016-03-21 15:47:52 -07002366
Makoto Onukid99c6f02016-03-28 11:02:54 -07002367 scheduleSaveUser(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002368
2369 if (doNotify) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002370 notifyListeners(packageName, owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002371 }
2372
Makoto Onukib08790c2016-06-23 14:05:46 -07002373 // If the app still exists (i.e. data cleared), we need to re-publish manifest shortcuts.
2374 if (appStillExists && (packageUserId == owningUserId)) {
2375 // This will do the notification and save when needed, so do it after the above
2376 // notifyListeners.
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002377 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07002378 }
2379
Makoto Onukicdc78f72016-03-21 15:47:52 -07002380 if (!wasUserLoaded) {
2381 // Note this will execute the scheduled save.
Makoto Onukid99c6f02016-03-28 11:02:54 -07002382 unloadUserLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002383 }
2384 }
2385
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002386 /**
2387 * Entry point from {@link LauncherApps}.
2388 */
2389 private class LocalService extends ShortcutServiceInternal {
Makoto Onuki2e210c42016-03-30 08:30:36 -07002390
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002391 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002392 public List<ShortcutInfo> getShortcuts(int launcherUserId,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002393 @NonNull String callingPackage, long changedSince,
Makoto Onukiabe84422016-04-07 09:41:19 -07002394 @Nullable String packageName, @Nullable List<String> shortcutIds,
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -08002395 @Nullable ComponentName componentName, @Nullable Intent intent,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002396 int queryFlags, int userId) {
2397 final ArrayList<ShortcutInfo> ret = new ArrayList<>();
Makoto Onuki9c850012016-07-26 15:50:50 -07002398
Makoto Onuki20c95f82016-05-11 16:51:01 -07002399 final boolean cloneKeyFieldOnly =
2400 ((queryFlags & ShortcutQuery.FLAG_GET_KEY_FIELDS_ONLY) != 0);
2401 final int cloneFlag = cloneKeyFieldOnly ? ShortcutInfo.CLONE_REMOVE_NON_KEY_INFO
2402 : ShortcutInfo.CLONE_REMOVE_FOR_LAUNCHER;
Makoto Onukiabe84422016-04-07 09:41:19 -07002403 if (packageName == null) {
2404 shortcutIds = null; // LauncherAppsService already threw for it though.
2405 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002406
2407 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002408 throwIfUserLockedL(userId);
2409 throwIfUserLockedL(launcherUserId);
2410
Makoto Onuki2e210c42016-03-30 08:30:36 -07002411 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002412 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002413
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002414 if (packageName != null) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002415 getShortcutsInnerLocked(launcherUserId,
Makoto Onukiabe84422016-04-07 09:41:19 -07002416 callingPackage, packageName, shortcutIds, changedSince,
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -08002417 componentName, intent, queryFlags, userId, ret, cloneFlag);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002418 } else {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002419 final List<String> shortcutIdsF = shortcutIds;
2420 getUserShortcutsLocked(userId).forAllPackages(p -> {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002421 getShortcutsInnerLocked(launcherUserId,
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002422 callingPackage, p.getPackageName(), shortcutIdsF, changedSince,
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -08002423 componentName, intent, queryFlags, userId, ret, cloneFlag);
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002424 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002425 }
2426 }
2427 return ret;
2428 }
2429
Makoto Onukid99c6f02016-03-28 11:02:54 -07002430 private void getShortcutsInnerLocked(int launcherUserId, @NonNull String callingPackage,
Makoto Onukiabe84422016-04-07 09:41:19 -07002431 @Nullable String packageName, @Nullable List<String> shortcutIds, long changedSince,
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -08002432 @Nullable ComponentName componentName, Intent intent, int queryFlags,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002433 int userId, ArrayList<ShortcutInfo> ret, int cloneFlag) {
Makoto Onukiabe84422016-04-07 09:41:19 -07002434 final ArraySet<String> ids = shortcutIds == null ? null
2435 : new ArraySet<>(shortcutIds);
2436
Makoto Onukic51b2872016-05-04 15:24:50 -07002437 final ShortcutPackage p = getUserShortcutsLocked(userId)
2438 .getPackageShortcutsIfExists(packageName);
2439 if (p == null) {
2440 return; // No need to instantiate ShortcutPackage.
2441 }
2442
2443 p.findAll(ret,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002444 (ShortcutInfo si) -> {
2445 if (si.getLastChangedTimestamp() < changedSince) {
2446 return false;
2447 }
Makoto Onukiabe84422016-04-07 09:41:19 -07002448 if (ids != null && !ids.contains(si.getId())) {
2449 return false;
2450 }
Makoto Onuki85694522016-05-04 12:53:37 -07002451 if (componentName != null) {
Makoto Onuki9fd90192017-01-06 18:31:03 +00002452 if (si.getActivity() != null
2453 && !si.getActivity().equals(componentName)) {
Makoto Onuki85694522016-05-04 12:53:37 -07002454 return false;
2455 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002456 }
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -08002457 if (intent != null
2458 && !si.hasMatchingFilter(mContext.getContentResolver(), intent)) {
2459 return false;
2460 }
2461
2462 if (((queryFlags & ShortcutQuery.FLAG_MATCH_CHOOSER) != 0)
2463 && si.isChooser()) {
2464 return true;
2465 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002466 if (((queryFlags & ShortcutQuery.FLAG_GET_DYNAMIC) != 0)
2467 && si.isDynamic()) {
2468 return true;
2469 }
2470 if (((queryFlags & ShortcutQuery.FLAG_GET_PINNED) != 0)
2471 && si.isPinned()) {
2472 return true;
2473 }
2474 if (((queryFlags & ShortcutQuery.FLAG_GET_MANIFEST) != 0)
2475 && si.isManifestShortcut()) {
2476 return true;
2477 }
2478 return false;
Makoto Onukid99c6f02016-03-28 11:02:54 -07002479 }, cloneFlag, callingPackage, launcherUserId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002480 }
2481
2482 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002483 public boolean isPinnedByCaller(int launcherUserId, @NonNull String callingPackage,
2484 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2485 Preconditions.checkStringNotEmpty(packageName, "packageName");
2486 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
2487
2488 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002489 throwIfUserLockedL(userId);
2490 throwIfUserLockedL(launcherUserId);
2491
Makoto Onuki2e210c42016-03-30 08:30:36 -07002492 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002493 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002494
Makoto Onukid99c6f02016-03-28 11:02:54 -07002495 final ShortcutInfo si = getShortcutInfoLocked(
2496 launcherUserId, callingPackage, packageName, shortcutId, userId);
2497 return si != null && si.isPinned();
2498 }
2499 }
2500
Makoto Onuki2e210c42016-03-30 08:30:36 -07002501 private ShortcutInfo getShortcutInfoLocked(
Makoto Onukid99c6f02016-03-28 11:02:54 -07002502 int launcherUserId, @NonNull String callingPackage,
2503 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2504 Preconditions.checkStringNotEmpty(packageName, "packageName");
2505 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
2506
Makoto Onuki02f338e2016-07-29 09:40:40 -07002507 throwIfUserLockedL(userId);
2508 throwIfUserLockedL(launcherUserId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002509
Makoto Onukic51b2872016-05-04 15:24:50 -07002510 final ShortcutPackage p = getUserShortcutsLocked(userId)
2511 .getPackageShortcutsIfExists(packageName);
2512 if (p == null) {
2513 return null;
2514 }
2515
Makoto Onukid99c6f02016-03-28 11:02:54 -07002516 final ArrayList<ShortcutInfo> list = new ArrayList<>(1);
Makoto Onukic51b2872016-05-04 15:24:50 -07002517 p.findAll(list,
Makoto Onukid99c6f02016-03-28 11:02:54 -07002518 (ShortcutInfo si) -> shortcutId.equals(si.getId()),
2519 /* clone flags=*/ 0, callingPackage, launcherUserId);
2520 return list.size() == 0 ? null : list.get(0);
2521 }
2522
2523 @Override
2524 public void pinShortcuts(int launcherUserId,
2525 @NonNull String callingPackage, @NonNull String packageName,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002526 @NonNull List<String> shortcutIds, int userId) {
2527 // Calling permission must be checked by LauncherAppsImpl.
2528 Preconditions.checkStringNotEmpty(packageName, "packageName");
2529 Preconditions.checkNotNull(shortcutIds, "shortcutIds");
2530
2531 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002532 throwIfUserLockedL(userId);
2533 throwIfUserLockedL(launcherUserId);
2534
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002535 final ShortcutLauncher launcher =
Makoto Onuki2e210c42016-03-30 08:30:36 -07002536 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId);
Makoto Onukic51b2872016-05-04 15:24:50 -07002537 launcher.attemptToRestoreIfNeededAndSave();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002538
Makoto Onukic51b2872016-05-04 15:24:50 -07002539 launcher.pinShortcuts(userId, packageName, shortcutIds);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002540 }
Makoto Onuki39686e82016-04-13 18:03:00 -07002541 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07002542
2543 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002544 }
2545
2546 @Override
Makoto Onuki440a1ea2016-07-20 14:21:18 -07002547 public Intent[] createShortcutIntents(int launcherUserId,
Makoto Onukid99c6f02016-03-28 11:02:54 -07002548 @NonNull String callingPackage,
Makoto Onuki43204b82016-03-08 16:16:44 -08002549 @NonNull String packageName, @NonNull String shortcutId, int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002550 // Calling permission must be checked by LauncherAppsImpl.
Makoto Onuki43204b82016-03-08 16:16:44 -08002551 Preconditions.checkStringNotEmpty(packageName, "packageName can't be empty");
2552 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId can't be empty");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002553
2554 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002555 throwIfUserLockedL(userId);
2556 throwIfUserLockedL(launcherUserId);
2557
Makoto Onuki2e210c42016-03-30 08:30:36 -07002558 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002559 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002560
Makoto Onukid99c6f02016-03-28 11:02:54 -07002561 // Make sure the shortcut is actually visible to the launcher.
2562 final ShortcutInfo si = getShortcutInfoLocked(
2563 launcherUserId, callingPackage, packageName, shortcutId, userId);
2564 // "si == null" should suffice here, but check the flags too just to make sure.
Makoto Onuki22fcc682016-05-17 14:52:19 -07002565 if (si == null || !si.isEnabled() || !si.isAlive()) {
Makoto Onuki83f6d2d2016-07-11 14:30:19 -07002566 Log.e(TAG, "Shortcut " + shortcutId + " does not exist or disabled");
Makoto Onukid99c6f02016-03-28 11:02:54 -07002567 return null;
2568 }
Makoto Onuki440a1ea2016-07-20 14:21:18 -07002569 return si.getIntents();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002570 }
2571 }
2572
2573 @Override
2574 public void addListener(@NonNull ShortcutChangeListener listener) {
2575 synchronized (mLock) {
2576 mListeners.add(Preconditions.checkNotNull(listener));
2577 }
2578 }
Makoto Onuki55046222016-03-08 10:49:47 -08002579
2580 @Override
Makoto Onukiabe84422016-04-07 09:41:19 -07002581 public int getShortcutIconResId(int launcherUserId, @NonNull String callingPackage,
2582 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2583 Preconditions.checkNotNull(callingPackage, "callingPackage");
2584 Preconditions.checkNotNull(packageName, "packageName");
2585 Preconditions.checkNotNull(shortcutId, "shortcutId");
Makoto Onuki55046222016-03-08 10:49:47 -08002586
2587 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002588 throwIfUserLockedL(userId);
2589 throwIfUserLockedL(launcherUserId);
2590
Makoto Onuki2e210c42016-03-30 08:30:36 -07002591 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002592 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002593
Makoto Onukic51b2872016-05-04 15:24:50 -07002594 final ShortcutPackage p = getUserShortcutsLocked(userId)
2595 .getPackageShortcutsIfExists(packageName);
2596 if (p == null) {
2597 return 0;
2598 }
2599
2600 final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId);
Makoto Onuki55046222016-03-08 10:49:47 -08002601 return (shortcutInfo != null && shortcutInfo.hasIconResource())
2602 ? shortcutInfo.getIconResourceId() : 0;
2603 }
2604 }
2605
2606 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002607 public ParcelFileDescriptor getShortcutIconFd(int launcherUserId,
Makoto Onukiabe84422016-04-07 09:41:19 -07002608 @NonNull String callingPackage, @NonNull String packageName,
2609 @NonNull String shortcutId, int userId) {
2610 Preconditions.checkNotNull(callingPackage, "callingPackage");
2611 Preconditions.checkNotNull(packageName, "packageName");
2612 Preconditions.checkNotNull(shortcutId, "shortcutId");
Makoto Onuki55046222016-03-08 10:49:47 -08002613
2614 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002615 throwIfUserLockedL(userId);
2616 throwIfUserLockedL(launcherUserId);
2617
Makoto Onuki2e210c42016-03-30 08:30:36 -07002618 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002619 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002620
Makoto Onukic51b2872016-05-04 15:24:50 -07002621 final ShortcutPackage p = getUserShortcutsLocked(userId)
2622 .getPackageShortcutsIfExists(packageName);
2623 if (p == null) {
2624 return null;
2625 }
2626
2627 final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId);
Makoto Onuki55046222016-03-08 10:49:47 -08002628 if (shortcutInfo == null || !shortcutInfo.hasIconFile()) {
2629 return null;
2630 }
2631 try {
Makoto Onuki34d1c912016-03-10 14:24:58 -08002632 if (shortcutInfo.getBitmapPath() == null) {
2633 Slog.w(TAG, "null bitmap detected in getShortcutIconFd()");
2634 return null;
2635 }
Makoto Onuki55046222016-03-08 10:49:47 -08002636 return ParcelFileDescriptor.open(
2637 new File(shortcutInfo.getBitmapPath()),
2638 ParcelFileDescriptor.MODE_READ_ONLY);
2639 } catch (FileNotFoundException e) {
2640 Slog.e(TAG, "Icon file not found: " + shortcutInfo.getBitmapPath());
2641 return null;
2642 }
2643 }
2644 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002645
2646 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002647 public boolean hasShortcutHostPermission(int launcherUserId,
2648 @NonNull String callingPackage) {
2649 return ShortcutService.this.hasShortcutHostPermission(callingPackage, launcherUserId);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002650 }
Sunny Goyal87a563e2017-01-01 19:42:45 -08002651
2652 @Override
2653 public boolean requestPinAppWidget(@NonNull String callingPackage,
Sunny Goyal4ad6b572017-02-28 11:11:51 -08002654 @NonNull AppWidgetProviderInfo appWidget, @Nullable Bundle extras,
2655 @Nullable IntentSender resultIntent, int userId) {
Sunny Goyal87a563e2017-01-01 19:42:45 -08002656 Preconditions.checkNotNull(appWidget);
Sunny Goyal4ad6b572017-02-28 11:11:51 -08002657 return requestPinItem(callingPackage, userId, null, appWidget, extras, resultIntent);
Sunny Goyal87a563e2017-01-01 19:42:45 -08002658 }
Sunny Goyal7f7372a2017-01-24 11:53:54 -08002659
2660 @Override
2661 public boolean isRequestPinItemSupported(int callingUserId, int requestType) {
2662 return ShortcutService.this.isRequestPinItemSupported(callingUserId, requestType);
2663 }
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002664 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002665
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002666 final BroadcastReceiver mReceiver = new BroadcastReceiver() {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002667 @Override
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002668 public void onReceive(Context context, Intent intent) {
2669 if (!mBootCompleted.get()) {
2670 return; // Boot not completed, ignore the broadcast.
2671 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07002672 try {
2673 if (Intent.ACTION_LOCALE_CHANGED.equals(intent.getAction())) {
2674 handleLocaleChanged();
2675 }
2676 } catch (Exception e) {
2677 wtf("Exception in mReceiver.onReceive", e);
Makoto Onukic51b2872016-05-04 15:24:50 -07002678 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002679 }
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002680 };
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002681
Makoto Onuki157b1622016-06-02 16:13:10 -07002682 void handleLocaleChanged() {
2683 if (DEBUG) {
2684 Slog.d(TAG, "handleLocaleChanged");
2685 }
2686 scheduleSaveBaseState();
2687
Makoto Onuki02f338e2016-07-29 09:40:40 -07002688 synchronized (mLock) {
2689 final long token = injectClearCallingIdentity();
2690 try {
2691 forEachLoadedUserLocked(user -> user.detectLocaleChange());
2692 } finally {
2693 injectRestoreCallingIdentity(token);
2694 }
Makoto Onuki157b1622016-06-02 16:13:10 -07002695 }
2696 }
2697
Makoto Onukif34c3082016-07-13 10:25:25 -07002698 /**
2699 * Package event callbacks.
2700 */
2701 @VisibleForTesting
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002702 final BroadcastReceiver mPackageMonitor = new BroadcastReceiver() {
Makoto Onukif34c3082016-07-13 10:25:25 -07002703 @Override
2704 public void onReceive(Context context, Intent intent) {
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002705 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
2706 if (userId == UserHandle.USER_NULL) {
2707 Slog.w(TAG, "Intent broadcast does not contain user handle: " + intent);
2708 return;
2709 }
2710
2711 final String action = intent.getAction();
2712
2713 // This is normally called on Handler, so clearCallingIdentity() isn't needed,
2714 // but we still check it in unit tests.
Makoto Onukif34c3082016-07-13 10:25:25 -07002715 final long token = injectClearCallingIdentity();
2716 try {
Makoto Onuki10305202016-07-14 18:14:08 -07002717 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002718 if (!isUserUnlockedL(userId)) {
2719 if (DEBUG) {
2720 Slog.d(TAG, "Ignoring package broadcast " + action
2721 + " for locked/stopped user " + userId);
2722 }
2723 return;
2724 }
2725
2726 // Whenever we get one of those package broadcasts, or get
2727 // ACTION_PREFERRED_ACTIVITY_CHANGED, we purge the default launcher cache.
Makoto Onuki10305202016-07-14 18:14:08 -07002728 final ShortcutUser user = getUserShortcutsLocked(userId);
2729 user.clearLauncher();
2730 }
2731 if (Intent.ACTION_PREFERRED_ACTIVITY_CHANGED.equals(action)) {
2732 // Nothing farther to do.
2733 return;
2734 }
2735
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002736 final Uri intentUri = intent.getData();
2737 final String packageName = (intentUri != null) ? intentUri.getSchemeSpecificPart()
2738 : null;
2739 if (packageName == null) {
2740 Slog.w(TAG, "Intent broadcast does not contain package name: " + intent);
2741 return;
2742 }
2743
2744 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
2745
2746 switch (action) {
2747 case Intent.ACTION_PACKAGE_ADDED:
2748 if (replacing) {
2749 handlePackageUpdateFinished(packageName, userId);
2750 } else {
2751 handlePackageAdded(packageName, userId);
2752 }
2753 break;
2754 case Intent.ACTION_PACKAGE_REMOVED:
2755 if (!replacing) {
2756 handlePackageRemoved(packageName, userId);
2757 }
2758 break;
2759 case Intent.ACTION_PACKAGE_CHANGED:
2760 handlePackageChanged(packageName, userId);
2761
2762 break;
2763 case Intent.ACTION_PACKAGE_DATA_CLEARED:
2764 handlePackageDataCleared(packageName, userId);
2765 break;
2766 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07002767 } catch (Exception e) {
2768 wtf("Exception in mPackageMonitor.onReceive", e);
Makoto Onukif34c3082016-07-13 10:25:25 -07002769 } finally {
2770 injectRestoreCallingIdentity(token);
Makoto Onukia2241832016-07-06 13:28:37 -07002771 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07002772 }
Makoto Onukif34c3082016-07-13 10:25:25 -07002773 };
Makoto Onukicdc78f72016-03-21 15:47:52 -07002774
Makoto Onuki0acbb142016-03-22 17:02:57 -07002775 /**
Makoto Onuki39686e82016-04-13 18:03:00 -07002776 * Called when a user is unlocked.
2777 * - Check all known packages still exist, and otherwise perform cleanup.
2778 * - If a package still exists, check the version code. If it's been updated, may need to
Makoto Onukib08790c2016-06-23 14:05:46 -07002779 * update timestamps of its shortcuts.
Makoto Onuki0acbb142016-03-22 17:02:57 -07002780 */
Makoto Onukid99c6f02016-03-28 11:02:54 -07002781 @VisibleForTesting
Makoto Onuki39686e82016-04-13 18:03:00 -07002782 void checkPackageChanges(@UserIdInt int ownerUserId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07002783 if (DEBUG) {
Makoto Onuki39686e82016-04-13 18:03:00 -07002784 Slog.d(TAG, "checkPackageChanges() ownerUserId=" + ownerUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002785 }
Makoto Onukib08790c2016-06-23 14:05:46 -07002786 if (injectIsSafeModeEnabled()) {
2787 Slog.i(TAG, "Safe mode, skipping checkPackageChanges()");
2788 return;
2789 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07002790
Makoto Onuki22fcc682016-05-17 14:52:19 -07002791 final long start = injectElapsedRealtime();
2792 try {
2793 final ArrayList<PackageWithUser> gonePackages = new ArrayList<>();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002794
Makoto Onuki22fcc682016-05-17 14:52:19 -07002795 synchronized (mLock) {
2796 final ShortcutUser user = getUserShortcutsLocked(ownerUserId);
2797
2798 // Find packages that have been uninstalled.
2799 user.forAllPackageItems(spi -> {
2800 if (spi.getPackageInfo().isShadow()) {
2801 return; // Don't delete shadow information.
2802 }
2803 if (!isPackageInstalled(spi.getPackageName(), spi.getPackageUserId())) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002804 if (DEBUG) {
2805 Slog.d(TAG, "Uninstalled: " + spi.getPackageName()
2806 + " user " + spi.getPackageUserId());
2807 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002808 gonePackages.add(PackageWithUser.of(spi));
2809 }
2810 });
2811 if (gonePackages.size() > 0) {
2812 for (int i = gonePackages.size() - 1; i >= 0; i--) {
2813 final PackageWithUser pu = gonePackages.get(i);
Makoto Onukib08790c2016-06-23 14:05:46 -07002814 cleanUpPackageLocked(pu.packageName, ownerUserId, pu.userId,
2815 /* appStillExists = */ false);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002816 }
Makoto Onukid99c6f02016-03-28 11:02:54 -07002817 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002818
Makoto Onuki248a0ef2016-11-03 15:59:01 -07002819 rescanUpdatedPackagesLocked(ownerUserId, user.getLastAppScanTime());
Makoto Onuki0acbb142016-03-22 17:02:57 -07002820 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002821 } finally {
2822 logDurationStat(Stats.CHECK_PACKAGE_CHANGES, start);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002823 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002824 verifyStates();
Makoto Onukicdc78f72016-03-21 15:47:52 -07002825 }
2826
Makoto Onuki248a0ef2016-11-03 15:59:01 -07002827 private void rescanUpdatedPackagesLocked(@UserIdInt int userId, long lastScanTime) {
Makoto Onuki377b7972016-08-09 14:43:55 -07002828 final ShortcutUser user = getUserShortcutsLocked(userId);
2829
Makoto Onuki33663282016-08-22 16:19:04 -07002830 // Note after each OTA, we'll need to rescan all system apps, as their lastUpdateTime
2831 // is not reliable.
Makoto Onuki377b7972016-08-09 14:43:55 -07002832 final long now = injectCurrentTimeMillis();
Makoto Onuki33663282016-08-22 16:19:04 -07002833 final boolean afterOta =
2834 !injectBuildFingerprint().equals(user.getLastAppScanOsFingerprint());
Makoto Onuki377b7972016-08-09 14:43:55 -07002835
2836 // Then for each installed app, publish manifest shortcuts when needed.
Makoto Onuki33663282016-08-22 16:19:04 -07002837 forUpdatedPackages(userId, lastScanTime, afterOta, ai -> {
Makoto Onuki377b7972016-08-09 14:43:55 -07002838 user.attemptToRestoreIfNeededAndSave(this, ai.packageName, userId);
Makoto Onuki248a0ef2016-11-03 15:59:01 -07002839
2840 user.rescanPackageIfNeeded(ai.packageName, /* forceRescan= */ true);
Makoto Onuki377b7972016-08-09 14:43:55 -07002841 });
2842
2843 // Write the time just before the scan, because there may be apps that have just
2844 // been updated, and we want to catch them in the next time.
2845 user.setLastAppScanTime(now);
Makoto Onuki33663282016-08-22 16:19:04 -07002846 user.setLastAppScanOsFingerprint(injectBuildFingerprint());
Makoto Onuki377b7972016-08-09 14:43:55 -07002847 scheduleSaveUser(userId);
2848 }
2849
Makoto Onuki0acbb142016-03-22 17:02:57 -07002850 private void handlePackageAdded(String packageName, @UserIdInt int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07002851 if (DEBUG) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07002852 Slog.d(TAG, String.format("handlePackageAdded: %s user=%d", packageName, userId));
2853 }
2854 synchronized (mLock) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002855 final ShortcutUser user = getUserShortcutsLocked(userId);
2856 user.attemptToRestoreIfNeededAndSave(this, packageName, userId);
Makoto Onuki64183d52016-08-08 14:11:34 -07002857 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002858 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002859 verifyStates();
Makoto Onuki0acbb142016-03-22 17:02:57 -07002860 }
2861
2862 private void handlePackageUpdateFinished(String packageName, @UserIdInt int userId) {
Makoto Onuki905e8852016-03-28 10:40:58 -07002863 if (DEBUG) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002864 Slog.d(TAG, String.format("handlePackageUpdateFinished: %s user=%d",
2865 packageName, userId));
Makoto Onuki0acbb142016-03-22 17:02:57 -07002866 }
2867 synchronized (mLock) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002868 final ShortcutUser user = getUserShortcutsLocked(userId);
2869 user.attemptToRestoreIfNeededAndSave(this, packageName, userId);
Makoto Onuki39686e82016-04-13 18:03:00 -07002870
Makoto Onuki22fcc682016-05-17 14:52:19 -07002871 if (isPackageInstalled(packageName, userId)) {
Makoto Onuki64183d52016-08-08 14:11:34 -07002872 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onuki39686e82016-04-13 18:03:00 -07002873 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07002874 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002875 verifyStates();
Makoto Onuki0acbb142016-03-22 17:02:57 -07002876 }
2877
Makoto Onuki2e210c42016-03-30 08:30:36 -07002878 private void handlePackageRemoved(String packageName, @UserIdInt int packageUserId) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07002879 if (DEBUG) {
Makoto Onuki2e210c42016-03-30 08:30:36 -07002880 Slog.d(TAG, String.format("handlePackageRemoved: %s user=%d", packageName,
2881 packageUserId));
Makoto Onukicdc78f72016-03-21 15:47:52 -07002882 }
Makoto Onukib08790c2016-06-23 14:05:46 -07002883 cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ false);
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002884
2885 verifyStates();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002886 }
2887
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002888 private void handlePackageDataCleared(String packageName, int packageUserId) {
2889 if (DEBUG) {
2890 Slog.d(TAG, String.format("handlePackageDataCleared: %s user=%d", packageName,
2891 packageUserId));
Makoto Onukicdc78f72016-03-21 15:47:52 -07002892 }
Makoto Onukib08790c2016-06-23 14:05:46 -07002893 cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ true);
2894
2895 verifyStates();
2896 }
2897
2898 private void handlePackageChanged(String packageName, int packageUserId) {
2899 if (DEBUG) {
2900 Slog.d(TAG, String.format("handlePackageChanged: %s user=%d", packageName,
2901 packageUserId));
2902 }
2903
2904 // Activities may be disabled or enabled. Just rescan the package.
2905 synchronized (mLock) {
2906 final ShortcutUser user = getUserShortcutsLocked(packageUserId);
2907
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002908 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07002909 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002910
2911 verifyStates();
Makoto Onukicdc78f72016-03-21 15:47:52 -07002912 }
2913
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002914 // === PackageManager interaction ===
Makoto Onuki0acbb142016-03-22 17:02:57 -07002915
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002916 /**
2917 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
2918 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002919 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002920 final PackageInfo getPackageInfoWithSignatures(String packageName, @UserIdInt int userId) {
2921 return getPackageInfo(packageName, userId, true);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002922 }
2923
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002924 /**
2925 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
2926 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002927 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002928 final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId) {
2929 return getPackageInfo(packageName, userId, false);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002930 }
2931
Makoto Onuki905e8852016-03-28 10:40:58 -07002932 int injectGetPackageUid(@NonNull String packageName, @UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002933 final long token = injectClearCallingIdentity();
Makoto Onuki905e8852016-03-28 10:40:58 -07002934 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002935 return mIPackageManager.getPackageUid(packageName, PACKAGE_MATCH_FLAGS, userId);
Makoto Onuki905e8852016-03-28 10:40:58 -07002936 } catch (RemoteException e) {
2937 // Shouldn't happen.
2938 Slog.wtf(TAG, "RemoteException", e);
2939 return -1;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002940 } finally {
2941 injectRestoreCallingIdentity(token);
Makoto Onuki905e8852016-03-28 10:40:58 -07002942 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07002943 }
2944
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002945 /**
2946 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
2947 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002948 @Nullable
Makoto Onuki0acbb142016-03-22 17:02:57 -07002949 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002950 final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId,
2951 boolean getSignatures) {
2952 return isInstalledOrNull(injectPackageInfoWithUninstalled(
2953 packageName, userId, getSignatures));
2954 }
2955
2956 /**
2957 * Do not use directly; this returns uninstalled packages too.
2958 */
2959 @Nullable
2960 @VisibleForTesting
2961 PackageInfo injectPackageInfoWithUninstalled(String packageName, @UserIdInt int userId,
Makoto Onuki0acbb142016-03-22 17:02:57 -07002962 boolean getSignatures) {
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07002963 final long start = injectElapsedRealtime();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002964 final long token = injectClearCallingIdentity();
Makoto Onuki0acbb142016-03-22 17:02:57 -07002965 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002966 return mIPackageManager.getPackageInfo(
2967 packageName, PACKAGE_MATCH_FLAGS
2968 | (getSignatures ? PackageManager.GET_SIGNATURES : 0), userId);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002969 } catch (RemoteException e) {
2970 // Shouldn't happen.
2971 Slog.wtf(TAG, "RemoteException", e);
2972 return null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002973 } finally {
2974 injectRestoreCallingIdentity(token);
Makoto Onuki2e210c42016-03-30 08:30:36 -07002975
2976 logDurationStat(
2977 (getSignatures ? Stats.GET_PACKAGE_INFO_WITH_SIG : Stats.GET_PACKAGE_INFO),
2978 start);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002979 }
2980 }
2981
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002982 /**
2983 * Returns {@link ApplicationInfo} unless it's uninstalled or disabled.
2984 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002985 @Nullable
Makoto Onuki905e8852016-03-28 10:40:58 -07002986 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002987 final ApplicationInfo getApplicationInfo(String packageName, @UserIdInt int userId) {
2988 return isInstalledOrNull(injectApplicationInfoWithUninstalled(packageName, userId));
2989 }
2990
2991 /**
2992 * Do not use directly; this returns uninstalled packages too.
2993 */
2994 @Nullable
2995 @VisibleForTesting
2996 ApplicationInfo injectApplicationInfoWithUninstalled(
2997 String packageName, @UserIdInt int userId) {
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07002998 final long start = injectElapsedRealtime();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002999 final long token = injectClearCallingIdentity();
Makoto Onuki905e8852016-03-28 10:40:58 -07003000 try {
3001 return mIPackageManager.getApplicationInfo(packageName, PACKAGE_MATCH_FLAGS, userId);
3002 } catch (RemoteException e) {
3003 // Shouldn't happen.
3004 Slog.wtf(TAG, "RemoteException", e);
3005 return null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003006 } finally {
3007 injectRestoreCallingIdentity(token);
Makoto Onuki2e210c42016-03-30 08:30:36 -07003008
3009 logDurationStat(Stats.GET_APPLICATION_INFO, start);
Makoto Onuki905e8852016-03-28 10:40:58 -07003010 }
3011 }
3012
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003013 /**
3014 * Returns {@link ActivityInfo} with its metadata unless it's uninstalled or disabled.
3015 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07003016 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003017 final ActivityInfo getActivityInfoWithMetadata(ComponentName activity, @UserIdInt int userId) {
3018 return isInstalledOrNull(injectGetActivityInfoWithMetadataWithUninstalled(
3019 activity, userId));
3020 }
3021
3022 /**
3023 * Do not use directly; this returns uninstalled packages too.
3024 */
3025 @Nullable
3026 @VisibleForTesting
3027 ActivityInfo injectGetActivityInfoWithMetadataWithUninstalled(
3028 ComponentName activity, @UserIdInt int userId) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07003029 final long start = injectElapsedRealtime();
3030 final long token = injectClearCallingIdentity();
3031 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07003032 return mIPackageManager.getActivityInfo(activity,
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003033 (PACKAGE_MATCH_FLAGS | PackageManager.GET_META_DATA), userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003034 } catch (RemoteException e) {
3035 // Shouldn't happen.
3036 Slog.wtf(TAG, "RemoteException", e);
3037 return null;
3038 } finally {
3039 injectRestoreCallingIdentity(token);
3040
Makoto Onukib08790c2016-06-23 14:05:46 -07003041 logDurationStat(Stats.GET_ACTIVITY_WITH_METADATA, start);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003042 }
3043 }
3044
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003045 /**
3046 * Return all installed and enabled packages.
3047 */
3048 @NonNull
Makoto Onuki22fcc682016-05-17 14:52:19 -07003049 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003050 final List<PackageInfo> getInstalledPackages(@UserIdInt int userId) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07003051 final long start = injectElapsedRealtime();
3052 final long token = injectClearCallingIdentity();
3053 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003054 final List<PackageInfo> all = injectGetPackagesWithUninstalled(userId);
3055
3056 all.removeIf(PACKAGE_NOT_INSTALLED);
3057
3058 return all;
Makoto Onuki22fcc682016-05-17 14:52:19 -07003059 } catch (RemoteException e) {
3060 // Shouldn't happen.
3061 Slog.wtf(TAG, "RemoteException", e);
3062 return null;
3063 } finally {
3064 injectRestoreCallingIdentity(token);
3065
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003066 logDurationStat(Stats.GET_INSTALLED_PACKAGES, start);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003067 }
3068 }
3069
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003070 /**
3071 * Do not use directly; this returns uninstalled packages too.
3072 */
3073 @NonNull
3074 @VisibleForTesting
3075 List<PackageInfo> injectGetPackagesWithUninstalled(@UserIdInt int userId)
3076 throws RemoteException {
3077 final ParceledListSlice<PackageInfo> parceledList =
3078 mIPackageManager.getInstalledPackages(PACKAGE_MATCH_FLAGS, userId);
3079 if (parceledList == null) {
3080 return Collections.emptyList();
3081 }
3082 return parceledList.getList();
3083 }
3084
Makoto Onuki33663282016-08-22 16:19:04 -07003085 private void forUpdatedPackages(@UserIdInt int userId, long lastScanTime, boolean afterOta,
Makoto Onuki22fcc682016-05-17 14:52:19 -07003086 Consumer<ApplicationInfo> callback) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003087 if (DEBUG) {
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003088 Slog.d(TAG, "forUpdatedPackages for user " + userId + ", lastScanTime=" + lastScanTime
3089 + " afterOta=" + afterOta);
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003090 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003091 final List<PackageInfo> list = getInstalledPackages(userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003092 for (int i = list.size() - 1; i >= 0; i--) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003093 final PackageInfo pi = list.get(i);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003094
Makoto Onuki64183d52016-08-08 14:11:34 -07003095 // If the package has been updated since the last scan time, then scan it.
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003096 // Also if it's right after an OTA, always re-scan all apps anyway, since the
3097 // shortcut parser might have changed.
3098 if (afterOta || (pi.lastUpdateTime >= lastScanTime)) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003099 if (DEBUG) {
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003100 Slog.d(TAG, "Found updated package " + pi.packageName
3101 + " updateTime=" + pi.lastUpdateTime);
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003102 }
3103 callback.accept(pi.applicationInfo);
Makoto Onuki22fcc682016-05-17 14:52:19 -07003104 }
3105 }
3106 }
3107
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003108 private boolean isApplicationFlagSet(@NonNull String packageName, int userId, int flags) {
3109 final ApplicationInfo ai = injectApplicationInfoWithUninstalled(packageName, userId);
Makoto Onuki905e8852016-03-28 10:40:58 -07003110 return (ai != null) && ((ai.flags & flags) == flags);
3111 }
3112
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003113 private static boolean isInstalled(@Nullable ApplicationInfo ai) {
3114 return (ai != null) && (ai.flags & ApplicationInfo.FLAG_INSTALLED) != 0;
3115 }
3116
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08003117 private static boolean isEphemeralApp(@Nullable ApplicationInfo ai) {
Svetoslav Ganov096d3042017-01-30 16:34:13 -08003118 return (ai != null) && ai.isInstantApp();
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08003119 }
3120
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003121 private static boolean isInstalled(@Nullable PackageInfo pi) {
3122 return (pi != null) && isInstalled(pi.applicationInfo);
3123 }
3124
3125 private static boolean isInstalled(@Nullable ActivityInfo ai) {
3126 return (ai != null) && isInstalled(ai.applicationInfo);
3127 }
3128
3129 private static ApplicationInfo isInstalledOrNull(ApplicationInfo ai) {
3130 return isInstalled(ai) ? ai : null;
3131 }
3132
3133 private static PackageInfo isInstalledOrNull(PackageInfo pi) {
3134 return isInstalled(pi) ? pi : null;
3135 }
3136
3137 private static ActivityInfo isInstalledOrNull(ActivityInfo ai) {
3138 return isInstalled(ai) ? ai : null;
3139 }
3140
Makoto Onuki2e210c42016-03-30 08:30:36 -07003141 boolean isPackageInstalled(String packageName, int userId) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003142 return getApplicationInfo(packageName, userId) != null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003143 }
3144
Makoto Onuki66e4a2b2017-01-23 11:37:45 -08003145 boolean isEphemeralApp(String packageName, int userId) {
3146 return isEphemeralApp(getApplicationInfo(packageName, userId));
3147 }
3148
Makoto Onuki22fcc682016-05-17 14:52:19 -07003149 @Nullable
3150 XmlResourceParser injectXmlMetaData(ActivityInfo activityInfo, String key) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07003151 return activityInfo.loadXmlMetaData(mContext.getPackageManager(), key);
Makoto Onuki39686e82016-04-13 18:03:00 -07003152 }
3153
Makoto Onuki157b1622016-06-02 16:13:10 -07003154 @Nullable
3155 Resources injectGetResourcesForApplicationAsUser(String packageName, int userId) {
3156 final long start = injectElapsedRealtime();
3157 final long token = injectClearCallingIdentity();
3158 try {
3159 return mContext.getPackageManager().getResourcesForApplicationAsUser(
3160 packageName, userId);
3161 } catch (NameNotFoundException e) {
3162 Slog.e(TAG, "Resources for package " + packageName + " not found");
3163 return null;
3164 } finally {
3165 injectRestoreCallingIdentity(token);
3166
3167 logDurationStat(Stats.GET_APPLICATION_RESOURCES, start);
3168 }
3169 }
3170
Makoto Onukib08790c2016-06-23 14:05:46 -07003171 private Intent getMainActivityIntent() {
3172 final Intent intent = new Intent(Intent.ACTION_MAIN);
3173 intent.addCategory(LAUNCHER_INTENT_CATEGORY);
3174 return intent;
3175 }
3176
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003177 /**
3178 * Same as queryIntentActivitiesAsUser, except it makes sure the package is installed,
3179 * and only returns exported activities.
3180 */
3181 @NonNull
3182 @VisibleForTesting
3183 List<ResolveInfo> queryActivities(@NonNull Intent baseIntent,
3184 @NonNull String packageName, @Nullable ComponentName activity, int userId) {
3185
3186 baseIntent.setPackage(Preconditions.checkNotNull(packageName));
3187 if (activity != null) {
3188 baseIntent.setComponent(activity);
3189 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08003190 return queryActivities(baseIntent, userId, /* exportedOnly =*/ true);
3191 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003192
Makoto Onuki2d895c32016-12-02 15:48:40 -08003193 @NonNull
3194 List<ResolveInfo> queryActivities(@NonNull Intent intent, int userId,
3195 boolean exportedOnly) {
3196 final List<ResolveInfo> resolved;
3197 final long token = injectClearCallingIdentity();
3198 try {
3199 resolved =
3200 mContext.getPackageManager().queryIntentActivitiesAsUser(
3201 intent, PACKAGE_MATCH_FLAGS, userId);
3202 } finally {
3203 injectRestoreCallingIdentity(token);
3204 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003205 if (resolved == null || resolved.size() == 0) {
3206 return EMPTY_RESOLVE_INFO;
3207 }
3208 // Make sure the package is installed.
3209 if (!isInstalled(resolved.get(0).activityInfo)) {
3210 return EMPTY_RESOLVE_INFO;
3211 }
Makoto Onuki2d895c32016-12-02 15:48:40 -08003212 if (exportedOnly) {
3213 resolved.removeIf(ACTIVITY_NOT_EXPORTED);
3214 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003215 return resolved;
3216 }
3217
3218 /**
3219 * Return the main activity that is enabled and exported. If multiple activities are found,
3220 * return the first one.
3221 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003222 @Nullable
3223 ComponentName injectGetDefaultMainActivity(@NonNull String packageName, int userId) {
3224 final long start = injectElapsedRealtime();
Makoto Onukib08790c2016-06-23 14:05:46 -07003225 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07003226 final List<ResolveInfo> resolved =
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003227 queryActivities(getMainActivityIntent(), packageName, null, userId);
3228 return resolved.size() == 0 ? null : resolved.get(0).activityInfo.getComponentName();
Makoto Onukib08790c2016-06-23 14:05:46 -07003229 } finally {
Makoto Onukib08790c2016-06-23 14:05:46 -07003230 logDurationStat(Stats.GET_LAUNCHER_ACTIVITY, start);
3231 }
3232 }
3233
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003234 /**
3235 * Return whether an activity is enabled, exported and main.
3236 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003237 boolean injectIsMainActivity(@NonNull ComponentName activity, int userId) {
3238 final long start = injectElapsedRealtime();
Makoto Onukib08790c2016-06-23 14:05:46 -07003239 try {
Makoto Onuki2d895c32016-12-02 15:48:40 -08003240 if (DUMMY_MAIN_ACTIVITY.equals(activity.getClassName())) {
3241 return true;
3242 }
3243 final List<ResolveInfo> resolved = queryActivities(
3244 getMainActivityIntent(), activity.getPackageName(), activity, userId);
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003245 return resolved.size() > 0;
Makoto Onukib08790c2016-06-23 14:05:46 -07003246 } finally {
Makoto Onukib08790c2016-06-23 14:05:46 -07003247 logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start);
3248 }
3249 }
3250
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003251 /**
Makoto Onuki2d895c32016-12-02 15:48:40 -08003252 * Create a dummy "main activity" component name which is used to create a dynamic shortcut
3253 * with no main activity temporarily.
3254 */
3255 @NonNull
3256 ComponentName getDummyMainActivity(@NonNull String packageName) {
3257 return new ComponentName(packageName, DUMMY_MAIN_ACTIVITY);
3258 }
3259
Makoto Onuki255461f2017-01-10 11:47:25 -08003260 boolean isDummyMainActivity(@Nullable ComponentName name) {
3261 return name != null && DUMMY_MAIN_ACTIVITY.equals(name.getClassName());
3262 }
3263
Makoto Onuki2d895c32016-12-02 15:48:40 -08003264 /**
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003265 * Return all the enabled, exported and main activities from a package.
3266 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003267 @NonNull
3268 List<ResolveInfo> injectGetMainActivities(@NonNull String packageName, int userId) {
3269 final long start = injectElapsedRealtime();
Makoto Onukib08790c2016-06-23 14:05:46 -07003270 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003271 return queryActivities(getMainActivityIntent(), packageName, null, userId);
Makoto Onukib08790c2016-06-23 14:05:46 -07003272 } finally {
Makoto Onukib08790c2016-06-23 14:05:46 -07003273 logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start);
3274 }
3275 }
3276
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003277 /**
3278 * Return whether an activity is enabled and exported.
3279 */
3280 @VisibleForTesting
3281 boolean injectIsActivityEnabledAndExported(
3282 @NonNull ComponentName activity, @UserIdInt int userId) {
3283 final long start = injectElapsedRealtime();
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003284 try {
3285 return queryActivities(new Intent(), activity.getPackageName(), activity, userId)
3286 .size() > 0;
3287 } finally {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003288 logDurationStat(Stats.IS_ACTIVITY_ENABLED, start);
3289 }
3290 }
3291
Makoto Onuki2d895c32016-12-02 15:48:40 -08003292 /**
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003293 * Get the {@link LauncherApps#ACTION_CONFIRM_PIN_SHORTCUT} or
3294 * {@link LauncherApps#ACTION_CONFIRM_PIN_APPWIDGET} activity in a given package depending on
3295 * the requestType.
Makoto Onuki2d895c32016-12-02 15:48:40 -08003296 */
3297 @Nullable
3298 ComponentName injectGetPinConfirmationActivity(@NonNull String launcherPackageName,
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003299 int launcherUserId, int requestType) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08003300 Preconditions.checkNotNull(launcherPackageName);
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003301 String action = requestType == LauncherApps.PinItemRequest.REQUEST_TYPE_SHORTCUT ?
3302 LauncherApps.ACTION_CONFIRM_PIN_SHORTCUT :
3303 LauncherApps.ACTION_CONFIRM_PIN_APPWIDGET;
Makoto Onuki2d895c32016-12-02 15:48:40 -08003304
Sunny Goyal7f7372a2017-01-24 11:53:54 -08003305 final Intent confirmIntent = new Intent(action).setPackage(launcherPackageName);
Makoto Onuki2d895c32016-12-02 15:48:40 -08003306 final List<ResolveInfo> candidates = queryActivities(
3307 confirmIntent, launcherUserId, /* exportedOnly =*/ false);
3308 for (ResolveInfo ri : candidates) {
3309 return ri.activityInfo.getComponentName();
3310 }
3311 return null;
3312 }
3313
Makoto Onukib08790c2016-06-23 14:05:46 -07003314 boolean injectIsSafeModeEnabled() {
3315 final long token = injectClearCallingIdentity();
3316 try {
3317 return IWindowManager.Stub
3318 .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE))
3319 .isSafeModeEnabled();
3320 } catch (RemoteException e) {
3321 return false; // Shouldn't happen though.
3322 } finally {
3323 injectRestoreCallingIdentity(token);
3324 }
3325 }
3326
Makoto Onuki2d895c32016-12-02 15:48:40 -08003327 /**
3328 * If {@code userId} is of a managed profile, return the parent user ID. Otherwise return
3329 * itself.
3330 */
3331 int getParentOrSelfUserId(int userId) {
3332 final long token = injectClearCallingIdentity();
3333 try {
3334 final UserInfo parent = mUserManager.getProfileParent(userId);
3335 return (parent != null) ? parent.id : userId;
3336 } finally {
3337 injectRestoreCallingIdentity(token);
3338 }
3339 }
3340
Sunny Goyal87a563e2017-01-01 19:42:45 -08003341 void injectSendIntentSender(IntentSender intentSender, Intent extras) {
Makoto Onuki2d895c32016-12-02 15:48:40 -08003342 if (intentSender == null) {
3343 return;
3344 }
3345 try {
Sunny Goyal87a563e2017-01-01 19:42:45 -08003346 intentSender.sendIntent(mContext, /* code= */ 0, extras,
Makoto Onuki2d895c32016-12-02 15:48:40 -08003347 /* onFinished=*/ null, /* handler= */ null);
3348 } catch (SendIntentException e) {
3349 Slog.w(TAG, "sendIntent failed().", e);
3350 }
3351 }
3352
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003353 // === Backup & restore ===
3354
Makoto Onuki0acbb142016-03-22 17:02:57 -07003355 boolean shouldBackupApp(String packageName, int userId) {
Makoto Onuki905e8852016-03-28 10:40:58 -07003356 return isApplicationFlagSet(packageName, userId, ApplicationInfo.FLAG_ALLOW_BACKUP);
Makoto Onuki0acbb142016-03-22 17:02:57 -07003357 }
3358
Makoto Onuki2e210c42016-03-30 08:30:36 -07003359 boolean shouldBackupApp(PackageInfo pi) {
3360 return (pi.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0;
3361 }
3362
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003363 @Override
Makoto Onuki2e210c42016-03-30 08:30:36 -07003364 public byte[] getBackupPayload(@UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003365 enforceSystem();
3366 if (DEBUG) {
3367 Slog.d(TAG, "Backing up user " + userId);
3368 }
3369 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003370 if (!isUserUnlockedL(userId)) {
3371 wtf("Can't backup: user " + userId + " is locked or not running");
3372 return null;
3373 }
3374
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003375 final ShortcutUser user = getUserShortcutsLocked(userId);
3376 if (user == null) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003377 wtf("Can't backup: user not found: id=" + userId);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003378 return null;
3379 }
3380
Makoto Onukic8c33292016-09-12 16:36:59 -07003381 // Update the signatures for all packages.
3382 user.forAllPackageItems(spi -> spi.refreshPackageSignatureAndSave());
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003383
Makoto Onukic8c33292016-09-12 16:36:59 -07003384 // Set the version code for the launchers.
3385 // We shouldn't do this for publisher packages, because we don't want to update the
3386 // version code without rescanning the manifest.
3387 user.forAllLaunchers(launcher -> launcher.ensureVersionInfo());
3388
3389 // Save to the filesystem.
3390 scheduleSaveUser(userId);
3391 saveDirtyInfo();
3392
3393 // Then create the backup payload.
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003394 final ByteArrayOutputStream os = new ByteArrayOutputStream(32 * 1024);
3395 try {
3396 saveUserInternalLocked(userId, os, /* forBackup */ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07003397 } catch (XmlPullParserException | IOException e) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003398 // Shouldn't happen.
3399 Slog.w(TAG, "Backup failed.", e);
3400 return null;
3401 }
3402 return os.toByteArray();
3403 }
3404 }
3405
3406 @Override
Makoto Onuki2e210c42016-03-30 08:30:36 -07003407 public void applyRestore(byte[] payload, @UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003408 enforceSystem();
3409 if (DEBUG) {
3410 Slog.d(TAG, "Restoring user " + userId);
3411 }
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003412 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003413 if (!isUserUnlockedL(userId)) {
3414 wtf("Can't restore: user " + userId + " is locked or not running");
3415 return;
3416 }
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003417 // Actually do restore.
3418 final ShortcutUser restored;
Makoto Onuki02f338e2016-07-29 09:40:40 -07003419 final ByteArrayInputStream is = new ByteArrayInputStream(payload);
3420 try {
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003421 restored = loadUserInternal(userId, is, /* fromBackup */ true);
3422 } catch (XmlPullParserException | IOException | InvalidFileFormatException e) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003423 Slog.w(TAG, "Restoration failed.", e);
3424 return;
3425 }
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07003426 getUserShortcutsLocked(userId).mergeRestoredFile(restored);
Makoto Onuki2e210c42016-03-30 08:30:36 -07003427
Makoto Onuki377b7972016-08-09 14:43:55 -07003428 // Rescan all packages to re-publish manifest shortcuts and do other checks.
3429 rescanUpdatedPackagesLocked(userId,
Makoto Onuki248a0ef2016-11-03 15:59:01 -07003430 0 // lastScanTime = 0; rescan all packages.
3431 );
Makoto Onuki2e210c42016-03-30 08:30:36 -07003432
3433 saveUserLocked(userId);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003434 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07003435 }
3436
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003437 // === Dump ===
3438
3439 @Override
3440 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Makoto Onuki76269922016-07-15 14:58:54 -07003441 enforceCallingOrSelfPermission(android.Manifest.permission.DUMP,
3442 "can't dump by this caller");
3443 boolean checkin = false;
3444 boolean clear = false;
3445 if (args != null) {
3446 for (String arg : args) {
3447 if ("-c".equals(arg)) {
3448 checkin = true;
3449 } else if ("--checkin".equals(arg)) {
3450 checkin = true;
3451 clear = true;
3452 }
3453 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003454 }
Makoto Onuki76269922016-07-15 14:58:54 -07003455
3456 if (checkin) {
3457 dumpCheckin(pw, clear);
3458 } else {
3459 dumpInner(pw);
3460 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003461 }
3462
Makoto Onuki76269922016-07-15 14:58:54 -07003463 private void dumpInner(PrintWriter pw) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003464 synchronized (mLock) {
3465 final long now = injectCurrentTimeMillis();
3466 pw.print("Now: [");
3467 pw.print(now);
3468 pw.print("] ");
3469 pw.print(formatTime(now));
Makoto Onuki55046222016-03-08 10:49:47 -08003470
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003471 pw.print(" Raw last reset: [");
3472 pw.print(mRawLastResetTime);
3473 pw.print("] ");
3474 pw.print(formatTime(mRawLastResetTime));
3475
3476 final long last = getLastResetTimeLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003477 pw.print(" Last reset: [");
3478 pw.print(last);
3479 pw.print("] ");
3480 pw.print(formatTime(last));
3481
Makoto Onuki55046222016-03-08 10:49:47 -08003482 final long next = getNextResetTimeLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003483 pw.print(" Next reset: [");
3484 pw.print(next);
3485 pw.print("] ");
3486 pw.print(formatTime(next));
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003487
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003488 pw.print(" Config:");
3489 pw.print(" Max icon dim: ");
3490 pw.println(mMaxIconDimension);
3491 pw.print(" Icon format: ");
3492 pw.println(mIconPersistFormat);
3493 pw.print(" Icon quality: ");
Makoto Onuki2e210c42016-03-30 08:30:36 -07003494 pw.println(mIconPersistQuality);
Makoto Onuki0033b2a2016-04-14 17:19:16 -07003495 pw.print(" saveDelayMillis: ");
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003496 pw.println(mSaveDelayMillis);
Makoto Onuki0033b2a2016-04-14 17:19:16 -07003497 pw.print(" resetInterval: ");
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003498 pw.println(mResetInterval);
Makoto Onuki0033b2a2016-04-14 17:19:16 -07003499 pw.print(" maxUpdatesPerInterval: ");
Makoto Onukib6d35232016-04-04 15:57:17 -07003500 pw.println(mMaxUpdatesPerInterval);
Makoto Onukib08790c2016-06-23 14:05:46 -07003501 pw.print(" maxShortcutsPerActivity: ");
Makoto Onukib5a012f2016-06-21 11:13:53 -07003502 pw.println(mMaxShortcuts);
Makoto Onuki55046222016-03-08 10:49:47 -08003503 pw.println();
3504
Makoto Onuki2e210c42016-03-30 08:30:36 -07003505 pw.println(" Stats:");
3506 synchronized (mStatLock) {
Makoto Onuki085a05c2016-08-19 11:39:29 -07003507 for (int i = 0; i < Stats.COUNT; i++) {
3508 dumpStatLS(pw, " ", i);
3509 }
Makoto Onuki2e210c42016-03-30 08:30:36 -07003510 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003511
Makoto Onukia2241832016-07-06 13:28:37 -07003512 pw.println();
3513 pw.print(" #Failures: ");
3514 pw.println(mWtfCount);
3515
3516 if (mLastWtfStacktrace != null) {
3517 pw.print(" Last failure stack trace: ");
3518 pw.println(Log.getStackTraceString(mLastWtfStacktrace));
3519 }
3520
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08003521 for (int i = 0; i < mUsers.size(); i++) {
3522 pw.println();
Makoto Onukic51b2872016-05-04 15:24:50 -07003523 mUsers.valueAt(i).dump(pw, " ");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003524 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003525
3526 pw.println();
3527 pw.println(" UID state:");
3528
3529 for (int i = 0; i < mUidState.size(); i++) {
3530 final int uid = mUidState.keyAt(i);
3531 final int state = mUidState.valueAt(i);
3532 pw.print(" UID=");
3533 pw.print(uid);
3534 pw.print(" state=");
3535 pw.print(state);
3536 if (isProcessStateForeground(state)) {
3537 pw.print(" [FG]");
3538 }
3539 pw.print(" last FG=");
3540 pw.print(mUidLastForegroundElapsedTime.get(uid));
3541 pw.println();
3542 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003543 }
3544 }
3545
Makoto Onuki41066a62016-03-09 16:18:44 -08003546 static String formatTime(long time) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003547 Time tobj = new Time();
3548 tobj.set(time);
3549 return tobj.format("%Y-%m-%d %H:%M:%S");
3550 }
3551
Makoto Onuki085a05c2016-08-19 11:39:29 -07003552 private void dumpStatLS(PrintWriter pw, String prefix, int statId) {
Makoto Onuki2e210c42016-03-30 08:30:36 -07003553 pw.print(prefix);
3554 final int count = mCountStats[statId];
3555 final long dur = mDurationStats[statId];
3556 pw.println(String.format("%s: count=%d, total=%dms, avg=%.1fms",
Makoto Onuki085a05c2016-08-19 11:39:29 -07003557 STAT_LABELS[statId], count, dur,
Makoto Onuki2e210c42016-03-30 08:30:36 -07003558 (count == 0 ? 0 : ((double) dur) / count)));
3559 }
3560
Makoto Onuki76269922016-07-15 14:58:54 -07003561 /**
3562 * Dumpsys for checkin.
3563 *
3564 * @param clear if true, clear the history information. Some other system services have this
3565 * behavior but shortcut service doesn't for now.
3566 */
3567 private void dumpCheckin(PrintWriter pw, boolean clear) {
3568 synchronized (mLock) {
3569 try {
3570 final JSONArray users = new JSONArray();
3571
3572 for (int i = 0; i < mUsers.size(); i++) {
3573 users.put(mUsers.valueAt(i).dumpCheckin(clear));
3574 }
3575
3576 final JSONObject result = new JSONObject();
3577
3578 result.put(KEY_SHORTCUT, users);
3579 result.put(KEY_LOW_RAM, injectIsLowRamDevice());
3580 result.put(KEY_ICON_SIZE, mMaxIconDimension);
3581
3582 pw.println(result.toString(1));
3583 } catch (JSONException e) {
3584 Slog.e(TAG, "Unable to write in json", e);
3585 }
3586 }
3587 }
3588
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003589 // === Shell support ===
3590
3591 @Override
3592 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003593 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003594
3595 enforceShell();
3596
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07003597 final long token = injectClearCallingIdentity();
3598 try {
Dianne Hackborn354736e2016-08-22 17:00:05 -07003599 final int status = (new MyShellCommand()).exec(this, in, out, err, args, callback,
3600 resultReceiver);
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07003601 resultReceiver.send(status, null);
3602 } finally {
3603 injectRestoreCallingIdentity(token);
3604 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003605 }
3606
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003607 static class CommandException extends Exception {
3608 public CommandException(String message) {
3609 super(message);
3610 }
3611 }
3612
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003613 /**
3614 * Handle "adb shell cmd".
3615 */
3616 private class MyShellCommand extends ShellCommand {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003617
3618 private int mUserId = UserHandle.USER_SYSTEM;
3619
Makoto Onuki02f338e2016-07-29 09:40:40 -07003620 private void parseOptionsLocked(boolean takeUser)
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003621 throws CommandException {
3622 String opt;
3623 while ((opt = getNextOption()) != null) {
3624 switch (opt) {
3625 case "--user":
3626 if (takeUser) {
3627 mUserId = UserHandle.parseUserArg(getNextArgRequired());
Makoto Onuki02f338e2016-07-29 09:40:40 -07003628 if (!isUserUnlockedL(mUserId)) {
Makoto Onukif34c3082016-07-13 10:25:25 -07003629 throw new CommandException(
3630 "User " + mUserId + " is not running or locked");
3631 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003632 break;
3633 }
3634 // fallthrough
3635 default:
3636 throw new CommandException("Unknown option: " + opt);
3637 }
3638 }
3639 }
3640
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003641 @Override
3642 public int onCommand(String cmd) {
3643 if (cmd == null) {
3644 return handleDefaultCommands(cmd);
3645 }
3646 final PrintWriter pw = getOutPrintWriter();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003647 try {
3648 switch (cmd) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003649 case "reset-throttling":
3650 handleResetThrottling();
3651 break;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003652 case "reset-all-throttling":
3653 handleResetAllThrottling();
3654 break;
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003655 case "override-config":
3656 handleOverrideConfig();
3657 break;
3658 case "reset-config":
3659 handleResetConfig();
3660 break;
3661 case "clear-default-launcher":
3662 handleClearDefaultLauncher();
3663 break;
3664 case "get-default-launcher":
3665 handleGetDefaultLauncher();
3666 break;
Makoto Onukiac214972016-04-04 10:19:45 -07003667 case "unload-user":
3668 handleUnloadUser();
3669 break;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003670 case "clear-shortcuts":
3671 handleClearShortcuts();
3672 break;
Makoto Onukib08790c2016-06-23 14:05:46 -07003673 case "verify-states": // hidden command to verify various internal states.
3674 handleVerifyStates();
3675 break;
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003676 default:
3677 return handleDefaultCommands(cmd);
3678 }
3679 } catch (CommandException e) {
3680 pw.println("Error: " + e.getMessage());
3681 return 1;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003682 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003683 pw.println("Success");
3684 return 0;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003685 }
3686
3687 @Override
3688 public void onHelp() {
3689 final PrintWriter pw = getOutPrintWriter();
3690 pw.println("Usage: cmd shortcut COMMAND [options ...]");
3691 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003692 pw.println("cmd shortcut reset-throttling [--user USER_ID]");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003693 pw.println(" Reset throttling for all packages and users");
3694 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003695 pw.println("cmd shortcut reset-all-throttling");
3696 pw.println(" Reset the throttling state for all users");
3697 pw.println();
Makoto Onuki4362a662016-03-08 18:59:09 -08003698 pw.println("cmd shortcut override-config CONFIG");
3699 pw.println(" Override the configuration for testing (will last until reboot)");
3700 pw.println();
3701 pw.println("cmd shortcut reset-config");
3702 pw.println(" Reset the configuration set with \"update-config\"");
3703 pw.println();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003704 pw.println("cmd shortcut clear-default-launcher [--user USER_ID]");
3705 pw.println(" Clear the cached default launcher");
3706 pw.println();
3707 pw.println("cmd shortcut get-default-launcher [--user USER_ID]");
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07003708 pw.println(" Show the default launcher");
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003709 pw.println();
Makoto Onukiac214972016-04-04 10:19:45 -07003710 pw.println("cmd shortcut unload-user [--user USER_ID]");
3711 pw.println(" Unload a user from the memory");
3712 pw.println(" (This should not affect any observable behavior)");
3713 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003714 pw.println("cmd shortcut clear-shortcuts [--user USER_ID] PACKAGE");
3715 pw.println(" Remove all shortcuts from a package, including pinned shortcuts");
3716 pw.println();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003717 }
3718
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003719 private void handleResetThrottling() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003720 synchronized (mLock) {
3721 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki4554d0e2016-03-14 15:51:41 -07003722
Makoto Onuki02f338e2016-07-29 09:40:40 -07003723 Slog.i(TAG, "cmd: handleResetThrottling: user=" + mUserId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003724
Makoto Onuki02f338e2016-07-29 09:40:40 -07003725 resetThrottlingInner(mUserId);
3726 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003727 }
3728
3729 private void handleResetAllThrottling() {
3730 Slog.i(TAG, "cmd: handleResetAllThrottling");
3731
3732 resetAllThrottlingInner();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003733 }
3734
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003735 private void handleOverrideConfig() throws CommandException {
Makoto Onuki4362a662016-03-08 18:59:09 -08003736 final String config = getNextArgRequired();
3737
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003738 Slog.i(TAG, "cmd: handleOverrideConfig: " + config);
3739
Makoto Onuki4362a662016-03-08 18:59:09 -08003740 synchronized (mLock) {
3741 if (!updateConfigurationLocked(config)) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003742 throw new CommandException("override-config failed. See logcat for details.");
Makoto Onuki4362a662016-03-08 18:59:09 -08003743 }
3744 }
Makoto Onuki4362a662016-03-08 18:59:09 -08003745 }
3746
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003747 private void handleResetConfig() {
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003748 Slog.i(TAG, "cmd: handleResetConfig");
3749
Makoto Onuki4362a662016-03-08 18:59:09 -08003750 synchronized (mLock) {
3751 loadConfigurationLocked();
3752 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003753 }
3754
3755 private void clearLauncher() {
3756 synchronized (mLock) {
Makoto Onuki10305202016-07-14 18:14:08 -07003757 getUserShortcutsLocked(mUserId).forceClearLauncher();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003758 }
3759 }
3760
3761 private void showLauncher() {
3762 synchronized (mLock) {
3763 // This ensures to set the cached launcher. Package name doesn't matter.
3764 hasShortcutHostPermissionInner("-", mUserId);
3765
3766 getOutPrintWriter().println("Launcher: "
Makoto Onuki10305202016-07-14 18:14:08 -07003767 + getUserShortcutsLocked(mUserId).getLastKnownLauncher());
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003768 }
3769 }
3770
3771 private void handleClearDefaultLauncher() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003772 synchronized (mLock) {
3773 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003774
Makoto Onuki02f338e2016-07-29 09:40:40 -07003775 clearLauncher();
3776 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003777 }
3778
3779 private void handleGetDefaultLauncher() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003780 synchronized (mLock) {
3781 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003782
Makoto Onuki02f338e2016-07-29 09:40:40 -07003783 clearLauncher();
3784 showLauncher();
3785 }
Makoto Onuki4362a662016-03-08 18:59:09 -08003786 }
Makoto Onukiac214972016-04-04 10:19:45 -07003787
3788 private void handleUnloadUser() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003789 synchronized (mLock) {
3790 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onukiac214972016-04-04 10:19:45 -07003791
Makoto Onuki02f338e2016-07-29 09:40:40 -07003792 Slog.i(TAG, "cmd: handleUnloadUser: user=" + mUserId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003793
Makoto Onuki02f338e2016-07-29 09:40:40 -07003794 ShortcutService.this.handleCleanupUser(mUserId);
3795 }
Makoto Onukiac214972016-04-04 10:19:45 -07003796 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003797
3798 private void handleClearShortcuts() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003799 synchronized (mLock) {
3800 parseOptionsLocked(/* takeUser =*/ true);
3801 final String packageName = getNextArgRequired();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003802
Makoto Onuki02f338e2016-07-29 09:40:40 -07003803 Slog.i(TAG, "cmd: handleClearShortcuts: user" + mUserId + ", " + packageName);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003804
Makoto Onuki02f338e2016-07-29 09:40:40 -07003805 ShortcutService.this.cleanUpPackageForAllLoadedUsers(packageName, mUserId,
3806 /* appStillExists = */ true);
3807 }
Makoto Onukib08790c2016-06-23 14:05:46 -07003808 }
3809
3810 private void handleVerifyStates() throws CommandException {
3811 try {
3812 verifyStatesForce(); // This will throw when there's an issue.
3813 } catch (Throwable th) {
3814 throw new CommandException(th.getMessage() + "\n" + Log.getStackTraceString(th));
3815 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003816 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003817 }
3818
3819 // === Unit test support ===
3820
3821 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07003822 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003823 long injectCurrentTimeMillis() {
3824 return System.currentTimeMillis();
3825 }
3826
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003827 @VisibleForTesting
3828 long injectElapsedRealtime() {
3829 return SystemClock.elapsedRealtime();
3830 }
3831
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003832 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07003833 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003834 int injectBinderCallingUid() {
3835 return getCallingUid();
3836 }
3837
Makoto Onuki31459242016-03-22 11:12:18 -07003838 private int getCallingUserId() {
Makoto Onuki4554d0e2016-03-14 15:51:41 -07003839 return UserHandle.getUserId(injectBinderCallingUid());
3840 }
3841
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07003842 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07003843 @VisibleForTesting
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07003844 long injectClearCallingIdentity() {
3845 return Binder.clearCallingIdentity();
3846 }
3847
3848 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07003849 @VisibleForTesting
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07003850 void injectRestoreCallingIdentity(long token) {
3851 Binder.restoreCallingIdentity(token);
3852 }
3853
Makoto Onuki33663282016-08-22 16:19:04 -07003854 // Injection point.
3855 @VisibleForTesting
3856 String injectBuildFingerprint() {
3857 return Build.FINGERPRINT;
3858 }
3859
Makoto Onukide667372016-03-15 14:29:20 -07003860 final void wtf(String message) {
Makoto Onukib08790c2016-06-23 14:05:46 -07003861 wtf(message, /* exception= */ null);
Makoto Onukide667372016-03-15 14:29:20 -07003862 }
3863
Makoto Onuki2e210c42016-03-30 08:30:36 -07003864 // Injection point.
Makoto Onukia2241832016-07-06 13:28:37 -07003865 void wtf(String message, Throwable e) {
3866 if (e == null) {
3867 e = new RuntimeException("Stacktrace");
3868 }
3869 synchronized (mLock) {
3870 mWtfCount++;
3871 mLastWtfStacktrace = new Exception("Last failure was logged here:");
3872 }
Makoto Onukide667372016-03-15 14:29:20 -07003873 Slog.wtf(TAG, message, e);
3874 }
3875
Makoto Onuki31459242016-03-22 11:12:18 -07003876 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003877 File injectSystemDataPath() {
3878 return Environment.getDataSystemDirectory();
3879 }
3880
Makoto Onuki31459242016-03-22 11:12:18 -07003881 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003882 File injectUserDataPath(@UserIdInt int userId) {
Makoto Onuki55046222016-03-08 10:49:47 -08003883 return new File(Environment.getDataSystemCeDirectory(userId), DIRECTORY_PER_USER);
3884 }
3885
Makoto Onuki4362a662016-03-08 18:59:09 -08003886 @VisibleForTesting
Makoto Onuki55046222016-03-08 10:49:47 -08003887 boolean injectIsLowRamDevice() {
3888 return ActivityManager.isLowRamDeviceStatic();
3889 }
3890
Makoto Onuki31459242016-03-22 11:12:18 -07003891 @VisibleForTesting
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003892 void injectRegisterUidObserver(IUidObserver observer, int which) {
3893 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003894 ActivityManager.getService().registerUidObserver(observer, which,
Dianne Hackborn5614bf52016-11-07 17:26:41 -08003895 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003896 } catch (RemoteException shouldntHappen) {
3897 }
3898 }
3899
Makoto Onuki55046222016-03-08 10:49:47 -08003900 File getUserBitmapFilePath(@UserIdInt int userId) {
3901 return new File(injectUserDataPath(userId), DIRECTORY_BITMAPS);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003902 }
3903
3904 @VisibleForTesting
Makoto Onuki31459242016-03-22 11:12:18 -07003905 SparseArray<ShortcutUser> getShortcutsForTest() {
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08003906 return mUsers;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003907 }
3908
3909 @VisibleForTesting
Makoto Onukib5a012f2016-06-21 11:13:53 -07003910 int getMaxShortcutsForTest() {
3911 return mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003912 }
3913
3914 @VisibleForTesting
Makoto Onukib6d35232016-04-04 15:57:17 -07003915 int getMaxUpdatesPerIntervalForTest() {
3916 return mMaxUpdatesPerInterval;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003917 }
3918
3919 @VisibleForTesting
Makoto Onuki4362a662016-03-08 18:59:09 -08003920 long getResetIntervalForTest() {
3921 return mResetInterval;
Makoto Onuki55046222016-03-08 10:49:47 -08003922 }
3923
3924 @VisibleForTesting
Makoto Onuki4362a662016-03-08 18:59:09 -08003925 int getMaxIconDimensionForTest() {
3926 return mMaxIconDimension;
3927 }
3928
3929 @VisibleForTesting
3930 CompressFormat getIconPersistFormatForTest() {
3931 return mIconPersistFormat;
3932 }
3933
3934 @VisibleForTesting
3935 int getIconPersistQualityForTest() {
3936 return mIconPersistQuality;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003937 }
Makoto Onuki41066a62016-03-09 16:18:44 -08003938
3939 @VisibleForTesting
Makoto Onuki22fcc682016-05-17 14:52:19 -07003940 ShortcutPackage getPackageShortcutForTest(String packageName, int userId) {
Makoto Onuki41066a62016-03-09 16:18:44 -08003941 synchronized (mLock) {
Makoto Onuki31459242016-03-22 11:12:18 -07003942 final ShortcutUser user = mUsers.get(userId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07003943 if (user == null) return null;
3944
Makoto Onuki22fcc682016-05-17 14:52:19 -07003945 return user.getAllPackagesForTest().get(packageName);
3946 }
3947 }
3948
3949 @VisibleForTesting
3950 ShortcutInfo getPackageShortcutForTest(String packageName, String shortcutId, int userId) {
3951 synchronized (mLock) {
Makoto Onukif34c3082016-07-13 10:25:25 -07003952 final ShortcutPackage pkg = getPackageShortcutForTest(packageName, userId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07003953 if (pkg == null) return null;
3954
3955 return pkg.findShortcutById(shortcutId);
Makoto Onuki41066a62016-03-09 16:18:44 -08003956 }
3957 }
Makoto Onuki7001a612016-05-27 13:24:28 -07003958
Makoto Onukifac592f2016-11-21 13:41:32 -08003959 @VisibleForTesting
3960 ShortcutLauncher getLauncherShortcutForTest(String packageName, int userId) {
3961 synchronized (mLock) {
3962 final ShortcutUser user = mUsers.get(userId);
3963 if (user == null) return null;
3964
3965 return user.getAllLaunchersForTest().get(PackageWithUser.of(userId, packageName));
3966 }
3967 }
3968
Makoto Onuki2d895c32016-12-02 15:48:40 -08003969 @VisibleForTesting
3970 ShortcutRequestPinProcessor getShortcutRequestPinProcessorForTest() {
3971 return mShortcutRequestPinProcessor;
3972 }
3973
Makoto Onuki7001a612016-05-27 13:24:28 -07003974 /**
3975 * Control whether {@link #verifyStates} should be performed. We always perform it during unit
3976 * tests.
3977 */
3978 @VisibleForTesting
3979 boolean injectShouldPerformVerification() {
3980 return DEBUG;
3981 }
3982
3983 /**
3984 * Check various internal states and throws if there's any inconsistency.
3985 * This is normally only enabled during unit tests.
3986 */
3987 final void verifyStates() {
3988 if (injectShouldPerformVerification()) {
3989 verifyStatesInner();
3990 }
3991 }
3992
Makoto Onukib08790c2016-06-23 14:05:46 -07003993 private final void verifyStatesForce() {
3994 verifyStatesInner();
3995 }
3996
Makoto Onuki7001a612016-05-27 13:24:28 -07003997 private void verifyStatesInner() {
Makoto Onuki10305202016-07-14 18:14:08 -07003998 synchronized (mLock) {
Makoto Onuki7001a612016-05-27 13:24:28 -07003999 forEachLoadedUserLocked(u -> u.forAllPackageItems(ShortcutPackageItem::verifyStates));
4000 }
4001 }
Makoto Onuki41066a62016-03-09 16:18:44 -08004002}