ClipData.java revision 3aef8e1d1b2f0b87d470bcccf37ba4ebb6560c45
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 android.content.res.AssetFileDescriptor;
20import android.graphics.Bitmap;
21import android.net.Uri;
22import android.os.Parcel;
23import android.os.Parcelable;
24import android.text.TextUtils;
25import android.util.Log;
26
27import java.io.FileInputStream;
28import java.io.FileNotFoundException;
29import java.io.IOException;
30import java.io.InputStreamReader;
31import java.util.ArrayList;
32
33/**
34 * Representation of a clipped data on the clipboard.
35 *
36 * <p>ClippedData is a complex type containing one or Item instances,
37 * each of which can hold one or more representations of an item of data.
38 * For display to the user, it also has a label and iconic representation.</p>
39 *
40 * <p>A ClipData contains a {@link ClipDescription}, which describes
41 * important meta-data about the clip.  In particular, its
42 * {@link ClipDescription#getMimeType(int) getDescription().getMimeType(int)}
43 * must return correct MIME type(s) describing the data in the clip.  For help
44 * in correctly constructing a clip with the correct MIME type, use
45 * {@link #newPlainText(CharSequence, CharSequence)},
46 * {@link #newUri(ContentResolver, CharSequence, Uri)}, and
47 * {@link #newIntent(CharSequence, Intent)}.
48 *
49 * <p>Each Item instance can be one of three main classes of data: a simple
50 * CharSequence of text, a single Intent object, or a Uri.  See {@link Item}
51 * for more details.
52 *
53 * <div class="special reference">
54 * <h3>Developer Guides</h3>
55 * <p>For more information about using the clipboard framework, read the
56 * <a href="{@docRoot}guide/topics/clipboard/copy-paste.html">Copy and Paste</a>
57 * developer guide.</p>
58 * </div>
59 *
60 * <a name="ImplementingPaste"></a>
61 * <h3>Implementing Paste or Drop</h3>
62 *
63 * <p>To implement a paste or drop of a ClippedData object into an application,
64 * the application must correctly interpret the data for its use.  If the {@link Item}
65 * it contains is simple text or an Intent, there is little to be done: text
66 * can only be interpreted as text, and an Intent will typically be used for
67 * creating shortcuts (such as placing icons on the home screen) or other
68 * actions.
69 *
70 * <p>If all you want is the textual representation of the clipped data, you
71 * can use the convenience method {@link Item#coerceToText Item.coerceToText}.
72 * In this case there is generally no need to worry about the MIME types
73 * reported by {@link ClipDescription#getMimeType(int) getDescription().getMimeType(int)},
74 * since any clip item an always be converted to a string.
75 *
76 * <p>More complicated exchanges will be done through URIs, in particular
77 * "content:" URIs.  A content URI allows the recipient of a ClippedData item
78 * to interact closely with the ContentProvider holding the data in order to
79 * negotiate the transfer of that data.  The clip must also be filled in with
80 * the available MIME types; {@link #newUri(ContentResolver, CharSequence, Uri)}
81 * will take care of correctly doing this.
82 *
83 * <p>For example, here is the paste function of a simple NotePad application.
84 * When retrieving the data from the clipboard, it can do either two things:
85 * if the clipboard contains a URI reference to an existing note, it copies
86 * the entire structure of the note into a new note; otherwise, it simply
87 * coerces the clip into text and uses that as the new note's contents.
88 *
89 * {@sample development/samples/NotePad/src/com/example/android/notepad/NoteEditor.java
90 *      paste}
91 *
92 * <p>In many cases an application can paste various types of streams of data.  For
93 * example, an e-mail application may want to allow the user to paste an image
94 * or other binary data as an attachment.  This is accomplished through the
95 * ContentResolver {@link ContentResolver#getStreamTypes(Uri, String)} and
96 * {@link ContentResolver#openTypedAssetFileDescriptor(Uri, String, android.os.Bundle)}
97 * methods.  These allow a client to discover the type(s) of data that a particular
98 * content URI can make available as a stream and retrieve the stream of data.
99 *
100 * <p>For example, the implementation of {@link Item#coerceToText Item.coerceToText}
101 * itself uses this to try to retrieve a URI clip as a stream of text:
102 *
103 * {@sample frameworks/base/core/java/android/content/ClipData.java coerceToText}
104 *
105 * <a name="ImplementingCopy"></a>
106 * <h3>Implementing Copy or Drag</h3>
107 *
108 * <p>To be the source of a clip, the application must construct a ClippedData
109 * object that any recipient can interpret best for their context.  If the clip
110 * is to contain a simple text, Intent, or URI, this is easy: an {@link Item}
111 * containing the appropriate data type can be constructed and used.
112 *
113 * <p>More complicated data types require the implementation of support in
114 * a ContentProvider for describing and generating the data for the recipient.
115 * A common scenario is one where an application places on the clipboard the
116 * content: URI of an object that the user has copied, with the data at that
117 * URI consisting of a complicated structure that only other applications with
118 * direct knowledge of the structure can use.
119 *
120 * <p>For applications that do not have intrinsic knowledge of the data structure,
121 * the content provider holding it can make the data available as an arbitrary
122 * number of types of data streams.  This is done by implementing the
123 * ContentProvider {@link ContentProvider#getStreamTypes(Uri, String)} and
124 * {@link ContentProvider#openTypedAssetFile(Uri, String, android.os.Bundle)}
125 * methods.
126 *
127 * <p>Going back to our simple NotePad application, this is the implementation
128 * it may have to convert a single note URI (consisting of a title and the note
129 * text) into a stream of plain text data.
130 *
131 * {@sample development/samples/NotePad/src/com/example/android/notepad/NotePadProvider.java
132 *      stream}
133 *
134 * <p>The copy operation in our NotePad application is now just a simple matter
135 * of making a clip containing the URI of the note being copied:
136 *
137 * {@sample development/samples/NotePad/src/com/example/android/notepad/NotesList.java
138 *      copy}
139 *
140 * <p>Note if a paste operation needs this clip as text (for example to paste
141 * into an editor), then {@link Item#coerceToText(Context)} will ask the content
142 * provider for the clip URI as text and successfully paste the entire note.
143 */
144public class ClipData implements Parcelable {
145    static final String[] MIMETYPES_TEXT_PLAIN = new String[] {
146        ClipDescription.MIMETYPE_TEXT_PLAIN };
147    static final String[] MIMETYPES_TEXT_URILIST = new String[] {
148        ClipDescription.MIMETYPE_TEXT_URILIST };
149    static final String[] MIMETYPES_TEXT_INTENT = new String[] {
150        ClipDescription.MIMETYPE_TEXT_INTENT };
151
152    final ClipDescription mClipDescription;
153
154    final Bitmap mIcon;
155
156    final ArrayList<Item> mItems = new ArrayList<Item>();
157
158    /**
159     * Description of a single item in a ClippedData.
160     *
161     * <p>The types than an individual item can currently contain are:</p>
162     *
163     * <ul>
164     * <li> Text: a basic string of text.  This is actually a CharSequence,
165     * so it can be formatted text supported by corresponding Android built-in
166     * style spans.  (Custom application spans are not supported and will be
167     * stripped when transporting through the clipboard.)
168     * <li> Intent: an arbitrary Intent object.  A typical use is the shortcut
169     * to create when pasting a clipped item on to the home screen.
170     * <li> Uri: a URI reference.  This may be any URI (such as an http: URI
171     * representing a bookmark), however it is often a content: URI.  Using
172     * content provider references as clips like this allows an application to
173     * share complex or large clips through the standard content provider
174     * facilities.
175     * </ul>
176     */
177    public static class Item {
178        final CharSequence mText;
179        final Intent mIntent;
180        final Uri mUri;
181
182        /**
183         * Create an Item consisting of a single block of (possibly styled) text.
184         */
185        public Item(CharSequence text) {
186            mText = text;
187            mIntent = null;
188            mUri = null;
189        }
190
191        /**
192         * Create an Item consisting of an arbitrary Intent.
193         */
194        public Item(Intent intent) {
195            mText = null;
196            mIntent = intent;
197            mUri = null;
198        }
199
200        /**
201         * Create an Item consisting of an arbitrary URI.
202         */
203        public Item(Uri uri) {
204            mText = null;
205            mIntent = null;
206            mUri = uri;
207        }
208
209        /**
210         * Create a complex Item, containing multiple representations of
211         * text, intent, and/or URI.
212         */
213        public Item(CharSequence text, Intent intent, Uri uri) {
214            mText = text;
215            mIntent = intent;
216            mUri = uri;
217        }
218
219        /**
220         * Retrieve the raw text contained in this Item.
221         */
222        public CharSequence getText() {
223            return mText;
224        }
225
226        /**
227         * Retrieve the raw Intent contained in this Item.
228         */
229        public Intent getIntent() {
230            return mIntent;
231        }
232
233        /**
234         * Retrieve the raw URI contained in this Item.
235         */
236        public Uri getUri() {
237            return mUri;
238        }
239
240        /**
241         * Turn this item into text, regardless of the type of data it
242         * actually contains.
243         *
244         * <p>The algorithm for deciding what text to return is:
245         * <ul>
246         * <li> If {@link #getText} is non-null, return that.
247         * <li> If {@link #getUri} is non-null, try to retrieve its data
248         * as a text stream from its content provider.  If this succeeds, copy
249         * the text into a String and return it.  If it is not a content: URI or
250         * the content provider does not supply a text representation, return
251         * the raw URI as a string.
252         * <li> If {@link #getIntent} is non-null, convert that to an intent:
253         * URI and returnit.
254         * <li> Otherwise, return an empty string.
255         * </ul>
256         *
257         * @param context The caller's Context, from which its ContentResolver
258         * and other things can be retrieved.
259         * @return Returns the item's textual representation.
260         */
261//BEGIN_INCLUDE(coerceToText)
262        public CharSequence coerceToText(Context context) {
263            // If this Item has an explicit textual value, simply return that.
264            if (mText != null) {
265                return mText;
266            }
267
268            // If this Item has a URI value, try using that.
269            if (mUri != null) {
270
271                // First see if the URI can be opened as a plain text stream
272                // (of any sub-type).  If so, this is the best textual
273                // representation for it.
274                FileInputStream stream = null;
275                try {
276                    // Ask for a stream of the desired type.
277                    AssetFileDescriptor descr = context.getContentResolver()
278                            .openTypedAssetFileDescriptor(mUri, "text/*", null);
279                    stream = descr.createInputStream();
280                    InputStreamReader reader = new InputStreamReader(stream, "UTF-8");
281
282                    // Got it...  copy the stream into a local string and return it.
283                    StringBuilder builder = new StringBuilder(128);
284                    char[] buffer = new char[8192];
285                    int len;
286                    while ((len=reader.read(buffer)) > 0) {
287                        builder.append(buffer, 0, len);
288                    }
289                    return builder.toString();
290
291                } catch (FileNotFoundException e) {
292                    // Unable to open content URI as text...  not really an
293                    // error, just something to ignore.
294
295                } catch (IOException e) {
296                    // Something bad has happened.
297                    Log.w("ClippedData", "Failure loading text", e);
298                    return e.toString();
299
300                } finally {
301                    if (stream != null) {
302                        try {
303                            stream.close();
304                        } catch (IOException e) {
305                        }
306                    }
307                }
308
309                // If we couldn't open the URI as a stream, then the URI itself
310                // probably serves fairly well as a textual representation.
311                return mUri.toString();
312            }
313
314            // Finally, if all we have is an Intent, then we can just turn that
315            // into text.  Not the most user-friendly thing, but it's something.
316            if (mIntent != null) {
317                return mIntent.toUri(Intent.URI_INTENT_SCHEME);
318            }
319
320            // Shouldn't get here, but just in case...
321            return "";
322        }
323//END_INCLUDE(coerceToText)
324    }
325
326    /**
327     * Create a new clip.
328     *
329     * @param label Label to show to the user describing this clip.
330     * @param mimeTypes An array of MIME types this data is available as.
331     * @param item The contents of the first item in the clip.
332     */
333    public ClipData(CharSequence label, String[] mimeTypes, Item item) {
334        mClipDescription = new ClipDescription(label, mimeTypes);
335        if (item == null) {
336            throw new NullPointerException("item is null");
337        }
338        mIcon = null;
339        mItems.add(item);
340    }
341
342    /**
343     * Create a new clip.
344     *
345     * @param description The ClipDescription describing the clip contents.
346     * @param item The contents of the first item in the clip.
347     */
348    public ClipData(ClipDescription description, Item item) {
349        mClipDescription = description;
350        if (item == null) {
351            throw new NullPointerException("item is null");
352        }
353        mIcon = null;
354        mItems.add(item);
355    }
356
357    /**
358     * Create a new ClipData holding data of the type
359     * {@link ClipDescription#MIMETYPE_TEXT_PLAIN}.
360     *
361     * @param label User-visible label for the clip data.
362     * @param text The actual text in the clip.
363     * @return Returns a new ClipData containing the specified data.
364     */
365    static public ClipData newPlainText(CharSequence label, CharSequence text) {
366        Item item = new Item(text);
367        return new ClipData(label, MIMETYPES_TEXT_PLAIN, item);
368    }
369
370    /**
371     * Create a new ClipData holding an Intent with MIME type
372     * {@link ClipDescription#MIMETYPE_TEXT_INTENT}.
373     *
374     * @param label User-visible label for the clip data.
375     * @param intent The actual Intent in the clip.
376     * @return Returns a new ClipData containing the specified data.
377     */
378    static public ClipData newIntent(CharSequence label, Intent intent) {
379        Item item = new Item(intent);
380        return new ClipData(label, MIMETYPES_TEXT_INTENT, item);
381    }
382
383    /**
384     * Create a new ClipData holding a URI.  If the URI is a content: URI,
385     * this will query the content provider for the MIME type of its data and
386     * use that as the MIME type.  Otherwise, it will use the MIME type
387     * {@link ClipDescription#MIMETYPE_TEXT_URILIST}.
388     *
389     * @param resolver ContentResolver used to get information about the URI.
390     * @param label User-visible label for the clip data.
391     * @param uri The URI in the clip.
392     * @return Returns a new ClipData containing the specified data.
393     */
394    static public ClipData newUri(ContentResolver resolver, CharSequence label,
395            Uri uri) {
396        Item item = new Item(uri);
397        String[] mimeTypes = null;
398        if ("content".equals(uri.getScheme())) {
399            String realType = resolver.getType(uri);
400            mimeTypes = resolver.getStreamTypes(uri, "*/*");
401            if (mimeTypes == null) {
402                if (realType != null) {
403                    mimeTypes = new String[] { realType, ClipDescription.MIMETYPE_TEXT_URILIST };
404                }
405            } else {
406                String[] tmp = new String[mimeTypes.length + (realType != null ? 2 : 1)];
407                int i = 0;
408                if (realType != null) {
409                    tmp[0] = realType;
410                    i++;
411                }
412                System.arraycopy(mimeTypes, 0, tmp, i, mimeTypes.length);
413                tmp[i + mimeTypes.length] = ClipDescription.MIMETYPE_TEXT_URILIST;
414                mimeTypes = tmp;
415            }
416        }
417        if (mimeTypes == null) {
418            mimeTypes = MIMETYPES_TEXT_URILIST;
419        }
420        return new ClipData(label, mimeTypes, item);
421    }
422
423    /**
424     * Create a new ClipData holding an URI with MIME type
425     * {@link ClipDescription#MIMETYPE_TEXT_URILIST}.
426     * Unlike {@link #newUri(ContentResolver, CharSequence, Uri)}, nothing
427     * is inferred about the URI -- if it is a content: URI holding a bitmap,
428     * the reported type will still be uri-list.  Use this with care!
429     *
430     * @param label User-visible label for the clip data.
431     * @param uri The URI in the clip.
432     * @return Returns a new ClipData containing the specified data.
433     */
434    static public ClipData newRawUri(CharSequence label, Uri uri) {
435        Item item = new Item(uri);
436        return new ClipData(label, MIMETYPES_TEXT_URILIST, item);
437    }
438
439    /**
440     * Return the {@link ClipDescription} associated with this data, describing
441     * what it contains.
442     */
443    public ClipDescription getDescription() {
444        return mClipDescription;
445    }
446
447    /**
448     * Add a new Item to the overall ClipData container.
449     */
450    public void addItem(Item item) {
451        if (item == null) {
452            throw new NullPointerException("item is null");
453        }
454        mItems.add(item);
455    }
456
457    /** @hide */
458    public Bitmap getIcon() {
459        return mIcon;
460    }
461
462    /**
463     * Return the number of items in the clip data.
464     */
465    public int getItemCount() {
466        return mItems.size();
467    }
468
469    /**
470     * Return a single item inside of the clip data.  The index can range
471     * from 0 to {@link #getItemCount()}-1.
472     */
473    public Item getItemAt(int index) {
474        return mItems.get(index);
475    }
476
477    @Override
478    public int describeContents() {
479        return 0;
480    }
481
482    @Override
483    public void writeToParcel(Parcel dest, int flags) {
484        mClipDescription.writeToParcel(dest, flags);
485        if (mIcon != null) {
486            dest.writeInt(1);
487            mIcon.writeToParcel(dest, flags);
488        } else {
489            dest.writeInt(0);
490        }
491        final int N = mItems.size();
492        dest.writeInt(N);
493        for (int i=0; i<N; i++) {
494            Item item = mItems.get(i);
495            TextUtils.writeToParcel(item.mText, dest, flags);
496            if (item.mIntent != null) {
497                dest.writeInt(1);
498                item.mIntent.writeToParcel(dest, flags);
499            } else {
500                dest.writeInt(0);
501            }
502            if (item.mUri != null) {
503                dest.writeInt(1);
504                item.mUri.writeToParcel(dest, flags);
505            } else {
506                dest.writeInt(0);
507            }
508        }
509    }
510
511    ClipData(Parcel in) {
512        mClipDescription = new ClipDescription(in);
513        if (in.readInt() != 0) {
514            mIcon = Bitmap.CREATOR.createFromParcel(in);
515        } else {
516            mIcon = null;
517        }
518        final int N = in.readInt();
519        for (int i=0; i<N; i++) {
520            CharSequence text = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
521            Intent intent = in.readInt() != 0 ? Intent.CREATOR.createFromParcel(in) : null;
522            Uri uri = in.readInt() != 0 ? Uri.CREATOR.createFromParcel(in) : null;
523            mItems.add(new Item(text, intent, uri));
524        }
525    }
526
527    public static final Parcelable.Creator<ClipData> CREATOR =
528        new Parcelable.Creator<ClipData>() {
529
530            public ClipData createFromParcel(Parcel source) {
531                return new ClipData(source);
532            }
533
534            public ClipData[] newArray(int size) {
535                return new ClipData[size];
536            }
537        };
538}
539