Merge branch 'share_link_show_shared_files' into share_link__new_share
[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.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.FileHandler;
29 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
30 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
31 import com.owncloud.android.lib.operations.common.OnRemoteOperationListener;
32 import com.owncloud.android.lib.operations.common.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.activity.FileDisplayActivity;
37 import com.owncloud.android.ui.activity.TransferServiceGetter;
38 import com.owncloud.android.ui.adapter.FileListListAdapter;
39 import com.owncloud.android.ui.dialog.EditNameDialog;
40 import com.owncloud.android.ui.dialog.EditNameDialog.EditNameDialogListener;
41 import com.owncloud.android.ui.fragment.ConfirmationDialogFragment.ConfirmationDialogFragmentListener;
42 import com.owncloud.android.ui.preview.PreviewImageFragment;
43 import com.owncloud.android.ui.preview.PreviewMediaFragment;
44 import com.owncloud.android.utils.Log_OC;
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_share_file: {
288 mContainerActivity.shareFileWithLink(getCurrentFile());
289 return true;
290 }
291 case R.id.action_rename_file: {
292 String fileName = mTargetFile.getFileName();
293 int extensionStart = mTargetFile.isFolder() ? -1 : fileName.lastIndexOf(".");
294 int selectionEnd = (extensionStart >= 0) ? extensionStart : fileName.length();
295 EditNameDialog dialog = EditNameDialog.newInstance(getString(R.string.rename_dialog_title), fileName, 0, selectionEnd, this);
296 dialog.show(getFragmentManager(), EditNameDialog.TAG);
297 return true;
298 }
299 case R.id.action_remove_file: {
300 int messageStringId = R.string.confirmation_remove_alert;
301 int posBtnStringId = R.string.confirmation_remove_remote;
302 int neuBtnStringId = -1;
303 if (mTargetFile.isFolder()) {
304 messageStringId = R.string.confirmation_remove_folder_alert;
305 posBtnStringId = R.string.confirmation_remove_remote_and_local;
306 neuBtnStringId = R.string.confirmation_remove_folder_local;
307 } else if (mTargetFile.isDown()) {
308 posBtnStringId = R.string.confirmation_remove_remote_and_local;
309 neuBtnStringId = R.string.confirmation_remove_local;
310 }
311 ConfirmationDialogFragment confDialog = ConfirmationDialogFragment.newInstance(
312 messageStringId,
313 new String[]{mTargetFile.getFileName()},
314 posBtnStringId,
315 neuBtnStringId,
316 R.string.common_cancel);
317 confDialog.setOnConfirmationListener(this);
318 confDialog.show(getFragmentManager(), FileDetailFragment.FTAG_CONFIRMATION);
319 return true;
320 }
321 case R.id.action_sync_file: {
322 Account account = AccountUtils.getCurrentOwnCloudAccount(getSherlockActivity());
323 RemoteOperation operation = new SynchronizeFileOperation(mTargetFile, null, mContainerActivity.getStorageManager(), account, true, getSherlockActivity());
324 operation.execute(account, getSherlockActivity(), mContainerActivity, mHandler, getSherlockActivity());
325 ((FileDisplayActivity) getSherlockActivity()).showLoadingDialog();
326 return true;
327 }
328 case R.id.action_cancel_download: {
329 FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
330 Account account = AccountUtils.getCurrentOwnCloudAccount(getActivity());
331 if (downloaderBinder != null && downloaderBinder.isDownloading(account, mTargetFile)) {
332 downloaderBinder.cancel(account, mTargetFile);
333 listDirectory();
334 mContainerActivity.onTransferStateChanged(mTargetFile, false, false);
335 }
336 return true;
337 }
338 case R.id.action_cancel_upload: {
339 FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
340 Account account = AccountUtils.getCurrentOwnCloudAccount(getActivity());
341 if (uploaderBinder != null && uploaderBinder.isUploading(account, mTargetFile)) {
342 uploaderBinder.cancel(account, mTargetFile);
343 listDirectory();
344 mContainerActivity.onTransferStateChanged(mTargetFile, false, false);
345 }
346 return true;
347 }
348 case R.id.action_see_details: {
349 ((FileFragment.ContainerActivity)getActivity()).showDetails(mTargetFile);
350 return true;
351 }
352 default:
353 return super.onContextItemSelected(item);
354 }
355 }
356
357
358 /**
359 * Use this to query the {@link OCFile} that is currently
360 * being displayed by this fragment
361 * @return The currently viewed OCFile
362 */
363 public OCFile getCurrentFile(){
364 return mFile;
365 }
366
367 /**
368 * Calls {@link OCFileListFragment#listDirectory(OCFile)} with a null parameter
369 */
370 public void listDirectory(){
371 listDirectory(null);
372 }
373
374 /**
375 * Lists the given directory on the view. When the input parameter is null,
376 * it will either refresh the last known directory. list the root
377 * if there never was a directory.
378 *
379 * @param directory File to be listed
380 */
381 public void listDirectory(OCFile directory) {
382 FileDataStorageManager storageManager = mContainerActivity.getStorageManager();
383 if (storageManager != null) {
384
385 // Check input parameters for null
386 if(directory == null){
387 if(mFile != null){
388 directory = mFile;
389 } else {
390 directory = storageManager.getFileByPath("/");
391 if (directory == null) return; // no files, wait for sync
392 }
393 }
394
395
396 // If that's not a directory -> List its parent
397 if(!directory.isFolder()){
398 Log_OC.w(TAG, "You see, that is not a directory -> " + directory.toString());
399 directory = storageManager.getFileById(directory.getParentId());
400 }
401
402 mAdapter.swapDirectory(directory, storageManager);
403 if (mFile == null || !mFile.equals(directory)) {
404 mList.setSelectionFromTop(0, 0);
405 }
406 mFile = directory;
407 }
408 }
409
410
411
412 /**
413 * Interface to implement by any Activity that includes some instance of FileListFragment
414 *
415 * @author David A. Velasco
416 */
417 public interface ContainerActivity extends TransferServiceGetter, OnRemoteOperationListener, FileHandler {
418
419 /**
420 * Callback method invoked when a the user browsed into a different folder through the list of files
421 *
422 * @param file
423 */
424 public void onBrowsedDownTo(OCFile folder);
425
426 public void shareFileWithLink(OCFile currentFile);
427
428 public void startDownloadForPreview(OCFile file);
429
430 public void startMediaPreview(OCFile file, int i, boolean b);
431
432 public void startImagePreview(OCFile file);
433
434 public void startSyncFolderOperation(OCFile folder);
435
436 /**
437 * Getter for the current DataStorageManager in the container activity
438 */
439 public FileDataStorageManager getStorageManager();
440
441
442 /**
443 * Callback method invoked when a the 'transfer state' of a file changes.
444 *
445 * This happens when a download or upload is started or ended for a file.
446 *
447 * This method is necessary by now to update the user interface of the double-pane layout in tablets
448 * because methods {@link FileDownloaderBinder#isDownloading(Account, OCFile)} and {@link FileUploaderBinder#isUploading(Account, OCFile)}
449 * won't provide the needed response before the method where this is called finishes.
450 *
451 * TODO Remove this when the transfer state of a file is kept in the database (other thing TODO)
452 *
453 * @param file OCFile which state changed.
454 * @param downloading Flag signaling if the file is now downloading.
455 * @param uploading Flag signaling if the file is now uploading.
456 */
457 public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading);
458
459 }
460
461
462 @Override
463 public void onDismiss(EditNameDialog dialog) {
464 if (dialog.getResult()) {
465 String newFilename = dialog.getNewFilename();
466 Log_OC.d(TAG, "name edit dialog dismissed with new name " + newFilename);
467 RemoteOperation operation = new RenameFileOperation(mTargetFile,
468 AccountUtils.getCurrentOwnCloudAccount(getActivity()),
469 newFilename,
470 mContainerActivity.getStorageManager());
471 operation.execute(AccountUtils.getCurrentOwnCloudAccount(getSherlockActivity()), getSherlockActivity(), mContainerActivity, mHandler, getSherlockActivity());
472 ((FileDisplayActivity) getActivity()).showLoadingDialog();
473 }
474 }
475
476
477 @Override
478 public void onConfirmation(String callerTag) {
479 if (callerTag.equals(FileDetailFragment.FTAG_CONFIRMATION)) {
480 if (mContainerActivity.getStorageManager().getFileById(mTargetFile.getFileId()) != null) {
481 RemoteOperation operation = new RemoveFileOperation( mTargetFile,
482 true,
483 mContainerActivity.getStorageManager());
484 operation.execute(AccountUtils.getCurrentOwnCloudAccount(getSherlockActivity()), getSherlockActivity(), mContainerActivity, mHandler, getSherlockActivity());
485
486 ((FileDisplayActivity) getActivity()).showLoadingDialog();
487 }
488 }
489 }
490
491 @Override
492 public void onNeutral(String callerTag) {
493 mContainerActivity.getStorageManager().removeFile(mTargetFile, false, true); // TODO perform in background task / new thread
494 listDirectory();
495 mContainerActivity.onTransferStateChanged(mTargetFile, false, false);
496 }
497
498 @Override
499 public void onCancel(String callerTag) {
500 Log_OC.d(TAG, "REMOVAL CANCELED");
501 }
502
503
504 }