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