blob: 3c1819880806dcbdc8d2e3fc79fc284f0c30be71 [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 Onuki31459242016-03-22 11:12:18 -070039import org.xmlpull.v1.XmlPullParser;
40import org.xmlpull.v1.XmlPullParserException;
41import org.xmlpull.v1.XmlSerializer;
42
43import java.io.File;
44import java.io.IOException;
45import java.io.PrintWriter;
46import java.util.ArrayList;
Makoto Onuki7001a612016-05-27 13:24:28 -070047import java.util.Collections;
48import java.util.Comparator;
Makoto Onuki31459242016-03-22 11:12:18 -070049import java.util.List;
Makoto Onukibe73a802016-04-15 14:46:35 -070050import java.util.Set;
Makoto Onuki31459242016-03-22 11:12:18 -070051import java.util.function.Predicate;
52
53/**
54 * Package information used by {@link ShortcutService}.
Makoto Onuki22fcc682016-05-17 14:52:19 -070055 * User information used by {@link ShortcutService}.
56 *
57 * All methods should be guarded by {@code #mShortcutUser.mService.mLock}.
Makoto Onuki31459242016-03-22 11:12:18 -070058 */
Makoto Onuki9da23fc2016-03-29 11:14:42 -070059class ShortcutPackage extends ShortcutPackageItem {
Makoto Onuki31459242016-03-22 11:12:18 -070060 private static final String TAG = ShortcutService.TAG;
Makoto Onuki9e1f5592016-06-08 12:30:23 -070061 private static final String TAG_VERIFY = ShortcutService.TAG + ".verify";
Makoto Onuki31459242016-03-22 11:12:18 -070062
63 static final String TAG_ROOT = "package";
64 private static final String TAG_INTENT_EXTRAS = "intent-extras";
65 private static final String TAG_EXTRAS = "extras";
66 private static final String TAG_SHORTCUT = "shortcut";
Makoto Onukib6d35232016-04-04 15:57:17 -070067 private static final String TAG_CATEGORIES = "categories";
Makoto Onuki31459242016-03-22 11:12:18 -070068
69 private static final String ATTR_NAME = "name";
Makoto Onuki31459242016-03-22 11:12:18 -070070 private static final String ATTR_CALL_COUNT = "call-count";
71 private static final String ATTR_LAST_RESET = "last-reset";
72 private static final String ATTR_ID = "id";
73 private static final String ATTR_ACTIVITY = "activity";
74 private static final String ATTR_TITLE = "title";
Makoto Onuki20c95f82016-05-11 16:51:01 -070075 private static final String ATTR_TITLE_RES_ID = "titleid";
Makoto Onuki157b1622016-06-02 16:13:10 -070076 private static final String ATTR_TITLE_RES_NAME = "titlename";
Makoto Onukie3ae7ec2016-03-29 15:45:25 -070077 private static final String ATTR_TEXT = "text";
Makoto Onuki20c95f82016-05-11 16:51:01 -070078 private static final String ATTR_TEXT_RES_ID = "textid";
Makoto Onuki157b1622016-06-02 16:13:10 -070079 private static final String ATTR_TEXT_RES_NAME = "textname";
Makoto Onuki20c95f82016-05-11 16:51:01 -070080 private static final String ATTR_DISABLED_MESSAGE = "dmessage";
81 private static final String ATTR_DISABLED_MESSAGE_RES_ID = "dmessageid";
Makoto Onuki157b1622016-06-02 16:13:10 -070082 private static final String ATTR_DISABLED_MESSAGE_RES_NAME = "dmessagename";
Makoto Onuki31459242016-03-22 11:12:18 -070083 private static final String ATTR_INTENT = "intent";
Makoto Onuki20c95f82016-05-11 16:51:01 -070084 private static final String ATTR_RANK = "rank";
Makoto Onuki31459242016-03-22 11:12:18 -070085 private static final String ATTR_TIMESTAMP = "timestamp";
86 private static final String ATTR_FLAGS = "flags";
Makoto Onuki157b1622016-06-02 16:13:10 -070087 private static final String ATTR_ICON_RES_ID = "icon-res";
88 private static final String ATTR_ICON_RES_NAME = "icon-resname";
Makoto Onuki31459242016-03-22 11:12:18 -070089 private static final String ATTR_BITMAP_PATH = "bitmap-path";
90
Makoto Onukib6d35232016-04-04 15:57:17 -070091 private static final String NAME_CATEGORIES = "categories";
92
93 private static final String TAG_STRING_ARRAY_XMLUTILS = "string-array";
94 private static final String ATTR_NAME_XMLUTILS = "name";
95
Makoto Onuki31459242016-03-22 11:12:18 -070096 /**
97 * All the shortcuts from the package, keyed on IDs.
98 */
99 final private ArrayMap<String, ShortcutInfo> mShortcuts = new ArrayMap<>();
100
101 /**
Makoto Onuki31459242016-03-22 11:12:18 -0700102 * # of times the package has called rate-limited APIs.
103 */
104 private int mApiCallCount;
105
106 /**
107 * When {@link #mApiCallCount} was reset last time.
108 */
109 private long mLastResetTime;
110
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700111 private final int mPackageUid;
112
113 private long mLastKnownForegroundElapsedTime;
114
Makoto Onukic51b2872016-05-04 15:24:50 -0700115 private ShortcutPackage(ShortcutUser shortcutUser,
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700116 int packageUserId, String packageName, ShortcutPackageInfo spi) {
117 super(shortcutUser, packageUserId, packageName,
118 spi != null ? spi : ShortcutPackageInfo.newEmpty());
119
Makoto Onukic51b2872016-05-04 15:24:50 -0700120 mPackageUid = shortcutUser.mService.injectGetPackageUid(packageName, packageUserId);
Makoto Onuki31459242016-03-22 11:12:18 -0700121 }
122
Makoto Onukic51b2872016-05-04 15:24:50 -0700123 public ShortcutPackage(ShortcutUser shortcutUser, int packageUserId, String packageName) {
124 this(shortcutUser, packageUserId, packageName, null);
Makoto Onuki0acbb142016-03-22 17:02:57 -0700125 }
126
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700127 @Override
128 public int getOwnerUserId() {
129 // For packages, always owner user == package user.
130 return getPackageUserId();
Makoto Onuki0acbb142016-03-22 17:02:57 -0700131 }
132
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700133 public int getPackageUid() {
134 return mPackageUid;
135 }
136
Makoto Onuki39686e82016-04-13 18:03:00 -0700137 /**
Makoto Onuki7001a612016-05-27 13:24:28 -0700138 * Called when a shortcut is about to be published. At this point we know the publisher
139 * package
Makoto Onuki39686e82016-04-13 18:03:00 -0700140 * exists (as opposed to Launcher trying to fetch shortcuts from a non-existent package), so
141 * we do some initialization for the package.
142 */
Makoto Onuki22fcc682016-05-17 14:52:19 -0700143 private void ensurePackageVersionInfo() {
Makoto Onuki39686e82016-04-13 18:03:00 -0700144 // Make sure we have the version code for the app. We need the version code in
145 // handlePackageUpdated().
146 if (getPackageInfo().getVersionCode() < 0) {
Makoto Onukic51b2872016-05-04 15:24:50 -0700147 final ShortcutService s = mShortcutUser.mService;
148
Makoto Onuki22fcc682016-05-17 14:52:19 -0700149 final PackageInfo pi = s.getPackageInfo(getPackageName(), getOwnerUserId());
150 if (pi != null) {
151 if (ShortcutService.DEBUG) {
152 Slog.d(TAG, String.format("Package %s version = %d", getPackageName(),
153 pi.versionCode));
154 }
155 getPackageInfo().updateVersionInfo(pi);
Makoto Onuki39686e82016-04-13 18:03:00 -0700156 s.scheduleSaveUser(getOwnerUserId());
157 }
158 }
159 }
160
Makoto Onuki157b1622016-06-02 16:13:10 -0700161 @Nullable
162 public Resources getPackageResources() {
163 return mShortcutUser.mService.injectGetResourcesForApplicationAsUser(
164 getPackageName(), getPackageUserId());
165 }
166
Makoto Onuki2e210c42016-03-30 08:30:36 -0700167 @Override
Makoto Onukic51b2872016-05-04 15:24:50 -0700168 protected void onRestoreBlocked() {
Makoto Onuki2e210c42016-03-30 08:30:36 -0700169 // Can't restore due to version/signature mismatch. Remove all shortcuts.
170 mShortcuts.clear();
171 }
172
173 @Override
Makoto Onukic51b2872016-05-04 15:24:50 -0700174 protected void onRestored() {
Makoto Onuki2e210c42016-03-30 08:30:36 -0700175 // Because some launchers may not have been restored (e.g. allowBackup=false),
176 // we need to re-calculate the pinned shortcuts.
Makoto Onukic51b2872016-05-04 15:24:50 -0700177 refreshPinnedFlags();
Makoto Onuki2e210c42016-03-30 08:30:36 -0700178 }
179
Makoto Onukid99c6f02016-03-28 11:02:54 -0700180 /**
181 * Note this does *not* provide a correct view to the calling launcher.
182 */
Makoto Onuki31459242016-03-22 11:12:18 -0700183 @Nullable
184 public ShortcutInfo findShortcutById(String id) {
185 return mShortcuts.get(id);
186 }
187
Makoto Onuki22fcc682016-05-17 14:52:19 -0700188 private void ensureNotImmutable(@Nullable ShortcutInfo shortcut) {
189 if (shortcut != null && shortcut.isImmutable()) {
190 throw new IllegalArgumentException(
191 "Manifest shortcut ID=" + shortcut.getId()
192 + " may not be manipulated via APIs");
193 }
194 }
195
196 private void ensureNotImmutable(@NonNull String id) {
197 ensureNotImmutable(mShortcuts.get(id));
198 }
199
200 public void ensureImmutableShortcutsNotIncludedWithIds(@NonNull List<String> shortcutIds) {
201 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
202 ensureNotImmutable(shortcutIds.get(i));
203 }
204 }
205
206 public void ensureImmutableShortcutsNotIncluded(@NonNull List<ShortcutInfo> shortcuts) {
207 for (int i = shortcuts.size() - 1; i >= 0; i--) {
208 ensureNotImmutable(shortcuts.get(i).getId());
209 }
210 }
211
212 private ShortcutInfo deleteShortcutInner(@NonNull String id) {
Makoto Onuki31459242016-03-22 11:12:18 -0700213 final ShortcutInfo shortcut = mShortcuts.remove(id);
214 if (shortcut != null) {
Makoto Onukic51b2872016-05-04 15:24:50 -0700215 mShortcutUser.mService.removeIcon(getPackageUserId(), shortcut);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700216 shortcut.clearFlags(ShortcutInfo.FLAG_DYNAMIC | ShortcutInfo.FLAG_PINNED
217 | ShortcutInfo.FLAG_MANIFEST);
Makoto Onuki31459242016-03-22 11:12:18 -0700218 }
219 return shortcut;
220 }
221
Makoto Onuki22fcc682016-05-17 14:52:19 -0700222 private void addShortcutInner(@NonNull ShortcutInfo newShortcut) {
Makoto Onuki157b1622016-06-02 16:13:10 -0700223 final ShortcutService s = mShortcutUser.mService;
224
Makoto Onuki22fcc682016-05-17 14:52:19 -0700225 deleteShortcutInner(newShortcut.getId());
Makoto Onuki157b1622016-06-02 16:13:10 -0700226
227 // Extract Icon and update the icon res ID and the bitmap path.
228 s.saveIconAndFixUpShortcut(getPackageUserId(), newShortcut);
229 s.fixUpShortcutResourceNamesAndValues(newShortcut);
Makoto Onuki31459242016-03-22 11:12:18 -0700230 mShortcuts.put(newShortcut.getId(), newShortcut);
231 }
232
233 /**
234 * Add a shortcut, or update one with the same ID, with taking over existing flags.
235 *
236 * It checks the max number of dynamic shortcuts.
237 */
Makoto Onuki22fcc682016-05-17 14:52:19 -0700238 public void addOrUpdateDynamicShortcut(@NonNull ShortcutInfo newShortcut) {
Makoto Onuki39686e82016-04-13 18:03:00 -0700239
Makoto Onuki22fcc682016-05-17 14:52:19 -0700240 Preconditions.checkArgument(newShortcut.isEnabled(),
241 "add/setDynamicShortcuts() cannot publish disabled shortcuts");
242
243 ensurePackageVersionInfo();
Makoto Onuki39686e82016-04-13 18:03:00 -0700244
Makoto Onuki31459242016-03-22 11:12:18 -0700245 newShortcut.addFlags(ShortcutInfo.FLAG_DYNAMIC);
246
247 final ShortcutInfo oldShortcut = mShortcuts.get(newShortcut.getId());
248
249 final boolean wasPinned;
Makoto Onuki31459242016-03-22 11:12:18 -0700250
251 if (oldShortcut == null) {
252 wasPinned = false;
Makoto Onuki31459242016-03-22 11:12:18 -0700253 } else {
Makoto Onuki22fcc682016-05-17 14:52:19 -0700254 // It's an update case.
255 // Make sure the target is updatable. (i.e. should be mutable.)
256 oldShortcut.ensureUpdatableWith(newShortcut);
257
Makoto Onuki31459242016-03-22 11:12:18 -0700258 wasPinned = oldShortcut.isPinned();
Makoto Onuki31459242016-03-22 11:12:18 -0700259 }
260
Makoto Onuki157b1622016-06-02 16:13:10 -0700261 // If it was originally pinned, the new one should be pinned too.
Makoto Onuki31459242016-03-22 11:12:18 -0700262 if (wasPinned) {
263 newShortcut.addFlags(ShortcutInfo.FLAG_PINNED);
264 }
265
Makoto Onuki22fcc682016-05-17 14:52:19 -0700266 addShortcutInner(newShortcut);
Makoto Onuki31459242016-03-22 11:12:18 -0700267 }
268
269 /**
270 * Remove all shortcuts that aren't pinned nor dynamic.
271 */
Makoto Onukic51b2872016-05-04 15:24:50 -0700272 private void removeOrphans() {
Makoto Onuki31459242016-03-22 11:12:18 -0700273 ArrayList<String> removeList = null; // Lazily initialize.
274
275 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
276 final ShortcutInfo si = mShortcuts.valueAt(i);
277
Makoto Onuki22fcc682016-05-17 14:52:19 -0700278 if (si.isAlive()) continue;
Makoto Onuki31459242016-03-22 11:12:18 -0700279
280 if (removeList == null) {
281 removeList = new ArrayList<>();
282 }
283 removeList.add(si.getId());
284 }
285 if (removeList != null) {
286 for (int i = removeList.size() - 1; i >= 0; i--) {
Makoto Onuki22fcc682016-05-17 14:52:19 -0700287 deleteShortcutInner(removeList.get(i));
Makoto Onuki31459242016-03-22 11:12:18 -0700288 }
289 }
290 }
291
292 /**
293 * Remove all dynamic shortcuts.
294 */
Makoto Onukic51b2872016-05-04 15:24:50 -0700295 public void deleteAllDynamicShortcuts() {
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700296 final long now = mShortcutUser.mService.injectCurrentTimeMillis();
297
Makoto Onuki22fcc682016-05-17 14:52:19 -0700298 boolean changed = false;
Makoto Onuki31459242016-03-22 11:12:18 -0700299 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
Makoto Onuki22fcc682016-05-17 14:52:19 -0700300 final ShortcutInfo si = mShortcuts.valueAt(i);
301 if (si.isDynamic()) {
302 changed = true;
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700303
304 si.setTimestamp(now);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700305 si.clearFlags(ShortcutInfo.FLAG_DYNAMIC);
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700306 si.setRank(0); // It may still be pinned, so clear the rank.
Makoto Onuki22fcc682016-05-17 14:52:19 -0700307 }
Makoto Onuki31459242016-03-22 11:12:18 -0700308 }
Makoto Onuki22fcc682016-05-17 14:52:19 -0700309 if (changed) {
310 removeOrphans();
311 }
Makoto Onuki31459242016-03-22 11:12:18 -0700312 }
313
314 /**
Makoto Onuki7001a612016-05-27 13:24:28 -0700315 * Remove a dynamic shortcut by ID. It'll be removed from the dynamic set, but if the shortcut
316 * is pinned, it'll remain as a pinned shortcut, and is still enabled.
Makoto Onukib08790c2016-06-23 14:05:46 -0700317 *
318 * @return true if it's actually removed because it wasn't pinned, or false if it's still
319 * pinned.
Makoto Onuki31459242016-03-22 11:12:18 -0700320 */
Makoto Onukib08790c2016-06-23 14:05:46 -0700321 public boolean deleteDynamicWithId(@NonNull String shortcutId) {
322 final ShortcutInfo removed = deleteOrDisableWithId(
323 shortcutId, /* disable =*/ false, /* overrideImmutable=*/ false);
324 return removed == null;
325 }
326
327 /**
328 * Disable a dynamic shortcut by ID. It'll be removed from the dynamic set, but if the shortcut
329 * is pinned, it'll remain as a pinned shortcut, but will be disabled.
330 *
331 * @return true if it's actually removed because it wasn't pinned, or false if it's still
332 * pinned.
333 */
334 private boolean disableDynamicWithId(@NonNull String shortcutId) {
335 final ShortcutInfo disabled = deleteOrDisableWithId(
336 shortcutId, /* disable =*/ true, /* overrideImmutable=*/ false);
337 return disabled == null;
Makoto Onuki22fcc682016-05-17 14:52:19 -0700338 }
339
Makoto Onuki7001a612016-05-27 13:24:28 -0700340 /**
341 * Disable a dynamic shortcut by ID. It'll be removed from the dynamic set, but if the shortcut
342 * is pinned, it'll remain as a pinned shortcut but will be disabled.
343 */
Makoto Onuki22fcc682016-05-17 14:52:19 -0700344 public void disableWithId(@NonNull String shortcutId, String disabledMessage,
345 int disabledMessageResId, boolean overrideImmutable) {
346 final ShortcutInfo disabled = deleteOrDisableWithId(shortcutId, /* disable =*/ true,
347 overrideImmutable);
348
349 if (disabled != null) {
350 if (disabledMessage != null) {
351 disabled.setDisabledMessage(disabledMessage);
352 } else if (disabledMessageResId != 0) {
353 disabled.setDisabledMessageResId(disabledMessageResId);
Makoto Onuki157b1622016-06-02 16:13:10 -0700354
355 mShortcutUser.mService.fixUpShortcutResourceNamesAndValues(disabled);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700356 }
357 }
358 }
359
360 @Nullable
361 private ShortcutInfo deleteOrDisableWithId(@NonNull String shortcutId, boolean disable,
362 boolean overrideImmutable) {
Makoto Onuki31459242016-03-22 11:12:18 -0700363 final ShortcutInfo oldShortcut = mShortcuts.get(shortcutId);
364
Makoto Onuki22fcc682016-05-17 14:52:19 -0700365 if (oldShortcut == null || !oldShortcut.isEnabled()) {
366 return null; // Doesn't exist or already disabled.
Makoto Onuki31459242016-03-22 11:12:18 -0700367 }
Makoto Onuki22fcc682016-05-17 14:52:19 -0700368 if (!overrideImmutable) {
369 ensureNotImmutable(oldShortcut);
Makoto Onuki31459242016-03-22 11:12:18 -0700370 }
371 if (oldShortcut.isPinned()) {
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700372
373 oldShortcut.setRank(0);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700374 oldShortcut.clearFlags(ShortcutInfo.FLAG_DYNAMIC | ShortcutInfo.FLAG_MANIFEST);
375 if (disable) {
376 oldShortcut.addFlags(ShortcutInfo.FLAG_DISABLED);
377 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700378 oldShortcut.setTimestamp(mShortcutUser.mService.injectCurrentTimeMillis());
379
Makoto Onuki22fcc682016-05-17 14:52:19 -0700380 return oldShortcut;
Makoto Onuki31459242016-03-22 11:12:18 -0700381 } else {
Makoto Onuki22fcc682016-05-17 14:52:19 -0700382 deleteShortcutInner(shortcutId);
383 return null;
384 }
385 }
386
387 public void enableWithId(@NonNull String shortcutId) {
388 final ShortcutInfo shortcut = mShortcuts.get(shortcutId);
389 if (shortcut != null) {
390 ensureNotImmutable(shortcut);
391 shortcut.clearFlags(ShortcutInfo.FLAG_DISABLED);
Makoto Onuki31459242016-03-22 11:12:18 -0700392 }
393 }
394
395 /**
396 * Called after a launcher updates the pinned set. For each shortcut in this package,
397 * set FLAG_PINNED if any launcher has pinned it. Otherwise, clear it.
398 *
399 * <p>Then remove all shortcuts that are not dynamic and no longer pinned either.
400 */
Makoto Onukic51b2872016-05-04 15:24:50 -0700401 public void refreshPinnedFlags() {
Makoto Onuki31459242016-03-22 11:12:18 -0700402 // First, un-pin all shortcuts
403 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
404 mShortcuts.valueAt(i).clearFlags(ShortcutInfo.FLAG_PINNED);
405 }
406
407 // Then, for the pinned set for each launcher, set the pin flag one by one.
Makoto Onukic51b2872016-05-04 15:24:50 -0700408 mShortcutUser.mService.getUserShortcutsLocked(getPackageUserId())
409 .forAllLaunchers(launcherShortcuts -> {
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700410 final ArraySet<String> pinned = launcherShortcuts.getPinnedShortcutIds(
Makoto Onuki2e210c42016-03-30 08:30:36 -0700411 getPackageName(), getPackageUserId());
Makoto Onuki31459242016-03-22 11:12:18 -0700412
413 if (pinned == null || pinned.size() == 0) {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700414 return;
Makoto Onuki31459242016-03-22 11:12:18 -0700415 }
416 for (int i = pinned.size() - 1; i >= 0; i--) {
Makoto Onuki2e210c42016-03-30 08:30:36 -0700417 final String id = pinned.valueAt(i);
418 final ShortcutInfo si = mShortcuts.get(id);
Makoto Onuki31459242016-03-22 11:12:18 -0700419 if (si == null) {
Makoto Onuki2e210c42016-03-30 08:30:36 -0700420 // This happens if a launcher pinned shortcuts from this package, then backup&
421 // restored, but this package doesn't allow backing up.
422 // In that case the launcher ends up having a dangling pinned shortcuts.
423 // That's fine, when the launcher is restored, we'll fix it.
424 continue;
Makoto Onuki31459242016-03-22 11:12:18 -0700425 }
Makoto Onuki2e210c42016-03-30 08:30:36 -0700426 si.addFlags(ShortcutInfo.FLAG_PINNED);
Makoto Onuki31459242016-03-22 11:12:18 -0700427 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700428 });
Makoto Onuki31459242016-03-22 11:12:18 -0700429
430 // Lastly, remove the ones that are no longer pinned nor dynamic.
Makoto Onukic51b2872016-05-04 15:24:50 -0700431 removeOrphans();
Makoto Onuki31459242016-03-22 11:12:18 -0700432 }
433
434 /**
435 * Number of calls that the caller has made, since the last reset.
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700436 *
437 * <p>This takes care of the resetting the counter for foreground apps as well as after
438 * locale changes.
Makoto Onuki31459242016-03-22 11:12:18 -0700439 */
Makoto Onukic51b2872016-05-04 15:24:50 -0700440 public int getApiCallCount() {
Makoto Onukic51b2872016-05-04 15:24:50 -0700441 final ShortcutService s = mShortcutUser.mService;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700442
443 // Reset the counter if:
444 // - the package is in foreground now.
445 // - the package is *not* in foreground now, but was in foreground at some point
446 // since the previous time it had been.
447 if (s.isUidForegroundLocked(mPackageUid)
448 || mLastKnownForegroundElapsedTime
449 < s.getUidLastForegroundElapsedTimeLocked(mPackageUid)) {
450 mLastKnownForegroundElapsedTime = s.injectElapsedRealtime();
Makoto Onukic51b2872016-05-04 15:24:50 -0700451 resetRateLimiting();
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700452 }
453
454 // Note resetThrottlingIfNeeded() and resetRateLimiting() will set 0 to mApiCallCount,
455 // but we just can't return 0 at this point, because we may have to update
456 // mLastResetTime.
457
Makoto Onuki31459242016-03-22 11:12:18 -0700458 final long last = s.getLastResetTimeLocked();
459
460 final long now = s.injectCurrentTimeMillis();
461 if (ShortcutService.isClockValid(now) && mLastResetTime > now) {
462 Slog.w(TAG, "Clock rewound");
463 // Clock rewound.
464 mLastResetTime = now;
465 mApiCallCount = 0;
466 return mApiCallCount;
467 }
468
469 // If not reset yet, then reset.
470 if (mLastResetTime < last) {
471 if (ShortcutService.DEBUG) {
Makoto Onukic51b2872016-05-04 15:24:50 -0700472 Slog.d(TAG, String.format("%s: last reset=%d, now=%d, last=%d: resetting",
473 getPackageName(), mLastResetTime, now, last));
Makoto Onuki31459242016-03-22 11:12:18 -0700474 }
475 mApiCallCount = 0;
476 mLastResetTime = last;
477 }
478 return mApiCallCount;
479 }
480
481 /**
482 * If the caller app hasn't been throttled yet, increment {@link #mApiCallCount}
483 * and return true. Otherwise just return false.
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700484 *
485 * <p>This takes care of the resetting the counter for foreground apps as well as after
486 * locale changes, which is done internally by {@link #getApiCallCount}.
Makoto Onuki31459242016-03-22 11:12:18 -0700487 */
Makoto Onukic51b2872016-05-04 15:24:50 -0700488 public boolean tryApiCall() {
489 final ShortcutService s = mShortcutUser.mService;
490
491 if (getApiCallCount() >= s.mMaxUpdatesPerInterval) {
Makoto Onuki31459242016-03-22 11:12:18 -0700492 return false;
493 }
494 mApiCallCount++;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700495 s.scheduleSaveUser(getOwnerUserId());
Makoto Onuki31459242016-03-22 11:12:18 -0700496 return true;
497 }
498
Makoto Onukic51b2872016-05-04 15:24:50 -0700499 public void resetRateLimiting() {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700500 if (ShortcutService.DEBUG) {
501 Slog.d(TAG, "resetRateLimiting: " + getPackageName());
502 }
503 if (mApiCallCount > 0) {
504 mApiCallCount = 0;
Makoto Onukic51b2872016-05-04 15:24:50 -0700505 mShortcutUser.mService.scheduleSaveUser(getOwnerUserId());
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700506 }
507 }
508
509 public void resetRateLimitingForCommandLineNoSaving() {
Makoto Onuki31459242016-03-22 11:12:18 -0700510 mApiCallCount = 0;
511 mLastResetTime = 0;
512 }
513
514 /**
515 * Find all shortcuts that match {@code query}.
516 */
Makoto Onukic51b2872016-05-04 15:24:50 -0700517 public void findAll(@NonNull List<ShortcutInfo> result,
Makoto Onukid99c6f02016-03-28 11:02:54 -0700518 @Nullable Predicate<ShortcutInfo> query, int cloneFlag) {
Makoto Onukic51b2872016-05-04 15:24:50 -0700519 findAll(result, query, cloneFlag, null, 0);
Makoto Onukid99c6f02016-03-28 11:02:54 -0700520 }
521
522 /**
523 * Find all shortcuts that match {@code query}.
524 *
525 * This will also provide a "view" for each launcher -- a non-dynamic shortcut that's not pinned
526 * by the calling launcher will not be included in the result, and also "isPinned" will be
527 * adjusted for the caller too.
528 */
Makoto Onukic51b2872016-05-04 15:24:50 -0700529 public void findAll(@NonNull List<ShortcutInfo> result,
Makoto Onuki31459242016-03-22 11:12:18 -0700530 @Nullable Predicate<ShortcutInfo> query, int cloneFlag,
Makoto Onukid99c6f02016-03-28 11:02:54 -0700531 @Nullable String callingLauncher, int launcherUserId) {
Makoto Onuki2e210c42016-03-30 08:30:36 -0700532 if (getPackageInfo().isShadow()) {
533 // Restored and the app not installed yet, so don't return any.
534 return;
535 }
Makoto Onuki31459242016-03-22 11:12:18 -0700536
Makoto Onukic51b2872016-05-04 15:24:50 -0700537 final ShortcutService s = mShortcutUser.mService;
538
Makoto Onuki31459242016-03-22 11:12:18 -0700539 // Set of pinned shortcuts by the calling launcher.
540 final ArraySet<String> pinnedByCallerSet = (callingLauncher == null) ? null
Makoto Onuki2e210c42016-03-30 08:30:36 -0700541 : s.getLauncherShortcutsLocked(callingLauncher, getPackageUserId(), launcherUserId)
542 .getPinnedShortcutIds(getPackageName(), getPackageUserId());
Makoto Onuki31459242016-03-22 11:12:18 -0700543
544 for (int i = 0; i < mShortcuts.size(); i++) {
545 final ShortcutInfo si = mShortcuts.valueAt(i);
546
Makoto Onuki22fcc682016-05-17 14:52:19 -0700547 // Need to adjust PINNED flag depending on the caller.
548 // Basically if the caller is a launcher (callingLauncher != null) and the launcher
549 // isn't pinning it, then we need to clear PINNED for this caller.
Makoto Onuki31459242016-03-22 11:12:18 -0700550 final boolean isPinnedByCaller = (callingLauncher == null)
551 || ((pinnedByCallerSet != null) && pinnedByCallerSet.contains(si.getId()));
Makoto Onuki22fcc682016-05-17 14:52:19 -0700552
553 if (si.isFloating()) {
Makoto Onuki31459242016-03-22 11:12:18 -0700554 if (!isPinnedByCaller) {
555 continue;
556 }
557 }
558 final ShortcutInfo clone = si.clone(cloneFlag);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700559
Makoto Onuki31459242016-03-22 11:12:18 -0700560 // Fix up isPinned for the caller. Note we need to do it before the "test" callback,
561 // since it may check isPinned.
562 if (!isPinnedByCaller) {
563 clone.clearFlags(ShortcutInfo.FLAG_PINNED);
564 }
565 if (query == null || query.test(clone)) {
566 result.add(clone);
567 }
568 }
569 }
570
571 public void resetThrottling() {
572 mApiCallCount = 0;
573 }
574
Makoto Onuki39686e82016-04-13 18:03:00 -0700575 /**
Makoto Onuki6c1dbd52016-05-02 15:19:32 -0700576 * Return the filenames (excluding path names) of icon bitmap files from this package.
577 */
578 public ArraySet<String> getUsedBitmapFiles() {
579 final ArraySet<String> usedFiles = new ArraySet<>(mShortcuts.size());
580
581 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
582 final ShortcutInfo si = mShortcuts.valueAt(i);
583 if (si.getBitmapPath() != null) {
584 usedFiles.add(getFileName(si.getBitmapPath()));
585 }
586 }
587 return usedFiles;
588 }
589
590 private static String getFileName(@NonNull String path) {
591 final int sep = path.lastIndexOf(File.separatorChar);
592 if (sep == -1) {
593 return path;
594 } else {
595 return path.substring(sep + 1);
596 }
597 }
598
599 /**
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700600 * @return false if any of the target activities are no longer enabled.
601 */
602 private boolean areAllActivitiesStillEnabled() {
603 if (mShortcuts.size() == 0) {
604 return true;
605 }
606 final ShortcutService s = mShortcutUser.mService;
607
608 // Normally the number of target activities is 1 or so, so no need to use a complex
609 // structure like a set.
610 final ArrayList<ComponentName> checked = new ArrayList<>(4);
611
612 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
613 final ShortcutInfo si = mShortcuts.valueAt(i);
614 final ComponentName activity = si.getActivity();
615
616 if (checked.contains(activity)) {
617 continue; // Already checked.
618 }
619 checked.add(activity);
620
621 if (!s.injectIsActivityEnabledAndExported(activity, getOwnerUserId())) {
622 return false;
623 }
624 }
625 return true;
626 }
627
628 /**
629 * Called when the package may be added or updated, or its activities may be disabled, and
630 * if so, rescan the package and do the necessary stuff.
Makoto Onuki22fcc682016-05-17 14:52:19 -0700631 *
632 * Add case:
633 * - Publish manifest shortcuts.
634 *
635 * Update case:
636 * - Re-publish manifest shortcuts.
637 * - If there are shortcuts with resources (icons or strings), update their timestamps.
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700638 * - Disable shortcuts whose target activities are disabled.
Makoto Onuki22fcc682016-05-17 14:52:19 -0700639 *
640 * @return TRUE if any shortcuts have been changed.
Makoto Onuki39686e82016-04-13 18:03:00 -0700641 */
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700642 public boolean rescanPackageIfNeeded(boolean isNewApp, boolean forceRescan) {
643 final ShortcutService s = mShortcutUser.mService;
644 final long start = s.injectElapsedRealtime();
Makoto Onuki39686e82016-04-13 18:03:00 -0700645
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700646 final PackageInfo pi;
647 try {
648 pi = mShortcutUser.mService.getPackageInfo(
649 getPackageName(), getPackageUserId());
650 if (pi == null) {
651 return false; // Shouldn't happen.
Makoto Onuki22fcc682016-05-17 14:52:19 -0700652 }
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700653
654 if (!isNewApp && !forceRescan) {
655 // Return if the package hasn't changed, ie:
656 // - version code hasn't change
657 // - lastUpdateTime hasn't change
658 // - all target activities are still enabled.
659 if ((getPackageInfo().getVersionCode() >= pi.versionCode)
660 && (getPackageInfo().getLastUpdateTime() >= pi.lastUpdateTime)
661 && areAllActivitiesStillEnabled()) {
662 return false;
663 }
664 }
665 } finally {
666 s.logDurationStat(Stats.PACKAGE_UPDATE_CHECK, start);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700667 }
668
669 // Now prepare to publish manifest shortcuts.
670 List<ShortcutInfo> newManifestShortcutList = null;
671 try {
672 newManifestShortcutList = ShortcutParser.parseShortcuts(mShortcutUser.mService,
673 getPackageName(), getPackageUserId());
674 } catch (IOException|XmlPullParserException e) {
675 Slog.e(TAG, "Failed to load shortcuts from AndroidManifest.xml.", e);
676 }
677 final int manifestShortcutSize = newManifestShortcutList == null ? 0
678 : newManifestShortcutList.size();
679 if (ShortcutService.DEBUG) {
680 Slog.d(TAG, String.format("Package %s has %d manifest shortcut(s)",
681 getPackageName(), manifestShortcutSize));
682 }
683 if (isNewApp && (manifestShortcutSize == 0)) {
684 // If it's a new app, and it doesn't have manifest shortcuts, then nothing to do.
685
686 // If it's an update, then it may already have manifest shortcuts, which need to be
687 // disabled.
688 return false;
689 }
690 if (ShortcutService.DEBUG) {
691 Slog.d(TAG, String.format("Package %s %s, version %d -> %d", getPackageName(),
692 (isNewApp ? "added" : "updated"),
693 getPackageInfo().getVersionCode(), pi.versionCode));
694 }
695
696 getPackageInfo().updateVersionInfo(pi);
Makoto Onuki39686e82016-04-13 18:03:00 -0700697
698 boolean changed = false;
Makoto Onuki39686e82016-04-13 18:03:00 -0700699
Makoto Onuki22fcc682016-05-17 14:52:19 -0700700 // For existing shortcuts, update timestamps if they have any resources.
Makoto Onukib08790c2016-06-23 14:05:46 -0700701 // Also check if shortcuts' activities are still main activities. Otherwise, disable them.
Makoto Onuki22fcc682016-05-17 14:52:19 -0700702 if (!isNewApp) {
Makoto Onuki157b1622016-06-02 16:13:10 -0700703 Resources publisherRes = null;
704
Makoto Onuki22fcc682016-05-17 14:52:19 -0700705 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
706 final ShortcutInfo si = mShortcuts.valueAt(i);
707
Makoto Onukib08790c2016-06-23 14:05:46 -0700708 if (si.isDynamic()) {
709 if (!s.injectIsMainActivity(si.getActivity(), getPackageUserId())) {
710 Slog.w(TAG, String.format(
711 "%s is no longer main activity. Disabling shorcut %s.",
712 getPackageName(), si.getId()));
713 if (disableDynamicWithId(si.getId())) {
714 continue; // Actually removed.
715 }
716 // Still pinned, so fall-through and possibly update the resources.
717 }
718 changed = true;
719 }
720
Makoto Onuki22fcc682016-05-17 14:52:19 -0700721 if (si.hasAnyResources()) {
Makoto Onuki157b1622016-06-02 16:13:10 -0700722 if (!si.isOriginallyFromManifest()) {
723 if (publisherRes == null) {
724 publisherRes = getPackageResources();
725 if (publisherRes == null) {
726 break; // Resources couldn't be loaded.
727 }
728 }
729
730 // If this shortcut is not from a manifest, then update all resource IDs
731 // from resource names. (We don't allow resource strings for
732 // non-manifest at the moment, but icons can still be resources.)
733 si.lookupAndFillInResourceIds(publisherRes);
734 }
Makoto Onuki22fcc682016-05-17 14:52:19 -0700735 changed = true;
736 si.setTimestamp(s.injectCurrentTimeMillis());
737 }
Makoto Onuki39686e82016-04-13 18:03:00 -0700738 }
739 }
Makoto Onuki22fcc682016-05-17 14:52:19 -0700740
741 // (Re-)publish manifest shortcut.
742 changed |= publishManifestShortcuts(newManifestShortcutList);
743
Makoto Onuki7001a612016-05-27 13:24:28 -0700744 if (newManifestShortcutList != null) {
745 changed |= pushOutExcessShortcuts();
746 }
747
Makoto Onukidf6da042016-06-16 09:51:40 -0700748 s.verifyStates();
749
Makoto Onuki39686e82016-04-13 18:03:00 -0700750 if (changed) {
751 // This will send a notification to the launcher, and also save .
752 s.packageShortcutsChanged(getPackageName(), getPackageUserId());
753 } else {
754 // Still save the version code.
755 s.scheduleSaveUser(getPackageUserId());
756 }
Makoto Onuki22fcc682016-05-17 14:52:19 -0700757 return changed;
758 }
759
760 private boolean publishManifestShortcuts(List<ShortcutInfo> newManifestShortcutList) {
761 if (ShortcutService.DEBUG) {
762 Slog.d(TAG, String.format(
763 "Package %s: publishing manifest shortcuts", getPackageName()));
764 }
765 boolean changed = false;
766
Makoto Onuki22fcc682016-05-17 14:52:19 -0700767 // Keep the previous IDs.
768 ArraySet<String> toDisableList = null;
769 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
770 final ShortcutInfo si = mShortcuts.valueAt(i);
771
772 if (si.isManifestShortcut()) {
773 if (toDisableList == null) {
774 toDisableList = new ArraySet<>();
775 }
776 toDisableList.add(si.getId());
777 }
778 }
779
780 // Publish new ones.
781 if (newManifestShortcutList != null) {
782 final int newListSize = newManifestShortcutList.size();
783
784 for (int i = 0; i < newListSize; i++) {
785 changed = true;
786
787 final ShortcutInfo newShortcut = newManifestShortcutList.get(i);
788 final boolean newDisabled = !newShortcut.isEnabled();
789
Makoto Onuki7001a612016-05-27 13:24:28 -0700790 final String id = newShortcut.getId();
Makoto Onuki22fcc682016-05-17 14:52:19 -0700791 final ShortcutInfo oldShortcut = mShortcuts.get(id);
792
793 boolean wasPinned = false;
794
795 if (oldShortcut != null) {
796 if (!oldShortcut.isOriginallyFromManifest()) {
797 Slog.e(TAG, "Shortcut with ID=" + newShortcut.getId()
798 + " exists but is not from AndroidManifest.xml, not updating.");
799 continue;
800 }
801 // Take over the pinned flag.
802 if (oldShortcut.isPinned()) {
803 wasPinned = true;
804 newShortcut.addFlags(ShortcutInfo.FLAG_PINNED);
805 }
806 }
807 if (newDisabled && !wasPinned) {
808 // If the shortcut is disabled, and it was *not* pinned, then this
809 // just doesn't have to be published.
810 // Just keep it in toDisableList, so the previous one would be removed.
811 continue;
812 }
Makoto Onuki22fcc682016-05-17 14:52:19 -0700813
814 // Note even if enabled=false, we still need to update all fields, so do it
815 // regardless.
816 addShortcutInner(newShortcut); // This will clean up the old one too.
817
818 if (!newDisabled && toDisableList != null) {
819 // Still alive, don't remove.
820 toDisableList.remove(id);
821 }
822 }
823 }
824
825 // Disable the previous manifest shortcuts that are no longer in the manifest.
826 if (toDisableList != null) {
827 if (ShortcutService.DEBUG) {
828 Slog.d(TAG, String.format(
829 "Package %s: disabling %d stale shortcuts", getPackageName(),
830 toDisableList.size()));
831 }
832 for (int i = toDisableList.size() - 1; i >= 0; i--) {
833 changed = true;
834
835 final String id = toDisableList.valueAt(i);
836
837 disableWithId(id, /* disable message =*/ null, /* disable message resid */ 0,
838 /* overrideImmutable=*/ true);
839 }
840 removeOrphans();
841 }
Makoto Onukidf6da042016-06-16 09:51:40 -0700842 adjustRanks();
Makoto Onuki22fcc682016-05-17 14:52:19 -0700843 return changed;
Makoto Onuki39686e82016-04-13 18:03:00 -0700844 }
845
Makoto Onuki7001a612016-05-27 13:24:28 -0700846 /**
847 * For each target activity, make sure # of dynamic + manifest shortcuts <= max.
848 * If too many, we'll remove the dynamic with the lowest ranks.
849 */
850 private boolean pushOutExcessShortcuts() {
851 final ShortcutService service = mShortcutUser.mService;
852 final int maxShortcuts = service.getMaxActivityShortcuts();
853
854 boolean changed = false;
855
856 final ArrayMap<ComponentName, ArrayList<ShortcutInfo>> all =
857 sortShortcutsToActivities();
858 for (int outer = all.size() - 1; outer >= 0; outer--) {
859 final ArrayList<ShortcutInfo> list = all.valueAt(outer);
860 if (list.size() <= maxShortcuts) {
861 continue;
862 }
863 // Sort by isManifestShortcut() and getRank().
864 Collections.sort(list, mShortcutTypeAndRankComparator);
865
866 // Keep [0 .. max), and remove (as dynamic) [max .. size)
867 for (int inner = list.size() - 1; inner >= maxShortcuts; inner--) {
868 final ShortcutInfo shortcut = list.get(inner);
869
870 if (shortcut.isManifestShortcut()) {
871 // This shouldn't happen -- excess shortcuts should all be non-manifest.
872 // But just in case.
873 service.wtf("Found manifest shortcuts in excess list.");
874 continue;
875 }
876 deleteDynamicWithId(shortcut.getId());
877 }
878 }
Makoto Onuki7001a612016-05-27 13:24:28 -0700879
880 return changed;
881 }
882
883 /**
884 * To sort by isManifestShortcut() and getRank(). i.e. manifest shortcuts come before
885 * non-manifest shortcuts, then sort by rank.
886 *
887 * This is used to decide which dynamic shortcuts to remove when an upgraded version has more
888 * manifest shortcuts than before and as a result we need to remove some of the dynamic
889 * shortcuts. We sort manifest + dynamic shortcuts by this order, and remove the ones with
890 * the last ones.
891 *
892 * (Note the number of manifest shortcuts is always <= the max number, because if there are
893 * more, ShortcutParser would ignore the rest.)
894 */
895 final Comparator<ShortcutInfo> mShortcutTypeAndRankComparator = (ShortcutInfo a,
896 ShortcutInfo b) -> {
897 if (a.isManifestShortcut() && !b.isManifestShortcut()) {
898 return -1;
899 }
900 if (!a.isManifestShortcut() && b.isManifestShortcut()) {
901 return 1;
902 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700903 return Integer.compare(a.getRank(), b.getRank());
Makoto Onuki7001a612016-05-27 13:24:28 -0700904 };
905
906 /**
907 * Build a list of shortcuts for each target activity and return as a map. The result won't
908 * contain "floating" shortcuts because they don't belong on any activities.
909 */
910 private ArrayMap<ComponentName, ArrayList<ShortcutInfo>> sortShortcutsToActivities() {
Makoto Onuki7001a612016-05-27 13:24:28 -0700911 final ArrayMap<ComponentName, ArrayList<ShortcutInfo>> activitiesToShortcuts
912 = new ArrayMap<>();
913 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
914 final ShortcutInfo si = mShortcuts.valueAt(i);
915 if (si.isFloating()) {
916 continue; // Ignore floating shortcuts, which are not tied to any activities.
917 }
918
919 final ComponentName activity = si.getActivity();
920
921 ArrayList<ShortcutInfo> list = activitiesToShortcuts.get(activity);
922 if (list == null) {
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700923 list = new ArrayList<>();
Makoto Onuki7001a612016-05-27 13:24:28 -0700924 activitiesToShortcuts.put(activity, list);
925 }
926 list.add(si);
927 }
928 return activitiesToShortcuts;
929 }
930
931 /** Used by {@link #enforceShortcutCountsBeforeOperation} */
932 private void incrementCountForActivity(ArrayMap<ComponentName, Integer> counts,
933 ComponentName cn, int increment) {
934 Integer oldValue = counts.get(cn);
935 if (oldValue == null) {
936 oldValue = 0;
937 }
938
939 counts.put(cn, oldValue + increment);
940 }
941
942 /**
943 * Called by
944 * {@link android.content.pm.ShortcutManager#setDynamicShortcuts},
945 * {@link android.content.pm.ShortcutManager#addDynamicShortcuts}, and
946 * {@link android.content.pm.ShortcutManager#updateShortcuts} before actually performing
947 * the operation to make sure the operation wouldn't result in the target activities having
948 * more than the allowed number of dynamic/manifest shortcuts.
949 *
950 * @param newList shortcut list passed to set, add or updateShortcuts().
951 * @param operation add, set or update.
952 * @throws IllegalArgumentException if the operation would result in going over the max
953 * shortcut count for any activity.
954 */
955 public void enforceShortcutCountsBeforeOperation(List<ShortcutInfo> newList,
956 @ShortcutOperation int operation) {
957 final ShortcutService service = mShortcutUser.mService;
958
959 // Current # of dynamic / manifest shortcuts for each activity.
960 // (If it's for update, then don't count dynamic shortcuts, since they'll be replaced
961 // anyway.)
962 final ArrayMap<ComponentName, Integer> counts = new ArrayMap<>(4);
963 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
964 final ShortcutInfo shortcut = mShortcuts.valueAt(i);
965
966 if (shortcut.isManifestShortcut()) {
967 incrementCountForActivity(counts, shortcut.getActivity(), 1);
968 } else if (shortcut.isDynamic() && (operation != ShortcutService.OPERATION_SET)) {
969 incrementCountForActivity(counts, shortcut.getActivity(), 1);
970 }
971 }
972
973 for (int i = newList.size() - 1; i >= 0; i--) {
974 final ShortcutInfo newShortcut = newList.get(i);
975 final ComponentName newActivity = newShortcut.getActivity();
976 if (newActivity == null) {
977 if (operation != ShortcutService.OPERATION_UPDATE) {
Makoto Onukib08790c2016-06-23 14:05:46 -0700978 service.wtf("Activity must not be null at this point");
979 continue; // Just ignore this invalid case.
Makoto Onuki7001a612016-05-27 13:24:28 -0700980 }
981 continue; // Activity can be null for update.
982 }
983
984 final ShortcutInfo original = mShortcuts.get(newShortcut.getId());
985 if (original == null) {
986 if (operation == ShortcutService.OPERATION_UPDATE) {
987 continue; // When updating, ignore if there's no target.
988 }
989 // Add() or set(), and there's no existing shortcut with the same ID. We're
990 // simply publishing (as opposed to updating) this shortcut, so just +1.
991 incrementCountForActivity(counts, newActivity, 1);
992 continue;
993 }
994 if (original.isFloating() && (operation == ShortcutService.OPERATION_UPDATE)) {
995 // Updating floating shortcuts doesn't affect the count, so ignore.
996 continue;
997 }
998
999 // If it's add() or update(), then need to decrement for the previous activity.
1000 // Skip it for set() since it's already been taken care of by not counting the original
1001 // dynamic shortcuts in the first loop.
1002 if (operation != ShortcutService.OPERATION_SET) {
1003 final ComponentName oldActivity = original.getActivity();
1004 if (!original.isFloating()) {
1005 incrementCountForActivity(counts, oldActivity, -1);
1006 }
1007 }
1008 incrementCountForActivity(counts, newActivity, 1);
1009 }
1010
1011 // Then make sure none of the activities have more than the max number of shortcuts.
1012 for (int i = counts.size() - 1; i >= 0; i--) {
1013 service.enforceMaxActivityShortcuts(counts.valueAt(i));
1014 }
1015 }
1016
Makoto Onuki157b1622016-06-02 16:13:10 -07001017 /**
1018 * For all the text fields, refresh the string values if they're from resources.
1019 */
1020 public void resolveResourceStrings() {
1021 final ShortcutService s = mShortcutUser.mService;
1022 boolean changed = false;
1023
1024 Resources publisherRes = null;
1025 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1026 final ShortcutInfo si = mShortcuts.valueAt(i);
1027
1028 if (si.hasStringResources()) {
1029 changed = true;
1030
1031 if (publisherRes == null) {
1032 publisherRes = getPackageResources();
1033 if (publisherRes == null) {
1034 break; // Resources couldn't be loaded.
1035 }
1036 }
1037
1038 si.resolveResourceStrings(publisherRes);
1039 si.setTimestamp(s.injectCurrentTimeMillis());
1040 }
1041 }
1042 if (changed) {
Makoto Onuki4e6cef42016-07-13 16:14:01 -07001043 s.packageShortcutsChanged(getPackageName(), getPackageUserId());
Makoto Onuki157b1622016-06-02 16:13:10 -07001044 }
1045 }
1046
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001047 /** Clears the implicit ranks for all shortcuts. */
1048 public void clearAllImplicitRanks() {
1049 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1050 final ShortcutInfo si = mShortcuts.valueAt(i);
1051 si.clearImplicitRankAndRankChangedFlag();
1052 }
1053 }
1054
1055 /**
1056 * Used to sort shortcuts for rank auto-adjusting.
1057 */
1058 final Comparator<ShortcutInfo> mShortcutRankComparator = (ShortcutInfo a, ShortcutInfo b) -> {
1059 // First, sort by rank.
1060 int ret = Integer.compare(a.getRank(), b.getRank());
1061 if (ret != 0) {
1062 return ret;
1063 }
1064 // When ranks are tie, then prioritize the ones that have just been assigned new ranks.
1065 // e.g. when there are 3 shortcuts, "s1" "s2" and "s3" with rank 0, 1, 2 respectively,
1066 // adding a shortcut "s4" with rank 1 will "insert" it between "s1" and "s2", because
1067 // "s2" and "s4" have the same rank 1 but s4 has isRankChanged() set.
1068 // Similarly, updating s3's rank to 1 will insert it between s1 and s2.
1069 if (a.isRankChanged() != b.isRankChanged()) {
1070 return a.isRankChanged() ? -1 : 1;
1071 }
1072 // If they're still tie, sort by implicit rank -- i.e. preserve the order in which
1073 // they're passed to the API.
1074 ret = Integer.compare(a.getImplicitRank(), b.getImplicitRank());
1075 if (ret != 0) {
1076 return ret;
1077 }
1078 // If they're stil tie, just sort by their IDs.
1079 // This may happen with updateShortcuts() -- see
1080 // the testUpdateShortcuts_noManifestShortcuts() test.
1081 return a.getId().compareTo(b.getId());
1082 };
1083
1084 /**
1085 * Re-calculate the ranks for all shortcuts.
1086 */
1087 public void adjustRanks() {
1088 final ShortcutService s = mShortcutUser.mService;
1089 final long now = s.injectCurrentTimeMillis();
1090
1091 // First, clear ranks for floating shortcuts.
1092 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1093 final ShortcutInfo si = mShortcuts.valueAt(i);
1094 if (si.isFloating()) {
1095 if (si.getRank() != 0) {
1096 si.setTimestamp(now);
1097 si.setRank(0);
1098 }
1099 }
1100 }
1101
1102 // Then adjust ranks. Ranks are unique for each activity, so we first need to sort
1103 // shortcuts to each activity.
1104 // Then sort the shortcuts within each activity with mShortcutRankComparator, and
1105 // assign ranks from 0.
1106 final ArrayMap<ComponentName, ArrayList<ShortcutInfo>> all =
1107 sortShortcutsToActivities();
1108 for (int outer = all.size() - 1; outer >= 0; outer--) { // For each activity.
1109 final ArrayList<ShortcutInfo> list = all.valueAt(outer);
1110
1111 // Sort by ranks and other signals.
1112 Collections.sort(list, mShortcutRankComparator);
1113
1114 int rank = 0;
1115
1116 final int size = list.size();
1117 for (int i = 0; i < size; i++) {
1118 final ShortcutInfo si = list.get(i);
1119 if (si.isManifestShortcut()) {
1120 // Don't adjust ranks for manifest shortcuts.
1121 continue;
1122 }
1123 // At this point, it must be dynamic.
1124 if (!si.isDynamic()) {
1125 s.wtf("Non-dynamic shortcut found.");
1126 continue;
1127 }
1128 final int thisRank = rank++;
1129 if (si.getRank() != thisRank) {
1130 si.setTimestamp(now);
1131 si.setRank(thisRank);
1132 }
1133 }
1134 }
1135 }
1136
Makoto Onukic51b2872016-05-04 15:24:50 -07001137 public void dump(@NonNull PrintWriter pw, @NonNull String prefix) {
Makoto Onuki31459242016-03-22 11:12:18 -07001138 pw.println();
1139
1140 pw.print(prefix);
1141 pw.print("Package: ");
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001142 pw.print(getPackageName());
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001143 pw.print(" UID: ");
1144 pw.print(mPackageUid);
Makoto Onuki31459242016-03-22 11:12:18 -07001145 pw.println();
1146
1147 pw.print(prefix);
1148 pw.print(" ");
1149 pw.print("Calls: ");
Makoto Onukic51b2872016-05-04 15:24:50 -07001150 pw.print(getApiCallCount());
Makoto Onuki31459242016-03-22 11:12:18 -07001151 pw.println();
1152
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001153 // getApiCallCount() may have updated mLastKnownForegroundElapsedTime.
1154 pw.print(prefix);
1155 pw.print(" ");
1156 pw.print("Last known FG: ");
1157 pw.print(mLastKnownForegroundElapsedTime);
1158 pw.println();
1159
Makoto Onuki31459242016-03-22 11:12:18 -07001160 // This should be after getApiCallCount(), which may update it.
1161 pw.print(prefix);
1162 pw.print(" ");
1163 pw.print("Last reset: [");
1164 pw.print(mLastResetTime);
1165 pw.print("] ");
Makoto Onukic51b2872016-05-04 15:24:50 -07001166 pw.print(ShortcutService.formatTime(mLastResetTime));
Makoto Onuki31459242016-03-22 11:12:18 -07001167 pw.println();
1168
Makoto Onukic51b2872016-05-04 15:24:50 -07001169 getPackageInfo().dump(pw, prefix + " ");
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001170 pw.println();
1171
Makoto Onuki39686e82016-04-13 18:03:00 -07001172 pw.print(prefix);
1173 pw.println(" Shortcuts:");
Makoto Onuki31459242016-03-22 11:12:18 -07001174 long totalBitmapSize = 0;
1175 final ArrayMap<String, ShortcutInfo> shortcuts = mShortcuts;
1176 final int size = shortcuts.size();
1177 for (int i = 0; i < size; i++) {
1178 final ShortcutInfo si = shortcuts.valueAt(i);
Makoto Onuki39686e82016-04-13 18:03:00 -07001179 pw.print(prefix);
1180 pw.print(" ");
Makoto Onuki31459242016-03-22 11:12:18 -07001181 pw.println(si.toInsecureString());
1182 if (si.getBitmapPath() != null) {
1183 final long len = new File(si.getBitmapPath()).length();
Makoto Onuki39686e82016-04-13 18:03:00 -07001184 pw.print(prefix);
1185 pw.print(" ");
Makoto Onuki31459242016-03-22 11:12:18 -07001186 pw.print("bitmap size=");
1187 pw.println(len);
1188
1189 totalBitmapSize += len;
1190 }
1191 }
1192 pw.print(prefix);
1193 pw.print(" ");
1194 pw.print("Total bitmap size: ");
1195 pw.print(totalBitmapSize);
1196 pw.print(" (");
Makoto Onukic51b2872016-05-04 15:24:50 -07001197 pw.print(Formatter.formatFileSize(mShortcutUser.mService.mContext, totalBitmapSize));
Makoto Onuki31459242016-03-22 11:12:18 -07001198 pw.println(")");
1199 }
1200
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001201 @Override
Makoto Onuki0acbb142016-03-22 17:02:57 -07001202 public void saveToXml(@NonNull XmlSerializer out, boolean forBackup)
1203 throws IOException, XmlPullParserException {
Makoto Onuki31459242016-03-22 11:12:18 -07001204 final int size = mShortcuts.size();
1205
1206 if (size == 0 && mApiCallCount == 0) {
1207 return; // nothing to write.
1208 }
1209
1210 out.startTag(null, TAG_ROOT);
1211
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001212 ShortcutService.writeAttr(out, ATTR_NAME, getPackageName());
Makoto Onuki31459242016-03-22 11:12:18 -07001213 ShortcutService.writeAttr(out, ATTR_CALL_COUNT, mApiCallCount);
1214 ShortcutService.writeAttr(out, ATTR_LAST_RESET, mLastResetTime);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001215 getPackageInfo().saveToXml(out);
Makoto Onuki31459242016-03-22 11:12:18 -07001216
1217 for (int j = 0; j < size; j++) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07001218 saveShortcut(out, mShortcuts.valueAt(j), forBackup);
Makoto Onuki31459242016-03-22 11:12:18 -07001219 }
1220
1221 out.endTag(null, TAG_ROOT);
1222 }
1223
Makoto Onuki0acbb142016-03-22 17:02:57 -07001224 private static void saveShortcut(XmlSerializer out, ShortcutInfo si, boolean forBackup)
Makoto Onuki31459242016-03-22 11:12:18 -07001225 throws IOException, XmlPullParserException {
Makoto Onuki0acbb142016-03-22 17:02:57 -07001226 if (forBackup) {
Makoto Onukif3ba2e02016-07-12 09:18:50 -07001227 if (!(si.isPinned() && si.isEnabled())) {
1228 return; // We only backup pinned shortcuts that are enabled.
Makoto Onuki0acbb142016-03-22 17:02:57 -07001229 }
1230 }
Makoto Onuki31459242016-03-22 11:12:18 -07001231 out.startTag(null, TAG_SHORTCUT);
1232 ShortcutService.writeAttr(out, ATTR_ID, si.getId());
1233 // writeAttr(out, "package", si.getPackageName()); // not needed
Makoto Onuki22fcc682016-05-17 14:52:19 -07001234 ShortcutService.writeAttr(out, ATTR_ACTIVITY, si.getActivity());
Makoto Onuki31459242016-03-22 11:12:18 -07001235 // writeAttr(out, "icon", si.getIcon()); // We don't save it.
1236 ShortcutService.writeAttr(out, ATTR_TITLE, si.getTitle());
Makoto Onuki20c95f82016-05-11 16:51:01 -07001237 ShortcutService.writeAttr(out, ATTR_TITLE_RES_ID, si.getTitleResId());
Makoto Onuki157b1622016-06-02 16:13:10 -07001238 ShortcutService.writeAttr(out, ATTR_TITLE_RES_NAME, si.getTitleResName());
Makoto Onukie3ae7ec2016-03-29 15:45:25 -07001239 ShortcutService.writeAttr(out, ATTR_TEXT, si.getText());
Makoto Onuki20c95f82016-05-11 16:51:01 -07001240 ShortcutService.writeAttr(out, ATTR_TEXT_RES_ID, si.getTextResId());
Makoto Onuki157b1622016-06-02 16:13:10 -07001241 ShortcutService.writeAttr(out, ATTR_TEXT_RES_NAME, si.getTextResName());
Makoto Onuki20c95f82016-05-11 16:51:01 -07001242 ShortcutService.writeAttr(out, ATTR_DISABLED_MESSAGE, si.getDisabledMessage());
Makoto Onukieddbfec2016-05-31 17:04:34 -07001243 ShortcutService.writeAttr(out, ATTR_DISABLED_MESSAGE_RES_ID,
1244 si.getDisabledMessageResourceId());
Makoto Onuki157b1622016-06-02 16:13:10 -07001245 ShortcutService.writeAttr(out, ATTR_DISABLED_MESSAGE_RES_NAME,
1246 si.getDisabledMessageResName());
Makoto Onuki31459242016-03-22 11:12:18 -07001247 ShortcutService.writeAttr(out, ATTR_INTENT, si.getIntentNoExtras());
Makoto Onuki31459242016-03-22 11:12:18 -07001248 ShortcutService.writeAttr(out, ATTR_TIMESTAMP,
1249 si.getLastChangedTimestamp());
Makoto Onuki0acbb142016-03-22 17:02:57 -07001250 if (forBackup) {
1251 // Don't write icon information. Also drop the dynamic flag.
1252 ShortcutService.writeAttr(out, ATTR_FLAGS,
1253 si.getFlags() &
1254 ~(ShortcutInfo.FLAG_HAS_ICON_FILE | ShortcutInfo.FLAG_HAS_ICON_RES
1255 | ShortcutInfo.FLAG_DYNAMIC));
1256 } else {
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001257 // When writing for backup, ranks shouldn't be saved, since shortcuts won't be restored
1258 // as dynamic.
1259 ShortcutService.writeAttr(out, ATTR_RANK, si.getRank());
1260
Makoto Onuki0acbb142016-03-22 17:02:57 -07001261 ShortcutService.writeAttr(out, ATTR_FLAGS, si.getFlags());
Makoto Onuki157b1622016-06-02 16:13:10 -07001262 ShortcutService.writeAttr(out, ATTR_ICON_RES_ID, si.getIconResourceId());
1263 ShortcutService.writeAttr(out, ATTR_ICON_RES_NAME, si.getIconResName());
Makoto Onuki0acbb142016-03-22 17:02:57 -07001264 ShortcutService.writeAttr(out, ATTR_BITMAP_PATH, si.getBitmapPath());
1265 }
Makoto Onuki31459242016-03-22 11:12:18 -07001266
Makoto Onukib6d35232016-04-04 15:57:17 -07001267 {
Makoto Onukibe73a802016-04-15 14:46:35 -07001268 final Set<String> cat = si.getCategories();
Makoto Onukib6d35232016-04-04 15:57:17 -07001269 if (cat != null && cat.size() > 0) {
1270 out.startTag(null, TAG_CATEGORIES);
1271 XmlUtils.writeStringArrayXml(cat.toArray(new String[cat.size()]),
1272 NAME_CATEGORIES, out);
1273 out.endTag(null, TAG_CATEGORIES);
1274 }
1275 }
1276
Makoto Onuki31459242016-03-22 11:12:18 -07001277 ShortcutService.writeTagExtra(out, TAG_INTENT_EXTRAS,
1278 si.getIntentPersistableExtras());
1279 ShortcutService.writeTagExtra(out, TAG_EXTRAS, si.getExtras());
1280
1281 out.endTag(null, TAG_SHORTCUT);
1282 }
1283
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001284 public static ShortcutPackage loadFromXml(ShortcutService s, ShortcutUser shortcutUser,
1285 XmlPullParser parser, boolean fromBackup)
Makoto Onuki31459242016-03-22 11:12:18 -07001286 throws IOException, XmlPullParserException {
1287
1288 final String packageName = ShortcutService.parseStringAttribute(parser,
1289 ATTR_NAME);
1290
Makoto Onukic51b2872016-05-04 15:24:50 -07001291 final ShortcutPackage ret = new ShortcutPackage(shortcutUser,
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001292 shortcutUser.getUserId(), packageName);
Makoto Onuki31459242016-03-22 11:12:18 -07001293
Makoto Onuki31459242016-03-22 11:12:18 -07001294 ret.mApiCallCount =
1295 ShortcutService.parseIntAttribute(parser, ATTR_CALL_COUNT);
1296 ret.mLastResetTime =
1297 ShortcutService.parseLongAttribute(parser, ATTR_LAST_RESET);
1298
1299 final int outerDepth = parser.getDepth();
1300 int type;
1301 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1302 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1303 if (type != XmlPullParser.START_TAG) {
1304 continue;
1305 }
1306 final int depth = parser.getDepth();
1307 final String tag = parser.getName();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001308 if (depth == outerDepth + 1) {
1309 switch (tag) {
1310 case ShortcutPackageInfo.TAG_ROOT:
Makoto Onuki2e210c42016-03-30 08:30:36 -07001311 ret.getPackageInfo().loadFromXml(parser, fromBackup);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001312 continue;
1313 case TAG_SHORTCUT:
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001314 final ShortcutInfo si = parseShortcut(parser, packageName,
1315 shortcutUser.getUserId());
Makoto Onuki31459242016-03-22 11:12:18 -07001316
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001317 // Don't use addShortcut(), we don't need to save the icon.
1318 ret.mShortcuts.put(si.getId(), si);
1319 continue;
1320 }
Makoto Onuki31459242016-03-22 11:12:18 -07001321 }
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001322 ShortcutService.warnForInvalidTag(depth, tag);
1323 }
Makoto Onuki31459242016-03-22 11:12:18 -07001324 return ret;
1325 }
1326
Makoto Onukiabe84422016-04-07 09:41:19 -07001327 private static ShortcutInfo parseShortcut(XmlPullParser parser, String packageName,
1328 @UserIdInt int userId) throws IOException, XmlPullParserException {
Makoto Onuki31459242016-03-22 11:12:18 -07001329 String id;
1330 ComponentName activityComponent;
1331 // Icon icon;
1332 String title;
Makoto Onuki20c95f82016-05-11 16:51:01 -07001333 int titleResId;
Makoto Onuki157b1622016-06-02 16:13:10 -07001334 String titleResName;
Makoto Onukie3ae7ec2016-03-29 15:45:25 -07001335 String text;
Makoto Onuki20c95f82016-05-11 16:51:01 -07001336 int textResId;
Makoto Onuki157b1622016-06-02 16:13:10 -07001337 String textResName;
Makoto Onuki20c95f82016-05-11 16:51:01 -07001338 String disabledMessage;
1339 int disabledMessageResId;
Makoto Onuki157b1622016-06-02 16:13:10 -07001340 String disabledMessageResName;
Makoto Onuki31459242016-03-22 11:12:18 -07001341 Intent intent;
1342 PersistableBundle intentPersistableExtras = null;
Makoto Onuki20c95f82016-05-11 16:51:01 -07001343 int rank;
Makoto Onuki31459242016-03-22 11:12:18 -07001344 PersistableBundle extras = null;
1345 long lastChangedTimestamp;
1346 int flags;
Makoto Onuki157b1622016-06-02 16:13:10 -07001347 int iconResId;
1348 String iconResName;
Makoto Onuki31459242016-03-22 11:12:18 -07001349 String bitmapPath;
Makoto Onukibe73a802016-04-15 14:46:35 -07001350 ArraySet<String> categories = null;
Makoto Onuki31459242016-03-22 11:12:18 -07001351
1352 id = ShortcutService.parseStringAttribute(parser, ATTR_ID);
1353 activityComponent = ShortcutService.parseComponentNameAttribute(parser,
1354 ATTR_ACTIVITY);
1355 title = ShortcutService.parseStringAttribute(parser, ATTR_TITLE);
Makoto Onuki20c95f82016-05-11 16:51:01 -07001356 titleResId = ShortcutService.parseIntAttribute(parser, ATTR_TITLE_RES_ID);
Makoto Onuki157b1622016-06-02 16:13:10 -07001357 titleResName = ShortcutService.parseStringAttribute(parser, ATTR_TITLE_RES_NAME);
Makoto Onukie3ae7ec2016-03-29 15:45:25 -07001358 text = ShortcutService.parseStringAttribute(parser, ATTR_TEXT);
Makoto Onuki20c95f82016-05-11 16:51:01 -07001359 textResId = ShortcutService.parseIntAttribute(parser, ATTR_TEXT_RES_ID);
Makoto Onuki157b1622016-06-02 16:13:10 -07001360 textResName = ShortcutService.parseStringAttribute(parser, ATTR_TEXT_RES_NAME);
Makoto Onuki20c95f82016-05-11 16:51:01 -07001361 disabledMessage = ShortcutService.parseStringAttribute(parser, ATTR_DISABLED_MESSAGE);
1362 disabledMessageResId = ShortcutService.parseIntAttribute(parser,
1363 ATTR_DISABLED_MESSAGE_RES_ID);
Makoto Onuki157b1622016-06-02 16:13:10 -07001364 disabledMessageResName = ShortcutService.parseStringAttribute(parser,
1365 ATTR_DISABLED_MESSAGE_RES_NAME);
Makoto Onuki31459242016-03-22 11:12:18 -07001366 intent = ShortcutService.parseIntentAttribute(parser, ATTR_INTENT);
Makoto Onuki20c95f82016-05-11 16:51:01 -07001367 rank = (int) ShortcutService.parseLongAttribute(parser, ATTR_RANK);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001368 lastChangedTimestamp = ShortcutService.parseLongAttribute(parser, ATTR_TIMESTAMP);
Makoto Onuki31459242016-03-22 11:12:18 -07001369 flags = (int) ShortcutService.parseLongAttribute(parser, ATTR_FLAGS);
Makoto Onuki157b1622016-06-02 16:13:10 -07001370 iconResId = (int) ShortcutService.parseLongAttribute(parser, ATTR_ICON_RES_ID);
1371 iconResName = ShortcutService.parseStringAttribute(parser, ATTR_ICON_RES_NAME);
Makoto Onuki31459242016-03-22 11:12:18 -07001372 bitmapPath = ShortcutService.parseStringAttribute(parser, ATTR_BITMAP_PATH);
1373
1374 final int outerDepth = parser.getDepth();
1375 int type;
1376 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1377 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1378 if (type != XmlPullParser.START_TAG) {
1379 continue;
1380 }
1381 final int depth = parser.getDepth();
1382 final String tag = parser.getName();
1383 if (ShortcutService.DEBUG_LOAD) {
1384 Slog.d(TAG, String.format(" depth=%d type=%d name=%s",
1385 depth, type, tag));
1386 }
1387 switch (tag) {
1388 case TAG_INTENT_EXTRAS:
1389 intentPersistableExtras = PersistableBundle.restoreFromXml(parser);
1390 continue;
1391 case TAG_EXTRAS:
1392 extras = PersistableBundle.restoreFromXml(parser);
1393 continue;
Makoto Onukib6d35232016-04-04 15:57:17 -07001394 case TAG_CATEGORIES:
1395 // This just contains string-array.
1396 continue;
1397 case TAG_STRING_ARRAY_XMLUTILS:
1398 if (NAME_CATEGORIES.equals(ShortcutService.parseStringAttribute(parser,
1399 ATTR_NAME_XMLUTILS))) {
Makoto Onukibe73a802016-04-15 14:46:35 -07001400 final String[] ar = XmlUtils.readThisStringArrayXml(
1401 parser, TAG_STRING_ARRAY_XMLUTILS, null);
1402 categories = new ArraySet<>(ar.length);
1403 for (int i = 0; i < ar.length; i++) {
1404 categories.add(ar[i]);
1405 }
Makoto Onukib6d35232016-04-04 15:57:17 -07001406 }
1407 continue;
Makoto Onuki31459242016-03-22 11:12:18 -07001408 }
1409 throw ShortcutService.throwForInvalidTag(depth, tag);
1410 }
Makoto Onukibe73a802016-04-15 14:46:35 -07001411
Makoto Onuki31459242016-03-22 11:12:18 -07001412 return new ShortcutInfo(
Makoto Onuki20c95f82016-05-11 16:51:01 -07001413 userId, id, packageName, activityComponent, /* icon =*/ null,
Makoto Onuki157b1622016-06-02 16:13:10 -07001414 title, titleResId, titleResName, text, textResId, textResName,
1415 disabledMessage, disabledMessageResId, disabledMessageResName,
Makoto Onukibe73a802016-04-15 14:46:35 -07001416 categories, intent,
Makoto Onuki20c95f82016-05-11 16:51:01 -07001417 intentPersistableExtras, rank, extras, lastChangedTimestamp, flags,
Makoto Onuki157b1622016-06-02 16:13:10 -07001418 iconResId, iconResName, bitmapPath);
Makoto Onuki31459242016-03-22 11:12:18 -07001419 }
Makoto Onuki2e210c42016-03-30 08:30:36 -07001420
1421 @VisibleForTesting
1422 List<ShortcutInfo> getAllShortcutsForTest() {
1423 return new ArrayList<>(mShortcuts.values());
1424 }
Makoto Onuki7001a612016-05-27 13:24:28 -07001425
1426 @Override
1427 public void verifyStates() {
1428 super.verifyStates();
1429
1430 boolean failed = false;
1431
1432 final ArrayMap<ComponentName, ArrayList<ShortcutInfo>> all =
1433 sortShortcutsToActivities();
1434
1435 // Make sure each activity won't have more than max shortcuts.
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001436 for (int outer = all.size() - 1; outer >= 0; outer--) {
1437 final ArrayList<ShortcutInfo> list = all.valueAt(outer);
1438 if (list.size() > mShortcutUser.mService.getMaxActivityShortcuts()) {
Makoto Onuki7001a612016-05-27 13:24:28 -07001439 failed = true;
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001440 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": activity " + all.keyAt(outer)
1441 + " has " + all.valueAt(outer).size() + " shortcuts.");
Makoto Onuki7001a612016-05-27 13:24:28 -07001442 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001443
1444 // Sort by rank.
1445 Collections.sort(list, (a, b) -> Integer.compare(a.getRank(), b.getRank()));
1446
1447 // Split into two arrays for each kind.
1448 final ArrayList<ShortcutInfo> dynamicList = new ArrayList<>(list);
1449 dynamicList.removeIf((si) -> !si.isDynamic());
1450
1451 final ArrayList<ShortcutInfo> manifestList = new ArrayList<>(list);
1452 dynamicList.removeIf((si) -> !si.isManifestShortcut());
1453
1454 verifyRanksSequential(dynamicList);
1455 verifyRanksSequential(manifestList);
Makoto Onuki7001a612016-05-27 13:24:28 -07001456 }
1457
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001458 // Verify each shortcut's status.
Makoto Onuki7001a612016-05-27 13:24:28 -07001459 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1460 final ShortcutInfo si = mShortcuts.valueAt(i);
Makoto Onukiff14f732016-06-30 17:07:25 -07001461 if (!(si.isDeclaredInManifest() || si.isDynamic() || si.isPinned())) {
Makoto Onuki7001a612016-05-27 13:24:28 -07001462 failed = true;
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001463 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
Makoto Onuki7001a612016-05-27 13:24:28 -07001464 + " is not manifest, dynamic or pinned.");
1465 }
Makoto Onukiff14f732016-06-30 17:07:25 -07001466 if (si.isDeclaredInManifest() && si.isDynamic()) {
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001467 failed = true;
1468 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1469 + " is both dynamic and manifest at the same time.");
1470 }
Makoto Onuki7001a612016-05-27 13:24:28 -07001471 if (si.getActivity() == null) {
1472 failed = true;
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001473 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
Makoto Onuki7001a612016-05-27 13:24:28 -07001474 + " has null activity.");
1475 }
1476 if ((si.isDynamic() || si.isManifestShortcut()) && !si.isEnabled()) {
1477 failed = true;
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001478 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
Makoto Onuki7001a612016-05-27 13:24:28 -07001479 + " is not floating, but is disabled.");
1480 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001481 if (si.isFloating() && si.getRank() != 0) {
1482 failed = true;
1483 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1484 + " is floating, but has rank=" + si.getRank());
1485 }
Makoto Onukidd097812016-06-29 13:10:09 -07001486 if (si.getIcon() != null) {
1487 failed = true;
1488 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1489 + " still has an icon");
1490 }
1491 if (si.hasIconFile() && si.hasIconResource()) {
1492 failed = true;
1493 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1494 + " has both resource and bitmap icons");
1495 }
Makoto Onuki7001a612016-05-27 13:24:28 -07001496 }
1497
1498 if (failed) {
1499 throw new IllegalStateException("See logcat for errors");
1500 }
1501 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001502
1503 private boolean verifyRanksSequential(List<ShortcutInfo> list) {
1504 boolean failed = false;
1505
1506 for (int i = 0; i < list.size(); i++) {
1507 final ShortcutInfo si = list.get(i);
1508 if (si.getRank() != i) {
1509 failed = true;
1510 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1511 + " rank=" + si.getRank() + " but expected to be "+ i);
1512 }
1513 }
1514 return failed;
1515 }
Makoto Onuki31459242016-03-22 11:12:18 -07001516}