PreviewImageFragment.java 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823
  1. /*
  2. * ownCloud Android client application
  3. *
  4. * @author David A. Velasco
  5. * Copyright (C) 2015 ownCloud Inc.
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License version 2,
  9. * as published by the Free Software Foundation.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. package com.owncloud.android.ui.preview;
  20. import android.accounts.Account;
  21. import android.app.Activity;
  22. import android.content.Context;
  23. import android.content.res.Resources;
  24. import android.graphics.Bitmap;
  25. import android.graphics.Color;
  26. import android.graphics.Point;
  27. import android.graphics.drawable.BitmapDrawable;
  28. import android.graphics.drawable.Drawable;
  29. import android.graphics.drawable.LayerDrawable;
  30. import android.graphics.drawable.PictureDrawable;
  31. import android.os.AsyncTask;
  32. import android.os.Build;
  33. import android.os.Bundle;
  34. import android.os.Process;
  35. import android.support.annotation.DrawableRes;
  36. import android.support.annotation.NonNull;
  37. import android.support.annotation.StringRes;
  38. import android.support.design.widget.Snackbar;
  39. import android.support.v4.app.FragmentStatePagerAdapter;
  40. import android.util.DisplayMetrics;
  41. import android.view.LayoutInflater;
  42. import android.view.Menu;
  43. import android.view.MenuInflater;
  44. import android.view.MenuItem;
  45. import android.view.View;
  46. import android.view.View.OnClickListener;
  47. import android.view.ViewGroup;
  48. import android.widget.ImageView;
  49. import android.widget.LinearLayout;
  50. import android.widget.ProgressBar;
  51. import android.widget.RelativeLayout;
  52. import android.widget.TextView;
  53. import com.caverock.androidsvg.SVG;
  54. import com.caverock.androidsvg.SVGParseException;
  55. import com.owncloud.android.MainApp;
  56. import com.owncloud.android.R;
  57. import com.owncloud.android.datamodel.OCFile;
  58. import com.owncloud.android.datamodel.ThumbnailsCacheManager;
  59. import com.owncloud.android.files.FileMenuFilter;
  60. import com.owncloud.android.lib.common.utils.Log_OC;
  61. import com.owncloud.android.ui.dialog.ConfirmationDialogFragment;
  62. import com.owncloud.android.ui.dialog.RemoveFilesDialogFragment;
  63. import com.owncloud.android.ui.fragment.FileFragment;
  64. import com.owncloud.android.utils.AnalyticsUtils;
  65. import com.owncloud.android.utils.BitmapUtils;
  66. import com.owncloud.android.utils.DisplayUtils;
  67. import com.owncloud.android.utils.MimeTypeUtil;
  68. import java.io.FileInputStream;
  69. import java.io.FileNotFoundException;
  70. import java.lang.ref.WeakReference;
  71. import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
  72. import third_parties.michaelOrtiz.TouchImageViewCustom;
  73. /**
  74. * This fragment shows a preview of a downloaded image.
  75. *
  76. * Trying to get an instance with a NULL {@link OCFile} will produce an
  77. * {@link IllegalStateException}.
  78. *
  79. * If the {@link OCFile} passed is not downloaded, an {@link IllegalStateException} is generated on
  80. * instantiation too.
  81. */
  82. public class PreviewImageFragment extends FileFragment {
  83. public static final String EXTRA_FILE = "FILE";
  84. private static final String ARG_FILE = "FILE";
  85. private static final String ARG_IGNORE_FIRST = "IGNORE_FIRST";
  86. private static final String ARG_SHOW_RESIZED_IMAGE = "SHOW_RESIZED_IMAGE";
  87. private static final String SCREEN_NAME = "Image Preview";
  88. private TouchImageViewCustom mImageView;
  89. private RelativeLayout mMultiView;
  90. protected LinearLayout mMultiListContainer;
  91. protected TextView mMultiListMessage;
  92. protected TextView mMultiListHeadline;
  93. protected ImageView mMultiListIcon;
  94. protected ProgressBar mMultiListProgress;
  95. private Boolean mShowResizedImage = false;
  96. public Bitmap mBitmap = null;
  97. private static final String TAG = PreviewImageFragment.class.getSimpleName();
  98. private boolean mIgnoreFirstSavedState;
  99. private LoadBitmapTask mLoadBitmapTask = null;
  100. /**
  101. * Public factory method to create a new fragment that previews an image.
  102. *
  103. * Android strongly recommends keep the empty constructor of fragments as the only public
  104. * constructor, and
  105. * use {@link #setArguments(Bundle)} to set the needed arguments.
  106. *
  107. * This method hides to client objects the need of doing the construction in two steps.
  108. *
  109. * @param imageFile An {@link OCFile} to preview as an image in the fragment
  110. * @param ignoreFirstSavedState Flag to work around an unexpected behaviour of
  111. * {@link FragmentStatePagerAdapter}
  112. * ; TODO better solution
  113. */
  114. public static PreviewImageFragment newInstance(@NonNull OCFile imageFile, boolean ignoreFirstSavedState,
  115. boolean showResizedImage) {
  116. PreviewImageFragment frag = new PreviewImageFragment();
  117. frag.mShowResizedImage = showResizedImage;
  118. Bundle args = new Bundle();
  119. args.putParcelable(ARG_FILE, imageFile);
  120. args.putBoolean(ARG_IGNORE_FIRST, ignoreFirstSavedState);
  121. args.putBoolean(ARG_SHOW_RESIZED_IMAGE, showResizedImage);
  122. frag.setArguments(args);
  123. return frag;
  124. }
  125. /**
  126. * Creates an empty fragment for image previews.
  127. *
  128. * MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically
  129. * (for instance, when the device is turned a aside).
  130. *
  131. * DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful
  132. * construction
  133. */
  134. public PreviewImageFragment() {
  135. mIgnoreFirstSavedState = false;
  136. }
  137. /**
  138. * {@inheritDoc}
  139. */
  140. @Override
  141. public void onCreate(Bundle savedInstanceState) {
  142. super.onCreate(savedInstanceState);
  143. Bundle args = getArguments();
  144. setFile(args.getParcelable(ARG_FILE));
  145. // TODO better in super, but needs to check ALL the class extending FileFragment;
  146. // not right now
  147. mIgnoreFirstSavedState = args.getBoolean(ARG_IGNORE_FIRST);
  148. mShowResizedImage = args.getBoolean(ARG_SHOW_RESIZED_IMAGE);
  149. setHasOptionsMenu(true);
  150. }
  151. /**
  152. * {@inheritDoc}
  153. */
  154. @Override
  155. public View onCreateView(LayoutInflater inflater, ViewGroup container,
  156. Bundle savedInstanceState) {
  157. super.onCreateView(inflater, container, savedInstanceState);
  158. View view = inflater.inflate(R.layout.preview_image_fragment, container, false);
  159. mImageView = view.findViewById(R.id.image);
  160. mImageView.setPreviewImageFragment(this);
  161. mImageView.setVisibility(View.GONE);
  162. view.setOnClickListener(new OnClickListener() {
  163. @Override
  164. public void onClick(View v) {
  165. ((PreviewImageActivity) getActivity()).toggleFullScreen();
  166. toggleImageBackground();
  167. }
  168. });
  169. mImageView.setOnClickListener(new OnClickListener() {
  170. @Override
  171. public void onClick(View v) {
  172. ((PreviewImageActivity) getActivity()).toggleFullScreen();
  173. toggleImageBackground();
  174. }
  175. });
  176. mMultiView = view.findViewById(R.id.multi_view);
  177. setupMultiView(view);
  178. setMultiListLoadingMessage();
  179. return view;
  180. }
  181. public void switchToFullScreen() {
  182. ((PreviewImageActivity) getActivity()).switchToFullScreen();
  183. }
  184. public void downloadFile() {
  185. ((PreviewImageActivity) getActivity()).requestForDownload(getFile());
  186. }
  187. protected void setupMultiView(View view) {
  188. mMultiListContainer = view.findViewById(R.id.empty_list_view);
  189. mMultiListMessage = view.findViewById(R.id.empty_list_view_text);
  190. mMultiListHeadline = view.findViewById(R.id.empty_list_view_headline);
  191. mMultiListIcon = view.findViewById(R.id.empty_list_icon);
  192. mMultiListProgress = view.findViewById(R.id.empty_list_progress);
  193. }
  194. /**
  195. * {@inheritDoc}
  196. */
  197. @Override
  198. public void onActivityCreated(Bundle savedInstanceState) {
  199. super.onActivityCreated(savedInstanceState);
  200. if (savedInstanceState != null) {
  201. if (!mIgnoreFirstSavedState) {
  202. OCFile file = savedInstanceState.getParcelable(PreviewImageFragment.EXTRA_FILE);
  203. setFile(file);
  204. } else {
  205. mIgnoreFirstSavedState = false;
  206. }
  207. }
  208. }
  209. /**
  210. * {@inheritDoc}
  211. */
  212. @Override
  213. public void onSaveInstanceState(Bundle outState) {
  214. super.onSaveInstanceState(outState);
  215. outState.putParcelable(PreviewImageFragment.EXTRA_FILE, getFile());
  216. }
  217. @Override
  218. public void onStart() {
  219. super.onStart();
  220. if (getFile() != null) {
  221. mImageView.setTag(getFile().getFileId());
  222. if (mShowResizedImage) {
  223. Bitmap resizedImage = ThumbnailsCacheManager.getBitmapFromDiskCache(
  224. String.valueOf(ThumbnailsCacheManager.PREFIX_RESIZED_IMAGE + getFile().getRemoteId()));
  225. if (resizedImage != null && !getFile().needsUpdateThumbnail()) {
  226. mImageView.setImageBitmap(resizedImage);
  227. mImageView.setVisibility(View.VISIBLE);
  228. mBitmap = resizedImage;
  229. } else {
  230. // show thumbnail while loading resized image
  231. Bitmap thumbnail = ThumbnailsCacheManager.getBitmapFromDiskCache(
  232. String.valueOf(ThumbnailsCacheManager.PREFIX_THUMBNAIL + getFile().getRemoteId()));
  233. if (thumbnail != null) {
  234. mImageView.setImageBitmap(thumbnail);
  235. mImageView.setVisibility(View.VISIBLE);
  236. mBitmap = thumbnail;
  237. } else {
  238. thumbnail = ThumbnailsCacheManager.mDefaultImg;
  239. }
  240. // generate new resized image
  241. if (ThumbnailsCacheManager.cancelPotentialThumbnailWork(getFile(), mImageView) &&
  242. mContainerActivity.getStorageManager() != null) {
  243. final ThumbnailsCacheManager.ResizedImageGenerationTask task =
  244. new ThumbnailsCacheManager.ResizedImageGenerationTask(PreviewImageFragment.this,
  245. mImageView,
  246. mContainerActivity.getStorageManager(),
  247. mContainerActivity.getStorageManager().getAccount());
  248. if (resizedImage == null) {
  249. resizedImage = thumbnail;
  250. }
  251. final ThumbnailsCacheManager.AsyncResizedImageDrawable asyncDrawable =
  252. new ThumbnailsCacheManager.AsyncResizedImageDrawable(
  253. MainApp.getAppContext().getResources(),
  254. resizedImage,
  255. task
  256. );
  257. mImageView.setImageDrawable(asyncDrawable);
  258. task.execute(getFile());
  259. }
  260. }
  261. mMultiView.setVisibility(View.GONE);
  262. if (getResources() != null) {
  263. mImageView.setBackgroundColor(getResources().getColor(R.color.black));
  264. }
  265. mImageView.setVisibility(View.VISIBLE);
  266. } else {
  267. mLoadBitmapTask = new LoadBitmapTask(mImageView);
  268. mLoadBitmapTask.execute(getFile());
  269. }
  270. } else {
  271. showErrorMessage(R.string.preview_image_error_no_local_file);
  272. }
  273. }
  274. @Override
  275. public void onStop() {
  276. Log_OC.d(TAG, "onStop starts");
  277. if (mLoadBitmapTask != null) {
  278. mLoadBitmapTask.cancel(true);
  279. mLoadBitmapTask = null;
  280. }
  281. super.onStop();
  282. }
  283. /**
  284. * {@inheritDoc}
  285. */
  286. @Override
  287. public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
  288. super.onCreateOptionsMenu(menu, inflater);
  289. inflater.inflate(R.menu.file_actions_menu, menu);
  290. }
  291. /**
  292. * {@inheritDoc}
  293. */
  294. @Override
  295. public void onPrepareOptionsMenu(Menu menu) {
  296. super.onPrepareOptionsMenu(menu);
  297. if (mContainerActivity.getStorageManager() != null && getFile() != null) {
  298. // Update the file
  299. setFile(mContainerActivity.getStorageManager().getFileById(getFile().getFileId()));
  300. FileMenuFilter mf = new FileMenuFilter(
  301. getFile(),
  302. mContainerActivity.getStorageManager().getAccount(),
  303. mContainerActivity,
  304. getActivity(),
  305. false
  306. );
  307. mf.filter(menu, true);
  308. }
  309. // additional restriction for this fragment
  310. // TODO allow renaming in PreviewImageFragment
  311. MenuItem item = menu.findItem(R.id.action_rename_file);
  312. if (item != null) {
  313. item.setVisible(false);
  314. item.setEnabled(false);
  315. }
  316. // additional restriction for this fragment
  317. // TODO allow refresh file in PreviewImageFragment
  318. item = menu.findItem(R.id.action_sync_file);
  319. if (item != null) {
  320. item.setVisible(false);
  321. item.setEnabled(false);
  322. }
  323. // additional restriction for this fragment
  324. item = menu.findItem(R.id.action_select_all);
  325. if (item != null) {
  326. item.setVisible(false);
  327. item.setEnabled(false);
  328. }
  329. // additional restriction for this fragment
  330. item = menu.findItem(R.id.action_move);
  331. if (item != null) {
  332. item.setVisible(false);
  333. item.setEnabled(false);
  334. }
  335. // additional restriction for this fragment
  336. item = menu.findItem(R.id.action_copy);
  337. if (item != null) {
  338. item.setVisible(false);
  339. item.setEnabled(false);
  340. }
  341. // additional restriction for this fragment
  342. item = menu.findItem(R.id.action_favorite);
  343. if (item != null) {
  344. item.setVisible(false);
  345. item.setEnabled(false);
  346. }
  347. // additional restriction for this fragment
  348. item = menu.findItem(R.id.action_unset_favorite);
  349. if (item != null) {
  350. item.setVisible(false);
  351. item.setEnabled(false);
  352. }
  353. if(getFile().isSharedWithMe() && !getFile().canReshare()){
  354. // additional restriction for this fragment
  355. item = menu.findItem(R.id.action_send_share_file);
  356. if(item != null){
  357. item.setVisible(false);
  358. item.setEnabled(false);
  359. }
  360. }
  361. }
  362. /**
  363. * {@inheritDoc}
  364. */
  365. @Override
  366. public boolean onOptionsItemSelected(MenuItem item) {
  367. switch (item.getItemId()) {
  368. case R.id.action_send_share_file:
  369. if(getFile().isSharedWithMe() && !getFile().canReshare()){
  370. Snackbar.make(getView(),
  371. R.string.resharing_is_not_allowed,
  372. Snackbar.LENGTH_LONG
  373. )
  374. .show();
  375. } else {
  376. mContainerActivity.getFileOperationsHelper().sendShareFile(getFile());
  377. }
  378. return true;
  379. case R.id.action_open_file_with:
  380. openFile();
  381. return true;
  382. case R.id.action_remove_file:
  383. RemoveFilesDialogFragment dialog = RemoveFilesDialogFragment.newInstance(getFile());
  384. dialog.show(getFragmentManager(), ConfirmationDialogFragment.FTAG_CONFIRMATION);
  385. return true;
  386. case R.id.action_see_details:
  387. seeDetails();
  388. return true;
  389. case R.id.action_download_file:
  390. case R.id.action_sync_file:
  391. mContainerActivity.getFileOperationsHelper().syncFile(getFile());
  392. return true;
  393. case R.id.action_set_as_wallpaper:
  394. mContainerActivity.getFileOperationsHelper().setPictureAs(getFile(), getImageView());
  395. return true;
  396. default:
  397. return super.onOptionsItemSelected(item);
  398. }
  399. }
  400. private void seeDetails() {
  401. mContainerActivity.showDetails(getFile());
  402. }
  403. @Override
  404. public void onResume() {
  405. super.onResume();
  406. if (getActivity() != null) {
  407. AnalyticsUtils.setCurrentScreenName(getActivity(), SCREEN_NAME, TAG);
  408. }
  409. }
  410. @Override
  411. public void onPause() {
  412. super.onPause();
  413. }
  414. @SuppressFBWarnings("Dm")
  415. @Override
  416. public void onDestroy() {
  417. if (mBitmap != null) {
  418. mBitmap.recycle();
  419. System.gc();
  420. // putting this in onStop() is just the same; the fragment is always destroyed by
  421. // {@link FragmentStatePagerAdapter} when the fragment in swiped further than the
  422. // valid offscreen distance, and onStop() is never called before than that
  423. }
  424. super.onDestroy();
  425. }
  426. /**
  427. * Opens the previewed image with an external application.
  428. */
  429. private void openFile() {
  430. mContainerActivity.getFileOperationsHelper().openFile(getFile());
  431. finish();
  432. }
  433. private class LoadBitmapTask extends AsyncTask<OCFile, Void, LoadImage> {
  434. /**
  435. * Weak reference to the target {@link ImageView} where the bitmap will be loaded into.
  436. *
  437. * Using a weak reference will avoid memory leaks if the target ImageView is retired from
  438. * memory before the load finishes.
  439. */
  440. private final WeakReference<ImageViewCustom> mImageViewRef;
  441. /**
  442. * Error message to show when a load fails
  443. */
  444. private int mErrorMessageId;
  445. /**
  446. * Constructor.
  447. *
  448. * @param imageView Target {@link ImageView} where the bitmap will be loaded into.
  449. */
  450. public LoadBitmapTask(ImageViewCustom imageView) {
  451. mImageViewRef = new WeakReference<>(imageView);
  452. }
  453. @Override
  454. protected LoadImage doInBackground(OCFile... params) {
  455. Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND + Process.THREAD_PRIORITY_MORE_FAVORABLE);
  456. Bitmap bitmapResult = null;
  457. Drawable drawableResult = null;
  458. if (params.length != 1) {
  459. return null;
  460. }
  461. OCFile ocFile = params[0];
  462. String storagePath = ocFile.getStoragePath();
  463. try {
  464. int maxDownScale = 3; // could be a parameter passed to doInBackground(...)
  465. Point screenSize = DisplayUtils.getScreenSize(getActivity());
  466. int minWidth = screenSize.x;
  467. int minHeight = screenSize.y;
  468. for (int i = 0; i < maxDownScale && bitmapResult == null && drawableResult == null; i++) {
  469. if (ocFile.getMimetype().equalsIgnoreCase("image/svg+xml")) {
  470. if (isCancelled()) {
  471. return null;
  472. }
  473. try {
  474. SVG svg = SVG.getFromInputStream(new FileInputStream(storagePath));
  475. drawableResult = new PictureDrawable(svg.renderToPicture());
  476. if (isCancelled()) {
  477. return new LoadImage(null, drawableResult, ocFile);
  478. }
  479. } catch (FileNotFoundException e) {
  480. mErrorMessageId = R.string.common_error_unknown;
  481. Log_OC.e(TAG, "File not found trying to load " + getFile().getStoragePath(), e);
  482. } catch (SVGParseException e) {
  483. mErrorMessageId = R.string.common_error_unknown;
  484. Log_OC.e(TAG, "Couldn't parse SVG " + getFile().getStoragePath(), e);
  485. }
  486. } else {
  487. if (isCancelled()) {
  488. return null;
  489. }
  490. try {
  491. bitmapResult = BitmapUtils.decodeSampledBitmapFromFile(storagePath, minWidth,
  492. minHeight);
  493. if (isCancelled()) {
  494. return new LoadImage(bitmapResult, null, ocFile);
  495. }
  496. if (bitmapResult == null) {
  497. mErrorMessageId = R.string.preview_image_error_unknown_format;
  498. Log_OC.e(TAG, "File could not be loaded as a bitmap: " + storagePath);
  499. break;
  500. } else {
  501. if (ocFile.getMimetype().equalsIgnoreCase("image/jpeg")) {
  502. // Rotate image, obeying exif tag.
  503. bitmapResult = BitmapUtils.rotateImage(bitmapResult, storagePath);
  504. }
  505. }
  506. } catch (OutOfMemoryError e) {
  507. mErrorMessageId = R.string.common_error_out_memory;
  508. if (i < maxDownScale - 1) {
  509. Log_OC.w(TAG, "Out of memory rendering file " + storagePath + " ; scaling down");
  510. minWidth = minWidth / 2;
  511. minHeight = minHeight / 2;
  512. } else {
  513. Log_OC.w(TAG, "Out of memory rendering file " + storagePath + " ; failing");
  514. }
  515. if (bitmapResult != null) {
  516. bitmapResult.recycle();
  517. }
  518. bitmapResult = null;
  519. }
  520. }
  521. }
  522. } catch (NoSuchFieldError e) {
  523. mErrorMessageId = R.string.common_error_unknown;
  524. Log_OC.e(TAG, "Error from access to non-existing field despite protection; file "
  525. + storagePath, e);
  526. } catch (Throwable t) {
  527. mErrorMessageId = R.string.common_error_unknown;
  528. Log_OC.e(TAG, "Unexpected error loading " + getFile().getStoragePath(), t);
  529. }
  530. return new LoadImage(bitmapResult, drawableResult, ocFile);
  531. }
  532. @Override
  533. protected void onCancelled(LoadImage result) {
  534. if (result != null && result.bitmap != null) {
  535. result.bitmap.recycle();
  536. }
  537. }
  538. @Override
  539. protected void onPostExecute(LoadImage result) {
  540. if (result.bitmap != null || result.drawable != null) {
  541. showLoadedImage(result);
  542. } else {
  543. showErrorMessage(mErrorMessageId);
  544. }
  545. if (result.bitmap != null && mBitmap != result.bitmap) {
  546. // unused bitmap, release it! (just in case)
  547. result.bitmap.recycle();
  548. }
  549. }
  550. private void showLoadedImage(LoadImage result) {
  551. final ImageViewCustom imageView = mImageViewRef.get();
  552. Bitmap bitmap = result.bitmap;
  553. if (imageView != null) {
  554. if (bitmap != null) {
  555. Log_OC.d(TAG, "Showing image with resolution " + bitmap.getWidth() + "x" +
  556. bitmap.getHeight());
  557. }
  558. if (result.ocFile.getMimetype().equalsIgnoreCase("image/png") ||
  559. result.ocFile.getMimetype().equals("image/svg+xml")) {
  560. if (getResources() != null) {
  561. Resources r = getResources();
  562. Drawable[] layers = new Drawable[2];
  563. layers[0] = r.getDrawable(R.color.white);
  564. Drawable bitmapDrawable;
  565. if (result.ocFile.getMimetype().equalsIgnoreCase("image/png") ) {
  566. bitmapDrawable = new BitmapDrawable(getResources(), bitmap);
  567. } else {
  568. bitmapDrawable = result.drawable;
  569. }
  570. layers[1] = bitmapDrawable;
  571. LayerDrawable layerDrawable = new LayerDrawable(layers);
  572. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  573. if (result.ocFile.getMimetype().equalsIgnoreCase("image/png")) {
  574. layerDrawable.setLayerHeight(0, convertDpToPixel(bitmap.getHeight(), getActivity()));
  575. layerDrawable.setLayerHeight(1, convertDpToPixel(bitmap.getHeight(), getActivity()));
  576. layerDrawable.setLayerWidth(0, convertDpToPixel(bitmap.getWidth(), getActivity()));
  577. layerDrawable.setLayerWidth(1, convertDpToPixel(bitmap.getWidth(), getActivity()));
  578. } else {
  579. layerDrawable.setLayerHeight(0, convertDpToPixel(bitmapDrawable.getIntrinsicHeight(),
  580. getActivity()));
  581. layerDrawable.setLayerHeight(1, convertDpToPixel(bitmapDrawable.getIntrinsicHeight(),
  582. getActivity()));
  583. layerDrawable.setLayerWidth(0, convertDpToPixel(bitmapDrawable.getIntrinsicWidth(),
  584. getActivity()));
  585. layerDrawable.setLayerWidth(1, convertDpToPixel(bitmapDrawable.getIntrinsicWidth(),
  586. getActivity()));
  587. }
  588. }
  589. imageView.setImageDrawable(layerDrawable);
  590. } else {
  591. imageView.setImageBitmap(bitmap);
  592. }
  593. }
  594. if (result.ocFile.getMimetype().equalsIgnoreCase("image/gif")) {
  595. imageView.setGIFImageFromStoragePath(result.ocFile.getStoragePath());
  596. } else if (!result.ocFile.getMimetype().equalsIgnoreCase("image/png") &&
  597. !result.ocFile.getMimetype().equals("image/svg+xml")) {
  598. imageView.setImageBitmap(bitmap);
  599. }
  600. imageView.setVisibility(View.VISIBLE);
  601. mBitmap = bitmap; // needs to be kept for recycling when not useful
  602. }
  603. mMultiView.setVisibility(View.GONE);
  604. if (getResources() != null) {
  605. mImageView.setBackgroundColor(getResources().getColor(R.color.black));
  606. }
  607. mImageView.setVisibility(View.VISIBLE);
  608. }
  609. }
  610. private void showErrorMessage(@StringRes int errorMessageId) {
  611. mImageView.setBackgroundColor(Color.TRANSPARENT);
  612. setMessageForMultiList(R.string.preview_sorry, errorMessageId, R.drawable.file_image);
  613. }
  614. private void setMultiListLoadingMessage() {
  615. if (mMultiView != null) {
  616. mMultiListHeadline.setText(R.string.file_list_loading);
  617. mMultiListMessage.setText("");
  618. mMultiListIcon.setVisibility(View.GONE);
  619. mMultiListProgress.setVisibility(View.VISIBLE);
  620. }
  621. }
  622. public void setMessageForMultiList(@StringRes int headline, @StringRes int message, @DrawableRes int icon) {
  623. if (mMultiListContainer != null && mMultiListMessage != null) {
  624. mMultiListHeadline.setText(headline);
  625. mMultiListMessage.setText(message);
  626. mMultiListIcon.setImageResource(icon);
  627. mMultiView.setBackgroundColor(Color.BLACK);
  628. mMultiListHeadline.setTextColor(getResources().getColor(R.color.standard_grey));
  629. mMultiListMessage.setTextColor(getResources().getColor(R.color.standard_grey));
  630. mMultiListMessage.setVisibility(View.VISIBLE);
  631. mMultiListIcon.setVisibility(View.VISIBLE);
  632. mMultiListProgress.setVisibility(View.GONE);
  633. }
  634. }
  635. public void setErrorPreviewMessage() {
  636. Snackbar.make(mMultiView, R.string.resized_image_not_possible, Snackbar.LENGTH_INDEFINITE)
  637. .setAction(R.string.common_yes, v -> downloadFile()).show();
  638. }
  639. public void setNoConnectionErrorMessage() {
  640. Snackbar.make(mMultiView, R.string.auth_no_net_conn_title, Snackbar.LENGTH_LONG).show();
  641. }
  642. /**
  643. * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewImageFragment}
  644. * to be previewed.
  645. *
  646. * @param file File to test if can be previewed.
  647. * @return 'True' if the file can be handled by the fragment.
  648. */
  649. public static boolean canBePreviewed(OCFile file) {
  650. return (file != null && MimeTypeUtil.isImage(file));
  651. }
  652. /**
  653. * Finishes the preview
  654. */
  655. private void finish() {
  656. Activity container = getActivity();
  657. container.finish();
  658. }
  659. private void toggleImageBackground() {
  660. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && getFile() != null
  661. && (getFile().getMimetype().equalsIgnoreCase("image/png") ||
  662. getFile().getMimetype().equalsIgnoreCase("image/svg+xml")) && getActivity() != null
  663. && getActivity() instanceof PreviewImageActivity && getResources() != null) {
  664. PreviewImageActivity previewImageActivity = (PreviewImageActivity) getActivity();
  665. if (mImageView.getDrawable() instanceof LayerDrawable) {
  666. LayerDrawable layerDrawable = (LayerDrawable) mImageView.getDrawable();
  667. Drawable layerOne;
  668. if (previewImageActivity.getSystemUIVisible()) {
  669. layerOne = getResources().getDrawable(R.color.white);
  670. } else {
  671. layerOne = getResources().getDrawable(R.drawable.backrepeat);
  672. }
  673. layerDrawable.setDrawableByLayerId(layerDrawable.getId(0), layerOne);
  674. mImageView.setImageDrawable(layerDrawable);
  675. mImageView.invalidate();
  676. }
  677. }
  678. }
  679. private static int convertDpToPixel(float dp, Context context) {
  680. Resources resources = context.getResources();
  681. DisplayMetrics metrics = resources.getDisplayMetrics();
  682. int px = (int) (dp * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT));
  683. return px;
  684. }
  685. public TouchImageViewCustom getImageView() {
  686. return mImageView;
  687. }
  688. private class LoadImage {
  689. private Bitmap bitmap;
  690. private Drawable drawable;
  691. private OCFile ocFile;
  692. public LoadImage(Bitmap bitmap, Drawable drawable, OCFile ocFile) {
  693. this.bitmap = bitmap;
  694. this.drawable = drawable;
  695. this.ocFile = ocFile;
  696. }
  697. }
  698. }