DisplayUtils.java 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  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. public static String convertIdn(String url, boolean toASCII) {
  223. String urlNoDots = url;
  224. String dots = "";
  225. while (urlNoDots.startsWith(".")) {
  226. urlNoDots = url.substring(1);
  227. dots = dots + ".";
  228. }
  229. // Find host name after '//' or '@'
  230. int hostStart = 0;
  231. if (urlNoDots.contains("//")) {
  232. hostStart = url.indexOf("//") + "//".length();
  233. } else if (url.contains("@")) {
  234. hostStart = url.indexOf('@') + "@".length();
  235. }
  236. int hostEnd = url.substring(hostStart).indexOf("/");
  237. // Handle URL which doesn't have a path (path is implicitly '/')
  238. hostEnd = hostEnd == -1 ? urlNoDots.length() : hostStart + hostEnd;
  239. String host = urlNoDots.substring(hostStart, hostEnd);
  240. host = toASCII ? IDN.toASCII(host) : IDN.toUnicode(host);
  241. return dots + urlNoDots.substring(0, hostStart) + host + urlNoDots.substring(hostEnd);
  242. }
  243. /**
  244. * creates the display string for an account.
  245. *
  246. * @param context the actual activity
  247. * @param savedAccount the actual, saved account
  248. * @param accountName the account name
  249. * @param fallbackString String to be used in case of an error
  250. * @return the display string for the given account data
  251. */
  252. public static String getAccountNameDisplayText(Context context, Account savedAccount, String accountName, String
  253. fallbackString) {
  254. try {
  255. return new OwnCloudAccount(savedAccount, context).getDisplayName()
  256. + "@"
  257. + convertIdn(accountName.substring(accountName.lastIndexOf('@') + 1), false);
  258. } catch (Exception e) {
  259. Log_OC.w(TAG, "Couldn't get display name for account, using old style");
  260. return fallbackString;
  261. }
  262. }
  263. /**
  264. * converts an array of accounts into a set of account names.
  265. *
  266. * @param accountList the account array
  267. * @return set of account names
  268. */
  269. public static Set<String> toAccountNameSet(Collection<Account> accountList) {
  270. Set<String> actualAccounts = new HashSet<>(accountList.size());
  271. for (Account account : accountList) {
  272. actualAccounts.add(account.name);
  273. }
  274. return actualAccounts;
  275. }
  276. /**
  277. * calculates the relative time string based on the given modification timestamp.
  278. *
  279. * @param context the app's context
  280. * @param modificationTimestamp the UNIX timestamp of the file modification time in milliseconds.
  281. * @return a relative time string
  282. */
  283. public static CharSequence getRelativeTimestamp(Context context, long modificationTimestamp) {
  284. return getRelativeDateTimeString(context, modificationTimestamp, DateUtils.SECOND_IN_MILLIS,
  285. DateUtils.WEEK_IN_MILLIS, 0);
  286. }
  287. /**
  288. * determines the info level color based on {@link #RELATIVE_THRESHOLD_WARNING}.
  289. *
  290. * @param context the app's context
  291. * @param relative relative value for which the info level color should be looked up
  292. * @return info level color
  293. */
  294. public static int getRelativeInfoColor(Context context, int relative) {
  295. if (relative < RELATIVE_THRESHOLD_WARNING) {
  296. return ThemeUtils.primaryColor(context, true);
  297. } else {
  298. return context.getResources().getColor(R.color.infolevel_warning);
  299. }
  300. }
  301. public static CharSequence getRelativeDateTimeString(Context c, long time, long minResolution,
  302. long transitionResolution, int flags) {
  303. CharSequence dateString = "";
  304. // in Future
  305. if (time > System.currentTimeMillis()) {
  306. return DisplayUtils.unixTimeToHumanReadable(time);
  307. }
  308. // < 60 seconds -> seconds ago
  309. else if ((System.currentTimeMillis() - time) < 60 * 1000 && minResolution == DateUtils.SECOND_IN_MILLIS) {
  310. return c.getString(R.string.file_list_seconds_ago);
  311. } else {
  312. dateString = DateUtils.getRelativeDateTimeString(c, time, minResolution, transitionResolution, flags);
  313. }
  314. String[] parts = dateString.toString().split(",");
  315. if (parts.length == 2) {
  316. if (parts[1].contains(":") && !parts[0].contains(":")) {
  317. return parts[0];
  318. } else if (parts[0].contains(":") && !parts[1].contains(":")) {
  319. return parts[1];
  320. }
  321. }
  322. // dateString contains unexpected format. fallback: use relative date time string from android api as is.
  323. return dateString.toString();
  324. }
  325. /**
  326. * Update the passed path removing the last "/" if it is not the root folder.
  327. *
  328. * @param path the path to be trimmed
  329. */
  330. public static String getPathWithoutLastSlash(String path) {
  331. // Remove last slash from path
  332. if (path.length() > 1 && path.charAt(path.length() - 1) == OCFile.PATH_SEPARATOR.charAt(0)) {
  333. return path.substring(0, path.length() - 1);
  334. }
  335. return path;
  336. }
  337. /**
  338. * Gets the screen size in pixels.
  339. *
  340. * @param caller Activity calling; needed to get access to the {@link android.view.WindowManager}
  341. * @return Size in pixels of the screen, or default {@link Point} if caller is null
  342. */
  343. public static Point getScreenSize(Activity caller) {
  344. Point size = new Point();
  345. if (caller != null) {
  346. caller.getWindowManager().getDefaultDisplay().getSize(size);
  347. }
  348. return size;
  349. }
  350. /**
  351. * styling of given spanText within a given text.
  352. *
  353. * @param text the non styled complete text
  354. * @param spanText the to be styled text
  355. * @param style the style to be applied
  356. */
  357. public static SpannableStringBuilder createTextWithSpan(String text, String spanText, StyleSpan style) {
  358. if (text == null) {
  359. return null;
  360. }
  361. SpannableStringBuilder sb = new SpannableStringBuilder(text);
  362. if(spanText == null) {
  363. return sb;
  364. }
  365. int start = text.lastIndexOf(spanText);
  366. if (start < 0) {
  367. return sb;
  368. }
  369. int end = start + spanText.length();
  370. sb.setSpan(style, start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  371. return sb;
  372. }
  373. public interface AvatarGenerationListener {
  374. void avatarGenerated(Drawable avatarDrawable, Object callContext);
  375. boolean shouldCallGeneratedCallback(String tag, Object callContext);
  376. }
  377. /**
  378. * fetches and sets the avatar of the given account in the passed callContext
  379. *
  380. * @param account the account to be used to connect to server
  381. * @param avatarRadius the avatar radius
  382. * @param resources reference for density information
  383. * @param callContext which context is called to set the generated avatar
  384. */
  385. public static void setAvatar(@NonNull Account account, AvatarGenerationListener listener,
  386. float avatarRadius, Resources resources, Object callContext, Context context) {
  387. AccountManager accountManager = AccountManager.get(context);
  388. String userId = accountManager.getUserData(account,
  389. com.owncloud.android.lib.common.accounts.AccountUtils.Constants.KEY_USER_ID);
  390. setAvatar(account, userId, listener, avatarRadius, resources, callContext, context);
  391. }
  392. /**
  393. * fetches and sets the avatar of the given account in the passed callContext
  394. *
  395. * @param account the account to be used to connect to server
  396. * @param userId the userId which avatar should be set
  397. * @param avatarRadius the avatar radius
  398. * @param resources reference for density information
  399. * @param callContext which context is called to set the generated avatar
  400. */
  401. public static void setAvatar(@NonNull Account account, @NonNull String userId, AvatarGenerationListener listener,
  402. float avatarRadius, Resources resources, Object callContext, Context context) {
  403. if (callContext instanceof View) {
  404. ((View) callContext).setContentDescription(account.name);
  405. }
  406. ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(context.getContentResolver());
  407. String serverName = account.name.substring(account.name.lastIndexOf('@') + 1, account.name.length());
  408. String eTag = arbitraryDataProvider.getValue(userId + "@" + serverName, ThumbnailsCacheManager.AVATAR);
  409. String avatarKey = "a_" + userId + "_" + serverName + "_" + eTag;
  410. // first show old one
  411. Drawable avatar = BitmapUtils.bitmapToCircularBitmapDrawable(resources,
  412. ThumbnailsCacheManager.getBitmapFromDiskCache(avatarKey));
  413. // if no one exists, show colored icon with initial char
  414. if (avatar == null) {
  415. try {
  416. avatar = TextDrawable.createAvatarByUserId(userId, avatarRadius);
  417. } catch (Exception e) {
  418. Log_OC.e(TAG, "Error calculating RGB value for active account icon.", e);
  419. avatar = resources.getDrawable(R.drawable.account_circle_white);
  420. }
  421. }
  422. // check for new avatar, eTag is compared, so only new one is downloaded
  423. if (ThumbnailsCacheManager.cancelPotentialAvatarWork(userId, callContext)) {
  424. final ThumbnailsCacheManager.AvatarGenerationTask task =
  425. new ThumbnailsCacheManager.AvatarGenerationTask(listener, callContext, account, resources,
  426. avatarRadius, userId, serverName, context);
  427. final ThumbnailsCacheManager.AsyncAvatarDrawable asyncDrawable =
  428. new ThumbnailsCacheManager.AsyncAvatarDrawable(resources, avatar, task);
  429. listener.avatarGenerated(asyncDrawable, callContext);
  430. task.execute(userId);
  431. }
  432. }
  433. public static void downloadIcon(Context context, String iconUrl, SimpleTarget imageView, int placeholder,
  434. int width, int height) {
  435. try {
  436. if (iconUrl.endsWith(".svg")) {
  437. downloadSVGIcon(context, iconUrl, imageView, placeholder, width, height);
  438. } else {
  439. downloadPNGIcon(context, iconUrl, imageView, placeholder);
  440. }
  441. } catch (Exception e) {
  442. Log_OC.d(TAG, "not setting image as activity is destroyed");
  443. }
  444. }
  445. private static void downloadPNGIcon(Context context, String iconUrl, SimpleTarget imageView, int placeholder) {
  446. Glide
  447. .with(context)
  448. .load(iconUrl)
  449. .centerCrop()
  450. .placeholder(placeholder)
  451. .error(placeholder)
  452. .crossFade()
  453. .into(imageView);
  454. }
  455. private static void downloadSVGIcon(Context context, String iconUrl, SimpleTarget imageView, int placeholder,
  456. int width, int height) {
  457. GenericRequestBuilder<Uri, InputStream, SVG, PictureDrawable> requestBuilder = Glide.with(context)
  458. .using(Glide.buildStreamModelLoader(Uri.class, context), InputStream.class)
  459. .from(Uri.class)
  460. .as(SVG.class)
  461. .transcode(new SvgDrawableTranscoder(), PictureDrawable.class)
  462. .sourceEncoder(new StreamEncoder())
  463. .cacheDecoder(new FileToStreamDecoder<>(new SvgDecoder(height, width)))
  464. .decoder(new SvgDecoder(height, width))
  465. .placeholder(placeholder)
  466. .error(placeholder)
  467. .animate(android.R.anim.fade_in);
  468. Uri uri = Uri.parse(iconUrl);
  469. requestBuilder
  470. .diskCacheStrategy(DiskCacheStrategy.SOURCE)
  471. .load(uri)
  472. .into(imageView);
  473. }
  474. public static Bitmap downloadImageSynchronous(Context context, String imageUrl) {
  475. try {
  476. return Glide.with(context)
  477. .load(imageUrl)
  478. .asBitmap()
  479. .diskCacheStrategy(DiskCacheStrategy.NONE)
  480. .skipMemoryCache(true)
  481. .into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
  482. .get();
  483. } catch (Exception e) {
  484. Log_OC.e(TAG, "Could not download image " + imageUrl);
  485. return null;
  486. }
  487. }
  488. public static void setupBottomBar(BottomNavigationView view, Resources resources, final Activity activity,
  489. int checkedMenuItem) {
  490. Menu menu = view.getMenu();
  491. Account account = AccountUtils.getCurrentOwnCloudAccount(MainApp.getAppContext());
  492. boolean searchSupported = AccountUtils.hasSearchSupport(account);
  493. if (!searchSupported) {
  494. menu.removeItem(R.id.nav_bar_favorites);
  495. menu.removeItem(R.id.nav_bar_photos);
  496. }
  497. if (resources.getBoolean(R.bool.use_home)) {
  498. menu.findItem(R.id.nav_bar_files).setTitle(resources.
  499. getString(R.string.drawer_item_home));
  500. menu.findItem(R.id.nav_bar_files).setIcon(R.drawable.ic_home);
  501. }
  502. setBottomBarItem(view, checkedMenuItem);
  503. view.setOnNavigationItemSelectedListener(
  504. new BottomNavigationView.OnNavigationItemSelectedListener() {
  505. @Override
  506. public boolean onNavigationItemSelected(@NonNull MenuItem item) {
  507. switch (item.getItemId()) {
  508. case R.id.nav_bar_files:
  509. EventBus.getDefault().post(new MenuItemClickEvent(item));
  510. if (activity != null) {
  511. activity.invalidateOptionsMenu();
  512. }
  513. break;
  514. case R.id.nav_bar_favorites:
  515. SearchEvent favoritesEvent = new SearchEvent("",
  516. SearchOperation.SearchType.FAVORITE_SEARCH,
  517. SearchEvent.UnsetType.UNSET_DRAWER);
  518. switchToSearchFragment(activity, favoritesEvent);
  519. break;
  520. case R.id.nav_bar_photos:
  521. SearchEvent photosEvent = new SearchEvent("image/%",
  522. SearchOperation.SearchType.CONTENT_TYPE_SEARCH,
  523. SearchEvent.UnsetType.UNSET_DRAWER);
  524. switchToSearchFragment(activity, photosEvent);
  525. break;
  526. case R.id.nav_bar_settings:
  527. EventBus.getDefault().post(new MenuItemClickEvent(item));
  528. break;
  529. default:
  530. break;
  531. }
  532. return true;
  533. }
  534. });
  535. }
  536. public static void setBottomBarItem(BottomNavigationView view, int checkedMenuItem) {
  537. Menu menu = view.getMenu();
  538. for (int i = 0; i < menu.size(); i++) {
  539. menu.getItem(i).setChecked(false);
  540. }
  541. if (checkedMenuItem != -1) {
  542. menu.findItem(checkedMenuItem).setChecked(true);
  543. }
  544. }
  545. private static void switchToSearchFragment(Activity activity, SearchEvent event) {
  546. if (activity instanceof FileDisplayActivity) {
  547. EventBus.getDefault().post(event);
  548. } else {
  549. Intent recentlyAddedIntent = new Intent(activity.getBaseContext(), FileDisplayActivity.class);
  550. recentlyAddedIntent.putExtra(OCFileListFragment.SEARCH_EVENT, Parcels.wrap(event));
  551. recentlyAddedIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  552. activity.startActivity(recentlyAddedIntent);
  553. }
  554. }
  555. /**
  556. * Get String data from a InputStream
  557. *
  558. * @param inputStream The File InputStream
  559. */
  560. public static String getData(InputStream inputStream) {
  561. BufferedReader buffreader = new BufferedReader(new InputStreamReader(inputStream));
  562. String line;
  563. StringBuilder text = new StringBuilder();
  564. try {
  565. while ((line = buffreader.readLine()) != null) {
  566. text.append(line);
  567. text.append('\n');
  568. }
  569. } catch (IOException e) {
  570. Log_OC.e(TAG, e.getMessage());
  571. }
  572. return text.toString();
  573. }
  574. /**
  575. * Show a temporary message in a {@link Snackbar} bound to the content view.
  576. *
  577. * @param activity The {@link Activity} to which's content view the {@link Snackbar} is bound.
  578. * @param messageResource The resource id of the string resource to use. Can be formatted text.
  579. */
  580. public static void showSnackMessage(Activity activity, @StringRes int messageResource) {
  581. showSnackMessage(activity.findViewById(android.R.id.content), messageResource);
  582. }
  583. /**
  584. * Show a temporary message in a {@link Snackbar} bound to the content view.
  585. *
  586. * @param activity The {@link Activity} to which's content view the {@link Snackbar} is bound.
  587. * @param message Message to show.
  588. */
  589. public static void showSnackMessage(Activity activity, String message) {
  590. Snackbar.make(activity.findViewById(android.R.id.content), message, Snackbar.LENGTH_LONG).show();
  591. }
  592. /**
  593. * Show a temporary message in a {@link Snackbar} bound to the given view.
  594. *
  595. * @param view The view the {@link Snackbar} is bound to.
  596. * @param messageResource The resource id of the string resource to use. Can be formatted text.
  597. */
  598. public static void showSnackMessage(View view, @StringRes int messageResource) {
  599. Snackbar.make(view, messageResource, Snackbar.LENGTH_LONG).show();
  600. }
  601. /**
  602. * Show a temporary message in a {@link Snackbar} bound to the given view.
  603. *
  604. * @param view The view the {@link Snackbar} is bound to.
  605. * @param message The message.
  606. */
  607. public static void showSnackMessage(View view, String message) {
  608. Snackbar.make(view, message, Snackbar.LENGTH_LONG).show();
  609. }
  610. /**
  611. * create a temporary message in a {@link Snackbar} bound to the given view.
  612. *
  613. * @param view The view the {@link Snackbar} is bound to.
  614. * @param messageResource The resource id of the string resource to use. Can be formatted text.
  615. */
  616. public static Snackbar createSnackbar(View view, @StringRes int messageResource, int length) {
  617. return Snackbar.make(view, messageResource, length);
  618. }
  619. /**
  620. * Show a temporary message in a {@link Snackbar} bound to the content view.
  621. *
  622. * @param activity The {@link Activity} to which's content view the {@link Snackbar} is bound.
  623. * @param messageResource The resource id of the string resource to use. Can be formatted text.
  624. * @param formatArgs The format arguments that will be used for substitution.
  625. */
  626. public static void showSnackMessage(Activity activity, @StringRes int messageResource, Object... formatArgs) {
  627. showSnackMessage(activity, activity.findViewById(android.R.id.content), messageResource, formatArgs);
  628. }
  629. /**
  630. * Show a temporary message in a {@link Snackbar} bound to the content view.
  631. *
  632. * @param context to load resources.
  633. * @param view The content view the {@link Snackbar} is bound to.
  634. * @param messageResource The resource id of the string resource to use. Can be formatted text.
  635. * @param formatArgs The format arguments that will be used for substitution.
  636. */
  637. public static void showSnackMessage(Context context, View view, @StringRes int messageResource, Object... formatArgs) {
  638. Snackbar.make(
  639. view,
  640. String.format(context.getString(messageResource, formatArgs)),
  641. Snackbar.LENGTH_LONG)
  642. .show();
  643. }
  644. // Solution inspired by https://stackoverflow.com/questions/34936590/why-isnt-my-vector-drawable-scaling-as-expected
  645. // Copied from https://raw.githubusercontent.com/nextcloud/talk-android/8ec8606bc61878e87e3ac8ad32c8b72d4680013c/app/src/main/java/com/nextcloud/talk/utils/DisplayUtils.java
  646. // under GPL3
  647. public static void useCompatVectorIfNeeded() {
  648. if (Build.VERSION.SDK_INT < 23) {
  649. try {
  650. @SuppressLint("RestrictedApi") AppCompatDrawableManager drawableManager = AppCompatDrawableManager.get();
  651. Class<?> inflateDelegateClass = Class.forName("android.support.v7.widget.AppCompatDrawableManager$InflateDelegate");
  652. Class<?> vdcInflateDelegateClass = Class.forName("android.support.v7.widget.AppCompatDrawableManager$VdcInflateDelegate");
  653. Constructor<?> constructor = vdcInflateDelegateClass.getDeclaredConstructor();
  654. constructor.setAccessible(true);
  655. Object vdcInflateDelegate = constructor.newInstance();
  656. Class<?> args[] = {String.class, inflateDelegateClass};
  657. Method addDelegate = AppCompatDrawableManager.class.getDeclaredMethod("addDelegate", args);
  658. addDelegate.setAccessible(true);
  659. addDelegate.invoke(drawableManager, "vector", vdcInflateDelegate);
  660. } catch (Exception e) {
  661. Log.e(TAG, "Failed to use reflection to enable proper vector scaling");
  662. }
  663. }
  664. }
  665. public static int convertDpToPixel(float dp, Context context) {
  666. Resources resources = context.getResources();
  667. DisplayMetrics metrics = resources.getDisplayMetrics();
  668. return (int) (dp * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT));
  669. }
  670. static public void showServerOutdatedSnackbar(Activity activity) {
  671. Snackbar.make(activity.findViewById(android.R.id.content),
  672. R.string.outdated_server, Snackbar.LENGTH_INDEFINITE)
  673. .setAction(R.string.dismiss, v -> {
  674. })
  675. .show();
  676. }
  677. }