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