PreviewImageFragment.java 31 KB

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