blob: 462ffd27072504149299b4c3788214f0834c45f6 [file] [log] [blame]
Jeff Sharkeye22d02e2013-04-26 16:54:55 -07001/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.documentsui;
18
Jeff Sharkey311a7d82015-04-11 21:27:21 -070019import static com.android.documentsui.BaseActivity.State.ACTION_BROWSE;
20import static com.android.documentsui.BaseActivity.State.ACTION_BROWSE_ALL;
Steve McKayd0a2a2c2015-03-25 14:35:33 -070021import static com.android.documentsui.BaseActivity.State.ACTION_CREATE;
22import static com.android.documentsui.BaseActivity.State.ACTION_MANAGE;
23import static com.android.documentsui.BaseActivity.State.MODE_GRID;
24import static com.android.documentsui.BaseActivity.State.MODE_LIST;
25import static com.android.documentsui.BaseActivity.State.MODE_UNKNOWN;
26import static com.android.documentsui.BaseActivity.State.SORT_ORDER_UNKNOWN;
Steve McKayfefcd702015-08-20 16:19:38 +000027import static com.android.documentsui.Shared.TAG;
Jeff Sharkeyac9e6272013-08-31 21:27:44 -070028import static com.android.documentsui.model.DocumentInfo.getCursorInt;
29import static com.android.documentsui.model.DocumentInfo.getCursorLong;
30import static com.android.documentsui.model.DocumentInfo.getCursorString;
Steve McKayef280152015-06-11 10:10:49 -070031import static com.android.internal.util.Preconditions.checkNotNull;
Steve McKayd57f5fa2015-07-23 16:33:41 -070032import static com.android.internal.util.Preconditions.checkState;
Steve McKay0599a442015-05-05 14:50:00 -070033
Ben Kwaf5858932015-04-07 15:43:39 -070034import android.app.Activity;
Jeff Sharkeyf63b7772013-10-01 17:57:41 -070035import android.app.ActivityManager;
Jeff Sharkey09c10bf2013-06-30 20:02:59 -070036import android.app.Fragment;
Jeff Sharkeye22d02e2013-04-26 16:54:55 -070037import android.app.FragmentManager;
38import android.app.FragmentTransaction;
Jeff Sharkeye22d02e2013-04-26 16:54:55 -070039import android.app.LoaderManager.LoaderCallbacks;
Vladislav Kaznacheev89b90332015-05-01 13:46:57 -070040import android.content.ClipData;
Jeff Sharkey3fd11772013-09-30 14:26:27 -070041import android.content.ContentProviderClient;
Jeff Sharkey873daa32013-08-18 17:38:20 -070042import android.content.ContentResolver;
Jeff Sharkeyd10f0492013-09-09 17:35:46 -070043import android.content.ContentValues;
Jeff Sharkeye22d02e2013-04-26 16:54:55 -070044import android.content.Context;
Jeff Sharkey873daa32013-08-18 17:38:20 -070045import android.content.Intent;
Jeff Sharkeye22d02e2013-04-26 16:54:55 -070046import android.content.Loader;
Jeff Sharkey083d7e12014-07-27 21:01:45 -070047import android.content.res.Resources;
Jeff Sharkeyac9e6272013-08-31 21:27:44 -070048import android.database.Cursor;
Jeff Sharkey8a8fb672013-05-07 12:41:33 -070049import android.graphics.Bitmap;
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -070050import android.graphics.Canvas;
Jeff Sharkey8a8fb672013-05-07 12:41:33 -070051import android.graphics.Point;
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -070052import android.graphics.drawable.Drawable;
Jeff Sharkeye22d02e2013-04-26 16:54:55 -070053import android.net.Uri;
Jeff Sharkey8a8fb672013-05-07 12:41:33 -070054import android.os.AsyncTask;
Jeff Sharkeye22d02e2013-04-26 16:54:55 -070055import android.os.Bundle;
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -070056import android.os.CancellationSignal;
Makoto Onuki77778752015-07-01 14:55:14 -070057import android.os.Handler;
58import android.os.Looper;
Jeff Sharkeye39a89b2013-10-29 11:56:37 -070059import android.os.OperationCanceledException;
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -070060import android.os.Parcelable;
Steve McKay8e258c62015-05-06 14:27:57 -070061import android.os.SystemProperties;
Jeff Sharkeye22d02e2013-04-26 16:54:55 -070062import android.provider.DocumentsContract;
Jeff Sharkeyac9e6272013-08-31 21:27:44 -070063import android.provider.DocumentsContract.Document;
Ben Kwa24be5d32015-08-27 16:04:46 -070064import android.support.annotation.Nullable;
Steve McKayef280152015-06-11 10:10:49 -070065import android.support.v7.widget.GridLayoutManager;
66import android.support.v7.widget.LinearLayoutManager;
67import android.support.v7.widget.RecyclerView;
68import android.support.v7.widget.RecyclerView.LayoutManager;
Steve McKayef280152015-06-11 10:10:49 -070069import android.support.v7.widget.RecyclerView.RecyclerListener;
70import android.support.v7.widget.RecyclerView.ViewHolder;
Jeff Sharkey6d579272015-06-11 09:16:19 -070071import android.text.TextUtils;
Jeff Sharkey09c10bf2013-06-30 20:02:59 -070072import android.text.format.DateUtils;
Jeff Sharkey2e694f82013-08-06 16:26:14 -070073import android.text.format.Formatter;
Jeff Sharkey8a8fb672013-05-07 12:41:33 -070074import android.text.format.Time;
75import android.util.Log;
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -070076import android.util.SparseArray;
Jeff Sharkeyc317af82013-07-01 16:56:54 -070077import android.view.ActionMode;
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -070078import android.view.DragEvent;
Steve McKayef280152015-06-11 10:10:49 -070079import android.view.GestureDetector;
Jeff Sharkeye22d02e2013-04-26 16:54:55 -070080import android.view.LayoutInflater;
Jeff Sharkey09c10bf2013-06-30 20:02:59 -070081import android.view.Menu;
Jeff Sharkey09c10bf2013-06-30 20:02:59 -070082import android.view.MenuItem;
Steve McKayef280152015-06-11 10:10:49 -070083import android.view.MotionEvent;
Jeff Sharkeye22d02e2013-04-26 16:54:55 -070084import android.view.View;
Steve McKayd57f5fa2015-07-23 16:33:41 -070085import android.view.View.OnLayoutChangeListener;
Jeff Sharkeye22d02e2013-04-26 16:54:55 -070086import android.view.ViewGroup;
Jeff Sharkeye22d02e2013-04-26 16:54:55 -070087import android.widget.ImageView;
Jeff Sharkeye22d02e2013-04-26 16:54:55 -070088import android.widget.TextView;
Jeff Sharkey873daa32013-08-18 17:38:20 -070089import android.widget.Toast;
Jeff Sharkeye22d02e2013-04-26 16:54:55 -070090
Steve McKay351a7492015-08-04 10:11:01 -070091import com.android.documentsui.BaseActivity.DocumentContext;
Steve McKayd0a2a2c2015-03-25 14:35:33 -070092import com.android.documentsui.BaseActivity.State;
Steve McKayef280152015-06-11 10:10:49 -070093import com.android.documentsui.MultiSelectManager.Selection;
Jeff Sharkey753a3ae2013-10-22 17:09:44 -070094import com.android.documentsui.ProviderExecutor.Preemptable;
Jeff Sharkeyd10f0492013-09-09 17:35:46 -070095import com.android.documentsui.RecentsProvider.StateColumns;
Jeff Sharkey724deeb2013-08-31 15:02:20 -070096import com.android.documentsui.model.DocumentInfo;
Tomasz Mikolajewski9452c442015-04-14 16:32:41 +090097import com.android.documentsui.model.DocumentStack;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -070098import com.android.documentsui.model.RootInfo;
Steve McKay1f199482015-05-20 15:58:42 -070099import com.android.internal.util.Preconditions;
Steve McKayfefcd702015-08-20 16:19:38 +0000100import com.google.common.collect.Lists;
Jeff Sharkeyc317af82013-07-01 16:56:54 -0700101
102import java.util.ArrayList;
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -0700103import java.util.Collections;
Jeff Sharkeya5defe32013-08-05 17:56:48 -0700104import java.util.List;
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700105
106/**
107 * Display the documents inside a single directory.
108 */
109public class DirectoryFragment extends Fragment {
110
Jeff Sharkeya5defe32013-08-05 17:56:48 -0700111 public static final int TYPE_NORMAL = 1;
112 public static final int TYPE_SEARCH = 2;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700113 public static final int TYPE_RECENT_OPEN = 3;
Jeff Sharkey5b535922013-08-02 15:55:26 -0700114
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700115 public static final int ANIM_NONE = 1;
116 public static final int ANIM_SIDE = 2;
117 public static final int ANIM_DOWN = 3;
118 public static final int ANIM_UP = 4;
119
Ben Kwaf5858932015-04-07 15:43:39 -0700120 public static final int REQUEST_COPY_DESTINATION = 1;
121
Steve McKayef280152015-06-11 10:10:49 -0700122 private static final int LOADER_ID = 42;
123 private static final boolean DEBUG = false;
Steve McKay8e258c62015-05-06 14:27:57 -0700124 private static final boolean DEBUG_ENABLE_DND = false;
125
Jeff Sharkey2e694f82013-08-06 16:26:14 -0700126 private static final String EXTRA_TYPE = "type";
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700127 private static final String EXTRA_ROOT = "root";
128 private static final String EXTRA_DOC = "doc";
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700129 private static final String EXTRA_QUERY = "query";
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700130 private static final String EXTRA_IGNORE_STATE = "ignoreState";
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700131
Ben Kwa24be5d32015-08-27 16:04:46 -0700132 private final Model mModel = new Model();
133
Steve McKayef280152015-06-11 10:10:49 -0700134 private final Handler mHandler = new Handler(Looper.getMainLooper());
Jeff Sharkey2e694f82013-08-06 16:26:14 -0700135
Steve McKayef280152015-06-11 10:10:49 -0700136 private View mEmptyView;
137 private RecyclerView mRecView;
138
139 private int mType = TYPE_NORMAL;
140 private String mStateKey;
141
142 private int mLastMode = MODE_UNKNOWN;
143 private int mLastSortOrder = SORT_ORDER_UNKNOWN;
144 private boolean mLastShowSize;
145 private boolean mHideGridTitles;
146 private boolean mSvelteRecents;
147 private Point mThumbSize;
148 private DocumentsAdapter mAdapter;
149 private LoaderCallbacks<DirectoryResult> mCallbacks;
Steve McKay1f199482015-05-20 15:58:42 -0700150 private FragmentTuner mFragmentTuner;
151 private DocumentClipper mClipper;
Steve McKayef280152015-06-11 10:10:49 -0700152 // These are lazily initialized.
Steve McKayd57f5fa2015-07-23 16:33:41 -0700153 private LinearLayoutManager mListLayout;
154 private GridLayoutManager mGridLayout;
Steve McKayd57f5fa2015-07-23 16:33:41 -0700155 private int mColumnCount = 1; // This will get updated when layout changes.
Steve McKay1f199482015-05-20 15:58:42 -0700156
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700157 public static void showNormal(FragmentManager fm, RootInfo root, DocumentInfo doc, int anim) {
158 show(fm, TYPE_NORMAL, root, doc, null, anim);
Jeff Sharkey2e694f82013-08-06 16:26:14 -0700159 }
160
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700161 public static void showSearch(FragmentManager fm, RootInfo root, String query, int anim) {
162 show(fm, TYPE_SEARCH, root, null, query, anim);
Jeff Sharkey2e694f82013-08-06 16:26:14 -0700163 }
164
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700165 public static void showRecentsOpen(FragmentManager fm, int anim) {
166 show(fm, TYPE_RECENT_OPEN, null, null, null, anim);
Jeff Sharkey2e694f82013-08-06 16:26:14 -0700167 }
168
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700169 private static void show(FragmentManager fm, int type, RootInfo root, DocumentInfo doc,
170 String query, int anim) {
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700171 final Bundle args = new Bundle();
Jeff Sharkey2e694f82013-08-06 16:26:14 -0700172 args.putInt(EXTRA_TYPE, type);
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700173 args.putParcelable(EXTRA_ROOT, root);
174 args.putParcelable(EXTRA_DOC, doc);
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700175 args.putString(EXTRA_QUERY, query);
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700176
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700177 final FragmentTransaction ft = fm.beginTransaction();
178 switch (anim) {
179 case ANIM_SIDE:
180 args.putBoolean(EXTRA_IGNORE_STATE, true);
181 break;
182 case ANIM_DOWN:
183 args.putBoolean(EXTRA_IGNORE_STATE, true);
184 ft.setCustomAnimations(R.animator.dir_down, R.animator.dir_frozen);
185 break;
186 case ANIM_UP:
187 ft.setCustomAnimations(R.animator.dir_frozen, R.animator.dir_up);
188 break;
189 }
190
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700191 final DirectoryFragment fragment = new DirectoryFragment();
192 fragment.setArguments(args);
193
Jeff Sharkey76112212013-08-06 11:26:10 -0700194 ft.replace(R.id.container_directory, fragment);
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700195 ft.commitAllowingStateLoss();
196 }
197
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700198 private static String buildStateKey(RootInfo root, DocumentInfo doc) {
199 final StringBuilder builder = new StringBuilder();
200 builder.append(root != null ? root.authority : "null").append(';');
201 builder.append(root != null ? root.rootId : "null").append(';');
202 builder.append(doc != null ? doc.documentId : "null");
203 return builder.toString();
204 }
205
Jeff Sharkeya5defe32013-08-05 17:56:48 -0700206 public static DirectoryFragment get(FragmentManager fm) {
207 // TODO: deal with multiple directories shown at once
Jeff Sharkey76112212013-08-06 11:26:10 -0700208 return (DirectoryFragment) fm.findFragmentById(R.id.container_directory);
Jeff Sharkeya5defe32013-08-05 17:56:48 -0700209 }
210
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700211 @Override
212 public View onCreateView(
213 LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
214 final Context context = inflater.getContext();
Jeff Sharkey083d7e12014-07-27 21:01:45 -0700215 final Resources res = context.getResources();
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700216 final View view = inflater.inflate(R.layout.fragment_directory, container, false);
217
Jeff Sharkeyc6cbdf12013-08-07 16:22:02 -0700218 mEmptyView = view.findViewById(android.R.id.empty);
219
Steve McKayef280152015-06-11 10:10:49 -0700220 mRecView = (RecyclerView) view.findViewById(R.id.recyclerView);
221 mRecView.setRecyclerListener(
222 new RecyclerListener() {
223 @Override
224 public void onViewRecycled(ViewHolder holder) {
225 cancelThumbnailTask(holder.itemView);
226 }
227 });
Steve McKay8e258c62015-05-06 14:27:57 -0700228
Steve McKayd57f5fa2015-07-23 16:33:41 -0700229 // TODO: Rather than update columns on layout changes, push this
230 // code (or something like it) into GridLayoutManager.
231 mRecView.addOnLayoutChangeListener(
232 new OnLayoutChangeListener() {
233
234 @Override
235 public void onLayoutChange(
236 View v, int left, int top, int right, int bottom, int oldLeft,
237 int oldTop, int oldRight, int oldBottom) {
Steve McKayfefcd702015-08-20 16:19:38 +0000238 mColumnCount = calculateColumnCount();
Steve McKayd57f5fa2015-07-23 16:33:41 -0700239 if (mGridLayout != null) {
240 mGridLayout.setSpanCount(mColumnCount);
241 }
242 }
243 });
244
245 // TODO: Add a divider between views (which might use RecyclerView.ItemDecoration).
Steve McKay8e258c62015-05-06 14:27:57 -0700246 if (DEBUG_ENABLE_DND) {
Steve McKayef280152015-06-11 10:10:49 -0700247 setupDragAndDropOnDirectoryView(mRecView);
Steve McKay8e258c62015-05-06 14:27:57 -0700248 }
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700249
Jeff Sharkeyac9e6272013-08-31 21:27:44 -0700250 return view;
251 }
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700252
Jeff Sharkeyac9e6272013-08-31 21:27:44 -0700253 @Override
Jeff Sharkeyf63b7772013-10-01 17:57:41 -0700254 public void onDestroyView() {
255 super.onDestroyView();
256
257 // Cancel any outstanding thumbnail requests
Steve McKayef280152015-06-11 10:10:49 -0700258 final int count = mRecView.getChildCount();
Jeff Sharkeyf63b7772013-10-01 17:57:41 -0700259 for (int i = 0; i < count; i++) {
Steve McKayef280152015-06-11 10:10:49 -0700260 final View view = mRecView.getChildAt(i);
261 cancelThumbnailTask(view);
Jeff Sharkeyf63b7772013-10-01 17:57:41 -0700262 }
Jeff Sharkeyfaaeb392013-10-04 14:44:56 -0700263
Steve McKayef280152015-06-11 10:10:49 -0700264 // Clear any outstanding selection
Ben Kwa24be5d32015-08-27 16:04:46 -0700265 mModel.clearSelection();
Jeff Sharkeyf63b7772013-10-01 17:57:41 -0700266 }
267
268 @Override
Jeff Sharkeyac9e6272013-08-31 21:27:44 -0700269 public void onActivityCreated(Bundle savedInstanceState) {
270 super.onActivityCreated(savedInstanceState);
271
272 final Context context = getActivity();
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700273 final State state = getDisplayState(DirectoryFragment.this);
Jeff Sharkeyac9e6272013-08-31 21:27:44 -0700274
Jeff Sharkey9656a532013-09-13 13:42:19 -0700275 final RootInfo root = getArguments().getParcelable(EXTRA_ROOT);
276 final DocumentInfo doc = getArguments().getParcelable(EXTRA_DOC);
277
Steve McKayef280152015-06-11 10:10:49 -0700278 mAdapter = new DocumentsAdapter(context);
279 mRecView.setAdapter(mAdapter);
280
281 GestureDetector.SimpleOnGestureListener listener =
282 new GestureDetector.SimpleOnGestureListener() {
283 @Override
284 public boolean onSingleTapUp(MotionEvent e) {
285 return DirectoryFragment.this.onSingleTapUp(e);
286 }
Steve McKay93d8ef42015-07-30 12:27:44 -0700287 @Override
288 public boolean onDoubleTap(MotionEvent e) {
289 Log.d(TAG, "Handling double tap.");
290 return DirectoryFragment.this.onDoubleTap(e);
291 }
Steve McKayef280152015-06-11 10:10:49 -0700292 };
293
Ben Kwa24be5d32015-08-27 16:04:46 -0700294 // TODO: instead of inserting the view into the constructor, extract listener-creation code
295 // and set the listener on the view after the fact. Then the view doesn't need to be passed
296 // into the selection manager which is passed into the model.
297 MultiSelectManager selMgr= new MultiSelectManager(
Steve McKay57394872015-08-12 14:48:34 -0700298 mRecView,
299 listener,
300 state.allowMultiple
301 ? MultiSelectManager.MODE_MULTIPLE
302 : MultiSelectManager.MODE_SINGLE);
Ben Kwa24be5d32015-08-27 16:04:46 -0700303 selMgr.addCallback(new SelectionModeListener());
304 mModel.setSelectionManager(selMgr);
Steve McKayef280152015-06-11 10:10:49 -0700305
Jeff Sharkey2e694f82013-08-06 16:26:14 -0700306 mType = getArguments().getInt(EXTRA_TYPE);
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700307 mStateKey = buildStateKey(root, doc);
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700308
Steve McKay1f199482015-05-20 15:58:42 -0700309 mFragmentTuner = pickFragmentTuner(state);
310 mClipper = new DocumentClipper(context);
311
Jeff Sharkey9656a532013-09-13 13:42:19 -0700312 if (mType == TYPE_RECENT_OPEN) {
313 // Hide titles when showing recents for picking images/videos
314 mHideGridTitles = MimePredicate.mimeMatches(
315 MimePredicate.VISUAL_MIMES, state.acceptMimes);
316 } else {
317 mHideGridTitles = (doc != null) && doc.isGridTitlesHidden();
318 }
319
Jeff Sharkeyf63b7772013-10-01 17:57:41 -0700320 final ActivityManager am = (ActivityManager) context.getSystemService(
321 Context.ACTIVITY_SERVICE);
322 mSvelteRecents = am.isLowRamDevice() && (mType == TYPE_RECENT_OPEN);
323
Jeff Sharkey46899c82013-08-18 22:26:48 -0700324 mCallbacks = new LoaderCallbacks<DirectoryResult>() {
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700325 @Override
Jeff Sharkey46899c82013-08-18 22:26:48 -0700326 public Loader<DirectoryResult> onCreateLoader(int id, Bundle args) {
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700327 final String query = getArguments().getString(EXTRA_QUERY);
Jeff Sharkey46165b52013-07-31 20:53:22 -0700328
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700329 Uri contentsUri;
330 switch (mType) {
331 case TYPE_NORMAL:
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700332 contentsUri = DocumentsContract.buildChildDocumentsUri(
333 doc.authority, doc.documentId);
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700334 if (state.action == ACTION_MANAGE) {
335 contentsUri = DocumentsContract.setManageMode(contentsUri);
336 }
Jeff Sharkeyd10f0492013-09-09 17:35:46 -0700337 return new DirectoryLoader(
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700338 context, mType, root, doc, contentsUri, state.userSortOrder);
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700339 case TYPE_SEARCH:
340 contentsUri = DocumentsContract.buildSearchDocumentsUri(
Jeff Sharkey0e8c8712013-09-12 21:59:06 -0700341 root.authority, root.rootId, query);
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700342 if (state.action == ACTION_MANAGE) {
343 contentsUri = DocumentsContract.setManageMode(contentsUri);
344 }
Jeff Sharkeyd10f0492013-09-09 17:35:46 -0700345 return new DirectoryLoader(
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700346 context, mType, root, doc, contentsUri, state.userSortOrder);
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700347 case TYPE_RECENT_OPEN:
Jeff Sharkey1c903cc2013-09-02 17:19:40 -0700348 final RootsCache roots = DocumentsApplication.getRootsCache(context);
Jeff Sharkey8b997042013-09-19 15:25:56 -0700349 return new RecentLoader(context, roots, state);
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700350 default:
351 throw new IllegalStateException("Unknown type " + mType);
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -0700352 }
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700353 }
354
355 @Override
Jeff Sharkey46899c82013-08-18 22:26:48 -0700356 public void onLoadFinished(Loader<DirectoryResult> loader, DirectoryResult result) {
Makoto Onuki77778752015-07-01 14:55:14 -0700357 if (result == null || result.exception != null) {
358 // onBackPressed does a fragment transaction, which can't be done inside
359 // onLoadFinished
360 mHandler.post(new Runnable() {
361 @Override
362 public void run() {
363 final Activity activity = getActivity();
364 if (activity != null) {
365 activity.onBackPressed();
366 }
367 }
368 });
369 return;
370 }
371
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700372 if (!isAdded()) return;
373
Ben Kwa24be5d32015-08-27 16:04:46 -0700374 // TODO: make the adapter listen to the model
375 mModel.update(result);
376 mAdapter.update();
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700377
378 // Push latest state up to UI
379 // TODO: if mode change was racing with us, don't overwrite it
Jeff Sharkey7d58fc62013-09-12 16:25:02 -0700380 if (result.mode != MODE_UNKNOWN) {
381 state.derivedMode = result.mode;
382 }
Jeff Sharkeyd10f0492013-09-09 17:35:46 -0700383 state.derivedSortOrder = result.sortOrder;
Steve McKayd0a2a2c2015-03-25 14:35:33 -0700384 ((BaseActivity) context).onStateChanged();
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700385
386 updateDisplayState();
387
Jeff Sharkey25f10b32013-10-07 14:08:17 -0700388 // When launched into empty recents, show drawer
Ben Kwa24be5d32015-08-27 16:04:46 -0700389 if (mType == TYPE_RECENT_OPEN && mModel.isEmpty() && !state.stackTouched &&
Steve McKayb68dd222015-04-20 17:18:15 -0700390 context instanceof DocumentsActivity) {
391 ((DocumentsActivity) context).setRootsDrawerOpen(true);
Jeff Sharkey25f10b32013-10-07 14:08:17 -0700392 }
393
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700394 // Restore any previous instance state
395 final SparseArray<Parcelable> container = state.dirState.remove(mStateKey);
396 if (container != null && !getArguments().getBoolean(EXTRA_IGNORE_STATE, false)) {
397 getView().restoreHierarchyState(container);
398 } else if (mLastSortOrder != state.derivedSortOrder) {
Steve McKayef280152015-06-11 10:10:49 -0700399 mRecView.smoothScrollToPosition(0);
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700400 }
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700401
402 mLastSortOrder = state.derivedSortOrder;
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700403 }
404
405 @Override
Jeff Sharkey46899c82013-08-18 22:26:48 -0700406 public void onLoaderReset(Loader<DirectoryResult> loader) {
Ben Kwa24be5d32015-08-27 16:04:46 -0700407 // TODO: make the adapter listen to the model.
408 mModel.update(null);
409 mAdapter.update();
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700410 }
411 };
412
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700413 // Kick off loader at least once
Steve McKayef280152015-06-11 10:10:49 -0700414 getLoaderManager().restartLoader(LOADER_ID, null, mCallbacks);
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700415
Kyle Horimoto426bd0d2015-07-29 15:33:49 -0700416 mFragmentTuner.afterActivityCreated(this);
Jeff Sharkey2e694f82013-08-06 16:26:14 -0700417 updateDisplayState();
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700418 }
419
Jeff Sharkey42d26792013-09-06 13:22:09 -0700420 @Override
Ben Kwaf5858932015-04-07 15:43:39 -0700421 public void onActivityResult(int requestCode, int resultCode, Intent data) {
Ben Kwaf5858932015-04-07 15:43:39 -0700422 // There's only one request code right now. Replace this with a switch statement or
423 // something more scalable when more codes are added.
424 if (requestCode != REQUEST_COPY_DESTINATION) {
425 return;
426 }
427 if (resultCode == Activity.RESULT_CANCELED || data == null) {
428 // User pressed the back button or otherwise cancelled the destination pick. Don't
429 // proceed with the copy.
430 return;
431 }
432
Tomasz Mikolajewski9452c442015-04-14 16:32:41 +0900433 CopyService.start(getActivity(), getDisplayState(this).selectedDocumentsForCopy,
Ben Kwacb4461f2015-05-05 11:50:11 -0700434 (DocumentStack) data.getParcelableExtra(CopyService.EXTRA_STACK),
435 data.getIntExtra(CopyService.EXTRA_TRANSFER_MODE, CopyService.TRANSFER_MODE_NONE));
Ben Kwaf5858932015-04-07 15:43:39 -0700436 }
437
Steve McKayef280152015-06-11 10:10:49 -0700438 private int getEventAdapterPosition(MotionEvent e) {
439 View view = mRecView.findChildViewUnder(e.getX(), e.getY());
440 return view != null ? mRecView.getChildAdapterPosition(view) : RecyclerView.NO_POSITION;
441 }
442
443 private boolean onSingleTapUp(MotionEvent e) {
Ben Kwa24be5d32015-08-27 16:04:46 -0700444 if (Events.isTouchEvent(e) && mModel.getSelection().isEmpty()) {
Steve McKay93d8ef42015-07-30 12:27:44 -0700445 int position = getEventAdapterPosition(e);
446 if (position != RecyclerView.NO_POSITION) {
447 return handleViewItem(position);
Steve McKayef280152015-06-11 10:10:49 -0700448 }
449 }
Steve McKay93d8ef42015-07-30 12:27:44 -0700450 return false;
451 }
Steve McKayef280152015-06-11 10:10:49 -0700452
Steve McKay93d8ef42015-07-30 12:27:44 -0700453 protected boolean onDoubleTap(MotionEvent e) {
454 if (Events.isMouseEvent(e)) {
455 Log.d(TAG, "Handling double tap from mouse.");
456 int position = getEventAdapterPosition(e);
457 if (position != RecyclerView.NO_POSITION) {
458 return handleViewItem(position);
459 }
460 }
461 return false;
462 }
463
464 private boolean handleViewItem(int position) {
Ben Kwa24be5d32015-08-27 16:04:46 -0700465 final Cursor cursor = mModel.getItem(position);
Steve McKay93d8ef42015-07-30 12:27:44 -0700466 checkNotNull(cursor, "Cursor cannot be null.");
467 final String docMimeType = getCursorString(cursor, Document.COLUMN_MIME_TYPE);
468 final int docFlags = getCursorInt(cursor, Document.COLUMN_FLAGS);
469 if (isDocumentEnabled(docMimeType, docFlags)) {
470 final DocumentInfo doc = DocumentInfo.fromDirectoryCursor(cursor);
Ben Kwa24be5d32015-08-27 16:04:46 -0700471 ((BaseActivity) getActivity()).onDocumentPicked(doc, mModel);
472 mModel.clearSelection();
Steve McKay93d8ef42015-07-30 12:27:44 -0700473 return true;
474 }
Steve McKayef280152015-06-11 10:10:49 -0700475 return false;
476 }
477
Ben Kwaf5858932015-04-07 15:43:39 -0700478 @Override
Jeff Sharkeyc8ae7a52013-09-18 16:26:49 -0700479 public void onStop() {
480 super.onStop();
481
482 // Remember last scroll location
483 final SparseArray<Parcelable> container = new SparseArray<Parcelable>();
484 getView().saveHierarchyState(container);
485 final State state = getDisplayState(this);
486 state.dirState.put(mStateKey, container);
487 }
488
489 @Override
Jeff Sharkey7d58fc62013-09-12 16:25:02 -0700490 public void onResume() {
491 super.onResume();
Jeff Sharkey42d26792013-09-06 13:22:09 -0700492 updateDisplayState();
493 }
494
Jeff Sharkeye8d13ea2014-08-08 15:10:03 -0700495 public void onDisplayStateChanged() {
496 updateDisplayState();
497 }
498
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700499 public void onUserSortOrderChanged() {
Jeff Sharkeyd10f0492013-09-09 17:35:46 -0700500 // Sort order change always triggers reload; we'll trigger state change
501 // on the flip side.
Steve McKayef280152015-06-11 10:10:49 -0700502 getLoaderManager().restartLoader(LOADER_ID, null, mCallbacks);
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700503 }
504
505 public void onUserModeChanged() {
Jeff Sharkeyd10f0492013-09-09 17:35:46 -0700506 final ContentResolver resolver = getActivity().getContentResolver();
507 final State state = getDisplayState(this);
508
509 final RootInfo root = getArguments().getParcelable(EXTRA_ROOT);
510 final DocumentInfo doc = getArguments().getParcelable(EXTRA_DOC);
511
Jeff Sharkey0e8c8712013-09-12 21:59:06 -0700512 if (root != null && doc != null) {
Jeff Sharkey7d58fc62013-09-12 16:25:02 -0700513 final Uri stateUri = RecentsProvider.buildState(
514 root.authority, root.rootId, doc.documentId);
515 final ContentValues values = new ContentValues();
516 values.put(StateColumns.MODE, state.userMode);
Jeff Sharkeyd10f0492013-09-09 17:35:46 -0700517
Jeff Sharkey7d58fc62013-09-12 16:25:02 -0700518 new AsyncTask<Void, Void, Void>() {
519 @Override
520 protected Void doInBackground(Void... params) {
521 resolver.insert(stateUri, values);
522 return null;
523 }
524 }.execute();
525 }
Jeff Sharkeyd10f0492013-09-09 17:35:46 -0700526
527 // Mode change is just visual change; no need to kick loader, and
528 // deliver change event immediately.
529 state.derivedMode = state.userMode;
Steve McKayd0a2a2c2015-03-25 14:35:33 -0700530 ((BaseActivity) getActivity()).onStateChanged();
Jeff Sharkeyd10f0492013-09-09 17:35:46 -0700531
Jeff Sharkeya4d1f222013-09-07 14:45:03 -0700532 updateDisplayState();
533 }
534
535 private void updateDisplayState() {
Jeff Sharkeyb3620442013-09-01 18:41:04 -0700536 final State state = getDisplayState(this);
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700537
Jeff Sharkey5e1884d2013-09-10 17:56:39 -0700538 if (mLastMode == state.derivedMode && mLastShowSize == state.showSize) return;
Jeff Sharkeyd10f0492013-09-09 17:35:46 -0700539 mLastMode = state.derivedMode;
Jeff Sharkey5e1884d2013-09-10 17:56:39 -0700540 mLastShowSize = state.showSize;
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700541
Steve McKayef280152015-06-11 10:10:49 -0700542 updateLayout(state.derivedMode);
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700543
Steve McKayef280152015-06-11 10:10:49 -0700544 mRecView.setAdapter(mAdapter);
545 }
546
547 /**
548 * Returns a {@code LayoutManager} for {@code mode}, lazily initializing
549 * classes as needed.
550 */
551 private void updateLayout(int mode) {
Jeff Sharkey8a8fb672013-05-07 12:41:33 -0700552 final int thumbSize;
Steve McKayef280152015-06-11 10:10:49 -0700553
554 final LayoutManager layout;
555 switch (mode) {
556 case MODE_GRID:
Steve McKayef280152015-06-11 10:10:49 -0700557 thumbSize = getResources().getDimensionPixelSize(R.dimen.grid_width);
Steve McKaya9be7182015-07-22 16:03:35 -0700558 if (mGridLayout == null) {
Steve McKayd57f5fa2015-07-23 16:33:41 -0700559 mGridLayout = new GridLayoutManager(getContext(), mColumnCount );
Steve McKaya9be7182015-07-22 16:03:35 -0700560 }
Steve McKayef280152015-06-11 10:10:49 -0700561 layout = mGridLayout;
562 break;
563 case MODE_LIST:
Steve McKaya9be7182015-07-22 16:03:35 -0700564 thumbSize = getResources().getDimensionPixelSize(R.dimen.icon_size);
Steve McKayef280152015-06-11 10:10:49 -0700565 if (mListLayout == null) {
566 mListLayout = new LinearLayoutManager(getContext());
567 }
Steve McKayef280152015-06-11 10:10:49 -0700568 layout = mListLayout;
569 break;
570 case MODE_UNKNOWN:
571 default:
572 throw new IllegalArgumentException("Unsupported layout mode: " + mode);
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700573 }
Jeff Sharkey8a8fb672013-05-07 12:41:33 -0700574
Steve McKayef280152015-06-11 10:10:49 -0700575 mRecView.setLayoutManager(layout);
Kyle Horimoto2da6e4a2015-08-27 16:44:00 -0700576 // TODO: Once b/23691541 is resolved, use a listener within MultiSelectManager instead of
577 // imperatively calling this function.
578 mSelectionManager.handleLayoutChanged();
Steve McKayef280152015-06-11 10:10:49 -0700579 // setting layout manager automatically invalidates existing ViewHolders.
Jeff Sharkey8a8fb672013-05-07 12:41:33 -0700580 mThumbSize = new Point(thumbSize, thumbSize);
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700581 }
582
Steve McKayfefcd702015-08-20 16:19:38 +0000583 private int calculateColumnCount() {
584 int cellWidth = getResources().getDimensionPixelSize(R.dimen.grid_width);
585 int cellMargin = 2 * getResources().getDimensionPixelSize(R.dimen.grid_item_margin);
Steve McKayd57f5fa2015-07-23 16:33:41 -0700586 int viewPadding = mRecView.getPaddingLeft() + mRecView.getPaddingRight();
Steve McKayfefcd702015-08-20 16:19:38 +0000587
Steve McKayd57f5fa2015-07-23 16:33:41 -0700588 checkState(mRecView.getWidth() > 0);
589 int columnCount = Math.max(1,
Steve McKayfefcd702015-08-20 16:19:38 +0000590 (mRecView.getWidth() - viewPadding) / (cellWidth + cellMargin));
591
Steve McKayd57f5fa2015-07-23 16:33:41 -0700592 return columnCount;
593 }
594
Steve McKayef280152015-06-11 10:10:49 -0700595 /**
596 * Manages the integration between our ActionMode and MultiSelectManager, initiating
597 * ActionMode when there is a selection, canceling it when there is no selection,
598 * and clearing selection when action mode is explicitly exited by the user.
599 */
600 private final class SelectionModeListener
601 implements MultiSelectManager.Callback, ActionMode.Callback {
602
603 private Selection mSelected = new Selection();
604 private ActionMode mActionMode;
Steve McKay4f4232d2015-07-22 12:13:46 -0700605 private int mNoDeleteCount = 0;
606 private Menu mMenu;
Steve McKayef280152015-06-11 10:10:49 -0700607
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700608 @Override
Steve McKayef280152015-06-11 10:10:49 -0700609 public boolean onBeforeItemStateChange(int position, boolean selected) {
610 // Directories and footer items cannot be checked
611 if (selected) {
Ben Kwa24be5d32015-08-27 16:04:46 -0700612 final Cursor cursor = mModel.getItem(position);
Steve McKayef280152015-06-11 10:10:49 -0700613 checkNotNull(cursor, "Cursor cannot be null.");
Jeff Sharkey7cf49032013-09-26 10:54:16 -0700614 final String docMimeType = getCursorString(cursor, Document.COLUMN_MIME_TYPE);
615 final int docFlags = getCursorInt(cursor, Document.COLUMN_FLAGS);
Steve McKayef280152015-06-11 10:10:49 -0700616 return isDocumentEnabled(docMimeType, docFlags);
617 }
618 return true;
619 }
620
621 @Override
622 public void onItemStateChanged(int position, boolean selected) {
Steve McKay4f4232d2015-07-22 12:13:46 -0700623
Ben Kwa24be5d32015-08-27 16:04:46 -0700624 final Cursor cursor = mModel.getItem(position);
Steve McKay4f4232d2015-07-22 12:13:46 -0700625 checkNotNull(cursor, "Cursor cannot be null.");
626
627 final int docFlags = getCursorInt(cursor, Document.COLUMN_FLAGS);
628 if ((docFlags & Document.FLAG_SUPPORTS_DELETE) == 0) {
629 mNoDeleteCount += selected ? 1 : -1;
630 }
Steve McKay57394872015-08-12 14:48:34 -0700631 }
Steve McKay4f4232d2015-07-22 12:13:46 -0700632
Steve McKay57394872015-08-12 14:48:34 -0700633 @Override
634 public void onSelectionChanged() {
Ben Kwa24be5d32015-08-27 16:04:46 -0700635 mModel.getSelection(mSelected);
Steve McKay4f4232d2015-07-22 12:13:46 -0700636 if (mSelected.size() > 0) {
Steve McKayef280152015-06-11 10:10:49 -0700637 if (DEBUG) Log.d(TAG, "Maybe starting action mode.");
638 if (mActionMode == null) {
639 if (DEBUG) Log.d(TAG, "Yeah. Starting action mode.");
640 mActionMode = getActivity().startActionMode(this);
Tomasz Mikolajewski2b6b0662015-07-28 14:59:00 +0900641 getActivity().getWindow().setStatusBarColor(
642 getResources().getColor(R.color.action_mode_status_bar_background));
Jeff Sharkeyaed873d2013-09-09 16:51:06 -0700643 }
Steve McKay4f4232d2015-07-22 12:13:46 -0700644 updateActionMenu();
645 } else {
646 if (DEBUG) Log.d(TAG, "Finishing action mode.");
647 if (mActionMode != null) {
648 mActionMode.finish();
649 }
Tomasz Mikolajewski2b6b0662015-07-28 14:59:00 +0900650 getActivity().getWindow().setStatusBarColor(
651 getResources().getColor(R.color.status_bar_background));
Jeff Sharkeyf339f252013-08-15 16:17:41 -0700652 }
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700653
Steve McKayef280152015-06-11 10:10:49 -0700654 if (mActionMode != null) {
655 mActionMode.setTitle(TextUtils.formatSelectedCount(mSelected.size()));
656 }
657 }
658
659 // Called when the user exits the action mode
660 @Override
661 public void onDestroyActionMode(ActionMode mode) {
662 if (DEBUG) Log.d(TAG, "Handling action mode destroyed.");
663 mActionMode = null;
664 // clear selection
Ben Kwa24be5d32015-08-27 16:04:46 -0700665 mModel.clearSelection();
Steve McKay4f4232d2015-07-22 12:13:46 -0700666 mSelected.clear();
667 mNoDeleteCount = 0;
Steve McKayef280152015-06-11 10:10:49 -0700668 }
669
Jeff Sharkeyc317af82013-07-01 16:56:54 -0700670 @Override
671 public boolean onCreateActionMode(ActionMode mode, Menu menu) {
672 mode.getMenuInflater().inflate(R.menu.mode_directory, menu);
Ben Kwa24be5d32015-08-27 16:04:46 -0700673 mode.setTitle(TextUtils.formatSelectedCount(mModel.getSelection().size()));
674 return mModel.getSelection().size() > 0;
Jeff Sharkeyc317af82013-07-01 16:56:54 -0700675 }
676
677 @Override
678 public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
Steve McKay4f4232d2015-07-22 12:13:46 -0700679 mMenu = menu;
680 updateActionMenu();
Jeff Sharkeyc317af82013-07-01 16:56:54 -0700681 return true;
682 }
683
Steve McKay4f4232d2015-07-22 12:13:46 -0700684 private void updateActionMenu() {
685 checkNotNull(mMenu);
686 // Delegate update logic to our owning action, since specialized logic is desired.
687 mFragmentTuner.updateActionMenu(mMenu, mType, mNoDeleteCount == 0);
688 }
689
Jeff Sharkeyc317af82013-07-01 16:56:54 -0700690 @Override
Steve McKayef280152015-06-11 10:10:49 -0700691 public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
Steve McKay1f199482015-05-20 15:58:42 -0700692
Ben Kwa24be5d32015-08-27 16:04:46 -0700693 Selection selection = mModel.getSelection(new Selection());
Jeff Sharkeyc317af82013-07-01 16:56:54 -0700694
Jeff Sharkey873daa32013-08-18 17:38:20 -0700695 final int id = item.getItemId();
696 if (id == R.id.menu_open) {
Steve McKayef280152015-06-11 10:10:49 -0700697 openDocuments(selection);
Jeff Sharkeyb3620442013-09-01 18:41:04 -0700698 mode.finish();
Jeff Sharkeyc317af82013-07-01 16:56:54 -0700699 return true;
Jeff Sharkey873daa32013-08-18 17:38:20 -0700700
701 } else if (id == R.id.menu_share) {
Steve McKayef280152015-06-11 10:10:49 -0700702 shareDocuments(selection);
Jeff Sharkeyb3620442013-09-01 18:41:04 -0700703 mode.finish();
Jeff Sharkey873daa32013-08-18 17:38:20 -0700704 return true;
705
706 } else if (id == R.id.menu_delete) {
Steve McKayef280152015-06-11 10:10:49 -0700707 deleteDocuments(selection);
Jeff Sharkeyb3620442013-09-01 18:41:04 -0700708 mode.finish();
Jeff Sharkey873daa32013-08-18 17:38:20 -0700709 return true;
710
Steve McKay1f199482015-05-20 15:58:42 -0700711 } else if (id == R.id.menu_copy_to) {
Steve McKayef280152015-06-11 10:10:49 -0700712 transferDocuments(selection, CopyService.TRANSFER_MODE_COPY);
Ben Kwacb4461f2015-05-05 11:50:11 -0700713 mode.finish();
714 return true;
715
Steve McKay1f199482015-05-20 15:58:42 -0700716 } else if (id == R.id.menu_move_to) {
Steve McKayef280152015-06-11 10:10:49 -0700717 transferDocuments(selection, CopyService.TRANSFER_MODE_MOVE);
Ben Kwa41b26c12015-03-31 10:11:43 -0700718 mode.finish();
719 return true;
720
Steve McKay1f199482015-05-20 15:58:42 -0700721 } else if (id == R.id.menu_copy_to_clipboard) {
Steve McKayef280152015-06-11 10:10:49 -0700722 copySelectionToClipboard(selection);
Steve McKay1f199482015-05-20 15:58:42 -0700723 mode.finish();
724 return true;
725
Ben Kwa512a6ba2015-03-31 08:15:21 -0700726 } else if (id == R.id.menu_select_all) {
Steve McKay0599a442015-05-05 14:50:00 -0700727 selectAllFiles();
Ben Kwa512a6ba2015-03-31 08:15:21 -0700728 return true;
729
Jeff Sharkeyc317af82013-07-01 16:56:54 -0700730 } else {
731 return false;
732 }
733 }
Steve McKayef280152015-06-11 10:10:49 -0700734 }
Jeff Sharkeyc317af82013-07-01 16:56:54 -0700735
Steve McKayef280152015-06-11 10:10:49 -0700736 private static void cancelThumbnailTask(View view) {
737 final ImageView iconThumb = (ImageView) view.findViewById(R.id.icon_thumb);
738 if (iconThumb != null) {
739 final ThumbnailAsyncTask oldTask = (ThumbnailAsyncTask) iconThumb.getTag();
740 if (oldTask != null) {
741 oldTask.preempt();
742 iconThumb.setTag(null);
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700743 }
744 }
Steve McKayef280152015-06-11 10:10:49 -0700745 }
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -0700746
Steve McKayef280152015-06-11 10:10:49 -0700747 private void openDocuments(final Selection selected) {
Steve McKay9276f3b2015-05-27 16:11:42 -0700748 new GetDocumentsTask() {
749 @Override
750 void onDocumentsReady(List<DocumentInfo> docs) {
Steve McKay0fbfc652015-08-20 16:48:49 -0700751 // TODO: Implement support in Files activity for opening multiple docs.
Steve McKay9276f3b2015-05-27 16:11:42 -0700752 BaseActivity.get(DirectoryFragment.this).onDocumentsPicked(docs);
Ben Kwaf527c632015-04-08 15:03:35 -0700753 }
Steve McKay9276f3b2015-05-27 16:11:42 -0700754 }.execute(selected);
Jeff Sharkey873daa32013-08-18 17:38:20 -0700755 }
756
Steve McKayef280152015-06-11 10:10:49 -0700757 private void shareDocuments(final Selection selected) {
Steve McKay9276f3b2015-05-27 16:11:42 -0700758 new GetDocumentsTask() {
759 @Override
760 void onDocumentsReady(List<DocumentInfo> docs) {
761 Intent intent;
762
763 // Filter out directories - those can't be shared.
Steve McKayfefcd702015-08-20 16:19:38 +0000764 List<DocumentInfo> docsForSend = new ArrayList<>();
Steve McKay9276f3b2015-05-27 16:11:42 -0700765 for (DocumentInfo doc: docs) {
766 if (!Document.MIME_TYPE_DIR.equals(doc.mimeType)) {
767 docsForSend.add(doc);
768 }
769 }
770
771 if (docsForSend.size() == 1) {
772 final DocumentInfo doc = docsForSend.get(0);
773
774 intent = new Intent(Intent.ACTION_SEND);
775 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
776 intent.addCategory(Intent.CATEGORY_DEFAULT);
777 intent.setType(doc.mimeType);
778 intent.putExtra(Intent.EXTRA_STREAM, doc.derivedUri);
779
780 } else if (docsForSend.size() > 1) {
781 intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
782 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
783 intent.addCategory(Intent.CATEGORY_DEFAULT);
784
Steve McKayfefcd702015-08-20 16:19:38 +0000785 final ArrayList<String> mimeTypes = new ArrayList<>();
786 final ArrayList<Uri> uris = new ArrayList<>();
Steve McKay9276f3b2015-05-27 16:11:42 -0700787 for (DocumentInfo doc : docsForSend) {
788 mimeTypes.add(doc.mimeType);
789 uris.add(doc.derivedUri);
790 }
791
792 intent.setType(findCommonMimeType(mimeTypes));
793 intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
794
795 } else {
796 return;
797 }
798
799 intent = Intent.createChooser(intent, getActivity().getText(R.string.share_via));
800 startActivity(intent);
801 }
802 }.execute(selected);
803 }
804
Steve McKayef280152015-06-11 10:10:49 -0700805 private void deleteDocuments(final Selection selected) {
Jeff Sharkey873daa32013-08-18 17:38:20 -0700806 final Context context = getActivity();
807 final ContentResolver resolver = context.getContentResolver();
808
Steve McKay9276f3b2015-05-27 16:11:42 -0700809 new GetDocumentsTask() {
810 @Override
811 void onDocumentsReady(List<DocumentInfo> docs) {
812 boolean hadTrouble = false;
813 for (DocumentInfo doc : docs) {
814 if (!doc.isDeleteSupported()) {
815 Log.w(TAG, "Skipping " + doc);
816 hadTrouble = true;
817 continue;
818 }
Jeff Sharkey873daa32013-08-18 17:38:20 -0700819
Steve McKay9276f3b2015-05-27 16:11:42 -0700820 ContentProviderClient client = null;
821 try {
822 client = DocumentsApplication.acquireUnstableProviderOrThrow(
823 resolver, doc.derivedUri.getAuthority());
824 DocumentsContract.deleteDocument(client, doc.derivedUri);
825 } catch (Exception e) {
826 Log.w(TAG, "Failed to delete " + doc);
827 hadTrouble = true;
828 } finally {
829 ContentProviderClient.releaseQuietly(client);
830 }
831 }
Jeff Sharkey873daa32013-08-18 17:38:20 -0700832
Steve McKay9276f3b2015-05-27 16:11:42 -0700833 if (hadTrouble) {
834 Toast.makeText(
835 context,
836 R.string.toast_failed_delete,
837 Toast.LENGTH_SHORT).show();
838 }
839 }
840 }.execute(selected);
Jeff Sharkey873daa32013-08-18 17:38:20 -0700841 }
842
Steve McKayef280152015-06-11 10:10:49 -0700843 private void transferDocuments(final Selection selected, final int mode) {
Ben Kwaf5858932015-04-07 15:43:39 -0700844 // Pop up a dialog to pick a destination. This is inadequate but works for now.
845 // TODO: Implement a picker that is to spec.
Daichi Hironocaadd412015-04-10 15:50:38 +0900846 final Intent intent = new Intent(
Daichi Hirono22574ed2015-04-15 13:41:18 +0900847 BaseActivity.DocumentsIntent.ACTION_OPEN_COPY_DESTINATION,
Daichi Hironocaadd412015-04-10 15:50:38 +0900848 Uri.EMPTY,
849 getActivity(),
850 DocumentsActivity.class);
Steve McKay9276f3b2015-05-27 16:11:42 -0700851
852 new GetDocumentsTask() {
853 @Override
854 void onDocumentsReady(List<DocumentInfo> docs) {
855 getDisplayState(DirectoryFragment.this).selectedDocumentsForCopy = docs;
856
857 boolean directoryCopy = false;
858 for (DocumentInfo info : docs) {
859 if (Document.MIME_TYPE_DIR.equals(info.mimeType)) {
860 directoryCopy = true;
861 break;
862 }
863 }
864 intent.putExtra(BaseActivity.DocumentsIntent.EXTRA_DIRECTORY_COPY, directoryCopy);
865 intent.putExtra(CopyService.EXTRA_TRANSFER_MODE, mode);
866 startActivityForResult(intent, REQUEST_COPY_DESTINATION);
Daichi Hironof2a822d2015-04-14 17:12:54 +0900867 }
Steve McKay9276f3b2015-05-27 16:11:42 -0700868 }.execute(selected);
Ben Kwa41b26c12015-03-31 10:11:43 -0700869 }
870
Jeff Sharkeyb3620442013-09-01 18:41:04 -0700871 private static State getDisplayState(Fragment fragment) {
Steve McKayd0a2a2c2015-03-25 14:35:33 -0700872 return ((BaseActivity) fragment.getActivity()).getDisplayState();
Jeff Sharkey09c10bf2013-06-30 20:02:59 -0700873 }
874
Jeff Sharkeyaed873d2013-09-09 16:51:06 -0700875 private static abstract class Footer {
876 private final int mItemViewType;
877
878 public Footer(int itemViewType) {
879 mItemViewType = itemViewType;
880 }
881
882 public abstract View getView(View convertView, ViewGroup parent);
883
884 public int getItemViewType() {
885 return mItemViewType;
886 }
Jeff Sharkey20b32272013-09-03 15:25:52 -0700887 }
888
Jeff Sharkey5e1884d2013-09-10 17:56:39 -0700889 private class LoadingFooter extends Footer {
Jeff Sharkeyaed873d2013-09-09 16:51:06 -0700890 public LoadingFooter() {
891 super(1);
892 }
893
Jeff Sharkey20b32272013-09-03 15:25:52 -0700894 @Override
895 public View getView(View convertView, ViewGroup parent) {
896 final Context context = parent.getContext();
Jeff Sharkey5e1884d2013-09-10 17:56:39 -0700897 final State state = getDisplayState(DirectoryFragment.this);
898
Jeff Sharkey20b32272013-09-03 15:25:52 -0700899 if (convertView == null) {
900 final LayoutInflater inflater = LayoutInflater.from(context);
Jeff Sharkey5e1884d2013-09-10 17:56:39 -0700901 if (state.derivedMode == MODE_LIST) {
902 convertView = inflater.inflate(R.layout.item_loading_list, parent, false);
903 } else if (state.derivedMode == MODE_GRID) {
904 convertView = inflater.inflate(R.layout.item_loading_grid, parent, false);
905 } else {
906 throw new IllegalStateException();
907 }
Jeff Sharkey20b32272013-09-03 15:25:52 -0700908 }
Jeff Sharkey5e1884d2013-09-10 17:56:39 -0700909
Jeff Sharkey20b32272013-09-03 15:25:52 -0700910 return convertView;
911 }
912 }
913
Jeff Sharkeyaed873d2013-09-09 16:51:06 -0700914 private class MessageFooter extends Footer {
Jeff Sharkey20b32272013-09-03 15:25:52 -0700915 private final int mIcon;
916 private final String mMessage;
917
Jeff Sharkeyaed873d2013-09-09 16:51:06 -0700918 public MessageFooter(int itemViewType, int icon, String message) {
919 super(itemViewType);
Jeff Sharkey20b32272013-09-03 15:25:52 -0700920 mIcon = icon;
921 mMessage = message;
922 }
923
924 @Override
925 public View getView(View convertView, ViewGroup parent) {
926 final Context context = parent.getContext();
927 final State state = getDisplayState(DirectoryFragment.this);
928
929 if (convertView == null) {
930 final LayoutInflater inflater = LayoutInflater.from(context);
Jeff Sharkeyd10f0492013-09-09 17:35:46 -0700931 if (state.derivedMode == MODE_LIST) {
Jeff Sharkey20b32272013-09-03 15:25:52 -0700932 convertView = inflater.inflate(R.layout.item_message_list, parent, false);
Jeff Sharkeyd10f0492013-09-09 17:35:46 -0700933 } else if (state.derivedMode == MODE_GRID) {
Jeff Sharkey20b32272013-09-03 15:25:52 -0700934 convertView = inflater.inflate(R.layout.item_message_grid, parent, false);
935 } else {
936 throw new IllegalStateException();
937 }
938 }
939
940 final ImageView icon = (ImageView) convertView.findViewById(android.R.id.icon);
941 final TextView title = (TextView) convertView.findViewById(android.R.id.title);
942 icon.setImageResource(mIcon);
943 title.setText(mMessage);
944 return convertView;
945 }
946 }
947
Steve McKayef280152015-06-11 10:10:49 -0700948 // Provide a reference to the views for each data item
949 // Complex data items may need more than one view per item, and
950 // you provide access to all the views for a data item in a view holder
951 private static final class DocumentHolder extends RecyclerView.ViewHolder {
952 // each data item is just a string in this case
953 public View view;
954 public String docId; // The stable document id.
955 public DocumentHolder(View view) {
956 super(view);
957 this.view = view;
958 }
959 }
960
Ben Kwa24be5d32015-08-27 16:04:46 -0700961 private final class DocumentsAdapter extends RecyclerView.Adapter<DocumentHolder> {
Steve McKayef280152015-06-11 10:10:49 -0700962
963 private final Context mContext;
964 private final LayoutInflater mInflater;
965 // TODO: Bring back support for footers.
Steve McKayfefcd702015-08-20 16:19:38 +0000966 private final List<Footer> mFooters = new ArrayList<>();
Steve McKayef280152015-06-11 10:10:49 -0700967
Steve McKayef280152015-06-11 10:10:49 -0700968 public DocumentsAdapter(Context context) {
969 mContext = context;
970 mInflater = LayoutInflater.from(context);
971 }
Jeff Sharkeyac9e6272013-08-31 21:27:44 -0700972
Ben Kwa24be5d32015-08-27 16:04:46 -0700973 public void update() {
Jeff Sharkey20b32272013-09-03 15:25:52 -0700974 mFooters.clear();
Ben Kwa24be5d32015-08-27 16:04:46 -0700975 if (mModel.info != null) {
976 mFooters.add(new MessageFooter(2, R.drawable.ic_dialog_info, mModel.info));
977 }
978 if (mModel.error != null) {
979 mFooters.add(new MessageFooter(3, R.drawable.ic_dialog_alert, mModel.error));
980 }
981 if (mModel.isLoading()) {
982 mFooters.add(new LoadingFooter());
Jeff Sharkey20b32272013-09-03 15:25:52 -0700983 }
Jeff Sharkeyc6cbdf12013-08-07 16:22:02 -0700984
Ben Kwa24be5d32015-08-27 16:04:46 -0700985 if (mModel.isEmpty()) {
Jeff Sharkeyc6cbdf12013-08-07 16:22:02 -0700986 mEmptyView.setVisibility(View.VISIBLE);
987 } else {
988 mEmptyView.setVisibility(View.GONE);
989 }
990
Jeff Sharkeya5defe32013-08-05 17:56:48 -0700991 notifyDataSetChanged();
Jeff Sharkeye22d02e2013-04-26 16:54:55 -0700992 }
993
994 @Override
Steve McKayef280152015-06-11 10:10:49 -0700995 public DocumentHolder onCreateViewHolder(ViewGroup parent, int viewType) {
996 final State state = getDisplayState(DirectoryFragment.this);
997 final LayoutInflater inflater = LayoutInflater.from(getContext());
998 switch (state.derivedMode) {
999 case MODE_GRID:
1000 return new DocumentHolder(inflater.inflate(R.layout.item_doc_grid, parent, false));
1001 case MODE_LIST:
1002 return new DocumentHolder(inflater.inflate(R.layout.item_doc_list, parent, false));
1003 case MODE_UNKNOWN:
1004 default:
1005 throw new IllegalStateException("Unsupported layout mode.");
Jeff Sharkey20b32272013-09-03 15:25:52 -07001006 }
1007 }
1008
Steve McKayef280152015-06-11 10:10:49 -07001009 @Override
1010 public void onBindViewHolder(DocumentHolder holder, int position) {
1011
1012 final Context context = getContext();
Jeff Sharkeyb3620442013-09-01 18:41:04 -07001013 final State state = getDisplayState(DirectoryFragment.this);
Jeff Sharkey9656a532013-09-13 13:42:19 -07001014 final DocumentInfo doc = getArguments().getParcelable(EXTRA_DOC);
Jeff Sharkey873daa32013-08-18 17:38:20 -07001015 final RootsCache roots = DocumentsApplication.getRootsCache(context);
1016 final ThumbnailCache thumbs = DocumentsApplication.getThumbnailsCache(
1017 context, mThumbSize);
1018
Ben Kwa24be5d32015-08-27 16:04:46 -07001019 final Cursor cursor = mModel.getItem(position);
Steve McKayef280152015-06-11 10:10:49 -07001020 checkNotNull(cursor, "Cursor cannot be null.");
Jeff Sharkeyac9e6272013-08-31 21:27:44 -07001021
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -07001022 final String docAuthority = getCursorString(cursor, RootCursorWrapper.COLUMN_AUTHORITY);
1023 final String docRootId = getCursorString(cursor, RootCursorWrapper.COLUMN_ROOT_ID);
Jeff Sharkeyac9e6272013-08-31 21:27:44 -07001024 final String docId = getCursorString(cursor, Document.COLUMN_DOCUMENT_ID);
1025 final String docMimeType = getCursorString(cursor, Document.COLUMN_MIME_TYPE);
1026 final String docDisplayName = getCursorString(cursor, Document.COLUMN_DISPLAY_NAME);
1027 final long docLastModified = getCursorLong(cursor, Document.COLUMN_LAST_MODIFIED);
1028 final int docIcon = getCursorInt(cursor, Document.COLUMN_ICON);
1029 final int docFlags = getCursorInt(cursor, Document.COLUMN_FLAGS);
1030 final String docSummary = getCursorString(cursor, Document.COLUMN_SUMMARY);
1031 final long docSize = getCursorLong(cursor, Document.COLUMN_SIZE);
Jeff Sharkeye22d02e2013-04-26 16:54:55 -07001032
Steve McKayef280152015-06-11 10:10:49 -07001033 holder.docId = docId;
1034 final View itemView = holder.view;
Ben Kwa24be5d32015-08-27 16:04:46 -07001035 itemView.setActivated(mModel.isSelected(position));
Jeff Sharkey9656a532013-09-13 13:42:19 -07001036
Steve McKayef280152015-06-11 10:10:49 -07001037 final View line1 = itemView.findViewById(R.id.line1);
1038 final View line2 = itemView.findViewById(R.id.line2);
1039
1040 final ImageView iconMime = (ImageView) itemView.findViewById(R.id.icon_mime);
1041 final ImageView iconThumb = (ImageView) itemView.findViewById(R.id.icon_thumb);
1042 final TextView title = (TextView) itemView.findViewById(android.R.id.title);
1043 final ImageView icon1 = (ImageView) itemView.findViewById(android.R.id.icon1);
1044 final ImageView icon2 = (ImageView) itemView.findViewById(android.R.id.icon2);
1045 final TextView summary = (TextView) itemView.findViewById(android.R.id.summary);
1046 final TextView date = (TextView) itemView.findViewById(R.id.date);
1047 final TextView size = (TextView) itemView.findViewById(R.id.size);
Jeff Sharkeye22d02e2013-04-26 16:54:55 -07001048
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -07001049 final ThumbnailAsyncTask oldTask = (ThumbnailAsyncTask) iconThumb.getTag();
Jeff Sharkey8a8fb672013-05-07 12:41:33 -07001050 if (oldTask != null) {
Jeff Sharkey753a3ae2013-10-22 17:09:44 -07001051 oldTask.preempt();
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -07001052 iconThumb.setTag(null);
Jeff Sharkey8a8fb672013-05-07 12:41:33 -07001053 }
1054
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -07001055 iconMime.animate().cancel();
1056 iconThumb.animate().cancel();
1057
Jeff Sharkeyaed873d2013-09-09 16:51:06 -07001058 final boolean supportsThumbnail = (docFlags & Document.FLAG_SUPPORTS_THUMBNAIL) != 0;
Jeff Sharkeyd10f0492013-09-09 17:35:46 -07001059 final boolean allowThumbnail = (state.derivedMode == MODE_GRID)
Jeff Sharkey9656a532013-09-13 13:42:19 -07001060 || MimePredicate.mimeMatches(MimePredicate.VISUAL_MIMES, docMimeType);
Jeff Sharkeyf63b7772013-10-01 17:57:41 -07001061 final boolean showThumbnail = supportsThumbnail && allowThumbnail && !mSvelteRecents;
Jeff Sharkeyaed873d2013-09-09 16:51:06 -07001062
Jeff Sharkey7e544612014-08-29 15:38:27 -07001063 final boolean enabled = isDocumentEnabled(docMimeType, docFlags);
1064 final float iconAlpha = (state.derivedMode == MODE_LIST && !enabled) ? 0.5f : 1f;
1065
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -07001066 boolean cacheHit = false;
Jeff Sharkey9656a532013-09-13 13:42:19 -07001067 if (showThumbnail) {
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -07001068 final Uri uri = DocumentsContract.buildDocumentUri(docAuthority, docId);
Jeff Sharkeyac9e6272013-08-31 21:27:44 -07001069 final Bitmap cachedResult = thumbs.get(uri);
Jeff Sharkey8a8fb672013-05-07 12:41:33 -07001070 if (cachedResult != null) {
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -07001071 iconThumb.setImageBitmap(cachedResult);
1072 cacheHit = true;
Jeff Sharkey8a8fb672013-05-07 12:41:33 -07001073 } else {
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -07001074 iconThumb.setImageDrawable(null);
Steve McKayef280152015-06-11 10:10:49 -07001075 // TODO: Hang this off DocumentHolder?
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -07001076 final ThumbnailAsyncTask task = new ThumbnailAsyncTask(
Jeff Sharkey7e544612014-08-29 15:38:27 -07001077 uri, iconMime, iconThumb, mThumbSize, iconAlpha);
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -07001078 iconThumb.setTag(task);
Jeff Sharkey753a3ae2013-10-22 17:09:44 -07001079 ProviderExecutor.forAuthority(docAuthority).execute(task);
Jeff Sharkey8a8fb672013-05-07 12:41:33 -07001080 }
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -07001081 }
1082
1083 // Always throw MIME icon into place, even when a thumbnail is being
1084 // loaded in background.
1085 if (cacheHit) {
1086 iconMime.setAlpha(0f);
Jeff Sharkey9dd02622013-09-27 16:44:11 -07001087 iconMime.setImageDrawable(null);
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -07001088 iconThumb.setAlpha(1f);
Jeff Sharkeye22d02e2013-04-26 16:54:55 -07001089 } else {
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -07001090 iconMime.setAlpha(1f);
1091 iconThumb.setAlpha(0f);
Jeff Sharkey9dd02622013-09-27 16:44:11 -07001092 iconThumb.setImageDrawable(null);
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001093 iconMime.setImageDrawable(
Steve McKayef280152015-06-11 10:10:49 -07001094 getDocumentIcon(mContext, docAuthority, docId, docMimeType, docIcon, state));
Jeff Sharkeye22d02e2013-04-26 16:54:55 -07001095 }
1096
Jeff Sharkey9656a532013-09-13 13:42:19 -07001097 boolean hasLine1 = false;
Jeff Sharkey42d26792013-09-06 13:22:09 -07001098 boolean hasLine2 = false;
1099
Jeff Sharkey9656a532013-09-13 13:42:19 -07001100 final boolean hideTitle = (state.derivedMode == MODE_GRID) && mHideGridTitles;
1101 if (!hideTitle) {
1102 title.setText(docDisplayName);
1103 hasLine1 = true;
1104 }
1105
1106 Drawable iconDrawable = null;
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -07001107 if (mType == TYPE_RECENT_OPEN) {
Jeff Sharkey8b997042013-09-19 15:25:56 -07001108 // We've already had to enumerate roots before any results can
1109 // be shown, so this will never block.
1110 final RootInfo root = roots.getRootBlocking(docAuthority, docRootId);
Jeff Sharkey93cdbc22014-07-29 17:33:36 -07001111 if (state.derivedMode == MODE_GRID) {
Steve McKayef280152015-06-11 10:10:49 -07001112 iconDrawable = root.loadGridIcon(mContext);
Jeff Sharkey93cdbc22014-07-29 17:33:36 -07001113 } else {
Steve McKayef280152015-06-11 10:10:49 -07001114 iconDrawable = root.loadIcon(mContext);
Jeff Sharkey93cdbc22014-07-29 17:33:36 -07001115 }
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -07001116
Jeff Sharkey7d58fc62013-09-12 16:25:02 -07001117 if (summary != null) {
1118 final boolean alwaysShowSummary = getResources()
1119 .getBoolean(R.bool.always_show_summary);
1120 if (alwaysShowSummary) {
1121 summary.setText(root.getDirectoryString());
1122 summary.setVisibility(View.VISIBLE);
1123 hasLine2 = true;
1124 } else {
Jeff Sharkey8b997042013-09-19 15:25:56 -07001125 if (iconDrawable != null && roots.isIconUniqueBlocking(root)) {
Jeff Sharkey7d58fc62013-09-12 16:25:02 -07001126 // No summary needed if icon speaks for itself
1127 summary.setVisibility(View.INVISIBLE);
1128 } else {
1129 summary.setText(root.getDirectoryString());
1130 summary.setVisibility(View.VISIBLE);
1131 summary.setTextAlignment(TextView.TEXT_ALIGNMENT_TEXT_END);
1132 hasLine2 = true;
1133 }
1134 }
Jeff Sharkeya35ac2d2013-09-10 12:04:26 -07001135 }
Jeff Sharkeyac9e6272013-08-31 21:27:44 -07001136 } else {
Jeff Sharkey9656a532013-09-13 13:42:19 -07001137 // Directories showing thumbnails in grid mode get a little icon
1138 // hint to remind user they're a directory.
1139 if (Document.MIME_TYPE_DIR.equals(docMimeType) && state.derivedMode == MODE_GRID
1140 && showThumbnail) {
Steve McKayef280152015-06-11 10:10:49 -07001141 iconDrawable = IconUtils.applyTintAttr(mContext, R.drawable.ic_doc_folder,
Jeff Sharkey34c54092014-08-08 13:08:56 -07001142 android.R.attr.textColorPrimaryInverse);
Jeff Sharkey9656a532013-09-13 13:42:19 -07001143 }
1144
Jeff Sharkey7d58fc62013-09-12 16:25:02 -07001145 if (summary != null) {
1146 if (docSummary != null) {
1147 summary.setText(docSummary);
1148 summary.setVisibility(View.VISIBLE);
1149 hasLine2 = true;
1150 } else {
1151 summary.setVisibility(View.INVISIBLE);
1152 }
Jeff Sharkeyd82b26b2013-09-02 15:07:28 -07001153 }
Jeff Sharkey2e694f82013-08-06 16:26:14 -07001154 }
1155
Jeff Sharkey9656a532013-09-13 13:42:19 -07001156 if (icon1 != null) icon1.setVisibility(View.GONE);
1157 if (icon2 != null) icon2.setVisibility(View.GONE);
1158
1159 if (iconDrawable != null) {
1160 if (hasLine1) {
1161 icon1.setVisibility(View.VISIBLE);
1162 icon1.setImageDrawable(iconDrawable);
1163 } else {
1164 icon2.setVisibility(View.VISIBLE);
1165 icon2.setImageDrawable(iconDrawable);
1166 }
1167 }
1168
Jeff Sharkeyac9e6272013-08-31 21:27:44 -07001169 if (docLastModified == -1) {
Jeff Sharkey8a8fb672013-05-07 12:41:33 -07001170 date.setText(null);
1171 } else {
Steve McKayef280152015-06-11 10:10:49 -07001172 date.setText(formatTime(mContext, docLastModified));
Jeff Sharkey42d26792013-09-06 13:22:09 -07001173 hasLine2 = true;
Jeff Sharkey8a8fb672013-05-07 12:41:33 -07001174 }
Jeff Sharkey2e694f82013-08-06 16:26:14 -07001175
1176 if (state.showSize) {
1177 size.setVisibility(View.VISIBLE);
Jeff Sharkeyac9e6272013-08-31 21:27:44 -07001178 if (Document.MIME_TYPE_DIR.equals(docMimeType) || docSize == -1) {
Jeff Sharkey2e694f82013-08-06 16:26:14 -07001179 size.setText(null);
1180 } else {
Steve McKayef280152015-06-11 10:10:49 -07001181 size.setText(Formatter.formatFileSize(mContext, docSize));
Jeff Sharkey42d26792013-09-06 13:22:09 -07001182 hasLine2 = true;
Jeff Sharkey2e694f82013-08-06 16:26:14 -07001183 }
1184 } else {
1185 size.setVisibility(View.GONE);
Jeff Sharkey09c10bf2013-06-30 20:02:59 -07001186 }
Jeff Sharkeya5defe32013-08-05 17:56:48 -07001187
Jeff Sharkey9656a532013-09-13 13:42:19 -07001188 if (line1 != null) {
1189 line1.setVisibility(hasLine1 ? View.VISIBLE : View.GONE);
1190 }
Jeff Sharkey7d58fc62013-09-12 16:25:02 -07001191 if (line2 != null) {
1192 line2.setVisibility(hasLine2 ? View.VISIBLE : View.GONE);
1193 }
Jeff Sharkey42d26792013-09-06 13:22:09 -07001194
Steve McKayef280152015-06-11 10:10:49 -07001195 setEnabledRecursive(itemView, enabled);
Jeff Sharkey7e544612014-08-29 15:38:27 -07001196
1197 iconMime.setAlpha(iconAlpha);
1198 iconThumb.setAlpha(iconAlpha);
1199 if (icon1 != null) icon1.setAlpha(iconAlpha);
1200 if (icon2 != null) icon2.setAlpha(iconAlpha);
Jeff Sharkeyaed873d2013-09-09 16:51:06 -07001201
Steve McKay8e258c62015-05-06 14:27:57 -07001202 if (DEBUG_ENABLE_DND) {
Steve McKayef280152015-06-11 10:10:49 -07001203 setupDragAndDropOnDocumentView(itemView, cursor);
Steve McKay8e258c62015-05-06 14:27:57 -07001204 }
Jeff Sharkeye22d02e2013-04-26 16:54:55 -07001205 }
Jeff Sharkey09c10bf2013-06-30 20:02:59 -07001206
Steve McKay351a7492015-08-04 10:11:01 -07001207 @Override
Steve McKayef280152015-06-11 10:10:49 -07001208 public int getItemCount() {
Ben Kwa24be5d32015-08-27 16:04:46 -07001209 return mModel.getItemCount();
Steve McKayef280152015-06-11 10:10:49 -07001210 // return mCursorCount + mFooters.size();
Jeff Sharkeyaed873d2013-09-09 16:51:06 -07001211 }
1212
1213 @Override
Jeff Sharkey20b32272013-09-03 15:25:52 -07001214 public int getItemViewType(int position) {
Ben Kwa24be5d32015-08-27 16:04:46 -07001215 final int itemCount = mModel.getItemCount();
1216 if (position < itemCount) {
Jeff Sharkey20b32272013-09-03 15:25:52 -07001217 return 0;
1218 } else {
Ben Kwa24be5d32015-08-27 16:04:46 -07001219 position -= itemCount;
Jeff Sharkeyaed873d2013-09-09 16:51:06 -07001220 return mFooters.get(position).getItemViewType();
Jeff Sharkey20b32272013-09-03 15:25:52 -07001221 }
1222 }
Jeff Sharkey8a8fb672013-05-07 12:41:33 -07001223 }
1224
1225 private static String formatTime(Context context, long when) {
1226 // TODO: DateUtils should make this easier
1227 Time then = new Time();
1228 then.set(when);
1229 Time now = new Time();
1230 now.setToNow();
1231
1232 int flags = DateUtils.FORMAT_NO_NOON | DateUtils.FORMAT_NO_MIDNIGHT
1233 | DateUtils.FORMAT_ABBREV_ALL;
1234
1235 if (then.year != now.year) {
1236 flags |= DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_DATE;
1237 } else if (then.yearDay != now.yearDay) {
1238 flags |= DateUtils.FORMAT_SHOW_DATE;
1239 } else {
1240 flags |= DateUtils.FORMAT_SHOW_TIME;
1241 }
1242
1243 return DateUtils.formatDateTime(context, when, flags);
1244 }
Jeff Sharkeyb3620442013-09-01 18:41:04 -07001245
1246 private String findCommonMimeType(List<String> mimeTypes) {
1247 String[] commonType = mimeTypes.get(0).split("/");
1248 if (commonType.length != 2) {
1249 return "*/*";
1250 }
1251
1252 for (int i = 1; i < mimeTypes.size(); i++) {
1253 String[] type = mimeTypes.get(i).split("/");
1254 if (type.length != 2) continue;
1255
1256 if (!commonType[1].equals(type[1])) {
1257 commonType[1] = "*";
1258 }
1259
1260 if (!commonType[0].equals(type[0])) {
1261 commonType[0] = "*";
1262 commonType[1] = "*";
1263 break;
1264 }
1265 }
1266
1267 return commonType[0] + "/" + commonType[1];
1268 }
Jeff Sharkeyaed873d2013-09-09 16:51:06 -07001269
1270 private void setEnabledRecursive(View v, boolean enabled) {
Jeff Sharkey9656a532013-09-13 13:42:19 -07001271 if (v == null) return;
Jeff Sharkeyaed873d2013-09-09 16:51:06 -07001272 if (v.isEnabled() == enabled) return;
1273 v.setEnabled(enabled);
1274
1275 if (v instanceof ViewGroup) {
1276 final ViewGroup vg = (ViewGroup) v;
1277 for (int i = vg.getChildCount() - 1; i >= 0; i--) {
1278 setEnabledRecursive(vg.getChildAt(i), enabled);
1279 }
1280 }
1281 }
Jeff Sharkey7cf49032013-09-26 10:54:16 -07001282
1283 private boolean isDocumentEnabled(String docMimeType, int docFlags) {
1284 final State state = getDisplayState(DirectoryFragment.this);
1285
Jeff Sharkey7cf49032013-09-26 10:54:16 -07001286 // Directories are always enabled
1287 if (Document.MIME_TYPE_DIR.equals(docMimeType)) {
1288 return true;
1289 }
1290
Jeff Sharkey783ebc22013-09-26 19:42:52 -07001291 // Read-only files are disabled when creating
1292 if (state.action == ACTION_CREATE && (docFlags & Document.FLAG_SUPPORTS_WRITE) == 0) {
1293 return false;
1294 }
1295
Jeff Sharkey7cf49032013-09-26 10:54:16 -07001296 return MimePredicate.mimeMatches(state.acceptMimes, docMimeType);
1297 }
Vladislav Kaznacheev89b90332015-05-01 13:46:57 -07001298
Steve McKay1f199482015-05-20 15:58:42 -07001299 private void copyFromClipboard() {
1300 new AsyncTask<Void, Void, List<DocumentInfo>>() {
1301
1302 @Override
1303 protected List<DocumentInfo> doInBackground(Void... params) {
1304 return mClipper.getClippedDocuments();
1305 }
1306
1307 @Override
1308 protected void onPostExecute(List<DocumentInfo> docs) {
1309 DocumentInfo destination =
1310 ((BaseActivity) getActivity()).getCurrentDirectory();
1311 copyDocuments(docs, destination);
1312 }
1313 }.execute();
Steve McKay0599a442015-05-05 14:50:00 -07001314 }
1315
Steve McKay1f199482015-05-20 15:58:42 -07001316 private void copyFromClipData(final ClipData clipData, final DocumentInfo destination) {
Steve McKayef280152015-06-11 10:10:49 -07001317 checkNotNull(clipData);
Steve McKay1f199482015-05-20 15:58:42 -07001318 new AsyncTask<Void, Void, List<DocumentInfo>>() {
Vladislav Kaznacheev89b90332015-05-01 13:46:57 -07001319
Steve McKay1f199482015-05-20 15:58:42 -07001320 @Override
1321 protected List<DocumentInfo> doInBackground(Void... params) {
1322 return mClipper.getDocumentsFromClipData(clipData);
1323 }
1324
1325 @Override
1326 protected void onPostExecute(List<DocumentInfo> docs) {
1327 copyDocuments(docs, destination);
1328 }
1329 }.execute();
1330 }
1331
1332 private void copyDocuments(final List<DocumentInfo> docs, final DocumentInfo destination) {
1333 if (!canCopy(docs, destination)) {
1334 Toast.makeText(
1335 getActivity(),
1336 R.string.clipboard_files_cannot_paste, Toast.LENGTH_SHORT).show();
Steve McKay0599a442015-05-05 14:50:00 -07001337 return;
1338 }
1339
Steve McKay1f199482015-05-20 15:58:42 -07001340 if (docs.isEmpty()) {
Vladislav Kaznacheev89b90332015-05-01 13:46:57 -07001341 return;
Vladislav Kaznacheeve16887a2015-05-05 12:09:47 -07001342 }
Vladislav Kaznacheev89b90332015-05-01 13:46:57 -07001343
Steve McKay1f199482015-05-20 15:58:42 -07001344 final DocumentStack curStack = getDisplayState(DirectoryFragment.this).stack;
Vladislav Kaznacheev89b90332015-05-01 13:46:57 -07001345 DocumentStack tmpStack = new DocumentStack();
Steve McKay1f199482015-05-20 15:58:42 -07001346 if (destination != null) {
1347 tmpStack.push(destination);
Vladislav Kaznacheev89b90332015-05-01 13:46:57 -07001348 tmpStack.addAll(curStack);
1349 } else {
1350 tmpStack = curStack;
1351 }
1352
Steve McKay1f199482015-05-20 15:58:42 -07001353 CopyService.start(getActivity(), docs, tmpStack, CopyService.TRANSFER_MODE_COPY);
Vladislav Kaznacheev89b90332015-05-01 13:46:57 -07001354 }
1355
1356 private ClipData getClipDataFromDocuments(List<DocumentInfo> docs) {
1357 Context context = getActivity();
1358 final ContentResolver resolver = context.getContentResolver();
1359 ClipData clipData = null;
1360 for (DocumentInfo doc : docs) {
1361 final Uri uri = DocumentsContract.buildDocumentUri(doc.authority, doc.documentId);
1362 if (clipData == null) {
Vladislav Kaznacheeve16887a2015-05-05 12:09:47 -07001363 // TODO: figure out what this string should be.
1364 // Currently it is not displayed anywhere in the UI, but this might change.
1365 final String label = "";
1366 clipData = ClipData.newUri(resolver, label, uri);
Vladislav Kaznacheev89b90332015-05-01 13:46:57 -07001367 } else {
1368 // TODO: update list of mime types in ClipData.
1369 clipData.addItem(new ClipData.Item(uri));
1370 }
1371 }
1372 return clipData;
1373 }
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001374
Steve McKay1f199482015-05-20 15:58:42 -07001375 void copySelectedToClipboard() {
Ben Kwa24be5d32015-08-27 16:04:46 -07001376 Selection sel = mModel.getSelection(new Selection());
Steve McKayef280152015-06-11 10:10:49 -07001377 copySelectionToClipboard(sel);
Steve McKay9276f3b2015-05-27 16:11:42 -07001378 }
Steve McKay0599a442015-05-05 14:50:00 -07001379
Steve McKayef280152015-06-11 10:10:49 -07001380 void copySelectionToClipboard(Selection items) {
Steve McKay9276f3b2015-05-27 16:11:42 -07001381 new GetDocumentsTask() {
1382 @Override
1383 void onDocumentsReady(List<DocumentInfo> docs) {
1384 mClipper.clipDocuments(docs);
Steve McKay1f199482015-05-20 15:58:42 -07001385 Activity activity = getActivity();
1386 Toast.makeText(activity,
1387 activity.getResources().getQuantityString(
1388 R.plurals.clipboard_files_clipped, docs.size(), docs.size()),
1389 Toast.LENGTH_SHORT).show();
Steve McKay9276f3b2015-05-27 16:11:42 -07001390 }
Steve McKayef280152015-06-11 10:10:49 -07001391 }.execute(items);
Steve McKay0599a442015-05-05 14:50:00 -07001392 }
1393
1394 void pasteFromClipboard() {
Steve McKay1f199482015-05-20 15:58:42 -07001395 copyFromClipboard();
1396 getActivity().invalidateOptionsMenu();
Steve McKay0599a442015-05-05 14:50:00 -07001397 }
1398
Steve McKay0599a442015-05-05 14:50:00 -07001399 /**
1400 * Returns true if the list of files can be copied to destination. Note that this
1401 * is a policy check only. Currently the method does not attempt to verify
1402 * available space or any other environmental aspects possibly resulting in
1403 * failure to copy.
1404 *
1405 * @return true if the list of files can be copied to destination.
1406 */
1407 boolean canCopy(List<DocumentInfo> files, DocumentInfo dest) {
1408 BaseActivity activity = (BaseActivity)getActivity();
1409
1410 final RootInfo root = activity.getCurrentRoot();
1411
1412 // Can't copy folders to Downloads.
1413 if (root.isDownloads()) {
1414 for (DocumentInfo docs : files) {
1415 if (docs.isDirectory()) {
1416 return false;
1417 }
1418 }
1419 }
1420
1421 return dest != null && dest.isDirectory() && dest.isCreateSupported();
1422 }
1423
1424 void selectAllFiles() {
Ben Kwa24be5d32015-08-27 16:04:46 -07001425 boolean changed = mModel.selectAll();
Steve McKay9459a7c2015-07-24 13:14:20 -07001426 if (changed) {
1427 updateDisplayState();
1428 }
Steve McKay0599a442015-05-05 14:50:00 -07001429 }
1430
Steve McKayef280152015-06-11 10:10:49 -07001431 private void setupDragAndDropOnDirectoryView(View view) {
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001432 // Listen for drops on non-directory items and empty space.
1433 view.setOnDragListener(mOnDragListener);
1434 }
1435
1436 private void setupDragAndDropOnDocumentView(View view, Cursor cursor) {
1437 final String docMimeType = getCursorString(cursor, Document.COLUMN_MIME_TYPE);
1438 if (Document.MIME_TYPE_DIR.equals(docMimeType)) {
1439 // Make a directory item a drop target. Drop on non-directories and empty space
1440 // is handled at the list/grid view level.
1441 view.setOnDragListener(mOnDragListener);
1442 }
1443
1444 // Temporary: attaching the listener to the title only.
1445 // Attaching to the entire item conflicts with the item long click handler responsible
1446 // for item selection.
1447 final View title = view.findViewById(android.R.id.title);
1448 title.setOnLongClickListener(mLongClickListener);
1449 }
1450
1451 private View.OnDragListener mOnDragListener = new View.OnDragListener() {
1452 @Override
1453 public boolean onDrag(View v, DragEvent event) {
1454 switch (event.getAction()) {
1455 case DragEvent.ACTION_DRAG_STARTED:
1456 // TODO: Check if the event contains droppable data.
1457 return true;
1458
1459 // TODO: Highlight potential drop target directory?
1460 // TODO: Expand drop target directory on hover?
1461 case DragEvent.ACTION_DRAG_ENTERED:
1462 case DragEvent.ACTION_DRAG_LOCATION:
1463 case DragEvent.ACTION_DRAG_EXITED:
1464 case DragEvent.ACTION_DRAG_ENDED:
1465 return true;
1466
1467 case DragEvent.ACTION_DROP:
Steve McKayef280152015-06-11 10:10:49 -07001468 int dstPosition = mRecView.getChildAdapterPosition(v);
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001469 DocumentInfo dstDir = null;
1470 if (dstPosition != android.widget.AdapterView.INVALID_POSITION) {
Ben Kwa24be5d32015-08-27 16:04:46 -07001471 Cursor dstCursor = mModel.getItem(dstPosition);
Steve McKayef280152015-06-11 10:10:49 -07001472 checkNotNull(dstCursor, "Cursor cannot be null.");
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001473 dstDir = DocumentInfo.fromDirectoryCursor(dstCursor);
1474 // TODO: Do not drop into the directory where the documents came from.
1475 }
1476 copyFromClipData(event.getClipData(), dstDir);
1477 return true;
1478 }
1479 return false;
1480 }
1481 };
1482
1483 private View.OnLongClickListener mLongClickListener = new View.OnLongClickListener() {
1484 @Override
1485 public boolean onLongClick(View v) {
1486 final List<DocumentInfo> docs = getDraggableDocuments(v);
1487 if (docs.isEmpty()) {
1488 return false;
1489 }
1490 v.startDrag(
1491 getClipDataFromDocuments(docs),
1492 new DrawableShadowBuilder(getDragShadowIcon(docs)),
1493 null,
1494 View.DRAG_FLAG_GLOBAL
1495 );
1496 return true;
1497 }
1498 };
1499
1500 private List<DocumentInfo> getDraggableDocuments(View currentItemView) {
Steve McKayef280152015-06-11 10:10:49 -07001501 int position = mRecView.getChildAdapterPosition(currentItemView);
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001502 if (position == android.widget.AdapterView.INVALID_POSITION) {
1503 return Collections.EMPTY_LIST;
1504 }
1505
Ben Kwa24be5d32015-08-27 16:04:46 -07001506 final List<DocumentInfo> selectedDocs = mModel.getSelectedDocuments();
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001507 if (!selectedDocs.isEmpty()) {
Ben Kwa24be5d32015-08-27 16:04:46 -07001508 if (!mModel.isSelected(position)) {
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001509 // There is a selection that does not include the current item, drag nothing.
1510 return Collections.EMPTY_LIST;
1511 }
1512 return selectedDocs;
1513 }
1514
Ben Kwa24be5d32015-08-27 16:04:46 -07001515 final Cursor cursor = mModel.getItem(position);
Steve McKayef280152015-06-11 10:10:49 -07001516 checkNotNull(cursor, "Cursor cannot be null.");
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001517 final DocumentInfo doc = DocumentInfo.fromDirectoryCursor(cursor);
Steve McKayfefcd702015-08-20 16:19:38 +00001518
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001519 return Lists.newArrayList(doc);
1520 }
1521
1522 private Drawable getDragShadowIcon(List<DocumentInfo> docs) {
1523 if (docs.size() == 1) {
1524 final DocumentInfo doc = docs.get(0);
1525 return getDocumentIcon(getActivity(), doc.authority, doc.documentId,
1526 doc.mimeType, doc.icon, getDisplayState(this));
1527 }
1528 return getActivity().getDrawable(R.drawable.ic_doc_generic);
1529 }
1530
1531 public static Drawable getDocumentIcon(Context context, String docAuthority, String docId,
1532 String docMimeType, int docIcon, State state) {
1533 if (docIcon != 0) {
1534 return IconUtils.loadPackageIcon(context, docAuthority, docIcon);
1535 } else {
1536 return IconUtils.loadMimeIcon(context, docMimeType, docAuthority, docId,
1537 state.derivedMode);
1538 }
1539 }
1540
Steve McKayef280152015-06-11 10:10:49 -07001541 private static class ThumbnailAsyncTask extends AsyncTask<Uri, Void, Bitmap>
1542 implements Preemptable {
1543 private final Uri mUri;
1544 private final ImageView mIconMime;
1545 private final ImageView mIconThumb;
1546 private final Point mThumbSize;
1547 private final float mTargetAlpha;
1548 private final CancellationSignal mSignal;
1549
1550 public ThumbnailAsyncTask(Uri uri, ImageView iconMime, ImageView iconThumb, Point thumbSize,
1551 float targetAlpha) {
1552 mUri = uri;
1553 mIconMime = iconMime;
1554 mIconThumb = iconThumb;
1555 mThumbSize = thumbSize;
1556 mTargetAlpha = targetAlpha;
1557 mSignal = new CancellationSignal();
1558 }
1559
1560 @Override
1561 public void preempt() {
1562 cancel(false);
1563 mSignal.cancel();
1564 }
1565
1566 @Override
1567 protected Bitmap doInBackground(Uri... params) {
1568 if (isCancelled()) return null;
1569
1570 final Context context = mIconThumb.getContext();
1571 final ContentResolver resolver = context.getContentResolver();
1572
1573 ContentProviderClient client = null;
1574 Bitmap result = null;
1575 try {
1576 client = DocumentsApplication.acquireUnstableProviderOrThrow(
1577 resolver, mUri.getAuthority());
1578 result = DocumentsContract.getDocumentThumbnail(client, mUri, mThumbSize, mSignal);
1579 if (result != null) {
1580 final ThumbnailCache thumbs = DocumentsApplication.getThumbnailsCache(
1581 context, mThumbSize);
1582 thumbs.put(mUri, result);
1583 }
1584 } catch (Exception e) {
1585 if (!(e instanceof OperationCanceledException)) {
1586 Log.w(TAG, "Failed to load thumbnail for " + mUri + ": " + e);
1587 }
1588 } finally {
1589 ContentProviderClient.releaseQuietly(client);
1590 }
1591 return result;
1592 }
1593
1594 @Override
1595 protected void onPostExecute(Bitmap result) {
1596 if (mIconThumb.getTag() == this && result != null) {
1597 mIconThumb.setTag(null);
1598 mIconThumb.setImageBitmap(result);
1599
1600 mIconMime.setAlpha(mTargetAlpha);
1601 mIconMime.animate().alpha(0f).start();
1602 mIconThumb.setAlpha(0f);
1603 mIconThumb.animate().alpha(mTargetAlpha).start();
1604 }
1605 }
1606 }
1607
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001608 private class DrawableShadowBuilder extends View.DragShadowBuilder {
1609
1610 private final Drawable mShadow;
1611
1612 private final int mShadowDimension;
1613
1614 public DrawableShadowBuilder(Drawable shadow) {
1615 mShadow = shadow;
1616 mShadowDimension = getResources().getDimensionPixelSize(
1617 R.dimen.drag_shadow_size);
1618 mShadow.setBounds(0, 0, mShadowDimension, mShadowDimension);
1619 }
1620
Ben Kwa24be5d32015-08-27 16:04:46 -07001621 @Override
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001622 public void onProvideShadowMetrics(
1623 Point shadowSize, Point shadowTouchPoint) {
1624 shadowSize.set(mShadowDimension, mShadowDimension);
1625 shadowTouchPoint.set(mShadowDimension / 2, mShadowDimension / 2);
1626 }
1627
Ben Kwa24be5d32015-08-27 16:04:46 -07001628 @Override
Vladislav Kaznacheevb6da7222015-05-01 14:18:57 -07001629 public void onDrawShadow(Canvas canvas) {
1630 mShadow.draw(canvas);
1631 }
1632 }
Steve McKay1f199482015-05-20 15:58:42 -07001633
1634 private FragmentTuner pickFragmentTuner(final State state) {
1635 return state.action == ACTION_BROWSE_ALL
Steve McKay0fbfc652015-08-20 16:48:49 -07001636 ? new FilesTuner()
Steve McKay1f199482015-05-20 15:58:42 -07001637 : new DefaultTuner(state);
1638 }
1639
1640 /**
1641 * Interface for specializing the Fragment for the "host" Activity.
1642 * Feel free to expand the role of this class to handle other specializations.
1643 */
1644 private interface FragmentTuner {
Steve McKay4f4232d2015-07-22 12:13:46 -07001645 void updateActionMenu(Menu menu, int dirType, boolean canDelete);
Kyle Horimoto426bd0d2015-07-29 15:33:49 -07001646 void afterActivityCreated(DirectoryFragment fragment);
Steve McKay1f199482015-05-20 15:58:42 -07001647 }
1648
1649 /**
Steve McKay9276f3b2015-05-27 16:11:42 -07001650 * Abstract task providing support for loading documents *off*
1651 * the main thread. And if it isn't obvious, creating a list
1652 * of documents (especially large lists) can be pretty expensive.
1653 */
1654 private abstract class GetDocumentsTask
Steve McKayef280152015-06-11 10:10:49 -07001655 extends AsyncTask<Selection, Void, List<DocumentInfo>> {
Steve McKay9276f3b2015-05-27 16:11:42 -07001656 @Override
Steve McKayef280152015-06-11 10:10:49 -07001657 protected final List<DocumentInfo> doInBackground(Selection... selected) {
Ben Kwa24be5d32015-08-27 16:04:46 -07001658 return mModel.getDocuments(selected[0]);
Steve McKay9276f3b2015-05-27 16:11:42 -07001659 }
1660
1661 @Override
1662 protected final void onPostExecute(List<DocumentInfo> docs) {
1663 onDocumentsReady(docs);
1664 }
1665
1666 abstract void onDocumentsReady(List<DocumentInfo> docs);
1667 }
1668
1669 /**
Steve McKay1f199482015-05-20 15:58:42 -07001670 * Provides support for Platform specific specializations of DirectoryFragment.
1671 */
1672 private static final class DefaultTuner implements FragmentTuner {
1673
1674 private final State mState;
1675
1676 public DefaultTuner(State state) {
1677 mState = state;
1678 }
1679
1680 @Override
Steve McKay4f4232d2015-07-22 12:13:46 -07001681 public void updateActionMenu(Menu menu, int dirType, boolean canDelete) {
Steve McKay1f199482015-05-20 15:58:42 -07001682 Preconditions.checkState(mState.action != ACTION_BROWSE_ALL);
1683
1684 final MenuItem open = menu.findItem(R.id.menu_open);
1685 final MenuItem share = menu.findItem(R.id.menu_share);
1686 final MenuItem delete = menu.findItem(R.id.menu_delete);
1687 final MenuItem copyTo = menu.findItem(R.id.menu_copy_to);
1688 final MenuItem moveTo = menu.findItem(R.id.menu_move_to);
1689 final MenuItem copyToClipboard = menu.findItem(R.id.menu_copy_to_clipboard);
1690
1691 final boolean manageOrBrowse = (mState.action == ACTION_MANAGE
1692 || mState.action == ACTION_BROWSE);
1693
1694 open.setVisible(!manageOrBrowse);
1695 share.setVisible(manageOrBrowse);
Steve McKay4f4232d2015-07-22 12:13:46 -07001696 delete.setVisible(manageOrBrowse && canDelete);
Steve McKay1f199482015-05-20 15:58:42 -07001697 // Disable copying from the Recents view.
1698 copyTo.setVisible(manageOrBrowse && dirType != TYPE_RECENT_OPEN);
1699 moveTo.setVisible(SystemProperties.getBoolean("debug.documentsui.enable_move", false));
1700
Steve McKay0fbfc652015-08-20 16:48:49 -07001701 // Only shown in files mode.
Steve McKay1f199482015-05-20 15:58:42 -07001702 copyToClipboard.setVisible(false);
1703 }
Kyle Horimoto426bd0d2015-07-29 15:33:49 -07001704
1705 @Override
1706 public void afterActivityCreated(DirectoryFragment fragment) {}
Steve McKay1f199482015-05-20 15:58:42 -07001707 }
1708
1709 /**
Steve McKay0fbfc652015-08-20 16:48:49 -07001710 * Provides support for Files activity specific specializations of DirectoryFragment.
Steve McKay1f199482015-05-20 15:58:42 -07001711 */
Steve McKay0fbfc652015-08-20 16:48:49 -07001712 private static final class FilesTuner implements FragmentTuner {
Steve McKay1f199482015-05-20 15:58:42 -07001713 @Override
Steve McKay4f4232d2015-07-22 12:13:46 -07001714 public void updateActionMenu(Menu menu, int dirType, boolean canDelete) {
Steve McKay1f199482015-05-20 15:58:42 -07001715 menu.findItem(R.id.menu_share).setVisible(true);
Steve McKay4f4232d2015-07-22 12:13:46 -07001716 menu.findItem(R.id.menu_delete).setVisible(canDelete);
Steve McKay1f199482015-05-20 15:58:42 -07001717 menu.findItem(R.id.menu_copy_to_clipboard).setVisible(true);
1718
1719 menu.findItem(R.id.menu_open).setVisible(false);
1720 menu.findItem(R.id.menu_copy_to).setVisible(false);
1721 menu.findItem(R.id.menu_move_to).setVisible(false);
1722 }
Kyle Horimoto426bd0d2015-07-29 15:33:49 -07001723
1724 @Override
Kyle Horimoto62a7fd02015-08-18 13:25:29 -07001725 public void afterActivityCreated(DirectoryFragment fragment) {}
Steve McKay1f199482015-05-20 15:58:42 -07001726 }
Ben Kwa24be5d32015-08-27 16:04:46 -07001727
1728 /**
1729 * The data model for the current loaded directory.
1730 */
1731 private final class Model implements DocumentContext {
1732 private MultiSelectManager mSelectionManager;
1733 private int mCursorCount;
1734 private boolean mIsLoading;
1735 @Nullable private Cursor mCursor;
1736 @Nullable private String info;
1737 @Nullable private String error;
1738
1739 /**
1740 * Sets the selection manager used by the model.
1741 * TODO: the model should instantiate the selection manager. See onActivityCreated.
1742 */
1743 void setSelectionManager(MultiSelectManager mgr) {
1744 mSelectionManager = mgr;
1745 }
1746
1747 /**
1748 * Selects all files in the current directory.
1749 * @return true if the selection state changed for any files.
1750 */
1751 boolean selectAll() {
1752 return mSelectionManager.setItemsSelected(0, mCursorCount, true);
1753 }
1754
1755 /**
1756 * Clones the current selection into the given Selection object.
1757 * @param selection
1758 * @return The selection that was passed in, for convenience.
1759 */
1760 Selection getSelection(Selection selection) {
1761 return mSelectionManager.getSelection(selection);
1762 }
1763
1764 /**
1765 * @return The current selection (the live instance, not a copy).
1766 */
1767 Selection getSelection() {
1768 return mSelectionManager.getSelection();
1769 }
1770
1771 boolean isSelected(int position) {
1772 return mSelectionManager.getSelection().contains(position);
1773 }
1774
1775 void clearSelection() {
1776 mSelectionManager.clearSelection();
1777 }
1778
1779 void update(DirectoryResult result) {
1780 if (DEBUG) Log.i(TAG, "Updating model with new result set.");
1781
1782 if (result == null) {
1783 mCursor = null;
1784 mCursorCount = 0;
1785 info = null;
1786 error = null;
1787 mIsLoading = false;
1788 return;
1789 }
1790
1791 if (result.exception != null) {
1792 Log.e(TAG, "Error while loading directory contents", result.exception);
1793 error = getString(R.string.query_error);
1794 return;
1795 }
1796
1797 mCursor = result.cursor;
1798 mCursorCount = mCursor.getCount();
1799
1800 final Bundle extras = mCursor.getExtras();
1801 if (extras != null) {
1802 info = extras.getString(DocumentsContract.EXTRA_INFO);
1803 error = extras.getString(DocumentsContract.EXTRA_ERROR);
1804 mIsLoading = extras.getBoolean(DocumentsContract.EXTRA_LOADING, false);
1805 }
1806 }
1807
1808 private int getItemCount() {
1809 return mCursorCount;
1810 }
1811
1812 private Cursor getItem(int position) {
1813 if (position >= mCursorCount) {
1814 throw new IndexOutOfBoundsException("Attempt to retrieve " + position + " of " +
1815 mCursorCount + " items");
1816 }
1817
1818 mCursor.moveToPosition(position);
1819 return mCursor;
1820 }
1821
1822 private boolean isEmpty() {
1823 return mCursorCount == 0;
1824 }
1825
1826 private boolean isLoading() {
1827 return mIsLoading;
1828 }
1829
1830 private List<DocumentInfo> getSelectedDocuments() {
1831 Selection sel = getSelection(new Selection());
1832 return getDocuments(sel);
1833 }
1834
1835 private List<DocumentInfo> getDocuments(Selection items) {
1836 if (items == null || items.size() == 0) {
1837 return new ArrayList<>(0);
1838 }
1839
1840 final List<DocumentInfo> docs = new ArrayList<>(items.size());
1841 final int size = items.size();
1842 for (int i = 0; i < size; i++) {
1843 final Cursor cursor = getItem(items.get(i));
1844 checkNotNull(cursor, "Cursor cannot be null.");
1845 final DocumentInfo doc = DocumentInfo.fromDirectoryCursor(cursor);
1846 docs.add(doc);
1847 }
1848 return docs;
1849 }
1850
1851 @Override
1852 public Cursor getCursor() {
1853 if (Looper.myLooper() != Looper.getMainLooper()) {
1854 throw new IllegalStateException("Can't call getCursor from non-main thread.");
1855 }
1856 return mCursor;
1857 }
1858 }
Jeff Sharkeye22d02e2013-04-26 16:54:55 -07001859}