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