enabled all occurrences.
[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.MainApp;
39 import com.owncloud.android.R;
40 import com.owncloud.android.authentication.AccountUtils;
41 import com.owncloud.android.datamodel.FileDataStorageManager;
42 import com.owncloud.android.datamodel.OCFile;
43 import com.owncloud.android.files.FileMenuFilter;
44 import com.owncloud.android.lib.common.utils.Log_OC;
45 import com.owncloud.android.lib.resources.status.OwnCloudVersion;
46 import com.owncloud.android.ui.activity.FileActivity;
47 import com.owncloud.android.ui.activity.FileDisplayActivity;
48 import com.owncloud.android.ui.activity.FolderPickerActivity;
49 import com.owncloud.android.ui.activity.OnEnforceableRefreshListener;
50 import com.owncloud.android.ui.adapter.FileListListAdapter;
51 import com.owncloud.android.ui.dialog.ConfirmationDialogFragment;
52 import com.owncloud.android.ui.dialog.FileActionsDialogFragment;
53 import com.owncloud.android.ui.dialog.RemoveFileDialogFragment;
54 import com.owncloud.android.ui.dialog.RenameFileDialogFragment;
55 import com.owncloud.android.ui.preview.PreviewImageFragment;
56 import com.owncloud.android.ui.preview.PreviewMediaFragment;
57 import com.owncloud.android.utils.FileStorageUtils;
58 import com.owncloud.android.ui.preview.PreviewTextFragment;
59
60 import java.io.File;
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, targetFile.getFileName());
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 * <p/>
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 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 listDirectory(file, MainApp.getOnlyOnDevice());
265 // then, notify parent activity to let it update its state and view
266 mContainerActivity.onBrowsedDownTo(file);
267 // save index and top position
268 saveIndexAndTopPosition(position);
269
270 } else { /// Click on a file
271 if (PreviewImageFragment.canBePreviewed(file)) {
272 // preview image - it handles the download, if needed
273 ((FileDisplayActivity)mContainerActivity).startImagePreview(file);
274 } else if (PreviewTextFragment.canBePreviewed(file)){
275 ((FileDisplayActivity)mContainerActivity).startTextPreview(file);
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 }
335
336 /**
337 * {@inheritDoc}
338 */
339 @Override
340 public boolean onFileActionChosen(int menuId, int filePosition) {
341 mTargetFile = (OCFile) mAdapter.getItem(filePosition);
342 switch (menuId) {
343 case R.id.action_share_file: {
344 mContainerActivity.getFileOperationsHelper().shareFileWithLink(mTargetFile);
345 return true;
346 }
347 case R.id.action_open_file_with: {
348 mContainerActivity.getFileOperationsHelper().openFile(mTargetFile);
349 return true;
350 }
351 case R.id.action_unshare_file: {
352 mContainerActivity.getFileOperationsHelper().unshareFileWithLink(mTargetFile);
353 return true;
354 }
355 case R.id.action_rename_file: {
356 RenameFileDialogFragment dialog = RenameFileDialogFragment.newInstance(mTargetFile);
357 dialog.show(getFragmentManager(), FileDetailFragment.FTAG_RENAME_FILE);
358 return true;
359 }
360 case R.id.action_remove_file: {
361 RemoveFileDialogFragment dialog = RemoveFileDialogFragment.newInstance(mTargetFile);
362 dialog.show(getFragmentManager(), ConfirmationDialogFragment.FTAG_CONFIRMATION);
363 return true;
364 }
365 case R.id.action_download_file:
366 case R.id.action_sync_file: {
367 mContainerActivity.getFileOperationsHelper().syncFile(mTargetFile);
368 return true;
369 }
370 case R.id.action_cancel_download:
371 case R.id.action_cancel_upload: {
372 ((FileDisplayActivity) mContainerActivity).cancelTransference(mTargetFile);
373 return true;
374 }
375 case R.id.action_see_details: {
376 mContainerActivity.showDetails(mTargetFile);
377 return true;
378 }
379 case R.id.action_send_file: {
380 // Obtain the file
381 if (!mTargetFile.isDown()) { // Download the file
382 Log_OC.d(TAG, mTargetFile.getRemotePath() + " : File must be downloaded");
383 ((FileDisplayActivity) mContainerActivity).startDownloadForSending(mTargetFile);
384
385 } else {
386 mContainerActivity.getFileOperationsHelper().sendDownloadedFile(mTargetFile);
387 }
388 return true;
389 }
390 case R.id.action_move: {
391 Intent action = new Intent(getActivity(), FolderPickerActivity.class);
392
393 // Pass mTargetFile that contains info of selected file/folder
394 action.putExtra(FolderPickerActivity.EXTRA_FILE, mTargetFile);
395 getActivity().startActivityForResult(action, FileDisplayActivity.ACTION_MOVE_FILES);
396 return true;
397 }
398 case R.id.action_favorite_file: {
399 mContainerActivity.getFileOperationsHelper().toggleFavorite(mTargetFile, true);
400 return true;
401 }
402 case R.id.action_unfavorite_file: {
403 mContainerActivity.getFileOperationsHelper().toggleFavorite(mTargetFile, false);
404 return true;
405 }
406 case R.id.action_copy:
407 Intent action = new Intent(getActivity(), FolderPickerActivity.class);
408
409 // Pass mTargetFile that contains info of selected file/folder
410 action.putExtra(FolderPickerActivity.EXTRA_FILE, mTargetFile);
411 getActivity().startActivityForResult(action, FileDisplayActivity.ACTION_COPY_FILES);
412 return true;
413 default:
414 return false;
415 }
416 }
417
418 /**
419 * {@inhericDoc}
420 */
421 @Override
422 public boolean onContextItemSelected (MenuItem item) {
423 AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
424 boolean matched = onFileActionChosen(item.getItemId(), ((AdapterContextMenuInfo) item.getMenuInfo()).position);
425 if(!matched) {
426 return super.onContextItemSelected(item);
427 } else {
428 return matched;
429 }
430 }
431
432
433 /**
434 * Use this to query the {@link OCFile} that is currently
435 * being displayed by this fragment
436 *
437 * @return The currently viewed OCFile
438 */
439 public OCFile getCurrentFile() {
440 return mFile;
441 }
442
443 /**
444 * Calls {@link OCFileListFragment#listDirectory(OCFile, boolean)} with a null parameter
445 */
446 public void listDirectory(boolean onlyOnDevice){
447 listDirectory(null, onlyOnDevice);
448 }
449
450 public void refreshDirectory(){
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 mAdapter.swapDirectory(directory, storageManager, onlyOnDevice);
483 if (mFile == null || !mFile.equals(directory)) {
484 mCurrentListView.setSelection(0);
485 }
486 mFile = directory;
487
488 updateLayout();
489
490 }
491 }
492
493 private void updateLayout() {
494 if (!mJustFolders) {
495 int filesCount = 0, foldersCount = 0, imagesCount = 0;
496 int count = mAdapter.getCount();
497 OCFile file;
498 for (int i=0; i < count ; i++) {
499 file = (OCFile) mAdapter.getItem(i);
500 if (file.isFolder()) {
501 foldersCount++;
502 } else {
503 if (!file.isHidden()) {
504 filesCount++;
505
506 if (file.isImage()) {
507 imagesCount++;
508 }
509 }
510 }
511 }
512 // set footer text
513 setFooterText(generateFooterText(filesCount, foldersCount));
514
515 // decide grid vs list view
516 OwnCloudVersion version = AccountUtils.getServerVersion(
517 ((FileActivity)mContainerActivity).getAccount());
518 if (version != null && version.supportsRemoteThumbnails() &&
519 imagesCount > 0 && imagesCount == filesCount) {
520 switchToGridView();
521 registerLongClickListener();
522 } else {
523 switchToListView();
524 }
525 }
526 }
527
528 private String generateFooterText(int filesCount, int foldersCount) {
529 String output;
530 if (filesCount <= 0) {
531 if (foldersCount <= 0) {
532 output = "";
533
534 } else if (foldersCount == 1) {
535 output = getResources().getString(R.string.file_list__footer__folder);
536
537 } else { // foldersCount > 1
538 output = getResources().getString(R.string.file_list__footer__folders, foldersCount);
539 }
540
541 } else if (filesCount == 1) {
542 if (foldersCount <= 0) {
543 output = getResources().getString(R.string.file_list__footer__file);
544
545 } else if (foldersCount == 1) {
546 output = getResources().getString(R.string.file_list__footer__file_and_folder);
547
548 } else { // foldersCount > 1
549 output = getResources().getString(R.string.file_list__footer__file_and_folders, foldersCount);
550 }
551 } else { // filesCount > 1
552 if (foldersCount <= 0) {
553 output = getResources().getString(R.string.file_list__footer__files, filesCount);
554
555 } else if (foldersCount == 1) {
556 output = getResources().getString(R.string.file_list__footer__files_and_folder, filesCount);
557
558 } else { // foldersCount > 1
559 output = getResources().getString(
560 R.string.file_list__footer__files_and_folders, filesCount, foldersCount
561 );
562
563 }
564 }
565 return output;
566 }
567
568 public void sortByName(boolean descending) {
569 mAdapter.setSortOrder(FileStorageUtils.SORT_NAME, descending);
570 }
571
572 public void sortByDate(boolean descending) {
573 mAdapter.setSortOrder(FileStorageUtils.SORT_DATE, descending);
574 }
575
576 public void sortBySize(boolean descending) {
577 mAdapter.setSortOrder(FileStorageUtils.SORT_SIZE, descending);
578 }
579 }