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