blob: 89deb9789ad766c9f270136fdcc33d845a623cb9 [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 McKayfad3d4a2015-09-22 15:09:21 -0700105
Steve McKayfefcd702015-08-20 16:19:38 +0000106import com.google.common.collect.Lists;
Jeff Sharkeyc317af82013-07-01 16:56:54 -0700107
108import java.util.ArrayList;
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -0700109import java.util.Collections;
Jeff Sharkeya5defe32013-08-05 17:56:48 -0700110import java.util.List;
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700111
112/**
113 * Display the documents inside a single directory.
114 */
115public class DirectoryFragment extends Fragment {
116
Jeff Sharkeya5defe32013-08-05 17:56:48 -0700117 public static final int TYPE_NORMAL = 1;
118 public static final int TYPE_SEARCH = 2;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700119 public static final int TYPE_RECENT_OPEN = 3;
Jeff Sharkey5b535922013-08-02 15:55:26 -0700120
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700121 public static final int ANIM_NONE = 1;
122 public static final int ANIM_SIDE = 2;
123 public static final int ANIM_DOWN = 3;
124 public static final int ANIM_UP = 4;
125
Ben Kwaf5858932015-04-07 15:43:39 -0700126 public static final int REQUEST_COPY_DESTINATION = 1;
127
Steve McKayef280152015-06-11 10:10:49 -0700128 private static final int LOADER_ID = 42;
129 private static final boolean DEBUG = false;
Steve McKay8e258c62015-05-06 14:27:57 -0700130 private static final boolean DEBUG_ENABLE_DND = false;
131
Jeff Sharkey2e694f82013-08-06 16:26:14 -0700132 private static final String EXTRA_TYPE = "type";
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700133 private static final String EXTRA_ROOT = "root";
134 private static final String EXTRA_DOC = "doc";
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700135 private static final String EXTRA_QUERY = "query";
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700136 private static final String EXTRA_IGNORE_STATE = "ignoreState";
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700137
Ben Kwa7461a952015-09-01 11:03:01 -0700138 private Model mModel;
Ben Kwa379e1762015-09-21 10:49:52 -0700139 private Model.UpdateListener mModelUpdateListener = new ModelUpdateListener();
Ben Kwa24be5d32015-08-27 16:04:46 -0700140
Steve McKayef280152015-06-11 10:10:49 -0700141 private final Handler mHandler = new Handler(Looper.getMainLooper());
Jeff Sharkey2e694f82013-08-06 16:26:14 -0700142
Steve McKayef280152015-06-11 10:10:49 -0700143 private View mEmptyView;
144 private RecyclerView mRecView;
145
146 private int mType = TYPE_NORMAL;
147 private String mStateKey;
148
149 private int mLastMode = MODE_UNKNOWN;
150 private int mLastSortOrder = SORT_ORDER_UNKNOWN;
151 private boolean mLastShowSize;
152 private boolean mHideGridTitles;
153 private boolean mSvelteRecents;
154 private Point mThumbSize;
155 private DocumentsAdapter mAdapter;
156 private LoaderCallbacks<DirectoryResult> mCallbacks;
Steve McKay1f199482015-05-20 15:58:42 -0700157 private FragmentTuner mFragmentTuner;
158 private DocumentClipper mClipper;
Steve McKayef280152015-06-11 10:10:49 -0700159 // These are lazily initialized.
Steve McKayd57f5fa2015-07-23 16:33:41 -0700160 private LinearLayoutManager mListLayout;
161 private GridLayoutManager mGridLayout;
Steve McKayd57f5fa2015-07-23 16:33:41 -0700162 private int mColumnCount = 1; // This will get updated when layout changes.
Steve McKay1f199482015-05-20 15:58:42 -0700163
Ben Kwac42fa402015-09-16 08:04:37 -0700164 private MessageBar mMessageBar;
Ben Kwa379e1762015-09-21 10:49:52 -0700165 private View mProgressBar;
Ben Kwac42fa402015-09-16 08:04:37 -0700166
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700167 public static void showNormal(FragmentManager fm, RootInfo root, DocumentInfo doc, int anim) {
168 show(fm, TYPE_NORMAL, root, doc, null, anim);
Jeff Sharkey2e694f82013-08-06 16:26:14 -0700169 }
170
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700171 public static void showSearch(FragmentManager fm, RootInfo root, String query, int anim) {
172 show(fm, TYPE_SEARCH, root, null, query, anim);
Jeff Sharkey2e694f82013-08-06 16:26:14 -0700173 }
174
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700175 public static void showRecentsOpen(FragmentManager fm, int anim) {
176 show(fm, TYPE_RECENT_OPEN, null, null, null, anim);
Jeff Sharkey2e694f82013-08-06 16:26:14 -0700177 }
178
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700179 private static void show(FragmentManager fm, int type, RootInfo root, DocumentInfo doc,
180 String query, int anim) {
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700181 final Bundle args = new Bundle();
Jeff Sharkey2e694f82013-08-06 16:26:14 -0700182 args.putInt(EXTRA_TYPE, type);
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700183 args.putParcelable(EXTRA_ROOT, root);
184 args.putParcelable(EXTRA_DOC, doc);
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700185 args.putString(EXTRA_QUERY, query);
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700186
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700187 final FragmentTransaction ft = fm.beginTransaction();
188 switch (anim) {
189 case ANIM_SIDE:
190 args.putBoolean(EXTRA_IGNORE_STATE, true);
191 break;
192 case ANIM_DOWN:
193 args.putBoolean(EXTRA_IGNORE_STATE, true);
194 ft.setCustomAnimations(R.animator.dir_down, R.animator.dir_frozen);
195 break;
196 case ANIM_UP:
197 ft.setCustomAnimations(R.animator.dir_frozen, R.animator.dir_up);
198 break;
199 }
200
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700201 final DirectoryFragment fragment = new DirectoryFragment();
202 fragment.setArguments(args);
203
Jeff Sharkey76112212013-08-06 11:26:10 -0700204 ft.replace(R.id.container_directory, fragment);
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700205 ft.commitAllowingStateLoss();
206 }
207
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700208 private static String buildStateKey(RootInfo root, DocumentInfo doc) {
209 final StringBuilder builder = new StringBuilder();
210 builder.append(root != null ? root.authority : "null").append(';');
211 builder.append(root != null ? root.rootId : "null").append(';');
212 builder.append(doc != null ? doc.documentId : "null");
213 return builder.toString();
214 }
215
Jeff Sharkeya5defe32013-08-05 17:56:48 -0700216 public static DirectoryFragment get(FragmentManager fm) {
217 // TODO: deal with multiple directories shown at once
Jeff Sharkey76112212013-08-06 11:26:10 -0700218 return (DirectoryFragment) fm.findFragmentById(R.id.container_directory);
Jeff Sharkeya5defe32013-08-05 17:56:48 -0700219 }
220
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700221 @Override
222 public View onCreateView(
223 LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
224 final Context context = inflater.getContext();
Jeff Sharkey083d7e12014-07-27 21:01:45 -0700225 final Resources res = context.getResources();
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700226 final View view = inflater.inflate(R.layout.fragment_directory, container, false);
227
Ben Kwac42fa402015-09-16 08:04:37 -0700228 mMessageBar = MessageBar.create(getChildFragmentManager());
Ben Kwa379e1762015-09-21 10:49:52 -0700229 mProgressBar = view.findViewById(R.id.progressbar);
Ben Kwac42fa402015-09-16 08:04:37 -0700230
Jeff Sharkeyc6cbdf12013-08-07 16:22:02 -0700231 mEmptyView = view.findViewById(android.R.id.empty);
232
Steve McKayef280152015-06-11 10:10:49 -0700233 mRecView = (RecyclerView) view.findViewById(R.id.recyclerView);
234 mRecView.setRecyclerListener(
235 new RecyclerListener() {
236 @Override
237 public void onViewRecycled(ViewHolder holder) {
238 cancelThumbnailTask(holder.itemView);
239 }
240 });
Steve McKay8e258c62015-05-06 14:27:57 -0700241
Steve McKayd57f5fa2015-07-23 16:33:41 -0700242 // TODO: Rather than update columns on layout changes, push this
243 // code (or something like it) into GridLayoutManager.
244 mRecView.addOnLayoutChangeListener(
245 new OnLayoutChangeListener() {
246
247 @Override
248 public void onLayoutChange(
249 View v, int left, int top, int right, int bottom, int oldLeft,
250 int oldTop, int oldRight, int oldBottom) {
Steve McKayfefcd702015-08-20 16:19:38 +0000251 mColumnCount = calculateColumnCount();
Steve McKayd57f5fa2015-07-23 16:33:41 -0700252 if (mGridLayout != null) {
253 mGridLayout.setSpanCount(mColumnCount);
254 }
255 }
256 });
257
258 // TODO: Add a divider between views (which might use RecyclerView.ItemDecoration).
Steve McKay8e258c62015-05-06 14:27:57 -0700259 if (DEBUG_ENABLE_DND) {
Steve McKayef280152015-06-11 10:10:49 -0700260 setupDragAndDropOnDirectoryView(mRecView);
Steve McKay8e258c62015-05-06 14:27:57 -0700261 }
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700262
Jeff Sharkeyac9e6272013-08-31 21:27:44 -0700263 return view;
264 }
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700265
Jeff Sharkeyac9e6272013-08-31 21:27:44 -0700266 @Override
Jeff Sharkeyf63b7772013-10-01 17:57:41 -0700267 public void onDestroyView() {
268 super.onDestroyView();
269
270 // Cancel any outstanding thumbnail requests
Steve McKayef280152015-06-11 10:10:49 -0700271 final int count = mRecView.getChildCount();
Jeff Sharkeyf63b7772013-10-01 17:57:41 -0700272 for (int i = 0; i < count; i++) {
Steve McKayef280152015-06-11 10:10:49 -0700273 final View view = mRecView.getChildAt(i);
274 cancelThumbnailTask(view);
Jeff Sharkeyf63b7772013-10-01 17:57:41 -0700275 }
Jeff Sharkeyfaaeb392013-10-04 14:44:56 -0700276
Steve McKayef280152015-06-11 10:10:49 -0700277 // Clear any outstanding selection
Ben Kwa24be5d32015-08-27 16:04:46 -0700278 mModel.clearSelection();
Jeff Sharkeyf63b7772013-10-01 17:57:41 -0700279 }
280
281 @Override
Jeff Sharkeyac9e6272013-08-31 21:27:44 -0700282 public void onActivityCreated(Bundle savedInstanceState) {
283 super.onActivityCreated(savedInstanceState);
284
285 final Context context = getActivity();
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700286 final State state = getDisplayState(DirectoryFragment.this);
Jeff Sharkeyac9e6272013-08-31 21:27:44 -0700287
Jeff Sharkey9656a532013-09-13 13:42:19 -0700288 final RootInfo root = getArguments().getParcelable(EXTRA_ROOT);
289 final DocumentInfo doc = getArguments().getParcelable(EXTRA_DOC);
290
Steve McKayef280152015-06-11 10:10:49 -0700291 mAdapter = new DocumentsAdapter(context);
292 mRecView.setAdapter(mAdapter);
293
294 GestureDetector.SimpleOnGestureListener listener =
295 new GestureDetector.SimpleOnGestureListener() {
296 @Override
297 public boolean onSingleTapUp(MotionEvent e) {
298 return DirectoryFragment.this.onSingleTapUp(e);
299 }
Steve McKay93d8ef42015-07-30 12:27:44 -0700300 @Override
301 public boolean onDoubleTap(MotionEvent e) {
302 Log.d(TAG, "Handling double tap.");
303 return DirectoryFragment.this.onDoubleTap(e);
304 }
Steve McKayef280152015-06-11 10:10:49 -0700305 };
306
Ben Kwa24be5d32015-08-27 16:04:46 -0700307 // TODO: instead of inserting the view into the constructor, extract listener-creation code
308 // and set the listener on the view after the fact. Then the view doesn't need to be passed
309 // into the selection manager which is passed into the model.
310 MultiSelectManager selMgr= new MultiSelectManager(
Steve McKay57394872015-08-12 14:48:34 -0700311 mRecView,
312 listener,
313 state.allowMultiple
314 ? MultiSelectManager.MODE_MULTIPLE
315 : MultiSelectManager.MODE_SINGLE);
Ben Kwa24be5d32015-08-27 16:04:46 -0700316 selMgr.addCallback(new SelectionModeListener());
Ben Kwa7461a952015-09-01 11:03:01 -0700317
Ben Kwa379e1762015-09-21 10:49:52 -0700318 mModel = new Model(context, selMgr, mAdapter);
319 mModel.addUpdateListener(mModelUpdateListener);
Steve McKayef280152015-06-11 10:10:49 -0700320
Jeff Sharkey2e694f82013-08-06 16:26:14 -0700321 mType = getArguments().getInt(EXTRA_TYPE);
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700322 mStateKey = buildStateKey(root, doc);
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700323
Steve McKay1f199482015-05-20 15:58:42 -0700324 mFragmentTuner = pickFragmentTuner(state);
325 mClipper = new DocumentClipper(context);
326
Jeff Sharkey9656a532013-09-13 13:42:19 -0700327 if (mType == TYPE_RECENT_OPEN) {
328 // Hide titles when showing recents for picking images/videos
329 mHideGridTitles = MimePredicate.mimeMatches(
330 MimePredicate.VISUAL_MIMES, state.acceptMimes);
331 } else {
332 mHideGridTitles = (doc != null) && doc.isGridTitlesHidden();
333 }
334
Jeff Sharkeyf63b7772013-10-01 17:57:41 -0700335 final ActivityManager am = (ActivityManager) context.getSystemService(
336 Context.ACTIVITY_SERVICE);
337 mSvelteRecents = am.isLowRamDevice() && (mType == TYPE_RECENT_OPEN);
338
Jeff Sharkey46899c82013-08-18 22:26:48 -0700339 mCallbacks = new LoaderCallbacks<DirectoryResult>() {
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700340 @Override
Jeff Sharkey46899c82013-08-18 22:26:48 -0700341 public Loader<DirectoryResult> onCreateLoader(int id, Bundle args) {
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700342 final String query = getArguments().getString(EXTRA_QUERY);
Jeff Sharkey46165b52013-07-31 20:53:22 -0700343
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700344 Uri contentsUri;
345 switch (mType) {
346 case TYPE_NORMAL:
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700347 contentsUri = DocumentsContract.buildChildDocumentsUri(
348 doc.authority, doc.documentId);
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700349 if (state.action == ACTION_MANAGE) {
350 contentsUri = DocumentsContract.setManageMode(contentsUri);
351 }
Jeff Sharkeyd10f0492013-09-09 17:35:46 -0700352 return new DirectoryLoader(
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700353 context, mType, root, doc, contentsUri, state.userSortOrder);
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700354 case TYPE_SEARCH:
355 contentsUri = DocumentsContract.buildSearchDocumentsUri(
Jeff Sharkey0e8c8712013-09-12 21:59:06 -0700356 root.authority, root.rootId, query);
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700357 if (state.action == ACTION_MANAGE) {
358 contentsUri = DocumentsContract.setManageMode(contentsUri);
359 }
Jeff Sharkeyd10f0492013-09-09 17:35:46 -0700360 return new DirectoryLoader(
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700361 context, mType, root, doc, contentsUri, state.userSortOrder);
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700362 case TYPE_RECENT_OPEN:
Jeff Sharkey1c903cc2013-09-02 17:19:40 -0700363 final RootsCache roots = DocumentsApplication.getRootsCache(context);
Jeff Sharkey8b997042013-09-19 15:25:56 -0700364 return new RecentLoader(context, roots, state);
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700365 default:
366 throw new IllegalStateException("Unknown type " + mType);
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700367 }
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700368 }
369
370 @Override
Jeff Sharkey46899c82013-08-18 22:26:48 -0700371 public void onLoadFinished(Loader<DirectoryResult> loader, DirectoryResult result) {
Makoto Onuki77778752015-07-01 14:55:14 -0700372 if (result == null || result.exception != null) {
373 // onBackPressed does a fragment transaction, which can't be done inside
374 // onLoadFinished
375 mHandler.post(new Runnable() {
376 @Override
377 public void run() {
378 final Activity activity = getActivity();
379 if (activity != null) {
380 activity.onBackPressed();
381 }
382 }
383 });
384 return;
385 }
386
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700387 if (!isAdded()) return;
388
Ben Kwa24be5d32015-08-27 16:04:46 -0700389 mModel.update(result);
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700390
391 // Push latest state up to UI
392 // TODO: if mode change was racing with us, don't overwrite it
Jeff Sharkey7d58fc62013-09-12 16:25:02 -0700393 if (result.mode != MODE_UNKNOWN) {
394 state.derivedMode = result.mode;
395 }
Jeff Sharkeyd10f0492013-09-09 17:35:46 -0700396 state.derivedSortOrder = result.sortOrder;
Steve McKayd0a2a2c2015-03-25 14:35:33 -0700397 ((BaseActivity) context).onStateChanged();
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700398
399 updateDisplayState();
400
Jeff Sharkey25f10b32013-10-07 14:08:17 -0700401 // When launched into empty recents, show drawer
Ben Kwa24be5d32015-08-27 16:04:46 -0700402 if (mType == TYPE_RECENT_OPEN && mModel.isEmpty() && !state.stackTouched &&
Steve McKayb68dd222015-04-20 17:18:15 -0700403 context instanceof DocumentsActivity) {
404 ((DocumentsActivity) context).setRootsDrawerOpen(true);
Jeff Sharkey25f10b32013-10-07 14:08:17 -0700405 }
406
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700407 // Restore any previous instance state
408 final SparseArray<Parcelable> container = state.dirState.remove(mStateKey);
409 if (container != null && !getArguments().getBoolean(EXTRA_IGNORE_STATE, false)) {
410 getView().restoreHierarchyState(container);
411 } else if (mLastSortOrder != state.derivedSortOrder) {
Steve McKayef280152015-06-11 10:10:49 -0700412 mRecView.smoothScrollToPosition(0);
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700413 }
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700414
415 mLastSortOrder = state.derivedSortOrder;
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700416 }
417
418 @Override
Jeff Sharkey46899c82013-08-18 22:26:48 -0700419 public void onLoaderReset(Loader<DirectoryResult> loader) {
Ben Kwa24be5d32015-08-27 16:04:46 -0700420 mModel.update(null);
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700421 }
422 };
423
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700424 // Kick off loader at least once
Steve McKayef280152015-06-11 10:10:49 -0700425 getLoaderManager().restartLoader(LOADER_ID, null, mCallbacks);
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700426
Kyle Horimoto426bd0d2015-07-29 15:33:49 -0700427 mFragmentTuner.afterActivityCreated(this);
Jeff Sharkey2e694f82013-08-06 16:26:14 -0700428 updateDisplayState();
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700429 }
430
Jeff Sharkey42d26792013-09-06 13:22:09 -0700431 @Override
Ben Kwaf5858932015-04-07 15:43:39 -0700432 public void onActivityResult(int requestCode, int resultCode, Intent data) {
Ben Kwaf5858932015-04-07 15:43:39 -0700433 // There's only one request code right now. Replace this with a switch statement or
434 // something more scalable when more codes are added.
435 if (requestCode != REQUEST_COPY_DESTINATION) {
436 return;
437 }
438 if (resultCode == Activity.RESULT_CANCELED || data == null) {
439 // User pressed the back button or otherwise cancelled the destination pick. Don't
440 // proceed with the copy.
441 return;
442 }
443
Tomasz Mikolajewski9452c442015-04-14 16:32:41 +0900444 CopyService.start(getActivity(), getDisplayState(this).selectedDocumentsForCopy,
Ben Kwacb4461f2015-05-05 11:50:11 -0700445 (DocumentStack) data.getParcelableExtra(CopyService.EXTRA_STACK),
446 data.getIntExtra(CopyService.EXTRA_TRANSFER_MODE, CopyService.TRANSFER_MODE_NONE));
Ben Kwaf5858932015-04-07 15:43:39 -0700447 }
448
Steve McKayef280152015-06-11 10:10:49 -0700449 private int getEventAdapterPosition(MotionEvent e) {
450 View view = mRecView.findChildViewUnder(e.getX(), e.getY());
451 return view != null ? mRecView.getChildAdapterPosition(view) : RecyclerView.NO_POSITION;
452 }
453
454 private boolean onSingleTapUp(MotionEvent e) {
Ben Kwa24be5d32015-08-27 16:04:46 -0700455 if (Events.isTouchEvent(e) && mModel.getSelection().isEmpty()) {
Steve McKay93d8ef42015-07-30 12:27:44 -0700456 int position = getEventAdapterPosition(e);
457 if (position != RecyclerView.NO_POSITION) {
458 return handleViewItem(position);
Steve McKayef280152015-06-11 10:10:49 -0700459 }
460 }
Steve McKay93d8ef42015-07-30 12:27:44 -0700461 return false;
462 }
Steve McKayef280152015-06-11 10:10:49 -0700463
Steve McKay93d8ef42015-07-30 12:27:44 -0700464 protected boolean onDoubleTap(MotionEvent e) {
465 if (Events.isMouseEvent(e)) {
466 Log.d(TAG, "Handling double tap from mouse.");
467 int position = getEventAdapterPosition(e);
468 if (position != RecyclerView.NO_POSITION) {
469 return handleViewItem(position);
470 }
471 }
472 return false;
473 }
474
475 private boolean handleViewItem(int position) {
Ben Kwa24be5d32015-08-27 16:04:46 -0700476 final Cursor cursor = mModel.getItem(position);
Steve McKay93d8ef42015-07-30 12:27:44 -0700477 checkNotNull(cursor, "Cursor cannot be null.");
478 final String docMimeType = getCursorString(cursor, Document.COLUMN_MIME_TYPE);
479 final int docFlags = getCursorInt(cursor, Document.COLUMN_FLAGS);
480 if (isDocumentEnabled(docMimeType, docFlags)) {
481 final DocumentInfo doc = DocumentInfo.fromDirectoryCursor(cursor);
Ben Kwa24be5d32015-08-27 16:04:46 -0700482 ((BaseActivity) getActivity()).onDocumentPicked(doc, mModel);
483 mModel.clearSelection();
Steve McKay93d8ef42015-07-30 12:27:44 -0700484 return true;
485 }
Steve McKayef280152015-06-11 10:10:49 -0700486 return false;
487 }
488
Ben Kwaf5858932015-04-07 15:43:39 -0700489 @Override
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700490 public void onStop() {
491 super.onStop();
492
493 // Remember last scroll location
494 final SparseArray<Parcelable> container = new SparseArray<Parcelable>();
495 getView().saveHierarchyState(container);
496 final State state = getDisplayState(this);
497 state.dirState.put(mStateKey, container);
498 }
499
500 @Override
Jeff Sharkey7d58fc62013-09-12 16:25:02 -0700501 public void onResume() {
502 super.onResume();
Jeff Sharkey42d26792013-09-06 13:22:09 -0700503 updateDisplayState();
504 }
505
Jeff Sharkeye8d13ea2014-08-08 15:10:03 -0700506 public void onDisplayStateChanged() {
507 updateDisplayState();
508 }
509
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700510 public void onUserSortOrderChanged() {
Jeff Sharkeyd10f0492013-09-09 17:35:46 -0700511 // Sort order change always triggers reload; we'll trigger state change
512 // on the flip side.
Steve McKayef280152015-06-11 10:10:49 -0700513 getLoaderManager().restartLoader(LOADER_ID, null, mCallbacks);
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700514 }
515
516 public void onUserModeChanged() {
Jeff Sharkeyd10f0492013-09-09 17:35:46 -0700517 final ContentResolver resolver = getActivity().getContentResolver();
518 final State state = getDisplayState(this);
519
520 final RootInfo root = getArguments().getParcelable(EXTRA_ROOT);
521 final DocumentInfo doc = getArguments().getParcelable(EXTRA_DOC);
522
Jeff Sharkey0e8c8712013-09-12 21:59:06 -0700523 if (root != null && doc != null) {
Jeff Sharkey7d58fc62013-09-12 16:25:02 -0700524 final Uri stateUri = RecentsProvider.buildState(
525 root.authority, root.rootId, doc.documentId);
526 final ContentValues values = new ContentValues();
527 values.put(StateColumns.MODE, state.userMode);
Jeff Sharkeyd10f0492013-09-09 17:35:46 -0700528
Jeff Sharkey7d58fc62013-09-12 16:25:02 -0700529 new AsyncTask<Void, Void, Void>() {
530 @Override
531 protected Void doInBackground(Void... params) {
532 resolver.insert(stateUri, values);
533 return null;
534 }
535 }.execute();
536 }
Jeff Sharkeyd10f0492013-09-09 17:35:46 -0700537
538 // Mode change is just visual change; no need to kick loader, and
539 // deliver change event immediately.
540 state.derivedMode = state.userMode;
Steve McKayd0a2a2c2015-03-25 14:35:33 -0700541 ((BaseActivity) getActivity()).onStateChanged();
Jeff Sharkeyd10f0492013-09-09 17:35:46 -0700542
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700543 updateDisplayState();
544 }
545
546 private void updateDisplayState() {
Jeff Sharkeyb3620442013-09-01 18:41:04 -0700547 final State state = getDisplayState(this);
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700548
Jeff Sharkey5e1884d2013-09-10 17:56:39 -0700549 if (mLastMode == state.derivedMode && mLastShowSize == state.showSize) return;
Jeff Sharkeyd10f0492013-09-09 17:35:46 -0700550 mLastMode = state.derivedMode;
Jeff Sharkey5e1884d2013-09-10 17:56:39 -0700551 mLastShowSize = state.showSize;
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700552
Steve McKayef280152015-06-11 10:10:49 -0700553 updateLayout(state.derivedMode);
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700554
Steve McKayef280152015-06-11 10:10:49 -0700555 mRecView.setAdapter(mAdapter);
556 }
557
558 /**
559 * Returns a {@code LayoutManager} for {@code mode}, lazily initializing
560 * classes as needed.
561 */
562 private void updateLayout(int mode) {
Jeff Sharkey8a8fb672013-05-07 12:41:33 -0700563 final int thumbSize;
Steve McKayef280152015-06-11 10:10:49 -0700564
565 final LayoutManager layout;
566 switch (mode) {
567 case MODE_GRID:
Steve McKayef280152015-06-11 10:10:49 -0700568 thumbSize = getResources().getDimensionPixelSize(R.dimen.grid_width);
Steve McKaya9be7182015-07-22 16:03:35 -0700569 if (mGridLayout == null) {
Steve McKayd57f5fa2015-07-23 16:33:41 -0700570 mGridLayout = new GridLayoutManager(getContext(), mColumnCount );
Steve McKaya9be7182015-07-22 16:03:35 -0700571 }
Steve McKayef280152015-06-11 10:10:49 -0700572 layout = mGridLayout;
573 break;
574 case MODE_LIST:
Steve McKaya9be7182015-07-22 16:03:35 -0700575 thumbSize = getResources().getDimensionPixelSize(R.dimen.icon_size);
Steve McKayef280152015-06-11 10:10:49 -0700576 if (mListLayout == null) {
577 mListLayout = new LinearLayoutManager(getContext());
578 }
Steve McKayef280152015-06-11 10:10:49 -0700579 layout = mListLayout;
580 break;
581 case MODE_UNKNOWN:
582 default:
583 throw new IllegalArgumentException("Unsupported layout mode: " + mode);
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700584 }
Jeff Sharkey8a8fb672013-05-07 12:41:33 -0700585
Steve McKayef280152015-06-11 10:10:49 -0700586 mRecView.setLayoutManager(layout);
Kyle Horimoto2da6e4a2015-08-27 16:44:00 -0700587 // TODO: Once b/23691541 is resolved, use a listener within MultiSelectManager instead of
588 // imperatively calling this function.
Steve McKay9058e042015-09-01 12:31:24 -0700589 mModel.mSelectionManager.handleLayoutChanged();
Steve McKayef280152015-06-11 10:10:49 -0700590 // setting layout manager automatically invalidates existing ViewHolders.
Jeff Sharkey8a8fb672013-05-07 12:41:33 -0700591 mThumbSize = new Point(thumbSize, thumbSize);
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700592 }
593
Steve McKayfefcd702015-08-20 16:19:38 +0000594 private int calculateColumnCount() {
595 int cellWidth = getResources().getDimensionPixelSize(R.dimen.grid_width);
596 int cellMargin = 2 * getResources().getDimensionPixelSize(R.dimen.grid_item_margin);
Steve McKayd57f5fa2015-07-23 16:33:41 -0700597 int viewPadding = mRecView.getPaddingLeft() + mRecView.getPaddingRight();
Steve McKayfefcd702015-08-20 16:19:38 +0000598
Steve McKayd57f5fa2015-07-23 16:33:41 -0700599 checkState(mRecView.getWidth() > 0);
600 int columnCount = Math.max(1,
Steve McKayfefcd702015-08-20 16:19:38 +0000601 (mRecView.getWidth() - viewPadding) / (cellWidth + cellMargin));
602
Steve McKayd57f5fa2015-07-23 16:33:41 -0700603 return columnCount;
604 }
605
Steve McKayef280152015-06-11 10:10:49 -0700606 /**
607 * Manages the integration between our ActionMode and MultiSelectManager, initiating
608 * ActionMode when there is a selection, canceling it when there is no selection,
609 * and clearing selection when action mode is explicitly exited by the user.
610 */
611 private final class SelectionModeListener
612 implements MultiSelectManager.Callback, ActionMode.Callback {
613
614 private Selection mSelected = new Selection();
615 private ActionMode mActionMode;
Steve McKay4f4232d2015-07-22 12:13:46 -0700616 private int mNoDeleteCount = 0;
617 private Menu mMenu;
Steve McKayef280152015-06-11 10:10:49 -0700618
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700619 @Override
Steve McKayef280152015-06-11 10:10:49 -0700620 public boolean onBeforeItemStateChange(int position, boolean selected) {
Ben Kwac42fa402015-09-16 08:04:37 -0700621 // Directories cannot be checked
Steve McKayef280152015-06-11 10:10:49 -0700622 if (selected) {
Ben Kwa24be5d32015-08-27 16:04:46 -0700623 final Cursor cursor = mModel.getItem(position);
Steve McKayef280152015-06-11 10:10:49 -0700624 checkNotNull(cursor, "Cursor cannot be null.");
Jeff Sharkey7cf49032013-09-26 10:54:16 -0700625 final String docMimeType = getCursorString(cursor, Document.COLUMN_MIME_TYPE);
626 final int docFlags = getCursorInt(cursor, Document.COLUMN_FLAGS);
Steve McKayef280152015-06-11 10:10:49 -0700627 return isDocumentEnabled(docMimeType, docFlags);
628 }
629 return true;
630 }
631
632 @Override
633 public void onItemStateChanged(int position, boolean selected) {
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) {
Ben Kwa33ba3342015-09-24 15:03:51 -0700719 // Exit selection mode first, so we avoid deselecting deleted documents.
Jeff Sharkeyb3620442013-09-01 18:41:04 -0700720 mode.finish();
Ben Kwa33ba3342015-09-24 15:03:51 -0700721 deleteDocuments(selection);
Jeff Sharkey873daa32013-08-18 17:38:20 -0700722 return true;
723
Steve McKay1f199482015-05-20 15:58:42 -0700724 } else if (id == R.id.menu_copy_to) {
Steve McKayef280152015-06-11 10:10:49 -0700725 transferDocuments(selection, CopyService.TRANSFER_MODE_COPY);
Ben Kwacb4461f2015-05-05 11:50:11 -0700726 mode.finish();
727 return true;
728
Steve McKay1f199482015-05-20 15:58:42 -0700729 } else if (id == R.id.menu_move_to) {
Ben Kwa33ba3342015-09-24 15:03:51 -0700730 // Exit selection mode first, so we avoid deselecting deleted documents.
Ben Kwa41b26c12015-03-31 10:11:43 -0700731 mode.finish();
Ben Kwa33ba3342015-09-24 15:03:51 -0700732 transferDocuments(selection, CopyService.TRANSFER_MODE_MOVE);
Ben Kwa41b26c12015-03-31 10:11:43 -0700733 return true;
734
Steve McKay1f199482015-05-20 15:58:42 -0700735 } else if (id == R.id.menu_copy_to_clipboard) {
Steve McKayef280152015-06-11 10:10:49 -0700736 copySelectionToClipboard(selection);
Steve McKay1f199482015-05-20 15:58:42 -0700737 mode.finish();
738 return true;
739
Ben Kwa512a6ba2015-03-31 08:15:21 -0700740 } else if (id == R.id.menu_select_all) {
Steve McKay0599a442015-05-05 14:50:00 -0700741 selectAllFiles();
Ben Kwa512a6ba2015-03-31 08:15:21 -0700742 return true;
743
Jeff Sharkeyc317af82013-07-01 16:56:54 -0700744 } else {
745 return false;
746 }
747 }
Steve McKayef280152015-06-11 10:10:49 -0700748 }
Jeff Sharkeyc317af82013-07-01 16:56:54 -0700749
Steve McKayef280152015-06-11 10:10:49 -0700750 private static void cancelThumbnailTask(View view) {
751 final ImageView iconThumb = (ImageView) view.findViewById(R.id.icon_thumb);
752 if (iconThumb != null) {
753 final ThumbnailAsyncTask oldTask = (ThumbnailAsyncTask) iconThumb.getTag();
754 if (oldTask != null) {
755 oldTask.preempt();
756 iconThumb.setTag(null);
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700757 }
758 }
Steve McKayef280152015-06-11 10:10:49 -0700759 }
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700760
Steve McKayef280152015-06-11 10:10:49 -0700761 private void openDocuments(final Selection selected) {
Steve McKay9276f3b2015-05-27 16:11:42 -0700762 new GetDocumentsTask() {
763 @Override
764 void onDocumentsReady(List<DocumentInfo> docs) {
Steve McKay0fbfc652015-08-20 16:48:49 -0700765 // TODO: Implement support in Files activity for opening multiple docs.
Steve McKay9276f3b2015-05-27 16:11:42 -0700766 BaseActivity.get(DirectoryFragment.this).onDocumentsPicked(docs);
Ben Kwaf527c632015-04-08 15:03:35 -0700767 }
Steve McKay9276f3b2015-05-27 16:11:42 -0700768 }.execute(selected);
Jeff Sharkey873daa32013-08-18 17:38:20 -0700769 }
770
Steve McKayef280152015-06-11 10:10:49 -0700771 private void shareDocuments(final Selection selected) {
Steve McKay9276f3b2015-05-27 16:11:42 -0700772 new GetDocumentsTask() {
773 @Override
774 void onDocumentsReady(List<DocumentInfo> docs) {
775 Intent intent;
776
777 // Filter out directories - those can't be shared.
Steve McKayfefcd702015-08-20 16:19:38 +0000778 List<DocumentInfo> docsForSend = new ArrayList<>();
Steve McKay9276f3b2015-05-27 16:11:42 -0700779 for (DocumentInfo doc: docs) {
780 if (!Document.MIME_TYPE_DIR.equals(doc.mimeType)) {
781 docsForSend.add(doc);
782 }
783 }
784
785 if (docsForSend.size() == 1) {
786 final DocumentInfo doc = docsForSend.get(0);
787
788 intent = new Intent(Intent.ACTION_SEND);
789 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
790 intent.addCategory(Intent.CATEGORY_DEFAULT);
791 intent.setType(doc.mimeType);
792 intent.putExtra(Intent.EXTRA_STREAM, doc.derivedUri);
793
794 } else if (docsForSend.size() > 1) {
795 intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
796 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
797 intent.addCategory(Intent.CATEGORY_DEFAULT);
798
Steve McKayfefcd702015-08-20 16:19:38 +0000799 final ArrayList<String> mimeTypes = new ArrayList<>();
800 final ArrayList<Uri> uris = new ArrayList<>();
Steve McKay9276f3b2015-05-27 16:11:42 -0700801 for (DocumentInfo doc : docsForSend) {
802 mimeTypes.add(doc.mimeType);
803 uris.add(doc.derivedUri);
804 }
805
806 intent.setType(findCommonMimeType(mimeTypes));
807 intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
808
809 } else {
810 return;
811 }
812
813 intent = Intent.createChooser(intent, getActivity().getText(R.string.share_via));
814 startActivity(intent);
815 }
816 }.execute(selected);
817 }
818
Steve McKayef280152015-06-11 10:10:49 -0700819 private void deleteDocuments(final Selection selected) {
Ben Kwa91923182015-08-27 16:06:33 -0700820 Context context = getActivity();
821 ContentResolver resolver = context.getContentResolver();
822 String message = Shared.getQuantityString(context, R.plurals.deleting, selected.size());
Jeff Sharkey873daa32013-08-18 17:38:20 -0700823
Ben Kwa91923182015-08-27 16:06:33 -0700824 mModel.markForDeletion(selected);
Jeff Sharkey873daa32013-08-18 17:38:20 -0700825
Ben Kwa91923182015-08-27 16:06:33 -0700826 Activity activity = getActivity();
827 Snackbar.make(this.getView(), message, Snackbar.LENGTH_LONG)
828 .setAction(
829 R.string.undo,
830 new android.view.View.OnClickListener() {
831 @Override
832 public void onClick(View view) {}
833 })
834 .setCallback(
835 new Snackbar.Callback() {
836 @Override
837 public void onDismissed(Snackbar snackbar, int event) {
838 if (event == Snackbar.Callback.DISMISS_EVENT_ACTION) {
839 mModel.undoDeletion();
840 } else {
Ben Kwa83cedf22015-09-11 15:15:45 -0700841 mModel.finalizeDeletion(
842 new Runnable() {
843 @Override
844 public void run() {
845 Snackbar.make(
846 DirectoryFragment.this.getView(),
847 R.string.toast_failed_delete,
848 Snackbar.LENGTH_LONG)
849 .show();
850
851 }
852 });
Ben Kwa91923182015-08-27 16:06:33 -0700853 }
Ben Kwa91923182015-08-27 16:06:33 -0700854 }
855 })
856 .show();
Jeff Sharkey873daa32013-08-18 17:38:20 -0700857 }
858
Steve McKayef280152015-06-11 10:10:49 -0700859 private void transferDocuments(final Selection selected, final int mode) {
Ben Kwaf5858932015-04-07 15:43:39 -0700860 // Pop up a dialog to pick a destination. This is inadequate but works for now.
861 // TODO: Implement a picker that is to spec.
Daichi Hironocaadd412015-04-10 15:50:38 +0900862 final Intent intent = new Intent(
Daichi Hirono22574ed2015-04-15 13:41:18 +0900863 BaseActivity.DocumentsIntent.ACTION_OPEN_COPY_DESTINATION,
Daichi Hironocaadd412015-04-10 15:50:38 +0900864 Uri.EMPTY,
865 getActivity(),
866 DocumentsActivity.class);
Steve McKay9276f3b2015-05-27 16:11:42 -0700867
868 new GetDocumentsTask() {
869 @Override
870 void onDocumentsReady(List<DocumentInfo> docs) {
871 getDisplayState(DirectoryFragment.this).selectedDocumentsForCopy = docs;
872
873 boolean directoryCopy = false;
874 for (DocumentInfo info : docs) {
875 if (Document.MIME_TYPE_DIR.equals(info.mimeType)) {
876 directoryCopy = true;
877 break;
878 }
879 }
880 intent.putExtra(BaseActivity.DocumentsIntent.EXTRA_DIRECTORY_COPY, directoryCopy);
881 intent.putExtra(CopyService.EXTRA_TRANSFER_MODE, mode);
882 startActivityForResult(intent, REQUEST_COPY_DESTINATION);
Daichi Hironof2a822d2015-04-14 17:12:54 +0900883 }
Steve McKay9276f3b2015-05-27 16:11:42 -0700884 }.execute(selected);
Ben Kwa41b26c12015-03-31 10:11:43 -0700885 }
886
Jeff Sharkeyb3620442013-09-01 18:41:04 -0700887 private static State getDisplayState(Fragment fragment) {
Steve McKayd0a2a2c2015-03-25 14:35:33 -0700888 return ((BaseActivity) fragment.getActivity()).getDisplayState();
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700889 }
890
Steve McKayef280152015-06-11 10:10:49 -0700891 // Provide a reference to the views for each data item
892 // Complex data items may need more than one view per item, and
893 // you provide access to all the views for a data item in a view holder
894 private static final class DocumentHolder extends RecyclerView.ViewHolder {
895 // each data item is just a string in this case
896 public View view;
897 public String docId; // The stable document id.
898 public DocumentHolder(View view) {
899 super(view);
900 this.view = view;
901 }
902 }
903
Ben Kwa379e1762015-09-21 10:49:52 -0700904 private final class DocumentsAdapter extends RecyclerView.Adapter<DocumentHolder> {
Steve McKayef280152015-06-11 10:10:49 -0700905
906 private final Context mContext;
907 private final LayoutInflater mInflater;
Steve McKayef280152015-06-11 10:10:49 -0700908
Steve McKayef280152015-06-11 10:10:49 -0700909 public DocumentsAdapter(Context context) {
910 mContext = context;
911 mInflater = LayoutInflater.from(context);
912 }
Jeff Sharkeyac9e6272013-08-31 21:27:44 -0700913
Ben Kwac42fa402015-09-16 08:04:37 -0700914 @Override
Steve McKayef280152015-06-11 10:10:49 -0700915 public DocumentHolder onCreateViewHolder(ViewGroup parent, int viewType) {
916 final State state = getDisplayState(DirectoryFragment.this);
917 final LayoutInflater inflater = LayoutInflater.from(getContext());
918 switch (state.derivedMode) {
919 case MODE_GRID:
920 return new DocumentHolder(inflater.inflate(R.layout.item_doc_grid, parent, false));
921 case MODE_LIST:
922 return new DocumentHolder(inflater.inflate(R.layout.item_doc_list, parent, false));
923 case MODE_UNKNOWN:
924 default:
925 throw new IllegalStateException("Unsupported layout mode.");
Jeff Sharkey20b32272013-09-03 15:25:52 -0700926 }
927 }
928
Steve McKayef280152015-06-11 10:10:49 -0700929 @Override
930 public void onBindViewHolder(DocumentHolder holder, int position) {
931
932 final Context context = getContext();
Jeff Sharkeyb3620442013-09-01 18:41:04 -0700933 final State state = getDisplayState(DirectoryFragment.this);
Jeff Sharkey9656a532013-09-13 13:42:19 -0700934 final DocumentInfo doc = getArguments().getParcelable(EXTRA_DOC);
Jeff Sharkey873daa32013-08-18 17:38:20 -0700935 final RootsCache roots = DocumentsApplication.getRootsCache(context);
936 final ThumbnailCache thumbs = DocumentsApplication.getThumbnailsCache(
937 context, mThumbSize);
938
Ben Kwa24be5d32015-08-27 16:04:46 -0700939 final Cursor cursor = mModel.getItem(position);
Steve McKayef280152015-06-11 10:10:49 -0700940 checkNotNull(cursor, "Cursor cannot be null.");
Jeff Sharkeyac9e6272013-08-31 21:27:44 -0700941
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700942 final String docAuthority = getCursorString(cursor, RootCursorWrapper.COLUMN_AUTHORITY);
943 final String docRootId = getCursorString(cursor, RootCursorWrapper.COLUMN_ROOT_ID);
Jeff Sharkeyac9e6272013-08-31 21:27:44 -0700944 final String docId = getCursorString(cursor, Document.COLUMN_DOCUMENT_ID);
945 final String docMimeType = getCursorString(cursor, Document.COLUMN_MIME_TYPE);
946 final String docDisplayName = getCursorString(cursor, Document.COLUMN_DISPLAY_NAME);
947 final long docLastModified = getCursorLong(cursor, Document.COLUMN_LAST_MODIFIED);
948 final int docIcon = getCursorInt(cursor, Document.COLUMN_ICON);
949 final int docFlags = getCursorInt(cursor, Document.COLUMN_FLAGS);
950 final String docSummary = getCursorString(cursor, Document.COLUMN_SUMMARY);
951 final long docSize = getCursorLong(cursor, Document.COLUMN_SIZE);
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700952
Steve McKayef280152015-06-11 10:10:49 -0700953 holder.docId = docId;
954 final View itemView = holder.view;
Ben Kwa24be5d32015-08-27 16:04:46 -0700955 itemView.setActivated(mModel.isSelected(position));
Jeff Sharkey9656a532013-09-13 13:42:19 -0700956
Steve McKayef280152015-06-11 10:10:49 -0700957 final View line1 = itemView.findViewById(R.id.line1);
958 final View line2 = itemView.findViewById(R.id.line2);
959
960 final ImageView iconMime = (ImageView) itemView.findViewById(R.id.icon_mime);
961 final ImageView iconThumb = (ImageView) itemView.findViewById(R.id.icon_thumb);
962 final TextView title = (TextView) itemView.findViewById(android.R.id.title);
963 final ImageView icon1 = (ImageView) itemView.findViewById(android.R.id.icon1);
964 final ImageView icon2 = (ImageView) itemView.findViewById(android.R.id.icon2);
965 final TextView summary = (TextView) itemView.findViewById(android.R.id.summary);
966 final TextView date = (TextView) itemView.findViewById(R.id.date);
967 final TextView size = (TextView) itemView.findViewById(R.id.size);
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700968
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700969 final ThumbnailAsyncTask oldTask = (ThumbnailAsyncTask) iconThumb.getTag();
Jeff Sharkey8a8fb672013-05-07 12:41:33 -0700970 if (oldTask != null) {
Jeff Sharkey753a3ae2013-10-22 17:09:44 -0700971 oldTask.preempt();
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700972 iconThumb.setTag(null);
Jeff Sharkey8a8fb672013-05-07 12:41:33 -0700973 }
974
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700975 iconMime.animate().cancel();
976 iconThumb.animate().cancel();
977
Jeff Sharkeyaed873d2013-09-09 16:51:06 -0700978 final boolean supportsThumbnail = (docFlags & Document.FLAG_SUPPORTS_THUMBNAIL) != 0;
Jeff Sharkeyd10f0492013-09-09 17:35:46 -0700979 final boolean allowThumbnail = (state.derivedMode == MODE_GRID)
Jeff Sharkey9656a532013-09-13 13:42:19 -0700980 || MimePredicate.mimeMatches(MimePredicate.VISUAL_MIMES, docMimeType);
Jeff Sharkeyf63b7772013-10-01 17:57:41 -0700981 final boolean showThumbnail = supportsThumbnail && allowThumbnail && !mSvelteRecents;
Jeff Sharkeyaed873d2013-09-09 16:51:06 -0700982
Jeff Sharkey7e544612014-08-29 15:38:27 -0700983 final boolean enabled = isDocumentEnabled(docMimeType, docFlags);
984 final float iconAlpha = (state.derivedMode == MODE_LIST && !enabled) ? 0.5f : 1f;
985
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700986 boolean cacheHit = false;
Jeff Sharkey9656a532013-09-13 13:42:19 -0700987 if (showThumbnail) {
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700988 final Uri uri = DocumentsContract.buildDocumentUri(docAuthority, docId);
Jeff Sharkeyac9e6272013-08-31 21:27:44 -0700989 final Bitmap cachedResult = thumbs.get(uri);
Jeff Sharkey8a8fb672013-05-07 12:41:33 -0700990 if (cachedResult != null) {
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700991 iconThumb.setImageBitmap(cachedResult);
992 cacheHit = true;
Jeff Sharkey8a8fb672013-05-07 12:41:33 -0700993 } else {
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700994 iconThumb.setImageDrawable(null);
Steve McKayef280152015-06-11 10:10:49 -0700995 // TODO: Hang this off DocumentHolder?
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700996 final ThumbnailAsyncTask task = new ThumbnailAsyncTask(
Jeff Sharkey7e544612014-08-29 15:38:27 -0700997 uri, iconMime, iconThumb, mThumbSize, iconAlpha);
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700998 iconThumb.setTag(task);
Jeff Sharkey753a3ae2013-10-22 17:09:44 -0700999 ProviderExecutor.forAuthority(docAuthority).execute(task);
Jeff Sharkey8a8fb672013-05-07 12:41:33 -07001000 }
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -07001001 }
1002
1003 // Always throw MIME icon into place, even when a thumbnail is being
1004 // loaded in background.
1005 if (cacheHit) {
1006 iconMime.setAlpha(0f);
Jeff Sharkey9dd02622013-09-27 16:44:11 -07001007 iconMime.setImageDrawable(null);
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -07001008 iconThumb.setAlpha(1f);
Jeff Sharkeye22d02e2013-04-26 16:54:55 -07001009 } else {
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -07001010 iconMime.setAlpha(1f);
1011 iconThumb.setAlpha(0f);
Jeff Sharkey9dd02622013-09-27 16:44:11 -07001012 iconThumb.setImageDrawable(null);
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001013 iconMime.setImageDrawable(
Steve McKayef280152015-06-11 10:10:49 -07001014 getDocumentIcon(mContext, docAuthority, docId, docMimeType, docIcon, state));
Jeff Sharkeye22d02e2013-04-26 16:54:55 -07001015 }
1016
Jeff Sharkey9656a532013-09-13 13:42:19 -07001017 boolean hasLine1 = false;
Jeff Sharkey42d26792013-09-06 13:22:09 -07001018 boolean hasLine2 = false;
1019
Jeff Sharkey9656a532013-09-13 13:42:19 -07001020 final boolean hideTitle = (state.derivedMode == MODE_GRID) && mHideGridTitles;
1021 if (!hideTitle) {
1022 title.setText(docDisplayName);
1023 hasLine1 = true;
1024 }
1025
1026 Drawable iconDrawable = null;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -07001027 if (mType == TYPE_RECENT_OPEN) {
Jeff Sharkey8b997042013-09-19 15:25:56 -07001028 // We've already had to enumerate roots before any results can
1029 // be shown, so this will never block.
1030 final RootInfo root = roots.getRootBlocking(docAuthority, docRootId);
Jeff Sharkey93cdbc22014-07-29 17:33:36 -07001031 if (state.derivedMode == MODE_GRID) {
Steve McKayef280152015-06-11 10:10:49 -07001032 iconDrawable = root.loadGridIcon(mContext);
Jeff Sharkey93cdbc22014-07-29 17:33:36 -07001033 } else {
Steve McKayef280152015-06-11 10:10:49 -07001034 iconDrawable = root.loadIcon(mContext);
Jeff Sharkey93cdbc22014-07-29 17:33:36 -07001035 }
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -07001036
Jeff Sharkey7d58fc62013-09-12 16:25:02 -07001037 if (summary != null) {
1038 final boolean alwaysShowSummary = getResources()
1039 .getBoolean(R.bool.always_show_summary);
1040 if (alwaysShowSummary) {
1041 summary.setText(root.getDirectoryString());
1042 summary.setVisibility(View.VISIBLE);
1043 hasLine2 = true;
1044 } else {
Jeff Sharkey8b997042013-09-19 15:25:56 -07001045 if (iconDrawable != null && roots.isIconUniqueBlocking(root)) {
Jeff Sharkey7d58fc62013-09-12 16:25:02 -07001046 // No summary needed if icon speaks for itself
1047 summary.setVisibility(View.INVISIBLE);
1048 } else {
1049 summary.setText(root.getDirectoryString());
1050 summary.setVisibility(View.VISIBLE);
1051 summary.setTextAlignment(TextView.TEXT_ALIGNMENT_TEXT_END);
1052 hasLine2 = true;
1053 }
1054 }
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -07001055 }
Jeff Sharkeyac9e6272013-08-31 21:27:44 -07001056 } else {
Jeff Sharkey9656a532013-09-13 13:42:19 -07001057 // Directories showing thumbnails in grid mode get a little icon
1058 // hint to remind user they're a directory.
1059 if (Document.MIME_TYPE_DIR.equals(docMimeType) && state.derivedMode == MODE_GRID
1060 && showThumbnail) {
Steve McKayef280152015-06-11 10:10:49 -07001061 iconDrawable = IconUtils.applyTintAttr(mContext, R.drawable.ic_doc_folder,
Jeff Sharkey34c54092014-08-08 13:08:56 -07001062 android.R.attr.textColorPrimaryInverse);
Jeff Sharkey9656a532013-09-13 13:42:19 -07001063 }
1064
Jeff Sharkey7d58fc62013-09-12 16:25:02 -07001065 if (summary != null) {
1066 if (docSummary != null) {
1067 summary.setText(docSummary);
1068 summary.setVisibility(View.VISIBLE);
1069 hasLine2 = true;
1070 } else {
1071 summary.setVisibility(View.INVISIBLE);
1072 }
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -07001073 }
Jeff Sharkey2e694f82013-08-06 16:26:14 -07001074 }
1075
Jeff Sharkey9656a532013-09-13 13:42:19 -07001076 if (icon1 != null) icon1.setVisibility(View.GONE);
1077 if (icon2 != null) icon2.setVisibility(View.GONE);
1078
1079 if (iconDrawable != null) {
1080 if (hasLine1) {
1081 icon1.setVisibility(View.VISIBLE);
1082 icon1.setImageDrawable(iconDrawable);
1083 } else {
1084 icon2.setVisibility(View.VISIBLE);
1085 icon2.setImageDrawable(iconDrawable);
1086 }
1087 }
1088
Jeff Sharkeyac9e6272013-08-31 21:27:44 -07001089 if (docLastModified == -1) {
Jeff Sharkey8a8fb672013-05-07 12:41:33 -07001090 date.setText(null);
1091 } else {
Steve McKayef280152015-06-11 10:10:49 -07001092 date.setText(formatTime(mContext, docLastModified));
Jeff Sharkey42d26792013-09-06 13:22:09 -07001093 hasLine2 = true;
Jeff Sharkey8a8fb672013-05-07 12:41:33 -07001094 }
Jeff Sharkey2e694f82013-08-06 16:26:14 -07001095
1096 if (state.showSize) {
1097 size.setVisibility(View.VISIBLE);
Jeff Sharkeyac9e6272013-08-31 21:27:44 -07001098 if (Document.MIME_TYPE_DIR.equals(docMimeType) || docSize == -1) {
Jeff Sharkey2e694f82013-08-06 16:26:14 -07001099 size.setText(null);
1100 } else {
Steve McKayef280152015-06-11 10:10:49 -07001101 size.setText(Formatter.formatFileSize(mContext, docSize));
Jeff Sharkey42d26792013-09-06 13:22:09 -07001102 hasLine2 = true;
Jeff Sharkey2e694f82013-08-06 16:26:14 -07001103 }
1104 } else {
1105 size.setVisibility(View.GONE);
Jeff Sharkey09c10bf2013-06-30 20:02:59 -07001106 }
Jeff Sharkeya5defe32013-08-05 17:56:48 -07001107
Jeff Sharkey9656a532013-09-13 13:42:19 -07001108 if (line1 != null) {
1109 line1.setVisibility(hasLine1 ? View.VISIBLE : View.GONE);
1110 }
Jeff Sharkey7d58fc62013-09-12 16:25:02 -07001111 if (line2 != null) {
1112 line2.setVisibility(hasLine2 ? View.VISIBLE : View.GONE);
1113 }
Jeff Sharkey42d26792013-09-06 13:22:09 -07001114
Steve McKayef280152015-06-11 10:10:49 -07001115 setEnabledRecursive(itemView, enabled);
Jeff Sharkey7e544612014-08-29 15:38:27 -07001116
1117 iconMime.setAlpha(iconAlpha);
1118 iconThumb.setAlpha(iconAlpha);
1119 if (icon1 != null) icon1.setAlpha(iconAlpha);
1120 if (icon2 != null) icon2.setAlpha(iconAlpha);
Jeff Sharkeyaed873d2013-09-09 16:51:06 -07001121
Steve McKay8e258c62015-05-06 14:27:57 -07001122 if (DEBUG_ENABLE_DND) {
Steve McKayef280152015-06-11 10:10:49 -07001123 setupDragAndDropOnDocumentView(itemView, cursor);
Steve McKay8e258c62015-05-06 14:27:57 -07001124 }
Jeff Sharkeye22d02e2013-04-26 16:54:55 -07001125 }
Jeff Sharkey09c10bf2013-06-30 20:02:59 -07001126
Steve McKay351a7492015-08-04 10:11:01 -07001127 @Override
Steve McKayef280152015-06-11 10:10:49 -07001128 public int getItemCount() {
Ben Kwa24be5d32015-08-27 16:04:46 -07001129 return mModel.getItemCount();
Jeff Sharkeyaed873d2013-09-09 16:51:06 -07001130 }
1131
Jeff Sharkey8a8fb672013-05-07 12:41:33 -07001132 }
1133
1134 private static String formatTime(Context context, long when) {
1135 // TODO: DateUtils should make this easier
1136 Time then = new Time();
1137 then.set(when);
1138 Time now = new Time();
1139 now.setToNow();
1140
1141 int flags = DateUtils.FORMAT_NO_NOON | DateUtils.FORMAT_NO_MIDNIGHT
1142 | DateUtils.FORMAT_ABBREV_ALL;
1143
1144 if (then.year != now.year) {
1145 flags |= DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_DATE;
1146 } else if (then.yearDay != now.yearDay) {
1147 flags |= DateUtils.FORMAT_SHOW_DATE;
1148 } else {
1149 flags |= DateUtils.FORMAT_SHOW_TIME;
1150 }
1151
1152 return DateUtils.formatDateTime(context, when, flags);
1153 }
Jeff Sharkeyb3620442013-09-01 18:41:04 -07001154
1155 private String findCommonMimeType(List<String> mimeTypes) {
1156 String[] commonType = mimeTypes.get(0).split("/");
1157 if (commonType.length != 2) {
1158 return "*/*";
1159 }
1160
1161 for (int i = 1; i < mimeTypes.size(); i++) {
1162 String[] type = mimeTypes.get(i).split("/");
1163 if (type.length != 2) continue;
1164
1165 if (!commonType[1].equals(type[1])) {
1166 commonType[1] = "*";
1167 }
1168
1169 if (!commonType[0].equals(type[0])) {
1170 commonType[0] = "*";
1171 commonType[1] = "*";
1172 break;
1173 }
1174 }
1175
1176 return commonType[0] + "/" + commonType[1];
1177 }
Jeff Sharkeyaed873d2013-09-09 16:51:06 -07001178
1179 private void setEnabledRecursive(View v, boolean enabled) {
Jeff Sharkey9656a532013-09-13 13:42:19 -07001180 if (v == null) return;
Jeff Sharkeyaed873d2013-09-09 16:51:06 -07001181 if (v.isEnabled() == enabled) return;
1182 v.setEnabled(enabled);
1183
1184 if (v instanceof ViewGroup) {
1185 final ViewGroup vg = (ViewGroup) v;
1186 for (int i = vg.getChildCount() - 1; i >= 0; i--) {
1187 setEnabledRecursive(vg.getChildAt(i), enabled);
1188 }
1189 }
1190 }
Jeff Sharkey7cf49032013-09-26 10:54:16 -07001191
1192 private boolean isDocumentEnabled(String docMimeType, int docFlags) {
1193 final State state = getDisplayState(DirectoryFragment.this);
1194
Jeff Sharkey7cf49032013-09-26 10:54:16 -07001195 // Directories are always enabled
1196 if (Document.MIME_TYPE_DIR.equals(docMimeType)) {
1197 return true;
1198 }
1199
Jeff Sharkey783ebc22013-09-26 19:42:52 -07001200 // Read-only files are disabled when creating
1201 if (state.action == ACTION_CREATE && (docFlags & Document.FLAG_SUPPORTS_WRITE) == 0) {
1202 return false;
1203 }
1204
Jeff Sharkey7cf49032013-09-26 10:54:16 -07001205 return MimePredicate.mimeMatches(state.acceptMimes, docMimeType);
1206 }
Vladislav Kaznacheev89b90332015-05-01 13:46:57 -07001207
Steve McKay1f199482015-05-20 15:58:42 -07001208 private void copyFromClipboard() {
1209 new AsyncTask<Void, Void, List<DocumentInfo>>() {
1210
1211 @Override
1212 protected List<DocumentInfo> doInBackground(Void... params) {
1213 return mClipper.getClippedDocuments();
1214 }
1215
1216 @Override
1217 protected void onPostExecute(List<DocumentInfo> docs) {
1218 DocumentInfo destination =
1219 ((BaseActivity) getActivity()).getCurrentDirectory();
1220 copyDocuments(docs, destination);
1221 }
1222 }.execute();
Steve McKay0599a442015-05-05 14:50:00 -07001223 }
1224
Steve McKay1f199482015-05-20 15:58:42 -07001225 private void copyFromClipData(final ClipData clipData, final DocumentInfo destination) {
Steve McKayef280152015-06-11 10:10:49 -07001226 checkNotNull(clipData);
Steve McKay1f199482015-05-20 15:58:42 -07001227 new AsyncTask<Void, Void, List<DocumentInfo>>() {
Vladislav Kaznacheev89b90332015-05-01 13:46:57 -07001228
Steve McKay1f199482015-05-20 15:58:42 -07001229 @Override
1230 protected List<DocumentInfo> doInBackground(Void... params) {
1231 return mClipper.getDocumentsFromClipData(clipData);
1232 }
1233
1234 @Override
1235 protected void onPostExecute(List<DocumentInfo> docs) {
1236 copyDocuments(docs, destination);
1237 }
1238 }.execute();
1239 }
1240
1241 private void copyDocuments(final List<DocumentInfo> docs, final DocumentInfo destination) {
1242 if (!canCopy(docs, destination)) {
1243 Toast.makeText(
1244 getActivity(),
1245 R.string.clipboard_files_cannot_paste, Toast.LENGTH_SHORT).show();
Steve McKay0599a442015-05-05 14:50:00 -07001246 return;
1247 }
1248
Steve McKay1f199482015-05-20 15:58:42 -07001249 if (docs.isEmpty()) {
Vladislav Kaznacheev89b90332015-05-01 13:46:57 -07001250 return;
Vladislav Kaznacheeve16887a2015-05-05 12:09:47 -07001251 }
Vladislav Kaznacheev89b90332015-05-01 13:46:57 -07001252
Steve McKay1f199482015-05-20 15:58:42 -07001253 final DocumentStack curStack = getDisplayState(DirectoryFragment.this).stack;
Vladislav Kaznacheev89b90332015-05-01 13:46:57 -07001254 DocumentStack tmpStack = new DocumentStack();
Steve McKay1f199482015-05-20 15:58:42 -07001255 if (destination != null) {
1256 tmpStack.push(destination);
Vladislav Kaznacheev89b90332015-05-01 13:46:57 -07001257 tmpStack.addAll(curStack);
1258 } else {
1259 tmpStack = curStack;
1260 }
1261
Steve McKay1f199482015-05-20 15:58:42 -07001262 CopyService.start(getActivity(), docs, tmpStack, CopyService.TRANSFER_MODE_COPY);
Vladislav Kaznacheev89b90332015-05-01 13:46:57 -07001263 }
1264
1265 private ClipData getClipDataFromDocuments(List<DocumentInfo> docs) {
1266 Context context = getActivity();
1267 final ContentResolver resolver = context.getContentResolver();
1268 ClipData clipData = null;
1269 for (DocumentInfo doc : docs) {
1270 final Uri uri = DocumentsContract.buildDocumentUri(doc.authority, doc.documentId);
1271 if (clipData == null) {
Vladislav Kaznacheeve16887a2015-05-05 12:09:47 -07001272 // TODO: figure out what this string should be.
1273 // Currently it is not displayed anywhere in the UI, but this might change.
1274 final String label = "";
1275 clipData = ClipData.newUri(resolver, label, uri);
Vladislav Kaznacheev89b90332015-05-01 13:46:57 -07001276 } else {
1277 // TODO: update list of mime types in ClipData.
1278 clipData.addItem(new ClipData.Item(uri));
1279 }
1280 }
1281 return clipData;
1282 }
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001283
Steve McKay1f199482015-05-20 15:58:42 -07001284 void copySelectedToClipboard() {
Ben Kwa24be5d32015-08-27 16:04:46 -07001285 Selection sel = mModel.getSelection(new Selection());
Steve McKayef280152015-06-11 10:10:49 -07001286 copySelectionToClipboard(sel);
Steve McKay9276f3b2015-05-27 16:11:42 -07001287 }
Steve McKay0599a442015-05-05 14:50:00 -07001288
Steve McKayef280152015-06-11 10:10:49 -07001289 void copySelectionToClipboard(Selection items) {
Steve McKay9276f3b2015-05-27 16:11:42 -07001290 new GetDocumentsTask() {
1291 @Override
1292 void onDocumentsReady(List<DocumentInfo> docs) {
1293 mClipper.clipDocuments(docs);
Steve McKay1f199482015-05-20 15:58:42 -07001294 Activity activity = getActivity();
1295 Toast.makeText(activity,
1296 activity.getResources().getQuantityString(
1297 R.plurals.clipboard_files_clipped, docs.size(), docs.size()),
1298 Toast.LENGTH_SHORT).show();
Steve McKay9276f3b2015-05-27 16:11:42 -07001299 }
Steve McKayef280152015-06-11 10:10:49 -07001300 }.execute(items);
Steve McKay0599a442015-05-05 14:50:00 -07001301 }
1302
1303 void pasteFromClipboard() {
Steve McKay1f199482015-05-20 15:58:42 -07001304 copyFromClipboard();
1305 getActivity().invalidateOptionsMenu();
Steve McKay0599a442015-05-05 14:50:00 -07001306 }
1307
Steve McKay0599a442015-05-05 14:50:00 -07001308 /**
1309 * Returns true if the list of files can be copied to destination. Note that this
1310 * is a policy check only. Currently the method does not attempt to verify
1311 * available space or any other environmental aspects possibly resulting in
1312 * failure to copy.
1313 *
1314 * @return true if the list of files can be copied to destination.
1315 */
1316 boolean canCopy(List<DocumentInfo> files, DocumentInfo dest) {
Ben Kwa91923182015-08-27 16:06:33 -07001317 BaseActivity activity = (BaseActivity) getActivity();
Steve McKay0599a442015-05-05 14:50:00 -07001318
1319 final RootInfo root = activity.getCurrentRoot();
1320
1321 // Can't copy folders to Downloads.
1322 if (root.isDownloads()) {
1323 for (DocumentInfo docs : files) {
1324 if (docs.isDirectory()) {
1325 return false;
1326 }
1327 }
1328 }
1329
1330 return dest != null && dest.isDirectory() && dest.isCreateSupported();
1331 }
1332
1333 void selectAllFiles() {
Ben Kwa24be5d32015-08-27 16:04:46 -07001334 boolean changed = mModel.selectAll();
Steve McKay9459a7c2015-07-24 13:14:20 -07001335 if (changed) {
1336 updateDisplayState();
1337 }
Steve McKay0599a442015-05-05 14:50:00 -07001338 }
1339
Steve McKayef280152015-06-11 10:10:49 -07001340 private void setupDragAndDropOnDirectoryView(View view) {
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001341 // Listen for drops on non-directory items and empty space.
1342 view.setOnDragListener(mOnDragListener);
1343 }
1344
1345 private void setupDragAndDropOnDocumentView(View view, Cursor cursor) {
1346 final String docMimeType = getCursorString(cursor, Document.COLUMN_MIME_TYPE);
1347 if (Document.MIME_TYPE_DIR.equals(docMimeType)) {
1348 // Make a directory item a drop target. Drop on non-directories and empty space
1349 // is handled at the list/grid view level.
1350 view.setOnDragListener(mOnDragListener);
1351 }
1352
1353 // Temporary: attaching the listener to the title only.
1354 // Attaching to the entire item conflicts with the item long click handler responsible
1355 // for item selection.
1356 final View title = view.findViewById(android.R.id.title);
1357 title.setOnLongClickListener(mLongClickListener);
1358 }
1359
1360 private View.OnDragListener mOnDragListener = new View.OnDragListener() {
1361 @Override
1362 public boolean onDrag(View v, DragEvent event) {
1363 switch (event.getAction()) {
1364 case DragEvent.ACTION_DRAG_STARTED:
1365 // TODO: Check if the event contains droppable data.
1366 return true;
1367
1368 // TODO: Highlight potential drop target directory?
1369 // TODO: Expand drop target directory on hover?
1370 case DragEvent.ACTION_DRAG_ENTERED:
1371 case DragEvent.ACTION_DRAG_LOCATION:
1372 case DragEvent.ACTION_DRAG_EXITED:
1373 case DragEvent.ACTION_DRAG_ENDED:
1374 return true;
1375
1376 case DragEvent.ACTION_DROP:
Vladislav Kaznacheev9400b892015-09-04 09:17:37 -07001377 int dstPosition = mRecView.getChildAdapterPosition(getContainingItemView(v));
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001378 DocumentInfo dstDir = null;
1379 if (dstPosition != android.widget.AdapterView.INVALID_POSITION) {
Ben Kwa24be5d32015-08-27 16:04:46 -07001380 Cursor dstCursor = mModel.getItem(dstPosition);
Steve McKayef280152015-06-11 10:10:49 -07001381 checkNotNull(dstCursor, "Cursor cannot be null.");
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001382 dstDir = DocumentInfo.fromDirectoryCursor(dstCursor);
1383 // TODO: Do not drop into the directory where the documents came from.
1384 }
1385 copyFromClipData(event.getClipData(), dstDir);
1386 return true;
1387 }
1388 return false;
1389 }
1390 };
1391
Vladislav Kaznacheev9400b892015-09-04 09:17:37 -07001392 private View getContainingItemView(View view) {
1393 while (true) {
1394 if (view.getLayoutParams() instanceof RecyclerView.LayoutParams) {
1395 return view;
1396 }
1397 ViewParent parent = view.getParent();
1398 if (parent == null || !(parent instanceof View)) {
1399 return null;
1400 }
1401 view = (View) parent;
1402 }
1403 }
1404
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001405 private View.OnLongClickListener mLongClickListener = new View.OnLongClickListener() {
1406 @Override
1407 public boolean onLongClick(View v) {
1408 final List<DocumentInfo> docs = getDraggableDocuments(v);
1409 if (docs.isEmpty()) {
1410 return false;
1411 }
1412 v.startDrag(
1413 getClipDataFromDocuments(docs),
1414 new DrawableShadowBuilder(getDragShadowIcon(docs)),
1415 null,
Vladislav Kaznacheeve3ce8a92015-07-15 18:04:04 -07001416 View.DRAG_FLAG_GLOBAL | View.DRAG_FLAG_GLOBAL_URI_READ |
1417 View.DRAG_FLAG_GLOBAL_URI_WRITE
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001418 );
1419 return true;
1420 }
1421 };
1422
1423 private List<DocumentInfo> getDraggableDocuments(View currentItemView) {
Vladislav Kaznacheev9400b892015-09-04 09:17:37 -07001424 int position = mRecView.getChildAdapterPosition(getContainingItemView(currentItemView));
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001425 if (position == android.widget.AdapterView.INVALID_POSITION) {
1426 return Collections.EMPTY_LIST;
1427 }
1428
Ben Kwa24be5d32015-08-27 16:04:46 -07001429 final List<DocumentInfo> selectedDocs = mModel.getSelectedDocuments();
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001430 if (!selectedDocs.isEmpty()) {
Ben Kwa24be5d32015-08-27 16:04:46 -07001431 if (!mModel.isSelected(position)) {
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001432 // There is a selection that does not include the current item, drag nothing.
1433 return Collections.EMPTY_LIST;
1434 }
1435 return selectedDocs;
1436 }
1437
Ben Kwa24be5d32015-08-27 16:04:46 -07001438 final Cursor cursor = mModel.getItem(position);
Steve McKayef280152015-06-11 10:10:49 -07001439 checkNotNull(cursor, "Cursor cannot be null.");
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001440 final DocumentInfo doc = DocumentInfo.fromDirectoryCursor(cursor);
Steve McKayfefcd702015-08-20 16:19:38 +00001441
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001442 return Lists.newArrayList(doc);
1443 }
1444
1445 private Drawable getDragShadowIcon(List<DocumentInfo> docs) {
1446 if (docs.size() == 1) {
1447 final DocumentInfo doc = docs.get(0);
1448 return getDocumentIcon(getActivity(), doc.authority, doc.documentId,
1449 doc.mimeType, doc.icon, getDisplayState(this));
1450 }
1451 return getActivity().getDrawable(R.drawable.ic_doc_generic);
1452 }
1453
1454 public static Drawable getDocumentIcon(Context context, String docAuthority, String docId,
1455 String docMimeType, int docIcon, State state) {
1456 if (docIcon != 0) {
1457 return IconUtils.loadPackageIcon(context, docAuthority, docIcon);
1458 } else {
1459 return IconUtils.loadMimeIcon(context, docMimeType, docAuthority, docId,
1460 state.derivedMode);
1461 }
1462 }
1463
Steve McKayef280152015-06-11 10:10:49 -07001464 private static class ThumbnailAsyncTask extends AsyncTask<Uri, Void, Bitmap>
1465 implements Preemptable {
1466 private final Uri mUri;
1467 private final ImageView mIconMime;
1468 private final ImageView mIconThumb;
1469 private final Point mThumbSize;
1470 private final float mTargetAlpha;
1471 private final CancellationSignal mSignal;
1472
1473 public ThumbnailAsyncTask(Uri uri, ImageView iconMime, ImageView iconThumb, Point thumbSize,
1474 float targetAlpha) {
1475 mUri = uri;
1476 mIconMime = iconMime;
1477 mIconThumb = iconThumb;
1478 mThumbSize = thumbSize;
1479 mTargetAlpha = targetAlpha;
1480 mSignal = new CancellationSignal();
1481 }
1482
1483 @Override
1484 public void preempt() {
1485 cancel(false);
1486 mSignal.cancel();
1487 }
1488
1489 @Override
1490 protected Bitmap doInBackground(Uri... params) {
1491 if (isCancelled()) return null;
1492
1493 final Context context = mIconThumb.getContext();
1494 final ContentResolver resolver = context.getContentResolver();
1495
1496 ContentProviderClient client = null;
1497 Bitmap result = null;
1498 try {
1499 client = DocumentsApplication.acquireUnstableProviderOrThrow(
1500 resolver, mUri.getAuthority());
1501 result = DocumentsContract.getDocumentThumbnail(client, mUri, mThumbSize, mSignal);
1502 if (result != null) {
1503 final ThumbnailCache thumbs = DocumentsApplication.getThumbnailsCache(
1504 context, mThumbSize);
1505 thumbs.put(mUri, result);
1506 }
1507 } catch (Exception e) {
1508 if (!(e instanceof OperationCanceledException)) {
1509 Log.w(TAG, "Failed to load thumbnail for " + mUri + ": " + e);
1510 }
1511 } finally {
1512 ContentProviderClient.releaseQuietly(client);
1513 }
1514 return result;
1515 }
1516
1517 @Override
1518 protected void onPostExecute(Bitmap result) {
1519 if (mIconThumb.getTag() == this && result != null) {
1520 mIconThumb.setTag(null);
1521 mIconThumb.setImageBitmap(result);
1522
1523 mIconMime.setAlpha(mTargetAlpha);
1524 mIconMime.animate().alpha(0f).start();
1525 mIconThumb.setAlpha(0f);
1526 mIconThumb.animate().alpha(mTargetAlpha).start();
1527 }
1528 }
1529 }
1530
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001531 private class DrawableShadowBuilder extends View.DragShadowBuilder {
1532
1533 private final Drawable mShadow;
1534
1535 private final int mShadowDimension;
1536
1537 public DrawableShadowBuilder(Drawable shadow) {
1538 mShadow = shadow;
1539 mShadowDimension = getResources().getDimensionPixelSize(
1540 R.dimen.drag_shadow_size);
1541 mShadow.setBounds(0, 0, mShadowDimension, mShadowDimension);
1542 }
1543
Ben Kwa24be5d32015-08-27 16:04:46 -07001544 @Override
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001545 public void onProvideShadowMetrics(
1546 Point shadowSize, Point shadowTouchPoint) {
1547 shadowSize.set(mShadowDimension, mShadowDimension);
1548 shadowTouchPoint.set(mShadowDimension / 2, mShadowDimension / 2);
1549 }
1550
Ben Kwa24be5d32015-08-27 16:04:46 -07001551 @Override
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001552 public void onDrawShadow(Canvas canvas) {
1553 mShadow.draw(canvas);
1554 }
1555 }
Steve McKay1f199482015-05-20 15:58:42 -07001556
1557 private FragmentTuner pickFragmentTuner(final State state) {
1558 return state.action == ACTION_BROWSE_ALL
Steve McKay0fbfc652015-08-20 16:48:49 -07001559 ? new FilesTuner()
Steve McKay1f199482015-05-20 15:58:42 -07001560 : new DefaultTuner(state);
1561 }
1562
1563 /**
1564 * Interface for specializing the Fragment for the "host" Activity.
1565 * Feel free to expand the role of this class to handle other specializations.
1566 */
1567 private interface FragmentTuner {
Steve McKay4f4232d2015-07-22 12:13:46 -07001568 void updateActionMenu(Menu menu, int dirType, boolean canDelete);
Kyle Horimoto426bd0d2015-07-29 15:33:49 -07001569 void afterActivityCreated(DirectoryFragment fragment);
Steve McKay1f199482015-05-20 15:58:42 -07001570 }
1571
1572 /**
Steve McKay9276f3b2015-05-27 16:11:42 -07001573 * Abstract task providing support for loading documents *off*
1574 * the main thread. And if it isn't obvious, creating a list
1575 * of documents (especially large lists) can be pretty expensive.
1576 */
1577 private abstract class GetDocumentsTask
Steve McKayef280152015-06-11 10:10:49 -07001578 extends AsyncTask<Selection, Void, List<DocumentInfo>> {
Steve McKay9276f3b2015-05-27 16:11:42 -07001579 @Override
Steve McKayef280152015-06-11 10:10:49 -07001580 protected final List<DocumentInfo> doInBackground(Selection... selected) {
Ben Kwa24be5d32015-08-27 16:04:46 -07001581 return mModel.getDocuments(selected[0]);
Steve McKay9276f3b2015-05-27 16:11:42 -07001582 }
1583
1584 @Override
1585 protected final void onPostExecute(List<DocumentInfo> docs) {
1586 onDocumentsReady(docs);
1587 }
1588
1589 abstract void onDocumentsReady(List<DocumentInfo> docs);
1590 }
1591
1592 /**
Steve McKay1f199482015-05-20 15:58:42 -07001593 * Provides support for Platform specific specializations of DirectoryFragment.
1594 */
1595 private static final class DefaultTuner implements FragmentTuner {
1596
1597 private final State mState;
1598
1599 public DefaultTuner(State state) {
1600 mState = state;
1601 }
1602
1603 @Override
Steve McKay4f4232d2015-07-22 12:13:46 -07001604 public void updateActionMenu(Menu menu, int dirType, boolean canDelete) {
Steve McKay1f199482015-05-20 15:58:42 -07001605 Preconditions.checkState(mState.action != ACTION_BROWSE_ALL);
1606
1607 final MenuItem open = menu.findItem(R.id.menu_open);
1608 final MenuItem share = menu.findItem(R.id.menu_share);
1609 final MenuItem delete = menu.findItem(R.id.menu_delete);
1610 final MenuItem copyTo = menu.findItem(R.id.menu_copy_to);
1611 final MenuItem moveTo = menu.findItem(R.id.menu_move_to);
1612 final MenuItem copyToClipboard = menu.findItem(R.id.menu_copy_to_clipboard);
1613
1614 final boolean manageOrBrowse = (mState.action == ACTION_MANAGE
1615 || mState.action == ACTION_BROWSE);
1616
1617 open.setVisible(!manageOrBrowse);
1618 share.setVisible(manageOrBrowse);
Steve McKay4f4232d2015-07-22 12:13:46 -07001619 delete.setVisible(manageOrBrowse && canDelete);
Steve McKay1f199482015-05-20 15:58:42 -07001620 // Disable copying from the Recents view.
1621 copyTo.setVisible(manageOrBrowse && dirType != TYPE_RECENT_OPEN);
1622 moveTo.setVisible(SystemProperties.getBoolean("debug.documentsui.enable_move", false));
1623
Steve McKay0fbfc652015-08-20 16:48:49 -07001624 // Only shown in files mode.
Steve McKay1f199482015-05-20 15:58:42 -07001625 copyToClipboard.setVisible(false);
1626 }
Kyle Horimoto426bd0d2015-07-29 15:33:49 -07001627
1628 @Override
1629 public void afterActivityCreated(DirectoryFragment fragment) {}
Steve McKay1f199482015-05-20 15:58:42 -07001630 }
1631
1632 /**
Steve McKay0fbfc652015-08-20 16:48:49 -07001633 * Provides support for Files activity specific specializations of DirectoryFragment.
Steve McKay1f199482015-05-20 15:58:42 -07001634 */
Steve McKay0fbfc652015-08-20 16:48:49 -07001635 private static final class FilesTuner implements FragmentTuner {
Steve McKay1f199482015-05-20 15:58:42 -07001636 @Override
Steve McKay4f4232d2015-07-22 12:13:46 -07001637 public void updateActionMenu(Menu menu, int dirType, boolean canDelete) {
Steve McKay1f199482015-05-20 15:58:42 -07001638 menu.findItem(R.id.menu_share).setVisible(true);
Steve McKay4f4232d2015-07-22 12:13:46 -07001639 menu.findItem(R.id.menu_delete).setVisible(canDelete);
Steve McKay1f199482015-05-20 15:58:42 -07001640 menu.findItem(R.id.menu_copy_to_clipboard).setVisible(true);
1641
1642 menu.findItem(R.id.menu_open).setVisible(false);
1643 menu.findItem(R.id.menu_copy_to).setVisible(false);
1644 menu.findItem(R.id.menu_move_to).setVisible(false);
1645 }
Kyle Horimoto426bd0d2015-07-29 15:33:49 -07001646
1647 @Override
Kyle Horimoto62a7fd02015-08-18 13:25:29 -07001648 public void afterActivityCreated(DirectoryFragment fragment) {}
Steve McKay1f199482015-05-20 15:58:42 -07001649 }
Ben Kwa24be5d32015-08-27 16:04:46 -07001650
1651 /**
1652 * The data model for the current loaded directory.
1653 */
Ben Kwa7461a952015-09-01 11:03:01 -07001654 @VisibleForTesting
1655 public static final class Model implements DocumentContext {
Ben Kwa24be5d32015-08-27 16:04:46 -07001656 private MultiSelectManager mSelectionManager;
Ben Kwa379e1762015-09-21 10:49:52 -07001657 private RecyclerView.Adapter<?> mViewAdapter;
Ben Kwa7461a952015-09-01 11:03:01 -07001658 private Context mContext;
Ben Kwa24be5d32015-08-27 16:04:46 -07001659 private int mCursorCount;
1660 private boolean mIsLoading;
Ben Kwa7461a952015-09-01 11:03:01 -07001661 private SparseBooleanArray mMarkedForDeletion = new SparseBooleanArray();
1662 private UpdateListener mUpdateListener;
Ben Kwa24be5d32015-08-27 16:04:46 -07001663 @Nullable private Cursor mCursor;
1664 @Nullable private String info;
1665 @Nullable private String error;
Ben Kwa7461a952015-09-01 11:03:01 -07001666
Ben Kwa379e1762015-09-21 10:49:52 -07001667 Model(Context context, MultiSelectManager selectionManager,
1668 RecyclerView.Adapter<?> viewAdapter) {
Ben Kwa7461a952015-09-01 11:03:01 -07001669 mContext = context;
1670 mSelectionManager = selectionManager;
Ben Kwa379e1762015-09-21 10:49:52 -07001671 mViewAdapter = viewAdapter;
Ben Kwa24be5d32015-08-27 16:04:46 -07001672 }
1673
1674 /**
1675 * Selects all files in the current directory.
1676 * @return true if the selection state changed for any files.
1677 */
1678 boolean selectAll() {
1679 return mSelectionManager.setItemsSelected(0, mCursorCount, true);
1680 }
1681
1682 /**
1683 * Clones the current selection into the given Selection object.
1684 * @param selection
1685 * @return The selection that was passed in, for convenience.
1686 */
1687 Selection getSelection(Selection selection) {
1688 return mSelectionManager.getSelection(selection);
1689 }
1690
1691 /**
1692 * @return The current selection (the live instance, not a copy).
1693 */
1694 Selection getSelection() {
1695 return mSelectionManager.getSelection();
1696 }
1697
1698 boolean isSelected(int position) {
1699 return mSelectionManager.getSelection().contains(position);
1700 }
1701
1702 void clearSelection() {
1703 mSelectionManager.clearSelection();
1704 }
1705
1706 void update(DirectoryResult result) {
1707 if (DEBUG) Log.i(TAG, "Updating model with new result set.");
1708
1709 if (result == null) {
1710 mCursor = null;
1711 mCursorCount = 0;
1712 info = null;
1713 error = null;
1714 mIsLoading = false;
Ben Kwa83cedf22015-09-11 15:15:45 -07001715 mUpdateListener.onModelUpdate(this);
Ben Kwa24be5d32015-08-27 16:04:46 -07001716 return;
1717 }
1718
1719 if (result.exception != null) {
1720 Log.e(TAG, "Error while loading directory contents", result.exception);
Ben Kwa83cedf22015-09-11 15:15:45 -07001721 mUpdateListener.onModelUpdateFailed(result.exception);
Ben Kwa24be5d32015-08-27 16:04:46 -07001722 return;
1723 }
1724
1725 mCursor = result.cursor;
1726 mCursorCount = mCursor.getCount();
1727
1728 final Bundle extras = mCursor.getExtras();
1729 if (extras != null) {
1730 info = extras.getString(DocumentsContract.EXTRA_INFO);
1731 error = extras.getString(DocumentsContract.EXTRA_ERROR);
1732 mIsLoading = extras.getBoolean(DocumentsContract.EXTRA_LOADING, false);
1733 }
Ben Kwa7461a952015-09-01 11:03:01 -07001734
Ben Kwa83cedf22015-09-11 15:15:45 -07001735 mUpdateListener.onModelUpdate(this);
Ben Kwa24be5d32015-08-27 16:04:46 -07001736 }
1737
Ben Kwa7461a952015-09-01 11:03:01 -07001738 int getItemCount() {
Ben Kwa91923182015-08-27 16:06:33 -07001739 return mCursorCount - mMarkedForDeletion.size();
Ben Kwa24be5d32015-08-27 16:04:46 -07001740 }
1741
Ben Kwa7461a952015-09-01 11:03:01 -07001742 Cursor getItem(int position) {
Ben Kwa91923182015-08-27 16:06:33 -07001743 // Items marked for deletion are masked out of the UI. To do this, for every marked
1744 // item whose position is less than the requested item position, advance the requested
1745 // position by 1.
1746 final int originalPos = position;
1747 final int size = mMarkedForDeletion.size();
Ben Kwa0d0daff2015-09-09 13:49:07 -07001748 for (int i = 0; i < size; ++i) {
Ben Kwa91923182015-08-27 16:06:33 -07001749 // It'd be more concise, but less efficient, to iterate over positions while calling
1750 // mMarkedForDeletion.get. Instead, iterate over deleted entries.
1751 if (mMarkedForDeletion.keyAt(i) <= position && mMarkedForDeletion.valueAt(i)) {
1752 ++position;
1753 }
1754 }
1755
1756 if (DEBUG) {
1757 Log.d(TAG, "Item position adjusted for deletion. Original: " + originalPos
1758 + " Adjusted: " + position);
1759 }
1760
Ben Kwa24be5d32015-08-27 16:04:46 -07001761 if (position >= mCursorCount) {
1762 throw new IndexOutOfBoundsException("Attempt to retrieve " + position + " of " +
1763 mCursorCount + " items");
1764 }
1765
1766 mCursor.moveToPosition(position);
1767 return mCursor;
1768 }
1769
1770 private boolean isEmpty() {
1771 return mCursorCount == 0;
1772 }
1773
1774 private boolean isLoading() {
1775 return mIsLoading;
1776 }
1777
1778 private List<DocumentInfo> getSelectedDocuments() {
1779 Selection sel = getSelection(new Selection());
1780 return getDocuments(sel);
1781 }
1782
Ben Kwa7461a952015-09-01 11:03:01 -07001783 List<DocumentInfo> getDocuments(Selection items) {
Ben Kwa91923182015-08-27 16:06:33 -07001784 final int size = (items != null) ? items.size() : 0;
Ben Kwa24be5d32015-08-27 16:04:46 -07001785
Ben Kwa91923182015-08-27 16:06:33 -07001786 final List<DocumentInfo> docs = new ArrayList<>(size);
Ben Kwa24be5d32015-08-27 16:04:46 -07001787 for (int i = 0; i < size; i++) {
1788 final Cursor cursor = getItem(items.get(i));
1789 checkNotNull(cursor, "Cursor cannot be null.");
1790 final DocumentInfo doc = DocumentInfo.fromDirectoryCursor(cursor);
1791 docs.add(doc);
1792 }
1793 return docs;
1794 }
1795
1796 @Override
1797 public Cursor getCursor() {
1798 if (Looper.myLooper() != Looper.getMainLooper()) {
1799 throw new IllegalStateException("Can't call getCursor from non-main thread.");
1800 }
1801 return mCursor;
1802 }
Ben Kwa91923182015-08-27 16:06:33 -07001803
Ben Kwa7461a952015-09-01 11:03:01 -07001804 List<DocumentInfo> getDocumentsMarkedForDeletion() {
Ben Kwa91923182015-08-27 16:06:33 -07001805 final int size = mMarkedForDeletion.size();
1806 List<DocumentInfo> docs = new ArrayList<>(size);
1807
1808 for (int i = 0; i < size; ++i) {
1809 final int position = mMarkedForDeletion.keyAt(i);
1810 checkState(position < mCursorCount);
1811 mCursor.moveToPosition(position);
1812 final DocumentInfo doc = DocumentInfo.fromDirectoryCursor(mCursor);
1813 docs.add(doc);
1814 }
1815 return docs;
1816 }
1817
1818 /**
1819 * Marks the given files for deletion. This will remove them from the UI. Clients must then
1820 * call either {@link #undoDeletion()} or {@link #finalizeDeletion()} to cancel or confirm
1821 * the deletion, respectively. Only one deletion operation is allowed at a time.
1822 *
1823 * @param selected A selection representing the files to delete.
1824 */
Ben Kwa7461a952015-09-01 11:03:01 -07001825 void markForDeletion(Selection selected) {
Ben Kwa91923182015-08-27 16:06:33 -07001826 // Only one deletion operation at a time.
1827 checkState(mMarkedForDeletion.size() == 0);
1828 // There should never be more to delete than what exists.
1829 checkState(mCursorCount >= selected.size());
1830
1831 final int size = selected.size();
1832 for (int i = 0; i < size; ++i) {
1833 int position = selected.get(i);
1834 if (DEBUG) Log.d(TAG, "Marked position " + position + " for deletion");
1835 mMarkedForDeletion.append(position, true);
Ben Kwa379e1762015-09-21 10:49:52 -07001836 mViewAdapter.notifyItemRemoved(position);
Ben Kwa91923182015-08-27 16:06:33 -07001837 }
1838 }
1839
1840 /**
1841 * Cancels an ongoing deletion operation. All files currently marked for deletion will be
1842 * unmarked, and restored in the UI. See {@link #markForDeletion(Selection)}.
1843 */
Ben Kwa7461a952015-09-01 11:03:01 -07001844 void undoDeletion() {
Ben Kwa91923182015-08-27 16:06:33 -07001845 // Iterate over deleted items, temporarily marking them false in the deletion list, and
1846 // re-adding them to the UI.
1847 final int size = mMarkedForDeletion.size();
1848 for (int i = 0; i < size; ++i) {
1849 final int position = mMarkedForDeletion.keyAt(i);
1850 mMarkedForDeletion.put(position, false);
Ben Kwa379e1762015-09-21 10:49:52 -07001851 mViewAdapter.notifyItemInserted(position);
Ben Kwa91923182015-08-27 16:06:33 -07001852 }
1853
1854 // Then, clear the deletion list.
1855 mMarkedForDeletion.clear();
1856 }
1857
1858 /**
1859 * Finalizes an ongoing deletion operation. All files currently marked for deletion will be
1860 * deleted. See {@link #markForDeletion(Selection)}.
Ben Kwa7461a952015-09-01 11:03:01 -07001861 *
1862 * @param view The view which will be used to interact with the user (e.g. surfacing
1863 * snackbars) for errors, info, etc.
Ben Kwa91923182015-08-27 16:06:33 -07001864 */
Ben Kwa83cedf22015-09-11 15:15:45 -07001865 void finalizeDeletion(Runnable errorCallback) {
Ben Kwa7461a952015-09-01 11:03:01 -07001866 final ContentResolver resolver = mContext.getContentResolver();
Ben Kwa83cedf22015-09-11 15:15:45 -07001867 DeleteFilesTask task = new DeleteFilesTask(resolver, errorCallback);
Ben Kwa7461a952015-09-01 11:03:01 -07001868 task.execute();
Ben Kwa91923182015-08-27 16:06:33 -07001869 }
1870
1871 /**
1872 * A Task which collects the DocumentInfo for documents that have been marked for deletion,
1873 * and actually deletes them.
1874 */
1875 private class DeleteFilesTask extends AsyncTask<Void, Void, List<DocumentInfo>> {
1876 private ContentResolver mResolver;
Ben Kwa7461a952015-09-01 11:03:01 -07001877 private Runnable mErrorCallback;
Ben Kwa91923182015-08-27 16:06:33 -07001878
Ben Kwa7461a952015-09-01 11:03:01 -07001879 /**
1880 * @param resolver A ContentResolver for performing the actual file deletions.
1881 * @param errorCallback A Runnable that is executed in the event that one or more errors
1882 * occured while copying files. Execution will occur on the UI thread.
1883 */
1884 public DeleteFilesTask(ContentResolver resolver, Runnable errorCallback) {
Ben Kwa91923182015-08-27 16:06:33 -07001885 mResolver = resolver;
Ben Kwa7461a952015-09-01 11:03:01 -07001886 mErrorCallback = errorCallback;
Ben Kwa91923182015-08-27 16:06:33 -07001887 }
1888
1889 @Override
1890 protected List<DocumentInfo> doInBackground(Void... params) {
1891 return getDocumentsMarkedForDeletion();
1892 }
1893
1894 @Override
1895 protected void onPostExecute(List<DocumentInfo> docs) {
1896 boolean hadTrouble = false;
1897 for (DocumentInfo doc : docs) {
1898 if (!doc.isDeleteSupported()) {
1899 Log.w(TAG, doc + " could not be deleted. Skipping...");
1900 hadTrouble = true;
1901 continue;
1902 }
1903
1904 ContentProviderClient client = null;
1905 try {
1906 if (DEBUG) Log.d(TAG, "Deleting: " + doc.displayName);
1907 client = DocumentsApplication.acquireUnstableProviderOrThrow(
1908 mResolver, doc.derivedUri.getAuthority());
1909 DocumentsContract.deleteDocument(client, doc.derivedUri);
1910 } catch (Exception e) {
1911 Log.w(TAG, "Failed to delete " + doc);
1912 hadTrouble = true;
1913 } finally {
1914 ContentProviderClient.releaseQuietly(client);
1915 }
1916 }
1917
1918 if (hadTrouble) {
Ben Kwa7461a952015-09-01 11:03:01 -07001919 // TODO show which files failed? b/23720103
1920 mErrorCallback.run();
Ben Kwa91923182015-08-27 16:06:33 -07001921 if (DEBUG) Log.d(TAG, "Deletion task completed. Some deletions failed.");
1922 } else {
1923 if (DEBUG) Log.d(TAG, "Deletion task completed successfully.");
1924 }
1925 mMarkedForDeletion.clear();
1926 }
1927 }
Ben Kwa7461a952015-09-01 11:03:01 -07001928
1929 void addUpdateListener(UpdateListener listener) {
1930 checkState(mUpdateListener == null);
1931 mUpdateListener = listener;
1932 }
1933
Ben Kwa379e1762015-09-21 10:49:52 -07001934 static class UpdateListener {
Ben Kwa7461a952015-09-01 11:03:01 -07001935 /**
1936 * Called when a successful update has occurred.
1937 */
Ben Kwa379e1762015-09-21 10:49:52 -07001938 void onModelUpdate(Model model) {}
Ben Kwa7461a952015-09-01 11:03:01 -07001939
1940 /**
1941 * Called when an update has been attempted but failed.
1942 */
Ben Kwa379e1762015-09-21 10:49:52 -07001943 void onModelUpdateFailed(Exception e) {}
1944 }
1945 }
Ben Kwa7461a952015-09-01 11:03:01 -07001946
Ben Kwa379e1762015-09-21 10:49:52 -07001947 private class ModelUpdateListener extends Model.UpdateListener {
1948 @Override
1949 public void onModelUpdate(Model model) {
1950 if (model.info != null || model.error != null) {
1951 mMessageBar.setInfo(model.info);
1952 mMessageBar.setError(model.error);
1953 mMessageBar.show();
1954 }
Ben Kwa7461a952015-09-01 11:03:01 -07001955
Ben Kwa379e1762015-09-21 10:49:52 -07001956 mProgressBar.setVisibility(model.isLoading() ? View.VISIBLE : View.GONE);
1957
1958 if (model.isEmpty()) {
1959 mEmptyView.setVisibility(View.VISIBLE);
1960 mRecView.setVisibility(View.GONE);
1961 } else {
1962 mEmptyView.setVisibility(View.GONE);
1963 mRecView.setVisibility(View.VISIBLE);
1964 }
1965
1966 mAdapter.notifyDataSetChanged();
1967 }
1968
1969 @Override
1970 public void onModelUpdateFailed(Exception e) {
1971 // TODO: deal with catastrophic update failures
1972 String error = getString(R.string.query_error);
1973 mAdapter.notifyDataSetChanged();
Ben Kwa7461a952015-09-01 11:03:01 -07001974 }
Ben Kwa24be5d32015-08-27 16:04:46 -07001975 }
Jeff Sharkeye22d02e2013-04-26 16:54:55 -07001976}