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