2537d80f4f9be7e99eb5f9486d32363e306aa818
[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.preference.PreferenceManager;
34 import android.text.format.DateUtils;
35 import android.view.LayoutInflater;
36 import android.view.View;
37 import android.view.ViewGroup;
38 import android.widget.AbsListView;
39 import android.widget.BaseAdapter;
40 import android.widget.GridView;
41 import android.widget.ImageView;
42 import android.widget.ListAdapter;
43 import android.widget.TextView;
44
45 import com.owncloud.android.R;
46 import com.owncloud.android.authentication.AccountUtils;
47 import com.owncloud.android.datamodel.FileDataStorageManager;
48 import com.owncloud.android.datamodel.OCFile;
49 import com.owncloud.android.datamodel.ThumbnailsCacheManager;
50 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
51 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
52 import com.owncloud.android.services.OperationsService.OperationsServiceBinder;
53 import com.owncloud.android.ui.activity.ComponentsGetter;
54 import com.owncloud.android.utils.DisplayUtils;
55 import com.owncloud.android.utils.FileStorageUtils;
56
57
58 /**
59 * This Adapter populates a ListView with all files and folders in an ownCloud
60 * instance.
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 Vector<OCFile> mFilesOrig = new Vector<OCFile>();
69 private boolean mJustFolders;
70
71 private FileDataStorageManager mStorageManager;
72 private Account mAccount;
73 private ComponentsGetter mTransferServiceGetter;
74 private boolean mGridMode;
75
76 private enum ViewType {LIST_ITEM, GRID_IMAGE, GRID_ITEM };
77
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 FileStorageUtils.mSortOrder = mAppPreferences.getInt("sortOrder", 0);
96 FileStorageUtils.mSortAscending = mAppPreferences.getBoolean("sortAscending", true);
97
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
162 switch (viewType){
163 case GRID_IMAGE:
164 view = inflator.inflate(R.layout.grid_image, null);
165 break;
166 case GRID_ITEM:
167 view = inflator.inflate(R.layout.grid_item, null);
168 break;
169 case LIST_ITEM:
170 view = inflator.inflate(R.layout.list_item, null);
171 break;
172 }
173
174 view.invalidate();
175
176 if (file != null){
177
178 ImageView fileIcon = (ImageView) view.findViewById(R.id.thumbnail);
179 fileIcon.setTag(file.getFileId());
180 TextView fileName;
181 String name;
182
183 switch (viewType){
184 case LIST_ITEM:
185 TextView fileSizeV = (TextView) view.findViewById(R.id.file_size);
186 TextView lastModV = (TextView) view.findViewById(R.id.last_mod);
187 ImageView checkBoxV = (ImageView) view.findViewById(R.id.custom_checkbox);
188
189 lastModV.setVisibility(View.VISIBLE);
190 lastModV.setText(showRelativeTimestamp(file));
191
192 checkBoxV.setVisibility(View.GONE);
193
194 fileSizeV.setVisibility(View.VISIBLE);
195 fileSizeV.setText(DisplayUtils.bytesToHumanReadable(file.getFileLength()));
196
197 if (!file.isFolder()) {
198 AbsListView parentList = (AbsListView)parent;
199 if (parentList.getChoiceMode() == AbsListView.CHOICE_MODE_NONE) {
200 checkBoxV.setVisibility(View.GONE);
201 } else {
202 if (parentList.isItemChecked(position)) {
203 checkBoxV.setImageResource(android.R.drawable.checkbox_on_background);
204 } else {
205 checkBoxV.setImageResource(android.R.drawable.checkbox_off_background);
206 }
207 checkBoxV.setVisibility(View.VISIBLE);
208 }
209
210 } else { //Folder
211 fileSizeV.setVisibility(View.INVISIBLE);
212 }
213
214 case GRID_ITEM:
215 // filename
216 fileName = (TextView) view.findViewById(R.id.Filename);
217 name = file.getFileName();
218 fileName.setText(name);
219
220 case GRID_IMAGE:
221 // sharedIcon
222 ImageView sharedIconV = (ImageView) view.findViewById(R.id.sharedIcon);
223 if (file.isShareByLink()) {
224 sharedIconV.setVisibility(View.VISIBLE);
225 sharedIconV.bringToFront();
226 } else {
227 sharedIconV.setVisibility(View.GONE);
228 }
229
230 // local state
231 ImageView localStateView = (ImageView) view.findViewById(R.id.localFileIndicator);
232 localStateView.bringToFront();
233 FileDownloaderBinder downloaderBinder = mTransferServiceGetter.getFileDownloaderBinder();
234 FileUploaderBinder uploaderBinder = mTransferServiceGetter.getFileUploaderBinder();
235 boolean downloading = (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, file));
236 OperationsServiceBinder opsBinder = mTransferServiceGetter.getOperationsServiceBinder();
237 downloading |= (opsBinder != null && opsBinder.isSynchronizing(mAccount, file.getRemotePath()));
238 if (downloading) {
239 localStateView.setImageResource(R.drawable.downloading_file_indicator);
240 localStateView.setVisibility(View.VISIBLE);
241 } else if (uploaderBinder != null && uploaderBinder.isUploading(mAccount, file)) {
242 localStateView.setImageResource(R.drawable.uploading_file_indicator);
243 localStateView.setVisibility(View.VISIBLE);
244 } else if (file.isDown()) {
245 localStateView.setImageResource(R.drawable.local_file_indicator);
246 localStateView.setVisibility(View.VISIBLE);
247 } else {
248 localStateView.setVisibility(View.INVISIBLE);
249 }
250
251 // share with me icon
252 if (!file.isFolder()) {
253 ImageView sharedWithMeIconV = (ImageView) view.findViewById(R.id.sharedWithMeIcon);
254 sharedWithMeIconV.bringToFront();
255 if (checkIfFileIsSharedWithMe(file)) {
256 sharedWithMeIconV.setVisibility(View.VISIBLE);
257 } else {
258 sharedWithMeIconV.setVisibility(View.GONE);
259 }
260 }
261
262 break;
263 }
264
265 // For all Views
266
267 // this if-else is needed even though favorite icon is visible by default
268 // because android reuses views in listview
269 if (!file.keepInSync()) {
270 view.findViewById(R.id.favoriteIcon).setVisibility(View.GONE);
271 } else {
272 view.findViewById(R.id.favoriteIcon).setVisibility(View.VISIBLE);
273 }
274
275 // No Folder
276 if (!file.isFolder()) {
277 if (file.isImage() && file.getRemoteId() != null){
278 // Thumbnail in Cache?
279 Bitmap thumbnail = ThumbnailsCacheManager.getBitmapFromDiskCache(
280 String.valueOf(file.getRemoteId())
281 );
282 if (thumbnail != null && !file.needsUpdateThumbnail()){
283 fileIcon.setImageBitmap(thumbnail);
284 } else {
285 // generate new Thumbnail
286 if (ThumbnailsCacheManager.cancelPotentialWork(file, fileIcon)) {
287 final ThumbnailsCacheManager.ThumbnailGenerationTask task =
288 new ThumbnailsCacheManager.ThumbnailGenerationTask(
289 fileIcon, mStorageManager, mAccount
290 );
291 if (thumbnail == null) {
292 thumbnail = ThumbnailsCacheManager.mDefaultImg;
293 }
294 final ThumbnailsCacheManager.AsyncDrawable asyncDrawable =
295 new ThumbnailsCacheManager.AsyncDrawable(
296 mContext.getResources(),
297 thumbnail,
298 task
299 );
300 fileIcon.setImageDrawable(asyncDrawable);
301 task.execute(file);
302 }
303 }
304 } else {
305 fileIcon.setImageResource(DisplayUtils.getFileTypeIconId(file.getMimetype(), file.getFileName()));
306 }
307 } else {
308 // Folder
309 if (checkIfFileIsSharedWithMe(file)) {
310 fileIcon.setImageResource(R.drawable.shared_with_me_folder);
311 } else if (file.isShareByLink()) {
312 // If folder is sharedByLink, icon folder must be changed to
313 // folder-public one
314 fileIcon.setImageResource(R.drawable.folder_public);
315 } else {
316 fileIcon.setImageResource(
317 DisplayUtils.getFileTypeIconId(file.getMimetype(), file.getFileName())
318 );
319 }
320 }
321 }
322
323 return view;
324 }
325
326 /**
327 * Local Folder size in human readable format
328 *
329 * @param path
330 * String
331 * @return Size in human readable format
332 */
333 private String getFolderSizeHuman(String path) {
334
335 File dir = new File(path);
336
337 if (dir.exists()) {
338 long bytes = FileStorageUtils.getFolderSize(dir);
339 return DisplayUtils.bytesToHumanReadable(bytes);
340 }
341
342 return "0 B";
343 }
344
345 /**
346 * Local Folder size
347 * @param dir File
348 * @return Size in bytes
349 */
350 private long getFolderSize(File dir) {
351 if (dir.exists()) {
352 long result = 0;
353 File[] fileList = dir.listFiles();
354 for(int i = 0; i < fileList.length; i++) {
355 if(fileList[i].isDirectory()) {
356 result += getFolderSize(fileList[i]);
357 } else {
358 result += fileList[i].length();
359 }
360 }
361 return result;
362 }
363 return 0;
364 }
365
366 @Override
367 public int getViewTypeCount() {
368 return 1;
369 }
370
371 @Override
372 public boolean hasStableIds() {
373 return true;
374 }
375
376 @Override
377 public boolean isEmpty() {
378 return (mFiles == null || mFiles.isEmpty());
379 }
380
381 /**
382 * Change the adapted directory for a new one
383 * @param directory New file to adapt. Can be NULL, meaning
384 * "no content to adapt".
385 * @param updatedStorageManager Optional updated storage manager; used to replace
386 * mStorageManager if is different (and not NULL)
387 */
388 public void swapDirectory(OCFile directory, FileDataStorageManager updatedStorageManager) {
389 mFile = directory;
390 if (updatedStorageManager != null && updatedStorageManager != mStorageManager) {
391 mStorageManager = updatedStorageManager;
392 mAccount = AccountUtils.getCurrentOwnCloudAccount(mContext);
393 }
394 if (mStorageManager != null) {
395 mFiles = mStorageManager.getFolderContent(mFile);
396 mFilesOrig.clear();
397 mFilesOrig.addAll(mFiles);
398
399 if (mJustFolders) {
400 mFiles = getFolders(mFiles);
401 }
402 } else {
403 mFiles = null;
404 }
405
406 mFiles = FileStorageUtils.sortFolder(mFiles);
407 notifyDataSetChanged();
408 }
409
410
411 /**
412 * Filter for getting only the folders
413 * @param files
414 * @return Vector<OCFile>
415 */
416 public Vector<OCFile> getFolders(Vector<OCFile> files) {
417 Vector<OCFile> ret = new Vector<OCFile>();
418 OCFile current = null;
419 for (int i=0; i<files.size(); i++) {
420 current = files.get(i);
421 if (current.isFolder()) {
422 ret.add(current);
423 }
424 }
425 return ret;
426 }
427
428
429 /**
430 * Check if parent folder does not include 'S' permission and if file/folder
431 * is shared with me
432 *
433 * @param file: OCFile
434 * @return boolean: True if it is shared with me and false if it is not
435 */
436 private boolean checkIfFileIsSharedWithMe(OCFile file) {
437 return (mFile.getPermissions() != null
438 && !mFile.getPermissions().contains(PERMISSION_SHARED_WITH_ME)
439 && file.getPermissions() != null
440 && file.getPermissions().contains(PERMISSION_SHARED_WITH_ME));
441 }
442
443 public void setSortOrder(Integer order, boolean ascending) {
444 SharedPreferences.Editor editor = mAppPreferences.edit();
445 editor.putInt("sortOrder", order);
446 editor.putBoolean("sortAscending", ascending);
447 editor.commit();
448
449 FileStorageUtils.mSortOrder = order;
450 FileStorageUtils.mSortAscending = ascending;
451
452
453 mFiles = FileStorageUtils.sortFolder(mFiles);
454 notifyDataSetChanged();
455
456 }
457
458 private CharSequence showRelativeTimestamp(OCFile file){
459 return DisplayUtils.getRelativeDateTimeString(mContext, file.getModificationTimestamp(),
460 DateUtils.SECOND_IN_MILLIS, DateUtils.WEEK_IN_MILLIS, 0);
461 }
462
463 public void setGridMode(boolean gridMode) {
464 mGridMode = gridMode;
465 }
466 }