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