Merge branch 'text_file_preview_pr_707_with_develop' of github.com:owncloud/android...
[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 import com.owncloud.android.ui.preview.PreviewTextFragment;
61
62 /**
63 * A Fragment that lists all files and folders in a given path.
64 *
65 * TODO refactor to get rid of direct dependency on FileDisplayActivity
66 */
67 public class OCFileListFragment extends ExtendedListFragment implements FileActionsDialogFragment.FileActionsDialogFragmentListener {
68
69 private static final String TAG = OCFileListFragment.class.getSimpleName();
70
71 private static final String MY_PACKAGE = OCFileListFragment.class.getPackage() != null ?
72 OCFileListFragment.class.getPackage().getName() : "com.owncloud.android.ui.fragment";
73
74 public final static String ARG_JUST_FOLDERS = MY_PACKAGE + ".JUST_FOLDERS";
75 public final static String ARG_ALLOW_CONTEXTUAL_ACTIONS = MY_PACKAGE + ".ALLOW_CONTEXTUAL";
76
77 private static final String KEY_FILE = MY_PACKAGE + ".extra.FILE";
78
79 private FileFragment.ContainerActivity mContainerActivity;
80
81 private OCFile mFile = null;
82 private FileListListAdapter mAdapter;
83 private boolean mJustFolders;
84
85 private OCFile mTargetFile;
86
87
88
89 /**
90 * {@inheritDoc}
91 */
92 @Override
93 public void onAttach(Activity activity) {
94 super.onAttach(activity);
95 Log_OC.e(TAG, "onAttach");
96 try {
97 mContainerActivity = (FileFragment.ContainerActivity) activity;
98
99 } catch (ClassCastException e) {
100 throw new ClassCastException(activity.toString() + " must implement " +
101 FileFragment.ContainerActivity.class.getSimpleName());
102 }
103 try {
104 setOnRefreshListener((OnEnforceableRefreshListener) activity);
105
106 } catch (ClassCastException e) {
107 throw new ClassCastException(activity.toString() + " must implement " +
108 SwipeRefreshLayout.OnRefreshListener.class.getSimpleName());
109 }
110 }
111
112
113 @Override
114 public void onDetach() {
115 setOnRefreshListener(null);
116 mContainerActivity = null;
117 super.onDetach();
118 }
119
120 /**
121 * {@inheritDoc}
122 */
123 @Override
124 public void onActivityCreated(Bundle savedInstanceState) {
125 super.onActivityCreated(savedInstanceState);
126 Log_OC.e(TAG, "onActivityCreated() start");
127
128 if (savedInstanceState != null) {
129 mFile = savedInstanceState.getParcelable(KEY_FILE);
130 }
131
132 if (mJustFolders) {
133 setFooterEnabled(false);
134 } else {
135 setFooterEnabled(true);
136 }
137
138 Bundle args = getArguments();
139 mJustFolders = (args == null) ? false : args.getBoolean(ARG_JUST_FOLDERS, false);
140 mAdapter = new FileListListAdapter(
141 mJustFolders,
142 getActivity(),
143 mContainerActivity
144 );
145 setListAdapter(mAdapter);
146
147 registerLongClickListener();
148 }
149
150 private void registerLongClickListener() {
151 getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
152 public boolean onItemLongClick(AdapterView<?> arg0, View v,
153 int index, long arg3) {
154 showFileAction(index);
155 return true;
156 }
157 });
158 }
159
160
161 private void showFileAction(int fileIndex) {
162 Bundle args = getArguments();
163 PopupMenu pm = new PopupMenu(getActivity(),null);
164 Menu menu = pm.getMenu();
165
166 boolean allowContextualActions =
167 (args == null) ? true : args.getBoolean(ARG_ALLOW_CONTEXTUAL_ACTIONS, true);
168
169 if (allowContextualActions) {
170 MenuInflater inflater = getActivity().getMenuInflater();
171
172 inflater.inflate(R.menu.file_actions_menu, menu);
173 OCFile targetFile = (OCFile) mAdapter.getItem(fileIndex);
174
175 if (mContainerActivity.getStorageManager() != null) {
176 FileMenuFilter mf = new FileMenuFilter(
177 targetFile,
178 mContainerActivity.getStorageManager().getAccount(),
179 mContainerActivity,
180 getActivity()
181 );
182 mf.filter(menu);
183 }
184
185 /// TODO break this direct dependency on FileDisplayActivity... if possible
186 MenuItem item = menu.findItem(R.id.action_open_file_with);
187 FileFragment frag = ((FileDisplayActivity)getActivity()).getSecondFragment();
188 if (frag != null && frag instanceof FileDetailFragment &&
189 frag.getFile().getFileId() == targetFile.getFileId()) {
190 item = menu.findItem(R.id.action_see_details);
191 if (item != null) {
192 item.setVisible(false);
193 item.setEnabled(false);
194 }
195 }
196
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 } else if (PreviewTextFragment.canBePreviewed(file)){
277 ((FileDisplayActivity)mContainerActivity).startTextPreview(file);
278 } else if (file.isDown()) {
279 if (PreviewMediaFragment.canBePreviewed(file)) {
280 // media preview
281 ((FileDisplayActivity)mContainerActivity).startMediaPreview(file, 0, true);
282 } else {
283 mContainerActivity.getFileOperationsHelper().openFile(file);
284 }
285
286 } else {
287 // automatic download, preview on finish
288 ((FileDisplayActivity)mContainerActivity).startDownloadForPreview(file);
289 }
290
291 }
292
293 } else {
294 Log_OC.d(TAG, "Null object in ListAdapter!!");
295 }
296
297 }
298
299 /**
300 * {@inheritDoc}
301 */
302 @Override
303 public void onCreateContextMenu (
304 ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
305 Bundle args = getArguments();
306 boolean allowContextualActions =
307 (args == null) ? true : args.getBoolean(ARG_ALLOW_CONTEXTUAL_ACTIONS, true);
308 if (allowContextualActions) {
309 MenuInflater inflater = getActivity().getMenuInflater();
310 inflater.inflate(R.menu.file_actions_menu, menu);
311 AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
312 OCFile targetFile = (OCFile) mAdapter.getItem(info.position);
313
314 if (mContainerActivity.getStorageManager() != null) {
315 FileMenuFilter mf = new FileMenuFilter(
316 targetFile,
317 mContainerActivity.getStorageManager().getAccount(),
318 mContainerActivity,
319 getActivity()
320 );
321 mf.filter(menu);
322 }
323
324 /// TODO break this direct dependency on FileDisplayActivity... if possible
325 MenuItem item = menu.findItem(R.id.action_open_file_with);
326 FileFragment frag = ((FileDisplayActivity)getActivity()).getSecondFragment();
327 if (frag != null && frag instanceof FileDetailFragment &&
328 frag.getFile().getFileId() == targetFile.getFileId()) {
329 item = menu.findItem(R.id.action_see_details);
330 if (item != null) {
331 item.setVisible(false);
332 item.setEnabled(false);
333 }
334 }
335 }
336 }
337
338 /**
339 * {@inheritDoc}
340 */
341 @Override
342 public boolean onFileActionChosen(int menuId, int filePosition) {
343 mTargetFile = (OCFile) mAdapter.getItem(filePosition);
344 switch (menuId) {
345 case R.id.action_share_file: {
346 mContainerActivity.getFileOperationsHelper().shareFileWithLink(mTargetFile);
347 return true;
348 }
349 case R.id.action_open_file_with: {
350 mContainerActivity.getFileOperationsHelper().openFile(mTargetFile);
351 return true;
352 }
353 case R.id.action_unshare_file: {
354 mContainerActivity.getFileOperationsHelper().unshareFileWithLink(mTargetFile);
355 return true;
356 }
357 case R.id.action_rename_file: {
358 RenameFileDialogFragment dialog = RenameFileDialogFragment.newInstance(mTargetFile);
359 dialog.show(getFragmentManager(), FileDetailFragment.FTAG_RENAME_FILE);
360 return true;
361 }
362 case R.id.action_remove_file: {
363 RemoveFileDialogFragment dialog = RemoveFileDialogFragment.newInstance(mTargetFile);
364 dialog.show(getFragmentManager(), ConfirmationDialogFragment.FTAG_CONFIRMATION);
365 return true;
366 }
367 case R.id.action_download_file:
368 case R.id.action_sync_file: {
369 mContainerActivity.getFileOperationsHelper().syncFile(mTargetFile);
370 return true;
371 }
372 case R.id.action_cancel_download:
373 case R.id.action_cancel_upload: {
374 ((FileDisplayActivity) mContainerActivity).cancelTransference(mTargetFile);
375 return true;
376 }
377 case R.id.action_see_details: {
378 mContainerActivity.showDetails(mTargetFile);
379 return true;
380 }
381 case R.id.action_send_file: {
382 // Obtain the file
383 if (!mTargetFile.isDown()) { // Download the file
384 Log_OC.d(TAG, mTargetFile.getRemotePath() + " : File must be downloaded");
385 ((FileDisplayActivity) mContainerActivity).startDownloadForSending(mTargetFile);
386
387 } else {
388 mContainerActivity.getFileOperationsHelper().sendDownloadedFile(mTargetFile);
389 }
390 return true;
391 }
392 case R.id.action_move: {
393 Intent action = new Intent(getActivity(), FolderPickerActivity.class);
394
395 // Pass mTargetFile that contains info of selected file/folder
396 action.putExtra(FolderPickerActivity.EXTRA_FILE, mTargetFile);
397 getActivity().startActivityForResult(action, FileDisplayActivity.ACTION_MOVE_FILES);
398 return true;
399 }
400 case R.id.action_favorite_file: {
401 mContainerActivity.getFileOperationsHelper().toggleFavorite(mTargetFile, true);
402 return true;
403 }
404 case R.id.action_unfavorite_file: {
405 mContainerActivity.getFileOperationsHelper().toggleFavorite(mTargetFile, false);
406 return true;
407 }
408 default:
409 return false;
410 }
411 }
412
413 /**
414 * {@inhericDoc}
415 */
416 @Override
417 public boolean onContextItemSelected (MenuItem item) {
418 AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
419 boolean matched = onFileActionChosen(item.getItemId(), ((AdapterContextMenuInfo) item.getMenuInfo()).position);
420 if(!matched) {
421 return super.onContextItemSelected(item);
422 } else {
423 return matched;
424 }
425 }
426
427
428 /**
429 * Use this to query the {@link OCFile} that is currently
430 * being displayed by this fragment
431 * @return The currently viewed OCFile
432 */
433 public OCFile getCurrentFile(){
434 return mFile;
435 }
436
437 /**
438 * Calls {@link OCFileListFragment#listDirectory(OCFile)} with a null parameter
439 */
440 public void listDirectory(/*boolean onlyOnDevice*/){
441 listDirectory(null);
442 // TODO Enable when "On Device" is recovered ?
443 // listDirectory(null, onlyOnDevice);
444 }
445
446 public void refreshDirectory(){
447 // TODO Enable when "On Device" is recovered ?
448 listDirectory(getCurrentFile()/*, MainApp.getOnlyOnDevice()*/);
449 }
450
451 /**
452 * Lists the given directory on the view. When the input parameter is null,
453 * it will either refresh the last known directory. list the root
454 * if there never was a directory.
455 *
456 * @param directory File to be listed
457 */
458 public void listDirectory(OCFile directory/*, boolean onlyOnDevice*/) {
459 FileDataStorageManager storageManager = mContainerActivity.getStorageManager();
460 if (storageManager != null) {
461
462 // Check input parameters for null
463 if(directory == null){
464 if(mFile != null){
465 directory = mFile;
466 } else {
467 directory = storageManager.getFileByPath("/");
468 if (directory == null) return; // no files, wait for sync
469 }
470 }
471
472
473 // If that's not a directory -> List its parent
474 if(!directory.isFolder()){
475 Log_OC.w(TAG, "You see, that is not a directory -> " + directory.toString());
476 directory = storageManager.getFileById(directory.getParentId());
477 }
478
479 // TODO Enable when "On Device" is recovered ?
480 mAdapter.swapDirectory(directory, storageManager/*, onlyOnDevice*/);
481 if (mFile == null || !mFile.equals(directory)) {
482 mCurrentListView.setSelection(0);
483 }
484 mFile = directory;
485
486 updateLayout();
487
488 }
489 }
490
491 private void updateLayout() {
492 if (!mJustFolders) {
493 int filesCount = 0, foldersCount = 0, imagesCount = 0;
494 int count = mAdapter.getCount();
495 OCFile file;
496 for (int i=0; i < count ; i++) {
497 file = (OCFile) mAdapter.getItem(i);
498 if (file.isFolder()) {
499 foldersCount++;
500 } else {
501 if (!file.isHidden()) {
502 filesCount++;
503
504 if (file.isImage()) {
505 imagesCount++;
506 }
507 }
508 }
509 }
510 // set footer text
511 setFooterText(generateFooterText(filesCount, foldersCount));
512
513 // decide grid vs list view
514 OwnCloudVersion version = AccountUtils.getServerVersion(
515 ((FileActivity)mContainerActivity).getAccount());
516 if (version != null && version.supportsRemoteThumbnails() &&
517 imagesCount > 0 && imagesCount == filesCount) {
518 switchToGridView();
519 registerLongClickListener();
520 } else {
521 switchToListView();
522 }
523 }
524 }
525
526 private String generateFooterText(int filesCount, int foldersCount) {
527 String output;
528 if (filesCount <= 0) {
529 if (foldersCount <= 0) {
530 output = "";
531
532 } else if (foldersCount == 1) {
533 output = getResources().getString(R.string.file_list__footer__folder);
534
535 } else { // foldersCount > 1
536 output = getResources().getString(R.string.file_list__footer__folders, foldersCount);
537 }
538
539 } else if (filesCount == 1) {
540 if (foldersCount <= 0) {
541 output = getResources().getString(R.string.file_list__footer__file);
542
543 } else if (foldersCount == 1) {
544 output = getResources().getString(R.string.file_list__footer__file_and_folder);
545
546 } else { // foldersCount > 1
547 output = getResources().getString(R.string.file_list__footer__file_and_folders, foldersCount);
548 }
549 } else { // filesCount > 1
550 if (foldersCount <= 0) {
551 output = getResources().getString(R.string.file_list__footer__files, filesCount);
552
553 } else if (foldersCount == 1) {
554 output = getResources().getString(R.string.file_list__footer__files_and_folder, filesCount);
555
556 } else { // foldersCount > 1
557 output = getResources().getString(
558 R.string.file_list__footer__files_and_folders, filesCount, foldersCount
559 );
560
561 }
562 }
563 return output;
564 }
565
566 public void sortByName(boolean descending) {
567 mAdapter.setSortOrder(FileStorageUtils.SORT_NAME, descending);
568 }
569
570 public void sortByDate(boolean descending) {
571 mAdapter.setSortOrder(FileStorageUtils.SORT_DATE, descending);
572 }
573
574 public void sortBySize(boolean descending) {
575 mAdapter.setSortOrder(FileStorageUtils.SORT_SIZE, descending);
576 }
577 }