blob: f692d1cabbf5d1901a717d934e823c36ca7492b0 [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
Steve McKayf8a5e082015-09-23 17:21:40 -070019import static com.android.documentsui.Shared.DEBUG;
Steve McKayfefcd702015-08-20 16:19:38 +000020import static com.android.documentsui.Shared.TAG;
Steve McKayf8a5e082015-09-23 17:21:40 -070021import static com.android.documentsui.State.ACTION_BROWSE;
22import static com.android.documentsui.State.ACTION_CREATE;
23import static com.android.documentsui.State.ACTION_MANAGE;
24import static com.android.documentsui.State.MODE_GRID;
25import static com.android.documentsui.State.MODE_LIST;
26import static com.android.documentsui.State.MODE_UNKNOWN;
27import static com.android.documentsui.State.SORT_ORDER_UNKNOWN;
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 McKayef280152015-06-11 10:10:49 -070097import com.android.documentsui.MultiSelectManager.Selection;
Jeff Sharkey753a3ae2013-10-22 17:09:44 -070098import com.android.documentsui.ProviderExecutor.Preemptable;
Jeff Sharkeyd10f0492013-09-09 17:35:46 -070099import com.android.documentsui.RecentsProvider.StateColumns;
Jeff Sharkey724deeb2013-08-31 15:02:20 -0700100import com.android.documentsui.model.DocumentInfo;
Tomasz Mikolajewski9452c442015-04-14 16:32:41 +0900101import com.android.documentsui.model.DocumentStack;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700102import com.android.documentsui.model.RootInfo;
Steve McKayfad3d4a2015-09-22 15:09:21 -0700103
Steve McKayfefcd702015-08-20 16:19:38 +0000104import com.google.common.collect.Lists;
Jeff Sharkeyc317af82013-07-01 16:56:54 -0700105
106import java.util.ArrayList;
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -0700107import java.util.Collections;
Jeff Sharkeya5defe32013-08-05 17:56:48 -0700108import java.util.List;
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700109
110/**
111 * Display the documents inside a single directory.
112 */
113public class DirectoryFragment extends Fragment {
114
Jeff Sharkeya5defe32013-08-05 17:56:48 -0700115 public static final int TYPE_NORMAL = 1;
116 public static final int TYPE_SEARCH = 2;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700117 public static final int TYPE_RECENT_OPEN = 3;
Jeff Sharkey5b535922013-08-02 15:55:26 -0700118
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700119 public static final int ANIM_NONE = 1;
120 public static final int ANIM_SIDE = 2;
121 public static final int ANIM_DOWN = 3;
122 public static final int ANIM_UP = 4;
123
Ben Kwaf5858932015-04-07 15:43:39 -0700124 public static final int REQUEST_COPY_DESTINATION = 1;
125
Steve McKayef280152015-06-11 10:10:49 -0700126 private static final int LOADER_ID = 42;
Steve McKay8e258c62015-05-06 14:27:57 -0700127 private static final boolean DEBUG_ENABLE_DND = false;
128
Jeff Sharkey2e694f82013-08-06 16:26:14 -0700129 private static final String EXTRA_TYPE = "type";
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700130 private static final String EXTRA_ROOT = "root";
131 private static final String EXTRA_DOC = "doc";
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700132 private static final String EXTRA_QUERY = "query";
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700133 private static final String EXTRA_IGNORE_STATE = "ignoreState";
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700134
Ben Kwa7461a952015-09-01 11:03:01 -0700135 private Model mModel;
Ben Kwa379e1762015-09-21 10:49:52 -0700136 private Model.UpdateListener mModelUpdateListener = new ModelUpdateListener();
Ben Kwa24be5d32015-08-27 16:04:46 -0700137
Steve McKayef280152015-06-11 10:10:49 -0700138 private final Handler mHandler = new Handler(Looper.getMainLooper());
Jeff Sharkey2e694f82013-08-06 16:26:14 -0700139
Steve McKayef280152015-06-11 10:10:49 -0700140 private View mEmptyView;
141 private RecyclerView mRecView;
142
143 private int mType = TYPE_NORMAL;
144 private String mStateKey;
145
146 private int mLastMode = MODE_UNKNOWN;
147 private int mLastSortOrder = SORT_ORDER_UNKNOWN;
148 private boolean mLastShowSize;
149 private boolean mHideGridTitles;
150 private boolean mSvelteRecents;
151 private Point mThumbSize;
152 private DocumentsAdapter mAdapter;
153 private LoaderCallbacks<DirectoryResult> mCallbacks;
Steve McKay1f199482015-05-20 15:58:42 -0700154 private FragmentTuner mFragmentTuner;
155 private DocumentClipper mClipper;
Steve McKayef280152015-06-11 10:10:49 -0700156 // These are lazily initialized.
Steve McKayd57f5fa2015-07-23 16:33:41 -0700157 private LinearLayoutManager mListLayout;
158 private GridLayoutManager mGridLayout;
Steve McKayd57f5fa2015-07-23 16:33:41 -0700159 private int mColumnCount = 1; // This will get updated when layout changes.
Steve McKay1f199482015-05-20 15:58:42 -0700160
Ben Kwac42fa402015-09-16 08:04:37 -0700161 private MessageBar mMessageBar;
Ben Kwa379e1762015-09-21 10:49:52 -0700162 private View mProgressBar;
Ben Kwac42fa402015-09-16 08:04:37 -0700163
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700164 public static void showNormal(FragmentManager fm, RootInfo root, DocumentInfo doc, int anim) {
165 show(fm, TYPE_NORMAL, root, doc, null, anim);
Jeff Sharkey2e694f82013-08-06 16:26:14 -0700166 }
167
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700168 public static void showSearch(FragmentManager fm, RootInfo root, String query, int anim) {
169 show(fm, TYPE_SEARCH, root, null, query, anim);
Jeff Sharkey2e694f82013-08-06 16:26:14 -0700170 }
171
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700172 public static void showRecentsOpen(FragmentManager fm, int anim) {
173 show(fm, TYPE_RECENT_OPEN, null, null, null, anim);
Jeff Sharkey2e694f82013-08-06 16:26:14 -0700174 }
175
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700176 private static void show(FragmentManager fm, int type, RootInfo root, DocumentInfo doc,
177 String query, int anim) {
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700178 final Bundle args = new Bundle();
Jeff Sharkey2e694f82013-08-06 16:26:14 -0700179 args.putInt(EXTRA_TYPE, type);
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700180 args.putParcelable(EXTRA_ROOT, root);
181 args.putParcelable(EXTRA_DOC, doc);
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700182 args.putString(EXTRA_QUERY, query);
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700183
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700184 final FragmentTransaction ft = fm.beginTransaction();
185 switch (anim) {
186 case ANIM_SIDE:
187 args.putBoolean(EXTRA_IGNORE_STATE, true);
188 break;
189 case ANIM_DOWN:
190 args.putBoolean(EXTRA_IGNORE_STATE, true);
191 ft.setCustomAnimations(R.animator.dir_down, R.animator.dir_frozen);
192 break;
193 case ANIM_UP:
194 ft.setCustomAnimations(R.animator.dir_frozen, R.animator.dir_up);
195 break;
196 }
197
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700198 final DirectoryFragment fragment = new DirectoryFragment();
199 fragment.setArguments(args);
200
Jeff Sharkey76112212013-08-06 11:26:10 -0700201 ft.replace(R.id.container_directory, fragment);
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700202 ft.commitAllowingStateLoss();
203 }
204
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700205 private static String buildStateKey(RootInfo root, DocumentInfo doc) {
206 final StringBuilder builder = new StringBuilder();
207 builder.append(root != null ? root.authority : "null").append(';');
208 builder.append(root != null ? root.rootId : "null").append(';');
209 builder.append(doc != null ? doc.documentId : "null");
210 return builder.toString();
211 }
212
Jeff Sharkeya5defe32013-08-05 17:56:48 -0700213 public static DirectoryFragment get(FragmentManager fm) {
214 // TODO: deal with multiple directories shown at once
Jeff Sharkey76112212013-08-06 11:26:10 -0700215 return (DirectoryFragment) fm.findFragmentById(R.id.container_directory);
Jeff Sharkeya5defe32013-08-05 17:56:48 -0700216 }
217
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700218 @Override
219 public View onCreateView(
220 LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
221 final Context context = inflater.getContext();
Jeff Sharkey083d7e12014-07-27 21:01:45 -0700222 final Resources res = context.getResources();
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700223 final View view = inflater.inflate(R.layout.fragment_directory, container, false);
224
Ben Kwac42fa402015-09-16 08:04:37 -0700225 mMessageBar = MessageBar.create(getChildFragmentManager());
Ben Kwa379e1762015-09-21 10:49:52 -0700226 mProgressBar = view.findViewById(R.id.progressbar);
Ben Kwac42fa402015-09-16 08:04:37 -0700227
Jeff Sharkeyc6cbdf12013-08-07 16:22:02 -0700228 mEmptyView = view.findViewById(android.R.id.empty);
229
Steve McKayef280152015-06-11 10:10:49 -0700230 mRecView = (RecyclerView) view.findViewById(R.id.recyclerView);
231 mRecView.setRecyclerListener(
232 new RecyclerListener() {
233 @Override
234 public void onViewRecycled(ViewHolder holder) {
235 cancelThumbnailTask(holder.itemView);
236 }
237 });
Steve McKay8e258c62015-05-06 14:27:57 -0700238
Steve McKayd57f5fa2015-07-23 16:33:41 -0700239 // TODO: Rather than update columns on layout changes, push this
240 // code (or something like it) into GridLayoutManager.
241 mRecView.addOnLayoutChangeListener(
242 new OnLayoutChangeListener() {
243
244 @Override
245 public void onLayoutChange(
246 View v, int left, int top, int right, int bottom, int oldLeft,
247 int oldTop, int oldRight, int oldBottom) {
Steve McKayfefcd702015-08-20 16:19:38 +0000248 mColumnCount = calculateColumnCount();
Steve McKayd57f5fa2015-07-23 16:33:41 -0700249 if (mGridLayout != null) {
250 mGridLayout.setSpanCount(mColumnCount);
251 }
252 }
253 });
254
255 // TODO: Add a divider between views (which might use RecyclerView.ItemDecoration).
Steve McKay8e258c62015-05-06 14:27:57 -0700256 if (DEBUG_ENABLE_DND) {
Steve McKayef280152015-06-11 10:10:49 -0700257 setupDragAndDropOnDirectoryView(mRecView);
Steve McKay8e258c62015-05-06 14:27:57 -0700258 }
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700259
Jeff Sharkeyac9e6272013-08-31 21:27:44 -0700260 return view;
261 }
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700262
Jeff Sharkeyac9e6272013-08-31 21:27:44 -0700263 @Override
Jeff Sharkeyf63b7772013-10-01 17:57:41 -0700264 public void onDestroyView() {
265 super.onDestroyView();
266
267 // Cancel any outstanding thumbnail requests
Steve McKayef280152015-06-11 10:10:49 -0700268 final int count = mRecView.getChildCount();
Jeff Sharkeyf63b7772013-10-01 17:57:41 -0700269 for (int i = 0; i < count; i++) {
Steve McKayef280152015-06-11 10:10:49 -0700270 final View view = mRecView.getChildAt(i);
271 cancelThumbnailTask(view);
Jeff Sharkeyf63b7772013-10-01 17:57:41 -0700272 }
Jeff Sharkeyfaaeb392013-10-04 14:44:56 -0700273
Steve McKayef280152015-06-11 10:10:49 -0700274 // Clear any outstanding selection
Ben Kwa24be5d32015-08-27 16:04:46 -0700275 mModel.clearSelection();
Jeff Sharkeyf63b7772013-10-01 17:57:41 -0700276 }
277
278 @Override
Jeff Sharkeyac9e6272013-08-31 21:27:44 -0700279 public void onActivityCreated(Bundle savedInstanceState) {
280 super.onActivityCreated(savedInstanceState);
281
282 final Context context = getActivity();
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700283 final State state = getDisplayState(DirectoryFragment.this);
Jeff Sharkeyac9e6272013-08-31 21:27:44 -0700284
Jeff Sharkey9656a532013-09-13 13:42:19 -0700285 final RootInfo root = getArguments().getParcelable(EXTRA_ROOT);
286 final DocumentInfo doc = getArguments().getParcelable(EXTRA_DOC);
287
Steve McKayef280152015-06-11 10:10:49 -0700288 mAdapter = new DocumentsAdapter(context);
289 mRecView.setAdapter(mAdapter);
290
291 GestureDetector.SimpleOnGestureListener listener =
292 new GestureDetector.SimpleOnGestureListener() {
293 @Override
294 public boolean onSingleTapUp(MotionEvent e) {
295 return DirectoryFragment.this.onSingleTapUp(e);
296 }
Steve McKay93d8ef42015-07-30 12:27:44 -0700297 @Override
298 public boolean onDoubleTap(MotionEvent e) {
299 Log.d(TAG, "Handling double tap.");
300 return DirectoryFragment.this.onDoubleTap(e);
301 }
Steve McKayef280152015-06-11 10:10:49 -0700302 };
303
Ben Kwa24be5d32015-08-27 16:04:46 -0700304 // TODO: instead of inserting the view into the constructor, extract listener-creation code
305 // and set the listener on the view after the fact. Then the view doesn't need to be passed
306 // into the selection manager which is passed into the model.
307 MultiSelectManager selMgr= new MultiSelectManager(
Steve McKay57394872015-08-12 14:48:34 -0700308 mRecView,
309 listener,
310 state.allowMultiple
311 ? MultiSelectManager.MODE_MULTIPLE
312 : MultiSelectManager.MODE_SINGLE);
Ben Kwa24be5d32015-08-27 16:04:46 -0700313 selMgr.addCallback(new SelectionModeListener());
Ben Kwa7461a952015-09-01 11:03:01 -0700314
Ben Kwa379e1762015-09-21 10:49:52 -0700315 mModel = new Model(context, selMgr, mAdapter);
316 mModel.addUpdateListener(mModelUpdateListener);
Steve McKayef280152015-06-11 10:10:49 -0700317
Jeff Sharkey2e694f82013-08-06 16:26:14 -0700318 mType = getArguments().getInt(EXTRA_TYPE);
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700319 mStateKey = buildStateKey(root, doc);
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700320
Steve McKay1f199482015-05-20 15:58:42 -0700321 mFragmentTuner = pickFragmentTuner(state);
322 mClipper = new DocumentClipper(context);
323
Jeff Sharkey9656a532013-09-13 13:42:19 -0700324 if (mType == TYPE_RECENT_OPEN) {
325 // Hide titles when showing recents for picking images/videos
326 mHideGridTitles = MimePredicate.mimeMatches(
327 MimePredicate.VISUAL_MIMES, state.acceptMimes);
328 } else {
329 mHideGridTitles = (doc != null) && doc.isGridTitlesHidden();
330 }
331
Jeff Sharkeyf63b7772013-10-01 17:57:41 -0700332 final ActivityManager am = (ActivityManager) context.getSystemService(
333 Context.ACTIVITY_SERVICE);
334 mSvelteRecents = am.isLowRamDevice() && (mType == TYPE_RECENT_OPEN);
335
Jeff Sharkey46899c82013-08-18 22:26:48 -0700336 mCallbacks = new LoaderCallbacks<DirectoryResult>() {
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700337 @Override
Jeff Sharkey46899c82013-08-18 22:26:48 -0700338 public Loader<DirectoryResult> onCreateLoader(int id, Bundle args) {
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700339 final String query = getArguments().getString(EXTRA_QUERY);
Jeff Sharkey46165b52013-07-31 20:53:22 -0700340
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700341 Uri contentsUri;
342 switch (mType) {
343 case TYPE_NORMAL:
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700344 contentsUri = DocumentsContract.buildChildDocumentsUri(
345 doc.authority, doc.documentId);
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700346 if (state.action == ACTION_MANAGE) {
347 contentsUri = DocumentsContract.setManageMode(contentsUri);
348 }
Jeff Sharkeyd10f0492013-09-09 17:35:46 -0700349 return new DirectoryLoader(
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700350 context, mType, root, doc, contentsUri, state.userSortOrder);
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700351 case TYPE_SEARCH:
352 contentsUri = DocumentsContract.buildSearchDocumentsUri(
Jeff Sharkey0e8c8712013-09-12 21:59:06 -0700353 root.authority, root.rootId, query);
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700354 if (state.action == ACTION_MANAGE) {
355 contentsUri = DocumentsContract.setManageMode(contentsUri);
356 }
Jeff Sharkeyd10f0492013-09-09 17:35:46 -0700357 return new DirectoryLoader(
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700358 context, mType, root, doc, contentsUri, state.userSortOrder);
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700359 case TYPE_RECENT_OPEN:
Jeff Sharkey1c903cc2013-09-02 17:19:40 -0700360 final RootsCache roots = DocumentsApplication.getRootsCache(context);
Jeff Sharkey8b997042013-09-19 15:25:56 -0700361 return new RecentLoader(context, roots, state);
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700362 default:
363 throw new IllegalStateException("Unknown type " + mType);
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700364 }
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700365 }
366
367 @Override
Jeff Sharkey46899c82013-08-18 22:26:48 -0700368 public void onLoadFinished(Loader<DirectoryResult> loader, DirectoryResult result) {
Makoto Onuki77778752015-07-01 14:55:14 -0700369 if (result == null || result.exception != null) {
370 // onBackPressed does a fragment transaction, which can't be done inside
371 // onLoadFinished
372 mHandler.post(new Runnable() {
373 @Override
374 public void run() {
375 final Activity activity = getActivity();
376 if (activity != null) {
377 activity.onBackPressed();
378 }
379 }
380 });
381 return;
382 }
383
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700384 if (!isAdded()) return;
385
Ben Kwa24be5d32015-08-27 16:04:46 -0700386 mModel.update(result);
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700387
388 // Push latest state up to UI
389 // TODO: if mode change was racing with us, don't overwrite it
Jeff Sharkey7d58fc62013-09-12 16:25:02 -0700390 if (result.mode != MODE_UNKNOWN) {
391 state.derivedMode = result.mode;
392 }
Jeff Sharkeyd10f0492013-09-09 17:35:46 -0700393 state.derivedSortOrder = result.sortOrder;
Steve McKayd0a2a2c2015-03-25 14:35:33 -0700394 ((BaseActivity) context).onStateChanged();
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700395
396 updateDisplayState();
397
Jeff Sharkey25f10b32013-10-07 14:08:17 -0700398 // When launched into empty recents, show drawer
Ben Kwa24be5d32015-08-27 16:04:46 -0700399 if (mType == TYPE_RECENT_OPEN && mModel.isEmpty() && !state.stackTouched &&
Steve McKayb68dd222015-04-20 17:18:15 -0700400 context instanceof DocumentsActivity) {
401 ((DocumentsActivity) context).setRootsDrawerOpen(true);
Jeff Sharkey25f10b32013-10-07 14:08:17 -0700402 }
403
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700404 // Restore any previous instance state
405 final SparseArray<Parcelable> container = state.dirState.remove(mStateKey);
406 if (container != null && !getArguments().getBoolean(EXTRA_IGNORE_STATE, false)) {
407 getView().restoreHierarchyState(container);
408 } else if (mLastSortOrder != state.derivedSortOrder) {
Steve McKayef280152015-06-11 10:10:49 -0700409 mRecView.smoothScrollToPosition(0);
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700410 }
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700411
412 mLastSortOrder = state.derivedSortOrder;
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700413 }
414
415 @Override
Jeff Sharkey46899c82013-08-18 22:26:48 -0700416 public void onLoaderReset(Loader<DirectoryResult> loader) {
Ben Kwa24be5d32015-08-27 16:04:46 -0700417 mModel.update(null);
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700418 }
419 };
420
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700421 // Kick off loader at least once
Steve McKayef280152015-06-11 10:10:49 -0700422 getLoaderManager().restartLoader(LOADER_ID, null, mCallbacks);
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700423
Kyle Horimoto426bd0d2015-07-29 15:33:49 -0700424 mFragmentTuner.afterActivityCreated(this);
Jeff Sharkey2e694f82013-08-06 16:26:14 -0700425 updateDisplayState();
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700426 }
427
Jeff Sharkey42d26792013-09-06 13:22:09 -0700428 @Override
Ben Kwaf5858932015-04-07 15:43:39 -0700429 public void onActivityResult(int requestCode, int resultCode, Intent data) {
Ben Kwaf5858932015-04-07 15:43:39 -0700430 // There's only one request code right now. Replace this with a switch statement or
431 // something more scalable when more codes are added.
432 if (requestCode != REQUEST_COPY_DESTINATION) {
433 return;
434 }
435 if (resultCode == Activity.RESULT_CANCELED || data == null) {
436 // User pressed the back button or otherwise cancelled the destination pick. Don't
437 // proceed with the copy.
438 return;
439 }
440
Tomasz Mikolajewski9452c442015-04-14 16:32:41 +0900441 CopyService.start(getActivity(), getDisplayState(this).selectedDocumentsForCopy,
Ben Kwacb4461f2015-05-05 11:50:11 -0700442 (DocumentStack) data.getParcelableExtra(CopyService.EXTRA_STACK),
443 data.getIntExtra(CopyService.EXTRA_TRANSFER_MODE, CopyService.TRANSFER_MODE_NONE));
Ben Kwaf5858932015-04-07 15:43:39 -0700444 }
445
Steve McKayef280152015-06-11 10:10:49 -0700446 private int getEventAdapterPosition(MotionEvent e) {
447 View view = mRecView.findChildViewUnder(e.getX(), e.getY());
448 return view != null ? mRecView.getChildAdapterPosition(view) : RecyclerView.NO_POSITION;
449 }
450
451 private boolean onSingleTapUp(MotionEvent e) {
Ben Kwa24be5d32015-08-27 16:04:46 -0700452 if (Events.isTouchEvent(e) && mModel.getSelection().isEmpty()) {
Steve McKay93d8ef42015-07-30 12:27:44 -0700453 int position = getEventAdapterPosition(e);
454 if (position != RecyclerView.NO_POSITION) {
455 return handleViewItem(position);
Steve McKayef280152015-06-11 10:10:49 -0700456 }
457 }
Steve McKay93d8ef42015-07-30 12:27:44 -0700458 return false;
459 }
Steve McKayef280152015-06-11 10:10:49 -0700460
Steve McKay93d8ef42015-07-30 12:27:44 -0700461 protected boolean onDoubleTap(MotionEvent e) {
462 if (Events.isMouseEvent(e)) {
463 Log.d(TAG, "Handling double tap from mouse.");
464 int position = getEventAdapterPosition(e);
465 if (position != RecyclerView.NO_POSITION) {
466 return handleViewItem(position);
467 }
468 }
469 return false;
470 }
471
472 private boolean handleViewItem(int position) {
Ben Kwa24be5d32015-08-27 16:04:46 -0700473 final Cursor cursor = mModel.getItem(position);
Steve McKay93d8ef42015-07-30 12:27:44 -0700474 checkNotNull(cursor, "Cursor cannot be null.");
475 final String docMimeType = getCursorString(cursor, Document.COLUMN_MIME_TYPE);
476 final int docFlags = getCursorInt(cursor, Document.COLUMN_FLAGS);
477 if (isDocumentEnabled(docMimeType, docFlags)) {
478 final DocumentInfo doc = DocumentInfo.fromDirectoryCursor(cursor);
Ben Kwa24be5d32015-08-27 16:04:46 -0700479 ((BaseActivity) getActivity()).onDocumentPicked(doc, mModel);
480 mModel.clearSelection();
Steve McKay93d8ef42015-07-30 12:27:44 -0700481 return true;
482 }
Steve McKayef280152015-06-11 10:10:49 -0700483 return false;
484 }
485
Ben Kwaf5858932015-04-07 15:43:39 -0700486 @Override
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700487 public void onStop() {
488 super.onStop();
489
490 // Remember last scroll location
491 final SparseArray<Parcelable> container = new SparseArray<Parcelable>();
492 getView().saveHierarchyState(container);
493 final State state = getDisplayState(this);
494 state.dirState.put(mStateKey, container);
495 }
496
497 @Override
Jeff Sharkey7d58fc62013-09-12 16:25:02 -0700498 public void onResume() {
499 super.onResume();
Jeff Sharkey42d26792013-09-06 13:22:09 -0700500 updateDisplayState();
501 }
502
Jeff Sharkeye8d13ea2014-08-08 15:10:03 -0700503 public void onDisplayStateChanged() {
504 updateDisplayState();
505 }
506
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700507 public void onUserSortOrderChanged() {
Jeff Sharkeyd10f0492013-09-09 17:35:46 -0700508 // Sort order change always triggers reload; we'll trigger state change
509 // on the flip side.
Steve McKayef280152015-06-11 10:10:49 -0700510 getLoaderManager().restartLoader(LOADER_ID, null, mCallbacks);
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700511 }
512
513 public void onUserModeChanged() {
Jeff Sharkeyd10f0492013-09-09 17:35:46 -0700514 final ContentResolver resolver = getActivity().getContentResolver();
515 final State state = getDisplayState(this);
516
517 final RootInfo root = getArguments().getParcelable(EXTRA_ROOT);
518 final DocumentInfo doc = getArguments().getParcelable(EXTRA_DOC);
519
Jeff Sharkey0e8c8712013-09-12 21:59:06 -0700520 if (root != null && doc != null) {
Jeff Sharkey7d58fc62013-09-12 16:25:02 -0700521 final Uri stateUri = RecentsProvider.buildState(
522 root.authority, root.rootId, doc.documentId);
523 final ContentValues values = new ContentValues();
524 values.put(StateColumns.MODE, state.userMode);
Jeff Sharkeyd10f0492013-09-09 17:35:46 -0700525
Jeff Sharkey7d58fc62013-09-12 16:25:02 -0700526 new AsyncTask<Void, Void, Void>() {
527 @Override
528 protected Void doInBackground(Void... params) {
529 resolver.insert(stateUri, values);
530 return null;
531 }
532 }.execute();
533 }
Jeff Sharkeyd10f0492013-09-09 17:35:46 -0700534
535 // Mode change is just visual change; no need to kick loader, and
536 // deliver change event immediately.
537 state.derivedMode = state.userMode;
Steve McKayd0a2a2c2015-03-25 14:35:33 -0700538 ((BaseActivity) getActivity()).onStateChanged();
Jeff Sharkeyd10f0492013-09-09 17:35:46 -0700539
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700540 updateDisplayState();
541 }
542
543 private void updateDisplayState() {
Jeff Sharkeyb3620442013-09-01 18:41:04 -0700544 final State state = getDisplayState(this);
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700545
Jeff Sharkey5e1884d2013-09-10 17:56:39 -0700546 if (mLastMode == state.derivedMode && mLastShowSize == state.showSize) return;
Jeff Sharkeyd10f0492013-09-09 17:35:46 -0700547 mLastMode = state.derivedMode;
Jeff Sharkey5e1884d2013-09-10 17:56:39 -0700548 mLastShowSize = state.showSize;
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700549
Steve McKayef280152015-06-11 10:10:49 -0700550 updateLayout(state.derivedMode);
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700551
Steve McKayef280152015-06-11 10:10:49 -0700552 mRecView.setAdapter(mAdapter);
553 }
554
555 /**
556 * Returns a {@code LayoutManager} for {@code mode}, lazily initializing
557 * classes as needed.
558 */
559 private void updateLayout(int mode) {
Jeff Sharkey8a8fb672013-05-07 12:41:33 -0700560 final int thumbSize;
Steve McKayef280152015-06-11 10:10:49 -0700561
562 final LayoutManager layout;
563 switch (mode) {
564 case MODE_GRID:
Steve McKayef280152015-06-11 10:10:49 -0700565 thumbSize = getResources().getDimensionPixelSize(R.dimen.grid_width);
Steve McKaya9be7182015-07-22 16:03:35 -0700566 if (mGridLayout == null) {
Steve McKayd57f5fa2015-07-23 16:33:41 -0700567 mGridLayout = new GridLayoutManager(getContext(), mColumnCount );
Steve McKaya9be7182015-07-22 16:03:35 -0700568 }
Steve McKayef280152015-06-11 10:10:49 -0700569 layout = mGridLayout;
570 break;
571 case MODE_LIST:
Steve McKaya9be7182015-07-22 16:03:35 -0700572 thumbSize = getResources().getDimensionPixelSize(R.dimen.icon_size);
Steve McKayef280152015-06-11 10:10:49 -0700573 if (mListLayout == null) {
574 mListLayout = new LinearLayoutManager(getContext());
575 }
Steve McKayef280152015-06-11 10:10:49 -0700576 layout = mListLayout;
577 break;
578 case MODE_UNKNOWN:
579 default:
580 throw new IllegalArgumentException("Unsupported layout mode: " + mode);
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700581 }
Jeff Sharkey8a8fb672013-05-07 12:41:33 -0700582
Steve McKayef280152015-06-11 10:10:49 -0700583 mRecView.setLayoutManager(layout);
Kyle Horimoto2da6e4a2015-08-27 16:44:00 -0700584 // TODO: Once b/23691541 is resolved, use a listener within MultiSelectManager instead of
585 // imperatively calling this function.
Steve McKay9058e042015-09-01 12:31:24 -0700586 mModel.mSelectionManager.handleLayoutChanged();
Steve McKayef280152015-06-11 10:10:49 -0700587 // setting layout manager automatically invalidates existing ViewHolders.
Jeff Sharkey8a8fb672013-05-07 12:41:33 -0700588 mThumbSize = new Point(thumbSize, thumbSize);
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700589 }
590
Steve McKayfefcd702015-08-20 16:19:38 +0000591 private int calculateColumnCount() {
592 int cellWidth = getResources().getDimensionPixelSize(R.dimen.grid_width);
593 int cellMargin = 2 * getResources().getDimensionPixelSize(R.dimen.grid_item_margin);
Steve McKayd57f5fa2015-07-23 16:33:41 -0700594 int viewPadding = mRecView.getPaddingLeft() + mRecView.getPaddingRight();
Steve McKayfefcd702015-08-20 16:19:38 +0000595
Steve McKayd57f5fa2015-07-23 16:33:41 -0700596 checkState(mRecView.getWidth() > 0);
597 int columnCount = Math.max(1,
Steve McKayfefcd702015-08-20 16:19:38 +0000598 (mRecView.getWidth() - viewPadding) / (cellWidth + cellMargin));
599
Steve McKayd57f5fa2015-07-23 16:33:41 -0700600 return columnCount;
601 }
602
Steve McKayef280152015-06-11 10:10:49 -0700603 /**
604 * Manages the integration between our ActionMode and MultiSelectManager, initiating
605 * ActionMode when there is a selection, canceling it when there is no selection,
606 * and clearing selection when action mode is explicitly exited by the user.
607 */
608 private final class SelectionModeListener
609 implements MultiSelectManager.Callback, ActionMode.Callback {
610
611 private Selection mSelected = new Selection();
612 private ActionMode mActionMode;
Steve McKay4f4232d2015-07-22 12:13:46 -0700613 private int mNoDeleteCount = 0;
614 private Menu mMenu;
Steve McKayef280152015-06-11 10:10:49 -0700615
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700616 @Override
Steve McKayef280152015-06-11 10:10:49 -0700617 public boolean onBeforeItemStateChange(int position, boolean selected) {
Ben Kwac42fa402015-09-16 08:04:37 -0700618 // Directories cannot be checked
Steve McKayef280152015-06-11 10:10:49 -0700619 if (selected) {
Ben Kwa24be5d32015-08-27 16:04:46 -0700620 final Cursor cursor = mModel.getItem(position);
Steve McKayef280152015-06-11 10:10:49 -0700621 checkNotNull(cursor, "Cursor cannot be null.");
Jeff Sharkey7cf49032013-09-26 10:54:16 -0700622 final String docMimeType = getCursorString(cursor, Document.COLUMN_MIME_TYPE);
623 final int docFlags = getCursorInt(cursor, Document.COLUMN_FLAGS);
Steve McKayef280152015-06-11 10:10:49 -0700624 return isDocumentEnabled(docMimeType, docFlags);
625 }
626 return true;
627 }
628
629 @Override
630 public void onItemStateChanged(int position, boolean selected) {
Steve McKay4f4232d2015-07-22 12:13:46 -0700631
Ben Kwa24be5d32015-08-27 16:04:46 -0700632 final Cursor cursor = mModel.getItem(position);
Steve McKay4f4232d2015-07-22 12:13:46 -0700633 checkNotNull(cursor, "Cursor cannot be null.");
634
635 final int docFlags = getCursorInt(cursor, Document.COLUMN_FLAGS);
636 if ((docFlags & Document.FLAG_SUPPORTS_DELETE) == 0) {
637 mNoDeleteCount += selected ? 1 : -1;
638 }
Steve McKay57394872015-08-12 14:48:34 -0700639 }
Steve McKay4f4232d2015-07-22 12:13:46 -0700640
Steve McKay57394872015-08-12 14:48:34 -0700641 @Override
642 public void onSelectionChanged() {
Ben Kwa24be5d32015-08-27 16:04:46 -0700643 mModel.getSelection(mSelected);
Ben Kwafe18c1b2015-09-11 15:40:18 -0700644 TypedValue color = new TypedValue();
Steve McKay4f4232d2015-07-22 12:13:46 -0700645 if (mSelected.size() > 0) {
Steve McKayef280152015-06-11 10:10:49 -0700646 if (DEBUG) Log.d(TAG, "Maybe starting action mode.");
647 if (mActionMode == null) {
648 if (DEBUG) Log.d(TAG, "Yeah. Starting action mode.");
649 mActionMode = getActivity().startActionMode(this);
Jeff Sharkeyaed873d2013-09-09 16:51:06 -0700650 }
Ben Kwafe18c1b2015-09-11 15:40:18 -0700651 getActivity().getTheme().resolveAttribute(
652 R.attr.colorActionMode, color, true);
Steve McKay4f4232d2015-07-22 12:13:46 -0700653 updateActionMenu();
654 } else {
655 if (DEBUG) Log.d(TAG, "Finishing action mode.");
656 if (mActionMode != null) {
657 mActionMode.finish();
658 }
Ben Kwa0574b182015-09-08 07:31:19 -0700659 getActivity().getTheme().resolveAttribute(
660 android.R.attr.colorPrimaryDark, color, true);
Jeff Sharkeyf339f252013-08-15 16:17:41 -0700661 }
Ben Kwafe18c1b2015-09-11 15:40:18 -0700662 getActivity().getWindow().setStatusBarColor(color.data);
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700663
Steve McKayef280152015-06-11 10:10:49 -0700664 if (mActionMode != null) {
665 mActionMode.setTitle(TextUtils.formatSelectedCount(mSelected.size()));
666 }
667 }
668
669 // Called when the user exits the action mode
670 @Override
671 public void onDestroyActionMode(ActionMode mode) {
672 if (DEBUG) Log.d(TAG, "Handling action mode destroyed.");
673 mActionMode = null;
674 // clear selection
Ben Kwa24be5d32015-08-27 16:04:46 -0700675 mModel.clearSelection();
Steve McKay4f4232d2015-07-22 12:13:46 -0700676 mSelected.clear();
677 mNoDeleteCount = 0;
Steve McKayef280152015-06-11 10:10:49 -0700678 }
679
Jeff Sharkeyc317af82013-07-01 16:56:54 -0700680 @Override
681 public boolean onCreateActionMode(ActionMode mode, Menu menu) {
682 mode.getMenuInflater().inflate(R.menu.mode_directory, menu);
Ben Kwa24be5d32015-08-27 16:04:46 -0700683 mode.setTitle(TextUtils.formatSelectedCount(mModel.getSelection().size()));
684 return mModel.getSelection().size() > 0;
Jeff Sharkeyc317af82013-07-01 16:56:54 -0700685 }
686
687 @Override
688 public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
Steve McKay4f4232d2015-07-22 12:13:46 -0700689 mMenu = menu;
690 updateActionMenu();
Jeff Sharkeyc317af82013-07-01 16:56:54 -0700691 return true;
692 }
693
Steve McKay4f4232d2015-07-22 12:13:46 -0700694 private void updateActionMenu() {
695 checkNotNull(mMenu);
696 // Delegate update logic to our owning action, since specialized logic is desired.
697 mFragmentTuner.updateActionMenu(mMenu, mType, mNoDeleteCount == 0);
698 }
699
Jeff Sharkeyc317af82013-07-01 16:56:54 -0700700 @Override
Steve McKayef280152015-06-11 10:10:49 -0700701 public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
Steve McKay1f199482015-05-20 15:58:42 -0700702
Ben Kwa24be5d32015-08-27 16:04:46 -0700703 Selection selection = mModel.getSelection(new Selection());
Jeff Sharkeyc317af82013-07-01 16:56:54 -0700704
Jeff Sharkey873daa32013-08-18 17:38:20 -0700705 final int id = item.getItemId();
706 if (id == R.id.menu_open) {
Steve McKayef280152015-06-11 10:10:49 -0700707 openDocuments(selection);
Jeff Sharkeyb3620442013-09-01 18:41:04 -0700708 mode.finish();
Jeff Sharkeyc317af82013-07-01 16:56:54 -0700709 return true;
Jeff Sharkey873daa32013-08-18 17:38:20 -0700710
711 } else if (id == R.id.menu_share) {
Steve McKayef280152015-06-11 10:10:49 -0700712 shareDocuments(selection);
Jeff Sharkeyb3620442013-09-01 18:41:04 -0700713 mode.finish();
Jeff Sharkey873daa32013-08-18 17:38:20 -0700714 return true;
715
716 } else if (id == R.id.menu_delete) {
Steve McKayef280152015-06-11 10:10:49 -0700717 deleteDocuments(selection);
Jeff Sharkeyb3620442013-09-01 18:41:04 -0700718 mode.finish();
Jeff Sharkey873daa32013-08-18 17:38:20 -0700719 return true;
720
Steve McKay1f199482015-05-20 15:58:42 -0700721 } else if (id == R.id.menu_copy_to) {
Steve McKayef280152015-06-11 10:10:49 -0700722 transferDocuments(selection, CopyService.TRANSFER_MODE_COPY);
Ben Kwacb4461f2015-05-05 11:50:11 -0700723 mode.finish();
724 return true;
725
Steve McKay1f199482015-05-20 15:58:42 -0700726 } else if (id == R.id.menu_move_to) {
Steve McKayef280152015-06-11 10:10:49 -0700727 transferDocuments(selection, CopyService.TRANSFER_MODE_MOVE);
Ben Kwa41b26c12015-03-31 10:11:43 -0700728 mode.finish();
729 return true;
730
Steve McKay1f199482015-05-20 15:58:42 -0700731 } else if (id == R.id.menu_copy_to_clipboard) {
Steve McKayef280152015-06-11 10:10:49 -0700732 copySelectionToClipboard(selection);
Steve McKay1f199482015-05-20 15:58:42 -0700733 mode.finish();
734 return true;
735
Ben Kwa512a6ba2015-03-31 08:15:21 -0700736 } else if (id == R.id.menu_select_all) {
Steve McKay0599a442015-05-05 14:50:00 -0700737 selectAllFiles();
Ben Kwa512a6ba2015-03-31 08:15:21 -0700738 return true;
739
Jeff Sharkeyc317af82013-07-01 16:56:54 -0700740 } else {
741 return false;
742 }
743 }
Steve McKayef280152015-06-11 10:10:49 -0700744 }
Jeff Sharkeyc317af82013-07-01 16:56:54 -0700745
Steve McKayef280152015-06-11 10:10:49 -0700746 private static void cancelThumbnailTask(View view) {
747 final ImageView iconThumb = (ImageView) view.findViewById(R.id.icon_thumb);
748 if (iconThumb != null) {
749 final ThumbnailAsyncTask oldTask = (ThumbnailAsyncTask) iconThumb.getTag();
750 if (oldTask != null) {
751 oldTask.preempt();
752 iconThumb.setTag(null);
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700753 }
754 }
Steve McKayef280152015-06-11 10:10:49 -0700755 }
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700756
Steve McKayef280152015-06-11 10:10:49 -0700757 private void openDocuments(final Selection selected) {
Steve McKay9276f3b2015-05-27 16:11:42 -0700758 new GetDocumentsTask() {
759 @Override
760 void onDocumentsReady(List<DocumentInfo> docs) {
Steve McKay0fbfc652015-08-20 16:48:49 -0700761 // TODO: Implement support in Files activity for opening multiple docs.
Steve McKay9276f3b2015-05-27 16:11:42 -0700762 BaseActivity.get(DirectoryFragment.this).onDocumentsPicked(docs);
Ben Kwaf527c632015-04-08 15:03:35 -0700763 }
Steve McKay9276f3b2015-05-27 16:11:42 -0700764 }.execute(selected);
Jeff Sharkey873daa32013-08-18 17:38:20 -0700765 }
766
Steve McKayef280152015-06-11 10:10:49 -0700767 private void shareDocuments(final Selection selected) {
Steve McKay9276f3b2015-05-27 16:11:42 -0700768 new GetDocumentsTask() {
769 @Override
770 void onDocumentsReady(List<DocumentInfo> docs) {
771 Intent intent;
772
773 // Filter out directories - those can't be shared.
Steve McKayfefcd702015-08-20 16:19:38 +0000774 List<DocumentInfo> docsForSend = new ArrayList<>();
Steve McKay9276f3b2015-05-27 16:11:42 -0700775 for (DocumentInfo doc: docs) {
776 if (!Document.MIME_TYPE_DIR.equals(doc.mimeType)) {
777 docsForSend.add(doc);
778 }
779 }
780
781 if (docsForSend.size() == 1) {
782 final DocumentInfo doc = docsForSend.get(0);
783
784 intent = new Intent(Intent.ACTION_SEND);
785 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
786 intent.addCategory(Intent.CATEGORY_DEFAULT);
787 intent.setType(doc.mimeType);
788 intent.putExtra(Intent.EXTRA_STREAM, doc.derivedUri);
789
790 } else if (docsForSend.size() > 1) {
791 intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
792 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
793 intent.addCategory(Intent.CATEGORY_DEFAULT);
794
Steve McKayfefcd702015-08-20 16:19:38 +0000795 final ArrayList<String> mimeTypes = new ArrayList<>();
796 final ArrayList<Uri> uris = new ArrayList<>();
Steve McKay9276f3b2015-05-27 16:11:42 -0700797 for (DocumentInfo doc : docsForSend) {
798 mimeTypes.add(doc.mimeType);
799 uris.add(doc.derivedUri);
800 }
801
802 intent.setType(findCommonMimeType(mimeTypes));
803 intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
804
805 } else {
806 return;
807 }
808
809 intent = Intent.createChooser(intent, getActivity().getText(R.string.share_via));
810 startActivity(intent);
811 }
812 }.execute(selected);
813 }
814
Steve McKayef280152015-06-11 10:10:49 -0700815 private void deleteDocuments(final Selection selected) {
Ben Kwa91923182015-08-27 16:06:33 -0700816 Context context = getActivity();
817 ContentResolver resolver = context.getContentResolver();
818 String message = Shared.getQuantityString(context, R.plurals.deleting, selected.size());
Jeff Sharkey873daa32013-08-18 17:38:20 -0700819
Ben Kwa91923182015-08-27 16:06:33 -0700820 mModel.markForDeletion(selected);
Jeff Sharkey873daa32013-08-18 17:38:20 -0700821
Ben Kwa91923182015-08-27 16:06:33 -0700822 Activity activity = getActivity();
823 Snackbar.make(this.getView(), message, Snackbar.LENGTH_LONG)
824 .setAction(
825 R.string.undo,
826 new android.view.View.OnClickListener() {
827 @Override
828 public void onClick(View view) {}
829 })
830 .setCallback(
831 new Snackbar.Callback() {
832 @Override
833 public void onDismissed(Snackbar snackbar, int event) {
834 if (event == Snackbar.Callback.DISMISS_EVENT_ACTION) {
835 mModel.undoDeletion();
836 } else {
Ben Kwa83cedf22015-09-11 15:15:45 -0700837 mModel.finalizeDeletion(
838 new Runnable() {
839 @Override
840 public void run() {
841 Snackbar.make(
842 DirectoryFragment.this.getView(),
843 R.string.toast_failed_delete,
844 Snackbar.LENGTH_LONG)
845 .show();
846
847 }
848 });
Ben Kwa91923182015-08-27 16:06:33 -0700849 }
Ben Kwa91923182015-08-27 16:06:33 -0700850 }
851 })
852 .show();
Jeff Sharkey873daa32013-08-18 17:38:20 -0700853 }
854
Steve McKayef280152015-06-11 10:10:49 -0700855 private void transferDocuments(final Selection selected, final int mode) {
Ben Kwaf5858932015-04-07 15:43:39 -0700856 // Pop up a dialog to pick a destination. This is inadequate but works for now.
857 // TODO: Implement a picker that is to spec.
Daichi Hironocaadd412015-04-10 15:50:38 +0900858 final Intent intent = new Intent(
Daichi Hirono22574ed2015-04-15 13:41:18 +0900859 BaseActivity.DocumentsIntent.ACTION_OPEN_COPY_DESTINATION,
Daichi Hironocaadd412015-04-10 15:50:38 +0900860 Uri.EMPTY,
861 getActivity(),
862 DocumentsActivity.class);
Steve McKay9276f3b2015-05-27 16:11:42 -0700863
864 new GetDocumentsTask() {
865 @Override
866 void onDocumentsReady(List<DocumentInfo> docs) {
867 getDisplayState(DirectoryFragment.this).selectedDocumentsForCopy = docs;
868
869 boolean directoryCopy = false;
870 for (DocumentInfo info : docs) {
871 if (Document.MIME_TYPE_DIR.equals(info.mimeType)) {
872 directoryCopy = true;
873 break;
874 }
875 }
876 intent.putExtra(BaseActivity.DocumentsIntent.EXTRA_DIRECTORY_COPY, directoryCopy);
877 intent.putExtra(CopyService.EXTRA_TRANSFER_MODE, mode);
878 startActivityForResult(intent, REQUEST_COPY_DESTINATION);
Daichi Hironof2a822d2015-04-14 17:12:54 +0900879 }
Steve McKay9276f3b2015-05-27 16:11:42 -0700880 }.execute(selected);
Ben Kwa41b26c12015-03-31 10:11:43 -0700881 }
882
Jeff Sharkeyb3620442013-09-01 18:41:04 -0700883 private static State getDisplayState(Fragment fragment) {
Steve McKayd0a2a2c2015-03-25 14:35:33 -0700884 return ((BaseActivity) fragment.getActivity()).getDisplayState();
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700885 }
886
Steve McKayef280152015-06-11 10:10:49 -0700887 // Provide a reference to the views for each data item
888 // Complex data items may need more than one view per item, and
889 // you provide access to all the views for a data item in a view holder
890 private static final class DocumentHolder extends RecyclerView.ViewHolder {
891 // each data item is just a string in this case
892 public View view;
893 public String docId; // The stable document id.
894 public DocumentHolder(View view) {
895 super(view);
896 this.view = view;
897 }
898 }
899
Ben Kwa379e1762015-09-21 10:49:52 -0700900 private final class DocumentsAdapter extends RecyclerView.Adapter<DocumentHolder> {
Steve McKayef280152015-06-11 10:10:49 -0700901
902 private final Context mContext;
903 private final LayoutInflater mInflater;
Steve McKayef280152015-06-11 10:10:49 -0700904
Steve McKayef280152015-06-11 10:10:49 -0700905 public DocumentsAdapter(Context context) {
906 mContext = context;
907 mInflater = LayoutInflater.from(context);
908 }
Jeff Sharkeyac9e6272013-08-31 21:27:44 -0700909
Ben Kwac42fa402015-09-16 08:04:37 -0700910 @Override
Steve McKayef280152015-06-11 10:10:49 -0700911 public DocumentHolder onCreateViewHolder(ViewGroup parent, int viewType) {
912 final State state = getDisplayState(DirectoryFragment.this);
913 final LayoutInflater inflater = LayoutInflater.from(getContext());
914 switch (state.derivedMode) {
915 case MODE_GRID:
916 return new DocumentHolder(inflater.inflate(R.layout.item_doc_grid, parent, false));
917 case MODE_LIST:
918 return new DocumentHolder(inflater.inflate(R.layout.item_doc_list, parent, false));
919 case MODE_UNKNOWN:
920 default:
921 throw new IllegalStateException("Unsupported layout mode.");
Jeff Sharkey20b32272013-09-03 15:25:52 -0700922 }
923 }
924
Steve McKayef280152015-06-11 10:10:49 -0700925 @Override
926 public void onBindViewHolder(DocumentHolder holder, int position) {
927
928 final Context context = getContext();
Jeff Sharkeyb3620442013-09-01 18:41:04 -0700929 final State state = getDisplayState(DirectoryFragment.this);
Jeff Sharkey9656a532013-09-13 13:42:19 -0700930 final DocumentInfo doc = getArguments().getParcelable(EXTRA_DOC);
Jeff Sharkey873daa32013-08-18 17:38:20 -0700931 final RootsCache roots = DocumentsApplication.getRootsCache(context);
932 final ThumbnailCache thumbs = DocumentsApplication.getThumbnailsCache(
933 context, mThumbSize);
934
Ben Kwa24be5d32015-08-27 16:04:46 -0700935 final Cursor cursor = mModel.getItem(position);
Steve McKayef280152015-06-11 10:10:49 -0700936 checkNotNull(cursor, "Cursor cannot be null.");
Jeff Sharkeyac9e6272013-08-31 21:27:44 -0700937
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700938 final String docAuthority = getCursorString(cursor, RootCursorWrapper.COLUMN_AUTHORITY);
939 final String docRootId = getCursorString(cursor, RootCursorWrapper.COLUMN_ROOT_ID);
Jeff Sharkeyac9e6272013-08-31 21:27:44 -0700940 final String docId = getCursorString(cursor, Document.COLUMN_DOCUMENT_ID);
941 final String docMimeType = getCursorString(cursor, Document.COLUMN_MIME_TYPE);
942 final String docDisplayName = getCursorString(cursor, Document.COLUMN_DISPLAY_NAME);
943 final long docLastModified = getCursorLong(cursor, Document.COLUMN_LAST_MODIFIED);
944 final int docIcon = getCursorInt(cursor, Document.COLUMN_ICON);
945 final int docFlags = getCursorInt(cursor, Document.COLUMN_FLAGS);
946 final String docSummary = getCursorString(cursor, Document.COLUMN_SUMMARY);
947 final long docSize = getCursorLong(cursor, Document.COLUMN_SIZE);
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700948
Steve McKayef280152015-06-11 10:10:49 -0700949 holder.docId = docId;
950 final View itemView = holder.view;
Ben Kwa24be5d32015-08-27 16:04:46 -0700951 itemView.setActivated(mModel.isSelected(position));
Jeff Sharkey9656a532013-09-13 13:42:19 -0700952
Steve McKayef280152015-06-11 10:10:49 -0700953 final View line1 = itemView.findViewById(R.id.line1);
954 final View line2 = itemView.findViewById(R.id.line2);
955
956 final ImageView iconMime = (ImageView) itemView.findViewById(R.id.icon_mime);
957 final ImageView iconThumb = (ImageView) itemView.findViewById(R.id.icon_thumb);
958 final TextView title = (TextView) itemView.findViewById(android.R.id.title);
959 final ImageView icon1 = (ImageView) itemView.findViewById(android.R.id.icon1);
960 final ImageView icon2 = (ImageView) itemView.findViewById(android.R.id.icon2);
961 final TextView summary = (TextView) itemView.findViewById(android.R.id.summary);
962 final TextView date = (TextView) itemView.findViewById(R.id.date);
963 final TextView size = (TextView) itemView.findViewById(R.id.size);
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700964
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700965 final ThumbnailAsyncTask oldTask = (ThumbnailAsyncTask) iconThumb.getTag();
Jeff Sharkey8a8fb672013-05-07 12:41:33 -0700966 if (oldTask != null) {
Jeff Sharkey753a3ae2013-10-22 17:09:44 -0700967 oldTask.preempt();
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700968 iconThumb.setTag(null);
Jeff Sharkey8a8fb672013-05-07 12:41:33 -0700969 }
970
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700971 iconMime.animate().cancel();
972 iconThumb.animate().cancel();
973
Jeff Sharkeyaed873d2013-09-09 16:51:06 -0700974 final boolean supportsThumbnail = (docFlags & Document.FLAG_SUPPORTS_THUMBNAIL) != 0;
Jeff Sharkeyd10f0492013-09-09 17:35:46 -0700975 final boolean allowThumbnail = (state.derivedMode == MODE_GRID)
Jeff Sharkey9656a532013-09-13 13:42:19 -0700976 || MimePredicate.mimeMatches(MimePredicate.VISUAL_MIMES, docMimeType);
Jeff Sharkeyf63b7772013-10-01 17:57:41 -0700977 final boolean showThumbnail = supportsThumbnail && allowThumbnail && !mSvelteRecents;
Jeff Sharkeyaed873d2013-09-09 16:51:06 -0700978
Jeff Sharkey7e544612014-08-29 15:38:27 -0700979 final boolean enabled = isDocumentEnabled(docMimeType, docFlags);
980 final float iconAlpha = (state.derivedMode == MODE_LIST && !enabled) ? 0.5f : 1f;
981
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700982 boolean cacheHit = false;
Jeff Sharkey9656a532013-09-13 13:42:19 -0700983 if (showThumbnail) {
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700984 final Uri uri = DocumentsContract.buildDocumentUri(docAuthority, docId);
Jeff Sharkeyac9e6272013-08-31 21:27:44 -0700985 final Bitmap cachedResult = thumbs.get(uri);
Jeff Sharkey8a8fb672013-05-07 12:41:33 -0700986 if (cachedResult != null) {
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700987 iconThumb.setImageBitmap(cachedResult);
988 cacheHit = true;
Jeff Sharkey8a8fb672013-05-07 12:41:33 -0700989 } else {
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700990 iconThumb.setImageDrawable(null);
Steve McKayef280152015-06-11 10:10:49 -0700991 // TODO: Hang this off DocumentHolder?
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700992 final ThumbnailAsyncTask task = new ThumbnailAsyncTask(
Jeff Sharkey7e544612014-08-29 15:38:27 -0700993 uri, iconMime, iconThumb, mThumbSize, iconAlpha);
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700994 iconThumb.setTag(task);
Jeff Sharkey753a3ae2013-10-22 17:09:44 -0700995 ProviderExecutor.forAuthority(docAuthority).execute(task);
Jeff Sharkey8a8fb672013-05-07 12:41:33 -0700996 }
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700997 }
998
999 // Always throw MIME icon into place, even when a thumbnail is being
1000 // loaded in background.
1001 if (cacheHit) {
1002 iconMime.setAlpha(0f);
Jeff Sharkey9dd02622013-09-27 16:44:11 -07001003 iconMime.setImageDrawable(null);
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -07001004 iconThumb.setAlpha(1f);
Jeff Sharkeye22d02e2013-04-26 16:54:55 -07001005 } else {
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -07001006 iconMime.setAlpha(1f);
1007 iconThumb.setAlpha(0f);
Jeff Sharkey9dd02622013-09-27 16:44:11 -07001008 iconThumb.setImageDrawable(null);
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001009 iconMime.setImageDrawable(
Steve McKayef280152015-06-11 10:10:49 -07001010 getDocumentIcon(mContext, docAuthority, docId, docMimeType, docIcon, state));
Jeff Sharkeye22d02e2013-04-26 16:54:55 -07001011 }
1012
Jeff Sharkey9656a532013-09-13 13:42:19 -07001013 boolean hasLine1 = false;
Jeff Sharkey42d26792013-09-06 13:22:09 -07001014 boolean hasLine2 = false;
1015
Jeff Sharkey9656a532013-09-13 13:42:19 -07001016 final boolean hideTitle = (state.derivedMode == MODE_GRID) && mHideGridTitles;
1017 if (!hideTitle) {
1018 title.setText(docDisplayName);
1019 hasLine1 = true;
1020 }
1021
1022 Drawable iconDrawable = null;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -07001023 if (mType == TYPE_RECENT_OPEN) {
Jeff Sharkey8b997042013-09-19 15:25:56 -07001024 // We've already had to enumerate roots before any results can
1025 // be shown, so this will never block.
1026 final RootInfo root = roots.getRootBlocking(docAuthority, docRootId);
Jeff Sharkey93cdbc22014-07-29 17:33:36 -07001027 if (state.derivedMode == MODE_GRID) {
Steve McKayef280152015-06-11 10:10:49 -07001028 iconDrawable = root.loadGridIcon(mContext);
Jeff Sharkey93cdbc22014-07-29 17:33:36 -07001029 } else {
Steve McKayef280152015-06-11 10:10:49 -07001030 iconDrawable = root.loadIcon(mContext);
Jeff Sharkey93cdbc22014-07-29 17:33:36 -07001031 }
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -07001032
Jeff Sharkey7d58fc62013-09-12 16:25:02 -07001033 if (summary != null) {
1034 final boolean alwaysShowSummary = getResources()
1035 .getBoolean(R.bool.always_show_summary);
1036 if (alwaysShowSummary) {
1037 summary.setText(root.getDirectoryString());
1038 summary.setVisibility(View.VISIBLE);
1039 hasLine2 = true;
1040 } else {
Jeff Sharkey8b997042013-09-19 15:25:56 -07001041 if (iconDrawable != null && roots.isIconUniqueBlocking(root)) {
Jeff Sharkey7d58fc62013-09-12 16:25:02 -07001042 // No summary needed if icon speaks for itself
1043 summary.setVisibility(View.INVISIBLE);
1044 } else {
1045 summary.setText(root.getDirectoryString());
1046 summary.setVisibility(View.VISIBLE);
1047 summary.setTextAlignment(TextView.TEXT_ALIGNMENT_TEXT_END);
1048 hasLine2 = true;
1049 }
1050 }
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -07001051 }
Jeff Sharkeyac9e6272013-08-31 21:27:44 -07001052 } else {
Jeff Sharkey9656a532013-09-13 13:42:19 -07001053 // Directories showing thumbnails in grid mode get a little icon
1054 // hint to remind user they're a directory.
1055 if (Document.MIME_TYPE_DIR.equals(docMimeType) && state.derivedMode == MODE_GRID
1056 && showThumbnail) {
Steve McKayef280152015-06-11 10:10:49 -07001057 iconDrawable = IconUtils.applyTintAttr(mContext, R.drawable.ic_doc_folder,
Jeff Sharkey34c54092014-08-08 13:08:56 -07001058 android.R.attr.textColorPrimaryInverse);
Jeff Sharkey9656a532013-09-13 13:42:19 -07001059 }
1060
Jeff Sharkey7d58fc62013-09-12 16:25:02 -07001061 if (summary != null) {
1062 if (docSummary != null) {
1063 summary.setText(docSummary);
1064 summary.setVisibility(View.VISIBLE);
1065 hasLine2 = true;
1066 } else {
1067 summary.setVisibility(View.INVISIBLE);
1068 }
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -07001069 }
Jeff Sharkey2e694f82013-08-06 16:26:14 -07001070 }
1071
Jeff Sharkey9656a532013-09-13 13:42:19 -07001072 if (icon1 != null) icon1.setVisibility(View.GONE);
1073 if (icon2 != null) icon2.setVisibility(View.GONE);
1074
1075 if (iconDrawable != null) {
1076 if (hasLine1) {
1077 icon1.setVisibility(View.VISIBLE);
1078 icon1.setImageDrawable(iconDrawable);
1079 } else {
1080 icon2.setVisibility(View.VISIBLE);
1081 icon2.setImageDrawable(iconDrawable);
1082 }
1083 }
1084
Jeff Sharkeyac9e6272013-08-31 21:27:44 -07001085 if (docLastModified == -1) {
Jeff Sharkey8a8fb672013-05-07 12:41:33 -07001086 date.setText(null);
1087 } else {
Steve McKayef280152015-06-11 10:10:49 -07001088 date.setText(formatTime(mContext, docLastModified));
Jeff Sharkey42d26792013-09-06 13:22:09 -07001089 hasLine2 = true;
Jeff Sharkey8a8fb672013-05-07 12:41:33 -07001090 }
Jeff Sharkey2e694f82013-08-06 16:26:14 -07001091
1092 if (state.showSize) {
1093 size.setVisibility(View.VISIBLE);
Jeff Sharkeyac9e6272013-08-31 21:27:44 -07001094 if (Document.MIME_TYPE_DIR.equals(docMimeType) || docSize == -1) {
Jeff Sharkey2e694f82013-08-06 16:26:14 -07001095 size.setText(null);
1096 } else {
Steve McKayef280152015-06-11 10:10:49 -07001097 size.setText(Formatter.formatFileSize(mContext, docSize));
Jeff Sharkey42d26792013-09-06 13:22:09 -07001098 hasLine2 = true;
Jeff Sharkey2e694f82013-08-06 16:26:14 -07001099 }
1100 } else {
1101 size.setVisibility(View.GONE);
Jeff Sharkey09c10bf2013-06-30 20:02:59 -07001102 }
Jeff Sharkeya5defe32013-08-05 17:56:48 -07001103
Jeff Sharkey9656a532013-09-13 13:42:19 -07001104 if (line1 != null) {
1105 line1.setVisibility(hasLine1 ? View.VISIBLE : View.GONE);
1106 }
Jeff Sharkey7d58fc62013-09-12 16:25:02 -07001107 if (line2 != null) {
1108 line2.setVisibility(hasLine2 ? View.VISIBLE : View.GONE);
1109 }
Jeff Sharkey42d26792013-09-06 13:22:09 -07001110
Steve McKayef280152015-06-11 10:10:49 -07001111 setEnabledRecursive(itemView, enabled);
Jeff Sharkey7e544612014-08-29 15:38:27 -07001112
1113 iconMime.setAlpha(iconAlpha);
1114 iconThumb.setAlpha(iconAlpha);
1115 if (icon1 != null) icon1.setAlpha(iconAlpha);
1116 if (icon2 != null) icon2.setAlpha(iconAlpha);
Jeff Sharkeyaed873d2013-09-09 16:51:06 -07001117
Steve McKay8e258c62015-05-06 14:27:57 -07001118 if (DEBUG_ENABLE_DND) {
Steve McKayef280152015-06-11 10:10:49 -07001119 setupDragAndDropOnDocumentView(itemView, cursor);
Steve McKay8e258c62015-05-06 14:27:57 -07001120 }
Jeff Sharkeye22d02e2013-04-26 16:54:55 -07001121 }
Jeff Sharkey09c10bf2013-06-30 20:02:59 -07001122
Steve McKay351a7492015-08-04 10:11:01 -07001123 @Override
Steve McKayef280152015-06-11 10:10:49 -07001124 public int getItemCount() {
Ben Kwa24be5d32015-08-27 16:04:46 -07001125 return mModel.getItemCount();
Jeff Sharkeyaed873d2013-09-09 16:51:06 -07001126 }
1127
Jeff Sharkey8a8fb672013-05-07 12:41:33 -07001128 }
1129
1130 private static String formatTime(Context context, long when) {
1131 // TODO: DateUtils should make this easier
1132 Time then = new Time();
1133 then.set(when);
1134 Time now = new Time();
1135 now.setToNow();
1136
1137 int flags = DateUtils.FORMAT_NO_NOON | DateUtils.FORMAT_NO_MIDNIGHT
1138 | DateUtils.FORMAT_ABBREV_ALL;
1139
1140 if (then.year != now.year) {
1141 flags |= DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_DATE;
1142 } else if (then.yearDay != now.yearDay) {
1143 flags |= DateUtils.FORMAT_SHOW_DATE;
1144 } else {
1145 flags |= DateUtils.FORMAT_SHOW_TIME;
1146 }
1147
1148 return DateUtils.formatDateTime(context, when, flags);
1149 }
Jeff Sharkeyb3620442013-09-01 18:41:04 -07001150
1151 private String findCommonMimeType(List<String> mimeTypes) {
1152 String[] commonType = mimeTypes.get(0).split("/");
1153 if (commonType.length != 2) {
1154 return "*/*";
1155 }
1156
1157 for (int i = 1; i < mimeTypes.size(); i++) {
1158 String[] type = mimeTypes.get(i).split("/");
1159 if (type.length != 2) continue;
1160
1161 if (!commonType[1].equals(type[1])) {
1162 commonType[1] = "*";
1163 }
1164
1165 if (!commonType[0].equals(type[0])) {
1166 commonType[0] = "*";
1167 commonType[1] = "*";
1168 break;
1169 }
1170 }
1171
1172 return commonType[0] + "/" + commonType[1];
1173 }
Jeff Sharkeyaed873d2013-09-09 16:51:06 -07001174
1175 private void setEnabledRecursive(View v, boolean enabled) {
Jeff Sharkey9656a532013-09-13 13:42:19 -07001176 if (v == null) return;
Jeff Sharkeyaed873d2013-09-09 16:51:06 -07001177 if (v.isEnabled() == enabled) return;
1178 v.setEnabled(enabled);
1179
1180 if (v instanceof ViewGroup) {
1181 final ViewGroup vg = (ViewGroup) v;
1182 for (int i = vg.getChildCount() - 1; i >= 0; i--) {
1183 setEnabledRecursive(vg.getChildAt(i), enabled);
1184 }
1185 }
1186 }
Jeff Sharkey7cf49032013-09-26 10:54:16 -07001187
1188 private boolean isDocumentEnabled(String docMimeType, int docFlags) {
1189 final State state = getDisplayState(DirectoryFragment.this);
1190
Jeff Sharkey7cf49032013-09-26 10:54:16 -07001191 // Directories are always enabled
1192 if (Document.MIME_TYPE_DIR.equals(docMimeType)) {
1193 return true;
1194 }
1195
Jeff Sharkey783ebc22013-09-26 19:42:52 -07001196 // Read-only files are disabled when creating
1197 if (state.action == ACTION_CREATE && (docFlags & Document.FLAG_SUPPORTS_WRITE) == 0) {
1198 return false;
1199 }
1200
Jeff Sharkey7cf49032013-09-26 10:54:16 -07001201 return MimePredicate.mimeMatches(state.acceptMimes, docMimeType);
1202 }
Vladislav Kaznacheev89b90332015-05-01 13:46:57 -07001203
Steve McKay1f199482015-05-20 15:58:42 -07001204 private void copyFromClipboard() {
1205 new AsyncTask<Void, Void, List<DocumentInfo>>() {
1206
1207 @Override
1208 protected List<DocumentInfo> doInBackground(Void... params) {
1209 return mClipper.getClippedDocuments();
1210 }
1211
1212 @Override
1213 protected void onPostExecute(List<DocumentInfo> docs) {
1214 DocumentInfo destination =
1215 ((BaseActivity) getActivity()).getCurrentDirectory();
1216 copyDocuments(docs, destination);
1217 }
1218 }.execute();
Steve McKay0599a442015-05-05 14:50:00 -07001219 }
1220
Steve McKay1f199482015-05-20 15:58:42 -07001221 private void copyFromClipData(final ClipData clipData, final DocumentInfo destination) {
Steve McKayef280152015-06-11 10:10:49 -07001222 checkNotNull(clipData);
Steve McKay1f199482015-05-20 15:58:42 -07001223 new AsyncTask<Void, Void, List<DocumentInfo>>() {
Vladislav Kaznacheev89b90332015-05-01 13:46:57 -07001224
Steve McKay1f199482015-05-20 15:58:42 -07001225 @Override
1226 protected List<DocumentInfo> doInBackground(Void... params) {
1227 return mClipper.getDocumentsFromClipData(clipData);
1228 }
1229
1230 @Override
1231 protected void onPostExecute(List<DocumentInfo> docs) {
1232 copyDocuments(docs, destination);
1233 }
1234 }.execute();
1235 }
1236
1237 private void copyDocuments(final List<DocumentInfo> docs, final DocumentInfo destination) {
1238 if (!canCopy(docs, destination)) {
1239 Toast.makeText(
1240 getActivity(),
1241 R.string.clipboard_files_cannot_paste, Toast.LENGTH_SHORT).show();
Steve McKay0599a442015-05-05 14:50:00 -07001242 return;
1243 }
1244
Steve McKay1f199482015-05-20 15:58:42 -07001245 if (docs.isEmpty()) {
Vladislav Kaznacheev89b90332015-05-01 13:46:57 -07001246 return;
Vladislav Kaznacheeve16887a2015-05-05 12:09:47 -07001247 }
Vladislav Kaznacheev89b90332015-05-01 13:46:57 -07001248
Steve McKay1f199482015-05-20 15:58:42 -07001249 final DocumentStack curStack = getDisplayState(DirectoryFragment.this).stack;
Vladislav Kaznacheev89b90332015-05-01 13:46:57 -07001250 DocumentStack tmpStack = new DocumentStack();
Steve McKay1f199482015-05-20 15:58:42 -07001251 if (destination != null) {
1252 tmpStack.push(destination);
Vladislav Kaznacheev89b90332015-05-01 13:46:57 -07001253 tmpStack.addAll(curStack);
1254 } else {
1255 tmpStack = curStack;
1256 }
1257
Steve McKay1f199482015-05-20 15:58:42 -07001258 CopyService.start(getActivity(), docs, tmpStack, CopyService.TRANSFER_MODE_COPY);
Vladislav Kaznacheev89b90332015-05-01 13:46:57 -07001259 }
1260
1261 private ClipData getClipDataFromDocuments(List<DocumentInfo> docs) {
1262 Context context = getActivity();
1263 final ContentResolver resolver = context.getContentResolver();
1264 ClipData clipData = null;
1265 for (DocumentInfo doc : docs) {
1266 final Uri uri = DocumentsContract.buildDocumentUri(doc.authority, doc.documentId);
1267 if (clipData == null) {
Vladislav Kaznacheeve16887a2015-05-05 12:09:47 -07001268 // TODO: figure out what this string should be.
1269 // Currently it is not displayed anywhere in the UI, but this might change.
1270 final String label = "";
1271 clipData = ClipData.newUri(resolver, label, uri);
Vladislav Kaznacheev89b90332015-05-01 13:46:57 -07001272 } else {
1273 // TODO: update list of mime types in ClipData.
1274 clipData.addItem(new ClipData.Item(uri));
1275 }
1276 }
1277 return clipData;
1278 }
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001279
Steve McKay1f199482015-05-20 15:58:42 -07001280 void copySelectedToClipboard() {
Ben Kwa24be5d32015-08-27 16:04:46 -07001281 Selection sel = mModel.getSelection(new Selection());
Steve McKayef280152015-06-11 10:10:49 -07001282 copySelectionToClipboard(sel);
Steve McKay9276f3b2015-05-27 16:11:42 -07001283 }
Steve McKay0599a442015-05-05 14:50:00 -07001284
Steve McKayef280152015-06-11 10:10:49 -07001285 void copySelectionToClipboard(Selection items) {
Steve McKay9276f3b2015-05-27 16:11:42 -07001286 new GetDocumentsTask() {
1287 @Override
1288 void onDocumentsReady(List<DocumentInfo> docs) {
1289 mClipper.clipDocuments(docs);
Steve McKay1f199482015-05-20 15:58:42 -07001290 Activity activity = getActivity();
1291 Toast.makeText(activity,
1292 activity.getResources().getQuantityString(
1293 R.plurals.clipboard_files_clipped, docs.size(), docs.size()),
1294 Toast.LENGTH_SHORT).show();
Steve McKay9276f3b2015-05-27 16:11:42 -07001295 }
Steve McKayef280152015-06-11 10:10:49 -07001296 }.execute(items);
Steve McKay0599a442015-05-05 14:50:00 -07001297 }
1298
1299 void pasteFromClipboard() {
Steve McKay1f199482015-05-20 15:58:42 -07001300 copyFromClipboard();
1301 getActivity().invalidateOptionsMenu();
Steve McKay0599a442015-05-05 14:50:00 -07001302 }
1303
Steve McKay0599a442015-05-05 14:50:00 -07001304 /**
1305 * Returns true if the list of files can be copied to destination. Note that this
1306 * is a policy check only. Currently the method does not attempt to verify
1307 * available space or any other environmental aspects possibly resulting in
1308 * failure to copy.
1309 *
1310 * @return true if the list of files can be copied to destination.
1311 */
1312 boolean canCopy(List<DocumentInfo> files, DocumentInfo dest) {
Ben Kwa91923182015-08-27 16:06:33 -07001313 BaseActivity activity = (BaseActivity) getActivity();
Steve McKay0599a442015-05-05 14:50:00 -07001314
1315 final RootInfo root = activity.getCurrentRoot();
1316
1317 // Can't copy folders to Downloads.
1318 if (root.isDownloads()) {
1319 for (DocumentInfo docs : files) {
1320 if (docs.isDirectory()) {
1321 return false;
1322 }
1323 }
1324 }
1325
1326 return dest != null && dest.isDirectory() && dest.isCreateSupported();
1327 }
1328
1329 void selectAllFiles() {
Ben Kwa24be5d32015-08-27 16:04:46 -07001330 boolean changed = mModel.selectAll();
Steve McKay9459a7c2015-07-24 13:14:20 -07001331 if (changed) {
1332 updateDisplayState();
1333 }
Steve McKay0599a442015-05-05 14:50:00 -07001334 }
1335
Steve McKayef280152015-06-11 10:10:49 -07001336 private void setupDragAndDropOnDirectoryView(View view) {
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001337 // Listen for drops on non-directory items and empty space.
1338 view.setOnDragListener(mOnDragListener);
1339 }
1340
1341 private void setupDragAndDropOnDocumentView(View view, Cursor cursor) {
1342 final String docMimeType = getCursorString(cursor, Document.COLUMN_MIME_TYPE);
1343 if (Document.MIME_TYPE_DIR.equals(docMimeType)) {
1344 // Make a directory item a drop target. Drop on non-directories and empty space
1345 // is handled at the list/grid view level.
1346 view.setOnDragListener(mOnDragListener);
1347 }
1348
1349 // Temporary: attaching the listener to the title only.
1350 // Attaching to the entire item conflicts with the item long click handler responsible
1351 // for item selection.
1352 final View title = view.findViewById(android.R.id.title);
1353 title.setOnLongClickListener(mLongClickListener);
1354 }
1355
1356 private View.OnDragListener mOnDragListener = new View.OnDragListener() {
1357 @Override
1358 public boolean onDrag(View v, DragEvent event) {
1359 switch (event.getAction()) {
1360 case DragEvent.ACTION_DRAG_STARTED:
1361 // TODO: Check if the event contains droppable data.
1362 return true;
1363
1364 // TODO: Highlight potential drop target directory?
1365 // TODO: Expand drop target directory on hover?
1366 case DragEvent.ACTION_DRAG_ENTERED:
1367 case DragEvent.ACTION_DRAG_LOCATION:
1368 case DragEvent.ACTION_DRAG_EXITED:
1369 case DragEvent.ACTION_DRAG_ENDED:
1370 return true;
1371
1372 case DragEvent.ACTION_DROP:
Vladislav Kaznacheev9400b892015-09-04 09:17:37 -07001373 int dstPosition = mRecView.getChildAdapterPosition(getContainingItemView(v));
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001374 DocumentInfo dstDir = null;
1375 if (dstPosition != android.widget.AdapterView.INVALID_POSITION) {
Ben Kwa24be5d32015-08-27 16:04:46 -07001376 Cursor dstCursor = mModel.getItem(dstPosition);
Steve McKayef280152015-06-11 10:10:49 -07001377 checkNotNull(dstCursor, "Cursor cannot be null.");
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001378 dstDir = DocumentInfo.fromDirectoryCursor(dstCursor);
1379 // TODO: Do not drop into the directory where the documents came from.
1380 }
1381 copyFromClipData(event.getClipData(), dstDir);
1382 return true;
1383 }
1384 return false;
1385 }
1386 };
1387
Vladislav Kaznacheev9400b892015-09-04 09:17:37 -07001388 private View getContainingItemView(View view) {
1389 while (true) {
1390 if (view.getLayoutParams() instanceof RecyclerView.LayoutParams) {
1391 return view;
1392 }
1393 ViewParent parent = view.getParent();
1394 if (parent == null || !(parent instanceof View)) {
1395 return null;
1396 }
1397 view = (View) parent;
1398 }
1399 }
1400
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001401 private View.OnLongClickListener mLongClickListener = new View.OnLongClickListener() {
1402 @Override
1403 public boolean onLongClick(View v) {
1404 final List<DocumentInfo> docs = getDraggableDocuments(v);
1405 if (docs.isEmpty()) {
1406 return false;
1407 }
1408 v.startDrag(
1409 getClipDataFromDocuments(docs),
1410 new DrawableShadowBuilder(getDragShadowIcon(docs)),
1411 null,
Vladislav Kaznacheeve3ce8a92015-07-15 18:04:04 -07001412 View.DRAG_FLAG_GLOBAL | View.DRAG_FLAG_GLOBAL_URI_READ |
1413 View.DRAG_FLAG_GLOBAL_URI_WRITE
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001414 );
1415 return true;
1416 }
1417 };
1418
1419 private List<DocumentInfo> getDraggableDocuments(View currentItemView) {
Vladislav Kaznacheev9400b892015-09-04 09:17:37 -07001420 int position = mRecView.getChildAdapterPosition(getContainingItemView(currentItemView));
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001421 if (position == android.widget.AdapterView.INVALID_POSITION) {
1422 return Collections.EMPTY_LIST;
1423 }
1424
Ben Kwa24be5d32015-08-27 16:04:46 -07001425 final List<DocumentInfo> selectedDocs = mModel.getSelectedDocuments();
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001426 if (!selectedDocs.isEmpty()) {
Ben Kwa24be5d32015-08-27 16:04:46 -07001427 if (!mModel.isSelected(position)) {
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001428 // There is a selection that does not include the current item, drag nothing.
1429 return Collections.EMPTY_LIST;
1430 }
1431 return selectedDocs;
1432 }
1433
Ben Kwa24be5d32015-08-27 16:04:46 -07001434 final Cursor cursor = mModel.getItem(position);
Steve McKayef280152015-06-11 10:10:49 -07001435 checkNotNull(cursor, "Cursor cannot be null.");
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001436 final DocumentInfo doc = DocumentInfo.fromDirectoryCursor(cursor);
Steve McKayfefcd702015-08-20 16:19:38 +00001437
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001438 return Lists.newArrayList(doc);
1439 }
1440
1441 private Drawable getDragShadowIcon(List<DocumentInfo> docs) {
1442 if (docs.size() == 1) {
1443 final DocumentInfo doc = docs.get(0);
1444 return getDocumentIcon(getActivity(), doc.authority, doc.documentId,
1445 doc.mimeType, doc.icon, getDisplayState(this));
1446 }
1447 return getActivity().getDrawable(R.drawable.ic_doc_generic);
1448 }
1449
1450 public static Drawable getDocumentIcon(Context context, String docAuthority, String docId,
1451 String docMimeType, int docIcon, State state) {
1452 if (docIcon != 0) {
1453 return IconUtils.loadPackageIcon(context, docAuthority, docIcon);
1454 } else {
1455 return IconUtils.loadMimeIcon(context, docMimeType, docAuthority, docId,
1456 state.derivedMode);
1457 }
1458 }
1459
Steve McKayef280152015-06-11 10:10:49 -07001460 private static class ThumbnailAsyncTask extends AsyncTask<Uri, Void, Bitmap>
1461 implements Preemptable {
1462 private final Uri mUri;
1463 private final ImageView mIconMime;
1464 private final ImageView mIconThumb;
1465 private final Point mThumbSize;
1466 private final float mTargetAlpha;
1467 private final CancellationSignal mSignal;
1468
1469 public ThumbnailAsyncTask(Uri uri, ImageView iconMime, ImageView iconThumb, Point thumbSize,
1470 float targetAlpha) {
1471 mUri = uri;
1472 mIconMime = iconMime;
1473 mIconThumb = iconThumb;
1474 mThumbSize = thumbSize;
1475 mTargetAlpha = targetAlpha;
1476 mSignal = new CancellationSignal();
1477 }
1478
1479 @Override
1480 public void preempt() {
1481 cancel(false);
1482 mSignal.cancel();
1483 }
1484
1485 @Override
1486 protected Bitmap doInBackground(Uri... params) {
1487 if (isCancelled()) return null;
1488
1489 final Context context = mIconThumb.getContext();
1490 final ContentResolver resolver = context.getContentResolver();
1491
1492 ContentProviderClient client = null;
1493 Bitmap result = null;
1494 try {
1495 client = DocumentsApplication.acquireUnstableProviderOrThrow(
1496 resolver, mUri.getAuthority());
1497 result = DocumentsContract.getDocumentThumbnail(client, mUri, mThumbSize, mSignal);
1498 if (result != null) {
1499 final ThumbnailCache thumbs = DocumentsApplication.getThumbnailsCache(
1500 context, mThumbSize);
1501 thumbs.put(mUri, result);
1502 }
1503 } catch (Exception e) {
1504 if (!(e instanceof OperationCanceledException)) {
1505 Log.w(TAG, "Failed to load thumbnail for " + mUri + ": " + e);
1506 }
1507 } finally {
1508 ContentProviderClient.releaseQuietly(client);
1509 }
1510 return result;
1511 }
1512
1513 @Override
1514 protected void onPostExecute(Bitmap result) {
1515 if (mIconThumb.getTag() == this && result != null) {
1516 mIconThumb.setTag(null);
1517 mIconThumb.setImageBitmap(result);
1518
1519 mIconMime.setAlpha(mTargetAlpha);
1520 mIconMime.animate().alpha(0f).start();
1521 mIconThumb.setAlpha(0f);
1522 mIconThumb.animate().alpha(mTargetAlpha).start();
1523 }
1524 }
1525 }
1526
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001527 private class DrawableShadowBuilder extends View.DragShadowBuilder {
1528
1529 private final Drawable mShadow;
1530
1531 private final int mShadowDimension;
1532
1533 public DrawableShadowBuilder(Drawable shadow) {
1534 mShadow = shadow;
1535 mShadowDimension = getResources().getDimensionPixelSize(
1536 R.dimen.drag_shadow_size);
1537 mShadow.setBounds(0, 0, mShadowDimension, mShadowDimension);
1538 }
1539
Ben Kwa24be5d32015-08-27 16:04:46 -07001540 @Override
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001541 public void onProvideShadowMetrics(
1542 Point shadowSize, Point shadowTouchPoint) {
1543 shadowSize.set(mShadowDimension, mShadowDimension);
1544 shadowTouchPoint.set(mShadowDimension / 2, mShadowDimension / 2);
1545 }
1546
Ben Kwa24be5d32015-08-27 16:04:46 -07001547 @Override
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001548 public void onDrawShadow(Canvas canvas) {
1549 mShadow.draw(canvas);
1550 }
1551 }
Steve McKay1f199482015-05-20 15:58:42 -07001552
1553 private FragmentTuner pickFragmentTuner(final State state) {
Steve McKay459bc2b2015-09-16 15:07:31 -07001554 return state.action == ACTION_BROWSE
Steve McKay0fbfc652015-08-20 16:48:49 -07001555 ? new FilesTuner()
Steve McKay459bc2b2015-09-16 15:07:31 -07001556 : new DefaultTuner(state.action);
Steve McKay1f199482015-05-20 15:58:42 -07001557 }
1558
1559 /**
1560 * Interface for specializing the Fragment for the "host" Activity.
1561 * Feel free to expand the role of this class to handle other specializations.
1562 */
1563 private interface FragmentTuner {
Steve McKay4f4232d2015-07-22 12:13:46 -07001564 void updateActionMenu(Menu menu, int dirType, boolean canDelete);
Kyle Horimoto426bd0d2015-07-29 15:33:49 -07001565 void afterActivityCreated(DirectoryFragment fragment);
Steve McKay1f199482015-05-20 15:58:42 -07001566 }
1567
1568 /**
Steve McKay9276f3b2015-05-27 16:11:42 -07001569 * Abstract task providing support for loading documents *off*
1570 * the main thread. And if it isn't obvious, creating a list
1571 * of documents (especially large lists) can be pretty expensive.
1572 */
1573 private abstract class GetDocumentsTask
Steve McKayef280152015-06-11 10:10:49 -07001574 extends AsyncTask<Selection, Void, List<DocumentInfo>> {
Steve McKay9276f3b2015-05-27 16:11:42 -07001575 @Override
Steve McKayef280152015-06-11 10:10:49 -07001576 protected final List<DocumentInfo> doInBackground(Selection... selected) {
Ben Kwa24be5d32015-08-27 16:04:46 -07001577 return mModel.getDocuments(selected[0]);
Steve McKay9276f3b2015-05-27 16:11:42 -07001578 }
1579
1580 @Override
1581 protected final void onPostExecute(List<DocumentInfo> docs) {
1582 onDocumentsReady(docs);
1583 }
1584
1585 abstract void onDocumentsReady(List<DocumentInfo> docs);
1586 }
1587
1588 /**
Steve McKay1f199482015-05-20 15:58:42 -07001589 * Provides support for Platform specific specializations of DirectoryFragment.
1590 */
1591 private static final class DefaultTuner implements FragmentTuner {
1592
Steve McKay459bc2b2015-09-16 15:07:31 -07001593 private final boolean mManaging;
Steve McKay1f199482015-05-20 15:58:42 -07001594
Steve McKay459bc2b2015-09-16 15:07:31 -07001595 public DefaultTuner(int action) {
1596 mManaging = (action == ACTION_MANAGE);
Steve McKay1f199482015-05-20 15:58:42 -07001597 }
1598
1599 @Override
Steve McKay4f4232d2015-07-22 12:13:46 -07001600 public void updateActionMenu(Menu menu, int dirType, boolean canDelete) {
Steve McKay1f199482015-05-20 15:58:42 -07001601
1602 final MenuItem open = menu.findItem(R.id.menu_open);
1603 final MenuItem share = menu.findItem(R.id.menu_share);
1604 final MenuItem delete = menu.findItem(R.id.menu_delete);
1605 final MenuItem copyTo = menu.findItem(R.id.menu_copy_to);
1606 final MenuItem moveTo = menu.findItem(R.id.menu_move_to);
1607 final MenuItem copyToClipboard = menu.findItem(R.id.menu_copy_to_clipboard);
1608
Steve McKay459bc2b2015-09-16 15:07:31 -07001609 open.setVisible(!mManaging);
1610 share.setVisible(mManaging);
1611 delete.setVisible(mManaging && canDelete);
Steve McKay1f199482015-05-20 15:58:42 -07001612 // Disable copying from the Recents view.
Steve McKay459bc2b2015-09-16 15:07:31 -07001613 copyTo.setVisible(mManaging && dirType != TYPE_RECENT_OPEN);
Steve McKay1f199482015-05-20 15:58:42 -07001614 moveTo.setVisible(SystemProperties.getBoolean("debug.documentsui.enable_move", false));
1615
Steve McKay0fbfc652015-08-20 16:48:49 -07001616 // Only shown in files mode.
Steve McKay1f199482015-05-20 15:58:42 -07001617 copyToClipboard.setVisible(false);
1618 }
Kyle Horimoto426bd0d2015-07-29 15:33:49 -07001619
1620 @Override
1621 public void afterActivityCreated(DirectoryFragment fragment) {}
Steve McKay1f199482015-05-20 15:58:42 -07001622 }
1623
1624 /**
Steve McKay0fbfc652015-08-20 16:48:49 -07001625 * Provides support for Files activity specific specializations of DirectoryFragment.
Steve McKay1f199482015-05-20 15:58:42 -07001626 */
Steve McKay0fbfc652015-08-20 16:48:49 -07001627 private static final class FilesTuner implements FragmentTuner {
Steve McKay1f199482015-05-20 15:58:42 -07001628 @Override
Steve McKay4f4232d2015-07-22 12:13:46 -07001629 public void updateActionMenu(Menu menu, int dirType, boolean canDelete) {
Steve McKay459bc2b2015-09-16 15:07:31 -07001630
Steve McKay1f199482015-05-20 15:58:42 -07001631 menu.findItem(R.id.menu_share).setVisible(true);
Steve McKay4f4232d2015-07-22 12:13:46 -07001632 menu.findItem(R.id.menu_delete).setVisible(canDelete);
Steve McKay1f199482015-05-20 15:58:42 -07001633 menu.findItem(R.id.menu_copy_to_clipboard).setVisible(true);
1634
1635 menu.findItem(R.id.menu_open).setVisible(false);
1636 menu.findItem(R.id.menu_copy_to).setVisible(false);
1637 menu.findItem(R.id.menu_move_to).setVisible(false);
1638 }
Kyle Horimoto426bd0d2015-07-29 15:33:49 -07001639
1640 @Override
Kyle Horimoto62a7fd02015-08-18 13:25:29 -07001641 public void afterActivityCreated(DirectoryFragment fragment) {}
Steve McKay1f199482015-05-20 15:58:42 -07001642 }
Ben Kwa24be5d32015-08-27 16:04:46 -07001643
1644 /**
1645 * The data model for the current loaded directory.
1646 */
Ben Kwa7461a952015-09-01 11:03:01 -07001647 @VisibleForTesting
1648 public static final class Model implements DocumentContext {
Ben Kwa24be5d32015-08-27 16:04:46 -07001649 private MultiSelectManager mSelectionManager;
Ben Kwa379e1762015-09-21 10:49:52 -07001650 private RecyclerView.Adapter<?> mViewAdapter;
Ben Kwa7461a952015-09-01 11:03:01 -07001651 private Context mContext;
Ben Kwa24be5d32015-08-27 16:04:46 -07001652 private int mCursorCount;
1653 private boolean mIsLoading;
Ben Kwa7461a952015-09-01 11:03:01 -07001654 private SparseBooleanArray mMarkedForDeletion = new SparseBooleanArray();
1655 private UpdateListener mUpdateListener;
Ben Kwa24be5d32015-08-27 16:04:46 -07001656 @Nullable private Cursor mCursor;
1657 @Nullable private String info;
1658 @Nullable private String error;
Ben Kwa7461a952015-09-01 11:03:01 -07001659
Ben Kwa379e1762015-09-21 10:49:52 -07001660 Model(Context context, MultiSelectManager selectionManager,
1661 RecyclerView.Adapter<?> viewAdapter) {
Ben Kwa7461a952015-09-01 11:03:01 -07001662 mContext = context;
1663 mSelectionManager = selectionManager;
Ben Kwa379e1762015-09-21 10:49:52 -07001664 mViewAdapter = viewAdapter;
Ben Kwa24be5d32015-08-27 16:04:46 -07001665 }
1666
1667 /**
1668 * Selects all files in the current directory.
1669 * @return true if the selection state changed for any files.
1670 */
1671 boolean selectAll() {
1672 return mSelectionManager.setItemsSelected(0, mCursorCount, true);
1673 }
1674
1675 /**
1676 * Clones the current selection into the given Selection object.
1677 * @param selection
1678 * @return The selection that was passed in, for convenience.
1679 */
1680 Selection getSelection(Selection selection) {
1681 return mSelectionManager.getSelection(selection);
1682 }
1683
1684 /**
1685 * @return The current selection (the live instance, not a copy).
1686 */
1687 Selection getSelection() {
1688 return mSelectionManager.getSelection();
1689 }
1690
1691 boolean isSelected(int position) {
1692 return mSelectionManager.getSelection().contains(position);
1693 }
1694
1695 void clearSelection() {
1696 mSelectionManager.clearSelection();
1697 }
1698
1699 void update(DirectoryResult result) {
1700 if (DEBUG) Log.i(TAG, "Updating model with new result set.");
1701
1702 if (result == null) {
1703 mCursor = null;
1704 mCursorCount = 0;
1705 info = null;
1706 error = null;
1707 mIsLoading = false;
Ben Kwa83cedf22015-09-11 15:15:45 -07001708 mUpdateListener.onModelUpdate(this);
Ben Kwa24be5d32015-08-27 16:04:46 -07001709 return;
1710 }
1711
1712 if (result.exception != null) {
1713 Log.e(TAG, "Error while loading directory contents", result.exception);
Ben Kwa83cedf22015-09-11 15:15:45 -07001714 mUpdateListener.onModelUpdateFailed(result.exception);
Ben Kwa24be5d32015-08-27 16:04:46 -07001715 return;
1716 }
1717
1718 mCursor = result.cursor;
1719 mCursorCount = mCursor.getCount();
1720
1721 final Bundle extras = mCursor.getExtras();
1722 if (extras != null) {
1723 info = extras.getString(DocumentsContract.EXTRA_INFO);
1724 error = extras.getString(DocumentsContract.EXTRA_ERROR);
1725 mIsLoading = extras.getBoolean(DocumentsContract.EXTRA_LOADING, false);
1726 }
Ben Kwa7461a952015-09-01 11:03:01 -07001727
Ben Kwa83cedf22015-09-11 15:15:45 -07001728 mUpdateListener.onModelUpdate(this);
Ben Kwa24be5d32015-08-27 16:04:46 -07001729 }
1730
Ben Kwa7461a952015-09-01 11:03:01 -07001731 int getItemCount() {
Ben Kwa91923182015-08-27 16:06:33 -07001732 return mCursorCount - mMarkedForDeletion.size();
Ben Kwa24be5d32015-08-27 16:04:46 -07001733 }
1734
Ben Kwa7461a952015-09-01 11:03:01 -07001735 Cursor getItem(int position) {
Ben Kwa91923182015-08-27 16:06:33 -07001736 // Items marked for deletion are masked out of the UI. To do this, for every marked
1737 // item whose position is less than the requested item position, advance the requested
1738 // position by 1.
1739 final int originalPos = position;
1740 final int size = mMarkedForDeletion.size();
Ben Kwa0d0daff2015-09-09 13:49:07 -07001741 for (int i = 0; i < size; ++i) {
Ben Kwa91923182015-08-27 16:06:33 -07001742 // It'd be more concise, but less efficient, to iterate over positions while calling
1743 // mMarkedForDeletion.get. Instead, iterate over deleted entries.
1744 if (mMarkedForDeletion.keyAt(i) <= position && mMarkedForDeletion.valueAt(i)) {
1745 ++position;
1746 }
1747 }
1748
1749 if (DEBUG) {
1750 Log.d(TAG, "Item position adjusted for deletion. Original: " + originalPos
1751 + " Adjusted: " + position);
1752 }
1753
Ben Kwa24be5d32015-08-27 16:04:46 -07001754 if (position >= mCursorCount) {
1755 throw new IndexOutOfBoundsException("Attempt to retrieve " + position + " of " +
1756 mCursorCount + " items");
1757 }
1758
1759 mCursor.moveToPosition(position);
1760 return mCursor;
1761 }
1762
1763 private boolean isEmpty() {
1764 return mCursorCount == 0;
1765 }
1766
1767 private boolean isLoading() {
1768 return mIsLoading;
1769 }
1770
1771 private List<DocumentInfo> getSelectedDocuments() {
1772 Selection sel = getSelection(new Selection());
1773 return getDocuments(sel);
1774 }
1775
Ben Kwa7461a952015-09-01 11:03:01 -07001776 List<DocumentInfo> getDocuments(Selection items) {
Ben Kwa91923182015-08-27 16:06:33 -07001777 final int size = (items != null) ? items.size() : 0;
Ben Kwa24be5d32015-08-27 16:04:46 -07001778
Ben Kwa91923182015-08-27 16:06:33 -07001779 final List<DocumentInfo> docs = new ArrayList<>(size);
Ben Kwa24be5d32015-08-27 16:04:46 -07001780 for (int i = 0; i < size; i++) {
1781 final Cursor cursor = getItem(items.get(i));
1782 checkNotNull(cursor, "Cursor cannot be null.");
1783 final DocumentInfo doc = DocumentInfo.fromDirectoryCursor(cursor);
1784 docs.add(doc);
1785 }
1786 return docs;
1787 }
1788
1789 @Override
1790 public Cursor getCursor() {
1791 if (Looper.myLooper() != Looper.getMainLooper()) {
1792 throw new IllegalStateException("Can't call getCursor from non-main thread.");
1793 }
1794 return mCursor;
1795 }
Ben Kwa91923182015-08-27 16:06:33 -07001796
Ben Kwa7461a952015-09-01 11:03:01 -07001797 List<DocumentInfo> getDocumentsMarkedForDeletion() {
Ben Kwa91923182015-08-27 16:06:33 -07001798 final int size = mMarkedForDeletion.size();
1799 List<DocumentInfo> docs = new ArrayList<>(size);
1800
1801 for (int i = 0; i < size; ++i) {
1802 final int position = mMarkedForDeletion.keyAt(i);
1803 checkState(position < mCursorCount);
1804 mCursor.moveToPosition(position);
1805 final DocumentInfo doc = DocumentInfo.fromDirectoryCursor(mCursor);
1806 docs.add(doc);
1807 }
1808 return docs;
1809 }
1810
1811 /**
1812 * Marks the given files for deletion. This will remove them from the UI. Clients must then
1813 * call either {@link #undoDeletion()} or {@link #finalizeDeletion()} to cancel or confirm
1814 * the deletion, respectively. Only one deletion operation is allowed at a time.
1815 *
1816 * @param selected A selection representing the files to delete.
1817 */
Ben Kwa7461a952015-09-01 11:03:01 -07001818 void markForDeletion(Selection selected) {
Ben Kwa91923182015-08-27 16:06:33 -07001819 // Only one deletion operation at a time.
1820 checkState(mMarkedForDeletion.size() == 0);
1821 // There should never be more to delete than what exists.
1822 checkState(mCursorCount >= selected.size());
1823
1824 final int size = selected.size();
1825 for (int i = 0; i < size; ++i) {
1826 int position = selected.get(i);
1827 if (DEBUG) Log.d(TAG, "Marked position " + position + " for deletion");
1828 mMarkedForDeletion.append(position, true);
Ben Kwa379e1762015-09-21 10:49:52 -07001829 mViewAdapter.notifyItemRemoved(position);
Ben Kwa91923182015-08-27 16:06:33 -07001830 }
1831 }
1832
1833 /**
1834 * Cancels an ongoing deletion operation. All files currently marked for deletion will be
1835 * unmarked, and restored in the UI. See {@link #markForDeletion(Selection)}.
1836 */
Ben Kwa7461a952015-09-01 11:03:01 -07001837 void undoDeletion() {
Ben Kwa91923182015-08-27 16:06:33 -07001838 // Iterate over deleted items, temporarily marking them false in the deletion list, and
1839 // re-adding them to the UI.
1840 final int size = mMarkedForDeletion.size();
1841 for (int i = 0; i < size; ++i) {
1842 final int position = mMarkedForDeletion.keyAt(i);
1843 mMarkedForDeletion.put(position, false);
Ben Kwa379e1762015-09-21 10:49:52 -07001844 mViewAdapter.notifyItemInserted(position);
Ben Kwa91923182015-08-27 16:06:33 -07001845 }
1846
1847 // Then, clear the deletion list.
1848 mMarkedForDeletion.clear();
1849 }
1850
1851 /**
1852 * Finalizes an ongoing deletion operation. All files currently marked for deletion will be
1853 * deleted. See {@link #markForDeletion(Selection)}.
Ben Kwa7461a952015-09-01 11:03:01 -07001854 *
1855 * @param view The view which will be used to interact with the user (e.g. surfacing
1856 * snackbars) for errors, info, etc.
Ben Kwa91923182015-08-27 16:06:33 -07001857 */
Ben Kwa83cedf22015-09-11 15:15:45 -07001858 void finalizeDeletion(Runnable errorCallback) {
Ben Kwa7461a952015-09-01 11:03:01 -07001859 final ContentResolver resolver = mContext.getContentResolver();
Ben Kwa83cedf22015-09-11 15:15:45 -07001860 DeleteFilesTask task = new DeleteFilesTask(resolver, errorCallback);
Ben Kwa7461a952015-09-01 11:03:01 -07001861 task.execute();
Ben Kwa91923182015-08-27 16:06:33 -07001862 }
1863
1864 /**
1865 * A Task which collects the DocumentInfo for documents that have been marked for deletion,
1866 * and actually deletes them.
1867 */
1868 private class DeleteFilesTask extends AsyncTask<Void, Void, List<DocumentInfo>> {
1869 private ContentResolver mResolver;
Ben Kwa7461a952015-09-01 11:03:01 -07001870 private Runnable mErrorCallback;
Ben Kwa91923182015-08-27 16:06:33 -07001871
Ben Kwa7461a952015-09-01 11:03:01 -07001872 /**
1873 * @param resolver A ContentResolver for performing the actual file deletions.
1874 * @param errorCallback A Runnable that is executed in the event that one or more errors
1875 * occured while copying files. Execution will occur on the UI thread.
1876 */
1877 public DeleteFilesTask(ContentResolver resolver, Runnable errorCallback) {
Ben Kwa91923182015-08-27 16:06:33 -07001878 mResolver = resolver;
Ben Kwa7461a952015-09-01 11:03:01 -07001879 mErrorCallback = errorCallback;
Ben Kwa91923182015-08-27 16:06:33 -07001880 }
1881
1882 @Override
1883 protected List<DocumentInfo> doInBackground(Void... params) {
1884 return getDocumentsMarkedForDeletion();
1885 }
1886
1887 @Override
1888 protected void onPostExecute(List<DocumentInfo> docs) {
1889 boolean hadTrouble = false;
1890 for (DocumentInfo doc : docs) {
1891 if (!doc.isDeleteSupported()) {
1892 Log.w(TAG, doc + " could not be deleted. Skipping...");
1893 hadTrouble = true;
1894 continue;
1895 }
1896
1897 ContentProviderClient client = null;
1898 try {
1899 if (DEBUG) Log.d(TAG, "Deleting: " + doc.displayName);
1900 client = DocumentsApplication.acquireUnstableProviderOrThrow(
1901 mResolver, doc.derivedUri.getAuthority());
1902 DocumentsContract.deleteDocument(client, doc.derivedUri);
1903 } catch (Exception e) {
1904 Log.w(TAG, "Failed to delete " + doc);
1905 hadTrouble = true;
1906 } finally {
1907 ContentProviderClient.releaseQuietly(client);
1908 }
1909 }
1910
1911 if (hadTrouble) {
Ben Kwa7461a952015-09-01 11:03:01 -07001912 // TODO show which files failed? b/23720103
1913 mErrorCallback.run();
Ben Kwa91923182015-08-27 16:06:33 -07001914 if (DEBUG) Log.d(TAG, "Deletion task completed. Some deletions failed.");
1915 } else {
1916 if (DEBUG) Log.d(TAG, "Deletion task completed successfully.");
1917 }
1918 mMarkedForDeletion.clear();
1919 }
1920 }
Ben Kwa7461a952015-09-01 11:03:01 -07001921
1922 void addUpdateListener(UpdateListener listener) {
1923 checkState(mUpdateListener == null);
1924 mUpdateListener = listener;
1925 }
1926
Ben Kwa379e1762015-09-21 10:49:52 -07001927 static class UpdateListener {
Ben Kwa7461a952015-09-01 11:03:01 -07001928 /**
1929 * Called when a successful update has occurred.
1930 */
Ben Kwa379e1762015-09-21 10:49:52 -07001931 void onModelUpdate(Model model) {}
Ben Kwa7461a952015-09-01 11:03:01 -07001932
1933 /**
1934 * Called when an update has been attempted but failed.
1935 */
Ben Kwa379e1762015-09-21 10:49:52 -07001936 void onModelUpdateFailed(Exception e) {}
1937 }
1938 }
Ben Kwa7461a952015-09-01 11:03:01 -07001939
Ben Kwa379e1762015-09-21 10:49:52 -07001940 private class ModelUpdateListener extends Model.UpdateListener {
1941 @Override
1942 public void onModelUpdate(Model model) {
1943 if (model.info != null || model.error != null) {
1944 mMessageBar.setInfo(model.info);
1945 mMessageBar.setError(model.error);
1946 mMessageBar.show();
1947 }
Ben Kwa7461a952015-09-01 11:03:01 -07001948
Ben Kwa379e1762015-09-21 10:49:52 -07001949 mProgressBar.setVisibility(model.isLoading() ? View.VISIBLE : View.GONE);
1950
1951 if (model.isEmpty()) {
1952 mEmptyView.setVisibility(View.VISIBLE);
1953 mRecView.setVisibility(View.GONE);
1954 } else {
1955 mEmptyView.setVisibility(View.GONE);
1956 mRecView.setVisibility(View.VISIBLE);
1957 }
1958
1959 mAdapter.notifyDataSetChanged();
1960 }
1961
1962 @Override
1963 public void onModelUpdateFailed(Exception e) {
1964 // TODO: deal with catastrophic update failures
1965 String error = getString(R.string.query_error);
1966 mAdapter.notifyDataSetChanged();
Ben Kwa7461a952015-09-01 11:03:01 -07001967 }
Ben Kwa24be5d32015-08-27 16:04:46 -07001968 }
Jeff Sharkeye22d02e2013-04-26 16:54:55 -07001969}