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