93a7b3013f25ee27242d9e5645eaab0fec90b01d
[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 import java.io.File;
21 import java.lang.ref.WeakReference;
22 import java.util.Vector;
23
24 import android.accounts.Account;
25 import android.content.Context;
26 import android.content.res.Resources;
27 import android.graphics.Bitmap;
28 import android.graphics.Bitmap.CompressFormat;
29 import android.graphics.BitmapFactory;
30 import android.graphics.drawable.BitmapDrawable;
31 import android.graphics.drawable.Drawable;
32 import android.media.ThumbnailUtils;
33 import android.os.AsyncTask;
34 import android.util.TypedValue;
35 import android.view.LayoutInflater;
36 import android.view.View;
37 import android.view.ViewGroup;
38 import android.widget.BaseAdapter;
39 import android.widget.ImageView;
40 import android.widget.ListAdapter;
41 import android.widget.ListView;
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.files.services.FileDownloader.FileDownloaderBinder;
49 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
50 import com.owncloud.android.ui.activity.ComponentsGetter;
51 import com.owncloud.android.utils.BitmapUtils;
52 import com.owncloud.android.utils.DisplayUtils;
53 import com.owncloud.android.utils.Log_OC;
54
55
56 /**
57 * This Adapter populates a ListView with all files and folders in an ownCloud
58 * instance.
59 *
60 * @author Bartek Przybylski
61 * @author Tobias Kaminsky
62 * @author David A. Velasco
63 */
64 public class FileListListAdapter extends BaseAdapter implements ListAdapter {
65 private final static String PERMISSION_SHARED_WITH_ME = "S";
66
67 private static final String TAG = FileListListAdapter.class.getSimpleName();
68
69 private Context mContext;
70 private OCFile mFile = null;
71 private Vector<OCFile> mFiles = null;
72 private boolean mJustFolders;
73
74 private FileDataStorageManager mStorageManager;
75 private Account mAccount;
76 private ComponentsGetter mTransferServiceGetter;
77
78 private final Object thumbnailDiskCacheLock = new Object();
79 private DiskLruImageCache mThumbnailCache;
80 private boolean mThumbnailCacheStarting = true;
81 private static final int DISK_CACHE_SIZE = 1024 * 1024 * 10; // 10MB
82 private static final CompressFormat mCompressFormat = CompressFormat.JPEG;
83 private static final int mCompressQuality = 70;
84 private Bitmap defaultImg;
85
86 public FileListListAdapter(
87 boolean justFolders,
88 Context context,
89 ComponentsGetter transferServiceGetter
90 ) {
91
92 mJustFolders = justFolders;
93 mContext = context;
94 mAccount = AccountUtils.getCurrentOwnCloudAccount(mContext);
95 mTransferServiceGetter = transferServiceGetter;
96 defaultImg = BitmapFactory.decodeResource(mContext.getResources(),
97 DisplayUtils.getResourceId("image/png", "default.png"));
98
99 // Initialise disk cache on background thread
100 new InitDiskCacheTask().execute();
101 }
102
103 class InitDiskCacheTask extends AsyncTask<File, Void, Void> {
104 @Override
105 protected Void doInBackground(File... params) {
106 synchronized (thumbnailDiskCacheLock) {
107 mThumbnailCache = new DiskLruImageCache(mContext, "thumbnailCache",
108 DISK_CACHE_SIZE, mCompressFormat, mCompressQuality);
109
110 mThumbnailCacheStarting = false; // Finished initialization
111 thumbnailDiskCacheLock.notifyAll(); // Wake any waiting threads
112 }
113 return null;
114 }
115 }
116
117 static class AsyncDrawable extends BitmapDrawable {
118 private final WeakReference<ThumbnailGenerationTask> bitmapWorkerTaskReference;
119
120 public AsyncDrawable(Resources res, Bitmap bitmap,
121 ThumbnailGenerationTask bitmapWorkerTask) {
122 super(res, bitmap);
123 bitmapWorkerTaskReference =
124 new WeakReference<ThumbnailGenerationTask>(bitmapWorkerTask);
125 }
126
127 public ThumbnailGenerationTask getBitmapWorkerTask() {
128 return bitmapWorkerTaskReference.get();
129 }
130 }
131
132 class ThumbnailGenerationTask extends AsyncTask<OCFile, Void, Bitmap> {
133 private final WeakReference<ImageView> imageViewReference;
134 private OCFile file;
135
136
137 public ThumbnailGenerationTask(ImageView imageView) {
138 // Use a WeakReference to ensure the ImageView can be garbage collected
139 imageViewReference = new WeakReference<ImageView>(imageView);
140 }
141
142 // Decode image in background.
143 @Override
144 protected Bitmap doInBackground(OCFile... params) {
145 Bitmap thumbnail = null;
146
147 try {
148 file = params[0];
149 final String imageKey = String.valueOf(file.getRemoteId());
150
151 // Check disk cache in background thread
152 thumbnail = getBitmapFromDiskCache(imageKey);
153
154 // Not found in disk cache
155 if (thumbnail == null) {
156 // Converts dp to pixel
157 Resources r = mContext.getResources();
158 int px = (int) Math.round(TypedValue.applyDimension(
159 TypedValue.COMPLEX_UNIT_DIP, 150, r.getDisplayMetrics()
160 ));
161
162 if (file.isDown()){
163 Bitmap bitmap = BitmapUtils.decodeSampledBitmapFromFile(
164 file.getStoragePath(), px, px);
165
166 if (bitmap != null) {
167 thumbnail = ThumbnailUtils.extractThumbnail(bitmap, px, px);
168
169 // Add thumbnail to cache
170 addBitmapToCache(imageKey, thumbnail);
171 }
172
173 } else {
174 // Download thumbnail from server
175 // Commented out as maybe changes to client library are needed
176 // DefaultHttpClient httpclient = new DefaultHttpClient();
177 // try {
178 // httpclient.getCredentialsProvider().setCredentials(
179 // new AuthScope(mClient.getBaseUri().toString().replace("https://", ""), 443),
180 // new UsernamePasswordCredentials(mClient.getCredentials().getUsername(), mClient.getCredentials().getAuthToken()));
181 //
182 //
183 // HttpGet httpget = new HttpGet(mClient.getBaseUri() + "/ocs/v1.php/thumbnail?x=50&y=50&path=" + URLEncoder.encode(file.getRemotePath(), "UTF-8"));
184 // HttpResponse response = httpclient.execute(httpget);
185 // HttpEntity entity = response.getEntity();
186 //
187 // if (entity != null) {
188 // byte[] bytes = EntityUtils.toByteArray(entity);
189 // Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
190 // thumbnail = ThumbnailUtils.extractThumbnail(bitmap, px, px);
191 //
192 // // Add thumbnail to cache
193 // if (thumbnail != null){
194 // addBitmapToCache(imageKey, thumbnail);
195 // }
196 // }
197 // } catch(Exception e){
198 // e.printStackTrace();
199 // }finally {
200 // httpclient.getConnectionManager().shutdown();
201 // }
202 }
203 }
204
205 } catch (Throwable t) {
206 // the app should never break due to a problem with thumbnails
207 Log_OC.e(TAG, "Generation of thumbnail for " + file + " failed", t);
208 if (t instanceof OutOfMemoryError) {
209 System.gc();
210 }
211 }
212
213 return thumbnail;
214 }
215
216 protected void onPostExecute(Bitmap bitmap){
217 if (isCancelled()) {
218 bitmap = null;
219 }
220
221 if (imageViewReference != null && bitmap != null) {
222 final ImageView imageView = imageViewReference.get();
223 final ThumbnailGenerationTask bitmapWorkerTask =
224 getBitmapWorkerTask(imageView);
225 if (this == bitmapWorkerTask && imageView != null) {
226 imageView.setImageBitmap(bitmap);
227 }
228 }
229 }
230 }
231
232 public void addBitmapToCache(String key, Bitmap bitmap) {
233 synchronized (thumbnailDiskCacheLock) {
234 if (mThumbnailCache != null && mThumbnailCache.getBitmap(key) == null) {
235 mThumbnailCache.put(key, bitmap);
236 }
237 }
238 }
239
240 public Bitmap getBitmapFromDiskCache(String key) {
241 synchronized (thumbnailDiskCacheLock) {
242 // Wait while disk cache is started from background thread
243 while (mThumbnailCacheStarting) {
244 try {
245 thumbnailDiskCacheLock.wait();
246 } catch (InterruptedException e) {}
247 }
248 if (mThumbnailCache != null) {
249 return (Bitmap) mThumbnailCache.getBitmap(key);
250 }
251 }
252 return null;
253 }
254
255 @Override
256 public boolean areAllItemsEnabled() {
257 return true;
258 }
259
260 @Override
261 public boolean isEnabled(int position) {
262 return true;
263 }
264
265 @Override
266 public int getCount() {
267 return mFiles != null ? mFiles.size() : 0;
268 }
269
270 @Override
271 public Object getItem(int position) {
272 if (mFiles == null || mFiles.size() <= position)
273 return null;
274 return mFiles.get(position);
275 }
276
277 @Override
278 public long getItemId(int position) {
279 if (mFiles == null || mFiles.size() <= position)
280 return 0;
281 return mFiles.get(position).getFileId();
282 }
283
284 @Override
285 public int getItemViewType(int position) {
286 return 0;
287 }
288
289 @Override
290 public View getView(int position, View convertView, ViewGroup parent) {
291 View view = convertView;
292 if (view == null) {
293 LayoutInflater inflator = (LayoutInflater) mContext
294 .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
295 view = inflator.inflate(R.layout.list_item, null);
296 }
297
298 if (mFiles != null && mFiles.size() > position) {
299 OCFile file = mFiles.get(position);
300 TextView fileName = (TextView) view.findViewById(R.id.Filename);
301 String name = file.getFileName();
302
303 fileName.setText(name);
304 ImageView fileIcon = (ImageView) view.findViewById(R.id.imageView1);
305 ImageView sharedIconV = (ImageView) view.findViewById(R.id.sharedIcon);
306 ImageView sharedWithMeIconV = (ImageView) view.findViewById(R.id.sharedWithMeIcon);
307 sharedWithMeIconV.setVisibility(View.GONE);
308
309 ImageView localStateView = (ImageView) view.findViewById(R.id.imageView2);
310 localStateView.bringToFront();
311 FileDownloaderBinder downloaderBinder =
312 mTransferServiceGetter.getFileDownloaderBinder();
313 FileUploaderBinder uploaderBinder = mTransferServiceGetter.getFileUploaderBinder();
314 if (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, file)) {
315 localStateView.setImageResource(R.drawable.downloading_file_indicator);
316 localStateView.setVisibility(View.VISIBLE);
317 } else if (uploaderBinder != null && uploaderBinder.isUploading(mAccount, file)) {
318 localStateView.setImageResource(R.drawable.uploading_file_indicator);
319 localStateView.setVisibility(View.VISIBLE);
320 } else if (file.isDown()) {
321 localStateView.setImageResource(R.drawable.local_file_indicator);
322 localStateView.setVisibility(View.VISIBLE);
323 } else {
324 localStateView.setVisibility(View.INVISIBLE);
325 }
326
327 TextView fileSizeV = (TextView) view.findViewById(R.id.file_size);
328 TextView lastModV = (TextView) view.findViewById(R.id.last_mod);
329 ImageView checkBoxV = (ImageView) view.findViewById(R.id.custom_checkbox);
330
331 if (!file.isFolder()) {
332 fileSizeV.setVisibility(View.VISIBLE);
333 fileSizeV.setText(DisplayUtils.bytesToHumanReadable(file.getFileLength()));
334 lastModV.setVisibility(View.VISIBLE);
335 lastModV.setText(
336 DisplayUtils.unixTimeToHumanReadable(file.getModificationTimestamp())
337 );
338 // this if-else is needed even thoe fav icon is visible by default
339 // because android reuses views in listview
340 if (!file.keepInSync()) {
341 view.findViewById(R.id.imageView3).setVisibility(View.GONE);
342 } else {
343 view.findViewById(R.id.imageView3).setVisibility(View.VISIBLE);
344 }
345
346 ListView parentList = (ListView)parent;
347 if (parentList.getChoiceMode() == ListView.CHOICE_MODE_NONE) {
348 checkBoxV.setVisibility(View.GONE);
349 } else {
350 if (parentList.isItemChecked(position)) {
351 checkBoxV.setImageResource(android.R.drawable.checkbox_on_background);
352 } else {
353 checkBoxV.setImageResource(android.R.drawable.checkbox_off_background);
354 }
355 checkBoxV.setVisibility(View.VISIBLE);
356 }
357
358 // get Thumbnail if file is image
359 if (file.isImage()){
360 // Thumbnail in Cache?
361 Bitmap thumbnail = getBitmapFromDiskCache(String.valueOf(file.getRemoteId()));
362 if (thumbnail != null){
363 fileIcon.setImageBitmap(thumbnail);
364 } else {
365 // generate new Thumbnail
366 if (cancelPotentialWork(file, fileIcon)) {
367 final ThumbnailGenerationTask task =
368 new ThumbnailGenerationTask(fileIcon);
369 final AsyncDrawable asyncDrawable =
370 new AsyncDrawable(mContext.getResources(), defaultImg, task);
371 fileIcon.setImageDrawable(asyncDrawable);
372 task.execute(file);
373 }
374 }
375 } else {
376 fileIcon.setImageResource(
377 DisplayUtils.getResourceId(file.getMimetype(), file.getFileName())
378 );
379 }
380
381 if (checkIfFileIsSharedWithMe(file)) {
382 sharedWithMeIconV.setVisibility(View.VISIBLE);
383 }
384 }
385 else {
386 fileSizeV.setVisibility(View.INVISIBLE);
387 //fileSizeV.setText(DisplayUtils.bytesToHumanReadable(file.getFileLength()));
388 lastModV.setVisibility(View.VISIBLE);
389 lastModV.setText(
390 DisplayUtils.unixTimeToHumanReadable(file.getModificationTimestamp())
391 );
392 checkBoxV.setVisibility(View.GONE);
393 view.findViewById(R.id.imageView3).setVisibility(View.GONE);
394
395 if (checkIfFileIsSharedWithMe(file)) {
396 fileIcon.setImageResource(R.drawable.shared_with_me_folder);
397 sharedWithMeIconV.setVisibility(View.VISIBLE);
398 } else {
399 fileIcon.setImageResource(
400 DisplayUtils.getResourceId(file.getMimetype(), file.getFileName())
401 );
402 }
403
404 // If folder is sharedByLink, icon folder must be changed to
405 // folder-public one
406 if (file.isShareByLink()) {
407 fileIcon.setImageResource(R.drawable.folder_public);
408 }
409 }
410
411 if (file.isShareByLink()) {
412 sharedIconV.setVisibility(View.VISIBLE);
413 } else {
414 sharedIconV.setVisibility(View.GONE);
415 }
416 }
417
418 return view;
419 }
420
421 public static boolean cancelPotentialWork(OCFile file, ImageView imageView) {
422 final ThumbnailGenerationTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
423
424 if (bitmapWorkerTask != null) {
425 final OCFile bitmapData = bitmapWorkerTask.file;
426 // If bitmapData is not yet set or it differs from the new data
427 if (bitmapData == null || bitmapData != file) {
428 // Cancel previous task
429 bitmapWorkerTask.cancel(true);
430 } else {
431 // The same work is already in progress
432 return false;
433 }
434 }
435 // No task associated with the ImageView, or an existing task was cancelled
436 return true;
437 }
438
439 private static ThumbnailGenerationTask getBitmapWorkerTask(ImageView imageView) {
440 if (imageView != null) {
441 final Drawable drawable = imageView.getDrawable();
442 if (drawable instanceof AsyncDrawable) {
443 final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
444 return asyncDrawable.getBitmapWorkerTask();
445 }
446 }
447 return null;
448 }
449
450 @Override
451 public int getViewTypeCount() {
452 return 1;
453 }
454
455 @Override
456 public boolean hasStableIds() {
457 return true;
458 }
459
460 @Override
461 public boolean isEmpty() {
462 return (mFiles == null || mFiles.isEmpty());
463 }
464
465 /**
466 * Change the adapted directory for a new one
467 * @param directory New file to adapt. Can be NULL, meaning
468 * "no content to adapt".
469 * @param updatedStorageManager Optional updated storage manager; used to replace
470 * mStorageManager if is different (and not NULL)
471 */
472 public void swapDirectory(OCFile directory, FileDataStorageManager updatedStorageManager) {
473 mFile = directory;
474 if (updatedStorageManager != null && updatedStorageManager != mStorageManager) {
475 mStorageManager = updatedStorageManager;
476 mAccount = AccountUtils.getCurrentOwnCloudAccount(mContext);
477 }
478 if (mStorageManager != null) {
479 mFiles = mStorageManager.getFolderContent(mFile);
480 if (mJustFolders) {
481 mFiles = getFolders(mFiles);
482 }
483 } else {
484 mFiles = null;
485 }
486 notifyDataSetChanged();
487 }
488
489
490 /**
491 * Filter for getting only the folders
492 * @param files
493 * @return Vector<OCFile>
494 */
495 public Vector<OCFile> getFolders(Vector<OCFile> files) {
496 Vector<OCFile> ret = new Vector<OCFile>();
497 OCFile current = null;
498 for (int i=0; i<files.size(); i++) {
499 current = files.get(i);
500 if (current.isFolder()) {
501 ret.add(current);
502 }
503 }
504 return ret;
505 }
506
507
508 /**
509 * Check if parent folder does not include 'S' permission and if file/folder
510 * is shared with me
511 *
512 * @param file: OCFile
513 * @return boolean: True if it is shared with me and false if it is not
514 */
515 private boolean checkIfFileIsSharedWithMe(OCFile file) {
516 return (mFile.getPermissions() != null
517 && !mFile.getPermissions().contains(PERMISSION_SHARED_WITH_ME)
518 && file.getPermissions() != null
519 && file.getPermissions().contains(PERMISSION_SHARED_WITH_ME));
520 }
521 }