blob: 0ee54e650db9302910d08871fb0e71d262b795f7 [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 Sharkeyd82b26b2013-09-02 15:07:28 -070034import android.provider.DocumentsContract.Root;
Jeff Sharkey9dd02622013-09-27 16:44:11 -070035import android.text.format.DateUtils;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070036import android.util.Log;
37
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070038import com.android.documentsui.model.RootInfo;
Jeff Sharkey6ee1dfe2015-10-19 17:46:04 -070039import com.android.internal.annotations.GuardedBy;
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
55public class RecentLoader 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 McKayfefcd702015-08-20 16:19:38 +000083 private final HashMap<RootInfo, RecentTask> 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
92 // TODO: create better transfer of ownership around cursor to ensure its
93 // closed in all edge cases.
94
95 public class RecentTask extends AbstractFuture<Cursor> implements Runnable, Closeable {
96 public final String authority;
97 public final String rootId;
98
99 private Cursor mWithRoot;
100
101 public RecentTask(String authority, String rootId) {
102 this.authority = authority;
103 this.rootId = rootId;
104 }
105
106 @Override
107 public void run() {
108 if (isCancelled()) return;
109
Jeff Sharkeyf63b7772013-10-01 17:57:41 -0700110 try {
111 mQueryPermits.acquire();
112 } catch (InterruptedException e) {
113 return;
114 }
115
116 try {
117 runInternal();
118 } finally {
119 mQueryPermits.release();
120 }
121 }
122
123 public void runInternal() {
Jeff Sharkey3fd11772013-09-30 14:26:27 -0700124 ContentProviderClient client = null;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700125 try {
Jeff Sharkey3fd11772013-09-30 14:26:27 -0700126 client = DocumentsApplication.acquireUnstableProviderOrThrow(
127 getContext().getContentResolver(), authority);
128
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700129 final Uri uri = DocumentsContract.buildRecentDocumentsUri(authority, rootId);
130 final Cursor cursor = client.query(
131 uri, null, null, null, DirectoryLoader.getQuerySortOrder(mSortOrder));
132 mWithRoot = new RootCursorWrapper(authority, rootId, cursor, MAX_DOCS_FROM_ROOT);
Jeff Sharkeyf63b7772013-10-01 17:57:41 -0700133
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700134 } catch (Exception e) {
Jeff Sharkey3fd11772013-09-30 14:26:27 -0700135 Log.w(TAG, "Failed to load " + authority + ", " + rootId, e);
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700136 } finally {
Jeff Sharkey3fd11772013-09-30 14:26:27 -0700137 ContentProviderClient.releaseQuietly(client);
138 }
139
140 set(mWithRoot);
141
142 mFirstPassLatch.countDown();
143 if (mFirstPassDone) {
144 onContentChanged();
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700145 }
146 }
147
148 @Override
149 public void close() throws IOException {
150 IoUtils.closeQuietly(mWithRoot);
151 }
152 }
153
Jeff Sharkey8b997042013-09-19 15:25:56 -0700154 public RecentLoader(Context context, RootsCache roots, State state) {
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700155 super(context);
Jeff Sharkey1c903cc2013-09-02 17:19:40 -0700156 mRoots = roots;
Jeff Sharkey8b997042013-09-19 15:25:56 -0700157 mState = state;
Jeff Sharkeyf63b7772013-10-01 17:57:41 -0700158
159 // Keep clients around on high-RAM devices, since we'd be spinning them
160 // up moments later to fetch thumbnails anyway.
161 final ActivityManager am = (ActivityManager) getContext().getSystemService(
162 Context.ACTIVITY_SERVICE);
163 mQueryPermits = new Semaphore(
164 am.isLowRamDevice() ? MAX_OUTSTANDING_RECENTS_SVELTE : MAX_OUTSTANDING_RECENTS);
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700165 }
166
167 @Override
168 public DirectoryResult loadInBackground() {
Jeff Sharkey6ee1dfe2015-10-19 17:46:04 -0700169 synchronized (mTasks) {
170 return loadInBackgroundLocked();
171 }
172 }
173
174 private DirectoryResult loadInBackgroundLocked() {
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700175 if (mFirstPassLatch == null) {
176 // First time through we kick off all the recent tasks, and wait
177 // around to see if everyone finishes quickly.
178
Jeff Sharkey8b997042013-09-19 15:25:56 -0700179 final Collection<RootInfo> roots = mRoots.getMatchingRootsBlocking(mState);
180 for (RootInfo root : roots) {
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700181 if ((root.flags & Root.FLAG_SUPPORTS_RECENTS) != 0) {
182 final RecentTask task = new RecentTask(root.authority, root.rootId);
183 mTasks.put(root, task);
184 }
185 }
186
187 mFirstPassLatch = new CountDownLatch(mTasks.size());
188 for (RecentTask task : mTasks.values()) {
Jeff Sharkeyf63b7772013-10-01 17:57:41 -0700189 ProviderExecutor.forAuthority(task.authority).execute(task);
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700190 }
191
192 try {
193 mFirstPassLatch.await(MAX_FIRST_PASS_WAIT_MILLIS, TimeUnit.MILLISECONDS);
194 mFirstPassDone = true;
195 } catch (InterruptedException e) {
196 throw new RuntimeException(e);
197 }
198 }
199
Jeff Sharkey9dd02622013-09-27 16:44:11 -0700200 final long rejectBefore = System.currentTimeMillis() - REJECT_OLDER_THAN;
201
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700202 // Collect all finished tasks
Jeff Sharkey3fd11772013-09-30 14:26:27 -0700203 boolean allDone = true;
Steve McKayfefcd702015-08-20 16:19:38 +0000204 List<Cursor> cursors = new ArrayList<>();
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700205 for (RecentTask task : mTasks.values()) {
206 if (task.isDone()) {
207 try {
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700208 final Cursor cursor = task.get();
Jeff Sharkey3fd11772013-09-30 14:26:27 -0700209 if (cursor == null) continue;
210
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700211 final FilteringCursorWrapper filtered = new FilteringCursorWrapper(
Jeff Sharkey9dd02622013-09-27 16:44:11 -0700212 cursor, mState.acceptMimes, RECENT_REJECT_MIMES, rejectBefore) {
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700213 @Override
214 public void close() {
215 // Ignored, since we manage cursor lifecycle internally
216 }
217 };
218 cursors.add(filtered);
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700219 } catch (InterruptedException e) {
220 throw new RuntimeException(e);
221 } catch (ExecutionException e) {
Jeff Sharkey3fd11772013-09-30 14:26:27 -0700222 // We already logged on other side
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700223 }
Jeff Sharkey3fd11772013-09-30 14:26:27 -0700224 } else {
225 allDone = false;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700226 }
227 }
228
Steve McKayfefcd702015-08-20 16:19:38 +0000229 if (DEBUG) {
Jeff Sharkey40457802013-09-21 13:57:33 -0700230 Log.d(TAG, "Found " + cursors.size() + " of " + mTasks.size() + " recent queries done");
Jeff Sharkey40457802013-09-21 13:57:33 -0700231 }
232
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700233 final DirectoryResult result = new DirectoryResult();
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700234 result.sortOrder = SORT_ORDER_LAST_MODIFIED;
235
Jeff Sharkey3fd11772013-09-30 14:26:27 -0700236 final Cursor merged;
237 if (cursors.size() > 0) {
238 merged = new MergeCursor(cursors.toArray(new Cursor[cursors.size()]));
239 } else {
240 // Return something when nobody is ready
241 merged = new MatrixCursor(new String[0]);
242 }
243
Ben Kwab8a5e082015-12-07 13:25:27 -0800244 // Tell the UI if this is an in-progress result. When loading is complete, another update is
245 // sent with EXTRA_LOADING set to false.
246 Bundle extras = new Bundle();
247 extras.putBoolean(DocumentsContract.EXTRA_LOADING, !allDone);
248 merged.setExtras(extras);
Jeff Sharkey9dd02622013-09-27 16:44:11 -0700249
Ben Kwab8a5e082015-12-07 13:25:27 -0800250 result.cursor = merged;
Jeff Sharkey9dd02622013-09-27 16:44:11 -0700251
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700252 return result;
253 }
254
255 @Override
256 public void cancelLoadInBackground() {
257 super.cancelLoadInBackground();
258 }
259
260 @Override
261 public void deliverResult(DirectoryResult result) {
262 if (isReset()) {
263 IoUtils.closeQuietly(result);
264 return;
265 }
266 DirectoryResult oldResult = mResult;
267 mResult = result;
268
269 if (isStarted()) {
270 super.deliverResult(result);
271 }
272
273 if (oldResult != null && oldResult != result) {
274 IoUtils.closeQuietly(oldResult);
275 }
276 }
277
278 @Override
279 protected void onStartLoading() {
280 if (mResult != null) {
281 deliverResult(mResult);
282 }
283 if (takeContentChanged() || mResult == null) {
284 forceLoad();
285 }
286 }
287
288 @Override
289 protected void onStopLoading() {
290 cancelLoad();
291 }
292
293 @Override
294 public void onCanceled(DirectoryResult result) {
295 IoUtils.closeQuietly(result);
296 }
297
298 @Override
299 protected void onReset() {
300 super.onReset();
301
302 // Ensure the loader is stopped
303 onStopLoading();
304
Jeff Sharkey6ee1dfe2015-10-19 17:46:04 -0700305 synchronized (mTasks) {
306 for (RecentTask task : mTasks.values()) {
307 IoUtils.closeQuietly(task);
308 }
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700309 }
310
311 IoUtils.closeQuietly(mResult);
312 mResult = null;
313 }
314}