Merge remote-tracking branch 'upstream/develop' into us4_view_text_files
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / fragment / OCFileListFragment.java
1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2014 ownCloud Inc.
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 *
17 */
18 package com.owncloud.android.ui.fragment;
19
20 import java.io.File;
21 import java.util.Vector;
22
23 import android.app.Activity;
24 import android.content.Context;
25 import android.content.Intent;
26 import android.os.Bundle;
27 import android.support.v4.widget.SwipeRefreshLayout;
28 import android.view.ContextMenu;
29 import android.view.MenuInflater;
30 import android.view.MenuItem;
31 import android.view.View;
32 import android.widget.AdapterView;
33 import android.widget.AdapterView.AdapterContextMenuInfo;
34 import android.widget.TextView;
35 import android.view.LayoutInflater;
36
37 import com.owncloud.android.R;
38 import com.owncloud.android.datamodel.FileDataStorageManager;
39 import com.owncloud.android.datamodel.OCFile;
40 import com.owncloud.android.files.FileMenuFilter;
41 import com.owncloud.android.lib.common.utils.Log_OC;
42 import com.owncloud.android.ui.activity.FileDisplayActivity;
43 import com.owncloud.android.ui.activity.FolderPickerActivity;
44 import com.owncloud.android.ui.activity.OnEnforceableRefreshListener;
45 import com.owncloud.android.ui.adapter.FileListListAdapter;
46 import com.owncloud.android.ui.dialog.ConfirmationDialogFragment;
47 import com.owncloud.android.ui.dialog.RemoveFileDialogFragment;
48 import com.owncloud.android.ui.dialog.RenameFileDialogFragment;
49 import com.owncloud.android.ui.preview.PreviewImageFragment;
50 import com.owncloud.android.ui.preview.PreviewMediaFragment;
51 import com.owncloud.android.ui.preview.PreviewTextFragment;
52
53 /**
54 * A Fragment that lists all files and folders in a given path.
55 *
56 * TODO refactorize to get rid of direct dependency on FileDisplayActivity
57 *
58 * @author Bartek Przybylski
59 * @author masensio
60 * @author David A. Velasco
61 */
62 public class OCFileListFragment extends ExtendedListFragment {
63
64 private static final String TAG = OCFileListFragment.class.getSimpleName();
65
66 private static final String MY_PACKAGE = OCFileListFragment.class.getPackage() != null ?
67 OCFileListFragment.class.getPackage().getName() : "com.owncloud.android.ui.fragment";
68
69 public final static String ARG_JUST_FOLDERS = MY_PACKAGE + ".JUST_FOLDERS";
70 public final static String ARG_ALLOW_CONTEXTUAL_ACTIONS = MY_PACKAGE + ".ALLOW_CONTEXTUAL";
71
72 private static final String KEY_FILE = MY_PACKAGE + ".extra.FILE";
73
74 private FileFragment.ContainerActivity mContainerActivity;
75
76 private OCFile mFile = null;
77 private FileListListAdapter mAdapter;
78 private View mFooterView;
79
80 private OCFile mTargetFile;
81
82
83 /**
84 * {@inheritDoc}
85 */
86 @Override
87 public void onAttach(Activity activity) {
88 super.onAttach(activity);
89 Log_OC.e(TAG, "onAttach");
90 try {
91 mContainerActivity = (FileFragment.ContainerActivity) activity;
92
93 } catch (ClassCastException e) {
94 throw new ClassCastException(activity.toString() + " must implement " +
95 FileFragment.ContainerActivity.class.getSimpleName());
96 }
97 try {
98 setOnRefreshListener((OnEnforceableRefreshListener) activity);
99
100 } catch (ClassCastException e) {
101 throw new ClassCastException(activity.toString() + " must implement " +
102 SwipeRefreshLayout.OnRefreshListener.class.getSimpleName());
103 }
104 }
105
106
107 @Override
108 public void onDetach() {
109 setOnRefreshListener(null);
110 mContainerActivity = null;
111 super.onDetach();
112 }
113
114 /**
115 * {@inheritDoc}
116 */
117 @Override
118 public void onActivityCreated(Bundle savedInstanceState) {
119 super.onActivityCreated(savedInstanceState);
120 Log_OC.e(TAG, "onActivityCreated() start");
121
122 if (savedInstanceState != null) {
123 mFile = savedInstanceState.getParcelable(KEY_FILE);
124 }
125
126 mFooterView = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
127 R.layout.list_footer, null, false);
128 setFooterView(mFooterView);
129
130 Bundle args = getArguments();
131 boolean justFolders = (args == null) ? false : args.getBoolean(ARG_JUST_FOLDERS, false);
132 mAdapter = new FileListListAdapter(
133 justFolders,
134 getSherlockActivity(),
135 mContainerActivity
136 );
137 setListAdapter(mAdapter);
138
139 registerForContextMenu(getListView());
140 getListView().setOnCreateContextMenuListener(this);
141 }
142
143 /**
144 * Saves the current listed folder.
145 */
146 @Override
147 public void onSaveInstanceState (Bundle outState) {
148 super.onSaveInstanceState(outState);
149 outState.putParcelable(KEY_FILE, mFile);
150 }
151
152 /**
153 * Call this, when the user presses the up button.
154 *
155 * Tries to move up the current folder one level. If the parent folder was removed from the
156 * database, it continues browsing up until finding an existing folders.
157 *
158 * return Count of folder levels browsed up.
159 */
160 public int onBrowseUp() {
161 OCFile parentDir = null;
162 int moveCount = 0;
163
164 if(mFile != null){
165 FileDataStorageManager storageManager = mContainerActivity.getStorageManager();
166
167 String parentPath = null;
168 if (mFile.getParentId() != FileDataStorageManager.ROOT_PARENT_ID) {
169 parentPath = new File(mFile.getRemotePath()).getParent();
170 parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath :
171 parentPath + OCFile.PATH_SEPARATOR;
172 parentDir = storageManager.getFileByPath(parentPath);
173 moveCount++;
174 } else {
175 parentDir = storageManager.getFileByPath(OCFile.ROOT_PATH);
176 }
177 while (parentDir == null) {
178 parentPath = new File(parentPath).getParent();
179 parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath :
180 parentPath + OCFile.PATH_SEPARATOR;
181 parentDir = storageManager.getFileByPath(parentPath);
182 moveCount++;
183 } // exit is granted because storageManager.getFileByPath("/") never returns null
184 mFile = parentDir;
185
186 listDirectory(mFile);
187
188 onRefresh(false);
189
190 // restore index and top position
191 restoreIndexAndTopPosition();
192
193 } // else - should never happen now
194
195 return moveCount;
196 }
197
198 @Override
199 public void onItemClick(AdapterView<?> l, View v, int position, long id) {
200 OCFile file = (OCFile) mAdapter.getItem(position);
201 if (file != null) {
202 if (file.isFolder()) {
203 // update state and view of this fragment
204 listDirectory(file);
205 // then, notify parent activity to let it update its state and view
206 mContainerActivity.onBrowsedDownTo(file);
207 // save index and top position
208 saveIndexAndTopPosition(position);
209
210 } else { /// Click on a file
211 if (PreviewImageFragment.canBePreviewed(file)) {
212 // preview image - it handles the download, if needed
213 ((FileDisplayActivity)mContainerActivity).startImagePreview(file);
214 } else if (PreviewTextFragment.canBePreviewed(file)){
215 ((FileDisplayActivity)mContainerActivity).startTextPreview(file);
216 } else if (file.isDown()) {
217 if (PreviewMediaFragment.canBePreviewed(file)) {
218 // media preview
219 ((FileDisplayActivity)mContainerActivity).startMediaPreview(file, 0, true);
220 } else {
221 mContainerActivity.getFileOperationsHelper().openFile(file);
222 }
223
224 } else {
225 // automatic download, preview on finish
226 ((FileDisplayActivity)mContainerActivity).startDownloadForPreview(file);
227 }
228
229 }
230
231 } else {
232 Log_OC.d(TAG, "Null object in ListAdapter!!");
233 }
234
235 }
236
237 /**
238 * {@inheritDoc}
239 */
240 @Override
241 public void onCreateContextMenu (
242 ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
243 super.onCreateContextMenu(menu, v, menuInfo);
244 Bundle args = getArguments();
245 boolean allowContextualActions =
246 (args == null) ? true : args.getBoolean(ARG_ALLOW_CONTEXTUAL_ACTIONS, true);
247 if (allowContextualActions) {
248 MenuInflater inflater = getSherlockActivity().getMenuInflater();
249 inflater.inflate(R.menu.file_actions_menu, menu);
250 AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
251 OCFile targetFile = (OCFile) mAdapter.getItem(info.position);
252
253 if (mContainerActivity.getStorageManager() != null) {
254 FileMenuFilter mf = new FileMenuFilter(
255 targetFile,
256 mContainerActivity.getStorageManager().getAccount(),
257 mContainerActivity,
258 getSherlockActivity()
259 );
260 mf.filter(menu);
261 }
262
263 /// additional restrictions for this fragment
264 // TODO allow in the future 'open with' for previewable files
265 MenuItem item = menu.findItem(R.id.action_open_file_with);
266 if (item != null) {
267 item.setVisible(false);
268 item.setEnabled(false);
269 }
270 /// TODO break this direct dependency on FileDisplayActivity... if possible
271 FileFragment frag = ((FileDisplayActivity)getSherlockActivity()).getSecondFragment();
272 if (frag != null && frag instanceof FileDetailFragment &&
273 frag.getFile().getFileId() == targetFile.getFileId()) {
274 item = menu.findItem(R.id.action_see_details);
275 if (item != null) {
276 item.setVisible(false);
277 item.setEnabled(false);
278 }
279 }
280 }
281 }
282
283
284 /**
285 * {@inhericDoc}
286 */
287 @Override
288 public boolean onContextItemSelected (MenuItem item) {
289 AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
290 mTargetFile = (OCFile) mAdapter.getItem(info.position);
291 switch (item.getItemId()) {
292 case R.id.action_share_file: {
293 mContainerActivity.getFileOperationsHelper().shareFileWithLink(mTargetFile);
294 return true;
295 }
296 case R.id.action_unshare_file: {
297 mContainerActivity.getFileOperationsHelper().unshareFileWithLink(mTargetFile);
298 return true;
299 }
300 case R.id.action_rename_file: {
301 RenameFileDialogFragment dialog = RenameFileDialogFragment.newInstance(mTargetFile);
302 dialog.show(getFragmentManager(), FileDetailFragment.FTAG_RENAME_FILE);
303 return true;
304 }
305 case R.id.action_remove_file: {
306 RemoveFileDialogFragment dialog = RemoveFileDialogFragment.newInstance(mTargetFile);
307 dialog.show(getFragmentManager(), ConfirmationDialogFragment.FTAG_CONFIRMATION);
308 return true;
309 }
310 case R.id.action_download_file:
311 case R.id.action_sync_file: {
312 mContainerActivity.getFileOperationsHelper().syncFile(mTargetFile);
313 return true;
314 }
315 case R.id.action_cancel_download:
316 case R.id.action_cancel_upload: {
317 ((FileDisplayActivity)mContainerActivity).cancelTransference(mTargetFile);
318 return true;
319 }
320 case R.id.action_see_details: {
321 mContainerActivity.showDetails(mTargetFile);
322 return true;
323 }
324 case R.id.action_send_file: {
325 // Obtain the file
326 if (!mTargetFile.isDown()) { // Download the file
327 Log_OC.d(TAG, mTargetFile.getRemotePath() + " : File must be downloaded");
328 ((FileDisplayActivity)mContainerActivity).startDownloadForSending(mTargetFile);
329
330 } else {
331 mContainerActivity.getFileOperationsHelper().sendDownloadedFile(mTargetFile);
332 }
333 return true;
334 }
335 case R.id.action_move: {
336 Intent action = new Intent(getActivity(), FolderPickerActivity.class);
337
338 // Pass mTargetFile that contains info of selected file/folder
339 action.putExtra(FolderPickerActivity.EXTRA_FILE, mTargetFile);
340 getActivity().startActivityForResult(action, FileDisplayActivity.ACTION_MOVE_FILES);
341 return true;
342 }
343 default:
344 return super.onContextItemSelected(item);
345 }
346 }
347
348
349 /**
350 * Use this to query the {@link OCFile} that is currently
351 * being displayed by this fragment
352 * @return The currently viewed OCFile
353 */
354 public OCFile getCurrentFile(){
355 return mFile;
356 }
357
358 /**
359 * Calls {@link OCFileListFragment#listDirectory(OCFile)} with a null parameter
360 */
361 public void listDirectory(){
362 listDirectory(null);
363 }
364
365 /**
366 * Lists the given directory on the view. When the input parameter is null,
367 * it will either refresh the last known directory. list the root
368 * if there never was a directory.
369 *
370 * @param directory File to be listed
371 */
372 public void listDirectory(OCFile directory) {
373 FileDataStorageManager storageManager = mContainerActivity.getStorageManager();
374 if (storageManager != null) {
375
376 // Check input parameters for null
377 if(directory == null){
378 if(mFile != null){
379 directory = mFile;
380 } else {
381 directory = storageManager.getFileByPath("/");
382 if (directory == null) return; // no files, wait for sync
383 }
384 }
385
386
387 // If that's not a directory -> List its parent
388 if(!directory.isFolder()){
389 Log_OC.w(TAG, "You see, that is not a directory -> " + directory.toString());
390 directory = storageManager.getFileById(directory.getParentId());
391 }
392
393 mAdapter.swapDirectory(directory, storageManager);
394 if (mFile == null || !mFile.equals(directory)) {
395 mList.setSelectionFromTop(0, 0);
396 }
397 mFile = directory;
398
399 // Update Footer
400 TextView footerText = (TextView) mFooterView.findViewById(R.id.footerText);
401 Log_OC.d("footer", String.valueOf(System.currentTimeMillis()));
402 footerText.setText(generateFooterText(directory));
403 Log_OC.d("footer", String.valueOf(System.currentTimeMillis()));
404 }
405 }
406
407 private String generateFooterText(OCFile directory) {
408 Integer files = 0;
409 Integer folders = 0;
410
411 FileDataStorageManager storageManager = mContainerActivity.getStorageManager();
412 Vector<OCFile> mFiles = storageManager.getFolderContent(mFile);
413
414 for (OCFile ocFile : mFiles) {
415 if (ocFile.isFolder()) {
416 folders++;
417 } else {
418 files++;
419 }
420 }
421
422 String output = "";
423
424 if (files > 0){
425 if (files == 1) {
426 output = output + files.toString() + " " + getResources().getString(R.string.file_list_file);
427 } else {
428 output = output + files.toString() + " " + getResources().getString(R.string.file_list_files);
429 }
430 }
431 if (folders > 0 && files > 0){
432 output = output + ", ";
433 }
434 if (folders == 1) {
435 output = output + folders.toString() + " " + getResources().getString(R.string.file_list_folder);
436 } else if (folders > 1) {
437 output = output + folders.toString() + " " + getResources().getString(R.string.file_list_folders);
438 }
439
440 return output;
441 }
442
443 public void sortByName(boolean descending) {
444 mAdapter.setSortOrder(FileListListAdapter.SORT_NAME, descending);
445 }
446
447 public void sortByDate(boolean descending) {
448 mAdapter.setSortOrder(FileListListAdapter.SORT_DATE, descending);
449 }
450
451 public void sortBySize(boolean descending) {
452 mAdapter.setSortOrder(FileListListAdapter.SORT_SIZE, descending);
453 }
454
455 }