blob: d5767b4cad8a22acbbc1633dbd4ba791e6863f5b [file] [log] [blame]
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package com.android.server.pm;
17
Makoto Onuki7001a612016-05-27 13:24:28 -070018import android.annotation.IntDef;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080019import android.annotation.NonNull;
20import android.annotation.Nullable;
21import android.annotation.UserIdInt;
Makoto Onuki55046222016-03-08 10:49:47 -080022import android.app.ActivityManager;
Makoto Onuki33525d22016-08-03 15:45:24 -070023import android.app.ActivityManagerInternal;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -070024import android.app.ActivityManagerNative;
Makoto Onuki0acbb142016-03-22 17:02:57 -070025import android.app.AppGlobals;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -070026import android.app.IUidObserver;
Makoto Onukiac042502016-05-20 16:39:42 -070027import android.app.usage.UsageStatsManagerInternal;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070028import android.content.BroadcastReceiver;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080029import android.content.ComponentName;
30import android.content.Context;
31import android.content.Intent;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070032import android.content.IntentFilter;
Makoto Onuki22fcc682016-05-17 14:52:19 -070033import android.content.pm.ActivityInfo;
Makoto Onuki0acbb142016-03-22 17:02:57 -070034import android.content.pm.ApplicationInfo;
35import android.content.pm.IPackageManager;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080036import android.content.pm.IShortcutService;
37import android.content.pm.LauncherApps;
38import android.content.pm.LauncherApps.ShortcutQuery;
Makoto Onuki0acbb142016-03-22 17:02:57 -070039import android.content.pm.PackageInfo;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080040import android.content.pm.PackageManager;
Makoto Onuki20c95f82016-05-11 16:51:01 -070041import android.content.pm.PackageManager.NameNotFoundException;
Makoto Onuki2d5b4652016-03-11 16:09:54 -080042import android.content.pm.PackageManagerInternal;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080043import android.content.pm.ParceledListSlice;
Makoto Onuki2d5b4652016-03-11 16:09:54 -080044import android.content.pm.ResolveInfo;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080045import android.content.pm.ShortcutInfo;
46import android.content.pm.ShortcutServiceInternal;
47import android.content.pm.ShortcutServiceInternal.ShortcutChangeListener;
Makoto Onuki157b1622016-06-02 16:13:10 -070048import android.content.res.Resources;
Makoto Onuki22fcc682016-05-17 14:52:19 -070049import android.content.res.XmlResourceParser;
Makoto Onuki55046222016-03-08 10:49:47 -080050import android.graphics.Bitmap;
51import android.graphics.Bitmap.CompressFormat;
Makoto Onuki55046222016-03-08 10:49:47 -080052import android.graphics.Canvas;
53import android.graphics.RectF;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080054import android.graphics.drawable.Icon;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070055import android.net.Uri;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080056import android.os.Binder;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080057import android.os.Environment;
Makoto Onuki2e210c42016-03-30 08:30:36 -070058import android.os.FileUtils;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080059import android.os.Handler;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070060import android.os.LocaleList;
Makoto Onukiaa8b94a2016-03-17 13:14:05 -070061import android.os.Looper;
Makoto Onuki55046222016-03-08 10:49:47 -080062import android.os.ParcelFileDescriptor;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080063import android.os.PersistableBundle;
64import android.os.Process;
65import android.os.RemoteException;
66import android.os.ResultReceiver;
Makoto Onuki55046222016-03-08 10:49:47 -080067import android.os.SELinux;
Makoto Onukib08790c2016-06-23 14:05:46 -070068import android.os.ServiceManager;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080069import android.os.ShellCommand;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -070070import android.os.SystemClock;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080071import android.os.UserHandle;
Makoto Onukicdc78f72016-03-21 15:47:52 -070072import android.os.UserManager;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080073import android.text.TextUtils;
74import android.text.format.Time;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080075import android.util.ArraySet;
76import android.util.AtomicFile;
Makoto Onuki4362a662016-03-08 18:59:09 -080077import android.util.KeyValueListParser;
Makoto Onukiac042502016-05-20 16:39:42 -070078import android.util.Log;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080079import android.util.Slog;
80import android.util.SparseArray;
Makoto Onuki02f338e2016-07-29 09:40:40 -070081import android.util.SparseBooleanArray;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -070082import android.util.SparseIntArray;
83import android.util.SparseLongArray;
Makoto Onuki55046222016-03-08 10:49:47 -080084import android.util.TypedValue;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080085import android.util.Xml;
Makoto Onukib08790c2016-06-23 14:05:46 -070086import android.view.IWindowManager;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080087
88import com.android.internal.annotations.GuardedBy;
89import com.android.internal.annotations.VisibleForTesting;
90import com.android.internal.os.BackgroundThread;
91import com.android.internal.util.FastXmlSerializer;
92import com.android.internal.util.Preconditions;
93import com.android.server.LocalServices;
94import com.android.server.SystemService;
Makoto Onukid99c6f02016-03-28 11:02:54 -070095import com.android.server.pm.ShortcutUser.PackageWithUser;
Makoto Onuki6f7362d92016-03-04 13:39:41 -080096
97import libcore.io.IoUtils;
98
Makoto Onuki76269922016-07-15 14:58:54 -070099import org.json.JSONArray;
100import org.json.JSONException;
101import org.json.JSONObject;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800102import org.xmlpull.v1.XmlPullParser;
103import org.xmlpull.v1.XmlPullParserException;
104import org.xmlpull.v1.XmlSerializer;
105
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700106import java.io.BufferedInputStream;
107import java.io.BufferedOutputStream;
108import java.io.ByteArrayInputStream;
109import java.io.ByteArrayOutputStream;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800110import java.io.File;
111import java.io.FileDescriptor;
112import java.io.FileInputStream;
113import java.io.FileNotFoundException;
114import java.io.FileOutputStream;
115import java.io.IOException;
Makoto Onuki55046222016-03-08 10:49:47 -0800116import java.io.InputStream;
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700117import java.io.OutputStream;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800118import java.io.PrintWriter;
Makoto Onuki7001a612016-05-27 13:24:28 -0700119import java.lang.annotation.Retention;
120import java.lang.annotation.RetentionPolicy;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800121import java.net.URISyntaxException;
122import java.nio.charset.StandardCharsets;
123import java.util.ArrayList;
Makoto Onuki22fcc682016-05-17 14:52:19 -0700124import java.util.Collections;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800125import java.util.List;
Makoto Onukic51b2872016-05-04 15:24:50 -0700126import java.util.concurrent.atomic.AtomicBoolean;
Makoto Onuki2e210c42016-03-30 08:30:36 -0700127import java.util.function.Consumer;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800128import java.util.function.Predicate;
129
130/**
131 * TODO:
Makoto Onuki22fcc682016-05-17 14:52:19 -0700132 * - getIconMaxWidth()/getIconMaxHeight() should use xdpi and ydpi.
Makoto Onukib5a012f2016-06-21 11:13:53 -0700133 * -> But TypedValue.applyDimension() doesn't differentiate x and y..?
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800134 *
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700135 * - Detect when already registered instances are passed to APIs again, which might break
Makoto Onukib08790c2016-06-23 14:05:46 -0700136 * internal bitmap handling.
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800137 */
138public class ShortcutService extends IShortcutService.Stub {
Makoto Onuki55046222016-03-08 10:49:47 -0800139 static final String TAG = "ShortcutService";
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800140
Makoto Onuki7001a612016-05-27 13:24:28 -0700141 static final boolean DEBUG = false; // STOPSHIP if true
Makoto Onuki41066a62016-03-09 16:18:44 -0800142 static final boolean DEBUG_LOAD = false; // STOPSHIP if true
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700143 static final boolean DEBUG_PROCSTATE = false; // STOPSHIP if true
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800144
Makoto Onuki4362a662016-03-08 18:59:09 -0800145 @VisibleForTesting
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700146 static final long DEFAULT_RESET_INTERVAL_SEC = 24 * 60 * 60; // 1 day
Makoto Onuki4362a662016-03-08 18:59:09 -0800147
148 @VisibleForTesting
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700149 static final int DEFAULT_MAX_UPDATES_PER_INTERVAL = 10;
Makoto Onuki4362a662016-03-08 18:59:09 -0800150
151 @VisibleForTesting
152 static final int DEFAULT_MAX_SHORTCUTS_PER_APP = 5;
153
154 @VisibleForTesting
155 static final int DEFAULT_MAX_ICON_DIMENSION_DP = 96;
156
157 @VisibleForTesting
158 static final int DEFAULT_MAX_ICON_DIMENSION_LOWRAM_DP = 48;
159
160 @VisibleForTesting
161 static final String DEFAULT_ICON_PERSIST_FORMAT = CompressFormat.PNG.name();
162
163 @VisibleForTesting
164 static final int DEFAULT_ICON_PERSIST_QUALITY = 100;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800165
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700166 @VisibleForTesting
167 static final int DEFAULT_SAVE_DELAY_MS = 3000;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800168
169 @VisibleForTesting
170 static final String FILENAME_BASE_STATE = "shortcut_service.xml";
171
172 @VisibleForTesting
173 static final String DIRECTORY_PER_USER = "shortcut_service";
174
175 @VisibleForTesting
176 static final String FILENAME_USER_PACKAGES = "shortcuts.xml";
177
Makoto Onuki55046222016-03-08 10:49:47 -0800178 static final String DIRECTORY_BITMAPS = "bitmaps";
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800179
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700180 private static final String TAG_ROOT = "root";
181 private static final String TAG_LAST_RESET_TIME = "last_reset_time";
Makoto Onuki55046222016-03-08 10:49:47 -0800182
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700183 private static final String ATTR_VALUE = "value";
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800184
Makoto Onukib08790c2016-06-23 14:05:46 -0700185 private static final String LAUNCHER_INTENT_CATEGORY = Intent.CATEGORY_LAUNCHER;
186
Makoto Onuki76269922016-07-15 14:58:54 -0700187 private static final String KEY_SHORTCUT = "shortcut";
188 private static final String KEY_LOW_RAM = "lowRam";
189 private static final String KEY_ICON_SIZE = "iconSize";
190
Makoto Onuki4362a662016-03-08 18:59:09 -0800191 @VisibleForTesting
192 interface ConfigConstants {
193 /**
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700194 * Key name for the save delay, in milliseconds. (int)
195 */
196 String KEY_SAVE_DELAY_MILLIS = "save_delay_ms";
197
198 /**
Makoto Onuki4362a662016-03-08 18:59:09 -0800199 * Key name for the throttling reset interval, in seconds. (long)
200 */
201 String KEY_RESET_INTERVAL_SEC = "reset_interval_sec";
202
203 /**
204 * Key name for the max number of modifying API calls per app for every interval. (int)
205 */
Makoto Onukib6d35232016-04-04 15:57:17 -0700206 String KEY_MAX_UPDATES_PER_INTERVAL = "max_updates_per_interval";
Makoto Onuki4362a662016-03-08 18:59:09 -0800207
208 /**
209 * Key name for the max icon dimensions in DP, for non-low-memory devices.
210 */
211 String KEY_MAX_ICON_DIMENSION_DP = "max_icon_dimension_dp";
212
213 /**
214 * Key name for the max icon dimensions in DP, for low-memory devices.
215 */
216 String KEY_MAX_ICON_DIMENSION_DP_LOWRAM = "max_icon_dimension_dp_lowram";
217
218 /**
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700219 * Key name for the max dynamic shortcuts per activity. (int)
Makoto Onuki4362a662016-03-08 18:59:09 -0800220 */
221 String KEY_MAX_SHORTCUTS = "max_shortcuts";
222
223 /**
Makoto Onuki41066a62016-03-09 16:18:44 -0800224 * Key name for icon compression quality, 0-100.
Makoto Onuki4362a662016-03-08 18:59:09 -0800225 */
226 String KEY_ICON_QUALITY = "icon_quality";
227
228 /**
229 * Key name for icon compression format: "PNG", "JPEG" or "WEBP"
230 */
231 String KEY_ICON_FORMAT = "icon_format";
232 }
233
Makoto Onuki41066a62016-03-09 16:18:44 -0800234 final Context mContext;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800235
236 private final Object mLock = new Object();
237
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700238 private static List<ResolveInfo> EMPTY_RESOLVE_INFO = new ArrayList<>(0);
239
240 private static Predicate<ResolveInfo> ACTIVITY_NOT_EXPORTED =
241 ri -> !ri.activityInfo.exported;
242
243 private static Predicate<PackageInfo> PACKAGE_NOT_INSTALLED = pi -> !isInstalled(pi);
244
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800245 private final Handler mHandler;
246
247 @GuardedBy("mLock")
248 private final ArrayList<ShortcutChangeListener> mListeners = new ArrayList<>(1);
249
250 @GuardedBy("mLock")
251 private long mRawLastResetTime;
252
253 /**
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -0800254 * User ID -> UserShortcuts
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800255 */
256 @GuardedBy("mLock")
Makoto Onuki31459242016-03-22 11:12:18 -0700257 private final SparseArray<ShortcutUser> mUsers = new SparseArray<>();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800258
259 /**
Makoto Onukib5a012f2016-06-21 11:13:53 -0700260 * Max number of dynamic + manifest shortcuts that each application can have at a time.
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800261 */
Makoto Onukib5a012f2016-06-21 11:13:53 -0700262 private int mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800263
264 /**
Makoto Onukib6d35232016-04-04 15:57:17 -0700265 * Max number of updating API calls that each application can make during the interval.
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800266 */
Makoto Onukib6d35232016-04-04 15:57:17 -0700267 int mMaxUpdatesPerInterval;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800268
269 /**
270 * Actual throttling-reset interval. By default it's a day.
271 */
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800272 private long mResetInterval;
273
Makoto Onuki55046222016-03-08 10:49:47 -0800274 /**
275 * Icon max width/height in pixels.
276 */
277 private int mMaxIconDimension;
278
Makoto Onuki4362a662016-03-08 18:59:09 -0800279 private CompressFormat mIconPersistFormat;
280 private int mIconPersistQuality;
Makoto Onuki55046222016-03-08 10:49:47 -0800281
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700282 private int mSaveDelayMillis;
283
Makoto Onuki0acbb142016-03-22 17:02:57 -0700284 private final IPackageManager mIPackageManager;
Makoto Onuki2d5b4652016-03-11 16:09:54 -0800285 private final PackageManagerInternal mPackageManagerInternal;
Makoto Onukicdc78f72016-03-21 15:47:52 -0700286 private final UserManager mUserManager;
Makoto Onukiac042502016-05-20 16:39:42 -0700287 private final UsageStatsManagerInternal mUsageStatsManagerInternal;
Makoto Onuki33525d22016-08-03 15:45:24 -0700288 private final ActivityManagerInternal mActivityManagerInternal;
Makoto Onuki2d5b4652016-03-11 16:09:54 -0800289
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700290 @GuardedBy("mLock")
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700291 final SparseIntArray mUidState = new SparseIntArray();
292
293 @GuardedBy("mLock")
294 final SparseLongArray mUidLastForegroundElapsedTime = new SparseLongArray();
295
296 @GuardedBy("mLock")
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700297 private List<Integer> mDirtyUserIds = new ArrayList<>();
298
Makoto Onukic51b2872016-05-04 15:24:50 -0700299 private final AtomicBoolean mBootCompleted = new AtomicBoolean();
300
Makoto Onuki905e8852016-03-28 10:40:58 -0700301 private static final int PACKAGE_MATCH_FLAGS =
302 PackageManager.MATCH_DIRECT_BOOT_AWARE
Makoto Onukib08790c2016-06-23 14:05:46 -0700303 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE
304 | PackageManager.MATCH_UNINSTALLED_PACKAGES;
Makoto Onuki905e8852016-03-28 10:40:58 -0700305
Makoto Onuki02f338e2016-07-29 09:40:40 -0700306 @GuardedBy("mLock")
307 final SparseBooleanArray mUnlockedUsers = new SparseBooleanArray();
308
Makoto Onuki2e210c42016-03-30 08:30:36 -0700309 // Stats
310 @VisibleForTesting
311 interface Stats {
312 int GET_DEFAULT_HOME = 0;
313 int GET_PACKAGE_INFO = 1;
314 int GET_PACKAGE_INFO_WITH_SIG = 2;
315 int GET_APPLICATION_INFO = 3;
316 int LAUNCHER_PERMISSION_CHECK = 4;
Makoto Onuki6c1dbd52016-05-02 15:19:32 -0700317 int CLEANUP_DANGLING_BITMAPS = 5;
Makoto Onukib08790c2016-06-23 14:05:46 -0700318 int GET_ACTIVITY_WITH_METADATA = 6;
Makoto Onuki6dd9fb72016-06-01 13:55:54 -0700319 int GET_INSTALLED_PACKAGES = 7;
Makoto Onuki22fcc682016-05-17 14:52:19 -0700320 int CHECK_PACKAGE_CHANGES = 8;
Makoto Onuki157b1622016-06-02 16:13:10 -0700321 int GET_APPLICATION_RESOURCES = 9;
322 int RESOURCE_NAME_LOOKUP = 10;
Makoto Onukib08790c2016-06-23 14:05:46 -0700323 int GET_LAUNCHER_ACTIVITY = 11;
324 int CHECK_LAUNCHER_ACTIVITY = 12;
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700325 int IS_ACTIVITY_ENABLED = 13;
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700326 int PACKAGE_UPDATE_CHECK = 14;
Makoto Onuki2e210c42016-03-30 08:30:36 -0700327
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700328 int COUNT = PACKAGE_UPDATE_CHECK + 1;
Makoto Onuki2e210c42016-03-30 08:30:36 -0700329 }
330
331 final Object mStatLock = new Object();
332
333 @GuardedBy("mStatLock")
334 private final int[] mCountStats = new int[Stats.COUNT];
335
336 @GuardedBy("mStatLock")
337 private final long[] mDurationStats = new long[Stats.COUNT];
338
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700339 private static final int PROCESS_STATE_FOREGROUND_THRESHOLD =
340 ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
341
Makoto Onuki7001a612016-05-27 13:24:28 -0700342 static final int OPERATION_SET = 0;
343 static final int OPERATION_ADD = 1;
344 static final int OPERATION_UPDATE = 2;
345
346 /** @hide */
347 @IntDef(value = {
348 OPERATION_SET,
349 OPERATION_ADD,
350 OPERATION_UPDATE
Makoto Onukib08790c2016-06-23 14:05:46 -0700351 })
Makoto Onuki7001a612016-05-27 13:24:28 -0700352 @Retention(RetentionPolicy.SOURCE)
Makoto Onukib08790c2016-06-23 14:05:46 -0700353 @interface ShortcutOperation {
354 }
Makoto Onuki7001a612016-05-27 13:24:28 -0700355
Makoto Onukia2241832016-07-06 13:28:37 -0700356 @GuardedBy("mLock")
357 private int mWtfCount = 0;
358
359 @GuardedBy("mLock")
360 private Exception mLastWtfStacktrace;
361
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800362 public ShortcutService(Context context) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700363 this(context, BackgroundThread.get().getLooper(), /*onyForPackgeManagerApis*/ false);
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700364 }
365
366 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700367 ShortcutService(Context context, Looper looper, boolean onlyForPackageManagerApis) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800368 mContext = Preconditions.checkNotNull(context);
369 LocalServices.addService(ShortcutServiceInternal.class, new LocalService());
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700370 mHandler = new Handler(looper);
Makoto Onuki0acbb142016-03-22 17:02:57 -0700371 mIPackageManager = AppGlobals.getPackageManager();
Makoto Onukiac042502016-05-20 16:39:42 -0700372 mPackageManagerInternal = Preconditions.checkNotNull(
373 LocalServices.getService(PackageManagerInternal.class));
374 mUserManager = Preconditions.checkNotNull(context.getSystemService(UserManager.class));
375 mUsageStatsManagerInternal = Preconditions.checkNotNull(
376 LocalServices.getService(UsageStatsManagerInternal.class));
Makoto Onuki33525d22016-08-03 15:45:24 -0700377 mActivityManagerInternal = Preconditions.checkNotNull(
378 LocalServices.getService(ActivityManagerInternal.class));
Makoto Onukicdc78f72016-03-21 15:47:52 -0700379
Makoto Onukiee6b6e42016-06-29 17:34:02 -0700380 if (onlyForPackageManagerApis) {
381 return; // Don't do anything further. For unit tests only.
382 }
383
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700384 // Register receivers.
385
386 // We need to set a priority, so let's just not use PackageMonitor for now.
387 // TODO Refactor PackageMonitor to support priorities.
388 final IntentFilter packageFilter = new IntentFilter();
389 packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
390 packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
391 packageFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
392 packageFilter.addAction(Intent.ACTION_PACKAGE_DATA_CLEARED);
393 packageFilter.addDataScheme("package");
394 packageFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
395 mContext.registerReceiverAsUser(mPackageMonitor, UserHandle.ALL,
396 packageFilter, null, mHandler);
397
Makoto Onuki10305202016-07-14 18:14:08 -0700398 final IntentFilter preferedActivityFilter = new IntentFilter();
399 preferedActivityFilter.addAction(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
400 preferedActivityFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
401 mContext.registerReceiverAsUser(mPackageMonitor, UserHandle.ALL,
402 preferedActivityFilter, null, mHandler);
403
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700404 final IntentFilter localeFilter = new IntentFilter();
405 localeFilter.addAction(Intent.ACTION_LOCALE_CHANGED);
406 localeFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
407 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL,
408 localeFilter, null, mHandler);
Makoto Onukif34c3082016-07-13 10:25:25 -0700409
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700410 injectRegisterUidObserver(mUidObserver, ActivityManager.UID_OBSERVER_PROCSTATE
411 | ActivityManager.UID_OBSERVER_GONE);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800412 }
413
Makoto Onuki2e210c42016-03-30 08:30:36 -0700414 void logDurationStat(int statId, long start) {
415 synchronized (mStatLock) {
416 mCountStats[statId]++;
Makoto Onuki6c1dbd52016-05-02 15:19:32 -0700417 mDurationStats[statId] += (injectElapsedRealtime() - start);
Makoto Onuki2e210c42016-03-30 08:30:36 -0700418 }
419 }
420
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700421 public String injectGetLocaleTagsForUser(@UserIdInt int userId) {
422 // TODO This should get the per-user locale. b/30123329 b/30119489
423 return LocaleList.getDefault().toLanguageTags();
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700424 }
425
426 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Makoto Onukib08790c2016-06-23 14:05:46 -0700427 @Override
428 public void onUidStateChanged(int uid, int procState) throws RemoteException {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700429 handleOnUidStateChanged(uid, procState);
430 }
431
Makoto Onukib08790c2016-06-23 14:05:46 -0700432 @Override
433 public void onUidGone(int uid) throws RemoteException {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700434 handleOnUidStateChanged(uid, ActivityManager.MAX_PROCESS_STATE);
435 }
436
Makoto Onukib08790c2016-06-23 14:05:46 -0700437 @Override
438 public void onUidActive(int uid) throws RemoteException {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700439 }
440
Makoto Onukib08790c2016-06-23 14:05:46 -0700441 @Override
442 public void onUidIdle(int uid) throws RemoteException {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700443 }
444 };
445
446 void handleOnUidStateChanged(int uid, int procState) {
447 if (DEBUG_PROCSTATE) {
448 Slog.d(TAG, "onUidStateChanged: uid=" + uid + " state=" + procState);
449 }
450 synchronized (mLock) {
451 mUidState.put(uid, procState);
452
453 // We need to keep track of last time an app comes to foreground.
454 // See ShortcutPackage.getApiCallCount() for how it's used.
455 // It doesn't have to be persisted, but it needs to be the elapsed time.
456 if (isProcessStateForeground(procState)) {
457 mUidLastForegroundElapsedTime.put(uid, injectElapsedRealtime());
458 }
459 }
460 }
461
462 private boolean isProcessStateForeground(int processState) {
Makoto Onuki33525d22016-08-03 15:45:24 -0700463 return (processState != ActivityManager.PROCESS_STATE_NONEXISTENT)
464 && (processState <= PROCESS_STATE_FOREGROUND_THRESHOLD);
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700465 }
466
467 boolean isUidForegroundLocked(int uid) {
468 if (uid == Process.SYSTEM_UID) {
469 // IUidObserver doesn't report the state of SYSTEM, but it always has bound services,
470 // so it's foreground anyway.
471 return true;
472 }
Makoto Onuki33525d22016-08-03 15:45:24 -0700473 // First, check with the local cache.
474 if (isProcessStateForeground(mUidState.get(uid, ActivityManager.MAX_PROCESS_STATE))) {
475 return true;
476 }
477 // If the cache says background, reach out to AM. Since it'll internally need to hold
478 // the AM lock, we use it as a last resort.
479 return isProcessStateForeground(mActivityManagerInternal.getUidProcessState(uid));
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700480 }
481
482 long getUidLastForegroundElapsedTimeLocked(int uid) {
483 return mUidLastForegroundElapsedTime.get(uid);
484 }
485
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800486 /**
487 * System service lifecycle.
488 */
489 public static final class Lifecycle extends SystemService {
490 final ShortcutService mService;
491
492 public Lifecycle(Context context) {
493 super(context);
494 mService = new ShortcutService(context);
495 }
496
497 @Override
498 public void onStart() {
499 publishBinderService(Context.SHORTCUT_SERVICE, mService);
500 }
501
502 @Override
503 public void onBootPhase(int phase) {
504 mService.onBootPhase(phase);
505 }
506
507 @Override
508 public void onCleanupUser(int userHandle) {
Makoto Onukicdc78f72016-03-21 15:47:52 -0700509 mService.handleCleanupUser(userHandle);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800510 }
511
512 @Override
Makoto Onukif3a572b2016-03-10 12:28:38 -0800513 public void onUnlockUser(int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -0700514 mService.handleUnlockUser(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800515 }
516 }
517
518 /** lifecycle event */
519 void onBootPhase(int phase) {
520 if (DEBUG) {
521 Slog.d(TAG, "onBootPhase: " + phase);
522 }
523 switch (phase) {
524 case SystemService.PHASE_LOCK_SETTINGS_READY:
525 initialize();
526 break;
Makoto Onukic51b2872016-05-04 15:24:50 -0700527 case SystemService.PHASE_BOOT_COMPLETED:
528 mBootCompleted.set(true);
529 break;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800530 }
531 }
532
533 /** lifecycle event */
Makoto Onukicdc78f72016-03-21 15:47:52 -0700534 void handleUnlockUser(int userId) {
Makoto Onuki22fcc682016-05-17 14:52:19 -0700535 if (DEBUG) {
536 Slog.d(TAG, "handleUnlockUser: user=" + userId);
537 }
Makoto Onukicdc78f72016-03-21 15:47:52 -0700538 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -0700539 mUnlockedUsers.put(userId, true);
540
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700541 // Preload the user's shortcuts.
542 // Also see if the locale has changed.
543 // Note as of nyc, the locale is per-user, so the locale shouldn't change
544 // when the user is locked. However due to b/30119489 it still happens.
545 getUserShortcutsLocked(userId).detectLocaleChange();
Makoto Onuki0acbb142016-03-22 17:02:57 -0700546
Makoto Onuki39686e82016-04-13 18:03:00 -0700547 checkPackageChanges(userId);
Makoto Onukicdc78f72016-03-21 15:47:52 -0700548 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800549 }
550
551 /** lifecycle event */
Makoto Onukicdc78f72016-03-21 15:47:52 -0700552 void handleCleanupUser(int userId) {
Makoto Onuki02f338e2016-07-29 09:40:40 -0700553 if (DEBUG) {
554 Slog.d(TAG, "handleCleanupUser: user=" + userId);
555 }
Makoto Onukicdc78f72016-03-21 15:47:52 -0700556 synchronized (mLock) {
557 unloadUserLocked(userId);
Makoto Onuki02f338e2016-07-29 09:40:40 -0700558
559 mUnlockedUsers.put(userId, false);
Makoto Onukicdc78f72016-03-21 15:47:52 -0700560 }
561 }
562
563 private void unloadUserLocked(int userId) {
564 if (DEBUG) {
565 Slog.d(TAG, "unloadUserLocked: user=" + userId);
566 }
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700567 // Save all dirty information.
568 saveDirtyInfo();
569
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800570 // Unload
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -0800571 mUsers.delete(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800572 }
573
574 /** Return the base state file name */
575 private AtomicFile getBaseStateFile() {
576 final File path = new File(injectSystemDataPath(), FILENAME_BASE_STATE);
577 path.mkdirs();
578 return new AtomicFile(path);
579 }
580
581 /**
582 * Init the instance. (load the state file, etc)
583 */
584 private void initialize() {
585 synchronized (mLock) {
Makoto Onuki4362a662016-03-08 18:59:09 -0800586 loadConfigurationLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800587 loadBaseStateLocked();
588 }
589 }
590
Makoto Onuki4362a662016-03-08 18:59:09 -0800591 /**
592 * Load the configuration from Settings.
593 */
594 private void loadConfigurationLocked() {
595 updateConfigurationLocked(injectShortcutManagerConstants());
596 }
Makoto Onuki55046222016-03-08 10:49:47 -0800597
Makoto Onuki4362a662016-03-08 18:59:09 -0800598 /**
599 * Load the configuration from Settings.
600 */
601 @VisibleForTesting
602 boolean updateConfigurationLocked(String config) {
603 boolean result = true;
604
605 final KeyValueListParser parser = new KeyValueListParser(',');
606 try {
607 parser.setString(config);
608 } catch (IllegalArgumentException e) {
609 // Failed to parse the settings string, log this and move on
610 // with defaults.
611 Slog.e(TAG, "Bad shortcut manager settings", e);
612 result = false;
613 }
614
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700615 mSaveDelayMillis = Math.max(0, (int) parser.getLong(ConfigConstants.KEY_SAVE_DELAY_MILLIS,
616 DEFAULT_SAVE_DELAY_MS));
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700617
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700618 mResetInterval = Math.max(1, parser.getLong(
Makoto Onuki4362a662016-03-08 18:59:09 -0800619 ConfigConstants.KEY_RESET_INTERVAL_SEC, DEFAULT_RESET_INTERVAL_SEC)
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700620 * 1000L);
Makoto Onuki4362a662016-03-08 18:59:09 -0800621
Makoto Onukib6d35232016-04-04 15:57:17 -0700622 mMaxUpdatesPerInterval = Math.max(0, (int) parser.getLong(
623 ConfigConstants.KEY_MAX_UPDATES_PER_INTERVAL, DEFAULT_MAX_UPDATES_PER_INTERVAL));
Makoto Onuki4362a662016-03-08 18:59:09 -0800624
Makoto Onukib5a012f2016-06-21 11:13:53 -0700625 mMaxShortcuts = Math.max(0, (int) parser.getLong(
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700626 ConfigConstants.KEY_MAX_SHORTCUTS, DEFAULT_MAX_SHORTCUTS_PER_APP));
Makoto Onuki4362a662016-03-08 18:59:09 -0800627
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -0700628 final int iconDimensionDp = Math.max(1, injectIsLowRamDevice()
Makoto Onuki4362a662016-03-08 18:59:09 -0800629 ? (int) parser.getLong(
Makoto Onukib08790c2016-06-23 14:05:46 -0700630 ConfigConstants.KEY_MAX_ICON_DIMENSION_DP_LOWRAM,
631 DEFAULT_MAX_ICON_DIMENSION_LOWRAM_DP)
Makoto Onuki4362a662016-03-08 18:59:09 -0800632 : (int) parser.getLong(
Makoto Onukib08790c2016-06-23 14:05:46 -0700633 ConfigConstants.KEY_MAX_ICON_DIMENSION_DP,
634 DEFAULT_MAX_ICON_DIMENSION_DP));
Makoto Onuki4362a662016-03-08 18:59:09 -0800635
636 mMaxIconDimension = injectDipToPixel(iconDimensionDp);
637
638 mIconPersistFormat = CompressFormat.valueOf(
639 parser.getString(ConfigConstants.KEY_ICON_FORMAT, DEFAULT_ICON_PERSIST_FORMAT));
640
641 mIconPersistQuality = (int) parser.getLong(
642 ConfigConstants.KEY_ICON_QUALITY,
643 DEFAULT_ICON_PERSIST_QUALITY);
644
645 return result;
646 }
647
648 @VisibleForTesting
649 String injectShortcutManagerConstants() {
650 return android.provider.Settings.Global.getString(
651 mContext.getContentResolver(),
652 android.provider.Settings.Global.SHORTCUT_MANAGER_CONSTANTS);
653 }
654
655 @VisibleForTesting
656 int injectDipToPixel(int dip) {
657 return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip,
658 mContext.getResources().getDisplayMetrics());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800659 }
660
Makoto Onuki55046222016-03-08 10:49:47 -0800661 // === Persisting ===
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800662
663 @Nullable
Makoto Onuki41066a62016-03-09 16:18:44 -0800664 static String parseStringAttribute(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800665 return parser.getAttributeValue(null, attribute);
666 }
667
Makoto Onuki0acbb142016-03-22 17:02:57 -0700668 static boolean parseBooleanAttribute(XmlPullParser parser, String attribute) {
669 return parseLongAttribute(parser, attribute) == 1;
670 }
671
Makoto Onuki41066a62016-03-09 16:18:44 -0800672 static int parseIntAttribute(XmlPullParser parser, String attribute) {
673 return (int) parseLongAttribute(parser, attribute);
674 }
675
Makoto Onukid99c6f02016-03-28 11:02:54 -0700676 static int parseIntAttribute(XmlPullParser parser, String attribute, int def) {
677 return (int) parseLongAttribute(parser, attribute, def);
678 }
679
Makoto Onuki41066a62016-03-09 16:18:44 -0800680 static long parseLongAttribute(XmlPullParser parser, String attribute) {
Makoto Onukid99c6f02016-03-28 11:02:54 -0700681 return parseLongAttribute(parser, attribute, 0);
682 }
683
684 static long parseLongAttribute(XmlPullParser parser, String attribute, long def) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800685 final String value = parseStringAttribute(parser, attribute);
686 if (TextUtils.isEmpty(value)) {
Makoto Onukid99c6f02016-03-28 11:02:54 -0700687 return def;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800688 }
689 try {
690 return Long.parseLong(value);
691 } catch (NumberFormatException e) {
692 Slog.e(TAG, "Error parsing long " + value);
Makoto Onukid99c6f02016-03-28 11:02:54 -0700693 return def;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800694 }
695 }
696
697 @Nullable
Makoto Onuki41066a62016-03-09 16:18:44 -0800698 static ComponentName parseComponentNameAttribute(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800699 final String value = parseStringAttribute(parser, attribute);
700 if (TextUtils.isEmpty(value)) {
701 return null;
702 }
703 return ComponentName.unflattenFromString(value);
704 }
705
706 @Nullable
Makoto Onuki440a1ea2016-07-20 14:21:18 -0700707 static Intent parseIntentAttributeNoDefault(XmlPullParser parser, String attribute) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800708 final String value = parseStringAttribute(parser, attribute);
Makoto Onukib5a012f2016-06-21 11:13:53 -0700709 Intent parsed = null;
710 if (!TextUtils.isEmpty(value)) {
711 try {
712 parsed = Intent.parseUri(value, /* flags =*/ 0);
713 } catch (URISyntaxException e) {
714 Slog.e(TAG, "Error parsing intent", e);
715 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800716 }
Makoto Onuki440a1ea2016-07-20 14:21:18 -0700717 return parsed;
718 }
719
720 @Nullable
721 static Intent parseIntentAttribute(XmlPullParser parser, String attribute) {
722 Intent parsed = parseIntentAttributeNoDefault(parser, attribute);
Makoto Onukib5a012f2016-06-21 11:13:53 -0700723 if (parsed == null) {
724 // Default intent.
725 parsed = new Intent(Intent.ACTION_VIEW);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800726 }
Makoto Onukib5a012f2016-06-21 11:13:53 -0700727 return parsed;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800728 }
729
Makoto Onuki41066a62016-03-09 16:18:44 -0800730 static void writeTagValue(XmlSerializer out, String tag, String value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800731 if (TextUtils.isEmpty(value)) return;
732
733 out.startTag(null, tag);
734 out.attribute(null, ATTR_VALUE, value);
735 out.endTag(null, tag);
736 }
737
Makoto Onuki41066a62016-03-09 16:18:44 -0800738 static void writeTagValue(XmlSerializer out, String tag, long value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800739 writeTagValue(out, tag, Long.toString(value));
740 }
741
Makoto Onuki2d5b4652016-03-11 16:09:54 -0800742 static void writeTagValue(XmlSerializer out, String tag, ComponentName name) throws IOException {
743 if (name == null) return;
744 writeTagValue(out, tag, name.flattenToString());
745 }
746
Makoto Onuki41066a62016-03-09 16:18:44 -0800747 static void writeTagExtra(XmlSerializer out, String tag, PersistableBundle bundle)
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800748 throws IOException, XmlPullParserException {
749 if (bundle == null) return;
750
751 out.startTag(null, tag);
752 bundle.saveToXml(out);
753 out.endTag(null, tag);
754 }
755
Makoto Onuki22fcc682016-05-17 14:52:19 -0700756 static void writeAttr(XmlSerializer out, String name, CharSequence value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800757 if (TextUtils.isEmpty(value)) return;
758
Makoto Onuki22fcc682016-05-17 14:52:19 -0700759 out.attribute(null, name, value.toString());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800760 }
761
Makoto Onuki41066a62016-03-09 16:18:44 -0800762 static void writeAttr(XmlSerializer out, String name, long value) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800763 writeAttr(out, name, String.valueOf(value));
764 }
765
Makoto Onuki0acbb142016-03-22 17:02:57 -0700766 static void writeAttr(XmlSerializer out, String name, boolean value) throws IOException {
767 if (value) {
768 writeAttr(out, name, "1");
769 }
770 }
771
Makoto Onuki41066a62016-03-09 16:18:44 -0800772 static void writeAttr(XmlSerializer out, String name, ComponentName comp) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800773 if (comp == null) return;
774 writeAttr(out, name, comp.flattenToString());
775 }
776
Makoto Onuki41066a62016-03-09 16:18:44 -0800777 static void writeAttr(XmlSerializer out, String name, Intent intent) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800778 if (intent == null) return;
779
780 writeAttr(out, name, intent.toUri(/* flags =*/ 0));
781 }
782
783 @VisibleForTesting
784 void saveBaseStateLocked() {
785 final AtomicFile file = getBaseStateFile();
786 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700787 Slog.d(TAG, "Saving to " + file.getBaseFile());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800788 }
789
790 FileOutputStream outs = null;
791 try {
792 outs = file.startWrite();
793
794 // Write to XML
795 XmlSerializer out = new FastXmlSerializer();
796 out.setOutput(outs, StandardCharsets.UTF_8.name());
797 out.startDocument(null, true);
798 out.startTag(null, TAG_ROOT);
799
800 // Body.
801 writeTagValue(out, TAG_LAST_RESET_TIME, mRawLastResetTime);
802
803 // Epilogue.
804 out.endTag(null, TAG_ROOT);
805 out.endDocument();
806
807 // Close.
808 file.finishWrite(outs);
809 } catch (IOException e) {
810 Slog.e(TAG, "Failed to write to file " + file.getBaseFile(), e);
811 file.failWrite(outs);
812 }
813 }
814
815 private void loadBaseStateLocked() {
816 mRawLastResetTime = 0;
817
818 final AtomicFile file = getBaseStateFile();
819 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700820 Slog.d(TAG, "Loading from " + file.getBaseFile());
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800821 }
822 try (FileInputStream in = file.openRead()) {
823 XmlPullParser parser = Xml.newPullParser();
824 parser.setInput(in, StandardCharsets.UTF_8.name());
825
826 int type;
827 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
828 if (type != XmlPullParser.START_TAG) {
829 continue;
830 }
831 final int depth = parser.getDepth();
832 // Check the root tag
833 final String tag = parser.getName();
834 if (depth == 1) {
835 if (!TAG_ROOT.equals(tag)) {
836 Slog.e(TAG, "Invalid root tag: " + tag);
837 return;
838 }
839 continue;
840 }
841 // Assume depth == 2
842 switch (tag) {
843 case TAG_LAST_RESET_TIME:
844 mRawLastResetTime = parseLongAttribute(parser, ATTR_VALUE);
845 break;
846 default:
847 Slog.e(TAG, "Invalid tag: " + tag);
848 break;
849 }
850 }
851 } catch (FileNotFoundException e) {
852 // Use the default
Makoto Onukib08790c2016-06-23 14:05:46 -0700853 } catch (IOException | XmlPullParserException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800854 Slog.e(TAG, "Failed to read file " + file.getBaseFile(), e);
855
856 mRawLastResetTime = 0;
857 }
858 // Adjust the last reset time.
859 getLastResetTimeLocked();
860 }
861
Makoto Onuki0eed4412016-07-21 11:21:59 -0700862 @VisibleForTesting
863 final File getUserFile(@UserIdInt int userId) {
864 return new File(injectUserDataPath(userId), FILENAME_USER_PACKAGES);
865 }
866
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800867 private void saveUserLocked(@UserIdInt int userId) {
Makoto Onuki0eed4412016-07-21 11:21:59 -0700868 final File path = getUserFile(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800869 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700870 Slog.d(TAG, "Saving to " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800871 }
Makoto Onuki0eed4412016-07-21 11:21:59 -0700872 path.getParentFile().mkdirs();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800873 final AtomicFile file = new AtomicFile(path);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700874 FileOutputStream os = null;
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800875 try {
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700876 os = file.startWrite();
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800877
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700878 saveUserInternalLocked(userId, os, /* forBackup= */ false);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800879
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700880 file.finishWrite(os);
Makoto Onukib08790c2016-06-23 14:05:46 -0700881 } catch (XmlPullParserException | IOException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800882 Slog.e(TAG, "Failed to write to file " + file.getBaseFile(), e);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700883 file.failWrite(os);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800884 }
885 }
886
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700887 private void saveUserInternalLocked(@UserIdInt int userId, OutputStream os,
888 boolean forBackup) throws IOException, XmlPullParserException {
889
890 final BufferedOutputStream bos = new BufferedOutputStream(os);
891
892 // Write to XML
893 XmlSerializer out = new FastXmlSerializer();
894 out.setOutput(bos, StandardCharsets.UTF_8.name());
895 out.startDocument(null, true);
896
Makoto Onukic51b2872016-05-04 15:24:50 -0700897 getUserShortcutsLocked(userId).saveToXml(out, forBackup);
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700898
899 out.endDocument();
900
901 bos.flush();
902 os.flush();
903 }
904
Makoto Onuki41066a62016-03-09 16:18:44 -0800905 static IOException throwForInvalidTag(int depth, String tag) throws IOException {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800906 throw new IOException(String.format("Invalid tag '%s' found at depth %d", tag, depth));
907 }
908
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700909 static void warnForInvalidTag(int depth, String tag) throws IOException {
910 Slog.w(TAG, String.format("Invalid tag '%s' found at depth %d", tag, depth));
911 }
912
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800913 @Nullable
Makoto Onuki31459242016-03-22 11:12:18 -0700914 private ShortcutUser loadUserLocked(@UserIdInt int userId) {
Makoto Onuki0eed4412016-07-21 11:21:59 -0700915 final File path = getUserFile(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800916 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700917 Slog.d(TAG, "Loading from " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800918 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800919 final AtomicFile file = new AtomicFile(path);
920
921 final FileInputStream in;
922 try {
923 in = file.openRead();
924 } catch (FileNotFoundException e) {
925 if (DEBUG) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700926 Slog.d(TAG, "Not found " + path);
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800927 }
928 return null;
929 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800930 try {
Makoto Onukib08790c2016-06-23 14:05:46 -0700931 final ShortcutUser ret = loadUserInternal(userId, in, /* forBackup= */ false);
Makoto Onuki6c1dbd52016-05-02 15:19:32 -0700932 cleanupDanglingBitmapDirectoriesLocked(userId, ret);
933 return ret;
Makoto Onukib08790c2016-06-23 14:05:46 -0700934 } catch (IOException | XmlPullParserException e) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800935 Slog.e(TAG, "Failed to read file " + file.getBaseFile(), e);
936 return null;
937 } finally {
938 IoUtils.closeQuietly(in);
939 }
940 }
941
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700942 private ShortcutUser loadUserInternal(@UserIdInt int userId, InputStream is,
943 boolean fromBackup) throws XmlPullParserException, IOException {
944
945 final BufferedInputStream bis = new BufferedInputStream(is);
946
947 ShortcutUser ret = null;
948 XmlPullParser parser = Xml.newPullParser();
949 parser.setInput(bis, StandardCharsets.UTF_8.name());
950
951 int type;
952 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
953 if (type != XmlPullParser.START_TAG) {
954 continue;
955 }
956 final int depth = parser.getDepth();
957
958 final String tag = parser.getName();
959 if (DEBUG_LOAD) {
960 Slog.d(TAG, String.format("depth=%d type=%d name=%s",
961 depth, type, tag));
962 }
963 if ((depth == 1) && ShortcutUser.TAG_ROOT.equals(tag)) {
964 ret = ShortcutUser.loadFromXml(this, parser, userId, fromBackup);
965 continue;
966 }
967 throwForInvalidTag(depth, tag);
968 }
969 return ret;
970 }
971
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800972 private void scheduleSaveBaseState() {
Makoto Onuki0acbb142016-03-22 17:02:57 -0700973 scheduleSaveInner(UserHandle.USER_NULL); // Special case -- use USER_NULL for base state.
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800974 }
975
Makoto Onuki2d5b4652016-03-11 16:09:54 -0800976 void scheduleSaveUser(@UserIdInt int userId) {
Makoto Onuki0acbb142016-03-22 17:02:57 -0700977 scheduleSaveInner(userId);
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700978 }
979
980 // In order to re-schedule, we need to reuse the same instance, so keep it in final.
981 private final Runnable mSaveDirtyInfoRunner = this::saveDirtyInfo;
982
Makoto Onuki0acbb142016-03-22 17:02:57 -0700983 private void scheduleSaveInner(@UserIdInt int userId) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700984 if (DEBUG) {
985 Slog.d(TAG, "Scheduling to save for " + userId);
986 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -0800987 synchronized (mLock) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -0700988 if (!mDirtyUserIds.contains(userId)) {
989 mDirtyUserIds.add(userId);
990 }
991 }
992 // If already scheduled, remove that and re-schedule in N seconds.
993 mHandler.removeCallbacks(mSaveDirtyInfoRunner);
994 mHandler.postDelayed(mSaveDirtyInfoRunner, mSaveDelayMillis);
995 }
996
997 @VisibleForTesting
998 void saveDirtyInfo() {
999 if (DEBUG) {
1000 Slog.d(TAG, "saveDirtyInfo");
1001 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001002 try {
1003 synchronized (mLock) {
1004 for (int i = mDirtyUserIds.size() - 1; i >= 0; i--) {
1005 final int userId = mDirtyUserIds.get(i);
1006 if (userId == UserHandle.USER_NULL) { // USER_NULL for base state.
1007 saveBaseStateLocked();
1008 } else {
1009 saveUserLocked(userId);
1010 }
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001011 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001012 mDirtyUserIds.clear();
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001013 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07001014 } catch (Exception e) {
1015 wtf("Exception in saveDirtyInfo", e);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001016 }
1017 }
1018
1019 /** Return the last reset time. */
1020 long getLastResetTimeLocked() {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001021 updateTimesLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001022 return mRawLastResetTime;
1023 }
1024
1025 /** Return the next reset time. */
1026 long getNextResetTimeLocked() {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001027 updateTimesLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001028 return mRawLastResetTime + mResetInterval;
1029 }
1030
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001031 static boolean isClockValid(long time) {
1032 return time >= 1420070400; // Thu, 01 Jan 2015 00:00:00 GMT
1033 }
1034
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001035 /**
1036 * Update the last reset time.
1037 */
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001038 private void updateTimesLocked() {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001039
1040 final long now = injectCurrentTimeMillis();
1041
1042 final long prevLastResetTime = mRawLastResetTime;
1043
1044 if (mRawLastResetTime == 0) { // first launch.
1045 // TODO Randomize??
1046 mRawLastResetTime = now;
1047 } else if (now < mRawLastResetTime) {
1048 // Clock rewound.
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001049 if (isClockValid(now)) {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001050 Slog.w(TAG, "Clock rewound");
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001051 // TODO Randomize??
1052 mRawLastResetTime = now;
1053 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001054 } else {
Makoto Onukiaa8b94a2016-03-17 13:14:05 -07001055 if ((mRawLastResetTime + mResetInterval) <= now) {
1056 final long offset = mRawLastResetTime % mResetInterval;
1057 mRawLastResetTime = ((now / mResetInterval) * mResetInterval) + offset;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001058 }
1059 }
1060 if (prevLastResetTime != mRawLastResetTime) {
1061 scheduleSaveBaseState();
1062 }
1063 }
1064
Makoto Onuki02f338e2016-07-29 09:40:40 -07001065 // Requires mLock held, but "Locked" prefix would look weired so we jsut say "L".
1066 protected boolean isUserUnlockedL(@UserIdInt int userId) {
1067 return mUnlockedUsers.get(userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07001068 }
1069
Makoto Onuki02f338e2016-07-29 09:40:40 -07001070 // Requires mLock held, but "Locked" prefix would look weired so we jsut say "L".
1071 void throwIfUserLockedL(@UserIdInt int userId) {
1072 if (!isUserUnlockedL(userId)) {
Makoto Onuki9c850012016-07-26 15:50:50 -07001073 throw new IllegalStateException("User " + userId + " is locked or not running");
1074 }
1075 }
1076
Makoto Onukicdc78f72016-03-21 15:47:52 -07001077 @GuardedBy("mLock")
1078 @NonNull
Makoto Onuki2e210c42016-03-30 08:30:36 -07001079 private boolean isUserLoadedLocked(@UserIdInt int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07001080 return mUsers.get(userId) != null;
1081 }
1082
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001083 /** Return the per-user state. */
1084 @GuardedBy("mLock")
1085 @NonNull
Makoto Onuki31459242016-03-22 11:12:18 -07001086 ShortcutUser getUserShortcutsLocked(@UserIdInt int userId) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001087 if (!isUserUnlockedL(userId)) {
Makoto Onuki9c850012016-07-26 15:50:50 -07001088 wtf("User still locked");
Makoto Onuki9c850012016-07-26 15:50:50 -07001089 }
1090
Makoto Onuki31459242016-03-22 11:12:18 -07001091 ShortcutUser userPackages = mUsers.get(userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001092 if (userPackages == null) {
1093 userPackages = loadUserLocked(userId);
1094 if (userPackages == null) {
Makoto Onukic51b2872016-05-04 15:24:50 -07001095 userPackages = new ShortcutUser(this, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001096 }
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08001097 mUsers.put(userId, userPackages);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001098 }
1099 return userPackages;
1100 }
1101
Makoto Onuki2e210c42016-03-30 08:30:36 -07001102 void forEachLoadedUserLocked(@NonNull Consumer<ShortcutUser> c) {
1103 for (int i = mUsers.size() - 1; i >= 0; i--) {
1104 c.accept(mUsers.valueAt(i));
1105 }
1106 }
1107
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001108 /** Return the per-user per-package state. */
1109 @GuardedBy("mLock")
1110 @NonNull
Makoto Onuki31459242016-03-22 11:12:18 -07001111 ShortcutPackage getPackageShortcutsLocked(
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001112 @NonNull String packageName, @UserIdInt int userId) {
Makoto Onukic51b2872016-05-04 15:24:50 -07001113 return getUserShortcutsLocked(userId).getPackageShortcuts(packageName);
Makoto Onukide667372016-03-15 14:29:20 -07001114 }
1115
1116 @GuardedBy("mLock")
1117 @NonNull
Makoto Onuki2e210c42016-03-30 08:30:36 -07001118 ShortcutLauncher getLauncherShortcutsLocked(
1119 @NonNull String packageName, @UserIdInt int ownerUserId,
1120 @UserIdInt int launcherUserId) {
1121 return getUserShortcutsLocked(ownerUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07001122 .getLauncherShortcuts(packageName, launcherUserId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001123 }
1124
1125 // === Caller validation ===
1126
Makoto Onuki55046222016-03-08 10:49:47 -08001127 void removeIcon(@UserIdInt int userId, ShortcutInfo shortcut) {
1128 if (shortcut.getBitmapPath() != null) {
1129 if (DEBUG) {
1130 Slog.d(TAG, "Removing " + shortcut.getBitmapPath());
1131 }
1132 new File(shortcut.getBitmapPath()).delete();
1133
1134 shortcut.setBitmapPath(null);
Makoto Onuki55046222016-03-08 10:49:47 -08001135 }
Makoto Onukidd097812016-06-29 13:10:09 -07001136 shortcut.setIconResourceId(0);
1137 shortcut.setIconResName(null);
1138 shortcut.clearFlags(ShortcutInfo.FLAG_HAS_ICON_FILE | ShortcutInfo.FLAG_HAS_ICON_RES);
Makoto Onuki55046222016-03-08 10:49:47 -08001139 }
1140
Makoto Onuki0033b2a2016-04-14 17:19:16 -07001141 public void cleanupBitmapsForPackage(@UserIdInt int userId, String packageName) {
1142 final File packagePath = new File(getUserBitmapFilePath(userId), packageName);
1143 if (!packagePath.isDirectory()) {
1144 return;
1145 }
1146 if (!(FileUtils.deleteContents(packagePath) && packagePath.delete())) {
1147 Slog.w(TAG, "Unable to remove directory " + packagePath);
1148 }
1149 }
1150
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001151 private void cleanupDanglingBitmapDirectoriesLocked(
1152 @UserIdInt int userId, @NonNull ShortcutUser user) {
1153 if (DEBUG) {
1154 Slog.d(TAG, "cleanupDanglingBitmaps: userId=" + userId);
1155 }
1156 final long start = injectElapsedRealtime();
1157
1158 final File bitmapDir = getUserBitmapFilePath(userId);
1159 final File[] children = bitmapDir.listFiles();
1160 if (children == null) {
1161 return;
1162 }
1163 for (File child : children) {
1164 if (!child.isDirectory()) {
1165 continue;
1166 }
1167 final String packageName = child.getName();
1168 if (DEBUG) {
1169 Slog.d(TAG, "cleanupDanglingBitmaps: Found directory=" + packageName);
1170 }
1171 if (!user.hasPackage(packageName)) {
1172 if (DEBUG) {
1173 Slog.d(TAG, "Removing dangling bitmap directory: " + packageName);
1174 }
1175 cleanupBitmapsForPackage(userId, packageName);
1176 } else {
1177 cleanupDanglingBitmapFilesLocked(userId, user, packageName, child);
1178 }
1179 }
1180 logDurationStat(Stats.CLEANUP_DANGLING_BITMAPS, start);
1181 }
1182
1183 private void cleanupDanglingBitmapFilesLocked(@UserIdInt int userId, @NonNull ShortcutUser user,
1184 @NonNull String packageName, @NonNull File path) {
1185 final ArraySet<String> usedFiles =
Makoto Onukic51b2872016-05-04 15:24:50 -07001186 user.getPackageShortcuts(packageName).getUsedBitmapFiles();
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07001187
1188 for (File child : path.listFiles()) {
1189 if (!child.isFile()) {
1190 continue;
1191 }
1192 final String name = child.getName();
1193 if (!usedFiles.contains(name)) {
1194 if (DEBUG) {
1195 Slog.d(TAG, "Removing dangling bitmap file: " + child.getAbsolutePath());
1196 }
1197 child.delete();
1198 }
1199 }
1200 }
1201
Makoto Onuki55046222016-03-08 10:49:47 -08001202 @VisibleForTesting
1203 static class FileOutputStreamWithPath extends FileOutputStream {
1204 private final File mFile;
1205
1206 public FileOutputStreamWithPath(File file) throws FileNotFoundException {
1207 super(file);
1208 mFile = file;
1209 }
1210
1211 public File getFile() {
1212 return mFile;
1213 }
1214 }
1215
1216 /**
1217 * Build the cached bitmap filename for a shortcut icon.
1218 *
1219 * The filename will be based on the ID, except certain characters will be escaped.
1220 */
1221 @VisibleForTesting
1222 FileOutputStreamWithPath openIconFileForWrite(@UserIdInt int userId, ShortcutInfo shortcut)
1223 throws IOException {
1224 final File packagePath = new File(getUserBitmapFilePath(userId),
Makoto Onuki22fcc682016-05-17 14:52:19 -07001225 shortcut.getPackage());
Makoto Onuki55046222016-03-08 10:49:47 -08001226 if (!packagePath.isDirectory()) {
1227 packagePath.mkdirs();
1228 if (!packagePath.isDirectory()) {
1229 throw new IOException("Unable to create directory " + packagePath);
1230 }
1231 SELinux.restorecon(packagePath);
1232 }
1233
1234 final String baseName = String.valueOf(injectCurrentTimeMillis());
Makoto Onukib08790c2016-06-23 14:05:46 -07001235 for (int suffix = 0; ; suffix++) {
Makoto Onuki55046222016-03-08 10:49:47 -08001236 final String filename = (suffix == 0 ? baseName : baseName + "_" + suffix) + ".png";
1237 final File file = new File(packagePath, filename);
1238 if (!file.exists()) {
1239 if (DEBUG) {
1240 Slog.d(TAG, "Saving icon to " + file.getAbsolutePath());
1241 }
1242 return new FileOutputStreamWithPath(file);
1243 }
1244 }
1245 }
1246
1247 void saveIconAndFixUpShortcut(@UserIdInt int userId, ShortcutInfo shortcut) {
1248 if (shortcut.hasIconFile() || shortcut.hasIconResource()) {
1249 return;
1250 }
1251
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001252 final long token = injectClearCallingIdentity();
Makoto Onuki55046222016-03-08 10:49:47 -08001253 try {
1254 // Clear icon info on the shortcut.
Makoto Onukidd097812016-06-29 13:10:09 -07001255 removeIcon(userId, shortcut);
Makoto Onuki55046222016-03-08 10:49:47 -08001256
1257 final Icon icon = shortcut.getIcon();
1258 if (icon == null) {
1259 return; // has no icon
1260 }
1261
Makoto Onukiabe84422016-04-07 09:41:19 -07001262 Bitmap bitmap;
Makoto Onuki55046222016-03-08 10:49:47 -08001263 try {
1264 switch (icon.getType()) {
1265 case Icon.TYPE_RESOURCE: {
1266 injectValidateIconResPackage(shortcut, icon);
1267
1268 shortcut.setIconResourceId(icon.getResId());
1269 shortcut.addFlags(ShortcutInfo.FLAG_HAS_ICON_RES);
1270 return;
1271 }
1272 case Icon.TYPE_BITMAP: {
Makoto Onukiabe84422016-04-07 09:41:19 -07001273 bitmap = icon.getBitmap(); // Don't recycle in this case.
Makoto Onuki55046222016-03-08 10:49:47 -08001274 break;
1275 }
Makoto Onuki55046222016-03-08 10:49:47 -08001276 default:
1277 // This shouldn't happen because we've already validated the icon, but
1278 // just in case.
1279 throw ShortcutInfo.getInvalidIconException();
1280 }
1281 if (bitmap == null) {
1282 Slog.e(TAG, "Null bitmap detected");
1283 return;
1284 }
1285 // Shrink and write to the file.
1286 File path = null;
1287 try {
1288 final FileOutputStreamWithPath out = openIconFileForWrite(userId, shortcut);
1289 try {
1290 path = out.getFile();
1291
Makoto Onukiabe84422016-04-07 09:41:19 -07001292 Bitmap shrunk = shrinkBitmap(bitmap, mMaxIconDimension);
1293 try {
1294 shrunk.compress(mIconPersistFormat, mIconPersistQuality, out);
1295 } finally {
1296 if (bitmap != shrunk) {
1297 shrunk.recycle();
1298 }
1299 }
Makoto Onuki55046222016-03-08 10:49:47 -08001300
1301 shortcut.setBitmapPath(out.getFile().getAbsolutePath());
1302 shortcut.addFlags(ShortcutInfo.FLAG_HAS_ICON_FILE);
1303 } finally {
1304 IoUtils.closeQuietly(out);
1305 }
Makoto Onukib08790c2016-06-23 14:05:46 -07001306 } catch (IOException | RuntimeException e) {
Makoto Onuki55046222016-03-08 10:49:47 -08001307 // STOPSHIP Change wtf to e
1308 Slog.wtf(ShortcutService.TAG, "Unable to write bitmap to file", e);
1309 if (path != null && path.exists()) {
1310 path.delete();
1311 }
1312 }
1313 } finally {
Makoto Onuki55046222016-03-08 10:49:47 -08001314 // Once saved, we won't use the original icon information, so null it out.
1315 shortcut.clearIcon();
1316 }
1317 } finally {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001318 injectRestoreCallingIdentity(token);
Makoto Onuki55046222016-03-08 10:49:47 -08001319 }
1320 }
1321
1322 // Unfortunately we can't do this check in unit tests because we fake creator package names,
1323 // so override in unit tests.
1324 // TODO CTS this case.
1325 void injectValidateIconResPackage(ShortcutInfo shortcut, Icon icon) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07001326 if (!shortcut.getPackage().equals(icon.getResPackage())) {
Makoto Onuki55046222016-03-08 10:49:47 -08001327 throw new IllegalArgumentException(
1328 "Icon resource must reside in shortcut owner package");
1329 }
1330 }
1331
1332 @VisibleForTesting
1333 static Bitmap shrinkBitmap(Bitmap in, int maxSize) {
1334 // Original width/height.
1335 final int ow = in.getWidth();
1336 final int oh = in.getHeight();
1337 if ((ow <= maxSize) && (oh <= maxSize)) {
1338 if (DEBUG) {
1339 Slog.d(TAG, String.format("Icon size %dx%d, no need to shrink", ow, oh));
1340 }
1341 return in;
1342 }
1343 final int longerDimension = Math.max(ow, oh);
1344
1345 // New width and height.
1346 final int nw = ow * maxSize / longerDimension;
1347 final int nh = oh * maxSize / longerDimension;
1348 if (DEBUG) {
1349 Slog.d(TAG, String.format("Icon size %dx%d, shrinking to %dx%d",
1350 ow, oh, nw, nh));
1351 }
1352
1353 final Bitmap scaledBitmap = Bitmap.createBitmap(nw, nh, Bitmap.Config.ARGB_8888);
1354 final Canvas c = new Canvas(scaledBitmap);
1355
1356 final RectF dst = new RectF(0, 0, nw, nh);
1357
1358 c.drawBitmap(in, /*src=*/ null, dst, /* paint =*/ null);
1359
Makoto Onuki55046222016-03-08 10:49:47 -08001360 return scaledBitmap;
1361 }
1362
Makoto Onuki157b1622016-06-02 16:13:10 -07001363 /**
1364 * For a shortcut, update all resource names from resource IDs, and also update all
1365 * resource-based strings.
1366 */
1367 void fixUpShortcutResourceNamesAndValues(ShortcutInfo si) {
1368 final Resources publisherRes = injectGetResourcesForApplicationAsUser(
1369 si.getPackage(), si.getUserId());
1370 if (publisherRes != null) {
1371 final long start = injectElapsedRealtime();
1372 try {
1373 si.lookupAndFillInResourceNames(publisherRes);
1374 } finally {
1375 logDurationStat(Stats.RESOURCE_NAME_LOOKUP, start);
1376 }
1377 si.resolveResourceStrings(publisherRes);
1378 }
1379 }
1380
Makoto Onuki55046222016-03-08 10:49:47 -08001381 // === Caller validation ===
1382
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001383 private boolean isCallerSystem() {
1384 final int callingUid = injectBinderCallingUid();
Makoto Onukib08790c2016-06-23 14:05:46 -07001385 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001386 }
1387
1388 private boolean isCallerShell() {
1389 final int callingUid = injectBinderCallingUid();
1390 return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
1391 }
1392
1393 private void enforceSystemOrShell() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001394 if (!(isCallerSystem() || isCallerShell())) {
1395 throw new SecurityException("Caller must be system or shell");
1396 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001397 }
1398
1399 private void enforceShell() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001400 if (!isCallerShell()) {
1401 throw new SecurityException("Caller must be shell");
1402 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001403 }
1404
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001405 private void enforceSystem() {
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07001406 if (!isCallerSystem()) {
1407 throw new SecurityException("Caller must be system");
1408 }
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001409 }
1410
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001411 private void enforceResetThrottlingPermission() {
1412 if (isCallerSystem()) {
1413 return;
1414 }
Makoto Onuki76269922016-07-15 14:58:54 -07001415 enforceCallingOrSelfPermission(
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001416 android.Manifest.permission.RESET_SHORTCUT_MANAGER_THROTTLING, null);
1417 }
1418
Makoto Onuki76269922016-07-15 14:58:54 -07001419 private void enforceCallingOrSelfPermission(
1420 @NonNull String permission, @Nullable String message) {
1421 if (isCallerSystem()) {
1422 return;
1423 }
1424 injectEnforceCallingPermission(permission, message);
1425 }
1426
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001427 /**
1428 * Somehow overriding ServiceContext.enforceCallingPermission() in the unit tests would confuse
1429 * mockito. So instead we extracted it here and override it in the tests.
1430 */
1431 @VisibleForTesting
1432 void injectEnforceCallingPermission(
1433 @NonNull String permission, @Nullable String message) {
1434 mContext.enforceCallingPermission(permission, message);
1435 }
1436
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001437 private void verifyCaller(@NonNull String packageName, @UserIdInt int userId) {
1438 Preconditions.checkStringNotEmpty(packageName, "packageName");
1439
1440 if (isCallerSystem()) {
1441 return; // no check
1442 }
1443
1444 final int callingUid = injectBinderCallingUid();
1445
1446 // Otherwise, make sure the arguments are valid.
1447 if (UserHandle.getUserId(callingUid) != userId) {
1448 throw new SecurityException("Invalid user-ID");
1449 }
Makoto Onuki55046222016-03-08 10:49:47 -08001450 if (injectGetPackageUid(packageName, userId) == injectBinderCallingUid()) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001451 return; // Caller is valid.
1452 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07001453 throw new SecurityException("Calling package name mismatch");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001454 }
1455
Makoto Onuki157b1622016-06-02 16:13:10 -07001456 // Overridden in unit tests to execute r synchronously.
1457 void injectPostToHandler(Runnable r) {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001458 mHandler.post(r);
1459 }
1460
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001461 /**
Makoto Onuki7001a612016-05-27 13:24:28 -07001462 * @throws IllegalArgumentException if {@code numShortcuts} is bigger than
Makoto Onukib08790c2016-06-23 14:05:46 -07001463 * {@link #getMaxActivityShortcuts()}.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001464 */
Makoto Onuki7001a612016-05-27 13:24:28 -07001465 void enforceMaxActivityShortcuts(int numShortcuts) {
Makoto Onukib5a012f2016-06-21 11:13:53 -07001466 if (numShortcuts > mMaxShortcuts) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001467 throw new IllegalArgumentException("Max number of dynamic shortcuts exceeded");
1468 }
1469 }
1470
1471 /**
Makoto Onuki7001a612016-05-27 13:24:28 -07001472 * Return the max number of dynamic + manifest shortcuts for each launcher icon.
1473 */
1474 int getMaxActivityShortcuts() {
Makoto Onukib5a012f2016-06-21 11:13:53 -07001475 return mMaxShortcuts;
Makoto Onuki7001a612016-05-27 13:24:28 -07001476 }
1477
1478 /**
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001479 * - Sends a notification to LauncherApps
1480 * - Write to file
1481 */
Makoto Onuki39686e82016-04-13 18:03:00 -07001482 void packageShortcutsChanged(@NonNull String packageName, @UserIdInt int userId) {
1483 if (DEBUG) {
1484 Slog.d(TAG, String.format(
1485 "Shortcut changes: package=%s, user=%d", packageName, userId));
1486 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001487 notifyListeners(packageName, userId);
1488 scheduleSaveUser(userId);
1489 }
1490
1491 private void notifyListeners(@NonNull String packageName, @UserIdInt int userId) {
Makoto Onuki157b1622016-06-02 16:13:10 -07001492 injectPostToHandler(() -> {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001493 try {
1494 final ArrayList<ShortcutChangeListener> copy;
1495 synchronized (mLock) {
1496 if (!isUserUnlockedL(userId)) {
1497 return;
1498 }
1499
1500 copy = new ArrayList<>(mListeners);
1501 }
1502 // Note onShortcutChanged() needs to be called with the system service permissions.
1503 for (int i = copy.size() - 1; i >= 0; i--) {
1504 copy.get(i).onShortcutChanged(packageName, userId);
1505 }
1506 } catch (Exception ignore) {
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07001507 }
1508 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001509 }
1510
1511 /**
1512 * Clean up / validate an incoming shortcut.
1513 * - Make sure all mandatory fields are set.
1514 * - Make sure the intent's extras are persistable, and them to set
Makoto Onuki0eed4412016-07-21 11:21:59 -07001515 * {@link ShortcutInfo#mIntentPersistableExtrases}. Also clear its extras.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001516 * - Clear flags.
Makoto Onuki55046222016-03-08 10:49:47 -08001517 *
1518 * TODO Detailed unit tests
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001519 */
Makoto Onuki55046222016-03-08 10:49:47 -08001520 private void fixUpIncomingShortcutInfo(@NonNull ShortcutInfo shortcut, boolean forUpdate) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001521 Preconditions.checkNotNull(shortcut, "Null shortcut detected");
Makoto Onuki22fcc682016-05-17 14:52:19 -07001522 if (shortcut.getActivity() != null) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001523 Preconditions.checkState(
Makoto Onuki22fcc682016-05-17 14:52:19 -07001524 shortcut.getPackage().equals(shortcut.getActivity().getPackageName()),
Makoto Onukib08790c2016-06-23 14:05:46 -07001525 "Cannot publish shortcut: activity " + shortcut.getActivity() + " does not"
1526 + " belong to package " + shortcut.getPackage());
Makoto Onuki13260b6ff2016-07-13 18:03:13 -07001527 Preconditions.checkState(
1528 injectIsMainActivity(shortcut.getActivity(), shortcut.getUserId()),
1529 "Cannot publish shortcut: activity " + shortcut.getActivity() + " is not"
1530 + " main activity");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001531 }
1532
Makoto Onuki55046222016-03-08 10:49:47 -08001533 if (!forUpdate) {
1534 shortcut.enforceMandatoryFields();
Makoto Onukib08790c2016-06-23 14:05:46 -07001535 Preconditions.checkArgument(
1536 injectIsMainActivity(shortcut.getActivity(), shortcut.getUserId()),
1537 "Cannot publish shortcut: " + shortcut.getActivity() + " is not main activity");
Makoto Onuki55046222016-03-08 10:49:47 -08001538 }
1539 if (shortcut.getIcon() != null) {
1540 ShortcutInfo.validateIcon(shortcut.getIcon());
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001541 }
1542
Makoto Onukide667372016-03-15 14:29:20 -07001543 shortcut.replaceFlags(0);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001544 }
1545
Makoto Onukib08790c2016-06-23 14:05:46 -07001546 /**
1547 * When a shortcut has no target activity, set the default one from the package.
1548 */
1549 private void fillInDefaultActivity(List<ShortcutInfo> shortcuts) {
1550
1551 ComponentName defaultActivity = null;
1552 for (int i = shortcuts.size() - 1; i >= 0; i--) {
1553 final ShortcutInfo si = shortcuts.get(i);
1554 if (si.getActivity() == null) {
1555 if (defaultActivity == null) {
1556 defaultActivity = injectGetDefaultMainActivity(
1557 si.getPackage(), si.getUserId());
1558 Preconditions.checkState(defaultActivity != null,
1559 "Launcher activity not found for package " + si.getPackage());
1560 }
1561 si.setActivity(defaultActivity);
1562 }
1563 }
1564 }
1565
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001566 private void assignImplicitRanks(List<ShortcutInfo> shortcuts) {
1567 for (int i = shortcuts.size() - 1; i >= 0; i--) {
1568 shortcuts.get(i).setImplicitRank(i);
1569 }
1570 }
1571
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001572 // === APIs ===
1573
1574 @Override
1575 public boolean setDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1576 @UserIdInt int userId) {
1577 verifyCaller(packageName, userId);
1578
1579 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
1580 final int size = newShortcuts.size();
1581
1582 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001583 throwIfUserLockedL(userId);
1584
Makoto Onuki31459242016-03-22 11:12:18 -07001585 final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07001586 ps.getUser().onCalledByPublisher(packageName);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001587
Makoto Onuki22fcc682016-05-17 14:52:19 -07001588 ps.ensureImmutableShortcutsNotIncluded(newShortcuts);
1589
Makoto Onukib08790c2016-06-23 14:05:46 -07001590 fillInDefaultActivity(newShortcuts);
1591
Makoto Onuki7001a612016-05-27 13:24:28 -07001592 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_SET);
1593
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001594 // Throttling.
Makoto Onukic51b2872016-05-04 15:24:50 -07001595 if (!ps.tryApiCall()) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001596 return false;
1597 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001598
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001599 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1600 ps.clearAllImplicitRanks();
1601 assignImplicitRanks(newShortcuts);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001602
Makoto Onukidf6da042016-06-16 09:51:40 -07001603 for (int i = 0; i < size; i++) {
1604 fixUpIncomingShortcutInfo(newShortcuts.get(i), /* forUpdate= */ false);
1605 }
1606
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001607 // First, remove all un-pinned; dynamic shortcuts
Makoto Onukic51b2872016-05-04 15:24:50 -07001608 ps.deleteAllDynamicShortcuts();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001609
1610 // Then, add/update all. We need to make sure to take over "pinned" flag.
1611 for (int i = 0; i < size; i++) {
1612 final ShortcutInfo newShortcut = newShortcuts.get(i);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001613 ps.addOrUpdateDynamicShortcut(newShortcut);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001614 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001615
1616 // Lastly, adjust the ranks.
1617 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001618 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001619 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001620
1621 verifyStates();
1622
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001623 return true;
1624 }
1625
1626 @Override
1627 public boolean updateShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1628 @UserIdInt int userId) {
1629 verifyCaller(packageName, userId);
1630
1631 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
Makoto Onuki55046222016-03-08 10:49:47 -08001632 final int size = newShortcuts.size();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001633
1634 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001635 throwIfUserLockedL(userId);
1636
Makoto Onuki31459242016-03-22 11:12:18 -07001637 final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07001638 ps.getUser().onCalledByPublisher(packageName);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001639
Makoto Onuki22fcc682016-05-17 14:52:19 -07001640 ps.ensureImmutableShortcutsNotIncluded(newShortcuts);
1641
Makoto Onukib08790c2016-06-23 14:05:46 -07001642 // For update, don't fill in the default activity. Having null activity means
1643 // "don't update the activity" here.
1644
Makoto Onuki7001a612016-05-27 13:24:28 -07001645 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_UPDATE);
1646
Makoto Onuki55046222016-03-08 10:49:47 -08001647 // Throttling.
Makoto Onukic51b2872016-05-04 15:24:50 -07001648 if (!ps.tryApiCall()) {
Makoto Onuki55046222016-03-08 10:49:47 -08001649 return false;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001650 }
1651
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001652 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1653 ps.clearAllImplicitRanks();
1654 assignImplicitRanks(newShortcuts);
1655
Makoto Onuki55046222016-03-08 10:49:47 -08001656 for (int i = 0; i < size; i++) {
1657 final ShortcutInfo source = newShortcuts.get(i);
1658 fixUpIncomingShortcutInfo(source, /* forUpdate= */ true);
1659
1660 final ShortcutInfo target = ps.findShortcutById(source.getId());
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001661 if (target == null) {
1662 continue;
1663 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07001664
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001665 if (target.isEnabled() != source.isEnabled()) {
1666 Slog.w(TAG,
1667 "ShortcutInfo.enabled cannot be changed with updateShortcuts()");
1668 }
Makoto Onuki55046222016-03-08 10:49:47 -08001669
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001670 // When updating the rank, we need to insert between existing ranks, so set
1671 // this setRankChanged, and also copy the implicit rank fo adjustRanks().
1672 if (source.hasRank()) {
1673 target.setRankChanged();
1674 target.setImplicitRank(source.getImplicitRank());
1675 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07001676
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001677 final boolean replacingIcon = (source.getIcon() != null);
1678 if (replacingIcon) {
1679 removeIcon(userId, target);
1680 }
Makoto Onuki55046222016-03-08 10:49:47 -08001681
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001682 // Note copyNonNullFieldsFrom() does the "updatable with?" check too.
1683 target.copyNonNullFieldsFrom(source);
1684 target.setTimestamp(injectCurrentTimeMillis());
1685
1686 if (replacingIcon) {
1687 saveIconAndFixUpShortcut(userId, target);
1688 }
1689
1690 // When we're updating any resource related fields, re-extract the res names and
1691 // the values.
1692 if (replacingIcon || source.hasStringResources()) {
1693 fixUpShortcutResourceNamesAndValues(target);
Makoto Onuki55046222016-03-08 10:49:47 -08001694 }
1695 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001696
1697 // Lastly, adjust the ranks.
1698 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001699 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001700 packageShortcutsChanged(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001701
Makoto Onuki7001a612016-05-27 13:24:28 -07001702 verifyStates();
1703
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001704 return true;
1705 }
1706
1707 @Override
Makoto Onukib6d35232016-04-04 15:57:17 -07001708 public boolean addDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001709 @UserIdInt int userId) {
1710 verifyCaller(packageName, userId);
1711
Makoto Onukib6d35232016-04-04 15:57:17 -07001712 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
1713 final int size = newShortcuts.size();
1714
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001715 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001716 throwIfUserLockedL(userId);
1717
Makoto Onuki31459242016-03-22 11:12:18 -07001718 final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07001719 ps.getUser().onCalledByPublisher(packageName);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001720
Makoto Onuki22fcc682016-05-17 14:52:19 -07001721 ps.ensureImmutableShortcutsNotIncluded(newShortcuts);
1722
Makoto Onukib08790c2016-06-23 14:05:46 -07001723 fillInDefaultActivity(newShortcuts);
1724
Makoto Onuki7001a612016-05-27 13:24:28 -07001725 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_ADD);
1726
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001727 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1728 ps.clearAllImplicitRanks();
1729 assignImplicitRanks(newShortcuts);
1730
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001731 // Throttling.
Makoto Onukic51b2872016-05-04 15:24:50 -07001732 if (!ps.tryApiCall()) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001733 return false;
1734 }
Makoto Onukib6d35232016-04-04 15:57:17 -07001735 for (int i = 0; i < size; i++) {
1736 final ShortcutInfo newShortcut = newShortcuts.get(i);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001737
Makoto Onukib6d35232016-04-04 15:57:17 -07001738 // Validate the shortcut.
1739 fixUpIncomingShortcutInfo(newShortcut, /* forUpdate= */ false);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001740
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001741 // When ranks are changing, we need to insert between ranks, so set the
1742 // "rank changed" flag.
1743 newShortcut.setRankChanged();
1744
Makoto Onukib6d35232016-04-04 15:57:17 -07001745 // Add it.
Makoto Onuki22fcc682016-05-17 14:52:19 -07001746 ps.addOrUpdateDynamicShortcut(newShortcut);
Makoto Onukib6d35232016-04-04 15:57:17 -07001747 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001748
1749 // Lastly, adjust the ranks.
1750 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001751 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001752 packageShortcutsChanged(packageName, userId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001753
Makoto Onuki7001a612016-05-27 13:24:28 -07001754 verifyStates();
1755
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001756 return true;
1757 }
1758
1759 @Override
Makoto Onuki20c95f82016-05-11 16:51:01 -07001760 public void disableShortcuts(String packageName, List shortcutIds,
Makoto Onukid6880792016-06-29 13:37:43 -07001761 CharSequence disabledMessage, int disabledMessageResId, @UserIdInt int userId) {
Makoto Onuki20c95f82016-05-11 16:51:01 -07001762 verifyCaller(packageName, userId);
1763 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
1764
1765 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001766 throwIfUserLockedL(userId);
1767
Makoto Onuki22fcc682016-05-17 14:52:19 -07001768 final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07001769 ps.getUser().onCalledByPublisher(packageName);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001770
1771 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds);
1772
Makoto Onukid6880792016-06-29 13:37:43 -07001773 final String disabledMessageString =
1774 (disabledMessage == null) ? null : disabledMessage.toString();
1775
Makoto Onuki22fcc682016-05-17 14:52:19 -07001776 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
1777 ps.disableWithId(Preconditions.checkStringNotEmpty((String) shortcutIds.get(i)),
Makoto Onukid6880792016-06-29 13:37:43 -07001778 disabledMessageString, disabledMessageResId,
Makoto Onuki22fcc682016-05-17 14:52:19 -07001779 /* overrideImmutable=*/ false);
1780 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001781
1782 // We may have removed dynamic shortcuts which may have left a gap, so adjust the ranks.
1783 ps.adjustRanks();
Makoto Onuki22fcc682016-05-17 14:52:19 -07001784 }
1785 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001786
1787 verifyStates();
Makoto Onuki22fcc682016-05-17 14:52:19 -07001788 }
1789
1790 @Override
1791 public void enableShortcuts(String packageName, List shortcutIds, @UserIdInt int userId) {
1792 verifyCaller(packageName, userId);
1793 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
1794
1795 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001796 throwIfUserLockedL(userId);
1797
Makoto Onuki22fcc682016-05-17 14:52:19 -07001798 final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07001799 ps.getUser().onCalledByPublisher(packageName);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001800
1801 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds);
1802
1803 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
1804 ps.enableWithId((String) shortcutIds.get(i));
1805 }
Makoto Onuki20c95f82016-05-11 16:51:01 -07001806 }
1807 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001808
1809 verifyStates();
Makoto Onuki20c95f82016-05-11 16:51:01 -07001810 }
1811
1812 @Override
Makoto Onukib6d35232016-04-04 15:57:17 -07001813 public void removeDynamicShortcuts(String packageName, List shortcutIds,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001814 @UserIdInt int userId) {
1815 verifyCaller(packageName, userId);
Makoto Onukib6d35232016-04-04 15:57:17 -07001816 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001817
1818 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001819 throwIfUserLockedL(userId);
1820
Makoto Onuki22fcc682016-05-17 14:52:19 -07001821 final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07001822 ps.getUser().onCalledByPublisher(packageName);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001823
1824 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds);
1825
Makoto Onukib6d35232016-04-04 15:57:17 -07001826 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07001827 ps.deleteDynamicWithId(
Makoto Onukib6d35232016-04-04 15:57:17 -07001828 Preconditions.checkStringNotEmpty((String) shortcutIds.get(i)));
1829 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001830
1831 // We may have removed dynamic shortcuts which may have left a gap, so adjust the ranks.
1832 ps.adjustRanks();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001833 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001834 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001835
1836 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001837 }
1838
1839 @Override
Makoto Onukib6d35232016-04-04 15:57:17 -07001840 public void removeAllDynamicShortcuts(String packageName, @UserIdInt int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001841 verifyCaller(packageName, userId);
1842
1843 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001844 throwIfUserLockedL(userId);
1845
Makoto Onuki4e6cef42016-07-13 16:14:01 -07001846 final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
1847 ps.getUser().onCalledByPublisher(packageName);
1848 ps.deleteAllDynamicShortcuts();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001849 }
Makoto Onuki39686e82016-04-13 18:03:00 -07001850 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07001851
1852 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001853 }
1854
1855 @Override
1856 public ParceledListSlice<ShortcutInfo> getDynamicShortcuts(String packageName,
1857 @UserIdInt int userId) {
1858 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07001859
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001860 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001861 throwIfUserLockedL(userId);
1862
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001863 return getShortcutsWithQueryLocked(
1864 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
1865 ShortcutInfo::isDynamic);
1866 }
1867 }
1868
1869 @Override
Makoto Onuki22fcc682016-05-17 14:52:19 -07001870 public ParceledListSlice<ShortcutInfo> getManifestShortcuts(String packageName,
1871 @UserIdInt int userId) {
1872 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07001873
Makoto Onuki22fcc682016-05-17 14:52:19 -07001874 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001875 throwIfUserLockedL(userId);
1876
Makoto Onuki22fcc682016-05-17 14:52:19 -07001877 return getShortcutsWithQueryLocked(
1878 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
1879 ShortcutInfo::isManifestShortcut);
1880 }
1881 }
1882
1883 @Override
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001884 public ParceledListSlice<ShortcutInfo> getPinnedShortcuts(String packageName,
1885 @UserIdInt int userId) {
1886 verifyCaller(packageName, userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07001887
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001888 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001889 throwIfUserLockedL(userId);
1890
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001891 return getShortcutsWithQueryLocked(
1892 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
1893 ShortcutInfo::isPinned);
1894 }
1895 }
1896
1897 private ParceledListSlice<ShortcutInfo> getShortcutsWithQueryLocked(@NonNull String packageName,
1898 @UserIdInt int userId, int cloneFlags, @NonNull Predicate<ShortcutInfo> query) {
1899
1900 final ArrayList<ShortcutInfo> ret = new ArrayList<>();
1901
Makoto Onuki4e6cef42016-07-13 16:14:01 -07001902 final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
1903 ps.getUser().onCalledByPublisher(packageName);
1904 ps.findAll(ret, query, cloneFlags);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001905
1906 return new ParceledListSlice<>(ret);
1907 }
1908
1909 @Override
Makoto Onukid6880792016-06-29 13:37:43 -07001910 public int getMaxShortcutCountPerActivity(String packageName, @UserIdInt int userId)
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001911 throws RemoteException {
1912 verifyCaller(packageName, userId);
1913
Makoto Onukib5a012f2016-06-21 11:13:53 -07001914 return mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001915 }
1916
1917 @Override
1918 public int getRemainingCallCount(String packageName, @UserIdInt int userId) {
1919 verifyCaller(packageName, userId);
1920
1921 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001922 throwIfUserLockedL(userId);
1923
Makoto Onuki4e6cef42016-07-13 16:14:01 -07001924 final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
1925 ps.getUser().onCalledByPublisher(packageName);
1926 return mMaxUpdatesPerInterval - ps.getApiCallCount();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001927 }
1928 }
1929
1930 @Override
1931 public long getRateLimitResetTime(String packageName, @UserIdInt int userId) {
1932 verifyCaller(packageName, userId);
1933
1934 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001935 throwIfUserLockedL(userId);
1936
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001937 return getNextResetTimeLocked();
1938 }
1939 }
1940
Makoto Onuki55046222016-03-08 10:49:47 -08001941 @Override
Makoto Onuki20c95f82016-05-11 16:51:01 -07001942 public int getIconMaxDimensions(String packageName, int userId) {
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07001943 verifyCaller(packageName, userId);
1944
Makoto Onuki55046222016-03-08 10:49:47 -08001945 synchronized (mLock) {
1946 return mMaxIconDimension;
1947 }
1948 }
1949
Makoto Onuki20c95f82016-05-11 16:51:01 -07001950 @Override
1951 public void reportShortcutUsed(String packageName, String shortcutId, int userId) {
1952 verifyCaller(packageName, userId);
1953
Makoto Onukiac042502016-05-20 16:39:42 -07001954 Preconditions.checkNotNull(shortcutId);
1955
1956 if (DEBUG) {
1957 Slog.d(TAG, String.format("reportShortcutUsed: Shortcut %s package %s used on user %d",
1958 shortcutId, packageName, userId));
1959 }
1960
1961 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001962 throwIfUserLockedL(userId);
1963
Makoto Onukiac042502016-05-20 16:39:42 -07001964 final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
Makoto Onuki4e6cef42016-07-13 16:14:01 -07001965 ps.getUser().onCalledByPublisher(packageName);
1966
Makoto Onukiac042502016-05-20 16:39:42 -07001967 if (ps.findShortcutById(shortcutId) == null) {
1968 Log.w(TAG, String.format("reportShortcutUsed: package %s doesn't have shortcut %s",
1969 packageName, shortcutId));
1970 return;
1971 }
1972 }
1973
1974 final long token = injectClearCallingIdentity();
1975 try {
1976 mUsageStatsManagerInternal.reportShortcutUsage(packageName, shortcutId, userId);
1977 } finally {
1978 injectRestoreCallingIdentity(token);
1979 }
Makoto Onuki20c95f82016-05-11 16:51:01 -07001980 }
1981
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001982 /**
Makoto Onukib08790c2016-06-23 14:05:46 -07001983 * Reset all throttling, for developer options and command line. Only system/shell can call
1984 * it.
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001985 */
1986 @Override
1987 public void resetThrottling() {
1988 enforceSystemOrShell();
1989
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001990 resetThrottlingInner(getCallingUserId());
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001991 }
1992
Makoto Onuki4554d0e2016-03-14 15:51:41 -07001993 void resetThrottlingInner(@UserIdInt int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08001994 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07001995 if (!isUserUnlockedL(userId)) {
1996 Log.w(TAG, "User " + userId + " is locked or not running");
1997 return;
1998 }
1999
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002000 getUserShortcutsLocked(userId).resetThrottling();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002001 }
Makoto Onuki4554d0e2016-03-14 15:51:41 -07002002 scheduleSaveUser(userId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002003 Slog.i(TAG, "ShortcutManager: throttling counter reset for user " + userId);
2004 }
2005
2006 void resetAllThrottlingInner() {
2007 synchronized (mLock) {
2008 mRawLastResetTime = injectCurrentTimeMillis();
2009 }
2010 scheduleSaveBaseState();
2011 Slog.i(TAG, "ShortcutManager: throttling counter reset for all users");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002012 }
2013
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002014 @Override
2015 public void onApplicationActive(String packageName, int userId) {
2016 if (DEBUG) {
2017 Slog.d(TAG, "onApplicationActive: package=" + packageName + " userid=" + userId);
2018 }
2019 enforceResetThrottlingPermission();
Makoto Onuki02f338e2016-07-29 09:40:40 -07002020
2021 synchronized (mLock) {
2022 if (!isUserUnlockedL(userId)) {
2023 // This is called by system UI, so no need to throw. Just ignore.
2024 return;
2025 }
2026
2027 getPackageShortcutsLocked(packageName, userId)
2028 .resetRateLimitingForCommandLineNoSaving();
2029 saveUserLocked(userId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002030 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002031 }
2032
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002033 // We override this method in unit tests to do a simpler check.
2034 boolean hasShortcutHostPermission(@NonNull String callingPackage, int userId) {
Makoto Onuki10305202016-07-14 18:14:08 -07002035 final long start = injectElapsedRealtime();
2036 try {
2037 return hasShortcutHostPermissionInner(callingPackage, userId);
2038 } finally {
2039 logDurationStat(Stats.LAUNCHER_PERMISSION_CHECK, start);
2040 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002041 }
2042
2043 // This method is extracted so we can directly call this method from unit tests,
2044 // even when hasShortcutPermission() is overridden.
2045 @VisibleForTesting
2046 boolean hasShortcutHostPermissionInner(@NonNull String callingPackage, int userId) {
2047 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002048 throwIfUserLockedL(userId);
2049
Makoto Onuki31459242016-03-22 11:12:18 -07002050 final ShortcutUser user = getUserShortcutsLocked(userId);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002051
Makoto Onuki10305202016-07-14 18:14:08 -07002052 // Always trust the in-memory cache.
2053 final ComponentName cached = user.getCachedLauncher();
2054 if (cached != null) {
2055 if (cached.getPackageName().equals(callingPackage)) {
2056 return true;
2057 }
2058 }
2059 // If the cached one doesn't match, then go ahead
2060
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002061 final List<ResolveInfo> allHomeCandidates = new ArrayList<>();
2062
2063 // Default launcher from package manager.
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07002064 final long startGetHomeActivitiesAsUser = injectElapsedRealtime();
Makoto Onuki10305202016-07-14 18:14:08 -07002065 final ComponentName defaultLauncher = mPackageManagerInternal
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002066 .getHomeActivitiesAsUser(allHomeCandidates, userId);
Makoto Onuki2e210c42016-03-30 08:30:36 -07002067 logDurationStat(Stats.GET_DEFAULT_HOME, startGetHomeActivitiesAsUser);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002068
2069 ComponentName detected;
2070 if (defaultLauncher != null) {
2071 detected = defaultLauncher;
2072 if (DEBUG) {
2073 Slog.v(TAG, "Default launcher from PM: " + detected);
2074 }
2075 } else {
Makoto Onuki10305202016-07-14 18:14:08 -07002076 detected = user.getLastKnownLauncher();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002077
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002078 if (detected != null) {
2079 if (injectIsActivityEnabledAndExported(detected, userId)) {
2080 if (DEBUG) {
2081 Slog.v(TAG, "Cached launcher: " + detected);
2082 }
2083 } else {
2084 Slog.w(TAG, "Cached launcher " + detected + " no longer exists");
2085 detected = null;
Makoto Onuki10305202016-07-14 18:14:08 -07002086 user.clearLauncher();
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002087 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002088 }
2089 }
2090
2091 if (detected == null) {
2092 // If we reach here, that means it's the first check since the user was created,
2093 // and there's already multiple launchers and there's no default set.
2094 // Find the system one with the highest priority.
2095 // (We need to check the priority too because of FallbackHome in Settings.)
2096 // If there's no system launcher yet, then no one can access shortcuts, until
2097 // the user explicitly
2098 final int size = allHomeCandidates.size();
2099
2100 int lastPriority = Integer.MIN_VALUE;
2101 for (int i = 0; i < size; i++) {
2102 final ResolveInfo ri = allHomeCandidates.get(i);
2103 if (!ri.activityInfo.applicationInfo.isSystemApp()) {
2104 continue;
2105 }
2106 if (DEBUG) {
2107 Slog.d(TAG, String.format("hasShortcutPermissionInner: pkg=%s prio=%d",
2108 ri.activityInfo.getComponentName(), ri.priority));
2109 }
2110 if (ri.priority < lastPriority) {
2111 continue;
2112 }
2113 detected = ri.activityInfo.getComponentName();
2114 lastPriority = ri.priority;
2115 }
2116 }
Makoto Onuki2e210c42016-03-30 08:30:36 -07002117
Makoto Onuki10305202016-07-14 18:14:08 -07002118 // Update the cache.
2119 user.setLauncher(detected);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002120 if (detected != null) {
2121 if (DEBUG) {
2122 Slog.v(TAG, "Detected launcher: " + detected);
2123 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002124 return detected.getPackageName().equals(callingPackage);
2125 } else {
2126 // Default launcher not found.
2127 return false;
2128 }
2129 }
2130 }
2131
Makoto Onukicdc78f72016-03-21 15:47:52 -07002132 // === House keeping ===
2133
Makoto Onukib08790c2016-06-23 14:05:46 -07002134 private void cleanUpPackageForAllLoadedUsers(String packageName, @UserIdInt int packageUserId,
2135 boolean appStillExists) {
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002136 synchronized (mLock) {
2137 forEachLoadedUserLocked(user ->
Makoto Onukib08790c2016-06-23 14:05:46 -07002138 cleanUpPackageLocked(packageName, user.getUserId(), packageUserId,
2139 appStillExists));
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002140 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002141 }
2142
Makoto Onuki2e210c42016-03-30 08:30:36 -07002143 /**
2144 * Remove all the information associated with a package. This will really remove all the
2145 * information, including the restore information (i.e. it'll remove packages even if they're
2146 * shadow).
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002147 *
2148 * This is called when an app is uninstalled, or an app gets "clear data"ed.
Makoto Onuki2e210c42016-03-30 08:30:36 -07002149 */
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002150 @VisibleForTesting
Makoto Onukib08790c2016-06-23 14:05:46 -07002151 void cleanUpPackageLocked(String packageName, int owningUserId, int packageUserId,
2152 boolean appStillExists) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002153 final boolean wasUserLoaded = isUserLoadedLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002154
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002155 final ShortcutUser user = getUserShortcutsLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002156 boolean doNotify = false;
2157
2158 // First, remove the package from the package list (if the package is a publisher).
Makoto Onukid99c6f02016-03-28 11:02:54 -07002159 if (packageUserId == owningUserId) {
Makoto Onukic51b2872016-05-04 15:24:50 -07002160 if (user.removePackage(packageName) != null) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002161 doNotify = true;
2162 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07002163 }
Makoto Onukid99c6f02016-03-28 11:02:54 -07002164
Makoto Onukicdc78f72016-03-21 15:47:52 -07002165 // Also remove from the launcher list (if the package is a launcher).
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002166 user.removeLauncher(packageUserId, packageName);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002167
2168 // Then remove pinned shortcuts from all launchers.
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002169 user.forAllLaunchers(l -> l.cleanUpPackage(packageName, packageUserId));
2170
2171 // Now there may be orphan shortcuts because we removed pinned shortcuts at the previous
Makoto Onukicdc78f72016-03-21 15:47:52 -07002172 // step. Remove them too.
Makoto Onukic51b2872016-05-04 15:24:50 -07002173 user.forAllPackages(p -> p.refreshPinnedFlags());
Makoto Onukicdc78f72016-03-21 15:47:52 -07002174
Makoto Onukid99c6f02016-03-28 11:02:54 -07002175 scheduleSaveUser(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002176
2177 if (doNotify) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002178 notifyListeners(packageName, owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002179 }
2180
Makoto Onukib08790c2016-06-23 14:05:46 -07002181 // If the app still exists (i.e. data cleared), we need to re-publish manifest shortcuts.
2182 if (appStillExists && (packageUserId == owningUserId)) {
2183 // This will do the notification and save when needed, so do it after the above
2184 // notifyListeners.
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002185 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07002186 }
2187
Makoto Onukicdc78f72016-03-21 15:47:52 -07002188 if (!wasUserLoaded) {
2189 // Note this will execute the scheduled save.
Makoto Onukid99c6f02016-03-28 11:02:54 -07002190 unloadUserLocked(owningUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002191 }
2192 }
2193
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002194 /**
2195 * Entry point from {@link LauncherApps}.
2196 */
2197 private class LocalService extends ShortcutServiceInternal {
Makoto Onuki2e210c42016-03-30 08:30:36 -07002198
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002199 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002200 public List<ShortcutInfo> getShortcuts(int launcherUserId,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002201 @NonNull String callingPackage, long changedSince,
Makoto Onukiabe84422016-04-07 09:41:19 -07002202 @Nullable String packageName, @Nullable List<String> shortcutIds,
2203 @Nullable ComponentName componentName,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002204 int queryFlags, int userId) {
2205 final ArrayList<ShortcutInfo> ret = new ArrayList<>();
Makoto Onuki9c850012016-07-26 15:50:50 -07002206
Makoto Onuki20c95f82016-05-11 16:51:01 -07002207 final boolean cloneKeyFieldOnly =
2208 ((queryFlags & ShortcutQuery.FLAG_GET_KEY_FIELDS_ONLY) != 0);
2209 final int cloneFlag = cloneKeyFieldOnly ? ShortcutInfo.CLONE_REMOVE_NON_KEY_INFO
2210 : ShortcutInfo.CLONE_REMOVE_FOR_LAUNCHER;
Makoto Onukiabe84422016-04-07 09:41:19 -07002211 if (packageName == null) {
2212 shortcutIds = null; // LauncherAppsService already threw for it though.
2213 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002214
2215 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002216 throwIfUserLockedL(userId);
2217 throwIfUserLockedL(launcherUserId);
2218
Makoto Onuki2e210c42016-03-30 08:30:36 -07002219 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002220 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002221
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002222 if (packageName != null) {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002223 getShortcutsInnerLocked(launcherUserId,
Makoto Onukiabe84422016-04-07 09:41:19 -07002224 callingPackage, packageName, shortcutIds, changedSince,
Makoto Onukide667372016-03-15 14:29:20 -07002225 componentName, queryFlags, userId, ret, cloneFlag);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002226 } else {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002227 final List<String> shortcutIdsF = shortcutIds;
2228 getUserShortcutsLocked(userId).forAllPackages(p -> {
Makoto Onukid99c6f02016-03-28 11:02:54 -07002229 getShortcutsInnerLocked(launcherUserId,
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002230 callingPackage, p.getPackageName(), shortcutIdsF, changedSince,
Makoto Onukide667372016-03-15 14:29:20 -07002231 componentName, queryFlags, userId, ret, cloneFlag);
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002232 });
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002233 }
2234 }
2235 return ret;
2236 }
2237
Makoto Onukid99c6f02016-03-28 11:02:54 -07002238 private void getShortcutsInnerLocked(int launcherUserId, @NonNull String callingPackage,
Makoto Onukiabe84422016-04-07 09:41:19 -07002239 @Nullable String packageName, @Nullable List<String> shortcutIds, long changedSince,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002240 @Nullable ComponentName componentName, int queryFlags,
2241 int userId, ArrayList<ShortcutInfo> ret, int cloneFlag) {
Makoto Onukiabe84422016-04-07 09:41:19 -07002242 final ArraySet<String> ids = shortcutIds == null ? null
2243 : new ArraySet<>(shortcutIds);
2244
Makoto Onukic51b2872016-05-04 15:24:50 -07002245 final ShortcutPackage p = getUserShortcutsLocked(userId)
2246 .getPackageShortcutsIfExists(packageName);
2247 if (p == null) {
2248 return; // No need to instantiate ShortcutPackage.
2249 }
2250
2251 p.findAll(ret,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002252 (ShortcutInfo si) -> {
2253 if (si.getLastChangedTimestamp() < changedSince) {
2254 return false;
2255 }
Makoto Onukiabe84422016-04-07 09:41:19 -07002256 if (ids != null && !ids.contains(si.getId())) {
2257 return false;
2258 }
Makoto Onuki85694522016-05-04 12:53:37 -07002259 if (componentName != null) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002260 if (si.getActivity() != null
2261 && !si.getActivity().equals(componentName)) {
Makoto Onuki85694522016-05-04 12:53:37 -07002262 return false;
2263 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002264 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002265 if (((queryFlags & ShortcutQuery.FLAG_GET_DYNAMIC) != 0)
2266 && si.isDynamic()) {
2267 return true;
2268 }
2269 if (((queryFlags & ShortcutQuery.FLAG_GET_PINNED) != 0)
2270 && si.isPinned()) {
2271 return true;
2272 }
2273 if (((queryFlags & ShortcutQuery.FLAG_GET_MANIFEST) != 0)
2274 && si.isManifestShortcut()) {
2275 return true;
2276 }
2277 return false;
Makoto Onukid99c6f02016-03-28 11:02:54 -07002278 }, cloneFlag, callingPackage, launcherUserId);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002279 }
2280
2281 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002282 public boolean isPinnedByCaller(int launcherUserId, @NonNull String callingPackage,
2283 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2284 Preconditions.checkStringNotEmpty(packageName, "packageName");
2285 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
2286
2287 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002288 throwIfUserLockedL(userId);
2289 throwIfUserLockedL(launcherUserId);
2290
Makoto Onuki2e210c42016-03-30 08:30:36 -07002291 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002292 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002293
Makoto Onukid99c6f02016-03-28 11:02:54 -07002294 final ShortcutInfo si = getShortcutInfoLocked(
2295 launcherUserId, callingPackage, packageName, shortcutId, userId);
2296 return si != null && si.isPinned();
2297 }
2298 }
2299
Makoto Onuki2e210c42016-03-30 08:30:36 -07002300 private ShortcutInfo getShortcutInfoLocked(
Makoto Onukid99c6f02016-03-28 11:02:54 -07002301 int launcherUserId, @NonNull String callingPackage,
2302 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2303 Preconditions.checkStringNotEmpty(packageName, "packageName");
2304 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
2305
Makoto Onuki02f338e2016-07-29 09:40:40 -07002306 throwIfUserLockedL(userId);
2307 throwIfUserLockedL(launcherUserId);
Makoto Onuki9c850012016-07-26 15:50:50 -07002308
Makoto Onukic51b2872016-05-04 15:24:50 -07002309 final ShortcutPackage p = getUserShortcutsLocked(userId)
2310 .getPackageShortcutsIfExists(packageName);
2311 if (p == null) {
2312 return null;
2313 }
2314
Makoto Onukid99c6f02016-03-28 11:02:54 -07002315 final ArrayList<ShortcutInfo> list = new ArrayList<>(1);
Makoto Onukic51b2872016-05-04 15:24:50 -07002316 p.findAll(list,
Makoto Onukid99c6f02016-03-28 11:02:54 -07002317 (ShortcutInfo si) -> shortcutId.equals(si.getId()),
2318 /* clone flags=*/ 0, callingPackage, launcherUserId);
2319 return list.size() == 0 ? null : list.get(0);
2320 }
2321
2322 @Override
2323 public void pinShortcuts(int launcherUserId,
2324 @NonNull String callingPackage, @NonNull String packageName,
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002325 @NonNull List<String> shortcutIds, int userId) {
2326 // Calling permission must be checked by LauncherAppsImpl.
2327 Preconditions.checkStringNotEmpty(packageName, "packageName");
2328 Preconditions.checkNotNull(shortcutIds, "shortcutIds");
2329
2330 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002331 throwIfUserLockedL(userId);
2332 throwIfUserLockedL(launcherUserId);
2333
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002334 final ShortcutLauncher launcher =
Makoto Onuki2e210c42016-03-30 08:30:36 -07002335 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId);
Makoto Onukic51b2872016-05-04 15:24:50 -07002336 launcher.attemptToRestoreIfNeededAndSave();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002337
Makoto Onukic51b2872016-05-04 15:24:50 -07002338 launcher.pinShortcuts(userId, packageName, shortcutIds);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002339 }
Makoto Onuki39686e82016-04-13 18:03:00 -07002340 packageShortcutsChanged(packageName, userId);
Makoto Onuki7001a612016-05-27 13:24:28 -07002341
2342 verifyStates();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002343 }
2344
2345 @Override
Makoto Onuki440a1ea2016-07-20 14:21:18 -07002346 public Intent[] createShortcutIntents(int launcherUserId,
Makoto Onukid99c6f02016-03-28 11:02:54 -07002347 @NonNull String callingPackage,
Makoto Onuki43204b82016-03-08 16:16:44 -08002348 @NonNull String packageName, @NonNull String shortcutId, int userId) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002349 // Calling permission must be checked by LauncherAppsImpl.
Makoto Onuki43204b82016-03-08 16:16:44 -08002350 Preconditions.checkStringNotEmpty(packageName, "packageName can't be empty");
2351 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId can't be empty");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002352
2353 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002354 throwIfUserLockedL(userId);
2355 throwIfUserLockedL(launcherUserId);
2356
Makoto Onuki2e210c42016-03-30 08:30:36 -07002357 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002358 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002359
Makoto Onukid99c6f02016-03-28 11:02:54 -07002360 // Make sure the shortcut is actually visible to the launcher.
2361 final ShortcutInfo si = getShortcutInfoLocked(
2362 launcherUserId, callingPackage, packageName, shortcutId, userId);
2363 // "si == null" should suffice here, but check the flags too just to make sure.
Makoto Onuki22fcc682016-05-17 14:52:19 -07002364 if (si == null || !si.isEnabled() || !si.isAlive()) {
Makoto Onuki83f6d2d2016-07-11 14:30:19 -07002365 Log.e(TAG, "Shortcut " + shortcutId + " does not exist or disabled");
Makoto Onukid99c6f02016-03-28 11:02:54 -07002366 return null;
2367 }
Makoto Onuki440a1ea2016-07-20 14:21:18 -07002368 return si.getIntents();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002369 }
2370 }
2371
2372 @Override
2373 public void addListener(@NonNull ShortcutChangeListener listener) {
2374 synchronized (mLock) {
2375 mListeners.add(Preconditions.checkNotNull(listener));
2376 }
2377 }
Makoto Onuki55046222016-03-08 10:49:47 -08002378
2379 @Override
Makoto Onukiabe84422016-04-07 09:41:19 -07002380 public int getShortcutIconResId(int launcherUserId, @NonNull String callingPackage,
2381 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2382 Preconditions.checkNotNull(callingPackage, "callingPackage");
2383 Preconditions.checkNotNull(packageName, "packageName");
2384 Preconditions.checkNotNull(shortcutId, "shortcutId");
Makoto Onuki55046222016-03-08 10:49:47 -08002385
2386 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002387 throwIfUserLockedL(userId);
2388 throwIfUserLockedL(launcherUserId);
2389
Makoto Onuki2e210c42016-03-30 08:30:36 -07002390 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002391 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002392
Makoto Onukic51b2872016-05-04 15:24:50 -07002393 final ShortcutPackage p = getUserShortcutsLocked(userId)
2394 .getPackageShortcutsIfExists(packageName);
2395 if (p == null) {
2396 return 0;
2397 }
2398
2399 final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId);
Makoto Onuki55046222016-03-08 10:49:47 -08002400 return (shortcutInfo != null && shortcutInfo.hasIconResource())
2401 ? shortcutInfo.getIconResourceId() : 0;
2402 }
2403 }
2404
2405 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002406 public ParcelFileDescriptor getShortcutIconFd(int launcherUserId,
Makoto Onukiabe84422016-04-07 09:41:19 -07002407 @NonNull String callingPackage, @NonNull String packageName,
2408 @NonNull String shortcutId, int userId) {
2409 Preconditions.checkNotNull(callingPackage, "callingPackage");
2410 Preconditions.checkNotNull(packageName, "packageName");
2411 Preconditions.checkNotNull(shortcutId, "shortcutId");
Makoto Onuki55046222016-03-08 10:49:47 -08002412
2413 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002414 throwIfUserLockedL(userId);
2415 throwIfUserLockedL(launcherUserId);
2416
Makoto Onuki2e210c42016-03-30 08:30:36 -07002417 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
Makoto Onukic51b2872016-05-04 15:24:50 -07002418 .attemptToRestoreIfNeededAndSave();
Makoto Onuki2e210c42016-03-30 08:30:36 -07002419
Makoto Onukic51b2872016-05-04 15:24:50 -07002420 final ShortcutPackage p = getUserShortcutsLocked(userId)
2421 .getPackageShortcutsIfExists(packageName);
2422 if (p == null) {
2423 return null;
2424 }
2425
2426 final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId);
Makoto Onuki55046222016-03-08 10:49:47 -08002427 if (shortcutInfo == null || !shortcutInfo.hasIconFile()) {
2428 return null;
2429 }
2430 try {
Makoto Onuki34d1c912016-03-10 14:24:58 -08002431 if (shortcutInfo.getBitmapPath() == null) {
2432 Slog.w(TAG, "null bitmap detected in getShortcutIconFd()");
2433 return null;
2434 }
Makoto Onuki55046222016-03-08 10:49:47 -08002435 return ParcelFileDescriptor.open(
2436 new File(shortcutInfo.getBitmapPath()),
2437 ParcelFileDescriptor.MODE_READ_ONLY);
2438 } catch (FileNotFoundException e) {
2439 Slog.e(TAG, "Icon file not found: " + shortcutInfo.getBitmapPath());
2440 return null;
2441 }
2442 }
2443 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002444
2445 @Override
Makoto Onukid99c6f02016-03-28 11:02:54 -07002446 public boolean hasShortcutHostPermission(int launcherUserId,
2447 @NonNull String callingPackage) {
2448 return ShortcutService.this.hasShortcutHostPermission(callingPackage, launcherUserId);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08002449 }
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002450 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002451
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002452 final BroadcastReceiver mReceiver = new BroadcastReceiver() {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002453 @Override
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002454 public void onReceive(Context context, Intent intent) {
2455 if (!mBootCompleted.get()) {
2456 return; // Boot not completed, ignore the broadcast.
2457 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07002458 try {
2459 if (Intent.ACTION_LOCALE_CHANGED.equals(intent.getAction())) {
2460 handleLocaleChanged();
2461 }
2462 } catch (Exception e) {
2463 wtf("Exception in mReceiver.onReceive", e);
Makoto Onukic51b2872016-05-04 15:24:50 -07002464 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07002465 }
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002466 };
Makoto Onuki6f7362d92016-03-04 13:39:41 -08002467
Makoto Onuki157b1622016-06-02 16:13:10 -07002468 void handleLocaleChanged() {
2469 if (DEBUG) {
2470 Slog.d(TAG, "handleLocaleChanged");
2471 }
2472 scheduleSaveBaseState();
2473
Makoto Onuki02f338e2016-07-29 09:40:40 -07002474 synchronized (mLock) {
2475 final long token = injectClearCallingIdentity();
2476 try {
2477 forEachLoadedUserLocked(user -> user.detectLocaleChange());
2478 } finally {
2479 injectRestoreCallingIdentity(token);
2480 }
Makoto Onuki157b1622016-06-02 16:13:10 -07002481 }
2482 }
2483
Makoto Onukif34c3082016-07-13 10:25:25 -07002484 /**
2485 * Package event callbacks.
2486 */
2487 @VisibleForTesting
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002488 final BroadcastReceiver mPackageMonitor = new BroadcastReceiver() {
Makoto Onukif34c3082016-07-13 10:25:25 -07002489 @Override
2490 public void onReceive(Context context, Intent intent) {
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002491 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
2492 if (userId == UserHandle.USER_NULL) {
2493 Slog.w(TAG, "Intent broadcast does not contain user handle: " + intent);
2494 return;
2495 }
2496
2497 final String action = intent.getAction();
2498
2499 // This is normally called on Handler, so clearCallingIdentity() isn't needed,
2500 // but we still check it in unit tests.
Makoto Onukif34c3082016-07-13 10:25:25 -07002501 final long token = injectClearCallingIdentity();
2502 try {
Makoto Onuki10305202016-07-14 18:14:08 -07002503 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07002504 if (!isUserUnlockedL(userId)) {
2505 if (DEBUG) {
2506 Slog.d(TAG, "Ignoring package broadcast " + action
2507 + " for locked/stopped user " + userId);
2508 }
2509 return;
2510 }
2511
2512 // Whenever we get one of those package broadcasts, or get
2513 // ACTION_PREFERRED_ACTIVITY_CHANGED, we purge the default launcher cache.
Makoto Onuki10305202016-07-14 18:14:08 -07002514 final ShortcutUser user = getUserShortcutsLocked(userId);
2515 user.clearLauncher();
2516 }
2517 if (Intent.ACTION_PREFERRED_ACTIVITY_CHANGED.equals(action)) {
2518 // Nothing farther to do.
2519 return;
2520 }
2521
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002522 final Uri intentUri = intent.getData();
2523 final String packageName = (intentUri != null) ? intentUri.getSchemeSpecificPart()
2524 : null;
2525 if (packageName == null) {
2526 Slog.w(TAG, "Intent broadcast does not contain package name: " + intent);
2527 return;
2528 }
2529
2530 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
2531
2532 switch (action) {
2533 case Intent.ACTION_PACKAGE_ADDED:
2534 if (replacing) {
2535 handlePackageUpdateFinished(packageName, userId);
2536 } else {
2537 handlePackageAdded(packageName, userId);
2538 }
2539 break;
2540 case Intent.ACTION_PACKAGE_REMOVED:
2541 if (!replacing) {
2542 handlePackageRemoved(packageName, userId);
2543 }
2544 break;
2545 case Intent.ACTION_PACKAGE_CHANGED:
2546 handlePackageChanged(packageName, userId);
2547
2548 break;
2549 case Intent.ACTION_PACKAGE_DATA_CLEARED:
2550 handlePackageDataCleared(packageName, userId);
2551 break;
2552 }
Makoto Onuki02f338e2016-07-29 09:40:40 -07002553 } catch (Exception e) {
2554 wtf("Exception in mPackageMonitor.onReceive", e);
Makoto Onukif34c3082016-07-13 10:25:25 -07002555 } finally {
2556 injectRestoreCallingIdentity(token);
Makoto Onukia2241832016-07-06 13:28:37 -07002557 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07002558 }
Makoto Onukif34c3082016-07-13 10:25:25 -07002559 };
Makoto Onukicdc78f72016-03-21 15:47:52 -07002560
Makoto Onuki0acbb142016-03-22 17:02:57 -07002561 /**
Makoto Onuki39686e82016-04-13 18:03:00 -07002562 * Called when a user is unlocked.
2563 * - Check all known packages still exist, and otherwise perform cleanup.
2564 * - If a package still exists, check the version code. If it's been updated, may need to
Makoto Onukib08790c2016-06-23 14:05:46 -07002565 * update timestamps of its shortcuts.
Makoto Onuki0acbb142016-03-22 17:02:57 -07002566 */
Makoto Onukid99c6f02016-03-28 11:02:54 -07002567 @VisibleForTesting
Makoto Onuki39686e82016-04-13 18:03:00 -07002568 void checkPackageChanges(@UserIdInt int ownerUserId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07002569 if (DEBUG) {
Makoto Onuki39686e82016-04-13 18:03:00 -07002570 Slog.d(TAG, "checkPackageChanges() ownerUserId=" + ownerUserId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07002571 }
Makoto Onukib08790c2016-06-23 14:05:46 -07002572 if (injectIsSafeModeEnabled()) {
2573 Slog.i(TAG, "Safe mode, skipping checkPackageChanges()");
2574 return;
2575 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07002576
Makoto Onuki22fcc682016-05-17 14:52:19 -07002577 final long start = injectElapsedRealtime();
2578 try {
2579 final ArrayList<PackageWithUser> gonePackages = new ArrayList<>();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002580
Makoto Onuki22fcc682016-05-17 14:52:19 -07002581 synchronized (mLock) {
2582 final ShortcutUser user = getUserShortcutsLocked(ownerUserId);
2583
2584 // Find packages that have been uninstalled.
2585 user.forAllPackageItems(spi -> {
2586 if (spi.getPackageInfo().isShadow()) {
2587 return; // Don't delete shadow information.
2588 }
2589 if (!isPackageInstalled(spi.getPackageName(), spi.getPackageUserId())) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002590 if (DEBUG) {
2591 Slog.d(TAG, "Uninstalled: " + spi.getPackageName()
2592 + " user " + spi.getPackageUserId());
2593 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002594 gonePackages.add(PackageWithUser.of(spi));
2595 }
2596 });
2597 if (gonePackages.size() > 0) {
2598 for (int i = gonePackages.size() - 1; i >= 0; i--) {
2599 final PackageWithUser pu = gonePackages.get(i);
Makoto Onukib08790c2016-06-23 14:05:46 -07002600 cleanUpPackageLocked(pu.packageName, ownerUserId, pu.userId,
2601 /* appStillExists = */ false);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002602 }
Makoto Onukid99c6f02016-03-28 11:02:54 -07002603 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002604
Makoto Onuki377b7972016-08-09 14:43:55 -07002605 rescanUpdatedPackagesLocked(ownerUserId, user.getLastAppScanTime(),
2606 /* forceRescan=*/ false);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002607 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07002608 } finally {
2609 logDurationStat(Stats.CHECK_PACKAGE_CHANGES, start);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002610 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002611 verifyStates();
Makoto Onukicdc78f72016-03-21 15:47:52 -07002612 }
2613
Makoto Onuki377b7972016-08-09 14:43:55 -07002614 private void rescanUpdatedPackagesLocked(@UserIdInt int userId, long lastScanTime,
2615 boolean forceRescan) {
2616 final ShortcutUser user = getUserShortcutsLocked(userId);
2617
2618 final long now = injectCurrentTimeMillis();
2619
2620 // Then for each installed app, publish manifest shortcuts when needed.
2621 forUpdatedPackages(userId, lastScanTime, ai -> {
2622 user.attemptToRestoreIfNeededAndSave(this, ai.packageName, userId);
2623 user.rescanPackageIfNeeded(ai.packageName, forceRescan);
2624 });
2625
2626 // Write the time just before the scan, because there may be apps that have just
2627 // been updated, and we want to catch them in the next time.
2628 user.setLastAppScanTime(now);
2629 scheduleSaveUser(userId);
2630 }
2631
Makoto Onuki0acbb142016-03-22 17:02:57 -07002632 private void handlePackageAdded(String packageName, @UserIdInt int userId) {
Makoto Onukicdc78f72016-03-21 15:47:52 -07002633 if (DEBUG) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07002634 Slog.d(TAG, String.format("handlePackageAdded: %s user=%d", packageName, userId));
2635 }
2636 synchronized (mLock) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002637 final ShortcutUser user = getUserShortcutsLocked(userId);
2638 user.attemptToRestoreIfNeededAndSave(this, packageName, userId);
Makoto Onuki64183d52016-08-08 14:11:34 -07002639 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002640 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002641 verifyStates();
Makoto Onuki0acbb142016-03-22 17:02:57 -07002642 }
2643
2644 private void handlePackageUpdateFinished(String packageName, @UserIdInt int userId) {
Makoto Onuki905e8852016-03-28 10:40:58 -07002645 if (DEBUG) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002646 Slog.d(TAG, String.format("handlePackageUpdateFinished: %s user=%d",
2647 packageName, userId));
Makoto Onuki0acbb142016-03-22 17:02:57 -07002648 }
2649 synchronized (mLock) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002650 final ShortcutUser user = getUserShortcutsLocked(userId);
2651 user.attemptToRestoreIfNeededAndSave(this, packageName, userId);
Makoto Onuki39686e82016-04-13 18:03:00 -07002652
Makoto Onuki22fcc682016-05-17 14:52:19 -07002653 if (isPackageInstalled(packageName, userId)) {
Makoto Onuki64183d52016-08-08 14:11:34 -07002654 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onuki39686e82016-04-13 18:03:00 -07002655 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07002656 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002657 verifyStates();
Makoto Onuki0acbb142016-03-22 17:02:57 -07002658 }
2659
Makoto Onuki2e210c42016-03-30 08:30:36 -07002660 private void handlePackageRemoved(String packageName, @UserIdInt int packageUserId) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07002661 if (DEBUG) {
Makoto Onuki2e210c42016-03-30 08:30:36 -07002662 Slog.d(TAG, String.format("handlePackageRemoved: %s user=%d", packageName,
2663 packageUserId));
Makoto Onukicdc78f72016-03-21 15:47:52 -07002664 }
Makoto Onukib08790c2016-06-23 14:05:46 -07002665 cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ false);
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002666
2667 verifyStates();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07002668 }
2669
Makoto Onuki9ac59d02016-04-26 11:23:14 -07002670 private void handlePackageDataCleared(String packageName, int packageUserId) {
2671 if (DEBUG) {
2672 Slog.d(TAG, String.format("handlePackageDataCleared: %s user=%d", packageName,
2673 packageUserId));
Makoto Onukicdc78f72016-03-21 15:47:52 -07002674 }
Makoto Onukib08790c2016-06-23 14:05:46 -07002675 cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ true);
2676
2677 verifyStates();
2678 }
2679
2680 private void handlePackageChanged(String packageName, int packageUserId) {
2681 if (DEBUG) {
2682 Slog.d(TAG, String.format("handlePackageChanged: %s user=%d", packageName,
2683 packageUserId));
2684 }
2685
2686 // Activities may be disabled or enabled. Just rescan the package.
2687 synchronized (mLock) {
2688 final ShortcutUser user = getUserShortcutsLocked(packageUserId);
2689
Makoto Onuki4e6cef42016-07-13 16:14:01 -07002690 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07002691 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07002692
2693 verifyStates();
Makoto Onukicdc78f72016-03-21 15:47:52 -07002694 }
2695
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002696 // === PackageManager interaction ===
Makoto Onuki0acbb142016-03-22 17:02:57 -07002697
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002698 /**
2699 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
2700 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002701 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002702 final PackageInfo getPackageInfoWithSignatures(String packageName, @UserIdInt int userId) {
2703 return getPackageInfo(packageName, userId, true);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002704 }
2705
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002706 /**
2707 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
2708 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002709 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002710 final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId) {
2711 return getPackageInfo(packageName, userId, false);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002712 }
2713
Makoto Onuki905e8852016-03-28 10:40:58 -07002714 int injectGetPackageUid(@NonNull String packageName, @UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002715 final long token = injectClearCallingIdentity();
Makoto Onuki905e8852016-03-28 10:40:58 -07002716 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002717 return mIPackageManager.getPackageUid(packageName, PACKAGE_MATCH_FLAGS, userId);
Makoto Onuki905e8852016-03-28 10:40:58 -07002718 } catch (RemoteException e) {
2719 // Shouldn't happen.
2720 Slog.wtf(TAG, "RemoteException", e);
2721 return -1;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002722 } finally {
2723 injectRestoreCallingIdentity(token);
Makoto Onuki905e8852016-03-28 10:40:58 -07002724 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07002725 }
2726
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002727 /**
2728 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
2729 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002730 @Nullable
Makoto Onuki0acbb142016-03-22 17:02:57 -07002731 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002732 final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId,
2733 boolean getSignatures) {
2734 return isInstalledOrNull(injectPackageInfoWithUninstalled(
2735 packageName, userId, getSignatures));
2736 }
2737
2738 /**
2739 * Do not use directly; this returns uninstalled packages too.
2740 */
2741 @Nullable
2742 @VisibleForTesting
2743 PackageInfo injectPackageInfoWithUninstalled(String packageName, @UserIdInt int userId,
Makoto Onuki0acbb142016-03-22 17:02:57 -07002744 boolean getSignatures) {
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07002745 final long start = injectElapsedRealtime();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002746 final long token = injectClearCallingIdentity();
Makoto Onuki0acbb142016-03-22 17:02:57 -07002747 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002748 return mIPackageManager.getPackageInfo(
2749 packageName, PACKAGE_MATCH_FLAGS
2750 | (getSignatures ? PackageManager.GET_SIGNATURES : 0), userId);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002751 } catch (RemoteException e) {
2752 // Shouldn't happen.
2753 Slog.wtf(TAG, "RemoteException", e);
2754 return null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002755 } finally {
2756 injectRestoreCallingIdentity(token);
Makoto Onuki2e210c42016-03-30 08:30:36 -07002757
2758 logDurationStat(
2759 (getSignatures ? Stats.GET_PACKAGE_INFO_WITH_SIG : Stats.GET_PACKAGE_INFO),
2760 start);
Makoto Onuki0acbb142016-03-22 17:02:57 -07002761 }
2762 }
2763
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002764 /**
2765 * Returns {@link ApplicationInfo} unless it's uninstalled or disabled.
2766 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002767 @Nullable
Makoto Onuki905e8852016-03-28 10:40:58 -07002768 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002769 final ApplicationInfo getApplicationInfo(String packageName, @UserIdInt int userId) {
2770 return isInstalledOrNull(injectApplicationInfoWithUninstalled(packageName, userId));
2771 }
2772
2773 /**
2774 * Do not use directly; this returns uninstalled packages too.
2775 */
2776 @Nullable
2777 @VisibleForTesting
2778 ApplicationInfo injectApplicationInfoWithUninstalled(
2779 String packageName, @UserIdInt int userId) {
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07002780 final long start = injectElapsedRealtime();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002781 final long token = injectClearCallingIdentity();
Makoto Onuki905e8852016-03-28 10:40:58 -07002782 try {
2783 return mIPackageManager.getApplicationInfo(packageName, PACKAGE_MATCH_FLAGS, userId);
2784 } catch (RemoteException e) {
2785 // Shouldn't happen.
2786 Slog.wtf(TAG, "RemoteException", e);
2787 return null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002788 } finally {
2789 injectRestoreCallingIdentity(token);
Makoto Onuki2e210c42016-03-30 08:30:36 -07002790
2791 logDurationStat(Stats.GET_APPLICATION_INFO, start);
Makoto Onuki905e8852016-03-28 10:40:58 -07002792 }
2793 }
2794
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002795 /**
2796 * Returns {@link ActivityInfo} with its metadata unless it's uninstalled or disabled.
2797 */
Makoto Onuki22fcc682016-05-17 14:52:19 -07002798 @Nullable
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002799 final ActivityInfo getActivityInfoWithMetadata(ComponentName activity, @UserIdInt int userId) {
2800 return isInstalledOrNull(injectGetActivityInfoWithMetadataWithUninstalled(
2801 activity, userId));
2802 }
2803
2804 /**
2805 * Do not use directly; this returns uninstalled packages too.
2806 */
2807 @Nullable
2808 @VisibleForTesting
2809 ActivityInfo injectGetActivityInfoWithMetadataWithUninstalled(
2810 ComponentName activity, @UserIdInt int userId) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002811 final long start = injectElapsedRealtime();
2812 final long token = injectClearCallingIdentity();
2813 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07002814 return mIPackageManager.getActivityInfo(activity,
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002815 (PACKAGE_MATCH_FLAGS | PackageManager.GET_META_DATA), userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002816 } catch (RemoteException e) {
2817 // Shouldn't happen.
2818 Slog.wtf(TAG, "RemoteException", e);
2819 return null;
2820 } finally {
2821 injectRestoreCallingIdentity(token);
2822
Makoto Onukib08790c2016-06-23 14:05:46 -07002823 logDurationStat(Stats.GET_ACTIVITY_WITH_METADATA, start);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002824 }
2825 }
2826
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002827 /**
2828 * Return all installed and enabled packages.
2829 */
2830 @NonNull
Makoto Onuki22fcc682016-05-17 14:52:19 -07002831 @VisibleForTesting
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002832 final List<PackageInfo> getInstalledPackages(@UserIdInt int userId) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002833 final long start = injectElapsedRealtime();
2834 final long token = injectClearCallingIdentity();
2835 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002836 final List<PackageInfo> all = injectGetPackagesWithUninstalled(userId);
2837
2838 all.removeIf(PACKAGE_NOT_INSTALLED);
2839
2840 return all;
Makoto Onuki22fcc682016-05-17 14:52:19 -07002841 } catch (RemoteException e) {
2842 // Shouldn't happen.
2843 Slog.wtf(TAG, "RemoteException", e);
2844 return null;
2845 } finally {
2846 injectRestoreCallingIdentity(token);
2847
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07002848 logDurationStat(Stats.GET_INSTALLED_PACKAGES, start);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002849 }
2850 }
2851
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002852 /**
2853 * Do not use directly; this returns uninstalled packages too.
2854 */
2855 @NonNull
2856 @VisibleForTesting
2857 List<PackageInfo> injectGetPackagesWithUninstalled(@UserIdInt int userId)
2858 throws RemoteException {
2859 final ParceledListSlice<PackageInfo> parceledList =
2860 mIPackageManager.getInstalledPackages(PACKAGE_MATCH_FLAGS, userId);
2861 if (parceledList == null) {
2862 return Collections.emptyList();
2863 }
2864 return parceledList.getList();
2865 }
2866
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07002867 private void forUpdatedPackages(@UserIdInt int userId, long lastScanTime,
Makoto Onuki22fcc682016-05-17 14:52:19 -07002868 Consumer<ApplicationInfo> callback) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07002869 if (DEBUG) {
2870 Slog.d(TAG, "forUpdatedPackages for user " + userId + ", lastScanTime=" + lastScanTime);
2871 }
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002872 final List<PackageInfo> list = getInstalledPackages(userId);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002873 for (int i = list.size() - 1; i >= 0; i--) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07002874 final PackageInfo pi = list.get(i);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002875
Makoto Onuki64183d52016-08-08 14:11:34 -07002876 // If the package has been updated since the last scan time, then scan it.
2877 // Also if it's a system app with no update, lastUpdateTime is not reliable, so
2878 // just scan it.
2879 if (pi.lastUpdateTime >= lastScanTime || isPureSystemApp(pi.applicationInfo)) {
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07002880 if (DEBUG) {
2881 Slog.d(TAG, "Found updated package " + pi.packageName);
2882 }
2883 callback.accept(pi.applicationInfo);
Makoto Onuki22fcc682016-05-17 14:52:19 -07002884 }
2885 }
2886 }
2887
Makoto Onuki64183d52016-08-08 14:11:34 -07002888 /**
2889 * @return true if it's a system app with no updates.
2890 */
2891 private boolean isPureSystemApp(ApplicationInfo ai) {
2892 return ai.isSystemApp() && !ai.isUpdatedSystemApp();
2893 }
2894
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002895 private boolean isApplicationFlagSet(@NonNull String packageName, int userId, int flags) {
2896 final ApplicationInfo ai = injectApplicationInfoWithUninstalled(packageName, userId);
Makoto Onuki905e8852016-03-28 10:40:58 -07002897 return (ai != null) && ((ai.flags & flags) == flags);
2898 }
2899
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002900 private static boolean isInstalled(@Nullable ApplicationInfo ai) {
2901 return (ai != null) && (ai.flags & ApplicationInfo.FLAG_INSTALLED) != 0;
2902 }
2903
2904 private static boolean isInstalled(@Nullable PackageInfo pi) {
2905 return (pi != null) && isInstalled(pi.applicationInfo);
2906 }
2907
2908 private static boolean isInstalled(@Nullable ActivityInfo ai) {
2909 return (ai != null) && isInstalled(ai.applicationInfo);
2910 }
2911
2912 private static ApplicationInfo isInstalledOrNull(ApplicationInfo ai) {
2913 return isInstalled(ai) ? ai : null;
2914 }
2915
2916 private static PackageInfo isInstalledOrNull(PackageInfo pi) {
2917 return isInstalled(pi) ? pi : null;
2918 }
2919
2920 private static ActivityInfo isInstalledOrNull(ActivityInfo ai) {
2921 return isInstalled(ai) ? ai : null;
2922 }
2923
Makoto Onuki2e210c42016-03-30 08:30:36 -07002924 boolean isPackageInstalled(String packageName, int userId) {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002925 return getApplicationInfo(packageName, userId) != null;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07002926 }
2927
Makoto Onuki22fcc682016-05-17 14:52:19 -07002928 @Nullable
2929 XmlResourceParser injectXmlMetaData(ActivityInfo activityInfo, String key) {
Makoto Onuki22fcc682016-05-17 14:52:19 -07002930 return activityInfo.loadXmlMetaData(mContext.getPackageManager(), key);
Makoto Onuki39686e82016-04-13 18:03:00 -07002931 }
2932
Makoto Onuki157b1622016-06-02 16:13:10 -07002933 @Nullable
2934 Resources injectGetResourcesForApplicationAsUser(String packageName, int userId) {
2935 final long start = injectElapsedRealtime();
2936 final long token = injectClearCallingIdentity();
2937 try {
2938 return mContext.getPackageManager().getResourcesForApplicationAsUser(
2939 packageName, userId);
2940 } catch (NameNotFoundException e) {
2941 Slog.e(TAG, "Resources for package " + packageName + " not found");
2942 return null;
2943 } finally {
2944 injectRestoreCallingIdentity(token);
2945
2946 logDurationStat(Stats.GET_APPLICATION_RESOURCES, start);
2947 }
2948 }
2949
Makoto Onukib08790c2016-06-23 14:05:46 -07002950 private Intent getMainActivityIntent() {
2951 final Intent intent = new Intent(Intent.ACTION_MAIN);
2952 intent.addCategory(LAUNCHER_INTENT_CATEGORY);
2953 return intent;
2954 }
2955
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002956 /**
2957 * Same as queryIntentActivitiesAsUser, except it makes sure the package is installed,
2958 * and only returns exported activities.
2959 */
2960 @NonNull
2961 @VisibleForTesting
2962 List<ResolveInfo> queryActivities(@NonNull Intent baseIntent,
2963 @NonNull String packageName, @Nullable ComponentName activity, int userId) {
2964
2965 baseIntent.setPackage(Preconditions.checkNotNull(packageName));
2966 if (activity != null) {
2967 baseIntent.setComponent(activity);
2968 }
2969
2970 final List<ResolveInfo> resolved =
2971 mContext.getPackageManager().queryIntentActivitiesAsUser(
2972 baseIntent, PACKAGE_MATCH_FLAGS, userId);
2973 if (resolved == null || resolved.size() == 0) {
2974 return EMPTY_RESOLVE_INFO;
2975 }
2976 // Make sure the package is installed.
2977 if (!isInstalled(resolved.get(0).activityInfo)) {
2978 return EMPTY_RESOLVE_INFO;
2979 }
2980 resolved.removeIf(ACTIVITY_NOT_EXPORTED);
2981 return resolved;
2982 }
2983
2984 /**
2985 * Return the main activity that is enabled and exported. If multiple activities are found,
2986 * return the first one.
2987 */
Makoto Onukib08790c2016-06-23 14:05:46 -07002988 @Nullable
2989 ComponentName injectGetDefaultMainActivity(@NonNull String packageName, int userId) {
2990 final long start = injectElapsedRealtime();
2991 final long token = injectClearCallingIdentity();
2992 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07002993 final List<ResolveInfo> resolved =
Makoto Onukiee6b6e42016-06-29 17:34:02 -07002994 queryActivities(getMainActivityIntent(), packageName, null, userId);
2995 return resolved.size() == 0 ? null : resolved.get(0).activityInfo.getComponentName();
Makoto Onukib08790c2016-06-23 14:05:46 -07002996 } finally {
2997 injectRestoreCallingIdentity(token);
2998
2999 logDurationStat(Stats.GET_LAUNCHER_ACTIVITY, start);
3000 }
3001 }
3002
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003003 /**
3004 * Return whether an activity is enabled, exported and main.
3005 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003006 boolean injectIsMainActivity(@NonNull ComponentName activity, int userId) {
3007 final long start = injectElapsedRealtime();
3008 final long token = injectClearCallingIdentity();
3009 try {
Makoto Onukib08790c2016-06-23 14:05:46 -07003010 final List<ResolveInfo> resolved =
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003011 queryActivities(getMainActivityIntent(), activity.getPackageName(),
3012 activity, userId);
3013 return resolved.size() > 0;
Makoto Onukib08790c2016-06-23 14:05:46 -07003014 } finally {
3015 injectRestoreCallingIdentity(token);
3016
3017 logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start);
3018 }
3019 }
3020
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003021 /**
3022 * Return all the enabled, exported and main activities from a package.
3023 */
Makoto Onukib08790c2016-06-23 14:05:46 -07003024 @NonNull
3025 List<ResolveInfo> injectGetMainActivities(@NonNull String packageName, int userId) {
3026 final long start = injectElapsedRealtime();
3027 final long token = injectClearCallingIdentity();
3028 try {
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003029 return queryActivities(getMainActivityIntent(), packageName, null, userId);
Makoto Onukib08790c2016-06-23 14:05:46 -07003030 } finally {
3031 injectRestoreCallingIdentity(token);
3032
3033 logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start);
3034 }
3035 }
3036
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003037 /**
3038 * Return whether an activity is enabled and exported.
3039 */
3040 @VisibleForTesting
3041 boolean injectIsActivityEnabledAndExported(
3042 @NonNull ComponentName activity, @UserIdInt int userId) {
3043 final long start = injectElapsedRealtime();
3044 final long token = injectClearCallingIdentity();
3045 try {
3046 return queryActivities(new Intent(), activity.getPackageName(), activity, userId)
3047 .size() > 0;
3048 } finally {
3049 injectRestoreCallingIdentity(token);
3050
3051 logDurationStat(Stats.IS_ACTIVITY_ENABLED, start);
3052 }
3053 }
3054
Makoto Onukib08790c2016-06-23 14:05:46 -07003055 boolean injectIsSafeModeEnabled() {
3056 final long token = injectClearCallingIdentity();
3057 try {
3058 return IWindowManager.Stub
3059 .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE))
3060 .isSafeModeEnabled();
3061 } catch (RemoteException e) {
3062 return false; // Shouldn't happen though.
3063 } finally {
3064 injectRestoreCallingIdentity(token);
3065 }
3066 }
3067
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003068 // === Backup & restore ===
3069
Makoto Onuki0acbb142016-03-22 17:02:57 -07003070 boolean shouldBackupApp(String packageName, int userId) {
Makoto Onuki905e8852016-03-28 10:40:58 -07003071 return isApplicationFlagSet(packageName, userId, ApplicationInfo.FLAG_ALLOW_BACKUP);
Makoto Onuki0acbb142016-03-22 17:02:57 -07003072 }
3073
Makoto Onuki2e210c42016-03-30 08:30:36 -07003074 boolean shouldBackupApp(PackageInfo pi) {
3075 return (pi.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0;
3076 }
3077
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003078 @Override
Makoto Onuki2e210c42016-03-30 08:30:36 -07003079 public byte[] getBackupPayload(@UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003080 enforceSystem();
3081 if (DEBUG) {
3082 Slog.d(TAG, "Backing up user " + userId);
3083 }
3084 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003085 if (!isUserUnlockedL(userId)) {
3086 wtf("Can't backup: user " + userId + " is locked or not running");
3087 return null;
3088 }
3089
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003090 final ShortcutUser user = getUserShortcutsLocked(userId);
3091 if (user == null) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003092 wtf("Can't backup: user not found: id=" + userId);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003093 return null;
3094 }
3095
Makoto Onukic51b2872016-05-04 15:24:50 -07003096 user.forAllPackageItems(spi -> spi.refreshPackageInfoAndSave());
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003097
3098 // Then save.
3099 final ByteArrayOutputStream os = new ByteArrayOutputStream(32 * 1024);
3100 try {
3101 saveUserInternalLocked(userId, os, /* forBackup */ true);
Makoto Onukib08790c2016-06-23 14:05:46 -07003102 } catch (XmlPullParserException | IOException e) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003103 // Shouldn't happen.
3104 Slog.w(TAG, "Backup failed.", e);
3105 return null;
3106 }
3107 return os.toByteArray();
3108 }
3109 }
3110
3111 @Override
Makoto Onuki2e210c42016-03-30 08:30:36 -07003112 public void applyRestore(byte[] payload, @UserIdInt int userId) {
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003113 enforceSystem();
3114 if (DEBUG) {
3115 Slog.d(TAG, "Restoring user " + userId);
3116 }
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003117 synchronized (mLock) {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003118 if (!isUserUnlockedL(userId)) {
3119 wtf("Can't restore: user " + userId + " is locked or not running");
3120 return;
3121 }
3122 final ShortcutUser user;
3123 final ByteArrayInputStream is = new ByteArrayInputStream(payload);
3124 try {
3125 user = loadUserInternal(userId, is, /* fromBackup */ true);
3126 } catch (XmlPullParserException | IOException e) {
3127 Slog.w(TAG, "Restoration failed.", e);
3128 return;
3129 }
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003130 mUsers.put(userId, user);
Makoto Onuki2e210c42016-03-30 08:30:36 -07003131
Makoto Onuki377b7972016-08-09 14:43:55 -07003132 // Rescan all packages to re-publish manifest shortcuts and do other checks.
3133 rescanUpdatedPackagesLocked(userId,
3134 0, // lastScanTime = 0; rescan all packages.
3135 /* forceRescan= */ true);
Makoto Onuki2e210c42016-03-30 08:30:36 -07003136
3137 saveUserLocked(userId);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07003138 }
Makoto Onukicdc78f72016-03-21 15:47:52 -07003139 }
3140
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003141 // === Dump ===
3142
3143 @Override
3144 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Makoto Onuki76269922016-07-15 14:58:54 -07003145 enforceCallingOrSelfPermission(android.Manifest.permission.DUMP,
3146 "can't dump by this caller");
3147 boolean checkin = false;
3148 boolean clear = false;
3149 if (args != null) {
3150 for (String arg : args) {
3151 if ("-c".equals(arg)) {
3152 checkin = true;
3153 } else if ("--checkin".equals(arg)) {
3154 checkin = true;
3155 clear = true;
3156 }
3157 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003158 }
Makoto Onuki76269922016-07-15 14:58:54 -07003159
3160 if (checkin) {
3161 dumpCheckin(pw, clear);
3162 } else {
3163 dumpInner(pw);
3164 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003165 }
3166
Makoto Onuki76269922016-07-15 14:58:54 -07003167 private void dumpInner(PrintWriter pw) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003168 synchronized (mLock) {
3169 final long now = injectCurrentTimeMillis();
3170 pw.print("Now: [");
3171 pw.print(now);
3172 pw.print("] ");
3173 pw.print(formatTime(now));
Makoto Onuki55046222016-03-08 10:49:47 -08003174
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003175 pw.print(" Raw last reset: [");
3176 pw.print(mRawLastResetTime);
3177 pw.print("] ");
3178 pw.print(formatTime(mRawLastResetTime));
3179
3180 final long last = getLastResetTimeLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003181 pw.print(" Last reset: [");
3182 pw.print(last);
3183 pw.print("] ");
3184 pw.print(formatTime(last));
3185
Makoto Onuki55046222016-03-08 10:49:47 -08003186 final long next = getNextResetTimeLocked();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003187 pw.print(" Next reset: [");
3188 pw.print(next);
3189 pw.print("] ");
3190 pw.print(formatTime(next));
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003191
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003192 pw.print(" Config:");
3193 pw.print(" Max icon dim: ");
3194 pw.println(mMaxIconDimension);
3195 pw.print(" Icon format: ");
3196 pw.println(mIconPersistFormat);
3197 pw.print(" Icon quality: ");
Makoto Onuki2e210c42016-03-30 08:30:36 -07003198 pw.println(mIconPersistQuality);
Makoto Onuki0033b2a2016-04-14 17:19:16 -07003199 pw.print(" saveDelayMillis: ");
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003200 pw.println(mSaveDelayMillis);
Makoto Onuki0033b2a2016-04-14 17:19:16 -07003201 pw.print(" resetInterval: ");
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003202 pw.println(mResetInterval);
Makoto Onuki0033b2a2016-04-14 17:19:16 -07003203 pw.print(" maxUpdatesPerInterval: ");
Makoto Onukib6d35232016-04-04 15:57:17 -07003204 pw.println(mMaxUpdatesPerInterval);
Makoto Onukib08790c2016-06-23 14:05:46 -07003205 pw.print(" maxShortcutsPerActivity: ");
Makoto Onukib5a012f2016-06-21 11:13:53 -07003206 pw.println(mMaxShortcuts);
Makoto Onuki55046222016-03-08 10:49:47 -08003207 pw.println();
3208
Makoto Onuki2e210c42016-03-30 08:30:36 -07003209 pw.println(" Stats:");
3210 synchronized (mStatLock) {
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003211 final String p = " ";
Makoto Onuki2e210c42016-03-30 08:30:36 -07003212 dumpStatLS(pw, p, Stats.GET_DEFAULT_HOME, "getHomeActivities()");
3213 dumpStatLS(pw, p, Stats.LAUNCHER_PERMISSION_CHECK, "Launcher permission check");
3214
3215 dumpStatLS(pw, p, Stats.GET_PACKAGE_INFO, "getPackageInfo()");
3216 dumpStatLS(pw, p, Stats.GET_PACKAGE_INFO_WITH_SIG, "getPackageInfo(SIG)");
3217 dumpStatLS(pw, p, Stats.GET_APPLICATION_INFO, "getApplicationInfo");
Makoto Onuki6c1dbd52016-05-02 15:19:32 -07003218 dumpStatLS(pw, p, Stats.CLEANUP_DANGLING_BITMAPS, "cleanupDanglingBitmaps");
Makoto Onukib08790c2016-06-23 14:05:46 -07003219 dumpStatLS(pw, p, Stats.GET_ACTIVITY_WITH_METADATA, "getActivity+metadata");
Makoto Onuki6dd9fb72016-06-01 13:55:54 -07003220 dumpStatLS(pw, p, Stats.GET_INSTALLED_PACKAGES, "getInstalledPackages");
Makoto Onuki22fcc682016-05-17 14:52:19 -07003221 dumpStatLS(pw, p, Stats.CHECK_PACKAGE_CHANGES, "checkPackageChanges");
Makoto Onuki157b1622016-06-02 16:13:10 -07003222 dumpStatLS(pw, p, Stats.GET_APPLICATION_RESOURCES, "getApplicationResources");
3223 dumpStatLS(pw, p, Stats.RESOURCE_NAME_LOOKUP, "resourceNameLookup");
Makoto Onukib08790c2016-06-23 14:05:46 -07003224 dumpStatLS(pw, p, Stats.GET_LAUNCHER_ACTIVITY, "getLauncherActivity");
3225 dumpStatLS(pw, p, Stats.CHECK_LAUNCHER_ACTIVITY, "checkLauncherActivity");
Makoto Onukiee6b6e42016-06-29 17:34:02 -07003226 dumpStatLS(pw, p, Stats.IS_ACTIVITY_ENABLED, "isActivityEnabled");
Makoto Onuki4e6cef42016-07-13 16:14:01 -07003227 dumpStatLS(pw, p, Stats.PACKAGE_UPDATE_CHECK, "packageUpdateCheck");
Makoto Onuki2e210c42016-03-30 08:30:36 -07003228 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003229
Makoto Onukia2241832016-07-06 13:28:37 -07003230 pw.println();
3231 pw.print(" #Failures: ");
3232 pw.println(mWtfCount);
3233
3234 if (mLastWtfStacktrace != null) {
3235 pw.print(" Last failure stack trace: ");
3236 pw.println(Log.getStackTraceString(mLastWtfStacktrace));
3237 }
3238
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08003239 for (int i = 0; i < mUsers.size(); i++) {
3240 pw.println();
Makoto Onukic51b2872016-05-04 15:24:50 -07003241 mUsers.valueAt(i).dump(pw, " ");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003242 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003243
3244 pw.println();
3245 pw.println(" UID state:");
3246
3247 for (int i = 0; i < mUidState.size(); i++) {
3248 final int uid = mUidState.keyAt(i);
3249 final int state = mUidState.valueAt(i);
3250 pw.print(" UID=");
3251 pw.print(uid);
3252 pw.print(" state=");
3253 pw.print(state);
3254 if (isProcessStateForeground(state)) {
3255 pw.print(" [FG]");
3256 }
3257 pw.print(" last FG=");
3258 pw.print(mUidLastForegroundElapsedTime.get(uid));
3259 pw.println();
3260 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003261 }
3262 }
3263
Makoto Onuki41066a62016-03-09 16:18:44 -08003264 static String formatTime(long time) {
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003265 Time tobj = new Time();
3266 tobj.set(time);
3267 return tobj.format("%Y-%m-%d %H:%M:%S");
3268 }
3269
Makoto Onuki2e210c42016-03-30 08:30:36 -07003270 private void dumpStatLS(PrintWriter pw, String prefix, int statId, String label) {
3271 pw.print(prefix);
3272 final int count = mCountStats[statId];
3273 final long dur = mDurationStats[statId];
3274 pw.println(String.format("%s: count=%d, total=%dms, avg=%.1fms",
3275 label, count, dur,
3276 (count == 0 ? 0 : ((double) dur) / count)));
3277 }
3278
Makoto Onuki76269922016-07-15 14:58:54 -07003279 /**
3280 * Dumpsys for checkin.
3281 *
3282 * @param clear if true, clear the history information. Some other system services have this
3283 * behavior but shortcut service doesn't for now.
3284 */
3285 private void dumpCheckin(PrintWriter pw, boolean clear) {
3286 synchronized (mLock) {
3287 try {
3288 final JSONArray users = new JSONArray();
3289
3290 for (int i = 0; i < mUsers.size(); i++) {
3291 users.put(mUsers.valueAt(i).dumpCheckin(clear));
3292 }
3293
3294 final JSONObject result = new JSONObject();
3295
3296 result.put(KEY_SHORTCUT, users);
3297 result.put(KEY_LOW_RAM, injectIsLowRamDevice());
3298 result.put(KEY_ICON_SIZE, mMaxIconDimension);
3299
3300 pw.println(result.toString(1));
3301 } catch (JSONException e) {
3302 Slog.e(TAG, "Unable to write in json", e);
3303 }
3304 }
3305 }
3306
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003307 // === Shell support ===
3308
3309 @Override
3310 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
3311 String[] args, ResultReceiver resultReceiver) throws RemoteException {
3312
3313 enforceShell();
3314
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07003315 final long token = injectClearCallingIdentity();
3316 try {
3317 final int status = (new MyShellCommand()).exec(this, in, out, err, args, resultReceiver);
3318 resultReceiver.send(status, null);
3319 } finally {
3320 injectRestoreCallingIdentity(token);
3321 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003322 }
3323
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003324 static class CommandException extends Exception {
3325 public CommandException(String message) {
3326 super(message);
3327 }
3328 }
3329
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003330 /**
3331 * Handle "adb shell cmd".
3332 */
3333 private class MyShellCommand extends ShellCommand {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003334
3335 private int mUserId = UserHandle.USER_SYSTEM;
3336
Makoto Onuki02f338e2016-07-29 09:40:40 -07003337 private void parseOptionsLocked(boolean takeUser)
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003338 throws CommandException {
3339 String opt;
3340 while ((opt = getNextOption()) != null) {
3341 switch (opt) {
3342 case "--user":
3343 if (takeUser) {
3344 mUserId = UserHandle.parseUserArg(getNextArgRequired());
Makoto Onuki02f338e2016-07-29 09:40:40 -07003345 if (!isUserUnlockedL(mUserId)) {
Makoto Onukif34c3082016-07-13 10:25:25 -07003346 throw new CommandException(
3347 "User " + mUserId + " is not running or locked");
3348 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003349 break;
3350 }
3351 // fallthrough
3352 default:
3353 throw new CommandException("Unknown option: " + opt);
3354 }
3355 }
3356 }
3357
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003358 @Override
3359 public int onCommand(String cmd) {
3360 if (cmd == null) {
3361 return handleDefaultCommands(cmd);
3362 }
3363 final PrintWriter pw = getOutPrintWriter();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003364 try {
3365 switch (cmd) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003366 case "reset-throttling":
3367 handleResetThrottling();
3368 break;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003369 case "reset-all-throttling":
3370 handleResetAllThrottling();
3371 break;
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003372 case "override-config":
3373 handleOverrideConfig();
3374 break;
3375 case "reset-config":
3376 handleResetConfig();
3377 break;
3378 case "clear-default-launcher":
3379 handleClearDefaultLauncher();
3380 break;
3381 case "get-default-launcher":
3382 handleGetDefaultLauncher();
3383 break;
Makoto Onukiac214972016-04-04 10:19:45 -07003384 case "unload-user":
3385 handleUnloadUser();
3386 break;
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003387 case "clear-shortcuts":
3388 handleClearShortcuts();
3389 break;
Makoto Onukib08790c2016-06-23 14:05:46 -07003390 case "verify-states": // hidden command to verify various internal states.
3391 handleVerifyStates();
3392 break;
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003393 default:
3394 return handleDefaultCommands(cmd);
3395 }
3396 } catch (CommandException e) {
3397 pw.println("Error: " + e.getMessage());
3398 return 1;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003399 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003400 pw.println("Success");
3401 return 0;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003402 }
3403
3404 @Override
3405 public void onHelp() {
3406 final PrintWriter pw = getOutPrintWriter();
3407 pw.println("Usage: cmd shortcut COMMAND [options ...]");
3408 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003409 pw.println("cmd shortcut reset-throttling [--user USER_ID]");
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003410 pw.println(" Reset throttling for all packages and users");
3411 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003412 pw.println("cmd shortcut reset-all-throttling");
3413 pw.println(" Reset the throttling state for all users");
3414 pw.println();
Makoto Onuki4362a662016-03-08 18:59:09 -08003415 pw.println("cmd shortcut override-config CONFIG");
3416 pw.println(" Override the configuration for testing (will last until reboot)");
3417 pw.println();
3418 pw.println("cmd shortcut reset-config");
3419 pw.println(" Reset the configuration set with \"update-config\"");
3420 pw.println();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003421 pw.println("cmd shortcut clear-default-launcher [--user USER_ID]");
3422 pw.println(" Clear the cached default launcher");
3423 pw.println();
3424 pw.println("cmd shortcut get-default-launcher [--user USER_ID]");
Makoto Onuki0b9d1db2016-07-18 14:16:41 -07003425 pw.println(" Show the default launcher");
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003426 pw.println();
Makoto Onukiac214972016-04-04 10:19:45 -07003427 pw.println("cmd shortcut unload-user [--user USER_ID]");
3428 pw.println(" Unload a user from the memory");
3429 pw.println(" (This should not affect any observable behavior)");
3430 pw.println();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003431 pw.println("cmd shortcut clear-shortcuts [--user USER_ID] PACKAGE");
3432 pw.println(" Remove all shortcuts from a package, including pinned shortcuts");
3433 pw.println();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003434 }
3435
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003436 private void handleResetThrottling() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003437 synchronized (mLock) {
3438 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki4554d0e2016-03-14 15:51:41 -07003439
Makoto Onuki02f338e2016-07-29 09:40:40 -07003440 Slog.i(TAG, "cmd: handleResetThrottling: user=" + mUserId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003441
Makoto Onuki02f338e2016-07-29 09:40:40 -07003442 resetThrottlingInner(mUserId);
3443 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003444 }
3445
3446 private void handleResetAllThrottling() {
3447 Slog.i(TAG, "cmd: handleResetAllThrottling");
3448
3449 resetAllThrottlingInner();
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003450 }
3451
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003452 private void handleOverrideConfig() throws CommandException {
Makoto Onuki4362a662016-03-08 18:59:09 -08003453 final String config = getNextArgRequired();
3454
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003455 Slog.i(TAG, "cmd: handleOverrideConfig: " + config);
3456
Makoto Onuki4362a662016-03-08 18:59:09 -08003457 synchronized (mLock) {
3458 if (!updateConfigurationLocked(config)) {
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003459 throw new CommandException("override-config failed. See logcat for details.");
Makoto Onuki4362a662016-03-08 18:59:09 -08003460 }
3461 }
Makoto Onuki4362a662016-03-08 18:59:09 -08003462 }
3463
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003464 private void handleResetConfig() {
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003465 Slog.i(TAG, "cmd: handleResetConfig");
3466
Makoto Onuki4362a662016-03-08 18:59:09 -08003467 synchronized (mLock) {
3468 loadConfigurationLocked();
3469 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003470 }
3471
3472 private void clearLauncher() {
3473 synchronized (mLock) {
Makoto Onuki10305202016-07-14 18:14:08 -07003474 getUserShortcutsLocked(mUserId).forceClearLauncher();
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003475 }
3476 }
3477
3478 private void showLauncher() {
3479 synchronized (mLock) {
3480 // This ensures to set the cached launcher. Package name doesn't matter.
3481 hasShortcutHostPermissionInner("-", mUserId);
3482
3483 getOutPrintWriter().println("Launcher: "
Makoto Onuki10305202016-07-14 18:14:08 -07003484 + getUserShortcutsLocked(mUserId).getLastKnownLauncher());
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003485 }
3486 }
3487
3488 private void handleClearDefaultLauncher() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003489 synchronized (mLock) {
3490 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003491
Makoto Onuki02f338e2016-07-29 09:40:40 -07003492 clearLauncher();
3493 }
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003494 }
3495
3496 private void handleGetDefaultLauncher() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003497 synchronized (mLock) {
3498 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onuki2d5b4652016-03-11 16:09:54 -08003499
Makoto Onuki02f338e2016-07-29 09:40:40 -07003500 clearLauncher();
3501 showLauncher();
3502 }
Makoto Onuki4362a662016-03-08 18:59:09 -08003503 }
Makoto Onukiac214972016-04-04 10:19:45 -07003504
3505 private void handleUnloadUser() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003506 synchronized (mLock) {
3507 parseOptionsLocked(/* takeUser =*/ true);
Makoto Onukiac214972016-04-04 10:19:45 -07003508
Makoto Onuki02f338e2016-07-29 09:40:40 -07003509 Slog.i(TAG, "cmd: handleUnloadUser: user=" + mUserId);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003510
Makoto Onuki02f338e2016-07-29 09:40:40 -07003511 ShortcutService.this.handleCleanupUser(mUserId);
3512 }
Makoto Onukiac214972016-04-04 10:19:45 -07003513 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003514
3515 private void handleClearShortcuts() throws CommandException {
Makoto Onuki02f338e2016-07-29 09:40:40 -07003516 synchronized (mLock) {
3517 parseOptionsLocked(/* takeUser =*/ true);
3518 final String packageName = getNextArgRequired();
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003519
Makoto Onuki02f338e2016-07-29 09:40:40 -07003520 Slog.i(TAG, "cmd: handleClearShortcuts: user" + mUserId + ", " + packageName);
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003521
Makoto Onuki02f338e2016-07-29 09:40:40 -07003522 ShortcutService.this.cleanUpPackageForAllLoadedUsers(packageName, mUserId,
3523 /* appStillExists = */ true);
3524 }
Makoto Onukib08790c2016-06-23 14:05:46 -07003525 }
3526
3527 private void handleVerifyStates() throws CommandException {
3528 try {
3529 verifyStatesForce(); // This will throw when there's an issue.
3530 } catch (Throwable th) {
3531 throw new CommandException(th.getMessage() + "\n" + Log.getStackTraceString(th));
3532 }
Makoto Onuki5ba0d3e2016-04-11 14:03:46 -07003533 }
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003534 }
3535
3536 // === Unit test support ===
3537
3538 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07003539 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003540 long injectCurrentTimeMillis() {
3541 return System.currentTimeMillis();
3542 }
3543
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003544 @VisibleForTesting
3545 long injectElapsedRealtime() {
3546 return SystemClock.elapsedRealtime();
3547 }
3548
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003549 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07003550 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003551 int injectBinderCallingUid() {
3552 return getCallingUid();
3553 }
3554
Makoto Onuki31459242016-03-22 11:12:18 -07003555 private int getCallingUserId() {
Makoto Onuki4554d0e2016-03-14 15:51:41 -07003556 return UserHandle.getUserId(injectBinderCallingUid());
3557 }
3558
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07003559 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07003560 @VisibleForTesting
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07003561 long injectClearCallingIdentity() {
3562 return Binder.clearCallingIdentity();
3563 }
3564
3565 // Injection point.
Makoto Onuki31459242016-03-22 11:12:18 -07003566 @VisibleForTesting
Makoto Onuki4dbe0de2016-03-14 17:31:49 -07003567 void injectRestoreCallingIdentity(long token) {
3568 Binder.restoreCallingIdentity(token);
3569 }
3570
Makoto Onukide667372016-03-15 14:29:20 -07003571 final void wtf(String message) {
Makoto Onukib08790c2016-06-23 14:05:46 -07003572 wtf(message, /* exception= */ null);
Makoto Onukide667372016-03-15 14:29:20 -07003573 }
3574
Makoto Onuki2e210c42016-03-30 08:30:36 -07003575 // Injection point.
Makoto Onukia2241832016-07-06 13:28:37 -07003576 void wtf(String message, Throwable e) {
3577 if (e == null) {
3578 e = new RuntimeException("Stacktrace");
3579 }
3580 synchronized (mLock) {
3581 mWtfCount++;
3582 mLastWtfStacktrace = new Exception("Last failure was logged here:");
3583 }
Makoto Onukide667372016-03-15 14:29:20 -07003584 Slog.wtf(TAG, message, e);
3585 }
3586
Makoto Onuki31459242016-03-22 11:12:18 -07003587 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003588 File injectSystemDataPath() {
3589 return Environment.getDataSystemDirectory();
3590 }
3591
Makoto Onuki31459242016-03-22 11:12:18 -07003592 @VisibleForTesting
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003593 File injectUserDataPath(@UserIdInt int userId) {
Makoto Onuki55046222016-03-08 10:49:47 -08003594 return new File(Environment.getDataSystemCeDirectory(userId), DIRECTORY_PER_USER);
3595 }
3596
Makoto Onuki4362a662016-03-08 18:59:09 -08003597 @VisibleForTesting
Makoto Onuki55046222016-03-08 10:49:47 -08003598 boolean injectIsLowRamDevice() {
3599 return ActivityManager.isLowRamDeviceStatic();
3600 }
3601
Makoto Onuki31459242016-03-22 11:12:18 -07003602 @VisibleForTesting
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07003603 void injectRegisterUidObserver(IUidObserver observer, int which) {
3604 try {
3605 ActivityManagerNative.getDefault().registerUidObserver(observer, which);
3606 } catch (RemoteException shouldntHappen) {
3607 }
3608 }
3609
Makoto Onuki55046222016-03-08 10:49:47 -08003610 File getUserBitmapFilePath(@UserIdInt int userId) {
3611 return new File(injectUserDataPath(userId), DIRECTORY_BITMAPS);
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003612 }
3613
3614 @VisibleForTesting
Makoto Onuki31459242016-03-22 11:12:18 -07003615 SparseArray<ShortcutUser> getShortcutsForTest() {
Makoto Onuki3f4b1ca2016-03-11 13:44:32 -08003616 return mUsers;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003617 }
3618
3619 @VisibleForTesting
Makoto Onukib5a012f2016-06-21 11:13:53 -07003620 int getMaxShortcutsForTest() {
3621 return mMaxShortcuts;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003622 }
3623
3624 @VisibleForTesting
Makoto Onukib6d35232016-04-04 15:57:17 -07003625 int getMaxUpdatesPerIntervalForTest() {
3626 return mMaxUpdatesPerInterval;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003627 }
3628
3629 @VisibleForTesting
Makoto Onuki4362a662016-03-08 18:59:09 -08003630 long getResetIntervalForTest() {
3631 return mResetInterval;
Makoto Onuki55046222016-03-08 10:49:47 -08003632 }
3633
3634 @VisibleForTesting
Makoto Onuki4362a662016-03-08 18:59:09 -08003635 int getMaxIconDimensionForTest() {
3636 return mMaxIconDimension;
3637 }
3638
3639 @VisibleForTesting
3640 CompressFormat getIconPersistFormatForTest() {
3641 return mIconPersistFormat;
3642 }
3643
3644 @VisibleForTesting
3645 int getIconPersistQualityForTest() {
3646 return mIconPersistQuality;
Makoto Onuki6f7362d92016-03-04 13:39:41 -08003647 }
Makoto Onuki41066a62016-03-09 16:18:44 -08003648
3649 @VisibleForTesting
Makoto Onuki22fcc682016-05-17 14:52:19 -07003650 ShortcutPackage getPackageShortcutForTest(String packageName, int userId) {
Makoto Onuki41066a62016-03-09 16:18:44 -08003651 synchronized (mLock) {
Makoto Onuki31459242016-03-22 11:12:18 -07003652 final ShortcutUser user = mUsers.get(userId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07003653 if (user == null) return null;
3654
Makoto Onuki22fcc682016-05-17 14:52:19 -07003655 return user.getAllPackagesForTest().get(packageName);
3656 }
3657 }
3658
3659 @VisibleForTesting
3660 ShortcutInfo getPackageShortcutForTest(String packageName, String shortcutId, int userId) {
3661 synchronized (mLock) {
Makoto Onukif34c3082016-07-13 10:25:25 -07003662 final ShortcutPackage pkg = getPackageShortcutForTest(packageName, userId);
Makoto Onukicdc78f72016-03-21 15:47:52 -07003663 if (pkg == null) return null;
3664
3665 return pkg.findShortcutById(shortcutId);
Makoto Onuki41066a62016-03-09 16:18:44 -08003666 }
3667 }
Makoto Onuki7001a612016-05-27 13:24:28 -07003668
3669 /**
3670 * Control whether {@link #verifyStates} should be performed. We always perform it during unit
3671 * tests.
3672 */
3673 @VisibleForTesting
3674 boolean injectShouldPerformVerification() {
3675 return DEBUG;
3676 }
3677
3678 /**
3679 * Check various internal states and throws if there's any inconsistency.
3680 * This is normally only enabled during unit tests.
3681 */
3682 final void verifyStates() {
3683 if (injectShouldPerformVerification()) {
3684 verifyStatesInner();
3685 }
3686 }
3687
Makoto Onukib08790c2016-06-23 14:05:46 -07003688 private final void verifyStatesForce() {
3689 verifyStatesInner();
3690 }
3691
Makoto Onuki7001a612016-05-27 13:24:28 -07003692 private void verifyStatesInner() {
Makoto Onuki10305202016-07-14 18:14:08 -07003693 synchronized (mLock) {
Makoto Onuki7001a612016-05-27 13:24:28 -07003694 forEachLoadedUserLocked(u -> u.forAllPackageItems(ShortcutPackageItem::verifyStates));
3695 }
3696 }
Makoto Onuki41066a62016-03-09 16:18:44 -08003697}