blob: cebc9b05679e6d480bd376689f859130d5d10666 [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 McKayf8a5e082015-09-23 17:21:40 -070019import static com.android.documentsui.Shared.DEBUG;
Steve McKayfefcd702015-08-20 16:19:38 +000020import static com.android.documentsui.Shared.TAG;
Steve McKayf8a5e082015-09-23 17:21:40 -070021import static com.android.documentsui.State.SORT_ORDER_LAST_MODIFIED;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070022
Jeff Sharkey3fd11772013-09-30 14:26:27 -070023import android.app.ActivityManager;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070024import android.content.AsyncTaskLoader;
25import android.content.ContentProviderClient;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070026import android.content.Context;
27import android.database.Cursor;
Jeff Sharkey3fd11772013-09-30 14:26:27 -070028import android.database.MatrixCursor;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070029import android.database.MergeCursor;
30import android.net.Uri;
Jeff Sharkey9dd02622013-09-27 16:44:11 -070031import android.os.Bundle;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070032import android.provider.DocumentsContract;
Jeff Sharkey9656a532013-09-13 13:42:19 -070033import android.provider.DocumentsContract.Document;
Jeff Sharkey9dd02622013-09-27 16:44:11 -070034import android.text.format.DateUtils;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070035import android.util.Log;
36
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070037import com.android.documentsui.model.RootInfo;
Jeff Sharkey6ee1dfe2015-10-19 17:46:04 -070038import com.android.internal.annotations.GuardedBy;
Steve McKay1aeb3952016-02-18 09:48:39 -080039
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070040import com.google.common.util.concurrent.AbstractFuture;
41
42import libcore.io.IoUtils;
43
44import java.io.Closeable;
45import java.io.IOException;
Steve McKayfefcd702015-08-20 16:19:38 +000046import java.util.ArrayList;
Jeff Sharkey8b997042013-09-19 15:25:56 -070047import java.util.Collection;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070048import java.util.HashMap;
49import java.util.List;
50import java.util.concurrent.CountDownLatch;
51import java.util.concurrent.ExecutionException;
Jeff Sharkeyf63b7772013-10-01 17:57:41 -070052import java.util.concurrent.Semaphore;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070053import java.util.concurrent.TimeUnit;
54
Steve McKay1aeb3952016-02-18 09:48:39 -080055public class RecentsLoader extends AsyncTaskLoader<DirectoryResult> {
Jeff Sharkeyf73d81a2013-11-18 17:41:33 -080056 // TODO: clean up cursor ownership so background thread doesn't traverse
57 // previously returned cursors for filtering/sorting; this currently races
58 // with the UI thread.
59
Jeff Sharkey3fd11772013-09-30 14:26:27 -070060 private static final int MAX_OUTSTANDING_RECENTS = 4;
61 private static final int MAX_OUTSTANDING_RECENTS_SVELTE = 2;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070062
63 /**
64 * Time to wait for first pass to complete before returning partial results.
65 */
Jeff Sharkey9dd02622013-09-27 16:44:11 -070066 private static final int MAX_FIRST_PASS_WAIT_MILLIS = 500;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070067
Jeff Sharkey9dd02622013-09-27 16:44:11 -070068 /** Maximum documents from a single root. */
69 private static final int MAX_DOCS_FROM_ROOT = 64;
70
71 /** Ignore documents older than this age. */
72 private static final long REJECT_OLDER_THAN = 45 * DateUtils.DAY_IN_MILLIS;
73
74 /** MIME types that should always be excluded from recents. */
75 private static final String[] RECENT_REJECT_MIMES = new String[] { Document.MIME_TYPE_DIR };
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070076
Jeff Sharkeyf63b7772013-10-01 17:57:41 -070077 private final Semaphore mQueryPermits;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070078
Jeff Sharkey8b997042013-09-19 15:25:56 -070079 private final RootsCache mRoots;
80 private final State mState;
Jeff Sharkey1c903cc2013-09-02 17:19:40 -070081
Jeff Sharkey6ee1dfe2015-10-19 17:46:04 -070082 @GuardedBy("mTasks")
Steve McKay1aeb3952016-02-18 09:48:39 -080083 private final HashMap<RootInfo, RecentsTask> mTasks = new HashMap<>();
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070084
85 private final int mSortOrder = State.SORT_ORDER_LAST_MODIFIED;
86
87 private CountDownLatch mFirstPassLatch;
88 private volatile boolean mFirstPassDone;
89
90 private DirectoryResult mResult;
91
Steve McKay1aeb3952016-02-18 09:48:39 -080092 public RecentsLoader(Context context, RootsCache roots, State state) {
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070093 super(context);
Jeff Sharkey1c903cc2013-09-02 17:19:40 -070094 mRoots = roots;
Jeff Sharkey8b997042013-09-19 15:25:56 -070095 mState = state;
Jeff Sharkeyf63b7772013-10-01 17:57:41 -070096
97 // Keep clients around on high-RAM devices, since we'd be spinning them
98 // up moments later to fetch thumbnails anyway.
99 final ActivityManager am = (ActivityManager) getContext().getSystemService(
100 Context.ACTIVITY_SERVICE);
101 mQueryPermits = new Semaphore(
102 am.isLowRamDevice() ? MAX_OUTSTANDING_RECENTS_SVELTE : MAX_OUTSTANDING_RECENTS);
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700103 }
104
105 @Override
106 public DirectoryResult loadInBackground() {
Jeff Sharkey6ee1dfe2015-10-19 17:46:04 -0700107 synchronized (mTasks) {
108 return loadInBackgroundLocked();
109 }
110 }
111
112 private DirectoryResult loadInBackgroundLocked() {
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700113 if (mFirstPassLatch == null) {
114 // First time through we kick off all the recent tasks, and wait
115 // around to see if everyone finishes quickly.
116
Jeff Sharkey8b997042013-09-19 15:25:56 -0700117 final Collection<RootInfo> roots = mRoots.getMatchingRootsBlocking(mState);
118 for (RootInfo root : roots) {
Steve McKay1aeb3952016-02-18 09:48:39 -0800119 if (root.supportsRecents()) {
120 mTasks.put(root, new RecentsTask(root.authority, root.rootId));
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700121 }
122 }
123
124 mFirstPassLatch = new CountDownLatch(mTasks.size());
Steve McKay1aeb3952016-02-18 09:48:39 -0800125 for (RecentsTask task : mTasks.values()) {
Jeff Sharkeyf63b7772013-10-01 17:57:41 -0700126 ProviderExecutor.forAuthority(task.authority).execute(task);
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700127 }
128
129 try {
130 mFirstPassLatch.await(MAX_FIRST_PASS_WAIT_MILLIS, TimeUnit.MILLISECONDS);
131 mFirstPassDone = true;
132 } catch (InterruptedException e) {
133 throw new RuntimeException(e);
134 }
135 }
136
Jeff Sharkey9dd02622013-09-27 16:44:11 -0700137 final long rejectBefore = System.currentTimeMillis() - REJECT_OLDER_THAN;
138
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700139 // Collect all finished tasks
Jeff Sharkey3fd11772013-09-30 14:26:27 -0700140 boolean allDone = true;
Steve McKayfefcd702015-08-20 16:19:38 +0000141 List<Cursor> cursors = new ArrayList<>();
Steve McKay1aeb3952016-02-18 09:48:39 -0800142 for (RecentsTask task : mTasks.values()) {
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700143 if (task.isDone()) {
144 try {
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700145 final Cursor cursor = task.get();
Jeff Sharkey3fd11772013-09-30 14:26:27 -0700146 if (cursor == null) continue;
147
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700148 final FilteringCursorWrapper filtered = new FilteringCursorWrapper(
Jeff Sharkey9dd02622013-09-27 16:44:11 -0700149 cursor, mState.acceptMimes, RECENT_REJECT_MIMES, rejectBefore) {
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700150 @Override
151 public void close() {
152 // Ignored, since we manage cursor lifecycle internally
153 }
154 };
155 cursors.add(filtered);
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700156 } catch (InterruptedException e) {
157 throw new RuntimeException(e);
158 } catch (ExecutionException e) {
Jeff Sharkey3fd11772013-09-30 14:26:27 -0700159 // We already logged on other side
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700160 }
Jeff Sharkey3fd11772013-09-30 14:26:27 -0700161 } else {
162 allDone = false;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700163 }
164 }
165
Steve McKayfefcd702015-08-20 16:19:38 +0000166 if (DEBUG) {
Jeff Sharkey40457802013-09-21 13:57:33 -0700167 Log.d(TAG, "Found " + cursors.size() + " of " + mTasks.size() + " recent queries done");
Jeff Sharkey40457802013-09-21 13:57:33 -0700168 }
169
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700170 final DirectoryResult result = new DirectoryResult();
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700171 result.sortOrder = SORT_ORDER_LAST_MODIFIED;
172
Jeff Sharkey3fd11772013-09-30 14:26:27 -0700173 final Cursor merged;
174 if (cursors.size() > 0) {
175 merged = new MergeCursor(cursors.toArray(new Cursor[cursors.size()]));
176 } else {
177 // Return something when nobody is ready
178 merged = new MatrixCursor(new String[0]);
179 }
180
Ben Kwab8a5e082015-12-07 13:25:27 -0800181 // Tell the UI if this is an in-progress result. When loading is complete, another update is
182 // sent with EXTRA_LOADING set to false.
183 Bundle extras = new Bundle();
184 extras.putBoolean(DocumentsContract.EXTRA_LOADING, !allDone);
185 merged.setExtras(extras);
Jeff Sharkey9dd02622013-09-27 16:44:11 -0700186
Ben Kwab8a5e082015-12-07 13:25:27 -0800187 result.cursor = merged;
Jeff Sharkey9dd02622013-09-27 16:44:11 -0700188
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700189 return result;
190 }
191
192 @Override
193 public void cancelLoadInBackground() {
194 super.cancelLoadInBackground();
195 }
196
197 @Override
198 public void deliverResult(DirectoryResult result) {
199 if (isReset()) {
200 IoUtils.closeQuietly(result);
201 return;
202 }
203 DirectoryResult oldResult = mResult;
204 mResult = result;
205
206 if (isStarted()) {
207 super.deliverResult(result);
208 }
209
210 if (oldResult != null && oldResult != result) {
211 IoUtils.closeQuietly(oldResult);
212 }
213 }
214
215 @Override
216 protected void onStartLoading() {
217 if (mResult != null) {
218 deliverResult(mResult);
219 }
220 if (takeContentChanged() || mResult == null) {
221 forceLoad();
222 }
223 }
224
225 @Override
226 protected void onStopLoading() {
227 cancelLoad();
228 }
229
230 @Override
231 public void onCanceled(DirectoryResult result) {
232 IoUtils.closeQuietly(result);
233 }
234
235 @Override
236 protected void onReset() {
237 super.onReset();
238
239 // Ensure the loader is stopped
240 onStopLoading();
241
Jeff Sharkey6ee1dfe2015-10-19 17:46:04 -0700242 synchronized (mTasks) {
Steve McKay1aeb3952016-02-18 09:48:39 -0800243 for (RecentsTask task : mTasks.values()) {
Jeff Sharkey6ee1dfe2015-10-19 17:46:04 -0700244 IoUtils.closeQuietly(task);
245 }
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700246 }
247
248 IoUtils.closeQuietly(mResult);
249 mResult = null;
250 }
Steve McKay1aeb3952016-02-18 09:48:39 -0800251
252 // TODO: create better transfer of ownership around cursor to ensure its
253 // closed in all edge cases.
254
255 public class RecentsTask extends AbstractFuture<Cursor> implements Runnable, Closeable {
256 public final String authority;
257 public final String rootId;
258
259 private Cursor mWithRoot;
260
261 public RecentsTask(String authority, String rootId) {
262 this.authority = authority;
263 this.rootId = rootId;
264 }
265
266 @Override
267 public void run() {
268 if (isCancelled()) return;
269
270 try {
271 mQueryPermits.acquire();
272 } catch (InterruptedException e) {
273 return;
274 }
275
276 try {
277 runInternal();
278 } finally {
279 mQueryPermits.release();
280 }
281 }
282
283 public void runInternal() {
284 ContentProviderClient client = null;
285 try {
286 client = DocumentsApplication.acquireUnstableProviderOrThrow(
287 getContext().getContentResolver(), authority);
288
289 final Uri uri = DocumentsContract.buildRecentDocumentsUri(authority, rootId);
290 final Cursor cursor = client.query(
291 uri, null, null, null, DirectoryLoader.getQuerySortOrder(mSortOrder));
292 mWithRoot = new RootCursorWrapper(authority, rootId, cursor, MAX_DOCS_FROM_ROOT);
293
294 } catch (Exception e) {
295 Log.w(TAG, "Failed to load " + authority + ", " + rootId, e);
296 } finally {
297 ContentProviderClient.releaseQuietly(client);
298 }
299
300 set(mWithRoot);
301
302 mFirstPassLatch.countDown();
303 if (mFirstPassDone) {
304 onContentChanged();
305 }
306 }
307
308 @Override
309 public void close() throws IOException {
310 IoUtils.closeQuietly(mWithRoot);
311 }
312 }
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700313}