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