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