• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright (c) 2010, 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 android.content;
18 
19 import android.annotation.FloatRange;
20 import android.annotation.IntDef;
21 import android.annotation.NonNull;
22 import android.os.Bundle;
23 import android.os.Parcel;
24 import android.os.Parcelable;
25 import android.os.PersistableBundle;
26 import android.text.TextUtils;
27 import android.util.ArrayMap;
28 import android.util.TimeUtils;
29 import android.util.proto.ProtoOutputStream;
30 import android.view.textclassifier.TextClassifier;
31 import android.view.textclassifier.TextLinks;
32 
33 import java.lang.annotation.Retention;
34 import java.lang.annotation.RetentionPolicy;
35 import java.util.ArrayList;
36 import java.util.Arrays;
37 import java.util.Map;
38 
39 /**
40  * Meta-data describing the contents of a {@link ClipData}.  Provides enough
41  * information to know if you can handle the ClipData, but not the data
42  * itself.
43  *
44  * <div class="special reference">
45  * <h3>Developer Guides</h3>
46  * <p>For more information about using the clipboard framework, read the
47  * <a href="{@docRoot}guide/topics/clipboard/copy-paste.html">Copy and Paste</a>
48  * developer guide.</p>
49  * </div>
50  */
51 @android.ravenwood.annotation.RavenwoodKeepWholeClass
52 public class ClipDescription implements Parcelable {
53     /**
54      * The MIME type for a clip holding plain text.
55      */
56     public static final String MIMETYPE_TEXT_PLAIN = "text/plain";
57 
58     /**
59      * The MIME type for a clip holding HTML text.
60      */
61     public static final String MIMETYPE_TEXT_HTML = "text/html";
62 
63     /**
64      * The MIME type for a clip holding one or more URIs.  This should be
65      * used for URIs that are meaningful to a user (such as an http: URI).
66      * It should <em>not</em> be used for a content: URI that references some
67      * other piece of data; in that case the MIME type should be the type
68      * of the referenced data.
69      */
70     public static final String MIMETYPE_TEXT_URILIST = "text/uri-list";
71 
72     /**
73      * The MIME type for a clip holding an Intent.
74      */
75     public static final String MIMETYPE_TEXT_INTENT = "text/vnd.android.intent";
76 
77     /**
78      * The MIME type for an activity. The ClipData must include intents with required extras
79      * {@link #EXTRA_PENDING_INTENT} and {@link Intent#EXTRA_USER}, and an optional
80      * {@link #EXTRA_ACTIVITY_OPTIONS}.
81      * @hide
82      */
83     public static final String MIMETYPE_APPLICATION_ACTIVITY = "application/vnd.android.activity";
84 
85     /**
86      * The MIME type for a shortcut. The ClipData must include intents with required extras
87      * {@link Intent#EXTRA_SHORTCUT_ID}, {@link Intent#EXTRA_PACKAGE_NAME} and
88      * {@link Intent#EXTRA_USER}, and an optional {@link #EXTRA_ACTIVITY_OPTIONS}.
89      * @hide
90      */
91     public static final String MIMETYPE_APPLICATION_SHORTCUT = "application/vnd.android.shortcut";
92 
93     /**
94      * The MIME type for a task. The ClipData must include an intent with a required extra
95      * {@link Intent#EXTRA_TASK_ID} of the task to launch.
96      * @hide
97      */
98     public static final String MIMETYPE_APPLICATION_TASK = "application/vnd.android.task";
99 
100     /**
101      * The MIME type for data whose type is otherwise unknown.
102      * <p>
103      * Per RFC 2046, the "application" media type is to be used for discrete
104      * data which do not fit in any of the other categories, and the
105      * "octet-stream" subtype is used to indicate that a body contains arbitrary
106      * binary data.
107      */
108     public static final String MIMETYPE_UNKNOWN = "application/octet-stream";
109 
110     /**
111      * The pending intent for the activity to launch.
112      * <p>
113      * Type: PendingIntent
114      * </p>
115      * @hide
116      */
117     public static final String EXTRA_PENDING_INTENT = "android.intent.extra.PENDING_INTENT";
118 
119     /**
120      * The activity options bundle to use when launching an activity.
121      * <p>
122      * Type: Bundle
123      * </p>
124      * @hide
125      */
126     public static final String EXTRA_ACTIVITY_OPTIONS = "android.intent.extra.ACTIVITY_OPTIONS";
127 
128     /**
129      * An instance id used for logging.
130      * <p>
131      * Type: {@link com.android.internal.logging.InstanceId}
132      * </p>
133      * @hide
134      */
135     public static final String EXTRA_LOGGING_INSTANCE_ID =
136             "android.intent.extra.LOGGING_INSTANCE_ID";
137 
138     /**
139      * The id of the task containing the window that initiated the drag that should be hidden.
140      * Only provided to internal drag handlers as a part of the DRAG_START event.
141      * @hide
142      */
143     public static final String EXTRA_HIDE_DRAG_SOURCE_TASK_ID =
144             "android.intent.extra.HIDE_DRAG_SOURCE_TASK_ID";
145 
146     /**
147      * Indicates that a ClipData contains potentially sensitive information, such as a
148      * password or credit card number.
149      * <p>
150      * Type: boolean
151      * <p>
152      * This extra can be used to indicate that a ClipData contains sensitive information that
153      * should be redacted or hidden from view until a user takes explicit action to reveal it
154      * (e.g., by pasting).
155      * <p>
156      * Adding this extra does not change clipboard behavior or add additional security to
157      * the ClipData. Its purpose is essentially a rendering hint from the source application,
158      * asking that the data within be obfuscated or redacted, unless the user has taken action
159      * to make it visible.
160      */
161     public static final String EXTRA_IS_SENSITIVE = "android.content.extra.IS_SENSITIVE";
162 
163     /** Indicates that a ClipData's source is a remote device.
164      * <p>
165      *     Type: boolean
166      * <p>
167      *     This extra can be used to indicate that a ClipData comes from a separate device rather
168      *     than being local. It is a rendering hint that can be used to take different behavior
169      *     based on the source device of copied data.
170      */
171     public static final String EXTRA_IS_REMOTE_DEVICE = "android.content.extra.IS_REMOTE_DEVICE";
172 
173     /** @hide */
174     @Retention(RetentionPolicy.SOURCE)
175     @IntDef(value =
176             { CLASSIFICATION_NOT_COMPLETE, CLASSIFICATION_NOT_PERFORMED, CLASSIFICATION_COMPLETE})
177     @interface ClassificationStatus {}
178 
179     /**
180      * Value returned by {@link #getConfidenceScore(String)} if text classification has not been
181      * completed on the associated clip. This will be always be the case if the clip has not been
182      * copied to clipboard, or if there is no associated clip.
183      */
184     public static final int CLASSIFICATION_NOT_COMPLETE = 1;
185 
186     /**
187      * Value returned by {@link #getConfidenceScore(String)} if text classification was not and will
188      * not be performed on the associated clip. This may be the case if the clip does not contain
189      * text in its first item, or if the text is too long.
190      */
191     public static final int CLASSIFICATION_NOT_PERFORMED = 2;
192 
193     /**
194      * Value returned by {@link #getConfidenceScore(String)} if text classification has been
195      * completed.
196      */
197     public static final int CLASSIFICATION_COMPLETE = 3;
198 
199     final CharSequence mLabel;
200     private final ArrayList<String> mMimeTypes;
201     private PersistableBundle mExtras;
202     private long mTimeStamp;
203     private boolean mIsStyledText;
204     private final ArrayMap<String, Float> mEntityConfidence = new ArrayMap<>();
205     private int mClassificationStatus = CLASSIFICATION_NOT_COMPLETE;
206 
207     /**
208      * Create a new clip.
209      *
210      * @param label Label to show to the user describing this clip.
211      * @param mimeTypes An array of MIME types this data is available as.
212      */
ClipDescription(CharSequence label, String[] mimeTypes)213     public ClipDescription(CharSequence label, String[] mimeTypes) {
214         if (mimeTypes == null) {
215             throw new NullPointerException("mimeTypes is null");
216         }
217         mLabel = label;
218         mMimeTypes = new ArrayList<String>(Arrays.asList(mimeTypes));
219     }
220 
221     /**
222      * Create a copy of a ClipDescription.
223      */
ClipDescription(ClipDescription o)224     public ClipDescription(ClipDescription o) {
225         mLabel = o.mLabel;
226         mMimeTypes = new ArrayList<String>(o.mMimeTypes);
227         mTimeStamp = o.mTimeStamp;
228     }
229 
230     /**
231      * Helper to compare two MIME types, where one may be a pattern.
232      * @param concreteType A fully-specified MIME type.
233      * @param desiredType A desired MIME type that may be a pattern such as *&#47;*.
234      * @return Returns true if the two MIME types match.
235      */
compareMimeTypes(String concreteType, String desiredType)236     public static boolean compareMimeTypes(String concreteType, String desiredType) {
237         final int typeLength = desiredType.length();
238         if (typeLength == 3 && desiredType.equals("*/*")) {
239             return true;
240         }
241 
242         final int slashpos = desiredType.indexOf('/');
243         if (slashpos > 0) {
244             if (typeLength == slashpos+2 && desiredType.charAt(slashpos+1) == '*') {
245                 if (desiredType.regionMatches(0, concreteType, 0, slashpos+1)) {
246                     return true;
247                 }
248             } else if (desiredType.equals(concreteType)) {
249                 return true;
250             }
251         }
252 
253         return false;
254     }
255 
256     /**
257      * Used for setting the timestamp at which the associated {@link ClipData} is copied to
258      * global clipboard.
259      *
260      * @param timeStamp at which the associated {@link ClipData} is copied to clipboard in
261      *                  {@link System#currentTimeMillis()} time base.
262      * @hide
263      */
setTimestamp(long timeStamp)264     public void setTimestamp(long timeStamp) {
265         mTimeStamp = timeStamp;
266     }
267 
268     /**
269      * Return the timestamp at which the associated {@link ClipData} is copied to global clipboard
270      * in the {@link System#currentTimeMillis()} time base.
271      *
272      * @return timestamp at which the associated {@link ClipData} is copied to global clipboard
273      *         or {@code 0} if it is not copied to clipboard.
274      */
getTimestamp()275     public long getTimestamp() {
276         return mTimeStamp;
277     }
278 
279     /**
280      * Return the label for this clip.
281      */
getLabel()282     public CharSequence getLabel() {
283         return mLabel;
284     }
285 
286     /**
287      * Check whether the clip description contains the given MIME type.
288      *
289      * @param mimeType The desired MIME type.  May be a pattern.
290      * @return Returns true if one of the MIME types in the clip description
291      * matches the desired MIME type, else false.
292      */
hasMimeType(String mimeType)293     public boolean hasMimeType(String mimeType) {
294         final int size = mMimeTypes.size();
295         for (int i=0; i<size; i++) {
296             if (compareMimeTypes(mMimeTypes.get(i), mimeType)) {
297                 return true;
298             }
299         }
300         return false;
301     }
302 
303     /**
304      * Check whether the clip description contains any of the given MIME types.
305      *
306      * @param targetMimeTypes The target MIME types. May use patterns.
307      * @return Returns true if at least one of the MIME types in the clip description matches at
308      * least one of the target MIME types, else false.
309      *
310      * @hide
311      */
hasMimeType(@onNull String[] targetMimeTypes)312     public boolean hasMimeType(@NonNull String[] targetMimeTypes) {
313         for (String targetMimeType : targetMimeTypes) {
314             if (hasMimeType(targetMimeType)) {
315                 return true;
316             }
317         }
318         return false;
319     }
320 
321     /**
322      * Filter the clip description MIME types by the given MIME type.  Returns
323      * all MIME types in the clip that match the given MIME type.
324      *
325      * @param mimeType The desired MIME type.  May be a pattern.
326      * @return Returns an array of all matching MIME types.  If there are no
327      * matching MIME types, null is returned.
328      */
filterMimeTypes(String mimeType)329     public String[] filterMimeTypes(String mimeType) {
330         ArrayList<String> array = null;
331         final int size = mMimeTypes.size();
332         for (int i=0; i<size; i++) {
333             if (compareMimeTypes(mMimeTypes.get(i), mimeType)) {
334                 if (array == null) {
335                     array = new ArrayList<String>();
336                 }
337                 array.add(mMimeTypes.get(i));
338             }
339         }
340         if (array == null) {
341             return null;
342         }
343         String[] rawArray = new String[array.size()];
344         array.toArray(rawArray);
345         return rawArray;
346     }
347 
348     /**
349      * Return the number of MIME types the clip is available in.
350      */
getMimeTypeCount()351     public int getMimeTypeCount() {
352         return mMimeTypes.size();
353     }
354 
355     /**
356      * Return one of the possible clip MIME types.
357      */
getMimeType(int index)358     public String getMimeType(int index) {
359         return mMimeTypes.get(index);
360     }
361 
362     /**
363      * Add MIME types to the clip description.
364      */
addMimeTypes(String[] mimeTypes)365     void addMimeTypes(String[] mimeTypes) {
366         for (int i=0; i!=mimeTypes.length; i++) {
367             final String mimeType = mimeTypes[i];
368             if (!mMimeTypes.contains(mimeType)) {
369                 mMimeTypes.add(mimeType);
370             }
371         }
372     }
373 
374     /**
375      * Retrieve extended data from the clip description.
376      *
377      * @return the bundle containing extended data previously set with
378      * {@link #setExtras(PersistableBundle)}, or null if no extras have been set.
379      *
380      * @see #setExtras(PersistableBundle)
381      */
getExtras()382     public PersistableBundle getExtras() {
383         return mExtras;
384     }
385 
386     /**
387      * Add extended data to the clip description.
388      *
389      * @see #getExtras()
390      */
setExtras(PersistableBundle extras)391     public void setExtras(PersistableBundle extras) {
392         mExtras = new PersistableBundle(extras);
393     }
394 
395     /** @hide */
validate()396     public void validate() {
397         if (mMimeTypes == null) {
398             throw new NullPointerException("null mime types");
399         }
400         final int size = mMimeTypes.size();
401         if (size <= 0) {
402             throw new IllegalArgumentException("must have at least 1 mime type");
403         }
404         for (int i=0; i<size; i++) {
405             if (mMimeTypes.get(i) == null) {
406                 throw new NullPointerException("mime type at " + i + " is null");
407             }
408         }
409     }
410 
411     /**
412      * Returns true if the first item of the associated {@link ClipData} contains styled text, i.e.
413      * if it contains spans such as {@link android.text.style.CharacterStyle CharacterStyle}, {@link
414      * android.text.style.ParagraphStyle ParagraphStyle}, or {@link
415      * android.text.style.UpdateAppearance UpdateAppearance}. Returns false if it does not, or if
416      * there is no associated clip data.
417      */
isStyledText()418     public boolean isStyledText() {
419         return mIsStyledText;
420     }
421 
422     /**
423      * Sets whether the associated {@link ClipData} contains styled text in its first item. This
424      * should be called when this description is associated with clip data or when the first item
425      * is added to the associated clip data.
426      */
setIsStyledText(boolean isStyledText)427     void setIsStyledText(boolean isStyledText) {
428         mIsStyledText = isStyledText;
429     }
430 
431     /**
432      * Sets the current status of text classification for the associated clip.
433      *
434      * @hide
435      */
setClassificationStatus(@lassificationStatus int status)436     public void setClassificationStatus(@ClassificationStatus int status) {
437         mClassificationStatus = status;
438     }
439 
440     /**
441      * Returns a score indicating confidence that an instance of the given entity is present in the
442      * first item of the clip data, if that item is plain text and text classification has been
443      * performed. The value ranges from 0 (low confidence) to 1 (high confidence). 0 indicates that
444      * the entity was not found in the classified text.
445      *
446      * <p>Entities should be as defined in the {@link TextClassifier} class, such as
447      * {@link TextClassifier#TYPE_ADDRESS}, {@link TextClassifier#TYPE_URL}, or
448      * {@link TextClassifier#TYPE_EMAIL}.
449      *
450      * <p>If the result is positive for any entity, the full classification result as a
451      * {@link TextLinks} object may be obtained using the {@link ClipData.Item#getTextLinks()}
452      * method.
453      *
454      * @throws IllegalStateException if {@link #getClassificationStatus()} is not
455      * {@link #CLASSIFICATION_COMPLETE}
456      */
457     @FloatRange(from = 0.0, to = 1.0)
getConfidenceScore(@onNull @extClassifier.EntityType String entity)458     public float getConfidenceScore(@NonNull @TextClassifier.EntityType String entity) {
459         if (mClassificationStatus != CLASSIFICATION_COMPLETE) {
460             throw new IllegalStateException("Classification not complete");
461         }
462         return mEntityConfidence.getOrDefault(entity, 0f);
463     }
464 
465     /**
466      * Returns {@link #CLASSIFICATION_COMPLETE} if text classification has been performed on the
467      * associated {@link ClipData}. If this is the case then {@link #getConfidenceScore} may be used
468      * to retrieve information about entities within the text. Otherwise, returns
469      * {@link #CLASSIFICATION_NOT_COMPLETE} if classification has not yet returned results, or
470      * {@link #CLASSIFICATION_NOT_PERFORMED} if classification was not attempted (e.g. because the
471      * text was too long).
472      */
getClassificationStatus()473     public @ClassificationStatus int getClassificationStatus() {
474         return mClassificationStatus;
475     }
476 
477     /**
478      * @hide
479      */
setConfidenceScores(Map<String, Float> confidences)480     public void setConfidenceScores(Map<String, Float> confidences) {
481         mEntityConfidence.clear();
482         mEntityConfidence.putAll(confidences);
483         mClassificationStatus = CLASSIFICATION_COMPLETE;
484     }
485 
486     @Override
toString()487     public String toString() {
488         StringBuilder b = new StringBuilder(128);
489 
490         b.append("ClipDescription { ");
491         toShortString(b, true);
492         b.append(" }");
493 
494         return b.toString();
495     }
496 
497     /**
498      * Appends this description to the given builder.
499      * @param redactContent If true, redacts common forms of PII; otherwise appends full details.
500      * @hide
501      */
toShortString(StringBuilder b, boolean redactContent)502     public boolean toShortString(StringBuilder b, boolean redactContent) {
503         boolean first = !toShortStringTypesOnly(b);
504         if (mLabel != null) {
505             if (!first) {
506                 b.append(' ');
507             }
508             first = false;
509             if (redactContent) {
510                 b.append("hasLabel(").append(mLabel.length()).append(')');
511             } else {
512                 b.append('"').append(mLabel).append('"');
513             }
514         }
515         if (mExtras != null) {
516             if (!first) {
517                 b.append(' ');
518             }
519             first = false;
520             if (redactContent) {
521                 if (mExtras.isParcelled()) {
522                     // We don't want this toString function to trigger un-parcelling.
523                     b.append("hasExtras");
524                 } else {
525                     b.append("hasExtras(").append(mExtras.size()).append(')');
526                 }
527             } else {
528                 b.append(mExtras.toString());
529             }
530         }
531         if (mTimeStamp > 0) {
532             if (!first) {
533                 b.append(' ');
534             }
535             first = false;
536             b.append('<');
537             b.append(TimeUtils.logTimeOfDay(mTimeStamp));
538             b.append('>');
539         }
540         return !first;
541     }
542 
543     /** @hide */
toShortStringTypesOnly(StringBuilder b)544     public boolean toShortStringTypesOnly(StringBuilder b) {
545         boolean first = true;
546         final int size = mMimeTypes.size();
547         for (int i=0; i<size; i++) {
548             if (!first) {
549                 b.append(' ');
550             }
551             first = false;
552             b.append(mMimeTypes.get(i));
553         }
554         return !first;
555     }
556 
557     /** @hide */
dumpDebug(ProtoOutputStream proto, long fieldId)558     public void dumpDebug(ProtoOutputStream proto, long fieldId) {
559         final long token = proto.start(fieldId);
560 
561         final int size = mMimeTypes.size();
562         for (int i = 0; i < size; i++) {
563             proto.write(ClipDescriptionProto.MIME_TYPES, mMimeTypes.get(i));
564         }
565 
566         if (mLabel != null) {
567             proto.write(ClipDescriptionProto.LABEL, mLabel.toString());
568         }
569         if (mExtras != null) {
570             mExtras.dumpDebug(proto, ClipDescriptionProto.EXTRAS);
571         }
572         if (mTimeStamp > 0) {
573             proto.write(ClipDescriptionProto.TIMESTAMP_MS, mTimeStamp);
574         }
575 
576         proto.end(token);
577     }
578 
579     @Override
describeContents()580     public int describeContents() {
581         return 0;
582     }
583 
584     @Override
writeToParcel(Parcel dest, int flags)585     public void writeToParcel(Parcel dest, int flags) {
586         TextUtils.writeToParcel(mLabel, dest, flags);
587         dest.writeStringList(mMimeTypes);
588         dest.writePersistableBundle(mExtras);
589         dest.writeLong(mTimeStamp);
590         dest.writeBoolean(mIsStyledText);
591         dest.writeInt(mClassificationStatus);
592         dest.writeBundle(confidencesToBundle());
593     }
594 
confidencesToBundle()595     private Bundle confidencesToBundle() {
596         Bundle bundle = new Bundle();
597         int size = mEntityConfidence.size();
598         for (int i = 0; i < size; i++) {
599             bundle.putFloat(mEntityConfidence.keyAt(i), mEntityConfidence.valueAt(i));
600         }
601         return bundle;
602     }
603 
readBundleToConfidences(Bundle bundle)604     private void readBundleToConfidences(Bundle bundle) {
605         for (String key : bundle.keySet()) {
606             mEntityConfidence.put(key, bundle.getFloat(key));
607         }
608     }
609 
ClipDescription(Parcel in)610     ClipDescription(Parcel in) {
611         mLabel = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
612         mMimeTypes = in.createStringArrayList();
613         mExtras = in.readPersistableBundle();
614         mTimeStamp = in.readLong();
615         mIsStyledText = in.readBoolean();
616         mClassificationStatus = in.readInt();
617         readBundleToConfidences(in.readBundle());
618     }
619 
620     public static final @android.annotation.NonNull Parcelable.Creator<ClipDescription> CREATOR =
621         new Parcelable.Creator<ClipDescription>() {
622 
623             public ClipDescription createFromParcel(Parcel source) {
624                 return new ClipDescription(source);
625             }
626 
627             public ClipDescription[] newArray(int size) {
628                 return new ClipDescription[size];
629             }
630         };
631 }
632