Merge branch 'develop' into imageGrid
[pub/Android/ownCloud.git] / src / com / owncloud / android / datamodel / ThumbnailsCacheManager.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012-2014 ownCloud Inc.
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 2,
6 * as published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 *
16 */
17
18 package com.owncloud.android.datamodel;
19
20 import java.io.File;
21 import java.lang.ref.WeakReference;
22
23 import org.apache.commons.httpclient.HttpStatus;
24 import org.apache.commons.httpclient.methods.GetMethod;
25
26 import android.accounts.Account;
27 import android.accounts.AccountManager;
28 import android.content.res.Resources;
29 import android.graphics.Bitmap;
30 import android.graphics.Bitmap.CompressFormat;
31 import android.graphics.BitmapFactory;
32 import android.graphics.drawable.BitmapDrawable;
33 import android.graphics.drawable.Drawable;
34 import android.media.ThumbnailUtils;
35 import android.net.Uri;
36 import android.os.AsyncTask;
37 import android.widget.ImageView;
38
39 import com.owncloud.android.MainApp;
40 import com.owncloud.android.R;
41 import com.owncloud.android.lib.common.OwnCloudAccount;
42 import com.owncloud.android.lib.common.OwnCloudClient;
43 import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
44 import com.owncloud.android.lib.common.accounts.AccountUtils.Constants;
45 import com.owncloud.android.lib.common.utils.Log_OC;
46 import com.owncloud.android.lib.resources.status.OwnCloudVersion;
47 import com.owncloud.android.ui.adapter.DiskLruImageCache;
48 import com.owncloud.android.utils.BitmapUtils;
49 import com.owncloud.android.utils.DisplayUtils;
50
51 /**
52 * Manager for concurrent access to thumbnails cache.
53 *
54 * @author Tobias Kaminsky
55 * @author David A. Velasco
56 */
57 public class ThumbnailsCacheManager {
58
59 private static final String TAG = ThumbnailsCacheManager.class.getSimpleName();
60
61 private static final String CACHE_FOLDER = "thumbnailCache";
62 private static final String MINOR_SERVER_VERSION_FOR_THUMBS = "7.8.0";
63
64 private static final Object mThumbnailsDiskCacheLock = new Object();
65 private static DiskLruImageCache mThumbnailCache = null;
66 private static boolean mThumbnailCacheStarting = true;
67
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;
72 private static String mServerVersion = null;
73
74 public static Bitmap mDefaultImg =
75 BitmapFactory.decodeResource(
76 MainApp.getAppContext().getResources(),
77 DisplayUtils.getFileTypeIconId("image/png", "default.png")
78 );
79
80
81 public static class InitDiskCacheTask extends AsyncTask<File, Void, Void> {
82
83 @Override
84 protected Void doInBackground(File... params) {
85 synchronized (mThumbnailsDiskCacheLock) {
86 mThumbnailCacheStarting = true;
87
88 if (mThumbnailCache == null) {
89 try {
90 // Check if media is mounted or storage is built-in, if so,
91 // try and use external cache dir; otherwise use internal cache dir
92 final String cachePath =
93 MainApp.getAppContext().getExternalCacheDir().getPath() +
94 File.separator + CACHE_FOLDER;
95 Log_OC.d(TAG, "create dir: " + cachePath);
96 final File diskCacheDir = new File(cachePath);
97 mThumbnailCache = new DiskLruImageCache(
98 diskCacheDir,
99 DISK_CACHE_SIZE,
100 mCompressFormat,
101 mCompressQuality
102 );
103 } catch (Exception e) {
104 Log_OC.d(TAG, "Thumbnail cache could not be opened ", e);
105 mThumbnailCache = null;
106 }
107 }
108 mThumbnailCacheStarting = false; // Finished initialization
109 mThumbnailsDiskCacheLock.notifyAll(); // Wake any waiting threads
110 }
111 return null;
112 }
113 }
114
115
116 public static void addBitmapToCache(String key, Bitmap bitmap) {
117 synchronized (mThumbnailsDiskCacheLock) {
118 if (mThumbnailCache != null) {
119 mThumbnailCache.put(key, bitmap);
120 }
121 }
122 }
123
124
125 public static Bitmap getBitmapFromDiskCache(String key) {
126 synchronized (mThumbnailsDiskCacheLock) {
127 // Wait while disk cache is started from background thread
128 while (mThumbnailCacheStarting) {
129 try {
130 mThumbnailsDiskCacheLock.wait();
131 } catch (InterruptedException e) {}
132 }
133 if (mThumbnailCache != null) {
134 return (Bitmap) mThumbnailCache.getBitmap(key);
135 }
136 }
137 return null;
138 }
139
140 public static class ThumbnailGenerationTask extends AsyncTask<Object, Void, Bitmap> {
141 private final WeakReference<ImageView> mImageViewReference;
142 private static Account mAccount;
143 private Object mFile;
144 private FileDataStorageManager mStorageManager;
145
146
147 public ThumbnailGenerationTask(ImageView imageView, FileDataStorageManager storageManager, Account account) {
148 // Use a WeakReference to ensure the ImageView can be garbage collected
149 mImageViewReference = new WeakReference<ImageView>(imageView);
150 if (storageManager == null)
151 throw new IllegalArgumentException("storageManager must not be NULL");
152 mStorageManager = storageManager;
153 mAccount = account;
154 }
155
156 public ThumbnailGenerationTask(ImageView imageView) {
157 // Use a WeakReference to ensure the ImageView can be garbage collected
158 mImageViewReference = new WeakReference<ImageView>(imageView);
159 }
160
161 @Override
162 protected Bitmap doInBackground(Object... params) {
163 Bitmap thumbnail = null;
164
165 try {
166 if (mAccount != null) {
167 AccountManager accountMgr = AccountManager.get(MainApp.getAppContext());
168
169 mServerVersion = accountMgr.getUserData(mAccount, Constants.KEY_OC_VERSION);
170 OwnCloudAccount ocAccount = new OwnCloudAccount(mAccount, MainApp.getAppContext());
171 mClient = OwnCloudClientManagerFactory.getDefaultSingleton().
172 getClientFor(ocAccount, MainApp.getAppContext());
173 }
174
175 mFile = params[0];
176
177 if (mFile instanceof OCFile) {
178 thumbnail = doOCFileInBackground();
179 } else if (mFile instanceof File) {
180 thumbnail = doFileInBackground();
181 } else {
182 // do nothing
183 }
184
185 }catch(Throwable t){
186 // the app should never break due to a problem with thumbnails
187 Log_OC.e(TAG, "Generation of thumbnail for " + mFile + " failed", t);
188 if (t instanceof OutOfMemoryError) {
189 System.gc();
190 }
191 }
192
193 return thumbnail;
194 }
195
196 protected void onPostExecute(Bitmap bitmap){
197 if (isCancelled()) {
198 bitmap = null;
199 }
200
201 if (mImageViewReference != null && bitmap != null) {
202 final ImageView imageView = mImageViewReference.get();
203 final ThumbnailGenerationTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
204 if (this == bitmapWorkerTask && imageView != null) {
205 String tagId = "";
206 if (mFile instanceof OCFile){
207 tagId = String.valueOf(((OCFile)mFile).getFileId());
208 } else if (mFile instanceof File){
209 tagId = String.valueOf(((File)mFile).hashCode());
210 }
211 if (String.valueOf(imageView.getTag()).equals(tagId)) {
212 imageView.setImageBitmap(bitmap);
213 }
214 }
215 }
216 }
217
218 /**
219 * Add thumbnail to cache
220 * @param imageKey: thumb key
221 * @param bitmap: image for extracting thumbnail
222 * @param path: image path
223 * @param px: thumbnail dp
224 * @return Bitmap
225 */
226 private Bitmap addThumbnailToCache(String imageKey, Bitmap bitmap, String path, int px){
227
228 Bitmap thumbnail = ThumbnailUtils.extractThumbnail(bitmap, px, px);
229
230 // Rotate image, obeying exif tag
231 thumbnail = BitmapUtils.rotateImage(thumbnail,path);
232
233 // Add thumbnail to cache
234 addBitmapToCache(imageKey, thumbnail);
235
236 return thumbnail;
237 }
238
239 /**
240 * Converts size of file icon from dp to pixel
241 * @return int
242 */
243 private int getThumbnailDimension(){
244 // Converts dp to pixel
245 Resources r = MainApp.getAppContext().getResources();
246 return (int) Math.round(r.getDimension(R.dimen.file_icon_size_grid));
247 }
248
249 private Bitmap doOCFileInBackground() {
250 Bitmap thumbnail = null;
251 OCFile file = (OCFile)mFile;
252
253 final String imageKey = String.valueOf(file.getRemoteId());
254
255 // Check disk cache in background thread
256 thumbnail = getBitmapFromDiskCache(imageKey);
257
258 // Not found in disk cache
259 if (thumbnail == null || file.needsUpdateThumbnail()) {
260
261 int px = getThumbnailDimension();
262
263 if (file.isDown()) {
264 Bitmap bitmap = BitmapUtils.decodeSampledBitmapFromFile(
265 file.getStoragePath(), px, px);
266
267 if (bitmap != null) {
268 thumbnail = addThumbnailToCache(imageKey, bitmap, file.getStoragePath(), px);
269
270 file.setNeedsUpdateThumbnail(false);
271 mStorageManager.saveFile(file);
272 }
273
274 } else {
275 // Download thumbnail from server
276 if (mClient != null && mServerVersion != null) {
277 OwnCloudVersion serverOCVersion = new OwnCloudVersion(mServerVersion);
278 if (serverOCVersion.compareTo(new OwnCloudVersion(MINOR_SERVER_VERSION_FOR_THUMBS)) >= 0) {
279 try {
280 int status = -1;
281
282 String uri = mClient.getBaseUri() + "/index.php/apps/files/api/v1/thumbnail/" +
283 px + "/" + px + Uri.encode(file.getRemotePath(), "/");
284 Log_OC.d("Thumbnail", "URI: " + uri);
285 GetMethod get = new GetMethod(uri);
286 status = mClient.executeMethod(get);
287 if (status == HttpStatus.SC_OK) {
288 byte[] bytes = get.getResponseBody();
289 Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
290 thumbnail = ThumbnailUtils.extractThumbnail(bitmap, px, px);
291
292 // Add thumbnail to cache
293 if (thumbnail != null) {
294 addBitmapToCache(imageKey, thumbnail);
295 }
296 }
297 } catch (Exception e) {
298 e.printStackTrace();
299 }
300 } else {
301 Log_OC.d(TAG, "Server too old");
302 }
303 }
304 }
305 }
306
307 return thumbnail;
308
309 }
310
311 private Bitmap doFileInBackground() {
312 Bitmap thumbnail = null;
313 File file = (File)mFile;
314
315 final String imageKey = String.valueOf(file.hashCode());
316
317 // Check disk cache in background thread
318 thumbnail = getBitmapFromDiskCache(imageKey);
319
320 // Not found in disk cache
321 if (thumbnail == null) {
322
323 int px = getThumbnailDimension();
324
325 Bitmap bitmap = BitmapUtils.decodeSampledBitmapFromFile(
326 file.getAbsolutePath(), px, px);
327
328 if (bitmap != null) {
329 thumbnail = addThumbnailToCache(imageKey, bitmap, file.getPath(), px);
330 }
331 }
332 return thumbnail;
333 }
334
335 }
336
337 public static boolean cancelPotentialWork(Object file, ImageView imageView) {
338 final ThumbnailGenerationTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
339
340 if (bitmapWorkerTask != null) {
341 final Object bitmapData = bitmapWorkerTask.mFile;
342 // If bitmapData is not yet set or it differs from the new data
343 if (bitmapData == null || bitmapData != file) {
344 // Cancel previous task
345 bitmapWorkerTask.cancel(true);
346 } else {
347 // The same work is already in progress
348 return false;
349 }
350 }
351 // No task associated with the ImageView, or an existing task was cancelled
352 return true;
353 }
354
355 public static ThumbnailGenerationTask getBitmapWorkerTask(ImageView imageView) {
356 if (imageView != null) {
357 final Drawable drawable = imageView.getDrawable();
358 if (drawable instanceof AsyncDrawable) {
359 final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
360 return asyncDrawable.getBitmapWorkerTask();
361 }
362 }
363 return null;
364 }
365
366 public static class AsyncDrawable extends BitmapDrawable {
367 private final WeakReference<ThumbnailGenerationTask> bitmapWorkerTaskReference;
368
369 public AsyncDrawable(
370 Resources res, Bitmap bitmap, ThumbnailGenerationTask bitmapWorkerTask
371 ) {
372
373 super(res, bitmap);
374 bitmapWorkerTaskReference =
375 new WeakReference<ThumbnailGenerationTask>(bitmapWorkerTask);
376 }
377
378 public ThumbnailGenerationTask getBitmapWorkerTask() {
379 return bitmapWorkerTaskReference.get();
380 }
381 }
382 }