blob: d558b07a7a70ccfd4398e42c2f1e7b1a7d22d3c8 [file] [log] [blame]
Makoto Onuki31459242016-03-22 11:12:18 -07001/*
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
18import android.annotation.NonNull;
19import android.annotation.Nullable;
Makoto Onukiabe84422016-04-07 09:41:19 -070020import android.annotation.UserIdInt;
Makoto Onuki31459242016-03-22 11:12:18 -070021import android.content.ComponentName;
22import android.content.Intent;
Makoto Onuki22fcc682016-05-17 14:52:19 -070023import android.content.pm.PackageInfo;
Makoto Onuki31459242016-03-22 11:12:18 -070024import android.content.pm.ShortcutInfo;
Makoto Onuki157b1622016-06-02 16:13:10 -070025import android.content.res.Resources;
Makoto Onuki31459242016-03-22 11:12:18 -070026import android.os.PersistableBundle;
27import android.text.format.Formatter;
28import android.util.ArrayMap;
29import android.util.ArraySet;
Makoto Onuki7001a612016-05-27 13:24:28 -070030import android.util.Log;
Makoto Onuki31459242016-03-22 11:12:18 -070031import android.util.Slog;
32
Makoto Onuki2e210c42016-03-30 08:30:36 -070033import com.android.internal.annotations.VisibleForTesting;
Makoto Onuki22fcc682016-05-17 14:52:19 -070034import com.android.internal.util.Preconditions;
Makoto Onukib6d35232016-04-04 15:57:17 -070035import com.android.internal.util.XmlUtils;
Makoto Onuki7001a612016-05-27 13:24:28 -070036import com.android.server.pm.ShortcutService.ShortcutOperation;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070037import com.android.server.pm.ShortcutService.Stats;
Makoto Onuki2e210c42016-03-30 08:30:36 -070038
Makoto Onuki76269922016-07-15 14:58:54 -070039import org.json.JSONException;
40import org.json.JSONObject;
Makoto Onuki31459242016-03-22 11:12:18 -070041import org.xmlpull.v1.XmlPullParser;
42import org.xmlpull.v1.XmlPullParserException;
43import org.xmlpull.v1.XmlSerializer;
44
45import java.io.File;
46import java.io.IOException;
47import java.io.PrintWriter;
48import java.util.ArrayList;
Makoto Onuki7001a612016-05-27 13:24:28 -070049import java.util.Collections;
50import java.util.Comparator;
Makoto Onuki31459242016-03-22 11:12:18 -070051import java.util.List;
Makoto Onukibe73a802016-04-15 14:46:35 -070052import java.util.Set;
Makoto Onuki31459242016-03-22 11:12:18 -070053import java.util.function.Predicate;
54
55/**
56 * Package information used by {@link ShortcutService}.
Makoto Onuki22fcc682016-05-17 14:52:19 -070057 * User information used by {@link ShortcutService}.
58 *
59 * All methods should be guarded by {@code #mShortcutUser.mService.mLock}.
Makoto Onuki31459242016-03-22 11:12:18 -070060 */
Makoto Onuki9da23fc2016-03-29 11:14:42 -070061class ShortcutPackage extends ShortcutPackageItem {
Makoto Onuki31459242016-03-22 11:12:18 -070062 private static final String TAG = ShortcutService.TAG;
Makoto Onuki9e1f5592016-06-08 12:30:23 -070063 private static final String TAG_VERIFY = ShortcutService.TAG + ".verify";
Makoto Onuki31459242016-03-22 11:12:18 -070064
65 static final String TAG_ROOT = "package";
Makoto Onuki440a1ea2016-07-20 14:21:18 -070066 private static final String TAG_INTENT_EXTRAS_LEGACY = "intent-extras";
67 private static final String TAG_INTENT = "intent";
Makoto Onuki31459242016-03-22 11:12:18 -070068 private static final String TAG_EXTRAS = "extras";
69 private static final String TAG_SHORTCUT = "shortcut";
Makoto Onukib6d35232016-04-04 15:57:17 -070070 private static final String TAG_CATEGORIES = "categories";
Makoto Onuki31459242016-03-22 11:12:18 -070071
72 private static final String ATTR_NAME = "name";
Makoto Onuki31459242016-03-22 11:12:18 -070073 private static final String ATTR_CALL_COUNT = "call-count";
74 private static final String ATTR_LAST_RESET = "last-reset";
75 private static final String ATTR_ID = "id";
76 private static final String ATTR_ACTIVITY = "activity";
77 private static final String ATTR_TITLE = "title";
Makoto Onuki20c95f82016-05-11 16:51:01 -070078 private static final String ATTR_TITLE_RES_ID = "titleid";
Makoto Onuki157b1622016-06-02 16:13:10 -070079 private static final String ATTR_TITLE_RES_NAME = "titlename";
Makoto Onukie3ae7ec2016-03-29 15:45:25 -070080 private static final String ATTR_TEXT = "text";
Makoto Onuki20c95f82016-05-11 16:51:01 -070081 private static final String ATTR_TEXT_RES_ID = "textid";
Makoto Onuki157b1622016-06-02 16:13:10 -070082 private static final String ATTR_TEXT_RES_NAME = "textname";
Makoto Onuki20c95f82016-05-11 16:51:01 -070083 private static final String ATTR_DISABLED_MESSAGE = "dmessage";
84 private static final String ATTR_DISABLED_MESSAGE_RES_ID = "dmessageid";
Makoto Onuki157b1622016-06-02 16:13:10 -070085 private static final String ATTR_DISABLED_MESSAGE_RES_NAME = "dmessagename";
Makoto Onuki440a1ea2016-07-20 14:21:18 -070086 private static final String ATTR_INTENT_LEGACY = "intent";
87 private static final String ATTR_INTENT_NO_EXTRA = "intent-base";
Makoto Onuki20c95f82016-05-11 16:51:01 -070088 private static final String ATTR_RANK = "rank";
Makoto Onuki31459242016-03-22 11:12:18 -070089 private static final String ATTR_TIMESTAMP = "timestamp";
90 private static final String ATTR_FLAGS = "flags";
Makoto Onuki157b1622016-06-02 16:13:10 -070091 private static final String ATTR_ICON_RES_ID = "icon-res";
92 private static final String ATTR_ICON_RES_NAME = "icon-resname";
Makoto Onuki31459242016-03-22 11:12:18 -070093 private static final String ATTR_BITMAP_PATH = "bitmap-path";
94
Makoto Onukib6d35232016-04-04 15:57:17 -070095 private static final String NAME_CATEGORIES = "categories";
96
97 private static final String TAG_STRING_ARRAY_XMLUTILS = "string-array";
98 private static final String ATTR_NAME_XMLUTILS = "name";
99
Makoto Onuki76269922016-07-15 14:58:54 -0700100 private static final String KEY_DYNAMIC = "dynamic";
101 private static final String KEY_MANIFEST = "manifest";
102 private static final String KEY_PINNED = "pinned";
103 private static final String KEY_BITMAPS = "bitmaps";
104 private static final String KEY_BITMAP_BYTES = "bitmapBytes";
105
Makoto Onuki31459242016-03-22 11:12:18 -0700106 /**
107 * All the shortcuts from the package, keyed on IDs.
108 */
109 final private ArrayMap<String, ShortcutInfo> mShortcuts = new ArrayMap<>();
110
111 /**
Makoto Onuki31459242016-03-22 11:12:18 -0700112 * # of times the package has called rate-limited APIs.
113 */
114 private int mApiCallCount;
115
116 /**
117 * When {@link #mApiCallCount} was reset last time.
118 */
119 private long mLastResetTime;
120
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700121 private final int mPackageUid;
122
123 private long mLastKnownForegroundElapsedTime;
124
Makoto Onukic51b2872016-05-04 15:24:50 -0700125 private ShortcutPackage(ShortcutUser shortcutUser,
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700126 int packageUserId, String packageName, ShortcutPackageInfo spi) {
127 super(shortcutUser, packageUserId, packageName,
128 spi != null ? spi : ShortcutPackageInfo.newEmpty());
129
Makoto Onukic51b2872016-05-04 15:24:50 -0700130 mPackageUid = shortcutUser.mService.injectGetPackageUid(packageName, packageUserId);
Makoto Onuki31459242016-03-22 11:12:18 -0700131 }
132
Makoto Onukic51b2872016-05-04 15:24:50 -0700133 public ShortcutPackage(ShortcutUser shortcutUser, int packageUserId, String packageName) {
134 this(shortcutUser, packageUserId, packageName, null);
Makoto Onuki0acbb142016-03-22 17:02:57 -0700135 }
136
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700137 @Override
138 public int getOwnerUserId() {
139 // For packages, always owner user == package user.
140 return getPackageUserId();
Makoto Onuki0acbb142016-03-22 17:02:57 -0700141 }
142
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700143 public int getPackageUid() {
144 return mPackageUid;
145 }
146
Makoto Onuki157b1622016-06-02 16:13:10 -0700147 @Nullable
148 public Resources getPackageResources() {
149 return mShortcutUser.mService.injectGetResourcesForApplicationAsUser(
150 getPackageName(), getPackageUserId());
151 }
152
Makoto Onuki2e210c42016-03-30 08:30:36 -0700153 @Override
Makoto Onukic51b2872016-05-04 15:24:50 -0700154 protected void onRestoreBlocked() {
Makoto Onuki2e210c42016-03-30 08:30:36 -0700155 // Can't restore due to version/signature mismatch. Remove all shortcuts.
156 mShortcuts.clear();
157 }
158
159 @Override
Makoto Onukic51b2872016-05-04 15:24:50 -0700160 protected void onRestored() {
Makoto Onuki2e210c42016-03-30 08:30:36 -0700161 // Because some launchers may not have been restored (e.g. allowBackup=false),
162 // we need to re-calculate the pinned shortcuts.
Makoto Onukic51b2872016-05-04 15:24:50 -0700163 refreshPinnedFlags();
Makoto Onuki2e210c42016-03-30 08:30:36 -0700164 }
165
Makoto Onukid99c6f02016-03-28 11:02:54 -0700166 /**
167 * Note this does *not* provide a correct view to the calling launcher.
168 */
Makoto Onuki31459242016-03-22 11:12:18 -0700169 @Nullable
170 public ShortcutInfo findShortcutById(String id) {
171 return mShortcuts.get(id);
172 }
173
Makoto Onuki22fcc682016-05-17 14:52:19 -0700174 private void ensureNotImmutable(@Nullable ShortcutInfo shortcut) {
175 if (shortcut != null && shortcut.isImmutable()) {
176 throw new IllegalArgumentException(
177 "Manifest shortcut ID=" + shortcut.getId()
178 + " may not be manipulated via APIs");
179 }
180 }
181
182 private void ensureNotImmutable(@NonNull String id) {
183 ensureNotImmutable(mShortcuts.get(id));
184 }
185
186 public void ensureImmutableShortcutsNotIncludedWithIds(@NonNull List<String> shortcutIds) {
187 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
188 ensureNotImmutable(shortcutIds.get(i));
189 }
190 }
191
192 public void ensureImmutableShortcutsNotIncluded(@NonNull List<ShortcutInfo> shortcuts) {
193 for (int i = shortcuts.size() - 1; i >= 0; i--) {
194 ensureNotImmutable(shortcuts.get(i).getId());
195 }
196 }
197
198 private ShortcutInfo deleteShortcutInner(@NonNull String id) {
Makoto Onuki31459242016-03-22 11:12:18 -0700199 final ShortcutInfo shortcut = mShortcuts.remove(id);
200 if (shortcut != null) {
Makoto Onukic51b2872016-05-04 15:24:50 -0700201 mShortcutUser.mService.removeIcon(getPackageUserId(), shortcut);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700202 shortcut.clearFlags(ShortcutInfo.FLAG_DYNAMIC | ShortcutInfo.FLAG_PINNED
203 | ShortcutInfo.FLAG_MANIFEST);
Makoto Onuki31459242016-03-22 11:12:18 -0700204 }
205 return shortcut;
206 }
207
Makoto Onuki22fcc682016-05-17 14:52:19 -0700208 private void addShortcutInner(@NonNull ShortcutInfo newShortcut) {
Makoto Onuki157b1622016-06-02 16:13:10 -0700209 final ShortcutService s = mShortcutUser.mService;
210
Makoto Onuki22fcc682016-05-17 14:52:19 -0700211 deleteShortcutInner(newShortcut.getId());
Makoto Onuki157b1622016-06-02 16:13:10 -0700212
213 // Extract Icon and update the icon res ID and the bitmap path.
214 s.saveIconAndFixUpShortcut(getPackageUserId(), newShortcut);
215 s.fixUpShortcutResourceNamesAndValues(newShortcut);
Makoto Onuki31459242016-03-22 11:12:18 -0700216 mShortcuts.put(newShortcut.getId(), newShortcut);
217 }
218
219 /**
220 * Add a shortcut, or update one with the same ID, with taking over existing flags.
221 *
222 * It checks the max number of dynamic shortcuts.
223 */
Makoto Onuki22fcc682016-05-17 14:52:19 -0700224 public void addOrUpdateDynamicShortcut(@NonNull ShortcutInfo newShortcut) {
Makoto Onuki39686e82016-04-13 18:03:00 -0700225
Makoto Onuki22fcc682016-05-17 14:52:19 -0700226 Preconditions.checkArgument(newShortcut.isEnabled(),
227 "add/setDynamicShortcuts() cannot publish disabled shortcuts");
228
Makoto Onuki31459242016-03-22 11:12:18 -0700229 newShortcut.addFlags(ShortcutInfo.FLAG_DYNAMIC);
230
231 final ShortcutInfo oldShortcut = mShortcuts.get(newShortcut.getId());
232
233 final boolean wasPinned;
Makoto Onuki31459242016-03-22 11:12:18 -0700234
235 if (oldShortcut == null) {
236 wasPinned = false;
Makoto Onuki31459242016-03-22 11:12:18 -0700237 } else {
Makoto Onuki22fcc682016-05-17 14:52:19 -0700238 // It's an update case.
239 // Make sure the target is updatable. (i.e. should be mutable.)
240 oldShortcut.ensureUpdatableWith(newShortcut);
241
Makoto Onuki31459242016-03-22 11:12:18 -0700242 wasPinned = oldShortcut.isPinned();
Makoto Onuki31459242016-03-22 11:12:18 -0700243 }
244
Makoto Onuki157b1622016-06-02 16:13:10 -0700245 // If it was originally pinned, the new one should be pinned too.
Makoto Onuki31459242016-03-22 11:12:18 -0700246 if (wasPinned) {
247 newShortcut.addFlags(ShortcutInfo.FLAG_PINNED);
248 }
249
Makoto Onuki22fcc682016-05-17 14:52:19 -0700250 addShortcutInner(newShortcut);
Makoto Onuki31459242016-03-22 11:12:18 -0700251 }
252
253 /**
254 * Remove all shortcuts that aren't pinned nor dynamic.
255 */
Makoto Onukic51b2872016-05-04 15:24:50 -0700256 private void removeOrphans() {
Makoto Onuki31459242016-03-22 11:12:18 -0700257 ArrayList<String> removeList = null; // Lazily initialize.
258
259 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
260 final ShortcutInfo si = mShortcuts.valueAt(i);
261
Makoto Onuki22fcc682016-05-17 14:52:19 -0700262 if (si.isAlive()) continue;
Makoto Onuki31459242016-03-22 11:12:18 -0700263
264 if (removeList == null) {
265 removeList = new ArrayList<>();
266 }
267 removeList.add(si.getId());
268 }
269 if (removeList != null) {
270 for (int i = removeList.size() - 1; i >= 0; i--) {
Makoto Onuki22fcc682016-05-17 14:52:19 -0700271 deleteShortcutInner(removeList.get(i));
Makoto Onuki31459242016-03-22 11:12:18 -0700272 }
273 }
274 }
275
276 /**
277 * Remove all dynamic shortcuts.
278 */
Makoto Onukic51b2872016-05-04 15:24:50 -0700279 public void deleteAllDynamicShortcuts() {
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700280 final long now = mShortcutUser.mService.injectCurrentTimeMillis();
281
Makoto Onuki22fcc682016-05-17 14:52:19 -0700282 boolean changed = false;
Makoto Onuki31459242016-03-22 11:12:18 -0700283 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
Makoto Onuki22fcc682016-05-17 14:52:19 -0700284 final ShortcutInfo si = mShortcuts.valueAt(i);
285 if (si.isDynamic()) {
286 changed = true;
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700287
288 si.setTimestamp(now);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700289 si.clearFlags(ShortcutInfo.FLAG_DYNAMIC);
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700290 si.setRank(0); // It may still be pinned, so clear the rank.
Makoto Onuki22fcc682016-05-17 14:52:19 -0700291 }
Makoto Onuki31459242016-03-22 11:12:18 -0700292 }
Makoto Onuki22fcc682016-05-17 14:52:19 -0700293 if (changed) {
294 removeOrphans();
295 }
Makoto Onuki31459242016-03-22 11:12:18 -0700296 }
297
298 /**
Makoto Onuki7001a612016-05-27 13:24:28 -0700299 * Remove a dynamic shortcut by ID. It'll be removed from the dynamic set, but if the shortcut
300 * is pinned, it'll remain as a pinned shortcut, and is still enabled.
Makoto Onukib08790c2016-06-23 14:05:46 -0700301 *
302 * @return true if it's actually removed because it wasn't pinned, or false if it's still
303 * pinned.
Makoto Onuki31459242016-03-22 11:12:18 -0700304 */
Makoto Onukib08790c2016-06-23 14:05:46 -0700305 public boolean deleteDynamicWithId(@NonNull String shortcutId) {
306 final ShortcutInfo removed = deleteOrDisableWithId(
307 shortcutId, /* disable =*/ false, /* overrideImmutable=*/ false);
308 return removed == null;
309 }
310
311 /**
312 * Disable a dynamic shortcut by ID. It'll be removed from the dynamic set, but if the shortcut
313 * is pinned, it'll remain as a pinned shortcut, but will be disabled.
314 *
315 * @return true if it's actually removed because it wasn't pinned, or false if it's still
316 * pinned.
317 */
318 private boolean disableDynamicWithId(@NonNull String shortcutId) {
319 final ShortcutInfo disabled = deleteOrDisableWithId(
320 shortcutId, /* disable =*/ true, /* overrideImmutable=*/ false);
321 return disabled == null;
Makoto Onuki22fcc682016-05-17 14:52:19 -0700322 }
323
Makoto Onuki7001a612016-05-27 13:24:28 -0700324 /**
325 * Disable a dynamic shortcut by ID. It'll be removed from the dynamic set, but if the shortcut
326 * is pinned, it'll remain as a pinned shortcut but will be disabled.
327 */
Makoto Onuki22fcc682016-05-17 14:52:19 -0700328 public void disableWithId(@NonNull String shortcutId, String disabledMessage,
329 int disabledMessageResId, boolean overrideImmutable) {
330 final ShortcutInfo disabled = deleteOrDisableWithId(shortcutId, /* disable =*/ true,
331 overrideImmutable);
332
333 if (disabled != null) {
334 if (disabledMessage != null) {
335 disabled.setDisabledMessage(disabledMessage);
336 } else if (disabledMessageResId != 0) {
337 disabled.setDisabledMessageResId(disabledMessageResId);
Makoto Onuki157b1622016-06-02 16:13:10 -0700338
339 mShortcutUser.mService.fixUpShortcutResourceNamesAndValues(disabled);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700340 }
341 }
342 }
343
344 @Nullable
345 private ShortcutInfo deleteOrDisableWithId(@NonNull String shortcutId, boolean disable,
346 boolean overrideImmutable) {
Makoto Onuki31459242016-03-22 11:12:18 -0700347 final ShortcutInfo oldShortcut = mShortcuts.get(shortcutId);
348
Makoto Onuki22fcc682016-05-17 14:52:19 -0700349 if (oldShortcut == null || !oldShortcut.isEnabled()) {
350 return null; // Doesn't exist or already disabled.
Makoto Onuki31459242016-03-22 11:12:18 -0700351 }
Makoto Onuki22fcc682016-05-17 14:52:19 -0700352 if (!overrideImmutable) {
353 ensureNotImmutable(oldShortcut);
Makoto Onuki31459242016-03-22 11:12:18 -0700354 }
355 if (oldShortcut.isPinned()) {
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700356
357 oldShortcut.setRank(0);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700358 oldShortcut.clearFlags(ShortcutInfo.FLAG_DYNAMIC | ShortcutInfo.FLAG_MANIFEST);
359 if (disable) {
360 oldShortcut.addFlags(ShortcutInfo.FLAG_DISABLED);
361 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700362 oldShortcut.setTimestamp(mShortcutUser.mService.injectCurrentTimeMillis());
363
Makoto Onuki22fcc682016-05-17 14:52:19 -0700364 return oldShortcut;
Makoto Onuki31459242016-03-22 11:12:18 -0700365 } else {
Makoto Onuki22fcc682016-05-17 14:52:19 -0700366 deleteShortcutInner(shortcutId);
367 return null;
368 }
369 }
370
371 public void enableWithId(@NonNull String shortcutId) {
372 final ShortcutInfo shortcut = mShortcuts.get(shortcutId);
373 if (shortcut != null) {
374 ensureNotImmutable(shortcut);
375 shortcut.clearFlags(ShortcutInfo.FLAG_DISABLED);
Makoto Onuki31459242016-03-22 11:12:18 -0700376 }
377 }
378
379 /**
380 * Called after a launcher updates the pinned set. For each shortcut in this package,
381 * set FLAG_PINNED if any launcher has pinned it. Otherwise, clear it.
382 *
383 * <p>Then remove all shortcuts that are not dynamic and no longer pinned either.
384 */
Makoto Onukic51b2872016-05-04 15:24:50 -0700385 public void refreshPinnedFlags() {
Makoto Onuki31459242016-03-22 11:12:18 -0700386 // First, un-pin all shortcuts
387 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
388 mShortcuts.valueAt(i).clearFlags(ShortcutInfo.FLAG_PINNED);
389 }
390
391 // Then, for the pinned set for each launcher, set the pin flag one by one.
Makoto Onukic51b2872016-05-04 15:24:50 -0700392 mShortcutUser.mService.getUserShortcutsLocked(getPackageUserId())
393 .forAllLaunchers(launcherShortcuts -> {
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700394 final ArraySet<String> pinned = launcherShortcuts.getPinnedShortcutIds(
Makoto Onuki2e210c42016-03-30 08:30:36 -0700395 getPackageName(), getPackageUserId());
Makoto Onuki31459242016-03-22 11:12:18 -0700396
397 if (pinned == null || pinned.size() == 0) {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700398 return;
Makoto Onuki31459242016-03-22 11:12:18 -0700399 }
400 for (int i = pinned.size() - 1; i >= 0; i--) {
Makoto Onuki2e210c42016-03-30 08:30:36 -0700401 final String id = pinned.valueAt(i);
402 final ShortcutInfo si = mShortcuts.get(id);
Makoto Onuki31459242016-03-22 11:12:18 -0700403 if (si == null) {
Makoto Onuki2e210c42016-03-30 08:30:36 -0700404 // This happens if a launcher pinned shortcuts from this package, then backup&
405 // restored, but this package doesn't allow backing up.
406 // In that case the launcher ends up having a dangling pinned shortcuts.
407 // That's fine, when the launcher is restored, we'll fix it.
408 continue;
Makoto Onuki31459242016-03-22 11:12:18 -0700409 }
Makoto Onuki2e210c42016-03-30 08:30:36 -0700410 si.addFlags(ShortcutInfo.FLAG_PINNED);
Makoto Onuki31459242016-03-22 11:12:18 -0700411 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700412 });
Makoto Onuki31459242016-03-22 11:12:18 -0700413
414 // Lastly, remove the ones that are no longer pinned nor dynamic.
Makoto Onukic51b2872016-05-04 15:24:50 -0700415 removeOrphans();
Makoto Onuki31459242016-03-22 11:12:18 -0700416 }
417
418 /**
419 * Number of calls that the caller has made, since the last reset.
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700420 *
421 * <p>This takes care of the resetting the counter for foreground apps as well as after
422 * locale changes.
Makoto Onuki31459242016-03-22 11:12:18 -0700423 */
Makoto Onukic51b2872016-05-04 15:24:50 -0700424 public int getApiCallCount() {
Makoto Onukic51b2872016-05-04 15:24:50 -0700425 final ShortcutService s = mShortcutUser.mService;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700426
427 // Reset the counter if:
428 // - the package is in foreground now.
429 // - the package is *not* in foreground now, but was in foreground at some point
430 // since the previous time it had been.
431 if (s.isUidForegroundLocked(mPackageUid)
432 || mLastKnownForegroundElapsedTime
433 < s.getUidLastForegroundElapsedTimeLocked(mPackageUid)) {
434 mLastKnownForegroundElapsedTime = s.injectElapsedRealtime();
Makoto Onukic51b2872016-05-04 15:24:50 -0700435 resetRateLimiting();
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700436 }
437
438 // Note resetThrottlingIfNeeded() and resetRateLimiting() will set 0 to mApiCallCount,
439 // but we just can't return 0 at this point, because we may have to update
440 // mLastResetTime.
441
Makoto Onuki31459242016-03-22 11:12:18 -0700442 final long last = s.getLastResetTimeLocked();
443
444 final long now = s.injectCurrentTimeMillis();
445 if (ShortcutService.isClockValid(now) && mLastResetTime > now) {
446 Slog.w(TAG, "Clock rewound");
447 // Clock rewound.
448 mLastResetTime = now;
449 mApiCallCount = 0;
450 return mApiCallCount;
451 }
452
453 // If not reset yet, then reset.
454 if (mLastResetTime < last) {
455 if (ShortcutService.DEBUG) {
Makoto Onukic51b2872016-05-04 15:24:50 -0700456 Slog.d(TAG, String.format("%s: last reset=%d, now=%d, last=%d: resetting",
457 getPackageName(), mLastResetTime, now, last));
Makoto Onuki31459242016-03-22 11:12:18 -0700458 }
459 mApiCallCount = 0;
460 mLastResetTime = last;
461 }
462 return mApiCallCount;
463 }
464
465 /**
466 * If the caller app hasn't been throttled yet, increment {@link #mApiCallCount}
467 * and return true. Otherwise just return false.
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700468 *
469 * <p>This takes care of the resetting the counter for foreground apps as well as after
470 * locale changes, which is done internally by {@link #getApiCallCount}.
Makoto Onuki31459242016-03-22 11:12:18 -0700471 */
Makoto Onukic51b2872016-05-04 15:24:50 -0700472 public boolean tryApiCall() {
473 final ShortcutService s = mShortcutUser.mService;
474
475 if (getApiCallCount() >= s.mMaxUpdatesPerInterval) {
Makoto Onuki31459242016-03-22 11:12:18 -0700476 return false;
477 }
478 mApiCallCount++;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700479 s.scheduleSaveUser(getOwnerUserId());
Makoto Onuki31459242016-03-22 11:12:18 -0700480 return true;
481 }
482
Makoto Onukic51b2872016-05-04 15:24:50 -0700483 public void resetRateLimiting() {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700484 if (ShortcutService.DEBUG) {
485 Slog.d(TAG, "resetRateLimiting: " + getPackageName());
486 }
487 if (mApiCallCount > 0) {
488 mApiCallCount = 0;
Makoto Onukic51b2872016-05-04 15:24:50 -0700489 mShortcutUser.mService.scheduleSaveUser(getOwnerUserId());
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700490 }
491 }
492
493 public void resetRateLimitingForCommandLineNoSaving() {
Makoto Onuki31459242016-03-22 11:12:18 -0700494 mApiCallCount = 0;
495 mLastResetTime = 0;
496 }
497
498 /**
499 * Find all shortcuts that match {@code query}.
500 */
Makoto Onukic51b2872016-05-04 15:24:50 -0700501 public void findAll(@NonNull List<ShortcutInfo> result,
Makoto Onukid99c6f02016-03-28 11:02:54 -0700502 @Nullable Predicate<ShortcutInfo> query, int cloneFlag) {
Makoto Onukic51b2872016-05-04 15:24:50 -0700503 findAll(result, query, cloneFlag, null, 0);
Makoto Onukid99c6f02016-03-28 11:02:54 -0700504 }
505
506 /**
507 * Find all shortcuts that match {@code query}.
508 *
509 * This will also provide a "view" for each launcher -- a non-dynamic shortcut that's not pinned
510 * by the calling launcher will not be included in the result, and also "isPinned" will be
511 * adjusted for the caller too.
512 */
Makoto Onukic51b2872016-05-04 15:24:50 -0700513 public void findAll(@NonNull List<ShortcutInfo> result,
Makoto Onuki31459242016-03-22 11:12:18 -0700514 @Nullable Predicate<ShortcutInfo> query, int cloneFlag,
Makoto Onukid99c6f02016-03-28 11:02:54 -0700515 @Nullable String callingLauncher, int launcherUserId) {
Makoto Onuki2e210c42016-03-30 08:30:36 -0700516 if (getPackageInfo().isShadow()) {
517 // Restored and the app not installed yet, so don't return any.
518 return;
519 }
Makoto Onuki31459242016-03-22 11:12:18 -0700520
Makoto Onukic51b2872016-05-04 15:24:50 -0700521 final ShortcutService s = mShortcutUser.mService;
522
Makoto Onuki31459242016-03-22 11:12:18 -0700523 // Set of pinned shortcuts by the calling launcher.
524 final ArraySet<String> pinnedByCallerSet = (callingLauncher == null) ? null
Makoto Onuki2e210c42016-03-30 08:30:36 -0700525 : s.getLauncherShortcutsLocked(callingLauncher, getPackageUserId(), launcherUserId)
526 .getPinnedShortcutIds(getPackageName(), getPackageUserId());
Makoto Onuki31459242016-03-22 11:12:18 -0700527
528 for (int i = 0; i < mShortcuts.size(); i++) {
529 final ShortcutInfo si = mShortcuts.valueAt(i);
530
Makoto Onuki22fcc682016-05-17 14:52:19 -0700531 // Need to adjust PINNED flag depending on the caller.
532 // Basically if the caller is a launcher (callingLauncher != null) and the launcher
533 // isn't pinning it, then we need to clear PINNED for this caller.
Makoto Onuki31459242016-03-22 11:12:18 -0700534 final boolean isPinnedByCaller = (callingLauncher == null)
535 || ((pinnedByCallerSet != null) && pinnedByCallerSet.contains(si.getId()));
Makoto Onuki22fcc682016-05-17 14:52:19 -0700536
537 if (si.isFloating()) {
Makoto Onuki31459242016-03-22 11:12:18 -0700538 if (!isPinnedByCaller) {
539 continue;
540 }
541 }
542 final ShortcutInfo clone = si.clone(cloneFlag);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700543
Makoto Onuki31459242016-03-22 11:12:18 -0700544 // Fix up isPinned for the caller. Note we need to do it before the "test" callback,
545 // since it may check isPinned.
546 if (!isPinnedByCaller) {
547 clone.clearFlags(ShortcutInfo.FLAG_PINNED);
548 }
549 if (query == null || query.test(clone)) {
550 result.add(clone);
551 }
552 }
553 }
554
555 public void resetThrottling() {
556 mApiCallCount = 0;
557 }
558
Makoto Onuki39686e82016-04-13 18:03:00 -0700559 /**
Makoto Onuki6c1dbd52016-05-02 15:19:32 -0700560 * Return the filenames (excluding path names) of icon bitmap files from this package.
561 */
562 public ArraySet<String> getUsedBitmapFiles() {
563 final ArraySet<String> usedFiles = new ArraySet<>(mShortcuts.size());
564
565 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
566 final ShortcutInfo si = mShortcuts.valueAt(i);
567 if (si.getBitmapPath() != null) {
568 usedFiles.add(getFileName(si.getBitmapPath()));
569 }
570 }
571 return usedFiles;
572 }
573
574 private static String getFileName(@NonNull String path) {
575 final int sep = path.lastIndexOf(File.separatorChar);
576 if (sep == -1) {
577 return path;
578 } else {
579 return path.substring(sep + 1);
580 }
581 }
582
583 /**
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700584 * @return false if any of the target activities are no longer enabled.
585 */
586 private boolean areAllActivitiesStillEnabled() {
587 if (mShortcuts.size() == 0) {
588 return true;
589 }
590 final ShortcutService s = mShortcutUser.mService;
591
592 // Normally the number of target activities is 1 or so, so no need to use a complex
593 // structure like a set.
594 final ArrayList<ComponentName> checked = new ArrayList<>(4);
595
596 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
597 final ShortcutInfo si = mShortcuts.valueAt(i);
598 final ComponentName activity = si.getActivity();
599
600 if (checked.contains(activity)) {
601 continue; // Already checked.
602 }
603 checked.add(activity);
604
605 if (!s.injectIsActivityEnabledAndExported(activity, getOwnerUserId())) {
606 return false;
607 }
608 }
609 return true;
610 }
611
612 /**
613 * Called when the package may be added or updated, or its activities may be disabled, and
614 * if so, rescan the package and do the necessary stuff.
Makoto Onuki22fcc682016-05-17 14:52:19 -0700615 *
616 * Add case:
617 * - Publish manifest shortcuts.
618 *
619 * Update case:
620 * - Re-publish manifest shortcuts.
621 * - If there are shortcuts with resources (icons or strings), update their timestamps.
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700622 * - Disable shortcuts whose target activities are disabled.
Makoto Onuki22fcc682016-05-17 14:52:19 -0700623 *
624 * @return TRUE if any shortcuts have been changed.
Makoto Onuki39686e82016-04-13 18:03:00 -0700625 */
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700626 public boolean rescanPackageIfNeeded(boolean isNewApp, boolean forceRescan) {
627 final ShortcutService s = mShortcutUser.mService;
628 final long start = s.injectElapsedRealtime();
Makoto Onuki39686e82016-04-13 18:03:00 -0700629
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700630 final PackageInfo pi;
631 try {
632 pi = mShortcutUser.mService.getPackageInfo(
633 getPackageName(), getPackageUserId());
634 if (pi == null) {
635 return false; // Shouldn't happen.
Makoto Onuki22fcc682016-05-17 14:52:19 -0700636 }
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700637
638 if (!isNewApp && !forceRescan) {
639 // Return if the package hasn't changed, ie:
640 // - version code hasn't change
641 // - lastUpdateTime hasn't change
642 // - all target activities are still enabled.
Makoto Onuki33663282016-08-22 16:19:04 -0700643
644 // Note, system apps timestamps do *not* change after OTAs. (But they do
645 // after an adb sync or a local flash.)
646 // This means if a system app's version code doesn't change on an OTA,
647 // we don't notice it's updated. But that's fine since their version code *should*
648 // really change on OTAs.
Makoto Onuki64183d52016-08-08 14:11:34 -0700649 if ((getPackageInfo().getVersionCode() == pi.versionCode)
650 && (getPackageInfo().getLastUpdateTime() == pi.lastUpdateTime)
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700651 && areAllActivitiesStillEnabled()) {
652 return false;
653 }
654 }
655 } finally {
656 s.logDurationStat(Stats.PACKAGE_UPDATE_CHECK, start);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700657 }
658
659 // Now prepare to publish manifest shortcuts.
660 List<ShortcutInfo> newManifestShortcutList = null;
661 try {
662 newManifestShortcutList = ShortcutParser.parseShortcuts(mShortcutUser.mService,
663 getPackageName(), getPackageUserId());
664 } catch (IOException|XmlPullParserException e) {
665 Slog.e(TAG, "Failed to load shortcuts from AndroidManifest.xml.", e);
666 }
667 final int manifestShortcutSize = newManifestShortcutList == null ? 0
668 : newManifestShortcutList.size();
669 if (ShortcutService.DEBUG) {
670 Slog.d(TAG, String.format("Package %s has %d manifest shortcut(s)",
671 getPackageName(), manifestShortcutSize));
672 }
673 if (isNewApp && (manifestShortcutSize == 0)) {
674 // If it's a new app, and it doesn't have manifest shortcuts, then nothing to do.
675
676 // If it's an update, then it may already have manifest shortcuts, which need to be
677 // disabled.
678 return false;
679 }
680 if (ShortcutService.DEBUG) {
681 Slog.d(TAG, String.format("Package %s %s, version %d -> %d", getPackageName(),
682 (isNewApp ? "added" : "updated"),
683 getPackageInfo().getVersionCode(), pi.versionCode));
684 }
685
686 getPackageInfo().updateVersionInfo(pi);
Makoto Onuki39686e82016-04-13 18:03:00 -0700687
688 boolean changed = false;
Makoto Onuki39686e82016-04-13 18:03:00 -0700689
Makoto Onuki22fcc682016-05-17 14:52:19 -0700690 // For existing shortcuts, update timestamps if they have any resources.
Makoto Onukib08790c2016-06-23 14:05:46 -0700691 // Also check if shortcuts' activities are still main activities. Otherwise, disable them.
Makoto Onuki22fcc682016-05-17 14:52:19 -0700692 if (!isNewApp) {
Makoto Onuki157b1622016-06-02 16:13:10 -0700693 Resources publisherRes = null;
694
Makoto Onuki22fcc682016-05-17 14:52:19 -0700695 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
696 final ShortcutInfo si = mShortcuts.valueAt(i);
697
Makoto Onukib08790c2016-06-23 14:05:46 -0700698 if (si.isDynamic()) {
699 if (!s.injectIsMainActivity(si.getActivity(), getPackageUserId())) {
700 Slog.w(TAG, String.format(
701 "%s is no longer main activity. Disabling shorcut %s.",
702 getPackageName(), si.getId()));
703 if (disableDynamicWithId(si.getId())) {
704 continue; // Actually removed.
705 }
706 // Still pinned, so fall-through and possibly update the resources.
707 }
708 changed = true;
709 }
710
Makoto Onuki22fcc682016-05-17 14:52:19 -0700711 if (si.hasAnyResources()) {
Makoto Onuki157b1622016-06-02 16:13:10 -0700712 if (!si.isOriginallyFromManifest()) {
713 if (publisherRes == null) {
714 publisherRes = getPackageResources();
715 if (publisherRes == null) {
716 break; // Resources couldn't be loaded.
717 }
718 }
719
720 // If this shortcut is not from a manifest, then update all resource IDs
721 // from resource names. (We don't allow resource strings for
722 // non-manifest at the moment, but icons can still be resources.)
723 si.lookupAndFillInResourceIds(publisherRes);
724 }
Makoto Onuki22fcc682016-05-17 14:52:19 -0700725 changed = true;
726 si.setTimestamp(s.injectCurrentTimeMillis());
727 }
Makoto Onuki39686e82016-04-13 18:03:00 -0700728 }
729 }
Makoto Onuki22fcc682016-05-17 14:52:19 -0700730
731 // (Re-)publish manifest shortcut.
732 changed |= publishManifestShortcuts(newManifestShortcutList);
733
Makoto Onuki7001a612016-05-27 13:24:28 -0700734 if (newManifestShortcutList != null) {
735 changed |= pushOutExcessShortcuts();
736 }
737
Makoto Onukidf6da042016-06-16 09:51:40 -0700738 s.verifyStates();
739
Makoto Onuki39686e82016-04-13 18:03:00 -0700740 if (changed) {
741 // This will send a notification to the launcher, and also save .
742 s.packageShortcutsChanged(getPackageName(), getPackageUserId());
743 } else {
744 // Still save the version code.
745 s.scheduleSaveUser(getPackageUserId());
746 }
Makoto Onuki22fcc682016-05-17 14:52:19 -0700747 return changed;
748 }
749
750 private boolean publishManifestShortcuts(List<ShortcutInfo> newManifestShortcutList) {
751 if (ShortcutService.DEBUG) {
752 Slog.d(TAG, String.format(
753 "Package %s: publishing manifest shortcuts", getPackageName()));
754 }
755 boolean changed = false;
756
Makoto Onuki22fcc682016-05-17 14:52:19 -0700757 // Keep the previous IDs.
758 ArraySet<String> toDisableList = null;
759 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
760 final ShortcutInfo si = mShortcuts.valueAt(i);
761
762 if (si.isManifestShortcut()) {
763 if (toDisableList == null) {
764 toDisableList = new ArraySet<>();
765 }
766 toDisableList.add(si.getId());
767 }
768 }
769
770 // Publish new ones.
771 if (newManifestShortcutList != null) {
772 final int newListSize = newManifestShortcutList.size();
773
774 for (int i = 0; i < newListSize; i++) {
775 changed = true;
776
777 final ShortcutInfo newShortcut = newManifestShortcutList.get(i);
778 final boolean newDisabled = !newShortcut.isEnabled();
779
Makoto Onuki7001a612016-05-27 13:24:28 -0700780 final String id = newShortcut.getId();
Makoto Onuki22fcc682016-05-17 14:52:19 -0700781 final ShortcutInfo oldShortcut = mShortcuts.get(id);
782
783 boolean wasPinned = false;
784
785 if (oldShortcut != null) {
786 if (!oldShortcut.isOriginallyFromManifest()) {
787 Slog.e(TAG, "Shortcut with ID=" + newShortcut.getId()
788 + " exists but is not from AndroidManifest.xml, not updating.");
789 continue;
790 }
791 // Take over the pinned flag.
792 if (oldShortcut.isPinned()) {
793 wasPinned = true;
794 newShortcut.addFlags(ShortcutInfo.FLAG_PINNED);
795 }
796 }
797 if (newDisabled && !wasPinned) {
798 // If the shortcut is disabled, and it was *not* pinned, then this
799 // just doesn't have to be published.
800 // Just keep it in toDisableList, so the previous one would be removed.
801 continue;
802 }
Makoto Onuki22fcc682016-05-17 14:52:19 -0700803
804 // Note even if enabled=false, we still need to update all fields, so do it
805 // regardless.
806 addShortcutInner(newShortcut); // This will clean up the old one too.
807
808 if (!newDisabled && toDisableList != null) {
809 // Still alive, don't remove.
810 toDisableList.remove(id);
811 }
812 }
813 }
814
815 // Disable the previous manifest shortcuts that are no longer in the manifest.
816 if (toDisableList != null) {
817 if (ShortcutService.DEBUG) {
818 Slog.d(TAG, String.format(
819 "Package %s: disabling %d stale shortcuts", getPackageName(),
820 toDisableList.size()));
821 }
822 for (int i = toDisableList.size() - 1; i >= 0; i--) {
823 changed = true;
824
825 final String id = toDisableList.valueAt(i);
826
827 disableWithId(id, /* disable message =*/ null, /* disable message resid */ 0,
828 /* overrideImmutable=*/ true);
829 }
830 removeOrphans();
831 }
Makoto Onukidf6da042016-06-16 09:51:40 -0700832 adjustRanks();
Makoto Onuki22fcc682016-05-17 14:52:19 -0700833 return changed;
Makoto Onuki39686e82016-04-13 18:03:00 -0700834 }
835
Makoto Onuki7001a612016-05-27 13:24:28 -0700836 /**
837 * For each target activity, make sure # of dynamic + manifest shortcuts <= max.
838 * If too many, we'll remove the dynamic with the lowest ranks.
839 */
840 private boolean pushOutExcessShortcuts() {
841 final ShortcutService service = mShortcutUser.mService;
842 final int maxShortcuts = service.getMaxActivityShortcuts();
843
844 boolean changed = false;
845
846 final ArrayMap<ComponentName, ArrayList<ShortcutInfo>> all =
847 sortShortcutsToActivities();
848 for (int outer = all.size() - 1; outer >= 0; outer--) {
849 final ArrayList<ShortcutInfo> list = all.valueAt(outer);
850 if (list.size() <= maxShortcuts) {
851 continue;
852 }
853 // Sort by isManifestShortcut() and getRank().
854 Collections.sort(list, mShortcutTypeAndRankComparator);
855
856 // Keep [0 .. max), and remove (as dynamic) [max .. size)
857 for (int inner = list.size() - 1; inner >= maxShortcuts; inner--) {
858 final ShortcutInfo shortcut = list.get(inner);
859
860 if (shortcut.isManifestShortcut()) {
861 // This shouldn't happen -- excess shortcuts should all be non-manifest.
862 // But just in case.
863 service.wtf("Found manifest shortcuts in excess list.");
864 continue;
865 }
866 deleteDynamicWithId(shortcut.getId());
867 }
868 }
Makoto Onuki7001a612016-05-27 13:24:28 -0700869
870 return changed;
871 }
872
873 /**
874 * To sort by isManifestShortcut() and getRank(). i.e. manifest shortcuts come before
875 * non-manifest shortcuts, then sort by rank.
876 *
877 * This is used to decide which dynamic shortcuts to remove when an upgraded version has more
878 * manifest shortcuts than before and as a result we need to remove some of the dynamic
879 * shortcuts. We sort manifest + dynamic shortcuts by this order, and remove the ones with
880 * the last ones.
881 *
882 * (Note the number of manifest shortcuts is always <= the max number, because if there are
883 * more, ShortcutParser would ignore the rest.)
884 */
885 final Comparator<ShortcutInfo> mShortcutTypeAndRankComparator = (ShortcutInfo a,
886 ShortcutInfo b) -> {
887 if (a.isManifestShortcut() && !b.isManifestShortcut()) {
888 return -1;
889 }
890 if (!a.isManifestShortcut() && b.isManifestShortcut()) {
891 return 1;
892 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700893 return Integer.compare(a.getRank(), b.getRank());
Makoto Onuki7001a612016-05-27 13:24:28 -0700894 };
895
896 /**
897 * Build a list of shortcuts for each target activity and return as a map. The result won't
898 * contain "floating" shortcuts because they don't belong on any activities.
899 */
900 private ArrayMap<ComponentName, ArrayList<ShortcutInfo>> sortShortcutsToActivities() {
Makoto Onuki7001a612016-05-27 13:24:28 -0700901 final ArrayMap<ComponentName, ArrayList<ShortcutInfo>> activitiesToShortcuts
902 = new ArrayMap<>();
903 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
904 final ShortcutInfo si = mShortcuts.valueAt(i);
905 if (si.isFloating()) {
906 continue; // Ignore floating shortcuts, which are not tied to any activities.
907 }
908
909 final ComponentName activity = si.getActivity();
910
911 ArrayList<ShortcutInfo> list = activitiesToShortcuts.get(activity);
912 if (list == null) {
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700913 list = new ArrayList<>();
Makoto Onuki7001a612016-05-27 13:24:28 -0700914 activitiesToShortcuts.put(activity, list);
915 }
916 list.add(si);
917 }
918 return activitiesToShortcuts;
919 }
920
921 /** Used by {@link #enforceShortcutCountsBeforeOperation} */
922 private void incrementCountForActivity(ArrayMap<ComponentName, Integer> counts,
923 ComponentName cn, int increment) {
924 Integer oldValue = counts.get(cn);
925 if (oldValue == null) {
926 oldValue = 0;
927 }
928
929 counts.put(cn, oldValue + increment);
930 }
931
932 /**
933 * Called by
934 * {@link android.content.pm.ShortcutManager#setDynamicShortcuts},
935 * {@link android.content.pm.ShortcutManager#addDynamicShortcuts}, and
936 * {@link android.content.pm.ShortcutManager#updateShortcuts} before actually performing
937 * the operation to make sure the operation wouldn't result in the target activities having
938 * more than the allowed number of dynamic/manifest shortcuts.
939 *
940 * @param newList shortcut list passed to set, add or updateShortcuts().
941 * @param operation add, set or update.
942 * @throws IllegalArgumentException if the operation would result in going over the max
943 * shortcut count for any activity.
944 */
945 public void enforceShortcutCountsBeforeOperation(List<ShortcutInfo> newList,
946 @ShortcutOperation int operation) {
947 final ShortcutService service = mShortcutUser.mService;
948
949 // Current # of dynamic / manifest shortcuts for each activity.
950 // (If it's for update, then don't count dynamic shortcuts, since they'll be replaced
951 // anyway.)
952 final ArrayMap<ComponentName, Integer> counts = new ArrayMap<>(4);
953 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
954 final ShortcutInfo shortcut = mShortcuts.valueAt(i);
955
956 if (shortcut.isManifestShortcut()) {
957 incrementCountForActivity(counts, shortcut.getActivity(), 1);
958 } else if (shortcut.isDynamic() && (operation != ShortcutService.OPERATION_SET)) {
959 incrementCountForActivity(counts, shortcut.getActivity(), 1);
960 }
961 }
962
963 for (int i = newList.size() - 1; i >= 0; i--) {
964 final ShortcutInfo newShortcut = newList.get(i);
965 final ComponentName newActivity = newShortcut.getActivity();
966 if (newActivity == null) {
967 if (operation != ShortcutService.OPERATION_UPDATE) {
Makoto Onukib08790c2016-06-23 14:05:46 -0700968 service.wtf("Activity must not be null at this point");
969 continue; // Just ignore this invalid case.
Makoto Onuki7001a612016-05-27 13:24:28 -0700970 }
971 continue; // Activity can be null for update.
972 }
973
974 final ShortcutInfo original = mShortcuts.get(newShortcut.getId());
975 if (original == null) {
976 if (operation == ShortcutService.OPERATION_UPDATE) {
977 continue; // When updating, ignore if there's no target.
978 }
979 // Add() or set(), and there's no existing shortcut with the same ID. We're
980 // simply publishing (as opposed to updating) this shortcut, so just +1.
981 incrementCountForActivity(counts, newActivity, 1);
982 continue;
983 }
984 if (original.isFloating() && (operation == ShortcutService.OPERATION_UPDATE)) {
985 // Updating floating shortcuts doesn't affect the count, so ignore.
986 continue;
987 }
988
989 // If it's add() or update(), then need to decrement for the previous activity.
990 // Skip it for set() since it's already been taken care of by not counting the original
991 // dynamic shortcuts in the first loop.
992 if (operation != ShortcutService.OPERATION_SET) {
993 final ComponentName oldActivity = original.getActivity();
994 if (!original.isFloating()) {
995 incrementCountForActivity(counts, oldActivity, -1);
996 }
997 }
998 incrementCountForActivity(counts, newActivity, 1);
999 }
1000
1001 // Then make sure none of the activities have more than the max number of shortcuts.
1002 for (int i = counts.size() - 1; i >= 0; i--) {
1003 service.enforceMaxActivityShortcuts(counts.valueAt(i));
1004 }
1005 }
1006
Makoto Onuki157b1622016-06-02 16:13:10 -07001007 /**
1008 * For all the text fields, refresh the string values if they're from resources.
1009 */
1010 public void resolveResourceStrings() {
1011 final ShortcutService s = mShortcutUser.mService;
1012 boolean changed = false;
1013
1014 Resources publisherRes = null;
1015 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1016 final ShortcutInfo si = mShortcuts.valueAt(i);
1017
1018 if (si.hasStringResources()) {
1019 changed = true;
1020
1021 if (publisherRes == null) {
1022 publisherRes = getPackageResources();
1023 if (publisherRes == null) {
1024 break; // Resources couldn't be loaded.
1025 }
1026 }
1027
1028 si.resolveResourceStrings(publisherRes);
1029 si.setTimestamp(s.injectCurrentTimeMillis());
1030 }
1031 }
1032 if (changed) {
Makoto Onuki4e6cef42016-07-13 16:14:01 -07001033 s.packageShortcutsChanged(getPackageName(), getPackageUserId());
Makoto Onuki157b1622016-06-02 16:13:10 -07001034 }
1035 }
1036
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001037 /** Clears the implicit ranks for all shortcuts. */
1038 public void clearAllImplicitRanks() {
1039 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1040 final ShortcutInfo si = mShortcuts.valueAt(i);
1041 si.clearImplicitRankAndRankChangedFlag();
1042 }
1043 }
1044
1045 /**
1046 * Used to sort shortcuts for rank auto-adjusting.
1047 */
1048 final Comparator<ShortcutInfo> mShortcutRankComparator = (ShortcutInfo a, ShortcutInfo b) -> {
1049 // First, sort by rank.
1050 int ret = Integer.compare(a.getRank(), b.getRank());
1051 if (ret != 0) {
1052 return ret;
1053 }
1054 // When ranks are tie, then prioritize the ones that have just been assigned new ranks.
1055 // e.g. when there are 3 shortcuts, "s1" "s2" and "s3" with rank 0, 1, 2 respectively,
1056 // adding a shortcut "s4" with rank 1 will "insert" it between "s1" and "s2", because
1057 // "s2" and "s4" have the same rank 1 but s4 has isRankChanged() set.
1058 // Similarly, updating s3's rank to 1 will insert it between s1 and s2.
1059 if (a.isRankChanged() != b.isRankChanged()) {
1060 return a.isRankChanged() ? -1 : 1;
1061 }
1062 // If they're still tie, sort by implicit rank -- i.e. preserve the order in which
1063 // they're passed to the API.
1064 ret = Integer.compare(a.getImplicitRank(), b.getImplicitRank());
1065 if (ret != 0) {
1066 return ret;
1067 }
1068 // If they're stil tie, just sort by their IDs.
1069 // This may happen with updateShortcuts() -- see
1070 // the testUpdateShortcuts_noManifestShortcuts() test.
1071 return a.getId().compareTo(b.getId());
1072 };
1073
1074 /**
1075 * Re-calculate the ranks for all shortcuts.
1076 */
1077 public void adjustRanks() {
1078 final ShortcutService s = mShortcutUser.mService;
1079 final long now = s.injectCurrentTimeMillis();
1080
1081 // First, clear ranks for floating shortcuts.
1082 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1083 final ShortcutInfo si = mShortcuts.valueAt(i);
1084 if (si.isFloating()) {
1085 if (si.getRank() != 0) {
1086 si.setTimestamp(now);
1087 si.setRank(0);
1088 }
1089 }
1090 }
1091
1092 // Then adjust ranks. Ranks are unique for each activity, so we first need to sort
1093 // shortcuts to each activity.
1094 // Then sort the shortcuts within each activity with mShortcutRankComparator, and
1095 // assign ranks from 0.
1096 final ArrayMap<ComponentName, ArrayList<ShortcutInfo>> all =
1097 sortShortcutsToActivities();
1098 for (int outer = all.size() - 1; outer >= 0; outer--) { // For each activity.
1099 final ArrayList<ShortcutInfo> list = all.valueAt(outer);
1100
1101 // Sort by ranks and other signals.
1102 Collections.sort(list, mShortcutRankComparator);
1103
1104 int rank = 0;
1105
1106 final int size = list.size();
1107 for (int i = 0; i < size; i++) {
1108 final ShortcutInfo si = list.get(i);
1109 if (si.isManifestShortcut()) {
1110 // Don't adjust ranks for manifest shortcuts.
1111 continue;
1112 }
1113 // At this point, it must be dynamic.
1114 if (!si.isDynamic()) {
1115 s.wtf("Non-dynamic shortcut found.");
1116 continue;
1117 }
1118 final int thisRank = rank++;
1119 if (si.getRank() != thisRank) {
1120 si.setTimestamp(now);
1121 si.setRank(thisRank);
1122 }
1123 }
1124 }
1125 }
1126
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07001127 /** @return true if there's any shortcuts that are not manifest shortcuts. */
1128 public boolean hasNonManifestShortcuts() {
1129 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1130 final ShortcutInfo si = mShortcuts.valueAt(i);
1131 if (!si.isDeclaredInManifest()) {
1132 return true;
1133 }
1134 }
1135 return false;
1136 }
1137
Makoto Onukic51b2872016-05-04 15:24:50 -07001138 public void dump(@NonNull PrintWriter pw, @NonNull String prefix) {
Makoto Onuki31459242016-03-22 11:12:18 -07001139 pw.println();
1140
1141 pw.print(prefix);
1142 pw.print("Package: ");
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001143 pw.print(getPackageName());
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001144 pw.print(" UID: ");
1145 pw.print(mPackageUid);
Makoto Onuki31459242016-03-22 11:12:18 -07001146 pw.println();
1147
1148 pw.print(prefix);
1149 pw.print(" ");
1150 pw.print("Calls: ");
Makoto Onukic51b2872016-05-04 15:24:50 -07001151 pw.print(getApiCallCount());
Makoto Onuki31459242016-03-22 11:12:18 -07001152 pw.println();
1153
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001154 // getApiCallCount() may have updated mLastKnownForegroundElapsedTime.
1155 pw.print(prefix);
1156 pw.print(" ");
1157 pw.print("Last known FG: ");
1158 pw.print(mLastKnownForegroundElapsedTime);
1159 pw.println();
1160
Makoto Onuki31459242016-03-22 11:12:18 -07001161 // This should be after getApiCallCount(), which may update it.
1162 pw.print(prefix);
1163 pw.print(" ");
1164 pw.print("Last reset: [");
1165 pw.print(mLastResetTime);
1166 pw.print("] ");
Makoto Onukic51b2872016-05-04 15:24:50 -07001167 pw.print(ShortcutService.formatTime(mLastResetTime));
Makoto Onuki31459242016-03-22 11:12:18 -07001168 pw.println();
1169
Makoto Onukic51b2872016-05-04 15:24:50 -07001170 getPackageInfo().dump(pw, prefix + " ");
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001171 pw.println();
1172
Makoto Onuki39686e82016-04-13 18:03:00 -07001173 pw.print(prefix);
1174 pw.println(" Shortcuts:");
Makoto Onuki31459242016-03-22 11:12:18 -07001175 long totalBitmapSize = 0;
1176 final ArrayMap<String, ShortcutInfo> shortcuts = mShortcuts;
1177 final int size = shortcuts.size();
1178 for (int i = 0; i < size; i++) {
1179 final ShortcutInfo si = shortcuts.valueAt(i);
Makoto Onuki39686e82016-04-13 18:03:00 -07001180 pw.print(prefix);
1181 pw.print(" ");
Makoto Onuki31459242016-03-22 11:12:18 -07001182 pw.println(si.toInsecureString());
1183 if (si.getBitmapPath() != null) {
1184 final long len = new File(si.getBitmapPath()).length();
Makoto Onuki39686e82016-04-13 18:03:00 -07001185 pw.print(prefix);
1186 pw.print(" ");
Makoto Onuki31459242016-03-22 11:12:18 -07001187 pw.print("bitmap size=");
1188 pw.println(len);
1189
1190 totalBitmapSize += len;
1191 }
1192 }
1193 pw.print(prefix);
1194 pw.print(" ");
1195 pw.print("Total bitmap size: ");
1196 pw.print(totalBitmapSize);
1197 pw.print(" (");
Makoto Onukic51b2872016-05-04 15:24:50 -07001198 pw.print(Formatter.formatFileSize(mShortcutUser.mService.mContext, totalBitmapSize));
Makoto Onuki31459242016-03-22 11:12:18 -07001199 pw.println(")");
1200 }
1201
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001202 @Override
Makoto Onuki76269922016-07-15 14:58:54 -07001203 public JSONObject dumpCheckin(boolean clear) throws JSONException {
1204 final JSONObject result = super.dumpCheckin(clear);
1205
1206 int numDynamic = 0;
1207 int numPinned = 0;
1208 int numManifest = 0;
1209 int numBitmaps = 0;
1210 long totalBitmapSize = 0;
1211
1212 final ArrayMap<String, ShortcutInfo> shortcuts = mShortcuts;
1213 final int size = shortcuts.size();
1214 for (int i = 0; i < size; i++) {
1215 final ShortcutInfo si = shortcuts.valueAt(i);
1216
1217 if (si.isDynamic()) numDynamic++;
1218 if (si.isDeclaredInManifest()) numManifest++;
1219 if (si.isPinned()) numPinned++;
1220
1221 if (si.getBitmapPath() != null) {
1222 numBitmaps++;
1223 totalBitmapSize += new File(si.getBitmapPath()).length();
1224 }
1225 }
1226
1227 result.put(KEY_DYNAMIC, numDynamic);
1228 result.put(KEY_MANIFEST, numManifest);
1229 result.put(KEY_PINNED, numPinned);
1230 result.put(KEY_BITMAPS, numBitmaps);
1231 result.put(KEY_BITMAP_BYTES, totalBitmapSize);
1232
1233 // TODO Log update frequency too.
1234
1235 return result;
1236 }
1237
1238 @Override
Makoto Onuki0acbb142016-03-22 17:02:57 -07001239 public void saveToXml(@NonNull XmlSerializer out, boolean forBackup)
1240 throws IOException, XmlPullParserException {
Makoto Onuki31459242016-03-22 11:12:18 -07001241 final int size = mShortcuts.size();
1242
1243 if (size == 0 && mApiCallCount == 0) {
1244 return; // nothing to write.
1245 }
1246
1247 out.startTag(null, TAG_ROOT);
1248
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001249 ShortcutService.writeAttr(out, ATTR_NAME, getPackageName());
Makoto Onuki31459242016-03-22 11:12:18 -07001250 ShortcutService.writeAttr(out, ATTR_CALL_COUNT, mApiCallCount);
1251 ShortcutService.writeAttr(out, ATTR_LAST_RESET, mLastResetTime);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001252 getPackageInfo().saveToXml(out);
Makoto Onuki31459242016-03-22 11:12:18 -07001253
1254 for (int j = 0; j < size; j++) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07001255 saveShortcut(out, mShortcuts.valueAt(j), forBackup);
Makoto Onuki31459242016-03-22 11:12:18 -07001256 }
1257
1258 out.endTag(null, TAG_ROOT);
1259 }
1260
Makoto Onuki0acbb142016-03-22 17:02:57 -07001261 private static void saveShortcut(XmlSerializer out, ShortcutInfo si, boolean forBackup)
Makoto Onuki31459242016-03-22 11:12:18 -07001262 throws IOException, XmlPullParserException {
Makoto Onuki0acbb142016-03-22 17:02:57 -07001263 if (forBackup) {
Makoto Onukif3ba2e02016-07-12 09:18:50 -07001264 if (!(si.isPinned() && si.isEnabled())) {
1265 return; // We only backup pinned shortcuts that are enabled.
Makoto Onuki0acbb142016-03-22 17:02:57 -07001266 }
1267 }
Makoto Onuki31459242016-03-22 11:12:18 -07001268 out.startTag(null, TAG_SHORTCUT);
1269 ShortcutService.writeAttr(out, ATTR_ID, si.getId());
1270 // writeAttr(out, "package", si.getPackageName()); // not needed
Makoto Onuki22fcc682016-05-17 14:52:19 -07001271 ShortcutService.writeAttr(out, ATTR_ACTIVITY, si.getActivity());
Makoto Onuki31459242016-03-22 11:12:18 -07001272 // writeAttr(out, "icon", si.getIcon()); // We don't save it.
1273 ShortcutService.writeAttr(out, ATTR_TITLE, si.getTitle());
Makoto Onuki20c95f82016-05-11 16:51:01 -07001274 ShortcutService.writeAttr(out, ATTR_TITLE_RES_ID, si.getTitleResId());
Makoto Onuki157b1622016-06-02 16:13:10 -07001275 ShortcutService.writeAttr(out, ATTR_TITLE_RES_NAME, si.getTitleResName());
Makoto Onukie3ae7ec2016-03-29 15:45:25 -07001276 ShortcutService.writeAttr(out, ATTR_TEXT, si.getText());
Makoto Onuki20c95f82016-05-11 16:51:01 -07001277 ShortcutService.writeAttr(out, ATTR_TEXT_RES_ID, si.getTextResId());
Makoto Onuki157b1622016-06-02 16:13:10 -07001278 ShortcutService.writeAttr(out, ATTR_TEXT_RES_NAME, si.getTextResName());
Makoto Onuki20c95f82016-05-11 16:51:01 -07001279 ShortcutService.writeAttr(out, ATTR_DISABLED_MESSAGE, si.getDisabledMessage());
Makoto Onukieddbfec2016-05-31 17:04:34 -07001280 ShortcutService.writeAttr(out, ATTR_DISABLED_MESSAGE_RES_ID,
1281 si.getDisabledMessageResourceId());
Makoto Onuki157b1622016-06-02 16:13:10 -07001282 ShortcutService.writeAttr(out, ATTR_DISABLED_MESSAGE_RES_NAME,
1283 si.getDisabledMessageResName());
Makoto Onuki31459242016-03-22 11:12:18 -07001284 ShortcutService.writeAttr(out, ATTR_TIMESTAMP,
1285 si.getLastChangedTimestamp());
Makoto Onuki0acbb142016-03-22 17:02:57 -07001286 if (forBackup) {
1287 // Don't write icon information. Also drop the dynamic flag.
1288 ShortcutService.writeAttr(out, ATTR_FLAGS,
1289 si.getFlags() &
1290 ~(ShortcutInfo.FLAG_HAS_ICON_FILE | ShortcutInfo.FLAG_HAS_ICON_RES
1291 | ShortcutInfo.FLAG_DYNAMIC));
1292 } else {
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001293 // When writing for backup, ranks shouldn't be saved, since shortcuts won't be restored
1294 // as dynamic.
1295 ShortcutService.writeAttr(out, ATTR_RANK, si.getRank());
1296
Makoto Onuki0acbb142016-03-22 17:02:57 -07001297 ShortcutService.writeAttr(out, ATTR_FLAGS, si.getFlags());
Makoto Onuki157b1622016-06-02 16:13:10 -07001298 ShortcutService.writeAttr(out, ATTR_ICON_RES_ID, si.getIconResourceId());
1299 ShortcutService.writeAttr(out, ATTR_ICON_RES_NAME, si.getIconResName());
Makoto Onuki0acbb142016-03-22 17:02:57 -07001300 ShortcutService.writeAttr(out, ATTR_BITMAP_PATH, si.getBitmapPath());
1301 }
Makoto Onuki31459242016-03-22 11:12:18 -07001302
Makoto Onukib6d35232016-04-04 15:57:17 -07001303 {
Makoto Onukibe73a802016-04-15 14:46:35 -07001304 final Set<String> cat = si.getCategories();
Makoto Onukib6d35232016-04-04 15:57:17 -07001305 if (cat != null && cat.size() > 0) {
1306 out.startTag(null, TAG_CATEGORIES);
1307 XmlUtils.writeStringArrayXml(cat.toArray(new String[cat.size()]),
1308 NAME_CATEGORIES, out);
1309 out.endTag(null, TAG_CATEGORIES);
1310 }
1311 }
Makoto Onuki440a1ea2016-07-20 14:21:18 -07001312 final Intent[] intentsNoExtras = si.getIntentsNoExtras();
1313 final PersistableBundle[] intentsExtras = si.getIntentPersistableExtrases();
1314 final int numIntents = intentsNoExtras.length;
1315 for (int i = 0; i < numIntents; i++) {
1316 out.startTag(null, TAG_INTENT);
1317 ShortcutService.writeAttr(out, ATTR_INTENT_NO_EXTRA, intentsNoExtras[i]);
1318 ShortcutService.writeTagExtra(out, TAG_EXTRAS, intentsExtras[i]);
1319 out.endTag(null, TAG_INTENT);
1320 }
Makoto Onukib6d35232016-04-04 15:57:17 -07001321
Makoto Onuki31459242016-03-22 11:12:18 -07001322 ShortcutService.writeTagExtra(out, TAG_EXTRAS, si.getExtras());
1323
1324 out.endTag(null, TAG_SHORTCUT);
1325 }
1326
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001327 public static ShortcutPackage loadFromXml(ShortcutService s, ShortcutUser shortcutUser,
1328 XmlPullParser parser, boolean fromBackup)
Makoto Onuki31459242016-03-22 11:12:18 -07001329 throws IOException, XmlPullParserException {
1330
1331 final String packageName = ShortcutService.parseStringAttribute(parser,
1332 ATTR_NAME);
1333
Makoto Onukic51b2872016-05-04 15:24:50 -07001334 final ShortcutPackage ret = new ShortcutPackage(shortcutUser,
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001335 shortcutUser.getUserId(), packageName);
Makoto Onuki31459242016-03-22 11:12:18 -07001336
Makoto Onuki31459242016-03-22 11:12:18 -07001337 ret.mApiCallCount =
1338 ShortcutService.parseIntAttribute(parser, ATTR_CALL_COUNT);
1339 ret.mLastResetTime =
1340 ShortcutService.parseLongAttribute(parser, ATTR_LAST_RESET);
1341
1342 final int outerDepth = parser.getDepth();
1343 int type;
1344 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1345 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1346 if (type != XmlPullParser.START_TAG) {
1347 continue;
1348 }
1349 final int depth = parser.getDepth();
1350 final String tag = parser.getName();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001351 if (depth == outerDepth + 1) {
1352 switch (tag) {
1353 case ShortcutPackageInfo.TAG_ROOT:
Makoto Onuki2e210c42016-03-30 08:30:36 -07001354 ret.getPackageInfo().loadFromXml(parser, fromBackup);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001355 continue;
1356 case TAG_SHORTCUT:
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001357 final ShortcutInfo si = parseShortcut(parser, packageName,
1358 shortcutUser.getUserId());
Makoto Onuki31459242016-03-22 11:12:18 -07001359
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001360 // Don't use addShortcut(), we don't need to save the icon.
1361 ret.mShortcuts.put(si.getId(), si);
1362 continue;
1363 }
Makoto Onuki31459242016-03-22 11:12:18 -07001364 }
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001365 ShortcutService.warnForInvalidTag(depth, tag);
1366 }
Makoto Onuki31459242016-03-22 11:12:18 -07001367 return ret;
1368 }
1369
Makoto Onukiabe84422016-04-07 09:41:19 -07001370 private static ShortcutInfo parseShortcut(XmlPullParser parser, String packageName,
1371 @UserIdInt int userId) throws IOException, XmlPullParserException {
Makoto Onuki31459242016-03-22 11:12:18 -07001372 String id;
1373 ComponentName activityComponent;
1374 // Icon icon;
1375 String title;
Makoto Onuki20c95f82016-05-11 16:51:01 -07001376 int titleResId;
Makoto Onuki157b1622016-06-02 16:13:10 -07001377 String titleResName;
Makoto Onukie3ae7ec2016-03-29 15:45:25 -07001378 String text;
Makoto Onuki20c95f82016-05-11 16:51:01 -07001379 int textResId;
Makoto Onuki157b1622016-06-02 16:13:10 -07001380 String textResName;
Makoto Onuki20c95f82016-05-11 16:51:01 -07001381 String disabledMessage;
1382 int disabledMessageResId;
Makoto Onuki157b1622016-06-02 16:13:10 -07001383 String disabledMessageResName;
Makoto Onuki440a1ea2016-07-20 14:21:18 -07001384 Intent intentLegacy;
1385 PersistableBundle intentPersistableExtrasLegacy = null;
1386 ArrayList<Intent> intents = new ArrayList<>();
Makoto Onuki20c95f82016-05-11 16:51:01 -07001387 int rank;
Makoto Onuki31459242016-03-22 11:12:18 -07001388 PersistableBundle extras = null;
1389 long lastChangedTimestamp;
1390 int flags;
Makoto Onuki157b1622016-06-02 16:13:10 -07001391 int iconResId;
1392 String iconResName;
Makoto Onuki31459242016-03-22 11:12:18 -07001393 String bitmapPath;
Makoto Onukibe73a802016-04-15 14:46:35 -07001394 ArraySet<String> categories = null;
Makoto Onuki31459242016-03-22 11:12:18 -07001395
1396 id = ShortcutService.parseStringAttribute(parser, ATTR_ID);
1397 activityComponent = ShortcutService.parseComponentNameAttribute(parser,
1398 ATTR_ACTIVITY);
1399 title = ShortcutService.parseStringAttribute(parser, ATTR_TITLE);
Makoto Onuki20c95f82016-05-11 16:51:01 -07001400 titleResId = ShortcutService.parseIntAttribute(parser, ATTR_TITLE_RES_ID);
Makoto Onuki157b1622016-06-02 16:13:10 -07001401 titleResName = ShortcutService.parseStringAttribute(parser, ATTR_TITLE_RES_NAME);
Makoto Onukie3ae7ec2016-03-29 15:45:25 -07001402 text = ShortcutService.parseStringAttribute(parser, ATTR_TEXT);
Makoto Onuki20c95f82016-05-11 16:51:01 -07001403 textResId = ShortcutService.parseIntAttribute(parser, ATTR_TEXT_RES_ID);
Makoto Onuki157b1622016-06-02 16:13:10 -07001404 textResName = ShortcutService.parseStringAttribute(parser, ATTR_TEXT_RES_NAME);
Makoto Onuki20c95f82016-05-11 16:51:01 -07001405 disabledMessage = ShortcutService.parseStringAttribute(parser, ATTR_DISABLED_MESSAGE);
1406 disabledMessageResId = ShortcutService.parseIntAttribute(parser,
1407 ATTR_DISABLED_MESSAGE_RES_ID);
Makoto Onuki157b1622016-06-02 16:13:10 -07001408 disabledMessageResName = ShortcutService.parseStringAttribute(parser,
1409 ATTR_DISABLED_MESSAGE_RES_NAME);
Makoto Onuki440a1ea2016-07-20 14:21:18 -07001410 intentLegacy = ShortcutService.parseIntentAttributeNoDefault(parser, ATTR_INTENT_LEGACY);
Makoto Onuki20c95f82016-05-11 16:51:01 -07001411 rank = (int) ShortcutService.parseLongAttribute(parser, ATTR_RANK);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001412 lastChangedTimestamp = ShortcutService.parseLongAttribute(parser, ATTR_TIMESTAMP);
Makoto Onuki31459242016-03-22 11:12:18 -07001413 flags = (int) ShortcutService.parseLongAttribute(parser, ATTR_FLAGS);
Makoto Onuki157b1622016-06-02 16:13:10 -07001414 iconResId = (int) ShortcutService.parseLongAttribute(parser, ATTR_ICON_RES_ID);
1415 iconResName = ShortcutService.parseStringAttribute(parser, ATTR_ICON_RES_NAME);
Makoto Onuki31459242016-03-22 11:12:18 -07001416 bitmapPath = ShortcutService.parseStringAttribute(parser, ATTR_BITMAP_PATH);
1417
1418 final int outerDepth = parser.getDepth();
1419 int type;
1420 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1421 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1422 if (type != XmlPullParser.START_TAG) {
1423 continue;
1424 }
1425 final int depth = parser.getDepth();
1426 final String tag = parser.getName();
1427 if (ShortcutService.DEBUG_LOAD) {
1428 Slog.d(TAG, String.format(" depth=%d type=%d name=%s",
1429 depth, type, tag));
1430 }
1431 switch (tag) {
Makoto Onuki440a1ea2016-07-20 14:21:18 -07001432 case TAG_INTENT_EXTRAS_LEGACY:
1433 intentPersistableExtrasLegacy = PersistableBundle.restoreFromXml(parser);
1434 continue;
1435 case TAG_INTENT:
1436 intents.add(parseIntent(parser));
Makoto Onuki31459242016-03-22 11:12:18 -07001437 continue;
1438 case TAG_EXTRAS:
1439 extras = PersistableBundle.restoreFromXml(parser);
1440 continue;
Makoto Onukib6d35232016-04-04 15:57:17 -07001441 case TAG_CATEGORIES:
1442 // This just contains string-array.
1443 continue;
1444 case TAG_STRING_ARRAY_XMLUTILS:
1445 if (NAME_CATEGORIES.equals(ShortcutService.parseStringAttribute(parser,
1446 ATTR_NAME_XMLUTILS))) {
Makoto Onukibe73a802016-04-15 14:46:35 -07001447 final String[] ar = XmlUtils.readThisStringArrayXml(
1448 parser, TAG_STRING_ARRAY_XMLUTILS, null);
1449 categories = new ArraySet<>(ar.length);
1450 for (int i = 0; i < ar.length; i++) {
1451 categories.add(ar[i]);
1452 }
Makoto Onukib6d35232016-04-04 15:57:17 -07001453 }
1454 continue;
Makoto Onuki31459242016-03-22 11:12:18 -07001455 }
1456 throw ShortcutService.throwForInvalidTag(depth, tag);
1457 }
Makoto Onukibe73a802016-04-15 14:46:35 -07001458
Makoto Onuki440a1ea2016-07-20 14:21:18 -07001459 if (intentLegacy != null) {
1460 // For the legacy file format which supported only one intent per shortcut.
1461 ShortcutInfo.setIntentExtras(intentLegacy, intentPersistableExtrasLegacy);
1462 intents.clear();
1463 intents.add(intentLegacy);
1464 }
1465
Makoto Onuki31459242016-03-22 11:12:18 -07001466 return new ShortcutInfo(
Makoto Onuki20c95f82016-05-11 16:51:01 -07001467 userId, id, packageName, activityComponent, /* icon =*/ null,
Makoto Onuki157b1622016-06-02 16:13:10 -07001468 title, titleResId, titleResName, text, textResId, textResName,
1469 disabledMessage, disabledMessageResId, disabledMessageResName,
Makoto Onuki440a1ea2016-07-20 14:21:18 -07001470 categories,
1471 intents.toArray(new Intent[intents.size()]),
1472 rank, extras, lastChangedTimestamp, flags,
Makoto Onuki157b1622016-06-02 16:13:10 -07001473 iconResId, iconResName, bitmapPath);
Makoto Onuki31459242016-03-22 11:12:18 -07001474 }
Makoto Onuki2e210c42016-03-30 08:30:36 -07001475
Makoto Onuki440a1ea2016-07-20 14:21:18 -07001476 private static Intent parseIntent(XmlPullParser parser)
1477 throws IOException, XmlPullParserException {
1478
1479 Intent intent = ShortcutService.parseIntentAttribute(parser,
1480 ATTR_INTENT_NO_EXTRA);
1481
1482 final int outerDepth = parser.getDepth();
1483 int type;
1484 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1485 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1486 if (type != XmlPullParser.START_TAG) {
1487 continue;
1488 }
1489 final int depth = parser.getDepth();
1490 final String tag = parser.getName();
1491 if (ShortcutService.DEBUG_LOAD) {
1492 Slog.d(TAG, String.format(" depth=%d type=%d name=%s",
1493 depth, type, tag));
1494 }
1495 switch (tag) {
1496 case TAG_EXTRAS:
1497 ShortcutInfo.setIntentExtras(intent,
1498 PersistableBundle.restoreFromXml(parser));
1499 continue;
1500 }
1501 throw ShortcutService.throwForInvalidTag(depth, tag);
1502 }
1503 return intent;
1504 }
1505
Makoto Onuki2e210c42016-03-30 08:30:36 -07001506 @VisibleForTesting
1507 List<ShortcutInfo> getAllShortcutsForTest() {
1508 return new ArrayList<>(mShortcuts.values());
1509 }
Makoto Onuki7001a612016-05-27 13:24:28 -07001510
1511 @Override
1512 public void verifyStates() {
1513 super.verifyStates();
1514
1515 boolean failed = false;
1516
1517 final ArrayMap<ComponentName, ArrayList<ShortcutInfo>> all =
1518 sortShortcutsToActivities();
1519
1520 // Make sure each activity won't have more than max shortcuts.
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001521 for (int outer = all.size() - 1; outer >= 0; outer--) {
1522 final ArrayList<ShortcutInfo> list = all.valueAt(outer);
1523 if (list.size() > mShortcutUser.mService.getMaxActivityShortcuts()) {
Makoto Onuki7001a612016-05-27 13:24:28 -07001524 failed = true;
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001525 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": activity " + all.keyAt(outer)
1526 + " has " + all.valueAt(outer).size() + " shortcuts.");
Makoto Onuki7001a612016-05-27 13:24:28 -07001527 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001528
1529 // Sort by rank.
1530 Collections.sort(list, (a, b) -> Integer.compare(a.getRank(), b.getRank()));
1531
1532 // Split into two arrays for each kind.
1533 final ArrayList<ShortcutInfo> dynamicList = new ArrayList<>(list);
1534 dynamicList.removeIf((si) -> !si.isDynamic());
1535
1536 final ArrayList<ShortcutInfo> manifestList = new ArrayList<>(list);
1537 dynamicList.removeIf((si) -> !si.isManifestShortcut());
1538
1539 verifyRanksSequential(dynamicList);
1540 verifyRanksSequential(manifestList);
Makoto Onuki7001a612016-05-27 13:24:28 -07001541 }
1542
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001543 // Verify each shortcut's status.
Makoto Onuki7001a612016-05-27 13:24:28 -07001544 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1545 final ShortcutInfo si = mShortcuts.valueAt(i);
Makoto Onukiff14f732016-06-30 17:07:25 -07001546 if (!(si.isDeclaredInManifest() || si.isDynamic() || si.isPinned())) {
Makoto Onuki7001a612016-05-27 13:24:28 -07001547 failed = true;
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001548 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
Makoto Onuki7001a612016-05-27 13:24:28 -07001549 + " is not manifest, dynamic or pinned.");
1550 }
Makoto Onukiff14f732016-06-30 17:07:25 -07001551 if (si.isDeclaredInManifest() && si.isDynamic()) {
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001552 failed = true;
1553 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1554 + " is both dynamic and manifest at the same time.");
1555 }
Makoto Onuki7001a612016-05-27 13:24:28 -07001556 if (si.getActivity() == null) {
1557 failed = true;
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001558 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
Makoto Onuki7001a612016-05-27 13:24:28 -07001559 + " has null activity.");
1560 }
1561 if ((si.isDynamic() || si.isManifestShortcut()) && !si.isEnabled()) {
1562 failed = true;
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001563 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
Makoto Onuki7001a612016-05-27 13:24:28 -07001564 + " is not floating, but is disabled.");
1565 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001566 if (si.isFloating() && si.getRank() != 0) {
1567 failed = true;
1568 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1569 + " is floating, but has rank=" + si.getRank());
1570 }
Makoto Onukidd097812016-06-29 13:10:09 -07001571 if (si.getIcon() != null) {
1572 failed = true;
1573 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1574 + " still has an icon");
1575 }
1576 if (si.hasIconFile() && si.hasIconResource()) {
1577 failed = true;
1578 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1579 + " has both resource and bitmap icons");
1580 }
Makoto Onuki7001a612016-05-27 13:24:28 -07001581 }
1582
1583 if (failed) {
1584 throw new IllegalStateException("See logcat for errors");
1585 }
1586 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001587
1588 private boolean verifyRanksSequential(List<ShortcutInfo> list) {
1589 boolean failed = false;
1590
1591 for (int i = 0; i < list.size(); i++) {
1592 final ShortcutInfo si = list.get(i);
1593 if (si.getRank() != i) {
1594 failed = true;
1595 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1596 + " rank=" + si.getRank() + " but expected to be "+ i);
1597 }
1598 }
1599 return failed;
1600 }
Makoto Onuki31459242016-03-22 11:12:18 -07001601}