Debian Codegraph @

core/java/android/content/ClipDescription.java

raw symbols SCIP
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 * @hide
162 */
163 public static final String EXTRA_IS_REMOTE_DEVICE = "android.content.extra.IS_REMOTE_DEVICE";
164
165 /** @hide */
166 @Retention(RetentionPolicy.SOURCE)
167 @IntDef(value =
168 { CLASSIFICATION_NOT_COMPLETE, CLASSIFICATION_NOT_PERFORMED, CLASSIFICATION_COMPLETE})
169 @interface ClassificationStatus {}
170
171 /**
172 * Value returned by {@link #getConfidenceScore(String)} if text classification has not been
173 * completed on the associated clip. This will be always be the case if the clip has not been
174 * copied to clipboard, or if there is no associated clip.
175 */
176 public static final int CLASSIFICATION_NOT_COMPLETE = 1;
177
178 /**
179 * Value returned by {@link #getConfidenceScore(String)} if text classification was not and will
180 * not be performed on the associated clip. This may be the case if the clip does not contain
181 * text in its first item, or if the text is too long.
182 */
183 public static final int CLASSIFICATION_NOT_PERFORMED = 2;
184
185 /**
186 * Value returned by {@link #getConfidenceScore(String)} if text classification has been
187 * completed.
188 */
189 public static final int CLASSIFICATION_COMPLETE = 3;
190
191 final CharSequence mLabel;
192 private final ArrayList<String> mMimeTypes;
193 private PersistableBundle mExtras;
194 private long mTimeStamp;
195 private boolean mIsStyledText;
196 private final ArrayMap<String, Float> mEntityConfidence = new ArrayMap<>();
197 private int mClassificationStatus = CLASSIFICATION_NOT_COMPLETE;
198
199 /**
200 * Create a new clip.
201 *
202 * @param label Label to show to the user describing this clip.
203 * @param mimeTypes An array of MIME types this data is available as.
204 */
205 public ClipDescription(CharSequence label, String[] mimeTypes) {
206 if (mimeTypes == null) {
207 throw new NullPointerException("mimeTypes is null");
208 }
209 mLabel = label;
210 mMimeTypes = new ArrayList<String>(Arrays.asList(mimeTypes));
211 }
212
213 /**
214 * Create a copy of a ClipDescription.
215 */
216 public ClipDescription(ClipDescription o) {
217 mLabel = o.mLabel;
218 mMimeTypes = new ArrayList<String>(o.mMimeTypes);
219 mTimeStamp = o.mTimeStamp;
220 }
221
222 /**
223 * Helper to compare two MIME types, where one may be a pattern.
224 * @param concreteType A fully-specified MIME type.
225 * @param desiredType A desired MIME type that may be a pattern such as *&#47;*.
226 * @return Returns true if the two MIME types match.
227 */
228 public static boolean compareMimeTypes(String concreteType, String desiredType) {
229 final int typeLength = desiredType.length();
230 if (typeLength == 3 && desiredType.equals("*/*")) {
231 return true;
232 }
233
234 final int slashpos = desiredType.indexOf('/');
235 if (slashpos > 0) {
236 if (typeLength == slashpos+2 && desiredType.charAt(slashpos+1) == '*') {
237 if (desiredType.regionMatches(0, concreteType, 0, slashpos+1)) {
238 return true;
239 }
240 } else if (desiredType.equals(concreteType)) {
241 return true;
242 }
243 }
244
245 return false;
246 }
247
248 /**
249 * Used for setting the timestamp at which the associated {@link ClipData} is copied to
250 * global clipboard.
251 *
252 * @param timeStamp at which the associated {@link ClipData} is copied to clipboard in
253 * {@link System#currentTimeMillis()} time base.
254 * @hide
255 */
256 public void setTimestamp(long timeStamp) {
257 mTimeStamp = timeStamp;
258 }
259
260 /**
261 * Return the timestamp at which the associated {@link ClipData} is copied to global clipboard
262 * in the {@link System#currentTimeMillis()} time base.
263 *
264 * @return timestamp at which the associated {@link ClipData} is copied to global clipboard
265 * or {@code 0} if it is not copied to clipboard.
266 */
267 public long getTimestamp() {
268 return mTimeStamp;
269 }
270
271 /**
272 * Return the label for this clip.
273 */
274 public CharSequence getLabel() {
275 return mLabel;
276 }
277
278 /**
279 * Check whether the clip description contains the given MIME type.
280 *
281 * @param mimeType The desired MIME type. May be a pattern.
282 * @return Returns true if one of the MIME types in the clip description
283 * matches the desired MIME type, else false.
284 */
285 public boolean hasMimeType(String mimeType) {
286 final int size = mMimeTypes.size();
287 for (int i=0; i<size; i++) {
288 if (compareMimeTypes(mMimeTypes.get(i), mimeType)) {
289 return true;
290 }
291 }
292 return false;
293 }
294
295 /**
296 * Check whether the clip description contains any of the given MIME types.
297 *
298 * @param targetMimeTypes The target MIME types. May use patterns.
299 * @return Returns true if at least one of the MIME types in the clip description matches at
300 * least one of the target MIME types, else false.
301 *
302 * @hide
303 */
304 public boolean hasMimeType(@NonNull String[] targetMimeTypes) {
305 for (String targetMimeType : targetMimeTypes) {
306 if (hasMimeType(targetMimeType)) {
307 return true;
308 }
309 }
310 return false;
311 }
312
313 /**
314 * Filter the clip description MIME types by the given MIME type. Returns
315 * all MIME types in the clip that match the given MIME type.
316 *
317 * @param mimeType The desired MIME type. May be a pattern.
318 * @return Returns an array of all matching MIME types. If there are no
319 * matching MIME types, null is returned.
320 */
321 public String[] filterMimeTypes(String mimeType) {
322 ArrayList<String> array = null;
323 final int size = mMimeTypes.size();
324 for (int i=0; i<size; i++) {
325 if (compareMimeTypes(mMimeTypes.get(i), mimeType)) {
326 if (array == null) {
327 array = new ArrayList<String>();
328 }
329 array.add(mMimeTypes.get(i));
330 }
331 }
332 if (array == null) {
333 return null;
334 }
335 String[] rawArray = new String[array.size()];
336 array.toArray(rawArray);
337 return rawArray;
338 }
339
340 /**
341 * Return the number of MIME types the clip is available in.
342 */
343 public int getMimeTypeCount() {
344 return mMimeTypes.size();
345 }
346
347 /**
348 * Return one of the possible clip MIME types.
349 */
350 public String getMimeType(int index) {
351 return mMimeTypes.get(index);
352 }
353
354 /**
355 * Add MIME types to the clip description.
356 */
357 void addMimeTypes(String[] mimeTypes) {
358 for (int i=0; i!=mimeTypes.length; i++) {
359 final String mimeType = mimeTypes[i];
360 if (!mMimeTypes.contains(mimeType)) {
361 mMimeTypes.add(mimeType);
362 }
363 }
364 }
365
366 /**
367 * Retrieve extended data from the clip description.
368 *
369 * @return the bundle containing extended data previously set with
370 * {@link #setExtras(PersistableBundle)}, or null if no extras have been set.
371 *
372 * @see #setExtras(PersistableBundle)
373 */
374 public PersistableBundle getExtras() {
375 return mExtras;
376 }
377
378 /**
379 * Add extended data to the clip description.
380 *
381 * @see #getExtras()
382 */
383 public void setExtras(PersistableBundle extras) {
384 mExtras = new PersistableBundle(extras);
385 }
386
387 /** @hide */
388 public void validate() {
389 if (mMimeTypes == null) {
390 throw new NullPointerException("null mime types");
391 }
392 final int size = mMimeTypes.size();
393 if (size <= 0) {
394 throw new IllegalArgumentException("must have at least 1 mime type");
395 }
396 for (int i=0; i<size; i++) {
397 if (mMimeTypes.get(i) == null) {
398 throw new NullPointerException("mime type at " + i + " is null");
399 }
400 }
401 }
402
403 /**
404 * Returns true if the first item of the associated {@link ClipData} contains styled text, i.e.
405 * if it contains spans such as {@link android.text.style.CharacterStyle CharacterStyle}, {@link
406 * android.text.style.ParagraphStyle ParagraphStyle}, or {@link
407 * android.text.style.UpdateAppearance UpdateAppearance}. Returns false if it does not, or if
408 * there is no associated clip data.
409 */
410 public boolean isStyledText() {
411 return mIsStyledText;
412 }
413
414 /**
415 * Sets whether the associated {@link ClipData} contains styled text in its first item. This
416 * should be called when this description is associated with clip data or when the first item
417 * is added to the associated clip data.
418 */
419 void setIsStyledText(boolean isStyledText) {
420 mIsStyledText = isStyledText;
421 }
422
423 /**
424 * Sets the current status of text classification for the associated clip.
425 *
426 * @hide
427 */
428 public void setClassificationStatus(@ClassificationStatus int status) {
429 mClassificationStatus = status;
430 }
431
432 /**
433 * Returns a score indicating confidence that an instance of the given entity is present in the
434 * first item of the clip data, if that item is plain text and text classification has been
435 * performed. The value ranges from 0 (low confidence) to 1 (high confidence). 0 indicates that
436 * the entity was not found in the classified text.
437 *
438 * <p>Entities should be as defined in the {@link TextClassifier} class, such as
439 * {@link TextClassifier#TYPE_ADDRESS}, {@link TextClassifier#TYPE_URL}, or
440 * {@link TextClassifier#TYPE_EMAIL}.
441 *
442 * <p>If the result is positive for any entity, the full classification result as a
443 * {@link TextLinks} object may be obtained using the {@link ClipData.Item#getTextLinks()}
444 * method.
445 *
446 * @throws IllegalStateException if {@link #getClassificationStatus()} is not
447 * {@link #CLASSIFICATION_COMPLETE}
448 */
449 @FloatRange(from = 0.0, to = 1.0)
450 public float getConfidenceScore(@NonNull @TextClassifier.EntityType String entity) {
451 if (mClassificationStatus != CLASSIFICATION_COMPLETE) {
452 throw new IllegalStateException("Classification not complete");
453 }
454 return mEntityConfidence.getOrDefault(entity, 0f);
455 }
456
457 /**
458 * Returns {@link #CLASSIFICATION_COMPLETE} if text classification has been performed on the
459 * associated {@link ClipData}. If this is the case then {@link #getConfidenceScore} may be used
460 * to retrieve information about entities within the text. Otherwise, returns
461 * {@link #CLASSIFICATION_NOT_COMPLETE} if classification has not yet returned results, or
462 * {@link #CLASSIFICATION_NOT_PERFORMED} if classification was not attempted (e.g. because the
463 * text was too long).
464 */
465 public @ClassificationStatus int getClassificationStatus() {
466 return mClassificationStatus;
467 }
468
469 /**
470 * @hide
471 */
472 public void setConfidenceScores(Map<String, Float> confidences) {
473 mEntityConfidence.clear();
474 mEntityConfidence.putAll(confidences);
475 mClassificationStatus = CLASSIFICATION_COMPLETE;
476 }
477
478 @Override
479 public String toString() {
480 StringBuilder b = new StringBuilder(128);
481
482 b.append("ClipDescription { ");
483 toShortString(b, true);
484 b.append(" }");
485
486 return b.toString();
487 }
488
489 /**
490 * Appends this description to the given builder.
491 * @param redactContent If true, redacts common forms of PII; otherwise appends full details.
492 * @hide
493 */
494 public boolean toShortString(StringBuilder b, boolean redactContent) {
495 boolean first = !toShortStringTypesOnly(b);
496 if (mLabel != null) {
497 if (!first) {
498 b.append(' ');
499 }
500 first = false;
501 if (redactContent) {
502 b.append("hasLabel(").append(mLabel.length()).append(')');
503 } else {
504 b.append('"').append(mLabel).append('"');
505 }
506 }
507 if (mExtras != null) {
508 if (!first) {
509 b.append(' ');
510 }
511 first = false;
512 if (redactContent) {
513 if (mExtras.isParcelled()) {
514 // We don't want this toString function to trigger un-parcelling.
515 b.append("hasExtras");
516 } else {
517 b.append("hasExtras(").append(mExtras.size()).append(')');
518 }
519 } else {
520 b.append(mExtras.toString());
521 }
522 }
523 if (mTimeStamp > 0) {
524 if (!first) {
525 b.append(' ');
526 }
527 first = false;
528 b.append('<');
529 b.append(TimeUtils.logTimeOfDay(mTimeStamp));
530 b.append('>');
531 }
532 return !first;
533 }
534
535 /** @hide */
536 public boolean toShortStringTypesOnly(StringBuilder b) {
537 boolean first = true;
538 final int size = mMimeTypes.size();
539 for (int i=0; i<size; i++) {
540 if (!first) {
541 b.append(' ');
542 }
543 first = false;
544 b.append(mMimeTypes.get(i));
545 }
546 return !first;
547 }
548
549 /** @hide */
550 public void dumpDebug(ProtoOutputStream proto, long fieldId) {
551 final long token = proto.start(fieldId);
552
553 final int size = mMimeTypes.size();
554 for (int i = 0; i < size; i++) {
555 proto.write(ClipDescriptionProto.MIME_TYPES, mMimeTypes.get(i));
556 }
557
558 if (mLabel != null) {
559 proto.write(ClipDescriptionProto.LABEL, mLabel.toString());
560 }
561 if (mExtras != null) {
562 mExtras.dumpDebug(proto, ClipDescriptionProto.EXTRAS);
563 }
564 if (mTimeStamp > 0) {
565 proto.write(ClipDescriptionProto.TIMESTAMP_MS, mTimeStamp);
566 }
567
568 proto.end(token);
569 }
570
571 @Override
572 public int describeContents() {
573 return 0;
574 }
575
576 @Override
577 public void writeToParcel(Parcel dest, int flags) {
578 TextUtils.writeToParcel(mLabel, dest, flags);
579 dest.writeStringList(mMimeTypes);
580 dest.writePersistableBundle(mExtras);
581 dest.writeLong(mTimeStamp);
582 dest.writeBoolean(mIsStyledText);
583 dest.writeInt(mClassificationStatus);
584 dest.writeBundle(confidencesToBundle());
585 }
586
587 private Bundle confidencesToBundle() {
588 Bundle bundle = new Bundle();
589 int size = mEntityConfidence.size();
590 for (int i = 0; i < size; i++) {
591 bundle.putFloat(mEntityConfidence.keyAt(i), mEntityConfidence.valueAt(i));
592 }
593 return bundle;
594 }
595
596 private void readBundleToConfidences(Bundle bundle) {
597 for (String key : bundle.keySet()) {
598 mEntityConfidence.put(key, bundle.getFloat(key));
599 }
600 }
601
602 ClipDescription(Parcel in) {
603 mLabel = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
604 mMimeTypes = in.createStringArrayList();
605 mExtras = in.readPersistableBundle();
606 mTimeStamp = in.readLong();
607 mIsStyledText = in.readBoolean();
608 mClassificationStatus = in.readInt();
609 readBundleToConfidences(in.readBundle());
610 }
611
612 public static final @android.annotation.NonNull Parcelable.Creator<ClipDescription> CREATOR =
613 new Parcelable.Creator<ClipDescription>() {
614
615 public ClipDescription createFromParcel(Parcel source) {
616 return new ClipDescription(source);
617 }
618
619 public ClipDescription[] newArray(int size) {
620 return new ClipDescription[size];
621 }
622 };
623 }