Merge branch 'master' of https://github.com/owncloud/android into material_buttons
[pub/Android/ownCloud.git] / src / com / owncloud / android / datamodel / ThumbnailsCacheManager.java
1 /**
2 * ownCloud Android client application
3 *
4 * @author Tobias Kaminsky
5 * @author David A. Velasco
6 * Copyright (C) 2015 ownCloud Inc.
7 *
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.
11 *
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.
16 *
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/>.
19 *
20 */
21
22 package com.owncloud.android.datamodel;
23
24 import java.io.File;
25 import java.io.InputStream;
26 import java.lang.ref.WeakReference;
27
28 import org.apache.commons.httpclient.HttpStatus;
29 import org.apache.commons.httpclient.methods.GetMethod;
30
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;
44
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;
56
57 /**
58 * Manager for concurrent access to thumbnails cache.
59 */
60 public class ThumbnailsCacheManager {
61
62 private static final String TAG = ThumbnailsCacheManager.class.getSimpleName();
63
64 private static final String CACHE_FOLDER = "thumbnailCache";
65
66 private static final Object mThumbnailsDiskCacheLock = new Object();
67 private static DiskLruImageCache mThumbnailCache = null;
68 private static boolean mThumbnailCacheStarting = true;
69
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;
74
75 public static Bitmap mDefaultImg =
76 BitmapFactory.decodeResource(
77 MainApp.getAppContext().getResources(),
78 R.drawable.file_image
79 );
80
81
82 public static class InitDiskCacheTask extends AsyncTask<File, Void, Void> {
83
84 @Override
85 protected Void doInBackground(File... params) {
86 synchronized (mThumbnailsDiskCacheLock) {
87 mThumbnailCacheStarting = true;
88
89 if (mThumbnailCache == null) {
90 try {
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(
99 diskCacheDir,
100 DISK_CACHE_SIZE,
101 mCompressFormat,
102 mCompressQuality
103 );
104 } catch (Exception e) {
105 Log_OC.d(TAG, "Thumbnail cache could not be opened ", e);
106 mThumbnailCache = null;
107 }
108 }
109 mThumbnailCacheStarting = false; // Finished initialization
110 mThumbnailsDiskCacheLock.notifyAll(); // Wake any waiting threads
111 }
112 return null;
113 }
114 }
115
116
117 public static void addBitmapToCache(String key, Bitmap bitmap) {
118 synchronized (mThumbnailsDiskCacheLock) {
119 if (mThumbnailCache != null) {
120 mThumbnailCache.put(key, bitmap);
121 }
122 }
123 }
124
125
126 public static Bitmap getBitmapFromDiskCache(String key) {
127 synchronized (mThumbnailsDiskCacheLock) {
128 // Wait while disk cache is started from background thread
129 while (mThumbnailCacheStarting) {
130 try {
131 mThumbnailsDiskCacheLock.wait();
132 } catch (InterruptedException e) {
133 Log_OC.e(TAG, "Wait in mThumbnailsDiskCacheLock was interrupted", e);
134 }
135 }
136 if (mThumbnailCache != null) {
137 return mThumbnailCache.getBitmap(key);
138 }
139 }
140 return null;
141 }
142
143 public static class ThumbnailGenerationTask extends AsyncTask<Object, Void, Bitmap> {
144 private final WeakReference<ImageView> mImageViewReference;
145 private static Account mAccount;
146 private Object mFile;
147 private FileDataStorageManager mStorageManager;
148
149
150 public ThumbnailGenerationTask(ImageView imageView, FileDataStorageManager storageManager,
151 Account account) {
152 // Use a WeakReference to ensure the ImageView can be garbage collected
153 mImageViewReference = new WeakReference<ImageView>(imageView);
154 if (storageManager == null)
155 throw new IllegalArgumentException("storageManager must not be NULL");
156 mStorageManager = storageManager;
157 mAccount = account;
158 }
159
160 public ThumbnailGenerationTask(ImageView imageView) {
161 // Use a WeakReference to ensure the ImageView can be garbage collected
162 mImageViewReference = new WeakReference<ImageView>(imageView);
163 }
164
165 @Override
166 protected Bitmap doInBackground(Object... params) {
167 Bitmap thumbnail = null;
168
169 try {
170 if (mAccount != null) {
171 OwnCloudAccount ocAccount = new OwnCloudAccount(mAccount,
172 MainApp.getAppContext());
173 mClient = OwnCloudClientManagerFactory.getDefaultSingleton().
174 getClientFor(ocAccount, MainApp.getAppContext());
175 }
176
177 mFile = params[0];
178
179 if (mFile instanceof OCFile) {
180 thumbnail = doOCFileInBackground();
181 } else if (mFile instanceof File) {
182 thumbnail = doFileInBackground();
183 //} else { do nothing
184 }
185
186 }catch(Throwable t){
187 // the app should never break due to a problem with thumbnails
188 Log_OC.e(TAG, "Generation of thumbnail for " + mFile + " failed", t);
189 if (t instanceof OutOfMemoryError) {
190 System.gc();
191 }
192 }
193
194 return thumbnail;
195 }
196
197 protected void onPostExecute(Bitmap bitmap){
198 if (bitmap != null) {
199 final ImageView imageView = mImageViewReference.get();
200 final ThumbnailGenerationTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
201 if (this == bitmapWorkerTask) {
202 String tagId = "";
203 if (mFile instanceof OCFile){
204 tagId = String.valueOf(((OCFile)mFile).getFileId());
205 } else if (mFile instanceof File){
206 tagId = String.valueOf(mFile.hashCode());
207 }
208 if (String.valueOf(imageView.getTag()).equals(tagId)) {
209 imageView.setImageBitmap(bitmap);
210 }
211 }
212 }
213 }
214
215 /**
216 * Add thumbnail to cache
217 * @param imageKey: thumb key
218 * @param bitmap: image for extracting thumbnail
219 * @param path: image path
220 * @param px: thumbnail dp
221 * @return Bitmap
222 */
223 private Bitmap addThumbnailToCache(String imageKey, Bitmap bitmap, String path, int px){
224
225 Bitmap thumbnail = ThumbnailUtils.extractThumbnail(bitmap, px, px);
226
227 // Rotate image, obeying exif tag
228 thumbnail = BitmapUtils.rotateImage(thumbnail,path);
229
230 // Add thumbnail to cache
231 addBitmapToCache(imageKey, thumbnail);
232
233 return thumbnail;
234 }
235
236 /**
237 * Converts size of file icon from dp to pixel
238 * @return int
239 */
240 private int getThumbnailDimension(){
241 // Converts dp to pixel
242 Resources r = MainApp.getAppContext().getResources();
243 return Math.round(r.getDimension(R.dimen.file_icon_size_grid));
244 }
245
246 private Bitmap doOCFileInBackground() {
247 OCFile file = (OCFile)mFile;
248
249 final String imageKey = String.valueOf(file.getRemoteId());
250
251 // Check disk cache in background thread
252 Bitmap thumbnail = getBitmapFromDiskCache(imageKey);
253
254 // Not found in disk cache
255 if (thumbnail == null || file.needsUpdateThumbnail()) {
256
257 int px = getThumbnailDimension();
258
259 if (file.isDown()) {
260 Bitmap temp = BitmapUtils.decodeSampledBitmapFromFile(
261 file.getStoragePath(), px, px);
262 Bitmap bitmap = ThumbnailUtils.extractThumbnail(temp, px, px);
263
264 if (bitmap != null) {
265 // Handle PNG
266 if (file.getMimetype().equalsIgnoreCase("image/png")) {
267 bitmap = handlePNG(bitmap, px);
268 }
269
270 thumbnail = addThumbnailToCache(imageKey, bitmap, file.getStoragePath(), px);
271
272 file.setNeedsUpdateThumbnail(false);
273 mStorageManager.saveFile(file);
274 }
275
276 } else {
277 // Download thumbnail from server
278 OwnCloudVersion serverOCVersion = AccountUtils.getServerVersion(mAccount);
279 if (mClient != null && serverOCVersion != null) {
280 if (serverOCVersion.supportsRemoteThumbnails()) {
281 try {
282 String uri = mClient.getBaseUri() + "" +
283 "/index.php/apps/files/api/v1/thumbnail/" +
284 px + "/" + px + Uri.encode(file.getRemotePath(), "/");
285 Log_OC.d("Thumbnail", "URI: " + uri);
286 GetMethod get = new GetMethod(uri);
287 int status = mClient.executeMethod(get);
288 if (status == HttpStatus.SC_OK) {
289 InputStream inputStream = get.getResponseBodyAsStream();
290 Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
291 thumbnail = ThumbnailUtils.extractThumbnail(bitmap, px, px);
292
293 // Handle PNG
294 if (file.getMimetype().equalsIgnoreCase("image/png")) {
295 thumbnail = handlePNG(thumbnail, px);
296 }
297
298 // Add thumbnail to cache
299 if (thumbnail != null) {
300 addBitmapToCache(imageKey, thumbnail);
301 }
302 }
303 } catch (Exception e) {
304 e.printStackTrace();
305 }
306 } else {
307 Log_OC.d(TAG, "Server too old");
308 }
309 }
310 }
311 }
312
313 return thumbnail;
314
315 }
316
317 private Bitmap handlePNG(Bitmap bitmap, int px){
318 Bitmap resultBitmap = Bitmap.createBitmap(px,
319 px,
320 Bitmap.Config.ARGB_8888);
321 Canvas c = new Canvas(resultBitmap);
322
323 c.drawColor(MainApp.getAppContext().getResources().
324 getColor(R.color.background_color));
325 c.drawBitmap(bitmap, 0, 0, null);
326
327 return resultBitmap;
328 }
329
330 private Bitmap doFileInBackground() {
331 File file = (File)mFile;
332
333 final String imageKey = String.valueOf(file.hashCode());
334
335 // Check disk cache in background thread
336 Bitmap thumbnail = getBitmapFromDiskCache(imageKey);
337
338 // Not found in disk cache
339 if (thumbnail == null) {
340
341 int px = getThumbnailDimension();
342
343 Bitmap bitmap = BitmapUtils.decodeSampledBitmapFromFile(
344 file.getAbsolutePath(), px, px);
345
346 if (bitmap != null) {
347 thumbnail = addThumbnailToCache(imageKey, bitmap, file.getPath(), px);
348 }
349 }
350 return thumbnail;
351 }
352
353 }
354
355 public static boolean cancelPotentialWork(Object file, ImageView imageView) {
356 final ThumbnailGenerationTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
357
358 if (bitmapWorkerTask != null) {
359 final Object bitmapData = bitmapWorkerTask.mFile;
360 // If bitmapData is not yet set or it differs from the new data
361 if (bitmapData == null || bitmapData != file) {
362 // Cancel previous task
363 bitmapWorkerTask.cancel(true);
364 Log_OC.v(TAG, "Cancelled generation of thumbnail for a reused imageView");
365 } else {
366 // The same work is already in progress
367 return false;
368 }
369 }
370 // No task associated with the ImageView, or an existing task was cancelled
371 return true;
372 }
373
374 public static ThumbnailGenerationTask getBitmapWorkerTask(ImageView imageView) {
375 if (imageView != null) {
376 final Drawable drawable = imageView.getDrawable();
377 if (drawable instanceof AsyncDrawable) {
378 final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
379 return asyncDrawable.getBitmapWorkerTask();
380 }
381 }
382 return null;
383 }
384
385 public static class AsyncDrawable extends BitmapDrawable {
386 private final WeakReference<ThumbnailGenerationTask> bitmapWorkerTaskReference;
387
388 public AsyncDrawable(
389 Resources res, Bitmap bitmap, ThumbnailGenerationTask bitmapWorkerTask
390 ) {
391
392 super(res, bitmap);
393 bitmapWorkerTaskReference =
394 new WeakReference<ThumbnailGenerationTask>(bitmapWorkerTask);
395 }
396
397 public ThumbnailGenerationTask getBitmapWorkerTask() {
398 return bitmapWorkerTaskReference.get();
399 }
400 }
401 }