Fix for 4.0 file action context menu (re-implement it via DialogFragment)
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / fragment / OCFileListFragment.java
1 /**
2 * ownCloud Android client application
3 *
4 * @author Bartek Przybylski
5 * @author masensio
6 * @author David A. Velasco
7 * Copyright (C) 2011 Bartek Przybylski
8 * Copyright (C) 2015 ownCloud Inc.
9 *
10 * This program is free software: you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License version 2,
12 * as published by the Free Software Foundation.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 *
22 */
23 package com.owncloud.android.ui.fragment;
24
25 import java.io.File;
26
27 import android.app.Activity;
28 import android.content.Intent;
29 import android.os.Bundle;
30 import android.support.v4.widget.SwipeRefreshLayout;
31 import android.view.ContextMenu;
32 import android.view.Menu;
33 import android.view.MenuInflater;
34 import android.view.MenuItem;
35 import android.view.View;
36 import android.widget.AdapterView;
37 import android.widget.AdapterView.AdapterContextMenuInfo;
38 import android.widget.PopupMenu;
39
40 import com.owncloud.android.R;
41 import com.owncloud.android.authentication.AccountUtils;
42 import com.owncloud.android.datamodel.FileDataStorageManager;
43 import com.owncloud.android.datamodel.OCFile;
44 import com.owncloud.android.files.FileMenuFilter;
45 import com.owncloud.android.lib.common.utils.Log_OC;
46 import com.owncloud.android.lib.resources.status.OwnCloudVersion;
47 import com.owncloud.android.ui.activity.FileActivity;
48 import com.owncloud.android.ui.activity.FileDisplayActivity;
49 import com.owncloud.android.ui.activity.FolderPickerActivity;
50 import com.owncloud.android.ui.activity.OnEnforceableRefreshListener;
51 import com.owncloud.android.ui.adapter.FileListListAdapter;
52 import com.owncloud.android.ui.dialog.ConfirmationDialogFragment;
53 import com.owncloud.android.ui.dialog.FileActionsDialogFragment;
54 import com.owncloud.android.ui.dialog.RemoveFileDialogFragment;
55 import com.owncloud.android.ui.dialog.RenameFileDialogFragment;
56 import com.owncloud.android.ui.preview.PreviewImageFragment;
57 import com.owncloud.android.ui.preview.PreviewMediaFragment;
58 import com.owncloud.android.utils.DialogMenuItem;
59 import com.owncloud.android.utils.FileStorageUtils;
60
61 /**
62 * A Fragment that lists all files and folders in a given path.
63 *
64 * TODO refactor to get rid of direct dependency on FileDisplayActivity
65 */
66 public class OCFileListFragment extends ExtendedListFragment implements FileActionsDialogFragment.FileActionsDialogFragmentListener {
67
68 private static final String TAG = OCFileListFragment.class.getSimpleName();
69
70 private static final String MY_PACKAGE = OCFileListFragment.class.getPackage() != null ?
71 OCFileListFragment.class.getPackage().getName() : "com.owncloud.android.ui.fragment";
72
73 public final static String ARG_JUST_FOLDERS = MY_PACKAGE + ".JUST_FOLDERS";
74 public final static String ARG_ALLOW_CONTEXTUAL_ACTIONS = MY_PACKAGE + ".ALLOW_CONTEXTUAL";
75
76 private static final String KEY_FILE = MY_PACKAGE + ".extra.FILE";
77
78 private FileFragment.ContainerActivity mContainerActivity;
79
80 private OCFile mFile = null;
81 private FileListListAdapter mAdapter;
82 private boolean mJustFolders;
83
84 private OCFile mTargetFile;
85
86
87
88 /**
89 * {@inheritDoc}
90 */
91 @Override
92 public void onAttach(Activity activity) {
93 super.onAttach(activity);
94 Log_OC.e(TAG, "onAttach");
95 try {
96 mContainerActivity = (FileFragment.ContainerActivity) activity;
97
98 } catch (ClassCastException e) {
99 throw new ClassCastException(activity.toString() + " must implement " +
100 FileFragment.ContainerActivity.class.getSimpleName());
101 }
102 try {
103 setOnRefreshListener((OnEnforceableRefreshListener) activity);
104
105 } catch (ClassCastException e) {
106 throw new ClassCastException(activity.toString() + " must implement " +
107 SwipeRefreshLayout.OnRefreshListener.class.getSimpleName());
108 }
109 }
110
111
112 @Override
113 public void onDetach() {
114 setOnRefreshListener(null);
115 mContainerActivity = null;
116 super.onDetach();
117 }
118
119 /**
120 * {@inheritDoc}
121 */
122 @Override
123 public void onActivityCreated(Bundle savedInstanceState) {
124 super.onActivityCreated(savedInstanceState);
125 Log_OC.e(TAG, "onActivityCreated() start");
126
127 if (savedInstanceState != null) {
128 mFile = savedInstanceState.getParcelable(KEY_FILE);
129 }
130
131 if (mJustFolders) {
132 setFooterEnabled(false);
133 } else {
134 setFooterEnabled(true);
135 }
136
137 Bundle args = getArguments();
138 mJustFolders = (args == null) ? false : args.getBoolean(ARG_JUST_FOLDERS, false);
139 mAdapter = new FileListListAdapter(
140 mJustFolders,
141 getActivity(),
142 mContainerActivity
143 );
144 setListAdapter(mAdapter);
145
146 registerLongClickListener();
147 }
148
149 private void registerLongClickListener() {
150 getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
151 public boolean onItemLongClick(AdapterView<?> arg0, View v,
152 int index, long arg3) {
153 showFileAction(index);
154 return true;
155 }
156 });
157 }
158
159
160 private void showFileAction(int fileIndex) {
161 Bundle args = getArguments();
162 PopupMenu pm = new PopupMenu(getActivity(),null);
163 Menu menu = pm.getMenu();
164
165 boolean allowContextualActions =
166 (args == null) ? true : args.getBoolean(ARG_ALLOW_CONTEXTUAL_ACTIONS, true);
167
168 if (allowContextualActions) {
169 MenuInflater inflater = getActivity().getMenuInflater();
170
171 inflater.inflate(R.menu.file_actions_menu, menu);
172 OCFile targetFile = (OCFile) mAdapter.getItem(fileIndex);
173
174 if (mContainerActivity.getStorageManager() != null) {
175 FileMenuFilter mf = new FileMenuFilter(
176 targetFile,
177 mContainerActivity.getStorageManager().getAccount(),
178 mContainerActivity,
179 getActivity()
180 );
181 mf.filter(menu);
182 }
183
184 /// TODO break this direct dependency on FileDisplayActivity... if possible
185 MenuItem item = menu.findItem(R.id.action_open_file_with);
186 FileFragment frag = ((FileDisplayActivity)getActivity()).getSecondFragment();
187 if (frag != null && frag instanceof FileDetailFragment &&
188 frag.getFile().getFileId() == targetFile.getFileId()) {
189 item = menu.findItem(R.id.action_see_details);
190 if (item != null) {
191 item.setVisible(false);
192 item.setEnabled(false);
193 }
194 }
195
196 MenuItem menuItem = new DialogMenuItem(item.getItemId());
197 FileActionsDialogFragment dialog = FileActionsDialogFragment.newInstance(menu, fileIndex);
198 dialog.setTargetFragment(this, 0);
199 dialog.show(getFragmentManager(), FileActionsDialogFragment.FTAG_FILE_ACTIONS);
200 }
201 }
202
203 /**
204 * Saves the current listed folder.
205 */
206 @Override
207 public void onSaveInstanceState (Bundle outState) {
208 super.onSaveInstanceState(outState);
209 outState.putParcelable(KEY_FILE, mFile);
210 }
211
212 /**
213 * Call this, when the user presses the up button.
214 *
215 * Tries to move up the current folder one level. If the parent folder was removed from the
216 * database, it continues browsing up until finding an existing folders.
217 *
218 * return Count of folder levels browsed up.
219 */
220 public int onBrowseUp() {
221 OCFile parentDir = null;
222 int moveCount = 0;
223
224 if(mFile != null){
225 FileDataStorageManager storageManager = mContainerActivity.getStorageManager();
226
227 String parentPath = null;
228 if (mFile.getParentId() != FileDataStorageManager.ROOT_PARENT_ID) {
229 parentPath = new File(mFile.getRemotePath()).getParent();
230 parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath :
231 parentPath + OCFile.PATH_SEPARATOR;
232 parentDir = storageManager.getFileByPath(parentPath);
233 moveCount++;
234 } else {
235 parentDir = storageManager.getFileByPath(OCFile.ROOT_PATH);
236 }
237 while (parentDir == null) {
238 parentPath = new File(parentPath).getParent();
239 parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath :
240 parentPath + OCFile.PATH_SEPARATOR;
241 parentDir = storageManager.getFileByPath(parentPath);
242 moveCount++;
243 } // exit is granted because storageManager.getFileByPath("/") never returns null
244 mFile = parentDir;
245
246 // TODO Enable when "On Device" is recovered ?
247 listDirectory(mFile /*, MainApp.getOnlyOnDevice()*/);
248
249 onRefresh(false);
250
251 // restore index and top position
252 restoreIndexAndTopPosition();
253
254 } // else - should never happen now
255
256 return moveCount;
257 }
258
259 @Override
260 public void onItemClick(AdapterView<?> l, View v, int position, long id) {
261 OCFile file = (OCFile) mAdapter.getItem(position);
262 if (file != null) {
263 if (file.isFolder()) {
264 // update state and view of this fragment
265 // TODO Enable when "On Device" is recovered ?
266 listDirectory(file/*, MainApp.getOnlyOnDevice()*/);
267 // then, notify parent activity to let it update its state and view
268 mContainerActivity.onBrowsedDownTo(file);
269 // save index and top position
270 saveIndexAndTopPosition(position);
271
272 } else { /// Click on a file
273 if (PreviewImageFragment.canBePreviewed(file)) {
274 // preview image - it handles the download, if needed
275 ((FileDisplayActivity)mContainerActivity).startImagePreview(file);
276
277 } else if (file.isDown()) {
278 if (PreviewMediaFragment.canBePreviewed(file)) {
279 // media preview
280 ((FileDisplayActivity)mContainerActivity).startMediaPreview(file, 0, true);
281 } else {
282 mContainerActivity.getFileOperationsHelper().openFile(file);
283 }
284
285 } else {
286 // automatic download, preview on finish
287 ((FileDisplayActivity)mContainerActivity).startDownloadForPreview(file);
288 }
289
290 }
291
292 } else {
293 Log_OC.d(TAG, "Null object in ListAdapter!!");
294 }
295
296 }
297
298 /**
299 * {@inheritDoc}
300 */
301 @Override
302 public void onCreateContextMenu (
303 ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
304 Bundle args = getArguments();
305 boolean allowContextualActions =
306 (args == null) ? true : args.getBoolean(ARG_ALLOW_CONTEXTUAL_ACTIONS, true);
307 if (allowContextualActions) {
308 MenuInflater inflater = getActivity().getMenuInflater();
309 inflater.inflate(R.menu.file_actions_menu, menu);
310 AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
311 OCFile targetFile = (OCFile) mAdapter.getItem(info.position);
312
313 if (mContainerActivity.getStorageManager() != null) {
314 FileMenuFilter mf = new FileMenuFilter(
315 targetFile,
316 mContainerActivity.getStorageManager().getAccount(),
317 mContainerActivity,
318 getActivity()
319 );
320 mf.filter(menu);
321 }
322
323 /// TODO break this direct dependency on FileDisplayActivity... if possible
324 MenuItem item = menu.findItem(R.id.action_open_file_with);
325 FileFragment frag = ((FileDisplayActivity)getActivity()).getSecondFragment();
326 if (frag != null && frag instanceof FileDetailFragment &&
327 frag.getFile().getFileId() == targetFile.getFileId()) {
328 item = menu.findItem(R.id.action_see_details);
329 if (item != null) {
330 item.setVisible(false);
331 item.setEnabled(false);
332 }
333 }
334 }
335 }
336
337 @Override
338 public boolean onFileActionChosen(int menuId, int filePosition) {
339 mTargetFile = (OCFile) mAdapter.getItem(filePosition);
340 switch (menuId) {
341 case R.id.action_share_file: {
342 mContainerActivity.getFileOperationsHelper().shareFileWithLink(mTargetFile);
343 return true;
344 }
345 case R.id.action_open_file_with: {
346 mContainerActivity.getFileOperationsHelper().openFile(mTargetFile);
347 return true;
348 }
349 case R.id.action_unshare_file: {
350 mContainerActivity.getFileOperationsHelper().unshareFileWithLink(mTargetFile);
351 return true;
352 }
353 case R.id.action_rename_file: {
354 RenameFileDialogFragment dialog = RenameFileDialogFragment.newInstance(mTargetFile);
355 dialog.show(getFragmentManager(), FileDetailFragment.FTAG_RENAME_FILE);
356 return true;
357 }
358 case R.id.action_remove_file: {
359 RemoveFileDialogFragment dialog = RemoveFileDialogFragment.newInstance(mTargetFile);
360 dialog.show(getFragmentManager(), ConfirmationDialogFragment.FTAG_CONFIRMATION);
361 return true;
362 }
363 case R.id.action_download_file:
364 case R.id.action_sync_file: {
365 mContainerActivity.getFileOperationsHelper().syncFile(mTargetFile);
366 return true;
367 }
368 case R.id.action_cancel_download:
369 case R.id.action_cancel_upload: {
370 ((FileDisplayActivity) mContainerActivity).cancelTransference(mTargetFile);
371 return true;
372 }
373 case R.id.action_see_details: {
374 mContainerActivity.showDetails(mTargetFile);
375 return true;
376 }
377 case R.id.action_send_file: {
378 // Obtain the file
379 if (!mTargetFile.isDown()) { // Download the file
380 Log_OC.d(TAG, mTargetFile.getRemotePath() + " : File must be downloaded");
381 ((FileDisplayActivity) mContainerActivity).startDownloadForSending(mTargetFile);
382
383 } else {
384 mContainerActivity.getFileOperationsHelper().sendDownloadedFile(mTargetFile);
385 }
386 return true;
387 }
388 case R.id.action_move: {
389 Intent action = new Intent(getActivity(), FolderPickerActivity.class);
390
391 // Pass mTargetFile that contains info of selected file/folder
392 action.putExtra(FolderPickerActivity.EXTRA_FILE, mTargetFile);
393 getActivity().startActivityForResult(action, FileDisplayActivity.ACTION_MOVE_FILES);
394 return true;
395 }
396 case R.id.action_favorite_file: {
397 mContainerActivity.getFileOperationsHelper().toggleFavorite(mTargetFile, true);
398 return true;
399 }
400 case R.id.action_unfavorite_file: {
401 mContainerActivity.getFileOperationsHelper().toggleFavorite(mTargetFile, false);
402 return true;
403 }
404 default:
405 return false;
406 }
407 }
408
409 /**
410 * {@inhericDoc}
411 */
412 @Override
413 public boolean onContextItemSelected (MenuItem item) {
414 AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
415 boolean matched = onFileActionChosen(item.getItemId(), ((AdapterContextMenuInfo) item.getMenuInfo()).position);
416 if(!matched) {
417 return super.onContextItemSelected(item);
418 } else {
419 return matched;
420 }
421 }
422
423
424 /**
425 * Use this to query the {@link OCFile} that is currently
426 * being displayed by this fragment
427 * @return The currently viewed OCFile
428 */
429 public OCFile getCurrentFile(){
430 return mFile;
431 }
432
433 /**
434 * Calls {@link OCFileListFragment#listDirectory(OCFile)} with a null parameter
435 */
436 public void listDirectory(/*boolean onlyOnDevice*/){
437 listDirectory(null);
438 // TODO Enable when "On Device" is recovered ?
439 // listDirectory(null, onlyOnDevice);
440 }
441
442 public void refreshDirectory(){
443 // TODO Enable when "On Device" is recovered ?
444 listDirectory(getCurrentFile()/*, MainApp.getOnlyOnDevice()*/);
445 }
446
447 /**
448 * Lists the given directory on the view. When the input parameter is null,
449 * it will either refresh the last known directory. list the root
450 * if there never was a directory.
451 *
452 * @param directory File to be listed
453 */
454 public void listDirectory(OCFile directory/*, boolean onlyOnDevice*/) {
455 FileDataStorageManager storageManager = mContainerActivity.getStorageManager();
456 if (storageManager != null) {
457
458 // Check input parameters for null
459 if(directory == null){
460 if(mFile != null){
461 directory = mFile;
462 } else {
463 directory = storageManager.getFileByPath("/");
464 if (directory == null) return; // no files, wait for sync
465 }
466 }
467
468
469 // If that's not a directory -> List its parent
470 if(!directory.isFolder()){
471 Log_OC.w(TAG, "You see, that is not a directory -> " + directory.toString());
472 directory = storageManager.getFileById(directory.getParentId());
473 }
474
475 // TODO Enable when "On Device" is recovered ?
476 mAdapter.swapDirectory(directory, storageManager/*, onlyOnDevice*/);
477 if (mFile == null || !mFile.equals(directory)) {
478 mCurrentListView.setSelection(0);
479 }
480 mFile = directory;
481
482 updateLayout();
483
484 }
485 }
486
487 private void updateLayout() {
488 if (!mJustFolders) {
489 int filesCount = 0, foldersCount = 0, imagesCount = 0;
490 int count = mAdapter.getCount();
491 OCFile file;
492 for (int i=0; i < count ; i++) {
493 file = (OCFile) mAdapter.getItem(i);
494 if (file.isFolder()) {
495 foldersCount++;
496 } else {
497 filesCount++;
498 if (file.isImage()){
499 imagesCount++;
500 }
501 }
502 }
503 // set footer text
504 setFooterText(generateFooterText(filesCount, foldersCount));
505
506 // decide grid vs list view
507 OwnCloudVersion version = AccountUtils.getServerVersion(
508 ((FileActivity)mContainerActivity).getAccount());
509 if (version != null && version.supportsRemoteThumbnails() &&
510 imagesCount > 0 && imagesCount == filesCount) {
511 switchToGridView();
512 registerLongClickListener();
513 } else {
514 switchToListView();
515 }
516 }
517 }
518
519 private String generateFooterText(int filesCount, int foldersCount) {
520 String output;
521 if (filesCount <= 0) {
522 if (foldersCount <= 0) {
523 output = "";
524
525 } else if (foldersCount == 1) {
526 output = getResources().getString(R.string.file_list__footer__folder);
527
528 } else { // foldersCount > 1
529 output = getResources().getString(R.string.file_list__footer__folders, foldersCount);
530 }
531
532 } else if (filesCount == 1) {
533 if (foldersCount <= 0) {
534 output = getResources().getString(R.string.file_list__footer__file);
535
536 } else if (foldersCount == 1) {
537 output = getResources().getString(R.string.file_list__footer__file_and_folder);
538
539 } else { // foldersCount > 1
540 output = getResources().getString(R.string.file_list__footer__file_and_folders, foldersCount);
541 }
542 } else { // filesCount > 1
543 if (foldersCount <= 0) {
544 output = getResources().getString(R.string.file_list__footer__files, filesCount);
545
546 } else if (foldersCount == 1) {
547 output = getResources().getString(R.string.file_list__footer__files_and_folder, filesCount);
548
549 } else { // foldersCount > 1
550 output = getResources().getString(
551 R.string.file_list__footer__files_and_folders, filesCount, foldersCount
552 );
553
554 }
555 }
556 return output;
557 }
558
559 public void sortByName(boolean descending) {
560 mAdapter.setSortOrder(FileStorageUtils.SORT_NAME, descending);
561 }
562
563 public void sortByDate(boolean descending) {
564 mAdapter.setSortOrder(FileStorageUtils.SORT_DATE, descending);
565 }
566
567 public void sortBySize(boolean descending) {
568 mAdapter.setSortOrder(FileStorageUtils.SORT_SIZE, descending);
569 }
570 }