blob: 490f94eacfc225fe36ff9b8e170b46c5055e341e [file] [log] [blame]
Ben Kwa0497da82015-11-30 23:00:02 -08001/*
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.dirlist;
18
19import static com.android.documentsui.Shared.DEBUG;
Ben Kwab8a5e082015-12-07 13:25:27 -080020import static com.android.documentsui.State.SORT_ORDER_DISPLAY_NAME;
21import static com.android.documentsui.State.SORT_ORDER_LAST_MODIFIED;
22import static com.android.documentsui.State.SORT_ORDER_SIZE;
23import static com.android.documentsui.model.DocumentInfo.getCursorLong;
Ben Kwa0497da82015-11-30 23:00:02 -080024import static com.android.documentsui.model.DocumentInfo.getCursorString;
25import static com.android.internal.util.Preconditions.checkNotNull;
Ben Kwa0497da82015-11-30 23:00:02 -080026
Ben Kwa0497da82015-11-30 23:00:02 -080027import android.database.Cursor;
Ben Kwa0497da82015-11-30 23:00:02 -080028import android.os.Bundle;
29import android.os.Looper;
30import android.provider.DocumentsContract;
31import android.provider.DocumentsContract.Document;
32import android.support.annotation.Nullable;
33import android.support.annotation.VisibleForTesting;
Ben Kwa0497da82015-11-30 23:00:02 -080034import android.util.Log;
Ben Kwa0497da82015-11-30 23:00:02 -080035
Ben Kwab8a5e082015-12-07 13:25:27 -080036import com.android.documentsui.BaseActivity.SiblingProvider;
Ben Kwa0497da82015-11-30 23:00:02 -080037import com.android.documentsui.DirectoryResult;
Ben Kwa0497da82015-11-30 23:00:02 -080038import com.android.documentsui.RootCursorWrapper;
39import com.android.documentsui.dirlist.MultiSelectManager.Selection;
40import com.android.documentsui.model.DocumentInfo;
Ben Kwa0497da82015-11-30 23:00:02 -080041
42import java.util.ArrayList;
Ben Kwa0497da82015-11-30 23:00:02 -080043import java.util.HashMap;
44import java.util.List;
Ben Kwab8a5e082015-12-07 13:25:27 -080045import java.util.Map;
Ben Kwa0497da82015-11-30 23:00:02 -080046
47/**
48 * The data model for the current loaded directory.
49 */
50@VisibleForTesting
Ben Kwab8a5e082015-12-07 13:25:27 -080051public class Model implements SiblingProvider {
Ben Kwa0497da82015-11-30 23:00:02 -080052 private static final String TAG = "Model";
Ben Kwab8a5e082015-12-07 13:25:27 -080053
Ben Kwa0497da82015-11-30 23:00:02 -080054 private boolean mIsLoading;
Ben Kwad72a1da2015-12-01 19:56:57 -080055 private List<UpdateListener> mUpdateListeners = new ArrayList<>();
Ben Kwa0497da82015-11-30 23:00:02 -080056 @Nullable private Cursor mCursor;
Ben Kwab8a5e082015-12-07 13:25:27 -080057 private int mCursorCount;
58 /** Maps Model ID to cursor positions, for looking up items by Model ID. */
59 private Map<String, Integer> mPositions = new HashMap<>();
60 /**
61 * A sorted array of model IDs for the files currently in the Model. Sort order is determined
62 * by {@link #mSortOrder}
63 */
64 private List<String> mIds = new ArrayList<>();
65 private int mSortOrder = SORT_ORDER_DISPLAY_NAME;
66
Ben Kwa0497da82015-11-30 23:00:02 -080067 @Nullable String info;
68 @Nullable String error;
Ben Kwa0497da82015-11-30 23:00:02 -080069
Ben Kwad72a1da2015-12-01 19:56:57 -080070 /**
Ben Kwab8a5e082015-12-07 13:25:27 -080071 * Generates a Model ID for a cursor entry that refers to a document. The Model ID is a unique
72 * string that can be used to identify the document referred to by the cursor.
Ben Kwad72a1da2015-12-01 19:56:57 -080073 *
74 * @param c A cursor that refers to a document.
75 */
Ben Kwab8a5e082015-12-07 13:25:27 -080076 private static String createModelId(Cursor c) {
77 // TODO: Maybe more efficient to use just the document ID, in cases where there is only one
78 // authority (which should be the majority of cases).
Steve McKaye9104032016-01-05 12:53:35 -080079 return createModelId(
80 getCursorString(c, RootCursorWrapper.COLUMN_AUTHORITY),
81 getCursorString(c, Document.COLUMN_DOCUMENT_ID));
82 }
83
84 /**
85 * Generates a Model ID for a cursor entry that refers to a document. The Model ID is a unique
86 * string that can be used to identify the document referred to by the cursor.
87 *
88 * @param c A cursor that refers to a document.
89 */
90 static String createModelId(String authority, String docId) {
91 return authority + "|" + docId;
Ben Kwad72a1da2015-12-01 19:56:57 -080092 }
93
Ben Kwad72a1da2015-12-01 19:56:57 -080094 private void notifyUpdateListeners() {
95 for (UpdateListener listener: mUpdateListeners) {
96 listener.onModelUpdate(this);
97 }
98 }
99
100 private void notifyUpdateListeners(Exception e) {
101 for (UpdateListener listener: mUpdateListeners) {
102 listener.onModelUpdateFailed(e);
103 }
104 }
105
Ben Kwa0497da82015-11-30 23:00:02 -0800106 void update(DirectoryResult result) {
107 if (DEBUG) Log.i(TAG, "Updating model with new result set.");
108
109 if (result == null) {
110 mCursor = null;
111 mCursorCount = 0;
Ben Kwab8a5e082015-12-07 13:25:27 -0800112 mIds.clear();
113 mPositions.clear();
Ben Kwa0497da82015-11-30 23:00:02 -0800114 info = null;
115 error = null;
116 mIsLoading = false;
Ben Kwad72a1da2015-12-01 19:56:57 -0800117 notifyUpdateListeners();
Ben Kwa0497da82015-11-30 23:00:02 -0800118 return;
119 }
120
121 if (result.exception != null) {
122 Log.e(TAG, "Error while loading directory contents", result.exception);
Ben Kwad72a1da2015-12-01 19:56:57 -0800123 notifyUpdateListeners(result.exception);
Ben Kwa0497da82015-11-30 23:00:02 -0800124 return;
125 }
126
127 mCursor = result.cursor;
128 mCursorCount = mCursor.getCount();
Ben Kwab8a5e082015-12-07 13:25:27 -0800129 mSortOrder = result.sortOrder;
Ben Kwa0497da82015-11-30 23:00:02 -0800130
Ben Kwab8a5e082015-12-07 13:25:27 -0800131 updateModelData();
Ben Kwa0497da82015-11-30 23:00:02 -0800132
133 final Bundle extras = mCursor.getExtras();
134 if (extras != null) {
135 info = extras.getString(DocumentsContract.EXTRA_INFO);
136 error = extras.getString(DocumentsContract.EXTRA_ERROR);
137 mIsLoading = extras.getBoolean(DocumentsContract.EXTRA_LOADING, false);
138 }
139
Ben Kwad72a1da2015-12-01 19:56:57 -0800140 notifyUpdateListeners();
Ben Kwa0497da82015-11-30 23:00:02 -0800141 }
142
Ben Kwad72a1da2015-12-01 19:56:57 -0800143 @VisibleForTesting
Ben Kwa0497da82015-11-30 23:00:02 -0800144 int getItemCount() {
Ben Kwada858bf2015-12-09 14:33:49 -0800145 return mCursorCount;
Ben Kwa0497da82015-11-30 23:00:02 -0800146 }
147
148 /**
Ben Kwab8a5e082015-12-07 13:25:27 -0800149 * Scan over the incoming cursor data, generate Model IDs for each row, and sort the IDs
150 * according to the current sort order.
Ben Kwa0497da82015-11-30 23:00:02 -0800151 */
Ben Kwab8a5e082015-12-07 13:25:27 -0800152 private void updateModelData() {
153 int[] positions = new int[mCursorCount];
154 mIds.clear();
Ben Kwa6280de02015-12-16 19:42:08 -0800155 String[] stringValues = new String[mCursorCount];
156 long[] longValues = null;
Ben Kwab8a5e082015-12-07 13:25:27 -0800157
Ben Kwa6280de02015-12-16 19:42:08 -0800158 if (mSortOrder == SORT_ORDER_LAST_MODIFIED || mSortOrder == SORT_ORDER_SIZE) {
159 longValues = new long[mCursorCount];
Ben Kwab8a5e082015-12-07 13:25:27 -0800160 }
161
Ben Kwa0497da82015-11-30 23:00:02 -0800162 mCursor.moveToPosition(-1);
163 for (int pos = 0; pos < mCursorCount; ++pos) {
164 mCursor.moveToNext();
Ben Kwab8a5e082015-12-07 13:25:27 -0800165 positions[pos] = pos;
166 mIds.add(createModelId(mCursor));
167
168 switch(mSortOrder) {
169 case SORT_ORDER_DISPLAY_NAME:
170 final String mimeType = getCursorString(mCursor, Document.COLUMN_MIME_TYPE);
171 final String displayName = getCursorString(
172 mCursor, Document.COLUMN_DISPLAY_NAME);
173 if (Document.MIME_TYPE_DIR.equals(mimeType)) {
Ben Kwa6280de02015-12-16 19:42:08 -0800174 stringValues[pos] = DocumentInfo.DIR_PREFIX + displayName;
Ben Kwab8a5e082015-12-07 13:25:27 -0800175 } else {
Ben Kwa6280de02015-12-16 19:42:08 -0800176 stringValues[pos] = displayName;
Ben Kwab8a5e082015-12-07 13:25:27 -0800177 }
178 break;
179 case SORT_ORDER_LAST_MODIFIED:
Ben Kwae4338342016-01-08 15:34:47 -0800180 longValues[pos] = getLastModified(mCursor);
Ben Kwa6280de02015-12-16 19:42:08 -0800181 stringValues[pos] = getCursorString(mCursor, Document.COLUMN_MIME_TYPE);
Ben Kwab8a5e082015-12-07 13:25:27 -0800182 break;
183 case SORT_ORDER_SIZE:
Ben Kwa6280de02015-12-16 19:42:08 -0800184 longValues[pos] = getCursorLong(mCursor, Document.COLUMN_SIZE);
185 stringValues[pos] = getCursorString(mCursor, Document.COLUMN_MIME_TYPE);
Ben Kwab8a5e082015-12-07 13:25:27 -0800186 break;
187 }
188 }
189
190 switch (mSortOrder) {
191 case SORT_ORDER_DISPLAY_NAME:
Ben Kwa6280de02015-12-16 19:42:08 -0800192 binarySort(stringValues, positions, mIds);
Ben Kwab8a5e082015-12-07 13:25:27 -0800193 break;
194 case SORT_ORDER_LAST_MODIFIED:
195 case SORT_ORDER_SIZE:
Ben Kwa6280de02015-12-16 19:42:08 -0800196 binarySort(longValues, stringValues, positions, mIds);
Ben Kwab8a5e082015-12-07 13:25:27 -0800197 break;
198 }
199
200 // Populate the positions.
201 mPositions.clear();
202 for (int i = 0; i < mCursorCount; ++i) {
203 mPositions.put(mIds.get(i), positions[i]);
204 }
205 }
206
207 /**
Ben Kwa6280de02015-12-16 19:42:08 -0800208 * Sorts model data. Takes three columns of index-corresponded data. The first column is the
209 * sort key. Rows are sorted in ascending alphabetical order on the sort key. This code is based
210 * on TimSort.binarySort().
211 *
212 * @param sortKey Data is sorted in ascending alphabetical order.
213 * @param positions Cursor positions to be sorted.
214 * @param ids Model IDs to be sorted.
Ben Kwab8a5e082015-12-07 13:25:27 -0800215 */
Ben Kwa6280de02015-12-16 19:42:08 -0800216 private static void binarySort(String[] sortKey, int[] positions, List<String> ids) {
Ben Kwab8a5e082015-12-07 13:25:27 -0800217 final int count = positions.length;
218 for (int start = 1; start < count; start++) {
219 final int pivotPosition = positions[start];
Ben Kwa6280de02015-12-16 19:42:08 -0800220 final String pivotValue = sortKey[start];
Ben Kwab8a5e082015-12-07 13:25:27 -0800221 final String pivotId = ids.get(start);
222
223 int left = 0;
224 int right = start;
225
226 while (left < right) {
227 int mid = (left + right) >>> 1;
228
229 final String lhs = pivotValue;
Ben Kwa6280de02015-12-16 19:42:08 -0800230 final String rhs = sortKey[mid];
Ben Kwab8a5e082015-12-07 13:25:27 -0800231 final int compare = DocumentInfo.compareToIgnoreCaseNullable(lhs, rhs);
232
233 if (compare < 0) {
234 right = mid;
235 } else {
236 left = mid + 1;
237 }
238 }
239
240 int n = start - left;
241 switch (n) {
242 case 2:
243 positions[left + 2] = positions[left + 1];
Ben Kwa6280de02015-12-16 19:42:08 -0800244 sortKey[left + 2] = sortKey[left + 1];
Ben Kwab8a5e082015-12-07 13:25:27 -0800245 ids.set(left + 2, ids.get(left + 1));
246 case 1:
247 positions[left + 1] = positions[left];
Ben Kwa6280de02015-12-16 19:42:08 -0800248 sortKey[left + 1] = sortKey[left];
Ben Kwab8a5e082015-12-07 13:25:27 -0800249 ids.set(left + 1, ids.get(left));
250 break;
251 default:
252 System.arraycopy(positions, left, positions, left + 1, n);
Ben Kwa6280de02015-12-16 19:42:08 -0800253 System.arraycopy(sortKey, left, sortKey, left + 1, n);
Ben Kwab8a5e082015-12-07 13:25:27 -0800254 for (int i = n; i >= 1; --i) {
255 ids.set(left + i, ids.get(left + i - 1));
256 }
257 }
258
259 positions[left] = pivotPosition;
Ben Kwa6280de02015-12-16 19:42:08 -0800260 sortKey[left] = pivotValue;
Ben Kwab8a5e082015-12-07 13:25:27 -0800261 ids.set(left, pivotId);
262 }
263 }
264
265 /**
Ben Kwa6280de02015-12-16 19:42:08 -0800266 * Sorts model data. Takes four columns of index-corresponded data. The first column is the sort
267 * key, and the second is an array of mime types. The rows are first bucketed by mime type
268 * (directories vs documents) and then each bucket is sorted independently in descending
269 * numerical order on the sort key. This code is based on TimSort.binarySort().
270 *
271 * @param sortKey Data is sorted in descending numerical order.
272 * @param mimeTypes Corresponding mime types. Directories will be sorted ahead of documents.
273 * @param positions Cursor positions to be sorted.
274 * @param ids Model IDs to be sorted.
Ben Kwab8a5e082015-12-07 13:25:27 -0800275 */
Ben Kwa6280de02015-12-16 19:42:08 -0800276 private static void binarySort(
277 long[] sortKey, String[] mimeTypes, int[] positions, List<String> ids) {
Ben Kwab8a5e082015-12-07 13:25:27 -0800278 final int count = positions.length;
279 for (int start = 1; start < count; start++) {
280 final int pivotPosition = positions[start];
Ben Kwa6280de02015-12-16 19:42:08 -0800281 final long pivotValue = sortKey[start];
282 final String pivotMime = mimeTypes[start];
Ben Kwab8a5e082015-12-07 13:25:27 -0800283 final String pivotId = ids.get(start);
284
285 int left = 0;
286 int right = start;
287
288 while (left < right) {
Ben Kwa6280de02015-12-16 19:42:08 -0800289 int mid = ((left + right) >>> 1);
Ben Kwab8a5e082015-12-07 13:25:27 -0800290
Ben Kwa6280de02015-12-16 19:42:08 -0800291 // First bucket by mime type. Directories always go in front.
292 int compare = 0;
293 final boolean lhsIsDir = Document.MIME_TYPE_DIR.equals(pivotMime);
294 final boolean rhsIsDir = Document.MIME_TYPE_DIR.equals(mimeTypes[mid]);
295 if (lhsIsDir && !rhsIsDir) {
296 compare = -1;
297 } else if (!lhsIsDir && rhsIsDir) {
298 compare = 1;
299 } else {
300 final long lhs = pivotValue;
301 final long rhs = sortKey[mid];
Ben Kwae4338342016-01-08 15:34:47 -0800302 // Sort in descending numerical order. This matches legacy behaviour, which
303 // yields largest or most recent items on top.
Ben Kwa6280de02015-12-16 19:42:08 -0800304 compare = -Long.compare(lhs, rhs);
305 }
Ben Kwab8a5e082015-12-07 13:25:27 -0800306
Ben Kwae4338342016-01-08 15:34:47 -0800307 // If numerical comparison yields a tie, use document ID as a tie breaker. This
308 // will yield stable results even if incoming items are continually shuffling and
309 // have identical numerical sort keys. One common example of this scenario is seen
310 // when sorting a set of active downloads by mod time.
311 if (compare == 0) {
312 compare = pivotId.compareTo(ids.get(mid));
313 }
314
Ben Kwab8a5e082015-12-07 13:25:27 -0800315 if (compare < 0) {
316 right = mid;
317 } else {
318 left = mid + 1;
319 }
320 }
321
322 int n = start - left;
323 switch (n) {
324 case 2:
325 positions[left + 2] = positions[left + 1];
Ben Kwa6280de02015-12-16 19:42:08 -0800326 sortKey[left + 2] = sortKey[left + 1];
327 mimeTypes[left + 2] = mimeTypes[left + 1];
Ben Kwab8a5e082015-12-07 13:25:27 -0800328 ids.set(left + 2, ids.get(left + 1));
329 case 1:
330 positions[left + 1] = positions[left];
Ben Kwa6280de02015-12-16 19:42:08 -0800331 sortKey[left + 1] = sortKey[left];
332 mimeTypes[left + 1] = mimeTypes[left];
Ben Kwab8a5e082015-12-07 13:25:27 -0800333 ids.set(left + 1, ids.get(left));
334 break;
335 default:
336 System.arraycopy(positions, left, positions, left + 1, n);
Ben Kwa6280de02015-12-16 19:42:08 -0800337 System.arraycopy(sortKey, left, sortKey, left + 1, n);
338 System.arraycopy(mimeTypes, left, mimeTypes, left + 1, n);
Ben Kwab8a5e082015-12-07 13:25:27 -0800339 for (int i = n; i >= 1; --i) {
340 ids.set(left + i, ids.get(left + i - 1));
341 }
342 }
343
344 positions[left] = pivotPosition;
Ben Kwa6280de02015-12-16 19:42:08 -0800345 sortKey[left] = pivotValue;
346 mimeTypes[left] = pivotMime;
Ben Kwab8a5e082015-12-07 13:25:27 -0800347 ids.set(left, pivotId);
Ben Kwa0497da82015-11-30 23:00:02 -0800348 }
349 }
350
Ben Kwae4338342016-01-08 15:34:47 -0800351 /**
352 * @return Timestamp for the given document. Some docs (e.g. active downloads) have a null
353 * timestamp - these will be replaced with MAX_LONG so that such files get sorted to the top
354 * when sorting by date.
355 */
356 long getLastModified(Cursor cursor) {
357 long l = getCursorLong(mCursor, Document.COLUMN_LAST_MODIFIED);
358 return (l == -1) ? Long.MAX_VALUE : l;
359 }
360
Ben Kwa0497da82015-11-30 23:00:02 -0800361 @Nullable Cursor getItem(String modelId) {
362 Integer pos = mPositions.get(modelId);
363 if (pos != null) {
364 mCursor.moveToPosition(pos);
365 return mCursor;
366 }
367 return null;
368 }
369
Ben Kwa0497da82015-11-30 23:00:02 -0800370 boolean isEmpty() {
371 return mCursorCount == 0;
372 }
373
374 boolean isLoading() {
375 return mIsLoading;
376 }
377
378 List<DocumentInfo> getDocuments(Selection items) {
379 final int size = (items != null) ? items.size() : 0;
380
381 final List<DocumentInfo> docs = new ArrayList<>(size);
Ben Kwad72a1da2015-12-01 19:56:57 -0800382 for (String modelId: items.getAll()) {
383 final Cursor cursor = getItem(modelId);
Ben Kwa0497da82015-11-30 23:00:02 -0800384 checkNotNull(cursor, "Cursor cannot be null.");
385 final DocumentInfo doc = DocumentInfo.fromDirectoryCursor(cursor);
386 docs.add(doc);
387 }
388 return docs;
389 }
390
391 @Override
392 public Cursor getCursor() {
393 if (Looper.myLooper() != Looper.getMainLooper()) {
394 throw new IllegalStateException("Can't call getCursor from non-main thread.");
395 }
396 return mCursor;
397 }
398
Ben Kwa0497da82015-11-30 23:00:02 -0800399 void addUpdateListener(UpdateListener listener) {
Ben Kwad72a1da2015-12-01 19:56:57 -0800400 mUpdateListeners.add(listener);
Ben Kwa0497da82015-11-30 23:00:02 -0800401 }
402
Ben Kwa472103f2016-02-10 15:48:25 -0800403 void removeUpdateListener(UpdateListener listener) {
404 mUpdateListeners.remove(listener);
405 }
406
Ben Kwad72a1da2015-12-01 19:56:57 -0800407 static interface UpdateListener {
Ben Kwa0497da82015-11-30 23:00:02 -0800408 /**
409 * Called when a successful update has occurred.
410 */
Ben Kwad72a1da2015-12-01 19:56:57 -0800411 void onModelUpdate(Model model);
Ben Kwa0497da82015-11-30 23:00:02 -0800412
413 /**
414 * Called when an update has been attempted but failed.
415 */
Ben Kwad72a1da2015-12-01 19:56:57 -0800416 void onModelUpdateFailed(Exception e);
Ben Kwa0497da82015-11-30 23:00:02 -0800417 }
Ben Kwab8a5e082015-12-07 13:25:27 -0800418
419 /**
420 * @return An ordered array of model IDs representing the documents in the model. It is sorted
421 * according to the current sort order, which was set by the last model update.
422 */
423 public List<String> getModelIds() {
424 return mIds;
425 }
Ben Kwa0497da82015-11-30 23:00:02 -0800426}