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