1/*
2 * Copyright (C) 2015 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 com.android.documentsui;
18
19import static com.android.documentsui.Shared.DEBUG;
20import static com.android.documentsui.Shared.MAX_DOCS_IN_INTENT;
21import static com.android.documentsui.model.DocumentInfo.getCursorString;
22
23import android.content.ClipData;
24import android.content.ClipDescription;
25import android.content.ComponentName;
26import android.content.Intent;
27import android.content.pm.PackageManager;
28import android.content.res.Resources;
29import android.database.Cursor;
30import android.net.Uri;
31import android.provider.DocumentsContract;
32import android.provider.DocumentsContract.Document;
33import android.support.annotation.Nullable;
34import android.text.TextUtils;
35import android.util.Log;
36import android.util.Range;
37
38import com.android.documentsui.dirlist.Model;
39import com.android.documentsui.model.DocumentInfo;
40
41import java.util.ArrayList;
42import java.util.List;
43
44/**
45 * Provides support for gather a list of quick-viewable files into a quick view intent.
46 */
47final class QuickViewIntentBuilder {
48
49    private static final String TAG = "QuickViewIntentBuilder";
50
51    private final DocumentInfo mDocument;
52    private final Model mModel;
53
54    private final PackageManager mPkgManager;
55    private final Resources mResources;
56
57    public QuickViewIntentBuilder(
58            PackageManager pkgManager,
59            Resources resources,
60            DocumentInfo doc,
61            Model model) {
62
63        mPkgManager = pkgManager;
64        mResources = resources;
65        mDocument = doc;
66        mModel = model;
67    }
68
69    /**
70     * Builds the intent for quick viewing. Short circuits building if a handler cannot
71     * be resolved; in this case {@code null} is returned.
72     */
73    @Nullable Intent build() {
74        if (DEBUG) Log.d(TAG, "Preparing intent for doc:" + mDocument.documentId);
75
76        String trustedPkg = mResources.getString(R.string.trusted_quick_viewer_package);
77
78        if (!TextUtils.isEmpty(trustedPkg)) {
79            Intent intent = new Intent(Intent.ACTION_QUICK_VIEW);
80            intent.setDataAndType(mDocument.derivedUri, mDocument.mimeType);
81            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
82            intent.setPackage(trustedPkg);
83            if (hasRegisteredHandler(intent)) {
84                final ArrayList<Uri> uris = new ArrayList<Uri>();
85                final int documentLocation = collectViewableUris(uris);
86                final Range<Integer> range = computeSiblingsRange(uris, documentLocation);
87
88                ClipData clipData = null;
89                ClipData.Item item;
90                Uri uri;
91                for (int i = range.getLower(); i <= range.getUpper(); i++) {
92                    uri = uris.get(i);
93                    item = new ClipData.Item(uri);
94                    if (DEBUG) Log.d(TAG, "Including file: " + uri);
95                    if (clipData == null) {
96                        clipData = new ClipData(
97                                "URIs", new String[] { ClipDescription.MIMETYPE_TEXT_URILIST },
98                                item);
99                    } else {
100                        clipData.addItem(item);
101                    }
102                }
103
104                // The documentLocation variable contains an index in "uris". However,
105                // ClipData contains a slice of "uris", so we need to shift the location
106                // so it points to the same Uri.
107                intent.putExtra(Intent.EXTRA_INDEX, documentLocation - range.getLower());
108                intent.setClipData(clipData);
109
110                return intent;
111            } else {
112                Log.e(TAG, "Can't resolve trusted quick view package: " + trustedPkg);
113            }
114        }
115
116        return null;
117    }
118
119    private int collectViewableUris(ArrayList<Uri> uris) {
120        final String[] siblingIds = mModel.getModelIds();
121        uris.ensureCapacity(siblingIds.length);
122
123        int documentLocation = 0;
124        Cursor cursor;
125        String mimeType;
126        String id;
127        String authority;
128        Uri uri;
129
130        // Cursor's are not guaranteed to be immutable. Hence, traverse it only once.
131        for (int i = 0; i < siblingIds.length; i++) {
132            cursor = mModel.getItem(siblingIds[i]);
133
134            if (cursor == null) {
135                if (DEBUG) Log.d(TAG,
136                        "Unable to obtain cursor for sibling document, modelId: "
137                        + siblingIds[i]);
138                continue;
139            }
140
141            mimeType = getCursorString(cursor, Document.COLUMN_MIME_TYPE);
142            if (Document.MIME_TYPE_DIR.equals(mimeType)) {
143                if (DEBUG) Log.d(TAG,
144                        "Skipping directory, not supported by quick view. modelId: "
145                        + siblingIds[i]);
146                continue;
147            }
148
149            id = getCursorString(cursor, Document.COLUMN_DOCUMENT_ID);
150            authority = getCursorString(cursor, RootCursorWrapper.COLUMN_AUTHORITY);
151            uri = DocumentsContract.buildDocumentUri(authority, id);
152
153            uris.add(uri);
154
155            if (id.equals(mDocument.documentId)) {
156                documentLocation = uris.size() - 1;  // Position in "uris", not in the model.
157                if (DEBUG) Log.d(TAG, "Found starting point for QV. " + documentLocation);
158            }
159        }
160
161        return documentLocation;
162    }
163
164    private static Range<Integer> computeSiblingsRange(List<Uri> uris, int documentLocation) {
165        // Restrict number of siblings to avoid hitting the IPC limit.
166        // TODO: Remove this restriction once ClipData can hold an arbitrary number of
167        // items.
168        int firstSibling;
169        int lastSibling;
170        if (documentLocation < uris.size() / 2) {
171            firstSibling = Math.max(0, documentLocation - MAX_DOCS_IN_INTENT / 2);
172            lastSibling = Math.min(uris.size() - 1, firstSibling + MAX_DOCS_IN_INTENT - 1);
173        } else {
174            lastSibling = Math.min(uris.size() - 1, documentLocation + MAX_DOCS_IN_INTENT / 2);
175            firstSibling = Math.max(0, lastSibling - MAX_DOCS_IN_INTENT + 1);
176        }
177
178        if (DEBUG) Log.d(TAG, "Copmuted siblings from index: " + firstSibling
179                + " to: " + lastSibling);
180
181        return new Range(firstSibling, lastSibling);
182    }
183
184    private boolean hasRegisteredHandler(Intent intent) {
185        // Try to resolve the intent. If a matching app isn't installed, it won't resolve.
186        return intent.resolveActivity(mPkgManager) != null;
187    }
188}
189