Merge branch 'sortingFiles' of https://github.com/tobiasKaminsky/android into sorting...
[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-2014 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
22 import android.app.Activity;
23 import android.content.Intent;
24 import android.os.Bundle;
25 import android.support.v4.widget.SwipeRefreshLayout;
26 import android.view.ContextMenu;
27 import android.view.MenuInflater;
28 import android.view.MenuItem;
29 import android.view.View;
30 import android.widget.AdapterView;
31 import android.widget.AdapterView.AdapterContextMenuInfo;
32
33 import com.owncloud.android.R;
34 import com.owncloud.android.datamodel.FileDataStorageManager;
35 import com.owncloud.android.datamodel.OCFile;
36 import com.owncloud.android.files.FileMenuFilter;
37 import com.owncloud.android.lib.common.utils.Log_OC;
38 import com.owncloud.android.ui.activity.FileDisplayActivity;
39 import com.owncloud.android.ui.activity.MoveActivity;
40 import com.owncloud.android.ui.activity.OnEnforceableRefreshListener;
41 import com.owncloud.android.ui.adapter.FileListListAdapter;
42 import com.owncloud.android.ui.dialog.ConfirmationDialogFragment;
43 import com.owncloud.android.ui.dialog.RemoveFileDialogFragment;
44 import com.owncloud.android.ui.dialog.RenameFileDialogFragment;
45 import com.owncloud.android.ui.preview.PreviewImageFragment;
46 import com.owncloud.android.ui.preview.PreviewMediaFragment;
47
48 /**
49 * A Fragment that lists all files and folders in a given path.
50 *
51 * TODO refactorize to get rid of direct dependency on FileDisplayActivity
52 *
53 * @author Bartek Przybylski
54 * @author masensio
55 * @author David A. Velasco
56 */
57 public class OCFileListFragment extends ExtendedListFragment {
58
59 private static final String TAG = OCFileListFragment.class.getSimpleName();
60
61 private static final String MY_PACKAGE = OCFileListFragment.class.getPackage() != null ?
62 OCFileListFragment.class.getPackage().getName() : "com.owncloud.android.ui.fragment";
63
64 public final static String ARG_JUST_FOLDERS = MY_PACKAGE + ".JUST_FOLDERS";
65 public final static String ARG_ALLOW_CONTEXTUAL_ACTIONS = MY_PACKAGE + ".ALLOW_CONTEXTUAL";
66
67 private static final String KEY_FILE = MY_PACKAGE + ".extra.FILE";
68
69 private FileFragment.ContainerActivity mContainerActivity;
70
71 private OCFile mFile = null;
72 private FileListListAdapter mAdapter;
73
74 private OCFile mTargetFile;
75
76
77 /**
78 * {@inheritDoc}
79 */
80 @Override
81 public void onAttach(Activity activity) {
82 super.onAttach(activity);
83 Log_OC.e(TAG, "onAttach");
84 try {
85 mContainerActivity = (FileFragment.ContainerActivity) activity;
86
87 } catch (ClassCastException e) {
88 throw new ClassCastException(activity.toString() + " must implement " +
89 FileFragment.ContainerActivity.class.getSimpleName());
90 }
91 try {
92 setOnRefreshListener((OnEnforceableRefreshListener) activity);
93
94 } catch (ClassCastException e) {
95 throw new ClassCastException(activity.toString() + " must implement " +
96 SwipeRefreshLayout.OnRefreshListener.class.getSimpleName());
97 }
98 }
99
100
101 @Override
102 public void onDetach() {
103 setOnRefreshListener(null);
104 mContainerActivity = null;
105 super.onDetach();
106 }
107
108 /**
109 * {@inheritDoc}
110 */
111 @Override
112 public void onActivityCreated(Bundle savedInstanceState) {
113 super.onActivityCreated(savedInstanceState);
114 Log_OC.e(TAG, "onActivityCreated() start");
115
116 if (savedInstanceState != null) {
117 mFile = savedInstanceState.getParcelable(KEY_FILE);
118 }
119
120 Bundle args = getArguments();
121 boolean justFolders = (args == null) ? false : args.getBoolean(ARG_JUST_FOLDERS, false);
122 mAdapter = new FileListListAdapter(
123 justFolders,
124 getSherlockActivity(),
125 mContainerActivity
126 );
127 setListAdapter(mAdapter);
128
129 registerForContextMenu(getListView());
130 getListView().setOnCreateContextMenuListener(this);
131 }
132
133 /**
134 * Saves the current listed folder.
135 */
136 @Override
137 public void onSaveInstanceState (Bundle outState) {
138 super.onSaveInstanceState(outState);
139 outState.putParcelable(KEY_FILE, mFile);
140 }
141
142 /**
143 * Call this, when the user presses the up button.
144 *
145 * Tries to move up the current folder one level. If the parent folder was removed from the
146 * database, it continues browsing up until finding an existing folders.
147 *
148 * return Count of folder levels browsed up.
149 */
150 public int onBrowseUp() {
151 OCFile parentDir = null;
152 int moveCount = 0;
153
154 if(mFile != null){
155 FileDataStorageManager storageManager = mContainerActivity.getStorageManager();
156
157 String parentPath = null;
158 if (mFile.getParentId() != FileDataStorageManager.ROOT_PARENT_ID) {
159 parentPath = new File(mFile.getRemotePath()).getParent();
160 parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath :
161 parentPath + OCFile.PATH_SEPARATOR;
162 parentDir = storageManager.getFileByPath(parentPath);
163 moveCount++;
164 } else {
165 parentDir = storageManager.getFileByPath(OCFile.ROOT_PATH);
166 }
167 while (parentDir == null) {
168 parentPath = new File(parentPath).getParent();
169 parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath :
170 parentPath + OCFile.PATH_SEPARATOR;
171 parentDir = storageManager.getFileByPath(parentPath);
172 moveCount++;
173 } // exit is granted because storageManager.getFileByPath("/") never returns null
174 mFile = parentDir;
175
176 listDirectory(mFile);
177
178 onRefresh(false);
179
180 // restore index and top position
181 restoreIndexAndTopPosition();
182
183 } // else - should never happen now
184
185 return moveCount;
186 }
187
188 @Override
189 public void onItemClick(AdapterView<?> l, View v, int position, long id) {
190 OCFile file = (OCFile) mAdapter.getItem(position);
191 if (file != null) {
192 if (file.isFolder()) {
193 // update state and view of this fragment
194 listDirectory(file);
195 // then, notify parent activity to let it update its state and view
196 mContainerActivity.onBrowsedDownTo(file);
197 // save index and top position
198 saveIndexAndTopPosition(position);
199
200 } else { /// Click on a file
201 if (PreviewImageFragment.canBePreviewed(file)) {
202 // preview image - it handles the download, if needed
203 ((FileDisplayActivity)mContainerActivity).startImagePreview(file);
204
205 } else if (file.isDown()) {
206 if (PreviewMediaFragment.canBePreviewed(file)) {
207 // media preview
208 ((FileDisplayActivity)mContainerActivity).startMediaPreview(file, 0, true);
209 } else {
210 mContainerActivity.getFileOperationsHelper().openFile(file);
211 }
212
213 } else {
214 // automatic download, preview on finish
215 ((FileDisplayActivity)mContainerActivity).startDownloadForPreview(file);
216 }
217
218 }
219
220 } else {
221 Log_OC.d(TAG, "Null object in ListAdapter!!");
222 }
223
224 }
225
226 /**
227 * {@inheritDoc}
228 */
229 @Override
230 public void onCreateContextMenu (
231 ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
232 super.onCreateContextMenu(menu, v, menuInfo);
233 Bundle args = getArguments();
234 boolean allowContextualActions =
235 (args == null) ? true : args.getBoolean(ARG_ALLOW_CONTEXTUAL_ACTIONS, true);
236 if (allowContextualActions) {
237 MenuInflater inflater = getSherlockActivity().getMenuInflater();
238 inflater.inflate(R.menu.file_actions_menu, menu);
239 AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
240 OCFile targetFile = (OCFile) mAdapter.getItem(info.position);
241
242 if (mContainerActivity.getStorageManager() != null) {
243 FileMenuFilter mf = new FileMenuFilter(
244 targetFile,
245 mContainerActivity.getStorageManager().getAccount(),
246 mContainerActivity,
247 getSherlockActivity()
248 );
249 mf.filter(menu);
250 }
251
252 /// additional restrictions for this fragment
253 // TODO allow in the future 'open with' for previewable files
254 MenuItem item = menu.findItem(R.id.action_open_file_with);
255 if (item != null) {
256 item.setVisible(false);
257 item.setEnabled(false);
258 }
259 /// TODO break this direct dependency on FileDisplayActivity... if possible
260 FileFragment frag = ((FileDisplayActivity)getSherlockActivity()).getSecondFragment();
261 if (frag != null && frag instanceof FileDetailFragment &&
262 frag.getFile().getFileId() == targetFile.getFileId()) {
263 item = menu.findItem(R.id.action_see_details);
264 if (item != null) {
265 item.setVisible(false);
266 item.setEnabled(false);
267 }
268 }
269 }
270 }
271
272
273 /**
274 * {@inhericDoc}
275 */
276 @Override
277 public boolean onContextItemSelected (MenuItem item) {
278 AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
279 mTargetFile = (OCFile) mAdapter.getItem(info.position);
280 switch (item.getItemId()) {
281 case R.id.action_share_file: {
282 mContainerActivity.getFileOperationsHelper().shareFileWithLink(mTargetFile);
283 return true;
284 }
285 case R.id.action_unshare_file: {
286 mContainerActivity.getFileOperationsHelper().unshareFileWithLink(mTargetFile);
287 return true;
288 }
289 case R.id.action_rename_file: {
290 RenameFileDialogFragment dialog = RenameFileDialogFragment.newInstance(mTargetFile);
291 dialog.show(getFragmentManager(), FileDetailFragment.FTAG_RENAME_FILE);
292 return true;
293 }
294 case R.id.action_remove_file: {
295 RemoveFileDialogFragment dialog = RemoveFileDialogFragment.newInstance(mTargetFile);
296 dialog.show(getFragmentManager(), ConfirmationDialogFragment.FTAG_CONFIRMATION);
297 return true;
298 }
299 case R.id.action_download_file:
300 case R.id.action_sync_file: {
301 mContainerActivity.getFileOperationsHelper().syncFile(mTargetFile);
302 return true;
303 }
304 case R.id.action_cancel_download:
305 case R.id.action_cancel_upload: {
306 ((FileDisplayActivity)mContainerActivity).cancelTransference(mTargetFile);
307 return true;
308 }
309 case R.id.action_see_details: {
310 mContainerActivity.showDetails(mTargetFile);
311 return true;
312 }
313 case R.id.action_send_file: {
314 // Obtain the file
315 if (!mTargetFile.isDown()) { // Download the file
316 Log_OC.d(TAG, mTargetFile.getRemotePath() + " : File must be downloaded");
317 ((FileDisplayActivity)mContainerActivity).startDownloadForSending(mTargetFile);
318
319 } else {
320 mContainerActivity.getFileOperationsHelper().sendDownloadedFile(mTargetFile);
321 }
322 return true;
323 }
324 case R.id.action_move: {
325 Intent action = new Intent(getActivity(), MoveActivity.class);
326
327 // Pass mTargetFile that contains info of selected file/folder
328 action.putExtra(MoveActivity.EXTRA_TARGET_FILE, mTargetFile);
329 getActivity().startActivityForResult(action, FileDisplayActivity.ACTION_MOVE_FILES);
330 return true;
331 }
332 default:
333 return super.onContextItemSelected(item);
334 }
335 }
336
337
338 /**
339 * Use this to query the {@link OCFile} that is currently
340 * being displayed by this fragment
341 * @return The currently viewed OCFile
342 */
343 public OCFile getCurrentFile(){
344 return mFile;
345 }
346
347 /**
348 * Calls {@link OCFileListFragment#listDirectory(OCFile)} with a null parameter
349 */
350 public void listDirectory(){
351 listDirectory(null);
352 }
353
354 /**
355 * Lists the given directory on the view. When the input parameter is null,
356 * it will either refresh the last known directory. list the root
357 * if there never was a directory.
358 *
359 * @param directory File to be listed
360 */
361 public void listDirectory(OCFile directory) {
362 FileDataStorageManager storageManager = mContainerActivity.getStorageManager();
363 if (storageManager != null) {
364
365 // Check input parameters for null
366 if(directory == null){
367 if(mFile != null){
368 directory = mFile;
369 } else {
370 directory = storageManager.getFileByPath("/");
371 if (directory == null) return; // no files, wait for sync
372 }
373 }
374
375
376 // If that's not a directory -> List its parent
377 if(!directory.isFolder()){
378 Log_OC.w(TAG, "You see, that is not a directory -> " + directory.toString());
379 directory = storageManager.getFileById(directory.getParentId());
380 }
381
382 mAdapter.swapDirectory(directory, storageManager);
383 if (mFile == null || !mFile.equals(directory)) {
384 mList.setSelectionFromTop(0, 0);
385 }
386 mFile = directory;
387 }
388 }
389
390 public void sortByName(boolean descending){
391 mAdapter.setSortOrder(0, descending);
392 }
393
394 public void sortByDate(boolean descending){
395 mAdapter.setSortOrder(1, descending);
396 }
397
398 public void sortBySize(boolean descending){
399 mAdapter.setSortOrder(2, descending);
400 }
401 }