blob: 21fe5ba6cfbac853bcfd5a20fc7e5222ea8b33fd [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;
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -080023import android.content.IntentFilter;
Makoto Onuki22fcc682016-05-17 14:52:19 -070024import android.content.pm.PackageInfo;
Makoto Onuki31459242016-03-22 11:12:18 -070025import android.content.pm.ShortcutInfo;
Makoto Onuki157b1622016-06-02 16:13:10 -070026import android.content.res.Resources;
Makoto Onuki31459242016-03-22 11:12:18 -070027import android.os.PersistableBundle;
28import android.text.format.Formatter;
29import android.util.ArrayMap;
30import android.util.ArraySet;
Makoto Onuki7001a612016-05-27 13:24:28 -070031import android.util.Log;
Makoto Onuki31459242016-03-22 11:12:18 -070032import android.util.Slog;
33
Makoto Onuki2e210c42016-03-30 08:30:36 -070034import com.android.internal.annotations.VisibleForTesting;
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -080035import com.android.internal.util.ArrayUtils;
Makoto Onuki22fcc682016-05-17 14:52:19 -070036import com.android.internal.util.Preconditions;
Makoto Onukib6d35232016-04-04 15:57:17 -070037import com.android.internal.util.XmlUtils;
Makoto Onuki7001a612016-05-27 13:24:28 -070038import com.android.server.pm.ShortcutService.ShortcutOperation;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070039import com.android.server.pm.ShortcutService.Stats;
Makoto Onuki2e210c42016-03-30 08:30:36 -070040
Makoto Onuki76269922016-07-15 14:58:54 -070041import org.json.JSONException;
42import org.json.JSONObject;
Makoto Onuki31459242016-03-22 11:12:18 -070043import org.xmlpull.v1.XmlPullParser;
44import org.xmlpull.v1.XmlPullParserException;
45import org.xmlpull.v1.XmlSerializer;
46
47import java.io.File;
48import java.io.IOException;
49import java.io.PrintWriter;
50import java.util.ArrayList;
Makoto Onuki7001a612016-05-27 13:24:28 -070051import java.util.Collections;
52import java.util.Comparator;
Makoto Onuki31459242016-03-22 11:12:18 -070053import java.util.List;
Makoto Onukibe73a802016-04-15 14:46:35 -070054import java.util.Set;
Makoto Onuki31459242016-03-22 11:12:18 -070055import java.util.function.Predicate;
56
57/**
58 * Package information used by {@link ShortcutService}.
Makoto Onuki22fcc682016-05-17 14:52:19 -070059 * User information used by {@link ShortcutService}.
60 *
61 * All methods should be guarded by {@code #mShortcutUser.mService.mLock}.
Makoto Onuki31459242016-03-22 11:12:18 -070062 */
Makoto Onuki9da23fc2016-03-29 11:14:42 -070063class ShortcutPackage extends ShortcutPackageItem {
Makoto Onuki31459242016-03-22 11:12:18 -070064 private static final String TAG = ShortcutService.TAG;
Makoto Onuki9e1f5592016-06-08 12:30:23 -070065 private static final String TAG_VERIFY = ShortcutService.TAG + ".verify";
Makoto Onuki31459242016-03-22 11:12:18 -070066
67 static final String TAG_ROOT = "package";
Makoto Onuki440a1ea2016-07-20 14:21:18 -070068 private static final String TAG_INTENT_EXTRAS_LEGACY = "intent-extras";
69 private static final String TAG_INTENT = "intent";
Makoto Onuki31459242016-03-22 11:12:18 -070070 private static final String TAG_EXTRAS = "extras";
71 private static final String TAG_SHORTCUT = "shortcut";
Makoto Onukib6d35232016-04-04 15:57:17 -070072 private static final String TAG_CATEGORIES = "categories";
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -080073 private static final String TAG_CHOOSER_EXTRAS = "chooser-extras";
74 private static final String TAG_CHOOSER_INTENT_FILTERS = "chooser-intent-filters";
75 private static final String TAG_CHOOSER_COMPONENT_NAMES = "chooser-component-names";
Makoto Onuki31459242016-03-22 11:12:18 -070076
77 private static final String ATTR_NAME = "name";
Makoto Onuki31459242016-03-22 11:12:18 -070078 private static final String ATTR_CALL_COUNT = "call-count";
79 private static final String ATTR_LAST_RESET = "last-reset";
80 private static final String ATTR_ID = "id";
81 private static final String ATTR_ACTIVITY = "activity";
82 private static final String ATTR_TITLE = "title";
Makoto Onuki20c95f82016-05-11 16:51:01 -070083 private static final String ATTR_TITLE_RES_ID = "titleid";
Makoto Onuki157b1622016-06-02 16:13:10 -070084 private static final String ATTR_TITLE_RES_NAME = "titlename";
Makoto Onukie3ae7ec2016-03-29 15:45:25 -070085 private static final String ATTR_TEXT = "text";
Makoto Onuki20c95f82016-05-11 16:51:01 -070086 private static final String ATTR_TEXT_RES_ID = "textid";
Makoto Onuki157b1622016-06-02 16:13:10 -070087 private static final String ATTR_TEXT_RES_NAME = "textname";
Makoto Onuki20c95f82016-05-11 16:51:01 -070088 private static final String ATTR_DISABLED_MESSAGE = "dmessage";
89 private static final String ATTR_DISABLED_MESSAGE_RES_ID = "dmessageid";
Makoto Onuki157b1622016-06-02 16:13:10 -070090 private static final String ATTR_DISABLED_MESSAGE_RES_NAME = "dmessagename";
Makoto Onuki440a1ea2016-07-20 14:21:18 -070091 private static final String ATTR_INTENT_LEGACY = "intent";
92 private static final String ATTR_INTENT_NO_EXTRA = "intent-base";
Makoto Onuki20c95f82016-05-11 16:51:01 -070093 private static final String ATTR_RANK = "rank";
Makoto Onuki31459242016-03-22 11:12:18 -070094 private static final String ATTR_TIMESTAMP = "timestamp";
95 private static final String ATTR_FLAGS = "flags";
Makoto Onuki157b1622016-06-02 16:13:10 -070096 private static final String ATTR_ICON_RES_ID = "icon-res";
97 private static final String ATTR_ICON_RES_NAME = "icon-resname";
Makoto Onuki31459242016-03-22 11:12:18 -070098 private static final String ATTR_BITMAP_PATH = "bitmap-path";
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -080099 private static final String ATTR_COMPONENT_NAMES = "component-names";
Makoto Onuki31459242016-03-22 11:12:18 -0700100
Makoto Onukib6d35232016-04-04 15:57:17 -0700101 private static final String NAME_CATEGORIES = "categories";
102
103 private static final String TAG_STRING_ARRAY_XMLUTILS = "string-array";
104 private static final String ATTR_NAME_XMLUTILS = "name";
105
Makoto Onuki76269922016-07-15 14:58:54 -0700106 private static final String KEY_DYNAMIC = "dynamic";
107 private static final String KEY_MANIFEST = "manifest";
108 private static final String KEY_PINNED = "pinned";
109 private static final String KEY_BITMAPS = "bitmaps";
110 private static final String KEY_BITMAP_BYTES = "bitmapBytes";
111
Makoto Onuki31459242016-03-22 11:12:18 -0700112 /**
113 * All the shortcuts from the package, keyed on IDs.
114 */
115 final private ArrayMap<String, ShortcutInfo> mShortcuts = new ArrayMap<>();
116
117 /**
Makoto Onuki31459242016-03-22 11:12:18 -0700118 * # of times the package has called rate-limited APIs.
119 */
120 private int mApiCallCount;
121
122 /**
123 * When {@link #mApiCallCount} was reset last time.
124 */
125 private long mLastResetTime;
126
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700127 private final int mPackageUid;
128
129 private long mLastKnownForegroundElapsedTime;
130
Makoto Onukic51b2872016-05-04 15:24:50 -0700131 private ShortcutPackage(ShortcutUser shortcutUser,
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700132 int packageUserId, String packageName, ShortcutPackageInfo spi) {
133 super(shortcutUser, packageUserId, packageName,
134 spi != null ? spi : ShortcutPackageInfo.newEmpty());
135
Makoto Onukic51b2872016-05-04 15:24:50 -0700136 mPackageUid = shortcutUser.mService.injectGetPackageUid(packageName, packageUserId);
Makoto Onuki31459242016-03-22 11:12:18 -0700137 }
138
Makoto Onukic51b2872016-05-04 15:24:50 -0700139 public ShortcutPackage(ShortcutUser shortcutUser, int packageUserId, String packageName) {
140 this(shortcutUser, packageUserId, packageName, null);
Makoto Onuki0acbb142016-03-22 17:02:57 -0700141 }
142
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700143 @Override
144 public int getOwnerUserId() {
145 // For packages, always owner user == package user.
146 return getPackageUserId();
Makoto Onuki0acbb142016-03-22 17:02:57 -0700147 }
148
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700149 public int getPackageUid() {
150 return mPackageUid;
151 }
152
Makoto Onuki157b1622016-06-02 16:13:10 -0700153 @Nullable
154 public Resources getPackageResources() {
155 return mShortcutUser.mService.injectGetResourcesForApplicationAsUser(
156 getPackageName(), getPackageUserId());
157 }
158
Makoto Onuki2e210c42016-03-30 08:30:36 -0700159 @Override
Makoto Onukic51b2872016-05-04 15:24:50 -0700160 protected void onRestoreBlocked() {
Makoto Onuki2e210c42016-03-30 08:30:36 -0700161 // Can't restore due to version/signature mismatch. Remove all shortcuts.
162 mShortcuts.clear();
163 }
164
165 @Override
Makoto Onukic51b2872016-05-04 15:24:50 -0700166 protected void onRestored() {
Makoto Onuki2e210c42016-03-30 08:30:36 -0700167 // Because some launchers may not have been restored (e.g. allowBackup=false),
168 // we need to re-calculate the pinned shortcuts.
Makoto Onukic51b2872016-05-04 15:24:50 -0700169 refreshPinnedFlags();
Makoto Onuki2e210c42016-03-30 08:30:36 -0700170 }
171
Makoto Onukid99c6f02016-03-28 11:02:54 -0700172 /**
173 * Note this does *not* provide a correct view to the calling launcher.
174 */
Makoto Onuki31459242016-03-22 11:12:18 -0700175 @Nullable
176 public ShortcutInfo findShortcutById(String id) {
177 return mShortcuts.get(id);
178 }
179
Makoto Onuki22fcc682016-05-17 14:52:19 -0700180 private void ensureNotImmutable(@Nullable ShortcutInfo shortcut) {
181 if (shortcut != null && shortcut.isImmutable()) {
182 throw new IllegalArgumentException(
183 "Manifest shortcut ID=" + shortcut.getId()
184 + " may not be manipulated via APIs");
185 }
186 }
187
Makoto Onuki2d895c32016-12-02 15:48:40 -0800188 public void ensureNotImmutable(@NonNull String id) {
Makoto Onuki22fcc682016-05-17 14:52:19 -0700189 ensureNotImmutable(mShortcuts.get(id));
190 }
191
192 public void ensureImmutableShortcutsNotIncludedWithIds(@NonNull List<String> shortcutIds) {
193 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
194 ensureNotImmutable(shortcutIds.get(i));
195 }
196 }
197
198 public void ensureImmutableShortcutsNotIncluded(@NonNull List<ShortcutInfo> shortcuts) {
199 for (int i = shortcuts.size() - 1; i >= 0; i--) {
200 ensureNotImmutable(shortcuts.get(i).getId());
201 }
202 }
203
204 private ShortcutInfo deleteShortcutInner(@NonNull String id) {
Makoto Onuki31459242016-03-22 11:12:18 -0700205 final ShortcutInfo shortcut = mShortcuts.remove(id);
206 if (shortcut != null) {
Makoto Onukic51b2872016-05-04 15:24:50 -0700207 mShortcutUser.mService.removeIcon(getPackageUserId(), shortcut);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700208 shortcut.clearFlags(ShortcutInfo.FLAG_DYNAMIC | ShortcutInfo.FLAG_PINNED
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -0800209 | ShortcutInfo.FLAG_MANIFEST | ShortcutInfo.FLAG_CHOOSER);
Makoto Onuki31459242016-03-22 11:12:18 -0700210 }
211 return shortcut;
212 }
213
Makoto Onuki22fcc682016-05-17 14:52:19 -0700214 private void addShortcutInner(@NonNull ShortcutInfo newShortcut) {
Makoto Onuki157b1622016-06-02 16:13:10 -0700215 final ShortcutService s = mShortcutUser.mService;
216
Makoto Onuki22fcc682016-05-17 14:52:19 -0700217 deleteShortcutInner(newShortcut.getId());
Makoto Onuki157b1622016-06-02 16:13:10 -0700218
219 // Extract Icon and update the icon res ID and the bitmap path.
220 s.saveIconAndFixUpShortcut(getPackageUserId(), newShortcut);
221 s.fixUpShortcutResourceNamesAndValues(newShortcut);
Makoto Onuki31459242016-03-22 11:12:18 -0700222 mShortcuts.put(newShortcut.getId(), newShortcut);
223 }
224
225 /**
226 * Add a shortcut, or update one with the same ID, with taking over existing flags.
227 *
228 * It checks the max number of dynamic shortcuts.
229 */
Makoto Onuki22fcc682016-05-17 14:52:19 -0700230 public void addOrUpdateDynamicShortcut(@NonNull ShortcutInfo newShortcut) {
Makoto Onuki39686e82016-04-13 18:03:00 -0700231
Makoto Onuki22fcc682016-05-17 14:52:19 -0700232 Preconditions.checkArgument(newShortcut.isEnabled(),
233 "add/setDynamicShortcuts() cannot publish disabled shortcuts");
234
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -0800235 addCorrectDynamicFlags(newShortcut);
Makoto Onuki31459242016-03-22 11:12:18 -0700236
237 final ShortcutInfo oldShortcut = mShortcuts.get(newShortcut.getId());
238
239 final boolean wasPinned;
Makoto Onuki31459242016-03-22 11:12:18 -0700240
241 if (oldShortcut == null) {
242 wasPinned = false;
Makoto Onuki31459242016-03-22 11:12:18 -0700243 } else {
Makoto Onuki22fcc682016-05-17 14:52:19 -0700244 // It's an update case.
245 // Make sure the target is updatable. (i.e. should be mutable.)
246 oldShortcut.ensureUpdatableWith(newShortcut);
247
Makoto Onuki31459242016-03-22 11:12:18 -0700248 wasPinned = oldShortcut.isPinned();
Makoto Onuki31459242016-03-22 11:12:18 -0700249 }
250
Makoto Onuki157b1622016-06-02 16:13:10 -0700251 // If it was originally pinned, the new one should be pinned too.
Makoto Onuki31459242016-03-22 11:12:18 -0700252 if (wasPinned) {
253 newShortcut.addFlags(ShortcutInfo.FLAG_PINNED);
254 }
255
Makoto Onuki22fcc682016-05-17 14:52:19 -0700256 addShortcutInner(newShortcut);
Makoto Onuki31459242016-03-22 11:12:18 -0700257 }
258
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -0800259 // TODO: Sample code & JavaDoc for ShortcutManager needs updating to reflect the fact that
260 // Chooser shortcuts are not always dynamic.
261 public void addCorrectDynamicFlags(@NonNull ShortcutInfo shortcut) {
262 if (shortcut.getIntent() != null) {
263 shortcut.addFlags(ShortcutInfo.FLAG_DYNAMIC);
264 }
265 if (!ArrayUtils.isEmpty(shortcut.getChooserIntentFilters())) {
266 shortcut.addFlags(ShortcutInfo.FLAG_CHOOSER);
267 }
268 }
269
Makoto Onuki31459242016-03-22 11:12:18 -0700270 /**
271 * Remove all shortcuts that aren't pinned nor dynamic.
272 */
Makoto Onukic51b2872016-05-04 15:24:50 -0700273 private void removeOrphans() {
Makoto Onuki31459242016-03-22 11:12:18 -0700274 ArrayList<String> removeList = null; // Lazily initialize.
275
276 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
277 final ShortcutInfo si = mShortcuts.valueAt(i);
278
Makoto Onuki22fcc682016-05-17 14:52:19 -0700279 if (si.isAlive()) continue;
Makoto Onuki31459242016-03-22 11:12:18 -0700280
281 if (removeList == null) {
282 removeList = new ArrayList<>();
283 }
284 removeList.add(si.getId());
285 }
286 if (removeList != null) {
287 for (int i = removeList.size() - 1; i >= 0; i--) {
Makoto Onuki22fcc682016-05-17 14:52:19 -0700288 deleteShortcutInner(removeList.get(i));
Makoto Onuki31459242016-03-22 11:12:18 -0700289 }
290 }
291 }
292
293 /**
294 * Remove all dynamic shortcuts.
295 */
Makoto Onukic51b2872016-05-04 15:24:50 -0700296 public void deleteAllDynamicShortcuts() {
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700297 final long now = mShortcutUser.mService.injectCurrentTimeMillis();
298
Makoto Onuki22fcc682016-05-17 14:52:19 -0700299 boolean changed = false;
Makoto Onuki31459242016-03-22 11:12:18 -0700300 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
Makoto Onuki22fcc682016-05-17 14:52:19 -0700301 final ShortcutInfo si = mShortcuts.valueAt(i);
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -0800302 if (si.isDynamic() || si.isChooser()) {
Makoto Onuki22fcc682016-05-17 14:52:19 -0700303 changed = true;
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700304
305 si.setTimestamp(now);
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -0800306 si.clearFlags(ShortcutInfo.FLAG_DYNAMIC | ShortcutInfo.FLAG_CHOOSER);
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700307 si.setRank(0); // It may still be pinned, so clear the rank.
Makoto Onuki22fcc682016-05-17 14:52:19 -0700308 }
Makoto Onuki31459242016-03-22 11:12:18 -0700309 }
Makoto Onuki22fcc682016-05-17 14:52:19 -0700310 if (changed) {
311 removeOrphans();
312 }
Makoto Onuki31459242016-03-22 11:12:18 -0700313 }
314
315 /**
Makoto Onuki7001a612016-05-27 13:24:28 -0700316 * Remove a dynamic shortcut by ID. It'll be removed from the dynamic set, but if the shortcut
317 * is pinned, it'll remain as a pinned shortcut, and is still enabled.
Makoto Onukib08790c2016-06-23 14:05:46 -0700318 *
319 * @return true if it's actually removed because it wasn't pinned, or false if it's still
320 * pinned.
Makoto Onuki31459242016-03-22 11:12:18 -0700321 */
Makoto Onukib08790c2016-06-23 14:05:46 -0700322 public boolean deleteDynamicWithId(@NonNull String shortcutId) {
323 final ShortcutInfo removed = deleteOrDisableWithId(
324 shortcutId, /* disable =*/ false, /* overrideImmutable=*/ false);
325 return removed == null;
326 }
327
328 /**
329 * Disable a dynamic shortcut by ID. It'll be removed from the dynamic set, but if the shortcut
330 * is pinned, it'll remain as a pinned shortcut, but will be disabled.
331 *
332 * @return true if it's actually removed because it wasn't pinned, or false if it's still
333 * pinned.
334 */
335 private boolean disableDynamicWithId(@NonNull String shortcutId) {
336 final ShortcutInfo disabled = deleteOrDisableWithId(
337 shortcutId, /* disable =*/ true, /* overrideImmutable=*/ false);
338 return disabled == null;
Makoto Onuki22fcc682016-05-17 14:52:19 -0700339 }
340
Makoto Onuki7001a612016-05-27 13:24:28 -0700341 /**
342 * Disable a dynamic shortcut by ID. It'll be removed from the dynamic set, but if the shortcut
343 * is pinned, it'll remain as a pinned shortcut but will be disabled.
344 */
Makoto Onuki22fcc682016-05-17 14:52:19 -0700345 public void disableWithId(@NonNull String shortcutId, String disabledMessage,
346 int disabledMessageResId, boolean overrideImmutable) {
347 final ShortcutInfo disabled = deleteOrDisableWithId(shortcutId, /* disable =*/ true,
348 overrideImmutable);
349
350 if (disabled != null) {
351 if (disabledMessage != null) {
352 disabled.setDisabledMessage(disabledMessage);
353 } else if (disabledMessageResId != 0) {
354 disabled.setDisabledMessageResId(disabledMessageResId);
Makoto Onuki157b1622016-06-02 16:13:10 -0700355
356 mShortcutUser.mService.fixUpShortcutResourceNamesAndValues(disabled);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700357 }
358 }
359 }
360
361 @Nullable
362 private ShortcutInfo deleteOrDisableWithId(@NonNull String shortcutId, boolean disable,
363 boolean overrideImmutable) {
Makoto Onuki31459242016-03-22 11:12:18 -0700364 final ShortcutInfo oldShortcut = mShortcuts.get(shortcutId);
365
Makoto Onuki22fcc682016-05-17 14:52:19 -0700366 if (oldShortcut == null || !oldShortcut.isEnabled()) {
367 return null; // Doesn't exist or already disabled.
Makoto Onuki31459242016-03-22 11:12:18 -0700368 }
Makoto Onuki22fcc682016-05-17 14:52:19 -0700369 if (!overrideImmutable) {
370 ensureNotImmutable(oldShortcut);
Makoto Onuki31459242016-03-22 11:12:18 -0700371 }
372 if (oldShortcut.isPinned()) {
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700373
374 oldShortcut.setRank(0);
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -0800375 oldShortcut.clearFlags(ShortcutInfo.FLAG_DYNAMIC | ShortcutInfo.FLAG_MANIFEST
376 | ShortcutInfo.FLAG_CHOOSER);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700377 if (disable) {
378 oldShortcut.addFlags(ShortcutInfo.FLAG_DISABLED);
379 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700380 oldShortcut.setTimestamp(mShortcutUser.mService.injectCurrentTimeMillis());
381
Makoto Onuki255461f2017-01-10 11:47:25 -0800382 // See ShortcutRequestPinProcessor.directPinShortcut().
383 if (mShortcutUser.mService.isDummyMainActivity(oldShortcut.getActivity())) {
384 oldShortcut.setActivity(null);
385 }
386
Makoto Onuki22fcc682016-05-17 14:52:19 -0700387 return oldShortcut;
Makoto Onuki31459242016-03-22 11:12:18 -0700388 } else {
Makoto Onuki22fcc682016-05-17 14:52:19 -0700389 deleteShortcutInner(shortcutId);
390 return null;
391 }
392 }
393
394 public void enableWithId(@NonNull String shortcutId) {
395 final ShortcutInfo shortcut = mShortcuts.get(shortcutId);
396 if (shortcut != null) {
397 ensureNotImmutable(shortcut);
398 shortcut.clearFlags(ShortcutInfo.FLAG_DISABLED);
Makoto Onuki31459242016-03-22 11:12:18 -0700399 }
400 }
401
402 /**
403 * Called after a launcher updates the pinned set. For each shortcut in this package,
404 * set FLAG_PINNED if any launcher has pinned it. Otherwise, clear it.
405 *
406 * <p>Then remove all shortcuts that are not dynamic and no longer pinned either.
407 */
Makoto Onukic51b2872016-05-04 15:24:50 -0700408 public void refreshPinnedFlags() {
Makoto Onuki31459242016-03-22 11:12:18 -0700409 // First, un-pin all shortcuts
410 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
411 mShortcuts.valueAt(i).clearFlags(ShortcutInfo.FLAG_PINNED);
412 }
413
414 // Then, for the pinned set for each launcher, set the pin flag one by one.
Makoto Onukic51b2872016-05-04 15:24:50 -0700415 mShortcutUser.mService.getUserShortcutsLocked(getPackageUserId())
416 .forAllLaunchers(launcherShortcuts -> {
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700417 final ArraySet<String> pinned = launcherShortcuts.getPinnedShortcutIds(
Makoto Onuki2e210c42016-03-30 08:30:36 -0700418 getPackageName(), getPackageUserId());
Makoto Onuki31459242016-03-22 11:12:18 -0700419
420 if (pinned == null || pinned.size() == 0) {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700421 return;
Makoto Onuki31459242016-03-22 11:12:18 -0700422 }
423 for (int i = pinned.size() - 1; i >= 0; i--) {
Makoto Onuki2e210c42016-03-30 08:30:36 -0700424 final String id = pinned.valueAt(i);
425 final ShortcutInfo si = mShortcuts.get(id);
Makoto Onuki31459242016-03-22 11:12:18 -0700426 if (si == null) {
Makoto Onuki2e210c42016-03-30 08:30:36 -0700427 // This happens if a launcher pinned shortcuts from this package, then backup&
428 // restored, but this package doesn't allow backing up.
429 // In that case the launcher ends up having a dangling pinned shortcuts.
430 // That's fine, when the launcher is restored, we'll fix it.
431 continue;
Makoto Onuki31459242016-03-22 11:12:18 -0700432 }
Makoto Onuki2e210c42016-03-30 08:30:36 -0700433 si.addFlags(ShortcutInfo.FLAG_PINNED);
Makoto Onuki31459242016-03-22 11:12:18 -0700434 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700435 });
Makoto Onuki31459242016-03-22 11:12:18 -0700436
437 // Lastly, remove the ones that are no longer pinned nor dynamic.
Makoto Onukic51b2872016-05-04 15:24:50 -0700438 removeOrphans();
Makoto Onuki31459242016-03-22 11:12:18 -0700439 }
440
441 /**
442 * Number of calls that the caller has made, since the last reset.
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700443 *
444 * <p>This takes care of the resetting the counter for foreground apps as well as after
445 * locale changes.
Makoto Onuki31459242016-03-22 11:12:18 -0700446 */
Makoto Onukic51b2872016-05-04 15:24:50 -0700447 public int getApiCallCount() {
Makoto Onukic51b2872016-05-04 15:24:50 -0700448 final ShortcutService s = mShortcutUser.mService;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700449
450 // Reset the counter if:
451 // - the package is in foreground now.
452 // - the package is *not* in foreground now, but was in foreground at some point
453 // since the previous time it had been.
454 if (s.isUidForegroundLocked(mPackageUid)
455 || mLastKnownForegroundElapsedTime
456 < s.getUidLastForegroundElapsedTimeLocked(mPackageUid)) {
457 mLastKnownForegroundElapsedTime = s.injectElapsedRealtime();
Makoto Onukic51b2872016-05-04 15:24:50 -0700458 resetRateLimiting();
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700459 }
460
461 // Note resetThrottlingIfNeeded() and resetRateLimiting() will set 0 to mApiCallCount,
462 // but we just can't return 0 at this point, because we may have to update
463 // mLastResetTime.
464
Makoto Onuki31459242016-03-22 11:12:18 -0700465 final long last = s.getLastResetTimeLocked();
466
467 final long now = s.injectCurrentTimeMillis();
468 if (ShortcutService.isClockValid(now) && mLastResetTime > now) {
469 Slog.w(TAG, "Clock rewound");
470 // Clock rewound.
471 mLastResetTime = now;
472 mApiCallCount = 0;
473 return mApiCallCount;
474 }
475
476 // If not reset yet, then reset.
477 if (mLastResetTime < last) {
478 if (ShortcutService.DEBUG) {
Makoto Onukic51b2872016-05-04 15:24:50 -0700479 Slog.d(TAG, String.format("%s: last reset=%d, now=%d, last=%d: resetting",
480 getPackageName(), mLastResetTime, now, last));
Makoto Onuki31459242016-03-22 11:12:18 -0700481 }
482 mApiCallCount = 0;
483 mLastResetTime = last;
484 }
485 return mApiCallCount;
486 }
487
488 /**
489 * If the caller app hasn't been throttled yet, increment {@link #mApiCallCount}
490 * and return true. Otherwise just return false.
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700491 *
492 * <p>This takes care of the resetting the counter for foreground apps as well as after
493 * locale changes, which is done internally by {@link #getApiCallCount}.
Makoto Onuki31459242016-03-22 11:12:18 -0700494 */
Makoto Onukic51b2872016-05-04 15:24:50 -0700495 public boolean tryApiCall() {
496 final ShortcutService s = mShortcutUser.mService;
497
498 if (getApiCallCount() >= s.mMaxUpdatesPerInterval) {
Makoto Onuki31459242016-03-22 11:12:18 -0700499 return false;
500 }
501 mApiCallCount++;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700502 s.scheduleSaveUser(getOwnerUserId());
Makoto Onuki31459242016-03-22 11:12:18 -0700503 return true;
504 }
505
Makoto Onukic51b2872016-05-04 15:24:50 -0700506 public void resetRateLimiting() {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700507 if (ShortcutService.DEBUG) {
508 Slog.d(TAG, "resetRateLimiting: " + getPackageName());
509 }
510 if (mApiCallCount > 0) {
511 mApiCallCount = 0;
Makoto Onukic51b2872016-05-04 15:24:50 -0700512 mShortcutUser.mService.scheduleSaveUser(getOwnerUserId());
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700513 }
514 }
515
516 public void resetRateLimitingForCommandLineNoSaving() {
Makoto Onuki31459242016-03-22 11:12:18 -0700517 mApiCallCount = 0;
518 mLastResetTime = 0;
519 }
520
521 /**
522 * Find all shortcuts that match {@code query}.
523 */
Makoto Onukic51b2872016-05-04 15:24:50 -0700524 public void findAll(@NonNull List<ShortcutInfo> result,
Makoto Onukid99c6f02016-03-28 11:02:54 -0700525 @Nullable Predicate<ShortcutInfo> query, int cloneFlag) {
Makoto Onukic51b2872016-05-04 15:24:50 -0700526 findAll(result, query, cloneFlag, null, 0);
Makoto Onukid99c6f02016-03-28 11:02:54 -0700527 }
528
529 /**
530 * Find all shortcuts that match {@code query}.
531 *
532 * This will also provide a "view" for each launcher -- a non-dynamic shortcut that's not pinned
533 * by the calling launcher will not be included in the result, and also "isPinned" will be
534 * adjusted for the caller too.
535 */
Makoto Onukic51b2872016-05-04 15:24:50 -0700536 public void findAll(@NonNull List<ShortcutInfo> result,
Makoto Onuki31459242016-03-22 11:12:18 -0700537 @Nullable Predicate<ShortcutInfo> query, int cloneFlag,
Makoto Onukid99c6f02016-03-28 11:02:54 -0700538 @Nullable String callingLauncher, int launcherUserId) {
Makoto Onuki2e210c42016-03-30 08:30:36 -0700539 if (getPackageInfo().isShadow()) {
540 // Restored and the app not installed yet, so don't return any.
541 return;
542 }
Makoto Onuki31459242016-03-22 11:12:18 -0700543
Makoto Onukic51b2872016-05-04 15:24:50 -0700544 final ShortcutService s = mShortcutUser.mService;
545
Makoto Onuki31459242016-03-22 11:12:18 -0700546 // Set of pinned shortcuts by the calling launcher.
547 final ArraySet<String> pinnedByCallerSet = (callingLauncher == null) ? null
Makoto Onuki2e210c42016-03-30 08:30:36 -0700548 : s.getLauncherShortcutsLocked(callingLauncher, getPackageUserId(), launcherUserId)
549 .getPinnedShortcutIds(getPackageName(), getPackageUserId());
Makoto Onuki31459242016-03-22 11:12:18 -0700550
551 for (int i = 0; i < mShortcuts.size(); i++) {
552 final ShortcutInfo si = mShortcuts.valueAt(i);
553
Makoto Onuki22fcc682016-05-17 14:52:19 -0700554 // Need to adjust PINNED flag depending on the caller.
555 // Basically if the caller is a launcher (callingLauncher != null) and the launcher
556 // isn't pinning it, then we need to clear PINNED for this caller.
Makoto Onuki31459242016-03-22 11:12:18 -0700557 final boolean isPinnedByCaller = (callingLauncher == null)
558 || ((pinnedByCallerSet != null) && pinnedByCallerSet.contains(si.getId()));
Makoto Onuki22fcc682016-05-17 14:52:19 -0700559
560 if (si.isFloating()) {
Makoto Onuki31459242016-03-22 11:12:18 -0700561 if (!isPinnedByCaller) {
562 continue;
563 }
564 }
565 final ShortcutInfo clone = si.clone(cloneFlag);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700566
Makoto Onuki31459242016-03-22 11:12:18 -0700567 // Fix up isPinned for the caller. Note we need to do it before the "test" callback,
568 // since it may check isPinned.
569 if (!isPinnedByCaller) {
570 clone.clearFlags(ShortcutInfo.FLAG_PINNED);
571 }
572 if (query == null || query.test(clone)) {
573 result.add(clone);
574 }
575 }
576 }
577
578 public void resetThrottling() {
579 mApiCallCount = 0;
580 }
581
Makoto Onuki39686e82016-04-13 18:03:00 -0700582 /**
Makoto Onuki6c1dbd52016-05-02 15:19:32 -0700583 * Return the filenames (excluding path names) of icon bitmap files from this package.
584 */
585 public ArraySet<String> getUsedBitmapFiles() {
586 final ArraySet<String> usedFiles = new ArraySet<>(mShortcuts.size());
587
588 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
589 final ShortcutInfo si = mShortcuts.valueAt(i);
590 if (si.getBitmapPath() != null) {
591 usedFiles.add(getFileName(si.getBitmapPath()));
592 }
593 }
594 return usedFiles;
595 }
596
597 private static String getFileName(@NonNull String path) {
598 final int sep = path.lastIndexOf(File.separatorChar);
599 if (sep == -1) {
600 return path;
601 } else {
602 return path.substring(sep + 1);
603 }
604 }
605
606 /**
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700607 * @return false if any of the target activities are no longer enabled.
608 */
609 private boolean areAllActivitiesStillEnabled() {
610 if (mShortcuts.size() == 0) {
611 return true;
612 }
613 final ShortcutService s = mShortcutUser.mService;
614
615 // Normally the number of target activities is 1 or so, so no need to use a complex
616 // structure like a set.
617 final ArrayList<ComponentName> checked = new ArrayList<>(4);
618
619 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
620 final ShortcutInfo si = mShortcuts.valueAt(i);
621 final ComponentName activity = si.getActivity();
622
623 if (checked.contains(activity)) {
624 continue; // Already checked.
625 }
626 checked.add(activity);
627
628 if (!s.injectIsActivityEnabledAndExported(activity, getOwnerUserId())) {
629 return false;
630 }
631 }
632 return true;
633 }
634
635 /**
636 * Called when the package may be added or updated, or its activities may be disabled, and
637 * if so, rescan the package and do the necessary stuff.
Makoto Onuki22fcc682016-05-17 14:52:19 -0700638 *
639 * Add case:
640 * - Publish manifest shortcuts.
641 *
642 * Update case:
643 * - Re-publish manifest shortcuts.
644 * - If there are shortcuts with resources (icons or strings), update their timestamps.
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700645 * - Disable shortcuts whose target activities are disabled.
Makoto Onuki22fcc682016-05-17 14:52:19 -0700646 *
647 * @return TRUE if any shortcuts have been changed.
Makoto Onuki39686e82016-04-13 18:03:00 -0700648 */
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700649 public boolean rescanPackageIfNeeded(boolean isNewApp, boolean forceRescan) {
650 final ShortcutService s = mShortcutUser.mService;
651 final long start = s.injectElapsedRealtime();
Makoto Onuki39686e82016-04-13 18:03:00 -0700652
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700653 final PackageInfo pi;
654 try {
655 pi = mShortcutUser.mService.getPackageInfo(
656 getPackageName(), getPackageUserId());
657 if (pi == null) {
658 return false; // Shouldn't happen.
Makoto Onuki22fcc682016-05-17 14:52:19 -0700659 }
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700660
Makoto Onuki248a0ef2016-11-03 15:59:01 -0700661 if (!isNewApp && !forceRescan) {
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700662 // Return if the package hasn't changed, ie:
663 // - version code hasn't change
664 // - lastUpdateTime hasn't change
665 // - all target activities are still enabled.
Makoto Onuki33663282016-08-22 16:19:04 -0700666
667 // Note, system apps timestamps do *not* change after OTAs. (But they do
668 // after an adb sync or a local flash.)
669 // This means if a system app's version code doesn't change on an OTA,
670 // we don't notice it's updated. But that's fine since their version code *should*
671 // really change on OTAs.
Makoto Onuki64183d52016-08-08 14:11:34 -0700672 if ((getPackageInfo().getVersionCode() == pi.versionCode)
673 && (getPackageInfo().getLastUpdateTime() == pi.lastUpdateTime)
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700674 && areAllActivitiesStillEnabled()) {
675 return false;
676 }
677 }
678 } finally {
679 s.logDurationStat(Stats.PACKAGE_UPDATE_CHECK, start);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700680 }
681
682 // Now prepare to publish manifest shortcuts.
683 List<ShortcutInfo> newManifestShortcutList = null;
684 try {
685 newManifestShortcutList = ShortcutParser.parseShortcuts(mShortcutUser.mService,
686 getPackageName(), getPackageUserId());
687 } catch (IOException|XmlPullParserException e) {
688 Slog.e(TAG, "Failed to load shortcuts from AndroidManifest.xml.", e);
689 }
690 final int manifestShortcutSize = newManifestShortcutList == null ? 0
691 : newManifestShortcutList.size();
692 if (ShortcutService.DEBUG) {
693 Slog.d(TAG, String.format("Package %s has %d manifest shortcut(s)",
694 getPackageName(), manifestShortcutSize));
695 }
696 if (isNewApp && (manifestShortcutSize == 0)) {
697 // If it's a new app, and it doesn't have manifest shortcuts, then nothing to do.
698
699 // If it's an update, then it may already have manifest shortcuts, which need to be
700 // disabled.
701 return false;
702 }
703 if (ShortcutService.DEBUG) {
704 Slog.d(TAG, String.format("Package %s %s, version %d -> %d", getPackageName(),
705 (isNewApp ? "added" : "updated"),
706 getPackageInfo().getVersionCode(), pi.versionCode));
707 }
708
709 getPackageInfo().updateVersionInfo(pi);
Makoto Onuki39686e82016-04-13 18:03:00 -0700710
711 boolean changed = false;
Makoto Onuki39686e82016-04-13 18:03:00 -0700712
Makoto Onuki22fcc682016-05-17 14:52:19 -0700713 // For existing shortcuts, update timestamps if they have any resources.
Makoto Onukib08790c2016-06-23 14:05:46 -0700714 // Also check if shortcuts' activities are still main activities. Otherwise, disable them.
Makoto Onuki22fcc682016-05-17 14:52:19 -0700715 if (!isNewApp) {
Makoto Onuki157b1622016-06-02 16:13:10 -0700716 Resources publisherRes = null;
717
Makoto Onuki22fcc682016-05-17 14:52:19 -0700718 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
719 final ShortcutInfo si = mShortcuts.valueAt(i);
720
Makoto Onuki2d895c32016-12-02 15:48:40 -0800721 // Disable dynamic shortcuts whose target activity is gone.
Makoto Onukib08790c2016-06-23 14:05:46 -0700722 if (si.isDynamic()) {
Makoto Onuki34145532017-03-14 17:58:36 -0700723 if (si.getActivity() == null) {
724 // Note if it's dynamic, it must have a target activity, but b/36228253.
725 s.wtf("null activity detected.");
726 // TODO Maybe remove it?
727 } else if (!s.injectIsMainActivity(si.getActivity(), getPackageUserId())) {
Makoto Onukib08790c2016-06-23 14:05:46 -0700728 Slog.w(TAG, String.format(
729 "%s is no longer main activity. Disabling shorcut %s.",
730 getPackageName(), si.getId()));
731 if (disableDynamicWithId(si.getId())) {
732 continue; // Actually removed.
733 }
734 // Still pinned, so fall-through and possibly update the resources.
735 }
736 changed = true;
737 }
738
Makoto Onuki22fcc682016-05-17 14:52:19 -0700739 if (si.hasAnyResources()) {
Makoto Onuki157b1622016-06-02 16:13:10 -0700740 if (!si.isOriginallyFromManifest()) {
741 if (publisherRes == null) {
742 publisherRes = getPackageResources();
743 if (publisherRes == null) {
744 break; // Resources couldn't be loaded.
745 }
746 }
747
748 // If this shortcut is not from a manifest, then update all resource IDs
749 // from resource names. (We don't allow resource strings for
750 // non-manifest at the moment, but icons can still be resources.)
751 si.lookupAndFillInResourceIds(publisherRes);
752 }
Makoto Onuki22fcc682016-05-17 14:52:19 -0700753 changed = true;
754 si.setTimestamp(s.injectCurrentTimeMillis());
755 }
Makoto Onuki39686e82016-04-13 18:03:00 -0700756 }
757 }
Makoto Onuki22fcc682016-05-17 14:52:19 -0700758
759 // (Re-)publish manifest shortcut.
760 changed |= publishManifestShortcuts(newManifestShortcutList);
761
Makoto Onuki7001a612016-05-27 13:24:28 -0700762 if (newManifestShortcutList != null) {
763 changed |= pushOutExcessShortcuts();
764 }
765
Makoto Onukidf6da042016-06-16 09:51:40 -0700766 s.verifyStates();
767
Makoto Onuki39686e82016-04-13 18:03:00 -0700768 if (changed) {
769 // This will send a notification to the launcher, and also save .
770 s.packageShortcutsChanged(getPackageName(), getPackageUserId());
771 } else {
772 // Still save the version code.
773 s.scheduleSaveUser(getPackageUserId());
774 }
Makoto Onuki22fcc682016-05-17 14:52:19 -0700775 return changed;
776 }
777
778 private boolean publishManifestShortcuts(List<ShortcutInfo> newManifestShortcutList) {
779 if (ShortcutService.DEBUG) {
780 Slog.d(TAG, String.format(
781 "Package %s: publishing manifest shortcuts", getPackageName()));
782 }
783 boolean changed = false;
784
Makoto Onuki22fcc682016-05-17 14:52:19 -0700785 // Keep the previous IDs.
786 ArraySet<String> toDisableList = null;
787 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
788 final ShortcutInfo si = mShortcuts.valueAt(i);
789
790 if (si.isManifestShortcut()) {
791 if (toDisableList == null) {
792 toDisableList = new ArraySet<>();
793 }
794 toDisableList.add(si.getId());
795 }
796 }
797
798 // Publish new ones.
799 if (newManifestShortcutList != null) {
800 final int newListSize = newManifestShortcutList.size();
801
802 for (int i = 0; i < newListSize; i++) {
803 changed = true;
804
805 final ShortcutInfo newShortcut = newManifestShortcutList.get(i);
806 final boolean newDisabled = !newShortcut.isEnabled();
807
Makoto Onuki7001a612016-05-27 13:24:28 -0700808 final String id = newShortcut.getId();
Makoto Onuki22fcc682016-05-17 14:52:19 -0700809 final ShortcutInfo oldShortcut = mShortcuts.get(id);
810
811 boolean wasPinned = false;
812
813 if (oldShortcut != null) {
814 if (!oldShortcut.isOriginallyFromManifest()) {
815 Slog.e(TAG, "Shortcut with ID=" + newShortcut.getId()
816 + " exists but is not from AndroidManifest.xml, not updating.");
817 continue;
818 }
819 // Take over the pinned flag.
820 if (oldShortcut.isPinned()) {
821 wasPinned = true;
822 newShortcut.addFlags(ShortcutInfo.FLAG_PINNED);
823 }
824 }
825 if (newDisabled && !wasPinned) {
826 // If the shortcut is disabled, and it was *not* pinned, then this
827 // just doesn't have to be published.
828 // Just keep it in toDisableList, so the previous one would be removed.
829 continue;
830 }
Makoto Onuki22fcc682016-05-17 14:52:19 -0700831
832 // Note even if enabled=false, we still need to update all fields, so do it
833 // regardless.
834 addShortcutInner(newShortcut); // This will clean up the old one too.
835
836 if (!newDisabled && toDisableList != null) {
837 // Still alive, don't remove.
838 toDisableList.remove(id);
839 }
840 }
841 }
842
843 // Disable the previous manifest shortcuts that are no longer in the manifest.
844 if (toDisableList != null) {
845 if (ShortcutService.DEBUG) {
846 Slog.d(TAG, String.format(
847 "Package %s: disabling %d stale shortcuts", getPackageName(),
848 toDisableList.size()));
849 }
850 for (int i = toDisableList.size() - 1; i >= 0; i--) {
851 changed = true;
852
853 final String id = toDisableList.valueAt(i);
854
855 disableWithId(id, /* disable message =*/ null, /* disable message resid */ 0,
856 /* overrideImmutable=*/ true);
857 }
858 removeOrphans();
859 }
Makoto Onukidf6da042016-06-16 09:51:40 -0700860 adjustRanks();
Makoto Onuki22fcc682016-05-17 14:52:19 -0700861 return changed;
Makoto Onuki39686e82016-04-13 18:03:00 -0700862 }
863
Makoto Onuki7001a612016-05-27 13:24:28 -0700864 /**
865 * For each target activity, make sure # of dynamic + manifest shortcuts <= max.
866 * If too many, we'll remove the dynamic with the lowest ranks.
867 */
868 private boolean pushOutExcessShortcuts() {
869 final ShortcutService service = mShortcutUser.mService;
870 final int maxShortcuts = service.getMaxActivityShortcuts();
871
872 boolean changed = false;
873
874 final ArrayMap<ComponentName, ArrayList<ShortcutInfo>> all =
875 sortShortcutsToActivities();
876 for (int outer = all.size() - 1; outer >= 0; outer--) {
877 final ArrayList<ShortcutInfo> list = all.valueAt(outer);
878 if (list.size() <= maxShortcuts) {
879 continue;
880 }
881 // Sort by isManifestShortcut() and getRank().
882 Collections.sort(list, mShortcutTypeAndRankComparator);
883
884 // Keep [0 .. max), and remove (as dynamic) [max .. size)
885 for (int inner = list.size() - 1; inner >= maxShortcuts; inner--) {
886 final ShortcutInfo shortcut = list.get(inner);
887
888 if (shortcut.isManifestShortcut()) {
889 // This shouldn't happen -- excess shortcuts should all be non-manifest.
890 // But just in case.
891 service.wtf("Found manifest shortcuts in excess list.");
892 continue;
893 }
894 deleteDynamicWithId(shortcut.getId());
895 }
896 }
Makoto Onuki7001a612016-05-27 13:24:28 -0700897
898 return changed;
899 }
900
901 /**
902 * To sort by isManifestShortcut() and getRank(). i.e. manifest shortcuts come before
903 * non-manifest shortcuts, then sort by rank.
904 *
905 * This is used to decide which dynamic shortcuts to remove when an upgraded version has more
906 * manifest shortcuts than before and as a result we need to remove some of the dynamic
907 * shortcuts. We sort manifest + dynamic shortcuts by this order, and remove the ones with
908 * the last ones.
909 *
910 * (Note the number of manifest shortcuts is always <= the max number, because if there are
911 * more, ShortcutParser would ignore the rest.)
912 */
913 final Comparator<ShortcutInfo> mShortcutTypeAndRankComparator = (ShortcutInfo a,
914 ShortcutInfo b) -> {
915 if (a.isManifestShortcut() && !b.isManifestShortcut()) {
916 return -1;
917 }
918 if (!a.isManifestShortcut() && b.isManifestShortcut()) {
919 return 1;
920 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700921 return Integer.compare(a.getRank(), b.getRank());
Makoto Onuki7001a612016-05-27 13:24:28 -0700922 };
923
924 /**
925 * Build a list of shortcuts for each target activity and return as a map. The result won't
926 * contain "floating" shortcuts because they don't belong on any activities.
927 */
928 private ArrayMap<ComponentName, ArrayList<ShortcutInfo>> sortShortcutsToActivities() {
Makoto Onuki7001a612016-05-27 13:24:28 -0700929 final ArrayMap<ComponentName, ArrayList<ShortcutInfo>> activitiesToShortcuts
930 = new ArrayMap<>();
931 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
932 final ShortcutInfo si = mShortcuts.valueAt(i);
933 if (si.isFloating()) {
934 continue; // Ignore floating shortcuts, which are not tied to any activities.
935 }
936
937 final ComponentName activity = si.getActivity();
Makoto Onuki34145532017-03-14 17:58:36 -0700938 if (activity == null) {
939 mShortcutUser.mService.wtf("null activity detected.");
940 continue;
941 }
Makoto Onuki7001a612016-05-27 13:24:28 -0700942
943 ArrayList<ShortcutInfo> list = activitiesToShortcuts.get(activity);
944 if (list == null) {
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700945 list = new ArrayList<>();
Makoto Onuki7001a612016-05-27 13:24:28 -0700946 activitiesToShortcuts.put(activity, list);
947 }
948 list.add(si);
949 }
950 return activitiesToShortcuts;
951 }
952
953 /** Used by {@link #enforceShortcutCountsBeforeOperation} */
954 private void incrementCountForActivity(ArrayMap<ComponentName, Integer> counts,
955 ComponentName cn, int increment) {
956 Integer oldValue = counts.get(cn);
957 if (oldValue == null) {
958 oldValue = 0;
959 }
960
961 counts.put(cn, oldValue + increment);
962 }
963
964 /**
965 * Called by
966 * {@link android.content.pm.ShortcutManager#setDynamicShortcuts},
967 * {@link android.content.pm.ShortcutManager#addDynamicShortcuts}, and
968 * {@link android.content.pm.ShortcutManager#updateShortcuts} before actually performing
969 * the operation to make sure the operation wouldn't result in the target activities having
970 * more than the allowed number of dynamic/manifest shortcuts.
971 *
972 * @param newList shortcut list passed to set, add or updateShortcuts().
973 * @param operation add, set or update.
974 * @throws IllegalArgumentException if the operation would result in going over the max
975 * shortcut count for any activity.
976 */
977 public void enforceShortcutCountsBeforeOperation(List<ShortcutInfo> newList,
978 @ShortcutOperation int operation) {
979 final ShortcutService service = mShortcutUser.mService;
980
981 // Current # of dynamic / manifest shortcuts for each activity.
982 // (If it's for update, then don't count dynamic shortcuts, since they'll be replaced
983 // anyway.)
984 final ArrayMap<ComponentName, Integer> counts = new ArrayMap<>(4);
985 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
986 final ShortcutInfo shortcut = mShortcuts.valueAt(i);
987
988 if (shortcut.isManifestShortcut()) {
989 incrementCountForActivity(counts, shortcut.getActivity(), 1);
990 } else if (shortcut.isDynamic() && (operation != ShortcutService.OPERATION_SET)) {
991 incrementCountForActivity(counts, shortcut.getActivity(), 1);
992 }
993 }
994
995 for (int i = newList.size() - 1; i >= 0; i--) {
996 final ShortcutInfo newShortcut = newList.get(i);
997 final ComponentName newActivity = newShortcut.getActivity();
998 if (newActivity == null) {
999 if (operation != ShortcutService.OPERATION_UPDATE) {
Makoto Onukib08790c2016-06-23 14:05:46 -07001000 service.wtf("Activity must not be null at this point");
1001 continue; // Just ignore this invalid case.
Makoto Onuki7001a612016-05-27 13:24:28 -07001002 }
1003 continue; // Activity can be null for update.
1004 }
1005
1006 final ShortcutInfo original = mShortcuts.get(newShortcut.getId());
1007 if (original == null) {
1008 if (operation == ShortcutService.OPERATION_UPDATE) {
1009 continue; // When updating, ignore if there's no target.
1010 }
1011 // Add() or set(), and there's no existing shortcut with the same ID. We're
1012 // simply publishing (as opposed to updating) this shortcut, so just +1.
1013 incrementCountForActivity(counts, newActivity, 1);
1014 continue;
1015 }
1016 if (original.isFloating() && (operation == ShortcutService.OPERATION_UPDATE)) {
1017 // Updating floating shortcuts doesn't affect the count, so ignore.
1018 continue;
1019 }
1020
1021 // If it's add() or update(), then need to decrement for the previous activity.
1022 // Skip it for set() since it's already been taken care of by not counting the original
1023 // dynamic shortcuts in the first loop.
1024 if (operation != ShortcutService.OPERATION_SET) {
1025 final ComponentName oldActivity = original.getActivity();
1026 if (!original.isFloating()) {
1027 incrementCountForActivity(counts, oldActivity, -1);
1028 }
1029 }
1030 incrementCountForActivity(counts, newActivity, 1);
1031 }
1032
1033 // Then make sure none of the activities have more than the max number of shortcuts.
1034 for (int i = counts.size() - 1; i >= 0; i--) {
1035 service.enforceMaxActivityShortcuts(counts.valueAt(i));
1036 }
1037 }
1038
Makoto Onuki157b1622016-06-02 16:13:10 -07001039 /**
1040 * For all the text fields, refresh the string values if they're from resources.
1041 */
1042 public void resolveResourceStrings() {
1043 final ShortcutService s = mShortcutUser.mService;
1044 boolean changed = false;
1045
1046 Resources publisherRes = null;
1047 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1048 final ShortcutInfo si = mShortcuts.valueAt(i);
1049
1050 if (si.hasStringResources()) {
1051 changed = true;
1052
1053 if (publisherRes == null) {
1054 publisherRes = getPackageResources();
1055 if (publisherRes == null) {
1056 break; // Resources couldn't be loaded.
1057 }
1058 }
1059
1060 si.resolveResourceStrings(publisherRes);
1061 si.setTimestamp(s.injectCurrentTimeMillis());
1062 }
1063 }
1064 if (changed) {
Makoto Onuki4e6cef42016-07-13 16:14:01 -07001065 s.packageShortcutsChanged(getPackageName(), getPackageUserId());
Makoto Onuki157b1622016-06-02 16:13:10 -07001066 }
1067 }
1068
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001069 /** Clears the implicit ranks for all shortcuts. */
1070 public void clearAllImplicitRanks() {
1071 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1072 final ShortcutInfo si = mShortcuts.valueAt(i);
1073 si.clearImplicitRankAndRankChangedFlag();
1074 }
1075 }
1076
1077 /**
1078 * Used to sort shortcuts for rank auto-adjusting.
1079 */
1080 final Comparator<ShortcutInfo> mShortcutRankComparator = (ShortcutInfo a, ShortcutInfo b) -> {
1081 // First, sort by rank.
1082 int ret = Integer.compare(a.getRank(), b.getRank());
1083 if (ret != 0) {
1084 return ret;
1085 }
1086 // When ranks are tie, then prioritize the ones that have just been assigned new ranks.
1087 // e.g. when there are 3 shortcuts, "s1" "s2" and "s3" with rank 0, 1, 2 respectively,
1088 // adding a shortcut "s4" with rank 1 will "insert" it between "s1" and "s2", because
1089 // "s2" and "s4" have the same rank 1 but s4 has isRankChanged() set.
1090 // Similarly, updating s3's rank to 1 will insert it between s1 and s2.
1091 if (a.isRankChanged() != b.isRankChanged()) {
1092 return a.isRankChanged() ? -1 : 1;
1093 }
1094 // If they're still tie, sort by implicit rank -- i.e. preserve the order in which
1095 // they're passed to the API.
1096 ret = Integer.compare(a.getImplicitRank(), b.getImplicitRank());
1097 if (ret != 0) {
1098 return ret;
1099 }
1100 // If they're stil tie, just sort by their IDs.
1101 // This may happen with updateShortcuts() -- see
1102 // the testUpdateShortcuts_noManifestShortcuts() test.
1103 return a.getId().compareTo(b.getId());
1104 };
1105
1106 /**
1107 * Re-calculate the ranks for all shortcuts.
1108 */
1109 public void adjustRanks() {
1110 final ShortcutService s = mShortcutUser.mService;
1111 final long now = s.injectCurrentTimeMillis();
1112
1113 // First, clear ranks for floating shortcuts.
1114 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1115 final ShortcutInfo si = mShortcuts.valueAt(i);
1116 if (si.isFloating()) {
1117 if (si.getRank() != 0) {
1118 si.setTimestamp(now);
1119 si.setRank(0);
1120 }
1121 }
1122 }
1123
1124 // Then adjust ranks. Ranks are unique for each activity, so we first need to sort
1125 // shortcuts to each activity.
1126 // Then sort the shortcuts within each activity with mShortcutRankComparator, and
1127 // assign ranks from 0.
1128 final ArrayMap<ComponentName, ArrayList<ShortcutInfo>> all =
1129 sortShortcutsToActivities();
1130 for (int outer = all.size() - 1; outer >= 0; outer--) { // For each activity.
1131 final ArrayList<ShortcutInfo> list = all.valueAt(outer);
1132
1133 // Sort by ranks and other signals.
1134 Collections.sort(list, mShortcutRankComparator);
1135
1136 int rank = 0;
1137
1138 final int size = list.size();
1139 for (int i = 0; i < size; i++) {
1140 final ShortcutInfo si = list.get(i);
1141 if (si.isManifestShortcut()) {
1142 // Don't adjust ranks for manifest shortcuts.
1143 continue;
1144 }
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -08001145 // At this point, it must be dynamic or a chooser.
1146 if (!si.isDynamicOrChooser()) {
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001147 s.wtf("Non-dynamic shortcut found.");
1148 continue;
1149 }
1150 final int thisRank = rank++;
1151 if (si.getRank() != thisRank) {
1152 si.setTimestamp(now);
1153 si.setRank(thisRank);
1154 }
1155 }
1156 }
1157 }
1158
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07001159 /** @return true if there's any shortcuts that are not manifest shortcuts. */
1160 public boolean hasNonManifestShortcuts() {
1161 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1162 final ShortcutInfo si = mShortcuts.valueAt(i);
1163 if (!si.isDeclaredInManifest()) {
1164 return true;
1165 }
1166 }
1167 return false;
1168 }
1169
Makoto Onukic51b2872016-05-04 15:24:50 -07001170 public void dump(@NonNull PrintWriter pw, @NonNull String prefix) {
Makoto Onuki31459242016-03-22 11:12:18 -07001171 pw.println();
1172
1173 pw.print(prefix);
1174 pw.print("Package: ");
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001175 pw.print(getPackageName());
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001176 pw.print(" UID: ");
1177 pw.print(mPackageUid);
Makoto Onuki31459242016-03-22 11:12:18 -07001178 pw.println();
1179
1180 pw.print(prefix);
1181 pw.print(" ");
1182 pw.print("Calls: ");
Makoto Onukic51b2872016-05-04 15:24:50 -07001183 pw.print(getApiCallCount());
Makoto Onuki31459242016-03-22 11:12:18 -07001184 pw.println();
1185
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001186 // getApiCallCount() may have updated mLastKnownForegroundElapsedTime.
1187 pw.print(prefix);
1188 pw.print(" ");
1189 pw.print("Last known FG: ");
1190 pw.print(mLastKnownForegroundElapsedTime);
1191 pw.println();
1192
Makoto Onuki31459242016-03-22 11:12:18 -07001193 // This should be after getApiCallCount(), which may update it.
1194 pw.print(prefix);
1195 pw.print(" ");
1196 pw.print("Last reset: [");
1197 pw.print(mLastResetTime);
1198 pw.print("] ");
Makoto Onukic51b2872016-05-04 15:24:50 -07001199 pw.print(ShortcutService.formatTime(mLastResetTime));
Makoto Onuki31459242016-03-22 11:12:18 -07001200 pw.println();
1201
Makoto Onukic51b2872016-05-04 15:24:50 -07001202 getPackageInfo().dump(pw, prefix + " ");
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001203 pw.println();
1204
Makoto Onuki39686e82016-04-13 18:03:00 -07001205 pw.print(prefix);
1206 pw.println(" Shortcuts:");
Makoto Onuki31459242016-03-22 11:12:18 -07001207 long totalBitmapSize = 0;
1208 final ArrayMap<String, ShortcutInfo> shortcuts = mShortcuts;
1209 final int size = shortcuts.size();
1210 for (int i = 0; i < size; i++) {
1211 final ShortcutInfo si = shortcuts.valueAt(i);
Makoto Onuki39686e82016-04-13 18:03:00 -07001212 pw.print(prefix);
1213 pw.print(" ");
Makoto Onuki31459242016-03-22 11:12:18 -07001214 pw.println(si.toInsecureString());
1215 if (si.getBitmapPath() != null) {
1216 final long len = new File(si.getBitmapPath()).length();
Makoto Onuki39686e82016-04-13 18:03:00 -07001217 pw.print(prefix);
1218 pw.print(" ");
Makoto Onuki31459242016-03-22 11:12:18 -07001219 pw.print("bitmap size=");
1220 pw.println(len);
1221
1222 totalBitmapSize += len;
1223 }
1224 }
1225 pw.print(prefix);
1226 pw.print(" ");
1227 pw.print("Total bitmap size: ");
1228 pw.print(totalBitmapSize);
1229 pw.print(" (");
Makoto Onukic51b2872016-05-04 15:24:50 -07001230 pw.print(Formatter.formatFileSize(mShortcutUser.mService.mContext, totalBitmapSize));
Makoto Onuki31459242016-03-22 11:12:18 -07001231 pw.println(")");
1232 }
1233
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001234 @Override
Makoto Onuki76269922016-07-15 14:58:54 -07001235 public JSONObject dumpCheckin(boolean clear) throws JSONException {
1236 final JSONObject result = super.dumpCheckin(clear);
1237
1238 int numDynamic = 0;
1239 int numPinned = 0;
1240 int numManifest = 0;
1241 int numBitmaps = 0;
1242 long totalBitmapSize = 0;
1243
1244 final ArrayMap<String, ShortcutInfo> shortcuts = mShortcuts;
1245 final int size = shortcuts.size();
1246 for (int i = 0; i < size; i++) {
1247 final ShortcutInfo si = shortcuts.valueAt(i);
1248
1249 if (si.isDynamic()) numDynamic++;
1250 if (si.isDeclaredInManifest()) numManifest++;
1251 if (si.isPinned()) numPinned++;
1252
1253 if (si.getBitmapPath() != null) {
1254 numBitmaps++;
1255 totalBitmapSize += new File(si.getBitmapPath()).length();
1256 }
1257 }
1258
1259 result.put(KEY_DYNAMIC, numDynamic);
1260 result.put(KEY_MANIFEST, numManifest);
1261 result.put(KEY_PINNED, numPinned);
1262 result.put(KEY_BITMAPS, numBitmaps);
1263 result.put(KEY_BITMAP_BYTES, totalBitmapSize);
1264
1265 // TODO Log update frequency too.
1266
1267 return result;
1268 }
1269
1270 @Override
Makoto Onuki0acbb142016-03-22 17:02:57 -07001271 public void saveToXml(@NonNull XmlSerializer out, boolean forBackup)
1272 throws IOException, XmlPullParserException {
Makoto Onuki31459242016-03-22 11:12:18 -07001273 final int size = mShortcuts.size();
1274
1275 if (size == 0 && mApiCallCount == 0) {
1276 return; // nothing to write.
1277 }
1278
1279 out.startTag(null, TAG_ROOT);
1280
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001281 ShortcutService.writeAttr(out, ATTR_NAME, getPackageName());
Makoto Onuki31459242016-03-22 11:12:18 -07001282 ShortcutService.writeAttr(out, ATTR_CALL_COUNT, mApiCallCount);
1283 ShortcutService.writeAttr(out, ATTR_LAST_RESET, mLastResetTime);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001284 getPackageInfo().saveToXml(out);
Makoto Onuki31459242016-03-22 11:12:18 -07001285
1286 for (int j = 0; j < size; j++) {
Makoto Onuki0acbb142016-03-22 17:02:57 -07001287 saveShortcut(out, mShortcuts.valueAt(j), forBackup);
Makoto Onuki31459242016-03-22 11:12:18 -07001288 }
1289
1290 out.endTag(null, TAG_ROOT);
1291 }
1292
Makoto Onuki0acbb142016-03-22 17:02:57 -07001293 private static void saveShortcut(XmlSerializer out, ShortcutInfo si, boolean forBackup)
Makoto Onuki31459242016-03-22 11:12:18 -07001294 throws IOException, XmlPullParserException {
Makoto Onuki0acbb142016-03-22 17:02:57 -07001295 if (forBackup) {
Makoto Onukif3ba2e02016-07-12 09:18:50 -07001296 if (!(si.isPinned() && si.isEnabled())) {
1297 return; // We only backup pinned shortcuts that are enabled.
Makoto Onuki0acbb142016-03-22 17:02:57 -07001298 }
1299 }
Makoto Onuki31459242016-03-22 11:12:18 -07001300 out.startTag(null, TAG_SHORTCUT);
1301 ShortcutService.writeAttr(out, ATTR_ID, si.getId());
1302 // writeAttr(out, "package", si.getPackageName()); // not needed
Makoto Onuki22fcc682016-05-17 14:52:19 -07001303 ShortcutService.writeAttr(out, ATTR_ACTIVITY, si.getActivity());
Makoto Onuki31459242016-03-22 11:12:18 -07001304 // writeAttr(out, "icon", si.getIcon()); // We don't save it.
1305 ShortcutService.writeAttr(out, ATTR_TITLE, si.getTitle());
Makoto Onuki20c95f82016-05-11 16:51:01 -07001306 ShortcutService.writeAttr(out, ATTR_TITLE_RES_ID, si.getTitleResId());
Makoto Onuki157b1622016-06-02 16:13:10 -07001307 ShortcutService.writeAttr(out, ATTR_TITLE_RES_NAME, si.getTitleResName());
Makoto Onukie3ae7ec2016-03-29 15:45:25 -07001308 ShortcutService.writeAttr(out, ATTR_TEXT, si.getText());
Makoto Onuki20c95f82016-05-11 16:51:01 -07001309 ShortcutService.writeAttr(out, ATTR_TEXT_RES_ID, si.getTextResId());
Makoto Onuki157b1622016-06-02 16:13:10 -07001310 ShortcutService.writeAttr(out, ATTR_TEXT_RES_NAME, si.getTextResName());
Makoto Onuki20c95f82016-05-11 16:51:01 -07001311 ShortcutService.writeAttr(out, ATTR_DISABLED_MESSAGE, si.getDisabledMessage());
Makoto Onukieddbfec2016-05-31 17:04:34 -07001312 ShortcutService.writeAttr(out, ATTR_DISABLED_MESSAGE_RES_ID,
1313 si.getDisabledMessageResourceId());
Makoto Onuki157b1622016-06-02 16:13:10 -07001314 ShortcutService.writeAttr(out, ATTR_DISABLED_MESSAGE_RES_NAME,
1315 si.getDisabledMessageResName());
Makoto Onuki31459242016-03-22 11:12:18 -07001316 ShortcutService.writeAttr(out, ATTR_TIMESTAMP,
1317 si.getLastChangedTimestamp());
Makoto Onuki0acbb142016-03-22 17:02:57 -07001318 if (forBackup) {
1319 // Don't write icon information. Also drop the dynamic flag.
1320 ShortcutService.writeAttr(out, ATTR_FLAGS,
1321 si.getFlags() &
1322 ~(ShortcutInfo.FLAG_HAS_ICON_FILE | ShortcutInfo.FLAG_HAS_ICON_RES
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -08001323 | ShortcutInfo.FLAG_DYNAMIC | ShortcutInfo.FLAG_CHOOSER));
Makoto Onuki0acbb142016-03-22 17:02:57 -07001324 } else {
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001325 // When writing for backup, ranks shouldn't be saved, since shortcuts won't be restored
1326 // as dynamic.
1327 ShortcutService.writeAttr(out, ATTR_RANK, si.getRank());
1328
Makoto Onuki0acbb142016-03-22 17:02:57 -07001329 ShortcutService.writeAttr(out, ATTR_FLAGS, si.getFlags());
Makoto Onuki157b1622016-06-02 16:13:10 -07001330 ShortcutService.writeAttr(out, ATTR_ICON_RES_ID, si.getIconResourceId());
1331 ShortcutService.writeAttr(out, ATTR_ICON_RES_NAME, si.getIconResName());
Makoto Onuki0acbb142016-03-22 17:02:57 -07001332 ShortcutService.writeAttr(out, ATTR_BITMAP_PATH, si.getBitmapPath());
1333 }
Makoto Onuki31459242016-03-22 11:12:18 -07001334
Makoto Onukib6d35232016-04-04 15:57:17 -07001335 {
Makoto Onukibe73a802016-04-15 14:46:35 -07001336 final Set<String> cat = si.getCategories();
Makoto Onukib6d35232016-04-04 15:57:17 -07001337 if (cat != null && cat.size() > 0) {
1338 out.startTag(null, TAG_CATEGORIES);
1339 XmlUtils.writeStringArrayXml(cat.toArray(new String[cat.size()]),
1340 NAME_CATEGORIES, out);
1341 out.endTag(null, TAG_CATEGORIES);
1342 }
1343 }
Makoto Onuki440a1ea2016-07-20 14:21:18 -07001344 final Intent[] intentsNoExtras = si.getIntentsNoExtras();
1345 final PersistableBundle[] intentsExtras = si.getIntentPersistableExtrases();
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -08001346 if (intentsNoExtras != null) {
1347 final int numIntents = intentsNoExtras.length;
1348 for (int i = 0; i < numIntents; i++) {
1349 out.startTag(null, TAG_INTENT);
1350 ShortcutService.writeAttr(out, ATTR_INTENT_NO_EXTRA, intentsNoExtras[i]);
1351 ShortcutService.writeTagExtra(out, TAG_EXTRAS, intentsExtras[i]);
1352 out.endTag(null, TAG_INTENT);
1353 }
1354 }
1355 ShortcutService.writeTagExtra(out, TAG_EXTRAS, si.getExtras());
1356
1357 ShortcutService.writeTagExtra(out, TAG_CHOOSER_EXTRAS, si.getChooserExtras());
1358
1359 final IntentFilter[] intentFilters = si.getChooserIntentFilters();
1360 if (intentFilters != null) {
1361 for (int i = 0; i < intentFilters.length; i++) {
1362 out.startTag(null, TAG_CHOOSER_INTENT_FILTERS);
1363 intentFilters[i].writeToXml(out);
1364 out.endTag(null, TAG_CHOOSER_INTENT_FILTERS);
1365 }
Makoto Onuki440a1ea2016-07-20 14:21:18 -07001366 }
Makoto Onukib6d35232016-04-04 15:57:17 -07001367
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -08001368 final ComponentName[] componentNames = si.getChooserComponentNames();
1369 if (componentNames != null) {
1370 for (int i = 0; i < componentNames.length; i++) {
1371 out.startTag(null, TAG_CHOOSER_COMPONENT_NAMES);
1372 ShortcutService.writeAttr(out, ATTR_COMPONENT_NAMES, componentNames[i]);
1373 out.endTag(null, TAG_CHOOSER_COMPONENT_NAMES);
1374 }
1375 }
Makoto Onuki31459242016-03-22 11:12:18 -07001376
1377 out.endTag(null, TAG_SHORTCUT);
1378 }
1379
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001380 public static ShortcutPackage loadFromXml(ShortcutService s, ShortcutUser shortcutUser,
1381 XmlPullParser parser, boolean fromBackup)
Makoto Onuki31459242016-03-22 11:12:18 -07001382 throws IOException, XmlPullParserException {
1383
1384 final String packageName = ShortcutService.parseStringAttribute(parser,
1385 ATTR_NAME);
1386
Makoto Onukic51b2872016-05-04 15:24:50 -07001387 final ShortcutPackage ret = new ShortcutPackage(shortcutUser,
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001388 shortcutUser.getUserId(), packageName);
Makoto Onuki31459242016-03-22 11:12:18 -07001389
Makoto Onuki31459242016-03-22 11:12:18 -07001390 ret.mApiCallCount =
1391 ShortcutService.parseIntAttribute(parser, ATTR_CALL_COUNT);
1392 ret.mLastResetTime =
1393 ShortcutService.parseLongAttribute(parser, ATTR_LAST_RESET);
1394
1395 final int outerDepth = parser.getDepth();
1396 int type;
1397 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1398 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1399 if (type != XmlPullParser.START_TAG) {
1400 continue;
1401 }
1402 final int depth = parser.getDepth();
1403 final String tag = parser.getName();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001404 if (depth == outerDepth + 1) {
1405 switch (tag) {
1406 case ShortcutPackageInfo.TAG_ROOT:
Makoto Onuki2e210c42016-03-30 08:30:36 -07001407 ret.getPackageInfo().loadFromXml(parser, fromBackup);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001408 continue;
1409 case TAG_SHORTCUT:
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001410 final ShortcutInfo si = parseShortcut(parser, packageName,
1411 shortcutUser.getUserId());
Makoto Onuki31459242016-03-22 11:12:18 -07001412
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001413 // Don't use addShortcut(), we don't need to save the icon.
1414 ret.mShortcuts.put(si.getId(), si);
1415 continue;
1416 }
Makoto Onuki31459242016-03-22 11:12:18 -07001417 }
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001418 ShortcutService.warnForInvalidTag(depth, tag);
1419 }
Makoto Onuki31459242016-03-22 11:12:18 -07001420 return ret;
1421 }
1422
Makoto Onukiabe84422016-04-07 09:41:19 -07001423 private static ShortcutInfo parseShortcut(XmlPullParser parser, String packageName,
1424 @UserIdInt int userId) throws IOException, XmlPullParserException {
Makoto Onuki31459242016-03-22 11:12:18 -07001425 String id;
1426 ComponentName activityComponent;
1427 // Icon icon;
1428 String title;
Makoto Onuki20c95f82016-05-11 16:51:01 -07001429 int titleResId;
Makoto Onuki157b1622016-06-02 16:13:10 -07001430 String titleResName;
Makoto Onukie3ae7ec2016-03-29 15:45:25 -07001431 String text;
Makoto Onuki20c95f82016-05-11 16:51:01 -07001432 int textResId;
Makoto Onuki157b1622016-06-02 16:13:10 -07001433 String textResName;
Makoto Onuki20c95f82016-05-11 16:51:01 -07001434 String disabledMessage;
1435 int disabledMessageResId;
Makoto Onuki157b1622016-06-02 16:13:10 -07001436 String disabledMessageResName;
Makoto Onuki440a1ea2016-07-20 14:21:18 -07001437 Intent intentLegacy;
1438 PersistableBundle intentPersistableExtrasLegacy = null;
1439 ArrayList<Intent> intents = new ArrayList<>();
Makoto Onuki20c95f82016-05-11 16:51:01 -07001440 int rank;
Makoto Onuki31459242016-03-22 11:12:18 -07001441 PersistableBundle extras = null;
1442 long lastChangedTimestamp;
1443 int flags;
Makoto Onuki157b1622016-06-02 16:13:10 -07001444 int iconResId;
1445 String iconResName;
Makoto Onuki31459242016-03-22 11:12:18 -07001446 String bitmapPath;
Makoto Onukibe73a802016-04-15 14:46:35 -07001447 ArraySet<String> categories = null;
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -08001448 PersistableBundle chooserExtras;
1449 List<IntentFilter> chooserIntentFilters = new ArrayList<>();
1450 List<ComponentName> chooserComponentNames = new ArrayList<>();
Makoto Onuki31459242016-03-22 11:12:18 -07001451
1452 id = ShortcutService.parseStringAttribute(parser, ATTR_ID);
1453 activityComponent = ShortcutService.parseComponentNameAttribute(parser,
1454 ATTR_ACTIVITY);
1455 title = ShortcutService.parseStringAttribute(parser, ATTR_TITLE);
Makoto Onuki20c95f82016-05-11 16:51:01 -07001456 titleResId = ShortcutService.parseIntAttribute(parser, ATTR_TITLE_RES_ID);
Makoto Onuki157b1622016-06-02 16:13:10 -07001457 titleResName = ShortcutService.parseStringAttribute(parser, ATTR_TITLE_RES_NAME);
Makoto Onukie3ae7ec2016-03-29 15:45:25 -07001458 text = ShortcutService.parseStringAttribute(parser, ATTR_TEXT);
Makoto Onuki20c95f82016-05-11 16:51:01 -07001459 textResId = ShortcutService.parseIntAttribute(parser, ATTR_TEXT_RES_ID);
Makoto Onuki157b1622016-06-02 16:13:10 -07001460 textResName = ShortcutService.parseStringAttribute(parser, ATTR_TEXT_RES_NAME);
Makoto Onuki20c95f82016-05-11 16:51:01 -07001461 disabledMessage = ShortcutService.parseStringAttribute(parser, ATTR_DISABLED_MESSAGE);
1462 disabledMessageResId = ShortcutService.parseIntAttribute(parser,
1463 ATTR_DISABLED_MESSAGE_RES_ID);
Makoto Onuki157b1622016-06-02 16:13:10 -07001464 disabledMessageResName = ShortcutService.parseStringAttribute(parser,
1465 ATTR_DISABLED_MESSAGE_RES_NAME);
Makoto Onuki440a1ea2016-07-20 14:21:18 -07001466 intentLegacy = ShortcutService.parseIntentAttributeNoDefault(parser, ATTR_INTENT_LEGACY);
Makoto Onuki20c95f82016-05-11 16:51:01 -07001467 rank = (int) ShortcutService.parseLongAttribute(parser, ATTR_RANK);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001468 lastChangedTimestamp = ShortcutService.parseLongAttribute(parser, ATTR_TIMESTAMP);
Makoto Onuki31459242016-03-22 11:12:18 -07001469 flags = (int) ShortcutService.parseLongAttribute(parser, ATTR_FLAGS);
Makoto Onuki157b1622016-06-02 16:13:10 -07001470 iconResId = (int) ShortcutService.parseLongAttribute(parser, ATTR_ICON_RES_ID);
1471 iconResName = ShortcutService.parseStringAttribute(parser, ATTR_ICON_RES_NAME);
Makoto Onuki31459242016-03-22 11:12:18 -07001472 bitmapPath = ShortcutService.parseStringAttribute(parser, ATTR_BITMAP_PATH);
1473
1474 final int outerDepth = parser.getDepth();
1475 int type;
1476 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1477 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1478 if (type != XmlPullParser.START_TAG) {
1479 continue;
1480 }
1481 final int depth = parser.getDepth();
1482 final String tag = parser.getName();
1483 if (ShortcutService.DEBUG_LOAD) {
1484 Slog.d(TAG, String.format(" depth=%d type=%d name=%s",
1485 depth, type, tag));
1486 }
1487 switch (tag) {
Makoto Onuki440a1ea2016-07-20 14:21:18 -07001488 case TAG_INTENT_EXTRAS_LEGACY:
1489 intentPersistableExtrasLegacy = PersistableBundle.restoreFromXml(parser);
1490 continue;
1491 case TAG_INTENT:
1492 intents.add(parseIntent(parser));
Makoto Onuki31459242016-03-22 11:12:18 -07001493 continue;
1494 case TAG_EXTRAS:
1495 extras = PersistableBundle.restoreFromXml(parser);
1496 continue;
Makoto Onukib6d35232016-04-04 15:57:17 -07001497 case TAG_CATEGORIES:
1498 // This just contains string-array.
1499 continue;
1500 case TAG_STRING_ARRAY_XMLUTILS:
1501 if (NAME_CATEGORIES.equals(ShortcutService.parseStringAttribute(parser,
1502 ATTR_NAME_XMLUTILS))) {
Makoto Onukibe73a802016-04-15 14:46:35 -07001503 final String[] ar = XmlUtils.readThisStringArrayXml(
1504 parser, TAG_STRING_ARRAY_XMLUTILS, null);
1505 categories = new ArraySet<>(ar.length);
1506 for (int i = 0; i < ar.length; i++) {
1507 categories.add(ar[i]);
1508 }
Makoto Onukib6d35232016-04-04 15:57:17 -07001509 }
1510 continue;
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -08001511 case TAG_CHOOSER_EXTRAS:
1512 chooserExtras = PersistableBundle.restoreFromXml(parser);
1513 continue;
1514 case TAG_CHOOSER_COMPONENT_NAMES:
1515 chooserComponentNames.add(ShortcutService.parseComponentNameAttribute(parser,
1516 ATTR_ACTIVITY));
1517 continue;
1518 case TAG_CHOOSER_INTENT_FILTERS:
1519 IntentFilter toAdd = new IntentFilter();
1520 toAdd.readFromXml(parser);
1521 chooserIntentFilters.add(toAdd);
1522 continue;
Makoto Onuki31459242016-03-22 11:12:18 -07001523 }
1524 throw ShortcutService.throwForInvalidTag(depth, tag);
1525 }
Makoto Onukibe73a802016-04-15 14:46:35 -07001526
Makoto Onuki440a1ea2016-07-20 14:21:18 -07001527 if (intentLegacy != null) {
1528 // For the legacy file format which supported only one intent per shortcut.
1529 ShortcutInfo.setIntentExtras(intentLegacy, intentPersistableExtrasLegacy);
1530 intents.clear();
1531 intents.add(intentLegacy);
1532 }
Makoto Onuki9fd90192017-01-06 18:31:03 +00001533
Makoto Onuki31459242016-03-22 11:12:18 -07001534 return new ShortcutInfo(
Makoto Onuki20c95f82016-05-11 16:51:01 -07001535 userId, id, packageName, activityComponent, /* icon =*/ null,
Makoto Onuki157b1622016-06-02 16:13:10 -07001536 title, titleResId, titleResName, text, textResId, textResName,
1537 disabledMessage, disabledMessageResId, disabledMessageResName,
Makoto Onuki440a1ea2016-07-20 14:21:18 -07001538 categories,
1539 intents.toArray(new Intent[intents.size()]),
1540 rank, extras, lastChangedTimestamp, flags,
Makoto Onuki157b1622016-06-02 16:13:10 -07001541 iconResId, iconResName, bitmapPath);
Makoto Onuki31459242016-03-22 11:12:18 -07001542 }
Makoto Onuki2e210c42016-03-30 08:30:36 -07001543
Makoto Onuki440a1ea2016-07-20 14:21:18 -07001544 private static Intent parseIntent(XmlPullParser parser)
1545 throws IOException, XmlPullParserException {
1546
1547 Intent intent = ShortcutService.parseIntentAttribute(parser,
1548 ATTR_INTENT_NO_EXTRA);
1549
1550 final int outerDepth = parser.getDepth();
1551 int type;
1552 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1553 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1554 if (type != XmlPullParser.START_TAG) {
1555 continue;
1556 }
1557 final int depth = parser.getDepth();
1558 final String tag = parser.getName();
1559 if (ShortcutService.DEBUG_LOAD) {
1560 Slog.d(TAG, String.format(" depth=%d type=%d name=%s",
1561 depth, type, tag));
1562 }
1563 switch (tag) {
1564 case TAG_EXTRAS:
1565 ShortcutInfo.setIntentExtras(intent,
1566 PersistableBundle.restoreFromXml(parser));
1567 continue;
1568 }
1569 throw ShortcutService.throwForInvalidTag(depth, tag);
1570 }
1571 return intent;
1572 }
1573
Makoto Onuki2e210c42016-03-30 08:30:36 -07001574 @VisibleForTesting
1575 List<ShortcutInfo> getAllShortcutsForTest() {
1576 return new ArrayList<>(mShortcuts.values());
1577 }
Makoto Onuki7001a612016-05-27 13:24:28 -07001578
1579 @Override
1580 public void verifyStates() {
1581 super.verifyStates();
1582
1583 boolean failed = false;
1584
Makoto Onuki255461f2017-01-10 11:47:25 -08001585 final ShortcutService s = mShortcutUser.mService;
1586
Makoto Onuki7001a612016-05-27 13:24:28 -07001587 final ArrayMap<ComponentName, ArrayList<ShortcutInfo>> all =
1588 sortShortcutsToActivities();
1589
1590 // Make sure each activity won't have more than max shortcuts.
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001591 for (int outer = all.size() - 1; outer >= 0; outer--) {
1592 final ArrayList<ShortcutInfo> list = all.valueAt(outer);
1593 if (list.size() > mShortcutUser.mService.getMaxActivityShortcuts()) {
Makoto Onuki7001a612016-05-27 13:24:28 -07001594 failed = true;
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001595 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": activity " + all.keyAt(outer)
1596 + " has " + all.valueAt(outer).size() + " shortcuts.");
Makoto Onuki7001a612016-05-27 13:24:28 -07001597 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001598
1599 // Sort by rank.
1600 Collections.sort(list, (a, b) -> Integer.compare(a.getRank(), b.getRank()));
1601
1602 // Split into two arrays for each kind.
1603 final ArrayList<ShortcutInfo> dynamicList = new ArrayList<>(list);
1604 dynamicList.removeIf((si) -> !si.isDynamic());
1605
1606 final ArrayList<ShortcutInfo> manifestList = new ArrayList<>(list);
1607 dynamicList.removeIf((si) -> !si.isManifestShortcut());
1608
1609 verifyRanksSequential(dynamicList);
1610 verifyRanksSequential(manifestList);
Makoto Onuki7001a612016-05-27 13:24:28 -07001611 }
1612
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001613 // Verify each shortcut's status.
Makoto Onuki7001a612016-05-27 13:24:28 -07001614 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1615 final ShortcutInfo si = mShortcuts.valueAt(i);
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -08001616 if (!(si.isDeclaredInManifest() || si.isDynamicOrChooser() || si.isPinned())) {
Makoto Onuki7001a612016-05-27 13:24:28 -07001617 failed = true;
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001618 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -08001619 + " is not manifest, dynamic, chooser or pinned.");
Makoto Onuki7001a612016-05-27 13:24:28 -07001620 }
Makoto Onukiff14f732016-06-30 17:07:25 -07001621 if (si.isDeclaredInManifest() && si.isDynamic()) {
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001622 failed = true;
1623 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1624 + " is both dynamic and manifest at the same time.");
1625 }
Makoto Onuki255461f2017-01-10 11:47:25 -08001626 if (si.getActivity() == null && !si.isFloating()) {
Makoto Onuki7001a612016-05-27 13:24:28 -07001627 failed = true;
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001628 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
Makoto Onuki255461f2017-01-10 11:47:25 -08001629 + " has null activity, but not floating.");
Makoto Onuki7001a612016-05-27 13:24:28 -07001630 }
Makoto Onuki9fd90192017-01-06 18:31:03 +00001631 if ((si.isDynamic() || si.isManifestShortcut()) && !si.isEnabled()) {
Makoto Onuki7001a612016-05-27 13:24:28 -07001632 failed = true;
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001633 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
Makoto Onuki7001a612016-05-27 13:24:28 -07001634 + " is not floating, but is disabled.");
1635 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001636 if (si.isFloating() && si.getRank() != 0) {
1637 failed = true;
1638 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1639 + " is floating, but has rank=" + si.getRank());
1640 }
Makoto Onukidd097812016-06-29 13:10:09 -07001641 if (si.getIcon() != null) {
1642 failed = true;
1643 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1644 + " still has an icon");
1645 }
Hyunyoung Songe4179e22017-03-01 12:51:26 -08001646 if (si.hasAdaptiveBitmap() && !si.hasIconFile()) {
Hyunyoung Songf281e7a2017-02-13 10:57:42 -08001647 failed = true;
1648 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
Hyunyoung Songe4179e22017-03-01 12:51:26 -08001649 + " has adaptive bitmap but was not saved to a file.");
Hyunyoung Songf281e7a2017-02-13 10:57:42 -08001650 }
Makoto Onukidd097812016-06-29 13:10:09 -07001651 if (si.hasIconFile() && si.hasIconResource()) {
1652 failed = true;
1653 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1654 + " has both resource and bitmap icons");
1655 }
Makoto Onuki255461f2017-01-10 11:47:25 -08001656 if (s.isDummyMainActivity(si.getActivity())) {
1657 failed = true;
1658 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1659 + " has a dummy target activity");
1660 }
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -08001661 if (si.getIntent() == null && !si.isChooser()) {
1662 failed = true;
1663 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1664 + " has a null intent, but is not a chooser");
1665 }
Makoto Onuki7001a612016-05-27 13:24:28 -07001666 }
1667
1668 if (failed) {
Makoto Onuki9fd90192017-01-06 18:31:03 +00001669 throw new IllegalStateException("See logcat for errors");
Makoto Onuki7001a612016-05-27 13:24:28 -07001670 }
1671 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001672
1673 private boolean verifyRanksSequential(List<ShortcutInfo> list) {
1674 boolean failed = false;
1675
1676 for (int i = 0; i < list.size(); i++) {
1677 final ShortcutInfo si = list.get(i);
1678 if (si.getRank() != i) {
1679 failed = true;
1680 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1681 + " rank=" + si.getRank() + " but expected to be "+ i);
1682 }
1683 }
1684 return failed;
1685 }
Makoto Onuki31459242016-03-22 11:12:18 -07001686}