Merge branch 'develop' of github.com:owncloud/android into switchListVsGrid
[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.DisplayUtils;
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 FileActionsDialogFragment dialog = FileActionsDialogFragment.newInstance(menu, fileIndex);
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 *
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
276 } else if (file.isDown()) {
277 if (PreviewMediaFragment.canBePreviewed(file)) {
278 // media preview
279 ((FileDisplayActivity)mContainerActivity).startMediaPreview(file, 0, true);
280 } else {
281 mContainerActivity.getFileOperationsHelper().openFile(file);
282 }
283
284 } else {
285 // automatic download, preview on finish
286 ((FileDisplayActivity)mContainerActivity).startDownloadForPreview(file);
287 }
288
289 }
290
291 } else {
292 Log_OC.d(TAG, "Null object in ListAdapter!!");
293 }
294
295 }
296
297 /**
298 * {@inheritDoc}
299 */
300 @Override
301 public void onCreateContextMenu (
302 ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
303 Bundle args = getArguments();
304 boolean allowContextualActions =
305 (args == null) ? true : args.getBoolean(ARG_ALLOW_CONTEXTUAL_ACTIONS, true);
306 if (allowContextualActions) {
307 MenuInflater inflater = getActivity().getMenuInflater();
308 inflater.inflate(R.menu.file_actions_menu, menu);
309 AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
310 OCFile targetFile = (OCFile) mAdapter.getItem(info.position);
311
312 if (mContainerActivity.getStorageManager() != null) {
313 FileMenuFilter mf = new FileMenuFilter(
314 targetFile,
315 mContainerActivity.getStorageManager().getAccount(),
316 mContainerActivity,
317 getActivity()
318 );
319 mf.filter(menu);
320 }
321
322 /// TODO break this direct dependency on FileDisplayActivity... if possible
323 MenuItem item = menu.findItem(R.id.action_open_file_with);
324 FileFragment frag = ((FileDisplayActivity)getActivity()).getSecondFragment();
325 if (frag != null && frag instanceof FileDetailFragment &&
326 frag.getFile().getFileId() == targetFile.getFileId()) {
327 item = menu.findItem(R.id.action_see_details);
328 if (item != null) {
329 item.setVisible(false);
330 item.setEnabled(false);
331 }
332 }
333
334 // String.format(mContext.getString(R.string.subject_token),
335 // getClient().getCredentials().getUsername(), file.getFileName()));
336 }
337 }
338
339 /**
340 * {@inheritDoc}
341 */
342 @Override
343 public boolean onFileActionChosen(int menuId, int filePosition) {
344 mTargetFile = (OCFile) mAdapter.getItem(filePosition);
345 switch (menuId) {
346 case R.id.action_share_file: {
347 mContainerActivity.getFileOperationsHelper().shareFileWithLink(mTargetFile);
348 return true;
349 }
350 case R.id.action_open_file_with: {
351 mContainerActivity.getFileOperationsHelper().openFile(mTargetFile);
352 return true;
353 }
354 case R.id.action_unshare_file: {
355 mContainerActivity.getFileOperationsHelper().unshareFileWithLink(mTargetFile);
356 return true;
357 }
358 case R.id.action_rename_file: {
359 RenameFileDialogFragment dialog = RenameFileDialogFragment.newInstance(mTargetFile);
360 dialog.show(getFragmentManager(), FileDetailFragment.FTAG_RENAME_FILE);
361 return true;
362 }
363 case R.id.action_remove_file: {
364 RemoveFileDialogFragment dialog = RemoveFileDialogFragment.newInstance(mTargetFile);
365 dialog.show(getFragmentManager(), ConfirmationDialogFragment.FTAG_CONFIRMATION);
366 return true;
367 }
368 case R.id.action_download_file:
369 case R.id.action_sync_file: {
370 mContainerActivity.getFileOperationsHelper().syncFile(mTargetFile);
371 return true;
372 }
373 case R.id.action_cancel_download:
374 case R.id.action_cancel_upload: {
375 ((FileDisplayActivity) mContainerActivity).cancelTransference(mTargetFile);
376 return true;
377 }
378 case R.id.action_see_details: {
379 mContainerActivity.showDetails(mTargetFile);
380 return true;
381 }
382 case R.id.action_send_file: {
383 // Obtain the file
384 if (!mTargetFile.isDown()) { // Download the file
385 Log_OC.d(TAG, mTargetFile.getRemotePath() + " : File must be downloaded");
386 ((FileDisplayActivity) mContainerActivity).startDownloadForSending(mTargetFile);
387
388 } else {
389 mContainerActivity.getFileOperationsHelper().sendDownloadedFile(mTargetFile);
390 }
391 return true;
392 }
393 case R.id.action_move: {
394 Intent action = new Intent(getActivity(), FolderPickerActivity.class);
395
396 // Pass mTargetFile that contains info of selected file/folder
397 action.putExtra(FolderPickerActivity.EXTRA_FILE, mTargetFile);
398 getActivity().startActivityForResult(action, FileDisplayActivity.ACTION_MOVE_FILES);
399 return true;
400 }
401 case R.id.action_favorite_file: {
402 mContainerActivity.getFileOperationsHelper().toggleFavorite(mTargetFile, true);
403 return true;
404 }
405 case R.id.action_unfavorite_file: {
406 mContainerActivity.getFileOperationsHelper().toggleFavorite(mTargetFile, false);
407 return true;
408 }
409 default:
410 return false;
411 }
412 }
413
414 /**
415 * {@inhericDoc}
416 */
417 @Override
418 public boolean onContextItemSelected (MenuItem item) {
419 AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
420 boolean matched = onFileActionChosen(item.getItemId(), ((AdapterContextMenuInfo) item.getMenuInfo()).position);
421 if(!matched) {
422 return super.onContextItemSelected(item);
423 } else {
424 return matched;
425 }
426 }
427
428
429 /**
430 * Use this to query the {@link OCFile} that is currently
431 * being displayed by this fragment
432 * @return The currently viewed OCFile
433 */
434 public OCFile getCurrentFile(){
435 return mFile;
436 }
437
438 /**
439 * Calls {@link OCFileListFragment#listDirectory(OCFile)} with a null parameter
440 */
441 public void listDirectory(/*boolean onlyOnDevice*/){
442 listDirectory(null);
443 // TODO Enable when "On Device" is recovered ?
444 // listDirectory(null, onlyOnDevice);
445 }
446
447 public void refreshDirectory(){
448 // TODO Enable when "On Device" is recovered ?
449 listDirectory(getCurrentFile()/*, MainApp.getOnlyOnDevice()*/);
450 }
451
452 /**
453 * Lists the given directory on the view. When the input parameter is null,
454 * it will either refresh the last known directory. list the root
455 * if there never was a directory.
456 *
457 * @param directory File to be listed
458 */
459 public void listDirectory(OCFile directory/*, boolean onlyOnDevice*/) {
460 FileDataStorageManager storageManager = mContainerActivity.getStorageManager();
461 if (storageManager != null) {
462
463 // Check input parameters for null
464 if(directory == null){
465 if(mFile != null){
466 directory = mFile;
467 } else {
468 directory = storageManager.getFileByPath("/");
469 if (directory == null) return; // no files, wait for sync
470 }
471 }
472
473
474 // If that's not a directory -> List its parent
475 if(!directory.isFolder()){
476 Log_OC.w(TAG, "You see, that is not a directory -> " + directory.toString());
477 directory = storageManager.getFileById(directory.getParentId());
478 }
479
480 // TODO Enable when "On Device" is recovered ?
481 mAdapter.swapDirectory(directory, storageManager/*, onlyOnDevice*/);
482 if (mFile == null || !mFile.equals(directory)) {
483 mCurrentListView.setSelection(0);
484 }
485 mFile = directory;
486
487 updateLayout();
488
489 }
490 }
491
492 private void updateLayout() {
493 if (!mJustFolders) {
494 int filesCount = 0, foldersCount = 0, imagesCount = 0;
495 int count = mAdapter.getCount();
496 OCFile file;
497 for (int i=0; i < count ; i++) {
498 file = (OCFile) mAdapter.getItem(i);
499 if (file.isFolder()) {
500 foldersCount++;
501 } else {
502 filesCount++;
503 if (file.isImage()){
504 imagesCount++;
505 }
506 }
507 }
508 // set footer text
509 setFooterText(generateFooterText(filesCount, foldersCount));
510
511 // decide grid vs list view
512 OwnCloudVersion version = AccountUtils.getServerVersion(
513 ((FileActivity)mContainerActivity).getAccount());
514 if (version != null && version.supportsRemoteThumbnails() &&
515 DisplayUtils.isGridView(mFile, mContainerActivity.getStorageManager())) {
516 switchToGridView();
517 registerLongClickListener();
518 } else {
519 switchToListView();
520 }
521 }
522 }
523
524 private String generateFooterText(int filesCount, int foldersCount) {
525 String output;
526 if (filesCount <= 0) {
527 if (foldersCount <= 0) {
528 output = "";
529
530 } else if (foldersCount == 1) {
531 output = getResources().getString(R.string.file_list__footer__folder);
532
533 } else { // foldersCount > 1
534 output = getResources().getString(R.string.file_list__footer__folders, foldersCount);
535 }
536
537 } else if (filesCount == 1) {
538 if (foldersCount <= 0) {
539 output = getResources().getString(R.string.file_list__footer__file);
540
541 } else if (foldersCount == 1) {
542 output = getResources().getString(R.string.file_list__footer__file_and_folder);
543
544 } else { // foldersCount > 1
545 output = getResources().getString(R.string.file_list__footer__file_and_folders, foldersCount);
546 }
547 } else { // filesCount > 1
548 if (foldersCount <= 0) {
549 output = getResources().getString(R.string.file_list__footer__files, filesCount);
550
551 } else if (foldersCount == 1) {
552 output = getResources().getString(R.string.file_list__footer__files_and_folder, filesCount);
553
554 } else { // foldersCount > 1
555 output = getResources().getString(
556 R.string.file_list__footer__files_and_folders, filesCount, foldersCount
557 );
558
559 }
560 }
561 return output;
562 }
563
564 public void sortByName(boolean descending) {
565 mAdapter.setSortOrder(FileStorageUtils.SORT_NAME, descending);
566 }
567
568 public void sortByDate(boolean descending) {
569 mAdapter.setSortOrder(FileStorageUtils.SORT_DATE, descending);
570 }
571
572 public void sortBySize(boolean descending) {
573 mAdapter.setSortOrder(FileStorageUtils.SORT_SIZE, descending);
574 }
575 }