blob: 6ce1896b8a276615a7809fc5c79ea1bcd8ab6bd0 [file] [log] [blame]
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -07001/*
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 com.android.documentsui;
18
Steve McKayd9caa6a2016-09-15 16:36:45 -070019import static com.android.documentsui.base.Shared.DEBUG;
20import static com.android.documentsui.base.Shared.TAG;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070021
Jeff Sharkey3fd11772013-09-30 14:26:27 -070022import android.app.ActivityManager;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070023import android.content.AsyncTaskLoader;
24import android.content.ContentProviderClient;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070025import android.content.Context;
26import android.database.Cursor;
Jeff Sharkey3fd11772013-09-30 14:26:27 -070027import android.database.MatrixCursor;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070028import android.database.MergeCursor;
29import android.net.Uri;
Jeff Sharkey9dd02622013-09-27 16:44:11 -070030import android.os.Bundle;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070031import android.provider.DocumentsContract;
Jeff Sharkey9656a532013-09-13 13:42:19 -070032import android.provider.DocumentsContract.Document;
Jeff Sharkey9dd02622013-09-27 16:44:11 -070033import android.text.format.DateUtils;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070034import android.util.Log;
35
Steve McKayd9caa6a2016-09-15 16:36:45 -070036import com.android.documentsui.base.FilteringCursorWrapper;
Steve McKayd0805062016-09-15 14:30:38 -070037import com.android.documentsui.base.RootInfo;
Steve McKayd9caa6a2016-09-15 16:36:45 -070038import com.android.documentsui.base.State;
39import com.android.documentsui.roots.RootCursorWrapper;
Steve McKay988d8a32016-09-27 09:41:17 -070040import com.android.documentsui.roots.RootsAccess;
Jeff Sharkey6ee1dfe2015-10-19 17:46:04 -070041import com.android.internal.annotations.GuardedBy;
Steve McKay1aeb3952016-02-18 09:48:39 -080042
Ben Lin1427c602016-09-22 14:12:19 -070043import libcore.io.IoUtils;
44
Garfield Tan2010ff72016-09-30 14:55:32 -070045import com.google.common.util.concurrent.AbstractFuture;
46
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070047import java.io.Closeable;
48import java.io.IOException;
Steve McKayfefcd702015-08-20 16:19:38 +000049import java.util.ArrayList;
Jeff Sharkey8b997042013-09-19 15:25:56 -070050import java.util.Collection;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070051import java.util.HashMap;
52import java.util.List;
Ben Lin1427c602016-09-22 14:12:19 -070053import java.util.Map;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070054import java.util.concurrent.CountDownLatch;
55import java.util.concurrent.ExecutionException;
Jeff Sharkeyf63b7772013-10-01 17:57:41 -070056import java.util.concurrent.Semaphore;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070057import java.util.concurrent.TimeUnit;
58
Steve McKay1aeb3952016-02-18 09:48:39 -080059public class RecentsLoader extends AsyncTaskLoader<DirectoryResult> {
Jeff Sharkeyf73d81a2013-11-18 17:41:33 -080060 // TODO: clean up cursor ownership so background thread doesn't traverse
61 // previously returned cursors for filtering/sorting; this currently races
62 // with the UI thread.
63
Jeff Sharkey3fd11772013-09-30 14:26:27 -070064 private static final int MAX_OUTSTANDING_RECENTS = 4;
65 private static final int MAX_OUTSTANDING_RECENTS_SVELTE = 2;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070066
67 /**
68 * Time to wait for first pass to complete before returning partial results.
69 */
Jeff Sharkey9dd02622013-09-27 16:44:11 -070070 private static final int MAX_FIRST_PASS_WAIT_MILLIS = 500;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070071
Jeff Sharkey9dd02622013-09-27 16:44:11 -070072 /** Maximum documents from a single root. */
73 private static final int MAX_DOCS_FROM_ROOT = 64;
74
75 /** Ignore documents older than this age. */
76 private static final long REJECT_OLDER_THAN = 45 * DateUtils.DAY_IN_MILLIS;
77
78 /** MIME types that should always be excluded from recents. */
79 private static final String[] RECENT_REJECT_MIMES = new String[] { Document.MIME_TYPE_DIR };
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070080
Jeff Sharkeyf63b7772013-10-01 17:57:41 -070081 private final Semaphore mQueryPermits;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070082
Steve McKay988d8a32016-09-27 09:41:17 -070083 private final RootsAccess mRoots;
Jeff Sharkey8b997042013-09-19 15:25:56 -070084 private final State mState;
Jeff Sharkey1c903cc2013-09-02 17:19:40 -070085
Jeff Sharkey6ee1dfe2015-10-19 17:46:04 -070086 @GuardedBy("mTasks")
Ben Lin1427c602016-09-22 14:12:19 -070087 /** A authority -> RecentsTask map */
88 private final Map<String, RecentsTask> mTasks = new HashMap<>();
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070089
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070090 private CountDownLatch mFirstPassLatch;
91 private volatile boolean mFirstPassDone;
92
93 private DirectoryResult mResult;
94
Steve McKay988d8a32016-09-27 09:41:17 -070095 public RecentsLoader(Context context, RootsAccess roots, State state) {
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070096 super(context);
Jeff Sharkey1c903cc2013-09-02 17:19:40 -070097 mRoots = roots;
Jeff Sharkey8b997042013-09-19 15:25:56 -070098 mState = state;
Jeff Sharkeyf63b7772013-10-01 17:57:41 -070099
100 // Keep clients around on high-RAM devices, since we'd be spinning them
101 // up moments later to fetch thumbnails anyway.
102 final ActivityManager am = (ActivityManager) getContext().getSystemService(
103 Context.ACTIVITY_SERVICE);
104 mQueryPermits = new Semaphore(
105 am.isLowRamDevice() ? MAX_OUTSTANDING_RECENTS_SVELTE : MAX_OUTSTANDING_RECENTS);
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700106 }
107
108 @Override
109 public DirectoryResult loadInBackground() {
Jeff Sharkey6ee1dfe2015-10-19 17:46:04 -0700110 synchronized (mTasks) {
111 return loadInBackgroundLocked();
112 }
113 }
114
115 private DirectoryResult loadInBackgroundLocked() {
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700116 if (mFirstPassLatch == null) {
117 // First time through we kick off all the recent tasks, and wait
118 // around to see if everyone finishes quickly.
Ben Lin1427c602016-09-22 14:12:19 -0700119 Map<String, List<String>> rootsIndex = indexRecentsRoots();
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700120
Ben Lin1427c602016-09-22 14:12:19 -0700121 for (String authority : rootsIndex.keySet()) {
122 mTasks.put(authority, new RecentsTask(authority, rootsIndex.get(authority)));
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700123 }
124
125 mFirstPassLatch = new CountDownLatch(mTasks.size());
Steve McKay1aeb3952016-02-18 09:48:39 -0800126 for (RecentsTask task : mTasks.values()) {
Jeff Sharkeyf63b7772013-10-01 17:57:41 -0700127 ProviderExecutor.forAuthority(task.authority).execute(task);
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700128 }
129
130 try {
131 mFirstPassLatch.await(MAX_FIRST_PASS_WAIT_MILLIS, TimeUnit.MILLISECONDS);
132 mFirstPassDone = true;
133 } catch (InterruptedException e) {
134 throw new RuntimeException(e);
135 }
136 }
137
Jeff Sharkey9dd02622013-09-27 16:44:11 -0700138 final long rejectBefore = System.currentTimeMillis() - REJECT_OLDER_THAN;
139
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700140 // Collect all finished tasks
Jeff Sharkey3fd11772013-09-30 14:26:27 -0700141 boolean allDone = true;
Ben Lin1427c602016-09-22 14:12:19 -0700142 int totalQuerySize = 0;
Steve McKayfefcd702015-08-20 16:19:38 +0000143 List<Cursor> cursors = new ArrayList<>();
Steve McKay1aeb3952016-02-18 09:48:39 -0800144 for (RecentsTask task : mTasks.values()) {
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700145 if (task.isDone()) {
146 try {
Ben Lin1427c602016-09-22 14:12:19 -0700147 final Cursor[] taskCursors = task.get();
148 if (taskCursors == null || taskCursors.length == 0) continue;
Jeff Sharkey3fd11772013-09-30 14:26:27 -0700149
Ben Lin1427c602016-09-22 14:12:19 -0700150 totalQuerySize += taskCursors.length;
151 for (Cursor cursor : taskCursors) {
152 if (cursor == null) {
153 // It's possible given an authority, some roots fail to return a cursor
154 // after a query.
155 continue;
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700156 }
Ben Lin1427c602016-09-22 14:12:19 -0700157 final FilteringCursorWrapper filtered = new FilteringCursorWrapper(
158 cursor, mState.acceptMimes, RECENT_REJECT_MIMES, rejectBefore) {
159 @Override
160 public void close() {
161 // Ignored, since we manage cursor lifecycle internally
162 }
163 };
164 cursors.add(filtered);
165 }
166
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700167 } catch (InterruptedException e) {
168 throw new RuntimeException(e);
169 } catch (ExecutionException e) {
Jeff Sharkey3fd11772013-09-30 14:26:27 -0700170 // We already logged on other side
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700171 }
Jeff Sharkey3fd11772013-09-30 14:26:27 -0700172 } else {
173 allDone = false;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700174 }
175 }
176
Steve McKayfefcd702015-08-20 16:19:38 +0000177 if (DEBUG) {
Ben Lin1427c602016-09-22 14:12:19 -0700178 Log.d(TAG,
179 "Found " + cursors.size() + " of " + totalQuerySize + " recent queries done");
Jeff Sharkey40457802013-09-21 13:57:33 -0700180 }
181
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700182 final DirectoryResult result = new DirectoryResult();
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700183
Jeff Sharkey3fd11772013-09-30 14:26:27 -0700184 final Cursor merged;
185 if (cursors.size() > 0) {
186 merged = new MergeCursor(cursors.toArray(new Cursor[cursors.size()]));
187 } else {
188 // Return something when nobody is ready
189 merged = new MatrixCursor(new String[0]);
190 }
191
Garfield Tan2010ff72016-09-30 14:55:32 -0700192
193 final Cursor sorted = mState.sortModel.sortCursor(merged);
194
Ben Kwab8a5e082015-12-07 13:25:27 -0800195 // Tell the UI if this is an in-progress result. When loading is complete, another update is
196 // sent with EXTRA_LOADING set to false.
197 Bundle extras = new Bundle();
198 extras.putBoolean(DocumentsContract.EXTRA_LOADING, !allDone);
Garfield Tan2010ff72016-09-30 14:55:32 -0700199 sorted.setExtras(extras);
Jeff Sharkey9dd02622013-09-27 16:44:11 -0700200
Garfield Tan2010ff72016-09-30 14:55:32 -0700201 result.cursor = sorted;
Jeff Sharkey9dd02622013-09-27 16:44:11 -0700202
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700203 return result;
204 }
205
Ben Lin1427c602016-09-22 14:12:19 -0700206 /**
207 * Returns a map of Authority -> rootIds
208 */
209 private Map<String, List<String>> indexRecentsRoots() {
210 final Collection<RootInfo> roots = mRoots.getMatchingRootsBlocking(mState);
211 HashMap<String, List<String>> rootsIndex = new HashMap<>();
212 for (RootInfo root : roots) {
213 if (!root.supportsRecents()) {
214 continue;
215 }
216
217 if (!rootsIndex.containsKey(root.authority)) {
218 rootsIndex.put(root.authority, new ArrayList<>());
219 }
220 rootsIndex.get(root.authority).add(root.rootId);
221 }
222
223 return rootsIndex;
224 }
225
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700226 @Override
227 public void cancelLoadInBackground() {
228 super.cancelLoadInBackground();
229 }
230
231 @Override
232 public void deliverResult(DirectoryResult result) {
233 if (isReset()) {
234 IoUtils.closeQuietly(result);
235 return;
236 }
237 DirectoryResult oldResult = mResult;
238 mResult = result;
239
240 if (isStarted()) {
241 super.deliverResult(result);
242 }
243
244 if (oldResult != null && oldResult != result) {
245 IoUtils.closeQuietly(oldResult);
246 }
247 }
248
249 @Override
250 protected void onStartLoading() {
251 if (mResult != null) {
252 deliverResult(mResult);
253 }
254 if (takeContentChanged() || mResult == null) {
255 forceLoad();
256 }
257 }
258
259 @Override
260 protected void onStopLoading() {
261 cancelLoad();
262 }
263
264 @Override
265 public void onCanceled(DirectoryResult result) {
266 IoUtils.closeQuietly(result);
267 }
268
269 @Override
270 protected void onReset() {
271 super.onReset();
272
273 // Ensure the loader is stopped
274 onStopLoading();
275
Jeff Sharkey6ee1dfe2015-10-19 17:46:04 -0700276 synchronized (mTasks) {
Steve McKay1aeb3952016-02-18 09:48:39 -0800277 for (RecentsTask task : mTasks.values()) {
Jeff Sharkey6ee1dfe2015-10-19 17:46:04 -0700278 IoUtils.closeQuietly(task);
279 }
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700280 }
281
282 IoUtils.closeQuietly(mResult);
283 mResult = null;
284 }
Steve McKay1aeb3952016-02-18 09:48:39 -0800285
286 // TODO: create better transfer of ownership around cursor to ensure its
287 // closed in all edge cases.
288
Ben Lin1427c602016-09-22 14:12:19 -0700289 public class RecentsTask extends AbstractFuture<Cursor[]> implements Runnable, Closeable {
Steve McKay1aeb3952016-02-18 09:48:39 -0800290 public final String authority;
Ben Lin1427c602016-09-22 14:12:19 -0700291 public final List<String> rootIds;
Steve McKay1aeb3952016-02-18 09:48:39 -0800292
Ben Lin1427c602016-09-22 14:12:19 -0700293 private Cursor[] mCursors;
Steve McKay1aeb3952016-02-18 09:48:39 -0800294
Ben Lin1427c602016-09-22 14:12:19 -0700295 public RecentsTask(String authority, List<String> rootIds) {
Steve McKay1aeb3952016-02-18 09:48:39 -0800296 this.authority = authority;
Ben Lin1427c602016-09-22 14:12:19 -0700297 this.rootIds = rootIds;
Steve McKay1aeb3952016-02-18 09:48:39 -0800298 }
299
300 @Override
301 public void run() {
302 if (isCancelled()) return;
303
304 try {
305 mQueryPermits.acquire();
306 } catch (InterruptedException e) {
307 return;
308 }
309
310 try {
311 runInternal();
312 } finally {
313 mQueryPermits.release();
314 }
315 }
316
317 public void runInternal() {
318 ContentProviderClient client = null;
319 try {
320 client = DocumentsApplication.acquireUnstableProviderOrThrow(
321 getContext().getContentResolver(), authority);
322
Ben Lin1427c602016-09-22 14:12:19 -0700323 final Cursor[] res = new Cursor[rootIds.size()];
324 mCursors = new Cursor[rootIds.size()];
325 for (int i = 0; i < rootIds.size(); i++) {
326 final Uri uri = DocumentsContract.buildRecentDocumentsUri(authority,
327 rootIds.get(i));
328 try {
329 res[i] = client.query(
330 uri, null, null, null, mState.sortModel.getDocumentSortQuery());
331 mCursors[i] = new RootCursorWrapper(authority, rootIds.get(i), res[i],
332 MAX_DOCS_FROM_ROOT);
333 } catch (Exception e) {
334 Log.w(TAG, "Failed to load " + authority + ", " + rootIds.get(i), e);
335 }
336 }
Steve McKay1aeb3952016-02-18 09:48:39 -0800337
338 } catch (Exception e) {
Ben Lin1427c602016-09-22 14:12:19 -0700339 Log.w(TAG, "Failed to acquire content resolver for authority: " + authority);
Steve McKay1aeb3952016-02-18 09:48:39 -0800340 } finally {
341 ContentProviderClient.releaseQuietly(client);
342 }
343
Ben Lin1427c602016-09-22 14:12:19 -0700344 set(mCursors);
Steve McKay1aeb3952016-02-18 09:48:39 -0800345
346 mFirstPassLatch.countDown();
347 if (mFirstPassDone) {
348 onContentChanged();
349 }
350 }
351
352 @Override
353 public void close() throws IOException {
Ben Lin1427c602016-09-22 14:12:19 -0700354 for (Cursor cursor : mCursors) {
355 IoUtils.closeQuietly(cursor);
356 }
Steve McKay1aeb3952016-02-18 09:48:39 -0800357 }
358 }
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700359}