Bind named read-only observables toward FXML views
This commit is contained in:
+19
-3
@@ -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
|
||||
<DirectBinding control="save" property="disable" path="saveDisabled" direction="view"/>
|
||||
```
|
||||
|
||||
`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
|
||||
|
||||
@@ -567,7 +582,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 |
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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, lifetime);
|
||||
return;
|
||||
}
|
||||
Property<?> attribute = (Property<?>) resolved.attribute;
|
||||
if (resolved.complex) {
|
||||
switch (binding.getDirection()) {
|
||||
case "both" -> alignBothComplex(controlProperty, attribute, lifetime);
|
||||
@@ -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<String, Object> namespace, Property<?> control, Resolved resolved,
|
||||
DirectBinding binding, ApplicationContext context, ViewLifetime lifetime) {
|
||||
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, lifetime);
|
||||
} else {
|
||||
alignConverted(control, resolved.attribute, converter(context, converterName),
|
||||
resolved.owner, resolved.name, true, false, lifetime);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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,10 @@ final class DirectBindingApplier {
|
||||
* which is the last name of the Path.
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
private static void alignConverted(Property<?> controlProperty, Property<?> attribute, Converter converter,
|
||||
ViewModel owner, String sourceName, boolean towardView, boolean towardModel, ViewLifetime lifetime) {
|
||||
private static void alignConverted(Property<?> controlProperty, ObservableValue<?> source, Converter converter,
|
||||
ViewModel owner, String sourceName, boolean towardView, boolean towardModel,
|
||||
ViewLifetime lifetime) {
|
||||
Property<Object> control = (Property<Object>) controlProperty;
|
||||
Property<Object> source = (Property<Object>) attribute;
|
||||
Link link = new Link();
|
||||
pushControl(control, source, converter, owner, sourceName, link);
|
||||
if (towardView) {
|
||||
@@ -293,9 +322,10 @@ final class DirectBindingApplier {
|
||||
});
|
||||
}
|
||||
if (towardModel) {
|
||||
Property<Object> target = (Property<Object>) source;
|
||||
lifetime.listen(control, (observable, oldValue, newValue) -> {
|
||||
if (!link.applying) {
|
||||
pushAttribute(control, source, converter, owner, sourceName, link);
|
||||
pushAttribute(control, target, converter, owner, sourceName, link);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -311,7 +341,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<Object> control, Property<Object> attribute, Converter converter,
|
||||
private static void pushControl(Property<Object> control, ObservableValue<?> attribute, Converter converter,
|
||||
ViewModel owner, String source, Link link) {
|
||||
try {
|
||||
Object shown = converter.toControlValue(attribute.getValue());
|
||||
@@ -321,8 +351,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));
|
||||
}
|
||||
}
|
||||
@@ -513,11 +548,11 @@ final class DirectBindingApplier {
|
||||
* @param attribute the Attribute
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
private static void alignTowardView(Property<?> controlProperty, Property<?> attribute, ViewLifetime lifetime) {
|
||||
private static void alignTowardView(Property<?> controlProperty, ObservableValue<?> attribute,
|
||||
ViewLifetime lifetime) {
|
||||
Property<Object> control = (Property<Object>) controlProperty;
|
||||
Property<Object> source = (Property<Object>) attribute;
|
||||
control.setValue(source.getValue());
|
||||
lifetime.listen(source, (observable, oldValue, newValue) -> control.setValue(newValue));
|
||||
control.setValue(attribute.getValue());
|
||||
lifetime.listen(attribute, (observable, oldValue, newValue) -> control.setValue(newValue));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -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<String> 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<String> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<?import de.neitzel.fx.view.BindingList?>
|
||||
<?import de.neitzel.fx.view.DirectBinding?>
|
||||
<?import javafx.scene.control.Button?>
|
||||
<?import javafx.scene.control.Label?>
|
||||
<?import javafx.scene.control.TextField?>
|
||||
<?import javafx.scene.layout.VBox?>
|
||||
|
||||
<VBox xmlns:fx="http://javafx.com/fxml/1"
|
||||
fx:controller="de.neitzel.fx.view.readable.ReadableSourcesController">
|
||||
<fx:define>
|
||||
<BindingList>
|
||||
<DirectBinding control="commit" property="disable" path="disabled" direction="view"/>
|
||||
<DirectBinding control="title" property="text" path="title" direction="view"/>
|
||||
<DirectBinding control="caption" property="text" path="observableTitle" direction="view"
|
||||
converter="de.neitzel.fx.view.readable.ReadableSourcesController$Caption"/>
|
||||
</BindingList>
|
||||
</fx:define>
|
||||
<Button fx:id="commit" text="Commit"/>
|
||||
<Label fx:id="title"/>
|
||||
<Label fx:id="caption"/>
|
||||
<TextField fx:id="unrelated"/>
|
||||
</VBox>
|
||||
Reference in New Issue
Block a user