DocumentsContract.java revision 75395651c272b3df746e0e5fede0a8fedd81e44b
1/*
2 * Copyright (C) 2013 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.provider;
18
19import static android.net.TrafficStats.KB_IN_BYTES;
20import static android.system.OsConstants.SEEK_SET;
21
22import android.annotation.Nullable;
23import android.content.ContentProviderClient;
24import android.content.ContentResolver;
25import android.content.Context;
26import android.content.Intent;
27import android.content.pm.ResolveInfo;
28import android.content.res.AssetFileDescriptor;
29import android.database.Cursor;
30import android.graphics.Bitmap;
31import android.graphics.BitmapFactory;
32import android.graphics.Matrix;
33import android.graphics.Point;
34import android.media.ExifInterface;
35import android.net.Uri;
36import android.os.Bundle;
37import android.os.CancellationSignal;
38import android.os.OperationCanceledException;
39import android.os.ParcelFileDescriptor;
40import android.os.ParcelFileDescriptor.OnCloseListener;
41import android.os.RemoteException;
42import android.system.ErrnoException;
43import android.system.Os;
44import android.util.Log;
45
46import libcore.io.IoUtils;
47
48import java.io.BufferedInputStream;
49import java.io.File;
50import java.io.FileDescriptor;
51import java.io.FileInputStream;
52import java.io.FileNotFoundException;
53import java.io.IOException;
54import java.util.List;
55
56/**
57 * Defines the contract between a documents provider and the platform.
58 * <p>
59 * To create a document provider, extend {@link DocumentsProvider}, which
60 * provides a foundational implementation of this contract.
61 * <p>
62 * All client apps must hold a valid URI permission grant to access documents,
63 * typically issued when a user makes a selection through
64 * {@link Intent#ACTION_OPEN_DOCUMENT}, {@link Intent#ACTION_CREATE_DOCUMENT},
65 * or {@link Intent#ACTION_OPEN_DOCUMENT_TREE}.
66 *
67 * @see DocumentsProvider
68 */
69public final class DocumentsContract {
70    private static final String TAG = "DocumentsContract";
71
72    // content://com.example/root/
73    // content://com.example/root/sdcard/
74    // content://com.example/root/sdcard/recent/
75    // content://com.example/root/sdcard/search/?query=pony
76    // content://com.example/document/12/
77    // content://com.example/document/12/children/
78    // content://com.example/tree/12/document/24/
79    // content://com.example/tree/12/document/24/children/
80
81    private DocumentsContract() {
82    }
83
84    /**
85     * Intent action used to identify {@link DocumentsProvider} instances. This
86     * is used in the {@code <intent-filter>} of a {@code <provider>}.
87     */
88    public static final String PROVIDER_INTERFACE = "android.content.action.DOCUMENTS_PROVIDER";
89
90    /** {@hide} */
91    public static final String EXTRA_PACKAGE_NAME = "android.content.extra.PACKAGE_NAME";
92
93    /** {@hide} */
94    public static final String EXTRA_SHOW_ADVANCED = "android.content.extra.SHOW_ADVANCED";
95
96    /** {@hide} */
97    public static final String EXTRA_SHOW_FILESIZE = "android.content.extra.SHOW_FILESIZE";
98
99    /** {@hide} */
100    public static final String EXTRA_TARGET_URI = "android.content.extra.TARGET_URI";
101
102    /**
103     * Set this in a DocumentsUI intent to cause a package's own roots to be
104     * excluded from the roots list.
105     */
106    public static final String EXTRA_EXCLUDE_SELF = "android.provider.extra.EXCLUDE_SELF";
107
108    /**
109     * Included in {@link AssetFileDescriptor#getExtras()} when returned
110     * thumbnail should be rotated.
111     *
112     * @see MediaStore.Images.ImageColumns#ORIENTATION
113     * @hide
114     */
115    public static final String EXTRA_ORIENTATION = "android.content.extra.ORIENTATION";
116
117    /**
118     * Overrides the default prompt text in DocumentsUI when set in an intent.
119     */
120    public static final String EXTRA_PROMPT = "android.provider.extra.PROMPT";
121
122    /** {@hide} */
123    public static final String ACTION_MANAGE_ROOT = "android.provider.action.MANAGE_ROOT";
124    /** {@hide} */
125    public static final String ACTION_MANAGE_DOCUMENT = "android.provider.action.MANAGE_DOCUMENT";
126
127    /** {@hide} */
128    public static final String ACTION_BROWSE = "android.provider.action.BROWSE";
129
130    /** {@hide} */
131    public static final String
132            ACTION_DOCUMENT_ROOT_SETTINGS = "android.provider.action.DOCUMENT_ROOT_SETTINGS";
133
134    /**
135     * Buffer is large enough to rewind past any EXIF headers.
136     */
137    private static final int THUMBNAIL_BUFFER_SIZE = (int) (128 * KB_IN_BYTES);
138
139    /** {@hide} */
140    public static final String PACKAGE_DOCUMENTS_UI = "com.android.documentsui";
141
142    /**
143     * Constants related to a document, including {@link Cursor} column names
144     * and flags.
145     * <p>
146     * A document can be either an openable stream (with a specific MIME type),
147     * or a directory containing additional documents (with the
148     * {@link #MIME_TYPE_DIR} MIME type). A directory represents the top of a
149     * subtree containing zero or more documents, which can recursively contain
150     * even more documents and directories.
151     * <p>
152     * All columns are <em>read-only</em> to client applications.
153     */
154    public final static class Document {
155        private Document() {
156        }
157
158        /**
159         * Unique ID of a document. This ID is both provided by and interpreted
160         * by a {@link DocumentsProvider}, and should be treated as an opaque
161         * value by client applications. This column is required.
162         * <p>
163         * Each document must have a unique ID within a provider, but that
164         * single document may be included as a child of multiple directories.
165         * <p>
166         * A provider must always return durable IDs, since they will be used to
167         * issue long-term URI permission grants when an application interacts
168         * with {@link Intent#ACTION_OPEN_DOCUMENT} and
169         * {@link Intent#ACTION_CREATE_DOCUMENT}.
170         * <p>
171         * Type: STRING
172         */
173        public static final String COLUMN_DOCUMENT_ID = "document_id";
174
175        /**
176         * Concrete MIME type of a document. For example, "image/png" or
177         * "application/pdf" for openable files. A document can also be a
178         * directory containing additional documents, which is represented with
179         * the {@link #MIME_TYPE_DIR} MIME type. This column is required.
180         * <p>
181         * Type: STRING
182         *
183         * @see #MIME_TYPE_DIR
184         */
185        public static final String COLUMN_MIME_TYPE = "mime_type";
186
187        /**
188         * Display name of a document, used as the primary title displayed to a
189         * user. This column is required.
190         * <p>
191         * Type: STRING
192         */
193        public static final String COLUMN_DISPLAY_NAME = OpenableColumns.DISPLAY_NAME;
194
195        /**
196         * Summary of a document, which may be shown to a user. This column is
197         * optional, and may be {@code null}.
198         * <p>
199         * Type: STRING
200         */
201        public static final String COLUMN_SUMMARY = "summary";
202
203        /**
204         * Timestamp when a document was last modified, in milliseconds since
205         * January 1, 1970 00:00:00.0 UTC. This column is required, and may be
206         * {@code null} if unknown. A {@link DocumentsProvider} can update this
207         * field using events from {@link OnCloseListener} or other reliable
208         * {@link ParcelFileDescriptor} transports.
209         * <p>
210         * Type: INTEGER (long)
211         *
212         * @see System#currentTimeMillis()
213         */
214        public static final String COLUMN_LAST_MODIFIED = "last_modified";
215
216        /**
217         * Specific icon resource ID for a document. This column is optional,
218         * and may be {@code null} to use a platform-provided default icon based
219         * on {@link #COLUMN_MIME_TYPE}.
220         * <p>
221         * Type: INTEGER (int)
222         */
223        public static final String COLUMN_ICON = "icon";
224
225        /**
226         * Flags that apply to a document. This column is required.
227         * <p>
228         * Type: INTEGER (int)
229         *
230         * @see #FLAG_SUPPORTS_WRITE
231         * @see #FLAG_SUPPORTS_DELETE
232         * @see #FLAG_SUPPORTS_THUMBNAIL
233         * @see #FLAG_DIR_PREFERS_GRID
234         * @see #FLAG_DIR_PREFERS_LAST_MODIFIED
235         * @see #FLAG_VIRTUAL_DOCUMENT
236         * @see #FLAG_ARCHIVE
237         */
238        public static final String COLUMN_FLAGS = "flags";
239
240        /**
241         * Size of a document, in bytes, or {@code null} if unknown. This column
242         * is required.
243         * <p>
244         * Type: INTEGER (long)
245         */
246        public static final String COLUMN_SIZE = OpenableColumns.SIZE;
247
248        /**
249         * MIME type of a document which is a directory that may contain
250         * additional documents.
251         *
252         * @see #COLUMN_MIME_TYPE
253         */
254        public static final String MIME_TYPE_DIR = "vnd.android.document/directory";
255
256        /**
257         * Flag indicating that a document can be represented as a thumbnail.
258         *
259         * @see #COLUMN_FLAGS
260         * @see DocumentsContract#getDocumentThumbnail(ContentResolver, Uri,
261         *      Point, CancellationSignal)
262         * @see DocumentsProvider#openDocumentThumbnail(String, Point,
263         *      android.os.CancellationSignal)
264         */
265        public static final int FLAG_SUPPORTS_THUMBNAIL = 1;
266
267        /**
268         * Flag indicating that a document supports writing.
269         * <p>
270         * When a document is opened with {@link Intent#ACTION_OPEN_DOCUMENT},
271         * the calling application is granted both
272         * {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and
273         * {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION}. However, the actual
274         * writability of a document may change over time, for example due to
275         * remote access changes. This flag indicates that a document client can
276         * expect {@link ContentResolver#openOutputStream(Uri)} to succeed.
277         *
278         * @see #COLUMN_FLAGS
279         */
280        public static final int FLAG_SUPPORTS_WRITE = 1 << 1;
281
282        /**
283         * Flag indicating that a document is deletable.
284         *
285         * @see #COLUMN_FLAGS
286         * @see DocumentsContract#deleteDocument(ContentResolver, Uri)
287         * @see DocumentsProvider#deleteDocument(String)
288         */
289        public static final int FLAG_SUPPORTS_DELETE = 1 << 2;
290
291        /**
292         * Flag indicating that a document is a directory that supports creation
293         * of new files within it. Only valid when {@link #COLUMN_MIME_TYPE} is
294         * {@link #MIME_TYPE_DIR}.
295         *
296         * @see #COLUMN_FLAGS
297         * @see DocumentsProvider#createDocument(String, String, String)
298         */
299        public static final int FLAG_DIR_SUPPORTS_CREATE = 1 << 3;
300
301        /**
302         * Flag indicating that a directory prefers its contents be shown in a
303         * larger format grid. Usually suitable when a directory contains mostly
304         * pictures. Only valid when {@link #COLUMN_MIME_TYPE} is
305         * {@link #MIME_TYPE_DIR}.
306         *
307         * @see #COLUMN_FLAGS
308         */
309        public static final int FLAG_DIR_PREFERS_GRID = 1 << 4;
310
311        /**
312         * Flag indicating that a directory prefers its contents be sorted by
313         * {@link #COLUMN_LAST_MODIFIED}. Only valid when
314         * {@link #COLUMN_MIME_TYPE} is {@link #MIME_TYPE_DIR}.
315         *
316         * @see #COLUMN_FLAGS
317         */
318        public static final int FLAG_DIR_PREFERS_LAST_MODIFIED = 1 << 5;
319
320        /**
321         * Flag indicating that a document can be renamed.
322         *
323         * @see #COLUMN_FLAGS
324         * @see DocumentsContract#renameDocument(ContentProviderClient, Uri,
325         *      String)
326         * @see DocumentsProvider#renameDocument(String, String)
327         */
328        public static final int FLAG_SUPPORTS_RENAME = 1 << 6;
329
330        /**
331         * Flag indicating that a document can be copied to another location
332         * within the same document provider.
333         *
334         * @see #COLUMN_FLAGS
335         * @see DocumentsContract#copyDocument(ContentProviderClient, Uri, Uri)
336         * @see DocumentsProvider#copyDocument(String, String)
337         */
338        public static final int FLAG_SUPPORTS_COPY = 1 << 7;
339
340        /**
341         * Flag indicating that a document can be moved to another location
342         * within the same document provider.
343         *
344         * @see #COLUMN_FLAGS
345         * @see DocumentsContract#moveDocument(ContentProviderClient, Uri, Uri)
346         * @see DocumentsProvider#moveDocument(String, String)
347         */
348        public static final int FLAG_SUPPORTS_MOVE = 1 << 8;
349
350        /**
351         * Flag indicating that a document is virtual, and doesn't have byte
352         * representation in the MIME type specified as {@link #COLUMN_MIME_TYPE}.
353         *
354         * @see #COLUMN_FLAGS
355         * @see #COLUMN_MIME_TYPE
356         * @see DocumentsProvider#openTypedDocument(String, String, Bundle,
357         *      android.os.CancellationSignal)
358         */
359        public static final int FLAG_VIRTUAL_DOCUMENT = 1 << 9;
360
361        /**
362         * Flag indicating that a document is an archive, and it's contents can be
363         * obtained via {@link DocumentsProvider#queryChildDocuments}.
364         * <p>
365         * The <em>provider</em> support library offers utility classes to add common
366         * archive support.
367         *
368         * @see #COLUMN_FLAGS
369         * @see DocumentsProvider#queryChildDocuments(String, String[], String)
370         */
371        public static final int FLAG_ARCHIVE = 1 << 10;
372
373        /**
374         * Flag indicating that document titles should be hidden when viewing
375         * this directory in a larger format grid. For example, a directory
376         * containing only images may want the image thumbnails to speak for
377         * themselves. Only valid when {@link #COLUMN_MIME_TYPE} is
378         * {@link #MIME_TYPE_DIR}.
379         *
380         * @see #COLUMN_FLAGS
381         * @see #FLAG_DIR_PREFERS_GRID
382         * @hide
383         */
384        public static final int FLAG_DIR_HIDE_GRID_TITLES = 1 << 16;
385    }
386
387    /**
388     * Constants related to a root of documents, including {@link Cursor} column
389     * names and flags. A root is the start of a tree of documents, such as a
390     * physical storage device, or an account. Each root starts at the directory
391     * referenced by {@link Root#COLUMN_DOCUMENT_ID}, which can recursively
392     * contain both documents and directories.
393     * <p>
394     * All columns are <em>read-only</em> to client applications.
395     */
396    public final static class Root {
397        private Root() {
398        }
399
400        /**
401         * Unique ID of a root. This ID is both provided by and interpreted by a
402         * {@link DocumentsProvider}, and should be treated as an opaque value
403         * by client applications. This column is required.
404         * <p>
405         * Type: STRING
406         */
407        public static final String COLUMN_ROOT_ID = "root_id";
408
409        /**
410         * Flags that apply to a root. This column is required.
411         * <p>
412         * Type: INTEGER (int)
413         *
414         * @see #FLAG_LOCAL_ONLY
415         * @see #FLAG_SUPPORTS_CREATE
416         * @see #FLAG_SUPPORTS_RECENTS
417         * @see #FLAG_SUPPORTS_SEARCH
418         */
419        public static final String COLUMN_FLAGS = "flags";
420
421        /**
422         * Icon resource ID for a root. This column is required.
423         * <p>
424         * Type: INTEGER (int)
425         */
426        public static final String COLUMN_ICON = "icon";
427
428        /**
429         * Title for a root, which will be shown to a user. This column is
430         * required. For a single storage service surfacing multiple accounts as
431         * different roots, this title should be the name of the service.
432         * <p>
433         * Type: STRING
434         */
435        public static final String COLUMN_TITLE = "title";
436
437        /**
438         * Summary for this root, which may be shown to a user. This column is
439         * optional, and may be {@code null}. For a single storage service
440         * surfacing multiple accounts as different roots, this summary should
441         * be the name of the account.
442         * <p>
443         * Type: STRING
444         */
445        public static final String COLUMN_SUMMARY = "summary";
446
447        /**
448         * Document which is a directory that represents the top directory of
449         * this root. This column is required.
450         * <p>
451         * Type: STRING
452         *
453         * @see Document#COLUMN_DOCUMENT_ID
454         */
455        public static final String COLUMN_DOCUMENT_ID = "document_id";
456
457        /**
458         * Number of bytes available in this root. This column is optional, and
459         * may be {@code null} if unknown or unbounded.
460         * <p>
461         * Type: INTEGER (long)
462         */
463        public static final String COLUMN_AVAILABLE_BYTES = "available_bytes";
464
465        /**
466         * Capacity of a root in bytes. This column is optional, and may be
467         * {@code null} if unknown or unbounded.
468         * {@hide}
469         * <p>
470         * Type: INTEGER (long)
471         */
472        public static final String COLUMN_CAPACITY_BYTES = "capacity_bytes";
473
474        /**
475         * MIME types supported by this root. This column is optional, and if
476         * {@code null} the root is assumed to support all MIME types. Multiple
477         * MIME types can be separated by a newline. For example, a root
478         * supporting audio might return "audio/*\napplication/x-flac".
479         * <p>
480         * Type: STRING
481         */
482        public static final String COLUMN_MIME_TYPES = "mime_types";
483
484        /** {@hide} */
485        public static final String MIME_TYPE_ITEM = "vnd.android.document/root";
486
487        /**
488         * Flag indicating that at least one directory under this root supports
489         * creating content. Roots with this flag will be shown when an
490         * application interacts with {@link Intent#ACTION_CREATE_DOCUMENT}.
491         *
492         * @see #COLUMN_FLAGS
493         */
494        public static final int FLAG_SUPPORTS_CREATE = 1;
495
496        /**
497         * Flag indicating that this root offers content that is strictly local
498         * on the device. That is, no network requests are made for the content.
499         *
500         * @see #COLUMN_FLAGS
501         * @see Intent#EXTRA_LOCAL_ONLY
502         */
503        public static final int FLAG_LOCAL_ONLY = 1 << 1;
504
505        /**
506         * Flag indicating that this root can be queried to provide recently
507         * modified documents.
508         *
509         * @see #COLUMN_FLAGS
510         * @see DocumentsContract#buildRecentDocumentsUri(String, String)
511         * @see DocumentsProvider#queryRecentDocuments(String, String[])
512         */
513        public static final int FLAG_SUPPORTS_RECENTS = 1 << 2;
514
515        /**
516         * Flag indicating that this root supports search.
517         *
518         * @see #COLUMN_FLAGS
519         * @see DocumentsContract#buildSearchDocumentsUri(String, String,
520         *      String)
521         * @see DocumentsProvider#querySearchDocuments(String, String,
522         *      String[])
523         */
524        public static final int FLAG_SUPPORTS_SEARCH = 1 << 3;
525
526        /**
527         * Flag indicating that this root supports testing parent child
528         * relationships.
529         *
530         * @see #COLUMN_FLAGS
531         * @see DocumentsProvider#isChildDocument(String, String)
532         */
533        public static final int FLAG_SUPPORTS_IS_CHILD = 1 << 4;
534
535        /**
536         * Flag indicating that this root is currently empty. This may be used
537         * to hide the root when opening documents, but the root will still be
538         * shown when creating documents and {@link #FLAG_SUPPORTS_CREATE} is
539         * also set. If the value of this flag changes, such as when a root
540         * becomes non-empty, you must send a content changed notification for
541         * {@link DocumentsContract#buildRootsUri(String)}.
542         *
543         * @see #COLUMN_FLAGS
544         * @see ContentResolver#notifyChange(Uri,
545         *      android.database.ContentObserver, boolean)
546         * @hide
547         */
548        public static final int FLAG_EMPTY = 1 << 16;
549
550        /**
551         * Flag indicating that this root should only be visible to advanced
552         * users.
553         *
554         * @see #COLUMN_FLAGS
555         * @hide
556         */
557        public static final int FLAG_ADVANCED = 1 << 17;
558
559        /**
560         * Flag indicating that this root has settings.
561         *
562         * @see #COLUMN_FLAGS
563         * @see DocumentsContract#ACTION_DOCUMENT_ROOT_SETTINGS
564         * @hide
565         */
566        public static final int FLAG_HAS_SETTINGS = 1 << 18;
567    }
568
569    /**
570     * Optional boolean flag included in a directory {@link Cursor#getExtras()}
571     * indicating that a document provider is still loading data. For example, a
572     * provider has returned some results, but is still waiting on an
573     * outstanding network request. The provider must send a content changed
574     * notification when loading is finished.
575     *
576     * @see ContentResolver#notifyChange(Uri, android.database.ContentObserver,
577     *      boolean)
578     */
579    public static final String EXTRA_LOADING = "loading";
580
581    /**
582     * Optional string included in a directory {@link Cursor#getExtras()}
583     * providing an informational message that should be shown to a user. For
584     * example, a provider may wish to indicate that not all documents are
585     * available.
586     */
587    public static final String EXTRA_INFO = "info";
588
589    /**
590     * Optional string included in a directory {@link Cursor#getExtras()}
591     * providing an error message that should be shown to a user. For example, a
592     * provider may wish to indicate that a network error occurred. The user may
593     * choose to retry, resulting in a new query.
594     */
595    public static final String EXTRA_ERROR = "error";
596
597    /**
598     * Optional result (I'm thinking boolean) answer to a question.
599     * {@hide}
600     */
601    public static final String EXTRA_RESULT = "result";
602
603    /** {@hide} */
604    public static final String METHOD_CREATE_DOCUMENT = "android:createDocument";
605    /** {@hide} */
606    public static final String METHOD_RENAME_DOCUMENT = "android:renameDocument";
607    /** {@hide} */
608    public static final String METHOD_DELETE_DOCUMENT = "android:deleteDocument";
609    /** {@hide} */
610    public static final String METHOD_COPY_DOCUMENT = "android:copyDocument";
611    /** {@hide} */
612    public static final String METHOD_MOVE_DOCUMENT = "android:moveDocument";
613    /** {@hide} */
614    public static final String METHOD_IS_CHILD_DOCUMENT = "android:isChildDocument";
615
616    /** {@hide} */
617    public static final String EXTRA_URI = "uri";
618
619    private static final String PATH_ROOT = "root";
620    private static final String PATH_RECENT = "recent";
621    private static final String PATH_DOCUMENT = "document";
622    private static final String PATH_CHILDREN = "children";
623    private static final String PATH_SEARCH = "search";
624    private static final String PATH_TREE = "tree";
625
626    private static final String PARAM_QUERY = "query";
627    private static final String PARAM_MANAGE = "manage";
628
629    /**
630     * Build URI representing the roots of a document provider. When queried, a
631     * provider will return one or more rows with columns defined by
632     * {@link Root}.
633     *
634     * @see DocumentsProvider#queryRoots(String[])
635     */
636    public static Uri buildRootsUri(String authority) {
637        return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT)
638                .authority(authority).appendPath(PATH_ROOT).build();
639    }
640
641    /**
642     * Build URI representing the given {@link Root#COLUMN_ROOT_ID} in a
643     * document provider.
644     *
645     * @see #getRootId(Uri)
646     */
647    public static Uri buildRootUri(String authority, String rootId) {
648        return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT)
649                .authority(authority).appendPath(PATH_ROOT).appendPath(rootId).build();
650    }
651
652    /**
653     * Builds URI for user home directory on external (local) storage.
654     * {@hide}
655     */
656    public static Uri buildHomeUri() {
657        // TODO: Avoid this type of interpackage copying. Added here to avoid
658        // direct coupling, but not ideal.
659        return DocumentsContract.buildRootUri("com.android.externalstorage.documents", "home");
660    }
661
662    /**
663     * Build URI representing the recently modified documents of a specific root
664     * in a document provider. When queried, a provider will return zero or more
665     * rows with columns defined by {@link Document}.
666     *
667     * @see DocumentsProvider#queryRecentDocuments(String, String[])
668     * @see #getRootId(Uri)
669     */
670    public static Uri buildRecentDocumentsUri(String authority, String rootId) {
671        return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT)
672                .authority(authority).appendPath(PATH_ROOT).appendPath(rootId)
673                .appendPath(PATH_RECENT).build();
674    }
675
676    /**
677     * Build URI representing access to descendant documents of the given
678     * {@link Document#COLUMN_DOCUMENT_ID}.
679     *
680     * @see #getTreeDocumentId(Uri)
681     */
682    public static Uri buildTreeDocumentUri(String authority, String documentId) {
683        return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT).authority(authority)
684                .appendPath(PATH_TREE).appendPath(documentId).build();
685    }
686
687    /**
688     * Build URI representing the target {@link Document#COLUMN_DOCUMENT_ID} in
689     * a document provider. When queried, a provider will return a single row
690     * with columns defined by {@link Document}.
691     *
692     * @see DocumentsProvider#queryDocument(String, String[])
693     * @see #getDocumentId(Uri)
694     */
695    public static Uri buildDocumentUri(String authority, String documentId) {
696        return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT)
697                .authority(authority).appendPath(PATH_DOCUMENT).appendPath(documentId).build();
698    }
699
700    /**
701     * Build URI representing the target {@link Document#COLUMN_DOCUMENT_ID} in
702     * a document provider. When queried, a provider will return a single row
703     * with columns defined by {@link Document}.
704     * <p>
705     * However, instead of directly accessing the target document, the returned
706     * URI will leverage access granted through a subtree URI, typically
707     * returned by {@link Intent#ACTION_OPEN_DOCUMENT_TREE}. The target document
708     * must be a descendant (child, grandchild, etc) of the subtree.
709     * <p>
710     * This is typically used to access documents under a user-selected
711     * directory tree, since it doesn't require the user to separately confirm
712     * each new document access.
713     *
714     * @param treeUri the subtree to leverage to gain access to the target
715     *            document. The target directory must be a descendant of this
716     *            subtree.
717     * @param documentId the target document, which the caller may not have
718     *            direct access to.
719     * @see Intent#ACTION_OPEN_DOCUMENT_TREE
720     * @see DocumentsProvider#isChildDocument(String, String)
721     * @see #buildDocumentUri(String, String)
722     */
723    public static Uri buildDocumentUriUsingTree(Uri treeUri, String documentId) {
724        return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT)
725                .authority(treeUri.getAuthority()).appendPath(PATH_TREE)
726                .appendPath(getTreeDocumentId(treeUri)).appendPath(PATH_DOCUMENT)
727                .appendPath(documentId).build();
728    }
729
730    /** {@hide} */
731    public static Uri buildDocumentUriMaybeUsingTree(Uri baseUri, String documentId) {
732        if (isTreeUri(baseUri)) {
733            return buildDocumentUriUsingTree(baseUri, documentId);
734        } else {
735            return buildDocumentUri(baseUri.getAuthority(), documentId);
736        }
737    }
738
739    /**
740     * Build URI representing the children of the target directory in a document
741     * provider. When queried, a provider will return zero or more rows with
742     * columns defined by {@link Document}.
743     *
744     * @param parentDocumentId the document to return children for, which must
745     *            be a directory with MIME type of
746     *            {@link Document#MIME_TYPE_DIR}.
747     * @see DocumentsProvider#queryChildDocuments(String, String[], String)
748     * @see #getDocumentId(Uri)
749     */
750    public static Uri buildChildDocumentsUri(String authority, String parentDocumentId) {
751        return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT).authority(authority)
752                .appendPath(PATH_DOCUMENT).appendPath(parentDocumentId).appendPath(PATH_CHILDREN)
753                .build();
754    }
755
756    /**
757     * Build URI representing the children of the target directory in a document
758     * provider. When queried, a provider will return zero or more rows with
759     * columns defined by {@link Document}.
760     * <p>
761     * However, instead of directly accessing the target directory, the returned
762     * URI will leverage access granted through a subtree URI, typically
763     * returned by {@link Intent#ACTION_OPEN_DOCUMENT_TREE}. The target
764     * directory must be a descendant (child, grandchild, etc) of the subtree.
765     * <p>
766     * This is typically used to access documents under a user-selected
767     * directory tree, since it doesn't require the user to separately confirm
768     * each new document access.
769     *
770     * @param treeUri the subtree to leverage to gain access to the target
771     *            document. The target directory must be a descendant of this
772     *            subtree.
773     * @param parentDocumentId the document to return children for, which the
774     *            caller may not have direct access to, and which must be a
775     *            directory with MIME type of {@link Document#MIME_TYPE_DIR}.
776     * @see Intent#ACTION_OPEN_DOCUMENT_TREE
777     * @see DocumentsProvider#isChildDocument(String, String)
778     * @see #buildChildDocumentsUri(String, String)
779     */
780    public static Uri buildChildDocumentsUriUsingTree(Uri treeUri, String parentDocumentId) {
781        return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT)
782                .authority(treeUri.getAuthority()).appendPath(PATH_TREE)
783                .appendPath(getTreeDocumentId(treeUri)).appendPath(PATH_DOCUMENT)
784                .appendPath(parentDocumentId).appendPath(PATH_CHILDREN).build();
785    }
786
787    /**
788     * Build URI representing a search for matching documents under a specific
789     * root in a document provider. When queried, a provider will return zero or
790     * more rows with columns defined by {@link Document}.
791     *
792     * @see DocumentsProvider#querySearchDocuments(String, String, String[])
793     * @see #getRootId(Uri)
794     * @see #getSearchDocumentsQuery(Uri)
795     */
796    public static Uri buildSearchDocumentsUri(
797            String authority, String rootId, String query) {
798        return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT).authority(authority)
799                .appendPath(PATH_ROOT).appendPath(rootId).appendPath(PATH_SEARCH)
800                .appendQueryParameter(PARAM_QUERY, query).build();
801    }
802
803    /**
804     * Test if the given URI represents a {@link Document} backed by a
805     * {@link DocumentsProvider}.
806     *
807     * @see #buildDocumentUri(String, String)
808     * @see #buildDocumentUriUsingTree(Uri, String)
809     */
810    public static boolean isDocumentUri(Context context, @Nullable Uri uri) {
811        if (isContentUri(uri) && isDocumentsProvider(context, uri.getAuthority())) {
812            final List<String> paths = uri.getPathSegments();
813            if (paths.size() == 2) {
814                return PATH_DOCUMENT.equals(paths.get(0));
815            } else if (paths.size() == 4) {
816                return PATH_TREE.equals(paths.get(0)) && PATH_DOCUMENT.equals(paths.get(2));
817            }
818        }
819        return false;
820    }
821
822    /** {@hide} */
823    public static boolean isRootUri(Context context, @Nullable Uri uri) {
824        if (isContentUri(uri) && isDocumentsProvider(context, uri.getAuthority())) {
825            final List<String> paths = uri.getPathSegments();
826            return (paths.size() == 2 && PATH_ROOT.equals(paths.get(0)));
827        }
828        return false;
829    }
830
831    /** {@hide} */
832    public static boolean isContentUri(@Nullable Uri uri) {
833        return uri != null && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme());
834    }
835
836    /** {@hide} */
837    public static boolean isTreeUri(Uri uri) {
838        final List<String> paths = uri.getPathSegments();
839        return (paths.size() >= 2 && PATH_TREE.equals(paths.get(0)));
840    }
841
842    private static boolean isDocumentsProvider(Context context, String authority) {
843        final Intent intent = new Intent(PROVIDER_INTERFACE);
844        final List<ResolveInfo> infos = context.getPackageManager()
845                .queryIntentContentProviders(intent, 0);
846        for (ResolveInfo info : infos) {
847            if (authority.equals(info.providerInfo.authority)) {
848                return true;
849            }
850        }
851        return false;
852    }
853
854    /**
855     * Extract the {@link Root#COLUMN_ROOT_ID} from the given URI.
856     */
857    public static String getRootId(Uri rootUri) {
858        final List<String> paths = rootUri.getPathSegments();
859        if (paths.size() >= 2 && PATH_ROOT.equals(paths.get(0))) {
860            return paths.get(1);
861        }
862        throw new IllegalArgumentException("Invalid URI: " + rootUri);
863    }
864
865    /**
866     * Extract the {@link Document#COLUMN_DOCUMENT_ID} from the given URI.
867     *
868     * @see #isDocumentUri(Context, Uri)
869     */
870    public static String getDocumentId(Uri documentUri) {
871        final List<String> paths = documentUri.getPathSegments();
872        if (paths.size() >= 2 && PATH_DOCUMENT.equals(paths.get(0))) {
873            return paths.get(1);
874        }
875        if (paths.size() >= 4 && PATH_TREE.equals(paths.get(0))
876                && PATH_DOCUMENT.equals(paths.get(2))) {
877            return paths.get(3);
878        }
879        throw new IllegalArgumentException("Invalid URI: " + documentUri);
880    }
881
882    /**
883     * Extract the via {@link Document#COLUMN_DOCUMENT_ID} from the given URI.
884     */
885    public static String getTreeDocumentId(Uri documentUri) {
886        final List<String> paths = documentUri.getPathSegments();
887        if (paths.size() >= 2 && PATH_TREE.equals(paths.get(0))) {
888            return paths.get(1);
889        }
890        throw new IllegalArgumentException("Invalid URI: " + documentUri);
891    }
892
893    /**
894     * Extract the search query from a URI built by
895     * {@link #buildSearchDocumentsUri(String, String, String)}.
896     */
897    public static String getSearchDocumentsQuery(Uri searchDocumentsUri) {
898        return searchDocumentsUri.getQueryParameter(PARAM_QUERY);
899    }
900
901    /** {@hide} */
902    public static Uri setManageMode(Uri uri) {
903        return uri.buildUpon().appendQueryParameter(PARAM_MANAGE, "true").build();
904    }
905
906    /** {@hide} */
907    public static boolean isManageMode(Uri uri) {
908        return uri.getBooleanQueryParameter(PARAM_MANAGE, false);
909    }
910
911    /**
912     * Return thumbnail representing the document at the given URI. Callers are
913     * responsible for their own in-memory caching.
914     *
915     * @param documentUri document to return thumbnail for, which must have
916     *            {@link Document#FLAG_SUPPORTS_THUMBNAIL} set.
917     * @param size optimal thumbnail size desired. A provider may return a
918     *            thumbnail of a different size, but never more than double the
919     *            requested size.
920     * @param signal signal used to indicate if caller is no longer interested
921     *            in the thumbnail.
922     * @return decoded thumbnail, or {@code null} if problem was encountered.
923     * @see DocumentsProvider#openDocumentThumbnail(String, Point,
924     *      android.os.CancellationSignal)
925     */
926    public static Bitmap getDocumentThumbnail(
927            ContentResolver resolver, Uri documentUri, Point size, CancellationSignal signal) {
928        final ContentProviderClient client = resolver.acquireUnstableContentProviderClient(
929                documentUri.getAuthority());
930        try {
931            return getDocumentThumbnail(client, documentUri, size, signal);
932        } catch (Exception e) {
933            if (!(e instanceof OperationCanceledException)) {
934                Log.w(TAG, "Failed to load thumbnail for " + documentUri + ": " + e);
935            }
936            return null;
937        } finally {
938            ContentProviderClient.releaseQuietly(client);
939        }
940    }
941
942    /** {@hide} */
943    public static Bitmap getDocumentThumbnail(
944            ContentProviderClient client, Uri documentUri, Point size, CancellationSignal signal)
945            throws RemoteException, IOException {
946        final Bundle openOpts = new Bundle();
947        openOpts.putParcelable(ContentResolver.EXTRA_SIZE, size);
948
949        AssetFileDescriptor afd = null;
950        Bitmap bitmap = null;
951        try {
952            afd = client.openTypedAssetFileDescriptor(documentUri, "image/*", openOpts, signal);
953
954            final FileDescriptor fd = afd.getFileDescriptor();
955            final long offset = afd.getStartOffset();
956
957            // Try seeking on the returned FD, since it gives us the most
958            // optimal decode path; otherwise fall back to buffering.
959            BufferedInputStream is = null;
960            try {
961                Os.lseek(fd, offset, SEEK_SET);
962            } catch (ErrnoException e) {
963                is = new BufferedInputStream(new FileInputStream(fd), THUMBNAIL_BUFFER_SIZE);
964                is.mark(THUMBNAIL_BUFFER_SIZE);
965            }
966
967            // We requested a rough thumbnail size, but the remote size may have
968            // returned something giant, so defensively scale down as needed.
969            final BitmapFactory.Options opts = new BitmapFactory.Options();
970            opts.inJustDecodeBounds = true;
971            if (is != null) {
972                BitmapFactory.decodeStream(is, null, opts);
973            } else {
974                BitmapFactory.decodeFileDescriptor(fd, null, opts);
975            }
976
977            final int widthSample = opts.outWidth / size.x;
978            final int heightSample = opts.outHeight / size.y;
979
980            opts.inJustDecodeBounds = false;
981            opts.inSampleSize = Math.min(widthSample, heightSample);
982            if (is != null) {
983                is.reset();
984                bitmap = BitmapFactory.decodeStream(is, null, opts);
985            } else {
986                try {
987                    Os.lseek(fd, offset, SEEK_SET);
988                } catch (ErrnoException e) {
989                    e.rethrowAsIOException();
990                }
991                bitmap = BitmapFactory.decodeFileDescriptor(fd, null, opts);
992            }
993
994            // Transform the bitmap if requested. We use a side-channel to
995            // communicate the orientation, since EXIF thumbnails don't contain
996            // the rotation flags of the original image.
997            final Bundle extras = afd.getExtras();
998            final int orientation = (extras != null) ? extras.getInt(EXTRA_ORIENTATION, 0) : 0;
999            if (orientation != 0) {
1000                final int width = bitmap.getWidth();
1001                final int height = bitmap.getHeight();
1002
1003                final Matrix m = new Matrix();
1004                m.setRotate(orientation, width / 2, height / 2);
1005                bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, m, false);
1006            }
1007        } finally {
1008            IoUtils.closeQuietly(afd);
1009        }
1010
1011        return bitmap;
1012    }
1013
1014    /**
1015     * Create a new document with given MIME type and display name.
1016     *
1017     * @param parentDocumentUri directory with
1018     *            {@link Document#FLAG_DIR_SUPPORTS_CREATE}
1019     * @param mimeType MIME type of new document
1020     * @param displayName name of new document
1021     * @return newly created document, or {@code null} if failed
1022     */
1023    public static Uri createDocument(ContentResolver resolver, Uri parentDocumentUri,
1024            String mimeType, String displayName) {
1025        final ContentProviderClient client = resolver.acquireUnstableContentProviderClient(
1026                parentDocumentUri.getAuthority());
1027        try {
1028            return createDocument(client, parentDocumentUri, mimeType, displayName);
1029        } catch (Exception e) {
1030            Log.w(TAG, "Failed to create document", e);
1031            return null;
1032        } finally {
1033            ContentProviderClient.releaseQuietly(client);
1034        }
1035    }
1036
1037    /** {@hide} */
1038    public static Uri createDocument(ContentProviderClient client, Uri parentDocumentUri,
1039            String mimeType, String displayName) throws RemoteException {
1040        final Bundle in = new Bundle();
1041        in.putParcelable(DocumentsContract.EXTRA_URI, parentDocumentUri);
1042        in.putString(Document.COLUMN_MIME_TYPE, mimeType);
1043        in.putString(Document.COLUMN_DISPLAY_NAME, displayName);
1044
1045        final Bundle out = client.call(METHOD_CREATE_DOCUMENT, null, in);
1046        return out.getParcelable(DocumentsContract.EXTRA_URI);
1047    }
1048
1049    /** {@hide} */
1050    public static boolean isChildDocument(ContentProviderClient client, Uri parentDocumentUri,
1051            Uri childDocumentUri) throws RemoteException {
1052
1053        final Bundle in = new Bundle();
1054        in.putParcelable(DocumentsContract.EXTRA_URI, parentDocumentUri);
1055        in.putParcelable(DocumentsContract.EXTRA_TARGET_URI, childDocumentUri);
1056
1057        final Bundle out = client.call(METHOD_IS_CHILD_DOCUMENT, null, in);
1058        if (out == null) {
1059            throw new RemoteException("Failed to get a reponse from isChildDocument query.");
1060        }
1061        if (!out.containsKey(DocumentsContract.EXTRA_RESULT)) {
1062            throw new RemoteException("Response did not include result field..");
1063        }
1064        return out.getBoolean(DocumentsContract.EXTRA_RESULT);
1065    }
1066
1067    /**
1068     * Change the display name of an existing document.
1069     * <p>
1070     * If the underlying provider needs to create a new
1071     * {@link Document#COLUMN_DOCUMENT_ID} to represent the updated display
1072     * name, that new document is returned and the original document is no
1073     * longer valid. Otherwise, the original document is returned.
1074     *
1075     * @param documentUri document with {@link Document#FLAG_SUPPORTS_RENAME}
1076     * @param displayName updated name for document
1077     * @return the existing or new document after the rename, or {@code null} if
1078     *         failed.
1079     */
1080    public static Uri renameDocument(ContentResolver resolver, Uri documentUri,
1081            String displayName) {
1082        final ContentProviderClient client = resolver.acquireUnstableContentProviderClient(
1083                documentUri.getAuthority());
1084        try {
1085            return renameDocument(client, documentUri, displayName);
1086        } catch (Exception e) {
1087            Log.w(TAG, "Failed to rename document", e);
1088            return null;
1089        } finally {
1090            ContentProviderClient.releaseQuietly(client);
1091        }
1092    }
1093
1094    /** {@hide} */
1095    public static Uri renameDocument(ContentProviderClient client, Uri documentUri,
1096            String displayName) throws RemoteException {
1097        final Bundle in = new Bundle();
1098        in.putParcelable(DocumentsContract.EXTRA_URI, documentUri);
1099        in.putString(Document.COLUMN_DISPLAY_NAME, displayName);
1100
1101        final Bundle out = client.call(METHOD_RENAME_DOCUMENT, null, in);
1102        final Uri outUri = out.getParcelable(DocumentsContract.EXTRA_URI);
1103        return (outUri != null) ? outUri : documentUri;
1104    }
1105
1106    /**
1107     * Delete the given document.
1108     *
1109     * @param documentUri document with {@link Document#FLAG_SUPPORTS_DELETE}
1110     * @return if the document was deleted successfully.
1111     */
1112    public static boolean deleteDocument(ContentResolver resolver, Uri documentUri) {
1113        final ContentProviderClient client = resolver.acquireUnstableContentProviderClient(
1114                documentUri.getAuthority());
1115        try {
1116            deleteDocument(client, documentUri);
1117            return true;
1118        } catch (Exception e) {
1119            Log.w(TAG, "Failed to delete document", e);
1120            return false;
1121        } finally {
1122            ContentProviderClient.releaseQuietly(client);
1123        }
1124    }
1125
1126    /** {@hide} */
1127    public static void deleteDocument(ContentProviderClient client, Uri documentUri)
1128            throws RemoteException {
1129        final Bundle in = new Bundle();
1130        in.putParcelable(DocumentsContract.EXTRA_URI, documentUri);
1131
1132        client.call(METHOD_DELETE_DOCUMENT, null, in);
1133    }
1134
1135    /**
1136     * Copies the given document.
1137     *
1138     * @param sourceDocumentUri document with {@link Document#FLAG_SUPPORTS_COPY}
1139     * @param targetParentDocumentUri document which will become a parent of the source
1140     *         document's copy.
1141     * @return the copied document, or {@code null} if failed.
1142     * @hide
1143     */
1144    public static Uri copyDocument(ContentResolver resolver, Uri sourceDocumentUri,
1145            Uri targetParentDocumentUri) {
1146        final ContentProviderClient client = resolver.acquireUnstableContentProviderClient(
1147                sourceDocumentUri.getAuthority());
1148        try {
1149            return copyDocument(client, sourceDocumentUri, targetParentDocumentUri);
1150        } catch (Exception e) {
1151            Log.w(TAG, "Failed to copy document", e);
1152            return null;
1153        } finally {
1154            ContentProviderClient.releaseQuietly(client);
1155        }
1156    }
1157
1158    /** {@hide} */
1159    public static Uri copyDocument(ContentProviderClient client, Uri sourceDocumentUri,
1160            Uri targetParentDocumentUri) throws RemoteException {
1161        final Bundle in = new Bundle();
1162        in.putParcelable(DocumentsContract.EXTRA_URI, sourceDocumentUri);
1163        in.putParcelable(DocumentsContract.EXTRA_TARGET_URI, targetParentDocumentUri);
1164
1165        final Bundle out = client.call(METHOD_COPY_DOCUMENT, null, in);
1166        return out.getParcelable(DocumentsContract.EXTRA_URI);
1167    }
1168
1169    /**
1170     * Moves the given document under a new parent.
1171     *
1172     * @param sourceDocumentUri document with {@link Document#FLAG_SUPPORTS_MOVE}
1173     * @param targetParentDocumentUri document which will become a new parent of the source
1174     *         document.
1175     * @return the moved document, or {@code null} if failed.
1176     * @hide
1177     */
1178    public static Uri moveDocument(ContentResolver resolver, Uri sourceDocumentUri,
1179            Uri targetParentDocumentUri) {
1180        final ContentProviderClient client = resolver.acquireUnstableContentProviderClient(
1181                sourceDocumentUri.getAuthority());
1182        try {
1183            return moveDocument(client, sourceDocumentUri, targetParentDocumentUri);
1184        } catch (Exception e) {
1185            Log.w(TAG, "Failed to move document", e);
1186            return null;
1187        } finally {
1188            ContentProviderClient.releaseQuietly(client);
1189        }
1190    }
1191
1192    /** {@hide} */
1193    public static Uri moveDocument(ContentProviderClient client, Uri sourceDocumentUri,
1194            Uri targetParentDocumentUri) throws RemoteException {
1195        final Bundle in = new Bundle();
1196        in.putParcelable(DocumentsContract.EXTRA_URI, sourceDocumentUri);
1197        in.putParcelable(DocumentsContract.EXTRA_TARGET_URI, targetParentDocumentUri);
1198
1199        final Bundle out = client.call(METHOD_MOVE_DOCUMENT, null, in);
1200        return out.getParcelable(DocumentsContract.EXTRA_URI);
1201    }
1202
1203    /**
1204     * Open the given image for thumbnail purposes, using any embedded EXIF
1205     * thumbnail if available, and providing orientation hints from the parent
1206     * image.
1207     *
1208     * @hide
1209     */
1210    public static AssetFileDescriptor openImageThumbnail(File file) throws FileNotFoundException {
1211        final ParcelFileDescriptor pfd = ParcelFileDescriptor.open(
1212                file, ParcelFileDescriptor.MODE_READ_ONLY);
1213        Bundle extras = null;
1214
1215        try {
1216            final ExifInterface exif = new ExifInterface(file.getAbsolutePath());
1217
1218            switch (exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, -1)) {
1219                case ExifInterface.ORIENTATION_ROTATE_90:
1220                    extras = new Bundle(1);
1221                    extras.putInt(EXTRA_ORIENTATION, 90);
1222                    break;
1223                case ExifInterface.ORIENTATION_ROTATE_180:
1224                    extras = new Bundle(1);
1225                    extras.putInt(EXTRA_ORIENTATION, 180);
1226                    break;
1227                case ExifInterface.ORIENTATION_ROTATE_270:
1228                    extras = new Bundle(1);
1229                    extras.putInt(EXTRA_ORIENTATION, 270);
1230                    break;
1231            }
1232
1233            final long[] thumb = exif.getThumbnailRange();
1234            if (thumb != null) {
1235                return new AssetFileDescriptor(pfd, thumb[0], thumb[1], extras);
1236            }
1237        } catch (IOException e) {
1238        }
1239
1240        return new AssetFileDescriptor(pfd, 0, AssetFileDescriptor.UNKNOWN_LENGTH, extras);
1241    }
1242}
1243