OSDN Git Service

0ec58ea40fe42f207df5b0ae2ae8fd001b12b7d0
[android-x86/frameworks-base.git] / core / java / android / content / ClipData.java
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 static android.content.ContentProvider.maybeAddUserId;
20
21 import android.content.pm.PackageManager;
22 import android.content.res.AssetFileDescriptor;
23 import android.graphics.Bitmap;
24 import android.net.Uri;
25 import android.os.Parcel;
26 import android.os.Parcelable;
27 import android.os.Process;
28 import android.os.StrictMode;
29 import android.text.Html;
30 import android.text.Spannable;
31 import android.text.SpannableStringBuilder;
32 import android.text.Spanned;
33 import android.text.TextUtils;
34 import android.text.style.URLSpan;
35 import android.util.Log;
36
37 import java.io.FileInputStream;
38 import java.io.FileNotFoundException;
39 import java.io.IOException;
40 import java.io.InputStreamReader;
41 import java.util.ArrayList;
42 import java.util.List;
43
44 /**
45  * Representation of a clipped data on the clipboard.
46  *
47  * <p>ClippedData is a complex type containing one or Item instances,
48  * each of which can hold one or more representations of an item of data.
49  * For display to the user, it also has a label and iconic representation.</p>
50  *
51  * <p>A ClipData contains a {@link ClipDescription}, which describes
52  * important meta-data about the clip.  In particular, its
53  * {@link ClipDescription#getMimeType(int) getDescription().getMimeType(int)}
54  * must return correct MIME type(s) describing the data in the clip.  For help
55  * in correctly constructing a clip with the correct MIME type, use
56  * {@link #newPlainText(CharSequence, CharSequence)},
57  * {@link #newUri(ContentResolver, CharSequence, Uri)}, and
58  * {@link #newIntent(CharSequence, Intent)}.
59  *
60  * <p>Each Item instance can be one of three main classes of data: a simple
61  * CharSequence of text, a single Intent object, or a Uri.  See {@link Item}
62  * for more details.
63  *
64  * <div class="special reference">
65  * <h3>Developer Guides</h3>
66  * <p>For more information about using the clipboard framework, read the
67  * <a href="{@docRoot}guide/topics/clipboard/copy-paste.html">Copy and Paste</a>
68  * developer guide.</p>
69  * </div>
70  *
71  * <a name="ImplementingPaste"></a>
72  * <h3>Implementing Paste or Drop</h3>
73  *
74  * <p>To implement a paste or drop of a ClippedData object into an application,
75  * the application must correctly interpret the data for its use.  If the {@link Item}
76  * it contains is simple text or an Intent, there is little to be done: text
77  * can only be interpreted as text, and an Intent will typically be used for
78  * creating shortcuts (such as placing icons on the home screen) or other
79  * actions.
80  *
81  * <p>If all you want is the textual representation of the clipped data, you
82  * can use the convenience method {@link Item#coerceToText Item.coerceToText}.
83  * In this case there is generally no need to worry about the MIME types
84  * reported by {@link ClipDescription#getMimeType(int) getDescription().getMimeType(int)},
85  * since any clip item can always be converted to a string.
86  *
87  * <p>More complicated exchanges will be done through URIs, in particular
88  * "content:" URIs.  A content URI allows the recipient of a ClippedData item
89  * to interact closely with the ContentProvider holding the data in order to
90  * negotiate the transfer of that data.  The clip must also be filled in with
91  * the available MIME types; {@link #newUri(ContentResolver, CharSequence, Uri)}
92  * will take care of correctly doing this.
93  *
94  * <p>For example, here is the paste function of a simple NotePad application.
95  * When retrieving the data from the clipboard, it can do either two things:
96  * if the clipboard contains a URI reference to an existing note, it copies
97  * the entire structure of the note into a new note; otherwise, it simply
98  * coerces the clip into text and uses that as the new note's contents.
99  *
100  * {@sample development/samples/NotePad/src/com/example/android/notepad/NoteEditor.java
101  *      paste}
102  *
103  * <p>In many cases an application can paste various types of streams of data.  For
104  * example, an e-mail application may want to allow the user to paste an image
105  * or other binary data as an attachment.  This is accomplished through the
106  * ContentResolver {@link ContentResolver#getStreamTypes(Uri, String)} and
107  * {@link ContentResolver#openTypedAssetFileDescriptor(Uri, String, android.os.Bundle)}
108  * methods.  These allow a client to discover the type(s) of data that a particular
109  * content URI can make available as a stream and retrieve the stream of data.
110  *
111  * <p>For example, the implementation of {@link Item#coerceToText Item.coerceToText}
112  * itself uses this to try to retrieve a URI clip as a stream of text:
113  *
114  * {@sample frameworks/base/core/java/android/content/ClipData.java coerceToText}
115  *
116  * <a name="ImplementingCopy"></a>
117  * <h3>Implementing Copy or Drag</h3>
118  *
119  * <p>To be the source of a clip, the application must construct a ClippedData
120  * object that any recipient can interpret best for their context.  If the clip
121  * is to contain a simple text, Intent, or URI, this is easy: an {@link Item}
122  * containing the appropriate data type can be constructed and used.
123  *
124  * <p>More complicated data types require the implementation of support in
125  * a ContentProvider for describing and generating the data for the recipient.
126  * A common scenario is one where an application places on the clipboard the
127  * content: URI of an object that the user has copied, with the data at that
128  * URI consisting of a complicated structure that only other applications with
129  * direct knowledge of the structure can use.
130  *
131  * <p>For applications that do not have intrinsic knowledge of the data structure,
132  * the content provider holding it can make the data available as an arbitrary
133  * number of types of data streams.  This is done by implementing the
134  * ContentProvider {@link ContentProvider#getStreamTypes(Uri, String)} and
135  * {@link ContentProvider#openTypedAssetFile(Uri, String, android.os.Bundle)}
136  * methods.
137  *
138  * <p>Going back to our simple NotePad application, this is the implementation
139  * it may have to convert a single note URI (consisting of a title and the note
140  * text) into a stream of plain text data.
141  *
142  * {@sample development/samples/NotePad/src/com/example/android/notepad/NotePadProvider.java
143  *      stream}
144  *
145  * <p>The copy operation in our NotePad application is now just a simple matter
146  * of making a clip containing the URI of the note being copied:
147  *
148  * {@sample development/samples/NotePad/src/com/example/android/notepad/NotesList.java
149  *      copy}
150  *
151  * <p>Note if a paste operation needs this clip as text (for example to paste
152  * into an editor), then {@link Item#coerceToText(Context)} will ask the content
153  * provider for the clip URI as text and successfully paste the entire note.
154  */
155 public class ClipData implements Parcelable {
156     static final String[] MIMETYPES_TEXT_PLAIN = new String[] {
157         ClipDescription.MIMETYPE_TEXT_PLAIN };
158     static final String[] MIMETYPES_TEXT_HTML = new String[] {
159         ClipDescription.MIMETYPE_TEXT_HTML };
160     static final String[] MIMETYPES_TEXT_URILIST = new String[] {
161         ClipDescription.MIMETYPE_TEXT_URILIST };
162     static final String[] MIMETYPES_TEXT_INTENT = new String[] {
163         ClipDescription.MIMETYPE_TEXT_INTENT };
164
165     final ClipDescription mClipDescription;
166     
167     final Bitmap mIcon;
168
169     final ArrayList<Item> mItems;
170
171     /**
172      * Description of a single item in a ClippedData.
173      *
174      * <p>The types than an individual item can currently contain are:</p>
175      *
176      * <ul>
177      * <li> Text: a basic string of text.  This is actually a CharSequence,
178      * so it can be formatted text supported by corresponding Android built-in
179      * style spans.  (Custom application spans are not supported and will be
180      * stripped when transporting through the clipboard.)
181      * <li> Intent: an arbitrary Intent object.  A typical use is the shortcut
182      * to create when pasting a clipped item on to the home screen.
183      * <li> Uri: a URI reference.  This may be any URI (such as an http: URI
184      * representing a bookmark), however it is often a content: URI.  Using
185      * content provider references as clips like this allows an application to
186      * share complex or large clips through the standard content provider
187      * facilities.
188      * </ul>
189      */
190     public static class Item {
191         final CharSequence mText;
192         final String mHtmlText;
193         final Intent mIntent;
194         Uri mUri;
195
196         /**
197          * Create an Item consisting of a single block of (possibly styled) text.
198          */
199         public Item(CharSequence text) {
200             mText = text;
201             mHtmlText = null;
202             mIntent = null;
203             mUri = null;
204         }
205
206         /**
207          * Create an Item consisting of a single block of (possibly styled) text,
208          * with an alternative HTML formatted representation.  You <em>must</em>
209          * supply a plain text representation in addition to HTML text; coercion
210          * will not be done from HTML formated text into plain text.
211          */
212         public Item(CharSequence text, String htmlText) {
213             mText = text;
214             mHtmlText = htmlText;
215             mIntent = null;
216             mUri = null;
217         }
218
219         /**
220          * Create an Item consisting of an arbitrary Intent.
221          */
222         public Item(Intent intent) {
223             mText = null;
224             mHtmlText = null;
225             mIntent = intent;
226             mUri = null;
227         }
228
229         /**
230          * Create an Item consisting of an arbitrary URI.
231          */
232         public Item(Uri uri) {
233             mText = null;
234             mHtmlText = null;
235             mIntent = null;
236             mUri = uri;
237         }
238
239         /**
240          * Create a complex Item, containing multiple representations of
241          * text, Intent, and/or URI.
242          */
243         public Item(CharSequence text, Intent intent, Uri uri) {
244             mText = text;
245             mHtmlText = null;
246             mIntent = intent;
247             mUri = uri;
248         }
249
250         /**
251          * Create a complex Item, containing multiple representations of
252          * text, HTML text, Intent, and/or URI.  If providing HTML text, you
253          * <em>must</em> supply a plain text representation as well; coercion
254          * will not be done from HTML formated text into plain text.
255          */
256         public Item(CharSequence text, String htmlText, Intent intent, Uri uri) {
257             if (htmlText != null && text == null) {
258                 throw new IllegalArgumentException(
259                         "Plain text must be supplied if HTML text is supplied");
260             }
261             mText = text;
262             mHtmlText = htmlText;
263             mIntent = intent;
264             mUri = uri;
265         }
266
267         /**
268          * Retrieve the raw text contained in this Item.
269          */
270         public CharSequence getText() {
271             return mText;
272         }
273
274         /**
275          * Retrieve the raw HTML text contained in this Item.
276          */
277         public String getHtmlText() {
278             return mHtmlText;
279         }
280
281         /**
282          * Retrieve the raw Intent contained in this Item.
283          */
284         public Intent getIntent() {
285             return mIntent;
286         }
287
288         /**
289          * Retrieve the raw URI contained in this Item.
290          */
291         public Uri getUri() {
292             return mUri;
293         }
294
295         /**
296          * Turn this item into text, regardless of the type of data it
297          * actually contains.
298          *
299          * <p>The algorithm for deciding what text to return is:
300          * <ul>
301          * <li> If {@link #getText} is non-null, return that.
302          * <li> If {@link #getUri} is non-null, try to retrieve its data
303          * as a text stream from its content provider.  If this succeeds, copy
304          * the text into a String and return it.  If it is not a content: URI or
305          * the content provider does not supply a text representation, return
306          * the raw URI as a string.
307          * <li> If {@link #getIntent} is non-null, convert that to an intent:
308          * URI and return it.
309          * <li> Otherwise, return an empty string.
310          * </ul>
311          *
312          * @param context The caller's Context, from which its ContentResolver
313          * and other things can be retrieved.
314          * @return Returns the item's textual representation.
315          */
316 //BEGIN_INCLUDE(coerceToText)
317         public CharSequence coerceToText(Context context) {
318             // If this Item has an explicit textual value, simply return that.
319             CharSequence text = getText();
320             if (text != null) {
321                 return text;
322             }
323
324             // If this Item has a URI value, try using that.
325             Uri uri = getUri();
326             if (uri != null) {
327
328                 // First see if the URI can be opened as a plain text stream
329                 // (of any sub-type).  If so, this is the best textual
330                 // representation for it.
331                 FileInputStream stream = null;
332                 try {
333                     // Ask for a stream of the desired type.
334                     AssetFileDescriptor descr = context.getContentResolver()
335                             .openTypedAssetFileDescriptor(uri, "text/*", null);
336                     stream = descr.createInputStream();
337                     InputStreamReader reader = new InputStreamReader(stream, "UTF-8");
338
339                     // Got it...  copy the stream into a local string and return it.
340                     StringBuilder builder = new StringBuilder(128);
341                     char[] buffer = new char[8192];
342                     int len;
343                     while ((len=reader.read(buffer)) > 0) {
344                         builder.append(buffer, 0, len);
345                     }
346                     return builder.toString();
347
348                 } catch (FileNotFoundException e) {
349                     // Unable to open content URI as text...  not really an
350                     // error, just something to ignore.
351
352                 } catch (IOException e) {
353                     // Something bad has happened.
354                     Log.w("ClippedData", "Failure loading text", e);
355                     return e.toString();
356
357                 } finally {
358                     if (stream != null) {
359                         try {
360                             stream.close();
361                         } catch (IOException e) {
362                         }
363                     }
364                 }
365
366                 // If we couldn't open the URI as a stream, then the URI itself
367                 // probably serves fairly well as a textual representation.
368                 return uri.toString();
369             }
370
371             // Finally, if all we have is an Intent, then we can just turn that
372             // into text.  Not the most user-friendly thing, but it's something.
373             Intent intent = getIntent();
374             if (intent != null) {
375                 return intent.toUri(Intent.URI_INTENT_SCHEME);
376             }
377
378             // Shouldn't get here, but just in case...
379             return "";
380         }
381 //END_INCLUDE(coerceToText)
382
383         /**
384          * Like {@link #coerceToHtmlText(Context)}, but any text that would
385          * be returned as HTML formatting will be returned as text with
386          * style spans.
387          * @param context The caller's Context, from which its ContentResolver
388          * and other things can be retrieved.
389          * @return Returns the item's textual representation.
390          */
391         public CharSequence coerceToStyledText(Context context) {
392             CharSequence text = getText();
393             if (text instanceof Spanned) {
394                 return text;
395             }
396             String htmlText = getHtmlText();
397             if (htmlText != null) {
398                 try {
399                     CharSequence newText = Html.fromHtml(htmlText);
400                     if (newText != null) {
401                         return newText;
402                     }
403                 } catch (RuntimeException e) {
404                     // If anything bad happens, we'll fall back on the plain text.
405                 }
406             }
407
408             if (text != null) {
409                 return text;
410             }
411             return coerceToHtmlOrStyledText(context, true);
412         }
413
414         /**
415          * Turn this item into HTML text, regardless of the type of data it
416          * actually contains.
417          *
418          * <p>The algorithm for deciding what text to return is:
419          * <ul>
420          * <li> If {@link #getHtmlText} is non-null, return that.
421          * <li> If {@link #getText} is non-null, return that, converting to
422          * valid HTML text.  If this text contains style spans,
423          * {@link Html#toHtml(Spanned) Html.toHtml(Spanned)} is used to
424          * convert them to HTML formatting.
425          * <li> If {@link #getUri} is non-null, try to retrieve its data
426          * as a text stream from its content provider.  If the provider can
427          * supply text/html data, that will be preferred and returned as-is.
428          * Otherwise, any text/* data will be returned and escaped to HTML.
429          * If it is not a content: URI or the content provider does not supply
430          * a text representation, HTML text containing a link to the URI
431          * will be returned.
432          * <li> If {@link #getIntent} is non-null, convert that to an intent:
433          * URI and return as an HTML link.
434          * <li> Otherwise, return an empty string.
435          * </ul>
436          *
437          * @param context The caller's Context, from which its ContentResolver
438          * and other things can be retrieved.
439          * @return Returns the item's representation as HTML text.
440          */
441         public String coerceToHtmlText(Context context) {
442             // If the item has an explicit HTML value, simply return that.
443             String htmlText = getHtmlText();
444             if (htmlText != null) {
445                 return htmlText;
446             }
447
448             // If this Item has a plain text value, return it as HTML.
449             CharSequence text = getText();
450             if (text != null) {
451                 if (text instanceof Spanned) {
452                     return Html.toHtml((Spanned)text);
453                 }
454                 return Html.escapeHtml(text);
455             }
456
457             text = coerceToHtmlOrStyledText(context, false);
458             return text != null ? text.toString() : null;
459         }
460
461         private CharSequence coerceToHtmlOrStyledText(Context context, boolean styled) {
462             // If this Item has a URI value, try using that.
463             if (mUri != null) {
464
465                 // Check to see what data representations the content
466                 // provider supports.  We would like HTML text, but if that
467                 // is not possible we'll live with plan text.
468                 String[] types = null;
469                 try {
470                     types = context.getContentResolver().getStreamTypes(mUri, "text/*");
471                 } catch (SecurityException e) {
472                     // No read permission for mUri, assume empty stream types list.
473                 }
474                 boolean hasHtml = false;
475                 boolean hasText = false;
476                 if (types != null) {
477                     for (String type : types) {
478                         if ("text/html".equals(type)) {
479                             hasHtml = true;
480                         } else if (type.startsWith("text/")) {
481                             hasText = true;
482                         }
483                     }
484                 }
485
486                 // If the provider can serve data we can use, open and load it.
487                 if (hasHtml || hasText) {
488                     FileInputStream stream = null;
489                     try {
490                         // Ask for a stream of the desired type.
491                         AssetFileDescriptor descr = context.getContentResolver()
492                                 .openTypedAssetFileDescriptor(mUri,
493                                         hasHtml ? "text/html" : "text/plain", null);
494                         stream = descr.createInputStream();
495                         InputStreamReader reader = new InputStreamReader(stream, "UTF-8");
496
497                         // Got it...  copy the stream into a local string and return it.
498                         StringBuilder builder = new StringBuilder(128);
499                         char[] buffer = new char[8192];
500                         int len;
501                         while ((len=reader.read(buffer)) > 0) {
502                             builder.append(buffer, 0, len);
503                         }
504                         String text = builder.toString();
505                         if (hasHtml) {
506                             if (styled) {
507                                 // We loaded HTML formatted text and the caller
508                                 // want styled text, convert it.
509                                 try {
510                                     CharSequence newText = Html.fromHtml(text);
511                                     return newText != null ? newText : text;
512                                 } catch (RuntimeException e) {
513                                     return text;
514                                 }
515                             } else {
516                                 // We loaded HTML formatted text and that is what
517                                 // the caller wants, just return it.
518                                 return text.toString();
519                             }
520                         }
521                         if (styled) {
522                             // We loaded plain text and the caller wants styled
523                             // text, that is all we have so return it.
524                             return text;
525                         } else {
526                             // We loaded plain text and the caller wants HTML
527                             // text, escape it for HTML.
528                             return Html.escapeHtml(text);
529                         }
530
531                     } catch (FileNotFoundException e) {
532                         // Unable to open content URI as text...  not really an
533                         // error, just something to ignore.
534
535                     } catch (IOException e) {
536                         // Something bad has happened.
537                         Log.w("ClippedData", "Failure loading text", e);
538                         return Html.escapeHtml(e.toString());
539
540                     } finally {
541                         if (stream != null) {
542                             try {
543                                 stream.close();
544                             } catch (IOException e) {
545                             }
546                         }
547                     }
548                 }
549
550                 // If we couldn't open the URI as a stream, then we can build
551                 // some HTML text with the URI itself.
552                 // probably serves fairly well as a textual representation.
553                 if (styled) {
554                     return uriToStyledText(mUri.toString());
555                 } else {
556                     return uriToHtml(mUri.toString());
557                 }
558             }
559
560             // Finally, if all we have is an Intent, then we can just turn that
561             // into text.  Not the most user-friendly thing, but it's something.
562             if (mIntent != null) {
563                 if (styled) {
564                     return uriToStyledText(mIntent.toUri(Intent.URI_INTENT_SCHEME));
565                 } else {
566                     return uriToHtml(mIntent.toUri(Intent.URI_INTENT_SCHEME));
567                 }
568             }
569
570             // Shouldn't get here, but just in case...
571             return "";
572         }
573
574         private String uriToHtml(String uri) {
575             StringBuilder builder = new StringBuilder(256);
576             builder.append("<a href=\"");
577             builder.append(Html.escapeHtml(uri));
578             builder.append("\">");
579             builder.append(Html.escapeHtml(uri));
580             builder.append("</a>");
581             return builder.toString();
582         }
583
584         private CharSequence uriToStyledText(String uri) {
585             SpannableStringBuilder builder = new SpannableStringBuilder();
586             builder.append(uri);
587             builder.setSpan(new URLSpan(uri), 0, builder.length(),
588                     Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
589             return builder;
590         }
591
592         @Override
593         public String toString() {
594             StringBuilder b = new StringBuilder(128);
595
596             b.append("ClipData.Item { ");
597             toShortString(b);
598             b.append(" }");
599
600             return b.toString();
601         }
602
603         /** @hide */
604         public void toShortString(StringBuilder b) {
605             if (mHtmlText != null) {
606                 b.append("H:");
607                 b.append(mHtmlText);
608             } else if (mText != null) {
609                 b.append("T:");
610                 b.append(mText);
611             } else if (mUri != null) {
612                 b.append("U:");
613                 b.append(mUri);
614             } else if (mIntent != null) {
615                 b.append("I:");
616                 mIntent.toShortString(b, true, true, true, true);
617             } else {
618                 b.append("NULL");
619             }
620         }
621
622         /** @hide */
623         public void toShortSummaryString(StringBuilder b) {
624             if (mHtmlText != null) {
625                 b.append("HTML");
626             } else if (mText != null) {
627                 b.append("TEXT");
628             } else if (mUri != null) {
629                 b.append("U:");
630                 b.append(mUri);
631             } else if (mIntent != null) {
632                 b.append("I:");
633                 mIntent.toShortString(b, true, true, true, true);
634             } else {
635                 b.append("NULL");
636             }
637         }
638     }
639
640     /**
641      * Create a new clip.
642      *
643      * @param label Label to show to the user describing this clip.
644      * @param mimeTypes An array of MIME types this data is available as.
645      * @param item The contents of the first item in the clip.
646      */
647     public ClipData(CharSequence label, String[] mimeTypes, Item item) {
648         mClipDescription = new ClipDescription(label, mimeTypes);
649         if (item == null) {
650             throw new NullPointerException("item is null");
651         }
652         mIcon = null;
653         mItems = new ArrayList<Item>();
654         mItems.add(item);
655     }
656
657     /**
658      * Create a new clip.
659      *
660      * @param description The ClipDescription describing the clip contents.
661      * @param item The contents of the first item in the clip.
662      */
663     public ClipData(ClipDescription description, Item item) {
664         mClipDescription = description;
665         if (item == null) {
666             throw new NullPointerException("item is null");
667         }
668         mIcon = null;
669         mItems = new ArrayList<Item>();
670         mItems.add(item);
671     }
672
673     /**
674      * Create a new clip that is a copy of another clip.  This does a deep-copy
675      * of all items in the clip.
676      *
677      * @param other The existing ClipData that is to be copied.
678      */
679     public ClipData(ClipData other) {
680         mClipDescription = other.mClipDescription;
681         mIcon = other.mIcon;
682         mItems = new ArrayList<Item>(other.mItems);
683     }
684
685     /**
686      * Create a new ClipData holding data of the type
687      * {@link ClipDescription#MIMETYPE_TEXT_PLAIN}.
688      *
689      * @param label User-visible label for the clip data.
690      * @param text The actual text in the clip.
691      * @return Returns a new ClipData containing the specified data.
692      */
693     static public ClipData newPlainText(CharSequence label, CharSequence text) {
694         Item item = new Item(text);
695         return new ClipData(label, MIMETYPES_TEXT_PLAIN, item);
696     }
697
698     /**
699      * Create a new ClipData holding data of the type
700      * {@link ClipDescription#MIMETYPE_TEXT_HTML}.
701      *
702      * @param label User-visible label for the clip data.
703      * @param text The text of clip as plain text, for receivers that don't
704      * handle HTML.  This is required.
705      * @param htmlText The actual HTML text in the clip.
706      * @return Returns a new ClipData containing the specified data.
707      */
708     static public ClipData newHtmlText(CharSequence label, CharSequence text,
709             String htmlText) {
710         Item item = new Item(text, htmlText);
711         return new ClipData(label, MIMETYPES_TEXT_HTML, item);
712     }
713
714     /**
715      * Create a new ClipData holding an Intent with MIME type
716      * {@link ClipDescription#MIMETYPE_TEXT_INTENT}.
717      *
718      * @param label User-visible label for the clip data.
719      * @param intent The actual Intent in the clip.
720      * @return Returns a new ClipData containing the specified data.
721      */
722     static public ClipData newIntent(CharSequence label, Intent intent) {
723         Item item = new Item(intent);
724         return new ClipData(label, MIMETYPES_TEXT_INTENT, item);
725     }
726
727     /**
728      * Create a new ClipData holding a URI.  If the URI is a content: URI,
729      * this will query the content provider for the MIME type of its data and
730      * use that as the MIME type.  Otherwise, it will use the MIME type
731      * {@link ClipDescription#MIMETYPE_TEXT_URILIST}.
732      *
733      * @param resolver ContentResolver used to get information about the URI.
734      * @param label User-visible label for the clip data.
735      * @param uri The URI in the clip.
736      * @return Returns a new ClipData containing the specified data.
737      */
738     static public ClipData newUri(ContentResolver resolver, CharSequence label,
739             Uri uri) {
740         Item item = new Item(uri);
741         String[] mimeTypes = null;
742         if ("content".equals(uri.getScheme())) {
743             String realType = resolver.getType(uri);
744             mimeTypes = resolver.getStreamTypes(uri, "*/*");
745             if (mimeTypes == null) {
746                 if (realType != null) {
747                     mimeTypes = new String[] { realType, ClipDescription.MIMETYPE_TEXT_URILIST };
748                 }
749             } else {
750                 String[] tmp = new String[mimeTypes.length + (realType != null ? 2 : 1)];
751                 int i = 0;
752                 if (realType != null) {
753                     tmp[0] = realType;
754                     i++;
755                 }
756                 System.arraycopy(mimeTypes, 0, tmp, i, mimeTypes.length);
757                 tmp[i + mimeTypes.length] = ClipDescription.MIMETYPE_TEXT_URILIST;
758                 mimeTypes = tmp;
759             }
760         }
761         if (mimeTypes == null) {
762             mimeTypes = MIMETYPES_TEXT_URILIST;
763         }
764         return new ClipData(label, mimeTypes, item);
765     }
766
767     /**
768      * Create a new ClipData holding an URI with MIME type
769      * {@link ClipDescription#MIMETYPE_TEXT_URILIST}.
770      * Unlike {@link #newUri(ContentResolver, CharSequence, Uri)}, nothing
771      * is inferred about the URI -- if it is a content: URI holding a bitmap,
772      * the reported type will still be uri-list.  Use this with care!
773      *
774      * @param label User-visible label for the clip data.
775      * @param uri The URI in the clip.
776      * @return Returns a new ClipData containing the specified data.
777      */
778     static public ClipData newRawUri(CharSequence label, Uri uri) {
779         Item item = new Item(uri);
780         return new ClipData(label, MIMETYPES_TEXT_URILIST, item);
781     }
782
783     /**
784      * Return the {@link ClipDescription} associated with this data, describing
785      * what it contains.
786      */
787     public ClipDescription getDescription() {
788         return mClipDescription;
789     }
790     
791     /**
792      * Add a new Item to the overall ClipData container.
793      */
794     public void addItem(Item item) {
795         if (item == null) {
796             throw new NullPointerException("item is null");
797         }
798         mItems.add(item);
799     }
800
801     /** @hide */
802     public Bitmap getIcon() {
803         return mIcon;
804     }
805
806     /**
807      * Return the number of items in the clip data.
808      */
809     public int getItemCount() {
810         return mItems.size();
811     }
812
813     /**
814      * Return a single item inside of the clip data.  The index can range
815      * from 0 to {@link #getItemCount()}-1.
816      */
817     public Item getItemAt(int index) {
818         return mItems.get(index);
819     }
820
821     /**
822      * Prepare this {@link ClipData} to leave an app process.
823      *
824      * @hide
825      */
826     public void prepareToLeaveProcess(boolean leavingPackage) {
827         final int size = mItems.size();
828         for (int i = 0; i < size; i++) {
829             final Item item = mItems.get(i);
830             if (item.mIntent != null) {
831                 item.mIntent.prepareToLeaveProcess(leavingPackage);
832             }
833             if (item.mUri != null && StrictMode.vmFileUriExposureEnabled() && leavingPackage) {
834                 item.mUri.checkFileUriExposed("ClipData.Item.getUri()");
835             }
836         }
837     }
838
839     /** @hide */
840     public void fixUris(int contentUserHint) {
841         final int size = mItems.size();
842         for (int i = 0; i < size; i++) {
843             final Item item = mItems.get(i);
844             if (item.mIntent != null) {
845                 item.mIntent.fixUris(contentUserHint);
846             }
847             if (item.mUri != null) {
848                 item.mUri = maybeAddUserId(item.mUri, contentUserHint);
849             }
850         }
851     }
852
853     /**
854      * Only fixing the data field of the intents
855      * @hide
856      */
857     public void fixUrisLight(int contentUserHint) {
858         final int size = mItems.size();
859         for (int i = 0; i < size; i++) {
860             final Item item = mItems.get(i);
861             if (item.mIntent != null) {
862                 Uri data = item.mIntent.getData();
863                 if (data != null) {
864                     item.mIntent.setData(maybeAddUserId(data, contentUserHint));
865                 }
866             }
867             if (item.mUri != null) {
868                 item.mUri = maybeAddUserId(item.mUri, contentUserHint);
869             }
870         }
871     }
872
873     @Override
874     public String toString() {
875         StringBuilder b = new StringBuilder(128);
876
877         b.append("ClipData { ");
878         toShortString(b);
879         b.append(" }");
880
881         return b.toString();
882     }
883
884     /** @hide */
885     public void toShortString(StringBuilder b) {
886         boolean first;
887         if (mClipDescription != null) {
888             first = !mClipDescription.toShortString(b);
889         } else {
890             first = true;
891         }
892         if (mIcon != null) {
893             if (!first) {
894                 b.append(' ');
895             }
896             first = false;
897             b.append("I:");
898             b.append(mIcon.getWidth());
899             b.append('x');
900             b.append(mIcon.getHeight());
901         }
902         for (int i=0; i<mItems.size(); i++) {
903             if (!first) {
904                 b.append(' ');
905             }
906             first = false;
907             b.append('{');
908             mItems.get(i).toShortString(b);
909             b.append('}');
910         }
911     }
912
913     /** @hide */
914     public void toShortStringShortItems(StringBuilder b, boolean first) {
915         if (mItems.size() > 0) {
916             if (!first) {
917                 b.append(' ');
918             }
919             mItems.get(0).toShortString(b);
920             if (mItems.size() > 1) {
921                 b.append(" ...");
922             }
923         }
924     }
925
926     /** @hide */
927     public void collectUris(List<Uri> out) {
928         for (int i = 0; i < mItems.size(); ++i) {
929             ClipData.Item item = getItemAt(i);
930
931             if (item.getUri() != null) {
932                 out.add(item.getUri());
933             }
934
935             Intent intent = item.getIntent();
936             if (intent != null) {
937                 if (intent.getData() != null) {
938                     out.add(intent.getData());
939                 }
940                 if (intent.getClipData() != null) {
941                     intent.getClipData().collectUris(out);
942                 }
943             }
944         }
945     }
946
947     @Override
948     public int describeContents() {
949         return 0;
950     }
951
952     @Override
953     public void writeToParcel(Parcel dest, int flags) {
954         mClipDescription.writeToParcel(dest, flags);
955         if (mIcon != null) {
956             dest.writeInt(1);
957             mIcon.writeToParcel(dest, flags);
958         } else {
959             dest.writeInt(0);
960         }
961         final int N = mItems.size();
962         dest.writeInt(N);
963         for (int i=0; i<N; i++) {
964             Item item = mItems.get(i);
965             TextUtils.writeToParcel(item.mText, dest, flags);
966             dest.writeString(item.mHtmlText);
967             if (item.mIntent != null) {
968                 dest.writeInt(1);
969                 item.mIntent.writeToParcel(dest, flags);
970             } else {
971                 dest.writeInt(0);
972             }
973             if (item.mUri != null) {
974                 dest.writeInt(1);
975                 item.mUri.writeToParcel(dest, flags);
976             } else {
977                 dest.writeInt(0);
978             }
979         }
980     }
981
982     ClipData(Parcel in) {
983         mClipDescription = new ClipDescription(in);
984         if (in.readInt() != 0) {
985             mIcon = Bitmap.CREATOR.createFromParcel(in);
986         } else {
987             mIcon = null;
988         }
989         mItems = new ArrayList<Item>();
990         final int N = in.readInt();
991         for (int i=0; i<N; i++) {
992             CharSequence text = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
993             String htmlText = in.readString();
994             Intent intent = in.readInt() != 0 ? Intent.CREATOR.createFromParcel(in) : null;
995             Uri uri = in.readInt() != 0 ? Uri.CREATOR.createFromParcel(in) : null;
996             mItems.add(new Item(text, htmlText, intent, uri));
997         }
998     }
999
1000     public static final Parcelable.Creator<ClipData> CREATOR =
1001         new Parcelable.Creator<ClipData>() {
1002
1003             public ClipData createFromParcel(Parcel source) {
1004                 return new ClipData(source);
1005             }
1006
1007             public ClipData[] newArray(int size) {
1008                 return new ClipData[size];
1009             }
1010         };
1011 }