ThumbnailsCacheManager.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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. package com.owncloud.android.datamodel;
  22. import java.io.File;
  23. import java.io.InputStream;
  24. import java.lang.ref.WeakReference;
  25. import org.apache.commons.httpclient.HttpStatus;
  26. import org.apache.commons.httpclient.methods.GetMethod;
  27. import android.accounts.Account;
  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.Canvas;
  33. import android.graphics.drawable.BitmapDrawable;
  34. import android.graphics.drawable.ColorDrawable;
  35. import android.graphics.drawable.Drawable;
  36. import android.media.ThumbnailUtils;
  37. import android.net.Uri;
  38. import android.os.AsyncTask;
  39. import android.widget.ImageView;
  40. import com.owncloud.android.MainApp;
  41. import com.owncloud.android.R;
  42. import com.owncloud.android.authentication.AccountUtils;
  43. import com.owncloud.android.lib.common.OwnCloudAccount;
  44. import com.owncloud.android.lib.common.OwnCloudClient;
  45. import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
  46. import com.owncloud.android.lib.common.utils.Log_OC;
  47. import com.owncloud.android.lib.resources.status.OwnCloudVersion;
  48. import com.owncloud.android.ui.adapter.DiskLruImageCache;
  49. import com.owncloud.android.utils.BitmapUtils;
  50. import com.owncloud.android.utils.DisplayUtils;
  51. /**
  52. * Manager for concurrent access to thumbnails cache.
  53. */
  54. public class ThumbnailsCacheManager {
  55. private static final String TAG = ThumbnailsCacheManager.class.getSimpleName();
  56. private static final String CACHE_FOLDER = "thumbnailCache";
  57. private static final Object mThumbnailsDiskCacheLock = new Object();
  58. private static DiskLruImageCache mThumbnailCache = null;
  59. private static boolean mThumbnailCacheStarting = true;
  60. private static final int DISK_CACHE_SIZE = 1024 * 1024 * 10; // 10MB
  61. private static final CompressFormat mCompressFormat = CompressFormat.JPEG;
  62. private static final int mCompressQuality = 70;
  63. private static OwnCloudClient mClient = null;
  64. public static Bitmap mDefaultImg =
  65. BitmapFactory.decodeResource(
  66. MainApp.getAppContext().getResources(),
  67. R.drawable.file_image
  68. );
  69. public static class InitDiskCacheTask extends AsyncTask<File, Void, Void> {
  70. @Override
  71. protected Void doInBackground(File... params) {
  72. synchronized (mThumbnailsDiskCacheLock) {
  73. mThumbnailCacheStarting = true;
  74. if (mThumbnailCache == null) {
  75. try {
  76. // Check if media is mounted or storage is built-in, if so,
  77. // try and use external cache dir; otherwise use internal cache dir
  78. final String cachePath =
  79. MainApp.getAppContext().getExternalCacheDir().getPath() +
  80. File.separator + CACHE_FOLDER;
  81. Log_OC.d(TAG, "create dir: " + cachePath);
  82. final File diskCacheDir = new File(cachePath);
  83. mThumbnailCache = new DiskLruImageCache(
  84. diskCacheDir,
  85. DISK_CACHE_SIZE,
  86. mCompressFormat,
  87. mCompressQuality
  88. );
  89. } catch (Exception e) {
  90. Log_OC.d(TAG, "Thumbnail cache could not be opened ", e);
  91. mThumbnailCache = null;
  92. }
  93. }
  94. mThumbnailCacheStarting = false; // Finished initialization
  95. mThumbnailsDiskCacheLock.notifyAll(); // Wake any waiting threads
  96. }
  97. return null;
  98. }
  99. }
  100. public static void addBitmapToCache(String key, Bitmap bitmap) {
  101. synchronized (mThumbnailsDiskCacheLock) {
  102. if (mThumbnailCache != null) {
  103. mThumbnailCache.put(key, bitmap);
  104. }
  105. }
  106. }
  107. public static Bitmap getBitmapFromDiskCache(String key) {
  108. synchronized (mThumbnailsDiskCacheLock) {
  109. // Wait while disk cache is started from background thread
  110. while (mThumbnailCacheStarting) {
  111. try {
  112. mThumbnailsDiskCacheLock.wait();
  113. } catch (InterruptedException e) {
  114. Log_OC.e(TAG, "Wait in mThumbnailsDiskCacheLock was interrupted", e);
  115. }
  116. }
  117. if (mThumbnailCache != null) {
  118. return mThumbnailCache.getBitmap(key);
  119. }
  120. }
  121. return null;
  122. }
  123. public static class ThumbnailGenerationTask extends AsyncTask<Object, Void, Bitmap> {
  124. private final WeakReference<ImageView> mImageViewReference;
  125. private static Account mAccount;
  126. private Object mFile;
  127. private FileDataStorageManager mStorageManager;
  128. public ThumbnailGenerationTask(ImageView imageView, FileDataStorageManager storageManager,
  129. Account account) {
  130. // Use a WeakReference to ensure the ImageView can be garbage collected
  131. mImageViewReference = new WeakReference<ImageView>(imageView);
  132. if (storageManager == null)
  133. throw new IllegalArgumentException("storageManager must not be NULL");
  134. mStorageManager = storageManager;
  135. mAccount = account;
  136. }
  137. public ThumbnailGenerationTask(ImageView imageView) {
  138. // Use a WeakReference to ensure the ImageView can be garbage collected
  139. mImageViewReference = new WeakReference<ImageView>(imageView);
  140. }
  141. @Override
  142. protected Bitmap doInBackground(Object... params) {
  143. Bitmap thumbnail = null;
  144. try {
  145. if (mAccount != null) {
  146. OwnCloudAccount ocAccount = new OwnCloudAccount(mAccount,
  147. MainApp.getAppContext());
  148. mClient = OwnCloudClientManagerFactory.getDefaultSingleton().
  149. getClientFor(ocAccount, MainApp.getAppContext());
  150. }
  151. mFile = params[0];
  152. if (mFile instanceof OCFile) {
  153. thumbnail = doOCFileInBackground();
  154. } else if (mFile instanceof File) {
  155. thumbnail = doFileInBackground();
  156. //} else { do nothing
  157. }
  158. }catch(Throwable t){
  159. // the app should never break due to a problem with thumbnails
  160. Log_OC.e(TAG, "Generation of thumbnail for " + mFile + " failed", t);
  161. if (t instanceof OutOfMemoryError) {
  162. System.gc();
  163. }
  164. }
  165. return thumbnail;
  166. }
  167. protected void onPostExecute(Bitmap bitmap){
  168. if (bitmap != null) {
  169. final ImageView imageView = mImageViewReference.get();
  170. final ThumbnailGenerationTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
  171. if (this == bitmapWorkerTask) {
  172. String tagId = "";
  173. if (mFile instanceof OCFile){
  174. tagId = String.valueOf(((OCFile)mFile).getFileId());
  175. } else if (mFile instanceof File){
  176. tagId = String.valueOf(mFile.hashCode());
  177. }
  178. if (String.valueOf(imageView.getTag()).equals(tagId)) {
  179. imageView.setImageBitmap(bitmap);
  180. }
  181. }
  182. }
  183. }
  184. /**
  185. * Add thumbnail to cache
  186. * @param imageKey: thumb key
  187. * @param bitmap: image for extracting thumbnail
  188. * @param path: image path
  189. * @param px: thumbnail dp
  190. * @return Bitmap
  191. */
  192. private Bitmap addThumbnailToCache(String imageKey, Bitmap bitmap, String path, int px){
  193. Bitmap thumbnail = ThumbnailUtils.extractThumbnail(bitmap, px, px);
  194. // Rotate image, obeying exif tag
  195. thumbnail = BitmapUtils.rotateImage(thumbnail,path);
  196. // Add thumbnail to cache
  197. addBitmapToCache(imageKey, thumbnail);
  198. return thumbnail;
  199. }
  200. /**
  201. * Converts size of file icon from dp to pixel
  202. * @return int
  203. */
  204. private int getThumbnailDimension(){
  205. // Converts dp to pixel
  206. Resources r = MainApp.getAppContext().getResources();
  207. return Math.round(r.getDimension(R.dimen.file_icon_size_grid));
  208. }
  209. private Bitmap doOCFileInBackground() {
  210. OCFile file = (OCFile)mFile;
  211. final String imageKey = String.valueOf(file.getRemoteId());
  212. // Check disk cache in background thread
  213. Bitmap thumbnail = getBitmapFromDiskCache(imageKey);
  214. // Not found in disk cache
  215. if (thumbnail == null || file.needsUpdateThumbnail()) {
  216. int px = getThumbnailDimension();
  217. if (file.isDown()) {
  218. Bitmap temp = BitmapUtils.decodeSampledBitmapFromFile(
  219. file.getStoragePath(), px, px);
  220. Bitmap bitmap = ThumbnailUtils.extractThumbnail(temp, px, px);
  221. if (bitmap != null) {
  222. // Handle PNG
  223. if (file.getMimetype().equalsIgnoreCase("image/png")) {
  224. bitmap = handlePNG(bitmap, px);
  225. }
  226. thumbnail = addThumbnailToCache(imageKey, bitmap, file.getStoragePath(), px);
  227. file.setNeedsUpdateThumbnail(false);
  228. mStorageManager.saveFile(file);
  229. }
  230. } else {
  231. // Download thumbnail from server
  232. OwnCloudVersion serverOCVersion = AccountUtils.getServerVersion(mAccount);
  233. if (mClient != null && serverOCVersion != null) {
  234. if (serverOCVersion.supportsRemoteThumbnails()) {
  235. try {
  236. String uri = mClient.getBaseUri() + "" +
  237. "/index.php/apps/files/api/v1/thumbnail/" +
  238. px + "/" + px + Uri.encode(file.getRemotePath(), "/");
  239. Log_OC.d("Thumbnail", "URI: " + uri);
  240. GetMethod get = new GetMethod(uri);
  241. int status = mClient.executeMethod(get);
  242. if (status == HttpStatus.SC_OK) {
  243. InputStream inputStream = get.getResponseBodyAsStream();
  244. Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
  245. thumbnail = ThumbnailUtils.extractThumbnail(bitmap, px, px);
  246. // Handle PNG
  247. if (file.getMimetype().equalsIgnoreCase("image/png")) {
  248. thumbnail = handlePNG(thumbnail, px);
  249. }
  250. // Add thumbnail to cache
  251. if (thumbnail != null) {
  252. addBitmapToCache(imageKey, thumbnail);
  253. }
  254. }
  255. } catch (Exception e) {
  256. e.printStackTrace();
  257. }
  258. } else {
  259. Log_OC.d(TAG, "Server too old");
  260. }
  261. }
  262. }
  263. }
  264. return thumbnail;
  265. }
  266. private Bitmap handlePNG(Bitmap bitmap, int px){
  267. Bitmap resultBitmap = Bitmap.createBitmap(px,
  268. px,
  269. Bitmap.Config.ARGB_8888);
  270. Canvas c = new Canvas(resultBitmap);
  271. c.drawColor(MainApp.getAppContext().getResources().
  272. getColor(R.color.background_color));
  273. c.drawBitmap(bitmap, 0, 0, null);
  274. return resultBitmap;
  275. }
  276. private Bitmap doFileInBackground() {
  277. File file = (File)mFile;
  278. final String imageKey = String.valueOf(file.hashCode());
  279. // Check disk cache in background thread
  280. Bitmap thumbnail = getBitmapFromDiskCache(imageKey);
  281. // Not found in disk cache
  282. if (thumbnail == null) {
  283. int px = getThumbnailDimension();
  284. Bitmap bitmap = BitmapUtils.decodeSampledBitmapFromFile(
  285. file.getAbsolutePath(), px, px);
  286. if (bitmap != null) {
  287. thumbnail = addThumbnailToCache(imageKey, bitmap, file.getPath(), px);
  288. }
  289. }
  290. return thumbnail;
  291. }
  292. }
  293. public static boolean cancelPotentialWork(Object file, ImageView imageView) {
  294. final ThumbnailGenerationTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
  295. if (bitmapWorkerTask != null) {
  296. final Object bitmapData = bitmapWorkerTask.mFile;
  297. // If bitmapData is not yet set or it differs from the new data
  298. if (bitmapData == null || bitmapData != file) {
  299. // Cancel previous task
  300. bitmapWorkerTask.cancel(true);
  301. Log_OC.v(TAG, "Cancelled generation of thumbnail for a reused imageView");
  302. } else {
  303. // The same work is already in progress
  304. return false;
  305. }
  306. }
  307. // No task associated with the ImageView, or an existing task was cancelled
  308. return true;
  309. }
  310. public static ThumbnailGenerationTask getBitmapWorkerTask(ImageView imageView) {
  311. if (imageView != null) {
  312. final Drawable drawable = imageView.getDrawable();
  313. if (drawable instanceof AsyncDrawable) {
  314. final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
  315. return asyncDrawable.getBitmapWorkerTask();
  316. }
  317. }
  318. return null;
  319. }
  320. public static class AsyncDrawable extends BitmapDrawable {
  321. private final WeakReference<ThumbnailGenerationTask> bitmapWorkerTaskReference;
  322. public AsyncDrawable(
  323. Resources res, Bitmap bitmap, ThumbnailGenerationTask bitmapWorkerTask
  324. ) {
  325. super(res, bitmap);
  326. bitmapWorkerTaskReference =
  327. new WeakReference<ThumbnailGenerationTask>(bitmapWorkerTask);
  328. }
  329. public ThumbnailGenerationTask getBitmapWorkerTask() {
  330. return bitmapWorkerTaskReference.get();
  331. }
  332. }
  333. }