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