diff --git a/fx/README.md b/fx/README.md index f5597db..91e569e 100644 --- a/fx/README.md +++ b/fx/README.md @@ -185,6 +185,21 @@ A binding that names no such control fails with `No control "` and the id. A mis | `view` | Shows the attribute and follows later changes of the JavaFX property. Edits to the control stay on the control. | | `model` | Shows the current value, writes the attribute when the control changes, and leaves the control where it is when the attribute changes later. | +For `view`, a public `xxxProperty()` accessor on the ViewModel or its replacement can +return an `ObservableValue`, such as a `ReadOnlyStringProperty` or a `BooleanBinding`. +The value is read once at load and then followed as the observable changes. For a computed +value, declare its dependencies in JavaFX. The example connects the derived +`saveDisabledProperty()` to a button. + +```xml + +``` + +`both` and `model` require an accessor that exposes a writable `Property`. The error for +a read-only source gives the path, target control and property, and FXML resource. +`ViewModel.property(name)` and `LoadedView.property(name)` continue to look up writable +properties. + The desk puts all three on `name`. The name field is `both`. Shown name (`nameEcho`) is `view`: typing there leaves `Person.name` and the name field unchanged, and typing in the name field updates the echo. Name draft (`nameDraft`) is `model`: it opens as `Ada Lovelace`, stays there while the name field changes, and typing in the draft writes `Person.name` and updates the name field and the echo. Always specify `direction`: it has no default. A non-null value other than `view`, `model`, or `both` fails the load with `Not a direction:`. Omitting it can currently fail with a `NullPointerException` during binding application. The ObservableList shortcut described above bypasses direction handling; do not rely on that shortcut to omit the declaration. @@ -193,7 +208,7 @@ For a complex last segment the control receives the model instance behind the vi ## Paths -A path is attribute names separated by `.`. One name is an attribute of this view's view model, or `latestMessage`, or a `nameProperty()` on the view model. Earlier names must be complex attributes. The direction applies to the last name. +A path is attribute names separated by `.`. The last name resolves to an attribute, `latestMessage`, or a `nameProperty()` accessor. Earlier names must be complex attributes. The direction applies to the last name. `home.street` on the home street label steps through the home view model, and `view` applies to `street`. When a complex attribute along the path is null, that binding is left unapplied and both sides keep their current values. The load still succeeds. @@ -201,7 +216,7 @@ The path is resolved when the binding is applied. A binding whose last segment i A list is not indexed in a path. Repeat a component, place a table, or hand a list of simple values to a control. -A path that is not a read-write attribute fails the load with `No read-write attribute for path "` and the path. `Object.getClass` is not an attribute, and a getter without a setter is not one either. +An unresolved path fails the load with `No read-write attribute for path "` and the path. `Object.getClass` is not an attribute, and a getter without a setter is not one either. ## Converter @@ -541,7 +556,8 @@ These are the `IllegalArgumentException` messages a document can produce. The vi | `No control "` | `fx:id` is missing | | `No property ` | the control has no such JavaFX property | | `Not a direction:` | an explicitly supplied direction is not `view`, `model`, or `both`; an omitted direction can instead cause `NullPointerException` | -| `No read-write attribute for path "` | the path is not an attribute | +| `No read-write attribute for path "` | the path did not resolve to an attribute or a named observable | +| `Read-only source for path` | use `view` to read an observable source | | `Not a binding element:` | a child of `BindingList` is not a direct binding, a computed binding, or a repeat | | `No converter ` / `Not a converter:` | the converter class is missing or does not implement `Converter` | | `No controller for ` / `No computed method "` | a computed binding has no controller or no such method | diff --git a/fx/src/main/java/de/neitzel/fx/view/DirectBinding.java b/fx/src/main/java/de/neitzel/fx/view/DirectBinding.java index c8fc994..d1eff69 100644 --- a/fx/src/main/java/de/neitzel/fx/view/DirectBinding.java +++ b/fx/src/main/java/de/neitzel/fx/view/DirectBinding.java @@ -11,7 +11,9 @@ import lombok.Setter; * View's ViewModel. Further names step into the ViewModel of a Complex attribute, and the * direction applies to the last name. When that last name is complex, the control receives the * Model instance behind the ViewModel. Direction values are {@code view}, {@code model}, and - * {@code both}. The Converter value is the class name. The container creates that class. + * {@code both}. The last segment of a {@code view} binding may also name a public + * {@code xxxProperty()} accessor returning a read-only observable. The Converter value is the + * class name. The container creates that class. */ @Getter @Setter diff --git a/fx/src/main/java/de/neitzel/fx/view/DirectBindingApplier.java b/fx/src/main/java/de/neitzel/fx/view/DirectBindingApplier.java index 8662e85..0c04dfd 100644 --- a/fx/src/main/java/de/neitzel/fx/view/DirectBindingApplier.java +++ b/fx/src/main/java/de/neitzel/fx/view/DirectBindingApplier.java @@ -6,7 +6,9 @@ import java.lang.reflect.Method; import java.util.List; import java.util.Map; import javafx.beans.property.Property; +import javafx.beans.value.ObservableValue; import javafx.collections.ObservableList; +import javafx.fxml.FXMLLoader; import lombok.AccessLevel; import lombok.RequiredArgsConstructor; @@ -41,7 +43,11 @@ final class DirectBindingApplier { return; } Property controlProperty = controlProperty(control, binding.getProperty()); - Property attribute = resolved.attribute; + if (!resolved.writable) { + alignReadOnly(namespace, controlProperty, resolved, binding, context); + return; + } + Property attribute = (Property) resolved.attribute; if (resolved.complex) { switch (binding.getDirection()) { case "both" -> alignBothComplex(controlProperty, attribute); @@ -72,6 +78,23 @@ final class DirectBindingApplier { } } + /** Connects a named observable to the View when its accessor exposes no writable property. */ + private static void alignReadOnly(Map namespace, Property control, Resolved resolved, + DirectBinding binding, ApplicationContext context) { + if (!"view".equals(binding.getDirection())) { + throw new IllegalArgumentException("Read-only source for path \"" + binding.getPath() + + "\" requires direction=\"view\" on " + binding.getControl() + "." + binding.getProperty() + + " in " + namespace.get(FXMLLoader.LOCATION_KEY)); + } + String converterName = binding.getConverter(); + if (converterName == null || converterName.isEmpty()) { + alignTowardView(control, resolved.attribute); + } else { + alignConverted(control, resolved.attribute, converter(context, converterName), + resolved.owner, resolved.name, true, false); + } + } + /** * Aligns a plain Attribute in the named direction. * @@ -100,7 +123,10 @@ final class DirectBindingApplier { /** * The Attribute the Path names. */ - private final Property attribute; + private final ObservableValue attribute; + + /** Whether the Attribute resolves to a writable endpoint. */ + private final boolean writable; /** * Whether that Attribute is complex. @@ -153,13 +179,16 @@ final class DirectBindingApplier { current = child; } String last = names[names.length - 1]; - Property attribute = propertyOf(current, last); - if (attribute == null) { + Property property = propertyOf(current, last); + ViewModel owner = current instanceof ViewModel model ? model : null; + if (property != null) { + return new Resolved(property, true, owner != null && owner.isComplex(last), owner, last); + } + ObservableValue source = NamedProperties.getReadOnly(current, last); + if (source == null) { throw missing(path); } - boolean complex = current instanceof ViewModel stepped && stepped.isComplex(last); - ViewModel owner = current instanceof ViewModel model ? model : null; - return new Resolved(attribute, complex, owner, last); + return new Resolved(source, false, false, owner, last); } /** @@ -279,10 +308,9 @@ final class DirectBindingApplier { * which is the last name of the Path. */ @SuppressWarnings("unchecked") - private static void alignConverted(Property controlProperty, Property attribute, Converter converter, + private static void alignConverted(Property controlProperty, ObservableValue source, Converter converter, ViewModel owner, String sourceName, boolean towardView, boolean towardModel) { Property control = (Property) controlProperty; - Property source = (Property) attribute; Link link = new Link(); pushControl(control, source, converter, owner, sourceName, link); if (towardView) { @@ -293,9 +321,10 @@ final class DirectBindingApplier { }); } if (towardModel) { + Property target = (Property) source; control.addListener((observable, oldValue, newValue) -> { if (!link.applying) { - pushAttribute(control, source, converter, owner, sourceName, link); + pushAttribute(control, target, converter, owner, sourceName, link); } }); } @@ -311,7 +340,7 @@ final class DirectBindingApplier { * @param source the Attribute name used as the failure source * @param link the guard against hearing this write */ - private static void pushControl(Property control, Property attribute, Converter converter, + private static void pushControl(Property control, ObservableValue attribute, Converter converter, ViewModel owner, String source, Link link) { try { Object shown = converter.toControlValue(attribute.getValue()); @@ -321,8 +350,13 @@ final class DirectBindingApplier { } finally { link.applying = false; } - owner.clearBindingFailure(source); + if (owner != null) { + owner.clearBindingFailure(source); + } } catch (RuntimeException failure) { + if (owner == null) { + throw failure; + } owner.reportBindingFailure(source, failureText(failure)); } } @@ -505,11 +539,10 @@ final class DirectBindingApplier { * @param attribute the Attribute */ @SuppressWarnings("unchecked") - private static void alignTowardView(Property controlProperty, Property attribute) { + private static void alignTowardView(Property controlProperty, ObservableValue attribute) { Property control = (Property) controlProperty; - Property source = (Property) attribute; - control.setValue(source.getValue()); - source.addListener((observable, oldValue, newValue) -> control.setValue(newValue)); + control.setValue(attribute.getValue()); + attribute.addListener((observable, oldValue, newValue) -> control.setValue(newValue)); } /** diff --git a/fx/src/main/java/de/neitzel/fx/view/NamedProperties.java b/fx/src/main/java/de/neitzel/fx/view/NamedProperties.java index 5fd625a..04366a4 100644 --- a/fx/src/main/java/de/neitzel/fx/view/NamedProperties.java +++ b/fx/src/main/java/de/neitzel/fx/view/NamedProperties.java @@ -1,6 +1,7 @@ package de.neitzel.fx.view; import javafx.beans.property.Property; +import javafx.beans.value.ObservableValue; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -26,17 +27,31 @@ final class NamedProperties { * @return the property, or {@code null} when {@code bean} declares none of that name */ static Property get(Object bean, String name) { + Object value = read(bean, name, true); + return value instanceof Property property ? property : null; + } + + /** + * Returns a named observable whose accessor exposes a read-only source. + * + * @param bean the object that declares the source + * @param name the source name + * @return the source or {@code null} when there is no such accessor or it returns {@code null} + */ + static ObservableValue getReadOnly(Object bean, String name) { + Object value = read(bean, name, false); + return value instanceof ObservableValue source ? source : null; + } + + private static Object read(Object bean, String name, boolean writable) { String methodName = name + "Property"; try { Method method = bean.getClass().getMethod(methodName); - if (!Property.class.isAssignableFrom(method.getReturnType())) { + Class type = method.getReturnType(); + if (!ObservableValue.class.isAssignableFrom(type) || writable != Property.class.isAssignableFrom(type)) { return null; } - Object value = method.invoke(bean); - if (value instanceof Property property) { - return property; - } - return null; + return method.invoke(bean); } catch (NoSuchMethodException notDeclared) { return null; } catch (IllegalAccessException | InvocationTargetException failure) { diff --git a/fx/src/test/java/de/neitzel/fx/view/BindReadOnlySourcesTest.java b/fx/src/test/java/de/neitzel/fx/view/BindReadOnlySourcesTest.java new file mode 100644 index 0000000..45ae477 --- /dev/null +++ b/fx/src/test/java/de/neitzel/fx/view/BindReadOnlySourcesTest.java @@ -0,0 +1,92 @@ +package de.neitzel.fx.view; + +import de.neitzel.fx.view.fixture.Person; +import de.neitzel.fx.view.readable.ReadableSourcesController.Sources; +import de.neitzel.injection.ApplicationContext; +import javafx.scene.control.Button; +import javafx.scene.control.Label; +import javafx.scene.control.TextField; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** DirectBinding reads declared observables toward the view. */ +class BindReadOnlySourcesTest { + private static final URL DOCUMENT = BindReadOnlySourcesTest.class.getResource("readable-sources.fxml"); + + @BeforeAll + static void startJavaFx() throws InterruptedException { + FxThread.start(); + } + + @Test + void followsOnlyDependenciesOfTheViewModelSource() throws Exception { + FxThread.onFx(() -> { + LoadedView view = ViewLoader.load(DOCUMENT, new Person("Ada"), context()); + Sources sources = (Sources) view.getViewModel(); + Button commit = (Button) view.getRoot().lookup("#commit"); + Label title = (Label) view.getRoot().lookup("#title"); + Label caption = (Label) view.getRoot().lookup("#caption"); + TextField unrelated = (TextField) view.getRoot().lookup("#unrelated"); + + assertTrue(commit.isDisable()); + assertEquals("First", title.getText()); + assertEquals("Caption: First", caption.getText()); + assertNull(view.property("title")); + int evaluations = sources.getEvaluations(); + unrelated.setText("A change outside the binding's dependencies"); + assertEquals(evaluations, sources.getEvaluations()); + + sources.getChoices().add("A"); + assertFalse(commit.isDisable()); + sources.getChoices().clear(); + assertTrue(commit.isDisable()); + assertEquals(evaluations + 2, sources.getEvaluations()); + + title.setText("A local edit"); + assertEquals("First", sources.titleProperty().get()); + sources.setTitle(""); + assertEquals("", title.getText()); + assertEquals("Caption: First", caption.getText()); + assertEquals("observableTitle", sources.getLatestMessage().getSource()); + sources.setTitle("Second"); + assertEquals("Second", title.getText()); + assertEquals("Caption: Second", caption.getText()); + assertNull(sources.getLatestMessage()); + }); + } + + @ParameterizedTest + @ValueSource(strings = {"both", "model"}) + void identifiesAnInvalidWriteBackWithItsDocumentAndEndpoints(String direction, @TempDir Path temporary) + throws Exception { + Path invalid = temporary.resolve("invalid-" + direction + ".fxml"); + String fxml = Files.readString(Path.of(DOCUMENT.toURI())); + Files.writeString(invalid, fxml.replace("path=\"observableTitle\" direction=\"view\"", + "path=\"observableTitle\" direction=\"" + direction + "\"")); + FxThread.onFx(() -> { + IllegalArgumentException failure = assertThrows(IllegalArgumentException.class, + () -> ViewLoader.load(invalid.toUri().toURL(), new Person("Ada"), context())); + assertTrue(failure.getMessage().contains("Read-only source"), failure.getMessage()); + assertTrue(failure.getMessage().contains("observableTitle"), failure.getMessage()); + assertTrue(failure.getMessage().contains("caption.text"), failure.getMessage()); + assertTrue(failure.getMessage().contains(invalid.getFileName().toString()), failure.getMessage()); + }); + } + + private static ApplicationContext context() { + return new ApplicationContext("de.neitzel.fx.view.readable"); + } +} diff --git a/fx/src/test/java/de/neitzel/fx/view/readable/ReadableSourcesController.java b/fx/src/test/java/de/neitzel/fx/view/readable/ReadableSourcesController.java new file mode 100644 index 0000000..cf177d1 --- /dev/null +++ b/fx/src/test/java/de/neitzel/fx/view/readable/ReadableSourcesController.java @@ -0,0 +1,65 @@ +package de.neitzel.fx.view.readable; + +import de.neitzel.fx.view.Converter; +import de.neitzel.fx.view.ViewModel; +import de.neitzel.fx.view.ViewModelClass; +import jakarta.inject.Singleton; +import javafx.beans.binding.Bindings; +import javafx.beans.binding.BooleanBinding; +import javafx.beans.property.ReadOnlyStringProperty; +import javafx.beans.property.ReadOnlyStringWrapper; +import javafx.beans.value.ObservableValue; +import javafx.collections.FXCollections; +import javafx.collections.ObservableList; +import lombok.Getter; + +/** Controller and presentation state for the read-only DirectBinding fixture. */ +@Singleton +@ViewModelClass(ReadableSourcesController.Sources.class) +public class ReadableSourcesController { + + /** Sources include a JavaFX binding, a read-only property, and an observable-typed accessor. */ + public static class Sources extends ViewModel { + @Getter + private final ObservableList choices = FXCollections.observableArrayList(); + @Getter + private int evaluations; + private final BooleanBinding disabled = Bindings.createBooleanBinding(() -> { + evaluations++; + return choices.isEmpty(); + }, choices); + private final ReadOnlyStringWrapper title = new ReadOnlyStringWrapper("First"); + + public Sources(Object model) { + super(model); + } + + public BooleanBinding disabledProperty() { + return disabled; + } + + public ReadOnlyStringProperty titleProperty() { + return title.getReadOnlyProperty(); + } + + public ObservableValue observableTitleProperty() { + return title; + } + + public void setTitle(String value) { + title.set(value); + } + } + + /** A display-only converter, with an invalid title for testing Message reporting. */ + @Singleton + public static class Caption implements Converter { + @Override + public Object toControlValue(Object value) { + if ("".equals(value)) { + throw new IllegalArgumentException("Caption is required"); + } + return "Caption: " + value; + } + } +} diff --git a/fx/src/test/resources/de/neitzel/fx/view/readable-sources.fxml b/fx/src/test/resources/de/neitzel/fx/view/readable-sources.fxml new file mode 100644 index 0000000..1e09391 --- /dev/null +++ b/fx/src/test/resources/de/neitzel/fx/view/readable-sources.fxml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + +