Removal of a folder (or file) not already existing in the server is considered a...
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / fragment / OCFileListFragment.java
1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
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.AccountUtils;
25 import com.owncloud.android.R;
26 import com.owncloud.android.datamodel.DataStorageManager;
27 import com.owncloud.android.datamodel.OCFile;
28 import com.owncloud.android.files.services.FileDownloader;
29 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
30 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
31 import com.owncloud.android.network.OwnCloudClientUtils;
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.ui.FragmentListView;
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
44 import eu.alefzero.webdav.WebdavClient;
45 import eu.alefzero.webdav.WebdavUtils;
46
47 import android.accounts.Account;
48 import android.app.Activity;
49 import android.content.ActivityNotFoundException;
50 import android.content.Intent;
51 import android.net.Uri;
52 import android.os.Bundle;
53 import android.os.Handler;
54 import android.util.Log;
55 import android.view.ContextMenu;
56 import android.view.MenuInflater;
57 import android.view.MenuItem;
58 import android.view.View;
59 import android.webkit.MimeTypeMap;
60 import android.widget.AdapterView;
61 import android.widget.Toast;
62 import android.widget.AdapterView.AdapterContextMenuInfo;
63
64 /**
65 * A Fragment that lists all files and folders in a given path.
66 *
67 * @author Bartek Przybylski
68 *
69 */
70 public class OCFileListFragment extends FragmentListView implements EditNameDialogListener, ConfirmationDialogFragmentListener {
71 private static final String TAG = "FileListFragment";
72 private static final String SAVED_LIST_POSITION = "LIST_POSITION";
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
83 /**
84 * {@inheritDoc}
85 */
86 @Override
87 public void onAttach(Activity activity) {
88 super.onAttach(activity);
89 try {
90 mContainerActivity = (ContainerActivity) activity;
91 } catch (ClassCastException e) {
92 throw new ClassCastException(activity.toString() + " must implement " + OCFileListFragment.ContainerActivity.class.getSimpleName());
93 }
94 }
95
96
97 /**
98 * {@inheritDoc}
99 */
100 @Override
101 public void onActivityCreated(Bundle savedInstanceState) {
102 Log.i(TAG, "onActivityCreated() start");
103
104 super.onActivityCreated(savedInstanceState);
105 mAdapter = new FileListListAdapter(mContainerActivity.getInitialDirectory(), mContainerActivity.getStorageManager(), getActivity(), mContainerActivity);
106 setListAdapter(mAdapter);
107
108 if (savedInstanceState != null) {
109 Log.i(TAG, "savedInstanceState is not null");
110 int position = savedInstanceState.getInt(SAVED_LIST_POSITION);
111 setReferencePosition(position);
112 }
113
114 registerForContextMenu(getListView());
115 getListView().setOnCreateContextMenuListener(this);
116
117 mHandler = new Handler();
118
119 Log.i(TAG, "onActivityCreated() stop");
120 }
121
122
123
124 @Override
125 public void onSaveInstanceState(Bundle savedInstanceState) {
126 Log.i(TAG, "onSaveInstanceState() start");
127
128 savedInstanceState.putInt(SAVED_LIST_POSITION, getReferencePosition());
129
130 Log.i(TAG, "onSaveInstanceState() stop");
131 }
132
133
134 @Override
135 public void onItemClick(AdapterView<?> l, View v, int position, long id) {
136 OCFile file = (OCFile) mAdapter.getItem(position);
137 if (file != null) {
138 /// Click on a directory
139 if (file.getMimetype().equals("DIR")) {
140 // just local updates
141 mFile = file;
142 listDirectory(file);
143 // any other updates are let to the container Activity
144 mContainerActivity.onDirectoryClick(file);
145
146 } else { /// Click on a file
147 mContainerActivity.onFileClick(file);
148 }
149
150 } else {
151 Log.d(TAG, "Null object in ListAdapter!!");
152 }
153
154 }
155
156 /**
157 * {@inheritDoc}
158 */
159 @Override
160 public void onCreateContextMenu (ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
161 super.onCreateContextMenu(menu, v, menuInfo);
162 MenuInflater inflater = getActivity().getMenuInflater();
163 inflater.inflate(R.menu.file_context_menu, menu);
164 AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
165 OCFile targetFile = (OCFile) mAdapter.getItem(info.position);
166 List<Integer> toHide = new ArrayList<Integer>();
167 List<Integer> toDisable = new ArrayList<Integer>();
168
169 if (targetFile.isDirectory()) {
170 // contextual menu for folders
171 toHide.add(R.id.open_file_item);
172 toHide.add(R.id.download_file_item);
173 toHide.add(R.id.cancel_download_item);
174 toHide.add(R.id.cancel_upload_item);
175 if ( mContainerActivity.getFileDownloaderBinder().isDownloading(AccountUtils.getCurrentOwnCloudAccount(getActivity()), targetFile) ||
176 mContainerActivity.getFileUploaderBinder().isUploading(AccountUtils.getCurrentOwnCloudAccount(getActivity()), targetFile) ) {
177 toDisable.add(R.id.rename_file_item);
178 toDisable.add(R.id.remove_file_item);
179
180 }
181
182 } else {
183 // contextual menu for regular files
184 if (targetFile.isDown()) {
185 toHide.add(R.id.cancel_download_item);
186 toHide.add(R.id.cancel_upload_item);
187 } else {
188 toHide.add(R.id.open_file_item);
189 }
190 if ( mContainerActivity.getFileDownloaderBinder().isDownloading(AccountUtils.getCurrentOwnCloudAccount(getActivity()), targetFile)) {
191 toHide.add(R.id.download_file_item);
192 toHide.add(R.id.cancel_upload_item);
193 toDisable.add(R.id.open_file_item);
194 toDisable.add(R.id.rename_file_item);
195 toDisable.add(R.id.remove_file_item);
196
197 } else if ( mContainerActivity.getFileUploaderBinder().isUploading(AccountUtils.getCurrentOwnCloudAccount(getActivity()), targetFile)) {
198 toHide.add(R.id.download_file_item);
199 toHide.add(R.id.cancel_download_item);
200 toDisable.add(R.id.open_file_item);
201 toDisable.add(R.id.rename_file_item);
202 toDisable.add(R.id.remove_file_item);
203
204 } else {
205 toHide.add(R.id.cancel_download_item);
206 toHide.add(R.id.cancel_upload_item);
207 }
208 }
209
210 MenuItem item = null;
211 for (int i : toHide) {
212 item = menu.findItem(i);
213 if (item != null) {
214 item.setVisible(false);
215 item.setEnabled(false);
216 }
217 }
218
219 for (int i : toDisable) {
220 item = menu.findItem(i);
221 if (item != null) {
222 item.setEnabled(false);
223 }
224 }
225 }
226
227
228 /**
229 * {@inhericDoc}
230 */
231 @Override
232 public boolean onContextItemSelected (MenuItem item) {
233 AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
234 mTargetFile = (OCFile) mAdapter.getItem(info.position);
235 switch (item.getItemId()) {
236 case R.id.rename_file_item: {
237 EditNameDialog dialog = EditNameDialog.newInstance(getString(R.string.rename_dialog_title), mTargetFile.getFileName(), this);
238 dialog.show(getFragmentManager(), EditNameDialog.TAG);
239 return true;
240 }
241 case R.id.remove_file_item: {
242 int messageStringId = R.string.confirmation_remove_alert;
243 int posBtnStringId = R.string.confirmation_remove_remote;
244 int neuBtnStringId = -1;
245 if (mTargetFile.isDirectory()) {
246 messageStringId = R.string.confirmation_remove_folder_alert;
247 posBtnStringId = R.string.confirmation_remove_remote_and_local;
248 neuBtnStringId = R.string.confirmation_remove_folder_local;
249 } else if (mTargetFile.isDown()) {
250 posBtnStringId = R.string.confirmation_remove_remote_and_local;
251 neuBtnStringId = R.string.confirmation_remove_local;
252 }
253 ConfirmationDialogFragment confDialog = ConfirmationDialogFragment.newInstance(
254 messageStringId,
255 new String[]{mTargetFile.getFileName()},
256 posBtnStringId,
257 neuBtnStringId,
258 R.string.common_cancel);
259 confDialog.setOnConfirmationListener(this);
260 confDialog.show(getFragmentManager(), FileDetailFragment.FTAG_CONFIRMATION);
261 return true;
262 }
263 case R.id.open_file_item: {
264 String storagePath = mTargetFile.getStoragePath();
265 String encodedStoragePath = WebdavUtils.encodePath(storagePath);
266 try {
267 Intent i = new Intent(Intent.ACTION_VIEW);
268 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mTargetFile.getMimetype());
269 i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
270 startActivity(i);
271
272 } catch (Throwable t) {
273 Log.e(TAG, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mTargetFile.getMimetype());
274 boolean toastIt = true;
275 String mimeType = "";
276 try {
277 Intent i = new Intent(Intent.ACTION_VIEW);
278 mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(storagePath.substring(storagePath.lastIndexOf('.') + 1));
279 if (mimeType == null || !mimeType.equals(mTargetFile.getMimetype())) {
280 if (mimeType != null) {
281 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mimeType);
282 } else {
283 // desperate try
284 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), "*/*");
285 }
286 i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
287 startActivity(i);
288 toastIt = false;
289 }
290
291 } catch (IndexOutOfBoundsException e) {
292 Log.e(TAG, "Trying to find out MIME type of a file without extension: " + storagePath);
293
294 } catch (ActivityNotFoundException e) {
295 Log.e(TAG, "No activity found to handle: " + storagePath + " with MIME type " + mimeType + " obtained from extension");
296
297 } catch (Throwable th) {
298 Log.e(TAG, "Unexpected problem when opening: " + storagePath, th);
299
300 } finally {
301 if (toastIt) {
302 Toast.makeText(getActivity(), "There is no application to handle file " + mTargetFile.getFileName(), Toast.LENGTH_SHORT).show();
303 }
304 }
305
306 }
307 return true;
308 }
309 case R.id.download_file_item: {
310 Account account = AccountUtils.getCurrentOwnCloudAccount(getActivity());
311 Intent i = new Intent(getActivity(), FileDownloader.class);
312 i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
313 i.putExtra(FileDownloader.EXTRA_FILE, mTargetFile);
314 getActivity().startService(i);
315 listDirectory();
316 mContainerActivity.onTransferStateChanged(mTargetFile, true, false);
317 return true;
318 }
319 case R.id.cancel_download_item: {
320 FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
321 Account account = AccountUtils.getCurrentOwnCloudAccount(getActivity());
322 if (downloaderBinder != null && downloaderBinder.isDownloading(account, mTargetFile)) {
323 downloaderBinder.cancel(account, mTargetFile);
324 listDirectory();
325 mContainerActivity.onTransferStateChanged(mTargetFile, false, false);
326 }
327 return true;
328 }
329 case R.id.cancel_upload_item: {
330 FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
331 Account account = AccountUtils.getCurrentOwnCloudAccount(getActivity());
332 if (uploaderBinder != null && uploaderBinder.isUploading(account, mTargetFile)) {
333 uploaderBinder.cancel(account, mTargetFile);
334 listDirectory();
335 mContainerActivity.onTransferStateChanged(mTargetFile, false, false);
336 }
337 return true;
338 }
339 default:
340 return super.onContextItemSelected(item);
341 }
342 }
343
344
345 /**
346 * Call this, when the user presses the up button
347 */
348 public void onNavigateUp() {
349 OCFile parentDir = null;
350
351 if(mFile != null){
352 DataStorageManager storageManager = mContainerActivity.getStorageManager();
353 parentDir = storageManager.getFileById(mFile.getParentId());
354 mFile = parentDir;
355 }
356 listDirectory(parentDir);
357 }
358
359 /**
360 * Use this to query the {@link OCFile} that is currently
361 * being displayed by this fragment
362 * @return The currently viewed OCFile
363 */
364 public OCFile getCurrentFile(){
365 return mFile;
366 }
367
368 /**
369 * Calls {@link OCFileListFragment#listDirectory(OCFile)} with a null parameter
370 */
371 public void listDirectory(){
372 listDirectory(null);
373 }
374
375 /**
376 * Lists the given directory on the view. When the input parameter is null,
377 * it will either refresh the last known directory, or list the root
378 * if there never was a directory.
379 *
380 * @param directory File to be listed
381 */
382 public void listDirectory(OCFile directory) {
383 DataStorageManager storageManager = mContainerActivity.getStorageManager();
384 if (storageManager != null) {
385
386 // Check input parameters for null
387 if(directory == null){
388 if(mFile != null){
389 directory = mFile;
390 } else {
391 directory = storageManager.getFileByPath("/");
392 if (directory == null) return; // no files, wait for sync
393 }
394 }
395
396
397 // If that's not a directory -> List its parent
398 if(!directory.isDirectory()){
399 Log.w(TAG, "You see, that is not a directory -> " + directory.toString());
400 directory = storageManager.getFileById(directory.getParentId());
401 }
402
403 mAdapter.swapDirectory(directory, storageManager);
404 if (mFile == null || !mFile.equals(directory)) {
405 mList.setSelectionFromTop(0, 0);
406 }
407 mFile = directory;
408 }
409 }
410
411
412
413 /**
414 * Interface to implement by any Activity that includes some instance of FileListFragment
415 *
416 * @author David A. Velasco
417 */
418 public interface ContainerActivity extends TransferServiceGetter, OnRemoteOperationListener {
419
420 /**
421 * Callback method invoked when a directory is clicked by the user on the files list
422 *
423 * @param file
424 */
425 public void onDirectoryClick(OCFile file);
426
427 /**
428 * Callback method invoked when a file (non directory) is clicked by the user on the files list
429 *
430 * @param file
431 */
432 public void onFileClick(OCFile file);
433
434 /**
435 * Getter for the current DataStorageManager in the container activity
436 */
437 public DataStorageManager getStorageManager();
438
439
440 /**
441 * Callback method invoked when the parent activity is fully created to get the directory to list firstly.
442 *
443 * @return Directory to list firstly. Can be NULL.
444 */
445 public OCFile getInitialDirectory();
446
447
448 /**
449 * Callback method invoked when a the 'transfer state' of a file changes.
450 *
451 * This happens when a download or upload is started or ended for a file.
452 *
453 * This method is necessary by now to update the user interface of the double-pane layout in tablets
454 * because methods {@link FileDownloaderBinder#isDownloading(Account, OCFile)} and {@link FileUploaderBinder#isUploading(Account, OCFile)}
455 * won't provide the needed response before the method where this is called finishes.
456 *
457 * TODO Remove this when the transfer state of a file is kept in the database (other thing TODO)
458 *
459 * @param file OCFile which state changed.
460 * @param downloading Flag signaling if the file is now downloading.
461 * @param uploading Flag signaling if the file is now uploading.
462 */
463 public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading);
464
465 }
466
467
468 @Override
469 public void onDismiss(EditNameDialog dialog) {
470 if (dialog.getResult()) {
471 String newFilename = dialog.getNewFilename();
472 Log.d(TAG, "name edit dialog dismissed with new name " + newFilename);
473 RemoteOperation operation = new RenameFileOperation(mTargetFile,
474 AccountUtils.getCurrentOwnCloudAccount(getActivity()),
475 newFilename,
476 mContainerActivity.getStorageManager());
477 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(AccountUtils.getCurrentOwnCloudAccount(getSherlockActivity()), getSherlockActivity().getApplicationContext());
478 operation.execute(wc, mContainerActivity, mHandler);
479 getActivity().showDialog(FileDisplayActivity.DIALOG_SHORT_WAIT);
480 }
481 }
482
483
484 @Override
485 public void onConfirmation(String callerTag) {
486 if (callerTag.equals(FileDetailFragment.FTAG_CONFIRMATION)) {
487 if (mContainerActivity.getStorageManager().getFileById(mTargetFile.getFileId()) != null) {
488 RemoteOperation operation = new RemoveFileOperation( mTargetFile,
489 true,
490 mContainerActivity.getStorageManager());
491 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(AccountUtils.getCurrentOwnCloudAccount(getSherlockActivity()), getSherlockActivity().getApplicationContext());
492 operation.execute(wc, mContainerActivity, mHandler);
493
494 getActivity().showDialog(FileDisplayActivity.DIALOG_SHORT_WAIT);
495 }
496 }
497 }
498
499 @Override
500 public void onNeutral(String callerTag) {
501 File f = null;
502 if (mTargetFile.isDirectory()) {
503 // TODO run in a secondary thread?
504 mContainerActivity.getStorageManager().removeDirectory(mTargetFile, false, true);
505
506 } else if (mTargetFile.isDown() && (f = new File(mTargetFile.getStoragePath())).exists()) {
507 f.delete();
508 mTargetFile.setStoragePath(null);
509 mContainerActivity.getStorageManager().saveFile(mTargetFile);
510 }
511 listDirectory();
512 mContainerActivity.onTransferStateChanged(mTargetFile, false, false);
513 }
514
515 @Override
516 public void onCancel(String callerTag) {
517 Log.d(TAG, "REMOVAL CANCELED");
518 }
519
520
521 }