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