1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2014 ownCloud Inc.
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.
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.
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/>.
18 package com
.owncloud
.android
.ui
.adapter
;
21 import java
.lang
.ref
.WeakReference
;
22 import java
.util
.Vector
;
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
;
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
;
56 * This Adapter populates a ListView with all files and folders in an ownCloud
59 * @author Bartek Przybylski
60 * @Author Tobias Kaminsky
63 public class FileListListAdapter
extends BaseAdapter
implements ListAdapter
{
64 private final static String PERMISSION_SHARED_WITH_ME
= "S";
66 private Context mContext
;
67 private OCFile mFile
= null
;
68 private Vector
<OCFile
> mFiles
= null
;
69 private boolean mJustFolders
;
71 private FileDataStorageManager mStorageManager
;
72 private Account mAccount
;
73 private ComponentsGetter mTransferServiceGetter
;
75 private final Object thumbnailDiskCacheLock
= new Object();
76 private DiskLruImageCache mThumbnailCache
;
77 private boolean mThumbnailCacheStarting
= true
;
78 private static final int DISK_CACHE_SIZE
= 1024 * 1024 * 10; // 10MB
79 private static final CompressFormat mCompressFormat
= CompressFormat
.JPEG
;
80 private static final int mCompressQuality
= 70;
81 private Bitmap defaultImg
;
83 public FileListListAdapter(
86 ComponentsGetter transferServiceGetter
89 mJustFolders
= justFolders
;
91 mAccount
= AccountUtils
.getCurrentOwnCloudAccount(mContext
);
92 mTransferServiceGetter
= transferServiceGetter
;
93 defaultImg
= BitmapFactory
.decodeResource(mContext
.getResources(),
94 DisplayUtils
.getResourceId("image/png", "default.png"));
96 // Initialise disk cache on background thread
97 new InitDiskCacheTask().execute();
100 class InitDiskCacheTask
extends AsyncTask
<File
, Void
, Void
> {
102 protected Void
doInBackground(File
... params
) {
103 synchronized (thumbnailDiskCacheLock
) {
104 mThumbnailCache
= new DiskLruImageCache(mContext
, "thumbnailCache",
105 DISK_CACHE_SIZE
, mCompressFormat
, mCompressQuality
);
107 mThumbnailCacheStarting
= false
; // Finished initialization
108 thumbnailDiskCacheLock
.notifyAll(); // Wake any waiting threads
114 static class AsyncDrawable
extends BitmapDrawable
{
115 private final WeakReference
<ThumbnailGenerationTask
> bitmapWorkerTaskReference
;
117 public AsyncDrawable(Resources res
, Bitmap bitmap
,
118 ThumbnailGenerationTask bitmapWorkerTask
) {
120 bitmapWorkerTaskReference
=
121 new WeakReference
<ThumbnailGenerationTask
>(bitmapWorkerTask
);
124 public ThumbnailGenerationTask
getBitmapWorkerTask() {
125 return bitmapWorkerTaskReference
.get();
129 class ThumbnailGenerationTask
extends AsyncTask
<OCFile
, Void
, Bitmap
> {
130 private final WeakReference
<ImageView
> imageViewReference
;
134 public ThumbnailGenerationTask(ImageView imageView
) {
135 // Use a WeakReference to ensure the ImageView can be garbage collected
136 imageViewReference
= new WeakReference
<ImageView
>(imageView
);
139 // Decode image in background.
141 protected Bitmap
doInBackground(OCFile
... params
) {
143 final String imageKey
= String
.valueOf(file
.getRemoteId());
145 // Check disk cache in background thread
146 Bitmap thumbnail
= getBitmapFromDiskCache(imageKey
);
148 // Not found in disk cache
149 if (thumbnail
== null
) {
150 // Converts dp to pixel
151 Resources r
= mContext
.getResources();
152 int px
= (int) Math
.round(TypedValue
.applyDimension(
153 TypedValue
.COMPLEX_UNIT_DIP
, 150, r
.getDisplayMetrics()
157 Bitmap bitmap
= BitmapUtils
.decodeSampledBitmapFromFile(
158 file
.getStoragePath(), px
, px
);
160 if (bitmap
!= null
) {
161 thumbnail
= ThumbnailUtils
.extractThumbnail(bitmap
, px
, px
);
163 // Add thumbnail to cache
164 addBitmapToCache(imageKey
, thumbnail
);
168 // Download thumbnail from server
169 // Commented out as maybe changes to client library are needed
170 // DefaultHttpClient httpclient = new DefaultHttpClient();
172 // httpclient.getCredentialsProvider().setCredentials(
173 // new AuthScope(mClient.getBaseUri().toString().replace("https://", ""), 443),
174 // new UsernamePasswordCredentials(mClient.getCredentials().getUsername(), mClient.getCredentials().getAuthToken()));
177 // HttpGet httpget = new HttpGet(mClient.getBaseUri() + "/ocs/v1.php/thumbnail?x=50&y=50&path=" + URLEncoder.encode(file.getRemotePath(), "UTF-8"));
178 // HttpResponse response = httpclient.execute(httpget);
179 // HttpEntity entity = response.getEntity();
181 // if (entity != null) {
182 // byte[] bytes = EntityUtils.toByteArray(entity);
183 // Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
184 // thumbnail = ThumbnailUtils.extractThumbnail(bitmap, px, px);
186 // // Add thumbnail to cache
187 // if (thumbnail != null){
188 // addBitmapToCache(imageKey, thumbnail);
191 // } catch(Exception e){
192 // e.printStackTrace();
194 // httpclient.getConnectionManager().shutdown();
201 protected void onPostExecute(Bitmap bitmap
){
206 if (imageViewReference
!= null
&& bitmap
!= null
) {
207 final ImageView imageView
= imageViewReference
.get();
208 final ThumbnailGenerationTask bitmapWorkerTask
=
209 getBitmapWorkerTask(imageView
);
210 if (this == bitmapWorkerTask
&& imageView
!= null
) {
211 imageView
.setImageBitmap(bitmap
);
217 public void addBitmapToCache(String key
, Bitmap bitmap
) {
218 synchronized (thumbnailDiskCacheLock
) {
219 if (mThumbnailCache
!= null
&& mThumbnailCache
.getBitmap(key
) == null
) {
220 mThumbnailCache
.put(key
, bitmap
);
225 public Bitmap
getBitmapFromDiskCache(String key
) {
226 synchronized (thumbnailDiskCacheLock
) {
227 // Wait while disk cache is started from background thread
228 while (mThumbnailCacheStarting
) {
230 thumbnailDiskCacheLock
.wait();
231 } catch (InterruptedException e
) {}
233 if (mThumbnailCache
!= null
) {
234 return (Bitmap
) mThumbnailCache
.getBitmap(key
);
241 public boolean areAllItemsEnabled() {
246 public boolean isEnabled(int position
) {
251 public int getCount() {
252 return mFiles
!= null ? mFiles
.size() : 0;
256 public Object
getItem(int position
) {
257 if (mFiles
== null
|| mFiles
.size() <= position
)
259 return mFiles
.get(position
);
263 public long getItemId(int position
) {
264 if (mFiles
== null
|| mFiles
.size() <= position
)
266 return mFiles
.get(position
).getFileId();
270 public int getItemViewType(int position
) {
275 public View
getView(int position
, View convertView
, ViewGroup parent
) {
276 View view
= convertView
;
278 LayoutInflater inflator
= (LayoutInflater
) mContext
279 .getSystemService(Context
.LAYOUT_INFLATER_SERVICE
);
280 view
= inflator
.inflate(R
.layout
.list_item
, null
);
283 if (mFiles
!= null
&& mFiles
.size() > position
) {
284 OCFile file
= mFiles
.get(position
);
285 TextView fileName
= (TextView
) view
.findViewById(R
.id
.Filename
);
286 String name
= file
.getFileName();
288 fileName
.setText(name
);
289 ImageView fileIcon
= (ImageView
) view
.findViewById(R
.id
.imageView1
);
290 ImageView sharedIconV
= (ImageView
) view
.findViewById(R
.id
.sharedIcon
);
291 ImageView sharedWithMeIconV
= (ImageView
) view
.findViewById(R
.id
.sharedWithMeIcon
);
292 sharedWithMeIconV
.setVisibility(View
.GONE
);
294 ImageView localStateView
= (ImageView
) view
.findViewById(R
.id
.imageView2
);
295 localStateView
.bringToFront();
296 FileDownloaderBinder downloaderBinder
=
297 mTransferServiceGetter
.getFileDownloaderBinder();
298 FileUploaderBinder uploaderBinder
= mTransferServiceGetter
.getFileUploaderBinder();
299 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, file
)) {
300 localStateView
.setImageResource(R
.drawable
.downloading_file_indicator
);
301 localStateView
.setVisibility(View
.VISIBLE
);
302 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, file
)) {
303 localStateView
.setImageResource(R
.drawable
.uploading_file_indicator
);
304 localStateView
.setVisibility(View
.VISIBLE
);
305 } else if (file
.isDown()) {
306 localStateView
.setImageResource(R
.drawable
.local_file_indicator
);
307 localStateView
.setVisibility(View
.VISIBLE
);
309 localStateView
.setVisibility(View
.INVISIBLE
);
312 TextView fileSizeV
= (TextView
) view
.findViewById(R
.id
.file_size
);
313 TextView lastModV
= (TextView
) view
.findViewById(R
.id
.last_mod
);
314 ImageView checkBoxV
= (ImageView
) view
.findViewById(R
.id
.custom_checkbox
);
316 if (!file
.isFolder()) {
317 fileSizeV
.setVisibility(View
.VISIBLE
);
318 fileSizeV
.setText(DisplayUtils
.bytesToHumanReadable(file
.getFileLength()));
319 lastModV
.setVisibility(View
.VISIBLE
);
321 DisplayUtils
.unixTimeToHumanReadable(file
.getModificationTimestamp())
323 // this if-else is needed even thoe fav icon is visible by default
324 // because android reuses views in listview
325 if (!file
.keepInSync()) {
326 view
.findViewById(R
.id
.imageView3
).setVisibility(View
.GONE
);
328 view
.findViewById(R
.id
.imageView3
).setVisibility(View
.VISIBLE
);
331 ListView parentList
= (ListView
)parent
;
332 if (parentList
.getChoiceMode() == ListView
.CHOICE_MODE_NONE
) {
333 checkBoxV
.setVisibility(View
.GONE
);
335 if (parentList
.isItemChecked(position
)) {
336 checkBoxV
.setImageResource(android
.R
.drawable
.checkbox_on_background
);
338 checkBoxV
.setImageResource(android
.R
.drawable
.checkbox_off_background
);
340 checkBoxV
.setVisibility(View
.VISIBLE
);
343 // get Thumbnail if file is image
345 // Thumbnail in Cache?
346 Bitmap thumbnail
= getBitmapFromDiskCache(String
.valueOf(file
.getRemoteId()));
347 if (thumbnail
!= null
){
348 fileIcon
.setImageBitmap(thumbnail
);
350 // generate new Thumbnail
351 if (cancelPotentialWork(file
, fileIcon
)) {
352 final ThumbnailGenerationTask task
=
353 new ThumbnailGenerationTask(fileIcon
);
354 final AsyncDrawable asyncDrawable
=
355 new AsyncDrawable(mContext
.getResources(), defaultImg
, task
);
356 fileIcon
.setImageDrawable(asyncDrawable
);
361 fileIcon
.setImageResource(
362 DisplayUtils
.getResourceId(file
.getMimetype(), file
.getFileName())
366 if (checkIfFileIsSharedWithMe(file
)) {
367 sharedWithMeIconV
.setVisibility(View
.VISIBLE
);
371 fileSizeV
.setVisibility(View
.INVISIBLE
);
372 //fileSizeV.setText(DisplayUtils.bytesToHumanReadable(file.getFileLength()));
373 lastModV
.setVisibility(View
.VISIBLE
);
375 DisplayUtils
.unixTimeToHumanReadable(file
.getModificationTimestamp())
377 checkBoxV
.setVisibility(View
.GONE
);
378 view
.findViewById(R
.id
.imageView3
).setVisibility(View
.GONE
);
380 if (checkIfFileIsSharedWithMe(file
)) {
381 fileIcon
.setImageResource(R
.drawable
.shared_with_me_folder
);
382 sharedWithMeIconV
.setVisibility(View
.VISIBLE
);
384 fileIcon
.setImageResource(
385 DisplayUtils
.getResourceId(file
.getMimetype(), file
.getFileName())
389 // If folder is sharedByLink, icon folder must be changed to
391 if (file
.isShareByLink()) {
392 fileIcon
.setImageResource(R
.drawable
.folder_public
);
396 if (file
.isShareByLink()) {
397 sharedIconV
.setVisibility(View
.VISIBLE
);
399 sharedIconV
.setVisibility(View
.GONE
);
406 public static boolean cancelPotentialWork(OCFile file
, ImageView imageView
) {
407 final ThumbnailGenerationTask bitmapWorkerTask
= getBitmapWorkerTask(imageView
);
409 if (bitmapWorkerTask
!= null
) {
410 final OCFile bitmapData
= bitmapWorkerTask
.file
;
411 // If bitmapData is not yet set or it differs from the new data
412 if (bitmapData
== null
|| bitmapData
!= file
) {
413 // Cancel previous task
414 bitmapWorkerTask
.cancel(true
);
416 // The same work is already in progress
420 // No task associated with the ImageView, or an existing task was cancelled
424 private static ThumbnailGenerationTask
getBitmapWorkerTask(ImageView imageView
) {
425 if (imageView
!= null
) {
426 final Drawable drawable
= imageView
.getDrawable();
427 if (drawable
instanceof AsyncDrawable
) {
428 final AsyncDrawable asyncDrawable
= (AsyncDrawable
) drawable
;
429 return asyncDrawable
.getBitmapWorkerTask();
436 public int getViewTypeCount() {
441 public boolean hasStableIds() {
446 public boolean isEmpty() {
447 return (mFiles
== null
|| mFiles
.isEmpty());
451 * Change the adapted directory for a new one
452 * @param directory New file to adapt. Can be NULL, meaning
453 * "no content to adapt".
454 * @param updatedStorageManager Optional updated storage manager; used to replace
455 * mStorageManager if is different (and not NULL)
457 public void swapDirectory(OCFile directory
, FileDataStorageManager updatedStorageManager
) {
459 if (updatedStorageManager
!= null
&& updatedStorageManager
!= mStorageManager
) {
460 mStorageManager
= updatedStorageManager
;
461 mAccount
= AccountUtils
.getCurrentOwnCloudAccount(mContext
);
463 if (mStorageManager
!= null
) {
464 mFiles
= mStorageManager
.getFolderContent(mFile
);
466 mFiles
= getFolders(mFiles
);
471 notifyDataSetChanged();
476 * Filter for getting only the folders
478 * @return Vector<OCFile>
480 public Vector
<OCFile
> getFolders(Vector
<OCFile
> files
) {
481 Vector
<OCFile
> ret
= new Vector
<OCFile
>();
482 OCFile current
= null
;
483 for (int i
=0; i
<files
.size(); i
++) {
484 current
= files
.get(i
);
485 if (current
.isFolder()) {
494 * Check if parent folder does not include 'S' permission and if file/folder
497 * @param file: OCFile
498 * @return boolean: True if it is shared with me and false if it is not
500 private boolean checkIfFileIsSharedWithMe(OCFile file
) {
501 return (mFile
.getPermissions() != null
502 && !mFile
.getPermissions().contains(PERMISSION_SHARED_WITH_ME
)
503 && file
.getPermissions() != null
504 && file
.getPermissions().contains(PERMISSION_SHARED_WITH_ME
));