From 2eee97c9e64dca79fc6b1614b304b398d25a7f4b Mon Sep 17 00:00:00 2001 From: Adrien Hopkins Date: Sat, 27 Mar 2021 16:36:39 -0500 Subject: Added automatic building with Gradle --- src/main/resources/about.txt | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 src/main/resources/about.txt (limited to 'src/main/resources') diff --git a/src/main/resources/about.txt b/src/main/resources/about.txt new file mode 100644 index 0000000..1bad9e8 --- /dev/null +++ b/src/main/resources/about.txt @@ -0,0 +1,12 @@ +About Unit Converter v0.2.0 + +Copyright Notice: + +Unit Converter Copyright (C) 2018-2021 Adrien Hopkins +This program comes with ABSOLUTELY NO WARRANTY; +for details read the LICENSE file, section 15 + +This is free software, and you are welcome to redistribute +it under certain conditions; for details go to + +or read the LICENSE file. \ No newline at end of file -- cgit v1.2.3 From 3e6fee9561a00e5d9958c5685336c9d68c8629e1 Mon Sep 17 00:00:00 2001 From: Adrien Hopkins Date: Sat, 27 Mar 2021 18:00:14 -0500 Subject: Used resources instead of Paths to make the generated jar work --- bin/main/.gitignore | 3 + build.gradle | 16 +- dimensionfile.txt | 18 -- metric_exceptions.txt | 19 -- .../converterGUI/UnitConverterGUI.java | 97 ++++++-- .../java/org/unitConverter/unit/UnitDatabase.java | 34 +++ src/main/resources/dimensionfile.txt | 18 ++ src/main/resources/metric_exceptions.txt | 19 ++ src/main/resources/unitsfile.txt | 267 +++++++++++++++++++++ unitsfile.txt | 267 --------------------- 10 files changed, 426 insertions(+), 332 deletions(-) delete mode 100644 dimensionfile.txt delete mode 100644 metric_exceptions.txt create mode 100644 src/main/resources/dimensionfile.txt create mode 100644 src/main/resources/metric_exceptions.txt create mode 100644 src/main/resources/unitsfile.txt delete mode 100644 unitsfile.txt (limited to 'src/main/resources') diff --git a/bin/main/.gitignore b/bin/main/.gitignore index b2d0b77..e5fcaae 100644 --- a/bin/main/.gitignore +++ b/bin/main/.gitignore @@ -1,2 +1,5 @@ /about.txt /org/ +/dimensionfile.txt +/metric_exceptions.txt +/unitsfile.txt diff --git a/build.gradle b/build.gradle index 11bf07b..1a2ef44 100644 --- a/build.gradle +++ b/build.gradle @@ -20,12 +20,18 @@ dependencies { testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0' } +jar { + manifest { + attributes 'Main-Class': "org.unitConverter.converterGUI.UnitConverterGUI" + } +} + test { - useJUnitPlatform() - testLogging { - events 'passed', 'skipped', 'failed' - } - finalizedBy jacocoTestReport + useJUnitPlatform() + testLogging { + events 'passed', 'skipped', 'failed' + } + finalizedBy jacocoTestReport } jacoco { diff --git a/dimensionfile.txt b/dimensionfile.txt deleted file mode 100644 index 3485de5..0000000 --- a/dimensionfile.txt +++ /dev/null @@ -1,18 +0,0 @@ -# A file for the unit dimensions in my unit converter program - -# SI Base Dimensions -# ! means "look for an existing dimension which I will load at the start" -# This is necessary because every dimension must be defined by others, and I need somewhere to start. - -# I have excluded electric current, quantity and luminous intensity since their units are exclusively SI. - -LENGTH ! -MASS ! -TIME ! -TEMPERATURE ! - -# Derived Dimensions -AREA LENGTH^2 -VOLUME LENGTH^3 -VELOCITY LENGTH / TIME -ENERGY MASS * VELOCITY^2 \ No newline at end of file diff --git a/metric_exceptions.txt b/metric_exceptions.txt deleted file mode 100644 index 73748c0..0000000 --- a/metric_exceptions.txt +++ /dev/null @@ -1,19 +0,0 @@ -# This is a list of exceptions for the one-way conversion mode -# Units in this list will be included in both From: and To: -# regardless of whether or not one-way conversion is enabled. - -tempC -tempCelsius -s -second -min -minute -h -hour -d -day -wk -week -gregorianmonth -gregorianyear -km/h \ No newline at end of file diff --git a/src/main/java/org/unitConverter/converterGUI/UnitConverterGUI.java b/src/main/java/org/unitConverter/converterGUI/UnitConverterGUI.java index c046846..ee1bcc3 100644 --- a/src/main/java/org/unitConverter/converterGUI/UnitConverterGUI.java +++ b/src/main/java/org/unitConverter/converterGUI/UnitConverterGUI.java @@ -23,6 +23,7 @@ import java.awt.GridLayout; import java.awt.event.KeyEvent; import java.io.BufferedWriter; import java.io.IOException; +import java.io.InputStream; import java.math.BigDecimal; import java.math.MathContext; import java.math.RoundingMode; @@ -36,6 +37,7 @@ import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.NoSuchElementException; +import java.util.Scanner; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; @@ -93,13 +95,11 @@ final class UnitConverterGUI { /** The default place where settings are stored. */ private static final String DEFAULT_SETTINGS_FILEPATH = "settings.txt"; /** The default place where units are stored. */ - private static final Path DEFAULT_UNITS_FILE = Path.of("unitsfile.txt"); + private static final String DEFAULT_UNITS_FILEPATH = "/unitsfile.txt"; /** The default place where dimensions are stored. */ - private static final Path DEFAULT_DIMENSION_FILE = Path - .of("dimensionfile.txt"); + private static final String DEFAULT_DIMENSIONS_FILEPATH = "/dimensionfile.txt"; /** The default place where exceptions are stored. */ - private static final Path DEFAULT_EXCEPTIONS_FILE = Path - .of("metric_exceptions.txt"); + private static final String DEFAULT_EXCEPTIONS_FILEPATH = "/metric_exceptions.txt"; /** * Adds default units and dimensions to a database. @@ -130,6 +130,41 @@ final class UnitConverterGUI { database.addDimension("TEMPERATURE", SI.Dimensions.TEMPERATURE); } + /** + * Gets the text of a resource file as a set of strings (each one is one + * line of the text). + * + * @param filename filename to get resource from + * @return contents of file + * @since 2021-03-27 + */ + public static final List getLinesFromResource(String filename) { + final List lines = new ArrayList<>(); + + try (InputStream stream = inputStream(filename); + Scanner scanner = new Scanner(stream)) { + while (scanner.hasNextLine()) { + lines.add(scanner.nextLine()); + } + } catch (final IOException e) { + throw new AssertionError( + "Error occurred while loading file " + filename, e); + } + + return lines; + } + + /** + * Gets an input stream for a resource file. + * + * @param filepath file to use as resource + * @return obtained Path + * @since 2021-03-27 + */ + private static final InputStream inputStream(String filepath) { + return UnitConverterGUI.class.getResourceAsStream(filepath); + } + /** * @return {@code line} with any comments removed. * @since 2021-03-13 @@ -161,9 +196,9 @@ final class UnitConverterGUI { /** A boolean remembering whether or not one-way conversion is on */ private boolean oneWay = true; - /** The prefix rule */ private DefaultPrefixRepetitionRule prefixRule = null; + // conditions for existence of From and To entries // used for one-way conversion private final MutablePredicate fromExistenceCondition = new MutablePredicate<>( @@ -196,21 +231,44 @@ final class UnitConverterGUI { DefaultPrefixRepetitionRule.NO_RESTRICTION); Presenter.addDefaults(this.database); - this.database.loadUnitsFile(DEFAULT_UNITS_FILE); - this.database.loadDimensionFile(DEFAULT_DIMENSION_FILE); + // load units and prefixes + try (final InputStream units = inputStream(DEFAULT_UNITS_FILEPATH)) { + this.database.loadUnitsFromStream(units); + } catch (final IOException e) { + throw new AssertionError("Loading of unitsfile.txt failed.", e); + } + + // load dimensions + try (final InputStream dimensions = inputStream( + DEFAULT_DIMENSIONS_FILEPATH)) { + this.database.loadDimensionsFromStream(dimensions); + } catch (final IOException e) { + throw new AssertionError("Loading of dimensionfile.txt failed.", e); + } // load metric exceptions try { - this.metricExceptions = Files.readAllLines(DEFAULT_EXCEPTIONS_FILE) - .stream().map(Presenter::withoutComments) - .filter(s -> !s.isBlank()).collect(Collectors.toSet()); + this.metricExceptions = new HashSet<>(); + try (InputStream exceptions = inputStream( + DEFAULT_EXCEPTIONS_FILEPATH); + Scanner scanner = new Scanner(exceptions)) { + while (scanner.hasNextLine()) { + final String line = Presenter + .withoutComments(scanner.nextLine()); + if (!line.isBlank()) { + this.metricExceptions.add(line); + } + } + } } catch (final IOException e) { throw new AssertionError("Loading of metric_exceptions.txt failed.", e); } // load settings - requires database to exist - this.loadSettings(); + if (Files.exists(this.getSettingsFile())) { + this.loadSettings(); + } // a comparator that can be used to compare prefix names // any name that does not exist is less than a name that does. @@ -1139,17 +1197,10 @@ final class UnitConverterGUI { infoPanel.add(infoTextArea); // get info text - final String infoText; - try { - final Path aboutFile = Path.of("src", "main", "resources", - "about.txt"); - infoText = Files.readAllLines(aboutFile).stream() - .map(Presenter::withoutComments) - .collect(Collectors.joining("\n")); - } catch (final IOException e) { - throw new AssertionError("I/O exception loading about.txt", - e); - } + final String infoText = Presenter + .getLinesFromResource("/about.txt").stream() + .map(Presenter::withoutComments) + .collect(Collectors.joining("\n")); infoTextArea.setText(infoText); } diff --git a/src/main/java/org/unitConverter/unit/UnitDatabase.java b/src/main/java/org/unitConverter/unit/UnitDatabase.java index 000acf5..6322fef 100644 --- a/src/main/java/org/unitConverter/unit/UnitDatabase.java +++ b/src/main/java/org/unitConverter/unit/UnitDatabase.java @@ -18,6 +18,7 @@ package org.unitConverter.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; @@ -34,6 +35,7 @@ import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.Objects; +import java.util.Scanner; import java.util.Set; import java.util.function.BiFunction; import java.util.function.Function; @@ -1879,6 +1881,22 @@ public final class UnitDatabase { } } + /** + * Adds all dimensions from a {@code InputStream}. Otherwise, works like + * {@link #loadDimensionFile}. + * + * @param stream stream to load from + * @since 2021-03-27 + */ + public void loadDimensionsFromStream(final InputStream stream) { + try (final Scanner scanner = new Scanner(stream)) { + long lineCounter = 0; + while (scanner.hasNextLine()) { + this.addDimensionFromLine(scanner.nextLine(), ++lineCounter); + } + } + } + /** * Adds all units from a file, using data from the database to parse them. *

@@ -1918,6 +1936,22 @@ public final class UnitDatabase { } } + /** + * Adds all units from a {@code InputStream}. Otherwise, works like + * {@link #loadUnitsFile}. + * + * @param stream stream to load from + * @since 2021-03-27 + */ + public void loadUnitsFromStream(InputStream stream) { + try (final Scanner scanner = new Scanner(stream)) { + long lineCounter = 0; + while (scanner.hasNextLine()) { + this.addUnitOrPrefixFromLine(scanner.nextLine(), ++lineCounter); + } + } + } + /** * @return a map mapping prefix names to prefixes * @since 2019-04-13 diff --git a/src/main/resources/dimensionfile.txt b/src/main/resources/dimensionfile.txt new file mode 100644 index 0000000..3485de5 --- /dev/null +++ b/src/main/resources/dimensionfile.txt @@ -0,0 +1,18 @@ +# A file for the unit dimensions in my unit converter program + +# SI Base Dimensions +# ! means "look for an existing dimension which I will load at the start" +# This is necessary because every dimension must be defined by others, and I need somewhere to start. + +# I have excluded electric current, quantity and luminous intensity since their units are exclusively SI. + +LENGTH ! +MASS ! +TIME ! +TEMPERATURE ! + +# Derived Dimensions +AREA LENGTH^2 +VOLUME LENGTH^3 +VELOCITY LENGTH / TIME +ENERGY MASS * VELOCITY^2 \ No newline at end of file diff --git a/src/main/resources/metric_exceptions.txt b/src/main/resources/metric_exceptions.txt new file mode 100644 index 0000000..73748c0 --- /dev/null +++ b/src/main/resources/metric_exceptions.txt @@ -0,0 +1,19 @@ +# This is a list of exceptions for the one-way conversion mode +# Units in this list will be included in both From: and To: +# regardless of whether or not one-way conversion is enabled. + +tempC +tempCelsius +s +second +min +minute +h +hour +d +day +wk +week +gregorianmonth +gregorianyear +km/h \ No newline at end of file diff --git a/src/main/resources/unitsfile.txt b/src/main/resources/unitsfile.txt new file mode 100644 index 0000000..eafe885 --- /dev/null +++ b/src/main/resources/unitsfile.txt @@ -0,0 +1,267 @@ +# A file for the units in my unit converter program + +# SI Base Units +# ! means "look for an existing unit which I will load at the start" +# This is necessary because every unit must be defined by others, and I need somewhere to start. + +metre ! +kilogram ! +second ! +ampere ! +kelvin ! +mole ! +candela ! + +# Symbols and aliases for base units + +meter metre +m metre +kg kilogram +s second +A ampere +K kelvin +mol mole +cd candela + +# the bit and byte, units of information + +bit ! +b bit +byte 8 bit +B byte + +# SI prefixes + +deca- 10 +deka- deca +hecto- 100 +kilo- 1e3 +mega- 1e6 +giga- 1e9 +tera- 1e12 +peta- 1e15 +exa- 1e18 +zetta- 1e21 +yotta- 1e24 + +deci- 1e-1 +centi- 1e-2 +milli- 1e-3 +micro- 1e-6 +nano- 1e-9 +pico- 1e-12 +femto- 1e-15 +atto- 1e-18 +zepto- 1e-21 +yocto- 1e-24 + +da- deca +D- deca +h- hecto +H- hecto +k- kilo +K- kilo +M- mega +G- giga +T- tera +P- peta +E- exa +Z- zetta +Y- yotta + +d- deci +c- centi +m- milli +u- micro +n- nano +p- pico +f- femto +a- atto +z- zepto +y- yocto + +# Binary prefixes (i.e. metric but 1024 replaces 1000) + +kibi- 1024^1 +mebi- 1024^2 +gibi- 1024^3 +tebi- 1024^4 +pebi- 1024^5 +exbi- 1024^6 +Ki- kibi +Mi- mebi +Gi- gibi +Ti- tebi +Pi- pebi +Ei- exbi + +# Derived SI units +# Note: it is best to have these before any non-SI units + +newton kg m / s^2 +N newton +pascal N / m^2 +Pa pascal +joule N m +J joule +watt J/s +W watt +coulomb A s +C coulomb +volt W/A +V volt +ohm V/A +siemens A/V +S siemens +farad C/V +F farad +weber V s +Wb weber +henry V s / A +H henry +tesla Wb / m^2 +T tesla +hertz 1 / s +Hz hertz + +gram millikg +g gram + +# Angle units and constants + +# Tau is the circle constant, equal to a circle's diameter divided by its radius +tau 6.28318530717958 +# Another common circle constant +pi tau / 2 + +radian m / m +rad radian +steradian m^2 / m^2 +sr steradian +degree tau / 360 radian +deg degree +° degree + +# Nonlinear units, which are not supported by the file reader and must be defined manually +# Use tempC(100) for 100 degrees Celsius + +tempCelsius ! +tempFahrenheit ! +tempC tempCelsius +tempF tempFahrenheit + +# Common time units +minute 60 second +min minute +hour 3600 second +h hour +day 86400 second +d day +week 7 day +wk week +julianyear 365.25 day +gregorianyear 365.2425 day +gregorianmonth gregorianyear / 12 + +# Other non-SI "metric" units +litre 0.001 m^3 +liter litre +l litre +L litre +tonne 1000 kg +t tonne +are 100 m^2 +hectare hectoare +arcminute 1 / 60 degree +arcmin arcminute +arcsecond 1 / 60 arcminute +arcsec arcsecond + +# constants +waterdensity kilogram / litre + +# Imperial length units +foot 0.3048 m +ft foot +inch foot / 12 +in inch +yard 3 foot +yd yard +mile 1760 yard +mi mile + +# Compressed notation +kph km / hour +mph mile / hour + +# Imperial weight units +pound 0.45359237 kg +lb pound +ounce pound / 16 +oz ounce +stone 14 lb +UShundredweight 100 lb +UKhundredweight 8 stone +USimperialton 20 UShundredweight +UKimperialton 10 UKhundredweight + +# Imperial volume units +UKfluidounce ounce / waterdensity +UKfloz UKfluidounce +UKcup 10 UKfloz +UKpint 2 UKcup +UKquart 2 UKpint +UKgallon 4 UKquart +UKgal UKgallon + +USgallon 231 inch^3 +USgal USgallon +USquart USgallon / 4 +USpint USquart / 2 +UScup USpint / 2 +USfluidounce UScup / 8 +USfloz USfluidounce +UStablespoon USfluidounce / 2 +UStbsp UStablespoon +USteaspoon UStablespoon / 3 +UStsp USteaspoon + +# Metric versions! +# tsp = 5 mL, tbsp = 15 mL, floz = 30 mL, cup = 240 mL, pint = 480 mL, quart = 960 mL, gallon = 3840 mL +# only metrictsp, metrictbsp and metriccup are common, the rest are derived from the US formulae with 240 mL cup +metricteaspoon 5 mL +teaspoon metricteaspoon +tsp metricteaspoon +metrictablespoon 3 metricteaspoon +tablespoon metrictablespoon +tbsp metrictablespoon +metricfluidounce 2 metrictablespoon +metriccup 8 metricfluidounce +cup metriccup +metricpint 2 metriccup +pint metricpint +metricquart 2 metricpint +quart metricquart +metricgallon 4 metricquart + +# Energy units +calorie 4.18 J +cal calorie +Calorie kilocalorie +Cal Calorie +Wh W h + +# Extra units to only include in the dimension-based converter +km km +cm cm +mm mm +mg mg +mL mL +ml ml +kJ kJ +MJ MJ +kWh kWh +m/s m / s +km/h km / h +ft/s foot / s +mi/h mile / hour \ No newline at end of file diff --git a/unitsfile.txt b/unitsfile.txt deleted file mode 100644 index eafe885..0000000 --- a/unitsfile.txt +++ /dev/null @@ -1,267 +0,0 @@ -# A file for the units in my unit converter program - -# SI Base Units -# ! means "look for an existing unit which I will load at the start" -# This is necessary because every unit must be defined by others, and I need somewhere to start. - -metre ! -kilogram ! -second ! -ampere ! -kelvin ! -mole ! -candela ! - -# Symbols and aliases for base units - -meter metre -m metre -kg kilogram -s second -A ampere -K kelvin -mol mole -cd candela - -# the bit and byte, units of information - -bit ! -b bit -byte 8 bit -B byte - -# SI prefixes - -deca- 10 -deka- deca -hecto- 100 -kilo- 1e3 -mega- 1e6 -giga- 1e9 -tera- 1e12 -peta- 1e15 -exa- 1e18 -zetta- 1e21 -yotta- 1e24 - -deci- 1e-1 -centi- 1e-2 -milli- 1e-3 -micro- 1e-6 -nano- 1e-9 -pico- 1e-12 -femto- 1e-15 -atto- 1e-18 -zepto- 1e-21 -yocto- 1e-24 - -da- deca -D- deca -h- hecto -H- hecto -k- kilo -K- kilo -M- mega -G- giga -T- tera -P- peta -E- exa -Z- zetta -Y- yotta - -d- deci -c- centi -m- milli -u- micro -n- nano -p- pico -f- femto -a- atto -z- zepto -y- yocto - -# Binary prefixes (i.e. metric but 1024 replaces 1000) - -kibi- 1024^1 -mebi- 1024^2 -gibi- 1024^3 -tebi- 1024^4 -pebi- 1024^5 -exbi- 1024^6 -Ki- kibi -Mi- mebi -Gi- gibi -Ti- tebi -Pi- pebi -Ei- exbi - -# Derived SI units -# Note: it is best to have these before any non-SI units - -newton kg m / s^2 -N newton -pascal N / m^2 -Pa pascal -joule N m -J joule -watt J/s -W watt -coulomb A s -C coulomb -volt W/A -V volt -ohm V/A -siemens A/V -S siemens -farad C/V -F farad -weber V s -Wb weber -henry V s / A -H henry -tesla Wb / m^2 -T tesla -hertz 1 / s -Hz hertz - -gram millikg -g gram - -# Angle units and constants - -# Tau is the circle constant, equal to a circle's diameter divided by its radius -tau 6.28318530717958 -# Another common circle constant -pi tau / 2 - -radian m / m -rad radian -steradian m^2 / m^2 -sr steradian -degree tau / 360 radian -deg degree -° degree - -# Nonlinear units, which are not supported by the file reader and must be defined manually -# Use tempC(100) for 100 degrees Celsius - -tempCelsius ! -tempFahrenheit ! -tempC tempCelsius -tempF tempFahrenheit - -# Common time units -minute 60 second -min minute -hour 3600 second -h hour -day 86400 second -d day -week 7 day -wk week -julianyear 365.25 day -gregorianyear 365.2425 day -gregorianmonth gregorianyear / 12 - -# Other non-SI "metric" units -litre 0.001 m^3 -liter litre -l litre -L litre -tonne 1000 kg -t tonne -are 100 m^2 -hectare hectoare -arcminute 1 / 60 degree -arcmin arcminute -arcsecond 1 / 60 arcminute -arcsec arcsecond - -# constants -waterdensity kilogram / litre - -# Imperial length units -foot 0.3048 m -ft foot -inch foot / 12 -in inch -yard 3 foot -yd yard -mile 1760 yard -mi mile - -# Compressed notation -kph km / hour -mph mile / hour - -# Imperial weight units -pound 0.45359237 kg -lb pound -ounce pound / 16 -oz ounce -stone 14 lb -UShundredweight 100 lb -UKhundredweight 8 stone -USimperialton 20 UShundredweight -UKimperialton 10 UKhundredweight - -# Imperial volume units -UKfluidounce ounce / waterdensity -UKfloz UKfluidounce -UKcup 10 UKfloz -UKpint 2 UKcup -UKquart 2 UKpint -UKgallon 4 UKquart -UKgal UKgallon - -USgallon 231 inch^3 -USgal USgallon -USquart USgallon / 4 -USpint USquart / 2 -UScup USpint / 2 -USfluidounce UScup / 8 -USfloz USfluidounce -UStablespoon USfluidounce / 2 -UStbsp UStablespoon -USteaspoon UStablespoon / 3 -UStsp USteaspoon - -# Metric versions! -# tsp = 5 mL, tbsp = 15 mL, floz = 30 mL, cup = 240 mL, pint = 480 mL, quart = 960 mL, gallon = 3840 mL -# only metrictsp, metrictbsp and metriccup are common, the rest are derived from the US formulae with 240 mL cup -metricteaspoon 5 mL -teaspoon metricteaspoon -tsp metricteaspoon -metrictablespoon 3 metricteaspoon -tablespoon metrictablespoon -tbsp metrictablespoon -metricfluidounce 2 metrictablespoon -metriccup 8 metricfluidounce -cup metriccup -metricpint 2 metriccup -pint metricpint -metricquart 2 metricpint -quart metricquart -metricgallon 4 metricquart - -# Energy units -calorie 4.18 J -cal calorie -Calorie kilocalorie -Cal Calorie -Wh W h - -# Extra units to only include in the dimension-based converter -km km -cm cm -mm mm -mg mg -mL mL -ml ml -kJ kJ -MJ MJ -kWh kWh -m/s m / s -km/h km / h -ft/s foot / s -mi/h mile / hour \ No newline at end of file -- cgit v1.2.3 From df3651baf72c799339268293fccb75e127bb336c Mon Sep 17 00:00:00 2001 From: Adrien Hopkins Date: Sat, 22 May 2021 14:51:05 -0500 Subject: Added an option to exclude duplicate units --- .../unitConverter/converterGUI/SearchBoxList.java | 15 ++++++- .../converterGUI/UnitConverterGUI.java | 46 +++++++++++++++++----- .../java/org/unitConverter/unit/UnitDatabase.java | 37 ++++++++++++++++- src/main/resources/unitsfile.txt | 9 ++++- .../org/unitConverter/unit/UnitDatabaseTest.java | 5 ++- 5 files changed, 96 insertions(+), 16 deletions(-) (limited to 'src/main/resources') diff --git a/src/main/java/org/unitConverter/converterGUI/SearchBoxList.java b/src/main/java/org/unitConverter/converterGUI/SearchBoxList.java index 10ef589..f52d57d 100644 --- a/src/main/java/org/unitConverter/converterGUI/SearchBoxList.java +++ b/src/main/java/org/unitConverter/converterGUI/SearchBoxList.java @@ -101,7 +101,7 @@ final class SearchBoxList extends JPanel { final Comparator defaultOrdering, final boolean caseSensitive) { super(new BorderLayout(), true); - this.itemsToFilter = itemsToFilter; + this.itemsToFilter = new ArrayList<>(itemsToFilter); this.defaultOrdering = defaultOrdering; this.caseSensitive = caseSensitive; @@ -296,6 +296,19 @@ final class SearchBoxList extends JPanel { this.listModel.sort(comparator); } + /** + * Resets the search box list's contents to the provided items, removing any + * old items + * + * @param newItems new items to put in list + * @since 2021-05-22 + */ + public void setItems(Collection newItems) { + this.itemsToFilter.clear(); + this.itemsToFilter.addAll(newItems); + this.reapplyFilter(); + } + /** * Manually updates the search box's item list. * diff --git a/src/main/java/org/unitConverter/converterGUI/UnitConverterGUI.java b/src/main/java/org/unitConverter/converterGUI/UnitConverterGUI.java index ee1bcc3..17ec5f9 100644 --- a/src/main/java/org/unitConverter/converterGUI/UnitConverterGUI.java +++ b/src/main/java/org/unitConverter/converterGUI/UnitConverterGUI.java @@ -216,6 +216,9 @@ final class UnitConverterGUI { private RoundingType roundingType = RoundingType.SIGNIFICANT_DIGITS; + // The "include duplicate units" setting + private boolean includeDuplicateUnits = true; + /** * Creates the presenter. * @@ -291,7 +294,7 @@ final class UnitConverterGUI { }; this.unitNames = new ArrayList<>( - this.database.unitMapPrefixless().keySet()); + this.database.unitMapPrefixless(true).keySet()); this.unitNames.sort(null); // sorts it using Comparable this.prefixNames = new ArrayList<>(this.database.prefixMap().keySet()); @@ -309,10 +312,10 @@ final class UnitConverterGUI { // print out unit counts System.out.printf( "Successfully loaded %d units with %d unit names (%d base units).%n", - new HashSet<>(this.database.unitMapPrefixless().values()).size(), - this.database.unitMapPrefixless().size(), - new HashSet<>(this.database.unitMapPrefixless().values()) - .stream().filter(isFullBase).count()); + this.database.unitMapPrefixless(false).size(), + this.database.unitMapPrefixless(true).size(), + this.database.unitMapPrefixless(false).values().stream() + .filter(isFullBase).count()); } /** @@ -586,6 +589,12 @@ final class UnitConverterGUI { this.toExistenceCondition.setPredicate(unitName -> true); } break; + case "include_duplicates": + this.includeDuplicateUnits = Boolean.valueOf(value); + if (this.view.presenter != null) { + this.view.update(); + } + break; default: System.err.printf("Warning: unrecognized setting \"%s\".", param); @@ -638,6 +647,8 @@ final class UnitConverterGUI { String.format("rounding_type=%s\n", this.roundingType)); writer.write(String.format("prefix_rule=%s\n", this.prefixRule)); writer.write(String.format("one_way=%s\n", this.oneWay)); + writer.write(String.format("include_duplicates=%s\n", + this.includeDuplicateUnits)); } catch (final IOException e) { e.printStackTrace(); this.view.showErrorDialog("I/O Error", @@ -646,6 +657,14 @@ final class UnitConverterGUI { } } + public final void setIncludeDuplicateUnits( + boolean includeDuplicateUnits) { + this.includeDuplicateUnits = includeDuplicateUnits; + + this.view.update(); + this.saveSettings(); + } + /** * Enables or disables one-way conversion. * @@ -760,8 +779,9 @@ final class UnitConverterGUI { * @since 2019-04-14 * @since v0.2.0 */ - private final Set unitNameSet() { - return this.database.unitMapPrefixless().keySet(); + public final Set unitNameSet() { + return this.database.unitMapPrefixless(this.includeDuplicateUnits) + .keySet(); } } @@ -1385,9 +1405,11 @@ final class UnitConverterGUI { .setAnchor(GridBagConstraints.LINE_START).build()); final JCheckBox showAllVariations = new JCheckBox( - "Show Symbols in \"Convert Units\""); - showAllVariations.setSelected(true); - showAllVariations.setEnabled(false); + "Show Duplicates in \"Convert Units\""); + showAllVariations + .setSelected(this.presenter.includeDuplicateUnits); + showAllVariations.addItemListener(e -> this.presenter + .setIncludeDuplicateUnits(e.getStateChange() == 1)); miscPanel.add(showAllVariations, new GridBagBuilder(0, 1) .setAnchor(GridBagConstraints.LINE_START).build()); @@ -1459,6 +1481,10 @@ final class UnitConverterGUI { } public void update() { + this.unitNameList.setItems(this.presenter.unitNameSet()); + this.fromSearch.setItems(this.presenter.fromEntries()); + this.toSearch.setItems(this.presenter.toEntries()); + switch (this.getActivePane()) { case UNIT_CONVERTER: this.fromSearch.updateList(); diff --git a/src/main/java/org/unitConverter/unit/UnitDatabase.java b/src/main/java/org/unitConverter/unit/UnitDatabase.java index 6322fef..673f119 100644 --- a/src/main/java/org/unitConverter/unit/UnitDatabase.java +++ b/src/main/java/org/unitConverter/unit/UnitDatabase.java @@ -27,6 +27,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; +import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; @@ -1096,6 +1097,13 @@ public final class UnitDatabase { private static final Pattern NAME_EXPRESSION = Pattern .compile("(\\S+)\\s+(\\S.*)"); + /** + * Like normal string comparisons, but shorter strings are always less than + * longer strings. + */ + private static final Comparator lengthFirstComparator = Comparator + .comparingInt(String::length).thenComparing(Comparator.naturalOrder()); + /** * The exponent operator * @@ -1149,6 +1157,22 @@ public final class UnitDatabase { throw new IllegalArgumentException("Exponents must be numbers."); } + /** + * @return true if entry represents a removable duplicate entry of unitMap. + * @since 2021-05-22 + */ + private static boolean isRemovableDuplicate(Map unitMap, + Entry entry) { + for (final Entry e : unitMap.entrySet()) { + final String name = e.getKey(); + final Unit value = e.getValue(); + if (lengthFirstComparator.compare(entry.getKey(), name) < 0 + && Objects.equals(unitMap.get(entry.getKey()), value)) + return true; + } + return false; + } + /** * The units in this system, excluding prefixes. * @@ -2015,11 +2039,20 @@ public final class UnitDatabase { } /** + * @param includeDuplicates if true, duplicate units will all exist in the + * map; if false, only one of each unit will exist, + * even if the names are different * @return a map mapping unit names to units, ignoring prefixes * @since 2019-04-13 * @since v0.2.0 */ - public Map unitMapPrefixless() { - return Collections.unmodifiableMap(this.prefixlessUnits); + public Map unitMapPrefixless(boolean includeDuplicates) { + if (includeDuplicates) + return Collections.unmodifiableMap(this.prefixlessUnits); + else + return Collections.unmodifiableMap(ConditionalExistenceCollections + .conditionalExistenceMap(this.prefixlessUnits, + entry -> !isRemovableDuplicate(this.prefixlessUnits, + entry))); } } diff --git a/src/main/resources/unitsfile.txt b/src/main/resources/unitsfile.txt index eafe885..340e8ea 100644 --- a/src/main/resources/unitsfile.txt +++ b/src/main/resources/unitsfile.txt @@ -251,15 +251,22 @@ Calorie kilocalorie Cal Calorie Wh W h -# Extra units to only include in the dimension-based converter +# Extra units to show in the dimension-based converter km km +kilometre km cm cm +centimetre cm mm mm +millimetre mm mg mg +milligram mg mL mL ml ml +millilitre mL kJ kJ +kilojoule kJ MJ MJ +megajoule MJ kWh kWh m/s m / s km/h km / h diff --git a/src/test/java/org/unitConverter/unit/UnitDatabaseTest.java b/src/test/java/org/unitConverter/unit/UnitDatabaseTest.java index f0ba8e5..7f957f3 100644 --- a/src/test/java/org/unitConverter/unit/UnitDatabaseTest.java +++ b/src/test/java/org/unitConverter/unit/UnitDatabaseTest.java @@ -134,7 +134,8 @@ class UnitDatabaseTest { @Test public void testPrefixlessUnitMap() { final UnitDatabase database = new UnitDatabase(); - final Map prefixlessUnits = database.unitMapPrefixless(); + final Map prefixlessUnits = database + .unitMapPrefixless(true); database.addUnit("U", U); database.addUnit("V", V); @@ -223,7 +224,7 @@ class UnitDatabaseTest { database.addPrefix("B", B); database.addPrefix("C", C); - final int NUM_UNITS = database.unitMapPrefixless().size(); + final int NUM_UNITS = database.unitMapPrefixless(true).size(); final int NUM_PREFIXES = database.prefixMap().size(); final Iterator nameIterator = database.unitMap().keySet() -- cgit v1.2.3 From 41b0eda07403db9b09184b79060bcc323dcdc753 Mon Sep 17 00:00:00 2001 From: Adrien Hopkins Date: Sat, 12 Jun 2021 07:36:15 -0500 Subject: Release 0.3.0 --- CHANGELOG.org | 6 ++++-- README.org | 8 ++++---- src/main/java/org/unitConverter/package-info.java | 4 ++-- src/main/resources/about.txt | 4 ++-- 4 files changed, 12 insertions(+), 10 deletions(-) (limited to 'src/main/resources') diff --git a/CHANGELOG.org b/CHANGELOG.org index 6c78f27..883861d 100644 --- a/CHANGELOG.org +++ b/CHANGELOG.org @@ -1,13 +1,15 @@ * Changelog All notable changes in this project will be shown in this file. -** Unreleased +** v0.3.0 - [2021-06-12 Sat] *** Added - Added a simple unit conversion method to the Unit interface - Added a static factory to create nonlinear units to the Unit interface + - Added a settings menu with many settings to change the system's behaviour. Allows you to control the precision settings, prefix repetition, and more. *** Changed + - Changed the unit system again! - You can now use tabs or spaces to separate unit names and their definitions in unit files. - - Unit Converter no longer uses Maven. + - Unit Converter uses Gradle instead of Maven. ** v0.2.0 - [2019-04-14] *** Added - A selection-based unit converter which allows you to select two units, input a value, and convert. diff --git a/README.org b/README.org index 2a6fa95..2625fea 100644 --- a/README.org +++ b/README.org @@ -1,10 +1,10 @@ -* Unit Converter v0.2.0 +* Unit Converter v0.3.0 (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. ** Features - Convert between units and expressions of units - - linear or base unit can use unit prefixes (including non-metric units!) + - linear or base units can use unit prefixes (including non-metric units!) - and prefixes are defined in an editable data file, in a simple and intuitive format. - Viewer and Prefix Viewer which allow you to search through all of the available units and prefixes and learn details about them. - All of SI included in default text file @@ -65,11 +65,11 @@ Nonlinear units cannot: - use prefixes - be defined by unit files -To define a nonlinear unit, make an anonymous inner type (or any other subclass) of AbstractUnit, and define the conversion methods. +To define a nonlinear unit, make an anonymous inner type (or any other subclass) of Unit, and define the conversion methods. You can do this easily using Unit's static methods. ** Unit and Prefix Viewers The unit and prefix viewers can be used to see the available units (without prefixes) and prefixes. Upon opening them, you will see a list of units or prefixes on your left. Using the text box above, the list can be filtered. When a unit is clicked on, details about will be displayed on the right. ** Copyright and Licences -The Unit Converter program is Copyright (C) 2018, 2019 Adrien Hopkins. It is released under the terms of the Aferro GNU General Public License, version 3.0 or any later version published by the Free Software Foundation. A copy of this license should be provided with this program, and a human-readable summary of the very similar GNU General Public License can be found at the following link: https://www.gnu.org/licenses/quick-guide-gplv3.html, although this summary is NOT a replacement for the actual license. +The Unit Converter program is Copyright (C) 2018-2021 Adrien Hopkins. It is released under the terms of the Aferro GNU General Public License, version 3.0 or any later version published by the Free Software Foundation. A copy of this license should be provided with this program, and a human-readable summary of the very similar GNU General Public License can be found at the following link: https://www.gnu.org/licenses/quick-guide-gplv3.html, although this summary is NOT a replacement for the actual license. This document is Copyright (C) 2019 Adrien Hopkins. This document is dual-licensed under the terms of the GNU Free Documentation License and the Creative Commons Attribution-ShareAlike License. More details are in the next paragraphs: diff --git a/src/main/java/org/unitConverter/package-info.java b/src/main/java/org/unitConverter/package-info.java index 23dd165..68a258f 100644 --- a/src/main/java/org/unitConverter/package-info.java +++ b/src/main/java/org/unitConverter/package-info.java @@ -1,5 +1,5 @@ /** - * Copyright (C) 2019 Adrien Hopkins + * Copyright (C) 2019-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 @@ -18,7 +18,7 @@ * A program that converts units. * * @author Adrien Hopkins - * @version v0.2.0 + * @version v0.3.0 * @since 2019-01-25 */ package org.unitConverter; \ No newline at end of file diff --git a/src/main/resources/about.txt b/src/main/resources/about.txt index 1bad9e8..da0ab11 100644 --- a/src/main/resources/about.txt +++ b/src/main/resources/about.txt @@ -1,4 +1,4 @@ -About Unit Converter v0.2.0 +About Unit Converter v0.3.0 Copyright Notice: @@ -9,4 +9,4 @@ for details read the LICENSE file, section 15 This is free software, and you are welcome to redistribute it under certain conditions; for details go to -or read the LICENSE file. \ No newline at end of file +or read the LICENSE file. -- cgit v1.2.3