From df6812a4c958553cfaf4587bf814de9d11be1a87 Mon Sep 17 00:00:00 2001 From: Justin Carter Date: Tue, 19 Nov 2019 09:23:57 +0100 Subject: [PATCH 1/4] Extract FormattingUtils from BSFormatter All formatting related functions that are depended on by core and desktop jars are extracted to the new class FormattingUtils. --- .../java/bisq/core/app/WalletAppSetup.java | 3 +- .../bisq/core/dao/presentation/DaoUtil.java | 11 +- .../alerts/market/MarketAlerts.java | 5 +- .../alerts/price/PriceAlert.java | 3 +- .../main/java/bisq/core/util/BSFormatter.java | 280 +---------------- .../java/bisq/core/util/BsqFormatter.java | 16 +- .../java/bisq/core/util/FormattingUtils.java | 288 ++++++++++++++++++ .../java/bisq/core/util/ParsingUtils.java | 2 +- .../bisq/core/util/FormattingUtilsTest.java | 69 +++++ .../ColoredDecimalPlacesWithZerosText.java | 9 +- .../ManageMarketAlertsWindow.java | 3 +- .../MobileNotificationsView.java | 11 +- .../main/dao/bonding/BondingViewUtils.java | 5 +- .../economy/dashboard/BsqDashboardView.java | 5 +- .../dao/governance/result/CycleListItem.java | 3 +- .../bisq/desktop/main/market/MarketView.java | 5 +- .../market/offerbook/OfferBookChartView.java | 7 +- .../main/market/spread/SpreadViewModel.java | 3 +- .../main/market/trades/TradesChartsView.java | 11 +- .../main/offer/MutableOfferViewModel.java | 27 +- .../offer/offerbook/OfferBookViewModel.java | 11 +- .../offer/takeoffer/TakeOfferViewModel.java | 7 +- .../main/overlays/windows/ContractWindow.java | 3 +- .../windows/DisputeSummaryWindow.java | 3 +- .../overlays/windows/OfferDetailsWindow.java | 9 +- .../windows/SignPaymentAccountsWindow.java | 5 +- .../overlays/windows/TradeDetailsWindow.java | 3 +- .../closedtrades/ClosedTradesViewModel.java | 5 +- .../editoffer/EditOfferViewModel.java | 7 +- .../failedtrades/FailedTradesViewModel.java | 3 +- .../openoffer/OpenOffersViewModel.java | 5 +- .../pendingtrades/PendingTradesDataModel.java | 4 +- .../pendingtrades/PendingTradesView.java | 3 +- .../pendingtrades/PendingTradesViewModel.java | 3 +- .../pendingtrades/steps/TradeStepView.java | 4 +- .../presentation/MarketPricePresentation.java | 5 +- .../settings/network/NetworkSettingsView.java | 5 +- .../settings/network/P2pNetworkListItem.java | 5 +- .../settings/preferences/PreferencesView.java | 9 +- .../java/bisq/desktop/util/DisplayUtils.java | 25 +- .../main/java/bisq/desktop/util/GUIUtil.java | 3 +- .../validation/SecurityDepositValidator.java | 5 +- .../bisq/desktop/util/BSFormatterTest.java | 41 +-- 43 files changed, 509 insertions(+), 430 deletions(-) create mode 100644 core/src/main/java/bisq/core/util/FormattingUtils.java create mode 100644 core/src/test/java/bisq/core/util/FormattingUtilsTest.java diff --git a/core/src/main/java/bisq/core/app/WalletAppSetup.java b/core/src/main/java/bisq/core/app/WalletAppSetup.java index 4c2406c7536..17c309b8229 100644 --- a/core/src/main/java/bisq/core/app/WalletAppSetup.java +++ b/core/src/main/java/bisq/core/app/WalletAppSetup.java @@ -23,6 +23,7 @@ import bisq.core.locale.Res; import bisq.core.user.Preferences; import bisq.core.util.BSFormatter; +import bisq.core.util.FormattingUtils; import org.bitcoinj.core.VersionMessage; import org.bitcoinj.store.BlockStoreException; @@ -123,7 +124,7 @@ void init(@Nullable Consumer chainFileLockedExceptionHandler, result = Res.get("mainView.footer.btcInfo", peers, Res.get("mainView.footer.btcInfo.synchronizingWith"), - getBtcNetworkAsString() + ": " + BSFormatter.formatToPercentWithSymbol(percentage)); + getBtcNetworkAsString() + ": " + FormattingUtils.formatToPercentWithSymbol(percentage)); } else { result = Res.get("mainView.footer.btcInfo", peers, diff --git a/core/src/main/java/bisq/core/dao/presentation/DaoUtil.java b/core/src/main/java/bisq/core/dao/presentation/DaoUtil.java index 9bfcff6a04b..0cfb677c1de 100644 --- a/core/src/main/java/bisq/core/dao/presentation/DaoUtil.java +++ b/core/src/main/java/bisq/core/dao/presentation/DaoUtil.java @@ -21,6 +21,7 @@ import bisq.core.dao.state.model.governance.DaoPhase; import bisq.core.locale.Res; import bisq.core.util.BSFormatter; +import bisq.core.util.FormattingUtils; import java.text.SimpleDateFormat; @@ -40,8 +41,8 @@ public static String getNextPhaseDuration(int height, DaoPhase.Phase phase, DaoF long now = new Date().getTime(); SimpleDateFormat dateFormatter = new SimpleDateFormat("dd MMM", Locale.getDefault()); SimpleDateFormat timeFormatter = new SimpleDateFormat("HH:mm", Locale.getDefault()); - String startDateTime = BSFormatter.formatDateTime(new Date(now + (start - height) * 10 * 60 * 1000L), dateFormatter, timeFormatter); - String endDateTime = BSFormatter.formatDateTime(new Date(now + (end - height) * 10 * 60 * 1000L), dateFormatter, timeFormatter); + String startDateTime = FormattingUtils.formatDateTime(new Date(now + (start - height) * 10 * 60 * 1000L), dateFormatter, timeFormatter); + String endDateTime = FormattingUtils.formatDateTime(new Date(now + (end - height) * 10 * 60 * 1000L), dateFormatter, timeFormatter); return Res.get("dao.cycle.phaseDurationWithoutBlocks", start, end, startDateTime, endDateTime); } @@ -53,9 +54,9 @@ public static String getPhaseDuration(int height, DaoPhase.Phase phase, DaoFacad long now = new Date().getTime(); SimpleDateFormat dateFormatter = new SimpleDateFormat("dd MMM", Locale.getDefault()); SimpleDateFormat timeFormatter = new SimpleDateFormat("HH:mm", Locale.getDefault()); - String startDateTime = BSFormatter.formatDateTime(new Date(now + (start - height) * 10 * 60 * 1000L), dateFormatter, timeFormatter); - String endDateTime = BSFormatter.formatDateTime(new Date(now + (end - height) * 10 * 60 * 1000L), dateFormatter, timeFormatter); - String durationTime = BSFormatter.formatDurationAsWords(duration * 10 * 60 * 1000, false, false); + String startDateTime = FormattingUtils.formatDateTime(new Date(now + (start - height) * 10 * 60 * 1000L), dateFormatter, timeFormatter); + String endDateTime = FormattingUtils.formatDateTime(new Date(now + (end - height) * 10 * 60 * 1000L), dateFormatter, timeFormatter); + String durationTime = FormattingUtils.formatDurationAsWords(duration * 10 * 60 * 1000, false, false); return Res.get("dao.cycle.phaseDuration", duration, durationTime, start, end, startDateTime, endDateTime); } } diff --git a/core/src/main/java/bisq/core/notifications/alerts/market/MarketAlerts.java b/core/src/main/java/bisq/core/notifications/alerts/market/MarketAlerts.java index 664ad169294..b6b892beb0c 100644 --- a/core/src/main/java/bisq/core/notifications/alerts/market/MarketAlerts.java +++ b/core/src/main/java/bisq/core/notifications/alerts/market/MarketAlerts.java @@ -31,6 +31,7 @@ import bisq.core.provider.price.PriceFeedService; import bisq.core.user.User; import bisq.core.util.BSFormatter; +import bisq.core.util.FormattingUtils; import bisq.common.crypto.KeyRing; import bisq.common.util.MathUtils; @@ -181,8 +182,8 @@ else if (!isFiatCurrency && !isSellOffer) String msg = Res.get("account.notifications.marketAlert.message.msg", direction, BSFormatter.getCurrencyPair(currencyCode), - BSFormatter.formatPrice(offerPrice), - BSFormatter.formatToPercentWithSymbol(ratio / 10000d), + FormattingUtils.formatPrice(offerPrice), + FormattingUtils.formatToPercentWithSymbol(ratio / 10000d), marketDir, Res.get(offer.getPaymentMethod().getId()), shortOfferId); diff --git a/core/src/main/java/bisq/core/notifications/alerts/price/PriceAlert.java b/core/src/main/java/bisq/core/notifications/alerts/price/PriceAlert.java index ba9630fda01..3f75f0fe56d 100644 --- a/core/src/main/java/bisq/core/notifications/alerts/price/PriceAlert.java +++ b/core/src/main/java/bisq/core/notifications/alerts/price/PriceAlert.java @@ -27,6 +27,7 @@ import bisq.core.provider.price.PriceFeedService; import bisq.core.user.User; import bisq.core.util.BSFormatter; +import bisq.core.util.FormattingUtils; import bisq.common.util.MathUtils; @@ -70,7 +71,7 @@ private void update() { if (priceAsLong > filter.getHigh() || priceAsLong < filter.getLow()) { String msg = Res.get("account.notifications.priceAlert.message.msg", currencyName, - BSFormatter.formatMarketPrice(priceAsDouble, currencyCode), + FormattingUtils.formatMarketPrice(priceAsDouble, currencyCode), BSFormatter.getCurrencyPair(currencyCode)); MobileMessage message = new MobileMessage(Res.get("account.notifications.priceAlert.message.title", currencyName), msg, diff --git a/core/src/main/java/bisq/core/util/BSFormatter.java b/core/src/main/java/bisq/core/util/BSFormatter.java index 00eb5e23a56..47ac17695b6 100644 --- a/core/src/main/java/bisq/core/util/BSFormatter.java +++ b/core/src/main/java/bisq/core/util/BSFormatter.java @@ -61,7 +61,6 @@ @Slf4j @Singleton public class BSFormatter { - public final static String RANGE_SEPARATOR = " - "; // We don't support localized formatting. Format is always using "." as decimal mark and no grouping separator. // Input of "," as decimal mark (like in german locale) will be replaced with ".". @@ -73,10 +72,6 @@ public class BSFormatter { // protected String currencyCode = CurrencyUtil.getDefaultFiatCurrencyAsCode(); - public static final MonetaryFormat fiatPriceFormat = new MonetaryFormat().shift(0).minDecimals(4).repeatOptionalDecimals(0, 0); - protected static final MonetaryFormat altcoinFormat = new MonetaryFormat().shift(0).minDecimals(8).repeatOptionalDecimals(0, 0); - protected static final DecimalFormat decimalFormat = new DecimalFormat("#.#"); - @Inject public BSFormatter() { @@ -97,88 +92,22 @@ public String formatCoin(Coin coin, int decimalPlaces) { return formatCoin(coin, decimalPlaces, false, 0); } - public String formatCoin(long value, MonetaryFormat coinFormat) { - return formatCoin(Coin.valueOf(value), -1, false, 0, coinFormat); - } - public String formatCoin(Coin coin, int decimalPlaces, boolean decimalAligned, int maxNumberOfDigits) { - return formatCoin(coin, decimalPlaces, decimalAligned, maxNumberOfDigits, monetaryFormat); - } - - public static String formatCoin(Coin coin, - int decimalPlaces, - boolean decimalAligned, - int maxNumberOfDigits, - MonetaryFormat coinFormat) { - String formattedCoin = ""; - - if (coin != null) { - try { - if (decimalPlaces < 0 || decimalPlaces > 4) { - formattedCoin = coinFormat.noCode().format(coin).toString(); - } else { - formattedCoin = coinFormat.noCode().minDecimals(decimalPlaces).repeatOptionalDecimals(1, decimalPlaces).format(coin).toString(); - } - } catch (Throwable t) { - log.warn("Exception at formatBtc: " + t.toString()); - } - } - - if (decimalAligned) { - formattedCoin = fillUpPlacesWithEmptyStrings(formattedCoin, maxNumberOfDigits); - } - - return formattedCoin; + return FormattingUtils.formatCoin(coin, decimalPlaces, decimalAligned, maxNumberOfDigits, monetaryFormat); } public String formatCoinWithCode(Coin coin) { - return formatCoinWithCode(coin, monetaryFormat); + return FormattingUtils.formatCoinWithCode(coin, monetaryFormat); } public String formatCoinWithCode(long value) { - return formatCoinWithCode(Coin.valueOf(value), monetaryFormat); - } - - public static String formatCoinWithCode(long value, MonetaryFormat coinFormat) { - return formatCoinWithCode(Coin.valueOf(value), coinFormat); - } - - public static String formatCoinWithCode(Coin coin, MonetaryFormat coinFormat) { - if (coin != null) { - try { - // we don't use the code feature from coinFormat as it does automatic switching between mBTC and BTC and - // pre and post fixing - return coinFormat.postfixCode().format(coin).toString(); - } catch (Throwable t) { - log.warn("Exception at formatBtcWithCode: " + t.toString()); - return ""; - } - } else { - return ""; - } + return FormattingUtils.formatCoinWithCode(Coin.valueOf(value), monetaryFormat); } /////////////////////////////////////////////////////////////////////////////////////////// // FIAT /////////////////////////////////////////////////////////////////////////////////////////// - public static String formatFiat(Fiat fiat, MonetaryFormat format, boolean appendCurrencyCode) { - if (fiat != null) { - try { - final String res = format.noCode().format(fiat).toString(); - if (appendCurrencyCode) - return res + " " + fiat.getCurrencyCode(); - else - return res; - } catch (Throwable t) { - log.warn("Exception at formatFiatWithCode: " + t.toString()); - return Res.get("shared.na") + " " + fiat.getCurrencyCode(); - } - } else { - return Res.get("shared.na"); - } - } - private static Fiat parseToFiat(String input, String currencyCode) { if (input != null && input.length() > 0) { try { @@ -216,117 +145,6 @@ public static Fiat parseToFiatWithPrecision(String input, String currencyCode) { return Fiat.valueOf(currencyCode, 0); } - - /////////////////////////////////////////////////////////////////////////////////////////// - // Altcoin - /////////////////////////////////////////////////////////////////////////////////////////// - - private static String formatAltcoin(Altcoin altcoin, boolean appendCurrencyCode) { - if (altcoin != null) { - try { - String res = altcoinFormat.noCode().format(altcoin).toString(); - if (appendCurrencyCode) - return res + " " + altcoin.getCurrencyCode(); - else - return res; - } catch (Throwable t) { - log.warn("Exception at formatAltcoin: " + t.toString()); - return Res.get("shared.na") + " " + altcoin.getCurrencyCode(); - } - } else { - return Res.get("shared.na"); - } - } - - - /////////////////////////////////////////////////////////////////////////////////////////// - // Volume - /////////////////////////////////////////////////////////////////////////////////////////// - - @NotNull - public static String fillUpPlacesWithEmptyStrings(String formattedNumber, int maxNumberOfDigits) { - //FIXME: temporary deactivate adding spaces in front of numbers as we don't use a monospace font right now. - /*int numberOfPlacesToFill = maxNumberOfDigits - formattedNumber.length(); - for (int i = 0; i < numberOfPlacesToFill; i++) { - formattedNumber = " " + formattedNumber; - }*/ - return formattedNumber; - } - - public static String formatAltcoinVolume(Altcoin altcoin, boolean appendCurrencyCode) { - if (altcoin != null) { - try { - // TODO quick hack... - String res; - if (altcoin.getCurrencyCode().equals("BSQ")) - res = altcoinFormat.noCode().minDecimals(2).repeatOptionalDecimals(0, 0).format(altcoin).toString(); - else - res = altcoinFormat.noCode().format(altcoin).toString(); - if (appendCurrencyCode) - return res + " " + altcoin.getCurrencyCode(); - else - return res; - } catch (Throwable t) { - log.warn("Exception at formatAltcoinVolume: " + t.toString()); - return Res.get("shared.na") + " " + altcoin.getCurrencyCode(); - } - } else { - return Res.get("shared.na"); - } - } - - - /////////////////////////////////////////////////////////////////////////////////////////// - // Price - /////////////////////////////////////////////////////////////////////////////////////////// - - - public static String formatPrice(Price price, MonetaryFormat fiatPriceFormat, boolean appendCurrencyCode) { - if (price != null) { - Monetary monetary = price.getMonetary(); - if (monetary instanceof Fiat) - return formatFiat((Fiat) monetary, fiatPriceFormat, appendCurrencyCode); - else - return formatAltcoin((Altcoin) monetary, appendCurrencyCode); - } else { - return Res.get("shared.na"); - } - } - - public static String formatPrice(Price price, boolean appendCurrencyCode) { - return formatPrice(price, fiatPriceFormat, true); - } - - public static String formatPrice(Price price) { - return formatPrice(price, fiatPriceFormat, false); - } - - /////////////////////////////////////////////////////////////////////////////////////////// - // Market price - /////////////////////////////////////////////////////////////////////////////////////////// - - public static String formatMarketPrice(double price, String currencyCode) { - if (CurrencyUtil.isFiatCurrency(currencyCode)) - return formatMarketPrice(price, 2); - else - return formatMarketPrice(price, 8); - } - - public static String formatMarketPrice(double price, int precision) { - return formatRoundedDoubleWithPrecision(price, precision); - } - - - /////////////////////////////////////////////////////////////////////////////////////////// - // Other - /////////////////////////////////////////////////////////////////////////////////////////// - - public static String formatRoundedDoubleWithPrecision(double value, int precision) { - decimalFormat.setMinimumFractionDigits(precision); - decimalFormat.setMaximumFractionDigits(precision); - return decimalFormat.format(MathUtils.roundDouble(value, precision)).replace(",", "."); - } - public static String getDirectionWithCodeDetailed(OfferPayload.Direction direction, String currencyCode) { if (CurrencyUtil.isFiatCurrency(currencyCode)) return (direction == OfferPayload.Direction.BUY) ? Res.get("shared.buyingBTCWith", currencyCode) : Res.get("shared.sellingBTCFor", currencyCode); @@ -338,89 +156,11 @@ public static String arbitratorAddressesToString(List nodeAddresses return nodeAddresses.stream().map(NodeAddress::getFullAddress).collect(Collectors.joining(", ")); } - public static String formatDateTime(Date date, boolean useLocaleAndLocalTimezone) { - Locale locale = useLocaleAndLocalTimezone ? GlobalSettings.getLocale() : Locale.US; - DateFormat dateInstance = DateFormat.getDateInstance(DateFormat.DEFAULT, locale); - DateFormat timeInstance = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale); - if (!useLocaleAndLocalTimezone) { - dateInstance.setTimeZone(TimeZone.getTimeZone("UTC")); - timeInstance.setTimeZone(TimeZone.getTimeZone("UTC")); - } - return formatDateTime(date, dateInstance, timeInstance); - } - - public static String formatDateTime(Date date, DateFormat dateFormatter, DateFormat timeFormatter) { - if (date != null) { - return dateFormatter.format(date) + " " + timeFormatter.format(date); - } else { - return ""; - } - } - public static String getDateFromBlockHeight(long blockHeight) { long now = new Date().getTime(); SimpleDateFormat dateFormatter = new SimpleDateFormat("dd MMM", Locale.getDefault()); SimpleDateFormat timeFormatter = new SimpleDateFormat("HH:mm", Locale.getDefault()); - return BSFormatter.formatDateTime(new Date(now + blockHeight * 10 * 60 * 1000L), dateFormatter, timeFormatter); - } - - public static String formatToPercentWithSymbol(double value) { - return formatToPercent(value) + "%"; - } - - public static String formatPercentagePrice(double value) { - return formatToPercentWithSymbol(value); - } - - public static String formatToPercent(double value) { - DecimalFormat decimalFormat = new DecimalFormat("#.##"); - decimalFormat.setMinimumFractionDigits(2); - decimalFormat.setMaximumFractionDigits(2); - return decimalFormat.format(MathUtils.roundDouble(value * 100.0, 2)).replace(",", "."); - } - - public static String formatDurationAsWords(long durationMillis) { - return formatDurationAsWords(durationMillis, false, true); - } - - public static String formatDurationAsWords(long durationMillis, boolean showSeconds, boolean showZeroValues) { - String format = ""; - String second = Res.get("time.second"); - String minute = Res.get("time.minute"); - String hour = Res.get("time.hour").toLowerCase(); - String day = Res.get("time.day").toLowerCase(); - String days = Res.get("time.days"); - String hours = Res.get("time.hours"); - String minutes = Res.get("time.minutes"); - String seconds = Res.get("time.seconds"); - - if (durationMillis >= DateUtils.MILLIS_PER_DAY) { - format = "d\' " + days + ", \'"; - } - - if (showSeconds) { - format += "H\' " + hours + ", \'m\' " + minutes + ", \'s\' " + seconds + "\'"; - } else { - format += "H\' " + hours + ", \'m\' " + minutes + "\'"; - } - - String duration = durationMillis > 0 ? DurationFormatUtils.formatDuration(durationMillis, format) : ""; - - duration = StringUtils.replacePattern(duration, "^1 " + seconds + "|\\b1 " + seconds, "1 " + second); - duration = StringUtils.replacePattern(duration, "^1 " + minutes + "|\\b1 " + minutes, "1 " + minute); - duration = StringUtils.replacePattern(duration, "^1 " + hours + "|\\b1 " + hours, "1 " + hour); - duration = StringUtils.replacePattern(duration, "^1 " + days + "|\\b1 " + days, "1 " + day); - - if (!showZeroValues) { - duration = duration.replace(", 0 seconds", ""); - duration = duration.replace(", 0 minutes", ""); - duration = duration.replace(", 0 hours", ""); - duration = StringUtils.replacePattern(duration, "^0 days, ", ""); - duration = StringUtils.replacePattern(duration, "^0 hours, ", ""); - duration = StringUtils.replacePattern(duration, "^0 minutes, ", ""); - duration = StringUtils.replacePattern(duration, "^0 seconds, ", ""); - } - return duration.trim(); + return FormattingUtils.formatDateTime(new Date(now + blockHeight * 10 * 60 * 1000L), dateFormatter, timeFormatter); } public static String getRole(boolean isBuyerMakerAndSellerTaker, boolean isMaker, String currencyCode) { @@ -447,18 +187,6 @@ public static String getRole(boolean isBuyerMakerAndSellerTaker, boolean isMaker } - public static String formatBytes(long bytes) { - double kb = 1024; - double mb = kb * kb; - DecimalFormat decimalFormat = new DecimalFormat("#.##"); - if (bytes < kb) - return bytes + " bytes"; - else if (bytes < mb) - return decimalFormat.format(bytes / kb) + " KB"; - else - return decimalFormat.format(bytes / mb) + " MB"; - } - public static String getCurrencyPair(String currencyCode) { if (CurrencyUtil.isFiatCurrency(currencyCode)) return Res.getBaseCurrencyCode() + "/" + currencyCode; diff --git a/core/src/main/java/bisq/core/util/BsqFormatter.java b/core/src/main/java/bisq/core/util/BsqFormatter.java index a1eb0debc4e..97595107343 100644 --- a/core/src/main/java/bisq/core/util/BsqFormatter.java +++ b/core/src/main/java/bisq/core/util/BsqFormatter.java @@ -123,27 +123,27 @@ public String formatMarketCap(MarketPrice bsqPriceMarketPrice, MarketPrice fiatM } public String formatBSQSatoshis(long satoshi) { - return super.formatCoin(satoshi, monetaryFormat); + return FormattingUtils.formatCoin(satoshi, monetaryFormat); } public String formatBSQSatoshisWithCode(long satoshi) { - return super.formatCoinWithCode(satoshi, monetaryFormat); + return FormattingUtils.formatCoinWithCode(satoshi, monetaryFormat); } public String formatBTCSatoshis(long satoshi) { - return super.formatCoin(satoshi, btcCoinFormat); + return FormattingUtils.formatCoin(satoshi, btcCoinFormat); } public String formatBTCWithCode(long satoshi) { - return BSFormatter.formatCoinWithCode(satoshi, btcCoinFormat); + return FormattingUtils.formatCoinWithCode(satoshi, btcCoinFormat); } public String formatBTCWithCode(Coin coin) { - return BSFormatter.formatCoinWithCode(coin, btcCoinFormat); + return FormattingUtils.formatCoinWithCode(coin, btcCoinFormat); } public String formatBTC(Coin coin) { - return super.formatCoin(coin.value, btcCoinFormat); + return FormattingUtils.formatCoin(coin.value, btcCoinFormat); } public Coin parseToBTC(String input) { @@ -176,7 +176,7 @@ public String formatParamValue(Param param, String value) { case BTC: return formatBTCWithCode(parseToBTC(value)); case PERCENT: - return formatToPercentWithSymbol(ParsingUtils.parsePercentStringToDouble(value)); + return FormattingUtils.formatToPercentWithSymbol(ParsingUtils.parsePercentStringToDouble(value)); case BLOCK: return Res.get("dao.param.blocks", Integer.parseInt(value)); case ADDRESS: @@ -216,7 +216,7 @@ public String parseParamValueToString(Param param, String inputValue) throws Pro case BTC: return formatBTC(parseParamValueToCoin(param, inputValue)); case PERCENT: - return formatToPercent(ParsingUtils.parsePercentStringToDouble(inputValue)); + return FormattingUtils.formatToPercent(ParsingUtils.parsePercentStringToDouble(inputValue)); case BLOCK: return Integer.toString(parseParamValueToBlocks(param, inputValue)); case ADDRESS: diff --git a/core/src/main/java/bisq/core/util/FormattingUtils.java b/core/src/main/java/bisq/core/util/FormattingUtils.java new file mode 100644 index 00000000000..a3d535944fa --- /dev/null +++ b/core/src/main/java/bisq/core/util/FormattingUtils.java @@ -0,0 +1,288 @@ +package bisq.core.util; + +import bisq.core.locale.CurrencyUtil; +import bisq.core.locale.GlobalSettings; +import bisq.core.locale.Res; +import bisq.core.monetary.Altcoin; +import bisq.core.monetary.Price; + +import bisq.common.util.MathUtils; + +import org.bitcoinj.core.Coin; +import org.bitcoinj.core.Monetary; +import org.bitcoinj.utils.Fiat; +import org.bitcoinj.utils.MonetaryFormat; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.time.DateUtils; +import org.apache.commons.lang3.time.DurationFormatUtils; + +import java.text.DateFormat; +import java.text.DecimalFormat; +import java.text.SimpleDateFormat; + +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +import lombok.extern.slf4j.Slf4j; + +import org.jetbrains.annotations.NotNull; + +@Slf4j +public class FormattingUtils { + public final static String RANGE_SEPARATOR = " - "; + + private static final MonetaryFormat fiatPriceFormat = new MonetaryFormat().shift(0).minDecimals(4).repeatOptionalDecimals(0, 0); + private static final MonetaryFormat altcoinFormat = new MonetaryFormat().shift(0).minDecimals(8).repeatOptionalDecimals(0, 0); + private static final DecimalFormat decimalFormat = new DecimalFormat("#.#"); + + public static String formatCoinWithCode(long value, MonetaryFormat coinFormat) { + return formatCoinWithCode(Coin.valueOf(value), coinFormat); + } + + public static String formatCoinWithCode(Coin coin, MonetaryFormat coinFormat) { + if (coin != null) { + try { + // we don't use the code feature from coinFormat as it does automatic switching between mBTC and BTC and + // pre and post fixing + return coinFormat.postfixCode().format(coin).toString(); + } catch (Throwable t) { + log.warn("Exception at formatCoinWithCode: " + t.toString()); + return ""; + } + } else { + return ""; + } + } + + public static String formatCoin(long value, MonetaryFormat coinFormat) { + return formatCoin(Coin.valueOf(value), -1, false, 0, coinFormat); + } + + public static String formatCoin(Coin coin, + int decimalPlaces, + boolean decimalAligned, + int maxNumberOfDigits, + MonetaryFormat coinFormat) { + String formattedCoin = ""; + + if (coin != null) { + try { + if (decimalPlaces < 0 || decimalPlaces > 4) { + formattedCoin = coinFormat.noCode().format(coin).toString(); + } else { + formattedCoin = coinFormat.noCode().minDecimals(decimalPlaces).repeatOptionalDecimals(1, decimalPlaces).format(coin).toString(); + } + } catch (Throwable t) { + log.warn("Exception at formatBtc: " + t.toString()); + } + } + + if (decimalAligned) { + formattedCoin = fillUpPlacesWithEmptyStrings(formattedCoin, maxNumberOfDigits); + } + + return formattedCoin; + } + + public static String formatFiat(Fiat fiat, MonetaryFormat format, boolean appendCurrencyCode) { + if (fiat != null) { + try { + final String res = format.noCode().format(fiat).toString(); + if (appendCurrencyCode) + return res + " " + fiat.getCurrencyCode(); + else + return res; + } catch (Throwable t) { + log.warn("Exception at formatFiatWithCode: " + t.toString()); + return Res.get("shared.na") + " " + fiat.getCurrencyCode(); + } + } else { + return Res.get("shared.na"); + } + } + + private static String formatAltcoin(Altcoin altcoin, boolean appendCurrencyCode) { + if (altcoin != null) { + try { + String res = altcoinFormat.noCode().format(altcoin).toString(); + if (appendCurrencyCode) + return res + " " + altcoin.getCurrencyCode(); + else + return res; + } catch (Throwable t) { + log.warn("Exception at formatAltcoin: " + t.toString()); + return Res.get("shared.na") + " " + altcoin.getCurrencyCode(); + } + } else { + return Res.get("shared.na"); + } + } + + public static String formatAltcoinVolume(Altcoin altcoin, boolean appendCurrencyCode) { + if (altcoin != null) { + try { + // TODO quick hack... + String res; + if (altcoin.getCurrencyCode().equals("BSQ")) + res = altcoinFormat.noCode().minDecimals(2).repeatOptionalDecimals(0, 0).format(altcoin).toString(); + else + res = altcoinFormat.noCode().format(altcoin).toString(); + if (appendCurrencyCode) + return res + " " + altcoin.getCurrencyCode(); + else + return res; + } catch (Throwable t) { + log.warn("Exception at formatAltcoinVolume: " + t.toString()); + return Res.get("shared.na") + " " + altcoin.getCurrencyCode(); + } + } else { + return Res.get("shared.na"); + } + } + + public static String formatPrice(Price price, MonetaryFormat fiatPriceFormat, boolean appendCurrencyCode) { + if (price != null) { + Monetary monetary = price.getMonetary(); + if (monetary instanceof Fiat) + return formatFiat((Fiat) monetary, fiatPriceFormat, appendCurrencyCode); + else + return formatAltcoin((Altcoin) monetary, appendCurrencyCode); + } else { + return Res.get("shared.na"); + } + } + + public static String formatPrice(Price price, boolean appendCurrencyCode) { + return formatPrice(price, fiatPriceFormat, true); + } + + public static String formatPrice(Price price) { + return formatPrice(price, fiatPriceFormat, false); + } + + public static String formatMarketPrice(double price, String currencyCode) { + if (CurrencyUtil.isFiatCurrency(currencyCode)) + return formatMarketPrice(price, 2); + else + return formatMarketPrice(price, 8); + } + + private static String formatMarketPrice(double price, int precision) { + return formatRoundedDoubleWithPrecision(price, precision); + } + + public static String formatRoundedDoubleWithPrecision(double value, int precision) { + decimalFormat.setMinimumFractionDigits(precision); + decimalFormat.setMaximumFractionDigits(precision); + return decimalFormat.format(MathUtils.roundDouble(value, precision)).replace(",", "."); + } + + public static String formatDateTime(Date date, boolean useLocaleAndLocalTimezone) { + Locale locale = useLocaleAndLocalTimezone ? GlobalSettings.getLocale() : Locale.US; + DateFormat dateInstance = DateFormat.getDateInstance(DateFormat.DEFAULT, locale); + DateFormat timeInstance = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale); + if (!useLocaleAndLocalTimezone) { + dateInstance.setTimeZone(TimeZone.getTimeZone("UTC")); + timeInstance.setTimeZone(TimeZone.getTimeZone("UTC")); + } + return formatDateTime(date, dateInstance, timeInstance); + } + + public static String formatDateTime(Date date, DateFormat dateFormatter, DateFormat timeFormatter) { + if (date != null) { + return dateFormatter.format(date) + " " + timeFormatter.format(date); + } else { + return ""; + } + } + + public static String getDateFromBlockHeight(long blockHeight) { + long now = new Date().getTime(); + SimpleDateFormat dateFormatter = new SimpleDateFormat("dd MMM", Locale.getDefault()); + SimpleDateFormat timeFormatter = new SimpleDateFormat("HH:mm", Locale.getDefault()); + return formatDateTime(new Date(now + blockHeight * 10 * 60 * 1000L), dateFormatter, timeFormatter); + } + + public static String formatToPercentWithSymbol(double value) { + return formatToPercent(value) + "%"; + } + + public static String formatPercentagePrice(double value) { + return formatToPercentWithSymbol(value); + } + + public static String formatToPercent(double value) { + DecimalFormat decimalFormat = new DecimalFormat("#.##"); + decimalFormat.setMinimumFractionDigits(2); + decimalFormat.setMaximumFractionDigits(2); + return decimalFormat.format(MathUtils.roundDouble(value * 100.0, 2)).replace(",", "."); + } + + public static String formatDurationAsWords(long durationMillis) { + return formatDurationAsWords(durationMillis, false, true); + } + + public static String formatDurationAsWords(long durationMillis, boolean showSeconds, boolean showZeroValues) { + String format = ""; + String second = Res.get("time.second"); + String minute = Res.get("time.minute"); + String hour = Res.get("time.hour").toLowerCase(); + String day = Res.get("time.day").toLowerCase(); + String days = Res.get("time.days"); + String hours = Res.get("time.hours"); + String minutes = Res.get("time.minutes"); + String seconds = Res.get("time.seconds"); + + if (durationMillis >= DateUtils.MILLIS_PER_DAY) { + format = "d\' " + days + ", \'"; + } + + if (showSeconds) { + format += "H\' " + hours + ", \'m\' " + minutes + ", \'s\' " + seconds + "\'"; + } else { + format += "H\' " + hours + ", \'m\' " + minutes + "\'"; + } + + String duration = durationMillis > 0 ? DurationFormatUtils.formatDuration(durationMillis, format) : ""; + + duration = StringUtils.replacePattern(duration, "^1 " + seconds + "|\\b1 " + seconds, "1 " + second); + duration = StringUtils.replacePattern(duration, "^1 " + minutes + "|\\b1 " + minutes, "1 " + minute); + duration = StringUtils.replacePattern(duration, "^1 " + hours + "|\\b1 " + hours, "1 " + hour); + duration = StringUtils.replacePattern(duration, "^1 " + days + "|\\b1 " + days, "1 " + day); + + if (!showZeroValues) { + duration = duration.replace(", 0 seconds", ""); + duration = duration.replace(", 0 minutes", ""); + duration = duration.replace(", 0 hours", ""); + duration = StringUtils.replacePattern(duration, "^0 days, ", ""); + duration = StringUtils.replacePattern(duration, "^0 hours, ", ""); + duration = StringUtils.replacePattern(duration, "^0 minutes, ", ""); + duration = StringUtils.replacePattern(duration, "^0 seconds, ", ""); + } + return duration.trim(); + } + + public static String formatBytes(long bytes) { + double kb = 1024; + double mb = kb * kb; + DecimalFormat decimalFormat = new DecimalFormat("#.##"); + if (bytes < kb) + return bytes + " bytes"; + else if (bytes < mb) + return decimalFormat.format(bytes / kb) + " KB"; + else + return decimalFormat.format(bytes / mb) + " MB"; + } + + @NotNull + public static String fillUpPlacesWithEmptyStrings(String formattedNumber, int maxNumberOfDigits) { + //FIXME: temporary deactivate adding spaces in front of numbers as we don't use a monospace font right now. + /*int numberOfPlacesToFill = maxNumberOfDigits - formattedNumber.length(); + for (int i = 0; i < numberOfPlacesToFill; i++) { + formattedNumber = " " + formattedNumber; + }*/ + return formattedNumber; + } +} diff --git a/core/src/main/java/bisq/core/util/ParsingUtils.java b/core/src/main/java/bisq/core/util/ParsingUtils.java index c63e5bf138f..e20521e83ce 100644 --- a/core/src/main/java/bisq/core/util/ParsingUtils.java +++ b/core/src/main/java/bisq/core/util/ParsingUtils.java @@ -48,7 +48,7 @@ public static long parsePriceStringToLong(String currencyCode, String amount, in long value = 0; try { double amountValue = Double.parseDouble(amount); - amount = BSFormatter.formatRoundedDoubleWithPrecision(amountValue, precision); + amount = FormattingUtils.formatRoundedDoubleWithPrecision(amountValue, precision); value = Price.parse(currencyCode, amount).getValue(); } catch (NumberFormatException ignore) { // expected NumberFormatException if input is not a number diff --git a/core/src/test/java/bisq/core/util/FormattingUtilsTest.java b/core/src/test/java/bisq/core/util/FormattingUtilsTest.java new file mode 100644 index 00000000000..76f5a46e0b7 --- /dev/null +++ b/core/src/test/java/bisq/core/util/FormattingUtilsTest.java @@ -0,0 +1,69 @@ +package bisq.core.util; + +import bisq.core.locale.Res; +import bisq.core.monetary.Altcoin; +import bisq.core.monetary.Price; + +import org.bitcoinj.utils.Fiat; + +import java.util.Locale; +import java.util.concurrent.TimeUnit; + +import com.natpryce.makeiteasy.Instantiator; +import com.natpryce.makeiteasy.Maker; +import com.natpryce.makeiteasy.Property; + +import org.junit.Before; +import org.junit.Test; + +import static com.natpryce.makeiteasy.MakeItEasy.a; +import static com.natpryce.makeiteasy.MakeItEasy.make; +import static com.natpryce.makeiteasy.MakeItEasy.with; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class FormattingUtilsTest { + private static final Property currencyCode = new Property<>(); + private static final Property priceString = new Property<>(); + private static final Maker usdPrice = a(lookup -> + new Price(Fiat.parseFiat(lookup.valueOf(currencyCode, "USD"), lookup.valueOf(priceString, "100")))); + + @Before + public void setUp() { + Locale.setDefault(new Locale("en", "US")); + Res.setBaseCurrencyCode("BTC"); + Res.setBaseCurrencyName("Bitcoin"); + } + + @Test + public void testFormatDurationAsWords() { + long oneDay = TimeUnit.DAYS.toMillis(1); + long oneHour = TimeUnit.HOURS.toMillis(1); + long oneMinute = TimeUnit.MINUTES.toMillis(1); + long oneSecond = TimeUnit.SECONDS.toMillis(1); + + assertEquals("1 hour, 0 minutes", FormattingUtils.formatDurationAsWords(oneHour)); + assertEquals("1 day, 0 hours, 0 minutes", FormattingUtils.formatDurationAsWords(oneDay)); + assertEquals("2 days, 0 hours, 1 minute", FormattingUtils.formatDurationAsWords(oneDay * 2 + oneMinute)); + assertEquals("2 days, 0 hours, 2 minutes", FormattingUtils.formatDurationAsWords(oneDay * 2 + oneMinute * 2)); + assertEquals("1 hour, 0 minutes, 0 seconds", FormattingUtils.formatDurationAsWords(oneHour, true, true)); + assertEquals("1 hour, 0 minutes, 1 second", FormattingUtils.formatDurationAsWords(oneHour + oneSecond, true, true)); + assertEquals("1 hour, 0 minutes, 2 seconds", FormattingUtils.formatDurationAsWords(oneHour + oneSecond * 2, true, true)); + assertEquals("2 days, 21 hours, 28 minutes", FormattingUtils.formatDurationAsWords(oneDay * 2 + oneHour * 21 + oneMinute * 28)); + assertEquals("110 days", FormattingUtils.formatDurationAsWords(oneDay * 110, false, false)); + assertEquals("10 days, 10 hours, 10 minutes, 10 seconds", FormattingUtils.formatDurationAsWords(oneDay * 10 + oneHour * 10 + oneMinute * 10 + oneSecond * 10, true, false)); + assertEquals("1 hour, 2 seconds", FormattingUtils.formatDurationAsWords(oneHour + oneSecond * 2, true, false)); + assertEquals("1 hour", FormattingUtils.formatDurationAsWords(oneHour + oneSecond * 2, false, false)); + assertEquals("0 hours, 0 minutes, 1 second", FormattingUtils.formatDurationAsWords(oneSecond, true, true)); + assertEquals("1 second", FormattingUtils.formatDurationAsWords(oneSecond, true, false)); + assertEquals("0 hours", FormattingUtils.formatDurationAsWords(oneSecond, false, false)); + assertEquals("", FormattingUtils.formatDurationAsWords(0)); + assertTrue(FormattingUtils.formatDurationAsWords(0).isEmpty()); + } + + @Test + public void testFormatPrice() { + assertEquals("100.0000", FormattingUtils.formatPrice(make(usdPrice))); + assertEquals("7098.4700", FormattingUtils.formatPrice(make(usdPrice.but(with(priceString, "7098.4700"))))); + } +} diff --git a/desktop/src/main/java/bisq/desktop/components/ColoredDecimalPlacesWithZerosText.java b/desktop/src/main/java/bisq/desktop/components/ColoredDecimalPlacesWithZerosText.java index 6ce8eb71b13..4622d74b940 100644 --- a/desktop/src/main/java/bisq/desktop/components/ColoredDecimalPlacesWithZerosText.java +++ b/desktop/src/main/java/bisq/desktop/components/ColoredDecimalPlacesWithZerosText.java @@ -17,13 +17,12 @@ package bisq.desktop.components; -import bisq.core.util.BSFormatter; +import bisq.core.util.FormattingUtils; import bisq.common.util.Tuple2; import javafx.scene.control.Label; import javafx.scene.layout.HBox; -import javafx.scene.text.Text; import javafx.geometry.Pos; @@ -34,12 +33,12 @@ public ColoredDecimalPlacesWithZerosText(String number, int numberOfZerosToColor if (numberOfZerosToColorize <= 0) { getChildren().addAll(new Label(number)); - } else if (number.contains(BSFormatter.RANGE_SEPARATOR)) { - String[] splitNumber = number.split(BSFormatter.RANGE_SEPARATOR); + } else if (number.contains(FormattingUtils.RANGE_SEPARATOR)) { + String[] splitNumber = number.split(FormattingUtils.RANGE_SEPARATOR); Tuple2 numbers = getSplittedNumberNodes(splitNumber[0], numberOfZerosToColorize); getChildren().addAll(numbers.first, numbers.second); - getChildren().add(new Label(BSFormatter.RANGE_SEPARATOR)); + getChildren().add(new Label(FormattingUtils.RANGE_SEPARATOR)); numbers = getSplittedNumberNodes(splitNumber[1], numberOfZerosToColorize); getChildren().addAll(numbers.first, numbers.second); diff --git a/desktop/src/main/java/bisq/desktop/main/account/content/notifications/ManageMarketAlertsWindow.java b/desktop/src/main/java/bisq/desktop/main/account/content/notifications/ManageMarketAlertsWindow.java index 70a6c58917e..b8818d85900 100644 --- a/desktop/src/main/java/bisq/desktop/main/account/content/notifications/ManageMarketAlertsWindow.java +++ b/desktop/src/main/java/bisq/desktop/main/account/content/notifications/ManageMarketAlertsWindow.java @@ -27,6 +27,7 @@ import bisq.core.notifications.alerts.market.MarketAlertFilter; import bisq.core.notifications.alerts.market.MarketAlerts; import bisq.core.util.BSFormatter; +import bisq.core.util.FormattingUtils; import bisq.common.UserThread; @@ -140,7 +141,7 @@ public TableCell call(TableColumn().headLine(Res.get("dao.bond.reputation.lockup.headline")) .confirmation(Res.get("dao.bond.reputation.lockup.details", bsqFormatter.formatCoinWithCode(lockupAmount), @@ -172,7 +173,7 @@ public void unLock(String lockupTxId, Consumer resultHandler) { Coin miningFee = miningFeeAndTxSize.first; int txSize = miningFeeAndTxSize.second; BSFormatter formatter = new BSFormatter(); - String duration = BSFormatter.formatDurationAsWords(lockTime * 10 * 60 * 1000L, false, false); + String duration = FormattingUtils.formatDurationAsWords(lockTime * 10 * 60 * 1000L, false, false); new Popup<>().headLine(Res.get("dao.bond.reputation.unlock.headline")) .confirmation(Res.get("dao.bond.reputation.unlock.details", bsqFormatter.formatCoinWithCode(unlockAmount), diff --git a/desktop/src/main/java/bisq/desktop/main/dao/economy/dashboard/BsqDashboardView.java b/desktop/src/main/java/bisq/desktop/main/dao/economy/dashboard/BsqDashboardView.java index a13d7ea035e..c75591a2304 100644 --- a/desktop/src/main/java/bisq/desktop/main/dao/economy/dashboard/BsqDashboardView.java +++ b/desktop/src/main/java/bisq/desktop/main/dao/economy/dashboard/BsqDashboardView.java @@ -36,6 +36,7 @@ import bisq.core.user.Preferences; import bisq.core.util.BSFormatter; import bisq.core.util.BsqFormatter; +import bisq.core.util.FormattingUtils; import bisq.common.util.MathUtils; import bisq.common.util.Tuple3; @@ -322,7 +323,7 @@ private void updatePrice() { Optional optionalBsqPrice = priceFeedService.getBsqPrice(); if (optionalBsqPrice.isPresent()) { Price bsqPrice = optionalBsqPrice.get(); - marketPriceLabel.setText(BSFormatter.formatPrice(bsqPrice) + " BSQ/BTC"); + marketPriceLabel.setText(FormattingUtils.formatPrice(bsqPrice) + " BSQ/BTC"); marketCapTextField.setText(bsqFormatter.formatMarketCap(priceFeedService.getMarketPrice("BSQ"), priceFeedService.getMarketPrice(preferences.getPreferredTradeCurrency().getCode()), @@ -368,7 +369,7 @@ private long updateAveragePriceField(TextField textField, int days) { long average = getAverage(bsqTradePast90Days); Coin oneBsq = Coin.valueOf(100); Price avgPrice = Price.valueOf("BSQ", average); - String avg = BsqFormatter.formatPrice(avgPrice); + String avg = FormattingUtils.formatPrice(avgPrice); String bsqInUsdAvg = average > 0 ? GUIUtil.getBsqInUsd(avgPrice, oneBsq, priceFeedService, bsqFormatter) : Res.get("shared.na"); textField.setText(avg + " BSQ/BTC (" + "1 BSQ = " + bsqInUsdAvg + ")"); return average; diff --git a/desktop/src/main/java/bisq/desktop/main/dao/governance/result/CycleListItem.java b/desktop/src/main/java/bisq/desktop/main/dao/governance/result/CycleListItem.java index 7ad3508121f..a46958af9d5 100644 --- a/desktop/src/main/java/bisq/desktop/main/dao/governance/result/CycleListItem.java +++ b/desktop/src/main/java/bisq/desktop/main/dao/governance/result/CycleListItem.java @@ -21,6 +21,7 @@ import bisq.core.dao.state.model.governance.EvaluatedProposal; import bisq.core.locale.Res; import bisq.core.util.BsqFormatter; +import bisq.core.util.FormattingUtils; import org.bitcoinj.core.Coin; @@ -45,7 +46,7 @@ public String getCycle() { public String getCycleDateTime(boolean useLocaleAndLocalTimezone) { long cycleStartTime = resultsOfCycle.getCycleStartTime(); - return cycleStartTime > 0 ? bsqFormatter.formatDateTime(new Date(cycleStartTime), useLocaleAndLocalTimezone) : Res.get("shared.na"); + return cycleStartTime > 0 ? FormattingUtils.formatDateTime(new Date(cycleStartTime), useLocaleAndLocalTimezone) : Res.get("shared.na"); } public int getCycleIndex() { diff --git a/desktop/src/main/java/bisq/desktop/main/market/MarketView.java b/desktop/src/main/java/bisq/desktop/main/market/MarketView.java index 535e61db449..5fe9b77f067 100644 --- a/desktop/src/main/java/bisq/desktop/main/market/MarketView.java +++ b/desktop/src/main/java/bisq/desktop/main/market/MarketView.java @@ -36,6 +36,7 @@ import bisq.core.offer.OfferPayload; import bisq.core.trade.statistics.TradeStatistics2; import bisq.core.util.BSFormatter; +import bisq.core.util.FormattingUtils; import bisq.network.p2p.P2PService; @@ -185,7 +186,7 @@ private String getAllTradesWithReferralId() { sb.append("Trade ID: ").append(trade.getOfferId()).append("\n") .append("Date: ").append(DisplayUtils.formatDateTime(trade.getTradeDate())).append("\n") .append("Market: ").append(BSFormatter.getCurrencyPair(trade.getCurrencyCode())).append("\n") - .append("Price: ").append(BSFormatter.formatPrice(trade.getTradePrice())).append("\n") + .append("Price: ").append(FormattingUtils.formatPrice(trade.getTradePrice())).append("\n") .append("Amount: ").append(formatter.formatCoin(trade.getTradeAmount())).append("\n") .append("Volume: ").append(DisplayUtils.formatVolume(trade.getTradeVolume())).append("\n") .append("Payment method: ").append(Res.get(trade.getOfferPaymentMethod())).append("\n") @@ -206,7 +207,7 @@ private String getAllOffersWithReferralId() { sb.append("Offer ID: ").append(offer.getId()).append("\n") .append("Type: ").append(offer.getDirection().name()).append("\n") .append("Market: ").append(BSFormatter.getCurrencyPair(offer.getCurrencyCode())).append("\n") - .append("Price: ").append(BSFormatter.formatPrice(offer.getPrice())).append("\n") + .append("Price: ").append(FormattingUtils.formatPrice(offer.getPrice())).append("\n") .append("Amount: ").append(DisplayUtils.formatAmount(offer, formatter)).append(" BTC\n") .append("Payment method: ").append(Res.get(offer.getPaymentMethod().getId())).append("\n") .append("ReferralID: ").append(offer.getOfferPayload().getExtraDataMap().get(OfferPayload.REFERRAL_ID)); diff --git a/desktop/src/main/java/bisq/desktop/main/market/offerbook/OfferBookChartView.java b/desktop/src/main/java/bisq/desktop/main/market/offerbook/OfferBookChartView.java index 2b136251029..8129df0c2d0 100644 --- a/desktop/src/main/java/bisq/desktop/main/market/offerbook/OfferBookChartView.java +++ b/desktop/src/main/java/bisq/desktop/main/market/offerbook/OfferBookChartView.java @@ -39,6 +39,7 @@ import bisq.core.offer.Offer; import bisq.core.offer.OfferPayload; import bisq.core.util.BSFormatter; +import bisq.core.util.FormattingUtils; import bisq.network.p2p.NodeAddress; @@ -221,15 +222,15 @@ protected void activate() { public String toString(Number object) { final double doubleValue = (double) object; if (CurrencyUtil.isCryptoCurrency(model.getCurrencyCode())) { - final String withCryptoPrecision = BSFormatter.formatRoundedDoubleWithPrecision(doubleValue, cryptoPrecision); + final String withCryptoPrecision = FormattingUtils.formatRoundedDoubleWithPrecision(doubleValue, cryptoPrecision); if (withCryptoPrecision.equals("0.000")) { cryptoPrecision = 8; - return BSFormatter.formatRoundedDoubleWithPrecision(doubleValue, cryptoPrecision); + return FormattingUtils.formatRoundedDoubleWithPrecision(doubleValue, cryptoPrecision); } else { return withCryptoPrecision; } } else { - return BSFormatter.formatRoundedDoubleWithPrecision(doubleValue, 2); + return FormattingUtils.formatRoundedDoubleWithPrecision(doubleValue, 2); } } diff --git a/desktop/src/main/java/bisq/desktop/main/market/spread/SpreadViewModel.java b/desktop/src/main/java/bisq/desktop/main/market/spread/SpreadViewModel.java index 199c5c1566c..fc5da37a60d 100644 --- a/desktop/src/main/java/bisq/desktop/main/market/spread/SpreadViewModel.java +++ b/desktop/src/main/java/bisq/desktop/main/market/spread/SpreadViewModel.java @@ -31,6 +31,7 @@ import bisq.core.provider.price.MarketPrice; import bisq.core.provider.price.PriceFeedService; import bisq.core.util.BSFormatter; +import bisq.core.util.FormattingUtils; import org.bitcoinj.core.Coin; import org.bitcoinj.utils.Fiat; @@ -185,7 +186,7 @@ private void update(ObservableList offerBookListItems) { .multiply(BigDecimal.valueOf(10000)) .divide(marketPriceAsBigDecimal, RoundingMode.HALF_UP) .doubleValue() / 10000; - percentage = BSFormatter.formatPercentagePrice(percentageValue); + percentage = FormattingUtils.formatPercentagePrice(percentageValue); } } catch (Throwable t) { try { diff --git a/desktop/src/main/java/bisq/desktop/main/market/trades/TradesChartsView.java b/desktop/src/main/java/bisq/desktop/main/market/trades/TradesChartsView.java index c2994b19eb5..57f88b34210 100644 --- a/desktop/src/main/java/bisq/desktop/main/market/trades/TradesChartsView.java +++ b/desktop/src/main/java/bisq/desktop/main/market/trades/TradesChartsView.java @@ -37,6 +37,7 @@ import bisq.core.offer.OfferPayload; import bisq.core.trade.statistics.TradeStatistics2; import bisq.core.util.BSFormatter; +import bisq.core.util.FormattingUtils; import bisq.common.UserThread; import bisq.common.util.MathUtils; @@ -346,9 +347,9 @@ public String toString(Number object) { double doubleValue = (double) object; if (CurrencyUtil.isCryptoCurrency(currencyCode)) { final double value = MathUtils.scaleDownByPowerOf10(doubleValue, 8); - return BSFormatter.formatRoundedDoubleWithPrecision(value, 8); + return FormattingUtils.formatRoundedDoubleWithPrecision(value, 8); } else { - return BSFormatter.formatPrice(Price.valueOf(currencyCode, MathUtils.doubleToLong(doubleValue))); + return FormattingUtils.formatPrice(Price.valueOf(currencyCode, MathUtils.doubleToLong(doubleValue))); } } @@ -363,9 +364,9 @@ public Number fromString(String string) { public String toString(Number object) { if (CurrencyUtil.isCryptoCurrency(model.getCurrencyCode())) { final double value = MathUtils.scaleDownByPowerOf10((long) object, 8); - return BSFormatter.formatRoundedDoubleWithPrecision(value, 8); + return FormattingUtils.formatRoundedDoubleWithPrecision(value, 8); } else { - return BSFormatter.formatPrice(Price.valueOf(model.getCurrencyCode(), (long) object)); + return FormattingUtils.formatPrice(Price.valueOf(model.getCurrencyCode(), (long) object)); } } @@ -619,7 +620,7 @@ public TableCell call( public void updateItem(final TradeStatistics2 item, boolean empty) { super.updateItem(item, empty); if (item != null) - setText(BSFormatter.formatPrice(item.getTradePrice())); + setText(FormattingUtils.formatPrice(item.getTradePrice())); else setText(""); } diff --git a/desktop/src/main/java/bisq/desktop/main/offer/MutableOfferViewModel.java b/desktop/src/main/java/bisq/desktop/main/offer/MutableOfferViewModel.java index 56aaeb922aa..f3a4373ccc4 100644 --- a/desktop/src/main/java/bisq/desktop/main/offer/MutableOfferViewModel.java +++ b/desktop/src/main/java/bisq/desktop/main/offer/MutableOfferViewModel.java @@ -53,6 +53,7 @@ import bisq.core.user.Preferences; import bisq.core.util.BSFormatter; import bisq.core.util.BsqFormatter; +import bisq.core.util.FormattingUtils; import bisq.core.util.ParsingUtils; import bisq.core.util.validation.InputValidator; @@ -326,7 +327,7 @@ private void createListeners() { double percentage = dataModel.getDirection() == compareDirection ? 1 - relation : relation - 1; percentage = MathUtils.roundDouble(percentage, 4); dataModel.setMarketPriceMargin(percentage); - marketPriceMargin.set(BSFormatter.formatToPercent(percentage)); + marketPriceMargin.set(FormattingUtils.formatToPercent(percentage)); applyMakerFee(); } catch (NumberFormatException t) { marketPriceMargin.set(""); @@ -367,7 +368,7 @@ private void createListeners() { Altcoin.SMALLEST_UNIT_EXPONENT : Fiat.SMALLEST_UNIT_EXPONENT; // protect from triggering unwanted updates ignorePriceStringListener = true; - price.set(BSFormatter.formatRoundedDoubleWithPrecision(targetPrice, precision)); + price.set(FormattingUtils.formatRoundedDoubleWithPrecision(targetPrice, precision)); ignorePriceStringListener = false; setPriceToModel(); dataModel.setMarketPriceMargin(percentage); @@ -444,7 +445,7 @@ private void createListeners() { priceListener = (ov, oldValue, newValue) -> { ignorePriceStringListener = true; if (newValue != null) - price.set(BSFormatter.formatPrice(newValue)); + price.set(FormattingUtils.formatPrice(newValue)); else price.set(""); @@ -464,7 +465,7 @@ private void createListeners() { securityDepositAsDoubleListener = (ov, oldValue, newValue) -> { if (newValue != null) { - buyerSecurityDeposit.set(BSFormatter.formatToPercent((double) newValue)); + buyerSecurityDeposit.set(FormattingUtils.formatToPercent((double) newValue)); if (dataModel.getAmount().get() != null) buyerSecurityDepositInBTC.set(btcFormatter.formatCoinWithCode(dataModel.getBuyerSecurityDepositAsCoin())); } else { @@ -523,7 +524,7 @@ private void applyMakerFee() { tradeFeeInBsqWithFiat.set(Res.get("createOffer.tradeFee.fiatAndPercent", feeInFiatAsString, - BSFormatter.formatToPercentWithSymbol(percent))); + FormattingUtils.formatToPercentWithSymbol(percent))); } } tradeFeeCurrencyCode.set(dataModel.isCurrencyForMakerFeeBtc() ? Res.getBaseCurrencyCode() : "BSQ"); @@ -604,7 +605,7 @@ boolean initWithData(OfferPayload.Direction direction, TradeCurrency tradeCurren isBuy ? Res.get("shared.buy") : Res.get("shared.sell")); securityDepositValidator.setPaymentAccount(dataModel.paymentAccount); - buyerSecurityDeposit.set(BSFormatter.formatToPercent(dataModel.getBuyerSecurityDeposit().get())); + buyerSecurityDeposit.set(FormattingUtils.formatToPercent(dataModel.getBuyerSecurityDeposit().get())); buyerSecurityDepositLabel.set(getSecurityDepositLabel()); applyMakerFee(); @@ -796,7 +797,7 @@ void onFocusOutPriceTextField(boolean oldValue, boolean newValue) { setPriceToModel(); ignorePriceStringListener = true; if (dataModel.getPrice().get() != null) - price.set(BSFormatter.formatPrice(dataModel.getPrice().get())); + price.set(FormattingUtils.formatPrice(dataModel.getPrice().get())); ignorePriceStringListener = false; dataModel.calculateVolume(); dataModel.calculateAmount(); @@ -820,7 +821,7 @@ public void onFocusOutPriceAsPercentageTextField(boolean oldValue, boolean newVa // field wasn't set manually inputIsMarketBasedPrice = true; } - marketPriceMargin.set(btcFormatter.formatRoundedDoubleWithPrecision(dataModel.getMarketPriceMargin() * 100, 2)); + marketPriceMargin.set(FormattingUtils.formatRoundedDoubleWithPrecision(dataModel.getMarketPriceMargin() * 100, 2)); } // We want to trigger a recalculation of the volume @@ -885,13 +886,13 @@ void onFocusOutBuyerSecurityDepositTextField(boolean oldValue, boolean newValue) Res.get("createOffer.tooLowSecDeposit.makerIsSeller"); new Popup<>() .warning(Res.get("createOffer.tooLowSecDeposit.warning", - BSFormatter.formatToPercentWithSymbol(defaultSecurityDeposit)) + "\n\n" + postfix) + FormattingUtils.formatToPercentWithSymbol(defaultSecurityDeposit)) + "\n\n" + postfix) .width(800) .actionButtonText(Res.get("createOffer.resetToDefault")) .onAction(() -> { dataModel.setBuyerSecurityDeposit(defaultSecurityDeposit); ignoreSecurityDepositStringListener = true; - buyerSecurityDeposit.set(BSFormatter.formatToPercent(dataModel.getBuyerSecurityDeposit().get())); + buyerSecurityDeposit.set(FormattingUtils.formatToPercent(dataModel.getBuyerSecurityDeposit().get())); ignoreSecurityDepositStringListener = false; }) .closeButtonText(Res.get("createOffer.useLowerValue")) @@ -908,7 +909,7 @@ void onFocusOutBuyerSecurityDepositTextField(boolean oldValue, boolean newValue) private void applyBuyerSecurityDepositOnFocusOut() { setBuyerSecurityDepositToModel(); ignoreSecurityDepositStringListener = true; - buyerSecurityDeposit.set(BSFormatter.formatToPercent(dataModel.getBuyerSecurityDeposit().get())); + buyerSecurityDeposit.set(FormattingUtils.formatToPercent(dataModel.getBuyerSecurityDeposit().get())); ignoreSecurityDepositStringListener = false; } @@ -932,7 +933,7 @@ public boolean isPriceInRange() { private void displayPriceOutOfRangePopup() { Popup popup = new Popup<>(); popup.warning(Res.get("createOffer.priceOutSideOfDeviation", - BSFormatter.formatToPercentWithSymbol(preferences.getMaxPriceDistanceInPercent()))) + FormattingUtils.formatToPercentWithSymbol(preferences.getMaxPriceDistanceInPercent()))) .actionButtonText(Res.get("createOffer.changePrice")) .onAction(popup::hide) .closeButtonTextWithGoTo("navigation.settings.preferences") @@ -1226,7 +1227,7 @@ private void updateMarketPriceToManual() { final boolean isCryptoCurrency = CurrencyUtil.isCryptoCurrency(currencyCode); int precision = isCryptoCurrency ? Altcoin.SMALLEST_UNIT_EXPONENT : Fiat.SMALLEST_UNIT_EXPONENT; - price.set(BSFormatter.formatRoundedDoubleWithPrecision(manualPriceAsDouble, precision)); + price.set(FormattingUtils.formatRoundedDoubleWithPrecision(manualPriceAsDouble, precision)); setPriceToModel(); dataModel.calculateTotalToPay(); updateButtonDisableState(); diff --git a/desktop/src/main/java/bisq/desktop/main/offer/offerbook/OfferBookViewModel.java b/desktop/src/main/java/bisq/desktop/main/offer/offerbook/OfferBookViewModel.java index 1a06267bfdb..036ef0a05c2 100644 --- a/desktop/src/main/java/bisq/desktop/main/offer/offerbook/OfferBookViewModel.java +++ b/desktop/src/main/java/bisq/desktop/main/offer/offerbook/OfferBookViewModel.java @@ -49,6 +49,7 @@ import bisq.core.user.User; import bisq.core.util.BSFormatter; import bisq.core.util.BsqFormatter; +import bisq.core.util.FormattingUtils; import bisq.network.p2p.NodeAddress; import bisq.network.p2p.P2PService; @@ -179,9 +180,9 @@ public OfferBookViewModel(User user, final OfferBookListItem item = highestAmountOffer.get(); if (!item.getOffer().isRange() && containsRangeAmount) { maxPlacesForAmount.set(formatAmount(item.getOffer(), false) - .length() * 2 + BSFormatter.RANGE_SEPARATOR.length()); + .length() * 2 + FormattingUtils.RANGE_SEPARATOR.length()); maxPlacesForVolume.set(formatVolume(item.getOffer(), false) - .length() * 2 + BSFormatter.RANGE_SEPARATOR.length()); + .length() * 2 + FormattingUtils.RANGE_SEPARATOR.length()); } else { maxPlacesForAmount.set(formatAmount(item.getOffer(), false).length()); maxPlacesForVolume.set(formatVolume(item.getOffer(), false).length()); @@ -365,7 +366,7 @@ String getPrice(OfferBookListItem item) { } String getAbsolutePriceMargin(Offer offer) { - return BSFormatter.formatPercentagePrice(Math.abs(offer.getMarketPriceMargin())); + return FormattingUtils.formatPercentagePrice(Math.abs(offer.getMarketPriceMargin())); } private String formatPrice(Offer offer, boolean decimalAligned) { @@ -375,12 +376,12 @@ private String formatPrice(Offer offer, boolean decimalAligned) { private String formatMarketPriceMargin(Offer offer, boolean decimalAligned) { String postFix = ""; if (offer.isUseMarketBasedPrice()) { - postFix = " (" + BSFormatter.formatPercentagePrice(offer.getMarketPriceMargin()) + ")"; + postFix = " (" + FormattingUtils.formatPercentagePrice(offer.getMarketPriceMargin()) + ")"; } if (decimalAligned) { - postFix = BSFormatter.fillUpPlacesWithEmptyStrings(postFix, maxPlacesForMarketPriceMargin.get()); + postFix = FormattingUtils.fillUpPlacesWithEmptyStrings(postFix, maxPlacesForMarketPriceMargin.get()); } return postFix; diff --git a/desktop/src/main/java/bisq/desktop/main/offer/takeoffer/TakeOfferViewModel.java b/desktop/src/main/java/bisq/desktop/main/offer/takeoffer/TakeOfferViewModel.java index a50b8f77229..ea913b3de64 100644 --- a/desktop/src/main/java/bisq/desktop/main/offer/takeoffer/TakeOfferViewModel.java +++ b/desktop/src/main/java/bisq/desktop/main/offer/takeoffer/TakeOfferViewModel.java @@ -45,6 +45,7 @@ import bisq.core.user.Preferences; import bisq.core.util.BSFormatter; import bisq.core.util.BsqFormatter; +import bisq.core.util.FormattingUtils; import bisq.core.util.validation.InputValidator; import bisq.network.p2p.P2PService; @@ -216,8 +217,8 @@ void initWithData(Offer offer) { } amountRange = btcFormatter.formatCoin(offer.getMinAmount()) + " - " + btcFormatter.formatCoin(offer.getAmount()); - price = BSFormatter.formatPrice(dataModel.tradePrice); - marketPriceMargin = BSFormatter.formatToPercent(offer.getMarketPriceMargin()); + price = FormattingUtils.formatPrice(dataModel.tradePrice); + marketPriceMargin = FormattingUtils.formatToPercent(offer.getMarketPriceMargin()); paymentLabel = Res.get("takeOffer.fundsBox.paymentLabel", offer.getShortId()); checkNotNull(dataModel.getAddressEntry(), "dataModel.getAddressEntry() must not be null"); @@ -327,7 +328,7 @@ private void applyTakerFee() { tradeFeeInBsqWithFiat.set(Res.get("createOffer.tradeFee.fiatAndPercent", feeInFiatAsString, - BSFormatter.formatToPercentWithSymbol(percent))); + FormattingUtils.formatToPercentWithSymbol(percent))); } } tradeFeeDescription.set(DevEnv.isDaoActivated() ? Res.get("createOffer.tradeFee.descriptionBSQEnabled") : diff --git a/desktop/src/main/java/bisq/desktop/main/overlays/windows/ContractWindow.java b/desktop/src/main/java/bisq/desktop/main/overlays/windows/ContractWindow.java index e91dfd98dda..100f646714f 100644 --- a/desktop/src/main/java/bisq/desktop/main/overlays/windows/ContractWindow.java +++ b/desktop/src/main/java/bisq/desktop/main/overlays/windows/ContractWindow.java @@ -38,6 +38,7 @@ import bisq.core.support.dispute.refund.RefundManager; import bisq.core.trade.Contract; import bisq.core.util.BSFormatter; +import bisq.core.util.FormattingUtils; import bisq.network.p2p.NodeAddress; @@ -154,7 +155,7 @@ private void addContent() { addConfirmationLabelLabel(gridPane, ++rowIndex, Res.get("shared.offerType"), DisplayUtils.getDirectionBothSides(offer.getDirection(), currencyCode)); addConfirmationLabelLabel(gridPane, ++rowIndex, Res.get("shared.tradePrice"), - BSFormatter.formatPrice(contract.getTradePrice())); + FormattingUtils.formatPrice(contract.getTradePrice())); addConfirmationLabelLabel(gridPane, ++rowIndex, Res.get("shared.tradeAmount"), formatter.formatCoinWithCode(contract.getTradeAmount())); addConfirmationLabelLabel(gridPane, ++rowIndex, DisplayUtils.formatVolumeLabel(currencyCode, ":"), diff --git a/desktop/src/main/java/bisq/desktop/main/overlays/windows/DisputeSummaryWindow.java b/desktop/src/main/java/bisq/desktop/main/overlays/windows/DisputeSummaryWindow.java index ae2fe46ccd9..16e9bccce0e 100644 --- a/desktop/src/main/java/bisq/desktop/main/overlays/windows/DisputeSummaryWindow.java +++ b/desktop/src/main/java/bisq/desktop/main/overlays/windows/DisputeSummaryWindow.java @@ -47,6 +47,7 @@ import bisq.core.trade.Contract; import bisq.core.util.BSFormatter; import bisq.core.util.CoinUtil; +import bisq.core.util.FormattingUtils; import bisq.core.util.ParsingUtils; import bisq.common.UserThread; @@ -293,7 +294,7 @@ private void addInfoPane() { addConfirmationLabelLabel(gridPane, ++rowIndex, Res.get("shared.tradeAmount"), formatter.formatCoinWithCode(contract.getTradeAmount())); addConfirmationLabelLabel(gridPane, ++rowIndex, Res.get("shared.tradePrice"), - BSFormatter.formatPrice(contract.getTradePrice())); + FormattingUtils.formatPrice(contract.getTradePrice())); addConfirmationLabelLabel(gridPane, ++rowIndex, Res.get("shared.tradeVolume"), DisplayUtils.formatVolumeWithCode(contract.getTradeVolume())); String securityDeposit = Res.getWithColAndCap("shared.buyer") + diff --git a/desktop/src/main/java/bisq/desktop/main/overlays/windows/OfferDetailsWindow.java b/desktop/src/main/java/bisq/desktop/main/overlays/windows/OfferDetailsWindow.java index a96c815e810..46e07bcc9e8 100644 --- a/desktop/src/main/java/bisq/desktop/main/overlays/windows/OfferDetailsWindow.java +++ b/desktop/src/main/java/bisq/desktop/main/overlays/windows/OfferDetailsWindow.java @@ -35,6 +35,7 @@ import bisq.core.payment.payload.PaymentMethod; import bisq.core.user.User; import bisq.core.util.BSFormatter; +import bisq.core.util.FormattingUtils; import bisq.common.crypto.KeyRing; import bisq.common.util.Tuple2; @@ -207,15 +208,15 @@ private void addContent() { String priceLabel = Res.get("shared.price"); if (takeOfferHandlerOptional.isPresent()) { - addConfirmationLabelLabel(gridPane, ++rowIndex, priceLabel, BSFormatter.formatPrice(tradePrice)); + addConfirmationLabelLabel(gridPane, ++rowIndex, priceLabel, FormattingUtils.formatPrice(tradePrice)); } else { Price price = offer.getPrice(); if (offer.isUseMarketBasedPrice()) { - addConfirmationLabelLabel(gridPane, ++rowIndex, priceLabel, BSFormatter.formatPrice(price) + + addConfirmationLabelLabel(gridPane, ++rowIndex, priceLabel, FormattingUtils.formatPrice(price) + " " + Res.get("offerDetailsWindow.distance", - BSFormatter.formatPercentagePrice(offer.getMarketPriceMargin()))); + FormattingUtils.formatPercentagePrice(offer.getMarketPriceMargin()))); } else { - addConfirmationLabelLabel(gridPane, ++rowIndex, priceLabel, BSFormatter.formatPrice(price)); + addConfirmationLabelLabel(gridPane, ++rowIndex, priceLabel, FormattingUtils.formatPrice(price)); } } final PaymentMethod paymentMethod = offer.getPaymentMethod(); diff --git a/desktop/src/main/java/bisq/desktop/main/overlays/windows/SignPaymentAccountsWindow.java b/desktop/src/main/java/bisq/desktop/main/overlays/windows/SignPaymentAccountsWindow.java index 44b47d9f442..4215d6896c8 100644 --- a/desktop/src/main/java/bisq/desktop/main/overlays/windows/SignPaymentAccountsWindow.java +++ b/desktop/src/main/java/bisq/desktop/main/overlays/windows/SignPaymentAccountsWindow.java @@ -31,6 +31,7 @@ import bisq.core.support.dispute.arbitration.TraderDataItem; import bisq.core.support.dispute.arbitration.arbitrator.ArbitratorManager; import bisq.core.util.BSFormatter; +import bisq.core.util.FormattingUtils; import bisq.common.util.Tuple2; import bisq.common.util.Tuple3; @@ -210,7 +211,7 @@ private void addSelectedAccountsContent() { .append(" (No. of signed accounts: ").append(list.size()).append(")\n"); list.forEach(traderDataItem -> { sb.append("Account created: ") - .append(BSFormatter.formatDateTime(new Date(traderDataItem.getAccountAgeWitness().getDate()), true)) + .append(FormattingUtils.formatDateTime(new Date(traderDataItem.getAccountAgeWitness().getDate()), true)) .append(" Account: ") .append(traderDataItem.getPaymentAccountPayload().getPaymentDetails()).append("\n"); }); @@ -226,7 +227,7 @@ private void addSelectedAccountsContent() { .append(" (No. of signed accounts: ").append(traderDataItemList.size()).append(")\n"); traderDataItemList.forEach(traderDataItem -> { sb.append("Account created: ") - .append(BSFormatter.formatDateTime(new Date(traderDataItem.getAccountAgeWitness().getDate()), true)) + .append(FormattingUtils.formatDateTime(new Date(traderDataItem.getAccountAgeWitness().getDate()), true)) .append(" Account: ") .append(traderDataItem.getPaymentAccountPayload().getPaymentDetails()).append("\n"); }); diff --git a/desktop/src/main/java/bisq/desktop/main/overlays/windows/TradeDetailsWindow.java b/desktop/src/main/java/bisq/desktop/main/overlays/windows/TradeDetailsWindow.java index 236a2fa6349..78ed986af2b 100644 --- a/desktop/src/main/java/bisq/desktop/main/overlays/windows/TradeDetailsWindow.java +++ b/desktop/src/main/java/bisq/desktop/main/overlays/windows/TradeDetailsWindow.java @@ -34,6 +34,7 @@ import bisq.core.trade.Trade; import bisq.core.trade.TradeManager; import bisq.core.util.BSFormatter; +import bisq.core.util.FormattingUtils; import bisq.network.p2p.NodeAddress; @@ -155,7 +156,7 @@ private void addContent() { DisplayUtils.formatVolumeLabel(offer.getCurrencyCode()) + fiatDirectionInfo, DisplayUtils.formatVolumeWithCode(trade.getTradeVolume())); addConfirmationLabelLabel(gridPane, ++rowIndex, Res.get("shared.tradePrice"), - BSFormatter.formatPrice(trade.getTradePrice())); + FormattingUtils.formatPrice(trade.getTradePrice())); addConfirmationLabelLabel(gridPane, ++rowIndex, Res.get("shared.paymentMethod"), Res.get(offer.getPaymentMethod().getId())); diff --git a/desktop/src/main/java/bisq/desktop/main/portfolio/closedtrades/ClosedTradesViewModel.java b/desktop/src/main/java/bisq/desktop/main/portfolio/closedtrades/ClosedTradesViewModel.java index 82a0a1a1383..29a29e149a0 100644 --- a/desktop/src/main/java/bisq/desktop/main/portfolio/closedtrades/ClosedTradesViewModel.java +++ b/desktop/src/main/java/bisq/desktop/main/portfolio/closedtrades/ClosedTradesViewModel.java @@ -27,6 +27,7 @@ import bisq.core.trade.Tradable; import bisq.core.trade.Trade; import bisq.core.util.BSFormatter; +import bisq.core.util.FormattingUtils; import com.google.inject.Inject; @@ -69,9 +70,9 @@ String getPrice(ClosedTradableListItem item) { return ""; Tradable tradable = item.getTradable(); if (tradable instanceof Trade) - return BSFormatter.formatPrice(((Trade) tradable).getTradePrice()); + return FormattingUtils.formatPrice(((Trade) tradable).getTradePrice()); else - return BSFormatter.formatPrice(tradable.getOffer().getPrice()); + return FormattingUtils.formatPrice(tradable.getOffer().getPrice()); } String getVolume(ClosedTradableListItem item) { diff --git a/desktop/src/main/java/bisq/desktop/main/portfolio/editoffer/EditOfferViewModel.java b/desktop/src/main/java/bisq/desktop/main/portfolio/editoffer/EditOfferViewModel.java index 8825ca4b6bd..0e82033f3c8 100644 --- a/desktop/src/main/java/bisq/desktop/main/portfolio/editoffer/EditOfferViewModel.java +++ b/desktop/src/main/java/bisq/desktop/main/portfolio/editoffer/EditOfferViewModel.java @@ -32,6 +32,7 @@ import bisq.core.user.Preferences; import bisq.core.util.BSFormatter; import bisq.core.util.BsqFormatter; +import bisq.core.util.FormattingUtils; import bisq.common.handlers.ErrorMessageHandler; import bisq.common.handlers.ResultHandler; @@ -94,12 +95,12 @@ public void onCancelEditOffer(ErrorMessageHandler errorMessageHandler) { public void onInvalidateMarketPriceMargin() { marketPriceMargin.set("0.00%"); - marketPriceMargin.set(BSFormatter.formatToPercent(dataModel.getMarketPriceMargin())); + marketPriceMargin.set(FormattingUtils.formatToPercent(dataModel.getMarketPriceMargin())); } public void onInvalidatePrice() { - price.set(BSFormatter.formatPrice(null)); - price.set(BSFormatter.formatPrice(dataModel.getPrice().get())); + price.set(FormattingUtils.formatPrice(null)); + price.set(FormattingUtils.formatPrice(dataModel.getPrice().get())); } public boolean isSecurityDepositValid() { diff --git a/desktop/src/main/java/bisq/desktop/main/portfolio/failedtrades/FailedTradesViewModel.java b/desktop/src/main/java/bisq/desktop/main/portfolio/failedtrades/FailedTradesViewModel.java index 9adda89e850..1b3d9d7e19d 100644 --- a/desktop/src/main/java/bisq/desktop/main/portfolio/failedtrades/FailedTradesViewModel.java +++ b/desktop/src/main/java/bisq/desktop/main/portfolio/failedtrades/FailedTradesViewModel.java @@ -23,6 +23,7 @@ import bisq.core.locale.Res; import bisq.core.util.BSFormatter; +import bisq.core.util.FormattingUtils; import com.google.inject.Inject; @@ -55,7 +56,7 @@ String getAmount(FailedTradesListItem item) { } String getPrice(FailedTradesListItem item) { - return (item != null) ? BSFormatter.formatPrice(item.getTrade().getTradePrice()) : ""; + return (item != null) ? FormattingUtils.formatPrice(item.getTrade().getTradePrice()) : ""; } String getVolume(FailedTradesListItem item) { diff --git a/desktop/src/main/java/bisq/desktop/main/portfolio/openoffer/OpenOffersViewModel.java b/desktop/src/main/java/bisq/desktop/main/portfolio/openoffer/OpenOffersViewModel.java index c362c8a10be..0b41cbc7619 100644 --- a/desktop/src/main/java/bisq/desktop/main/portfolio/openoffer/OpenOffersViewModel.java +++ b/desktop/src/main/java/bisq/desktop/main/portfolio/openoffer/OpenOffersViewModel.java @@ -28,6 +28,7 @@ import bisq.core.offer.OpenOffer; import bisq.core.util.BSFormatter; import bisq.core.util.BsqFormatter; +import bisq.core.util.FormattingUtils; import bisq.network.p2p.P2PService; @@ -89,8 +90,8 @@ String getPrice(OpenOfferListItem item) { if (price != null) { String postFix = ""; if (offer.isUseMarketBasedPrice()) - postFix = " (" + BSFormatter.formatPercentagePrice(offer.getMarketPriceMargin()) + ")"; - return BSFormatter.formatPrice(price) + postFix; + postFix = " (" + FormattingUtils.formatPercentagePrice(offer.getMarketPriceMargin()) + ")"; + return FormattingUtils.formatPrice(price) + postFix; } else { return Res.get("shared.na"); } diff --git a/desktop/src/main/java/bisq/desktop/main/portfolio/pendingtrades/PendingTradesDataModel.java b/desktop/src/main/java/bisq/desktop/main/portfolio/pendingtrades/PendingTradesDataModel.java index 53fc9023ea2..e2c8055bf2b 100644 --- a/desktop/src/main/java/bisq/desktop/main/portfolio/pendingtrades/PendingTradesDataModel.java +++ b/desktop/src/main/java/bisq/desktop/main/portfolio/pendingtrades/PendingTradesDataModel.java @@ -50,7 +50,7 @@ import bisq.core.trade.Trade; import bisq.core.trade.TradeManager; import bisq.core.user.Preferences; -import bisq.core.util.BSFormatter; +import bisq.core.util.FormattingUtils; import bisq.network.p2p.P2PService; @@ -564,7 +564,7 @@ private void doOpenDispute(boolean isSupportTicket, Transaction depositTx) { if (remaining > 0) { new Popup<>() .instruction(Res.get("portfolio.pending.timeLockNotOver", - BSFormatter.getDateFromBlockHeight(remaining), remaining)) + FormattingUtils.getDateFromBlockHeight(remaining), remaining)) .show(); return; } diff --git a/desktop/src/main/java/bisq/desktop/main/portfolio/pendingtrades/PendingTradesView.java b/desktop/src/main/java/bisq/desktop/main/portfolio/pendingtrades/PendingTradesView.java index 7ba40d8067f..2af42d08957 100644 --- a/desktop/src/main/java/bisq/desktop/main/portfolio/pendingtrades/PendingTradesView.java +++ b/desktop/src/main/java/bisq/desktop/main/portfolio/pendingtrades/PendingTradesView.java @@ -40,6 +40,7 @@ import bisq.core.trade.Trade; import bisq.core.user.Preferences; import bisq.core.util.BSFormatter; +import bisq.core.util.FormattingUtils; import bisq.network.p2p.NodeAddress; @@ -548,7 +549,7 @@ public TableCell call( public void updateItem(final PendingTradesListItem item, boolean empty) { super.updateItem(item, empty); if (item != null && !empty) - setGraphic(new AutoTooltipLabel(BSFormatter.formatPrice(item.getPrice()))); + setGraphic(new AutoTooltipLabel(FormattingUtils.formatPrice(item.getPrice()))); else setGraphic(null); } diff --git a/desktop/src/main/java/bisq/desktop/main/portfolio/pendingtrades/PendingTradesViewModel.java b/desktop/src/main/java/bisq/desktop/main/portfolio/pendingtrades/PendingTradesViewModel.java index 69454b419c9..1bed862fc16 100644 --- a/desktop/src/main/java/bisq/desktop/main/portfolio/pendingtrades/PendingTradesViewModel.java +++ b/desktop/src/main/java/bisq/desktop/main/portfolio/pendingtrades/PendingTradesViewModel.java @@ -33,6 +33,7 @@ import bisq.core.user.User; import bisq.core.util.BSFormatter; import bisq.core.util.BsqFormatter; +import bisq.core.util.FormattingUtils; import bisq.core.util.validation.BtcAddressValidator; import bisq.network.p2p.P2PService; @@ -223,7 +224,7 @@ private long getRemainingTradeDuration() { } public String getRemainingTradeDurationAsWords() { - return BSFormatter.formatDurationAsWords(Math.max(0, getRemainingTradeDuration())); + return FormattingUtils.formatDurationAsWords(Math.max(0, getRemainingTradeDuration())); } public double getRemainingTradeDurationAsPercentage() { diff --git a/desktop/src/main/java/bisq/desktop/main/portfolio/pendingtrades/steps/TradeStepView.java b/desktop/src/main/java/bisq/desktop/main/portfolio/pendingtrades/steps/TradeStepView.java index 164b95eb263..110b80c8c6e 100644 --- a/desktop/src/main/java/bisq/desktop/main/portfolio/pendingtrades/steps/TradeStepView.java +++ b/desktop/src/main/java/bisq/desktop/main/portfolio/pendingtrades/steps/TradeStepView.java @@ -32,7 +32,7 @@ import bisq.core.trade.Contract; import bisq.core.trade.Trade; import bisq.core.user.Preferences; -import bisq.core.util.BSFormatter; +import bisq.core.util.FormattingUtils; import bisq.network.p2p.BootstrapListener; @@ -551,7 +551,7 @@ private void openMediationResultPopup(String headLine) { .instruction(Res.get("portfolio.pending.mediationResult.popup.info", myPayoutAmount, peersPayoutAmount, - BSFormatter.getDateFromBlockHeight(remaining), + FormattingUtils.getDateFromBlockHeight(remaining), lockTime)) .actionButtonText(actionButtonText) .onAction(() -> { diff --git a/desktop/src/main/java/bisq/desktop/main/presentation/MarketPricePresentation.java b/desktop/src/main/java/bisq/desktop/main/presentation/MarketPricePresentation.java index d6e4f6f5627..6c80c0d4ed7 100644 --- a/desktop/src/main/java/bisq/desktop/main/presentation/MarketPricePresentation.java +++ b/desktop/src/main/java/bisq/desktop/main/presentation/MarketPricePresentation.java @@ -31,6 +31,7 @@ import bisq.core.provider.price.PriceFeedService; import bisq.core.user.Preferences; import bisq.core.util.BSFormatter; +import bisq.core.util.FormattingUtils; import bisq.common.UserThread; @@ -137,7 +138,7 @@ private void fillPriceFeedComboBoxItems() { } private void setupMarketPriceFeed() { - priceFeedService.requestPriceFeed(price -> marketPrice.set(BSFormatter.formatMarketPrice(price, priceFeedService.getCurrencyCode())), + priceFeedService.requestPriceFeed(price -> marketPrice.set(FormattingUtils.formatMarketPrice(price, priceFeedService.getCurrencyCode())), (errorMessage, throwable) -> marketPrice.set(Res.get("shared.na"))); marketPriceBinding = EasyBind.combine( @@ -194,7 +195,7 @@ private void setMarketPriceInItems() { MarketPrice marketPrice = priceFeedService.getMarketPrice(currencyCode); String priceString; if (marketPrice != null && marketPrice.isPriceAvailable()) { - priceString = BSFormatter.formatMarketPrice(marketPrice.getPrice(), currencyCode); + priceString = FormattingUtils.formatMarketPrice(marketPrice.getPrice(), currencyCode); item.setPriceAvailable(true); item.setExternallyProvidedPrice(marketPrice.isExternallyProvidedPrice()); } else { diff --git a/desktop/src/main/java/bisq/desktop/main/settings/network/NetworkSettingsView.java b/desktop/src/main/java/bisq/desktop/main/settings/network/NetworkSettingsView.java index 4f98f015e09..2c58462bce0 100644 --- a/desktop/src/main/java/bisq/desktop/main/settings/network/NetworkSettingsView.java +++ b/desktop/src/main/java/bisq/desktop/main/settings/network/NetworkSettingsView.java @@ -36,6 +36,7 @@ import bisq.core.locale.Res; import bisq.core.user.Preferences; import bisq.core.util.BSFormatter; +import bisq.core.util.FormattingUtils; import bisq.network.p2p.P2PService; import bisq.network.p2p.network.Statistic; @@ -304,8 +305,8 @@ public void activate() { totalTrafficTextField.textProperty().bind(EasyBind.combine(Statistic.totalSentBytesProperty(), Statistic.totalReceivedBytesProperty(), (sent, received) -> Res.get("settings.net.sentReceived", - BSFormatter.formatBytes((long) sent), - BSFormatter.formatBytes((long) received)))); + FormattingUtils.formatBytes((long) sent), + FormattingUtils.formatBytes((long) received)))); bitcoinSortedList.comparatorProperty().bind(bitcoinPeersTableView.comparatorProperty()); bitcoinPeersTableView.setItems(bitcoinSortedList); diff --git a/desktop/src/main/java/bisq/desktop/main/settings/network/P2pNetworkListItem.java b/desktop/src/main/java/bisq/desktop/main/settings/network/P2pNetworkListItem.java index db5e9b9ad37..b43243838df 100644 --- a/desktop/src/main/java/bisq/desktop/main/settings/network/P2pNetworkListItem.java +++ b/desktop/src/main/java/bisq/desktop/main/settings/network/P2pNetworkListItem.java @@ -21,6 +21,7 @@ import bisq.core.locale.Res; import bisq.core.util.BSFormatter; +import bisq.core.util.FormattingUtils; import bisq.network.p2p.network.Connection; import bisq.network.p2p.network.OutboundConnection; @@ -64,9 +65,9 @@ public P2pNetworkListItem(Connection connection, ClockWatcher clockWatcher, BSFo this.statistic = connection.getStatistic(); sentBytesSubscription = EasyBind.subscribe(statistic.sentBytesProperty(), - e -> sentBytes.set(BSFormatter.formatBytes((long) e))); + e -> sentBytes.set(FormattingUtils.formatBytes((long) e))); receivedBytesSubscription = EasyBind.subscribe(statistic.receivedBytesProperty(), - e -> receivedBytes.set(BSFormatter.formatBytes((long) e))); + e -> receivedBytes.set(FormattingUtils.formatBytes((long) e))); onionAddressSubscription = EasyBind.subscribe(connection.getPeersNodeAddressProperty(), nodeAddress -> onionAddress.set(nodeAddress != null ? nodeAddress.getFullAddress() : Res.get("settings.net.notKnownYet"))); roundTripTimeSubscription = EasyBind.subscribe(statistic.roundTripTimeProperty(), diff --git a/desktop/src/main/java/bisq/desktop/main/settings/preferences/PreferencesView.java b/desktop/src/main/java/bisq/desktop/main/settings/preferences/PreferencesView.java index d8233b5589f..0c7bfb65b2e 100644 --- a/desktop/src/main/java/bisq/desktop/main/settings/preferences/PreferencesView.java +++ b/desktop/src/main/java/bisq/desktop/main/settings/preferences/PreferencesView.java @@ -47,6 +47,7 @@ import bisq.core.user.BlockChainExplorer; import bisq.core.user.Preferences; import bisq.core.util.BSFormatter; +import bisq.core.util.FormattingUtils; import bisq.core.util.ParsingUtils; import bisq.core.util.validation.IntegerValidator; @@ -300,16 +301,16 @@ private void initializeGeneralOptions() { preferences.setMaxPriceDistanceInPercent(value); } else { new Popup<>().warning(Res.get("setting.preferences.deviationToLarge", maxDeviation * 100)).show(); - UserThread.runAfter(() -> deviationInputTextField.setText(BSFormatter.formatPercentagePrice(preferences.getMaxPriceDistanceInPercent())), 100, TimeUnit.MILLISECONDS); + UserThread.runAfter(() -> deviationInputTextField.setText(FormattingUtils.formatPercentagePrice(preferences.getMaxPriceDistanceInPercent())), 100, TimeUnit.MILLISECONDS); } } catch (NumberFormatException t) { log.error("Exception at parseDouble deviation: " + t.toString()); - UserThread.runAfter(() -> deviationInputTextField.setText(BSFormatter.formatPercentagePrice(preferences.getMaxPriceDistanceInPercent())), 100, TimeUnit.MILLISECONDS); + UserThread.runAfter(() -> deviationInputTextField.setText(FormattingUtils.formatPercentagePrice(preferences.getMaxPriceDistanceInPercent())), 100, TimeUnit.MILLISECONDS); } }; deviationFocusedListener = (observable1, oldValue1, newValue1) -> { if (oldValue1 && !newValue1) - UserThread.runAfter(() -> deviationInputTextField.setText(BSFormatter.formatPercentagePrice(preferences.getMaxPriceDistanceInPercent())), 100, TimeUnit.MILLISECONDS); + UserThread.runAfter(() -> deviationInputTextField.setText(FormattingUtils.formatPercentagePrice(preferences.getMaxPriceDistanceInPercent())), 100, TimeUnit.MILLISECONDS); }; // ignoreTraders @@ -725,7 +726,7 @@ public BlockChainExplorer fromString(String string) { }); blockChainExplorerComboBox.setOnAction(e -> preferences.setBlockChainExplorer(blockChainExplorerComboBox.getSelectionModel().getSelectedItem())); - deviationInputTextField.setText(BSFormatter.formatPercentagePrice(preferences.getMaxPriceDistanceInPercent())); + deviationInputTextField.setText(FormattingUtils.formatPercentagePrice(preferences.getMaxPriceDistanceInPercent())); deviationInputTextField.textProperty().addListener(deviationListener); deviationInputTextField.focusedProperty().addListener(deviationFocusedListener); diff --git a/desktop/src/main/java/bisq/desktop/util/DisplayUtils.java b/desktop/src/main/java/bisq/desktop/util/DisplayUtils.java index 7a1f1f8721a..cd66eadcdc9 100644 --- a/desktop/src/main/java/bisq/desktop/util/DisplayUtils.java +++ b/desktop/src/main/java/bisq/desktop/util/DisplayUtils.java @@ -9,6 +9,7 @@ import bisq.core.offer.Offer; import bisq.core.offer.OfferPayload; import bisq.core.util.BSFormatter; +import bisq.core.util.FormattingUtils; import bisq.core.util.ParsingUtils; import org.bitcoinj.core.Coin; @@ -34,14 +35,14 @@ public class DisplayUtils { private static final MonetaryFormat fiatVolumeFormat = new MonetaryFormat().shift(0).minDecimals(2).repeatOptionalDecimals(0, 0); public static String formatDateTime(Date date) { - return BSFormatter.formatDateTime(date, true); + return FormattingUtils.formatDateTime(date, true); } public static String formatDateTimeSpan(Date dateFrom, Date dateTo) { if (dateFrom != null && dateTo != null) { DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.DEFAULT, GlobalSettings.getLocale()); DateFormat timeFormatter = DateFormat.getTimeInstance(DateFormat.DEFAULT, GlobalSettings.getLocale()); - return dateFormatter.format(dateFrom) + " " + timeFormatter.format(dateFrom) + BSFormatter.RANGE_SEPARATOR + timeFormatter.format(dateTo); + return dateFormatter.format(dateFrom) + " " + timeFormatter.format(dateFrom) + FormattingUtils.RANGE_SEPARATOR + timeFormatter.format(dateTo); } else { return ""; } @@ -86,10 +87,10 @@ public static String formatVolume(Offer offer, Boolean decimalAligned, int maxNu } public static String formatVolume(Offer offer, Boolean decimalAligned, int maxNumberOfDigits, boolean showRange) { - String formattedVolume = offer.isRange() && showRange ? formatVolume(offer.getMinVolume()) + BSFormatter.RANGE_SEPARATOR + formatVolume(offer.getVolume()) : formatVolume(offer.getVolume()); + String formattedVolume = offer.isRange() && showRange ? formatVolume(offer.getMinVolume()) + FormattingUtils.RANGE_SEPARATOR + formatVolume(offer.getVolume()) : formatVolume(offer.getVolume()); if (decimalAligned) { - formattedVolume = BSFormatter.fillUpPlacesWithEmptyStrings(formattedVolume, maxNumberOfDigits); + formattedVolume = FormattingUtils.fillUpPlacesWithEmptyStrings(formattedVolume, maxNumberOfDigits); } return formattedVolume; } @@ -102,9 +103,9 @@ private static String formatVolume(Volume volume, MonetaryFormat fiatVolumeForma if (volume != null) { Monetary monetary = volume.getMonetary(); if (monetary instanceof Fiat) - return BSFormatter.formatFiat((Fiat) monetary, fiatVolumeFormat, appendCurrencyCode); + return FormattingUtils.formatFiat((Fiat) monetary, fiatVolumeFormat, appendCurrencyCode); else - return BSFormatter.formatAltcoinVolume((Altcoin) monetary, appendCurrencyCode); + return FormattingUtils.formatAltcoinVolume((Altcoin) monetary, appendCurrencyCode); } else { return ""; } @@ -209,9 +210,9 @@ public static String formatAmount(Offer offer, BSFormatter formatter) { } private static String formatAmount(Offer offer, boolean decimalAligned, BSFormatter bsFormatter) { - String formattedAmount = offer.isRange() ? bsFormatter.formatCoin(offer.getMinAmount()) + BSFormatter.RANGE_SEPARATOR + bsFormatter.formatCoin(offer.getAmount()) : bsFormatter.formatCoin(offer.getAmount()); + String formattedAmount = offer.isRange() ? bsFormatter.formatCoin(offer.getMinAmount()) + FormattingUtils.RANGE_SEPARATOR + bsFormatter.formatCoin(offer.getAmount()) : bsFormatter.formatCoin(offer.getAmount()); if (decimalAligned) { - formattedAmount = BSFormatter.fillUpPlacesWithEmptyStrings(formattedAmount, 15); + formattedAmount = FormattingUtils.fillUpPlacesWithEmptyStrings(formattedAmount, 15); } return formattedAmount; } @@ -221,10 +222,10 @@ public static String formatAmount(Offer offer, boolean decimalAligned, int maxPlaces, BSFormatter bsFormatter) { - String formattedAmount = offer.isRange() ? bsFormatter.formatCoin(offer.getMinAmount(), decimalPlaces) + BSFormatter.RANGE_SEPARATOR + bsFormatter.formatCoin(offer.getAmount(), decimalPlaces) : bsFormatter.formatCoin(offer.getAmount(), decimalPlaces); + String formattedAmount = offer.isRange() ? bsFormatter.formatCoin(offer.getMinAmount(), decimalPlaces) + FormattingUtils.RANGE_SEPARATOR + bsFormatter.formatCoin(offer.getAmount(), decimalPlaces) : bsFormatter.formatCoin(offer.getAmount(), decimalPlaces); if (decimalAligned) { - formattedAmount = BSFormatter.fillUpPlacesWithEmptyStrings(formattedAmount, maxPlaces); + formattedAmount = FormattingUtils.fillUpPlacesWithEmptyStrings(formattedAmount, maxPlaces); } return formattedAmount; } @@ -234,10 +235,10 @@ public static String formatAmount(Offer offer, /////////////////////////////////////////////////////////////////////////////////////////// public static String formatPrice(Price price, Boolean decimalAligned, int maxPlaces) { - String formattedPrice = BSFormatter.formatPrice(price); + String formattedPrice = FormattingUtils.formatPrice(price); if (decimalAligned) { - formattedPrice = BSFormatter.fillUpPlacesWithEmptyStrings(formattedPrice, maxPlaces); + formattedPrice = FormattingUtils.fillUpPlacesWithEmptyStrings(formattedPrice, maxPlaces); } return formattedPrice; } diff --git a/desktop/src/main/java/bisq/desktop/util/GUIUtil.java b/desktop/src/main/java/bisq/desktop/util/GUIUtil.java index 4491d3e22a6..c4525f16a2a 100644 --- a/desktop/src/main/java/bisq/desktop/util/GUIUtil.java +++ b/desktop/src/main/java/bisq/desktop/util/GUIUtil.java @@ -52,6 +52,7 @@ import bisq.core.util.BSFormatter; import bisq.core.util.BsqFormatter; import bisq.core.util.CoinUtil; +import bisq.core.util.FormattingUtils; import bisq.network.p2p.P2PService; @@ -667,7 +668,7 @@ public static String getPercentageOfTradeAmount(Coin fee, Coin tradeAmount) { } public static String getPercentage(Coin part, Coin total) { - return BSFormatter.formatToPercentWithSymbol((double) part.value / (double) total.value); + return FormattingUtils.formatToPercentWithSymbol((double) part.value / (double) total.value); } public static T getParentOfType(Node node, Class t) { diff --git a/desktop/src/main/java/bisq/desktop/util/validation/SecurityDepositValidator.java b/desktop/src/main/java/bisq/desktop/util/validation/SecurityDepositValidator.java index db491b20ae6..c3b510d33e1 100644 --- a/desktop/src/main/java/bisq/desktop/util/validation/SecurityDepositValidator.java +++ b/desktop/src/main/java/bisq/desktop/util/validation/SecurityDepositValidator.java @@ -21,6 +21,7 @@ import bisq.core.locale.Res; import bisq.core.payment.PaymentAccount; import bisq.core.util.BSFormatter; +import bisq.core.util.FormattingUtils; import bisq.core.util.ParsingUtils; import javax.inject.Inject; @@ -61,7 +62,7 @@ private ValidationResult validateIfNotTooLowPercentageValue(String input) { double minPercentage = Restrictions.getMinBuyerSecurityDepositAsPercent(paymentAccount); if (percentage < minPercentage) return new ValidationResult(false, - Res.get("validation.inputTooSmall", BSFormatter.formatToPercentWithSymbol(minPercentage))); + Res.get("validation.inputTooSmall", FormattingUtils.formatToPercentWithSymbol(minPercentage))); else return new ValidationResult(true); } catch (Throwable t) { @@ -75,7 +76,7 @@ private ValidationResult validateIfNotTooHighPercentageValue(String input) { double maxPercentage = Restrictions.getMaxBuyerSecurityDepositAsPercent(paymentAccount); if (percentage > maxPercentage) return new ValidationResult(false, - Res.get("validation.inputTooLarge", BSFormatter.formatToPercentWithSymbol(maxPercentage))); + Res.get("validation.inputTooLarge", FormattingUtils.formatToPercentWithSymbol(maxPercentage))); else return new ValidationResult(true); } catch (Throwable t) { diff --git a/desktop/src/test/java/bisq/desktop/util/BSFormatterTest.java b/desktop/src/test/java/bisq/desktop/util/BSFormatterTest.java index 23f0282a3ec..1a1202c4b40 100644 --- a/desktop/src/test/java/bisq/desktop/util/BSFormatterTest.java +++ b/desktop/src/test/java/bisq/desktop/util/BSFormatterTest.java @@ -18,12 +18,9 @@ package bisq.desktop.util; import bisq.core.locale.Res; -import bisq.core.monetary.Volume; -import bisq.core.offer.Offer; -import bisq.core.offer.OfferPayload; import bisq.core.util.BSFormatter; +import bisq.core.util.FormattingUtils; -import org.bitcoinj.core.Coin; import org.bitcoinj.core.CoinMaker; import java.util.Locale; @@ -32,11 +29,8 @@ import org.junit.Before; import org.junit.Test; -import static bisq.desktop.maker.OfferMaker.btcUsdOffer; import static bisq.desktop.maker.PriceMaker.priceString; import static bisq.desktop.maker.PriceMaker.usdPrice; -import static bisq.desktop.maker.VolumeMaker.usdVolume; -import static bisq.desktop.maker.VolumeMaker.volumeString; import static com.natpryce.makeiteasy.MakeItEasy.a; import static com.natpryce.makeiteasy.MakeItEasy.make; import static com.natpryce.makeiteasy.MakeItEasy.with; @@ -45,7 +39,6 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; public class BSFormatterTest { @@ -59,38 +52,6 @@ public void setUp() { Res.setBaseCurrencyName("Bitcoin"); } - @Test - public void testFormatDurationAsWords() { - long oneDay = TimeUnit.DAYS.toMillis(1); - long oneHour = TimeUnit.HOURS.toMillis(1); - long oneMinute = TimeUnit.MINUTES.toMillis(1); - long oneSecond = TimeUnit.SECONDS.toMillis(1); - - assertEquals("1 hour, 0 minutes", BSFormatter.formatDurationAsWords(oneHour)); - assertEquals("1 day, 0 hours, 0 minutes", BSFormatter.formatDurationAsWords(oneDay)); - assertEquals("2 days, 0 hours, 1 minute", BSFormatter.formatDurationAsWords(oneDay * 2 + oneMinute)); - assertEquals("2 days, 0 hours, 2 minutes", BSFormatter.formatDurationAsWords(oneDay * 2 + oneMinute * 2)); - assertEquals("1 hour, 0 minutes, 0 seconds", BSFormatter.formatDurationAsWords(oneHour, true, true)); - assertEquals("1 hour, 0 minutes, 1 second", BSFormatter.formatDurationAsWords(oneHour + oneSecond, true, true)); - assertEquals("1 hour, 0 minutes, 2 seconds", BSFormatter.formatDurationAsWords(oneHour + oneSecond * 2, true, true)); - assertEquals("2 days, 21 hours, 28 minutes", BSFormatter.formatDurationAsWords(oneDay * 2 + oneHour * 21 + oneMinute * 28)); - assertEquals("110 days", BSFormatter.formatDurationAsWords(oneDay * 110, false, false)); - assertEquals("10 days, 10 hours, 10 minutes, 10 seconds", BSFormatter.formatDurationAsWords(oneDay * 10 + oneHour * 10 + oneMinute * 10 + oneSecond * 10, true, false)); - assertEquals("1 hour, 2 seconds", BSFormatter.formatDurationAsWords(oneHour + oneSecond * 2, true, false)); - assertEquals("1 hour", BSFormatter.formatDurationAsWords(oneHour + oneSecond * 2, false, false)); - assertEquals("0 hours, 0 minutes, 1 second", BSFormatter.formatDurationAsWords(oneSecond, true, true)); - assertEquals("1 second", BSFormatter.formatDurationAsWords(oneSecond, true, false)); - assertEquals("0 hours", BSFormatter.formatDurationAsWords(oneSecond, false, false)); - assertEquals("", BSFormatter.formatDurationAsWords(0)); - assertTrue(BSFormatter.formatDurationAsWords(0).isEmpty()); - } - - @Test - public void testFormatPrice() { - assertEquals("100.0000", BSFormatter.formatPrice(make(usdPrice))); - assertEquals("7098.4700", BSFormatter.formatPrice(make(usdPrice.but(with(priceString, "7098.4700"))))); - } - @Test public void testFormatCoin() { assertEquals("1.00", formatter.formatCoin(oneBitcoin)); From 06c2fa5ea00dbd245889c34c1d2057eaa1b2d5c7 Mon Sep 17 00:00:00 2001 From: Justin Carter Date: Wed, 11 Sep 2019 16:29:46 +0200 Subject: [PATCH 2/4] Remove dead Code from BSFormatter --- .../main/java/bisq/core/util/BSFormatter.java | 45 ------------------- 1 file changed, 45 deletions(-) diff --git a/core/src/main/java/bisq/core/util/BSFormatter.java b/core/src/main/java/bisq/core/util/BSFormatter.java index 47ac17695b6..1c79e407477 100644 --- a/core/src/main/java/bisq/core/util/BSFormatter.java +++ b/core/src/main/java/bisq/core/util/BSFormatter.java @@ -104,47 +104,6 @@ public String formatCoinWithCode(long value) { return FormattingUtils.formatCoinWithCode(Coin.valueOf(value), monetaryFormat); } - /////////////////////////////////////////////////////////////////////////////////////////// - // FIAT - /////////////////////////////////////////////////////////////////////////////////////////// - - private static Fiat parseToFiat(String input, String currencyCode) { - if (input != null && input.length() > 0) { - try { - return Fiat.parseFiat(currencyCode, ParsingUtils.cleanDoubleInput(input)); - } catch (Exception e) { - log.warn("Exception at parseToFiat: " + e.toString()); - return Fiat.valueOf(currencyCode, 0); - } - - } else { - return Fiat.valueOf(currencyCode, 0); - } - } - - /** - * Converts to a fiat with max. 2 decimal places. Last place gets rounded. - * 0.234 -> 0.23 - * 0.235 -> 0.24 - * - * @param input - * @return - */ - - public static Fiat parseToFiatWithPrecision(String input, String currencyCode) { - if (input != null && input.length() > 0) { - try { - return parseToFiat(new BigDecimal(ParsingUtils.cleanDoubleInput(input)).setScale(2, BigDecimal.ROUND_HALF_UP).toString(), - currencyCode); - } catch (Throwable t) { - log.warn("Exception at parseToFiatWithPrecision: " + t.toString()); - return Fiat.valueOf(currencyCode, 0); - } - - } - return Fiat.valueOf(currencyCode, 0); - } - public static String getDirectionWithCodeDetailed(OfferPayload.Direction direction, String currencyCode) { if (CurrencyUtil.isFiatCurrency(currencyCode)) return (direction == OfferPayload.Direction.BUY) ? Res.get("shared.buyingBTCWith", currencyCode) : Res.get("shared.sellingBTCFor", currencyCode); @@ -152,10 +111,6 @@ public static String getDirectionWithCodeDetailed(OfferPayload.Direction directi return (direction == OfferPayload.Direction.SELL) ? Res.get("shared.buyingCurrency", currencyCode) : Res.get("shared.sellingCurrency", currencyCode); } - public static String arbitratorAddressesToString(List nodeAddresses) { - return nodeAddresses.stream().map(NodeAddress::getFullAddress).collect(Collectors.joining(", ")); - } - public static String getDateFromBlockHeight(long blockHeight) { long now = new Date().getTime(); SimpleDateFormat dateFormatter = new SimpleDateFormat("dd MMM", Locale.getDefault()); From dc741984ce074159c54e73e83f16ff47f9e32f03 Mon Sep 17 00:00:00 2001 From: Justin Carter Date: Fri, 13 Sep 2019 08:27:56 +0200 Subject: [PATCH 3/4] Move Currency related helpers out of BSFormatter to CurrencyUtils --- .../java/bisq/core/locale/CurrencyUtil.java | 25 +++++++++++++++++++ .../alerts/market/MarketAlerts.java | 2 +- .../alerts/price/PriceAlert.java | 2 +- .../main/java/bisq/core/util/BSFormatter.java | 24 ------------------ .../bisq/desktop/main/market/MarketView.java | 5 ++-- .../market/offerbook/OfferBookChartView.java | 2 +- .../main/market/trades/TradesChartsView.java | 4 +-- .../desktop/main/offer/MutableOfferView.java | 4 +-- .../main/offer/offerbook/OfferBookView.java | 6 ++--- .../main/offer/takeoffer/TakeOfferView.java | 4 +-- .../closedtrades/ClosedTradesViewModel.java | 3 ++- .../failedtrades/FailedTradesViewModel.java | 3 ++- .../openoffer/OpenOffersViewModel.java | 3 ++- .../pendingtrades/PendingTradesViewModel.java | 3 ++- .../presentation/MarketPricePresentation.java | 4 +-- .../main/support/dispute/DisputeView.java | 4 +-- 16 files changed, 52 insertions(+), 46 deletions(-) diff --git a/core/src/main/java/bisq/core/locale/CurrencyUtil.java b/core/src/main/java/bisq/core/locale/CurrencyUtil.java index ac8a8350174..b98b5b3d893 100644 --- a/core/src/main/java/bisq/core/locale/CurrencyUtil.java +++ b/core/src/main/java/bisq/core/locale/CurrencyUtil.java @@ -507,4 +507,29 @@ public static List getActiveSortedCryptoCurrencies(AssetService .filter(e -> !filterManager.isCurrencyBanned(e.getCode())) .collect(Collectors.toList()); } + + public static String getCurrencyPair(String currencyCode) { + if (isFiatCurrency(currencyCode)) + return Res.getBaseCurrencyCode() + "/" + currencyCode; + else + return currencyCode + "/" + Res.getBaseCurrencyCode(); + } + + public static String getCounterCurrency(String currencyCode) { + if (isFiatCurrency(currencyCode)) + return currencyCode; + else + return Res.getBaseCurrencyCode(); + } + + public static String getPriceWithCurrencyCode(String currencyCode) { + return getPriceWithCurrencyCode(currencyCode, "shared.priceInCurForCur"); + } + + public static String getPriceWithCurrencyCode(String currencyCode, String translationKey) { + if (isCryptoCurrency(currencyCode)) + return Res.get(translationKey, Res.getBaseCurrencyCode(), currencyCode); + else + return Res.get(translationKey, currencyCode, Res.getBaseCurrencyCode()); + } } diff --git a/core/src/main/java/bisq/core/notifications/alerts/market/MarketAlerts.java b/core/src/main/java/bisq/core/notifications/alerts/market/MarketAlerts.java index b6b892beb0c..5ab49fbb2e4 100644 --- a/core/src/main/java/bisq/core/notifications/alerts/market/MarketAlerts.java +++ b/core/src/main/java/bisq/core/notifications/alerts/market/MarketAlerts.java @@ -181,7 +181,7 @@ else if (!isFiatCurrency && !isSellOffer) ratio = Math.abs(ratio); String msg = Res.get("account.notifications.marketAlert.message.msg", direction, - BSFormatter.getCurrencyPair(currencyCode), + CurrencyUtil.getCurrencyPair(currencyCode), FormattingUtils.formatPrice(offerPrice), FormattingUtils.formatToPercentWithSymbol(ratio / 10000d), marketDir, diff --git a/core/src/main/java/bisq/core/notifications/alerts/price/PriceAlert.java b/core/src/main/java/bisq/core/notifications/alerts/price/PriceAlert.java index 3f75f0fe56d..4d57f4dad65 100644 --- a/core/src/main/java/bisq/core/notifications/alerts/price/PriceAlert.java +++ b/core/src/main/java/bisq/core/notifications/alerts/price/PriceAlert.java @@ -72,7 +72,7 @@ private void update() { String msg = Res.get("account.notifications.priceAlert.message.msg", currencyName, FormattingUtils.formatMarketPrice(priceAsDouble, currencyCode), - BSFormatter.getCurrencyPair(currencyCode)); + CurrencyUtil.getCurrencyPair(currencyCode)); MobileMessage message = new MobileMessage(Res.get("account.notifications.priceAlert.message.title", currencyName), msg, MobileMessageType.PRICE); diff --git a/core/src/main/java/bisq/core/util/BSFormatter.java b/core/src/main/java/bisq/core/util/BSFormatter.java index 1c79e407477..7a72f15c05f 100644 --- a/core/src/main/java/bisq/core/util/BSFormatter.java +++ b/core/src/main/java/bisq/core/util/BSFormatter.java @@ -142,28 +142,4 @@ public static String getRole(boolean isBuyerMakerAndSellerTaker, boolean isMaker } - public static String getCurrencyPair(String currencyCode) { - if (CurrencyUtil.isFiatCurrency(currencyCode)) - return Res.getBaseCurrencyCode() + "/" + currencyCode; - else - return currencyCode + "/" + Res.getBaseCurrencyCode(); - } - - public static String getCounterCurrency(String currencyCode) { - if (CurrencyUtil.isFiatCurrency(currencyCode)) - return currencyCode; - else - return Res.getBaseCurrencyCode(); - } - - public static String getPriceWithCurrencyCode(String currencyCode) { - return getPriceWithCurrencyCode(currencyCode, "shared.priceInCurForCur"); - } - - public static String getPriceWithCurrencyCode(String currencyCode, String translationKey) { - if (CurrencyUtil.isCryptoCurrency(currencyCode)) - return Res.get(translationKey, Res.getBaseCurrencyCode(), currencyCode); - else - return Res.get(translationKey, currencyCode, Res.getBaseCurrencyCode()); - } } diff --git a/desktop/src/main/java/bisq/desktop/main/market/MarketView.java b/desktop/src/main/java/bisq/desktop/main/market/MarketView.java index 5fe9b77f067..d006f08e058 100644 --- a/desktop/src/main/java/bisq/desktop/main/market/MarketView.java +++ b/desktop/src/main/java/bisq/desktop/main/market/MarketView.java @@ -32,6 +32,7 @@ import bisq.desktop.main.overlays.popups.Popup; import bisq.desktop.util.DisplayUtils; +import bisq.core.locale.CurrencyUtil; import bisq.core.locale.Res; import bisq.core.offer.OfferPayload; import bisq.core.trade.statistics.TradeStatistics2; @@ -185,7 +186,7 @@ private String getAllTradesWithReferralId() { StringBuilder sb = new StringBuilder(); sb.append("Trade ID: ").append(trade.getOfferId()).append("\n") .append("Date: ").append(DisplayUtils.formatDateTime(trade.getTradeDate())).append("\n") - .append("Market: ").append(BSFormatter.getCurrencyPair(trade.getCurrencyCode())).append("\n") + .append("Market: ").append(CurrencyUtil.getCurrencyPair(trade.getCurrencyCode())).append("\n") .append("Price: ").append(FormattingUtils.formatPrice(trade.getTradePrice())).append("\n") .append("Amount: ").append(formatter.formatCoin(trade.getTradeAmount())).append("\n") .append("Volume: ").append(DisplayUtils.formatVolume(trade.getTradeVolume())).append("\n") @@ -206,7 +207,7 @@ private String getAllOffersWithReferralId() { StringBuilder sb = new StringBuilder(); sb.append("Offer ID: ").append(offer.getId()).append("\n") .append("Type: ").append(offer.getDirection().name()).append("\n") - .append("Market: ").append(BSFormatter.getCurrencyPair(offer.getCurrencyCode())).append("\n") + .append("Market: ").append(CurrencyUtil.getCurrencyPair(offer.getCurrencyCode())).append("\n") .append("Price: ").append(FormattingUtils.formatPrice(offer.getPrice())).append("\n") .append("Amount: ").append(DisplayUtils.formatAmount(offer, formatter)).append(" BTC\n") .append("Payment method: ").append(Res.get(offer.getPaymentMethod().getId())).append("\n") diff --git a/desktop/src/main/java/bisq/desktop/main/market/offerbook/OfferBookChartView.java b/desktop/src/main/java/bisq/desktop/main/market/offerbook/OfferBookChartView.java index 8129df0c2d0..68001d63e4d 100644 --- a/desktop/src/main/java/bisq/desktop/main/market/offerbook/OfferBookChartView.java +++ b/desktop/src/main/java/bisq/desktop/main/market/offerbook/OfferBookChartView.java @@ -267,7 +267,7 @@ public Number fromString(String string) { priceColumnLabel.set(Res.get("shared.priceWithCur", code)); } - xAxis.setLabel(BSFormatter.getPriceWithCurrencyCode(code)); + xAxis.setLabel(CurrencyUtil.getPriceWithCurrencyCode(code)); seriesBuy.setName(leftHeaderLabel.getText() + " "); seriesSell.setName(rightHeaderLabel.getText()); diff --git a/desktop/src/main/java/bisq/desktop/main/market/trades/TradesChartsView.java b/desktop/src/main/java/bisq/desktop/main/market/trades/TradesChartsView.java index 57f88b34210..275d2d5decf 100644 --- a/desktop/src/main/java/bisq/desktop/main/market/trades/TradesChartsView.java +++ b/desktop/src/main/java/bisq/desktop/main/market/trades/TradesChartsView.java @@ -241,7 +241,7 @@ else if (model.getSelectedCurrencyListItem().isPresent()) String code = selectedTradeCurrency.getCode(); volumeColumn.setGraphic(new AutoTooltipLabel(Res.get("shared.amountWithCur", code))); - priceColumnLabel.set(BSFormatter.getPriceWithCurrencyCode(code)); + priceColumnLabel.set(CurrencyUtil.getPriceWithCurrencyCode(code)); tableView.getColumns().remove(marketColumn); } @@ -596,7 +596,7 @@ public TableCell call( public void updateItem(final TradeStatistics2 item, boolean empty) { super.updateItem(item, empty); if (item != null) - setText(BSFormatter.getCurrencyPair(item.getCurrencyCode())); + setText(CurrencyUtil.getCurrencyPair(item.getCurrencyCode())); else setText(""); } diff --git a/desktop/src/main/java/bisq/desktop/main/offer/MutableOfferView.java b/desktop/src/main/java/bisq/desktop/main/offer/MutableOfferView.java index b39c66c3f43..a9535131c62 100644 --- a/desktop/src/main/java/bisq/desktop/main/offer/MutableOfferView.java +++ b/desktop/src/main/java/bisq/desktop/main/offer/MutableOfferView.java @@ -553,11 +553,11 @@ protected void close() { /////////////////////////////////////////////////////////////////////////////////////////// private void addBindings() { - priceCurrencyLabel.textProperty().bind(createStringBinding(() -> BSFormatter.getCounterCurrency(model.tradeCurrencyCode.get()), model.tradeCurrencyCode)); + priceCurrencyLabel.textProperty().bind(createStringBinding(() -> CurrencyUtil.getCounterCurrency(model.tradeCurrencyCode.get()), model.tradeCurrencyCode)); marketBasedPriceLabel.prefWidthProperty().bind(priceCurrencyLabel.widthProperty()); volumeCurrencyLabel.textProperty().bind(model.tradeCurrencyCode); - priceDescriptionLabel.textProperty().bind(createStringBinding(() -> BSFormatter.getPriceWithCurrencyCode(model.tradeCurrencyCode.get(), "shared.fixedPriceInCurForCur"), model.tradeCurrencyCode)); + priceDescriptionLabel.textProperty().bind(createStringBinding(() -> CurrencyUtil.getPriceWithCurrencyCode(model.tradeCurrencyCode.get(), "shared.fixedPriceInCurForCur"), model.tradeCurrencyCode)); volumeDescriptionLabel.textProperty().bind(createStringBinding(model.volumeDescriptionLabel::get, model.tradeCurrencyCode, model.volumeDescriptionLabel)); amountTextField.textProperty().bindBidirectional(model.amount); minAmountTextField.textProperty().bindBidirectional(model.minAmount); diff --git a/desktop/src/main/java/bisq/desktop/main/offer/offerbook/OfferBookView.java b/desktop/src/main/java/bisq/desktop/main/offer/offerbook/OfferBookView.java index 60a3f597433..06c69fa7d49 100644 --- a/desktop/src/main/java/bisq/desktop/main/offer/offerbook/OfferBookView.java +++ b/desktop/src/main/java/bisq/desktop/main/offer/offerbook/OfferBookView.java @@ -236,7 +236,7 @@ public void initialize() { tableView.setPlaceholder(placeholder); marketColumn.setComparator(Comparator.comparing( - o -> BSFormatter.getCurrencyPair(o.getOffer().getCurrencyCode()), + o -> CurrencyUtil.getCurrencyPair(o.getOffer().getCurrencyCode()), Comparator.nullsFirst(Comparator.naturalOrder()) )); priceColumn.setComparator(Comparator.comparing(o -> o.getOffer().getPrice(), Comparator.nullsFirst(Comparator.naturalOrder()))); @@ -326,7 +326,7 @@ protected void activate() { tableView.getColumns().add(0, marketColumn); } else { volumeColumn.setTitleWithHelpText(Res.get("offerbook.volume", code), Res.get("shared.amountHelp")); - priceColumn.setTitle(BSFormatter.getPriceWithCurrencyCode(code)); + priceColumn.setTitle(CurrencyUtil.getPriceWithCurrencyCode(code)); priceColumn.getStyleClass().add("first-column"); tableView.getColumns().remove(marketColumn); @@ -697,7 +697,7 @@ public void updateItem(final OfferBookListItem item, boolean empty) { super.updateItem(item, empty); if (item != null && !empty) - setText(BSFormatter.getCurrencyPair(item.getOffer().getCurrencyCode())); + setText(CurrencyUtil.getCurrencyPair(item.getOffer().getCurrencyCode())); else setText(""); } diff --git a/desktop/src/main/java/bisq/desktop/main/offer/takeoffer/TakeOfferView.java b/desktop/src/main/java/bisq/desktop/main/offer/takeoffer/TakeOfferView.java index 5023ba847f5..65b1ff64a99 100644 --- a/desktop/src/main/java/bisq/desktop/main/offer/takeoffer/TakeOfferView.java +++ b/desktop/src/main/java/bisq/desktop/main/offer/takeoffer/TakeOfferView.java @@ -278,7 +278,7 @@ protected void activate() { String currencyCode = model.dataModel.getCurrencyCode(); volumeCurrencyLabel.setText(currencyCode); - priceDescriptionLabel.setText(BSFormatter.getPriceWithCurrencyCode(currencyCode)); + priceDescriptionLabel.setText(CurrencyUtil.getPriceWithCurrencyCode(currencyCode)); volumeDescriptionLabel.setText(model.volumeDescriptionLabel.get()); if (model.getPossiblePaymentAccounts().size() > 1) { @@ -599,7 +599,7 @@ private void addBindings() { totalToPayTextField.textProperty().bind(model.totalToPay); addressTextField.amountAsCoinProperty().bind(model.dataModel.getMissingCoin()); amountTextField.validationResultProperty().bind(model.amountValidationResult); - priceCurrencyLabel.textProperty().bind(createStringBinding(() -> BSFormatter.getCounterCurrency(model.dataModel.getCurrencyCode()))); + priceCurrencyLabel.textProperty().bind(createStringBinding(() -> CurrencyUtil.getCounterCurrency(model.dataModel.getCurrencyCode()))); priceAsPercentageLabel.prefWidthProperty().bind(priceCurrencyLabel.widthProperty()); nextButton.disableProperty().bind(model.isNextButtonDisabled); tradeFeeInBtcLabel.textProperty().bind(model.tradeFeeInBtcWithFiat); diff --git a/desktop/src/main/java/bisq/desktop/main/portfolio/closedtrades/ClosedTradesViewModel.java b/desktop/src/main/java/bisq/desktop/main/portfolio/closedtrades/ClosedTradesViewModel.java index 29a29e149a0..f6f146ef59b 100644 --- a/desktop/src/main/java/bisq/desktop/main/portfolio/closedtrades/ClosedTradesViewModel.java +++ b/desktop/src/main/java/bisq/desktop/main/portfolio/closedtrades/ClosedTradesViewModel.java @@ -22,6 +22,7 @@ import bisq.desktop.util.DisplayUtils; import bisq.core.account.witness.AccountAgeWitnessService; +import bisq.core.locale.CurrencyUtil; import bisq.core.locale.Res; import bisq.core.offer.OpenOffer; import bisq.core.trade.Tradable; @@ -136,7 +137,7 @@ String getMarketLabel(ClosedTradableListItem item) { if ((item == null)) return ""; - return BSFormatter.getCurrencyPair(item.getTradable().getOffer().getCurrencyCode()); + return CurrencyUtil.getCurrencyPair(item.getTradable().getOffer().getCurrencyCode()); } String getState(ClosedTradableListItem item) { diff --git a/desktop/src/main/java/bisq/desktop/main/portfolio/failedtrades/FailedTradesViewModel.java b/desktop/src/main/java/bisq/desktop/main/portfolio/failedtrades/FailedTradesViewModel.java index 1b3d9d7e19d..a3937f9c63c 100644 --- a/desktop/src/main/java/bisq/desktop/main/portfolio/failedtrades/FailedTradesViewModel.java +++ b/desktop/src/main/java/bisq/desktop/main/portfolio/failedtrades/FailedTradesViewModel.java @@ -21,6 +21,7 @@ import bisq.desktop.common.model.ViewModel; import bisq.desktop.util.DisplayUtils; +import bisq.core.locale.CurrencyUtil; import bisq.core.locale.Res; import bisq.core.util.BSFormatter; import bisq.core.util.FormattingUtils; @@ -74,7 +75,7 @@ String getMarketLabel(FailedTradesListItem item) { if ((item == null)) return ""; - return BSFormatter.getCurrencyPair(item.getTrade().getOffer().getCurrencyCode()); + return CurrencyUtil.getCurrencyPair(item.getTrade().getOffer().getCurrencyCode()); } String getDate(FailedTradesListItem item) { diff --git a/desktop/src/main/java/bisq/desktop/main/portfolio/openoffer/OpenOffersViewModel.java b/desktop/src/main/java/bisq/desktop/main/portfolio/openoffer/OpenOffersViewModel.java index 0b41cbc7619..11241be9122 100644 --- a/desktop/src/main/java/bisq/desktop/main/portfolio/openoffer/OpenOffersViewModel.java +++ b/desktop/src/main/java/bisq/desktop/main/portfolio/openoffer/OpenOffersViewModel.java @@ -22,6 +22,7 @@ import bisq.desktop.util.DisplayUtils; import bisq.desktop.util.GUIUtil; +import bisq.core.locale.CurrencyUtil; import bisq.core.locale.Res; import bisq.core.monetary.Price; import bisq.core.offer.Offer; @@ -112,7 +113,7 @@ String getMarketLabel(OpenOfferListItem item) { if ((item == null)) return ""; - return BSFormatter.getCurrencyPair(item.getOffer().getCurrencyCode()); + return CurrencyUtil.getCurrencyPair(item.getOffer().getCurrencyCode()); } String getDate(OpenOfferListItem item) { diff --git a/desktop/src/main/java/bisq/desktop/main/portfolio/pendingtrades/PendingTradesViewModel.java b/desktop/src/main/java/bisq/desktop/main/portfolio/pendingtrades/PendingTradesViewModel.java index 1bed862fc16..8883715c3e3 100644 --- a/desktop/src/main/java/bisq/desktop/main/portfolio/pendingtrades/PendingTradesViewModel.java +++ b/desktop/src/main/java/bisq/desktop/main/portfolio/pendingtrades/PendingTradesViewModel.java @@ -24,6 +24,7 @@ import bisq.core.account.witness.AccountAgeWitness; import bisq.core.account.witness.AccountAgeWitnessService; +import bisq.core.locale.CurrencyUtil; import bisq.core.locale.Res; import bisq.core.network.MessageState; import bisq.core.offer.Offer; @@ -202,7 +203,7 @@ String getMarketLabel(PendingTradesListItem item) { if ((item == null)) return ""; - return BSFormatter.getCurrencyPair(item.getTrade().getOffer().getCurrencyCode()); + return CurrencyUtil.getCurrencyPair(item.getTrade().getOffer().getCurrencyCode()); } private long getMaxTradePeriod() { diff --git a/desktop/src/main/java/bisq/desktop/main/presentation/MarketPricePresentation.java b/desktop/src/main/java/bisq/desktop/main/presentation/MarketPricePresentation.java index 6c80c0d4ed7..bacf3a4860d 100644 --- a/desktop/src/main/java/bisq/desktop/main/presentation/MarketPricePresentation.java +++ b/desktop/src/main/java/bisq/desktop/main/presentation/MarketPricePresentation.java @@ -143,7 +143,7 @@ private void setupMarketPriceFeed() { marketPriceBinding = EasyBind.combine( marketPriceCurrencyCode, marketPrice, - (currencyCode, price) -> BSFormatter.getCurrencyPair(currencyCode) + ": " + price); + (currencyCode, price) -> CurrencyUtil.getCurrencyPair(currencyCode) + ": " + price); marketPriceBinding.subscribe((observable, oldValue, newValue) -> { if (newValue != null && !newValue.equals(oldValue)) { @@ -202,7 +202,7 @@ private void setMarketPriceInItems() { priceString = Res.get("shared.na"); item.setPriceAvailable(false); } - item.setDisplayString(BSFormatter.getCurrencyPair(currencyCode) + ": " + priceString); + item.setDisplayString(CurrencyUtil.getCurrencyPair(currencyCode) + ": " + priceString); final String code = item.currencyCode; if (selectedPriceFeedComboBoxItemProperty.get() != null && diff --git a/desktop/src/main/java/bisq/desktop/main/support/dispute/DisputeView.java b/desktop/src/main/java/bisq/desktop/main/support/dispute/DisputeView.java index eb0048f7211..333fe0078a0 100644 --- a/desktop/src/main/java/bisq/desktop/main/support/dispute/DisputeView.java +++ b/desktop/src/main/java/bisq/desktop/main/support/dispute/DisputeView.java @@ -216,7 +216,7 @@ public void initialize() { dateColumn.setComparator(Comparator.comparing(Dispute::getOpeningDate)); buyerOnionAddressColumn.setComparator(Comparator.comparing(this::getBuyerOnionAddressColumnLabel)); sellerOnionAddressColumn.setComparator(Comparator.comparing(this::getSellerOnionAddressColumnLabel)); - marketColumn.setComparator((o1, o2) -> BSFormatter.getCurrencyPair(o1.getContract().getOfferPayload().getCurrencyCode()).compareTo(o2.getContract().getOfferPayload().getCurrencyCode())); + marketColumn.setComparator((o1, o2) -> CurrencyUtil.getCurrencyPair(o1.getContract().getOfferPayload().getCurrencyCode()).compareTo(o2.getContract().getOfferPayload().getCurrencyCode())); dateColumn.setSortType(TableColumn.SortType.DESCENDING); tableView.getSortOrder().add(dateColumn); @@ -733,7 +733,7 @@ public TableCell call(TableColumn column) { public void updateItem(final Dispute item, boolean empty) { super.updateItem(item, empty); if (item != null && !empty) - setText(BSFormatter.getCurrencyPair(item.getContract().getOfferPayload().getCurrencyCode())); + setText(CurrencyUtil.getCurrencyPair(item.getContract().getOfferPayload().getCurrencyCode())); else setText(""); } From cfaa23effc31c02fe6b578da9281072c19d8d946 Mon Sep 17 00:00:00 2001 From: Justin Carter Date: Mon, 18 Nov 2019 14:29:42 +0100 Subject: [PATCH 4/4] Move functions that only have 1 call-site out of BSFormatter Make them private instance functions at call site to minimize dependencies. --- .../main/java/bisq/core/util/BSFormatter.java | 32 ------------------- .../offer/offerbook/OfferBookViewModel.java | 9 +++++- .../pendingtrades/PendingTradesViewModel.java | 27 +++++++++++++++- 3 files changed, 34 insertions(+), 34 deletions(-) diff --git a/core/src/main/java/bisq/core/util/BSFormatter.java b/core/src/main/java/bisq/core/util/BSFormatter.java index 7a72f15c05f..164d63da754 100644 --- a/core/src/main/java/bisq/core/util/BSFormatter.java +++ b/core/src/main/java/bisq/core/util/BSFormatter.java @@ -104,42 +104,10 @@ public String formatCoinWithCode(long value) { return FormattingUtils.formatCoinWithCode(Coin.valueOf(value), monetaryFormat); } - public static String getDirectionWithCodeDetailed(OfferPayload.Direction direction, String currencyCode) { - if (CurrencyUtil.isFiatCurrency(currencyCode)) - return (direction == OfferPayload.Direction.BUY) ? Res.get("shared.buyingBTCWith", currencyCode) : Res.get("shared.sellingBTCFor", currencyCode); - else - return (direction == OfferPayload.Direction.SELL) ? Res.get("shared.buyingCurrency", currencyCode) : Res.get("shared.sellingCurrency", currencyCode); - } - public static String getDateFromBlockHeight(long blockHeight) { long now = new Date().getTime(); SimpleDateFormat dateFormatter = new SimpleDateFormat("dd MMM", Locale.getDefault()); SimpleDateFormat timeFormatter = new SimpleDateFormat("HH:mm", Locale.getDefault()); return FormattingUtils.formatDateTime(new Date(now + blockHeight * 10 * 60 * 1000L), dateFormatter, timeFormatter); } - - public static String getRole(boolean isBuyerMakerAndSellerTaker, boolean isMaker, String currencyCode) { - if (CurrencyUtil.isFiatCurrency(currencyCode)) { - String baseCurrencyCode = Res.getBaseCurrencyCode(); - if (isBuyerMakerAndSellerTaker) - return isMaker ? - Res.get("formatter.asMaker", baseCurrencyCode, Res.get("shared.buyer")) : - Res.get("formatter.asTaker", baseCurrencyCode, Res.get("shared.seller")); - else - return isMaker ? - Res.get("formatter.asMaker", baseCurrencyCode, Res.get("shared.seller")) : - Res.get("formatter.asTaker", baseCurrencyCode, Res.get("shared.buyer")); - } else { - if (isBuyerMakerAndSellerTaker) - return isMaker ? - Res.get("formatter.asMaker", currencyCode, Res.get("shared.seller")) : - Res.get("formatter.asTaker", currencyCode, Res.get("shared.buyer")); - else - return isMaker ? - Res.get("formatter.asMaker", currencyCode, Res.get("shared.buyer")) : - Res.get("formatter.asTaker", currencyCode, Res.get("shared.seller")); - } - - } - } diff --git a/desktop/src/main/java/bisq/desktop/main/offer/offerbook/OfferBookViewModel.java b/desktop/src/main/java/bisq/desktop/main/offer/offerbook/OfferBookViewModel.java index 036ef0a05c2..b40bb08a3a6 100644 --- a/desktop/src/main/java/bisq/desktop/main/offer/offerbook/OfferBookViewModel.java +++ b/desktop/src/main/java/bisq/desktop/main/offer/offerbook/OfferBookViewModel.java @@ -478,7 +478,7 @@ private boolean isF2F(Offer offer) { } String getDirectionLabelTooltip(Offer offer) { - return BSFormatter.getDirectionWithCodeDetailed(offer.getMirroredDirection(), offer.getCurrencyCode()); + return getDirectionWithCodeDetailed(offer.getMirroredDirection(), offer.getCurrencyCode()); } Optional getMostMaturePaymentAccountForOffer(Offer offer) { @@ -636,4 +636,11 @@ public String getMakerFeeAsString(Offer offer) { btcFormatter.formatCoinWithCode(offer.getMakerFee()) : bsqFormatter.formatCoinWithCode(offer.getMakerFee()); } + + private static String getDirectionWithCodeDetailed(OfferPayload.Direction direction, String currencyCode) { + if (CurrencyUtil.isFiatCurrency(currencyCode)) + return (direction == OfferPayload.Direction.BUY) ? Res.get("shared.buyingBTCWith", currencyCode) : Res.get("shared.sellingBTCFor", currencyCode); + else + return (direction == OfferPayload.Direction.SELL) ? Res.get("shared.buyingCurrency", currencyCode) : Res.get("shared.sellingCurrency", currencyCode); + } } diff --git a/desktop/src/main/java/bisq/desktop/main/portfolio/pendingtrades/PendingTradesViewModel.java b/desktop/src/main/java/bisq/desktop/main/portfolio/pendingtrades/PendingTradesViewModel.java index 8883715c3e3..34f8856240d 100644 --- a/desktop/src/main/java/bisq/desktop/main/portfolio/pendingtrades/PendingTradesViewModel.java +++ b/desktop/src/main/java/bisq/desktop/main/portfolio/pendingtrades/PendingTradesViewModel.java @@ -256,7 +256,7 @@ String getMyRole(PendingTradesListItem item) { Contract contract = trade.getContract(); if (contract != null) { Offer offer = trade.getOffer(); - return BSFormatter.getRole(contract.isBuyerMakerAndSellerTaker(), dataModel.isMaker(offer), offer.getCurrencyCode()); + return getRole(contract.isBuyerMakerAndSellerTaker(), dataModel.isMaker(offer), offer.getCurrencyCode()); } else { return ""; } @@ -482,4 +482,29 @@ private void onTradeStateChanged(Trade.State tradeState) { break; } } + + private static String getRole(boolean isBuyerMakerAndSellerTaker, boolean isMaker, String currencyCode) { + if (CurrencyUtil.isFiatCurrency(currencyCode)) { + String baseCurrencyCode = Res.getBaseCurrencyCode(); + if (isBuyerMakerAndSellerTaker) + return isMaker ? + Res.get("formatter.asMaker", baseCurrencyCode, Res.get("shared.buyer")) : + Res.get("formatter.asTaker", baseCurrencyCode, Res.get("shared.seller")); + else + return isMaker ? + Res.get("formatter.asMaker", baseCurrencyCode, Res.get("shared.seller")) : + Res.get("formatter.asTaker", baseCurrencyCode, Res.get("shared.buyer")); + } else { + if (isBuyerMakerAndSellerTaker) + return isMaker ? + Res.get("formatter.asMaker", currencyCode, Res.get("shared.seller")) : + Res.get("formatter.asTaker", currencyCode, Res.get("shared.buyer")); + else + return isMaker ? + Res.get("formatter.asMaker", currencyCode, Res.get("shared.buyer")) : + Res.get("formatter.asTaker", currencyCode, Res.get("shared.seller")); + } + + } + }