blob: 88e2c220bb8dc637a08ef011111d26e9d8f3cfc9 [file] [log] [blame]
Dianne Hackborn9f531192010-08-04 17:48:03 -07001/**
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
Nicolas Prevotd85fc722014-04-16 19:52:08 +010019import static android.content.ContentProvider.maybeAddUserId;
Vladislav Kaznacheeve1f5e132017-01-27 16:56:40 -080020import static android.content.ContentResolver.SCHEME_ANDROID_RESOURCE;
21import static android.content.ContentResolver.SCHEME_CONTENT;
22import static android.content.ContentResolver.SCHEME_FILE;
Vladislav Kaznacheevc14df8e2016-01-22 11:49:13 -080023
Mathew Inwood5c0d3542018-08-14 13:54:31 +010024import android.annotation.UnsupportedAppUsage;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070025import android.content.res.AssetFileDescriptor;
Dianne Hackborn9f531192010-08-04 17:48:03 -070026import android.graphics.Bitmap;
27import android.net.Uri;
Mathew Inwood8c854f82018-09-14 12:35:36 +010028import android.os.Build;
Dianne Hackborn9f531192010-08-04 17:48:03 -070029import android.os.Parcel;
Satoshi Niwa472371c2018-08-01 17:22:02 +090030import android.os.ParcelFileDescriptor;
Dianne Hackborn9f531192010-08-04 17:48:03 -070031import android.os.Parcelable;
Jeff Sharkeya14acd22013-04-02 18:27:45 -070032import android.os.StrictMode;
Dianne Hackbornacb69bb2012-04-13 15:36:06 -070033import android.text.Html;
34import android.text.Spannable;
35import android.text.SpannableStringBuilder;
36import android.text.Spanned;
Dianne Hackborn9f531192010-08-04 17:48:03 -070037import android.text.TextUtils;
Dianne Hackbornacb69bb2012-04-13 15:36:06 -070038import android.text.style.URLSpan;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070039import android.util.Log;
Kweku Adams85f2fbc2017-12-18 12:04:12 -080040import android.util.proto.ProtoOutputStream;
Dianne Hackborn9f531192010-08-04 17:48:03 -070041
Vladislav Kaznacheev8e7b9402016-11-23 15:31:13 -080042import com.android.internal.util.ArrayUtils;
43
Kweku Adams85f2fbc2017-12-18 12:04:12 -080044import libcore.io.IoUtils;
45
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070046import java.io.FileInputStream;
47import java.io.FileNotFoundException;
48import java.io.IOException;
49import java.io.InputStreamReader;
Dianne Hackborn9f531192010-08-04 17:48:03 -070050import java.util.ArrayList;
Vladislav Kaznacheev9149d2b2015-12-15 12:16:28 -080051import java.util.List;
Dianne Hackborn9f531192010-08-04 17:48:03 -070052
53/**
54 * Representation of a clipped data on the clipboard.
55 *
Vladislav Kaznacheev7e4669c2016-05-02 17:04:08 -070056 * <p>ClipData is a complex type containing one or more Item instances,
Dianne Hackborn9f531192010-08-04 17:48:03 -070057 * each of which can hold one or more representations of an item of data.
Vladislav Kaznacheev7e4669c2016-05-02 17:04:08 -070058 * For display to the user, it also has a label.</p>
Dianne Hackborn9f531192010-08-04 17:48:03 -070059 *
Dianne Hackbornf834dfa2010-10-26 12:43:57 -070060 * <p>A ClipData contains a {@link ClipDescription}, which describes
61 * important meta-data about the clip. In particular, its
62 * {@link ClipDescription#getMimeType(int) getDescription().getMimeType(int)}
Dianne Hackborn1040dc42010-08-26 22:11:06 -070063 * must return correct MIME type(s) describing the data in the clip. For help
64 * in correctly constructing a clip with the correct MIME type, use
Dianne Hackborn327fbd22011-01-17 14:38:50 -080065 * {@link #newPlainText(CharSequence, CharSequence)},
66 * {@link #newUri(ContentResolver, CharSequence, Uri)}, and
67 * {@link #newIntent(CharSequence, Intent)}.
Dianne Hackborn1040dc42010-08-26 22:11:06 -070068 *
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070069 * <p>Each Item instance can be one of three main classes of data: a simple
70 * CharSequence of text, a single Intent object, or a Uri. See {@link Item}
71 * for more details.
Dianne Hackborn9f531192010-08-04 17:48:03 -070072 *
Joe Fernandez3aef8e1d2011-12-20 10:38:34 -080073 * <div class="special reference">
74 * <h3>Developer Guides</h3>
75 * <p>For more information about using the clipboard framework, read the
76 * <a href="{@docRoot}guide/topics/clipboard/copy-paste.html">Copy and Paste</a>
77 * developer guide.</p>
78 * </div>
79 *
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070080 * <a name="ImplementingPaste"></a>
81 * <h3>Implementing Paste or Drop</h3>
82 *
Vladislav Kaznacheev7e4669c2016-05-02 17:04:08 -070083 * <p>To implement a paste or drop of a ClipData object into an application,
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070084 * the application must correctly interpret the data for its use. If the {@link Item}
85 * it contains is simple text or an Intent, there is little to be done: text
86 * can only be interpreted as text, and an Intent will typically be used for
87 * creating shortcuts (such as placing icons on the home screen) or other
88 * actions.
89 *
90 * <p>If all you want is the textual representation of the clipped data, you
91 * can use the convenience method {@link Item#coerceToText Item.coerceToText}.
Dianne Hackborn1040dc42010-08-26 22:11:06 -070092 * In this case there is generally no need to worry about the MIME types
Dianne Hackbornf834dfa2010-10-26 12:43:57 -070093 * reported by {@link ClipDescription#getMimeType(int) getDescription().getMimeType(int)},
Newton Allen4465d1a2013-11-26 10:25:38 -080094 * since any clip item can always be converted to a string.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070095 *
96 * <p>More complicated exchanges will be done through URIs, in particular
Vladislav Kaznacheev7e4669c2016-05-02 17:04:08 -070097 * "content:" URIs. A content URI allows the recipient of a ClipData item
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070098 * to interact closely with the ContentProvider holding the data in order to
Dianne Hackborn1040dc42010-08-26 22:11:06 -070099 * negotiate the transfer of that data. The clip must also be filled in with
Dianne Hackborn327fbd22011-01-17 14:38:50 -0800100 * the available MIME types; {@link #newUri(ContentResolver, CharSequence, Uri)}
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700101 * will take care of correctly doing this.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700102 *
103 * <p>For example, here is the paste function of a simple NotePad application.
104 * When retrieving the data from the clipboard, it can do either two things:
105 * if the clipboard contains a URI reference to an existing note, it copies
106 * the entire structure of the note into a new note; otherwise, it simply
107 * coerces the clip into text and uses that as the new note's contents.
108 *
109 * {@sample development/samples/NotePad/src/com/example/android/notepad/NoteEditor.java
110 * paste}
111 *
112 * <p>In many cases an application can paste various types of streams of data. For
113 * example, an e-mail application may want to allow the user to paste an image
114 * or other binary data as an attachment. This is accomplished through the
115 * ContentResolver {@link ContentResolver#getStreamTypes(Uri, String)} and
116 * {@link ContentResolver#openTypedAssetFileDescriptor(Uri, String, android.os.Bundle)}
117 * methods. These allow a client to discover the type(s) of data that a particular
118 * content URI can make available as a stream and retrieve the stream of data.
119 *
120 * <p>For example, the implementation of {@link Item#coerceToText Item.coerceToText}
121 * itself uses this to try to retrieve a URI clip as a stream of text:
122 *
Dianne Hackbornf6d952b2010-08-27 15:41:13 -0700123 * {@sample frameworks/base/core/java/android/content/ClipData.java coerceToText}
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700124 *
125 * <a name="ImplementingCopy"></a>
126 * <h3>Implementing Copy or Drag</h3>
127 *
Vladislav Kaznacheev7e4669c2016-05-02 17:04:08 -0700128 * <p>To be the source of a clip, the application must construct a ClipData
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700129 * object that any recipient can interpret best for their context. If the clip
130 * is to contain a simple text, Intent, or URI, this is easy: an {@link Item}
131 * containing the appropriate data type can be constructed and used.
132 *
133 * <p>More complicated data types require the implementation of support in
134 * a ContentProvider for describing and generating the data for the recipient.
135 * A common scenario is one where an application places on the clipboard the
136 * content: URI of an object that the user has copied, with the data at that
137 * URI consisting of a complicated structure that only other applications with
138 * direct knowledge of the structure can use.
139 *
140 * <p>For applications that do not have intrinsic knowledge of the data structure,
141 * the content provider holding it can make the data available as an arbitrary
142 * number of types of data streams. This is done by implementing the
143 * ContentProvider {@link ContentProvider#getStreamTypes(Uri, String)} and
144 * {@link ContentProvider#openTypedAssetFile(Uri, String, android.os.Bundle)}
145 * methods.
146 *
147 * <p>Going back to our simple NotePad application, this is the implementation
148 * it may have to convert a single note URI (consisting of a title and the note
149 * text) into a stream of plain text data.
150 *
151 * {@sample development/samples/NotePad/src/com/example/android/notepad/NotePadProvider.java
152 * stream}
153 *
154 * <p>The copy operation in our NotePad application is now just a simple matter
155 * of making a clip containing the URI of the note being copied:
156 *
157 * {@sample development/samples/NotePad/src/com/example/android/notepad/NotesList.java
158 * copy}
159 *
160 * <p>Note if a paste operation needs this clip as text (for example to paste
161 * into an editor), then {@link Item#coerceToText(Context)} will ask the content
162 * provider for the clip URI as text and successfully paste the entire note.
Dianne Hackborn9f531192010-08-04 17:48:03 -0700163 */
Dianne Hackbornf834dfa2010-10-26 12:43:57 -0700164public class ClipData implements Parcelable {
165 static final String[] MIMETYPES_TEXT_PLAIN = new String[] {
166 ClipDescription.MIMETYPE_TEXT_PLAIN };
Dianne Hackbornacb69bb2012-04-13 15:36:06 -0700167 static final String[] MIMETYPES_TEXT_HTML = new String[] {
168 ClipDescription.MIMETYPE_TEXT_HTML };
Dianne Hackbornf834dfa2010-10-26 12:43:57 -0700169 static final String[] MIMETYPES_TEXT_URILIST = new String[] {
170 ClipDescription.MIMETYPE_TEXT_URILIST };
171 static final String[] MIMETYPES_TEXT_INTENT = new String[] {
172 ClipDescription.MIMETYPE_TEXT_INTENT };
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700173
Satoshi Niwa472371c2018-08-01 17:22:02 +0900174 // Constants used in {@link #writeHtmlTextToParcel}.
175 static final int PARCEL_MAX_SIZE_BYTES = 800 * 1024;
176 static final int PARCEL_TYPE_STRING = 0;
177 static final int PARCEL_TYPE_PFD = 1;
178
Dianne Hackbornf834dfa2010-10-26 12:43:57 -0700179 final ClipDescription mClipDescription;
Vladislav Kaznacheev7e4669c2016-05-02 17:04:08 -0700180
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700181 final Bitmap mIcon;
Dianne Hackborn9f531192010-08-04 17:48:03 -0700182
Dianne Hackborn21c241e2012-03-08 13:57:23 -0800183 final ArrayList<Item> mItems;
Dianne Hackborn9f531192010-08-04 17:48:03 -0700184
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700185 /**
Vladislav Kaznacheev7e4669c2016-05-02 17:04:08 -0700186 * Description of a single item in a ClipData.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700187 *
188 * <p>The types than an individual item can currently contain are:</p>
189 *
190 * <ul>
191 * <li> Text: a basic string of text. This is actually a CharSequence,
192 * so it can be formatted text supported by corresponding Android built-in
193 * style spans. (Custom application spans are not supported and will be
194 * stripped when transporting through the clipboard.)
195 * <li> Intent: an arbitrary Intent object. A typical use is the shortcut
196 * to create when pasting a clipped item on to the home screen.
197 * <li> Uri: a URI reference. This may be any URI (such as an http: URI
198 * representing a bookmark), however it is often a content: URI. Using
199 * content provider references as clips like this allows an application to
200 * share complex or large clips through the standard content provider
201 * facilities.
202 * </ul>
203 */
Dianne Hackborn9f531192010-08-04 17:48:03 -0700204 public static class Item {
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700205 final CharSequence mText;
Dianne Hackbornacb69bb2012-04-13 15:36:06 -0700206 final String mHtmlText;
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700207 final Intent mIntent;
Mathew Inwood8c854f82018-09-14 12:35:36 +0100208 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100209 Uri mUri;
Dianne Hackborn9f531192010-08-04 17:48:03 -0700210
Nicolas Prevot58926242016-07-14 19:11:10 +0100211 /** @hide */
212 public Item(Item other) {
213 mText = other.mText;
214 mHtmlText = other.mHtmlText;
215 mIntent = other.mIntent;
216 mUri = other.mUri;
217 }
218
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700219 /**
220 * Create an Item consisting of a single block of (possibly styled) text.
221 */
Dianne Hackborn9f531192010-08-04 17:48:03 -0700222 public Item(CharSequence text) {
223 mText = text;
Dianne Hackbornacb69bb2012-04-13 15:36:06 -0700224 mHtmlText = null;
225 mIntent = null;
226 mUri = null;
227 }
228
229 /**
230 * Create an Item consisting of a single block of (possibly styled) text,
231 * with an alternative HTML formatted representation. You <em>must</em>
232 * supply a plain text representation in addition to HTML text; coercion
kopriva219f7dc2018-10-09 13:42:28 -0700233 * will not be done from HTML formatted text into plain text.
Satoshi Niwa472371c2018-08-01 17:22:02 +0900234 * <p class="note"><strong>Note:</strong> It is strongly recommended to
235 * use content: URI for sharing large clip data. Starting on API 30,
236 * ClipData.Item doesn't accept an HTML text if it's larger than 800KB.
237 * </p>
Dianne Hackbornacb69bb2012-04-13 15:36:06 -0700238 */
239 public Item(CharSequence text, String htmlText) {
240 mText = text;
241 mHtmlText = htmlText;
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700242 mIntent = null;
243 mUri = null;
Dianne Hackborn9f531192010-08-04 17:48:03 -0700244 }
245
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700246 /**
247 * Create an Item consisting of an arbitrary Intent.
248 */
Dianne Hackborn9f531192010-08-04 17:48:03 -0700249 public Item(Intent intent) {
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700250 mText = null;
Dianne Hackbornacb69bb2012-04-13 15:36:06 -0700251 mHtmlText = null;
Dianne Hackborn9f531192010-08-04 17:48:03 -0700252 mIntent = intent;
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700253 mUri = null;
Dianne Hackborn9f531192010-08-04 17:48:03 -0700254 }
255
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700256 /**
257 * Create an Item consisting of an arbitrary URI.
258 */
Dianne Hackborn9f531192010-08-04 17:48:03 -0700259 public Item(Uri uri) {
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700260 mText = null;
Dianne Hackbornacb69bb2012-04-13 15:36:06 -0700261 mHtmlText = null;
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700262 mIntent = null;
Dianne Hackborn9f531192010-08-04 17:48:03 -0700263 mUri = uri;
264 }
265
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700266 /**
267 * Create a complex Item, containing multiple representations of
Dianne Hackbornacb69bb2012-04-13 15:36:06 -0700268 * text, Intent, and/or URI.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700269 */
Dianne Hackborn9f531192010-08-04 17:48:03 -0700270 public Item(CharSequence text, Intent intent, Uri uri) {
271 mText = text;
Dianne Hackbornacb69bb2012-04-13 15:36:06 -0700272 mHtmlText = null;
273 mIntent = intent;
274 mUri = uri;
275 }
276
277 /**
278 * Create a complex Item, containing multiple representations of
279 * text, HTML text, Intent, and/or URI. If providing HTML text, you
280 * <em>must</em> supply a plain text representation as well; coercion
kopriva219f7dc2018-10-09 13:42:28 -0700281 * will not be done from HTML formatted text into plain text.
Dianne Hackbornacb69bb2012-04-13 15:36:06 -0700282 */
283 public Item(CharSequence text, String htmlText, Intent intent, Uri uri) {
284 if (htmlText != null && text == null) {
285 throw new IllegalArgumentException(
286 "Plain text must be supplied if HTML text is supplied");
287 }
288 mText = text;
289 mHtmlText = htmlText;
Dianne Hackborn9f531192010-08-04 17:48:03 -0700290 mIntent = intent;
291 mUri = uri;
292 }
293
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700294 /**
295 * Retrieve the raw text contained in this Item.
296 */
Dianne Hackborn9f531192010-08-04 17:48:03 -0700297 public CharSequence getText() {
298 return mText;
299 }
300
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700301 /**
Dianne Hackbornacb69bb2012-04-13 15:36:06 -0700302 * Retrieve the raw HTML text contained in this Item.
303 */
304 public String getHtmlText() {
305 return mHtmlText;
306 }
307
308 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700309 * Retrieve the raw Intent contained in this Item.
310 */
Dianne Hackborn9f531192010-08-04 17:48:03 -0700311 public Intent getIntent() {
312 return mIntent;
313 }
314
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700315 /**
316 * Retrieve the raw URI contained in this Item.
317 */
Dianne Hackborn9f531192010-08-04 17:48:03 -0700318 public Uri getUri() {
319 return mUri;
320 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700321
322 /**
323 * Turn this item into text, regardless of the type of data it
324 * actually contains.
325 *
326 * <p>The algorithm for deciding what text to return is:
327 * <ul>
328 * <li> If {@link #getText} is non-null, return that.
329 * <li> If {@link #getUri} is non-null, try to retrieve its data
330 * as a text stream from its content provider. If this succeeds, copy
331 * the text into a String and return it. If it is not a content: URI or
332 * the content provider does not supply a text representation, return
333 * the raw URI as a string.
334 * <li> If {@link #getIntent} is non-null, convert that to an intent:
Dianne Hackbornacb69bb2012-04-13 15:36:06 -0700335 * URI and return it.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700336 * <li> Otherwise, return an empty string.
337 * </ul>
338 *
339 * @param context The caller's Context, from which its ContentResolver
340 * and other things can be retrieved.
341 * @return Returns the item's textual representation.
342 */
343//BEGIN_INCLUDE(coerceToText)
344 public CharSequence coerceToText(Context context) {
345 // If this Item has an explicit textual value, simply return that.
Dianne Hackbornacb69bb2012-04-13 15:36:06 -0700346 CharSequence text = getText();
347 if (text != null) {
348 return text;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700349 }
350
351 // If this Item has a URI value, try using that.
Dianne Hackbornacb69bb2012-04-13 15:36:06 -0700352 Uri uri = getUri();
353 if (uri != null) {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700354 // First see if the URI can be opened as a plain text stream
355 // (of any sub-type). If so, this is the best textual
356 // representation for it.
Daichi Hirono3d9f3fc2017-04-12 14:23:06 +0900357 final ContentResolver resolver = context.getContentResolver();
358 AssetFileDescriptor descr = null;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700359 FileInputStream stream = null;
Daichi Hirono3d9f3fc2017-04-12 14:23:06 +0900360 InputStreamReader reader = null;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700361 try {
Daichi Hirono3d9f3fc2017-04-12 14:23:06 +0900362 try {
363 // Ask for a stream of the desired type.
364 descr = resolver.openTypedAssetFileDescriptor(uri, "text/*", null);
365 } catch (SecurityException e) {
366 Log.w("ClipData", "Failure opening stream", e);
367 } catch (FileNotFoundException|RuntimeException e) {
368 // Unable to open content URI as text... not really an
369 // error, just something to ignore.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700370 }
Daichi Hirono3d9f3fc2017-04-12 14:23:06 +0900371 if (descr != null) {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700372 try {
Daichi Hirono3d9f3fc2017-04-12 14:23:06 +0900373 stream = descr.createInputStream();
374 reader = new InputStreamReader(stream, "UTF-8");
375
376 // Got it... copy the stream into a local string and return it.
377 final StringBuilder builder = new StringBuilder(128);
378 char[] buffer = new char[8192];
379 int len;
380 while ((len=reader.read(buffer)) > 0) {
381 builder.append(buffer, 0, len);
382 }
383 return builder.toString();
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700384 } catch (IOException e) {
Daichi Hirono3d9f3fc2017-04-12 14:23:06 +0900385 // Something bad has happened.
386 Log.w("ClipData", "Failure loading text", e);
387 return e.toString();
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700388 }
389 }
Daichi Hirono3d9f3fc2017-04-12 14:23:06 +0900390 } finally {
391 IoUtils.closeQuietly(descr);
392 IoUtils.closeQuietly(stream);
393 IoUtils.closeQuietly(reader);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700394 }
395
Vladislav Kaznacheeve1f5e132017-01-27 16:56:40 -0800396 // If we couldn't open the URI as a stream, use the URI itself as a textual
397 // representation (but not for "content", "android.resource" or "file" schemes).
398 final String scheme = uri.getScheme();
399 if (SCHEME_CONTENT.equals(scheme)
400 || SCHEME_ANDROID_RESOURCE.equals(scheme)
401 || SCHEME_FILE.equals(scheme)) {
402 return "";
403 }
Dianne Hackbornacb69bb2012-04-13 15:36:06 -0700404 return uri.toString();
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700405 }
406
407 // Finally, if all we have is an Intent, then we can just turn that
408 // into text. Not the most user-friendly thing, but it's something.
Dianne Hackbornacb69bb2012-04-13 15:36:06 -0700409 Intent intent = getIntent();
410 if (intent != null) {
411 return intent.toUri(Intent.URI_INTENT_SCHEME);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700412 }
413
414 // Shouldn't get here, but just in case...
415 return "";
416 }
417//END_INCLUDE(coerceToText)
Dianne Hackborn21c241e2012-03-08 13:57:23 -0800418
Dianne Hackbornacb69bb2012-04-13 15:36:06 -0700419 /**
420 * Like {@link #coerceToHtmlText(Context)}, but any text that would
421 * be returned as HTML formatting will be returned as text with
422 * style spans.
423 * @param context The caller's Context, from which its ContentResolver
424 * and other things can be retrieved.
425 * @return Returns the item's textual representation.
426 */
427 public CharSequence coerceToStyledText(Context context) {
428 CharSequence text = getText();
429 if (text instanceof Spanned) {
430 return text;
431 }
432 String htmlText = getHtmlText();
433 if (htmlText != null) {
434 try {
435 CharSequence newText = Html.fromHtml(htmlText);
436 if (newText != null) {
437 return newText;
438 }
439 } catch (RuntimeException e) {
440 // If anything bad happens, we'll fall back on the plain text.
441 }
442 }
443
444 if (text != null) {
445 return text;
446 }
447 return coerceToHtmlOrStyledText(context, true);
448 }
449
450 /**
451 * Turn this item into HTML text, regardless of the type of data it
452 * actually contains.
453 *
454 * <p>The algorithm for deciding what text to return is:
455 * <ul>
456 * <li> If {@link #getHtmlText} is non-null, return that.
457 * <li> If {@link #getText} is non-null, return that, converting to
458 * valid HTML text. If this text contains style spans,
459 * {@link Html#toHtml(Spanned) Html.toHtml(Spanned)} is used to
460 * convert them to HTML formatting.
461 * <li> If {@link #getUri} is non-null, try to retrieve its data
462 * as a text stream from its content provider. If the provider can
463 * supply text/html data, that will be preferred and returned as-is.
464 * Otherwise, any text/* data will be returned and escaped to HTML.
465 * If it is not a content: URI or the content provider does not supply
466 * a text representation, HTML text containing a link to the URI
467 * will be returned.
468 * <li> If {@link #getIntent} is non-null, convert that to an intent:
469 * URI and return as an HTML link.
470 * <li> Otherwise, return an empty string.
471 * </ul>
472 *
473 * @param context The caller's Context, from which its ContentResolver
474 * and other things can be retrieved.
475 * @return Returns the item's representation as HTML text.
476 */
477 public String coerceToHtmlText(Context context) {
478 // If the item has an explicit HTML value, simply return that.
479 String htmlText = getHtmlText();
480 if (htmlText != null) {
481 return htmlText;
482 }
483
484 // If this Item has a plain text value, return it as HTML.
485 CharSequence text = getText();
486 if (text != null) {
487 if (text instanceof Spanned) {
488 return Html.toHtml((Spanned)text);
489 }
490 return Html.escapeHtml(text);
491 }
492
493 text = coerceToHtmlOrStyledText(context, false);
494 return text != null ? text.toString() : null;
495 }
496
497 private CharSequence coerceToHtmlOrStyledText(Context context, boolean styled) {
498 // If this Item has a URI value, try using that.
499 if (mUri != null) {
500
501 // Check to see what data representations the content
502 // provider supports. We would like HTML text, but if that
503 // is not possible we'll live with plan text.
Vladislav Kaznacheevc14df8e2016-01-22 11:49:13 -0800504 String[] types = null;
505 try {
506 types = context.getContentResolver().getStreamTypes(mUri, "text/*");
507 } catch (SecurityException e) {
508 // No read permission for mUri, assume empty stream types list.
509 }
Dianne Hackbornacb69bb2012-04-13 15:36:06 -0700510 boolean hasHtml = false;
511 boolean hasText = false;
512 if (types != null) {
513 for (String type : types) {
514 if ("text/html".equals(type)) {
515 hasHtml = true;
516 } else if (type.startsWith("text/")) {
517 hasText = true;
518 }
519 }
520 }
521
522 // If the provider can serve data we can use, open and load it.
523 if (hasHtml || hasText) {
524 FileInputStream stream = null;
525 try {
526 // Ask for a stream of the desired type.
527 AssetFileDescriptor descr = context.getContentResolver()
528 .openTypedAssetFileDescriptor(mUri,
529 hasHtml ? "text/html" : "text/plain", null);
530 stream = descr.createInputStream();
531 InputStreamReader reader = new InputStreamReader(stream, "UTF-8");
532
533 // Got it... copy the stream into a local string and return it.
534 StringBuilder builder = new StringBuilder(128);
535 char[] buffer = new char[8192];
536 int len;
537 while ((len=reader.read(buffer)) > 0) {
538 builder.append(buffer, 0, len);
539 }
540 String text = builder.toString();
541 if (hasHtml) {
542 if (styled) {
543 // We loaded HTML formatted text and the caller
544 // want styled text, convert it.
545 try {
546 CharSequence newText = Html.fromHtml(text);
547 return newText != null ? newText : text;
548 } catch (RuntimeException e) {
549 return text;
550 }
551 } else {
552 // We loaded HTML formatted text and that is what
553 // the caller wants, just return it.
554 return text.toString();
555 }
556 }
557 if (styled) {
558 // We loaded plain text and the caller wants styled
559 // text, that is all we have so return it.
560 return text;
561 } else {
562 // We loaded plain text and the caller wants HTML
563 // text, escape it for HTML.
564 return Html.escapeHtml(text);
565 }
566
Vladislav Kaznacheevb143ff62017-01-27 16:39:13 -0800567 } catch (SecurityException e) {
568 Log.w("ClipData", "Failure opening stream", e);
569
Dianne Hackbornacb69bb2012-04-13 15:36:06 -0700570 } catch (FileNotFoundException e) {
571 // Unable to open content URI as text... not really an
572 // error, just something to ignore.
573
574 } catch (IOException e) {
575 // Something bad has happened.
Vladislav Kaznacheev7e4669c2016-05-02 17:04:08 -0700576 Log.w("ClipData", "Failure loading text", e);
Dianne Hackbornacb69bb2012-04-13 15:36:06 -0700577 return Html.escapeHtml(e.toString());
578
579 } finally {
580 if (stream != null) {
581 try {
582 stream.close();
583 } catch (IOException e) {
584 }
585 }
586 }
587 }
588
Vladislav Kaznacheeve1f5e132017-01-27 16:56:40 -0800589 // If we couldn't open the URI as a stream, use the URI itself as a textual
590 // representation (but not for "content", "android.resource" or "file" schemes).
591 final String scheme = mUri.getScheme();
592 if (SCHEME_CONTENT.equals(scheme)
593 || SCHEME_ANDROID_RESOURCE.equals(scheme)
594 || SCHEME_FILE.equals(scheme)) {
595 return "";
596 }
597
Dianne Hackbornacb69bb2012-04-13 15:36:06 -0700598 if (styled) {
599 return uriToStyledText(mUri.toString());
600 } else {
601 return uriToHtml(mUri.toString());
602 }
603 }
604
605 // Finally, if all we have is an Intent, then we can just turn that
606 // into text. Not the most user-friendly thing, but it's something.
607 if (mIntent != null) {
608 if (styled) {
609 return uriToStyledText(mIntent.toUri(Intent.URI_INTENT_SCHEME));
610 } else {
611 return uriToHtml(mIntent.toUri(Intent.URI_INTENT_SCHEME));
612 }
613 }
614
615 // Shouldn't get here, but just in case...
616 return "";
617 }
618
619 private String uriToHtml(String uri) {
620 StringBuilder builder = new StringBuilder(256);
621 builder.append("<a href=\"");
Nick Kralevichc92db392012-07-27 13:22:20 -0700622 builder.append(Html.escapeHtml(uri));
Dianne Hackbornacb69bb2012-04-13 15:36:06 -0700623 builder.append("\">");
624 builder.append(Html.escapeHtml(uri));
625 builder.append("</a>");
626 return builder.toString();
627 }
628
629 private CharSequence uriToStyledText(String uri) {
630 SpannableStringBuilder builder = new SpannableStringBuilder();
631 builder.append(uri);
632 builder.setSpan(new URLSpan(uri), 0, builder.length(),
633 Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
634 return builder;
635 }
636
Dianne Hackborn21c241e2012-03-08 13:57:23 -0800637 @Override
638 public String toString() {
639 StringBuilder b = new StringBuilder(128);
640
641 b.append("ClipData.Item { ");
642 toShortString(b);
643 b.append(" }");
644
645 return b.toString();
646 }
647
648 /** @hide */
649 public void toShortString(StringBuilder b) {
Dianne Hackbornacb69bb2012-04-13 15:36:06 -0700650 if (mHtmlText != null) {
651 b.append("H:");
652 b.append(mHtmlText);
653 } else if (mText != null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -0800654 b.append("T:");
655 b.append(mText);
656 } else if (mUri != null) {
657 b.append("U:");
658 b.append(mUri);
659 } else if (mIntent != null) {
660 b.append("I:");
661 mIntent.toShortString(b, true, true, true, true);
662 } else {
663 b.append("NULL");
664 }
665 }
Dianne Hackbornae498722015-08-14 13:29:47 -0700666
667 /** @hide */
668 public void toShortSummaryString(StringBuilder b) {
669 if (mHtmlText != null) {
670 b.append("HTML");
671 } else if (mText != null) {
672 b.append("TEXT");
673 } else if (mUri != null) {
674 b.append("U:");
675 b.append(mUri);
676 } else if (mIntent != null) {
677 b.append("I:");
678 mIntent.toShortString(b, true, true, true, true);
679 } else {
680 b.append("NULL");
681 }
682 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -0800683
684 /** @hide */
685 public void writeToProto(ProtoOutputStream proto, long fieldId) {
686 final long token = proto.start(fieldId);
687
688 if (mHtmlText != null) {
689 proto.write(ClipDataProto.Item.HTML_TEXT, mHtmlText);
690 } else if (mText != null) {
691 proto.write(ClipDataProto.Item.TEXT, mText.toString());
692 } else if (mUri != null) {
693 proto.write(ClipDataProto.Item.URI, mUri.toString());
694 } else if (mIntent != null) {
695 mIntent.writeToProto(proto, ClipDataProto.Item.INTENT, true, true, true, true);
696 } else {
697 proto.write(ClipDataProto.Item.NOTHING, true);
698 }
699
700 proto.end(token);
701 }
Dianne Hackborn9f531192010-08-04 17:48:03 -0700702 }
703
704 /**
705 * Create a new clip.
706 *
707 * @param label Label to show to the user describing this clip.
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700708 * @param mimeTypes An array of MIME types this data is available as.
Dianne Hackborn9f531192010-08-04 17:48:03 -0700709 * @param item The contents of the first item in the clip.
710 */
Dianne Hackborn327fbd22011-01-17 14:38:50 -0800711 public ClipData(CharSequence label, String[] mimeTypes, Item item) {
Dianne Hackbornf834dfa2010-10-26 12:43:57 -0700712 mClipDescription = new ClipDescription(label, mimeTypes);
Dianne Hackborn9f531192010-08-04 17:48:03 -0700713 if (item == null) {
714 throw new NullPointerException("item is null");
715 }
Dianne Hackborn327fbd22011-01-17 14:38:50 -0800716 mIcon = null;
Dianne Hackborn21c241e2012-03-08 13:57:23 -0800717 mItems = new ArrayList<Item>();
Dianne Hackborn9f531192010-08-04 17:48:03 -0700718 mItems.add(item);
719 }
720
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700721 /**
Dianne Hackbornf834dfa2010-10-26 12:43:57 -0700722 * Create a new clip.
723 *
724 * @param description The ClipDescription describing the clip contents.
Dianne Hackbornf834dfa2010-10-26 12:43:57 -0700725 * @param item The contents of the first item in the clip.
726 */
Dianne Hackborn327fbd22011-01-17 14:38:50 -0800727 public ClipData(ClipDescription description, Item item) {
Dianne Hackbornf834dfa2010-10-26 12:43:57 -0700728 mClipDescription = description;
729 if (item == null) {
730 throw new NullPointerException("item is null");
731 }
Dianne Hackborn327fbd22011-01-17 14:38:50 -0800732 mIcon = null;
Dianne Hackborn21c241e2012-03-08 13:57:23 -0800733 mItems = new ArrayList<Item>();
Dianne Hackbornf834dfa2010-10-26 12:43:57 -0700734 mItems.add(item);
735 }
736
737 /**
Steve McKay57eaaf62016-06-13 12:53:31 -0700738 * Create a new clip.
739 *
740 * @param description The ClipDescription describing the clip contents.
741 * @param items The items in the clip. Not that a defensive copy of this
742 * list is not made, so caution should be taken to ensure the
743 * list is not available for further modification.
744 * @hide
745 */
746 public ClipData(ClipDescription description, ArrayList<Item> items) {
747 mClipDescription = description;
748 if (items == null) {
749 throw new NullPointerException("item is null");
750 }
751 mIcon = null;
752 mItems = items;
753 }
754
755 /**
Dianne Hackborn21c241e2012-03-08 13:57:23 -0800756 * Create a new clip that is a copy of another clip. This does a deep-copy
757 * of all items in the clip.
758 *
759 * @param other The existing ClipData that is to be copied.
760 */
761 public ClipData(ClipData other) {
762 mClipDescription = other.mClipDescription;
763 mIcon = other.mIcon;
764 mItems = new ArrayList<Item>(other.mItems);
765 }
766
767 /**
Dianne Hackbornf834dfa2010-10-26 12:43:57 -0700768 * Create a new ClipData holding data of the type
769 * {@link ClipDescription#MIMETYPE_TEXT_PLAIN}.
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700770 *
771 * @param label User-visible label for the clip data.
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700772 * @param text The actual text in the clip.
773 * @return Returns a new ClipData containing the specified data.
774 */
Dianne Hackborn327fbd22011-01-17 14:38:50 -0800775 static public ClipData newPlainText(CharSequence label, CharSequence text) {
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700776 Item item = new Item(text);
Dianne Hackborn327fbd22011-01-17 14:38:50 -0800777 return new ClipData(label, MIMETYPES_TEXT_PLAIN, item);
778 }
779
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700780 /**
Dianne Hackbornacb69bb2012-04-13 15:36:06 -0700781 * Create a new ClipData holding data of the type
782 * {@link ClipDescription#MIMETYPE_TEXT_HTML}.
783 *
784 * @param label User-visible label for the clip data.
785 * @param text The text of clip as plain text, for receivers that don't
786 * handle HTML. This is required.
787 * @param htmlText The actual HTML text in the clip.
788 * @return Returns a new ClipData containing the specified data.
789 */
790 static public ClipData newHtmlText(CharSequence label, CharSequence text,
791 String htmlText) {
792 Item item = new Item(text, htmlText);
793 return new ClipData(label, MIMETYPES_TEXT_HTML, item);
794 }
795
796 /**
Dianne Hackbornf834dfa2010-10-26 12:43:57 -0700797 * Create a new ClipData holding an Intent with MIME type
798 * {@link ClipDescription#MIMETYPE_TEXT_INTENT}.
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700799 *
800 * @param label User-visible label for the clip data.
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700801 * @param intent The actual Intent in the clip.
802 * @return Returns a new ClipData containing the specified data.
803 */
Dianne Hackborn327fbd22011-01-17 14:38:50 -0800804 static public ClipData newIntent(CharSequence label, Intent intent) {
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700805 Item item = new Item(intent);
Dianne Hackborn327fbd22011-01-17 14:38:50 -0800806 return new ClipData(label, MIMETYPES_TEXT_INTENT, item);
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700807 }
808
809 /**
810 * Create a new ClipData holding a URI. If the URI is a content: URI,
811 * this will query the content provider for the MIME type of its data and
812 * use that as the MIME type. Otherwise, it will use the MIME type
Dianne Hackbornf834dfa2010-10-26 12:43:57 -0700813 * {@link ClipDescription#MIMETYPE_TEXT_URILIST}.
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700814 *
815 * @param resolver ContentResolver used to get information about the URI.
816 * @param label User-visible label for the clip data.
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700817 * @param uri The URI in the clip.
818 * @return Returns a new ClipData containing the specified data.
819 */
820 static public ClipData newUri(ContentResolver resolver, CharSequence label,
Dianne Hackborn327fbd22011-01-17 14:38:50 -0800821 Uri uri) {
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700822 Item item = new Item(uri);
Vladislav Kaznacheev8e7b9402016-11-23 15:31:13 -0800823 String[] mimeTypes = getMimeTypes(resolver, uri);
824 return new ClipData(label, mimeTypes, item);
825 }
826
827 /**
828 * Finds all applicable MIME types for a given URI.
829 *
830 * @param resolver ContentResolver used to get information about the URI.
831 * @param uri The URI.
832 * @return Returns an array of MIME types.
833 */
834 private static String[] getMimeTypes(ContentResolver resolver, Uri uri) {
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700835 String[] mimeTypes = null;
Vladislav Kaznacheeve1f5e132017-01-27 16:56:40 -0800836 if (SCHEME_CONTENT.equals(uri.getScheme())) {
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700837 String realType = resolver.getType(uri);
838 mimeTypes = resolver.getStreamTypes(uri, "*/*");
Vladislav Kaznacheevf67661c2016-05-03 15:02:33 -0700839 if (realType != null) {
840 if (mimeTypes == null) {
841 mimeTypes = new String[] { realType };
Vladislav Kaznacheev8e7b9402016-11-23 15:31:13 -0800842 } else if (!ArrayUtils.contains(mimeTypes, realType)) {
Vladislav Kaznacheevf67661c2016-05-03 15:02:33 -0700843 String[] tmp = new String[mimeTypes.length + 1];
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700844 tmp[0] = realType;
Vladislav Kaznacheevf67661c2016-05-03 15:02:33 -0700845 System.arraycopy(mimeTypes, 0, tmp, 1, mimeTypes.length);
846 mimeTypes = tmp;
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700847 }
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700848 }
849 }
850 if (mimeTypes == null) {
851 mimeTypes = MIMETYPES_TEXT_URILIST;
852 }
Vladislav Kaznacheev8e7b9402016-11-23 15:31:13 -0800853 return mimeTypes;
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700854 }
855
856 /**
Dianne Hackbornf834dfa2010-10-26 12:43:57 -0700857 * Create a new ClipData holding an URI with MIME type
858 * {@link ClipDescription#MIMETYPE_TEXT_URILIST}.
Dianne Hackborn327fbd22011-01-17 14:38:50 -0800859 * Unlike {@link #newUri(ContentResolver, CharSequence, Uri)}, nothing
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700860 * is inferred about the URI -- if it is a content: URI holding a bitmap,
861 * the reported type will still be uri-list. Use this with care!
862 *
863 * @param label User-visible label for the clip data.
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700864 * @param uri The URI in the clip.
865 * @return Returns a new ClipData containing the specified data.
866 */
Dianne Hackborn327fbd22011-01-17 14:38:50 -0800867 static public ClipData newRawUri(CharSequence label, Uri uri) {
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700868 Item item = new Item(uri);
Dianne Hackborn327fbd22011-01-17 14:38:50 -0800869 return new ClipData(label, MIMETYPES_TEXT_URILIST, item);
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700870 }
871
Dianne Hackbornf834dfa2010-10-26 12:43:57 -0700872 /**
873 * Return the {@link ClipDescription} associated with this data, describing
874 * what it contains.
875 */
876 public ClipDescription getDescription() {
877 return mClipDescription;
878 }
Vladislav Kaznacheevf67661c2016-05-03 15:02:33 -0700879
Dianne Hackborn327fbd22011-01-17 14:38:50 -0800880 /**
881 * Add a new Item to the overall ClipData container.
Vladislav Kaznacheevf67661c2016-05-03 15:02:33 -0700882 * <p> This method will <em>not</em> update the list of available MIME types in the
883 * {@link ClipDescription}. It should be used only when adding items which do not add new
Vladislav Kaznacheevc35c02f2017-04-20 08:38:21 -0700884 * MIME types to this clip. If this is not the case, use {@link #addItem(ContentResolver, Item)}
Vladislav Kaznacheev8e7b9402016-11-23 15:31:13 -0800885 * or call {@link #ClipData(CharSequence, String[], Item)} with a complete list of MIME types.
Vladislav Kaznacheevf67661c2016-05-03 15:02:33 -0700886 * @param item Item to be added.
Dianne Hackborn327fbd22011-01-17 14:38:50 -0800887 */
Dianne Hackborn9f531192010-08-04 17:48:03 -0700888 public void addItem(Item item) {
889 if (item == null) {
890 throw new NullPointerException("item is null");
891 }
892 mItems.add(item);
893 }
894
Vladislav Kaznacheevc35c02f2017-04-20 08:38:21 -0700895 /** @removed use #addItem(ContentResolver, Item) instead */
896 @Deprecated
897 public void addItem(Item item, ContentResolver resolver) {
898 addItem(resolver, item);
899 }
900
Vladislav Kaznacheev8e7b9402016-11-23 15:31:13 -0800901 /**
902 * Add a new Item to the overall ClipData container.
903 * <p> Unlike {@link #addItem(Item)}, this method will update the list of available MIME types
904 * in the {@link ClipDescription}.
Vladislav Kaznacheev8e7b9402016-11-23 15:31:13 -0800905 * @param resolver ContentResolver used to get information about the URI possibly contained in
906 * the item.
Vladislav Kaznacheevc35c02f2017-04-20 08:38:21 -0700907 * @param item Item to be added.
Vladislav Kaznacheev8e7b9402016-11-23 15:31:13 -0800908 */
Vladislav Kaznacheevc35c02f2017-04-20 08:38:21 -0700909 public void addItem(ContentResolver resolver, Item item) {
Vladislav Kaznacheev8e7b9402016-11-23 15:31:13 -0800910 addItem(item);
911
912 if (item.getHtmlText() != null) {
913 mClipDescription.addMimeTypes(MIMETYPES_TEXT_HTML);
914 } else if (item.getText() != null) {
915 mClipDescription.addMimeTypes(MIMETYPES_TEXT_PLAIN);
916 }
917
918 if (item.getIntent() != null) {
919 mClipDescription.addMimeTypes(MIMETYPES_TEXT_INTENT);
920 }
921
922 if (item.getUri() != null) {
923 mClipDescription.addMimeTypes(getMimeTypes(resolver, item.getUri()));
924 }
925 }
926
Dianne Hackborn327fbd22011-01-17 14:38:50 -0800927 /** @hide */
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100928 @UnsupportedAppUsage
Dianne Hackborn9f531192010-08-04 17:48:03 -0700929 public Bitmap getIcon() {
930 return mIcon;
931 }
932
Dianne Hackborn327fbd22011-01-17 14:38:50 -0800933 /**
934 * Return the number of items in the clip data.
935 */
Dianne Hackborn9f531192010-08-04 17:48:03 -0700936 public int getItemCount() {
937 return mItems.size();
938 }
939
Dianne Hackborn327fbd22011-01-17 14:38:50 -0800940 /**
941 * Return a single item inside of the clip data. The index can range
942 * from 0 to {@link #getItemCount()}-1.
943 */
944 public Item getItemAt(int index) {
Dianne Hackborn9f531192010-08-04 17:48:03 -0700945 return mItems.get(index);
946 }
947
Nicolas Prevot58926242016-07-14 19:11:10 +0100948 /** @hide */
949 public void setItemAt(int index, Item item) {
950 mItems.set(index, item);
951 }
952
Jeff Sharkeya14acd22013-04-02 18:27:45 -0700953 /**
954 * Prepare this {@link ClipData} to leave an app process.
955 *
956 * @hide
957 */
Jeff Sharkey344744b2016-01-28 19:03:30 -0700958 public void prepareToLeaveProcess(boolean leavingPackage) {
Jeff Sharkeyf361f2f2016-12-21 10:48:42 -0700959 // Assume that callers are going to be granting permissions
960 prepareToLeaveProcess(leavingPackage, Intent.FLAG_GRANT_READ_URI_PERMISSION);
Jeff Sharkeyfb833f32016-12-01 14:59:59 -0700961 }
962
963 /**
964 * Prepare this {@link ClipData} to leave an app process.
965 *
966 * @hide
967 */
968 public void prepareToLeaveProcess(boolean leavingPackage, int intentFlags) {
Jeff Sharkeya14acd22013-04-02 18:27:45 -0700969 final int size = mItems.size();
970 for (int i = 0; i < size; i++) {
971 final Item item = mItems.get(i);
972 if (item.mIntent != null) {
Jeff Sharkey344744b2016-01-28 19:03:30 -0700973 item.mIntent.prepareToLeaveProcess(leavingPackage);
Jeff Sharkeya14acd22013-04-02 18:27:45 -0700974 }
Jeff Sharkeyfb833f32016-12-01 14:59:59 -0700975 if (item.mUri != null && leavingPackage) {
976 if (StrictMode.vmFileUriExposureEnabled()) {
977 item.mUri.checkFileUriExposed("ClipData.Item.getUri()");
978 }
979 if (StrictMode.vmContentUriWithoutPermissionEnabled()) {
980 item.mUri.checkContentUriWithoutPermission("ClipData.Item.getUri()",
981 intentFlags);
982 }
Jeff Sharkeya14acd22013-04-02 18:27:45 -0700983 }
984 }
985 }
986
Jeff Sharkeyd136e512016-03-09 22:30:56 -0700987 /** {@hide} */
988 public void prepareToEnterProcess() {
989 final int size = mItems.size();
990 for (int i = 0; i < size; i++) {
991 final Item item = mItems.get(i);
992 if (item.mIntent != null) {
993 item.mIntent.prepareToEnterProcess();
994 }
995 }
996 }
997
Nicolas Prevotd1c99b12014-07-04 16:56:17 +0100998 /** @hide */
999 public void fixUris(int contentUserHint) {
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001000 final int size = mItems.size();
1001 for (int i = 0; i < size; i++) {
1002 final Item item = mItems.get(i);
1003 if (item.mIntent != null) {
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01001004 item.mIntent.fixUris(contentUserHint);
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001005 }
1006 if (item.mUri != null) {
Nicolas Prevotd1c99b12014-07-04 16:56:17 +01001007 item.mUri = maybeAddUserId(item.mUri, contentUserHint);
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001008 }
1009 }
1010 }
1011
Nicolas Prevotf1939902014-06-25 09:29:02 +01001012 /**
1013 * Only fixing the data field of the intents
1014 * @hide
1015 */
1016 public void fixUrisLight(int contentUserHint) {
1017 final int size = mItems.size();
1018 for (int i = 0; i < size; i++) {
1019 final Item item = mItems.get(i);
1020 if (item.mIntent != null) {
1021 Uri data = item.mIntent.getData();
1022 if (data != null) {
1023 item.mIntent.setData(maybeAddUserId(data, contentUserHint));
1024 }
1025 }
1026 if (item.mUri != null) {
1027 item.mUri = maybeAddUserId(item.mUri, contentUserHint);
1028 }
1029 }
1030 }
1031
Dianne Hackborn9f531192010-08-04 17:48:03 -07001032 @Override
Dianne Hackborn21c241e2012-03-08 13:57:23 -08001033 public String toString() {
1034 StringBuilder b = new StringBuilder(128);
1035
1036 b.append("ClipData { ");
1037 toShortString(b);
1038 b.append(" }");
1039
1040 return b.toString();
1041 }
1042
1043 /** @hide */
1044 public void toShortString(StringBuilder b) {
1045 boolean first;
1046 if (mClipDescription != null) {
1047 first = !mClipDescription.toShortString(b);
1048 } else {
1049 first = true;
1050 }
1051 if (mIcon != null) {
1052 if (!first) {
1053 b.append(' ');
1054 }
1055 first = false;
1056 b.append("I:");
1057 b.append(mIcon.getWidth());
1058 b.append('x');
1059 b.append(mIcon.getHeight());
1060 }
1061 for (int i=0; i<mItems.size(); i++) {
1062 if (!first) {
1063 b.append(' ');
1064 }
1065 first = false;
1066 b.append('{');
1067 mItems.get(i).toShortString(b);
1068 b.append('}');
1069 }
1070 }
1071
Dianne Hackbornae498722015-08-14 13:29:47 -07001072 /** @hide */
1073 public void toShortStringShortItems(StringBuilder b, boolean first) {
1074 if (mItems.size() > 0) {
1075 if (!first) {
1076 b.append(' ');
1077 }
1078 mItems.get(0).toShortString(b);
1079 if (mItems.size() > 1) {
1080 b.append(" ...");
1081 }
1082 }
1083 }
1084
Vladislav Kaznacheev9149d2b2015-12-15 12:16:28 -08001085 /** @hide */
Kweku Adams85f2fbc2017-12-18 12:04:12 -08001086 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1087 final long token = proto.start(fieldId);
1088
1089 if (mClipDescription != null) {
1090 mClipDescription.writeToProto(proto, ClipDataProto.DESCRIPTION);
1091 }
1092 if (mIcon != null) {
1093 final long iToken = proto.start(ClipDataProto.ICON);
1094 proto.write(ClipDataProto.Icon.WIDTH, mIcon.getWidth());
1095 proto.write(ClipDataProto.Icon.HEIGHT, mIcon.getHeight());
1096 proto.end(iToken);
1097 }
1098 for (int i = 0; i < mItems.size(); i++) {
1099 mItems.get(i).writeToProto(proto, ClipDataProto.ITEMS);
1100 }
1101
1102 proto.end(token);
1103 }
1104
1105 /** @hide */
Vladislav Kaznacheev9149d2b2015-12-15 12:16:28 -08001106 public void collectUris(List<Uri> out) {
1107 for (int i = 0; i < mItems.size(); ++i) {
1108 ClipData.Item item = getItemAt(i);
1109
1110 if (item.getUri() != null) {
1111 out.add(item.getUri());
1112 }
1113
1114 Intent intent = item.getIntent();
1115 if (intent != null) {
1116 if (intent.getData() != null) {
1117 out.add(intent.getData());
1118 }
1119 if (intent.getClipData() != null) {
1120 intent.getClipData().collectUris(out);
1121 }
1122 }
1123 }
1124 }
1125
Dianne Hackborn21c241e2012-03-08 13:57:23 -08001126 @Override
Dianne Hackborn9f531192010-08-04 17:48:03 -07001127 public int describeContents() {
1128 return 0;
1129 }
1130
1131 @Override
1132 public void writeToParcel(Parcel dest, int flags) {
Dianne Hackbornf834dfa2010-10-26 12:43:57 -07001133 mClipDescription.writeToParcel(dest, flags);
Dianne Hackborn9f531192010-08-04 17:48:03 -07001134 if (mIcon != null) {
1135 dest.writeInt(1);
1136 mIcon.writeToParcel(dest, flags);
1137 } else {
1138 dest.writeInt(0);
1139 }
1140 final int N = mItems.size();
1141 dest.writeInt(N);
1142 for (int i=0; i<N; i++) {
1143 Item item = mItems.get(i);
1144 TextUtils.writeToParcel(item.mText, dest, flags);
Satoshi Niwa472371c2018-08-01 17:22:02 +09001145 writeHtmlTextToParcel(item.mHtmlText, dest, flags);
Dianne Hackborn9f531192010-08-04 17:48:03 -07001146 if (item.mIntent != null) {
1147 dest.writeInt(1);
1148 item.mIntent.writeToParcel(dest, flags);
1149 } else {
1150 dest.writeInt(0);
1151 }
1152 if (item.mUri != null) {
1153 dest.writeInt(1);
1154 item.mUri.writeToParcel(dest, flags);
1155 } else {
1156 dest.writeInt(0);
1157 }
1158 }
1159 }
1160
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001161 ClipData(Parcel in) {
Dianne Hackbornf834dfa2010-10-26 12:43:57 -07001162 mClipDescription = new ClipDescription(in);
Dianne Hackborn9f531192010-08-04 17:48:03 -07001163 if (in.readInt() != 0) {
1164 mIcon = Bitmap.CREATOR.createFromParcel(in);
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001165 } else {
1166 mIcon = null;
Dianne Hackborn9f531192010-08-04 17:48:03 -07001167 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08001168 mItems = new ArrayList<Item>();
Dianne Hackborn9f531192010-08-04 17:48:03 -07001169 final int N = in.readInt();
1170 for (int i=0; i<N; i++) {
1171 CharSequence text = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
Satoshi Niwa472371c2018-08-01 17:22:02 +09001172 String htmlText = readHtmlTextFromParcel(in);
Dianne Hackborn9f531192010-08-04 17:48:03 -07001173 Intent intent = in.readInt() != 0 ? Intent.CREATOR.createFromParcel(in) : null;
1174 Uri uri = in.readInt() != 0 ? Uri.CREATOR.createFromParcel(in) : null;
Dianne Hackbornacb69bb2012-04-13 15:36:06 -07001175 mItems.add(new Item(text, htmlText, intent, uri));
Dianne Hackborn9f531192010-08-04 17:48:03 -07001176 }
1177 }
1178
Jeff Sharkey9e8f83d2019-02-28 12:06:45 -07001179 public static final @android.annotation.NonNull Parcelable.Creator<ClipData> CREATOR =
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001180 new Parcelable.Creator<ClipData>() {
Dianne Hackborn9f531192010-08-04 17:48:03 -07001181
Steve McKay57eaaf62016-06-13 12:53:31 -07001182 @Override
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001183 public ClipData createFromParcel(Parcel source) {
1184 return new ClipData(source);
Dianne Hackborn9f531192010-08-04 17:48:03 -07001185 }
1186
Steve McKay57eaaf62016-06-13 12:53:31 -07001187 @Override
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001188 public ClipData[] newArray(int size) {
1189 return new ClipData[size];
Dianne Hackborn9f531192010-08-04 17:48:03 -07001190 }
1191 };
Satoshi Niwa472371c2018-08-01 17:22:02 +09001192
1193 /**
1194 * Helper function for writing an HTML text into a parcel.
1195 * If the text size is larger than 400KB, it writes the text to a file descriptor to prevent the
1196 * parcel from exceeding 800KB binder size limit. {@link android.os.Binder#checkParcel()}
1197 * Otherwise, it directly writes the text into the parcel.
1198 * Note: This function is a workaround for existing applications that still use HTML for sharing
1199 * large clip data. We will ask application developers to use content: URI instead and remove
1200 * this function in API 30.
1201 */
1202 private static void writeHtmlTextToParcel(String text, Parcel dest, int flags) {
1203 byte[] textData = (text != null) ? text.getBytes() : new byte[0];
1204 if (textData.length > PARCEL_MAX_SIZE_BYTES / 2
1205 && Build.VERSION.SDK_INT <= Build.VERSION_CODES.Q) {
1206 try {
1207 ParcelFileDescriptor pfd = ParcelFileDescriptor.fromData(textData, null);
1208 dest.writeInt(PARCEL_TYPE_PFD);
1209 dest.writeParcelable(pfd, flags);
1210 } catch (IOException e) {
1211 throw new IllegalStateException(
1212 "Error creating the shared memory area: " + e.toString());
1213 }
1214 } else {
1215 dest.writeInt(PARCEL_TYPE_STRING);
1216 dest.writeString(text);
1217 }
1218 }
1219
1220 /**
1221 * Reads a text written by writeHtmlTextToParcel.
1222 */
1223 private static String readHtmlTextFromParcel(Parcel in) {
1224 if (in.readInt() == PARCEL_TYPE_STRING) {
1225 return in.readString();
1226 }
1227 ParcelFileDescriptor pfd =
1228 in.readParcelable(ParcelFileDescriptor.class.getClassLoader());
1229 if (pfd == null) {
1230 throw new IllegalStateException("Error reading ParcelFileDescriptor from Parcel");
1231 }
1232 FileInputStream fis = new ParcelFileDescriptor.AutoCloseInputStream(pfd);
1233 InputStreamReader reader = new InputStreamReader(fis);
1234 StringBuilder builder = new StringBuilder();
1235 char[] buffer = new char[4096];
1236 int numRead;
1237 try {
1238 while ((numRead = reader.read(buffer)) != -1) {
1239 builder.append(buffer, 0, numRead);
1240 }
1241 return builder.toString();
1242 } catch (IOException e) {
1243 throw new IllegalStateException(
1244 "Error reading data from ParcelFileDescriptor: " + e.toString());
1245 } finally {
1246 IoUtils.closeQuietly(fis);
1247 }
1248 }
Dianne Hackborn9f531192010-08-04 17:48:03 -07001249}