blob: b30cab6ccf9d638f446af71ac334f9871ca6df7e [file] [log] [blame]
Jeff Sharkeye22d02e2013-04-26 16:54:55 -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
Jeff Sharkey311a7d82015-04-11 21:27:21 -070019import static com.android.documentsui.BaseActivity.State.ACTION_BROWSE;
20import static com.android.documentsui.BaseActivity.State.ACTION_BROWSE_ALL;
Steve McKayd0a2a2c2015-03-25 14:35:33 -070021import static com.android.documentsui.BaseActivity.State.ACTION_CREATE;
22import static com.android.documentsui.BaseActivity.State.ACTION_MANAGE;
23import static com.android.documentsui.BaseActivity.State.MODE_GRID;
24import static com.android.documentsui.BaseActivity.State.MODE_LIST;
25import static com.android.documentsui.BaseActivity.State.MODE_UNKNOWN;
26import static com.android.documentsui.BaseActivity.State.SORT_ORDER_UNKNOWN;
Steve McKayfefcd702015-08-20 16:19:38 +000027import static com.android.documentsui.Shared.TAG;
Jeff Sharkeyac9e6272013-08-31 21:27:44 -070028import static com.android.documentsui.model.DocumentInfo.getCursorInt;
29import static com.android.documentsui.model.DocumentInfo.getCursorLong;
30import static com.android.documentsui.model.DocumentInfo.getCursorString;
Steve McKayef280152015-06-11 10:10:49 -070031import static com.android.internal.util.Preconditions.checkNotNull;
Steve McKayd57f5fa2015-07-23 16:33:41 -070032import static com.android.internal.util.Preconditions.checkState;
Steve McKay0599a442015-05-05 14:50:00 -070033
Ben Kwaf5858932015-04-07 15:43:39 -070034import android.app.Activity;
Jeff Sharkeyf63b7772013-10-01 17:57:41 -070035import android.app.ActivityManager;
Jeff Sharkey09c10bf2013-06-30 20:02:59 -070036import android.app.Fragment;
Jeff Sharkeye22d02e2013-04-26 16:54:55 -070037import android.app.FragmentManager;
38import android.app.FragmentTransaction;
Jeff Sharkeye22d02e2013-04-26 16:54:55 -070039import android.app.LoaderManager.LoaderCallbacks;
Vladislav Kaznacheev89b90332015-05-01 13:46:57 -070040import android.content.ClipData;
Jeff Sharkey3fd11772013-09-30 14:26:27 -070041import android.content.ContentProviderClient;
Jeff Sharkey873daa32013-08-18 17:38:20 -070042import android.content.ContentResolver;
Jeff Sharkeyd10f0492013-09-09 17:35:46 -070043import android.content.ContentValues;
Jeff Sharkeye22d02e2013-04-26 16:54:55 -070044import android.content.Context;
Jeff Sharkey873daa32013-08-18 17:38:20 -070045import android.content.Intent;
Jeff Sharkeye22d02e2013-04-26 16:54:55 -070046import android.content.Loader;
Jeff Sharkey083d7e12014-07-27 21:01:45 -070047import android.content.res.Resources;
Jeff Sharkeyac9e6272013-08-31 21:27:44 -070048import android.database.Cursor;
Jeff Sharkey8a8fb672013-05-07 12:41:33 -070049import android.graphics.Bitmap;
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -070050import android.graphics.Canvas;
Jeff Sharkey8a8fb672013-05-07 12:41:33 -070051import android.graphics.Point;
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -070052import android.graphics.drawable.Drawable;
Jeff Sharkeye22d02e2013-04-26 16:54:55 -070053import android.net.Uri;
Jeff Sharkey8a8fb672013-05-07 12:41:33 -070054import android.os.AsyncTask;
Jeff Sharkeye22d02e2013-04-26 16:54:55 -070055import android.os.Bundle;
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -070056import android.os.CancellationSignal;
Makoto Onuki77778752015-07-01 14:55:14 -070057import android.os.Handler;
58import android.os.Looper;
Jeff Sharkeye39a89b2013-10-29 11:56:37 -070059import android.os.OperationCanceledException;
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -070060import android.os.Parcelable;
Steve McKay8e258c62015-05-06 14:27:57 -070061import android.os.SystemProperties;
Jeff Sharkeye22d02e2013-04-26 16:54:55 -070062import android.provider.DocumentsContract;
Jeff Sharkeyac9e6272013-08-31 21:27:44 -070063import android.provider.DocumentsContract.Document;
Ben Kwa24be5d32015-08-27 16:04:46 -070064import android.support.annotation.Nullable;
Ben Kwa7461a952015-09-01 11:03:01 -070065import android.support.annotation.VisibleForTesting;
Ben Kwa91923182015-08-27 16:06:33 -070066import android.support.design.widget.Snackbar;
Steve McKayef280152015-06-11 10:10:49 -070067import android.support.v7.widget.GridLayoutManager;
68import android.support.v7.widget.LinearLayoutManager;
69import android.support.v7.widget.RecyclerView;
70import android.support.v7.widget.RecyclerView.LayoutManager;
Steve McKayef280152015-06-11 10:10:49 -070071import android.support.v7.widget.RecyclerView.RecyclerListener;
72import android.support.v7.widget.RecyclerView.ViewHolder;
Jeff Sharkey6d579272015-06-11 09:16:19 -070073import android.text.TextUtils;
Jeff Sharkey09c10bf2013-06-30 20:02:59 -070074import android.text.format.DateUtils;
Jeff Sharkey2e694f82013-08-06 16:26:14 -070075import android.text.format.Formatter;
Jeff Sharkey8a8fb672013-05-07 12:41:33 -070076import android.text.format.Time;
77import android.util.Log;
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -070078import android.util.SparseArray;
Ben Kwa91923182015-08-27 16:06:33 -070079import android.util.SparseBooleanArray;
Ben Kwa0574b182015-09-08 07:31:19 -070080import android.util.TypedValue;
Jeff Sharkeyc317af82013-07-01 16:56:54 -070081import android.view.ActionMode;
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -070082import android.view.DragEvent;
Steve McKayef280152015-06-11 10:10:49 -070083import android.view.GestureDetector;
Jeff Sharkeye22d02e2013-04-26 16:54:55 -070084import android.view.LayoutInflater;
Jeff Sharkey09c10bf2013-06-30 20:02:59 -070085import android.view.Menu;
Jeff Sharkey09c10bf2013-06-30 20:02:59 -070086import android.view.MenuItem;
Steve McKayef280152015-06-11 10:10:49 -070087import android.view.MotionEvent;
Jeff Sharkeye22d02e2013-04-26 16:54:55 -070088import android.view.View;
Steve McKayd57f5fa2015-07-23 16:33:41 -070089import android.view.View.OnLayoutChangeListener;
Jeff Sharkeye22d02e2013-04-26 16:54:55 -070090import android.view.ViewGroup;
Vladislav Kaznacheev9400b892015-09-04 09:17:37 -070091import android.view.ViewParent;
Jeff Sharkeye22d02e2013-04-26 16:54:55 -070092import android.widget.ImageView;
Jeff Sharkeye22d02e2013-04-26 16:54:55 -070093import android.widget.TextView;
Jeff Sharkey873daa32013-08-18 17:38:20 -070094import android.widget.Toast;
Jeff Sharkeye22d02e2013-04-26 16:54:55 -070095
Steve McKay351a7492015-08-04 10:11:01 -070096import com.android.documentsui.BaseActivity.DocumentContext;
Steve McKayd0a2a2c2015-03-25 14:35:33 -070097import com.android.documentsui.BaseActivity.State;
Steve McKayef280152015-06-11 10:10:49 -070098import com.android.documentsui.MultiSelectManager.Selection;
Jeff Sharkey753a3ae2013-10-22 17:09:44 -070099import com.android.documentsui.ProviderExecutor.Preemptable;
Jeff Sharkeyd10f0492013-09-09 17:35:46 -0700100import com.android.documentsui.RecentsProvider.StateColumns;
Jeff Sharkey724deeb2013-08-31 15:02:20 -0700101import com.android.documentsui.model.DocumentInfo;
Tomasz Mikolajewski9452c442015-04-14 16:32:41 +0900102import com.android.documentsui.model.DocumentStack;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700103import com.android.documentsui.model.RootInfo;
Steve McKay1f199482015-05-20 15:58:42 -0700104import com.android.internal.util.Preconditions;
Steve McKayfefcd702015-08-20 16:19:38 +0000105import com.google.common.collect.Lists;
Jeff Sharkeyc317af82013-07-01 16:56:54 -0700106
107import java.util.ArrayList;
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -0700108import java.util.Collections;
Jeff Sharkeya5defe32013-08-05 17:56:48 -0700109import java.util.List;
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700110
111/**
112 * Display the documents inside a single directory.
113 */
114public class DirectoryFragment extends Fragment {
115
Jeff Sharkeya5defe32013-08-05 17:56:48 -0700116 public static final int TYPE_NORMAL = 1;
117 public static final int TYPE_SEARCH = 2;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700118 public static final int TYPE_RECENT_OPEN = 3;
Jeff Sharkey5b535922013-08-02 15:55:26 -0700119
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700120 public static final int ANIM_NONE = 1;
121 public static final int ANIM_SIDE = 2;
122 public static final int ANIM_DOWN = 3;
123 public static final int ANIM_UP = 4;
124
Ben Kwaf5858932015-04-07 15:43:39 -0700125 public static final int REQUEST_COPY_DESTINATION = 1;
126
Steve McKayef280152015-06-11 10:10:49 -0700127 private static final int LOADER_ID = 42;
128 private static final boolean DEBUG = false;
Steve McKay8e258c62015-05-06 14:27:57 -0700129 private static final boolean DEBUG_ENABLE_DND = false;
130
Jeff Sharkey2e694f82013-08-06 16:26:14 -0700131 private static final String EXTRA_TYPE = "type";
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700132 private static final String EXTRA_ROOT = "root";
133 private static final String EXTRA_DOC = "doc";
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700134 private static final String EXTRA_QUERY = "query";
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700135 private static final String EXTRA_IGNORE_STATE = "ignoreState";
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700136
Ben Kwa7461a952015-09-01 11:03:01 -0700137 private Model mModel;
Ben Kwa379e1762015-09-21 10:49:52 -0700138 private Model.UpdateListener mModelUpdateListener = new ModelUpdateListener();
Ben Kwa24be5d32015-08-27 16:04:46 -0700139
Steve McKayef280152015-06-11 10:10:49 -0700140 private final Handler mHandler = new Handler(Looper.getMainLooper());
Jeff Sharkey2e694f82013-08-06 16:26:14 -0700141
Steve McKayef280152015-06-11 10:10:49 -0700142 private View mEmptyView;
143 private RecyclerView mRecView;
144
145 private int mType = TYPE_NORMAL;
146 private String mStateKey;
147
148 private int mLastMode = MODE_UNKNOWN;
149 private int mLastSortOrder = SORT_ORDER_UNKNOWN;
150 private boolean mLastShowSize;
151 private boolean mHideGridTitles;
152 private boolean mSvelteRecents;
153 private Point mThumbSize;
154 private DocumentsAdapter mAdapter;
155 private LoaderCallbacks<DirectoryResult> mCallbacks;
Steve McKay1f199482015-05-20 15:58:42 -0700156 private FragmentTuner mFragmentTuner;
157 private DocumentClipper mClipper;
Steve McKayef280152015-06-11 10:10:49 -0700158 // These are lazily initialized.
Steve McKayd57f5fa2015-07-23 16:33:41 -0700159 private LinearLayoutManager mListLayout;
160 private GridLayoutManager mGridLayout;
Steve McKayd57f5fa2015-07-23 16:33:41 -0700161 private int mColumnCount = 1; // This will get updated when layout changes.
Steve McKay1f199482015-05-20 15:58:42 -0700162
Ben Kwac42fa402015-09-16 08:04:37 -0700163 private MessageBar mMessageBar;
Ben Kwa379e1762015-09-21 10:49:52 -0700164 private View mProgressBar;
Ben Kwac42fa402015-09-16 08:04:37 -0700165
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700166 public static void showNormal(FragmentManager fm, RootInfo root, DocumentInfo doc, int anim) {
167 show(fm, TYPE_NORMAL, root, doc, null, anim);
Jeff Sharkey2e694f82013-08-06 16:26:14 -0700168 }
169
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700170 public static void showSearch(FragmentManager fm, RootInfo root, String query, int anim) {
171 show(fm, TYPE_SEARCH, root, null, query, anim);
Jeff Sharkey2e694f82013-08-06 16:26:14 -0700172 }
173
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700174 public static void showRecentsOpen(FragmentManager fm, int anim) {
175 show(fm, TYPE_RECENT_OPEN, null, null, null, anim);
Jeff Sharkey2e694f82013-08-06 16:26:14 -0700176 }
177
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700178 private static void show(FragmentManager fm, int type, RootInfo root, DocumentInfo doc,
179 String query, int anim) {
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700180 final Bundle args = new Bundle();
Jeff Sharkey2e694f82013-08-06 16:26:14 -0700181 args.putInt(EXTRA_TYPE, type);
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700182 args.putParcelable(EXTRA_ROOT, root);
183 args.putParcelable(EXTRA_DOC, doc);
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700184 args.putString(EXTRA_QUERY, query);
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700185
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700186 final FragmentTransaction ft = fm.beginTransaction();
187 switch (anim) {
188 case ANIM_SIDE:
189 args.putBoolean(EXTRA_IGNORE_STATE, true);
190 break;
191 case ANIM_DOWN:
192 args.putBoolean(EXTRA_IGNORE_STATE, true);
193 ft.setCustomAnimations(R.animator.dir_down, R.animator.dir_frozen);
194 break;
195 case ANIM_UP:
196 ft.setCustomAnimations(R.animator.dir_frozen, R.animator.dir_up);
197 break;
198 }
199
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700200 final DirectoryFragment fragment = new DirectoryFragment();
201 fragment.setArguments(args);
202
Jeff Sharkey76112212013-08-06 11:26:10 -0700203 ft.replace(R.id.container_directory, fragment);
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700204 ft.commitAllowingStateLoss();
205 }
206
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700207 private static String buildStateKey(RootInfo root, DocumentInfo doc) {
208 final StringBuilder builder = new StringBuilder();
209 builder.append(root != null ? root.authority : "null").append(';');
210 builder.append(root != null ? root.rootId : "null").append(';');
211 builder.append(doc != null ? doc.documentId : "null");
212 return builder.toString();
213 }
214
Jeff Sharkeya5defe32013-08-05 17:56:48 -0700215 public static DirectoryFragment get(FragmentManager fm) {
216 // TODO: deal with multiple directories shown at once
Jeff Sharkey76112212013-08-06 11:26:10 -0700217 return (DirectoryFragment) fm.findFragmentById(R.id.container_directory);
Jeff Sharkeya5defe32013-08-05 17:56:48 -0700218 }
219
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700220 @Override
221 public View onCreateView(
222 LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
223 final Context context = inflater.getContext();
Jeff Sharkey083d7e12014-07-27 21:01:45 -0700224 final Resources res = context.getResources();
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700225 final View view = inflater.inflate(R.layout.fragment_directory, container, false);
226
Ben Kwac42fa402015-09-16 08:04:37 -0700227 mMessageBar = MessageBar.create(getChildFragmentManager());
Ben Kwa379e1762015-09-21 10:49:52 -0700228 mProgressBar = view.findViewById(R.id.progressbar);
Ben Kwac42fa402015-09-16 08:04:37 -0700229
Jeff Sharkeyc6cbdf12013-08-07 16:22:02 -0700230 mEmptyView = view.findViewById(android.R.id.empty);
231
Steve McKayef280152015-06-11 10:10:49 -0700232 mRecView = (RecyclerView) view.findViewById(R.id.recyclerView);
233 mRecView.setRecyclerListener(
234 new RecyclerListener() {
235 @Override
236 public void onViewRecycled(ViewHolder holder) {
237 cancelThumbnailTask(holder.itemView);
238 }
239 });
Steve McKay8e258c62015-05-06 14:27:57 -0700240
Steve McKayd57f5fa2015-07-23 16:33:41 -0700241 // TODO: Rather than update columns on layout changes, push this
242 // code (or something like it) into GridLayoutManager.
243 mRecView.addOnLayoutChangeListener(
244 new OnLayoutChangeListener() {
245
246 @Override
247 public void onLayoutChange(
248 View v, int left, int top, int right, int bottom, int oldLeft,
249 int oldTop, int oldRight, int oldBottom) {
Steve McKayfefcd702015-08-20 16:19:38 +0000250 mColumnCount = calculateColumnCount();
Steve McKayd57f5fa2015-07-23 16:33:41 -0700251 if (mGridLayout != null) {
252 mGridLayout.setSpanCount(mColumnCount);
253 }
254 }
255 });
256
257 // TODO: Add a divider between views (which might use RecyclerView.ItemDecoration).
Steve McKay8e258c62015-05-06 14:27:57 -0700258 if (DEBUG_ENABLE_DND) {
Steve McKayef280152015-06-11 10:10:49 -0700259 setupDragAndDropOnDirectoryView(mRecView);
Steve McKay8e258c62015-05-06 14:27:57 -0700260 }
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700261
Jeff Sharkeyac9e6272013-08-31 21:27:44 -0700262 return view;
263 }
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700264
Jeff Sharkeyac9e6272013-08-31 21:27:44 -0700265 @Override
Jeff Sharkeyf63b7772013-10-01 17:57:41 -0700266 public void onDestroyView() {
267 super.onDestroyView();
268
269 // Cancel any outstanding thumbnail requests
Steve McKayef280152015-06-11 10:10:49 -0700270 final int count = mRecView.getChildCount();
Jeff Sharkeyf63b7772013-10-01 17:57:41 -0700271 for (int i = 0; i < count; i++) {
Steve McKayef280152015-06-11 10:10:49 -0700272 final View view = mRecView.getChildAt(i);
273 cancelThumbnailTask(view);
Jeff Sharkeyf63b7772013-10-01 17:57:41 -0700274 }
Jeff Sharkeyfaaeb392013-10-04 14:44:56 -0700275
Steve McKayef280152015-06-11 10:10:49 -0700276 // Clear any outstanding selection
Ben Kwa24be5d32015-08-27 16:04:46 -0700277 mModel.clearSelection();
Jeff Sharkeyf63b7772013-10-01 17:57:41 -0700278 }
279
280 @Override
Jeff Sharkeyac9e6272013-08-31 21:27:44 -0700281 public void onActivityCreated(Bundle savedInstanceState) {
282 super.onActivityCreated(savedInstanceState);
283
284 final Context context = getActivity();
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700285 final State state = getDisplayState(DirectoryFragment.this);
Jeff Sharkeyac9e6272013-08-31 21:27:44 -0700286
Jeff Sharkey9656a532013-09-13 13:42:19 -0700287 final RootInfo root = getArguments().getParcelable(EXTRA_ROOT);
288 final DocumentInfo doc = getArguments().getParcelable(EXTRA_DOC);
289
Steve McKayef280152015-06-11 10:10:49 -0700290 mAdapter = new DocumentsAdapter(context);
291 mRecView.setAdapter(mAdapter);
292
293 GestureDetector.SimpleOnGestureListener listener =
294 new GestureDetector.SimpleOnGestureListener() {
295 @Override
296 public boolean onSingleTapUp(MotionEvent e) {
297 return DirectoryFragment.this.onSingleTapUp(e);
298 }
Steve McKay93d8ef42015-07-30 12:27:44 -0700299 @Override
300 public boolean onDoubleTap(MotionEvent e) {
301 Log.d(TAG, "Handling double tap.");
302 return DirectoryFragment.this.onDoubleTap(e);
303 }
Steve McKayef280152015-06-11 10:10:49 -0700304 };
305
Ben Kwa24be5d32015-08-27 16:04:46 -0700306 // TODO: instead of inserting the view into the constructor, extract listener-creation code
307 // and set the listener on the view after the fact. Then the view doesn't need to be passed
308 // into the selection manager which is passed into the model.
309 MultiSelectManager selMgr= new MultiSelectManager(
Steve McKay57394872015-08-12 14:48:34 -0700310 mRecView,
311 listener,
312 state.allowMultiple
313 ? MultiSelectManager.MODE_MULTIPLE
314 : MultiSelectManager.MODE_SINGLE);
Ben Kwa24be5d32015-08-27 16:04:46 -0700315 selMgr.addCallback(new SelectionModeListener());
Ben Kwa7461a952015-09-01 11:03:01 -0700316
Ben Kwa379e1762015-09-21 10:49:52 -0700317 mModel = new Model(context, selMgr, mAdapter);
318 mModel.addUpdateListener(mModelUpdateListener);
Steve McKayef280152015-06-11 10:10:49 -0700319
Jeff Sharkey2e694f82013-08-06 16:26:14 -0700320 mType = getArguments().getInt(EXTRA_TYPE);
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700321 mStateKey = buildStateKey(root, doc);
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700322
Steve McKay1f199482015-05-20 15:58:42 -0700323 mFragmentTuner = pickFragmentTuner(state);
324 mClipper = new DocumentClipper(context);
325
Jeff Sharkey9656a532013-09-13 13:42:19 -0700326 if (mType == TYPE_RECENT_OPEN) {
327 // Hide titles when showing recents for picking images/videos
328 mHideGridTitles = MimePredicate.mimeMatches(
329 MimePredicate.VISUAL_MIMES, state.acceptMimes);
330 } else {
331 mHideGridTitles = (doc != null) && doc.isGridTitlesHidden();
332 }
333
Jeff Sharkeyf63b7772013-10-01 17:57:41 -0700334 final ActivityManager am = (ActivityManager) context.getSystemService(
335 Context.ACTIVITY_SERVICE);
336 mSvelteRecents = am.isLowRamDevice() && (mType == TYPE_RECENT_OPEN);
337
Jeff Sharkey46899c82013-08-18 22:26:48 -0700338 mCallbacks = new LoaderCallbacks<DirectoryResult>() {
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700339 @Override
Jeff Sharkey46899c82013-08-18 22:26:48 -0700340 public Loader<DirectoryResult> onCreateLoader(int id, Bundle args) {
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700341 final String query = getArguments().getString(EXTRA_QUERY);
Jeff Sharkey46165b52013-07-31 20:53:22 -0700342
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700343 Uri contentsUri;
344 switch (mType) {
345 case TYPE_NORMAL:
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700346 contentsUri = DocumentsContract.buildChildDocumentsUri(
347 doc.authority, doc.documentId);
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700348 if (state.action == ACTION_MANAGE) {
349 contentsUri = DocumentsContract.setManageMode(contentsUri);
350 }
Jeff Sharkeyd10f0492013-09-09 17:35:46 -0700351 return new DirectoryLoader(
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700352 context, mType, root, doc, contentsUri, state.userSortOrder);
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700353 case TYPE_SEARCH:
354 contentsUri = DocumentsContract.buildSearchDocumentsUri(
Jeff Sharkey0e8c8712013-09-12 21:59:06 -0700355 root.authority, root.rootId, query);
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700356 if (state.action == ACTION_MANAGE) {
357 contentsUri = DocumentsContract.setManageMode(contentsUri);
358 }
Jeff Sharkeyd10f0492013-09-09 17:35:46 -0700359 return new DirectoryLoader(
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700360 context, mType, root, doc, contentsUri, state.userSortOrder);
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700361 case TYPE_RECENT_OPEN:
Jeff Sharkey1c903cc2013-09-02 17:19:40 -0700362 final RootsCache roots = DocumentsApplication.getRootsCache(context);
Jeff Sharkey8b997042013-09-19 15:25:56 -0700363 return new RecentLoader(context, roots, state);
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700364 default:
365 throw new IllegalStateException("Unknown type " + mType);
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700366 }
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700367 }
368
369 @Override
Jeff Sharkey46899c82013-08-18 22:26:48 -0700370 public void onLoadFinished(Loader<DirectoryResult> loader, DirectoryResult result) {
Makoto Onuki77778752015-07-01 14:55:14 -0700371 if (result == null || result.exception != null) {
372 // onBackPressed does a fragment transaction, which can't be done inside
373 // onLoadFinished
374 mHandler.post(new Runnable() {
375 @Override
376 public void run() {
377 final Activity activity = getActivity();
378 if (activity != null) {
379 activity.onBackPressed();
380 }
381 }
382 });
383 return;
384 }
385
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700386 if (!isAdded()) return;
387
Ben Kwa24be5d32015-08-27 16:04:46 -0700388 mModel.update(result);
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700389
390 // Push latest state up to UI
391 // TODO: if mode change was racing with us, don't overwrite it
Jeff Sharkey7d58fc62013-09-12 16:25:02 -0700392 if (result.mode != MODE_UNKNOWN) {
393 state.derivedMode = result.mode;
394 }
Jeff Sharkeyd10f0492013-09-09 17:35:46 -0700395 state.derivedSortOrder = result.sortOrder;
Steve McKayd0a2a2c2015-03-25 14:35:33 -0700396 ((BaseActivity) context).onStateChanged();
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700397
398 updateDisplayState();
399
Jeff Sharkey25f10b32013-10-07 14:08:17 -0700400 // When launched into empty recents, show drawer
Ben Kwa24be5d32015-08-27 16:04:46 -0700401 if (mType == TYPE_RECENT_OPEN && mModel.isEmpty() && !state.stackTouched &&
Steve McKayb68dd222015-04-20 17:18:15 -0700402 context instanceof DocumentsActivity) {
403 ((DocumentsActivity) context).setRootsDrawerOpen(true);
Jeff Sharkey25f10b32013-10-07 14:08:17 -0700404 }
405
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700406 // Restore any previous instance state
407 final SparseArray<Parcelable> container = state.dirState.remove(mStateKey);
408 if (container != null && !getArguments().getBoolean(EXTRA_IGNORE_STATE, false)) {
409 getView().restoreHierarchyState(container);
410 } else if (mLastSortOrder != state.derivedSortOrder) {
Steve McKayef280152015-06-11 10:10:49 -0700411 mRecView.smoothScrollToPosition(0);
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700412 }
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700413
414 mLastSortOrder = state.derivedSortOrder;
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700415 }
416
417 @Override
Jeff Sharkey46899c82013-08-18 22:26:48 -0700418 public void onLoaderReset(Loader<DirectoryResult> loader) {
Ben Kwa24be5d32015-08-27 16:04:46 -0700419 mModel.update(null);
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700420 }
421 };
422
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700423 // Kick off loader at least once
Steve McKayef280152015-06-11 10:10:49 -0700424 getLoaderManager().restartLoader(LOADER_ID, null, mCallbacks);
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700425
Kyle Horimoto426bd0d2015-07-29 15:33:49 -0700426 mFragmentTuner.afterActivityCreated(this);
Jeff Sharkey2e694f82013-08-06 16:26:14 -0700427 updateDisplayState();
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700428 }
429
Jeff Sharkey42d26792013-09-06 13:22:09 -0700430 @Override
Ben Kwaf5858932015-04-07 15:43:39 -0700431 public void onActivityResult(int requestCode, int resultCode, Intent data) {
Ben Kwaf5858932015-04-07 15:43:39 -0700432 // There's only one request code right now. Replace this with a switch statement or
433 // something more scalable when more codes are added.
434 if (requestCode != REQUEST_COPY_DESTINATION) {
435 return;
436 }
437 if (resultCode == Activity.RESULT_CANCELED || data == null) {
438 // User pressed the back button or otherwise cancelled the destination pick. Don't
439 // proceed with the copy.
440 return;
441 }
442
Tomasz Mikolajewski9452c442015-04-14 16:32:41 +0900443 CopyService.start(getActivity(), getDisplayState(this).selectedDocumentsForCopy,
Ben Kwacb4461f2015-05-05 11:50:11 -0700444 (DocumentStack) data.getParcelableExtra(CopyService.EXTRA_STACK),
445 data.getIntExtra(CopyService.EXTRA_TRANSFER_MODE, CopyService.TRANSFER_MODE_NONE));
Ben Kwaf5858932015-04-07 15:43:39 -0700446 }
447
Steve McKayef280152015-06-11 10:10:49 -0700448 private int getEventAdapterPosition(MotionEvent e) {
449 View view = mRecView.findChildViewUnder(e.getX(), e.getY());
450 return view != null ? mRecView.getChildAdapterPosition(view) : RecyclerView.NO_POSITION;
451 }
452
453 private boolean onSingleTapUp(MotionEvent e) {
Ben Kwa24be5d32015-08-27 16:04:46 -0700454 if (Events.isTouchEvent(e) && mModel.getSelection().isEmpty()) {
Steve McKay93d8ef42015-07-30 12:27:44 -0700455 int position = getEventAdapterPosition(e);
456 if (position != RecyclerView.NO_POSITION) {
457 return handleViewItem(position);
Steve McKayef280152015-06-11 10:10:49 -0700458 }
459 }
Steve McKay93d8ef42015-07-30 12:27:44 -0700460 return false;
461 }
Steve McKayef280152015-06-11 10:10:49 -0700462
Steve McKay93d8ef42015-07-30 12:27:44 -0700463 protected boolean onDoubleTap(MotionEvent e) {
464 if (Events.isMouseEvent(e)) {
465 Log.d(TAG, "Handling double tap from mouse.");
466 int position = getEventAdapterPosition(e);
467 if (position != RecyclerView.NO_POSITION) {
468 return handleViewItem(position);
469 }
470 }
471 return false;
472 }
473
474 private boolean handleViewItem(int position) {
Ben Kwa24be5d32015-08-27 16:04:46 -0700475 final Cursor cursor = mModel.getItem(position);
Steve McKay93d8ef42015-07-30 12:27:44 -0700476 checkNotNull(cursor, "Cursor cannot be null.");
477 final String docMimeType = getCursorString(cursor, Document.COLUMN_MIME_TYPE);
478 final int docFlags = getCursorInt(cursor, Document.COLUMN_FLAGS);
479 if (isDocumentEnabled(docMimeType, docFlags)) {
480 final DocumentInfo doc = DocumentInfo.fromDirectoryCursor(cursor);
Ben Kwa24be5d32015-08-27 16:04:46 -0700481 ((BaseActivity) getActivity()).onDocumentPicked(doc, mModel);
482 mModel.clearSelection();
Steve McKay93d8ef42015-07-30 12:27:44 -0700483 return true;
484 }
Steve McKayef280152015-06-11 10:10:49 -0700485 return false;
486 }
487
Ben Kwaf5858932015-04-07 15:43:39 -0700488 @Override
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700489 public void onStop() {
490 super.onStop();
491
492 // Remember last scroll location
493 final SparseArray<Parcelable> container = new SparseArray<Parcelable>();
494 getView().saveHierarchyState(container);
495 final State state = getDisplayState(this);
496 state.dirState.put(mStateKey, container);
497 }
498
499 @Override
Jeff Sharkey7d58fc62013-09-12 16:25:02 -0700500 public void onResume() {
501 super.onResume();
Jeff Sharkey42d26792013-09-06 13:22:09 -0700502 updateDisplayState();
503 }
504
Jeff Sharkeye8d13ea2014-08-08 15:10:03 -0700505 public void onDisplayStateChanged() {
506 updateDisplayState();
507 }
508
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700509 public void onUserSortOrderChanged() {
Jeff Sharkeyd10f0492013-09-09 17:35:46 -0700510 // Sort order change always triggers reload; we'll trigger state change
511 // on the flip side.
Steve McKayef280152015-06-11 10:10:49 -0700512 getLoaderManager().restartLoader(LOADER_ID, null, mCallbacks);
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700513 }
514
515 public void onUserModeChanged() {
Jeff Sharkeyd10f0492013-09-09 17:35:46 -0700516 final ContentResolver resolver = getActivity().getContentResolver();
517 final State state = getDisplayState(this);
518
519 final RootInfo root = getArguments().getParcelable(EXTRA_ROOT);
520 final DocumentInfo doc = getArguments().getParcelable(EXTRA_DOC);
521
Jeff Sharkey0e8c8712013-09-12 21:59:06 -0700522 if (root != null && doc != null) {
Jeff Sharkey7d58fc62013-09-12 16:25:02 -0700523 final Uri stateUri = RecentsProvider.buildState(
524 root.authority, root.rootId, doc.documentId);
525 final ContentValues values = new ContentValues();
526 values.put(StateColumns.MODE, state.userMode);
Jeff Sharkeyd10f0492013-09-09 17:35:46 -0700527
Jeff Sharkey7d58fc62013-09-12 16:25:02 -0700528 new AsyncTask<Void, Void, Void>() {
529 @Override
530 protected Void doInBackground(Void... params) {
531 resolver.insert(stateUri, values);
532 return null;
533 }
534 }.execute();
535 }
Jeff Sharkeyd10f0492013-09-09 17:35:46 -0700536
537 // Mode change is just visual change; no need to kick loader, and
538 // deliver change event immediately.
539 state.derivedMode = state.userMode;
Steve McKayd0a2a2c2015-03-25 14:35:33 -0700540 ((BaseActivity) getActivity()).onStateChanged();
Jeff Sharkeyd10f0492013-09-09 17:35:46 -0700541
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700542 updateDisplayState();
543 }
544
545 private void updateDisplayState() {
Jeff Sharkeyb3620442013-09-01 18:41:04 -0700546 final State state = getDisplayState(this);
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700547
Jeff Sharkey5e1884d2013-09-10 17:56:39 -0700548 if (mLastMode == state.derivedMode && mLastShowSize == state.showSize) return;
Jeff Sharkeyd10f0492013-09-09 17:35:46 -0700549 mLastMode = state.derivedMode;
Jeff Sharkey5e1884d2013-09-10 17:56:39 -0700550 mLastShowSize = state.showSize;
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700551
Steve McKayef280152015-06-11 10:10:49 -0700552 updateLayout(state.derivedMode);
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700553
Steve McKayef280152015-06-11 10:10:49 -0700554 mRecView.setAdapter(mAdapter);
555 }
556
557 /**
558 * Returns a {@code LayoutManager} for {@code mode}, lazily initializing
559 * classes as needed.
560 */
561 private void updateLayout(int mode) {
Jeff Sharkey8a8fb672013-05-07 12:41:33 -0700562 final int thumbSize;
Steve McKayef280152015-06-11 10:10:49 -0700563
564 final LayoutManager layout;
565 switch (mode) {
566 case MODE_GRID:
Steve McKayef280152015-06-11 10:10:49 -0700567 thumbSize = getResources().getDimensionPixelSize(R.dimen.grid_width);
Steve McKaya9be7182015-07-22 16:03:35 -0700568 if (mGridLayout == null) {
Steve McKayd57f5fa2015-07-23 16:33:41 -0700569 mGridLayout = new GridLayoutManager(getContext(), mColumnCount );
Steve McKaya9be7182015-07-22 16:03:35 -0700570 }
Steve McKayef280152015-06-11 10:10:49 -0700571 layout = mGridLayout;
572 break;
573 case MODE_LIST:
Steve McKaya9be7182015-07-22 16:03:35 -0700574 thumbSize = getResources().getDimensionPixelSize(R.dimen.icon_size);
Steve McKayef280152015-06-11 10:10:49 -0700575 if (mListLayout == null) {
576 mListLayout = new LinearLayoutManager(getContext());
577 }
Steve McKayef280152015-06-11 10:10:49 -0700578 layout = mListLayout;
579 break;
580 case MODE_UNKNOWN:
581 default:
582 throw new IllegalArgumentException("Unsupported layout mode: " + mode);
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700583 }
Jeff Sharkey8a8fb672013-05-07 12:41:33 -0700584
Steve McKayef280152015-06-11 10:10:49 -0700585 mRecView.setLayoutManager(layout);
Kyle Horimoto2da6e4a2015-08-27 16:44:00 -0700586 // TODO: Once b/23691541 is resolved, use a listener within MultiSelectManager instead of
587 // imperatively calling this function.
Steve McKay9058e042015-09-01 12:31:24 -0700588 mModel.mSelectionManager.handleLayoutChanged();
Steve McKayef280152015-06-11 10:10:49 -0700589 // setting layout manager automatically invalidates existing ViewHolders.
Jeff Sharkey8a8fb672013-05-07 12:41:33 -0700590 mThumbSize = new Point(thumbSize, thumbSize);
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700591 }
592
Steve McKayfefcd702015-08-20 16:19:38 +0000593 private int calculateColumnCount() {
594 int cellWidth = getResources().getDimensionPixelSize(R.dimen.grid_width);
595 int cellMargin = 2 * getResources().getDimensionPixelSize(R.dimen.grid_item_margin);
Steve McKayd57f5fa2015-07-23 16:33:41 -0700596 int viewPadding = mRecView.getPaddingLeft() + mRecView.getPaddingRight();
Steve McKayfefcd702015-08-20 16:19:38 +0000597
Steve McKayd57f5fa2015-07-23 16:33:41 -0700598 checkState(mRecView.getWidth() > 0);
599 int columnCount = Math.max(1,
Steve McKayfefcd702015-08-20 16:19:38 +0000600 (mRecView.getWidth() - viewPadding) / (cellWidth + cellMargin));
601
Steve McKayd57f5fa2015-07-23 16:33:41 -0700602 return columnCount;
603 }
604
Steve McKayef280152015-06-11 10:10:49 -0700605 /**
606 * Manages the integration between our ActionMode and MultiSelectManager, initiating
607 * ActionMode when there is a selection, canceling it when there is no selection,
608 * and clearing selection when action mode is explicitly exited by the user.
609 */
610 private final class SelectionModeListener
611 implements MultiSelectManager.Callback, ActionMode.Callback {
612
613 private Selection mSelected = new Selection();
614 private ActionMode mActionMode;
Steve McKay4f4232d2015-07-22 12:13:46 -0700615 private int mNoDeleteCount = 0;
616 private Menu mMenu;
Steve McKayef280152015-06-11 10:10:49 -0700617
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700618 @Override
Steve McKayef280152015-06-11 10:10:49 -0700619 public boolean onBeforeItemStateChange(int position, boolean selected) {
Ben Kwac42fa402015-09-16 08:04:37 -0700620 // Directories cannot be checked
Steve McKayef280152015-06-11 10:10:49 -0700621 if (selected) {
Ben Kwa24be5d32015-08-27 16:04:46 -0700622 final Cursor cursor = mModel.getItem(position);
Steve McKayef280152015-06-11 10:10:49 -0700623 checkNotNull(cursor, "Cursor cannot be null.");
Jeff Sharkey7cf49032013-09-26 10:54:16 -0700624 final String docMimeType = getCursorString(cursor, Document.COLUMN_MIME_TYPE);
625 final int docFlags = getCursorInt(cursor, Document.COLUMN_FLAGS);
Steve McKayef280152015-06-11 10:10:49 -0700626 return isDocumentEnabled(docMimeType, docFlags);
627 }
628 return true;
629 }
630
631 @Override
632 public void onItemStateChanged(int position, boolean selected) {
Steve McKay4f4232d2015-07-22 12:13:46 -0700633
Ben Kwa24be5d32015-08-27 16:04:46 -0700634 final Cursor cursor = mModel.getItem(position);
Steve McKay4f4232d2015-07-22 12:13:46 -0700635 checkNotNull(cursor, "Cursor cannot be null.");
636
637 final int docFlags = getCursorInt(cursor, Document.COLUMN_FLAGS);
638 if ((docFlags & Document.FLAG_SUPPORTS_DELETE) == 0) {
639 mNoDeleteCount += selected ? 1 : -1;
640 }
Steve McKay57394872015-08-12 14:48:34 -0700641 }
Steve McKay4f4232d2015-07-22 12:13:46 -0700642
Steve McKay57394872015-08-12 14:48:34 -0700643 @Override
644 public void onSelectionChanged() {
Ben Kwa24be5d32015-08-27 16:04:46 -0700645 mModel.getSelection(mSelected);
Ben Kwafe18c1b2015-09-11 15:40:18 -0700646 TypedValue color = new TypedValue();
Steve McKay4f4232d2015-07-22 12:13:46 -0700647 if (mSelected.size() > 0) {
Steve McKayef280152015-06-11 10:10:49 -0700648 if (DEBUG) Log.d(TAG, "Maybe starting action mode.");
649 if (mActionMode == null) {
650 if (DEBUG) Log.d(TAG, "Yeah. Starting action mode.");
651 mActionMode = getActivity().startActionMode(this);
Jeff Sharkeyaed873d2013-09-09 16:51:06 -0700652 }
Ben Kwafe18c1b2015-09-11 15:40:18 -0700653 getActivity().getTheme().resolveAttribute(
654 R.attr.colorActionMode, color, true);
Steve McKay4f4232d2015-07-22 12:13:46 -0700655 updateActionMenu();
656 } else {
657 if (DEBUG) Log.d(TAG, "Finishing action mode.");
658 if (mActionMode != null) {
659 mActionMode.finish();
660 }
Ben Kwa0574b182015-09-08 07:31:19 -0700661 getActivity().getTheme().resolveAttribute(
662 android.R.attr.colorPrimaryDark, color, true);
Jeff Sharkeyf339f252013-08-15 16:17:41 -0700663 }
Ben Kwafe18c1b2015-09-11 15:40:18 -0700664 getActivity().getWindow().setStatusBarColor(color.data);
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700665
Steve McKayef280152015-06-11 10:10:49 -0700666 if (mActionMode != null) {
667 mActionMode.setTitle(TextUtils.formatSelectedCount(mSelected.size()));
668 }
669 }
670
671 // Called when the user exits the action mode
672 @Override
673 public void onDestroyActionMode(ActionMode mode) {
674 if (DEBUG) Log.d(TAG, "Handling action mode destroyed.");
675 mActionMode = null;
676 // clear selection
Ben Kwa24be5d32015-08-27 16:04:46 -0700677 mModel.clearSelection();
Steve McKay4f4232d2015-07-22 12:13:46 -0700678 mSelected.clear();
679 mNoDeleteCount = 0;
Steve McKayef280152015-06-11 10:10:49 -0700680 }
681
Jeff Sharkeyc317af82013-07-01 16:56:54 -0700682 @Override
683 public boolean onCreateActionMode(ActionMode mode, Menu menu) {
684 mode.getMenuInflater().inflate(R.menu.mode_directory, menu);
Ben Kwa24be5d32015-08-27 16:04:46 -0700685 mode.setTitle(TextUtils.formatSelectedCount(mModel.getSelection().size()));
686 return mModel.getSelection().size() > 0;
Jeff Sharkeyc317af82013-07-01 16:56:54 -0700687 }
688
689 @Override
690 public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
Steve McKay4f4232d2015-07-22 12:13:46 -0700691 mMenu = menu;
692 updateActionMenu();
Jeff Sharkeyc317af82013-07-01 16:56:54 -0700693 return true;
694 }
695
Steve McKay4f4232d2015-07-22 12:13:46 -0700696 private void updateActionMenu() {
697 checkNotNull(mMenu);
698 // Delegate update logic to our owning action, since specialized logic is desired.
699 mFragmentTuner.updateActionMenu(mMenu, mType, mNoDeleteCount == 0);
700 }
701
Jeff Sharkeyc317af82013-07-01 16:56:54 -0700702 @Override
Steve McKayef280152015-06-11 10:10:49 -0700703 public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
Steve McKay1f199482015-05-20 15:58:42 -0700704
Ben Kwa24be5d32015-08-27 16:04:46 -0700705 Selection selection = mModel.getSelection(new Selection());
Jeff Sharkeyc317af82013-07-01 16:56:54 -0700706
Jeff Sharkey873daa32013-08-18 17:38:20 -0700707 final int id = item.getItemId();
708 if (id == R.id.menu_open) {
Steve McKayef280152015-06-11 10:10:49 -0700709 openDocuments(selection);
Jeff Sharkeyb3620442013-09-01 18:41:04 -0700710 mode.finish();
Jeff Sharkeyc317af82013-07-01 16:56:54 -0700711 return true;
Jeff Sharkey873daa32013-08-18 17:38:20 -0700712
713 } else if (id == R.id.menu_share) {
Steve McKayef280152015-06-11 10:10:49 -0700714 shareDocuments(selection);
Jeff Sharkeyb3620442013-09-01 18:41:04 -0700715 mode.finish();
Jeff Sharkey873daa32013-08-18 17:38:20 -0700716 return true;
717
718 } else if (id == R.id.menu_delete) {
Steve McKayef280152015-06-11 10:10:49 -0700719 deleteDocuments(selection);
Jeff Sharkeyb3620442013-09-01 18:41:04 -0700720 mode.finish();
Jeff Sharkey873daa32013-08-18 17:38:20 -0700721 return true;
722
Steve McKay1f199482015-05-20 15:58:42 -0700723 } else if (id == R.id.menu_copy_to) {
Steve McKayef280152015-06-11 10:10:49 -0700724 transferDocuments(selection, CopyService.TRANSFER_MODE_COPY);
Ben Kwacb4461f2015-05-05 11:50:11 -0700725 mode.finish();
726 return true;
727
Steve McKay1f199482015-05-20 15:58:42 -0700728 } else if (id == R.id.menu_move_to) {
Steve McKayef280152015-06-11 10:10:49 -0700729 transferDocuments(selection, CopyService.TRANSFER_MODE_MOVE);
Ben Kwa41b26c12015-03-31 10:11:43 -0700730 mode.finish();
731 return true;
732
Steve McKay1f199482015-05-20 15:58:42 -0700733 } else if (id == R.id.menu_copy_to_clipboard) {
Steve McKayef280152015-06-11 10:10:49 -0700734 copySelectionToClipboard(selection);
Steve McKay1f199482015-05-20 15:58:42 -0700735 mode.finish();
736 return true;
737
Ben Kwa512a6ba2015-03-31 08:15:21 -0700738 } else if (id == R.id.menu_select_all) {
Steve McKay0599a442015-05-05 14:50:00 -0700739 selectAllFiles();
Ben Kwa512a6ba2015-03-31 08:15:21 -0700740 return true;
741
Jeff Sharkeyc317af82013-07-01 16:56:54 -0700742 } else {
743 return false;
744 }
745 }
Steve McKayef280152015-06-11 10:10:49 -0700746 }
Jeff Sharkeyc317af82013-07-01 16:56:54 -0700747
Steve McKayef280152015-06-11 10:10:49 -0700748 private static void cancelThumbnailTask(View view) {
749 final ImageView iconThumb = (ImageView) view.findViewById(R.id.icon_thumb);
750 if (iconThumb != null) {
751 final ThumbnailAsyncTask oldTask = (ThumbnailAsyncTask) iconThumb.getTag();
752 if (oldTask != null) {
753 oldTask.preempt();
754 iconThumb.setTag(null);
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700755 }
756 }
Steve McKayef280152015-06-11 10:10:49 -0700757 }
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700758
Steve McKayef280152015-06-11 10:10:49 -0700759 private void openDocuments(final Selection selected) {
Steve McKay9276f3b2015-05-27 16:11:42 -0700760 new GetDocumentsTask() {
761 @Override
762 void onDocumentsReady(List<DocumentInfo> docs) {
Steve McKay0fbfc652015-08-20 16:48:49 -0700763 // TODO: Implement support in Files activity for opening multiple docs.
Steve McKay9276f3b2015-05-27 16:11:42 -0700764 BaseActivity.get(DirectoryFragment.this).onDocumentsPicked(docs);
Ben Kwaf527c632015-04-08 15:03:35 -0700765 }
Steve McKay9276f3b2015-05-27 16:11:42 -0700766 }.execute(selected);
Jeff Sharkey873daa32013-08-18 17:38:20 -0700767 }
768
Steve McKayef280152015-06-11 10:10:49 -0700769 private void shareDocuments(final Selection selected) {
Steve McKay9276f3b2015-05-27 16:11:42 -0700770 new GetDocumentsTask() {
771 @Override
772 void onDocumentsReady(List<DocumentInfo> docs) {
773 Intent intent;
774
775 // Filter out directories - those can't be shared.
Steve McKayfefcd702015-08-20 16:19:38 +0000776 List<DocumentInfo> docsForSend = new ArrayList<>();
Steve McKay9276f3b2015-05-27 16:11:42 -0700777 for (DocumentInfo doc: docs) {
778 if (!Document.MIME_TYPE_DIR.equals(doc.mimeType)) {
779 docsForSend.add(doc);
780 }
781 }
782
783 if (docsForSend.size() == 1) {
784 final DocumentInfo doc = docsForSend.get(0);
785
786 intent = new Intent(Intent.ACTION_SEND);
787 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
788 intent.addCategory(Intent.CATEGORY_DEFAULT);
789 intent.setType(doc.mimeType);
790 intent.putExtra(Intent.EXTRA_STREAM, doc.derivedUri);
791
792 } else if (docsForSend.size() > 1) {
793 intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
794 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
795 intent.addCategory(Intent.CATEGORY_DEFAULT);
796
Steve McKayfefcd702015-08-20 16:19:38 +0000797 final ArrayList<String> mimeTypes = new ArrayList<>();
798 final ArrayList<Uri> uris = new ArrayList<>();
Steve McKay9276f3b2015-05-27 16:11:42 -0700799 for (DocumentInfo doc : docsForSend) {
800 mimeTypes.add(doc.mimeType);
801 uris.add(doc.derivedUri);
802 }
803
804 intent.setType(findCommonMimeType(mimeTypes));
805 intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
806
807 } else {
808 return;
809 }
810
811 intent = Intent.createChooser(intent, getActivity().getText(R.string.share_via));
812 startActivity(intent);
813 }
814 }.execute(selected);
815 }
816
Steve McKayef280152015-06-11 10:10:49 -0700817 private void deleteDocuments(final Selection selected) {
Ben Kwa91923182015-08-27 16:06:33 -0700818 Context context = getActivity();
819 ContentResolver resolver = context.getContentResolver();
820 String message = Shared.getQuantityString(context, R.plurals.deleting, selected.size());
Jeff Sharkey873daa32013-08-18 17:38:20 -0700821
Ben Kwa91923182015-08-27 16:06:33 -0700822 mModel.markForDeletion(selected);
Jeff Sharkey873daa32013-08-18 17:38:20 -0700823
Ben Kwa91923182015-08-27 16:06:33 -0700824 Activity activity = getActivity();
825 Snackbar.make(this.getView(), message, Snackbar.LENGTH_LONG)
826 .setAction(
827 R.string.undo,
828 new android.view.View.OnClickListener() {
829 @Override
830 public void onClick(View view) {}
831 })
832 .setCallback(
833 new Snackbar.Callback() {
834 @Override
835 public void onDismissed(Snackbar snackbar, int event) {
836 if (event == Snackbar.Callback.DISMISS_EVENT_ACTION) {
837 mModel.undoDeletion();
838 } else {
Ben Kwa83cedf22015-09-11 15:15:45 -0700839 mModel.finalizeDeletion(
840 new Runnable() {
841 @Override
842 public void run() {
843 Snackbar.make(
844 DirectoryFragment.this.getView(),
845 R.string.toast_failed_delete,
846 Snackbar.LENGTH_LONG)
847 .show();
848
849 }
850 });
Ben Kwa91923182015-08-27 16:06:33 -0700851 }
Ben Kwa91923182015-08-27 16:06:33 -0700852 }
853 })
854 .show();
Jeff Sharkey873daa32013-08-18 17:38:20 -0700855 }
856
Steve McKayef280152015-06-11 10:10:49 -0700857 private void transferDocuments(final Selection selected, final int mode) {
Ben Kwaf5858932015-04-07 15:43:39 -0700858 // Pop up a dialog to pick a destination. This is inadequate but works for now.
859 // TODO: Implement a picker that is to spec.
Daichi Hironocaadd412015-04-10 15:50:38 +0900860 final Intent intent = new Intent(
Daichi Hirono22574ed2015-04-15 13:41:18 +0900861 BaseActivity.DocumentsIntent.ACTION_OPEN_COPY_DESTINATION,
Daichi Hironocaadd412015-04-10 15:50:38 +0900862 Uri.EMPTY,
863 getActivity(),
864 DocumentsActivity.class);
Steve McKay9276f3b2015-05-27 16:11:42 -0700865
866 new GetDocumentsTask() {
867 @Override
868 void onDocumentsReady(List<DocumentInfo> docs) {
869 getDisplayState(DirectoryFragment.this).selectedDocumentsForCopy = docs;
870
871 boolean directoryCopy = false;
872 for (DocumentInfo info : docs) {
873 if (Document.MIME_TYPE_DIR.equals(info.mimeType)) {
874 directoryCopy = true;
875 break;
876 }
877 }
878 intent.putExtra(BaseActivity.DocumentsIntent.EXTRA_DIRECTORY_COPY, directoryCopy);
879 intent.putExtra(CopyService.EXTRA_TRANSFER_MODE, mode);
880 startActivityForResult(intent, REQUEST_COPY_DESTINATION);
Daichi Hironof2a822d2015-04-14 17:12:54 +0900881 }
Steve McKay9276f3b2015-05-27 16:11:42 -0700882 }.execute(selected);
Ben Kwa41b26c12015-03-31 10:11:43 -0700883 }
884
Jeff Sharkeyb3620442013-09-01 18:41:04 -0700885 private static State getDisplayState(Fragment fragment) {
Steve McKayd0a2a2c2015-03-25 14:35:33 -0700886 return ((BaseActivity) fragment.getActivity()).getDisplayState();
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700887 }
888
Steve McKayef280152015-06-11 10:10:49 -0700889 // Provide a reference to the views for each data item
890 // Complex data items may need more than one view per item, and
891 // you provide access to all the views for a data item in a view holder
892 private static final class DocumentHolder extends RecyclerView.ViewHolder {
893 // each data item is just a string in this case
894 public View view;
895 public String docId; // The stable document id.
896 public DocumentHolder(View view) {
897 super(view);
898 this.view = view;
899 }
900 }
901
Ben Kwa379e1762015-09-21 10:49:52 -0700902 private final class DocumentsAdapter extends RecyclerView.Adapter<DocumentHolder> {
Steve McKayef280152015-06-11 10:10:49 -0700903
904 private final Context mContext;
905 private final LayoutInflater mInflater;
Steve McKayef280152015-06-11 10:10:49 -0700906
Steve McKayef280152015-06-11 10:10:49 -0700907 public DocumentsAdapter(Context context) {
908 mContext = context;
909 mInflater = LayoutInflater.from(context);
910 }
Jeff Sharkeyac9e6272013-08-31 21:27:44 -0700911
Ben Kwac42fa402015-09-16 08:04:37 -0700912 @Override
Steve McKayef280152015-06-11 10:10:49 -0700913 public DocumentHolder onCreateViewHolder(ViewGroup parent, int viewType) {
914 final State state = getDisplayState(DirectoryFragment.this);
915 final LayoutInflater inflater = LayoutInflater.from(getContext());
916 switch (state.derivedMode) {
917 case MODE_GRID:
918 return new DocumentHolder(inflater.inflate(R.layout.item_doc_grid, parent, false));
919 case MODE_LIST:
920 return new DocumentHolder(inflater.inflate(R.layout.item_doc_list, parent, false));
921 case MODE_UNKNOWN:
922 default:
923 throw new IllegalStateException("Unsupported layout mode.");
Jeff Sharkey20b32272013-09-03 15:25:52 -0700924 }
925 }
926
Steve McKayef280152015-06-11 10:10:49 -0700927 @Override
928 public void onBindViewHolder(DocumentHolder holder, int position) {
929
930 final Context context = getContext();
Jeff Sharkeyb3620442013-09-01 18:41:04 -0700931 final State state = getDisplayState(DirectoryFragment.this);
Jeff Sharkey9656a532013-09-13 13:42:19 -0700932 final DocumentInfo doc = getArguments().getParcelable(EXTRA_DOC);
Jeff Sharkey873daa32013-08-18 17:38:20 -0700933 final RootsCache roots = DocumentsApplication.getRootsCache(context);
934 final ThumbnailCache thumbs = DocumentsApplication.getThumbnailsCache(
935 context, mThumbSize);
936
Ben Kwa24be5d32015-08-27 16:04:46 -0700937 final Cursor cursor = mModel.getItem(position);
Steve McKayef280152015-06-11 10:10:49 -0700938 checkNotNull(cursor, "Cursor cannot be null.");
Jeff Sharkeyac9e6272013-08-31 21:27:44 -0700939
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700940 final String docAuthority = getCursorString(cursor, RootCursorWrapper.COLUMN_AUTHORITY);
941 final String docRootId = getCursorString(cursor, RootCursorWrapper.COLUMN_ROOT_ID);
Jeff Sharkeyac9e6272013-08-31 21:27:44 -0700942 final String docId = getCursorString(cursor, Document.COLUMN_DOCUMENT_ID);
943 final String docMimeType = getCursorString(cursor, Document.COLUMN_MIME_TYPE);
944 final String docDisplayName = getCursorString(cursor, Document.COLUMN_DISPLAY_NAME);
945 final long docLastModified = getCursorLong(cursor, Document.COLUMN_LAST_MODIFIED);
946 final int docIcon = getCursorInt(cursor, Document.COLUMN_ICON);
947 final int docFlags = getCursorInt(cursor, Document.COLUMN_FLAGS);
948 final String docSummary = getCursorString(cursor, Document.COLUMN_SUMMARY);
949 final long docSize = getCursorLong(cursor, Document.COLUMN_SIZE);
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700950
Steve McKayef280152015-06-11 10:10:49 -0700951 holder.docId = docId;
952 final View itemView = holder.view;
Ben Kwa24be5d32015-08-27 16:04:46 -0700953 itemView.setActivated(mModel.isSelected(position));
Jeff Sharkey9656a532013-09-13 13:42:19 -0700954
Steve McKayef280152015-06-11 10:10:49 -0700955 final View line1 = itemView.findViewById(R.id.line1);
956 final View line2 = itemView.findViewById(R.id.line2);
957
958 final ImageView iconMime = (ImageView) itemView.findViewById(R.id.icon_mime);
959 final ImageView iconThumb = (ImageView) itemView.findViewById(R.id.icon_thumb);
960 final TextView title = (TextView) itemView.findViewById(android.R.id.title);
961 final ImageView icon1 = (ImageView) itemView.findViewById(android.R.id.icon1);
962 final ImageView icon2 = (ImageView) itemView.findViewById(android.R.id.icon2);
963 final TextView summary = (TextView) itemView.findViewById(android.R.id.summary);
964 final TextView date = (TextView) itemView.findViewById(R.id.date);
965 final TextView size = (TextView) itemView.findViewById(R.id.size);
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700966
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700967 final ThumbnailAsyncTask oldTask = (ThumbnailAsyncTask) iconThumb.getTag();
Jeff Sharkey8a8fb672013-05-07 12:41:33 -0700968 if (oldTask != null) {
Jeff Sharkey753a3ae2013-10-22 17:09:44 -0700969 oldTask.preempt();
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700970 iconThumb.setTag(null);
Jeff Sharkey8a8fb672013-05-07 12:41:33 -0700971 }
972
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700973 iconMime.animate().cancel();
974 iconThumb.animate().cancel();
975
Jeff Sharkeyaed873d2013-09-09 16:51:06 -0700976 final boolean supportsThumbnail = (docFlags & Document.FLAG_SUPPORTS_THUMBNAIL) != 0;
Jeff Sharkeyd10f0492013-09-09 17:35:46 -0700977 final boolean allowThumbnail = (state.derivedMode == MODE_GRID)
Jeff Sharkey9656a532013-09-13 13:42:19 -0700978 || MimePredicate.mimeMatches(MimePredicate.VISUAL_MIMES, docMimeType);
Jeff Sharkeyf63b7772013-10-01 17:57:41 -0700979 final boolean showThumbnail = supportsThumbnail && allowThumbnail && !mSvelteRecents;
Jeff Sharkeyaed873d2013-09-09 16:51:06 -0700980
Jeff Sharkey7e544612014-08-29 15:38:27 -0700981 final boolean enabled = isDocumentEnabled(docMimeType, docFlags);
982 final float iconAlpha = (state.derivedMode == MODE_LIST && !enabled) ? 0.5f : 1f;
983
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700984 boolean cacheHit = false;
Jeff Sharkey9656a532013-09-13 13:42:19 -0700985 if (showThumbnail) {
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700986 final Uri uri = DocumentsContract.buildDocumentUri(docAuthority, docId);
Jeff Sharkeyac9e6272013-08-31 21:27:44 -0700987 final Bitmap cachedResult = thumbs.get(uri);
Jeff Sharkey8a8fb672013-05-07 12:41:33 -0700988 if (cachedResult != null) {
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700989 iconThumb.setImageBitmap(cachedResult);
990 cacheHit = true;
Jeff Sharkey8a8fb672013-05-07 12:41:33 -0700991 } else {
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700992 iconThumb.setImageDrawable(null);
Steve McKayef280152015-06-11 10:10:49 -0700993 // TODO: Hang this off DocumentHolder?
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700994 final ThumbnailAsyncTask task = new ThumbnailAsyncTask(
Jeff Sharkey7e544612014-08-29 15:38:27 -0700995 uri, iconMime, iconThumb, mThumbSize, iconAlpha);
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700996 iconThumb.setTag(task);
Jeff Sharkey753a3ae2013-10-22 17:09:44 -0700997 ProviderExecutor.forAuthority(docAuthority).execute(task);
Jeff Sharkey8a8fb672013-05-07 12:41:33 -0700998 }
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700999 }
1000
1001 // Always throw MIME icon into place, even when a thumbnail is being
1002 // loaded in background.
1003 if (cacheHit) {
1004 iconMime.setAlpha(0f);
Jeff Sharkey9dd02622013-09-27 16:44:11 -07001005 iconMime.setImageDrawable(null);
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -07001006 iconThumb.setAlpha(1f);
Jeff Sharkeye22d02e2013-04-26 16:54:55 -07001007 } else {
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -07001008 iconMime.setAlpha(1f);
1009 iconThumb.setAlpha(0f);
Jeff Sharkey9dd02622013-09-27 16:44:11 -07001010 iconThumb.setImageDrawable(null);
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001011 iconMime.setImageDrawable(
Steve McKayef280152015-06-11 10:10:49 -07001012 getDocumentIcon(mContext, docAuthority, docId, docMimeType, docIcon, state));
Jeff Sharkeye22d02e2013-04-26 16:54:55 -07001013 }
1014
Jeff Sharkey9656a532013-09-13 13:42:19 -07001015 boolean hasLine1 = false;
Jeff Sharkey42d26792013-09-06 13:22:09 -07001016 boolean hasLine2 = false;
1017
Jeff Sharkey9656a532013-09-13 13:42:19 -07001018 final boolean hideTitle = (state.derivedMode == MODE_GRID) && mHideGridTitles;
1019 if (!hideTitle) {
1020 title.setText(docDisplayName);
1021 hasLine1 = true;
1022 }
1023
1024 Drawable iconDrawable = null;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -07001025 if (mType == TYPE_RECENT_OPEN) {
Jeff Sharkey8b997042013-09-19 15:25:56 -07001026 // We've already had to enumerate roots before any results can
1027 // be shown, so this will never block.
1028 final RootInfo root = roots.getRootBlocking(docAuthority, docRootId);
Jeff Sharkey93cdbc22014-07-29 17:33:36 -07001029 if (state.derivedMode == MODE_GRID) {
Steve McKayef280152015-06-11 10:10:49 -07001030 iconDrawable = root.loadGridIcon(mContext);
Jeff Sharkey93cdbc22014-07-29 17:33:36 -07001031 } else {
Steve McKayef280152015-06-11 10:10:49 -07001032 iconDrawable = root.loadIcon(mContext);
Jeff Sharkey93cdbc22014-07-29 17:33:36 -07001033 }
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -07001034
Jeff Sharkey7d58fc62013-09-12 16:25:02 -07001035 if (summary != null) {
1036 final boolean alwaysShowSummary = getResources()
1037 .getBoolean(R.bool.always_show_summary);
1038 if (alwaysShowSummary) {
1039 summary.setText(root.getDirectoryString());
1040 summary.setVisibility(View.VISIBLE);
1041 hasLine2 = true;
1042 } else {
Jeff Sharkey8b997042013-09-19 15:25:56 -07001043 if (iconDrawable != null && roots.isIconUniqueBlocking(root)) {
Jeff Sharkey7d58fc62013-09-12 16:25:02 -07001044 // No summary needed if icon speaks for itself
1045 summary.setVisibility(View.INVISIBLE);
1046 } else {
1047 summary.setText(root.getDirectoryString());
1048 summary.setVisibility(View.VISIBLE);
1049 summary.setTextAlignment(TextView.TEXT_ALIGNMENT_TEXT_END);
1050 hasLine2 = true;
1051 }
1052 }
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -07001053 }
Jeff Sharkeyac9e6272013-08-31 21:27:44 -07001054 } else {
Jeff Sharkey9656a532013-09-13 13:42:19 -07001055 // Directories showing thumbnails in grid mode get a little icon
1056 // hint to remind user they're a directory.
1057 if (Document.MIME_TYPE_DIR.equals(docMimeType) && state.derivedMode == MODE_GRID
1058 && showThumbnail) {
Steve McKayef280152015-06-11 10:10:49 -07001059 iconDrawable = IconUtils.applyTintAttr(mContext, R.drawable.ic_doc_folder,
Jeff Sharkey34c54092014-08-08 13:08:56 -07001060 android.R.attr.textColorPrimaryInverse);
Jeff Sharkey9656a532013-09-13 13:42:19 -07001061 }
1062
Jeff Sharkey7d58fc62013-09-12 16:25:02 -07001063 if (summary != null) {
1064 if (docSummary != null) {
1065 summary.setText(docSummary);
1066 summary.setVisibility(View.VISIBLE);
1067 hasLine2 = true;
1068 } else {
1069 summary.setVisibility(View.INVISIBLE);
1070 }
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -07001071 }
Jeff Sharkey2e694f82013-08-06 16:26:14 -07001072 }
1073
Jeff Sharkey9656a532013-09-13 13:42:19 -07001074 if (icon1 != null) icon1.setVisibility(View.GONE);
1075 if (icon2 != null) icon2.setVisibility(View.GONE);
1076
1077 if (iconDrawable != null) {
1078 if (hasLine1) {
1079 icon1.setVisibility(View.VISIBLE);
1080 icon1.setImageDrawable(iconDrawable);
1081 } else {
1082 icon2.setVisibility(View.VISIBLE);
1083 icon2.setImageDrawable(iconDrawable);
1084 }
1085 }
1086
Jeff Sharkeyac9e6272013-08-31 21:27:44 -07001087 if (docLastModified == -1) {
Jeff Sharkey8a8fb672013-05-07 12:41:33 -07001088 date.setText(null);
1089 } else {
Steve McKayef280152015-06-11 10:10:49 -07001090 date.setText(formatTime(mContext, docLastModified));
Jeff Sharkey42d26792013-09-06 13:22:09 -07001091 hasLine2 = true;
Jeff Sharkey8a8fb672013-05-07 12:41:33 -07001092 }
Jeff Sharkey2e694f82013-08-06 16:26:14 -07001093
1094 if (state.showSize) {
1095 size.setVisibility(View.VISIBLE);
Jeff Sharkeyac9e6272013-08-31 21:27:44 -07001096 if (Document.MIME_TYPE_DIR.equals(docMimeType) || docSize == -1) {
Jeff Sharkey2e694f82013-08-06 16:26:14 -07001097 size.setText(null);
1098 } else {
Steve McKayef280152015-06-11 10:10:49 -07001099 size.setText(Formatter.formatFileSize(mContext, docSize));
Jeff Sharkey42d26792013-09-06 13:22:09 -07001100 hasLine2 = true;
Jeff Sharkey2e694f82013-08-06 16:26:14 -07001101 }
1102 } else {
1103 size.setVisibility(View.GONE);
Jeff Sharkey09c10bf2013-06-30 20:02:59 -07001104 }
Jeff Sharkeya5defe32013-08-05 17:56:48 -07001105
Jeff Sharkey9656a532013-09-13 13:42:19 -07001106 if (line1 != null) {
1107 line1.setVisibility(hasLine1 ? View.VISIBLE : View.GONE);
1108 }
Jeff Sharkey7d58fc62013-09-12 16:25:02 -07001109 if (line2 != null) {
1110 line2.setVisibility(hasLine2 ? View.VISIBLE : View.GONE);
1111 }
Jeff Sharkey42d26792013-09-06 13:22:09 -07001112
Steve McKayef280152015-06-11 10:10:49 -07001113 setEnabledRecursive(itemView, enabled);
Jeff Sharkey7e544612014-08-29 15:38:27 -07001114
1115 iconMime.setAlpha(iconAlpha);
1116 iconThumb.setAlpha(iconAlpha);
1117 if (icon1 != null) icon1.setAlpha(iconAlpha);
1118 if (icon2 != null) icon2.setAlpha(iconAlpha);
Jeff Sharkeyaed873d2013-09-09 16:51:06 -07001119
Steve McKay8e258c62015-05-06 14:27:57 -07001120 if (DEBUG_ENABLE_DND) {
Steve McKayef280152015-06-11 10:10:49 -07001121 setupDragAndDropOnDocumentView(itemView, cursor);
Steve McKay8e258c62015-05-06 14:27:57 -07001122 }
Jeff Sharkeye22d02e2013-04-26 16:54:55 -07001123 }
Jeff Sharkey09c10bf2013-06-30 20:02:59 -07001124
Steve McKay351a7492015-08-04 10:11:01 -07001125 @Override
Steve McKayef280152015-06-11 10:10:49 -07001126 public int getItemCount() {
Ben Kwa24be5d32015-08-27 16:04:46 -07001127 return mModel.getItemCount();
Jeff Sharkeyaed873d2013-09-09 16:51:06 -07001128 }
1129
Jeff Sharkey8a8fb672013-05-07 12:41:33 -07001130 }
1131
1132 private static String formatTime(Context context, long when) {
1133 // TODO: DateUtils should make this easier
1134 Time then = new Time();
1135 then.set(when);
1136 Time now = new Time();
1137 now.setToNow();
1138
1139 int flags = DateUtils.FORMAT_NO_NOON | DateUtils.FORMAT_NO_MIDNIGHT
1140 | DateUtils.FORMAT_ABBREV_ALL;
1141
1142 if (then.year != now.year) {
1143 flags |= DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_DATE;
1144 } else if (then.yearDay != now.yearDay) {
1145 flags |= DateUtils.FORMAT_SHOW_DATE;
1146 } else {
1147 flags |= DateUtils.FORMAT_SHOW_TIME;
1148 }
1149
1150 return DateUtils.formatDateTime(context, when, flags);
1151 }
Jeff Sharkeyb3620442013-09-01 18:41:04 -07001152
1153 private String findCommonMimeType(List<String> mimeTypes) {
1154 String[] commonType = mimeTypes.get(0).split("/");
1155 if (commonType.length != 2) {
1156 return "*/*";
1157 }
1158
1159 for (int i = 1; i < mimeTypes.size(); i++) {
1160 String[] type = mimeTypes.get(i).split("/");
1161 if (type.length != 2) continue;
1162
1163 if (!commonType[1].equals(type[1])) {
1164 commonType[1] = "*";
1165 }
1166
1167 if (!commonType[0].equals(type[0])) {
1168 commonType[0] = "*";
1169 commonType[1] = "*";
1170 break;
1171 }
1172 }
1173
1174 return commonType[0] + "/" + commonType[1];
1175 }
Jeff Sharkeyaed873d2013-09-09 16:51:06 -07001176
1177 private void setEnabledRecursive(View v, boolean enabled) {
Jeff Sharkey9656a532013-09-13 13:42:19 -07001178 if (v == null) return;
Jeff Sharkeyaed873d2013-09-09 16:51:06 -07001179 if (v.isEnabled() == enabled) return;
1180 v.setEnabled(enabled);
1181
1182 if (v instanceof ViewGroup) {
1183 final ViewGroup vg = (ViewGroup) v;
1184 for (int i = vg.getChildCount() - 1; i >= 0; i--) {
1185 setEnabledRecursive(vg.getChildAt(i), enabled);
1186 }
1187 }
1188 }
Jeff Sharkey7cf49032013-09-26 10:54:16 -07001189
1190 private boolean isDocumentEnabled(String docMimeType, int docFlags) {
1191 final State state = getDisplayState(DirectoryFragment.this);
1192
Jeff Sharkey7cf49032013-09-26 10:54:16 -07001193 // Directories are always enabled
1194 if (Document.MIME_TYPE_DIR.equals(docMimeType)) {
1195 return true;
1196 }
1197
Jeff Sharkey783ebc22013-09-26 19:42:52 -07001198 // Read-only files are disabled when creating
1199 if (state.action == ACTION_CREATE && (docFlags & Document.FLAG_SUPPORTS_WRITE) == 0) {
1200 return false;
1201 }
1202
Jeff Sharkey7cf49032013-09-26 10:54:16 -07001203 return MimePredicate.mimeMatches(state.acceptMimes, docMimeType);
1204 }
Vladislav Kaznacheev89b90332015-05-01 13:46:57 -07001205
Steve McKay1f199482015-05-20 15:58:42 -07001206 private void copyFromClipboard() {
1207 new AsyncTask<Void, Void, List<DocumentInfo>>() {
1208
1209 @Override
1210 protected List<DocumentInfo> doInBackground(Void... params) {
1211 return mClipper.getClippedDocuments();
1212 }
1213
1214 @Override
1215 protected void onPostExecute(List<DocumentInfo> docs) {
1216 DocumentInfo destination =
1217 ((BaseActivity) getActivity()).getCurrentDirectory();
1218 copyDocuments(docs, destination);
1219 }
1220 }.execute();
Steve McKay0599a442015-05-05 14:50:00 -07001221 }
1222
Steve McKay1f199482015-05-20 15:58:42 -07001223 private void copyFromClipData(final ClipData clipData, final DocumentInfo destination) {
Steve McKayef280152015-06-11 10:10:49 -07001224 checkNotNull(clipData);
Steve McKay1f199482015-05-20 15:58:42 -07001225 new AsyncTask<Void, Void, List<DocumentInfo>>() {
Vladislav Kaznacheev89b90332015-05-01 13:46:57 -07001226
Steve McKay1f199482015-05-20 15:58:42 -07001227 @Override
1228 protected List<DocumentInfo> doInBackground(Void... params) {
1229 return mClipper.getDocumentsFromClipData(clipData);
1230 }
1231
1232 @Override
1233 protected void onPostExecute(List<DocumentInfo> docs) {
1234 copyDocuments(docs, destination);
1235 }
1236 }.execute();
1237 }
1238
1239 private void copyDocuments(final List<DocumentInfo> docs, final DocumentInfo destination) {
1240 if (!canCopy(docs, destination)) {
1241 Toast.makeText(
1242 getActivity(),
1243 R.string.clipboard_files_cannot_paste, Toast.LENGTH_SHORT).show();
Steve McKay0599a442015-05-05 14:50:00 -07001244 return;
1245 }
1246
Steve McKay1f199482015-05-20 15:58:42 -07001247 if (docs.isEmpty()) {
Vladislav Kaznacheev89b90332015-05-01 13:46:57 -07001248 return;
Vladislav Kaznacheeve16887a2015-05-05 12:09:47 -07001249 }
Vladislav Kaznacheev89b90332015-05-01 13:46:57 -07001250
Steve McKay1f199482015-05-20 15:58:42 -07001251 final DocumentStack curStack = getDisplayState(DirectoryFragment.this).stack;
Vladislav Kaznacheev89b90332015-05-01 13:46:57 -07001252 DocumentStack tmpStack = new DocumentStack();
Steve McKay1f199482015-05-20 15:58:42 -07001253 if (destination != null) {
1254 tmpStack.push(destination);
Vladislav Kaznacheev89b90332015-05-01 13:46:57 -07001255 tmpStack.addAll(curStack);
1256 } else {
1257 tmpStack = curStack;
1258 }
1259
Steve McKay1f199482015-05-20 15:58:42 -07001260 CopyService.start(getActivity(), docs, tmpStack, CopyService.TRANSFER_MODE_COPY);
Vladislav Kaznacheev89b90332015-05-01 13:46:57 -07001261 }
1262
1263 private ClipData getClipDataFromDocuments(List<DocumentInfo> docs) {
1264 Context context = getActivity();
1265 final ContentResolver resolver = context.getContentResolver();
1266 ClipData clipData = null;
1267 for (DocumentInfo doc : docs) {
1268 final Uri uri = DocumentsContract.buildDocumentUri(doc.authority, doc.documentId);
1269 if (clipData == null) {
Vladislav Kaznacheeve16887a2015-05-05 12:09:47 -07001270 // TODO: figure out what this string should be.
1271 // Currently it is not displayed anywhere in the UI, but this might change.
1272 final String label = "";
1273 clipData = ClipData.newUri(resolver, label, uri);
Vladislav Kaznacheev89b90332015-05-01 13:46:57 -07001274 } else {
1275 // TODO: update list of mime types in ClipData.
1276 clipData.addItem(new ClipData.Item(uri));
1277 }
1278 }
1279 return clipData;
1280 }
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001281
Steve McKay1f199482015-05-20 15:58:42 -07001282 void copySelectedToClipboard() {
Ben Kwa24be5d32015-08-27 16:04:46 -07001283 Selection sel = mModel.getSelection(new Selection());
Steve McKayef280152015-06-11 10:10:49 -07001284 copySelectionToClipboard(sel);
Steve McKay9276f3b2015-05-27 16:11:42 -07001285 }
Steve McKay0599a442015-05-05 14:50:00 -07001286
Steve McKayef280152015-06-11 10:10:49 -07001287 void copySelectionToClipboard(Selection items) {
Steve McKay9276f3b2015-05-27 16:11:42 -07001288 new GetDocumentsTask() {
1289 @Override
1290 void onDocumentsReady(List<DocumentInfo> docs) {
1291 mClipper.clipDocuments(docs);
Steve McKay1f199482015-05-20 15:58:42 -07001292 Activity activity = getActivity();
1293 Toast.makeText(activity,
1294 activity.getResources().getQuantityString(
1295 R.plurals.clipboard_files_clipped, docs.size(), docs.size()),
1296 Toast.LENGTH_SHORT).show();
Steve McKay9276f3b2015-05-27 16:11:42 -07001297 }
Steve McKayef280152015-06-11 10:10:49 -07001298 }.execute(items);
Steve McKay0599a442015-05-05 14:50:00 -07001299 }
1300
1301 void pasteFromClipboard() {
Steve McKay1f199482015-05-20 15:58:42 -07001302 copyFromClipboard();
1303 getActivity().invalidateOptionsMenu();
Steve McKay0599a442015-05-05 14:50:00 -07001304 }
1305
Steve McKay0599a442015-05-05 14:50:00 -07001306 /**
1307 * Returns true if the list of files can be copied to destination. Note that this
1308 * is a policy check only. Currently the method does not attempt to verify
1309 * available space or any other environmental aspects possibly resulting in
1310 * failure to copy.
1311 *
1312 * @return true if the list of files can be copied to destination.
1313 */
1314 boolean canCopy(List<DocumentInfo> files, DocumentInfo dest) {
Ben Kwa91923182015-08-27 16:06:33 -07001315 BaseActivity activity = (BaseActivity) getActivity();
Steve McKay0599a442015-05-05 14:50:00 -07001316
1317 final RootInfo root = activity.getCurrentRoot();
1318
1319 // Can't copy folders to Downloads.
1320 if (root.isDownloads()) {
1321 for (DocumentInfo docs : files) {
1322 if (docs.isDirectory()) {
1323 return false;
1324 }
1325 }
1326 }
1327
1328 return dest != null && dest.isDirectory() && dest.isCreateSupported();
1329 }
1330
1331 void selectAllFiles() {
Ben Kwa24be5d32015-08-27 16:04:46 -07001332 boolean changed = mModel.selectAll();
Steve McKay9459a7c2015-07-24 13:14:20 -07001333 if (changed) {
1334 updateDisplayState();
1335 }
Steve McKay0599a442015-05-05 14:50:00 -07001336 }
1337
Steve McKayef280152015-06-11 10:10:49 -07001338 private void setupDragAndDropOnDirectoryView(View view) {
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001339 // Listen for drops on non-directory items and empty space.
1340 view.setOnDragListener(mOnDragListener);
1341 }
1342
1343 private void setupDragAndDropOnDocumentView(View view, Cursor cursor) {
1344 final String docMimeType = getCursorString(cursor, Document.COLUMN_MIME_TYPE);
1345 if (Document.MIME_TYPE_DIR.equals(docMimeType)) {
1346 // Make a directory item a drop target. Drop on non-directories and empty space
1347 // is handled at the list/grid view level.
1348 view.setOnDragListener(mOnDragListener);
1349 }
1350
1351 // Temporary: attaching the listener to the title only.
1352 // Attaching to the entire item conflicts with the item long click handler responsible
1353 // for item selection.
1354 final View title = view.findViewById(android.R.id.title);
1355 title.setOnLongClickListener(mLongClickListener);
1356 }
1357
1358 private View.OnDragListener mOnDragListener = new View.OnDragListener() {
1359 @Override
1360 public boolean onDrag(View v, DragEvent event) {
1361 switch (event.getAction()) {
1362 case DragEvent.ACTION_DRAG_STARTED:
1363 // TODO: Check if the event contains droppable data.
1364 return true;
1365
1366 // TODO: Highlight potential drop target directory?
1367 // TODO: Expand drop target directory on hover?
1368 case DragEvent.ACTION_DRAG_ENTERED:
1369 case DragEvent.ACTION_DRAG_LOCATION:
1370 case DragEvent.ACTION_DRAG_EXITED:
1371 case DragEvent.ACTION_DRAG_ENDED:
1372 return true;
1373
1374 case DragEvent.ACTION_DROP:
Vladislav Kaznacheev9400b892015-09-04 09:17:37 -07001375 int dstPosition = mRecView.getChildAdapterPosition(getContainingItemView(v));
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001376 DocumentInfo dstDir = null;
1377 if (dstPosition != android.widget.AdapterView.INVALID_POSITION) {
Ben Kwa24be5d32015-08-27 16:04:46 -07001378 Cursor dstCursor = mModel.getItem(dstPosition);
Steve McKayef280152015-06-11 10:10:49 -07001379 checkNotNull(dstCursor, "Cursor cannot be null.");
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001380 dstDir = DocumentInfo.fromDirectoryCursor(dstCursor);
1381 // TODO: Do not drop into the directory where the documents came from.
1382 }
1383 copyFromClipData(event.getClipData(), dstDir);
1384 return true;
1385 }
1386 return false;
1387 }
1388 };
1389
Vladislav Kaznacheev9400b892015-09-04 09:17:37 -07001390 private View getContainingItemView(View view) {
1391 while (true) {
1392 if (view.getLayoutParams() instanceof RecyclerView.LayoutParams) {
1393 return view;
1394 }
1395 ViewParent parent = view.getParent();
1396 if (parent == null || !(parent instanceof View)) {
1397 return null;
1398 }
1399 view = (View) parent;
1400 }
1401 }
1402
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001403 private View.OnLongClickListener mLongClickListener = new View.OnLongClickListener() {
1404 @Override
1405 public boolean onLongClick(View v) {
1406 final List<DocumentInfo> docs = getDraggableDocuments(v);
1407 if (docs.isEmpty()) {
1408 return false;
1409 }
1410 v.startDrag(
1411 getClipDataFromDocuments(docs),
1412 new DrawableShadowBuilder(getDragShadowIcon(docs)),
1413 null,
Vladislav Kaznacheeve3ce8a92015-07-15 18:04:04 -07001414 View.DRAG_FLAG_GLOBAL | View.DRAG_FLAG_GLOBAL_URI_READ |
1415 View.DRAG_FLAG_GLOBAL_URI_WRITE
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001416 );
1417 return true;
1418 }
1419 };
1420
1421 private List<DocumentInfo> getDraggableDocuments(View currentItemView) {
Vladislav Kaznacheev9400b892015-09-04 09:17:37 -07001422 int position = mRecView.getChildAdapterPosition(getContainingItemView(currentItemView));
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001423 if (position == android.widget.AdapterView.INVALID_POSITION) {
1424 return Collections.EMPTY_LIST;
1425 }
1426
Ben Kwa24be5d32015-08-27 16:04:46 -07001427 final List<DocumentInfo> selectedDocs = mModel.getSelectedDocuments();
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001428 if (!selectedDocs.isEmpty()) {
Ben Kwa24be5d32015-08-27 16:04:46 -07001429 if (!mModel.isSelected(position)) {
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001430 // There is a selection that does not include the current item, drag nothing.
1431 return Collections.EMPTY_LIST;
1432 }
1433 return selectedDocs;
1434 }
1435
Ben Kwa24be5d32015-08-27 16:04:46 -07001436 final Cursor cursor = mModel.getItem(position);
Steve McKayef280152015-06-11 10:10:49 -07001437 checkNotNull(cursor, "Cursor cannot be null.");
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001438 final DocumentInfo doc = DocumentInfo.fromDirectoryCursor(cursor);
Steve McKayfefcd702015-08-20 16:19:38 +00001439
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001440 return Lists.newArrayList(doc);
1441 }
1442
1443 private Drawable getDragShadowIcon(List<DocumentInfo> docs) {
1444 if (docs.size() == 1) {
1445 final DocumentInfo doc = docs.get(0);
1446 return getDocumentIcon(getActivity(), doc.authority, doc.documentId,
1447 doc.mimeType, doc.icon, getDisplayState(this));
1448 }
1449 return getActivity().getDrawable(R.drawable.ic_doc_generic);
1450 }
1451
1452 public static Drawable getDocumentIcon(Context context, String docAuthority, String docId,
1453 String docMimeType, int docIcon, State state) {
1454 if (docIcon != 0) {
1455 return IconUtils.loadPackageIcon(context, docAuthority, docIcon);
1456 } else {
1457 return IconUtils.loadMimeIcon(context, docMimeType, docAuthority, docId,
1458 state.derivedMode);
1459 }
1460 }
1461
Steve McKayef280152015-06-11 10:10:49 -07001462 private static class ThumbnailAsyncTask extends AsyncTask<Uri, Void, Bitmap>
1463 implements Preemptable {
1464 private final Uri mUri;
1465 private final ImageView mIconMime;
1466 private final ImageView mIconThumb;
1467 private final Point mThumbSize;
1468 private final float mTargetAlpha;
1469 private final CancellationSignal mSignal;
1470
1471 public ThumbnailAsyncTask(Uri uri, ImageView iconMime, ImageView iconThumb, Point thumbSize,
1472 float targetAlpha) {
1473 mUri = uri;
1474 mIconMime = iconMime;
1475 mIconThumb = iconThumb;
1476 mThumbSize = thumbSize;
1477 mTargetAlpha = targetAlpha;
1478 mSignal = new CancellationSignal();
1479 }
1480
1481 @Override
1482 public void preempt() {
1483 cancel(false);
1484 mSignal.cancel();
1485 }
1486
1487 @Override
1488 protected Bitmap doInBackground(Uri... params) {
1489 if (isCancelled()) return null;
1490
1491 final Context context = mIconThumb.getContext();
1492 final ContentResolver resolver = context.getContentResolver();
1493
1494 ContentProviderClient client = null;
1495 Bitmap result = null;
1496 try {
1497 client = DocumentsApplication.acquireUnstableProviderOrThrow(
1498 resolver, mUri.getAuthority());
1499 result = DocumentsContract.getDocumentThumbnail(client, mUri, mThumbSize, mSignal);
1500 if (result != null) {
1501 final ThumbnailCache thumbs = DocumentsApplication.getThumbnailsCache(
1502 context, mThumbSize);
1503 thumbs.put(mUri, result);
1504 }
1505 } catch (Exception e) {
1506 if (!(e instanceof OperationCanceledException)) {
1507 Log.w(TAG, "Failed to load thumbnail for " + mUri + ": " + e);
1508 }
1509 } finally {
1510 ContentProviderClient.releaseQuietly(client);
1511 }
1512 return result;
1513 }
1514
1515 @Override
1516 protected void onPostExecute(Bitmap result) {
1517 if (mIconThumb.getTag() == this && result != null) {
1518 mIconThumb.setTag(null);
1519 mIconThumb.setImageBitmap(result);
1520
1521 mIconMime.setAlpha(mTargetAlpha);
1522 mIconMime.animate().alpha(0f).start();
1523 mIconThumb.setAlpha(0f);
1524 mIconThumb.animate().alpha(mTargetAlpha).start();
1525 }
1526 }
1527 }
1528
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001529 private class DrawableShadowBuilder extends View.DragShadowBuilder {
1530
1531 private final Drawable mShadow;
1532
1533 private final int mShadowDimension;
1534
1535 public DrawableShadowBuilder(Drawable shadow) {
1536 mShadow = shadow;
1537 mShadowDimension = getResources().getDimensionPixelSize(
1538 R.dimen.drag_shadow_size);
1539 mShadow.setBounds(0, 0, mShadowDimension, mShadowDimension);
1540 }
1541
Ben Kwa24be5d32015-08-27 16:04:46 -07001542 @Override
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001543 public void onProvideShadowMetrics(
1544 Point shadowSize, Point shadowTouchPoint) {
1545 shadowSize.set(mShadowDimension, mShadowDimension);
1546 shadowTouchPoint.set(mShadowDimension / 2, mShadowDimension / 2);
1547 }
1548
Ben Kwa24be5d32015-08-27 16:04:46 -07001549 @Override
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001550 public void onDrawShadow(Canvas canvas) {
1551 mShadow.draw(canvas);
1552 }
1553 }
Steve McKay1f199482015-05-20 15:58:42 -07001554
1555 private FragmentTuner pickFragmentTuner(final State state) {
1556 return state.action == ACTION_BROWSE_ALL
Steve McKay0fbfc652015-08-20 16:48:49 -07001557 ? new FilesTuner()
Steve McKay1f199482015-05-20 15:58:42 -07001558 : new DefaultTuner(state);
1559 }
1560
1561 /**
1562 * Interface for specializing the Fragment for the "host" Activity.
1563 * Feel free to expand the role of this class to handle other specializations.
1564 */
1565 private interface FragmentTuner {
Steve McKay4f4232d2015-07-22 12:13:46 -07001566 void updateActionMenu(Menu menu, int dirType, boolean canDelete);
Kyle Horimoto426bd0d2015-07-29 15:33:49 -07001567 void afterActivityCreated(DirectoryFragment fragment);
Steve McKay1f199482015-05-20 15:58:42 -07001568 }
1569
1570 /**
Steve McKay9276f3b2015-05-27 16:11:42 -07001571 * Abstract task providing support for loading documents *off*
1572 * the main thread. And if it isn't obvious, creating a list
1573 * of documents (especially large lists) can be pretty expensive.
1574 */
1575 private abstract class GetDocumentsTask
Steve McKayef280152015-06-11 10:10:49 -07001576 extends AsyncTask<Selection, Void, List<DocumentInfo>> {
Steve McKay9276f3b2015-05-27 16:11:42 -07001577 @Override
Steve McKayef280152015-06-11 10:10:49 -07001578 protected final List<DocumentInfo> doInBackground(Selection... selected) {
Ben Kwa24be5d32015-08-27 16:04:46 -07001579 return mModel.getDocuments(selected[0]);
Steve McKay9276f3b2015-05-27 16:11:42 -07001580 }
1581
1582 @Override
1583 protected final void onPostExecute(List<DocumentInfo> docs) {
1584 onDocumentsReady(docs);
1585 }
1586
1587 abstract void onDocumentsReady(List<DocumentInfo> docs);
1588 }
1589
1590 /**
Steve McKay1f199482015-05-20 15:58:42 -07001591 * Provides support for Platform specific specializations of DirectoryFragment.
1592 */
1593 private static final class DefaultTuner implements FragmentTuner {
1594
1595 private final State mState;
1596
1597 public DefaultTuner(State state) {
1598 mState = state;
1599 }
1600
1601 @Override
Steve McKay4f4232d2015-07-22 12:13:46 -07001602 public void updateActionMenu(Menu menu, int dirType, boolean canDelete) {
Steve McKay1f199482015-05-20 15:58:42 -07001603 Preconditions.checkState(mState.action != ACTION_BROWSE_ALL);
1604
1605 final MenuItem open = menu.findItem(R.id.menu_open);
1606 final MenuItem share = menu.findItem(R.id.menu_share);
1607 final MenuItem delete = menu.findItem(R.id.menu_delete);
1608 final MenuItem copyTo = menu.findItem(R.id.menu_copy_to);
1609 final MenuItem moveTo = menu.findItem(R.id.menu_move_to);
1610 final MenuItem copyToClipboard = menu.findItem(R.id.menu_copy_to_clipboard);
1611
1612 final boolean manageOrBrowse = (mState.action == ACTION_MANAGE
1613 || mState.action == ACTION_BROWSE);
1614
1615 open.setVisible(!manageOrBrowse);
1616 share.setVisible(manageOrBrowse);
Steve McKay4f4232d2015-07-22 12:13:46 -07001617 delete.setVisible(manageOrBrowse && canDelete);
Steve McKay1f199482015-05-20 15:58:42 -07001618 // Disable copying from the Recents view.
1619 copyTo.setVisible(manageOrBrowse && dirType != TYPE_RECENT_OPEN);
1620 moveTo.setVisible(SystemProperties.getBoolean("debug.documentsui.enable_move", false));
1621
Steve McKay0fbfc652015-08-20 16:48:49 -07001622 // Only shown in files mode.
Steve McKay1f199482015-05-20 15:58:42 -07001623 copyToClipboard.setVisible(false);
1624 }
Kyle Horimoto426bd0d2015-07-29 15:33:49 -07001625
1626 @Override
1627 public void afterActivityCreated(DirectoryFragment fragment) {}
Steve McKay1f199482015-05-20 15:58:42 -07001628 }
1629
1630 /**
Steve McKay0fbfc652015-08-20 16:48:49 -07001631 * Provides support for Files activity specific specializations of DirectoryFragment.
Steve McKay1f199482015-05-20 15:58:42 -07001632 */
Steve McKay0fbfc652015-08-20 16:48:49 -07001633 private static final class FilesTuner implements FragmentTuner {
Steve McKay1f199482015-05-20 15:58:42 -07001634 @Override
Steve McKay4f4232d2015-07-22 12:13:46 -07001635 public void updateActionMenu(Menu menu, int dirType, boolean canDelete) {
Steve McKay1f199482015-05-20 15:58:42 -07001636 menu.findItem(R.id.menu_share).setVisible(true);
Steve McKay4f4232d2015-07-22 12:13:46 -07001637 menu.findItem(R.id.menu_delete).setVisible(canDelete);
Steve McKay1f199482015-05-20 15:58:42 -07001638 menu.findItem(R.id.menu_copy_to_clipboard).setVisible(true);
1639
1640 menu.findItem(R.id.menu_open).setVisible(false);
1641 menu.findItem(R.id.menu_copy_to).setVisible(false);
1642 menu.findItem(R.id.menu_move_to).setVisible(false);
1643 }
Kyle Horimoto426bd0d2015-07-29 15:33:49 -07001644
1645 @Override
Kyle Horimoto62a7fd02015-08-18 13:25:29 -07001646 public void afterActivityCreated(DirectoryFragment fragment) {}
Steve McKay1f199482015-05-20 15:58:42 -07001647 }
Ben Kwa24be5d32015-08-27 16:04:46 -07001648
1649 /**
1650 * The data model for the current loaded directory.
1651 */
Ben Kwa7461a952015-09-01 11:03:01 -07001652 @VisibleForTesting
1653 public static final class Model implements DocumentContext {
Ben Kwa24be5d32015-08-27 16:04:46 -07001654 private MultiSelectManager mSelectionManager;
Ben Kwa379e1762015-09-21 10:49:52 -07001655 private RecyclerView.Adapter<?> mViewAdapter;
Ben Kwa7461a952015-09-01 11:03:01 -07001656 private Context mContext;
Ben Kwa24be5d32015-08-27 16:04:46 -07001657 private int mCursorCount;
1658 private boolean mIsLoading;
Ben Kwa7461a952015-09-01 11:03:01 -07001659 private SparseBooleanArray mMarkedForDeletion = new SparseBooleanArray();
1660 private UpdateListener mUpdateListener;
Ben Kwa24be5d32015-08-27 16:04:46 -07001661 @Nullable private Cursor mCursor;
1662 @Nullable private String info;
1663 @Nullable private String error;
Ben Kwa7461a952015-09-01 11:03:01 -07001664
Ben Kwa379e1762015-09-21 10:49:52 -07001665 Model(Context context, MultiSelectManager selectionManager,
1666 RecyclerView.Adapter<?> viewAdapter) {
Ben Kwa7461a952015-09-01 11:03:01 -07001667 mContext = context;
1668 mSelectionManager = selectionManager;
Ben Kwa379e1762015-09-21 10:49:52 -07001669 mViewAdapter = viewAdapter;
Ben Kwa24be5d32015-08-27 16:04:46 -07001670 }
1671
1672 /**
1673 * Selects all files in the current directory.
1674 * @return true if the selection state changed for any files.
1675 */
1676 boolean selectAll() {
1677 return mSelectionManager.setItemsSelected(0, mCursorCount, true);
1678 }
1679
1680 /**
1681 * Clones the current selection into the given Selection object.
1682 * @param selection
1683 * @return The selection that was passed in, for convenience.
1684 */
1685 Selection getSelection(Selection selection) {
1686 return mSelectionManager.getSelection(selection);
1687 }
1688
1689 /**
1690 * @return The current selection (the live instance, not a copy).
1691 */
1692 Selection getSelection() {
1693 return mSelectionManager.getSelection();
1694 }
1695
1696 boolean isSelected(int position) {
1697 return mSelectionManager.getSelection().contains(position);
1698 }
1699
1700 void clearSelection() {
1701 mSelectionManager.clearSelection();
1702 }
1703
1704 void update(DirectoryResult result) {
1705 if (DEBUG) Log.i(TAG, "Updating model with new result set.");
1706
1707 if (result == null) {
1708 mCursor = null;
1709 mCursorCount = 0;
1710 info = null;
1711 error = null;
1712 mIsLoading = false;
Ben Kwa83cedf22015-09-11 15:15:45 -07001713 mUpdateListener.onModelUpdate(this);
Ben Kwa24be5d32015-08-27 16:04:46 -07001714 return;
1715 }
1716
1717 if (result.exception != null) {
1718 Log.e(TAG, "Error while loading directory contents", result.exception);
Ben Kwa83cedf22015-09-11 15:15:45 -07001719 mUpdateListener.onModelUpdateFailed(result.exception);
Ben Kwa24be5d32015-08-27 16:04:46 -07001720 return;
1721 }
1722
1723 mCursor = result.cursor;
1724 mCursorCount = mCursor.getCount();
1725
1726 final Bundle extras = mCursor.getExtras();
1727 if (extras != null) {
1728 info = extras.getString(DocumentsContract.EXTRA_INFO);
1729 error = extras.getString(DocumentsContract.EXTRA_ERROR);
1730 mIsLoading = extras.getBoolean(DocumentsContract.EXTRA_LOADING, false);
1731 }
Ben Kwa7461a952015-09-01 11:03:01 -07001732
Ben Kwa83cedf22015-09-11 15:15:45 -07001733 mUpdateListener.onModelUpdate(this);
Ben Kwa24be5d32015-08-27 16:04:46 -07001734 }
1735
Ben Kwa7461a952015-09-01 11:03:01 -07001736 int getItemCount() {
Ben Kwa91923182015-08-27 16:06:33 -07001737 return mCursorCount - mMarkedForDeletion.size();
Ben Kwa24be5d32015-08-27 16:04:46 -07001738 }
1739
Ben Kwa7461a952015-09-01 11:03:01 -07001740 Cursor getItem(int position) {
Ben Kwa91923182015-08-27 16:06:33 -07001741 // Items marked for deletion are masked out of the UI. To do this, for every marked
1742 // item whose position is less than the requested item position, advance the requested
1743 // position by 1.
1744 final int originalPos = position;
1745 final int size = mMarkedForDeletion.size();
Ben Kwa0d0daff2015-09-09 13:49:07 -07001746 for (int i = 0; i < size; ++i) {
Ben Kwa91923182015-08-27 16:06:33 -07001747 // It'd be more concise, but less efficient, to iterate over positions while calling
1748 // mMarkedForDeletion.get. Instead, iterate over deleted entries.
1749 if (mMarkedForDeletion.keyAt(i) <= position && mMarkedForDeletion.valueAt(i)) {
1750 ++position;
1751 }
1752 }
1753
1754 if (DEBUG) {
1755 Log.d(TAG, "Item position adjusted for deletion. Original: " + originalPos
1756 + " Adjusted: " + position);
1757 }
1758
Ben Kwa24be5d32015-08-27 16:04:46 -07001759 if (position >= mCursorCount) {
1760 throw new IndexOutOfBoundsException("Attempt to retrieve " + position + " of " +
1761 mCursorCount + " items");
1762 }
1763
1764 mCursor.moveToPosition(position);
1765 return mCursor;
1766 }
1767
1768 private boolean isEmpty() {
1769 return mCursorCount == 0;
1770 }
1771
1772 private boolean isLoading() {
1773 return mIsLoading;
1774 }
1775
1776 private List<DocumentInfo> getSelectedDocuments() {
1777 Selection sel = getSelection(new Selection());
1778 return getDocuments(sel);
1779 }
1780
Ben Kwa7461a952015-09-01 11:03:01 -07001781 List<DocumentInfo> getDocuments(Selection items) {
Ben Kwa91923182015-08-27 16:06:33 -07001782 final int size = (items != null) ? items.size() : 0;
Ben Kwa24be5d32015-08-27 16:04:46 -07001783
Ben Kwa91923182015-08-27 16:06:33 -07001784 final List<DocumentInfo> docs = new ArrayList<>(size);
Ben Kwa24be5d32015-08-27 16:04:46 -07001785 for (int i = 0; i < size; i++) {
1786 final Cursor cursor = getItem(items.get(i));
1787 checkNotNull(cursor, "Cursor cannot be null.");
1788 final DocumentInfo doc = DocumentInfo.fromDirectoryCursor(cursor);
1789 docs.add(doc);
1790 }
1791 return docs;
1792 }
1793
1794 @Override
1795 public Cursor getCursor() {
1796 if (Looper.myLooper() != Looper.getMainLooper()) {
1797 throw new IllegalStateException("Can't call getCursor from non-main thread.");
1798 }
1799 return mCursor;
1800 }
Ben Kwa91923182015-08-27 16:06:33 -07001801
Ben Kwa7461a952015-09-01 11:03:01 -07001802 List<DocumentInfo> getDocumentsMarkedForDeletion() {
Ben Kwa91923182015-08-27 16:06:33 -07001803 final int size = mMarkedForDeletion.size();
1804 List<DocumentInfo> docs = new ArrayList<>(size);
1805
1806 for (int i = 0; i < size; ++i) {
1807 final int position = mMarkedForDeletion.keyAt(i);
1808 checkState(position < mCursorCount);
1809 mCursor.moveToPosition(position);
1810 final DocumentInfo doc = DocumentInfo.fromDirectoryCursor(mCursor);
1811 docs.add(doc);
1812 }
1813 return docs;
1814 }
1815
1816 /**
1817 * Marks the given files for deletion. This will remove them from the UI. Clients must then
1818 * call either {@link #undoDeletion()} or {@link #finalizeDeletion()} to cancel or confirm
1819 * the deletion, respectively. Only one deletion operation is allowed at a time.
1820 *
1821 * @param selected A selection representing the files to delete.
1822 */
Ben Kwa7461a952015-09-01 11:03:01 -07001823 void markForDeletion(Selection selected) {
Ben Kwa91923182015-08-27 16:06:33 -07001824 // Only one deletion operation at a time.
1825 checkState(mMarkedForDeletion.size() == 0);
1826 // There should never be more to delete than what exists.
1827 checkState(mCursorCount >= selected.size());
1828
1829 final int size = selected.size();
1830 for (int i = 0; i < size; ++i) {
1831 int position = selected.get(i);
1832 if (DEBUG) Log.d(TAG, "Marked position " + position + " for deletion");
1833 mMarkedForDeletion.append(position, true);
Ben Kwa379e1762015-09-21 10:49:52 -07001834 mViewAdapter.notifyItemRemoved(position);
Ben Kwa91923182015-08-27 16:06:33 -07001835 }
1836 }
1837
1838 /**
1839 * Cancels an ongoing deletion operation. All files currently marked for deletion will be
1840 * unmarked, and restored in the UI. See {@link #markForDeletion(Selection)}.
1841 */
Ben Kwa7461a952015-09-01 11:03:01 -07001842 void undoDeletion() {
Ben Kwa91923182015-08-27 16:06:33 -07001843 // Iterate over deleted items, temporarily marking them false in the deletion list, and
1844 // re-adding them to the UI.
1845 final int size = mMarkedForDeletion.size();
1846 for (int i = 0; i < size; ++i) {
1847 final int position = mMarkedForDeletion.keyAt(i);
1848 mMarkedForDeletion.put(position, false);
Ben Kwa379e1762015-09-21 10:49:52 -07001849 mViewAdapter.notifyItemInserted(position);
Ben Kwa91923182015-08-27 16:06:33 -07001850 }
1851
1852 // Then, clear the deletion list.
1853 mMarkedForDeletion.clear();
1854 }
1855
1856 /**
1857 * Finalizes an ongoing deletion operation. All files currently marked for deletion will be
1858 * deleted. See {@link #markForDeletion(Selection)}.
Ben Kwa7461a952015-09-01 11:03:01 -07001859 *
1860 * @param view The view which will be used to interact with the user (e.g. surfacing
1861 * snackbars) for errors, info, etc.
Ben Kwa91923182015-08-27 16:06:33 -07001862 */
Ben Kwa83cedf22015-09-11 15:15:45 -07001863 void finalizeDeletion(Runnable errorCallback) {
Ben Kwa7461a952015-09-01 11:03:01 -07001864 final ContentResolver resolver = mContext.getContentResolver();
Ben Kwa83cedf22015-09-11 15:15:45 -07001865 DeleteFilesTask task = new DeleteFilesTask(resolver, errorCallback);
Ben Kwa7461a952015-09-01 11:03:01 -07001866 task.execute();
Ben Kwa91923182015-08-27 16:06:33 -07001867 }
1868
1869 /**
1870 * A Task which collects the DocumentInfo for documents that have been marked for deletion,
1871 * and actually deletes them.
1872 */
1873 private class DeleteFilesTask extends AsyncTask<Void, Void, List<DocumentInfo>> {
1874 private ContentResolver mResolver;
Ben Kwa7461a952015-09-01 11:03:01 -07001875 private Runnable mErrorCallback;
Ben Kwa91923182015-08-27 16:06:33 -07001876
Ben Kwa7461a952015-09-01 11:03:01 -07001877 /**
1878 * @param resolver A ContentResolver for performing the actual file deletions.
1879 * @param errorCallback A Runnable that is executed in the event that one or more errors
1880 * occured while copying files. Execution will occur on the UI thread.
1881 */
1882 public DeleteFilesTask(ContentResolver resolver, Runnable errorCallback) {
Ben Kwa91923182015-08-27 16:06:33 -07001883 mResolver = resolver;
Ben Kwa7461a952015-09-01 11:03:01 -07001884 mErrorCallback = errorCallback;
Ben Kwa91923182015-08-27 16:06:33 -07001885 }
1886
1887 @Override
1888 protected List<DocumentInfo> doInBackground(Void... params) {
1889 return getDocumentsMarkedForDeletion();
1890 }
1891
1892 @Override
1893 protected void onPostExecute(List<DocumentInfo> docs) {
1894 boolean hadTrouble = false;
1895 for (DocumentInfo doc : docs) {
1896 if (!doc.isDeleteSupported()) {
1897 Log.w(TAG, doc + " could not be deleted. Skipping...");
1898 hadTrouble = true;
1899 continue;
1900 }
1901
1902 ContentProviderClient client = null;
1903 try {
1904 if (DEBUG) Log.d(TAG, "Deleting: " + doc.displayName);
1905 client = DocumentsApplication.acquireUnstableProviderOrThrow(
1906 mResolver, doc.derivedUri.getAuthority());
1907 DocumentsContract.deleteDocument(client, doc.derivedUri);
1908 } catch (Exception e) {
1909 Log.w(TAG, "Failed to delete " + doc);
1910 hadTrouble = true;
1911 } finally {
1912 ContentProviderClient.releaseQuietly(client);
1913 }
1914 }
1915
1916 if (hadTrouble) {
Ben Kwa7461a952015-09-01 11:03:01 -07001917 // TODO show which files failed? b/23720103
1918 mErrorCallback.run();
Ben Kwa91923182015-08-27 16:06:33 -07001919 if (DEBUG) Log.d(TAG, "Deletion task completed. Some deletions failed.");
1920 } else {
1921 if (DEBUG) Log.d(TAG, "Deletion task completed successfully.");
1922 }
1923 mMarkedForDeletion.clear();
1924 }
1925 }
Ben Kwa7461a952015-09-01 11:03:01 -07001926
1927 void addUpdateListener(UpdateListener listener) {
1928 checkState(mUpdateListener == null);
1929 mUpdateListener = listener;
1930 }
1931
Ben Kwa379e1762015-09-21 10:49:52 -07001932 static class UpdateListener {
Ben Kwa7461a952015-09-01 11:03:01 -07001933 /**
1934 * Called when a successful update has occurred.
1935 */
Ben Kwa379e1762015-09-21 10:49:52 -07001936 void onModelUpdate(Model model) {}
Ben Kwa7461a952015-09-01 11:03:01 -07001937
1938 /**
1939 * Called when an update has been attempted but failed.
1940 */
Ben Kwa379e1762015-09-21 10:49:52 -07001941 void onModelUpdateFailed(Exception e) {}
1942 }
1943 }
Ben Kwa7461a952015-09-01 11:03:01 -07001944
Ben Kwa379e1762015-09-21 10:49:52 -07001945 private class ModelUpdateListener extends Model.UpdateListener {
1946 @Override
1947 public void onModelUpdate(Model model) {
1948 if (model.info != null || model.error != null) {
1949 mMessageBar.setInfo(model.info);
1950 mMessageBar.setError(model.error);
1951 mMessageBar.show();
1952 }
Ben Kwa7461a952015-09-01 11:03:01 -07001953
Ben Kwa379e1762015-09-21 10:49:52 -07001954 mProgressBar.setVisibility(model.isLoading() ? View.VISIBLE : View.GONE);
1955
1956 if (model.isEmpty()) {
1957 mEmptyView.setVisibility(View.VISIBLE);
1958 mRecView.setVisibility(View.GONE);
1959 } else {
1960 mEmptyView.setVisibility(View.GONE);
1961 mRecView.setVisibility(View.VISIBLE);
1962 }
1963
1964 mAdapter.notifyDataSetChanged();
1965 }
1966
1967 @Override
1968 public void onModelUpdateFailed(Exception e) {
1969 // TODO: deal with catastrophic update failures
1970 String error = getString(R.string.query_error);
1971 mAdapter.notifyDataSetChanged();
Ben Kwa7461a952015-09-01 11:03:01 -07001972 }
Ben Kwa24be5d32015-08-27 16:04:46 -07001973 }
Jeff Sharkeye22d02e2013-04-26 16:54:55 -07001974}