aboutsummaryrefslogtreecommitdiff
path: root/java/src/com/android/intentresolver/ChooserListAdapter.java
blob: e6d6dbf45747f41db3f40310e3b0354a2e070c56 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
/*
 * Copyright (C) 2019 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.intentresolver;

import static com.android.intentresolver.ChooserActivity.TARGET_TYPE_SHORTCUTS_FROM_PREDICTION_SERVICE;
import static com.android.intentresolver.ChooserActivity.TARGET_TYPE_SHORTCUTS_FROM_SHORTCUT_MANAGER;

import android.annotation.Nullable;
import android.app.ActivityManager;
import android.app.prediction.AppTarget;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.LabeledIntent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.pm.ShortcutInfo;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Trace;
import android.os.UserHandle;
import android.os.UserManager;
import android.provider.DeviceConfig;
import android.service.chooser.ChooserTarget;
import android.text.Layout;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.android.intentresolver.chooser.DisplayResolveInfo;
import com.android.intentresolver.chooser.MultiDisplayResolveInfo;
import com.android.intentresolver.chooser.NotSelectableTargetInfo;
import com.android.intentresolver.chooser.SelectableTargetInfo;
import com.android.intentresolver.chooser.TargetInfo;
import com.android.intentresolver.icons.TargetDataLoader;
import com.android.intentresolver.logging.EventLog;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.config.sysui.SystemUiDeviceConfigFlags;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

public class ChooserListAdapter extends ResolverListAdapter {
    private static final String TAG = "ChooserListAdapter";
    private static final boolean DEBUG = false;

    public static final int NO_POSITION = -1;
    public static final int TARGET_BAD = -1;
    public static final int TARGET_CALLER = 0;
    public static final int TARGET_SERVICE = 1;
    public static final int TARGET_STANDARD = 2;
    public static final int TARGET_STANDARD_AZ = 3;

    private static final int MAX_SUGGESTED_APP_TARGETS = 4;

    /** {@link #getBaseScore} */
    public static final float CALLER_TARGET_SCORE_BOOST = 900.f;
    /** {@link #getBaseScore} */
    public static final float SHORTCUT_TARGET_SCORE_BOOST = 90.f;

    private final ChooserRequestParameters mChooserRequest;
    private final int mMaxRankedTargets;

    private final EventLog mEventLog;

    private final Set<TargetInfo> mRequestedIcons = new HashSet<>();

    // Reserve spots for incoming direct share targets by adding placeholders
    private final TargetInfo mPlaceHolderTargetInfo;
    private final TargetDataLoader mTargetDataLoader;
    private final List<TargetInfo> mServiceTargets = new ArrayList<>();
    private final List<DisplayResolveInfo> mCallerTargets = new ArrayList<>();

    private final ShortcutSelectionLogic mShortcutSelectionLogic;

    // Sorted list of DisplayResolveInfos for the alphabetical app section.
    private List<DisplayResolveInfo> mSortedList = new ArrayList<>();

    private final ItemRevealAnimationTracker mAnimationTracker = new ItemRevealAnimationTracker();

    // For pinned direct share labels, if the text spans multiple lines, the TextView will consume
    // the full width, even if the characters actually take up less than that. Measure the actual
    // line widths and constrain the View's width based upon that so that the pin doesn't end up
    // very far from the text.
    private final View.OnLayoutChangeListener mPinTextSpacingListener =
            new View.OnLayoutChangeListener() {
                @Override
                public void onLayoutChange(View v, int left, int top, int right, int bottom,
                        int oldLeft, int oldTop, int oldRight, int oldBottom) {
                    TextView textView = (TextView) v;
                    Layout layout = textView.getLayout();
                    if (layout != null) {
                        int textWidth = 0;
                        for (int line = 0; line < layout.getLineCount(); line++) {
                            textWidth = Math.max((int) Math.ceil(layout.getLineMax(line)),
                                    textWidth);
                        }
                        int desiredWidth = textWidth + textView.getPaddingLeft()
                                + textView.getPaddingRight();
                        if (textView.getWidth() > desiredWidth) {
                            ViewGroup.LayoutParams params = textView.getLayoutParams();
                            params.width = desiredWidth;
                            textView.setLayoutParams(params);
                            // Need to wait until layout pass is over before requesting layout.
                            textView.post(() -> textView.requestLayout());
                        }
                        textView.removeOnLayoutChangeListener(this);
                    }
                }
            };

    public ChooserListAdapter(
            Context context,
            List<Intent> payloadIntents,
            Intent[] initialIntents,
            List<ResolveInfo> rList,
            boolean filterLastUsed,
            ResolverListController resolverListController,
            UserHandle userHandle,
            Intent targetIntent,
            ResolverListCommunicator resolverListCommunicator,
            PackageManager packageManager,
            EventLog eventLog,
            ChooserRequestParameters chooserRequest,
            int maxRankedTargets,
            UserHandle initialIntentsUserSpace,
            TargetDataLoader targetDataLoader) {
        // Don't send the initial intents through the shared ResolverActivity path,
        // we want to separate them into a different section.
        super(
                context,
                payloadIntents,
                null,
                rList,
                filterLastUsed,
                resolverListController,
                userHandle,
                targetIntent,
                resolverListCommunicator,
                initialIntentsUserSpace,
                targetDataLoader);

        mChooserRequest = chooserRequest;
        mMaxRankedTargets = maxRankedTargets;

        mPlaceHolderTargetInfo = NotSelectableTargetInfo.newPlaceHolderTargetInfo(context);
        mTargetDataLoader = targetDataLoader;
        createPlaceHolders();
        mEventLog = eventLog;
        mShortcutSelectionLogic = new ShortcutSelectionLogic(
                context.getResources().getInteger(R.integer.config_maxShortcutTargetsPerApp),
                DeviceConfig.getBoolean(
                        DeviceConfig.NAMESPACE_SYSTEMUI,
                        SystemUiDeviceConfigFlags.APPLY_SHARING_APP_LIMITS_IN_SYSUI,
                        true)
        );

        if (initialIntents != null) {
            for (int i = 0; i < initialIntents.length; i++) {
                final Intent ii = initialIntents[i];
                if (ii == null) {
                    continue;
                }

                // We reimplement Intent#resolveActivityInfo here because if we have an
                // implicit intent, we want the ResolveInfo returned by PackageManager
                // instead of one we reconstruct ourselves. The ResolveInfo returned might
                // have extra metadata and resolvePackageName set and we want to respect that.
                ResolveInfo ri = null;
                ActivityInfo ai = null;
                final ComponentName cn = ii.getComponent();
                if (cn != null) {
                    try {
                        ai = packageManager.getActivityInfo(
                                ii.getComponent(),
                                PackageManager.ComponentInfoFlags.of(PackageManager.GET_META_DATA));
                        ri = new ResolveInfo();
                        ri.activityInfo = ai;
                    } catch (PackageManager.NameNotFoundException ignored) {
                        // ai will == null below
                    }
                }
                if (ai == null) {
                    // Because of AIDL bug, resolveActivity can't accept subclasses of Intent.
                    final Intent rii = (ii.getClass() == Intent.class) ? ii : new Intent(ii);
                    ri = packageManager.resolveActivity(
                            rii,
                            PackageManager.ResolveInfoFlags.of(PackageManager.MATCH_DEFAULT_ONLY));
                    ai = ri != null ? ri.activityInfo : null;
                }
                if (ai == null) {
                    Log.w(TAG, "No activity found for " + ii);
                    continue;
                }
                UserManager userManager =
                        (UserManager) context.getSystemService(Context.USER_SERVICE);
                if (ii instanceof LabeledIntent) {
                    LabeledIntent li = (LabeledIntent) ii;
                    ri.resolvePackageName = li.getSourcePackage();
                    ri.labelRes = li.getLabelResource();
                    ri.nonLocalizedLabel = li.getNonLocalizedLabel();
                    ri.icon = li.getIconResource();
                    ri.iconResourceId = ri.icon;
                }
                if (userManager.isManagedProfile()) {
                    ri.noResourceId = true;
                    ri.icon = 0;
                }
                ri.userHandle = initialIntentsUserSpace;
                // TODO: remove DisplayResolveInfo dependency on presentation getter
                DisplayResolveInfo displayResolveInfo = DisplayResolveInfo.newDisplayResolveInfo(
                        ii, ri, ii, mTargetDataLoader.createPresentationGetter(ri));
                mCallerTargets.add(displayResolveInfo);
                if (mCallerTargets.size() == MAX_SUGGESTED_APP_TARGETS) break;
            }
        }
    }

    @Override
    public void handlePackagesChanged() {
        if (DEBUG) {
            Log.d(TAG, "clearing queryTargets on package change");
        }
        createPlaceHolders();
        mResolverListCommunicator.onHandlePackagesChanged(this);

    }

    @Override
    protected boolean rebuildList(boolean doPostProcessing) {
        mAnimationTracker.reset();
        mSortedList.clear();
        boolean result = super.rebuildList(doPostProcessing);
        notifyDataSetChanged();
        return result;
    }

    private void createPlaceHolders() {
        mServiceTargets.clear();
        for (int i = 0; i < mMaxRankedTargets; ++i) {
            mServiceTargets.add(mPlaceHolderTargetInfo);
        }
    }

    @Override
    View onCreateView(ViewGroup parent) {
        return mInflater.inflate(R.layout.resolve_grid_item, parent, false);
    }

    @VisibleForTesting
    @Override
    public void onBindView(View view, TargetInfo info, int position) {
        final ViewHolder holder = (ViewHolder) view.getTag();

        if (info == null) {
            holder.icon.setImageDrawable(loadIconPlaceholder());
            return;
        }

        holder.bindLabel(info.getDisplayLabel(), info.getExtendedInfo());
        mAnimationTracker.animateLabel(holder.text, info);
        if (holder.text2.getVisibility() == View.VISIBLE) {
            mAnimationTracker.animateLabel(holder.text2, info);
        }
        holder.bindIcon(info);
        if (info.getDisplayIconHolder().getDisplayIcon() != null) {
            mAnimationTracker.animateIcon(holder.icon, info);
        } else {
            holder.icon.clearAnimation();
        }

        if (info.isSelectableTargetInfo()) {
            // direct share targets should append the application name for a better readout
            DisplayResolveInfo rInfo = info.getDisplayResolveInfo();
            CharSequence appName = rInfo != null ? rInfo.getDisplayLabel() : "";
            CharSequence extendedInfo = info.getExtendedInfo();
            String contentDescription = String.join(" ", info.getDisplayLabel(),
                    extendedInfo != null ? extendedInfo : "", appName);
            holder.updateContentDescription(contentDescription);
            if (!info.hasDisplayIcon()) {
                loadDirectShareIcon((SelectableTargetInfo) info);
            }
        } else if (info.isDisplayResolveInfo()) {
            DisplayResolveInfo dri = (DisplayResolveInfo) info;
            if (!dri.hasDisplayIcon()) {
                loadIcon(dri);
            }
        }

        // If target is loading, show a special placeholder shape in the label, make unclickable
        if (info.isPlaceHolderTargetInfo()) {
            final int maxWidth = mContext.getResources().getDimensionPixelSize(
                    R.dimen.chooser_direct_share_label_placeholder_max_width);
            holder.text.setMaxWidth(maxWidth);
            holder.text.setBackground(mContext.getResources().getDrawable(
                    R.drawable.chooser_direct_share_label_placeholder, mContext.getTheme()));
            // Prevent rippling by removing background containing ripple
            holder.itemView.setBackground(null);
        } else {
            holder.text.setMaxWidth(Integer.MAX_VALUE);
            holder.text.setBackground(null);
            holder.itemView.setBackground(holder.defaultItemViewBackground);
        }

        // Always remove the spacing listener, attach as needed to direct share targets below.
        holder.text.removeOnLayoutChangeListener(mPinTextSpacingListener);

        if (info.isMultiDisplayResolveInfo()) {
            // If the target is grouped show an indicator
            Drawable bkg = mContext.getDrawable(R.drawable.chooser_group_background);
            holder.text.setPaddingRelative(0, 0, bkg.getIntrinsicWidth() /* end */, 0);
            holder.text.setBackground(bkg);
        } else if (info.isPinned() && (getPositionTargetType(position) == TARGET_STANDARD
                || getPositionTargetType(position) == TARGET_SERVICE)) {
            // If the appShare or directShare target is pinned and in the suggested row show a
            // pinned indicator
            Drawable bkg = mContext.getDrawable(R.drawable.chooser_pinned_background);
            holder.text.setPaddingRelative(bkg.getIntrinsicWidth() /* start */, 0, 0, 0);
            holder.text.setBackground(bkg);
            holder.text.addOnLayoutChangeListener(mPinTextSpacingListener);
        } else {
            holder.text.setBackground(null);
            holder.text.setPaddingRelative(0, 0, 0, 0);
        }
    }

    private void loadDirectShareIcon(SelectableTargetInfo info) {
        if (mRequestedIcons.add(info)) {
            mTargetDataLoader.loadDirectShareIcon(
                    info,
                    getUserHandle(),
                    (drawable) -> onDirectShareIconLoaded(info, drawable));
        }
    }

    private void onDirectShareIconLoaded(SelectableTargetInfo mTargetInfo, Drawable icon) {
        if (icon != null && !mTargetInfo.hasDisplayIcon()) {
            mTargetInfo.getDisplayIconHolder().setDisplayIcon(icon);
            notifyDataSetChanged();
        }
    }

    void updateAlphabeticalList() {
        // TODO: this procedure seems like it should be relatively lightweight. Why does it need to
        // run in an `AsyncTask`?
        new AsyncTask<Void, Void, List<DisplayResolveInfo>>() {
            @Override
            protected List<DisplayResolveInfo> doInBackground(Void... voids) {
                try {
                    Trace.beginSection("update-alphabetical-list");
                    return updateList();
                } finally {
                    Trace.endSection();
                }
            }

            private List<DisplayResolveInfo> updateList() {
                List<DisplayResolveInfo> allTargets = new ArrayList<>();
                allTargets.addAll(getTargetsInCurrentDisplayList());
                allTargets.addAll(mCallerTargets);

                // Consolidate multiple targets from same app.
                return allTargets
                        .stream()
                        .collect(Collectors.groupingBy(target ->
                                target.getResolvedComponentName().getPackageName()
                                + "#" + target.getDisplayLabel()
                                + '#' + target.getResolveInfo().userHandle.getIdentifier()
                        ))
                        .values()
                        .stream()
                        .map(appTargets ->
                                (appTargets.size() == 1)
                                ? appTargets.get(0)
                                : MultiDisplayResolveInfo.newMultiDisplayResolveInfo(appTargets))
                        .sorted(new ChooserActivity.AzInfoComparator(mContext))
                        .collect(Collectors.toList());
            }
            @Override
            protected void onPostExecute(List<DisplayResolveInfo> newList) {
                mSortedList = newList;
                notifyDataSetChanged();
            }
        }.execute();
    }

    @Override
    public int getCount() {
        return getRankedTargetCount() + getAlphaTargetCount()
                + getSelectableServiceTargetCount() + getCallerTargetCount();
    }

    @Override
    public int getUnfilteredCount() {
        int appTargets = super.getUnfilteredCount();
        if (appTargets > mMaxRankedTargets) {
            // TODO: what does this condition mean?
            appTargets = appTargets + mMaxRankedTargets;
        }
        return appTargets + getSelectableServiceTargetCount() + getCallerTargetCount();
    }


    public int getCallerTargetCount() {
        return mCallerTargets.size();
    }

    /**
     * Filter out placeholders and non-selectable service targets
     */
    public int getSelectableServiceTargetCount() {
        int count = 0;
        for (TargetInfo info : mServiceTargets) {
            if (info.isSelectableTargetInfo()) {
                count++;
            }
        }
        return count;
    }

    public int getServiceTargetCount() {
        if (mChooserRequest.isSendActionTarget() && !ActivityManager.isLowRamDeviceStatic()) {
            return Math.min(mServiceTargets.size(), mMaxRankedTargets);
        }

        return 0;
    }

    public int getAlphaTargetCount() {
        int groupedCount = mSortedList.size();
        int ungroupedCount = mCallerTargets.size() + getDisplayResolveInfoCount();
        return (ungroupedCount > mMaxRankedTargets) ? groupedCount : 0;
    }

    /**
     * Fetch ranked app target count
     */
    public int getRankedTargetCount() {
        int spacesAvailable = mMaxRankedTargets - getCallerTargetCount();
        return Math.min(spacesAvailable, super.getCount());
    }

    /** Get all the {@link DisplayResolveInfo} data for our targets. */
    public DisplayResolveInfo[] getDisplayResolveInfos() {
        int size = getDisplayResolveInfoCount();
        DisplayResolveInfo[] resolvedTargets = new DisplayResolveInfo[size];
        for (int i = 0; i < size; i++) {
            resolvedTargets[i] = getDisplayResolveInfo(i);
        }
        return resolvedTargets;
    }

    public int getPositionTargetType(int position) {
        int offset = 0;

        final int serviceTargetCount = getServiceTargetCount();
        if (position < serviceTargetCount) {
            return TARGET_SERVICE;
        }
        offset += serviceTargetCount;

        final int callerTargetCount = getCallerTargetCount();
        if (position - offset < callerTargetCount) {
            return TARGET_CALLER;
        }
        offset += callerTargetCount;

        final int rankedTargetCount = getRankedTargetCount();
        if (position - offset < rankedTargetCount) {
            return TARGET_STANDARD;
        }
        offset += rankedTargetCount;

        final int standardTargetCount = getAlphaTargetCount();
        if (position - offset < standardTargetCount) {
            return TARGET_STANDARD_AZ;
        }

        return TARGET_BAD;
    }

    @Override
    public TargetInfo getItem(int position) {
        return targetInfoForPosition(position, true);
    }

    /**
     * Find target info for a given position.
     * Since ChooserActivity displays several sections of content, determine which
     * section provides this item.
     */
    @Override
    public TargetInfo targetInfoForPosition(int position, boolean filtered) {
        if (position == NO_POSITION) {
            return null;
        }

        int offset = 0;

        // Direct share targets
        final int serviceTargetCount = filtered ? getServiceTargetCount() :
                getSelectableServiceTargetCount();
        if (position < serviceTargetCount) {
            return mServiceTargets.get(position);
        }
        offset += serviceTargetCount;

        // Targets provided by calling app
        final int callerTargetCount = getCallerTargetCount();
        if (position - offset < callerTargetCount) {
            return mCallerTargets.get(position - offset);
        }
        offset += callerTargetCount;

        // Ranked standard app targets
        final int rankedTargetCount = getRankedTargetCount();
        if (position - offset < rankedTargetCount) {
            return filtered ? super.getItem(position - offset)
                    : getDisplayResolveInfo(position - offset);
        }
        offset += rankedTargetCount;

        // Alphabetical complete app target list.
        if (position - offset < getAlphaTargetCount() && !mSortedList.isEmpty()) {
            return mSortedList.get(position - offset);
        }

        return null;
    }

    // Check whether {@code dri} should be added into mDisplayList.
    @Override
    protected boolean shouldAddResolveInfo(DisplayResolveInfo dri) {
        // Checks if this info is already listed in callerTargets.
        for (TargetInfo existingInfo : mCallerTargets) {
            if (mResolverListCommunicator.resolveInfoMatch(
                    dri.getResolveInfo(), existingInfo.getResolveInfo())) {
                return false;
            }
        }
        return super.shouldAddResolveInfo(dri);
    }

    /**
     * Fetch surfaced direct share target info
     */
    public List<TargetInfo> getSurfacedTargetInfo() {
        return mServiceTargets.subList(0,
                Math.min(mMaxRankedTargets, getSelectableServiceTargetCount()));
    }


    /**
     * Evaluate targets for inclusion in the direct share area. May not be included
     * if score is too low.
     */
    public void addServiceResults(
            @Nullable DisplayResolveInfo origTarget,
            List<ChooserTarget> targets,
            @ChooserActivity.ShareTargetType int targetType,
            Map<ChooserTarget, ShortcutInfo> directShareToShortcutInfos,
            Map<ChooserTarget, AppTarget> directShareToAppTargets) {
        // Avoid inserting any potentially late results.
        if ((mServiceTargets.size() == 1) && mServiceTargets.get(0).isEmptyTargetInfo()) {
            return;
        }
        boolean isShortcutResult = targetType == TARGET_TYPE_SHORTCUTS_FROM_SHORTCUT_MANAGER
                || targetType == TARGET_TYPE_SHORTCUTS_FROM_PREDICTION_SERVICE;
        boolean isUpdated = mShortcutSelectionLogic.addServiceResults(
                origTarget,
                getBaseScore(origTarget, targetType),
                targets,
                isShortcutResult,
                directShareToShortcutInfos,
                directShareToAppTargets,
                mContext.createContextAsUser(getUserHandle(), 0),
                mChooserRequest.getTargetIntent(),
                mChooserRequest.getReferrerFillInIntent(),
                mMaxRankedTargets,
                mServiceTargets);
        if (isUpdated) {
            notifyDataSetChanged();
        }
    }

    /**
     * Use the scoring system along with artificial boosts to create up to 4 distinct buckets:
     * <ol>
     *   <li>App-supplied targets
     *   <li>Shortcuts ranked via App Prediction Manager
     *   <li>Shortcuts ranked via legacy heuristics
     *   <li>Legacy direct share targets
     * </ol>
     */
    public float getBaseScore(
            DisplayResolveInfo target,
            @ChooserActivity.ShareTargetType int targetType) {
        if (target == null) {
            return CALLER_TARGET_SCORE_BOOST;
        }
        float score = super.getScore(target);
        if (targetType == TARGET_TYPE_SHORTCUTS_FROM_SHORTCUT_MANAGER
                || targetType == TARGET_TYPE_SHORTCUTS_FROM_PREDICTION_SERVICE) {
            return score * SHORTCUT_TARGET_SCORE_BOOST;
        }
        return score;
    }

    /**
     * Calling this marks service target loading complete, and will attempt to no longer
     * update the direct share area.
     */
    public void completeServiceTargetLoading() {
        mServiceTargets.removeIf(o -> o.isPlaceHolderTargetInfo());
        if (mServiceTargets.isEmpty()) {
            mServiceTargets.add(NotSelectableTargetInfo.newEmptyTargetInfo());
            mEventLog.logSharesheetEmptyDirectShareRow();
        }
        notifyDataSetChanged();
    }

    /**
     * Rather than fully sorting the input list, this sorting task will put the top k elements
     * in the head of input list and fill the tail with other elements in undetermined order.
     */
    @Override
    AsyncTask<List<ResolvedComponentInfo>,
                Void,
                List<ResolvedComponentInfo>> createSortingTask(boolean doPostProcessing) {
        return new AsyncTask<List<ResolvedComponentInfo>,
                Void,
                List<ResolvedComponentInfo>>() {
            @Override
            protected List<ResolvedComponentInfo> doInBackground(
                    List<ResolvedComponentInfo>... params) {
                Trace.beginSection("ChooserListAdapter#SortingTask");
                mResolverListController.topK(params[0], mMaxRankedTargets);
                Trace.endSection();
                return params[0];
            }
            @Override
            protected void onPostExecute(List<ResolvedComponentInfo> sortedComponents) {
                processSortedList(sortedComponents, doPostProcessing);
                if (doPostProcessing) {
                    mResolverListCommunicator.updateProfileViewButton();
                    notifyDataSetChanged();
                }
            }
        };
    }

}