From da3a5098602f8177f6d5dac4a322f70d6fdf9126 Mon Sep 17 00:00:00 2001 From: Adrien Hopkins Date: Fri, 24 Dec 2021 16:03:26 -0500 Subject: Did some API design for user settings, and moved GUI to a new package --- .../java/sevenUnitsGUI/StandardDisplayRules.java | 74 ++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 src/main/java/sevenUnitsGUI/StandardDisplayRules.java (limited to 'src/main/java/sevenUnitsGUI/StandardDisplayRules.java') diff --git a/src/main/java/sevenUnitsGUI/StandardDisplayRules.java b/src/main/java/sevenUnitsGUI/StandardDisplayRules.java new file mode 100644 index 0000000..331f598 --- /dev/null +++ b/src/main/java/sevenUnitsGUI/StandardDisplayRules.java @@ -0,0 +1,74 @@ +/** + * Copyright (C) 2021 Adrien Hopkins + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +package sevenUnitsGUI; + +import java.util.function.Function; + +import sevenUnits.utils.UncertainDouble; + +/** + * The default rules for displaying numbers. + * + * Unless otherwise stated, all of this class's functions throw + * {@link NullPointerException} when they receive a null parameter. + * + * @since 2021-12-24 + */ +final class StandardDisplayRules { + /** + * Rounds using UncertainDouble's toString method. + */ + private static final Function SCIENTIFIC_ROUNDING_RULE = new Function<>() { + @Override + public String apply(UncertainDouble t) { + return t.toString(false); + } + + @Override + public String toString() { + return "Scientific Rounding"; + } + }; + + /** + * @return a rule that rounds using UncertainDouble's own toString(false) + * function. + * @since 2021-12-24 + */ + public static final Function getScientificRule() { + return SCIENTIFIC_ROUNDING_RULE; + } + + /** + * Gets one of the standard rules from its string representation. + * + * @param ruleToString string representation of the display rule + * @return display rule + * @throws IllegalArgumentException if the provided string is not that of a + * standard rule. + * @since 2021-12-24 + */ + public static final Function getStandardRule( + String ruleToString) { + throw new UnsupportedOperationException("Not implemented yet"); + } + + private StandardDisplayRules() { + throw new AssertionError( + "This is a static utility class, you may not get instances of it."); + } +} -- cgit v1.2.3 From 4aaf6a8b60fbec63c2e0bee624b3859ded0ecde3 Mon Sep 17 00:00:00 2001 From: Adrien Hopkins Date: Sat, 16 Apr 2022 15:57:00 -0500 Subject: Added a full suite of frontend tests (Added tests for the settings and unit/prefix viewer parts of the GUI, which are not yet implemented) --- src/main/java/sevenUnits/unit/UnitPrefix.java | 135 +++++-------- src/main/java/sevenUnitsGUI/Presenter.java | 14 +- .../java/sevenUnitsGUI/StandardDisplayRules.java | 26 +++ src/main/java/sevenUnitsGUI/ViewBot.java | 200 +++++++++++++++++++- src/test/java/sevenUnitsGUI/PresenterTest.java | 210 +++++++++++++++++++-- 5 files changed, 482 insertions(+), 103 deletions(-) (limited to 'src/main/java/sevenUnitsGUI/StandardDisplayRules.java') diff --git a/src/main/java/sevenUnits/unit/UnitPrefix.java b/src/main/java/sevenUnits/unit/UnitPrefix.java index bf9d1fd..e1f7788 100644 --- a/src/main/java/sevenUnits/unit/UnitPrefix.java +++ b/src/main/java/sevenUnits/unit/UnitPrefix.java @@ -17,69 +17,59 @@ package sevenUnits.unit; import java.util.Objects; -import java.util.Optional; -import java.util.Set; import sevenUnits.utils.DecimalComparison; import sevenUnits.utils.NameSymbol; +import sevenUnits.utils.Nameable; /** - * A prefix that can be applied to a {@code LinearUnit} to multiply it by some value + * A prefix that can be applied to a {@code LinearUnit} to multiply it by some + * value * * @author Adrien Hopkins * @since 2019-10-16 */ -public final class UnitPrefix { +public final class UnitPrefix implements Nameable { /** * Gets a {@code UnitPrefix} from a multiplier * - * @param multiplier - * multiplier of prefix + * @param multiplier multiplier of prefix * @return prefix * @since 2019-10-16 */ public static UnitPrefix valueOf(final double multiplier) { return new UnitPrefix(multiplier, NameSymbol.EMPTY); } - + /** * Gets a {@code UnitPrefix} from a multiplier and a name * - * @param multiplier - * multiplier of prefix - * @param ns - * name(s) and symbol of prefix + * @param multiplier multiplier of prefix + * @param ns name(s) and symbol of prefix * @return prefix * @since 2019-10-16 - * @throws NullPointerException - * if ns is null + * @throws NullPointerException if ns is null */ - public static UnitPrefix valueOf(final double multiplier, final NameSymbol ns) { - return new UnitPrefix(multiplier, Objects.requireNonNull(ns, "ns must not be null.")); + public static UnitPrefix valueOf(final double multiplier, + final NameSymbol ns) { + return new UnitPrefix(multiplier, + Objects.requireNonNull(ns, "ns must not be null.")); } - - /** - * This prefix's primary name - */ - private final Optional primaryName; - - /** - * This prefix's symbol - */ - private final Optional symbol; - + /** - * Other names and symbols used by this prefix + * This prefix's name(s) and symbol. + * + * @since 2022-04-16 */ - private final Set otherNames; - + private final NameSymbol nameSymbol; + /** * The number that this prefix multiplies units by * * @since 2019-10-16 */ private final double multiplier; - + /** * Creates the {@code DefaultUnitPrefix}. * @@ -89,28 +79,24 @@ public final class UnitPrefix { */ private UnitPrefix(final double multiplier, final NameSymbol ns) { this.multiplier = multiplier; - this.primaryName = ns.getPrimaryName(); - this.symbol = ns.getSymbol(); - this.otherNames = ns.getOtherNames(); + this.nameSymbol = ns; } - + /** * Divides this prefix by a scalar * - * @param divisor - * number to divide by + * @param divisor number to divide by * @return quotient of prefix and scalar * @since 2019-10-16 */ public UnitPrefix dividedBy(final double divisor) { return valueOf(this.getMultiplier() / divisor); } - + /** * Divides this prefix by {@code other}. * - * @param other - * prefix to divide by + * @param other prefix to divide by * @return quotient of prefixes * @since 2019-04-13 * @since v0.2.0 @@ -118,7 +104,7 @@ public final class UnitPrefix { public UnitPrefix dividedBy(final UnitPrefix other) { return valueOf(this.getMultiplier() / other.getMultiplier()); } - + /** * {@inheritDoc} * @@ -133,9 +119,10 @@ public final class UnitPrefix { if (!(obj instanceof UnitPrefix)) return false; final UnitPrefix other = (UnitPrefix) obj; - return DecimalComparison.equals(this.getMultiplier(), other.getMultiplier()); + return DecimalComparison.equals(this.getMultiplier(), + other.getMultiplier()); } - + /** * @return prefix's multiplier * @since 2019-11-26 @@ -143,31 +130,12 @@ public final class UnitPrefix { public double getMultiplier() { return this.multiplier; } - - /** - * @return other names - * @since 2019-11-26 - */ - public final Set getOtherNames() { - return this.otherNames; - } - - /** - * @return primary name - * @since 2019-11-26 - */ - public final Optional getPrimaryName() { - return this.primaryName; - } - - /** - * @return symbol - * @since 2019-11-26 - */ - public final Optional getSymbol() { - return this.symbol; + + @Override + public NameSymbol getNameSymbol() { + return this.nameSymbol; } - + /** * {@inheritDoc} * @@ -177,24 +145,22 @@ public final class UnitPrefix { public int hashCode() { return DecimalComparison.hash(this.getMultiplier()); } - + /** * Multiplies this prefix by a scalar * - * @param multiplicand - * number to multiply by + * @param multiplicand number to multiply by * @return product of prefix and scalar * @since 2019-10-16 */ public UnitPrefix times(final double multiplicand) { return valueOf(this.getMultiplier() * multiplicand); } - + /** * Multiplies this prefix by {@code other}. * - * @param other - * prefix to multiply by + * @param other prefix to multiply by * @return product of prefixes * @since 2019-04-13 * @since v0.2.0 @@ -202,12 +168,11 @@ public final class UnitPrefix { public UnitPrefix times(final UnitPrefix other) { return valueOf(this.getMultiplier() * other.getMultiplier()); } - + /** * Raises this prefix to an exponent. * - * @param exponent - * exponent to raise to + * @param exponent exponent to raise to * @return result of exponentiation. * @since 2019-04-13 * @since v0.2.0 @@ -215,27 +180,27 @@ public final class UnitPrefix { public UnitPrefix toExponent(final double exponent) { return valueOf(Math.pow(this.getMultiplier(), exponent)); } - + /** * @return a string describing the prefix and its multiplier */ @Override public String toString() { - if (this.primaryName.isPresent()) - return String.format("%s (\u00D7 %s)", this.primaryName.get(), this.multiplier); - else if (this.symbol.isPresent()) - return String.format("%s (\u00D7 %s)", this.symbol.get(), this.multiplier); + if (this.getPrimaryName().isPresent()) + return String.format("%s (\u00D7 %s)", this.getPrimaryName().get(), + this.multiplier); + else if (this.getSymbol().isPresent()) + return String.format("%s (\u00D7 %s)", this.getSymbol().get(), + this.multiplier); else return String.format("Unit Prefix (\u00D7 %s)", this.multiplier); } - + /** - * @param ns - * name(s) and symbol to use + * @param ns name(s) and symbol to use * @return copy of this prefix with provided name(s) and symbol * @since 2019-11-26 - * @throws NullPointerException - * if ns is null + * @throws NullPointerException if ns is null */ public UnitPrefix withName(final NameSymbol ns) { return valueOf(this.multiplier, ns); diff --git a/src/main/java/sevenUnitsGUI/Presenter.java b/src/main/java/sevenUnitsGUI/Presenter.java index b38f90b..5c8ce53 100644 --- a/src/main/java/sevenUnitsGUI/Presenter.java +++ b/src/main/java/sevenUnitsGUI/Presenter.java @@ -18,6 +18,7 @@ package sevenUnitsGUI; import java.io.IOException; import java.io.InputStream; +import java.nio.file.Path; import java.util.ArrayList; import java.util.HashSet; import java.util.List; @@ -50,7 +51,8 @@ import sevenUnits.utils.UncertainDouble; */ public final class Presenter { /** The default place where settings are stored. */ - private static final String DEFAULT_SETTINGS_FILEPATH = "settings.txt"; + private static final Path DEFAULT_SETTINGS_FILEPATH = Path + .of("settings.txt"); /** The default place where units are stored. */ private static final String DEFAULT_UNITS_FILEPATH = "/unitsfile.txt"; /** The default place where dimensions are stored. */ @@ -406,17 +408,18 @@ public final class Presenter { * * @since 2022-03-30 */ - public boolean isOneWayConversionEnabled() { + public boolean oneWayConversionEnabled() { return this.oneWayConversionEnabled; } /** * Loads settings from the user's settings file and applies them to the * presenter. - * + * + * @param settingsFile file settings should be loaded from * @since 2021-12-15 */ - private void loadSettings() {} + void loadSettings(Path settingsFile) {} /** * Completes creation of the presenter. This part of the initialization @@ -438,9 +441,10 @@ public final class Presenter { /** * Saves the presenter's settings to the user settings file. * + * @param settingsFile file settings should be saved to * @since 2021-12-15 */ - private void saveSettings() {} + void saveSettings(Path settingsFile) {} /** * @param numberDisplayRule the new rule that will be used by this presenter diff --git a/src/main/java/sevenUnitsGUI/StandardDisplayRules.java b/src/main/java/sevenUnitsGUI/StandardDisplayRules.java index 331f598..f6272c8 100644 --- a/src/main/java/sevenUnitsGUI/StandardDisplayRules.java +++ b/src/main/java/sevenUnitsGUI/StandardDisplayRules.java @@ -44,6 +44,32 @@ final class StandardDisplayRules { } }; + /** + * Gets a display rule that rounds numbers to a fixed number of decimal + * places. + * + * @param decimalPlaces number of decimal places + * @return display rule + * @since 2022-04-16 + */ + public static final Function getFixedPlacesRule( + int decimalPlaces) { + throw new UnsupportedOperationException("Not implemented yet"); + } + + /** + * Gets a display rule that rounds numbers to a fixed number of significant + * figures. + * + * @param significantFigures number of significant figures + * @return display rule + * @since 2022-04-16 + */ + public static final Function getFixedPrecisionRule( + int significantFigures) { + throw new UnsupportedOperationException("Not implemented yet"); + } + /** * @return a rule that rounds using UncertainDouble's own toString(false) * function. diff --git a/src/main/java/sevenUnitsGUI/ViewBot.java b/src/main/java/sevenUnitsGUI/ViewBot.java index 9f9a524..988d1bc 100644 --- a/src/main/java/sevenUnitsGUI/ViewBot.java +++ b/src/main/java/sevenUnitsGUI/ViewBot.java @@ -25,6 +25,7 @@ import java.util.Set; import sevenUnits.unit.UnitType; import sevenUnits.utils.NameSymbol; +import sevenUnits.utils.Nameable; /** * A class that simulates a View (supports both unit and expression conversion) @@ -34,6 +35,163 @@ import sevenUnits.utils.NameSymbol; * @since 2022-01-29 */ final class ViewBot implements UnitConversionView, ExpressionConversionView { + /** + * A record of the parameters given to + * {@link View#showPrefix(NameSymbol, String)}, for testing. + * + * @since 2022-04-16 + */ + public static final class PrefixViewingRecord implements Nameable { + private final NameSymbol nameSymbol; + private final String multiplierString; + + /** + * @param nameSymbol + * @param multiplierString + * @since 2022-04-16 + */ + public PrefixViewingRecord(NameSymbol nameSymbol, + String multiplierString) { + this.nameSymbol = nameSymbol; + this.multiplierString = multiplierString; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (!(obj instanceof PrefixViewingRecord)) + return false; + final PrefixViewingRecord other = (PrefixViewingRecord) obj; + return Objects.equals(this.multiplierString, other.multiplierString) + && Objects.equals(this.nameSymbol, other.nameSymbol); + } + + @Override + public NameSymbol getNameSymbol() { + return this.nameSymbol; + } + + @Override + public int hashCode() { + return Objects.hash(this.multiplierString, this.nameSymbol); + } + + public String multiplierString() { + return this.multiplierString; + } + + public NameSymbol nameSymbol() { + return this.nameSymbol; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("PrefixViewingRecord [nameSymbol="); + builder.append(this.nameSymbol); + builder.append(", multiplierString="); + builder.append(this.multiplierString); + builder.append("]"); + return builder.toString(); + } + } + + /** + * A record of the parameters given to + * {@link View#showUnit(NameSymbol, String, String, UnitType)}, for testing. + * + * @since 2022-04-16 + */ + public static final class UnitViewingRecord implements Nameable { + private final NameSymbol nameSymbol; + private final String definition; + private final String dimensionName; + private final UnitType unitType; + + /** + * @since 2022-04-16 + */ + public UnitViewingRecord(NameSymbol nameSymbol, String definition, + String dimensionName, UnitType unitType) { + this.nameSymbol = nameSymbol; + this.definition = definition; + this.dimensionName = dimensionName; + this.unitType = unitType; + } + + /** + * @return the definition + * @since 2022-04-16 + */ + public String definition() { + return this.definition; + } + + /** + * @return the dimensionName + * @since 2022-04-16 + */ + public String dimensionName() { + return this.dimensionName; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (!(obj instanceof UnitViewingRecord)) + return false; + final UnitViewingRecord other = (UnitViewingRecord) obj; + return Objects.equals(this.definition, other.definition) + && Objects.equals(this.dimensionName, other.dimensionName) + && Objects.equals(this.nameSymbol, other.nameSymbol) + && this.unitType == other.unitType; + } + + /** + * @return the nameSymbol + * @since 2022-04-16 + */ + @Override + public NameSymbol getNameSymbol() { + return this.nameSymbol; + } + + @Override + public int hashCode() { + return Objects.hash(this.definition, this.dimensionName, + this.nameSymbol, this.unitType); + } + + public NameSymbol nameSymbol() { + return this.nameSymbol; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("UnitViewingRecord [nameSymbol="); + builder.append(this.nameSymbol); + builder.append(", definition="); + builder.append(this.definition); + builder.append(", dimensionName="); + builder.append(this.dimensionName); + builder.append(", unitType="); + builder.append(this.unitType); + builder.append("]"); + return builder.toString(); + } + + /** + * @return the unitType + * @since 2022-04-16 + */ + public UnitType unitType() { + return this.unitType; + } + } + /** The presenter that works with this ViewBot */ private final Presenter presenter; @@ -62,6 +220,10 @@ final class ViewBot implements UnitConversionView, ExpressionConversionView { private final List unitConversions; /** Saved outputs of all unit expressions */ private final List expressionConversions; + /** Saved outputs of all unit viewings */ + private final List unitViewingRecords; + /** Saved outputs of all prefix viewings */ + private final List prefixViewingRecords; /** * Creates a new {@code ViewBot} with a new presenter. @@ -73,6 +235,8 @@ final class ViewBot implements UnitConversionView, ExpressionConversionView { this.unitConversions = new ArrayList<>(); this.expressionConversions = new ArrayList<>(); + this.unitViewingRecords = new ArrayList<>(); + this.prefixViewingRecords = new ArrayList<>(); } /** @@ -80,7 +244,7 @@ final class ViewBot implements UnitConversionView, ExpressionConversionView { * @since 2022-04-09 */ public List expressionConversionList() { - return this.expressionConversions; + return Collections.unmodifiableList(this.expressionConversions); } /** @@ -158,6 +322,14 @@ final class ViewBot implements UnitConversionView, ExpressionConversionView { throw new UnsupportedOperationException("Not implemented yet"); } + /** + * @return list of records of this viewBot's prefix views + * @since 2022-04-16 + */ + public List prefixViewList() { + return Collections.unmodifiableList(this.prefixViewingRecords); + } + @Override public void setDimensionNames(Set dimensionNames) { this.dimensionNames = Objects.requireNonNull(dimensionNames, @@ -259,6 +431,24 @@ final class ViewBot implements UnitConversionView, ExpressionConversionView { throw new UnsupportedOperationException("Not implemented yet"); } + public void setViewedPrefixName( + @SuppressWarnings("unused") Optional viewedPrefixName) { + throw new UnsupportedOperationException("Not implemented yet"); + } + + public void setViewedPrefixName(String viewedPrefixName) { + this.setViewedPrefixName(Optional.of(viewedPrefixName)); + } + + public void setViewedUnitName( + @SuppressWarnings("unused") Optional viewedUnitName) { + throw new UnsupportedOperationException("Not implemented yet"); + } + + public void setViewedUnitName(String viewedUnitName) { + this.setViewedUnitName(Optional.of(viewedUnitName)); + } + @Override public void showErrorMessage(String title, String message) { System.err.printf("%s: %s%n", title, message); @@ -299,4 +489,12 @@ final class ViewBot implements UnitConversionView, ExpressionConversionView { public List unitConversionList() { return Collections.unmodifiableList(this.unitConversions); } + + /** + * @return list of records of unit viewings made by this bot + * @since 2022-04-16 + */ + public List unitViewList() { + return Collections.unmodifiableList(this.unitViewingRecords); + } } diff --git a/src/test/java/sevenUnitsGUI/PresenterTest.java b/src/test/java/sevenUnitsGUI/PresenterTest.java index 3fe7e47..85ebe09 100644 --- a/src/test/java/sevenUnitsGUI/PresenterTest.java +++ b/src/test/java/sevenUnitsGUI/PresenterTest.java @@ -17,20 +17,29 @@ package sevenUnitsGUI; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assumptions.assumeTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; +import java.nio.file.Path; import java.util.List; import java.util.Set; +import java.util.function.Function; import java.util.stream.Collectors; +import java.util.stream.Stream; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import sevenUnits.unit.BaseDimension; +import sevenUnits.unit.BritishImperial; import sevenUnits.unit.Metric; import sevenUnits.unit.Unit; +import sevenUnits.unit.UnitType; import sevenUnits.unit.UnitValue; +import sevenUnits.utils.NameSymbol; import sevenUnits.utils.Nameable; import sevenUnits.utils.ObjectProduct; +import sevenUnits.utils.UncertainDouble; /** * @author Adrien Hopkins @@ -38,12 +47,27 @@ import sevenUnits.utils.ObjectProduct; * @since 2022-02-10 */ public final class PresenterTest { + private static final Path TEST_SETTINGS = Path.of("src", "test", "resources", + "test-settings.txt"); static final Set testUnits = Set.of(Metric.METRE, Metric.KILOMETRE, Metric.METRE_PER_SECOND, Metric.KILOMETRE_PER_HOUR); static final Set> testDimensions = Set .of(Metric.Dimensions.LENGTH, Metric.Dimensions.VELOCITY); + /** + * @return rounding rules used by {@link #testRoundingRules} + * @since 2022-04-16 + */ + private static final Stream> getRoundingRules() { + final var SCIENTIFIC_ROUNDING = StandardDisplayRules.getScientificRule(); + final var INTEGER_ROUNDING = StandardDisplayRules.getFixedPlacesRule(0); + final var SIG_FIG_ROUNDING = StandardDisplayRules + .getFixedPrecisionRule(4); + + return Stream.of(SCIENTIFIC_ROUNDING, INTEGER_ROUNDING, SIG_FIG_ROUNDING); + } + private static final Set names(Set units) { return units.stream().map(Nameable::getName).collect(Collectors.toSet()); } @@ -106,23 +130,185 @@ public final class PresenterTest { assertEquals(List.of(expectedUC), viewBot.unitConversionList()); } + /** + * Tests that duplicate units are successfully removed, if that is asked for + * + * @since 2022-04-16 + */ @Test void testDuplicateUnits() { - assumeTrue(false, "Not yet implemented"); - /* - * enable and disable duplicate units and check for those in From and To, - * include duplicate units in the input set - */ + final var metre = Metric.METRE; + final var meter = Metric.METRE.withName(NameSymbol.of("meter", "m")); + + // load 2 duplicate units + final var viewBot = new ViewBot(); + final var presenter = new Presenter(viewBot); + presenter.database.clear(); + presenter.database.addUnit("metre", metre); + presenter.database.addUnit("meter", meter); + + // test that only one of them is included if duplicate units disabled + presenter.setShowDuplicateUnits(false); + presenter.updateView(); + assertEquals(1, viewBot.getFromUnitNames().size()); + assertEquals(1, viewBot.getToUnitNames().size()); + + // test that both of them is included if duplicate units enabled + presenter.setShowDuplicateUnits(true); + presenter.updateView(); + assertEquals(2, viewBot.getFromUnitNames().size()); + assertEquals(2, viewBot.getToUnitNames().size()); } + /** + * Tests that one-way conversion correctly filters From and To units + * + * @since 2022-04-16 + */ @Test void testOneWayConversion() { - assumeTrue(false, "Not yet implemented"); - /* - * enable and disable one-way conversion, testing the units in From and To - * on each setting to ensure they match the rule. Include at least one - * metric exception. - */ + // metre is metric, inch is non-metric, tempC is semi-metric + final var allNames = Set.of("metre", "inch", "tempC"); + final var metricNames = Set.of("metre", "tempC"); + final var nonMetricNames = Set.of("inch", "tempC"); + + // load view with one metric and one non-metric unit + final var viewBot = new ViewBot(); + final var presenter = new Presenter(viewBot); + presenter.database.clear(); + presenter.database.addUnit("metre", Metric.METRE); + presenter.database.addUnit("inch", BritishImperial.Length.INCH); + presenter.database.addUnit("tempC", Metric.CELSIUS); + + // test that units are removed from each side when one-way conversion is + // enabled + presenter.setOneWayConversionEnabled(true); + presenter.updateView(); + assertEquals(metricNames, viewBot.getFromUnitNames()); + assertEquals(nonMetricNames, viewBot.getToUnitNames()); + + // test that units are kept when one-way conversion is disabled + presenter.setOneWayConversionEnabled(false); + presenter.updateView(); + assertEquals(allNames, viewBot.getFromUnitNames()); + assertEquals(allNames, viewBot.getToUnitNames()); + } + + /** + * Tests the prefix-viewing functionality. + * + * @since 2022-04-16 + */ + @Test + void testPrefixViewing() { + // setup + final var viewBot = new ViewBot(); + final var presenter = new Presenter(viewBot); + viewBot.setViewablePrefixNames(Set.of("kilo", "milli")); + presenter.setNumberDisplayRule(UncertainDouble::toString); + + // view prefix + viewBot.setViewedPrefixName("kilo"); + presenter.prefixSelected(); // just in case + + // get correct values + final var expectedNameSymbol = Metric.KILO.getNameSymbol(); + final var expectedMultiplierString = String + .valueOf(Metric.KILO.getMultiplier()); + + // test that presenter's values are correct + final var prefixRecord = viewBot.prefixViewList().get(0); + assertEquals(expectedNameSymbol, prefixRecord.getNameSymbol()); + assertEquals(expectedMultiplierString, prefixRecord.multiplierString()); + } + + /** + * Tests that rounding rules are used correctly. + * + * @since 2022-04-16 + */ + @ParameterizedTest + @MethodSource("getRoundingRules") + void testRoundingRules(Function roundingRule) { + // setup + final var viewBot = new ViewBot(); + final var presenter = new Presenter(viewBot); + presenter.setNumberDisplayRule(roundingRule); + + // convert and round + viewBot.setInputValue("12345.6789"); + viewBot.setFromSelection("metre"); + viewBot.setToSelection("kilometre"); + presenter.convertUnits(); + + // test the result of the rounding + final String expectedOutputString = roundingRule + .apply(UncertainDouble.of(12.3456789, 0)); + final String actualOutputString = viewBot.unitConversionList().get(0) + .outputValueString(); + assertEquals(expectedOutputString, actualOutputString); + } + + /** + * Tests that settings can be saved to and loaded from a file. + * + * @since 2022-04-16 + */ + @Test + void testSettingsSaving() { + // setup + final var viewBot = new ViewBot(); + final var presenter = new Presenter(viewBot); + + // set and save custom settings + presenter.setOneWayConversionEnabled(true); + presenter.setShowDuplicateUnits(true); + presenter.setNumberDisplayRule( + StandardDisplayRules.getFixedPrecisionRule(11)); + presenter.saveSettings(TEST_SETTINGS); + + // overwrite custom settings + presenter.setOneWayConversionEnabled(false); + presenter.setShowDuplicateUnits(false); + presenter.setNumberDisplayRule(StandardDisplayRules.getScientificRule()); + + // load settings & test that they're the same + presenter.loadSettings(TEST_SETTINGS); + assertTrue(presenter.oneWayConversionEnabled()); + assertTrue(presenter.duplicateUnitsShown()); + assertEquals(StandardDisplayRules.getFixedPlacesRule(11), + presenter.getNumberDisplayRule()); + } + + /** + * Ensures the Presenter generates the correct data upon a unit-viewing. + * + * @since 2022-04-16 + */ + @Test + void testUnitViewing() { + // setup + final var viewBot = new ViewBot(); + final var presenter = new Presenter(viewBot); + viewBot.setViewableUnitNames(names(testUnits)); + + // view unit + viewBot.setViewedUnitName("metre"); + presenter.unitNameSelected(); // just in case this isn't triggered + // automatically + + // get correct values + final var expectedNameSymbol = Metric.METRE.getNameSymbol(); + final var expectedDefinition = Metric.METRE.toDefinitionString(); + final var expectedDimensionName = Metric.METRE.getDimension().getName(); + final var expectedUnitType = UnitType.METRIC; + + // test for correctness + final var viewRecord = viewBot.unitViewList().get(0); + assertEquals(expectedNameSymbol, viewRecord.getNameSymbol()); + assertEquals(expectedDefinition, viewRecord.definition()); + assertEquals(expectedDimensionName, viewRecord.dimensionName()); + assertEquals(expectedUnitType, viewRecord.unitType()); } /** -- cgit v1.2.3 From f0541a955b6e4b12d808cffec0874f50a004e8b9 Mon Sep 17 00:00:00 2001 From: Adrien Hopkins Date: Mon, 18 Apr 2022 17:01:54 -0500 Subject: Implemented rounding and duplicate-removal settings into the new GUI --- CHANGELOG.org | 2 + .../sevenUnits/converterGUI/SevenUnitsGUI.java | 2 +- src/main/java/sevenUnits/unit/LinearUnitValue.java | 10 +- src/main/java/sevenUnits/unit/UnitDatabase.java | 6 +- .../java/sevenUnits/utils/UncertainDouble.java | 24 +- src/main/java/sevenUnitsGUI/Presenter.java | 56 ++++- .../java/sevenUnitsGUI/StandardDisplayRules.java | 220 +++++++++++++--- src/main/java/sevenUnitsGUI/TabbedView.java | 280 +++++++++++++++++---- src/test/java/sevenUnits/unit/UnitTest.java | 14 +- .../java/sevenUnits/utils/UncertainDoubleTest.java | 11 + src/test/java/sevenUnitsGUI/PresenterTest.java | 14 +- 11 files changed, 518 insertions(+), 121 deletions(-) (limited to 'src/main/java/sevenUnitsGUI/StandardDisplayRules.java') diff --git a/CHANGELOG.org b/CHANGELOG.org index 61d9333..c164d1f 100644 --- a/CHANGELOG.org +++ b/CHANGELOG.org @@ -10,6 +10,8 @@ - BaseDimension is now Nameable. As a consequence, its name and symbol return Optional instead of String, even though they will always succeed. - The UnitDatabase's units, prefixes and dimensions are now always named - The toString method of the common unit classes is now simpler. Alternate toString functions that describe the full unit are provided. + - UncertainDouble and LinearUnitValue accept a RoundingMode in their complicated toString functions. + - Rounding rules are now in their own classes - Tweaked the look of the unit and expression conversion sections of the view ** v0.3.2 - [2021-12-02 Thu] *** Added diff --git a/src/main/java/sevenUnits/converterGUI/SevenUnitsGUI.java b/src/main/java/sevenUnits/converterGUI/SevenUnitsGUI.java index 55e1546..e10bab4 100644 --- a/src/main/java/sevenUnits/converterGUI/SevenUnitsGUI.java +++ b/src/main/java/sevenUnits/converterGUI/SevenUnitsGUI.java @@ -488,7 +488,7 @@ final class SevenUnitsGUI { case SIGNIFICANT_DIGITS: return this.getRoundedString(value.asUnitValue()); case SCIENTIFIC: - return value.toString(showUncertainty); + return value.toString(showUncertainty, RoundingMode.HALF_EVEN); default: throw new AssertionError("Invalid switch condition."); } diff --git a/src/main/java/sevenUnits/unit/LinearUnitValue.java b/src/main/java/sevenUnits/unit/LinearUnitValue.java index a50e1f5..f91d30b 100644 --- a/src/main/java/sevenUnits/unit/LinearUnitValue.java +++ b/src/main/java/sevenUnits/unit/LinearUnitValue.java @@ -16,6 +16,7 @@ */ package sevenUnits.unit; +import java.math.RoundingMode; import java.util.Objects; import java.util.Optional; @@ -300,7 +301,7 @@ public final class LinearUnitValue { @Override public String toString() { - return this.toString(!this.value.isExact()); + return this.toString(!this.value.isExact(), RoundingMode.HALF_EVEN); } /** @@ -315,7 +316,8 @@ public final class LinearUnitValue { * * @since 2020-07-26 */ - public String toString(final boolean showUncertainty) { + public String toString(final boolean showUncertainty, + RoundingMode roundingMode) { final Optional primaryName = this.unit.getPrimaryName(); final Optional symbol = this.unit.getSymbol(); final String chosenName = symbol.orElse(primaryName.orElse(null)); @@ -325,10 +327,10 @@ public final class LinearUnitValue { // get rounded strings // if showUncertainty is true, add brackets around the string final String valueString = (showUncertainty ? "(" : "") - + this.value.toString(showUncertainty) + + this.value.toString(showUncertainty, roundingMode) + (showUncertainty ? ")" : ""); final String baseValueString = (showUncertainty ? "(" : "") - + baseValue.toString(showUncertainty) + + baseValue.toString(showUncertainty, roundingMode) + (showUncertainty ? ")" : ""); // create string diff --git a/src/main/java/sevenUnits/unit/UnitDatabase.java b/src/main/java/sevenUnits/unit/UnitDatabase.java index 7b02ac7..a4f0c44 100644 --- a/src/main/java/sevenUnits/unit/UnitDatabase.java +++ b/src/main/java/sevenUnits/unit/UnitDatabase.java @@ -19,7 +19,6 @@ package sevenUnits.unit; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; -import java.math.BigDecimal; import java.nio.file.Files; import java.nio.file.Path; import java.util.AbstractSet; @@ -1705,11 +1704,8 @@ public final class UnitDatabase { LinearUnitValue getLinearUnitValue(final String name) { try { // try to parse it as a number - otherwise it is not a number! - final BigDecimal number = new BigDecimal(name); - - final double uncertainty = Math.pow(10, -number.scale()); return LinearUnitValue.of(Metric.ONE, - UncertainDouble.of(number.doubleValue(), uncertainty)); + UncertainDouble.fromRoundedString(name)); } catch (final NumberFormatException e) { return LinearUnitValue.getExact(this.getLinearUnit(name), 1); } diff --git a/src/main/java/sevenUnits/utils/UncertainDouble.java b/src/main/java/sevenUnits/utils/UncertainDouble.java index fe41104..ac523b3 100644 --- a/src/main/java/sevenUnits/utils/UncertainDouble.java +++ b/src/main/java/sevenUnits/utils/UncertainDouble.java @@ -45,6 +45,21 @@ public final class UncertainDouble implements Comparable { // optional "± [number]" + "(?:\\s*(?:±|\\+-)\\s*" + NUMBER_REGEX + ")?"); + /** + * Gets an UncertainDouble from a double string. The uncertainty of the + * double will be one of the lowest decimal place of the number. For example, + * "12345.678" will become 12345.678 ± 0.001. + * + * @throws NumberFormatException if the argument is not a number + * + * @since 2022-04-18 + */ + public static final UncertainDouble fromRoundedString(String s) { + final BigDecimal value = new BigDecimal(s); + final double uncertainty = Math.pow(10, -value.scale()); + return UncertainDouble.of(value.doubleValue(), uncertainty); + } + /** * Parses a string in the form of {@link UncertainDouble#toString(boolean)} * and returns the corresponding {@code UncertainDouble} instance. @@ -348,7 +363,7 @@ public final class UncertainDouble implements Comparable { */ @Override public final String toString() { - return this.toString(!this.isExact()); + return this.toString(!this.isExact(), RoundingMode.HALF_EVEN); } /** @@ -379,7 +394,8 @@ public final class UncertainDouble implements Comparable { * * @since 2020-09-07 */ - public final String toString(boolean showUncertainty) { + public final String toString(boolean showUncertainty, + RoundingMode roundingMode) { String valueString, uncertaintyString; // generate the string representation of value and uncertainty @@ -394,9 +410,9 @@ public final class UncertainDouble implements Comparable { final int displayScale = this.getDisplayScale(); final BigDecimal roundedUncertainty = bigUncertainty - .setScale(displayScale, RoundingMode.HALF_EVEN); + .setScale(displayScale, roundingMode); final BigDecimal roundedValue = bigValue.setScale(displayScale, - RoundingMode.HALF_EVEN); + roundingMode); valueString = roundedValue.toString(); uncertaintyString = roundedUncertainty.toString(); diff --git a/src/main/java/sevenUnitsGUI/Presenter.java b/src/main/java/sevenUnitsGUI/Presenter.java index 981af21..85a0ddc 100644 --- a/src/main/java/sevenUnitsGUI/Presenter.java +++ b/src/main/java/sevenUnitsGUI/Presenter.java @@ -242,6 +242,9 @@ public final class Presenter { throw new AssertionError("Loading of metric_exceptions.txt failed.", e); } + + // set default settings temporarily + this.numberDisplayRule = StandardDisplayRules.uncertaintyBased(); } /** @@ -293,9 +296,21 @@ public final class Presenter { // convert and show output if (from.getUnit().canConvertTo(to)) { - final double value = from.asUnitValue().convertTo(to).getValue(); + final UncertainDouble uncertainValue; + + // uncertainty is meaningless for non-linear units, so we will have + // to erase uncertainty information for them + if (to instanceof LinearUnit) { + final var toLinear = (LinearUnit) to; + uncertainValue = from.convertTo(toLinear).getValue(); + } else { + final double value = from.asUnitValue().convertTo(to).getValue(); + uncertainValue = UncertainDouble.of(value, 0); + } + final UnitConversionRecord uc = UnitConversionRecord.valueOf( - fromExpression, toExpression, "", String.valueOf(value)); + fromExpression, toExpression, "", + this.numberDisplayRule.apply(uncertainValue)); xcview.showExpressionConversionOutput(uc); } else { this.view.showErrorMessage("Conversion Error", @@ -324,7 +339,7 @@ public final class Presenter { final Optional fromUnitOptional = ucview.getFromSelection(); final Optional toUnitOptional = ucview.getToSelection(); - final String valueString = ucview.getInputValue(); + final String inputValueString = ucview.getInputValue(); // extract values from optionals final String fromUnitString, toUnitString; @@ -345,7 +360,7 @@ public final class Presenter { // convert strings to data, checking if anything is invalid final Unit fromUnit, toUnit; - final double value; + final UncertainDouble uncertainValue; if (this.database.containsUnitName(fromUnitString)) { fromUnit = this.database.getUnit(fromUnitString); @@ -356,23 +371,42 @@ public final class Presenter { } else throw this.viewError("Nonexistent To unit: %s", toUnitString); try { - value = Double.parseDouble(valueString); + uncertainValue = UncertainDouble + .fromRoundedString(inputValueString); } catch (final NumberFormatException e) { this.view.showErrorMessage("Value Error", - "Invalid value " + valueString); + "Invalid value " + inputValueString); return; } if (!fromUnit.canConvertTo(toUnit)) throw this.viewError("Could not convert between %s and %s", fromUnit, toUnit); - - // convert! - final UnitValue initialValue = UnitValue.of(fromUnit, value); - final UnitValue converted = initialValue.convertTo(toUnit); + + // convert - we will need to erase uncertainty for non-linear units, so + // we need to treat linear and non-linear units differently + final String outputValueString; + if (fromUnit instanceof LinearUnit && toUnit instanceof LinearUnit) { + final LinearUnit fromLinear = (LinearUnit) fromUnit; + final LinearUnit toLinear = (LinearUnit) toUnit; + final LinearUnitValue initialValue = LinearUnitValue.of(fromLinear, + uncertainValue); + final LinearUnitValue converted = initialValue.convertTo(toLinear); + + outputValueString = this.numberDisplayRule + .apply(converted.getValue()); + } else { + final UnitValue initialValue = UnitValue.of(fromUnit, + uncertainValue.value()); + final UnitValue converted = initialValue.convertTo(toUnit); + + outputValueString = this.numberDisplayRule + .apply(UncertainDouble.of(converted.getValue(), 0)); + } ucview.showUnitConversionOutput( - UnitConversionRecord.fromValues(initialValue, converted)); + UnitConversionRecord.valueOf(fromUnitString, toUnitString, + inputValueString, outputValueString)); } else throw new UnsupportedOperationException( "This function can only be called when the view is a UnitConversionView."); diff --git a/src/main/java/sevenUnitsGUI/StandardDisplayRules.java b/src/main/java/sevenUnitsGUI/StandardDisplayRules.java index f6272c8..0c0ba8e 100644 --- a/src/main/java/sevenUnitsGUI/StandardDisplayRules.java +++ b/src/main/java/sevenUnitsGUI/StandardDisplayRules.java @@ -1,5 +1,5 @@ /** - * Copyright (C) 2021 Adrien Hopkins + * Copyright (C) 2022 Adrien Hopkins * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by @@ -16,67 +16,192 @@ */ package sevenUnitsGUI; +import java.math.BigDecimal; +import java.math.MathContext; +import java.math.RoundingMode; import java.util.function.Function; +import java.util.regex.Pattern; import sevenUnits.utils.UncertainDouble; /** - * The default rules for displaying numbers. - * - * Unless otherwise stated, all of this class's functions throw - * {@link NullPointerException} when they receive a null parameter. + * A static utility class that can be used to make display rules for the + * presenter. * - * @since 2021-12-24 + * @since 2022-04-18 */ -final class StandardDisplayRules { +public final class StandardDisplayRules { /** - * Rounds using UncertainDouble's toString method. + * A rule that rounds to a fixed number of decimal places. + * + * @since 2022-04-18 */ - private static final Function SCIENTIFIC_ROUNDING_RULE = new Function<>() { + public static final class FixedDecimals + implements Function { + public static final Pattern TO_STRING_PATTERN = Pattern + .compile("Round to (\\d+) decimal places"); + /** + * The number of places to round to. + */ + private final int decimalPlaces; + + /** + * @param decimalPlaces + * @since 2022-04-18 + */ + private FixedDecimals(int decimalPlaces) { + this.decimalPlaces = decimalPlaces; + } + @Override public String apply(UncertainDouble t) { - return t.toString(false); + final var toRound = new BigDecimal(t.value()); + return toRound.setScale(this.decimalPlaces, RoundingMode.HALF_EVEN) + .toPlainString(); + } + + /** + * @return the number of decimal places this rule rounds to + * @since 2022-04-18 + */ + public int decimalPlaces() { + return this.decimalPlaces; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (!(obj instanceof FixedDecimals)) + return false; + final FixedDecimals other = (FixedDecimals) obj; + if (this.decimalPlaces != other.decimalPlaces) + return false; + return true; + } + + @Override + public int hashCode() { + return 31 + this.decimalPlaces; } @Override public String toString() { - return "Scientific Rounding"; + return "Round to " + this.decimalPlaces + " decimal places"; } - }; + } /** - * Gets a display rule that rounds numbers to a fixed number of decimal - * places. + * A rule that rounds to a fixed number of significant digits. * - * @param decimalPlaces number of decimal places - * @return display rule - * @since 2022-04-16 + * @since 2022-04-18 */ - public static final Function getFixedPlacesRule( - int decimalPlaces) { - throw new UnsupportedOperationException("Not implemented yet"); + public static final class FixedPrecision + implements Function { + public static final Pattern TO_STRING_PATTERN = Pattern + .compile("Round to (\\d+) significant figures"); + + /** + * The number of significant figures to round to. + */ + private final MathContext mathContext; + + /** + * @param significantFigures + * @since 2022-04-18 + */ + private FixedPrecision(int significantFigures) { + this.mathContext = new MathContext(significantFigures, + RoundingMode.HALF_EVEN); + } + + @Override + public String apply(UncertainDouble t) { + final var toRound = new BigDecimal(t.value()); + return toRound.round(this.mathContext).toString(); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (!(obj instanceof FixedPrecision)) + return false; + final FixedPrecision other = (FixedPrecision) obj; + if (this.mathContext == null) { + if (other.mathContext != null) + return false; + } else if (!this.mathContext.equals(other.mathContext)) + return false; + return true; + } + + @Override + public int hashCode() { + return 127 + + (this.mathContext == null ? 0 : this.mathContext.hashCode()); + } + + /** + * @return the number of significant figures this rule rounds to + * @since 2022-04-18 + */ + public int significantFigures() { + return this.mathContext.getPrecision(); + } + + @Override + public String toString() { + return "Round to " + this.mathContext.getPrecision() + + " significant figures"; + } } /** - * Gets a display rule that rounds numbers to a fixed number of significant - * figures. + * A rounding rule that rounds based on UncertainDouble's toString method. + * This means the output will have around as many significant figures as the + * input. * - * @param significantFigures number of significant figures - * @return display rule - * @since 2022-04-16 + * @since 2022-04-18 + */ + public static final class UncertaintyBased + implements Function { + private UncertaintyBased() {} + + @Override + public String apply(UncertainDouble t) { + return t.toString(false, RoundingMode.HALF_EVEN); + } + + @Override + public String toString() { + return "Uncertainty-Based Rounding"; + } + } + + /** + * For now, I want this to be a singleton. I might want to add a parameter + * later, so I won't make it an enum. + */ + private static final UncertaintyBased UNCERTAINTY_BASED_ROUNDING_RULE = new UncertaintyBased(); + + /** + * @param decimalPlaces decimal places to round to + * @return a rounding rule that rounds to fixed number of decimal places + * @since 2022-04-18 */ - public static final Function getFixedPrecisionRule( - int significantFigures) { - throw new UnsupportedOperationException("Not implemented yet"); + public static final FixedDecimals fixedDecimals(int decimalPlaces) { + return new FixedDecimals(decimalPlaces); } /** - * @return a rule that rounds using UncertainDouble's own toString(false) - * function. - * @since 2021-12-24 + * @param significantFigures significant figures to round to + * @return a rounding rule that rounds to a fixed number of significant + * figures + * @since 2022-04-18 */ - public static final Function getScientificRule() { - return SCIENTIFIC_ROUNDING_RULE; + public static final FixedPrecision fixedPrecision(int significantFigures) { + return new FixedPrecision(significantFigures); } /** @@ -90,11 +215,32 @@ final class StandardDisplayRules { */ public static final Function getStandardRule( String ruleToString) { - throw new UnsupportedOperationException("Not implemented yet"); + if (UNCERTAINTY_BASED_ROUNDING_RULE.toString().equals(ruleToString)) + return UNCERTAINTY_BASED_ROUNDING_RULE; + + // test if it is a fixed-places rule + final var placesMatch = FixedDecimals.TO_STRING_PATTERN + .matcher(ruleToString); + if (placesMatch.matches()) + return new FixedDecimals(Integer.valueOf(placesMatch.group(1))); + + // test if it is a fixed-sig-fig rule + final var sigFigMatch = FixedPrecision.TO_STRING_PATTERN + .matcher(ruleToString); + if (sigFigMatch.matches()) + return new FixedPrecision(Integer.valueOf(sigFigMatch.group(1))); + + throw new IllegalArgumentException( + "Provided string does not match any given rules."); } - private StandardDisplayRules() { - throw new AssertionError( - "This is a static utility class, you may not get instances of it."); + /** + * @return an UncertainDouble-based rounding rule + * @since 2022-04-18 + */ + public static final UncertaintyBased uncertaintyBased() { + return UNCERTAINTY_BASED_ROUNDING_RULE; } + + private StandardDisplayRules() {} } diff --git a/src/main/java/sevenUnitsGUI/TabbedView.java b/src/main/java/sevenUnitsGUI/TabbedView.java index d0eb32f..3a951ef 100644 --- a/src/main/java/sevenUnitsGUI/TabbedView.java +++ b/src/main/java/sevenUnitsGUI/TabbedView.java @@ -20,16 +20,18 @@ import java.awt.BorderLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; +import java.awt.event.ItemEvent; import java.awt.event.KeyEvent; -import java.text.DecimalFormat; -import java.text.NumberFormat; import java.util.AbstractSet; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.NoSuchElementException; +import java.util.Objects; import java.util.Optional; +import java.util.OptionalInt; import java.util.Set; +import java.util.function.Function; import javax.swing.BorderFactory; import javax.swing.BoxLayout; @@ -37,7 +39,6 @@ import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; -import javax.swing.JFormattedTextField; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; @@ -58,6 +59,7 @@ import javax.swing.border.TitledBorder; import sevenUnits.ProgramInfo; import sevenUnits.unit.UnitType; import sevenUnits.utils.NameSymbol; +import sevenUnits.utils.UncertainDouble; /** * A View that separates its functions into multiple tabs @@ -111,7 +113,99 @@ final class TabbedView implements ExpressionConversionView, UnitConversionView { } - private static final NumberFormat NUMBER_FORMATTER = new DecimalFormat(); + /** + * The standard types of rounding, corresponding to the options on the + * TabbedView's settings panel. + * + * @since 2022-04-18 + */ + private static enum StandardRoundingType { + /** + * Rounds to a fixed number of significant digits. Precision is used, + * representing the number of significant digits to round to. + */ + SIGNIFICANT_DIGITS(true) { + @Override + public Function getRuleFromPrecision( + int precision) { + return StandardDisplayRules.fixedPrecision(precision); + } + }, + /** + * Rounds to a fixed number of decimal places. Precision is used, + * representing the number of decimal places to round to. + */ + DECIMAL_PLACES(true) { + @Override + public Function getRuleFromPrecision( + int precision) { + return StandardDisplayRules.fixedDecimals(precision); + } + }, + /** + * Rounds according to UncertainDouble's toString method. The specified + * precision is ignored. + */ + UNCERTAINTY(false) { + @Override + public Function getRuleFromPrecision( + int precision) { + return StandardDisplayRules.uncertaintyBased(); + } + }; + + /** + * If true, this type of rounding rule requires you to specify a + * precision. + */ + private final boolean requiresPrecision; + + /** + * @param canCustomizePrecision + * @since 2022-04-18 + */ + private StandardRoundingType(boolean requiresPrecision) { + this.requiresPrecision = requiresPrecision; + } + + /** + * Gets a rounding rule of this type. + * + * @param precision the rounding type's precision. If + * {@link #requiresPrecision} is false, this field will + * be ignored. + * @return rounding rule + * @since 2022-04-18 + */ + public abstract Function getRuleFromPrecision( + int precision); + + /** + * Tries to get this rule without specifying precision. + * + * @throws UnsupportedOperationException if this rule requires specifying + * precision + * @since 2022-04-18 + */ + public final Function getRuleWithoutPrecision() { + if (this.requiresPrecision()) + throw new UnsupportedOperationException("Rounding type " + this + + " requires you to specify precision."); + else + // random number to mess with anyone who lies about whether or not + // precision is required + return this.getRuleFromPrecision(-623546735); + } + + /** + * @return whether or not this rounding type requires you to specify an + * integer precision + * @since 2022-04-18 + */ + public boolean requiresPrecision() { + return this.requiresPrecision; + } + } /** * Creates a TabbedView. @@ -137,7 +231,7 @@ final class TabbedView implements ExpressionConversionView, UnitConversionView { /** The combo box that selects dimensions */ private final JComboBox dimensionSelector; /** The panel for inputting values in the dimension-based converter */ - private final JFormattedTextField valueInput; + private final JTextField valueInput; /** The panel for "From" in the dimension-based converter */ private final SearchBoxList fromSearch; /** The panel for "To" in the dimension-based converter */ @@ -163,6 +257,10 @@ final class TabbedView implements ExpressionConversionView, UnitConversionView { /** The text box for prefix data in the prefix viewer */ private final JTextArea prefixTextBox; + // SETTINGS STUFF + private StandardRoundingType roundingType; + private int precision; + /** * Creates the view and makes it visible to the user * @@ -229,7 +327,7 @@ final class TabbedView implements ExpressionConversionView, UnitConversionView { final JLabel valuePrompt = new JLabel("Value to convert: "); outputPanel.add(valuePrompt, BorderLayout.LINE_START); - this.valueInput = new JFormattedTextField(NUMBER_FORMATTER); + this.valueInput = new JTextField(); outputPanel.add(this.valueInput, BorderLayout.CENTER); // conversion button @@ -352,61 +450,89 @@ final class TabbedView implements ExpressionConversionView, UnitConversionView { // rounding rule selection final ButtonGroup roundingRuleButtons = new ButtonGroup(); + this.roundingType = this.getPresenterRoundingType() + .orElseThrow(() -> new AssertionError( + "Presenter loaded non-standard rounding rule")); + this.precision = this.getPresenterPrecision().orElse(6); final JLabel roundingRuleLabel = new JLabel("Rounding Rule:"); roundingPanel.add(roundingRuleLabel, new GridBagBuilder(0, 0) .setAnchor(GridBagConstraints.LINE_START).build()); + // sigDigSlider needs to be first so that the rounding-type buttons can + // show and hide it + final JLabel sliderLabel = new JLabel("Precision:"); + sliderLabel.setVisible( + this.roundingType != StandardRoundingType.UNCERTAINTY); + roundingPanel.add(sliderLabel, new GridBagBuilder(0, 4) + .setAnchor(GridBagConstraints.LINE_START).build()); + + final JSlider sigDigSlider = new JSlider(0, 12); + roundingPanel.add(sigDigSlider, new GridBagBuilder(0, 5) + .setAnchor(GridBagConstraints.LINE_START).build()); + + sigDigSlider.setMajorTickSpacing(4); + sigDigSlider.setMinorTickSpacing(1); + sigDigSlider.setSnapToTicks(true); + sigDigSlider.setPaintTicks(true); + sigDigSlider.setPaintLabels(true); + + sigDigSlider.setVisible( + this.roundingType != StandardRoundingType.UNCERTAINTY); + sigDigSlider.setValue(this.precision); + + sigDigSlider.addChangeListener(e -> { + this.precision = sigDigSlider.getValue(); + this.updatePresenterRoundingRule(); + }); + + // significant digit rounding final JRadioButton fixedPrecision = new JRadioButton( "Fixed Precision"); -// if (this.presenter.roundingType == RoundingType.SIGNIFICANT_DIGITS) { -// fixedPrecision.setSelected(true); -// } -// fixedPrecision.addActionListener(e -> this.presenter -// .setRoundingType(RoundingType.SIGNIFICANT_DIGITS)); + if (this.roundingType == StandardRoundingType.SIGNIFICANT_DIGITS) { + fixedPrecision.setSelected(true); + } + fixedPrecision.addActionListener(e -> { + this.roundingType = StandardRoundingType.SIGNIFICANT_DIGITS; + sliderLabel.setVisible(true); + sigDigSlider.setVisible(true); + this.updatePresenterRoundingRule(); + }); roundingRuleButtons.add(fixedPrecision); roundingPanel.add(fixedPrecision, new GridBagBuilder(0, 1) .setAnchor(GridBagConstraints.LINE_START).build()); + // decimal place rounding final JRadioButton fixedDecimals = new JRadioButton( "Fixed Decimal Places"); -// if (this.presenter.roundingType == RoundingType.DECIMAL_PLACES) { -// fixedDecimals.setSelected(true); -// } -// fixedDecimals.addActionListener(e -> this.presenter -// .setRoundingType(RoundingType.DECIMAL_PLACES)); + if (this.roundingType == StandardRoundingType.DECIMAL_PLACES) { + fixedDecimals.setSelected(true); + } + fixedDecimals.addActionListener(e -> { + this.roundingType = StandardRoundingType.DECIMAL_PLACES; + sliderLabel.setVisible(true); + sigDigSlider.setVisible(true); + this.updatePresenterRoundingRule(); + }); roundingRuleButtons.add(fixedDecimals); roundingPanel.add(fixedDecimals, new GridBagBuilder(0, 2) .setAnchor(GridBagConstraints.LINE_START).build()); + // scientific rounding final JRadioButton relativePrecision = new JRadioButton( - "Scientific Precision"); -// if (this.presenter.roundingType == RoundingType.SCIENTIFIC) { -// relativePrecision.setSelected(true); -// } -// relativePrecision.addActionListener( -// e -> this.presenter.setRoundingType(RoundingType.SCIENTIFIC)); + "Uncertainty-Based Rounding"); + if (this.roundingType == StandardRoundingType.UNCERTAINTY) { + relativePrecision.setSelected(true); + } + relativePrecision.addActionListener(e -> { + this.roundingType = StandardRoundingType.UNCERTAINTY; + sliderLabel.setVisible(false); + sigDigSlider.setVisible(false); + this.updatePresenterRoundingRule(); + }); roundingRuleButtons.add(relativePrecision); roundingPanel.add(relativePrecision, new GridBagBuilder(0, 3) .setAnchor(GridBagConstraints.LINE_START).build()); - - final JLabel sliderLabel = new JLabel("Precision:"); - roundingPanel.add(sliderLabel, new GridBagBuilder(0, 4) - .setAnchor(GridBagConstraints.LINE_START).build()); - - final JSlider sigDigSlider = new JSlider(0, 12); - roundingPanel.add(sigDigSlider, new GridBagBuilder(0, 5) - .setAnchor(GridBagConstraints.LINE_START).build()); - - sigDigSlider.setMajorTickSpacing(4); - sigDigSlider.setMinorTickSpacing(1); - sigDigSlider.setSnapToTicks(true); - sigDigSlider.setPaintTicks(true); - sigDigSlider.setPaintLabels(true); -// sigDigSlider.setValue(this.presenter.precision); - -// sigDigSlider.addChangeListener( -// e -> this.presenter.setPrecision(sigDigSlider.getValue())); } // ============ PREFIX REPETITION SETTINGS ============ @@ -501,17 +627,18 @@ final class TabbedView implements ExpressionConversionView, UnitConversionView { miscPanel.setLayout(new GridBagLayout()); final JCheckBox oneWay = new JCheckBox("Convert One Way Only"); -// oneWay.setSelected(this.presenter.oneWay); -// oneWay.addItemListener( -// e -> this.presenter.setOneWay(e.getStateChange() == 1)); + oneWay.setSelected(this.presenter.oneWayConversionEnabled()); + oneWay.addItemListener(e -> this.presenter.setOneWayConversionEnabled( + e.getStateChange() == ItemEvent.SELECTED)); miscPanel.add(oneWay, new GridBagBuilder(0, 0) .setAnchor(GridBagConstraints.LINE_START).build()); final JCheckBox showAllVariations = new JCheckBox( "Show Duplicates in \"Convert Units\""); -// showAllVariations.setSelected(this.presenter.includeDuplicateUnits); -// showAllVariations.addItemListener(e -> this.presenter -// .setIncludeDuplicateUnits(e.getStateChange() == 1)); + showAllVariations.setSelected(this.presenter.duplicateUnitsShown()); + showAllVariations + .addItemListener(e -> this.presenter.setShowDuplicateUnits( + e.getStateChange() == ItemEvent.SELECTED)); miscPanel.add(showAllVariations, new GridBagBuilder(0, 1) .setAnchor(GridBagConstraints.LINE_START).build()); @@ -552,6 +679,43 @@ final class TabbedView implements ExpressionConversionView, UnitConversionView { return this.valueInput.getText(); } + /** + * @return the precision of the presenter's rounding rule, if that is + * meaningful + * @since 2022-04-18 + */ + private OptionalInt getPresenterPrecision() { + final var presenterRule = this.presenter.getNumberDisplayRule(); + if (presenterRule instanceof StandardDisplayRules.FixedDecimals) + return OptionalInt + .of(((StandardDisplayRules.FixedDecimals) presenterRule) + .decimalPlaces()); + else if (presenterRule instanceof StandardDisplayRules.FixedPrecision) + return OptionalInt + .of(((StandardDisplayRules.FixedPrecision) presenterRule) + .significantFigures()); + else + return OptionalInt.empty(); + } + + /** + * Determines which rounding type the presenter is currently using, if any. + * + * @since 2022-04-18 + */ + private Optional getPresenterRoundingType() { + final var presenterRule = this.presenter.getNumberDisplayRule(); + if (Objects.equals(presenterRule, + StandardDisplayRules.uncertaintyBased())) + return Optional.of(StandardRoundingType.UNCERTAINTY); + else if (presenterRule instanceof StandardDisplayRules.FixedDecimals) + return Optional.of(StandardRoundingType.DECIMAL_PLACES); + else if (presenterRule instanceof StandardDisplayRules.FixedPrecision) + return Optional.of(StandardRoundingType.SIGNIFICANT_DIGITS); + else + return Optional.empty(); + } + @Override public Optional getSelectedDimensionName() { final String selectedItem = (String) this.dimensionSelector @@ -644,4 +808,28 @@ final class TabbedView implements ExpressionConversionView, UnitConversionView { public void showUnitConversionOutput(UnitConversionRecord uc) { this.unitOutput.setText(uc.toString()); } + + /** + * Sets the presenter's rounding rule to the one specified by the current + * settings + * + * @since 2022-04-18 + */ + private void updatePresenterRoundingRule() { + final Function roundingRule; + switch (this.roundingType) { + case DECIMAL_PLACES: + roundingRule = StandardDisplayRules.fixedDecimals(this.precision); + break; + case SIGNIFICANT_DIGITS: + roundingRule = StandardDisplayRules.fixedPrecision(this.precision); + break; + case UNCERTAINTY: + roundingRule = StandardDisplayRules.uncertaintyBased(); + break; + default: + throw new AssertionError(); + } + this.presenter.setNumberDisplayRule(roundingRule); + } } diff --git a/src/test/java/sevenUnits/unit/UnitTest.java b/src/test/java/sevenUnits/unit/UnitTest.java index f174e7c..d3699ca 100644 --- a/src/test/java/sevenUnits/unit/UnitTest.java +++ b/src/test/java/sevenUnits/unit/UnitTest.java @@ -21,6 +21,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.math.RoundingMode; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; @@ -164,8 +165,9 @@ class UnitTest { UncertainDouble.of(10, 0.24)); assertEquals("(10.0 ± 0.2) m", value.toString()); - assertEquals("(10.0 ± 0.2) m", value.toString(true)); - assertEquals("10.0 m", value.toString(false)); + assertEquals("(10.0 ± 0.2) m", + value.toString(true, RoundingMode.HALF_EVEN)); + assertEquals("10.0 m", value.toString(false, RoundingMode.HALF_EVEN)); } /** @@ -179,8 +181,9 @@ class UnitTest { UncertainDouble.of(10, 0)); assertEquals("10.0 m", value.toString()); - assertEquals("(10.0 ± 0.0) m", value.toString(true)); - assertEquals("10.0 m", value.toString(false)); + assertEquals("(10.0 ± 0.0) m", + value.toString(true, RoundingMode.HALF_EVEN)); + assertEquals("10.0 m", value.toString(false, RoundingMode.HALF_EVEN)); } /** @@ -194,7 +197,8 @@ class UnitTest { Metric.METRE.withName(NameSymbol.EMPTY), UncertainDouble.of(10, 0.24)); - assertEquals("10.0 unnamed unit (= 10.0 m)", value.toString(false)); + assertEquals("10.0 unnamed unit (= 10.0 m)", + value.toString(false, RoundingMode.HALF_EVEN)); } /** diff --git a/src/test/java/sevenUnits/utils/UncertainDoubleTest.java b/src/test/java/sevenUnits/utils/UncertainDoubleTest.java index c891f20..0e18461 100644 --- a/src/test/java/sevenUnits/utils/UncertainDoubleTest.java +++ b/src/test/java/sevenUnits/utils/UncertainDoubleTest.java @@ -19,6 +19,7 @@ package sevenUnits.utils; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static sevenUnits.utils.UncertainDouble.fromRoundedString; import static sevenUnits.utils.UncertainDouble.fromString; import static sevenUnits.utils.UncertainDouble.of; @@ -66,6 +67,16 @@ class UncertainDoubleTest { x.toExponentExact(Math.E).value()); } + /** + * Test for {@link UncertainDouble#fromRoundedString} + * + * @since 2022-04-18 + */ + @Test + final void testFromRoundedString() { + assertEquals(of(12345.678, 0.001), fromRoundedString("12345.678")); + } + @Test final void testFromString() { // valid strings diff --git a/src/test/java/sevenUnitsGUI/PresenterTest.java b/src/test/java/sevenUnitsGUI/PresenterTest.java index 8446a90..f52d846 100644 --- a/src/test/java/sevenUnitsGUI/PresenterTest.java +++ b/src/test/java/sevenUnitsGUI/PresenterTest.java @@ -60,10 +60,9 @@ public final class PresenterTest { * @since 2022-04-16 */ private static final Stream> getRoundingRules() { - final var SCIENTIFIC_ROUNDING = StandardDisplayRules.getScientificRule(); - final var INTEGER_ROUNDING = StandardDisplayRules.getFixedPlacesRule(0); - final var SIG_FIG_ROUNDING = StandardDisplayRules - .getFixedPrecisionRule(4); + final var SCIENTIFIC_ROUNDING = StandardDisplayRules.uncertaintyBased(); + final var INTEGER_ROUNDING = StandardDisplayRules.fixedDecimals(0); + final var SIG_FIG_ROUNDING = StandardDisplayRules.fixedPrecision(4); return Stream.of(SCIENTIFIC_ROUNDING, INTEGER_ROUNDING, SIG_FIG_ROUNDING); } @@ -264,20 +263,19 @@ public final class PresenterTest { // set and save custom settings presenter.setOneWayConversionEnabled(true); presenter.setShowDuplicateUnits(true); - presenter.setNumberDisplayRule( - StandardDisplayRules.getFixedPrecisionRule(11)); + presenter.setNumberDisplayRule(StandardDisplayRules.fixedPrecision(11)); presenter.saveSettings(TEST_SETTINGS); // overwrite custom settings presenter.setOneWayConversionEnabled(false); presenter.setShowDuplicateUnits(false); - presenter.setNumberDisplayRule(StandardDisplayRules.getScientificRule()); + presenter.setNumberDisplayRule(StandardDisplayRules.uncertaintyBased()); // load settings & test that they're the same presenter.loadSettings(TEST_SETTINGS); assertTrue(presenter.oneWayConversionEnabled()); assertTrue(presenter.duplicateUnitsShown()); - assertEquals(StandardDisplayRules.getFixedPlacesRule(11), + assertEquals(StandardDisplayRules.fixedPrecision(11), presenter.getNumberDisplayRule()); } -- cgit v1.2.3 From 39668f4b274f0e7996f65b4f432a48ae0d88daca Mon Sep 17 00:00:00 2001 From: Adrien Hopkins Date: Fri, 8 Jul 2022 12:46:45 -0500 Subject: Bumped version number to 0.4.0b1 & added @since --- CHANGELOG.org | 2 +- README.org | 2 +- docs/design.org | 2 +- docs/design.pdf | Bin 348080 -> 348051 bytes docs/design.tex | 68 ++++++++++----------- docs/manual.org | 6 +- docs/manual.pdf | Bin 173138 -> 173293 bytes docs/manual.tex | 36 +++++------ screenshots/main-interface-settings.png | Bin 25953 -> 25953 bytes src/main/java/sevenUnits/ProgramInfo.java | 4 +- src/main/java/sevenUnits/unit/BaseDimension.java | 5 +- src/main/java/sevenUnits/utils/NameSymbol.java | 1 + .../sevenUnits/utils/SemanticVersionNumber.java | 25 ++++++++ .../sevenUnitsGUI/ExpressionConversionView.java | 4 ++ src/main/java/sevenUnitsGUI/Main.java | 6 +- src/main/java/sevenUnitsGUI/PrefixSearchRule.java | 12 ++++ .../java/sevenUnitsGUI/StandardDisplayRules.java | 8 +++ .../java/sevenUnitsGUI/UnitConversionRecord.java | 8 +++ .../java/sevenUnitsGUI/UnitConversionView.java | 12 ++++ src/main/java/sevenUnitsGUI/View.java | 10 +++ src/main/java/sevenUnitsGUI/ViewBot.java | 1 + 21 files changed, 150 insertions(+), 62 deletions(-) (limited to 'src/main/java/sevenUnitsGUI/StandardDisplayRules.java') diff --git a/CHANGELOG.org b/CHANGELOG.org index 7000828..de873b3 100644 --- a/CHANGELOG.org +++ b/CHANGELOG.org @@ -1,6 +1,6 @@ * Changelog All notable changes in this project will be shown in this file. -** Unreleased +** v0.4.0 (Unreleased) *** Added - Added tests for the GUI - Added an object for the version numbers (SemanticVersionNumber) diff --git a/README.org b/README.org index f891bdc..171b4d9 100644 --- a/README.org +++ b/README.org @@ -1,4 +1,4 @@ -* 7Units v0.4.0a1 +* 7Units v0.4.0b1 (this project uses Semantic Versioning) ** What is it? This is a unit converter, which allows you to convert between different units, and includes a GUI which can read unit data from a file (using some unit math) and convert between units that you type in, and has a unit and prefix viewer to check the units that have been loaded in. diff --git a/docs/design.org b/docs/design.org index 467c018..0e4ca92 100644 --- a/docs/design.org +++ b/docs/design.org @@ -1,5 +1,5 @@ #+TITLE: 7Units Design Document -#+SUBTITLE: For version 0.4.0-alpha.1 +#+SUBTITLE: For version 0.4.0-beta.1 #+DATE: 2022 July 8 #+LaTeX_HEADER: \usepackage[a4paper, lmargin=25mm, rmargin=25mm, tmargin=25mm, bmargin=25mm]{geometry} #+LaTeX_HEADER: \usepackage{xurl} diff --git a/docs/design.pdf b/docs/design.pdf index 56d73a6..99fbb3b 100644 Binary files a/docs/design.pdf and b/docs/design.pdf differ diff --git a/docs/design.tex b/docs/design.tex index 5023fb3..9434cc1 100644 --- a/docs/design.tex +++ b/docs/design.tex @@ -1,4 +1,4 @@ -% Created 2022-07-08 Fri 10:05 +% Created 2022-07-08 Fri 12:43 % Intended LaTeX compiler: pdflatex \documentclass[11pt]{article} \usepackage[utf8]{inputenc} @@ -18,7 +18,7 @@ \usepackage{xurl} \date{2022 July 8} \title{7Units Design Document\\\medskip -\large For version 0.4.0-alpha.1} +\large For version 0.4.0-beta.1} \hypersetup{ pdfauthor={}, pdftitle={7Units Design Document}, @@ -34,35 +34,35 @@ \newpage \section{Introduction} -\label{sec:orgd3381a6} +\label{sec:orga266915} 7Units is a program that can convert between units. This document details the internal design of 7Units, intended to be used by current and future developers. \section{System Overview} -\label{sec:org9bd9474} +\label{sec:org6d969dd} \begin{figure}[htbp] \centering \includegraphics[height=144px]{./diagrams/overview-diagram.plantuml.png} \caption{A big-picture diagram of 7Units, containing all of the major classes.} \end{figure} \subsection{Packages of 7Units} -\label{sec:org5c8f3ee} +\label{sec:orged5584a} 7Units splits its code into three main packages: \begin{description} -\item[{\texttt{sevenUnits.unit}}] The \hyperref[sec:org1171d15]{unit system} +\item[{\texttt{sevenUnits.unit}}] The \hyperref[sec:orgf969629]{unit system} \item[{\texttt{sevenUnits.utils}}] Extra classes that aid the unit system. -\item[{\texttt{sevenUnitsGUI}}] The \hyperref[sec:orgb716c37]{front end} code +\item[{\texttt{sevenUnitsGUI}}] The \hyperref[sec:org431a987]{front end} code \end{description} \texttt{sevenUnits.unit} depends on \texttt{sevenUnits.utils}, while \texttt{sevenUnitsGUI} depends on both \texttt{sevenUnits} packages. There is only one class that isn't in any of these packages, \texttt{sevenUnits.VersionInfo}. \subsection{Major Classes of 7Units} -\label{sec:org22c5367} +\label{sec:org147769f} \begin{description} -\item[{\hyperref[sec:orge128590]{sevenUnits.unit.Unit}}] The class representing a unit -\item[{\hyperref[sec:orgc8dc0e4]{sevenUnits.unit.UnitDatabase}}] A class that stores collections of units, prefixes and dimensions. -\item[{\hyperref[sec:orgf3ee40e]{sevenUnitsGUI.View}}] The class that handles interaction between the user and the program. -\item[{\hyperref[sec:orgcf5cc70]{sevenUnitsGUI.Presenter}}] The class that handles communication between the \texttt{View} and the unit system. +\item[{\hyperref[sec:org93aab3e]{sevenUnits.unit.Unit}}] The class representing a unit +\item[{\hyperref[sec:org0a33326]{sevenUnits.unit.UnitDatabase}}] A class that stores collections of units, prefixes and dimensions. +\item[{\hyperref[sec:org5460ab6]{sevenUnitsGUI.View}}] The class that handles interaction between the user and the program. +\item[{\hyperref[sec:org4f735c1]{sevenUnitsGUI.Presenter}}] The class that handles communication between the \texttt{View} and the unit system. \end{description} \newpage \subsection{Process of Unit Conversion} -\label{sec:org73700d8} +\label{sec:org65b1400} \begin{figure}[htbp] \centering \includegraphics[width=.9\linewidth]{./diagrams/convert-units.plantuml.png} @@ -77,7 +77,7 @@ \end{enumerate} \newpage \subsection{Process of Expression Conversion} -\label{sec:org3e8ae17} +\label{sec:orgc9346ba} The process of expression conversion is similar to that of unit conversion. \begin{figure}[htbp] \centering @@ -93,7 +93,7 @@ The process of expression conversion is similar to that of unit conversion. \end{enumerate} \newpage \section{Unit System Design} -\label{sec:org1171d15} +\label{sec:orgf969629} Any code related to the backend unit system is stored in the \texttt{sevenUnits.unit} package. Here is a class diagram of the system. Unimportant methods, methods inherited from Object, getters and setters have been omitted. @@ -104,11 +104,11 @@ Here is a class diagram of the system. Unimportant methods, methods inherited f \end{figure} \newpage \subsection{Dimensions} -\label{sec:org14cd421} -Dimensions represent what a unit is measuring, such as length, time, or energy. Dimensions are represented as an \hyperref[sec:orgc3e831c]{ObjectProduct}, where \texttt{BaseDimension} is a very simple class (its only properties are a name and a symbol) which represents the dimension of a base unit; these base dimensions can be multiplied to create all other Dimensions. +\label{sec:orgda7eb73} +Dimensions represent what a unit is measuring, such as length, time, or energy. Dimensions are represented as an \hyperref[sec:org9c5f1fc]{ObjectProduct}, where \texttt{BaseDimension} is a very simple class (its only properties are a name and a symbol) which represents the dimension of a base unit; these base dimensions can be multiplied to create all other Dimensions. \subsection{Unit Classes} -\label{sec:orge128590} -Units are internally represented by the abstract class \texttt{Unit}. All units have an \hyperref[sec:orgc3e831c]{ObjectProduct} (referred to as the base) that they are based on, a dimension (ObjectProduct), one or more names and a symbol (these last two bits of data are contained in the \texttt{NameSymbol} class). The dimension is calculated from the base unit when needed; the variable is just a cache. It has two constructors: a package-private one used to make \texttt{BaseUnit} instances, and a protected one used to make general units (for other subclasses of \texttt{Unit}). All unit classes are immutable. +\label{sec:org93aab3e} +Units are internally represented by the abstract class \texttt{Unit}. All units have an \hyperref[sec:org9c5f1fc]{ObjectProduct} (referred to as the base) that they are based on, a dimension (ObjectProduct), one or more names and a symbol (these last two bits of data are contained in the \texttt{NameSymbol} class). The dimension is calculated from the base unit when needed; the variable is just a cache. It has two constructors: a package-private one used to make \texttt{BaseUnit} instances, and a protected one used to make general units (for other subclasses of \texttt{Unit}). All unit classes are immutable. Units also have two conversion functions - one which converts from a value expressed in this unit to its base unit, and another which converts from a value expressed in the base unit to this unit. In \texttt{Unit}, they are defined as two abstract methods. This allows you to convert from any unit to any other (as long as they have the same base, i.e. you aren't converting metres to pounds). To convert from A to B, first convert from A to its base, then convert from the base to B. @@ -133,20 +133,20 @@ There are a few more classes which play small roles in the unit system: \item[{USCustomary}] A static utility class with instances of common units in the US Customary system (not to be confused with the British Imperial system; it has the same unit names but the values of a few units are different). \end{description} \subsection{Prefixes} -\label{sec:org1bd7050} +\label{sec:org40fa3a0} A \texttt{UnitPrefix} is a simple object that can multiply a \texttt{LinearUnit} by a value. It can calculate a new name for the unit by combining its name and the unit's name (symbols are done similarly). It can do multiplication, division and exponentation with a number, as well as multiplication and division with another prefix; all of these work by changing the prefix's multiplier. \subsection{The Unit Database} -\label{sec:orgc8dc0e4} +\label{sec:org0a33326} The \texttt{UnitDatabase} class stores all of the unit, prefix and dimension data used by this program. It is not a representation of an actual database, just a class that stores lots of data. Units are stored using a custom \texttt{Map} implementation (\texttt{PrefixedUnitMap}) which maps unit names to units. It is backed by two maps: one for units (without prefixes) and one for prefixes. It is programmed to include prefixes (so if units includes "metre" and prefixes includes "kilo", this map will include "kilometre", mapping it to a unit representing a kilometre). It is immutable, but you can modify the underlying maps, which is reflected in the \texttt{PrefixedUnitMap}. Other than that, it is a normal map implementation. Prefixes and dimensions are stored in normal maps. \subsubsection{Parsing Expressions} -\label{sec:orgb7ee1da} -Each \texttt{UnitDatabase} instance has four \hyperref[sec:orgd351c2f]{ExpressionParser} instances associated with it, for four types of expressions: unit, unit value, prefix and dimension. They are mostly similar, with operators corresponding to each operation of the corresponding class (\texttt{LinearUnit}, \texttt{LinearUnitValue}, \texttt{UnitPrefix}, \texttt{ObjectProduct}). Unit and unit value expressions use linear units; nonlinear units can be used with a special syntax (like "degC(20)") and are immediately converted to a linear unit representing their base (Kelvin in this case) before operating. +\label{sec:orgb3362c7} +Each \texttt{UnitDatabase} instance has four \hyperref[sec:org7f49fac]{ExpressionParser} instances associated with it, for four types of expressions: unit, unit value, prefix and dimension. They are mostly similar, with operators corresponding to each operation of the corresponding class (\texttt{LinearUnit}, \texttt{LinearUnitValue}, \texttt{UnitPrefix}, \texttt{ObjectProduct}). Unit and unit value expressions use linear units; nonlinear units can be used with a special syntax (like "degC(20)") and are immediately converted to a linear unit representing their base (Kelvin in this case) before operating. \subsubsection{Parsing Files} -\label{sec:org072dc65} +\label{sec:org5f50970} There are two types of data files: unit and dimension. Unit files contain data about units and prefixes. Each line contains the name of a unit or prefix (prefixes end in a dash, units don't) followed by an expression which defines it, separated by one or more space characters (this behaviour is defined by the static regular expression \texttt{NAME\_EXPRESSION}). Unit files are parsed line by line, each line being run through the \texttt{addUnitOrPrefixFromLine} method, which splits a line into name and expression, determines whether it's a unit or a prefix, and parses the expression. Because all units are defined by others, base units need to be defined with a special expression "!"; \textbf{these units should be added to the database before parsing the file}. @@ -154,10 +154,10 @@ Unit files contain data about units and prefixes. Each line contains the name o Dimension files are similar, only for dimensions instead of units and prefixes. \newpage \section{Front-End Design} -\label{sec:orgb716c37} +\label{sec:org431a987} The front-end of 7Units is based on an MVP model. There are two major frontend classes, the \textbf{View} and the \textbf{Presenter}. \subsection{The View} -\label{sec:orgf3ee40e} +\label{sec:org5460ab6} The \texttt{View} is the part of the frontend code that directly interacts with the user. It handles input and output, but does not do any processing. Processing is handled by the presenter and the backend code. The \texttt{View} is an interface, not a single class, so that I can easily create multiple views without having to rewrite any processing code. This allows me to easily prototype changes to the GUI without messing with existing code. @@ -171,10 +171,10 @@ There are currently two implementations of the \texttt{View}: \end{description} Both of these \texttt{View} implementations implement \texttt{UnitConversionView} and \texttt{ExpressionConversionView}. \subsection{The Presenter} -\label{sec:orgcf5cc70} +\label{sec:org4f735c1} The \texttt{Presenter} is an intermediary between the \texttt{View} and the backend code. It accepts the user's input and passes it to the backend, then accepts the backend's output and passes it to the frontend for user viewing. Its main functions do not have arguments or return values; instead it takes input from and provides output to the \texttt{View} via its public methods. \subsubsection{Rules} -\label{sec:org9542834} +\label{sec:org29011d5} The \texttt{Presenter} has a set of function-object rules that determine some of its behaviours. Each corresponds to a setting in the \texttt{View}, but they can be set to other values via the \texttt{Presenter}'s setters (although nonstandard rules cannot be saved and loaded): \begin{description} \item[{numberDisplayRule}] A function that determines how numbers are displayed. This controls the rounding rules. @@ -184,7 +184,7 @@ The \texttt{Presenter} has a set of function-object rules that determine some of These rules have been made this way to enable an incredible level of customization of these behaviours. Because any function object with the correct arguments and return type is accepted, these rules (especially the number display rule) can do much more than the default behaviours. \subsection{Utility Classes} -\label{sec:orgc49ece0} +\label{sec:orga401626} The frontend has many miscellaneous utility classes. Many of them are package-private. Here is a list of them, with a brief description of what they do and where they are used: \begin{description} \item[{DefaultPrefixRepetitionRule}] An enum containing the available rules determining when you can repeat prefixes. Used by the \texttt{TabbedView} for selecting the rule and by the \texttt{Presenter} for loading it from a file. @@ -197,15 +197,15 @@ The frontend has many miscellaneous utility classes. Many of them are package-p \end{description} \newpage \section{Utility Classes} -\label{sec:orgc90957f} +\label{sec:org9889589} 7Units has a few general "utility" classes. They aren't directly related to units, but are used in the units system. \subsection{ObjectProduct} -\label{sec:orgc3e831c} +\label{sec:org9c5f1fc} An \texttt{ObjectProduct} represents a "product" of elements of some type. The units system uses them to represent coherent units as a product of base units, and dimensions as a product of base dimensions. Internally, it is represented using a map mapping objects to their exponents in the product. For example, the unit "kg m\textsuperscript{2} / s\textsuperscript{2}" (i.e. a Joule) would be represented with a map like \texttt{[kg: 1, m: 2, s: -2]}. \subsection{ExpressionParser} -\label{sec:orgd351c2f} +\label{sec:org7f49fac} The \texttt{ExpressionParser} class is used to parse the unit, prefix and dimension expressions that are used throughout 7Units. An expression is something like "(2 m + 30 J / N) * 8 s)". Each instance represents a type of expression, containing a way to obtain values (such as numbers or units) from the text and operations that can be done on these values (such as addition, subtraction or multiplication). Each operation also has a priority, which controls the order of operations (i.e. multiplication gets a higher priority than addition). \texttt{ExpressionParser} has a parameterized type \texttt{T}, which represents the type of the value used in the expression. The expression parser currently only supports one type of value per expression; in the expressions used by 7Units numbers are treated as a kind of unit or prefix. Operators are represented by internal types; the system distinguishes between unary operators (those that take a single value, like negation) and binary operators (those that take 2 values, like +, -, * or /). @@ -222,13 +222,13 @@ Expressions are parsed in 2 steps: After evaluating the last token, there should be one value left in the stack - the answer. If there isn't, the original expression was malformed. \end{enumerate} \subsection{Math Classes} -\label{sec:orgdadbc0d} +\label{sec:org48c9af9} There are two simple math classes in 7Units: \begin{description} \item[{\texttt{UncertainDouble}}] Like a \texttt{double}, but with an uncertainty (e.g. \(2.0 \pm 0.4\)). The operations are like those of the regular Double, only they also calculate the uncertainty of the final value. They also have "exact" versions to help interoperation between \texttt{double} and \texttt{UncertainDouble}. It is used by the converter's Scientific Precision setting. \item[{\texttt{DecimalComparison}}] A static utility class that contains a few alternate equals() methods for \texttt{double} and \texttt{UncertainDouble}. These methods allow a slight (configurable) difference between values to still be considered equal, to fight roundoff error. \end{description} \subsection{Collection Classes} -\label{sec:org7421746} +\label{sec:org9065607} The \texttt{ConditionalExistenceCollections} class contains wrapper implementations of \texttt{Collection}, \texttt{Iterator}, \texttt{Map} and \texttt{Set}. These implementations ignore elements that do not pass a certain condition - if an element fails the condition, \texttt{contains} will return false, the iterator will skip past it, it won't be counted in \texttt{size}, etc. even if it exists in the original collection. Effectively, any element of the original collection that fails the test does not exist. \end{document} diff --git a/docs/manual.org b/docs/manual.org index 6de3b93..bcaaf6b 100644 --- a/docs/manual.org +++ b/docs/manual.org @@ -1,5 +1,5 @@ #+TITLE: 7Units User Manual -#+SUBTITLE: For Version 0.4.0-alpha.1 +#+SUBTITLE: For Version 0.4.0-beta.1 #+DATE: 2022 July 8 #+LaTeX_HEADER: \usepackage[a4paper, lmargin=25mm, rmargin=25mm, tmargin=25mm, bmargin=25mm]{geometry} @@ -9,7 +9,7 @@ * System Requirements - Works on all major operating systems \\ *NOTE:* All screenshots in this document were taken on Windows 10. If you use a different operating system, the program will probably look different than what is shown. - - Java version 11-15 required + - Java version 11+ required # installation instructions go here - wait until git repository is fixed/set up #+LaTeX: \newpage * How to Use 7Units @@ -47,7 +47,7 @@ [[../screenshots/sample-conversion-results-expression-converter.png]] * 7Units Settings All settings can be accessed in the tab with the gear icon. - #+CAPTION: The settings menu, as of version 0.4.0-alpha.1 + #+CAPTION: The settings menu, as of version 0.4.0-beta.1 #+ATTR_LaTeX: :height 250px [[../screenshots/main-interface-settings.png]] ** Rounding Settings diff --git a/docs/manual.pdf b/docs/manual.pdf index 71cb886..430eb09 100644 Binary files a/docs/manual.pdf and b/docs/manual.pdf differ diff --git a/docs/manual.tex b/docs/manual.tex index 4b8e4ab..bc80a69 100644 --- a/docs/manual.tex +++ b/docs/manual.tex @@ -1,4 +1,4 @@ -% Created 2022-07-08 Fri 10:17 +% Created 2022-07-08 Fri 12:44 % Intended LaTeX compiler: pdflatex \documentclass[11pt]{article} \usepackage[utf8]{inputenc} @@ -17,7 +17,7 @@ \usepackage[a4paper, lmargin=25mm, rmargin=25mm, tmargin=25mm, bmargin=25mm]{geometry} \date{2022 July 8} \title{7Units User Manual\\\medskip -\large For Version 0.4.0-alpha.1} +\large For Version 0.4.0-beta.1} \hypersetup{ pdfauthor={}, pdftitle={7Units User Manual}, @@ -32,21 +32,21 @@ \newpage \section{Introduction and Purpose} -\label{sec:org26b964e} +\label{sec:org40df1fc} 7Units is a program that can be used to convert units. This document outlines how to use the program. \section{System Requirements} -\label{sec:orgfb95788} +\label{sec:org5bf24ac} \begin{itemize} \item Works on all major operating systems \\ \textbf{NOTE:} All screenshots in this document were taken on Windows 10. If you use a different operating system, the program will probably look different than what is shown. -\item Java version 11-15 required +\item Java version 11+ required \end{itemize} \newpage \section{How to Use 7Units} -\label{sec:orgc48d5d5} +\label{sec:org0303c2c} \subsection{Simple Unit Conversion} -\label{sec:orgd56d395} +\label{sec:orgfdea557} \begin{enumerate} \item Select the "Convert Units" tab if it is not already selected. You should see a screen like in figure \ref{main-interface-dimension}: \begin{figure}[htbp] @@ -71,7 +71,7 @@ \end{figure} \end{enumerate} \subsection{Complex Unit Conversion} -\label{sec:org79999e9} +\label{sec:orgaebd362} \begin{enumerate} \item Select the "Convert Unit Expressions" if it is not already selected. You should see a screen like in figure \ref{main-interface-expression}: \begin{figure}[htbp] @@ -79,7 +79,7 @@ \includegraphics[height=250px]{../screenshots/main-interface-expression-converter.png} \caption{\label{main-interface-expression}Taken in version 0.3.0} \end{figure} -\item Enter a \hyperref[sec:org28ae9bb]{unit expression} in the From box. This can be something like "\texttt{7 km}" or "\texttt{6 ft - 2 in}" or "\texttt{3 kg m + 9 lb ft + (35 mm)\textasciicircum{}2 * (85 oz) / (20 in)}". +\item Enter a \hyperref[sec:org1bb92a1]{unit expression} in the From box. This can be something like "\texttt{7 km}" or "\texttt{6 ft - 2 in}" or "\texttt{3 kg m + 9 lb ft + (35 mm)\textasciicircum{}2 * (85 oz) / (20 in)}". \item Enter a unit name (or another unit expression) in the To box. \item Press the Convert button. This will calculate the value of the first expression, and convert it to a multiple of the second unit (or expression). \begin{figure}[htbp] @@ -89,15 +89,15 @@ \end{figure} \end{enumerate} \section{7Units Settings} -\label{sec:org6032cec} +\label{sec:orgcab9094} All settings can be accessed in the tab with the gear icon. \begin{figure}[htbp] \centering \includegraphics[height=250px]{../screenshots/main-interface-settings.png} -\caption{The settings menu, as of version 0.4.0-alpha.1} +\caption{The settings menu, as of version 0.4.0-beta.1} \end{figure} \subsection{Rounding Settings} -\label{sec:orgbe67478} +\label{sec:orgbb50019} These settings control how the output of a unit conversion is rounded. \begin{description} \item[{Fixed Precision}] Round to a fixed number of \href{https://en.wikipedia.org/wiki/Significant\_figures}{significant digits}. The number of significant digits is controlled by the precision slider below. @@ -105,7 +105,7 @@ These settings control how the output of a unit conversion is rounded. \item[{Scientific Precision}] Intelligent rounding which uses the precision of the input value(s) to determine the output precision. Not affected by the precision slider. \end{description} \subsection{Prefix Repetition Settings} -\label{sec:org3207fad} +\label{sec:org48d4cc7} These settings control when you are allowed to repeat unit prefixes (e.g. kilokilometre) \begin{description} \item[{No Repetition}] Units may only have one prefix. @@ -120,7 +120,7 @@ These settings control when you are allowed to repeat unit prefixes (e.g. kiloki \end{itemize} \end{description} \subsection{Search Settings} -\label{sec:orge76e8f6} +\label{sec:orgce39699} These settings control which prefixes are shown in the "Convert Units" tab. Only coherent SI units (e.g. metre, second, newton, joule) will get prefixes. Some prefixed units are created in the unitfile, and will stay regardless of this setting (though they can be removed from the unitfile). \begin{description} \item[{Never Include Prefixed Units}] Prefixed units will only be shown if they are explicitly added to the unitfile. @@ -128,15 +128,15 @@ These settings control which prefixes are shown in the "Convert Units" tab. Onl \item[{Include All Single Prefixes}] Every coherent unit will have every prefixed version of it included in the list. \end{description} \subsection{Miscellaneous Settings} -\label{sec:org5613324} +\label{sec:org2332067} \begin{description} \item[{Convert One Way Only}] In the simple conversion tab, only imperial/customary units will be shown on the left, and only metric units\footnote{7Units's definition of "metric" is stricter than the SI, but all of the common units that are commonly considered metric but not included in 7Units's definition are included in the exceptions file.} will be shown on the right. Units listed in the exceptions file (\texttt{src/main/resources/metric\_exceptions.txt}) will be shown on both sides. This is a way to reduce the number of options you must search through if you only convert one way. The expressions tab is unaffected. \item[{Show Duplicates in "Convert Units"}] If unchecked, any unit that has multiple names will only have one included in the Convert Units lists. The selected name will be the longest; if there are multiple longest names one is selected arbitrarily. You will still be able to use these alternate names in the expressions tab. \end{description} \section{Appendices} -\label{sec:org03406a3} +\label{sec:orgd294b53} \subsection{Unit Expressions} -\label{sec:org28ae9bb} +\label{sec:org1bb92a1} A unit expression is simply a math expression where the values being operated on are units or numbers. The operations that can be used are (in order of precedence): \begin{itemize} \item Exponentiation (\^{}); the exponent must be an integer. Both units and numbers can be raised to an exponent @@ -146,6 +146,6 @@ A unit expression is simply a math expression where the values being operated on Brackets can be used to manipulate the order of operations, and nonlinear units like Celsius and Fahrenheit cannot be used in expressions. You can use a value in a nonlinear unit by putting brackets after it - for example, degC(12) represents the value 12 \textdegree{} C \subsection{Other Expressions} -\label{sec:orgb03cf2c} +\label{sec:org2f36819} There are also a simplified version of expressions for prefixes and dimensions. Only multiplication, division and exponentation are supported. Currently, exponentation is not supported for dimensions, but that may be fixed in the future. \end{document} diff --git a/screenshots/main-interface-settings.png b/screenshots/main-interface-settings.png index c29f65c..39b95f4 100644 Binary files a/screenshots/main-interface-settings.png and b/screenshots/main-interface-settings.png differ diff --git a/src/main/java/sevenUnits/ProgramInfo.java b/src/main/java/sevenUnits/ProgramInfo.java index f32d2c7..6ebe66c 100644 --- a/src/main/java/sevenUnits/ProgramInfo.java +++ b/src/main/java/sevenUnits/ProgramInfo.java @@ -26,9 +26,9 @@ import sevenUnits.utils.SemanticVersionNumber; */ public final class ProgramInfo { - /** The version number (0.4.0-alpha+dev) */ + /** The version number (0.4.0-beta.1) */ public static final SemanticVersionNumber VERSION = SemanticVersionNumber - .preRelease(0, 4, 0, "alpha", 1); + .preRelease(0, 4, 0, "beta", 1); private ProgramInfo() { // this class is only for static variables, you shouldn't be able to diff --git a/src/main/java/sevenUnits/unit/BaseDimension.java b/src/main/java/sevenUnits/unit/BaseDimension.java index bcd57d9..820d48c 100644 --- a/src/main/java/sevenUnits/unit/BaseDimension.java +++ b/src/main/java/sevenUnits/unit/BaseDimension.java @@ -1,5 +1,5 @@ /** - * Copyright (C) 2019 Adrien Hopkins + * Copyright (C) 2019, 2022 Adrien Hopkins * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by @@ -63,6 +63,9 @@ public final class BaseDimension implements Nameable { this.symbol = Objects.requireNonNull(symbol, "symbol must not be null."); } + /** + * @since v0.4.0 + */ @Override public NameSymbol getNameSymbol() { return NameSymbol.of(this.name, this.symbol); diff --git a/src/main/java/sevenUnits/utils/NameSymbol.java b/src/main/java/sevenUnits/utils/NameSymbol.java index 7ef2967..9388f63 100644 --- a/src/main/java/sevenUnits/utils/NameSymbol.java +++ b/src/main/java/sevenUnits/utils/NameSymbol.java @@ -294,6 +294,7 @@ public final class NameSymbol { * extra name. If this {@code NameSymbol} has a primary name, the provided * name will become an other name, otherwise it will become the primary name. * + * @since v0.4.0 * @since 2022-04-19 */ public final NameSymbol withExtraName(String name) { diff --git a/src/main/java/sevenUnits/utils/SemanticVersionNumber.java b/src/main/java/sevenUnits/utils/SemanticVersionNumber.java index a663a11..e80e16e 100644 --- a/src/main/java/sevenUnits/utils/SemanticVersionNumber.java +++ b/src/main/java/sevenUnits/utils/SemanticVersionNumber.java @@ -39,6 +39,7 @@ import java.util.regex.Pattern; * are made * * + * @since v0.4.0 * @since 2022-02-19 */ public final class SemanticVersionNumber @@ -51,6 +52,7 @@ public final class SemanticVersionNumber * throw NullPointerExceptions, everything else throws * IllegalArgumentException. * + * @since v0.4.0 * @since 2022-02-19 */ public static final class Builder { @@ -67,6 +69,7 @@ public final class SemanticVersionNumber * @param major major version number of final version * @param minor minor version number of final version * @param patch patch version number of final version + * @since v0.4.0 * @since 2022-02-19 */ private Builder(int major, int minor, int patch) { @@ -79,6 +82,7 @@ public final class SemanticVersionNumber /** * @return version number created by this builder + * @since v0.4.0 * @since 2022-02-19 */ public SemanticVersionNumber build() { @@ -91,6 +95,7 @@ public final class SemanticVersionNumber * * @param identifiers build metadata * @return this builder + * @since v0.4.0 * @since 2022-02-19 */ public Builder buildMetadata(List identifiers) { @@ -110,6 +115,7 @@ public final class SemanticVersionNumber * * @param identifiers build metadata * @return this builder + * @since v0.4.0 * @since 2022-02-19 */ public Builder buildMetadata(String... identifiers) { @@ -148,6 +154,7 @@ public final class SemanticVersionNumber * * @param identifiers pre-release identifier(s) to add * @return this builder + * @since v0.4.0 * @since 2022-02-19 */ public Builder preRelease(int... identifiers) { @@ -166,6 +173,7 @@ public final class SemanticVersionNumber * * @param identifiers pre-release identifier(s) to add * @return this builder + * @since v0.4.0 * @since 2022-02-19 */ public Builder preRelease(List identifiers) { @@ -185,6 +193,7 @@ public final class SemanticVersionNumber * * @param identifiers pre-release identifier(s) to add * @return this builder + * @since v0.4.0 * @since 2022-02-19 */ public Builder preRelease(String... identifiers) { @@ -205,6 +214,7 @@ public final class SemanticVersionNumber * @param identifier1 first identifier * @param identifier2 second identifier * @return this builder + * @since v0.4.0 * @since 2022-02-19 */ public Builder preRelease(String identifier1, int identifier2) { @@ -270,6 +280,7 @@ public final class SemanticVersionNumber * @param patch patch version number of final version * @return version number builder * @throws IllegalArgumentException if any argument is negative + * @since v0.4.0 * @since 2022-02-19 */ public static final SemanticVersionNumber.Builder builder(int major, @@ -293,6 +304,7 @@ public final class SemanticVersionNumber * @param b second list * @return result of comparison as in a comparator * @see Comparator + * @since v0.4.0 * @since 2022-02-20 */ private static final int compareIdentifiers(List a, List b) { @@ -353,6 +365,7 @@ public final class SemanticVersionNumber * * @param versionString string to parse * @return {@code SemanticVersionNumber} instance + * @since v0.4.0 * @since 2022-02-19 * @see {@link #toString} */ @@ -396,6 +409,7 @@ public final class SemanticVersionNumber * * @param versionString string to test * @return true iff string is valid + * @since v0.4.0 * @since 2022-02-19 */ public static final boolean isValidVersionString(String versionString) { @@ -415,6 +429,7 @@ public final class SemanticVersionNumber * @throws IllegalArgumentException if any argument is negative or if the * preReleaseType is null, empty or not * alphanumeric (0-9, A-Z, a-z, - only) + * @since v0.4.0 * @since 2022-02-19 */ public static final SemanticVersionNumber preRelease(int major, int minor, @@ -452,6 +467,7 @@ public final class SemanticVersionNumber * @param patch patch version number * @return {@code SemanticVersionNumber} instance * @throws IllegalArgumentException if any argument is negative + * @since v0.4.0 * @since 2022-02-19 */ public static final SemanticVersionNumber stableVersion(int major, int minor, @@ -484,6 +500,7 @@ public final class SemanticVersionNumber * @param patch patch version number * @param preReleaseIdentifiers pre-release version data * @param buildMetadata build metadata + * @since v0.4.0 * @since 2022-02-19 */ private SemanticVersionNumber(int major, int minor, int patch, @@ -497,6 +514,7 @@ public final class SemanticVersionNumber /** * @return build metadata (empty if there is none) + * @since v0.4.0 * @since 2022-02-19 */ public List buildMetadata() { @@ -567,6 +585,7 @@ public final class SemanticVersionNumber * @param other version to compare with * @return true if you can definitely upgrade to {@code other} without * changing code + * @since v0.4.0 * @since 2022-02-20 */ public boolean compatibleWith(SemanticVersionNumber other) { @@ -620,6 +639,7 @@ public final class SemanticVersionNumber /** * @return true iff this version is stable (major version > 0 and not a * pre-release) + * @since v0.4.0 * @since 2022-02-19 */ public boolean isStable() { @@ -629,6 +649,7 @@ public final class SemanticVersionNumber /** * @return the MAJOR version number, incremented when you make backwards * incompatible API changes + * @since v0.4.0 * @since 2022-02-19 */ public int majorVersion() { @@ -638,6 +659,7 @@ public final class SemanticVersionNumber /** * @return the MINOR version number, incremented when you add backwards * compatible functionality + * @since v0.4.0 * @since 2022-02-19 */ public int minorVersion() { @@ -647,6 +669,7 @@ public final class SemanticVersionNumber /** * @return the PATCH version number, incremented when you make backwards * compatible bug fixes + * @since v0.4.0 * @since 2022-02-19 */ public int patchVersion() { @@ -656,6 +679,7 @@ public final class SemanticVersionNumber /** * @return identifiers describing this pre-release (empty if not a * pre-release) + * @since v0.4.0 * @since 2022-02-19 */ public List preReleaseIdentifiers() { @@ -674,6 +698,7 @@ public final class SemanticVersionNumber * 1, pre-release identifiers "alpha" and "1" and build metadata "2022-02-19" * has a string representation "3.2.1-alpha.1+2022-02-19". * + * @since v0.4.0 * @see The official SemVer specification */ @Override diff --git a/src/main/java/sevenUnitsGUI/ExpressionConversionView.java b/src/main/java/sevenUnitsGUI/ExpressionConversionView.java index 872ca10..5c39788 100644 --- a/src/main/java/sevenUnitsGUI/ExpressionConversionView.java +++ b/src/main/java/sevenUnitsGUI/ExpressionConversionView.java @@ -20,17 +20,20 @@ package sevenUnitsGUI; * A View that can convert unit expressions * * @author Adrien Hopkins + * @since v0.4.0 * @since 2021-12-15 */ public interface ExpressionConversionView extends View { /** * @return unit expression to convert from + * @since v0.4.0 * @since 2021-12-15 */ String getFromExpression(); /** * @return unit expression to convert to + * @since v0.4.0 * @since 2021-12-15 */ String getToExpression(); @@ -39,6 +42,7 @@ public interface ExpressionConversionView extends View { * Shows the output of an expression conversion to the user. * * @param uc unit conversion to show + * @since v0.4.0 * @since 2021-12-15 */ void showExpressionConversionOutput(UnitConversionRecord uc); diff --git a/src/main/java/sevenUnitsGUI/Main.java b/src/main/java/sevenUnitsGUI/Main.java index b5a896f..998b373 100644 --- a/src/main/java/sevenUnitsGUI/Main.java +++ b/src/main/java/sevenUnitsGUI/Main.java @@ -19,12 +19,16 @@ package sevenUnitsGUI; /** * The main code for the 7Units GUI * + * @since v0.4.0 * @since 2022-04-19 */ public final class Main { /** - * @param args + * The main method that starts 7Units + * + * @param args commandline arguments + * @since v0.4.0 * @since 2022-04-19 */ public static void main(String[] args) { diff --git a/src/main/java/sevenUnitsGUI/PrefixSearchRule.java b/src/main/java/sevenUnitsGUI/PrefixSearchRule.java index 2928082..87f14a8 100644 --- a/src/main/java/sevenUnitsGUI/PrefixSearchRule.java +++ b/src/main/java/sevenUnitsGUI/PrefixSearchRule.java @@ -33,24 +33,31 @@ import sevenUnits.unit.UnitPrefix; * A search rule that applies a certain set of prefixes to a unit. It always * includes the original unit in the output map. * + * @since v0.4.0 * @since 2022-07-06 */ public final class PrefixSearchRule implements Function, Map> { /** * A rule that does not add any prefixed versions of units. + * + * @since v0.4.0 */ public static final PrefixSearchRule NO_PREFIXES = getUniversalRule( Set.of()); /** * A rule that gives every unit a common set of prefixes. + * + * @since v0.4.0 */ public static final PrefixSearchRule COMMON_PREFIXES = getCoherentOnlyRule( Set.of(Metric.MILLI, Metric.KILO)); /** * A rule that gives every unit all metric prefixes. + * + * @since v0.4.0 */ public static final PrefixSearchRule ALL_METRIC_PREFIXES = getCoherentOnlyRule( Metric.ALL_PREFIXES); @@ -62,6 +69,7 @@ public final class PrefixSearchRule implements * * @param prefixes prefixes to apply * @return prefix rule + * @since v0.4.0 * @since 2022-07-06 */ public static final PrefixSearchRule getCoherentOnlyRule( @@ -75,6 +83,7 @@ public final class PrefixSearchRule implements * * @param prefixes prefixes to apply * @return prefix rule + * @since v0.4.0 * @since 2022-07-06 */ public static final PrefixSearchRule getUniversalRule( @@ -95,6 +104,7 @@ public final class PrefixSearchRule implements /** * @param prefixes * @param metricOnly + * @since v0.4.0 * @since 2022-07-06 */ public PrefixSearchRule(Set prefixes, @@ -140,6 +150,7 @@ public final class PrefixSearchRule implements /** * @return the allowUnit + * @since v0.4.0 * @since 2022-07-06 */ public Predicate getAllowUnit() { @@ -148,6 +159,7 @@ public final class PrefixSearchRule implements /** * @return the prefixes that are applied by this rule + * @since v0.4.0 * @since 2022-07-06 */ public Set getPrefixes() { diff --git a/src/main/java/sevenUnitsGUI/StandardDisplayRules.java b/src/main/java/sevenUnitsGUI/StandardDisplayRules.java index 0c0ba8e..cc69d31 100644 --- a/src/main/java/sevenUnitsGUI/StandardDisplayRules.java +++ b/src/main/java/sevenUnitsGUI/StandardDisplayRules.java @@ -28,12 +28,14 @@ import sevenUnits.utils.UncertainDouble; * A static utility class that can be used to make display rules for the * presenter. * + * @since v0.4.0 * @since 2022-04-18 */ public final class StandardDisplayRules { /** * A rule that rounds to a fixed number of decimal places. * + * @since v0.4.0 * @since 2022-04-18 */ public static final class FixedDecimals @@ -94,6 +96,7 @@ public final class StandardDisplayRules { /** * A rule that rounds to a fixed number of significant digits. * + * @since v0.4.0 * @since 2022-04-18 */ public static final class FixedPrecision @@ -162,6 +165,7 @@ public final class StandardDisplayRules { * This means the output will have around as many significant figures as the * input. * + * @since v0.4.0 * @since 2022-04-18 */ public static final class UncertaintyBased @@ -188,6 +192,7 @@ public final class StandardDisplayRules { /** * @param decimalPlaces decimal places to round to * @return a rounding rule that rounds to fixed number of decimal places + * @since v0.4.0 * @since 2022-04-18 */ public static final FixedDecimals fixedDecimals(int decimalPlaces) { @@ -198,6 +203,7 @@ public final class StandardDisplayRules { * @param significantFigures significant figures to round to * @return a rounding rule that rounds to a fixed number of significant * figures + * @since v0.4.0 * @since 2022-04-18 */ public static final FixedPrecision fixedPrecision(int significantFigures) { @@ -211,6 +217,7 @@ public final class StandardDisplayRules { * @return display rule * @throws IllegalArgumentException if the provided string is not that of a * standard rule. + * @since v0.4.0 * @since 2021-12-24 */ public static final Function getStandardRule( @@ -236,6 +243,7 @@ public final class StandardDisplayRules { /** * @return an UncertainDouble-based rounding rule + * @since v0.4.0 * @since 2022-04-18 */ public static final UncertaintyBased uncertaintyBased() { diff --git a/src/main/java/sevenUnitsGUI/UnitConversionRecord.java b/src/main/java/sevenUnitsGUI/UnitConversionRecord.java index f951f44..fa64ee9 100644 --- a/src/main/java/sevenUnitsGUI/UnitConversionRecord.java +++ b/src/main/java/sevenUnitsGUI/UnitConversionRecord.java @@ -24,6 +24,7 @@ import sevenUnits.unit.UnitValue; /** * A record of a conversion between units or expressions * + * @since v0.4.0 * @since 2022-04-09 */ public final class UnitConversionRecord { @@ -33,6 +34,7 @@ public final class UnitConversionRecord { * @param input input unit & value * @param output output unit & value * @return unit conversion record + * @since v0.4.0 * @since 2022-04-09 */ public static UnitConversionRecord fromLinearValues(LinearUnitValue input, @@ -49,6 +51,7 @@ public final class UnitConversionRecord { * @param input input unit & value * @param output output unit & value * @return unit conversion record + * @since v0.4.0 * @since 2022-04-09 */ public static UnitConversionRecord fromValues(UnitValue input, @@ -67,6 +70,7 @@ public final class UnitConversionRecord { * @param inputValueString string representing input value * @param outputValueString string representing output value * @return unit conversion record + * @since v0.4.0 * @since 2022-04-09 */ public static UnitConversionRecord valueOf(String fromName, String toName, @@ -143,6 +147,7 @@ public final class UnitConversionRecord { /** * @return name of unit or expression that was converted from + * @since v0.4.0 * @since 2022-04-09 */ public String fromName() { @@ -166,6 +171,7 @@ public final class UnitConversionRecord { /** * @return string representing input value + * @since v0.4.0 * @since 2022-04-09 */ public String inputValueString() { @@ -174,6 +180,7 @@ public final class UnitConversionRecord { /** * @return string representing output value + * @since v0.4.0 * @since 2022-04-09 */ public String outputValueString() { @@ -182,6 +189,7 @@ public final class UnitConversionRecord { /** * @return name of unit or expression that was converted to + * @since v0.4.0 * @since 2022-04-09 */ public String toName() { diff --git a/src/main/java/sevenUnitsGUI/UnitConversionView.java b/src/main/java/sevenUnitsGUI/UnitConversionView.java index 6a95aa5..0d07823 100644 --- a/src/main/java/sevenUnitsGUI/UnitConversionView.java +++ b/src/main/java/sevenUnitsGUI/UnitConversionView.java @@ -23,23 +23,27 @@ import java.util.Set; * A View that supports single unit-based conversion * * @author Adrien Hopkins + * @since v0.4.0 * @since 2021-12-15 */ public interface UnitConversionView extends View { /** * @return dimensions available for filtering + * @since v0.4.0 * @since 2022-01-29 */ Set getDimensionNames(); /** * @return name of unit to convert from + * @since v0.4.0 * @since 2021-12-15 */ Optional getFromSelection(); /** * @return list of names of units available to convert from + * @since v0.4.0 * @since 2022-03-30 */ Set getFromUnitNames(); @@ -47,24 +51,28 @@ public interface UnitConversionView extends View { /** * @return value to convert between the units (specifically, the numeric * string provided by the user) + * @since v0.4.0 * @since 2021-12-15 */ String getInputValue(); /** * @return selected dimension + * @since v0.4.0 * @since 2021-12-15 */ Optional getSelectedDimensionName(); /** * @return name of unit to convert to + * @since v0.4.0 * @since 2021-12-15 */ Optional getToSelection(); /** * @return list of names of units available to convert to + * @since v0.4.0 * @since 2022-03-30 */ Set getToUnitNames(); @@ -73,6 +81,7 @@ public interface UnitConversionView extends View { * Sets the available dimensions for filtering. * * @param dimensionNames names of dimensions to use + * @since v0.4.0 * @since 2021-12-15 */ void setDimensionNames(Set dimensionNames); @@ -83,6 +92,7 @@ public interface UnitConversionView extends View { * that allow the user to select units from a list. * * @param unitNames names of units to convert from + * @since v0.4.0 * @since 2021-12-15 */ void setFromUnitNames(Set unitNames); @@ -93,6 +103,7 @@ public interface UnitConversionView extends View { * that allow the user to select units from a list. * * @param unitNames names of units to convert to + * @since v0.4.0 * @since 2021-12-15 */ void setToUnitNames(Set unitNames); @@ -102,6 +113,7 @@ public interface UnitConversionView extends View { * * @param input input unit & value (obtained from this view) * @param output output unit & value + * @since v0.4.0 * @since 2021-12-24 */ void showUnitConversionOutput(UnitConversionRecord uc); diff --git a/src/main/java/sevenUnitsGUI/View.java b/src/main/java/sevenUnitsGUI/View.java index b2d2b94..bb810ec 100644 --- a/src/main/java/sevenUnitsGUI/View.java +++ b/src/main/java/sevenUnitsGUI/View.java @@ -26,11 +26,13 @@ import sevenUnits.utils.NameSymbol; * An object that controls user interaction with 7Units * * @author Adrien Hopkins + * @since v0.4.0 * @since 2021-12-15 */ public interface View { /** * @return a new tabbed view + * @since v0.4.0 * @since 2022-04-19 */ static View createTabbedView() { @@ -39,18 +41,21 @@ public interface View { /** * @return the presenter associated with this view + * @since v0.4.0 * @since 2022-04-19 */ Presenter getPresenter(); /** * @return name of prefix currently being viewed + * @since v0.4.0 * @since 2022-04-10 */ Optional getViewedPrefixName(); /** * @return name of unit currently being viewed + * @since v0.4.0 * @since 2022-04-10 */ Optional getViewedUnitName(); @@ -60,6 +65,7 @@ public interface View { * viewer * * @param prefixNames prefix names to view + * @since v0.4.0 * @since 2022-04-10 */ void setViewablePrefixNames(Set prefixNames); @@ -68,6 +74,7 @@ public interface View { * Sets the list of units that are available to be viewed in a unit viewer * * @param unitNames unit names to view + * @since v0.4.0 * @since 2022-04-10 */ void setViewableUnitNames(Set unitNames); @@ -78,6 +85,7 @@ public interface View { * @param title title of error message; on any view that uses an error * dialog, this should be the title of the error dialog. * @param message error message + * @since v0.4.0 * @since 2021-12-15 */ void showErrorMessage(String title, String message); @@ -87,6 +95,7 @@ public interface View { * * @param name name(s) and symbol of prefix * @param multiplierString string representation of prefix multiplier + * @since v0.4.0 * @since 2022-04-10 */ void showPrefix(NameSymbol name, String multiplierString); @@ -98,6 +107,7 @@ public interface View { * @param definition unit's definition string * @param dimensionName name of unit's dimension * @param type type of unit (metric/semi-metric/non-metric) + * @since v0.4.0 * @since 2022-04-10 */ void showUnit(NameSymbol name, String definition, String dimensionName, diff --git a/src/main/java/sevenUnitsGUI/ViewBot.java b/src/main/java/sevenUnitsGUI/ViewBot.java index a3ba7a2..e7304c4 100644 --- a/src/main/java/sevenUnitsGUI/ViewBot.java +++ b/src/main/java/sevenUnitsGUI/ViewBot.java @@ -32,6 +32,7 @@ import sevenUnits.utils.Nameable; * for testing. Getters and setters work as expected. * * @author Adrien Hopkins + * @since v0.4.0 * @since 2022-01-29 */ public final class ViewBot -- cgit v1.2.3