- initial image grid
[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 = "6.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.getResourceId("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
141 public static boolean cancelPotentialWork(OCFile file, ImageView imageView) {
142 final ThumbnailGenerationTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
143
144 if (bitmapWorkerTask != null) {
145 final OCFile bitmapData = bitmapWorkerTask.mFile;
146 // If bitmapData is not yet set or it differs from the new data
147 if (bitmapData == null || bitmapData != file) {
148 // Cancel previous task
149 bitmapWorkerTask.cancel(true);
150 } else {
151 // The same work is already in progress
152 return false;
153 }
154 }
155 // No task associated with the ImageView, or an existing task was cancelled
156 return true;
157 }
158
159 public static ThumbnailGenerationTask getBitmapWorkerTask(ImageView imageView) {
160 if (imageView != null) {
161 final Drawable drawable = imageView.getDrawable();
162 if (drawable instanceof AsyncDrawable) {
163 final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
164 return asyncDrawable.getBitmapWorkerTask();
165 }
166 }
167 return null;
168 }
169
170 public static class ThumbnailGenerationTask extends AsyncTask<OCFile, Void, Bitmap> {
171 private final WeakReference<ImageView> mImageViewReference;
172 private static Account mAccount;
173 private OCFile mFile;
174 private FileDataStorageManager mStorageManager;
175
176 public ThumbnailGenerationTask(ImageView imageView, FileDataStorageManager storageManager, Account account) {
177 // Use a WeakReference to ensure the ImageView can be garbage collected
178 mImageViewReference = new WeakReference<ImageView>(imageView);
179 if (storageManager == null)
180 throw new IllegalArgumentException("storageManager must not be NULL");
181 mStorageManager = storageManager;
182 mAccount = account;
183 }
184
185 // Decode image in background.
186 @Override
187 protected Bitmap doInBackground(OCFile... params) {
188 Bitmap thumbnail = null;
189
190 try {
191 if (mAccount != null) {
192 AccountManager accountMgr = AccountManager.get(MainApp.getAppContext());
193
194 mServerVersion = accountMgr.getUserData(mAccount, Constants.KEY_OC_VERSION);
195 OwnCloudAccount ocAccount = new OwnCloudAccount(mAccount, MainApp.getAppContext());
196 mClient = OwnCloudClientManagerFactory.getDefaultSingleton().
197 getClientFor(ocAccount, MainApp.getAppContext());
198 }
199
200 mFile = params[0];
201 final String imageKey = String.valueOf(mFile.getRemoteId());
202
203 // Check disk cache in background thread
204 thumbnail = getBitmapFromDiskCache(imageKey);
205
206 // Not found in disk cache
207 if (thumbnail == null || mFile.needsUpdateThumbnail()) {
208 // Use Width of imageView -> no blurry images on big screens
209 int px = mImageViewReference.get().getWidth();
210
211 if (mFile.isDown()){
212 Bitmap bitmap = BitmapUtils.decodeSampledBitmapFromFile(
213 mFile.getStoragePath(), px, px);
214
215 if (bitmap != null) {
216 thumbnail = ThumbnailUtils.extractThumbnail(bitmap, px, px);
217
218 // Add thumbnail to cache
219 addBitmapToCache(imageKey, thumbnail);
220
221 mFile.setNeedsUpdateThumbnail(false);
222 mStorageManager.saveFile(mFile);
223 }
224
225 } else {
226 // Download thumbnail from server
227 if (mClient != null && mServerVersion != null) {
228 OwnCloudVersion serverOCVersion = new OwnCloudVersion(mServerVersion);
229 if (serverOCVersion.compareTo(new OwnCloudVersion(MINOR_SERVER_VERSION_FOR_THUMBS)) >= 0) {
230 try {
231 int status = -1;
232
233 String uri = mClient.getBaseUri() + "/index.php/apps/files/api/v1/thumbnail/" +
234 px + "/" + px + Uri.encode(mFile.getRemotePath(), "/");
235 Log_OC.d("Thumbnail", "URI: " + uri);
236 GetMethod get = new GetMethod(uri);
237 status = mClient.executeMethod(get);
238 if (status == HttpStatus.SC_OK) {
239 byte[] bytes = get.getResponseBody();
240 Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
241 thumbnail = ThumbnailUtils.extractThumbnail(bitmap, px, px);
242
243 // Add thumbnail to cache
244 if (thumbnail != null) {
245 addBitmapToCache(imageKey, thumbnail);
246 }
247 }
248 } catch (Exception e) {
249 e.printStackTrace();
250 }
251 } else {
252 Log_OC.d(TAG, "Server too old");
253 }
254 }
255 }
256 }
257
258 } catch (Throwable t) {
259 // the app should never break due to a problem with thumbnails
260 Log_OC.e(TAG, "Generation of thumbnail for " + mFile + " failed", t);
261 if (t instanceof OutOfMemoryError) {
262 System.gc();
263 }
264 }
265
266 return thumbnail;
267 }
268
269 protected void onPostExecute(Bitmap bitmap){
270 if (isCancelled()) {
271 bitmap = null;
272 }
273
274 if (mImageViewReference != null && bitmap != null) {
275 final ImageView imageView = mImageViewReference.get();
276 final ThumbnailGenerationTask bitmapWorkerTask =
277 getBitmapWorkerTask(imageView);
278 if (this == bitmapWorkerTask && imageView != null && imageView.getTag() != null && mFile != null) {
279 if (imageView.getTag().equals(mFile.getFileId())) {
280 imageView.setImageBitmap(bitmap);
281 }
282 }
283 }
284 }
285 }
286
287
288 public static class AsyncDrawable extends BitmapDrawable {
289 private final WeakReference<ThumbnailGenerationTask> bitmapWorkerTaskReference;
290
291 public AsyncDrawable(
292 Resources res, Bitmap bitmap, ThumbnailGenerationTask bitmapWorkerTask
293 ) {
294
295 super(res, bitmap);
296 bitmapWorkerTaskReference =
297 new WeakReference<ThumbnailGenerationTask>(bitmapWorkerTask);
298 }
299
300 public ThumbnailGenerationTask getBitmapWorkerTask() {
301 return bitmapWorkerTaskReference.get();
302 }
303 }
304
305
306 /**
307 * Remove from cache the remoteId passed
308 * @param fileRemoteId: remote id of mFile passed
309 */
310 public static void removeFileFromCache(String fileRemoteId){
311 synchronized (mThumbnailsDiskCacheLock) {
312 if (mThumbnailCache != null) {
313 mThumbnailCache.removeKey(fileRemoteId);
314 }
315 mThumbnailsDiskCacheLock.notifyAll(); // Wake any waiting threads
316 }
317 }
318
319 }