Merge remote-tracking branch 'remotes/upstream/master' into resizedImagesMaster
[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.accounts.AccountManager;
33 import android.content.Context;
34 import android.content.res.Resources;
35 import android.graphics.Bitmap;
36 import android.graphics.Bitmap.CompressFormat;
37 import android.graphics.BitmapFactory;
38 import android.graphics.Point;
39 import android.graphics.Canvas;
40 import android.graphics.drawable.BitmapDrawable;
41 import android.graphics.drawable.ColorDrawable;
42 import android.graphics.drawable.Drawable;
43 import android.media.ThumbnailUtils;
44 import android.net.Uri;
45 import android.os.AsyncTask;
46 import android.view.Display;
47 import android.view.View;
48 import android.view.WindowManager;
49 import android.widget.ImageView;
50 import android.widget.ProgressBar;
51
52 import com.owncloud.android.MainApp;
53 import com.owncloud.android.R;
54 import com.owncloud.android.authentication.AccountUtils;
55 import com.owncloud.android.lib.common.OwnCloudAccount;
56 import com.owncloud.android.lib.common.OwnCloudClient;
57 import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
58 import com.owncloud.android.lib.common.utils.Log_OC;
59 import com.owncloud.android.lib.resources.status.OwnCloudVersion;
60 import com.owncloud.android.ui.adapter.DiskLruImageCache;
61 import com.owncloud.android.utils.BitmapUtils;
62 import com.owncloud.android.utils.DisplayUtils;
63
64 /**
65 * Manager for concurrent access to thumbnails cache.
66 */
67 public class ThumbnailsCacheManager {
68
69 private static final String TAG = ThumbnailsCacheManager.class.getSimpleName();
70
71 private static final String CACHE_FOLDER = "thumbnailCache";
72
73 private static final Object mThumbnailsDiskCacheLock = new Object();
74 private static DiskLruImageCache mThumbnailCache = null;
75 private static boolean mThumbnailCacheStarting = true;
76
77 private static final int DISK_CACHE_SIZE = 1024 * 1024 * 10; // 10MB
78 private static final CompressFormat mCompressFormat = CompressFormat.JPEG;
79 private static final int mCompressQuality = 70;
80 private static OwnCloudClient mClient = null;
81
82 public static Bitmap mDefaultImg =
83 BitmapFactory.decodeResource(
84 MainApp.getAppContext().getResources(),
85 R.drawable.file_image
86 );
87
88
89 public static class InitDiskCacheTask extends AsyncTask<File, Void, Void> {
90
91 @Override
92 protected Void doInBackground(File... params) {
93 synchronized (mThumbnailsDiskCacheLock) {
94 mThumbnailCacheStarting = true;
95
96 if (mThumbnailCache == null) {
97 try {
98 // Check if media is mounted or storage is built-in, if so,
99 // try and use external cache dir; otherwise use internal cache dir
100 final String cachePath =
101 MainApp.getAppContext().getExternalCacheDir().getPath() +
102 File.separator + CACHE_FOLDER;
103 Log_OC.d(TAG, "create dir: " + cachePath);
104 final File diskCacheDir = new File(cachePath);
105 mThumbnailCache = new DiskLruImageCache(
106 diskCacheDir,
107 DISK_CACHE_SIZE,
108 mCompressFormat,
109 mCompressQuality
110 );
111 } catch (Exception e) {
112 Log_OC.d(TAG, "Thumbnail cache could not be opened ", e);
113 mThumbnailCache = null;
114 }
115 }
116 mThumbnailCacheStarting = false; // Finished initialization
117 mThumbnailsDiskCacheLock.notifyAll(); // Wake any waiting threads
118 }
119 return null;
120 }
121 }
122
123
124 public static void addBitmapToCache(String key, Bitmap bitmap) {
125 synchronized (mThumbnailsDiskCacheLock) {
126 if (mThumbnailCache != null) {
127 mThumbnailCache.put(key, bitmap);
128 }
129 }
130 }
131
132
133 public static Bitmap getBitmapFromDiskCache(String key) {
134 synchronized (mThumbnailsDiskCacheLock) {
135 // Wait while disk cache is started from background thread
136 while (mThumbnailCacheStarting) {
137 try {
138 mThumbnailsDiskCacheLock.wait();
139 } catch (InterruptedException e) {
140 Log_OC.e(TAG, "Wait in mThumbnailsDiskCacheLock was interrupted", e);
141 }
142 }
143 if (mThumbnailCache != null) {
144 return mThumbnailCache.getBitmap(key);
145 }
146 }
147 return null;
148 }
149
150 public static class ThumbnailGenerationTask extends AsyncTask<Object, Void, Bitmap> {
151 private final WeakReference<ImageView> mImageViewReference;
152 private WeakReference<ProgressBar> mProgressWheelRef;
153 private static Account mAccount;
154 private Object mFile;
155 private Boolean mIsThumbnail;
156 private FileDataStorageManager mStorageManager;
157
158 public ThumbnailGenerationTask(ImageView imageView, FileDataStorageManager storageManager,
159 Account account) {
160 // Use a WeakReference to ensure the ImageView can be garbage collected
161 mImageViewReference = new WeakReference<ImageView>(imageView);
162 if (storageManager == null)
163 throw new IllegalArgumentException("storageManager must not be NULL");
164 mStorageManager = storageManager;
165 mAccount = account;
166 }
167
168 public ThumbnailGenerationTask(ImageView imageView, FileDataStorageManager storageManager,
169 Account account, ProgressBar progressWheel) {
170 this(imageView, storageManager, account);
171 mProgressWheelRef = new WeakReference<ProgressBar>(progressWheel);
172 }
173
174 public ThumbnailGenerationTask(ImageView imageView) {
175 // Use a WeakReference to ensure the ImageView can be garbage collected
176 mImageViewReference = new WeakReference<ImageView>(imageView);
177 }
178
179 @Override
180 protected Bitmap doInBackground(Object... params) {
181 Bitmap thumbnail = null;
182
183 try {
184 if (mAccount != null) {
185 OwnCloudAccount ocAccount = new OwnCloudAccount(mAccount,
186 MainApp.getAppContext());
187 mClient = OwnCloudClientManagerFactory.getDefaultSingleton().
188 getClientFor(ocAccount, MainApp.getAppContext());
189 }
190
191 mFile = params[0];
192 mIsThumbnail = (Boolean) params[1];
193
194
195 if (mFile instanceof OCFile) {
196 thumbnail = doOCFileInBackground(mIsThumbnail);
197 } else if (mFile instanceof File) {
198 thumbnail = doFileInBackground(mIsThumbnail);
199 } else {
200 // do nothing
201 }
202
203 }catch(Throwable t){
204 // the app should never break due to a problem with thumbnails
205 Log_OC.e(TAG, "Generation of thumbnail for " + mFile + " failed", t);
206 if (t instanceof OutOfMemoryError) {
207 System.gc();
208 }
209 }
210
211 return thumbnail;
212 }
213
214 protected void onPostExecute(Bitmap bitmap){
215 if (bitmap != null) {
216 final ImageView imageView = mImageViewReference.get();
217 final ThumbnailGenerationTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
218 if (this == bitmapWorkerTask) {
219 String tagId = "";
220 if (mFile instanceof OCFile){
221 tagId = String.valueOf(((OCFile)mFile).getFileId());
222 } else if (mFile instanceof File){
223 tagId = String.valueOf(mFile.hashCode());
224 }
225 if (String.valueOf(imageView.getTag()).equals(tagId)) {
226 if (mProgressWheelRef != null) {
227 final ProgressBar progressWheel = mProgressWheelRef.get();
228 if (progressWheel != null) {
229 progressWheel.setVisibility(View.GONE);
230 }
231 }
232 imageView.setImageBitmap(bitmap);
233 imageView.setVisibility(View.VISIBLE);
234 }
235 }
236 }
237 }
238
239 /**
240 * Add thumbnail to cache
241 * @param imageKey: thumb key
242 * @param bitmap: image for extracting thumbnail
243 * @param path: image path
244 * @param pxW: thumbnail width
245 * @param pxH: thumbnail height
246 * @return Bitmap
247 */
248 private Bitmap addThumbnailToCache(String imageKey, Bitmap bitmap, String path, int pxW, int pxH){
249
250 Bitmap thumbnail = ThumbnailUtils.extractThumbnail(bitmap, pxW, pxH);
251
252 // Rotate image, obeying exif tag
253 thumbnail = BitmapUtils.rotateImage(thumbnail,path);
254
255 // Add thumbnail to cache
256 addBitmapToCache(imageKey, thumbnail);
257
258 return thumbnail;
259 }
260
261 /**
262 * Converts size of file icon from dp to pixel
263 * @return int
264 */
265 private int getThumbnailDimension(){
266 // Converts dp to pixel
267 Resources r = MainApp.getAppContext().getResources();
268 return Math.round(r.getDimension(R.dimen.file_icon_size_grid));
269 }
270
271 private Point getScreenDimension(){
272 WindowManager wm = (WindowManager) MainApp.getAppContext().getSystemService(Context.WINDOW_SERVICE);
273 Display display = wm.getDefaultDisplay();
274 Point test = new Point();
275 display.getSize(test);
276 return test;
277 }
278
279 private Bitmap doOCFileInBackground(Boolean isThumbnail) {
280 Bitmap thumbnail = null;
281 OCFile file = (OCFile)mFile;
282
283 // distinguish between thumbnail and resized image
284 String temp = String.valueOf(file.getRemoteId());
285 if (isThumbnail){
286 temp = "t" + temp;
287 } else {
288 temp = "r" + temp;
289 }
290
291 final String imageKey = temp;
292
293 // Check disk cache in background thread
294 thumbnail = getBitmapFromDiskCache(imageKey);
295
296 // Not found in disk cache
297 if (thumbnail == null || file.needsUpdateThumbnail()) {
298 int pxW = 0;
299 int pxH = 0;
300 if (mIsThumbnail) {
301 pxW = pxH = getThumbnailDimension();
302 } else {
303 Point p = getScreenDimension();
304 pxW = p.x;
305 pxH = p.y;
306 }
307
308 if (file.isDown()) {
309 Bitmap bitmap = BitmapUtils.decodeSampledBitmapFromFile(
310 file.getStoragePath(), pxW, pxH);
311
312 if (bitmap != null) {
313 // Handle PNG
314 if (file.getMimetype().equalsIgnoreCase("image/png")) {
315 bitmap = handlePNG(bitmap, pxW);
316 }
317
318 thumbnail = addThumbnailToCache(imageKey, bitmap, file.getStoragePath(), pxW, pxH);
319
320 file.setNeedsUpdateThumbnail(false);
321 mStorageManager.saveFile(file);
322 }
323
324 } else {
325 // Download thumbnail from server
326 OwnCloudVersion serverOCVersion = AccountUtils.getServerVersion(mAccount);
327 if (mClient != null && serverOCVersion != null) {
328 if (serverOCVersion.supportsRemoteThumbnails()) {
329 try {
330 String uri = mClient.getBaseUri() + "" +
331 "/index.php/apps/files/api/v1/thumbnail/" +
332 pxW + "/" + pxH + Uri.encode(file.getRemotePath(), "/");
333 Log_OC.d("Thumbnail", "URI: " + uri);
334 GetMethod get = new GetMethod(uri);
335 int status = mClient.executeMethod(get);
336 if (status == HttpStatus.SC_OK) {
337 InputStream inputStream = get.getResponseBodyAsStream();
338 Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
339 thumbnail = ThumbnailUtils.extractThumbnail(bitmap, pxW, pxH);
340 byte[] bytes = get.getResponseBody();
341
342 if (mIsThumbnail) {
343 thumbnail = ThumbnailUtils.extractThumbnail(bitmap, pxW, pxH);
344 } else {
345 thumbnail = bitmap;
346 }
347
348 // Handle PNG
349 if (file.getMimetype().equalsIgnoreCase("image/png")) {
350 thumbnail = handlePNG(thumbnail, pxW);
351 }
352
353 // Add thumbnail to cache
354 if (thumbnail != null) {
355 addBitmapToCache(imageKey, thumbnail);
356 }
357 }
358 } catch (Exception e) {
359 e.printStackTrace();
360 }
361 } else {
362 Log_OC.d(TAG, "Server too old");
363 }
364 }
365 }
366 }
367
368 return thumbnail;
369
370 }
371
372 private Bitmap handlePNG(Bitmap bitmap, int px){
373 Bitmap resultBitmap = Bitmap.createBitmap(px,
374 px,
375 Bitmap.Config.ARGB_8888);
376 Canvas c = new Canvas(resultBitmap);
377
378 c.drawColor(MainApp.getAppContext().getResources().
379 getColor(R.color.background_color));
380 c.drawBitmap(bitmap, 0, 0, null);
381
382 return resultBitmap;
383 }
384
385 private Bitmap doFileInBackground(Boolean mIsThumbnail) {
386 File file = (File)mFile;
387
388 // distinguish between thumbnail and resized image
389 String temp = String.valueOf(file.hashCode());
390 if (mIsThumbnail){
391 temp = "t" + temp;
392 } else {
393 temp = "r" + temp;
394 }
395
396 final String imageKey = temp;
397
398 // Check disk cache in background thread
399 Bitmap thumbnail = getBitmapFromDiskCache(imageKey);
400
401 // Not found in disk cache
402 if (thumbnail == null) {
403 int pxW = 0;
404 int pxH = 0;
405 if (mIsThumbnail) {
406 pxW = pxH = getThumbnailDimension();
407 } else {
408 Point p = getScreenDimension();
409 pxW = p.x;
410 pxH = p.y;
411 }
412
413 Bitmap bitmap = BitmapUtils.decodeSampledBitmapFromFile(
414 file.getAbsolutePath(), pxW, pxH);
415
416 if (bitmap != null) {
417 thumbnail = addThumbnailToCache(imageKey, bitmap, file.getPath(), pxW, pxH);
418 }
419 }
420 return thumbnail;
421 }
422
423 }
424
425 public static boolean cancelPotentialWork(Object file, ImageView imageView) {
426 final ThumbnailGenerationTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
427
428 if (bitmapWorkerTask != null) {
429 final Object bitmapData = bitmapWorkerTask.mFile;
430 // If bitmapData is not yet set or it differs from the new data
431 if (bitmapData == null || bitmapData != file) {
432 // Cancel previous task
433 bitmapWorkerTask.cancel(true);
434 Log_OC.v(TAG, "Cancelled generation of thumbnail for a reused imageView");
435 } else {
436 // The same work is already in progress
437 return false;
438 }
439 }
440 // No task associated with the ImageView, or an existing task was cancelled
441 return true;
442 }
443
444 public static ThumbnailGenerationTask getBitmapWorkerTask(ImageView imageView) {
445 if (imageView != null) {
446 final Drawable drawable = imageView.getDrawable();
447 if (drawable instanceof AsyncDrawable) {
448 final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
449 return asyncDrawable.getBitmapWorkerTask();
450 }
451 }
452 return null;
453 }
454
455 public static class AsyncDrawable extends BitmapDrawable {
456 private final WeakReference<ThumbnailGenerationTask> bitmapWorkerTaskReference;
457
458 public AsyncDrawable(
459 Resources res, Bitmap bitmap, ThumbnailGenerationTask bitmapWorkerTask
460 ) {
461
462 super(res, bitmap);
463 bitmapWorkerTaskReference =
464 new WeakReference<ThumbnailGenerationTask>(bitmapWorkerTask);
465 }
466
467 public ThumbnailGenerationTask getBitmapWorkerTask() {
468 return bitmapWorkerTaskReference.get();
469 }
470 }
471 }