OC-922: Synchronize folder, refresh folder size
[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.DataStorageManager;
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.RemoteOperationResult;
35 import com.owncloud.android.operations.RemoveFileOperation;
36 import com.owncloud.android.operations.RenameFileOperation;
37 import com.owncloud.android.operations.SynchronizeFileOperation;
38 import com.owncloud.android.ui.activity.FileDisplayActivity;
39 import com.owncloud.android.ui.activity.TransferServiceGetter;
40 import com.owncloud.android.ui.adapter.FileListListAdapter;
41 import com.owncloud.android.ui.dialog.EditNameDialog;
42 import com.owncloud.android.ui.dialog.EditNameDialog.EditNameDialogListener;
43 import com.owncloud.android.ui.fragment.ConfirmationDialogFragment.ConfirmationDialogFragmentListener;
44 import com.owncloud.android.ui.preview.PreviewImageFragment;
45 import com.owncloud.android.ui.preview.PreviewMediaFragment;
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 public void onBrowseUp() {
128 OCFile parentDir = null;
129
130 if(mFile != null){
131 DataStorageManager storageManager = mContainerActivity.getStorageManager();
132 parentDir = storageManager.getFileById(mFile.getParentId());
133
134 // Update folder size on DB
135 storageManager.calculateFolderSize(mFile.getFileId());
136
137 mFile = parentDir;
138
139 }
140 listDirectory(parentDir);
141
142
143 mContainerActivity.syncFolderOperation(mFile.getRemotePath(), mFile.getParentId());
144
145 }
146
147 @Override
148 public void onItemClick(AdapterView<?> l, View v, int position, long id) {
149 OCFile file = (OCFile) mAdapter.getItem(position);
150 if (file != null) {
151 if (file.isDirectory()) {
152 // update state and view of this fragment
153 listDirectory(file);
154 // then, notify parent activity to let it update its state and view, and other fragments
155 mContainerActivity.onBrowsedDownTo(file);
156
157 } else { /// Click on a file
158 if (PreviewImageFragment.canBePreviewed(file)) {
159 // preview image - it handles the download, if needed
160 mContainerActivity.startImagePreview(file);
161
162 } else if (file.isDown()) {
163 if (PreviewMediaFragment.canBePreviewed(file)) {
164 // media preview
165 mContainerActivity.startMediaPreview(file, 0, true);
166 } else {
167 // open with
168 mContainerActivity.openFile(file);
169 }
170
171 } else {
172 // automatic download, preview on finish
173 mContainerActivity.startDownloadForPreview(file);
174 }
175
176 }
177
178 } else {
179 Log_OC.d(TAG, "Null object in ListAdapter!!");
180 }
181
182 }
183
184 /**
185 * {@inheritDoc}
186 */
187 @Override
188 public void onCreateContextMenu (ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
189 super.onCreateContextMenu(menu, v, menuInfo);
190 MenuInflater inflater = getActivity().getMenuInflater();
191 inflater.inflate(R.menu.file_actions_menu, menu);
192 AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
193 OCFile targetFile = (OCFile) mAdapter.getItem(info.position);
194 List<Integer> toHide = new ArrayList<Integer>();
195 List<Integer> toDisable = new ArrayList<Integer>();
196
197 MenuItem item = null;
198 if (targetFile.isDirectory()) {
199 // contextual menu for folders
200 toHide.add(R.id.action_open_file_with);
201 toHide.add(R.id.action_download_file);
202 toHide.add(R.id.action_cancel_download);
203 toHide.add(R.id.action_cancel_upload);
204 toHide.add(R.id.action_sync_file);
205 toHide.add(R.id.action_see_details);
206 if ( mContainerActivity.getFileDownloaderBinder().isDownloading(AccountUtils.getCurrentOwnCloudAccount(getActivity()), targetFile) ||
207 mContainerActivity.getFileUploaderBinder().isUploading(AccountUtils.getCurrentOwnCloudAccount(getActivity()), targetFile) ) {
208 toDisable.add(R.id.action_rename_file);
209 toDisable.add(R.id.action_remove_file);
210
211 }
212
213 } else {
214 // contextual menu for regular files
215
216 // new design: 'download' and 'open with' won't be available anymore in context menu
217 toHide.add(R.id.action_download_file);
218 toHide.add(R.id.action_open_file_with);
219
220 if (targetFile.isDown()) {
221 toHide.add(R.id.action_cancel_download);
222 toHide.add(R.id.action_cancel_upload);
223
224 } else {
225 toHide.add(R.id.action_sync_file);
226 }
227 if ( mContainerActivity.getFileDownloaderBinder().isDownloading(AccountUtils.getCurrentOwnCloudAccount(getActivity()), targetFile)) {
228 toHide.add(R.id.action_cancel_upload);
229 toDisable.add(R.id.action_rename_file);
230 toDisable.add(R.id.action_remove_file);
231
232 } else if ( mContainerActivity.getFileUploaderBinder().isUploading(AccountUtils.getCurrentOwnCloudAccount(getActivity()), targetFile)) {
233 toHide.add(R.id.action_cancel_download);
234 toDisable.add(R.id.action_rename_file);
235 toDisable.add(R.id.action_remove_file);
236
237 } else {
238 toHide.add(R.id.action_cancel_download);
239 toHide.add(R.id.action_cancel_upload);
240 }
241 }
242
243 for (int i : toHide) {
244 item = menu.findItem(i);
245 if (item != null) {
246 item.setVisible(false);
247 item.setEnabled(false);
248 }
249 }
250
251 for (int i : toDisable) {
252 item = menu.findItem(i);
253 if (item != null) {
254 item.setEnabled(false);
255 }
256 }
257 }
258
259
260 /**
261 * {@inhericDoc}
262 */
263 @Override
264 public boolean onContextItemSelected (MenuItem item) {
265 AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
266 mTargetFile = (OCFile) mAdapter.getItem(info.position);
267 switch (item.getItemId()) {
268 case R.id.action_rename_file: {
269 String fileName = mTargetFile.getFileName();
270 int extensionStart = mTargetFile.isDirectory() ? -1 : fileName.lastIndexOf(".");
271 int selectionEnd = (extensionStart >= 0) ? extensionStart : fileName.length();
272 EditNameDialog dialog = EditNameDialog.newInstance(getString(R.string.rename_dialog_title), fileName, 0, selectionEnd, this);
273 dialog.show(getFragmentManager(), EditNameDialog.TAG);
274 return true;
275 }
276 case R.id.action_remove_file: {
277 int messageStringId = R.string.confirmation_remove_alert;
278 int posBtnStringId = R.string.confirmation_remove_remote;
279 int neuBtnStringId = -1;
280 if (mTargetFile.isDirectory()) {
281 messageStringId = R.string.confirmation_remove_folder_alert;
282 posBtnStringId = R.string.confirmation_remove_remote_and_local;
283 neuBtnStringId = R.string.confirmation_remove_folder_local;
284 } else if (mTargetFile.isDown()) {
285 posBtnStringId = R.string.confirmation_remove_remote_and_local;
286 neuBtnStringId = R.string.confirmation_remove_local;
287 }
288 ConfirmationDialogFragment confDialog = ConfirmationDialogFragment.newInstance(
289 messageStringId,
290 new String[]{mTargetFile.getFileName()},
291 posBtnStringId,
292 neuBtnStringId,
293 R.string.common_cancel);
294 confDialog.setOnConfirmationListener(this);
295 confDialog.show(getFragmentManager(), FileDetailFragment.FTAG_CONFIRMATION);
296 return true;
297 }
298 case R.id.action_sync_file: {
299 Account account = AccountUtils.getCurrentOwnCloudAccount(getSherlockActivity());
300 RemoteOperation operation = new SynchronizeFileOperation(mTargetFile, null, mContainerActivity.getStorageManager(), account, true, false, getSherlockActivity());
301 operation.execute(account, getSherlockActivity(), mContainerActivity, mHandler, getSherlockActivity());
302 getSherlockActivity().showDialog(FileDisplayActivity.DIALOG_SHORT_WAIT);
303 return true;
304 }
305 case R.id.action_cancel_download: {
306 FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
307 Account account = AccountUtils.getCurrentOwnCloudAccount(getActivity());
308 if (downloaderBinder != null && downloaderBinder.isDownloading(account, mTargetFile)) {
309 downloaderBinder.cancel(account, mTargetFile);
310 listDirectory();
311 mContainerActivity.onTransferStateChanged(mTargetFile, false, false);
312 }
313 return true;
314 }
315 case R.id.action_cancel_upload: {
316 FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
317 Account account = AccountUtils.getCurrentOwnCloudAccount(getActivity());
318 if (uploaderBinder != null && uploaderBinder.isUploading(account, mTargetFile)) {
319 uploaderBinder.cancel(account, mTargetFile);
320 listDirectory();
321 mContainerActivity.onTransferStateChanged(mTargetFile, false, false);
322 }
323 return true;
324 }
325 case R.id.action_see_details: {
326 ((FileFragment.ContainerActivity)getActivity()).showDetails(mTargetFile);
327 return true;
328 }
329 default:
330 return super.onContextItemSelected(item);
331 }
332 }
333
334
335 /**
336 * Use this to query the {@link OCFile} that is currently
337 * being displayed by this fragment
338 * @return The currently viewed OCFile
339 */
340 public OCFile getCurrentFile(){
341 return mFile;
342 }
343
344 /**
345 * Calls {@link OCFileListFragment#listDirectory(OCFile)} with a null parameter
346 */
347 public void listDirectory(){
348 listDirectory(null);
349 }
350
351 /**
352 * Lists the given directory on the view. When the input parameter is null,
353 * it will either refresh the last known directory. list the root
354 * if there never was a directory.
355 *
356 * @param directory File to be listed
357 */
358 public void listDirectory(OCFile directory) {
359 DataStorageManager storageManager = mContainerActivity.getStorageManager();
360 if (storageManager != null) {
361
362 // Check input parameters for null
363 if(directory == null){
364 if(mFile != null){
365 directory = mFile;
366 } else {
367 directory = storageManager.getFileByPath("/");
368 if (directory == null) return; // no files, wait for sync
369 }
370 }
371
372
373 // If that's not a directory -> List its parent
374 if(!directory.isDirectory()){
375 Log_OC.w(TAG, "You see, that is not a directory -> " + directory.toString());
376 directory = storageManager.getFileById(directory.getParentId());
377 }
378
379 mAdapter.swapDirectory(directory, storageManager);
380 if (mFile == null || !mFile.equals(directory)) {
381 mList.setSelectionFromTop(0, 0);
382 }
383 mFile = directory;
384 }
385 }
386
387
388
389 /**
390 * Interface to implement by any Activity that includes some instance of FileListFragment
391 *
392 * @author David A. Velasco
393 */
394 public interface ContainerActivity extends TransferServiceGetter, OnRemoteOperationListener, FileHandler {
395
396 /**
397 * Callback method invoked when a the user browsed into a different folder through the list of files
398 *
399 * @param file
400 */
401 public void onBrowsedDownTo(OCFile folder);
402
403 public void startDownloadForPreview(OCFile file);
404
405 public void startMediaPreview(OCFile file, int i, boolean b);
406
407 public void startImagePreview(OCFile file);
408
409 public void syncFolderOperation(String remotePath, long parentId);
410
411 /**
412 * Getter for the current DataStorageManager in the container activity
413 */
414 public DataStorageManager getStorageManager();
415
416
417 /**
418 * Callback method invoked when a the 'transfer state' of a file changes.
419 *
420 * This happens when a download or upload is started or ended for a file.
421 *
422 * This method is necessary by now to update the user interface of the double-pane layout in tablets
423 * because methods {@link FileDownloaderBinder#isDownloading(Account, OCFile)} and {@link FileUploaderBinder#isUploading(Account, OCFile)}
424 * won't provide the needed response before the method where this is called finishes.
425 *
426 * TODO Remove this when the transfer state of a file is kept in the database (other thing TODO)
427 *
428 * @param file OCFile which state changed.
429 * @param downloading Flag signaling if the file is now downloading.
430 * @param uploading Flag signaling if the file is now uploading.
431 */
432 public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading);
433
434 }
435
436
437 @Override
438 public void onDismiss(EditNameDialog dialog) {
439 if (dialog.getResult()) {
440 String newFilename = dialog.getNewFilename();
441 Log_OC.d(TAG, "name edit dialog dismissed with new name " + newFilename);
442 RemoteOperation operation = new RenameFileOperation(mTargetFile,
443 AccountUtils.getCurrentOwnCloudAccount(getActivity()),
444 newFilename,
445 mContainerActivity.getStorageManager());
446 operation.execute(AccountUtils.getCurrentOwnCloudAccount(getSherlockActivity()), getSherlockActivity(), mContainerActivity, mHandler, getSherlockActivity());
447 getActivity().showDialog(FileDisplayActivity.DIALOG_SHORT_WAIT);
448 }
449 }
450
451
452 @Override
453 public void onConfirmation(String callerTag) {
454 if (callerTag.equals(FileDetailFragment.FTAG_CONFIRMATION)) {
455 if (mContainerActivity.getStorageManager().getFileById(mTargetFile.getFileId()) != null) {
456 RemoteOperation operation = new RemoveFileOperation( mTargetFile,
457 true,
458 mContainerActivity.getStorageManager());
459 operation.execute(AccountUtils.getCurrentOwnCloudAccount(getSherlockActivity()), getSherlockActivity(), mContainerActivity, mHandler, getSherlockActivity());
460
461 getActivity().showDialog(FileDisplayActivity.DIALOG_SHORT_WAIT);
462 }
463 }
464 }
465
466 @Override
467 public void onNeutral(String callerTag) {
468 File f = null;
469 if (mTargetFile.isDirectory()) {
470 // TODO run in a secondary thread?
471 mContainerActivity.getStorageManager().removeDirectory(mTargetFile, false, true);
472
473 } else if (mTargetFile.isDown() && (f = new File(mTargetFile.getStoragePath())).exists()) {
474 f.delete();
475 mTargetFile.setStoragePath(null);
476 mContainerActivity.getStorageManager().saveFile(mTargetFile);
477 }
478 listDirectory();
479 mContainerActivity.onTransferStateChanged(mTargetFile, false, false);
480 }
481
482 @Override
483 public void onCancel(String callerTag) {
484 Log_OC.d(TAG, "REMOVAL CANCELED");
485 }
486
487
488 }