038a627205aea3f58e77bd212399c50c42209f30
[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 thumbnail = ThumbnailUtils.extractThumbnail(bitmap, px, px);
176
177 // Add thumbnail to cache
178 addBitmapToCache(imageKey, thumbnail);
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 return thumbnail;
212 }
213
214 protected void onPostExecute(Bitmap bitmap){
215 if (isCancelled()) {
216 bitmap = null;
217 }
218
219 if (imageViewReference != null && bitmap != null) {
220 final ImageView imageView = imageViewReference.get();
221 final ThumbnailGenerationTask bitmapWorkerTask =
222 getBitmapWorkerTask(imageView);
223 if (this == bitmapWorkerTask && imageView != null) {
224 imageView.setImageBitmap(bitmap);
225 }
226 }
227 }
228 }
229
230 public void addBitmapToCache(String key, Bitmap bitmap) {
231 synchronized (thumbnailDiskCacheLock) {
232 if (mThumbnailCache != null && mThumbnailCache.getBitmap(key) == null) {
233 mThumbnailCache.put(key, bitmap);
234 }
235 }
236 }
237
238 public Bitmap getBitmapFromDiskCache(String key) {
239 synchronized (thumbnailDiskCacheLock) {
240 // Wait while disk cache is started from background thread
241 while (mThumbnailCacheStarting) {
242 try {
243 thumbnailDiskCacheLock.wait();
244 } catch (InterruptedException e) {}
245 }
246 if (mThumbnailCache != null) {
247 return (Bitmap) mThumbnailCache.getBitmap(key);
248 }
249 }
250 return null;
251 }
252
253 @Override
254 public boolean areAllItemsEnabled() {
255 return true;
256 }
257
258 @Override
259 public boolean isEnabled(int position) {
260 return true;
261 }
262
263 @Override
264 public int getCount() {
265 return mFiles != null ? mFiles.size() : 0;
266 }
267
268 @Override
269 public Object getItem(int position) {
270 if (mFiles == null || mFiles.size() <= position)
271 return null;
272 return mFiles.get(position);
273 }
274
275 @Override
276 public long getItemId(int position) {
277 if (mFiles == null || mFiles.size() <= position)
278 return 0;
279 return mFiles.get(position).getFileId();
280 }
281
282 @Override
283 public int getItemViewType(int position) {
284 return 0;
285 }
286
287 @Override
288 public View getView(int position, View convertView, ViewGroup parent) {
289 View view = convertView;
290 if (view == null) {
291 LayoutInflater inflator = (LayoutInflater) mContext
292 .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
293 view = inflator.inflate(R.layout.list_item, null);
294 }
295
296 if (mFiles != null && mFiles.size() > position) {
297 OCFile file = mFiles.get(position);
298 TextView fileName = (TextView) view.findViewById(R.id.Filename);
299 String name = file.getFileName();
300
301 fileName.setText(name);
302 ImageView fileIcon = (ImageView) view.findViewById(R.id.imageView1);
303 ImageView sharedIconV = (ImageView) view.findViewById(R.id.sharedIcon);
304 ImageView sharedWithMeIconV = (ImageView) view.findViewById(R.id.sharedWithMeIcon);
305 sharedWithMeIconV.setVisibility(View.GONE);
306
307 ImageView localStateView = (ImageView) view.findViewById(R.id.imageView2);
308 localStateView.bringToFront();
309 FileDownloaderBinder downloaderBinder =
310 mTransferServiceGetter.getFileDownloaderBinder();
311 FileUploaderBinder uploaderBinder = mTransferServiceGetter.getFileUploaderBinder();
312 if (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, file)) {
313 localStateView.setImageResource(R.drawable.downloading_file_indicator);
314 localStateView.setVisibility(View.VISIBLE);
315 } else if (uploaderBinder != null && uploaderBinder.isUploading(mAccount, file)) {
316 localStateView.setImageResource(R.drawable.uploading_file_indicator);
317 localStateView.setVisibility(View.VISIBLE);
318 } else if (file.isDown()) {
319 localStateView.setImageResource(R.drawable.local_file_indicator);
320 localStateView.setVisibility(View.VISIBLE);
321 } else {
322 localStateView.setVisibility(View.INVISIBLE);
323 }
324
325 TextView fileSizeV = (TextView) view.findViewById(R.id.file_size);
326 TextView lastModV = (TextView) view.findViewById(R.id.last_mod);
327 ImageView checkBoxV = (ImageView) view.findViewById(R.id.custom_checkbox);
328
329 if (!file.isFolder()) {
330 fileSizeV.setVisibility(View.VISIBLE);
331 fileSizeV.setText(DisplayUtils.bytesToHumanReadable(file.getFileLength()));
332 lastModV.setVisibility(View.VISIBLE);
333 lastModV.setText(
334 DisplayUtils.unixTimeToHumanReadable(file.getModificationTimestamp())
335 );
336 // this if-else is needed even thoe fav icon is visible by default
337 // because android reuses views in listview
338 if (!file.keepInSync()) {
339 view.findViewById(R.id.imageView3).setVisibility(View.GONE);
340 } else {
341 view.findViewById(R.id.imageView3).setVisibility(View.VISIBLE);
342 }
343
344 ListView parentList = (ListView)parent;
345 if (parentList.getChoiceMode() == ListView.CHOICE_MODE_NONE) {
346 checkBoxV.setVisibility(View.GONE);
347 } else {
348 if (parentList.isItemChecked(position)) {
349 checkBoxV.setImageResource(android.R.drawable.checkbox_on_background);
350 } else {
351 checkBoxV.setImageResource(android.R.drawable.checkbox_off_background);
352 }
353 checkBoxV.setVisibility(View.VISIBLE);
354 }
355
356 // get Thumbnail if file is image
357 if (file.isImage()){
358 // Thumbnail in Cache?
359 Bitmap thumbnail = getBitmapFromDiskCache(String.valueOf(file.getRemoteId()));
360 if (thumbnail != null){
361 fileIcon.setImageBitmap(thumbnail);
362 } else {
363 // generate new Thumbnail
364 if (cancelPotentialWork(file, fileIcon)) {
365 final ThumbnailGenerationTask task =
366 new ThumbnailGenerationTask(fileIcon);
367 final AsyncDrawable asyncDrawable =
368 new AsyncDrawable(mContext.getResources(), defaultImg, task);
369 fileIcon.setImageDrawable(asyncDrawable);
370 task.execute(file);
371 }
372 }
373 } else {
374 fileIcon.setImageResource(
375 DisplayUtils.getResourceId(file.getMimetype(), file.getFileName())
376 );
377 }
378
379 if (checkIfFileIsSharedWithMe(file)) {
380 sharedWithMeIconV.setVisibility(View.VISIBLE);
381 }
382 }
383 else {
384 fileSizeV.setVisibility(View.INVISIBLE);
385 //fileSizeV.setText(DisplayUtils.bytesToHumanReadable(file.getFileLength()));
386 lastModV.setVisibility(View.VISIBLE);
387 lastModV.setText(
388 DisplayUtils.unixTimeToHumanReadable(file.getModificationTimestamp())
389 );
390 checkBoxV.setVisibility(View.GONE);
391 view.findViewById(R.id.imageView3).setVisibility(View.GONE);
392
393 if (checkIfFileIsSharedWithMe(file)) {
394 fileIcon.setImageResource(R.drawable.shared_with_me_folder);
395 sharedWithMeIconV.setVisibility(View.VISIBLE);
396 } else {
397 fileIcon.setImageResource(
398 DisplayUtils.getResourceId(file.getMimetype(), file.getFileName())
399 );
400 }
401
402 // If folder is sharedByLink, icon folder must be changed to
403 // folder-public one
404 if (file.isShareByLink()) {
405 fileIcon.setImageResource(R.drawable.folder_public);
406 }
407 }
408
409 if (file.isShareByLink()) {
410 sharedIconV.setVisibility(View.VISIBLE);
411 } else {
412 sharedIconV.setVisibility(View.GONE);
413 }
414 }
415
416 return view;
417 }
418
419 public static boolean cancelPotentialWork(OCFile file, ImageView imageView) {
420 final ThumbnailGenerationTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
421
422 if (bitmapWorkerTask != null) {
423 final OCFile bitmapData = bitmapWorkerTask.file;
424 // If bitmapData is not yet set or it differs from the new data
425 if (bitmapData == null || bitmapData != file) {
426 // Cancel previous task
427 bitmapWorkerTask.cancel(true);
428 } else {
429 // The same work is already in progress
430 return false;
431 }
432 }
433 // No task associated with the ImageView, or an existing task was cancelled
434 return true;
435 }
436
437 private static ThumbnailGenerationTask getBitmapWorkerTask(ImageView imageView) {
438 if (imageView != null) {
439 final Drawable drawable = imageView.getDrawable();
440 if (drawable instanceof AsyncDrawable) {
441 final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
442 return asyncDrawable.getBitmapWorkerTask();
443 }
444 }
445 return null;
446 }
447
448 @Override
449 public int getViewTypeCount() {
450 return 1;
451 }
452
453 @Override
454 public boolean hasStableIds() {
455 return true;
456 }
457
458 @Override
459 public boolean isEmpty() {
460 return (mFiles == null || mFiles.isEmpty());
461 }
462
463 /**
464 * Change the adapted directory for a new one
465 * @param directory New file to adapt. Can be NULL, meaning
466 * "no content to adapt".
467 * @param updatedStorageManager Optional updated storage manager; used to replace
468 * mStorageManager if is different (and not NULL)
469 */
470 public void swapDirectory(OCFile directory, FileDataStorageManager updatedStorageManager) {
471 mFile = directory;
472 if (updatedStorageManager != null && updatedStorageManager != mStorageManager) {
473 mStorageManager = updatedStorageManager;
474 mAccount = AccountUtils.getCurrentOwnCloudAccount(mContext);
475 }
476 if (mStorageManager != null) {
477 mFiles = mStorageManager.getFolderContent(mFile);
478 if (mJustFolders) {
479 mFiles = getFolders(mFiles);
480 }
481 } else {
482 mFiles = null;
483 }
484 notifyDataSetChanged();
485 }
486
487
488 /**
489 * Filter for getting only the folders
490 * @param files
491 * @return Vector<OCFile>
492 */
493 public Vector<OCFile> getFolders(Vector<OCFile> files) {
494 Vector<OCFile> ret = new Vector<OCFile>();
495 OCFile current = null;
496 for (int i=0; i<files.size(); i++) {
497 current = files.get(i);
498 if (current.isFolder()) {
499 ret.add(current);
500 }
501 }
502 return ret;
503 }
504
505
506 /**
507 * Check if parent folder does not include 'S' permission and if file/folder
508 * is shared with me
509 *
510 * @param file: OCFile
511 * @return boolean: True if it is shared with me and false if it is not
512 */
513 private boolean checkIfFileIsSharedWithMe(OCFile file) {
514 return (mFile.getPermissions() != null
515 && !mFile.getPermissions().contains(PERMISSION_SHARED_WITH_ME)
516 && file.getPermissions() != null
517 && file.getPermissions().contains(PERMISSION_SHARED_WITH_ME));
518 }
519 }