blob: c37ceb3bc1b0a40caeffd5d80a9d534ba54053b1 [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;
Mehdi Alizadehebb4b602019-02-05 15:52:18 -080021import android.app.Person;
Makoto Onuki31459242016-03-22 11:12:18 -070022import android.content.ComponentName;
23import android.content.Intent;
Mehdi Alizadeh406e8b32018-12-11 18:21:49 -080024import android.content.IntentFilter;
Felipe Leme90205ef2019-03-05 09:59:52 -080025import android.content.LocusId;
Makoto Onuki22fcc682016-05-17 14:52:19 -070026import android.content.pm.PackageInfo;
Makoto Onuki31459242016-03-22 11:12:18 -070027import android.content.pm.ShortcutInfo;
Mehdi Alizadeh406e8b32018-12-11 18:21:49 -080028import android.content.pm.ShortcutManager;
Makoto Onuki157b1622016-06-02 16:13:10 -070029import android.content.res.Resources;
Makoto Onuki31459242016-03-22 11:12:18 -070030import android.os.PersistableBundle;
31import android.text.format.Formatter;
32import android.util.ArrayMap;
33import android.util.ArraySet;
Makoto Onuki7001a612016-05-27 13:24:28 -070034import android.util.Log;
Makoto Onuki31459242016-03-22 11:12:18 -070035import android.util.Slog;
36
Makoto Onuki2e210c42016-03-30 08:30:36 -070037import com.android.internal.annotations.VisibleForTesting;
Mehdi Alizadehebb4b602019-02-05 15:52:18 -080038import com.android.internal.util.ArrayUtils;
Makoto Onuki22fcc682016-05-17 14:52:19 -070039import com.android.internal.util.Preconditions;
Makoto Onukib6d35232016-04-04 15:57:17 -070040import com.android.internal.util.XmlUtils;
Makoto Onuki20b82212017-10-04 15:03:50 -070041import com.android.server.pm.ShortcutService.DumpFilter;
Makoto Onuki7001a612016-05-27 13:24:28 -070042import com.android.server.pm.ShortcutService.ShortcutOperation;
Makoto Onuki4e6cef42016-07-13 16:14:01 -070043import com.android.server.pm.ShortcutService.Stats;
Makoto Onuki2e210c42016-03-30 08:30:36 -070044
Makoto Onuki76269922016-07-15 14:58:54 -070045import org.json.JSONException;
46import org.json.JSONObject;
Makoto Onuki31459242016-03-22 11:12:18 -070047import org.xmlpull.v1.XmlPullParser;
48import org.xmlpull.v1.XmlPullParserException;
49import org.xmlpull.v1.XmlSerializer;
50
51import java.io.File;
52import java.io.IOException;
53import java.io.PrintWriter;
54import java.util.ArrayList;
Makoto Onuki7001a612016-05-27 13:24:28 -070055import java.util.Collections;
56import java.util.Comparator;
Makoto Onuki31459242016-03-22 11:12:18 -070057import java.util.List;
Daulet Zhanguzin82adfcb2020-01-02 17:31:40 +000058import java.util.Objects;
Makoto Onukibe73a802016-04-15 14:46:35 -070059import java.util.Set;
Makoto Onuki31459242016-03-22 11:12:18 -070060import java.util.function.Predicate;
61
62/**
63 * Package information used by {@link ShortcutService}.
Makoto Onuki22fcc682016-05-17 14:52:19 -070064 * User information used by {@link ShortcutService}.
65 *
66 * All methods should be guarded by {@code #mShortcutUser.mService.mLock}.
Makoto Onuki31459242016-03-22 11:12:18 -070067 */
Makoto Onuki9da23fc2016-03-29 11:14:42 -070068class ShortcutPackage extends ShortcutPackageItem {
Makoto Onuki31459242016-03-22 11:12:18 -070069 private static final String TAG = ShortcutService.TAG;
Makoto Onuki9e1f5592016-06-08 12:30:23 -070070 private static final String TAG_VERIFY = ShortcutService.TAG + ".verify";
Makoto Onuki31459242016-03-22 11:12:18 -070071
72 static final String TAG_ROOT = "package";
Makoto Onuki440a1ea2016-07-20 14:21:18 -070073 private static final String TAG_INTENT_EXTRAS_LEGACY = "intent-extras";
74 private static final String TAG_INTENT = "intent";
Makoto Onuki31459242016-03-22 11:12:18 -070075 private static final String TAG_EXTRAS = "extras";
76 private static final String TAG_SHORTCUT = "shortcut";
Mehdi Alizadehabec3192019-06-27 18:06:15 -070077 private static final String TAG_SHARE_TARGET = "share-target";
Makoto Onukib6d35232016-04-04 15:57:17 -070078 private static final String TAG_CATEGORIES = "categories";
Mehdi Alizadehebb4b602019-02-05 15:52:18 -080079 private static final String TAG_PERSON = "person";
Makoto Onuki31459242016-03-22 11:12:18 -070080
81 private static final String ATTR_NAME = "name";
Makoto Onuki31459242016-03-22 11:12:18 -070082 private static final String ATTR_CALL_COUNT = "call-count";
83 private static final String ATTR_LAST_RESET = "last-reset";
84 private static final String ATTR_ID = "id";
85 private static final String ATTR_ACTIVITY = "activity";
86 private static final String ATTR_TITLE = "title";
Makoto Onuki20c95f82016-05-11 16:51:01 -070087 private static final String ATTR_TITLE_RES_ID = "titleid";
Makoto Onuki157b1622016-06-02 16:13:10 -070088 private static final String ATTR_TITLE_RES_NAME = "titlename";
Makoto Onukie3ae7ec2016-03-29 15:45:25 -070089 private static final String ATTR_TEXT = "text";
Makoto Onuki20c95f82016-05-11 16:51:01 -070090 private static final String ATTR_TEXT_RES_ID = "textid";
Makoto Onuki157b1622016-06-02 16:13:10 -070091 private static final String ATTR_TEXT_RES_NAME = "textname";
Makoto Onuki20c95f82016-05-11 16:51:01 -070092 private static final String ATTR_DISABLED_MESSAGE = "dmessage";
93 private static final String ATTR_DISABLED_MESSAGE_RES_ID = "dmessageid";
Makoto Onuki157b1622016-06-02 16:13:10 -070094 private static final String ATTR_DISABLED_MESSAGE_RES_NAME = "dmessagename";
Makoto Onukia4f89b12017-10-05 10:37:55 -070095 private static final String ATTR_DISABLED_REASON = "disabled-reason";
Makoto Onuki440a1ea2016-07-20 14:21:18 -070096 private static final String ATTR_INTENT_LEGACY = "intent";
97 private static final String ATTR_INTENT_NO_EXTRA = "intent-base";
Makoto Onuki20c95f82016-05-11 16:51:01 -070098 private static final String ATTR_RANK = "rank";
Makoto Onuki31459242016-03-22 11:12:18 -070099 private static final String ATTR_TIMESTAMP = "timestamp";
100 private static final String ATTR_FLAGS = "flags";
Makoto Onuki157b1622016-06-02 16:13:10 -0700101 private static final String ATTR_ICON_RES_ID = "icon-res";
102 private static final String ATTR_ICON_RES_NAME = "icon-resname";
Makoto Onuki31459242016-03-22 11:12:18 -0700103 private static final String ATTR_BITMAP_PATH = "bitmap-path";
Adam Hed4586b12019-03-19 12:01:00 -0700104 private static final String ATTR_LOCUS_ID = "locus-id";
Makoto Onuki31459242016-03-22 11:12:18 -0700105
Mehdi Alizadehebb4b602019-02-05 15:52:18 -0800106 private static final String ATTR_PERSON_NAME = "name";
107 private static final String ATTR_PERSON_URI = "uri";
108 private static final String ATTR_PERSON_KEY = "key";
109 private static final String ATTR_PERSON_IS_BOT = "is-bot";
110 private static final String ATTR_PERSON_IS_IMPORTANT = "is-important";
111
Makoto Onukib6d35232016-04-04 15:57:17 -0700112 private static final String NAME_CATEGORIES = "categories";
113
114 private static final String TAG_STRING_ARRAY_XMLUTILS = "string-array";
115 private static final String ATTR_NAME_XMLUTILS = "name";
116
Makoto Onuki76269922016-07-15 14:58:54 -0700117 private static final String KEY_DYNAMIC = "dynamic";
118 private static final String KEY_MANIFEST = "manifest";
119 private static final String KEY_PINNED = "pinned";
120 private static final String KEY_BITMAPS = "bitmaps";
121 private static final String KEY_BITMAP_BYTES = "bitmapBytes";
122
Makoto Onuki31459242016-03-22 11:12:18 -0700123 /**
124 * All the shortcuts from the package, keyed on IDs.
125 */
126 final private ArrayMap<String, ShortcutInfo> mShortcuts = new ArrayMap<>();
127
128 /**
Mehdi Alizadeh32774622018-11-05 17:32:01 -0800129 * All the share targets from the package
130 */
131 private final ArrayList<ShareTargetInfo> mShareTargets = new ArrayList<>(0);
132
133 /**
Makoto Onuki31459242016-03-22 11:12:18 -0700134 * # of times the package has called rate-limited APIs.
135 */
136 private int mApiCallCount;
137
138 /**
139 * When {@link #mApiCallCount} was reset last time.
140 */
141 private long mLastResetTime;
142
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700143 private final int mPackageUid;
144
145 private long mLastKnownForegroundElapsedTime;
146
Makoto Onukic51b2872016-05-04 15:24:50 -0700147 private ShortcutPackage(ShortcutUser shortcutUser,
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700148 int packageUserId, String packageName, ShortcutPackageInfo spi) {
149 super(shortcutUser, packageUserId, packageName,
150 spi != null ? spi : ShortcutPackageInfo.newEmpty());
151
Makoto Onukic51b2872016-05-04 15:24:50 -0700152 mPackageUid = shortcutUser.mService.injectGetPackageUid(packageName, packageUserId);
Makoto Onuki31459242016-03-22 11:12:18 -0700153 }
154
Makoto Onukic51b2872016-05-04 15:24:50 -0700155 public ShortcutPackage(ShortcutUser shortcutUser, int packageUserId, String packageName) {
156 this(shortcutUser, packageUserId, packageName, null);
Makoto Onuki0acbb142016-03-22 17:02:57 -0700157 }
158
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700159 @Override
160 public int getOwnerUserId() {
161 // For packages, always owner user == package user.
162 return getPackageUserId();
Makoto Onuki0acbb142016-03-22 17:02:57 -0700163 }
164
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700165 public int getPackageUid() {
166 return mPackageUid;
167 }
168
Makoto Onuki157b1622016-06-02 16:13:10 -0700169 @Nullable
170 public Resources getPackageResources() {
171 return mShortcutUser.mService.injectGetResourcesForApplicationAsUser(
172 getPackageName(), getPackageUserId());
173 }
174
Makoto Onuki50a320e2017-05-31 14:38:42 -0700175 public int getShortcutCount() {
176 return mShortcuts.size();
177 }
178
Makoto Onuki2e210c42016-03-30 08:30:36 -0700179 @Override
Makoto Onukia4f89b12017-10-05 10:37:55 -0700180 protected boolean canRestoreAnyVersion() {
181 return false;
Makoto Onuki2e210c42016-03-30 08:30:36 -0700182 }
183
184 @Override
Makoto Onukia4f89b12017-10-05 10:37:55 -0700185 protected void onRestored(int restoreBlockReason) {
186 // Shortcuts have been restored.
187 // - Unshadow all shortcuts.
188 // - Set disabled reason.
189 // - Disable if needed.
190 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
191 ShortcutInfo si = mShortcuts.valueAt(i);
192 si.clearFlags(ShortcutInfo.FLAG_SHADOW);
193
194 si.setDisabledReason(restoreBlockReason);
195 if (restoreBlockReason != ShortcutInfo.DISABLED_REASON_NOT_DISABLED) {
196 si.addFlags(ShortcutInfo.FLAG_DISABLED);
197 }
198 }
Makoto Onuki2e210c42016-03-30 08:30:36 -0700199 // Because some launchers may not have been restored (e.g. allowBackup=false),
200 // we need to re-calculate the pinned shortcuts.
Makoto Onukic51b2872016-05-04 15:24:50 -0700201 refreshPinnedFlags();
Makoto Onuki2e210c42016-03-30 08:30:36 -0700202 }
203
Makoto Onukid99c6f02016-03-28 11:02:54 -0700204 /**
205 * Note this does *not* provide a correct view to the calling launcher.
206 */
Makoto Onuki31459242016-03-22 11:12:18 -0700207 @Nullable
208 public ShortcutInfo findShortcutById(String id) {
209 return mShortcuts.get(id);
210 }
211
Makoto Onukia4f89b12017-10-05 10:37:55 -0700212 public boolean isShortcutExistsAndInvisibleToPublisher(String id) {
213 ShortcutInfo si = findShortcutById(id);
214 return si != null && !si.isVisibleToPublisher();
215 }
216
217 public boolean isShortcutExistsAndVisibleToPublisher(String id) {
218 ShortcutInfo si = findShortcutById(id);
219 return si != null && si.isVisibleToPublisher();
220 }
221
222 private void ensureNotImmutable(@Nullable ShortcutInfo shortcut, boolean ignoreInvisible) {
223 if (shortcut != null && shortcut.isImmutable()
224 && (!ignoreInvisible || shortcut.isVisibleToPublisher())) {
Makoto Onuki22fcc682016-05-17 14:52:19 -0700225 throw new IllegalArgumentException(
226 "Manifest shortcut ID=" + shortcut.getId()
227 + " may not be manipulated via APIs");
228 }
229 }
230
Makoto Onukia4f89b12017-10-05 10:37:55 -0700231 public void ensureNotImmutable(@NonNull String id, boolean ignoreInvisible) {
232 ensureNotImmutable(mShortcuts.get(id), ignoreInvisible);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700233 }
234
Makoto Onukia4f89b12017-10-05 10:37:55 -0700235 public void ensureImmutableShortcutsNotIncludedWithIds(@NonNull List<String> shortcutIds,
236 boolean ignoreInvisible) {
Makoto Onuki22fcc682016-05-17 14:52:19 -0700237 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
Makoto Onukia4f89b12017-10-05 10:37:55 -0700238 ensureNotImmutable(shortcutIds.get(i), ignoreInvisible);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700239 }
240 }
241
Makoto Onukia4f89b12017-10-05 10:37:55 -0700242 public void ensureImmutableShortcutsNotIncluded(@NonNull List<ShortcutInfo> shortcuts,
243 boolean ignoreInvisible) {
Makoto Onuki22fcc682016-05-17 14:52:19 -0700244 for (int i = shortcuts.size() - 1; i >= 0; i--) {
Makoto Onukia4f89b12017-10-05 10:37:55 -0700245 ensureNotImmutable(shortcuts.get(i).getId(), ignoreInvisible);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700246 }
247 }
248
Makoto Onukia4f89b12017-10-05 10:37:55 -0700249 /**
250 * Delete a shortcut by ID. This will *always* remove it even if it's immutable or invisible.
251 */
252 private ShortcutInfo forceDeleteShortcutInner(@NonNull String id) {
Makoto Onuki31459242016-03-22 11:12:18 -0700253 final ShortcutInfo shortcut = mShortcuts.remove(id);
254 if (shortcut != null) {
Makoto Onuki475c3652017-05-08 14:29:03 -0700255 mShortcutUser.mService.removeIconLocked(shortcut);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700256 shortcut.clearFlags(ShortcutInfo.FLAG_DYNAMIC | ShortcutInfo.FLAG_PINNED
Makoto Onuki99302b52017-03-29 12:42:26 -0700257 | ShortcutInfo.FLAG_MANIFEST);
Makoto Onuki31459242016-03-22 11:12:18 -0700258 }
259 return shortcut;
260 }
261
Makoto Onukia4f89b12017-10-05 10:37:55 -0700262 /**
263 * Force replace a shortcut. If there's already a shortcut with the same ID, it'll be removed,
264 * even if it's invisible.
265 */
266 private void forceReplaceShortcutInner(@NonNull ShortcutInfo newShortcut) {
Makoto Onuki157b1622016-06-02 16:13:10 -0700267 final ShortcutService s = mShortcutUser.mService;
268
Makoto Onukia4f89b12017-10-05 10:37:55 -0700269 forceDeleteShortcutInner(newShortcut.getId());
Makoto Onuki157b1622016-06-02 16:13:10 -0700270
271 // Extract Icon and update the icon res ID and the bitmap path.
Makoto Onuki475c3652017-05-08 14:29:03 -0700272 s.saveIconAndFixUpShortcutLocked(newShortcut);
Makoto Onuki157b1622016-06-02 16:13:10 -0700273 s.fixUpShortcutResourceNamesAndValues(newShortcut);
Makoto Onuki31459242016-03-22 11:12:18 -0700274 mShortcuts.put(newShortcut.getId(), newShortcut);
275 }
276
277 /**
Makoto Onukia4f89b12017-10-05 10:37:55 -0700278 * Add a shortcut. If there's already a one with the same ID, it'll be removed, even if it's
279 * invisible.
Makoto Onuki31459242016-03-22 11:12:18 -0700280 *
281 * It checks the max number of dynamic shortcuts.
282 */
Makoto Onukia4f89b12017-10-05 10:37:55 -0700283 public void addOrReplaceDynamicShortcut(@NonNull ShortcutInfo newShortcut) {
Makoto Onuki39686e82016-04-13 18:03:00 -0700284
Makoto Onuki22fcc682016-05-17 14:52:19 -0700285 Preconditions.checkArgument(newShortcut.isEnabled(),
286 "add/setDynamicShortcuts() cannot publish disabled shortcuts");
287
Makoto Onuki99302b52017-03-29 12:42:26 -0700288 newShortcut.addFlags(ShortcutInfo.FLAG_DYNAMIC);
Makoto Onuki31459242016-03-22 11:12:18 -0700289
290 final ShortcutInfo oldShortcut = mShortcuts.get(newShortcut.getId());
291
292 final boolean wasPinned;
Makoto Onuki31459242016-03-22 11:12:18 -0700293
294 if (oldShortcut == null) {
295 wasPinned = false;
Makoto Onuki31459242016-03-22 11:12:18 -0700296 } else {
Makoto Onuki22fcc682016-05-17 14:52:19 -0700297 // It's an update case.
298 // Make sure the target is updatable. (i.e. should be mutable.)
Makoto Onukia4f89b12017-10-05 10:37:55 -0700299 oldShortcut.ensureUpdatableWith(newShortcut, /*isUpdating=*/ false);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700300
Makoto Onuki31459242016-03-22 11:12:18 -0700301 wasPinned = oldShortcut.isPinned();
Makoto Onuki31459242016-03-22 11:12:18 -0700302 }
303
Makoto Onuki157b1622016-06-02 16:13:10 -0700304 // If it was originally pinned, the new one should be pinned too.
Makoto Onuki31459242016-03-22 11:12:18 -0700305 if (wasPinned) {
306 newShortcut.addFlags(ShortcutInfo.FLAG_PINNED);
307 }
308
Makoto Onukia4f89b12017-10-05 10:37:55 -0700309 forceReplaceShortcutInner(newShortcut);
Makoto Onuki31459242016-03-22 11:12:18 -0700310 }
311
312 /**
Mehdi Alizadeh505fb762020-01-21 17:26:24 -0800313 * Remove all shortcuts that aren't pinned, cached nor dynamic.
Makoto Onuki31459242016-03-22 11:12:18 -0700314 */
Makoto Onukic51b2872016-05-04 15:24:50 -0700315 private void removeOrphans() {
Makoto Onuki31459242016-03-22 11:12:18 -0700316 ArrayList<String> removeList = null; // Lazily initialize.
317
318 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
319 final ShortcutInfo si = mShortcuts.valueAt(i);
320
Makoto Onuki22fcc682016-05-17 14:52:19 -0700321 if (si.isAlive()) continue;
Makoto Onuki31459242016-03-22 11:12:18 -0700322
323 if (removeList == null) {
324 removeList = new ArrayList<>();
325 }
326 removeList.add(si.getId());
327 }
328 if (removeList != null) {
329 for (int i = removeList.size() - 1; i >= 0; i--) {
Makoto Onukia4f89b12017-10-05 10:37:55 -0700330 forceDeleteShortcutInner(removeList.get(i));
Makoto Onuki31459242016-03-22 11:12:18 -0700331 }
332 }
333 }
334
335 /**
336 * Remove all dynamic shortcuts.
337 */
Makoto Onukia4f89b12017-10-05 10:37:55 -0700338 public void deleteAllDynamicShortcuts(boolean ignoreInvisible) {
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700339 final long now = mShortcutUser.mService.injectCurrentTimeMillis();
340
Makoto Onuki22fcc682016-05-17 14:52:19 -0700341 boolean changed = false;
Makoto Onuki31459242016-03-22 11:12:18 -0700342 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
Makoto Onuki22fcc682016-05-17 14:52:19 -0700343 final ShortcutInfo si = mShortcuts.valueAt(i);
Makoto Onukia4f89b12017-10-05 10:37:55 -0700344 if (si.isDynamic() && (!ignoreInvisible || si.isVisibleToPublisher())) {
Makoto Onuki22fcc682016-05-17 14:52:19 -0700345 changed = true;
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700346
347 si.setTimestamp(now);
Makoto Onuki99302b52017-03-29 12:42:26 -0700348 si.clearFlags(ShortcutInfo.FLAG_DYNAMIC);
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700349 si.setRank(0); // It may still be pinned, so clear the rank.
Makoto Onuki22fcc682016-05-17 14:52:19 -0700350 }
Makoto Onuki31459242016-03-22 11:12:18 -0700351 }
Makoto Onuki22fcc682016-05-17 14:52:19 -0700352 if (changed) {
353 removeOrphans();
354 }
Makoto Onuki31459242016-03-22 11:12:18 -0700355 }
356
357 /**
Makoto Onuki7001a612016-05-27 13:24:28 -0700358 * Remove a dynamic shortcut by ID. It'll be removed from the dynamic set, but if the shortcut
Mehdi Alizadeh505fb762020-01-21 17:26:24 -0800359 * is pinned or cached, it'll remain as a pinned or cached shortcut, and is still enabled.
Makoto Onukib08790c2016-06-23 14:05:46 -0700360 *
Mehdi Alizadeh505fb762020-01-21 17:26:24 -0800361 * @return true if it's removed, or false if it was not actually removed because it is either
362 * pinned or cached.
Makoto Onuki31459242016-03-22 11:12:18 -0700363 */
Makoto Onukia4f89b12017-10-05 10:37:55 -0700364 public boolean deleteDynamicWithId(@NonNull String shortcutId, boolean ignoreInvisible) {
Makoto Onukib08790c2016-06-23 14:05:46 -0700365 final ShortcutInfo removed = deleteOrDisableWithId(
Makoto Onukia4f89b12017-10-05 10:37:55 -0700366 shortcutId, /* disable =*/ false, /* overrideImmutable=*/ false, ignoreInvisible,
367 ShortcutInfo.DISABLED_REASON_NOT_DISABLED);
Makoto Onukib08790c2016-06-23 14:05:46 -0700368 return removed == null;
369 }
370
371 /**
372 * Disable a dynamic shortcut by ID. It'll be removed from the dynamic set, but if the shortcut
373 * is pinned, it'll remain as a pinned shortcut, but will be disabled.
374 *
375 * @return true if it's actually removed because it wasn't pinned, or false if it's still
376 * pinned.
377 */
Makoto Onukia4f89b12017-10-05 10:37:55 -0700378 private boolean disableDynamicWithId(@NonNull String shortcutId, boolean ignoreInvisible,
379 int disabledReason) {
Makoto Onukib08790c2016-06-23 14:05:46 -0700380 final ShortcutInfo disabled = deleteOrDisableWithId(
Makoto Onukia4f89b12017-10-05 10:37:55 -0700381 shortcutId, /* disable =*/ true, /* overrideImmutable=*/ false, ignoreInvisible,
382 disabledReason);
Makoto Onukib08790c2016-06-23 14:05:46 -0700383 return disabled == null;
Makoto Onuki22fcc682016-05-17 14:52:19 -0700384 }
385
Makoto Onuki7001a612016-05-27 13:24:28 -0700386 /**
Mehdi Alizadeh505fb762020-01-21 17:26:24 -0800387 * Remove a long lived shortcut by ID. If the shortcut is pinned, it'll remain as a pinned
388 * shortcut, and is still enabled.
389 *
390 * @return true if it's actually removed because it wasn't pinned, or false if it's still
391 * pinned.
392 */
393 public boolean deleteLongLivedWithId(@NonNull String shortcutId, boolean ignoreInvisible) {
394 final ShortcutInfo shortcut = mShortcuts.get(shortcutId);
395 if (shortcut != null) {
396 shortcut.clearFlags(ShortcutInfo.FLAG_CACHED);
397 }
398 final ShortcutInfo removed = deleteOrDisableWithId(
399 shortcutId, /* disable =*/ false, /* overrideImmutable=*/ false, ignoreInvisible,
400 ShortcutInfo.DISABLED_REASON_NOT_DISABLED);
401 return removed == null;
402 }
403
404 /**
Makoto Onuki7001a612016-05-27 13:24:28 -0700405 * Disable a dynamic shortcut by ID. It'll be removed from the dynamic set, but if the shortcut
406 * is pinned, it'll remain as a pinned shortcut but will be disabled.
407 */
Makoto Onuki22fcc682016-05-17 14:52:19 -0700408 public void disableWithId(@NonNull String shortcutId, String disabledMessage,
Makoto Onukia4f89b12017-10-05 10:37:55 -0700409 int disabledMessageResId, boolean overrideImmutable, boolean ignoreInvisible,
410 int disabledReason) {
Makoto Onuki22fcc682016-05-17 14:52:19 -0700411 final ShortcutInfo disabled = deleteOrDisableWithId(shortcutId, /* disable =*/ true,
Makoto Onukia4f89b12017-10-05 10:37:55 -0700412 overrideImmutable, ignoreInvisible, disabledReason);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700413
414 if (disabled != null) {
415 if (disabledMessage != null) {
416 disabled.setDisabledMessage(disabledMessage);
417 } else if (disabledMessageResId != 0) {
418 disabled.setDisabledMessageResId(disabledMessageResId);
Makoto Onuki157b1622016-06-02 16:13:10 -0700419
420 mShortcutUser.mService.fixUpShortcutResourceNamesAndValues(disabled);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700421 }
422 }
423 }
424
425 @Nullable
426 private ShortcutInfo deleteOrDisableWithId(@NonNull String shortcutId, boolean disable,
Makoto Onukia4f89b12017-10-05 10:37:55 -0700427 boolean overrideImmutable, boolean ignoreInvisible, int disabledReason) {
428 Preconditions.checkState(
429 (disable == (disabledReason != ShortcutInfo.DISABLED_REASON_NOT_DISABLED)),
430 "disable and disabledReason disagree: " + disable + " vs " + disabledReason);
Makoto Onuki31459242016-03-22 11:12:18 -0700431 final ShortcutInfo oldShortcut = mShortcuts.get(shortcutId);
432
Makoto Onukia4f89b12017-10-05 10:37:55 -0700433 if (oldShortcut == null || !oldShortcut.isEnabled()
434 && (ignoreInvisible && !oldShortcut.isVisibleToPublisher())) {
Makoto Onuki22fcc682016-05-17 14:52:19 -0700435 return null; // Doesn't exist or already disabled.
Makoto Onuki31459242016-03-22 11:12:18 -0700436 }
Makoto Onuki22fcc682016-05-17 14:52:19 -0700437 if (!overrideImmutable) {
Makoto Onukia4f89b12017-10-05 10:37:55 -0700438 ensureNotImmutable(oldShortcut, /*ignoreInvisible=*/ true);
Makoto Onuki31459242016-03-22 11:12:18 -0700439 }
Mehdi Alizadeh505fb762020-01-21 17:26:24 -0800440 if (oldShortcut.isPinned() || oldShortcut.isCached()) {
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700441
442 oldShortcut.setRank(0);
Makoto Onuki99302b52017-03-29 12:42:26 -0700443 oldShortcut.clearFlags(ShortcutInfo.FLAG_DYNAMIC | ShortcutInfo.FLAG_MANIFEST);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700444 if (disable) {
445 oldShortcut.addFlags(ShortcutInfo.FLAG_DISABLED);
Makoto Onukia4f89b12017-10-05 10:37:55 -0700446 // Do not overwrite the disabled reason if one is alreay set.
447 if (oldShortcut.getDisabledReason() == ShortcutInfo.DISABLED_REASON_NOT_DISABLED) {
448 oldShortcut.setDisabledReason(disabledReason);
449 }
Makoto Onuki22fcc682016-05-17 14:52:19 -0700450 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -0700451 oldShortcut.setTimestamp(mShortcutUser.mService.injectCurrentTimeMillis());
452
Makoto Onuki255461f2017-01-10 11:47:25 -0800453 // See ShortcutRequestPinProcessor.directPinShortcut().
454 if (mShortcutUser.mService.isDummyMainActivity(oldShortcut.getActivity())) {
455 oldShortcut.setActivity(null);
456 }
457
Makoto Onuki22fcc682016-05-17 14:52:19 -0700458 return oldShortcut;
Makoto Onuki31459242016-03-22 11:12:18 -0700459 } else {
Makoto Onukia4f89b12017-10-05 10:37:55 -0700460 forceDeleteShortcutInner(shortcutId);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700461 return null;
462 }
463 }
464
465 public void enableWithId(@NonNull String shortcutId) {
466 final ShortcutInfo shortcut = mShortcuts.get(shortcutId);
467 if (shortcut != null) {
Makoto Onukia4f89b12017-10-05 10:37:55 -0700468 ensureNotImmutable(shortcut, /*ignoreInvisible=*/ true);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700469 shortcut.clearFlags(ShortcutInfo.FLAG_DISABLED);
Makoto Onukia4f89b12017-10-05 10:37:55 -0700470 shortcut.setDisabledReason(ShortcutInfo.DISABLED_REASON_NOT_DISABLED);
Makoto Onuki31459242016-03-22 11:12:18 -0700471 }
472 }
473
Makoto Onukia4f89b12017-10-05 10:37:55 -0700474 public void updateInvisibleShortcutForPinRequestWith(@NonNull ShortcutInfo shortcut) {
475 final ShortcutInfo source = mShortcuts.get(shortcut.getId());
Daulet Zhanguzin82adfcb2020-01-02 17:31:40 +0000476 Objects.requireNonNull(source);
Makoto Onukia4f89b12017-10-05 10:37:55 -0700477
478 mShortcutUser.mService.validateShortcutForPinRequest(shortcut);
479
480 shortcut.addFlags(ShortcutInfo.FLAG_PINNED);
481
482 forceReplaceShortcutInner(shortcut);
483
484 adjustRanks();
485 }
486
Makoto Onuki31459242016-03-22 11:12:18 -0700487 /**
488 * Called after a launcher updates the pinned set. For each shortcut in this package,
489 * set FLAG_PINNED if any launcher has pinned it. Otherwise, clear it.
490 *
491 * <p>Then remove all shortcuts that are not dynamic and no longer pinned either.
492 */
Makoto Onukic51b2872016-05-04 15:24:50 -0700493 public void refreshPinnedFlags() {
Makoto Onuki31459242016-03-22 11:12:18 -0700494 // First, un-pin all shortcuts
495 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
496 mShortcuts.valueAt(i).clearFlags(ShortcutInfo.FLAG_PINNED);
497 }
498
499 // Then, for the pinned set for each launcher, set the pin flag one by one.
Makoto Onuki47ed1712017-12-20 14:40:20 +0900500 mShortcutUser.forAllLaunchers(launcherShortcuts -> {
Makoto Onuki9da23fc2016-03-29 11:14:42 -0700501 final ArraySet<String> pinned = launcherShortcuts.getPinnedShortcutIds(
Makoto Onuki2e210c42016-03-30 08:30:36 -0700502 getPackageName(), getPackageUserId());
Makoto Onuki31459242016-03-22 11:12:18 -0700503
504 if (pinned == null || pinned.size() == 0) {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700505 return;
Makoto Onuki31459242016-03-22 11:12:18 -0700506 }
507 for (int i = pinned.size() - 1; i >= 0; i--) {
Makoto Onuki2e210c42016-03-30 08:30:36 -0700508 final String id = pinned.valueAt(i);
509 final ShortcutInfo si = mShortcuts.get(id);
Makoto Onuki31459242016-03-22 11:12:18 -0700510 if (si == null) {
Makoto Onuki2e210c42016-03-30 08:30:36 -0700511 // This happens if a launcher pinned shortcuts from this package, then backup&
512 // restored, but this package doesn't allow backing up.
513 // In that case the launcher ends up having a dangling pinned shortcuts.
514 // That's fine, when the launcher is restored, we'll fix it.
515 continue;
Makoto Onuki31459242016-03-22 11:12:18 -0700516 }
Makoto Onuki2e210c42016-03-30 08:30:36 -0700517 si.addFlags(ShortcutInfo.FLAG_PINNED);
Makoto Onuki31459242016-03-22 11:12:18 -0700518 }
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700519 });
Makoto Onuki31459242016-03-22 11:12:18 -0700520
Mehdi Alizadeh505fb762020-01-21 17:26:24 -0800521 // Lastly, remove the ones that are no longer pinned, cached nor dynamic.
Makoto Onukic51b2872016-05-04 15:24:50 -0700522 removeOrphans();
Makoto Onuki31459242016-03-22 11:12:18 -0700523 }
524
525 /**
526 * Number of calls that the caller has made, since the last reset.
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700527 *
528 * <p>This takes care of the resetting the counter for foreground apps as well as after
529 * locale changes.
Makoto Onuki31459242016-03-22 11:12:18 -0700530 */
Makoto Onuki7d0fa812018-02-21 11:24:43 -0800531 public int getApiCallCount(boolean unlimited) {
Makoto Onukic51b2872016-05-04 15:24:50 -0700532 final ShortcutService s = mShortcutUser.mService;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700533
534 // Reset the counter if:
535 // - the package is in foreground now.
536 // - the package is *not* in foreground now, but was in foreground at some point
537 // since the previous time it had been.
538 if (s.isUidForegroundLocked(mPackageUid)
Makoto Onuki7d0fa812018-02-21 11:24:43 -0800539 || (mLastKnownForegroundElapsedTime
540 < s.getUidLastForegroundElapsedTimeLocked(mPackageUid))
541 || unlimited) {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700542 mLastKnownForegroundElapsedTime = s.injectElapsedRealtime();
Makoto Onukic51b2872016-05-04 15:24:50 -0700543 resetRateLimiting();
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700544 }
545
546 // Note resetThrottlingIfNeeded() and resetRateLimiting() will set 0 to mApiCallCount,
547 // but we just can't return 0 at this point, because we may have to update
548 // mLastResetTime.
549
Makoto Onuki31459242016-03-22 11:12:18 -0700550 final long last = s.getLastResetTimeLocked();
551
552 final long now = s.injectCurrentTimeMillis();
553 if (ShortcutService.isClockValid(now) && mLastResetTime > now) {
554 Slog.w(TAG, "Clock rewound");
555 // Clock rewound.
556 mLastResetTime = now;
557 mApiCallCount = 0;
558 return mApiCallCount;
559 }
560
561 // If not reset yet, then reset.
562 if (mLastResetTime < last) {
563 if (ShortcutService.DEBUG) {
Makoto Onukic51b2872016-05-04 15:24:50 -0700564 Slog.d(TAG, String.format("%s: last reset=%d, now=%d, last=%d: resetting",
565 getPackageName(), mLastResetTime, now, last));
Makoto Onuki31459242016-03-22 11:12:18 -0700566 }
567 mApiCallCount = 0;
568 mLastResetTime = last;
569 }
570 return mApiCallCount;
571 }
572
573 /**
574 * If the caller app hasn't been throttled yet, increment {@link #mApiCallCount}
575 * and return true. Otherwise just return false.
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700576 *
577 * <p>This takes care of the resetting the counter for foreground apps as well as after
578 * locale changes, which is done internally by {@link #getApiCallCount}.
Makoto Onuki31459242016-03-22 11:12:18 -0700579 */
Makoto Onuki7d0fa812018-02-21 11:24:43 -0800580 public boolean tryApiCall(boolean unlimited) {
Makoto Onukic51b2872016-05-04 15:24:50 -0700581 final ShortcutService s = mShortcutUser.mService;
582
Makoto Onuki7d0fa812018-02-21 11:24:43 -0800583 if (getApiCallCount(unlimited) >= s.mMaxUpdatesPerInterval) {
Makoto Onuki31459242016-03-22 11:12:18 -0700584 return false;
585 }
586 mApiCallCount++;
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700587 s.scheduleSaveUser(getOwnerUserId());
Makoto Onuki31459242016-03-22 11:12:18 -0700588 return true;
589 }
590
Makoto Onukic51b2872016-05-04 15:24:50 -0700591 public void resetRateLimiting() {
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700592 if (ShortcutService.DEBUG) {
593 Slog.d(TAG, "resetRateLimiting: " + getPackageName());
594 }
595 if (mApiCallCount > 0) {
596 mApiCallCount = 0;
Makoto Onukic51b2872016-05-04 15:24:50 -0700597 mShortcutUser.mService.scheduleSaveUser(getOwnerUserId());
Makoto Onuki4d36b3a2016-04-27 12:00:17 -0700598 }
599 }
600
601 public void resetRateLimitingForCommandLineNoSaving() {
Makoto Onuki31459242016-03-22 11:12:18 -0700602 mApiCallCount = 0;
603 mLastResetTime = 0;
604 }
605
606 /**
607 * Find all shortcuts that match {@code query}.
608 */
Makoto Onukic51b2872016-05-04 15:24:50 -0700609 public void findAll(@NonNull List<ShortcutInfo> result,
Makoto Onukid99c6f02016-03-28 11:02:54 -0700610 @Nullable Predicate<ShortcutInfo> query, int cloneFlag) {
Makoto Onuki634cecb2017-10-13 17:10:48 -0700611 findAll(result, query, cloneFlag, null, 0, /*getPinnedByAnyLauncher=*/ false);
Makoto Onukid99c6f02016-03-28 11:02:54 -0700612 }
613
614 /**
615 * Find all shortcuts that match {@code query}.
616 *
617 * This will also provide a "view" for each launcher -- a non-dynamic shortcut that's not pinned
618 * by the calling launcher will not be included in the result, and also "isPinned" will be
619 * adjusted for the caller too.
620 */
Makoto Onukic51b2872016-05-04 15:24:50 -0700621 public void findAll(@NonNull List<ShortcutInfo> result,
Makoto Onuki31459242016-03-22 11:12:18 -0700622 @Nullable Predicate<ShortcutInfo> query, int cloneFlag,
Makoto Onuki634cecb2017-10-13 17:10:48 -0700623 @Nullable String callingLauncher, int launcherUserId, boolean getPinnedByAnyLauncher) {
Makoto Onuki2e210c42016-03-30 08:30:36 -0700624 if (getPackageInfo().isShadow()) {
625 // Restored and the app not installed yet, so don't return any.
626 return;
627 }
Makoto Onuki31459242016-03-22 11:12:18 -0700628
Makoto Onukic51b2872016-05-04 15:24:50 -0700629 final ShortcutService s = mShortcutUser.mService;
630
Makoto Onuki31459242016-03-22 11:12:18 -0700631 // Set of pinned shortcuts by the calling launcher.
632 final ArraySet<String> pinnedByCallerSet = (callingLauncher == null) ? null
Makoto Onuki2e210c42016-03-30 08:30:36 -0700633 : s.getLauncherShortcutsLocked(callingLauncher, getPackageUserId(), launcherUserId)
634 .getPinnedShortcutIds(getPackageName(), getPackageUserId());
Makoto Onuki31459242016-03-22 11:12:18 -0700635
636 for (int i = 0; i < mShortcuts.size(); i++) {
637 final ShortcutInfo si = mShortcuts.valueAt(i);
638
Makoto Onuki22fcc682016-05-17 14:52:19 -0700639 // Need to adjust PINNED flag depending on the caller.
640 // Basically if the caller is a launcher (callingLauncher != null) and the launcher
641 // isn't pinning it, then we need to clear PINNED for this caller.
Makoto Onuki31459242016-03-22 11:12:18 -0700642 final boolean isPinnedByCaller = (callingLauncher == null)
643 || ((pinnedByCallerSet != null) && pinnedByCallerSet.contains(si.getId()));
Makoto Onuki22fcc682016-05-17 14:52:19 -0700644
Makoto Onuki634cecb2017-10-13 17:10:48 -0700645 if (!getPinnedByAnyLauncher) {
646 if (si.isFloating()) {
647 if (!isPinnedByCaller) {
648 continue;
649 }
Makoto Onuki31459242016-03-22 11:12:18 -0700650 }
651 }
652 final ShortcutInfo clone = si.clone(cloneFlag);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700653
Makoto Onuki31459242016-03-22 11:12:18 -0700654 // Fix up isPinned for the caller. Note we need to do it before the "test" callback,
655 // since it may check isPinned.
Makoto Onuki35559d62017-11-06 16:26:32 -0800656 // However, if getPinnedByAnyLauncher is set, we do it after the test.
657 if (!getPinnedByAnyLauncher) {
658 if (!isPinnedByCaller) {
659 clone.clearFlags(ShortcutInfo.FLAG_PINNED);
660 }
Makoto Onuki31459242016-03-22 11:12:18 -0700661 }
662 if (query == null || query.test(clone)) {
Makoto Onuki35559d62017-11-06 16:26:32 -0800663 if (!isPinnedByCaller) {
664 clone.clearFlags(ShortcutInfo.FLAG_PINNED);
665 }
Makoto Onuki31459242016-03-22 11:12:18 -0700666 result.add(clone);
667 }
668 }
669 }
670
671 public void resetThrottling() {
672 mApiCallCount = 0;
673 }
674
Makoto Onuki39686e82016-04-13 18:03:00 -0700675 /**
Mehdi Alizadeh406e8b32018-12-11 18:21:49 -0800676 * Returns a list of ShortcutInfos that match the given intent filter and the category of
677 * available ShareTarget definitions in this package.
678 */
679 public List<ShortcutManager.ShareShortcutInfo> getMatchingShareTargets(
680 @NonNull IntentFilter filter) {
681 final List<ShareTargetInfo> matchedTargets = new ArrayList<>();
682 for (int i = 0; i < mShareTargets.size(); i++) {
683 final ShareTargetInfo target = mShareTargets.get(i);
684 for (ShareTargetInfo.TargetData data : target.mTargetData) {
685 if (filter.hasDataType(data.mMimeType)) {
686 // Matched at least with one data type
687 matchedTargets.add(target);
688 break;
689 }
690 }
691 }
692
693 if (matchedTargets.isEmpty()) {
694 return new ArrayList<>();
695 }
696
Mehdi Alizadehc6096022019-05-27 12:17:36 -0700697 // Get the list of all dynamic shortcuts in this package.
Mehdi Alizadeh406e8b32018-12-11 18:21:49 -0800698 final ArrayList<ShortcutInfo> shortcuts = new ArrayList<>();
Mehdi Alizadehc6096022019-05-27 12:17:36 -0700699 findAll(shortcuts, ShortcutInfo::isDynamicVisible,
700 ShortcutInfo.CLONE_REMOVE_FOR_APP_PREDICTION);
Mehdi Alizadeh406e8b32018-12-11 18:21:49 -0800701
702 final List<ShortcutManager.ShareShortcutInfo> result = new ArrayList<>();
703 for (int i = 0; i < shortcuts.size(); i++) {
Mehdi Alizadeh97fb3ed2019-04-25 14:52:02 -0700704 final Set<String> categories = shortcuts.get(i).getCategories();
705 if (categories == null || categories.isEmpty()) {
706 continue;
707 }
Mehdi Alizadeh406e8b32018-12-11 18:21:49 -0800708 for (int j = 0; j < matchedTargets.size(); j++) {
709 // Shortcut must have all of share target categories
710 boolean hasAllCategories = true;
711 final ShareTargetInfo target = matchedTargets.get(j);
712 for (int q = 0; q < target.mCategories.length; q++) {
Mehdi Alizadeh97fb3ed2019-04-25 14:52:02 -0700713 if (!categories.contains(target.mCategories[q])) {
Mehdi Alizadeh406e8b32018-12-11 18:21:49 -0800714 hasAllCategories = false;
715 break;
716 }
717 }
718 if (hasAllCategories) {
Mehdi Alizadeh97fb3ed2019-04-25 14:52:02 -0700719 result.add(new ShortcutManager.ShareShortcutInfo(shortcuts.get(i),
720 new ComponentName(getPackageName(), target.mTargetClass)));
Mehdi Alizadeh406e8b32018-12-11 18:21:49 -0800721 break;
722 }
723 }
724 }
725 return result;
726 }
727
Mehdi Alizadeh85fd3d52019-01-23 12:49:53 -0800728 public boolean hasShareTargets() {
729 return !mShareTargets.isEmpty();
730 }
731
Mehdi Alizadeh406e8b32018-12-11 18:21:49 -0800732 /**
Mehdi Alizadeh97fb3ed2019-04-25 14:52:02 -0700733 * Returns the number of shortcuts that can be used as a share target in the ShareSheet. Such
734 * shortcuts must have a matching category with at least one of the defined ShareTargets from
735 * the app's Xml resource.
736 */
737 int getSharingShortcutCount() {
738 if (mShortcuts.isEmpty() || mShareTargets.isEmpty()) {
739 return 0;
740 }
741
742 // Get the list of all dynamic shortcuts in this package
743 final ArrayList<ShortcutInfo> shortcuts = new ArrayList<>();
744 findAll(shortcuts, ShortcutInfo::isDynamicVisible, ShortcutInfo.CLONE_REMOVE_FOR_LAUNCHER);
745
746 int sharingShortcutCount = 0;
747 for (int i = 0; i < shortcuts.size(); i++) {
748 final Set<String> categories = shortcuts.get(i).getCategories();
749 if (categories == null || categories.isEmpty()) {
750 continue;
751 }
752 for (int j = 0; j < mShareTargets.size(); j++) {
753 // A SharingShortcut must have all of share target categories
754 boolean hasAllCategories = true;
755 final ShareTargetInfo target = mShareTargets.get(j);
756 for (int q = 0; q < target.mCategories.length; q++) {
757 if (!categories.contains(target.mCategories[q])) {
758 hasAllCategories = false;
759 break;
760 }
761 }
762 if (hasAllCategories) {
763 sharingShortcutCount++;
764 break;
765 }
766 }
767 }
768 return sharingShortcutCount;
769 }
770
771 /**
Makoto Onuki6c1dbd52016-05-02 15:19:32 -0700772 * Return the filenames (excluding path names) of icon bitmap files from this package.
773 */
774 public ArraySet<String> getUsedBitmapFiles() {
775 final ArraySet<String> usedFiles = new ArraySet<>(mShortcuts.size());
776
777 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
778 final ShortcutInfo si = mShortcuts.valueAt(i);
779 if (si.getBitmapPath() != null) {
780 usedFiles.add(getFileName(si.getBitmapPath()));
781 }
782 }
783 return usedFiles;
784 }
785
786 private static String getFileName(@NonNull String path) {
787 final int sep = path.lastIndexOf(File.separatorChar);
788 if (sep == -1) {
789 return path;
790 } else {
791 return path.substring(sep + 1);
792 }
793 }
794
795 /**
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700796 * @return false if any of the target activities are no longer enabled.
797 */
798 private boolean areAllActivitiesStillEnabled() {
799 if (mShortcuts.size() == 0) {
800 return true;
801 }
802 final ShortcutService s = mShortcutUser.mService;
803
804 // Normally the number of target activities is 1 or so, so no need to use a complex
805 // structure like a set.
806 final ArrayList<ComponentName> checked = new ArrayList<>(4);
807
808 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
809 final ShortcutInfo si = mShortcuts.valueAt(i);
810 final ComponentName activity = si.getActivity();
811
812 if (checked.contains(activity)) {
813 continue; // Already checked.
814 }
815 checked.add(activity);
816
Makoto Onuki40dc2112017-10-18 12:52:45 -0700817 if ((activity != null)
818 && !s.injectIsActivityEnabledAndExported(activity, getOwnerUserId())) {
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700819 return false;
820 }
821 }
822 return true;
823 }
824
825 /**
826 * Called when the package may be added or updated, or its activities may be disabled, and
827 * if so, rescan the package and do the necessary stuff.
Makoto Onuki22fcc682016-05-17 14:52:19 -0700828 *
829 * Add case:
830 * - Publish manifest shortcuts.
831 *
832 * Update case:
833 * - Re-publish manifest shortcuts.
834 * - If there are shortcuts with resources (icons or strings), update their timestamps.
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700835 * - Disable shortcuts whose target activities are disabled.
Makoto Onuki22fcc682016-05-17 14:52:19 -0700836 *
837 * @return TRUE if any shortcuts have been changed.
Makoto Onuki39686e82016-04-13 18:03:00 -0700838 */
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700839 public boolean rescanPackageIfNeeded(boolean isNewApp, boolean forceRescan) {
840 final ShortcutService s = mShortcutUser.mService;
Makoto Onuki84d59342018-02-02 09:22:38 -0800841 final long start = s.getStatStartTime();
Makoto Onuki39686e82016-04-13 18:03:00 -0700842
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700843 final PackageInfo pi;
844 try {
845 pi = mShortcutUser.mService.getPackageInfo(
846 getPackageName(), getPackageUserId());
847 if (pi == null) {
848 return false; // Shouldn't happen.
Makoto Onuki22fcc682016-05-17 14:52:19 -0700849 }
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700850
Makoto Onuki248a0ef2016-11-03 15:59:01 -0700851 if (!isNewApp && !forceRescan) {
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700852 // Return if the package hasn't changed, ie:
853 // - version code hasn't change
854 // - lastUpdateTime hasn't change
855 // - all target activities are still enabled.
Makoto Onuki33663282016-08-22 16:19:04 -0700856
857 // Note, system apps timestamps do *not* change after OTAs. (But they do
858 // after an adb sync or a local flash.)
859 // This means if a system app's version code doesn't change on an OTA,
860 // we don't notice it's updated. But that's fine since their version code *should*
861 // really change on OTAs.
Dianne Hackborn3accca02013-09-20 09:32:11 -0700862 if ((getPackageInfo().getVersionCode() == pi.getLongVersionCode())
Makoto Onuki64183d52016-08-08 14:11:34 -0700863 && (getPackageInfo().getLastUpdateTime() == pi.lastUpdateTime)
Makoto Onuki4e6cef42016-07-13 16:14:01 -0700864 && areAllActivitiesStillEnabled()) {
865 return false;
866 }
867 }
868 } finally {
869 s.logDurationStat(Stats.PACKAGE_UPDATE_CHECK, start);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700870 }
871
872 // Now prepare to publish manifest shortcuts.
873 List<ShortcutInfo> newManifestShortcutList = null;
874 try {
875 newManifestShortcutList = ShortcutParser.parseShortcuts(mShortcutUser.mService,
Mehdi Alizadeh32774622018-11-05 17:32:01 -0800876 getPackageName(), getPackageUserId(), mShareTargets);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700877 } catch (IOException|XmlPullParserException e) {
878 Slog.e(TAG, "Failed to load shortcuts from AndroidManifest.xml.", e);
879 }
880 final int manifestShortcutSize = newManifestShortcutList == null ? 0
881 : newManifestShortcutList.size();
882 if (ShortcutService.DEBUG) {
Mehdi Alizadeh32774622018-11-05 17:32:01 -0800883 Slog.d(TAG,
884 String.format("Package %s has %d manifest shortcut(s), and %d share target(s)",
885 getPackageName(), manifestShortcutSize, mShareTargets.size()));
Makoto Onuki22fcc682016-05-17 14:52:19 -0700886 }
887 if (isNewApp && (manifestShortcutSize == 0)) {
888 // If it's a new app, and it doesn't have manifest shortcuts, then nothing to do.
889
890 // If it's an update, then it may already have manifest shortcuts, which need to be
891 // disabled.
892 return false;
893 }
894 if (ShortcutService.DEBUG) {
895 Slog.d(TAG, String.format("Package %s %s, version %d -> %d", getPackageName(),
896 (isNewApp ? "added" : "updated"),
Dianne Hackborn3accca02013-09-20 09:32:11 -0700897 getPackageInfo().getVersionCode(), pi.getLongVersionCode()));
Makoto Onuki22fcc682016-05-17 14:52:19 -0700898 }
899
Makoto Onukia4f89b12017-10-05 10:37:55 -0700900 getPackageInfo().updateFromPackageInfo(pi);
Dianne Hackborn3accca02013-09-20 09:32:11 -0700901 final long newVersionCode = getPackageInfo().getVersionCode();
Makoto Onukia4f89b12017-10-05 10:37:55 -0700902
903 // See if there are any shortcuts that were prevented restoring because the app was of a
904 // lower version, and re-enable them.
905 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
906 final ShortcutInfo si = mShortcuts.valueAt(i);
907 if (si.getDisabledReason() != ShortcutInfo.DISABLED_REASON_VERSION_LOWER) {
908 continue;
909 }
910 if (getPackageInfo().getBackupSourceVersionCode() > newVersionCode) {
911 if (ShortcutService.DEBUG) {
912 Slog.d(TAG, String.format("Shortcut %s require version %s, still not restored.",
913 si.getId(), getPackageInfo().getBackupSourceVersionCode()));
914 }
915 continue;
916 }
917 Slog.i(TAG, String.format("Restoring shortcut: %s", si.getId()));
918 si.clearFlags(ShortcutInfo.FLAG_DISABLED);
919 si.setDisabledReason(ShortcutInfo.DISABLED_REASON_NOT_DISABLED);
920 }
Makoto Onuki39686e82016-04-13 18:03:00 -0700921
Makoto Onuki22fcc682016-05-17 14:52:19 -0700922 // For existing shortcuts, update timestamps if they have any resources.
Makoto Onukib08790c2016-06-23 14:05:46 -0700923 // Also check if shortcuts' activities are still main activities. Otherwise, disable them.
Makoto Onuki22fcc682016-05-17 14:52:19 -0700924 if (!isNewApp) {
Makoto Onuki157b1622016-06-02 16:13:10 -0700925 Resources publisherRes = null;
926
Makoto Onuki22fcc682016-05-17 14:52:19 -0700927 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
928 final ShortcutInfo si = mShortcuts.valueAt(i);
929
Makoto Onuki2d895c32016-12-02 15:48:40 -0800930 // Disable dynamic shortcuts whose target activity is gone.
Makoto Onukib08790c2016-06-23 14:05:46 -0700931 if (si.isDynamic()) {
Makoto Onuki34145532017-03-14 17:58:36 -0700932 if (si.getActivity() == null) {
933 // Note if it's dynamic, it must have a target activity, but b/36228253.
934 s.wtf("null activity detected.");
935 // TODO Maybe remove it?
936 } else if (!s.injectIsMainActivity(si.getActivity(), getPackageUserId())) {
Makoto Onukib08790c2016-06-23 14:05:46 -0700937 Slog.w(TAG, String.format(
938 "%s is no longer main activity. Disabling shorcut %s.",
939 getPackageName(), si.getId()));
Makoto Onukia4f89b12017-10-05 10:37:55 -0700940 if (disableDynamicWithId(si.getId(), /*ignoreInvisible*/ false,
941 ShortcutInfo.DISABLED_REASON_APP_CHANGED)) {
Makoto Onukib08790c2016-06-23 14:05:46 -0700942 continue; // Actually removed.
943 }
944 // Still pinned, so fall-through and possibly update the resources.
945 }
Makoto Onukib08790c2016-06-23 14:05:46 -0700946 }
947
Makoto Onuki22fcc682016-05-17 14:52:19 -0700948 if (si.hasAnyResources()) {
Makoto Onuki157b1622016-06-02 16:13:10 -0700949 if (!si.isOriginallyFromManifest()) {
950 if (publisherRes == null) {
951 publisherRes = getPackageResources();
952 if (publisherRes == null) {
953 break; // Resources couldn't be loaded.
954 }
955 }
956
957 // If this shortcut is not from a manifest, then update all resource IDs
958 // from resource names. (We don't allow resource strings for
959 // non-manifest at the moment, but icons can still be resources.)
960 si.lookupAndFillInResourceIds(publisherRes);
961 }
Makoto Onuki22fcc682016-05-17 14:52:19 -0700962 si.setTimestamp(s.injectCurrentTimeMillis());
963 }
Makoto Onuki39686e82016-04-13 18:03:00 -0700964 }
965 }
Makoto Onuki22fcc682016-05-17 14:52:19 -0700966
967 // (Re-)publish manifest shortcut.
Makoto Onuki82fb2eb2017-03-31 16:58:26 -0700968 publishManifestShortcuts(newManifestShortcutList);
Makoto Onuki22fcc682016-05-17 14:52:19 -0700969
Makoto Onuki7001a612016-05-27 13:24:28 -0700970 if (newManifestShortcutList != null) {
Makoto Onuki82fb2eb2017-03-31 16:58:26 -0700971 pushOutExcessShortcuts();
Makoto Onuki7001a612016-05-27 13:24:28 -0700972 }
973
Makoto Onukidf6da042016-06-16 09:51:40 -0700974 s.verifyStates();
975
Makoto Onuki82fb2eb2017-03-31 16:58:26 -0700976 // This will send a notification to the launcher, and also save .
977 s.packageShortcutsChanged(getPackageName(), getPackageUserId());
978 return true; // true means changed.
Makoto Onuki22fcc682016-05-17 14:52:19 -0700979 }
980
981 private boolean publishManifestShortcuts(List<ShortcutInfo> newManifestShortcutList) {
982 if (ShortcutService.DEBUG) {
983 Slog.d(TAG, String.format(
984 "Package %s: publishing manifest shortcuts", getPackageName()));
985 }
986 boolean changed = false;
987
Makoto Onuki22fcc682016-05-17 14:52:19 -0700988 // Keep the previous IDs.
989 ArraySet<String> toDisableList = null;
990 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
991 final ShortcutInfo si = mShortcuts.valueAt(i);
992
993 if (si.isManifestShortcut()) {
994 if (toDisableList == null) {
995 toDisableList = new ArraySet<>();
996 }
997 toDisableList.add(si.getId());
998 }
999 }
1000
1001 // Publish new ones.
1002 if (newManifestShortcutList != null) {
1003 final int newListSize = newManifestShortcutList.size();
1004
1005 for (int i = 0; i < newListSize; i++) {
1006 changed = true;
1007
1008 final ShortcutInfo newShortcut = newManifestShortcutList.get(i);
1009 final boolean newDisabled = !newShortcut.isEnabled();
1010
Makoto Onuki7001a612016-05-27 13:24:28 -07001011 final String id = newShortcut.getId();
Makoto Onuki22fcc682016-05-17 14:52:19 -07001012 final ShortcutInfo oldShortcut = mShortcuts.get(id);
1013
1014 boolean wasPinned = false;
1015
1016 if (oldShortcut != null) {
1017 if (!oldShortcut.isOriginallyFromManifest()) {
1018 Slog.e(TAG, "Shortcut with ID=" + newShortcut.getId()
1019 + " exists but is not from AndroidManifest.xml, not updating.");
1020 continue;
1021 }
1022 // Take over the pinned flag.
1023 if (oldShortcut.isPinned()) {
1024 wasPinned = true;
1025 newShortcut.addFlags(ShortcutInfo.FLAG_PINNED);
1026 }
1027 }
1028 if (newDisabled && !wasPinned) {
1029 // If the shortcut is disabled, and it was *not* pinned, then this
1030 // just doesn't have to be published.
1031 // Just keep it in toDisableList, so the previous one would be removed.
1032 continue;
1033 }
Makoto Onuki22fcc682016-05-17 14:52:19 -07001034
1035 // Note even if enabled=false, we still need to update all fields, so do it
1036 // regardless.
Makoto Onukia4f89b12017-10-05 10:37:55 -07001037 forceReplaceShortcutInner(newShortcut); // This will clean up the old one too.
Makoto Onuki22fcc682016-05-17 14:52:19 -07001038
1039 if (!newDisabled && toDisableList != null) {
1040 // Still alive, don't remove.
1041 toDisableList.remove(id);
1042 }
1043 }
1044 }
1045
1046 // Disable the previous manifest shortcuts that are no longer in the manifest.
1047 if (toDisableList != null) {
1048 if (ShortcutService.DEBUG) {
1049 Slog.d(TAG, String.format(
1050 "Package %s: disabling %d stale shortcuts", getPackageName(),
1051 toDisableList.size()));
1052 }
1053 for (int i = toDisableList.size() - 1; i >= 0; i--) {
1054 changed = true;
1055
1056 final String id = toDisableList.valueAt(i);
1057
1058 disableWithId(id, /* disable message =*/ null, /* disable message resid */ 0,
Makoto Onukia4f89b12017-10-05 10:37:55 -07001059 /* overrideImmutable=*/ true, /*ignoreInvisible=*/ false,
1060 ShortcutInfo.DISABLED_REASON_APP_CHANGED);
Makoto Onuki22fcc682016-05-17 14:52:19 -07001061 }
1062 removeOrphans();
1063 }
Makoto Onukidf6da042016-06-16 09:51:40 -07001064 adjustRanks();
Makoto Onuki22fcc682016-05-17 14:52:19 -07001065 return changed;
Makoto Onuki39686e82016-04-13 18:03:00 -07001066 }
1067
Makoto Onuki7001a612016-05-27 13:24:28 -07001068 /**
1069 * For each target activity, make sure # of dynamic + manifest shortcuts <= max.
1070 * If too many, we'll remove the dynamic with the lowest ranks.
1071 */
1072 private boolean pushOutExcessShortcuts() {
1073 final ShortcutService service = mShortcutUser.mService;
1074 final int maxShortcuts = service.getMaxActivityShortcuts();
1075
1076 boolean changed = false;
1077
1078 final ArrayMap<ComponentName, ArrayList<ShortcutInfo>> all =
1079 sortShortcutsToActivities();
1080 for (int outer = all.size() - 1; outer >= 0; outer--) {
1081 final ArrayList<ShortcutInfo> list = all.valueAt(outer);
1082 if (list.size() <= maxShortcuts) {
1083 continue;
1084 }
1085 // Sort by isManifestShortcut() and getRank().
1086 Collections.sort(list, mShortcutTypeAndRankComparator);
1087
1088 // Keep [0 .. max), and remove (as dynamic) [max .. size)
1089 for (int inner = list.size() - 1; inner >= maxShortcuts; inner--) {
1090 final ShortcutInfo shortcut = list.get(inner);
1091
1092 if (shortcut.isManifestShortcut()) {
1093 // This shouldn't happen -- excess shortcuts should all be non-manifest.
1094 // But just in case.
1095 service.wtf("Found manifest shortcuts in excess list.");
1096 continue;
1097 }
Makoto Onukia4f89b12017-10-05 10:37:55 -07001098 deleteDynamicWithId(shortcut.getId(), /*ignoreInvisible=*/ true);
Makoto Onuki7001a612016-05-27 13:24:28 -07001099 }
1100 }
Makoto Onuki7001a612016-05-27 13:24:28 -07001101
1102 return changed;
1103 }
1104
1105 /**
1106 * To sort by isManifestShortcut() and getRank(). i.e. manifest shortcuts come before
1107 * non-manifest shortcuts, then sort by rank.
1108 *
1109 * This is used to decide which dynamic shortcuts to remove when an upgraded version has more
1110 * manifest shortcuts than before and as a result we need to remove some of the dynamic
1111 * shortcuts. We sort manifest + dynamic shortcuts by this order, and remove the ones with
1112 * the last ones.
1113 *
1114 * (Note the number of manifest shortcuts is always <= the max number, because if there are
1115 * more, ShortcutParser would ignore the rest.)
1116 */
1117 final Comparator<ShortcutInfo> mShortcutTypeAndRankComparator = (ShortcutInfo a,
1118 ShortcutInfo b) -> {
1119 if (a.isManifestShortcut() && !b.isManifestShortcut()) {
1120 return -1;
1121 }
1122 if (!a.isManifestShortcut() && b.isManifestShortcut()) {
1123 return 1;
1124 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001125 return Integer.compare(a.getRank(), b.getRank());
Makoto Onuki7001a612016-05-27 13:24:28 -07001126 };
1127
1128 /**
1129 * Build a list of shortcuts for each target activity and return as a map. The result won't
1130 * contain "floating" shortcuts because they don't belong on any activities.
1131 */
1132 private ArrayMap<ComponentName, ArrayList<ShortcutInfo>> sortShortcutsToActivities() {
Makoto Onuki7001a612016-05-27 13:24:28 -07001133 final ArrayMap<ComponentName, ArrayList<ShortcutInfo>> activitiesToShortcuts
1134 = new ArrayMap<>();
1135 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1136 final ShortcutInfo si = mShortcuts.valueAt(i);
1137 if (si.isFloating()) {
1138 continue; // Ignore floating shortcuts, which are not tied to any activities.
1139 }
1140
1141 final ComponentName activity = si.getActivity();
Makoto Onuki34145532017-03-14 17:58:36 -07001142 if (activity == null) {
1143 mShortcutUser.mService.wtf("null activity detected.");
1144 continue;
1145 }
Makoto Onuki7001a612016-05-27 13:24:28 -07001146
1147 ArrayList<ShortcutInfo> list = activitiesToShortcuts.get(activity);
1148 if (list == null) {
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001149 list = new ArrayList<>();
Makoto Onuki7001a612016-05-27 13:24:28 -07001150 activitiesToShortcuts.put(activity, list);
1151 }
1152 list.add(si);
1153 }
1154 return activitiesToShortcuts;
1155 }
1156
1157 /** Used by {@link #enforceShortcutCountsBeforeOperation} */
1158 private void incrementCountForActivity(ArrayMap<ComponentName, Integer> counts,
1159 ComponentName cn, int increment) {
1160 Integer oldValue = counts.get(cn);
1161 if (oldValue == null) {
1162 oldValue = 0;
1163 }
1164
1165 counts.put(cn, oldValue + increment);
1166 }
1167
1168 /**
1169 * Called by
1170 * {@link android.content.pm.ShortcutManager#setDynamicShortcuts},
1171 * {@link android.content.pm.ShortcutManager#addDynamicShortcuts}, and
1172 * {@link android.content.pm.ShortcutManager#updateShortcuts} before actually performing
1173 * the operation to make sure the operation wouldn't result in the target activities having
1174 * more than the allowed number of dynamic/manifest shortcuts.
1175 *
1176 * @param newList shortcut list passed to set, add or updateShortcuts().
1177 * @param operation add, set or update.
1178 * @throws IllegalArgumentException if the operation would result in going over the max
1179 * shortcut count for any activity.
1180 */
1181 public void enforceShortcutCountsBeforeOperation(List<ShortcutInfo> newList,
1182 @ShortcutOperation int operation) {
1183 final ShortcutService service = mShortcutUser.mService;
1184
1185 // Current # of dynamic / manifest shortcuts for each activity.
1186 // (If it's for update, then don't count dynamic shortcuts, since they'll be replaced
1187 // anyway.)
1188 final ArrayMap<ComponentName, Integer> counts = new ArrayMap<>(4);
1189 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1190 final ShortcutInfo shortcut = mShortcuts.valueAt(i);
1191
1192 if (shortcut.isManifestShortcut()) {
1193 incrementCountForActivity(counts, shortcut.getActivity(), 1);
1194 } else if (shortcut.isDynamic() && (operation != ShortcutService.OPERATION_SET)) {
1195 incrementCountForActivity(counts, shortcut.getActivity(), 1);
1196 }
1197 }
1198
1199 for (int i = newList.size() - 1; i >= 0; i--) {
1200 final ShortcutInfo newShortcut = newList.get(i);
1201 final ComponentName newActivity = newShortcut.getActivity();
1202 if (newActivity == null) {
1203 if (operation != ShortcutService.OPERATION_UPDATE) {
Makoto Onukib08790c2016-06-23 14:05:46 -07001204 service.wtf("Activity must not be null at this point");
1205 continue; // Just ignore this invalid case.
Makoto Onuki7001a612016-05-27 13:24:28 -07001206 }
1207 continue; // Activity can be null for update.
1208 }
1209
1210 final ShortcutInfo original = mShortcuts.get(newShortcut.getId());
1211 if (original == null) {
1212 if (operation == ShortcutService.OPERATION_UPDATE) {
1213 continue; // When updating, ignore if there's no target.
1214 }
1215 // Add() or set(), and there's no existing shortcut with the same ID. We're
1216 // simply publishing (as opposed to updating) this shortcut, so just +1.
1217 incrementCountForActivity(counts, newActivity, 1);
1218 continue;
1219 }
1220 if (original.isFloating() && (operation == ShortcutService.OPERATION_UPDATE)) {
1221 // Updating floating shortcuts doesn't affect the count, so ignore.
1222 continue;
1223 }
1224
1225 // If it's add() or update(), then need to decrement for the previous activity.
1226 // Skip it for set() since it's already been taken care of by not counting the original
1227 // dynamic shortcuts in the first loop.
1228 if (operation != ShortcutService.OPERATION_SET) {
1229 final ComponentName oldActivity = original.getActivity();
1230 if (!original.isFloating()) {
1231 incrementCountForActivity(counts, oldActivity, -1);
1232 }
1233 }
1234 incrementCountForActivity(counts, newActivity, 1);
1235 }
1236
1237 // Then make sure none of the activities have more than the max number of shortcuts.
1238 for (int i = counts.size() - 1; i >= 0; i--) {
1239 service.enforceMaxActivityShortcuts(counts.valueAt(i));
1240 }
1241 }
1242
Makoto Onuki157b1622016-06-02 16:13:10 -07001243 /**
1244 * For all the text fields, refresh the string values if they're from resources.
1245 */
1246 public void resolveResourceStrings() {
1247 final ShortcutService s = mShortcutUser.mService;
1248 boolean changed = false;
1249
1250 Resources publisherRes = null;
1251 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1252 final ShortcutInfo si = mShortcuts.valueAt(i);
1253
1254 if (si.hasStringResources()) {
1255 changed = true;
1256
1257 if (publisherRes == null) {
1258 publisherRes = getPackageResources();
1259 if (publisherRes == null) {
1260 break; // Resources couldn't be loaded.
1261 }
1262 }
1263
1264 si.resolveResourceStrings(publisherRes);
1265 si.setTimestamp(s.injectCurrentTimeMillis());
1266 }
1267 }
1268 if (changed) {
Makoto Onuki4e6cef42016-07-13 16:14:01 -07001269 s.packageShortcutsChanged(getPackageName(), getPackageUserId());
Makoto Onuki157b1622016-06-02 16:13:10 -07001270 }
1271 }
1272
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001273 /** Clears the implicit ranks for all shortcuts. */
1274 public void clearAllImplicitRanks() {
1275 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1276 final ShortcutInfo si = mShortcuts.valueAt(i);
1277 si.clearImplicitRankAndRankChangedFlag();
1278 }
1279 }
1280
1281 /**
1282 * Used to sort shortcuts for rank auto-adjusting.
1283 */
1284 final Comparator<ShortcutInfo> mShortcutRankComparator = (ShortcutInfo a, ShortcutInfo b) -> {
1285 // First, sort by rank.
1286 int ret = Integer.compare(a.getRank(), b.getRank());
1287 if (ret != 0) {
1288 return ret;
1289 }
1290 // When ranks are tie, then prioritize the ones that have just been assigned new ranks.
1291 // e.g. when there are 3 shortcuts, "s1" "s2" and "s3" with rank 0, 1, 2 respectively,
1292 // adding a shortcut "s4" with rank 1 will "insert" it between "s1" and "s2", because
1293 // "s2" and "s4" have the same rank 1 but s4 has isRankChanged() set.
1294 // Similarly, updating s3's rank to 1 will insert it between s1 and s2.
1295 if (a.isRankChanged() != b.isRankChanged()) {
1296 return a.isRankChanged() ? -1 : 1;
1297 }
1298 // If they're still tie, sort by implicit rank -- i.e. preserve the order in which
1299 // they're passed to the API.
1300 ret = Integer.compare(a.getImplicitRank(), b.getImplicitRank());
1301 if (ret != 0) {
1302 return ret;
1303 }
Makoto Onukia4f89b12017-10-05 10:37:55 -07001304 // If they're still tie, just sort by their IDs.
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001305 // This may happen with updateShortcuts() -- see
1306 // the testUpdateShortcuts_noManifestShortcuts() test.
1307 return a.getId().compareTo(b.getId());
1308 };
1309
1310 /**
1311 * Re-calculate the ranks for all shortcuts.
1312 */
1313 public void adjustRanks() {
1314 final ShortcutService s = mShortcutUser.mService;
1315 final long now = s.injectCurrentTimeMillis();
1316
1317 // First, clear ranks for floating shortcuts.
1318 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1319 final ShortcutInfo si = mShortcuts.valueAt(i);
1320 if (si.isFloating()) {
1321 if (si.getRank() != 0) {
1322 si.setTimestamp(now);
1323 si.setRank(0);
1324 }
1325 }
1326 }
1327
1328 // Then adjust ranks. Ranks are unique for each activity, so we first need to sort
1329 // shortcuts to each activity.
1330 // Then sort the shortcuts within each activity with mShortcutRankComparator, and
1331 // assign ranks from 0.
1332 final ArrayMap<ComponentName, ArrayList<ShortcutInfo>> all =
1333 sortShortcutsToActivities();
1334 for (int outer = all.size() - 1; outer >= 0; outer--) { // For each activity.
1335 final ArrayList<ShortcutInfo> list = all.valueAt(outer);
1336
1337 // Sort by ranks and other signals.
1338 Collections.sort(list, mShortcutRankComparator);
1339
1340 int rank = 0;
1341
1342 final int size = list.size();
1343 for (int i = 0; i < size; i++) {
1344 final ShortcutInfo si = list.get(i);
1345 if (si.isManifestShortcut()) {
1346 // Don't adjust ranks for manifest shortcuts.
1347 continue;
1348 }
Mehdi Alizadeh505fb762020-01-21 17:26:24 -08001349 if (si.isCached() && !si.isDynamic()) {
1350 // Don't adjust ranks for cached shortcuts that are not dynamic anymore.
1351 continue;
1352 }
Makoto Onuki99302b52017-03-29 12:42:26 -07001353 // At this point, it must be dynamic.
1354 if (!si.isDynamic()) {
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001355 s.wtf("Non-dynamic shortcut found.");
1356 continue;
1357 }
1358 final int thisRank = rank++;
1359 if (si.getRank() != thisRank) {
1360 si.setTimestamp(now);
1361 si.setRank(thisRank);
1362 }
1363 }
1364 }
1365 }
1366
Makoto Onukifc4cf2d2016-08-24 11:10:26 -07001367 /** @return true if there's any shortcuts that are not manifest shortcuts. */
1368 public boolean hasNonManifestShortcuts() {
1369 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1370 final ShortcutInfo si = mShortcuts.valueAt(i);
1371 if (!si.isDeclaredInManifest()) {
1372 return true;
1373 }
1374 }
1375 return false;
1376 }
1377
Makoto Onuki20b82212017-10-04 15:03:50 -07001378 public void dump(@NonNull PrintWriter pw, @NonNull String prefix, DumpFilter filter) {
Makoto Onuki31459242016-03-22 11:12:18 -07001379 pw.println();
1380
1381 pw.print(prefix);
1382 pw.print("Package: ");
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001383 pw.print(getPackageName());
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001384 pw.print(" UID: ");
1385 pw.print(mPackageUid);
Makoto Onuki31459242016-03-22 11:12:18 -07001386 pw.println();
1387
1388 pw.print(prefix);
1389 pw.print(" ");
1390 pw.print("Calls: ");
Makoto Onuki7d0fa812018-02-21 11:24:43 -08001391 pw.print(getApiCallCount(/*unlimited=*/ false));
Makoto Onuki31459242016-03-22 11:12:18 -07001392 pw.println();
1393
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001394 // getApiCallCount() may have updated mLastKnownForegroundElapsedTime.
1395 pw.print(prefix);
1396 pw.print(" ");
1397 pw.print("Last known FG: ");
1398 pw.print(mLastKnownForegroundElapsedTime);
1399 pw.println();
1400
Makoto Onuki31459242016-03-22 11:12:18 -07001401 // This should be after getApiCallCount(), which may update it.
1402 pw.print(prefix);
1403 pw.print(" ");
1404 pw.print("Last reset: [");
1405 pw.print(mLastResetTime);
1406 pw.print("] ");
Makoto Onukic51b2872016-05-04 15:24:50 -07001407 pw.print(ShortcutService.formatTime(mLastResetTime));
Makoto Onuki31459242016-03-22 11:12:18 -07001408 pw.println();
1409
Makoto Onukic51b2872016-05-04 15:24:50 -07001410 getPackageInfo().dump(pw, prefix + " ");
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001411 pw.println();
1412
Makoto Onuki39686e82016-04-13 18:03:00 -07001413 pw.print(prefix);
1414 pw.println(" Shortcuts:");
Makoto Onuki31459242016-03-22 11:12:18 -07001415 long totalBitmapSize = 0;
1416 final ArrayMap<String, ShortcutInfo> shortcuts = mShortcuts;
1417 final int size = shortcuts.size();
1418 for (int i = 0; i < size; i++) {
1419 final ShortcutInfo si = shortcuts.valueAt(i);
Makoto Onuki6208c672017-10-02 16:20:35 -07001420 pw.println(si.toDumpString(prefix + " "));
Makoto Onuki31459242016-03-22 11:12:18 -07001421 if (si.getBitmapPath() != null) {
1422 final long len = new File(si.getBitmapPath()).length();
Makoto Onuki39686e82016-04-13 18:03:00 -07001423 pw.print(prefix);
1424 pw.print(" ");
Makoto Onuki31459242016-03-22 11:12:18 -07001425 pw.print("bitmap size=");
1426 pw.println(len);
1427
1428 totalBitmapSize += len;
1429 }
1430 }
1431 pw.print(prefix);
1432 pw.print(" ");
1433 pw.print("Total bitmap size: ");
1434 pw.print(totalBitmapSize);
1435 pw.print(" (");
Makoto Onukic51b2872016-05-04 15:24:50 -07001436 pw.print(Formatter.formatFileSize(mShortcutUser.mService.mContext, totalBitmapSize));
Makoto Onuki31459242016-03-22 11:12:18 -07001437 pw.println(")");
1438 }
1439
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001440 @Override
Makoto Onuki76269922016-07-15 14:58:54 -07001441 public JSONObject dumpCheckin(boolean clear) throws JSONException {
1442 final JSONObject result = super.dumpCheckin(clear);
1443
1444 int numDynamic = 0;
1445 int numPinned = 0;
1446 int numManifest = 0;
1447 int numBitmaps = 0;
1448 long totalBitmapSize = 0;
1449
1450 final ArrayMap<String, ShortcutInfo> shortcuts = mShortcuts;
1451 final int size = shortcuts.size();
1452 for (int i = 0; i < size; i++) {
1453 final ShortcutInfo si = shortcuts.valueAt(i);
1454
1455 if (si.isDynamic()) numDynamic++;
1456 if (si.isDeclaredInManifest()) numManifest++;
1457 if (si.isPinned()) numPinned++;
1458
1459 if (si.getBitmapPath() != null) {
1460 numBitmaps++;
1461 totalBitmapSize += new File(si.getBitmapPath()).length();
1462 }
1463 }
1464
1465 result.put(KEY_DYNAMIC, numDynamic);
1466 result.put(KEY_MANIFEST, numManifest);
1467 result.put(KEY_PINNED, numPinned);
1468 result.put(KEY_BITMAPS, numBitmaps);
1469 result.put(KEY_BITMAP_BYTES, totalBitmapSize);
1470
1471 // TODO Log update frequency too.
1472
1473 return result;
1474 }
1475
1476 @Override
Makoto Onuki0acbb142016-03-22 17:02:57 -07001477 public void saveToXml(@NonNull XmlSerializer out, boolean forBackup)
1478 throws IOException, XmlPullParserException {
Makoto Onuki31459242016-03-22 11:12:18 -07001479 final int size = mShortcuts.size();
Mehdi Alizadehabec3192019-06-27 18:06:15 -07001480 final int shareTargetSize = mShareTargets.size();
Makoto Onuki31459242016-03-22 11:12:18 -07001481
Mehdi Alizadehabec3192019-06-27 18:06:15 -07001482 if (size == 0 && shareTargetSize == 0 && mApiCallCount == 0) {
Makoto Onuki31459242016-03-22 11:12:18 -07001483 return; // nothing to write.
1484 }
1485
1486 out.startTag(null, TAG_ROOT);
1487
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001488 ShortcutService.writeAttr(out, ATTR_NAME, getPackageName());
Makoto Onuki31459242016-03-22 11:12:18 -07001489 ShortcutService.writeAttr(out, ATTR_CALL_COUNT, mApiCallCount);
1490 ShortcutService.writeAttr(out, ATTR_LAST_RESET, mLastResetTime);
Makoto Onukie3fffa92018-02-28 16:25:40 -08001491 getPackageInfo().saveToXml(mShortcutUser.mService, out, forBackup);
Makoto Onuki31459242016-03-22 11:12:18 -07001492
1493 for (int j = 0; j < size; j++) {
Makoto Onukia4f89b12017-10-05 10:37:55 -07001494 saveShortcut(out, mShortcuts.valueAt(j), forBackup,
1495 getPackageInfo().isBackupAllowed());
Makoto Onuki31459242016-03-22 11:12:18 -07001496 }
1497
Mehdi Alizadehabec3192019-06-27 18:06:15 -07001498 if (!forBackup) {
1499 for (int j = 0; j < shareTargetSize; j++) {
1500 mShareTargets.get(j).saveToXml(out);
1501 }
1502 }
1503
Makoto Onuki31459242016-03-22 11:12:18 -07001504 out.endTag(null, TAG_ROOT);
1505 }
1506
Makoto Onukia4f89b12017-10-05 10:37:55 -07001507 private void saveShortcut(XmlSerializer out, ShortcutInfo si, boolean forBackup,
1508 boolean appSupportsBackup)
Makoto Onuki31459242016-03-22 11:12:18 -07001509 throws IOException, XmlPullParserException {
Makoto Onuki475c3652017-05-08 14:29:03 -07001510
1511 final ShortcutService s = mShortcutUser.mService;
1512
Makoto Onuki0acbb142016-03-22 17:02:57 -07001513 if (forBackup) {
Makoto Onukif3ba2e02016-07-12 09:18:50 -07001514 if (!(si.isPinned() && si.isEnabled())) {
Makoto Onukia4f89b12017-10-05 10:37:55 -07001515 // We only backup pinned shortcuts that are enabled.
1516 // Note, this means, shortcuts that are restored but are blocked restore, e.g. due
1517 // to a lower version code, will not be ported to a new device.
1518 return;
Makoto Onuki0acbb142016-03-22 17:02:57 -07001519 }
1520 }
Makoto Onukia4f89b12017-10-05 10:37:55 -07001521 final boolean shouldBackupDetails =
1522 !forBackup // It's not backup
1523 || appSupportsBackup; // Or, it's a backup and app supports backup.
1524
Makoto Onuki475c3652017-05-08 14:29:03 -07001525 // Note: at this point no shortcuts should have bitmaps pending save, but if they do,
1526 // just remove the bitmap.
1527 if (si.isIconPendingSave()) {
1528 s.removeIconLocked(si);
1529 }
Makoto Onuki31459242016-03-22 11:12:18 -07001530 out.startTag(null, TAG_SHORTCUT);
1531 ShortcutService.writeAttr(out, ATTR_ID, si.getId());
1532 // writeAttr(out, "package", si.getPackageName()); // not needed
Makoto Onuki22fcc682016-05-17 14:52:19 -07001533 ShortcutService.writeAttr(out, ATTR_ACTIVITY, si.getActivity());
Makoto Onuki31459242016-03-22 11:12:18 -07001534 // writeAttr(out, "icon", si.getIcon()); // We don't save it.
1535 ShortcutService.writeAttr(out, ATTR_TITLE, si.getTitle());
Makoto Onuki20c95f82016-05-11 16:51:01 -07001536 ShortcutService.writeAttr(out, ATTR_TITLE_RES_ID, si.getTitleResId());
Makoto Onuki157b1622016-06-02 16:13:10 -07001537 ShortcutService.writeAttr(out, ATTR_TITLE_RES_NAME, si.getTitleResName());
Makoto Onukie3ae7ec2016-03-29 15:45:25 -07001538 ShortcutService.writeAttr(out, ATTR_TEXT, si.getText());
Makoto Onuki20c95f82016-05-11 16:51:01 -07001539 ShortcutService.writeAttr(out, ATTR_TEXT_RES_ID, si.getTextResId());
Makoto Onuki157b1622016-06-02 16:13:10 -07001540 ShortcutService.writeAttr(out, ATTR_TEXT_RES_NAME, si.getTextResName());
Makoto Onukia4f89b12017-10-05 10:37:55 -07001541 if (shouldBackupDetails) {
1542 ShortcutService.writeAttr(out, ATTR_DISABLED_MESSAGE, si.getDisabledMessage());
1543 ShortcutService.writeAttr(out, ATTR_DISABLED_MESSAGE_RES_ID,
1544 si.getDisabledMessageResourceId());
1545 ShortcutService.writeAttr(out, ATTR_DISABLED_MESSAGE_RES_NAME,
1546 si.getDisabledMessageResName());
1547 }
1548 ShortcutService.writeAttr(out, ATTR_DISABLED_REASON, si.getDisabledReason());
Makoto Onuki31459242016-03-22 11:12:18 -07001549 ShortcutService.writeAttr(out, ATTR_TIMESTAMP,
1550 si.getLastChangedTimestamp());
Adam Hed4586b12019-03-19 12:01:00 -07001551 final LocusId locusId = si.getLocusId();
1552 if (locusId != null) {
1553 ShortcutService.writeAttr(out, ATTR_LOCUS_ID, si.getLocusId().getId());
1554 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07001555 if (forBackup) {
1556 // Don't write icon information. Also drop the dynamic flag.
Makoto Onukia4f89b12017-10-05 10:37:55 -07001557
1558 int flags = si.getFlags() &
1559 ~(ShortcutInfo.FLAG_HAS_ICON_FILE | ShortcutInfo.FLAG_HAS_ICON_RES
Makoto Onuki475c3652017-05-08 14:29:03 -07001560 | ShortcutInfo.FLAG_ICON_FILE_PENDING_SAVE
Makoto Onukia4f89b12017-10-05 10:37:55 -07001561 | ShortcutInfo.FLAG_DYNAMIC);
1562 ShortcutService.writeAttr(out, ATTR_FLAGS, flags);
1563
1564 // Set the publisher version code at every backup.
Dianne Hackborn3accca02013-09-20 09:32:11 -07001565 final long packageVersionCode = getPackageInfo().getVersionCode();
Makoto Onukia4f89b12017-10-05 10:37:55 -07001566 if (packageVersionCode == 0) {
1567 s.wtf("Package version code should be available at this point.");
1568 // However, 0 is a valid version code, so we just go ahead with it...
1569 }
Makoto Onuki0acbb142016-03-22 17:02:57 -07001570 } else {
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001571 // When writing for backup, ranks shouldn't be saved, since shortcuts won't be restored
1572 // as dynamic.
1573 ShortcutService.writeAttr(out, ATTR_RANK, si.getRank());
1574
Makoto Onuki0acbb142016-03-22 17:02:57 -07001575 ShortcutService.writeAttr(out, ATTR_FLAGS, si.getFlags());
Makoto Onuki157b1622016-06-02 16:13:10 -07001576 ShortcutService.writeAttr(out, ATTR_ICON_RES_ID, si.getIconResourceId());
1577 ShortcutService.writeAttr(out, ATTR_ICON_RES_NAME, si.getIconResName());
Makoto Onuki0acbb142016-03-22 17:02:57 -07001578 ShortcutService.writeAttr(out, ATTR_BITMAP_PATH, si.getBitmapPath());
1579 }
Makoto Onuki31459242016-03-22 11:12:18 -07001580
Makoto Onukia4f89b12017-10-05 10:37:55 -07001581 if (shouldBackupDetails) {
1582 {
1583 final Set<String> cat = si.getCategories();
1584 if (cat != null && cat.size() > 0) {
1585 out.startTag(null, TAG_CATEGORIES);
1586 XmlUtils.writeStringArrayXml(cat.toArray(new String[cat.size()]),
1587 NAME_CATEGORIES, out);
1588 out.endTag(null, TAG_CATEGORIES);
1589 }
Makoto Onukib6d35232016-04-04 15:57:17 -07001590 }
Mehdi Alizadehebb4b602019-02-05 15:52:18 -08001591 if (!forBackup) { // Don't backup the persons field.
1592 final Person[] persons = si.getPersons();
1593 if (!ArrayUtils.isEmpty(persons)) {
1594 for (int i = 0; i < persons.length; i++) {
1595 final Person p = persons[i];
1596
1597 out.startTag(null, TAG_PERSON);
1598 ShortcutService.writeAttr(out, ATTR_PERSON_NAME, p.getName());
1599 ShortcutService.writeAttr(out, ATTR_PERSON_URI, p.getUri());
1600 ShortcutService.writeAttr(out, ATTR_PERSON_KEY, p.getKey());
1601 ShortcutService.writeAttr(out, ATTR_PERSON_IS_BOT, p.isBot());
1602 ShortcutService.writeAttr(out, ATTR_PERSON_IS_IMPORTANT, p.isImportant());
1603 out.endTag(null, TAG_PERSON);
1604 }
1605 }
1606 }
Makoto Onukia4f89b12017-10-05 10:37:55 -07001607 final Intent[] intentsNoExtras = si.getIntentsNoExtras();
1608 final PersistableBundle[] intentsExtras = si.getIntentPersistableExtrases();
1609 final int numIntents = intentsNoExtras.length;
1610 for (int i = 0; i < numIntents; i++) {
1611 out.startTag(null, TAG_INTENT);
1612 ShortcutService.writeAttr(out, ATTR_INTENT_NO_EXTRA, intentsNoExtras[i]);
1613 ShortcutService.writeTagExtra(out, TAG_EXTRAS, intentsExtras[i]);
1614 out.endTag(null, TAG_INTENT);
1615 }
Makoto Onuki99302b52017-03-29 12:42:26 -07001616
Makoto Onukia4f89b12017-10-05 10:37:55 -07001617 ShortcutService.writeTagExtra(out, TAG_EXTRAS, si.getExtras());
1618 }
Hakan Seyalioglu58fc95d2016-12-13 15:23:22 -08001619
Makoto Onuki31459242016-03-22 11:12:18 -07001620 out.endTag(null, TAG_SHORTCUT);
1621 }
1622
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001623 public static ShortcutPackage loadFromXml(ShortcutService s, ShortcutUser shortcutUser,
1624 XmlPullParser parser, boolean fromBackup)
Makoto Onuki31459242016-03-22 11:12:18 -07001625 throws IOException, XmlPullParserException {
1626
1627 final String packageName = ShortcutService.parseStringAttribute(parser,
1628 ATTR_NAME);
1629
Makoto Onukic51b2872016-05-04 15:24:50 -07001630 final ShortcutPackage ret = new ShortcutPackage(shortcutUser,
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001631 shortcutUser.getUserId(), packageName);
Makoto Onuki31459242016-03-22 11:12:18 -07001632
Makoto Onuki31459242016-03-22 11:12:18 -07001633 ret.mApiCallCount =
1634 ShortcutService.parseIntAttribute(parser, ATTR_CALL_COUNT);
1635 ret.mLastResetTime =
1636 ShortcutService.parseLongAttribute(parser, ATTR_LAST_RESET);
1637
Makoto Onukia4f89b12017-10-05 10:37:55 -07001638
Makoto Onuki31459242016-03-22 11:12:18 -07001639 final int outerDepth = parser.getDepth();
1640 int type;
1641 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1642 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1643 if (type != XmlPullParser.START_TAG) {
1644 continue;
1645 }
1646 final int depth = parser.getDepth();
1647 final String tag = parser.getName();
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001648 if (depth == outerDepth + 1) {
1649 switch (tag) {
1650 case ShortcutPackageInfo.TAG_ROOT:
Makoto Onuki2e210c42016-03-30 08:30:36 -07001651 ret.getPackageInfo().loadFromXml(parser, fromBackup);
Makoto Onukia4f89b12017-10-05 10:37:55 -07001652
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001653 continue;
1654 case TAG_SHORTCUT:
Makoto Onuki4d36b3a2016-04-27 12:00:17 -07001655 final ShortcutInfo si = parseShortcut(parser, packageName,
Makoto Onukia4f89b12017-10-05 10:37:55 -07001656 shortcutUser.getUserId(), fromBackup);
Makoto Onuki31459242016-03-22 11:12:18 -07001657
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001658 // Don't use addShortcut(), we don't need to save the icon.
1659 ret.mShortcuts.put(si.getId(), si);
1660 continue;
Mehdi Alizadehabec3192019-06-27 18:06:15 -07001661 case TAG_SHARE_TARGET:
1662 ret.mShareTargets.add(ShareTargetInfo.loadFromXml(parser));
1663 continue;
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001664 }
Makoto Onuki31459242016-03-22 11:12:18 -07001665 }
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001666 ShortcutService.warnForInvalidTag(depth, tag);
1667 }
Makoto Onuki31459242016-03-22 11:12:18 -07001668 return ret;
1669 }
1670
Makoto Onukiabe84422016-04-07 09:41:19 -07001671 private static ShortcutInfo parseShortcut(XmlPullParser parser, String packageName,
Makoto Onukia4f89b12017-10-05 10:37:55 -07001672 @UserIdInt int userId, boolean fromBackup)
1673 throws IOException, XmlPullParserException {
Makoto Onuki31459242016-03-22 11:12:18 -07001674 String id;
1675 ComponentName activityComponent;
1676 // Icon icon;
1677 String title;
Makoto Onuki20c95f82016-05-11 16:51:01 -07001678 int titleResId;
Makoto Onuki157b1622016-06-02 16:13:10 -07001679 String titleResName;
Makoto Onukie3ae7ec2016-03-29 15:45:25 -07001680 String text;
Makoto Onuki20c95f82016-05-11 16:51:01 -07001681 int textResId;
Makoto Onuki157b1622016-06-02 16:13:10 -07001682 String textResName;
Makoto Onuki20c95f82016-05-11 16:51:01 -07001683 String disabledMessage;
1684 int disabledMessageResId;
Makoto Onuki157b1622016-06-02 16:13:10 -07001685 String disabledMessageResName;
Makoto Onukia4f89b12017-10-05 10:37:55 -07001686 int disabledReason;
Makoto Onuki440a1ea2016-07-20 14:21:18 -07001687 Intent intentLegacy;
1688 PersistableBundle intentPersistableExtrasLegacy = null;
1689 ArrayList<Intent> intents = new ArrayList<>();
Makoto Onuki20c95f82016-05-11 16:51:01 -07001690 int rank;
Makoto Onuki31459242016-03-22 11:12:18 -07001691 PersistableBundle extras = null;
1692 long lastChangedTimestamp;
1693 int flags;
Makoto Onuki157b1622016-06-02 16:13:10 -07001694 int iconResId;
1695 String iconResName;
Makoto Onuki31459242016-03-22 11:12:18 -07001696 String bitmapPath;
Adam Hed4586b12019-03-19 12:01:00 -07001697 final String locusIdString;
Makoto Onukia4f89b12017-10-05 10:37:55 -07001698 int backupVersionCode;
Makoto Onukibe73a802016-04-15 14:46:35 -07001699 ArraySet<String> categories = null;
Mehdi Alizadehebb4b602019-02-05 15:52:18 -08001700 ArrayList<Person> persons = new ArrayList<>();
Makoto Onuki31459242016-03-22 11:12:18 -07001701
1702 id = ShortcutService.parseStringAttribute(parser, ATTR_ID);
1703 activityComponent = ShortcutService.parseComponentNameAttribute(parser,
1704 ATTR_ACTIVITY);
1705 title = ShortcutService.parseStringAttribute(parser, ATTR_TITLE);
Makoto Onuki20c95f82016-05-11 16:51:01 -07001706 titleResId = ShortcutService.parseIntAttribute(parser, ATTR_TITLE_RES_ID);
Makoto Onuki157b1622016-06-02 16:13:10 -07001707 titleResName = ShortcutService.parseStringAttribute(parser, ATTR_TITLE_RES_NAME);
Makoto Onukie3ae7ec2016-03-29 15:45:25 -07001708 text = ShortcutService.parseStringAttribute(parser, ATTR_TEXT);
Makoto Onuki20c95f82016-05-11 16:51:01 -07001709 textResId = ShortcutService.parseIntAttribute(parser, ATTR_TEXT_RES_ID);
Makoto Onuki157b1622016-06-02 16:13:10 -07001710 textResName = ShortcutService.parseStringAttribute(parser, ATTR_TEXT_RES_NAME);
Makoto Onuki20c95f82016-05-11 16:51:01 -07001711 disabledMessage = ShortcutService.parseStringAttribute(parser, ATTR_DISABLED_MESSAGE);
1712 disabledMessageResId = ShortcutService.parseIntAttribute(parser,
1713 ATTR_DISABLED_MESSAGE_RES_ID);
Makoto Onuki157b1622016-06-02 16:13:10 -07001714 disabledMessageResName = ShortcutService.parseStringAttribute(parser,
1715 ATTR_DISABLED_MESSAGE_RES_NAME);
Makoto Onukia4f89b12017-10-05 10:37:55 -07001716 disabledReason = ShortcutService.parseIntAttribute(parser, ATTR_DISABLED_REASON);
Makoto Onuki440a1ea2016-07-20 14:21:18 -07001717 intentLegacy = ShortcutService.parseIntentAttributeNoDefault(parser, ATTR_INTENT_LEGACY);
Makoto Onuki20c95f82016-05-11 16:51:01 -07001718 rank = (int) ShortcutService.parseLongAttribute(parser, ATTR_RANK);
Makoto Onuki9da23fc2016-03-29 11:14:42 -07001719 lastChangedTimestamp = ShortcutService.parseLongAttribute(parser, ATTR_TIMESTAMP);
Makoto Onuki31459242016-03-22 11:12:18 -07001720 flags = (int) ShortcutService.parseLongAttribute(parser, ATTR_FLAGS);
Makoto Onuki157b1622016-06-02 16:13:10 -07001721 iconResId = (int) ShortcutService.parseLongAttribute(parser, ATTR_ICON_RES_ID);
1722 iconResName = ShortcutService.parseStringAttribute(parser, ATTR_ICON_RES_NAME);
Makoto Onuki31459242016-03-22 11:12:18 -07001723 bitmapPath = ShortcutService.parseStringAttribute(parser, ATTR_BITMAP_PATH);
Adam Hed4586b12019-03-19 12:01:00 -07001724 locusIdString = ShortcutService.parseStringAttribute(parser, ATTR_LOCUS_ID);
Makoto Onuki31459242016-03-22 11:12:18 -07001725
1726 final int outerDepth = parser.getDepth();
1727 int type;
1728 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1729 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1730 if (type != XmlPullParser.START_TAG) {
1731 continue;
1732 }
1733 final int depth = parser.getDepth();
1734 final String tag = parser.getName();
1735 if (ShortcutService.DEBUG_LOAD) {
1736 Slog.d(TAG, String.format(" depth=%d type=%d name=%s",
1737 depth, type, tag));
1738 }
1739 switch (tag) {
Makoto Onuki440a1ea2016-07-20 14:21:18 -07001740 case TAG_INTENT_EXTRAS_LEGACY:
1741 intentPersistableExtrasLegacy = PersistableBundle.restoreFromXml(parser);
1742 continue;
1743 case TAG_INTENT:
1744 intents.add(parseIntent(parser));
Makoto Onuki31459242016-03-22 11:12:18 -07001745 continue;
1746 case TAG_EXTRAS:
1747 extras = PersistableBundle.restoreFromXml(parser);
1748 continue;
Makoto Onukib6d35232016-04-04 15:57:17 -07001749 case TAG_CATEGORIES:
1750 // This just contains string-array.
1751 continue;
Mehdi Alizadehebb4b602019-02-05 15:52:18 -08001752 case TAG_PERSON:
1753 persons.add(parsePerson(parser));
1754 continue;
Makoto Onukib6d35232016-04-04 15:57:17 -07001755 case TAG_STRING_ARRAY_XMLUTILS:
1756 if (NAME_CATEGORIES.equals(ShortcutService.parseStringAttribute(parser,
1757 ATTR_NAME_XMLUTILS))) {
Makoto Onukibe73a802016-04-15 14:46:35 -07001758 final String[] ar = XmlUtils.readThisStringArrayXml(
1759 parser, TAG_STRING_ARRAY_XMLUTILS, null);
1760 categories = new ArraySet<>(ar.length);
1761 for (int i = 0; i < ar.length; i++) {
1762 categories.add(ar[i]);
1763 }
Makoto Onukib6d35232016-04-04 15:57:17 -07001764 }
1765 continue;
Makoto Onuki31459242016-03-22 11:12:18 -07001766 }
1767 throw ShortcutService.throwForInvalidTag(depth, tag);
1768 }
Makoto Onukibe73a802016-04-15 14:46:35 -07001769
Makoto Onuki440a1ea2016-07-20 14:21:18 -07001770 if (intentLegacy != null) {
1771 // For the legacy file format which supported only one intent per shortcut.
1772 ShortcutInfo.setIntentExtras(intentLegacy, intentPersistableExtrasLegacy);
1773 intents.clear();
1774 intents.add(intentLegacy);
1775 }
Makoto Onuki9fd90192017-01-06 18:31:03 +00001776
Makoto Onukia4f89b12017-10-05 10:37:55 -07001777
1778 if ((disabledReason == ShortcutInfo.DISABLED_REASON_NOT_DISABLED)
1779 && ((flags & ShortcutInfo.FLAG_DISABLED) != 0)) {
1780 // We didn't used to have the disabled reason, so if a shortcut is disabled
1781 // and has no reason, we assume it was disabled by publisher.
1782 disabledReason = ShortcutInfo.DISABLED_REASON_BY_APP;
1783 }
1784
1785 // All restored shortcuts are initially "shadow".
1786 if (fromBackup) {
1787 flags |= ShortcutInfo.FLAG_SHADOW;
1788 }
1789
Adam Hed4586b12019-03-19 12:01:00 -07001790 final LocusId locusId = locusIdString == null ? null : new LocusId(locusIdString);
Felipe Leme90205ef2019-03-05 09:59:52 -08001791
Makoto Onuki31459242016-03-22 11:12:18 -07001792 return new ShortcutInfo(
Felipe Leme90205ef2019-03-05 09:59:52 -08001793 userId, id, packageName, activityComponent, /* icon= */ null,
Makoto Onuki157b1622016-06-02 16:13:10 -07001794 title, titleResId, titleResName, text, textResId, textResName,
1795 disabledMessage, disabledMessageResId, disabledMessageResName,
Makoto Onuki440a1ea2016-07-20 14:21:18 -07001796 categories,
1797 intents.toArray(new Intent[intents.size()]),
1798 rank, extras, lastChangedTimestamp, flags,
Mehdi Alizadehebb4b602019-02-05 15:52:18 -08001799 iconResId, iconResName, bitmapPath, disabledReason,
Felipe Leme90205ef2019-03-05 09:59:52 -08001800 persons.toArray(new Person[persons.size()]), locusId);
Makoto Onuki31459242016-03-22 11:12:18 -07001801 }
Makoto Onuki2e210c42016-03-30 08:30:36 -07001802
Makoto Onuki440a1ea2016-07-20 14:21:18 -07001803 private static Intent parseIntent(XmlPullParser parser)
1804 throws IOException, XmlPullParserException {
1805
1806 Intent intent = ShortcutService.parseIntentAttribute(parser,
1807 ATTR_INTENT_NO_EXTRA);
1808
1809 final int outerDepth = parser.getDepth();
1810 int type;
1811 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1812 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1813 if (type != XmlPullParser.START_TAG) {
1814 continue;
1815 }
1816 final int depth = parser.getDepth();
1817 final String tag = parser.getName();
1818 if (ShortcutService.DEBUG_LOAD) {
1819 Slog.d(TAG, String.format(" depth=%d type=%d name=%s",
1820 depth, type, tag));
1821 }
1822 switch (tag) {
1823 case TAG_EXTRAS:
1824 ShortcutInfo.setIntentExtras(intent,
1825 PersistableBundle.restoreFromXml(parser));
1826 continue;
1827 }
1828 throw ShortcutService.throwForInvalidTag(depth, tag);
1829 }
1830 return intent;
1831 }
1832
Mehdi Alizadehebb4b602019-02-05 15:52:18 -08001833 private static Person parsePerson(XmlPullParser parser)
1834 throws IOException, XmlPullParserException {
1835 CharSequence name = ShortcutService.parseStringAttribute(parser, ATTR_PERSON_NAME);
1836 String uri = ShortcutService.parseStringAttribute(parser, ATTR_PERSON_URI);
1837 String key = ShortcutService.parseStringAttribute(parser, ATTR_PERSON_KEY);
1838 boolean isBot = ShortcutService.parseBooleanAttribute(parser, ATTR_PERSON_IS_BOT);
1839 boolean isImportant = ShortcutService.parseBooleanAttribute(parser,
1840 ATTR_PERSON_IS_IMPORTANT);
1841
1842 Person.Builder builder = new Person.Builder();
1843 builder.setName(name).setUri(uri).setKey(key).setBot(isBot).setImportant(isImportant);
1844 return builder.build();
1845 }
1846
Makoto Onuki2e210c42016-03-30 08:30:36 -07001847 @VisibleForTesting
1848 List<ShortcutInfo> getAllShortcutsForTest() {
1849 return new ArrayList<>(mShortcuts.values());
1850 }
Makoto Onuki7001a612016-05-27 13:24:28 -07001851
Mehdi Alizadeh32774622018-11-05 17:32:01 -08001852 @VisibleForTesting
1853 List<ShareTargetInfo> getAllShareTargetsForTest() {
1854 return new ArrayList<>(mShareTargets);
1855 }
1856
Makoto Onuki7001a612016-05-27 13:24:28 -07001857 @Override
1858 public void verifyStates() {
1859 super.verifyStates();
1860
1861 boolean failed = false;
1862
Makoto Onuki255461f2017-01-10 11:47:25 -08001863 final ShortcutService s = mShortcutUser.mService;
1864
Makoto Onuki7001a612016-05-27 13:24:28 -07001865 final ArrayMap<ComponentName, ArrayList<ShortcutInfo>> all =
1866 sortShortcutsToActivities();
1867
1868 // Make sure each activity won't have more than max shortcuts.
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001869 for (int outer = all.size() - 1; outer >= 0; outer--) {
1870 final ArrayList<ShortcutInfo> list = all.valueAt(outer);
1871 if (list.size() > mShortcutUser.mService.getMaxActivityShortcuts()) {
Makoto Onuki7001a612016-05-27 13:24:28 -07001872 failed = true;
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001873 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": activity " + all.keyAt(outer)
1874 + " has " + all.valueAt(outer).size() + " shortcuts.");
Makoto Onuki7001a612016-05-27 13:24:28 -07001875 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001876
1877 // Sort by rank.
1878 Collections.sort(list, (a, b) -> Integer.compare(a.getRank(), b.getRank()));
1879
1880 // Split into two arrays for each kind.
1881 final ArrayList<ShortcutInfo> dynamicList = new ArrayList<>(list);
1882 dynamicList.removeIf((si) -> !si.isDynamic());
1883
1884 final ArrayList<ShortcutInfo> manifestList = new ArrayList<>(list);
1885 dynamicList.removeIf((si) -> !si.isManifestShortcut());
1886
1887 verifyRanksSequential(dynamicList);
1888 verifyRanksSequential(manifestList);
Makoto Onuki7001a612016-05-27 13:24:28 -07001889 }
1890
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001891 // Verify each shortcut's status.
Makoto Onuki7001a612016-05-27 13:24:28 -07001892 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1893 final ShortcutInfo si = mShortcuts.valueAt(i);
Mehdi Alizadeh505fb762020-01-21 17:26:24 -08001894 if (!(si.isDeclaredInManifest() || si.isDynamic() || si.isPinned() || si.isCached())) {
Makoto Onuki7001a612016-05-27 13:24:28 -07001895 failed = true;
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001896 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
Makoto Onuki99302b52017-03-29 12:42:26 -07001897 + " is not manifest, dynamic or pinned.");
Makoto Onuki7001a612016-05-27 13:24:28 -07001898 }
Makoto Onukiff14f732016-06-30 17:07:25 -07001899 if (si.isDeclaredInManifest() && si.isDynamic()) {
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001900 failed = true;
1901 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1902 + " is both dynamic and manifest at the same time.");
1903 }
Makoto Onuki255461f2017-01-10 11:47:25 -08001904 if (si.getActivity() == null && !si.isFloating()) {
Makoto Onuki7001a612016-05-27 13:24:28 -07001905 failed = true;
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001906 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
Makoto Onuki255461f2017-01-10 11:47:25 -08001907 + " has null activity, but not floating.");
Makoto Onuki7001a612016-05-27 13:24:28 -07001908 }
Makoto Onuki9fd90192017-01-06 18:31:03 +00001909 if ((si.isDynamic() || si.isManifestShortcut()) && !si.isEnabled()) {
Makoto Onuki7001a612016-05-27 13:24:28 -07001910 failed = true;
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001911 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
Makoto Onuki7001a612016-05-27 13:24:28 -07001912 + " is not floating, but is disabled.");
1913 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001914 if (si.isFloating() && si.getRank() != 0) {
1915 failed = true;
1916 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1917 + " is floating, but has rank=" + si.getRank());
1918 }
Makoto Onukidd097812016-06-29 13:10:09 -07001919 if (si.getIcon() != null) {
1920 failed = true;
1921 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1922 + " still has an icon");
1923 }
Hyunyoung Songe4179e22017-03-01 12:51:26 -08001924 if (si.hasAdaptiveBitmap() && !si.hasIconFile()) {
Hyunyoung Songf281e7a2017-02-13 10:57:42 -08001925 failed = true;
1926 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
Hyunyoung Songe4179e22017-03-01 12:51:26 -08001927 + " has adaptive bitmap but was not saved to a file.");
Hyunyoung Songf281e7a2017-02-13 10:57:42 -08001928 }
Makoto Onukidd097812016-06-29 13:10:09 -07001929 if (si.hasIconFile() && si.hasIconResource()) {
1930 failed = true;
1931 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1932 + " has both resource and bitmap icons");
1933 }
Makoto Onukia4f89b12017-10-05 10:37:55 -07001934 if (si.isEnabled()
1935 != (si.getDisabledReason() == ShortcutInfo.DISABLED_REASON_NOT_DISABLED)) {
1936 failed = true;
1937 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1938 + " isEnabled() and getDisabledReason() disagree: "
1939 + si.isEnabled() + " vs " + si.getDisabledReason());
1940 }
1941 if ((si.getDisabledReason() == ShortcutInfo.DISABLED_REASON_VERSION_LOWER)
1942 && (getPackageInfo().getBackupSourceVersionCode()
1943 == ShortcutInfo.VERSION_CODE_UNKNOWN)) {
1944 failed = true;
1945 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1946 + " RESTORED_VERSION_LOWER with no backup source version code.");
1947 }
Makoto Onuki255461f2017-01-10 11:47:25 -08001948 if (s.isDummyMainActivity(si.getActivity())) {
1949 failed = true;
1950 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1951 + " has a dummy target activity");
1952 }
Makoto Onuki7001a612016-05-27 13:24:28 -07001953 }
1954
1955 if (failed) {
Makoto Onuki9fd90192017-01-06 18:31:03 +00001956 throw new IllegalStateException("See logcat for errors");
Makoto Onuki7001a612016-05-27 13:24:28 -07001957 }
1958 }
Makoto Onuki9e1f5592016-06-08 12:30:23 -07001959
1960 private boolean verifyRanksSequential(List<ShortcutInfo> list) {
1961 boolean failed = false;
1962
1963 for (int i = 0; i < list.size(); i++) {
1964 final ShortcutInfo si = list.get(i);
1965 if (si.getRank() != i) {
1966 failed = true;
1967 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1968 + " rank=" + si.getRank() + " but expected to be "+ i);
1969 }
1970 }
1971 return failed;
1972 }
Makoto Onuki31459242016-03-22 11:12:18 -07001973}