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