DisplayUtils.java 31 KB

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