ThumbnailsCacheManager.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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(FileDataStorageManager storageManager, Account account){
  138. if (storageManager == null)
  139. throw new IllegalArgumentException("storageManager must not be NULL");
  140. mStorageManager = storageManager;
  141. mAccount = account;
  142. mImageViewReference = null;
  143. }
  144. public ThumbnailGenerationTask(ImageView imageView) {
  145. // Use a WeakReference to ensure the ImageView can be garbage collected
  146. mImageViewReference = new WeakReference<ImageView>(imageView);
  147. }
  148. @Override
  149. protected Bitmap doInBackground(Object... params) {
  150. Bitmap thumbnail = null;
  151. try {
  152. if (mAccount != null) {
  153. OwnCloudAccount ocAccount = new OwnCloudAccount(mAccount,
  154. MainApp.getAppContext());
  155. mClient = OwnCloudClientManagerFactory.getDefaultSingleton().
  156. getClientFor(ocAccount, MainApp.getAppContext());
  157. }
  158. mFile = params[0];
  159. if (mFile instanceof OCFile) {
  160. thumbnail = doOCFileInBackground();
  161. } else if (mFile instanceof File) {
  162. thumbnail = doFileInBackground();
  163. //} else { do nothing
  164. }
  165. }catch(Throwable t){
  166. // the app should never break due to a problem with thumbnails
  167. Log_OC.e(TAG, "Generation of thumbnail for " + mFile + " failed", t);
  168. if (t instanceof OutOfMemoryError) {
  169. System.gc();
  170. }
  171. }
  172. return thumbnail;
  173. }
  174. protected void onPostExecute(Bitmap bitmap){
  175. if (bitmap != null && mImageViewReference != null) {
  176. final ImageView imageView = mImageViewReference.get();
  177. final ThumbnailGenerationTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
  178. if (this == bitmapWorkerTask) {
  179. String tagId = "";
  180. if (mFile instanceof OCFile){
  181. tagId = String.valueOf(((OCFile)mFile).getFileId());
  182. } else if (mFile instanceof File){
  183. tagId = String.valueOf(mFile.hashCode());
  184. }
  185. if (String.valueOf(imageView.getTag()).equals(tagId)) {
  186. imageView.setImageBitmap(bitmap);
  187. }
  188. }
  189. }
  190. }
  191. /**
  192. * Add thumbnail to cache
  193. * @param imageKey: thumb key
  194. * @param bitmap: image for extracting thumbnail
  195. * @param path: image path
  196. * @param px: thumbnail dp
  197. * @return Bitmap
  198. */
  199. private Bitmap addThumbnailToCache(String imageKey, Bitmap bitmap, String path, int px){
  200. Bitmap thumbnail = ThumbnailUtils.extractThumbnail(bitmap, px, px);
  201. // Rotate image, obeying exif tag
  202. thumbnail = BitmapUtils.rotateImage(thumbnail,path);
  203. // Add thumbnail to cache
  204. addBitmapToCache(imageKey, thumbnail);
  205. return thumbnail;
  206. }
  207. /**
  208. * Converts size of file icon from dp to pixel
  209. * @return int
  210. */
  211. private int getThumbnailDimension(){
  212. // Converts dp to pixel
  213. Resources r = MainApp.getAppContext().getResources();
  214. return Math.round(r.getDimension(R.dimen.file_icon_size_grid));
  215. }
  216. private Bitmap doOCFileInBackground() {
  217. OCFile file = (OCFile)mFile;
  218. final String imageKey = String.valueOf(file.getRemoteId());
  219. // Check disk cache in background thread
  220. Bitmap thumbnail = getBitmapFromDiskCache(imageKey);
  221. // Not found in disk cache
  222. if (thumbnail == null || file.needsUpdateThumbnail()) {
  223. int px = getThumbnailDimension();
  224. if (file.isDown()) {
  225. Bitmap temp = BitmapUtils.decodeSampledBitmapFromFile(
  226. file.getStoragePath(), px, px);
  227. Bitmap bitmap = ThumbnailUtils.extractThumbnail(temp, px, px);
  228. if (bitmap != null) {
  229. // Handle PNG
  230. if (file.getMimetype().equalsIgnoreCase("image/png")) {
  231. bitmap = handlePNG(bitmap, px);
  232. }
  233. thumbnail = addThumbnailToCache(imageKey, bitmap, file.getStoragePath(), px);
  234. file.setNeedsUpdateThumbnail(false);
  235. mStorageManager.saveFile(file);
  236. }
  237. } else {
  238. // Download thumbnail from server
  239. OwnCloudVersion serverOCVersion = AccountUtils.getServerVersion(mAccount);
  240. if (mClient != null && serverOCVersion != null) {
  241. if (serverOCVersion.supportsRemoteThumbnails()) {
  242. GetMethod get = null;
  243. try {
  244. String uri = mClient.getBaseUri() + "" +
  245. "/index.php/apps/files/api/v1/thumbnail/" +
  246. px + "/" + px + Uri.encode(file.getRemotePath(), "/");
  247. Log_OC.d("Thumbnail", "URI: " + uri);
  248. get = new GetMethod(uri);
  249. int status = mClient.executeMethod(get);
  250. if (status == HttpStatus.SC_OK) {
  251. InputStream inputStream = get.getResponseBodyAsStream();
  252. Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
  253. thumbnail = ThumbnailUtils.extractThumbnail(bitmap, px, px);
  254. // Handle PNG
  255. if (file.getMimetype().equalsIgnoreCase("image/png")) {
  256. thumbnail = handlePNG(thumbnail, px);
  257. }
  258. // Add thumbnail to cache
  259. if (thumbnail != null) {
  260. addBitmapToCache(imageKey, thumbnail);
  261. }
  262. } else {
  263. mClient.exhaustResponse(get.getResponseBodyAsStream());
  264. }
  265. } catch (Exception e) {
  266. e.printStackTrace();
  267. } finally {
  268. if (get != null) {
  269. get.releaseConnection();
  270. }
  271. }
  272. } else {
  273. Log_OC.d(TAG, "Server too old");
  274. }
  275. }
  276. }
  277. }
  278. return thumbnail;
  279. }
  280. private Bitmap handlePNG(Bitmap bitmap, int px){
  281. Bitmap resultBitmap = Bitmap.createBitmap(px,
  282. px,
  283. Bitmap.Config.ARGB_8888);
  284. Canvas c = new Canvas(resultBitmap);
  285. c.drawColor(MainApp.getAppContext().getResources().
  286. getColor(R.color.background_color));
  287. c.drawBitmap(bitmap, 0, 0, null);
  288. return resultBitmap;
  289. }
  290. private Bitmap doFileInBackground() {
  291. File file = (File)mFile;
  292. final String imageKey = String.valueOf(file.hashCode());
  293. // Check disk cache in background thread
  294. Bitmap thumbnail = getBitmapFromDiskCache(imageKey);
  295. // Not found in disk cache
  296. if (thumbnail == null) {
  297. int px = getThumbnailDimension();
  298. Bitmap bitmap = BitmapUtils.decodeSampledBitmapFromFile(
  299. file.getAbsolutePath(), px, px);
  300. if (bitmap != null) {
  301. thumbnail = addThumbnailToCache(imageKey, bitmap, file.getPath(), px);
  302. }
  303. }
  304. return thumbnail;
  305. }
  306. }
  307. public static boolean cancelPotentialWork(Object file, ImageView imageView) {
  308. final ThumbnailGenerationTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
  309. if (bitmapWorkerTask != null) {
  310. final Object bitmapData = bitmapWorkerTask.mFile;
  311. // If bitmapData is not yet set or it differs from the new data
  312. if (bitmapData == null || bitmapData != file) {
  313. // Cancel previous task
  314. bitmapWorkerTask.cancel(true);
  315. Log_OC.v(TAG, "Cancelled generation of thumbnail for a reused imageView");
  316. } else {
  317. // The same work is already in progress
  318. return false;
  319. }
  320. }
  321. // No task associated with the ImageView, or an existing task was cancelled
  322. return true;
  323. }
  324. public static ThumbnailGenerationTask getBitmapWorkerTask(ImageView imageView) {
  325. if (imageView != null) {
  326. final Drawable drawable = imageView.getDrawable();
  327. if (drawable instanceof AsyncDrawable) {
  328. final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
  329. return asyncDrawable.getBitmapWorkerTask();
  330. }
  331. }
  332. return null;
  333. }
  334. public static class AsyncDrawable extends BitmapDrawable {
  335. private final WeakReference<ThumbnailGenerationTask> bitmapWorkerTaskReference;
  336. public AsyncDrawable(
  337. Resources res, Bitmap bitmap, ThumbnailGenerationTask bitmapWorkerTask
  338. ) {
  339. super(res, bitmap);
  340. bitmapWorkerTaskReference =
  341. new WeakReference<ThumbnailGenerationTask>(bitmapWorkerTask);
  342. }
  343. public ThumbnailGenerationTask getBitmapWorkerTask() {
  344. return bitmapWorkerTaskReference.get();
  345. }
  346. }
  347. }