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