DisplayUtils.java 27 KB

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