DisplayUtils.java 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751
  1. /*
  2. * Nextcloud Android client application
  3. *
  4. * @author Andy Scherzinger
  5. * @author Bartek Przybylski
  6. * @author David A. Velasco
  7. * Copyright (C) 2011 Bartek Przybylski
  8. * Copyright (C) 2015 ownCloud Inc.
  9. * Copyright (C) 2016 Andy Scherzinger
  10. *
  11. * This program is free software; you can redistribute it and/or
  12. * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
  13. * License as published by the Free Software Foundation; either
  14. * version 3 of the License, or any later version.
  15. *
  16. * This program is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
  20. *
  21. * You should have received a copy of the GNU Affero General Public
  22. * License along with this program. If not, see <http://www.gnu.org/licenses/>.
  23. */
  24. package com.owncloud.android.utils;
  25. import android.accounts.Account;
  26. import android.accounts.AccountManager;
  27. import android.annotation.SuppressLint;
  28. import android.app.Activity;
  29. import android.content.Context;
  30. import android.content.Intent;
  31. import android.content.res.Resources;
  32. import android.graphics.Bitmap;
  33. import android.graphics.Point;
  34. import android.graphics.drawable.Drawable;
  35. import android.graphics.drawable.PictureDrawable;
  36. import android.net.Uri;
  37. import android.text.Spannable;
  38. import android.text.SpannableStringBuilder;
  39. import android.text.TextUtils;
  40. import android.text.format.DateUtils;
  41. import android.text.style.StyleSpan;
  42. import android.util.DisplayMetrics;
  43. import android.util.Log;
  44. import android.view.View;
  45. import com.bumptech.glide.GenericRequestBuilder;
  46. import com.bumptech.glide.Glide;
  47. import com.bumptech.glide.load.engine.DiskCacheStrategy;
  48. import com.bumptech.glide.load.model.StreamEncoder;
  49. import com.bumptech.glide.load.resource.file.FileToStreamDecoder;
  50. import com.bumptech.glide.request.target.SimpleTarget;
  51. import com.bumptech.glide.request.target.Target;
  52. import com.caverock.androidsvg.SVG;
  53. import com.google.android.material.snackbar.Snackbar;
  54. import com.nextcloud.client.account.CurrentAccountProvider;
  55. import com.nextcloud.client.network.ClientFactory;
  56. import com.owncloud.android.MainApp;
  57. import com.owncloud.android.R;
  58. import com.owncloud.android.datamodel.ArbitraryDataProvider;
  59. import com.owncloud.android.datamodel.OCFile;
  60. import com.owncloud.android.datamodel.ThumbnailsCacheManager;
  61. import com.owncloud.android.lib.common.OwnCloudAccount;
  62. import com.owncloud.android.lib.common.utils.Log_OC;
  63. import com.owncloud.android.ui.TextDrawable;
  64. import com.owncloud.android.ui.activity.FileDisplayActivity;
  65. import com.owncloud.android.ui.events.SearchEvent;
  66. import com.owncloud.android.ui.fragment.OCFileListFragment;
  67. import com.owncloud.android.utils.glide.CustomGlideUriLoader;
  68. import com.owncloud.android.utils.svg.SvgDecoder;
  69. import com.owncloud.android.utils.svg.SvgDrawableTranscoder;
  70. import org.greenrobot.eventbus.EventBus;
  71. import org.parceler.Parcels;
  72. import java.io.BufferedReader;
  73. import java.io.IOException;
  74. import java.io.InputStream;
  75. import java.io.InputStreamReader;
  76. import java.lang.reflect.Constructor;
  77. import java.lang.reflect.Method;
  78. import java.math.BigDecimal;
  79. import java.net.IDN;
  80. import java.nio.charset.Charset;
  81. import java.text.DateFormat;
  82. import java.util.Collection;
  83. import java.util.Date;
  84. import java.util.HashMap;
  85. import java.util.HashSet;
  86. import java.util.Locale;
  87. import java.util.Map;
  88. import java.util.Set;
  89. import androidx.annotation.NonNull;
  90. import androidx.annotation.Nullable;
  91. import androidx.annotation.StringRes;
  92. import androidx.appcompat.widget.AppCompatDrawableManager;
  93. /**
  94. * A helper class for UI/display related operations.
  95. */
  96. public final class DisplayUtils {
  97. private static final String TAG = DisplayUtils.class.getSimpleName();
  98. private static final String[] sizeSuffixes = {"B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"};
  99. private static final int[] sizeScales = {0, 0, 1, 1, 1, 2, 2, 2, 2};
  100. private static final int RELATIVE_THRESHOLD_WARNING = 80;
  101. private static final String MIME_TYPE_UNKNOWN = "Unknown type";
  102. private static final String HTTP_PROTOCOL = "http://";
  103. private static final String HTTPS_PROTOCOL = "https://";
  104. private static final String TWITTER_HANDLE_PREFIX = "@";
  105. private static final int MIMETYPE_PARTS_COUNT = 2;
  106. private static final int BYTE_SIZE_DIVIDER = 1024;
  107. private static final double BYTE_SIZE_DIVIDER_DOUBLE = 1024.0;
  108. private static final int DATE_TIME_PARTS_SIZE = 2;
  109. private static Map<String, String> mimeType2HumanReadable;
  110. static {
  111. mimeType2HumanReadable = new HashMap<>();
  112. // images
  113. mimeType2HumanReadable.put("image/jpeg", "JPEG image");
  114. mimeType2HumanReadable.put("image/jpg", "JPEG image");
  115. mimeType2HumanReadable.put("image/png", "PNG image");
  116. mimeType2HumanReadable.put("image/bmp", "Bitmap image");
  117. mimeType2HumanReadable.put("image/gif", "GIF image");
  118. mimeType2HumanReadable.put("image/svg+xml", "JPEG image");
  119. mimeType2HumanReadable.put("image/tiff", "TIFF image");
  120. // music
  121. mimeType2HumanReadable.put("audio/mpeg", "MP3 music file");
  122. mimeType2HumanReadable.put("application/ogg", "OGG music file");
  123. }
  124. private DisplayUtils() {
  125. // utility class -> private constructor
  126. }
  127. /**
  128. * Converts the file size in bytes to human readable output.
  129. * <ul>
  130. * <li>appends a size suffix, e.g. B, KB, MB etc.</li>
  131. * <li>rounds the size based on the suffix to 0,1 or 2 decimals</li>
  132. * </ul>
  133. *
  134. * @param bytes Input file size
  135. * @return something readable like "12 MB", {@link com.owncloud.android.R.string#common_pending} for negative
  136. * byte values
  137. */
  138. public static String bytesToHumanReadable(long bytes) {
  139. if (bytes < 0) {
  140. return MainApp.getAppContext().getString(R.string.common_pending);
  141. } else {
  142. double result = bytes;
  143. int suffixIndex = 0;
  144. while (result > BYTE_SIZE_DIVIDER && suffixIndex < sizeSuffixes.length) {
  145. result /= BYTE_SIZE_DIVIDER_DOUBLE;
  146. suffixIndex++;
  147. }
  148. return new BigDecimal(String.valueOf(result)).setScale(
  149. sizeScales[suffixIndex], BigDecimal.ROUND_HALF_UP) + " " + sizeSuffixes[suffixIndex];
  150. }
  151. }
  152. /**
  153. * Converts MIME types like "image/jpg" to more end user friendly output
  154. * like "JPG image".
  155. *
  156. * @param mimetype MIME type to convert
  157. * @return A human friendly version of the MIME type, {@link #MIME_TYPE_UNKNOWN} if it can't be converted
  158. */
  159. public static String convertMIMEtoPrettyPrint(String mimetype) {
  160. final String humanReadableMime = mimeType2HumanReadable.get(mimetype);
  161. if (humanReadableMime != null) {
  162. return humanReadableMime;
  163. }
  164. if (mimetype.split("/").length >= MIMETYPE_PARTS_COUNT) {
  165. return mimetype.split("/")[1].toUpperCase(Locale.getDefault()) + " file";
  166. }
  167. return MIME_TYPE_UNKNOWN;
  168. }
  169. /**
  170. * Converts Unix time to human readable format
  171. *
  172. * @param milliseconds that have passed since 01/01/1970
  173. * @return The human readable time for the users locale
  174. */
  175. public static String unixTimeToHumanReadable(long milliseconds) {
  176. Date date = new Date(milliseconds);
  177. DateFormat df = DateFormat.getDateTimeInstance();
  178. return df.format(date);
  179. }
  180. /**
  181. * beautifies a given URL by removing any http/https protocol prefix.
  182. *
  183. * @param url to be beautified url
  184. * @return beautified url
  185. */
  186. public static String beautifyURL(@Nullable String url) {
  187. if (TextUtils.isEmpty(url)) {
  188. return "";
  189. }
  190. if (url.length() >= 7 && HTTP_PROTOCOL.equalsIgnoreCase(url.substring(0, 7))) {
  191. return url.substring(HTTP_PROTOCOL.length()).trim();
  192. }
  193. if (url.length() >= 8 && HTTPS_PROTOCOL.equalsIgnoreCase(url.substring(0, 8))) {
  194. return url.substring(HTTPS_PROTOCOL.length()).trim();
  195. }
  196. return url.trim();
  197. }
  198. /**
  199. * beautifies a given twitter handle by prefixing it with an @ in case it is missing.
  200. *
  201. * @param handle to be beautified twitter handle
  202. * @return beautified twitter handle
  203. */
  204. public static String beautifyTwitterHandle(@Nullable String handle) {
  205. if (handle != null) {
  206. String trimmedHandle = handle.trim();
  207. if (TextUtils.isEmpty(trimmedHandle)) {
  208. return "";
  209. }
  210. if (trimmedHandle.startsWith(TWITTER_HANDLE_PREFIX)) {
  211. return trimmedHandle;
  212. } else {
  213. return TWITTER_HANDLE_PREFIX + trimmedHandle;
  214. }
  215. } else {
  216. return "";
  217. }
  218. }
  219. /**
  220. * Converts an internationalized domain name (IDN) in an URL to and from ASCII/Unicode.
  221. *
  222. * @param url the URL where the domain name should be converted
  223. * @param toASCII if true converts from Unicode to ASCII, if false converts from ASCII to Unicode
  224. * @return the URL containing the converted domain name
  225. */
  226. public static String convertIdn(String url, boolean toASCII) {
  227. String urlNoDots = url;
  228. String dots = "";
  229. while (urlNoDots.length() > 0 && urlNoDots.charAt(0) == '.') {
  230. urlNoDots = url.substring(1);
  231. dots = dots + ".";
  232. }
  233. // Find host name after '//' or '@'
  234. int hostStart = 0;
  235. if (urlNoDots.contains("//")) {
  236. hostStart = url.indexOf("//") + "//".length();
  237. } else if (url.contains("@")) {
  238. hostStart = url.indexOf('@') + "@".length();
  239. }
  240. int hostEnd = url.substring(hostStart).indexOf("/");
  241. // Handle URL which doesn't have a path (path is implicitly '/')
  242. hostEnd = hostEnd == -1 ? urlNoDots.length() : hostStart + hostEnd;
  243. String host = urlNoDots.substring(hostStart, hostEnd);
  244. host = toASCII ? IDN.toASCII(host) : IDN.toUnicode(host);
  245. return dots + urlNoDots.substring(0, hostStart) + host + urlNoDots.substring(hostEnd);
  246. }
  247. /**
  248. * creates the display string for an account.
  249. *
  250. * @param context the actual activity
  251. * @param savedAccount the actual, saved account
  252. * @param accountName the account name
  253. * @param fallbackString String to be used in case of an error
  254. * @return the display string for the given account data
  255. */
  256. public static String getAccountNameDisplayText(Context context, Account savedAccount, String accountName, String
  257. fallbackString) {
  258. try {
  259. return new OwnCloudAccount(savedAccount, context).getDisplayName()
  260. + "@"
  261. + convertIdn(accountName.substring(accountName.lastIndexOf('@') + 1), false);
  262. } catch (Exception e) {
  263. Log_OC.w(TAG, "Couldn't get display name for account, using old style");
  264. return fallbackString;
  265. }
  266. }
  267. /**
  268. * converts an array of accounts into a set of account names.
  269. *
  270. * @param accountList the account array
  271. * @return set of account names
  272. */
  273. public static Set<String> toAccountNameSet(Collection<Account> accountList) {
  274. Set<String> actualAccounts = new HashSet<>(accountList.size());
  275. for (Account account : accountList) {
  276. actualAccounts.add(account.name);
  277. }
  278. return actualAccounts;
  279. }
  280. /**
  281. * calculates the relative time string based on the given modification timestamp.
  282. *
  283. * @param context the app's context
  284. * @param modificationTimestamp the UNIX timestamp of the file modification time in milliseconds.
  285. * @return a relative time string
  286. */
  287. public static CharSequence getRelativeTimestamp(Context context, long modificationTimestamp) {
  288. return getRelativeDateTimeString(context, modificationTimestamp, DateUtils.SECOND_IN_MILLIS,
  289. DateUtils.WEEK_IN_MILLIS, 0);
  290. }
  291. /**
  292. * determines the info level color based on {@link #RELATIVE_THRESHOLD_WARNING}.
  293. *
  294. * @param context the app's context
  295. * @param relative relative value for which the info level color should be looked up
  296. * @return info level color
  297. */
  298. public static int getRelativeInfoColor(Context context, int relative) {
  299. if (relative < RELATIVE_THRESHOLD_WARNING) {
  300. return ThemeUtils.primaryColor(context, true);
  301. } else {
  302. return context.getResources().getColor(R.color.infolevel_warning);
  303. }
  304. }
  305. public static CharSequence getRelativeDateTimeString(Context c, long time, long minResolution,
  306. long transitionResolution, int flags) {
  307. CharSequence dateString = "";
  308. // in Future
  309. if (time > System.currentTimeMillis()) {
  310. return DisplayUtils.unixTimeToHumanReadable(time);
  311. }
  312. // < 60 seconds -> seconds ago
  313. else if ((System.currentTimeMillis() - time) < 60 * 1000 && minResolution == DateUtils.SECOND_IN_MILLIS) {
  314. return c.getString(R.string.file_list_seconds_ago);
  315. } else {
  316. dateString = DateUtils.getRelativeDateTimeString(c, time, minResolution, transitionResolution, flags);
  317. }
  318. String[] parts = dateString.toString().split(",");
  319. if (parts.length == DATE_TIME_PARTS_SIZE) {
  320. if (parts[1].contains(":") && !parts[0].contains(":")) {
  321. return parts[0];
  322. } else if (parts[0].contains(":") && !parts[1].contains(":")) {
  323. return parts[1];
  324. }
  325. }
  326. // dateString contains unexpected format. fallback: use relative date time string from android api as is.
  327. return dateString.toString();
  328. }
  329. /**
  330. * Update the passed path removing the last "/" if it is not the root folder.
  331. *
  332. * @param path the path to be trimmed
  333. */
  334. public static String getPathWithoutLastSlash(String path) {
  335. // Remove last slash from path
  336. if (path.length() > 1 && path.charAt(path.length() - 1) == OCFile.PATH_SEPARATOR.charAt(0)) {
  337. return path.substring(0, path.length() - 1);
  338. }
  339. return path;
  340. }
  341. /**
  342. * Gets the screen size in pixels.
  343. *
  344. * @param caller Activity calling; needed to get access to the {@link android.view.WindowManager}
  345. * @return Size in pixels of the screen, or default {@link Point} if caller is null
  346. */
  347. public static Point getScreenSize(Activity caller) {
  348. Point size = new Point();
  349. if (caller != null) {
  350. caller.getWindowManager().getDefaultDisplay().getSize(size);
  351. }
  352. return size;
  353. }
  354. /**
  355. * styling of given spanText within a given text.
  356. *
  357. * @param text the non styled complete text
  358. * @param spanText the to be styled text
  359. * @param style the style to be applied
  360. */
  361. public static SpannableStringBuilder createTextWithSpan(String text, String spanText, StyleSpan style) {
  362. if (text == null) {
  363. return null;
  364. }
  365. SpannableStringBuilder sb = new SpannableStringBuilder(text);
  366. if(spanText == null) {
  367. return sb;
  368. }
  369. int start = text.lastIndexOf(spanText);
  370. if (start < 0) {
  371. return sb;
  372. }
  373. int end = start + spanText.length();
  374. sb.setSpan(style, start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  375. return sb;
  376. }
  377. public interface AvatarGenerationListener {
  378. void avatarGenerated(Drawable avatarDrawable, Object callContext);
  379. boolean shouldCallGeneratedCallback(String tag, Object callContext);
  380. }
  381. /**
  382. * fetches and sets the avatar of the given account in the passed callContext
  383. *
  384. * @param account the account to be used to connect to server
  385. * @param avatarRadius the avatar radius
  386. * @param resources reference for density information
  387. * @param callContext which context is called to set the generated avatar
  388. */
  389. public static void setAvatar(@NonNull Account account, AvatarGenerationListener listener,
  390. float avatarRadius, Resources resources, Object callContext, Context context) {
  391. AccountManager accountManager = AccountManager.get(context);
  392. String userId = accountManager.getUserData(account,
  393. com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_USER_ID);
  394. setAvatar(account, userId, listener, avatarRadius, resources, callContext, context);
  395. }
  396. /**
  397. * fetches and sets the avatar of the given account in the passed callContext
  398. *
  399. * @param account the account to be used to connect to server
  400. * @param userId the userId which avatar should be set
  401. * @param avatarRadius the avatar radius
  402. * @param resources reference for density information
  403. * @param callContext which context is called to set the generated avatar
  404. */
  405. public static void setAvatar(@NonNull Account account, @NonNull String userId, AvatarGenerationListener listener,
  406. float avatarRadius, Resources resources, Object callContext, Context context) {
  407. setAvatar(account, userId, userId, listener, avatarRadius, resources, callContext, context);
  408. }
  409. /**
  410. * fetches and sets the avatar of the given account in the passed callContext
  411. *
  412. * @param account the account to be used to connect to server
  413. * @param userId the userId which avatar should be set
  414. * @param displayName displayName used to generate avatar with first char, only used as fallback
  415. * @param avatarRadius the avatar radius
  416. * @param resources reference for density information
  417. * @param callContext which context is called to set the generated avatar
  418. */
  419. public static void setAvatar(@NonNull Account account,
  420. @NonNull String userId,
  421. String displayName,
  422. AvatarGenerationListener listener,
  423. float avatarRadius,
  424. Resources resources,
  425. Object callContext,
  426. Context context) {
  427. if (callContext instanceof View) {
  428. ((View) callContext).setContentDescription(String.valueOf(account.hashCode()));
  429. }
  430. ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(context.getContentResolver());
  431. String serverName = account.name.substring(account.name.lastIndexOf('@') + 1);
  432. String eTag = arbitraryDataProvider.getValue(userId + "@" + serverName, ThumbnailsCacheManager.AVATAR);
  433. String avatarKey = "a_" + userId + "_" + serverName + "_" + eTag;
  434. // first show old one
  435. Drawable avatar = BitmapUtils.bitmapToCircularBitmapDrawable(resources,
  436. ThumbnailsCacheManager.getBitmapFromDiskCache(avatarKey));
  437. // if no one exists, show colored icon with initial char
  438. if (avatar == null) {
  439. try {
  440. avatar = TextDrawable.createAvatarByUserId(displayName, avatarRadius);
  441. } catch (Exception e) {
  442. Log_OC.e(TAG, "Error calculating RGB value for active account icon.", e);
  443. avatar = resources.getDrawable(R.drawable.account_circle_white);
  444. }
  445. }
  446. // check for new avatar, eTag is compared, so only new one is downloaded
  447. if (ThumbnailsCacheManager.cancelPotentialAvatarWork(userId, callContext)) {
  448. final ThumbnailsCacheManager.AvatarGenerationTask task =
  449. new ThumbnailsCacheManager.AvatarGenerationTask(listener, callContext, account, resources,
  450. avatarRadius, userId, serverName, context);
  451. final ThumbnailsCacheManager.AsyncAvatarDrawable asyncDrawable =
  452. new ThumbnailsCacheManager.AsyncAvatarDrawable(resources, avatar, task);
  453. listener.avatarGenerated(asyncDrawable, callContext);
  454. task.execute(userId);
  455. }
  456. }
  457. public static void downloadIcon(CurrentAccountProvider currentAccountProvider,
  458. ClientFactory clientFactory,
  459. Context context,
  460. String iconUrl,
  461. SimpleTarget imageView,
  462. int placeholder,
  463. int width,
  464. int height) {
  465. try {
  466. if (iconUrl.endsWith(".svg")) {
  467. downloadSVGIcon(currentAccountProvider, clientFactory, context, iconUrl, imageView, placeholder, width,
  468. height);
  469. } else {
  470. downloadPNGIcon(context, iconUrl, imageView, placeholder);
  471. }
  472. } catch (Exception e) {
  473. Log_OC.d(TAG, "not setting image as activity is destroyed");
  474. }
  475. }
  476. private static void downloadPNGIcon(Context context, String iconUrl, SimpleTarget imageView, int placeholder) {
  477. Glide
  478. .with(context)
  479. .load(iconUrl)
  480. .centerCrop()
  481. .placeholder(placeholder)
  482. .error(placeholder)
  483. .crossFade()
  484. .into(imageView);
  485. }
  486. private static void downloadSVGIcon(CurrentAccountProvider currentAccountProvider,
  487. ClientFactory clientFactory,
  488. Context context,
  489. String iconUrl,
  490. SimpleTarget imageView,
  491. int placeholder,
  492. int width,
  493. int height) {
  494. GenericRequestBuilder<Uri, InputStream, SVG, PictureDrawable> requestBuilder = Glide.with(context)
  495. .using(new CustomGlideUriLoader(currentAccountProvider, clientFactory), InputStream.class)
  496. .from(Uri.class)
  497. .as(SVG.class)
  498. .transcode(new SvgDrawableTranscoder(), PictureDrawable.class)
  499. .sourceEncoder(new StreamEncoder())
  500. .cacheDecoder(new FileToStreamDecoder<>(new SvgDecoder(height, width)))
  501. .decoder(new SvgDecoder(height, width))
  502. .placeholder(placeholder)
  503. .error(placeholder)
  504. .animate(android.R.anim.fade_in);
  505. Uri uri = Uri.parse(iconUrl);
  506. requestBuilder
  507. .diskCacheStrategy(DiskCacheStrategy.SOURCE)
  508. .load(uri)
  509. .into(imageView);
  510. }
  511. public static Bitmap downloadImageSynchronous(Context context, String imageUrl) {
  512. try {
  513. return Glide.with(context)
  514. .load(imageUrl)
  515. .asBitmap()
  516. .diskCacheStrategy(DiskCacheStrategy.NONE)
  517. .skipMemoryCache(true)
  518. .into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
  519. .get();
  520. } catch (Exception e) {
  521. Log_OC.e(TAG, "Could not download image " + imageUrl);
  522. return null;
  523. }
  524. }
  525. private static void switchToSearchFragment(Activity activity, SearchEvent event) {
  526. if (activity instanceof FileDisplayActivity) {
  527. EventBus.getDefault().post(event);
  528. } else {
  529. Intent recentlyAddedIntent = new Intent(activity.getBaseContext(), FileDisplayActivity.class);
  530. recentlyAddedIntent.putExtra(OCFileListFragment.SEARCH_EVENT, Parcels.wrap(event));
  531. recentlyAddedIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  532. activity.startActivity(recentlyAddedIntent);
  533. }
  534. }
  535. /**
  536. * Get String data from a InputStream
  537. *
  538. * @param inputStream The File InputStream
  539. */
  540. public static String getData(InputStream inputStream) {
  541. BufferedReader buffreader = new BufferedReader(new InputStreamReader(inputStream, Charset.defaultCharset()));
  542. String line;
  543. StringBuilder text = new StringBuilder();
  544. try {
  545. while ((line = buffreader.readLine()) != null) {
  546. text.append(line);
  547. text.append('\n');
  548. }
  549. } catch (IOException e) {
  550. Log_OC.e(TAG, e.getMessage());
  551. }
  552. return text.toString();
  553. }
  554. /**
  555. * Show a temporary message in a {@link Snackbar} bound to the content view.
  556. *
  557. * @param activity The {@link Activity} to which's content view the {@link Snackbar} is bound.
  558. * @param messageResource The resource id of the string resource to use. Can be formatted text.
  559. */
  560. public static void showSnackMessage(Activity activity, @StringRes int messageResource) {
  561. showSnackMessage(activity.findViewById(android.R.id.content), messageResource);
  562. }
  563. /**
  564. * Show a temporary message in a {@link Snackbar} bound to the content view.
  565. *
  566. * @param activity The {@link Activity} to which's content view the {@link Snackbar} is bound.
  567. * @param message Message to show.
  568. */
  569. public static void showSnackMessage(Activity activity, String message) {
  570. Snackbar.make(activity.findViewById(android.R.id.content), message, Snackbar.LENGTH_LONG).show();
  571. }
  572. /**
  573. * Show a temporary message in a {@link Snackbar} bound to the given view.
  574. *
  575. * @param view The view the {@link Snackbar} is bound to.
  576. * @param messageResource The resource id of the string resource to use. Can be formatted text.
  577. */
  578. public static void showSnackMessage(View view, @StringRes int messageResource) {
  579. Snackbar.make(view, messageResource, Snackbar.LENGTH_LONG).show();
  580. }
  581. /**
  582. * Show a temporary message in a {@link Snackbar} bound to the given view.
  583. *
  584. * @param view The view the {@link Snackbar} is bound to.
  585. * @param message The message.
  586. */
  587. public static void showSnackMessage(View view, String message) {
  588. Snackbar.make(view, message, Snackbar.LENGTH_LONG).show();
  589. }
  590. /**
  591. * create a temporary message in a {@link Snackbar} bound to the given view.
  592. *
  593. * @param view The view the {@link Snackbar} is bound to.
  594. * @param messageResource The resource id of the string resource to use. Can be formatted text.
  595. */
  596. public static Snackbar createSnackbar(View view, @StringRes int messageResource, int length) {
  597. return Snackbar.make(view, messageResource, length);
  598. }
  599. /**
  600. * Show a temporary message in a {@link Snackbar} bound to the content view.
  601. *
  602. * @param activity The {@link Activity} to which's content view the {@link Snackbar} is bound.
  603. * @param messageResource The resource id of the string resource to use. Can be formatted text.
  604. * @param formatArgs The format arguments that will be used for substitution.
  605. */
  606. public static void showSnackMessage(Activity activity, @StringRes int messageResource, Object... formatArgs) {
  607. showSnackMessage(activity, activity.findViewById(android.R.id.content), messageResource, formatArgs);
  608. }
  609. /**
  610. * Show a temporary message in a {@link Snackbar} bound to the content view.
  611. *
  612. * @param context to load resources.
  613. * @param view The content view the {@link Snackbar} is bound to.
  614. * @param messageResource The resource id of the string resource to use. Can be formatted text.
  615. * @param formatArgs The format arguments that will be used for substitution.
  616. */
  617. public static void showSnackMessage(Context context, View view, @StringRes int messageResource, Object... formatArgs) {
  618. Snackbar.make(
  619. view,
  620. String.format(context.getString(messageResource, formatArgs)),
  621. Snackbar.LENGTH_LONG)
  622. .show();
  623. }
  624. // Solution inspired by https://stackoverflow.com/questions/34936590/why-isnt-my-vector-drawable-scaling-as-expected
  625. // Copied from https://raw.githubusercontent.com/nextcloud/talk-android/8ec8606bc61878e87e3ac8ad32c8b72d4680013c/app/src/main/java/com/nextcloud/talk/utils/DisplayUtils.java
  626. // under GPL3
  627. public static void useCompatVectorIfNeeded() {
  628. try {
  629. @SuppressLint("RestrictedApi") AppCompatDrawableManager drawableManager = AppCompatDrawableManager.get();
  630. Class<?> inflateDelegateClass = Class.forName("android.support.v7.widget.AppCompatDrawableManager$InflateDelegate");
  631. Class<?> vdcInflateDelegateClass = Class.forName("android.support.v7.widget.AppCompatDrawableManager$VdcInflateDelegate");
  632. Constructor<?> constructor = vdcInflateDelegateClass.getDeclaredConstructor();
  633. constructor.setAccessible(true);
  634. Object vdcInflateDelegate = constructor.newInstance();
  635. Class<?> args[] = {String.class, inflateDelegateClass};
  636. Method addDelegate = AppCompatDrawableManager.class.getDeclaredMethod("addDelegate", args);
  637. addDelegate.setAccessible(true);
  638. addDelegate.invoke(drawableManager, "vector", vdcInflateDelegate);
  639. } catch (Exception e) {
  640. Log.e(TAG, "Failed to use reflection to enable proper vector scaling");
  641. }
  642. }
  643. public static int convertDpToPixel(float dp, Context context) {
  644. Resources resources = context.getResources();
  645. DisplayMetrics metrics = resources.getDisplayMetrics();
  646. return (int) (dp * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT));
  647. }
  648. static public void showServerOutdatedSnackbar(Activity activity, int length) {
  649. Snackbar.make(activity.findViewById(android.R.id.content),
  650. R.string.outdated_server, length)
  651. .setAction(R.string.dismiss, v -> {
  652. })
  653. .show();
  654. }
  655. static public void startLinkIntent(Activity activity, @StringRes int link) {
  656. Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(activity.getString(link)));
  657. DisplayUtils.startIntentIfAppAvailable(intent, activity, R.string.no_browser_available);
  658. }
  659. static public void startIntentIfAppAvailable(Intent intent, Activity activity, @StringRes int error) {
  660. if (intent.resolveActivity(activity.getPackageManager()) != null) {
  661. activity.startActivity(intent);
  662. } else {
  663. DisplayUtils.showSnackMessage(activity, error);
  664. }
  665. }
  666. }