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
.Canvas
;
37 import android
.graphics
.drawable
.BitmapDrawable
;
38 import android
.graphics
.drawable
.ColorDrawable
;
39 import android
.graphics
.drawable
.Drawable
;
40 import android
.media
.ThumbnailUtils
;
41 import android
.net
.Uri
;
42 import android
.os
.AsyncTask
;
43 import android
.widget
.ImageView
;
45 import com
.owncloud
.android
.MainApp
;
46 import com
.owncloud
.android
.R
;
47 import com
.owncloud
.android
.authentication
.AccountUtils
;
48 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
49 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
50 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
51 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
52 import com
.owncloud
.android
.lib
.resources
.status
.OwnCloudVersion
;
53 import com
.owncloud
.android
.ui
.adapter
.DiskLruImageCache
;
54 import com
.owncloud
.android
.utils
.BitmapUtils
;
55 import com
.owncloud
.android
.utils
.DisplayUtils
;
58 * Manager for concurrent access to thumbnails cache.
60 public class ThumbnailsCacheManager
{
62 private static final String TAG
= ThumbnailsCacheManager
.class.getSimpleName();
64 private static final String CACHE_FOLDER
= "thumbnailCache";
66 private static final Object mThumbnailsDiskCacheLock
= new Object();
67 private static DiskLruImageCache mThumbnailCache
= null
;
68 private static boolean mThumbnailCacheStarting
= true
;
70 private static final int DISK_CACHE_SIZE
= 1024 * 1024 * 10; // 10MB
71 private static final CompressFormat mCompressFormat
= CompressFormat
.JPEG
;
72 private static final int mCompressQuality
= 70;
73 private static OwnCloudClient mClient
= null
;
75 public static Bitmap mDefaultImg
=
76 BitmapFactory
.decodeResource(
77 MainApp
.getAppContext().getResources(),
82 public static class InitDiskCacheTask
extends AsyncTask
<File
, Void
, Void
> {
85 protected Void
doInBackground(File
... params
) {
86 synchronized (mThumbnailsDiskCacheLock
) {
87 mThumbnailCacheStarting
= true
;
89 if (mThumbnailCache
== null
) {
91 // Check if media is mounted or storage is built-in, if so,
92 // try and use external cache dir; otherwise use internal cache dir
93 final String cachePath
=
94 MainApp
.getAppContext().getExternalCacheDir().getPath() +
95 File
.separator
+ CACHE_FOLDER
;
96 Log_OC
.d(TAG
, "create dir: " + cachePath
);
97 final File diskCacheDir
= new File(cachePath
);
98 mThumbnailCache
= new DiskLruImageCache(
104 } catch (Exception e
) {
105 Log_OC
.d(TAG
, "Thumbnail cache could not be opened ", e
);
106 mThumbnailCache
= null
;
109 mThumbnailCacheStarting
= false
; // Finished initialization
110 mThumbnailsDiskCacheLock
.notifyAll(); // Wake any waiting threads
117 public static void addBitmapToCache(String key
, Bitmap bitmap
) {
118 synchronized (mThumbnailsDiskCacheLock
) {
119 if (mThumbnailCache
!= null
) {
120 mThumbnailCache
.put(key
, bitmap
);
126 public static Bitmap
getBitmapFromDiskCache(String key
) {
127 synchronized (mThumbnailsDiskCacheLock
) {
128 // Wait while disk cache is started from background thread
129 while (mThumbnailCacheStarting
) {
131 mThumbnailsDiskCacheLock
.wait();
132 } catch (InterruptedException e
) {
133 Log_OC
.e(TAG
, "Wait in mThumbnailsDiskCacheLock was interrupted", e
);
136 if (mThumbnailCache
!= null
) {
137 return mThumbnailCache
.getBitmap(key
);
144 * Sets max size of cache
145 * @param maxSize in MB
148 public static boolean setMaxSize(long maxSize
){
149 if (mThumbnailCache
!= null
){
150 mThumbnailCache
.setMaxSize(maxSize
* 1024 * 1024);
157 public static class ThumbnailGenerationTask
extends AsyncTask
<Object
, Void
, Bitmap
> {
158 private final WeakReference
<ImageView
> mImageViewReference
;
159 private static Account mAccount
;
160 private Object mFile
;
161 private FileDataStorageManager mStorageManager
;
164 public ThumbnailGenerationTask(ImageView imageView
, FileDataStorageManager storageManager
,
166 // Use a WeakReference to ensure the ImageView can be garbage collected
167 mImageViewReference
= new WeakReference
<ImageView
>(imageView
);
168 if (storageManager
== null
)
169 throw new IllegalArgumentException("storageManager must not be NULL");
170 mStorageManager
= storageManager
;
174 public ThumbnailGenerationTask(ImageView imageView
) {
175 // Use a WeakReference to ensure the ImageView can be garbage collected
176 mImageViewReference
= new WeakReference
<ImageView
>(imageView
);
180 protected Bitmap
doInBackground(Object
... params
) {
181 Bitmap thumbnail
= null
;
184 if (mAccount
!= null
) {
185 OwnCloudAccount ocAccount
= new OwnCloudAccount(mAccount
,
186 MainApp
.getAppContext());
187 mClient
= OwnCloudClientManagerFactory
.getDefaultSingleton().
188 getClientFor(ocAccount
, MainApp
.getAppContext());
193 if (mFile
instanceof OCFile
) {
194 thumbnail
= doOCFileInBackground();
195 } else if (mFile
instanceof File
) {
196 thumbnail
= doFileInBackground();
197 //} else { do nothing
201 // the app should never break due to a problem with thumbnails
202 Log_OC
.e(TAG
, "Generation of thumbnail for " + mFile
+ " failed", t
);
203 if (t
instanceof OutOfMemoryError
) {
211 protected void onPostExecute(Bitmap bitmap
){
212 if (bitmap
!= null
) {
213 final ImageView imageView
= mImageViewReference
.get();
214 final ThumbnailGenerationTask bitmapWorkerTask
= getBitmapWorkerTask(imageView
);
215 if (this == bitmapWorkerTask
) {
217 if (mFile
instanceof OCFile
){
218 tagId
= String
.valueOf(((OCFile
)mFile
).getFileId());
219 } else if (mFile
instanceof File
){
220 tagId
= String
.valueOf(mFile
.hashCode());
222 if (String
.valueOf(imageView
.getTag()).equals(tagId
)) {
223 imageView
.setImageBitmap(bitmap
);
230 * Add thumbnail to cache
231 * @param imageKey: thumb key
232 * @param bitmap: image for extracting thumbnail
233 * @param path: image path
234 * @param px: thumbnail dp
237 private Bitmap
addThumbnailToCache(String imageKey
, Bitmap bitmap
, String path
, int px
){
239 Bitmap thumbnail
= ThumbnailUtils
.extractThumbnail(bitmap
, px
, px
);
241 // Rotate image, obeying exif tag
242 thumbnail
= BitmapUtils
.rotateImage(thumbnail
,path
);
244 // Add thumbnail to cache
245 addBitmapToCache(imageKey
, thumbnail
);
251 * Converts size of file icon from dp to pixel
254 private int getThumbnailDimension(){
255 // Converts dp to pixel
256 Resources r
= MainApp
.getAppContext().getResources();
257 return Math
.round(r
.getDimension(R
.dimen
.file_icon_size_grid
));
260 private Bitmap
doOCFileInBackground() {
261 OCFile file
= (OCFile
)mFile
;
263 final String imageKey
= String
.valueOf(file
.getRemoteId());
265 // Check disk cache in background thread
266 Bitmap thumbnail
= getBitmapFromDiskCache(imageKey
);
268 // Not found in disk cache
269 if (thumbnail
== null
|| file
.needsUpdateThumbnail()) {
271 int px
= getThumbnailDimension();
274 Bitmap temp
= BitmapUtils
.decodeSampledBitmapFromFile(
275 file
.getStoragePath(), px
, px
);
276 Bitmap bitmap
= ThumbnailUtils
.extractThumbnail(temp
, px
, px
);
278 if (bitmap
!= null
) {
280 if (file
.getMimetype().equalsIgnoreCase("image/png")) {
281 bitmap
= handlePNG(bitmap
, px
);
284 thumbnail
= addThumbnailToCache(imageKey
, bitmap
, file
.getStoragePath(), px
);
286 file
.setNeedsUpdateThumbnail(false
);
287 mStorageManager
.saveFile(file
);
291 // Download thumbnail from server
292 OwnCloudVersion serverOCVersion
= AccountUtils
.getServerVersion(mAccount
);
293 if (mClient
!= null
&& serverOCVersion
!= null
) {
294 if (serverOCVersion
.supportsRemoteThumbnails()) {
296 String uri
= mClient
.getBaseUri() + "" +
297 "/index.php/apps/files/api/v1/thumbnail/" +
298 px
+ "/" + px
+ Uri
.encode(file
.getRemotePath(), "/");
299 Log_OC
.d("Thumbnail", "URI: " + uri
);
300 GetMethod get
= new GetMethod(uri
);
301 int status
= mClient
.executeMethod(get
);
302 if (status
== HttpStatus
.SC_OK
) {
303 InputStream inputStream
= get
.getResponseBodyAsStream();
304 Bitmap bitmap
= BitmapFactory
.decodeStream(inputStream
);
305 thumbnail
= ThumbnailUtils
.extractThumbnail(bitmap
, px
, px
);
308 if (file
.getMimetype().equalsIgnoreCase("image/png")) {
309 thumbnail
= handlePNG(thumbnail
, px
);
312 // Add thumbnail to cache
313 if (thumbnail
!= null
) {
314 addBitmapToCache(imageKey
, thumbnail
);
317 } catch (Exception e
) {
321 Log_OC
.d(TAG
, "Server too old");
331 private Bitmap
handlePNG(Bitmap bitmap
, int px
){
332 Bitmap resultBitmap
= Bitmap
.createBitmap(px
,
334 Bitmap
.Config
.ARGB_8888
);
335 Canvas c
= new Canvas(resultBitmap
);
337 c
.drawColor(MainApp
.getAppContext().getResources().
338 getColor(R
.color
.background_color
));
339 c
.drawBitmap(bitmap
, 0, 0, null
);
344 private Bitmap
doFileInBackground() {
345 File file
= (File
)mFile
;
347 final String imageKey
= String
.valueOf(file
.hashCode());
349 // Check disk cache in background thread
350 Bitmap thumbnail
= getBitmapFromDiskCache(imageKey
);
352 // Not found in disk cache
353 if (thumbnail
== null
) {
355 int px
= getThumbnailDimension();
357 Bitmap bitmap
= BitmapUtils
.decodeSampledBitmapFromFile(
358 file
.getAbsolutePath(), px
, px
);
360 if (bitmap
!= null
) {
361 thumbnail
= addThumbnailToCache(imageKey
, bitmap
, file
.getPath(), px
);
369 public static boolean cancelPotentialWork(Object file
, ImageView imageView
) {
370 final ThumbnailGenerationTask bitmapWorkerTask
= getBitmapWorkerTask(imageView
);
372 if (bitmapWorkerTask
!= null
) {
373 final Object bitmapData
= bitmapWorkerTask
.mFile
;
374 // If bitmapData is not yet set or it differs from the new data
375 if (bitmapData
== null
|| bitmapData
!= file
) {
376 // Cancel previous task
377 bitmapWorkerTask
.cancel(true
);
378 Log_OC
.v(TAG
, "Cancelled generation of thumbnail for a reused imageView");
380 // The same work is already in progress
384 // No task associated with the ImageView, or an existing task was cancelled
388 public static ThumbnailGenerationTask
getBitmapWorkerTask(ImageView imageView
) {
389 if (imageView
!= null
) {
390 final Drawable drawable
= imageView
.getDrawable();
391 if (drawable
instanceof AsyncDrawable
) {
392 final AsyncDrawable asyncDrawable
= (AsyncDrawable
) drawable
;
393 return asyncDrawable
.getBitmapWorkerTask();
399 public static class AsyncDrawable
extends BitmapDrawable
{
400 private final WeakReference
<ThumbnailGenerationTask
> bitmapWorkerTaskReference
;
402 public AsyncDrawable(
403 Resources res
, Bitmap bitmap
, ThumbnailGenerationTask bitmapWorkerTask
407 bitmapWorkerTaskReference
=
408 new WeakReference
<ThumbnailGenerationTask
>(bitmapWorkerTask
);
411 public ThumbnailGenerationTask
getBitmapWorkerTask() {
412 return bitmapWorkerTaskReference
.get();