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