DisplayUtils.java 32 KB

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