blob: 7f00ee23696b0a6f5e8f6fd25ed87ac228d00c52 [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 McKay98f8c5f2017-03-03 13:52:14 -080036import com.android.documentsui.base.Features;
Steve McKayd9caa6a2016-09-15 16:36:45 -070037import com.android.documentsui.base.FilteringCursorWrapper;
Steve McKayd0805062016-09-15 14:30:38 -070038import com.android.documentsui.base.RootInfo;
Steve McKayd9caa6a2016-09-15 16:36:45 -070039import com.android.documentsui.base.State;
Jon Mann9bd40992017-03-24 12:34:34 -070040import com.android.documentsui.roots.ProvidersAccess;
Steve McKayd9caa6a2016-09-15 16:36:45 -070041import com.android.documentsui.roots.RootCursorWrapper;
Jeff Sharkey6ee1dfe2015-10-19 17:46:04 -070042import com.android.internal.annotations.GuardedBy;
Steve McKay1aeb3952016-02-18 09:48:39 -080043
Garfield Tan2010ff72016-09-30 14:55:32 -070044import com.google.common.util.concurrent.AbstractFuture;
45
Steve McKay50b9bae2017-01-17 11:12:08 -080046import libcore.io.IoUtils;
47
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070048import java.io.Closeable;
49import java.io.IOException;
Steve McKayfefcd702015-08-20 16:19:38 +000050import java.util.ArrayList;
Jeff Sharkey8b997042013-09-19 15:25:56 -070051import java.util.Collection;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070052import java.util.HashMap;
53import java.util.List;
Ben Lin1427c602016-09-22 14:12:19 -070054import java.util.Map;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070055import java.util.concurrent.CountDownLatch;
56import java.util.concurrent.ExecutionException;
Jeff Sharkeyf63b7772013-10-01 17:57:41 -070057import java.util.concurrent.Semaphore;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070058import java.util.concurrent.TimeUnit;
59
Steve McKay1aeb3952016-02-18 09:48:39 -080060public class RecentsLoader extends AsyncTaskLoader<DirectoryResult> {
Jeff Sharkeyf73d81a2013-11-18 17:41:33 -080061 // TODO: clean up cursor ownership so background thread doesn't traverse
62 // previously returned cursors for filtering/sorting; this currently races
63 // with the UI thread.
64
Jeff Sharkey3fd11772013-09-30 14:26:27 -070065 private static final int MAX_OUTSTANDING_RECENTS = 4;
66 private static final int MAX_OUTSTANDING_RECENTS_SVELTE = 2;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070067
68 /**
69 * Time to wait for first pass to complete before returning partial results.
70 */
Jeff Sharkey9dd02622013-09-27 16:44:11 -070071 private static final int MAX_FIRST_PASS_WAIT_MILLIS = 500;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070072
Jeff Sharkey9dd02622013-09-27 16:44:11 -070073 /** Maximum documents from a single root. */
74 private static final int MAX_DOCS_FROM_ROOT = 64;
75
76 /** Ignore documents older than this age. */
77 private static final long REJECT_OLDER_THAN = 45 * DateUtils.DAY_IN_MILLIS;
78
79 /** MIME types that should always be excluded from recents. */
80 private static final String[] RECENT_REJECT_MIMES = new String[] { Document.MIME_TYPE_DIR };
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070081
Jeff Sharkeyf63b7772013-10-01 17:57:41 -070082 private final Semaphore mQueryPermits;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070083
Jon Mann9bd40992017-03-24 12:34:34 -070084 private final ProvidersAccess mProviders;
Jeff Sharkey8b997042013-09-19 15:25:56 -070085 private final State mState;
Steve McKay98f8c5f2017-03-03 13:52:14 -080086 private final Features mFeatures;
Jeff Sharkey1c903cc2013-09-02 17:19:40 -070087
Jeff Sharkey6ee1dfe2015-10-19 17:46:04 -070088 @GuardedBy("mTasks")
Ben Lin1427c602016-09-22 14:12:19 -070089 /** A authority -> RecentsTask map */
90 private final Map<String, RecentsTask> mTasks = new HashMap<>();
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070091
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070092 private CountDownLatch mFirstPassLatch;
93 private volatile boolean mFirstPassDone;
94
95 private DirectoryResult mResult;
96
Jon Mann9bd40992017-03-24 12:34:34 -070097 public RecentsLoader(Context context, ProvidersAccess providers, State state, Features features) {
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070098 super(context);
Jon Mann9bd40992017-03-24 12:34:34 -070099 mProviders = providers;
Jeff Sharkey8b997042013-09-19 15:25:56 -0700100 mState = state;
Steve McKay98f8c5f2017-03-03 13:52:14 -0800101 mFeatures = features;
Jeff Sharkeyf63b7772013-10-01 17:57:41 -0700102
103 // Keep clients around on high-RAM devices, since we'd be spinning them
104 // up moments later to fetch thumbnails anyway.
105 final ActivityManager am = (ActivityManager) getContext().getSystemService(
106 Context.ACTIVITY_SERVICE);
107 mQueryPermits = new Semaphore(
108 am.isLowRamDevice() ? MAX_OUTSTANDING_RECENTS_SVELTE : MAX_OUTSTANDING_RECENTS);
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700109 }
110
111 @Override
112 public DirectoryResult loadInBackground() {
Jeff Sharkey6ee1dfe2015-10-19 17:46:04 -0700113 synchronized (mTasks) {
114 return loadInBackgroundLocked();
115 }
116 }
117
118 private DirectoryResult loadInBackgroundLocked() {
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700119 if (mFirstPassLatch == null) {
120 // First time through we kick off all the recent tasks, and wait
121 // around to see if everyone finishes quickly.
Ben Lin1427c602016-09-22 14:12:19 -0700122 Map<String, List<String>> rootsIndex = indexRecentsRoots();
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700123
Ben Lin1427c602016-09-22 14:12:19 -0700124 for (String authority : rootsIndex.keySet()) {
125 mTasks.put(authority, new RecentsTask(authority, rootsIndex.get(authority)));
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700126 }
127
128 mFirstPassLatch = new CountDownLatch(mTasks.size());
Steve McKay1aeb3952016-02-18 09:48:39 -0800129 for (RecentsTask task : mTasks.values()) {
Jeff Sharkeyf63b7772013-10-01 17:57:41 -0700130 ProviderExecutor.forAuthority(task.authority).execute(task);
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700131 }
132
133 try {
134 mFirstPassLatch.await(MAX_FIRST_PASS_WAIT_MILLIS, TimeUnit.MILLISECONDS);
135 mFirstPassDone = true;
136 } catch (InterruptedException e) {
137 throw new RuntimeException(e);
138 }
139 }
140
Jeff Sharkey9dd02622013-09-27 16:44:11 -0700141 final long rejectBefore = System.currentTimeMillis() - REJECT_OLDER_THAN;
142
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700143 // Collect all finished tasks
Jeff Sharkey3fd11772013-09-30 14:26:27 -0700144 boolean allDone = true;
Ben Lin1427c602016-09-22 14:12:19 -0700145 int totalQuerySize = 0;
Garfield Tan2b9578f2016-10-10 15:47:24 -0700146 List<Cursor> cursors = new ArrayList<>(mTasks.size());
Steve McKay1aeb3952016-02-18 09:48:39 -0800147 for (RecentsTask task : mTasks.values()) {
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700148 if (task.isDone()) {
149 try {
Ben Lin1427c602016-09-22 14:12:19 -0700150 final Cursor[] taskCursors = task.get();
151 if (taskCursors == null || taskCursors.length == 0) continue;
Jeff Sharkey3fd11772013-09-30 14:26:27 -0700152
Ben Lin1427c602016-09-22 14:12:19 -0700153 totalQuerySize += taskCursors.length;
154 for (Cursor cursor : taskCursors) {
155 if (cursor == null) {
156 // It's possible given an authority, some roots fail to return a cursor
157 // after a query.
158 continue;
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700159 }
Ben Lin1427c602016-09-22 14:12:19 -0700160 final FilteringCursorWrapper filtered = new FilteringCursorWrapper(
161 cursor, mState.acceptMimes, RECENT_REJECT_MIMES, rejectBefore) {
162 @Override
163 public void close() {
164 // Ignored, since we manage cursor lifecycle internally
165 }
166 };
167 cursors.add(filtered);
168 }
169
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700170 } catch (InterruptedException e) {
171 throw new RuntimeException(e);
172 } catch (ExecutionException e) {
Jeff Sharkey3fd11772013-09-30 14:26:27 -0700173 // We already logged on other side
Garfield Tan2b9578f2016-10-10 15:47:24 -0700174 } catch (Exception e) {
175 // Catch exceptions thrown when we read the cursor.
176 Log.e(TAG, "Failed to query Recents for authority: " + task.authority
177 + ". Skip this authority in Recents.", e);
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700178 }
Jeff Sharkey3fd11772013-09-30 14:26:27 -0700179 } else {
180 allDone = false;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700181 }
182 }
183
Steve McKayfefcd702015-08-20 16:19:38 +0000184 if (DEBUG) {
Ben Lin1427c602016-09-22 14:12:19 -0700185 Log.d(TAG,
186 "Found " + cursors.size() + " of " + totalQuerySize + " recent queries done");
Jeff Sharkey40457802013-09-21 13:57:33 -0700187 }
188
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700189 final DirectoryResult result = new DirectoryResult();
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700190
Jeff Sharkey3fd11772013-09-30 14:26:27 -0700191 final Cursor merged;
192 if (cursors.size() > 0) {
193 merged = new MergeCursor(cursors.toArray(new Cursor[cursors.size()]));
194 } else {
195 // Return something when nobody is ready
196 merged = new MatrixCursor(new String[0]);
197 }
198
Garfield Tan2010ff72016-09-30 14:55:32 -0700199 final Cursor sorted = mState.sortModel.sortCursor(merged);
200
Ben Kwab8a5e082015-12-07 13:25:27 -0800201 // Tell the UI if this is an in-progress result. When loading is complete, another update is
202 // sent with EXTRA_LOADING set to false.
203 Bundle extras = new Bundle();
204 extras.putBoolean(DocumentsContract.EXTRA_LOADING, !allDone);
Garfield Tan2010ff72016-09-30 14:55:32 -0700205 sorted.setExtras(extras);
Jeff Sharkey9dd02622013-09-27 16:44:11 -0700206
Garfield Tan2010ff72016-09-30 14:55:32 -0700207 result.cursor = sorted;
Jeff Sharkey9dd02622013-09-27 16:44:11 -0700208
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700209 return result;
210 }
211
Ben Lin1427c602016-09-22 14:12:19 -0700212 /**
213 * Returns a map of Authority -> rootIds
214 */
215 private Map<String, List<String>> indexRecentsRoots() {
Jon Mann9bd40992017-03-24 12:34:34 -0700216 final Collection<RootInfo> roots = mProviders.getMatchingRootsBlocking(mState);
Ben Lin1427c602016-09-22 14:12:19 -0700217 HashMap<String, List<String>> rootsIndex = new HashMap<>();
218 for (RootInfo root : roots) {
219 if (!root.supportsRecents()) {
220 continue;
221 }
222
223 if (!rootsIndex.containsKey(root.authority)) {
224 rootsIndex.put(root.authority, new ArrayList<>());
225 }
226 rootsIndex.get(root.authority).add(root.rootId);
227 }
228
229 return rootsIndex;
230 }
231
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700232 @Override
233 public void cancelLoadInBackground() {
234 super.cancelLoadInBackground();
235 }
236
237 @Override
238 public void deliverResult(DirectoryResult result) {
239 if (isReset()) {
240 IoUtils.closeQuietly(result);
241 return;
242 }
243 DirectoryResult oldResult = mResult;
244 mResult = result;
245
246 if (isStarted()) {
247 super.deliverResult(result);
248 }
249
250 if (oldResult != null && oldResult != result) {
251 IoUtils.closeQuietly(oldResult);
252 }
253 }
254
255 @Override
256 protected void onStartLoading() {
257 if (mResult != null) {
258 deliverResult(mResult);
259 }
260 if (takeContentChanged() || mResult == null) {
261 forceLoad();
262 }
263 }
264
265 @Override
266 protected void onStopLoading() {
267 cancelLoad();
268 }
269
270 @Override
271 public void onCanceled(DirectoryResult result) {
272 IoUtils.closeQuietly(result);
273 }
274
275 @Override
276 protected void onReset() {
277 super.onReset();
278
279 // Ensure the loader is stopped
280 onStopLoading();
281
Jeff Sharkey6ee1dfe2015-10-19 17:46:04 -0700282 synchronized (mTasks) {
Steve McKay1aeb3952016-02-18 09:48:39 -0800283 for (RecentsTask task : mTasks.values()) {
Jeff Sharkey6ee1dfe2015-10-19 17:46:04 -0700284 IoUtils.closeQuietly(task);
285 }
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700286 }
287
288 IoUtils.closeQuietly(mResult);
289 mResult = null;
290 }
Steve McKay1aeb3952016-02-18 09:48:39 -0800291
292 // TODO: create better transfer of ownership around cursor to ensure its
293 // closed in all edge cases.
294
Ben Lin1427c602016-09-22 14:12:19 -0700295 public class RecentsTask extends AbstractFuture<Cursor[]> implements Runnable, Closeable {
Steve McKay1aeb3952016-02-18 09:48:39 -0800296 public final String authority;
Ben Lin1427c602016-09-22 14:12:19 -0700297 public final List<String> rootIds;
Steve McKay1aeb3952016-02-18 09:48:39 -0800298
Ben Lin1427c602016-09-22 14:12:19 -0700299 private Cursor[] mCursors;
Jon Mann9f404c22017-03-22 18:49:56 -0700300 private boolean mIsClosed = false;
Steve McKay1aeb3952016-02-18 09:48:39 -0800301
Ben Lin1427c602016-09-22 14:12:19 -0700302 public RecentsTask(String authority, List<String> rootIds) {
Steve McKay1aeb3952016-02-18 09:48:39 -0800303 this.authority = authority;
Ben Lin1427c602016-09-22 14:12:19 -0700304 this.rootIds = rootIds;
Steve McKay1aeb3952016-02-18 09:48:39 -0800305 }
306
307 @Override
308 public void run() {
309 if (isCancelled()) return;
310
311 try {
312 mQueryPermits.acquire();
313 } catch (InterruptedException e) {
314 return;
315 }
316
317 try {
318 runInternal();
319 } finally {
320 mQueryPermits.release();
321 }
322 }
323
Jon Mann9f404c22017-03-22 18:49:56 -0700324 public synchronized void runInternal() {
325 if (mIsClosed) {
326 return;
327 }
328
Steve McKay1aeb3952016-02-18 09:48:39 -0800329 ContentProviderClient client = null;
330 try {
331 client = DocumentsApplication.acquireUnstableProviderOrThrow(
332 getContext().getContentResolver(), authority);
333
Ben Lin1427c602016-09-22 14:12:19 -0700334 final Cursor[] res = new Cursor[rootIds.size()];
335 mCursors = new Cursor[rootIds.size()];
336 for (int i = 0; i < rootIds.size(); i++) {
Steve McKay50b9bae2017-01-17 11:12:08 -0800337 final Uri uri =
338 DocumentsContract.buildRecentDocumentsUri(authority, rootIds.get(i));
Ben Lin1427c602016-09-22 14:12:19 -0700339 try {
Steve McKay98f8c5f2017-03-03 13:52:14 -0800340 if (mFeatures.isContentPagingEnabled()) {
Steve McKayf208d842017-02-27 12:57:58 -0800341 final Bundle queryArgs = new Bundle();
342 mState.sortModel.addQuerySortArgs(queryArgs);
343 res[i] = client.query(uri, null, queryArgs, null);
344 } else {
345 res[i] = client.query(
346 uri, null, null, null, mState.sortModel.getDocumentSortQuery());
347 }
Ben Lin1427c602016-09-22 14:12:19 -0700348 mCursors[i] = new RootCursorWrapper(authority, rootIds.get(i), res[i],
349 MAX_DOCS_FROM_ROOT);
350 } catch (Exception e) {
351 Log.w(TAG, "Failed to load " + authority + ", " + rootIds.get(i), e);
352 }
353 }
Steve McKay1aeb3952016-02-18 09:48:39 -0800354
355 } catch (Exception e) {
Ben Lin1427c602016-09-22 14:12:19 -0700356 Log.w(TAG, "Failed to acquire content resolver for authority: " + authority);
Steve McKay1aeb3952016-02-18 09:48:39 -0800357 } finally {
358 ContentProviderClient.releaseQuietly(client);
359 }
360
Ben Lin1427c602016-09-22 14:12:19 -0700361 set(mCursors);
Steve McKay1aeb3952016-02-18 09:48:39 -0800362
363 mFirstPassLatch.countDown();
364 if (mFirstPassDone) {
365 onContentChanged();
366 }
367 }
368
369 @Override
Jon Mann9f404c22017-03-22 18:49:56 -0700370 public synchronized void close() throws IOException {
371 if (mCursors == null) {
372 return;
373 }
374
Ben Lin1427c602016-09-22 14:12:19 -0700375 for (Cursor cursor : mCursors) {
376 IoUtils.closeQuietly(cursor);
377 }
Jon Mann9f404c22017-03-22 18:49:56 -0700378
379 mIsClosed = true;
Steve McKay1aeb3952016-02-18 09:48:39 -0800380 }
381 }
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700382}