diff options
author | Adrien Hopkins <adrien.p.hopkins@gmail.com> | 2025-06-15 19:26:12 -0500 |
---|---|---|
committer | Adrien Hopkins <adrien.p.hopkins@gmail.com> | 2025-06-15 19:26:12 -0500 |
commit | da740edd3972fa049c4c8d0e43448c10a6a65dce (patch) | |
tree | 4a0d4f9fa861560d273249666c7a2acc12e9f235 /src/main/java/sevenUnitsGUI | |
parent | 34f0321a31e728fa66057d0decd9a938d133d596 (diff) |
Format & clean up source code
Diffstat (limited to 'src/main/java/sevenUnitsGUI')
-rw-r--r-- | src/main/java/sevenUnitsGUI/DefaultPrefixRepetitionRule.java | 8 | ||||
-rw-r--r-- | src/main/java/sevenUnitsGUI/DelegateListModel.java | 30 | ||||
-rw-r--r-- | src/main/java/sevenUnitsGUI/ExpressionConversionView.java | 4 | ||||
-rw-r--r-- | src/main/java/sevenUnitsGUI/FilterComparator.java | 23 | ||||
-rw-r--r-- | src/main/java/sevenUnitsGUI/GridBagBuilder.java | 25 | ||||
-rw-r--r-- | src/main/java/sevenUnitsGUI/PrefixSearchRule.java | 19 | ||||
-rw-r--r-- | src/main/java/sevenUnitsGUI/Presenter.java | 345 | ||||
-rw-r--r-- | src/main/java/sevenUnitsGUI/SearchBoxList.java | 47 | ||||
-rw-r--r-- | src/main/java/sevenUnitsGUI/StandardDisplayRules.java | 24 | ||||
-rw-r--r-- | src/main/java/sevenUnitsGUI/TabbedView.java | 378 | ||||
-rw-r--r-- | src/main/java/sevenUnitsGUI/UnitConversionRecord.java | 42 | ||||
-rw-r--r-- | src/main/java/sevenUnitsGUI/UnitConversionView.java | 4 | ||||
-rw-r--r-- | src/main/java/sevenUnitsGUI/View.java | 6 | ||||
-rw-r--r-- | src/main/java/sevenUnitsGUI/ViewBot.java | 23 | ||||
-rw-r--r-- | src/main/java/sevenUnitsGUI/package-info.java | 2 |
15 files changed, 471 insertions, 509 deletions
diff --git a/src/main/java/sevenUnitsGUI/DefaultPrefixRepetitionRule.java b/src/main/java/sevenUnitsGUI/DefaultPrefixRepetitionRule.java index 97df107..a441911 100644 --- a/src/main/java/sevenUnitsGUI/DefaultPrefixRepetitionRule.java +++ b/src/main/java/sevenUnitsGUI/DefaultPrefixRepetitionRule.java @@ -56,7 +56,7 @@ public enum DefaultPrefixRepetitionRule implements Predicate<List<UnitPrefix>> { final boolean magnifying; if (prefixes.isEmpty()) return true; - else if (prefixes.get(0).getMultiplier() > 1) { + if (prefixes.get(0).getMultiplier() > 1) { magnifying = true; } else { magnifying = false; @@ -68,15 +68,13 @@ public enum DefaultPrefixRepetitionRule implements Predicate<List<UnitPrefix>> { if (!Metric.DECIMAL_PREFIXES.contains(prefixes.get(0))) return NO_REPETITION.test(prefixes); - int part = 0; // 0=yotta/yoctos, 1=kilo-zetta/milli-zepto, + var part = 0; // 0=yotta/yoctos, 1=kilo-zetta/milli-zepto, // 2=deka,hecto,deci,centi for (final UnitPrefix prefix : prefixes) { // check that the current prefix is metric and appropriately // magnifying/reducing - if (!Metric.DECIMAL_PREFIXES.contains(prefix)) - return false; - if (magnifying != prefix.getMultiplier() > 1) + if (!Metric.DECIMAL_PREFIXES.contains(prefix) || (magnifying != prefix.getMultiplier() > 1)) return false; // check if the current prefix is correct diff --git a/src/main/java/sevenUnitsGUI/DelegateListModel.java b/src/main/java/sevenUnitsGUI/DelegateListModel.java index 200eee2..da4f978 100644 --- a/src/main/java/sevenUnitsGUI/DelegateListModel.java +++ b/src/main/java/sevenUnitsGUI/DelegateListModel.java @@ -31,7 +31,7 @@ import javax.swing.AbstractListModel; * the delegated list's methods because the delegate methods handle updating the * list. * </p> - * + * * @author Adrien Hopkins * @since 2019-01-14 * @since v0.1.0 @@ -46,7 +46,7 @@ final class DelegateListModel<E> extends AbstractListModel<E> /** * The list that this model is a delegate to. - * + * * @since 2019-01-14 * @since v0.1.0 */ @@ -54,7 +54,7 @@ final class DelegateListModel<E> extends AbstractListModel<E> /** * Creates an empty {@code DelegateListModel}. - * + * * @since 2019-04-13 * @since v0.2.0 */ @@ -64,7 +64,7 @@ final class DelegateListModel<E> extends AbstractListModel<E> /** * Creates the {@code DelegateListModel}. - * + * * @param delegate list to delegate * @since 2019-01-14 * @since v0.1.0 @@ -75,8 +75,8 @@ final class DelegateListModel<E> extends AbstractListModel<E> @Override public boolean add(final E element) { - final int index = this.delegate.size(); - final boolean success = this.delegate.add(element); + final var index = this.delegate.size(); + final var success = this.delegate.add(element); this.fireIntervalAdded(this, index, index); return success; } @@ -89,7 +89,7 @@ final class DelegateListModel<E> extends AbstractListModel<E> @Override public boolean addAll(final Collection<? extends E> c) { - boolean changed = false; + var changed = false; for (final E e : c) { if (this.add(e)) { changed = true; @@ -109,7 +109,7 @@ final class DelegateListModel<E> extends AbstractListModel<E> @Override public void clear() { - final int oldSize = this.delegate.size(); + final var oldSize = this.delegate.size(); this.delegate.clear(); if (oldSize >= 1) { this.fireIntervalRemoved(this, 0, oldSize - 1); @@ -177,7 +177,7 @@ final class DelegateListModel<E> extends AbstractListModel<E> @Override public E remove(final int index) { - final E returnValue = this.delegate.get(index); + final var returnValue = this.delegate.get(index); this.delegate.remove(index); this.fireIntervalRemoved(this, index, index); return returnValue; @@ -185,15 +185,15 @@ final class DelegateListModel<E> extends AbstractListModel<E> @Override public boolean remove(final Object o) { - final int index = this.delegate.indexOf(o); - final boolean returnValue = this.delegate.remove(o); + final var index = this.delegate.indexOf(o); + final var returnValue = this.delegate.remove(o); this.fireIntervalRemoved(this, index, index); return returnValue; } @Override public boolean removeAll(final Collection<?> c) { - boolean changed = false; + var changed = false; for (final Object e : c) { if (this.remove(e)) { changed = true; @@ -204,15 +204,15 @@ final class DelegateListModel<E> extends AbstractListModel<E> @Override public boolean retainAll(final Collection<?> c) { - final int oldSize = this.size(); - final boolean returnValue = this.delegate.retainAll(c); + final var oldSize = this.size(); + final var returnValue = this.delegate.retainAll(c); this.fireIntervalRemoved(this, this.size(), oldSize - 1); return returnValue; } @Override public E set(final int index, final E element) { - final E returnValue = this.delegate.get(index); + final var returnValue = this.delegate.get(index); this.delegate.set(index, element); this.fireContentsChanged(this, index, index); return returnValue; diff --git a/src/main/java/sevenUnitsGUI/ExpressionConversionView.java b/src/main/java/sevenUnitsGUI/ExpressionConversionView.java index 20eb23c..ce69365 100644 --- a/src/main/java/sevenUnitsGUI/ExpressionConversionView.java +++ b/src/main/java/sevenUnitsGUI/ExpressionConversionView.java @@ -18,7 +18,7 @@ package sevenUnitsGUI; /** * A View that can convert unit expressions - * + * * @author Adrien Hopkins * @since 2021-12-15 * @since v0.4.0 @@ -40,7 +40,7 @@ public interface ExpressionConversionView extends View { /** * Shows the output of an expression conversion to the user. - * + * * @param uc unit conversion to show * @since 2021-12-15 * @since v0.4.0 diff --git a/src/main/java/sevenUnitsGUI/FilterComparator.java b/src/main/java/sevenUnitsGUI/FilterComparator.java index d7a59c4..ff942fb 100644 --- a/src/main/java/sevenUnitsGUI/FilterComparator.java +++ b/src/main/java/sevenUnitsGUI/FilterComparator.java @@ -21,9 +21,9 @@ import java.util.Objects; /** * A comparator that compares strings using a filter. - * + * * @param <T> type of element being compared - * + * * @author Adrien Hopkins * @since 2019-01-15 * @since v0.1.0 @@ -31,21 +31,21 @@ import java.util.Objects; final class FilterComparator<T> implements Comparator<T> { /** * The filter that the comparator is filtered by. - * + * * @since 2019-01-15 * @since v0.1.0 */ private final String filter; /** * The comparator to use if the arguments are otherwise equal. - * + * * @since 2019-01-15 * @since v0.1.0 */ private final Comparator<T> comparator; /** * Whether or not the comparison is case-sensitive. - * + * * @since 2019-04-14 * @since v0.2.0 */ @@ -53,7 +53,7 @@ final class FilterComparator<T> implements Comparator<T> { /** * Creates the {@code FilterComparator}. - * + * * @param filter * @since 2019-01-15 * @since v0.1.0 @@ -64,7 +64,7 @@ final class FilterComparator<T> implements Comparator<T> { /** * Creates the {@code FilterComparator}. - * + * * @param filter string to filter by * @param comparator comparator to fall back to if all else fails, null is * compareTo. @@ -79,7 +79,7 @@ final class FilterComparator<T> implements Comparator<T> { /** * Creates the {@code FilterComparator}. - * + * * @param filter string to filter by * @param comparator comparator to fall back to if all else fails, null is * compareTo. @@ -118,19 +118,18 @@ final class FilterComparator<T> implements Comparator<T> { // elements that start with the filter always go first if (str0.startsWith(this.filter) && !str1.startsWith(this.filter)) return -1; - else if (!str0.startsWith(this.filter) && str1.startsWith(this.filter)) + if (!str0.startsWith(this.filter) && str1.startsWith(this.filter)) return 1; // elements that contain the filter but don't start with them go next if (str0.contains(this.filter) && !str1.contains(this.filter)) return -1; - else if (!str0.contains(this.filter) && !str1.contains(this.filter)) + if (!str0.contains(this.filter) && !str1.contains(this.filter)) return 1; // other elements go last if (this.comparator == null) return str0.compareTo(str1); - else - return this.comparator.compare(arg0, arg1); + return this.comparator.compare(arg0, arg1); } } diff --git a/src/main/java/sevenUnitsGUI/GridBagBuilder.java b/src/main/java/sevenUnitsGUI/GridBagBuilder.java index 81d1e79..a9fede3 100644 --- a/src/main/java/sevenUnitsGUI/GridBagBuilder.java +++ b/src/main/java/sevenUnitsGUI/GridBagBuilder.java @@ -21,7 +21,7 @@ import java.awt.Insets; /** * A builder for Java's {@link java.awt.GridBagConstraints} class. - * + * * @author Adrien Hopkins * @since 2018-11-30 * @since v0.1.0 @@ -40,7 +40,7 @@ final class GridBagBuilder { * <p> * The default value is <code>RELATIVE</code>. <code>gridx</code> should be a * non-negative value. - * + * * @serial * @see #clone() * @see java.awt.GridBagConstraints#gridy @@ -58,7 +58,7 @@ final class GridBagBuilder { * <p> * The default value is <code>RELATIVE</code>. <code>gridy</code> should be a * non-negative value. - * + * * @serial * @see #clone() * @see java.awt.GridBagConstraints#gridx @@ -76,7 +76,7 @@ final class GridBagBuilder { * from <code>gridx</code> to the next to the last one in its row. * <p> * <code>gridwidth</code> should be non-negative and the default value is 1. - * + * * @serial * @see #clone() * @see java.awt.GridBagConstraints#gridheight @@ -96,7 +96,7 @@ final class GridBagBuilder { * <p> * <code>gridheight</code> should be a non-negative value and the default * value is 1. - * + * * @serial * @see #clone() * @see java.awt.GridBagConstraints#gridwidth @@ -119,7 +119,7 @@ final class GridBagBuilder { * <p> * The default value of this field is <code>0</code>. <code>weightx</code> * should be a non-negative value. - * + * * @serial * @see #clone() * @see java.awt.GridBagConstraints#weighty @@ -142,7 +142,7 @@ final class GridBagBuilder { * <p> * The default value of this field is <code>0</code>. <code>weighty</code> * should be a non-negative value. - * + * * @serial * @see #clone() * @see java.awt.GridBagConstraints#weightx @@ -173,7 +173,7 @@ final class GridBagBuilder { * <code>BELOW_BASELINE</code>, <code>BELOW_BASELINE_LEADING</code>, and * <code>BELOW_BASELINE_TRAILING</code>. The default value is * <code>CENTER</code>. - * + * * @serial * @see #clone() * @see java.awt.ComponentOrientation @@ -199,7 +199,7 @@ final class GridBagBuilder { * </ul> * <p> * The default value is <code>NONE</code>. - * + * * @serial * @see #clone() */ @@ -212,7 +212,7 @@ final class GridBagBuilder { * amount of space between the component and the edges of its display area. * <p> * The default value is <code>new Insets(0, 0, 0, 0)</code>. - * + * * @serial * @see #clone() */ @@ -226,7 +226,7 @@ final class GridBagBuilder { * is at least its minimum width plus <code>ipadx</code> pixels. * <p> * The default value is <code>0</code>. - * + * * @serial * @see #clone() * @see java.awt.GridBagConstraints#ipady @@ -241,7 +241,7 @@ final class GridBagBuilder { * least its minimum height plus <code>ipady</code> pixels. * <p> * The default value is 0. - * + * * @serial * @see #clone() * @see java.awt.GridBagConstraints#ipadx @@ -292,7 +292,6 @@ final class GridBagBuilder { final int gridheight, final double weightx, final double weighty, final int anchor, final int fill, final Insets insets, final int ipadx, final int ipady) { - super(); this.gridx = gridx; this.gridy = gridy; this.gridwidth = gridwidth; diff --git a/src/main/java/sevenUnitsGUI/PrefixSearchRule.java b/src/main/java/sevenUnitsGUI/PrefixSearchRule.java index 2ea0923..73d12bc 100644 --- a/src/main/java/sevenUnitsGUI/PrefixSearchRule.java +++ b/src/main/java/sevenUnitsGUI/PrefixSearchRule.java @@ -73,7 +73,7 @@ public final class PrefixSearchRule implements * @since 2022-07-06 * @since v0.4.0 */ - public static final PrefixSearchRule getCoherentOnlyRule( + public static PrefixSearchRule getCoherentOnlyRule( Set<UnitPrefix> prefixes) { return new PrefixSearchRule(prefixes, u -> u.isCoherent() && !u.getName().equals("kilogram")); @@ -87,19 +87,14 @@ public final class PrefixSearchRule implements * @since 2022-07-06 * @since v0.4.0 */ - public static final PrefixSearchRule getUniversalRule( - Set<UnitPrefix> prefixes) { + public static PrefixSearchRule getUniversalRule(Set<UnitPrefix> prefixes) { return new PrefixSearchRule(prefixes, u -> true); } - /** - * The set of prefixes that will be applied to the unit. - */ + /** The set of prefixes that will be applied to the unit. */ private final Set<UnitPrefix> prefixes; - /** - * Determines which units are given prefixes. - */ + /** Determines which units are given prefixes. */ private final Predicate<LinearUnit> prefixableUnitRule; /** @@ -118,8 +113,8 @@ public final class PrefixSearchRule implements @Override public Map<String, LinearUnit> apply(Entry<String, LinearUnit> t) { final Map<String, LinearUnit> outputUnits = new HashMap<>(); - final String originalName = t.getKey(); - final LinearUnit originalUnit = t.getValue(); + final var originalName = t.getKey(); + final var originalUnit = t.getValue(); outputUnits.put(originalName, originalUnit); if (this.prefixableUnitRule.test(originalUnit)) { for (final UnitPrefix prefix : this.prefixes) { @@ -136,7 +131,7 @@ public final class PrefixSearchRule implements return true; if (!(obj instanceof PrefixSearchRule)) return false; - final PrefixSearchRule other = (PrefixSearchRule) obj; + final var other = (PrefixSearchRule) obj; return Objects.equals(this.prefixableUnitRule, other.prefixableUnitRule) && Objects.equals(this.prefixes, other.prefixes); } diff --git a/src/main/java/sevenUnitsGUI/Presenter.java b/src/main/java/sevenUnitsGUI/Presenter.java index 9913e89..7fd979a 100644 --- a/src/main/java/sevenUnitsGUI/Presenter.java +++ b/src/main/java/sevenUnitsGUI/Presenter.java @@ -86,11 +86,11 @@ public final class Presenter { * </ul> */ static final String DEFAULT_LOCALE = "en"; - + 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. * @@ -112,14 +112,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); } - + private static String displayRuleToString( Function<UncertainDouble, String> numberDisplayRule) { if (numberDisplayRule instanceof FixedDecimals) @@ -128,12 +128,11 @@ public final class Presenter { if (numberDisplayRule instanceof FixedPrecision) return String.format("FIXED_PRECISION %d", ((FixedPrecision) numberDisplayRule).significantFigures()); - else if (numberDisplayRule instanceof UncertaintyBased) + if (numberDisplayRule instanceof UncertaintyBased) return "UNCERTAINTY_BASED"; - else - return numberDisplayRule.toString(); + return numberDisplayRule.toString(); } - + /** * Determines where to wrap {@code toWrap} with a max line length of * {@code maxLineLength}. If no good spot is found, returns -1. @@ -148,7 +147,7 @@ public final class Presenter { } return -1; } - + /** * Gets the text of a resource file as a set of strings (each one is one line * of the text). @@ -160,7 +159,7 @@ public final class Presenter { */ private static List<String> getLinesFromResource(String filename) { final List<String> lines = new ArrayList<>(); - + try (var stream = inputStream(filename); var scanner = new Scanner(stream)) { while (scanner.hasNextLine()) { @@ -170,10 +169,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. * @@ -185,7 +184,7 @@ public final class Presenter { 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. @@ -196,38 +195,37 @@ public final class Presenter { 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"; - else if (PrefixSearchRule.ALL_METRIC_PREFIXES.equals(searchRule)) + if (PrefixSearchRule.ALL_METRIC_PREFIXES.equals(searchRule)) return "ALL_METRIC_PREFIXES"; - else - return searchRule.toString(); + return searchRule.toString(); } - + /** * @return true iff a and b have any elements in common * @since 2022-04-19 @@ -240,22 +238,20 @@ 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"); - else - return Path.of(envFolder); + return Path.of(envFolder); } final var envFolder = System.getenv("XDG_CONFIG_HOME"); if (envFolder == null || "".equals(envFolder)) return Path.of(System.getenv("HOME"), ".config"); - else - return Path.of(envFolder); + return Path.of(envFolder); } - + /** * @return {@code line} with any comments removed. * @since 2021-03-13 @@ -265,7 +261,7 @@ public final class Presenter { final var index = line.indexOf('#'); return index == -1 ? line : line.substring(0, index); } - + /** * Wraps a string, ensuring no line is longer than {@code maxLineLength}. * @@ -290,23 +286,21 @@ public final class Presenter { wrapped.append(remaining); return wrapped.toString(); } - - /** - * The view that this presenter communicates with - */ + + /** 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 @@ -314,60 +308,60 @@ 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; - + /** 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 * 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; - + /** * 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 * @@ -379,40 +373,40 @@ public final class Presenter { this.view = view; this.database = new UnitDatabase(); this.metricExceptions = new HashSet<>(); - + this.locales = this.loadLocales(); this.userLocale = DEFAULT_LOCALE; - + // set default settings temporarily if (Files.exists(CONFIG_FILE)) { this.loadSettings(CONFIG_FILE); } - + this.reloadData(); - + // print out unit counts 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 String fileName = file.getName(file.getNameCount() - 1).toString(); - final String localeName = fileName.substring(0, fileName.length() - 4); - try (Stream<String> lines = Files.lines(file)) { + 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 String[] parts = line.split("=", 2); + final var parts = line.split("=", 2); if (parts.length < 2) return; - + locale.put(parts[0], parts[1]); } - + /** * Applies a search rule to an entry in a name-unit map. * @@ -433,7 +427,7 @@ public final class Presenter { } 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. @@ -450,10 +444,10 @@ public final class Presenter { throw new UnsupportedOperationException( "This function can only be called when the view is an ExpressionConversionView"); final var xcview = (ExpressionConversionView) this.view; - + final var fromExpression = xcview.getFromExpression(); final var toExpression = xcview.getToExpression(); - + // expressions must not be empty if (fromExpression.isEmpty()) { this.view.showErrorMessage("Parse Error", @@ -465,7 +459,7 @@ public final class Presenter { "Please enter a unit expression in the To: box."); return; } - + final Optional<UnitConversionRecord> uc; if (this.database.containsUnitSetName(toExpression)) { uc = this.convertExpressionToNamedMultiUnit(fromExpression, @@ -476,10 +470,10 @@ public final class Presenter { } else { uc = this.convertExpressionToExpression(fromExpression, toExpression); } - + uc.ifPresent(xcview::showExpressionConversionOutput); } - + /** * Converts a unit expression to another expression. * @@ -508,7 +502,7 @@ public final class Presenter { "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", @@ -517,7 +511,7 @@ public final class Presenter { 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) { @@ -527,13 +521,13 @@ public final class Presenter { 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. @@ -551,7 +545,7 @@ public final class Presenter { "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 { @@ -570,7 +564,7 @@ public final class Presenter { return Optional.empty(); } } - + final List<LinearUnitValue> toValues; try { toValues = from.convertToMultiple(toUnits); @@ -579,12 +573,12 @@ public final class Presenter { "Invalid units separated by ';': " + e.getMessage()); return Optional.empty(); } - + final var toExpression = this.linearUnitValueSumToString(toValues); return Optional.of( UnitConversionRecord.valueOf(fromExpression, toExpression, "", "")); } - + /** * 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. @@ -602,7 +596,7 @@ public final class Presenter { "Could not recognize text in From entry: " + e.getMessage()); return Optional.empty(); } - + final var toUnits = this.database.getUnitSet(toName); final List<LinearUnitValue> toValues; try { @@ -612,12 +606,12 @@ public final class Presenter { "Invalid units separated by ';': " + e.getMessage()); return Optional.empty(); } - + 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. @@ -634,36 +628,33 @@ public final class Presenter { 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()) { - fromUnitString = fromUnitOptional.orElseThrow(); - } else { + if (!fromUnitOptional.isPresent()) { this.view.showErrorMessage("Unit Selection Error", "Please specify a From unit"); return; } - if (toUnitOptional.isPresent()) { - toUnitString = toUnitOptional.orElseThrow(); - } else { + fromUnitString = fromUnitOptional.orElseThrow(); + if (!toUnitOptional.isPresent()) { this.view.showErrorMessage("Unit Selection Error", "Please specify a To unit"); return; } - + toUnitString = toUnitOptional.orElseThrow(); + // convert strings to data, checking if anything is invalid final Unit fromUnit; final UncertainDouble uncertainValue; - - if (this.database.containsUnitName(fromUnitString)) { - fromUnit = this.database.getUnit(fromUnitString); - } else + + 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) { @@ -683,7 +674,7 @@ public final class Presenter { } else throw this.viewError("Nonexistent To unit: %s", toUnitString); } - + private UnitConversionRecord convertUnitToMulti(String fromUnitString, String inputValueString, Unit fromUnit, List<LinearUnit> toMulti, UncertainDouble uncertainValue) { @@ -692,7 +683,7 @@ public final class Presenter { throw this.viewError("Could not convert between %s and %s", fromUnit, toUnit); } - + final LinearUnitValue initValue; if (fromUnit instanceof LinearUnit) { final var fromLinear = (LinearUnit) fromUnit; @@ -701,21 +692,21 @@ public final class Presenter { initValue = UnitValue.of(fromUnit, uncertainValue.value()) .convertToBase(NameSymbol.EMPTY); } - + final var converted = initValue.convertToMultiple(toMulti); final var toExpression = this.linearUnitValueSumToString(converted); return UnitConversionRecord.valueOf(fromUnitString, toExpression, inputValueString, ""); - + } - + 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; @@ -725,21 +716,21 @@ public final class Presenter { 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 @@ -748,44 +739,44 @@ public final class Presenter { 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 Path customFilepath = Presenter + final var customFilepath = Presenter .pathFromConfig("about/" + this.userLocale + ".txt"); if (Files.exists(customFilepath)) { - try (Stream<String> lines = Files.lines(customFilepath)) { + try (var lines = Files.lines(customFilepath)) { return this.formatAboutText(lines); } catch (final IOException e) { - final String filename = String.format("/about/%s.txt", + final var filename = String.format("/about/%s.txt", this.userLocale); return this.formatAboutText( Presenter.getLinesFromResource(filename).stream()); } - } else if (LOCAL_LOCALES.contains(this.userLocale)) { - final String filename = String.format("/about/%s.txt", + } + if (LOCAL_LOCALES.contains(this.userLocale)) { + final var filename = String.format("/about/%s.txt", this.userLocale); return this.formatAboutText( Presenter.getLinesFromResource(filename).stream()); - } else { - final String filename = String.format("/about/%s.txt", DEFAULT_LOCALE); - 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 @@ -794,7 +785,7 @@ public final class Presenter { public Set<String> getAvailableLocales() { return this.locales.keySet(); } - + /** * Gets a name for this dimension using the database * @@ -810,7 +801,7 @@ public final class Presenter { .filter(d -> d.equals(dimension)).findAny().map(Nameable::getName) .orElse(dimension.toString(Nameable::getName)); } - + /** * 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 @@ -824,7 +815,7 @@ public final class Presenter { 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 @@ -834,7 +825,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 @@ -845,7 +836,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 @@ -854,7 +845,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 @@ -863,7 +854,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 @@ -873,7 +864,7 @@ public final class Presenter { return PrefixSearchRule.getCoherentOnlyRule( new HashSet<>(this.database.prefixMap(true).values())); } - + /** * @return user's selected locale * @since 2025-02-21 @@ -882,7 +873,7 @@ public final class Presenter { public String getUserLocale() { return this.userLocale; } - + /** * @return the view associated with this presenter * @since 2022-04-19 @@ -891,7 +882,7 @@ public final class Presenter { 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. @@ -910,7 +901,7 @@ public final class Presenter { errorMessage); } } - + /** * @return whether or not the provided unit is semi-metric (i.e. an * exception) @@ -927,7 +918,7 @@ public final class Presenter { && this.metricExceptions.contains(symbol.orElseThrow()) || sharesAnyElements(this.metricExceptions, u.getOtherNames()); } - + /** * 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 @@ -945,10 +936,8 @@ public final class Presenter { return integerPart + " + " + this.numberDisplayRule.apply(last.getValue()) + " " + last.getUnit(); } - - /** - * Load units, prefixes and dimensions from the default files. - */ + + /** Load units, prefixes and dimensions from the default files. */ private void loadDefaultData() { // load units and prefixes try (final var units = inputStream(DEFAULT_UNITS_FILEPATH)) { @@ -956,7 +945,7 @@ public final class Presenter { } 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( @@ -964,7 +953,7 @@ public final class Presenter { } catch (final IOException e) { throw new AssertionError("Loading of dimensionfile.txt failed.", e); } - + // load metric exceptions try { try (var exceptions = inputStream(DEFAULT_EXCEPTIONS_FILEPATH); @@ -981,7 +970,7 @@ public final class Presenter { e); } } - + private void loadExceptionFile(Path exceptionFile) { try (var lines = Files.lines(exceptionFile)) { lines.map(Presenter::withoutComments) @@ -992,7 +981,7 @@ public final class Presenter { + exceptionFile + "\": " + e.getLocalizedMessage()); } } - + /** * Loads all available locales, including custom ones, into a map. * @@ -1002,14 +991,14 @@ public final class Presenter { final Map<String, Map<String, String>> locales = new HashMap<>(); for (final String localeName : LOCAL_LOCALES) { final Map<String, String> locale = new HashMap<>(); - final String filename = "/locales/" + localeName + ".txt"; + 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 (Stream<Path> files = Files.list(USER_LOCALES_DIR)) { + try (var files = Files.list(USER_LOCALES_DIR)) { files.forEach(localeFile -> { try { this.addLocaleFile(locales, localeFile); @@ -1023,7 +1012,7 @@ public final class Presenter { } return locales; } - + /** * Loads settings from the user's settings file and applies them to the * presenter. @@ -1036,11 +1025,11 @@ public final class Presenter { 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 @@ -1090,12 +1079,12 @@ public final class Presenter { break; } } - + if (this.view.getPresenter() != null) { this.updateView(); } } - + /** * @return a message showing how much stuff has been loaded * @since 2024-08-22 @@ -1120,19 +1109,19 @@ public final class Presenter { .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; } - + /** * Completes creation of the presenter. This part of the initialization * depends on the view's functions, so it cannot be run if the components @@ -1147,11 +1136,11 @@ public final class Presenter { final var ucview = (UnitConversionView) this.view; ucview.setDimensionNames(this.database.dimensionMap().keySet()); } - + this.updateView(); this.view.updateText(); } - + void prefixSelected() { final var selectedPrefixName = this.view.getViewedPrefixName(); final Optional<UnitPrefix> selectedPrefix = selectedPrefixName @@ -1162,26 +1151,24 @@ public final class Presenter { .ifPresent(prefix -> this.view.showPrefix(prefix.getNameSymbol(), String.valueOf(prefix.getMultiplier()))); } - - /** - * Clears then reloads all unit, prefix, dimension and exception data. - */ + + /** 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. @@ -1199,10 +1186,10 @@ public final class Presenter { return false; } } - + return this.writeSettings(CONFIG_FILE); } - + private void setDisplayRuleFromString(String ruleString) { final var tokens = ruleString.split(" "); switch (tokens[0]) { @@ -1223,7 +1210,7 @@ public final class Presenter { break; } } - + /** * @param numberDisplayRule the new rule that will be used by this presenter * to convert numbers into strings @@ -1234,7 +1221,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 @@ -1246,7 +1233,7 @@ public final class Presenter { Function<String, UncertainDouble> numberParsingRule) { this.numberParsingRule = numberParsingRule; } - + /** * @param oneWayConversionEnabled whether not one-way conversion should be * enabled @@ -1258,7 +1245,7 @@ public final class Presenter { this.oneWayConversionEnabled = oneWayConversionEnabled; this.updateView(); } - + /** * @param prefixRepetitionRule the rule that determines whether a set of * prefixes is valid @@ -1270,7 +1257,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 @@ -1283,7 +1270,7 @@ public final class Presenter { Function<Map.Entry<String, LinearUnit>, Map<String, LinearUnit>> searchRule) { this.searchRule = searchRule; } - + private void setSearchRuleFromString(String ruleString) { switch (ruleString) { case "NO_PREFIXES": @@ -1301,7 +1288,7 @@ public final class Presenter { ruleString); } } - + /** * @param showDuplicateUnits whether or not duplicate units should be shown * @since 2022-03-30 @@ -1311,7 +1298,7 @@ public final class Presenter { 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) @@ -1323,11 +1310,11 @@ public final class Presenter { 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 */ @@ -1336,7 +1323,7 @@ public final class Presenter { this.reloadData(); this.updateView(); } - + /** * Sets the user's locale, updating the view. * @@ -1346,7 +1333,7 @@ public final class Presenter { this.userLocale = userLocale; this.view.updateText(); } - + /** * Shows a unit in the unit viewer * @@ -1363,7 +1350,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. @@ -1380,7 +1367,7 @@ public final class Presenter { : null); selectedUnit.ifPresent(this::showUnit); } - + /** * Updates the view's From and To units, if it has some * @@ -1391,20 +1378,20 @@ public final class Presenter { if (this.view instanceof UnitConversionView) { final var 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(); var unitSets = this.database.unitSetMap().entrySet().stream(); - + // filter by dimension, if one is selected if (selectedDimensionName.isPresent()) { final var viewDimension = this.database @@ -1416,7 +1403,7 @@ public final class Presenter { unitSets = unitSets.filter(us -> viewDimension .equals(us.getValue().get(0).getDimension())); } - + // filter by unit type, if desired if (this.oneWayConversionEnabled) { fromUnits = fromUnits.filter(u -> UnitType.getType(u.getValue(), @@ -1427,7 +1414,7 @@ public final class Presenter { 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())); @@ -1439,14 +1426,12 @@ public final class Presenter { ucview.setToUnitNames(toNames); } } - - /** - * @return true iff the default datafiles are being used - */ + + /** @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 @@ -1459,7 +1444,7 @@ public final class Presenter { return new AssertionError("View Programming Error (from " + this.view + "): " + String.format(message, args)); } - + /** * Saves the presenter's settings to the user settings file. * diff --git a/src/main/java/sevenUnitsGUI/SearchBoxList.java b/src/main/java/sevenUnitsGUI/SearchBoxList.java index 43a57ce..bddce04 100644 --- a/src/main/java/sevenUnitsGUI/SearchBoxList.java +++ b/src/main/java/sevenUnitsGUI/SearchBoxList.java @@ -49,7 +49,7 @@ final class SearchBoxList<E> extends JPanel { /** * The text to place in an empty search box. - * + * * @since 2019-04-13 * @since v0.2.0 */ @@ -57,7 +57,7 @@ final class SearchBoxList<E> extends JPanel { /** * The color to use for an empty foreground. - * + * * @since 2019-04-13 * @since v0.2.0 */ @@ -82,7 +82,7 @@ final class SearchBoxList<E> extends JPanel { /** * Creates an empty SearchBoxList - * + * * @since 2022-02-19 * @since v0.4.0 */ @@ -92,7 +92,7 @@ final class SearchBoxList<E> extends JPanel { /** * Creates the {@code SearchBoxList}. - * + * * @param itemsToFilter items to put in the list * @since 2019-04-14 * @since v0.2.0 @@ -103,12 +103,12 @@ final class SearchBoxList<E> extends JPanel { /** * Creates the {@code SearchBoxList}. - * + * * @param itemsToFilter items to put in the list * @param defaultOrdering default ordering of items after filtration * (null=Comparable) * @param caseSensitive whether or not the filtration is case-sensitive - * + * * @since 2019-04-13 * @since v0.2.0 */ @@ -149,7 +149,7 @@ final class SearchBoxList<E> extends JPanel { /** * Adds an additional filter for searching. - * + * * @param filter filter to add. * @since 2019-04-13 * @since v0.2.0 @@ -160,7 +160,7 @@ final class SearchBoxList<E> extends JPanel { /** * Resets the search filter. - * + * * @since 2019-04-13 * @since v0.2.0 */ @@ -183,7 +183,7 @@ final class SearchBoxList<E> extends JPanel { * @since 2019-04-14 * @since v0.2.0 */ - public final JTextField getSearchBox() { + public JTextField getSearchBox() { return this.searchBox; } @@ -197,9 +197,8 @@ final class SearchBoxList<E> extends JPanel { private Predicate<E> getSearchFilter(final String searchText) { if (this.caseSensitive) return item -> item.toString().contains(searchText); - else - return item -> item.toString().toLowerCase() - .contains(searchText.toLowerCase()); + return item -> item.toString().toLowerCase() + .contains(searchText.toLowerCase()); } /** @@ -207,7 +206,7 @@ final class SearchBoxList<E> extends JPanel { * @since 2019-04-14 * @since v0.2.0 */ - public final JList<E> getSearchList() { + public JList<E> getSearchList() { return this.searchItems; } @@ -231,16 +230,16 @@ final class SearchBoxList<E> extends JPanel { /** * Re-applies the filters. - * + * * @since 2019-04-13 * @since v0.2.0 */ public void reapplyFilter() { - final String searchText = this.searchBoxEmpty ? "" + final var searchText = this.searchBoxEmpty ? "" : this.searchBox.getText(); - final FilterComparator<E> comparator = new FilterComparator<>(searchText, + final var comparator = new FilterComparator<E>(searchText, this.defaultOrdering, this.caseSensitive); - final Predicate<E> searchFilter = this.getSearchFilter(searchText); + final var searchFilter = this.getSearchFilter(searchText); this.listModel.clear(); this.itemsToFilter.forEach(item -> { @@ -258,7 +257,7 @@ final class SearchBoxList<E> extends JPanel { /** * Runs whenever the search box gains focus. - * + * * @param e focus event * @since 2019-04-13 * @since v0.2.0 @@ -273,7 +272,7 @@ final class SearchBoxList<E> extends JPanel { /** * Runs whenever the search box loses focus. - * + * * @param e focus event * @since 2019-04-13 * @since v0.2.0 @@ -291,7 +290,7 @@ final class SearchBoxList<E> extends JPanel { * <p> * Reapplies the search filter, and custom filters. * </p> - * + * * @since 2019-04-14 * @since v0.2.0 */ @@ -299,11 +298,11 @@ final class SearchBoxList<E> extends JPanel { if (this.searchBoxFocused) { this.searchBoxEmpty = this.searchBox.getText().equals(""); } - final String searchText = this.searchBoxEmpty ? "" + final var searchText = this.searchBoxEmpty ? "" : this.searchBox.getText(); - final FilterComparator<E> comparator = new FilterComparator<>(searchText, + final var comparator = new FilterComparator<E>(searchText, this.defaultOrdering, this.caseSensitive); - final Predicate<E> searchFilter = this.getSearchFilter(searchText); + final var searchFilter = this.getSearchFilter(searchText); // initialize list with items that match the filter then sort this.listModel.clear(); @@ -336,7 +335,7 @@ final class SearchBoxList<E> extends JPanel { /** * Manually updates the search box's item list. - * + * * @since 2020-08-27 * @since v0.3.0 */ diff --git a/src/main/java/sevenUnitsGUI/StandardDisplayRules.java b/src/main/java/sevenUnitsGUI/StandardDisplayRules.java index d710117..16d31ae 100644 --- a/src/main/java/sevenUnitsGUI/StandardDisplayRules.java +++ b/src/main/java/sevenUnitsGUI/StandardDisplayRules.java @@ -43,9 +43,7 @@ public final class StandardDisplayRules { /** Regular expression used for converting this to a string. */ public static final Pattern TO_STRING_PATTERN = Pattern .compile("Round to (\\d+) decimal places"); - /** - * The number of places to round to. - */ + /** The number of places to round to. */ private final int decimalPlaces; /** @@ -79,7 +77,7 @@ public final class StandardDisplayRules { return true; if (!(obj instanceof FixedDecimals)) return false; - final FixedDecimals other = (FixedDecimals) obj; + final var other = (FixedDecimals) obj; if (this.decimalPlaces != other.decimalPlaces) return false; return true; @@ -108,9 +106,7 @@ public final class StandardDisplayRules { public static final Pattern TO_STRING_PATTERN = Pattern .compile("Round to (\\d+) significant figures"); - /** - * The number of significant figures to round to. - */ + /** The number of significant figures to round to. */ private final MathContext mathContext; /** @@ -135,7 +131,7 @@ public final class StandardDisplayRules { return true; if (!(obj instanceof FixedPrecision)) return false; - final FixedPrecision other = (FixedPrecision) obj; + final var other = (FixedPrecision) obj; if (this.mathContext == null) { if (other.mathContext != null) return false; @@ -202,7 +198,7 @@ public final class StandardDisplayRules { * @since 2022-04-18 * @since v0.4.0 */ - public static final FixedDecimals fixedDecimals(int decimalPlaces) { + public static FixedDecimals fixedDecimals(int decimalPlaces) { return new FixedDecimals(decimalPlaces); } @@ -213,7 +209,7 @@ public final class StandardDisplayRules { * @since 2022-04-18 * @since v0.4.0 */ - public static final FixedPrecision fixedPrecision(int significantFigures) { + public static FixedPrecision fixedPrecision(int significantFigures) { return new FixedPrecision(significantFigures); } @@ -227,7 +223,7 @@ public final class StandardDisplayRules { * @since 2021-12-24 * @since v0.4.0 */ - public static final Function<UncertainDouble, String> getStandardRule( + public static Function<UncertainDouble, String> getStandardRule( String ruleToString) { if (UNCERTAINTY_BASED_ROUNDING_RULE.toString().equals(ruleToString)) return UNCERTAINTY_BASED_ROUNDING_RULE; @@ -236,13 +232,13 @@ public final class StandardDisplayRules { final var placesMatch = FixedDecimals.TO_STRING_PATTERN .matcher(ruleToString); if (placesMatch.matches()) - return new FixedDecimals(Integer.valueOf(placesMatch.group(1))); + return new FixedDecimals(Integer.parseInt(placesMatch.group(1))); // test if it is a fixed-sig-fig rule final var sigFigMatch = FixedPrecision.TO_STRING_PATTERN .matcher(ruleToString); if (sigFigMatch.matches()) - return new FixedPrecision(Integer.valueOf(sigFigMatch.group(1))); + return new FixedPrecision(Integer.parseInt(sigFigMatch.group(1))); throw new IllegalArgumentException( "Provided string does not match any given rules."); @@ -253,7 +249,7 @@ public final class StandardDisplayRules { * @since 2022-04-18 * @since v0.4.0 */ - public static final UncertaintyBased uncertaintyBased() { + public static UncertaintyBased uncertaintyBased() { return UNCERTAINTY_BASED_ROUNDING_RULE; } diff --git a/src/main/java/sevenUnitsGUI/TabbedView.java b/src/main/java/sevenUnitsGUI/TabbedView.java index 1afaf33..8be58f5 100644 --- a/src/main/java/sevenUnitsGUI/TabbedView.java +++ b/src/main/java/sevenUnitsGUI/TabbedView.java @@ -81,7 +81,7 @@ final class TabbedView implements ExpressionConversionView, UnitConversionView { */ private static final class JComboBoxItemSet<E> extends AbstractSet<E> { private final JComboBox<E> comboBox; - + /** * @param comboBox combo box to get items from * @since 2022-02-19 @@ -90,35 +90,34 @@ final class TabbedView implements ExpressionConversionView, UnitConversionView { public JComboBoxItemSet(JComboBox<E> comboBox) { this.comboBox = comboBox; } - + @Override public Iterator<E> iterator() { return new Iterator<>() { private int index = 0; - + @Override public boolean hasNext() { return this.index < JComboBoxItemSet.this.size(); } - + @Override public E next() { if (this.hasNext()) return JComboBoxItemSet.this.comboBox.getItemAt(this.index++); - else - throw new NoSuchElementException( - "Iterator has finished iteration"); + throw new NoSuchElementException( + "Iterator has finished iteration"); } }; } - + @Override public int size() { return this.comboBox.getItemCount(); } - + } - + /** * The standard types of rounding, corresponding to the options on the * TabbedView's settings panel. @@ -126,7 +125,7 @@ final class TabbedView implements ExpressionConversionView, UnitConversionView { * @since 2022-04-18 * @since v0.4.0 */ - private static enum StandardRoundingType { + private enum StandardRoundingType { /** * Rounds to a fixed number of significant digits. Precision is used, * representing the number of significant digits to round to. @@ -143,7 +142,7 @@ final class TabbedView implements ExpressionConversionView, UnitConversionView { */ UNCERTAINTY; } - + /** * Creates a TabbedView. * @@ -157,14 +156,14 @@ final class TabbedView implements ExpressionConversionView, UnitConversionView { @SuppressWarnings("unused") final View view = new TabbedView(); } - + /** The Presenter that handles this View */ final Presenter presenter; /** The frame that this view lives on */ final JFrame frame; /** The tabbed pane that contains all of the components */ final JTabbedPane masterPane; - + // DIMENSION-BASED CONVERTER /** The combo box that selects dimensions */ final JComboBox<String> dimensionSelector; @@ -178,7 +177,7 @@ final class TabbedView implements ExpressionConversionView, UnitConversionView { final JButton convertUnitButton; /** The output area in the dimension-based converter */ final JTextArea unitOutput; - + // EXPRESSION-BASED CONVERTER /** The "From" entry in the conversion panel */ final JTextField fromEntry; @@ -188,7 +187,7 @@ final class TabbedView implements ExpressionConversionView, UnitConversionView { final JButton convertExpressionButton; /** The output area in the conversion panel */ final JTextArea expressionOutput; - + // UNIT AND PREFIX VIEWERS /** The searchable list of unit names in the unit viewer */ private final SearchBoxList<String> unitNameList; @@ -198,18 +197,18 @@ final class TabbedView implements ExpressionConversionView, UnitConversionView { private final JTextArea unitTextBox; /** The text box for prefix data in the prefix viewer */ private final JTextArea prefixTextBox; - + // INFO & SETTINGS STUFF final JTextArea infoTextArea; private final JComboBox<String> localeSelector; private StandardRoundingType roundingType; private int precision; - + private final Map<String, Consumer<String>> localizedTextSetters; - + /** * Creates the view and makes it visible to the user - * + * * @since 2022-02-19 * @since v0.4.0 */ @@ -223,180 +222,183 @@ final class TabbedView implements ExpressionConversionView, UnitConversionView { System.err.println("Failed to enable system look-and-feel."); e.printStackTrace(); } - + // initialize important components this.presenter = new Presenter(this); this.frame = new JFrame("7Units (Unlocalized)"); this.frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); - + // master components (those that contain everything else within them) this.masterPane = new JTabbedPane(); this.frame.add(this.masterPane); - + this.localizedTextSetters = new HashMap<>(); - + // ============ UNIT CONVERSION TAB ============ - final JPanel convertUnitPanel = new JPanel(); + final var convertUnitPanel = new JPanel(); this.masterPane.addTab("Convert Units", convertUnitPanel); this.localizedTextSetters.put("tv.convert_units.title", txt -> this.masterPane.setTitleAt(0, txt)); this.masterPane.setMnemonicAt(0, KeyEvent.VK_U); convertUnitPanel.setLayout(new BorderLayout()); - + { // panel for input part - final JPanel inputPanel = new JPanel(); + final var inputPanel = new JPanel(); convertUnitPanel.add(inputPanel, BorderLayout.CENTER); inputPanel.setLayout(new GridLayout(1, 3)); inputPanel.setBorder(new EmptyBorder(6, 6, 3, 6)); - + this.fromSearch = new SearchBoxList<>(); inputPanel.add(this.fromSearch); - - final JPanel inBetweenPanel = new JPanel(); + + final var inBetweenPanel = new JPanel(); inputPanel.add(inBetweenPanel); inBetweenPanel.setLayout(new BorderLayout()); - + this.dimensionSelector = new JComboBox<>(); inBetweenPanel.add(this.dimensionSelector, BorderLayout.PAGE_START); this.dimensionSelector .addItemListener(e -> this.presenter.updateView()); - - final JLabel arrowLabel = new JLabel("-->"); + + final var arrowLabel = new JLabel("-->"); inBetweenPanel.add(arrowLabel, BorderLayout.CENTER); arrowLabel.setHorizontalAlignment(SwingConstants.CENTER); - + this.toSearch = new SearchBoxList<>(); inputPanel.add(this.toSearch); } - + { // panel for submit and output, and also value entry - final JPanel outputPanel = new JPanel(); + final var outputPanel = new JPanel(); convertUnitPanel.add(outputPanel, BorderLayout.PAGE_END); outputPanel.setLayout(new BorderLayout()); outputPanel.setBorder(new EmptyBorder(3, 6, 6, 6)); - - final JLabel valuePrompt = new JLabel(); - this.localizedTextSetters.put("tv.convert_units.value_prompt", + + final var valuePrompt = new JLabel(); + this.localizedTextSetters.put("tv.convert_units.value_prompt", valuePrompt::setText); outputPanel.add(valuePrompt, BorderLayout.LINE_START); - + this.valueInput = new JTextField(); outputPanel.add(this.valueInput, BorderLayout.CENTER); - + // conversion button this.convertUnitButton = new JButton("Convert"); - this.localizedTextSetters.put("tv.convert_units.convert_btn", + this.localizedTextSetters.put("tv.convert_units.convert_btn", this.convertUnitButton::setText); outputPanel.add(this.convertUnitButton, BorderLayout.LINE_END); this.convertUnitButton .addActionListener(e -> this.presenter.convertUnits()); this.convertUnitButton.setMnemonic(KeyEvent.VK_ENTER); - + // conversion output this.unitOutput = new JTextArea(2, 32); outputPanel.add(this.unitOutput, BorderLayout.PAGE_END); this.unitOutput.setEditable(false); } - + // ============ EXPRESSION CONVERSION TAB ============ - final JPanel convertExpressionPanel = new JPanel(); + final var convertExpressionPanel = new JPanel(); this.masterPane.addTab("Convert Unit Expressions", convertExpressionPanel); - this.localizedTextSetters.put("tv.convert_expressions.title", + this.localizedTextSetters.put("tv.convert_expressions.title", txt -> this.masterPane.setTitleAt(1, txt)); this.masterPane.setMnemonicAt(1, KeyEvent.VK_E); convertExpressionPanel.setLayout(new GridLayout(4, 1)); - + // from and to expressions this.fromEntry = new JTextField(); convertExpressionPanel.add(this.fromEntry); - this.localizedTextSetters.put("tv.convert_expressions.from", - txt -> this.fromEntry.setBorder(BorderFactory.createTitledBorder(txt))); - + this.localizedTextSetters.put("tv.convert_expressions.from", + txt -> this.fromEntry + .setBorder(BorderFactory.createTitledBorder(txt))); + this.toEntry = new JTextField(); convertExpressionPanel.add(this.toEntry); - this.localizedTextSetters.put("tv.convert_expressions.to", - txt -> this.toEntry.setBorder(BorderFactory.createTitledBorder(txt))); - + this.localizedTextSetters.put("tv.convert_expressions.to", + txt -> this.toEntry + .setBorder(BorderFactory.createTitledBorder(txt))); + // button to convert this.convertExpressionButton = new JButton(); this.localizedTextSetters.put("tv.convert_expressions.convert_btn", this.convertExpressionButton::setText); convertExpressionPanel.add(this.convertExpressionButton); - + this.convertExpressionButton .addActionListener(e -> this.presenter.convertExpressions()); this.convertExpressionButton.setMnemonic(KeyEvent.VK_ENTER); - + // output of conversion this.expressionOutput = new JTextArea(2, 32); convertExpressionPanel.add(this.expressionOutput); - this.localizedTextSetters.put("tv.convert_expressions.output", - txt -> this.expressionOutput.setBorder(BorderFactory.createTitledBorder(txt))); + this.localizedTextSetters.put("tv.convert_expressions.output", + txt -> this.expressionOutput + .setBorder(BorderFactory.createTitledBorder(txt))); this.expressionOutput.setEditable(false); - + // =========== UNIT VIEWER =========== - final JPanel unitLookupPanel = new JPanel(); + final var unitLookupPanel = new JPanel(); this.masterPane.addTab("Unit Viewer", unitLookupPanel); - this.localizedTextSetters.put("tv.unit_viewer.title", + this.localizedTextSetters.put("tv.unit_viewer.title", txt -> this.masterPane.setTitleAt(2, txt)); this.masterPane.setMnemonicAt(2, KeyEvent.VK_V); unitLookupPanel.setLayout(new GridLayout()); - + this.unitNameList = new SearchBoxList<>(); unitLookupPanel.add(this.unitNameList); this.unitNameList.getSearchList() .addListSelectionListener(e -> this.presenter.unitNameSelected()); - + // the text box for unit's toString this.unitTextBox = new JTextArea(); unitLookupPanel.add(this.unitTextBox); this.unitTextBox.setEditable(false); this.unitTextBox.setLineWrap(true); - + // ============ PREFIX VIEWER ============= - final JPanel prefixLookupPanel = new JPanel(); + final var prefixLookupPanel = new JPanel(); this.masterPane.addTab("Prefix Viewer", prefixLookupPanel); - this.localizedTextSetters.put("tv.prefix_viewer.title", + this.localizedTextSetters.put("tv.prefix_viewer.title", txt -> this.masterPane.setTitleAt(3, txt)); this.masterPane.setMnemonicAt(3, KeyEvent.VK_P); prefixLookupPanel.setLayout(new GridLayout(1, 2)); - + this.prefixNameList = new SearchBoxList<>(); prefixLookupPanel.add(this.prefixNameList); this.prefixNameList.getSearchList() .addListSelectionListener(e -> this.presenter.prefixSelected()); - + // the text box for prefix's toString this.prefixTextBox = new JTextArea(); prefixLookupPanel.add(this.prefixTextBox); this.prefixTextBox.setEditable(false); this.prefixTextBox.setLineWrap(true); - + // ============ INFO PANEL ============ - - final JPanel infoPanel = new JPanel(); + + final var infoPanel = new JPanel(); this.masterPane.addTab("\uD83D\uDEC8", // info (i) character new JScrollPane(infoPanel)); - + this.infoTextArea = new JTextArea(); this.infoTextArea.setEditable(false); this.infoTextArea.setOpaque(false); infoPanel.add(this.infoTextArea); - + // ============ SETTINGS PANEL ============ this.localeSelector = new JComboBox<>(); this.masterPane.addTab("\u2699", new JScrollPane(this.createSettingsPanel())); this.masterPane.setMnemonicAt(5, KeyEvent.VK_S); - + // ============ FINALIZE CREATION OF VIEW ============ this.presenter.postViewInitialize(); this.updateText(); this.frame.pack(); this.frame.setVisible(true); } - + /** * Creates and returns the settings panel (in its own function to make this * code more organized, as this function is massive!) @@ -405,64 +407,64 @@ final class TabbedView implements ExpressionConversionView, UnitConversionView { * @since v0.4.0 */ private JPanel createSettingsPanel() { - final JPanel settingsPanel = new JPanel(); - + final var settingsPanel = new JPanel(); + settingsPanel .setLayout(new BoxLayout(settingsPanel, BoxLayout.PAGE_AXIS)); - + // ============ ROUNDING SETTINGS ============ { - final JPanel roundingPanel = new JPanel(); + final var roundingPanel = new JPanel(); settingsPanel.add(roundingPanel); - this.localizedTextSetters.put("tv.settings.rounding.title", + this.localizedTextSetters.put("tv.settings.rounding.title", txt -> roundingPanel.setBorder(new TitledBorder(txt))); roundingPanel.setLayout(new GridBagLayout()); - + // rounding rule selection - final ButtonGroup roundingRuleButtons = new ButtonGroup(); + final var roundingRuleButtons = new ButtonGroup(); this.roundingType = this.getPresenterRoundingType() .orElseThrow(() -> new AssertionError( "Presenter loaded non-standard rounding rule")); this.precision = this.getPresenterPrecision().orElse(6); - - final JLabel roundingRuleLabel = new JLabel(); - this.localizedTextSetters.put("tv.settings.rounding.rule", + + final var roundingRuleLabel = new JLabel(); + this.localizedTextSetters.put("tv.settings.rounding.rule", roundingRuleLabel::setText); roundingPanel.add(roundingRuleLabel, new GridBagBuilder(0, 0) .setAnchor(GridBagConstraints.LINE_START).build()); - + // sigDigSlider needs to be first so that the rounding-type buttons can // show and hide it - final JLabel sliderLabel = new JLabel(); - this.localizedTextSetters.put("tv.settings.rounding.precision", + final var sliderLabel = new JLabel(); + this.localizedTextSetters.put("tv.settings.rounding.precision", sliderLabel::setText); sliderLabel.setVisible( this.roundingType != StandardRoundingType.UNCERTAINTY); roundingPanel.add(sliderLabel, new GridBagBuilder(0, 4) .setAnchor(GridBagConstraints.LINE_START).build()); - - final JSlider sigDigSlider = new JSlider(0, 12); + + final var sigDigSlider = new JSlider(0, 12); roundingPanel.add(sigDigSlider, new GridBagBuilder(0, 5) .setAnchor(GridBagConstraints.LINE_START).build()); - + sigDigSlider.setMajorTickSpacing(4); sigDigSlider.setMinorTickSpacing(1); sigDigSlider.setSnapToTicks(true); sigDigSlider.setPaintTicks(true); sigDigSlider.setPaintLabels(true); - + sigDigSlider.setVisible( this.roundingType != StandardRoundingType.UNCERTAINTY); sigDigSlider.setValue(this.precision); - + sigDigSlider.addChangeListener(e -> { this.precision = sigDigSlider.getValue(); this.updatePresenterRoundingRule(); }); - + // significant digit rounding - final JRadioButton fixedPrecision = new JRadioButton(); - this.localizedTextSetters.put("tv.settings.rounding.fixed_sigfig", + final var fixedPrecision = new JRadioButton(); + this.localizedTextSetters.put("tv.settings.rounding.fixed_sigfig", fixedPrecision::setText); if (this.roundingType == StandardRoundingType.SIGNIFICANT_DIGITS) { fixedPrecision.setSelected(true); @@ -476,10 +478,10 @@ final class TabbedView implements ExpressionConversionView, UnitConversionView { roundingRuleButtons.add(fixedPrecision); roundingPanel.add(fixedPrecision, new GridBagBuilder(0, 1) .setAnchor(GridBagConstraints.LINE_START).build()); - + // decimal place rounding - final JRadioButton fixedDecimals = new JRadioButton(); - this.localizedTextSetters.put("tv.settings.rounding.fixed_places", + final var fixedDecimals = new JRadioButton(); + this.localizedTextSetters.put("tv.settings.rounding.fixed_places", fixedDecimals::setText); if (this.roundingType == StandardRoundingType.DECIMAL_PLACES) { fixedDecimals.setSelected(true); @@ -493,10 +495,10 @@ final class TabbedView implements ExpressionConversionView, UnitConversionView { roundingRuleButtons.add(fixedDecimals); roundingPanel.add(fixedDecimals, new GridBagBuilder(0, 2) .setAnchor(GridBagConstraints.LINE_START).build()); - + // scientific rounding - final JRadioButton relativePrecision = new JRadioButton(); - this.localizedTextSetters.put("tv.settings.rounding.uncertainty", + final var relativePrecision = new JRadioButton(); + this.localizedTextSetters.put("tv.settings.rounding.uncertainty", relativePrecision::setText); if (this.roundingType == StandardRoundingType.UNCERTAINTY) { relativePrecision.setSelected(true); @@ -511,24 +513,24 @@ final class TabbedView implements ExpressionConversionView, UnitConversionView { roundingPanel.add(relativePrecision, new GridBagBuilder(0, 3) .setAnchor(GridBagConstraints.LINE_START).build()); } - + // ============ PREFIX REPETITION SETTINGS ============ { - final JPanel prefixRepetitionPanel = new JPanel(); + final var prefixRepetitionPanel = new JPanel(); settingsPanel.add(prefixRepetitionPanel); - this.localizedTextSetters.put("tv.settings.repetition.title", + this.localizedTextSetters.put("tv.settings.repetition.title", txt -> prefixRepetitionPanel.setBorder(new TitledBorder(txt))); prefixRepetitionPanel.setLayout(new GridBagLayout()); - + final var prefixRule = this.getPresenterPrefixRule() .orElseThrow(() -> new AssertionError( "Presenter loaded non-standard prefix rule")); - + // prefix rules - final ButtonGroup prefixRuleButtons = new ButtonGroup(); - - final JRadioButton noRepetition = new JRadioButton(); - this.localizedTextSetters.put("tv.settings.repetition.no", + final var prefixRuleButtons = new ButtonGroup(); + + final var noRepetition = new JRadioButton(); + this.localizedTextSetters.put("tv.settings.repetition.no", noRepetition::setText); if (prefixRule == DefaultPrefixRepetitionRule.NO_REPETITION) { noRepetition.setSelected(true); @@ -541,9 +543,9 @@ final class TabbedView implements ExpressionConversionView, UnitConversionView { prefixRuleButtons.add(noRepetition); prefixRepetitionPanel.add(noRepetition, new GridBagBuilder(0, 0) .setAnchor(GridBagConstraints.LINE_START).build()); - - final JRadioButton noRestriction = new JRadioButton(); - this.localizedTextSetters.put("tv.settings.repetition.any", + + final var noRestriction = new JRadioButton(); + this.localizedTextSetters.put("tv.settings.repetition.any", noRestriction::setText); if (prefixRule == DefaultPrefixRepetitionRule.NO_RESTRICTION) { noRestriction.setSelected(true); @@ -556,9 +558,9 @@ final class TabbedView implements ExpressionConversionView, UnitConversionView { prefixRuleButtons.add(noRestriction); prefixRepetitionPanel.add(noRestriction, new GridBagBuilder(0, 1) .setAnchor(GridBagConstraints.LINE_START).build()); - - final JRadioButton customRepetition = new JRadioButton(); - this.localizedTextSetters.put("tv.settings.repetition.complex", + + final var customRepetition = new JRadioButton(); + this.localizedTextSetters.put("tv.settings.repetition.complex", customRepetition::setText); if (prefixRule == DefaultPrefixRepetitionRule.COMPLEX_REPETITION) { customRepetition.setSelected(true); @@ -572,22 +574,22 @@ final class TabbedView implements ExpressionConversionView, UnitConversionView { prefixRepetitionPanel.add(customRepetition, new GridBagBuilder(0, 2) .setAnchor(GridBagConstraints.LINE_START).build()); } - + // ============ SEARCH SETTINGS ============ { - final JPanel searchingPanel = new JPanel(); + final var searchingPanel = new JPanel(); settingsPanel.add(searchingPanel); - this.localizedTextSetters.put("tv.settings.search.title", + this.localizedTextSetters.put("tv.settings.search.title", txt -> searchingPanel.setBorder(new TitledBorder(txt))); searchingPanel.setLayout(new GridBagLayout()); - + // searching rules - final ButtonGroup searchRuleButtons = new ButtonGroup(); - + final var searchRuleButtons = new ButtonGroup(); + final var searchRule = this.presenter.getSearchRule(); - - final JRadioButton noPrefixes = new JRadioButton(); - this.localizedTextSetters.put("tv.settings.search.no_prefixes", + + final var noPrefixes = new JRadioButton(); + this.localizedTextSetters.put("tv.settings.search.no_prefixes", noPrefixes::setText); noPrefixes.addActionListener(e -> { this.presenter.setSearchRule(PrefixSearchRule.NO_PREFIXES); @@ -597,9 +599,9 @@ final class TabbedView implements ExpressionConversionView, UnitConversionView { searchRuleButtons.add(noPrefixes); searchingPanel.add(noPrefixes, new GridBagBuilder(0, 0) .setAnchor(GridBagConstraints.LINE_START).build()); - - final JRadioButton commonPrefixes = new JRadioButton(); - this.localizedTextSetters.put("tv.settings.search.common_prefixes", + + final var commonPrefixes = new JRadioButton(); + this.localizedTextSetters.put("tv.settings.search.common_prefixes", commonPrefixes::setText); commonPrefixes.addActionListener(e -> { this.presenter.setSearchRule(PrefixSearchRule.COMMON_PREFIXES); @@ -609,9 +611,9 @@ final class TabbedView implements ExpressionConversionView, UnitConversionView { searchRuleButtons.add(commonPrefixes); searchingPanel.add(commonPrefixes, new GridBagBuilder(0, 1) .setAnchor(GridBagConstraints.LINE_START).build()); - - final JRadioButton alwaysInclude = new JRadioButton(); - this.localizedTextSetters.put("tv.settings.search.all_prefixes", + + final var alwaysInclude = new JRadioButton(); + this.localizedTextSetters.put("tv.settings.search.all_prefixes", alwaysInclude::setText); alwaysInclude.addActionListener(e -> { this.presenter @@ -622,7 +624,7 @@ final class TabbedView implements ExpressionConversionView, UnitConversionView { searchRuleButtons.add(alwaysInclude); searchingPanel.add(alwaysInclude, new GridBagBuilder(0, 3) .setAnchor(GridBagConstraints.LINE_START).build()); - + if (PrefixSearchRule.NO_PREFIXES.equals(searchRule)) { noPrefixes.setSelected(true); } else if (PrefixSearchRule.COMMON_PREFIXES.equals(searchRule)) { @@ -634,14 +636,14 @@ final class TabbedView implements ExpressionConversionView, UnitConversionView { this.presenter.saveSettings(); } } - + // ============ OTHER SETTINGS ============ { - final JPanel miscPanel = new JPanel(); + final var miscPanel = new JPanel(); settingsPanel.add(miscPanel); miscPanel.setLayout(new GridBagLayout()); - - final JCheckBox oneWay = new JCheckBox(); + + final var oneWay = new JCheckBox(); this.localizedTextSetters.put("tv.settings.oneway", oneWay::setText); oneWay.setSelected(this.presenter.oneWayConversionEnabled()); oneWay.addItemListener(e -> { @@ -651,9 +653,9 @@ final class TabbedView implements ExpressionConversionView, UnitConversionView { }); miscPanel.add(oneWay, new GridBagBuilder(0, 0, 2, 1) .setAnchor(GridBagConstraints.LINE_START).build()); - - final JCheckBox showAllVariations = new JCheckBox(); - this.localizedTextSetters.put("tv.settings.show_duplicate", + + final var showAllVariations = new JCheckBox(); + this.localizedTextSetters.put("tv.settings.show_duplicate", showAllVariations::setText); showAllVariations.setSelected(this.presenter.duplicatesShown()); showAllVariations.addItemListener(e -> { @@ -663,25 +665,25 @@ final class TabbedView implements ExpressionConversionView, UnitConversionView { }); miscPanel.add(showAllVariations, new GridBagBuilder(0, 1, 2, 1) .setAnchor(GridBagConstraints.LINE_START).build()); - - final JCheckBox useDefaultFiles = new JCheckBox(); - this.localizedTextSetters.put("tv.settings.use_default_files", + + final var useDefaultFiles = new JCheckBox(); + this.localizedTextSetters.put("tv.settings.use_default_files", useDefaultFiles::setText); useDefaultFiles.setSelected(this.presenter.usingDefaultDatafiles()); useDefaultFiles.addItemListener(e -> { - this.presenter - .setUseDefaultDatafiles(e.getStateChange() == ItemEvent.SELECTED); + this.presenter.setUseDefaultDatafiles( + e.getStateChange() == ItemEvent.SELECTED); this.presenter.saveSettings(); }); miscPanel.add(useDefaultFiles, new GridBagBuilder(0, 2, 2, 1) .setAnchor(GridBagConstraints.LINE_START).build()); - - final JLabel localeLabel = new JLabel(); - this.localizedTextSetters.put("tv.settings.locale", + + final var localeLabel = new JLabel(); + this.localizedTextSetters.put("tv.settings.locale", localeLabel::setText); miscPanel.add(localeLabel, new GridBagBuilder(0, 3, 1, 1) .setAnchor(GridBagConstraints.LINE_START).build()); - + this.presenter.getAvailableLocales().stream().sorted() .forEachOrdered(this.localeSelector::addItem); this.localeSelector.setSelectedItem(this.presenter.getUserLocale()); @@ -691,51 +693,51 @@ final class TabbedView implements ExpressionConversionView, UnitConversionView { }); miscPanel.add(localeSelector, new GridBagBuilder(1, 3, 1, 1) .setAnchor(GridBagConstraints.LINE_END).build()); - - final JButton unitFileButton = new JButton(); - this.localizedTextSetters.put("tv.settings.unitfiles.button", + + final var unitFileButton = new JButton(); + this.localizedTextSetters.put("tv.settings.unitfiles.button", unitFileButton::setText); unitFileButton.setEnabled(false); miscPanel.add(unitFileButton, new GridBagBuilder(0, 4, 2, 1) .setAnchor(GridBagConstraints.LINE_START).build()); } - + return settingsPanel; } - + @Override public Set<String> getDimensionNames() { return Collections .unmodifiableSet(new JComboBoxItemSet<>(this.dimensionSelector)); } - + @Override public String getFromExpression() { return this.fromEntry.getText(); } - + @Override public Optional<String> getFromSelection() { return this.fromSearch.getSelectedValue(); } - + @Override public Set<String> getFromUnitNames() { // this should work because the only way I can mutate the item list is // with setFromUnits which only accepts a Set return new HashSet<>(this.fromSearch.getItems()); } - + @Override public String getInputValue() { return this.valueInput.getText(); } - + @Override public Presenter getPresenter() { return this.presenter; } - + /** * @return the precision of the presenter's rounding rule, if that is * meaningful @@ -748,14 +750,13 @@ final class TabbedView implements ExpressionConversionView, UnitConversionView { return OptionalInt .of(((StandardDisplayRules.FixedDecimals) presenterRule) .decimalPlaces()); - else if (presenterRule instanceof StandardDisplayRules.FixedPrecision) + if (presenterRule instanceof StandardDisplayRules.FixedPrecision) return OptionalInt .of(((StandardDisplayRules.FixedPrecision) presenterRule) .significantFigures()); - else - return OptionalInt.empty(); + return OptionalInt.empty(); } - + /** * @return presenter's prefix repetition rule * @since 2022-04-19 @@ -767,7 +768,7 @@ final class TabbedView implements ExpressionConversionView, UnitConversionView { ? Optional.of((DefaultPrefixRepetitionRule) prefixRule) : Optional.empty(); } - + /** * Determines which rounding type the presenter is currently using, if any. * @@ -779,48 +780,47 @@ final class TabbedView implements ExpressionConversionView, UnitConversionView { if (Objects.equals(presenterRule, StandardDisplayRules.uncertaintyBased())) return Optional.of(StandardRoundingType.UNCERTAINTY); - else if (presenterRule instanceof StandardDisplayRules.FixedDecimals) + if (presenterRule instanceof StandardDisplayRules.FixedDecimals) return Optional.of(StandardRoundingType.DECIMAL_PLACES); - else if (presenterRule instanceof StandardDisplayRules.FixedPrecision) + if (presenterRule instanceof StandardDisplayRules.FixedPrecision) return Optional.of(StandardRoundingType.SIGNIFICANT_DIGITS); - else - return Optional.empty(); + return Optional.empty(); } - + @Override public Optional<String> getSelectedDimensionName() { - final String selectedItem = (String) this.dimensionSelector + final var selectedItem = (String) this.dimensionSelector .getSelectedItem(); return Optional.ofNullable(selectedItem); } - + @Override public String getToExpression() { return this.toEntry.getText(); } - + @Override public Optional<String> getToSelection() { return this.toSearch.getSelectedValue(); } - + @Override public Set<String> getToUnitNames() { // this should work because the only way I can mutate the item list is // with setToUnits which only accepts a Set return new HashSet<>(this.toSearch.getItems()); } - + @Override public Optional<String> getViewedPrefixName() { return this.prefixNameList.getSelectedValue(); } - + @Override public Optional<String> getViewedUnitName() { return this.unitNameList.getSelectedValue(); } - + @Override public void setDimensionNames(Set<String> dimensionNames) { this.dimensionSelector.removeAllItems(); @@ -828,44 +828,44 @@ final class TabbedView implements ExpressionConversionView, UnitConversionView { this.dimensionSelector.addItem(d); } } - + @Override public void setFromUnitNames(Set<String> units) { this.fromSearch.setItems(units); } - + @Override public void setToUnitNames(Set<String> units) { this.toSearch.setItems(units); } - + @Override public void setViewablePrefixNames(Set<String> prefixNames) { this.prefixNameList.setItems(prefixNames); } - + @Override public void setViewableUnitNames(Set<String> unitNames) { this.unitNameList.setItems(unitNames); } - + @Override public void showErrorMessage(String title, String message) { JOptionPane.showMessageDialog(this.frame, message, title, JOptionPane.ERROR_MESSAGE); } - + @Override public void showExpressionConversionOutput(UnitConversionRecord uc) { this.expressionOutput.setText(uc.toString()); } - + @Override public void showPrefix(NameSymbol name, String multiplierString) { this.prefixTextBox.setText( String.format("%s%nMultiplier: %s", name, multiplierString)); } - + @Override public void showUnit(NameSymbol name, String definition, String dimensionName, UnitType type) { @@ -873,16 +873,16 @@ final class TabbedView implements ExpressionConversionView, UnitConversionView { String.format("%s%nDefinition: %s%nDimension: %s%nType: %s", name, definition, dimensionName, type)); } - + @Override public void showUnitConversionOutput(UnitConversionRecord uc) { this.unitOutput.setText(uc.toString()); } - + /** * Sets the presenter's rounding rule to the one specified by the current * settings - * + * * @since 2022-04-18 * @since v0.4.0 */ @@ -910,7 +910,7 @@ final class TabbedView implements ExpressionConversionView, UnitConversionView { this.frame.setTitle(this.presenter.getLocalizedText("tv.title") .replace("[v]", ProgramInfo.VERSION.toString())); this.infoTextArea.setText(this.presenter.getAboutText()); - this.localizedTextSetters.forEach((id, action) -> - action.accept(this.presenter.getLocalizedText(id))); + this.localizedTextSetters.forEach( + (id, action) -> action.accept(this.presenter.getLocalizedText(id))); } } diff --git a/src/main/java/sevenUnitsGUI/UnitConversionRecord.java b/src/main/java/sevenUnitsGUI/UnitConversionRecord.java index 958deae..3c2bb6c 100644 --- a/src/main/java/sevenUnitsGUI/UnitConversionRecord.java +++ b/src/main/java/sevenUnitsGUI/UnitConversionRecord.java @@ -44,7 +44,7 @@ public final class UnitConversionRecord { input.getValue().toString(false, RoundingMode.HALF_EVEN), output.getValue().toString(false, RoundingMode.HALF_EVEN)); } - + /** * Gets a {@code UnitConversionRecord} from two unit values * @@ -60,7 +60,7 @@ public final class UnitConversionRecord { output.getUnit().getName(), String.valueOf(input.getValue()), String.valueOf(output.getValue())); } - + /** * Gets a {@code UnitConversionRecord} * @@ -78,16 +78,12 @@ public final class UnitConversionRecord { return new UnitConversionRecord(fromName, toName, inputValueString, outputValueString); } - - /** - * The name of the unit or expression that was converted from - */ + + /** The name of the unit or expression that was converted from */ private final String fromName; - /** - * The name of the unit or expression that was converted to - */ + /** The name of the unit or expression that was converted to */ private final String toName; - + /** * A string representing the input value. It doesn't need to be the same as * the input value's string representation; it could be rounded, for example. @@ -98,7 +94,7 @@ public final class UnitConversionRecord { * the input value's string representation; it could be rounded, for example. */ private final String outputValueString; - + /** * @param fromName name of unit or expression that was converted * from @@ -115,14 +111,14 @@ public final class UnitConversionRecord { this.inputValueString = inputValueString; this.outputValueString = outputValueString; } - + @Override public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof UnitConversionRecord)) return false; - final UnitConversionRecord other = (UnitConversionRecord) obj; + final var other = (UnitConversionRecord) obj; if (this.fromName == null) { if (other.fromName != null) return false; @@ -145,7 +141,7 @@ public final class UnitConversionRecord { return false; return true; } - + /** * @return name of unit or expression that was converted from * @since 2022-04-09 @@ -154,11 +150,11 @@ public final class UnitConversionRecord { public String fromName() { return this.fromName; } - + @Override public int hashCode() { - final int prime = 31; - int result = 1; + final var prime = 31; + var result = 1; result = prime * result + (this.fromName == null ? 0 : this.fromName.hashCode()); result = prime * result + (this.inputValueString == null ? 0 @@ -169,7 +165,7 @@ public final class UnitConversionRecord { + (this.toName == null ? 0 : this.toName.hashCode()); return result; } - + /** * @return string representing input value * @since 2022-04-09 @@ -178,7 +174,7 @@ public final class UnitConversionRecord { public String inputValueString() { return this.inputValueString; } - + /** * @return string representing output value * @since 2022-04-09 @@ -187,7 +183,7 @@ public final class UnitConversionRecord { public String outputValueString() { return this.outputValueString; } - + /** * @return name of unit or expression that was converted to * @since 2022-04-09 @@ -196,12 +192,12 @@ public final class UnitConversionRecord { public String toName() { return this.toName; } - + @Override public String toString() { - final String inputString = this.inputValueString.isBlank() ? this.fromName + final var inputString = this.inputValueString.isBlank() ? this.fromName : this.inputValueString + " " + this.fromName; - final String outputString = this.outputValueString.isBlank() ? this.toName + final var outputString = this.outputValueString.isBlank() ? this.toName : this.outputValueString + " " + this.toName; return inputString + " = " + outputString; } diff --git a/src/main/java/sevenUnitsGUI/UnitConversionView.java b/src/main/java/sevenUnitsGUI/UnitConversionView.java index c7ffda4..fa3a388 100644 --- a/src/main/java/sevenUnitsGUI/UnitConversionView.java +++ b/src/main/java/sevenUnitsGUI/UnitConversionView.java @@ -21,7 +21,7 @@ import java.util.Set; /** * A View that supports single unit-based conversion - * + * * @author Adrien Hopkins * @since 2021-12-15 * @since v0.4.0 @@ -110,7 +110,7 @@ public interface UnitConversionView extends View { /** * Shows the output of a unit conversion. - * + * * @param uc record of unit conversion * @since 2021-12-24 * @since v0.4.0 diff --git a/src/main/java/sevenUnitsGUI/View.java b/src/main/java/sevenUnitsGUI/View.java index fc04593..0adeb3a 100644 --- a/src/main/java/sevenUnitsGUI/View.java +++ b/src/main/java/sevenUnitsGUI/View.java @@ -24,7 +24,7 @@ import sevenUnits.utils.NameSymbol; /** * An object that controls user interaction with 7Units - * + * * @author Adrien Hopkins * @since 2021-12-15 * @since v0.4.0 @@ -112,10 +112,10 @@ public interface View { */ void showUnit(NameSymbol name, String definition, String dimensionName, UnitType type); - + /** * Updates the view's text to reflect the presenter's locale. - * + * * This method <b>must not</b> call {@link Presenter#setUserLocale(String)}. */ void updateText(); diff --git a/src/main/java/sevenUnitsGUI/ViewBot.java b/src/main/java/sevenUnitsGUI/ViewBot.java index 689b460..750e2d9 100644 --- a/src/main/java/sevenUnitsGUI/ViewBot.java +++ b/src/main/java/sevenUnitsGUI/ViewBot.java @@ -30,7 +30,7 @@ import sevenUnits.utils.Nameable; /** * A class that simulates a View (supports both unit and expression conversion) * for testing. Getters and setters work as expected. - * + * * @author Adrien Hopkins * @since 2022-01-29 * @since v0.4.0 @@ -66,7 +66,7 @@ public final class ViewBot return true; if (!(obj instanceof PrefixViewingRecord)) return false; - final PrefixViewingRecord other = (PrefixViewingRecord) obj; + final var other = (PrefixViewingRecord) obj; return Objects.equals(this.multiplierString, other.multiplierString) && Objects.equals(this.nameSymbol, other.nameSymbol); } @@ -93,7 +93,7 @@ public final class ViewBot @Override public String toString() { - final StringBuilder builder = new StringBuilder(); + final var builder = new StringBuilder(); builder.append("PrefixViewingRecord [nameSymbol="); builder.append(this.nameSymbol); builder.append(", multiplierString="); @@ -156,7 +156,7 @@ public final class ViewBot return true; if (!(obj instanceof UnitViewingRecord)) return false; - final UnitViewingRecord other = (UnitViewingRecord) obj; + final var other = (UnitViewingRecord) obj; return Objects.equals(this.definition, other.definition) && Objects.equals(this.dimensionName, other.dimensionName) && Objects.equals(this.nameSymbol, other.nameSymbol) @@ -186,7 +186,7 @@ public final class ViewBot @Override public String toString() { - final StringBuilder builder = new StringBuilder(); + final var builder = new StringBuilder(); builder.append("UnitViewingRecord [nameSymbol="); builder.append(this.nameSymbol); builder.append(", definition="); @@ -424,6 +424,7 @@ public final class ViewBot /** * Sets the view's selected dimension + * * @param selectedDimensionName name of dimension to select (string) */ public void setSelectedDimensionName(String selectedDimensionName) { @@ -453,9 +454,7 @@ public final class ViewBot "toSelection cannot be null."); } - /** - * @param toSelection unit set in the 'To' selection - */ + /** @param toSelection unit set in the 'To' selection */ public void setToSelection(String toSelection) { this.setToSelection(Optional.of(toSelection)); } @@ -475,9 +474,7 @@ public final class ViewBot // do nothing, ViewBot supports selecting any unit } - /** - * @param viewedPrefixName name of prefix being used - */ + /** @param viewedPrefixName name of prefix being used */ public void setViewedPrefixName(Optional<String> viewedPrefixName) { this.prefixViewerSelection = viewedPrefixName; } @@ -490,9 +487,7 @@ public final class ViewBot this.setViewedPrefixName(Optional.of(viewedPrefixName)); } - /** - * @param viewedUnitName name of unit being used - */ + /** @param viewedUnitName name of unit being used */ public void setViewedUnitName(Optional<String> viewedUnitName) { this.unitViewerSelection = viewedUnitName; } diff --git a/src/main/java/sevenUnitsGUI/package-info.java b/src/main/java/sevenUnitsGUI/package-info.java index 74ec18c..9432960 100644 --- a/src/main/java/sevenUnitsGUI/package-info.java +++ b/src/main/java/sevenUnitsGUI/package-info.java @@ -16,7 +16,7 @@ */ /** * The MVP GUI of SevenUnits - * + * * @author Adrien Hopkins * @since 2021-12-15 * @since v0.4.0 |