DisplayUtils.java 32 KB

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