DocumentsContract.java revision d3afdeebeb9dcfbb5f24e4afac988e2e96de26de
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_SUPPORTS_TYPED_DOCUMENT
234         * @see #FLAG_DIR_PREFERS_GRID
235         * @see #FLAG_DIR_PREFERS_LAST_MODIFIED
236         * @see #FLAG_VIRTUAL_DOCUMENT
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 can be converted to alternative types.
352         *
353         * @see #COLUMN_FLAGS
354         * @see DocumentsProvider#openTypedDocument(String, String, Bundle,
355         *      android.os.CancellationSignal)
356         */
357        public static final int FLAG_SUPPORTS_TYPED_DOCUMENT = 1 << 9;
358
359        /**
360         * Flag indicating that a document is virtual, and doesn't have byte
361         * representation in the MIME type specified as {@link #COLUMN_MIME_TYPE}.
362         *
363         * @see #COLUMN_FLAGS
364         * @see #COLUMN_MIME_TYPE
365         * @see DocumentsProvider#openTypedDocument(String, String, Bundle,
366         *      android.os.CancellationSignal)
367         */
368        public static final int FLAG_VIRTUAL_DOCUMENT = 1 << 10;
369
370        /**
371         * Flag indicating that document titles should be hidden when viewing
372         * this directory in a larger format grid. For example, a directory
373         * containing only images may want the image thumbnails to speak for
374         * themselves. Only valid when {@link #COLUMN_MIME_TYPE} is
375         * {@link #MIME_TYPE_DIR}.
376         *
377         * @see #COLUMN_FLAGS
378         * @see #FLAG_DIR_PREFERS_GRID
379         * @hide
380         */
381        public static final int FLAG_DIR_HIDE_GRID_TITLES = 1 << 16;
382    }
383
384    /**
385     * Constants related to a root of documents, including {@link Cursor} column
386     * names and flags. A root is the start of a tree of documents, such as a
387     * physical storage device, or an account. Each root starts at the directory
388     * referenced by {@link Root#COLUMN_DOCUMENT_ID}, which can recursively
389     * contain both documents and directories.
390     * <p>
391     * All columns are <em>read-only</em> to client applications.
392     */
393    public final static class Root {
394        private Root() {
395        }
396
397        /**
398         * Unique ID of a root. This ID is both provided by and interpreted by a
399         * {@link DocumentsProvider}, and should be treated as an opaque value
400         * by client applications. This column is required.
401         * <p>
402         * Type: STRING
403         */
404        public static final String COLUMN_ROOT_ID = "root_id";
405
406        /**
407         * Flags that apply to a root. This column is required.
408         * <p>
409         * Type: INTEGER (int)
410         *
411         * @see #FLAG_LOCAL_ONLY
412         * @see #FLAG_SUPPORTS_CREATE
413         * @see #FLAG_SUPPORTS_RECENTS
414         * @see #FLAG_SUPPORTS_SEARCH
415         */
416        public static final String COLUMN_FLAGS = "flags";
417
418        /**
419         * Icon resource ID for a root. This column is required.
420         * <p>
421         * Type: INTEGER (int)
422         */
423        public static final String COLUMN_ICON = "icon";
424
425        /**
426         * Title for a root, which will be shown to a user. This column is
427         * required. For a single storage service surfacing multiple accounts as
428         * different roots, this title should be the name of the service.
429         * <p>
430         * Type: STRING
431         */
432        public static final String COLUMN_TITLE = "title";
433
434        /**
435         * Summary for this root, which may be shown to a user. This column is
436         * optional, and may be {@code null}. For a single storage service
437         * surfacing multiple accounts as different roots, this summary should
438         * be the name of the account.
439         * <p>
440         * Type: STRING
441         */
442        public static final String COLUMN_SUMMARY = "summary";
443
444        /**
445         * Document which is a directory that represents the top directory of
446         * this root. This column is required.
447         * <p>
448         * Type: STRING
449         *
450         * @see Document#COLUMN_DOCUMENT_ID
451         */
452        public static final String COLUMN_DOCUMENT_ID = "document_id";
453
454        /**
455         * Number of bytes available in this root. This column is optional, and
456         * may be {@code null} if unknown or unbounded.
457         * <p>
458         * Type: INTEGER (long)
459         */
460        public static final String COLUMN_AVAILABLE_BYTES = "available_bytes";
461
462        /**
463         * Capacity of a root in bytes. This column is optional, and may be
464         * {@code null} if unknown or unbounded.
465         * {@hide}
466         * <p>
467         * Type: INTEGER (long)
468         */
469        public static final String COLUMN_CAPACITY_BYTES = "capacity_bytes";
470
471        /**
472         * MIME types supported by this root. This column is optional, and if
473         * {@code null} the root is assumed to support all MIME types. Multiple
474         * MIME types can be separated by a newline. For example, a root
475         * supporting audio might return "audio/*\napplication/x-flac".
476         * <p>
477         * Type: STRING
478         */
479        public static final String COLUMN_MIME_TYPES = "mime_types";
480
481        /** {@hide} */
482        public static final String MIME_TYPE_ITEM = "vnd.android.document/root";
483
484        /**
485         * Flag indicating that at least one directory under this root supports
486         * creating content. Roots with this flag will be shown when an
487         * application interacts with {@link Intent#ACTION_CREATE_DOCUMENT}.
488         *
489         * @see #COLUMN_FLAGS
490         */
491        public static final int FLAG_SUPPORTS_CREATE = 1;
492
493        /**
494         * Flag indicating that this root offers content that is strictly local
495         * on the device. That is, no network requests are made for the content.
496         *
497         * @see #COLUMN_FLAGS
498         * @see Intent#EXTRA_LOCAL_ONLY
499         */
500        public static final int FLAG_LOCAL_ONLY = 1 << 1;
501
502        /**
503         * Flag indicating that this root can be queried to provide recently
504         * modified documents.
505         *
506         * @see #COLUMN_FLAGS
507         * @see DocumentsContract#buildRecentDocumentsUri(String, String)
508         * @see DocumentsProvider#queryRecentDocuments(String, String[])
509         */
510        public static final int FLAG_SUPPORTS_RECENTS = 1 << 2;
511
512        /**
513         * Flag indicating that this root supports search.
514         *
515         * @see #COLUMN_FLAGS
516         * @see DocumentsContract#buildSearchDocumentsUri(String, String,
517         *      String)
518         * @see DocumentsProvider#querySearchDocuments(String, String,
519         *      String[])
520         */
521        public static final int FLAG_SUPPORTS_SEARCH = 1 << 3;
522
523        /**
524         * Flag indicating that this root supports testing parent child
525         * relationships.
526         *
527         * @see #COLUMN_FLAGS
528         * @see DocumentsProvider#isChildDocument(String, String)
529         */
530        public static final int FLAG_SUPPORTS_IS_CHILD = 1 << 4;
531
532        /**
533         * Flag indicating that this root is currently empty. This may be used
534         * to hide the root when opening documents, but the root will still be
535         * shown when creating documents and {@link #FLAG_SUPPORTS_CREATE} is
536         * also set. If the value of this flag changes, such as when a root
537         * becomes non-empty, you must send a content changed notification for
538         * {@link DocumentsContract#buildRootsUri(String)}.
539         *
540         * @see #COLUMN_FLAGS
541         * @see ContentResolver#notifyChange(Uri,
542         *      android.database.ContentObserver, boolean)
543         * @hide
544         */
545        public static final int FLAG_EMPTY = 1 << 16;
546
547        /**
548         * Flag indicating that this root should only be visible to advanced
549         * users.
550         *
551         * @see #COLUMN_FLAGS
552         * @hide
553         */
554        public static final int FLAG_ADVANCED = 1 << 17;
555
556        /**
557         * Flag indicating that this root has settings.
558         *
559         * @see #COLUMN_FLAGS
560         * @see DocumentsContract#ACTION_DOCUMENT_ROOT_SETTINGS
561         * @hide
562         */
563        public static final int FLAG_HAS_SETTINGS = 1 << 18;
564    }
565
566    /**
567     * Optional boolean flag included in a directory {@link Cursor#getExtras()}
568     * indicating that a document provider is still loading data. For example, a
569     * provider has returned some results, but is still waiting on an
570     * outstanding network request. The provider must send a content changed
571     * notification when loading is finished.
572     *
573     * @see ContentResolver#notifyChange(Uri, android.database.ContentObserver,
574     *      boolean)
575     */
576    public static final String EXTRA_LOADING = "loading";
577
578    /**
579     * Optional string included in a directory {@link Cursor#getExtras()}
580     * providing an informational message that should be shown to a user. For
581     * example, a provider may wish to indicate that not all documents are
582     * available.
583     */
584    public static final String EXTRA_INFO = "info";
585
586    /**
587     * Optional string included in a directory {@link Cursor#getExtras()}
588     * providing an error message that should be shown to a user. For example, a
589     * provider may wish to indicate that a network error occurred. The user may
590     * choose to retry, resulting in a new query.
591     */
592    public static final String EXTRA_ERROR = "error";
593
594    /**
595     * Optional result (I'm thinking boolean) answer to a question.
596     * {@hide}
597     */
598    public static final String EXTRA_RESULT = "result";
599
600    /** {@hide} */
601    public static final String METHOD_CREATE_DOCUMENT = "android:createDocument";
602    /** {@hide} */
603    public static final String METHOD_RENAME_DOCUMENT = "android:renameDocument";
604    /** {@hide} */
605    public static final String METHOD_DELETE_DOCUMENT = "android:deleteDocument";
606    /** {@hide} */
607    public static final String METHOD_COPY_DOCUMENT = "android:copyDocument";
608    /** {@hide} */
609    public static final String METHOD_MOVE_DOCUMENT = "android:moveDocument";
610    /** {@hide} */
611    public static final String METHOD_IS_CHILD_DOCUMENT = "android:isChildDocument";
612
613    /** {@hide} */
614    public static final String EXTRA_URI = "uri";
615
616    private static final String PATH_ROOT = "root";
617    private static final String PATH_RECENT = "recent";
618    private static final String PATH_DOCUMENT = "document";
619    private static final String PATH_CHILDREN = "children";
620    private static final String PATH_SEARCH = "search";
621    private static final String PATH_TREE = "tree";
622
623    private static final String PARAM_QUERY = "query";
624    private static final String PARAM_MANAGE = "manage";
625
626    /**
627     * Build URI representing the roots of a document provider. When queried, a
628     * provider will return one or more rows with columns defined by
629     * {@link Root}.
630     *
631     * @see DocumentsProvider#queryRoots(String[])
632     */
633    public static Uri buildRootsUri(String authority) {
634        return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT)
635                .authority(authority).appendPath(PATH_ROOT).build();
636    }
637
638    /**
639     * Build URI representing the given {@link Root#COLUMN_ROOT_ID} in a
640     * document provider.
641     *
642     * @see #getRootId(Uri)
643     */
644    public static Uri buildRootUri(String authority, String rootId) {
645        return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT)
646                .authority(authority).appendPath(PATH_ROOT).appendPath(rootId).build();
647    }
648
649    /**
650     * Build URI representing the recently modified documents of a specific root
651     * in a document provider. When queried, a provider will return zero or more
652     * rows with columns defined by {@link Document}.
653     *
654     * @see DocumentsProvider#queryRecentDocuments(String, String[])
655     * @see #getRootId(Uri)
656     */
657    public static Uri buildRecentDocumentsUri(String authority, String rootId) {
658        return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT)
659                .authority(authority).appendPath(PATH_ROOT).appendPath(rootId)
660                .appendPath(PATH_RECENT).build();
661    }
662
663    /**
664     * Build URI representing access to descendant documents of the given
665     * {@link Document#COLUMN_DOCUMENT_ID}.
666     *
667     * @see #getTreeDocumentId(Uri)
668     */
669    public static Uri buildTreeDocumentUri(String authority, String documentId) {
670        return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT).authority(authority)
671                .appendPath(PATH_TREE).appendPath(documentId).build();
672    }
673
674    /**
675     * Build URI representing the target {@link Document#COLUMN_DOCUMENT_ID} in
676     * a document provider. When queried, a provider will return a single row
677     * with columns defined by {@link Document}.
678     *
679     * @see DocumentsProvider#queryDocument(String, String[])
680     * @see #getDocumentId(Uri)
681     */
682    public static Uri buildDocumentUri(String authority, String documentId) {
683        return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT)
684                .authority(authority).appendPath(PATH_DOCUMENT).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     * <p>
692     * However, instead of directly accessing the target document, the returned
693     * URI will leverage access granted through a subtree URI, typically
694     * returned by {@link Intent#ACTION_OPEN_DOCUMENT_TREE}. The target document
695     * must be a descendant (child, grandchild, etc) of the subtree.
696     * <p>
697     * This is typically used to access documents under a user-selected
698     * directory tree, since it doesn't require the user to separately confirm
699     * each new document access.
700     *
701     * @param treeUri the subtree to leverage to gain access to the target
702     *            document. The target directory must be a descendant of this
703     *            subtree.
704     * @param documentId the target document, which the caller may not have
705     *            direct access to.
706     * @see Intent#ACTION_OPEN_DOCUMENT_TREE
707     * @see DocumentsProvider#isChildDocument(String, String)
708     * @see #buildDocumentUri(String, String)
709     */
710    public static Uri buildDocumentUriUsingTree(Uri treeUri, String documentId) {
711        return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT)
712                .authority(treeUri.getAuthority()).appendPath(PATH_TREE)
713                .appendPath(getTreeDocumentId(treeUri)).appendPath(PATH_DOCUMENT)
714                .appendPath(documentId).build();
715    }
716
717    /** {@hide} */
718    public static Uri buildDocumentUriMaybeUsingTree(Uri baseUri, String documentId) {
719        if (isTreeUri(baseUri)) {
720            return buildDocumentUriUsingTree(baseUri, documentId);
721        } else {
722            return buildDocumentUri(baseUri.getAuthority(), documentId);
723        }
724    }
725
726    /**
727     * Build URI representing the children of the target directory in a document
728     * provider. When queried, a provider will return zero or more rows with
729     * columns defined by {@link Document}.
730     *
731     * @param parentDocumentId the document to return children for, which must
732     *            be a directory with MIME type of
733     *            {@link Document#MIME_TYPE_DIR}.
734     * @see DocumentsProvider#queryChildDocuments(String, String[], String)
735     * @see #getDocumentId(Uri)
736     */
737    public static Uri buildChildDocumentsUri(String authority, String parentDocumentId) {
738        return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT).authority(authority)
739                .appendPath(PATH_DOCUMENT).appendPath(parentDocumentId).appendPath(PATH_CHILDREN)
740                .build();
741    }
742
743    /**
744     * Build URI representing the children of the target directory in a document
745     * provider. When queried, a provider will return zero or more rows with
746     * columns defined by {@link Document}.
747     * <p>
748     * However, instead of directly accessing the target directory, the returned
749     * URI will leverage access granted through a subtree URI, typically
750     * returned by {@link Intent#ACTION_OPEN_DOCUMENT_TREE}. The target
751     * directory must be a descendant (child, grandchild, etc) of the subtree.
752     * <p>
753     * This is typically used to access documents under a user-selected
754     * directory tree, since it doesn't require the user to separately confirm
755     * each new document access.
756     *
757     * @param treeUri the subtree to leverage to gain access to the target
758     *            document. The target directory must be a descendant of this
759     *            subtree.
760     * @param parentDocumentId the document to return children for, which the
761     *            caller may not have direct access to, and which must be a
762     *            directory with MIME type of {@link Document#MIME_TYPE_DIR}.
763     * @see Intent#ACTION_OPEN_DOCUMENT_TREE
764     * @see DocumentsProvider#isChildDocument(String, String)
765     * @see #buildChildDocumentsUri(String, String)
766     */
767    public static Uri buildChildDocumentsUriUsingTree(Uri treeUri, String parentDocumentId) {
768        return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT)
769                .authority(treeUri.getAuthority()).appendPath(PATH_TREE)
770                .appendPath(getTreeDocumentId(treeUri)).appendPath(PATH_DOCUMENT)
771                .appendPath(parentDocumentId).appendPath(PATH_CHILDREN).build();
772    }
773
774    /**
775     * Build URI representing a search for matching documents under a specific
776     * root in a document provider. When queried, a provider will return zero or
777     * more rows with columns defined by {@link Document}.
778     *
779     * @see DocumentsProvider#querySearchDocuments(String, String, String[])
780     * @see #getRootId(Uri)
781     * @see #getSearchDocumentsQuery(Uri)
782     */
783    public static Uri buildSearchDocumentsUri(
784            String authority, String rootId, String query) {
785        return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT).authority(authority)
786                .appendPath(PATH_ROOT).appendPath(rootId).appendPath(PATH_SEARCH)
787                .appendQueryParameter(PARAM_QUERY, query).build();
788    }
789
790    /**
791     * Test if the given URI represents a {@link Document} backed by a
792     * {@link DocumentsProvider}.
793     *
794     * @see #buildDocumentUri(String, String)
795     * @see #buildDocumentUriUsingTree(Uri, String)
796     */
797    public static boolean isDocumentUri(Context context, @Nullable Uri uri) {
798        if (isContentUri(uri) && isDocumentsProvider(context, uri.getAuthority())) {
799            final List<String> paths = uri.getPathSegments();
800            if (paths.size() == 2) {
801                return PATH_DOCUMENT.equals(paths.get(0));
802            } else if (paths.size() == 4) {
803                return PATH_TREE.equals(paths.get(0)) && PATH_DOCUMENT.equals(paths.get(2));
804            }
805        }
806        return false;
807    }
808
809    /** {@hide} */
810    public static boolean isRootUri(Context context, @Nullable Uri uri) {
811        if (isContentUri(uri) && isDocumentsProvider(context, uri.getAuthority())) {
812            final List<String> paths = uri.getPathSegments();
813            return (paths.size() == 2 && PATH_ROOT.equals(paths.get(0)));
814        }
815        return false;
816    }
817
818    /** {@hide} */
819    public static boolean isContentUri(@Nullable Uri uri) {
820        return uri != null && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme());
821    }
822
823    /** {@hide} */
824    public static boolean isTreeUri(Uri uri) {
825        final List<String> paths = uri.getPathSegments();
826        return (paths.size() >= 2 && PATH_TREE.equals(paths.get(0)));
827    }
828
829    private static boolean isDocumentsProvider(Context context, String authority) {
830        final Intent intent = new Intent(PROVIDER_INTERFACE);
831        final List<ResolveInfo> infos = context.getPackageManager()
832                .queryIntentContentProviders(intent, 0);
833        for (ResolveInfo info : infos) {
834            if (authority.equals(info.providerInfo.authority)) {
835                return true;
836            }
837        }
838        return false;
839    }
840
841    /**
842     * Extract the {@link Root#COLUMN_ROOT_ID} from the given URI.
843     */
844    public static String getRootId(Uri rootUri) {
845        final List<String> paths = rootUri.getPathSegments();
846        if (paths.size() >= 2 && PATH_ROOT.equals(paths.get(0))) {
847            return paths.get(1);
848        }
849        throw new IllegalArgumentException("Invalid URI: " + rootUri);
850    }
851
852    /**
853     * Extract the {@link Document#COLUMN_DOCUMENT_ID} from the given URI.
854     *
855     * @see #isDocumentUri(Context, Uri)
856     */
857    public static String getDocumentId(Uri documentUri) {
858        final List<String> paths = documentUri.getPathSegments();
859        if (paths.size() >= 2 && PATH_DOCUMENT.equals(paths.get(0))) {
860            return paths.get(1);
861        }
862        if (paths.size() >= 4 && PATH_TREE.equals(paths.get(0))
863                && PATH_DOCUMENT.equals(paths.get(2))) {
864            return paths.get(3);
865        }
866        throw new IllegalArgumentException("Invalid URI: " + documentUri);
867    }
868
869    /**
870     * Extract the via {@link Document#COLUMN_DOCUMENT_ID} from the given URI.
871     */
872    public static String getTreeDocumentId(Uri documentUri) {
873        final List<String> paths = documentUri.getPathSegments();
874        if (paths.size() >= 2 && PATH_TREE.equals(paths.get(0))) {
875            return paths.get(1);
876        }
877        throw new IllegalArgumentException("Invalid URI: " + documentUri);
878    }
879
880    /**
881     * Extract the search query from a URI built by
882     * {@link #buildSearchDocumentsUri(String, String, String)}.
883     */
884    public static String getSearchDocumentsQuery(Uri searchDocumentsUri) {
885        return searchDocumentsUri.getQueryParameter(PARAM_QUERY);
886    }
887
888    /** {@hide} */
889    public static Uri setManageMode(Uri uri) {
890        return uri.buildUpon().appendQueryParameter(PARAM_MANAGE, "true").build();
891    }
892
893    /** {@hide} */
894    public static boolean isManageMode(Uri uri) {
895        return uri.getBooleanQueryParameter(PARAM_MANAGE, false);
896    }
897
898    /**
899     * Return thumbnail representing the document at the given URI. Callers are
900     * responsible for their own in-memory caching.
901     *
902     * @param documentUri document to return thumbnail for, which must have
903     *            {@link Document#FLAG_SUPPORTS_THUMBNAIL} set.
904     * @param size optimal thumbnail size desired. A provider may return a
905     *            thumbnail of a different size, but never more than double the
906     *            requested size.
907     * @param signal signal used to indicate if caller is no longer interested
908     *            in the thumbnail.
909     * @return decoded thumbnail, or {@code null} if problem was encountered.
910     * @see DocumentsProvider#openDocumentThumbnail(String, Point,
911     *      android.os.CancellationSignal)
912     */
913    public static Bitmap getDocumentThumbnail(
914            ContentResolver resolver, Uri documentUri, Point size, CancellationSignal signal) {
915        final ContentProviderClient client = resolver.acquireUnstableContentProviderClient(
916                documentUri.getAuthority());
917        try {
918            return getDocumentThumbnail(client, documentUri, size, signal);
919        } catch (Exception e) {
920            if (!(e instanceof OperationCanceledException)) {
921                Log.w(TAG, "Failed to load thumbnail for " + documentUri + ": " + e);
922            }
923            return null;
924        } finally {
925            ContentProviderClient.releaseQuietly(client);
926        }
927    }
928
929    /** {@hide} */
930    public static Bitmap getDocumentThumbnail(
931            ContentProviderClient client, Uri documentUri, Point size, CancellationSignal signal)
932            throws RemoteException, IOException {
933        final Bundle openOpts = new Bundle();
934        openOpts.putParcelable(ContentResolver.EXTRA_SIZE, size);
935
936        AssetFileDescriptor afd = null;
937        Bitmap bitmap = null;
938        try {
939            afd = client.openTypedAssetFileDescriptor(documentUri, "image/*", openOpts, signal);
940
941            final FileDescriptor fd = afd.getFileDescriptor();
942            final long offset = afd.getStartOffset();
943
944            // Try seeking on the returned FD, since it gives us the most
945            // optimal decode path; otherwise fall back to buffering.
946            BufferedInputStream is = null;
947            try {
948                Os.lseek(fd, offset, SEEK_SET);
949            } catch (ErrnoException e) {
950                is = new BufferedInputStream(new FileInputStream(fd), THUMBNAIL_BUFFER_SIZE);
951                is.mark(THUMBNAIL_BUFFER_SIZE);
952            }
953
954            // We requested a rough thumbnail size, but the remote size may have
955            // returned something giant, so defensively scale down as needed.
956            final BitmapFactory.Options opts = new BitmapFactory.Options();
957            opts.inJustDecodeBounds = true;
958            if (is != null) {
959                BitmapFactory.decodeStream(is, null, opts);
960            } else {
961                BitmapFactory.decodeFileDescriptor(fd, null, opts);
962            }
963
964            final int widthSample = opts.outWidth / size.x;
965            final int heightSample = opts.outHeight / size.y;
966
967            opts.inJustDecodeBounds = false;
968            opts.inSampleSize = Math.min(widthSample, heightSample);
969            if (is != null) {
970                is.reset();
971                bitmap = BitmapFactory.decodeStream(is, null, opts);
972            } else {
973                try {
974                    Os.lseek(fd, offset, SEEK_SET);
975                } catch (ErrnoException e) {
976                    e.rethrowAsIOException();
977                }
978                bitmap = BitmapFactory.decodeFileDescriptor(fd, null, opts);
979            }
980
981            // Transform the bitmap if requested. We use a side-channel to
982            // communicate the orientation, since EXIF thumbnails don't contain
983            // the rotation flags of the original image.
984            final Bundle extras = afd.getExtras();
985            final int orientation = (extras != null) ? extras.getInt(EXTRA_ORIENTATION, 0) : 0;
986            if (orientation != 0) {
987                final int width = bitmap.getWidth();
988                final int height = bitmap.getHeight();
989
990                final Matrix m = new Matrix();
991                m.setRotate(orientation, width / 2, height / 2);
992                bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, m, false);
993            }
994        } finally {
995            IoUtils.closeQuietly(afd);
996        }
997
998        return bitmap;
999    }
1000
1001    /**
1002     * Create a new document with given MIME type and display name.
1003     *
1004     * @param parentDocumentUri directory with
1005     *            {@link Document#FLAG_DIR_SUPPORTS_CREATE}
1006     * @param mimeType MIME type of new document
1007     * @param displayName name of new document
1008     * @return newly created document, or {@code null} if failed
1009     */
1010    public static Uri createDocument(ContentResolver resolver, Uri parentDocumentUri,
1011            String mimeType, String displayName) {
1012        final ContentProviderClient client = resolver.acquireUnstableContentProviderClient(
1013                parentDocumentUri.getAuthority());
1014        try {
1015            return createDocument(client, parentDocumentUri, mimeType, displayName);
1016        } catch (Exception e) {
1017            Log.w(TAG, "Failed to create document", e);
1018            return null;
1019        } finally {
1020            ContentProviderClient.releaseQuietly(client);
1021        }
1022    }
1023
1024    /** {@hide} */
1025    public static Uri createDocument(ContentProviderClient client, Uri parentDocumentUri,
1026            String mimeType, String displayName) throws RemoteException {
1027        final Bundle in = new Bundle();
1028        in.putParcelable(DocumentsContract.EXTRA_URI, parentDocumentUri);
1029        in.putString(Document.COLUMN_MIME_TYPE, mimeType);
1030        in.putString(Document.COLUMN_DISPLAY_NAME, displayName);
1031
1032        final Bundle out = client.call(METHOD_CREATE_DOCUMENT, null, in);
1033        return out.getParcelable(DocumentsContract.EXTRA_URI);
1034    }
1035
1036    /** {@hide} */
1037    public static boolean isChildDocument(ContentProviderClient client, Uri parentDocumentUri,
1038            Uri childDocumentUri) throws RemoteException {
1039
1040        final Bundle in = new Bundle();
1041        in.putParcelable(DocumentsContract.EXTRA_URI, parentDocumentUri);
1042        in.putParcelable(DocumentsContract.EXTRA_TARGET_URI, childDocumentUri);
1043
1044        final Bundle out = client.call(METHOD_IS_CHILD_DOCUMENT, null, in);
1045        if (out == null) {
1046            throw new RemoteException("Failed to get a reponse from isChildDocument query.");
1047        }
1048        if (!out.containsKey(DocumentsContract.EXTRA_RESULT)) {
1049            throw new RemoteException("Response did not include result field..");
1050        }
1051        return out.getBoolean(DocumentsContract.EXTRA_RESULT);
1052    }
1053
1054    /**
1055     * Change the display name of an existing document.
1056     * <p>
1057     * If the underlying provider needs to create a new
1058     * {@link Document#COLUMN_DOCUMENT_ID} to represent the updated display
1059     * name, that new document is returned and the original document is no
1060     * longer valid. Otherwise, the original document is returned.
1061     *
1062     * @param documentUri document with {@link Document#FLAG_SUPPORTS_RENAME}
1063     * @param displayName updated name for document
1064     * @return the existing or new document after the rename, or {@code null} if
1065     *         failed.
1066     */
1067    public static Uri renameDocument(ContentResolver resolver, Uri documentUri,
1068            String displayName) {
1069        final ContentProviderClient client = resolver.acquireUnstableContentProviderClient(
1070                documentUri.getAuthority());
1071        try {
1072            return renameDocument(client, documentUri, displayName);
1073        } catch (Exception e) {
1074            Log.w(TAG, "Failed to rename document", e);
1075            return null;
1076        } finally {
1077            ContentProviderClient.releaseQuietly(client);
1078        }
1079    }
1080
1081    /** {@hide} */
1082    public static Uri renameDocument(ContentProviderClient client, Uri documentUri,
1083            String displayName) throws RemoteException {
1084        final Bundle in = new Bundle();
1085        in.putParcelable(DocumentsContract.EXTRA_URI, documentUri);
1086        in.putString(Document.COLUMN_DISPLAY_NAME, displayName);
1087
1088        final Bundle out = client.call(METHOD_RENAME_DOCUMENT, null, in);
1089        final Uri outUri = out.getParcelable(DocumentsContract.EXTRA_URI);
1090        return (outUri != null) ? outUri : documentUri;
1091    }
1092
1093    /**
1094     * Delete the given document.
1095     *
1096     * @param documentUri document with {@link Document#FLAG_SUPPORTS_DELETE}
1097     * @return if the document was deleted successfully.
1098     */
1099    public static boolean deleteDocument(ContentResolver resolver, Uri documentUri) {
1100        final ContentProviderClient client = resolver.acquireUnstableContentProviderClient(
1101                documentUri.getAuthority());
1102        try {
1103            deleteDocument(client, documentUri);
1104            return true;
1105        } catch (Exception e) {
1106            Log.w(TAG, "Failed to delete document", e);
1107            return false;
1108        } finally {
1109            ContentProviderClient.releaseQuietly(client);
1110        }
1111    }
1112
1113    /** {@hide} */
1114    public static void deleteDocument(ContentProviderClient client, Uri documentUri)
1115            throws RemoteException {
1116        final Bundle in = new Bundle();
1117        in.putParcelable(DocumentsContract.EXTRA_URI, documentUri);
1118
1119        client.call(METHOD_DELETE_DOCUMENT, null, in);
1120    }
1121
1122    /**
1123     * Copies the given document.
1124     *
1125     * @param sourceDocumentUri document with {@link Document#FLAG_SUPPORTS_COPY}
1126     * @param targetParentDocumentUri document which will become a parent of the source
1127     *         document's copy.
1128     * @return the copied document, or {@code null} if failed.
1129     * @hide
1130     */
1131    public static Uri copyDocument(ContentResolver resolver, Uri sourceDocumentUri,
1132            Uri targetParentDocumentUri) {
1133        final ContentProviderClient client = resolver.acquireUnstableContentProviderClient(
1134                sourceDocumentUri.getAuthority());
1135        try {
1136            return copyDocument(client, sourceDocumentUri, targetParentDocumentUri);
1137        } catch (Exception e) {
1138            Log.w(TAG, "Failed to copy document", e);
1139            return null;
1140        } finally {
1141            ContentProviderClient.releaseQuietly(client);
1142        }
1143    }
1144
1145    /** {@hide} */
1146    public static Uri copyDocument(ContentProviderClient client, Uri sourceDocumentUri,
1147            Uri targetParentDocumentUri) throws RemoteException {
1148        final Bundle in = new Bundle();
1149        in.putParcelable(DocumentsContract.EXTRA_URI, sourceDocumentUri);
1150        in.putParcelable(DocumentsContract.EXTRA_TARGET_URI, targetParentDocumentUri);
1151
1152        final Bundle out = client.call(METHOD_COPY_DOCUMENT, null, in);
1153        return out.getParcelable(DocumentsContract.EXTRA_URI);
1154    }
1155
1156    /**
1157     * Moves the given document under a new parent.
1158     *
1159     * @param sourceDocumentUri document with {@link Document#FLAG_SUPPORTS_MOVE}
1160     * @param targetParentDocumentUri document which will become a new parent of the source
1161     *         document.
1162     * @return the moved document, or {@code null} if failed.
1163     * @hide
1164     */
1165    public static Uri moveDocument(ContentResolver resolver, Uri sourceDocumentUri,
1166            Uri targetParentDocumentUri) {
1167        final ContentProviderClient client = resolver.acquireUnstableContentProviderClient(
1168                sourceDocumentUri.getAuthority());
1169        try {
1170            return moveDocument(client, sourceDocumentUri, targetParentDocumentUri);
1171        } catch (Exception e) {
1172            Log.w(TAG, "Failed to move document", e);
1173            return null;
1174        } finally {
1175            ContentProviderClient.releaseQuietly(client);
1176        }
1177    }
1178
1179    /** {@hide} */
1180    public static Uri moveDocument(ContentProviderClient client, Uri sourceDocumentUri,
1181            Uri targetParentDocumentUri) throws RemoteException {
1182        final Bundle in = new Bundle();
1183        in.putParcelable(DocumentsContract.EXTRA_URI, sourceDocumentUri);
1184        in.putParcelable(DocumentsContract.EXTRA_TARGET_URI, targetParentDocumentUri);
1185
1186        final Bundle out = client.call(METHOD_MOVE_DOCUMENT, null, in);
1187        return out.getParcelable(DocumentsContract.EXTRA_URI);
1188    }
1189
1190    /**
1191     * Open the given image for thumbnail purposes, using any embedded EXIF
1192     * thumbnail if available, and providing orientation hints from the parent
1193     * image.
1194     *
1195     * @hide
1196     */
1197    public static AssetFileDescriptor openImageThumbnail(File file) throws FileNotFoundException {
1198        final ParcelFileDescriptor pfd = ParcelFileDescriptor.open(
1199                file, ParcelFileDescriptor.MODE_READ_ONLY);
1200        Bundle extras = null;
1201
1202        try {
1203            final ExifInterface exif = new ExifInterface(file.getAbsolutePath());
1204
1205            switch (exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, -1)) {
1206                case ExifInterface.ORIENTATION_ROTATE_90:
1207                    extras = new Bundle(1);
1208                    extras.putInt(EXTRA_ORIENTATION, 90);
1209                    break;
1210                case ExifInterface.ORIENTATION_ROTATE_180:
1211                    extras = new Bundle(1);
1212                    extras.putInt(EXTRA_ORIENTATION, 180);
1213                    break;
1214                case ExifInterface.ORIENTATION_ROTATE_270:
1215                    extras = new Bundle(1);
1216                    extras.putInt(EXTRA_ORIENTATION, 270);
1217                    break;
1218            }
1219
1220            final long[] thumb = exif.getThumbnailRange();
1221            if (thumb != null) {
1222                return new AssetFileDescriptor(pfd, thumb[0], thumb[1], extras);
1223            }
1224        } catch (IOException e) {
1225        }
1226
1227        return new AssetFileDescriptor(pfd, 0, AssetFileDescriptor.UNKNOWN_LENGTH, extras);
1228    }
1229}
1230