1 /*
2  * Copyright (C) 2019 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.intentresolver.chooser;
18 
19 
20 import android.app.Activity;
21 import android.app.prediction.AppTarget;
22 import android.content.ComponentName;
23 import android.content.Context;
24 import android.content.Intent;
25 import android.content.SharedPreferences;
26 import android.content.pm.ResolveInfo;
27 import android.content.pm.ShortcutInfo;
28 import android.content.pm.ShortcutManager;
29 import android.graphics.drawable.Drawable;
30 import android.os.Bundle;
31 import android.os.UserHandle;
32 import android.service.chooser.ChooserTarget;
33 import android.text.TextUtils;
34 import android.util.HashedStringCache;
35 
36 import androidx.annotation.Nullable;
37 
38 import com.android.intentresolver.ChooserListAdapter;
39 import com.android.intentresolver.ChooserRefinementManager;
40 import com.android.intentresolver.ResolverActivity;
41 
42 import java.util.ArrayList;
43 import java.util.List;
44 import java.util.Objects;
45 
46 /**
47  * A single target as represented in the chooser.
48  */
49 public interface TargetInfo {
50 
51     /**
52      * Container for a {@link TargetInfo}'s (potentially) mutable icon state. This is provided to
53      * encapsulate the state so that the {@link TargetInfo} itself can be "immutable" (in some
54      * sense) as long as it always returns the same {@link IconHolder} instance.
55      *
56      * TODO: move "stateful" responsibilities out to clients; for more info see the Javadoc comment
57      * on {@link #getDisplayIconHolder()}.
58      */
59     interface IconHolder {
60         /** @return the icon (if it's already loaded, or statically available), or null. */
61         @Nullable
getDisplayIcon()62         Drawable getDisplayIcon();
63 
64         /**
65          * @param icon the icon to return on subsequent calls to {@link #getDisplayIcon()}.
66          * Implementations may discard this request as a no-op if they don't support setting.
67          */
setDisplayIcon(Drawable icon)68         void setDisplayIcon(Drawable icon);
69     }
70 
71     /** A simple mutable-container implementation of {@link IconHolder}. */
72     final class SettableIconHolder implements IconHolder {
73         @Nullable
74         private Drawable mDisplayIcon;
75 
76         @Nullable
getDisplayIcon()77         public Drawable getDisplayIcon() {
78             return mDisplayIcon;
79         }
80 
setDisplayIcon(Drawable icon)81         public void setDisplayIcon(Drawable icon) {
82             mDisplayIcon = icon;
83         }
84     }
85 
86     /**
87      * Get the resolved intent that represents this target. Note that this may not be the
88      * intent that will be launched by calling one of the <code>start</code> methods provided;
89      * this is the intent that will be credited with the launch.
90      *
91      * @return the resolved intent for this target
92      */
getResolvedIntent()93     Intent getResolvedIntent();
94 
95     /**
96      * Get the target intent, the one that will be used with one of the <code>start</code> methods.
97      * @return the intent with target will be launced with.
98      */
getTargetIntent()99     @Nullable Intent getTargetIntent();
100 
101     /**
102      * Get the resolved component name that represents this target. Note that this may not
103      * be the component that will be directly launched by calling one of the <code>start</code>
104      * methods provided; this is the component that will be credited with the launch. This may be
105      * null if the target was specified by a caller-provided {@link ChooserTarget} that we failed to
106      * resolve to a component on the system.
107      *
108      * @return the resolved ComponentName for this target
109      */
110     @Nullable
getResolvedComponentName()111     ComponentName getResolvedComponentName();
112 
113     /**
114      * If this target was historically built from a (now-deprecated) {@link ChooserTarget} record,
115      * get the {@link ComponentName} that would've been provided by that record.
116      *
117      * TODO: for (historical) {@link ChooserTargetInfo} targets, this differs from the result of
118      * {@link #getResolvedComponentName()} only for caller-provided targets that we fail to resolve;
119      * then this returns the name of the component that was requested, and the other returns null.
120      * At the time of writing, this method is only called in contexts where the client knows that
121      * the target was a historical {@link ChooserTargetInfo}. Thus this method could be removed and
122      * all clients consolidated on the other, if we have some alternate mechanism of tracking this
123      * discrepancy; or if we know that the distinction won't apply in the conditions when we call
124      * this method; or if we determine that tracking the distinction isn't a requirement for us.
125      */
126     @Nullable
getChooserTargetComponentName()127     default ComponentName getChooserTargetComponentName() {
128         return null;
129     }
130 
131     /**
132      * Start the activity referenced by this target as if the Activity's caller was performing the
133      * start operation.
134      *
135      * @param activity calling Activity (actually) performing the launch
136      * @param options ActivityOptions bundle
137      * @param userId userId to start as or {@link UserHandle#USER_NULL} for activity's caller
138      * @return true if the start completed successfully
139      */
startAsCaller(Activity activity, Bundle options, int userId)140     boolean startAsCaller(Activity activity, Bundle options, int userId);
141 
142     /**
143      * Start the activity referenced by this target as a given user.
144      *
145      * @param activity calling activity performing the launch
146      * @param options ActivityOptions bundle
147      * @param user handle for the user to start the activity as
148      * @return true if the start completed successfully
149      */
startAsUser(Activity activity, Bundle options, UserHandle user)150     boolean startAsUser(Activity activity, Bundle options, UserHandle user);
151 
152     /**
153      * Return the ResolveInfo about how and why this target matched the original query
154      * for available targets.
155      *
156      * @return ResolveInfo representing this target's match
157      */
getResolveInfo()158     ResolveInfo getResolveInfo();
159 
160     /**
161      * Return the human-readable text label for this target.
162      *
163      * @return user-visible target label
164      */
getDisplayLabel()165     CharSequence getDisplayLabel();
166 
167     /**
168      * Return any extended info for this target. This may be used to disambiguate
169      * otherwise identical targets.
170      *
171      * @return human-readable disambig string or null if none present
172      */
getExtendedInfo()173     CharSequence getExtendedInfo();
174 
175     /**
176      * @return the {@link IconHolder} for the icon used to represent this target, including badge.
177      *
178      * TODO: while the {@link TargetInfo} may be immutable in always returning the same instance of
179      * {@link IconHolder} here, the holder itself is mutable state, and could become a problem if we
180      * ever rely on {@link TargetInfo} immutability elsewhere. Ideally, the {@link TargetInfo}
181      * should provide an immutable "spec" that tells clients <em>how</em> to load the appropriate
182      * icon, while leaving the load itself to some external component.
183      */
getDisplayIconHolder()184     IconHolder getDisplayIconHolder();
185 
186     /**
187      * @return true if display icon is available.
188      */
hasDisplayIcon()189     default boolean hasDisplayIcon() {
190         return getDisplayIconHolder().getDisplayIcon() != null;
191     }
192 
193     /**
194      * Attempt to apply a {@code proposedRefinement} that the {@link ChooserRefinementManager}
195      * received from the caller's refinement flow. This may succeed only if the target has a source
196      * intent that matches the filtering parameters of the proposed refinement (according to
197      * {@link Intent#filterEquals}). Then the first such match is the "base intent," and the
198      * proposed refinement is merged into that base (via {@link Intent#fillIn}; this can never
199      * result in a change to the {@link Intent#filterEquals} status of the base, but may e.g. add
200      * new "extras" that weren't previously given in the base intent).
201      *
202      * @return a copy of this {@link TargetInfo} where the "base intent to send" is the result of
203      * merging the refinement into the best-matching source intent, if possible. If there is no
204      * suitable match for the proposed refinement, or if merging fails for any other reason, this
205      * returns null.
206      *
207      * @see android.content.Intent#fillIn(Intent, int)
208      */
209     @Nullable
tryToCloneWithAppliedRefinement(Intent proposedRefinement)210     TargetInfo tryToCloneWithAppliedRefinement(Intent proposedRefinement);
211 
212     /**
213      * @return the list of supported source intents deduped against this single target
214      */
getAllSourceIntents()215     List<Intent> getAllSourceIntents();
216 
217     /**
218      * @return the one or more {@link DisplayResolveInfo}s that this target represents in the UI.
219      *
220      * TODO: clarify the semantics of the {@link DisplayResolveInfo} branch of {@link TargetInfo}'s
221      * class hierarchy. Why is it that {@link MultiDisplayResolveInfo} can stand in for some
222      * "virtual" {@link DisplayResolveInfo} targets that aren't individually represented in the UI,
223      * but OTOH a {@link ChooserTargetInfo} (which doesn't inherit from {@link DisplayResolveInfo})
224      * can't provide its own UI treatment, and instead needs us to reach into its composed-in
225      * info via {@link #getDisplayResolveInfo()}? It seems like {@link DisplayResolveInfo} may be
226      * required to populate views in our UI, while {@link ChooserTargetInfo} may carry some other
227      * metadata. For non-{@link ChooserTargetInfo} targets (e.g. in {@link ResolverActivity}) the
228      * "naked" {@link DisplayResolveInfo} might also be taken to provide some of this metadata, but
229      * this presents a denormalization hazard since the "UI info" ({@link DisplayResolveInfo}) that
230      * represents a {@link ChooserTargetInfo} might provide different values than its enclosing
231      * {@link ChooserTargetInfo} (as they both implement {@link TargetInfo}). We could try to
232      * address this by splitting {@link DisplayResolveInfo} into two types; one (which implements
233      * the same {@link TargetInfo} interface as {@link ChooserTargetInfo}) provides the previously-
234      * implicit "metadata", and the other provides only the UI treatment for a target of any type
235      * (taking over the respective methods that previously belonged to {@link TargetInfo}).
236      */
getAllDisplayTargets()237     ArrayList<DisplayResolveInfo> getAllDisplayTargets();
238 
239     /**
240      * @return true if this target cannot be selected by the user
241      */
isSuspended()242     boolean isSuspended();
243 
244     /**
245      * @return true if this target should be pinned to the front by the request of the user
246      */
isPinned()247     boolean isPinned();
248 
249     /**
250      * Determine whether two targets represent "similar" content that could be de-duped.
251      * Note an earlier version of this code cautioned maintainers,
252      * "do not label as 'equals', since this doesn't quite work as intended with java 8."
253      * This seems to refer to the rule that interfaces can't provide defaults that conflict with the
254      * definitions of "real" methods in {@code java.lang.Object}, and (if desired) it could be
255      * presumably resolved by converting {@code TargetInfo} from an interface to an abstract class.
256      */
isSimilar(TargetInfo other)257     default boolean isSimilar(TargetInfo other) {
258         if (other == null) {
259             return false;
260         }
261 
262         // TODO: audit usage and try to reconcile a behavior that doesn't depend on the legacy
263         // subclass type. Note that the `isSimilar()` method was pulled up from the legacy
264         // `ChooserTargetInfo`, so no legacy behavior currently depends on calling `isSimilar()` on
265         // an instance where `isChooserTargetInfo()` would return false (although technically it may
266         // have been possible for the `other` target to be of a different type). Thus we have
267         // flexibility in defining the similarity conditions between pairs of non "chooser" targets.
268         if (isChooserTargetInfo()) {
269             return other.isChooserTargetInfo()
270                     && Objects.equals(
271                             getChooserTargetComponentName(), other.getChooserTargetComponentName())
272                     && TextUtils.equals(getDisplayLabel(), other.getDisplayLabel())
273                     && TextUtils.equals(getExtendedInfo(), other.getExtendedInfo());
274         } else {
275             return !other.isChooserTargetInfo() && Objects.equals(this, other);
276         }
277     }
278 
279     /**
280      * @return the target score, including any Chooser-specific modifications that may have been
281      * applied (either overriding by special-case for "non-selectable" targets, or by twiddling the
282      * scores of "selectable" targets in {@link ChooserListAdapter}). Higher scores are "better."
283      * Targets that aren't intended for ranking/scoring should return a negative value.
284      */
getModifiedScore()285     default float getModifiedScore() {
286         return -0.1f;
287     }
288 
289     /**
290      * @return the {@link ShortcutInfo} for any shortcut associated with this target.
291      */
292     @Nullable
getDirectShareShortcutInfo()293     default ShortcutInfo getDirectShareShortcutInfo() {
294         return null;
295     }
296 
297     /**
298      * @return the ID of the shortcut represented by this target, or null if the target didn't come
299      * from a {@link ShortcutManager} shortcut.
300      */
301     @Nullable
getDirectShareShortcutId()302     default String getDirectShareShortcutId() {
303         ShortcutInfo shortcut = getDirectShareShortcutInfo();
304         if (shortcut == null) {
305             return null;
306         }
307         return shortcut.getId();
308     }
309 
310     /**
311      * @return the {@link AppTarget} metadata if this target was sourced from App Prediction
312      * service, or null otherwise.
313      */
314     @Nullable
getDirectShareAppTarget()315     default AppTarget getDirectShareAppTarget() {
316         return null;
317     }
318 
319     /**
320      * Get more info about this target in the form of a {@link DisplayResolveInfo}, if available.
321      * TODO: this seems to return non-null only for ChooserTargetInfo subclasses. Determine the
322      * meaning of a TargetInfo (ChooserTargetInfo) embedding another kind of TargetInfo
323      * (DisplayResolveInfo) in this way, and - at least - improve this documentation; OTOH this
324      * probably indicates an opportunity to simplify or better separate these APIs. (For example,
325      * targets that <em>don't</em> descend from ChooserTargetInfo instead descend directly from
326      * DisplayResolveInfo; should they return `this`? Do we always use DisplayResolveInfo to
327      * represent visual properties, and then either assume some implicit metadata properties *or*
328      * embed that visual representation within a ChooserTargetInfo to carry additional metadata? If
329      * that's the case, maybe we could decouple by saying that all TargetInfos compose-in their
330      * visual representation [as a DisplayResolveInfo, now the root of its own class hierarchy] and
331      * then add a new TargetInfo type that explicitly represents the "implicit metadata" that we
332      * previously assumed for "naked DisplayResolveInfo targets" that weren't wrapped as
333      * ChooserTargetInfos. Or does all this complexity disappear once we stop relying on the
334      * deprecated ChooserTarget type?)
335      */
336     @Nullable
getDisplayResolveInfo()337     default DisplayResolveInfo getDisplayResolveInfo() {
338         return null;
339     }
340 
341     /**
342      * @return true if this target represents a legacy {@code ChooserTargetInfo}. These objects were
343      * historically documented as representing "[a] TargetInfo for Direct Share." However, not all
344      * of these targets are actually *valid* for direct share; e.g. some represent "empty" items
345      * (although perhaps only for display in the Direct Share UI?). In even earlier versions, these
346      * targets may also have been results from peers in the (now-deprecated/unsupported)
347      * {@code ChooserTargetService} ecosystem; even though we no longer use these services, we're
348      * still shoehorning other target data into the deprecated {@link ChooserTarget} structure for
349      * compatibility with some internal APIs.
350      * TODO: refactor to clarify the semantics of any target for which this method returns true
351      * (e.g., are they characterized by their application in the Direct Share UI?), and to remove
352      * the scaffolding that adapts to and from the {@link ChooserTarget} structure. Eventually, we
353      * expect to remove this method (and others that strictly indicate legacy subclass roles) in
354      * favor of a more semantic design that expresses the purpose and distinctions in those roles.
355      */
isChooserTargetInfo()356     default boolean isChooserTargetInfo() {
357         return false;
358     }
359 
360     /**
361      * @return true if this target represents a legacy {@code DisplayResolveInfo}. These objects
362      * were historically documented as an augmented "TargetInfo plus additional information needed
363      * to render it (such as icon and label) and resolve it to an activity." That description in no
364      * way distinguishes from the base {@code TargetInfo} API. At the time of writing, these objects
365      * are most-clearly defined by their opposite; this returns true for exactly those instances of
366      * {@code TargetInfo} where {@link #isChooserTargetInfo()} returns false (these conditions are
367      * complementary because they correspond to the immediate {@code TargetInfo} child types that
368      * historically partitioned all concrete {@code TargetInfo} implementations). These may(?)
369      * represent any target displayed somewhere other than the Direct Share UI.
370      */
isDisplayResolveInfo()371     default boolean isDisplayResolveInfo() {
372         return false;
373     }
374 
375     /**
376      * @return true if this target represents a legacy {@code MultiDisplayResolveInfo}. These
377      * objects were historically documented as representing "a 'stack' of chooser targets for
378      * various activities within the same component." For historical reasons this currently can
379      * return true only if {@link #isDisplayResolveInfo()} returns true (because the legacy classes
380      * shared an inheritance relationship), but new code should avoid relying on that relationship
381      * since these APIs are "in transition."
382      */
isMultiDisplayResolveInfo()383     default boolean isMultiDisplayResolveInfo() {
384         return false;
385     }
386 
387     /**
388      * @return true if this target represents a legacy {@code SelectableTargetInfo}. Note that this
389      * is defined for legacy compatibility and may not conform to other notions of a "selectable"
390      * target. For historical reasons, this method and {@link #isNotSelectableTargetInfo()} only
391      * partition the {@code TargetInfo} instances for which {@link #isChooserTargetInfo()} returns
392      * true; otherwise <em>both</em> methods return false.
393      * TODO: define selectability for targets not historically from {@code ChooserTargetInfo},
394      * then attempt to replace this with a new method like {@code TargetInfo#isSelectable()} that
395      * actually partitions <em>all</em> target types (after updating client usage as needed).
396      */
isSelectableTargetInfo()397     default boolean isSelectableTargetInfo() {
398         return false;
399     }
400 
401     /**
402      * @return true if this target represents a legacy {@code NotSelectableTargetInfo} (i.e., a
403      * target where {@link #isChooserTargetInfo()} is true but {@link #isSelectableTargetInfo()} is
404      * false). For more information on how this divides the space of targets, see the Javadoc for
405      * {@link #isSelectableTargetInfo()}.
406      */
isNotSelectableTargetInfo()407     default boolean isNotSelectableTargetInfo() {
408         return false;
409     }
410 
411     /**
412      * @return true if this target represents a legacy {@code ChooserActivity#EmptyTargetInfo}. Note
413      * that this is defined for legacy compatibility and may not conform to other notions of an
414      * "empty" target.
415      */
isEmptyTargetInfo()416     default boolean isEmptyTargetInfo() {
417         return false;
418     }
419 
420     /**
421      * @return true if this target represents a legacy {@code ChooserActivity#PlaceHolderTargetInfo}
422      * (defined only for compatibility with historic use in {@link ChooserListAdapter}). For
423      * historic reasons (owing to a legacy subclass relationship) this can return true only if
424      * {@link #isNotSelectableTargetInfo()} also returns true.
425      */
isPlaceHolderTargetInfo()426     default boolean isPlaceHolderTargetInfo() {
427         return false;
428     }
429 
430     /**
431      * @return true if this target should be logged with the "direct_share" metrics category in
432      * {@link ResolverActivity#maybeLogCrossProfileTargetLaunch}. This is defined for legacy
433      * compatibility and is <em>not</em> likely to be a good indicator of whether this is actually a
434      * "direct share" target (e.g. because it historically also applies to "empty" and "placeholder"
435      * targets).
436      */
isInDirectShareMetricsCategory()437     default boolean isInDirectShareMetricsCategory() {
438         return isChooserTargetInfo();
439     }
440 
441     /**
442      * @param context caller's context, to provide the {@link SharedPreferences} for use by the
443      * {@link HashedStringCache}.
444      * @return a hashed ID that should be logged along with our target-selection metrics, or null.
445      * The contents of the plaintext are defined for historical reasons, "the package name + target
446      * name to answer the question if most users share to mostly the same person
447      * or to a bunch of different people." Clients should consider this as opaque data for logging
448      * only; they should not rely on any particular semantics about the value.
449      */
getHashedTargetIdForMetrics(Context context)450     default HashedStringCache.HashResult getHashedTargetIdForMetrics(Context context) {
451         return null;
452     }
453 
454     /**
455      * Fix the URIs in {@code intent} if cross-profile sharing is required. This should be called
456      * before launching the intent as another user.
457      */
prepareIntentForCrossProfileLaunch(Intent intent, int targetUserId)458     static void prepareIntentForCrossProfileLaunch(Intent intent, int targetUserId) {
459         final int currentUserId = UserHandle.myUserId();
460         if (targetUserId != currentUserId) {
461             intent.fixUris(currentUserId);
462         }
463     }
464 
465     /**
466      * Derive a "complete" intent from a proposed `refinement` intent by merging it into a matching
467      * `base` intent, without modifying the filter-equality properties of the `base` intent, while
468      * still allowing the `refinement` to replace Share "payload" fields.
469      * Note! Callers are responsible for ensuring that the `base` is a suitable match for the given
470      * `refinement`, such that the two can be merged without modifying filter-equality properties.
471      */
mergeRefinementIntoMatchingBaseIntent(Intent base, Intent refinement)472     static Intent mergeRefinementIntoMatchingBaseIntent(Intent base, Intent refinement) {
473         Intent mergedIntent = new Intent(base);
474 
475         /* Copy over any fields from the `refinement` that weren't already specified by the `base`,
476          * along with the refined ClipData (if present, even if that overwrites data given in the
477          * `base` intent).
478          *
479          * Refinement may have modified the payload content stored in the ClipData; such changes
480          * are permitted in refinement since ClipData isn't a factor in the determination of
481          * `Intent.filterEquals()` (which must be preserved as an invariant of refinement). */
482         mergedIntent.fillIn(refinement, Intent.FILL_IN_CLIP_DATA);
483 
484         /* Refinement may also modify payload content held in the 'extras' representation, as again
485          * those attributes aren't a factor in determining filter-equality. There is no `FILL_IN_*`
486          * flag that would allow the refinement to overwrite existing keys in the `base` extras, so
487          * here we have to implement the logic ourselves.
488          *
489          * Note this still doesn't imply that the refined intent is the final authority on extras;
490          * in particular, `SelectableTargetInfo.mActivityStarter` uses `Intent.putExtras(Bundle)` to
491          * merge in the `mChooserTargetIntentExtras` (i.e., the `EXTRA_SHORTCUT_ID`), which will
492          * overwrite any existing value.
493          *
494          * TODO: formalize the precedence and make sure extras are set in the appropriate stages,
495          * instead of relying on maintainers to know that (e.g.) authoritative changes belong in the
496          * `TargetActivityStarter`. Otherwise, any extras-based data that Sharesheet adds internally
497          * might be susceptible to "spoofing" from the refinement activity. */
498         mergedIntent.putExtras(refinement);  // Re-merge extras to favor refinement.
499 
500         // TODO(b/279067078): consider how to populate the "merged" ClipData. The `base`
501         // already has non-null ClipData due to the implicit migration in Intent, so if the
502         // refinement modified any of the payload extras, they *must* also provide a modified
503         // ClipData, or else the updated "extras" payload will be inconsistent with the
504         // pre-refinement ClipData when they're merged together. We may be able to do better,
505         // but there are complicated tradeoffs.
506 
507         return mergedIntent;
508     }
509 }
510