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