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