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.java408
1 files changed, 272 insertions, 136 deletions
diff --git a/src/main/java/sevenUnitsGUI/Presenter.java b/src/main/java/sevenUnitsGUI/Presenter.java
index abdd1f6..eba8438 100644
--- a/src/main/java/sevenUnitsGUI/Presenter.java
+++ b/src/main/java/sevenUnitsGUI/Presenter.java
@@ -49,6 +49,9 @@ import sevenUnits.unit.UnitValue;
import sevenUnits.utils.Nameable;
import sevenUnits.utils.ObjectProduct;
import sevenUnits.utils.UncertainDouble;
+import sevenUnitsGUI.StandardDisplayRules.FixedDecimals;
+import sevenUnitsGUI.StandardDisplayRules.FixedPrecision;
+import sevenUnitsGUI.StandardDisplayRules.UncertaintyBased;
/**
* An object that handles interactions between the view and the backend code
@@ -57,16 +60,42 @@ import sevenUnits.utils.UncertainDouble;
* @since 2021-12-15
*/
public final class Presenter {
- /** The default place where settings are stored. */
- private static final Path DEFAULT_SETTINGS_FILEPATH = Path
- .of("settings.txt");
+ /**
+ * The place where settings are stored. Both this path and its parent
+ * directory may not exist.
+ */
+ private static final Path CONFIG_FILE = userConfigDir().resolve("SevenUnits")
+ .resolve("config.txt");
/** The default place where units are stored. */
private static final String DEFAULT_UNITS_FILEPATH = "/unitsfile.txt";
/** The default place where dimensions are stored. */
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";
-
+
+ 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);
+ }
+
/**
* Adds default units and dimensions to a database.
*
@@ -88,14 +117,14 @@ public final class Presenter {
// nonlinear units - must be loaded manually
database.addUnit("tempCelsius", Metric.CELSIUS);
database.addUnit("tempFahrenheit", BritishImperial.FAHRENHEIT);
-
+
// load initial dimensions
database.addDimension("Length", Metric.Dimensions.LENGTH);
database.addDimension("Mass", Metric.Dimensions.MASS);
database.addDimension("Time", Metric.Dimensions.TIME);
database.addDimension("Temperature", Metric.Dimensions.TEMPERATURE);
}
-
+
/**
* @return text in About file
* @since 2022-02-19
@@ -105,7 +134,7 @@ public final class Presenter {
.map(Presenter::withoutComments).collect(Collectors.joining("\n"))
.replaceAll("\\[VERSION\\]", ProgramInfo.VERSION.toString());
}
-
+
/**
* Gets the text of a resource file as a set of strings (each one is one line
* of the text).
@@ -116,7 +145,7 @@ public final class Presenter {
*/
private static final List<String> getLinesFromResource(String filename) {
final List<String> lines = new ArrayList<>();
-
+
try (InputStream stream = inputStream(filename);
Scanner scanner = new Scanner(stream)) {
while (scanner.hasNextLine()) {
@@ -126,10 +155,10 @@ public final class Presenter {
throw new AssertionError(
"Error occurred while loading file " + filename, e);
}
-
+
return lines;
}
-
+
/**
* Gets an input stream for a resource file.
*
@@ -140,7 +169,7 @@ public final class Presenter {
private static final InputStream inputStream(String filepath) {
return Presenter.class.getResourceAsStream(filepath);
}
-
+
/**
* @return true iff a and b have any elements in common
* @since 2022-04-19
@@ -152,7 +181,7 @@ public final class Presenter {
}
return false;
}
-
+
/**
* @return {@code line} with any comments removed.
* @since 2021-03-13
@@ -161,25 +190,25 @@ public final class Presenter {
final int index = line.indexOf('#');
return index == -1 ? line : line.substring(0, index);
}
-
+
// ====== SETTINGS ======
-
+
/**
* The view that this presenter communicates with
*/
private final View view;
-
+
/**
* The database that this presenter communicates with (effectively the model)
*/
final UnitDatabase database;
-
+
/**
* The rule used for parsing input numbers. Any number-string inputted into
* this program will be parsed using this method. <b>Not implemented yet.</b>
*/
private Function<String, UncertainDouble> numberParsingRule;
-
+
/**
* The rule used for displaying the results of unit conversions. The result
* of unit conversions will be put into this function, and the resulting
@@ -187,41 +216,41 @@ public final class Presenter {
*/
private Function<UncertainDouble, String> numberDisplayRule = StandardDisplayRules
.uncertaintyBased();
-
+
/**
* A predicate that determines whether or not a certain combination of
* prefixes is allowed. If it returns false, a combination of prefixes will
* not be allowed. Prefixes are put in the list from right to left.
*/
private Predicate<List<UnitPrefix>> prefixRepetitionRule = DefaultPrefixRepetitionRule.NO_RESTRICTION;
-
+
/**
* A rule that accepts a prefixless name-unit pair and returns a map mapping
* names to prefixed versions of that unit (including the unit itself) that
* should be searchable.
*/
private Function<Map.Entry<String, LinearUnit>, Map<String, LinearUnit>> searchRule = PrefixSearchRule.NO_PREFIXES;
-
+
/**
* The set of units that is considered neither metric nor nonmetric for the
* purposes of the metric-imperial one-way conversion. These units are
* included in both From and To, even if One Way Conversion is enabled.
*/
private final Set<String> metricExceptions;
-
+
/**
* 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
* unit list.
*/
private boolean oneWayConversionEnabled = false;
-
+
/**
* If this is false, duplicate units and prefixes will be removed from the
* unit view in views that show units as a list to choose from.
*/
private boolean showDuplicates = false;
-
+
/**
* Creates a Presenter
*
@@ -232,14 +261,14 @@ public final class Presenter {
this.view = view;
this.database = new UnitDatabase();
addDefaults(this.database);
-
+
// 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)) {
@@ -247,7 +276,7 @@ public final class Presenter {
} catch (final IOException e) {
throw new AssertionError("Loading of dimensionfile.txt failed.", e);
}
-
+
// load metric exceptions
try {
this.metricExceptions = new HashSet<>();
@@ -265,14 +294,16 @@ public final class Presenter {
throw new AssertionError("Loading of metric_exceptions.txt failed.",
e);
}
-
+
// set default settings temporarily
- this.loadSettings(DEFAULT_SETTINGS_FILEPATH);
-
+ 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();
-
+
// print out unit counts
System.out.printf(
"Successfully loaded %d units with %d unit names (%d base units).%n",
@@ -281,7 +312,7 @@ public final class Presenter {
this.database.unitMapPrefixless(false).values().stream()
.filter(isFullBase).count());
}
-
+
/**
* Applies a search rule to an entry in a name-unit map.
*
@@ -301,7 +332,7 @@ public final class Presenter {
} else
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.
@@ -315,10 +346,10 @@ public final class Presenter {
public void convertExpressions() {
if (this.view instanceof ExpressionConversionView) {
final ExpressionConversionView xcview = (ExpressionConversionView) this.view;
-
+
final String fromExpression = xcview.getFromExpression();
final String toExpression = xcview.getToExpression();
-
+
// expressions must not be empty
if (fromExpression.isEmpty()) {
this.view.showErrorMessage("Parse Error",
@@ -330,7 +361,7 @@ public final class Presenter {
"Please enter a unit expression in the To: box.");
return;
}
-
+
// evaluate expressions
final LinearUnitValue from;
final Unit to;
@@ -348,11 +379,11 @@ public final class Presenter {
"Could not recognize text in To entry: " + e.getMessage());
return;
}
-
+
// convert and show output
if (from.getUnit().canConvertTo(to)) {
final UncertainDouble uncertainValue;
-
+
// uncertainty is meaningless for non-linear units, so we will have
// to erase uncertainty information for them
if (to instanceof LinearUnit) {
@@ -362,7 +393,7 @@ public final class Presenter {
final double value = from.asUnitValue().convertTo(to).getValue();
uncertainValue = UncertainDouble.of(value, 0);
}
-
+
final UnitConversionRecord uc = UnitConversionRecord.valueOf(
fromExpression, toExpression, "",
this.numberDisplayRule.apply(uncertainValue));
@@ -372,12 +403,12 @@ public final class Presenter {
"Cannot convert between \"" + fromExpression + "\" and \""
+ toExpression + "\".");
}
-
+
} else
throw new UnsupportedOperationException(
"This function can only be called when the view is an ExpressionConversionView");
}
-
+
/**
* Converts from the view's input unit to its output unit. Displays an error
* message if any of the required fields are invalid.
@@ -391,11 +422,11 @@ public final class Presenter {
public void convertUnits() {
if (this.view instanceof UnitConversionView) {
final UnitConversionView ucview = (UnitConversionView) this.view;
-
+
final Optional<String> fromUnitOptional = ucview.getFromSelection();
final Optional<String> toUnitOptional = ucview.getToSelection();
final String inputValueString = ucview.getInputValue();
-
+
// extract values from optionals
final String fromUnitString, toUnitString;
if (fromUnitOptional.isPresent()) {
@@ -412,11 +443,11 @@ public final class Presenter {
"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
@@ -433,11 +464,11 @@ public final class Presenter {
"Invalid value " + inputValueString);
return;
}
-
+
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;
@@ -447,18 +478,18 @@ public final class Presenter {
final LinearUnitValue initialValue = LinearUnitValue.of(fromLinear,
uncertainValue);
final LinearUnitValue converted = initialValue.convertTo(toLinear);
-
+
outputValueString = this.numberDisplayRule
.apply(converted.getValue());
} else {
final UnitValue initialValue = UnitValue.of(fromUnit,
uncertainValue.value());
final UnitValue converted = initialValue.convertTo(toUnit);
-
+
outputValueString = this.numberDisplayRule
.apply(UncertainDouble.of(converted.getValue(), 0));
}
-
+
ucview.showUnitConversionOutput(
UnitConversionRecord.valueOf(fromUnitString, toUnitString,
inputValueString, outputValueString));
@@ -466,7 +497,7 @@ public final class Presenter {
throw new UnsupportedOperationException(
"This function can only be called when the view is a UnitConversionView.");
}
-
+
/**
* @return true iff duplicate units are shown in unit lists
* @since 2022-03-30
@@ -474,7 +505,7 @@ public final class Presenter {
public boolean duplicatesShown() {
return this.showDuplicates;
}
-
+
/**
* Gets a name for this dimension using the database
*
@@ -489,7 +520,7 @@ public final class Presenter {
.filter(d -> d.equals(dimension)).findAny().map(Nameable::getName)
.orElse(dimension.toString(Nameable::getName));
}
-
+
/**
* @return the rule that is used by this presenter to convert numbers into
* strings
@@ -498,7 +529,7 @@ public final class Presenter {
public Function<UncertainDouble, String> getNumberDisplayRule() {
return this.numberDisplayRule;
}
-
+
/**
* @return the rule that is used by this presenter to convert strings into
* numbers
@@ -508,7 +539,7 @@ public final class Presenter {
private Function<String, UncertainDouble> getNumberParsingRule() {
return this.numberParsingRule;
}
-
+
/**
* @return the rule that determines whether a set of prefixes is valid
* @since 2022-04-19
@@ -516,7 +547,7 @@ public final class Presenter {
public Predicate<List<UnitPrefix>> getPrefixRepetitionRule() {
return this.prefixRepetitionRule;
}
-
+
/**
* @return the rule that determines which units are prefixed
* @since 2022-07-08
@@ -524,7 +555,7 @@ public final class Presenter {
public Function<Map.Entry<String, LinearUnit>, Map<String, LinearUnit>> getSearchRule() {
return this.searchRule;
}
-
+
/**
* @return a search rule that shows all single prefixes
* @since 2022-07-08
@@ -533,7 +564,7 @@ public final class Presenter {
return PrefixSearchRule.getCoherentOnlyRule(
new HashSet<>(this.database.prefixMap(true).values()));
}
-
+
/**
* @return the view associated with this presenter
* @since 2022-04-19
@@ -541,7 +572,7 @@ public final class Presenter {
public View getView() {
return this.view;
}
-
+
/**
* @return whether or not the provided unit is semi-metric (i.e. an
* exception)
@@ -557,7 +588,7 @@ public final class Presenter {
&& this.metricExceptions.contains(symbol.orElseThrow())
|| sharesAnyElements(this.metricExceptions, u.getOtherNames());
}
-
+
/**
* Loads settings from the user's settings file and applies them to the
* presenter.
@@ -566,58 +597,124 @@ public final class Presenter {
* @since 2021-12-15
*/
void loadSettings(Path settingsFile) {
- try {
- // read file line by line
- final int lineNum = 0;
- for (final String line : Files.readAllLines(settingsFile)) {
- final int equalsIndex = line.indexOf('=');
- if (equalsIndex == -1)
- throw new IllegalStateException(
- "Settings file is malformed at line " + lineNum);
-
- final String param = line.substring(0, equalsIndex);
- final String value = line.substring(equalsIndex + 1);
-
- switch (param) {
- // set manually to avoid the unnecessary saving of the non-manual
- // methods
- case "number_display_rule":
- this.numberDisplayRule = StandardDisplayRules
- .getStandardRule(value);
- break;
- case "prefix_rule":
- this.prefixRepetitionRule = DefaultPrefixRepetitionRule
- .valueOf(value);
- this.database.setPrefixRepetitionRule(this.prefixRepetitionRule);
- break;
- case "one_way":
- this.oneWayConversionEnabled = Boolean.valueOf(value);
- break;
- case "include_duplicates":
- this.showDuplicates = Boolean.valueOf(value);
- break;
- case "search_prefix_rule":
- if (PrefixSearchRule.NO_PREFIXES.toString().equals(value)) {
- this.searchRule = PrefixSearchRule.NO_PREFIXES;
- } else if (PrefixSearchRule.COMMON_PREFIXES.toString()
- .equals(value)) {
- this.searchRule = PrefixSearchRule.COMMON_PREFIXES;
- } else {
- this.searchRule = this.getUniversalSearchRule();
- }
- break;
- default:
- System.err.printf("Warning: unrecognized setting \"%s\".%n",
- param);
- break;
- }
- }
- if (this.view.getPresenter() != null) {
- this.updateView();
+ for (Map.Entry<String, String> setting : settingsFromFile(settingsFile)) {
+ final String 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));
+ break;
+ case "custom_exception_file":
+ this.loadExceptionFile(pathFromConfig(value));
+ break;
+ case "custom_unit_file":
+ this.database.loadUnitsFile(pathFromConfig(value));
+ break;
+ case "number_display_rule":
+ this.setDisplayRuleFromString(value);
+ break;
+ case "prefix_rule":
+ this.prefixRepetitionRule = DefaultPrefixRepetitionRule
+ .valueOf(value);
+ this.database.setPrefixRepetitionRule(this.prefixRepetitionRule);
+ break;
+ case "one_way":
+ this.oneWayConversionEnabled = Boolean.valueOf(value);
+ break;
+ case "include_duplicates":
+ this.showDuplicates = Boolean.valueOf(value);
+ break;
+ case "search_prefix_rule":
+ this.setSearchRuleFromString(value);
+ break;
+ default:
+ System.err.printf("Warning: unrecognized setting \"%s\".%n",
+ setting.getKey());
+ break;
}
- } catch (final IOException e) {}
+ }
+
+ if (this.view.getPresenter() != null) {
+ this.updateView();
+ }
+ }
+
+ 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 true iff the One-Way Conversion feature is available (views that
* show units as a list will have metric units removed from the From
@@ -628,7 +725,7 @@ public final class Presenter {
public boolean oneWayConversionEnabled() {
return this.oneWayConversionEnabled;
}
-
+
/**
* Completes creation of the presenter. This part of the initialization
* depends on the view's functions, so it cannot be run if the components
@@ -642,10 +739,10 @@ public final class Presenter {
final UnitConversionView ucview = (UnitConversionView) this.view;
ucview.setDimensionNames(this.database.dimensionMap().keySet());
}
-
+
this.updateView();
}
-
+
void prefixSelected() {
final Optional<String> selectedPrefixName = this.view
.getViewedPrefixName();
@@ -657,42 +754,81 @@ public final class Presenter {
.ifPresent(prefix -> this.view.showPrefix(prefix.getNameSymbol(),
String.valueOf(prefix.getMultiplier())));
}
-
+
/**
- * Saves the presenter's current settings to its default filepath.
+ * 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
*/
- public void saveSettings() {
- this.saveSettings(DEFAULT_SETTINGS_FILEPATH);
+ public boolean saveSettings() {
+ final Path configDir = CONFIG_FILE.getParent();
+ if (!Files.exists(configDir)) {
+ try {
+ Files.createDirectories(configDir);
+ } catch (IOException e) {
+ return false;
+ }
+ }
+
+ 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
*/
- void saveSettings(Path settingsFile) {
+ boolean writeSettings(Path settingsFile) {
try (BufferedWriter writer = Files.newBufferedWriter(settingsFile)) {
writer.write(String.format("number_display_rule=%s\n",
- this.numberDisplayRule));
+ 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", this.searchRule));
+ 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 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
@@ -702,7 +838,7 @@ public final class Presenter {
Function<UncertainDouble, String> numberDisplayRule) {
this.numberDisplayRule = numberDisplayRule;
}
-
+
/**
* @param numberParsingRule the new rule that will be used by this presenter
* to convert strings into numbers
@@ -713,7 +849,7 @@ public final class Presenter {
Function<String, UncertainDouble> numberParsingRule) {
this.numberParsingRule = numberParsingRule;
}
-
+
/**
* @param oneWayConversionEnabled whether not one-way conversion should be
* enabled
@@ -724,7 +860,7 @@ public final class Presenter {
this.oneWayConversionEnabled = oneWayConversionEnabled;
this.updateView();
}
-
+
/**
* @param prefixRepetitionRule the rule that determines whether a set of
* prefixes is valid
@@ -735,7 +871,7 @@ public final class Presenter {
this.prefixRepetitionRule = prefixRepetitionRule;
this.database.setPrefixRepetitionRule(prefixRepetitionRule);
}
-
+
/**
* @param searchRule A rule that accepts a prefixless name-unit pair and
* returns a map mapping names to prefixed versions of that
@@ -747,7 +883,7 @@ public final class Presenter {
Function<Map.Entry<String, LinearUnit>, Map<String, LinearUnit>> searchRule) {
this.searchRule = searchRule;
}
-
+
/**
* @param showDuplicateUnits whether or not duplicate units should be shown
* @since 2022-03-30
@@ -756,7 +892,7 @@ public final class Presenter {
this.showDuplicates = showDuplicateUnits;
this.updateView();
}
-
+
/**
* Shows a unit in the unit viewer
*
@@ -772,7 +908,7 @@ public final class Presenter {
final var unitType = UnitType.getType(u, this::isSemiMetric);
this.view.showUnit(nameSymbol, definition, dimensionString, unitType);
}
-
+
/**
* Runs whenever a unit name is selected in the unit viewer. Gets the
* description of a unit and displays it.
@@ -788,7 +924,7 @@ public final class Presenter {
: null);
selectedUnit.ifPresent(this::showUnit);
}
-
+
/**
* Updates the view's From and To units, if it has some
*
@@ -798,19 +934,19 @@ public final class Presenter {
if (this.view instanceof UnitConversionView) {
final UnitConversionView ucview = (UnitConversionView) this.view;
final var selectedDimensionName = ucview.getSelectedDimensionName();
-
+
// load units & prefixes into viewers
this.view.setViewableUnitNames(
this.database.unitMapPrefixless(this.showDuplicates).keySet());
this.view.setViewablePrefixNames(
this.database.prefixMap(this.showDuplicates).keySet());
-
+
// get From and To units
var fromUnits = this.database.unitMapPrefixless(this.showDuplicates)
.entrySet().stream();
var toUnits = this.database.unitMapPrefixless(this.showDuplicates)
.entrySet().stream();
-
+
// filter by dimension, if one is selected
if (selectedDimensionName.isPresent()) {
final var viewDimension = this.database
@@ -820,7 +956,7 @@ public final class Presenter {
toUnits = toUnits.filter(
u -> viewDimension.equals(u.getValue().getDimension()));
}
-
+
// filter by unit type, if desired
if (this.oneWayConversionEnabled) {
fromUnits = fromUnits.filter(u -> UnitType.getType(u.getValue(),
@@ -828,7 +964,7 @@ public final class Presenter {
toUnits = toUnits.filter(u -> UnitType.getType(u.getValue(),
this::isSemiMetric) != UnitType.NON_METRIC);
}
-
+
// set unit names
ucview.setFromUnitNames(fromUnits.flatMap(this::applySearchRule)
.map(Map.Entry::getKey).collect(Collectors.toSet()));
@@ -836,7 +972,7 @@ public final class Presenter {
.map(Map.Entry::getKey).collect(Collectors.toSet()));
}
}
-
+
/**
* @param message message to add
* @param args string formatting arguments for message