DocumentsContract.java revision a8057a9dcef71f9b3e0f31e830d750337a4349ba
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 = "Documents";
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    /** {@hide} */
595    public static final String METHOD_CREATE_DOCUMENT = "android:createDocument";
596    /** {@hide} */
597    public static final String METHOD_RENAME_DOCUMENT = "android:renameDocument";
598    /** {@hide} */
599    public static final String METHOD_DELETE_DOCUMENT = "android:deleteDocument";
600    /** {@hide} */
601    public static final String METHOD_COPY_DOCUMENT = "android:copyDocument";
602    /** {@hide} */
603    public static final String METHOD_MOVE_DOCUMENT = "android:moveDocument";
604
605    /** {@hide} */
606    public static final String EXTRA_URI = "uri";
607
608    private static final String PATH_ROOT = "root";
609    private static final String PATH_RECENT = "recent";
610    private static final String PATH_DOCUMENT = "document";
611    private static final String PATH_CHILDREN = "children";
612    private static final String PATH_SEARCH = "search";
613    private static final String PATH_TREE = "tree";
614
615    private static final String PARAM_QUERY = "query";
616    private static final String PARAM_MANAGE = "manage";
617
618    /**
619     * Build URI representing the roots of a document provider. When queried, a
620     * provider will return one or more rows with columns defined by
621     * {@link Root}.
622     *
623     * @see DocumentsProvider#queryRoots(String[])
624     */
625    public static Uri buildRootsUri(String authority) {
626        return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT)
627                .authority(authority).appendPath(PATH_ROOT).build();
628    }
629
630    /**
631     * Build URI representing the given {@link Root#COLUMN_ROOT_ID} in a
632     * document provider.
633     *
634     * @see #getRootId(Uri)
635     */
636    public static Uri buildRootUri(String authority, String rootId) {
637        return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT)
638                .authority(authority).appendPath(PATH_ROOT).appendPath(rootId).build();
639    }
640
641    /**
642     * Build URI representing the recently modified documents of a specific root
643     * in a document provider. When queried, a provider will return zero or more
644     * rows with columns defined by {@link Document}.
645     *
646     * @see DocumentsProvider#queryRecentDocuments(String, String[])
647     * @see #getRootId(Uri)
648     */
649    public static Uri buildRecentDocumentsUri(String authority, String rootId) {
650        return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT)
651                .authority(authority).appendPath(PATH_ROOT).appendPath(rootId)
652                .appendPath(PATH_RECENT).build();
653    }
654
655    /**
656     * Build URI representing access to descendant documents of the given
657     * {@link Document#COLUMN_DOCUMENT_ID}.
658     *
659     * @see #getTreeDocumentId(Uri)
660     */
661    public static Uri buildTreeDocumentUri(String authority, String documentId) {
662        return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT).authority(authority)
663                .appendPath(PATH_TREE).appendPath(documentId).build();
664    }
665
666    /**
667     * Build URI representing the target {@link Document#COLUMN_DOCUMENT_ID} in
668     * a document provider. When queried, a provider will return a single row
669     * with columns defined by {@link Document}.
670     *
671     * @see DocumentsProvider#queryDocument(String, String[])
672     * @see #getDocumentId(Uri)
673     */
674    public static Uri buildDocumentUri(String authority, String documentId) {
675        return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT)
676                .authority(authority).appendPath(PATH_DOCUMENT).appendPath(documentId).build();
677    }
678
679    /**
680     * Build URI representing the target {@link Document#COLUMN_DOCUMENT_ID} in
681     * a document provider. When queried, a provider will return a single row
682     * with columns defined by {@link Document}.
683     * <p>
684     * However, instead of directly accessing the target document, the returned
685     * URI will leverage access granted through a subtree URI, typically
686     * returned by {@link Intent#ACTION_OPEN_DOCUMENT_TREE}. The target document
687     * must be a descendant (child, grandchild, etc) of the subtree.
688     * <p>
689     * This is typically used to access documents under a user-selected
690     * directory tree, since it doesn't require the user to separately confirm
691     * each new document access.
692     *
693     * @param treeUri the subtree to leverage to gain access to the target
694     *            document. The target directory must be a descendant of this
695     *            subtree.
696     * @param documentId the target document, which the caller may not have
697     *            direct access to.
698     * @see Intent#ACTION_OPEN_DOCUMENT_TREE
699     * @see DocumentsProvider#isChildDocument(String, String)
700     * @see #buildDocumentUri(String, String)
701     */
702    public static Uri buildDocumentUriUsingTree(Uri treeUri, String documentId) {
703        return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT)
704                .authority(treeUri.getAuthority()).appendPath(PATH_TREE)
705                .appendPath(getTreeDocumentId(treeUri)).appendPath(PATH_DOCUMENT)
706                .appendPath(documentId).build();
707    }
708
709    /** {@hide} */
710    public static Uri buildDocumentUriMaybeUsingTree(Uri baseUri, String documentId) {
711        if (isTreeUri(baseUri)) {
712            return buildDocumentUriUsingTree(baseUri, documentId);
713        } else {
714            return buildDocumentUri(baseUri.getAuthority(), documentId);
715        }
716    }
717
718    /**
719     * Build URI representing the children of the target directory in a document
720     * provider. When queried, a provider will return zero or more rows with
721     * columns defined by {@link Document}.
722     *
723     * @param parentDocumentId the document to return children for, which must
724     *            be a directory with MIME type of
725     *            {@link Document#MIME_TYPE_DIR}.
726     * @see DocumentsProvider#queryChildDocuments(String, String[], String)
727     * @see #getDocumentId(Uri)
728     */
729    public static Uri buildChildDocumentsUri(String authority, String parentDocumentId) {
730        return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT).authority(authority)
731                .appendPath(PATH_DOCUMENT).appendPath(parentDocumentId).appendPath(PATH_CHILDREN)
732                .build();
733    }
734
735    /**
736     * Build URI representing the children of the target directory in a document
737     * provider. When queried, a provider will return zero or more rows with
738     * columns defined by {@link Document}.
739     * <p>
740     * However, instead of directly accessing the target directory, the returned
741     * URI will leverage access granted through a subtree URI, typically
742     * returned by {@link Intent#ACTION_OPEN_DOCUMENT_TREE}. The target
743     * directory must be a descendant (child, grandchild, etc) of the subtree.
744     * <p>
745     * This is typically used to access documents under a user-selected
746     * directory tree, since it doesn't require the user to separately confirm
747     * each new document access.
748     *
749     * @param treeUri the subtree to leverage to gain access to the target
750     *            document. The target directory must be a descendant of this
751     *            subtree.
752     * @param parentDocumentId the document to return children for, which the
753     *            caller may not have direct access to, and which must be a
754     *            directory with MIME type of {@link Document#MIME_TYPE_DIR}.
755     * @see Intent#ACTION_OPEN_DOCUMENT_TREE
756     * @see DocumentsProvider#isChildDocument(String, String)
757     * @see #buildChildDocumentsUri(String, String)
758     */
759    public static Uri buildChildDocumentsUriUsingTree(Uri treeUri, String parentDocumentId) {
760        return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT)
761                .authority(treeUri.getAuthority()).appendPath(PATH_TREE)
762                .appendPath(getTreeDocumentId(treeUri)).appendPath(PATH_DOCUMENT)
763                .appendPath(parentDocumentId).appendPath(PATH_CHILDREN).build();
764    }
765
766    /**
767     * Build URI representing a search for matching documents under a specific
768     * root in a document provider. When queried, a provider will return zero or
769     * more rows with columns defined by {@link Document}.
770     *
771     * @see DocumentsProvider#querySearchDocuments(String, String, String[])
772     * @see #getRootId(Uri)
773     * @see #getSearchDocumentsQuery(Uri)
774     */
775    public static Uri buildSearchDocumentsUri(
776            String authority, String rootId, String query) {
777        return new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT).authority(authority)
778                .appendPath(PATH_ROOT).appendPath(rootId).appendPath(PATH_SEARCH)
779                .appendQueryParameter(PARAM_QUERY, query).build();
780    }
781
782    /**
783     * Test if the given URI represents a {@link Document} backed by a
784     * {@link DocumentsProvider}.
785     *
786     * @see #buildDocumentUri(String, String)
787     * @see #buildDocumentUriUsingTree(Uri, String)
788     */
789    public static boolean isDocumentUri(Context context, @Nullable Uri uri) {
790        if (isContentUri(uri) && isDocumentsProvider(context, uri.getAuthority())) {
791            final List<String> paths = uri.getPathSegments();
792            if (paths.size() == 2) {
793                return PATH_DOCUMENT.equals(paths.get(0));
794            } else if (paths.size() == 4) {
795                return PATH_TREE.equals(paths.get(0)) && PATH_DOCUMENT.equals(paths.get(2));
796            }
797        }
798        return false;
799    }
800
801    /** {@hide} */
802    public static boolean isRootUri(Context context, @Nullable Uri uri) {
803        if (isContentUri(uri) && isDocumentsProvider(context, uri.getAuthority())) {
804            final List<String> paths = uri.getPathSegments();
805            return (paths.size() == 2 && PATH_ROOT.equals(paths.get(0)));
806        }
807        return false;
808    }
809
810    /** {@hide} */
811    public static boolean isContentUri(@Nullable Uri uri) {
812        return uri != null && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme());
813    }
814
815    /** {@hide} */
816    public static boolean isTreeUri(Uri uri) {
817        final List<String> paths = uri.getPathSegments();
818        return (paths.size() >= 2 && PATH_TREE.equals(paths.get(0)));
819    }
820
821    private static boolean isDocumentsProvider(Context context, String authority) {
822        final Intent intent = new Intent(PROVIDER_INTERFACE);
823        final List<ResolveInfo> infos = context.getPackageManager()
824                .queryIntentContentProviders(intent, 0);
825        for (ResolveInfo info : infos) {
826            if (authority.equals(info.providerInfo.authority)) {
827                return true;
828            }
829        }
830        return false;
831    }
832
833    /**
834     * Extract the {@link Root#COLUMN_ROOT_ID} from the given URI.
835     */
836    public static String getRootId(Uri rootUri) {
837        final List<String> paths = rootUri.getPathSegments();
838        if (paths.size() >= 2 && PATH_ROOT.equals(paths.get(0))) {
839            return paths.get(1);
840        }
841        throw new IllegalArgumentException("Invalid URI: " + rootUri);
842    }
843
844    /**
845     * Extract the {@link Document#COLUMN_DOCUMENT_ID} from the given URI.
846     *
847     * @see #isDocumentUri(Context, Uri)
848     */
849    public static String getDocumentId(Uri documentUri) {
850        final List<String> paths = documentUri.getPathSegments();
851        if (paths.size() >= 2 && PATH_DOCUMENT.equals(paths.get(0))) {
852            return paths.get(1);
853        }
854        if (paths.size() >= 4 && PATH_TREE.equals(paths.get(0))
855                && PATH_DOCUMENT.equals(paths.get(2))) {
856            return paths.get(3);
857        }
858        throw new IllegalArgumentException("Invalid URI: " + documentUri);
859    }
860
861    /**
862     * Extract the via {@link Document#COLUMN_DOCUMENT_ID} from the given URI.
863     */
864    public static String getTreeDocumentId(Uri documentUri) {
865        final List<String> paths = documentUri.getPathSegments();
866        if (paths.size() >= 2 && PATH_TREE.equals(paths.get(0))) {
867            return paths.get(1);
868        }
869        throw new IllegalArgumentException("Invalid URI: " + documentUri);
870    }
871
872    /**
873     * Extract the search query from a URI built by
874     * {@link #buildSearchDocumentsUri(String, String, String)}.
875     */
876    public static String getSearchDocumentsQuery(Uri searchDocumentsUri) {
877        return searchDocumentsUri.getQueryParameter(PARAM_QUERY);
878    }
879
880    /** {@hide} */
881    public static Uri setManageMode(Uri uri) {
882        return uri.buildUpon().appendQueryParameter(PARAM_MANAGE, "true").build();
883    }
884
885    /** {@hide} */
886    public static boolean isManageMode(Uri uri) {
887        return uri.getBooleanQueryParameter(PARAM_MANAGE, false);
888    }
889
890    /**
891     * Return thumbnail representing the document at the given URI. Callers are
892     * responsible for their own in-memory caching.
893     *
894     * @param documentUri document to return thumbnail for, which must have
895     *            {@link Document#FLAG_SUPPORTS_THUMBNAIL} set.
896     * @param size optimal thumbnail size desired. A provider may return a
897     *            thumbnail of a different size, but never more than double the
898     *            requested size.
899     * @param signal signal used to indicate if caller is no longer interested
900     *            in the thumbnail.
901     * @return decoded thumbnail, or {@code null} if problem was encountered.
902     * @see DocumentsProvider#openDocumentThumbnail(String, Point,
903     *      android.os.CancellationSignal)
904     */
905    public static Bitmap getDocumentThumbnail(
906            ContentResolver resolver, Uri documentUri, Point size, CancellationSignal signal) {
907        final ContentProviderClient client = resolver.acquireUnstableContentProviderClient(
908                documentUri.getAuthority());
909        try {
910            return getDocumentThumbnail(client, documentUri, size, signal);
911        } catch (Exception e) {
912            if (!(e instanceof OperationCanceledException)) {
913                Log.w(TAG, "Failed to load thumbnail for " + documentUri + ": " + e);
914            }
915            return null;
916        } finally {
917            ContentProviderClient.releaseQuietly(client);
918        }
919    }
920
921    /** {@hide} */
922    public static Bitmap getDocumentThumbnail(
923            ContentProviderClient client, Uri documentUri, Point size, CancellationSignal signal)
924            throws RemoteException, IOException {
925        final Bundle openOpts = new Bundle();
926        openOpts.putParcelable(ContentResolver.EXTRA_SIZE, size);
927
928        AssetFileDescriptor afd = null;
929        Bitmap bitmap = null;
930        try {
931            afd = client.openTypedAssetFileDescriptor(documentUri, "image/*", openOpts, signal);
932
933            final FileDescriptor fd = afd.getFileDescriptor();
934            final long offset = afd.getStartOffset();
935
936            // Try seeking on the returned FD, since it gives us the most
937            // optimal decode path; otherwise fall back to buffering.
938            BufferedInputStream is = null;
939            try {
940                Os.lseek(fd, offset, SEEK_SET);
941            } catch (ErrnoException e) {
942                is = new BufferedInputStream(new FileInputStream(fd), THUMBNAIL_BUFFER_SIZE);
943                is.mark(THUMBNAIL_BUFFER_SIZE);
944            }
945
946            // We requested a rough thumbnail size, but the remote size may have
947            // returned something giant, so defensively scale down as needed.
948            final BitmapFactory.Options opts = new BitmapFactory.Options();
949            opts.inJustDecodeBounds = true;
950            if (is != null) {
951                BitmapFactory.decodeStream(is, null, opts);
952            } else {
953                BitmapFactory.decodeFileDescriptor(fd, null, opts);
954            }
955
956            final int widthSample = opts.outWidth / size.x;
957            final int heightSample = opts.outHeight / size.y;
958
959            opts.inJustDecodeBounds = false;
960            opts.inSampleSize = Math.min(widthSample, heightSample);
961            if (is != null) {
962                is.reset();
963                bitmap = BitmapFactory.decodeStream(is, null, opts);
964            } else {
965                try {
966                    Os.lseek(fd, offset, SEEK_SET);
967                } catch (ErrnoException e) {
968                    e.rethrowAsIOException();
969                }
970                bitmap = BitmapFactory.decodeFileDescriptor(fd, null, opts);
971            }
972
973            // Transform the bitmap if requested. We use a side-channel to
974            // communicate the orientation, since EXIF thumbnails don't contain
975            // the rotation flags of the original image.
976            final Bundle extras = afd.getExtras();
977            final int orientation = (extras != null) ? extras.getInt(EXTRA_ORIENTATION, 0) : 0;
978            if (orientation != 0) {
979                final int width = bitmap.getWidth();
980                final int height = bitmap.getHeight();
981
982                final Matrix m = new Matrix();
983                m.setRotate(orientation, width / 2, height / 2);
984                bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, m, false);
985            }
986        } finally {
987            IoUtils.closeQuietly(afd);
988        }
989
990        return bitmap;
991    }
992
993    /**
994     * Create a new document with given MIME type and display name.
995     *
996     * @param parentDocumentUri directory with
997     *            {@link Document#FLAG_DIR_SUPPORTS_CREATE}
998     * @param mimeType MIME type of new document
999     * @param displayName name of new document
1000     * @return newly created document, or {@code null} if failed
1001     */
1002    public static Uri createDocument(ContentResolver resolver, Uri parentDocumentUri,
1003            String mimeType, String displayName) {
1004        final ContentProviderClient client = resolver.acquireUnstableContentProviderClient(
1005                parentDocumentUri.getAuthority());
1006        try {
1007            return createDocument(client, parentDocumentUri, mimeType, displayName);
1008        } catch (Exception e) {
1009            Log.w(TAG, "Failed to create document", e);
1010            return null;
1011        } finally {
1012            ContentProviderClient.releaseQuietly(client);
1013        }
1014    }
1015
1016    /** {@hide} */
1017    public static Uri createDocument(ContentProviderClient client, Uri parentDocumentUri,
1018            String mimeType, String displayName) throws RemoteException {
1019        final Bundle in = new Bundle();
1020        in.putParcelable(DocumentsContract.EXTRA_URI, parentDocumentUri);
1021        in.putString(Document.COLUMN_MIME_TYPE, mimeType);
1022        in.putString(Document.COLUMN_DISPLAY_NAME, displayName);
1023
1024        final Bundle out = client.call(METHOD_CREATE_DOCUMENT, null, in);
1025        return out.getParcelable(DocumentsContract.EXTRA_URI);
1026    }
1027
1028    /**
1029     * Change the display name of an existing document.
1030     * <p>
1031     * If the underlying provider needs to create a new
1032     * {@link Document#COLUMN_DOCUMENT_ID} to represent the updated display
1033     * name, that new document is returned and the original document is no
1034     * longer valid. Otherwise, the original document is returned.
1035     *
1036     * @param documentUri document with {@link Document#FLAG_SUPPORTS_RENAME}
1037     * @param displayName updated name for document
1038     * @return the existing or new document after the rename, or {@code null} if
1039     *         failed.
1040     */
1041    public static Uri renameDocument(ContentResolver resolver, Uri documentUri,
1042            String displayName) {
1043        final ContentProviderClient client = resolver.acquireUnstableContentProviderClient(
1044                documentUri.getAuthority());
1045        try {
1046            return renameDocument(client, documentUri, displayName);
1047        } catch (Exception e) {
1048            Log.w(TAG, "Failed to rename document", e);
1049            return null;
1050        } finally {
1051            ContentProviderClient.releaseQuietly(client);
1052        }
1053    }
1054
1055    /** {@hide} */
1056    public static Uri renameDocument(ContentProviderClient client, Uri documentUri,
1057            String displayName) throws RemoteException {
1058        final Bundle in = new Bundle();
1059        in.putParcelable(DocumentsContract.EXTRA_URI, documentUri);
1060        in.putString(Document.COLUMN_DISPLAY_NAME, displayName);
1061
1062        final Bundle out = client.call(METHOD_RENAME_DOCUMENT, null, in);
1063        final Uri outUri = out.getParcelable(DocumentsContract.EXTRA_URI);
1064        return (outUri != null) ? outUri : documentUri;
1065    }
1066
1067    /**
1068     * Delete the given document.
1069     *
1070     * @param documentUri document with {@link Document#FLAG_SUPPORTS_DELETE}
1071     * @return if the document was deleted successfully.
1072     */
1073    public static boolean deleteDocument(ContentResolver resolver, Uri documentUri) {
1074        final ContentProviderClient client = resolver.acquireUnstableContentProviderClient(
1075                documentUri.getAuthority());
1076        try {
1077            deleteDocument(client, documentUri);
1078            return true;
1079        } catch (Exception e) {
1080            Log.w(TAG, "Failed to delete document", e);
1081            return false;
1082        } finally {
1083            ContentProviderClient.releaseQuietly(client);
1084        }
1085    }
1086
1087    /** {@hide} */
1088    public static void deleteDocument(ContentProviderClient client, Uri documentUri)
1089            throws RemoteException {
1090        final Bundle in = new Bundle();
1091        in.putParcelable(DocumentsContract.EXTRA_URI, documentUri);
1092
1093        client.call(METHOD_DELETE_DOCUMENT, null, in);
1094    }
1095
1096    /**
1097     * Copies the given document.
1098     *
1099     * @param sourceDocumentUri document with {@link Document#FLAG_SUPPORTS_COPY}
1100     * @param targetParentDocumentUri document which will become a parent of the source
1101     *         document's copy.
1102     * @return the copied document, or {@code null} if failed.
1103     * @hide
1104     */
1105    public static Uri copyDocument(ContentResolver resolver, Uri sourceDocumentUri,
1106            Uri targetParentDocumentUri) {
1107        final ContentProviderClient client = resolver.acquireUnstableContentProviderClient(
1108                sourceDocumentUri.getAuthority());
1109        try {
1110            return copyDocument(client, sourceDocumentUri, targetParentDocumentUri);
1111        } catch (Exception e) {
1112            Log.w(TAG, "Failed to copy document", e);
1113            return null;
1114        } finally {
1115            ContentProviderClient.releaseQuietly(client);
1116        }
1117    }
1118
1119    /** {@hide} */
1120    public static Uri copyDocument(ContentProviderClient client, Uri sourceDocumentUri,
1121            Uri targetParentDocumentUri) throws RemoteException {
1122        final Bundle in = new Bundle();
1123        in.putParcelable(DocumentsContract.EXTRA_URI, sourceDocumentUri);
1124        in.putParcelable(DocumentsContract.EXTRA_TARGET_URI, targetParentDocumentUri);
1125
1126        final Bundle out = client.call(METHOD_COPY_DOCUMENT, null, in);
1127        return out.getParcelable(DocumentsContract.EXTRA_URI);
1128    }
1129
1130    /**
1131     * Moves the given document under a new parent.
1132     *
1133     * @param sourceDocumentUri document with {@link Document#FLAG_SUPPORTS_MOVE}
1134     * @param targetParentDocumentUri document which will become a new parent of the source
1135     *         document.
1136     * @return the moved document, or {@code null} if failed.
1137     * @hide
1138     */
1139    public static Uri moveDocument(ContentResolver resolver, Uri sourceDocumentUri,
1140            Uri targetParentDocumentUri) {
1141        final ContentProviderClient client = resolver.acquireUnstableContentProviderClient(
1142                sourceDocumentUri.getAuthority());
1143        try {
1144            return moveDocument(client, sourceDocumentUri, targetParentDocumentUri);
1145        } catch (Exception e) {
1146            Log.w(TAG, "Failed to move document", e);
1147            return null;
1148        } finally {
1149            ContentProviderClient.releaseQuietly(client);
1150        }
1151    }
1152
1153    /** {@hide} */
1154    public static Uri moveDocument(ContentProviderClient client, Uri sourceDocumentUri,
1155            Uri targetParentDocumentUri) throws RemoteException {
1156        final Bundle in = new Bundle();
1157        in.putParcelable(DocumentsContract.EXTRA_URI, sourceDocumentUri);
1158        in.putParcelable(DocumentsContract.EXTRA_TARGET_URI, targetParentDocumentUri);
1159
1160        final Bundle out = client.call(METHOD_MOVE_DOCUMENT, null, in);
1161        return out.getParcelable(DocumentsContract.EXTRA_URI);
1162    }
1163
1164    /**
1165     * Open the given image for thumbnail purposes, using any embedded EXIF
1166     * thumbnail if available, and providing orientation hints from the parent
1167     * image.
1168     *
1169     * @hide
1170     */
1171    public static AssetFileDescriptor openImageThumbnail(File file) throws FileNotFoundException {
1172        final ParcelFileDescriptor pfd = ParcelFileDescriptor.open(
1173                file, ParcelFileDescriptor.MODE_READ_ONLY);
1174        Bundle extras = null;
1175
1176        try {
1177            final ExifInterface exif = new ExifInterface(file.getAbsolutePath());
1178
1179            switch (exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, -1)) {
1180                case ExifInterface.ORIENTATION_ROTATE_90:
1181                    extras = new Bundle(1);
1182                    extras.putInt(EXTRA_ORIENTATION, 90);
1183                    break;
1184                case ExifInterface.ORIENTATION_ROTATE_180:
1185                    extras = new Bundle(1);
1186                    extras.putInt(EXTRA_ORIENTATION, 180);
1187                    break;
1188                case ExifInterface.ORIENTATION_ROTATE_270:
1189                    extras = new Bundle(1);
1190                    extras.putInt(EXTRA_ORIENTATION, 270);
1191                    break;
1192            }
1193
1194            final long[] thumb = exif.getThumbnailRange();
1195            if (thumb != null) {
1196                return new AssetFileDescriptor(pfd, thumb[0], thumb[1], extras);
1197            }
1198        } catch (IOException e) {
1199        }
1200
1201        return new AssetFileDescriptor(pfd, 0, AssetFileDescriptor.UNKNOWN_LENGTH, extras);
1202    }
1203}
1204