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
.io
.IOException
;
22 import java
.lang
.ref
.WeakReference
;
23 //import java.net.URLEncoder;
24 import java
.util
.Vector
;
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
;
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
;
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;
73 * This Adapter populates a ListView with all files and folders in an ownCloud
76 * @author Bartek Przybylski
77 * @Author Tobias Kaminsky
80 public class FileListListAdapter
extends BaseAdapter
implements ListAdapter
{
81 private final static String PERMISSION_SHARED_WITH_ME
= "S";
83 private Context mContext
;
84 private OCFile mFile
= null
;
85 private Vector
<OCFile
> mFiles
= null
;
86 private boolean mJustFolders
;
88 private FileDataStorageManager mStorageManager
;
89 private Account mAccount
;
90 private ComponentsGetter mTransferServiceGetter
;
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
;
100 public FileListListAdapter(
103 ComponentsGetter transferServiceGetter
106 mJustFolders
= justFolders
;
108 mAccount
= AccountUtils
.getCurrentOwnCloudAccount(mContext
);
109 mTransferServiceGetter
= transferServiceGetter
;
110 defaultImg
= BitmapFactory
.decodeResource(mContext
.getResources(),
111 DisplayUtils
.getResourceId("image/png", "default.png"));
113 // Initialise disk cache on background thread
114 new InitDiskCacheTask().execute();
117 class InitDiskCacheTask
extends AsyncTask
<File
, Void
, Void
> {
119 protected Void
doInBackground(File
... params
) {
120 synchronized (thumbnailDiskCacheLock
) {
121 mThumbnailCache
= new DiskLruImageCache(mContext
, "thumbnailCache",
122 DISK_CACHE_SIZE
, mCompressFormat
, mCompressQuality
);
124 mThumbnailCacheStarting
= false
; // Finished initialization
125 thumbnailDiskCacheLock
.notifyAll(); // Wake any waiting threads
131 static class AsyncDrawable
extends BitmapDrawable
{
132 private final WeakReference
<ThumbnailGenerationTask
> bitmapWorkerTaskReference
;
134 public AsyncDrawable(Resources res
, Bitmap bitmap
,
135 ThumbnailGenerationTask bitmapWorkerTask
) {
137 bitmapWorkerTaskReference
=
138 new WeakReference
<ThumbnailGenerationTask
>(bitmapWorkerTask
);
141 public ThumbnailGenerationTask
getBitmapWorkerTask() {
142 return bitmapWorkerTaskReference
.get();
146 class ThumbnailGenerationTask
extends AsyncTask
<OCFile
, Void
, Bitmap
> {
147 private final WeakReference
<ImageView
> imageViewReference
;
151 public ThumbnailGenerationTask(ImageView imageView
) {
152 // Use a WeakReference to ensure the ImageView can be garbage collected
153 imageViewReference
= new WeakReference
<ImageView
>(imageView
);
156 // Decode image in background.
158 protected Bitmap
doInBackground(OCFile
... params
) {
160 final String imageKey
= String
.valueOf(file
.getRemoteId());
162 // Check disk cache in background thread
163 Bitmap thumbnail
= getBitmapFromDiskCache(imageKey
);
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()
174 Bitmap bitmap
= BitmapFactory
.decodeFile(file
.getStoragePath());
175 thumbnail
= ThumbnailUtils
.extractThumbnail(bitmap
, px
, px
);
177 // Add thumbnail to cache
178 addBitmapToCache(imageKey
, thumbnail
);
181 // Download thumbnail from server
182 // Commented out as maybe changes to client library are needed
183 // DefaultHttpClient httpclient = new DefaultHttpClient();
185 // httpclient.getCredentialsProvider().setCredentials(
186 // new AuthScope(mClient.getBaseUri().toString().replace("https://", ""), 443),
187 // new UsernamePasswordCredentials(mClient.getCredentials().getUsername(), mClient.getCredentials().getAuthToken()));
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();
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);
199 // // Add thumbnail to cache
200 // if (thumbnail != null){
201 // addBitmapToCache(imageKey, thumbnail);
204 // } catch(Exception e){
205 // e.printStackTrace();
207 // httpclient.getConnectionManager().shutdown();
214 protected void onPostExecute(Bitmap bitmap
){
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
);
230 public void addBitmapToCache(String key
, Bitmap bitmap
) {
231 synchronized (thumbnailDiskCacheLock
) {
232 if (mThumbnailCache
!= null
&& mThumbnailCache
.getBitmap(key
) == null
) {
233 mThumbnailCache
.put(key
, bitmap
);
238 public Bitmap
getBitmapFromDiskCache(String key
) {
239 synchronized (thumbnailDiskCacheLock
) {
240 // Wait while disk cache is started from background thread
241 while (mThumbnailCacheStarting
) {
243 thumbnailDiskCacheLock
.wait();
244 } catch (InterruptedException e
) {}
246 if (mThumbnailCache
!= null
) {
247 return (Bitmap
) mThumbnailCache
.getBitmap(key
);
254 public boolean areAllItemsEnabled() {
259 public boolean isEnabled(int position
) {
264 public int getCount() {
265 return mFiles
!= null ? mFiles
.size() : 0;
269 public Object
getItem(int position
) {
270 if (mFiles
== null
|| mFiles
.size() <= position
)
272 return mFiles
.get(position
);
276 public long getItemId(int position
) {
277 if (mFiles
== null
|| mFiles
.size() <= position
)
279 return mFiles
.get(position
).getFileId();
283 public int getItemViewType(int position
) {
288 public View
getView(int position
, View convertView
, ViewGroup parent
) {
289 View view
= convertView
;
291 LayoutInflater inflator
= (LayoutInflater
) mContext
292 .getSystemService(Context
.LAYOUT_INFLATER_SERVICE
);
293 view
= inflator
.inflate(R
.layout
.list_item
, null
);
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();
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
);
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
);
322 localStateView
.setVisibility(View
.INVISIBLE
);
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
);
329 if (!file
.isFolder()) {
330 fileSizeV
.setVisibility(View
.VISIBLE
);
331 fileSizeV
.setText(DisplayUtils
.bytesToHumanReadable(file
.getFileLength()));
332 lastModV
.setVisibility(View
.VISIBLE
);
334 DisplayUtils
.unixTimeToHumanReadable(file
.getModificationTimestamp())
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
);
341 view
.findViewById(R
.id
.imageView3
).setVisibility(View
.VISIBLE
);
344 ListView parentList
= (ListView
)parent
;
345 if (parentList
.getChoiceMode() == ListView
.CHOICE_MODE_NONE
) {
346 checkBoxV
.setVisibility(View
.GONE
);
348 if (parentList
.isItemChecked(position
)) {
349 checkBoxV
.setImageResource(android
.R
.drawable
.checkbox_on_background
);
351 checkBoxV
.setImageResource(android
.R
.drawable
.checkbox_off_background
);
353 checkBoxV
.setVisibility(View
.VISIBLE
);
356 // get Thumbnail if file is image
358 // Thumbnail in Cache?
359 Bitmap thumbnail
= getBitmapFromDiskCache(String
.valueOf(file
.getRemoteId()));
360 if (thumbnail
!= null
){
361 fileIcon
.setImageBitmap(thumbnail
);
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
);
374 fileIcon
.setImageResource(
375 DisplayUtils
.getResourceId(file
.getMimetype(), file
.getFileName())
379 if (checkIfFileIsSharedWithMe(file
)) {
380 sharedWithMeIconV
.setVisibility(View
.VISIBLE
);
384 fileSizeV
.setVisibility(View
.INVISIBLE
);
385 //fileSizeV.setText(DisplayUtils.bytesToHumanReadable(file.getFileLength()));
386 lastModV
.setVisibility(View
.VISIBLE
);
388 DisplayUtils
.unixTimeToHumanReadable(file
.getModificationTimestamp())
390 checkBoxV
.setVisibility(View
.GONE
);
391 view
.findViewById(R
.id
.imageView3
).setVisibility(View
.GONE
);
393 if (checkIfFileIsSharedWithMe(file
)) {
394 fileIcon
.setImageResource(R
.drawable
.shared_with_me_folder
);
395 sharedWithMeIconV
.setVisibility(View
.VISIBLE
);
397 fileIcon
.setImageResource(
398 DisplayUtils
.getResourceId(file
.getMimetype(), file
.getFileName())
402 // If folder is sharedByLink, icon folder must be changed to
404 if (file
.isShareByLink()) {
405 fileIcon
.setImageResource(R
.drawable
.folder_public
);
409 if (file
.isShareByLink()) {
410 sharedIconV
.setVisibility(View
.VISIBLE
);
412 sharedIconV
.setVisibility(View
.GONE
);
419 public static boolean cancelPotentialWork(OCFile file
, ImageView imageView
) {
420 final ThumbnailGenerationTask bitmapWorkerTask
= getBitmapWorkerTask(imageView
);
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
);
429 // The same work is already in progress
433 // No task associated with the ImageView, or an existing task was cancelled
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();
449 public int getViewTypeCount() {
454 public boolean hasStableIds() {
459 public boolean isEmpty() {
460 return (mFiles
== null
|| mFiles
.isEmpty());
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)
470 public void swapDirectory(OCFile directory
, FileDataStorageManager updatedStorageManager
) {
472 if (updatedStorageManager
!= null
&& updatedStorageManager
!= mStorageManager
) {
473 mStorageManager
= updatedStorageManager
;
474 mAccount
= AccountUtils
.getCurrentOwnCloudAccount(mContext
);
476 if (mStorageManager
!= null
) {
477 mFiles
= mStorageManager
.getFolderContent(mFile
);
479 mFiles
= getFolders(mFiles
);
484 notifyDataSetChanged();
489 * Filter for getting only the folders
491 * @return Vector<OCFile>
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()) {
507 * Check if parent folder does not include 'S' permission and if file/folder
510 * @param file: OCFile
511 * @return boolean: True if it is shared with me and false if it is not
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
));