c2f70e8d0ee4431cd062b571e1c094d48716b7d0
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / adapter / FileListListAdapter.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.adapter;
19
20
21 import java.io.File;
22 import java.util.Collections;
23 import java.util.Comparator;
24 import java.util.Vector;
25
26 import third_parties.daveKoeller.AlphanumComparator;
27 import android.accounts.Account;
28 import android.content.Context;
29 import android.content.SharedPreferences;
30 import android.graphics.Bitmap;
31 import android.graphics.BitmapFactory;
32 import android.media.ThumbnailUtils;
33 import android.preference.PreferenceManager;
34 import android.text.format.DateUtils;
35 import android.view.LayoutInflater;
36 import android.view.View;
37 import android.view.ViewGroup;
38 import android.widget.BaseAdapter;
39 import android.widget.Filter;
40 import android.widget.Filterable;
41 import android.widget.GridView;
42 import android.widget.ImageView;
43 import android.widget.ListAdapter;
44 import android.widget.TextView;
45
46 import com.owncloud.android.R;
47 import com.owncloud.android.authentication.AccountUtils;
48 import com.owncloud.android.datamodel.FileDataStorageManager;
49 import com.owncloud.android.datamodel.OCFile;
50 import com.owncloud.android.datamodel.ThumbnailsCacheManager;
51 import com.owncloud.android.datamodel.ThumbnailsCacheManager.AsyncDrawable;
52 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
53 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
54 import com.owncloud.android.lib.common.utils.Log_OC;
55 import com.owncloud.android.ui.activity.ComponentsGetter;
56 import com.owncloud.android.utils.DisplayUtils;
57 import com.owncloud.android.utils.FileStorageUtils;
58
59
60 /**
61 * This Adapter populates a ListView with all files and folders in an ownCloud
62 * instance.
63 *
64 * @author Bartek Przybylski
65 * @author Tobias Kaminsky
66 * @author David A. Velasco
67 */
68 public class FileListListAdapter extends BaseAdapter implements ListAdapter {
69 private final static String PERMISSION_SHARED_WITH_ME = "S";
70
71 private Context mContext;
72 private OCFile mFile = null;
73 private Vector<OCFile> mFiles = null;
74 private Vector<OCFile> mFilesOrig = new Vector<OCFile>();
75 private boolean mJustFolders;
76
77 private FileDataStorageManager mStorageManager;
78 private Account mAccount;
79 private ComponentsGetter mTransferServiceGetter;
80 private enum ViewType {LIST_ITEM, GRID_IMAGE, GRID_ITEM };
81 private Integer mSortOrder;
82 public static final Integer SORT_NAME = 0;
83 public static final Integer SORT_DATE = 1;
84 public static final Integer SORT_SIZE = 2;
85 private Boolean mSortAscending;
86 private SharedPreferences mAppPreferences;
87
88 public FileListListAdapter(
89 boolean justFolders,
90 Context context,
91 ComponentsGetter transferServiceGetter
92 ) {
93
94 mJustFolders = justFolders;
95 mContext = context;
96 mAccount = AccountUtils.getCurrentOwnCloudAccount(mContext);
97 mTransferServiceGetter = transferServiceGetter;
98
99 mAppPreferences = PreferenceManager
100 .getDefaultSharedPreferences(mContext);
101
102 // Read sorting order, default to sort by name ascending
103 mSortOrder = mAppPreferences
104 .getInt("sortOrder", 0);
105 mSortAscending = mAppPreferences.getBoolean("sortAscending", true);
106
107 // initialise thumbnails cache on background thread
108 new ThumbnailsCacheManager.InitDiskCacheTask().execute();
109 }
110
111 @Override
112 public boolean areAllItemsEnabled() {
113 return true;
114 }
115
116 @Override
117 public boolean isEnabled(int position) {
118 return true;
119 }
120
121 @Override
122 public int getCount() {
123 return mFiles != null ? mFiles.size() : 0;
124 }
125
126 @Override
127 public Object getItem(int position) {
128 if (mFiles == null || mFiles.size() <= position)
129 return null;
130 return mFiles.get(position);
131 }
132
133 @Override
134 public long getItemId(int position) {
135 if (mFiles == null || mFiles.size() <= position)
136 return 0;
137 return mFiles.get(position).getFileId();
138 }
139
140 @Override
141 public int getItemViewType(int position) {
142 return 0;
143 }
144
145 @Override
146 public View getView(int position, View convertView, ViewGroup parent) {
147 // decide image vs. file view
148 double countImages = 0;
149 double countFiles = 0;
150
151 for (OCFile file : mFiles){
152 if (!file.isFolder()){
153 countFiles++;
154
155 if (file.isImage()){
156 countImages++;
157 }
158 }
159 }
160
161 // TODO threshold as constant in Preferences
162 // > 50% Images --> image view
163 boolean fileView = true;
164 if ((countImages / countFiles) >= 0.5){
165 fileView = false;
166 } else {
167 fileView = true;
168 }
169
170 View view = convertView;
171 OCFile file = null;
172 LayoutInflater inflator = (LayoutInflater) mContext
173 .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
174
175 if (mFiles != null && mFiles.size() > position) {
176 file = mFiles.get(position);
177 }
178
179 // Find out which layout should be displayed
180 ViewType viewType;
181 if (fileView){
182 viewType = ViewType.LIST_ITEM;
183 } else if (file.isImage()){
184 viewType = ViewType.GRID_IMAGE;
185 } else {
186 viewType = ViewType.GRID_ITEM;
187 }
188
189 // Create View
190 switch (viewType){
191 case GRID_IMAGE:
192 view = inflator.inflate(R.layout.grid_image, null);
193 break;
194 case GRID_ITEM:
195 view = inflator.inflate(R.layout.grid_item, null);
196 break;
197 case LIST_ITEM:
198 view = inflator.inflate(R.layout.list_item, null);
199 break;
200 }
201
202 view.invalidate();
203
204 if (file != null){
205
206 ImageView fileIcon = (ImageView) view.findViewById(R.id.thumbnail);
207 TextView fileName;
208 String name;
209
210 switch (viewType){
211 case LIST_ITEM:
212 fileName = (TextView) view.findViewById(R.id.Filename);
213 name = file.getFileName();
214 fileName.setText(name);
215
216 TextView fileSizeV = (TextView) view.findViewById(R.id.file_size);
217 TextView lastModV = (TextView) view.findViewById(R.id.last_mod);
218 ImageView checkBoxV = (ImageView) view.findViewById(R.id.custom_checkbox);
219
220 lastModV.setVisibility(View.VISIBLE);
221 lastModV.setText(showRelativeTimestamp(file));
222
223 checkBoxV.setVisibility(View.GONE);
224
225 fileSizeV.setVisibility(View.VISIBLE);
226 fileSizeV.setText(DisplayUtils.bytesToHumanReadable(file.getFileLength()));
227
228 ImageView sharedIconV = (ImageView) view.findViewById(R.id.sharedIcon);
229
230
231 if (file.isShareByLink()) {
232 sharedIconV.setVisibility(View.VISIBLE);
233 } else {
234 sharedIconV.setVisibility(View.GONE);
235 }
236
237 ImageView localStateView = (ImageView) view.findViewById(R.id.localFileIndicator);
238
239 if (!file.isFolder()) {
240 GridView parentList = (GridView)parent;
241 if (parentList.getChoiceMode() == GridView.CHOICE_MODE_NONE) {
242 checkBoxV.setVisibility(View.GONE);
243 } else {
244 if (parentList.isItemChecked(position)) {
245 checkBoxV.setImageResource(android.R.drawable.checkbox_on_background);
246 } else {
247 checkBoxV.setImageResource(android.R.drawable.checkbox_off_background);
248 }
249 checkBoxV.setVisibility(View.VISIBLE);
250 }
251
252 localStateView.bringToFront();
253 FileDownloaderBinder downloaderBinder = mTransferServiceGetter.getFileDownloaderBinder();
254 FileUploaderBinder uploaderBinder = mTransferServiceGetter.getFileUploaderBinder();
255 if (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, file)) {
256 localStateView.setImageResource(R.drawable.downloading_file_indicator);
257 localStateView.setVisibility(View.VISIBLE);
258 } else if (uploaderBinder != null && uploaderBinder.isUploading(mAccount, file)) {
259 localStateView.setImageResource(R.drawable.uploading_file_indicator);
260 localStateView.setVisibility(View.VISIBLE);
261 } else if (file.isDown()) {
262 localStateView.setImageResource(R.drawable.local_file_indicator);
263 localStateView.setVisibility(View.VISIBLE);
264 } else {
265 localStateView.setVisibility(View.INVISIBLE);
266 }
267
268 ImageView sharedWithMeIconV = (ImageView) view.findViewById(R.id.sharedWithMeIcon);
269 if (checkIfFileIsSharedWithMe(file)) {
270 sharedWithMeIconV.setVisibility(View.VISIBLE);
271 } else {
272 sharedWithMeIconV.setVisibility(View.GONE);
273 }
274 } else {
275 localStateView.setVisibility(View.INVISIBLE);
276 }
277 break;
278 case GRID_ITEM:
279 fileName = (TextView) view.findViewById(R.id.Filename);
280 name = file.getFileName();
281 fileName.setText(name);
282 break;
283 case GRID_IMAGE:
284 break;
285 }
286
287 // For all Views
288
289 // this if-else is needed even though favorite icon is visible by default
290 // because android reuses views in listview
291 if (!file.keepInSync()) {
292 view.findViewById(R.id.favoriteIcon).setVisibility(View.GONE);
293 } else {
294 view.findViewById(R.id.favoriteIcon).setVisibility(View.VISIBLE);
295 }
296
297 // No Folder
298 if (!file.isFolder()) {
299 if (file.isImage() && file.getRemoteId() != null){
300 // Thumbnail in Cache?
301 Bitmap thumbnail = ThumbnailsCacheManager.getBitmapFromDiskCache(
302 String.valueOf(file.getRemoteId())
303 );
304 if (thumbnail != null && !file.needsUpdateThumbnail()){
305 fileIcon.setImageBitmap(thumbnail);
306 } else {
307 // generate new Thumbnail
308 if (ThumbnailsCacheManager.cancelPotentialWork(file, fileIcon)) {
309 final ThumbnailsCacheManager.ThumbnailGenerationTask task =
310 new ThumbnailsCacheManager.ThumbnailGenerationTask(
311 fileIcon, mStorageManager, mAccount
312 );
313 if (thumbnail == null) {
314 thumbnail = ThumbnailsCacheManager.mDefaultImg;
315 }
316 final AsyncDrawable asyncDrawable = new AsyncDrawable(
317 mContext.getResources(),
318 thumbnail,
319 task
320 );
321 fileIcon.setImageDrawable(asyncDrawable);
322 task.execute(file);
323
324 }
325 }
326 }
327 else {
328 fileIcon.setImageResource(DisplayUtils.getResourceId(file.getMimetype(), file.getFileName()));
329 }
330 } else {
331 // Folder
332 if (checkIfFileIsSharedWithMe(file)) {
333 fileIcon.setImageResource(R.drawable.shared_with_me_folder);
334 } else if (file.isShareByLink()) {
335 // If folder is sharedByLink, icon folder must be changed to
336 // folder-public one
337 fileIcon.setImageResource(R.drawable.folder_public);
338 } else {
339 fileIcon.setImageResource(DisplayUtils.getResourceId(file.getMimetype(), file.getFileName()));
340 }
341 }
342 }
343
344 return view;
345 }
346
347 /**
348 * Local Folder size in human readable format
349 *
350 * @param path
351 * String
352 * @return Size in human readable format
353 */
354 private String getFolderSizeHuman(String path) {
355
356 File dir = new File(path);
357
358 if (dir.exists()) {
359 long bytes = getFolderSize(dir);
360 return DisplayUtils.bytesToHumanReadable(bytes);
361 }
362
363 return "0 B";
364 }
365
366 /**
367 * Local Folder size
368 * @param dir File
369 * @return Size in bytes
370 */
371 private long getFolderSize(File dir) {
372 if (dir.exists()) {
373 long result = 0;
374 File[] fileList = dir.listFiles();
375 for(int i = 0; i < fileList.length; i++) {
376 if(fileList[i].isDirectory()) {
377 result += getFolderSize(fileList[i]);
378 } else {
379 result += fileList[i].length();
380 }
381 }
382 return result;
383 }
384 return 0;
385 }
386
387 @Override
388 public int getViewTypeCount() {
389 return 1;
390 }
391
392 @Override
393 public boolean hasStableIds() {
394 return true;
395 }
396
397 @Override
398 public boolean isEmpty() {
399 return (mFiles == null || mFiles.isEmpty());
400 }
401
402 /**
403 * Change the adapted directory for a new one
404 * @param directory New file to adapt. Can be NULL, meaning
405 * "no content to adapt".
406 * @param updatedStorageManager Optional updated storage manager; used to replace
407 * mStorageManager if is different (and not NULL)
408 */
409 public void swapDirectory(OCFile directory, FileDataStorageManager updatedStorageManager) {
410 mFile = directory;
411 if (updatedStorageManager != null && updatedStorageManager != mStorageManager) {
412 mStorageManager = updatedStorageManager;
413 mAccount = AccountUtils.getCurrentOwnCloudAccount(mContext);
414 }
415 if (mStorageManager != null) {
416 mFiles = mStorageManager.getFolderContent(mFile);
417 mFilesOrig.clear();
418 mFilesOrig.addAll(mFiles);
419
420 if (mJustFolders) {
421 mFiles = getFolders(mFiles);
422 }
423 } else {
424 mFiles = null;
425 }
426
427 sortDirectory();
428 }
429
430 /**
431 * Sorts all filenames, regarding last user decision
432 */
433 private void sortDirectory(){
434 switch (mSortOrder){
435 case 0:
436 sortByName(mSortAscending);
437 break;
438 case 1:
439 sortByDate(mSortAscending);
440 break;
441 case 2:
442 sortBySize(mSortAscending);
443 break;
444 }
445
446 notifyDataSetChanged();
447 }
448
449
450 /**
451 * Filter for getting only the folders
452 * @param files
453 * @return Vector<OCFile>
454 */
455 public Vector<OCFile> getFolders(Vector<OCFile> files) {
456 Vector<OCFile> ret = new Vector<OCFile>();
457 OCFile current = null;
458 for (int i=0; i<files.size(); i++) {
459 current = files.get(i);
460 if (current.isFolder()) {
461 ret.add(current);
462 }
463 }
464 return ret;
465 }
466
467
468 /**
469 * Check if parent folder does not include 'S' permission and if file/folder
470 * is shared with me
471 *
472 * @param file: OCFile
473 * @return boolean: True if it is shared with me and false if it is not
474 */
475 private boolean checkIfFileIsSharedWithMe(OCFile file) {
476 return (mFile.getPermissions() != null
477 && !mFile.getPermissions().contains(PERMISSION_SHARED_WITH_ME)
478 && file.getPermissions() != null
479 && file.getPermissions().contains(PERMISSION_SHARED_WITH_ME));
480 }
481
482 /**
483 * Sorts list by Date
484 * @param sortAscending true: ascending, false: descending
485 */
486 private void sortByDate(boolean sortAscending){
487 final Integer val;
488 if (sortAscending){
489 val = 1;
490 } else {
491 val = -1;
492 }
493
494 Collections.sort(mFiles, new Comparator<OCFile>() {
495 public int compare(OCFile o1, OCFile o2) {
496 if (o1.isFolder() && o2.isFolder()) {
497 Long obj1 = o1.getModificationTimestamp();
498 return val * obj1.compareTo(o2.getModificationTimestamp());
499 }
500 else if (o1.isFolder()) {
501 return -1;
502 } else if (o2.isFolder()) {
503 return 1;
504 } else if (o1.getModificationTimestamp() == 0 || o2.getModificationTimestamp() == 0){
505 return 0;
506 } else {
507 Long obj1 = o1.getModificationTimestamp();
508 return val * obj1.compareTo(o2.getModificationTimestamp());
509 }
510 }
511 });
512 }
513
514 /**
515 * Sorts list by Size
516 * @param sortAscending true: ascending, false: descending
517 */
518 private void sortBySize(boolean sortAscending){
519 final Integer val;
520 if (sortAscending){
521 val = 1;
522 } else {
523 val = -1;
524 }
525
526 Collections.sort(mFiles, new Comparator<OCFile>() {
527 public int compare(OCFile o1, OCFile o2) {
528 if (o1.isFolder() && o2.isFolder()) {
529 Long obj1 = getFolderSize(new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, o1)));
530 return val * obj1.compareTo(getFolderSize(new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, o2))));
531 }
532 else if (o1.isFolder()) {
533 return -1;
534 } else if (o2.isFolder()) {
535 return 1;
536 } else if (o1.getFileLength() == 0 || o2.getFileLength() == 0){
537 return 0;
538 } else {
539 Long obj1 = o1.getFileLength();
540 return val * obj1.compareTo(o2.getFileLength());
541 }
542 }
543 });
544 }
545
546 /**
547 * Sorts list by Name
548 * @param sortAscending true: ascending, false: descending
549 */
550 private void sortByName(boolean sortAscending){
551 final Integer val;
552 if (sortAscending){
553 val = 1;
554 } else {
555 val = -1;
556 }
557
558 Collections.sort(mFiles, new Comparator<OCFile>() {
559 public int compare(OCFile o1, OCFile o2) {
560 if (o1.isFolder() && o2.isFolder()) {
561 return val * o1.getRemotePath().toLowerCase().compareTo(o2.getRemotePath().toLowerCase());
562 } else if (o1.isFolder()) {
563 return -1;
564 } else if (o2.isFolder()) {
565 return 1;
566 }
567 return val * new AlphanumComparator().compare(o1, o2);
568 }
569 });
570 }
571
572 public void setSortOrder(Integer order, boolean ascending) {
573 SharedPreferences.Editor editor = mAppPreferences.edit();
574 editor.putInt("sortOrder", order);
575 editor.putBoolean("sortAscending", ascending);
576 editor.commit();
577
578 mSortOrder = order;
579 mSortAscending = ascending;
580
581 sortDirectory();
582 }
583
584 private CharSequence showRelativeTimestamp(OCFile file){
585 return DisplayUtils.getRelativeDateTimeString(mContext, file.getModificationTimestamp(),
586 DateUtils.SECOND_IN_MILLIS, DateUtils.WEEK_IN_MILLIS, 0);
587 }
588 }