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