1 /*
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  */
16 package com.android.server.pm;
17 
18 import static android.content.pm.ShortcutInfo.DISABLED_REASON_BACKUP_NOT_SUPPORTED;
19 import static android.content.pm.ShortcutInfo.DISABLED_REASON_NOT_DISABLED;
20 import static android.content.pm.ShortcutInfo.DISABLED_REASON_SIGNATURE_MISMATCH;
21 import static android.content.pm.ShortcutInfo.DISABLED_REASON_VERSION_LOWER;
22 
23 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.anyOrNull;
24 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.anyStringOrNull;
25 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertAllDisabled;
26 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertAllDynamic;
27 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertAllDynamicOrPinned;
28 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertAllEnabled;
29 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertAllHaveIntents;
30 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertAllHaveTitle;
31 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertAllImmutable;
32 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertAllKeyFieldsOnly;
33 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertAllManifest;
34 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertAllNotHaveIntents;
35 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertAllNotHaveTitle;
36 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertAllNotKeyFieldsOnly;
37 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertAllNotManifest;
38 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertAllPinned;
39 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertAllUnique;
40 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertBitmapSize;
41 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertBundleEmpty;
42 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertCallbackNotReceived;
43 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertCallbackReceived;
44 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertCannotUpdateImmutable;
45 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertDynamicAndPinned;
46 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertDynamicOnly;
47 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertDynamicShortcutCountExceeded;
48 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertEmpty;
49 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertExpectException;
50 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertForLauncherCallback;
51 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertShortcutIds;
52 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertWith;
53 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.filterByActivity;
54 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.findShortcut;
55 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.hashSet;
56 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.list;
57 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.makeBundle;
58 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.pfdToBitmap;
59 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.resetAll;
60 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.set;
61 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.waitOnMainThread;
62 
63 import static org.mockito.Matchers.any;
64 import static org.mockito.Matchers.anyInt;
65 import static org.mockito.Matchers.anyString;
66 import static org.mockito.Matchers.eq;
67 import static org.mockito.Mockito.doReturn;
68 import static org.mockito.Mockito.mock;
69 import static org.mockito.Mockito.reset;
70 import static org.mockito.Mockito.times;
71 import static org.mockito.Mockito.verify;
72 
73 import android.Manifest.permission;
74 import android.app.ActivityManager;
75 import android.content.ActivityNotFoundException;
76 import android.content.ComponentName;
77 import android.content.Intent;
78 import android.content.IntentFilter;
79 import android.content.pm.ApplicationInfo;
80 import android.content.pm.LauncherApps;
81 import android.content.pm.LauncherApps.PinItemRequest;
82 import android.content.pm.LauncherApps.ShortcutQuery;
83 import android.content.pm.PackageInfo;
84 import android.content.pm.ShortcutInfo;
85 import android.graphics.Bitmap;
86 import android.graphics.Bitmap.CompressFormat;
87 import android.graphics.BitmapFactory;
88 import android.graphics.drawable.AdaptiveIconDrawable;
89 import android.graphics.drawable.Drawable;
90 import android.graphics.drawable.Icon;
91 import android.net.Uri;
92 import android.os.Bundle;
93 import android.os.Handler;
94 import android.os.Looper;
95 import android.os.Process;
96 import android.os.UserHandle;
97 import android.test.suitebuilder.annotation.SmallTest;
98 import android.util.Log;
99 import android.util.SparseArray;
100 import android.util.Xml;
101 
102 import com.android.frameworks.servicestests.R;
103 import com.android.internal.util.FastXmlSerializer;
104 import com.android.server.pm.ShortcutService.ConfigConstants;
105 import com.android.server.pm.ShortcutService.FileOutputStreamWithPath;
106 import com.android.server.pm.ShortcutUser.PackageWithUser;
107 
108 import org.mockito.ArgumentCaptor;
109 import org.xmlpull.v1.XmlPullParser;
110 import org.xmlpull.v1.XmlPullParserException;
111 import org.xmlpull.v1.XmlSerializer;
112 
113 import java.io.ByteArrayInputStream;
114 import java.io.ByteArrayOutputStream;
115 import java.io.File;
116 import java.io.IOException;
117 import java.io.InputStreamReader;
118 import java.nio.charset.StandardCharsets;
119 import java.util.ArrayList;
120 import java.util.List;
121 import java.util.Locale;
122 import java.util.function.BiConsumer;
123 
124 /**
125  * Tests for ShortcutService and ShortcutManager.
126  *
127  m FrameworksServicesTests &&
128  adb install \
129  -r -g ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
130  adb shell am instrument -e class com.android.server.pm.ShortcutManagerTest1 \
131  -w com.android.frameworks.servicestests/androidx.test.runner.AndroidJUnitRunner
132  */
133 @SmallTest
134 public class ShortcutManagerTest1 extends BaseShortcutManagerTest {
135     /**
136      * Test for the first launch path, no settings file available.
137      */
testFirstInitialize()138     public void testFirstInitialize() {
139         assertResetTimes(START_TIME, START_TIME + INTERVAL);
140     }
141 
142     /**
143      * Test for {@link ShortcutService#getLastResetTimeLocked()} and
144      * {@link ShortcutService#getNextResetTimeLocked()}.
145      */
testUpdateAndGetNextResetTimeLocked()146     public void testUpdateAndGetNextResetTimeLocked() {
147         assertResetTimes(START_TIME, START_TIME + INTERVAL);
148 
149         // Advance clock.
150         mInjectedCurrentTimeMillis += 100;
151 
152         // Shouldn't have changed.
153         assertResetTimes(START_TIME, START_TIME + INTERVAL);
154 
155         // Advance clock, almost the reset time.
156         mInjectedCurrentTimeMillis = START_TIME + INTERVAL - 1;
157 
158         // Shouldn't have changed.
159         assertResetTimes(START_TIME, START_TIME + INTERVAL);
160 
161         // Advance clock.
162         mInjectedCurrentTimeMillis += 1;
163 
164         assertResetTimes(START_TIME + INTERVAL, START_TIME + 2 * INTERVAL);
165 
166         // Advance further; 4 hours since start.
167         mInjectedCurrentTimeMillis = START_TIME + 4 * INTERVAL + 50;
168 
169         assertResetTimes(START_TIME + 4 * INTERVAL, START_TIME + 5 * INTERVAL);
170     }
171 
172     /**
173      * Test for the restoration from saved file.
174      */
testInitializeFromSavedFile()175     public void testInitializeFromSavedFile() {
176 
177         mInjectedCurrentTimeMillis = START_TIME + 4 * INTERVAL + 50;
178         assertResetTimes(START_TIME + 4 * INTERVAL, START_TIME + 5 * INTERVAL);
179 
180         mService.saveBaseStateLocked();
181 
182         dumpBaseStateFile();
183 
184         mService.saveDirtyInfo();
185 
186         // Restore.
187         initService();
188 
189         assertResetTimes(START_TIME + 4 * INTERVAL, START_TIME + 5 * INTERVAL);
190     }
191 
192     /**
193      * Test for the restoration from restored file.
194      */
testLoadFromBrokenFile()195     public void testLoadFromBrokenFile() {
196         // TODO Add various broken cases.
197     }
198 
testLoadConfig()199     public void testLoadConfig() {
200         mService.updateConfigurationLocked(
201                 ConfigConstants.KEY_RESET_INTERVAL_SEC + "=123,"
202                         + ConfigConstants.KEY_MAX_SHORTCUTS + "=4,"
203                         + ConfigConstants.KEY_MAX_UPDATES_PER_INTERVAL + "=5,"
204                         + ConfigConstants.KEY_MAX_ICON_DIMENSION_DP + "=100,"
205                         + ConfigConstants.KEY_MAX_ICON_DIMENSION_DP_LOWRAM + "=50,"
206                         + ConfigConstants.KEY_ICON_FORMAT + "=WEBP,"
207                         + ConfigConstants.KEY_ICON_QUALITY + "=75");
208         assertEquals(123000, mService.getResetIntervalForTest());
209         assertEquals(4, mService.getMaxShortcutsForTest());
210         assertEquals(5, mService.getMaxUpdatesPerIntervalForTest());
211         assertEquals(100, mService.getMaxIconDimensionForTest());
212         assertEquals(CompressFormat.WEBP, mService.getIconPersistFormatForTest());
213         assertEquals(75, mService.getIconPersistQualityForTest());
214 
215         mInjectedIsLowRamDevice = true;
216         mService.updateConfigurationLocked(
217                 ConfigConstants.KEY_MAX_ICON_DIMENSION_DP + "=100,"
218                         + ConfigConstants.KEY_MAX_ICON_DIMENSION_DP_LOWRAM + "=50,"
219                         + ConfigConstants.KEY_ICON_FORMAT + "=JPEG");
220         assertEquals(ShortcutService.DEFAULT_RESET_INTERVAL_SEC * 1000,
221                 mService.getResetIntervalForTest());
222 
223         assertEquals(ShortcutService.DEFAULT_MAX_SHORTCUTS_PER_APP,
224                 mService.getMaxShortcutsForTest());
225 
226         assertEquals(ShortcutService.DEFAULT_MAX_UPDATES_PER_INTERVAL,
227                 mService.getMaxUpdatesPerIntervalForTest());
228 
229         assertEquals(50, mService.getMaxIconDimensionForTest());
230 
231         assertEquals(CompressFormat.JPEG, mService.getIconPersistFormatForTest());
232 
233         assertEquals(ShortcutService.DEFAULT_ICON_PERSIST_QUALITY,
234                 mService.getIconPersistQualityForTest());
235     }
236 
237     // === Test for app side APIs ===
238 
239     /** Test for {@link android.content.pm.ShortcutManager#getMaxShortcutCountForActivity()} */
testGetMaxDynamicShortcutCount()240     public void testGetMaxDynamicShortcutCount() {
241         assertEquals(MAX_SHORTCUTS, mManager.getMaxShortcutCountForActivity());
242     }
243 
244     /** Test for {@link android.content.pm.ShortcutManager#getRemainingCallCount()} */
testGetRemainingCallCount()245     public void testGetRemainingCallCount() {
246         assertEquals(MAX_UPDATES_PER_INTERVAL, mManager.getRemainingCallCount());
247     }
248 
testGetIconMaxDimensions()249     public void testGetIconMaxDimensions() {
250         assertEquals(MAX_ICON_DIMENSION, mManager.getIconMaxWidth());
251         assertEquals(MAX_ICON_DIMENSION, mManager.getIconMaxHeight());
252     }
253 
254     /** Test for {@link android.content.pm.ShortcutManager#getRateLimitResetTime()} */
testGetRateLimitResetTime()255     public void testGetRateLimitResetTime() {
256         assertEquals(START_TIME + INTERVAL, mManager.getRateLimitResetTime());
257 
258         mInjectedCurrentTimeMillis = START_TIME + 4 * INTERVAL + 50;
259 
260         assertEquals(START_TIME + 5 * INTERVAL, mManager.getRateLimitResetTime());
261     }
262 
testSetDynamicShortcuts()263     public void testSetDynamicShortcuts() {
264         setCaller(CALLING_PACKAGE_1, USER_0);
265 
266         final Icon icon1 = Icon.createWithResource(getTestContext(), R.drawable.icon1);
267         final Icon icon2 = Icon.createWithBitmap(BitmapFactory.decodeResource(
268                 getTestContext().getResources(), R.drawable.icon2));
269         final Icon icon3 = Icon.createWithAdaptiveBitmap(BitmapFactory.decodeResource(
270                 getTestContext().getResources(), R.drawable.icon2));
271 
272         final ShortcutInfo si1 = makeShortcut(
273                 "shortcut1",
274                 "Title 1",
275                 makeComponent(ShortcutActivity.class),
276                 icon1,
277                 makeIntent(Intent.ACTION_ASSIST, ShortcutActivity2.class,
278                         "key1", "val1", "nest", makeBundle("key", 123)),
279                 /* weight */ 10);
280 
281         final ShortcutInfo si2 = makeShortcut(
282                 "shortcut2",
283                 "Title 2",
284                 /* activity */ null,
285                 icon2,
286                 makeIntent(Intent.ACTION_ASSIST, ShortcutActivity3.class),
287                 /* weight */ 12);
288         final ShortcutInfo si3 = makeShortcut(
289                 "shortcut3",
290                 "Title 3",
291                 /* activity */ null,
292                 icon3,
293                 makeIntent(Intent.ACTION_ASSIST, ShortcutActivity3.class),
294                 /* weight */ 13);
295 
296         assertTrue(mManager.setDynamicShortcuts(list(si1, si2, si3)));
297         assertShortcutIds(assertAllNotKeyFieldsOnly(
298                 mManager.getDynamicShortcuts()),
299                 "shortcut1", "shortcut2", "shortcut3");
300         assertEquals(2, mManager.getRemainingCallCount());
301 
302         // TODO: Check fields
303 
304         assertTrue(mManager.setDynamicShortcuts(list(si1)));
305         assertShortcutIds(assertAllNotKeyFieldsOnly(
306                 mManager.getDynamicShortcuts()),
307                 "shortcut1");
308         assertEquals(1, mManager.getRemainingCallCount());
309 
310         assertTrue(mManager.setDynamicShortcuts(list()));
311         assertEquals(0, mManager.getDynamicShortcuts().size());
312         assertEquals(0, mManager.getRemainingCallCount());
313 
314         dumpsysOnLogcat();
315 
316         mInjectedCurrentTimeMillis++; // Need to advance the clock for reset to work.
317         mService.resetThrottlingInner(UserHandle.USER_SYSTEM);
318 
319         dumpsysOnLogcat();
320 
321         assertTrue(mManager.setDynamicShortcuts(list(si2, si3)));
322         assertEquals(2, mManager.getDynamicShortcuts().size());
323 
324         // TODO Check max number
325 
326         mRunningUsers.put(USER_10, true);
327 
328         runWithCaller(CALLING_PACKAGE_2, USER_10, () -> {
329             assertTrue(mManager.setDynamicShortcuts(list(makeShortcut("s1"))));
330         });
331     }
332 
testAddDynamicShortcuts()333     public void testAddDynamicShortcuts() {
334         setCaller(CALLING_PACKAGE_1, USER_0);
335 
336         final ShortcutInfo si1 = makeShortcut("shortcut1");
337         final ShortcutInfo si2 = makeShortcut("shortcut2");
338         final ShortcutInfo si3 = makeShortcut("shortcut3");
339 
340         assertEquals(3, mManager.getRemainingCallCount());
341 
342         assertTrue(mManager.setDynamicShortcuts(list(si1)));
343         assertEquals(2, mManager.getRemainingCallCount());
344         assertShortcutIds(assertAllNotKeyFieldsOnly(
345                 mManager.getDynamicShortcuts()),
346                 "shortcut1");
347 
348         assertTrue(mManager.addDynamicShortcuts(list(si2, si3)));
349         assertEquals(1, mManager.getRemainingCallCount());
350         assertShortcutIds(assertAllNotKeyFieldsOnly(
351                 mManager.getDynamicShortcuts()),
352                 "shortcut1", "shortcut2", "shortcut3");
353 
354         // This should not crash.  It'll still consume the quota.
355         assertTrue(mManager.addDynamicShortcuts(list()));
356         assertEquals(0, mManager.getRemainingCallCount());
357         assertShortcutIds(assertAllNotKeyFieldsOnly(
358                 mManager.getDynamicShortcuts()),
359                 "shortcut1", "shortcut2", "shortcut3");
360 
361         mInjectedCurrentTimeMillis += INTERVAL; // reset
362 
363         // Add with the same ID
364         assertTrue(mManager.addDynamicShortcuts(list(makeShortcut("shortcut1"))));
365         assertEquals(2, mManager.getRemainingCallCount());
366         assertShortcutIds(assertAllNotKeyFieldsOnly(
367                 mManager.getDynamicShortcuts()),
368                 "shortcut1", "shortcut2", "shortcut3");
369 
370         // TODO Check max number
371 
372         // TODO Check fields.
373 
374         mRunningUsers.put(USER_10, true);
375 
376         runWithCaller(CALLING_PACKAGE_2, USER_10, () -> {
377             assertTrue(mManager.addDynamicShortcuts(list(makeShortcut("s1"))));
378         });
379     }
380 
testUnlimitedCalls()381     public void testUnlimitedCalls() {
382         setCaller(CALLING_PACKAGE_1, USER_0);
383 
384         final ShortcutInfo si1 = makeShortcut("shortcut1");
385 
386         assertEquals(3, mManager.getRemainingCallCount());
387 
388         assertTrue(mManager.setDynamicShortcuts(list(si1)));
389         assertEquals(2, mManager.getRemainingCallCount());
390 
391         assertTrue(mManager.addDynamicShortcuts(list(si1)));
392         assertEquals(1, mManager.getRemainingCallCount());
393 
394         assertTrue(mManager.updateShortcuts(list(si1)));
395         assertEquals(0, mManager.getRemainingCallCount());
396 
397         // Unlimited now.
398         mInjectHasUnlimitedShortcutsApiCallsPermission = true;
399 
400         assertEquals(3, mManager.getRemainingCallCount());
401 
402         assertTrue(mManager.setDynamicShortcuts(list(si1)));
403         assertEquals(3, mManager.getRemainingCallCount());
404 
405         assertTrue(mManager.addDynamicShortcuts(list(si1)));
406         assertEquals(3, mManager.getRemainingCallCount());
407 
408         assertTrue(mManager.updateShortcuts(list(si1)));
409         assertEquals(3, mManager.getRemainingCallCount());
410     }
411 
testPublishWithNoActivity()412     public void testPublishWithNoActivity() {
413         // If activity is not explicitly set, use the default one.
414 
415         mRunningUsers.put(USER_10, true);
416 
417         runWithCaller(CALLING_PACKAGE_2, USER_10, () -> {
418             // s1 and s3 has no activities.
419             final ShortcutInfo si1 = new ShortcutInfo.Builder(mClientContext, "si1")
420                     .setShortLabel("label1")
421                     .setIntent(new Intent("action1"))
422                     .build();
423             final ShortcutInfo si2 = new ShortcutInfo.Builder(mClientContext, "si2")
424                     .setShortLabel("label2")
425                     .setActivity(new ComponentName(getCallingPackage(), "abc"))
426                     .setIntent(new Intent("action2"))
427                     .build();
428             final ShortcutInfo si3 = new ShortcutInfo.Builder(mClientContext, "si3")
429                     .setShortLabel("label3")
430                     .setIntent(new Intent("action3"))
431                     .build();
432 
433             // Set test 1
434             assertTrue(mManager.setDynamicShortcuts(list(si1)));
435 
436             assertWith(getCallerShortcuts())
437                     .haveIds("si1")
438                     .forShortcutWithId("si1", si -> {
439                         assertEquals(new ComponentName(getCallingPackage(),
440                                 MAIN_ACTIVITY_CLASS), si.getActivity());
441                     });
442 
443             // Set test 2
444             assertTrue(mManager.setDynamicShortcuts(list(si2, si1)));
445 
446             assertWith(getCallerShortcuts())
447                     .haveIds("si1", "si2")
448                     .forShortcutWithId("si1", si -> {
449                         assertEquals(new ComponentName(getCallingPackage(),
450                                 MAIN_ACTIVITY_CLASS), si.getActivity());
451                     })
452                     .forShortcutWithId("si2", si -> {
453                         assertEquals(new ComponentName(getCallingPackage(),
454                                 "abc"), si.getActivity());
455                     });
456 
457 
458             // Set test 3
459             assertTrue(mManager.setDynamicShortcuts(list(si3, si1)));
460 
461             assertWith(getCallerShortcuts())
462                     .haveIds("si1", "si3")
463                     .forShortcutWithId("si1", si -> {
464                         assertEquals(new ComponentName(getCallingPackage(),
465                                 MAIN_ACTIVITY_CLASS), si.getActivity());
466                     })
467                     .forShortcutWithId("si3", si -> {
468                         assertEquals(new ComponentName(getCallingPackage(),
469                                 MAIN_ACTIVITY_CLASS), si.getActivity());
470                     });
471 
472             mInjectedCurrentTimeMillis += INTERVAL; // reset throttling
473 
474             // Add test 1
475             mManager.removeAllDynamicShortcuts();
476             assertTrue(mManager.addDynamicShortcuts(list(si1)));
477 
478             assertWith(getCallerShortcuts())
479                     .haveIds("si1")
480                     .forShortcutWithId("si1", si -> {
481                         assertEquals(new ComponentName(getCallingPackage(),
482                                 MAIN_ACTIVITY_CLASS), si.getActivity());
483                     });
484 
485             // Add test 2
486             mManager.removeAllDynamicShortcuts();
487             assertTrue(mManager.addDynamicShortcuts(list(si2, si1)));
488 
489             assertWith(getCallerShortcuts())
490                     .haveIds("si1", "si2")
491                     .forShortcutWithId("si1", si -> {
492                         assertEquals(new ComponentName(getCallingPackage(),
493                                 MAIN_ACTIVITY_CLASS), si.getActivity());
494                     })
495                     .forShortcutWithId("si2", si -> {
496                         assertEquals(new ComponentName(getCallingPackage(),
497                                 "abc"), si.getActivity());
498                     });
499 
500 
501             // Add test 3
502             mManager.removeAllDynamicShortcuts();
503             assertTrue(mManager.addDynamicShortcuts(list(si3, si1)));
504 
505             assertWith(getCallerShortcuts())
506                     .haveIds("si1", "si3")
507                     .forShortcutWithId("si1", si -> {
508                         assertEquals(new ComponentName(getCallingPackage(),
509                                 MAIN_ACTIVITY_CLASS), si.getActivity());
510                     })
511                     .forShortcutWithId("si3", si -> {
512                         assertEquals(new ComponentName(getCallingPackage(),
513                                 MAIN_ACTIVITY_CLASS), si.getActivity());
514                     });
515         });
516     }
517 
testPublishWithNoActivity_noMainActivityInPackage()518     public void testPublishWithNoActivity_noMainActivityInPackage() {
519         mRunningUsers.put(USER_10, true);
520 
521         runWithCaller(CALLING_PACKAGE_2, USER_10, () -> {
522             final ShortcutInfo si1 = new ShortcutInfo.Builder(mClientContext, "si1")
523                     .setShortLabel("label1")
524                     .setIntent(new Intent("action1"))
525                     .build();
526 
527             // Returning null means there's no main activity in this package.
528             mMainActivityFetcher = (packageName, userId) -> null;
529 
530             assertExpectException(
531                     RuntimeException.class, "Launcher activity not found for", () -> {
532                         assertTrue(mManager.setDynamicShortcuts(list(si1)));
533                     });
534         });
535     }
536 
testDeleteDynamicShortcuts()537     public void testDeleteDynamicShortcuts() {
538         final ShortcutInfo si1 = makeShortcut("shortcut1");
539         final ShortcutInfo si2 = makeShortcut("shortcut2");
540         final ShortcutInfo si3 = makeShortcut("shortcut3");
541         final ShortcutInfo si4 = makeShortcut("shortcut4");
542 
543         assertTrue(mManager.setDynamicShortcuts(list(si1, si2, si3, si4)));
544         assertShortcutIds(assertAllNotKeyFieldsOnly(
545                 mManager.getDynamicShortcuts()),
546                 "shortcut1", "shortcut2", "shortcut3", "shortcut4");
547 
548         assertEquals(2, mManager.getRemainingCallCount());
549 
550         mManager.removeDynamicShortcuts(list("shortcut1"));
551         assertShortcutIds(assertAllNotKeyFieldsOnly(
552                 mManager.getDynamicShortcuts()),
553                 "shortcut2", "shortcut3", "shortcut4");
554 
555         mManager.removeDynamicShortcuts(list("shortcut1"));
556         assertShortcutIds(assertAllNotKeyFieldsOnly(
557                 mManager.getDynamicShortcuts()),
558                 "shortcut2", "shortcut3", "shortcut4");
559 
560         mManager.removeDynamicShortcuts(list("shortcutXXX"));
561         assertShortcutIds(assertAllNotKeyFieldsOnly(
562                 mManager.getDynamicShortcuts()),
563                 "shortcut2", "shortcut3", "shortcut4");
564 
565         mManager.removeDynamicShortcuts(list("shortcut2", "shortcut4"));
566         assertShortcutIds(assertAllNotKeyFieldsOnly(
567                 mManager.getDynamicShortcuts()),
568                 "shortcut3");
569 
570         mManager.removeDynamicShortcuts(list("shortcut3"));
571         assertShortcutIds(assertAllNotKeyFieldsOnly(
572                 mManager.getDynamicShortcuts()));
573 
574         // Still 2 calls left.
575         assertEquals(2, mManager.getRemainingCallCount());
576     }
577 
testDeleteAllDynamicShortcuts()578     public void testDeleteAllDynamicShortcuts() {
579         final ShortcutInfo si1 = makeShortcut("shortcut1");
580         final ShortcutInfo si2 = makeShortcut("shortcut2");
581         final ShortcutInfo si3 = makeShortcut("shortcut3");
582 
583         assertTrue(mManager.setDynamicShortcuts(list(si1, si2, si3)));
584         assertShortcutIds(assertAllNotKeyFieldsOnly(
585                 mManager.getDynamicShortcuts()),
586                 "shortcut1", "shortcut2", "shortcut3");
587 
588         assertEquals(2, mManager.getRemainingCallCount());
589 
590         mManager.removeAllDynamicShortcuts();
591         assertEquals(0, mManager.getDynamicShortcuts().size());
592         assertEquals(2, mManager.getRemainingCallCount());
593 
594         // Note delete shouldn't affect throttling, so...
595         assertEquals(0, mManager.getDynamicShortcuts().size());
596         assertEquals(0, mManager.getDynamicShortcuts().size());
597         assertEquals(0, mManager.getDynamicShortcuts().size());
598 
599         // This should still work.
600         assertTrue(mManager.setDynamicShortcuts(list(si1, si2, si3)));
601         assertEquals(3, mManager.getDynamicShortcuts().size());
602 
603         // Still 1 call left
604         assertEquals(1, mManager.getRemainingCallCount());
605     }
606 
testIcons()607     public void testIcons() throws IOException {
608         final Icon res32x32 = Icon.createWithResource(getTestContext(), R.drawable.black_32x32);
609         final Icon res64x64 = Icon.createWithResource(getTestContext(), R.drawable.black_64x64);
610         final Icon res512x512 = Icon.createWithResource(getTestContext(), R.drawable.black_512x512);
611 
612         final Icon bmp32x32 = Icon.createWithBitmap(BitmapFactory.decodeResource(
613                 getTestContext().getResources(), R.drawable.black_32x32));
614         final Icon bmp64x64_maskable = Icon.createWithAdaptiveBitmap(BitmapFactory.decodeResource(
615                 getTestContext().getResources(), R.drawable.black_64x64));
616         final Icon bmp512x512 = Icon.createWithBitmap(BitmapFactory.decodeResource(
617                 getTestContext().getResources(), R.drawable.black_512x512));
618 
619         // Set from package 1
620         setCaller(CALLING_PACKAGE_1);
621         assertTrue(mManager.setDynamicShortcuts(list(
622                 makeShortcutWithIcon("res32x32", res32x32),
623                 makeShortcutWithIcon("res64x64", res64x64),
624                 makeShortcutWithIcon("bmp32x32", bmp32x32),
625                 makeShortcutWithIcon("bmp64x64", bmp64x64_maskable),
626                 makeShortcutWithIcon("bmp512x512", bmp512x512),
627                 makeShortcut("none")
628         )));
629 
630         // getDynamicShortcuts() shouldn't return icons, thus assertAllNotHaveIcon().
631         assertShortcutIds(assertAllNotHaveIcon(mManager.getDynamicShortcuts()),
632                 "res32x32",
633                 "res64x64",
634                 "bmp32x32",
635                 "bmp64x64",
636                 "bmp512x512",
637                 "none");
638 
639         // Call from another caller with the same ID, just to make sure storage is per-package.
640         setCaller(CALLING_PACKAGE_2);
641         assertTrue(mManager.setDynamicShortcuts(list(
642                 makeShortcutWithIcon("res32x32", res512x512),
643                 makeShortcutWithIcon("res64x64", res512x512),
644                 makeShortcutWithIcon("none", res512x512)
645         )));
646         assertShortcutIds(assertAllNotHaveIcon(mManager.getDynamicShortcuts()),
647                 "res32x32",
648                 "res64x64",
649                 "none");
650 
651         // Different profile.  Note the names and the contents don't match.
652         setCaller(CALLING_PACKAGE_1, USER_P0);
653         assertTrue(mManager.setDynamicShortcuts(list(
654                 makeShortcutWithIcon("res32x32", res512x512),
655                 makeShortcutWithIcon("bmp32x32", bmp512x512)
656         )));
657         assertShortcutIds(assertAllNotHaveIcon(mManager.getDynamicShortcuts()),
658                 "res32x32",
659                 "bmp32x32");
660 
661         // Re-initialize and load from the files.
662         mService.saveDirtyInfo();
663         initService();
664 
665         // Load from launcher.
666         Bitmap bmp;
667 
668         setCaller(LAUNCHER_1);
669         // Check hasIconResource()/hasIconFile().
670         assertShortcutIds(assertAllHaveIconResId(
671                 list(getShortcutInfoAsLauncher(CALLING_PACKAGE_1, "res32x32", USER_0))),
672                 "res32x32");
673 
674         assertShortcutIds(assertAllHaveIconResId(
675                 list(getShortcutInfoAsLauncher(CALLING_PACKAGE_1, "res64x64", USER_0))),
676                 "res64x64");
677 
678         assertShortcutIds(assertAllHaveIconFile(
679                 list(getShortcutInfoAsLauncher(CALLING_PACKAGE_1, "bmp32x32", USER_0))),
680                 "bmp32x32");
681 
682         assertShortcutIds(assertAllHaveIconFile(
683                 list(getShortcutInfoAsLauncher(CALLING_PACKAGE_1, "bmp64x64", USER_0))),
684                 "bmp64x64");
685 
686         assertShortcutIds(assertAllHaveIconFile(
687                 list(getShortcutInfoAsLauncher(CALLING_PACKAGE_1, "bmp512x512", USER_0))),
688                 "bmp512x512");
689 
690         assertShortcutIds(assertAllHaveIconResId(
691                 list(getShortcutInfoAsLauncher(CALLING_PACKAGE_1, "res32x32", USER_P0))),
692                 "res32x32");
693         assertShortcutIds(assertAllHaveIconFile(
694                 list(getShortcutInfoAsLauncher(CALLING_PACKAGE_1, "bmp32x32", USER_P0))),
695                 "bmp32x32");
696 
697         // Check
698         assertEquals(
699                 R.drawable.black_32x32,
700                 mLauncherApps.getShortcutIconResId(
701                         getShortcutInfoAsLauncher(CALLING_PACKAGE_1, "res32x32", USER_0)));
702 
703         assertEquals(
704                 R.drawable.black_64x64,
705                 mLauncherApps.getShortcutIconResId(
706                         getShortcutInfoAsLauncher(CALLING_PACKAGE_1, "res64x64", USER_0)));
707 
708         assertEquals(
709                 0, // because it's not a resource
710                 mLauncherApps.getShortcutIconResId(
711                         getShortcutInfoAsLauncher(CALLING_PACKAGE_1, "bmp32x32", USER_0)));
712         assertEquals(
713                 0, // because it's not a resource
714                 mLauncherApps.getShortcutIconResId(
715                         getShortcutInfoAsLauncher(CALLING_PACKAGE_1, "bmp64x64", USER_0)));
716         assertEquals(
717                 0, // because it's not a resource
718                 mLauncherApps.getShortcutIconResId(
719                         getShortcutInfoAsLauncher(CALLING_PACKAGE_1, "bmp512x512", USER_0)));
720 
721         bmp = pfdToBitmap(mLauncherApps.getShortcutIconFd(
722                 getShortcutInfoAsLauncher(CALLING_PACKAGE_1, "bmp32x32", USER_0)));
723         assertBitmapSize(32, 32, bmp);
724 
725         bmp = pfdToBitmap(mLauncherApps.getShortcutIconFd(
726                 getShortcutInfoAsLauncher(CALLING_PACKAGE_1, "bmp64x64", USER_0)));
727         assertBitmapSize(64, 64, bmp);
728 
729         bmp = pfdToBitmap(mLauncherApps.getShortcutIconFd(
730                 getShortcutInfoAsLauncher(CALLING_PACKAGE_1, "bmp512x512", USER_0)));
731         assertBitmapSize(128, 128, bmp);
732 
733         assertEquals(
734                 R.drawable.black_512x512,
735                 mLauncherApps.getShortcutIconResId(
736                         getShortcutInfoAsLauncher(CALLING_PACKAGE_1, "res32x32", USER_P0)));
737         // Should be 512x512, so shrunk.
738         bmp = pfdToBitmap(mLauncherApps.getShortcutIconFd(
739                 getShortcutInfoAsLauncher(CALLING_PACKAGE_1, "bmp32x32", USER_P0)));
740         assertBitmapSize(128, 128, bmp);
741 
742         // Also check the overload APIs too.
743         assertEquals(
744                 R.drawable.black_32x32,
745                 mLauncherApps.getShortcutIconResId(CALLING_PACKAGE_1, "res32x32", HANDLE_USER_0));
746         assertEquals(
747                 R.drawable.black_64x64,
748                 mLauncherApps.getShortcutIconResId(CALLING_PACKAGE_1, "res64x64", HANDLE_USER_0));
749         assertEquals(
750                 R.drawable.black_512x512,
751                 mLauncherApps.getShortcutIconResId(CALLING_PACKAGE_1, "res32x32", HANDLE_USER_P0));
752         bmp = pfdToBitmap(
753                 mLauncherApps.getShortcutIconFd(CALLING_PACKAGE_1, "bmp32x32", HANDLE_USER_P0));
754         assertBitmapSize(128, 128, bmp);
755 
756         Drawable dr = mLauncherApps.getShortcutIconDrawable(
757                 makeShortcutWithIcon("bmp64x64", bmp64x64_maskable), 0);
758         assertTrue(dr instanceof AdaptiveIconDrawable);
759         float viewportPercentage = 1 / (1 + 2 * AdaptiveIconDrawable.getExtraInsetFraction());
760         assertEquals((int) (bmp64x64_maskable.getBitmap().getWidth() * viewportPercentage),
761                 dr.getIntrinsicWidth());
762         assertEquals((int) (bmp64x64_maskable.getBitmap().getHeight() * viewportPercentage),
763                 dr.getIntrinsicHeight());
764     }
765 
testCleanupDanglingBitmaps()766     public void testCleanupDanglingBitmaps() throws Exception {
767         assertBitmapDirectories(USER_0, EMPTY_STRINGS);
768         assertBitmapDirectories(USER_10, EMPTY_STRINGS);
769 
770         // Make some shortcuts with bitmap icons.
771         final Icon bmp32x32 = Icon.createWithBitmap(BitmapFactory.decodeResource(
772                 getTestContext().getResources(), R.drawable.black_32x32));
773 
774         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
775             mManager.setDynamicShortcuts(list(
776                     makeShortcutWithIcon("s1", bmp32x32),
777                     makeShortcutWithIcon("s2", bmp32x32),
778                     makeShortcutWithIcon("s3", bmp32x32)
779             ));
780         });
781 
782         // Increment the time (which actually we don't have to), which is used for filenames.
783         mInjectedCurrentTimeMillis++;
784 
785         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
786             mManager.setDynamicShortcuts(list(
787                     makeShortcutWithIcon("s4", bmp32x32),
788                     makeShortcutWithIcon("s5", bmp32x32),
789                     makeShortcutWithIcon("s6", bmp32x32)
790             ));
791         });
792 
793         // Increment the time, which is used for filenames.
794         mInjectedCurrentTimeMillis++;
795 
796         runWithCaller(CALLING_PACKAGE_3, USER_0, () -> {
797             mManager.setDynamicShortcuts(list(
798             ));
799         });
800 
801         // For USER-10, let's try without updating the times.
802         mRunningUsers.put(USER_10, true);
803 
804         runWithCaller(CALLING_PACKAGE_1, USER_10, () -> {
805             mManager.setDynamicShortcuts(list(
806                     makeShortcutWithIcon("10s1", bmp32x32),
807                     makeShortcutWithIcon("10s2", bmp32x32),
808                     makeShortcutWithIcon("10s3", bmp32x32)
809             ));
810         });
811         runWithCaller(CALLING_PACKAGE_2, USER_10, () -> {
812             mManager.setDynamicShortcuts(list(
813                     makeShortcutWithIcon("10s4", bmp32x32),
814                     makeShortcutWithIcon("10s5", bmp32x32),
815                     makeShortcutWithIcon("10s6", bmp32x32)
816             ));
817         });
818         runWithCaller(CALLING_PACKAGE_3, USER_10, () -> {
819             mManager.setDynamicShortcuts(list(
820             ));
821         });
822 
823         dumpsysOnLogcat();
824 
825         mService.waitForBitmapSavesForTest();
826         // Check files and directories.
827         // Package 3 has no bitmaps, so we don't create a directory.
828         assertBitmapDirectories(USER_0, CALLING_PACKAGE_1, CALLING_PACKAGE_2);
829         assertBitmapDirectories(USER_10, CALLING_PACKAGE_1, CALLING_PACKAGE_2);
830 
831         assertBitmapFiles(USER_0, CALLING_PACKAGE_1,
832                 getBitmapFilename(USER_0, CALLING_PACKAGE_1, "s1"),
833                 getBitmapFilename(USER_0, CALLING_PACKAGE_1, "s2"),
834                 getBitmapFilename(USER_0, CALLING_PACKAGE_1, "s3")
835         );
836         assertBitmapFiles(USER_0, CALLING_PACKAGE_2,
837                 getBitmapFilename(USER_0, CALLING_PACKAGE_2, "s4"),
838                 getBitmapFilename(USER_0, CALLING_PACKAGE_2, "s5"),
839                 getBitmapFilename(USER_0, CALLING_PACKAGE_2, "s6")
840         );
841         assertBitmapFiles(USER_0, CALLING_PACKAGE_3,
842                 EMPTY_STRINGS
843         );
844         assertBitmapFiles(USER_10, CALLING_PACKAGE_1,
845                 getBitmapFilename(USER_10, CALLING_PACKAGE_1, "10s1"),
846                 getBitmapFilename(USER_10, CALLING_PACKAGE_1, "10s2"),
847                 getBitmapFilename(USER_10, CALLING_PACKAGE_1, "10s3")
848         );
849         assertBitmapFiles(USER_10, CALLING_PACKAGE_2,
850                 getBitmapFilename(USER_10, CALLING_PACKAGE_2, "10s4"),
851                 getBitmapFilename(USER_10, CALLING_PACKAGE_2, "10s5"),
852                 getBitmapFilename(USER_10, CALLING_PACKAGE_2, "10s6")
853         );
854         assertBitmapFiles(USER_10, CALLING_PACKAGE_3,
855                 EMPTY_STRINGS
856         );
857 
858         // Then create random directories and files.
859         makeFile(mService.getUserBitmapFilePath(USER_0), "a.b.c").mkdir();
860         makeFile(mService.getUserBitmapFilePath(USER_0), "d.e.f").mkdir();
861         makeFile(mService.getUserBitmapFilePath(USER_0), "d.e.f", "123").createNewFile();
862         makeFile(mService.getUserBitmapFilePath(USER_0), "d.e.f", "456").createNewFile();
863 
864         makeFile(mService.getUserBitmapFilePath(USER_0), CALLING_PACKAGE_3).mkdir();
865 
866         makeFile(mService.getUserBitmapFilePath(USER_0), CALLING_PACKAGE_1, "1").createNewFile();
867         makeFile(mService.getUserBitmapFilePath(USER_0), CALLING_PACKAGE_1, "2").createNewFile();
868         makeFile(mService.getUserBitmapFilePath(USER_0), CALLING_PACKAGE_1, "3").createNewFile();
869         makeFile(mService.getUserBitmapFilePath(USER_0), CALLING_PACKAGE_1, "4").createNewFile();
870 
871         makeFile(mService.getUserBitmapFilePath(USER_10), "10a.b.c").mkdir();
872         makeFile(mService.getUserBitmapFilePath(USER_10), "10d.e.f").mkdir();
873         makeFile(mService.getUserBitmapFilePath(USER_10), "10d.e.f", "123").createNewFile();
874         makeFile(mService.getUserBitmapFilePath(USER_10), "10d.e.f", "456").createNewFile();
875 
876         makeFile(mService.getUserBitmapFilePath(USER_10), CALLING_PACKAGE_2, "1").createNewFile();
877         makeFile(mService.getUserBitmapFilePath(USER_10), CALLING_PACKAGE_2, "2").createNewFile();
878         makeFile(mService.getUserBitmapFilePath(USER_10), CALLING_PACKAGE_2, "3").createNewFile();
879         makeFile(mService.getUserBitmapFilePath(USER_10), CALLING_PACKAGE_2, "4").createNewFile();
880 
881         mService.waitForBitmapSavesForTest();
882         assertBitmapDirectories(USER_0, CALLING_PACKAGE_1, CALLING_PACKAGE_2, CALLING_PACKAGE_3,
883                 "a.b.c", "d.e.f");
884 
885         // Save and load.  When a user is loaded, we do the cleanup.
886         mService.saveDirtyInfo();
887         initService();
888 
889         mService.handleUnlockUser(USER_0);
890         mService.handleUnlockUser(USER_10);
891         mService.handleUnlockUser(20); // Make sure the logic will still work for nonexistent user.
892 
893         // The below check is the same as above, except this time USER_0 use the CALLING_PACKAGE_3
894         // directory.
895 
896         mService.waitForBitmapSavesForTest();
897         assertBitmapDirectories(USER_0, CALLING_PACKAGE_1, CALLING_PACKAGE_2, CALLING_PACKAGE_3);
898         assertBitmapDirectories(USER_10, CALLING_PACKAGE_1, CALLING_PACKAGE_2);
899 
900         assertBitmapFiles(USER_0, CALLING_PACKAGE_1,
901                 getBitmapFilename(USER_0, CALLING_PACKAGE_1, "s1"),
902                 getBitmapFilename(USER_0, CALLING_PACKAGE_1, "s2"),
903                 getBitmapFilename(USER_0, CALLING_PACKAGE_1, "s3")
904         );
905         assertBitmapFiles(USER_0, CALLING_PACKAGE_2,
906                 getBitmapFilename(USER_0, CALLING_PACKAGE_2, "s4"),
907                 getBitmapFilename(USER_0, CALLING_PACKAGE_2, "s5"),
908                 getBitmapFilename(USER_0, CALLING_PACKAGE_2, "s6")
909         );
910         assertBitmapFiles(USER_0, CALLING_PACKAGE_3,
911                 EMPTY_STRINGS
912         );
913         assertBitmapFiles(USER_10, CALLING_PACKAGE_1,
914                 getBitmapFilename(USER_10, CALLING_PACKAGE_1, "10s1"),
915                 getBitmapFilename(USER_10, CALLING_PACKAGE_1, "10s2"),
916                 getBitmapFilename(USER_10, CALLING_PACKAGE_1, "10s3")
917         );
918         assertBitmapFiles(USER_10, CALLING_PACKAGE_2,
919                 getBitmapFilename(USER_10, CALLING_PACKAGE_2, "10s4"),
920                 getBitmapFilename(USER_10, CALLING_PACKAGE_2, "10s5"),
921                 getBitmapFilename(USER_10, CALLING_PACKAGE_2, "10s6")
922         );
923         assertBitmapFiles(USER_10, CALLING_PACKAGE_3,
924                 EMPTY_STRINGS
925         );
926     }
927 
checkShrinkBitmap(int expectedWidth, int expectedHeight, int resId, int maxSize)928     protected void checkShrinkBitmap(int expectedWidth, int expectedHeight, int resId, int maxSize) {
929         assertBitmapSize(expectedWidth, expectedHeight,
930                 ShortcutService.shrinkBitmap(BitmapFactory.decodeResource(
931                         getTestContext().getResources(), resId),
932                         maxSize));
933     }
934 
testShrinkBitmap()935     public void testShrinkBitmap() {
936         checkShrinkBitmap(32, 32, R.drawable.black_512x512, 32);
937         checkShrinkBitmap(511, 511, R.drawable.black_512x512, 511);
938         checkShrinkBitmap(512, 512, R.drawable.black_512x512, 512);
939 
940         checkShrinkBitmap(1024, 4096, R.drawable.black_1024x4096, 4096);
941         checkShrinkBitmap(1024, 4096, R.drawable.black_1024x4096, 4100);
942         checkShrinkBitmap(512, 2048, R.drawable.black_1024x4096, 2048);
943 
944         checkShrinkBitmap(4096, 1024, R.drawable.black_4096x1024, 4096);
945         checkShrinkBitmap(4096, 1024, R.drawable.black_4096x1024, 4100);
946         checkShrinkBitmap(2048, 512, R.drawable.black_4096x1024, 2048);
947     }
948 
openIconFileForWriteAndGetPath(int userId, String packageName)949     protected File openIconFileForWriteAndGetPath(int userId, String packageName)
950             throws IOException {
951         // Shortcut IDs aren't used in the path, so just pass the same ID.
952         final FileOutputStreamWithPath out =
953                 mService.openIconFileForWrite(userId, makePackageShortcut(packageName, "id"));
954         out.close();
955         return out.getFile();
956     }
957 
testOpenIconFileForWrite()958     public void testOpenIconFileForWrite() throws IOException {
959         mInjectedCurrentTimeMillis = 1000;
960 
961         final File p10_1_1 = openIconFileForWriteAndGetPath(10, CALLING_PACKAGE_1);
962         final File p10_1_2 = openIconFileForWriteAndGetPath(10, CALLING_PACKAGE_1);
963 
964         final File p10_2_1 = openIconFileForWriteAndGetPath(10, CALLING_PACKAGE_2);
965         final File p10_2_2 = openIconFileForWriteAndGetPath(10, CALLING_PACKAGE_2);
966 
967         final File p11_1_1 = openIconFileForWriteAndGetPath(11, CALLING_PACKAGE_1);
968         final File p11_1_2 = openIconFileForWriteAndGetPath(11, CALLING_PACKAGE_1);
969 
970         mInjectedCurrentTimeMillis++;
971 
972         final File p10_1_3 = openIconFileForWriteAndGetPath(10, CALLING_PACKAGE_1);
973         final File p10_1_4 = openIconFileForWriteAndGetPath(10, CALLING_PACKAGE_1);
974         final File p10_1_5 = openIconFileForWriteAndGetPath(10, CALLING_PACKAGE_1);
975 
976         final File p10_2_3 = openIconFileForWriteAndGetPath(10, CALLING_PACKAGE_2);
977         final File p11_1_3 = openIconFileForWriteAndGetPath(11, CALLING_PACKAGE_1);
978 
979         // Make sure their paths are all unique
980         assertAllUnique(list(
981                 p10_1_1,
982                 p10_1_2,
983                 p10_1_3,
984                 p10_1_4,
985                 p10_1_5,
986 
987                 p10_2_1,
988                 p10_2_2,
989                 p10_2_3,
990 
991                 p11_1_1,
992                 p11_1_2,
993                 p11_1_3
994         ));
995 
996         // Check each set has the same parent.
997         assertEquals(p10_1_1.getParent(), p10_1_2.getParent());
998         assertEquals(p10_1_1.getParent(), p10_1_3.getParent());
999         assertEquals(p10_1_1.getParent(), p10_1_4.getParent());
1000         assertEquals(p10_1_1.getParent(), p10_1_5.getParent());
1001 
1002         assertEquals(p10_2_1.getParent(), p10_2_2.getParent());
1003         assertEquals(p10_2_1.getParent(), p10_2_3.getParent());
1004 
1005         assertEquals(p11_1_1.getParent(), p11_1_2.getParent());
1006         assertEquals(p11_1_1.getParent(), p11_1_3.getParent());
1007 
1008         // Check the parents are still unique.
1009         assertAllUnique(list(
1010                 p10_1_1.getParent(),
1011                 p10_2_1.getParent(),
1012                 p11_1_1.getParent()
1013         ));
1014 
1015         // All files created at the same time for the same package/user, expcet for the first ones,
1016         // will have "_" in the path.
1017         assertFalse(p10_1_1.getName().contains("_"));
1018         assertTrue(p10_1_2.getName().contains("_"));
1019         assertFalse(p10_1_3.getName().contains("_"));
1020         assertTrue(p10_1_4.getName().contains("_"));
1021         assertTrue(p10_1_5.getName().contains("_"));
1022 
1023         assertFalse(p10_2_1.getName().contains("_"));
1024         assertTrue(p10_2_2.getName().contains("_"));
1025         assertFalse(p10_2_3.getName().contains("_"));
1026 
1027         assertFalse(p11_1_1.getName().contains("_"));
1028         assertTrue(p11_1_2.getName().contains("_"));
1029         assertFalse(p11_1_3.getName().contains("_"));
1030     }
1031 
testUpdateShortcuts()1032     public void testUpdateShortcuts() {
1033         runWithCaller(CALLING_PACKAGE_1, UserHandle.USER_SYSTEM, () -> {
1034             assertTrue(mManager.setDynamicShortcuts(list(
1035                     makeShortcut("s1"),
1036                     makeShortcut("s2"),
1037                     makeShortcut("s3"),
1038                     makeShortcut("s4"),
1039                     makeShortcut("s5")
1040             )));
1041         });
1042         runWithCaller(CALLING_PACKAGE_2, UserHandle.USER_SYSTEM, () -> {
1043             assertTrue(mManager.setDynamicShortcuts(list(
1044                     makeShortcut("s1"),
1045                     makeShortcut("s2"),
1046                     makeShortcut("s3"),
1047                     makeShortcut("s4"),
1048                     makeShortcut("s5")
1049             )));
1050         });
1051         runWithCaller(LAUNCHER_1, UserHandle.USER_SYSTEM, () -> {
1052             mLauncherApps.pinShortcuts(CALLING_PACKAGE_1, list("s2", "s3"),
1053                     getCallingUser());
1054             mLauncherApps.pinShortcuts(CALLING_PACKAGE_2, list("s4", "s5"),
1055                     getCallingUser());
1056         });
1057         runWithCaller(CALLING_PACKAGE_1, UserHandle.USER_SYSTEM, () -> {
1058             mManager.removeDynamicShortcuts(list("s1"));
1059             mManager.removeDynamicShortcuts(list("s2"));
1060         });
1061         runWithCaller(CALLING_PACKAGE_2, UserHandle.USER_SYSTEM, () -> {
1062             mManager.removeDynamicShortcuts(list("s1"));
1063             mManager.removeDynamicShortcuts(list("s3"));
1064             mManager.removeDynamicShortcuts(list("s5"));
1065         });
1066         runWithCaller(CALLING_PACKAGE_1, UserHandle.USER_SYSTEM, () -> {
1067             assertShortcutIds(assertAllDynamic(
1068                     mManager.getDynamicShortcuts()),
1069                     "s3", "s4", "s5");
1070             assertShortcutIds(assertAllPinned(
1071                     mManager.getPinnedShortcuts()),
1072                     "s2", "s3");
1073         });
1074         runWithCaller(CALLING_PACKAGE_2, UserHandle.USER_SYSTEM, () -> {
1075             assertShortcutIds(assertAllDynamic(
1076                     mManager.getDynamicShortcuts()),
1077                     "s2", "s4");
1078             assertShortcutIds(assertAllPinned(
1079                     mManager.getPinnedShortcuts()),
1080                     "s4", "s5");
1081         });
1082 
1083         runWithCaller(CALLING_PACKAGE_1, UserHandle.USER_SYSTEM, () -> {
1084             ShortcutInfo s2 = makeShortcutBuilder()
1085                     .setId("s2")
1086                     .setIcon(Icon.createWithResource(getTestContext(), R.drawable.black_32x32))
1087                     .build();
1088 
1089             ShortcutInfo s4 = makeShortcutBuilder()
1090                     .setId("s4")
1091                     .setTitle("new title")
1092                     .build();
1093 
1094             mManager.updateShortcuts(list(s2, s4));
1095         });
1096         runWithCaller(CALLING_PACKAGE_2, UserHandle.USER_SYSTEM, () -> {
1097             ShortcutInfo s2 = makeShortcutBuilder()
1098                     .setId("s2")
1099                     .setIntent(makeIntent(Intent.ACTION_ANSWER, ShortcutActivity.class,
1100                             "key1", "val1"))
1101                     .build();
1102 
1103             ShortcutInfo s4 = makeShortcutBuilder()
1104                     .setId("s4")
1105                     .setIntent(new Intent(Intent.ACTION_ALL_APPS))
1106                     .build();
1107 
1108             mManager.updateShortcuts(list(s2, s4));
1109         });
1110 
1111         runWithCaller(CALLING_PACKAGE_1, UserHandle.USER_SYSTEM, () -> {
1112             assertShortcutIds(assertAllDynamic(
1113                     mManager.getDynamicShortcuts()),
1114                     "s3", "s4", "s5");
1115             assertShortcutIds(assertAllPinned(
1116                     mManager.getPinnedShortcuts()),
1117                     "s2", "s3");
1118 
1119             ShortcutInfo s = getCallerShortcut("s2");
1120             assertTrue(s.hasIconResource());
1121             assertEquals(R.drawable.black_32x32, s.getIconResourceId());
1122             assertEquals("string/r" + R.drawable.black_32x32, s.getIconResName());
1123             assertEquals("Title-s2", s.getTitle());
1124 
1125             s = getCallerShortcut("s4");
1126             assertFalse(s.hasIconResource());
1127             assertEquals(0, s.getIconResourceId());
1128             assertEquals("new title", s.getTitle());
1129         });
1130         runWithCaller(CALLING_PACKAGE_2, UserHandle.USER_SYSTEM, () -> {
1131             assertShortcutIds(assertAllDynamic(
1132                     mManager.getDynamicShortcuts()),
1133                     "s2", "s4");
1134             assertShortcutIds(assertAllPinned(
1135                     mManager.getPinnedShortcuts()),
1136                     "s4", "s5");
1137 
1138             ShortcutInfo s = getCallerShortcut("s2");
1139             assertFalse(s.hasIconResource());
1140             assertEquals(0, s.getIconResourceId());
1141             assertEquals("Title-s2", s.getTitle());
1142             assertEquals(Intent.ACTION_ANSWER, s.getIntent().getAction());
1143             assertEquals(1, s.getIntent().getExtras().size());
1144 
1145             s = getCallerShortcut("s4");
1146             assertFalse(s.hasIconResource());
1147             assertEquals(0, s.getIconResourceId());
1148             assertEquals("Title-s4", s.getTitle());
1149             assertEquals(Intent.ACTION_ALL_APPS, s.getIntent().getAction());
1150             assertBundleEmpty(s.getIntent().getExtras());
1151         });
1152         // TODO Check with other fields too.
1153 
1154         // TODO Check bitmap removal too.
1155 
1156         mRunningUsers.put(USER_11, true);
1157 
1158         runWithCaller(CALLING_PACKAGE_2, USER_11, () -> {
1159             mManager.updateShortcuts(list());
1160         });
1161     }
1162 
testUpdateShortcuts_icons()1163     public void testUpdateShortcuts_icons() {
1164         runWithCaller(CALLING_PACKAGE_1, UserHandle.USER_SYSTEM, () -> {
1165             assertTrue(mManager.setDynamicShortcuts(list(
1166                     makeShortcut("s1")
1167             )));
1168 
1169             // Set resource icon
1170             assertTrue(mManager.updateShortcuts(list(
1171                     new ShortcutInfo.Builder(mClientContext, "s1")
1172                             .setIcon(Icon.createWithResource(getTestContext(), R.drawable.black_32x32))
1173                             .build()
1174             )));
1175             mService.waitForBitmapSavesForTest();
1176             assertWith(getCallerShortcuts())
1177                     .forShortcutWithId("s1", si -> {
1178                         assertTrue(si.hasIconResource());
1179                         assertEquals(R.drawable.black_32x32, si.getIconResourceId());
1180                     });
1181             mService.waitForBitmapSavesForTest();
1182             // Set bitmap icon
1183             assertTrue(mManager.updateShortcuts(list(
1184                     new ShortcutInfo.Builder(mClientContext, "s1")
1185                             .setIcon(Icon.createWithBitmap(BitmapFactory.decodeResource(
1186                                     getTestContext().getResources(), R.drawable.black_64x64)))
1187                             .build()
1188             )));
1189             mService.waitForBitmapSavesForTest();
1190             assertWith(getCallerShortcuts())
1191                     .forShortcutWithId("s1", si -> {
1192                         assertTrue(si.hasIconFile());
1193                     });
1194 
1195             mInjectedCurrentTimeMillis += INTERVAL; // reset throttling
1196 
1197             // Do it again, with the reverse order (bitmap -> icon)
1198             assertTrue(mManager.setDynamicShortcuts(list(
1199                     makeShortcut("s1")
1200             )));
1201 
1202             // Set bitmap icon
1203             assertTrue(mManager.updateShortcuts(list(
1204                     new ShortcutInfo.Builder(mClientContext, "s1")
1205                             .setIcon(Icon.createWithBitmap(BitmapFactory.decodeResource(
1206                                     getTestContext().getResources(), R.drawable.black_64x64)))
1207                             .build()
1208             )));
1209             mService.waitForBitmapSavesForTest();
1210             assertWith(getCallerShortcuts())
1211                     .forShortcutWithId("s1", si -> {
1212                         assertTrue(si.hasIconFile());
1213                     });
1214 
1215             // Set resource icon
1216             assertTrue(mManager.updateShortcuts(list(
1217                     new ShortcutInfo.Builder(mClientContext, "s1")
1218                             .setIcon(Icon.createWithResource(getTestContext(), R.drawable.black_32x32))
1219                             .build()
1220             )));
1221             mService.waitForBitmapSavesForTest();
1222             assertWith(getCallerShortcuts())
1223                     .forShortcutWithId("s1", si -> {
1224                         assertTrue(si.hasIconResource());
1225                         assertEquals(R.drawable.black_32x32, si.getIconResourceId());
1226                     });
1227         });
1228     }
1229 
1230     // === Test for launcher side APIs ===
1231 
testGetShortcuts()1232     public void testGetShortcuts() {
1233 
1234         // Set up shortcuts.
1235 
1236         setCaller(CALLING_PACKAGE_1);
1237         final ShortcutInfo s1_1 = makeShortcut("s1");
1238         final ShortcutInfo s1_2 = makeShortcut("s2");
1239 
1240         assertTrue(mManager.setDynamicShortcuts(list(s1_1, s1_2)));
1241 
1242         // Because setDynamicShortcuts will update the timestamps when ranks are changing,
1243         // we explicitly set timestamps here.
1244         getCallerShortcut("s1").setTimestamp(5000);
1245         getCallerShortcut("s2").setTimestamp(1000);
1246 
1247         setCaller(CALLING_PACKAGE_2);
1248         final ShortcutInfo s2_2 = makeShortcut("s2");
1249         final ShortcutInfo s2_3 = makeShortcutWithActivity("s3",
1250                 makeComponent(ShortcutActivity2.class));
1251         final ShortcutInfo s2_4 = makeShortcutWithActivity("s4",
1252                 makeComponent(ShortcutActivity.class));
1253         assertTrue(mManager.setDynamicShortcuts(list(s2_2, s2_3, s2_4)));
1254 
1255         getCallerShortcut("s2").setTimestamp(1500);
1256         getCallerShortcut("s3").setTimestamp(3000);
1257         getCallerShortcut("s4").setTimestamp(500);
1258 
1259         setCaller(CALLING_PACKAGE_3);
1260         final ShortcutInfo s3_2 = makeShortcut("s3");
1261         assertTrue(mManager.setDynamicShortcuts(list(s3_2)));
1262 
1263         getCallerShortcut("s3").setTimestamp(START_TIME + 5000);
1264 
1265         setCaller(LAUNCHER_1);
1266 
1267         // Get dynamic
1268         assertAllDynamic(assertAllHaveTitle(assertAllNotHaveIntents(assertAllStringsResolved(
1269                 assertShortcutIds(
1270                         assertAllNotKeyFieldsOnly(
1271                                 mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
1272                         /* activity =*/ null, ShortcutQuery.FLAG_GET_DYNAMIC), getCallingUser())),
1273                         "s1", "s2")))));
1274 
1275         // Get pinned
1276         assertShortcutIds(
1277                 mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
1278                         /* activity =*/ null,
1279                         ShortcutQuery.FLAG_GET_PINNED), getCallingUser())
1280                 /* none */);
1281 
1282         // Get both, with timestamp
1283         assertAllDynamic(assertAllHaveTitle(assertAllNotHaveIntents(assertShortcutIds(
1284                 assertAllNotKeyFieldsOnly(mLauncherApps.getShortcuts(buildQuery(
1285                         /* time =*/ 1000, CALLING_PACKAGE_2,
1286                         /* activity =*/ null,
1287                         ShortcutQuery.FLAG_GET_PINNED | ShortcutQuery.FLAG_GET_DYNAMIC),
1288                         getCallingUser())),
1289                 "s2", "s3"))));
1290 
1291         // FLAG_GET_KEY_FIELDS_ONLY
1292         assertAllDynamic(assertAllNotHaveTitle(assertAllNotHaveIntents(assertShortcutIds(
1293                 assertAllKeyFieldsOnly(mLauncherApps.getShortcuts(buildQuery(
1294                         /* time =*/ 1000, CALLING_PACKAGE_2,
1295                         /* activity =*/ null,
1296                         ShortcutQuery.FLAG_GET_DYNAMIC | ShortcutQuery.FLAG_GET_KEY_FIELDS_ONLY),
1297                         getCallingUser())),
1298                 "s2", "s3"))));
1299 
1300         // Filter by activity
1301         assertAllDynamic(assertAllHaveTitle(assertAllNotHaveIntents(assertShortcutIds(
1302                 assertAllNotKeyFieldsOnly(mLauncherApps.getShortcuts(buildQuery(
1303                         /* time =*/ 0, CALLING_PACKAGE_2,
1304                         new ComponentName(CALLING_PACKAGE_2, ShortcutActivity.class.getName()),
1305                         ShortcutQuery.FLAG_GET_PINNED | ShortcutQuery.FLAG_GET_DYNAMIC),
1306                         getCallingUser())),
1307                 "s4"))));
1308 
1309         // With ID.
1310         assertAllDynamic(assertAllNotHaveTitle(assertAllNotHaveIntents(assertShortcutIds(
1311                 assertAllKeyFieldsOnly(mLauncherApps.getShortcuts(buildQuery(
1312                         /* time =*/ 1000, CALLING_PACKAGE_2, list("s3"),
1313                         /* activity =*/ null,
1314                         ShortcutQuery.FLAG_GET_DYNAMIC | ShortcutQuery.FLAG_GET_KEY_FIELDS_ONLY),
1315                         getCallingUser())),
1316                 "s3"))));
1317         assertAllDynamic(assertAllNotHaveTitle(assertAllNotHaveIntents(assertShortcutIds(
1318                 assertAllKeyFieldsOnly(mLauncherApps.getShortcuts(buildQuery(
1319                         /* time =*/ 1000, CALLING_PACKAGE_2, list("s3", "s2", "ss"),
1320                         /* activity =*/ null,
1321                         ShortcutQuery.FLAG_GET_DYNAMIC | ShortcutQuery.FLAG_GET_KEY_FIELDS_ONLY),
1322                         getCallingUser())),
1323                 "s2", "s3"))));
1324         assertAllDynamic(assertAllNotHaveTitle(assertAllNotHaveIntents(assertShortcutIds(
1325                 assertAllKeyFieldsOnly(mLauncherApps.getShortcuts(buildQuery(
1326                         /* time =*/ 1000, CALLING_PACKAGE_2, list("s3x", "s2x"),
1327                         /* activity =*/ null,
1328                         ShortcutQuery.FLAG_GET_DYNAMIC | ShortcutQuery.FLAG_GET_KEY_FIELDS_ONLY),
1329                         getCallingUser()))
1330                 /* empty */))));
1331         assertAllDynamic(assertAllNotHaveTitle(assertAllNotHaveIntents(assertShortcutIds(
1332                 assertAllKeyFieldsOnly(mLauncherApps.getShortcuts(buildQuery(
1333                         /* time =*/ 1000, CALLING_PACKAGE_2, list(),
1334                         /* activity =*/ null,
1335                         ShortcutQuery.FLAG_GET_DYNAMIC | ShortcutQuery.FLAG_GET_KEY_FIELDS_ONLY),
1336                         getCallingUser()))
1337                 /* empty */))));
1338 
1339         // Pin some shortcuts.
1340         mLauncherApps.pinShortcuts(CALLING_PACKAGE_2,
1341                 list("s3", "s4"), getCallingUser());
1342 
1343         // Pinned ones only
1344         assertAllPinned(assertAllHaveTitle(assertAllNotHaveIntents(assertShortcutIds(
1345                 assertAllNotKeyFieldsOnly(mLauncherApps.getShortcuts(buildQuery(
1346                         /* time =*/ 1000, CALLING_PACKAGE_2,
1347                         /* activity =*/ null,
1348                         ShortcutQuery.FLAG_GET_PINNED),
1349                         getCallingUser())),
1350                 "s3"))));
1351 
1352         // All packages.
1353         assertShortcutIds(assertAllNotKeyFieldsOnly(
1354                 mLauncherApps.getShortcuts(buildQuery(
1355                         /* time =*/ 5000, /* package= */ null,
1356                         /* activity =*/ null,
1357                         ShortcutQuery.FLAG_GET_DYNAMIC | ShortcutQuery.FLAG_GET_PINNED),
1358                         getCallingUser())),
1359                 "s1", "s3");
1360 
1361         assertExpectException(
1362                 IllegalArgumentException.class, "package name must also be set", () -> {
1363                     mLauncherApps.getShortcuts(buildQuery(
1364                     /* time =*/ 0, /* package= */ null, list("id"),
1365                     /* activity =*/ null, /* flags */ 0), getCallingUser());
1366                 });
1367 
1368         // TODO More tests: pinned but dynamic.
1369     }
1370 
testGetShortcuts_shortcutKinds()1371     public void testGetShortcuts_shortcutKinds() throws Exception {
1372         // Create 3 manifest and 3 dynamic shortcuts
1373         addManifestShortcutResource(
1374                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
1375                 R.xml.shortcut_3);
1376         updatePackageVersion(CALLING_PACKAGE_1, 1);
1377         mService.mPackageMonitor.onReceive(getTestContext(),
1378                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
1379 
1380         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
1381             assertTrue(mManager.setDynamicShortcuts(list(
1382                     makeShortcut("s1"), makeShortcut("s2"), makeShortcut("s3"))));
1383         });
1384 
1385         // Pin 2 and 3
1386         runWithCaller(LAUNCHER_1, USER_0, () -> {
1387             mLauncherApps.pinShortcuts(CALLING_PACKAGE_1, list("ms2", "ms3", "s2", "s3"),
1388                     HANDLE_USER_0);
1389         });
1390 
1391         // Remove ms3 and s3
1392         addManifestShortcutResource(
1393                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
1394                 R.xml.shortcut_2);
1395         updatePackageVersion(CALLING_PACKAGE_1, 1);
1396         mService.mPackageMonitor.onReceive(getTestContext(),
1397                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
1398 
1399         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
1400             assertTrue(mManager.setDynamicShortcuts(list(
1401                     makeShortcut("s1"), makeShortcut("s2"))));
1402         });
1403 
1404         // Check their status.
1405         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
1406             assertWith(getCallerShortcuts())
1407                     .haveIds("ms1", "ms2", "ms3", "s1", "s2", "s3")
1408 
1409                     .selectByIds("ms1", "ms2")
1410                     .areAllManifest()
1411                     .areAllImmutable()
1412                     .areAllNotDynamic()
1413 
1414                     .revertToOriginalList()
1415                     .selectByIds("ms3")
1416                     .areAllNotManifest()
1417                     .areAllImmutable()
1418                     .areAllDisabled()
1419                     .areAllNotDynamic()
1420 
1421                     .revertToOriginalList()
1422                     .selectByIds("s1", "s2")
1423                     .areAllNotManifest()
1424                     .areAllMutable()
1425                     .areAllDynamic()
1426 
1427                     .revertToOriginalList()
1428                     .selectByIds("s3")
1429                     .areAllNotManifest()
1430                     .areAllMutable()
1431                     .areAllEnabled()
1432                     .areAllNotDynamic()
1433 
1434                     .revertToOriginalList()
1435                     .selectByIds("s1", "ms1")
1436                     .areAllNotPinned()
1437 
1438                     .revertToOriginalList()
1439                     .selectByIds("s2", "s3", "ms2", "ms3")
1440                     .areAllPinned()
1441             ;
1442         });
1443 
1444         // Finally, actual tests.
1445         runWithCaller(LAUNCHER_1, USER_0, () -> {
1446             assertWith(mLauncherApps.getShortcuts(
1447                     buildQueryWithFlags(ShortcutQuery.FLAG_GET_DYNAMIC), HANDLE_USER_0))
1448                     .haveIds("s1", "s2");
1449             assertWith(mLauncherApps.getShortcuts(
1450                     buildQueryWithFlags(ShortcutQuery.FLAG_GET_MANIFEST), HANDLE_USER_0))
1451                     .haveIds("ms1", "ms2");
1452             assertWith(mLauncherApps.getShortcuts(
1453                     buildQueryWithFlags(ShortcutQuery.FLAG_GET_PINNED), HANDLE_USER_0))
1454                     .haveIds("s2", "s3", "ms2", "ms3");
1455 
1456             assertWith(mLauncherApps.getShortcuts(
1457                     buildQueryWithFlags(
1458                             ShortcutQuery.FLAG_GET_DYNAMIC | ShortcutQuery.FLAG_GET_PINNED
1459                     ), HANDLE_USER_0))
1460                     .haveIds("s1", "s2", "s3", "ms2", "ms3");
1461 
1462             assertWith(mLauncherApps.getShortcuts(
1463                     buildQueryWithFlags(
1464                             ShortcutQuery.FLAG_GET_MANIFEST | ShortcutQuery.FLAG_GET_PINNED
1465                     ), HANDLE_USER_0))
1466                     .haveIds("ms1", "s2", "s3", "ms2", "ms3");
1467 
1468             assertWith(mLauncherApps.getShortcuts(
1469                     buildQueryWithFlags(
1470                             ShortcutQuery.FLAG_GET_DYNAMIC | ShortcutQuery.FLAG_GET_MANIFEST
1471                     ), HANDLE_USER_0))
1472                     .haveIds("ms1", "ms2", "s1", "s2");
1473 
1474             assertWith(mLauncherApps.getShortcuts(
1475                     buildQueryWithFlags(
1476                             ShortcutQuery.FLAG_GET_ALL_KINDS
1477                     ), HANDLE_USER_0))
1478                     .haveIds("ms1", "ms2", "ms3", "s1", "s2", "s3");
1479         });
1480     }
1481 
testGetShortcuts_resolveStrings()1482     public void testGetShortcuts_resolveStrings() throws Exception {
1483         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
1484             ShortcutInfo si = new ShortcutInfo.Builder(mClientContext)
1485                     .setId("id")
1486                     .setActivity(new ComponentName(mClientContext, "dummy"))
1487                     .setTitleResId(10)
1488                     .setTextResId(11)
1489                     .setDisabledMessageResId(12)
1490                     .setIntent(makeIntent("action", ShortcutActivity.class))
1491                     .build();
1492             mManager.setDynamicShortcuts(list(si));
1493         });
1494         runWithCaller(CALLING_PACKAGE_1, USER_P0, () -> {
1495             ShortcutInfo si = new ShortcutInfo.Builder(mClientContext)
1496                     .setId("id")
1497                     .setActivity(new ComponentName(mClientContext, "dummy"))
1498                     .setTitleResId(10)
1499                     .setTextResId(11)
1500                     .setDisabledMessageResId(12)
1501                     .setIntent(makeIntent("action", ShortcutActivity.class))
1502                     .build();
1503             mManager.setDynamicShortcuts(list(si));
1504         });
1505 
1506         runWithCaller(LAUNCHER_1, USER_0, () -> {
1507             final ShortcutQuery q = new ShortcutQuery();
1508             q.setQueryFlags(ShortcutQuery.FLAG_GET_DYNAMIC);
1509 
1510             // USER 0
1511             List<ShortcutInfo> ret = assertShortcutIds(
1512                     assertAllStringsResolved(mLauncherApps.getShortcuts(q, HANDLE_USER_0)),
1513                     "id");
1514             assertEquals("string-com.android.test.1-user:0-res:10/en", ret.get(0).getTitle());
1515             assertEquals("string-com.android.test.1-user:0-res:11/en", ret.get(0).getText());
1516             assertEquals("string-com.android.test.1-user:0-res:12/en",
1517                     ret.get(0).getDisabledMessage());
1518 
1519             // USER P0
1520             ret = assertShortcutIds(
1521                     assertAllStringsResolved(mLauncherApps.getShortcuts(q, HANDLE_USER_P0)),
1522                     "id");
1523             assertEquals("string-com.android.test.1-user:20-res:10/en", ret.get(0).getTitle());
1524             assertEquals("string-com.android.test.1-user:20-res:11/en", ret.get(0).getText());
1525             assertEquals("string-com.android.test.1-user:20-res:12/en",
1526                     ret.get(0).getDisabledMessage());
1527         });
1528     }
1529 
1530     // TODO resource
testGetShortcutInfo()1531     public void testGetShortcutInfo() {
1532         // Create shortcuts.
1533         setCaller(CALLING_PACKAGE_1);
1534         final ShortcutInfo s1_1 = makeShortcut(
1535                 "s1",
1536                 "Title 1",
1537                 makeComponent(ShortcutActivity.class),
1538                 /* icon =*/ null,
1539                 makeIntent(Intent.ACTION_ASSIST, ShortcutActivity2.class,
1540                         "key1", "val1", "nest", makeBundle("key", 123)),
1541                 /* weight */ 10);
1542 
1543         final ShortcutInfo s1_2 = makeShortcut(
1544                 "s2",
1545                 "Title 2",
1546                 /* activity */ null,
1547                 /* icon =*/ null,
1548                 makeIntent(Intent.ACTION_ASSIST, ShortcutActivity3.class),
1549                 /* weight */ 12);
1550 
1551         assertTrue(mManager.setDynamicShortcuts(list(s1_1, s1_2)));
1552         dumpsysOnLogcat();
1553 
1554         setCaller(CALLING_PACKAGE_2);
1555         final ShortcutInfo s2_1 = makeShortcut(
1556                 "s1",
1557                 "ABC",
1558                 makeComponent(ShortcutActivity2.class),
1559                 /* icon =*/ null,
1560                 makeIntent(Intent.ACTION_ANSWER, ShortcutActivity2.class,
1561                         "key1", "val1", "nest", makeBundle("key", 123)),
1562                 /* weight */ 10);
1563         assertTrue(mManager.setDynamicShortcuts(list(s2_1)));
1564         dumpsysOnLogcat();
1565 
1566         // Pin some.
1567         setCaller(LAUNCHER_1);
1568 
1569         mLauncherApps.pinShortcuts(CALLING_PACKAGE_1,
1570                 list("s2"), getCallingUser());
1571 
1572         dumpsysOnLogcat();
1573 
1574         // Delete some.
1575         setCaller(CALLING_PACKAGE_1);
1576         assertShortcutIds(mManager.getPinnedShortcuts(), "s2");
1577         mManager.removeDynamicShortcuts(list("s2"));
1578         assertShortcutIds(mManager.getPinnedShortcuts(), "s2");
1579 
1580         dumpsysOnLogcat();
1581 
1582         setCaller(LAUNCHER_1);
1583         List<ShortcutInfo> list;
1584 
1585         // Note we don't guarantee the orders.
1586         list = assertShortcutIds(assertAllHaveTitle(assertAllNotHaveIntents(
1587                 assertAllNotKeyFieldsOnly(
1588                         mLauncherApps.getShortcutInfo(CALLING_PACKAGE_1,
1589                                 list("s2", "s1", "s3", null), getCallingUser())))),
1590                 "s1", "s2");
1591         assertEquals("Title 1", findById(list, "s1").getTitle());
1592         assertEquals("Title 2", findById(list, "s2").getTitle());
1593 
1594         assertShortcutIds(assertAllHaveTitle(assertAllNotHaveIntents(
1595                 mLauncherApps.getShortcutInfo(CALLING_PACKAGE_1,
1596                         list("s3"), getCallingUser())))
1597                 /* none */);
1598 
1599         list = assertShortcutIds(assertAllHaveTitle(assertAllNotHaveIntents(
1600                 mLauncherApps.getShortcutInfo(CALLING_PACKAGE_2,
1601                         list("s1", "s2", "s3"), getCallingUser()))),
1602                 "s1");
1603         assertEquals("ABC", findById(list, "s1").getTitle());
1604     }
1605 
testPinShortcutAndGetPinnedShortcuts()1606     public void testPinShortcutAndGetPinnedShortcuts() {
1607         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
1608             final ShortcutInfo s1_1 = makeShortcutWithTimestamp("s1", 1000);
1609             final ShortcutInfo s1_2 = makeShortcutWithTimestamp("s2", 2000);
1610 
1611             assertTrue(mManager.setDynamicShortcuts(list(s1_1, s1_2)));
1612         });
1613 
1614         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
1615             final ShortcutInfo s2_2 = makeShortcutWithTimestamp("s2", 1500);
1616             final ShortcutInfo s2_3 = makeShortcutWithTimestamp("s3", 3000);
1617             final ShortcutInfo s2_4 = makeShortcutWithTimestamp("s4", 500);
1618             assertTrue(mManager.setDynamicShortcuts(list(s2_2, s2_3, s2_4)));
1619         });
1620 
1621         runWithCaller(CALLING_PACKAGE_3, USER_0, () -> {
1622             final ShortcutInfo s3_2 = makeShortcutWithTimestamp("s2", 1000);
1623             assertTrue(mManager.setDynamicShortcuts(list(s3_2)));
1624         });
1625 
1626         // Pin some.
1627         runWithCaller(LAUNCHER_1, USER_0, () -> {
1628             mLauncherApps.pinShortcuts(CALLING_PACKAGE_1,
1629                     list("s2", "s3"), getCallingUser());
1630 
1631             mLauncherApps.pinShortcuts(CALLING_PACKAGE_2,
1632                     list("s3", "s4", "s5"), getCallingUser());
1633 
1634             mLauncherApps.pinShortcuts(CALLING_PACKAGE_3,
1635                     list("s3"), getCallingUser());  // Note ID doesn't exist
1636         });
1637 
1638         // Delete some.
1639         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
1640             assertShortcutIds(mManager.getPinnedShortcuts(), "s2");
1641             mManager.removeDynamicShortcuts(list("s2"));
1642             assertShortcutIds(mManager.getPinnedShortcuts(), "s2");
1643 
1644             assertShortcutIds(mManager.getDynamicShortcuts(), "s1");
1645         });
1646 
1647         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
1648             assertShortcutIds(mManager.getPinnedShortcuts(), "s3", "s4");
1649             mManager.removeDynamicShortcuts(list("s3"));
1650             assertShortcutIds(mManager.getPinnedShortcuts(), "s3", "s4");
1651 
1652             assertShortcutIds(mManager.getDynamicShortcuts(), "s2", "s4");
1653         });
1654 
1655         runWithCaller(CALLING_PACKAGE_3, USER_0, () -> {
1656             assertShortcutIds(mManager.getPinnedShortcuts() /* none */);
1657             mManager.removeDynamicShortcuts(list("s2"));
1658             assertShortcutIds(mManager.getPinnedShortcuts() /* none */);
1659 
1660             assertEmpty(mManager.getDynamicShortcuts());
1661         });
1662 
1663         // Get pinned shortcuts from launcher
1664         runWithCaller(LAUNCHER_1, USER_0, () -> {
1665             // CALLING_PACKAGE_1 deleted s2, but it's pinned, so it still exists.
1666             assertShortcutIds(assertAllPinned(assertAllNotKeyFieldsOnly(assertAllEnabled(
1667                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
1668                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), getCallingUser())))),
1669                     "s2");
1670 
1671             assertShortcutIds(assertAllPinned(assertAllNotKeyFieldsOnly(assertAllEnabled(
1672                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
1673                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), getCallingUser())))),
1674                     "s3", "s4");
1675 
1676             assertShortcutIds(assertAllPinned(assertAllNotKeyFieldsOnly(assertAllEnabled(
1677                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_3,
1678                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), getCallingUser()))))
1679                     /* none */);
1680         });
1681     }
1682 
1683     /**
1684      * This is similar to the above test, except it used "disable" instead of "remove".  It also
1685      * does "enable".
1686      */
testDisableAndEnableShortcuts()1687     public void testDisableAndEnableShortcuts() {
1688         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
1689             final ShortcutInfo s1_1 = makeShortcutWithTimestamp("s1", 1000);
1690             final ShortcutInfo s1_2 = makeShortcutWithTimestamp("s2", 2000);
1691 
1692             assertTrue(mManager.setDynamicShortcuts(list(s1_1, s1_2)));
1693         });
1694 
1695         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
1696             final ShortcutInfo s2_2 = makeShortcutWithTimestamp("s2", 1500);
1697             final ShortcutInfo s2_3 = makeShortcutWithTimestamp("s3", 3000);
1698             final ShortcutInfo s2_4 = makeShortcutWithTimestamp("s4", 500);
1699             assertTrue(mManager.setDynamicShortcuts(list(s2_2, s2_3, s2_4)));
1700         });
1701 
1702         runWithCaller(CALLING_PACKAGE_3, USER_0, () -> {
1703             final ShortcutInfo s3_2 = makeShortcutWithTimestamp("s2", 1000);
1704             assertTrue(mManager.setDynamicShortcuts(list(s3_2)));
1705         });
1706 
1707         // Pin some.
1708         runWithCaller(LAUNCHER_1, USER_0, () -> {
1709             mLauncherApps.pinShortcuts(CALLING_PACKAGE_1,
1710                     list("s2", "s3"), getCallingUser());
1711 
1712             mLauncherApps.pinShortcuts(CALLING_PACKAGE_2,
1713                     list("s3", "s4", "s5"), getCallingUser());
1714 
1715             mLauncherApps.pinShortcuts(CALLING_PACKAGE_3,
1716                     list("s3"), getCallingUser());  // Note ID doesn't exist
1717         });
1718 
1719         // Disable some.
1720         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
1721             assertShortcutIds(mManager.getPinnedShortcuts(), "s2");
1722 
1723             mManager.updateShortcuts(list(
1724                     new ShortcutInfo.Builder(mClientContext, "s2").setDisabledMessage("xyz")
1725                             .build()));
1726 
1727             mManager.disableShortcuts(list("s2"));
1728 
1729             assertShortcutIds(mManager.getPinnedShortcuts(), "s2");
1730             assertShortcutIds(mManager.getDynamicShortcuts(), "s1");
1731         });
1732 
1733         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
1734             assertShortcutIds(mManager.getPinnedShortcuts(), "s3", "s4");
1735 
1736             // disable should work even if a shortcut is not dynamic, so try calling "remove" first
1737             // here.
1738             mManager.removeDynamicShortcuts(list("s3"));
1739             mManager.disableShortcuts(list("s3"));
1740 
1741             assertShortcutIds(mManager.getPinnedShortcuts(), "s3", "s4");
1742             assertShortcutIds(mManager.getDynamicShortcuts(), "s2", "s4");
1743         });
1744 
1745         runWithCaller(CALLING_PACKAGE_3, USER_0, () -> {
1746             assertShortcutIds(mManager.getPinnedShortcuts() /* none */);
1747 
1748             mManager.disableShortcuts(list("s2"));
1749 
1750             assertShortcutIds(mManager.getPinnedShortcuts() /* none */);
1751 
1752             assertEmpty(mManager.getDynamicShortcuts());
1753             assertEmpty(getCallerShortcuts());
1754         });
1755 
1756         // Get pinned shortcuts from launcher
1757         runWithCaller(LAUNCHER_1, USER_0, () -> {
1758             // CALLING_PACKAGE_1 deleted s2, but it's pinned, so it still exists, and disabled.
1759             assertWith(mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
1760                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), getCallingUser()))
1761                     .haveIds("s2")
1762                     .areAllWithDisabledReason(ShortcutInfo.DISABLED_REASON_BY_APP)
1763                     .forAllShortcuts(si -> {
1764                         assertEquals("xyz", si.getDisabledMessage());
1765                     })
1766                     .areAllPinned()
1767                     .areAllNotWithKeyFieldsOnly()
1768                     .areAllDisabled();
1769             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s2", USER_0,
1770                     ActivityNotFoundException.class);
1771 
1772             // Here, s4 is still enabled and launchable, but s3 is disabled.
1773             assertWith(mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
1774                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), getCallingUser()))
1775                     .haveIds("s3", "s4")
1776                     .areAllPinned()
1777                     .areAllNotWithKeyFieldsOnly()
1778 
1779                     .selectByIds("s3")
1780                     .areAllDisabled()
1781 
1782                     .revertToOriginalList()
1783                     .selectByIds("s4")
1784                     .areAllEnabled();
1785 
1786             assertStartShortcutThrowsException(CALLING_PACKAGE_2, "s3", USER_0,
1787                     ActivityNotFoundException.class);
1788             assertShortcutLaunchable(CALLING_PACKAGE_2, "s4", USER_0);
1789 
1790             assertShortcutIds(assertAllPinned(assertAllNotKeyFieldsOnly(assertAllEnabled(
1791                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_3,
1792                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), getCallingUser()))))
1793                     /* none */);
1794         });
1795 
1796         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
1797             mManager.enableShortcuts(list("s2"));
1798 
1799             assertShortcutIds(mManager.getPinnedShortcuts(), "s2");
1800             assertShortcutIds(mManager.getDynamicShortcuts(), "s1");
1801         });
1802         runWithCaller(LAUNCHER_1, USER_0, () -> {
1803             // CALLING_PACKAGE_1 deleted s2, but it's pinned, so it still exists.
1804             assertShortcutIds(assertAllPinned(assertAllNotKeyFieldsOnly(assertAllEnabled(
1805                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
1806                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), getCallingUser())))),
1807                     "s2");
1808             assertShortcutLaunchable(CALLING_PACKAGE_1, "s2", USER_0);
1809         });
1810     }
1811 
testDisableShortcuts_thenRepublish()1812     public void testDisableShortcuts_thenRepublish() {
1813         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
1814             assertTrue(mManager.setDynamicShortcuts(list(
1815                     makeShortcut("s1"), makeShortcut("s2"), makeShortcut("s3"))));
1816 
1817             runWithCaller(LAUNCHER_1, USER_0, () -> {
1818                 mLauncherApps.pinShortcuts(
1819                         CALLING_PACKAGE_1, list("s1", "s2", "s3"), HANDLE_USER_0);
1820             });
1821 
1822             mManager.disableShortcuts(list("s1", "s2", "s3"));
1823 
1824             assertWith(getCallerShortcuts())
1825                     .haveIds("s1", "s2", "s3")
1826                     .areAllNotDynamic()
1827                     .areAllPinned()
1828                     .areAllDisabled();
1829 
1830             // Make sure updateShortcuts() will not re-enable them.
1831             assertTrue(mManager.updateShortcuts(list(
1832                     makeShortcut("s1"), makeShortcut("s2"), makeShortcut("s3"))));
1833 
1834             assertWith(getCallerShortcuts())
1835                     .haveIds("s1", "s2", "s3")
1836                     .areAllNotDynamic()
1837                     .areAllPinned()
1838                     .areAllDisabled();
1839 
1840             // Re-publish s1 with setDynamicShortcuts.
1841             mInjectedCurrentTimeMillis += INTERVAL; // reset throttling
1842 
1843             assertTrue(mManager.setDynamicShortcuts(list(
1844                     makeShortcut("s1"))));
1845 
1846             assertWith(getCallerShortcuts())
1847                     .haveIds("s1", "s2", "s3")
1848 
1849                     .selectByIds("s1")
1850                     .areAllDynamic()
1851                     .areAllPinned()
1852                     .areAllEnabled()
1853 
1854                     .revertToOriginalList()
1855                     .selectByIds("s2", "s3")
1856                     .areAllNotDynamic()
1857                     .areAllPinned()
1858                     .areAllDisabled();
1859 
1860             // Re-publish s2 with addDynamicShortcuts.
1861             mInjectedCurrentTimeMillis += INTERVAL; // reset throttling
1862 
1863             assertTrue(mManager.addDynamicShortcuts(list(
1864                     makeShortcut("s2"))));
1865 
1866             assertWith(getCallerShortcuts())
1867                     .haveIds("s1", "s2", "s3")
1868 
1869                     .selectByIds("s1", "s2")
1870                     .areAllDynamic()
1871                     .areAllPinned()
1872                     .areAllEnabled()
1873 
1874                     .revertToOriginalList()
1875                     .selectByIds("s3")
1876                     .areAllNotDynamic()
1877                     .areAllPinned()
1878                     .areAllDisabled();
1879         });
1880     }
1881 
testPinShortcutAndGetPinnedShortcuts_multi()1882     public void testPinShortcutAndGetPinnedShortcuts_multi() {
1883         // Create some shortcuts.
1884         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
1885             assertTrue(mManager.setDynamicShortcuts(list(
1886                     makeShortcut("s1"), makeShortcut("s2"), makeShortcut("s3"))));
1887         });
1888 
1889         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
1890             assertTrue(mManager.setDynamicShortcuts(list(
1891                     makeShortcut("s1"), makeShortcut("s2"), makeShortcut("s3"))));
1892         });
1893 
1894         dumpsysOnLogcat();
1895 
1896         // Pin some.
1897         runWithCaller(LAUNCHER_1, USER_0, () -> {
1898             mLauncherApps.pinShortcuts(CALLING_PACKAGE_1,
1899                     list("s3", "s4"), getCallingUser());
1900 
1901             mLauncherApps.pinShortcuts(CALLING_PACKAGE_2,
1902                     list("s1", "s2", "s4"), getCallingUser());
1903         });
1904 
1905         dumpsysOnLogcat();
1906 
1907         // Delete some.
1908         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
1909             assertShortcutIds(mManager.getPinnedShortcuts(), "s3");
1910             mManager.removeDynamicShortcuts(list("s3"));
1911             assertShortcutIds(mManager.getPinnedShortcuts(), "s3");
1912         });
1913 
1914         dumpsysOnLogcat();
1915 
1916         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
1917             assertShortcutIds(mManager.getPinnedShortcuts(), "s1", "s2");
1918             mManager.removeDynamicShortcuts(list("s1"));
1919             mManager.removeDynamicShortcuts(list("s3"));
1920             assertShortcutIds(mManager.getPinnedShortcuts(), "s1", "s2");
1921         });
1922 
1923         dumpsysOnLogcat();
1924 
1925         // Get pinned shortcuts from launcher
1926         runWithCaller(LAUNCHER_1, USER_0, () -> {
1927             assertShortcutIds(assertAllPinned(assertAllNotKeyFieldsOnly(
1928                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
1929                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), getCallingUser()))),
1930                     "s3");
1931 
1932             assertShortcutIds(assertAllPinned(assertAllNotKeyFieldsOnly(
1933                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
1934                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), getCallingUser()))),
1935                     "s1", "s2");
1936 
1937             assertShortcutIds(assertAllDynamicOrPinned(
1938                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
1939                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED
1940                                     | ShortcutQuery.FLAG_GET_DYNAMIC), getCallingUser())),
1941                     "s1", "s2", "s3");
1942 
1943             assertShortcutIds(assertAllDynamicOrPinned(
1944                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
1945                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED
1946                                     | ShortcutQuery.FLAG_GET_DYNAMIC), getCallingUser())),
1947                     "s1", "s2");
1948         });
1949 
1950         dumpsysOnLogcat("Before launcher 2");
1951 
1952         runWithCaller(LAUNCHER_2, USER_0, () -> {
1953             // Launcher2 still has no pinned ones.
1954             assertShortcutIds(assertAllPinned(assertAllNotKeyFieldsOnly(
1955                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
1956                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), getCallingUser())))
1957                     /* none */);
1958             assertShortcutIds(assertAllPinned(assertAllNotKeyFieldsOnly(
1959                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
1960                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), getCallingUser())))
1961                     /* none */);
1962 
1963             // Make sure FLAG_MATCH_ALL_PINNED will be ignored.
1964             assertWith(mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
1965                     /* activity =*/ null, ShortcutQuery.FLAG_MATCH_PINNED
1966                             | ShortcutQuery.FLAG_MATCH_PINNED_BY_ANY_LAUNCHER), getCallingUser()))
1967                     .isEmpty();
1968 
1969             // Make sure the special permission works.
1970             mInjectCheckAccessShortcutsPermission = true;
1971 
1972             dumpsysOnLogcat("All-pinned");
1973 
1974             assertWith(mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
1975                     /* activity =*/ null, ShortcutQuery.FLAG_MATCH_PINNED
1976                             | ShortcutQuery.FLAG_MATCH_PINNED_BY_ANY_LAUNCHER), getCallingUser()))
1977                     .haveIds("s1", "s2");
1978             assertWith(mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
1979                     /* activity =*/ null, ShortcutQuery.FLAG_MATCH_PINNED), getCallingUser()))
1980                     .isEmpty();
1981 
1982             assertShortcutLaunchable(CALLING_PACKAGE_2, "s1", getCallingUser().getIdentifier());
1983 
1984             mInjectCheckAccessShortcutsPermission = false;
1985 
1986             assertShortcutNotLaunched(CALLING_PACKAGE_2, "s1", getCallingUser().getIdentifier());
1987 
1988             assertShortcutIds(assertAllDynamic(
1989                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
1990                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED
1991                                     | ShortcutQuery.FLAG_GET_DYNAMIC), getCallingUser())),
1992                     "s1", "s2");
1993             assertShortcutIds(assertAllDynamic(
1994                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
1995                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED
1996                                     | ShortcutQuery.FLAG_GET_DYNAMIC), getCallingUser())),
1997                     "s2");
1998 
1999             // Now pin some.
2000             mLauncherApps.pinShortcuts(CALLING_PACKAGE_1,
2001                     list("s1", "s2"), getCallingUser());
2002 
2003             mLauncherApps.pinShortcuts(CALLING_PACKAGE_2,
2004                     list("s1", "s2"), getCallingUser());
2005 
2006             assertShortcutIds(assertAllDynamic(
2007                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
2008                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED
2009                                     | ShortcutQuery.FLAG_GET_DYNAMIC), getCallingUser())),
2010                     "s1", "s2");
2011 
2012             // S1 was not visible to it, so shouldn't be pinned.
2013             assertShortcutIds(assertAllDynamic(
2014                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
2015                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED
2016                                     | ShortcutQuery.FLAG_GET_DYNAMIC), getCallingUser())),
2017                     "s2");
2018         });
2019 
2020         // Re-initialize and load from the files.
2021         mService.saveDirtyInfo();
2022         initService();
2023 
2024         // Load from file.
2025         mService.handleUnlockUser(USER_0);
2026 
2027         // Make sure package info is restored too.
2028         runWithCaller(LAUNCHER_1, USER_0, () -> {
2029             assertShortcutIds(assertAllPinned(assertAllNotKeyFieldsOnly(
2030                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
2031                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), getCallingUser()))),
2032                     "s3");
2033             assertShortcutIds(assertAllPinned(assertAllNotKeyFieldsOnly(
2034                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
2035                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), getCallingUser()))),
2036                     "s1", "s2");
2037         });
2038         runWithCaller(LAUNCHER_2, USER_0, () -> {
2039             assertShortcutIds(assertAllDynamic(
2040                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
2041                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED
2042                                     | ShortcutQuery.FLAG_GET_DYNAMIC), getCallingUser())),
2043                     "s1", "s2");
2044             assertShortcutIds(assertAllDynamic(
2045                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
2046                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED
2047                                     | ShortcutQuery.FLAG_GET_DYNAMIC), getCallingUser())),
2048                     "s2");
2049         });
2050 
2051         // Delete all dynamic.
2052         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
2053             mManager.removeAllDynamicShortcuts();
2054 
2055             assertEquals(0, mManager.getDynamicShortcuts().size());
2056             assertShortcutIds(assertAllPinned(mManager.getPinnedShortcuts()), "s1", "s2", "s3");
2057         });
2058         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
2059             mManager.removeAllDynamicShortcuts();
2060 
2061             assertEquals(0, mManager.getDynamicShortcuts().size());
2062             assertShortcutIds(assertAllPinned(mManager.getPinnedShortcuts()), "s2", "s1");
2063         });
2064 
2065         runWithCaller(LAUNCHER_1, USER_0, () -> {
2066             assertShortcutIds(assertAllPinned(assertAllNotKeyFieldsOnly(
2067                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
2068                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), getCallingUser()))),
2069                     "s3");
2070 
2071             assertShortcutIds(assertAllPinned(assertAllNotKeyFieldsOnly(
2072                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
2073                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), getCallingUser()))),
2074                     "s1", "s2");
2075 
2076             // from all packages.
2077             assertShortcutIds(assertAllPinned(assertAllNotKeyFieldsOnly(
2078                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, null,
2079                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), getCallingUser()))),
2080                     "s1", "s2", "s3");
2081 
2082             // Update pined.  Note s2 and s3 are actually available, but not visible to this
2083             // launcher, so still can't be pinned.
2084             mLauncherApps.pinShortcuts(CALLING_PACKAGE_1, list("s1", "s2", "s3", "s4"),
2085                     getCallingUser());
2086 
2087             assertShortcutIds(assertAllPinned(assertAllNotKeyFieldsOnly(
2088                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
2089                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), getCallingUser()))),
2090                     "s3");
2091         });
2092         // Re-publish s1.
2093         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
2094             assertTrue(mManager.addDynamicShortcuts(list(makeShortcut("s1"))));
2095 
2096             assertShortcutIds(assertAllDynamic(mManager.getDynamicShortcuts()), "s1");
2097             assertShortcutIds(assertAllPinned(mManager.getPinnedShortcuts()), "s1", "s2", "s3");
2098         });
2099         runWithCaller(LAUNCHER_1, USER_0, () -> {
2100             assertShortcutIds(assertAllPinned(assertAllNotKeyFieldsOnly(
2101                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
2102                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), getCallingUser()))),
2103                     "s3");
2104 
2105             // Now "s1" is visible, so can be pinned.
2106             mLauncherApps.pinShortcuts(CALLING_PACKAGE_1, list("s1", "s2", "s3", "s4"),
2107                     getCallingUser());
2108 
2109             assertShortcutIds(assertAllPinned(assertAllNotKeyFieldsOnly(
2110                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
2111                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), getCallingUser()))),
2112                     "s1", "s3");
2113         });
2114 
2115         // Now clear pinned shortcuts.  First, from launcher 1.
2116         runWithCaller(LAUNCHER_1, USER_0, () -> {
2117             mLauncherApps.pinShortcuts(CALLING_PACKAGE_1, list(), getCallingUser());
2118             mLauncherApps.pinShortcuts(CALLING_PACKAGE_2, list(), getCallingUser());
2119 
2120             assertEquals(0,
2121                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
2122                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), getCallingUser()).size());
2123             assertEquals(0,
2124                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
2125                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), getCallingUser()).size());
2126         });
2127         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
2128             assertShortcutIds(assertAllDynamic(mManager.getDynamicShortcuts()), "s1");
2129             assertShortcutIds(assertAllPinned(mManager.getPinnedShortcuts()), "s1", "s2");
2130         });
2131         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
2132             assertEquals(0, mManager.getDynamicShortcuts().size());
2133             assertShortcutIds(assertAllPinned(mManager.getPinnedShortcuts()), "s2");
2134         });
2135 
2136         // Clear all pins from launcher 2.
2137         runWithCaller(LAUNCHER_2, USER_0, () -> {
2138             mLauncherApps.pinShortcuts(CALLING_PACKAGE_1, list(), getCallingUser());
2139             mLauncherApps.pinShortcuts(CALLING_PACKAGE_2, list(), getCallingUser());
2140 
2141             assertEquals(0,
2142                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
2143                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), getCallingUser()).size());
2144             assertEquals(0,
2145                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
2146                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), getCallingUser()).size());
2147         });
2148         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
2149             assertShortcutIds(assertAllDynamic(mManager.getDynamicShortcuts()), "s1");
2150             assertEquals(0, mManager.getPinnedShortcuts().size());
2151         });
2152         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
2153             assertEquals(0, mManager.getDynamicShortcuts().size());
2154             assertEquals(0, mManager.getPinnedShortcuts().size());
2155         });
2156     }
2157 
testPinShortcutAndGetPinnedShortcuts_assistant()2158     public void testPinShortcutAndGetPinnedShortcuts_assistant() {
2159         // Create some shortcuts.
2160         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
2161             assertTrue(mManager.setDynamicShortcuts(list(
2162                     makeShortcut("s1"), makeShortcut("s2"), makeShortcut("s3"))));
2163         });
2164 
2165         // Pin some.
2166         runWithCaller(LAUNCHER_1, USER_0, () -> {
2167             mLauncherApps.pinShortcuts(CALLING_PACKAGE_1,
2168                     list("s3", "s4"), getCallingUser());
2169         });
2170 
2171         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
2172             assertTrue(mManager.setDynamicShortcuts(list(
2173                     makeShortcut("s1"))));
2174         });
2175 
2176         runWithCaller(LAUNCHER_2, USER_0, () -> {
2177             final ShortcutQuery allPinned = new ShortcutQuery().setQueryFlags(
2178                     ShortcutQuery.FLAG_MATCH_PINNED_BY_ANY_LAUNCHER);
2179 
2180             assertWith(mLauncherApps.getShortcuts(allPinned, HANDLE_USER_0))
2181                     .isEmpty();
2182 
2183             assertShortcutLaunchable(CALLING_PACKAGE_1, "s1", USER_0);
2184             assertShortcutNotLaunched(CALLING_PACKAGE_1, "s3", USER_0);
2185             assertShortcutNotLaunched(CALLING_PACKAGE_1, "s4", USER_0);
2186 
2187             // Make it the assistant app.
2188             mInternal.setShortcutHostPackage("assistant", LAUNCHER_2, USER_0);
2189             assertWith(mLauncherApps.getShortcuts(allPinned, HANDLE_USER_0))
2190                     .haveIds("s3");
2191 
2192             assertShortcutLaunchable(CALLING_PACKAGE_1, "s1", USER_0);
2193             assertShortcutLaunchable(CALLING_PACKAGE_1, "s3", USER_0);
2194             assertShortcutNotLaunched(CALLING_PACKAGE_1, "s4", USER_0);
2195 
2196             mInternal.setShortcutHostPackage("another-type", LAUNCHER_3, USER_0);
2197             assertWith(mLauncherApps.getShortcuts(allPinned, HANDLE_USER_0))
2198                     .haveIds("s3");
2199 
2200             mInternal.setShortcutHostPackage("assistant", null, USER_0);
2201             assertWith(mLauncherApps.getShortcuts(allPinned, HANDLE_USER_0))
2202                     .isEmpty();
2203 
2204             mInternal.setShortcutHostPackage("assistant", LAUNCHER_2, USER_0);
2205             assertWith(mLauncherApps.getShortcuts(allPinned, HANDLE_USER_0))
2206                     .haveIds("s3");
2207 
2208             mInternal.setShortcutHostPackage("assistant", LAUNCHER_1, USER_0);
2209             assertWith(mLauncherApps.getShortcuts(allPinned, HANDLE_USER_0))
2210                     .isEmpty();
2211         });
2212     }
2213 
testPinShortcutAndGetPinnedShortcuts_crossProfile_plusLaunch()2214     public void testPinShortcutAndGetPinnedShortcuts_crossProfile_plusLaunch() {
2215         // Create some shortcuts.
2216         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
2217             assertTrue(mManager.setDynamicShortcuts(list(
2218                     makeShortcut("s1"), makeShortcut("s2"), makeShortcut("s3"))));
2219         });
2220         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
2221             assertTrue(mManager.setDynamicShortcuts(list(
2222                     makeShortcut("s1"), makeShortcut("s2"), makeShortcut("s3"))));
2223         });
2224 
2225         mRunningUsers.put(USER_10, true);
2226 
2227         runWithCaller(CALLING_PACKAGE_1, USER_10, () -> {
2228             assertTrue(mManager.setDynamicShortcuts(list(
2229                     makeShortcut("s1"), makeShortcut("s2"), makeShortcut("s3"),
2230                     makeShortcut("s4"), makeShortcut("s5"), makeShortcut("s6"))));
2231         });
2232 
2233         // Pin some shortcuts and see the result.
2234 
2235         runWithCaller(LAUNCHER_1, USER_0, () -> {
2236             mLauncherApps.pinShortcuts(CALLING_PACKAGE_1,
2237                     list("s1"), HANDLE_USER_0);
2238 
2239             mLauncherApps.pinShortcuts(CALLING_PACKAGE_2,
2240                     list("s1", "s2", "s3"), HANDLE_USER_0);
2241         });
2242 
2243         runWithCaller(LAUNCHER_1, USER_P0, () -> {
2244             mLauncherApps.pinShortcuts(CALLING_PACKAGE_1,
2245                     list("s2"), HANDLE_USER_0);
2246 
2247             mLauncherApps.pinShortcuts(CALLING_PACKAGE_2,
2248                     list("s2", "s3"), HANDLE_USER_0);
2249         });
2250 
2251         runWithCaller(LAUNCHER_2, USER_P0, () -> {
2252             mLauncherApps.pinShortcuts(CALLING_PACKAGE_1,
2253                     list("s3"), HANDLE_USER_0);
2254 
2255             mLauncherApps.pinShortcuts(CALLING_PACKAGE_2,
2256                     list("s3"), HANDLE_USER_0);
2257         });
2258 
2259         runWithCaller(LAUNCHER_2, USER_10, () -> {
2260             mLauncherApps.pinShortcuts(CALLING_PACKAGE_1,
2261                     list("s1", "s2", "s3"), HANDLE_USER_10);
2262         });
2263 
2264         // First, make sure managed profile can't see other profiles.
2265         runWithCaller(LAUNCHER_1, USER_P1, () -> {
2266 
2267             final ShortcutQuery q = new ShortcutQuery().setQueryFlags(
2268                     ShortcutQuery.FLAG_MATCH_DYNAMIC | ShortcutQuery.FLAG_MATCH_PINNED
2269                             | ShortcutQuery.FLAG_MATCH_MANIFEST);
2270 
2271             // No shortcuts are visible.
2272             assertWith(mLauncherApps.getShortcuts(q, HANDLE_USER_0)).isEmpty();
2273 
2274             mLauncherApps.pinShortcuts(CALLING_PACKAGE_1, list("s1"), HANDLE_USER_0);
2275 
2276             // Should have no effects.
2277             assertWith(mLauncherApps.getShortcuts(q, HANDLE_USER_0)).isEmpty();
2278 
2279             assertShortcutNotLaunched(CALLING_PACKAGE_1, "s1", USER_0);
2280         });
2281 
2282         // Cross profile pinning.
2283         final int PIN_AND_DYNAMIC = ShortcutQuery.FLAG_GET_PINNED | ShortcutQuery.FLAG_GET_DYNAMIC;
2284 
2285         runWithCaller(LAUNCHER_1, USER_0, () -> {
2286             assertShortcutIds(assertAllPinned(
2287                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
2288                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), HANDLE_USER_0)),
2289                     "s1");
2290             assertShortcutIds(assertAllDynamic(
2291                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
2292                     /* activity =*/ null, ShortcutQuery.FLAG_GET_DYNAMIC), HANDLE_USER_0)),
2293                     "s1", "s2", "s3");
2294             assertShortcutIds(assertAllDynamicOrPinned(
2295                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
2296                     /* activity =*/ null, PIN_AND_DYNAMIC), HANDLE_USER_0)),
2297                     "s1", "s2", "s3");
2298 
2299             assertShortcutIds(assertAllPinned(
2300                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
2301                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), HANDLE_USER_0)),
2302                     "s1", "s2", "s3");
2303             assertShortcutIds(assertAllDynamic(
2304                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
2305                     /* activity =*/ null, ShortcutQuery.FLAG_GET_DYNAMIC), HANDLE_USER_0)),
2306                     "s1", "s2", "s3");
2307             assertShortcutIds(assertAllDynamicOrPinned(
2308                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
2309                     /* activity =*/ null, PIN_AND_DYNAMIC), HANDLE_USER_0)),
2310                     "s1", "s2", "s3");
2311 
2312             assertShortcutLaunchable(CALLING_PACKAGE_1, "s1", USER_0);
2313             assertShortcutLaunchable(CALLING_PACKAGE_1, "s2", USER_0);
2314             assertShortcutLaunchable(CALLING_PACKAGE_1, "s3", USER_0);
2315 
2316             assertShortcutLaunchable(CALLING_PACKAGE_2, "s1", USER_0);
2317             assertShortcutLaunchable(CALLING_PACKAGE_2, "s2", USER_0);
2318             assertShortcutLaunchable(CALLING_PACKAGE_2, "s3", USER_0);
2319 
2320             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s1", USER_10,
2321                     SecurityException.class);
2322             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s2", USER_10,
2323                     SecurityException.class);
2324             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s3", USER_10,
2325                     SecurityException.class);
2326             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s4", USER_10,
2327                     SecurityException.class);
2328             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s5", USER_10,
2329                     SecurityException.class);
2330             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s6", USER_10,
2331                     SecurityException.class);
2332         });
2333         runWithCaller(LAUNCHER_1, USER_P0, () -> {
2334             assertShortcutIds(assertAllPinned(
2335                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
2336                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), HANDLE_USER_0)),
2337                     "s2");
2338             assertShortcutIds(assertAllDynamic(
2339                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
2340                     /* activity =*/ null, ShortcutQuery.FLAG_GET_DYNAMIC), HANDLE_USER_0)),
2341                     "s1", "s2", "s3");
2342             assertShortcutIds(assertAllDynamicOrPinned(
2343                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
2344                     /* activity =*/ null, PIN_AND_DYNAMIC), HANDLE_USER_0)),
2345                     "s1", "s2", "s3");
2346 
2347             assertShortcutIds(assertAllPinned(
2348                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
2349                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), HANDLE_USER_0)),
2350                     "s2", "s3");
2351             assertShortcutIds(assertAllDynamic(
2352                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
2353                     /* activity =*/ null, ShortcutQuery.FLAG_GET_DYNAMIC), HANDLE_USER_0)),
2354                     "s1", "s2", "s3");
2355             assertShortcutIds(assertAllDynamicOrPinned(
2356                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
2357                     /* activity =*/ null, PIN_AND_DYNAMIC), HANDLE_USER_0)),
2358                     "s1", "s2", "s3");
2359 
2360             assertShortcutLaunchable(CALLING_PACKAGE_1, "s1", USER_0);
2361             assertShortcutLaunchable(CALLING_PACKAGE_1, "s2", USER_0);
2362             assertShortcutLaunchable(CALLING_PACKAGE_1, "s3", USER_0);
2363 
2364             assertShortcutLaunchable(CALLING_PACKAGE_2, "s1", USER_0);
2365             assertShortcutLaunchable(CALLING_PACKAGE_2, "s2", USER_0);
2366             assertShortcutLaunchable(CALLING_PACKAGE_2, "s3", USER_0);
2367 
2368             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s1", USER_10,
2369                     SecurityException.class);
2370             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s2", USER_10,
2371                     SecurityException.class);
2372             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s3", USER_10,
2373                     SecurityException.class);
2374             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s4", USER_10,
2375                     SecurityException.class);
2376             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s5", USER_10,
2377                     SecurityException.class);
2378             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s6", USER_10,
2379                     SecurityException.class);
2380         });
2381         runWithCaller(LAUNCHER_2, USER_P0, () -> {
2382             assertShortcutIds(assertAllPinned(
2383                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
2384                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), HANDLE_USER_0)),
2385                     "s3");
2386             assertShortcutIds(assertAllDynamic(
2387                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
2388                     /* activity =*/ null, ShortcutQuery.FLAG_GET_DYNAMIC), HANDLE_USER_0)),
2389                     "s1", "s2", "s3");
2390             assertShortcutIds(assertAllDynamicOrPinned(
2391                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
2392                     /* activity =*/ null, PIN_AND_DYNAMIC), HANDLE_USER_0)),
2393                     "s1", "s2", "s3");
2394 
2395             assertShortcutIds(assertAllPinned(
2396                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
2397                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), HANDLE_USER_0)),
2398                     "s3");
2399             assertShortcutIds(assertAllDynamic(
2400                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
2401                     /* activity =*/ null, ShortcutQuery.FLAG_GET_DYNAMIC), HANDLE_USER_0)),
2402                     "s1", "s2", "s3");
2403             assertShortcutIds(assertAllDynamicOrPinned(
2404                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
2405                     /* activity =*/ null, PIN_AND_DYNAMIC), HANDLE_USER_0)),
2406                     "s1", "s2", "s3");
2407 
2408             assertShortcutLaunchable(CALLING_PACKAGE_1, "s1", USER_0);
2409             assertShortcutLaunchable(CALLING_PACKAGE_1, "s2", USER_0);
2410             assertShortcutLaunchable(CALLING_PACKAGE_1, "s3", USER_0);
2411 
2412             assertShortcutLaunchable(CALLING_PACKAGE_2, "s1", USER_0);
2413             assertShortcutLaunchable(CALLING_PACKAGE_2, "s2", USER_0);
2414             assertShortcutLaunchable(CALLING_PACKAGE_2, "s3", USER_0);
2415 
2416             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s1", USER_10,
2417                     SecurityException.class);
2418             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s2", USER_10,
2419                     SecurityException.class);
2420             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s3", USER_10,
2421                     SecurityException.class);
2422             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s4", USER_10,
2423                     SecurityException.class);
2424             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s5", USER_10,
2425                     SecurityException.class);
2426             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s6", USER_10,
2427                     SecurityException.class);
2428         });
2429         runWithCaller(LAUNCHER_2, USER_10, () -> {
2430             assertShortcutIds(assertAllPinned(
2431                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
2432                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), HANDLE_USER_10)),
2433                     "s1", "s2", "s3");
2434             assertShortcutIds(assertAllDynamic(
2435                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
2436                     /* activity =*/ null, ShortcutQuery.FLAG_GET_DYNAMIC), HANDLE_USER_10)),
2437                     "s1", "s2", "s3", "s4", "s5", "s6");
2438             assertShortcutIds(assertAllDynamicOrPinned(
2439                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
2440                     /* activity =*/ null, PIN_AND_DYNAMIC), HANDLE_USER_10)),
2441                     "s1", "s2", "s3", "s4", "s5", "s6");
2442         });
2443 
2444         // Remove some dynamic shortcuts.
2445 
2446         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
2447             assertTrue(mManager.setDynamicShortcuts(list(
2448                     makeShortcut("s1"))));
2449         });
2450         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
2451             assertTrue(mManager.setDynamicShortcuts(list(
2452                     makeShortcut("s1"))));
2453         });
2454         runWithCaller(CALLING_PACKAGE_1, USER_10, () -> {
2455             assertTrue(mManager.setDynamicShortcuts(list(
2456                     makeShortcut("s1"))));
2457         });
2458 
2459         runWithCaller(LAUNCHER_1, USER_0, () -> {
2460             assertShortcutIds(assertAllPinned(
2461                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
2462                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), HANDLE_USER_0)),
2463                     "s1");
2464             assertShortcutIds(assertAllDynamic(
2465                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
2466                     /* activity =*/ null, ShortcutQuery.FLAG_GET_DYNAMIC), HANDLE_USER_0)),
2467                     "s1");
2468             assertShortcutIds(assertAllDynamicOrPinned(
2469                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
2470                     /* activity =*/ null, PIN_AND_DYNAMIC), HANDLE_USER_0)),
2471                     "s1");
2472 
2473             assertShortcutIds(assertAllPinned(
2474                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
2475                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), HANDLE_USER_0)),
2476                     "s1", "s2", "s3");
2477             assertShortcutIds(assertAllDynamic(
2478                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
2479                     /* activity =*/ null, ShortcutQuery.FLAG_GET_DYNAMIC), HANDLE_USER_0)),
2480                     "s1");
2481             assertShortcutIds(assertAllDynamicOrPinned(
2482                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
2483                     /* activity =*/ null, PIN_AND_DYNAMIC), HANDLE_USER_0)),
2484                     "s1", "s2", "s3");
2485 
2486             assertShortcutLaunchable(CALLING_PACKAGE_1, "s1", USER_0);
2487             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s2", USER_0,
2488                     ActivityNotFoundException.class);
2489             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s3", USER_0,
2490                     ActivityNotFoundException.class);
2491 
2492             assertShortcutLaunchable(CALLING_PACKAGE_2, "s1", USER_0);
2493             assertShortcutLaunchable(CALLING_PACKAGE_2, "s2", USER_0);
2494             assertShortcutLaunchable(CALLING_PACKAGE_2, "s3", USER_0);
2495 
2496             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s1", USER_10,
2497                     SecurityException.class);
2498             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s2", USER_10,
2499                     SecurityException.class);
2500             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s3", USER_10,
2501                     SecurityException.class);
2502             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s4", USER_10,
2503                     SecurityException.class);
2504             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s5", USER_10,
2505                     SecurityException.class);
2506             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s6", USER_10,
2507                     SecurityException.class);
2508         });
2509         runWithCaller(LAUNCHER_1, USER_P0, () -> {
2510             assertShortcutIds(assertAllPinned(
2511                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
2512                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), HANDLE_USER_0)),
2513                     "s2");
2514             assertShortcutIds(assertAllDynamic(
2515                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
2516                     /* activity =*/ null, ShortcutQuery.FLAG_GET_DYNAMIC), HANDLE_USER_0)),
2517                     "s1");
2518             assertShortcutIds(assertAllDynamicOrPinned(
2519                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
2520                     /* activity =*/ null, PIN_AND_DYNAMIC), HANDLE_USER_0)),
2521                     "s1", "s2");
2522 
2523             assertShortcutIds(assertAllPinned(
2524                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
2525                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), HANDLE_USER_0)),
2526                     "s2", "s3");
2527             assertShortcutIds(assertAllDynamic(
2528                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
2529                     /* activity =*/ null, ShortcutQuery.FLAG_GET_DYNAMIC), HANDLE_USER_0)),
2530                     "s1");
2531             assertShortcutIds(assertAllDynamicOrPinned(
2532                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
2533                     /* activity =*/ null, PIN_AND_DYNAMIC), HANDLE_USER_0)),
2534                     "s1", "s2", "s3");
2535 
2536             assertShortcutLaunchable(CALLING_PACKAGE_1, "s1", USER_0);
2537             assertShortcutLaunchable(CALLING_PACKAGE_1, "s2", USER_0);
2538             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s3", USER_0,
2539                     ActivityNotFoundException.class);
2540 
2541             assertShortcutLaunchable(CALLING_PACKAGE_2, "s1", USER_0);
2542             assertShortcutLaunchable(CALLING_PACKAGE_2, "s2", USER_0);
2543             assertShortcutLaunchable(CALLING_PACKAGE_2, "s3", USER_0);
2544 
2545             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s1", USER_10,
2546                     SecurityException.class);
2547             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s2", USER_10,
2548                     SecurityException.class);
2549             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s3", USER_10,
2550                     SecurityException.class);
2551             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s4", USER_10,
2552                     SecurityException.class);
2553             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s5", USER_10,
2554                     SecurityException.class);
2555             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s6", USER_10,
2556                     SecurityException.class);
2557         });
2558         runWithCaller(LAUNCHER_2, USER_P0, () -> {
2559             assertShortcutIds(assertAllPinned(
2560                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
2561                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), HANDLE_USER_0)),
2562                     "s3");
2563             assertShortcutIds(assertAllDynamic(
2564                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
2565                     /* activity =*/ null, ShortcutQuery.FLAG_GET_DYNAMIC), HANDLE_USER_0)),
2566                     "s1");
2567             assertShortcutIds(assertAllDynamicOrPinned(
2568                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
2569                     /* activity =*/ null, PIN_AND_DYNAMIC), HANDLE_USER_0)),
2570                     "s1", "s3");
2571 
2572             assertShortcutIds(assertAllPinned(
2573                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
2574                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), HANDLE_USER_0)),
2575                     "s3");
2576             assertShortcutIds(assertAllDynamic(
2577                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
2578                     /* activity =*/ null, ShortcutQuery.FLAG_GET_DYNAMIC), HANDLE_USER_0)),
2579                     "s1");
2580             assertShortcutIds(assertAllDynamicOrPinned(
2581                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
2582                     /* activity =*/ null, PIN_AND_DYNAMIC), HANDLE_USER_0)),
2583                     "s1", "s3");
2584 
2585             assertShortcutLaunchable(CALLING_PACKAGE_1, "s1", USER_0);
2586             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s2", USER_0,
2587                     ActivityNotFoundException.class);
2588             assertShortcutLaunchable(CALLING_PACKAGE_1, "s3", USER_0);
2589 
2590             assertShortcutLaunchable(CALLING_PACKAGE_2, "s1", USER_0);
2591             assertStartShortcutThrowsException(CALLING_PACKAGE_2, "s2", USER_0,
2592                     ActivityNotFoundException.class);
2593             assertShortcutLaunchable(CALLING_PACKAGE_2, "s3", USER_0);
2594 
2595             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s1", USER_10,
2596                     SecurityException.class);
2597             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s2", USER_10,
2598                     SecurityException.class);
2599             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s3", USER_10,
2600                     SecurityException.class);
2601             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s4", USER_10,
2602                     SecurityException.class);
2603             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s5", USER_10,
2604                     SecurityException.class);
2605             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s6", USER_10,
2606                     SecurityException.class);
2607         });
2608         runWithCaller(LAUNCHER_2, USER_10, () -> {
2609             assertShortcutIds(assertAllPinned(
2610                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
2611                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), HANDLE_USER_10)),
2612                     "s1", "s2", "s3");
2613             assertShortcutIds(assertAllDynamic(
2614                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
2615                     /* activity =*/ null, ShortcutQuery.FLAG_GET_DYNAMIC), HANDLE_USER_10)),
2616                     "s1");
2617             assertShortcutIds(assertAllDynamicOrPinned(
2618                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
2619                     /* activity =*/ null, PIN_AND_DYNAMIC), HANDLE_USER_10)),
2620                     "s1", "s2", "s3");
2621 
2622             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s1", USER_0,
2623                     SecurityException.class);
2624             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s2", USER_0,
2625                     SecurityException.class);
2626             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s3", USER_0,
2627                     SecurityException.class);
2628 
2629             assertStartShortcutThrowsException(CALLING_PACKAGE_2, "s1", USER_0,
2630                     SecurityException.class);
2631             assertStartShortcutThrowsException(CALLING_PACKAGE_2, "s2", USER_0,
2632                     SecurityException.class);
2633             assertStartShortcutThrowsException(CALLING_PACKAGE_2, "s3", USER_0,
2634                     SecurityException.class);
2635 
2636             assertShortcutLaunchable(CALLING_PACKAGE_1, "s1", USER_10);
2637             assertShortcutLaunchable(CALLING_PACKAGE_1, "s2", USER_10);
2638             assertShortcutLaunchable(CALLING_PACKAGE_1, "s3", USER_10);
2639             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s4", USER_10,
2640                     ActivityNotFoundException.class);
2641             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s5", USER_10,
2642                     ActivityNotFoundException.class);
2643             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s6", USER_10,
2644                     ActivityNotFoundException.class);
2645         });
2646 
2647         // Save & load and make sure we still have the same information.
2648         mService.saveDirtyInfo();
2649         initService();
2650         mService.handleUnlockUser(USER_0);
2651 
2652         runWithCaller(LAUNCHER_1, USER_0, () -> {
2653             assertShortcutIds(assertAllPinned(
2654                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
2655                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), HANDLE_USER_0)),
2656                     "s1");
2657             assertShortcutIds(assertAllDynamic(
2658                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
2659                     /* activity =*/ null, ShortcutQuery.FLAG_GET_DYNAMIC), HANDLE_USER_0)),
2660                     "s1");
2661             assertShortcutIds(assertAllDynamicOrPinned(
2662                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
2663                     /* activity =*/ null, PIN_AND_DYNAMIC), HANDLE_USER_0)),
2664                     "s1");
2665 
2666             assertShortcutIds(assertAllPinned(
2667                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
2668                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), HANDLE_USER_0)),
2669                     "s1", "s2", "s3");
2670             assertShortcutIds(assertAllDynamic(
2671                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
2672                     /* activity =*/ null, ShortcutQuery.FLAG_GET_DYNAMIC), HANDLE_USER_0)),
2673                     "s1");
2674             assertShortcutIds(assertAllDynamicOrPinned(
2675                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
2676                     /* activity =*/ null, PIN_AND_DYNAMIC), HANDLE_USER_0)),
2677                     "s1", "s2", "s3");
2678 
2679             assertShortcutLaunchable(CALLING_PACKAGE_1, "s1", USER_0);
2680             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s2", USER_0,
2681                     ActivityNotFoundException.class);
2682             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s3", USER_0,
2683                     ActivityNotFoundException.class);
2684 
2685             assertShortcutLaunchable(CALLING_PACKAGE_2, "s1", USER_0);
2686             assertShortcutLaunchable(CALLING_PACKAGE_2, "s2", USER_0);
2687             assertShortcutLaunchable(CALLING_PACKAGE_2, "s3", USER_0);
2688 
2689             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s1", USER_10,
2690                     SecurityException.class);
2691             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s2", USER_10,
2692                     SecurityException.class);
2693             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s3", USER_10,
2694                     SecurityException.class);
2695             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s4", USER_10,
2696                     SecurityException.class);
2697             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s5", USER_10,
2698                     SecurityException.class);
2699             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s6", USER_10,
2700                     SecurityException.class);
2701         });
2702         runWithCaller(LAUNCHER_1, USER_P0, () -> {
2703             assertShortcutIds(assertAllPinned(
2704                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
2705                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), HANDLE_USER_0)),
2706                     "s2");
2707             assertShortcutIds(assertAllDynamic(
2708                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
2709                     /* activity =*/ null, ShortcutQuery.FLAG_GET_DYNAMIC), HANDLE_USER_0)),
2710                     "s1");
2711             assertShortcutIds(assertAllDynamicOrPinned(
2712                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
2713                     /* activity =*/ null, PIN_AND_DYNAMIC), HANDLE_USER_0)),
2714                     "s1", "s2");
2715 
2716             assertShortcutIds(assertAllPinned(
2717                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
2718                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), HANDLE_USER_0)),
2719                     "s2", "s3");
2720             assertShortcutIds(assertAllDynamic(
2721                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
2722                     /* activity =*/ null, ShortcutQuery.FLAG_GET_DYNAMIC), HANDLE_USER_0)),
2723                     "s1");
2724             assertShortcutIds(assertAllDynamicOrPinned(
2725                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
2726                     /* activity =*/ null, PIN_AND_DYNAMIC), HANDLE_USER_0)),
2727                     "s1", "s2", "s3");
2728 
2729             assertShortcutLaunchable(CALLING_PACKAGE_1, "s1", USER_0);
2730             assertShortcutLaunchable(CALLING_PACKAGE_1, "s2", USER_0);
2731             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s3", USER_0,
2732                     ActivityNotFoundException.class);
2733 
2734             assertShortcutLaunchable(CALLING_PACKAGE_2, "s1", USER_0);
2735             assertShortcutLaunchable(CALLING_PACKAGE_2, "s2", USER_0);
2736             assertShortcutLaunchable(CALLING_PACKAGE_2, "s3", USER_0);
2737 
2738             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s1", USER_10,
2739                     SecurityException.class);
2740             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s2", USER_10,
2741                     SecurityException.class);
2742             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s3", USER_10,
2743                     SecurityException.class);
2744             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s4", USER_10,
2745                     SecurityException.class);
2746             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s5", USER_10,
2747                     SecurityException.class);
2748             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s6", USER_10,
2749                     SecurityException.class);
2750         });
2751         runWithCaller(LAUNCHER_2, USER_P0, () -> {
2752             assertShortcutIds(assertAllPinned(
2753                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
2754                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), HANDLE_USER_0)),
2755                     "s3");
2756             assertShortcutIds(assertAllDynamic(
2757                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
2758                     /* activity =*/ null, ShortcutQuery.FLAG_GET_DYNAMIC), HANDLE_USER_0)),
2759                     "s1");
2760             assertShortcutIds(assertAllDynamicOrPinned(
2761                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_1,
2762                     /* activity =*/ null, PIN_AND_DYNAMIC), HANDLE_USER_0)),
2763                     "s1", "s3");
2764 
2765             assertShortcutIds(assertAllPinned(
2766                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
2767                     /* activity =*/ null, ShortcutQuery.FLAG_GET_PINNED), HANDLE_USER_0)),
2768                     "s3");
2769             assertShortcutIds(assertAllDynamic(
2770                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
2771                     /* activity =*/ null, ShortcutQuery.FLAG_GET_DYNAMIC), HANDLE_USER_0)),
2772                     "s1");
2773             assertShortcutIds(assertAllDynamicOrPinned(
2774                     mLauncherApps.getShortcuts(buildQuery(/* time =*/ 0, CALLING_PACKAGE_2,
2775                     /* activity =*/ null, PIN_AND_DYNAMIC), HANDLE_USER_0)),
2776                     "s1", "s3");
2777 
2778             assertShortcutLaunchable(CALLING_PACKAGE_1, "s1", USER_0);
2779             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s2", USER_0,
2780                     ActivityNotFoundException.class);
2781             assertShortcutLaunchable(CALLING_PACKAGE_1, "s3", USER_0);
2782 
2783             assertShortcutLaunchable(CALLING_PACKAGE_2, "s1", USER_0);
2784             assertStartShortcutThrowsException(CALLING_PACKAGE_2, "s2", USER_0,
2785                     ActivityNotFoundException.class);
2786             assertShortcutLaunchable(CALLING_PACKAGE_2, "s3", USER_0);
2787 
2788             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s1", USER_10,
2789                     SecurityException.class);
2790             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s2", USER_10,
2791                     SecurityException.class);
2792             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s3", USER_10,
2793                     SecurityException.class);
2794             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s4", USER_10,
2795                     SecurityException.class);
2796             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s5", USER_10,
2797                     SecurityException.class);
2798             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s6", USER_10,
2799                     SecurityException.class);
2800         });
2801     }
2802 
testStartShortcut()2803     public void testStartShortcut() {
2804         // Create some shortcuts.
2805         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
2806             final ShortcutInfo s1_1 = makeShortcut(
2807                     "s1",
2808                     "Title 1",
2809                     makeComponent(ShortcutActivity.class),
2810                     /* icon =*/ null,
2811                     new Intent[]{makeIntent(Intent.ACTION_ASSIST, ShortcutActivity2.class,
2812                             "key1", "val1", "nest", makeBundle("key", 123))
2813                             .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK),
2814                             new Intent("act2").setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION)},
2815                     /* rank */ 10);
2816 
2817             final ShortcutInfo s1_2 = makeShortcut(
2818                     "s2",
2819                     "Title 2",
2820             /* activity */ null,
2821             /* icon =*/ null,
2822                     makeIntent(Intent.ACTION_ASSIST, ShortcutActivity3.class),
2823             /* rank */ 12);
2824 
2825             final ShortcutInfo s1_3 = makeShortcut("s3");
2826 
2827             assertTrue(mManager.setDynamicShortcuts(list(s1_1, s1_2, s1_3)));
2828         });
2829 
2830         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
2831             final ShortcutInfo s2_1 = makeShortcut(
2832                     "s1",
2833                     "ABC",
2834                     makeComponent(ShortcutActivity.class),
2835                     /* icon =*/ null,
2836                     makeIntent(Intent.ACTION_ANSWER, ShortcutActivity.class,
2837                             "key1", "val1", "nest", makeBundle("key", 123)),
2838                     /* weight */ 10);
2839             assertTrue(mManager.setDynamicShortcuts(list(s2_1)));
2840         });
2841 
2842         // Pin some.
2843         runWithCaller(LAUNCHER_1, USER_0, () -> {
2844             mLauncherApps.pinShortcuts(CALLING_PACKAGE_1,
2845                     list("s1", "s2"), getCallingUser());
2846 
2847             mLauncherApps.pinShortcuts(CALLING_PACKAGE_2,
2848                     list("s1"), getCallingUser());
2849         });
2850 
2851         // Just to make it complicated, delete some.
2852         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
2853             mManager.removeDynamicShortcuts(list("s2"));
2854         });
2855 
2856         runWithCaller(LAUNCHER_1, USER_0, () -> {
2857             final Intent[] intents = launchShortcutAndGetIntents(CALLING_PACKAGE_1, "s1", USER_0);
2858             assertEquals(ShortcutActivity2.class.getName(),
2859                     intents[0].getComponent().getClassName());
2860             assertEquals(Intent.ACTION_ASSIST,
2861                     intents[0].getAction());
2862             assertEquals(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK,
2863                     intents[0].getFlags());
2864 
2865             assertEquals("act2",
2866                     intents[1].getAction());
2867             assertEquals(Intent.FLAG_ACTIVITY_NO_ANIMATION,
2868                     intents[1].getFlags());
2869 
2870             assertEquals(
2871                     ShortcutActivity3.class.getName(),
2872                     launchShortcutAndGetIntent(CALLING_PACKAGE_1, "s2", USER_0)
2873                             .getComponent().getClassName());
2874             assertEquals(
2875                     ShortcutActivity.class.getName(),
2876                     launchShortcutAndGetIntent(CALLING_PACKAGE_2, "s1", USER_0)
2877                             .getComponent().getClassName());
2878 
2879             assertShortcutLaunchable(CALLING_PACKAGE_1, "s3", USER_0);
2880 
2881             assertShortcutNotLaunched("no-such-package", "s2", USER_0);
2882             assertShortcutNotLaunched(CALLING_PACKAGE_1, "xxxx", USER_0);
2883         });
2884 
2885         // LAUNCHER_1 is no longer the default launcher
2886         setDefaultLauncherChecker((pkg, userId) -> false);
2887 
2888         runWithCaller(LAUNCHER_1, USER_0, () -> {
2889             // Not the default launcher, but pinned shortcuts are still lauchable.
2890             final Intent[] intents = launchShortcutAndGetIntents(CALLING_PACKAGE_1, "s1", USER_0);
2891             assertEquals(ShortcutActivity2.class.getName(),
2892                     intents[0].getComponent().getClassName());
2893             assertEquals(Intent.ACTION_ASSIST,
2894                     intents[0].getAction());
2895             assertEquals(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK,
2896                     intents[0].getFlags());
2897 
2898             assertEquals("act2",
2899                     intents[1].getAction());
2900             assertEquals(Intent.FLAG_ACTIVITY_NO_ANIMATION,
2901                     intents[1].getFlags());
2902             assertEquals(
2903                     ShortcutActivity3.class.getName(),
2904                     launchShortcutAndGetIntent(CALLING_PACKAGE_1, "s2", USER_0)
2905                             .getComponent().getClassName());
2906             assertEquals(
2907                     ShortcutActivity.class.getName(),
2908                     launchShortcutAndGetIntent(CALLING_PACKAGE_2, "s1", USER_0)
2909                             .getComponent().getClassName());
2910 
2911             // Not pinned, so not lauchable.
2912         });
2913 
2914         // Test inner errors.
2915         runWithCaller(LAUNCHER_1, USER_0, () -> {
2916             // Not launchable.
2917             doReturn(ActivityManager.START_CLASS_NOT_FOUND)
2918                     .when(mMockActivityTaskManagerInternal).startActivitiesAsPackage(
2919                     anyStringOrNull(), anyInt(),
2920                     anyOrNull(Intent[].class), anyOrNull(Bundle.class));
2921             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s1", USER_0,
2922                     ActivityNotFoundException.class);
2923 
2924             // Still not launchable.
2925             doReturn(ActivityManager.START_CLASS_NOT_FOUND)
2926                     .when(mMockActivityTaskManagerInternal)
2927                     .startActivitiesAsPackage(
2928                             anyStringOrNull(), anyInt(),
2929                             anyOrNull(Intent[].class), anyOrNull(Bundle.class));
2930             assertStartShortcutThrowsException(CALLING_PACKAGE_1, "s1", USER_0,
2931                     ActivityNotFoundException.class);
2932         });
2933 
2934 
2935         // TODO Check extra, etc
2936     }
2937 
testLauncherCallback()2938     public void testLauncherCallback() throws Throwable {
2939         // Disable throttling for this test.
2940         mService.updateConfigurationLocked(
2941                 ConfigConstants.KEY_MAX_UPDATES_PER_INTERVAL + "=99999999,"
2942                         + ConfigConstants.KEY_MAX_SHORTCUTS + "=99999999"
2943         );
2944 
2945         setCaller(LAUNCHER_1, USER_0);
2946 
2947         assertForLauncherCallback(mLauncherApps, () -> {
2948             runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
2949                 assertTrue(mManager.setDynamicShortcuts(list(
2950                         makeShortcut("s1"), makeShortcut("s2"), makeShortcut("s3"))));
2951             });
2952         }).assertCallbackCalledForPackageAndUser(CALLING_PACKAGE_1, HANDLE_USER_0)
2953                 .haveIds("s1", "s2", "s3")
2954                 .areAllWithKeyFieldsOnly()
2955                 .areAllDynamic();
2956 
2957         // From different package.
2958         assertForLauncherCallback(mLauncherApps, () -> {
2959             runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
2960                 assertTrue(mManager.setDynamicShortcuts(list(
2961                         makeShortcut("s1"), makeShortcut("s2"), makeShortcut("s3"))));
2962             });
2963         }).assertCallbackCalledForPackageAndUser(CALLING_PACKAGE_2, HANDLE_USER_0)
2964                 .haveIds("s1", "s2", "s3")
2965                 .areAllWithKeyFieldsOnly()
2966                 .areAllDynamic();
2967 
2968         mRunningUsers.put(USER_10, true);
2969 
2970         // Different user, callback shouldn't be called.
2971         assertForLauncherCallback(mLauncherApps, () -> {
2972             runWithCaller(CALLING_PACKAGE_1, USER_10, () -> {
2973                 assertTrue(mManager.setDynamicShortcuts(list(
2974                         makeShortcut("s1"), makeShortcut("s2"), makeShortcut("s3"))));
2975             });
2976         }).assertNoCallbackCalled();
2977 
2978 
2979         // Test for addDynamicShortcuts.
2980         assertForLauncherCallback(mLauncherApps, () -> {
2981             runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
2982                 assertTrue(mManager.addDynamicShortcuts(list(makeShortcut("s4"))));
2983             });
2984         }).assertCallbackCalledForPackageAndUser(CALLING_PACKAGE_1, HANDLE_USER_0)
2985                 .haveIds("s1", "s2", "s3", "s4")
2986                 .areAllWithKeyFieldsOnly()
2987                 .areAllDynamic();
2988 
2989         // Test for remove
2990         assertForLauncherCallback(mLauncherApps, () -> {
2991             runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
2992                 mManager.removeDynamicShortcuts(list("s1"));
2993             });
2994         }).assertCallbackCalledForPackageAndUser(CALLING_PACKAGE_1, HANDLE_USER_0)
2995                 .haveIds("s2", "s3", "s4")
2996                 .areAllWithKeyFieldsOnly()
2997                 .areAllDynamic();
2998 
2999         // Test for update
3000         assertForLauncherCallback(mLauncherApps, () -> {
3001             runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
3002                 assertTrue(mManager.updateShortcuts(list(
3003                         makeShortcut("s1"), makeShortcut("s2"))));
3004             });
3005         }).assertCallbackCalledForPackageAndUser(CALLING_PACKAGE_1, HANDLE_USER_0)
3006                 // All remaining shortcuts will be passed regardless of what's been updated.
3007                 .haveIds("s2", "s3", "s4")
3008                 .areAllWithKeyFieldsOnly()
3009                 .areAllDynamic();
3010 
3011         // Test for deleteAll
3012         assertForLauncherCallback(mLauncherApps, () -> {
3013             runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
3014                 mManager.removeAllDynamicShortcuts();
3015             });
3016         }).assertCallbackCalledForPackageAndUser(CALLING_PACKAGE_1, HANDLE_USER_0)
3017                 .isEmpty();
3018 
3019         // Update package1 with manifest shortcuts
3020         assertForLauncherCallback(mLauncherApps, () -> {
3021             addManifestShortcutResource(
3022                     new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
3023                     R.xml.shortcut_2);
3024             updatePackageVersion(CALLING_PACKAGE_1, 1);
3025             mService.mPackageMonitor.onReceive(getTestContext(),
3026                     genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
3027         }).assertCallbackCalledForPackageAndUser(CALLING_PACKAGE_1, HANDLE_USER_0)
3028                 .areAllManifest()
3029                 .areAllWithKeyFieldsOnly()
3030                 .haveIds("ms1", "ms2");
3031 
3032         // Make sure pinned shortcuts are passed too.
3033         // 1. Add dynamic shortcuts.
3034         runWithCaller(CALLING_PACKAGE_1, UserHandle.USER_SYSTEM, () -> {
3035             assertTrue(mManager.setDynamicShortcuts(list(
3036                     makeShortcut("s1"), makeShortcut("s2"))));
3037         });
3038 
3039         // 2. Pin some.
3040         runWithCaller(LAUNCHER_1, UserHandle.USER_SYSTEM, () -> {
3041             mLauncherApps.pinShortcuts(CALLING_PACKAGE_1, list("ms2", "s2"), HANDLE_USER_0);
3042         });
3043         runWithCaller(CALLING_PACKAGE_1, UserHandle.USER_SYSTEM, () -> {
3044             assertWith(getCallerShortcuts())
3045                     .haveIds("ms1", "ms2", "s1", "s2")
3046                     .areAllEnabled()
3047 
3048                     .selectByIds("ms1", "ms2")
3049                     .areAllManifest()
3050 
3051                     .revertToOriginalList()
3052                     .selectByIds("s1", "s2")
3053                     .areAllDynamic()
3054             ;
3055         });
3056 
3057         // 3 Update the app with no manifest shortcuts.  (Pinned one will survive.)
3058         addManifestShortcutResource(
3059                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
3060                 R.xml.shortcut_0);
3061         updatePackageVersion(CALLING_PACKAGE_1, 1);
3062         mService.mPackageMonitor.onReceive(getTestContext(),
3063                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
3064 
3065         assertForLauncherCallback(mLauncherApps, () -> {
3066             runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
3067                 mManager.removeDynamicShortcuts(list("s2"));
3068 
3069                 assertWith(getCallerShortcuts())
3070                         .haveIds("ms2", "s1", "s2")
3071 
3072                         .selectByIds("ms2")
3073                         .areAllNotManifest()
3074                         .areAllPinned()
3075                         .areAllImmutable()
3076                         .areAllDisabled()
3077 
3078                         .revertToOriginalList()
3079                         .selectByIds("s1")
3080                         .areAllDynamic()
3081                         .areAllNotPinned()
3082                         .areAllEnabled()
3083 
3084                         .revertToOriginalList()
3085                         .selectByIds("s2")
3086                         .areAllNotDynamic()
3087                         .areAllPinned()
3088                         .areAllEnabled()
3089                 ;
3090             });
3091         }).assertCallbackCalledForPackageAndUser(CALLING_PACKAGE_1, HANDLE_USER_0)
3092                 .haveIds("ms2", "s1", "s2")
3093                 .areAllWithKeyFieldsOnly();
3094 
3095         // Remove CALLING_PACKAGE_2
3096         assertForLauncherCallback(mLauncherApps, () -> {
3097             uninstallPackage(USER_0, CALLING_PACKAGE_2);
3098             mService.cleanUpPackageLocked(CALLING_PACKAGE_2, USER_0, USER_0,
3099                     /* appStillExists = */ false);
3100         }).assertCallbackCalledForPackageAndUser(CALLING_PACKAGE_2, HANDLE_USER_0)
3101                 .isEmpty();
3102     }
3103 
testLauncherCallback_crossProfile()3104     public void testLauncherCallback_crossProfile() throws Throwable {
3105         prepareCrossProfileDataSet();
3106 
3107         final Handler h = new Handler(Looper.getMainLooper());
3108 
3109         final LauncherApps.Callback c0_1 = mock(LauncherApps.Callback.class);
3110         final LauncherApps.Callback c0_2 = mock(LauncherApps.Callback.class);
3111         final LauncherApps.Callback c0_3 = mock(LauncherApps.Callback.class);
3112         final LauncherApps.Callback c0_4 = mock(LauncherApps.Callback.class);
3113 
3114         final LauncherApps.Callback cP0_1 = mock(LauncherApps.Callback.class);
3115         final LauncherApps.Callback cP1_1 = mock(LauncherApps.Callback.class);
3116         final LauncherApps.Callback c10_1 = mock(LauncherApps.Callback.class);
3117         final LauncherApps.Callback c10_2 = mock(LauncherApps.Callback.class);
3118         final LauncherApps.Callback c11_1 = mock(LauncherApps.Callback.class);
3119 
3120         final List<LauncherApps.Callback> all =
3121                 list(c0_1, c0_2, c0_3, c0_4, cP0_1, c10_1, c11_1);
3122 
3123         setDefaultLauncherChecker((pkg, userId) -> {
3124             switch (userId) {
3125                 case USER_0:
3126                     return LAUNCHER_2.equals(pkg);
3127                 case USER_P0:
3128                     return LAUNCHER_1.equals(pkg);
3129                 case USER_P1:
3130                     return LAUNCHER_1.equals(pkg);
3131                 case USER_10:
3132                     return LAUNCHER_1.equals(pkg);
3133                 case USER_11:
3134                     return LAUNCHER_1.equals(pkg);
3135                 default:
3136                     return false;
3137             }
3138         });
3139 
3140         runWithCaller(LAUNCHER_1, USER_0, () -> mLauncherApps.registerCallback(c0_1, h));
3141         runWithCaller(LAUNCHER_2, USER_0, () -> mLauncherApps.registerCallback(c0_2, h));
3142         runWithCaller(LAUNCHER_3, USER_0, () -> mLauncherApps.registerCallback(c0_3, h));
3143         runWithCaller(LAUNCHER_4, USER_0, () -> mLauncherApps.registerCallback(c0_4, h));
3144         runWithCaller(LAUNCHER_1, USER_P0, () -> mLauncherApps.registerCallback(cP0_1, h));
3145         runWithCaller(LAUNCHER_1, USER_P1, () -> mLauncherApps.registerCallback(cP1_1, h));
3146         runWithCaller(LAUNCHER_1, USER_10, () -> mLauncherApps.registerCallback(c10_1, h));
3147         runWithCaller(LAUNCHER_2, USER_10, () -> mLauncherApps.registerCallback(c10_2, h));
3148         runWithCaller(LAUNCHER_1, USER_11, () -> mLauncherApps.registerCallback(c11_1, h));
3149 
3150         // User 0.
3151 
3152         resetAll(all);
3153         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
3154             mManager.removeDynamicShortcuts(list());
3155         });
3156         waitOnMainThread();
3157 
3158         assertCallbackNotReceived(c0_1);
3159         assertCallbackNotReceived(c0_3);
3160         assertCallbackNotReceived(c0_4);
3161         assertCallbackNotReceived(c10_1);
3162         assertCallbackNotReceived(c10_2);
3163         assertCallbackNotReceived(c11_1);
3164         assertCallbackReceived(c0_2, HANDLE_USER_0, CALLING_PACKAGE_1, "s1", "s2", "s3");
3165         assertCallbackReceived(cP0_1, HANDLE_USER_0, CALLING_PACKAGE_1, "s1", "s2", "s3", "s4");
3166         assertCallbackNotReceived(cP1_1);
3167 
3168         // User 0, different package.
3169 
3170         resetAll(all);
3171         runWithCaller(CALLING_PACKAGE_3, USER_0, () -> {
3172             mManager.removeDynamicShortcuts(list());
3173         });
3174         waitOnMainThread();
3175 
3176         assertCallbackNotReceived(c0_1);
3177         assertCallbackNotReceived(c0_3);
3178         assertCallbackNotReceived(c0_4);
3179         assertCallbackNotReceived(c10_1);
3180         assertCallbackNotReceived(c10_2);
3181         assertCallbackNotReceived(c11_1);
3182         assertCallbackReceived(c0_2, HANDLE_USER_0, CALLING_PACKAGE_3, "s1", "s2", "s3", "s4");
3183         assertCallbackReceived(cP0_1, HANDLE_USER_0, CALLING_PACKAGE_3,
3184                 "s1", "s2", "s3", "s4", "s5", "s6");
3185         assertCallbackNotReceived(cP1_1);
3186 
3187         // Work profile.
3188         resetAll(all);
3189         runWithCaller(CALLING_PACKAGE_1, USER_P0, () -> {
3190             mManager.removeDynamicShortcuts(list());
3191         });
3192         waitOnMainThread();
3193 
3194         assertCallbackNotReceived(c0_1);
3195         assertCallbackNotReceived(c0_3);
3196         assertCallbackNotReceived(c0_4);
3197         assertCallbackNotReceived(c10_1);
3198         assertCallbackNotReceived(c10_2);
3199         assertCallbackNotReceived(c11_1);
3200         assertCallbackReceived(c0_2, HANDLE_USER_P0, CALLING_PACKAGE_1, "s1", "s2", "s3", "s5");
3201         assertCallbackReceived(cP0_1, HANDLE_USER_P0, CALLING_PACKAGE_1, "s1", "s2", "s3", "s4");
3202         assertCallbackNotReceived(cP1_1);
3203 
3204         // Normal secondary user.
3205         mRunningUsers.put(USER_10, true);
3206 
3207         resetAll(all);
3208         runWithCaller(CALLING_PACKAGE_1, USER_10, () -> {
3209             mManager.removeDynamicShortcuts(list());
3210         });
3211         waitOnMainThread();
3212 
3213         assertCallbackNotReceived(c0_1);
3214         assertCallbackNotReceived(c0_2);
3215         assertCallbackNotReceived(c0_3);
3216         assertCallbackNotReceived(c0_4);
3217         assertCallbackNotReceived(cP0_1);
3218         assertCallbackNotReceived(c10_2);
3219         assertCallbackNotReceived(c11_1);
3220         assertCallbackReceived(c10_1, HANDLE_USER_10, CALLING_PACKAGE_1,
3221                 "x1", "x2", "x3", "x4", "x5");
3222         assertCallbackNotReceived(cP1_1);
3223     }
3224 
3225     // === Test for persisting ===
3226 
testSaveAndLoadUser_empty()3227     public void testSaveAndLoadUser_empty() {
3228         assertTrue(mManager.setDynamicShortcuts(list()));
3229 
3230         Log.i(TAG, "Saved state");
3231         dumpsysOnLogcat();
3232         dumpUserFile(0);
3233 
3234         // Restore.
3235         mService.saveDirtyInfo();
3236         initService();
3237 
3238         assertEquals(0, mManager.getDynamicShortcuts().size());
3239     }
3240 
3241     /**
3242      * Try save and load, also stop/start the user.
3243      */
testSaveAndLoadUser()3244     public void testSaveAndLoadUser() {
3245         // First, create some shortcuts and save.
3246         runWithCaller(CALLING_PACKAGE_1, UserHandle.USER_SYSTEM, () -> {
3247             final Icon icon1 = Icon.createWithResource(getTestContext(), R.drawable.black_64x16);
3248             final Icon icon2 = Icon.createWithBitmap(BitmapFactory.decodeResource(
3249                     getTestContext().getResources(), R.drawable.icon2));
3250 
3251             final ShortcutInfo si1 = makeShortcut(
3252                     "s1",
3253                     "title1-1",
3254                     makeComponent(ShortcutActivity.class),
3255                     icon1,
3256                     makeIntent(Intent.ACTION_ASSIST, ShortcutActivity2.class,
3257                             "key1", "val1", "nest", makeBundle("key", 123)),
3258                         /* weight */ 10);
3259 
3260             final ShortcutInfo si2 = makeShortcut(
3261                     "s2",
3262                     "title1-2",
3263                         /* activity */ null,
3264                     icon2,
3265                     makeIntent(Intent.ACTION_ASSIST, ShortcutActivity3.class),
3266                         /* weight */ 12);
3267 
3268             assertTrue(mManager.setDynamicShortcuts(list(si1, si2)));
3269 
3270             assertEquals(START_TIME + INTERVAL, mManager.getRateLimitResetTime());
3271             assertEquals(2, mManager.getRemainingCallCount());
3272         });
3273         runWithCaller(CALLING_PACKAGE_2, UserHandle.USER_SYSTEM, () -> {
3274             final Icon icon1 = Icon.createWithResource(getTestContext(), R.drawable.black_16x64);
3275             final Icon icon2 = Icon.createWithBitmap(BitmapFactory.decodeResource(
3276                     getTestContext().getResources(), R.drawable.icon2));
3277 
3278             final ShortcutInfo si1 = makeShortcut(
3279                     "s1",
3280                     "title2-1",
3281                     makeComponent(ShortcutActivity.class),
3282                     icon1,
3283                     makeIntent(Intent.ACTION_ASSIST, ShortcutActivity2.class,
3284                             "key1", "val1", "nest", makeBundle("key", 123)),
3285                         /* weight */ 10);
3286 
3287             final ShortcutInfo si2 = makeShortcut(
3288                     "s2",
3289                     "title2-2",
3290                         /* activity */ null,
3291                     icon2,
3292                     makeIntent(Intent.ACTION_ASSIST, ShortcutActivity3.class),
3293                         /* weight */ 12);
3294 
3295             assertTrue(mManager.setDynamicShortcuts(list(si1, si2)));
3296 
3297             assertEquals(START_TIME + INTERVAL, mManager.getRateLimitResetTime());
3298             assertEquals(2, mManager.getRemainingCallCount());
3299         });
3300 
3301         mRunningUsers.put(USER_10, true);
3302 
3303         runWithCaller(CALLING_PACKAGE_1, USER_10, () -> {
3304             final Icon icon1 = Icon.createWithResource(getTestContext(), R.drawable.black_64x64);
3305             final Icon icon2 = Icon.createWithBitmap(BitmapFactory.decodeResource(
3306                     getTestContext().getResources(), R.drawable.icon2));
3307 
3308             final ShortcutInfo si1 = makeShortcut(
3309                     "s1",
3310                     "title10-1-1",
3311                     makeComponent(ShortcutActivity.class),
3312                     icon1,
3313                     makeIntent(Intent.ACTION_ASSIST, ShortcutActivity2.class,
3314                             "key1", "val1", "nest", makeBundle("key", 123)),
3315                         /* weight */ 10);
3316 
3317             final ShortcutInfo si2 = makeShortcut(
3318                     "s2",
3319                     "title10-1-2",
3320                         /* activity */ null,
3321                     icon2,
3322                     makeIntent(Intent.ACTION_ASSIST, ShortcutActivity3.class),
3323                         /* weight */ 12);
3324 
3325             assertTrue(mManager.setDynamicShortcuts(list(si1, si2)));
3326 
3327             assertEquals(START_TIME + INTERVAL, mManager.getRateLimitResetTime());
3328             assertEquals(2, mManager.getRemainingCallCount());
3329         });
3330 
3331         mService.getShortcutsForTest().get(UserHandle.USER_SYSTEM).setLauncher(
3332                 new ComponentName("pkg1", "class"));
3333 
3334         // Restore.
3335         mService.saveDirtyInfo();
3336         initService();
3337 
3338         // Before the load, the map should be empty.
3339         assertEquals(0, mService.getShortcutsForTest().size());
3340 
3341         // this will pre-load the per-user info.
3342         mService.handleUnlockUser(UserHandle.USER_SYSTEM);
3343 
3344         // Now it's loaded.
3345         assertEquals(1, mService.getShortcutsForTest().size());
3346 
3347         runWithCaller(CALLING_PACKAGE_1, UserHandle.USER_SYSTEM, () -> {
3348             assertShortcutIds(assertAllDynamic(assertAllHaveIntents(assertAllHaveIcon(
3349                     mManager.getDynamicShortcuts()))), "s1", "s2");
3350             assertEquals(2, mManager.getRemainingCallCount());
3351 
3352             assertEquals("title1-1", getCallerShortcut("s1").getTitle());
3353             assertEquals("title1-2", getCallerShortcut("s2").getTitle());
3354         });
3355         runWithCaller(CALLING_PACKAGE_2, UserHandle.USER_SYSTEM, () -> {
3356             assertShortcutIds(assertAllDynamic(assertAllHaveIntents(assertAllHaveIcon(
3357                     mManager.getDynamicShortcuts()))), "s1", "s2");
3358             assertEquals(2, mManager.getRemainingCallCount());
3359 
3360             assertEquals("title2-1", getCallerShortcut("s1").getTitle());
3361             assertEquals("title2-2", getCallerShortcut("s2").getTitle());
3362         });
3363 
3364         assertEquals("pkg1", mService.getShortcutsForTest().get(UserHandle.USER_SYSTEM)
3365                 .getLastKnownLauncher().getPackageName());
3366 
3367         // Start another user
3368         mService.handleUnlockUser(USER_10);
3369 
3370         // Now the size is 2.
3371         assertEquals(2, mService.getShortcutsForTest().size());
3372 
3373         runWithCaller(CALLING_PACKAGE_1, USER_10, () -> {
3374             assertShortcutIds(assertAllDynamic(assertAllHaveIntents(assertAllHaveIcon(
3375                     mManager.getDynamicShortcuts()))), "s1", "s2");
3376             assertEquals(2, mManager.getRemainingCallCount());
3377 
3378             assertEquals("title10-1-1", getCallerShortcut("s1").getTitle());
3379             assertEquals("title10-1-2", getCallerShortcut("s2").getTitle());
3380         });
3381         assertNull(mService.getShortcutsForTest().get(USER_10).getLastKnownLauncher());
3382 
3383         // Try stopping the user
3384         mService.handleStopUser(USER_10);
3385 
3386         // Now it's unloaded.
3387         assertEquals(1, mService.getShortcutsForTest().size());
3388 
3389         // TODO Check all other fields
3390     }
3391 
testCleanupPackage()3392     public void testCleanupPackage() {
3393         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
3394             assertTrue(mManager.setDynamicShortcuts(list(
3395                     makeShortcut("s0_1"))));
3396         });
3397         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
3398             assertTrue(mManager.setDynamicShortcuts(list(
3399                     makeShortcut("s0_2"))));
3400         });
3401         runWithCaller(LAUNCHER_1, USER_0, () -> {
3402             mLauncherApps.pinShortcuts(CALLING_PACKAGE_1, list("s0_1"),
3403                     HANDLE_USER_0);
3404             mLauncherApps.pinShortcuts(CALLING_PACKAGE_2, list("s0_2"),
3405                     HANDLE_USER_0);
3406         });
3407         runWithCaller(LAUNCHER_2, USER_0, () -> {
3408             mLauncherApps.pinShortcuts(CALLING_PACKAGE_1, list("s0_1"),
3409                     HANDLE_USER_0);
3410             mLauncherApps.pinShortcuts(CALLING_PACKAGE_2, list("s0_2"),
3411                     HANDLE_USER_0);
3412         });
3413 
3414         mRunningUsers.put(USER_10, true);
3415 
3416         runWithCaller(CALLING_PACKAGE_1, USER_10, () -> {
3417             assertTrue(mManager.setDynamicShortcuts(list(
3418                     makeShortcut("s10_1"))));
3419         });
3420         runWithCaller(CALLING_PACKAGE_2, USER_10, () -> {
3421             assertTrue(mManager.setDynamicShortcuts(list(
3422                     makeShortcut("s10_2"))));
3423         });
3424         runWithCaller(LAUNCHER_1, USER_10, () -> {
3425             mLauncherApps.pinShortcuts(CALLING_PACKAGE_1, list("s10_1"),
3426                     HANDLE_USER_10);
3427             mLauncherApps.pinShortcuts(CALLING_PACKAGE_2, list("s10_2"),
3428                     HANDLE_USER_10);
3429         });
3430         runWithCaller(LAUNCHER_2, USER_10, () -> {
3431             mLauncherApps.pinShortcuts(CALLING_PACKAGE_1, list("s10_1"),
3432                     HANDLE_USER_10);
3433             mLauncherApps.pinShortcuts(CALLING_PACKAGE_2, list("s10_2"),
3434                     HANDLE_USER_10);
3435         });
3436 
3437         // Remove all dynamic shortcuts; now all shortcuts are just pinned.
3438         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
3439             mManager.removeAllDynamicShortcuts();
3440         });
3441         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
3442             mManager.removeAllDynamicShortcuts();
3443         });
3444         runWithCaller(CALLING_PACKAGE_1, USER_10, () -> {
3445             mManager.removeAllDynamicShortcuts();
3446         });
3447         runWithCaller(CALLING_PACKAGE_2, USER_10, () -> {
3448             mManager.removeAllDynamicShortcuts();
3449         });
3450 
3451 
3452         final SparseArray<ShortcutUser> users = mService.getShortcutsForTest();
3453         assertEquals(2, users.size());
3454         assertEquals(USER_0, users.keyAt(0));
3455         assertEquals(USER_10, users.keyAt(1));
3456 
3457         final ShortcutUser user0 = users.get(USER_0);
3458         final ShortcutUser user10 = users.get(USER_10);
3459 
3460 
3461         // Check the registered packages.
3462         dumpsysOnLogcat();
3463         assertEquals(set(CALLING_PACKAGE_1, CALLING_PACKAGE_2),
3464                 hashSet(user0.getAllPackagesForTest().keySet()));
3465         assertEquals(set(CALLING_PACKAGE_1, CALLING_PACKAGE_2),
3466                 hashSet(user10.getAllPackagesForTest().keySet()));
3467         assertEquals(
3468                 set(PackageWithUser.of(USER_0, LAUNCHER_1),
3469                         PackageWithUser.of(USER_0, LAUNCHER_2)),
3470                 hashSet(user0.getAllLaunchersForTest().keySet()));
3471         assertEquals(
3472                 set(PackageWithUser.of(USER_10, LAUNCHER_1),
3473                         PackageWithUser.of(USER_10, LAUNCHER_2)),
3474                 hashSet(user10.getAllLaunchersForTest().keySet()));
3475         assertShortcutIds(getLauncherPinnedShortcuts(LAUNCHER_1, USER_0),
3476                 "s0_1", "s0_2");
3477         assertShortcutIds(getLauncherPinnedShortcuts(LAUNCHER_2, USER_0),
3478                 "s0_1", "s0_2");
3479         assertShortcutIds(getLauncherPinnedShortcuts(LAUNCHER_1, USER_10),
3480                 "s10_1", "s10_2");
3481         assertShortcutIds(getLauncherPinnedShortcuts(LAUNCHER_2, USER_10),
3482                 "s10_1", "s10_2");
3483         assertShortcutExists(CALLING_PACKAGE_1, "s0_1", USER_0);
3484         assertShortcutExists(CALLING_PACKAGE_2, "s0_2", USER_0);
3485         assertShortcutExists(CALLING_PACKAGE_1, "s10_1", USER_10);
3486         assertShortcutExists(CALLING_PACKAGE_2, "s10_2", USER_10);
3487 
3488         mService.saveDirtyInfo();
3489 
3490         // Nonexistent package.
3491         uninstallPackage(USER_0, "abc");
3492         mService.cleanUpPackageLocked("abc", USER_0, USER_0, /* appStillExists = */ false);
3493 
3494         // No changes.
3495         assertEquals(set(CALLING_PACKAGE_1, CALLING_PACKAGE_2),
3496                 hashSet(user0.getAllPackagesForTest().keySet()));
3497         assertEquals(set(CALLING_PACKAGE_1, CALLING_PACKAGE_2),
3498                 hashSet(user10.getAllPackagesForTest().keySet()));
3499         assertEquals(
3500                 set(PackageWithUser.of(USER_0, LAUNCHER_1),
3501                         PackageWithUser.of(USER_0, LAUNCHER_2)),
3502                 hashSet(user0.getAllLaunchersForTest().keySet()));
3503         assertEquals(
3504                 set(PackageWithUser.of(USER_10, LAUNCHER_1),
3505                         PackageWithUser.of(USER_10, LAUNCHER_2)),
3506                 hashSet(user10.getAllLaunchersForTest().keySet()));
3507         assertShortcutIds(getLauncherPinnedShortcuts(LAUNCHER_1, USER_0),
3508                 "s0_1", "s0_2");
3509         assertShortcutIds(getLauncherPinnedShortcuts(LAUNCHER_2, USER_0),
3510                 "s0_1", "s0_2");
3511         assertShortcutIds(getLauncherPinnedShortcuts(LAUNCHER_1, USER_10),
3512                 "s10_1", "s10_2");
3513         assertShortcutIds(getLauncherPinnedShortcuts(LAUNCHER_2, USER_10),
3514                 "s10_1", "s10_2");
3515         assertShortcutExists(CALLING_PACKAGE_1, "s0_1", USER_0);
3516         assertShortcutExists(CALLING_PACKAGE_2, "s0_2", USER_0);
3517         assertShortcutExists(CALLING_PACKAGE_1, "s10_1", USER_10);
3518         assertShortcutExists(CALLING_PACKAGE_2, "s10_2", USER_10);
3519 
3520         mService.saveDirtyInfo();
3521 
3522         // Remove a package.
3523         uninstallPackage(USER_0, CALLING_PACKAGE_1);
3524         mService.cleanUpPackageLocked(CALLING_PACKAGE_1, USER_0, USER_0,
3525                 /* appStillExists = */ false);
3526 
3527         assertEquals(set(CALLING_PACKAGE_2),
3528                 hashSet(user0.getAllPackagesForTest().keySet()));
3529         assertEquals(set(CALLING_PACKAGE_1, CALLING_PACKAGE_2),
3530                 hashSet(user10.getAllPackagesForTest().keySet()));
3531         assertEquals(
3532                 set(PackageWithUser.of(USER_0, LAUNCHER_1),
3533                         PackageWithUser.of(USER_0, LAUNCHER_2)),
3534                 hashSet(user0.getAllLaunchersForTest().keySet()));
3535         assertEquals(
3536                 set(PackageWithUser.of(USER_10, LAUNCHER_1),
3537                         PackageWithUser.of(USER_10, LAUNCHER_2)),
3538                 hashSet(user10.getAllLaunchersForTest().keySet()));
3539         assertShortcutIds(getLauncherPinnedShortcuts(LAUNCHER_1, USER_0),
3540                 "s0_2");
3541         assertShortcutIds(getLauncherPinnedShortcuts(LAUNCHER_2, USER_0),
3542                 "s0_2");
3543         assertShortcutIds(getLauncherPinnedShortcuts(LAUNCHER_1, USER_10),
3544                 "s10_1", "s10_2");
3545         assertShortcutIds(getLauncherPinnedShortcuts(LAUNCHER_2, USER_10),
3546                 "s10_1", "s10_2");
3547         assertShortcutNotExists(CALLING_PACKAGE_1, "s0_1", USER_0);
3548         assertShortcutExists(CALLING_PACKAGE_2, "s0_2", USER_0);
3549         assertShortcutExists(CALLING_PACKAGE_1, "s10_1", USER_10);
3550         assertShortcutExists(CALLING_PACKAGE_2, "s10_2", USER_10);
3551 
3552         mService.saveDirtyInfo();
3553 
3554         // Remove a launcher.
3555         uninstallPackage(USER_10, LAUNCHER_1);
3556         mService.cleanUpPackageLocked(LAUNCHER_1, USER_10, USER_10, /* appStillExists = */ false);
3557 
3558         assertEquals(set(CALLING_PACKAGE_2),
3559                 hashSet(user0.getAllPackagesForTest().keySet()));
3560         assertEquals(set(CALLING_PACKAGE_1, CALLING_PACKAGE_2),
3561                 hashSet(user10.getAllPackagesForTest().keySet()));
3562         assertEquals(
3563                 set(PackageWithUser.of(USER_0, LAUNCHER_1),
3564                         PackageWithUser.of(USER_0, LAUNCHER_2)),
3565                 hashSet(user0.getAllLaunchersForTest().keySet()));
3566         assertEquals(
3567                 set(PackageWithUser.of(USER_10, LAUNCHER_2)),
3568                 hashSet(user10.getAllLaunchersForTest().keySet()));
3569         assertShortcutIds(getLauncherPinnedShortcuts(LAUNCHER_1, USER_0),
3570                 "s0_2");
3571         assertShortcutIds(getLauncherPinnedShortcuts(LAUNCHER_2, USER_0),
3572                 "s0_2");
3573         assertShortcutIds(getLauncherPinnedShortcuts(LAUNCHER_2, USER_10),
3574                 "s10_1", "s10_2");
3575         assertShortcutNotExists(CALLING_PACKAGE_1, "s0_1", USER_0);
3576         assertShortcutExists(CALLING_PACKAGE_2, "s0_2", USER_0);
3577         assertShortcutExists(CALLING_PACKAGE_1, "s10_1", USER_10);
3578         assertShortcutExists(CALLING_PACKAGE_2, "s10_2", USER_10);
3579 
3580         mService.saveDirtyInfo();
3581 
3582         // Remove a package.
3583         uninstallPackage(USER_10, CALLING_PACKAGE_2);
3584         mService.cleanUpPackageLocked(CALLING_PACKAGE_2, USER_10, USER_10,
3585                 /* appStillExists = */ false);
3586 
3587         assertEquals(set(CALLING_PACKAGE_2),
3588                 hashSet(user0.getAllPackagesForTest().keySet()));
3589         assertEquals(set(CALLING_PACKAGE_1),
3590                 hashSet(user10.getAllPackagesForTest().keySet()));
3591         assertEquals(
3592                 set(PackageWithUser.of(USER_0, LAUNCHER_1),
3593                         PackageWithUser.of(USER_0, LAUNCHER_2)),
3594                 hashSet(user0.getAllLaunchersForTest().keySet()));
3595         assertEquals(
3596                 set(PackageWithUser.of(USER_10, LAUNCHER_2)),
3597                 hashSet(user10.getAllLaunchersForTest().keySet()));
3598         assertShortcutIds(getLauncherPinnedShortcuts(LAUNCHER_1, USER_0),
3599                 "s0_2");
3600         assertShortcutIds(getLauncherPinnedShortcuts(LAUNCHER_2, USER_0),
3601                 "s0_2");
3602         assertShortcutIds(getLauncherPinnedShortcuts(LAUNCHER_2, USER_10),
3603                 "s10_1");
3604         assertShortcutNotExists(CALLING_PACKAGE_1, "s0_1", USER_0);
3605         assertShortcutExists(CALLING_PACKAGE_2, "s0_2", USER_0);
3606         assertShortcutExists(CALLING_PACKAGE_1, "s10_1", USER_10);
3607         assertShortcutNotExists(CALLING_PACKAGE_2, "s10_2", USER_10);
3608 
3609         mService.saveDirtyInfo();
3610 
3611         // Remove the other launcher from user 10 too.
3612         uninstallPackage(USER_10, LAUNCHER_2);
3613         mService.cleanUpPackageLocked(LAUNCHER_2, USER_10, USER_10,
3614                 /* appStillExists = */ false);
3615 
3616         assertEquals(set(CALLING_PACKAGE_2),
3617                 hashSet(user0.getAllPackagesForTest().keySet()));
3618         assertEquals(set(CALLING_PACKAGE_1),
3619                 hashSet(user10.getAllPackagesForTest().keySet()));
3620         assertEquals(
3621                 set(PackageWithUser.of(USER_0, LAUNCHER_1),
3622                         PackageWithUser.of(USER_0, LAUNCHER_2)),
3623                 hashSet(user0.getAllLaunchersForTest().keySet()));
3624         assertEquals(
3625                 set(),
3626                 hashSet(user10.getAllLaunchersForTest().keySet()));
3627         assertShortcutIds(getLauncherPinnedShortcuts(LAUNCHER_1, USER_0),
3628                 "s0_2");
3629         assertShortcutIds(getLauncherPinnedShortcuts(LAUNCHER_2, USER_0),
3630                 "s0_2");
3631 
3632         // Note the pinned shortcuts on user-10 no longer referred, so they should both be removed.
3633         assertShortcutNotExists(CALLING_PACKAGE_1, "s0_1", USER_0);
3634         assertShortcutExists(CALLING_PACKAGE_2, "s0_2", USER_0);
3635         assertShortcutNotExists(CALLING_PACKAGE_1, "s10_1", USER_10);
3636         assertShortcutNotExists(CALLING_PACKAGE_2, "s10_2", USER_10);
3637 
3638         mService.saveDirtyInfo();
3639 
3640         // More remove.
3641         uninstallPackage(USER_10, CALLING_PACKAGE_1);
3642         mService.cleanUpPackageLocked(CALLING_PACKAGE_1, USER_10, USER_10,
3643                 /* appStillExists = */ false);
3644 
3645         assertEquals(set(CALLING_PACKAGE_2),
3646                 hashSet(user0.getAllPackagesForTest().keySet()));
3647         assertEquals(set(),
3648                 hashSet(user10.getAllPackagesForTest().keySet()));
3649         assertEquals(
3650                 set(PackageWithUser.of(USER_0, LAUNCHER_1),
3651                         PackageWithUser.of(USER_0, LAUNCHER_2)),
3652                 hashSet(user0.getAllLaunchersForTest().keySet()));
3653         assertEquals(set(),
3654                 hashSet(user10.getAllLaunchersForTest().keySet()));
3655         assertShortcutIds(getLauncherPinnedShortcuts(LAUNCHER_1, USER_0),
3656                 "s0_2");
3657         assertShortcutIds(getLauncherPinnedShortcuts(LAUNCHER_2, USER_0),
3658                 "s0_2");
3659 
3660         // Note the pinned shortcuts on user-10 no longer referred, so they should both be removed.
3661         assertShortcutNotExists(CALLING_PACKAGE_1, "s0_1", USER_0);
3662         assertShortcutExists(CALLING_PACKAGE_2, "s0_2", USER_0);
3663         assertShortcutNotExists(CALLING_PACKAGE_1, "s10_1", USER_10);
3664         assertShortcutNotExists(CALLING_PACKAGE_2, "s10_2", USER_10);
3665 
3666         mService.saveDirtyInfo();
3667     }
3668 
testCleanupPackage_republishManifests()3669     public void testCleanupPackage_republishManifests() {
3670         addManifestShortcutResource(
3671                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
3672                 R.xml.shortcut_2);
3673         updatePackageVersion(CALLING_PACKAGE_1, 1);
3674         mService.mPackageMonitor.onReceive(getTestContext(),
3675                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
3676 
3677         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
3678             assertTrue(mManager.setDynamicShortcuts(list(
3679                     makeShortcut("s1"), makeShortcut("s2"), makeShortcut("s3"))));
3680         });
3681         runWithCaller(LAUNCHER_1, USER_0, () -> {
3682             mLauncherApps.pinShortcuts(CALLING_PACKAGE_1,
3683                     list("s2", "s3", "ms1", "ms2"), HANDLE_USER_0);
3684         });
3685 
3686         // Remove ms2 from manifest.
3687         addManifestShortcutResource(
3688                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
3689                 R.xml.shortcut_1);
3690         updatePackageVersion(CALLING_PACKAGE_1, 1);
3691         mService.mPackageMonitor.onReceive(getTestContext(),
3692                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
3693 
3694         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
3695             assertTrue(mManager.setDynamicShortcuts(list(
3696                     makeShortcut("s1"), makeShortcut("s2"))));
3697 
3698             // Make sure the shortcuts are in the intended state.
3699             assertWith(getCallerShortcuts())
3700                     .haveIds("ms1", "ms2", "s1", "s2", "s3")
3701 
3702                     .selectByIds("ms1")
3703                     .areAllManifest()
3704                     .areAllPinned()
3705 
3706                     .revertToOriginalList()
3707                     .selectByIds("ms2")
3708                     .areAllNotManifest()
3709                     .areAllPinned()
3710 
3711                     .revertToOriginalList()
3712                     .selectByIds("s1")
3713                     .areAllDynamic()
3714                     .areAllNotPinned()
3715 
3716                     .revertToOriginalList()
3717                     .selectByIds("s2")
3718                     .areAllDynamic()
3719                     .areAllPinned()
3720 
3721                     .revertToOriginalList()
3722                     .selectByIds("s3")
3723                     .areAllNotDynamic()
3724                     .areAllPinned();
3725         });
3726 
3727         // Clean up + re-publish manifests.
3728         mService.cleanUpPackageLocked(CALLING_PACKAGE_1, USER_0, USER_0,
3729                 /* appStillExists = */ true);
3730         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
3731             assertWith(getCallerShortcuts())
3732                     .haveIds("ms1")
3733                     .areAllManifest();
3734         });
3735     }
3736 
testHandleGonePackage_crossProfile()3737     public void testHandleGonePackage_crossProfile() {
3738         // Create some shortcuts.
3739         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
3740             assertTrue(mManager.setDynamicShortcuts(list(
3741                     makeShortcut("s1"), makeShortcut("s2"), makeShortcut("s3"))));
3742         });
3743         runWithCaller(CALLING_PACKAGE_1, USER_P0, () -> {
3744             assertTrue(mManager.setDynamicShortcuts(list(
3745                     makeShortcut("s1"), makeShortcut("s2"), makeShortcut("s3"))));
3746         });
3747         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
3748             assertTrue(mManager.setDynamicShortcuts(list(
3749                     makeShortcut("s1"), makeShortcut("s2"), makeShortcut("s3"))));
3750         });
3751 
3752         mRunningUsers.put(USER_10, true);
3753 
3754         runWithCaller(CALLING_PACKAGE_1, USER_10, () -> {
3755             assertTrue(mManager.setDynamicShortcuts(list(
3756                     makeShortcut("s1"), makeShortcut("s2"), makeShortcut("s3"))));
3757         });
3758 
3759         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_1, "s1", USER_0));
3760         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_1, "s2", USER_0));
3761         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_1, "s3", USER_0));
3762 
3763         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_1, "s1", USER_P0));
3764         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_1, "s2", USER_P0));
3765         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_1, "s3", USER_P0));
3766 
3767         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_2, "s1", USER_0));
3768         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_2, "s2", USER_0));
3769         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_2, "s3", USER_0));
3770 
3771         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_1, "s1", USER_10));
3772         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_1, "s2", USER_10));
3773         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_1, "s3", USER_10));
3774 
3775         // Pin some.
3776 
3777         runWithCaller(LAUNCHER_1, USER_0, () -> {
3778             mLauncherApps.pinShortcuts(CALLING_PACKAGE_1,
3779                     list("s1"), HANDLE_USER_0);
3780 
3781             mLauncherApps.pinShortcuts(CALLING_PACKAGE_1,
3782                     list("s2"), UserHandle.of(USER_P0));
3783 
3784             mLauncherApps.pinShortcuts(CALLING_PACKAGE_2,
3785                     list("s3"), HANDLE_USER_0);
3786         });
3787 
3788         runWithCaller(LAUNCHER_1, USER_P0, () -> {
3789             mLauncherApps.pinShortcuts(CALLING_PACKAGE_1,
3790                     list("s2"), HANDLE_USER_0);
3791 
3792             mLauncherApps.pinShortcuts(CALLING_PACKAGE_1,
3793                     list("s3"), UserHandle.of(USER_P0));
3794 
3795             mLauncherApps.pinShortcuts(CALLING_PACKAGE_2,
3796                     list("s1"), HANDLE_USER_0);
3797         });
3798 
3799         runWithCaller(LAUNCHER_1, USER_10, () -> {
3800             mLauncherApps.pinShortcuts(CALLING_PACKAGE_1,
3801                     list("s3"), HANDLE_USER_10);
3802         });
3803 
3804         // Check the state.
3805 
3806         assertDynamicAndPinned(getPackageShortcut(CALLING_PACKAGE_1, "s1", USER_0));
3807         assertDynamicAndPinned(getPackageShortcut(CALLING_PACKAGE_1, "s2", USER_0));
3808         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_1, "s3", USER_0));
3809 
3810         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_1, "s1", USER_P0));
3811         assertDynamicAndPinned(getPackageShortcut(CALLING_PACKAGE_1, "s2", USER_P0));
3812         assertDynamicAndPinned(getPackageShortcut(CALLING_PACKAGE_1, "s3", USER_P0));
3813 
3814         assertDynamicAndPinned(getPackageShortcut(CALLING_PACKAGE_2, "s1", USER_0));
3815         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_2, "s2", USER_0));
3816         assertDynamicAndPinned(getPackageShortcut(CALLING_PACKAGE_2, "s3", USER_0));
3817 
3818         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_1, "s1", USER_10));
3819         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_1, "s2", USER_10));
3820         assertDynamicAndPinned(getPackageShortcut(CALLING_PACKAGE_1, "s3", USER_10));
3821 
3822         // Make sure all the information is persisted.
3823         mService.saveDirtyInfo();
3824         initService();
3825         mService.handleUnlockUser(USER_0);
3826         mService.handleUnlockUser(USER_P0);
3827         mService.handleUnlockUser(USER_10);
3828 
3829         assertDynamicAndPinned(getPackageShortcut(CALLING_PACKAGE_1, "s1", USER_0));
3830         assertDynamicAndPinned(getPackageShortcut(CALLING_PACKAGE_1, "s2", USER_0));
3831         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_1, "s3", USER_0));
3832 
3833         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_1, "s1", USER_P0));
3834         assertDynamicAndPinned(getPackageShortcut(CALLING_PACKAGE_1, "s2", USER_P0));
3835         assertDynamicAndPinned(getPackageShortcut(CALLING_PACKAGE_1, "s3", USER_P0));
3836 
3837         assertDynamicAndPinned(getPackageShortcut(CALLING_PACKAGE_2, "s1", USER_0));
3838         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_2, "s2", USER_0));
3839         assertDynamicAndPinned(getPackageShortcut(CALLING_PACKAGE_2, "s3", USER_0));
3840 
3841         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_1, "s1", USER_10));
3842         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_1, "s2", USER_10));
3843         assertDynamicAndPinned(getPackageShortcut(CALLING_PACKAGE_1, "s3", USER_10));
3844 
3845         // Start uninstalling.
3846         uninstallPackage(USER_10, LAUNCHER_1);
3847         mService.checkPackageChanges(USER_10);
3848 
3849         assertDynamicAndPinned(getPackageShortcut(CALLING_PACKAGE_1, "s1", USER_0));
3850         assertDynamicAndPinned(getPackageShortcut(CALLING_PACKAGE_1, "s2", USER_0));
3851         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_1, "s3", USER_0));
3852 
3853         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_1, "s1", USER_P0));
3854         assertDynamicAndPinned(getPackageShortcut(CALLING_PACKAGE_1, "s2", USER_P0));
3855         assertDynamicAndPinned(getPackageShortcut(CALLING_PACKAGE_1, "s3", USER_P0));
3856 
3857         assertDynamicAndPinned(getPackageShortcut(CALLING_PACKAGE_2, "s1", USER_0));
3858         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_2, "s2", USER_0));
3859         assertDynamicAndPinned(getPackageShortcut(CALLING_PACKAGE_2, "s3", USER_0));
3860 
3861         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_1, "s1", USER_10));
3862         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_1, "s2", USER_10));
3863         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_1, "s3", USER_10));
3864 
3865         // Uninstall.
3866         uninstallPackage(USER_10, CALLING_PACKAGE_1);
3867         mService.checkPackageChanges(USER_10);
3868 
3869         assertDynamicAndPinned(getPackageShortcut(CALLING_PACKAGE_1, "s1", USER_0));
3870         assertDynamicAndPinned(getPackageShortcut(CALLING_PACKAGE_1, "s2", USER_0));
3871         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_1, "s3", USER_0));
3872 
3873         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_1, "s1", USER_P0));
3874         assertDynamicAndPinned(getPackageShortcut(CALLING_PACKAGE_1, "s2", USER_P0));
3875         assertDynamicAndPinned(getPackageShortcut(CALLING_PACKAGE_1, "s3", USER_P0));
3876 
3877         assertDynamicAndPinned(getPackageShortcut(CALLING_PACKAGE_2, "s1", USER_0));
3878         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_2, "s2", USER_0));
3879         assertDynamicAndPinned(getPackageShortcut(CALLING_PACKAGE_2, "s3", USER_0));
3880 
3881         assertNull(getPackageShortcut(CALLING_PACKAGE_1, "s1", USER_10));
3882         assertNull(getPackageShortcut(CALLING_PACKAGE_1, "s2", USER_10));
3883         assertNull(getPackageShortcut(CALLING_PACKAGE_1, "s3", USER_10));
3884 
3885         uninstallPackage(USER_P0, LAUNCHER_1);
3886         mService.checkPackageChanges(USER_0);
3887 
3888         assertDynamicAndPinned(getPackageShortcut(CALLING_PACKAGE_1, "s1", USER_0));
3889         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_1, "s2", USER_0));
3890         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_1, "s3", USER_0));
3891 
3892         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_1, "s1", USER_P0));
3893         assertDynamicAndPinned(getPackageShortcut(CALLING_PACKAGE_1, "s2", USER_P0));
3894         assertDynamicAndPinned(getPackageShortcut(CALLING_PACKAGE_1, "s3", USER_P0));
3895 
3896         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_2, "s1", USER_0));
3897         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_2, "s2", USER_0));
3898         assertDynamicAndPinned(getPackageShortcut(CALLING_PACKAGE_2, "s3", USER_0));
3899 
3900         assertNull(getPackageShortcut(CALLING_PACKAGE_1, "s1", USER_10));
3901         assertNull(getPackageShortcut(CALLING_PACKAGE_1, "s2", USER_10));
3902         assertNull(getPackageShortcut(CALLING_PACKAGE_1, "s3", USER_10));
3903 
3904         mService.checkPackageChanges(USER_P0);
3905 
3906         assertDynamicAndPinned(getPackageShortcut(CALLING_PACKAGE_1, "s1", USER_0));
3907         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_1, "s2", USER_0));
3908         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_1, "s3", USER_0));
3909 
3910         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_1, "s1", USER_P0));
3911         assertDynamicAndPinned(getPackageShortcut(CALLING_PACKAGE_1, "s2", USER_P0));
3912         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_1, "s3", USER_P0));
3913 
3914         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_2, "s1", USER_0));
3915         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_2, "s2", USER_0));
3916         assertDynamicAndPinned(getPackageShortcut(CALLING_PACKAGE_2, "s3", USER_0));
3917 
3918         assertNull(getPackageShortcut(CALLING_PACKAGE_1, "s1", USER_10));
3919         assertNull(getPackageShortcut(CALLING_PACKAGE_1, "s2", USER_10));
3920         assertNull(getPackageShortcut(CALLING_PACKAGE_1, "s3", USER_10));
3921 
3922         uninstallPackage(USER_P0, CALLING_PACKAGE_1);
3923 
3924         mService.saveDirtyInfo();
3925         initService();
3926         mService.handleUnlockUser(USER_0);
3927         mService.handleUnlockUser(USER_P0);
3928         mService.handleUnlockUser(USER_10);
3929 
3930         assertDynamicAndPinned(getPackageShortcut(CALLING_PACKAGE_1, "s1", USER_0));
3931         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_1, "s2", USER_0));
3932         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_1, "s3", USER_0));
3933 
3934         assertNull(getPackageShortcut(CALLING_PACKAGE_1, "s1", USER_P0));
3935         assertNull(getPackageShortcut(CALLING_PACKAGE_1, "s2", USER_P0));
3936         assertNull(getPackageShortcut(CALLING_PACKAGE_1, "s3", USER_P0));
3937 
3938         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_2, "s1", USER_0));
3939         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_2, "s2", USER_0));
3940         assertDynamicAndPinned(getPackageShortcut(CALLING_PACKAGE_2, "s3", USER_0));
3941 
3942         assertNull(getPackageShortcut(CALLING_PACKAGE_1, "s1", USER_10));
3943         assertNull(getPackageShortcut(CALLING_PACKAGE_1, "s2", USER_10));
3944         assertNull(getPackageShortcut(CALLING_PACKAGE_1, "s3", USER_10));
3945 
3946         // Uninstall
3947         uninstallPackage(USER_0, LAUNCHER_1);
3948 
3949         mService.saveDirtyInfo();
3950         initService();
3951         mService.handleUnlockUser(USER_0);
3952         mService.handleUnlockUser(USER_P0);
3953         mService.handleUnlockUser(USER_10);
3954 
3955         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_1, "s1", USER_0));
3956         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_1, "s2", USER_0));
3957         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_1, "s3", USER_0));
3958 
3959         assertNull(getPackageShortcut(CALLING_PACKAGE_1, "s1", USER_P0));
3960         assertNull(getPackageShortcut(CALLING_PACKAGE_1, "s2", USER_P0));
3961         assertNull(getPackageShortcut(CALLING_PACKAGE_1, "s3", USER_P0));
3962 
3963         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_2, "s1", USER_0));
3964         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_2, "s2", USER_0));
3965         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_2, "s3", USER_0));
3966 
3967         assertNull(getPackageShortcut(CALLING_PACKAGE_1, "s1", USER_10));
3968         assertNull(getPackageShortcut(CALLING_PACKAGE_1, "s2", USER_10));
3969         assertNull(getPackageShortcut(CALLING_PACKAGE_1, "s3", USER_10));
3970 
3971         uninstallPackage(USER_0, CALLING_PACKAGE_2);
3972 
3973         mService.saveDirtyInfo();
3974         initService();
3975         mService.handleUnlockUser(USER_0);
3976         mService.handleUnlockUser(USER_P0);
3977         mService.handleUnlockUser(USER_10);
3978 
3979         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_1, "s1", USER_0));
3980         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_1, "s2", USER_0));
3981         assertDynamicOnly(getPackageShortcut(CALLING_PACKAGE_1, "s3", USER_0));
3982 
3983         assertNull(getPackageShortcut(CALLING_PACKAGE_1, "s1", USER_P0));
3984         assertNull(getPackageShortcut(CALLING_PACKAGE_1, "s2", USER_P0));
3985         assertNull(getPackageShortcut(CALLING_PACKAGE_1, "s3", USER_P0));
3986 
3987         assertNull(getPackageShortcut(CALLING_PACKAGE_2, "s1", USER_0));
3988         assertNull(getPackageShortcut(CALLING_PACKAGE_2, "s2", USER_0));
3989         assertNull(getPackageShortcut(CALLING_PACKAGE_2, "s3", USER_0));
3990 
3991         assertNull(getPackageShortcut(CALLING_PACKAGE_1, "s1", USER_10));
3992         assertNull(getPackageShortcut(CALLING_PACKAGE_1, "s2", USER_10));
3993         assertNull(getPackageShortcut(CALLING_PACKAGE_1, "s3", USER_10));
3994     }
3995 
checkCanRestoreTo(int expected, ShortcutPackageInfo spi, boolean anyVersionOk, int version, boolean nowBackupAllowed, String... signatures)3996     protected void checkCanRestoreTo(int expected, ShortcutPackageInfo spi,
3997             boolean anyVersionOk, int version, boolean nowBackupAllowed, String... signatures) {
3998         final PackageInfo pi = genPackage("dummy", /* uid */ 0, version, signatures);
3999         if (!nowBackupAllowed) {
4000             pi.applicationInfo.flags &= ~ApplicationInfo.FLAG_ALLOW_BACKUP;
4001         }
4002 
4003         doReturn(expected != DISABLED_REASON_SIGNATURE_MISMATCH).when(
4004                 mMockPackageManagerInternal).isDataRestoreSafe(any(byte[].class), anyString());
4005 
4006         assertEquals(expected, spi.canRestoreTo(mService, pi, anyVersionOk));
4007     }
4008 
testCanRestoreTo()4009     public void testCanRestoreTo() {
4010         addPackage(CALLING_PACKAGE_1, CALLING_UID_1, 10, "sig1");
4011         addPackage(CALLING_PACKAGE_2, CALLING_UID_2, 10, "sig1", "sig2");
4012         addPackage(CALLING_PACKAGE_3, CALLING_UID_3, 10, "sig1");
4013 
4014         updatePackageInfo(CALLING_PACKAGE_3,
4015                 pi -> pi.applicationInfo.flags &= ~ApplicationInfo.FLAG_ALLOW_BACKUP);
4016 
4017         final ShortcutPackageInfo spi1 = ShortcutPackageInfo.generateForInstalledPackageForTest(
4018                 mService, CALLING_PACKAGE_1, USER_0);
4019         final ShortcutPackageInfo spi2 = ShortcutPackageInfo.generateForInstalledPackageForTest(
4020                 mService, CALLING_PACKAGE_2, USER_0);
4021         final ShortcutPackageInfo spi3 = ShortcutPackageInfo.generateForInstalledPackageForTest(
4022                 mService, CALLING_PACKAGE_3, USER_0);
4023 
4024         checkCanRestoreTo(DISABLED_REASON_NOT_DISABLED, spi1, false, 10, true, "sig1");
4025         checkCanRestoreTo(DISABLED_REASON_NOT_DISABLED, spi1, false, 10, true, "x", "sig1");
4026         checkCanRestoreTo(DISABLED_REASON_NOT_DISABLED, spi1, false, 10, true, "sig1", "y");
4027         checkCanRestoreTo(DISABLED_REASON_NOT_DISABLED, spi1, false, 10, true, "x", "sig1", "y");
4028         checkCanRestoreTo(DISABLED_REASON_NOT_DISABLED, spi1, false, 11, true, "sig1");
4029 
4030         checkCanRestoreTo(DISABLED_REASON_SIGNATURE_MISMATCH, spi1, false, 10, true/* empty */);
4031         checkCanRestoreTo(DISABLED_REASON_SIGNATURE_MISMATCH, spi1, false, 10, true, "x");
4032         checkCanRestoreTo(DISABLED_REASON_SIGNATURE_MISMATCH, spi1, false, 10, true, "x", "y");
4033         checkCanRestoreTo(DISABLED_REASON_SIGNATURE_MISMATCH, spi1, false, 10, true, "x");
4034         checkCanRestoreTo(DISABLED_REASON_VERSION_LOWER, spi1, false, 9, true, "sig1");
4035 
4036         // Any version okay.
4037         checkCanRestoreTo(DISABLED_REASON_NOT_DISABLED, spi1, true, 9, true, "sig1");
4038         checkCanRestoreTo(DISABLED_REASON_NOT_DISABLED, spi1, true, 9, true, "sig1");
4039 
4040         checkCanRestoreTo(DISABLED_REASON_NOT_DISABLED, spi2, false, 10, true, "sig1", "sig2");
4041         checkCanRestoreTo(DISABLED_REASON_NOT_DISABLED, spi2, false, 10, true, "sig2", "sig1");
4042         checkCanRestoreTo(DISABLED_REASON_NOT_DISABLED, spi2, false, 10, true, "x", "sig1", "sig2");
4043         checkCanRestoreTo(DISABLED_REASON_NOT_DISABLED, spi2, false, 10, true, "x", "sig2", "sig1");
4044         checkCanRestoreTo(DISABLED_REASON_NOT_DISABLED, spi2, false, 10, true, "sig1", "sig2", "y");
4045         checkCanRestoreTo(DISABLED_REASON_NOT_DISABLED, spi2, false, 10, true, "sig2", "sig1", "y");
4046         checkCanRestoreTo(DISABLED_REASON_NOT_DISABLED, spi2, false, 10, true, "x", "sig1", "sig2", "y");
4047         checkCanRestoreTo(DISABLED_REASON_NOT_DISABLED, spi2, false, 10, true, "x", "sig2", "sig1", "y");
4048         checkCanRestoreTo(DISABLED_REASON_NOT_DISABLED, spi2, false, 11, true, "x", "sig2", "sig1", "y");
4049 
4050         checkCanRestoreTo(DISABLED_REASON_SIGNATURE_MISMATCH,
4051                 spi2, false, 10, true, "sig1", "sig2x");
4052         checkCanRestoreTo(DISABLED_REASON_SIGNATURE_MISMATCH,
4053                 spi2, false, 10, true, "sig2", "sig1x");
4054         checkCanRestoreTo(DISABLED_REASON_SIGNATURE_MISMATCH,
4055                 spi2, false, 10, true, "x", "sig1x", "sig2");
4056         checkCanRestoreTo(DISABLED_REASON_SIGNATURE_MISMATCH,
4057                 spi2, false, 10, true, "x", "sig2x", "sig1");
4058         checkCanRestoreTo(DISABLED_REASON_SIGNATURE_MISMATCH,
4059                 spi2, false, 10, true, "sig1", "sig2x", "y");
4060         checkCanRestoreTo(DISABLED_REASON_SIGNATURE_MISMATCH,
4061                 spi2, false, 10, true, "sig2", "sig1x", "y");
4062         checkCanRestoreTo(DISABLED_REASON_SIGNATURE_MISMATCH,
4063                 spi2, false, 10, true, "x", "sig1x", "sig2", "y");
4064         checkCanRestoreTo(DISABLED_REASON_SIGNATURE_MISMATCH,
4065                 spi2, false, 10, true, "x", "sig2x", "sig1", "y");
4066         checkCanRestoreTo(DISABLED_REASON_SIGNATURE_MISMATCH,
4067                 spi2, false, 11, true, "x", "sig2x", "sig1", "y");
4068 
4069         checkCanRestoreTo(DISABLED_REASON_BACKUP_NOT_SUPPORTED, spi1, true, 10, false, "sig1");
4070         checkCanRestoreTo(DISABLED_REASON_BACKUP_NOT_SUPPORTED, spi3, true, 10, true, "sig1");
4071     }
4072 
testHandlePackageDelete()4073     public void testHandlePackageDelete() {
4074         checkHandlePackageDeleteInner((userId, packageName) -> {
4075             uninstallPackage(userId, packageName);
4076             mService.mPackageMonitor.onReceive(getTestContext(),
4077                     genPackageDeleteIntent(packageName, userId));
4078         });
4079     }
4080 
testHandlePackageDisable()4081     public void testHandlePackageDisable() {
4082         checkHandlePackageDeleteInner((userId, packageName) -> {
4083             disablePackage(userId, packageName);
4084             mService.mPackageMonitor.onReceive(getTestContext(),
4085                     genPackageChangedIntent(packageName, userId));
4086         });
4087     }
4088 
checkHandlePackageDeleteInner(BiConsumer<Integer, String> remover)4089     private void checkHandlePackageDeleteInner(BiConsumer<Integer, String> remover) {
4090         final Icon bmp32x32 = Icon.createWithBitmap(BitmapFactory.decodeResource(
4091                 getTestContext().getResources(), R.drawable.black_32x32));
4092         setCaller(CALLING_PACKAGE_1, USER_0);
4093         assertTrue(mManager.addDynamicShortcuts(list(
4094                 makeShortcutWithIcon("s1", bmp32x32), makeShortcutWithIcon("s2", bmp32x32)
4095         )));
4096         // Also add a manifest shortcut, which should be removed too.
4097         addManifestShortcutResource(
4098                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
4099                 R.xml.shortcut_1);
4100         updatePackageVersion(CALLING_PACKAGE_1, 1);
4101         mService.mPackageMonitor.onReceive(getTestContext(),
4102                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
4103         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
4104             assertWith(getCallerShortcuts())
4105                     .haveIds("s1", "s2", "ms1")
4106 
4107                     .selectManifest()
4108                     .haveIds("ms1");
4109         });
4110 
4111         setCaller(CALLING_PACKAGE_2, USER_0);
4112         assertTrue(mManager.addDynamicShortcuts(list(makeShortcutWithIcon("s1", bmp32x32))));
4113 
4114         setCaller(CALLING_PACKAGE_3, USER_0);
4115         assertTrue(mManager.addDynamicShortcuts(list(makeShortcutWithIcon("s1", bmp32x32))));
4116 
4117         mRunningUsers.put(USER_10, true);
4118 
4119         setCaller(CALLING_PACKAGE_1, USER_10);
4120         assertTrue(mManager.addDynamicShortcuts(list(makeShortcutWithIcon("s1", bmp32x32))));
4121 
4122         setCaller(CALLING_PACKAGE_2, USER_10);
4123         assertTrue(mManager.addDynamicShortcuts(list(makeShortcutWithIcon("s1", bmp32x32))));
4124 
4125         setCaller(CALLING_PACKAGE_3, USER_10);
4126         assertTrue(mManager.addDynamicShortcuts(list(makeShortcutWithIcon("s1", bmp32x32))));
4127 
4128         assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_1, "s1", USER_0));
4129         assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_2, "s1", USER_0));
4130         assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_3, "s1", USER_0));
4131         assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_1, "s1", USER_10));
4132         assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_2, "s1", USER_10));
4133         assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_3, "s1", USER_10));
4134 
4135         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_1, USER_0));
4136         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_2, USER_0));
4137         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_3, USER_0));
4138         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_1, USER_10));
4139         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_2, USER_10));
4140         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_3, USER_10));
4141 
4142         remover.accept(USER_0, CALLING_PACKAGE_1);
4143 
4144         assertNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_1, "s1", USER_0));
4145         assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_2, "s1", USER_0));
4146         assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_3, "s1", USER_0));
4147         assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_1, "s1", USER_10));
4148         assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_2, "s1", USER_10));
4149         assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_3, "s1", USER_10));
4150 
4151         assertFalse(bitmapDirectoryExists(CALLING_PACKAGE_1, USER_0));
4152         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_2, USER_0));
4153         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_3, USER_0));
4154         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_1, USER_10));
4155         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_2, USER_10));
4156         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_3, USER_10));
4157 
4158         mRunningUsers.put(USER_10, true);
4159 
4160         remover.accept(USER_10, CALLING_PACKAGE_2);
4161 
4162         assertNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_1, "s1", USER_0));
4163         assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_2, "s1", USER_0));
4164         assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_3, "s1", USER_0));
4165         assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_1, "s1", USER_10));
4166         assertNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_2, "s1", USER_10));
4167         assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_3, "s1", USER_10));
4168 
4169         assertFalse(bitmapDirectoryExists(CALLING_PACKAGE_1, USER_0));
4170         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_2, USER_0));
4171         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_3, USER_0));
4172         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_1, USER_10));
4173         assertFalse(bitmapDirectoryExists(CALLING_PACKAGE_2, USER_10));
4174         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_3, USER_10));
4175 
4176         mInjectedPackages.remove(CALLING_PACKAGE_1);
4177         mInjectedPackages.remove(CALLING_PACKAGE_3);
4178 
4179         mService.checkPackageChanges(USER_0);
4180 
4181         assertNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_1, "s1", USER_0));
4182         assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_2, "s1", USER_0));
4183         assertNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_3, "s1", USER_0));  // ---------------
4184         assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_1, "s1", USER_10));
4185         assertNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_2, "s1", USER_10));
4186         assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_3, "s1", USER_10));
4187 
4188         assertFalse(bitmapDirectoryExists(CALLING_PACKAGE_1, USER_0));
4189         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_2, USER_0));
4190         assertFalse(bitmapDirectoryExists(CALLING_PACKAGE_3, USER_0));
4191         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_1, USER_10));
4192         assertFalse(bitmapDirectoryExists(CALLING_PACKAGE_2, USER_10));
4193         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_3, USER_10));
4194 
4195         mService.checkPackageChanges(USER_10);
4196 
4197         assertNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_1, "s1", USER_0));
4198         assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_2, "s1", USER_0));
4199         assertNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_3, "s1", USER_0));
4200         assertNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_1, "s1", USER_10));
4201         assertNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_2, "s1", USER_10));
4202         assertNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_3, "s1", USER_10));
4203 
4204         assertFalse(bitmapDirectoryExists(CALLING_PACKAGE_1, USER_0));
4205         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_2, USER_0));
4206         assertFalse(bitmapDirectoryExists(CALLING_PACKAGE_3, USER_0));
4207         assertFalse(bitmapDirectoryExists(CALLING_PACKAGE_1, USER_10));
4208         assertFalse(bitmapDirectoryExists(CALLING_PACKAGE_2, USER_10));
4209         assertFalse(bitmapDirectoryExists(CALLING_PACKAGE_3, USER_10));
4210     }
4211 
4212     /** Almost ame as testHandlePackageDelete, except it doesn't uninstall packages. */
testHandlePackageClearData()4213     public void testHandlePackageClearData() {
4214         final Icon bmp32x32 = Icon.createWithBitmap(BitmapFactory.decodeResource(
4215                 getTestContext().getResources(), R.drawable.black_32x32));
4216         setCaller(CALLING_PACKAGE_1, USER_0);
4217         assertTrue(mManager.addDynamicShortcuts(list(
4218                 makeShortcutWithIcon("s1", bmp32x32), makeShortcutWithIcon("s2", bmp32x32)
4219         )));
4220 
4221         setCaller(CALLING_PACKAGE_2, USER_0);
4222         assertTrue(mManager.addDynamicShortcuts(list(makeShortcutWithIcon("s1", bmp32x32))));
4223 
4224         setCaller(CALLING_PACKAGE_3, USER_0);
4225         assertTrue(mManager.addDynamicShortcuts(list(makeShortcutWithIcon("s1", bmp32x32))));
4226 
4227         mRunningUsers.put(USER_10, true);
4228 
4229         setCaller(CALLING_PACKAGE_1, USER_10);
4230         assertTrue(mManager.addDynamicShortcuts(list(makeShortcutWithIcon("s1", bmp32x32))));
4231 
4232         setCaller(CALLING_PACKAGE_2, USER_10);
4233         assertTrue(mManager.addDynamicShortcuts(list(makeShortcutWithIcon("s1", bmp32x32))));
4234 
4235         setCaller(CALLING_PACKAGE_3, USER_10);
4236         assertTrue(mManager.addDynamicShortcuts(list(makeShortcutWithIcon("s1", bmp32x32))));
4237 
4238         assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_1, "s1", USER_0));
4239         assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_2, "s1", USER_0));
4240         assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_3, "s1", USER_0));
4241         assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_1, "s1", USER_10));
4242         assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_2, "s1", USER_10));
4243         assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_3, "s1", USER_10));
4244 
4245         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_1, USER_0));
4246         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_2, USER_0));
4247         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_3, USER_0));
4248         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_1, USER_10));
4249         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_2, USER_10));
4250         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_3, USER_10));
4251 
4252         mService.mPackageMonitor.onReceive(getTestContext(),
4253                 genPackageDataClear(CALLING_PACKAGE_1, USER_0));
4254 
4255         assertNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_1, "s1", USER_0));
4256         assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_2, "s1", USER_0));
4257         assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_3, "s1", USER_0));
4258         assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_1, "s1", USER_10));
4259         assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_2, "s1", USER_10));
4260         assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_3, "s1", USER_10));
4261 
4262         assertFalse(bitmapDirectoryExists(CALLING_PACKAGE_1, USER_0));
4263         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_2, USER_0));
4264         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_3, USER_0));
4265         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_1, USER_10));
4266         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_2, USER_10));
4267         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_3, USER_10));
4268 
4269         mRunningUsers.put(USER_10, true);
4270 
4271         mService.mPackageMonitor.onReceive(getTestContext(),
4272                 genPackageDataClear(CALLING_PACKAGE_2, USER_10));
4273 
4274         assertNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_1, "s1", USER_0));
4275         assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_2, "s1", USER_0));
4276         assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_3, "s1", USER_0));
4277         assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_1, "s1", USER_10));
4278         assertNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_2, "s1", USER_10));
4279         assertNotNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_3, "s1", USER_10));
4280 
4281         assertFalse(bitmapDirectoryExists(CALLING_PACKAGE_1, USER_0));
4282         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_2, USER_0));
4283         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_3, USER_0));
4284         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_1, USER_10));
4285         assertFalse(bitmapDirectoryExists(CALLING_PACKAGE_2, USER_10));
4286         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_3, USER_10));
4287     }
4288 
testHandlePackageClearData_manifestRepublished()4289     public void testHandlePackageClearData_manifestRepublished() {
4290 
4291         mRunningUsers.put(USER_10, true);
4292 
4293         // Add two manifests and two dynamics.
4294         addManifestShortcutResource(
4295                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
4296                 R.xml.shortcut_2);
4297         updatePackageVersion(CALLING_PACKAGE_1, 1);
4298         mService.mPackageMonitor.onReceive(getTestContext(),
4299                 genPackageAddIntent(CALLING_PACKAGE_1, USER_10));
4300 
4301         runWithCaller(CALLING_PACKAGE_1, USER_10, () -> {
4302             assertTrue(mManager.addDynamicShortcuts(list(
4303                     makeShortcut("s1"), makeShortcut("s2"))));
4304         });
4305         runWithCaller(LAUNCHER_1, USER_10, () -> {
4306             mLauncherApps.pinShortcuts(CALLING_PACKAGE_1, list("ms2", "s2"), HANDLE_USER_10);
4307         });
4308 
4309         runWithCaller(CALLING_PACKAGE_1, USER_10, () -> {
4310             assertWith(getCallerShortcuts())
4311                     .haveIds("ms1", "ms2", "s1", "s2")
4312                     .areAllEnabled()
4313 
4314                     .selectPinned()
4315                     .haveIds("ms2", "s2");
4316         });
4317 
4318         // Clear data
4319         mService.mPackageMonitor.onReceive(getTestContext(),
4320                 genPackageDataClear(CALLING_PACKAGE_1, USER_10));
4321 
4322         // Only manifest shortcuts will remain, and are no longer pinned.
4323         runWithCaller(CALLING_PACKAGE_1, USER_10, () -> {
4324             assertWith(getCallerShortcuts())
4325                     .haveIds("ms1", "ms2")
4326                     .areAllEnabled()
4327                     .areAllNotPinned();
4328         });
4329     }
4330 
testHandlePackageUpdate()4331     public void testHandlePackageUpdate() throws Throwable {
4332         // Set up shortcuts and launchers.
4333 
4334         final Icon res32x32 = Icon.createWithResource(getTestContext(), R.drawable.black_32x32);
4335         final Icon bmp32x32 = Icon.createWithBitmap(BitmapFactory.decodeResource(
4336                 getTestContext().getResources(), R.drawable.black_32x32));
4337 
4338         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
4339             assertTrue(mManager.setDynamicShortcuts(list(
4340                     makeShortcut("s1"),
4341                     makeShortcutWithIcon("s2", res32x32),
4342                     makeShortcutWithIcon("s3", res32x32),
4343                     makeShortcutWithIcon("s4", bmp32x32))));
4344         });
4345         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
4346             assertTrue(mManager.setDynamicShortcuts(list(
4347                     makeShortcut("s1"),
4348                     makeShortcutWithIcon("s2", bmp32x32))));
4349         });
4350         runWithCaller(CALLING_PACKAGE_3, USER_0, () -> {
4351             assertTrue(mManager.setDynamicShortcuts(list(
4352                     makeShortcutWithIcon("s1", res32x32))));
4353         });
4354 
4355         mRunningUsers.put(USER_10, true);
4356 
4357         runWithCaller(CALLING_PACKAGE_1, USER_10, () -> {
4358             assertTrue(mManager.setDynamicShortcuts(list(
4359                     makeShortcutWithIcon("s1", res32x32),
4360                     makeShortcutWithIcon("s2", res32x32))));
4361         });
4362         runWithCaller(CALLING_PACKAGE_2, USER_10, () -> {
4363             assertTrue(mManager.setDynamicShortcuts(list(
4364                     makeShortcutWithIcon("s1", bmp32x32),
4365                     makeShortcutWithIcon("s2", bmp32x32))));
4366         });
4367 
4368         LauncherApps.Callback c0 = mock(LauncherApps.Callback.class);
4369         LauncherApps.Callback c10 = mock(LauncherApps.Callback.class);
4370 
4371         runWithCaller(LAUNCHER_1, USER_0, () -> {
4372             mLauncherApps.registerCallback(c0, new Handler(Looper.getMainLooper()));
4373         });
4374         runWithCaller(LAUNCHER_1, USER_10, () -> {
4375             mLauncherApps.registerCallback(c10, new Handler(Looper.getMainLooper()));
4376         });
4377 
4378         mInjectedCurrentTimeMillis = START_TIME + 100;
4379 
4380         ArgumentCaptor<List> shortcuts;
4381 
4382         // Update the version info for package 1.
4383         reset(c0);
4384         reset(c10);
4385         updatePackageVersion(CALLING_PACKAGE_1, 1);
4386 
4387         // Then send the broadcast, to only user-0.
4388         mService.mPackageMonitor.onReceive(getTestContext(),
4389                 genPackageUpdateIntent(CALLING_PACKAGE_1, USER_0));
4390 
4391         waitOnMainThread();
4392 
4393         // User-0 should get the notification.
4394         shortcuts = ArgumentCaptor.forClass(List.class);
4395         verify(c0).onShortcutsChanged(
4396                 eq(CALLING_PACKAGE_1),
4397                 shortcuts.capture(),
4398                 eq(HANDLE_USER_0));
4399 
4400         // User-10 shouldn't yet get the notification.
4401         verify(c10, times(0)).onShortcutsChanged(
4402                 eq(CALLING_PACKAGE_1),
4403                 any(List.class),
4404                 any(UserHandle.class));
4405         assertShortcutIds(shortcuts.getValue(), "s1", "s2", "s3", "s4");
4406         assertEquals(START_TIME,
4407                 findShortcut(shortcuts.getValue(), "s1").getLastChangedTimestamp());
4408         assertEquals(START_TIME + 100,
4409                 findShortcut(shortcuts.getValue(), "s2").getLastChangedTimestamp());
4410         assertEquals(START_TIME + 100,
4411                 findShortcut(shortcuts.getValue(), "s3").getLastChangedTimestamp());
4412         assertEquals(START_TIME,
4413                 findShortcut(shortcuts.getValue(), "s4").getLastChangedTimestamp());
4414 
4415         // Next, send an unlock event on user-10.  Now we scan packages on this user and send a
4416         // notification to the launcher.
4417         mInjectedCurrentTimeMillis = START_TIME + 200;
4418 
4419         mRunningUsers.put(USER_10, true);
4420         mUnlockedUsers.put(USER_10, true);
4421 
4422         reset(c0);
4423         reset(c10);
4424         setPackageLastUpdateTime(CALLING_PACKAGE_1, mInjectedCurrentTimeMillis);
4425         mService.handleUnlockUser(USER_10);
4426         mService.checkPackageChanges(USER_10);
4427 
4428         waitOnMainThread();
4429 
4430         shortcuts = ArgumentCaptor.forClass(List.class);
4431         verify(c0, times(0)).onShortcutsChanged(
4432                 eq(CALLING_PACKAGE_1),
4433                 any(List.class),
4434                 any(UserHandle.class));
4435 
4436         verify(c10).onShortcutsChanged(
4437                 eq(CALLING_PACKAGE_1),
4438                 shortcuts.capture(),
4439                 eq(HANDLE_USER_10));
4440 
4441         assertShortcutIds(shortcuts.getValue(), "s1", "s2");
4442         assertEquals(START_TIME + 200,
4443                 findShortcut(shortcuts.getValue(), "s1").getLastChangedTimestamp());
4444         assertEquals(START_TIME + 200,
4445                 findShortcut(shortcuts.getValue(), "s2").getLastChangedTimestamp());
4446 
4447 
4448         // Do the same thing for package 2, which doesn't have resource icons.
4449         mInjectedCurrentTimeMillis = START_TIME + 300;
4450 
4451         reset(c0);
4452         reset(c10);
4453         updatePackageVersion(CALLING_PACKAGE_2, 10);
4454 
4455         // Then send the broadcast, to only user-0.
4456         mService.mPackageMonitor.onReceive(getTestContext(),
4457                 genPackageUpdateIntent(CALLING_PACKAGE_2, USER_0));
4458 
4459         waitOnMainThread();
4460 
4461         verify(c0, times(0)).onShortcutsChanged(
4462                 eq(CALLING_PACKAGE_1),
4463                 any(List.class),
4464                 any(UserHandle.class));
4465 
4466         verify(c10, times(0)).onShortcutsChanged(
4467                 eq(CALLING_PACKAGE_1),
4468                 any(List.class),
4469                 any(UserHandle.class));
4470 
4471         // Do the same thing for package 3
4472         mInjectedCurrentTimeMillis = START_TIME + 400;
4473 
4474         reset(c0);
4475         reset(c10);
4476         updatePackageVersion(CALLING_PACKAGE_3, 100);
4477 
4478         // Then send the broadcast, to only user-0.
4479         mService.mPackageMonitor.onReceive(getTestContext(),
4480                 genPackageUpdateIntent(CALLING_PACKAGE_3, USER_0));
4481         mService.checkPackageChanges(USER_10);
4482 
4483         waitOnMainThread();
4484 
4485         shortcuts = ArgumentCaptor.forClass(List.class);
4486         verify(c0).onShortcutsChanged(
4487                 eq(CALLING_PACKAGE_3),
4488                 shortcuts.capture(),
4489                 eq(HANDLE_USER_0));
4490 
4491         // User 10 doesn't have package 3, so no callback.
4492         verify(c10, times(0)).onShortcutsChanged(
4493                 eq(CALLING_PACKAGE_3),
4494                 any(List.class),
4495                 any(UserHandle.class));
4496 
4497         assertShortcutIds(shortcuts.getValue(), "s1");
4498         assertEquals(START_TIME + 400,
4499                 findShortcut(shortcuts.getValue(), "s1").getLastChangedTimestamp());
4500     }
4501 
4502     /**
4503      * Test the case where an updated app has resource IDs changed.
4504      */
testHandlePackageUpdate_resIdChanged()4505     public void testHandlePackageUpdate_resIdChanged() throws Exception {
4506         final Icon icon1 = Icon.createWithResource(getTestContext(), /* res ID */ 1000);
4507         final Icon icon2 = Icon.createWithResource(getTestContext(), /* res ID */ 1001);
4508 
4509         // Set up shortcuts.
4510         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
4511             // Note resource strings are not officially supported (they're hidden), but
4512             // should work.
4513 
4514             final ShortcutInfo s1 = new ShortcutInfo.Builder(mClientContext)
4515                     .setId("s1")
4516                     .setActivity(makeComponent(ShortcutActivity.class))
4517                     .setIntent(new Intent(Intent.ACTION_VIEW))
4518                     .setIcon(icon1)
4519                     .setTitleResId(10000)
4520                     .setTextResId(10001)
4521                     .setDisabledMessageResId(10002)
4522                     .build();
4523 
4524             final ShortcutInfo s2 = new ShortcutInfo.Builder(mClientContext)
4525                     .setId("s2")
4526                     .setActivity(makeComponent(ShortcutActivity.class))
4527                     .setIntent(new Intent(Intent.ACTION_VIEW))
4528                     .setIcon(icon2)
4529                     .setTitleResId(20000)
4530                     .build();
4531 
4532             assertTrue(mManager.setDynamicShortcuts(list(s1, s2)));
4533         });
4534 
4535         // Verify.
4536         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
4537             final ShortcutInfo s1 = getCallerShortcut("s1");
4538             final ShortcutInfo s2 = getCallerShortcut("s2");
4539 
4540             assertEquals(1000, s1.getIconResourceId());
4541             assertEquals(10000, s1.getTitleResId());
4542             assertEquals(10001, s1.getTextResId());
4543             assertEquals(10002, s1.getDisabledMessageResourceId());
4544 
4545             assertEquals(1001, s2.getIconResourceId());
4546             assertEquals(20000, s2.getTitleResId());
4547             assertEquals(0, s2.getTextResId());
4548             assertEquals(0, s2.getDisabledMessageResourceId());
4549         });
4550 
4551         mService.saveDirtyInfo();
4552         initService();
4553 
4554         // Set up the mock resources again, with an "adjustment".
4555         // When the package is updated, the service will fetch the updated res-IDs with res-names,
4556         // and the new IDs will have this offset.
4557         setUpAppResources(10);
4558 
4559         // Update the package.
4560         updatePackageVersion(CALLING_PACKAGE_1, 1);
4561         mService.mPackageMonitor.onReceive(getTestContext(),
4562                 genPackageUpdateIntent(CALLING_PACKAGE_1, USER_0));
4563 
4564         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
4565             final ShortcutInfo s1 = getCallerShortcut("s1");
4566             final ShortcutInfo s2 = getCallerShortcut("s2");
4567 
4568             assertEquals(1010, s1.getIconResourceId());
4569             assertEquals(10010, s1.getTitleResId());
4570             assertEquals(10011, s1.getTextResId());
4571             assertEquals(10012, s1.getDisabledMessageResourceId());
4572 
4573             assertEquals(1011, s2.getIconResourceId());
4574             assertEquals(20010, s2.getTitleResId());
4575             assertEquals(0, s2.getTextResId());
4576             assertEquals(0, s2.getDisabledMessageResourceId());
4577         });
4578     }
4579 
testHandlePackageUpdate_systemAppUpdate()4580     public void testHandlePackageUpdate_systemAppUpdate() {
4581 
4582         // Package1 is a system app.  Package 2 is not a system app, so it's not scanned
4583         // in this test at all.
4584         mSystemPackages.add(CALLING_PACKAGE_1);
4585 
4586         // Initial state: no shortcuts.
4587         mService.checkPackageChanges(USER_0);
4588 
4589         assertEquals(mInjectedCurrentTimeMillis,
4590                 mService.getUserShortcutsLocked(USER_0).getLastAppScanTime());
4591         assertEquals(mInjectedBuildFingerprint,
4592                 mService.getUserShortcutsLocked(USER_0).getLastAppScanOsFingerprint());
4593 
4594         // They have no shortcuts.
4595         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
4596             assertWith(getCallerShortcuts())
4597                     .isEmpty();
4598         });
4599 
4600         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
4601             assertWith(getCallerShortcuts())
4602                     .isEmpty();
4603         });
4604 
4605         // Next.
4606         // Update the packages -- now they have 1 manifest shortcut.
4607         // But checkPackageChanges() don't notice it, since their version code / timestamp haven't
4608         // changed.
4609         addManifestShortcutResource(
4610                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
4611                 R.xml.shortcut_1);
4612         addManifestShortcutResource(
4613                 new ComponentName(CALLING_PACKAGE_2, ShortcutActivity.class.getName()),
4614                 R.xml.shortcut_1);
4615         mInjectedCurrentTimeMillis += 1000;
4616         mService.checkPackageChanges(USER_0);
4617 
4618         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
4619             assertWith(getCallerShortcuts())
4620                     .isEmpty();
4621         });
4622         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
4623             assertWith(getCallerShortcuts())
4624                     .isEmpty();
4625         });
4626 
4627         // Next.
4628         // Update the build finger print.  All apps will be scanned now.
4629         mInjectedBuildFingerprint = "update1";
4630         mInjectedCurrentTimeMillis += 1000;
4631         mService.checkPackageChanges(USER_0);
4632 
4633         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
4634             assertWith(getCallerShortcuts())
4635                     .haveIds("ms1");
4636         });
4637         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
4638             assertWith(getCallerShortcuts())
4639                     .haveIds("ms1");
4640         });
4641 
4642         // Next.
4643         // Update manifest shortcuts.
4644         addManifestShortcutResource(
4645                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
4646                 R.xml.shortcut_2);
4647         addManifestShortcutResource(
4648                 new ComponentName(CALLING_PACKAGE_2, ShortcutActivity.class.getName()),
4649                 R.xml.shortcut_2);
4650         mInjectedCurrentTimeMillis += 1000;
4651         mService.checkPackageChanges(USER_0);
4652 
4653         // Fingerprint hasn't changed, so there packages weren't scanned.
4654         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
4655             assertWith(getCallerShortcuts())
4656                     .haveIds("ms1");
4657         });
4658         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
4659             assertWith(getCallerShortcuts())
4660                     .haveIds("ms1");
4661         });
4662 
4663         // Update the fingerprint.  CALLING_PACKAGE_1's version code hasn't changed, but we scan
4664         // all apps anyway.
4665         mInjectedBuildFingerprint = "update2";
4666         mInjectedCurrentTimeMillis += 1000;
4667         mService.checkPackageChanges(USER_0);
4668 
4669         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
4670             assertWith(getCallerShortcuts())
4671                     .haveIds("ms1", "ms2");
4672         });
4673         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
4674             assertWith(getCallerShortcuts())
4675                     .haveIds("ms1", "ms2");
4676         });
4677 
4678         // Make sure getLastAppScanTime / getLastAppScanOsFingerprint are persisted.
4679         initService();
4680         assertEquals(mInjectedCurrentTimeMillis,
4681                 mService.getUserShortcutsLocked(USER_0).getLastAppScanTime());
4682         assertEquals(mInjectedBuildFingerprint,
4683                 mService.getUserShortcutsLocked(USER_0).getLastAppScanOsFingerprint());
4684     }
4685 
testHandlePackageChanged()4686     public void testHandlePackageChanged() {
4687         final ComponentName ACTIVITY1 = new ComponentName(CALLING_PACKAGE_1, "act1");
4688         final ComponentName ACTIVITY2 = new ComponentName(CALLING_PACKAGE_1, "act2");
4689 
4690         addManifestShortcutResource(ACTIVITY1, R.xml.shortcut_1);
4691         addManifestShortcutResource(ACTIVITY2, R.xml.shortcut_1_alt);
4692 
4693         mRunningUsers.put(USER_10, true);
4694 
4695         updatePackageVersion(CALLING_PACKAGE_1, 1);
4696         mService.mPackageMonitor.onReceive(getTestContext(),
4697                 genPackageAddIntent(CALLING_PACKAGE_1, USER_10));
4698 
4699         runWithCaller(CALLING_PACKAGE_1, USER_10, () -> {
4700             assertTrue(mManager.addDynamicShortcuts(list(
4701                     makeShortcutWithActivity("s1", ACTIVITY1),
4702                     makeShortcutWithActivity("s2", ACTIVITY2)
4703             )));
4704         });
4705         runWithCaller(LAUNCHER_1, USER_10, () -> {
4706             mLauncherApps.pinShortcuts(CALLING_PACKAGE_1, list("ms1-alt", "s2"), HANDLE_USER_10);
4707         });
4708 
4709         runWithCaller(CALLING_PACKAGE_1, USER_10, () -> {
4710             assertWith(getCallerShortcuts())
4711                     .haveIds("ms1", "ms1-alt", "s1", "s2")
4712                     .areAllEnabled()
4713 
4714                     .selectPinned()
4715                     .haveIds("ms1-alt", "s2")
4716 
4717                     .revertToOriginalList()
4718                     .selectByIds("ms1", "s1")
4719                     .areAllWithActivity(ACTIVITY1)
4720 
4721                     .revertToOriginalList()
4722                     .selectByIds("ms1-alt", "s2")
4723                     .areAllWithActivity(ACTIVITY2)
4724             ;
4725         });
4726 
4727         // First, no changes.
4728         mService.mPackageMonitor.onReceive(getTestContext(),
4729                 genPackageChangedIntent(CALLING_PACKAGE_1, USER_10));
4730 
4731         runWithCaller(CALLING_PACKAGE_1, USER_10, () -> {
4732             assertWith(getCallerShortcuts())
4733                     .haveIds("ms1", "ms1-alt", "s1", "s2")
4734                     .areAllEnabled()
4735 
4736                     .selectPinned()
4737                     .haveIds("ms1-alt", "s2")
4738 
4739                     .revertToOriginalList()
4740                     .selectByIds("ms1", "s1")
4741                     .areAllWithActivity(ACTIVITY1)
4742 
4743                     .revertToOriginalList()
4744                     .selectByIds("ms1-alt", "s2")
4745                     .areAllWithActivity(ACTIVITY2)
4746             ;
4747         });
4748 
4749         // Disable activity 1
4750         mEnabledActivityChecker = (activity, userId) -> !ACTIVITY1.equals(activity);
4751         mService.mPackageMonitor.onReceive(getTestContext(),
4752                 genPackageChangedIntent(CALLING_PACKAGE_1, USER_10));
4753 
4754         runWithCaller(CALLING_PACKAGE_1, USER_10, () -> {
4755             assertWith(getCallerShortcuts())
4756                     .haveIds("ms1-alt", "s2")
4757                     .areAllEnabled()
4758 
4759                     .selectPinned()
4760                     .haveIds("ms1-alt", "s2")
4761 
4762                     .revertToOriginalList()
4763                     .selectByIds("ms1-alt", "s2")
4764                     .areAllWithActivity(ACTIVITY2)
4765             ;
4766         });
4767 
4768         // Re-enable activity 1.
4769         // Manifest shortcuts will be re-published, but dynamic ones are not.
4770         mEnabledActivityChecker = (activity, userId) -> true;
4771         mService.mPackageMonitor.onReceive(getTestContext(),
4772                 genPackageChangedIntent(CALLING_PACKAGE_1, USER_10));
4773 
4774         runWithCaller(CALLING_PACKAGE_1, USER_10, () -> {
4775             assertWith(getCallerShortcuts())
4776                     .haveIds("ms1", "ms1-alt", "s2")
4777                     .areAllEnabled()
4778 
4779                     .selectPinned()
4780                     .haveIds("ms1-alt", "s2")
4781 
4782                     .revertToOriginalList()
4783                     .selectByIds("ms1")
4784                     .areAllWithActivity(ACTIVITY1)
4785 
4786                     .revertToOriginalList()
4787                     .selectByIds("ms1-alt", "s2")
4788                     .areAllWithActivity(ACTIVITY2)
4789             ;
4790         });
4791 
4792         // Disable activity 2
4793         // Because "ms1-alt" and "s2" are both pinned, they will remain, but disabled.
4794         mEnabledActivityChecker = (activity, userId) -> !ACTIVITY2.equals(activity);
4795         mService.mPackageMonitor.onReceive(getTestContext(),
4796                 genPackageChangedIntent(CALLING_PACKAGE_1, USER_10));
4797 
4798         runWithCaller(CALLING_PACKAGE_1, USER_10, () -> {
4799             assertWith(getCallerShortcuts())
4800                     .haveIds("ms1", "ms1-alt", "s2")
4801 
4802                     .selectDynamic().isEmpty().revertToOriginalList() // no dynamics.
4803 
4804                     .selectPinned()
4805                     .haveIds("ms1-alt", "s2")
4806                     .areAllDisabled()
4807 
4808                     .revertToOriginalList()
4809                     .selectByIds("ms1")
4810                     .areAllWithActivity(ACTIVITY1)
4811                     .areAllEnabled()
4812             ;
4813         });
4814     }
4815 
testHandlePackageUpdate_activityNoLongerMain()4816     public void testHandlePackageUpdate_activityNoLongerMain() throws Throwable {
4817         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
4818             assertTrue(mManager.setDynamicShortcuts(list(
4819                     makeShortcutWithActivity("s1a",
4820                             new ComponentName(getCallingPackage(), "act1")),
4821                     makeShortcutWithActivity("s1b",
4822                             new ComponentName(getCallingPackage(), "act1")),
4823                     makeShortcutWithActivity("s2a",
4824                             new ComponentName(getCallingPackage(), "act2")),
4825                     makeShortcutWithActivity("s2b",
4826                             new ComponentName(getCallingPackage(), "act2")),
4827                     makeShortcutWithActivity("s3a",
4828                             new ComponentName(getCallingPackage(), "act3")),
4829                     makeShortcutWithActivity("s3b",
4830                             new ComponentName(getCallingPackage(), "act3"))
4831             )));
4832             assertWith(getCallerShortcuts())
4833                     .haveIds("s1a", "s1b", "s2a", "s2b", "s3a", "s3b")
4834                     .areAllDynamic();
4835         });
4836         runWithCaller(LAUNCHER_1, USER_0, () -> {
4837             mLauncherApps.pinShortcuts(CALLING_PACKAGE_1,
4838                     list("s1b", "s2b", "s3b"),
4839                     HANDLE_USER_0);
4840         });
4841         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
4842             assertWith(getCallerShortcuts())
4843                     .haveIds("s1a", "s1b", "s2a", "s2b", "s3a", "s3b")
4844                     .areAllDynamic()
4845 
4846                     .selectByIds("s1b", "s2b", "s3b")
4847                     .areAllPinned();
4848         });
4849 
4850         // Update the app and act2 and act3 are no longer main.
4851         mMainActivityChecker = (activity, userId) -> {
4852             return activity.getClassName().equals("act1");
4853         };
4854 
4855         setCaller(LAUNCHER_1, USER_0);
4856         assertForLauncherCallback(mLauncherApps, () -> {
4857             updatePackageVersion(CALLING_PACKAGE_1, 1);
4858             mService.mPackageMonitor.onReceive(getTestContext(),
4859                     genPackageUpdateIntent(CALLING_PACKAGE_1, USER_0));
4860         }).assertCallbackCalledForPackageAndUser(CALLING_PACKAGE_1, HANDLE_USER_0)
4861                 // Make sure the launcher gets callbacks.
4862                 .haveIds("s1a", "s1b", "s2b", "s3b")
4863                 .areAllWithKeyFieldsOnly();
4864 
4865         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
4866             // s2a and s3a are gone, but s2b and s3b will remain because they're pinned, and
4867             // disabled.
4868             assertWith(getCallerShortcuts())
4869                     .haveIds("s1a", "s1b", "s2b", "s3b")
4870 
4871                     .selectByIds("s1a", "s1b")
4872                     .areAllDynamic()
4873                     .areAllEnabled()
4874 
4875                     .revertToOriginalList()
4876                     .selectByIds("s2b", "s3b")
4877                     .areAllNotDynamic()
4878                     .areAllDisabled()
4879                     .areAllPinned()
4880             ;
4881         });
4882     }
4883 
prepareForBackupTest()4884     protected void prepareForBackupTest() {
4885         prepareCrossProfileDataSet();
4886 
4887         backupAndRestore();
4888     }
4889 
4890     /**
4891      * Make sure the backup data doesn't have the following information:
4892      * - Launchers on other users.
4893      * - Non-backup app information.
4894      *
4895      * But restores all other infomation.
4896      *
4897      * It also omits the following pieces of information, but that's tested in
4898      * {@link ShortcutManagerTest2#testShortcutInfoSaveAndLoad_forBackup}.
4899      * - Unpinned dynamic shortcuts
4900      * - Bitmaps
4901      */
testBackupAndRestore()4902     public void testBackupAndRestore() {
4903 
4904         assertFileNotExists("user-0/shortcut_dump/restore-0-start.txt");
4905         assertFileNotExists("user-0/shortcut_dump/restore-1-payload.xml");
4906         assertFileNotExists("user-0/shortcut_dump/restore-2.txt");
4907         assertFileNotExists("user-0/shortcut_dump/restore-3.txt");
4908         assertFileNotExists("user-0/shortcut_dump/restore-4.txt");
4909         assertFileNotExists("user-0/shortcut_dump/restore-5-finish.txt");
4910 
4911         prepareForBackupTest();
4912 
4913         assertFileExistsWithContent("user-0/shortcut_dump/restore-0-start.txt");
4914         assertFileExistsWithContent("user-0/shortcut_dump/restore-1-payload.xml");
4915         assertFileExistsWithContent("user-0/shortcut_dump/restore-2.txt");
4916         assertFileExistsWithContent("user-0/shortcut_dump/restore-3.txt");
4917         assertFileExistsWithContent("user-0/shortcut_dump/restore-4.txt");
4918         assertFileExistsWithContent("user-0/shortcut_dump/restore-5-finish.txt");
4919 
4920         checkBackupAndRestore_success(/*firstRestore=*/ true);
4921     }
4922 
testBackupAndRestore_backupRestoreTwice()4923     public void testBackupAndRestore_backupRestoreTwice() {
4924         prepareForBackupTest();
4925 
4926         checkBackupAndRestore_success(/*firstRestore=*/ true);
4927 
4928         // Run a backup&restore again. Note the shortcuts that weren't restored in the previous
4929         // restore are disabled, so they won't be restored again.
4930         dumpsysOnLogcat("Before second backup&restore");
4931 
4932         backupAndRestore();
4933 
4934         dumpsysOnLogcat("After second backup&restore");
4935 
4936         checkBackupAndRestore_success(/*firstRestore=*/ false);
4937     }
4938 
testBackupAndRestore_restoreToNewVersion()4939     public void testBackupAndRestore_restoreToNewVersion() {
4940         prepareForBackupTest();
4941 
4942         addPackage(CALLING_PACKAGE_1, CALLING_UID_1, 2);
4943         addPackage(LAUNCHER_1, LAUNCHER_UID_1, 5);
4944 
4945         checkBackupAndRestore_success(/*firstRestore=*/ true);
4946     }
4947 
testBackupAndRestore_restoreToSuperSetSignatures()4948     public void testBackupAndRestore_restoreToSuperSetSignatures() {
4949         prepareForBackupTest();
4950 
4951         // Change package signatures.
4952         addPackage(CALLING_PACKAGE_1, CALLING_UID_1, 1, "sigx", CALLING_PACKAGE_1);
4953         addPackage(LAUNCHER_1, LAUNCHER_UID_1, 4, LAUNCHER_1, "sigy");
4954 
4955         checkBackupAndRestore_success(/*firstRestore=*/ true);
4956     }
4957 
checkBackupAndRestore_success(boolean firstRestore)4958     protected void checkBackupAndRestore_success(boolean firstRestore) {
4959         // Make sure non-system user is not restored.
4960         final ShortcutUser userP0 = mService.getUserShortcutsLocked(USER_P0);
4961         assertEquals(0, userP0.getAllPackagesForTest().size());
4962         assertEquals(0, userP0.getAllLaunchersForTest().size());
4963 
4964         // Make sure only "allowBackup" apps are restored, and are shadow.
4965         final ShortcutUser user0 = mService.getUserShortcutsLocked(USER_0);
4966         assertExistsAndShadow(user0.getAllPackagesForTest().get(CALLING_PACKAGE_1));
4967         assertExistsAndShadow(user0.getAllPackagesForTest().get(CALLING_PACKAGE_2));
4968 
4969         assertExistsAndShadow(user0.getAllPackagesForTest().get(CALLING_PACKAGE_3));
4970         assertExistsAndShadow(user0.getAllLaunchersForTest().get(
4971                 PackageWithUser.of(USER_0, LAUNCHER_1)));
4972         assertExistsAndShadow(user0.getAllLaunchersForTest().get(
4973                 PackageWithUser.of(USER_0, LAUNCHER_2)));
4974 
4975         assertNull(user0.getAllLaunchersForTest().get(PackageWithUser.of(USER_0, LAUNCHER_3)));
4976         assertNull(user0.getAllLaunchersForTest().get(PackageWithUser.of(USER_P0, LAUNCHER_1)));
4977 
4978         doReturn(true).when(mMockPackageManagerInternal).isDataRestoreSafe(any(byte[].class),
4979                 anyString());
4980 
4981         installPackage(USER_0, CALLING_PACKAGE_1);
4982         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
4983             assertWith(getCallerVisibleShortcuts())
4984                     .selectDynamic()
4985                     .isEmpty()
4986 
4987                     .revertToOriginalList()
4988                     .selectPinned()
4989                     .haveIds("s1", "s2")
4990                     .areAllEnabled();
4991         });
4992 
4993         installPackage(USER_0, LAUNCHER_1);
4994         runWithCaller(LAUNCHER_1, USER_0, () -> {
4995             assertWith(mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_1), HANDLE_USER_0))
4996                     .areAllPinned()
4997                     .haveIds("s1")
4998                     .areAllEnabled();
4999 
5000             assertWith(mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_2), HANDLE_USER_0))
5001                     .isEmpty();
5002 
5003             assertWith(mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_3), HANDLE_USER_0))
5004                     .isEmpty();
5005 
5006             assertWith(mLauncherApps.getShortcuts(QUERY_ALL, HANDLE_USER_P0))
5007                     .isEmpty();
5008         });
5009 
5010         installPackage(USER_0, CALLING_PACKAGE_2);
5011         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
5012             assertWith(getCallerVisibleShortcuts())
5013                     .selectDynamic()
5014                     .isEmpty()
5015 
5016                     .revertToOriginalList()
5017                     .selectPinned()
5018                     .haveIds("s1", "s2", "s3")
5019                     .areAllEnabled();
5020         });
5021 
5022         runWithCaller(LAUNCHER_1, USER_0, () -> {
5023             assertWith(mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_1), HANDLE_USER_0))
5024                     .areAllPinned()
5025                     .haveIds("s1")
5026                     .areAllEnabled();
5027 
5028             assertWith(mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_2), HANDLE_USER_0))
5029                     .areAllPinned()
5030                     .haveIds("s1", "s2")
5031                     .areAllEnabled();
5032 
5033             assertWith(mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_3), HANDLE_USER_0))
5034                     .isEmpty();
5035 
5036             assertWith(mLauncherApps.getShortcuts(QUERY_ALL, HANDLE_USER_P0))
5037                     .isEmpty();
5038         });
5039 
5040         // 3 shouldn't be backed up, so no pinned shortcuts.
5041         installPackage(USER_0, CALLING_PACKAGE_3);
5042         runWithCaller(CALLING_PACKAGE_3, USER_0, () -> {
5043             assertWith(getCallerVisibleShortcuts())
5044                     .isEmpty();
5045         });
5046 
5047         // Launcher on a different profile shouldn't be restored.
5048         runWithCaller(LAUNCHER_1, USER_P0, () -> {
5049             assertWith(mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_1), HANDLE_USER_0))
5050                     .isEmpty();
5051             assertWith(mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_2), HANDLE_USER_0))
5052                     .isEmpty();
5053             assertWith(mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_3), HANDLE_USER_0))
5054                     .isEmpty();
5055         });
5056 
5057         // Package on a different profile, no restore.
5058         installPackage(USER_P0, CALLING_PACKAGE_1);
5059         runWithCaller(CALLING_PACKAGE_1, USER_P0, () -> {
5060             assertWith(getCallerVisibleShortcuts())
5061                     .isEmpty();
5062         });
5063 
5064         // Restore launcher 2 on user 0.
5065         installPackage(USER_0, LAUNCHER_2);
5066         runWithCaller(LAUNCHER_2, USER_0, () -> {
5067             assertWith(mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_1), HANDLE_USER_0))
5068                     .areAllPinned()
5069                     .haveIds("s2")
5070                     .areAllEnabled();
5071 
5072             assertWith(mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_2), HANDLE_USER_0))
5073                     .areAllPinned()
5074                     .haveIds("s2", "s3")
5075                     .areAllEnabled();
5076 
5077             if (firstRestore) {
5078                 assertWith(
5079                         mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_3), HANDLE_USER_0))
5080                         .haveIds("s2", "s3", "s4")
5081                         .areAllDisabled()
5082                         .areAllPinned()
5083                         .areAllNotDynamic()
5084                         .areAllWithDisabledReason(
5085                                 ShortcutInfo.DISABLED_REASON_BACKUP_NOT_SUPPORTED);
5086             } else {
5087                 assertWith(
5088                         mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_3), HANDLE_USER_0))
5089                         .isEmpty();
5090             }
5091 
5092             assertWith(mLauncherApps.getShortcuts(QUERY_ALL, HANDLE_USER_P0))
5093                     .isEmpty();
5094         });
5095 
5096 
5097         // Restoration of launcher2 shouldn't affect other packages; so do the same checks and
5098         // make sure they still have the same result.
5099         installPackage(USER_0, CALLING_PACKAGE_1);
5100         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
5101             assertWith(getCallerVisibleShortcuts())
5102                     .areAllPinned()
5103                     .haveIds("s1", "s2");
5104         });
5105 
5106         installPackage(USER_0, LAUNCHER_1);
5107         runWithCaller(LAUNCHER_1, USER_0, () -> {
5108             assertWith(mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_1), HANDLE_USER_0))
5109                     .areAllPinned()
5110                     .haveIds("s1")
5111                     .areAllEnabled();
5112 
5113             assertWith(mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_2), HANDLE_USER_0))
5114                     .areAllPinned()
5115                     .haveIds("s1", "s2")
5116                     .areAllEnabled();
5117 
5118             if (firstRestore) {
5119                 assertWith(
5120                         mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_3), HANDLE_USER_0))
5121                         .haveIds("s1", "s2", "s3")
5122                         .areAllDisabled()
5123                         .areAllPinned()
5124                         .areAllNotDynamic()
5125                         .areAllWithDisabledReason(ShortcutInfo.DISABLED_REASON_BACKUP_NOT_SUPPORTED);
5126             } else {
5127                 assertWith(
5128                         mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_3), HANDLE_USER_0))
5129                         .isEmpty();
5130             }
5131 
5132             assertWith(mLauncherApps.getShortcuts(QUERY_ALL, HANDLE_USER_P0))
5133                     .isEmpty();
5134         });
5135 
5136         installPackage(USER_0, CALLING_PACKAGE_2);
5137         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
5138             assertWith(getCallerVisibleShortcuts())
5139                     .areAllPinned()
5140                     .haveIds("s1", "s2", "s3")
5141                     .areAllEnabled();
5142         });
5143     }
5144 
testBackupAndRestore_publisherLowerVersion()5145     public void testBackupAndRestore_publisherLowerVersion() {
5146         prepareForBackupTest();
5147 
5148         addPackage(CALLING_PACKAGE_1, CALLING_UID_1, 0); // Lower version
5149 
5150         checkBackupAndRestore_publisherNotRestored(ShortcutInfo.DISABLED_REASON_VERSION_LOWER);
5151     }
5152 
testBackupAndRestore_publisherWrongSignature()5153     public void testBackupAndRestore_publisherWrongSignature() {
5154         prepareForBackupTest();
5155 
5156         addPackage(CALLING_PACKAGE_1, CALLING_UID_1, 10, "sigx"); // different signature
5157 
5158         checkBackupAndRestore_publisherNotRestored(ShortcutInfo.DISABLED_REASON_SIGNATURE_MISMATCH);
5159     }
5160 
testBackupAndRestore_publisherNoLongerBackupTarget()5161     public void testBackupAndRestore_publisherNoLongerBackupTarget() {
5162         prepareForBackupTest();
5163 
5164         updatePackageInfo(CALLING_PACKAGE_1,
5165                 pi -> pi.applicationInfo.flags &= ~ApplicationInfo.FLAG_ALLOW_BACKUP);
5166 
5167         checkBackupAndRestore_publisherNotRestored(
5168                 ShortcutInfo.DISABLED_REASON_BACKUP_NOT_SUPPORTED);
5169     }
5170 
checkBackupAndRestore_publisherNotRestored( int package1DisabledReason)5171     protected void checkBackupAndRestore_publisherNotRestored(
5172             int package1DisabledReason) {
5173         doReturn(package1DisabledReason != ShortcutInfo.DISABLED_REASON_SIGNATURE_MISMATCH).when(
5174                 mMockPackageManagerInternal).isDataRestoreSafe(any(byte[].class),
5175                 eq(CALLING_PACKAGE_1));
5176 
5177         installPackage(USER_0, CALLING_PACKAGE_1);
5178         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
5179             assertEquals(0, mManager.getDynamicShortcuts().size());
5180             assertEquals(0, mManager.getPinnedShortcuts().size());
5181         });
5182         assertFalse(mService.getPackageShortcutForTest(CALLING_PACKAGE_1, USER_0)
5183                 .getPackageInfo().isShadow());
5184 
5185         doReturn(true).when(mMockPackageManagerInternal).isDataRestoreSafe(
5186                 any(byte[].class), anyString());
5187 
5188         installPackage(USER_0, CALLING_PACKAGE_2);
5189         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
5190             assertEquals(0, mManager.getDynamicShortcuts().size());
5191             assertShortcutIds(assertAllPinned(
5192                     mManager.getPinnedShortcuts()),
5193                     "s1", "s2", "s3");
5194         });
5195         assertFalse(mService.getPackageShortcutForTest(CALLING_PACKAGE_2, USER_0)
5196                 .getPackageInfo().isShadow());
5197 
5198         installPackage(USER_0, LAUNCHER_1);
5199         runWithCaller(LAUNCHER_1, USER_0, () -> {
5200             assertWith(mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_1), HANDLE_USER_0))
5201                     .haveIds("s1")
5202                     .areAllPinned()
5203                     .areAllDisabled()
5204                     .areAllWithDisabledReason(package1DisabledReason)
5205                     .forAllShortcuts(si -> {
5206                         switch (package1DisabledReason) {
5207                             case ShortcutInfo.DISABLED_REASON_VERSION_LOWER:
5208                                 assertEquals("App version downgraded, or isn’t compatible"
5209                                         + " with this shortcut",
5210                                         si.getDisabledMessage());
5211                                 break;
5212                             case ShortcutInfo.DISABLED_REASON_SIGNATURE_MISMATCH:
5213                                 assertEquals(
5214                                         "Couldn\u2019t restore shortcut because of app"
5215                                         + " signature mismatch",
5216                                         si.getDisabledMessage());
5217                                 break;
5218                             case ShortcutInfo.DISABLED_REASON_BACKUP_NOT_SUPPORTED:
5219                                 assertEquals(
5220                                         "Couldn\u2019t restore shortcut because app"
5221                                         + " doesn\u2019t support backup and restore",
5222                                         si.getDisabledMessage());
5223                                 break;
5224                             default:
5225                                 fail("Unhandled disabled reason: " + package1DisabledReason);
5226                         }
5227                     });
5228             assertWith(mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_2), HANDLE_USER_0))
5229                     .haveIds("s1", "s2")
5230                     .areAllPinned()
5231                     .areAllEnabled();
5232             assertWith(mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_3), HANDLE_USER_0))
5233                     .isEmpty();
5234         });
5235         installPackage(USER_0, LAUNCHER_2);
5236         runWithCaller(LAUNCHER_2, USER_0, () -> {
5237             assertWith(mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_1), HANDLE_USER_0))
5238                     .haveIds("s2")
5239                     .areAllPinned()
5240                     .areAllDisabled()
5241                     .areAllWithDisabledReason(package1DisabledReason);
5242             assertWith(mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_2), HANDLE_USER_0))
5243                     .haveIds("s2", "s3")
5244                     .areAllPinned()
5245                     .areAllEnabled();
5246             assertWith(mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_3), HANDLE_USER_0))
5247                     .isEmpty();
5248         });
5249 
5250         installPackage(USER_0, CALLING_PACKAGE_3);
5251         runWithCaller(CALLING_PACKAGE_3, USER_0, () -> {
5252             assertEquals(0, mManager.getDynamicShortcuts().size());
5253             assertEquals(0, mManager.getPinnedShortcuts().size());
5254         });
5255 
5256         runWithCaller(LAUNCHER_1, USER_0, () -> {
5257             assertWith(mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_1), HANDLE_USER_0))
5258                     .haveIds("s1")
5259                     .areAllPinned()
5260                     .areAllDisabled()
5261                     .areAllWithDisabledReason(package1DisabledReason);
5262             assertWith(mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_2), HANDLE_USER_0))
5263                     .haveIds("s1", "s2")
5264                     .areAllPinned()
5265                     .areAllEnabled();
5266             assertWith(mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_3), HANDLE_USER_0))
5267                     .haveIds("s1", "s2", "s3")
5268                     .areAllPinned()
5269                     .areAllDisabled()
5270                     .areAllWithDisabledReason(ShortcutInfo.DISABLED_REASON_BACKUP_NOT_SUPPORTED);
5271         });
5272         runWithCaller(LAUNCHER_2, USER_0, () -> {
5273             assertWith(mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_1), HANDLE_USER_0))
5274                     .haveIds("s2")
5275                     .areAllPinned()
5276                     .areAllDisabled()
5277                     .areAllWithDisabledReason(package1DisabledReason);
5278             assertWith(mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_2), HANDLE_USER_0))
5279                     .haveIds("s2", "s3")
5280                     .areAllPinned()
5281                     .areAllEnabled();
5282             assertWith(mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_3), HANDLE_USER_0))
5283                     .haveIds("s2", "s3", "s4")
5284                     .areAllPinned()
5285                     .areAllDisabled()
5286                     .areAllWithDisabledReason(ShortcutInfo.DISABLED_REASON_BACKUP_NOT_SUPPORTED);
5287         });
5288     }
5289 
testBackupAndRestore_launcherLowerVersion()5290     public void testBackupAndRestore_launcherLowerVersion() {
5291         prepareForBackupTest();
5292 
5293         addPackage(LAUNCHER_1, LAUNCHER_UID_1, 0); // Lower version
5294 
5295         // Note, we restore pinned shortcuts even if the launcher is of a lower version.
5296         checkBackupAndRestore_success(/*firstRestore=*/ true);
5297     }
5298 
testBackupAndRestore_launcherWrongSignature()5299     public void testBackupAndRestore_launcherWrongSignature() {
5300         prepareForBackupTest();
5301 
5302         addPackage(LAUNCHER_1, LAUNCHER_UID_1, 10, "sigx"); // different signature
5303 
5304         checkBackupAndRestore_launcherNotRestored(true);
5305     }
5306 
testBackupAndRestore_launcherNoLongerBackupTarget()5307     public void testBackupAndRestore_launcherNoLongerBackupTarget() {
5308         prepareForBackupTest();
5309 
5310         updatePackageInfo(LAUNCHER_1,
5311                 pi -> pi.applicationInfo.flags &= ~ApplicationInfo.FLAG_ALLOW_BACKUP);
5312 
5313         checkBackupAndRestore_launcherNotRestored(false);
5314     }
5315 
checkBackupAndRestore_launcherNotRestored(boolean differentSignatures)5316     protected void checkBackupAndRestore_launcherNotRestored(boolean differentSignatures) {
5317         doReturn(true).when(mMockPackageManagerInternal).isDataRestoreSafe(
5318                 any(byte[].class), anyString());
5319 
5320         installPackage(USER_0, CALLING_PACKAGE_1);
5321         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
5322             assertEquals(0, mManager.getDynamicShortcuts().size());
5323 
5324             // s1 was pinned by launcher 1, which is not restored, yet, so we still see "s1" here.
5325             assertShortcutIds(assertAllPinned(
5326                     mManager.getPinnedShortcuts()),
5327                     "s1", "s2");
5328         });
5329 
5330         installPackage(USER_0, CALLING_PACKAGE_2);
5331         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
5332             assertEquals(0, mManager.getDynamicShortcuts().size());
5333             assertShortcutIds(assertAllPinned(
5334                     mManager.getPinnedShortcuts()),
5335                     "s1", "s2", "s3");
5336         });
5337 
5338         doReturn(!differentSignatures).when(mMockPackageManagerInternal).isDataRestoreSafe(
5339                 any(byte[].class), eq(LAUNCHER_1));
5340 
5341         // Now we try to restore launcher 1.  Then we realize it's not restorable, so L1 has no pinned
5342         // shortcuts.
5343         installPackage(USER_0, LAUNCHER_1);
5344         runWithCaller(LAUNCHER_1, USER_0, () -> {
5345             assertShortcutIds(assertAllPinned(
5346                     mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_1), HANDLE_USER_0))
5347                     /* empty */);
5348             assertShortcutIds(assertAllPinned(
5349                     mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_2), HANDLE_USER_0))
5350                     /* empty */);
5351             assertShortcutIds(assertAllPinned(
5352                     mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_3), HANDLE_USER_0))
5353                     /* empty */);
5354         });
5355         assertFalse(mService.getLauncherShortcutForTest(LAUNCHER_1, USER_0)
5356                 .getPackageInfo().isShadow());
5357 
5358         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
5359             assertEquals(0, mManager.getDynamicShortcuts().size());
5360 
5361             // Now CALLING_PACKAGE_1 realizes "s1" is no longer pinned.
5362             assertShortcutIds(assertAllPinned(
5363                     mManager.getPinnedShortcuts()),
5364                     "s2");
5365         });
5366 
5367         doReturn(true).when(mMockPackageManagerInternal).isDataRestoreSafe(
5368                 any(byte[].class), anyString());
5369 
5370         installPackage(USER_0, LAUNCHER_2);
5371         runWithCaller(LAUNCHER_2, USER_0, () -> {
5372             assertShortcutIds(assertAllPinned(
5373                     mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_1), HANDLE_USER_0)),
5374                     "s2");
5375             assertShortcutIds(assertAllPinned(
5376                     mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_2), HANDLE_USER_0)),
5377                     "s2", "s3");
5378             assertShortcutIds(assertAllPinned(
5379                     mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_3), HANDLE_USER_0))
5380                     /* empty */);
5381         });
5382         assertFalse(mService.getLauncherShortcutForTest(LAUNCHER_2, USER_0)
5383                 .getPackageInfo().isShadow());
5384 
5385         installPackage(USER_0, CALLING_PACKAGE_3);
5386         runWithCaller(CALLING_PACKAGE_3, USER_0, () -> {
5387             assertEquals(0, mManager.getDynamicShortcuts().size());
5388             assertEquals(0, mManager.getPinnedShortcuts().size());
5389         });
5390 
5391         runWithCaller(LAUNCHER_1, USER_0, () -> {
5392             assertShortcutIds(assertAllPinned(
5393                     mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_1), HANDLE_USER_0))
5394                     /* empty */);
5395             assertShortcutIds(assertAllPinned(
5396                     mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_2), HANDLE_USER_0))
5397                     /* empty */);
5398             assertShortcutIds(assertAllPinned(
5399                     mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_3), HANDLE_USER_0))
5400                     /* empty */);
5401         });
5402         runWithCaller(LAUNCHER_2, USER_0, () -> {
5403             assertShortcutIds(assertAllPinned(
5404                     mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_1), HANDLE_USER_0)),
5405                     "s2");
5406             assertShortcutIds(assertAllPinned(
5407                     mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_2), HANDLE_USER_0)),
5408                     "s2", "s3");
5409         });
5410     }
5411 
testBackupAndRestore_launcherAndPackageNoLongerBackupTarget()5412     public void testBackupAndRestore_launcherAndPackageNoLongerBackupTarget() {
5413         prepareForBackupTest();
5414 
5415         updatePackageInfo(CALLING_PACKAGE_1,
5416                 pi -> pi.applicationInfo.flags &= ~ApplicationInfo.FLAG_ALLOW_BACKUP);
5417 
5418         updatePackageInfo(LAUNCHER_1,
5419                 pi -> pi.applicationInfo.flags &= ~ApplicationInfo.FLAG_ALLOW_BACKUP);
5420 
5421         checkBackupAndRestore_publisherAndLauncherNotRestored();
5422     }
5423 
checkBackupAndRestore_publisherAndLauncherNotRestored()5424     protected void checkBackupAndRestore_publisherAndLauncherNotRestored() {
5425         doReturn(true).when(mMockPackageManagerInternal).isDataRestoreSafe(any(byte[].class),
5426                 anyString());
5427         installPackage(USER_0, CALLING_PACKAGE_1);
5428         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
5429             assertEquals(0, mManager.getDynamicShortcuts().size());
5430             assertEquals(0, mManager.getPinnedShortcuts().size());
5431         });
5432 
5433         installPackage(USER_0, CALLING_PACKAGE_2);
5434         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
5435             assertEquals(0, mManager.getDynamicShortcuts().size());
5436             assertShortcutIds(assertAllPinned(
5437                     mManager.getPinnedShortcuts()),
5438                     "s1", "s2", "s3");
5439         });
5440 
5441         installPackage(USER_0, LAUNCHER_1);
5442         runWithCaller(LAUNCHER_1, USER_0, () -> {
5443             assertShortcutIds(assertAllPinned(
5444                     mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_1), HANDLE_USER_0))
5445                     /* empty */);
5446             assertShortcutIds(assertAllPinned(
5447                     mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_2), HANDLE_USER_0))
5448                     /* empty */);
5449             assertShortcutIds(assertAllPinned(
5450                     mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_3), HANDLE_USER_0))
5451                     /* empty */);
5452         });
5453         installPackage(USER_0, LAUNCHER_2);
5454         runWithCaller(LAUNCHER_2, USER_0, () -> {
5455             assertWith(mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_1), HANDLE_USER_0))
5456                     .areAllPinned()
5457                     .haveIds("s2")
5458                     .areAllDisabled();
5459             assertWith(mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_2), HANDLE_USER_0))
5460                     .areAllPinned()
5461                     .haveIds("s2", "s3");
5462             assertWith(mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_3), HANDLE_USER_0))
5463                     .isEmpty();
5464         });
5465 
5466         // Because launcher 1 wasn't restored, "s1" is no longer pinned.
5467         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
5468             assertEquals(0, mManager.getDynamicShortcuts().size());
5469             assertShortcutIds(assertAllPinned(
5470                     mManager.getPinnedShortcuts()),
5471                     "s2", "s3");
5472         });
5473 
5474         installPackage(USER_0, CALLING_PACKAGE_3);
5475         runWithCaller(CALLING_PACKAGE_3, USER_0, () -> {
5476             assertEquals(0, mManager.getDynamicShortcuts().size());
5477             assertEquals(0, mManager.getPinnedShortcuts().size());
5478         });
5479 
5480         runWithCaller(LAUNCHER_1, USER_0, () -> {
5481             assertShortcutIds(assertAllPinned(
5482                     mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_1), HANDLE_USER_0))
5483                     /* empty */);
5484             assertShortcutIds(assertAllPinned(
5485                     mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_2), HANDLE_USER_0))
5486                     /* empty */);
5487             assertShortcutIds(assertAllPinned(
5488                     mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_3), HANDLE_USER_0))
5489                     /* empty */);
5490         });
5491         runWithCaller(LAUNCHER_2, USER_0, () -> {
5492             assertWith(mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_1), HANDLE_USER_0))
5493                     .areAllPinned()
5494                     .haveIds("s2")
5495                     .areAllDisabled();
5496             assertWith(mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_2), HANDLE_USER_0))
5497                     .areAllPinned()
5498                     .haveIds("s2", "s3");
5499             assertWith(
5500                     mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_3), HANDLE_USER_0))
5501                     .haveIds("s2", "s3", "s4")
5502                     .areAllDisabled()
5503                     .areAllPinned()
5504                     .areAllNotDynamic()
5505                     .areAllWithDisabledReason(
5506                             ShortcutInfo.DISABLED_REASON_BACKUP_NOT_SUPPORTED);
5507         });
5508     }
5509 
testBackupAndRestore_disabled()5510     public void testBackupAndRestore_disabled() {
5511         prepareCrossProfileDataSet();
5512 
5513         // Before doing backup & restore, disable s1.
5514         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
5515             mManager.disableShortcuts(list("s1"));
5516         });
5517 
5518         backupAndRestore();
5519 
5520         // Below is copied from checkBackupAndRestore_success.
5521 
5522         // Make sure non-system user is not restored.
5523         final ShortcutUser userP0 = mService.getUserShortcutsLocked(USER_P0);
5524         assertEquals(0, userP0.getAllPackagesForTest().size());
5525         assertEquals(0, userP0.getAllLaunchersForTest().size());
5526 
5527         // Make sure only "allowBackup" apps are restored, and are shadow.
5528         final ShortcutUser user0 = mService.getUserShortcutsLocked(USER_0);
5529         assertExistsAndShadow(user0.getAllPackagesForTest().get(CALLING_PACKAGE_1));
5530         assertExistsAndShadow(user0.getAllPackagesForTest().get(CALLING_PACKAGE_2));
5531         assertExistsAndShadow(user0.getAllPackagesForTest().get(CALLING_PACKAGE_3));
5532         assertExistsAndShadow(user0.getAllLaunchersForTest().get(
5533                 PackageWithUser.of(USER_0, LAUNCHER_1)));
5534         assertExistsAndShadow(user0.getAllLaunchersForTest().get(
5535                 PackageWithUser.of(USER_0, LAUNCHER_2)));
5536 
5537         assertNull(user0.getAllLaunchersForTest().get(PackageWithUser.of(USER_0, LAUNCHER_3)));
5538         assertNull(user0.getAllLaunchersForTest().get(PackageWithUser.of(USER_P0, LAUNCHER_1)));
5539 
5540         doReturn(true).when(mMockPackageManagerInternal).isDataRestoreSafe(any(byte[].class),
5541                 anyString());
5542 
5543         installPackage(USER_0, CALLING_PACKAGE_1);
5544         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
5545             assertWith(getCallerVisibleShortcuts())
5546                     .areAllEnabled() // disabled shortcuts shouldn't be restored.
5547 
5548                     .selectDynamic()
5549                     .isEmpty()
5550 
5551                     .revertToOriginalList()
5552                     .selectPinned()
5553                     // s1 is not restored.
5554                     .haveIds("s2");
5555         });
5556 
5557         installPackage(USER_0, LAUNCHER_1);
5558         runWithCaller(LAUNCHER_1, USER_0, () -> {
5559             // Note, s1 was pinned by launcher 1, but was disabled, so isn't restored.
5560             assertWith(mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_1), HANDLE_USER_0))
5561                     .isEmpty();
5562 
5563             assertWith(mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_2), HANDLE_USER_0))
5564                     .isEmpty();
5565 
5566             assertWith(mLauncherApps.getShortcuts(buildAllQuery(CALLING_PACKAGE_3), HANDLE_USER_0))
5567                     .isEmpty();
5568 
5569             assertWith(mLauncherApps.getShortcuts(QUERY_ALL, HANDLE_USER_P0))
5570                     .isEmpty();
5571         });
5572     }
5573 
5574 
testBackupAndRestore_manifestRePublished()5575     public void testBackupAndRestore_manifestRePublished() {
5576         // Publish two manifest shortcuts.
5577         addManifestShortcutResource(
5578                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
5579                 R.xml.shortcut_2);
5580         updatePackageVersion(CALLING_PACKAGE_1, 1);
5581         mService.mPackageMonitor.onReceive(mServiceContext,
5582                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
5583 
5584         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
5585             assertTrue(mManager.setDynamicShortcuts(list(
5586                     makeShortcut("s1"), makeShortcut("s2"), makeShortcut("s3"))));
5587         });
5588 
5589         // Pin from launcher 1.
5590         runWithCaller(LAUNCHER_1, USER_0, () -> {
5591             mLauncherApps.pinShortcuts(CALLING_PACKAGE_1,
5592                     list("ms1", "ms2", "s1", "s2"), HANDLE_USER_0);
5593         });
5594 
5595         // Update and now ms2 is gone -> disabled.
5596         addManifestShortcutResource(
5597                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
5598                 R.xml.shortcut_1);
5599         updatePackageVersion(CALLING_PACKAGE_1, 1);
5600         mService.mPackageMonitor.onReceive(mServiceContext,
5601                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
5602 
5603         // Make sure the manifest shortcuts have been published.
5604         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
5605             assertWith(getCallerShortcuts())
5606                     .selectManifest()
5607                     .haveIds("ms1")
5608 
5609                     .revertToOriginalList()
5610                     .selectDynamic()
5611                     .haveIds("s1", "s2", "s3")
5612 
5613                     .revertToOriginalList()
5614                     .selectPinned()
5615                     .haveIds("ms1", "ms2", "s1", "s2")
5616 
5617                     .revertToOriginalList()
5618                     .selectByIds("ms1")
5619                     .areAllManifest()
5620                     .areAllEnabled()
5621 
5622                     .revertToOriginalList()
5623                     .selectByIds("ms2")
5624                     .areAllNotManifest()
5625                     .areAllDisabled();
5626         });
5627 
5628         doReturn(true).when(mMockPackageManagerInternal).isDataRestoreSafe(
5629                 any(byte[].class), anyString());
5630         backupAndRestore();
5631 
5632         // When re-installing the app, the manifest shortcut should be re-published.
5633         mService.mPackageMonitor.onReceive(mServiceContext,
5634                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
5635         mService.mPackageMonitor.onReceive(mServiceContext,
5636                 genPackageAddIntent(LAUNCHER_1, USER_0));
5637 
5638         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
5639             assertWith(getCallerVisibleShortcuts())
5640                     .selectPinned()
5641                     // ms2 was disabled, so not restored.
5642                     .haveIds("ms1", "s1", "s2")
5643                     .areAllEnabled()
5644 
5645                     .revertToOriginalList()
5646                     .selectByIds("ms1")
5647                     .areAllManifest()
5648 
5649                     .revertToOriginalList()
5650                     .selectByIds("s1", "s2")
5651                     .areAllNotDynamic()
5652             ;
5653         });
5654     }
5655 
5656     /**
5657      * It's the case with preintalled apps -- when applyRestore() is called, the system
5658      * apps are already installed, so manifest shortcuts need to be re-published.
5659      *
5660      * Also, when a restore target app is already installed, and
5661      * - if it has allowBackup=true, we'll restore normally, so all existing shortcuts will be
5662      * replaced. (but manifest shortcuts will be re-published anyway.)  We log a warning on
5663      * logcat.
5664      * - if it has allowBackup=false, we don't touch any of the existing shortcuts.
5665      */
testBackupAndRestore_appAlreadyInstalledWhenRestored()5666     public void testBackupAndRestore_appAlreadyInstalledWhenRestored() {
5667         // Pre-backup.  Same as testBackupAndRestore_manifestRePublished().
5668 
5669         // Publish two manifest shortcuts.
5670         addManifestShortcutResource(
5671                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
5672                 R.xml.shortcut_2);
5673         updatePackageVersion(CALLING_PACKAGE_1, 1);
5674         mService.mPackageMonitor.onReceive(mServiceContext,
5675                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
5676 
5677         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
5678             assertTrue(mManager.setDynamicShortcuts(list(
5679                     makeShortcut("s1"), makeShortcut("s2"), makeShortcut("s3"))));
5680         });
5681 
5682         // Pin from launcher 1.
5683         runWithCaller(LAUNCHER_1, USER_0, () -> {
5684             mLauncherApps.pinShortcuts(CALLING_PACKAGE_1,
5685                     list("ms1", "ms2", "s1", "s2"), HANDLE_USER_0);
5686         });
5687 
5688         // Update and now ms2 is gone -> disabled.
5689         addManifestShortcutResource(
5690                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
5691                 R.xml.shortcut_1);
5692         updatePackageVersion(CALLING_PACKAGE_1, 1);
5693         mService.mPackageMonitor.onReceive(mServiceContext,
5694                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
5695 
5696         // Set up shortcuts for package 3, which won't be backed up / restored.
5697         addManifestShortcutResource(
5698                 new ComponentName(CALLING_PACKAGE_3, ShortcutActivity.class.getName()),
5699                 R.xml.shortcut_1);
5700         updatePackageVersion(CALLING_PACKAGE_3, 1);
5701         mService.mPackageMonitor.onReceive(mServiceContext,
5702                 genPackageAddIntent(CALLING_PACKAGE_3, USER_0));
5703 
5704         runWithCaller(CALLING_PACKAGE_3, USER_0, () -> {
5705             assertTrue(getManager().setDynamicShortcuts(list(
5706                     makeShortcut("s1"))));
5707         });
5708 
5709         // Make sure the manifest shortcuts have been published.
5710         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
5711             assertWith(getCallerShortcuts())
5712                     .selectManifest()
5713                     .haveIds("ms1")
5714 
5715                     .revertToOriginalList()
5716                     .selectDynamic()
5717                     .haveIds("s1", "s2", "s3")
5718 
5719                     .revertToOriginalList()
5720                     .selectPinned()
5721                     .haveIds("ms1", "ms2", "s1", "s2")
5722 
5723                     .revertToOriginalList()
5724                     .selectByIds("ms1")
5725                     .areAllManifest()
5726                     .areAllEnabled()
5727 
5728                     .revertToOriginalList()
5729                     .selectByIds("ms2")
5730                     .areAllNotManifest()
5731                     .areAllDisabled();
5732         });
5733 
5734         runWithCaller(CALLING_PACKAGE_3, USER_0, () -> {
5735             assertWith(getCallerShortcuts())
5736                     .haveIds("s1", "ms1");
5737         });
5738 
5739         doReturn(true).when(mMockPackageManagerInternal).isDataRestoreSafe(any(byte[].class),
5740                 anyString());
5741         // Backup and *without restarting the service, just call applyRestore()*.
5742         {
5743             int prevUid = mInjectedCallingUid;
5744             mInjectedCallingUid = Process.SYSTEM_UID; // Only system can call it.
5745 
5746             dumpsysOnLogcat("Before backup");
5747 
5748             final byte[] payload = mService.getBackupPayload(USER_0);
5749             if (ENABLE_DUMP) {
5750                 final String xml = new String(payload);
5751                 Log.v(TAG, "Backup payload:");
5752                 for (String line : xml.split("\n")) {
5753                     Log.v(TAG, line);
5754                 }
5755             }
5756             mService.applyRestore(payload, USER_0);
5757 
5758             dumpsysOnLogcat("After restore");
5759 
5760             mInjectedCallingUid = prevUid;
5761         }
5762 
5763         // The check is also the same as testBackupAndRestore_manifestRePublished().
5764         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
5765             assertWith(getCallerVisibleShortcuts())
5766                     .selectPinned()
5767                     // ms2 was disabled, so not restored.
5768                     .haveIds("ms1", "s1", "s2")
5769                     .areAllEnabled()
5770 
5771                     .revertToOriginalList()
5772                     .selectByIds("ms1")
5773                     .areAllManifest()
5774 
5775                     .revertToOriginalList()
5776                     .selectByIds("s1", "s2")
5777                     .areAllNotDynamic()
5778             ;
5779         });
5780 
5781         // Package 3 still has the same shortcuts.
5782         runWithCaller(CALLING_PACKAGE_3, USER_0, () -> {
5783             assertWith(getCallerShortcuts())
5784                     .haveIds("s1", "ms1");
5785         });
5786     }
5787 
5788 
5789     /**
5790      * Restored to a lower version with no manifest shortcuts. All shortcuts are now invisible,
5791      * and all calls from the publisher should ignore them.
5792      */
testBackupAndRestore_disabledShortcutsAreIgnored()5793     public void testBackupAndRestore_disabledShortcutsAreIgnored() {
5794         // Publish two manifest shortcuts.
5795         addManifestShortcutResource(
5796                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
5797                 R.xml.shortcut_5_altalt);
5798         updatePackageVersion(CALLING_PACKAGE_1, 1);
5799         mService.mPackageMonitor.onReceive(mServiceContext,
5800                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
5801 
5802         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
5803             assertTrue(mManager.setDynamicShortcuts(list(
5804                     makeShortcutWithShortLabel("s1", "original-title"),
5805                     makeShortcut("s2"), makeShortcut("s3"))));
5806         });
5807 
5808         // Pin from launcher 1.
5809         runWithCaller(LAUNCHER_1, USER_0, () -> {
5810             mLauncherApps.pinShortcuts(CALLING_PACKAGE_1,
5811                     list("ms1", "ms2", "ms3", "ms4", "s1", "s2"), HANDLE_USER_0);
5812         });
5813 
5814         doReturn(true).when(mMockPackageManagerInternal).isDataRestoreSafe(
5815                 any(byte[].class), anyString());
5816 
5817         backupAndRestore();
5818 
5819         // Lower the version and remove the manifest shortcuts.
5820         addManifestShortcutResource(
5821                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
5822                 R.xml.shortcut_0);
5823         addPackage(CALLING_PACKAGE_1, CALLING_UID_1, 0); // Lower version
5824 
5825         // When re-installing the app, the manifest shortcut should be re-published.
5826         mService.mPackageMonitor.onReceive(mServiceContext,
5827                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
5828         mService.mPackageMonitor.onReceive(mServiceContext,
5829                 genPackageAddIntent(LAUNCHER_1, USER_0));
5830 
5831         // No shortcuts should be visible to the publisher.
5832         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
5833             assertWith(getCallerVisibleShortcuts())
5834                     .isEmpty();
5835         });
5836 
5837         final Runnable checkAllDisabledForLauncher = () -> {
5838             runWithCaller(LAUNCHER_1, USER_0, () -> {
5839                 assertWith(getShortcutAsLauncher(USER_0))
5840                         .areAllPinned()
5841                         .haveIds("ms1", "ms2", "ms3", "ms4", "s1", "s2")
5842                         .areAllDisabled()
5843                         .areAllWithDisabledReason(ShortcutInfo.DISABLED_REASON_VERSION_LOWER)
5844 
5845                         .forShortcutWithId("s1", si -> {
5846                             assertEquals("original-title", si.getShortLabel());
5847                         })
5848                         .forShortcutWithId("ms1", si -> {
5849                             assertEquals("string-com.android.test.1-user:0-res:"
5850                                             + R.string.shortcut_title1 + "/en"
5851                                     , si.getShortLabel());
5852                         })
5853                         .forShortcutWithId("ms2", si -> {
5854                             assertEquals("string-com.android.test.1-user:0-res:"
5855                                             + R.string.shortcut_title2 + "/en"
5856                                     , si.getShortLabel());
5857                         })
5858                         .forShortcutWithId("ms3", si -> {
5859                             assertEquals("string-com.android.test.1-user:0-res:"
5860                                             + R.string.shortcut_title1 + "/en"
5861                                     , si.getShortLabel());
5862                             assertEquals("string-com.android.test.1-user:0-res:"
5863                                             + R.string.shortcut_title2 + "/en"
5864                                     , si.getLongLabel());
5865                         })
5866                         .forShortcutWithId("ms4", si -> {
5867                             assertEquals("string-com.android.test.1-user:0-res:"
5868                                             + R.string.shortcut_title2 + "/en"
5869                                     , si.getShortLabel());
5870                             assertEquals("string-com.android.test.1-user:0-res:"
5871                                             + R.string.shortcut_title2 + "/en"
5872                                     , si.getLongLabel());
5873                         });
5874             });
5875         };
5876 
5877         checkAllDisabledForLauncher.run();
5878 
5879         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
5880 
5881             makeCallerForeground(); // CALLING_PACKAGE_1 is now in the foreground.
5882 
5883             // All changing API calls should be ignored.
5884 
5885             getManager().enableShortcuts(list("ms1", "ms2", "ms3", "ms4", "s1", "s2"));
5886             checkAllDisabledForLauncher.run();
5887 
5888             getManager().enableShortcuts(list("ms1", "ms2", "ms3", "ms4", "s1", "s2"));
5889             checkAllDisabledForLauncher.run();
5890 
5891             getManager().enableShortcuts(list("ms1", "ms2", "ms3", "ms4", "s1", "s2"));
5892             checkAllDisabledForLauncher.run();
5893 
5894             getManager().removeAllDynamicShortcuts();
5895             getManager().removeDynamicShortcuts(list("ms1", "ms2", "ms3", "ms4", "s1", "s2"));
5896             checkAllDisabledForLauncher.run();
5897 
5898             getManager().updateShortcuts(list(makeShortcutWithShortLabel("s1", "new-title")));
5899             checkAllDisabledForLauncher.run();
5900 
5901 
5902             // Add a shortcut -- even though ms1 was immutable, it will succeed.
5903             assertTrue(getManager().addDynamicShortcuts(list(
5904                     makeShortcutWithShortLabel("ms1", "original-title"))));
5905 
5906             runWithCaller(LAUNCHER_1, USER_0, () -> {
5907                 assertWith(getShortcutAsLauncher(USER_0))
5908                         .haveIds("ms1", "ms2", "ms3", "ms4", "s1", "s2")
5909 
5910                         .selectByIds("ms1")
5911                         .areAllEnabled()
5912                         .areAllDynamic()
5913                         .areAllPinned()
5914                         .forAllShortcuts(si -> {
5915                             assertEquals("original-title", si.getShortLabel());
5916                         })
5917 
5918                         // The rest still exist and disabled.
5919                         .revertToOriginalList()
5920                         .selectByIds("ms2", "ms3", "ms4", "s1", "s2")
5921                         .areAllDisabled()
5922                         .areAllPinned()
5923                 ;
5924             });
5925 
5926             assertTrue(getManager().setDynamicShortcuts(list(
5927                     makeShortcutWithShortLabel("ms2", "new-title-2"))));
5928 
5929             runWithCaller(LAUNCHER_1, USER_0, () -> {
5930                 assertWith(getShortcutAsLauncher(USER_0))
5931                         .haveIds("ms1", "ms2", "ms3", "ms4", "s1", "s2")
5932 
5933                         .selectByIds("ms1")
5934                         .areAllEnabled()
5935                         .areAllNotDynamic() // ms1 was not in the list, so no longer dynamic.
5936                         .areAllPinned()
5937                         .areAllMutable()
5938                         .forAllShortcuts(si -> {
5939                             assertEquals("original-title", si.getShortLabel());
5940                         })
5941 
5942                         .revertToOriginalList()
5943                         .selectByIds("ms2")
5944                         .areAllEnabled()
5945                         .areAllDynamic()
5946                         .areAllPinned()
5947                         .areAllMutable()
5948                         .forAllShortcuts(si -> {
5949                             assertEquals("new-title-2", si.getShortLabel());
5950                         })
5951 
5952                         // The rest still exist and disabled.
5953                         .revertToOriginalList()
5954                         .selectByIds("ms3", "ms4", "s1", "s2")
5955                         .areAllDisabled()
5956                         .areAllPinned()
5957                 ;
5958             });
5959 
5960             // Prepare for requestPinShortcut().
5961             setDefaultLauncher(USER_0, mMainActivityFetcher.apply(LAUNCHER_1, USER_0));
5962             mPinConfirmActivityFetcher = (packageName, userId) ->
5963                     new ComponentName(packageName, PIN_CONFIRM_ACTIVITY_CLASS);
5964 
5965             mManager.requestPinShortcut(
5966                     makeShortcutWithShortLabel("ms3", "new-title-3"),
5967                     /*PendingIntent=*/ null);
5968 
5969             // Note this was pinned, so it'll be accepted right away.
5970             runWithCaller(LAUNCHER_1, USER_0, () -> {
5971                 assertWith(getShortcutAsLauncher(USER_0))
5972                         .selectByIds("ms3")
5973                         .areAllEnabled()
5974                         .areAllNotDynamic()
5975                         .areAllPinned()
5976                         .areAllMutable()
5977                         .forAllShortcuts(si -> {
5978                             assertEquals("new-title-3", si.getShortLabel());
5979                             // The new one replaces the old manifest shortcut, so the long label
5980                             // should be gone now.
5981                             assertNull(si.getLongLabel());
5982                         });
5983             });
5984 
5985             // Now, change the launcher to launcher2, and request pin again.
5986             setDefaultLauncher(USER_0, mMainActivityFetcher.apply(LAUNCHER_2, USER_0));
5987 
5988             reset(mServiceContext);
5989 
5990             assertTrue(mManager.isRequestPinShortcutSupported());
5991             mManager.requestPinShortcut(
5992                     makeShortcutWithShortLabel("ms4", "new-title-4"),
5993                     /*PendingIntent=*/ null);
5994 
5995             // Initially there should be no pinned shortcuts for L2.
5996             runWithCaller(LAUNCHER_2, USER_0, () -> {
5997                 assertWith(getShortcutAsLauncher(USER_0))
5998                         .selectPinned()
5999                         .isEmpty();
6000 
6001                 final ArgumentCaptor<Intent> intent = ArgumentCaptor.forClass(Intent.class);
6002 
6003                 verify(mServiceContext).startActivityAsUser(intent.capture(), eq(HANDLE_USER_0));
6004 
6005                 assertEquals(LauncherApps.ACTION_CONFIRM_PIN_SHORTCUT,
6006                         intent.getValue().getAction());
6007                 assertEquals(LAUNCHER_2, intent.getValue().getComponent().getPackageName());
6008 
6009                 // Check the request object.
6010                 final PinItemRequest request = mLauncherApps.getPinItemRequest(intent.getValue());
6011 
6012                 assertNotNull(request);
6013                 assertEquals(PinItemRequest.REQUEST_TYPE_SHORTCUT, request.getRequestType());
6014 
6015                 assertWith(request.getShortcutInfo())
6016                         .haveIds("ms4")
6017                         .areAllOrphan()
6018                         .forAllShortcuts(si -> {
6019                             assertEquals("new-title-4", si.getShortLabel());
6020                             // The new one replaces the old manifest shortcut, so the long label
6021                             // should be gone now.
6022                             assertNull(si.getLongLabel());
6023                         });
6024                 assertTrue(request.accept());
6025 
6026                 assertWith(getShortcutAsLauncher(USER_0))
6027                         .selectPinned()
6028                         .haveIds("ms4")
6029                         .areAllEnabled();
6030             });
6031         });
6032     }
6033 
6034     /**
6035      * Test for restoring the pre-P backup format.
6036      */
testBackupAndRestore_api27format()6037     public void testBackupAndRestore_api27format() throws Exception {
6038         final byte[] payload = readTestAsset("shortcut/shortcut_api27_backup.xml").getBytes();
6039 
6040         addPackage(CALLING_PACKAGE_1, CALLING_UID_1, 10, "22222");
6041         addPackage(LAUNCHER_1, LAUNCHER_UID_1, 10, "11111");
6042 
6043         doReturn(true).when(mMockPackageManagerInternal).isDataRestoreSafe(
6044                 any(byte[].class), anyString());
6045 
6046         runWithSystemUid(() -> mService.applyRestore(payload, USER_0));
6047 
6048         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
6049             assertWith(getCallerShortcuts())
6050                     .areAllPinned()
6051                     .haveIds("s1")
6052                     .areAllEnabled();
6053         });
6054 
6055         runWithCaller(LAUNCHER_1, USER_0, () -> {
6056             assertWith(getShortcutAsLauncher(USER_0))
6057                     .areAllPinned()
6058                     .haveIds("s1")
6059                     .areAllEnabled();
6060         });
6061         // Make sure getBackupSourceVersionCode and isBackupSourceBackupAllowed
6062         // are correct. We didn't have them in the old format.
6063         assertEquals(8, mService.getPackageShortcutForTest(CALLING_PACKAGE_1, USER_0)
6064                 .getPackageInfo().getBackupSourceVersionCode());
6065         assertTrue(mService.getPackageShortcutForTest(CALLING_PACKAGE_1, USER_0)
6066                 .getPackageInfo().isBackupSourceBackupAllowed());
6067 
6068         assertEquals(9, mService.getLauncherShortcutForTest(LAUNCHER_1, USER_0)
6069                 .getPackageInfo().getBackupSourceVersionCode());
6070         assertTrue(mService.getLauncherShortcutForTest(LAUNCHER_1, USER_0)
6071                 .getPackageInfo().isBackupSourceBackupAllowed());
6072 
6073     }
6074 
testSaveAndLoad_crossProfile()6075     public void testSaveAndLoad_crossProfile() {
6076         prepareCrossProfileDataSet();
6077 
6078         dumpsysOnLogcat("Before save & load");
6079 
6080         mService.saveDirtyInfo();
6081         initService();
6082 
6083         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
6084             assertShortcutIds(assertAllDynamic(mManager.getDynamicShortcuts()),
6085                     "s1", "s2", "s3");
6086             assertShortcutIds(assertAllPinned(mManager.getPinnedShortcuts()),
6087                     "s1", "s2", "s3", "s4");
6088         });
6089         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
6090             assertShortcutIds(assertAllDynamic(mManager.getDynamicShortcuts()),
6091                     "s1", "s2", "s3");
6092             assertShortcutIds(assertAllPinned(mManager.getPinnedShortcuts()),
6093                     "s1", "s2", "s3", "s4", "s5");
6094         });
6095         runWithCaller(CALLING_PACKAGE_3, USER_0, () -> {
6096             assertShortcutIds(assertAllDynamic(mManager.getDynamicShortcuts()),
6097                     "s1", "s2", "s3");
6098             assertShortcutIds(assertAllPinned(mManager.getPinnedShortcuts()),
6099                     "s1", "s2", "s3", "s4", "s5", "s6");
6100         });
6101         runWithCaller(CALLING_PACKAGE_4, USER_0, () -> {
6102             assertShortcutIds(assertAllDynamic(mManager.getDynamicShortcuts())
6103                     /* empty */);
6104             assertShortcutIds(assertAllPinned(mManager.getPinnedShortcuts())
6105                     /* empty */);
6106         });
6107         runWithCaller(CALLING_PACKAGE_1, USER_P0, () -> {
6108             assertShortcutIds(assertAllDynamic(mManager.getDynamicShortcuts()),
6109                     "s1", "s2", "s3");
6110             assertShortcutIds(assertAllPinned(mManager.getPinnedShortcuts()),
6111                     "s1", "s2", "s3", "s4", "s5", "s6");
6112         });
6113         runWithCaller(CALLING_PACKAGE_2, USER_P0, () -> {
6114             assertShortcutIds(assertAllDynamic(mManager.getDynamicShortcuts())
6115                     /* empty */);
6116             assertShortcutIds(assertAllPinned(mManager.getPinnedShortcuts())
6117                     /* empty */);
6118         });
6119         runWithCaller(CALLING_PACKAGE_1, USER_10, () -> {
6120             assertShortcutIds(assertAllDynamic(mManager.getDynamicShortcuts()),
6121                     "x1", "x2", "x3");
6122             assertShortcutIds(assertAllPinned(mManager.getPinnedShortcuts()),
6123                     "x4", "x5");
6124         });
6125         runWithCaller(LAUNCHER_1, USER_0, () -> {
6126             assertShortcutIds(
6127                     mLauncherApps.getShortcuts(buildPinnedQuery(CALLING_PACKAGE_1), HANDLE_USER_0),
6128                     "s1");
6129             assertShortcutIds(
6130                     mLauncherApps.getShortcuts(buildPinnedQuery(CALLING_PACKAGE_2), HANDLE_USER_0),
6131                     "s1", "s2");
6132             assertShortcutIds(
6133                     mLauncherApps.getShortcuts(buildPinnedQuery(CALLING_PACKAGE_3), HANDLE_USER_0),
6134                     "s1", "s2", "s3");
6135             assertShortcutIds(
6136                     mLauncherApps.getShortcuts(buildPinnedQuery(CALLING_PACKAGE_4), HANDLE_USER_0)
6137                     /* empty */);
6138             assertShortcutIds(
6139                     mLauncherApps.getShortcuts(buildPinnedQuery(CALLING_PACKAGE_1), HANDLE_USER_P0),
6140                     "s1", "s4");
6141             assertShortcutIds(
6142                     mLauncherApps.getShortcuts(buildPinnedQuery(CALLING_PACKAGE_2), HANDLE_USER_P0)
6143                     /* empty */);
6144             assertExpectException(
6145                     SecurityException.class, "", () -> {
6146                         mLauncherApps.getShortcuts(
6147                                 buildAllQuery(CALLING_PACKAGE_1), HANDLE_USER_10);
6148                     });
6149         });
6150         runWithCaller(LAUNCHER_2, USER_0, () -> {
6151             assertShortcutIds(
6152                     mLauncherApps.getShortcuts(buildPinnedQuery(CALLING_PACKAGE_1), HANDLE_USER_0),
6153                     "s2");
6154             assertShortcutIds(
6155                     mLauncherApps.getShortcuts(buildPinnedQuery(CALLING_PACKAGE_2), HANDLE_USER_0),
6156                     "s2", "s3");
6157             assertShortcutIds(
6158                     mLauncherApps.getShortcuts(buildPinnedQuery(CALLING_PACKAGE_3), HANDLE_USER_0),
6159                     "s2", "s3", "s4");
6160             assertShortcutIds(
6161                     mLauncherApps.getShortcuts(buildPinnedQuery(CALLING_PACKAGE_4), HANDLE_USER_0)
6162                     /* empty */);
6163             assertShortcutIds(
6164                     mLauncherApps.getShortcuts(buildPinnedQuery(CALLING_PACKAGE_1), HANDLE_USER_P0),
6165                     "s2", "s5");
6166             assertShortcutIds(
6167                     mLauncherApps.getShortcuts(buildPinnedQuery(CALLING_PACKAGE_2), HANDLE_USER_P0)
6168                     /* empty */);
6169         });
6170         runWithCaller(LAUNCHER_3, USER_0, () -> {
6171             assertShortcutIds(
6172                     mLauncherApps.getShortcuts(buildPinnedQuery(CALLING_PACKAGE_1), HANDLE_USER_0),
6173                     "s3");
6174             assertShortcutIds(
6175                     mLauncherApps.getShortcuts(buildPinnedQuery(CALLING_PACKAGE_2), HANDLE_USER_0),
6176                     "s3", "s4");
6177             assertShortcutIds(
6178                     mLauncherApps.getShortcuts(buildPinnedQuery(CALLING_PACKAGE_3), HANDLE_USER_0),
6179                     "s3", "s4", "s5");
6180             assertShortcutIds(
6181                     mLauncherApps.getShortcuts(buildPinnedQuery(CALLING_PACKAGE_4), HANDLE_USER_0)
6182                     /* empty */);
6183             assertShortcutIds(
6184                     mLauncherApps.getShortcuts(buildPinnedQuery(CALLING_PACKAGE_1), HANDLE_USER_P0),
6185                     "s3", "s6");
6186             assertShortcutIds(
6187                     mLauncherApps.getShortcuts(buildPinnedQuery(CALLING_PACKAGE_2), HANDLE_USER_P0)
6188                     /* empty */);
6189         });
6190         runWithCaller(LAUNCHER_4, USER_0, () -> {
6191             assertShortcutIds(
6192                     mLauncherApps.getShortcuts(buildPinnedQuery(CALLING_PACKAGE_1), HANDLE_USER_0)
6193                     /* empty */);
6194             assertShortcutIds(
6195                     mLauncherApps.getShortcuts(buildPinnedQuery(CALLING_PACKAGE_2), HANDLE_USER_0)
6196                     /* empty */);
6197             assertShortcutIds(
6198                     mLauncherApps.getShortcuts(buildPinnedQuery(CALLING_PACKAGE_3), HANDLE_USER_0)
6199                     /* empty */);
6200             assertShortcutIds(
6201                     mLauncherApps.getShortcuts(buildPinnedQuery(CALLING_PACKAGE_4), HANDLE_USER_0)
6202                     /* empty */);
6203             assertShortcutIds(
6204                     mLauncherApps.getShortcuts(buildPinnedQuery(CALLING_PACKAGE_1), HANDLE_USER_P0)
6205                     /* empty */);
6206             assertShortcutIds(
6207                     mLauncherApps.getShortcuts(buildPinnedQuery(CALLING_PACKAGE_2), HANDLE_USER_P0)
6208                     /* empty */);
6209         });
6210         runWithCaller(LAUNCHER_1, USER_P0, () -> {
6211             assertShortcutIds(
6212                     mLauncherApps.getShortcuts(buildPinnedQuery(CALLING_PACKAGE_1), HANDLE_USER_0),
6213                     "s3", "s4");
6214             assertShortcutIds(
6215                     mLauncherApps.getShortcuts(buildPinnedQuery(CALLING_PACKAGE_2), HANDLE_USER_0),
6216                     "s3", "s4", "s5");
6217             assertShortcutIds(
6218                     mLauncherApps.getShortcuts(buildPinnedQuery(CALLING_PACKAGE_3), HANDLE_USER_0),
6219                     "s3", "s4", "s5", "s6");
6220             assertShortcutIds(
6221                     mLauncherApps.getShortcuts(buildPinnedQuery(CALLING_PACKAGE_1), HANDLE_USER_P0),
6222                     "s1", "s4");
6223             assertExpectException(
6224                     SecurityException.class, "unrelated profile", () -> {
6225                         mLauncherApps.getShortcuts(
6226                                 buildAllQuery(CALLING_PACKAGE_1), HANDLE_USER_10);
6227                     });
6228         });
6229         runWithCaller(LAUNCHER_1, USER_10, () -> {
6230             assertShortcutIds(
6231                     mLauncherApps.getShortcuts(buildPinnedQuery(CALLING_PACKAGE_1), HANDLE_USER_10),
6232                     "x4", "x5");
6233             assertShortcutIds(
6234                     mLauncherApps.getShortcuts(buildPinnedQuery(CALLING_PACKAGE_2), HANDLE_USER_10)
6235                     /* empty */);
6236             assertShortcutIds(
6237                     mLauncherApps.getShortcuts(buildPinnedQuery(CALLING_PACKAGE_3), HANDLE_USER_10)
6238                     /* empty */);
6239             assertExpectException(
6240                     SecurityException.class, "unrelated profile", () -> {
6241                         mLauncherApps.getShortcuts(
6242                                 buildAllQuery(CALLING_PACKAGE_1), HANDLE_USER_0);
6243                     });
6244             assertExpectException(
6245                     SecurityException.class, "unrelated profile", () -> {
6246                         mLauncherApps.getShortcuts(
6247                                 buildAllQuery(CALLING_PACKAGE_1), HANDLE_USER_P0);
6248                     });
6249         });
6250         // Check the user-IDs.
6251         assertEquals(USER_0,
6252                 mService.getUserShortcutsLocked(USER_0).getPackageShortcuts(CALLING_PACKAGE_1)
6253                         .getOwnerUserId());
6254         assertEquals(USER_0,
6255                 mService.getUserShortcutsLocked(USER_0).getPackageShortcuts(CALLING_PACKAGE_1)
6256                         .getPackageUserId());
6257         assertEquals(USER_P0,
6258                 mService.getUserShortcutsLocked(USER_P0).getPackageShortcuts(CALLING_PACKAGE_1)
6259                         .getOwnerUserId());
6260         assertEquals(USER_P0,
6261                 mService.getUserShortcutsLocked(USER_P0).getPackageShortcuts(CALLING_PACKAGE_1)
6262                         .getPackageUserId());
6263 
6264         assertEquals(USER_0,
6265                 mService.getUserShortcutsLocked(USER_0).getLauncherShortcuts(LAUNCHER_1, USER_0)
6266                         .getOwnerUserId());
6267         assertEquals(USER_0,
6268                 mService.getUserShortcutsLocked(USER_0).getLauncherShortcuts(LAUNCHER_1, USER_0)
6269                         .getPackageUserId());
6270         assertEquals(USER_P0,
6271                 mService.getUserShortcutsLocked(USER_P0).getLauncherShortcuts(LAUNCHER_1, USER_0)
6272                         .getOwnerUserId());
6273         assertEquals(USER_0,
6274                 mService.getUserShortcutsLocked(USER_P0).getLauncherShortcuts(LAUNCHER_1, USER_0)
6275                         .getPackageUserId());
6276     }
6277 
testOnApplicationActive_permission()6278     public void testOnApplicationActive_permission() {
6279         assertExpectException(SecurityException.class, "Missing permission", () ->
6280                 mManager.onApplicationActive(CALLING_PACKAGE_1, USER_0));
6281 
6282         // Has permission, now it should pass.
6283         mCallerPermissions.add(permission.RESET_SHORTCUT_MANAGER_THROTTLING);
6284         mManager.onApplicationActive(CALLING_PACKAGE_1, USER_0);
6285     }
6286 
testGetShareTargets_permission()6287     public void testGetShareTargets_permission() {
6288         IntentFilter filter = new IntentFilter();
6289 
6290         assertExpectException(SecurityException.class, "Missing permission", () ->
6291                 mManager.getShareTargets(filter));
6292 
6293         // Has permission, now it should pass.
6294         mCallerPermissions.add(permission.MANAGE_APP_PREDICTIONS);
6295         mManager.getShareTargets(filter);
6296     }
6297 
testHasShareTargets_permission()6298     public void testHasShareTargets_permission() {
6299         assertExpectException(SecurityException.class, "Missing permission", () ->
6300                 mManager.hasShareTargets(CALLING_PACKAGE_1));
6301 
6302         // Has permission, now it should pass.
6303         mCallerPermissions.add(permission.MANAGE_APP_PREDICTIONS);
6304         mManager.hasShareTargets(CALLING_PACKAGE_1);
6305     }
6306 
testDumpsys_crossProfile()6307     public void testDumpsys_crossProfile() {
6308         prepareCrossProfileDataSet();
6309         dumpsysOnLogcat("test1", /* force= */ true);
6310     }
6311 
testDumpsys_withIcons()6312     public void testDumpsys_withIcons() throws IOException {
6313         testIcons();
6314         // Dump after having some icons.
6315         dumpsysOnLogcat("test1", /* force= */ true);
6316     }
6317 
testManifestShortcut_publishOnUnlockUser()6318     public void testManifestShortcut_publishOnUnlockUser() {
6319         addManifestShortcutResource(
6320                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
6321                 R.xml.shortcut_1);
6322         addManifestShortcutResource(
6323                 new ComponentName(CALLING_PACKAGE_2, ShortcutActivity.class.getName()),
6324                 R.xml.shortcut_2);
6325         addManifestShortcutResource(
6326                 new ComponentName(CALLING_PACKAGE_3, ShortcutActivity.class.getName()),
6327                 R.xml.shortcut_5);
6328 
6329         // Unlock user-0.
6330         mInjectedCurrentTimeMillis += 100;
6331         mService.handleUnlockUser(USER_0);
6332 
6333         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
6334             assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
6335                     mManager.getManifestShortcuts()))),
6336                     "ms1");
6337             assertEmpty(mManager.getPinnedShortcuts());
6338         });
6339 
6340         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
6341             assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
6342                     mManager.getManifestShortcuts()))),
6343                     "ms1", "ms2");
6344             assertEmpty(mManager.getPinnedShortcuts());
6345         });
6346 
6347         runWithCaller(CALLING_PACKAGE_3, USER_0, () -> {
6348             assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
6349                     mManager.getManifestShortcuts()))),
6350                     "ms1", "ms2", "ms3", "ms4", "ms5");
6351             assertEmpty(mManager.getPinnedShortcuts());
6352         });
6353 
6354         // Try on another user, with some packages uninstalled.
6355         mRunningUsers.put(USER_10, true);
6356 
6357         uninstallPackage(USER_10, CALLING_PACKAGE_1);
6358         uninstallPackage(USER_10, CALLING_PACKAGE_3);
6359 
6360         mInjectedCurrentTimeMillis += 100;
6361         mService.handleUnlockUser(USER_10);
6362 
6363         runWithCaller(CALLING_PACKAGE_1, USER_10, () -> {
6364             assertEmpty(mManager.getManifestShortcuts());
6365             assertEmpty(mManager.getPinnedShortcuts());
6366         });
6367 
6368         runWithCaller(CALLING_PACKAGE_2, USER_10, () -> {
6369             assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
6370                     mManager.getManifestShortcuts()))),
6371                     "ms1", "ms2");
6372             assertEmpty(mManager.getPinnedShortcuts());
6373         });
6374 
6375         runWithCaller(CALLING_PACKAGE_3, USER_10, () -> {
6376             assertEmpty(mManager.getManifestShortcuts());
6377             assertEmpty(mManager.getPinnedShortcuts());
6378         });
6379 
6380         // Now change the resources for package 1, and unlock again.
6381         // But we still see *old* shortcuts, because the package version and install time
6382         // hasn't changed.
6383         shutdownServices();
6384 
6385         mInjectedCurrentTimeMillis += 100;
6386 
6387         addManifestShortcutResource(
6388                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
6389                 R.xml.shortcut_5);
6390         addManifestShortcutResource(
6391                 new ComponentName(CALLING_PACKAGE_3, ShortcutActivity.class.getName()),
6392                 R.xml.shortcut_1);
6393 
6394         initService();
6395         mService.handleUnlockUser(USER_0);
6396 
6397         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
6398             assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled( // FAIL
6399                     mManager.getManifestShortcuts()))),
6400                     "ms1");
6401             assertEmpty(mManager.getPinnedShortcuts());
6402         });
6403 
6404         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
6405             assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
6406                     mManager.getManifestShortcuts()))),
6407                     "ms1", "ms2");
6408             assertEmpty(mManager.getPinnedShortcuts());
6409         });
6410 
6411         runWithCaller(CALLING_PACKAGE_3, USER_0, () -> {
6412             assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
6413                     mManager.getManifestShortcuts()))),
6414                     "ms1", "ms2", "ms3", "ms4", "ms5");
6415             assertEmpty(mManager.getPinnedShortcuts());
6416         });
6417 
6418         // Do it again, but this time we change the app version, so we do detect the changes.
6419         shutdownServices();
6420 
6421         mInjectedCurrentTimeMillis += 100;
6422 
6423         updatePackageVersion(CALLING_PACKAGE_1, 1);
6424         updatePackageLastUpdateTime(CALLING_PACKAGE_3, 1);
6425 
6426         initService();
6427         mService.handleUnlockUser(USER_0);
6428 
6429         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
6430             assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
6431                     mManager.getManifestShortcuts()))),
6432                     "ms1", "ms2", "ms3", "ms4", "ms5");
6433             assertEmpty(mManager.getPinnedShortcuts());
6434         });
6435 
6436         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
6437             assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
6438                     mManager.getManifestShortcuts()))),
6439                     "ms1", "ms2");
6440             assertEmpty(mManager.getPinnedShortcuts());
6441         });
6442 
6443         runWithCaller(CALLING_PACKAGE_3, USER_0, () -> {
6444             assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
6445                     mManager.getManifestShortcuts()))),
6446                     "ms1");
6447             assertEmpty(mManager.getPinnedShortcuts());
6448         });
6449 
6450         // Next, try removing all shortcuts, with some of them pinned.
6451         runWithCaller(LAUNCHER_1, USER_0, () -> {
6452             mLauncherApps.pinShortcuts(CALLING_PACKAGE_1, list("ms3"), HANDLE_USER_0);
6453             mLauncherApps.pinShortcuts(CALLING_PACKAGE_2, list("ms2"), HANDLE_USER_0);
6454             mLauncherApps.pinShortcuts(CALLING_PACKAGE_3, list("ms1"), HANDLE_USER_0);
6455         });
6456         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
6457             assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
6458                     mManager.getManifestShortcuts()))),
6459                     "ms1", "ms2", "ms3", "ms4", "ms5");
6460             assertShortcutIds(assertAllImmutable(assertAllPinned(assertAllManifest(
6461                     assertAllEnabled(mManager.getPinnedShortcuts())))),
6462                     "ms3");
6463         });
6464 
6465         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
6466             assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
6467                     mManager.getManifestShortcuts()))),
6468                     "ms1", "ms2");
6469             assertShortcutIds(assertAllImmutable(assertAllPinned(assertAllManifest(
6470                     assertAllEnabled(mManager.getPinnedShortcuts())))),
6471                     "ms2");
6472         });
6473 
6474         runWithCaller(CALLING_PACKAGE_3, USER_0, () -> {
6475             assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
6476                     mManager.getManifestShortcuts()))),
6477                     "ms1");
6478             assertShortcutIds(assertAllImmutable(assertAllPinned(assertAllManifest(
6479                     assertAllEnabled(mManager.getPinnedShortcuts())))),
6480                     "ms1");
6481         });
6482 
6483         shutdownServices();
6484 
6485         mInjectedCurrentTimeMillis += 100;
6486 
6487         addManifestShortcutResource(
6488                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
6489                 R.xml.shortcut_0);
6490         addManifestShortcutResource(
6491                 new ComponentName(CALLING_PACKAGE_2, ShortcutActivity.class.getName()),
6492                 R.xml.shortcut_1);
6493         addManifestShortcutResource(
6494                 new ComponentName(CALLING_PACKAGE_3, ShortcutActivity.class.getName()),
6495                 R.xml.shortcut_0);
6496 
6497         updatePackageVersion(CALLING_PACKAGE_1, 1);
6498         updatePackageVersion(CALLING_PACKAGE_2, 1);
6499         updatePackageVersion(CALLING_PACKAGE_3, 1);
6500 
6501         initService();
6502         mService.handleUnlockUser(USER_0);
6503 
6504         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
6505             assertEmpty(mManager.getManifestShortcuts());
6506             assertShortcutIds(assertAllImmutable(assertAllPinned(assertAllNotManifest(
6507                     assertAllDisabled(mManager.getPinnedShortcuts())))),
6508                     "ms3");
6509         });
6510 
6511         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
6512             assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
6513                     mManager.getManifestShortcuts()))),
6514                     "ms1");
6515             assertShortcutIds(assertAllImmutable(assertAllPinned(assertAllNotManifest(
6516                     assertAllDisabled(mManager.getPinnedShortcuts())))),
6517                     "ms2");
6518         });
6519 
6520         runWithCaller(CALLING_PACKAGE_3, USER_0, () -> {
6521             assertEmpty(mManager.getManifestShortcuts());
6522             assertShortcutIds(assertAllImmutable(assertAllPinned(assertAllNotManifest(
6523                     assertAllDisabled(mManager.getPinnedShortcuts())))),
6524                     "ms1");
6525         });
6526 
6527         // Make sure we don't have ShortcutPackage for packages that don't have shortcuts.
6528         assertNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_4, USER_0));
6529         assertNull(mService.getPackageShortcutForTest(LAUNCHER_1, USER_0));
6530     }
6531 
testManifestShortcut_publishOnBroadcast()6532     public void testManifestShortcut_publishOnBroadcast() {
6533         // First, no packages are installed.
6534         uninstallPackage(USER_0, CALLING_PACKAGE_1);
6535         uninstallPackage(USER_0, CALLING_PACKAGE_2);
6536         uninstallPackage(USER_0, CALLING_PACKAGE_3);
6537         uninstallPackage(USER_0, CALLING_PACKAGE_4);
6538         uninstallPackage(USER_10, CALLING_PACKAGE_1);
6539         uninstallPackage(USER_10, CALLING_PACKAGE_2);
6540         uninstallPackage(USER_10, CALLING_PACKAGE_3);
6541         uninstallPackage(USER_10, CALLING_PACKAGE_4);
6542 
6543         mService.handleUnlockUser(USER_0);
6544 
6545         mRunningUsers.put(USER_10, true);
6546         mService.handleUnlockUser(USER_10);
6547 
6548         // Originally no manifest shortcuts.
6549         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
6550             assertEmpty(mManager.getManifestShortcuts());
6551             assertEmpty(mManager.getPinnedShortcuts());
6552         });
6553 
6554         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
6555             assertEmpty(mManager.getManifestShortcuts());
6556             assertEmpty(mManager.getPinnedShortcuts());
6557         });
6558 
6559         runWithCaller(CALLING_PACKAGE_3, USER_0, () -> {
6560             assertEmpty(mManager.getManifestShortcuts());
6561             assertEmpty(mManager.getPinnedShortcuts());
6562         });
6563 
6564         // Package 1 updated, with manifest shortcuts.
6565         addManifestShortcutResource(
6566                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
6567                 R.xml.shortcut_1);
6568         updatePackageVersion(CALLING_PACKAGE_1, 1);
6569                 mService.mPackageMonitor.onReceive(getTestContext(),
6570                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
6571 
6572         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
6573             assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
6574                     mManager.getManifestShortcuts()))),
6575                     "ms1");
6576             assertEmpty(mManager.getPinnedShortcuts());
6577         });
6578 
6579         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
6580             assertEmpty(mManager.getManifestShortcuts());
6581             assertEmpty(mManager.getPinnedShortcuts());
6582         });
6583 
6584         // Package 2 updated, with manifest shortcuts.
6585 
6586         addManifestShortcutResource(
6587                 new ComponentName(CALLING_PACKAGE_2, ShortcutActivity.class.getName()),
6588                 R.xml.shortcut_5_altalt);
6589         updatePackageVersion(CALLING_PACKAGE_2, 1);
6590                 mService.mPackageMonitor.onReceive(getTestContext(),
6591                 genPackageAddIntent(CALLING_PACKAGE_2, USER_0));
6592 
6593         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
6594             assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
6595                     mManager.getManifestShortcuts()))),
6596                     "ms1");
6597             assertEmpty(mManager.getPinnedShortcuts());
6598         });
6599 
6600         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
6601             assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
6602                     mManager.getManifestShortcuts()))),
6603                     "ms1", "ms2", "ms3", "ms4", "ms5");
6604             assertWith(getCallerShortcuts()).selectManifest()
6605                     .selectByActivity(
6606                             new ComponentName(CALLING_PACKAGE_2, ShortcutActivity.class.getName()))
6607                     .haveRanksInOrder("ms1", "ms2", "ms3", "ms4", "ms5");
6608             assertEmpty(mManager.getPinnedShortcuts());
6609         });
6610 
6611         // Package 2 updated, with less manifest shortcuts.
6612         // This time we use updatePackageLastUpdateTime() instead of updatePackageVersion().
6613 
6614         dumpsysOnLogcat("Before pinning");
6615 
6616         // Also pin some.
6617         runWithCaller(LAUNCHER_1, USER_0, () -> {
6618             mLauncherApps.pinShortcuts(CALLING_PACKAGE_2, list("ms2", "ms3"), HANDLE_USER_0);
6619         });
6620 
6621         dumpsysOnLogcat("After pinning");
6622 
6623         addManifestShortcutResource(
6624                 new ComponentName(CALLING_PACKAGE_2, ShortcutActivity.class.getName()),
6625                 R.xml.shortcut_2);
6626         updatePackageLastUpdateTime(CALLING_PACKAGE_2, 1);
6627                 mService.mPackageMonitor.onReceive(getTestContext(),
6628                 genPackageAddIntent(CALLING_PACKAGE_2, USER_0));
6629 
6630         dumpsysOnLogcat("After updating package 2");
6631 
6632         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
6633             assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
6634                     mManager.getManifestShortcuts()))),
6635                     "ms1");
6636             assertEmpty(mManager.getPinnedShortcuts());
6637         });
6638 
6639         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
6640             assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
6641                     mManager.getManifestShortcuts()))),
6642                     "ms1", "ms2");
6643             assertWith(getCallerShortcuts()).selectManifest()
6644                     .selectByActivity(
6645                             new ComponentName(CALLING_PACKAGE_2, ShortcutActivity.class.getName()))
6646                     .haveRanksInOrder("ms1", "ms2");
6647             assertShortcutIds(assertAllImmutable(assertAllPinned(
6648                     mManager.getPinnedShortcuts())),
6649                     "ms2", "ms3");
6650             // ms3 is no longer in manifest, so should be disabled.
6651             // but ms1 and ms2 should be enabled.
6652             assertWith(getCallerShortcuts())
6653                     .selectByIds("ms1", "ms2")
6654                     .areAllEnabled()
6655 
6656                     .revertToOriginalList()
6657                     .selectByIds("ms3")
6658                     .areAllDisabled()
6659                     .areAllWithDisabledReason(ShortcutInfo.DISABLED_REASON_APP_CHANGED);
6660         });
6661 
6662         // Make sure the launcher see the correct disabled reason.
6663         runWithCaller(LAUNCHER_1, USER_0, () -> {
6664             assertWith(getShortcutAsLauncher(USER_0))
6665                     .forShortcutWithId("ms3", si -> {
6666                         assertEquals("string-com.android.test.2-user:0-res:"
6667                                         + R.string.shortcut_disabled_message3 + "/en",
6668                                 si.getDisabledMessage());
6669                     });
6670         });
6671 
6672 
6673         // Package 2 on user 10 has no shortcuts yet.
6674         runWithCaller(CALLING_PACKAGE_2, USER_10, () -> {
6675             assertEmpty(mManager.getManifestShortcuts());
6676             assertEmpty(mManager.getPinnedShortcuts());
6677         });
6678         // Send add broadcast, but the user is not running, so should be ignored.
6679         mService.handleStopUser(USER_10);
6680         mRunningUsers.put(USER_10, false);
6681         mUnlockedUsers.put(USER_10, false);
6682 
6683         mService.mPackageMonitor.onReceive(getTestContext(),
6684                 genPackageAddIntent(CALLING_PACKAGE_2, USER_10));
6685         runWithCaller(CALLING_PACKAGE_2, USER_10, () -> {
6686             // Don't use the mManager APIs to get shortcuts, because they'll trigger the package
6687             // update check.
6688             // So look the internal data directly using getCallerShortcuts().
6689             assertEmpty(getCallerShortcuts());
6690         });
6691 
6692         // Try again, but the user is locked, so still ignored.
6693         mRunningUsers.put(USER_10, true);
6694                 mService.mPackageMonitor.onReceive(getTestContext(),
6695                 genPackageAddIntent(CALLING_PACKAGE_2, USER_10));
6696         runWithCaller(CALLING_PACKAGE_2, USER_10, () -> {
6697             // Don't use the mManager APIs to get shortcuts, because they'll trigger the package
6698             // update check.
6699             // So look the internal data directly using getCallerShortcuts().
6700             assertEmpty(getCallerShortcuts());
6701         });
6702 
6703         // Unlock the user, now it should work.
6704         mUnlockedUsers.put(USER_10, true);
6705 
6706         // Send PACKAGE_ADD broadcast to have Package 2 on user-10 publish manifest shortcuts.
6707                 mService.mPackageMonitor.onReceive(getTestContext(),
6708                 genPackageAddIntent(CALLING_PACKAGE_2, USER_10));
6709 
6710         runWithCaller(CALLING_PACKAGE_2, USER_10, () -> {
6711             assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
6712                     mManager.getManifestShortcuts()))),
6713                     "ms1", "ms2");
6714             assertWith(getCallerShortcuts()).selectManifest()
6715                     .selectByActivity(
6716                             new ComponentName(CALLING_PACKAGE_2, ShortcutActivity.class.getName()))
6717                     .haveRanksInOrder("ms1", "ms2");
6718             assertEmpty(mManager.getPinnedShortcuts());
6719         });
6720 
6721         // But it shouldn't affect user-0.
6722         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
6723             assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
6724                     mManager.getManifestShortcuts()))),
6725                     "ms1", "ms2");
6726             assertWith(getCallerShortcuts()).selectManifest()
6727                     .selectByActivity(
6728                             new ComponentName(CALLING_PACKAGE_2, ShortcutActivity.class.getName()))
6729                     .haveRanksInOrder("ms1", "ms2");
6730             assertShortcutIds(assertAllImmutable(assertAllPinned(
6731                     mManager.getPinnedShortcuts())),
6732                     "ms2", "ms3");
6733             assertAllEnabled(list(getCallerShortcut("ms1")));
6734             assertAllEnabled(list(getCallerShortcut("ms2")));
6735             assertAllDisabled(list(getCallerShortcut("ms3")));
6736         });
6737 
6738         // Multiple activities.
6739         // Add shortcuts on activity 2 for package 2.
6740         addManifestShortcutResource(
6741                 new ComponentName(CALLING_PACKAGE_2, ShortcutActivity.class.getName()),
6742                 R.xml.shortcut_5_alt);
6743         addManifestShortcutResource(
6744                 new ComponentName(CALLING_PACKAGE_2, ShortcutActivity2.class.getName()),
6745                 R.xml.shortcut_5_reverse);
6746 
6747         updatePackageLastUpdateTime(CALLING_PACKAGE_2, 1);
6748                 mService.mPackageMonitor.onReceive(getTestContext(),
6749                 genPackageAddIntent(CALLING_PACKAGE_2, USER_0));
6750 
6751         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
6752             assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
6753                     mManager.getManifestShortcuts()))),
6754                     "ms1", "ms2", "ms3", "ms4", "ms5",
6755                     "ms1_alt", "ms2_alt", "ms3_alt", "ms4_alt", "ms5_alt");
6756 
6757             // Make sure they have the correct ranks, regardless of their ID's alphabetical order.
6758             assertWith(getCallerShortcuts()).selectManifest()
6759                     .selectByActivity(
6760                             new ComponentName(CALLING_PACKAGE_2, ShortcutActivity.class.getName()))
6761                     .haveRanksInOrder("ms1_alt", "ms2_alt", "ms3_alt", "ms4_alt", "ms5_alt");
6762             assertWith(getCallerShortcuts()).selectManifest()
6763                     .selectByActivity(
6764                             new ComponentName(CALLING_PACKAGE_2, ShortcutActivity2.class.getName()))
6765                     .haveRanksInOrder("ms5", "ms4", "ms3", "ms2", "ms1");
6766         });
6767 
6768         // Package 2 now has no manifest shortcuts.
6769         addManifestShortcutResource(
6770                 new ComponentName(CALLING_PACKAGE_2, ShortcutActivity.class.getName()),
6771                 R.xml.shortcut_0);
6772         addManifestShortcutResource(
6773                 new ComponentName(CALLING_PACKAGE_2, ShortcutActivity2.class.getName()),
6774                 R.xml.shortcut_0);
6775         updatePackageLastUpdateTime(CALLING_PACKAGE_2, 1);
6776                 mService.mPackageMonitor.onReceive(getTestContext(),
6777                 genPackageAddIntent(CALLING_PACKAGE_2, USER_0));
6778 
6779         // No manifest shortcuts, and pinned ones are disabled.
6780         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
6781             assertEmpty(mManager.getManifestShortcuts());
6782             assertShortcutIds(assertAllImmutable(assertAllPinned(assertAllDisabled(
6783                     mManager.getPinnedShortcuts()))),
6784                     "ms2", "ms3");
6785         });
6786     }
6787 
testManifestShortcuts_missingMandatoryFields()6788     public void testManifestShortcuts_missingMandatoryFields() {
6789         // Start with no apps installed.
6790         uninstallPackage(USER_0, CALLING_PACKAGE_1);
6791         uninstallPackage(USER_0, CALLING_PACKAGE_2);
6792         uninstallPackage(USER_0, CALLING_PACKAGE_3);
6793         uninstallPackage(USER_0, CALLING_PACKAGE_4);
6794 
6795         mService.handleUnlockUser(USER_0);
6796 
6797         // Make sure no manifest shortcuts.
6798         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
6799             assertEmpty(mManager.getManifestShortcuts());
6800         });
6801 
6802         // Package 1 updated, which has one valid manifest shortcut and one invalid.
6803         addManifestShortcutResource(
6804                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
6805                 R.xml.shortcut_error_1);
6806         updatePackageVersion(CALLING_PACKAGE_1, 1);
6807                 mService.mPackageMonitor.onReceive(getTestContext(),
6808                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
6809 
6810         // Only the valid one is published.
6811         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
6812             assertWith(getCallerShortcuts())
6813                     .areAllManifest()
6814                     .areAllImmutable()
6815                     .areAllEnabled()
6816                     .haveIds("x1");
6817         });
6818 
6819         // Package 1 updated, which has one valid manifest shortcut and one invalid.
6820         addManifestShortcutResource(
6821                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
6822                 R.xml.shortcut_error_2);
6823         updatePackageVersion(CALLING_PACKAGE_1, 1);
6824                 mService.mPackageMonitor.onReceive(getTestContext(),
6825                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
6826 
6827         // Only the valid one is published.
6828         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
6829             assertWith(getCallerShortcuts())
6830                     .areAllManifest()
6831                     .areAllImmutable()
6832                     .areAllEnabled()
6833                     .haveIds("x2");
6834         });
6835 
6836         // Package 1 updated, which has one valid manifest shortcut and one invalid.
6837         addManifestShortcutResource(
6838                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
6839                 R.xml.shortcut_error_3);
6840         updatePackageVersion(CALLING_PACKAGE_1, 1);
6841                 mService.mPackageMonitor.onReceive(getTestContext(),
6842                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
6843 
6844         // Only the valid one is published.
6845         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
6846             assertWith(getCallerShortcuts())
6847                     .areAllManifest()
6848                     .areAllImmutable()
6849                     .areAllEnabled()
6850                     .haveIds("x3")
6851                     .forShortcutWithId("x3", si -> {
6852                         assertEquals(set("cat2"), si.getCategories());
6853                      });
6854         });
6855     }
6856 
testManifestShortcuts_intentDefinitions()6857     public void testManifestShortcuts_intentDefinitions() {
6858         addManifestShortcutResource(
6859                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
6860                 R.xml.shortcut_error_4);
6861         updatePackageVersion(CALLING_PACKAGE_1, 1);
6862                 mService.mPackageMonitor.onReceive(getTestContext(),
6863                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
6864 
6865         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
6866             // Make sure invalid ones are not published.
6867             // Note that at this point disabled ones don't show up because they weren't pinned.
6868             assertWith(getCallerShortcuts())
6869                     .haveIds("ms1", "ms2")
6870                     .areAllManifest()
6871                     .areAllNotDynamic()
6872                     .areAllNotPinned()
6873                     .areAllImmutable()
6874                     .areAllEnabled()
6875                     .forShortcutWithId("ms1", si -> {
6876                         assertTrue(si.isEnabled());
6877                         assertEquals(1, si.getIntents().length);
6878 
6879                         assertEquals("action1", si.getIntent().getAction());
6880                         assertEquals("value1", si.getIntent().getStringExtra("key1"));
6881                         assertEquals(Intent.FLAG_ACTIVITY_NEW_TASK |
6882                                 Intent.FLAG_ACTIVITY_CLEAR_TASK |
6883                                 Intent.FLAG_ACTIVITY_TASK_ON_HOME, si.getIntent().getFlags());
6884 
6885                         assertEquals("action1", si.getIntents()[0].getAction());
6886                         assertEquals("value1", si.getIntents()[0].getStringExtra("key1"));
6887                         assertEquals(Intent.FLAG_ACTIVITY_NEW_TASK |
6888                                 Intent.FLAG_ACTIVITY_CLEAR_TASK |
6889                                 Intent.FLAG_ACTIVITY_TASK_ON_HOME, si.getIntents()[0].getFlags());
6890                     })
6891                     .forShortcutWithId("ms2", si -> {
6892                         assertTrue(si.isEnabled());
6893                         assertEquals(2, si.getIntents().length);
6894 
6895                         // getIntent will return the last one.
6896                         assertEquals("action2_2", si.getIntent().getAction());
6897                         assertEquals("value2", si.getIntent().getStringExtra("key2"));
6898                         assertEquals(0, si.getIntent().getFlags());
6899 
6900                         final Intent i1 = si.getIntents()[0];
6901                         final Intent i2 = si.getIntents()[1];
6902 
6903                         assertEquals("action2_1", i1.getAction());
6904                         assertEquals("value1", i1.getStringExtra("key1"));
6905                         assertEquals(Intent.FLAG_ACTIVITY_NEW_TASK |
6906                                         Intent.FLAG_ACTIVITY_CLEAR_TASK |
6907                                         Intent.FLAG_ACTIVITY_TASK_ON_HOME, i1.getFlags());
6908 
6909                         assertEquals("action2_2", i2.getAction());
6910                         assertEquals("value2", i2.getStringExtra("key2"));
6911                         assertEquals(0, i2.getFlags());
6912                     });
6913         });
6914 
6915         // Publish 5 enabled to pin some, so we can later test disabled manfiest shortcuts..
6916         addManifestShortcutResource(
6917                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
6918                 R.xml.shortcut_5);
6919         updatePackageVersion(CALLING_PACKAGE_1, 1);
6920                 mService.mPackageMonitor.onReceive(getTestContext(),
6921                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
6922 
6923         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
6924             // Make sure 5 manifest shortcuts are published.
6925             assertWith(getCallerShortcuts())
6926                     .haveIds("ms1", "ms2", "ms3", "ms4", "ms5")
6927                     .areAllManifest()
6928                     .areAllNotDynamic()
6929                     .areAllNotPinned()
6930                     .areAllImmutable()
6931                     .areAllEnabled();
6932         });
6933 
6934         runWithCaller(LAUNCHER_1, USER_0, () -> {
6935             mLauncherApps.pinShortcuts(CALLING_PACKAGE_1,
6936                     list("ms3", "ms4", "ms5"), HANDLE_USER_0);
6937         });
6938 
6939         // Make sure they're pinned.
6940         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
6941             assertWith(getCallerShortcuts())
6942                     .haveIds("ms1", "ms2", "ms3", "ms4", "ms5")
6943                     .selectByIds("ms1", "ms2")
6944                     .areAllNotPinned()
6945                     .areAllEnabled()
6946 
6947                     .revertToOriginalList()
6948                     .selectByIds("ms3", "ms4", "ms5")
6949                     .areAllPinned()
6950                     .areAllEnabled();
6951         });
6952 
6953         // Update the app.
6954         addManifestShortcutResource(
6955                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
6956                 R.xml.shortcut_error_4);
6957         updatePackageVersion(CALLING_PACKAGE_1, 1);
6958                 mService.mPackageMonitor.onReceive(getTestContext(),
6959                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
6960 
6961         // Make sure 3, 4 and 5 still exist but disabled.
6962         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
6963             assertWith(getCallerShortcuts())
6964                     .haveIds("ms1", "ms2", "ms3", "ms4", "ms5")
6965                     .areAllNotDynamic()
6966                     .areAllImmutable()
6967 
6968                     .selectByIds("ms1", "ms2")
6969                     .areAllManifest()
6970                     .areAllNotPinned()
6971                     .areAllEnabled()
6972 
6973                     .revertToOriginalList()
6974                     .selectByIds("ms3", "ms4", "ms5")
6975                     .areAllNotManifest()
6976                     .areAllPinned()
6977                     .areAllDisabled()
6978 
6979                     .revertToOriginalList()
6980                     .forShortcutWithId("ms1", si -> {
6981                         assertEquals(si.getId(), "action1", si.getIntent().getAction());
6982                     })
6983                     .forShortcutWithId("ms2", si -> {
6984                         // getIntent returns the last one.
6985                         assertEquals(si.getId(), "action2_2", si.getIntent().getAction());
6986                     })
6987                     .forShortcutWithId("ms3", si -> {
6988                         assertEquals(si.getId(), Intent.ACTION_VIEW, si.getIntent().getAction());
6989                     })
6990                     .forShortcutWithId("ms4", si -> {
6991                         assertEquals(si.getId(), Intent.ACTION_VIEW, si.getIntent().getAction());
6992                     })
6993                     .forShortcutWithId("ms5", si -> {
6994                         assertEquals(si.getId(), "action", si.getIntent().getAction());
6995                     });
6996         });
6997     }
6998 
testManifestShortcuts_checkAllFields()6999     public void testManifestShortcuts_checkAllFields() {
7000         mService.handleUnlockUser(USER_0);
7001 
7002         // Package 1 updated, which has one valid manifest shortcut and one invalid.
7003         addManifestShortcutResource(
7004                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
7005                 R.xml.shortcut_5);
7006         updatePackageVersion(CALLING_PACKAGE_1, 1);
7007                 mService.mPackageMonitor.onReceive(getTestContext(),
7008                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
7009 
7010         // Only the valid one is published.
7011         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
7012             assertWith(getCallerShortcuts())
7013                     .haveIds("ms1", "ms2", "ms3", "ms4", "ms5")
7014                     .areAllManifest()
7015                     .areAllImmutable()
7016                     .areAllEnabled()
7017                     .areAllNotPinned()
7018                     .areAllNotDynamic()
7019 
7020                     .forShortcutWithId("ms1", si -> {
7021                         assertEquals(R.drawable.icon1, si.getIconResourceId());
7022                         assertEquals(new ComponentName(CALLING_PACKAGE_1,
7023                                 ShortcutActivity.class.getName()),
7024                                 si.getActivity());
7025 
7026                         assertEquals(R.string.shortcut_title1, si.getTitleResId());
7027                         assertEquals("r" + R.string.shortcut_title1, si.getTitleResName());
7028                         assertEquals(R.string.shortcut_text1, si.getTextResId());
7029                         assertEquals("r" + R.string.shortcut_text1, si.getTextResName());
7030                         assertEquals(R.string.shortcut_disabled_message1,
7031                                 si.getDisabledMessageResourceId());
7032                         assertEquals("r" + R.string.shortcut_disabled_message1,
7033                                 si.getDisabledMessageResName());
7034 
7035                         assertEquals(set("android.shortcut.conversation", "android.shortcut.media"),
7036                                 si.getCategories());
7037                         assertEquals("action1", si.getIntent().getAction());
7038                         assertEquals(Uri.parse("http://a.b.c/1"), si.getIntent().getData());
7039                     })
7040 
7041                     .forShortcutWithId("ms2", si -> {
7042                         assertEquals("ms2", si.getId());
7043                         assertEquals(R.drawable.icon2, si.getIconResourceId());
7044 
7045                         assertEquals(R.string.shortcut_title2, si.getTitleResId());
7046                         assertEquals("r" + R.string.shortcut_title2, si.getTitleResName());
7047                         assertEquals(R.string.shortcut_text2, si.getTextResId());
7048                         assertEquals("r" + R.string.shortcut_text2, si.getTextResName());
7049                         assertEquals(R.string.shortcut_disabled_message2,
7050                                 si.getDisabledMessageResourceId());
7051                         assertEquals("r" + R.string.shortcut_disabled_message2,
7052                                 si.getDisabledMessageResName());
7053 
7054                         assertEquals(set("android.shortcut.conversation"), si.getCategories());
7055                         assertEquals("action2", si.getIntent().getAction());
7056                         assertEquals(null, si.getIntent().getData());
7057                     })
7058 
7059                     .forShortcutWithId("ms3", si -> {
7060                         assertEquals(0, si.getIconResourceId());
7061                         assertEquals(R.string.shortcut_title1, si.getTitleResId());
7062                         assertEquals("r" + R.string.shortcut_title1, si.getTitleResName());
7063 
7064                         assertEquals(0, si.getTextResId());
7065                         assertEquals(null, si.getTextResName());
7066                         assertEquals(0, si.getDisabledMessageResourceId());
7067                         assertEquals(null, si.getDisabledMessageResName());
7068 
7069                         assertEmpty(si.getCategories());
7070                         assertEquals("android.intent.action.VIEW", si.getIntent().getAction());
7071                         assertEquals(null, si.getIntent().getData());
7072                     })
7073 
7074                     .forShortcutWithId("ms4", si -> {
7075                         assertEquals(0, si.getIconResourceId());
7076                         assertEquals(R.string.shortcut_title2, si.getTitleResId());
7077                         assertEquals("r" + R.string.shortcut_title2, si.getTitleResName());
7078 
7079                         assertEquals(0, si.getTextResId());
7080                         assertEquals(null, si.getTextResName());
7081                         assertEquals(0, si.getDisabledMessageResourceId());
7082                         assertEquals(null, si.getDisabledMessageResName());
7083 
7084                         assertEquals(set("cat"), si.getCategories());
7085                         assertEquals("android.intent.action.VIEW2", si.getIntent().getAction());
7086                         assertEquals(null, si.getIntent().getData());
7087                     })
7088 
7089                     .forShortcutWithId("ms5", si -> {
7090                         si = getCallerShortcut("ms5");
7091                         assertEquals("action", si.getIntent().getAction());
7092                         assertEquals("http://www/", si.getIntent().getData().toString());
7093                         assertEquals("foo/bar", si.getIntent().getType());
7094                         assertEquals(
7095                                 new ComponentName("abc", ".xyz"), si.getIntent().getComponent());
7096 
7097                         assertEquals(set("cat1", "cat2"), si.getIntent().getCategories());
7098                         assertEquals("value1", si.getIntent().getStringExtra("key1"));
7099                         assertEquals("value2", si.getIntent().getStringExtra("key2"));
7100                     });
7101         });
7102     }
7103 
testManifestShortcuts_localeChange()7104     public void testManifestShortcuts_localeChange() throws InterruptedException {
7105         mService.handleUnlockUser(USER_0);
7106 
7107         // Package 1 updated, which has one valid manifest shortcut and one invalid.
7108         addManifestShortcutResource(
7109                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
7110                 R.xml.shortcut_2);
7111         updatePackageVersion(CALLING_PACKAGE_1, 1);
7112                 mService.mPackageMonitor.onReceive(getTestContext(),
7113                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
7114 
7115         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
7116             mManager.setDynamicShortcuts(list(makeShortcutWithTitle("s1", "title")));
7117 
7118             assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
7119                     mManager.getManifestShortcuts()))),
7120                     "ms1", "ms2");
7121 
7122             // check first shortcut.
7123             ShortcutInfo si = getCallerShortcut("ms1");
7124 
7125             assertEquals("ms1", si.getId());
7126             assertEquals("string-com.android.test.1-user:0-res:" + R.string.shortcut_title1 + "/en",
7127                     si.getTitle());
7128             assertEquals("string-com.android.test.1-user:0-res:" + R.string.shortcut_text1 + "/en",
7129                     si.getText());
7130             assertEquals("string-com.android.test.1-user:0-res:"
7131                             + R.string.shortcut_disabled_message1 + "/en",
7132                     si.getDisabledMessage());
7133             assertEquals(START_TIME, si.getLastChangedTimestamp());
7134 
7135             // check another
7136             si = getCallerShortcut("ms2");
7137 
7138             assertEquals("ms2", si.getId());
7139             assertEquals("string-com.android.test.1-user:0-res:" + R.string.shortcut_title2 + "/en",
7140                     si.getTitle());
7141             assertEquals("string-com.android.test.1-user:0-res:" + R.string.shortcut_text2 + "/en",
7142                     si.getText());
7143             assertEquals("string-com.android.test.1-user:0-res:"
7144                             + R.string.shortcut_disabled_message2 + "/en",
7145                     si.getDisabledMessage());
7146             assertEquals(START_TIME, si.getLastChangedTimestamp());
7147 
7148             // Check the dynamic one.
7149             si = getCallerShortcut("s1");
7150 
7151             assertEquals("s1", si.getId());
7152             assertEquals("title", si.getTitle());
7153             assertEquals(null, si.getText());
7154             assertEquals(null, si.getDisabledMessage());
7155             assertEquals(START_TIME, si.getLastChangedTimestamp());
7156         });
7157 
7158         mInjectedCurrentTimeMillis++;
7159 
7160         // Change the locale and send the broadcast, make sure the launcher gets a callback too.
7161         mInjectedLocale = Locale.JAPANESE;
7162 
7163         setCaller(LAUNCHER_1, USER_0);
7164 
7165         assertForLauncherCallback(mLauncherApps, () -> {
7166             mService.mReceiver.onReceive(mServiceContext, new Intent(Intent.ACTION_LOCALE_CHANGED));
7167         }).assertCallbackCalledForPackageAndUser(CALLING_PACKAGE_1, HANDLE_USER_0)
7168                 .haveIds("ms1", "ms2", "s1");
7169 
7170         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
7171             // check first shortcut.
7172             ShortcutInfo si = getCallerShortcut("ms1");
7173 
7174             assertEquals("ms1", si.getId());
7175             assertEquals("string-com.android.test.1-user:0-res:" + R.string.shortcut_title1 + "/ja",
7176                     si.getTitle());
7177             assertEquals("string-com.android.test.1-user:0-res:" + R.string.shortcut_text1 + "/ja",
7178                     si.getText());
7179             assertEquals("string-com.android.test.1-user:0-res:"
7180                             + R.string.shortcut_disabled_message1 + "/ja",
7181                     si.getDisabledMessage());
7182             assertEquals(START_TIME + 1, si.getLastChangedTimestamp());
7183 
7184             // check another
7185             si = getCallerShortcut("ms2");
7186 
7187             assertEquals("ms2", si.getId());
7188             assertEquals("string-com.android.test.1-user:0-res:" + R.string.shortcut_title2 + "/ja",
7189                     si.getTitle());
7190             assertEquals("string-com.android.test.1-user:0-res:" + R.string.shortcut_text2 + "/ja",
7191                     si.getText());
7192             assertEquals("string-com.android.test.1-user:0-res:"
7193                             + R.string.shortcut_disabled_message2 + "/ja",
7194                     si.getDisabledMessage());
7195             assertEquals(START_TIME + 1, si.getLastChangedTimestamp());
7196 
7197             // Check the dynamic one.  (locale change shouldn't affect.)
7198             si = getCallerShortcut("s1");
7199 
7200             assertEquals("s1", si.getId());
7201             assertEquals("title", si.getTitle());
7202             assertEquals(null, si.getText());
7203             assertEquals(null, si.getDisabledMessage());
7204             assertEquals(START_TIME, si.getLastChangedTimestamp()); // Not changed.
7205         });
7206     }
7207 
testManifestShortcuts_updateAndDisabled_notPinned()7208     public void testManifestShortcuts_updateAndDisabled_notPinned() {
7209         mService.handleUnlockUser(USER_0);
7210 
7211         // First, just publish a manifest shortcut.
7212         addManifestShortcutResource(
7213                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
7214                 R.xml.shortcut_1);
7215         updatePackageVersion(CALLING_PACKAGE_1, 1);
7216                 mService.mPackageMonitor.onReceive(getTestContext(),
7217                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
7218 
7219         // Only the valid one is published.
7220         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
7221             assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
7222                     mManager.getManifestShortcuts()))),
7223                     "ms1");
7224             assertEmpty(mManager.getPinnedShortcuts());
7225 
7226             // Make sure there's no other dangling shortcuts.
7227             assertShortcutIds(getCallerShortcuts(), "ms1");
7228         });
7229 
7230         // Now version up, the manifest shortcut is disabled now.
7231         addManifestShortcutResource(
7232                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
7233                 R.xml.shortcut_1_disable);
7234         updatePackageVersion(CALLING_PACKAGE_1, 1);
7235                 mService.mPackageMonitor.onReceive(getTestContext(),
7236                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
7237 
7238         // Because shortcut 1 wasn't pinned, it'll just go away.
7239         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
7240             assertEmpty(mManager.getManifestShortcuts());
7241             assertEmpty(mManager.getPinnedShortcuts());
7242 
7243             // Make sure there's no other dangling shortcuts.
7244             assertEmpty(getCallerShortcuts());
7245         });
7246     }
7247 
testManifestShortcuts_updateAndDisabled_pinned()7248     public void testManifestShortcuts_updateAndDisabled_pinned() {
7249         mService.handleUnlockUser(USER_0);
7250 
7251         // First, just publish a manifest shortcut.
7252         addManifestShortcutResource(
7253                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
7254                 R.xml.shortcut_1);
7255         updatePackageVersion(CALLING_PACKAGE_1, 1);
7256                 mService.mPackageMonitor.onReceive(getTestContext(),
7257                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
7258 
7259         // Only the valid one is published.
7260         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
7261             assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
7262                     mManager.getManifestShortcuts()))),
7263                     "ms1");
7264             assertEmpty(mManager.getPinnedShortcuts());
7265 
7266             // Make sure there's no other dangling shortcuts.
7267             assertShortcutIds(getCallerShortcuts(), "ms1");
7268         });
7269 
7270         runWithCaller(LAUNCHER_1, USER_0, () -> {
7271             mLauncherApps.pinShortcuts(CALLING_PACKAGE_1, list("ms1"), HANDLE_USER_0);
7272         });
7273 
7274         // Now upgrade, the manifest shortcut is disabled now.
7275         addManifestShortcutResource(
7276                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
7277                 R.xml.shortcut_1_disable);
7278         updatePackageVersion(CALLING_PACKAGE_1, 1);
7279                 mService.mPackageMonitor.onReceive(getTestContext(),
7280                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
7281 
7282         // Because shortcut 1 was pinned, it'll still exist as pinned, but disabled.
7283         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
7284             assertEmpty(mManager.getManifestShortcuts());
7285             assertShortcutIds(assertAllNotManifest(assertAllImmutable(assertAllDisabled(
7286                     mManager.getPinnedShortcuts()))),
7287                     "ms1");
7288 
7289             // Make sure the fields are updated.
7290             ShortcutInfo si = getCallerShortcut("ms1");
7291 
7292             assertEquals("ms1", si.getId());
7293             assertEquals(R.drawable.icon2, si.getIconResourceId());
7294             assertEquals(R.string.shortcut_title2, si.getTitleResId());
7295             assertEquals(R.string.shortcut_text2, si.getTextResId());
7296             assertEquals(R.string.shortcut_disabled_message2, si.getDisabledMessageResourceId());
7297             assertEquals(Intent.ACTION_VIEW, si.getIntent().getAction());
7298 
7299             // Make sure there's no other dangling shortcuts.
7300             assertShortcutIds(getCallerShortcuts(), "ms1");
7301         });
7302     }
7303 
testManifestShortcuts_duplicateInSingleActivity()7304     public void testManifestShortcuts_duplicateInSingleActivity() {
7305         mService.handleUnlockUser(USER_0);
7306 
7307         // The XML has two shortcuts with the same ID.
7308         addManifestShortcutResource(
7309                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
7310                 R.xml.shortcut_2_duplicate);
7311         updatePackageVersion(CALLING_PACKAGE_1, 1);
7312                 mService.mPackageMonitor.onReceive(getTestContext(),
7313                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
7314 
7315         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
7316             assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
7317                     mManager.getManifestShortcuts()))),
7318                     "ms1");
7319 
7320             // Make sure the first one has survived.  (the second one has a different title.)
7321             ShortcutInfo si = getCallerShortcut("ms1");
7322             assertEquals(R.string.shortcut_title1, si.getTitleResId());
7323 
7324             // Make sure there's no other dangling shortcuts.
7325             assertShortcutIds(getCallerShortcuts(), "ms1");
7326         });
7327     }
7328 
testManifestShortcuts_duplicateInTwoActivities()7329     public void testManifestShortcuts_duplicateInTwoActivities() {
7330         mService.handleUnlockUser(USER_0);
7331 
7332         // ShortcutActivity has shortcut ms1
7333         addManifestShortcutResource(
7334                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
7335                 R.xml.shortcut_1);
7336 
7337         // ShortcutActivity2 has two shortcuts, ms1 and ms2.
7338         addManifestShortcutResource(
7339                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity2.class.getName()),
7340                 R.xml.shortcut_5);
7341         updatePackageVersion(CALLING_PACKAGE_1, 1);
7342                 mService.mPackageMonitor.onReceive(getTestContext(),
7343                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
7344 
7345         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
7346             assertShortcutIds(assertAllManifest(assertAllImmutable(assertAllEnabled(
7347                     mManager.getManifestShortcuts()))),
7348                     "ms1", "ms2", "ms3", "ms4", "ms5");
7349 
7350             // ms1 should belong to ShortcutActivity.
7351             ShortcutInfo si = getCallerShortcut("ms1");
7352             assertEquals(R.string.shortcut_title1, si.getTitleResId());
7353             assertEquals(new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
7354                     si.getActivity());
7355             assertEquals(0, si.getRank());
7356 
7357             // ms2 should belong to ShortcutActivity*2*.
7358             si = getCallerShortcut("ms2");
7359             assertEquals(R.string.shortcut_title2, si.getTitleResId());
7360             assertEquals(new ComponentName(CALLING_PACKAGE_1, ShortcutActivity2.class.getName()),
7361                     si.getActivity());
7362 
7363             // Also check the ranks
7364             assertWith(getCallerShortcuts()).selectManifest()
7365                     .selectByActivity(
7366                             new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()))
7367                     .haveRanksInOrder("ms1");
7368             assertWith(getCallerShortcuts()).selectManifest()
7369                     .selectByActivity(
7370                             new ComponentName(CALLING_PACKAGE_1, ShortcutActivity2.class.getName()))
7371                     .haveRanksInOrder("ms2", "ms3", "ms4", "ms5");
7372 
7373             // Make sure there's no other dangling shortcuts.
7374             assertShortcutIds(getCallerShortcuts(), "ms1", "ms2", "ms3", "ms4", "ms5");
7375         });
7376     }
7377 
7378     /**
7379      * Manifest shortcuts cannot override shortcuts that were published via the APIs.
7380      */
testManifestShortcuts_cannotOverrideNonManifest()7381     public void testManifestShortcuts_cannotOverrideNonManifest() {
7382         mService.handleUnlockUser(USER_0);
7383 
7384         // Create a non-pinned dynamic shortcut and a non-dynamic pinned shortcut.
7385 
7386         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
7387             mManager.setDynamicShortcuts(list(
7388                     makeShortcut("ms1", "title1",
7389                             new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
7390                     /* icon */ null, new Intent("action1"), /* rank */ 0),
7391                     makeShortcut("ms2", "title2",
7392                             new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
7393                     /* icon */ null, new Intent("action1"), /* rank */ 0)));
7394         });
7395 
7396         runWithCaller(LAUNCHER_1, USER_0, () -> {
7397             mLauncherApps.pinShortcuts(CALLING_PACKAGE_1, list("ms2"), HANDLE_USER_0);
7398         });
7399 
7400         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
7401             mManager.removeDynamicShortcuts(list("ms2"));
7402 
7403             assertShortcutIds(mManager.getDynamicShortcuts(), "ms1");
7404             assertShortcutIds(mManager.getPinnedShortcuts(), "ms2");
7405             assertEmpty(mManager.getManifestShortcuts());
7406         });
7407 
7408         // Then update the app with 5 manifest shortcuts.
7409         // Make sure "ms1" and "ms2" won't be replaced.
7410         addManifestShortcutResource(
7411                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
7412                 R.xml.shortcut_5);
7413         updatePackageVersion(CALLING_PACKAGE_1, 1);
7414                 mService.mPackageMonitor.onReceive(getTestContext(),
7415                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
7416 
7417         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
7418             assertShortcutIds(assertAllNotManifest(mManager.getDynamicShortcuts()), "ms1");
7419             assertShortcutIds(assertAllNotManifest(mManager.getPinnedShortcuts()), "ms2");
7420             assertShortcutIds(assertAllManifest(mManager.getManifestShortcuts()),
7421                     "ms3", "ms4", "ms5");
7422 
7423             // ms1 and ms2 shouold keep the original title.
7424             ShortcutInfo si = getCallerShortcut("ms1");
7425             assertEquals("title1", si.getTitle());
7426 
7427             si = getCallerShortcut("ms2");
7428             assertEquals("title2", si.getTitle());
7429         });
7430     }
7431 
checkManifestShortcuts_immutable_verify()7432     protected void checkManifestShortcuts_immutable_verify() {
7433         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
7434             assertShortcutIds(assertAllNotManifest(assertAllEnabled(
7435                     mManager.getDynamicShortcuts())),
7436                     "s1");
7437             assertShortcutIds(assertAllManifest(assertAllEnabled(
7438                     mManager.getManifestShortcuts())),
7439                     "ms1");
7440             assertShortcutIds(assertAllNotManifest(assertAllDisabled(
7441                     mManager.getPinnedShortcuts())),
7442                     "ms2");
7443 
7444             assertEquals("t1", getCallerShortcut("s1").getTitle());
7445 
7446             // Make sure there are no other shortcuts.
7447             assertShortcutIds(getCallerShortcuts(), "s1", "ms1", "ms2");
7448         });
7449     }
7450 
7451     /**
7452      * Make sure the APIs won't work on manifest shortcuts.
7453      */
testManifestShortcuts_immutable()7454     public void testManifestShortcuts_immutable() {
7455         mService.handleUnlockUser(USER_0);
7456 
7457         // Create a non-pinned manifest shortcut, a pinned shortcut that was originally
7458         // a manifest shortcut, as well as a dynamic shortcut.
7459 
7460         addManifestShortcutResource(
7461                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
7462                 R.xml.shortcut_2);
7463         updatePackageVersion(CALLING_PACKAGE_1, 1);
7464                 mService.mPackageMonitor.onReceive(getTestContext(),
7465                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
7466 
7467         runWithCaller(LAUNCHER_1, USER_0, () -> {
7468             mLauncherApps.pinShortcuts(CALLING_PACKAGE_1, list("ms2"), HANDLE_USER_0);
7469         });
7470 
7471         addManifestShortcutResource(
7472                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
7473                 R.xml.shortcut_1);
7474         updatePackageVersion(CALLING_PACKAGE_1, 1);
7475                 mService.mPackageMonitor.onReceive(getTestContext(),
7476                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
7477 
7478         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
7479             mManager.addDynamicShortcuts(list(makeShortcutWithTitle("s1", "t1")));
7480         });
7481 
7482         checkManifestShortcuts_immutable_verify();
7483 
7484         // Note that even though the first argument is not immutable and only the second one
7485         // is immutable, the first argument should not be executed either.
7486 
7487         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
7488             assertCannotUpdateImmutable(() -> {
7489                 mManager.setDynamicShortcuts(list(makeShortcut("xx"), makeShortcut("ms1")));
7490             });
7491             assertCannotUpdateImmutable(() -> {
7492                 mManager.setDynamicShortcuts(list(makeShortcut("xx"), makeShortcut("ms2")));
7493             });
7494         });
7495         checkManifestShortcuts_immutable_verify();
7496 
7497         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
7498             assertCannotUpdateImmutable(() -> {
7499                 mManager.addDynamicShortcuts(list(makeShortcut("xx"), makeShortcut("ms1")));
7500             });
7501             assertCannotUpdateImmutable(() -> {
7502                 mManager.addDynamicShortcuts(list(makeShortcut("xx"), makeShortcut("ms2")));
7503             });
7504         });
7505         checkManifestShortcuts_immutable_verify();
7506 
7507 
7508         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
7509             assertCannotUpdateImmutable(() -> {
7510                 mManager.updateShortcuts(list(makeShortcut("s1"), makeShortcut("ms1")));
7511             });
7512             assertCannotUpdateImmutable(() -> {
7513                 mManager.updateShortcuts(list(makeShortcut("s1"), makeShortcut("ms2")));
7514             });
7515         });
7516         checkManifestShortcuts_immutable_verify();
7517 
7518         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
7519             assertCannotUpdateImmutable(() -> {
7520                 mManager.removeDynamicShortcuts(list("s1", "ms1"));
7521             });
7522             assertCannotUpdateImmutable(() -> {
7523                 mManager.removeDynamicShortcuts(list("s2", "ms2"));
7524             });
7525         });
7526         checkManifestShortcuts_immutable_verify();
7527 
7528         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
7529             assertCannotUpdateImmutable(() -> {
7530                 mManager.disableShortcuts(list("s1", "ms1"));
7531             });
7532         });
7533         checkManifestShortcuts_immutable_verify();
7534 
7535         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
7536             assertCannotUpdateImmutable(() -> {
7537                 mManager.enableShortcuts(list("s1", "ms2"));
7538             });
7539         });
7540         checkManifestShortcuts_immutable_verify();
7541     }
7542 
7543 
7544     /**
7545      * Make sure the APIs won't work on manifest shortcuts.
7546      */
testManifestShortcuts_tooMany()7547     public void testManifestShortcuts_tooMany() {
7548         // Change the max number of shortcuts.
7549         mService.updateConfigurationLocked(ConfigConstants.KEY_MAX_SHORTCUTS + "=3");
7550 
7551         mService.handleUnlockUser(USER_0);
7552 
7553         addManifestShortcutResource(
7554                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
7555                 R.xml.shortcut_5);
7556         updatePackageVersion(CALLING_PACKAGE_1, 1);
7557                 mService.mPackageMonitor.onReceive(getTestContext(),
7558                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
7559 
7560         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
7561             // Only the first 3 should be published.
7562             assertShortcutIds(mManager.getManifestShortcuts(), "ms1", "ms2", "ms3");
7563         });
7564     }
7565 
testMaxShortcutCount_set()7566     public void testMaxShortcutCount_set() {
7567         // Change the max number of shortcuts.
7568         mService.updateConfigurationLocked(ConfigConstants.KEY_MAX_SHORTCUTS + "=3");
7569 
7570         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
7571             final ComponentName a1 = new ComponentName(mClientContext, ShortcutActivity.class);
7572             final ComponentName a2 = new ComponentName(mClientContext, ShortcutActivity2.class);
7573             final ShortcutInfo s1_1 = makeShortcutWithActivity("s11", a1);
7574             final ShortcutInfo s1_2 = makeShortcutWithActivity("s12", a1);
7575             final ShortcutInfo s1_3 = makeShortcutWithActivity("s13", a1);
7576             final ShortcutInfo s1_4 = makeShortcutWithActivity("s14", a1);
7577             final ShortcutInfo s1_5 = makeShortcutWithActivity("s15", a1);
7578             final ShortcutInfo s1_6 = makeShortcutWithActivity("s16", a1);
7579             final ShortcutInfo s2_1 = makeShortcutWithActivity("s21", a2);
7580             final ShortcutInfo s2_2 = makeShortcutWithActivity("s22", a2);
7581             final ShortcutInfo s2_3 = makeShortcutWithActivity("s23", a2);
7582             final ShortcutInfo s2_4 = makeShortcutWithActivity("s24", a2);
7583 
7584             // 3 shortcuts for 2 activities -> okay
7585             mManager.setDynamicShortcuts(list(s1_1, s1_2, s1_3, s2_1, s2_2, s2_3));
7586             assertShortcutIds(mManager.getDynamicShortcuts(),
7587                     "s11", "s12", "s13", "s21", "s22", "s23");
7588 
7589             mManager.removeAllDynamicShortcuts();
7590 
7591             // 4 shortcut for activity 1 -> too many.
7592             assertDynamicShortcutCountExceeded(() -> {
7593                 mManager.setDynamicShortcuts(list(s1_1, s1_2, s1_3, s1_4, s2_1, s2_2, s2_3));
7594             });
7595             assertEmpty(mManager.getDynamicShortcuts());
7596 
7597             // 4 shortcut for activity 2 -> too many.
7598             assertDynamicShortcutCountExceeded(() -> {
7599                 mManager.setDynamicShortcuts(list(s1_1, s1_2, s1_3, s2_1, s2_2, s2_3, s2_4));
7600             });
7601             assertEmpty(mManager.getDynamicShortcuts());
7602 
7603             // First, set 3.  Then set 4, which should be ignored.
7604             mManager.setDynamicShortcuts(list(s1_1, s1_2, s1_3));
7605             assertShortcutIds(mManager.getDynamicShortcuts(),
7606                     "s11", "s12", "s13");
7607             assertDynamicShortcutCountExceeded(() -> {
7608                 mManager.setDynamicShortcuts(list(s2_1, s2_2, s2_3, s2_4));
7609             });
7610             assertShortcutIds(mManager.getDynamicShortcuts(),
7611                     "s11", "s12", "s13");
7612 
7613             // Set will remove the old dynamic set, unlike add, so the following should pass.
7614             mManager.setDynamicShortcuts(list(s1_1, s1_2, s1_3));
7615             assertShortcutIds(mManager.getDynamicShortcuts(),
7616                     "s11", "s12", "s13");
7617             mManager.setDynamicShortcuts(list(s1_4, s1_5, s1_6));
7618             assertShortcutIds(mManager.getDynamicShortcuts(),
7619                     "s14", "s15", "s16");
7620 
7621             // Now, test with 2 manifest shortcuts.
7622             mManager.removeAllDynamicShortcuts();
7623             addManifestShortcutResource(
7624                     new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
7625                     R.xml.shortcut_2);
7626             updatePackageVersion(CALLING_PACKAGE_1, 1);
7627                     mService.mPackageMonitor.onReceive(getTestContext(),
7628                     genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
7629             assertEquals(2, mManager.getManifestShortcuts().size());
7630 
7631             // Setting 1 to activity 1 will work.
7632             mManager.setDynamicShortcuts(list(s1_1, s2_1, s2_2, s2_3));
7633             assertShortcutIds(mManager.getDynamicShortcuts(),
7634                     "s11", "s21", "s22", "s23");
7635             assertEquals(2, mManager.getManifestShortcuts().size());
7636 
7637             // But setting 2 will not.
7638             mManager.removeAllDynamicShortcuts();
7639             assertDynamicShortcutCountExceeded(() -> {
7640                 mManager.setDynamicShortcuts(list(s1_1, s1_2, s2_1, s2_2, s2_3));
7641             });
7642             assertEmpty(mManager.getDynamicShortcuts());
7643             assertEquals(2, mManager.getManifestShortcuts().size());
7644         });
7645     }
7646 
testMaxShortcutCount_add()7647     public void testMaxShortcutCount_add() {
7648         // Change the max number of shortcuts.
7649         mService.updateConfigurationLocked(ConfigConstants.KEY_MAX_SHORTCUTS + "=3");
7650 
7651         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
7652             final ComponentName a1 = new ComponentName(mClientContext, ShortcutActivity.class);
7653             final ComponentName a2 = new ComponentName(mClientContext, ShortcutActivity2.class);
7654             final ShortcutInfo s1_1 = makeShortcutWithActivity("s11", a1);
7655             final ShortcutInfo s1_2 = makeShortcutWithActivity("s12", a1);
7656             final ShortcutInfo s1_3 = makeShortcutWithActivity("s13", a1);
7657             final ShortcutInfo s1_4 = makeShortcutWithActivity("s14", a1);
7658             final ShortcutInfo s2_1 = makeShortcutWithActivity("s21", a2);
7659             final ShortcutInfo s2_2 = makeShortcutWithActivity("s22", a2);
7660             final ShortcutInfo s2_3 = makeShortcutWithActivity("s23", a2);
7661             final ShortcutInfo s2_4 = makeShortcutWithActivity("s24", a2);
7662 
7663             // 3 shortcuts for 2 activities -> okay
7664             mManager.addDynamicShortcuts(list(s1_1, s1_2, s1_3, s2_1, s2_2, s2_3));
7665             assertShortcutIds(mManager.getDynamicShortcuts(),
7666                     "s11", "s12", "s13", "s21", "s22", "s23");
7667 
7668             mManager.removeAllDynamicShortcuts();
7669 
7670             // 4 shortcut for activity 1 -> too many.
7671             assertDynamicShortcutCountExceeded(() -> {
7672                 mManager.addDynamicShortcuts(list(s1_1, s1_2, s1_3, s1_4, s2_1, s2_2, s2_3));
7673             });
7674             assertEmpty(mManager.getDynamicShortcuts());
7675 
7676             // 4 shortcut for activity 2 -> too many.
7677             assertDynamicShortcutCountExceeded(() -> {
7678                 mManager.addDynamicShortcuts(list(s1_1, s1_2, s1_3, s2_1, s2_2, s2_3, s2_4));
7679             });
7680             assertEmpty(mManager.getDynamicShortcuts());
7681 
7682             // First, set 3.  Then add 1 more, which should be ignored.
7683             mManager.setDynamicShortcuts(list(s1_1, s1_2, s1_3));
7684             assertShortcutIds(mManager.getDynamicShortcuts(),
7685                     "s11", "s12", "s13");
7686             assertDynamicShortcutCountExceeded(() -> {
7687                 mManager.addDynamicShortcuts(list(s1_4, s2_1));
7688             });
7689             assertShortcutIds(mManager.getDynamicShortcuts(),
7690                     "s11", "s12", "s13");
7691 
7692             // Update existing one, which should work.
7693             mManager.addDynamicShortcuts(list(makeShortcutWithActivityAndTitle(
7694                     "s11", a1, "xxx"), s2_1));
7695             assertShortcutIds(mManager.getDynamicShortcuts(),
7696                     "s11", "s12", "s13", "s21");
7697             assertEquals("xxx", getCallerShortcut("s11").getTitle());
7698 
7699             // Make sure pinned shortcuts won't affect.
7700             // - Pin s11 - s13, and remove all dynamic.
7701             runWithCaller(LAUNCHER_1, USER_0, () -> {
7702                 mLauncherApps.pinShortcuts(CALLING_PACKAGE_1, list("s11", "s12", "s13"),
7703                         HANDLE_USER_0);
7704             });
7705             mManager.removeAllDynamicShortcuts();
7706 
7707             assertEmpty(mManager.getDynamicShortcuts());
7708             assertShortcutIds(mManager.getPinnedShortcuts(),
7709                     "s11", "s12", "s13");
7710 
7711             // Then add dynamic.
7712             mManager.addDynamicShortcuts(list(s1_4, s2_1, s2_2, s2_3));
7713 
7714             assertShortcutIds(mManager.getDynamicShortcuts(),
7715                     "s14", "s21", "s22", "s23");
7716             assertShortcutIds(mManager.getPinnedShortcuts(),
7717                     "s11", "s12", "s13");
7718 
7719             // Adding "s11" and "s12" back, should work
7720             mManager.addDynamicShortcuts(list(s1_1, s1_2));
7721 
7722             assertShortcutIds(mManager.getDynamicShortcuts(),
7723                     "s14", "s11", "s12", "s21", "s22", "s23");
7724             assertShortcutIds(mManager.getPinnedShortcuts(),
7725                     "s11", "s12", "s13");
7726 
7727             // Adding back s13 doesn't work.
7728             assertDynamicShortcutCountExceeded(() -> {
7729                 mManager.addDynamicShortcuts(list(s1_3));
7730             });
7731 
7732             assertShortcutIds(filterByActivity(mManager.getDynamicShortcuts(), a1),
7733                     "s11", "s12", "s14");
7734             assertShortcutIds(filterByActivity(mManager.getDynamicShortcuts(), a2),
7735                     "s21", "s22", "s23");
7736 
7737             // Now swap the activities.
7738             mManager.updateShortcuts(list(
7739                     makeShortcutWithActivity("s11", a2),
7740                     makeShortcutWithActivity("s21", a1)));
7741 
7742             assertShortcutIds(filterByActivity(mManager.getDynamicShortcuts(), a1),
7743                     "s21", "s12", "s14");
7744             assertShortcutIds(filterByActivity(mManager.getDynamicShortcuts(), a2),
7745                     "s11", "s22", "s23");
7746 
7747             // Now, test with 2 manifest shortcuts.
7748             mManager.removeAllDynamicShortcuts();
7749             addManifestShortcutResource(
7750                     new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
7751                     R.xml.shortcut_2);
7752             updatePackageVersion(CALLING_PACKAGE_1, 1);
7753                     mService.mPackageMonitor.onReceive(getTestContext(),
7754                     genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
7755 
7756             assertEquals(2, mManager.getManifestShortcuts().size());
7757 
7758             // Adding one shortcut to activity 1 works fine.
7759             mManager.addDynamicShortcuts(list(s1_1, s2_1, s2_2, s2_3));
7760             assertShortcutIds(mManager.getDynamicShortcuts(),
7761                     "s11", "s21", "s22", "s23");
7762             assertEquals(2, mManager.getManifestShortcuts().size());
7763 
7764             // But adding one more doesn't.
7765             assertDynamicShortcutCountExceeded(() -> {
7766                 mManager.addDynamicShortcuts(list(s1_4, s2_1));
7767             });
7768             assertShortcutIds(mManager.getDynamicShortcuts(),
7769                     "s11", "s21", "s22", "s23");
7770             assertEquals(2, mManager.getManifestShortcuts().size());
7771         });
7772     }
7773 
testMaxShortcutCount_update()7774     public void testMaxShortcutCount_update() {
7775         // Change the max number of shortcuts.
7776         mService.updateConfigurationLocked(ConfigConstants.KEY_MAX_SHORTCUTS + "=3");
7777 
7778         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
7779             final ComponentName a1 = new ComponentName(mClientContext, ShortcutActivity.class);
7780             final ComponentName a2 = new ComponentName(mClientContext, ShortcutActivity2.class);
7781             final ShortcutInfo s1_1 = makeShortcutWithActivity("s11", a1);
7782             final ShortcutInfo s1_2 = makeShortcutWithActivity("s12", a1);
7783             final ShortcutInfo s1_3 = makeShortcutWithActivity("s13", a1);
7784             final ShortcutInfo s1_4 = makeShortcutWithActivity("s14", a1);
7785             final ShortcutInfo s1_5 = makeShortcutWithActivity("s15", a1);
7786             final ShortcutInfo s2_1 = makeShortcutWithActivity("s21", a2);
7787             final ShortcutInfo s2_2 = makeShortcutWithActivity("s22", a2);
7788             final ShortcutInfo s2_3 = makeShortcutWithActivity("s23", a2);
7789             final ShortcutInfo s2_4 = makeShortcutWithActivity("s24", a2);
7790 
7791             // 3 shortcuts for 2 activities -> okay
7792             mManager.setDynamicShortcuts(list(s1_1, s1_2, s1_3, s2_1, s2_2, s2_3));
7793             assertShortcutIds(mManager.getDynamicShortcuts(),
7794                     "s11", "s12", "s13", "s21", "s22", "s23");
7795 
7796             // Trying to move s11 from a1 to a2 should fail.
7797             assertDynamicShortcutCountExceeded(() -> {
7798                 mManager.updateShortcuts(list(makeShortcutWithActivity("s11", a2)));
7799             });
7800             assertShortcutIds(mManager.getDynamicShortcuts(),
7801                     "s11", "s12", "s13", "s21", "s22", "s23");
7802 
7803             // Trying to move s21 from a2 to a1 should also fail.
7804             assertDynamicShortcutCountExceeded(() -> {
7805                 mManager.updateShortcuts(list(makeShortcutWithActivity("s21", a1)));
7806             });
7807             assertShortcutIds(mManager.getDynamicShortcuts(),
7808                     "s11", "s12", "s13", "s21", "s22", "s23");
7809 
7810             // But, if we do these two at the same time, it should work.
7811             mManager.updateShortcuts(list(
7812                     makeShortcutWithActivity("s11", a2),
7813                     makeShortcutWithActivity("s21", a1)));
7814             assertShortcutIds(mManager.getDynamicShortcuts(),
7815                     "s11", "s12", "s13", "s21", "s22", "s23");
7816             assertShortcutIds(filterByActivity(mManager.getDynamicShortcuts(), a1),
7817                     "s21", "s12", "s13");
7818             assertShortcutIds(filterByActivity(mManager.getDynamicShortcuts(), a2),
7819                     "s11", "s22", "s23");
7820 
7821             // Then reset.
7822             mManager.setDynamicShortcuts(list(s1_1, s1_2, s1_3, s2_1, s2_2, s2_3));
7823             assertShortcutIds(mManager.getDynamicShortcuts(),
7824                     "s11", "s12", "s13", "s21", "s22", "s23");
7825 
7826             // Pin some to have more shortcuts for a1.
7827             runWithCaller(LAUNCHER_1, USER_0, () -> {
7828                 mLauncherApps.pinShortcuts(CALLING_PACKAGE_1, list("s11", "s12", "s13"),
7829                         HANDLE_USER_0);
7830             });
7831             mManager.setDynamicShortcuts(list(s1_4, s1_5, s2_1, s2_2, s2_3));
7832             assertShortcutIds(mManager.getDynamicShortcuts(),
7833                     "s14", "s15", "s21", "s22", "s23");
7834             assertShortcutIds(mManager.getPinnedShortcuts(),
7835                     "s11", "s12", "s13");
7836 
7837             // a1 already has 2 dynamic shortcuts (and 3 pinned shortcuts that used to belong on it)
7838             // But that doesn't matter for update -- the following should still work.
7839             mManager.updateShortcuts(list(
7840                     makeShortcutWithActivityAndTitle("s11", a1, "xxx1"),
7841                     makeShortcutWithActivityAndTitle("s12", a1, "xxx2"),
7842                     makeShortcutWithActivityAndTitle("s13", a1, "xxx3"),
7843                     makeShortcutWithActivityAndTitle("s14", a1, "xxx4"),
7844                     makeShortcutWithActivityAndTitle("s15", a1, "xxx5")));
7845             // All the shortcuts should still exist they all belong on same activities,
7846             // with the updated titles.
7847             assertShortcutIds(mManager.getDynamicShortcuts(),
7848                     "s14", "s15", "s21", "s22", "s23");
7849             assertShortcutIds(mManager.getPinnedShortcuts(),
7850                     "s11", "s12", "s13");
7851 
7852             assertShortcutIds(filterByActivity(mManager.getDynamicShortcuts(), a1),
7853                     "s14", "s15");
7854             assertShortcutIds(filterByActivity(mManager.getDynamicShortcuts(), a2),
7855                     "s21", "s22", "s23");
7856 
7857             assertEquals("xxx1", getCallerShortcut("s11").getTitle());
7858             assertEquals("xxx2", getCallerShortcut("s12").getTitle());
7859             assertEquals("xxx3", getCallerShortcut("s13").getTitle());
7860             assertEquals("xxx4", getCallerShortcut("s14").getTitle());
7861             assertEquals("xxx5", getCallerShortcut("s15").getTitle());
7862         });
7863     }
7864 
testShortcutsPushedOutByManifest()7865     public void testShortcutsPushedOutByManifest() {
7866         // Change the max number of shortcuts.
7867         mService.updateConfigurationLocked(ConfigConstants.KEY_MAX_SHORTCUTS + "=3");
7868 
7869         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
7870             final ComponentName a1 = new ComponentName(mClientContext, ShortcutActivity.class);
7871             final ComponentName a2 = new ComponentName(mClientContext, ShortcutActivity2.class);
7872             final ShortcutInfo s1_1 = makeShortcutWithActivityAndRank("s11", a1, 4);
7873             final ShortcutInfo s1_2 = makeShortcutWithActivityAndRank("s12", a1, 3);
7874             final ShortcutInfo s1_3 = makeShortcutWithActivityAndRank("s13", a1, 2);
7875             final ShortcutInfo s1_4 = makeShortcutWithActivityAndRank("s14", a1, 1);
7876             final ShortcutInfo s1_5 = makeShortcutWithActivityAndRank("s15", a1, 0);
7877             final ShortcutInfo s2_1 = makeShortcutWithActivityAndRank("s21", a2, 0);
7878             final ShortcutInfo s2_2 = makeShortcutWithActivityAndRank("s22", a2, 1);
7879             final ShortcutInfo s2_3 = makeShortcutWithActivityAndRank("s23", a2, 2);
7880             final ShortcutInfo s2_4 = makeShortcutWithActivityAndRank("s24", a2, 3);
7881             final ShortcutInfo s2_5 = makeShortcutWithActivityAndRank("s25", a2, 4);
7882 
7883             // Initial state.
7884             mManager.setDynamicShortcuts(list(s1_1, s1_2, s1_3, s2_1, s2_2, s2_3));
7885             runWithCaller(LAUNCHER_1, USER_0, () -> {
7886                 mLauncherApps.pinShortcuts(CALLING_PACKAGE_1, list("s11", "s12", "s21", "s22"),
7887                         HANDLE_USER_0);
7888             });
7889             mManager.setDynamicShortcuts(list(s1_2, s1_3, s1_4, s2_2, s2_3, s2_4));
7890             assertShortcutIds(assertAllEnabled(mManager.getDynamicShortcuts()),
7891                     "s12", "s13", "s14",
7892                     "s22", "s23", "s24");
7893             assertShortcutIds(assertAllEnabled(mManager.getPinnedShortcuts()),
7894                     "s11", "s12",
7895                     "s21", "s22");
7896 
7897             // Add 1 manifest shortcut to a1.
7898             addManifestShortcutResource(
7899                     new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
7900                     R.xml.shortcut_1);
7901             updatePackageVersion(CALLING_PACKAGE_1, 1);
7902                     mService.mPackageMonitor.onReceive(getTestContext(),
7903                     genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
7904             assertEquals(1, mManager.getManifestShortcuts().size());
7905 
7906             // s12 removed.
7907             assertShortcutIds(assertAllEnabled(mManager.getDynamicShortcuts()),
7908                     "s13", "s14",
7909                     "s22", "s23", "s24");
7910             assertShortcutIds(assertAllEnabled(mManager.getPinnedShortcuts()),
7911                     "s11", "s12",
7912                     "s21", "s22");
7913 
7914             // Add more manifest shortcuts.
7915             addManifestShortcutResource(
7916                     new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
7917                     R.xml.shortcut_2);
7918             addManifestShortcutResource(
7919                     new ComponentName(CALLING_PACKAGE_1, ShortcutActivity2.class.getName()),
7920                     R.xml.shortcut_1_alt);
7921             updatePackageVersion(CALLING_PACKAGE_1, 1);
7922                     mService.mPackageMonitor.onReceive(getTestContext(),
7923                     genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
7924             assertEquals(3, mManager.getManifestShortcuts().size());
7925 
7926             // Note the ones with the highest rank values (== least important) will be removed.
7927             assertShortcutIds(assertAllEnabled(mManager.getDynamicShortcuts()),
7928                     "s14",
7929                     "s22", "s23");
7930             assertShortcutIds(assertAllEnabled(mManager.getPinnedShortcuts()),
7931                     "s11", "s12",
7932                     "s21", "s22");
7933 
7934             // Add more manifest shortcuts.
7935             addManifestShortcutResource(
7936                     new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
7937                     R.xml.shortcut_2);
7938             addManifestShortcutResource(
7939                     new ComponentName(CALLING_PACKAGE_1, ShortcutActivity2.class.getName()),
7940                     R.xml.shortcut_5_alt); // manifest has 5, but max is 3, so a2 will have 3.
7941             updatePackageVersion(CALLING_PACKAGE_1, 1);
7942                     mService.mPackageMonitor.onReceive(getTestContext(),
7943                     genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
7944             assertEquals(5, mManager.getManifestShortcuts().size());
7945 
7946             assertShortcutIds(assertAllEnabled(mManager.getDynamicShortcuts()),
7947                     "s14" // a1 has 1 dynamic
7948             ); // a2 has no dynamic
7949             assertShortcutIds(assertAllEnabled(mManager.getPinnedShortcuts()),
7950                     "s11", "s12",
7951                     "s21", "s22");
7952 
7953             // Update, no manifest shortucts.  This doesn't affect anything.
7954             addManifestShortcutResource(
7955                     new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
7956                     R.xml.shortcut_0);
7957             addManifestShortcutResource(
7958                     new ComponentName(CALLING_PACKAGE_1, ShortcutActivity2.class.getName()),
7959                     R.xml.shortcut_0);
7960             updatePackageVersion(CALLING_PACKAGE_1, 1);
7961                     mService.mPackageMonitor.onReceive(getTestContext(),
7962                     genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
7963             assertEquals(0, mManager.getManifestShortcuts().size());
7964 
7965             assertShortcutIds(assertAllEnabled(mManager.getDynamicShortcuts()),
7966                     "s14");
7967             assertShortcutIds(assertAllEnabled(mManager.getPinnedShortcuts()),
7968                     "s11", "s12",
7969                     "s21", "s22");
7970         });
7971     }
7972 
testReturnedByServer()7973     public void testReturnedByServer() {
7974         // Package 1 updated, with manifest shortcuts.
7975         addManifestShortcutResource(
7976                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
7977                 R.xml.shortcut_1);
7978         updatePackageVersion(CALLING_PACKAGE_1, 1);
7979         mService.mPackageMonitor.onReceive(getTestContext(),
7980                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
7981 
7982         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
7983             assertWith(mManager.getManifestShortcuts())
7984                     .haveIds("ms1")
7985                     .forAllShortcuts(si -> assertTrue(si.isReturnedByServer()));
7986 
7987             assertTrue(mManager.setDynamicShortcuts(list(makeShortcut("s1"))));
7988 
7989             assertWith(mManager.getDynamicShortcuts())
7990                     .haveIds("s1")
7991                     .forAllShortcuts(si -> assertTrue(si.isReturnedByServer()));
7992         });
7993 
7994         // Pin them.
7995         runWithCaller(LAUNCHER_1, USER_0, () -> {
7996             mLauncherApps.pinShortcuts(CALLING_PACKAGE_1,
7997                     list("ms1", "s1"), getCallingUser());
7998             assertWith(getShortcutAsLauncher(USER_0))
7999                     .haveIds("ms1", "s1")
8000                     .forAllShortcuts(si -> assertTrue(si.isReturnedByServer()));
8001         });
8002 
8003         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
8004             assertWith(mManager.getPinnedShortcuts())
8005                     .haveIds("ms1", "s1")
8006                     .forAllShortcuts(si -> assertTrue(si.isReturnedByServer()));
8007         });
8008 
8009         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
8010             // This shows a warning log, but should still work.
8011             assertTrue(mManager.setDynamicShortcuts(mManager.getDynamicShortcuts()));
8012 
8013             assertWith(mManager.getDynamicShortcuts())
8014                     .haveIds("s1")
8015                     .forAllShortcuts(si -> assertTrue(si.isReturnedByServer()));
8016         });
8017     }
8018 
testIsForegroundDefaultLauncher_true()8019     public void testIsForegroundDefaultLauncher_true() {
8020         final ComponentName defaultLauncher = new ComponentName("default", "launcher");
8021         final int uid = 1024;
8022 
8023         setDefaultLauncher(UserHandle.USER_SYSTEM, defaultLauncher);
8024         makeUidForeground(uid);
8025 
8026         assertTrue(mInternal.isForegroundDefaultLauncher("default", uid));
8027     }
8028 
8029 
testIsForegroundDefaultLauncher_defaultButNotForeground()8030     public void testIsForegroundDefaultLauncher_defaultButNotForeground() {
8031         final ComponentName defaultLauncher = new ComponentName("default", "launcher");
8032         final int uid = 1024;
8033 
8034         setDefaultLauncher(UserHandle.USER_SYSTEM, defaultLauncher);
8035         makeUidBackground(uid);
8036 
8037         assertFalse(mInternal.isForegroundDefaultLauncher("default", uid));
8038     }
8039 
testIsForegroundDefaultLauncher_foregroundButNotDefault()8040     public void testIsForegroundDefaultLauncher_foregroundButNotDefault() {
8041         final ComponentName defaultLauncher = new ComponentName("default", "launcher");
8042         final int uid = 1024;
8043 
8044         setDefaultLauncher(UserHandle.USER_SYSTEM, defaultLauncher);
8045         makeUidForeground(uid);
8046 
8047         assertFalse(mInternal.isForegroundDefaultLauncher("another", uid));
8048     }
8049 
testParseShareTargetsFromManifest()8050     public void testParseShareTargetsFromManifest() {
8051         // These values must exactly match the content of shortcuts_share_targets.xml resource
8052         List<ShareTargetInfo> expectedValues = new ArrayList<>();
8053         expectedValues.add(new ShareTargetInfo(
8054                 new ShareTargetInfo.TargetData[]{new ShareTargetInfo.TargetData(
8055                         "http", "www.google.com", "1234", "somePath", "somePathPattern",
8056                         "somePathPrefix", "text/plain")}, "com.test.directshare.TestActivity1",
8057                 new String[]{"com.test.category.CATEGORY1", "com.test.category.CATEGORY2"}));
8058         expectedValues.add(new ShareTargetInfo(new ShareTargetInfo.TargetData[]{
8059                 new ShareTargetInfo.TargetData(null, null, null, null, null, null, "video/mp4"),
8060                 new ShareTargetInfo.TargetData("content", null, null, null, null, null, "video/*")},
8061                 "com.test.directshare.TestActivity5",
8062                 new String[]{"com.test.category.CATEGORY5", "com.test.category.CATEGORY6"}));
8063 
8064         addManifestShortcutResource(
8065                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
8066                 R.xml.shortcut_share_targets);
8067         updatePackageVersion(CALLING_PACKAGE_1, 1);
8068         mService.mPackageMonitor.onReceive(getTestContext(),
8069                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
8070 
8071         List<ShareTargetInfo> shareTargets = getCallerShareTargets();
8072 
8073         assertNotNull(shareTargets);
8074         assertEquals(expectedValues.size(), shareTargets.size());
8075 
8076         for (int i = 0; i < expectedValues.size(); i++) {
8077             ShareTargetInfo expected = expectedValues.get(i);
8078             ShareTargetInfo actual = shareTargets.get(i);
8079 
8080             assertEquals(expected.mTargetData.length, actual.mTargetData.length);
8081             for (int j = 0; j < expected.mTargetData.length; j++) {
8082                 assertEquals(expected.mTargetData[j].mScheme, actual.mTargetData[j].mScheme);
8083                 assertEquals(expected.mTargetData[j].mHost, actual.mTargetData[j].mHost);
8084                 assertEquals(expected.mTargetData[j].mPort, actual.mTargetData[j].mPort);
8085                 assertEquals(expected.mTargetData[j].mPath, actual.mTargetData[j].mPath);
8086                 assertEquals(expected.mTargetData[j].mPathPrefix,
8087                         actual.mTargetData[j].mPathPrefix);
8088                 assertEquals(expected.mTargetData[j].mPathPattern,
8089                         actual.mTargetData[j].mPathPattern);
8090                 assertEquals(expected.mTargetData[j].mMimeType, actual.mTargetData[j].mMimeType);
8091             }
8092 
8093             assertEquals(expected.mTargetClass, actual.mTargetClass);
8094 
8095             assertEquals(expected.mCategories.length, actual.mCategories.length);
8096             for (int j = 0; j < expected.mCategories.length; j++) {
8097                 assertEquals(expected.mCategories[j], actual.mCategories[j]);
8098             }
8099         }
8100     }
8101 
testShareTargetInfo_saveToXml()8102     public void testShareTargetInfo_saveToXml() throws IOException, XmlPullParserException {
8103         List<ShareTargetInfo> expectedValues = new ArrayList<>();
8104         expectedValues.add(new ShareTargetInfo(
8105                 new ShareTargetInfo.TargetData[]{new ShareTargetInfo.TargetData(
8106                         "http", "www.google.com", "1234", "somePath", "somePathPattern",
8107                         "somePathPrefix", "text/plain")}, "com.test.directshare.TestActivity1",
8108                 new String[]{"com.test.category.CATEGORY1", "com.test.category.CATEGORY2"}));
8109         expectedValues.add(new ShareTargetInfo(new ShareTargetInfo.TargetData[]{
8110                 new ShareTargetInfo.TargetData(null, null, null, null, null, null, "video/mp4"),
8111                 new ShareTargetInfo.TargetData("content", null, null, null, null, null, "video/*")},
8112                 "com.test.directshare.TestActivity5",
8113                 new String[]{"com.test.category.CATEGORY5", "com.test.category.CATEGORY6"}));
8114 
8115         // Write ShareTargets to Xml
8116         ByteArrayOutputStream outStream = new ByteArrayOutputStream();
8117         final XmlSerializer outXml = new FastXmlSerializer();
8118         outXml.setOutput(outStream, StandardCharsets.UTF_8.name());
8119         outXml.startDocument(null, true);
8120         for (int i = 0; i < expectedValues.size(); i++) {
8121             expectedValues.get(i).saveToXml(outXml);
8122         }
8123         outXml.endDocument();
8124         outXml.flush();
8125 
8126         // Read ShareTargets from Xml
8127         ByteArrayInputStream inStream = new ByteArrayInputStream(outStream.toByteArray());
8128         XmlPullParser parser = Xml.newPullParser();
8129         parser.setInput(new InputStreamReader(inStream));
8130         List<ShareTargetInfo> shareTargets = new ArrayList<>();
8131         int type;
8132         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
8133             if (type == XmlPullParser.START_TAG && parser.getName().equals("share-target")) {
8134                 shareTargets.add(ShareTargetInfo.loadFromXml(parser));
8135             }
8136         }
8137 
8138         // Assert two lists are equal
8139         assertNotNull(shareTargets);
8140         assertEquals(expectedValues.size(), shareTargets.size());
8141 
8142         for (int i = 0; i < expectedValues.size(); i++) {
8143             ShareTargetInfo expected = expectedValues.get(i);
8144             ShareTargetInfo actual = shareTargets.get(i);
8145 
8146             assertEquals(expected.mTargetData.length, actual.mTargetData.length);
8147             for (int j = 0; j < expected.mTargetData.length; j++) {
8148                 assertEquals(expected.mTargetData[j].mScheme, actual.mTargetData[j].mScheme);
8149                 assertEquals(expected.mTargetData[j].mHost, actual.mTargetData[j].mHost);
8150                 assertEquals(expected.mTargetData[j].mPort, actual.mTargetData[j].mPort);
8151                 assertEquals(expected.mTargetData[j].mPath, actual.mTargetData[j].mPath);
8152                 assertEquals(expected.mTargetData[j].mPathPrefix,
8153                         actual.mTargetData[j].mPathPrefix);
8154                 assertEquals(expected.mTargetData[j].mPathPattern,
8155                         actual.mTargetData[j].mPathPattern);
8156                 assertEquals(expected.mTargetData[j].mMimeType, actual.mTargetData[j].mMimeType);
8157             }
8158 
8159             assertEquals(expected.mTargetClass, actual.mTargetClass);
8160 
8161             assertEquals(expected.mCategories.length, actual.mCategories.length);
8162             for (int j = 0; j < expected.mCategories.length; j++) {
8163                 assertEquals(expected.mCategories[j], actual.mCategories[j]);
8164             }
8165         }
8166     }
8167 }
8168