diff options
author | Adrien Hopkins <adrien.p.hopkins@gmail.com> | 2024-03-24 13:14:11 -0500 |
---|---|---|
committer | Adrien Hopkins <adrien.p.hopkins@gmail.com> | 2024-03-24 13:14:11 -0500 |
commit | 26291e672b0e683edc9d57710a9a9d96ca199c45 (patch) | |
tree | df88f3d3f110e50f38b8a2752d55df4a0c777677 /src/main/java/sevenUnitsGUI/Presenter.java | |
parent | cc45a65c78c578eb404d8773b22e5b046917621f (diff) |
Format source code & set explicit UTF-8
Diffstat (limited to 'src/main/java/sevenUnitsGUI/Presenter.java')
-rw-r--r-- | src/main/java/sevenUnitsGUI/Presenter.java | 190 |
1 files changed, 98 insertions, 92 deletions
diff --git a/src/main/java/sevenUnitsGUI/Presenter.java b/src/main/java/sevenUnitsGUI/Presenter.java index b129d95..eba8438 100644 --- a/src/main/java/sevenUnitsGUI/Presenter.java +++ b/src/main/java/sevenUnitsGUI/Presenter.java @@ -61,17 +61,18 @@ import sevenUnitsGUI.StandardDisplayRules.UncertaintyBased; */ public final class Presenter { /** - * The place where settings are stored. - * Both this path and its parent directory may not exist. + * 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"); + 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"); @@ -116,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 @@ -133,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). @@ -144,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()) { @@ -154,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. * @@ -168,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 @@ -180,7 +181,7 @@ public final class Presenter { } return false; } - + /** * @return {@code line} with any comments removed. * @since 2021-03-13 @@ -189,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 @@ -215,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 * @@ -260,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)) { @@ -275,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<>(); @@ -293,16 +294,16 @@ public final class Presenter { throw new AssertionError("Loading of metric_exceptions.txt failed.", e); } - + // 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(); - + // print out unit counts System.out.printf( "Successfully loaded %d units with %d unit names (%d base units).%n", @@ -311,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. * @@ -331,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. @@ -345,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", @@ -360,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; @@ -378,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) { @@ -392,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)); @@ -402,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. @@ -421,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()) { @@ -442,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 @@ -463,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; @@ -477,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)); @@ -496,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 @@ -504,7 +505,7 @@ public final class Presenter { public boolean duplicatesShown() { return this.showDuplicates; } - + /** * Gets a name for this dimension using the database * @@ -519,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 @@ -528,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 @@ -538,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 @@ -546,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 @@ -554,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 @@ -563,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 @@ -571,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) @@ -587,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. @@ -616,7 +617,7 @@ public final class Presenter { break; case "prefix_rule": this.prefixRepetitionRule = DefaultPrefixRepetitionRule - .valueOf(value); + .valueOf(value); this.database.setPrefixRepetitionRule(this.prefixRepetitionRule); break; case "one_way": @@ -643,10 +644,11 @@ 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(); + .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."); + this.view.showErrorMessage("Settings Loading Error", + "Error loading settings file. Using default settings."); return null; } } @@ -662,7 +664,7 @@ public final class Presenter { return Map.entry(param, value); } - + private void setSearchRuleFromString(String ruleString) { switch (ruleString) { case "NO_PREFIXES": @@ -675,7 +677,9 @@ public final class Presenter { this.searchRule = PrefixSearchRule.ALL_METRIC_PREFIXES; break; default: - System.err.printf("Warning: unrecognized value for search_prefix_rule: %s\n", ruleString); + System.err.printf( + "Warning: unrecognized value for search_prefix_rule: %s\n", + ruleString); } } @@ -694,7 +698,8 @@ public final class Presenter { this.numberDisplayRule = StandardDisplayRules.uncertaintyBased(); break; default: - this.numberDisplayRule = StandardDisplayRules.getStandardRule(ruleString); + this.numberDisplayRule = StandardDisplayRules + .getStandardRule(ruleString); break; } } @@ -706,8 +711,7 @@ public final class Presenter { } catch (IOException e) { this.view.showErrorMessage("File Load Error", "Error loading configured metric exception file \"" - + exceptionFile + "\": " - + e.getLocalizedMessage()); + + exceptionFile + "\": " + e.getLocalizedMessage()); } } @@ -721,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 @@ -735,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(); @@ -750,10 +754,10 @@ public final class Presenter { .ifPresent(prefix -> this.view.showPrefix(prefix.getNameSymbol(), String.valueOf(prefix.getMultiplier()))); } - + /** - * Saves the presenter's current settings to the config file, - * creating it if it doesn't exist. + * 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 @@ -770,7 +774,7 @@ public final class Presenter { return this.writeSettings(CONFIG_FILE); } - + /** * Saves the presenter's settings to the user settings file. * @@ -798,8 +802,9 @@ public final class Presenter { return false; } } - - private static String searchRuleToString(Function<Map.Entry<String, LinearUnit>, Map<String, LinearUnit>> searchRule) { + + 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)) { @@ -810,10 +815,11 @@ public final class Presenter { return searchRule.toString(); } - private static String displayRuleToString(Function<UncertainDouble, String> numberDisplayRule) { + private static String displayRuleToString( + Function<UncertainDouble, String> numberDisplayRule) { if (numberDisplayRule instanceof FixedDecimals) { return String.format("FIXED_DECIMALS %d", - ((FixedDecimals) numberDisplayRule) .decimalPlaces()); + ((FixedDecimals) numberDisplayRule).decimalPlaces()); } else if (numberDisplayRule instanceof FixedPrecision) { return String.format("FIXED_PRECISION %d", ((FixedPrecision) numberDisplayRule).significantFigures()); @@ -832,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 @@ -843,7 +849,7 @@ public final class Presenter { Function<String, UncertainDouble> numberParsingRule) { this.numberParsingRule = numberParsingRule; } - + /** * @param oneWayConversionEnabled whether not one-way conversion should be * enabled @@ -854,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 @@ -865,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 @@ -877,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 @@ -886,7 +892,7 @@ public final class Presenter { this.showDuplicates = showDuplicateUnits; this.updateView(); } - + /** * Shows a unit in the unit viewer * @@ -902,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. @@ -918,7 +924,7 @@ public final class Presenter { : null); selectedUnit.ifPresent(this::showUnit); } - + /** * Updates the view's From and To units, if it has some * @@ -928,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 @@ -950,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(), @@ -958,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())); @@ -966,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 |