updated readme
[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 android.app.Activity;
26 import android.content.Intent;
27 import android.os.Bundle;
28 import android.support.v4.widget.SwipeRefreshLayout;
29 import android.view.ContextMenu;
30 import android.view.Menu;
31 import android.view.MenuInflater;
32 import android.view.MenuItem;
33 import android.view.View;
34 import android.widget.AdapterView;
35 import android.widget.AdapterView.AdapterContextMenuInfo;
36 import android.widget.PopupMenu;
37
38 import com.owncloud.android.R;
39 import com.owncloud.android.authentication.AccountUtils;
40 import com.owncloud.android.datamodel.FileDataStorageManager;
41 import com.owncloud.android.datamodel.OCFile;
42 import com.owncloud.android.files.FileMenuFilter;
43 import com.owncloud.android.lib.common.utils.Log_OC;
44 import com.owncloud.android.lib.resources.status.OwnCloudVersion;
45 import com.owncloud.android.ui.activity.FileActivity;
46 import com.owncloud.android.ui.activity.FileDisplayActivity;
47 import com.owncloud.android.ui.activity.FolderPickerActivity;
48 import com.owncloud.android.ui.activity.OnEnforceableRefreshListener;
49 import com.owncloud.android.ui.adapter.FileListListAdapter;
50 import com.owncloud.android.ui.dialog.ConfirmationDialogFragment;
51 import com.owncloud.android.ui.dialog.FileActionsDialogFragment;
52 import com.owncloud.android.ui.dialog.RemoveFileDialogFragment;
53 import com.owncloud.android.ui.dialog.RenameFileDialogFragment;
54 import com.owncloud.android.ui.preview.PreviewImageFragment;
55 import com.owncloud.android.ui.preview.PreviewMediaFragment;
56 import com.owncloud.android.utils.FileStorageUtils;
57 import com.owncloud.android.ui.preview.PreviewTextFragment;
58
59 import java.io.File;
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 FileActionsDialogFragment dialog = FileActionsDialogFragment.newInstance(menu, fileIndex, targetFile.getFileName());
197 dialog.setTargetFragment(this, 0);
198 dialog.show(getFragmentManager(), FileActionsDialogFragment.FTAG_FILE_ACTIONS);
199 }
200 }
201
202 /**
203 * Saves the current listed folder.
204 */
205 @Override
206 public void onSaveInstanceState(Bundle outState) {
207 super.onSaveInstanceState(outState);
208 outState.putParcelable(KEY_FILE, mFile);
209 }
210
211 /**
212 * Call this, when the user presses the up button.
213 *
214 * Tries to move up the current folder one level. If the parent folder was removed from the
215 * database, it continues browsing up until finding an existing folders.
216 * <p/>
217 * return Count of folder levels browsed up.
218 */
219 public int onBrowseUp() {
220 OCFile parentDir = null;
221 int moveCount = 0;
222
223 if (mFile != null) {
224 FileDataStorageManager storageManager = mContainerActivity.getStorageManager();
225
226 String parentPath = null;
227 if (mFile.getParentId() != FileDataStorageManager.ROOT_PARENT_ID) {
228 parentPath = new File(mFile.getRemotePath()).getParent();
229 parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath :
230 parentPath + OCFile.PATH_SEPARATOR;
231 parentDir = storageManager.getFileByPath(parentPath);
232 moveCount++;
233 } else {
234 parentDir = storageManager.getFileByPath(OCFile.ROOT_PATH);
235 }
236 while (parentDir == null) {
237 parentPath = new File(parentPath).getParent();
238 parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath :
239 parentPath + OCFile.PATH_SEPARATOR;
240 parentDir = storageManager.getFileByPath(parentPath);
241 moveCount++;
242 } // exit is granted because storageManager.getFileByPath("/") never returns null
243 mFile = parentDir;
244
245 // TODO Enable when "On Device" is recovered ?
246 listDirectory(mFile /*, MainApp.getOnlyOnDevice()*/);
247
248 onRefresh(false);
249
250 // restore index and top position
251 restoreIndexAndTopPosition();
252
253 } // else - should never happen now
254
255 return moveCount;
256 }
257
258 @Override
259 public void onItemClick(AdapterView<?> l, View v, int position, long id) {
260 OCFile file = (OCFile) mAdapter.getItem(position);
261 if (file != null) {
262 if (file.isFolder()) {
263 // update state and view of this fragment
264 // TODO Enable when "On Device" is recovered ?
265 listDirectory(file/*, MainApp.getOnlyOnDevice()*/);
266 // then, notify parent activity to let it update its state and view
267 mContainerActivity.onBrowsedDownTo(file);
268 // save index and top position
269 saveIndexAndTopPosition(position);
270
271 } else { /// Click on a file
272 if (PreviewImageFragment.canBePreviewed(file)) {
273 // preview image - it handles the download, if needed
274 ((FileDisplayActivity)mContainerActivity).startImagePreview(file);
275 } else if (PreviewTextFragment.canBePreviewed(file)){
276 ((FileDisplayActivity)mContainerActivity).startTextPreview(file);
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 }
286 }
287
288 } else {
289 Log_OC.d(TAG, "Null object in ListAdapter!!");
290 }
291
292 }
293
294 /**
295 * {@inheritDoc}
296 */
297 @Override
298 public void onCreateContextMenu(
299 ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
300 Bundle args = getArguments();
301 boolean allowContextualActions =
302 (args == null) ? true : args.getBoolean(ARG_ALLOW_CONTEXTUAL_ACTIONS, true);
303 if (allowContextualActions) {
304 MenuInflater inflater = getActivity().getMenuInflater();
305 inflater.inflate(R.menu.file_actions_menu, menu);
306 AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
307 OCFile targetFile = (OCFile) mAdapter.getItem(info.position);
308
309 if (mContainerActivity.getStorageManager() != null) {
310 FileMenuFilter mf = new FileMenuFilter(
311 targetFile,
312 mContainerActivity.getStorageManager().getAccount(),
313 mContainerActivity,
314 getActivity()
315 );
316 mf.filter(menu);
317 }
318
319 /// TODO break this direct dependency on FileDisplayActivity... if possible
320 MenuItem item = menu.findItem(R.id.action_open_file_with);
321 FileFragment frag = ((FileDisplayActivity)getActivity()).getSecondFragment();
322 if (frag != null && frag instanceof FileDetailFragment &&
323 frag.getFile().getFileId() == targetFile.getFileId()) {
324 item = menu.findItem(R.id.action_see_details);
325 if (item != null) {
326 item.setVisible(false);
327 item.setEnabled(false);
328 }
329 }
330 }
331 }
332
333 /**
334 * {@inheritDoc}
335 */
336 @Override
337 public boolean onFileActionChosen(int menuId, int filePosition) {
338 mTargetFile = (OCFile) mAdapter.getItem(filePosition);
339 switch (menuId) {
340 case R.id.action_share_file: {
341 mContainerActivity.getFileOperationsHelper().shareFileWithLink(mTargetFile);
342 return true;
343 }
344 case R.id.action_open_file_with: {
345 mContainerActivity.getFileOperationsHelper().openFile(mTargetFile);
346 return true;
347 }
348 case R.id.action_unshare_file: {
349 mContainerActivity.getFileOperationsHelper().unshareFileWithLink(mTargetFile);
350 return true;
351 }
352 case R.id.action_rename_file: {
353 RenameFileDialogFragment dialog = RenameFileDialogFragment.newInstance(mTargetFile);
354 dialog.show(getFragmentManager(), FileDetailFragment.FTAG_RENAME_FILE);
355 return true;
356 }
357 case R.id.action_remove_file: {
358 RemoveFileDialogFragment dialog = RemoveFileDialogFragment.newInstance(mTargetFile);
359 dialog.show(getFragmentManager(), ConfirmationDialogFragment.FTAG_CONFIRMATION);
360 return true;
361 }
362 case R.id.action_download_file:
363 case R.id.action_sync_file: {
364 mContainerActivity.getFileOperationsHelper().syncFile(mTargetFile);
365 return true;
366 }
367 case R.id.action_cancel_download:
368 case R.id.action_cancel_upload: {
369 ((FileDisplayActivity) mContainerActivity).cancelTransference(mTargetFile);
370 return true;
371 }
372 case R.id.action_see_details: {
373 mContainerActivity.showDetails(mTargetFile);
374 return true;
375 }
376 case R.id.action_send_file: {
377 // Obtain the file
378 if (!mTargetFile.isDown()) { // Download the file
379 Log_OC.d(TAG, mTargetFile.getRemotePath() + " : File must be downloaded");
380 ((FileDisplayActivity) mContainerActivity).startDownloadForSending(mTargetFile);
381
382 } else {
383 mContainerActivity.getFileOperationsHelper().sendDownloadedFile(mTargetFile);
384 }
385 return true;
386 }
387 case R.id.action_move: {
388 Intent action = new Intent(getActivity(), FolderPickerActivity.class);
389
390 // Pass mTargetFile that contains info of selected file/folder
391 action.putExtra(FolderPickerActivity.EXTRA_FILE, mTargetFile);
392 getActivity().startActivityForResult(action, FileDisplayActivity.ACTION_MOVE_FILES);
393 return true;
394 }
395 case R.id.action_favorite_file: {
396 mContainerActivity.getFileOperationsHelper().toggleFavorite(mTargetFile, true);
397 return true;
398 }
399 case R.id.action_unfavorite_file: {
400 mContainerActivity.getFileOperationsHelper().toggleFavorite(mTargetFile, false);
401 return true;
402 }
403 case R.id.action_copy:
404 Intent action = new Intent(getActivity(), FolderPickerActivity.class);
405
406 // Pass mTargetFile that contains info of selected file/folder
407 action.putExtra(FolderPickerActivity.EXTRA_FILE, mTargetFile);
408 getActivity().startActivityForResult(action, FileDisplayActivity.ACTION_COPY_FILES);
409 return true;
410 default:
411 return false;
412 }
413 }
414
415 /**
416 * {@inhericDoc}
417 */
418 @Override
419 public boolean onContextItemSelected (MenuItem item) {
420 AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
421 boolean matched = onFileActionChosen(item.getItemId(), ((AdapterContextMenuInfo) item.getMenuInfo()).position);
422 if(!matched) {
423 return super.onContextItemSelected(item);
424 } else {
425 return matched;
426 }
427 }
428
429
430 /**
431 * Use this to query the {@link OCFile} that is currently
432 * being displayed by this fragment
433 *
434 * @return The currently viewed OCFile
435 */
436 public OCFile getCurrentFile() {
437 return mFile;
438 }
439
440 /**
441 * Calls {@link OCFileListFragment#listDirectory(OCFile)} with a null parameter
442 */
443 public void listDirectory(/*boolean onlyOnDevice*/){
444 listDirectory(null);
445 // TODO Enable when "On Device" is recovered ?
446 // listDirectory(null, onlyOnDevice);
447 }
448
449 public void refreshDirectory(){
450 // TODO Enable when "On Device" is recovered ?
451 listDirectory(getCurrentFile()/*, MainApp.getOnlyOnDevice()*/);
452 }
453
454 /**
455 * Lists the given directory on the view. When the input parameter is null,
456 * it will either refresh the last known directory. list the root
457 * if there never was a directory.
458 *
459 * @param directory File to be listed
460 */
461 public void listDirectory(OCFile directory/*, boolean onlyOnDevice*/) {
462 FileDataStorageManager storageManager = mContainerActivity.getStorageManager();
463 if (storageManager != null) {
464
465 // Check input parameters for null
466 if (directory == null) {
467 if (mFile != null) {
468 directory = mFile;
469 } else {
470 directory = storageManager.getFileByPath("/");
471 if (directory == null) return; // no files, wait for sync
472 }
473 }
474
475
476 // If that's not a directory -> List its parent
477 if (!directory.isFolder()) {
478 Log_OC.w(TAG, "You see, that is not a directory -> " + directory.toString());
479 directory = storageManager.getFileById(directory.getParentId());
480 }
481
482 // TODO Enable when "On Device" is recovered ?
483 mAdapter.swapDirectory(directory, storageManager/*, onlyOnDevice*/);
484 if (mFile == null || !mFile.equals(directory)) {
485 mCurrentListView.setSelection(0);
486 }
487 mFile = directory;
488
489 updateLayout();
490
491 }
492 }
493
494 private void updateLayout() {
495 if (!mJustFolders) {
496 int filesCount = 0, foldersCount = 0, imagesCount = 0;
497 int count = mAdapter.getCount();
498 OCFile file;
499 for (int i=0; i < count ; i++) {
500 file = (OCFile) mAdapter.getItem(i);
501 if (file.isFolder()) {
502 foldersCount++;
503 } else {
504 if (!file.isHidden()) {
505 filesCount++;
506
507 if (file.isImage()) {
508 imagesCount++;
509 }
510 }
511 }
512 }
513 // set footer text
514 setFooterText(generateFooterText(filesCount, foldersCount));
515
516 // decide grid vs list view
517 OwnCloudVersion version = AccountUtils.getServerVersion(
518 ((FileActivity)mContainerActivity).getAccount());
519 if (version != null && version.supportsRemoteThumbnails() &&
520 imagesCount > 0 && imagesCount == filesCount) {
521 switchToGridView();
522 registerLongClickListener();
523 } else {
524 switchToListView();
525 }
526 }
527 }
528
529 private String generateFooterText(int filesCount, int foldersCount) {
530 String output;
531 if (filesCount <= 0) {
532 if (foldersCount <= 0) {
533 output = "";
534
535 } else if (foldersCount == 1) {
536 output = getResources().getString(R.string.file_list__footer__folder);
537
538 } else { // foldersCount > 1
539 output = getResources().getString(R.string.file_list__footer__folders, foldersCount);
540 }
541
542 } else if (filesCount == 1) {
543 if (foldersCount <= 0) {
544 output = getResources().getString(R.string.file_list__footer__file);
545
546 } else if (foldersCount == 1) {
547 output = getResources().getString(R.string.file_list__footer__file_and_folder);
548
549 } else { // foldersCount > 1
550 output = getResources().getString(R.string.file_list__footer__file_and_folders, foldersCount);
551 }
552 } else { // filesCount > 1
553 if (foldersCount <= 0) {
554 output = getResources().getString(R.string.file_list__footer__files, filesCount);
555
556 } else if (foldersCount == 1) {
557 output = getResources().getString(R.string.file_list__footer__files_and_folder, filesCount);
558
559 } else { // foldersCount > 1
560 output = getResources().getString(
561 R.string.file_list__footer__files_and_folders, filesCount, foldersCount
562 );
563
564 }
565 }
566 return output;
567 }
568
569 public void sortByName(boolean descending) {
570 mAdapter.setSortOrder(FileStorageUtils.SORT_NAME, descending);
571 }
572
573 public void sortByDate(boolean descending) {
574 mAdapter.setSortOrder(FileStorageUtils.SORT_DATE, descending);
575 }
576
577 public void sortBySize(boolean descending) {
578 mAdapter.setSortOrder(FileStorageUtils.SORT_SIZE, descending);
579 }
580 }