summaryrefslogtreecommitdiff
path: root/src/main/java/sevenUnitsGUI/Presenter.java
diff options
context:
space:
mode:
Diffstat (limited to 'src/main/java/sevenUnitsGUI/Presenter.java')
-rw-r--r--src/main/java/sevenUnitsGUI/Presenter.java1209
1 files changed, 850 insertions, 359 deletions
diff --git a/src/main/java/sevenUnitsGUI/Presenter.java b/src/main/java/sevenUnitsGUI/Presenter.java
index eba8438..d258e1f 100644
--- a/src/main/java/sevenUnitsGUI/Presenter.java
+++ b/src/main/java/sevenUnitsGUI/Presenter.java
@@ -1,5 +1,5 @@
/**
- * Copyright (C) 2021-2022 Adrien Hopkins
+ * Copyright (C) 2021-2025 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,12 +16,12 @@
*/
package sevenUnitsGUI;
-import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
+import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
@@ -40,12 +40,14 @@ import sevenUnits.unit.BaseUnit;
import sevenUnits.unit.BritishImperial;
import sevenUnits.unit.LinearUnit;
import sevenUnits.unit.LinearUnitValue;
+import sevenUnits.unit.LoadingException;
import sevenUnits.unit.Metric;
import sevenUnits.unit.Unit;
import sevenUnits.unit.UnitDatabase;
import sevenUnits.unit.UnitPrefix;
import sevenUnits.unit.UnitType;
import sevenUnits.unit.UnitValue;
+import sevenUnits.utils.NameSymbol;
import sevenUnits.utils.Nameable;
import sevenUnits.utils.ObjectProduct;
import sevenUnits.utils.UncertainDouble;
@@ -55,9 +57,10 @@ import sevenUnitsGUI.StandardDisplayRules.UncertaintyBased;
/**
* An object that handles interactions between the view and the backend code
- *
+ *
* @author Adrien Hopkins
* @since 2021-12-15
+ * @since v0.4.0
*/
public final class Presenter {
/**
@@ -72,33 +75,25 @@ public final class Presenter {
private static final String DEFAULT_DIMENSIONS_FILEPATH = "/dimensionfile.txt";
/** The default place where exceptions are stored. */
private static final String DEFAULT_EXCEPTIONS_FILEPATH = "/metric_exceptions.txt";
+ /** A Predicate that returns true iff the argument is a full base unit */
+ private static final Predicate<Unit> IS_FULL_BASE = unit -> unit instanceof LinearUnit
+ && ((LinearUnit) unit).isBase();
+ /**
+ * The default locale, used in two situations:
+ * <ul>
+ * <li>If no text is available in your locale, uses text from this locale.
+ * <li>Users are initialized with this locale.
+ * </ul>
+ */
+ static final String DEFAULT_LOCALE = "en";
- private static final Path userConfigDir() {
- if (System.getProperty("os.name").startsWith("Windows")) {
- final String envFolder = System.getenv("LOCALAPPDATA");
- if (envFolder == null || "".equals(envFolder)) {
- return Path.of(System.getenv("USERPROFILE"), "AppData", "Local");
- } else {
- return Path.of(envFolder);
- }
- } else {
- final String envFolder = System.getenv("XDG_CONFIG_HOME");
- if (envFolder == null || "".equals(envFolder)) {
- return Path.of(System.getenv("HOME"), ".config");
- } else {
- return Path.of(envFolder);
- }
- }
- }
-
- /** Gets a Path from a pathname in the config file. */
- private static Path pathFromConfig(String pathname) {
- return CONFIG_FILE.getParent().resolve(pathname);
- }
+ private static final List<String> LOCAL_LOCALES = List.of("en", "fr");
+ private static final Path USER_LOCALES_DIR = userConfigDir()
+ .resolve("SevenUnits").resolve("locales");
/**
* Adds default units and dimensions to a database.
- *
+ *
* @param database database to add to
* @since 2019-04-14
* @since v0.2.0
@@ -125,14 +120,32 @@ public final class Presenter {
database.addDimension("Temperature", Metric.Dimensions.TEMPERATURE);
}
+ private static String displayRuleToString(
+ Function<UncertainDouble, String> numberDisplayRule) {
+ if (numberDisplayRule instanceof FixedDecimals)
+ return String.format("FIXED_DECIMALS %d",
+ ((FixedDecimals) numberDisplayRule).decimalPlaces());
+ if (numberDisplayRule instanceof FixedPrecision)
+ return String.format("FIXED_PRECISION %d",
+ ((FixedPrecision) numberDisplayRule).significantFigures());
+ if (numberDisplayRule instanceof UncertaintyBased)
+ return "UNCERTAINTY_BASED";
+ return numberDisplayRule.toString();
+ }
+
/**
- * @return text in About file
- * @since 2022-02-19
+ * Determines where to wrap {@code toWrap} with a max line length of
+ * {@code maxLineLength}. If no good spot is found, returns -1.
+ *
+ * @since 2024-08-22
+ * @since v1.0.0
*/
- public static final String getAboutText() {
- return Presenter.getLinesFromResource("/about.txt").stream()
- .map(Presenter::withoutComments).collect(Collectors.joining("\n"))
- .replaceAll("\\[VERSION\\]", ProgramInfo.VERSION.toString());
+ private static int findLineSplit(String toWrap, int maxLineLength) {
+ for (var i = maxLineLength - 1; i >= 0; i--) {
+ if (Character.isWhitespace(toWrap.charAt(i)))
+ return i;
+ }
+ return -1;
}
/**
@@ -142,12 +155,13 @@ public final class Presenter {
* @param filename filename to get resource from
* @return contents of file
* @since 2021-03-27
+ * @since v0.3.0
*/
- private static final List<String> getLinesFromResource(String filename) {
+ private static List<String> getLinesFromResource(String filename) {
final List<String> lines = new ArrayList<>();
- try (InputStream stream = inputStream(filename);
- Scanner scanner = new Scanner(stream)) {
+ try (var stream = inputStream(filename);
+ var scanner = new Scanner(stream)) {
while (scanner.hasNextLine()) {
lines.add(scanner.nextLine());
}
@@ -165,16 +179,59 @@ public final class Presenter {
* @param filepath file to use as resource
* @return obtained Path
* @since 2021-03-27
+ * @since v0.3.0
*/
- private static final InputStream inputStream(String filepath) {
+ private static InputStream inputStream(String filepath) {
return Presenter.class.getResourceAsStream(filepath);
}
/**
+ * Convert a linear unit value to a string, where the number is rounded to
+ * the nearest integer.
+ *
+ * @since 2024-08-16
+ * @since v1.0.0
+ */
+ private static String linearUnitValueIntToString(LinearUnitValue uv) {
+ return Long.toString(Math.round(uv.getValueExact())) + " " + uv.getUnit();
+ }
+
+ private static Map.Entry<String, String> parseSettingLine(String line) {
+ final var equalsIndex = line.indexOf('=');
+ if (equalsIndex == -1)
+ throw new IllegalStateException(
+ "Settings file is malformed at line: " + line);
+
+ final var param = line.substring(0, equalsIndex);
+ final var value = line.substring(equalsIndex + 1);
+
+ return Map.entry(param, value);
+ }
+
+ /** Gets a Path from a pathname in the config file. */
+ private static Path pathFromConfig(String pathname) {
+ return CONFIG_FILE.getParent().resolve(pathname);
+ }
+
+ // ====== SETTINGS ======
+
+ private static String searchRuleToString(
+ Function<Map.Entry<String, LinearUnit>, Map<String, LinearUnit>> searchRule) {
+ if (PrefixSearchRule.NO_PREFIXES.equals(searchRule))
+ return "NO_PREFIXES";
+ if (PrefixSearchRule.COMMON_PREFIXES.equals(searchRule))
+ return "COMMON_PREFIXES";
+ if (PrefixSearchRule.ALL_METRIC_PREFIXES.equals(searchRule))
+ return "ALL_METRIC_PREFIXES";
+ return searchRule.toString();
+ }
+
+ /**
* @return true iff a and b have any elements in common
* @since 2022-04-19
+ * @since v0.4.0
*/
- private static final boolean sharesAnyElements(Set<?> a, Set<?> b) {
+ private static boolean sharesAnyElements(Set<?> a, Set<?> b) {
for (final Object e : a) {
if (b.contains(e))
return true;
@@ -182,20 +239,55 @@ public final class Presenter {
return false;
}
+ private static Path userConfigDir() {
+ if (System.getProperty("os.name").startsWith("Windows")) {
+ final var envFolder = System.getenv("LOCALAPPDATA");
+ if (envFolder == null || "".equals(envFolder))
+ return Path.of(System.getenv("USERPROFILE"), "AppData", "Local");
+ return Path.of(envFolder);
+ }
+ final var envFolder = System.getenv("XDG_CONFIG_HOME");
+ if (envFolder == null || "".equals(envFolder))
+ return Path.of(System.getenv("HOME"), ".config");
+ return Path.of(envFolder);
+ }
+
/**
* @return {@code line} with any comments removed.
* @since 2021-03-13
+ * @since v0.3.0
*/
- private static final String withoutComments(String line) {
- final int index = line.indexOf('#');
+ private static String withoutComments(String line) {
+ final var index = line.indexOf('#');
return index == -1 ? line : line.substring(0, index);
}
- // ====== SETTINGS ======
-
/**
- * The view that this presenter communicates with
+ * Wraps a string, ensuring no line is longer than {@code maxLineLength}.
+ *
+ * @since 2024-08-22
+ * @since v1.0.0
*/
+ private static String wrapString(String toWrap, int maxLineLength) {
+ final var wrapped = new StringBuilder(toWrap.length());
+ var remaining = toWrap;
+ while (remaining.length() > maxLineLength) {
+ final var spot = findLineSplit(toWrap, maxLineLength);
+ if (spot == -1) {
+ wrapped.append(remaining.substring(0, maxLineLength));
+ wrapped.append("-\n");
+ remaining = remaining.substring(maxLineLength).stripLeading();
+ } else {
+ wrapped.append(remaining.substring(0, spot));
+ wrapped.append("\n");
+ remaining = remaining.substring(spot + 1).stripLeading();
+ }
+ }
+ wrapped.append(remaining);
+ return wrapped.toString();
+ }
+
+ /** The view that this presenter communicates with */
private final View view;
/**
@@ -238,6 +330,12 @@ public final class Presenter {
*/
private final Set<String> metricExceptions;
+ /** maps locale names (e.g. 'en') to key-text maps */
+ final Map<String, Map<String, String>> locales;
+
+ /** name of locale in locales to use */
+ String userLocale;
+
/**
* If this is true, views that show units as a list will have metric units
* removed from the From unit list and imperial/USC units removed from the To
@@ -252,65 +350,61 @@ public final class Presenter {
private boolean showDuplicates = false;
/**
+ * The default unit, prefix, dimension and exception data will only be loaded
+ * if this variable is true.
+ */
+ private boolean useDefaultDatafiles = true;
+
+ /** Custom unit datafiles that will be loaded by {@link #reloadData} */
+ private final Set<Path> customUnitFiles = new HashSet<>();
+ /** Custom dimension datafiles that will be loaded by {@link #reloadData} */
+ private final Set<Path> customDimensionFiles = new HashSet<>();
+ /** Custom exception datafiles that will be loaded by {@link #reloadData} */
+ private final Set<Path> customExceptionFiles = new HashSet<>();
+
+ /**
* Creates a Presenter
- *
+ *
* @param view the view that this presenter communicates with
* @since 2021-12-15
+ * @since v0.4.0
*/
public Presenter(View view) {
this.view = view;
this.database = new UnitDatabase();
- addDefaults(this.database);
+ this.metricExceptions = new HashSet<>();
- // 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 = 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);
- }
+ this.locales = this.loadLocales();
+ this.userLocale = DEFAULT_LOCALE;
// set default settings temporarily
if (Files.exists(CONFIG_FILE)) {
this.loadSettings(CONFIG_FILE);
}
- // a Predicate that returns true iff the argument is a full base unit
- final Predicate<Unit> isFullBase = unit -> unit instanceof LinearUnit
- && ((LinearUnit) unit).isBase();
+ this.reloadData();
// print out unit counts
- System.out.printf(
- "Successfully loaded %d units with %d unit names (%d base units).%n",
- this.database.unitMapPrefixless(false).size(),
- this.database.unitMapPrefixless(true).size(),
- this.database.unitMapPrefixless(false).values().stream()
- .filter(isFullBase).count());
+ System.out.println(this.loadStatMsg());
+ }
+
+ private void addLocaleFile(Map<String, Map<String, String>> locales,
+ Path file) throws IOException {
+ final Map<String, String> locale = new HashMap<>();
+ final var fileName = file.getName(file.getNameCount() - 1).toString();
+ final var localeName = fileName.substring(0, fileName.length() - 4);
+ try (var lines = Files.lines(file)) {
+ lines.forEach(line -> this.addLocaleLine(locale, line));
+ }
+ locales.put(localeName, locale);
+ }
+
+ private void addLocaleLine(Map<String, String> locale, String line) {
+ final var parts = line.split("=", 2);
+ if (parts.length < 2)
+ return;
+
+ locale.put(parts[0], parts[1]);
}
/**
@@ -319,201 +413,387 @@ public final class Presenter {
* @param e entry
* @return stream of entries, ready for flat-mapping
* @since 2022-07-06
+ * @since v0.4.0
*/
- private final Stream<Map.Entry<String, Unit>> applySearchRule(
+ private Stream<Map.Entry<String, Unit>> applySearchRule(
Map.Entry<String, Unit> e) {
- final Unit u = e.getValue();
+ final var u = e.getValue();
if (u instanceof LinearUnit) {
- final String name = e.getKey();
+ final var name = e.getKey();
final Map.Entry<String, LinearUnit> linearEntry = Map.entry(name,
(LinearUnit) u);
return this.searchRule.apply(linearEntry).entrySet().stream().map(
entry -> Map.entry(entry.getKey(), (Unit) entry.getValue()));
- } else
- return Stream.of(e);
+ }
+ return Stream.of(e);
}
/**
* Converts from the view's input expression to its output expression.
* Displays an error message if any of the required fields are invalid.
- *
+ *
* @throws UnsupportedOperationException if the view does not support
* expression-based conversion (does
* not implement
* {@link ExpressionConversionView})
* @since 2021-12-15
+ * @since v0.4.0
*/
public void convertExpressions() {
- if (this.view instanceof ExpressionConversionView) {
- final ExpressionConversionView xcview = (ExpressionConversionView) this.view;
+ if (!(this.view instanceof ExpressionConversionView))
+ throw new UnsupportedOperationException(
+ "This function can only be called when the view is an ExpressionConversionView");
+ final var xcview = (ExpressionConversionView) this.view;
- final String fromExpression = xcview.getFromExpression();
- final String toExpression = xcview.getToExpression();
+ final var fromExpression = xcview.getFromExpression();
+ final var toExpression = xcview.getToExpression();
- // expressions must not be empty
- if (fromExpression.isEmpty()) {
- this.view.showErrorMessage("Parse Error",
- "Please enter a unit expression in the From: box.");
- return;
- }
- if (toExpression.isEmpty()) {
- this.view.showErrorMessage("Parse Error",
- "Please enter a unit expression in the To: box.");
- return;
- }
+ // expressions must not be empty
+ if (fromExpression.isEmpty()) {
+ this.view.showErrorMessage("Parse Error",
+ "Please enter a unit expression in the From: box.");
+ return;
+ }
+ if (toExpression.isEmpty()) {
+ this.view.showErrorMessage("Parse Error",
+ "Please enter a unit expression in the To: box.");
+ return;
+ }
- // evaluate expressions
- final LinearUnitValue from;
- final Unit to;
- try {
- from = this.database.evaluateUnitExpression(fromExpression);
- } catch (final IllegalArgumentException | NoSuchElementException e) {
- this.view.showErrorMessage("Parse Error",
- "Could not recognize text in From entry: " + e.getMessage());
- return;
- }
+ final Optional<UnitConversionRecord> uc;
+ if (this.database.containsUnitSetName(toExpression)) {
+ uc = this.convertExpressionToNamedMultiUnit(fromExpression,
+ toExpression);
+ } else if (toExpression.contains(";")) {
+ final var toExpressions = toExpression.split(";");
+ uc = this.convertExpressionToMultiUnit(fromExpression, toExpressions);
+ } else {
+ uc = this.convertExpressionToExpression(fromExpression, toExpression);
+ }
+
+ uc.ifPresent(xcview::showExpressionConversionOutput);
+ }
+
+ /**
+ * Converts a unit expression to another expression.
+ *
+ * If an error happened, it is shown to the view and Optional.empty() is
+ * returned.
+ *
+ * @since 2024-08-15
+ * @since v1.0.0
+ */
+ private Optional<UnitConversionRecord> convertExpressionToExpression(
+ String fromExpression, String toExpression) {
+ // evaluate expressions
+ final LinearUnitValue from;
+ final Unit to;
+ try {
+ from = this.database.evaluateUnitExpression(fromExpression);
+ } catch (final IllegalArgumentException | NoSuchElementException e) {
+ this.view.showErrorMessage("Parse Error",
+ "Could not recognize text in From entry: " + e.getMessage());
+ return Optional.empty();
+ }
+ try {
+ to = this.database.getUnitFromExpression(toExpression);
+ } catch (final IllegalArgumentException | NoSuchElementException e) {
+ this.view.showErrorMessage("Parse Error",
+ "Could not recognize text in To entry: " + e.getMessage());
+ return Optional.empty();
+ }
+
+ // convert and show output
+ if (!from.getUnit().canConvertTo(to)) {
+ this.view.showErrorMessage("Conversion Error",
+ "Cannot convert between \"" + fromExpression + "\" and \""
+ + toExpression + "\".");
+ return Optional.empty();
+ }
+ 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 var value = from.asUnitValue().convertTo(to).getValue();
+ uncertainValue = UncertainDouble.of(value, 0);
+ }
+
+ final var uc = UnitConversionRecord.valueOf(fromExpression, toExpression,
+ "", this.numberDisplayRule.apply(uncertainValue));
+ return Optional.of(uc);
+
+ }
+
+ /**
+ * Convert an expression to a MultiUnit. If an error happened, it is shown to
+ * the view and Optional.empty() is returned.
+ *
+ * @since 2024-08-15
+ * @since v1.0.0
+ */
+ private Optional<UnitConversionRecord> convertExpressionToMultiUnit(
+ String fromExpression, String[] toExpressions) {
+ final LinearUnitValue from;
+ try {
+ from = this.database.evaluateUnitExpression(fromExpression);
+ } catch (final IllegalArgumentException | NoSuchElementException e) {
+ this.view.showErrorMessage("Parse Error",
+ "Could not recognize text in From entry: " + e.getMessage());
+ return Optional.empty();
+ }
+
+ final List<LinearUnit> toUnits = new ArrayList<>(toExpressions.length);
+ for (final String toExpression : toExpressions) {
try {
- to = this.database.getUnitFromExpression(toExpression);
+ final var toI = this.database
+ .getUnitFromExpression(toExpression.trim());
+ if (!(toI instanceof LinearUnit)) {
+ this.view.showErrorMessage("Unit Type Error",
+ "Units separated by ';' must be linear; " + toI
+ + " is not.");
+ return Optional.empty();
+ }
+ toUnits.add((LinearUnit) toI);
} catch (final IllegalArgumentException | NoSuchElementException e) {
this.view.showErrorMessage("Parse Error",
"Could not recognize text in To entry: " + e.getMessage());
- return;
+ return Optional.empty();
}
+ }
+
+ final List<LinearUnitValue> toValues;
+ try {
+ toValues = from.convertToMultiple(toUnits);
+ } catch (final IllegalArgumentException e) {
+ this.view.showErrorMessage("Unit Error",
+ "Invalid units separated by ';': " + e.getMessage());
+ return Optional.empty();
+ }
- // convert and show output
- if (from.getUnit().canConvertTo(to)) {
- final UncertainDouble uncertainValue;
+ final var toExpression = this.linearUnitValueSumToString(toValues);
+ return Optional.of(
+ UnitConversionRecord.valueOf(fromExpression, toExpression, "", ""));
+ }
- // 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);
- }
+ /**
+ * Convert an expression to a MultiUnit with a name from the database. If an
+ * error happened, it is shown to the view and Optional.empty() is returned.
+ *
+ * @since 2024-08-15
+ * @since v1.0.0
+ */
+ private Optional<UnitConversionRecord> convertExpressionToNamedMultiUnit(
+ String fromExpression, String toName) {
+ final LinearUnitValue from;
+ try {
+ from = this.database.evaluateUnitExpression(fromExpression);
+ } catch (final IllegalArgumentException | NoSuchElementException e) {
+ this.view.showErrorMessage("Parse Error",
+ "Could not recognize text in From entry: " + e.getMessage());
+ return Optional.empty();
+ }
- final UnitConversionRecord uc = UnitConversionRecord.valueOf(
- fromExpression, toExpression, "",
- this.numberDisplayRule.apply(uncertainValue));
- xcview.showExpressionConversionOutput(uc);
- } else {
- this.view.showErrorMessage("Conversion Error",
- "Cannot convert between \"" + fromExpression + "\" and \""
- + toExpression + "\".");
- }
+ final var toUnits = this.database.getUnitSet(toName);
+ final List<LinearUnitValue> toValues;
+ try {
+ toValues = from.convertToMultiple(toUnits);
+ } catch (final IllegalArgumentException e) {
+ this.view.showErrorMessage("Unit Error",
+ "Invalid units separated by ';': " + e.getMessage());
+ return Optional.empty();
+ }
- } else
- throw new UnsupportedOperationException(
- "This function can only be called when the view is an ExpressionConversionView");
+ final var toExpression = this.linearUnitValueSumToString(toValues);
+ return Optional.of(
+ UnitConversionRecord.valueOf(fromExpression, toExpression, "", ""));
}
/**
* Converts from the view's input unit to its output unit. Displays an error
* message if any of the required fields are invalid.
- *
+ *
* @throws UnsupportedOperationException if the view does not support
* unit-based conversion (does not
* implement
* {@link UnitConversionView})
* @since 2021-12-15
+ * @since v0.4.0
*/
public void convertUnits() {
- if (this.view instanceof UnitConversionView) {
- final UnitConversionView ucview = (UnitConversionView) this.view;
+ if (!(this.view instanceof UnitConversionView))
+ throw new UnsupportedOperationException(
+ "This function can only be called when the view is a UnitConversionView.");
+ final var ucview = (UnitConversionView) this.view;
+
+ final var fromUnitOptional = ucview.getFromSelection();
+ final var toUnitOptional = ucview.getToSelection();
+ final var inputValueString = ucview.getInputValue();
+
+ // extract values from optionals
+ final String fromUnitString, toUnitString;
+ if (!fromUnitOptional.isPresent()) {
+ this.view.showErrorMessage("Unit Selection Error",
+ "Please specify a From unit");
+ return;
+ }
+ fromUnitString = fromUnitOptional.orElseThrow();
+ if (!toUnitOptional.isPresent()) {
+ this.view.showErrorMessage("Unit Selection Error",
+ "Please specify a To unit");
+ return;
+ }
+ toUnitString = toUnitOptional.orElseThrow();
- final Optional<String> fromUnitOptional = ucview.getFromSelection();
- final Optional<String> toUnitOptional = ucview.getToSelection();
- final String inputValueString = ucview.getInputValue();
+ // convert strings to data, checking if anything is invalid
+ final Unit fromUnit;
+ final UncertainDouble uncertainValue;
- // extract values from optionals
- final String fromUnitString, toUnitString;
- if (fromUnitOptional.isPresent()) {
- fromUnitString = fromUnitOptional.orElseThrow();
- } else {
- this.view.showErrorMessage("Unit Selection Error",
- "Please specify a From unit");
- return;
- }
- if (toUnitOptional.isPresent()) {
- toUnitString = toUnitOptional.orElseThrow();
- } else {
- this.view.showErrorMessage("Unit Selection Error",
- "Please specify a To unit");
- return;
- }
-
- // convert strings to data, checking if anything is invalid
- final Unit fromUnit, toUnit;
- final UncertainDouble uncertainValue;
-
- if (this.database.containsUnitName(fromUnitString)) {
- fromUnit = this.database.getUnit(fromUnitString);
- } else
- throw this.viewError("Nonexistent From unit: %s", fromUnitString);
- if (this.database.containsUnitName(toUnitString)) {
- toUnit = this.database.getUnit(toUnitString);
- } else
- throw this.viewError("Nonexistent To unit: %s", toUnitString);
- try {
- uncertainValue = UncertainDouble
- .fromRoundedString(inputValueString);
- } catch (final NumberFormatException e) {
- this.view.showErrorMessage("Value Error",
- "Invalid value " + inputValueString);
- return;
- }
+ if (!this.database.containsUnitName(fromUnitString))
+ throw this.viewError("Nonexistent From unit: %s", fromUnitString);
+ fromUnit = this.database.getUnit(fromUnitString);
+ try {
+ uncertainValue = UncertainDouble.fromRoundedString(inputValueString);
+ } catch (final NumberFormatException e) {
+ this.view.showErrorMessage("Value Error",
+ "Invalid value " + inputValueString);
+ return;
+ }
+ if (this.database.containsUnitName(toUnitString)) {
+ final var toUnit = this.database.getUnit(toUnitString);
+ ucview.showUnitConversionOutput(
+ this.convertUnitToUnit(fromUnitString, toUnitString,
+ inputValueString, fromUnit, toUnit, uncertainValue));
+ } else if (this.database.containsUnitSetName(toUnitString)) {
+ final var toMulti = this.database.getUnitSet(toUnitString);
+ ucview.showUnitConversionOutput(this.convertUnitToMulti(fromUnitString,
+ inputValueString, fromUnit, toMulti, uncertainValue));
+ } else
+ throw this.viewError("Nonexistent To unit: %s", toUnitString);
+ }
+ private UnitConversionRecord convertUnitToMulti(String fromUnitString,
+ String inputValueString, Unit fromUnit, List<LinearUnit> toMulti,
+ UncertainDouble uncertainValue) {
+ for (final LinearUnit toUnit : toMulti) {
if (!fromUnit.canConvertTo(toUnit))
throw this.viewError("Could not convert between %s and %s",
fromUnit, 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);
+ final LinearUnitValue initValue;
+ if (fromUnit instanceof LinearUnit) {
+ final var fromLinear = (LinearUnit) fromUnit;
+ initValue = LinearUnitValue.of(fromLinear, uncertainValue);
+ } else {
+ initValue = UnitValue.of(fromUnit, uncertainValue.value())
+ .convertToBase(NameSymbol.EMPTY);
+ }
- outputValueString = this.numberDisplayRule
- .apply(UncertainDouble.of(converted.getValue(), 0));
- }
+ final var converted = initValue.convertToMultiple(toMulti);
+ final var toExpression = this.linearUnitValueSumToString(converted);
+ return UnitConversionRecord.valueOf(fromUnitString, toExpression,
+ inputValueString, "");
- ucview.showUnitConversionOutput(
- UnitConversionRecord.valueOf(fromUnitString, toUnitString,
- inputValueString, outputValueString));
- } else
- throw new UnsupportedOperationException(
- "This function can only be called when the view is a UnitConversionView.");
+ }
+
+ private UnitConversionRecord convertUnitToUnit(String fromUnitString,
+ String toUnitString, String inputValueString, Unit fromUnit,
+ Unit toUnit, UncertainDouble uncertainValue) {
+ if (!fromUnit.canConvertTo(toUnit))
+ throw this.viewError("Could not convert between %s and %s", fromUnit,
+ 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 var fromLinear = (LinearUnit) fromUnit;
+ final var toLinear = (LinearUnit) toUnit;
+ final var initialValue = LinearUnitValue.of(fromLinear,
+ uncertainValue);
+ final var converted = initialValue.convertTo(toLinear);
+
+ outputValueString = this.numberDisplayRule.apply(converted.getValue());
+ } else {
+ final var initialValue = UnitValue.of(fromUnit,
+ uncertainValue.value());
+ final var converted = initialValue.convertTo(toUnit);
+
+ outputValueString = this.numberDisplayRule
+ .apply(UncertainDouble.of(converted.getValue(), 0));
+ }
+
+ return UnitConversionRecord.valueOf(fromUnitString, toUnitString,
+ inputValueString, outputValueString);
}
/**
* @return true iff duplicate units are shown in unit lists
* @since 2022-03-30
+ * @since v0.4.0
*/
public boolean duplicatesShown() {
return this.showDuplicates;
}
+ private String formatAboutText(Stream<String> rawLines) {
+ return rawLines.map(Presenter::withoutComments)
+ .collect(Collectors.joining("\n"))
+ .replaceAll("\\[VERSION\\]", ProgramInfo.VERSION.toString())
+ .replaceAll("\\[LOADSTATS\\]", wrapString(this.loadStatMsg(), 72));
+ }
+
+ /**
+ * @return text in About file
+ * @since 2022-02-19
+ * @since v0.4.0
+ */
+ public String getAboutText() {
+ final var customFilepath = Presenter
+ .pathFromConfig("about/" + this.userLocale + ".txt");
+ if (Files.exists(customFilepath)) {
+ try (var lines = Files.lines(customFilepath)) {
+ return this.formatAboutText(lines);
+ } catch (final IOException e) {
+ final var filename = String.format("/about/%s.txt",
+ this.userLocale);
+ return this.formatAboutText(
+ Presenter.getLinesFromResource(filename).stream());
+ }
+ }
+ if (LOCAL_LOCALES.contains(this.userLocale)) {
+ final var filename = String.format("/about/%s.txt", this.userLocale);
+ return this.formatAboutText(
+ Presenter.getLinesFromResource(filename).stream());
+ }
+ final var filename = String.format("/about/%s.txt", DEFAULT_LOCALE);
+ return this
+ .formatAboutText(Presenter.getLinesFromResource(filename).stream());
+
+ }
+
+ /**
+ * @return set of all locales available to select
+ * @since 2025-02-21
+ * @since v1.0.0
+ */
+ public Set<String> getAvailableLocales() {
+ return this.locales.keySet();
+ }
+
/**
* Gets a name for this dimension using the database
*
* @param dimension dimension to name
* @return name of dimension
* @since 2022-04-16
+ * @since v0.4.0
*/
- final String getDimensionName(ObjectProduct<BaseDimension> dimension) {
+ String getDimensionName(ObjectProduct<BaseDimension> dimension) {
// find this dimension in the database and get its name
// if it isn't there, use the dimension's toString instead
return this.database.dimensionMap().values().stream()
@@ -522,9 +802,24 @@ public final class Presenter {
}
/**
+ * Gets the correct text for a provided ID. If this text is available in the
+ * user's locale, that text is provided. Otherwise, text is taken from the
+ * system default locale {@link #DEFAULT_LOCALE}.
+ *
+ * @param textID ID of text to get (used in locale files)
+ * @return text to be displayed
+ */
+ public String getLocalizedText(String textID) {
+ final var userLocale = this.locales.get(this.userLocale);
+ final var defaultLocale = this.locales.get(DEFAULT_LOCALE);
+ return userLocale.getOrDefault(textID, defaultLocale.get(textID));
+ }
+
+ /**
* @return the rule that is used by this presenter to convert numbers into
* strings
* @since 2022-04-10
+ * @since v0.4.0
*/
public Function<UncertainDouble, String> getNumberDisplayRule() {
return this.numberDisplayRule;
@@ -534,6 +829,7 @@ public final class Presenter {
* @return the rule that is used by this presenter to convert strings into
* numbers
* @since 2022-04-10
+ * @since v0.4.0
*/
@SuppressWarnings("unused") // not implemented yet
private Function<String, UncertainDouble> getNumberParsingRule() {
@@ -543,6 +839,7 @@ public final class Presenter {
/**
* @return the rule that determines whether a set of prefixes is valid
* @since 2022-04-19
+ * @since v0.4.0
*/
public Predicate<List<UnitPrefix>> getPrefixRepetitionRule() {
return this.prefixRepetitionRule;
@@ -551,6 +848,7 @@ public final class Presenter {
/**
* @return the rule that determines which units are prefixed
* @since 2022-07-08
+ * @since v0.4.0
*/
public Function<Map.Entry<String, LinearUnit>, Map<String, LinearUnit>> getSearchRule() {
return this.searchRule;
@@ -559,6 +857,7 @@ public final class Presenter {
/**
* @return a search rule that shows all single prefixes
* @since 2022-07-08
+ * @since v0.4.0
*/
public Function<Map.Entry<String, LinearUnit>, Map<String, LinearUnit>> getUniversalSearchRule() {
return PrefixSearchRule.getCoherentOnlyRule(
@@ -566,19 +865,49 @@ public final class Presenter {
}
/**
+ * @return user's selected locale
+ * @since 2025-02-21
+ * @since v1.0.0
+ */
+ public String getUserLocale() {
+ return this.userLocale;
+ }
+
+ /**
* @return the view associated with this presenter
* @since 2022-04-19
+ * @since v0.4.0
*/
public View getView() {
return this.view;
}
/**
+ * Accepts a list of errors. If that list is non-empty, prints an error
+ * message and alerts the user.
+ *
+ * @since 2024-08-22
+ * @since v1.0.0
+ */
+ private void handleLoadErrors(List<LoadingException> errors) {
+ if (!errors.isEmpty()) {
+ final var errorMessage = String.format(
+ "%d error(s) happened while loading file:\n%s\n", errors.size(),
+ errors.stream().map(Throwable::getMessage)
+ .collect(Collectors.joining("\n")));
+ System.err.print(errorMessage);
+ this.view.showErrorMessage(errors.size() + "Loading Error(s)",
+ errorMessage);
+ }
+ }
+
+ /**
* @return whether or not the provided unit is semi-metric (i.e. an
* exception)
* @since 2022-04-16
+ * @since v0.4.0
*/
- final boolean isSemiMetric(Unit u) {
+ boolean isSemiMetric(Unit u) {
// determine if u is an exception
final var primaryName = u.getPrimaryName();
final var symbol = u.getSymbol();
@@ -590,27 +919,127 @@ public final class Presenter {
}
/**
+ * Convert a list of LinearUnitValues that you would get from a unit-set
+ * conversion to a string. All but the last have their numbers rendered as
+ * integers, since they are always integers. The last one follows the usual
+ * number display rule.
+ *
+ * @since 2024-08-16
+ * @since v1.0.0
+ */
+ private String linearUnitValueSumToString(List<LinearUnitValue> values) {
+ final var integerPart = values.subList(0, values.size() - 1).stream()
+ .map(Presenter::linearUnitValueIntToString)
+ .collect(Collectors.joining(" + "));
+ final var last = values.get(values.size() - 1);
+ return integerPart + " + " + this.numberDisplayRule.apply(last.getValue())
+ + " " + last.getUnit();
+ }
+
+ /** Load units, prefixes and dimensions from the default files. */
+ private void loadDefaultData() {
+ // load units and prefixes
+ try (final var units = inputStream(DEFAULT_UNITS_FILEPATH)) {
+ this.handleLoadErrors(this.database.loadUnitsFromStream(units));
+ } catch (final IOException e) {
+ throw new AssertionError("Loading of unitsfile.txt failed.", e);
+ }
+
+ // load dimensions
+ try (final var dimensions = inputStream(DEFAULT_DIMENSIONS_FILEPATH)) {
+ this.handleLoadErrors(
+ this.database.loadDimensionsFromStream(dimensions));
+ } catch (final IOException e) {
+ throw new AssertionError("Loading of dimensionfile.txt failed.", e);
+ }
+
+ // load metric exceptions
+ try {
+ try (var exceptions = inputStream(DEFAULT_EXCEPTIONS_FILEPATH);
+ var scanner = new Scanner(exceptions)) {
+ while (scanner.hasNextLine()) {
+ final var 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);
+ }
+ }
+
+ private void loadExceptionFile(Path exceptionFile) {
+ try (var lines = Files.lines(exceptionFile)) {
+ lines.map(Presenter::withoutComments)
+ .forEach(this.metricExceptions::add);
+ } catch (final IOException e) {
+ this.view.showErrorMessage("File Load Error",
+ "Error loading configured metric exception file \""
+ + exceptionFile + "\": " + e.getLocalizedMessage());
+ }
+ }
+
+ /**
+ * Loads all available locales, including custom ones, into a map.
+ *
+ * @return map containing locales
+ */
+ private Map<String, Map<String, String>> loadLocales() {
+ final Map<String, Map<String, String>> locales = new HashMap<>();
+ for (final String localeName : LOCAL_LOCALES) {
+ final Map<String, String> locale = new HashMap<>();
+ final var filename = "/locales/" + localeName + ".txt";
+ getLinesFromResource(filename)
+ .forEach(line -> this.addLocaleLine(locale, line));
+ locales.put(localeName, locale);
+ }
+
+ if (Files.exists(USER_LOCALES_DIR)) {
+ try (var files = Files.list(USER_LOCALES_DIR)) {
+ files.forEach(localeFile -> {
+ try {
+ this.addLocaleFile(locales, localeFile);
+ } catch (final IOException e) {
+ e.printStackTrace();
+ }
+ });
+ } catch (final IOException e) {
+ e.printStackTrace();
+ }
+ }
+ return locales;
+ }
+
+ /**
* 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
+ * @since v0.4.0
*/
void loadSettings(Path settingsFile) {
- for (Map.Entry<String, String> setting : settingsFromFile(settingsFile)) {
- final String value = setting.getValue();
+ this.customDimensionFiles.clear();
+ this.customExceptionFiles.clear();
+ this.customUnitFiles.clear();
+
+ for (final Map.Entry<String, String> setting : this
+ .settingsFromFile(settingsFile)) {
+ final var value = setting.getValue();
switch (setting.getKey()) {
// set manually to avoid the unnecessary saving of the non-manual
// methods
case "custom_dimension_file":
- this.database.loadDimensionFile(pathFromConfig(value));
+ this.customDimensionFiles.add(pathFromConfig(value));
break;
case "custom_exception_file":
- this.loadExceptionFile(pathFromConfig(value));
+ this.customExceptionFiles.add(pathFromConfig(value));
break;
case "custom_unit_file":
- this.database.loadUnitsFile(pathFromConfig(value));
+ this.customUnitFiles.add(pathFromConfig(value));
break;
case "number_display_rule":
this.setDisplayRuleFromString(value);
@@ -621,14 +1050,28 @@ public final class Presenter {
this.database.setPrefixRepetitionRule(this.prefixRepetitionRule);
break;
case "one_way":
- this.oneWayConversionEnabled = Boolean.valueOf(value);
+ this.oneWayConversionEnabled = Boolean.parseBoolean(value);
break;
case "include_duplicates":
- this.showDuplicates = Boolean.valueOf(value);
+ this.showDuplicates = Boolean.parseBoolean(value);
break;
case "search_prefix_rule":
this.setSearchRuleFromString(value);
break;
+ case "use_default_datafiles":
+ this.useDefaultDatafiles = Boolean.parseBoolean(value);
+ break;
+ case "locale":
+ if (this.locales.containsKey(value)) {
+ this.userLocale = value;
+ } else {
+ System.err.printf("Warning: unrecognized locale \"%s\".%n",
+ value);
+ this.view.showErrorMessage("Unrecognized Locale",
+ "Could not find locale \"" + value
+ + "\", resetting to default.");
+ }
+ break;
default:
System.err.printf("Warning: unrecognized setting \"%s\".%n",
setting.getKey());
@@ -641,86 +1084,38 @@ public final class Presenter {
}
}
- private List<Map.Entry<String, String>> settingsFromFile(Path settingsFile) {
- try (Stream<String> lines = Files.lines(settingsFile)) {
- return lines.map(Presenter::withoutComments)
- .filter(line -> !line.isBlank()).map(Presenter::parseSettingLine)
- .toList();
- } catch (final IOException e) {
- this.view.showErrorMessage("Settings Loading Error",
- "Error loading settings file. Using default settings.");
- return null;
- }
- }
-
- private static Map.Entry<String, String> parseSettingLine(String line) {
- final int equalsIndex = line.indexOf('=');
- if (equalsIndex == -1)
- throw new IllegalStateException(
- "Settings file is malformed at line: " + line);
-
- final String param = line.substring(0, equalsIndex);
- final String value = line.substring(equalsIndex + 1);
-
- return Map.entry(param, value);
- }
-
- private void setSearchRuleFromString(String ruleString) {
- switch (ruleString) {
- case "NO_PREFIXES":
- this.searchRule = PrefixSearchRule.NO_PREFIXES;
- break;
- case "COMMON_PREFIXES":
- this.searchRule = PrefixSearchRule.COMMON_PREFIXES;
- break;
- case "ALL_METRIC_PREFIXES":
- this.searchRule = PrefixSearchRule.ALL_METRIC_PREFIXES;
- break;
- default:
- System.err.printf(
- "Warning: unrecognized value for search_prefix_rule: %s\n",
- ruleString);
- }
- }
-
- private void setDisplayRuleFromString(String ruleString) {
- String[] tokens = ruleString.split(" ");
- switch (tokens[0]) {
- case "FIXED_DECIMALS":
- final int decimals = Integer.parseInt(tokens[1]);
- this.numberDisplayRule = StandardDisplayRules.fixedDecimals(decimals);
- break;
- case "FIXED_PRECISION":
- final int sigDigs = Integer.parseInt(tokens[1]);
- this.numberDisplayRule = StandardDisplayRules.fixedPrecision(sigDigs);
- break;
- case "UNCERTAINTY_BASED":
- this.numberDisplayRule = StandardDisplayRules.uncertaintyBased();
- break;
- default:
- this.numberDisplayRule = StandardDisplayRules
- .getStandardRule(ruleString);
- break;
- }
- }
-
- private void loadExceptionFile(Path exceptionFile) {
- try (Stream<String> lines = Files.lines(exceptionFile)) {
- lines.map(Presenter::withoutComments)
- .forEach(this.metricExceptions::add);
- } catch (IOException e) {
- this.view.showErrorMessage("File Load Error",
- "Error loading configured metric exception file \""
- + exceptionFile + "\": " + e.getLocalizedMessage());
- }
+ /**
+ * @return a message showing how much stuff has been loaded
+ * @since 2024-08-22
+ * @since v1.0.0
+ */
+ private String loadStatMsg() {
+ return this.getLocalizedText("load_stat_msg")
+ .replace("[u]",
+ Integer.toString(
+ this.database.unitMapPrefixless(false).size()))
+ .replace("[un]",
+ Integer
+ .toString(this.database.unitMapPrefixless(true).size()))
+ .replace("[b]",
+ Long.toString(this.database.unitMapPrefixless(false).values()
+ .stream().filter(IS_FULL_BASE).count()))
+ .replace("[p]",
+ Integer.toString(this.database.prefixMap(false).size()))
+ .replace("[pn]",
+ Integer.toString(this.database.prefixMap(true).size()))
+ .replace("[s]", Integer.toString(this.database.unitSetMap().size()))
+ .replace("[d]",
+ Integer.toString(this.database.dimensionMap().size()));
}
/**
* @return true iff the One-Way Conversion feature is available (views that
* show units as a list will have metric units removed from the From
* unit list and imperial/USC units removed from the To unit list)
- *
+ *
* @since 2022-03-30
+ * @since v0.4.0
*/
public boolean oneWayConversionEnabled() {
return this.oneWayConversionEnabled;
@@ -730,22 +1125,23 @@ public final class Presenter {
* Completes creation of the presenter. This part of the initialization
* depends on the view's functions, so it cannot be run if the components
* they depend on are not created yet.
- *
+ *
* @since 2022-02-26
+ * @since v0.4.0
*/
public void postViewInitialize() {
// unit conversion specific stuff
if (this.view instanceof UnitConversionView) {
- final UnitConversionView ucview = (UnitConversionView) this.view;
+ final var ucview = (UnitConversionView) this.view;
ucview.setDimensionNames(this.database.dimensionMap().keySet());
}
this.updateView();
+ this.view.updateText();
}
void prefixSelected() {
- final Optional<String> selectedPrefixName = this.view
- .getViewedPrefixName();
+ final var selectedPrefixName = this.view.getViewedPrefixName();
final Optional<UnitPrefix> selectedPrefix = selectedPrefixName
.map(name -> this.database.containsPrefixName(name)
? this.database.getPrefix(name)
@@ -755,19 +1151,37 @@ public final class Presenter {
String.valueOf(prefix.getMultiplier())));
}
+ /** Clears then reloads all unit, prefix, dimension and exception data. */
+ public void reloadData() {
+ this.database.clear();
+ this.metricExceptions.clear();
+ addDefaults(this.database);
+
+ if (this.useDefaultDatafiles) {
+ this.loadDefaultData();
+ }
+
+ this.customUnitFiles.forEach(
+ path -> this.handleLoadErrors(this.database.loadUnitsFile(path)));
+ this.customDimensionFiles.forEach(path -> this
+ .handleLoadErrors(this.database.loadDimensionFile(path)));
+ this.customExceptionFiles.forEach(this::loadExceptionFile);
+ }
+
/**
* Saves the presenter's current settings to the config file, creating it if
* it doesn't exist.
- *
+ *
* @return false iff the presenter could not write to the file
* @since 2022-04-19
+ * @since v0.4.0
*/
public boolean saveSettings() {
- final Path configDir = CONFIG_FILE.getParent();
+ final var configDir = CONFIG_FILE.getParent();
if (!Files.exists(configDir)) {
try {
Files.createDirectories(configDir);
- } catch (IOException e) {
+ } catch (final IOException e) {
return false;
}
}
@@ -775,64 +1189,32 @@ public final class Presenter {
return this.writeSettings(CONFIG_FILE);
}
- /**
- * Saves the presenter's settings to the user settings file.
- *
- * @param settingsFile file settings should be saved to
- * @since 2021-12-15
- */
- boolean writeSettings(Path settingsFile) {
- try (BufferedWriter writer = Files.newBufferedWriter(settingsFile)) {
- writer.write(String.format("number_display_rule=%s\n",
- displayRuleToString(this.numberDisplayRule)));
- writer.write(
- String.format("prefix_rule=%s\n", this.prefixRepetitionRule));
- writer.write(
- String.format("one_way=%s\n", this.oneWayConversionEnabled));
- writer.write(
- String.format("include_duplicates=%s\n", this.showDuplicates));
- writer.write(String.format("search_prefix_rule=%s\n",
- searchRuleToString(this.searchRule)));
- return true;
- } catch (final IOException e) {
- e.printStackTrace();
- this.view.showErrorMessage("I/O Error",
- "Error occurred while saving settings: "
- + e.getLocalizedMessage());
- return false;
+ private void setDisplayRuleFromString(String ruleString) {
+ final var tokens = ruleString.split(" ");
+ switch (tokens[0]) {
+ case "FIXED_DECIMALS":
+ final var decimals = Integer.parseInt(tokens[1]);
+ this.numberDisplayRule = StandardDisplayRules.fixedDecimals(decimals);
+ break;
+ case "FIXED_PRECISION":
+ final var sigDigs = Integer.parseInt(tokens[1]);
+ this.numberDisplayRule = StandardDisplayRules.fixedPrecision(sigDigs);
+ break;
+ case "UNCERTAINTY_BASED":
+ this.numberDisplayRule = StandardDisplayRules.uncertaintyBased();
+ break;
+ default:
+ this.numberDisplayRule = StandardDisplayRules
+ .getStandardRule(ruleString);
+ break;
}
}
- private static String searchRuleToString(
- Function<Map.Entry<String, LinearUnit>, Map<String, LinearUnit>> searchRule) {
- if (PrefixSearchRule.NO_PREFIXES.equals(searchRule)) {
- return "NO_PREFIXES";
- } else if (PrefixSearchRule.COMMON_PREFIXES.equals(searchRule)) {
- return "COMMON_PREFIXES";
- } else if (PrefixSearchRule.ALL_METRIC_PREFIXES.equals(searchRule)) {
- return "ALL_METRIC_PREFIXES";
- } else
- return searchRule.toString();
- }
-
- private static String displayRuleToString(
- Function<UncertainDouble, String> numberDisplayRule) {
- if (numberDisplayRule instanceof FixedDecimals) {
- return String.format("FIXED_DECIMALS %d",
- ((FixedDecimals) numberDisplayRule).decimalPlaces());
- } else if (numberDisplayRule instanceof FixedPrecision) {
- return String.format("FIXED_PRECISION %d",
- ((FixedPrecision) numberDisplayRule).significantFigures());
- } else if (numberDisplayRule instanceof UncertaintyBased) {
- return "UNCERTAINTY_BASED";
- } else
- return numberDisplayRule.toString();
- }
-
/**
* @param numberDisplayRule the new rule that will be used by this presenter
* to convert numbers into strings
* @since 2022-04-10
+ * @since v0.4.0
*/
public void setNumberDisplayRule(
Function<UncertainDouble, String> numberDisplayRule) {
@@ -843,6 +1225,7 @@ public final class Presenter {
* @param numberParsingRule the new rule that will be used by this presenter
* to convert strings into numbers
* @since 2022-04-10
+ * @since v0.4.0
*/
@SuppressWarnings("unused") // not implemented yet
private void setNumberParsingRule(
@@ -854,7 +1237,8 @@ public final class Presenter {
* @param oneWayConversionEnabled whether not one-way conversion should be
* enabled
* @since 2022-03-30
- * @see {@link #isOneWayConversionEnabled}
+ * @since v0.4.0
+ * @see #oneWayConversionEnabled
*/
public void setOneWayConversionEnabled(boolean oneWayConversionEnabled) {
this.oneWayConversionEnabled = oneWayConversionEnabled;
@@ -865,6 +1249,7 @@ public final class Presenter {
* @param prefixRepetitionRule the rule that determines whether a set of
* prefixes is valid
* @since 2022-04-19
+ * @since v0.4.0
*/
public void setPrefixRepetitionRule(
Predicate<List<UnitPrefix>> prefixRepetitionRule) {
@@ -878,30 +1263,86 @@ public final class Presenter {
* unit (including the unit itself) that should be
* searchable.
* @since 2022-07-08
+ * @since v0.4.0
*/
public void setSearchRule(
Function<Map.Entry<String, LinearUnit>, Map<String, LinearUnit>> searchRule) {
this.searchRule = searchRule;
}
+ private void setSearchRuleFromString(String ruleString) {
+ switch (ruleString) {
+ case "NO_PREFIXES":
+ this.searchRule = PrefixSearchRule.NO_PREFIXES;
+ break;
+ case "COMMON_PREFIXES":
+ this.searchRule = PrefixSearchRule.COMMON_PREFIXES;
+ break;
+ case "ALL_METRIC_PREFIXES":
+ this.searchRule = PrefixSearchRule.ALL_METRIC_PREFIXES;
+ break;
+ default:
+ System.err.printf(
+ "Warning: unrecognized value for search_prefix_rule: %s\n",
+ ruleString);
+ }
+ }
+
/**
* @param showDuplicateUnits whether or not duplicate units should be shown
* @since 2022-03-30
+ * @since v0.4.0
*/
public void setShowDuplicates(boolean showDuplicateUnits) {
this.showDuplicates = showDuplicateUnits;
this.updateView();
}
+ private List<Map.Entry<String, String>> settingsFromFile(Path settingsFile) {
+ try (var lines = Files.lines(settingsFile)) {
+ return lines.map(Presenter::withoutComments)
+ .filter(line -> !line.isBlank()).map(Presenter::parseSettingLine)
+ .toList();
+ } catch (final IOException e) {
+ this.view.showErrorMessage("Settings Loading Error",
+ "Error loading settings file. Using default settings.");
+ return null;
+ }
+ }
+
+ /**
+ * Sets whether or not the default datafiles will be loaded. This method
+ * automatically updates the view's units.
+ *
+ * @param useDefaultDatafiles whether or not default datafiles should be
+ * loaded
+ */
+ public void setUseDefaultDatafiles(boolean useDefaultDatafiles) {
+ this.useDefaultDatafiles = useDefaultDatafiles;
+ this.reloadData();
+ this.updateView();
+ }
+
+ /**
+ * Sets the user's locale, updating the view.
+ *
+ * @param userLocale locale to use
+ */
+ public void setUserLocale(String userLocale) {
+ this.userLocale = userLocale;
+ this.view.updateText();
+ }
+
/**
* Shows a unit in the unit viewer
*
* @param u unit to show
* @since 2022-04-16
+ * @since v0.4.0
*/
- private final void showUnit(Unit u) {
+ private void showUnit(Unit u) {
final var nameSymbol = u.getNameSymbol();
- final boolean isBase = u instanceof BaseUnit
+ final var isBase = u instanceof BaseUnit
|| u instanceof LinearUnit && ((LinearUnit) u).isBase();
final var definition = isBase ? "(Base unit)" : u.toDefinitionString();
final var dimensionString = this.getDimensionName(u.getDimension());
@@ -912,12 +1353,13 @@ public final class Presenter {
/**
* Runs whenever a unit name is selected in the unit viewer. Gets the
* description of a unit and displays it.
- *
+ *
* @since 2022-04-10
+ * @since v0.4.0
*/
void unitNameSelected() {
// get selected unit, if it's there and valid
- final Optional<String> selectedUnitName = this.view.getViewedUnitName();
+ final var selectedUnitName = this.view.getViewedUnitName();
final Optional<Unit> selectedUnit = selectedUnitName
.map(unitName -> this.database.containsUnitName(unitName)
? this.database.getUnit(unitName)
@@ -927,12 +1369,13 @@ public final class Presenter {
/**
* Updates the view's From and To units, if it has some
- *
+ *
* @since 2021-12-15
+ * @since v0.4.0
*/
public void updateView() {
if (this.view instanceof UnitConversionView) {
- final UnitConversionView ucview = (UnitConversionView) this.view;
+ final var ucview = (UnitConversionView) this.view;
final var selectedDimensionName = ucview.getSelectedDimensionName();
// load units & prefixes into viewers
@@ -946,6 +1389,7 @@ public final class Presenter {
.entrySet().stream();
var toUnits = this.database.unitMapPrefixless(this.showDuplicates)
.entrySet().stream();
+ var unitSets = this.database.unitSetMap().entrySet().stream();
// filter by dimension, if one is selected
if (selectedDimensionName.isPresent()) {
@@ -955,6 +1399,8 @@ public final class Presenter {
u -> viewDimension.equals(u.getValue().getDimension()));
toUnits = toUnits.filter(
u -> viewDimension.equals(u.getValue().getDimension()));
+ unitSets = unitSets.filter(us -> viewDimension
+ .equals(us.getValue().get(0).getDimension()));
}
// filter by unit type, if desired
@@ -963,25 +1409,70 @@ public final class Presenter {
this::isSemiMetric) != UnitType.METRIC);
toUnits = toUnits.filter(u -> UnitType.getType(u.getValue(),
this::isSemiMetric) != UnitType.NON_METRIC);
+ // unit sets are never considered metric
+ unitSets = unitSets
+ .filter(us -> this.metricExceptions.contains(us.getKey()));
}
// set unit names
ucview.setFromUnitNames(fromUnits.flatMap(this::applySearchRule)
.map(Map.Entry::getKey).collect(Collectors.toSet()));
- ucview.setToUnitNames(toUnits.flatMap(this::applySearchRule)
- .map(Map.Entry::getKey).collect(Collectors.toSet()));
+ final var toUnitNames = toUnits.flatMap(this::applySearchRule)
+ .map(Map.Entry::getKey);
+ final var unitSetNames = unitSets.map(Map.Entry::getKey);
+ final var toNames = Stream.concat(toUnitNames, unitSetNames)
+ .collect(Collectors.toSet());
+ ucview.setToUnitNames(toNames);
}
}
+ /** @return true iff the default datafiles are being used */
+ public boolean usingDefaultDatafiles() {
+ return this.useDefaultDatafiles;
+ }
+
/**
* @param message message to add
* @param args string formatting arguments for message
* @return AssertionError stating that an error has happened in the view's
* code
* @since 2022-04-09
+ * @since v0.4.0
*/
private AssertionError viewError(String message, Object... args) {
return new AssertionError("View Programming Error (from " + this.view
+ "): " + String.format(message, args));
}
+
+ /**
+ * Saves the presenter's settings to the user settings file.
+ *
+ * @param settingsFile file settings should be saved to
+ * @since 2021-12-15
+ * @since v0.4.0
+ */
+ boolean writeSettings(Path settingsFile) {
+ try (var writer = Files.newBufferedWriter(settingsFile)) {
+ writer.write(String.format("number_display_rule=%s\n",
+ displayRuleToString(this.numberDisplayRule)));
+ writer.write(
+ String.format("prefix_rule=%s\n", this.prefixRepetitionRule));
+ writer.write(
+ String.format("one_way=%s\n", this.oneWayConversionEnabled));
+ writer.write(
+ String.format("include_duplicates=%s\n", this.showDuplicates));
+ writer.write(String.format("search_prefix_rule=%s\n",
+ searchRuleToString(this.searchRule)));
+ writer.write(String.format("use_default_datafiles=%s\n",
+ this.useDefaultDatafiles));
+ writer.write(String.format("locale=%s\n", this.userLocale));
+ return true;
+ } catch (final IOException e) {
+ e.printStackTrace();
+ this.view.showErrorMessage("I/O Error",
+ "Error occurred while saving settings: "
+ + e.getLocalizedMessage());
+ return false;
+ }
+ }
}