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