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