Fixes the text preview issue
[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.MenuInflater;
33 import android.view.MenuItem;
34 import android.view.View;
35 import android.widget.AdapterView;
36 import android.widget.AdapterView.AdapterContextMenuInfo;
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.RemoveFileDialogFragment;
52 import com.owncloud.android.ui.dialog.RenameFileDialogFragment;
53 import com.owncloud.android.ui.preview.PreviewImageFragment;
54 import com.owncloud.android.ui.preview.PreviewMediaFragment;
55 import com.owncloud.android.utils.FileStorageUtils;
56 import com.owncloud.android.ui.preview.PreviewTextFragment;
57
58 /**
59 * A Fragment that lists all files and folders in a given path.
60 *
61 * TODO refactor to get rid of direct dependency on FileDisplayActivity
62 */
63 public class OCFileListFragment extends ExtendedListFragment {
64
65 private static final String TAG = OCFileListFragment.class.getSimpleName();
66
67 private static final String MY_PACKAGE = OCFileListFragment.class.getPackage() != null ?
68 OCFileListFragment.class.getPackage().getName() : "com.owncloud.android.ui.fragment";
69
70 public final static String ARG_JUST_FOLDERS = MY_PACKAGE + ".JUST_FOLDERS";
71 public final static String ARG_ALLOW_CONTEXTUAL_ACTIONS = MY_PACKAGE + ".ALLOW_CONTEXTUAL";
72
73 private static final String KEY_FILE = MY_PACKAGE + ".extra.FILE";
74
75 private FileFragment.ContainerActivity mContainerActivity;
76
77 private OCFile mFile = null;
78 private FileListListAdapter mAdapter;
79 private boolean mJustFolders;
80
81 private OCFile mTargetFile;
82
83
84
85 /**
86 * {@inheritDoc}
87 */
88 @Override
89 public void onAttach(Activity activity) {
90 super.onAttach(activity);
91 Log_OC.e(TAG, "onAttach");
92 try {
93 mContainerActivity = (FileFragment.ContainerActivity) activity;
94
95 } catch (ClassCastException e) {
96 throw new ClassCastException(activity.toString() + " must implement " +
97 FileFragment.ContainerActivity.class.getSimpleName());
98 }
99 try {
100 setOnRefreshListener((OnEnforceableRefreshListener) activity);
101
102 } catch (ClassCastException e) {
103 throw new ClassCastException(activity.toString() + " must implement " +
104 SwipeRefreshLayout.OnRefreshListener.class.getSimpleName());
105 }
106 }
107
108
109 @Override
110 public void onDetach() {
111 setOnRefreshListener(null);
112 mContainerActivity = null;
113 super.onDetach();
114 }
115
116 /**
117 * {@inheritDoc}
118 */
119 @Override
120 public void onActivityCreated(Bundle savedInstanceState) {
121 super.onActivityCreated(savedInstanceState);
122 Log_OC.e(TAG, "onActivityCreated() start");
123
124 if (savedInstanceState != null) {
125 mFile = savedInstanceState.getParcelable(KEY_FILE);
126 }
127
128 if (mJustFolders) {
129 setFooterEnabled(false);
130 } else {
131 setFooterEnabled(true);
132 }
133
134 Bundle args = getArguments();
135 mJustFolders = (args == null) ? false : args.getBoolean(ARG_JUST_FOLDERS, false);
136 mAdapter = new FileListListAdapter(
137 mJustFolders,
138 getActivity(),
139 mContainerActivity
140 );
141 setListAdapter(mAdapter);
142
143 registerForContextMenu();
144 }
145
146 /**
147 * Saves the current listed folder.
148 */
149 @Override
150 public void onSaveInstanceState (Bundle outState) {
151 super.onSaveInstanceState(outState);
152 outState.putParcelable(KEY_FILE, mFile);
153 }
154
155 /**
156 * Call this, when the user presses the up button.
157 *
158 * Tries to move up the current folder one level. If the parent folder was removed from the
159 * database, it continues browsing up until finding an existing folders.
160 *
161 * return Count of folder levels browsed up.
162 */
163 public int onBrowseUp() {
164 OCFile parentDir = null;
165 int moveCount = 0;
166
167 if(mFile != null){
168 FileDataStorageManager storageManager = mContainerActivity.getStorageManager();
169
170 String parentPath = null;
171 if (mFile.getParentId() != FileDataStorageManager.ROOT_PARENT_ID) {
172 parentPath = new File(mFile.getRemotePath()).getParent();
173 parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath :
174 parentPath + OCFile.PATH_SEPARATOR;
175 parentDir = storageManager.getFileByPath(parentPath);
176 moveCount++;
177 } else {
178 parentDir = storageManager.getFileByPath(OCFile.ROOT_PATH);
179 }
180 while (parentDir == null) {
181 parentPath = new File(parentPath).getParent();
182 parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath :
183 parentPath + OCFile.PATH_SEPARATOR;
184 parentDir = storageManager.getFileByPath(parentPath);
185 moveCount++;
186 } // exit is granted because storageManager.getFileByPath("/") never returns null
187 mFile = parentDir;
188
189 // TODO Enable when "On Device" is recovered ?
190 listDirectory(mFile /*, MainApp.getOnlyOnDevice()*/);
191
192 onRefresh(false);
193
194 // restore index and top position
195 restoreIndexAndTopPosition();
196
197 } // else - should never happen now
198
199 return moveCount;
200 }
201
202 @Override
203 public void onItemClick(AdapterView<?> l, View v, int position, long id) {
204 OCFile file = (OCFile) mAdapter.getItem(position);
205 if (file != null) {
206 if (file.isFolder()) {
207 // update state and view of this fragment
208 // TODO Enable when "On Device" is recovered ?
209 listDirectory(file/*, MainApp.getOnlyOnDevice()*/);
210 // then, notify parent activity to let it update its state and view
211 mContainerActivity.onBrowsedDownTo(file);
212 // save index and top position
213 saveIndexAndTopPosition(position);
214
215 } else { /// Click on a file
216 if (PreviewImageFragment.canBePreviewed(file)) {
217 // preview image - it handles the download, if needed
218 ((FileDisplayActivity)mContainerActivity).startImagePreview(file);
219 } else if (PreviewTextFragment.canBePreviewed(file)){
220 ((FileDisplayActivity)mContainerActivity).startTextPreview(file);
221 } else if (file.isDown()) {
222 if (PreviewMediaFragment.canBePreviewed(file)) {
223 // media preview
224 ((FileDisplayActivity)mContainerActivity).startMediaPreview(file, 0, true);
225 } else {
226 mContainerActivity.getFileOperationsHelper().openFile(file);
227 }
228
229 } else {
230 // automatic download, preview on finish
231 ((FileDisplayActivity)mContainerActivity).startDownloadForPreview(file);
232 }
233
234 }
235
236 } else {
237 Log_OC.d(TAG, "Null object in ListAdapter!!");
238 }
239
240 }
241
242 /**
243 * {@inheritDoc}
244 */
245 @Override
246 public void onCreateContextMenu (
247 ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
248 super.onCreateContextMenu(menu, v, menuInfo);
249 Bundle args = getArguments();
250 boolean allowContextualActions =
251 (args == null) ? true : args.getBoolean(ARG_ALLOW_CONTEXTUAL_ACTIONS, true);
252 if (allowContextualActions) {
253 MenuInflater inflater = getActivity().getMenuInflater();
254 inflater.inflate(R.menu.file_actions_menu, menu);
255 AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
256 OCFile targetFile = (OCFile) mAdapter.getItem(info.position);
257
258 if (mContainerActivity.getStorageManager() != null) {
259 FileMenuFilter mf = new FileMenuFilter(
260 targetFile,
261 mContainerActivity.getStorageManager().getAccount(),
262 mContainerActivity,
263 getActivity()
264 );
265 mf.filter(menu);
266 }
267
268 /// TODO break this direct dependency on FileDisplayActivity... if possible
269 MenuItem item = menu.findItem(R.id.action_open_file_with);
270 FileFragment frag = ((FileDisplayActivity)getActivity()).getSecondFragment();
271 if (frag != null && frag instanceof FileDetailFragment &&
272 frag.getFile().getFileId() == targetFile.getFileId()) {
273 item = menu.findItem(R.id.action_see_details);
274 if (item != null) {
275 item.setVisible(false);
276 item.setEnabled(false);
277 }
278 }
279 }
280 }
281
282
283 /**
284 * {@inhericDoc}
285 */
286 @Override
287 public boolean onContextItemSelected (MenuItem item) {
288 AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
289 mTargetFile = (OCFile) mAdapter.getItem(info.position);
290 switch (item.getItemId()) {
291 case R.id.action_share_file: {
292 mContainerActivity.getFileOperationsHelper().shareFileWithLink(mTargetFile);
293 return true;
294 }
295 case R.id.action_open_file_with: {
296 mContainerActivity.getFileOperationsHelper().openFile(mTargetFile);
297 return true;
298 }
299 case R.id.action_unshare_file: {
300 mContainerActivity.getFileOperationsHelper().unshareFileWithLink(mTargetFile);
301 return true;
302 }
303 case R.id.action_rename_file: {
304 RenameFileDialogFragment dialog = RenameFileDialogFragment.newInstance(mTargetFile);
305 dialog.show(getFragmentManager(), FileDetailFragment.FTAG_RENAME_FILE);
306 return true;
307 }
308 case R.id.action_remove_file: {
309 RemoveFileDialogFragment dialog = RemoveFileDialogFragment.newInstance(mTargetFile);
310 dialog.show(getFragmentManager(), ConfirmationDialogFragment.FTAG_CONFIRMATION);
311 return true;
312 }
313 case R.id.action_download_file:
314 case R.id.action_sync_file: {
315 mContainerActivity.getFileOperationsHelper().syncFile(mTargetFile);
316 return true;
317 }
318 case R.id.action_cancel_download:
319 case R.id.action_cancel_upload: {
320 ((FileDisplayActivity)mContainerActivity).cancelTransference(mTargetFile);
321 return true;
322 }
323 case R.id.action_see_details: {
324 mContainerActivity.showDetails(mTargetFile);
325 return true;
326 }
327 case R.id.action_send_file: {
328 // Obtain the file
329 if (!mTargetFile.isDown()) { // Download the file
330 Log_OC.d(TAG, mTargetFile.getRemotePath() + " : File must be downloaded");
331 ((FileDisplayActivity)mContainerActivity).startDownloadForSending(mTargetFile);
332
333 } else {
334 mContainerActivity.getFileOperationsHelper().sendDownloadedFile(mTargetFile);
335 }
336 return true;
337 }
338 case R.id.action_move: {
339 Intent action = new Intent(getActivity(), FolderPickerActivity.class);
340
341 // Pass mTargetFile that contains info of selected file/folder
342 action.putExtra(FolderPickerActivity.EXTRA_FILE, mTargetFile);
343 getActivity().startActivityForResult(action, FileDisplayActivity.ACTION_MOVE_FILES);
344 return true;
345 }
346 case R.id.action_favorite_file:{
347 mContainerActivity.getFileOperationsHelper().toggleFavorite(mTargetFile, true);
348 return true;
349 }
350 case R.id.action_unfavorite_file:{
351 mContainerActivity.getFileOperationsHelper().toggleFavorite(mTargetFile, false);
352 return true;
353 }
354 default:
355 return super.onContextItemSelected(item);
356 }
357 }
358
359
360 /**
361 * Use this to query the {@link OCFile} that is currently
362 * being displayed by this fragment
363 * @return The currently viewed OCFile
364 */
365 public OCFile getCurrentFile(){
366 return mFile;
367 }
368
369 /**
370 * Calls {@link OCFileListFragment#listDirectory(OCFile)} with a null parameter
371 */
372 public void listDirectory(/*boolean onlyOnDevice*/){
373 listDirectory(null);
374 // TODO Enable when "On Device" is recovered ?
375 // listDirectory(null, onlyOnDevice);
376 }
377
378 public void refreshDirectory(){
379 // TODO Enable when "On Device" is recovered ?
380 listDirectory(getCurrentFile()/*, MainApp.getOnlyOnDevice()*/);
381 }
382
383 /**
384 * Lists the given directory on the view. When the input parameter is null,
385 * it will either refresh the last known directory. list the root
386 * if there never was a directory.
387 *
388 * @param directory File to be listed
389 */
390 public void listDirectory(OCFile directory/*, boolean onlyOnDevice*/) {
391 FileDataStorageManager storageManager = mContainerActivity.getStorageManager();
392 if (storageManager != null) {
393
394 // Check input parameters for null
395 if(directory == null){
396 if(mFile != null){
397 directory = mFile;
398 } else {
399 directory = storageManager.getFileByPath("/");
400 if (directory == null) return; // no files, wait for sync
401 }
402 }
403
404
405 // If that's not a directory -> List its parent
406 if(!directory.isFolder()){
407 Log_OC.w(TAG, "You see, that is not a directory -> " + directory.toString());
408 directory = storageManager.getFileById(directory.getParentId());
409 }
410
411 // TODO Enable when "On Device" is recovered ?
412 mAdapter.swapDirectory(directory, storageManager/*, onlyOnDevice*/);
413 if (mFile == null || !mFile.equals(directory)) {
414 mCurrentListView.setSelection(0);
415 }
416 mFile = directory;
417
418 updateLayout();
419
420 }
421 }
422
423 private void updateLayout() {
424 if (!mJustFolders) {
425 int filesCount = 0, foldersCount = 0, imagesCount = 0;
426 int count = mAdapter.getCount();
427 OCFile file;
428 for (int i=0; i < count ; i++) {
429 file = (OCFile) mAdapter.getItem(i);
430 if (file.isFolder()) {
431 foldersCount++;
432 } else {
433 filesCount++;
434 if (file.isImage()){
435 imagesCount++;
436 }
437 }
438 }
439 // set footer text
440 setFooterText(generateFooterText(filesCount, foldersCount));
441
442 // decide grid vs list view
443 OwnCloudVersion version = AccountUtils.getServerVersion(
444 ((FileActivity)mContainerActivity).getAccount());
445 if (version != null && version.supportsRemoteThumbnails() &&
446 imagesCount > 0 && imagesCount == filesCount) {
447 switchToGridView();
448 } else {
449 switchToListView();
450 }
451 }
452 }
453
454 private String generateFooterText(int filesCount, int foldersCount) {
455 String output;
456 if (filesCount <= 0) {
457 if (foldersCount <= 0) {
458 output = "";
459
460 } else if (foldersCount == 1) {
461 output = getResources().getString(R.string.file_list__footer__folder);
462
463 } else { // foldersCount > 1
464 output = getResources().getString(R.string.file_list__footer__folders, foldersCount);
465 }
466
467 } else if (filesCount == 1) {
468 if (foldersCount <= 0) {
469 output = getResources().getString(R.string.file_list__footer__file);
470
471 } else if (foldersCount == 1) {
472 output = getResources().getString(R.string.file_list__footer__file_and_folder);
473
474 } else { // foldersCount > 1
475 output = getResources().getString(R.string.file_list__footer__file_and_folders, foldersCount);
476 }
477 } else { // filesCount > 1
478 if (foldersCount <= 0) {
479 output = getResources().getString(R.string.file_list__footer__files, filesCount);
480
481 } else if (foldersCount == 1) {
482 output = getResources().getString(R.string.file_list__footer__files_and_folder, filesCount);
483
484 } else { // foldersCount > 1
485 output = getResources().getString(
486 R.string.file_list__footer__files_and_folders, filesCount, foldersCount
487 );
488
489 }
490 }
491 return output;
492 }
493
494
495 public void sortByName(boolean descending) {
496 mAdapter.setSortOrder(FileStorageUtils.SORT_NAME, descending);
497 }
498
499 public void sortByDate(boolean descending) {
500 mAdapter.setSortOrder(FileStorageUtils.SORT_DATE, descending);
501 }
502
503 public void sortBySize(boolean descending) {
504 mAdapter.setSortOrder(FileStorageUtils.SORT_SIZE, descending);
505 }
506
507
508 }