19a482c5579e949fe03fc5306ebbfc98bd651122
[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.ArrayList;
22 import java.util.List;
23
24 import com.owncloud.android.R;
25 import com.owncloud.android.authentication.AccountUtils;
26 import com.owncloud.android.datamodel.FileDataStorageManager;
27 import com.owncloud.android.datamodel.OCFile;
28 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
29 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
30 import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;
31 import com.owncloud.android.lib.common.operations.RemoteOperation;
32 import com.owncloud.android.operations.RemoveFileOperation;
33 import com.owncloud.android.operations.RenameFileOperation;
34 import com.owncloud.android.operations.SynchronizeFileOperation;
35 import com.owncloud.android.ui.activity.FileDisplayActivity;
36 import com.owncloud.android.ui.activity.TransferServiceGetter;
37 import com.owncloud.android.ui.adapter.FileListListAdapter;
38 import com.owncloud.android.ui.dialog.EditNameDialog;
39 import com.owncloud.android.ui.dialog.EditNameDialog.EditNameDialogListener;
40 import com.owncloud.android.ui.fragment.ConfirmationDialogFragment.ConfirmationDialogFragmentListener;
41 import com.owncloud.android.ui.preview.PreviewImageFragment;
42 import com.owncloud.android.ui.preview.PreviewMediaFragment;
43 import com.owncloud.android.utils.Log_OC;
44
45 import android.accounts.Account;
46 import android.app.Activity;
47 import android.os.Bundle;
48 import android.os.Handler;
49 import android.view.ContextMenu;
50 import android.view.MenuInflater;
51 import android.view.MenuItem;
52 import android.view.View;
53 import android.widget.AdapterView;
54 import android.widget.AdapterView.AdapterContextMenuInfo;
55
56 /**
57 * A Fragment that lists all files and folders in a given path.
58 *
59 * @author Bartek Przybylski
60 *
61 */
62 public class OCFileListFragment extends ExtendedListFragment implements EditNameDialogListener, ConfirmationDialogFragmentListener {
63
64 private static final String TAG = OCFileListFragment.class.getSimpleName();
65
66 private static final String MY_PACKAGE = OCFileListFragment.class.getPackage() != null ? OCFileListFragment.class.getPackage().getName() : "com.owncloud.android.ui.fragment";
67 private static final String EXTRA_FILE = MY_PACKAGE + ".extra.FILE";
68
69 private static final String KEY_INDEXES = "INDEXES";
70 private static final String KEY_FIRST_POSITIONS= "FIRST_POSITIONS";
71 private static final String KEY_TOPS = "TOPS";
72 private static final String KEY_HEIGHT_CELL = "HEIGHT_CELL";
73
74 private OCFileListFragment.ContainerActivity mContainerActivity;
75
76 private OCFile mFile = null;
77 private FileListListAdapter mAdapter;
78
79 private Handler mHandler;
80 private OCFile mTargetFile;
81
82 // Save the state of the scroll in browsing
83 private ArrayList<Integer> mIndexes;
84 private ArrayList<Integer> mFirstPositions;
85 private ArrayList<Integer> mTops;
86
87 private int mHeightCell = 0;
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 = (ContainerActivity) activity;
98 } catch (ClassCastException e) {
99 throw new ClassCastException(activity.toString() + " must implement " + OCFileListFragment.ContainerActivity.class.getSimpleName());
100 }
101 }
102
103
104 /**
105 * {@inheritDoc}
106 */
107 @Override
108 public void onActivityCreated(Bundle savedInstanceState) {
109 super.onActivityCreated(savedInstanceState);
110 Log_OC.e(TAG, "onActivityCreated() start");
111
112 if (savedInstanceState != null) {
113 mFile = savedInstanceState.getParcelable(EXTRA_FILE);
114 mIndexes = savedInstanceState.getIntegerArrayList(KEY_INDEXES);
115 mFirstPositions = savedInstanceState.getIntegerArrayList(KEY_FIRST_POSITIONS);
116 mTops = savedInstanceState.getIntegerArrayList(KEY_TOPS);
117 mHeightCell = savedInstanceState.getInt(KEY_HEIGHT_CELL);
118
119 } else {
120 mIndexes = new ArrayList<Integer>();
121 mFirstPositions = new ArrayList<Integer>();
122 mTops = new ArrayList<Integer>();
123 mHeightCell = 0;
124
125 }
126
127 mAdapter = new FileListListAdapter(getActivity(), mContainerActivity, mFile);
128
129 setListAdapter(mAdapter);
130
131 registerForContextMenu(getListView());
132 getListView().setOnCreateContextMenuListener(this);
133
134 mHandler = new Handler();
135
136 }
137
138 /**
139 * Saves the current listed folder.
140 */
141 @Override
142 public void onSaveInstanceState (Bundle outState) {
143 super.onSaveInstanceState(outState);
144 outState.putParcelable(EXTRA_FILE, mFile);
145 outState.putIntegerArrayList(KEY_INDEXES, mIndexes);
146 outState.putIntegerArrayList(KEY_FIRST_POSITIONS, mFirstPositions);
147 outState.putIntegerArrayList(KEY_TOPS, mTops);
148 outState.putInt(KEY_HEIGHT_CELL, mHeightCell);
149 }
150
151 /**
152 * Call this, when the user presses the up button.
153 *
154 * Tries to move up the current folder one level. If the parent folder was removed from the database,
155 * it continues browsing up until finding an existing folders.
156 *
157 * return Count of folder levels browsed up.
158 */
159 public int onBrowseUp() {
160 OCFile parentDir = null;
161 int moveCount = 0;
162
163 if(mFile != null){
164 FileDataStorageManager storageManager = mContainerActivity.getStorageManager();
165
166 String parentPath = null;
167 if (mFile.getParentId() != FileDataStorageManager.ROOT_PARENT_ID) {
168 parentPath = new File(mFile.getRemotePath()).getParent();
169 parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath : parentPath + OCFile.PATH_SEPARATOR;
170 parentDir = storageManager.getFileByPath(parentPath);
171 moveCount++;
172 } else {
173 parentDir = storageManager.getFileByPath(OCFile.ROOT_PATH); // never returns null; keep the path in root folder
174 }
175 while (parentDir == null) {
176 parentPath = new File(parentPath).getParent();
177 parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath : parentPath + OCFile.PATH_SEPARATOR;
178 parentDir = storageManager.getFileByPath(parentPath);
179 moveCount++;
180 } // exit is granted because storageManager.getFileByPath("/") never returns null
181 mFile = parentDir;
182 }
183
184 if (mFile != null) {
185 listDirectory(mFile);
186
187 mContainerActivity.startSyncFolderOperation(mFile);
188
189 // restore index and top position
190 restoreIndexAndTopPosition();
191
192 } // else - should never happen now
193
194 return moveCount;
195 }
196
197 /*
198 * Restore index and position
199 */
200 private void restoreIndexAndTopPosition() {
201 if (mIndexes.size() > 0) {
202 // needs to be checked; not every browse-up had a browse-down before
203
204 int index = mIndexes.remove(mIndexes.size() - 1);
205
206 int firstPosition = mFirstPositions.remove(mFirstPositions.size() -1);
207
208 int top = mTops.remove(mTops.size() - 1);
209
210 mList.setSelectionFromTop(firstPosition, top);
211
212 // Move the scroll if the selection is not visible
213 int indexPosition = mHeightCell*index;
214 int height = mList.getHeight();
215
216 if (indexPosition > height) {
217 if (android.os.Build.VERSION.SDK_INT >= 11)
218 {
219 mList.smoothScrollToPosition(index);
220 }
221 else if (android.os.Build.VERSION.SDK_INT >= 8)
222 {
223 mList.setSelectionFromTop(index, 0);
224 }
225
226 }
227 }
228 }
229
230 /*
231 * Save index and top position
232 */
233 private void saveIndexAndTopPosition(int index) {
234
235 mIndexes.add(index);
236
237 int firstPosition = mList.getFirstVisiblePosition();
238 mFirstPositions.add(firstPosition);
239
240 View view = mList.getChildAt(0);
241 int top = (view == null) ? 0 : view.getTop() ;
242
243 mTops.add(top);
244
245 // Save the height of a cell
246 mHeightCell = (view == null || mHeightCell != 0) ? mHeightCell : view.getHeight();
247 }
248
249 @Override
250 public void onItemClick(AdapterView<?> l, View v, int position, long id) {
251 OCFile file = (OCFile) mAdapter.getItem(position);
252 if (file != null) {
253 if (file.isFolder()) {
254 // update state and view of this fragment
255 listDirectory(file);
256 // then, notify parent activity to let it update its state and view, and other fragments
257 mContainerActivity.onBrowsedDownTo(file);
258 // save index and top position
259 saveIndexAndTopPosition(position);
260
261 } else { /// Click on a file
262 if (PreviewImageFragment.canBePreviewed(file)) {
263 // preview image - it handles the download, if needed
264 mContainerActivity.startImagePreview(file);
265
266 } else if (file.isDown()) {
267 if (PreviewMediaFragment.canBePreviewed(file)) {
268 // media preview
269 mContainerActivity.startMediaPreview(file, 0, true);
270 } else {
271 FileDisplayActivity activity = (FileDisplayActivity) getSherlockActivity();
272 activity.getFileOperationsHelper().openFile(file, activity);
273 }
274
275 } else {
276 // automatic download, preview on finish
277 mContainerActivity.startDownloadForPreview(file);
278 }
279
280 }
281
282 } else {
283 Log_OC.d(TAG, "Null object in ListAdapter!!");
284 }
285
286 }
287
288 /**
289 * {@inheritDoc}
290 */
291 @Override
292 public void onCreateContextMenu (ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
293 super.onCreateContextMenu(menu, v, menuInfo);
294 MenuInflater inflater = getActivity().getMenuInflater();
295 inflater.inflate(R.menu.file_actions_menu, menu);
296 AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
297 OCFile targetFile = (OCFile) mAdapter.getItem(info.position);
298 List<Integer> toHide = new ArrayList<Integer>();
299 List<Integer> toDisable = new ArrayList<Integer>();
300
301 MenuItem item = null;
302 if (targetFile.isFolder()) {
303 // contextual menu for folders
304 toHide.add(R.id.action_open_file_with);
305 toHide.add(R.id.action_download_file);
306 toHide.add(R.id.action_cancel_download);
307 toHide.add(R.id.action_cancel_upload);
308 toHide.add(R.id.action_sync_file);
309 toHide.add(R.id.action_see_details);
310 toHide.add(R.id.action_send_file);
311 if ( mContainerActivity.getFileDownloaderBinder().isDownloading(AccountUtils.getCurrentOwnCloudAccount(getActivity()), targetFile) ||
312 mContainerActivity.getFileUploaderBinder().isUploading(AccountUtils.getCurrentOwnCloudAccount(getActivity()), targetFile) ) {
313 toDisable.add(R.id.action_rename_file);
314 toDisable.add(R.id.action_remove_file);
315
316 }
317
318 } else {
319 // contextual menu for regular files
320
321 // new design: 'download' and 'open with' won't be available anymore in context menu
322 toHide.add(R.id.action_download_file);
323 toHide.add(R.id.action_open_file_with);
324
325 if (targetFile.isDown()) {
326 toHide.add(R.id.action_cancel_download);
327 toHide.add(R.id.action_cancel_upload);
328
329 } else {
330 toHide.add(R.id.action_sync_file);
331 }
332 if ( mContainerActivity.getFileDownloaderBinder().isDownloading(AccountUtils.getCurrentOwnCloudAccount(getActivity()), targetFile)) {
333 toHide.add(R.id.action_cancel_upload);
334 toDisable.add(R.id.action_rename_file);
335 toDisable.add(R.id.action_remove_file);
336
337 } else if ( mContainerActivity.getFileUploaderBinder().isUploading(AccountUtils.getCurrentOwnCloudAccount(getActivity()), targetFile)) {
338 toHide.add(R.id.action_cancel_download);
339 toDisable.add(R.id.action_rename_file);
340 toDisable.add(R.id.action_remove_file);
341
342 } else {
343 toHide.add(R.id.action_cancel_download);
344 toHide.add(R.id.action_cancel_upload);
345 }
346 }
347
348 // Options shareLink
349 if (!targetFile.isShareByLink()) {
350 toHide.add(R.id.action_unshare_file);
351 }
352
353 // Send file
354 boolean sendEnabled = getString(R.string.send_files_to_other_apps).equalsIgnoreCase("on");
355 if (!sendEnabled) {
356 toHide.add(R.id.action_send_file);
357 }
358
359 for (int i : toHide) {
360 item = menu.findItem(i);
361 if (item != null) {
362 item.setVisible(false);
363 item.setEnabled(false);
364 }
365 }
366
367 for (int i : toDisable) {
368 item = menu.findItem(i);
369 if (item != null) {
370 item.setEnabled(false);
371 }
372 }
373 }
374
375
376 /**
377 * {@inhericDoc}
378 */
379 @Override
380 public boolean onContextItemSelected (MenuItem item) {
381 AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
382 mTargetFile = (OCFile) mAdapter.getItem(info.position);
383 switch (item.getItemId()) {
384 case R.id.action_share_file: {
385 FileDisplayActivity activity = (FileDisplayActivity) getSherlockActivity();
386 activity.getFileOperationsHelper().shareFileWithLink(mTargetFile, activity);
387 return true;
388 }
389 case R.id.action_unshare_file: {
390 FileDisplayActivity activity = (FileDisplayActivity) getSherlockActivity();
391 activity.getFileOperationsHelper().unshareFileWithLink(mTargetFile, activity);
392 return true;
393 }
394 case R.id.action_rename_file: {
395 String fileName = mTargetFile.getFileName();
396 int extensionStart = mTargetFile.isFolder() ? -1 : fileName.lastIndexOf(".");
397 int selectionEnd = (extensionStart >= 0) ? extensionStart : fileName.length();
398 EditNameDialog dialog = EditNameDialog.newInstance(getString(R.string.rename_dialog_title), fileName, 0, selectionEnd, this);
399 dialog.show(getFragmentManager(), EditNameDialog.TAG);
400 return true;
401 }
402 case R.id.action_remove_file: {
403 int messageStringId = R.string.confirmation_remove_alert;
404 int posBtnStringId = R.string.confirmation_remove_remote;
405 int neuBtnStringId = -1;
406 if (mTargetFile.isFolder()) {
407 messageStringId = R.string.confirmation_remove_folder_alert;
408 posBtnStringId = R.string.confirmation_remove_remote_and_local;
409 neuBtnStringId = R.string.confirmation_remove_folder_local;
410 } else if (mTargetFile.isDown()) {
411 posBtnStringId = R.string.confirmation_remove_remote_and_local;
412 neuBtnStringId = R.string.confirmation_remove_local;
413 }
414 ConfirmationDialogFragment confDialog = ConfirmationDialogFragment.newInstance(
415 messageStringId,
416 new String[]{mTargetFile.getFileName()},
417 posBtnStringId,
418 neuBtnStringId,
419 R.string.common_cancel);
420 confDialog.setOnConfirmationListener(this);
421 confDialog.show(getFragmentManager(), FileDetailFragment.FTAG_CONFIRMATION);
422 return true;
423 }
424 case R.id.action_sync_file: {
425 Account account = AccountUtils.getCurrentOwnCloudAccount(getSherlockActivity());
426 RemoteOperation operation = new SynchronizeFileOperation(mTargetFile, null, mContainerActivity.getStorageManager(), account, true, getSherlockActivity());
427 operation.execute(account, getSherlockActivity(), mContainerActivity, mHandler, getSherlockActivity());
428 ((FileDisplayActivity) getSherlockActivity()).showLoadingDialog();
429 return true;
430 }
431 case R.id.action_cancel_download: {
432 FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
433 Account account = AccountUtils.getCurrentOwnCloudAccount(getActivity());
434 if (downloaderBinder != null && downloaderBinder.isDownloading(account, mTargetFile)) {
435 downloaderBinder.cancel(account, mTargetFile);
436 listDirectory();
437 mContainerActivity.onTransferStateChanged(mTargetFile, false, false);
438 }
439 return true;
440 }
441 case R.id.action_cancel_upload: {
442 FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
443 Account account = AccountUtils.getCurrentOwnCloudAccount(getActivity());
444 if (uploaderBinder != null && uploaderBinder.isUploading(account, mTargetFile)) {
445 uploaderBinder.cancel(account, mTargetFile);
446 listDirectory();
447 mContainerActivity.onTransferStateChanged(mTargetFile, false, false);
448 }
449 return true;
450 }
451 case R.id.action_see_details: {
452 ((FileFragment.ContainerActivity)getActivity()).showDetails(mTargetFile);
453 return true;
454 }
455 case R.id.action_send_file: {
456 // Obtain the file
457 if (!mTargetFile.isDown()) { // Download the file
458 Log_OC.d(TAG, mTargetFile.getRemotePath() + " : File must be downloaded");
459 mContainerActivity.startDownloadForSending(mTargetFile);
460
461 } else {
462
463 FileDisplayActivity activity = (FileDisplayActivity) getSherlockActivity();
464 activity.getFileOperationsHelper().sendDownloadedFile(mTargetFile, activity);
465 }
466 return true;
467 }
468 default:
469 return super.onContextItemSelected(item);
470 }
471 }
472
473
474 /**
475 * Use this to query the {@link OCFile} that is currently
476 * being displayed by this fragment
477 * @return The currently viewed OCFile
478 */
479 public OCFile getCurrentFile(){
480 return mFile;
481 }
482
483 /**
484 * Calls {@link OCFileListFragment#listDirectory(OCFile)} with a null parameter
485 */
486 public void listDirectory(){
487 listDirectory(null);
488 }
489
490 /**
491 * Lists the given directory on the view. When the input parameter is null,
492 * it will either refresh the last known directory. list the root
493 * if there never was a directory.
494 *
495 * @param directory File to be listed
496 */
497 public void listDirectory(OCFile directory) {
498 FileDataStorageManager storageManager = mContainerActivity.getStorageManager();
499 if (storageManager != null) {
500
501 // Check input parameters for null
502 if(directory == null){
503 if(mFile != null){
504 directory = mFile;
505 } else {
506 directory = storageManager.getFileByPath("/");
507 if (directory == null) return; // no files, wait for sync
508 }
509 }
510
511
512 // If that's not a directory -> List its parent
513 if(!directory.isFolder()){
514 Log_OC.w(TAG, "You see, that is not a directory -> " + directory.toString());
515 directory = storageManager.getFileById(directory.getParentId());
516 }
517
518 mAdapter.swapDirectory(directory, storageManager);
519 if (mFile == null || !mFile.equals(directory)) {
520 mList.setSelectionFromTop(0, 0);
521 }
522 mFile = directory;
523 }
524 }
525
526
527
528 /**
529 * Interface to implement by any Activity that includes some instance of FileListFragment
530 *
531 * @author David A. Velasco
532 */
533 public interface ContainerActivity extends TransferServiceGetter, OnRemoteOperationListener {
534
535 /**
536 * Callback method invoked when a the user browsed into a different folder through the list of files
537 *
538 * @param file
539 */
540 public void onBrowsedDownTo(OCFile folder);
541
542 public void startDownloadForPreview(OCFile file);
543
544 public void startMediaPreview(OCFile file, int i, boolean b);
545
546 public void startImagePreview(OCFile file);
547
548 public void startSyncFolderOperation(OCFile folder);
549
550 /**
551 * Getter for the current DataStorageManager in the container activity
552 */
553 public FileDataStorageManager getStorageManager();
554
555
556 /**
557 * Callback method invoked when a the 'transfer state' of a file changes.
558 *
559 * This happens when a download or upload is started or ended for a file.
560 *
561 * This method is necessary by now to update the user interface of the double-pane layout in tablets
562 * because methods {@link FileDownloaderBinder#isDownloading(Account, OCFile)} and {@link FileUploaderBinder#isUploading(Account, OCFile)}
563 * won't provide the needed response before the method where this is called finishes.
564 *
565 * TODO Remove this when the transfer state of a file is kept in the database (other thing TODO)
566 *
567 * @param file OCFile which state changed.
568 * @param downloading Flag signaling if the file is now downloading.
569 * @param uploading Flag signaling if the file is now uploading.
570 */
571 public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading);
572
573 void startDownloadForSending(OCFile file);
574
575 }
576
577
578 @Override
579 public void onDismiss(EditNameDialog dialog) {
580 if (dialog.getResult()) {
581 String newFilename = dialog.getNewFilename();
582 Log_OC.d(TAG, "name edit dialog dismissed with new name " + newFilename);
583 RemoteOperation operation = new RenameFileOperation(mTargetFile,
584 AccountUtils.getCurrentOwnCloudAccount(getActivity()),
585 newFilename,
586 mContainerActivity.getStorageManager());
587 operation.execute(AccountUtils.getCurrentOwnCloudAccount(getSherlockActivity()), getSherlockActivity(), mContainerActivity, mHandler, getSherlockActivity());
588 ((FileDisplayActivity) getActivity()).showLoadingDialog();
589 }
590 }
591
592
593 @Override
594 public void onConfirmation(String callerTag) {
595 if (callerTag.equals(FileDetailFragment.FTAG_CONFIRMATION)) {
596 if (mContainerActivity.getStorageManager().getFileById(mTargetFile.getFileId()) != null) {
597 RemoteOperation operation = new RemoveFileOperation( mTargetFile,
598 true,
599 mContainerActivity.getStorageManager());
600 operation.execute(AccountUtils.getCurrentOwnCloudAccount(getSherlockActivity()), getSherlockActivity(), mContainerActivity, mHandler, getSherlockActivity());
601
602 ((FileDisplayActivity) getActivity()).showLoadingDialog();
603 }
604 }
605 }
606
607 @Override
608 public void onNeutral(String callerTag) {
609 mContainerActivity.getStorageManager().removeFile(mTargetFile, false, true); // TODO perform in background task / new thread
610 listDirectory();
611 mContainerActivity.onTransferStateChanged(mTargetFile, false, false);
612 }
613
614 @Override
615 public void onCancel(String callerTag) {
616 Log_OC.d(TAG, "REMOVAL CANCELED");
617 }
618
619
620 }