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