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