blob: dfceff8d22b07fb88e23dde74b55e41790590a4e [file] [log] [blame]
Jeff Sharkey9e0036e2013-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
Steve McKayf8621552015-11-03 15:23:16 -080017package com.android.documentsui.dirlist;
Jeff Sharkey9e0036e2013-04-26 16:54:55 -070018
Steve McKay7a3b88c2015-09-23 17:21:40 -070019import static com.android.documentsui.Shared.DEBUG;
Steve McKay7a3b88c2015-09-23 17:21:40 -070020import static com.android.documentsui.State.ACTION_MANAGE;
21import static com.android.documentsui.State.MODE_GRID;
22import static com.android.documentsui.State.MODE_LIST;
Steve McKay7a3b88c2015-09-23 17:21:40 -070023import static com.android.documentsui.State.SORT_ORDER_UNKNOWN;
Jeff Sharkey5dfb3452013-08-31 21:27:44 -070024import static com.android.documentsui.model.DocumentInfo.getCursorInt;
Jeff Sharkey5dfb3452013-08-31 21:27:44 -070025import static com.android.documentsui.model.DocumentInfo.getCursorString;
Steve McKay3da8afc2015-05-05 14:50:00 -070026
Steve McKayaa15dae2016-02-09 16:17:24 -080027import android.annotation.IntDef;
Steve McKay9ed88a42016-01-21 18:46:15 -080028import android.annotation.StringRes;
Ben Kwaef3f2622015-04-07 15:43:39 -070029import android.app.Activity;
Jeff Sharkeyd01571e2013-10-01 17:57:41 -070030import android.app.ActivityManager;
Steve McKay7a3b8112016-02-23 10:06:50 -080031import android.app.AlertDialog;
Jeff Sharkey54e55b72013-06-30 20:02:59 -070032import android.app.Fragment;
Jeff Sharkey9e0036e2013-04-26 16:54:55 -070033import android.app.FragmentManager;
34import android.app.FragmentTransaction;
Jeff Sharkey9e0036e2013-04-26 16:54:55 -070035import android.app.LoaderManager.LoaderCallbacks;
Vladislav Kaznacheev335dba52015-05-01 13:46:57 -070036import android.content.ClipData;
Jeff Sharkey9e0036e2013-04-26 16:54:55 -070037import android.content.Context;
Steve McKay7a3b8112016-02-23 10:06:50 -080038import android.content.DialogInterface;
Jeff Sharkey4eb407a2013-08-18 17:38:20 -070039import android.content.Intent;
Jeff Sharkey9e0036e2013-04-26 16:54:55 -070040import android.content.Loader;
Jeff Sharkey5dfb3452013-08-31 21:27:44 -070041import android.database.Cursor;
Vladislav Kaznacheev42a6bbc2015-05-01 14:18:57 -070042import android.graphics.Canvas;
Jeff Sharkey9d0843d2013-05-07 12:41:33 -070043import android.graphics.Point;
Jeff Sharkey4ec97392013-09-10 12:04:26 -070044import android.graphics.drawable.Drawable;
Jeff Sharkey9e0036e2013-04-26 16:54:55 -070045import android.net.Uri;
Jeff Sharkey9d0843d2013-05-07 12:41:33 -070046import android.os.AsyncTask;
Jeff Sharkey9e0036e2013-04-26 16:54:55 -070047import android.os.Bundle;
Jeff Sharkeye20a3ac2013-09-18 16:26:49 -070048import android.os.Parcelable;
Jeff Sharkey9e0036e2013-04-26 16:54:55 -070049import android.provider.DocumentsContract;
Jeff Sharkey5dfb3452013-08-31 21:27:44 -070050import android.provider.DocumentsContract.Document;
Ben Kwac64cb252015-08-27 16:04:46 -070051import android.support.annotation.Nullable;
Ben Kwa304895a2015-08-27 16:06:33 -070052import android.support.design.widget.Snackbar;
Ben Kwae3dfebf2016-02-18 16:45:45 -080053import android.support.v13.view.DragStartHelper;
Steve McKay4b3a13c2015-06-11 10:10:49 -070054import android.support.v7.widget.GridLayoutManager;
Steve McKayef16f5f2015-12-22 18:15:31 -080055import android.support.v7.widget.GridLayoutManager.SpanSizeLookup;
Steve McKay4b3a13c2015-06-11 10:10:49 -070056import android.support.v7.widget.RecyclerView;
Steve McKay669ebe72015-10-19 12:04:21 -070057import android.support.v7.widget.RecyclerView.OnItemTouchListener;
Steve McKay4b3a13c2015-06-11 10:10:49 -070058import android.support.v7.widget.RecyclerView.RecyclerListener;
59import android.support.v7.widget.RecyclerView.ViewHolder;
Jeff Sharkeyf491c722015-06-11 09:16:19 -070060import android.text.TextUtils;
Jeff Sharkey9d0843d2013-05-07 12:41:33 -070061import android.util.Log;
Jeff Sharkeye20a3ac2013-09-18 16:26:49 -070062import android.util.SparseArray;
Ben Kwa0f7078f02015-09-08 07:31:19 -070063import android.util.TypedValue;
Jeff Sharkeybe8b12e2013-07-01 16:56:54 -070064import android.view.ActionMode;
Vladislav Kaznacheev42a6bbc2015-05-01 14:18:57 -070065import android.view.DragEvent;
Steve McKay4b3a13c2015-06-11 10:10:49 -070066import android.view.GestureDetector;
Ben Kwa67924892016-01-27 09:58:36 -080067import android.view.KeyEvent;
Jeff Sharkey9e0036e2013-04-26 16:54:55 -070068import android.view.LayoutInflater;
Jeff Sharkey54e55b72013-06-30 20:02:59 -070069import android.view.Menu;
Jeff Sharkey54e55b72013-06-30 20:02:59 -070070import android.view.MenuItem;
Steve McKay4b3a13c2015-06-11 10:10:49 -070071import android.view.MotionEvent;
Jeff Sharkey9e0036e2013-04-26 16:54:55 -070072import android.view.View;
73import android.view.ViewGroup;
Jeff Sharkey9e0036e2013-04-26 16:54:55 -070074import android.widget.ImageView;
Jeff Sharkey9e0036e2013-04-26 16:54:55 -070075import android.widget.TextView;
76
Steve McKayf8621552015-11-03 15:23:16 -080077import com.android.documentsui.BaseActivity;
Steve McKayf8621552015-11-03 15:23:16 -080078import com.android.documentsui.DirectoryLoader;
79import com.android.documentsui.DirectoryResult;
80import com.android.documentsui.DocumentClipper;
81import com.android.documentsui.DocumentsActivity;
82import com.android.documentsui.DocumentsApplication;
83import com.android.documentsui.Events;
Ben Kwa0436a752016-01-15 10:43:24 -080084import com.android.documentsui.Events.MotionInputEvent;
Steve McKayf8621552015-11-03 15:23:16 -080085import com.android.documentsui.Menus;
86import com.android.documentsui.MessageBar;
87import com.android.documentsui.MimePredicate;
Steve McKayf8621552015-11-03 15:23:16 -080088import com.android.documentsui.R;
Steve McKaye2af0782016-02-18 09:48:39 -080089import com.android.documentsui.RecentsLoader;
Steve McKayf8621552015-11-03 15:23:16 -080090import com.android.documentsui.RootsCache;
91import com.android.documentsui.Shared;
92import com.android.documentsui.Snackbars;
93import com.android.documentsui.State;
Ben Kwa1e2fa5e2016-02-02 23:00:02 -080094import com.android.documentsui.State.ViewMode;
Steve McKayf8621552015-11-03 15:23:16 -080095import com.android.documentsui.dirlist.MultiSelectManager.Selection;
Jeff Sharkeyae9b51b2013-08-31 15:02:20 -070096import com.android.documentsui.model.DocumentInfo;
Tomasz Mikolajewskif8c3f322015-04-14 16:32:41 +090097import com.android.documentsui.model.DocumentStack;
Jeff Sharkey251097b2013-09-02 15:07:28 -070098import com.android.documentsui.model.RootInfo;
Steve McKay14e827a2016-01-06 18:32:13 -080099import com.android.documentsui.services.FileOperationService;
Ben Kwa1e2fa5e2016-02-02 23:00:02 -0800100import com.android.documentsui.services.FileOperationService.OpType;
Steve McKay14e827a2016-01-06 18:32:13 -0800101import com.android.documentsui.services.FileOperations;
Steve McKaya1f76802016-02-25 13:34:03 -0800102
Steve McKay58efce32015-08-20 16:19:38 +0000103import com.google.common.collect.Lists;
Jeff Sharkeybe8b12e2013-07-01 16:56:54 -0700104
Steve McKayaa15dae2016-02-09 16:17:24 -0800105import java.lang.annotation.Retention;
106import java.lang.annotation.RetentionPolicy;
Jeff Sharkeybe8b12e2013-07-01 16:56:54 -0700107import java.util.ArrayList;
Vladislav Kaznacheev42a6bbc2015-05-01 14:18:57 -0700108import java.util.Collections;
Jeff Sharkeyef7184a2013-08-05 17:56:48 -0700109import java.util.List;
Ben Kwa990489d2016-02-25 14:10:40 -0800110import java.util.Objects;
Jeff Sharkey54e55b72013-06-30 20:02:59 -0700111
112/**
113 * Display the documents inside a single directory.
114 */
Aga Wronska893390b2016-02-17 13:50:42 -0800115public class DirectoryFragment extends Fragment
116 implements DocumentsAdapter.Environment, LoaderCallbacks<DirectoryResult> {
Jeff Sharkey54e55b72013-06-30 20:02:59 -0700117
Steve McKayaa15dae2016-02-09 16:17:24 -0800118 @IntDef(flag = true, value = {
119 TYPE_NORMAL,
Steve McKayaa15dae2016-02-09 16:17:24 -0800120 TYPE_RECENT_OPEN
121 })
122 @Retention(RetentionPolicy.SOURCE)
123 public @interface ResultType {}
Jeff Sharkeyef7184a2013-08-05 17:56:48 -0700124 public static final int TYPE_NORMAL = 1;
Aga Wronska893390b2016-02-17 13:50:42 -0800125 public static final int TYPE_RECENT_OPEN = 2;
Jeff Sharkeydc2963a2013-08-02 15:55:26 -0700126
Aga Wronska893390b2016-02-17 13:50:42 -0800127 @IntDef(flag = true, value = {
128 ANIM_NONE,
129 ANIM_SIDE,
130 ANIM_LEAVE,
131 ANIM_ENTER
132 })
133 @Retention(RetentionPolicy.SOURCE)
134 public @interface AnimationType {}
Jeff Sharkeye20a3ac2013-09-18 16:26:49 -0700135 public static final int ANIM_NONE = 1;
136 public static final int ANIM_SIDE = 2;
Tomasz Mikolajewskie3fe9d72016-02-03 16:53:21 +0900137 public static final int ANIM_LEAVE = 3;
138 public static final int ANIM_ENTER = 4;
Jeff Sharkeye20a3ac2013-09-18 16:26:49 -0700139
Steve McKaya6bbeab2016-02-17 15:02:01 -0800140 @IntDef(flag = true, value = {
141 REQUEST_COPY_DESTINATION
142 })
143 @Retention(RetentionPolicy.SOURCE)
144 public @interface RequestCode {}
Ben Kwaef3f2622015-04-07 15:43:39 -0700145 public static final int REQUEST_COPY_DESTINATION = 1;
146
Steve McKay35645432016-01-20 15:09:35 -0800147 private static final String TAG = "DirectoryFragment";
148 private static final int LOADER_ID = 42;
Steve McKay35645432016-01-20 15:09:35 -0800149
Ben Kwa18fce3c2015-09-01 11:03:01 -0700150 private Model mModel;
Ben Kwa8250db42015-10-07 14:15:12 -0700151 private MultiSelectManager mSelectionManager;
Ben Kwa91caed82015-09-21 10:49:52 -0700152 private Model.UpdateListener mModelUpdateListener = new ModelUpdateListener();
Ben Kwa0436a752016-01-15 10:43:24 -0800153 private ItemEventListener mItemEventListener = new ItemEventListener();
Ben Kwab0bfe2d2016-02-09 11:27:45 -0800154 private FocusManager mFocusManager;
Ben Kwac64cb252015-08-27 16:04:46 -0700155
Ben Kwad8391492015-12-17 10:37:00 -0800156 private IconHelper mIconHelper;
157
Steve McKay4b3a13c2015-06-11 10:10:49 -0700158 private View mEmptyView;
159 private RecyclerView mRecView;
Steve McKay41585d52016-01-21 15:10:39 -0800160 private ListeningGestureDetector mGestureDetector;
Steve McKay4b3a13c2015-06-11 10:10:49 -0700161
Steve McKay4b3a13c2015-06-11 10:10:49 -0700162 private String mStateKey;
163
Steve McKay4b3a13c2015-06-11 10:10:49 -0700164 private int mLastSortOrder = SORT_ORDER_UNKNOWN;
Steve McKay4b3a13c2015-06-11 10:10:49 -0700165 private DocumentsAdapter mAdapter;
Steve McKayf69502c2015-11-09 17:38:35 +0900166 private FragmentTuner mTuner;
Steve McKaybdbd0ff2015-05-20 15:58:42 -0700167 private DocumentClipper mClipper;
Ben Kwa1e2fa5e2016-02-02 23:00:02 -0800168 private GridLayoutManager mLayout;
Steve McKay0ba3a142015-07-23 16:33:41 -0700169 private int mColumnCount = 1; // This will get updated when layout changes.
Steve McKaybdbd0ff2015-05-20 15:58:42 -0700170
Ben Kwa3b19e312015-09-16 08:04:37 -0700171 private MessageBar mMessageBar;
Ben Kwa91caed82015-09-21 10:49:52 -0700172 private View mProgressBar;
Ben Kwa3b19e312015-09-16 08:04:37 -0700173
Aga Wronska893390b2016-02-17 13:50:42 -0800174 // Directory fragment state is defined by: root, document, query, type, selection
175 private @ResultType int mType = TYPE_NORMAL;
176 private RootInfo mRoot;
177 private DocumentInfo mDocument;
178 private String mQuery = null;
179 private Selection mSelection = null;
180 private boolean mSearchMode = false;
181
Jeff Sharkey9e0036e2013-04-26 16:54:55 -0700182 @Override
183 public View onCreateView(
184 LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Jeff Sharkey54e55b72013-06-30 20:02:59 -0700185 final View view = inflater.inflate(R.layout.fragment_directory, container, false);
186
Ben Kwa3b19e312015-09-16 08:04:37 -0700187 mMessageBar = MessageBar.create(getChildFragmentManager());
Ben Kwa91caed82015-09-21 10:49:52 -0700188 mProgressBar = view.findViewById(R.id.progressbar);
Ben Kwa3b19e312015-09-16 08:04:37 -0700189
Jeff Sharkey9fb567b2013-08-07 16:22:02 -0700190 mEmptyView = view.findViewById(android.R.id.empty);
191
Ben Kwa2036dad2016-02-10 07:46:35 -0800192 mRecView = (RecyclerView) view.findViewById(R.id.dir_list);
Steve McKay4b3a13c2015-06-11 10:10:49 -0700193 mRecView.setRecyclerListener(
194 new RecyclerListener() {
195 @Override
196 public void onViewRecycled(ViewHolder holder) {
197 cancelThumbnailTask(holder.itemView);
198 }
199 });
Steve McKayb46383b2015-05-06 14:27:57 -0700200
Ben Kwae48e4ca2015-10-20 15:02:33 -0700201 mRecView.setItemAnimator(new DirectoryItemAnimator(getActivity()));
Ben Kwabd964562015-10-14 08:00:27 -0700202
Ben Kwa990489d2016-02-25 14:10:40 -0800203 // Make the recycler and the empty views responsive to drop events.
204 mRecView.setOnDragListener(mOnDragListener);
205 mEmptyView.setOnDragListener(mOnDragListener);
Jeff Sharkey54e55b72013-06-30 20:02:59 -0700206
Jeff Sharkey5dfb3452013-08-31 21:27:44 -0700207 return view;
208 }
Jeff Sharkey54e55b72013-06-30 20:02:59 -0700209
Jeff Sharkey5dfb3452013-08-31 21:27:44 -0700210 @Override
Jeff Sharkeyd01571e2013-10-01 17:57:41 -0700211 public void onDestroyView() {
Aga Wronskad5597432016-02-26 11:36:07 -0800212 mSelectionManager.clearSelection();
Jeff Sharkeyd01571e2013-10-01 17:57:41 -0700213
214 // Cancel any outstanding thumbnail requests
Steve McKay4b3a13c2015-06-11 10:10:49 -0700215 final int count = mRecView.getChildCount();
Jeff Sharkeyd01571e2013-10-01 17:57:41 -0700216 for (int i = 0; i < count; i++) {
Steve McKay4b3a13c2015-06-11 10:10:49 -0700217 final View view = mRecView.getChildAt(i);
218 cancelThumbnailTask(view);
Jeff Sharkeyd01571e2013-10-01 17:57:41 -0700219 }
Aga Wronskad5597432016-02-26 11:36:07 -0800220
221 super.onDestroyView();
Jeff Sharkeyd01571e2013-10-01 17:57:41 -0700222 }
223
224 @Override
Jeff Sharkey5dfb3452013-08-31 21:27:44 -0700225 public void onActivityCreated(Bundle savedInstanceState) {
226 super.onActivityCreated(savedInstanceState);
227
228 final Context context = getActivity();
Steve McKayf69502c2015-11-09 17:38:35 +0900229 final State state = getDisplayState();
Jeff Sharkey5dfb3452013-08-31 21:27:44 -0700230
Aga Wronska893390b2016-02-17 13:50:42 -0800231 // Read arguments when object created for the first time.
232 // Restore state if fragment recreated.
233 Bundle args = savedInstanceState == null ? getArguments() : savedInstanceState;
234 mRoot = args.getParcelable(Shared.EXTRA_ROOT);
235 mDocument = args.getParcelable(Shared.EXTRA_DOC);
236 mStateKey = buildStateKey(mRoot, mDocument);
237 mQuery = args.getString(Shared.EXTRA_QUERY);
238 mType = args.getInt(Shared.EXTRA_TYPE);
239 mSelection = args.getParcelable(Shared.EXTRA_SELECTION);
240 mSearchMode = args.getBoolean(Shared.EXTRA_SEARCH_MODE);
Jeff Sharkeyf6db1542013-09-13 13:42:19 -0700241
Steve McKay3eb2d072016-01-25 19:00:22 -0800242 mIconHelper = new IconHelper(context, MODE_GRID);
Steve McKayef16f5f2015-12-22 18:15:31 -0800243
244 mAdapter = new SectionBreakDocumentsAdapterWrapper(
245 this, new ModelBackedDocumentsAdapter(this, mIconHelper));
246
Steve McKay4b3a13c2015-06-11 10:10:49 -0700247 mRecView.setAdapter(mAdapter);
248
Ben Kwa1e2fa5e2016-02-02 23:00:02 -0800249 mLayout = new GridLayoutManager(getContext(), mColumnCount);
250 SpanSizeLookup lookup = mAdapter.createSpanSizeLookup();
251 if (lookup != null) {
252 mLayout.setSpanSizeLookup(lookup);
253 }
254 mRecView.setLayoutManager(mLayout);
255
Ben Kwae3dfebf2016-02-18 16:45:45 -0800256 mGestureDetector =
257 new ListeningGestureDetector(this.getContext(), mDragHelper, new GestureListener());
Steve McKay669ebe72015-10-19 12:04:21 -0700258
Steve McKay41585d52016-01-21 15:10:39 -0800259 mRecView.addOnItemTouchListener(mGestureDetector);
Steve McKay669ebe72015-10-19 12:04:21 -0700260
Ben Kwac64cb252015-08-27 16:04:46 -0700261 // TODO: instead of inserting the view into the constructor, extract listener-creation code
262 // and set the listener on the view after the fact. Then the view doesn't need to be passed
Ben Kwa8250db42015-10-07 14:15:12 -0700263 // into the selection manager.
264 mSelectionManager = new MultiSelectManager(
Steve McKaydbec47a2015-08-12 14:48:34 -0700265 mRecView,
Steve McKay44408262016-01-05 15:27:17 -0800266 mAdapter,
Steve McKaydbec47a2015-08-12 14:48:34 -0700267 state.allowMultiple
268 ? MultiSelectManager.MODE_MULTIPLE
Steve McKaye852d932016-02-08 19:09:42 -0800269 : MultiSelectManager.MODE_SINGLE,
Aga Wronska893390b2016-02-17 13:50:42 -0800270 null);
Steve McKaye852d932016-02-08 19:09:42 -0800271
Aga Wronska893390b2016-02-17 13:50:42 -0800272 mSelectionManager.addCallback(new SelectionModeListener());
Ben Kwa18fce3c2015-09-01 11:03:01 -0700273
Steve McKay35645432016-01-20 15:09:35 -0800274 mModel = new Model();
Ben Kwa743c7c22015-12-01 19:56:57 -0800275 mModel.addUpdateListener(mAdapter);
Ben Kwa91caed82015-09-21 10:49:52 -0700276 mModel.addUpdateListener(mModelUpdateListener);
Steve McKay4b3a13c2015-06-11 10:10:49 -0700277
Ben Kwaa4acc902016-02-10 15:48:25 -0800278 // Make sure this is done after the RecyclerView is set up.
279 mFocusManager = new FocusManager(context, mRecView, mModel);
280
Steve McKayaa15dae2016-02-09 16:17:24 -0800281 mTuner = FragmentTuner.pick(getContext(), state);
Steve McKaybdbd0ff2015-05-20 15:58:42 -0700282 mClipper = new DocumentClipper(context);
283
Ben Kwad8391492015-12-17 10:37:00 -0800284 boolean hideGridTitles;
Jeff Sharkeyf6db1542013-09-13 13:42:19 -0700285 if (mType == TYPE_RECENT_OPEN) {
286 // Hide titles when showing recents for picking images/videos
Ben Kwad8391492015-12-17 10:37:00 -0800287 hideGridTitles = MimePredicate.mimeMatches(
Jeff Sharkeyf6db1542013-09-13 13:42:19 -0700288 MimePredicate.VISUAL_MIMES, state.acceptMimes);
289 } else {
Aga Wronska893390b2016-02-17 13:50:42 -0800290 hideGridTitles = (mDocument != null) && mDocument.isGridTitlesHidden();
Jeff Sharkeyf6db1542013-09-13 13:42:19 -0700291 }
Ben Kwad8391492015-12-17 10:37:00 -0800292 GridDocumentHolder.setHideTitles(hideGridTitles);
Jeff Sharkeyf6db1542013-09-13 13:42:19 -0700293
Jeff Sharkeyd01571e2013-10-01 17:57:41 -0700294 final ActivityManager am = (ActivityManager) context.getSystemService(
295 Context.ACTIVITY_SERVICE);
Ben Kwad8391492015-12-17 10:37:00 -0800296 boolean svelte = am.isLowRamDevice() && (mType == TYPE_RECENT_OPEN);
297 mIconHelper.setThumbnailsEnabled(!svelte);
Jeff Sharkeyd01571e2013-10-01 17:57:41 -0700298
Jeff Sharkeyd182bb62013-09-07 14:45:03 -0700299 // Kick off loader at least once
Aga Wronska893390b2016-02-17 13:50:42 -0800300 getLoaderManager().restartLoader(LOADER_ID, null, this);
Jeff Sharkey9e0036e2013-04-26 16:54:55 -0700301 }
302
Jeff Sharkey28c05ee2013-09-06 13:22:09 -0700303 @Override
Steve McKaye852d932016-02-08 19:09:42 -0800304 public void onSaveInstanceState(Bundle outState) {
Aga Wronska893390b2016-02-17 13:50:42 -0800305 super.onSaveInstanceState(outState);
306
Aga Wronskad5597432016-02-26 11:36:07 -0800307 mSelectionManager.getSelection(mSelection);
308
Aga Wronska893390b2016-02-17 13:50:42 -0800309 outState.putInt(Shared.EXTRA_TYPE, mType);
310 outState.putParcelable(Shared.EXTRA_ROOT, mRoot);
311 outState.putParcelable(Shared.EXTRA_DOC, mDocument);
312 outState.putString(Shared.EXTRA_QUERY, mQuery);
Aga Wronskad5597432016-02-26 11:36:07 -0800313 outState.putParcelable(Shared.EXTRA_SELECTION, mSelection);
Aga Wronska893390b2016-02-17 13:50:42 -0800314 outState.putBoolean(Shared.EXTRA_SEARCH_MODE, mSearchMode);
Aga Wronskad5597432016-02-26 11:36:07 -0800315
Steve McKaye852d932016-02-08 19:09:42 -0800316 }
317
318 @Override
Steve McKaya6bbeab2016-02-17 15:02:01 -0800319 public void onActivityResult(@RequestCode int requestCode, int resultCode, Intent data) {
320 switch(requestCode) {
321 case REQUEST_COPY_DESTINATION:
322 handleCopyResult(resultCode, data);
323 break;
324 default:
325 throw new UnsupportedOperationException("Unknown request code: " + requestCode);
Ben Kwaef3f2622015-04-07 15:43:39 -0700326 }
Steve McKaya6bbeab2016-02-17 15:02:01 -0800327 }
328
329 private void handleCopyResult(int resultCode, Intent data) {
Ben Kwaef3f2622015-04-07 15:43:39 -0700330 if (resultCode == Activity.RESULT_CANCELED || data == null) {
331 // User pressed the back button or otherwise cancelled the destination pick. Don't
332 // proceed with the copy.
333 return;
334 }
335
Steve McKaya6bbeab2016-02-17 15:02:01 -0800336 @OpType int operationType = data.getIntExtra(
Steve McKay14e827a2016-01-06 18:32:13 -0800337 FileOperationService.EXTRA_OPERATION,
338 FileOperationService.OPERATION_COPY);
339
340 FileOperations.start(
341 getActivity(),
342 getDisplayState().selectedDocumentsForCopy,
Tomasz Mikolajewskib8436af2016-01-25 16:20:15 +0900343 getDisplayState().stack.peek(),
Steve McKay323ee3e2015-09-25 16:02:56 -0700344 (DocumentStack) data.getParcelableExtra(Shared.EXTRA_STACK),
Steve McKay14e827a2016-01-06 18:32:13 -0800345 operationType);
Ben Kwaef3f2622015-04-07 15:43:39 -0700346 }
347
Steve McKay5353a1e2015-07-30 12:27:44 -0700348 protected boolean onDoubleTap(MotionEvent e) {
349 if (Events.isMouseEvent(e)) {
Ben Kwa003a9992015-11-30 23:00:02 -0800350 String id = getModelId(e);
351 if (id != null) {
352 return handleViewItem(id);
Steve McKay5353a1e2015-07-30 12:27:44 -0700353 }
354 }
355 return false;
356 }
357
Ben Kwa003a9992015-11-30 23:00:02 -0800358 private boolean handleViewItem(String id) {
359 final Cursor cursor = mModel.getItem(id);
Steve McKaya1f76802016-02-25 13:34:03 -0800360
361 assert(cursor != null);
362
Steve McKay5353a1e2015-07-30 12:27:44 -0700363 final String docMimeType = getCursorString(cursor, Document.COLUMN_MIME_TYPE);
364 final int docFlags = getCursorInt(cursor, Document.COLUMN_FLAGS);
Steve McKayf69502c2015-11-09 17:38:35 +0900365 if (mTuner.isDocumentEnabled(docMimeType, docFlags)) {
Steve McKay5353a1e2015-07-30 12:27:44 -0700366 final DocumentInfo doc = DocumentInfo.fromDirectoryCursor(cursor);
Ben Kwac64cb252015-08-27 16:04:46 -0700367 ((BaseActivity) getActivity()).onDocumentPicked(doc, mModel);
Ben Kwa8250db42015-10-07 14:15:12 -0700368 mSelectionManager.clearSelection();
Steve McKay5353a1e2015-07-30 12:27:44 -0700369 return true;
370 }
Steve McKay4b3a13c2015-06-11 10:10:49 -0700371 return false;
372 }
373
Ben Kwaef3f2622015-04-07 15:43:39 -0700374 @Override
Jeff Sharkeye20a3ac2013-09-18 16:26:49 -0700375 public void onStop() {
376 super.onStop();
377
378 // Remember last scroll location
379 final SparseArray<Parcelable> container = new SparseArray<Parcelable>();
380 getView().saveHierarchyState(container);
Steve McKayf69502c2015-11-09 17:38:35 +0900381 final State state = getDisplayState();
Jeff Sharkeye20a3ac2013-09-18 16:26:49 -0700382 state.dirState.put(mStateKey, container);
383 }
384
Jeff Sharkey669f8e72014-08-08 15:10:03 -0700385 public void onDisplayStateChanged() {
386 updateDisplayState();
387 }
388
Steve McKay3eb2d072016-01-25 19:00:22 -0800389 public void onSortOrderChanged() {
390 // Sort order is implemented as a sorting wrapper around directory
391 // results. So when sort order changes, we force a reload of the directory.
Aga Wronska893390b2016-02-17 13:50:42 -0800392 getLoaderManager().restartLoader(LOADER_ID, null, this);
Jeff Sharkeyd182bb62013-09-07 14:45:03 -0700393 }
394
Steve McKay3eb2d072016-01-25 19:00:22 -0800395 public void onViewModeChanged() {
396 // Mode change is just visual change; no need to kick loader.
Jeff Sharkeyd182bb62013-09-07 14:45:03 -0700397 updateDisplayState();
398 }
399
400 private void updateDisplayState() {
Steve McKay3eb2d072016-01-25 19:00:22 -0800401 State state = getDisplayState();
Steve McKay4b3a13c2015-06-11 10:10:49 -0700402 updateLayout(state.derivedMode);
Steve McKay4b3a13c2015-06-11 10:10:49 -0700403 mRecView.setAdapter(mAdapter);
404 }
405
406 /**
Ben Kwa1e2fa5e2016-02-02 23:00:02 -0800407 * Updates the layout after the view mode switches.
408 * @param mode The new view mode.
Steve McKay4b3a13c2015-06-11 10:10:49 -0700409 */
Ben Kwa1e2fa5e2016-02-02 23:00:02 -0800410 private void updateLayout(@ViewMode int mode) {
411 mColumnCount = calculateColumnCount(mode);
412 if (mLayout != null) {
413 mLayout.setSpanCount(mColumnCount);
Jeff Sharkey54e55b72013-06-30 20:02:59 -0700414 }
Jeff Sharkey9d0843d2013-05-07 12:41:33 -0700415
Steve McKay76be6202016-01-12 11:14:33 -0800416 int pad = getDirectoryPadding(mode);
417 mRecView.setPadding(pad, pad, pad, pad);
Ben Kwa1e2fa5e2016-02-02 23:00:02 -0800418 mRecView.requestLayout();
Steve McKay76be6202016-01-12 11:14:33 -0800419 mSelectionManager.handleLayoutChanged(); // RecyclerView doesn't do this for us
Steve McKay3eb2d072016-01-25 19:00:22 -0800420 mIconHelper.setViewMode(mode);
Jeff Sharkey54e55b72013-06-30 20:02:59 -0700421 }
422
Ben Kwa1e2fa5e2016-02-02 23:00:02 -0800423 private int calculateColumnCount(@ViewMode int mode) {
424 if (mode == MODE_LIST) {
425 // List mode is a "grid" with 1 column.
426 return 1;
427 }
428
Steve McKay58efce32015-08-20 16:19:38 +0000429 int cellWidth = getResources().getDimensionPixelSize(R.dimen.grid_width);
430 int cellMargin = 2 * getResources().getDimensionPixelSize(R.dimen.grid_item_margin);
Steve McKay0ba3a142015-07-23 16:33:41 -0700431 int viewPadding = mRecView.getPaddingLeft() + mRecView.getPaddingRight();
Steve McKay58efce32015-08-20 16:19:38 +0000432
Steve McKaya1f76802016-02-25 13:34:03 -0800433 assert(mRecView.getWidth() > 0);
434
Steve McKay0ba3a142015-07-23 16:33:41 -0700435 int columnCount = Math.max(1,
Steve McKay58efce32015-08-20 16:19:38 +0000436 (mRecView.getWidth() - viewPadding) / (cellWidth + cellMargin));
437
Steve McKay0ba3a142015-07-23 16:33:41 -0700438 return columnCount;
439 }
440
Ben Kwa1e2fa5e2016-02-02 23:00:02 -0800441 private int getDirectoryPadding(@ViewMode int mode) {
Steve McKay76be6202016-01-12 11:14:33 -0800442 switch (mode) {
443 case MODE_GRID:
Ben Kwa1e2fa5e2016-02-02 23:00:02 -0800444 return getResources().getDimensionPixelSize(R.dimen.grid_container_padding);
Steve McKay76be6202016-01-12 11:14:33 -0800445 case MODE_LIST:
Ben Kwa1e2fa5e2016-02-02 23:00:02 -0800446 return getResources().getDimensionPixelSize(R.dimen.list_container_padding);
Steve McKay76be6202016-01-12 11:14:33 -0800447 default:
448 throw new IllegalArgumentException("Unsupported layout mode: " + mode);
449 }
450 }
451
Steve McKayef16f5f2015-12-22 18:15:31 -0800452 @Override
453 public int getColumnCount() {
454 return mColumnCount;
455 }
456
Steve McKay4b3a13c2015-06-11 10:10:49 -0700457 /**
458 * Manages the integration between our ActionMode and MultiSelectManager, initiating
459 * ActionMode when there is a selection, canceling it when there is no selection,
460 * and clearing selection when action mode is explicitly exited by the user.
461 */
462 private final class SelectionModeListener
463 implements MultiSelectManager.Callback, ActionMode.Callback {
464
465 private Selection mSelected = new Selection();
466 private ActionMode mActionMode;
Steve McKay503648d2015-07-22 12:13:46 -0700467 private int mNoDeleteCount = 0;
Aga Wronska3b327ef2016-01-20 16:32:33 -0800468 private int mNoRenameCount = -1;
Steve McKay503648d2015-07-22 12:13:46 -0700469 private Menu mMenu;
Steve McKay4b3a13c2015-06-11 10:10:49 -0700470
Jeff Sharkey54e55b72013-06-30 20:02:59 -0700471 @Override
Ben Kwa743c7c22015-12-01 19:56:57 -0800472 public boolean onBeforeItemStateChange(String modelId, boolean selected) {
Steve McKay4b3a13c2015-06-11 10:10:49 -0700473 if (selected) {
Ben Kwa743c7c22015-12-01 19:56:57 -0800474 final Cursor cursor = mModel.getItem(modelId);
Steve McKaya1f76802016-02-25 13:34:03 -0800475
476 assert(cursor != null);
477
Jeff Sharkey2a030b02013-09-26 10:54:16 -0700478 final String docMimeType = getCursorString(cursor, Document.COLUMN_MIME_TYPE);
479 final int docFlags = getCursorInt(cursor, Document.COLUMN_FLAGS);
Tomasz Mikolajewskia8057a92015-11-16 11:41:28 +0900480 return mTuner.canSelectType(docMimeType, docFlags);
Steve McKay4b3a13c2015-06-11 10:10:49 -0700481 }
482 return true;
483 }
484
485 @Override
Ben Kwa743c7c22015-12-01 19:56:57 -0800486 public void onItemStateChanged(String modelId, boolean selected) {
487 final Cursor cursor = mModel.getItem(modelId);
Steve McKay30551a22016-02-16 13:08:10 -0800488 if (cursor == null) {
489 Log.e(TAG, "Model returned null cursor for document: " + modelId
490 + ". Ignoring state changed event.");
491 return;
492 }
Steve McKay503648d2015-07-22 12:13:46 -0700493
Ben Kwa67924892016-01-27 09:58:36 -0800494 // TODO: Should this be happening in onSelectionChanged? Technically this callback is
495 // triggered on "silent" selection updates (i.e. we might be reacting to unfinalized
496 // selection changes here)
Steve McKay503648d2015-07-22 12:13:46 -0700497 final int docFlags = getCursorInt(cursor, Document.COLUMN_FLAGS);
Steve McKay27d20a32016-02-22 18:38:09 -0800498 if ((docFlags & Document.FLAG_SUPPORTS_DELETE) == 0
499 && (docFlags & Document.FLAG_SUPPORTS_DELETE) == 0) {
Steve McKay503648d2015-07-22 12:13:46 -0700500 mNoDeleteCount += selected ? 1 : -1;
501 }
Aga Wronska3b327ef2016-01-20 16:32:33 -0800502 if ((docFlags & Document.FLAG_SUPPORTS_RENAME) != 0) {
503 mNoRenameCount += selected ? 1 : -1;
504 }
Steve McKaydbec47a2015-08-12 14:48:34 -0700505 }
Steve McKay503648d2015-07-22 12:13:46 -0700506
Steve McKaydbec47a2015-08-12 14:48:34 -0700507 @Override
508 public void onSelectionChanged() {
Ben Kwa8250db42015-10-07 14:15:12 -0700509 mSelectionManager.getSelection(mSelected);
Ben Kwa7cc80012015-09-11 15:40:18 -0700510 TypedValue color = new TypedValue();
Steve McKay503648d2015-07-22 12:13:46 -0700511 if (mSelected.size() > 0) {
Steve McKay4b3a13c2015-06-11 10:10:49 -0700512 if (DEBUG) Log.d(TAG, "Maybe starting action mode.");
513 if (mActionMode == null) {
514 if (DEBUG) Log.d(TAG, "Yeah. Starting action mode.");
515 mActionMode = getActivity().startActionMode(this);
Jeff Sharkey3f4c2052013-09-09 16:51:06 -0700516 }
Ben Kwa8250db42015-10-07 14:15:12 -0700517 getActivity().getTheme().resolveAttribute(R.attr.colorActionMode, color, true);
Steve McKay503648d2015-07-22 12:13:46 -0700518 updateActionMenu();
519 } else {
520 if (DEBUG) Log.d(TAG, "Finishing action mode.");
521 if (mActionMode != null) {
522 mActionMode.finish();
523 }
Ben Kwa0f7078f02015-09-08 07:31:19 -0700524 getActivity().getTheme().resolveAttribute(
525 android.R.attr.colorPrimaryDark, color, true);
Jeff Sharkeya5599ef2013-08-15 16:17:41 -0700526 }
Ben Kwa7cc80012015-09-11 15:40:18 -0700527 getActivity().getWindow().setStatusBarColor(color.data);
Jeff Sharkey54e55b72013-06-30 20:02:59 -0700528
Steve McKay4b3a13c2015-06-11 10:10:49 -0700529 if (mActionMode != null) {
Steve McKay5aacf1f2015-10-27 14:15:58 -0700530 mActionMode.setTitle(String.valueOf(mSelected.size()));
Steve McKay4b3a13c2015-06-11 10:10:49 -0700531 }
532 }
533
534 // Called when the user exits the action mode
535 @Override
536 public void onDestroyActionMode(ActionMode mode) {
537 if (DEBUG) Log.d(TAG, "Handling action mode destroyed.");
538 mActionMode = null;
539 // clear selection
Ben Kwa8250db42015-10-07 14:15:12 -0700540 mSelectionManager.clearSelection();
Steve McKay503648d2015-07-22 12:13:46 -0700541 mSelected.clear();
542 mNoDeleteCount = 0;
Aga Wronska3b327ef2016-01-20 16:32:33 -0800543 mNoRenameCount = -1;
Steve McKay4b3a13c2015-06-11 10:10:49 -0700544 }
545
Jeff Sharkeybe8b12e2013-07-01 16:56:54 -0700546 @Override
547 public boolean onCreateActionMode(ActionMode mode, Menu menu) {
Ben Kwa8250db42015-10-07 14:15:12 -0700548 int size = mSelectionManager.getSelection().size();
Jeff Sharkeybe8b12e2013-07-01 16:56:54 -0700549 mode.getMenuInflater().inflate(R.menu.mode_directory, menu);
Ben Kwa8250db42015-10-07 14:15:12 -0700550 mode.setTitle(TextUtils.formatSelectedCount(size));
551 return (size > 0);
Jeff Sharkeybe8b12e2013-07-01 16:56:54 -0700552 }
553
554 @Override
555 public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
Steve McKay503648d2015-07-22 12:13:46 -0700556 mMenu = menu;
557 updateActionMenu();
Jeff Sharkeybe8b12e2013-07-01 16:56:54 -0700558 return true;
559 }
560
Aga Wronska3b327ef2016-01-20 16:32:33 -0800561 boolean canRenameSelection() {
562 return mNoRenameCount == 0 && mSelectionManager.getSelection().size() == 1;
563 }
564
565 boolean canDeleteSelection() {
566 return mNoDeleteCount == 0;
567 }
568
Steve McKay503648d2015-07-22 12:13:46 -0700569 private void updateActionMenu() {
Steve McKaya1f76802016-02-25 13:34:03 -0800570 assert(mMenu != null);
Aga Wronska3b327ef2016-01-20 16:32:33 -0800571
Steve McKay503648d2015-07-22 12:13:46 -0700572 // Delegate update logic to our owning action, since specialized logic is desired.
Aga Wronska3b327ef2016-01-20 16:32:33 -0800573 mTuner.updateActionMenu(mMenu, mType, canDeleteSelection(), canRenameSelection());
Steve McKay5bbae102015-10-01 11:39:24 -0700574 Menus.disableHiddenItems(mMenu);
Steve McKay503648d2015-07-22 12:13:46 -0700575 }
576
Jeff Sharkeybe8b12e2013-07-01 16:56:54 -0700577 @Override
Steve McKay4b3a13c2015-06-11 10:10:49 -0700578 public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
Steve McKaybdbd0ff2015-05-20 15:58:42 -0700579
Ben Kwa8250db42015-10-07 14:15:12 -0700580 Selection selection = mSelectionManager.getSelection(new Selection());
Jeff Sharkeybe8b12e2013-07-01 16:56:54 -0700581
Steve McKayc2b4b3d2015-12-01 17:02:42 -0800582 switch (item.getItemId()) {
583 case R.id.menu_open:
584 openDocuments(selection);
585 mode.finish();
586 return true;
Jeff Sharkey4eb407a2013-08-18 17:38:20 -0700587
Steve McKayc2b4b3d2015-12-01 17:02:42 -0800588 case R.id.menu_share:
589 shareDocuments(selection);
590 mode.finish();
591 return true;
Jeff Sharkey4eb407a2013-08-18 17:38:20 -0700592
Steve McKayc2b4b3d2015-12-01 17:02:42 -0800593 case R.id.menu_delete:
594 // Exit selection mode first, so we avoid deselecting deleted documents.
595 mode.finish();
596 deleteDocuments(selection);
597 return true;
Jeff Sharkey4eb407a2013-08-18 17:38:20 -0700598
Steve McKayc2b4b3d2015-12-01 17:02:42 -0800599 case R.id.menu_copy_to:
Steve McKay14e827a2016-01-06 18:32:13 -0800600 transferDocuments(selection, FileOperationService.OPERATION_COPY);
Steve McKayc2b4b3d2015-12-01 17:02:42 -0800601 mode.finish();
602 return true;
Ben Kwa0b4a3c42015-05-05 11:50:11 -0700603
Steve McKayc2b4b3d2015-12-01 17:02:42 -0800604 case R.id.menu_move_to:
605 // Exit selection mode first, so we avoid deselecting deleted documents.
606 mode.finish();
Steve McKay14e827a2016-01-06 18:32:13 -0800607 transferDocuments(selection, FileOperationService.OPERATION_MOVE);
Steve McKayc2b4b3d2015-12-01 17:02:42 -0800608 return true;
Ben Kwad99109f2015-03-31 10:11:43 -0700609
Steve McKayc2b4b3d2015-12-01 17:02:42 -0800610 case R.id.menu_copy_to_clipboard:
Steve McKaycbee5442016-01-28 15:30:10 -0800611 copySelectedToClipboard();
Steve McKayc2b4b3d2015-12-01 17:02:42 -0800612 return true;
Steve McKaybdbd0ff2015-05-20 15:58:42 -0700613
Steve McKayc2b4b3d2015-12-01 17:02:42 -0800614 case R.id.menu_select_all:
615 selectAllFiles();
616 return true;
Ben Kwa3bcc94882015-03-31 08:15:21 -0700617
Aga Wronska3b327ef2016-01-20 16:32:33 -0800618 case R.id.menu_rename:
619 renameDocuments(selection);
620 mode.finish();
621 return true;
622
Steve McKayc2b4b3d2015-12-01 17:02:42 -0800623 default:
624 if (DEBUG) Log.d(TAG, "Unhandled menu item selected: " + item);
625 return false;
Jeff Sharkeybe8b12e2013-07-01 16:56:54 -0700626 }
627 }
Steve McKay4b3a13c2015-06-11 10:10:49 -0700628 }
Jeff Sharkeybe8b12e2013-07-01 16:56:54 -0700629
Steve McKaycbee5442016-01-28 15:30:10 -0800630 public final boolean onBackPressed() {
631 if (mSelectionManager.hasSelection()) {
632 if (DEBUG) Log.d(TAG, "Clearing selection on back pressed.");
633 mSelectionManager.clearSelection();
634 return true;
635 }
636 return false;
637 }
638
Ben Kwad8391492015-12-17 10:37:00 -0800639 private void cancelThumbnailTask(View view) {
Steve McKay4b3a13c2015-06-11 10:10:49 -0700640 final ImageView iconThumb = (ImageView) view.findViewById(R.id.icon_thumb);
641 if (iconThumb != null) {
Ben Kwad8391492015-12-17 10:37:00 -0800642 mIconHelper.stopLoading(iconThumb);
Jeff Sharkey4ec97392013-09-10 12:04:26 -0700643 }
Steve McKay4b3a13c2015-06-11 10:10:49 -0700644 }
Jeff Sharkey4ec97392013-09-10 12:04:26 -0700645
Steve McKay4b3a13c2015-06-11 10:10:49 -0700646 private void openDocuments(final Selection selected) {
Steve McKayab7865c2015-05-27 16:11:42 -0700647 new GetDocumentsTask() {
648 @Override
649 void onDocumentsReady(List<DocumentInfo> docs) {
Steve McKay12055472015-08-20 16:48:49 -0700650 // TODO: Implement support in Files activity for opening multiple docs.
Steve McKayab7865c2015-05-27 16:11:42 -0700651 BaseActivity.get(DirectoryFragment.this).onDocumentsPicked(docs);
Ben Kwa726cf702015-04-08 15:03:35 -0700652 }
Steve McKayab7865c2015-05-27 16:11:42 -0700653 }.execute(selected);
Jeff Sharkey4eb407a2013-08-18 17:38:20 -0700654 }
655
Steve McKay4b3a13c2015-06-11 10:10:49 -0700656 private void shareDocuments(final Selection selected) {
Steve McKayab7865c2015-05-27 16:11:42 -0700657 new GetDocumentsTask() {
658 @Override
659 void onDocumentsReady(List<DocumentInfo> docs) {
660 Intent intent;
661
662 // Filter out directories - those can't be shared.
Steve McKay58efce32015-08-20 16:19:38 +0000663 List<DocumentInfo> docsForSend = new ArrayList<>();
Steve McKayab7865c2015-05-27 16:11:42 -0700664 for (DocumentInfo doc: docs) {
665 if (!Document.MIME_TYPE_DIR.equals(doc.mimeType)) {
666 docsForSend.add(doc);
667 }
668 }
669
670 if (docsForSend.size() == 1) {
671 final DocumentInfo doc = docsForSend.get(0);
672
673 intent = new Intent(Intent.ACTION_SEND);
674 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
675 intent.addCategory(Intent.CATEGORY_DEFAULT);
676 intent.setType(doc.mimeType);
677 intent.putExtra(Intent.EXTRA_STREAM, doc.derivedUri);
678
679 } else if (docsForSend.size() > 1) {
680 intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
681 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
682 intent.addCategory(Intent.CATEGORY_DEFAULT);
683
Steve McKay58efce32015-08-20 16:19:38 +0000684 final ArrayList<String> mimeTypes = new ArrayList<>();
685 final ArrayList<Uri> uris = new ArrayList<>();
Steve McKayab7865c2015-05-27 16:11:42 -0700686 for (DocumentInfo doc : docsForSend) {
687 mimeTypes.add(doc.mimeType);
688 uris.add(doc.derivedUri);
689 }
690
691 intent.setType(findCommonMimeType(mimeTypes));
692 intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
693
694 } else {
695 return;
696 }
697
698 intent = Intent.createChooser(intent, getActivity().getText(R.string.share_via));
699 startActivity(intent);
700 }
701 }.execute(selected);
702 }
703
Steve McKay4b3a13c2015-06-11 10:10:49 -0700704 private void deleteDocuments(final Selection selected) {
Steve McKaya1f76802016-02-25 13:34:03 -0800705 assert(!selected.isEmpty());
Jeff Sharkey4eb407a2013-08-18 17:38:20 -0700706
Tomasz Mikolajewskib8436af2016-01-25 16:20:15 +0900707 final DocumentInfo srcParent = getDisplayState().stack.peek();
708 new GetDocumentsTask() {
709 @Override
Steve McKay7a3b8112016-02-23 10:06:50 -0800710 void onDocumentsReady(final List<DocumentInfo> docs) {
711 new AlertDialog.Builder(getActivity())
712 .setTitle(R.string.delete_confirmation_title)
713 .setMessage(
714 Shared.getQuantityString(
715 getActivity(),
716 R.plurals.delete_confirmation_message,
717 docs.size()))
718 .setPositiveButton(
719 android.R.string.yes,
720 new DialogInterface.OnClickListener() {
721 public void onClick(DialogInterface dialog, int id) {
722 // Hide the files in the UI.
723 mAdapter.hide(selected.getAll());
724 FileOperations.delete(
725 getActivity(), docs, srcParent, getDisplayState().stack);
Ben Kwa304895a2015-08-27 16:06:33 -0700726 }
727 })
Steve McKay7a3b8112016-02-23 10:06:50 -0800728 .setNegativeButton(android.R.string.no, null)
729 .show();
730 }
731 }.execute(selected);
Jeff Sharkey4eb407a2013-08-18 17:38:20 -0700732 }
733
Ben Kwa1e2fa5e2016-02-02 23:00:02 -0800734 private void transferDocuments(final Selection selected, final @OpType int mode) {
Ben Kwaef3f2622015-04-07 15:43:39 -0700735 // Pop up a dialog to pick a destination. This is inadequate but works for now.
736 // TODO: Implement a picker that is to spec.
Daichi Hironobbe22922015-04-10 15:50:38 +0900737 final Intent intent = new Intent(
Ben Kwa84cebbe2015-09-25 14:48:29 -0700738 Shared.ACTION_PICK_COPY_DESTINATION,
Daichi Hironobbe22922015-04-10 15:50:38 +0900739 Uri.EMPTY,
740 getActivity(),
741 DocumentsActivity.class);
Steve McKayab7865c2015-05-27 16:11:42 -0700742
Steve McKaya6bbeab2016-02-17 15:02:01 -0800743 // Set an appropriate title on the drawer when it is shown in the picker.
744 // Coupled with the fact that we auto-open the drawer for copy/move operations
745 // it should basically be the thing people see first.
746 int drawerTitleId = mode == FileOperationService.OPERATION_MOVE
747 ? R.string.menu_move : R.string.menu_copy;
748 intent.putExtra(DocumentsContract.EXTRA_PROMPT, getResources().getString(drawerTitleId));
749
Steve McKayab7865c2015-05-27 16:11:42 -0700750 new GetDocumentsTask() {
751 @Override
752 void onDocumentsReady(List<DocumentInfo> docs) {
Steve McKaya6bbeab2016-02-17 15:02:01 -0800753 // TODO: Can this move to Fragment bundle state?
Steve McKayf69502c2015-11-09 17:38:35 +0900754 getDisplayState().selectedDocumentsForCopy = docs;
Steve McKayab7865c2015-05-27 16:11:42 -0700755
Steve McKaya6bbeab2016-02-17 15:02:01 -0800756 // Determine if there is a directory in the set of documents
757 // to be copied? Why? Directory creation isn't supported by some roots
758 // (like Downloads). This informs DocumentsActivity (the "picker")
759 // to restrict available roots to just those with support.
760 intent.putExtra(Shared.EXTRA_DIRECTORY_COPY, hasDirectory(docs));
Steve McKay14e827a2016-01-06 18:32:13 -0800761 intent.putExtra(FileOperationService.EXTRA_OPERATION, mode);
Steve McKaya6bbeab2016-02-17 15:02:01 -0800762
763 // This just identifies the type of request...we'll check it
764 // when we reveive a response.
Steve McKayab7865c2015-05-27 16:11:42 -0700765 startActivityForResult(intent, REQUEST_COPY_DESTINATION);
Daichi Hirono9be34292015-04-14 17:12:54 +0900766 }
Steve McKaya6bbeab2016-02-17 15:02:01 -0800767
Steve McKayab7865c2015-05-27 16:11:42 -0700768 }.execute(selected);
Ben Kwad99109f2015-03-31 10:11:43 -0700769 }
770
Steve McKaya6bbeab2016-02-17 15:02:01 -0800771 private static boolean hasDirectory(List<DocumentInfo> docs) {
772 for (DocumentInfo info : docs) {
773 if (Document.MIME_TYPE_DIR.equals(info.mimeType)) {
774 return true;
775 }
776 }
777 return false;
778 }
779
Aga Wronska3b327ef2016-01-20 16:32:33 -0800780 private void renameDocuments(Selection selected) {
781 // Batch renaming not supported
782 // Rename option is only available in menu when 1 document selected
Steve McKaya1f76802016-02-25 13:34:03 -0800783 assert(selected.size() == 1);
Aga Wronska3b327ef2016-01-20 16:32:33 -0800784
785 new GetDocumentsTask() {
786 @Override
787 void onDocumentsReady(List<DocumentInfo> docs) {
788 RenameDocumentFragment.show(getFragmentManager(), docs.get(0));
789 }
790 }.execute(selected);
791 }
792
Steve McKayef16f5f2015-12-22 18:15:31 -0800793 @Override
794 public void initDocumentHolder(DocumentHolder holder) {
Ben Kwa0436a752016-01-15 10:43:24 -0800795 holder.addEventListener(mItemEventListener);
Ben Kwa2036dad2016-02-10 07:46:35 -0800796 holder.itemView.setOnFocusChangeListener(mFocusManager);
Steve McKayef16f5f2015-12-22 18:15:31 -0800797 }
798
799 @Override
800 public void onBindDocumentHolder(DocumentHolder holder, Cursor cursor) {
Ben Kwa990489d2016-02-25 14:10:40 -0800801 setupDragAndDropOnDocumentView(holder.itemView, cursor);
Steve McKayef16f5f2015-12-22 18:15:31 -0800802 }
803
804 @Override
805 public State getDisplayState() {
Steve McKayf69502c2015-11-09 17:38:35 +0900806 return ((BaseActivity) getActivity()).getDisplayState();
Jeff Sharkey54e55b72013-06-30 20:02:59 -0700807 }
808
Steve McKayef16f5f2015-12-22 18:15:31 -0800809 @Override
810 public Model getModel() {
811 return mModel;
812 }
813
814 @Override
815 public boolean isDocumentEnabled(String docMimeType, int docFlags) {
816 return mTuner.isDocumentEnabled(docMimeType, docFlags);
817 }
818
Steve McKay9ed88a42016-01-21 18:46:15 -0800819 private void showEmptyDirectory() {
Ben Kwa0e9aae42016-02-04 16:35:27 -0800820 showEmptyView(R.string.empty, R.drawable.cabinet);
Ben Kwa91bec532015-09-16 13:15:38 -0700821 }
822
Steve McKay9ed88a42016-01-21 18:46:15 -0800823 private void showNoResults(RootInfo root) {
824 CharSequence msg = getContext().getResources().getText(R.string.no_results);
Ben Kwa0e9aae42016-02-04 16:35:27 -0800825 showEmptyView(String.format(String.valueOf(msg), root.title), R.drawable.cabinet);
Ben Kwa91bec532015-09-16 13:15:38 -0700826 }
827
Steve McKay9ed88a42016-01-21 18:46:15 -0800828 private void showQueryError() {
Ben Kwa0e9aae42016-02-04 16:35:27 -0800829 showEmptyView(R.string.query_error, R.drawable.hourglass);
Steve McKay9ed88a42016-01-21 18:46:15 -0800830 }
831
Ben Kwa0e9aae42016-02-04 16:35:27 -0800832 private void showEmptyView(@StringRes int id, int drawable) {
833 showEmptyView(getContext().getResources().getText(id), drawable);
Steve McKay9ed88a42016-01-21 18:46:15 -0800834 }
835
Ben Kwa0e9aae42016-02-04 16:35:27 -0800836 private void showEmptyView(CharSequence msg, int drawable) {
Steve McKay9ed88a42016-01-21 18:46:15 -0800837 View content = mEmptyView.findViewById(R.id.content);
838 TextView msgView = (TextView) mEmptyView.findViewById(R.id.message);
Ben Kwa0e9aae42016-02-04 16:35:27 -0800839 ImageView imageView = (ImageView) mEmptyView.findViewById(R.id.artwork);
Steve McKay9ed88a42016-01-21 18:46:15 -0800840 msgView.setText(msg);
Ben Kwa0e9aae42016-02-04 16:35:27 -0800841 imageView.setImageResource(drawable);
Steve McKay9ed88a42016-01-21 18:46:15 -0800842
Steve McKay9ed88a42016-01-21 18:46:15 -0800843 mEmptyView.setVisibility(View.VISIBLE);
Aga Wronskad4b17532016-02-12 09:15:32 -0800844 mEmptyView.requestFocus();
Steve McKay9ed88a42016-01-21 18:46:15 -0800845 mRecView.setVisibility(View.GONE);
Steve McKay9ed88a42016-01-21 18:46:15 -0800846 }
847
848 private void showDirectory() {
Ben Kwa91bec532015-09-16 13:15:38 -0700849 mEmptyView.setVisibility(View.GONE);
850 mRecView.setVisibility(View.VISIBLE);
Aga Wronskad4b17532016-02-12 09:15:32 -0800851 mRecView.requestFocus();
Ben Kwa91bec532015-09-16 13:15:38 -0700852 }
853
Jeff Sharkeyb5133112013-09-01 18:41:04 -0700854 private String findCommonMimeType(List<String> mimeTypes) {
855 String[] commonType = mimeTypes.get(0).split("/");
856 if (commonType.length != 2) {
857 return "*/*";
858 }
859
860 for (int i = 1; i < mimeTypes.size(); i++) {
861 String[] type = mimeTypes.get(i).split("/");
862 if (type.length != 2) continue;
863
864 if (!commonType[1].equals(type[1])) {
865 commonType[1] = "*";
866 }
867
868 if (!commonType[0].equals(type[0])) {
869 commonType[0] = "*";
870 commonType[1] = "*";
871 break;
872 }
873 }
874
875 return commonType[0] + "/" + commonType[1];
876 }
Jeff Sharkey3f4c2052013-09-09 16:51:06 -0700877
Steve McKaybdbd0ff2015-05-20 15:58:42 -0700878 private void copyFromClipboard() {
879 new AsyncTask<Void, Void, List<DocumentInfo>>() {
880
881 @Override
882 protected List<DocumentInfo> doInBackground(Void... params) {
883 return mClipper.getClippedDocuments();
884 }
885
886 @Override
887 protected void onPostExecute(List<DocumentInfo> docs) {
888 DocumentInfo destination =
889 ((BaseActivity) getActivity()).getCurrentDirectory();
890 copyDocuments(docs, destination);
891 }
892 }.execute();
Steve McKay3da8afc2015-05-05 14:50:00 -0700893 }
894
Steve McKaybdbd0ff2015-05-20 15:58:42 -0700895 private void copyFromClipData(final ClipData clipData, final DocumentInfo destination) {
Steve McKaya1f76802016-02-25 13:34:03 -0800896 assert(clipData != null);
897
Steve McKaybdbd0ff2015-05-20 15:58:42 -0700898 new AsyncTask<Void, Void, List<DocumentInfo>>() {
Vladislav Kaznacheev335dba52015-05-01 13:46:57 -0700899
Steve McKaybdbd0ff2015-05-20 15:58:42 -0700900 @Override
901 protected List<DocumentInfo> doInBackground(Void... params) {
902 return mClipper.getDocumentsFromClipData(clipData);
903 }
904
905 @Override
906 protected void onPostExecute(List<DocumentInfo> docs) {
907 copyDocuments(docs, destination);
908 }
909 }.execute();
910 }
911
912 private void copyDocuments(final List<DocumentInfo> docs, final DocumentInfo destination) {
Steve McKay4a1ca862016-02-17 18:25:47 -0800913 BaseActivity activity = (BaseActivity) getActivity();
914 if (!canCopy(docs, activity.getCurrentRoot(), destination)) {
Steve McKay5bbae102015-10-01 11:39:24 -0700915 Snackbars.makeSnackbar(
Steve McKaybdbd0ff2015-05-20 15:58:42 -0700916 getActivity(),
Ben Kwa94b486d2015-09-30 10:00:10 -0700917 R.string.clipboard_files_cannot_paste,
918 Snackbar.LENGTH_SHORT)
919 .show();
Steve McKay3da8afc2015-05-05 14:50:00 -0700920 return;
921 }
922
Steve McKaybdbd0ff2015-05-20 15:58:42 -0700923 if (docs.isEmpty()) {
Vladislav Kaznacheev335dba52015-05-01 13:46:57 -0700924 return;
Vladislav Kaznacheevd69d3c42015-05-05 12:09:47 -0700925 }
Vladislav Kaznacheev335dba52015-05-01 13:46:57 -0700926
Steve McKayf69502c2015-11-09 17:38:35 +0900927 final DocumentStack curStack = getDisplayState().stack;
Vladislav Kaznacheev335dba52015-05-01 13:46:57 -0700928 DocumentStack tmpStack = new DocumentStack();
Steve McKaybdbd0ff2015-05-20 15:58:42 -0700929 if (destination != null) {
930 tmpStack.push(destination);
Vladislav Kaznacheev335dba52015-05-01 13:46:57 -0700931 tmpStack.addAll(curStack);
932 } else {
933 tmpStack = curStack;
934 }
935
Steve McKay14e827a2016-01-06 18:32:13 -0800936 FileOperations.copy(getActivity(), docs, tmpStack);
Vladislav Kaznacheev335dba52015-05-01 13:46:57 -0700937 }
938
Steve McKayf8621552015-11-03 15:23:16 -0800939 public void copySelectedToClipboard() {
Steve McKayd28c5c32015-12-07 16:31:42 -0800940 Selection selection = mSelectionManager.getSelection(new Selection());
941 if (!selection.isEmpty()) {
942 copySelectionToClipboard(selection);
Steve McKaycbee5442016-01-28 15:30:10 -0800943 mSelectionManager.clearSelection();
Steve McKayd28c5c32015-12-07 16:31:42 -0800944 }
Steve McKayab7865c2015-05-27 16:11:42 -0700945 }
Steve McKay3da8afc2015-05-05 14:50:00 -0700946
Steve McKayd28c5c32015-12-07 16:31:42 -0800947 void copySelectionToClipboard(Selection selection) {
Steve McKaya1f76802016-02-25 13:34:03 -0800948 assert(!selection.isEmpty());
Steve McKayab7865c2015-05-27 16:11:42 -0700949 new GetDocumentsTask() {
950 @Override
951 void onDocumentsReady(List<DocumentInfo> docs) {
952 mClipper.clipDocuments(docs);
Steve McKaybdbd0ff2015-05-20 15:58:42 -0700953 Activity activity = getActivity();
Steve McKay5bbae102015-10-01 11:39:24 -0700954 Snackbars.makeSnackbar(activity,
Steve McKaybdbd0ff2015-05-20 15:58:42 -0700955 activity.getResources().getQuantityString(
956 R.plurals.clipboard_files_clipped, docs.size(), docs.size()),
Ben Kwa862b96412015-12-07 13:25:27 -0800957 Snackbar.LENGTH_SHORT).show();
Steve McKayab7865c2015-05-27 16:11:42 -0700958 }
Steve McKayd28c5c32015-12-07 16:31:42 -0800959 }.execute(selection);
Steve McKay3da8afc2015-05-05 14:50:00 -0700960 }
961
Steve McKayf8621552015-11-03 15:23:16 -0800962 public void pasteFromClipboard() {
Steve McKaybdbd0ff2015-05-20 15:58:42 -0700963 copyFromClipboard();
964 getActivity().invalidateOptionsMenu();
Steve McKay3da8afc2015-05-05 14:50:00 -0700965 }
966
Steve McKay3da8afc2015-05-05 14:50:00 -0700967 /**
968 * Returns true if the list of files can be copied to destination. Note that this
969 * is a policy check only. Currently the method does not attempt to verify
970 * available space or any other environmental aspects possibly resulting in
971 * failure to copy.
972 *
973 * @return true if the list of files can be copied to destination.
974 */
Steve McKay4a1ca862016-02-17 18:25:47 -0800975 private boolean canCopy(List<DocumentInfo> files, RootInfo root, DocumentInfo dest) {
976 if (dest == null || !dest.isDirectory() || !dest.isCreateSupported()) {
977 return false;
978 }
Steve McKay3da8afc2015-05-05 14:50:00 -0700979
Steve McKay008e9482016-02-18 15:32:16 -0800980 // Can't copy folders to downloads, because we don't show folders there.
981 if (!root.isDownloads()) {
Steve McKay3da8afc2015-05-05 14:50:00 -0700982 for (DocumentInfo docs : files) {
983 if (docs.isDirectory()) {
984 return false;
985 }
986 }
987 }
988
Steve McKay4a1ca862016-02-17 18:25:47 -0800989 return true;
Steve McKay3da8afc2015-05-05 14:50:00 -0700990 }
991
Steve McKayf8621552015-11-03 15:23:16 -0800992 public void selectAllFiles() {
Ben Kwa862b96412015-12-07 13:25:27 -0800993 // Only select things currently visible in the adapter.
994 boolean changed = mSelectionManager.setItemsSelected(mAdapter.getModelIds(), true);
Steve McKayb04b1642015-07-24 13:14:20 -0700995 if (changed) {
996 updateDisplayState();
997 }
Steve McKay3da8afc2015-05-05 14:50:00 -0700998 }
999
Ben Kwa2036dad2016-02-10 07:46:35 -08001000 /**
1001 * Attempts to restore focus on the directory listing.
1002 */
1003 public void requestFocus() {
1004 mFocusManager.restoreLastFocus();
1005 }
1006
Vladislav Kaznacheev42a6bbc2015-05-01 14:18:57 -07001007 private void setupDragAndDropOnDocumentView(View view, Cursor cursor) {
1008 final String docMimeType = getCursorString(cursor, Document.COLUMN_MIME_TYPE);
1009 if (Document.MIME_TYPE_DIR.equals(docMimeType)) {
1010 // Make a directory item a drop target. Drop on non-directories and empty space
1011 // is handled at the list/grid view level.
1012 view.setOnDragListener(mOnDragListener);
1013 }
1014
Ben Kwa990489d2016-02-25 14:10:40 -08001015 // Make all items draggable.
Ben Kwae3dfebf2016-02-18 16:45:45 -08001016 view.setOnLongClickListener(mDragHelper);
Vladislav Kaznacheev42a6bbc2015-05-01 14:18:57 -07001017 }
1018
1019 private View.OnDragListener mOnDragListener = new View.OnDragListener() {
1020 @Override
1021 public boolean onDrag(View v, DragEvent event) {
1022 switch (event.getAction()) {
1023 case DragEvent.ACTION_DRAG_STARTED:
1024 // TODO: Check if the event contains droppable data.
1025 return true;
1026
Vladislav Kaznacheev42a6bbc2015-05-01 14:18:57 -07001027 // TODO: Expand drop target directory on hover?
1028 case DragEvent.ACTION_DRAG_ENTERED:
Ben Kwa1b685e52016-02-24 10:05:53 -08001029 setDropTargetHighlight(v, true);
Ben Kwae3dfebf2016-02-18 16:45:45 -08001030 return true;
Vladislav Kaznacheev42a6bbc2015-05-01 14:18:57 -07001031 case DragEvent.ACTION_DRAG_EXITED:
Ben Kwa1b685e52016-02-24 10:05:53 -08001032 setDropTargetHighlight(v, false);
Ben Kwae3dfebf2016-02-18 16:45:45 -08001033 return true;
1034
1035 case DragEvent.ACTION_DRAG_LOCATION:
Ben Kwa990489d2016-02-25 14:10:40 -08001036 return true;
1037
Vladislav Kaznacheev42a6bbc2015-05-01 14:18:57 -07001038 case DragEvent.ACTION_DRAG_ENDED:
Ben Kwa990489d2016-02-25 14:10:40 -08001039 if (event.getResult()) {
1040 // Exit selection mode if the drop was handled.
1041 mSelectionManager.clearSelection();
1042 }
Vladislav Kaznacheev42a6bbc2015-05-01 14:18:57 -07001043 return true;
1044
1045 case DragEvent.ACTION_DROP:
Ben Kwa990489d2016-02-25 14:10:40 -08001046 // After a drop event, always stop highlighting the target.
Ben Kwa1b685e52016-02-24 10:05:53 -08001047 setDropTargetHighlight(v, false);
Ben Kwa990489d2016-02-25 14:10:40 -08001048 // Don't copy from the cwd into the cwd. Note: this currently doesn't work for
1049 // multi-window drag, because localState isn't carried over from one process to
1050 // another.
1051 Object src = event.getLocalState();
1052 DocumentInfo dst = getDestination(v);
1053 if (Objects.equals(src, dst)) {
1054 return false;
1055 }
1056 copyFromClipData(event.getClipData(), dst);
Vladislav Kaznacheev42a6bbc2015-05-01 14:18:57 -07001057 return true;
1058 }
1059 return false;
1060 }
Ben Kwae3dfebf2016-02-18 16:45:45 -08001061
Ben Kwa990489d2016-02-25 14:10:40 -08001062 private DocumentInfo getDestination(View v) {
1063 String id = getModelId(v);
1064 if (id != null) {
1065 Cursor dstCursor = mModel.getItem(id);
Steve McKaya1f76802016-02-25 13:34:03 -08001066 assert(dstCursor != null);
Ben Kwa990489d2016-02-25 14:10:40 -08001067 return DocumentInfo.fromDirectoryCursor(dstCursor);
1068 }
1069
1070 if (v == mRecView || v == mEmptyView) {
1071 return getDisplayState().stack.peek();
1072 }
1073
1074 return null;
1075 }
1076
Ben Kwa1b685e52016-02-24 10:05:53 -08001077 private void setDropTargetHighlight(View v, boolean highlight) {
Ben Kwae3dfebf2016-02-18 16:45:45 -08001078 // Note: use exact comparison - this code is searching for views which are children of
1079 // the RecyclerView instance in the UI.
1080 if (v.getParent() == mRecView) {
1081 RecyclerView.ViewHolder vh = mRecView.getChildViewHolder(v);
1082 if (vh instanceof DocumentHolder) {
1083 ((DocumentHolder) vh).setHighlighted(highlight);
1084 }
1085 }
1086 }
Vladislav Kaznacheev42a6bbc2015-05-01 14:18:57 -07001087 };
1088
Ben Kwa003a9992015-11-30 23:00:02 -08001089 /**
1090 * Gets the model ID for a given motion event (using the event position)
1091 */
1092 private String getModelId(MotionEvent e) {
1093 View view = mRecView.findChildViewUnder(e.getX(), e.getY());
1094 if (view == null) {
1095 return null;
1096 }
1097 RecyclerView.ViewHolder vh = mRecView.getChildViewHolder(view);
1098 if (vh instanceof DocumentHolder) {
1099 return ((DocumentHolder) vh).modelId;
1100 } else {
1101 return null;
1102 }
1103 }
1104
1105 /**
1106 * Gets the model ID for a given RecyclerView item.
1107 * @param view A View that is a document item view, or a child of a document item view.
1108 * @return The Model ID for the given document, or null if the given view is not associated with
1109 * a document item view.
1110 */
1111 private String getModelId(View view) {
Ben Kwae3dfebf2016-02-18 16:45:45 -08001112 View itemView = mRecView.findContainingItemView(view);
1113 if (itemView != null) {
1114 RecyclerView.ViewHolder vh = mRecView.getChildViewHolder(itemView);
1115 if (vh instanceof DocumentHolder) {
1116 return ((DocumentHolder) vh).modelId;
Vladislav Kaznacheevb5999ef2015-09-04 09:17:37 -07001117 }
Vladislav Kaznacheevb5999ef2015-09-04 09:17:37 -07001118 }
Ben Kwae3dfebf2016-02-18 16:45:45 -08001119 return null;
Vladislav Kaznacheevb5999ef2015-09-04 09:17:37 -07001120 }
1121
Vladislav Kaznacheev42a6bbc2015-05-01 14:18:57 -07001122 private List<DocumentInfo> getDraggableDocuments(View currentItemView) {
Ben Kwa003a9992015-11-30 23:00:02 -08001123 String modelId = getModelId(currentItemView);
1124 if (modelId == null) {
Vladislav Kaznacheev42a6bbc2015-05-01 14:18:57 -07001125 return Collections.EMPTY_LIST;
1126 }
1127
Ben Kwa8250db42015-10-07 14:15:12 -07001128 final List<DocumentInfo> selectedDocs =
1129 mModel.getDocuments(mSelectionManager.getSelection());
Vladislav Kaznacheev42a6bbc2015-05-01 14:18:57 -07001130 if (!selectedDocs.isEmpty()) {
Ben Kwa003a9992015-11-30 23:00:02 -08001131 if (!isSelected(modelId)) {
Vladislav Kaznacheev42a6bbc2015-05-01 14:18:57 -07001132 // There is a selection that does not include the current item, drag nothing.
1133 return Collections.EMPTY_LIST;
1134 }
1135 return selectedDocs;
1136 }
1137
Ben Kwa003a9992015-11-30 23:00:02 -08001138 final Cursor cursor = mModel.getItem(modelId);
Steve McKay58efce32015-08-20 16:19:38 +00001139
Steve McKaya1f76802016-02-25 13:34:03 -08001140 assert(cursor != null);
1141
1142 return Lists.newArrayList(
1143 DocumentInfo.fromDirectoryCursor(cursor));
Vladislav Kaznacheev42a6bbc2015-05-01 14:18:57 -07001144 }
1145
1146 private Drawable getDragShadowIcon(List<DocumentInfo> docs) {
1147 if (docs.size() == 1) {
1148 final DocumentInfo doc = docs.get(0);
Ben Kwad8391492015-12-17 10:37:00 -08001149 return mIconHelper.getDocumentIcon(getActivity(), doc.authority, doc.documentId,
1150 doc.mimeType, doc.icon);
Vladislav Kaznacheev42a6bbc2015-05-01 14:18:57 -07001151 }
1152 return getActivity().getDrawable(R.drawable.ic_doc_generic);
1153 }
1154
Vladislav Kaznacheev42a6bbc2015-05-01 14:18:57 -07001155 private class DrawableShadowBuilder extends View.DragShadowBuilder {
1156
1157 private final Drawable mShadow;
1158
1159 private final int mShadowDimension;
1160
1161 public DrawableShadowBuilder(Drawable shadow) {
1162 mShadow = shadow;
1163 mShadowDimension = getResources().getDimensionPixelSize(
1164 R.dimen.drag_shadow_size);
1165 mShadow.setBounds(0, 0, mShadowDimension, mShadowDimension);
1166 }
1167
Ben Kwac64cb252015-08-27 16:04:46 -07001168 @Override
Vladislav Kaznacheev42a6bbc2015-05-01 14:18:57 -07001169 public void onProvideShadowMetrics(
1170 Point shadowSize, Point shadowTouchPoint) {
1171 shadowSize.set(mShadowDimension, mShadowDimension);
1172 shadowTouchPoint.set(mShadowDimension / 2, mShadowDimension / 2);
1173 }
1174
Ben Kwac64cb252015-08-27 16:04:46 -07001175 @Override
Vladislav Kaznacheev42a6bbc2015-05-01 14:18:57 -07001176 public void onDrawShadow(Canvas canvas) {
1177 mShadow.draw(canvas);
1178 }
1179 }
Steve McKaybdbd0ff2015-05-20 15:58:42 -07001180
Steve McKaybdbd0ff2015-05-20 15:58:42 -07001181 /**
Steve McKayab7865c2015-05-27 16:11:42 -07001182 * Abstract task providing support for loading documents *off*
1183 * the main thread. And if it isn't obvious, creating a list
1184 * of documents (especially large lists) can be pretty expensive.
1185 */
1186 private abstract class GetDocumentsTask
Steve McKay4b3a13c2015-06-11 10:10:49 -07001187 extends AsyncTask<Selection, Void, List<DocumentInfo>> {
Steve McKayab7865c2015-05-27 16:11:42 -07001188 @Override
Steve McKay4b3a13c2015-06-11 10:10:49 -07001189 protected final List<DocumentInfo> doInBackground(Selection... selected) {
Ben Kwac64cb252015-08-27 16:04:46 -07001190 return mModel.getDocuments(selected[0]);
Steve McKayab7865c2015-05-27 16:11:42 -07001191 }
1192
1193 @Override
1194 protected final void onPostExecute(List<DocumentInfo> docs) {
1195 onDocumentsReady(docs);
1196 }
1197
1198 abstract void onDocumentsReady(List<DocumentInfo> docs);
1199 }
1200
Steve McKayef16f5f2015-12-22 18:15:31 -08001201 @Override
1202 public boolean isSelected(String modelId) {
Ben Kwa743c7c22015-12-01 19:56:57 -08001203 return mSelectionManager.getSelection().contains(modelId);
Ben Kwa91caed82015-09-21 10:49:52 -07001204 }
Ben Kwa18fce3c2015-09-01 11:03:01 -07001205
Ben Kwa0436a752016-01-15 10:43:24 -08001206 private class ItemEventListener implements DocumentHolder.EventListener {
Ben Kwabd964562015-10-14 08:00:27 -07001207 @Override
Ben Kwa0436a752016-01-15 10:43:24 -08001208 public boolean onActivate(DocumentHolder doc) {
Ben Kwa67924892016-01-27 09:58:36 -08001209 // Toggle selection if we're in selection mode, othewise, view item.
1210 if (mSelectionManager.hasSelection()) {
1211 mSelectionManager.toggleSelection(doc.modelId);
1212 } else {
1213 handleViewItem(doc.modelId);
1214 }
Ben Kwa0436a752016-01-15 10:43:24 -08001215 return true;
1216 }
1217
1218 @Override
1219 public boolean onSelect(DocumentHolder doc) {
1220 mSelectionManager.toggleSelection(doc.modelId);
1221 mSelectionManager.setSelectionRangeBegin(doc.getAdapterPosition());
1222 return true;
Ben Kwabd964562015-10-14 08:00:27 -07001223 }
Ben Kwa67924892016-01-27 09:58:36 -08001224
1225 @Override
1226 public boolean onKey(DocumentHolder doc, int keyCode, KeyEvent event) {
1227 // Only handle key-down events. This is simpler, consistent with most other UIs, and
1228 // enables the handling of repeated key events from holding down a key.
1229 if (event.getAction() != KeyEvent.ACTION_DOWN) {
1230 return false;
1231 }
1232
Ben Kwa22937c92016-02-23 23:00:01 -08001233 // Ignore tab key events. Those should be handled by the top-level key handler.
1234 if (keyCode == KeyEvent.KEYCODE_TAB) {
1235 return false;
1236 }
1237
Ben Kwab0bfe2d2016-02-09 11:27:45 -08001238 if (mFocusManager.handleKey(doc, keyCode, event)) {
Ben Kwa83df50f2016-02-10 14:01:19 -08001239 // Handle range selection adjustments. Extending the selection will adjust the
1240 // bounds of the in-progress range selection. Each time an unshifted navigation
1241 // event is received, the range selection is restarted.
1242 if (shouldExtendSelection(event)) {
1243 if (!mSelectionManager.isRangeSelectionActive()) {
1244 // Start a range selection if one isn't active
1245 mSelectionManager.startRangeSelection(doc.getAdapterPosition());
1246 }
1247 mSelectionManager.snapRangeSelection(mFocusManager.getFocusPosition());
1248 } else {
1249 mSelectionManager.endRangeSelection();
1250 }
Ben Kwab0bfe2d2016-02-09 11:27:45 -08001251 return true;
Ben Kwa67924892016-01-27 09:58:36 -08001252 }
1253
Ben Kwab0bfe2d2016-02-09 11:27:45 -08001254 // Handle enter key events
1255 if (keyCode == KeyEvent.KEYCODE_ENTER) {
Ben Kwa09eb77b2016-02-10 08:57:25 -08001256 if (event.isShiftPressed()) {
1257 return onSelect(doc);
1258 } else {
1259 return onActivate(doc);
1260 }
Ben Kwab0bfe2d2016-02-09 11:27:45 -08001261 }
1262
1263 return false;
Ben Kwa67924892016-01-27 09:58:36 -08001264 }
Ben Kwa83df50f2016-02-10 14:01:19 -08001265
1266 private boolean shouldExtendSelection(KeyEvent event) {
1267 return Events.isNavigationKeyCode(event.getKeyCode()) &&
1268 event.isShiftPressed();
1269 }
Ben Kwabd964562015-10-14 08:00:27 -07001270 }
1271
Steve McKayef16f5f2015-12-22 18:15:31 -08001272 private final class ModelUpdateListener implements Model.UpdateListener {
Ben Kwa91caed82015-09-21 10:49:52 -07001273 @Override
1274 public void onModelUpdate(Model model) {
1275 if (model.info != null || model.error != null) {
1276 mMessageBar.setInfo(model.info);
1277 mMessageBar.setError(model.error);
1278 mMessageBar.show();
1279 }
Ben Kwa18fce3c2015-09-01 11:03:01 -07001280
Ben Kwa91caed82015-09-21 10:49:52 -07001281 mProgressBar.setVisibility(model.isLoading() ? View.VISIBLE : View.GONE);
1282
1283 if (model.isEmpty()) {
Aga Wronska893390b2016-02-17 13:50:42 -08001284 if (mSearchMode) {
Steve McKay9ed88a42016-01-21 18:46:15 -08001285 showNoResults(getDisplayState().stack.root);
1286 } else {
1287 showEmptyDirectory();
1288 }
Ben Kwa91caed82015-09-21 10:49:52 -07001289 } else {
Steve McKay9ed88a42016-01-21 18:46:15 -08001290 showDirectory();
Ben Kwa91bec532015-09-16 13:15:38 -07001291 mAdapter.notifyDataSetChanged();
Ben Kwa91caed82015-09-21 10:49:52 -07001292 }
Ben Kwa91caed82015-09-21 10:49:52 -07001293 }
1294
1295 @Override
1296 public void onModelUpdateFailed(Exception e) {
Steve McKay9ed88a42016-01-21 18:46:15 -08001297 showQueryError();
Ben Kwa18fce3c2015-09-01 11:03:01 -07001298 }
Ben Kwac64cb252015-08-27 16:04:46 -07001299 }
Ben Kwa0436a752016-01-15 10:43:24 -08001300
Ben Kwae3dfebf2016-02-18 16:45:45 -08001301 private DragStartHelper mDragHelper = new DragStartHelper(null) {
Steve McKay41585d52016-01-21 15:10:39 -08001302 @Override
Ben Kwae3dfebf2016-02-18 16:45:45 -08001303 protected boolean onDragStart(View v) {
1304 if (isSelected(getModelId(v))) {
Steve McKay41585d52016-01-21 15:10:39 -08001305 List<DocumentInfo> docs = getDraggableDocuments(v);
1306 if (docs.isEmpty()) {
1307 return false;
1308 }
Ben Kwa990489d2016-02-25 14:10:40 -08001309 v.startDragAndDrop(
1310 mClipper.getClipDataForDocuments(docs),
Steve McKay41585d52016-01-21 15:10:39 -08001311 new DrawableShadowBuilder(getDragShadowIcon(docs)),
Ben Kwa990489d2016-02-25 14:10:40 -08001312 getDisplayState().stack.peek(),
Steve McKay41585d52016-01-21 15:10:39 -08001313 View.DRAG_FLAG_GLOBAL | View.DRAG_FLAG_GLOBAL_URI_READ |
1314 View.DRAG_FLAG_GLOBAL_URI_WRITE
1315 );
1316 return true;
1317 }
1318
1319 return false;
1320 }
1321 };
1322
1323 // Previously we listened to events with one class, only to bounce them forward
1324 // to GestureDetector. We're still doing that here, but with a single class
1325 // that reduces overall complexity in our glue code.
1326 private static final class ListeningGestureDetector extends GestureDetector
1327 implements OnItemTouchListener {
1328
1329 private int mLastTool = -1;
Ben Kwae3dfebf2016-02-18 16:45:45 -08001330 private DragStartHelper mDragHelper;
Steve McKay41585d52016-01-21 15:10:39 -08001331
Ben Kwae3dfebf2016-02-18 16:45:45 -08001332 public ListeningGestureDetector(
1333 Context context, DragStartHelper dragHelper, GestureListener listener) {
Steve McKay41585d52016-01-21 15:10:39 -08001334 super(context, listener);
Ben Kwae3dfebf2016-02-18 16:45:45 -08001335 mDragHelper = dragHelper;
Steve McKay41585d52016-01-21 15:10:39 -08001336 setOnDoubleTapListener(listener);
1337 }
1338
1339 boolean mouseSpawnedLastEvent() {
1340 return Events.isMouseType(mLastTool);
1341 }
1342
1343 boolean touchSpawnedLastEvent() {
1344 return Events.isTouchType(mLastTool);
1345 }
1346
1347 @Override
1348 public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
1349 mLastTool = e.getToolType(0);
Ben Kwae3dfebf2016-02-18 16:45:45 -08001350
1351 // Detect drag events. When a drag is detected, intercept the rest of the gesture.
1352 View itemView = rv.findChildViewUnder(e.getX(), e.getY());
1353 if (itemView != null && mDragHelper.handleTouch(itemView, e)) {
1354 return true;
1355 }
1356 // Forward unhandled events to the GestureDetector.
1357 onTouchEvent(e);
1358
Steve McKay41585d52016-01-21 15:10:39 -08001359 return false;
1360 }
1361
1362 @Override
Ben Kwae3dfebf2016-02-18 16:45:45 -08001363 public void onTouchEvent(RecyclerView rv, MotionEvent e) {
1364 View itemView = rv.findChildViewUnder(e.getX(), e.getY());
1365 mDragHelper.handleTouch(itemView, e);
1366 // Note: even though this event is being handled as part of a drag gesture, continue
1367 // forwarding to the GestureDetector. The detector needs to see the entire cluster of
1368 // events in order to properly interpret gestures.
1369 onTouchEvent(e);
1370 }
Steve McKay41585d52016-01-21 15:10:39 -08001371
1372 @Override
1373 public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {}
1374 }
1375
Ben Kwa0436a752016-01-15 10:43:24 -08001376 /**
1377 * The gesture listener for items in the list/grid view. Interprets gestures and sends the
1378 * events to the target DocumentHolder, whence they are routed to the appropriate listener.
1379 */
1380 private class GestureListener extends GestureDetector.SimpleOnGestureListener {
1381 @Override
1382 public boolean onSingleTapUp(MotionEvent e) {
1383 // Single tap logic:
1384 // If the selection manager is active, it gets first whack at handling tap
1385 // events. Otherwise, tap events are routed to the target DocumentHolder.
1386 boolean handled = mSelectionManager.onSingleTapUp(
1387 new MotionInputEvent(e, mRecView));
1388
1389 if (handled) {
1390 return handled;
1391 }
1392
1393 // Give the DocumentHolder a crack at the event.
1394 DocumentHolder holder = getTarget(e);
1395 if (holder != null) {
1396 handled = holder.onSingleTapUp(e);
1397 }
1398
1399 return handled;
1400 }
1401
1402 @Override
1403 public void onLongPress(MotionEvent e) {
1404 // Long-press events get routed directly to the selection manager. They can be
1405 // changed to route through the DocumentHolder if necessary.
1406 mSelectionManager.onLongPress(new MotionInputEvent(e, mRecView));
1407 }
1408
1409 @Override
1410 public boolean onDoubleTap(MotionEvent e) {
1411 // Double-tap events are handled directly by the DirectoryFragment. They can be changed
1412 // to route through the DocumentHolder if necessary.
1413 return DirectoryFragment.this.onDoubleTap(e);
1414 }
1415
1416 private @Nullable DocumentHolder getTarget(MotionEvent e) {
1417 View childView = mRecView.findChildViewUnder(e.getX(), e.getY());
1418 if (childView != null) {
1419 return (DocumentHolder) mRecView.getChildViewHolder(childView);
1420 } else {
1421 return null;
1422 }
1423 }
1424 }
Steve McKay9ed88a42016-01-21 18:46:15 -08001425
1426 public static void showDirectory(
1427 FragmentManager fm, RootInfo root, DocumentInfo doc, int anim) {
Aga Wronska893390b2016-02-17 13:50:42 -08001428 create(fm, TYPE_NORMAL, root, doc, null, anim);
Steve McKay9ed88a42016-01-21 18:46:15 -08001429 }
1430
1431 public static void showRecentsOpen(FragmentManager fm, int anim) {
Aga Wronska893390b2016-02-17 13:50:42 -08001432 create(fm, TYPE_RECENT_OPEN, null, null, null, anim);
Steve McKay9ed88a42016-01-21 18:46:15 -08001433 }
1434
Aga Wronska893390b2016-02-17 13:50:42 -08001435 public static void reloadSearch(FragmentManager fm, RootInfo root, DocumentInfo doc,
1436 String query) {
1437 DirectoryFragment df = get(fm);
1438
1439 df.mQuery = query;
1440 df.mRoot = root;
1441 df.mDocument = doc;
1442 df.mSearchMode = query != null;
1443 df.getLoaderManager().restartLoader(LOADER_ID, null, df);
1444 }
1445
1446 public static void reload(FragmentManager fm, int type, RootInfo root, DocumentInfo doc,
1447 String query) {
1448 DirectoryFragment df = get(fm);
1449 df.mType = type;
1450 df.mQuery = query;
1451 df.mRoot = root;
1452 df.mDocument = doc;
1453 df.mSearchMode = query != null;
1454 df.getLoaderManager().restartLoader(LOADER_ID, null, df);
1455 }
1456
1457 public static void create(FragmentManager fm, int type, RootInfo root, DocumentInfo doc,
Steve McKay9ed88a42016-01-21 18:46:15 -08001458 String query, int anim) {
1459 final Bundle args = new Bundle();
Aga Wronska893390b2016-02-17 13:50:42 -08001460 args.putInt(Shared.EXTRA_TYPE, type);
1461 args.putParcelable(Shared.EXTRA_ROOT, root);
1462 args.putParcelable(Shared.EXTRA_DOC, doc);
1463 args.putString(Shared.EXTRA_QUERY, query);
Aga Wronskad5597432016-02-26 11:36:07 -08001464 args.putParcelable(Shared.EXTRA_SELECTION, new Selection());
Steve McKay9ed88a42016-01-21 18:46:15 -08001465
1466 final FragmentTransaction ft = fm.beginTransaction();
1467 switch (anim) {
1468 case ANIM_SIDE:
Aga Wronska893390b2016-02-17 13:50:42 -08001469 args.putBoolean(Shared.EXTRA_IGNORE_STATE, true);
Steve McKay9ed88a42016-01-21 18:46:15 -08001470 break;
Tomasz Mikolajewskie3fe9d72016-02-03 16:53:21 +09001471 case ANIM_ENTER:
Aga Wronska893390b2016-02-17 13:50:42 -08001472 args.putBoolean(Shared.EXTRA_IGNORE_STATE, true);
Tomasz Mikolajewskie3fe9d72016-02-03 16:53:21 +09001473 ft.setCustomAnimations(R.animator.dir_enter, R.animator.dir_frozen);
Steve McKay9ed88a42016-01-21 18:46:15 -08001474 break;
Tomasz Mikolajewskie3fe9d72016-02-03 16:53:21 +09001475 case ANIM_LEAVE:
1476 ft.setCustomAnimations(R.animator.dir_frozen, R.animator.dir_leave);
Steve McKay9ed88a42016-01-21 18:46:15 -08001477 break;
1478 }
1479
1480 final DirectoryFragment fragment = new DirectoryFragment();
1481 fragment.setArguments(args);
1482
Aga Wronska893390b2016-02-17 13:50:42 -08001483 ft.replace(getFragmentId(), fragment);
Steve McKay9ed88a42016-01-21 18:46:15 -08001484 ft.commitAllowingStateLoss();
1485 }
1486
1487 private static String buildStateKey(RootInfo root, DocumentInfo doc) {
1488 final StringBuilder builder = new StringBuilder();
1489 builder.append(root != null ? root.authority : "null").append(';');
1490 builder.append(root != null ? root.rootId : "null").append(';');
1491 builder.append(doc != null ? doc.documentId : "null");
1492 return builder.toString();
1493 }
1494
1495 public static @Nullable DirectoryFragment get(FragmentManager fm) {
1496 // TODO: deal with multiple directories shown at once
Aga Wronska893390b2016-02-17 13:50:42 -08001497 Fragment fragment = fm.findFragmentById(getFragmentId());
Steve McKay9ed88a42016-01-21 18:46:15 -08001498 return fragment instanceof DirectoryFragment
1499 ? (DirectoryFragment) fragment
1500 : null;
1501 }
Aga Wronska893390b2016-02-17 13:50:42 -08001502
1503 private static int getFragmentId() {
1504 return R.id.container_directory;
1505 }
1506
1507 @Override
1508 public Loader<DirectoryResult> onCreateLoader(int id, Bundle args) {
1509 Context context = getActivity();
1510 State state = getDisplayState();
1511
1512 Uri contentsUri;
1513 switch (mType) {
1514 case TYPE_NORMAL:
1515 contentsUri = mSearchMode ? DocumentsContract.buildSearchDocumentsUri(
1516 mRoot.authority, mRoot.rootId, mQuery)
1517 : DocumentsContract.buildChildDocumentsUri(
1518 mDocument.authority, mDocument.documentId);
1519 if (state.action == ACTION_MANAGE) {
1520 contentsUri = DocumentsContract.setManageMode(contentsUri);
1521 }
1522 return new DirectoryLoader(
Steve McKay27d20a32016-02-22 18:38:09 -08001523 context, mType, mRoot, mDocument, contentsUri, state.userSortOrder,
1524 mSearchMode);
Aga Wronska893390b2016-02-17 13:50:42 -08001525 case TYPE_RECENT_OPEN:
1526 final RootsCache roots = DocumentsApplication.getRootsCache(context);
1527 return new RecentsLoader(context, roots, state);
1528 default:
1529 throw new IllegalStateException("Unknown type " + mType);
1530 }
1531 }
1532
1533 @Override
1534 public void onLoadFinished(Loader<DirectoryResult> loader, DirectoryResult result) {
1535 if (!isAdded()) return;
1536
1537 State state = getDisplayState();
1538
1539 mAdapter.notifyDataSetChanged();
1540 mModel.update(result);
1541
1542 state.derivedSortOrder = result.sortOrder;
1543
1544 updateLayout(state.derivedMode);
1545
1546 if (mSelection != null) {
1547 mSelectionManager.setItemsSelected(mSelection.toList(), true);
1548 }
1549
1550 // Restore any previous instance state
1551 final SparseArray<Parcelable> container = state.dirState.remove(mStateKey);
1552 if (container != null && !getArguments().getBoolean(Shared.EXTRA_IGNORE_STATE, false)) {
1553 getView().restoreHierarchyState(container);
1554 } else if (mLastSortOrder != state.derivedSortOrder) {
1555 // The derived sort order takes the user sort order into account, but applies
1556 // directory-specific defaults when the user doesn't explicitly set the sort
1557 // order. Scroll to the top if the sort order actually changed.
1558 mRecView.smoothScrollToPosition(0);
1559 }
1560
1561 mLastSortOrder = state.derivedSortOrder;
1562
1563 mTuner.onModelLoaded(mModel, mType, mSearchMode);
1564
1565 }
1566
1567 @Override
1568 public void onLoaderReset(Loader<DirectoryResult> loader) {
1569 mModel.update(null);
1570 }
1571 }