PreviewImageFragment.java 30 KB

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