97724046583875c5e25b906432d42e46be53e8fb
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / adapter / FileListListAdapter.java
1 /**
2 * ownCloud Android client application
3 *
4 * @author Bartek Przybylski
5 * @author Tobias Kaminsky
6 * @author David A. Velasco
7 * @author masensio
8 * Copyright (C) 2011 Bartek Przybylski
9 * Copyright (C) 2015 ownCloud Inc.
10 *
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License version 2,
13 * as published by the Free Software Foundation.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with this program. If not, see <http://www.gnu.org/licenses/>.
22 *
23 */
24 package com.owncloud.android.ui.adapter;
25
26
27 import java.io.File;
28 import java.util.ArrayList;
29 import java.util.HashMap;
30 import java.util.Map;
31 import java.util.Vector;
32
33 import android.accounts.Account;
34 import android.content.Context;
35 import android.content.SharedPreferences;
36 import android.graphics.Bitmap;
37 import android.graphics.Color;
38 import android.os.Build;
39 import android.preference.PreferenceManager;
40 import android.text.format.DateUtils;
41 import android.view.LayoutInflater;
42 import android.view.View;
43 import android.view.ViewGroup;
44 import android.widget.AbsListView;
45 import android.widget.BaseAdapter;
46 import android.widget.ImageView;
47 import android.widget.LinearLayout;
48 import android.widget.ListAdapter;
49 import android.widget.TextView;
50
51 import com.owncloud.android.R;
52 import com.owncloud.android.authentication.AccountUtils;
53 import com.owncloud.android.datamodel.FileDataStorageManager;
54 import com.owncloud.android.datamodel.OCFile;
55 import com.owncloud.android.datamodel.ThumbnailsCacheManager;
56 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
57 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
58 import com.owncloud.android.services.OperationsService.OperationsServiceBinder;
59 import com.owncloud.android.ui.activity.ComponentsGetter;
60 import com.owncloud.android.utils.DisplayUtils;
61 import com.owncloud.android.utils.FileStorageUtils;
62 import com.owncloud.android.utils.MimetypeIconUtil;
63
64
65 /**
66 * This Adapter populates a ListView with all files and folders in an ownCloud
67 * instance.
68 */
69 public class FileListListAdapter extends BaseAdapter implements ListAdapter {
70 private final static String PERMISSION_SHARED_WITH_ME = "S";
71
72 private Context mContext;
73 private OCFile mFile = null;
74 private Vector<OCFile> mFiles = null;
75 private Vector<OCFile> mFilesOrig = new Vector<OCFile>();
76 private boolean mJustFolders;
77
78 private FileDataStorageManager mStorageManager;
79 private Account mAccount;
80 private ComponentsGetter mTransferServiceGetter;
81 private boolean mGridMode;
82
83 private enum ViewType {LIST_ITEM, GRID_IMAGE, GRID_ITEM };
84
85 private SharedPreferences mAppPreferences;
86
87 private HashMap<Integer, Boolean> mSelection = new HashMap<Integer, Boolean>();
88
89 public FileListListAdapter(
90 boolean justFolders,
91 Context context,
92 ComponentsGetter transferServiceGetter
93 ) {
94
95 mJustFolders = justFolders;
96 mContext = context;
97 mAccount = AccountUtils.getCurrentOwnCloudAccount(mContext);
98 mTransferServiceGetter = transferServiceGetter;
99
100 mAppPreferences = PreferenceManager
101 .getDefaultSharedPreferences(mContext);
102
103 // Read sorting order, default to sort by name ascending
104 FileStorageUtils.mSortOrder = mAppPreferences.getInt("sortOrder", 0);
105 FileStorageUtils.mSortAscending = mAppPreferences.getBoolean("sortAscending", true);
106
107 // initialise thumbnails cache on background thread
108 new ThumbnailsCacheManager.InitDiskCacheTask().execute();
109
110 mGridMode = false;
111 }
112
113 @Override
114 public boolean areAllItemsEnabled() {
115 return true;
116 }
117
118 @Override
119 public boolean isEnabled(int position) {
120 return true;
121 }
122
123 @Override
124 public int getCount() {
125 return mFiles != null ? mFiles.size() : 0;
126 }
127
128 @Override
129 public Object getItem(int position) {
130 if (mFiles == null || mFiles.size() <= position)
131 return null;
132 return mFiles.get(position);
133 }
134
135 @Override
136 public long getItemId(int position) {
137 if (mFiles == null || mFiles.size() <= position)
138 return 0;
139 return mFiles.get(position).getFileId();
140 }
141
142 @Override
143 public int getItemViewType(int position) {
144 return 0;
145 }
146
147 @Override
148 public View getView(int position, View convertView, ViewGroup parent) {
149
150 View view = convertView;
151 OCFile file = null;
152 LayoutInflater inflator = (LayoutInflater) mContext
153 .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
154
155 if (mFiles != null && mFiles.size() > position) {
156 file = mFiles.get(position);
157 }
158
159 // Find out which layout should be displayed
160 ViewType viewType;
161 if (!mGridMode){
162 viewType = ViewType.LIST_ITEM;
163 } else if (file.isImage() || file.isVideo()){
164 viewType = ViewType.GRID_IMAGE;
165 } else {
166 viewType = ViewType.GRID_ITEM;
167 }
168
169 // create view only if differs, otherwise reuse
170 if (convertView == null || (convertView != null && convertView.getTag() != viewType)) {
171 switch (viewType) {
172 case GRID_IMAGE:
173 view = inflator.inflate(R.layout.grid_image, null);
174 view.setTag(ViewType.GRID_IMAGE);
175 break;
176 case GRID_ITEM:
177 view = inflator.inflate(R.layout.grid_item, null);
178 view.setTag(ViewType.GRID_ITEM);
179 break;
180 case LIST_ITEM:
181 view = inflator.inflate(R.layout.list_item, null);
182 view.setTag(ViewType.LIST_ITEM);
183 break;
184 }
185 }
186
187 view.invalidate();
188
189 if (file != null){
190
191 ImageView fileIcon = (ImageView) view.findViewById(R.id.thumbnail);
192
193 fileIcon.setTag(file.getFileId());
194 TextView fileName;
195 String name = file.getFileName();
196
197 LinearLayout linearLayout = (LinearLayout) view.findViewById(R.id.ListItemLayout);
198 linearLayout.setContentDescription("LinearLayout-" + name);
199
200 switch (viewType){
201 case LIST_ITEM:
202 TextView fileSizeV = (TextView) view.findViewById(R.id.file_size);
203 TextView fileSizeSeparatorV = (TextView) view.findViewById(R.id.file_separator);
204 TextView lastModV = (TextView) view.findViewById(R.id.last_mod);
205
206
207 lastModV.setVisibility(View.VISIBLE);
208 lastModV.setText(showRelativeTimestamp(file));
209
210
211 fileSizeSeparatorV.setVisibility(View.VISIBLE);
212 fileSizeV.setVisibility(View.VISIBLE);
213 fileSizeV.setText(DisplayUtils.bytesToHumanReadable(file.getFileLength()));
214
215 if (!file.isFolder()) {
216 AbsListView parentList = (AbsListView)parent;
217 if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
218 if (parentList.getChoiceMode() == AbsListView.CHOICE_MODE_NONE) {
219 checkBoxV.setVisibility(View.GONE);
220 } else {
221 if (parentList.isItemChecked(position)) {
222 checkBoxV.setImageResource(
223 R.drawable.ic_checkbox_marked);
224 } else {
225 checkBoxV.setImageResource(
226 R.drawable.ic_checkbox_blank_outline);
227 }
228 checkBoxV.setVisibility(View.VISIBLE);
229 }
230 }
231
232 } else { //Folder
233 fileSizeSeparatorV.setVisibility(View.INVISIBLE);
234 fileSizeV.setVisibility(View.INVISIBLE);
235 }
236
237 case GRID_ITEM:
238 // filename
239 fileName = (TextView) view.findViewById(R.id.Filename);
240 name = file.getFileName();
241 fileName.setText(name);
242
243 case GRID_IMAGE:
244 // sharedIcon
245 ImageView sharedIconV = (ImageView) view.findViewById(R.id.sharedIcon);
246 if (file.isShareByLink()) {
247 sharedIconV.setVisibility(View.VISIBLE);
248 sharedIconV.bringToFront();
249 } else {
250 sharedIconV.setVisibility(View.GONE);
251 }
252
253 // local state
254 ImageView localStateView = (ImageView) view.findViewById(R.id.localFileIndicator);
255 localStateView.bringToFront();
256 FileDownloaderBinder downloaderBinder =
257 mTransferServiceGetter.getFileDownloaderBinder();
258 FileUploaderBinder uploaderBinder =
259 mTransferServiceGetter.getFileUploaderBinder();
260 boolean downloading = (downloaderBinder != null &&
261 downloaderBinder.isDownloading(mAccount, file));
262 OperationsServiceBinder opsBinder =
263 mTransferServiceGetter.getOperationsServiceBinder();
264 downloading |= (opsBinder != null &&
265 opsBinder.isSynchronizing(mAccount, file.getRemotePath()));
266 if (downloading) {
267 localStateView.setImageResource(R.drawable.downloading_file_indicator);
268 localStateView.setVisibility(View.VISIBLE);
269 } else if (uploaderBinder != null &&
270 uploaderBinder.isUploading(mAccount, file)) {
271 localStateView.setImageResource(R.drawable.uploading_file_indicator);
272 localStateView.setVisibility(View.VISIBLE);
273 } else if (file.isDown()) {
274 localStateView.setImageResource(R.drawable.local_file_indicator);
275 localStateView.setVisibility(View.VISIBLE);
276 } else {
277 localStateView.setVisibility(View.INVISIBLE);
278 }
279
280 // share with me icon
281 ImageView sharedWithMeIconV = (ImageView)
282 view.findViewById(R.id.sharedWithMeIcon);
283 sharedWithMeIconV.bringToFront();
284 if (checkIfFileIsSharedWithMe(file) &&
285 (!file.isFolder() || !mGridMode)) {
286 sharedWithMeIconV.setVisibility(View.VISIBLE);
287 } else {
288 sharedWithMeIconV.setVisibility(View.GONE);
289 }
290
291 break;
292 }
293
294 ImageView checkBoxV = (ImageView) view.findViewById(R.id.custom_checkbox);
295 checkBoxV.setVisibility(View.GONE);
296
297 AbsListView parentList = (AbsListView)parent;
298 if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
299 if (parentList.getChoiceMode() == AbsListView.CHOICE_MODE_NONE) {
300 checkBoxV.setVisibility(View.GONE);
301 } else if (parentList.getCheckedItemCount() > 0){
302 if (parentList.isItemChecked(position)) {
303 checkBoxV.setImageResource(
304 android.R.drawable.checkbox_on_background);
305 } else {
306 checkBoxV.setImageResource(
307 android.R.drawable.checkbox_off_background);
308 }
309 checkBoxV.setVisibility(View.VISIBLE);
310 }
311 }
312
313 // For all Views
314
315 // this if-else is needed even though favorite icon is visible by default
316 // because android reuses views in listview
317 if (!file.isFavorite()) {
318 view.findViewById(R.id.favoriteIcon).setVisibility(View.GONE);
319 } else {
320 view.findViewById(R.id.favoriteIcon).setVisibility(View.VISIBLE);
321 }
322
323 // No Folder
324 if (!file.isFolder()) {
325 if (file.isImage() && file.getRemoteId() != null){
326 // Thumbnail in Cache?
327 Bitmap thumbnail = ThumbnailsCacheManager.getBitmapFromDiskCache(
328 String.valueOf(file.getRemoteId())
329 );
330 if (thumbnail != null && !file.needsUpdateThumbnail()){
331 fileIcon.setImageBitmap(thumbnail);
332 } else {
333 // generate new Thumbnail
334 if (ThumbnailsCacheManager.cancelPotentialWork(file, fileIcon)) {
335 final ThumbnailsCacheManager.ThumbnailGenerationTask task =
336 new ThumbnailsCacheManager.ThumbnailGenerationTask(
337 fileIcon, mStorageManager, mAccount
338 );
339 if (thumbnail == null) {
340 thumbnail = ThumbnailsCacheManager.mDefaultImg;
341 }
342 final ThumbnailsCacheManager.AsyncDrawable asyncDrawable =
343 new ThumbnailsCacheManager.AsyncDrawable(
344 mContext.getResources(),
345 thumbnail,
346 task
347 );
348 fileIcon.setImageDrawable(asyncDrawable);
349 task.execute(file, true);
350 }
351 }
352
353 if (file.getMimetype().equalsIgnoreCase("image/png")) {
354 fileIcon.setBackgroundColor(mContext.getResources()
355 .getColor(R.color.background_color));
356 }
357
358
359 } else {
360 fileIcon.setImageResource(MimetypeIconUtil.getFileTypeIconId(file.getMimetype(),
361 file.getFileName()));
362 }
363
364 } else {
365 // Folder
366 fileIcon.setImageResource(
367 MimetypeIconUtil.getFolderTypeIconId(
368 checkIfFileIsSharedWithMe(file), file.isShareByLink()));
369 }
370 }
371
372 if (mSelection.get(position) != null) {
373 view.setBackgroundColor(Color.rgb(248, 248, 248));
374 } else {
375 view.setBackgroundColor(Color.WHITE);
376 }
377
378 return view;
379 }
380
381 /**
382 * Local Folder size in human readable format
383 *
384 * @param path
385 * String
386 * @return Size in human readable format
387 */
388 private String getFolderSizeHuman(String path) {
389
390 File dir = new File(path);
391
392 if (dir.exists()) {
393 long bytes = FileStorageUtils.getFolderSize(dir);
394 return DisplayUtils.bytesToHumanReadable(bytes);
395 }
396
397 return "0 B";
398 }
399
400 /**
401 * Local Folder size
402 * @param dir File
403 * @return Size in bytes
404 */
405 private long getFolderSize(File dir) {
406 if (dir.exists()) {
407 long result = 0;
408 File[] fileList = dir.listFiles();
409 for(int i = 0; i < fileList.length; i++) {
410 if(fileList[i].isDirectory()) {
411 result += getFolderSize(fileList[i]);
412 } else {
413 result += fileList[i].length();
414 }
415 }
416 return result;
417 }
418 return 0;
419 }
420
421 @Override
422 public int getViewTypeCount() {
423 return 1;
424 }
425
426 @Override
427 public boolean hasStableIds() {
428 return true;
429 }
430
431 @Override
432 public boolean isEmpty() {
433 return (mFiles == null || mFiles.isEmpty());
434 }
435
436 /**
437 * Change the adapted directory for a new one
438 * @param directory New file to adapt. Can be NULL, meaning
439 * "no content to adapt".
440 * @param updatedStorageManager Optional updated storage manager; used to replace
441 * mStorageManager if is different (and not NULL)
442 */
443 public void swapDirectory(OCFile directory, FileDataStorageManager updatedStorageManager
444 , boolean onlyOnDevice) {
445 mFile = directory;
446 if (updatedStorageManager != null && updatedStorageManager != mStorageManager) {
447 mStorageManager = updatedStorageManager;
448 mAccount = AccountUtils.getCurrentOwnCloudAccount(mContext);
449 }
450 if (mStorageManager != null) {
451 mFiles = mStorageManager.getFolderContent(mFile, onlyOnDevice);
452 mFilesOrig.clear();
453 mFilesOrig.addAll(mFiles);
454
455 if (mJustFolders) {
456 mFiles = getFolders(mFiles);
457 }
458 } else {
459 mFiles = null;
460 }
461
462 mFiles = FileStorageUtils.sortOcFolder(mFiles);
463 notifyDataSetChanged();
464 }
465
466
467 /**
468 * Filter for getting only the folders
469 * @param files
470 * @return Vector<OCFile>
471 */
472 public Vector<OCFile> getFolders(Vector<OCFile> files) {
473 Vector<OCFile> ret = new Vector<OCFile>();
474 OCFile current = null;
475 for (int i=0; i<files.size(); i++) {
476 current = files.get(i);
477 if (current.isFolder()) {
478 ret.add(current);
479 }
480 }
481 return ret;
482 }
483
484
485 /**
486 * Check if parent folder does not include 'S' permission and if file/folder
487 * is shared with me
488 *
489 * @param file: OCFile
490 * @return boolean: True if it is shared with me and false if it is not
491 */
492 private boolean checkIfFileIsSharedWithMe(OCFile file) {
493 return (mFile.getPermissions() != null
494 && !mFile.getPermissions().contains(PERMISSION_SHARED_WITH_ME)
495 && file.getPermissions() != null
496 && file.getPermissions().contains(PERMISSION_SHARED_WITH_ME));
497 }
498
499 public void setSortOrder(Integer order, boolean ascending) {
500 SharedPreferences.Editor editor = mAppPreferences.edit();
501 editor.putInt("sortOrder", order);
502 editor.putBoolean("sortAscending", ascending);
503 editor.commit();
504
505 FileStorageUtils.mSortOrder = order;
506 FileStorageUtils.mSortAscending = ascending;
507
508
509 mFiles = FileStorageUtils.sortOcFolder(mFiles);
510 notifyDataSetChanged();
511
512 }
513
514 private CharSequence showRelativeTimestamp(OCFile file){
515 return DisplayUtils.getRelativeDateTimeString(mContext, file.getModificationTimestamp(),
516 DateUtils.SECOND_IN_MILLIS, DateUtils.WEEK_IN_MILLIS, 0);
517 }
518
519 public void setGridMode(boolean gridMode) {
520 mGridMode = gridMode;
521 }
522
523 public boolean isGridMode() {
524 return mGridMode;
525 }
526
527 public void setNewSelection(int position, boolean checked) {
528 mSelection.put(position, checked);
529 notifyDataSetChanged();
530 }
531
532 public void removeSelection(int position) {
533 mSelection.remove(position);
534 notifyDataSetChanged();
535 }
536
537 public void removeSelection(){
538 mSelection.clear();
539 notifyDataSetChanged();
540 }
541
542 public ArrayList<Integer> getCheckedItemPositions() {
543 ArrayList<Integer> ids = new ArrayList<Integer>();
544
545 for (Map.Entry<Integer, Boolean> entry : mSelection.entrySet()){
546 if (entry.getValue()){
547 ids.add(entry.getKey());
548 }
549 }
550 return ids;
551 }
552
553 public ArrayList<OCFile> getCheckedItems() {
554 ArrayList<OCFile> files = new ArrayList<OCFile>();
555
556 for (Map.Entry<Integer, Boolean> entry : mSelection.entrySet()){
557 if (entry.getValue()){
558 files.add((OCFile) getItem(entry.getKey()));
559 }
560 }
561 return files;
562 }
563 }