2 * ownCloud Android client application
4 * @author Tobias Kaminsky
5 * @author David A. Velasco
6 * Copyright (C) 2015 ownCloud Inc.
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License version 2,
10 * as published by the Free Software Foundation.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
22 package com
.owncloud
.android
.datamodel
;
25 import java
.io
.InputStream
;
26 import java
.lang
.ref
.WeakReference
;
28 import org
.apache
.commons
.httpclient
.HttpStatus
;
29 import org
.apache
.commons
.httpclient
.methods
.GetMethod
;
31 import android
.accounts
.Account
;
32 import android
.content
.res
.Resources
;
33 import android
.graphics
.Bitmap
;
34 import android
.graphics
.Bitmap
.CompressFormat
;
35 import android
.graphics
.BitmapFactory
;
36 import android
.graphics
.drawable
.BitmapDrawable
;
37 import android
.graphics
.drawable
.Drawable
;
38 import android
.media
.ThumbnailUtils
;
39 import android
.net
.Uri
;
40 import android
.os
.AsyncTask
;
41 import android
.widget
.ImageView
;
43 import com
.owncloud
.android
.MainApp
;
44 import com
.owncloud
.android
.R
;
45 import com
.owncloud
.android
.authentication
.AccountUtils
;
46 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
47 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
48 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
49 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
50 import com
.owncloud
.android
.lib
.resources
.status
.OwnCloudVersion
;
51 import com
.owncloud
.android
.ui
.adapter
.DiskLruImageCache
;
52 import com
.owncloud
.android
.utils
.BitmapUtils
;
53 import com
.owncloud
.android
.utils
.DisplayUtils
;
56 * Manager for concurrent access to thumbnails cache.
58 public class ThumbnailsCacheManager
{
60 private static final String TAG
= ThumbnailsCacheManager
.class.getSimpleName();
62 private static final String CACHE_FOLDER
= "thumbnailCache";
64 private static final Object mThumbnailsDiskCacheLock
= new Object();
65 private static DiskLruImageCache mThumbnailCache
= null
;
66 private static boolean mThumbnailCacheStarting
= true
;
68 private static final int DISK_CACHE_SIZE
= 1024 * 1024 * 10; // 10MB
69 private static final CompressFormat mCompressFormat
= CompressFormat
.JPEG
;
70 private static final int mCompressQuality
= 70;
71 private static OwnCloudClient mClient
= null
;
73 public static Bitmap mDefaultImg
=
74 BitmapFactory
.decodeResource(
75 MainApp
.getAppContext().getResources(),
76 DisplayUtils
.getFileTypeIconId("image/png", "default.png")
80 public static class InitDiskCacheTask
extends AsyncTask
<File
, Void
, Void
> {
83 protected Void
doInBackground(File
... params
) {
84 synchronized (mThumbnailsDiskCacheLock
) {
85 mThumbnailCacheStarting
= true
;
87 if (mThumbnailCache
== null
) {
89 // Check if media is mounted or storage is built-in, if so,
90 // try and use external cache dir; otherwise use internal cache dir
91 final String cachePath
=
92 MainApp
.getAppContext().getExternalCacheDir().getPath() +
93 File
.separator
+ CACHE_FOLDER
;
94 Log_OC
.d(TAG
, "create dir: " + cachePath
);
95 final File diskCacheDir
= new File(cachePath
);
96 mThumbnailCache
= new DiskLruImageCache(
102 } catch (Exception e
) {
103 Log_OC
.d(TAG
, "Thumbnail cache could not be opened ", e
);
104 mThumbnailCache
= null
;
107 mThumbnailCacheStarting
= false
; // Finished initialization
108 mThumbnailsDiskCacheLock
.notifyAll(); // Wake any waiting threads
115 public static void addBitmapToCache(String key
, Bitmap bitmap
) {
116 synchronized (mThumbnailsDiskCacheLock
) {
117 if (mThumbnailCache
!= null
) {
118 mThumbnailCache
.put(key
, bitmap
);
124 public static Bitmap
getBitmapFromDiskCache(String key
) {
125 synchronized (mThumbnailsDiskCacheLock
) {
126 // Wait while disk cache is started from background thread
127 while (mThumbnailCacheStarting
) {
129 mThumbnailsDiskCacheLock
.wait();
130 } catch (InterruptedException e
) {
131 Log_OC
.e(TAG
, "Wait in mThumbnailsDiskCacheLock was interrupted", e
);
134 if (mThumbnailCache
!= null
) {
135 return mThumbnailCache
.getBitmap(key
);
141 public static class ThumbnailGenerationTask
extends AsyncTask
<Object
, Void
, Bitmap
> {
142 private final WeakReference
<ImageView
> mImageViewReference
;
143 private static Account mAccount
;
144 private Object mFile
;
145 private FileDataStorageManager mStorageManager
;
148 public ThumbnailGenerationTask(ImageView imageView
, FileDataStorageManager storageManager
,
150 // Use a WeakReference to ensure the ImageView can be garbage collected
151 mImageViewReference
= new WeakReference
<ImageView
>(imageView
);
152 if (storageManager
== null
)
153 throw new IllegalArgumentException("storageManager must not be NULL");
154 mStorageManager
= storageManager
;
158 public ThumbnailGenerationTask(ImageView imageView
) {
159 // Use a WeakReference to ensure the ImageView can be garbage collected
160 mImageViewReference
= new WeakReference
<ImageView
>(imageView
);
164 protected Bitmap
doInBackground(Object
... params
) {
165 Bitmap thumbnail
= null
;
168 if (mAccount
!= null
) {
169 OwnCloudAccount ocAccount
= new OwnCloudAccount(mAccount
,
170 MainApp
.getAppContext());
171 mClient
= OwnCloudClientManagerFactory
.getDefaultSingleton().
172 getClientFor(ocAccount
, MainApp
.getAppContext());
177 if (mFile
instanceof OCFile
) {
178 thumbnail
= doOCFileInBackground();
179 } else if (mFile
instanceof File
) {
180 thumbnail
= doFileInBackground();
181 //} else { do nothing
185 // the app should never break due to a problem with thumbnails
186 Log_OC
.e(TAG
, "Generation of thumbnail for " + mFile
+ " failed", t
);
187 if (t
instanceof OutOfMemoryError
) {
195 protected void onPostExecute(Bitmap bitmap
){
200 if (bitmap
!= null
) {
201 final ImageView imageView
= mImageViewReference
.get();
202 final ThumbnailGenerationTask bitmapWorkerTask
= getBitmapWorkerTask(imageView
);
203 if (this == bitmapWorkerTask
) {
205 if (mFile
instanceof OCFile
){
206 tagId
= String
.valueOf(((OCFile
)mFile
).getFileId());
207 } else if (mFile
instanceof File
){
208 tagId
= String
.valueOf(mFile
.hashCode());
210 if (String
.valueOf(imageView
.getTag()).equals(tagId
)) {
211 imageView
.setImageBitmap(bitmap
);
218 * Add thumbnail to cache
219 * @param imageKey: thumb key
220 * @param bitmap: image for extracting thumbnail
221 * @param path: image path
222 * @param px: thumbnail dp
225 private Bitmap
addThumbnailToCache(String imageKey
, Bitmap bitmap
, String path
, int px
){
227 Bitmap thumbnail
= ThumbnailUtils
.extractThumbnail(bitmap
, px
, px
);
229 // Rotate image, obeying exif tag
230 thumbnail
= BitmapUtils
.rotateImage(thumbnail
,path
);
232 // Add thumbnail to cache
233 addBitmapToCache(imageKey
, thumbnail
);
239 * Converts size of file icon from dp to pixel
242 private int getThumbnailDimension(){
243 // Converts dp to pixel
244 Resources r
= MainApp
.getAppContext().getResources();
245 return Math
.round(r
.getDimension(R
.dimen
.file_icon_size_grid
));
248 private Bitmap
doOCFileInBackground() {
249 OCFile file
= (OCFile
)mFile
;
251 final String imageKey
= String
.valueOf(file
.getRemoteId());
253 // Check disk cache in background thread
254 Bitmap thumbnail
= getBitmapFromDiskCache(imageKey
);
256 // Not found in disk cache
257 if (thumbnail
== null
|| file
.needsUpdateThumbnail()) {
259 int px
= getThumbnailDimension();
262 Bitmap bitmap
= BitmapUtils
.decodeSampledBitmapFromFile(
263 file
.getStoragePath(), px
, px
);
265 if (bitmap
!= null
) {
266 thumbnail
= addThumbnailToCache(imageKey
, bitmap
, file
.getStoragePath(), px
);
268 file
.setNeedsUpdateThumbnail(false
);
269 mStorageManager
.saveFile(file
);
273 // Download thumbnail from server
274 OwnCloudVersion serverOCVersion
= AccountUtils
.getServerVersion(mAccount
);
275 if (mClient
!= null
&& serverOCVersion
!= null
) {
276 if (serverOCVersion
.supportsRemoteThumbnails()) {
278 String uri
= mClient
.getBaseUri() + "" +
279 "/index.php/apps/files/api/v1/thumbnail/" +
280 px
+ "/" + px
+ Uri
.encode(file
.getRemotePath(), "/");
281 Log_OC
.d("Thumbnail", "URI: " + uri
);
282 GetMethod get
= new GetMethod(uri
);
283 int status
= mClient
.executeMethod(get
);
284 if (status
== HttpStatus
.SC_OK
) {
285 // byte[] bytes = get.getResponseBody();
286 // Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0,
288 InputStream inputStream
= get
.getResponseBodyAsStream();
289 Bitmap bitmap
= BitmapFactory
.decodeStream(inputStream
);
290 thumbnail
= ThumbnailUtils
.extractThumbnail(bitmap
, px
, px
);
292 // Add thumbnail to cache
293 if (thumbnail
!= null
) {
294 addBitmapToCache(imageKey
, thumbnail
);
297 } catch (Exception e
) {
301 Log_OC
.d(TAG
, "Server too old");
311 private Bitmap
doFileInBackground() {
312 File file
= (File
)mFile
;
314 final String imageKey
= String
.valueOf(file
.hashCode());
316 // Check disk cache in background thread
317 Bitmap thumbnail
= getBitmapFromDiskCache(imageKey
);
319 // Not found in disk cache
320 if (thumbnail
== null
) {
322 int px
= getThumbnailDimension();
324 Bitmap bitmap
= BitmapUtils
.decodeSampledBitmapFromFile(
325 file
.getAbsolutePath(), px
, px
);
327 if (bitmap
!= null
) {
328 thumbnail
= addThumbnailToCache(imageKey
, bitmap
, file
.getPath(), px
);
336 public static boolean cancelPotentialWork(Object file
, ImageView imageView
) {
337 final ThumbnailGenerationTask bitmapWorkerTask
= getBitmapWorkerTask(imageView
);
339 if (bitmapWorkerTask
!= null
) {
340 final Object bitmapData
= bitmapWorkerTask
.mFile
;
341 // If bitmapData is not yet set or it differs from the new data
342 if (bitmapData
== null
|| bitmapData
!= file
) {
343 // Cancel previous task
344 bitmapWorkerTask
.cancel(true
);
346 // The same work is already in progress
350 // No task associated with the ImageView, or an existing task was cancelled
354 public static ThumbnailGenerationTask
getBitmapWorkerTask(ImageView imageView
) {
355 if (imageView
!= null
) {
356 final Drawable drawable
= imageView
.getDrawable();
357 if (drawable
instanceof AsyncDrawable
) {
358 final AsyncDrawable asyncDrawable
= (AsyncDrawable
) drawable
;
359 return asyncDrawable
.getBitmapWorkerTask();
365 public static class AsyncDrawable
extends BitmapDrawable
{
366 private final WeakReference
<ThumbnailGenerationTask
> bitmapWorkerTaskReference
;
368 public AsyncDrawable(
369 Resources res
, Bitmap bitmap
, ThumbnailGenerationTask bitmapWorkerTask
373 bitmapWorkerTaskReference
=
374 new WeakReference
<ThumbnailGenerationTask
>(bitmapWorkerTask
);
377 public ThumbnailGenerationTask
getBitmapWorkerTask() {
378 return bitmapWorkerTaskReference
.get();